public void True_False_Literals()
		{
			var target = new Interpreter();

			Assert.IsTrue((bool)target.Eval("true"));
			Assert.IsFalse((bool)target.Eval("false"));
		}
 public override double Evaluate(Parser parser, Interpreter ii)
 {
     var name = _left as NameExpression;
     if (name == null)
     {
         throw new ProcessusException(parser.Source, _token, "Left side of increment/decrement postfix was not a variable.");
     }
     switch (_token.Identifier)
     {
         case MathTokenType.Increment:
         {
             double d = name.Evaluate(parser, ii);
             ii.Engine.Variables.SetVar(name.Name, d + 1);
             return d;
         }
         case MathTokenType.Decrement:
         {
             double d = name.Evaluate(parser, ii);
             ii.Engine.Variables.SetVar(name.Name, d - 1);
             return d;
         }
         default:
             throw new ProcessusException(parser.Source, _token, "Invalid postfix operator '" + _token.Value + "'.");
     }
 }
Exemple #3
0
 internal void LoadFunctions(Interpreter interpreter)
 {
     foreach (var func in _functions)
     {
         interpreter.SetFunction(func.Name, func.GetDelegate());
     }
 }
 public override void EvaluateNode(Interpreter.EvaluationContext context, AstMode mode, DateTime time)
 {
     foreach (var rule in TradingRules)
     {
         rule.EvaluateNode(context, AstMode.None, time);
     }
 }
        public void Can_use_overloaded_operators_on_class()
        {
            var target = new Interpreter();

            var x = new ClassWithOverloadedBinaryOperators(3);
            target.SetVariable("x", x);

            string y = "5";
            Assert.IsFalse(x == y);
            Assert.IsFalse(target.Eval<bool>("x == y", new Parameter("y", y)));

            y = "3";
            Assert.IsTrue(x == y);
            Assert.IsTrue(target.Eval<bool>("x == y", new Parameter("y", y)));

            Assert.IsFalse(target.Eval<bool>("x == \"4\""));
            Assert.IsTrue(target.Eval<bool>("x == \"3\""));

            Assert.IsTrue(!x == "-3");
            Assert.IsTrue(target.Eval<bool>("!x == \"-3\""));

            var z = new ClassWithOverloadedBinaryOperators(10);
            Assert.IsTrue((x + z) == "13");
            Assert.IsTrue(target.Eval<bool>("(x + z) == \"13\"", new Parameter("z", z)));
        }
        public void New_And_Member_Access()
        {
            var target = new Interpreter();

            Assert.AreEqual(new DateTime(2015, 1, 24).Month, target.Eval("new DateTime(2015,   1, 24).Month"));
            Assert.AreEqual(new DateTime(2015, 1, 24).Month + 34, target.Eval("new DateTime( 2015, 1, 24).Month + 34"));
        }
        public void New_Of_Base_Type()
        {
            var target = new Interpreter();

            Assert.AreEqual(new DateTime(2015, 1, 24), target.Eval("new DateTime(2015, 1, 24)"));
            Assert.AreEqual(new string('a', 10), target.Eval("new string('a', 10)"));
        }
        public void Static_Methods_of_Base_Types()
        {
            var target = new Interpreter();

            Assert.AreEqual(TimeSpan.FromMilliseconds(2000.49), target.Eval("TimeSpan.FromMilliseconds(2000.49)"));
            Assert.AreEqual(DateTime.DaysInMonth(2094, 11), target.Eval("DateTime.DaysInMonth(2094, 11)"));
        }
        /// <summary>
        /// Perform additional checks based on the parameter types
        /// </summary>
        /// <param name="root">The element on which the errors should be reported</param>
        /// <param name="context">The evaluation context</param>
        /// <param name="actualParameters">The parameters applied to this function call</param>
        public override void additionalChecks(ModelElement root, Interpreter.InterpretationContext context, Dictionary<string, Interpreter.Expression> actualParameters)
        {
            CheckFunctionalParameter(root, context, actualParameters[First.Name], 1);
            CheckFunctionalParameter(root, context, actualParameters[Second.Name], 1);

            Function function1 = actualParameters[First.Name].GetExpressionType() as Function;
            Function function2 = actualParameters[Second.Name].GetExpressionType() as Function;

            if (function1 != null && function2 != null)
            {
                if (function1.FormalParameters.Count == 1 && function2.FormalParameters.Count == 1)
                {
                    Parameter p1 = (Parameter)function1.FormalParameters[0];
                    Parameter p2 = (Parameter)function2.FormalParameters[0];

                    if (p1.Type != p2.Type && p1.Type != EFSSystem.DoubleType && p2.Type != EFSSystem.DoubleType)
                    {
                        root.AddError("The formal parameters for the functions provided as parameter are not the same");
                    }
                }

                if (function1.ReturnType != function2.ReturnType && function1.ReturnType != EFSSystem.DoubleType && function2.ReturnType != EFSSystem.DoubleType)
                {
                    root.AddError("The return values for the functions provided as parameter are not the same");
                }
            }
        }
Exemple #10
0
        public void Convert_Class()
        {
            var target = new Interpreter();

            Assert.AreEqual(Convert.ToString(3), target.Eval("Convert.ToString(3)"));
            Assert.AreEqual(Convert.ToInt16("23"), target.Eval("Convert.ToInt16(\"23\")"));
        }
Exemple #11
0
        public void Math_Class()
        {
            var target = new Interpreter();

            Assert.AreEqual(Math.Pow(3, 4), target.Eval("Math.Pow(3, 4)"));
            Assert.AreEqual(Math.Sin(30.234), target.Eval("Math.Sin(30.234)"));
        }
 public static void DoTable(Tree<Cell> table, Interpreter activeFixture, bool inFlow)
 {
     var activeFlowFixture = activeFixture as FlowInterpreter;
     if (activeFlowFixture != null) activeFlowFixture.DoSetUp(table);
     activeFixture.Interpret(table);
     if (activeFlowFixture != null && !inFlow) activeFlowFixture.DoTearDown(table);
 }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="rule"></param>
 /// <param name="preCondition">The precondition which setup the initial state</param>
 /// <param name="initialState">The initial stae of this transition</param>
 /// <param name="update">The statement which set up the target state</param>
 /// <param name="targetState">The target state of this transition</param>
 public Transition(PreCondition preCondition, State initialState, Interpreter.Statement.VariableUpdateStatement update, State targetState)
 {
     PreCondition = preCondition;
     InitialState = initialState;
     Update = update;
     TargetState = targetState;
 }
