Inheritance: ScriptFunction, System.Reflection.IReflect, System.Collections.IEnumerable, System.Runtime.InteropServices.Expando.IExpando
 public void Generate()
 {
     indensionStack.Clear();
     indensionStack.Push(-1);
     if (app == null) app = new Application();
     thisPresentation = app.Presentations.Add(MsoTriState.msoFalse);
     var cl = new DocumentClosure(null, thisPresentation, app);
     CurrentClosure = cl;
     ChangeTheme();
     cl.Initialize();
     cl.WorkPath = DefaultWorkPath;
     var module = thisPresentation.VBProject.VBComponents.Add(vbext_ComponentType.vbext_ct_StdModule);
     module.CodeModule.AddFromString(Resources.VBAModule);
     while (true)
     {
         var thisLine = ScriptReader.ReadLine();
         if (thisLine == null) break;
         Console.WriteLine(thisLine);
         if (!string.IsNullOrWhiteSpace(thisLine) && thisLine.TrimStart()[0] != '#')
             ParseLine(thisLine);
     }
     while (CurrentClosure != null) ExitClosure();
     app.Run("PAG_PostProcess", thisPresentation);
     var wnd = thisPresentation.NewWindow();
     thisPresentation.VBProject.VBComponents.Remove(module);
     wnd.Activate();
     //thisPresentation.Close();
 }
示例#2
0
		static public Handle Add (uint t, GLib.TimeoutHandler timeout_handler)
		{
			Closure c;
			c = new Closure (timeout_handler);
			c.Id = GLib.Timeout.Add (t, new GLib.TimeoutHandler (c.Handler));
			return c;
		}
 /**
  * Constructor that performs no validation.
  * Use <code>getInstance</code> if you want that.
  *
  * @param predicates  array of predicates, not cloned, no nulls
  * @param closures  matching array of closures, not cloned, no nulls
  * @param defaultClosure  the closure to use if no match, null means nop
  */
 public SwitchClosure(Predicate[] predicates, Closure[] closures, Closure defaultClosure)
     : base()
 {
     iPredicates = predicates;
     iClosures = closures;
     iDefault = (defaultClosure == null ? NOPClosure.INSTANCE : defaultClosure);
 }
示例#4
0
文件: lfunc.cs 项目: raymanyu/kopilua
 // we have a gc, so nothing to do
 public static void luaF_freeclosure(lua_State L, Closure c)
 {
     int size = (c.c.isC != 0) ? sizeCclosure(c.c.nupvalues) :
                           sizeLclosure(c.l.nupvalues);
       //luaM_freemem(L, c, size);
       SubtractTotalBytes(L, size);
 }
示例#5
0
 // we have a gc, so nothing to do
 public static void LuaFFreeClosure(LuaState L, Closure c)
 {
     int size = (c.c.isC != 0) ? SizeCclosure(c.c.nupvalues) :
                             SizeLclosure(c.l.nupvalues);
     //luaM_freemem(L, c, size);
     SubtractTotalBytes(L, size);
 }
示例#6
0
		// RENAMEME: It is linguistically awkward that we pass in
		// "handlers", and get back "handles".
		static public Handle Add (GLib.IdleHandler idle_handler)
		{
			Closure c;
			c = new Closure (idle_handler);
			c.Id = GLib.Idle.Add (new GLib.IdleHandler (c.Handler));
			return c;
		}
 /**
  * Constructor that performs no validation.
  * Use <code>getInstance</code> if you want that.
  *
  * @param predicate  the predicate used to evaluate when the loop terminates, not null
  * @param closure  the closure the execute, not null
  * @param doLoop  true to act as a do-while loop, always executing the closure once
  */
 public WhileClosure(Predicate predicate, Closure closure, bool doLoop)
     : base()
 {
     iPredicate = predicate;
     iClosure = closure;
     iDoLoop = doLoop;
 }
示例#8
0
 public StronglyTypedAstBuilder(Closure externalClosure)
 {
     foreach (var pair in externalClosure)
     {
         _closure.Add(pair.Key, pair.Value);
     }
 }
 /**
  * Constructor that performs no validation.
  * Use <code>getInstance</code> if you want that.
  *
  * @param predicate  predicate to switch on, not null
  * @param trueClosure  closure used if true, not null
  * @param falseClosure  closure used if false, not null
  */
 public IfClosure(Predicate predicate, Closure trueClosure, Closure falseClosure)
     : base()
 {
     iPredicate = predicate;
     iTrueClosure = trueClosure;
     iFalseClosure = falseClosure;
 }
        public void ShouldBeAbleToNestClosures()
        {
            MathOperation add = delegate(int a, int b) { return a + b; };
            Closure doMath = new Closure(add, new Closure(add, new Closure(add, 1, 1), 1), 1);

            int result = (int) doMath.Invoke();
            Assert.IsTrue(result == 4);
        }
 protected IEnumerator CallLuaClosure(LuaEnvironment luaEnv, Closure callback)
 {
     yield return new WaitForEndOfFrame();
     if (callback != null)
     {
         luaEnv.RunLuaFunction(callback, true);
     }
 }
 /**
  * Clone the closures to ensure that the internal reference can't be messed with.
  *
  * @param closures  the closures to copy
  * @return the cloned closures
  */
 internal static Closure[] copy(Closure[] closures)
 {
     if (closures == null)
     {
         return null;
     }
     return (Closure[])closures.clone();
 }
 /**
  * Factory method that performs validation.
  *
  * @param closure  the closure to call, not null
  * @return the <code>closure</code> transformer
  * @throws IllegalArgumentException if the closure is null
  */
 public static Transformer getInstance(Closure closure)
 {
     if (closure == null)
     {
         throw new java.lang.IllegalArgumentException("Closure must not be null");
     }
     return new ClosureTransformer(closure);
 }
 /**
  * Factory method that performs validation and copies the parameter array.
  *
  * @param closures  the closures to chain, copied, no nulls
  * @return the <code>chained</code> closure
  * @throws IllegalArgumentException if the closures array is null
  * @throws IllegalArgumentException if any closure in the array is null
  */
 public static Closure getInstance(Closure[] closures)
 {
     FunctorUtils.validate(closures);
     if (closures.Length == 0)
     {
         return NOPClosure.INSTANCE;
     }
     closures = FunctorUtils.copy(closures);
     return new ChainedClosure(closures);
 }
        public void CurriedClosureShouldBeAbleToBindToAStronglyTypedDelegate()
        {
            MathOperation add = delegate(int a, int b) { return a + b; };
            Closure doMath = new Closure(add, Args.Lambda, 1);
            SingleOperatorMathOperation mathOp = doMath.AdaptTo<SingleOperatorMathOperation>();

            // return 5 + 1
            int result = mathOp(5);
            // The result should be 6
            Assert.AreEqual(6, result);
        }
示例#16
0
		public DynValue Coroutine_Create(Closure closure)
		{
			// create a processor instance
			Processor P = new Processor(this);

			// Put the closure as first value on the stack, for future reference
			P.m_ValueStack.Push(DynValue.NewClosure(closure));

			// Return the coroutine handle
			return DynValue.NewCoroutine(new Coroutine(P));
		}
 /**
  * Factory method that performs validation.
  *
  * @param predicate  the predicate used to evaluate when the loop terminates, not null
  * @param closure  the closure the execute, not null
  * @param doLoop  true to act as a do-while loop, always executing the closure once
  * @return the <code>while</code> closure
  * @throws IllegalArgumentException if the predicate or closure is null
  */
 public static Closure getInstance(Predicate predicate, Closure closure, bool doLoop)
 {
     if (predicate == null)
     {
         throw new java.lang.IllegalArgumentException("Predicate must not be null");
     }
     if (closure == null)
     {
         throw new java.lang.IllegalArgumentException("Closure must not be null");
     }
     return new WhileClosure(predicate, closure, doLoop);
 }
 /**
  * Factory method that performs validation.
  * <p>
  * A null closure or zero count returns the <code>NOPClosure</code>.
  * A count of one returns the specified closure.
  *
  * @param count  the number of times to execute the closure
  * @param closure  the closure to execute, not null
  * @return the <code>for</code> closure
  */
 public static Closure getInstance(int count, Closure closure)
 {
     if (count <= 0 || closure == null)
     {
         return NOPClosure.INSTANCE;
     }
     if (count == 1)
     {
         return closure;
     }
     return new ForClosure(count, closure);
 }
示例#19
0
        public MethodResolution(MethodInfo methodInfo, Closure closure, InvokeExpression callAst)
        {
            MethodInfo = methodInfo;
            Closure = closure;
            CallAst = callAst;
            Result = null;

            PassesComplete = null;
            Target = new StronglyTypedAstBuilder(closure).Visit(callAst.Target);
            FormalArgs = new List<Type>(MethodInfo.GetParameters().Select(p => p.ParameterType));
            RealArgs = new List<Expression>(callAst.Args.Select(ast => ast is LambdaExpression ?
                new StronglyTypedAstBuilder(closure).VisitLambda((LambdaExpression)ast, null, true) :
                new StronglyTypedAstBuilder(closure).Visit(ast)));
            InferenceCache = new Dictionary<Type, Type>();
            Array.ForEach(MethodInfo.GetGenericArguments(), t => InferenceCache.Add(t, null));
        }
示例#20
0
        /// <summary>
        /// Initialises the Lua environment and compiles the Lua string for execution later on.
        /// </summary>
        protected virtual void InitExecuteLua()
        {
            if (initialised)
            {
                return;
            }

            // Cache a descriptive name to use in Lua error messages
            friendlyName = gameObject.name + "." + parentBlock.blockName + "." + "ExecuteLua #" + commandIndex.ToString();

            Flowchart flowchart = GetFlowchart();

            // See if a Lua Environment has been assigned to this Flowchart
            if (luaEnvironment == null)        
            {
                luaEnvironment = flowchart.luaEnvironment;
            }

            // No Lua Environment specified so just use any available or create one.
            if (luaEnvironment == null)        
            {
                luaEnvironment = LuaEnvironment.GetLua();
            }

            string s = GetLuaString();
            luaFunction = luaEnvironment.LoadLuaString(s, friendlyName);

            // Add a binding to the parent flowchart
            if (flowchart.luaBindingName != "")
            {
                Table globals = luaEnvironment.Interpreter.Globals;
                if (globals != null)
                {
                    globals[flowchart.luaBindingName] = flowchart;
                }
            }

            // Always initialise when playing in the editor.
            // Allows the user to edit the Lua script while the game is playing.
            if ( !(Application.isPlaying && Application.isEditor) )
            {
                initialised = true;
            }

        }
