コード例 #1
0
        public override Expression Parse(Token[] tokens, int index)
        {
            if (index < tokens.Length - 2 && tokens[index].Type == TokenType.Identifier && tokens[index + 1].Type == TokenType.RoundOpen)
            {
                var function = new FunctionCall
                                   {
                                       Identifier = tokens[index],
                                       ArgumentList = ParseSubExpression(tokens, index + 1, 1, ArgumentListParsers),
                                       StringIndex = tokens[index].Index
                                   };
                function.Add(new SingleToken() { Token = function.Identifier});
                if (function.ArgumentList != null) function.Add(function.ArgumentList);
                function.TokenLength = 1 + function.ArgumentList.TokenLength;
                var semiColonIndex = index + 1 + function.ArgumentList.TokenLength;
                if (semiColonIndex < tokens.Length)
                {
                    var semiColon = tokens[semiColonIndex];
                    if (semiColon.Type == TokenType.SemiColon)
                    {
                        function.SemiColon = semiColon;
                        function.TokenLength++;
                        function.Add(new SingleToken() { Token = semiColon});
                    }
                }

                var lastToken = tokens[index + function.TokenLength - 1];
                function.StringLength = lastToken.Index + lastToken.Value.Length - function.StringIndex;

                return function;
            }
            return null;
        }
        public void AddTransaction(string tType, IStepModel step, IStepService stepService, String stepName = "", String parentTransactionName = "")
        {
            try
            {
                var fc = new FunctionCall();
                var fcs = new FunctionCallSignature { Name = tType};

                //check if the step is already predefined. This is in case of surrounding web_concurrent_start and web_concurrent_end
                //String name = (stepName == "") ? tNumber + ". " + step.ComposedName : tNumber + ". " + stepName;

                fcs.Parameters.Add(new FunctionCallParameter(stepName, ParameterType.ArgtypeString));
                //if we are adding lr_start_sub_transaction add the parent transaction name
                if (tType.Contains("start_sub"))
                    fcs.Parameters.Add(new FunctionCallParameter(parentTransactionName, ParameterType.ArgtypeNumber));

                //if we are adding lr_end_transaction add the LR_AUTO parameter
                if (tType.Contains("end"))
                    fcs.Parameters.Add(new FunctionCallParameter("LR_AUTO", ParameterType.ArgtypeNumber));

                fc.Signature = fcs;
                fc.Location = new FunctionCallLocation(step.FunctionCall.Location.FilePath, null, null);
                IStepModel newStep = stepService.GenerateStep(fc);

                RelativeStep relativity = (tType.Contains("start")) ? RelativeStep.Before : RelativeStep.After;

                if (tType.Contains("end"))
                    tNumber++;

                stepService.AddStep(ref newStep, step, relativity, false);
            }
            catch (Exception ex)
            {
                MessageService.ShowMessage(string.Format(ex.StackTrace));
            }
        }
コード例 #3
0
ファイル: StartCoroutine.cs プロジェクト: GameDiffs/TheForest
 public override void Reset()
 {
     this.gameObject = null;
     this.behaviour = null;
     this.functionCall = null;
     this.stopOnExit = false;
 }
コード例 #4
0
 public void ProcessFunctionCall(FunctionCall FunctionCall)
 {
     if (FunctionCall.OverClause != null)
     {
         if (FunctionCall.OverClause.WindowFrameClause != null)
         {
             if (FunctionCall.OverClause.WindowFrameClause.WindowFrameType == WindowFrameType.Range)
             {
                 _smells.SendFeedBack(25, FunctionCall.OverClause.WindowFrameClause);
             }
         }
         else
         {
             if (FunctionCall.OverClause.OrderByClause != null)
             {
                 switch (FunctionCall.FunctionName.Value.ToLower())
                 {
                     case "row_number":
                     case "rank":
                     case "dense_rank":
                     case "ntile":
                     case "lag":
                     case "lead":
                         break;
                     default:
                         _smells.SendFeedBack(26, FunctionCall.OverClause);
                         break;
                 }
             }
         }
     }
 }
コード例 #5
0
 private void Check(CodeElement e, SymbolTable table, FunctionCall call, FunctionDeclaration definition)
 {
     var parameters = definition.Profile.Parameters;
     if (call.InputParameters.Count > parameters.Count) {
     var m = System.String.Format("Function {0} only takes {1} parameters", definition.Name, parameters.Count);
     DiagnosticUtils.AddError(e, m);
     }
     for (int c = 0; c < parameters.Count; c++) {
     var expected = parameters[c];
     if (c < call.InputParameters.Count) {
         var actual = call.InputParameters[c];
         if (actual.IsLiteral) continue;
         var found = table.GetVariable(new URI(actual.Value));
         if (found.Count < 1) DiagnosticUtils.AddError(e, "Parameter "+actual.Value+" is not referenced");
         if (found.Count > 1) DiagnosticUtils.AddError(e, "Ambiguous reference to parameter "+actual.Value);
         if (found.Count!= 1) continue;
         var type = found[0] as Typed;
         // type check. please note:
         // 1- if only one of [actual|expected] types is null, overriden DataType.!= operator will detect it
         // 2- if both are null, we WANT it to break: in TypeCobol EVERYTHING should be typed,
         //    and things we cannot know their type as typed as DataType.Unknown (which is a non-null valid type).
         if (type == null || type.DataType != expected.DataType) {
             var m = System.String.Format("Function {0} expected parameter {1} of type {2} (actual: {3})", definition.Name, c+1, expected.DataType, type.DataType);
             DiagnosticUtils.AddError(e, m);
         }
         if (type != null && type.Length > expected.Length) {
             var m = System.String.Format("Function {0} expected parameter {1} of max length {2} (actual: {3})", definition.Name, c+1, expected.Length, type.Length);
             DiagnosticUtils.AddError(e, m);
         }
     } else {
         var m = System.String.Format("Function {0} is missing parameter {1} of type {2}", definition.Name, c+1, expected.DataType);
         DiagnosticUtils.AddError(e, m);
     }
     }
 }
コード例 #6
0
ファイル: SendMessage.cs プロジェクト: RosalieChang/hello
		public override void Reset()
		{
			gameObject = null;
			delivery = MessageType.SendMessage;
			options = SendMessageOptions.DontRequireReceiver;
			functionCall = null;
		}
コード例 #7
0
ファイル: StartCoroutine.cs プロジェクト: hughrogers/RPGQuest
 public override void Reset()
 {
     gameObject = null;
     behaviour = null;
     functionCall = null;
     stopOnExit = false;
 }
コード例 #8
0
ファイル: Packets.cs プロジェクト: swax/CodePerspective
 public CallStat(FunctionCall call)
 {
     ID = call.ID;
     TotalHits = call.TotalHits;
     TotalCallTime = call.TotalCallTime;
     TotalTimeOutsideDest = call.TotalTimeOutsideDest;
 }
コード例 #9
0
 private void checkIsSuspected(FunctionCall function)
 {
     if (function == null || function.Parameters == null) return;
     if (function.Parameters.OfType<ColumnReferenceExpression>().Any())
     {
         IsSuspected = true;
     }
 }
コード例 #10
0
 protected virtual bool IsCallInsecure(FunctionCall call)
 {
     return
         call.ParamTokens
             .Any(y => y.TokenType == PhpTokenType.Variable && Php.Superglobals
                 .Any(z => z == y.Lexeme)) ||
         call.ParamTokens
             .Any(y => (y.TokenType == PhpTokenType.String || y.TokenType == PhpTokenType.HereDocString) &&
                 Php.Superglobals.Any(z => y.Lexeme.Contains(z)));
 }
コード例 #11
0
 protected override bool IsCallInsecure(FunctionCall call)
 {
     return base.IsCallInsecure(call) && call.ParamTokens
         .Any(x => (x.TokenType == PhpTokenType.String || x.TokenType == PhpTokenType.HereDocString) &&
             x.Lexeme.ToLower().Contains("location:") &&
             (Php.Superglobals
                 .Any(y => x.Lexeme.Contains(y)) ||
             call.ParamTokens
                 .Any(y => y.TokenType == PhpTokenType.Variable && Php.Superglobals
                     .Any(z => y.Lexeme.Contains(z)))));
 }
