/// <summary>
        /// Checks function call expressions for correct number of parameters.
        /// </summary>
        /// <param name="semActs">The semantic analyser</param>
        /// <param name="exp">The functioncallexpression</param>
        private SemanticCheckResult CheckFunctionCall(SemActs semActs, FunctionCallExpr exp)
        {
            var functionName = exp.ToQualifiedName();
            var exists       = exp.SymScope.IsFunction(functionName);

            // 1. Function does not exist.
            if (!exists)
            {
                return(AddErrorCode(ErrorCodes.Func1000, exp, functionName));
            }
            var sym  = exp.SymScope.GetSymbol(functionName) as SymbolFunction;
            var func = sym.FuncExpr as FunctionExpr;

            // 5. Check that named parameters exist.
            foreach (var argExpr in exp.ParamListExpressions)
            {
                if (argExpr.IsNodeType(NodeTypes.SysNamedParameter))
                {
                    var argName = ((NamedParameterExpr)argExpr).Name;
                    if (!func.Meta.ArgumentsLookup.ContainsKey(argName))
                    {
                        AddErrorCode(ErrorCodes.Func1002, exp, argName);
                    }
                }
            }
            return(SemanticCheckResult.Valid);
        }
Example #2
0
 public override Expression Substitute(Expression expr)
 {
     if (expr is FunctionCallExpr)
     {
         FunctionCallExpr  e        = (FunctionCallExpr)expr;
         Expression        receiver = Substitute(e.Receiver);
         List <Expression> newArgs  = SubstituteExprList(e.Args);
         FunctionCallExpr  newFce   = new FunctionCallExpr(expr.tok, e.Name, receiver, e.OpenParen, newArgs, e.AtLabel);
         if (e.Function == A)
         {
             newFce.Function = B;
             newFce.Type     = e.Type; // TODO: this may not work with type parameters.
         }
         else
         {
             newFce.Function = e.Function;
             newFce.Type     = e.Type;
         }
         newFce.TypeApplication_AtEnclosingClass = e.TypeApplication_AtEnclosingClass; // resolve here
         newFce.TypeApplication_JustFunction     = e.TypeApplication_JustFunction;     // resolve here
         newFce.IsByMethodCall = e.IsByMethodCall;
         return(newFce);
     }
     return(base.Substitute(expr));
 }
Example #3
0
        /// <summary>
        /// Parse the expression.
        /// </summary>
        /// <returns></returns>
        public override Expr Parse()
        {
            var  printToken = _tokenIt.NextToken;
            var  lineToken  = _tokenIt.AdvanceAndGet <Token>();
            Expr lineExp    = null;

            if (lineToken.Kind == TokenKind.Multi)
            {
                lineExp = _parser.ParseInterpolatedExpression(lineToken);
            }
            else
            {
                lineExp = new ConstantExpr(lineToken.Value);
            }

            var exp = new FunctionCallExpr();

            exp.NameExp = new VariableExpr("print");
            exp.ParamListExpressions.Add(lineExp);
            _parser.SetScriptPosition(exp, printToken);

            // Move past this plugin.
            _tokenIt.Advance();
            return(exp);
        }
        private static object ToNumberFunction(string s, string s1, FunctionCallExpr arg3)
        {
            double d;

            double.TryParse(arg3.ParamList[0].ToString(), NumberStyles.Any, CultureInfo.CurrentCulture, out d);
            return(d);
        }
Example #5
0
        /// <summary>
        /// Prints to the console.
        /// </summary>
        /// /// <param name="settings">Settings for interpreter</param>
        /// <param name="exp">The functiona call expression</param>
        /// <param name="printline">Whether to print with line or no line</param>
        public static string Print(FunctionCallExpr exp)
        {
            string message = LogHelper.BuildMessage(exp.ParamList);

            Console.WriteLine(message);
            return(message);
        }
Example #6
0
            public void FunctionCallCallsVisitOnAllParametersPassedTest()
            {
                var target = new EvaluateVisitor();

                var functionName     = RandomGenerator.String();
                var functionNameExpr = new IdentifierExpr(functionName);

                var parameters = new[]
                {
                    new VarDefinitionStmt(new IdentifierExpr("A"), new IdentifierExpr("INT"), false, new ConstantExpr(1)),
                    new VarDefinitionStmt(new IdentifierExpr("B"), new IdentifierExpr("STRING"), false, new ConstantExpr("TEST")),
                    new VarDefinitionStmt(new IdentifierExpr("C"), new IdentifierExpr("BOOL"), false, new ConstantExpr(true))
                };

                var values = new Expression[]
                {
                    new ConstantExpr(1),
                    new ConstantExpr(RandomGenerator.String()),
                    new ConstantExpr(true)
                };

                var returnValue = values[1];

                var functionDefinition = new FunctionDefinitionExpr(functionNameExpr, parameters,
                                                                    new ScopeBlockStmt(new[] { new ReturnStmt(returnValue) }), new IdentifierExpr("String"));

                var expr = new FunctionCallExpr(functionNameExpr, values);

                _scope.DefineIdentifier(functionName, Value.FromObject(functionDefinition));

                var actual = target.Visit(expr, _scope);

                Assert.AreEqual(((ConstantExpr)returnValue).Value, actual.ToObject());
            }
 private static object BetweenFunction(string arg1, string arg2, FunctionCallExpr arg3)
 {
     if (arg3.ParamList.Count == 0)
     {
         return(int.MaxValue);
     }
     return(int.MaxValue);
 }