示例#21
0
        /// <summary>
        /// Extension for MenuDialog that allows AddOption to call a Lua function when an option is selected.
        /// </summary>
        public static bool AddOption(this MenuDialog menuDialog, string text, bool interactable, LuaEnvironment luaEnvironment, Closure callBack)
        {
            if (!menuDialog.gameObject.activeSelf)
            {
                menuDialog.gameObject.SetActive(true);
            }

            bool addedOption = false;
            foreach (Button button in menuDialog.cachedButtons)
            {
                if (!button.gameObject.activeSelf)
                {
                    button.gameObject.SetActive(true);

                    button.interactable = interactable;

                    Text textComponent = button.GetComponentInChildren<Text>();
                    if (textComponent != null)
                    {
                        textComponent.text = text;
                    }

                    button.onClick.AddListener(delegate {

                        menuDialog.StopAllCoroutines(); // Stop timeout
                        menuDialog.Clear();
                        menuDialog.HideSayDialog();

                        if (callBack != null)
                        {
                            luaEnvironment.RunLuaFunction(callBack, true);
                        }
                    });

                    addedOption = true;
                    break;
                }
            }

            return addedOption;
        }
        public void ShouldBeAbleToCurryArguments()
        {
            object source = new object();
            EventArgs args = new EventArgs();

            ITestCounter counter = mock.NewMock<ITestCounter>();
            Expect.Once.On(counter).Method("Increment").WithAnyArguments();

            EventHandler dummyHandler = delegate(object eventSource, EventArgs e)
                                            {
                                                // The arguments passed to the
                                                // delegate should match the ones
                                                // given
                                                Assert.AreSame(eventSource, source);
                                                Assert.AreSame(e, args);
                                                counter.Increment();
                                            };

            Closure closure = new Closure(dummyHandler, source);
            Assert.IsTrue(closure.Arguments.Contains(source));
            closure.Invoke(args);
        }
示例#23
0
        /// <summary>
        /// Extension for MenuDialog that allows ShowTimer to call a Lua function when the timer expires.
        /// </summary>
        public static IEnumerator ShowTimer(this MenuDialog menuDialog, float duration, LuaEnvironment luaEnvironment, Closure callBack)
        {
            if (menuDialog.cachedSlider == null ||
                duration <= 0f)
            {
                yield break;
            }

            menuDialog.cachedSlider.gameObject.SetActive(true);
            menuDialog.StopAllCoroutines();

            float elapsedTime = 0;
            Slider timeoutSlider = menuDialog.GetComponentInChildren<Slider>();

            while (elapsedTime < duration)
            {
                if (timeoutSlider != null)
                {
                    float t = 1f - elapsedTime / duration;
                    timeoutSlider.value = t;
                }

                elapsedTime += Time.deltaTime;

                yield return null;
            }

            menuDialog.Clear();
            menuDialog.gameObject.SetActive(false);
            menuDialog.HideSayDialog();

            if (callBack != null)
            {
                luaEnvironment.RunLuaFunction(callBack, true);
            }
        }
        /// <summary>
        /// A Unity coroutine method which updates a Lua coroutine each frame.
        /// <param name="closure">A MoonSharp closure object representing a function.</param>
        /// <param name="onComplete">A delegate method that is called when the coroutine completes. Includes return parameter.</param>
        /// </summary>
        protected virtual IEnumerator RunLuaCoroutine(Closure closure, Action<DynValue> onComplete = null)
        {
            DynValue co = interpreter.CreateCoroutine(closure);

            DynValue returnValue = null;
            while (co.Coroutine.State != CoroutineState.Dead)
            {
                try
                {                
                    returnValue = co.Coroutine.Resume();
                }
                catch (InterpreterException ex)
                {
                    LogException(ex.DecoratedMessage, GetSourceCode());
                }

                yield return null;
            }

            if (onComplete != null)
            {
                onComplete(returnValue);
            }
        }
示例#25
0
 internal static void setclvalue(lua_State L, TValue obj, Closure x)
 {
     obj.value.gc = x;
     obj.tt       = LUA_TFUNCTION;
     checkliveness(G(L), obj);
 }
示例#26
0
        public Task Execute(TCommand command, CancellationToken cancellationToken)
        {
            var closure = new Closure(this, command, cancellationToken);

            return(closure.Execute());
        }
示例#27
0
 /// <summary>
 /// Initializes a new instance of the struct.
 /// </summary>
 /// <param name="module">The module.</param>
 /// <param name="receiver">The receiver, also known as the "this" reference.</param>
 /// <param name="arguments">The arguments.</param>
 /// <param name="entry">The entry point into the code.</param>
 /// <param name="closure">The initial closure, or null if none.</param>
 public Interpreter(Module module, Value receiver, Value[] arguments, int entry = 0, Closure closure = null)
 {
     this.Module           = module ?? throw new ArgumentNullException(nameof(module));
     this.Receiver         = receiver;
     this.Arguments        = arguments ?? throw new ArgumentNullException(nameof(arguments));
     this.Closure          = closure;
     this.ExceptionHandler = null;
     this.Stack            = Array.Empty <Value>();
     this.SP = 0;
     this.IP = entry;
 }
示例#28
0
        public TableDfa ToDfa()
        {
            var queuePool = SharedPools.Default <ProcessOnceQueue <Closure> >();
            var queue     = queuePool.Allocate();

            queue.Clear();
            var start = new Closure(Start, _nullTransitions, _finalStates);

            queue.Enqueue(
                start);

            var tableDfa = new TableDfa(start.GetHashCode());

            while (queue.Count > 0)
            {
                var transitions = SharedPools
                                  .Default <Dictionary <char, SortedSet <int> > >()
                                  .AllocateAndClear();

                var nfaClosure   = queue.Dequeue();
                var nfaClosureId = nfaClosure.GetHashCode();
                tableDfa.SetFinal(nfaClosureId, nfaClosure.IsFinal);

                for (int i = 0; i < nfaClosure.States.Length; i++)
                {
                    var state = nfaClosure.States[i];
                    Dictionary <char, int> characterTransitions = null;
                    if (!_table.TryGetValue(state, out characterTransitions))
                    {
                        continue;
                    }

                    foreach (var characterTransition in characterTransitions)
                    {
                        SortedSet <int> targets = null;
                        if (!transitions.TryGetValue(characterTransition.Key, out targets))
                        {
                            targets = SharedPools.Default <SortedSet <int> >().AllocateAndClear();
                            transitions.Add(characterTransition.Key, targets);
                        }

                        targets.Add(characterTransition.Value);
                    }
                }

                foreach (var targetSet in transitions)
                {
                    var closure = new Closure(targetSet.Value, _nullTransitions, _finalStates);
                    closure = queue.EnqueueOrGetExisting(closure);
                    var closureId = closure.GetHashCode();

                    tableDfa.AddTransition(nfaClosureId, targetSet.Key, closureId);
                    tableDfa.SetFinal(closureId, closure.IsFinal);

                    SharedPools.Default <SortedSet <int> >().ClearAndFree(targetSet.Value);
                }

                SharedPools
                .Default <Dictionary <char, SortedSet <int> > >()
                .ClearAndFree(transitions);
            }

            queuePool.Free(queue);
            return(tableDfa);
        }
示例#29
0
 /// <summary>
 /// Duplicates a closure with a specific bound object and class scope.
 /// </summary>
 public static Closure bind(Closure closure, object newthis, PhpValue newscope = default(PhpValue)) => closure.bindTo(newthis, newscope);
示例#30
0
        /// <summary>
        /// Adds the option to the list of displayed options, calls a Lua function when selected.
        /// Will cause the Menu dialog to become visible if it is not already visible.
        /// </summary>
        /// <returns><c>true</c>, if the option was added successfully.</returns>
        public virtual bool AddOption(string text, bool interactable, LuaEnvironment luaEnv, Closure callBack)
        {
            if (!gameObject.activeSelf)
            {
                gameObject.SetActive(true);
            }

            // Copy to local variables
            LuaEnvironment env  = luaEnv;
            Closure        call = callBack;

            UnityEngine.Events.UnityAction action = delegate
            {
                StopAllCoroutines();
                // Stop timeout
                Clear();
                HideSayDialog();
                // Use a coroutine to call the callback on the next frame
                StartCoroutine(CallLuaClosure(env, call));
            };

            return(AddOption(text, interactable, false, action));
        }
                private static Scope CreateNestedScope(BoundNode node, Scope parentScope, Closure currentClosure)
                {
                    Debug.Assert(parentScope.BoundNode != node);

                    var newScope = new Scope(parentScope, node, currentClosure);

                    parentScope.NestedScopes.Add(newScope);
                    return(newScope);
                }
示例#32
0
 internal static void SetCLValue(LuaState L, TValue obj, Closure x)
 {
     obj.value.gc = x;
     obj.tt = LUA_TFUNCTION;
     CheckLiveness(G(L), obj);
 }
示例#33
0
文件: lgc.cs 项目: raymanyu/kopilua
 private static void traverseclosure(global_State g, Closure cl)
 {
     markobject(g, cl.c.env);
       if (cl.c.isC != 0) {
     int i;
     for (i=0; i<cl.c.nupvalues; i++)  /* mark its upvalues */
       markvalue(g, cl.c.upvalue[i]);
       }
       else {
     int i;
     lua_assert(cl.l.nupvalues == cl.l.p.nups);
     markobject(g, cl.l.p);
     for (i=0; i<cl.l.nupvalues; i++)  /* mark its upvalues */
       markobject(g, cl.l.upvals[i]);
       }
 }