Exemple #14
0
 public static void Instantiate(Assembly a, Interpreter interp)
 {
     Hashtable table = interp.VarTable;
     try {
         CodeChunk chunk = (CodeChunk)a.CreateInstance("CsiChunk");
         chunk.Go(table);
         // vs 0.8 we display the type and value of expressions.  The variable $_ is
         // always set, which is useful if you want to save the result of the last
         // calculation.
         if (interp.returnsValue && DumpingValue) {
             object val = table["_"];
             Type type = val.GetType();
             string stype = type.ToString();
             if (stype.StartsWith("System."))  // to simplify things a little bit...
                 stype = stype.Substring(7);
             stype = "("+stype+")";
             if (val is string) {
                 Print(stype,"'"+val+"'");
             } else
             if (val is IEnumerable) {
                 Print(stype);
                 Dumpl((IEnumerable)val);
             } else
                 Print(stype,val);
         }
     }  catch(Exception ex) {
         Print(ex.GetType() + " was thrown: " + ex.Message);
     }
 }
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Result result
            )
        {
            if ((arguments == null) || (arguments.Count < 2))
            {
                result = Utility.WrongNumberOfArguments(
                    this, 1, arguments, "command");

                return ReturnCode.Error;
            }

            try
            {
                var processor = new CommandLineProcessor();
                var o = processor.Pharse(arguments.Select(argument => (string) argument).Skip(1).ToArray());
                if (!(o is string) && o is IEnumerable)
                    result = new StringList(o);
                else
                {
                    result = o == null ? "" : new Variant(o).ToString();
                }
            }
            catch (Exception exception)
            {
                Log.Error("Script error ", exception);
                result = "Error on command execution " + exception.Message;
            }
            return ReturnCode.Ok;
        }
Exemple #16
0
        public virtual object GetProperty(Interpreter interpreter, TemplateFrame frame, object o, object property, string propertyName)
        {
            object value;
            IDictionary map = (IDictionary)o;

            if (property == null)
                value = map[TemplateGroup.DefaultKey];
            else if (property.Equals("Keys"))
                value = map.Keys;
            else if (property.Equals("Values"))
                value = map.Values;
            else if (map.Contains(property))
                value = map[property];
            else if (map.Contains(propertyName))
                value = map[propertyName]; // if can't find the key, try ToString version
            else
                value = map[TemplateGroup.DefaultKey]; // not found, use default

            if (object.ReferenceEquals(value, TemplateGroup.DictionaryKey))
            {
                value = property;
            }

            return value;
        }
Exemple #17
0
 public override object Execute(Interpreter interpreter)
 {
     Console.WriteLine ("Mono Debugger (C) 2003-2007 Novell, Inc.\n" +
                "Written by Martin Baulig ([email protected])\n" +
                "        and Chris Toshok ([email protected])\n");
     return null;
 }
 public override double Evaluate(Parser parser, Interpreter ii)
 {
     var name = _right as NameExpression;
     switch (_token.Identifier)
     {
         case MathTokenType.Minus:
             return -_right.Evaluate(parser, ii);
         case MathTokenType.Increment:
         {
             if (name == null)
             {
                 throw new ManhoodException(parser.Source, _token, "Increment prefix could not find a variable.");
             }
             double d = name.Evaluate(parser, ii) + 1;
             ii.Engine.Variables.SetVar(name.Name, d);
             return d;
         }
         case MathTokenType.Decrement:
         {
             if (name == null)
             {
                 throw new ManhoodException(parser.Source, _token, "Decrement prefix could not find a variable.");
             }
             double d = name.Evaluate(parser, ii) - 1;
             ii.Engine.Variables.SetVar(name.Name, d);
             return d;
         }
         default:
             throw new ManhoodException(parser.Source, _token, "Invalid prefix operator '" + _token + "'.");
     }
 }
Exemple #19
0
        public TagBlueprint(Interpreter interpreter, Source source, Stringe name, IEnumerable<Token<TokenType>>[] args = null)
            : base(interpreter)
        {
            Source = source;
            Name = name;

            if (!Interpreter.TagFuncs.TryGetValue(Name.Value.ToLower().Trim(), out _tagDef))
            {
                throw new ManhoodException(Source, Name, "The tag '" + Name.Value + "' does not exist.");
            }

            _tagDef.ValidateArgCount(source, name, args != null ? args.Length : 0);

            if (args == null)
            {
                _args = Enumerable.Empty<TagArg>().ToArray();
            }
            else
            {
                // Insert token arguments into the array, set string args to null.
                _args = args.Select((a, i) => _tagDef.ArgTypes[i] == TagArgType.Tokens ? TagArg.FromTokens(a) : null).ToArray();

                // Queue string arguments on the stack.
                for (int i = 0; i < _tagDef.ArgTypes.Length; i++)
                {
                    if (_tagDef.ArgTypes[i] == TagArgType.Result)
                    {
                        interpreter.PushState(Interpreter.State.CreateDerivedDistinct(source, args[i], interpreter));
                    }
                }
            }
        }
        /// <summary>
        /// Ensures that the parameter provided corresponds to a function double->double
        /// </summary>
        /// <param name="root">Element on which the errors shall be attached</param>
        /// <param name="context">The context used to evaluate the expression</param>
        /// <param name="expression">The expression which references the function</param>
        /// <param name="count">the expected number of parameters</param>
        protected virtual void CheckFunctionalParameter(ModelElement root, Interpreter.InterpretationContext context, Interpreter.Expression expression, int count)
        {
            Types.Type type = expression.GetExpressionType();

            Function function = type as Function;
            if (function != null)
            {
                if (function.FormalParameters.Count == count)
                {
                    foreach (Parameter parameter in function.FormalParameters)
                    {
                        if (!parameter.Type.IsDouble())
                        {
                            root.AddError(expression.ToString() + " does not takes a double for parameter " + parameter.Name);
                        }
                    }
                }
                else
                {
                    root.AddError(expression.ToString() + " does not take " + count + "parameter(s) as input");
                }

                if (!function.ReturnType.IsDouble())
                {
                    root.AddError(expression.ToString() + " does not return a double");
                }
            }
            else
            {
                if (!type.IsDouble())
                {
                    root.AddError(expression.ToString() + " type is not double");
                }
            }
        }
        public void If_Operators()
        {
            var target = new Interpreter();

            Assert.AreEqual(10 > 3 ? "yes" : "no", target.Eval("10 > 3 ? \"yes\" : \"no\""));
            Assert.AreEqual(10 < 3 ? "yes" : "no", target.Eval("10 < 3 ? \"yes\" : \"no\""));
        }