コード例 #12
0
ファイル: JsonMasherTests.cs プロジェクト: mbrezu/JsonMasher
        public void TestEmpty()
        {
            // Arrange
            var data = MakeNestedArray();
            var op   = new FunctionCall(Empty.Builtin);

            // Act
            var result = op.RunAsSequence(data);

            // Assert
            result.Count().Should().Be(0);
        }
コード例 #13
0
        private static bool GetFunction(AstRoot astRoot, ref int position, out FunctionCall functionCall, out Variable functionVariable)
        {
            // Note that we do not want just the deepest call since in abc(def())
            // when position is over 'def' we actually want signature help for 'abc'
            // while simple depth search will find 'def'.
            functionVariable = null;
            int p = position;

            functionCall = astRoot.GetSpecificNodeFromPosition <FunctionCall>(p, (x) => {
                var fc = x as FunctionCall;
                // Take into account incompleted argument lists line in 'func(a|'
                return(fc != null && (fc.Arguments.Contains(p) || (fc.CloseBrace == null && fc.Arguments.End == p)));
            });

            if (functionCall == null && position > 0)
            {
                // Retry in case caret is at the very end of function signature
                // that does not have final close brace yet.
                functionCall = astRoot.GetNodeOfTypeFromPosition <FunctionCall>(position - 1, includeEnd: true);
                if (functionCall != null)
                {
                    // But if signature does have closing brace and caret
                    // is beyond it, we are really otuside of the signature.
                    if (functionCall.CloseBrace != null && position >= functionCall.CloseBrace.End)
                    {
                        return(false);
                    }

                    if (position > functionCall.SignatureEnd)
                    {
                        position = functionCall.SignatureEnd;
                    }
                }
            }

            if (functionCall != null && functionCall.Children.Count > 0)
            {
                functionVariable = functionCall.Children[0] as Variable;
                if (functionVariable == null)
                {
                    // Might be in a namespace
                    var op = functionCall.Children[0] as IOperator;
                    if (op != null && op.OperatorType == OperatorType.Namespace)
                    {
                        functionVariable = op.RightOperand as Variable;
                    }
                }
                return(functionVariable != null);
            }

            return(false);
        }
コード例 #14
0
        public IInterpreter NoLimitsVariadicFunctionWithSpread()
        {
            var interpreter = new Interpreter.Interpreter();

            foreach (var mutability in Options.AllMutabilityModes)
            {
                var env = Language.Environment.Create(new Options()
                {
                    AllowInvalidMainResult = true
                }.SetMutability(mutability));
                var root_ns = env.Root;

                root_ns.AddBuilder(FunctionBuilder.Create(
                                       "sum",
                                       ExpressionReadMode.ReadRequired,
                                       NameFactory.Int64NameReference(),
                                       Block.CreateStatement(new IExpression[] {
                    // let i0 = n.at(0)
                    VariableDeclaration.CreateStatement("i0", null, FunctionCall.Create(NameReference.Create("n", NameFactory.PropertyIndexerName),
                                                                                        FunctionArgument.Create(NatLiteral.Create("0")))),
                    // let i1 = n.at(1)
                    VariableDeclaration.CreateStatement("i1", null, FunctionCall.Create(NameReference.Create("n", NameFactory.PropertyIndexerName),
                                                                                        FunctionArgument.Create(NatLiteral.Create("1")))),
                    // return i0+i1
                    Return.Create(ExpressionFactory.Add("i0", "i1"))
                }))
                                   .Parameters(FunctionParameter.Create("n", NameFactory.Int64NameReference(), Variadic.Create(), null, isNameRequired: false)));

                var main_func = root_ns.AddBuilder(FunctionBuilder.Create(
                                                       "main",
                                                       ExpressionReadMode.OptionalUse,
                                                       NameFactory.Int64NameReference(),
                                                       Block.CreateStatement(new IExpression[] {
                    VariableDeclaration.CreateStatement("x", null,
                                                        ExpressionFactory.HeapConstructor(NameFactory.ChunkNameReference(NameFactory.Int64NameReference()),
                                                                                          FunctionArgument.Create(NatLiteral.Create("2"))),
                                                        env.Options.ReassignableModifier()),
                    Assignment.CreateStatement(FunctionCall.Indexer(NameReference.Create("x"), FunctionArgument.Create(NatLiteral.Create("0"))),
                                               Int64Literal.Create("-6")),
                    Assignment.CreateStatement(FunctionCall.Indexer(NameReference.Create("x"), FunctionArgument.Create(NatLiteral.Create("1"))),
                                               Int64Literal.Create("8")),
                    Return.Create(FunctionCall.Create(NameReference.Create("sum"),
                                                      FunctionArgument.Create(Spread.Create(NameReference.Create("x")))))
                })));

                ExecValue result = interpreter.TestRun(env);

                Assert.AreEqual(2L, result.RetValue.PlainValue);
            }

            return(interpreter);
        }
コード例 #15
0
ファイル: Inheritance.cs プロジェクト: macias/Skila
        public IInterpreter InheritingEnums()
        {
            var interpreter = new Interpreter.Interpreter();

            foreach (var mutability in Options.AllMutabilityModes)
            {
                var env = Environment.Create(new Options()
                {
                    AllowInvalidMainResult = true,
                    DebugThrowOnError      = true
                }.SetMutability(mutability));
                var root_ns = env.Root;

                root_ns.AddBuilder(TypeBuilder.CreateEnum("Weekend")
                                   .With(EnumCaseBuilder.Create("Sat", "Sun"))
                                   .SetModifier(EntityModifier.Base));

                root_ns.AddBuilder(TypeBuilder.CreateEnum("First")
                                   .With(EnumCaseBuilder.Create("Mon"))
                                   .Parents("Weekend"));

                root_ns.AddBuilder(FunctionBuilder.Create(
                                       "main",
                                       ExpressionReadMode.OptionalUse,
                                       NameFactory.NatNameReference(),
                                       Block.CreateStatement(new IExpression[] {
                    // let a Weekend = First.Sat
                    VariableDeclaration.CreateStatement("a", NameReference.Create("Weekend"),
                                                        // please note we only refer to "Sat" through "First", the type is still "Weekend"
                                                        NameReference.Create("First", "Sat")),
                    // var b First = Weekend.Sun
                    VariableDeclaration.CreateStatement("b", NameReference.Create("First"), NameReference.Create("Weekend", "Sun"),
                                                        env.Options.ReassignableModifier()),
                    // b = First.Mon
                    Assignment.CreateStatement(NameReference.Create("b"), NameReference.Create("First", "Mon")),
                    // let x = a to Nat; // 0
                    VariableDeclaration.CreateStatement("x", null, FunctionCall.ConvCall(NameReference.Create("a"),
                                                                                         NameFactory.NatNameReference())),
                    // let y = b to Nat; // 2
                    VariableDeclaration.CreateStatement("y", null, FunctionCall.ConvCall(NameReference.Create("b"),
                                                                                         NameFactory.NatNameReference())),
                    // return x + y
                    Return.Create(ExpressionFactory.Add(NameReference.Create("x"), NameReference.Create("y")))
                })));

                ExecValue result = interpreter.TestRun(env);

                Assert.AreEqual(2UL, result.RetValue.PlainValue);
            }

            return(interpreter);
        }
コード例 #16
0
        /// <summary>
        /// Create call stack pattern and either insert into database or match to existing.
        /// Update Associate Buggs.
        /// </summary>
        /// <param name="newCrash"></param>
        private void BuildPattern(Crash newCrash)
        {
            var callstack = new CallStackContainer(newCrash);

            newCrash.Module = callstack.GetModuleName();
            if (newCrash.PatternId == null)
            {
                var patternList = new List <string>();

                try
                {
                    foreach (var entry in callstack.CallStackEntries.Take(CallStackContainer.MaxLinesToParse))
                    {
                        FunctionCall currentFunctionCall;

                        var csEntry      = entry;
                        var functionCall = _unitOfWork.FunctionRepository.First(f => f.Call == csEntry.FunctionName);
                        if (functionCall != null)
                        {
                            currentFunctionCall = functionCall;
                        }
                        else
                        {
                            currentFunctionCall = new FunctionCall {
                                Call = csEntry.FunctionName
                            };
                            _unitOfWork.FunctionRepository.Save(currentFunctionCall);
                            _unitOfWork.Save();
                        }

                        patternList.Add(currentFunctionCall.Id.ToString());
                    }

                    newCrash.Pattern = string.Join("+", patternList);
                }
                catch (Exception ex)
                {
                    var messageBuilder = new StringBuilder();
                    FLogger.Global.WriteException("Build Pattern exception: " + ex.Message.ToString(CultureInfo.InvariantCulture));
                    messageBuilder.AppendLine("Exception was:");
                    messageBuilder.AppendLine(ex.ToString());
                    while (ex.InnerException != null)
                    {
                        ex = ex.InnerException;
                        messageBuilder.AppendLine(ex.ToString());
                    }

                    _slackWriter.Write("Build Pattern Exception : " + ex.Message.ToString(CultureInfo.InvariantCulture));
                    throw;
                }
            }
        }