示例#34
0
 public object[] Call(Closure c, params object[] args)
 {
     var cb = ((ClosureBase)c).CreateCallableInstance();
     foreach(var arg in args) {
         cb.AddParam(arg);
     }
     if (cb is InternalClosure) {
         ((InternalClosure)cb).Run();
         return cb.GetResults().ToArray();
     }
     else { //cb is FunctionClosure
         return vm.Run((FunctionClosure)cb);
     }
 }
示例#35
0
        private ObjectLiteral BuildExecuteOutputs(Context context, ModuleLiteral env, ProcessOutputs processOutputs, bool isService)
        {
            var entry = context.TopStack;

            using (var empty = EvaluationStackFrame.Empty())
            {
                var getOutputFile = new Closure(
                    env,
                    FunctionLikeExpression.CreateAmbient(ExecuteResultGetOutputFile, m_getOutputFileSignature, GetOutputFile, m_getOutputFileStatistic),
                    frame: empty);

                var getOutputDirectory = new Closure(
                    env,
                    FunctionLikeExpression.CreateAmbient(ExecuteResultGetOutputDirectory, m_getOutputDirectorySignature, GetOutputDirectory, m_getOutputDirectoryStatistic),
                    frame: empty);

                var getOutputFiles = new Closure(
                    env,
                    FunctionLikeExpression.CreateAmbient(ExecuteResultGetOutputFiles, m_getOutputFilesSignature, GetOutputFiles, m_getOutputFilesStatistic),
                    frame: empty);

                var getRequiredOutputFiles = new Closure(
                    env,
                    FunctionLikeExpression.CreateAmbient(ExecuteResultGetRequiredOutputFiles, m_getRequiredOutputFilesSignature, GetRequiredOutputFiles, m_getRequiredOutputFilesStatistic),
                    frame: empty);

                var bindings = new List <Binding>(isService ? 5 : 4)
                {
                    new Binding(ExecuteResultGetOutputFile, getOutputFile, location: default),
                    new Binding(ExecuteResultGetOutputDirectory, getOutputDirectory, location: default),
                    new Binding(ExecuteResultGetOutputFiles, getOutputFiles, location: default),
                    new Binding(ExecuteResultGetRequiredOutputFiles, getRequiredOutputFiles, location: default),
                };
                if (isService)
                {
                    bindings.Add(new Binding(CreateServiceResultServiceId, processOutputs.ProcessPipId, location: default));
                }

                return(ObjectLiteral.Create(bindings, entry.InvocationLocation, entry.Path));
            }

            // Local functions
            EvaluationResult GetOutputFile(Context contextArg, ModuleLiteral envArg, EvaluationStackFrame args)
            {
                var outputPath = Args.AsPathOrUndefined(args, 0, false);

                if (outputPath.IsValid && processOutputs.TryGetOutputFile(outputPath, out var file))
                {
                    return(EvaluationResult.Create(file));
                }

                return(EvaluationResult.Undefined);
            }

            EvaluationResult GetOutputDirectory(Context contextArg, ModuleLiteral envArg, EvaluationStackFrame args)
            {
                var outputDir = Args.AsDirectory(args, 0);

                if (outputDir.IsValid && processOutputs.TryGetOutputDirectory(outputDir.Path, out var output))
                {
                    return(EvaluationResult.Create(output));
                }

                return(EvaluationResult.Undefined);
            }

            EvaluationResult GetOutputFiles(Context contextArg, ModuleLiteral envArg, EvaluationStackFrame args)
            {
                var outputFiles = processOutputs.GetOutputFiles().Select(f => EvaluationResult.Create(f)).ToArray();

                return(EvaluationResult.Create(ArrayLiteral.CreateWithoutCopy(outputFiles, entry.InvocationLocation, entry.Path)));
            }

            EvaluationResult GetRequiredOutputFiles(Context contextArg, ModuleLiteral envArg, EvaluationStackFrame args)
            {
                var outputFiles = processOutputs.GetRequiredOutputFiles().Select(f => EvaluationResult.Create(f)).ToArray();

                return(EvaluationResult.Create(ArrayLiteral.CreateWithoutCopy(outputFiles, entry.InvocationLocation, entry.Path)));
            }
        }
示例#36
0
        /// <summary>
        /// 返回与指定处理器数据相关的指定类型的委托。
        /// </summary>
        /// <typeparam name="TDelegate">委托的类型。</typeparam>
        /// <param name="data">处理器数据。</param>
        /// <param name="id">处理器标识。</param>
        /// <param name="instance">处理器要绑定到的实例。</param>
        /// <returns>与 <paramref name="data"/> 相关的 <typeparamref name="TDelegate"/> 类型的委托。</returns>
        private static TDelegate CreateSwitcher <TDelegate>(ProcessorData data, string id, object instance)
            where TDelegate : class
        {
            Contract.Requires(data != null);
            var    invoke     = typeof(TDelegate).GetInvokeMethod();
            var    paramTypes = invoke.GetParameterTypes();
            object closure;

            if (data.IsStatic)
            {
                closure = data.Processors;
            }
            else
            {
                closure = new Closure(new[] { instance, data.Processors }, null);
            }
            var method = new DynamicMethod("MethodSwitcher", invoke.ReturnType,
                                           paramTypes.Insert(0, closure.GetType()), true);
            var il = method.GetILGenerator();

            // 静态方法中,arg_0 用作存储处理器委托字典。
            if (data.IsStatic)
            {
                il.Emit(OpCodes.Ldarg_0);
            }
            else
            {
                // 实例方法中,Closure.Constants[1] 用作存储处理器委托字典。
                il.EmitLoadClosureConstant(1, typeof(Dictionary <Type, Delegate>));
            }
            // 判断关键参数是否为 null。
            il.EmitLoadArg(data.KeyIndex + 1);
            var keyNullCase = il.DefineLabel();

            il.Emit(OpCodes.Brtrue, keyNullCase);
            // 关键参数为 null,将 object 作为查找类型。
            il.EmitConstant(typeof(object));
            var endKeyNull = il.DefineLabel();

            il.Emit(OpCodes.Br, endKeyNull);
            // 关键参数不为 null,将参数类型作为查找类型。
            il.MarkLabel(keyNullCase);
            il.EmitLoadArg(data.KeyIndex + 1);
            il.EmitCall(methodGetType);
            il.MarkLabel(endKeyNull);
            // 调用 GetMethod 方法,取得方法委托。
            il.EmitConstant(id);
            il.EmitCall(methodGetMethod);
            il.Emit(OpCodes.Castclass, data.DelegateType);
            //// 载入参数,调用委托。
            var originParamTypes = data.DelegateParamTypes;

            if (!data.IsStatic)
            {
                // 载入实例,Closure.Constants[0]。
                il.EmitLoadClosureConstant(0, instance.GetType());
            }
            var offset = data.IsStatic ? 0 : 1;

            for (var i = 0; i < paramTypes.Length; i++)
            {
                var paramType  = paramTypes[i];
                var targetType = originParamTypes[i + offset];
                Contract.Assume(paramType != null && targetType != null);
                il.EmitLoadArg(i + 1, paramType, targetType);
            }
            il.Emit(OpCodes.Callvirt, data.DelegateType.GetInvokeMethod());
            var returnType       = originParamTypes[originParamTypes.Length - 1];
            var targetReturnType = invoke.ReturnType;

            // 转换返回类型。
            if (returnType == typeof(void))
            {
                if (targetReturnType != typeof(void))
                {
                    il.EmitConstant(null, targetReturnType);
                }
            }
            else
            {
                if (targetReturnType == typeof(void))
                {
                    il.Emit(OpCodes.Pop);
                }
                else if (returnType != targetReturnType)
                {
                    il.EmitConversion(returnType, targetReturnType, true, ConversionType.Explicit);
                }
            }
            il.Emit(OpCodes.Ret);
            return(method.CreateDelegate(typeof(TDelegate), closure) as TDelegate);
        }
