public static PValue RunStatically(StackContext sctx, PValue[] args) { if(args.Length < 1) throw new PrexoniteException(Alias + "(...) requires at least one argument."); PValue rawVersion; if(args.Length == 1) { if(args[0].Type == PType.Object[typeof(MetaEntry)]) { var entry = (MetaEntry) args[0].Value; ModuleName moduleName; if (ModuleName.TryParse(entry, out moduleName)) return sctx.CreateNativePValue(sctx.Cache[moduleName]); else return PType.Null; } else { var raw = args[0].CallToString(sctx); ModuleName moduleName; if (ModuleName.TryParse(raw, out moduleName)) return sctx.CreateNativePValue(sctx.Cache[moduleName]); else return PType.Null; } } else if((rawVersion = args[1]).Type.Equals(PType.Object[typeof(Version)])) { var raw = args[0].CallToString(sctx); return sctx.CreateNativePValue(sctx.Cache[new ModuleName(raw, (Version) rawVersion.Value)]); } else { var raw = args[0].CallToString(sctx); Version version; if (Version.TryParse(rawVersion.CallToString(sctx), out version)) return sctx.CreateNativePValue(sctx.Cache[new ModuleName(raw, version)]); else return PType.Null; } }
public static PValue RunStatically(StackContext sctx, PValue[] args) { if (args.Length == 0) { return sctx.CreateNativePValue(NoSourcePosition.Instance); } string file = args[0].CallToString(sctx); int? line, column; PValue box; if (args.Length >= 2 && args[1].TryConvertTo(sctx, IntPType.Instance,true,out box)) { line = (int) box.Value; } else { line = null; } if (args.Length >= 3 && args[2].TryConvertTo(sctx, IntPType.Instance, true, out box)) { column = (int) box.Value; } else { column = null; } return sctx.CreateNativePValue(new SourcePosition(file, line ?? -1, column ?? -1)); }
public static PValue RunStatically(StackContext sctx, PValue[] args) { if (args == null) throw new ArgumentNullException("args"); if (sctx == null) throw new ArgumentNullException("sctx"); var xss = new List<IEnumerable<PValue>>(); foreach (var arg in args) { var xs = Map._ToEnumerable(sctx, arg); if (xs != null) xss.Add(xs); } var n = xss.Count; if (n < 2) throw new PrexoniteException("Except requires at least two sources."); var t = new Dictionary<PValue, bool>(); //All elements of the last source are considered candidates foreach (var x in xss[n - 1]) if (!t.ContainsKey(x)) t.Add(x, true); for (var i = 0; i < n - 1; i++) foreach (var x in xss[i]) if (t.ContainsKey(x)) t.Remove(x); return sctx.CreateNativePValue(t.Keys); }
public static PValue RunStatically(StackContext sctx, PValue[] args) { if (args.Length < 2) throw new PrexoniteException("then command requires two arguments."); return sctx.CreateNativePValue(new CallComposition(args[0], args[1])); }
// Bound statically by CIL compiler // ReSharper disable UnusedMember.Global public static PValue RunStatically(StackContext sctx, PValue[] args) // ReSharper restore UnusedMember.Global { var carrier = new ContextCarrier(); var corctx = new CoroutineContext(sctx, CoroutineRunStatically(carrier, args)); carrier.StackContext = corctx; return sctx.CreateNativePValue(new Coroutine(corctx)); }
/* function foo(a) [share c] * { * var b; * var d; * return ->d; * } */ public static void Test1(StackContext sctx, PValue[] args, PVariable[] sharedVariables, out PValue result) { var a = args[0]; var b = PType.Null.CreatePValue(); var c = sharedVariables[0]; var d = new PVariable(); d.Value = PType.Null; var argv = new[] {a, b}; a = new PValue(true, PType.Bool); b = sctx.CreateNativePValue(sctx.ParentApplication.Functions["funcid"]); a.DynamicCall(sctx, null, PCall.Get, "memid"); result = sctx.CreateNativePValue(d); }
// ReSharper disable MemberCanBePrivate.Global public static PValue RunStatically(StackContext sctx, PValue[] args) // ReSharper restore MemberCanBePrivate.Global { if (args.Length < 3) throw new PrexoniteException(Alias + " requires three arguments: " + Alias + "(fMoveNext, fCurrent, fDispose);"); return sctx.CreateNativePValue(new EnumeratorProxy(sctx, args[0], args[1], args[2])); }
public override PValue Run(StackContext sctx, PValue[] args) { if (args.Length < 1) return PType.Null; var closed = new PValue[args.Length - 1]; Array.Copy(args, 1, closed, 0, args.Length - 1); return sctx.CreateNativePValue(new FunctionalPartialCall(args[0], closed)); }
public static PValue RunStatically(StackContext sctx, PValue[] args) { if (args.Length == 0) return PType.Null; var arg = args[0]; if (arg == null) return PType.Null; return sctx.CreateNativePValue(arg); }
/// <summary> /// Executes the command. /// </summary> /// <param name = "sctx">The stack context in which to execut the command.</param> /// <param name = "args">The arguments to be passed to the command.</param> /// <returns>The value returned by the command. Must not be null. (But possibly {null~Null})</returns> public override PValue Run(StackContext sctx, PValue[] args) { if (sctx == null) throw new ArgumentNullException("sctx"); if (args == null) throw new ArgumentNullException("args"); var carrier = new ContextCarrier(); var corctx = new CoroutineContext(sctx, CoroutineRun(carrier, args)); carrier.StackContext = corctx; return sctx.CreateNativePValue(new Coroutine(corctx)); }
internal bool TryDynamicCall( StackContext sctx, PValue subject, PValue[] args, PCall call, string id, out PValue result, out MemberInfo resolvedMember, bool suppressIObject) { result = null; resolvedMember = null; if (id == null) id = ""; var iobj = subject.Value as IObject; if ((!suppressIObject) && iobj != null && iobj.TryDynamicCall(sctx, args, call, id, out result)) return true; //Special interop members switch (id.ToLowerInvariant()) { case @"\implements": foreach (var arg in args) { Type T; if (arg.Type is ObjectPType && typeof (Type).IsAssignableFrom(((ObjectPType) arg.Type).ClrType)) T = (Type) arg.Value; else T = GetType(sctx, arg.CallToString(sctx)); if (!T.IsAssignableFrom(ClrType)) { result = false; return true; } } result = true; return true; case @"\boxed": result = sctx.CreateNativePValue(subject); return true; } var cond = new call_conditions(sctx, args, call, id); MemberTypes mtypes; MemberFilter filter; if (id.Length != 0) { filter = _member_filter; if (id.LastIndexOf('\\') == 0) return false; //Default index accessors do not accept calling directives mtypes = MemberTypes.Event | MemberTypes.Field | MemberTypes.Method | MemberTypes.Property; } else { filter = _default_member_filter; mtypes = MemberTypes.Property | MemberTypes.Method; cond.memberRestriction = new List<MemberInfo>(_clrType.GetDefaultMembers()); cond.IgnoreId = true; if (subject.Value is Array) { cond.memberRestriction.AddRange( _clrType.FindMembers( MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance, Type.FilterName, cond.Call == PCall.Get ? "GetValue" : "SetValue")); cond.memberRestriction.AddRange( _clrType.FindMembers( MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance, Type.FilterName, cond.Call == PCall.Get ? "Get" : "Set")); } } //Get public member candidates, a stack is used so that newly discovered members // can be examined with priority var candidates = new Stack<MemberInfo>( _clrType.FindMembers( mtypes, //Member types BindingFlags.Instance | BindingFlags.Public, //Search domain filter, cond)); //Filter if (candidates.Count == 1) resolvedMember = candidates.Peek(); var ret = _try_execute(candidates, cond, subject, out result); if (!ret) //Call did not succeed -> member invalid resolvedMember = null; return ret; }
public override PValue Run(StackContext sctx, PValue[] args) { if (args.Length < CallingConventionArgumentsCount) throw new PrexoniteException( "Id of macro implementation, effect flag, call type and/or context missing."); var entityRef = _getMacroRef(sctx, args[0]); //Parse arguments var context = _getContext(args[1]); var call = _getCallType(args[2]); var justEffect = _getEffectFlag(args[3]); // Prepare macro var target = _loader.FunctionTargets[context.Function]; var argList = Call.FlattenArguments(sctx, args, CallingConventionArgumentsCount); _detectRuntimeValues(argList); var inv = new AstExpand(context.Invocation.Position, entityRef, call); inv.Arguments.AddRange(argList.Select(p => (AstExpr) p.Value)); //Execute the macro MacroSession macroSession = null; try { macroSession = target.AcquireMacroSession(); return sctx.CreateNativePValue( macroSession.ExpandMacro(inv, justEffect)); } finally { if (macroSession != null) target.ReleaseMacroSession(macroSession); } }
protected override PValue Invoke(StackContext sctx, PValue[] nonArguments, PValue[] arguments) { var end = _wrappingDirectives.Offset + _wrappingDirectives.Count; var effectiveArguments = new PValue[_getEffectiveArgc(arguments.Length)]; var effIdx = 0; var argIdx = 0; for (var i = _wrappingDirectives.Offset; i < end; i++) { var directive = _wrappingDirectives.Array[i]; System.Diagnostics.Debug.Assert(directive != 0); if (directive > 0) { Array.Copy(arguments, argIdx, effectiveArguments, effIdx, directive); argIdx += directive; effIdx += directive; } else { directive = -directive; var list = new List<PValue>(directive); for (var j = 0; j < directive; j++) list.Add(arguments[argIdx++]); effectiveArguments[effIdx++] = sctx.CreateNativePValue(list); } } System.Diagnostics.Debug.Assert(effectiveArguments.Length - effIdx == arguments.Length - argIdx); Array.Copy(arguments, argIdx, effectiveArguments, effIdx, effectiveArguments.Length - effIdx); return nonArguments[0].IndirectCall(sctx, effectiveArguments); }
public static PValue RunStatically(StackContext sctx, PValue[] args) { if (sctx == null) throw new ArgumentNullException("sctx"); if (args == null) throw new ArgumentNullException("args"); PValue head; var nextArg = ((IEnumerable<PValue>) args).GetEnumerator(); IEnumerator<PValue> nextX; try { if (!nextArg.MoveNext()) throw new PrexoniteException("headtail requires at least one argument."); var arg = nextArg.Current; var xs = Map._ToEnumerable(sctx, arg); nextX = xs.GetEnumerator(); try { if (!nextX.MoveNext()) return PType.Null; head = nextX.Current; } catch (Exception) { nextX.Dispose(); throw; } } catch (Exception) { nextArg.Dispose(); throw; } return (PValue) new List<PValue> { head, sctx.CreateNativePValue( new Coroutine(new CoroutineContext(sctx, _tail(sctx, nextX, nextArg)))) }; }
/// <summary> /// Provides macro environment to its implementing function. The resulting closure /// implements the expansion of the macro. /// </summary> /// <param name = "sctx">The stack context to use for wrapping the context.</param> /// <param name = "func">The implementation of the macro.</param> /// <param name = "context">The macro context for this expansion.</param> /// <returns>A closure that implements the expansion of this macro.</returns> public static Closure PrepareMacroImplementation(StackContext sctx, PFunction func, MacroContext context) { var contextVar = CompilerTarget.CreateReadonlyVariable(sctx.CreateNativePValue(context)); var env = new SymbolTable<PVariable>(1) {{MacroAliases.ContextAlias, contextVar}}; var sharedVariables = func.Meta[PFunction.SharedNamesKey].List.Select(entry => env[entry.Text]). ToArray(); return new Closure(func, sharedVariables); }
private static IEnumerable<PValue> _wrapDynamicIEnumerable(StackContext sctx, PValue psource) { var pvEnumerator = psource.DynamicCall(sctx, Runtime.EmptyPValueArray, PCall.Get, "GetEnumerator"). ConvertTo(sctx, typeof (IEnumerator)); var enumerator = (IEnumerator) pvEnumerator.Value; PValueEnumerator pvEnum; try { if ((pvEnum = enumerator as PValueEnumerator) != null) { while (pvEnum.MoveNext()) yield return pvEnum.Current; } else { while (enumerator.MoveNext()) yield return sctx.CreateNativePValue(enumerator.Current); } } finally { var disposable = enumerator as IDisposable; if (disposable != null) disposable.Dispose(); } }
public static PValue RunStatically(StackContext sctx, PValue[] args) { var carrier = new ContextCarrier(); var corctx = new CoroutineContext(sctx, CoroutineRunStatically(carrier, args)); carrier.StackContext = corctx; return sctx.CreateNativePValue(new Coroutine(corctx)); }
public override bool IndirectCall( StackContext sctx, PValue subject, PValue[] args, out PValue result) { if (sctx == null) throw new ArgumentNullException("sctx"); if (subject == null) throw new ArgumentNullException("subject"); if (args == null) args = new PValue[] {}; result = null; var argc = args.Length; var pvht = (PValueHashtable) subject.Value; if (argc == 0) { result = sctx.CreateNativePValue(new PValueEnumeratorWrapper(pvht.GetPValueEnumerator())); } else if (argc == 1) { if (!pvht.TryGetValue(args[0], out result)) result = false; } else { pvht.AddOverride(args[0], args[1]); } return result != null; }
/// <summary> /// Returns the caller of the supplied stack context. /// </summary> /// <param name = "sctx">The stack contetx that wishes to find out, who called him.</param> /// <param name = "args">Ignored</param> /// <returns>Either the stack context of the caller or null encapsulated in a PValue.</returns> public override PValue Run(StackContext sctx, PValue[] args) { return sctx.CreateNativePValue(GetCaller(sctx)); }
public static PValue RunStatically(StackContext sctx, PValue[] args) { if (sctx == null) throw new ArgumentNullException("sctx"); if (args == null || args.Length == 0 || args[0] == null) return PType.Null.CreatePValue(); var iargs = Call.FlattenArguments(sctx, args, 1); var retChan = new Channel(); var T = new Thread(() => { PValue result; try { result = args[0].IndirectCall(sctx, iargs.ToArray()); } catch (Exception ex) { result = sctx.CreateNativePValue(ex); } retChan.Send(result); }) { IsBackground = true }; T.Start(); return PType.Object.CreatePValue(retChan); }
public static PValue GetCallerFromCilFunction(StackContext sctx) { var stack = sctx.ParentEngine.Stack; if (stack.Count == 0) return PType.Null; else return sctx.CreateNativePValue(stack.Last.Value); }
public static PValue RunStatically(StackContext sctx, PValue fpv, PValue[] iargs, bool useIndirectCallAsFallback) { IStackAware f; IMaybeStackAware m; CilClosure cilClosure; PFunction func = null; PVariable[] sharedVars = null; PValue result; ReturnMode returnMode; if ((cilClosure = fpv.Value as CilClosure) != null) { func = cilClosure.Function; sharedVars = cilClosure.SharedVariables; } if ((func = func ?? fpv.Value as PFunction) != null && func.HasCilImplementation) { func.CilImplementation.Invoke( func, CilFunctionContext.New(sctx, func), iargs, sharedVars ?? new PVariable[0], out result, out returnMode); } else if ((f = fpv.Value as IStackAware) != null) { //Create stack context, let the engine execute it var subCtx = f.CreateStackContext(sctx, iargs); sctx.ParentEngine.Process(subCtx); result = subCtx.ReturnValue; returnMode = subCtx.ReturnMode; } else if ((m = fpv.Value as IMaybeStackAware) != null) { StackContext subCtx; if (m.TryDefer(sctx, iargs, out subCtx, out result)) { sctx.ParentEngine.Process(subCtx); result = subCtx.ReturnValue; returnMode = subCtx.ReturnMode; } else if (useIndirectCallAsFallback) { returnMode = ReturnMode.Exit; } else { throw new PrexoniteException( string.Format( "Invocation of {0} did not produce a valid return mode. " + "Only Prexonite functions have a return mode.", fpv.CallToString(sctx))); } } else if (useIndirectCallAsFallback) { result = fpv.IndirectCall(sctx, iargs); returnMode = ReturnMode.Exit; } else { throw new PrexoniteException( "call\\sub\\perform requires its argument to be stack aware."); } return new PValueKeyValuePair(sctx.CreateNativePValue(returnMode), result); }
public override bool TryDynamicCall( StackContext sctx, PValue subject, PValue[] args, PCall call, string id, out PValue result) { if (sctx == null) throw new ArgumentNullException("sctx"); if (subject == null) throw new ArgumentNullException("subject"); if (args == null) throw new ArgumentNullException("args"); if (id == null) id = ""; var c = (char) subject.Value; CultureInfo ci; switch (id.ToLowerInvariant()) { case "getnumericvalue": result = System.Char.GetNumericValue(c); break; case "getunicodecategory": result = sctx.CreateNativePValue(System.Char.GetUnicodeCategory(c)); break; case "iscontrol": result = System.Char.IsControl(c); break; case "isdigit": result = System.Char.IsDigit(c); break; case "ishighsurrogate": result = System.Char.IsHighSurrogate(c); break; case "isletter": result = System.Char.IsLetter(c); break; case "isletterordigit": result = System.Char.IsLetterOrDigit(c); break; case "islower": result = System.Char.IsLower(c); break; case "islowsurrogate": result = System.Char.IsLowSurrogate(c); break; case "isnumber": result = System.Char.IsNumber(c); break; case "ispunctuation": result = System.Char.IsPunctuation(c); break; case "issurrogate": result = System.Char.IsSurrogate(c); break; case "issymbol": result = System.Char.IsSymbol(c); break; case "isupper": result = System.Char.IsUpper(c); break; case "iswhitespace": result = System.Char.IsWhiteSpace(c); break; case "tolower": if (args.Length > 0 && args[0].TryConvertTo(sctx, false, out ci)) result = System.Char.ToLower(c, ci); else result = System.Char.ToLower(c); break; case "toupper": if (args.Length > 0 && args[0].TryConvertTo(sctx, false, out ci)) result = System.Char.ToUpper(c, ci); else result = System.Char.ToUpper(c); break; case "tolowerinvariant": result = System.Char.ToLowerInvariant(c); break; case "toupperinvariant": result = System.Char.ToUpperInvariant(c); break; case "length": result = 1; break; default: //Try CLR dynamic call var clrint = Object[subject.ClrType]; if (!clrint.TryDynamicCall(sctx, subject, args, call, id, out result)) result = null; break; } return result != null; }
public static PValue RunStatically(StackContext sctx, PValue[] args) { return sctx.CreateNativePValue(_unscopedFactories.GetOrAdd(sctx.ParentApplication.Module.Name, n => new UnscopedFactory(n))); }
public override PValue Run(StackContext sctx, PValue[] args) { if (args.Length < 3) throw new PrexoniteException(string.Format( "{0} requires at least 3 arguments.", Alias)); var id = args[0].CallToString(sctx); var interpretation = (SymbolInterpretations) args[1].Value; var module = args[2].Value as ModuleName; if (module == null) { var moduleRaw = args[2].Value as string; if (moduleRaw != null) { if (!ModuleName.TryParse(moduleRaw, out module)) throw new PrexoniteException("Invalid module name \"" + moduleRaw + "\"."); } } switch (interpretation) { case SymbolInterpretations.Function: PFunction func; if(module == null) { throw new PrexoniteException(string.Format("Cannot create reference to function {0}. Module name is missing.", id)); } else if(sctx.ParentApplication.TryGetFunction(id,module, out func)) { return sctx.CreateNativePValue(func); } else { throw new PrexoniteException( string.Format("Cannot create reference to function {0} from module {1}. Function or module is missing from context.", id, module)); } case SymbolInterpretations.MacroCommand: return sctx.CreateNativePValue(_loader.MacroCommands[id]); default: throw new PrexoniteException( string.Format("Unknown macro interpretation {0} in {1}.", Enum.GetName(typeof (SymbolInterpretations), interpretation), Alias)); } }
public static PValue CreateConstFunction(PValue constant, StackContext sctx) { return sctx.CreateNativePValue(new Impl(constant)); }
protected override bool InternalConvertTo( StackContext sctx, PValue subject, PType target, bool useExplicit, out PValue result) { if (sctx == null) throw new ArgumentNullException("sctx"); if (subject == null) throw new ArgumentNullException("subject"); if ((object) target == null) throw new ArgumentNullException("target"); var pvht = subject.Value as PValueHashtable; if (pvht == null) throw new ArgumentException("Subject must be a Hash."); result = null; if (target is ObjectPType) { var tT = ((ObjectPType) target).ClrType; if (tT == typeof (IDictionary<PValue, PValue>) || tT == typeof (Dictionary<PValue, PValue>) || tT == typeof (IDictionary) || tT == typeof (IEnumerable<KeyValuePair<PValue, PValue>>) || tT == typeof (IEnumerable) || tT == typeof (ICollection<KeyValuePair<PValue, PValue>>) || tT == typeof (ICollection)) { result = new PValue(pvht, target); } else if (tT == typeof (IEnumerable<PValue>) || tT == typeof (IList<PValue>) || tT == typeof (IList)) { var lst = new List<PValue>(pvht.Count); foreach (var pair in pvht) lst.Add(sctx.CreateNativePValue(new PValueKeyValuePair(pair))); result = new PValue(lst, target); } } else if (target is ListPType) { var lst = new List<PValue>(pvht.Count); foreach (var pair in pvht) lst.Add(sctx.CreateNativePValue(new PValueKeyValuePair(pair.Key, pair.Value))); result = List.CreatePValue(lst); } return result != null; }
public override bool TryDynamicCall( StackContext sctx, PValue subject, PValue[] args, PCall call, string id, out PValue result) { result = null; if (Engine.StringsAreEqual(id, "tostring")) result = String.CreatePValue(""); else if (Engine.StringsAreEqual(id, @"\boxed")) result = sctx.CreateNativePValue(CreatePValue()); return result != null; }
public override bool TryDynamicCall( StackContext sctx, PValue subject, PValue[] args, PCall call, string id, out PValue result) { if (sctx == null) throw new ArgumentNullException("sctx"); result = null; switch (id.ToUpperInvariant()) { case "TO": if (args.Length < 1) break; var upperLimitPV = args[0].ConvertTo(sctx, Int, true); var stepPV = args.Length > 1 ? args[1].ConvertTo(sctx, Int, true) : 1; var lowerLimit = (int) subject.Value; var upperLimit = (int) upperLimitPV.Value; var step = (int) stepPV.Value; result = sctx.CreateNativePValue (new Coroutine(new CoroutineContext(sctx, _generateIntegerRange(lowerLimit, step, upperLimit)))); break; } if (result != null) return true; //Try CLR dynamic call var clrint = Object[subject.ClrType]; return clrint.TryDynamicCall(sctx, subject, args, call, id, out result); }
private static IEnumerable<PValue> _wrapNonGenericIEnumerable(StackContext sctx, IEnumerable nonGeneric) { foreach (var obj in nonGeneric) yield return sctx.CreateNativePValue(obj); }