Ejemplo n.º 1
0
        public void ExecutesDelegatePerformance()
        {
            Dictionary<string, object> vars = new Dictionary<string, object>(5);
            WaitCallback noop = delegate (object arg)
                                      {
                                          // noop
                                      };
            vars["noop"] = noop;

            FunctionNode fn = new FunctionNode();
            fn.Text = "noop";
            StringLiteralNode str = new StringLiteralNode();
            str.Text = "theArg";
            fn.addChild(str);

            int ITERATIONS = 10000000;

            StopWatch watch = new StopWatch();
            using (watch.Start("Duration Direct: {0}"))
            {
                for (int i = 0; i < ITERATIONS; i++)
                {
                    ((WaitCallback)vars["noop"])(str.getText());
                }
            }

            using (watch.Start("Duration SpEL: {0}"))
            {
                for (int i = 0; i < ITERATIONS; i++)
                {
                    fn.GetValue(null, vars);
                }
            }
        }
Ejemplo n.º 2
0
 protected bool Equals(FunctionNode other)
 {
     return base.Equals(other)
            && string.Equals(Name, other.Name)
            && IsPure.Equals(other.IsPure)
            && Equals(ReturnTypeSignature, other.ReturnTypeSignature);
 }
Ejemplo n.º 3
0
        public Word Visit(FunctionNode functionNode)
        {
            var function = new Function(functionNode);

            if (Procedures.Contains(function))
            {
                return(ErrorFactory.AlreadyDefinedProcedure(functionNode, function.Name, function.ParamCount));
            }
            return(function);
        }
Ejemplo n.º 4
0
 public Constructor(CanonicalNameReference canonicalName, Flag flags, Name name,
                    List <Expression> annotations, FunctionNode function, List <Initializer> initializers)
 {
     this.canonicalName = canonicalName;
     this.flags         = flags;
     this.name          = name;
     this.annotations   = annotations;
     this.function      = function;
     this.initializers  = initializers;
 }
Ejemplo n.º 5
0
        public void ExtractReplicationGuidesFromText04()
        {
            List <int> guides = new List <int>();
            string     text   = " <   101>  <  abc   >  <203> ";

            bool result = FunctionNode.ExtractReplicationGuideFromText(guides, text);

            Assert.AreEqual(false, result);
            Assert.AreEqual(0, guides.Count);
        }
Ejemplo n.º 6
0
        public object Visit(FunctionNode node)
        {
            var paramList = new List <object>();

            foreach (var pi in node.Parameters)
            {
                paramList.Add(pi.Accept(this));
            }
            return(_functionRunner.Invoke(new FunctionContext(node.Name, paramList)));
        }
Ejemplo n.º 7
0
        public void ExtractReplicationGuidesFromText03()
        {
            List <int> guides = new List <int>();
            string     text   = null;

            Assert.Throws <ArgumentNullException>(() =>
            {
                FunctionNode.ExtractReplicationGuideFromText(guides, text);
            });
        }
Ejemplo n.º 8
0
        public void Visit_IfElseThrowsException_ExceptionShouldBeThrownOutsideTheVisitor()
        {
            var visitor        = new ScriptVisitor(context => throw new InvalidOperationException("Operation failed"));
            var conditionInstr = new ValueNode(true);
            var ifInstr        = new FunctionNode("name", new List <IAstNode>());
            var elseInstr      = new ValueNode(false);

            Assert.Throws <InvalidOperationException>(() =>
                                                      visitor.Visit(new IfElseNode(conditionInstr, ifInstr, elseInstr)));
        }
Ejemplo n.º 9
0
        private void tvExpressions_Click(object sender, System.EventArgs e)
        {
            FunctionNode FunctionNode = tvExpressions.GetNodeAt(tvExpressions.PointToClient(Cursor.Position)) as FunctionNode;

            if (FunctionNode == null)
            {
                return;
            }
            tvExpressions.SelectedNode = FunctionNode;
        }