Example #8
0
 /// <summary>
 /// Visits the function call expression tree
 /// </summary>
 /// <param name="exp"></param>
 public void FunctionCall(FunctionCallExpr exp)
 {
     _callBack(exp);
     foreach (var paramExp in exp.ParamListExpressions)
     {
         _callBack(paramExp);
     }
 }
            public void FunctionNamePropertyReturnsPassedName()
            {
                var name      = new IdentifierExpr(RandomGenerator.String());
                var arguments = new Expression[] { new ConstantExpr(RandomGenerator.Int()), new ConstantExpr(RandomGenerator.Int()) };

                var target = new FunctionCallExpr(name, arguments);

                Assert.AreSame(name.Name, target.FunctionName.Name);
            }
            public void FunctionNamePropertyReturnsPassedName()
            {
                var name = new IdentifierExpr(RandomGenerator.String());
                var arguments = new Expression[] { new ConstantExpr(RandomGenerator.Int()), new ConstantExpr(RandomGenerator.Int()) };

                var target = new FunctionCallExpr(name, arguments);

                Assert.AreSame(name.Name, target.FunctionName.Name);
            }
        private static object FixFormatFunction(string s, string s1, FunctionCallExpr args)
        {
            double d;

            double.TryParse(args.ParamList[0].ToString(), NumberStyles.Any, CultureInfo.CurrentCulture, out d);
            var fmt = args.ParamList.Count > 1 ? args.ParamList[1].ToString() : "#,#0.00";

            return(d.ToString(fmt));
        }
Example #12
0
        /// <summary>
        /// Evauate and run the function
        /// </summary>
        /// <returns></returns>
        public object VisitFunctionCall(FunctionCallExpr expr)
        {
            object result = null;

            // CASE 1: Exp is variable -> internal/external script. "getuser()".
            if (expr.NameExp.IsNodeType(NodeTypes.SysVariable))
            {
                return(FunctionHelper.CallFunction(this.Ctx, expr, null, true, this));
            }

            // At this point, is a method call on an object.
            var member = expr.NameExp.Evaluate(this);

            result = member;
            var isMemberAccessType = member is MemberAccess;

            if (!isMemberAccessType)
            {
                return(result);
            }

            var callStackName = expr.NameExp.ToQualifiedName();
            var maccess       = member as MemberAccess;

            if (!IsMemberCall(maccess))
            {
                return(result);
            }

            this.Ctx.State.Stack.Push(callStackName, expr);
            // CASE 2: Module.Function
            if (maccess.Mode == MemberMode.FunctionScript && maccess.Expr != null)
            {
                var fexpr         = maccess.Expr as FunctionExpr;
                var resolveParams = !expr.RetainEvaluatedParams;
                result = FunctionHelper.CallFunctionInScript(this.Ctx, this, fexpr.Meta.Name, fexpr, expr.ParamListExpressions, expr.ParamList, resolveParams);
            }
            // CASE 3: object "." method call from script is a external/internal function e.g log.error -> external c# callback.
            else if (maccess.IsInternalExternalFunctionCall())
            {
                result = FunctionHelper.CallFunction(Ctx, expr, maccess.FullMemberName, false, this);
            }
            // CASE 4: Method call / Property on Language types
            else if (maccess.Type != null)
            {
                result = FunctionHelper.CallMemberOnBasicType(this.Ctx, expr, maccess, expr.ParamListExpressions, expr.ParamList, this);
            }
            // CASE 5: Member call via "." : either static or instance method call. e.g. Person.Create() or instance1.FullName() e.g.
            else if (maccess.Mode == MemberMode.CustObjMethodStatic || maccess.Mode == MemberMode.CustObjMethodInstance)
            {
                result = FunctionHelper.CallMemberOnClass(this.Ctx, expr, maccess, expr.ParamListExpressions, expr.ParamList, this);
            }
            // Pop the function name off the call stack.
            this.Ctx.State.Stack.Pop();
            return(result);
        }
Example #13
0
        /// <summary>
        /// Calls the custom function.
        /// </summary>
        /// <param name="name">Name of the function</param>
        /// <param name="exp"></param>
        /// <returns></returns>
        public object Call(string name, FunctionCallExpr exp)
        {
            var callback = GetByName(name);

            // 1. Resolve parameter froms expressions into Lang values.
            ParamHelper.ResolveParametersToHostLangValues(exp.ParamListExpressions, exp.ParamList);
            object result = callback(exp);

            return(result);
        }
