示例#1
0
 private void WriteFunctionCallExp(FunctionCallExpression functioncall, StringBuilder programBuilder)
 {
     foreach (var id in registerFile.listofFunctions)
     {
         if (id == functioncall.Id)
         {
             recursive = true; break;
         }
     }
     if (recursive == false)
     {
         for (int i = 0; i < functioncall.Parameters.Exprlist.Count; i++)
         {
             WriteExpr(functioncall.Parameters.Exprlist[i], registerFile, programBuilder);
         }
         programBuilder.AppendLine("\t pop ebp");
     }
     else
     {
         foreach (var param in functioncall.Parameters.Exprlist)
         {
             WriteExpr(param, registerFile, programBuilder);
         }
     }
 }
示例#2
0
        public void TestReplaceVariablesIndexFunctionCall()
        {
            var functionDefinition = UserFunctionDefinitionExpression.ParseForTest("function func(i) => 6");

            var functionCall = new FunctionCallExpression("func", new ExpressionBase[] { new IntegerConstantExpression(2) });
            var value        = new IntegerConstantExpression(98);

            var variable = new VariableExpression("variable");
            var dict     = new DictionaryExpression();

            dict.Add(new IntegerConstantExpression(6), value);

            var scope = new InterpreterScope();

            scope.AssignVariable(variable, dict);
            scope.AddFunction(functionDefinition);

            var expr = new IndexedVariableExpression(variable, functionCall);

            ExpressionBase result;

            Assert.That(expr.ReplaceVariables(scope, out result), Is.True);
            Assert.That(result, Is.InstanceOf <IntegerConstantExpression>());
            Assert.That(((IntegerConstantExpression)result).Value, Is.EqualTo(98));
        }
示例#3
0
        public override bool ReplaceVariables(InterpreterScope scope, out ExpressionBase result)
        {
            if (!base.ReplaceVariables(scope, out result))
            {
                return(false);
            }

            var func = result as FunctionCallExpression;

            if (func == null)
            {
                return(true);
            }

            var when = GetParameter(scope, "when", out result);

            if (result != null)
            {
                return(false);
            }

            var format = GetStringParameter(scope, "format", out result);

            if (result != null)
            {
                return(false);
            }

            result = new FunctionCallExpression(Name.Name, new ExpressionBase[] { func.Parameters.First(), when, format });
            CopyLocation(result);

            return(true);
        }
示例#4
0
        /// <summary>
        /// 处理函数调用
        /// </summary>
        /// <returns></returns>
        private FunctionCallExpression ParseFunctionCall()
        {
            Tokens.MoveToNext();
            var function = new FunctionCallExpression(Tokens.Current.Position)
            {
                Target = ParseBinaryOperator(GeneralParser(TokenType.String, TokenType.Number, TokenType.PluginCallStart, TokenType.Variable, TokenType.Constant, TokenType.LeftParenthesis))
            };

            while (Tokens.Current.Type != TokenType.LineBreak && Tokens.Current.Type != TokenType.RightParenthesis)
            {
                var parameter = new ParameterExpression(Tokens.Current.Position)
                {
                    Name = ParseBinaryOperator(
                        GeneralParser(TokenType.String, TokenType.Number, TokenType.PluginCallStart, TokenType.Variable, TokenType.Constant, TokenType.LeftParenthesis),
                        0,
                        TokenType.Equal)
                };
                if (Tokens.Current.Type != TokenType.Equal)
                {
                    throw new CompileException(Identifier, Tokens.Current.Position, "Function call parameters must have value");
                }
                Tokens.MoveToNext();
                parameter.Value = ParseBinaryOperator(GeneralParser(
                                                          TokenType.String, TokenType.Number, TokenType.PluginCallStart, TokenType.Variable, TokenType.Constant, TokenType.LeftParenthesis, TokenType.LogicNot));
                function.Parameters.Add(parameter);
            }
            return(function);
        }
