Esempio n. 1
0
        public SequenceNode FunctionCall(Function from, Node[] args, RegisterNode result, out Action <Node> nextNodeSetter)
        {
            var pl  = _enclosedIn == null ? 0 : 1; // space for enclosing function stack frame address
            var seq = new Node[args.Length + Math.Max(0, args.Length - Target.HardwareRegistersOrder.Length) + 3 + pl];

            // params in registers, params on stack, call, result, cleanup stack
            if (pl == 1)
            {
                seq[0] = new AssignmentNode(Target.HardwareRegistersOrder[0], from.ComputationOfStackFrameAddress(this));
            }
            var i = 0;

            for (; i < Target.HardwareRegistersOrder.Length && i < args.Length; ++i)
            {
                seq[i + pl] = new AssignmentNode(Target.HardwareRegistersOrder[i], args[i]);
            }
            var ptr = i + pl;

            for (; i < args.Length; ++i)
            {
                var v = Push(args[i]);
                seq[ptr++] = v.Item1;
                seq[ptr++] = v.Item2;
            }
            seq[ptr++] = new FunctionCallNode(this);
            seq[ptr++] = new AssignmentNode(result, Body.Last().ResultRegister);  // Assume value of function body is return value
            seq[ptr++] = new AssignmentNode(Target.RSP, new AddOperatorNode(Target.RSP, new ConstantNode <long>(_stackFrameSize)));
            return(new SequenceNode(seq, out nextNodeSetter, result));
        }
        private QueryNode FormatIndexOfFunction(FunctionCallNode nodeIn)
        {
            QueryNode result = FormatStringFunction("INSTR", nodeIn);

            _sql.Append(" - 1");
            return(result);
        }
        public LanguageType Visit(FunctionCallNode node)
        {
            var functionNode  = CurrentSymbolTable.Get(node.Name, CurrentSymbolTable).Node as FunctionNode;
            var child         = functionNode.Params;
            var paramchildren = node.GetChildren();

            while (child != null)
            {
                if (paramchildren == null)
                {
                    throw new AlangExeption(node, $"Too few arguments, in {functionNode.Identifier}. Should have been {functionNode.Params.NumberOfSiblings} number of argument, but was {node.NumberOfChildren}");
                }
                var ShouldBeType = child.Accept(this);
                var actualtype   = paramchildren.Accept(this);

                if (ShouldBeType != actualtype)
                {
                    throw new AlangExeption(node, $"Argument at {paramchildren.Start} is type {actualtype.ToLower()}, but should be {ShouldBeType.ToLower()}");
                }

                child         = child.RightSibling;
                paramchildren = paramchildren.RightSibling;
            }

            if (paramchildren != null)
            {
                throw new AlangExeption(node, $"Too many arguments, in {functionNode.Identifier}. Should have been {functionNode.Params.NumberOfSiblings} number of argument, but was {node.NumberOfChildren}");
            }
            return(functionNode.Type);
        }
 public void VisitFunctionCall(FunctionCallNode node)
 {
     for (int i = 0, ilen = node.Arguments.Count; i < ilen; ++i)
     {
         node.Arguments[i] = _processor.ProcessReplacement(node.Arguments[i]);
     }
 }
Esempio n. 5
0
        public override AssociativeNode VisitFunctionCallNode(FunctionCallNode node)
        {
            if (node == null)
            {
                return(null);
            }

            var func = node.Function.Accept(this);

            if (node.Function != func)
            {
                node.Function = func;
            }

            node.FormalArguments = VisitNodeList(node.FormalArguments);

            if (node.ArrayDimensions != null)
            {
                var newArrayDimensions = node.ArrayDimensions.Accept(this);
                if (node.ArrayDimensions != newArrayDimensions)
                {
                    node.ArrayDimensions = newArrayDimensions as ArrayNode;
                }
            }

            return(node);
        }
Esempio n. 6
0
        private IdentifierListNode GenerateNewIdentifierList(string newNodeName, FunctionCallNode funcCall)
        {
            var newNode = CoreUtils.CreateNodeFromString(newNodeName);

            if (newNode == null)
            {
                return(null);
            }

            // append argument list from original method to newNode
            var newMethodName = ((IdentifierListNode)newNode).RightNode.Name;

            var newMethod = new FunctionCallNode
            {
                Function        = AstFactory.BuildIdentifier(newMethodName),
                FormalArguments = funcCall.FormalArguments
            };
            var newIdentList = new IdentifierListNode
            {
                LeftNode  = ((IdentifierListNode)newNode).LeftNode,
                RightNode = newMethod,
                Optr      = Operator.dot
            };

            return(newIdentList);
        }