コード例 #17
0
        public override void ExplicitVisit(FunctionCall node)
        {
            string functionName = node.FunctionName.Value;

            if (RestrictedFunctionsList.Contains(functionName, StringComparer.InvariantCultureIgnoreCase))
            {
                FragmentsFound.Add(new FunctionCallFragmentInfo()
                {
                    Fragment     = node,
                    FunctionName = functionName
                });
            }
        }
コード例 #18
0
ファイル: JsonMasherTests.cs プロジェクト: mbrezu/JsonMasher
        public void ContainsStringsTest()
        {
            // Arrange
            var data = Json.String("abacabacab");
            var op   = new FunctionCall(
                Contains.Builtin, new Literal("acab"));

            // Act
            var result = op.RunAsSequence(data);

            // Assert
            Json.Array(result).DeepEqual("[true]".AsJson()).Should().BeTrue();
        }
コード例 #19
0
ファイル: PrintAstVisitor.cs プロジェクト: SuNNjek/ParseTest
        public override void Visit(FunctionCall visitable)
        {
            WriteIndentantion(true).AppendLine($"Function call: {visitable.Name.Value}");

            for (int i = 0; i < visitable.Arguments.Count; i++)
            {
                WriteIndentantion(true).AppendLine($"Argument {i}:");
                Start(visitable.Arguments[i]);
                _indentLevel--;
            }

            _indentLevel--;
        }
コード例 #20
0
ファイル: Preprocessor.cs プロジェクト: Frazi1/SharpCompiler
        private static void Process(this FunctionCall functionCall)
        {
            //functionCall.Name.Process();
            var functionDeclaration = functionCall.Scope.GlobalFunctionSearch(functionCall.ExtendedId.Name);

            if (functionDeclaration == null)
            {
                throw new ScopeException($"Function with name \"{functionCall.ExtendedId.Name}\" does not exist");
            }

            CheckCallParameters(functionCall, functionCall.FunctionCallParameters, functionDeclaration.ParameterNodes);
            functionCall.ReturnType = functionDeclaration.ReturnType;
        }
コード例 #21
0
ファイル: ExprTypeChecking.cs プロジェクト: qunyanm/boogie
        public FunctionCall CreateFunctionCall(string Name, Microsoft.Boogie.Type returnType, IList<Microsoft.Boogie.Type> argTypes)
        {
            var returnVar = new Formal(Token.NoToken, new TypedIdent(Token.NoToken, "", returnType), false);
            var vars = new List<Variable>();
            foreach (var T in argTypes)
            {
                vars.Add( new Formal(Token.NoToken, new TypedIdent(Token.NoToken, "",T), true));
            }

            // Finally build the function and the function call
            var funcCall = new FunctionCall(new Function(Token.NoToken, Name, vars, returnVar));
            return funcCall;
        }
コード例 #22
0
        public void TestCallGraph()
        {
            var names = new List <string> {
                "a", "b", "c"
            };
            var functions = new List <FunctionDeclaration>();
            var calls     = new List <FunctionCall>();

            foreach (var id in names)
            {
                var functionCall = new FunctionCall(
                    new Range(new StringLocation(0), new StringLocation(1)),
                    "b",
                    new List <Expression>());
                calls.Add(functionCall);
                var body = new InstructionBlock(
                    new Range(new StringLocation(0), new StringLocation(1)),
                    new List <Expression> {
                    functionCall
                });
                var fun = new FunctionDeclaration(
                    new Range(new StringLocation(0), new StringLocation(1)),
                    id,
                    UnitType.Instance,
                    new List <VariableDeclaration>(),
                    body,
                    false);
                functions.Add(fun);
            }

            foreach (var call in calls)
            {
                call.Declaration = functions[1];
            }

            var root = new Program(
                new Range(new StringLocation(0), new StringLocation(1)),
                new List <StructDeclaration>(),
                functions);

            CallGraphGenerator gen = new CallGraphGenerator();
            var dict = gen.BuildCallGraph(root);

            Assert.AreEqual(1, dict[functions[0]].Count);
            Assert.AreEqual(1, dict[functions[1]].Count);
            Assert.AreEqual(1, dict[functions[2]].Count);

            Assert.IsTrue(dict[functions[0]].Contains(functions[1]));
            Assert.IsTrue(dict[functions[1]].Contains(functions[1]));
            Assert.IsTrue(dict[functions[2]].Contains(functions[1]));
        }
コード例 #23
0
        public override void Evaluate(ComputationContext ctx)
        {
            if (this.Evaluation == null)
            {
                FunctionDefinition func = this.EnclosingScope <FunctionDefinition>();
                if (func == null)
                {
                    ctx.ErrorManager.AddError(ErrorCode.ReturnOutsideFunction, this);
                }
                else
                {
                    if (func.IsResultTypeNameInfered)
                    {
                        if (this.Expr == null)
                        {
                            func.AddResultTypeCandidate(ctx.Env.UnitType.InstanceOf);
                        }
                        else
                        {
                            func.AddResultTypeCandidate(this.Expr.Evaluation.Components);
                        }
                    }
                    else
                    {
                        IEntityInstance func_result = func.ResultParameter.TypeName.Evaluation.Components;

                        if (this.Expr == null)
                        {
                            if (!ctx.Env.IsUnitType(func_result))
                            {
                                ctx.ErrorManager.AddError(ErrorCode.EmptyReturn, this);
                            }
                        }
                        else
                        {
                            this.DataTransfer(ctx, ref this.expr, func_result);
                        }
                    }
                }

                // https://stackoverflow.com/questions/7563981/why-isnt-g-tail-call-optimizing-while-gcc-is
                // http://www.drdobbs.com/tackling-c-tail-calls/184401756
                if (this.Expr is FunctionCall call && call.IsRecall() &&
                    !func.Parameters.Any(it => ctx.Env.IsReferenceOfType(it.TypeName.Evaluation.Components)))
                {
                    this.TailCallOptimization = call;
                }

                this.Evaluation = ctx.Env.UnitEvaluation;
            }
        }
コード例 #24
0
ファイル: Properties.cs プロジェクト: macias/Skila
        public IInterpreter OverridingMethodWithIndexerGetter()
        {
            var interpreter = new Interpreter.Interpreter();

            foreach (var mutability in Options.AllMutabilityModes)
            {
                var env = Language.Environment.Create(new Options()
                {
                    AllowInvalidMainResult = true,
                    DebugThrowOnError      = true
                }.SetMutability(mutability));
                var root_ns = env.Root;

                root_ns.AddBuilder(TypeBuilder.CreateInterface("IProvider")
                                   .With(FunctionBuilder.CreateDeclaration(NameFactory.PropertyIndexerName, ExpressionReadMode.ReadRequired, NameFactory.Int64NameReference())
                                         .Parameters(FunctionParameter.Create("x", NameFactory.Int64NameReference()))));

                root_ns.AddBuilder(TypeBuilder.Create("Middle")
                                   .Parents("IProvider")
                                   .SetModifier(EntityModifier.Base)
                                   .With(FunctionBuilder.Create(NameFactory.PropertyIndexerName, ExpressionReadMode.ReadRequired, NameFactory.Int64NameReference(),
                                                                Block.CreateStatement(Return.Create(Int64Literal.Create("500"))))
                                         .SetModifier(EntityModifier.Override | EntityModifier.UnchainBase)
                                         .Parameters(FunctionParameter.Create("x", NameFactory.Int64NameReference(), ExpressionReadMode.CannotBeRead))));

                root_ns.AddBuilder(TypeBuilder.Create("Last")
                                   .Parents("Middle")
                                   .SetModifier(EntityModifier.Base)
                                   .With(PropertyBuilder.CreateIndexer(env.Options, NameFactory.Int64NameReference())
                                         .Parameters(FunctionParameter.Create("x", NameFactory.Int64NameReference(), ExpressionReadMode.CannotBeRead))
                                         .With(PropertyMemberBuilder.CreateIndexerGetter(Block.CreateStatement(Return.Create(Int64Literal.Create("2"))))
                                               .Modifier(EntityModifier.Override | EntityModifier.UnchainBase))));

                root_ns.AddBuilder(FunctionBuilder.Create(
                                       "main",
                                       ExpressionReadMode.OptionalUse,
                                       NameFactory.Int64NameReference(),
                                       Block.CreateStatement(new IExpression[] {
                    VariableDeclaration.CreateStatement("p", NameFactory.PointerNameReference("IProvider"),
                                                        ExpressionFactory.HeapConstructor("Last")),
                    Return.Create(FunctionCall.Create(NameReference.Create("p", NameFactory.PropertyIndexerName),
                                                      FunctionArgument.Create(Int64Literal.Create("18"))))
                })));

                ExecValue result = interpreter.TestRun(env);

                Assert.AreEqual(2L, result.RetValue.PlainValue);
            }

            return(interpreter);
        }