Ejemplo n.º 10
0
        public void Visit(FunctionNode node)
        {
            CurrentSymbolTable.Insert(node.Identifier, node.Type, node);

            CurrentSymbolTable.OpenScope();
            node.AcceptSiblings(node.Params, this);
            node.AcceptChildren(this);
            node.SymbolTable = CurrentSymbolTable.currentTable;
            CurrentSymbolTable.CloseScope();
        }
Ejemplo n.º 11
0
        public void AssignStatementWithVariable_ShouldContainExpressionNode()
        {
            var          ast      = TestHelpers.MakeAstRoot("int varTest = 2;\nint tester = 2;\nfunction testFunction -> | void\ntester = varTest;\nendfunction");
            FunctionNode funcNode = ast.GetChildren(2) as FunctionNode;

            AssignmentNode assignNode = funcNode.GetChildren(0) as AssignmentNode;

            Assert.That(assignNode.Identifier, Is.EqualTo("tester"));
            Assert.That(assignNode.Expression, Is.TypeOf <IdentfierNode>());
        }
Ejemplo n.º 12
0
        internal void FetchAndTranslate(FunctionNode func)
        {
            var fetcher  = new Fetcher(_compiler, func);
            var vc       = fetcher.Run();
            var analyzer = new LivenessAnalyzer(func, vc);

            analyzer.Run();
            var translator = new Translator(_assembler, _compiler, _codeContext, func, vc);

            translator.Run();
        }
Ejemplo n.º 13
0
        public void Successfully_ListAllValuesForSingleExpr_Expand()
        {
            var data  = Data(Roll9Conf);
            var group = new GroupNode(null, new List <DiceAST> {
                _2d20
            });
            var node = new FunctionNode(FunctionScope.Group, "expand", new DiceAST[0], data);

            node.Context.Expression = group;
            EvaluateNode(node, data, 2, "{2d20}.expand() => (9 + 9) => 18");
        }
        public void Analyze_Function_ReturnsFunctionNode()
        {
            SyntaxNode root = new FunctionNode(new IdentifierNode("ln"), new List <SyntaxNode>
            {
                new IdentifierNode("e")
            });

            root = SemanticAnalyzer.Analyze(root, new Environment());

            Assert.AreEqual("ln(e)", root.ToString());
        }
        public void Visit(FunctionNode op)
        {
            string parameters = ParameterList(op);

            EmitGraphvizNodeBegin($"{op.Name}({parameters})");
            foreach (var parameter in op.Parameters)
            {
                parameter.Accept(this);
            }
            EmitGraphvizNodeEnd();
        }
Ejemplo n.º 16
0
        public void AssignStatementHasCorrectId()
        {
            var          ast      = TestHelpers.MakeAstRoot("int tester = 2;\nfunction testFunction -> | void\ntester = 4;\nendfunction");
            FunctionNode funcNode = ast.GetChildren(1) as FunctionNode;

            AssignmentNode assignNode = funcNode.GetChildren(0) as AssignmentNode;

            //TestContext.WriteLine(((ExpressionNode)assignNode.Expression).Operator);
            Assert.That(assignNode.Identifier, Is.EqualTo("tester"));
            Assert.That(assignNode.Expression, Is.TypeOf <IntNode>());
        }
Ejemplo n.º 17
0
        public void FunctionNodeHasCorrectIdAndTypeAndChildren()
        {
            AstNode presumableFuncNode = astRoot.GetChildren(3);

            Assert.That(presumableFuncNode, Is.TypeOf <FunctionNode>());

            FunctionNode functionNode = presumableFuncNode as FunctionNode;

            Assert.That(functionNode.Identifier, Is.EqualTo("setup"));
            Assert.That(functionNode.Type, Is.EqualTo(LanguageType.Void));
            Assert.That(functionNode.NumberOfChildren, Is.EqualTo(8));
        }