Esempio n. 7
0
        private QueryNode FormatSubstringFunction(FunctionCallNode nodeIn)
        {
            this.sql.Append("SUBSTRING(");
            nodeIn.Arguments[0].Accept(this);
            if (nodeIn.Arguments.Count > 1)
            {
                this.sql.Append(", ");

                var constantParam = (ConstantNode)nodeIn.Arguments[1];
                nodeIn.Arguments[1] = new ConstantNode(Convert.ToInt32(constantParam.Value) + 1); //workaround for SQLCe firing exception when simply appending +1 to the query parameter

                nodeIn.Arguments[1].Accept(this);

                if (nodeIn.Arguments.Count > 2)
                {
                    this.sql.Append(", ");
                    nodeIn.Arguments[2].Accept(this);
                }
                else // SQL Substring requires the length, if nothing passed, we grab till the end of string
                {
                    this.sql.Append(", ");
                    this.sql.AppendFormat("LEN(");
                    nodeIn.Arguments[0].Accept(this);
                    this.sql.Append(")");
                }
            }
            this.sql.Append(")");
            return(nodeIn);
        }
        private QueryNode FormatFloorFunction(FunctionCallNode nodeIn)
        {
            // CASE WHEN x >= 0 THEN CAST(id AS INTEGER) // for +ve values cast to integer to drop the decimal places
            //      WHEN CAST(id AS INTEGER) = id THEN id // for integers just return them as they are
            //      ELSE CAST(id - 1.0 AS INTEGER) // for -ve values cast to integer rounds up close to zero
            // END

            var whenXisPositive     = new BinaryOperatorNode(BinaryOperatorKind.GreaterThanOrEqual, nodeIn.Arguments[0], new ConstantNode(0));
            var castToInt           = new ConvertNode(nodeIn.Arguments[0], typeof(int));
            var whenXIsInteger      = new BinaryOperatorNode(BinaryOperatorKind.Equal, castToInt, nodeIn.Arguments[0]);
            var subtractOne         = new BinaryOperatorNode(BinaryOperatorKind.Subtract, nodeIn.Arguments[0], new ConstantNode(1));
            var subtractOneThenCast = new ConvertNode(subtractOne, typeof(int));

            _sql.Append("(CASE WHEN ");
            whenXisPositive.Accept(this);
            _sql.Append(" THEN ");
            castToInt.Accept(this);
            _sql.Append(" WHEN ");
            whenXIsInteger.Accept(this);
            _sql.Append(" THEN ");
            nodeIn.Arguments[0].Accept(this);
            _sql.Append(" ELSE ");
            subtractOneThenCast.Accept(this);
            _sql.Append(" END)");
            return(nodeIn);
        }
        //check if function resoluted has the same arguments type and return type
        public override void Visit(FunctionCallNode node)
        {
            base.Visit(node);

            if (node.Definition == null)
            {
                throw new TypeCheckException("Definition is not resolved.");
            }

            var listOfFunctionCallArguments = node.Arguments.ToList();
            var listOfFunctionArguments     = node.Definition.Parameters.ToList();

            if (listOfFunctionArguments.Count != listOfFunctionCallArguments.Count)
            {
                throw new TypeCheckException("Improper number of arguments.");
            }

            for (int i = 0; i < listOfFunctionArguments.Count; i++)
            {
                if (!listOfFunctionArguments[i].Type.Equals(listOfFunctionCallArguments[i].ExpressionType, false))
                {
                    throw new Exception(String.Format("Argument {0} has improper type.", i));
                }
            }

            node.ExpressionType = node.Definition.ResultType;
        }
