Ejemplo n.º 1
0
        public void Register(string name, ICallable <R> callable, params string[] domains)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException("name");
            }

            if (callable == null)
            {
                throw new ArgumentNullException("callable");
            }

            if (domains == null)
            {
                throw new ArgumentNullException("domains");
            }

            foreach (string domain in domains)
            {
                if (_recs.ContainsKey(domain))
                {
                    _recs[domain][name] = callable;
                }
                else
                {
                    _recs[domain] = new Dictionary <string, ICallable <R> >
                    {
                        { name, callable }
                    };
                }
            }
        }
Ejemplo n.º 2
0
        public object Invoke(ICallable method, object[] parameters)
        {
            if (this.host == null)
                this.host = Machine.Current.GetHost(this.HostId);

            return this.host.Invoke(this, method, parameters);
        }
Ejemplo n.º 3
0
 public AppJsObject(IronJS.Environment env, ICallable app)
     : base(env, env.NewObject())
 {
     Put("call",
         IronJS.Native.Utils.CreateFunction <Func <BoxedValue, CommonObject> >(env, 1,
                                                                               environ => ConvertArrayToObject(env, app.Call(CreateDictionary(environ.Object as EnvironmentJsObject)))));
 }
Ejemplo n.º 4
0
		private void BlockTag(string tag, IDictionary attributes, ICallable block)
		{
			Output.Write("<{0}", tag);

			System.Collections.Generic.List<string> attributeValues = new System.Collections.Generic.List<string>();

			if (null != attributes)
			{
				foreach(DictionaryEntry entry in attributes)
				{
					attributeValues.Add(string.Format("{0}=\"{1}\"", entry.Key, entry.Value));
				}
			}

			if (0 != attributeValues.Count)
			{
				Output.Write(" ");
				Output.Write(string.Join(" ", attributeValues.ToArray()));
			}

			Output.Write(">");
			if (block != null)
			{
				block.Call(null);
			}
			Output.Write("</{0}>", tag);
		}
 public void OnOperationEnd(ICallable operation, IApplyData values)
 {
     if (!DisableBorrowing)
     {
         curFrame = operationStack.Pop();
     }
 }
Ejemplo n.º 6
0
        public object Invoke(IObject obj, ICallable method, params object[] arguments)
        {
            Machine current = Machine.Current;

            try
            {
                this.machine.SetCurrent();

                if (obj is ObjectProxy)
                {
                    ObjectProxy proxy = (ObjectProxy)obj;

                    if (proxy.HostId != this.Id)
                    {
                        throw new NotSupportedException();
                    }

                    return(this.Invoke(proxy.ObjectId, method, arguments));
                }

                return(obj.Invoke(method, arguments));
            }
            finally
            {
                Machine.SetCurrent(current);
            }
        }
Ejemplo n.º 7
0
 public virtual void OnOperationStart(ICallable _, IApplyData values)
 {
     if (!DisableBorrowing)
     {
         operationStack.Push(new StackFrame(values));
     }
 }
Ejemplo n.º 8
0
 public virtual void OnOperationEnd(ICallable _, IApplyData values)
 {
     if (!DisableBorrowing)
     {
         operationStack.Pop();
     }
 }
Ejemplo n.º 9
0
        public void OnOperationEndHandler(ICallable operation, IApplyData result)
        {
            if (this.operations.Count <= 1)
            {
                return;
            }
            if (!this.operations.TryPop(out var currentOperation) || currentOperation == null)
            {
                return;
            }
            if (!this.operations.TryPeek(out var parentOp) || parentOp == null)
            {
                return;
            }

            // CNOTs are Controlled X under the hood, so we don't need to render the nested CNOT
            if ((currentOperation.Gate == "X" && currentOperation.IsControlled) &&
                (parentOp.Gate == "X" && parentOp.IsControlled))
            {
                return;
            }

            // Add operation to parent operation's children
            parentOp.Children = (parentOp.Children ?? ImmutableList <Operation> .Empty).Add(currentOperation);

            // Add target qubits to parent
            parentOp.Targets = parentOp.Targets
                               .Concat(currentOperation.Targets.Where(reg => reg is QubitRegister))
                               .Distinct();
        }
Ejemplo n.º 10
0
        public object VisitCallExpr(Expr.Call expr)
        {
            object callee = Evaluate(expr.Callee);

            List <object> arguments = new List <object>();

            foreach (var argument in expr.Arguments)
            {
                arguments.Add(Evaluate(argument));
            }

            if (!(callee is ICallable))
            {
                throw new InterpretingException(expr.Paren,
                                                "Can only call functions and classes.");
            }

            ICallable function = (ICallable)callee;

            if (arguments.Count != function.Arity)
            {
                throw new InterpretingException(expr.Paren,
                                                $"Expected {function.Arity} arguments but got {arguments.Count}.");
            }
            return(function.Call(this, arguments));
        }