Exemple #22
0
 public void CanInterpretTwoSentences()
 {
     Interpreter interpreter = new Interpreter();
     var commands = interpreter.Parse("PRESS A,\"B\",C\r\nPRESS A,B").ToList();
     Assert.AreEqual(2, commands.Count);
     Assert.AreEqual(2, commands[1].Parameters.Count);
 }
        public void Alphabetic_Literals()
        {
            var target = new Interpreter();

            Assert.AreEqual("ciao", target.Eval("\"ciao\""));
            Assert.AreEqual('c', target.Eval("'c'"));
        }
 private static bool CapsInfer(Interpreter interpreter, Source source, Stringe tagname, TagArg[] args)
 {
     // TODO: Make capsinfer properly infer "first" capitalization given multiple sentences. Currently, it mistakes it for "word" mode.
     var words = Regex.Matches(args[0].GetString(), @"\w+").OfType<Match>().Select(m => m.Value).ToArray();
     int wCount = words.Length;
     int uCount = 0;
     int fwCount = 0;
     bool firstCharIsUpper = false;
     for (int i = 0; i < wCount; i++)
     {
         if (words[i].All(Char.IsUpper))
         {
             uCount++;
         }
         if (Char.IsUpper(words[i][0]))
         {
             fwCount++;
             if (i == 0) firstCharIsUpper = true;
         }
     }
     if (uCount == wCount)
     {
         interpreter.CurrentState.Output.SetCaps(Capitalization.Upper);
     }
     else if (wCount > 1 && fwCount == wCount)
     {
         interpreter.CurrentState.Output.SetCaps(Capitalization.Word);
     }
     else if (firstCharIsUpper)
     {
         interpreter.CurrentState.Output.SetCaps(Capitalization.First);
     }
     return false;
 }
        public SpiderView(SpiderHost host)
        {
            this.Host = host;
            this.Scripting = new Scripting.LuaInterpreter(this);
            this.Preprocessor = new Preprocessor.LuaMako(this);
            this.Scripting.RegisterFunction("refresh", GetType().GetMethod("refresh"), this);

            this.timer = new Timer();
            InitializeComponent();
            this.tabBar = new TabBar(this);
            this.deck = new Panel();
            tabBar.Dock = DockStyle.Top;
            tabBar.Height = 23;
            this.Controls.Add(deck);
            this.Controls.Add(tabBar);
            deck.Dock = DockStyle.Fill;
            this.tabBar.Dock = DockStyle.Top;
            Block = Stylesheet.Blocks["Body"];
            this.BackColor = Block.BackColor;
            this.ForeColor = Block.ForeColor;
            this.tabBar.TabChange += tabBar_TabChange;
            this.timer.Tick += timer_Tick;
            this.timer.Interval = 1000;
            this.Click += SpiderView_Click;
        }
        public override double Evaluate(Parser parser, Interpreter ii)
        {
            if (_token.Identifier == MathTokenType.Swap)
            {
                var left = _left as NameExpression;
                var right = _right as NameExpression;
                if (left == null) throw new ManhoodException(parser.Source, _token, "Left side of swap operation was not a variable.");
                if (right == null) throw new ManhoodException(parser.Source, _token, "Right side of swap operation was not a variable.");
                double temp = left.Evaluate(parser, ii);
                double b = right.Evaluate(parser, ii);
                ii.Engine.Variables.SetVar(left.Name, b);
                ii.Engine.Variables.SetVar(right.Name, temp);
                return b;
            }
            Func<Parser, Interpreter, NameExpression, Expression, double> assignFunc;
            if (AssignOperations.TryGetValue(_token.Identifier, out assignFunc))
            {
                var left = _left as NameExpression;
                if (left == null) throw new ManhoodException(parser.Source, _token, "Left side of assignment was not a variable.");
                return assignFunc(parser, ii, left, _right);
            }

            Func<double, double, double> func;
            if (!Operations.TryGetValue(_token.Identifier, out func))
            {
                throw new ManhoodException(parser.Source, _token, "Invalid binary operation '" + _token + "'.");
            }
            return func(_left.Evaluate(parser, ii), _right.Evaluate(parser, ii));
        }
Exemple #27
0
        private void calculateButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ClearScreen();

                string formula = formulaTextBox.Text;

                TokenReader reader = new TokenReader(CultureInfo.InvariantCulture);
                List<Token> tokens = reader.Read(formula);

                ShowTokens(tokens);

                AstBuilder astBuilder = new AstBuilder();
                Operation operation = astBuilder.Build(tokens);

                ShowAbstractSyntaxTree(operation);

                Dictionary<string, double> variables = new Dictionary<string, double>();
                foreach (Variable variable in GetVariables(operation))
                {
                    double value = AskValueOfVariable(variable);
                    variables.Add(variable.Name, value);
                }

                IExecutor executor = new Interpreter();
                double result = executor.Execute(operation, variables);

                resultTextBox.Text = "" + result;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        public void SystemExceptions_are_preserved_using_method_invocation()
        {
            var target = new Interpreter();
            target.SetVariable("a", new MyTestService());

            target.Eval("a.ThrowException()");
        }
 public override void EvaluateNode(Interpreter.EvaluationContext context, AstMode mode, DateTime time)
 {
     if (ExecuteFrequency.CanExecute(context.StartDate, time))
     {
         Statements.EvaluateNode(context, AstMode.None, time);
     }
 }
		public void Numeric_Operators_Priority()
		{
			var target = new Interpreter();

			Assert.AreEqual(8 / 2 + 2, target.Eval("8 / 2 + 2"));
			Assert.AreEqual(8 + 2 / 2, target.Eval("8 + 2 / 2"));
		}
 /// <summary>
 ///
 /// </summary>
 /// <param name="dsObject"></param>
 /// <param name="context"></param>
 /// <param name="dsi"></param>
 public override void OnDispose(StackValue dsObject, ProtoCore.Runtime.Context context, Interpreter dsi)
 {
     lock (DSObjectMap)
     {
         Object clrobject;
         if (DSObjectMap.TryGetValue(dsObject, out clrobject))
         {
             DSObjectMap.Remove(dsObject);
             CLRObjectMap.Remove(clrobject);
             dsi.runtime.Core.FFIPropertyChangedMonitor.RemoveFFIObject(clrobject);
         }
     }
 }
    private void OnLoadFiles(string[] paths)
    {
        if (paths == null || paths.Length == 0 || string.IsNullOrWhiteSpace(paths[0]))
        {
            if (FullFilename == null)
            {
                wizardDlg.CloseDialog(DialogAction.Cancel);
            }
            return;
        }

        FullFilename = paths[0];
        var filename = Path.GetFileName(FullFilename);

        fileLabel.text = filename;

        interpreter = Interpreter.Get(FullFilename);
        fileInfo    = interpreter.GetBasicInfo(FullFilename);

        if (fileInfo == null)
        {
            ShowWarningMessage(translator.Get("Invalid file"), openFile, true);
            return;
        }

        // Update field dropdown if file is vector data
        bool isVectorData = interpreter is ShapefileInterpreter;

        if (isVectorData)
        {
            UpdateFieldDropdown(FullFilename);
        }

        // Show/hide field label and dropdown depending on vector or raster data
        fieldLabel.gameObject.SetActive(isVectorData);
        fieldDropdown.gameObject.SetActive(isVectorData);

        var filename_lc = filename.ToLower();

        // Try to guess the site
        if (string.IsNullOrWhiteSpace(siteDropdown.input.text))
        {
            var sites = dataManager.sites;
            for (int i = 0; i < sites.Count; i++)
            {
                if (filename_lc.Contains(sites[i].Name.ToLower()))
                {
                    siteDropdown.value = i;
                    break;
                }
            }
        }

        // Try to guess the layer (and group)
        if (!layerDropdown.HasSelected)
        {
            var layer = GetLayer(filename_lc);
            if (layer == null && !string.IsNullOrWhiteSpace(fileInfo.suggestedLayerName))
            {
                layer = GetLayer(fileInfo.suggestedLayerName.ToLower());
            }

            if (layer != null)
            {
                groupDropdown.value = dataManager.groups.IndexOf(layer.Group);
                layerDropdown.value = layer.Group.layers.IndexOf(layer);
            }
        }

        // Suggest the resolution
        if (!resolutionDropdown.HasSelected && fileInfo.degreesPerPixel != 0)
        {
            for (int i = 0; i < resolutions.Length; i++)
            {
                if (fileInfo.degreesPerPixel.Similar(resolutions[i].ToDegrees()))
                {
                    resolutionDropdown.value = i;
                    break;
                }
            }
        }

        // Suggest the units
        if (string.IsNullOrWhiteSpace(unitsInput.text) && !string.IsNullOrWhiteSpace(fileInfo.suggestedUnits))
        {
            unitsInput.text = translator.Get(fileInfo.suggestedUnits);
        }

        if (fileInfo != null)
        {
            CheckBounds();
            CheckRasterSize();
            CheckResolution();
        }

        ValidateResolutionDrowndown();

        UpdateProgress();
    }