Esempio n. 10
0
        public void VisitFunctionCall(FunctionCallNode node)
        {
            // Don't insert unreachable code
            if (!_builder.InsertBlock.IsValid)
            {
                return;
            }

            CodeGeneratorContext.Function func = _genContext.GetFunctionDeclaration(node.LHS);
            Type[] paramTypes = func.FunctionType.ParamTypes;

            Value[] args = new Value[node.Arguments.Count];
            for (int i = 0, ilen = node.Arguments.Count; i < ilen; ++i)
            {
                node.Arguments[i].AcceptExpressionVisitor(this);
                if (!_visitedValue.IsValid)
                {
                    throw new InvalidOperationException("argument did not produce a usable rvalue");
                }

                args[i] = ConvertToType(_visitedValue, paramTypes[i]);
            }

            // Force debug location on call instructions to make ExecutionEngine happy
            SetCurrentDebugLocation(node, true);
            _visitedValue = _builder.BuildCall(func.FunctionValue, args);
            _builder.SetCurrentDebugLocation(Metadata.Null);
        }
        public void ToODataString_EscapesThe_Uri()
        {
            //__updatedat gt datetimeoffset'2014-04-04T07:00:00.0000000+00:00'
            var datetime1 = new ConstantNode(new DateTimeOffset(2014, 4, 4, 7, 0, 0, TimeSpan.FromHours(0)));
            var updatedAt = new MemberAccessNode(null, "__updatedat");
            var gt1       = new BinaryOperatorNode(BinaryOperatorKind.GreaterThan, updatedAt, datetime1);

            // __updatedat gt datetime'2014-04-04T07:0:0.000Z'
            var datetime2 = new ConstantNode(new DateTime(2014, 4, 4, 7, 0, 0, DateTimeKind.Utc));
            var someDate  = new MemberAccessNode(null, "someDate");
            var gt2       = new BinaryOperatorNode(BinaryOperatorKind.GreaterThan, someDate, datetime2);

            // startswith(text,'this&''%%=,?#')
            var text       = new MemberAccessNode(null, "text");
            var value      = new ConstantNode("this&'%%=,?#");
            var startswith = new FunctionCallNode("startswith", new QueryNode[] { text, value });

            //__updatedat gt datetimeoffset'2014-04-04T07:00:00.0000000+00:00' and startswith(text,'this&''%%=,?#')
            var and2 = new BinaryOperatorNode(BinaryOperatorKind.And, gt2, startswith);

            var and1 = new BinaryOperatorNode(BinaryOperatorKind.And, gt1, and2);

            var desc = new MobileServiceTableQueryDescription("someTable")
            {
                Filter = and1
            };

            Assert.AreEqual(desc.ToODataString(), EscapedODataString);
        }
Esempio n. 12
0
 public void VisitFunctionCall(FunctionCallNode node)
 {
     Print($"Function Call (name: {node.LHS.Name}, {node.Arguments.Count} arguments)");
     foreach (IExpressionNode argument in node.Arguments)
     {
         VisitSubnode(argument);
     }
 }
Esempio n. 13
0
        public static void functionCallNode(FunctionCallNode functionCallNode, ActivationFrame activationFrame, VariableDeclarationNode variableToAssignTo)
        {
            IList <Node> functionList = new List <Node>();

            functionList.Add(functionCallNode);
            interpreterCallback.execute(functionList);
            assignReturnValueToVariable(activationFrame, variableToAssignTo);
        }
Esempio n. 14
0
        public override Node visitFunctionCall(JuliarParser.FunctionCallContext ctx)
        {
            FunctionCallNode node = new FunctionCallNode();

            new IterateOverContext(this, ctx, this, node);

            return(node);
        }
Esempio n. 15
0
        private QueryNode FormatDateFunction(string formatSting, FunctionCallNode nodeIn)
        {
            this.sql.AppendFormat("DATEPART({0}, ", formatSting);
            nodeIn.Arguments[0].Accept(this);
            this.sql.Append(")");

            return(nodeIn);
        }
Esempio n. 16
0
        private QueryNode FormatFloorFunction(FunctionCallNode nodeIn)
        {
            this.sql.Append("FLOOR(");
            nodeIn.Arguments[0].Accept(this);
            this.sql.Append(")");

            return(nodeIn);
        }