Ejemplo n.º 11
0
 public CallableAsEvaluable(ICallable callable, object value, IContinuation succ, IFailure fail)
 {
     this.callable = callable;
     this.value = value;
     this.succ = succ;
     this.fail = fail;
 }
Ejemplo n.º 12
0
        public virtual object Invoke(string name, object[] parameters)
        {
            object value = this.GetValue(name);

            if (value == null && this.IsNativeMethod(name))
            {
                return(ObjectUtilities.GetNativeValue(this, name, parameters));
            }

            if (value == null)
            {
                throw new InvalidOperationException(string.Format("Unknown member '{0}'", name));
            }

            if (!(value is ICallable))
            {
                if (parameters == null)
                {
                    return(value);
                }

                throw new InvalidOperationException(string.Format("'{0}' is not a method", name));
            }

            ICallable method = (ICallable)value;

            IBindingEnvironment objenv = new ObjectEnvironment(this, method.Environment);

            return(method.Invoke(objenv, parameters));
        }
Ejemplo n.º 13
0
        public static object Partition(object proc, object list)
        {
            ICallable p = RequiresNotNull <ICallable>(proc);
            Cons      e = Requires <Runtime.Cons>(list);
            Cons      h = null, head = null;
            Cons      h2 = null, head2 = null;

            while (e != null)
            {
                if (IsTrue(p.Call(e.car)))
                {
                    if (h == null)
                    {
                        h = head = new Cons(e.car);
                    }
                    else
                    {
                        h = (Cons)(h.cdr = new Cons(e.car));
                    }
                }
                else
                {
                    if (h2 == null)
                    {
                        h2 = head2 = new Cons(e.car);
                    }
                    else
                    {
                        h2 = (Cons)(h2.cdr = new Cons(e.car));
                    }
                }
                e = e.cdr as Cons;
            }
            return(Values(head, head2));
        }
 private void Start(ICallable <object> task, int numInstances)
 {
     for (int i = 0; i < numInstances; i++)
     {
         Start(task);
     }
 }
Ejemplo n.º 15
0
 private object EvalFunction(ICallable callee, object[] args)
 {
     if (callee is IntrinsicFunction)
     {
         IntrinsicFunction ifun   = (IntrinsicFunction)callee;
         MethodBase        mmodel = ifun.MethodModel;
         if (mmodel != null)
         {
             if (mmodel.IsStatic)
             {
                 return(mmodel.ConvertArgumentsAndInvoke(null, args));
             }
             else
             {
                 object[] eargs = new object[args.Length - 1];
                 Array.Copy(args, 1, eargs, 0, eargs.Length);
                 return(mmodel.ConvertArgumentsAndInvoke(args[0], eargs));
             }
         }
         else
         {
             throw new NotImplementedException();
         }
     }
     else if (callee is MSILFunctionRef)
     {
         MSILFunctionRef mfr = (MSILFunctionRef)callee;
         return(InterpreteInternal(mfr.Method, args));
     }
     else
     {
         throw new NotImplementedException();
     }
 }
Ejemplo n.º 16
0
        public static object GroupBy(object proc, object list)
        {
            ICallable p      = RequiresNotNull <ICallable>(proc);
            Cons      e      = Requires <Runtime.Cons>(list);
            Hashtable result = new Hashtable();

            while (e != null)
            {
                object key = p.Call(e.car);

                object c = result[key];
                result[key] = new Cons(e.car, c);

                e = e.cdr as Cons;
            }

            Hashtable final = new Hashtable(result.Count);

            //now reverse the values
            foreach (DictionaryEntry de in result)
            {
                final[de.Key] = Reverse(de.Value);
            }

            return(final);
        }
Ejemplo n.º 17
0
        public void RecursionFail1Test()
        {
            ToffoliSimulator sim = new ToffoliSimulator();

            {
                StackTraceCollector sc = new StackTraceCollector(sim);
                ICallable           op = sim.Get <ICallable, RecursionFail1>();
                try
                {
                    QVoid res = op.Apply <QVoid>(QVoid.Instance);
                }
                catch (ExecutionFailException)
                {
                    StackFrame[] stackFrames = sc.CallStack;

                    Assert.Equal(4, stackFrames.Length);

                    Assert.Equal(namespacePrefix + "RecursionFail", stackFrames[0].Callable.FullName);
                    Assert.Equal(namespacePrefix + "RecursionFail", stackFrames[1].Callable.FullName);
                    Assert.Equal(namespacePrefix + "RecursionFail", stackFrames[2].Callable.FullName);
                    Assert.Equal(namespacePrefix + "RecursionFail1", stackFrames[3].Callable.FullName);

                    Assert.Equal(OperationFunctor.Body, stackFrames[0].Callable.Variant);
                    Assert.Equal(OperationFunctor.Body, stackFrames[1].Callable.Variant);
                    Assert.Equal(OperationFunctor.Body, stackFrames[2].Callable.Variant);
                    Assert.Equal(OperationFunctor.Body, stackFrames[3].Callable.Variant);

                    Assert.Equal(70, stackFrames[0].FailedLineNumber);
                    Assert.Equal(66, stackFrames[1].FailedLineNumber);
                    Assert.Equal(66, stackFrames[2].FailedLineNumber);
                    Assert.Equal(75, stackFrames[3].FailedLineNumber);
                }
            }
        }