Example #14
0
        /// <summary>
        /// Checks function call expressions for correct number of parameters.
        /// </summary>
        /// <param name="semActs">The semantic analyser</param>
        /// <param name="exp">The functioncallexpression</param>
        private void CheckFunctionCall(SemActs semActs, FunctionCallExpr exp)
        {
            var func = _ctx.Functions.GetByName(exp.Name);

            // 1. Number of params
            if (func.Meta.Arguments.Count < exp.ParamListExpressions.Count)
            {
                AddError("Function parameters do not match", exp);
            }
        }
Example #15
0
 /// <summary>
 /// Visits the function call expression tree
 /// </summary>
 /// <param name="exp"></param>
 public object VisitFunctionCall(FunctionCallExpr exp)
 {
     _callBackOnNodeStart(exp);
     foreach (var paramExp in exp.ParamListExpressions)
     {
         _callBackOnNodeStart(paramExp);
     }
     _callBackOnNodeEnd(exp);
     return(null);
 }
Example #16
0
        /// <summary>
        /// Creates a function call expression.
        /// </summary>
        /// <param name="nameExpr"></param>
        /// <param name="parameters"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static Expr FunctionCall(Expr nameExpr, List <Expr> parameters, TokenData token)
        {
            var funcExp = new FunctionCallExpr();

            funcExp.NameExp = nameExpr;
            funcExp.ParamListExpressions = parameters == null ? new List <Expr>() : parameters;
            funcExp.ParamList            = new List <object>();
            SetupContext(funcExp, token);
            return(funcExp);
        }
        public string GenerateString(FunctionCallExpr expression)
        {
            var self       = expression.tok.val;
            var open       = expression.OpenParen.val;
            var rightNames = expression.Args.Select(a => GenerateString(a));
            var right      = String.Join(", ", rightNames);
            var close      = ")";

            return(self + open + right + close);
        }
Example #18
0
            public void FunctionCallWithEmptyScopeTest()
            {
                var target = new EvaluateVisitor();

                var functionName           = RandomGenerator.String();
                var calledFunctionNameExpr = new IdentifierExpr(functionName);

                var expr = new FunctionCallExpr(calledFunctionNameExpr, new Expression[0]);

                target.Visit(expr, _scope);
            }
            public void AcceptMethodCallsOnlyVisitOnVisitorWithThisAndNoOtherVisitMethods()
            {
                var name = new IdentifierExpr(RandomGenerator.String());
                var arguments = new Expression[] { new ConstantExpr(RandomGenerator.Int()), new ConstantExpr(RandomGenerator.Int()) };

                var target = new FunctionCallExpr(name, arguments);
                // throw exception is any other methods called other than the PlusExpr overload.
                var visitor = new Mock<IExpressionVisitor<string, int>>(MockBehavior.Strict);
                visitor.Setup(x => x.Visit(target, 123)).Returns("");

                target.Accept(visitor.Object, 123);
            }
        public FunctionCallExpr BuildFuncCallExpr(Context ctx, string varName, string memName, List <object> args)
        {
            var exp    = new FunctionCallExpr();
            var memExp = new MemberAccessExpr(new VariableExpr(varName), memName, false);

            memExp.Ctx = ctx;
            ((VariableExpr)memExp.VariableExp).Ctx = ctx;
            exp.NameExp   = memExp;
            exp.ParamList = args;
            exp.Ctx       = ctx;
            return(exp);
        }
Example #21
0
        /// <summary>
        /// Push the function expression on the call stack
        /// </summary>
        /// <param name="qualifiedName">Name of function call</param>
        /// <param name="exp">Function Call expression</param>
        public bool Push(string qualifiedName, FunctionCallExpr exp)
        {
            _stack.Add(new Tuple <string, FunctionCallExpr>(qualifiedName, exp));
            _lastIndex++;

            if (_limitCheck != null)
            {
                _limitCheck(exp, _lastIndex);
            }

            return(true);
        }
Example #22
0
            public void FunctionCallOnNonFunctionTest()
            {
                var target = new EvaluateVisitor();

                var functionNameExpr = new IdentifierExpr(RandomGenerator.String());

                var expr = new FunctionCallExpr(functionNameExpr, new Expression[0]);

                _scope.DefineIdentifier(functionNameExpr.Name, Value.FromObject(RandomGenerator.String()));

                target.Visit(expr, _scope);
            }
            public void AcceptMethodCallsVisitOnVisitorWithThis()
            {
                var name = new IdentifierExpr(RandomGenerator.String());
                var arguments = new Expression[] { new ConstantExpr(RandomGenerator.Int()), new ConstantExpr(RandomGenerator.Int()) };

                var target = new FunctionCallExpr(name, arguments);
                var visitor = new Mock<IExpressionVisitor<string, int>>();

                target.Accept(visitor.Object, 0);

                visitor.Verify(x => x.Visit(target, 0), Times.Once);
            }
            public void AcceptMethodCallsVisitOnVisitorWithThis()
            {
                var name      = new IdentifierExpr(RandomGenerator.String());
                var arguments = new Expression[] { new ConstantExpr(RandomGenerator.Int()), new ConstantExpr(RandomGenerator.Int()) };

                var target  = new FunctionCallExpr(name, arguments);
                var visitor = new Mock <IExpressionVisitor <string, int> >();

                target.Accept(visitor.Object, 0);

                visitor.Verify(x => x.Visit(target, 0), Times.Once);
            }