Ejemplo n.º 18
0
        public void IfNode_ShouldHaveAlternate()
        {
            FunctionNode funcNode         = astRoot.GetChildren(4) as FunctionNode;
            AstNode      presumableIfNode = funcNode.GetChildren(4);

            Assert.That(presumableIfNode, Is.TypeOf <IfNode>());

            IfNode ifNode = presumableIfNode as IfNode;

            Assert.That(ifNode.Alternate, Is.Not.Null);
            Assert.That(ifNode.GetChildren(), Is.Not.Null);
        }
        public void Should_return_filter_descriptor_for_function()
        {
            FunctionNode functionNode = StringFunction();

            functionNode.Accept(visitor);

            FilterDescriptor result = (FilterDescriptor)visitor.Result;

            Assert.Equal(FilterOperator.StartsWith, result.Operator);
            Assert.Equal("Name", result.Member);
            Assert.Equal("J", result.Value);
        }
Ejemplo n.º 20
0
        private T GetResult <T>(FunctionCallExpression node, List <object> parameters,
                                FunctionNode funcNode, List <object> scope)
        {
            List <object> funcParameters = scope;

            for (int i = 0; i < node.Children.Count; i++)
            {
                TypeEnum type = funcNode.FunctionType.ParameterTypes[i].Type;
                funcParameters.Add(_interpreter.Dispatch(node.Children[i], parameters, type));
            }
            return(_interpreter.Function <T>(funcNode, funcParameters));
        }
Ejemplo n.º 21
0
 private void AddSymbolsFromFunc(FunctionNode functionNode)
 {
     //todo user func
     //foreach (var funcNodeArgument in functionNode.FormalArguments)
     //{
     //    var compLitNode = funcNodeArgument as RelationNode;
     //    if(compLitNode != null)
     //        functionNode.SymbolTable.AddRelSymbol(compLitNode);
     //    else
     //        functionNode.SymbolTable.AddSetSymbol((SetNode)funcNodeArgument);
     //}
 }
Ejemplo n.º 22
0
        private void BeginFunction(VariableType[] args, VariableType ret, CallingConvention callingConvention)
        {
            _function = new FunctionNode(CreateLabelNode(), CreateLabelNode(), args, ret, callingConvention);

            AddNode(_function);
            AddNode(_function.Entry);
            var node = _currentNode;

            AddNode(_function.Exit);            // Add function exit / epilog marker.
            AddNode(_function.End);             // Add function end.
            SetCurrentNode(node);
        }
Ejemplo n.º 23
0
        public void TestSerializeNullException()
        {
            IGraphController graphController = new GraphController(null);
            IStorage         storage         = null;
            IVisualNode      node            = new FunctionNode(graphController, "", "-", "double,double");
            ISlot            slot            = new Slot(graphController, SlotType.Input, node);

            Assert.Throws <ArgumentNullException>(() =>
            {
                slot.Serialize(storage);
            });
        }
Ejemplo n.º 24
0
        public override void Visit(FunctionNode node)
        {
            if (node.Name == "Main")
            {
                _currentStringBuilder = MainBody;

                VisitChildren(node);
            }
            else
            {
                _currentStringBuilder = Functions;
                _currentStringBuilder.Append("\n");

                _currentStringBuilder.Append($"public static");
                if (node.IsCollection)
                {
                    _currentStringBuilder.Append($" Collection<");
                    _currentStringBuilder.Append($"{ResolveTypeToCS(Utilities.FindTypeFromString(node.ReturnType))}");
                    _currentStringBuilder.Append($">");
                }
                else
                {
                    _currentStringBuilder.Append($" {ResolveTypeToCS(Utilities.FindTypeFromString(node.ReturnType))}");
                }

                _currentStringBuilder.Append($" {HandleCSharpKeywords(node.Name)} (");
                bool first = true;
                foreach (var item in node.Parameters)
                {
                    if (first)
                    {
                        first = false;
                        item.Accept(this);
                    }
                    else
                    {
                        _currentStringBuilder.Append($",");
                        item.Accept(this);
                    }
                }
                _currentStringBuilder.Append(") \n");

                _currentStringBuilder.Append("{\n");

                VisitChildren(node);

                _currentStringBuilder.Append("\n");

                _currentStringBuilder.Append("}");
            }
            _currentStringBuilder = Functions;
        }