示例#5
0
        public void FunctionCallExpression4()
        {
            var e = new FunctionCallExpression("f", new [] { (Expression) new Literal("x"), new StringLiteral("y") });

            Assert.IsFalse(e.IsTrivial);
            Assert.AreEqual("f(x, \"y\")", e.ToString());
        }
        public string Visit(FunctionCallExpression call)
        {
            var codeWriter = new XzaarCodeWriter();
            var indent     = isInsideExpression ? 0 : currentIndent;
            var instance   = call.GetInstance();

            if (instance != null)
            {
                codeWriter.Write(Visit(instance));
                codeWriter.Write("." + call.MethodName + "(");
            }
            else
            {
                codeWriter.Write(call.MethodName + "(", indent);
            }

            for (int index = 0; index < call.Arguments.Count; index++)
            {
                var arg = call.Arguments[index];
                codeWriter.Write(Visit(arg));
                if (index + 1 < call.ArgumentCount)
                {
                    codeWriter.Write(", ");
                }
            }

            codeWriter.Write(")");
            if (!isInsideExpression)
            {
                codeWriter.NewLine();
            }
            return(codeWriter.ToString());
        }
示例#7
0
        private static FunctionCallExpression GetFunctionCallExpression(string identifier, List <ExpressionNode> children, List <int> globalReferences)
        {
            FunctionCallExpression functionCallExpression = new FunctionCallExpression(identifier, children, 0, 0);

            functionCallExpression.GlobalReferences = globalReferences;
            return(functionCallExpression);
        }
        public static void ShouldParseNoArgumentsCall()
        {
            var expected = new FunctionCallExpression("b", Enumerable.Empty <LuaExpression>());
            var actual   = Helpers.ParseExpression("b()");

            Assert.AreEqual(expected, actual);
        }
示例#9
0
        public void TestReplaceVariablesIndexFunctionCall()
        {
            var input     = "function func(i) => 6";
            var tokenizer = new PositionalTokenizer(Tokenizer.CreateTokenizer(input));

            tokenizer.Match("function");
            var functionDefinition = (FunctionDefinitionExpression)FunctionDefinitionExpression.Parse(tokenizer);

            var functionCall = new FunctionCallExpression("func", new ExpressionBase[] { new IntegerConstantExpression(2) });
            var value        = new IntegerConstantExpression(98);

            var variable = new VariableExpression("variable");
            var dict     = new DictionaryExpression();

            dict.Entries.Add(new DictionaryExpression.DictionaryEntry {
                Key = new IntegerConstantExpression(6), Value = value
            });

            var scope = new InterpreterScope();

            scope.AssignVariable(variable, dict);
            scope.AddFunction(functionDefinition);

            var expr = new IndexedVariableExpression(variable, functionCall);

            ExpressionBase result;

            Assert.That(expr.ReplaceVariables(scope, out result), Is.True);
            Assert.That(result, Is.InstanceOf <IntegerConstantExpression>());
            Assert.That(((IntegerConstantExpression)result).Value, Is.EqualTo(98));
        }
        public void TestReplaceVariablesMethodCall()
        {
            var functionDefinition = UserFunctionDefinitionExpression.ParseForTest("function func(i) { j = i }");

            var functionCall = new FunctionCallExpression("func", new ExpressionBase[] { new IntegerConstantExpression(2) });
            var value1       = new IntegerConstantExpression(98);
            var expr         = new DictionaryExpression();

            expr.Add(functionCall, value1);

            var scope = new InterpreterScope();

            scope.AddFunction(functionDefinition);

            ExpressionBase result;

            Assert.That(expr.ReplaceVariables(scope, out result), Is.False);
            Assert.That(result, Is.InstanceOf <ParseErrorExpression>());
            var parseError = (ParseErrorExpression)result;

            while (parseError.InnerError != null)
            {
                parseError = parseError.InnerError;
            }
            Assert.That(parseError.Message, Is.EqualTo("func did not return a value"));
        }
        public void TestEvaluateDictionaryByReference()
        {
            // ensures the dictionary is passed by reference to func(), so it can be modified
            // within func(). it's also much more efficient to pass the dictionary by reference
            // instead of evaluating it (which creates a copy).
            var functionDefinition = Parse("function func(d) { d[\"key\"] = 2 }");
            var scope = new InterpreterScope();

            scope.AddFunction(functionDefinition);

            var dict = new DictionaryExpression();

            dict.Add(new StringConstantExpression("key"), new IntegerConstantExpression(1));
            scope.AssignVariable(new VariableExpression("dict"), dict);

            var functionCall = new FunctionCallExpression("func", new ExpressionBase[] { new VariableExpression("dict") });

            ExpressionBase result;

            Assert.That(functionCall.Evaluate(scope, out result), Is.True);
            Assert.That(result, Is.Null);

            Assert.That(dict.Count, Is.EqualTo(1));
            Assert.That(dict[0].Value, Is.InstanceOf <IntegerConstantExpression>());
            Assert.That(((IntegerConstantExpression)dict[0].Value).Value, Is.EqualTo(2));
        }