Esempio n. 17
0
        private QueryNode FormatCeilingFunction(FunctionCallNode nodeIn)
        {
            this.sql.Append("CEILING(");
            nodeIn.Arguments[0].Accept(this);
            this.sql.Append(")");

            return(nodeIn);
        }
        private QueryNode FormatDateFunction(string formatSting, FunctionCallNode nodeIn)
        {
            // CAST(strftime('%d', datetime([__createdAt], 'unixepoch')) AS INTEGER)
            this.sql.AppendFormat("CAST(strftime('{0}', datetime(", formatSting);
            nodeIn.Arguments[0].Accept(this);
            this.sql.Append(", 'unixepoch')) AS INTEGER)");

            return(nodeIn);
        }
        private QueryNode FormatRoundFunction(FunctionCallNode nodeIn)
        {
            this.sql.Append("ROUND(");

            nodeIn.Arguments[0].Accept(this);

            this.sql.Append(", 0)");

            return(nodeIn);
        }
Esempio n. 20
0
 public void Visit(FunctionCallNode functionCall)
 {
     functionCall.Callee.Parent = functionCall;
     functionCall.Callee.Accept(this);
     foreach (var arg in functionCall.Arguments)
     {
         arg.Parent = functionCall;
         arg.Accept(this);
     }
 }
Esempio n. 21
0
 public void visit(FunctionCallNode fcn)
 {
     foreach (BaseCommand bc in commands)
     {
         if (bc.Match(fcn.Name))
         {
             bc.Execute(vm, fcn);
         }
     }
 }
Esempio n. 22
0
 private QueryNode FormatIndexOfFunction(FunctionCallNode nodeIn)
 {
     this.sql.Append("CHARINDEX(");
     nodeIn.Arguments[1].Accept(this);
     this.sql.Append(", ");
     nodeIn.Arguments[0].Accept(this);
     this.sql.Append(")");
     this.sql.Append(" - 1");
     return(nodeIn);
 }
Esempio n. 23
0
        public void ReproMAGN3603()
        {
            string code = @"a = 1 + (2 * 3);
                            b = (1 + 2) * 3;
                            c = 1 + 2 * 3;";

            ElementResolver elementResolver = new ElementResolver();
            ParseParam      parseParam      = new ParseParam(Guid.NewGuid(), code, elementResolver);

            Assert.IsTrue(CompilerUtils.PreCompileCodeBlock(thisTest.CreateTestCore(), ref parseParam));
            Assert.IsTrue(parseParam.ParsedNodes != null && parseParam.ParsedNodes.Count() > 0);

            var parsedNode = parseParam.ParsedNodes.ElementAt(0);

            BinaryExpressionNode n        = parsedNode as BinaryExpressionNode;
            FunctionCallNode     funcCall = n.RightNode as FunctionCallNode;

            Assert.IsTrue(n != null && funcCall != null);
            IdentifierNode identNode = funcCall.Function as IdentifierNode;

            Assert.IsTrue(identNode != null && identNode.Value == "%add");
            var args = funcCall.FormalArguments;

            Assert.IsTrue(args.Count == 2);
            Assert.IsTrue(args[0] is IntNode);
            FunctionCallNode nestedFuncCall = args[1] as FunctionCallNode;

            Assert.IsTrue(nestedFuncCall != null && (nestedFuncCall.Function as IdentifierNode).Value == "%mul");

            parsedNode = parseParam.ParsedNodes.ElementAt(1);

            n        = parsedNode as BinaryExpressionNode;
            funcCall = n.RightNode as FunctionCallNode;
            Assert.IsTrue(n != null && funcCall != null);
            identNode = funcCall.Function as IdentifierNode;
            Assert.IsTrue(identNode != null && identNode.Value == "%mul");
            args = funcCall.FormalArguments;
            Assert.IsTrue(args.Count == 2);
            Assert.IsTrue(args[1] is IntNode);
            nestedFuncCall = args[0] as FunctionCallNode;
            Assert.IsTrue(nestedFuncCall != null && (nestedFuncCall.Function as IdentifierNode).Value == "%add");

            parsedNode = parseParam.ParsedNodes.ElementAt(2);

            n        = parsedNode as BinaryExpressionNode;
            funcCall = n.RightNode as FunctionCallNode;
            Assert.IsTrue(n != null && funcCall != null);
            identNode = funcCall.Function as IdentifierNode;
            Assert.IsTrue(identNode != null && identNode.Value == "%add");
            args = funcCall.FormalArguments;
            Assert.IsTrue(args.Count == 2);
            Assert.IsTrue(args[0] is IntNode);
            nestedFuncCall = args[1] as FunctionCallNode;
            Assert.IsTrue(nestedFuncCall != null && (nestedFuncCall.Function as IdentifierNode).Value == "%mul");
        }