Ejemplo n.º 25
0
 private void InsertDeclaration(AST ast, ASTNode himeNode)
 {
     if (himeNode.Children[0].Value == "export")
     {
         ExportNode exportNode = CreateExportNode(himeNode);
         ast.Exports.Add(exportNode);
     }
     else
     {
         FunctionNode functionNode = CreateFunctionNode(himeNode);
         ast.Functions.Add(functionNode);
     }
 }
Ejemplo n.º 26
0
 public static FunctionNode CreateFunctionNode(
     FunctionNode fn,
     VariableNode name,
     ListNode <DeclareNode> args,
     ITypeNode?ret,
     INode where
     )
 {
     fn.Name = name;
     fn.Arguments.AddRange(args.List);
     fn.Return = ret;
     return(fn.R(name));
 }
Ejemplo n.º 27
0
        private Expression Build(FunctionNode node)
        {
            string methodName;

            if (!_methodNames.TryGetValue(node.FunctionName.ToLower(), out methodName))
            {
                return(null);
            }

            var expression = GetExpression(methodName, node.Arguments);

            return(expression);
        }
Ejemplo n.º 28
0
 public override void Visit(FunctionNode node)
 {
     Emit(node.ID + "(");
     foreach (Node argumentNode in node.Arguments)
     {
         Visit(argumentNode);
         if (argumentNode != node.Arguments[^ 1])
         {
             Emit(", ");
         }
     }
     Emit(node is FunctionStmtNode ? ");\n" : ")");
 }
Ejemplo n.º 29
0
        public void ExtractReplicationGuideFromText00()
        {
            List <int> guides = new List <int>();
            string     text   = " <   101   >   <   203   >   ";
            // string text = ""; null; "       ";
            // string text = " <   101   >   <  xyz >   <   203   >   ";
            bool result = FunctionNode.ExtractReplicationGuideFromText(guides, text);

            Assert.AreEqual(true, result);
            Assert.AreEqual(2, guides.Count);
            Assert.AreEqual(101, guides[0]);
            Assert.AreEqual(203, guides[1]);
        }
Ejemplo n.º 30
0
        public ClassMemberNode(string name, ExprNode expr, FunctionNode func, TypeNode annotation, TokenLocation location) : base(location)
        {
            Name         = name;
            Expr         = expr;
            Func         = func;
            Annotation   = annotation;
            Binding.Name = Name;

            if (Func != null)
            {
                Func.IsClassMember = true;
            }
        }