Exemple #33
0
        ///////////////////////////////////////////////////////////////////////

        #region Debugger Breakpoint Support Methods
#if DEBUGGER
        public static ReturnCode Breakpoint(
            IDebugger debugger,
            Interpreter interpreter,
            InteractiveLoopData loopData,
            ref Result result
            )
        {
            if (interpreter == null)
            {
                result = "invalid interpreter";
                return(ReturnCode.Error);
            }

            if (!interpreter.Interactive)
            {
                result = "cannot break into interactive loop";
                return(ReturnCode.Error);
            }

            if (debugger != null)
            {
                /* IGNORED */
                debugger.EnterLoop();
            }

            try
            {
                ReturnCode code;

                InteractiveLoopCallback interactiveLoopCallback =
                    interpreter.InteractiveLoopCallback;

                if (interactiveLoopCallback != null)
                {
                    code = interactiveLoopCallback(
                        interpreter, new InteractiveLoopData(loopData, true),
                        ref result);
                }
                else
                {
#if SHELL
                    //
                    // NOTE: This is the only place in the debugger subsystem
                    //       where the InteractiveLoop method may be called.
                    //       All other methods in the Debugger class and/or
                    //       any external classes that desire the interactive
                    //       debugging functionality should call this method.
                    //
                    code = Interpreter.InteractiveLoop(
                        interpreter, new InteractiveLoopData(loopData, true),
                        ref result);
#else
                    result = "not implemented";
                    code   = ReturnCode.Error;
#endif
                }

                //
                // NOTE: Only check (or update) the interpreter state at this
                //       point if the interpreter is still usable (i.e. it is
                //       not disposed) -AND- the interactive loop returned a
                //       successful result.
                //
                if ((code == ReturnCode.Ok) && Engine.IsUsable(interpreter))
                {
                    //
                    // NOTE: Upon exiting the interactive loop, temporarily
                    //       prevent the engine from checking interpreter
                    //       readiness.  This is used to avoid potentially
                    //       breaking back into the interactive loop due to
                    //       breakpoints caused by script cancellation, etc.
                    //
                    interpreter.IsDebuggerExiting = true;
                }

                return(code);
            }
            finally
            {
                if (debugger != null)
                {
                    /* IGNORED */
                    debugger.ExitLoop();
                }
            }
        }
Exemple #34
0
        void TestIt(string input, decimal value)
        {
            Interpreter I = new Interpreter();

            Assert.AreEqual(value, I.Calculate(input));
        }