Example #25
0
        /// <summary>
        /// Logs severity to console.
        /// </summary>
        /// <param name="settings">Settings for interpreter</param>
        /// <param name="exp">The functiona call expression</param>
        public static string Log(LangSettings settings, FunctionCallExpr exp)
        {
            if (!settings.EnableLogging)
            {
                return(string.Empty);
            }
            var funcname = exp.ToQualifiedName();
            var severity = funcname.Substring(funcname.IndexOf(".") + 1);
            var message  = BuildMessage(exp.ParamList);

            Console.WriteLine(severity.ToUpper() + " : " + message);
            return(message);
        }
            public void AcceptMethodCallsOnlyVisitOnVisitorWithThisAndNoOtherVisitMethods()
            {
                var name      = new IdentifierExpr(RandomGenerator.String());
                var arguments = new Expression[] { new ConstantExpr(RandomGenerator.Int()), new ConstantExpr(RandomGenerator.Int()) };

                var target = new FunctionCallExpr(name, arguments);
                // throw exception is any other methods called other than the PlusExpr overload.
                var visitor = new Mock <IExpressionVisitor <string, int> >(MockBehavior.Strict);

                visitor.Setup(x => x.Visit(target, 123)).Returns("");

                target.Accept(visitor.Object, 123);
            }
Example #27
0
        /// <summary>
        /// Calls an internal function or external function.
        /// </summary>
        /// <param name="ctx">The context of the runtime.</param>
        /// <param name="fexpr">The function call expression</param>
        /// <param name="functionName">The name of the function. if not supplied, gets from the fexpr</param>
        /// <param name="pushCallStack"></param>
        /// <returns></returns>
        public static object CallFunction(Context ctx, FunctionCallExpr fexpr, string functionName, bool pushCallStack, IAstVisitor visitor)
        {
            if (string.IsNullOrEmpty(functionName))
            {
                functionName = fexpr.NameExp.ToQualifiedName();
            }

            // 1. Check if script func or extern func.
            var isScriptFunc = fexpr.SymScope.IsFunction(functionName);
            var isExternFunc = ctx.ExternalFunctions.Contains(functionName);

            // 2. If neither, this is an error scenario.
            if (!isScriptFunc && !isExternFunc)
            {
                throw ExceptionHelper.BuildRunTimeException(fexpr, "Function does not exist : '" + functionName + "'");
            }

            // 3. Push the name of the function on teh call stack
            if (pushCallStack)
            {
                ctx.State.Stack.Push(functionName, fexpr);
            }

            // 4. Call the function.
            object result = null;

            // Case 1: Custom C# function blog.create blog.*
            if (isExternFunc)
            {
                result = FunctionHelper.CallFunctionExternal(ctx, visitor, functionName, fexpr);
            }

            // Case 2: Script functions "createUser('john');"
            else
            {
                var sym           = fexpr.SymScope.GetSymbol(functionName) as SymbolFunction;
                var func          = sym.FuncExpr as FunctionExpr;
                var resolveParams = !fexpr.RetainEvaluatedParams;
                result = FunctionHelper.CallFunctionInScript(ctx, visitor, functionName, func, fexpr.ParamListExpressions,
                                                             fexpr.ParamList, resolveParams);
            }
            // 3. Finnaly pop the call stact.
            if (pushCallStack)
            {
                ctx.State.Stack.Pop();
            }

            result = CheckConvert(result);
            return(result);
        }
Example #28
0
        /// <summary>
        /// Logs a call to the console.
        /// </summary>
        /// <param name="exp"></param>
        public void Log(FunctionCallExpr exp)
        {
            var settings = this.Ctx.Settings;

            if (!settings.EnablePrinting)
            {
                return;
            }

            var funcname = exp.ToQualifiedName();
            var severity = funcname.Substring(funcname.IndexOf(".") + 1);
            var message  = BuildMessage(exp.ParamList);

            Console.WriteLine(severity.ToUpper() + " : " + message);
        }
Example #29
0
            public void FunctionCallWithNoReturnStatementTest()
            {
                var target = new EvaluateVisitor();

                var functionName       = RandomGenerator.String();
                var functionNameExpr   = new IdentifierExpr(functionName);
                var returnValue        = RandomGenerator.String();
                var functionDefinition = new FunctionDefinitionExpr(functionNameExpr, new VarDefinitionStmt[0], new ScopeBlockStmt(new[] { new NoOpStatement() }), new IdentifierExpr("String"));

                var expr = new FunctionCallExpr(functionNameExpr, new Expression[0]);

                _scope.DefineIdentifier(functionName, Value.FromObject(functionDefinition));

                target.Visit(expr, _scope);
            }