コード例 #25
0
        public IErrorReporter ErrorEscapingReceivedReferenceFromFunction()
        {
            NameResolver resolver = null;

            foreach (var mutability in Options.AllMutabilityModes)
            {
                var env = Language.Environment.Create(new Options()
                {
                    DiscardingAnyExpressionDuringTests = true
                }
                                                      .SetMutability(mutability));
                var root_ns = env.Root;

                root_ns.AddBuilder(FunctionBuilder.Create("selector",
                                                          ExpressionReadMode.ReadRequired,
                                                          NameFactory.ReferenceNameReference(NameFactory.IntNameReference()),

                                                          Block.CreateStatement(
                                                              ExpressionFactory.Readout("b"),
                                                              Return.Create(NameReference.Create("a"))
                                                              ))
                                   .Parameters(
                                       FunctionParameter.Create("a", NameFactory.ReferenceNameReference(NameFactory.IntNameReference())),
                                       FunctionParameter.Create("b", NameFactory.ReferenceNameReference(NameFactory.IntNameReference()))));


                FunctionCall call = FunctionCall.Create("selector", IntLiteral.Create("2"), IntLiteral.Create("3"));

                FunctionDefinition func = root_ns.AddBuilder(FunctionBuilder.Create("notimportant",
                                                                                    ExpressionReadMode.OptionalUse,
                                                                                    NameFactory.UnitNameReference(),

                                                                                    Block.CreateStatement(
                                                                                        VariableDeclaration.CreateStatement("h", NameFactory.ReferenceNameReference(NameFactory.IntNameReference()),
                                                                                                                            IntLiteral.Create("0"), EntityModifier.Reassignable),
                                                                                        Block.CreateStatement(
                                                                                            // error: the most alive reference the function can return is limited to this scope
                                                                                            // so it cannot be assigned to outer-scope variable
                                                                                            Assignment.CreateStatement(NameReference.Create("h"), call)
                                                                                            ),
                                                                                        ExpressionFactory.Readout("h")
                                                                                        )));


                resolver = NameResolver.Create(env);

                Assert.AreEqual(1, resolver.ErrorManager.Errors.Count);
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.EscapingReference, call));
            }
            return(resolver);
        }
コード例 #26
0
ファイル: Inheritance.cs プロジェクト: macias/Skila
        public IInterpreter VirtualCall()
        {
            var interpreter = new Interpreter.Interpreter();

            foreach (var mutability in Options.AllMutabilityModes)
            {
                var env = Environment.Create(new Options()
                {
                    AllowInvalidMainResult = true,
                    DebugThrowOnError      = true
                }.SetMutability(mutability));
                var root_ns = env.Root;

                root_ns.AddBuilder(TypeBuilder.Create("MyBase")
                                   .SetModifier(EntityModifier.Base)
                                   .With(FunctionBuilder.Create(
                                             "bar",
                                             ExpressionReadMode.ReadRequired,
                                             NameFactory.Int64NameReference(),
                                             Block.CreateStatement(new[] {
                    Return.Create(Int64Literal.Create("33"))
                }))
                                         .SetModifier(EntityModifier.Base)));

                TypeDefinition type_impl = root_ns.AddBuilder(TypeBuilder.Create("SomeChild")
                                                              .With(FunctionBuilder.Create("bar",
                                                                                           ExpressionReadMode.ReadRequired,
                                                                                           NameFactory.Int64NameReference(),
                                                                                           Block.CreateStatement(new[] {
                    Return.Create(Int64Literal.Create("2"))
                }))
                                                                    .SetModifier(EntityModifier.Override | EntityModifier.UnchainBase))
                                                              .Parents(NameReference.Create("MyBase")));

                var main_func = root_ns.AddBuilder(FunctionBuilder.Create(
                                                       "main",
                                                       ExpressionReadMode.OptionalUse,
                                                       NameFactory.Int64NameReference(),
                                                       Block.CreateStatement(new IExpression[] {
                    VariableDeclaration.CreateStatement("i", NameFactory.PointerNameReference(NameReference.Create("MyBase")),
                                                        ExpressionFactory.HeapConstructor(NameReference.Create("SomeChild"))),
                    Return.Create(FunctionCall.Create(NameReference.Create("i", "bar")))
                })));

                ExecValue result = interpreter.TestRun(env);

                Assert.AreEqual(2L, result.RetValue.PlainValue);
            }

            return(interpreter);
        }
コード例 #27
0
        public static IEnumerable <IInstruction> GetFunctionCallInstructions(this FunctionCall functionCall)
        {
            List <IInstruction> instructions = new List <IInstruction>();

            //Add parameters to stack
            functionCall.FunctionCallParameters.ForEach(expression =>
            {
                instructions.AddRange(expression.GetInstructions());
            });

            var scope = functionCall.Scope;
            FunctionDeclaration functionDeclaration = scope.GlobalFunctionSearch(functionCall.ExtendedId.Name);
            var javaRefAtrribute =
                functionDeclaration.AttributeUsages.Find(usage => usage.Name.Name == "JavaRef");

            if (javaRefAtrribute != null)
            {
                string externName = javaRefAtrribute.FunctionCallParameters
                                    .First()
                                    .CastTo <StringExpression>()
                                    .Value
                                    .RemoveFirstAndLastCharacters();
                invokestaticInstruction invokestaticInstruction = InvokestaticInstruction
                                                                  .WithMethodFullName(externName)
                                                                  .WithReturnType(
                    ReturnTypeToJavaConverter.ConvertToFullRepresentation(functionDeclaration.ReturnType));
                functionDeclaration
                .ParameterNodes
                .Select(parameter => ReturnTypeToJavaConverter.ConvertToFullRepresentation(parameter.ReturnType))
                .ForEach(typeName => invokestaticInstruction.WithParameterType(typeName));
                instructions.Add(invokestaticInstruction);
            }
            else
            {
                //var splittedName = functionCall.FunctionDeclaration.FullName.Split('.');
                //string correctedName;
                //if (splittedName.Length == 1)
                //    correctedName = splittedName[0].ToCamelCase();
                //else
                //    correctedName = $"{splittedName[0]}/{splittedName[1].ToCamelCase()}";
                invokestaticInstruction invokestaticInstruction = InvokestaticInstruction
                                                                  .WithMethodFullName(/*correctedName*/ functionCall.FunctionDeclaration.FullNameCamelCased)
                                                                  .WithReturnType(ReturnTypeToJavaConverter.ConvertToFullRepresentation(functionCall.ReturnType));
                functionDeclaration
                .ParameterNodes
                .Select(parameter => ReturnTypeToJavaConverter.ConvertToFullRepresentation(parameter.ReturnType))
                .ForEach(typeName => invokestaticInstruction.WithParameterType(typeName));
                instructions.Add(invokestaticInstruction);
            }
            return(instructions);
        }