Exemple #35
0
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Result result
            )
        {
            ReturnCode code = ReturnCode.Ok;

            if (interpreter != null)
            {
                if (arguments != null)
                {
                    if ((arguments.Count == 5) || (arguments.Count == 6))
                    {
                        ///////////////////////////////////////////////////////////////////////////////////////////////
                        //
                        // test name description ?constraints? body result
                        //
                        ///////////////////////////////////////////////////////////////////////////////////////////////

                        string name = arguments[1];

#if DEBUGGER
                        if (DebuggerOps.CanHitBreakpoints(interpreter,
                                                          EngineFlags.None, BreakpointType.Test))
                        {
                            code = interpreter.CheckBreakpoints(
                                code, BreakpointType.Test, name,
                                null, null, this, null, clientData,
                                arguments, ref result);
                        }

                        if (code == ReturnCode.Ok)
#endif
                        {
                            string description = arguments[2];

                            string          constraints;
                            string          body;
                            IScriptLocation bodyLocation;
                            string          expectedResult;

                            if (arguments.Count == 6)
                            {
                                constraints    = arguments[3];
                                body           = arguments[4];
                                bodyLocation   = arguments[4];
                                expectedResult = arguments[5];
                            }
                            else
                            {
                                constraints    = null;
                                body           = arguments[3];
                                bodyLocation   = arguments[3];
                                expectedResult = arguments[4];
                            }

                            ReturnCodeList returnCodes = new ReturnCodeList(new ReturnCode[] {
                                ReturnCode.Ok, ReturnCode.Return
                            });

                            MatchMode mode = StringOps.DefaultResultMatchMode;

                            bool noCase = false;

                            ///////////////////////////////////////////////////////////////////////////////////////////////

                            int testLevels = interpreter.EnterTestLevel();

                            try
                            {
                                //
                                // NOTE: Create a place to put all the output of the this command.
                                //
                                StringBuilder testData = StringOps.NewStringBuilder();

                                //
                                // NOTE: Are we going to skip this test?
                                //
                                bool skip = false;
                                bool fail = true;

                                code = TestOps.CheckConstraints(
                                    interpreter, testLevels, name, constraints,
                                    false, false, testData, ref skip, ref fail,
                                    ref result);

                                //
                                // NOTE: Track the fact that we handled this test.
                                //
                                int[] testStatistics = null;

                                if (code == ReturnCode.Ok)
                                {
                                    testStatistics = interpreter.TestStatistics;

                                    if ((testStatistics != null) && (testLevels == 1) && skip)
                                    {
                                        Interlocked.Increment(ref testStatistics[
                                                                  (int)TestInformationType.Total]);
                                    }
                                }

                                if ((code == ReturnCode.Ok) && !skip)
                                {
                                    code = TestOps.RecordInformation(
                                        interpreter, TestInformationType.Counts, name,
                                        null, true, ref result);
                                }

                                //
                                // NOTE: Check test constraints to see if we should run the test.
                                //
                                if ((code == ReturnCode.Ok) && !skip)
                                {
                                    ReturnCode bodyCode   = ReturnCode.Ok;
                                    Result     bodyResult = null;

                                    //
                                    // NOTE: Only run the test body if the setup is successful.
                                    //
                                    if (body != null)
                                    {
                                        TestOps.AppendFormat(
                                            interpreter, testData, TestOutputType.Start,
                                            "---- {0} start", name);

                                        TestOps.AppendLine(
                                            interpreter, testData, TestOutputType.Start);

                                        int savedPreviousLevels = interpreter.BeginNestedExecution();

                                        try
                                        {
                                            ICallFrame frame = interpreter.NewTrackingCallFrame(
                                                StringList.MakeList(this.Name, "body", name),
                                                CallFrameFlags.Test);

                                            interpreter.PushAutomaticCallFrame(frame);

                                            try
                                            {
                                                bodyCode = interpreter.EvaluateScript(
                                                    body, bodyLocation, ref bodyResult);

                                                if ((bodyResult == null) && ScriptOps.HasFlags(
                                                        interpreter, InterpreterFlags.TestNullIsEmpty,
                                                        true))
                                                {
                                                    bodyResult = String.Empty;
                                                }

                                                if (bodyCode == ReturnCode.Error)
                                                {
                                                    /* IGNORED */
                                                    interpreter.CopyErrorInformation(
                                                        VariableFlags.None, ref bodyResult);
                                                }
                                            }
                                            finally
                                            {
                                                //
                                                // NOTE: Pop the original call frame that we pushed above
                                                //       and any intervening scope call frames that may be
                                                //       leftover (i.e. they were not explicitly closed).
                                                //
                                                /* IGNORED */
                                                interpreter.PopScopeCallFramesAndOneMore();
                                            }
                                        }
                                        catch (Exception e)
                                        {
                                            bodyResult = e;
                                            bodyCode   = ReturnCode.Error;
                                        }
                                        finally
                                        {
                                            interpreter.EndNestedExecution(savedPreviousLevels);
                                        }
                                    }

                                    //
                                    // NOTE: Did we fail to match the return code?
                                    //
                                    bool codeFailure = !returnCodes.Contains(bodyCode);

                                    //
                                    // NOTE: Does the actual result match the expected result?
                                    //
                                    bool       scriptFailure = false;
                                    ReturnCode scriptCode    = ReturnCode.Ok;
                                    Result     scriptResult  = null;

                                    if (!codeFailure)
                                    {
                                        if (expectedResult != null)
                                        {
                                            scriptCode = TestOps.Match(
                                                interpreter, mode, bodyResult,
                                                expectedResult, noCase, null,
                                                TestOps.RegExOptions, false,
                                                ref scriptFailure, ref scriptResult);

                                            if (scriptCode == ReturnCode.Ok)
                                            {
                                                scriptFailure = !scriptFailure;
                                            }
                                            else
                                            {
                                                scriptFailure = true;
                                            }
                                        }
                                    }

                                    //
                                    // NOTE: If any of the important things failed, the test fails.
                                    //
                                    if (!(codeFailure || scriptFailure))
                                    {
                                        //
                                        // PASS: Test ran with no errors and the results match
                                        //       what we expected.
                                        //
                                        if ((testStatistics != null) && (testLevels == 1))
                                        {
                                            Interlocked.Increment(ref testStatistics[
                                                                      (int)TestInformationType.Passed]);

                                            Interlocked.Increment(ref testStatistics[
                                                                      (int)TestInformationType.Total]);
                                        }

                                        TestOps.AppendFormat(
                                            interpreter, testData, TestOutputType.Pass,
                                            "++++ {0} PASSED", name);

                                        TestOps.AppendLine(
                                            interpreter, testData, TestOutputType.Pass);
                                    }
                                    else
                                    {
                                        //
                                        // FAIL: Test ran with errors or the result does not match
                                        //       what we expected.
                                        //
                                        if ((testStatistics != null) && (testLevels == 1))
                                        {
                                            if (fail)
                                            {
                                                Interlocked.Increment(ref testStatistics[
                                                                          (int)TestInformationType.Failed]);

                                                Interlocked.Increment(ref testStatistics[
                                                                          (int)TestInformationType.Total]);
                                            }
                                        }

                                        //
                                        // NOTE: Keep track of each test that fails.
                                        //
                                        if (testLevels == 1)
                                        {
                                            TestOps.RecordInformation(
                                                interpreter, TestInformationType.FailedNames,
                                                name, null, true);
                                        }

                                        TestOps.AppendLine(
                                            interpreter, testData, TestOutputType.Fail);

                                        TestOps.AppendFormat(
                                            interpreter, testData, TestOutputType.Fail,
                                            "==== {0} {1} {2}", name, description.Trim(),
                                            fail ? "FAILED" : "IGNORED");

                                        TestOps.AppendLine(
                                            interpreter, testData, TestOutputType.Fail);

                                        if (body != null)
                                        {
                                            TestOps.AppendLine(
                                                interpreter, testData, TestOutputType.Body,
                                                "==== Contents of test case:");

                                            TestOps.AppendLine(
                                                interpreter, testData, TestOutputType.Body,
                                                body);
                                        }

                                        if (scriptFailure)
                                        {
                                            if (scriptCode == ReturnCode.Ok)
                                            {
                                                TestOps.AppendLine(
                                                    interpreter, testData, TestOutputType.Reason,
                                                    "---- Result was:");

                                                TestOps.AppendLine(
                                                    interpreter, testData, TestOutputType.Reason,
                                                    bodyResult);

                                                TestOps.AppendFormat(
                                                    interpreter, testData, TestOutputType.Reason,
                                                    "---- Result should have been ({0} matching):",
                                                    mode);

                                                TestOps.AppendLine(
                                                    interpreter, testData, TestOutputType.Reason);

                                                TestOps.AppendLine(
                                                    interpreter, testData, TestOutputType.Reason,
                                                    expectedResult);
                                            }
                                            else
                                            {
                                                TestOps.Append(
                                                    interpreter, testData, TestOutputType.Reason,
                                                    "---- Error testing result: ");

                                                TestOps.AppendLine(
                                                    interpreter, testData, TestOutputType.Reason,
                                                    scriptResult);

                                                if ((scriptResult != null) &&
                                                    (scriptResult.ErrorInfo != null))
                                                {
                                                    TestOps.Append(
                                                        interpreter, testData, TestOutputType.Error,
                                                        "---- errorInfo(matchResult): ");

                                                    TestOps.AppendLine(
                                                        interpreter, testData, TestOutputType.Error,
                                                        scriptResult.ErrorInfo);

                                                    TestOps.Append(
                                                        interpreter, testData, TestOutputType.Error,
                                                        "---- errorCode(matchResult): ");

                                                    TestOps.AppendLine(
                                                        interpreter, testData, TestOutputType.Error,
                                                        scriptResult.ErrorCode);
                                                }
                                            }
                                        }

                                        if (codeFailure)
                                        {
                                            ReturnCodeDictionary returnCodeMessages =
                                                interpreter.TestReturnCodeMessages;

                                            string codeMessage;

                                            if ((returnCodeMessages == null) ||
                                                (!returnCodeMessages.TryGetValue(
                                                     bodyCode, out codeMessage) &&
                                                 !returnCodeMessages.TryGetValue(
                                                     ReturnCode.Invalid, out codeMessage)))
                                            {
                                                codeMessage = "Unknown";
                                            }

                                            TestOps.AppendFormat(
                                                interpreter, testData, TestOutputType.Reason,
                                                "---- {0}; Return code was: {1}",
                                                codeMessage, bodyCode);

                                            TestOps.AppendLine(
                                                interpreter, testData, TestOutputType.Reason);

                                            TestOps.Append(
                                                interpreter, testData, TestOutputType.Reason,
                                                "---- Return code should have been one of: ");

                                            TestOps.AppendLine(
                                                interpreter, testData, TestOutputType.Reason,
                                                returnCodes.ToString());

                                            if ((bodyResult != null) &&
                                                (bodyResult.ErrorInfo != null) &&
                                                !returnCodes.Contains(ReturnCode.Error))
                                            {
                                                TestOps.Append(
                                                    interpreter, testData, TestOutputType.Error,
                                                    "---- errorInfo(body): ");

                                                TestOps.AppendLine(
                                                    interpreter, testData, TestOutputType.Error,
                                                    bodyResult.ErrorInfo);

                                                TestOps.Append(
                                                    interpreter, testData, TestOutputType.Error,
                                                    "---- errorCode(body): ");

                                                TestOps.AppendLine(
                                                    interpreter, testData, TestOutputType.Error,
                                                    bodyResult.ErrorCode);
                                            }
                                        }

                                        TestOps.AppendFormat(
                                            interpreter, testData, TestOutputType.Fail,
                                            "==== {0} {1}", name, fail ? "FAILED" : "IGNORED");

                                        TestOps.AppendLine(
                                            interpreter, testData, TestOutputType.Fail);
                                    }
                                }

                                //
                                // NOTE: Did the above code succeed?
                                //
                                if (code == ReturnCode.Ok)
                                {
                                    //
                                    // NOTE: The result is the complete output produced by the
                                    //       entire test.
                                    //
                                    if (testData != null)
                                    {
                                        result = testData;
                                    }
                                    else
                                    {
                                        result = String.Empty;
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                Engine.SetExceptionErrorCode(interpreter, e);

                                result = e;
                                code   = ReturnCode.Error;
                            }
                            finally
                            {
                                interpreter.ExitTestLevel();
                            }
                        }
                    }
                    else
                    {
                        result = String.Format(
                            "wrong # args: should be \"{0} name description constraints body result\"",
                            this.Name);

                        code = ReturnCode.Error;
                    }
                }
                else
                {
                    result = "invalid argument list";
                    code   = ReturnCode.Error;
                }
            }
            else
            {
                result = "invalid interpreter";
                code   = ReturnCode.Error;
            }

            return(code);
        }
        /// <summary>
        /// Initializes primary properties on the DS object for given FFI
        /// object.
        /// </summary>
        /// <param name="ffiObject">FFI object in context</param>
        /// <param name="dsObject">Design script object</param>
        /// <param name="context">Execution context</param>
        /// <param name="dsi">Interpreter</param>
        /// <param name="classIndex">Class index of design script data type</param>
        private void PopulatePrimaryProperties(object ffiObject, StackValue dsObject, ProtoCore.Runtime.Context context, Interpreter dsi, int classIndex)
        {
            Dictionary <string, object> properties = GetPrimaryProperties(ffiObject);

            if (null == properties || properties.Count == 0)
            {
                return;
            }

            var core = dsi.runtime.Core;

            StackValue[] svs = core.Heap.Heaplist[(int)dsObject.opdata].Stack;
            for (int ix = 0; ix < svs.Length; ++ix)
            {
                SymbolNode symbol = core.DSExecutable.classTable.ClassNodes[classIndex].symbols.symbolList[ix];
                object     prop   = null;
                if (properties.TryGetValue(symbol.name, out prop) && null != prop)
                {
                    svs[ix] = Marshal(prop, context, dsi, GetMarshaledType(prop.GetType()));
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="context"></param>
        /// <param name="dsi"></param>
        /// <returns></returns>
        private StackValue CreateDSObject(object obj, ProtoCore.Runtime.Context context, Interpreter dsi)
        {
            //We are here, because we want to create DS object of user defined type.
            var  core       = dsi.runtime.Core;
            var  classTable = core.DSExecutable.classTable;
            Type objType    = GetPublicType(obj.GetType());
            int  type       = classTable.IndexOf(GetTypeName(objType));

            //Recursively get the base class type if available.
            while (type == -1 && objType != null)
            {
                objType = objType.BaseType;
                if (null != objType)
                {
                    type = classTable.IndexOf(GetTypeName(objType));
                }
            }

            int ptr = ProtoCore.DSASM.Constants.kInvalidPointer;

            lock (core.Heap.cslock)
            {
                ptr = core.Heap.Allocate(classTable.ClassNodes[type].size);
            }

            MetaData metadata;

            metadata.type = type;
            StackValue retval = StackUtils.BuildPointer(ptr, metadata);

            BindObjects(obj, retval);
            dsi.runtime.Core.FFIPropertyChangedMonitor.AddFFIObject(obj);

            //If we are in debug mode, populate primary properties if there is any.
            //if (core.Options.IDEDebugMode)
            //    PopulatePrimaryProperties(obj, retval, context, dsi, type);

            return(retval);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="dsObject"></param>
        /// <param name="context"></param>
        /// <param name="dsi"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public override object UnMarshal(StackValue dsObject, ProtoCore.Runtime.Context context, Interpreter dsi, System.Type type)
        {
            object clrObject = null;

            switch (dsObject.optype)
            {
            case AddressType.ArrayPointer:
            {
                if (type.IsArray || type == typeof(object))
                {
                    return(ConvertDSArrayToCSArray(dsObject, context, dsi, type));
                }
                if (typeof(System.Collections.ICollection).IsAssignableFrom(type))
                {
                    Type   arrayType = type.GetGenericArguments()[0].MakeArrayType();
                    object arr       = ConvertDSArrayToCSArray(dsObject, context, dsi, arrayType);
                    return(Activator.CreateInstance(type, new[] { arr }));        //Create the collection using
                }
                else if (typeof(System.Collections.IEnumerable).IsAssignableFrom(type))
                {
                    Type   arrayType = type.GetGenericArguments()[0].MakeArrayType();
                    object arr       = ConvertDSArrayToCSArray(dsObject, context, dsi, arrayType);
                    return(arr);

/*
 *                          Type genericType = type.GetGenericArguments()[0];
 *                          return ConvertDSArrayToCSList(dsObject, context, dsi, genericType);
 *
 *                          Type listType = typeof(List<>).MakeGenericType(genericType);
 *                          var list = Activator.CreateInstance(listType);
 *                          listType.GetMethod("AddRange").Invoke(list, new object[]{arr});
 *                          return list;
 */
                }
                break;
            }

            case AddressType.Int:
            case AddressType.Double:
            case AddressType.Boolean:
            case AddressType.Char:
            case AddressType.String:
            {
                clrObject = TryGetPrimitiveObject(dsObject, context, dsi, type);
                break;
            }

            case AddressType.Null:
            {
                return(null);
            }

            case AddressType.Pointer:
            {
                DSObjectMap.TryGetValue(dsObject, out clrObject);
                break;
            }

            default:
            {
                throw new NotSupportedException(string.Format("Operand type {0} not supported for marshalling", dsObject.optype));
            }
            }

            if (null != clrObject)
            {
                return(clrObject);
            }

            return(CreateCLRObject(dsObject, context, dsi, type));
        }
 public override object UnMarshal(StackValue dsObject, ProtoCore.Runtime.Context context, Interpreter dsi, Type type)
 {
     char[] array = PrimitiveMarshler.ConvertDSArrayToCSArray <char>(kCharMarshaler, dsObject, context, dsi);
     return(new string(array));
 }
        private object TryGetPrimitiveObject(StackValue dsObject, ProtoCore.Runtime.Context context, Interpreter dsi, System.Type type)
        {
            FFIObjectMarshler marshaler;
            Type dsObjectType = type;

            if (dsObjectType == typeof(object))
            {
                dsObjectType = GetPrimitiveType(dsObject.optype);
            }
            else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                dsObjectType = Nullable.GetUnderlyingType(type);
            }

            if (mPrimitiveMarshalers.TryGetValue(dsObjectType, out marshaler))
            {
                return(marshaler.UnMarshal(dsObject, context, dsi, type));
            }

            return(null);
        }
 public override object UnMarshal(StackValue dsObject, ProtoCore.Runtime.Context context, Interpreter dsi, Type type)
 {
     return(ProtoCore.Utils.EncodingUtils.ConvertInt64ToCharacter(dsObject.opdata));
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="context"></param>
        /// <param name="dsi"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public override StackValue Marshal(object obj, ProtoCore.Runtime.Context context, Interpreter dsi, ProtoCore.Type type)
        {
            if (obj == null)
            {
                return(StackUtils.BuildNull());
            }

            FFIObjectMarshler marshaler = null;
            StackValue        retVal;
            Type objType = obj.GetType();

            if (type.IsIndexable)
            {
                if (obj is System.Collections.ICollection)
                {
                    System.Collections.ICollection collection = obj as System.Collections.ICollection;
                    object[] array = new object[collection.Count];
                    collection.CopyTo(array, 0);
                    return(PrimitiveMarshler.ConvertCSArrayToDSArray(this, array, context, dsi, type));
                }
                else if (obj is System.Collections.IEnumerable)
                {
                    System.Collections.IEnumerable enumerable = obj as System.Collections.IEnumerable;
                    return(PrimitiveMarshler.ConvertCSArrayToDSArray(this, enumerable, context, dsi, type));
                }
            }

            Array arr = obj as Array;

            if (null != arr)
            {
                return(PrimitiveMarshler.ConvertCSArrayToDSArray(this, arr, context, dsi, type));
            }
            else if ((PrimitiveMarshler.IsPrimitiveDSType(type) || PrimitiveMarshler.IsPrimitiveObjectType(obj, type)) && mPrimitiveMarshalers.TryGetValue(objType, out marshaler))
            {
                return(marshaler.Marshal(obj, context, dsi, type));
            }
            else if (CLRObjectMap.TryGetValue(obj, out retVal))
            {
                return(retVal);
            }

            return(CreateDSObject(obj, context, dsi));
        }
 public override object UnMarshal(StackValue dsObject, ProtoCore.Runtime.Context context, Interpreter dsi, Type type)
 {
     return(dsObject.opdata == 0 ? false : true);
 }
        public override StackValue Marshal(object obj, ProtoCore.Runtime.Context context, Interpreter dsi, ProtoCore.Type type)
        {
            string     str     = (string)obj;
            StackValue dsarray = PrimitiveMarshler.ConvertCSArrayToDSArray(kCharMarshaler, str.ToCharArray(), context, dsi, type);

            return(StackUtils.BuildString(dsarray.opdata));
        }
        public override object UnMarshal(StackValue dsObject, ProtoCore.Runtime.Context context, Interpreter dsi, Type type)
        {
            if (dsObject.opdata_d > MaxValue || dsObject.opdata_d < MinValue)
            {
                string message = String.Format(ProtoCore.RuntimeData.WarningMessage.kFFIInvalidCast, dsObject.opdata_d, type.Name, MinValue, MaxValue);
                dsi.LogWarning(ProtoCore.RuntimeData.WarningID.kTypeMismatch, message);
            }

            return(CastToDouble(dsObject.opdata_d));
        }
 public override StackValue Marshal(object obj, ProtoCore.Runtime.Context context, Interpreter dsi, ProtoCore.Type type)
 {
     return(StackUtils.BuildChar((char)obj));
 }
 public override void OnDispose(StackValue dsObject, ProtoCore.Runtime.Context context, Interpreter dsi)
 {
     throw new NotImplementedException();
 }
 public override StackValue Marshal(object obj, ProtoCore.Runtime.Context context, Interpreter dsi, ProtoCore.Type type)
 {
     return(StackUtils.BuildNode(AddressType.Boolean, (bool)obj ? 1 : 0));
 }
        public static StackValue ConvertCSArrayToDSArray(FFIObjectMarshler marshaler, IEnumerable enumerable, ProtoCore.Runtime.Context context, Interpreter dsi, ProtoCore.Type type)
        {
            var core = dsi.runtime.Core;
            List <StackValue> svs = new List <StackValue>();

            //Create new dsType for marshaling the elements, by reducing the rank
            ProtoCore.Type dsType = new ProtoCore.Type {
                Name = type.Name, rank = type.rank - 1, UID = type.UID
            };
            dsType.IsIndexable = dsType.rank > 0;

            foreach (var item in enumerable)
            {
                StackValue value = marshaler.Marshal(item, context, dsi, dsType);
                svs.Add(value);
            }

            var retVal = dsi.runtime.rmem.BuildArray(svs.ToArray());

            return(retVal);
        }
 public override StackValue Marshal(object obj, ProtoCore.Runtime.Context context, Interpreter dsi, ProtoCore.Type type)
 {
     return(StackUtils.BuildDouble(System.Convert.ToDouble(obj)));
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="dsObject"></param>
        /// <param name="context"></param>
        /// <param name="dsi"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private object CreateCLRObject(StackValue dsObject, ProtoCore.Runtime.Context context, Interpreter dsi, System.Type type)
        {
            object clrObject = TryGetPrimitiveObject(dsObject, context, dsi, type);

            if (null != clrObject)
            {
                return(clrObject);
            }
            //Must be a user defined type, and expecting a var object
            if (type == typeof(object) && dsObject.optype == AddressType.Pointer)
            {
                //TOD: Fix GC issue, don't know how/when this will get GCed??
                dsi.runtime.rmem.Heap.IncRefCount(dsObject);
                BindObjects(dsObject, dsObject);
                return(dsObject);
            }

            throw new InvalidOperationException("Unable to locate managed object for given dsObject.");
        }
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dsObject"></param>
        /// <param name="context"></param>
        /// <param name="dsi"></param>
        /// <returns></returns>
        public static T[] ConvertDSArrayToCSArray <T>(FFIObjectMarshler marshaler, StackValue dsObject, ProtoCore.Runtime.Context context, Interpreter dsi)
        {
            StackValue[] arr   = dsi.runtime.rmem.GetArrayElements(dsObject);
            int          count = arr.Length;

            T[]  array   = new T[count];
            Type objType = typeof(T);

            for (int idx = 0; idx < count; ++idx)
            {
                object obj = marshaler.UnMarshal(arr[idx], context, dsi, objType);
                if (null == obj)
                {
                    if (objType.IsValueType)
                    {
                        throw new System.InvalidCastException(string.Format("Null value cannot be cast to {0}", objType.Name));
                    }

                    array[idx] = default(T);
                }
                else
                {
                    array[idx] = (T)obj;
                }
            }

            return(array);
        }
Exemple #53
0
        private SelectorContext selector(int _p)
        {
            ParserRuleContext _parentctx = Context;
            int             _parentState = State;
            SelectorContext _localctx    = new SelectorContext(Context, _parentState);
            SelectorContext _prevctx     = _localctx;
            int             _startState  = 12;

            EnterRecursionRule(_localctx, 12, RULE_selector, _p);
            try {
                int _alt;
                EnterOuterAlt(_localctx, 1);
                {
                    State = 64;
                    ErrorHandler.Sync(this);
                    switch (Interpreter.AdaptivePredict(TokenStream, 5, Context))
                    {
                    case 1:
                    {
                        State = 62;
                        identifier();
                    }
                    break;

                    case 2:
                    {
                        State = 63;
                        functionInvoke();
                    }
                    break;
                    }
                    Context.Stop = TokenStream.LT(-1);
                    State        = 76;
                    ErrorHandler.Sync(this);
                    _alt = Interpreter.AdaptivePredict(TokenStream, 7, Context);
                    while (_alt != 2 && _alt != global::Antlr4.Runtime.Atn.ATN.INVALID_ALT_NUMBER)
                    {
                        if (_alt == 1)
                        {
                            if (ParseListeners != null)
                            {
                                TriggerExitRuleEvent();
                            }
                            _prevctx = _localctx;
                            {
                                State = 74;
                                ErrorHandler.Sync(this);
                                switch (Interpreter.AdaptivePredict(TokenStream, 6, Context))
                                {
                                case 1:
                                {
                                    _localctx = new SelectorContext(_parentctx, _parentState);
                                    PushNewRecursionContext(_localctx, _startState, RULE_selector);
                                    State = 66;
                                    if (!(Precpred(Context, 2)))
                                    {
                                        throw new FailedPredicateException(this, "Precpred(Context, 2)");
                                    }
                                    State = 67;
                                    Match(DOT);
                                    State = 68;
                                    identifier();
                                }
                                break;

                                case 2:
                                {
                                    _localctx = new SelectorContext(_parentctx, _parentState);
                                    PushNewRecursionContext(_localctx, _startState, RULE_selector);
                                    State = 69;
                                    if (!(Precpred(Context, 1)))
                                    {
                                        throw new FailedPredicateException(this, "Precpred(Context, 1)");
                                    }
                                    State = 70;
                                    Match(LBRACKET);
                                    State = 71;
                                    simple();
                                    State = 72;
                                    Match(RBRACKET);
                                }
                                break;
                                }
                            }
                        }
                        State = 78;
                        ErrorHandler.Sync(this);
                        _alt = Interpreter.AdaptivePredict(TokenStream, 7, Context);
                    }
                }
            }
            catch (RecognitionException re) {
                _localctx.exception = re;
                ErrorHandler.ReportError(this, re);
                ErrorHandler.Recover(this, re);
            }
            finally {
                UnrollRecursionContexts(_parentctx);
            }
            return(_localctx);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="csArray"></param>
        /// <param name="context"></param>
        /// <param name="dsi"></param>
        /// <returns></returns>
        public static StackValue ConvertCSArrayToDSArray(FFIObjectMarshler marshaler, Array csArray, ProtoCore.Runtime.Context context, Interpreter dsi, ProtoCore.Type type)
        {
            var core = dsi.runtime.Core;

            StackValue[] sv   = new StackValue[csArray.Length];
            int          size = sv.Length;

            //Create new dsType for marshaling the elements, by reducing the rank
            ProtoCore.Type dsType = new ProtoCore.Type {
                Name = type.Name, rank = type.rank - 1, UID = type.UID
            };
            dsType.IsIndexable = dsType.rank > 0;

            for (int i = 0; i < size; ++i)
            {
                StackValue value = marshaler.Marshal(csArray.GetValue(i), context, dsi, dsType);
                sv[i] = value;
            }

            var retVal = dsi.runtime.rmem.BuildArray(sv);

            return(retVal);
        }
Exemple #55
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="terp"></param>
 /// <returns></returns>
 public Interpreter GetInterpreter(Interpreter terp)
 {
     return(terp);
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="dsObject"></param>
        /// <param name="context"></param>
        /// <param name="dsi"></param>
        /// <param name="arrayType"></param>
        /// <returns></returns>
        private object ConvertDSArrayToCSArray(StackValue dsObject, ProtoCore.Runtime.Context context, Interpreter dsi, System.Type arrayType)
        {
            if (arrayType.IsArray)
            {
                //  processing only for the primitive types
                //  anything else will be dealt with as it was earlier
                //
                if (arrayType.UnderlyingSystemType == typeof(int[]))
                {
                    return(PrimitiveMarshler.ConvertDSArrayToCSArray <int>(this, dsObject, context, dsi));
                }
                else if (arrayType.UnderlyingSystemType == typeof(double[]))
                {
                    return(PrimitiveMarshler.ConvertDSArrayToCSArray <double>(this, dsObject, context, dsi));
                }
                else if (arrayType.UnderlyingSystemType == typeof(bool[]))
                {
                    return(PrimitiveMarshler.ConvertDSArrayToCSArray <bool>(this, dsObject, context, dsi));
                }
            }

            int         ptr   = (int)dsObject.opdata;
            HeapElement hs    = dsi.runtime.rmem.Heap.Heaplist[ptr];
            int         count = hs.VisibleSize;

            //  use arraylist instead of object[], this allows us to correctly capture
            //  the type of objects being passed
            //
            ArrayList arrList     = new ArrayList();
            var       elementType = arrayType.GetElementType();

            if (elementType == null)
            {
                elementType = typeof(object);
            }
            for (int idx = 0; idx < count; ++idx)
            {
                arrList.Add(UnMarshal(hs.Stack[idx], context, dsi, elementType));
            }

            return(arrList.ToArray(elementType));
        }
Exemple #57
0
 private static ReturnCode InteractiveLoopCallback(Interpreter interpreter, InteractiveLoopData loopData, ref Result result)
 {
     return(ReturnCode.Ok);
 }
 public void SetUp()
 {
     _interpreter = new Interpreter();
 }
Exemple #59
0
 private static ReturnCode ExecuteCallback(Interpreter interpreter, IClientData clientData, ArgumentList arguments, ref Result result)
 {
     return(ReturnCode.Ok);
 }
Exemple #60
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="terp"></param>
 public void StoreInterpreter(Interpreter terp)
 {
 }