Ejemplo n.º 18
0
        public ICallable Instantiate(BindingContext context, IEnumerable <IBoundDecl> typeArgs,
                                     IBoundDecl argType)
        {
            bool dummy;

            Struct.BuildContext(context,
                                ParameterType, argType, ref typeArgs, out dummy);

            // bail if we couldn't get the right number of type arguments
            if ((typeArgs == null) || (Struct.TypeParameters.Count != typeArgs.Count()))
            {
                return(null);
            }

            // instantiate the structure
            var structure = Struct.Instantiate(context.Compiler, typeArgs);

            // now build the auto functions for it
            ICallable instantiated = null;

            foreach (ICallable function in structure.BuildFunctions())
            {
                // add to the symbol table so they are only instantiated once
                context.Compiler.Functions.Add(function);

                if ((Name == function.Name) && function.GetType().Equals(FunctionType))
                {
                    instantiated = function;
                }
            }

            return(instantiated);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Called by Unity.
        /// </summary>
        protected virtual void Awake()
        {
            try
            {
                _host.Execute(Script.String());
            }
            catch (Exception exception)
            {
                Debug.LogWarning("Could not execute script: " + exception.Message);

                return;
            }

            _this = JsValue.FromObject(_host, this);

            _update      = _host.GetFunction("Update");
            _fixedUpdate = _host.GetFunction("FixedUpdate");
            _lateUpdate  = _host.GetFunction("LateUpdate");
            _awake       = _host.GetFunction("Awake");
            _start       = _host.GetFunction("Start");
            _onEnable    = _host.GetFunction("OnEnable");
            _onDisable   = _host.GetFunction("OnDisable");
            _onDestroy   = _host.GetFunction("OnDestroy");

            if (null != _awake)
            {
                _awake.Call(_this, null);
            }
        }
Ejemplo n.º 20
0
 public override TResult Call <TResult>(ICallable <TResult> callable)
 {
     lock (Mutex)
     {
         return(callable.Call());
     }
 }
Ejemplo n.º 21
0
        public object Visit(Call expr)
        {
            object callee = Evaluate(expr.callee);

            List <object> arguments = new List <object>();

            foreach (Expr argument in expr.arguments)
            {
                arguments.Add(Evaluate(argument));
            }

            if (!(callee is ICallable))
            {
                throw new ErrorHandler.RuntimeError(expr.paren, "Can't call this datatype: " + (callee == null ? "null" : callee.ToString()));
            }

            ICallable called = (ICallable)callee;

            if (arguments.Count != called.Arity())
            {
                throw new ErrorHandler.RuntimeError(expr.paren, "Expected " + called.Arity() + " arguments but received " + arguments.Count);
            }

            return(called.Call(this, expr.paren, arguments));
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Callback to notify tracer that an operation execution has ended.
        /// Passes callBack down to metricsCalculator and runtimeChecker.
        /// </summary>
        public void OnOperationEnd(ICallable operation, IApplyData resultValue)
        {
            qubitManager.OnOperationEnd(operation, resultValue);
            if (listeners.Length > 0 && callStackDepth <= callStackDepthLimit)
            {
                if (tracingDataInQubitsIsNeeded)
                {
                    var        qubits      = new List <Qubit>(resultValue?.Qubits?.Where(q => q != null) ?? Qubit.NO_QUBITS);
                    object[][] tracingData = GetTracingData(qubits);
                    for (int i = 0; i < listeners.Length; ++i)
                    {
                        listeners[i].OnOperationEnd(tracingData[i]);
                    }
                }
                else
                {
                    for (int i = 0; i < listeners.Length; ++i)
                    {
                        listeners[i].OnOperationEnd(null);
                    }
                }
            }

            callStackDepth -= 1;
        }
Ejemplo n.º 23
0
        static void Main(string[] args)
        {
            System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew();

            ICallable <string> doHello       = Table.GetCallable("foo", "hello");
            ICallable <string> doHelloPerson = Table.GetCallable("foo", "person");
            ICallable <int>    doThree       = IntTable.GetCallable("bar", "three");

            Console.WriteLine(doHello.InvokeWithArgs().ToString());
            Console.WriteLine(doThree.InvokeWithArgs().ToString());

            Console.WriteLine(doHelloPerson.InvokeWithArgs("Bob").ToString());

            ICallable <int> addition = IntTable.GetCallable("math", "add");

            Console.WriteLine(addition.InvokeWithArgs(3, 3));

            sw.Stop();

            Console.WriteLine(sw.ElapsedMilliseconds);
            Console.WriteLine();

            sw.Reset();
            sw.Start();

            Console.WriteLine(Table.TableInfo.ToList());
            Console.WriteLine(IntTable.TableInfo.ToList());

            sw.Stop();

            Console.WriteLine(sw.ElapsedMilliseconds);

            Console.ReadKey();
        }
        /// <summary>
        /// Callback method for the OnOperationStart event.
        /// </summary>
        public void CountOperationCalls(ICallable op, IApplyData data)
        {
            // Count all operations, grouped by operation
            if (_operationsCount.ContainsKey(op))
            {
                _operationsCount[op]++;
            }
            else
            {
                _operationsCount[op] = 1;
            }

            // Check if the operation has multiple qubit parameters, if yes, count it
            int nQubits = 0;

            using (IEnumerator <Qubit> enumerator = data?.Qubits?.GetEnumerator())
            {
                if (enumerator is null)
                {
                    // The operation doesn't have qubit parameters
                    return;
                }
                while (enumerator.MoveNext() && nQubits < 2)
                {
                    nQubits++;
                }
            }
            if (nQubits >= 2)
            {
                _multiQubitOperations++;
            }
        }
Ejemplo n.º 25
0
        /**
         * Convenience utility: creates a "session fail" retry loop calling the given proc
         *
         * @param client Zookeeper
         * @param mode how to handle session failures
         * @param proc procedure to call with retry
         * @param <T> return type
         * @return procedure result
         * @throws Exception any non-retriable errors
         */
        public static T callWithRetry <T>(CuratorZookeeperClient client, Mode mode, ICallable <T> proc)
        {
            T result = default(T);
            SessionFailRetryLoop retryLoop = client.newSessionFailRetryLoop(mode);

            retryLoop.start();
            try
            {
                while (retryLoop.shouldContinue())
                {
                    try
                    {
                        result = proc.call();
                    }
                    catch (Exception e)
                    {
                        ThreadUtils.checkInterrupted(e);
                        retryLoop.takeException(e);
                    }
                }
            }
            finally
            {
                retryLoop.Dispose();
            }
            return(result);
        }
Ejemplo n.º 26
0
        public Task <T> Submit(ICallable <T> task)
        {
            var t = factory.StartNew(task.Call);

            taskQueue.Enqueue(t);
            return(t);
        }
Ejemplo n.º 27
0
        private static QVoid ExecuteConditionalStatementInternal(QuantumProcessorDispatcher Simulator,
                                                                 long statement,
                                                                 ICallable onEqualOp,
                                                                 ICallable onNonEqualOp,
                                                                 OperationFunctor type,
                                                                 IQArray <Qubit>?ctrls)
        {
            bool run;

            run = Simulator.QuantumProcessor.RunThenClause(statement);
            while (run)
            {
                RunClause(onEqualOp, type, ctrls);
                run = Simulator.QuantumProcessor.RepeatThenClause(statement);
            }

            run = Simulator.QuantumProcessor.RunElseClause(statement);
            while (run)
            {
                RunClause(onNonEqualOp, type, ctrls);
                run = Simulator.QuantumProcessor.RepeatElseClause(statement);
            }

            Simulator.QuantumProcessor.EndConditionalStatement(statement);

            return(QVoid.Instance);
        }
Ejemplo n.º 28
0
 /// <summary>提交一个线程等待执行
 /// </summary>
 /// <param name="callable">The callable.</param>
 /// <param name="state">The state.</param>
 public static void Submit(ICallable callable, object state)
 {
     if (!callable.IsRunning)
     {
         ThreadPool.QueueUserWorkItem(new WaitCallback(callable.Call), state);
     }
 }
Ejemplo n.º 29
0
        object Expr.IVisitor <object> .Visit(Expr.Call _call)
        {
            object callee = Evaluate(_call.callee);

            List <object> arguments = new List <object>();

            foreach (Expr argument in _call.arguments)
            {
                arguments.Add(Evaluate(argument));
            }

            if (!(callee is ICallable))
            {
                throw new RuntimeError(_call.paren, "Can only call functions and classes.");
            }

            ICallable function = (ICallable)callee;

            if (arguments.Count != function.Arity)
            {
                throw new RuntimeError(_call.paren, "Expected " + function.Arity + " arguments, but got " + arguments.Count + ".");
            }



            return(function.Call(this, arguments));
        }
Ejemplo n.º 30
0
        /**
         * Removes and signals all waiting threads, invokes done(), and
         * nulls out callable.
         */
        private void finishCompletion()
        {
            // assert state > COMPLETING;
            for (WaitNode q; (q = waiters) != null;)
            {
                if (Interlocked.CompareExchange(ref waiters, null, q) == q)
                {
                    for (;;)
                    {
                        Thread t = q.Thread;
                        if (t != null)
                        {
                            q.Thread = null;
                        }
                        WaitNode next = q.Next;
                        if (next == null)
                        {
                            break;
                        }
                        q.Next = null; // unlink to help gc
                        q      = next;
                    }
                    break;
                }
            }

            done();

            callable = null;        // to reduce footprint
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Gets the reference of the designator if it covers the position given
        /// </summary>
        /// <param name="designator"></param>
        protected override void VisitDesignator(Designator designator)
        {
            if (ShouldCheck(designator))
            {
                Type type = designator.Ref as Type;
                if (Context == null && type != null)
                {
                    Context = type;
                }

                ITypedElement element = designator.Ref as ITypedElement;
                if (Context == null && element != null)
                {
                    Context = element;
                }

                ICallable callable = designator.Ref as ICallable;
                if (Context == null && callable != null)
                {
                    Context = callable;
                }

                NameSpace nameSpace = designator.Ref as NameSpace;
                if (Context == null && nameSpace != null)
                {
                    Context = nameSpace;
                }
            }
        }
Ejemplo n.º 32
0
 /// <summary>提交一个线程等待执行
 ///     <remark>abu 2008-03-07 </remark>
 /// </summary>
 /// <param name="callable">The callable.</param>
 /// <param name="state">The state.</param>
 public static void Submit(ICallable callable, object state)
 {
     if (!callable.IsRunning)
     {
         ThreadPool.QueueUserWorkItem(new WaitCallback(callable.Call), state);
     }
 }
Ejemplo n.º 33
0
        /// <summary>
        /// Callback to notify tracer that an operation execution has started.
        /// Passes callBack down to metricsCalculator and runtimeChecker.
        /// </summary>
        public void OnOperationStart(ICallable operation, IApplyData inputValue)
        {
            callStackDepth += 1;
            qubitManager.OnOperationStart(operation, inputValue);

            if (listeners.Length > 0 && callStackDepth <= callStackDepthLimit)
            {
                HashedString hashedOperationName = new HashedString(operation.FullName);
                if (tracingDataInQubitsIsNeeded)
                {
                    var        qubits      = new List <Qubit>(inputValue?.Qubits?.Where(q => q != null) ?? Qubit.NO_QUBITS);
                    object[][] tracingData = GetTracingData(qubits);
                    for (int i = 0; i < listeners.Length; ++i)
                    {
                        listeners[i].OnOperationStart(hashedOperationName, operation.Variant, listenerNeedsTracingData[i] ? tracingData[i] : null);
                    }
                }
                else
                {
                    for (int i = 0; i < listeners.Length; ++i)
                    {
                        listeners[i].OnOperationStart(hashedOperationName, operation.Variant, null);
                    }
                }
            }
        }
Ejemplo n.º 34
0
        public object VisitCallExpr(Expr.Call expr)
        {
            object callee = Evaluate(expr.callee);

            List <object> arguments = new List <object>();

            foreach (Expr argument in expr.arguments)
            {
                arguments.Add(Evaluate(argument));
            }

            if (!(callee is ICallable))
            {
                throw new RuntimeError(expr.paren,
                                       "Can only call functions and classes.");
            }

            ICallable function = (ICallable)callee;

            if (arguments.Count != function.Arity())
            {
                throw new RuntimeError(expr.paren, "Expected " +
                                       function.Arity() + " arguments but got " +
                                       arguments.Count + ".");
            }

            return(function.Call(this, arguments));
        }
 public int Call(ICallable callable, double salience, object value, IContinuation succ, IFailure fail)
 {
     if (callable is IAgent)
         ((IAgent)callable).Initialize(this, salience);
     if (salience > 0)
         return callable.Call(value, succ, fail);
     return 1;
 }
		/// <summary>
		/// Initializes a new instance of the <see cref="BrailViewComponentContext"/> class.
		/// </summary>
		/// <param name="parent">The parent.</param>
		/// <param name="body">The body.</param>
		/// <param name="name">The name.</param>
		/// <param name="text">The text.</param>
		/// <param name="parameters">The parameters.</param>
		public BrailViewComponentContext(BrailBase parent, ICallable body,
										 string name, TextWriter text, IDictionary parameters)
		{
			this.parent = parent;
			this.body = body;
			componentName = name;
			default_writer = text;
			componentParameters = parameters;
		}
		/// <summary>
		/// Initializes a new instance of the <see cref="BrailViewComponentContext"/> class.
		/// </summary>
		/// <param name="parent">The parent.</param>
		/// <param name="body">The body.</param>
		/// <param name="name">The name.</param>
		/// <param name="text">The text.</param>
		/// <param name="parameters">The parameters.</param>
		public BrailViewComponentContext(BrailBase parent, ICallable body,
		                                 string name, TextWriter text, IDictionary parameters)
		{
			this.parent = parent;
			this.body = body;
			componentName = name;
			default_writer = text;
			componentParameters = IgnoreNull.ReplaceIgnoreNullsWithTargets(parameters);
		}
Ejemplo n.º 38
0
		public AbstractInvocation( ICallable callable, object proxy, MethodInfo method, object newtarget )
		{
			this.callable = callable;
			this.proxy = proxy;

			this.target = callable.Target;
			
			if (newtarget != null)
			{
				this.target = newtarget;
			}

			this.method = method;
		}
Ejemplo n.º 39
0
        public Iterator(IEnvironment environment, IDynamic iterable)
        {
            _environment = environment;

            var o = iterable.ConvertToObject();
            var createIterator = o.Get("createIterator") as ICallable;
            if (createIterator == null)
                throw environment.CreateTypeError("The object supplied does not contain a callable property named 'createIterator'.");
            _iterator = createIterator.Call(environment, iterable, environment.EmptyArgs).ConvertToObject();
            if (!_iterator.HasProperty("current"))
                throw environment.CreateTypeError("The object returned from the iterable supplied does not have a property named 'current'.");
            _next = _iterator.Get("next") as ICallable;
            if (_next == null)
                throw environment.CreateTypeError("The object returned from the iterable supplied does not have a callable property named 'next'.");
        }
Ejemplo n.º 40
0
        public static object CallResult(ICallable callable, object value, int maxtime, double exitscore)
        {
            QueueArena arena = new QueueArena();
            BestContinuation getbest = new BestContinuation();
            LastFailure getlast = new LastFailure();

            arena.Call(callable, 100.0, value, getbest.GetContinue(), getlast.GetFail());

            while (maxtime > 0 && getbest.Salience <= exitscore && !arena.IsEmpty)
                maxtime -= arena.EvaluateOne();

            if (getbest.Value == null && getlast.Reason != null)
                return new Exception(getlast.Reason);

            return getbest.Value;
        }
Ejemplo n.º 41
0
        /// <summary>
        /// Adds the given function to the symbol table.
        /// </summary>
        public void Add(ICallable callable)
        {
            // match against the unique name
            var uniqueName = callable.UniqueName();

            //### bob: if we want users to be able to override intrinsics, we may need to handle this differently
            if (mCallables.ContainsKey(uniqueName)) throw new CompileException("A function named " + uniqueName + " has already been declared.");

            mCallables.Add(uniqueName, callable);

            // if there is an inferrable name, also include the name without the type arguments
            if (callable.HasInferrableTypeArguments)
            {
                mCallables.Add(callable.UniqueInferredName(), callable);
            }
        }
Ejemplo n.º 42
0
        private void BlockTag(string tag, IDictionary attributes, ICallable block)
        {
            writer.WriteStartElement(tag);

            if (null != attributes)
            {
                foreach(DictionaryEntry entry in attributes)
                {
                    writer.WriteAttributeString((string) entry.Key, (string) entry.Value);
                }
            }

            if (block != null)
            {
                block.Call(null);
            }
            writer.WriteEndElement();
        }
Ejemplo n.º 43
0
        /// <summary>
        /// Creates the association between parameter (from the called ICallable) and its associated expression
        /// </summary>
        /// <param name="callable"></param>
        /// <returns></returns>
        private Dictionary<Parameter, Expression> createParameterAssociation(ICallable callable)
        {
            Dictionary<Parameter, Expression> retVal = null;

            if (callable != null)
            {
                if (callable.FormalParameters.Count == NamedActualParameters.Count + ActualParameters.Count)
                {
                    retVal = new Dictionary<Parameter, Expression>();

                    int i = 0;
                    foreach (Expression expression in ActualParameters)
                    {
                        Parameter parameter = callable.FormalParameters[i] as Parameter;
                        retVal.Add(parameter, expression);
                        i = i + 1;
                    }

                    foreach (KeyValuePair<string, Expression> pair in NamedActualParameters)
                    {
                        Parameter parameter = callable.getFormalParameter(pair.Key);
                        if (parameter != null)
                        {
                            retVal.Add(parameter, pair.Value);
                        }
                    }
                }
            }

            return retVal;
        }
Ejemplo n.º 44
0
        public static IEnumerable map(object enumerable, ICallable function)
        {
            if (null == enumerable) throw new ArgumentNullException("enumerable");
            if (null == function) throw new ArgumentNullException("function");

            object[] args = new object[1];
            foreach (object item in iterator(enumerable))
            {
                args[0] = item;
                yield return function.Call(args);
            }
        }
Ejemplo n.º 45
0
        /// <summary>
        /// Provides the parameter association according to the icallable provided.
        /// If the call is statically determined, take the cached association
        /// </summary>
        /// <param name="callable"></param>
        /// <returns></returns>
        private Dictionary<Parameter, Expression> getParameterAssociation(ICallable callable)
        {
            Dictionary<Parameter, Expression> retVal = ParameterAssociation;

            if (retVal == null)
            {
                retVal = createParameterAssociation(callable);
            }

            return retVal;
        }
Ejemplo n.º 46
0
 public HFilterIterable(IEnvironment environment, IObject iterable, ICallable predicate)
     : base(environment)
 {
     _iterable = iterable;
     _predicate = predicate;
 }
Ejemplo n.º 47
0
 public virtual void DefineGetter (string name, ICallable getter)
 {
     Slot slot = GetSlot (name, name.GetHashCode ());
     if (slot == null) {
         slot = new Slot ();
         AddSlot (name, name.GetHashCode (), slot);
     }
     slot.getter = getter;
 }
Ejemplo n.º 48
0
 public virtual object Invoke(ICallable method, object[] parameters)
 {
     return method.Invoke(null, this, parameters);
 }
Ejemplo n.º 49
0
        private bool TryFind(string name, IEnumerable<IBoundDecl> typeArguments, IBoundDecl paramType, out ICallable bound)
        {
            string uniqueName = Callable.UniqueName(name, typeArguments, paramType);

            // look up by unique name
            if (mCallables.TryGetValue(uniqueName, out bound)) return true;

            // wasn't found
            return false;
        }
Ejemplo n.º 50
0
        /// <summary> Call {@link
        /// Callable#call(Context cx, Scriptable scope, Scriptable thisObj,
        /// Object[] args)}
        /// using the Context instance associated with the current thread.
        /// If no Context is associated with the thread, then
        /// {@link ContextFactory#makeContext()} will be called to construct
        /// new Context instance. The instance will be temporary associated
        /// with the thread during call to {@link ContextAction#run(Context)}.
        /// <p>
        /// It is allowed to use null for <tt>factory</tt> argument
        /// in which case the factory associated with the scope will be
        /// used to create new context instances.
        /// 
        /// </summary>
        public static object Call(ContextFactory factory, ICallable callable, IScriptable scope, IScriptable thisObj, object [] args)
        {
            if (factory == null) {
                factory = ContextFactory.Global;
            }

            Context cx = CurrentContext;
            if (cx != null) {
                object result;
                if (cx.factory != null) {
                    result = callable.Call (cx, scope, thisObj, args);
                }
                else {
                    // Context was associated with the thread via Context.enter,
                    // set factory to make Context.enter/exit to be no-op
                    // during call
                    cx.factory = factory;
                    try {
                        result = callable.Call (cx, scope, thisObj, args);
                    }
                    finally {
                        cx.factory = null;
                    }
                }
                return result;
            }

            cx = PrepareNewContext (AppDomain.CurrentDomain, factory);
            try {
                return callable.Call (cx, scope, thisObj, args);
            }
            finally {
                ReleaseContext (cx);
            }
        }
Ejemplo n.º 51
0
        void ArgumentList(AST parent, ICallable list)
        {
            bool matched;
            ts.allow_reg_exp = true;
            matched = ts.MatchToken (Token.RP);
            ts.allow_reg_exp = false;

            if (!matched) {
                bool first = true;
                do {
                    if (!first)
                        decompiler.AddToken (Token.COMMA);
                    first = false;
                    list.AddArg (AssignExpr (parent, false));
                } while (ts.MatchToken (Token.COMMA));
                MustMatchToken (Token.RP, "msg.no.paren.arg");
            }
            decompiler.AddToken (Token.RP);
        }
Ejemplo n.º 52
0
 public void Tag(string name, ICallable block)
 {
     BlockTag(name, null, block);
 }
Ejemplo n.º 53
0
        /// <summary>
        /// Creates the parameter value associationg according to actual parameters
        /// </summary>
        /// <param name="context">The interpretation context</param>
        /// <param name="callable">The callable</param>
        /// <param name="log">Indicates whether errors should be logged</param>
        /// <returns></returns>
        public Dictionary<Variables.Actual, Values.IValue> AssignParameterValues(InterpretationContext context, ICallable callable, bool log)
        {
            // Compute the unnamed actual parameter values
            Dictionary<Variables.Actual, Values.IValue> retVal = new Dictionary<Variables.Actual, Values.IValue>();

            if (callable.FormalParameters.Count == NamedActualParameters.Count + ActualParameters.Count)
            {
                int i = 0;
                foreach (Expression expression in ActualParameters)
                {
                    Parameter parameter = callable.FormalParameters[i] as Parameter;
                    Values.IValue val = expression.GetValue(context);
                    if (val != null)
                    {
                        Variables.Actual actual = parameter.createActual();
                        val = val.RightSide(actual, false);
                        retVal.Add(actual, val);
                    }
                    else
                    {
                        AddError("Cannot evaluate value for parameter " + i + " (" + expression.ToString() + ") of function " + callable.Name);
                        return new Dictionary<Variables.Actual, Values.IValue>();
                    }
                    i = i + 1;
                }

                foreach (KeyValuePair<string, Expression> pair in NamedActualParameters)
                {
                    Parameter parameter = callable.getFormalParameter(pair.Key);
                    Values.IValue val = pair.Value.GetValue(context);
                    if (val != null)
                    {
                        Variables.Actual actual = parameter.createActual();
                        val = val.RightSide(actual, false);
                        actual.Value = val;
                        retVal.Add(actual, val);
                    }
                    else
                    {
                        AddError("Cannot evaluate value for parameter " + pair.Key + " of function " + callable.Name);
                        return new Dictionary<Variables.Actual, Values.IValue>();
                    }
                }
            }

            return retVal;
        }
		public void RegisterSection(string name, ICallable section)
		{
			if (sections == null)
			{
				sections = new Hashtable(StringComparer.InvariantCultureIgnoreCase);
			}
			sections[name] = section;
		}
Ejemplo n.º 55
0
        public static object DoTopCall(ICallable callable, Context cx, IScriptable scope, IScriptable thisObj, object [] args)
        {
            if (scope == null)
                throw new ArgumentException ();
            if (cx.topCallScope != null)
                throw new ApplicationException ();

            object result;
            cx.topCallScope = ScriptableObject.GetTopLevelScope (scope);
            cx.useDynamicScope = cx.HasFeature (Context.Features.DynamicScope);
            ContextFactory f = cx.Factory;
            try {
                result = f.DoTopCall (callable, cx, scope, thisObj, args);
            }
            finally {
                cx.topCallScope = null;
                // Cleanup cached references
                cx.cachedXMLLib = null;

                if (cx.currentActivationCall != null) {
                    // Function should always call exitActivationFunction
                    // if it creates activation record
                    throw new ApplicationException (
                        "ActivationCall without exitActivationFunction() invokation."
                    );
                }
            }
            return result;
        }
 /// <summary> Call {@link
 /// Callable#call(Context cx, Scriptable scope, Scriptable thisObj,
 /// Object[] args)}
 /// of <i>callable</i> under restricted security domain where an action is
 /// allowed only if it is allowed according to the Java stack on the
 /// moment of the <i>execWithDomain</i> call and <i>securityDomain</i>.
 /// Any call to {@link #getDynamicSecurityDomain(Object)} during
 /// execution of <tt>callable.call(cx, scope, thisObj, args)</tt>
 /// should return a domain incorporate restrictions imposed by
 /// <i>securityDomain</i> and Java stack on the moment of callWithDomain
 /// invocation.
 /// <p>
 /// </summary>
 public abstract object callWithDomain (object securityDomain, Context cx, ICallable callable, IScriptable scope, IScriptable thisObj, object [] args);
Ejemplo n.º 57
0
 public virtual void DefineGetter (int index, ICallable getter)
 {
     Slot slot = GetSlot (null, index);
     if (slot == null) {
         slot = new Slot ();
         AddSlot (null, index, slot);
     }
     slot.getter = getter;        
 }
        /// <summary>
        ///     Provides the ICallable that is statically defined
        /// </summary>
        public override ICallable GetStaticCallable()
        {
            if (_staticCallable == null)
            {
                _staticCallable = GetExpressionType() as ICallable;
            }

            return _staticCallable;
        }
Ejemplo n.º 59
0
 public bool Call(ICallable callable, double salience, object value, IContinuation succ, IFailure fail)
 {
     AddCodelet(new CodeletEvaluableWrapper(new CallableAsEvaluable(callable, value, succ, fail), this, salience, 1, 1), "Call");
     return true;
 }
Ejemplo n.º 60
0
 public void Tag(string name, IDictionary attributes, ICallable block)
 {
     BlockTag(name, attributes, block);
 }