コード例 #28
0
        void BuildPattern(Crash CrashInstance)
        {
            List <string> Pattern = new List <string>();

            // Get an array of callstack items
            CallStackContainer CallStack = new CallStackContainer(CrashInstance);

            CallStack.bDisplayFunctionNames = true;

            if (CrashInstance.Pattern == null)
            {
                // Set the module based on the modules in the callstack
                CrashInstance.Module = CallStack.GetModuleName();
                try
                {
                    using (FAutoScopedLogTimer LogTimer = new FAutoScopedLogTimer(this.GetType().ToString() + "(Id=" + CrashInstance.Id + ")"))
                    {
                        foreach (CallStackEntry Entry in CallStack.CallStackEntries.Take(64))
                        {
                            FunctionCall CurrentFunctionCall = new FunctionCall();

                            if (FunctionCalls.Where(f => f.Call == Entry.FunctionName).Count() > 0)
                            {
                                CurrentFunctionCall = FunctionCalls.Where(f => f.Call == Entry.FunctionName).First();
                            }
                            else
                            {
                                CurrentFunctionCall      = new FunctionCall();
                                CurrentFunctionCall.Call = Entry.FunctionName;
                                FunctionCalls.InsertOnSubmit(CurrentFunctionCall);
                            }

                            //CrashRepository.Context.SubmitChanges();

                            Pattern.Add(CurrentFunctionCall.Id.ToString());
                        }

                        //CrashInstance.Pattern = "+";
                        CrashInstance.Pattern = string.Join("+", Pattern);
                        // We need something like this +1+2+3+5+ for searching for exact pattern like +5+
                        //CrashInstance.Pattern += "+";

                        CrashRepository.Context.SubmitChanges();
                    }
                }
                catch (Exception Ex)
                {
                    FLogger.WriteEvent("Exception in BuildPattern: " + Ex.ToString());
                }
            }
        }
コード例 #29
0
        public IErrorReporter ErrorAbusingForcedConst()
        {
            NameResolver resolver = null;

            foreach (var mutability in Options.AllMutabilityModes)
            {
                var env = Language.Environment.Create(new Options()
                {
                    DiscardingAnyExpressionDuringTests = true
                }.SetMutability(mutability));
                var root_ns = env.Root;

                root_ns.AddBuilder(TypeBuilder.Create("Stone"));

                root_ns.AddBuilder(TypeBuilder.Create("Mutator", "M")
                                   .With(FunctionBuilder.Create("violate", NameFactory.UnitNameReference(), Block.CreateStatement())
                                         .SetModifier(EntityModifier.Mutable))
                                   .SetModifier(EntityModifier.Mutable));

                root_ns.AddBuilder(TypeBuilder.Create("Mangler")
                                   .SetModifier(EntityModifier.Mutable)
                                   .With(VariableDeclaration.CreateStatement("m",
                                                                             NameFactory.PointerNameReference(NameReference.Create("Mutator", NameReference.Create("Stone"))),
                                                                             Undef.Create(),
                                                                             EntityModifier.Public | env.Options.ReassignableModifier()))
                                   );

                FunctionCall mut_call   = FunctionCall.Create(NameReference.CreateThised("f", "m", NameFactory.MutableName("violate")));
                IExpression  assignment = Assignment.CreateStatement(NameReference.CreateThised("f", "m"), Undef.Create());
                root_ns.AddBuilder(TypeBuilder.Create("Keeper")
                                   .With(VariableDeclaration.CreateStatement("f",
                                                                             NameFactory.PointerNameReference(NameReference.Create(TypeMutability.ForceConst, "Mangler")),
                                                                             Undef.Create(),
                                                                             EntityModifier.Public))
                                   .With(FunctionBuilder.Create("testing", NameFactory.UnitNameReference(),
                                                                Block.CreateStatement(
                                                                    mut_call,
                                                                    assignment
                                                                    ))));



                resolver = NameResolver.Create(env);

                Assert.AreEqual(2, resolver.ErrorManager.Errors.Count);
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.AlteringNonMutableInstance, mut_call));
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.AlteringNonMutableInstance, assignment));
            }

            return(resolver);
        }
コード例 #30
0
ファイル: Templates.cs プロジェクト: macias/Skila
        public IErrorReporter ErrorCallingTraitMethodOnHost()
        {
            NameResolver resolver = null;

            foreach (var mutability in Options.AllMutabilityModes)
            {
                var env = Environment.Create(new Options()
                {
                    AllowInvalidMainResult = true
                }.SetMutability(mutability));
                var root_ns = env.Root;

                root_ns.AddBuilder(TypeBuilder.CreateInterface("ISay")
                                   .With(FunctionBuilder.CreateDeclaration("say", ExpressionReadMode.ReadRequired, NameFactory.Int64NameReference())));

                root_ns.AddBuilder(TypeBuilder.Create("NoSay"));

                // this function is located in trait, thus unavailable
                FunctionCall int_call = FunctionCall.Create(NameReference.CreateThised("hello"));
                root_ns.AddBuilder(TypeBuilder.Create("Greeter", "T")
                                   .With(FunctionBuilder.Create("reaching", NameFactory.UnitNameReference(),
                                                                Block.CreateStatement(int_call))));

                root_ns.AddBuilder(TypeBuilder.Create("Greeter", "X")
                                   .SetModifier(EntityModifier.Trait)
                                   .Constraints(ConstraintBuilder.Create("X").Inherits("ISay"))
                                   .With(FunctionBuilder.Create("hello", ExpressionReadMode.ReadRequired, NameFactory.Int64NameReference(),
                                                                Block.CreateStatement(
                                                                    Return.Create(Int64Literal.Create("7"))
                                                                    ))));

                FunctionCall ext_call = FunctionCall.Create(NameReference.Create("g", "hello"));
                root_ns.AddBuilder(FunctionBuilder.Create(
                                       "main",
                                       ExpressionReadMode.OptionalUse,
                                       NameFactory.Int64NameReference(),
                                       Block.CreateStatement(
                                           VariableDeclaration.CreateStatement("g", null,
                                                                               ExpressionFactory.StackConstructor(NameReference.Create("Greeter", NameReference.Create("NoSay")))),
                                           Return.Create(ext_call)
                                           )));

                resolver = NameResolver.Create(env);

                Assert.AreEqual(2, resolver.ErrorManager.Errors.Count);
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.ReferenceNotFound, ext_call.Name));
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.ReferenceNotFound, int_call.Name));
            }

            return(resolver);
        }
コード例 #31
0
ファイル: Templates.cs プロジェクト: macias/Skila
        public IErrorReporter ErrorHasConstraint()
        {
            NameResolver resolver = null;

            foreach (var mutability in Options.AllMutabilityModes)
            {
                var env = Environment.Create(new Options()
                {
                    AllowInvalidMainResult = true, AllowProtocols = true
                }.SetMutability(mutability));
                var root_ns = env.Root;

                FunctionDefinition func_constraint = FunctionBuilder.CreateDeclaration("getMe",
                                                                                       ExpressionReadMode.ReadRequired, NameFactory.Int64NameReference());

                // this function accepts any parameter where parameter type has function "getMe"
                FunctionDefinition constrained_func = root_ns.AddBuilder(FunctionBuilder.Create("proxy",
                                                                                                TemplateParametersBuffer.Create().Add("T").Values,
                                                                                                ExpressionReadMode.ReadRequired, NameFactory.Int64NameReference(), Block.CreateStatement(new[] {
                    Return.Create(FunctionCall.Create(NameReference.Create("t", "getMe")))
                }))
                                                                         .Constraints(ConstraintBuilder.Create("T").Has(func_constraint))
                                                                         .Parameters(FunctionParameter.Create("t", NameFactory.PointerNameReference("T"))));

                // this type does NOT have function "getMe"
                TypeDefinition type_impl = root_ns.AddBuilder(TypeBuilder.Create("YMan")
                                                              .With(FunctionBuilder.Create("missing",
                                                                                           ExpressionReadMode.ReadRequired,
                                                                                           NameFactory.Int64NameReference(),
                                                                                           Block.CreateStatement(new[] {
                    Return.Create(Int64Literal.Create("2"))
                }))));

                FunctionCall call = FunctionCall.Create(NameReference.Create("proxy"), FunctionArgument.Create(NameReference.Create("y_man")));
                root_ns.AddBuilder(FunctionBuilder.Create(
                                       "main",
                                       ExpressionReadMode.OptionalUse,
                                       NameFactory.Int64NameReference(),
                                       Block.CreateStatement(new IExpression[] {
                    VariableDeclaration.CreateStatement("y_man", null, ExpressionFactory.HeapConstructor(NameReference.Create("YMan"))),
                    Return.Create(call)
                })));

                resolver = NameResolver.Create(env);

                Assert.AreEqual(1, resolver.ErrorManager.Errors.Count);
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.ViolatedHasFunctionConstraint, call.Callee));
            }

            return(resolver);
        }