Example #30
0
        /// <summary>
        /// Prints a line to the console.
        /// </summary>
        /// <param name="exp"></param>
        public void PrintLn(FunctionCallExpr exp)
        {
            var settings = this.Ctx.Settings;

            if (!settings.EnablePrinting)
            {
                return;
            }

            string message = BuildMessage(exp.ParamList);

            if (settings.EnablePrinting)
            {
                Console.WriteLine(message);
            }
        }
Example #31
0
            public void LambdaCallTest()
            {
                var target = new EvaluateVisitor();

                var functionName       = RandomGenerator.String();
                var functionNameExpr   = new IdentifierExpr(functionName);
                var returnValue        = RandomGenerator.String();
                var functionDefinition = new LambdaDefinitionExpr(functionNameExpr, new VarDefinitionStmt[0], new ConstantExpr(returnValue), new IdentifierExpr("String"));

                var expr = new FunctionCallExpr(functionNameExpr, new Expression[0]);

                _scope.DefineIdentifier(functionName, Value.FromObject(functionDefinition));

                var actual = target.Visit(expr, _scope);

                Assert.AreEqual(returnValue, actual.ToObject());
            }
Example #32
0
            public void FunctionCallOnUndefinedFuncTest()
            {
                var target = new EvaluateVisitor();

                var functionName            = RandomGenerator.String();
                var definedFunctionNameExpr = new IdentifierExpr(functionName);
                var calledFunctionNameExpr  = new IdentifierExpr(functionName + "UNDEFINED");
                var returnValue             = RandomGenerator.String();

                var functionDefinition = new FunctionDefinitionExpr(definedFunctionNameExpr, new VarDefinitionStmt[0],
                                                                    new ScopeBlockStmt(new[] { new ReturnStmt(new ConstantExpr(returnValue)) }), new IdentifierExpr("String"));

                var expr = new FunctionCallExpr(calledFunctionNameExpr, new Expression[0]);

                _scope.DefineIdentifier(functionName, Value.FromObject(functionDefinition));

                target.Visit(expr, _scope);
            }
Example #33
0
        public DataElement Visit(FunctionCallExpr expr)
        {
            // evaluate all of the call arguments
            // this may emit instructions and allocate locals
            var arguments = EvaluateArguments(expr.CallStmt.Arguments);

            // insert local and =() right before the actual function call
            var local = AllocateLocal();

            Emit(new TargetInstruction(local, _instructions));
            EmitCall("=");

            // emit the call instruction
            EmitCall(expr.CallStmt.MethodName, arguments);

            // return the local the functions result is written to
            return(local);
        }
            public void FunctionCallCallsVisitOnAllParametersPassedTest()
            {
                var target = new EvaluateVisitor();

                var functionName = RandomGenerator.String();
                var functionNameExpr = new IdentifierExpr(functionName);

                var parameters = new[]
                {
                    new VarDefinitionStmt(new IdentifierExpr("A"), new IdentifierExpr("INT"), false, new ConstantExpr(1)),
                    new VarDefinitionStmt(new IdentifierExpr("B"), new IdentifierExpr("STRING"), false, new ConstantExpr("TEST")),
                    new VarDefinitionStmt(new IdentifierExpr("C"), new IdentifierExpr("BOOL"), false, new ConstantExpr(true))
                };

                var values = new Expression[]
                {
                    new ConstantExpr(1),
                    new ConstantExpr(RandomGenerator.String()),
                    new ConstantExpr(true)
                };

                var returnValue = values[1];

                var functionDefinition = new FunctionDefinitionExpr(functionNameExpr, parameters,
                    new ScopeBlockStmt(new[] { new ReturnStmt(returnValue) }), new IdentifierExpr("String"));

                var expr = new FunctionCallExpr(functionNameExpr, values);

                _scope.DefineIdentifier(functionName, Value.FromObject(functionDefinition));

                var actual = target.Visit(expr, _scope);

                Assert.AreEqual(((ConstantExpr)returnValue).Value, actual.ToObject());
            }
Example #35
0
 void CompileFunctionCallExpr(FunctionCallExpr e, TextWriter twr, TextWriter wr, bool inLetExprBody, FCE_Arg_Translator tr) {
    Function f = cce.NonNull(e.Function);
    if (f.IsStatic) {
      twr.Write(TypeName_Companion(e.Receiver.Type, wr));
    } else {
      twr.Write("(");
      tr(e.Receiver, wr, inLetExprBody);
      twr.Write(")");
    }
    twr.Write(".@{0}", f.CompileName);
    if (f.TypeArgs.Count != 0) {
        List<Type> typeArgs = f.TypeArgs.ConvertAll(ta => e.TypeArgumentSubstitutions[ta]);
        twr.Write("<" + TypeNames(typeArgs, wr) + ">");
    }
    twr.Write("(");
    string sep = "";
    for (int i = 0; i < e.Args.Count; i++) {
      if (!e.Function.Formals[i].IsGhost) {
        twr.Write(sep);
        tr(e.Args[i], wr);
        sep = ", ";
      }
    }
    twr.Write(")");
  }