Ejemplo n.º 31
0
        /// <summary>The <see cref="TermNode"/> visit implementation</summary>
        /// <param name="termNode">The term AST node</param>
        /// <returns>The modified AST node if modified otherwise the original node</returns>
        public override AstNode VisitTermNode(TermNode termNode)
        {
            // term
            // : unary_operator?
            // [ NUMBER S* | PERCENTAGE S* | LENGTH S* | EMS S* | EXS S* | ANGLE S* |
            // TIME S* | FREQ S* ]
            // | STRING S* | IDENT S* | URI S* | hexcolor | function
            // ;

            // append for: unary_operator?
            // TODO - Shall we remove the '+' operator here?
            _printerFormatter.Append(termNode.UnaryOperator);
            if (termNode.IsBinary && FunctionNode.IsBinaryOperator(termNode.UnaryOperator))
            {
                _printerFormatter.Append(" ");
            }

            // append for: [ NUMBER S* | PERCENTAGE S* | LENGTH S* | EMS S* | EXS S* | ANGLE S* | TIME S* | FREQ S* ]
            if (!string.IsNullOrWhiteSpace(termNode.NumberBasedValue))
            {
                _printerFormatter.Append(termNode.NumberBasedValue);
            }
            else if (!string.IsNullOrWhiteSpace(termNode.StringBasedValue))
            {
                // append for: | STRING S* | IDENT S* | URI S*
                _printerFormatter.Append(termNode.StringBasedValue);
            }
            else if (!string.IsNullOrWhiteSpace(termNode.ReplacementTokenBasedValue))
            {
                // TODO: REPLACECSSTOKENONPRINT
                _printerFormatter.Append(termNode.ReplacementTokenBasedValue);
            }
            else if (!string.IsNullOrWhiteSpace(termNode.Hexcolor))
            {
                // append for: hexcolor
                _printerFormatter.Append(termNode.Hexcolor);
            }
            else if (termNode.FunctionNode != null)
            {
                // append for: function
                // Invoke the Function visitor
                termNode.FunctionNode.Accept(this);
            }

            foreach (var comment in termNode.ImportantComments)
            {
                comment.Accept(this);
            }

            return(termNode);
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Declares a new function.
        /// </summary>
        private void declareFunction(FunctionNode node)
        {
            if (node.Name == "_")
            {
                Error(CompilerMessages.UnderscoreName);
            }

            var isVariadic = false;

            // validation
            if (node.Arguments.Count > 0)
            {
                for (var idx = 0; idx < node.Arguments.Count; idx++)
                {
                    var curr = node.Arguments[idx];
                    if (curr.Name == "_")
                    {
                        curr.Name = Unique.AnonymousArgName();
                    }

                    if (curr.Type == typeof(UnspecifiedType))
                    {
                        Error(CompilerMessages.LambdaArgTypeUnknown);
                    }

                    if (curr.IsVariadic)
                    {
                        if (idx < node.Arguments.Count - 1)
                        {
                            Error(CompilerMessages.VariadicArgumentNotLast);
                        }

                        isVariadic = true;
                    }
                }
            }
            else
            {
                if (node.Name == EntityNames.RunMethodName || node.Name == EntityNames.EntryPointMethodName)
                {
                    Error(CompilerMessages.ReservedFunctionRedefinition, node.Name);
                }
            }

            var method = MainType.CreateMethod(node.Name, node.ReturnTypeSignature, node.Arguments, true, prepare: false);

            method.Kind       = TypeContentsKind.UserDefined;
            method.IsPure     = node.IsPure;
            method.IsVariadic = isVariadic;
            method.Body       = node.Body;
        }
Ejemplo n.º 33
0
            public LambdaComparer(LambdaExpressionNode lambdaExpression)
            {
                FunctionNode functionNode = new FunctionNode();
                functionNode.Text = "compare";
                VariableNode x = new VariableNode();
                x.Text = "x";
                VariableNode y = new VariableNode();
                y.Text = "y";

                functionNode.addChild(x);
                functionNode.addChild(y);

                _fn = functionNode;
                _variables = new Hashtable();
                _variables.Add( "compare", lambdaExpression );
            }
Ejemplo n.º 34
0
        public void ExecutesDelegate()
        {
            Dictionary<string, object> vars = new Dictionary<string, object>();
            vars["concat"] = new TestCallback(Concat);

            FunctionNode fn = new FunctionNode();
            fn.Text = "concat";
            StringLiteralNode str = new StringLiteralNode();
            str.Text = "theValue";
            fn.addChild(str);
            StringLiteralNode str2 = new StringLiteralNode();
            str2.Text = "theValue";
            fn.addChild(str2);

            IExpression exp = fn;
            Assert.AreEqual(string.Format("{0},{1},{2}", this.GetHashCode(), str.Text, str2.Text), exp.GetValue(null, vars));
        }
Ejemplo n.º 35
0
            public LambdaComparer(LambdaExpressionNode lambdaExpression)
            {
                var functionNode = new FunctionNode {Text = "compare"};
                var x = new VariableNode {Text = "x"};
                var y = new VariableNode {Text = "y"};

                functionNode.addChild(x);
                functionNode.addChild(y);

                _fn = functionNode;
                _variables = new Dictionary<string, object>
                {
                    {"compare", lambdaExpression}
                };
            }
Ejemplo n.º 36
0
        public void ExecutesLambdaFunction()
        {
            Dictionary<string, object> vars = new Dictionary<string, object>();
            Expression.RegisterFunction("ident", "{|n| $n}", vars);

            FunctionNode fn = new FunctionNode();
            fn.Text = "ident";
            StringLiteralNode str = new StringLiteralNode();
            str.Text = "theValue";
            fn.addChild(str);

            IExpression exp = fn;
            Assert.AreEqual(str.Text, exp.GetValue(null, vars));
        }
 public FunctionNodeViewModel(FunctionNode graphItemObject, Invert.Core.GraphDesigner.DiagramViewModel diagramViewModel) : 
         base(graphItemObject, diagramViewModel) {
 }
Ejemplo n.º 38
0
        private void DrawingBoard_Click(object sender, MouseEventArgs e)
        {
            // If a method isn't selected, do nothing
            if (lstMethods.SelectedItems.Count <= 0)
            {
                return;
            }

            // Otherwise, generate a new Node to and add it to our code base
            Node f = null;

            switch (CurrentMode[cmbSelectionPicker.Text])
            {
                case METHODS:
                    f = new FunctionNode(mAvailableMethods[lstMethods.SelectedIndices[0]]);
                    break;

                case CONSTANTS:
                    f = new ConstantNode(ConstantNode.ConstConverter[lstMethods.SelectedItems[0].Text]);
                    break;

                case OPERATORS:
                    f = new OperatorNode(OperatorNode.Operators[lstMethods.SelectedIndices[0]]);
                    break;

                default:
                    throw new InvalidOperationException("You somehow got something besides Meth/Const/Op in the cmb box.");
                    break;
            }

            f.Location = e.Location;
            mCommands.Add(f);
            spltMainContainer.Panel2.Controls.Add(f);
        }
Ejemplo n.º 39
0
        //done
        private void ParseFunction(Node subtree)
        {
            FunctionNode func = new FunctionNode(subtree);
            //we already checked we had a Define
            tokens.Next();
            SymbolTable.EnterScope();
            //Define Return Name(params):
            tokens.ConsumeToken(TokenType.Type);
            func.ReturnType = tokens.LastToken.Value;

            tokens.ConsumeToken(TokenType.Ident);
            func.Ident = tokens.LastToken.Value;

            tokens.ConsumeToken(TokenType.LeftParen);
            if (tokens.CurrentToken != TokenType.RightParen)
            {
                ParseFunctionParamList(func);
            }
            tokens.ConsumeToken(TokenType.RightParen).ConsumeToken(TokenType.Colon); //and close
            FunctionTable.Add(func.CreateSignature(), func);
            ParseBlock(func);
            if (func.ReturnType == "Void")
            {
                func.Children[1].AddChild(new ReturnNode(func.Children[1]));
            }
            SymbolTable.ExitScope();
        }
Ejemplo n.º 40
0
        /// <summary>
        /// Declares a new function.
        /// </summary>
        private void declareFunction(FunctionNode node)
        {
            if (node.Name == "_")
                Error(CompilerMessages.UnderscoreName);

            var isVariadic = false;

            // validation
            if (node.Arguments.Count > 0)
            {
                for (var idx = 0; idx < node.Arguments.Count; idx++)
                {
                    var curr = node.Arguments[idx];
                    if (curr.Name == "_")
                        curr.Name = Unique.AnonymousArgName();

                    if(curr.Type == typeof(UnspecifiedType))
                        Error(CompilerMessages.LambdaArgTypeUnknown);

                    if (curr.IsVariadic)
                    {
                        if (idx < node.Arguments.Count - 1)
                            Error(CompilerMessages.VariadicArgumentNotLast);

                        isVariadic = true;
                    }
                }
            }
            else
            {
                if (node.Name == EntityNames.RunMethodName || node.Name == EntityNames.EntryPointMethodName)
                    Error(CompilerMessages.ReservedFunctionRedefinition, node.Name);
            }

            var method = MainType.CreateMethod(node.Name, node.ReturnTypeSignature, node.Arguments, true, prepare: false);
            method.Kind = TypeContentsKind.UserDefined;
            method.IsPure = node.IsPure;
            method.IsVariadic = isVariadic;
            method.Body = node.Body;
        }
Ejemplo n.º 41
0
        private static void GenerateFunctionDeclaration(FunctionNode node, DataContext data)
        {
            data.VariableMap.DeclareVariable(node.FunctionName, node.Line, node.Column);

            StartLine(data, "context.DeclareVariable(\"{0}\", isConst: true, value: ", node.FunctionName);

            GenerateFunction(node, data);

            EndLine(data, ");");
        }
Ejemplo n.º 42
0
        private static void GenerateFunction(FunctionNode node, DataContext data)
        {
            Append(data, "new ScriptFunction(new Func<ScriptExecutionContext, dynamic[]");

            if (node.Args.Count > 0)
            {
                Append(data, ", ");
                Append(data, string.Join(", ", Enumerable.Repeat("dynamic", node.Args.Count)));
            }

            string functionName = "Function" + data.GetNextFunctionIndex();
            Append(data, ", dynamic>({0})", functionName);

            data.VariableMap.PushFrame();

            Append(data, ", ");
            if (node.Args.Count > 0)
            {
                Append(data, "new dynamic[] {{ ");

                for (int i = 0; i < node.Args.Count; i++)
                {
                    data.VariableMap.DeclareVariable(node.Args[i].VariableName, node.Line, node.Column);

                    if (i != 0)
                        Append(data, ", ");

                    if (node.Args[i].ValueExpression != null)
                    {
                        GenerateExpression(node.Args[i].ValueExpression, data);
                    }
                    else
                    {
                        Append(data, "null");
                    }
                }

                Append(data, " }}");
            }
            else
            {
                Append(data, "null");
            }

            var variableDeclarations = node.BodyStatementBlock.Find<VariableDeclarationNode>().Where(x => x.FindParent<FunctionNode>() == node).Select(x => x.VariableName);

            var capturedVariables = node.BodyStatementBlock.Find<VariableReferenceNode>()
                .Where(x =>
                    x.FindParent<FunctionNode>() == node &&
                    !variableDeclarations.Contains(x.VariableName) &&
                    !data.VariableMap.IsVariableDeclaredInCurrentFrame(x.VariableName)
                )
                .ToArray();

            Append(data, ", ");
            if (capturedVariables.Length > 0)
            {
                Append(data, "new dynamic[] {{ ");

                for (int i = 0; i < capturedVariables.Length; i++)
                {
                    if (i != 0)
                        Append(data, ", ");

                    Append(data, "context[\"{0}\"]", capturedVariables[i].VariableName);
                }

                Append(data, " }}");
            }
            else
            {
                Append(data, "null");
            }

            Append(data, ")");

            data.PushCodeBlock(functionName);
            data.CodeBlock.Padding = 2;

            string returnType = "dynamic";

            if (node.IsGenerator)
                returnType = "IEnumerable<dynamic>";

            Append(data, "private static {0} {1}(ScriptExecutionContext context, dynamic[] captures", returnType, functionName);

            if (node.Args.Count > 0)
            {
                Append(data, ", ");
                Append(data, string.Join(", ", node.Args.Select(x => "dynamic " + data.VariableMap.GetVariableName(x.VariableName))));
            }

            EndLine(data, ")");

            WriteLine(data, "{{");

            data.CodeBlock.Padding++;

            if (!node.IsGenerator)
                WriteLine(data, "context.PushStackFrame(\"{0}\");", !node.IsAnonymous ? node.FunctionName : "<anonymous>");

            foreach (var arg in node.Args)
                WriteLine(data, "context.DeclareVariable(\"{0}\", {1});", arg.VariableName, data.VariableMap.GetVariableName(arg.VariableName));

            for (int i = 0; i < capturedVariables.Length; i++)
                WriteLine(data, "context.DeclareVariable(\"{0}\", captures[{1}]);", capturedVariables[i].VariableName, i);

            if (!node.IsGenerator)
            {
                WriteLine(data, "bool isError = false;");

                WriteLine(data, "try {{");

                data.CodeBlock.Padding++;
            }

            GenerateStatementBlock(node.BodyStatementBlock, data, pushStackFrame: false);

            if (!(node.BodyStatementBlock.Last() is ReturnNode) && !node.IsGenerator)
            {
                WriteLine(data, "return null;");
            }

            if (!node.IsGenerator)
            {
                data.CodeBlock.Padding--;
                WriteLine(data, "}} catch(Exception) {{");

                data.CodeBlock.Padding++;
                WriteLine(data, "isError = true;");
                WriteLine(data, "throw;");

                data.CodeBlock.Padding--;
                WriteLine(data, "}} finally {{");

                data.CodeBlock.Padding++;
                WriteLine(data, "if (!isError) {{");

                data.CodeBlock.Padding++;
                WriteLine(data, "context.PopStackFrame();");

                data.CodeBlock.Padding--;
                WriteLine(data, "}}");

                data.CodeBlock.Padding--;
                WriteLine(data, "}}");
            }

            data.CodeBlock.Padding--;
            WriteLine(data, "}}");

            data.PopCodeBlock();

            data.VariableMap.PopFrame();
        }
 private FunctionNode StringFunction()
 {
     FunctionNode comparisonNode = new FunctionNode
     {
         FilterOperator = FilterOperator.StartsWith,
         Arguments =
         {
             new PropertyNode
             {
                 Name = "Name"
             },
             new StringNode
             {
                 Value = "J"
             }
         }
     };
     return comparisonNode;
 }
Ejemplo n.º 44
0
        /// <summary>
        /// fun_def                                     = [ "pure" ] "fun" identifier [ ":" type ] fun_args "->" block
        /// </summary>
        private FunctionNode parseFunDef()
        {
            var node = new FunctionNode();
            node.IsPure = check(LexemType.Pure);

            if (!check(LexemType.Fun))
            {
                if (node.IsPure)
                    error(ParserMessages.FunctionDefExpected);
                else
                    return null;
            }

            node.Name = ensure(LexemType.Identifier, ParserMessages.FunctionIdentifierExpected).Value;
            if (check(LexemType.Colon))
                node.ReturnTypeSignature = ensure(parseType, ParserMessages.FunctionReturnExpected);

            node.Arguments = attempt(() => parseFunArgs(true)) ?? new List<FunctionArgument>();
            ensure(LexemType.Arrow, ParserMessages.SymbolExpected, "->");
            node.Body.LoadFrom(ensure(parseBlock, ParserMessages.FunctionBodyExpected));

            return node;
        }
Ejemplo n.º 45
0
        internal virtual INode BuildExpression(Dictionary<NodeModel, Dictionary<int, INode>> buildDict)
        {
            //Debug.WriteLine("Building expression...");

            if (OutPortData.Count > 1)
            {
                var names = OutPortData.Select(x => x.NickName).Zip(Enumerable.Range(0, OutPortData.Count), (x, i) => x+i).ToList();
                var listNode = new FunctionNode("list", names);
                foreach (var data in names.Zip(Enumerable.Range(0, OutPortData.Count), (name, index) => new { Name=name, Index=index }))
                {
                    listNode.ConnectInput(data.Name, Build(buildDict, data.Index));
                }
                return listNode;
            }
            else
                return Build(buildDict, 0);
        }
Ejemplo n.º 46
0
        private void ParseFunctionParamList(FunctionNode func)
        {
            if (func.Ident == "Greet")
            {
                int i;
            }
            bool cont;
            do
            {
                cont = false;
                VariableNode var = new VariableNode(func.Params);
                var.Type = tokens.CurrentToken.Value;
                tokens.ConsumeToken(TokenType.Type);

                if (tokens.CurrentToken == TokenType.LeftSquare)
                {
                    var.IsArray = true;
                    var.ArraySize = null;
                    tokens.ConsumeToken(TokenType.LeftSquare);
                    tokens.ConsumeToken(TokenType.RightSquare);
                }

                tokens.ConsumeToken(TokenType.Ident); //name
                var.Ident = tokens.LastToken.Value;

                SymbolTable.AddVariable(var.Ident, var);
                if (tokens.CurrentToken == TokenType.Comma) //moar
                {
                    tokens.ConsumeToken(TokenType.Comma);
                    cont = true;
                }
            } while (cont);
                 //okay we hit the end
            //SymbolTable.ExitScope();
        }