Esempio n. 24
0
        private static FunctionDotCallNode CreateFunctionCallNode(string className, string methodName, List <AssociativeNode> args, Core core)
        {
            FunctionCallNode fNode = new FunctionCallNode();

            fNode.Function        = new IdentifierNode(methodName);
            fNode.FormalArguments = args;

            IdentifierNode inode = new IdentifierNode(className);

            return(CoreUtils.GenerateCallDotNode(inode, fNode, core));
        }
Esempio n. 25
0
        public void VisitFunctionCall(FunctionCallNode node)
        {
            VisitPreOrder(node);

            foreach (IExpressionNode argument in node.Arguments)
            {
                argument.AcceptExpressionVisitor(this);
            }

            VisitPostOrder(node);
        }
Esempio n. 26
0
        public override AstNode VisitFunctioncall(ALangParser.FunctioncallContext context)
        {
            FunctionCallNode node = new FunctionCallNode(context);

            node.Name = context.ID().GetText();
            if (context.inputparams() != null)
            {
                node.AdoptChildren(context.inputparams().Accept(this));
            }
            return(node);
        }
        private QueryNode FormatCeilingFunction(FunctionCallNode nodeIn)
        {
            // floor(x) + (x == floor(x) ? 0 : 1)
            FormatFloorFunction(nodeIn);
            this.sql.Append(" + (CASE WHEN ");
            nodeIn.Arguments[0].Accept(this);
            this.sql.Append(" = ");
            FormatFloorFunction(nodeIn);
            this.sql.Append(" THEN 0 ELSE 1 END)");

            return(nodeIn);
        }
        private QueryNode FormatConcatFunction(FunctionCallNode nodeIn)
        {
            string separator = String.Empty;

            foreach (QueryNode arg in nodeIn.Arguments)
            {
                this.sql.Append(separator);
                arg.Accept(this);
                separator = " || ";
            }
            return(nodeIn);
        }
Esempio n. 29
0
            public Brep.Node Build(FunctionCallNode funCallNode)
            {
                var args = new Brep.Node[funCallNode.Arguments.Count];

                for (var i = 0; i < args.Length; ++i)
                {
                    args[i] = Build(funCallNode.Arguments[i] as dynamic);
                }
                Action <Brep.Node> setter;

                return(funCallNode.Definition.BackendFunction.FunctionCall(funDef.BackendFunction, args, out setter));
            }
Esempio n. 30
0
        public virtual void VisitFunctionCallNode(FunctionCallNode node)
        {
            for (int i = 0; i < node.FormalArguments.Count; ++i)
            {
                node.FormalArguments[i].Accept(this);
            }

            if (node.ArrayDimensions != null)
            {
                node.ArrayDimensions.Accept(this);
            }
        }
        /// <summary>
        /// Process member references.
        /// </summary>
        /// <param name="expression">
        /// The expression to visit.
        /// </param>
        /// <returns>
        /// The visited expression.
        /// </returns>
        private Expression VisitMemberAccess(MemberExpression expression)
        {
            // Lookup the Mobile Services name of the member and use that
            string memberName = GetTableMemberName(expression, this.contractResolver);
            if (memberName != null)
            {
                this.filterExpression.Push(new MemberAccessNode(null, memberName));
                return expression;
            }
            
            // Check if this member is actually a function that looks like a
            // property (like string.Length, etc.)
            string methodName = null;
            MemberInfoKey memberInfoKey = new MemberInfoKey(expression.Member);
            if (InstanceProperties.TryGetValue(memberInfoKey, out methodName))
            {
                var fnCallNode = new FunctionCallNode(methodName, null);
                this.filterExpression.Push(fnCallNode);

                this.Visit(expression.Expression);

                this.SetChildren(fnCallNode);

                return expression;
            }

            // Otherwise we can't process the member.
            throw new NotSupportedException(
                string.Format(
                    CultureInfo.InvariantCulture,
                    "The member '{0}' is not supported in the 'Where' Mobile Services query expression '{1}'.",
                    expression != null && expression.Member != null ? expression.Member.Name : null,
                    expression != null ? expression.ToString() : null));
        }