コード例 #32
0
 public static bool IsStaticDispatching(TranslatorContext context, FunctionCall node)
 {
     if (node.Expression is MemberAccess memberAccess)
     {
         if (memberAccess.Expression is Identifier ident)
         {
             if (context.GetASTNodeById(ident.ReferencedDeclaration) is ContractDefinition)
             {
                 return(true);
             }
         }
     }
     return(false);
 }
コード例 #33
0
        private void HandleCount(FunctionCall functionCall)
        {
            var parameters = functionCall.Parameters;

            if (functionCall.Wildcard)
            {
                AddExpressionToStack(AggregationUtils.CallCount(_previousStage));
                AddNameToStack($"count(*)");
            }
            else
            {
                throw new SqlErrorException("Count only works with '*' right now.");
            }
        }
コード例 #34
0
        /// <summary>
        /// Génère le code d'un appel de "macro" fonction.
        /// </summary>
        /// <param name="call"></param>
        /// <returns></returns>
        string GenerateMacroFunctionCall(FunctionCall call)
        {
            StringBuilder builder = new StringBuilder();

            Clank.Core.Model.MacroContainer macros = m_project.Macros;
            ClankTypeInstance owner;

            if (call.IsConstructor)
            {
                owner = call.Func.ReturnType;
            }
            else
            {
                owner = call.Src.Type;
            }

            Model.MacroContainer.MacroClass klass = macros.FindClassByType(owner.BaseType);
            string fullname = call.Func.GetFullName();

            if (!klass.Functions.ContainsKey(fullname))
            {
                throw new Exception("Le type array '" + klass.Type.GetFullName() + "' ne contient pas de constructeur sans paramètre, et ce constructeur est nécessaire à la sérialisation de cet array");
            }
            Clank.Core.Model.MacroContainer.MacroFunction func = klass.Functions[fullname]; // TODO : GetFullName() ??

            // Nom de la fonctin native dont les paramètres sont entourés par des $
            string nativeFuncName = func.LanguageToFunctionName[LANG_KEY];


            // Remplace les paramètres par leurs values.
            for (int i = 0; i < call.Func.Arguments.Count; i++)
            {
                nativeFuncName = nativeFuncName.Replace(SemanticConstants.ReplaceChr + "(" + call.Func.Arguments[i].ArgName + ")",
                                                        GenerateEvaluable(call.Arguments[i]));
            }


            // Remplace les params génériques par leurs valeurs.
            for (int i = 0; i < call.Func.Owner.GenericArgumentNames.Count; i++)
            {
                nativeFuncName = nativeFuncName.Replace(SemanticConstants.ReplaceChr + "(" + call.Func.Owner.GenericArgumentNames[i] + ")",
                                                        GenerateTypeInstanceName(owner.GenericArguments[i]));
            }

            // Remplace @self par le nom de la variable.
            nativeFuncName = nativeFuncName.Replace(SemanticConstants.SelfKW, GenerateEvaluable(call.Src));

            builder.Append(nativeFuncName);
            return(builder.ToString().Replace(".[", "["));
        }