示例#37
0
        void IMod.Init()
        {
            _G.path = Path.GetFullPath(Path.Combine(API.Helper.getModDirectory(this), "..", "..", "Lua Mods"));

            _G.LuaState.Globals["ScrW"] = new CallbackFunction((ScriptExecutionContext context, CallbackArguments arguments) => {
                return(DynValue.NewNumber(Screen.PrimaryScreen.Bounds.Width));
            });

            _G.LuaState.Globals["ScrH"] = new CallbackFunction((ScriptExecutionContext context, CallbackArguments arguments) => {
                return(DynValue.NewNumber(Screen.PrimaryScreen.Bounds.Height));
            });

            UserData.RegisterAssembly();
            Lua.Enums.Register(_G.LuaState);

            Lua.Surface surface = new Lua.Surface(_G.LuaState);
            _G.LuaState.Globals["draw"]    = new Lua.Draw(_G.LuaState, surface);
            _G.LuaState.Globals["surface"] = surface;
            _G.LuaState.Globals["hook"]    = _G.hook;
            _G.hook.form = form;
            _G.LuaState.Globals["input"]  = new Lua.Input(_G.LuaState);
            _G.LuaState.Globals["Msg"]    = _G.LuaState.Globals["print"];
            _G.LuaState.Globals["config"] = new Lua.Config(Path.Combine(_G.path, "config.ini"));

            _G.LuaState.Globals["AddConsoleCommand"] = new CallbackFunction((ScriptExecutionContext context, CallbackArguments arguments) => {
                return(DynValue.Nil);
            });

            _G.LuaState.Globals["Derma_StringRequest"] = new CallbackFunction((ScriptExecutionContext context, CallbackArguments arguments) => {
                string title       = arguments.AsStringUsingMeta(context, 0, "Derma_StringRequest");
                string subtitle    = arguments.AsStringUsingMeta(context, 1, "Derma_StringRequest");
                string value       = arguments.AsStringUsingMeta(context, 2, "Derma_StringRequest");
                Closure confirm    = arguments[3].Function;
                Closure cancel     = arguments.Count > 4 ? arguments[4].Function : default(Closure);
                string confirmText = arguments.Count > 5 ? arguments.AsStringUsingMeta(context, 5, "Derma_StringRequest") : "OK";
                string cancelText  = arguments.Count > 6 ? arguments.AsStringUsingMeta(context, 6, "Derma_StringRequest") : "Cancel";
                DialogResult res   = _G.InputBox(ref value, title, subtitle, confirmText, cancelText);
                if (res == DialogResult.Cancel)
                {
                    if (cancel != default(Closure))
                    {
                        cancel.Call();
                    }
                }
                else if (res == DialogResult.OK)
                {
                    confirm.Call(DynValue.NewString(value));
                }
                return(DynValue.Nil);
            });

            _G.LuaState.Globals["Derma_Message"] = new CallbackFunction((ScriptExecutionContext context, CallbackArguments arguments) => {
                string text    = arguments.AsStringUsingMeta(context, 0, "Derma_Message");
                string title   = arguments.AsStringUsingMeta(context, 1, "Derma_Message");
                string confirm = arguments.AsStringUsingMeta(context, 2, "Derma_Message");
                _G.MessageBox(text, title, confirm);
                return(DynValue.Nil);
            });

            _G.LuaState.Globals["HTTP"] = new CallbackFunction((ScriptExecutionContext context, CallbackArguments arguments) => {
                if (arguments.Count == 1 && arguments[0].Type == DataType.Table)
                {
                    return(DynValue.NewBoolean(Lua.Http.Request(arguments[0].Table)));
                }
                return(DynValue.False);
            });

            Util.include("http");
            Util.include("math");
            Util.include("string");
            Util.include("table");
            Util.include("bit");
            Util.include("color");
            Util.include("concommand");
            Util.include("defaultcmds");

            KeyEnums.Load();

            GooseProxy.Register();
            _G.LuaState.Globals["goose"]           = new GooseProxy(_G.LuaState);
            _G.LuaState.Globals["GetModDirectory"] = new CallbackFunction((ScriptExecutionContext context, CallbackArguments arguments) => {
                return(DynValue.NewString(_G.path));
            });
            _G.LuaState.Globals["CurTime"] = new CallbackFunction((ScriptExecutionContext context, CallbackArguments arguments) => {
                return(DynValue.NewNumber(SamEngine.Time.time));
            });

            _G.LuaState.Globals["RegisterTask"] = CallbackFunction.FromMethodInfo(_G.LuaState, typeof(Task).GetMethod("Register"));

            InjectionPoints.PreTickEvent       += preTick;
            InjectionPoints.PostTickEvent      += postTick;
            InjectionPoints.PreRenderEvent     += preRender;
            InjectionPoints.PostRenderEvent    += postRender;
            InjectionPoints.PreUpdateRigEvent  += preRig;
            InjectionPoints.PostUpdateRigEvent += postRig;

            Thread thread = new Thread(() => {
                form = new formLoader();
                form.ShowDialog();
            });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();

            System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
            timer.Tick += delegate {
                while (_G.mainQueue.Count > 0)
                {
                    try {
                        _G.mainQueue.Dequeue().Invoke();
                    } catch (InterpreterException ex) {
                        Util.MsgC(form, Color.FromArgb(255, 0, 0), string.Format("[ERROR] {0}: {1}\r\n{2}", ex.Source, ex.DecoratedMessage, ex.StackTrace), "\r\n");
                    } catch (Exception ex) {
                        MessageBox.Show(ex.ToString(), ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            };
            timer.Interval = 1;
            timer.Start();
        }
示例#38
0
 public EventListener(string eventName, Closure callback)
 {
     this.eventName = eventName;
     this.callback  = callback;
 }
示例#39
0
 public void RegisterEventListener(string eventName, Closure callback)
 {
     eventListeners.Add(new EventListener(eventName, callback));
 }
示例#40
0
        /// <summary> Runs the given piece of code, and returns the value left at the top of the stack. </summary>
        public Val Execute(Closure fn, params Val[] args)
        {
            State              st           = new State(fn, args);
            CodeHandle         code         = default;
            List <Instruction> instructions = null;

            if (_logger.EnableInstructionLogging)
            {
                _logger.Log("Executing: ", fn.name);
                _logger.Log(_ctx.code.DebugPrint(fn));
            }

            while (!st.done)
            {
                if (!code.Equals(st.fn.code))
                {
                    code         = st.fn.code;
                    instructions = _ctx.code.Get(code).instructions;
                }

                if (st.pc >= instructions.Count)
                {
                    throw new LanguageError("Runaway opcodes!");
                }

                // fetch instruction
                Instruction instr = instructions[st.pc++];

                if (_logger.EnableStackLogging)
                {
                    _logger.Log("                                    " + State.PrintStack(st));
                    _logger.Log(string.Format("[{0,2}] {1,3} : {2}", st.stack.Count, st.pc - 1, instr.DebugPrint()));
                }

                // and now a big old switch statement. not handler functions - this is much faster.

                switch (instr.type)
                {
                case Opcode.LABEL:
                    // no op :)
                    break;

                case Opcode.PUSH_CONST: {
                    st.Push(instr.first);
                }
                break;

                case Opcode.LOCAL_GET: {
                    VarPos pos   = new VarPos(instr.first, instr.second);
                    Val    value = Environment.GetValueAt(pos, st.env);
                    st.Push(value);
                }
                break;

                case Opcode.LOCAL_SET: {
                    VarPos pos   = new VarPos(instr.first, instr.second);
                    Val    value = st.Peek();
                    Environment.SetValueAt(pos, value, st.env);
                }
                break;

                case Opcode.GLOBAL_GET: {
                    Symbol symbol = instr.first.AsSymbol;
                    Val    value  = symbol.pkg.GetValue(symbol);
                    st.Push(value);
                }
                break;

                case Opcode.GLOBAL_SET: {
                    Symbol symbol = instr.first.AsSymbol;
                    Val    value  = st.Peek();
                    symbol.pkg.SetValue(symbol, value);
                }
                break;

                case Opcode.STACK_POP:
                    st.Pop();
                    break;

                case Opcode.JMP_IF_TRUE: {
                    Val value = st.Pop();
                    if (value.CastToBool)
                    {
                        st.pc = GetLabelPosition(instr);
                    }
                }
                break;

                case Opcode.JMP_IF_FALSE: {
                    Val value = st.Pop();
                    if (!value.CastToBool)
                    {
                        st.pc = GetLabelPosition(instr);
                    }
                }
                break;

                case Opcode.JMP_TO_LABEL: {
                    st.pc = GetLabelPosition(instr);
                }
                break;

                case Opcode.MAKE_ENV: {
                    int argcount = instr.first.AsInt;
                    if (st.argcount != argcount)
                    {
                        throw new LanguageError($"Argument count error, expected {argcount}, got {st.argcount}");
                    }

                    // make an environment for the given number of named args
                    st.env = new Environment(st.argcount, st.env);

                    // move named arguments onto the stack frame
                    for (int i = argcount - 1; i >= 0; i--)
                    {
                        st.env.SetValue(i, st.Pop());
                    }
                }
                break;

                case Opcode.MAKE_ENVDOT: {
                    int argcount = instr.first.AsInt;
                    if (st.argcount < argcount)
                    {
                        throw new LanguageError($"Argument count error, expected {argcount} or more, got {st.argcount}");
                    }

                    // make an environment for all named args, +1 for the list of remaining varargs
                    int dotted = st.argcount - argcount;
                    st.env = new Environment(argcount + 1, st.env);

                    // cons up dotted values from the stack
                    for (int dd = dotted - 1; dd >= 0; dd--)
                    {
                        Val arg = st.Pop();
                        st.env.SetValue(argcount, new Val(new Cons(arg, st.env.GetValue(argcount))));
                    }

                    // and move the named ones onto the environment stack frame
                    for (int i = argcount - 1; i >= 0; i--)
                    {
                        st.env.SetValue(i, st.Pop());
                    }
                }
                break;

                case Opcode.DUPLICATE: {
                    if (st.stack.Count == 0)
                    {
                        throw new LanguageError("Cannot duplicate on an empty stack!");
                    }
                    st.Push(st.Peek());
                }
                break;

                case Opcode.JMP_CLOSURE: {
                    st.env = st.env.parent;         // discard the top environment frame
                    Val     top     = st.Pop();
                    Closure closure = top.AsClosureOrNull;

                    // set vm state to the beginning of the closure
                    st.fn       = closure ?? throw new LanguageError($"Unknown function during function call around: {DebugRecentInstructions(st, instructions)}");
                    st.env      = closure.env;
                    st.pc       = 0;
                    st.argcount = instr.first.AsInt;
                }
                break;

                case Opcode.SAVE_RETURN: {
                    // save current vm state to a return value
                    st.Push(new Val(new ReturnAddress(st.fn, GetLabelPosition(instr), st.env, instr.first.AsStringOrNull)));
                }
                break;

                case Opcode.RETURN_VAL:
                    if (st.stack.Count > 1)
                    {
                        // preserve return value on top of the stack
                        Val           retval  = st.Pop();
                        ReturnAddress retaddr = st.Pop().AsReturnAddress;
                        st.Push(retval);

                        // restore vm state from the return value
                        st.fn  = retaddr.fn;
                        st.env = retaddr.env;
                        st.pc  = retaddr.pc;
                    }
                    else
                    {
                        st.done = true;     // this will force the virtual machine to finish up
                    }
                    break;

                case Opcode.MAKE_CLOSURE: {
                    var cl = instr.first.AsClosure;
                    st.Push(new Closure(cl.code, st.env, null, cl.name));
                }
                break;

                case Opcode.CALL_PRIMOP: {
                    string name = instr.first.AsString;
                    int    argn = (instr.second.IsInt) ? instr.second.AsInt : st.argcount;

                    Primitive prim = Primitives.FindNary(name, argn);
                    if (prim == null)
                    {
                        throw new LanguageError($"Invalid argument count to primitive {name}, count of {argn}");
                    }

                    Val result = prim.Call(_ctx, argn, st);
                    st.Push(result);
                }
                break;

                default:
                    throw new LanguageError("Unknown instruction type: " + instr.type);
                }
            }

            // return whatever's on the top of the stack
            if (st.stack.Count == 0)
            {
                throw new LanguageError("Stack underflow!");
            }

            return(st.Peek());
        }
示例#41
0
        protected internal static Expression GetAst(object args, CodeBlock cb, bool istailposition)
        {
            var spanHint = SpanHint;

            if (args is Annotation)
            {
                args = ((Annotation)args).stripped;
            }
            Cons c = args as Cons;

            if (c != null)
            {
                // in debug mode, this will be (annotated-call <location> . symbol)
                // TODO: see if the discarded annotation is useful
                if (ScriptDomainManager.Options.DebugMode && c.car is Cons)
                {
                    Cons ac = c.car as Cons;
                    if (ac.car == SymbolTable.StringToObject("annotated-call"))
                    {
                        object se = ((Cons)ac.cdr).cdr;
                        if (se is SymbolId)
                        {
                            c.car = se;
                        }
                    }
                }

                if (c.car is SymbolId)
                {
                    SymbolId f = (SymbolId)c.car;

                    Variable var = cb.Lookup(f);

                    if (var != null && !assigns.ContainsKey(f))
                    {
                        var = null;
                    }

                    object m;

#if OPTIMIZATIONS
#if !BLAH
                    CodeBlockExpression cbe;

                    //// needs to do the same for overloads...
                    if (SimpleGenerator.libraryglobals.TryGetValue(f, out cbe))
                    {
                        Expression[] ppp = GetAstListNoCast(c.cdr as Cons, cb);

                        if (cbe.Block.ParameterCount < 9 && cbe.Block.ParameterCount == ppp.Length)
                        {
                            //inline here? we could for simple bodies, but we need to copy the entire structure
                            if (!(cbe.Block.HasEnvironment || cbe.Block.IsClosure))
                            {
                                if (cbe.Block.Body is ReturnStatement)
                                {
                                    ReturnStatement rs = (ReturnStatement)cbe.Block.Body;

                                    if (!cb.IsGlobal && IsSimpleExpression(rs.Expression))
                                    {
                                        return(InlineCall(cb, Ast.CodeBlockExpression(RewriteBody(cbe.Block), false, cbe.IsStronglyTyped), ppp));
                                    }
                                }
                            }
                            if (cbe.Block != cb.Parent && cbe.Block != cb) // do TCE later
                            {
                                return(CallNormal(cbe, ppp));
                            }
                        }
                    }

                    // varargs
                    if (SimpleGenerator.libraryglobalsX.TryGetValue(f, out cbe))
                    {
                        Expression[] ppp = GetAstListNoCast(c.cdr as Cons, cb);

                        if (cbe.Block.ParameterCount < 9 && cbe.Block.ParameterCount - 1 <= ppp.Length)
                        {
                            //inline here?
                            return(CallVarArgs(cbe, ppp));
                        }
                    }

                    // overloads
                    CodeBlockDescriptor[] cbd;
                    if (SimpleGenerator.libraryglobalsN.TryGetValue(f, out cbd))
                    {
                        Expression[] ppp = GetAstListNoCast(c.cdr as Cons, cb);

                        foreach (CodeBlockDescriptor d in cbd)
                        {
                            if (d.codeblock.Block.ParameterCount < 9)
                            {
                                if (ppp.Length == d.arity || (d.varargs && ppp.Length > d.arity))
                                {
                                    if (d.varargs)
                                    {
                                        //inline here?
                                        return(CallVarArgs(d.codeblock, ppp));
                                    }
                                    else
                                    {
                                        //inline here?
                                        //if (d.codeblock.Block != cb.Parent && d.codeblock.Block != cb) // do TCE later, not yet
                                        {
                                            return(CallNormal(d.codeblock, ppp));
                                        }
                                    }
                                }
                            }
                        }
                    }
#endif

                    //if (!ScriptDomainManager.Options.DebugMode)
                    {
                        if (f == SymbolTable.StringToId("call-with-values"))
                        {
                            Expression[] ppp = GetAstListNoCast(c.cdr as Cons, cb);
                            if (ppp.Length == 2 && ppp[1] is MethodCallExpression)
                            {
                                MethodCallExpression consumer = ppp[1] as MethodCallExpression;

                                if (ppp[0] is MethodCallExpression)
                                {
                                    MethodCallExpression producer = ppp[0] as MethodCallExpression;
                                    if (consumer.Method == Closure_Make && producer.Method == Closure_Make)
                                    {
                                        CodeBlockExpression ccbe = consumer.Arguments[0] as CodeBlockExpression;
                                        CodeBlockExpression pcbe = producer.Arguments[0] as CodeBlockExpression;

                                        pcbe.Block.Bind();
                                        ccbe.Block.Bind();

                                        if (ccbe.Block.ParameterCount == 0)
                                        {
                                            return(InlineCall(cb, ccbe));
                                        }
                                        else if (ccbe.Block.ParameterCount == 1)
                                        {
                                            return(InlineCall(cb, ccbe, Ast.SimpleCallHelper(typeof(Helpers).GetMethod("UnwrapValue"), InlineCall(cb, pcbe))));
                                        }
                                        else
                                        {
                                            Variable values = cb.CreateTemporaryVariable((SymbolId)Builtins.GenSym("values"), typeof(object[]));

                                            Expression valuesarr = Ast.Read(values);

                                            Expression[] pppp = new Expression[ccbe.Block.ParameterCount];

                                            for (int i = 0; i < pppp.Length; i++)
                                            {
                                                pppp[i] = Ast.ArrayIndex(valuesarr, Ast.Constant(i));
                                            }

                                            return(Ast.Comma(
                                                       Ast.Void(
                                                           Ast.Write(
                                                               values,
                                                               Ast.ComplexCallHelper(
                                                                   Ast.SimpleCallHelper(typeof(Helpers).GetMethod("WrapValue"), InlineCall(cb, pcbe)),
                                                                   typeof(MultipleValues).GetMethod("ToArray", new Type[] { typeof(int) }),
                                                                   Ast.Constant(pppp.Length)))),
                                                       InlineCall(cb, ccbe, pppp)));
                                        }
                                    }
                                }
                                if (consumer.Method == Closure_Make)
                                {
                                    CodeBlockExpression ccbe = consumer.Arguments[0] as CodeBlockExpression;
                                    ccbe.Block.Bind();

                                    Expression producer = ppp[0];

                                    Expression exx = Ast.ConvertHelper(producer, typeof(Callable));

                                    MethodInfo callx = GetCallable(0);

                                    if (ccbe.Block.ParameterCount == 0)
                                    {
                                        return(InlineCall(cb, ccbe));
                                    }
                                    else if (ccbe.Block.ParameterCount == 1)
                                    {
                                        return(InlineCall(cb, ccbe, Ast.SimpleCallHelper(typeof(Helpers).GetMethod("UnwrapValue"), Ast.Call(exx, callx))));
                                    }
                                    else
                                    {
                                        Variable values = cb.CreateTemporaryVariable((SymbolId)Builtins.GenSym("values"), typeof(object[]));

                                        Expression valuesarr = Ast.Read(values);

                                        Expression[] pppp = new Expression[ccbe.Block.ParameterCount];

                                        for (int i = 0; i < pppp.Length; i++)
                                        {
                                            pppp[i] = Ast.ArrayIndex(valuesarr, Ast.Constant(i));
                                        }

                                        return(Ast.Comma(
                                                   Ast.Void(
                                                       Ast.Write(
                                                           values,
                                                           Ast.ComplexCallHelper(
                                                               Ast.SimpleCallHelper(typeof(Helpers).GetMethod("WrapValue"),
                                                                                    Ast.Call(exx, callx)),
                                                               typeof(MultipleValues).GetMethod("ToArray", new Type[] { typeof(int) }),
                                                               Ast.Constant(pppp.Length)))),
                                                   InlineCall(cb, ccbe, pppp)));
                                    }
                                }
                            }
                            else
                            {
                                ;
                            }
                        }
                    }
#endif
                    // this can be enabled once builtins are auto CPS'd.
                    // ok I tried, but there are issues still, not sure what
#if OPTIMIZATIONS
                    // check for inline emitter
                    InlineEmitter ie;
                    if (TryGetInlineEmitter(f, out ie))
                    {
                        Expression result = ie(GetAstList(c.cdr as Cons, cb));
                        // if null is returned, the method cannot be inlined
                        if (result != null)
                        {
                            if (spanHint.IsValid)
                            {
                                result.SetLoc(spanHint);
                            }
                            return(result);
                        }
                    }
#endif

                    if (Context.Scope.TryLookupName(f, out m))
                    {
                        if (var == null)
                        {
                            IGenerator gh = m as IGenerator;
                            if (gh != null)
                            {
                                return(gh.Generate(c.cdr, cb));
                            }

                            BuiltinMethod bf = m as BuiltinMethod;
                            if (bf != null)
                            {
                                MethodBinder mb   = bf.Binder;
                                Expression[] pars = Array.ConvertAll(GetAstList(c.cdr as Cons, cb), e => Unwrap(e));

                                if (bf.AllowConstantFold && !ScriptDomainManager.Options.DebugMode)
                                {
                                    bool constant = Array.TrueForAll(pars, e => e is ConstantExpression && e.Type != typeof(BigInteger));

                                    if (constant)
                                    {
                                        object[]    cargs = Array.ConvertAll(pars, e => GetRuntimeConstant((ConstantExpression)e));
                                        CallTarget0 disp  = delegate
                                        {
                                            return(bf.Call(cargs));
                                        };
                                        CallTarget1 handler = delegate(object e)
                                        {
                                            throw new CompileTimeEvaluationException();
                                        };

                                        try
                                        {
                                            object result = Runtime.R6RS.Exceptions.WithExceptionHandler(
                                                Closure.Create(handler),
                                                Closure.Create(disp));
                                            var rrrr = GetCons(result, cb);
                                            if (spanHint.IsValid)
                                            {
                                                rrrr.SetLoc(spanHint);
                                            }
                                            return(rrrr);
                                        }
                                        catch (CompileTimeEvaluationException)
                                        {
                                        }
                                    }
                                }

                                Type[]          types = GetExpressionTypes(pars);
                                MethodCandidate mc    = mb.MakeBindingTarget(CallType.None, types);
                                if (mc != null)
                                {
                                    if (mc.Target.NeedsContext)
                                    {
                                        pars = ArrayUtils.Insert <Expression>(Ast.CodeContext(), pars);
                                    }
                                    MethodBase meth = mc.Target.Method;

                                    var rrrr = Ast.ComplexCallHelper(meth as MethodInfo, pars);
                                    if (spanHint.IsValid)
                                    {
                                        rrrr.SetLoc(spanHint);
                                    }
                                    return(rrrr);
                                }
                            }

                            Closure clos = m as Closure;
                            if (clos != null && !SetGenerator.IsAssigned(f))
                            {
                                // no provision for varargs
                                MethodInfo[] mis = clos.Targets;
                                if (mis.Length > 0)
                                {
                                    MethodBinder mb = MethodBinder.MakeBinder(binder, SymbolTable.IdToString(f), mis, BinderType.Normal);

                                    Expression[] pars = Array.ConvertAll(GetAstList(c.cdr as Cons, cb), e => Unwrap(e));

                                    if (clos.AllowConstantFold && !ScriptDomainManager.Options.DebugMode)
                                    {
                                        bool constant = Array.TrueForAll(pars, e => e is ConstantExpression && e.Type != typeof(BigInteger));

                                        if (constant)
                                        {
                                            object[] cargs = Array.ConvertAll(pars, e => GetRuntimeConstant((ConstantExpression)e));

                                            CallTarget0 disp = delegate
                                            {
                                                var rrrr = clos.Call(cargs);
                                                return(rrrr);
                                            };

                                            CallTarget1 handler = delegate(object e)
                                            {
                                                throw new CompileTimeEvaluationException();
                                            };

                                            try
                                            {
                                                object result = Runtime.R6RS.Exceptions.WithExceptionHandler(
                                                    Closure.Create(handler),
                                                    Closure.Create(disp));
                                                var rrrr = GetCons(result, cb);
                                                if (spanHint.IsValid)
                                                {
                                                    rrrr.SetLoc(spanHint);
                                                }
                                                return(rrrr);
                                            }
                                            catch (CompileTimeEvaluationException)
                                            {
                                            }
                                        }
                                    }

                                    // exclude transient members if needed
                                    if (!AllowTransientBinding)
                                    {
                                        mis = Array.FindAll(mis, x => !IsTransient(x.Module));
                                    }

                                    if (mis.Length > 0)
                                    {
                                        Type[]          types = GetExpressionTypes(pars);
                                        MethodCandidate mc    = mb.MakeBindingTarget(CallType.None, types);
                                        if (mc != null)
                                        {
                                            if (mc.Target.NeedsContext)
                                            {
                                                pars = ArrayUtils.Insert <Expression>(Ast.CodeContext(), pars);
                                            }
                                            MethodBase meth = mc.Target.Method;

                                            var rrrr = Ast.ComplexCallHelper(meth as MethodInfo, pars);
                                            if (spanHint.IsValid)
                                            {
                                                rrrr.SetLoc(spanHint);
                                            }
                                            return(rrrr);
                                        }
                                    }
                                }
                                // check for overload thing
                            }
                        }
                    }
                }


                Expression ex = Unwrap(GetAst(c.car, cb));

                // a 'let'
                if (ex is MethodCallExpression)
                {
                    var ppp = GetAstList(c.cdr as Cons, cb);
                    MethodCallExpression mcexpr = (MethodCallExpression)ex;
                    if (mcexpr.Method == Closure_Make)
                    {
                        CodeBlockExpression cbe = mcexpr.Arguments[0] as CodeBlockExpression;

                        if (ppp.Length < 9 && cbe.Block.ParameterCount == ppp.Length)
                        {
                            return(InlineCall(cb, cbe, istailposition, ppp));
                        }
                    }

                    // cater for varargs more efficiently, this does not seem to hit, probably needed somewhere else
                    if (mcexpr.Method == Closure_MakeVarArgsX)
                    {
                        CodeBlockExpression cbe = mcexpr.Arguments[0] as CodeBlockExpression;

                        if (ppp.Length < 9 && cbe.Block.ParameterCount <= ppp.Length)
                        {
                            return(CallVarArgs(cbe, ppp));
                        }
                    }
                }

                if (ex is NewExpression && typeof(ITypedCallable).IsAssignableFrom(ex.Type))
                {
                    NewExpression       mcexpr = ex as NewExpression;
                    CodeBlockExpression cbe    = mcexpr.Arguments[0] as CodeBlockExpression;
                    if (cbe == null && mcexpr.Arguments[0].Type == typeof(CodeContext) && mcexpr.Arguments[0] is ConstantExpression) // implies null
                    {
                        cbe = mcexpr.Arguments[1] as CodeBlockExpression;
                    }
                    if (cbe != null)
                    {
                        var ppp = GetAstListNoCast(c.cdr as Cons, cb);

                        if (ppp.Length < 9 && cbe.Block.ParameterCount == ppp.Length)
                        {
                            return(InlineCall(cb, cbe, istailposition, ppp));
                        }
                    }
                }

                if (ex is ConstantExpression)
                {
                    Builtins.SyntaxError(SymbolTable.StringToObject("generator"), "expecting a procedure", c.car, c);
                }

                Expression r = null;

                if (ex.Type.Name.StartsWith("TypedClosure"))
                {
                    Expression[] pp = GetAstListNoCast(c.cdr as Cons, cb);

                    var m = ex.Type.GetMethod("Invoke");
                    //TODO: add more checks, should we attempt some casting for types?
                    if (m.GetParameters().Length != pp.Length)
                    {
                        Builtins.SyntaxError(SymbolTable.StringToObject("apply-typed-lambda"),
                                             string.Format("incorrect number of parameters, expected {0} got {1}", m.GetParameters().Length, pp.Length),
                                             c.car, c);
                    }
                    r = Ast.SimpleCallHelper(ex, m, pp);
                }
                else
                {
                    Expression[] pp = GetAstList(c.cdr as Cons, cb);

                    if (ex.Type != typeof(Callable))
                    {
                        ex = Ast.ConvertHelper(ex, typeof(Callable));
                    }

                    MethodInfo call = GetCallable(pp.Length);

                    r = pp.Length > 8 ?
                        Ast.Call(ex, call, Ast.NewArray(typeof(object[]), pp)) :
                        Ast.Call(ex, call, pp);
                }

                if (spanHint.IsValid)
                {
                    r.SetLoc(spanHint);
                }

                return(r);
            }

            object[] v = args as object[];

            if (v != null)
            {
                return(GetConsVector(v, cb));
            }
            else if (args is byte[])
            {
                Expression[] ba = Array.ConvertAll(args as byte[], b => Ast.Constant(b));
                return(Ast.NewArray(typeof(byte[]), ba));
            }
            else
            {
                if (args is SymbolId)
                {
                    SymbolId sym = (SymbolId)args;
                    if (sym == SymbolTable.StringToId("uninitialized"))
                    {
                        return(Ast.ReadField(null, typeof(Uninitialized), "Instance"));
                    }
                    else
                    {
                        return(Read(sym, cb, typeof(object)));
                    }
                }
                if (args == Builtins.Unspecified)
                {
                    return(Ast.ReadField(null, Unspecified));
                }
                if (args is Fraction)
                {
                    Fraction f = (Fraction)args;
                    return(Ast.Constant(new FractionConstant(f)));
                }
                if (args is ComplexFraction)
                {
                    ComplexFraction f = (ComplexFraction)args;
                    return(Ast.Constant(new ComplexFractionConstant(f)));
                }
                if (args != null && args.GetType().Name == "stx")
                {
                    args = new SerializedConstant(args);
                }
                return(Ast.Constant(args));
            }
        }
示例#42
0
 public void SaveClosure(Closure closure)
 {
     ClosureCollection.InsertOne(closure);
 }
示例#43
0
        private EvaluationResult DoGetOrAdd(Context context, ModuleLiteral env, EvaluationResult key, EvaluationResult?state, Closure factoryClosure)
        {
            var helper = new HashingHelper(context.PathTable, recordFingerprintString: false);

            // Add the qualifier to the key
            var qualifierId            = context.LastActiveModuleQualifier.QualifierId;
            var qualifierDisplayString = context.ContextTree.FrontEndContext.QualifierTable.GetQualifier(qualifierId).ToDisplayString(StringTable);

            helper.Add(qualifierDisplayString);
            if (!TryHashValue(key, helper))
            {
                return(EvaluationResult.Error);
            }

            var keyFingerprint           = helper.GenerateHash().ToHex();
            var thunkCreatedByThisThread = false;

            // ensure that all concurrent evaluations of the same value cache key will get the same thunk and module
            var thunkAndModule = context.EvaluationScheduler.ValueCacheGetOrAdd(
                keyFingerprint,
                () =>
            {
                var factoryArgs = state.HasValue
                        ? new Expression[] { new LocalReferenceExpression(SymbolAtom.Create(context.StringTable, "state"), index: factoryClosure.Frame.Length, default) }
                        : CollectionUtilities.EmptyArray <Expression>();

                var thunk  = new Thunk(ApplyExpression.Create(factoryClosure, factoryArgs, factoryClosure.Location), null);
                var module = context.LastActiveUsedModule;
                thunkCreatedByThisThread = true;
                return(thunk, module);
            });
示例#44
0
文件: MondValue.cs 项目: foobit/Mond
 internal MondValue(Closure closure)
 {
     Type          = MondValueType.Function;
     FunctionValue = closure;
 }
示例#45
0
 internal static void SetCLValue(LuaState L, TValue obj, Closure x)
 {
     obj.value.gc = x;
     obj.tt       = LUA_TFUNCTION;
     CheckLiveness(G(L), obj);
 }
示例#46
0
        private static void Main(string[] args)
        {
            LogFactory.SetDefaultLog(new ConsoleLog());

            _settings = _settingsProvider.GetSettings();

            var uzClient = new UzClient(_settings.BaseUrl, _settings.SessionCookie);
            var telebot  = new TelegramBot(_settings.BotToken, _settings.MasterChatID);

            using (var locker = new AutoResetEvent(false))
            {
                var closure = new Closure(uzClient, telebot, locker);

                Console.OutputEncoding  = Encoding.UTF8;
                Console.CancelKeyPress += closure.CancelKeyPressHandler;

                uzClient.ScanEvent += (o, e) => telebot.SendMasterMessage(e.Message);

                Run(uzClient, telebot);

                //host.Initialize();


                //telebot.Error += (o, e) => { };

                //var provider = resolver.Get<ISettingsProvider>();
                //var settings = provider.GetSettings();
                //_proxyProvider = resolver.Get<IProxyProvider>();

                //var bot = new TelegramBotClient(settings.TeleBotKey);
                //bot.OnMessage += BotOnOnMessage;
                //bot.OnReceiveError += (sender, eventArgs) => Console.WriteLine("Bot receive error:{0}{1}", Environment.NewLine, eventArgs.ApiRequestException);
                //bot.OnReceiveGeneralError += (sender, eventArgs) => Console.WriteLine("Bot general receive error:{0}{1}", Environment.NewLine, eventArgs.Exception);

                //host.Started += (sender, eventArgs) => bot.StartReceiving();
                //host.Stopping += (sender, eventArgs) => bot.StopReceiving();
                //host.Stopped += (sender, eventArgs) => locker.Set();

/*
 *                              var assembly = Assembly.GetExecutingAssembly();
 *                              var asmName = assembly.GetName().Name;
 *                              var builder = resolver.Get<IStateMachineBuilder<TestState, StateMachineStuff, string>>();
 *                              IStateMachine<TestState, StateMachineStuff, string> sm;
 *
 *                              using (var str = assembly.GetManifestResourceStream($"{asmName}.Properties.testmachine.scxml"))
 *                              {
 *                                      sm = builder.BuildFromXml(str, new StateMachineStuff());
 *                              }
 *
 * //				var sm = resolver.Get<IStateMachineBuilder<DayOfWeek, EventArgs, string>>()
 * //							.AddDefaultStates((e, dw, inp) => Console.WriteLine($"Came here by input: {inp}"), null, null)
 * //							.AddTransition(DayOfWeek.Sunday, DayOfWeek.Monday, (e, dw, dwNew, inp) => true)
 * //							.Build(EventArgs.Empty);
 * //				sm.MoveNext("test");
 */
                //RunBot(bot, locker);
                //host.Start();

                /*
                 * string inp;
                 *
                 *
                 * while (!String.IsNullOrEmpty(inp = Console.ReadLine()))
                 * {
                 *      sm.MoveNext(inp);
                 * }
                 */
                locker.WaitOne();

                Console.WriteLine("Got shutdown signal. Stopping application...");
                Console.CancelKeyPress -= closure.CancelKeyPressHandler;
            }
        }
        private static Resource ClosureOperation(NameValueCollection queryParam)
        {
            bool outcome  = true;
            int  spReturn = 0;
            bool resync   = false;

            string nameVal    = Utilities.GetQueryValue("name", queryParam);
            string versionVal = Utilities.GetQueryValue("version", queryParam);
            string codeVals   = Utilities.GetQueryValue("code", queryParam);
            string systemVal  = Utilities.GetQueryValue("system", queryParam);

            // need to determine task (initialise /add concept / version check / resync) from what is passed
            // nb client can pass a version or concept(s), but not both
            if (string.IsNullOrEmpty(nameVal))
            {
                throw new Exception(MISSING_CLOSURE_NAME);
            }

            // nb if versionVal = 0 will re-synch entire table (BUT if >0 changes since certain version OR specific version?)
            resync = !string.IsNullOrEmpty(versionVal);

            if (resync && !string.IsNullOrEmpty(codeVals))
            {
                throw new Exception(INVALID_CLOSURE_PARAMS);
            }

            if (!string.IsNullOrEmpty(codeVals) || resync)
            {
                if (systemVal != FhirSnomed.URI && !resync)
                {
                    throw new Exception(UNSUPPORTED_CODE_SYSTEM);
                }

                string newConcepts    = string.Empty;
                short  dbVer          = 0;
                string storedConcepts = Closure.GetClosureConcepts(nameVal, (short)spReturn, out dbVer);
                bool   codesToAdd     = false;

                foreach (string cd in codeVals.Split(';'))
                {
                    if (!string.IsNullOrEmpty(cd))
                    {
                        string newCode = cd.Trim() + "|";
                        if (storedConcepts.IndexOf(newCode) < 0)
                        {
                            storedConcepts += newCode;
                            codesToAdd      = true;
                        }
                    }
                }

                if (codesToAdd)
                {
                    spReturn = Closure.UpdateClosureTable(nameVal, storedConcepts, CLOSURE_CODE_SYSTEM_ID, CLOSURE_CODE_SYSTEM_VERSION);
                }

                if (spReturn == -1)
                {
                    throw new Exception(INVALID_CLOSURE_NAME);
                }
                else if (spReturn == 99)
                {
                    throw new Exception(REINITIALISE_CLOSURE);
                }

                ConceptMap cMap = new ConceptMap();
                cMap.Id           = Guid.NewGuid().ToString();
                cMap.Version      = dbVer.ToString();
                cMap.Name         = "Updates for Closure Table " + nameVal;
                cMap.Status       = PublicationStatus.Active;
                cMap.Experimental = true;
                cMap.Date         = Hl7.Fhir.Model.Date.Today().Value;

                ConceptMap.GroupComponent gc = new ConceptMap.GroupComponent();
                gc.Source        = CLOSURE_CODE_SYSTEM_ID;
                gc.SourceVersion = CLOSURE_CODE_SYSTEM_VERSION;
                gc.Target        = CLOSURE_CODE_SYSTEM_ID;
                gc.TargetVersion = CLOSURE_CODE_SYSTEM_VERSION;

                if (resync)
                {
                    codeVals = storedConcepts.Replace("|", ";");
                }

                string subSuper = string.Empty;

                // look for sub-type / super-type relationships between existing codes and new codes
                foreach (string newCode in codeVals.Split(';'))
                {
                    foreach (string storedCode in storedConcepts.Split('|'))
                    {
                        if (!string.IsNullOrEmpty(newCode) && newCode != storedCode)
                        {
                            // does one of these codes subsume another?
                            string relat     = TerminologyCodeSystem.GetRelationship(storedCode, newCode);
                            string supertype = string.Empty;
                            string subType   = string.Empty;

                            if (relat == TerminologyCodeSystem.CODE_RELATIONSHIP_SUBSUMED_BY)
                            {
                                subType   = storedCode;
                                supertype = newCode;
                            }
                            else if (relat == TerminologyCodeSystem.CODE_RELATIONSHIP_SUBSUMES)
                            {
                                subType   = newCode;
                                supertype = storedCode;
                            }

                            // check if this combination used already (reSync)
                            string combo   = subType + "+" + supertype + "|";
                            bool   newPair = false;

                            if (!string.IsNullOrEmpty(supertype))
                            {
                                if (subSuper.IndexOf(combo) < 0)
                                {
                                    subSuper += combo;
                                    newPair   = true;
                                }
                            }

                            if (newPair)
                            {
                                ConceptMap.SourceElementComponent sec = new ConceptMap.SourceElementComponent {
                                    Code = subType
                                };
                                ConceptMap.TargetElementComponent tec = new ConceptMap.TargetElementComponent {
                                    Code = supertype, Equivalence = ConceptMap.ConceptMapEquivalence.Subsumes
                                };
                                sec.Target.Add(tec);
                                gc.Element.Add(sec);
                            }
                        }
                    }
                }

                cMap.Group.Add(gc);

                return(cMap);
            }
            else
            {
                // initialise Closure Table
                outcome = Closure.AddClosureTable(nameVal, CLOSURE_CODE_SYSTEM_ID, CLOSURE_CODE_SYSTEM_VERSION);
                if (outcome == false)
                {
                    throw new Exception(INVALID_CLOSURE_NAME);
                }
            }

            Parameters param = new Parameters();

            param.Add("outcome", new FhirBoolean(outcome));

            return(param);
        }
示例#48
0
        /// <summary>
        /// Compiles the expression x, given the environment env, into a vector of instructions.
        /// </summary>
        private List <Instruction> Compile(Val x, Environment env, State st)
        {
            // check if macro
            if (IsMacroApplication(x))
            {
                return(Compile(MacroExpandFull(x), env, st));
            }

            if (x.IsSymbol)         // check if symbol
            {
                return(CompileVariable(x.AsSymbol, env, st));
            }

            if (x.IsAtom)           // check if it's not a list
            {
                return(CompileConstant(x, st));
            }

            // it's not an atom, it's a list, deal with it.
            VerifyExpression(Cons.IsList(x), "Non-list expression detected!");
            Cons   cons = x.AsConsOrNull;
            Symbol name = cons.first.AsSymbolOrNull;

            if (name == _quote)      // (quote value)
            {
                VerifyArgCount(cons, 1);
                return(CompileConstant(cons.second, st)); // second element is the constant
            }
            if (name == _begin)                           // (begin ...)
            {
                return(CompileBegin(cons.rest, env, st));
            }
            if (name == _set)        // (set! symbol-name value)
            {
                VerifyArgCount(cons, 2);
                VerifyExpression(cons.second.IsSymbol, "Invalid lvalue in set!, must be a symbol, got: ", cons.second);
                return(CompileVarSet(cons.second.AsSymbol, cons.third, env, st));
            }
            if (name == _if)         // (if pred then else) or (if pred then)
            {
                VerifyArgCount(cons, 2, 3);
                return(CompileIf(
                           cons.second,                                        // pred
                           cons.third,                                         // then
                           (cons.afterThird.IsNotNil ? cons.fourth : Val.NIL), // else
                           env, st));
            }
            if (name == _ifStar)     // (if *pred else)
            {
                VerifyArgCount(cons, 2);
                return(CompileIfStar(
                           cons.second, // pred
                           cons.third,  // else
                           env, st));
            }
            if (name == _while)      // (while pred body ...)
            {
                Cons body = cons.afterSecond.AsConsOrNull;
                return(CompileWhile(cons.second, body, env, st));
            }
            if (name == _lambda)     // (lambda (args...) body...)
            {
                if (st.IsUnused)
                {
                    return(null);    // it's not used, don't compile
                }
                else
                {
                    Cons    body = cons.afterSecond.AsConsOrNull;
                    Closure f    = CompileLambda(cons.second, body, env);
                    //string debug = $"#{f.code.index} : " + Val.DebugPrint(cons.afterSecond);
                    string debug = Val.DebugPrint(cons.afterSecond);
                    return(Merge(
                               Emit(Opcode.MAKE_CLOSURE, new Val(f), Val.NIL, debug),
                               EmitIf(st.IsFinal, Emit(Opcode.RETURN_VAL))));
                }
            }
            if (name == _defmacro)
            {
                return(CompileAndInstallMacroDefinition(cons.rest.AsConsOrNull, env, st));
            }

            return(CompileFunctionCall(cons.first, cons.rest.AsConsOrNull, env, st));
        }
示例#49
0
 public CompilationResults(Closure closure, List <CodeHandle> blocks)
 {
     this.closure = closure;
     this.recents = blocks;
 }
示例#50
0
 private static bool noLuaClosure(Closure f)
 {
     return(f == null || f.c.tt == LUA_TCCL);
 }
示例#51
0
        private static int auxgetinfo(lua_State L, CharPtr what, lua_Debug ar,
                                      Closure f, CallInfo ci)
        {
            int status = 1;

            for (; what[0] != 0; what = what.next())
            {
                switch (what[0])
                {
                case 'S': {
                    funcinfo(ar, f);
                    break;
                }

                case 'l': {
                    ar.currentline = (ci != null && isLua(ci) != 0) ? currentline(ci) : -1;
                    break;
                }

                case 'u': {
                    ar.nups = (f == null) ? (byte)0 : f.c.nupvalues;             //FIXME:(added)
                    if (noLuaClosure(f))
                    {
                        ar.isvararg = (char)1;
                        ar.nparams  = 0;
                    }
                    else
                    {
                        ar.isvararg = (char)(f.l.p.is_vararg);           //FIXME: added (char)
                        ar.nparams  = f.l.p.numparams;
                    }
                    break;
                }

                case 't': {
                    ar.istailcall = (ci != null) ? (char)(ci.callstatus & CIST_TAIL) : (char)0;             //FIXME: added (char)
                    break;
                }

                case 'n': {
                    /* calling function is a known Lua function? */
                    if (ci != null && (ci.callstatus & CIST_TAIL) == 0 && isLua(ci.previous) != 0)
                    {
                        ar.namewhat = getfuncname(L, ci.previous, ref ar.name);
                    }
                    else
                    {
                        ar.namewhat = null;
                    }
                    if (ar.namewhat == null)
                    {
                        ar.namewhat = "";            /* not found */
                        ar.name     = null;
                    }
                    break;
                }

                case 'L':
                case 'f':            /* handled by lua_getinfo */
                    break;

                default: status = 0;  break;          /* invalid option */
                }
            }
            return(status);
        }
示例#52
0
 /// <nodoc />
 internal StackEntry Initialize(Closure closure, ApplyExpression ambientCall, AbsolutePath path, LineInfo location, DebugInfo debugInfo)
 => Initialize(closure?.Function, closure?.Env, ambientCall, path, location, debugInfo);
示例#53
0
        public static void AddBuiltins(CodeContext cc, Type builtinstype)
        {
            BuiltinMethod.binder  = binder;
            BuiltinMethod.context = cc;

            Dictionary <string, List <MethodBase> > cpsfree = new Dictionary <string, List <MethodBase> >();
            Dictionary <string, bool> foldable = new Dictionary <string, bool>();

            foreach (MethodInfo mi in builtinstype.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Static))
            {
                foreach (BuiltinAttribute ba in mi.GetCustomAttributes(typeof(BuiltinAttribute), false))
                {
                    if (CheckParams(mi))
                    {
                        string            name = ba.Name ?? mi.Name.ToLower();
                        List <MethodBase> meths;

                        foldable[name] = ba.AllowConstantFold;

                        if (!cpsfree.TryGetValue(name, out meths))
                        {
                            cpsfree[name] = meths = new List <MethodBase>();
                        }
                        meths.Add(mi);
                    }
                    else
                    {
                        throw new NotSupportedException("all arguments must be of type object, method: " + mi);
                    }
                }
            }

            foreach (string mn in cpsfree.Keys)
            {
                object s           = SymbolTable.StringToObject(mn);
                var    targets     = cpsfree[mn].ToArray();
                var    paramcounts = new int[targets.Length];
                var    fold        = foldable[mn];

                if (AllIsSimple(targets, paramcounts))
                {
                    Callable c = null;
                    if (targets.Length == 1)
                    {
                        var dt = CallTargets.GetTargetType(false, paramcounts[0], false);
                        var d  = Delegate.CreateDelegate(dt, targets[0] as MethodInfo);
                        c = Closure.Create(d, paramcounts[0]);
                    }
                    else
                    {
                        var d = new Delegate[targets.Length];

                        for (int i = 0; i < d.Length; i++)
                        {
                            var dt = CallTargets.GetTargetType(false, paramcounts[i], false);
                            d[i] = Delegate.CreateDelegate(dt, targets[i] as MethodInfo);
                        }

                        c = Closure.CreateCase(d, paramcounts);
                    }
                    c.AllowConstantFold = fold;
                    cc.Scope.SetName((SymbolId)s, c);
                }
                else
                {
                    cc.Scope.SetName((SymbolId)s, new BuiltinMethod(mn, targets, fold));
                }
            }
        }
示例#54
0
 /// <summary>
 /// Duplicates a closure with a specific bound object and class scope.
 /// </summary>
 public static Closure bind(Closure closure, object newthis, string newscope = null) => closure.bindTo(newthis, newscope);
示例#55
0
文件: lgc.cs 项目: NLua/KopiLua
 private static void TraverseClosure(GlobalState g, Closure cl)
 {
     MarkObject(g, cl.c.env);
       if (cl.c.isC != 0) {
     int i;
     for (i=0; i<cl.c.nupvalues; i++)  /* mark its upvalues */
       MarkValue(g, cl.c.upvalue[i]);
       }
       else {
     int i;
     LuaAssert(cl.l.nupvalues == cl.l.p.nups);
     MarkObject(g, cl.l.p);
     for (i=0; i<cl.l.nupvalues; i++)  /* mark its upvalues */
       MarkObject(g, cl.l.upvals[i]);
       }
 }
示例#56
0
 /// <summary> Converts a set of instructions to a string </summary>
 public string DebugPrint(Closure cl, int indentLevel = 1) =>
 DebugPrint(cl.code, indentLevel);
示例#57
0
 internal static void setclvalue(lua_State L, TValue obj, Closure x)
 {
     obj.value.gc = x;
     obj.tt = LUA_TFUNCTION;
     checkliveness(G(L), obj);
 }
示例#58
0
        /// <summary>
        /// Load and run a string containing Lua script. May be run as a coroutine.
        /// <param name="luaString">The Lua code to be run.</param>
        /// <param name="friendlyName">A descriptive name to be used in error reports.</param>
        /// <param name="runAsCoroutine">Run the Lua code as a coroutine to support asynchronous operations.</param>
        /// <param name="onComplete">Method to callback when the Lua code finishes exection. Supports return parameters.</param>
        /// </summary>
        public virtual void DoLuaString(string luaString, string friendlyName, bool runAsCoroutine, Action <DynValue> onComplete = null)
        {
            Closure fn = LoadLuaString(luaString, friendlyName);

            RunLuaFunction(fn, runAsCoroutine, onComplete);
        }
示例#59
0
		/// <summary>
		/// Creates a closure from a bytecode address.
		/// </summary>
		/// <param name="address">The address.</param>
		/// <param name="envTable">The env table to create a 0-upvalue</param>
		/// <returns></returns>
		private DynValue MakeClosure(int address, Table envTable = null)
		{
			this.CheckScriptOwnership(envTable);
			Closure c;

			if (envTable == null)
				c = new Closure(this, address, new SymbolRef[0], new DynValue[0]);
			else
			{
				var syms = new SymbolRef[1] {
					new SymbolRef() { i_Env = null, i_Index= 0, i_Name = WellKnownSymbols.ENV, i_Type =  SymbolRefType.DefaultEnv },
				};

				var vals = new DynValue[1] {
					DynValue.NewTable(envTable)
				};

				c = new Closure(this, address, syms, vals);
			}

			return DynValue.NewClosure(c);
		}
示例#60
0
        public bool AddOption(string text, bool interactable, ILuaEnvironment luaEnv, Closure callBack)
        {
            if (!gameObject.activeSelf)
            {
                gameObject.SetActive(true);
            }

            bool addedOption = false;

            foreach (Button button in CachedButtons)
            {
                if (!button.gameObject.activeSelf)
                {
                    button.gameObject.SetActive(true);

                    button.interactable = interactable;

                    Text textComponent = button.GetComponentInChildren <Text>();
                    if (textComponent != null)
                    {
                        textComponent.text = text;
                    }

                    button.onClick.AddListener(delegate {
                        StopAllCoroutines(); // Stop timeout
                        Clear();
                        HideSayDialog();

                        if (callBack != null)
                        {
                            luaEnv.RunLuaFunction(callBack, true);
                        }
                    });

                    addedOption = true;
                    break;
                }
            }

            return(addedOption);
        }