示例#12
0
        public override bool ReplaceVariables(InterpreterScope scope, out ExpressionBase result)
        {
            var comparison = GetParameter(scope, "comparison", out result);

            if (comparison == null)
            {
                return(false);
            }

            var condition = comparison as ConditionalExpression;

            if (condition != null && condition.Operation == ConditionalOperation.Or)
            {
                ExpressionBase left = new FunctionCallExpression(Name.Name, new ExpressionBase[] { condition.Left });
                if (!left.ReplaceVariables(scope, out result))
                {
                    return(false);
                }
                left = result;

                ExpressionBase right = new FunctionCallExpression(Name.Name, new ExpressionBase[] { condition.Right });
                if (!right.ReplaceVariables(scope, out result))
                {
                    return(false);
                }
                right = result;

                result = new ConditionalExpression(left, ConditionalOperation.And, right);
                return(true);
            }

            return(base.ReplaceVariables(scope, out result));
        }
示例#13
0
        private string EvaluateError(string formatString, ExpressionBase[] parameters)
        {
            var newParameters = new List <ExpressionBase>();

            newParameters.Add(new StringConstantExpression(formatString));
            newParameters.AddRange(parameters);

            var expression = new FunctionCallExpression("format", newParameters);
            var scope      = new InterpreterScope();

            scope.AddFunction(new FormatFunction());
            scope.AddFunction(new AddFunction());

            ExpressionBase result;

            Assert.That(expression.Evaluate(scope, out result), Is.False);

            Assert.That(result, Is.InstanceOf <ParseErrorExpression>());
            var parseError = (ParseErrorExpression)result;

            while (parseError.InnerError != null)
            {
                parseError = parseError.InnerError;
            }
            return(parseError.Message);
        }
示例#14
0
        public void TestReplaceVariablesMethodCall()
        {
            var input     = "function func(i) { j = i }";
            var tokenizer = new PositionalTokenizer(Tokenizer.CreateTokenizer(input));

            tokenizer.Match("function");
            var functionDefinition = (FunctionDefinitionExpression)FunctionDefinitionExpression.Parse(tokenizer);

            var functionCall = new FunctionCallExpression("func", new ExpressionBase[] { new IntegerConstantExpression(2) });
            var value1       = new IntegerConstantExpression(98);
            var expr         = new DictionaryExpression();

            expr.Entries.Add(new DictionaryExpression.DictionaryEntry {
                Key = functionCall, Value = value1
            });

            var scope = new InterpreterScope();

            scope.AddFunction(functionDefinition);

            ExpressionBase result;

            Assert.That(expr.ReplaceVariables(scope, out result), Is.False);
            Assert.That(result, Is.InstanceOf <ParseErrorExpression>());
            Assert.That(((ParseErrorExpression)result).Message, Is.EqualTo("func did not return a value"));
        }
示例#15
0
        public void TestReplaceVariablesFunctionCall()
        {
            var input     = "function func(i) => 6";
            var tokenizer = new PositionalTokenizer(Tokenizer.CreateTokenizer(input));

            tokenizer.Match("function");
            var functionDefinition = (FunctionDefinitionExpression)FunctionDefinitionExpression.Parse(tokenizer);

            var functionCall = new FunctionCallExpression("func", new ExpressionBase[] { new IntegerConstantExpression(2) });
            var value1       = new IntegerConstantExpression(98);
            var expr         = new DictionaryExpression();

            expr.Entries.Add(new DictionaryExpression.DictionaryEntry {
                Key = functionCall, Value = value1
            });

            var scope = new InterpreterScope();

            scope.AddFunction(functionDefinition);

            ExpressionBase result;

            Assert.That(expr.ReplaceVariables(scope, out result), Is.True);
            Assert.That(result, Is.InstanceOf <DictionaryExpression>());
            var dictResult = (DictionaryExpression)result;

            Assert.That(dictResult.Entries.Count, Is.EqualTo(1));
            Assert.That(dictResult.Entries[0].Key, Is.EqualTo(new IntegerConstantExpression(6)));
            Assert.That(dictResult.Entries[0].Value, Is.EqualTo(value1));
        }