コード例 #35
0
ファイル: Visitor.cs プロジェクト: fingerpasswang/Relua
 public virtual void Visit(FunctionCall node)
 {
     if (node.Arguments.Count > 0 &&
         node.Function is TableAccess tableAccess &&
         tableAccess.Table == node.Arguments[0] &&
         tableAccess.Index is StringLiteral stringLiteral &&
         stringLiteral.Value.IsIdentifier()
         )
     {
         for (int i = 1; i < node.Arguments.Count; i++)
         {
             node.Arguments[i].Accept(this);
         }
     }
コード例 #36
0
ファイル: AbsyQuant.cs プロジェクト: luckysunda/hice-dt
            public override Expr VisitNAryExpr(NAryExpr node)
            {
                //Contract.Requires(node != null);
                Contract.Ensures(Contract.Result <Expr>() != null);
                FunctionCall fn = node.Fun as FunctionCall;

                if (fn != null && cce.NonNull(fn.Func).NeverTrigger)
                {
                    parent.Triggers = new Trigger(fn.Func.tok, false, new List <Expr> {
                        node
                    }, parent.Triggers);
                }
                return(base.VisitNAryExpr(node));
            }
コード例 #37
0
ファイル: Typer.cs プロジェクト: Daouki/wire
        public IType VisitFunctionCall(FunctionCall functionCall)
        {
            var calleeType = GetExpressionType(functionCall.Callee);

            if (calleeType is FunctionType calleeFunctionType)
            {
                return(calleeFunctionType.ReturnType);
            }

            _context.Error(
                functionCall.Callee.Span,
                "cannot call a non-callable type \"{calleType}\"");
            return(null);
        }
コード例 #38
0
 protected override void TranslateFunctionCall(List <string> output, FunctionCall functionCall)
 {
     TranslateExpression(output, functionCall.Root);
     output.Add("(");
     for (int i = 0; i < functionCall.Args.Length; ++i)
     {
         if (i > 0)
         {
             output.Add(", ");
         }
         TranslateExpression(output, functionCall.Args[i]);
     }
     output.Add(")");
 }
コード例 #39
0
 public static bool IsAbiFunction(FunctionCall node)
 {
     if (node.Expression is MemberAccess member)
     {
         if (member.Expression is Identifier ident)
         {
             if (ident.Name.Equals("abi"))
             {
                 return(true);
             }
         }
     }
     return(false);
 }
コード例 #40
0
 public object EvalFunction(FunctionCall funcref, object[] args, TypeDescriptor resultType)
 {
     if (funcref.Callee is IntrinsicFunction)
     {
         IntrinsicFunction ifun   = (IntrinsicFunction)funcref.Callee;
         MethodBase        mmodel = ifun.MethodModel;
         if (mmodel != null && mmodel.IsStatic)
         {
             object result = mmodel.ConvertArgumentsAndInvoke(null, args);
             return(result);
         }
     }
     return(DoEvalFunction(funcref, args));
 }
コード例 #41
0
ファイル: Parser.cs プロジェクト: danielsada/deep-lingo
        public Node StatementList()
        {
            var exprList = new FunctionCall();

            while (FirstOfExprUnary.Contains(CurrentToken) || CurrentToken == TokenType.LIST)
            {
                if (CurrentToken == TokenType.LIST)
                {
                    Expect(TokenType.LIST);
                }
                exprList.Add(Expression());
            }
            return(exprList);
        }
コード例 #42
0
ファイル: TypeChecker.cs プロジェクト: nobikik9/kju
            private Clause OverloadsClause(FunctionCall call)
            {
                Func <FunctionDeclaration, Alternative> alternative = decl =>
                                                                      Enumerable.Zip(call.Arguments, decl.Parameters, this.MatchArgument)
                                                                      .Append((call.Type, decl.ReturnType))
                                                                      .ToList();

                call.DeclarationCandidates = call.DeclarationCandidates
                                             .Where(decl => call.Arguments.Count == decl.Parameters.Count).ToList();
                var alternatives = call.DeclarationCandidates
                                   .Select(alternative).ToList();

                return(new Clause(alternatives, call.InputRange));
            }
コード例 #43
0
        private void analysisFunctionCall(FunctionCall functionCall)
        {
            if (functionCall == null)
                return;

            switch (functionCall.FunctionName.Value.ToLowerInvariant())
            {
                case "sum":
                    if (!hasCastAsBigInt(functionCall))
                    {
                        IsSuspected = true;
                    }
                    break;
                default:
                    return;
            }
        }
コード例 #44
0
        private static bool hasCastAsBigInt(FunctionCall functionCall)
        {
            foreach (var parameter in functionCall.Parameters.OfType<CastCall>())
            {
                var dataType = parameter.DataType as SqlDataTypeReference;
                if (dataType == null)
                    continue;

                switch (dataType.SqlDataTypeOption)
                {
                    case SqlDataTypeOption.BigInt:
                        return true;
                }
            }

            return false;
        }
コード例 #45
0
ファイル: TextBalloon.cs プロジェクト: steynh/GamingMinor
        public TextBalloon(
            IParent parent,
            PhysicalObject2D talkingObject,
            Vector2 offset, int fontSize, 
            FunctionCall whenDone = null, 
            bool repeatAction = false
        )
            : base(parent)
        {
            TalkingObject = talkingObject;

            Offset = offset;
            _currentRow = 0;
            _started = false;
            _visible = false;

            _charTimer = 0;
            _currentChar = 0;
            _currentRow = 0;
            _fontSize = fontSize;
            WhenDone = whenDone;
            this.RepeatAction = repeatAction;
        }
コード例 #46
0
        private QuerySpecification BuildSelectSubQuery(QuerySpecification originalSelectQuery)
        {
            var subQuerySelect = new QuerySpecification();
            var countStar = new FunctionCall();
            countStar.FunctionName = new Identifier {Value = "count"};
            countStar.Parameters.Add(
                    new ColumnReferenceExpression
                        {
                            ColumnType = ColumnType.Wildcard
                        }
                );

            subQuerySelect.SelectElements.Add(new SelectScalarExpression()
            {
                Expression = countStar
            });

            subQuerySelect.FromClause = originalSelectQuery.FromClause;
            return subQuerySelect;
        }
コード例 #47
0
ファイル: Button.cs プロジェクト: steynh/GamingMinor
 public void AddOnClickListener(FunctionCall listener)
 {
     _onClickListeners.Add(listener);
 }
コード例 #48
0
        public override bool Rewrite(CodeDescriptor decompilee, MethodBase callee, StackElement[] args, IDecompiler stack, IFunctionBuilder builder)
        {
            Type returnType;
            if (callee.ReturnsSomething(out returnType))
            {
                dynamic awaiter = args[0].Sample;
                if ((object)awaiter != null)
                {
                    if (!awaiter.IsCompleted)
                        throw new InvalidOperationException("Task not completed - what are you awaiting for?");

                    object resultSample = awaiter.GetResult();
                    var resultType = resultSample.GetType();
                    var fspec = new FunctionSpec(resultType)
                    {
                        IntrinsicRep = IntrinsicFunctions.GetAsyncResult(awaiter)
                    };
                    var fcall = new FunctionCall()
                    {
                        Callee = fspec,
                        Arguments = new Expression[0],
                        ResultType = resultType
                    };
                    stack.Push(fcall, resultSample);
                }
            }
            return true;
        }
コード例 #49
0
        private void ImplementJoin(JoinParams jp, IAlgorithmBuilder builder, StateInfo sin)
        {
            Contract.Requires<ArgumentNullException>(jp != null);
            Contract.Requires<ArgumentNullException>(builder != null);
            Contract.Requires<ArgumentNullException>(sin != null);

            var jspec = new FunctionSpec(typeof(bool))
            {
                IntrinsicRep = IntrinsicFunctions.Join(jp)
            };
            var jcall = new FunctionCall()
            {
                Callee = jspec,
                Arguments = new Expression[0],
                ResultType = typeof(bool)
            };

            builder.If(jcall);
            var pi1 = new ProceedWithStateInfo()
            {
                TargetState = sin,
                TargetWaitState = false,
                LambdaTransition = true
            };
            var pspec1 = new FunctionSpec(typeof(void))
            {
                IntrinsicRep = IntrinsicFunctions.ProceedWithState(pi1)
            };
            builder.Call(pspec1, LiteralReference.CreateConstant(pi1));
            builder.Else();
            var sin2 = sin.Fork(sin.ILState);
            var pi2 = new ProceedWithStateInfo()
            {
                TargetState = sin,
                TargetWaitState = true,
                LambdaTransition = false
            };
            var pspec2 = new FunctionSpec(typeof(void))
            {
                IntrinsicRep = IntrinsicFunctions.ProceedWithState(pi2)
            };
            builder.Call(pspec2, LiteralReference.CreateConstant(pi2));
            builder.EndIf();

            if (_curCoFSM != null)
                _curCoFSM.Dependencies.Add(jp.JoinedTask);
        }
コード例 #50
0
ファイル: ProcessRequestNode.cs プロジェクト: mm-binary/DARF
        private object processCallArgument(ExecutionContext context, FunctionCall call)
        {
            if (Helper.IsObject(call.Identifier))
            {
                return Helper.ReadObject(call.Identifier);
            }
            else
            {
                string[] blockService = call.Identifier.Split('.');
                string blockId = blockService[0];
                string serviceName = blockService[1];

                object[] args = new object[call.Arguments.Count];

                for(int i=0;i<args.Length;i++)
                {
                    args[i] = processCallArgument(context, call.Arguments[i]);
                }

                return context.CurrentBlockWeb[blockId].ProcessRequest(serviceName, args);
            }
        }
コード例 #51
0
 public override void ExplicitVisit(FunctionCall node)
 {
     analysisFunctionCall(node);
     base.ExplicitVisit(node);
 }
コード例 #52
0
 public void Visit(FunctionCall fc)
 {
     _sb.AppendFormat("{0}(", fc.FunctionName);
     if (fc.Arguments.Count > 0) {
         var i = 0;
         for (; i < fc.Arguments.Count - 1; ++i) {
             fc.Arguments[i].Accept(this);
             _sb.Append(", ");
         }
         fc.Arguments[i].Accept(this);
     }
     _sb.Append(")");
 }
コード例 #53
0
        /// <summary>
        ///     Generates the code for a FunctionCall node.
        /// </summary>
        /// <param name="fc">The FunctionCall node.</param>
        /// <param name="NeedRetVal"></param>
        /// <returns>String containing C# code for FunctionCall fc.</returns>
        private string GenerateFunctionCall(FunctionCall fc, bool NeedRetVal)
        {
            StringBuilder retVal = new StringBuilder(), tmpVal = new StringBuilder();
            bool marc = FuncCallsMarc();

            string Mname = "";
            bool isEnumerable = false;

            //int NeedCloseParent = 0;

            foreach (SYMBOL kid in fc.kids)
            {
                //                if (kid is ArgumentList && m_SLCompatabilityMode)
                if (kid is ArgumentList)
                {
                    ArgumentList al = kid as ArgumentList;
                    int comma = al.kids.Count - 1; // tells us whether to print a comma

                    foreach (SYMBOL s in al.kids)
                    {
                        if (s is BinaryExpression)
                        {
                            BinaryExpression be = s as BinaryExpression;
                            //FunctionCalls += GenerateNode(s);
                            if (be.ExpressionSymbol.Equals("&&") || be.ExpressionSymbol.Equals("||"))
                            {
                                // special case handling for logical and/or, see Mantis 3174
                                tmpVal.Append("((bool)(");
                                tmpVal.Append(GenerateNode((SYMBOL) be.kids.Pop()));
                                tmpVal.Append("))");
                                tmpVal.Append(Generate(String.Format(" {0} ", be.ExpressionSymbol.Substring(0, 1)), be));
                                tmpVal.Append("((bool)(");
                                foreach (SYMBOL kidb in be.kids)
                                    retVal.Append(GenerateNode(kidb));
                                tmpVal.Append("))");
                            }
                            else
                            {
                                tmpVal.Append(GenerateNode((SYMBOL) be.kids.Pop()));
                                tmpVal.Append(Generate(String.Format(" {0} ", be.ExpressionSymbol), be));
                                foreach (SYMBOL kidb in be.kids)
                                {
                                    if (kidb is FunctionCallExpression)
                                    {
                                        tmpVal.Append(GenerateNode(kidb));
                                    }
                                    else if (kidb is TypecastExpression)
                                    {
                                        tmpVal.Append(Generate(String.Format("({0}) (", ((TypecastExpression) kidb).TypecastType)));
                                        tmpVal.Append(GenerateNode((SYMBOL) kidb.kids.Pop()));
                                        tmpVal.Append(Generate(")"));
                                    }

                                    else
                                        tmpVal.Append(GenerateNode(kidb));
                                }
                            }
                        }
                        else if (s is TypecastExpression)
                        {
                            tmpVal.Append(Generate(String.Format("({0}) (", ((TypecastExpression) s).TypecastType)));
                            tmpVal.Append(GenerateNode((SYMBOL) s.kids.Pop()));
                            tmpVal.Append(Generate(")"));
                        }
                        else
                        {
                            tmpVal.Append(GenerateNode(s));
                        }

                        if (0 < comma--)
                            tmpVal.Append(Generate(", "));
                    }
                }
                else
                {
                    tmpVal.Append(GenerateNode(kid));
                }
            }

            isEnumerable = false;
            bool DTFunction = false;

            string rettype = "void";
            if (LocalMethods.TryGetValue(fc.Id, out rettype))
                isEnumerable = true;
                /* suspended.. API fails with IEnums
                        else if (IenFunctions.TryGetValue(fc.Id, out rettype))
                            isEnumerable = true;
            */
            else if (DTFunctions.Contains(fc.Id))
            {
                DTFunction = true;
            }

            //Check whether this function is an API function
            if (m_apiFunctions.ContainsKey(CheckName(fc.Id)))
            {
                //Add the m_apis link
                fc.Id = String.Format("(({0})m_apis[\"{1}\"]).{2}",
                                      m_apiFunctions[CheckName(fc.Id)].InterfaceName,
                                      m_apiFunctions[CheckName(fc.Id)].Name, fc.Id);
            }

            if (DTFunction)
            {
                retVal.Append(Generate("yield return "));
                retVal.Append(Generate(String.Format("{0}(", CheckName(fc.Id)), fc));
                retVal.Append(tmpVal.ToString());
                retVal.Append(Generate(")"));
            }
            else if (isEnumerable)
            {
                if (m_isInEnumeratedDeclaration && NeedRetVal) //Got to have a retVal for do/while
                {
                    //This is for things like the do/while statement, where a function is in the while() part and can't be dumped in front of the do/while
                    string MethodName = StringUtils.RandomString(10, true);
                    string typeDefs = "";
                    ObjectList arguements = null;
                    if (LocalMethodArguements.TryGetValue(fc.Id, out arguements))
                    {
                        // print the state arguments, if any
                        foreach (SYMBOL kid in arguements)
                        {
                            if (kid is ArgumentDeclarationList)
                            {
                                ArgumentDeclarationList ADL = (ArgumentDeclarationList) kid;
                                typeDefs += (GenerateArgumentDeclarationList(ADL)) + ",";
                            }
                        }
                    }
                    if (typeDefs.Length != 0)
                        typeDefs = typeDefs.Remove(typeDefs.Length - 1);

                    string newMethod = string.Format("private {0} {1}({2}, out bool ahwowuerogng)", rettype, MethodName,
                                                     typeDefs);
                    newMethod += (Generate("{"));
                    newMethod += (Generate("ahwowuerogng = true;"));
                    Mname = StringUtils.RandomString(10, true);
                    newMethod += (Generate("System.Collections.IEnumerator " + Mname + " = "));
                    newMethod += (Generate(String.Format("{0}(", CheckName(fc.Id)), fc));
                    newMethod += (tmpVal.ToString());
                    newMethod += (Generate(");"));

                    newMethod += (Generate(" try {"));
                    newMethod += (Generate(Mname + ".MoveNext();"));
                    newMethod += (Generate("  if(" + Mname + ".Current != null)"));
                    newMethod += (Generate("   return (" + rettype + ")" + Mname + ".Current;"));
                    newMethod += (Generate("  }")); //End of try
                    newMethod += (Generate(" catch(Exception ex) "));
                    newMethod += (Generate("  {"));
                    newMethod += (Generate("  }")); //End of catch
                    newMethod += (Generate("ahwowuerogng = true;"));
                    newMethod += (Generate("return default(" + rettype + ");")); //End while
                    newMethod += "}";
                    MethodsToAdd.Add(newMethod);

                    List<string> fCalls = new List<string>();
                    string boolname = StringUtils.RandomString(10, true);
                    fCalls.Add(Generate("bool " + boolname + " = true;"));
                    retVal.Append(MethodName + "(" + tmpVal.ToString() + ", out " + boolname + ")");
                    lock (FuncCalls)
                        FuncCalls.AddRange(fCalls);
                }
                else
                {
                    //Function calls are added to the DumpFunc command, and will be dumped safely before the statement that occurs here, so we don't have to deal with the issues behind having { and } in this area.
                    Mname = StringUtils.RandomString(10, true);
                    string Exname = StringUtils.RandomString(10, true);
                    List<string> fCalls = new List<string>
                                              {
                                                  Generate("string " + Exname + " =  \"\";"),
                                                  Generate("System.Collections.IEnumerator " + Mname + " = "),
                                                  Generate(String.Format("{0}(", CheckName(fc.Id)), fc),
                                                  tmpVal.ToString(),
                                                  Generate(");"),
                                                  Generate("while (true) {"),
                                                  Generate(" try {"),
                                                  Generate("  if(!" + Mname + ".MoveNext())"),
                                                  Generate("   break;"),
                                                  Generate("  }"),
                                                  Generate(" catch(Exception ex) "),
                                                  Generate("  {"),
                                                  Generate("  " + Exname + " = ex.Message;"),
                                                  Generate("  }"),
                                                  Generate(" if(" + Exname + " != \"\")"),
                                                  Generate("   yield return " + Exname + ";"),
                                                  Generate(" else if(" + Mname + ".Current == null || " + Mname +
                                                           ".Current is DateTime)"),
                                                  Generate("   yield return " + Mname + ".Current;"),
                                                  Generate(" else break;"),
                                                  Generate(" }")
                                              };

                    //Let the other things process for a bit here at the end of each enumeration
                    //Let the other things process for a bit here at the end of each enumeration
                    if (NeedRetVal && rettype != "void")
                    {
                        retVal.Append(" (" + rettype + ") " + Mname + ".Current");
                    }
                    lock (FuncCalls)
                        FuncCalls.AddRange(fCalls);
                }
            }
            else
            {
                retVal.Append(Generate(String.Format("{0}(", CheckName(fc.Id)), fc));
                retVal.Append(tmpVal.ToString());

                retVal.Append(Generate(")"));
            }

            //Function calls are first if needed
            return DumpFunc(marc) + retVal.ToString() + DumpAfterFunc(marc);
        }
コード例 #54
0
 public int IntParameter(FunctionCall data, int num)
 {
     if (data.variables.Count() >= num && num >= 1)
     {
         return (int)Script.Str2Float(GetVar(data.variables[num - 1].value));
     }
     else
         return -1;
 }
コード例 #55
0
 public string StringParameter(FunctionCall data, int num)
 {
     if (data.variables.Count() >= num && num >= 1)
     {
         return GetVar(data.variables[num - 1].value);
     }
     else
         return "NULL";
 }
コード例 #56
0
 /// <summary>
 /// Add a new Bugg to the data store
 /// </summary>
 /// <param name="entity"></param>
 public void Save(FunctionCall entity)
 {
     _entityContext.FunctionCalls.Add(entity);
 }
コード例 #57
0
 /// <summary>
 /// Remove a Bugg from the data store
 /// </summary>
 /// <param name="entity"></param>
 public void Delete(FunctionCall entity)
 {
     _entityContext.FunctionCalls.Remove(entity);
 }
コード例 #58
0
		public ExpressionFunctionCalls(FunctionCall function, Sequence<NamedFunction> functions) {
			Debug.Assert(function != null);
			this.function = function;
			this.functions = functions.ToList();
		}
コード例 #59
0
		public ExpressionFunctionCalls(FunctionCall function): this(function, null) {}
コード例 #60
0
        /// <summary>
        /// Update an existing Bugg
        /// </summary>
        /// <param name="entity"></param>
        public void Update(FunctionCall entity)
        {
            var set = _entityContext.Set<FunctionCall>();
            var entry = set.Local.SingleOrDefault(f => f.Id == entity.Id);

            if (entry != null)
            {
                var attachedFeature = _entityContext.Entry(entry);
                attachedFeature.CurrentValues.SetValues(entity);
                attachedFeature.State = EntityState.Modified;
            }
            else
            {
                _entityContext.FunctionCalls.Attach(entity);
                _entityContext.Entry(entity).State = EntityState.Modified;
            }
        }