Example #36
0
        void CompileFunctionCallExpr(FunctionCallExpr e, bool inLetExprBody)
        {
            Contract.Requires(e != null && e.Function != null);
              Function f = e.Function;

              if (f.TypeArgs.Count != 0) {
            j.WriteComment("BUGBUG CompileFunctionCallExpr support for TypeArgs"); // bugbug: implement
              }

              using (WriteArray()) {
            j.WriteValue(KremlinAst.EApp); // of (expr * expr list)
            using (WriteArray()) {
              // expr1: Function to call
              using (WriteArray()) {
            var old = j.Formatting;
            j.Formatting = Formatting.None;
            j.WriteValue(KremlinAst.EQualified);
            WriteLident(f);
            j.Formatting = old;
              }
              // expr2: list of arguments
              using (WriteArray()) {
            for (int i = 0; i < e.Args.Count; i++) {
              if (!e.Function.Formals[i].IsGhost) {
                TrExpr(e.Args[i], inLetExprBody);
              }
            }
              }
            }
              }
        }
Example #37
0
 public Tuple<Method,TypeApply> GetSeqBuildMethod(Type t, SeqTree tree, List<bool> elemDimensions)
 {
     
     
     if (elemDimensions.Count == 0)
     {
         return GetSeqMethod(t, "seq_Empty");
     }
     if (elemDimensions.Count == 2 && elemDimensions[0] && elemDimensions[1])
     {
         return GetSeqMethod(t, "seq_Append");
     }
     string op = "seq_" + SeqTree.TreeName(tree);
     DatatypeDecl seqDecl = FindDatatype("Seq");
     var tok = new Bpl.Token(0, 0);
     tok.filename = @"!\Seq.dfy";
     TypeApply tApp = Compile_SeqType((SeqType)t);
     Type dataType = new UserDefinedType(tok, "Seq", seqDecl, new List<Type> { ((SeqType)t).Arg });
     Type elemType = ((SeqType)t).Arg;
     Func<string,Type,Expression> idExpr = (x, typ) => {
         var e = new IdentifierExpr(tok, x);
         e.Type = typ;
         e.Var = new LocalVariable(tok, tok, x, typ, false);
         return e;
     };
     Func<string,List<Expression>,FunctionCallExpr> seqCall = (x, args) => {
         var seqOp = GetSeqOperation(t, x);
         FunctionCallExpr callExpr = new FunctionCallExpr(
             tok, "Seq_Empty", new ThisExpr(tok), tok, args);
         callExpr.Function = seqOp.Item1;
         callExpr.TypeArgumentSubstitutions = seqOp.Item2.typeArgs;
         return callExpr;
     };
     Expression empty = seqCall("Seq_Empty", new List<Expression> {});
     int varCount = 0;
     Func<SeqTree,Expression> resultRec = null;
     resultRec = (subtree) =>
     {
         if (subtree == null)
         {
             return idExpr("s" + (varCount++), dataType);
         }
         if (subtree.buildCount >= 0)
         {
             Expression build = empty;
             for (int i = 0; i < subtree.buildCount; i++)
             {
                 build = seqCall("Seq_Build", new List<Expression>
                     { build, idExpr("a" + (varCount++), elemType) });
             }
             return build;
         }
         else
         {
             return seqCall("Seq_Append", new List<Expression>
                 { resultRec(subtree.left), resultRec(subtree.right) });
         }
     };
     Expression result = resultRec(tree);
     Expression post = seqCall("Seq_Equal", new List<Expression> { idExpr("s", dataType), result });
     List<Statement> stmts = new List<Statement>();
     for (int i = elemDimensions.Count; i > 0;)
     {
         bool isFirst = (i == elemDimensions.Count);
         i--;
         if (elemDimensions[i])
         {
             if (isFirst)
             {
                 
                 stmts.Add(new AssignStmt(tok, tok, idExpr("s", dataType),
                     new ExprRhs(idExpr("s" + i, dataType))));
             }
             else
             {
                 // s := seq_Append(s9, s);
                 var selectExpr = new MemberSelectExpr(tok, new ThisExpr(tok), "seq_Append");
                 selectExpr.Member = FindMethod(selectExpr.MemberName);  // Manually resolve here
                 selectExpr.TypeApplication = new List<Type>() { elemType }; // Manually resolve here
                 selectExpr.Type = new InferredTypeProxy();  // Manually resolve here
                 
                 CallStmt callStmt = new CallStmt(tok, tok,
                     new List<Expression> {idExpr("s", dataType)},
                     selectExpr, new List<Expression>
                         { idExpr("s" + i, dataType), idExpr("s", dataType) });                                                        
                 stmts.Add(callStmt);
             }
         }
         else
         {
             if (isFirst)
             {
                 
                 DatatypeValue nil = new DatatypeValue(tok, "Seq", "Nil", new List<Expression>() {});
                 nil.Type = dataType;
                 nil.InferredTypeArgs = new List<Type> { elemType };
                 nil.Ctor = seqDecl.Ctors[0];
                 Util.Assert(nil.Ctor.Name == "Seq_Nil");
                 stmts.Add(new AssignStmt(tok, tok, idExpr("s", dataType), new ExprRhs(nil)));
             }
             // lemma_Seq_Cons(ai, s);
             var selectExpr = new MemberSelectExpr(tok, new ThisExpr(tok), "lemma_Seq_Cons");                
             selectExpr.Member = FindMethod(selectExpr.MemberName);   // Manually resolve here
             selectExpr.TypeApplication = new List<Type>() { elemType }; // Manually resolve here
             selectExpr.Type = new InferredTypeProxy();  // Manually resolve here
             
             CallStmt callStmt = new CallStmt(tok, tok,
                 new List<Expression> {},
                 selectExpr, new List<Expression>
                     { idExpr("a" + i, elemType), idExpr("s", dataType) });                                
             callStmt.IsGhost = true;
             stmts.Add(callStmt);
             
             DatatypeValue cons = new DatatypeValue(tok, "Seq", "Cons", new List<Expression>()
                 { idExpr("a" + i, elemType), idExpr("s", dataType) });
             cons.Type = dataType;
             cons.InferredTypeArgs = new List<Type> { elemType };
             cons.Ctor = seqDecl.Ctors[1];
             Util.Assert(cons.Ctor.Name == "Seq_Cons");
             stmts.Add(new AssignStmt(tok, tok, idExpr("s", dataType), new ExprRhs(cons)));
         }
     }
     BlockStmt body = new BlockStmt(tok, tok, stmts);
     List<Formal> ins = new List<Formal>();
     for (int i = 0; i < elemDimensions.Count; i++)
     {
         bool isSeq = elemDimensions[i];
         ins.Add(new Formal(tok, (isSeq ? "s" : "a") + i, isSeq ? dataType : elemType, true, false));
     }
     List<Formal> outs = new List<Formal> { new Formal(tok, "s", dataType, false, false) };
     List<MaybeFreeExpression> reqs = new List<MaybeFreeExpression>();
     List<MaybeFreeExpression> enss = new List<MaybeFreeExpression> { new MaybeFreeExpression(post) };
     Specification<FrameExpression> mods = new Specification<FrameExpression>(new List<FrameExpression>(), null);
     Specification<Expression> decs = new Specification<Expression>(new List<Expression>(), null);
     Attributes attrs = new Attributes("dafnycc_conservative_seq_triggers", new List<Expression>(), null);
     Method m = new Method(tok, op, true, false, tApp.typeParams, ins, outs, reqs, mods, enss, decs, body, attrs, tok);
     m.EnclosingClass = GetSeqMethod(t, "seq_Append").Item1.EnclosingClass;
     return Tuple.Create(m, Compile_Method(m, tApp.typeArgs));
 }