示例#16
0
        private void CheckFunctionCallExpression(FunctionCallExpression e, TypeCheckingContext context)
        {
            for (int i = 0; i <= e.Parameters.Length - 1; i++)
            {
                PerformTypeChecking(e.Parameters[i], context);
            }

            Type[] parameterClasses = e.Parameters.Select(i => i.Type).ToArray();
            if (e.MethodName == "Loop" || e.MethodName.Contains("MCM") || e.MethodName.Contains("Draw_"))
            {
                var list = parameterClasses.ToList();
                list.Add(typeof(object));
                parameterClasses = list.ToArray();
            }
            e.Method = context.VariableContext.SearchMethod(e.MethodName, null, parameterClasses);

            if (e.Method == null)
            {
                var coe = LocalRepo.Coefficients.FirstOrDefault(m => m.CoefficientName == e.MethodName);
                if (coe != null)
                {
                    context.VariableContext.Set(e.MethodName, LocalRepo.CoefficientDetails.Where(m => m.CoefficientID == coe.CoefficientID).ToList());
                    e.Method       = this.GetType().GetMethods()[0]; //模拟一个方法
                    e.IsCustomFunc = true;
                }
                else
                {
                    e.IsCustomFunc = false;
                }
                if (!e.IsCustomFunc)
                {
                    StringBuilder list = new StringBuilder();
                    foreach (Type type in parameterClasses)
                    {
                        list.Append(type).Append(",");
                    }

                    list.Remove(list.Length - 1, 1);


                    StringBuilder locations = new StringBuilder();
                    foreach (Type type in context.VariableContext.GetMethodExtenders())
                    {
                        locations.Append(type).Append("\r\n");
                    }
                    context.ErrorProvider.ThrowException(string.Format("Method {0}({1}) cannot be found.\r\nSearched the following locations:\r\n{2}",
                                                                       e.MethodName,
                                                                       list,
                                                                       locations), e);
                }
            }
            e.Type = e.Method.ReturnType;
            context.LambdaContext.PushCallerMethod(e);
            for (int i = 0; i <= e.Parameters.Length - 1; i++)
            {
                PerformTypeChecking(e.Parameters[i], context);
            }

            context.LambdaContext.PopCallerMethod();
        }
示例#17
0
 public void Visit(FunctionCallExpression expression)
 {
     Visit(expression.Function);
     Write("(");
     expression.Parameters.DoBetween(Visit, (n, p) => Write(", "));
     Write(")");
 }
        public TypeNode VisitFunctionCall(FunctionCallExpression funcCallExpNode, List <TypeNode> parameterTypes)
        {
            TypeNode res;

            if (IsLocalReferenceAMatch(funcCallExpNode, parameterTypes))
            {
                funcCallExpNode.GlobalReferences = new List <int>();
                FunctionTypeNode funcDeclType = (FunctionTypeNode)parameterTypes[funcCallExpNode.LocalReference];
                res = funcDeclType.ReturnType;
            }
            else
            {
                List <int> matchingRefs = funcCallExpNode.GlobalReferences;
                CheckMatches(funcCallExpNode.Children, matchingRefs, parameterTypes);
                if (matchingRefs.Count > 1)
                {
                    throw new OverloadException(funcCallExpNode, GetFunctions(matchingRefs));
                }
                else if (matchingRefs.Count == 0)
                {
                    throw new NoMatchingFunctionFoundException(funcCallExpNode);
                }

                funcCallExpNode.LocalReference   = FunctionCallExpression.NO_LOCAL_REF;
                funcCallExpNode.GlobalReferences = matchingRefs;
                res = _functions[matchingRefs.First()].FunctionType.ReturnType;
            }

            return(res);
        }