Esempio n. 32
0
        private void ParseExpression(Node subtree)
        {
            if (tokens.CurrentToken == TokenType.Delim)
                return;
            //shunting yard
            #region Init
            Stack<OperatorNode> opStack = new Stack<OperatorNode>();
            Stack<ExpressionNode> termStack = new Stack<ExpressionNode>();
            Stack<int> argStack = new Stack<int>();
            Func<ExpressionNode, bool> isConstantExpr = new Func<ExpressionNode,bool>(delegate (ExpressionNode e)
            {
                if(e.Children.Count !=1)
                    return false;
                ConstantNode con = e.Children[0] as ConstantNode;
                if(con != null)
                    return true;
                else
                    return false;
            });
            Action popAndMakeExpr = new Action(() =>
                {
                    ExpressionNode newExpr = new ExpressionNode(null);
                    if (opStack.Peek().GetType() == typeof(FunctionCallNode))
                    {
                        Stack<ExpressionNode> paramStack = new Stack<ExpressionNode>(); //since they pop backwards
                        //make a new function node
                        FunctionCallNode funcCall = (FunctionCallNode)opStack.Pop();
                        //whilst we have logged arguments for the current function
                        while (argStack.Peek() != 0)
                        {
                            //take each arg and pop it to the stack.
                            paramStack.Push(termStack.Pop());
                            int val  = argStack.Pop();
                            argStack.Push(--val);
                        }
                        //okay no more args
                        FunctionCallParamListNode paramList = new FunctionCallParamListNode(funcCall);
                        foreach (ExpressionNode expr in paramStack)
                            paramList.AddChild(expr);
                        newExpr.AddChild(funcCall);
                        //look up the function with the given arguments
                        funcCall.Function = FunctionTable.Lookup(funcCall.Ident, funcCall.Children[0].Children);
                        argStack.Pop();
                    }
                    else
                    {
                        ExpressionNode term2 = termStack.Pop();
                        ExpressionNode term1 = termStack.Pop();
                        OperatorNode tempOpNode = opStack.Pop();
                        if (term1.Type != term2.Type)
                        {
                            ErrorHandler.RaiseError(new Error(tokens.CurrentToken.LineNo,
                                "Cannot form expression with types: " + term1.Type + " and " + term2.Type));
                        }
                        newExpr.Type = term1.Type;
                        //code folding
                        if (isConstantExpr(term1) && isConstantExpr(term2))
                        {
                            newExpr.AddChild(OpTable.Calculate((ConstantNode)term1.Children[0], (ConstantNode)term2.Children[0],
                                tempOpNode.Op));
                        }
                        else
                        {
                            newExpr.AddChild(term1);
                            newExpr.AddChild(tempOpNode);
                            newExpr.AddChild(term2);
                        }
                    }
                    termStack.Push(newExpr);
                });
            #endregion
            //welp
            while (true)
            {
                if (tokens.CurrentToken == TokenType.Type && tokens.NextToken == TokenType.Ident)
                {
                    ErrorHandler.RaiseError(new Error(tokens.CurrentToken.LineNo, "likely a missing delimiter"));
                    break;
                }
                //Ident
                if (tokens.CurrentToken == TokenType.Ident)
                {
                    if (argStack.Count > 0 && argStack.Peek() == 0)
                    {
                        argStack.Pop();
                        argStack.Push(1);
                    }
                    //Ident(..), also known as a function call
                    if (tokens.NextToken == TokenType.LeftParen)
                    {
                        FunctionCallNode funcCall = new FunctionCallNode(null); //ew
                        OperatorNode paren = new OperatorNode(null);
                        paren.Op = TokenType.LeftParen;
                        funcCall.Ident = tokens.CurrentToken.Value;
                        opStack.Push(funcCall);
                        opStack.Push(paren);
                        argStack.Push(0);
                        tokens.Next();
                    }
                    else
                    {
                        ExpressionNode termNode = new ExpressionNode(null); //parentless for now
                        VariableNode var = new VariableNode(termNode);
                        var.Ident = tokens.CurrentToken.Value;
                        var = SymbolTable.Lookup(var.Ident);
                        termNode.Type = var.Type;
                        termStack.Push(termNode);
                    }
                    //op time
                }
                else if (tokens.CurrentToken == TokenType.StringLiteral || tokens.CurrentToken == TokenType.False
                    || tokens.CurrentToken == TokenType.True || tokens.CurrentToken == TokenType.Number)
                {
                    if (argStack.Count > 0 && argStack.Peek() == 0)
                    {
                        argStack.Pop();
                        argStack.Push(1);
                    }
                    ExpressionNode term = new ExpressionNode(null);
                    switch (tokens.CurrentToken.Type)
                    {
                        case TokenType.StringLiteral:
                            ConstantNode<string> stringNode = new ConstantNode<string>(term);
                            stringNode.Value = tokens.CurrentToken.Value;
                            term.Type = "String";
                            termStack.Push(term);
                            break;
                        case TokenType.False:
                        case TokenType.True:
                            ConstantNode<bool> boolNode = new ConstantNode<bool>(term);
                            boolNode.Value = (tokens.CurrentToken == TokenType.True ? true : false);
                            term.Type = "Bool";
                            termStack.Push(term);
                            break;
                        case TokenType.Number:
                            int val;
                            if (Int32.TryParse(tokens.CurrentToken.Value, out val))
                            {
                                ConstantNode<int> intNode = new ConstantNode<int>(term);
                                intNode.Value = val;
                                term.Type = "Int";
                                termStack.Push(term);
                            }
                            else
                            {
                                ConstantNode<double> doubleNode = new ConstantNode<double>(term);
                                doubleNode.Value = double.Parse(tokens.CurrentToken.Value);
                                term.Type = "Double";
                                termStack.Push(term);
                            }
                            break;

                    }
                }
                //operator
                else if (OpTable.ExpressionOperators.Contains(tokens.CurrentToken))
                {
                    OperatorNode opNode = new OperatorNode(null);
                    opNode.Op = tokens.CurrentToken.Type;
                    while (opStack.Count != 0 && OpTable.Precedence(opStack.Peek().Op)
                        >= OpTable.Precedence(opNode.Op))
                    {
                        popAndMakeExpr();
                    }
                    opStack.Push(opNode);
                }
                //right paren
                else if (tokens.CurrentToken == TokenType.RightParen)
                {
                    while (opStack.Peek().Op != TokenType.LeftParen && opStack.Count != 0)
                    {
                        popAndMakeExpr();
                    }

                    if (opStack.Count == 0)
                        ErrorHandler.RaiseError(new Error(tokens.CurrentToken.LineNo, "mismatched brackets"));
                    opStack.Pop();
                    if (opStack.Peek().GetType() == typeof(FunctionCallNode)) //function call
                    {
                        popAndMakeExpr();
                    }
                }
                //left paren
                else if (tokens.CurrentToken == TokenType.LeftParen)
                {
                    OperatorNode node = new OperatorNode(null);
                    node.Op = TokenType.LeftParen;
                    opStack.Push(node);
                }
                else if (tokens.CurrentToken == TokenType.Comma)
                {
                    if (argStack.Count == 0)
                    {
                        ErrorHandler.RaiseError(new Error(tokens.CurrentToken.LineNo,
                            "found a comma outside of a function"));
                    }
                    while (opStack.Peek().Op != TokenType.LeftParen && opStack.Count != 0)
                    {
                        popAndMakeExpr();
                    }

                    if (opStack.Count == 0)
                        ErrorHandler.RaiseError(new Error(tokens.CurrentToken.LineNo, "mismatched brackets"));
                    //opStack.Pop();
                    int args = argStack.Pop();
                    argStack.Push(++args);
                }
                else if (tokens.CurrentToken == TokenType.Delim)
                {
                    tokens.Next();
                    break;
                }
                //delim, colon, error, etc
                else
                {
                    ErrorHandler.RaiseError(new UnexpectedTokenError(tokens.CurrentToken,
                        "part of an expression or a delim", tokens.CurrentToken.LineNo));
                }
                tokens.Next();
            }

            //clean up
            while (termStack.Count > 1 && opStack.Count > 0 && opStack.Peek().Op != TokenType.LeftParen)
            {
                if (opStack.Count == 0)
                {
                    ErrorHandler.RaiseError(new Error(tokens.CurrentToken.LineNo, "Not enough operators, or missing a delim."));
                    break;
                }
                popAndMakeExpr();
            }
            if(opStack.Count > 0 && opStack.Peek().Op == TokenType.LeftParen)
            {
                ErrorHandler.RaiseError(new Error(tokens.CurrentToken.LineNo, "bracket problems, or too many ops"));
            }
            string type = ((TypedNode)termStack.Peek().Children[0]).Type;
            termStack.Peek().Type = type;
            subtree.AddChild(termStack.Pop());
            //okay we hit a delim
            return;
        }
        /// <summary>
        /// Process method calls which map one-to-one on an odata supported method.
        /// </summary>
        /// <param name="expression">
        /// The expression to visit.
        /// </param>
        /// <param name="methodName">
        /// The name of the method to look for.
        /// </param>
        /// <param name="isStatic">
        /// Indicates if the method to look for is static.
        /// </param>
        /// <returns>
        /// The visited expression.
        /// </returns>
        private void VisitODataMethodCall(MethodCallExpression expression, string methodName, bool isStatic)
        {
            Debug.Assert(expression != null, "expression cannot be null!");
            Debug.Assert(methodName != null, "methodName cannot be null!");
            
            var fnCallNode = new FunctionCallNode(methodName, null);

            // adding node as a marker for start of arguments
            this.filterExpression.Push(fnCallNode);

            foreach (Expression argument in GetFilterMethodArguments(expression, methodName, isStatic))
            {
                this.Visit(argument);
            }

            SetChildren(fnCallNode);
        }
        public void ToODataString_EscapesThe_Uri()
        {

            //updatedat gt datetimeoffset'2014-04-04T07:00:00.0000000+00:00'
            var datetime1 = new ConstantNode(new DateTimeOffset(2014, 4, 4, 7, 0, 0, TimeSpan.FromHours(0)));
            var updatedAt = new MemberAccessNode(null, "updatedat");
            var gt1 = new BinaryOperatorNode(BinaryOperatorKind.GreaterThan, updatedAt, datetime1);

            // updatedat gt datetime'2014-04-04T07:0:0.000Z'
            var datetime2 = new ConstantNode(new DateTime(2014, 4, 4, 7, 0, 0, DateTimeKind.Utc));
            var someDate = new MemberAccessNode(null, "someDate");
            var gt2 = new BinaryOperatorNode(BinaryOperatorKind.GreaterThan, someDate, datetime2);

            // startswith(text,'this&''%%=,?#')
            var text = new MemberAccessNode(null, "text");
            var value = new ConstantNode("this&'%%=,?#");
            var startswith = new FunctionCallNode("startswith", new QueryNode[] { text, value });

            //updatedat gt datetimeoffset'2014-04-04T07:00:00.0000000+00:00' and startswith(text,'this&''%%=,?#')
            var and2 = new BinaryOperatorNode(BinaryOperatorKind.And, gt2, startswith);

            var and1 = new BinaryOperatorNode(BinaryOperatorKind.And, gt1, and2);

            var desc = new MobileServiceTableQueryDescription("someTable") { Filter = and1 };
            Assert.AreEqual(desc.ToODataString(), EscapedODataString);
        }
Esempio n. 35
0
        private static void GenerateFunctionCall(FunctionCallNode node, DataContext data)
        {
            bool shouldCallInvoke = !(node.FunctionExpression is MemberAccessNode);

            if (shouldCallInvoke)
                Append(data, "Invoke(context, ");

            GenerateExpression(node.FunctionExpression, data);

            if (!shouldCallInvoke)
                Append(data, "(");

            for (int i = 0; i < node.Args.Count; i++)
            {
                if (i != 0 || shouldCallInvoke)
                    Append(data, ", ");

                GenerateExpression(node.Args[i], data);
            }

            Append(data, ")");
        }
Esempio n. 36
0
 public FunctionCallNode(FunctionCallNode rhs) : base(rhs)
 {
     Function = ProtoCore.Utils.NodeUtils.Clone(rhs.Function);
     FormalArguments = new List<ImperativeNode>();
     foreach (ImperativeNode argNode in rhs.FormalArguments)
     {
         ImperativeNode tempNode = ProtoCore.Utils.NodeUtils.Clone(argNode);
         FormalArguments.Add(tempNode);
     }
 }