Example #38
0
    public override void Compile_FunctionAsMethod(Function function, Dictionary<TypeParameter,Type> typeArgs,
        Dictionary<string,TypeParameter> substArgs)
    {
        var tok = function.tok;
        if (Attributes.Contains(function.Attributes, "CompiledSpec"))
        {
            
            
            string specName = function.Name.Substring("CompiledSpec_".Length);
            function = FindFunction(specName);
        }
        bool hidden = Attributes.Contains(function.Attributes, "opaque");
        Formal result = new Formal(function.tok, "__result", function.ResultType, false, function.IsGhost);
        string funName = function.Name;
        string name = FunName(DafnySpec.SimpleSanitizedName(function));
        FunctionCallExpr call = new FunctionCallExpr(tok, name, new ThisExpr(tok), tok,
            function.Formals.ConvertAll(f => (Expression)
                MakeIdentifierExpr(f.Name, f.Type, f.IsGhost)));
        call.Function = function;
        call.TypeArgumentSubstitutions = typeArgs;
        call.Type = function.ResultType;
        CallStmt revealCall = null;
        if (hidden)
        {
            var selectExpr = new MemberSelectExpr(tok, new ThisExpr(tok), "reveal_" + function.Name);
            selectExpr.Member = FindMethod(selectExpr.MemberName);  // Manually resolve here
            selectExpr.TypeApplication = new List<Type>();  // Manually resolve here
            selectExpr.Type = new InferredTypeProxy();  // Manually resolve here            

            revealCall = new CallStmt(tok, tok, new List<Expression>(), selectExpr, new List<Expression>());
            revealCall.IsGhost = true;                                    
            ClassDecl cls = (ClassDecl)function.EnclosingClass;
            string fullName = "#" + function.Name + "_FULL";
            function = (Function)cls.Members.Find(m => m.Name == fullName);
            if (function == null)
            {
                throw new Exception("internal error: could not find function " + fullName);
            }
            substArgs = new Dictionary<string,TypeParameter>();
            function.TypeArgs.ForEach(t => substArgs.Add(t.Name, t));
            typeArgs = typeArgs.ToDictionary(p => substArgs[p.Key.Name], p => p.Value);
        }
        Expression funBody = function.Body;
        BlockStmt body = null;
        if (funBody != null)
        {
            ReturnStmt retStmt = new ReturnStmt(tok, tok, new List<AssignmentRhs>() {
                    new ExprRhs(funBody)
                });
            body = new BlockStmt(tok, tok,
                hidden
                    ? (new List<Statement>() { revealCall, retStmt })
                    : (new List<Statement>() { retStmt }));
        }
        List<Expression> ens = new List<Expression> {
                MakeBinaryExpr(BinaryExpr.Opcode.Eq, BinaryExpr.ResolvedOpcode.EqCommon, Type.Bool,
                    MakeIdentifierExpr("__result", function.ResultType, function.IsGhost),
                    call)
            }.Concat(function.Ens).ToList();
        Method method = new Method(tok, funName, function.IsStatic, function.IsGhost,
            function.TypeArgs, function.Formals, new List<Formal> { result },
            function.Req.ConvertAll(e => new MaybeFreeExpression(e)),
            new Specification<FrameExpression>(new List<FrameExpression>(), null),
            ens.ConvertAll(e => new MaybeFreeExpression(e)),
            function.Decreases,
            body, function.Attributes, function.SignatureEllipsis);
        method.EnclosingClass = function.EnclosingClass;
        Compile_Method(method, typeArgs);
    }
            public void FunctionCallOnNonFunctionTest()
            {
                var target = new EvaluateVisitor();

                var functionNameExpr = new IdentifierExpr(RandomGenerator.String());

                var expr = new FunctionCallExpr(functionNameExpr, new Expression[0]);

                _scope.DefineIdentifier(functionNameExpr.Name, Value.FromObject(RandomGenerator.String()));

                target.Visit(expr, _scope);
            }
            public void FunctionCallWithEmptyScopeTest()
            {
                var target = new EvaluateVisitor();

                var functionName = RandomGenerator.String();
                var calledFunctionNameExpr = new IdentifierExpr(functionName);

                var expr = new FunctionCallExpr(calledFunctionNameExpr, new Expression[0]);

                target.Visit(expr, _scope);
            }
            public void FunctionCallWithNoReturnStatementTest()
            {
                var target = new EvaluateVisitor();

                var functionName = RandomGenerator.String();
                var functionNameExpr = new IdentifierExpr(functionName);
                var returnValue = RandomGenerator.String();
                var functionDefinition = new FunctionDefinitionExpr(functionNameExpr, new VarDefinitionStmt[0], new ScopeBlockStmt(new[] { new NoOpStatement()  }), new IdentifierExpr("String"));

                var expr = new FunctionCallExpr(functionNameExpr, new Expression[0]);

                _scope.DefineIdentifier(functionName, Value.FromObject(functionDefinition));

                target.Visit(expr, _scope);
            }
            public void LambdaCallTest()
            {
                var target = new EvaluateVisitor();

                var functionName = RandomGenerator.String();
                var functionNameExpr = new IdentifierExpr(functionName);
                var returnValue = RandomGenerator.String();
                var functionDefinition = new LambdaDefinitionExpr(functionNameExpr, new VarDefinitionStmt[0], new ConstantExpr(returnValue), new IdentifierExpr("String"));

                var expr = new FunctionCallExpr(functionNameExpr, new Expression[0]);

                _scope.DefineIdentifier(functionName, Value.FromObject(functionDefinition));

                var actual = target.Visit(expr, _scope);

                Assert.AreEqual(returnValue, actual.ToObject());
            }