示例#19
0
        public void TestPopComparison()
        {
            var scope = new InterpreterScope();

            var array    = new ArrayExpression();
            var funcCall = new FunctionCallExpression("happy", new ExpressionBase[] { new IntegerConstantExpression(1) });

            array.Entries.Add(new ComparisonExpression(funcCall, ComparisonOperation.Equal, new IntegerConstantExpression(2)));
            scope.DefineVariable(new VariableDefinitionExpression("arr"), array);

            var happyFunc = new FunctionDefinitionExpression("happy");

            happyFunc.Parameters.Add(new VariableDefinitionExpression("num1"));
            happyFunc.Expressions.Add(new ReturnExpression(new VariableExpression("num1")));
            scope.AddFunction(happyFunc);

            var entry = Evaluate("array_pop(arr)", scope);

            Assert.That(entry, Is.InstanceOf <ComparisonExpression>());

            var comparison = (ComparisonExpression)entry;

            Assert.That(comparison.Left, Is.InstanceOf <FunctionCallExpression>());
            Assert.That(((FunctionCallExpression)comparison.Left).FunctionName.Name, Is.EqualTo("happy"));
            Assert.That(comparison.Right, Is.InstanceOf <IntegerConstantExpression>());
            Assert.That(((IntegerConstantExpression)comparison.Right).Value, Is.EqualTo(2));
        }
示例#20
0
        public void Reduce_FunctionWithConstantParameters()
        {
            _runtime
            .Setup(mock => mock.FindAndCall("f",
                                            It.Is <IExecutionContext>(context =>
                                                                      context.Line == 0 &&
                                                                      context.Column == 0 &&
                                                                      context.Count == 2 &&
                                                                      context[0].Equals(new IntValue(1)) &&
                                                                      context[1].Equals(new IntValue(2))
                                                                      )))
            .Returns(new IntValue(3));

            var expr =
                new FunctionCallExpression(0, 0, "f", new []
            {
                new ConstantExpression(0, 1, new IntValue(1)),
                new ConstantExpression(0, 3, new IntValue(2)),
            });
            var reduced = expr.Accept(_visitor);

            Assert.IsInstanceOfType(reduced, typeof(ConstantExpression));

            var constant = (ConstantExpression)reduced;

            Assert.AreEqual(new IntValue(3), constant.Value);
            Assert.AreEqual(0, constant.Line);
            Assert.AreEqual(0, constant.Column);
        }
        public override Expression Reduce(Expression root, ExpressionReductor reductor)
        {
            if (!(root is FunctionCallExpression))
            {
                return(root);
            }


            FunctionCallExpression func = root as FunctionCallExpression;

            if (func.MethodName == "pow")
            {
                if (func.Parameters[1].IsConstant(1))
                {
                    return(func.Parameters[0]);
                }
                else if (func.Parameters[1].IsConstant(0))
                {
                    return(ConstantExpression.create(1, 0, 0));
                }
            }



            return(root);
        }
示例#22
0
        public override bool ReplaceVariables(InterpreterScope scope, out ExpressionBase result)
        {
            var name = GetStringParameter(scope, "name", out result);

            if (name == null)
            {
                return(false);
            }

            var format = GetStringParameter(scope, "format", out result);

            if (format == null)
            {
                return(false);
            }

            var valueFormat = Leaderboard.ParseFormat(format.Value);

            if (valueFormat == ValueFormat.None)
            {
                result = new ParseErrorExpression(format.Value + " is not a supported rich_presence_value format", format);
                return(false);
            }

            var expression = GetParameter(scope, "expression", out result);

            if (expression == null)
            {
                return(false);
            }

            result = new FunctionCallExpression(Name.Name, new ExpressionBase[] { name, expression, format });
            CopyLocation(result);
            return(true);
        }