Example #43
0
 protected Expression CloneCallAndAddK(FunctionCallExpr e) {
   Contract.Requires(e != null);
   var receiver = CloneExpr(e.Receiver);
   var args = new List<Expression>();
   args.Add(k);
   foreach (var arg in e.Args) {
     args.Add(CloneExpr(arg));
   }
   var fexp = new FunctionCallExpr(Tok(e.tok), e.Name + "#", receiver, e.OpenParen, args);
   reporter.Info(MessageSource.Cloner, e.tok, e.Name + suffix);
   return fexp;
 }
            public void FunctionCallOnUndefinedFuncTest()
            {
                var target = new EvaluateVisitor();

                var functionName = RandomGenerator.String();
                var definedFunctionNameExpr = new IdentifierExpr(functionName);
                var calledFunctionNameExpr = new IdentifierExpr(functionName + "UNDEFINED");
                var returnValue = RandomGenerator.String();

                var functionDefinition = new FunctionDefinitionExpr(definedFunctionNameExpr, new VarDefinitionStmt[0],
                    new ScopeBlockStmt(new[] { new ReturnStmt(new ConstantExpr(returnValue)) }), new IdentifierExpr("String"));

                var expr = new FunctionCallExpr(calledFunctionNameExpr, new Expression[0]);

                _scope.DefineIdentifier(functionName, Value.FromObject(functionDefinition));

                target.Visit(expr, _scope);
            }