示例#23
0
        public void FunctionCallExpression2()
        {
            var e = new FunctionCallExpression("", new Expression[0]);

            Assert.IsFalse(e.IsTrivial);
            Assert.AreEqual("()", e.ToString());
        }
 public TypeNode Dispatch(ExpressionNode node, List <TypeNode> parameterTypes)
 {
     return(node switch
     {
         IBinaryNumberOperator n => _numberHelper.VisitBinaryNumOp(n, parameterTypes),
         IBinaryBooleanOperator n => _booleanHelper.VisitBinaryBoolOp(n, parameterTypes),
         IBinarySetOperator n => _setHelper.VisitBinarySetOp(n, parameterTypes),
         SubsetExpression n => _setHelper.VisitSubset(n, parameterTypes),
         SetExpression n => _setHelper.VisitSet(n, parameterTypes),
         NotExpression n => _booleanHelper.VisitNot(n, parameterTypes),
         FunctionCallExpression n => _declarationHelper.VisitFunctionCall(n, parameterTypes),
         IdentifierExpression n => _declarationHelper.VisitIdentifier(n, parameterTypes),
         IntegerLiteralExpression _ => _declarationHelper.VisitIntegerLiteral(),
         RealLiteralExpression _ => _declarationHelper.VisitRealLiteral(),
         BooleanLiteralExpression _ => _declarationHelper.VisitBooleanLiteral(),
         StringLiteralExpression _ => _declarationHelper.VisitStringLiteral(),
         EmptySetLiteralExpression _ => _declarationHelper.VisitEmptySetLiteral(),
         AdditionExpression n => _commonOperatorHelper.VisitAddition(n, parameterTypes),
         SubtractionExpression n => _commonOperatorHelper.VisitSubtraction(n, parameterTypes),
         AbsoluteValueExpression n => _commonOperatorHelper.VisitAbsoluteValue(n, parameterTypes),
         IRelationOperator n => _commonOperatorHelper.VisitRelationalOperator(n, parameterTypes),
         IEquivalenceOperator n => _commonOperatorHelper.VisitEquivalenceOperator(n, parameterTypes),
         NegativeExpression n => _numberHelper.VisitNegative(n, parameterTypes),
         ElementExpression n => _commonOperatorHelper.VisitElement(n, parameterTypes),
         ISetGraphField n => _commonOperatorHelper.VisitISetGraphField(n, parameterTypes),
         IFunctionGraphField n => _commonOperatorHelper.VisitIFunctionGraphField(n, parameterTypes),
         GraphExpression n => _commonOperatorHelper.VisitGraph(n, parameterTypes),
         AnonymousFunctionExpression n => _declarationHelper.VisitAnonymousFunction(n, parameterTypes),
         _ => throw new UnimplementedTypeCheckerException(node, "Dispatch"),
     });
        private DatabaseReference GetDatabaseReference(FunctionCallExpression fc, SyntaxNode location, ClusterSymbol defaultCluster)
        {
            if (fc.ReferencedSymbol == Functions.Database &&
                TryGetConstantStringArgumentValue(fc, 0, out var databaseName))
            {
                location = location ?? fc.ArgumentList.Expressions[0].Element;

                string cluster;

                // get cluster name from explicit cluster reference (if possible)
                if (!(fc.Parent is PathExpression p &&
                      p.Selector == fc &&
                      p.Expression is FunctionCallExpression fcCluster &&
                      fcCluster.ReferencedSymbol == Functions.Cluster &&
                      TryGetConstantStringArgumentValue(fcCluster, 0, out cluster)))
                {
                    // otherwise use the default cluster
                    cluster = defaultCluster.Name;
                }

                return(new DatabaseReference(databaseName, cluster, location.TextStart, location.Width));
            }

            return(null);
        }
示例#26
0
        /// <summary>
        /// Parses while a certain condition matches.
        /// </summary>
        /// <param name="source">Source enumerator.</param>
        /// <param name="functionName">Function used to get the name of the function that should be called.</param>
        /// <param name="upper">Previous function to get the arguments from.</param>
        /// <param name="condition">Checks whether the token type of the current token matches the current.</param>
        /// <param name="error">Output error string.</param>
        /// <returns>Instance of a class that implements IExpression.</returns>
        private static IExpression ParseWhile(this IEnumerator <Token> source,
                                              UpperDelegate upper,
                                              Func <TokenType, string> functionName,
                                              Predicate <TokenType> condition,
                                              out string error)
        {
            var left = upper(source, out error);

            if (condition((TokenType)source.Current) && left is null)
            {
                return(null);
            }

            while (condition((TokenType)source.Current))
            {
                var type = (TokenType)source.Current;
                source.MatchAndEat(type, out error);

                var right = upper(source, out error);
                if (right is null)
                {
                    error = "Expected right side of the expression.";
                    return(null);
                }

                left = new FunctionCallExpression(functionName(type), left, right);
            }

            return(left);
        }
示例#27
0
        public override bool ReplaceVariables(InterpreterScope scope, out ExpressionBase result)
        {
            var count = GetIntegerParameter(scope, "count", out result);

            if (count == null)
            {
                return(false);
            }

            var varargs = GetParameter(scope, "varargs", out result) as ArrayExpression;

            if (varargs == null)
            {
                if (!(result is ParseErrorExpression))
                {
                    result = new ParseErrorExpression("unexpected varargs", count);
                }
                return(false);
            }

            var parameters = new List <ExpressionBase>();

            parameters.Add(count);

            // special case - if there's a single array parameter, assume it's a list of conditions
            if (varargs.Entries.Count == 1)
            {
                var arrayExpression = varargs.Entries[0] as ArrayExpression;
                if (arrayExpression == null)
                {
                    var referenceExpression = varargs.Entries[0] as VariableReferenceExpression;
                    if (referenceExpression != null)
                    {
                        arrayExpression = referenceExpression.Expression as ArrayExpression;
                    }
                }
                if (arrayExpression != null)
                {
                    varargs = arrayExpression;
                }
            }

            var tallyScope = new InterpreterScope(scope);

            tallyScope.Context = this;

            foreach (var entry in varargs.Entries)
            {
                if (!entry.ReplaceVariables(tallyScope, out result))
                {
                    return(false);
                }

                parameters.Add(result);
            }

            result = new FunctionCallExpression(Name.Name, parameters.ToArray());
            CopyLocation(result);
            return(true);
        }
示例#28
0
        private Expression CompileFunctionCall(string functionName, int lambdaLevel)
        {
            List <Expression> parameters = new List <Expression>();

            while (!End)
            {
                if (IsPunctuationOf(")"))
                {
                    Move();
                    break;
                }

                parameters.Add(Compile(lambdaLevel));
                if (IsPunctuationOf(","))
                {
                    Move();
                }
                else if (!IsPunctuationOf(")"))
                {
                    ThrowExpects(")");
                }
            }


            FunctionCallExpression func = new FunctionCallExpression(functionName, parameters.ToArray(), PeekPos(), Pos);

            PopPosition();
            return(func);
        }
示例#29
0
        public string Visit(FunctionCallExpression call)
        {
            var codeWriter       = new XzaarCodeWriter();
            var indent           = IsInsideExpression ? 0 : currentIndent;
            var instance         = call.GetInstance();
            var methodInvocation = call.MethodName + "(";
            var instanceText     = string.Empty;

            if (instance != null)
            {
                instanceText = instance is VariableDefinitionExpression instanceExpr
                    ? instanceExpr.Name + "."
                    : Visit(instance) + ".";
            }
            codeWriter.Write(instanceText + methodInvocation, indent);

            insideExpressionCount++;

            for (int index = 0; index < call.Arguments.Count; index++)
            {
                var arg = call.Arguments[index];
                codeWriter.Write(Visit(arg));
                if (index + 1 < call.ArgumentCount)
                {
                    codeWriter.Write(", ");
                }
            }
            insideExpressionCount--;
            codeWriter.Write(")");
            if (!IsInsideExpression)
            {
                codeWriter.NewLine();
            }
            return(codeWriter.ToString());
        }
示例#30
0
        public ParseErrorExpression CallFunction(FunctionCallExpression functionCall, InterpreterScope scope)
        {
            var functionDefinition = scope.GetFunction(functionCall.FunctionName.Name);

            if (functionDefinition == null)
            {
                return(new UnknownVariableParseErrorExpression("Unknown function: " + functionCall.FunctionName.Name, functionCall.FunctionName));
            }

            var triggerBuilderFunction = functionDefinition as FunctionDefinition;

            if (triggerBuilderFunction == null)
            {
                return(new ParseErrorExpression(functionCall.FunctionName.Name + " cannot be called from within a trigger clause", functionCall));
            }

            var error = triggerBuilderFunction.BuildTrigger(this, scope, functionCall);

            if (error != null)
            {
                return(ParseErrorExpression.WrapError(error, "Function call failed.", functionCall));
            }

            return(null);
        }
        public override LuaExpression Parse(INextAwareEnumerator<Token> reader, IParserContext context)
        {
            var name = reader.Current.Value;
            reader.MoveNext();
            reader.VerifyExpectedToken(LuaToken.LeftBracket);

            var parametersParser = new ExpressionListParser();

            var expression = new FunctionCallExpression(name, parametersParser.Parse(reader, context).ToList());
            reader.VerifyExpectedToken(LuaToken.RightBracket);
            return expression;
        }
示例#32
0
        public void VisitFunctionCallExpression(FunctionCallExpression functionCallExpression)
        {
            VisitExpression(functionCallExpression.Target);

            ReturnValue = null;

            foreach (Expression s in functionCallExpression.Arguments) {
                VisitExpression(s);
            }

            ReturnValue = null;
        }