Exemple #1
0
 public ForStatement(StatementList Conditions, StatementList Body)
 {
     this.Initialize = Conditions[0];
     this.Condition = Conditions[1];
     this.Step = Conditions[2];
     this.Body = Body;
 }
Exemple #2
0
 internal Statement(IHost host)
     : base(host)
 {
     Attributes = new AttributeList(host);
     Children = new StatementList(host);
     Parameters = new ParameterList(host);
 }
 public TableRowStatement(String var, Expression value, StatementList attributes, StatementList statements)
 {
     _var= var;
     _value = value;
     _attributes = attributes;
     _statements = statements;
 }
Exemple #4
0
        public GeneratedCode Parse(List<Token> _tokens)
        {
            Dictionary<string, Function> Functions = new Dictionary<string, Function>();
            StatementList TopLevelStatements = new StatementList();
            Tokens = _tokens;
            Position = 0;

            GetNextToken(); //Initialize first token
            while (true)
            {
                if (CurToken.Type == TokenType.EOF)
                    break;
                if (CurToken.IsCharacter(";"))
                    GetNextToken(); //eat ;
                else if (CurToken.IsIdentifier("function"))
                {
                    Function func = ParseFunction();
                    Functions[func.Name] = func;
                }
                else
                    TopLevelStatements.Add(ParseStatement());
            }
            Function TopLevel = new Function(TopLevelStatements);
            return new GeneratedCode()
            {
                TopLevelStatements = TopLevel,
                Functions = Functions
            };
        }
        public override Expression VisitReturnValue(ReturnValue returnValue)
        {
            // return a default value of the same type as the return value
            TypeNode returnType = returnValue.Type;
            ITypeParameter itp = returnType as ITypeParameter;
            if (itp != null)
            {
                Local loc = new Local(returnType);

                UnaryExpression loca = new UnaryExpression(loc, NodeType.AddressOf, loc.Type.GetReferenceType());
                StatementList statements = new StatementList(2);

                statements.Add(new AssignmentStatement(new AddressDereference(loca, returnType, false, 0),
                    new Literal(null, SystemTypes.Object)));

                statements.Add(new ExpressionStatement(loc));

                return new BlockExpression(new Block(statements), returnType);
            }

            if (returnType.IsValueType)
                return new Literal(0, returnType);
            
            return new Literal(null, returnType);
        }
Exemple #6
0
 public ForStatement(Statement Initialize, Statement Condition, Statement Step, StatementList Body)
 {
     this.Initialize = Initialize;
     this.Condition = Condition;
     this.Body = Body;
     this.Step = Step;
 }
Exemple #7
0
 private Statement()
 {
     Attributes = new AttributeList();
     Children = new StatementList();
     Parameters = new ParameterList();
     IdentifierParts = new List<Identifier>();
     Errors = new List<ParserError>();
 }
 public Loop(string loopVariable, Expression from, string upDown, Expression to, Expression withClause, StatementList stmts)
 {
     LoopVariable = loopVariable;
     InitialValue = from;
     EndingValue = to;
     StepDirection = upDown;
     Step = withClause;
     Statements = stmts;
 }
Exemple #9
0
 public Normalizer(TypeSystem typeSystem){
   this.typeSystem = typeSystem;
   this.exitTargets = new StatementList();
   this.continueTargets = new StatementList();
   this.currentTryStatements = new Stack();
   this.exceptionBlockFor = new TrivialHashtable();
   this.visitedCompleteTypes = new TrivialHashtable();
   this.EndIfLabel = new TrivialHashtable();
   this.foreachLength = 7;
   this.WrapToBlockExpression = true;
   this.useGenerics = TargetPlatform.UseGenerics;
 }
        public UnlessStatement(Expression condition, StatementList unlessBranch,
                            StatementList elseBranch)
        {
            if (condition == null)
            {
                throw new ArgumentException("Invalid condition for IF statement.");
            }
            _conditionExpr = condition;

            _unlessBranchStatements = unlessBranch;
            _elseBranchStatements = elseBranch;
        }
        public string Render(StatementList statements, object model)
        {
            var factory = _host.DependencyResolver.Resolve<IRendererFactory>();

            StringBuilder sb = new StringBuilder();
            foreach (var element in statements)
            {
                var renderer = factory.GetRenderer(element.Name);
                sb.AppendLine(renderer.Render(element, model));
            }

            return sb.ToString().Trim();
        }
Exemple #12
0
 public override Block VisitBlock(Block block){
   if (block == null) return null;
   StatementList savedStatementList = this.CurrentStatementList;
   try{
     StatementList oldStatements = block.Statements;
     int n = oldStatements == null ? 0 : oldStatements.Length;
     StatementList newStatements = this.CurrentStatementList = block.Statements = new StatementList(n);
     for (int i = 0; i < n; i++)
       newStatements.Add((Statement)this.Visit(oldStatements[i]));
     return block;
   }finally{
     this.CurrentStatementList = savedStatementList;
   }
 }
 public FilterStatement(String filterName, StatementList args)
 {
     _filterName = filterName;
     _filter = Utils.LiquidFilters[filterName];
     if (args != null && args.Count > 0)
     {
         _arguments = new List<Expression>();
         foreach (var statement in args)
             if (statement is Expression)
                 _arguments.Add((Expression) statement);
             else
                 throw new ArgumentException(String.Format("Wrong argument to filter: {0}", statement.Print("")));
     }
 }
        public OutputStatement(Expression expr, StatementList filters)
        {
            _expr = expr;
            if(filters!= null)
            {
                _filters = new List<FilterStatement>();
                foreach (var filter in filters)
                {
                    if(filter is FilterStatement)
                        _filters.Add(filter as FilterStatement);
                    else
                        throw new ArgumentException(filter.Print(""),"filters");
                }

            }
        }
        public override void VisitStatementList(StatementList statements)
        {
            if (statements == null) return;

            for (int i = 0; i < statements.Count; i++)
            {
                var stmt = statements[i];
                if (stmt == null) continue;

                if (stmt.SourceContext.IsValid)
                {
                    this.currentSourceContext = stmt.SourceContext;
                }

                this.Visit(stmt);
            }
        }
 public override Statement VisitBranch(Branch branch){
   if (branch == null) return null;
   if (branch.Target == null) return null;
   branch.Condition = this.VisitExpression(branch.Condition);
   int n = this.localsStack.top+1;
   LocalsStack targetStack = (LocalsStack)this.StackLocalsAtEntry[branch.Target.UniqueKey];
   if (targetStack == null){
     this.StackLocalsAtEntry[branch.Target.UniqueKey] = this.localsStack.Clone();
     return branch;
   }
   //Target block has an entry stack that is different from the current stack. Need to copy stack before branching.
   if (n <= 0) return branch; //Empty stack, no need to copy
   StatementList statements = new StatementList(n+1);
   this.localsStack.Transfer(targetStack, statements);
   statements.Add(branch);
   return new Block(statements);
 }
Exemple #17
0
        public Node Loop()
        {
            var idToken  = Expect(TokenCategory.LOOP);
            var stmtList = new StatementList();

            while (firstOfStatement.Contains(CurrentToken))
            {
                stmtList.Add(Statement());
            }
            Expect(TokenCategory.END);
            Expect(TokenCategory.ENDLINE);
            var result = new Loop()
            {
                stmtList
            };

            result.AnchorToken = idToken;
            return(result);
        }
Exemple #18
0
 /// <summary>
 /// Finds the subsequent statement in this block that defines a condition code based on the
 /// result in expression <paramref name="exp"/>.
 /// </summary>
 /// <param name="p"></param>
 /// <param name="ax"></param>
 /// <returns></returns>
 public CondMatch FindConditionOf(StatementList stms, int iStm, Expression exp)
 {
     for (int i = iStm + 1; i < stms.Count; ++i)
     {
         if (!condm.Match(stms[i].Instruction))
         {
             continue;
         }
         var grf     = (Identifier)condm.CapturedExpressions("grf");
         var condExp = condm.CapturedExpressions("exp");
         if (grf.Storage is FlagGroupStorage && exp == condExp)
         {
             return(new CondMatch {
                 FlagGroup = grf, src = exp, StatementIndex = i
             });
         }
     }
     return(null);
 }
Exemple #19
0
        public void TestSelecColumnsWithAlias()
        {
            StatementList statementList = new StatementList()
            {
                Statements = new List <Statement>()
                {
                    new SelectStatement()
                    {
                        SelectElements = new List <Expressions.SelectExpression>()
                        {
                            new SelectScalarExpression()
                            {
                                Expression = new ColumnReference()
                                {
                                    Identifiers = new List <string>()
                                    {
                                        "c1"
                                    }
                                },
                                Alias = "a"
                            },
                            new SelectScalarExpression()
                            {
                                Expression = new ColumnReference()
                                {
                                    Identifiers = new List <string>()
                                    {
                                        "c2"
                                    }
                                },
                                Alias = "b"
                            }
                        }
                    }
                }
            };

            var expected = "SELECT c1 AS a, c2 AS b";
            var actual   = statementList.Print();

            actual.Should().Be(expected);
        }
        private string GetTableTypeBody(string sqlText)
        {
            var createTableTypeBody = new CodeWriter();

            var parser = new TSql120Parser(false);

            var statementList = new StatementList();
            IList <ParseError> errors;
            var script2 = parser.Parse(new StringReader(sqlText), out errors) as TSqlScript;

            if (errors.Count > 0)
            {
                var errorList = new StringBuilder();
                foreach (var error in errors)
                {
                    errorList.AppendLine($"{error.Message}<br/>");
                }
                throw new ApplicationException(errorList.ToString());
            }

            var scriptGen = new Sql120ScriptGenerator();

            foreach (var batch2 in script2.Batches)
            {
                foreach (var statement in batch2.Statements)
                {
                    var createTypeTableStatement = statement as CreateTypeTableStatement;

                    if (createTypeTableStatement == null)
                    {
                        continue;
                    }

                    string scriptOut;
                    scriptGen.GenerateScript(createTypeTableStatement, out scriptOut);

                    createTableTypeBody.WriteLine(scriptOut);
                }
            }

            return(createTableTypeBody.ToString());
        }
Exemple #21
0
        public void UpdateTwo(Type runnerType)
        {
            var runner = (IQueryRunner)Provider.GetRequiredService(runnerType);

            ResetDb(runner);

            var stmtList = new StatementList();

            stmtList.Update(
                DB.Products.Where(p => p.ProductId == 1),
                (_, builder) => builder.Value(b => b.Name, "Not tonight"));

            stmtList.Update(
                DB.Products.Where(p => p.ProductId == 2),
                (_, builder) => builder.Value(b => b.Name, "Nontoonyt Island"));

            var affectedRows = runner.ExecuteNonQuery(stmtList);

            Assert.AreEqual(2, affectedRows);
        }
 public FilterStatement(String filterName, StatementList args)
 {
     _filterName = filterName;
     _filter     = Utils.LiquidFilters[filterName];
     if (args != null && args.Count > 0)
     {
         _arguments = new List <Expression>();
         foreach (var statement in args)
         {
             if (statement is Expression)
             {
                 _arguments.Add((Expression)statement);
             }
             else
             {
                 throw new ArgumentException(String.Format("Wrong argument to filter: {0}", statement.Print("")));
             }
         }
     }
 }
Exemple #23
0
        public static string CreateStaticConstructorsCallsProcedure()
        {
            StatementList body = new StatementList();

            foreach (var staticConstructor in staticConstructors)
            {
                var ctor = BoogieMethod.From(staticConstructor);
                body.Add(BoogieGenerator.Instance().ProcedureCall(ctor, new List <Expression>(), null));
            }

            string        procedureName       = "$call_static_constructors";
            string        attributes          = String.Empty;
            StatementList localVariables      = new StatementList();
            String        parametersWithTypes = String.Empty;
            String        returnTypeIfAny     = String.Empty;

            BoogieProcedureTemplate temp = new BoogieProcedureTemplate(procedureName, attributes, localVariables, body, parametersWithTypes, returnTypeIfAny, false);

            return(temp.TransformText());
        }
Exemple #24
0
        /// <summary>
        /// Walks the statement list of the given block gathering information from declarations for use by forward references. Does not recurse into nested blocks.
        /// </summary>
        /// <param name="block">The block whose declarations are to be processed</param>
        /// <param name="scope">Maps identifiers to Metadata nodes (e.g. Fields).</param>
        /// <param name="targetFor">Maps labels (Identifiers) to the corresponding labeled blocks (single statements are promoted to blocks for this purpose).</param>
        /// <param name="labelList">A list of all the labels encountered by Declarer.</param>
        public virtual void VisitBlock(Block block, Class scope, TrivialHashtable targetFor, IdentifierList labelList)
        {
            if (block == null)
            {
                return;
            }
            this.scope     = scope;
            this.targetFor = targetFor;
            this.labelList = labelList;
            StatementList statements = block.Statements;

            if (statements == null)
            {
                return;
            }
            for (int i = 0, n = statements.Count; i < n; i++)
            {
                statements[i] = (Statement)this.Visit(statements[i]);
            }
        }
        /// <summary>
        /// Gets the statement for the label, if it does not exist returns null.
        /// </summary>
        public StatementList ReadStatementsForLabel(string label)
        {
            var returnStatements = new StatementList
            {
                Statements = new List <TermStatement>()
            };

            var terms = ReadInternalTermsForLabel(label);

            if (!terms.Any())
            {
                return(null);
            }

            foreach (var internalTerm in terms)
            {
                returnStatements.Statements.Add(ReadRootTermStatement(internalTerm));
            }
            return(returnStatements);
        }
Exemple #26
0
        public void SetVariableIdentityExpression(Type runnerType)
        {
            var stmtList = new StatementList();

            stmtList.Insert(DB.Products, insert => insert.Value(p => p.Name, "test insert product"));
            var identity = stmtList.DeclareSqlVariable <int>("myident");

            stmtList.SetSqlVariable(identity, (ctx) => Function.LastInsertIdentity <int>(ctx));

            var select = stmtList.Select(ctx => new { Identity = identity.Value });

            var runner = (IQueryRunner)Provider.GetRequiredService(runnerType);

            ResetDb(runner);

            var results = runner.ExecuteQuery(select).ToList();

            Assert.AreEqual(1, results.Count, "Should be 1 result");
            Assert.AreEqual(3, results[0].Identity, "New identity should be 3");
        }
Exemple #27
0
        private static BlockStatement MakeMachineTransitionFunctionBody(Machine machine, string transitionName)
        {
            StatementList bodyStmtList = new StatementList();

            SwitchStatement switchStmt = new SwitchStatement();

            switchStmt.Expression = new IdentifierExpression(
                String.Format("{0}_state", machine.Name));

            foreach (var state in machine.States)
            {
                if (state.HasTransitions)
                {
                    foreach (var stateTransitionName in state.GetTransitionNames())
                    {
                        if (stateTransitionName == transitionName)
                        {
                            StatementList caseStmtBodyStmtList = new StatementList();
                            caseStmtBodyStmtList.Add(
                                new InvokeStatement(
                                    new InvokeExpression(
                                        new IdentifierExpression(
                                            String.Format("{0}_{1}_{2}", machine.Name, state.Name, transitionName)))));

                            CaseStatement caseStmt = new CaseStatement(
                                new LiteralExpression(
                                    String.Format("State_{0}", state.Name)),
                                new BlockStatement(caseStmtBodyStmtList));

                            switchStmt.Cases.Add(caseStmt);
                        }
                    }
                }
            }

            switchStmt.DefaultCaseStmt = new BlockStatement();

            bodyStmtList.Add(switchStmt);

            return(new BlockStatement(bodyStmtList));
        }
Exemple #28
0
        public void FuncCallTest5()
        {
            var lambda = new LambdaExpression(MetaData.Empty,
                                              new StatementList(MetaData.Empty,
                                                                new ReturnStatement(MetaData.Empty,
                                                                                    new FunctionCallExpression(MetaData.Empty,
                                                                                                               new LambdaExpression(MetaData.Empty,
                                                                                                                                    new StatementList(MetaData.Empty,
                                                                                                                                                      new ReturnStatement(MetaData.Empty,
                                                                                                                                                                          new FunctionCallExpression(MetaData.Empty,
                                                                                                                                                                                                     new VariableExpression(MetaData.Empty, "recur"),
                                                                                                                                                                                                     new List <Expression>(new[]
            {
                new VariableExpression(MetaData.Empty, "a")
            })))
                                                                                                                                                      ), returnType:
                                                                                                                                    new UnknownType(MetaData.Empty, "i8")),
                                                                                                               new List <Expression>()))),
                                              new List <VariableDeclaration>(new[]
            {
                new VariableDeclaration(MetaData.Empty, "a", type:
                                        new UnknownType(MetaData.Empty, "i8"))
            }), new UnknownType(MetaData.Empty, "i8"));
            var example = new StatementList(MetaData.Empty,
                                            new VariableDeclaration(MetaData.Empty, "recurFunc",
                                                                    lambda),
                                            new VariableDeclaration(MetaData.Empty, "gg", isMutable: true, type:
                                                                    new UnknownType(MetaData.Empty, "i8")),
                                            new AssignmentStatement(MetaData.Empty,
                                                                    new VariableExpression(MetaData.Empty, "gg"),
                                                                    new FunctionCallExpression(MetaData.Empty,
                                                                                               new VariableExpression(MetaData.Empty, "recurFunc"),
                                                                                               new List <Expression>(new[]
            {
                new IntLiteralExpression(MetaData.Empty, "233", true, 8)
            }))));

            example.SurroundWith(Environment.SolarSystem);
            example.PrintDumpInfo();
            Assert.IsTrue(0 == Errors.ErrList.Count);
        }
Exemple #29
0
        public void visitStatementList(StatementList sl)
        {
            Scope parentScope = _currentScope;

            _currentScope = new Scope(parentScope);

            sl.scope = _currentScope;

            // if there are formal args in play, assume they should be added to this scope
            while (_formalArgs.Count > 0)
            {
                Variable v = _formalArgs[0];
                _formalArgs.RemoveAt(0);
                visitVariable(v);
            }

            visitChildren(sl);

            // now that we've finished with the statement list return to the previous scope
            _currentScope = parentScope;
        }
        public Node If()
        {
            var ifToken = Expect(TokenCategory.IF);
            var expr    = Expression();

            Expect(TokenCategory.THEN);
            var stmtList = new StatementList();

            while (firstOfStatement.Contains(CurrentToken))
            {
                stmtList.Add(Statement());
            }
            Expect(TokenCategory.END);
            var result = new If()
            {
                expr, stmtList
            };

            result.AnchorToken = ifToken;
            return(result);
        }
Exemple #31
0
        public void TestSelectStar()
        {
            StatementList statementList = new StatementList()
            {
                Statements = new List <Statement>()
                {
                    new SelectStatement()
                    {
                        SelectElements = new List <Expressions.SelectExpression>()
                        {
                            new SelectStarExpression()
                        }
                    }
                }
            };

            var expected = "SELECT *";
            var actual   = statementList.Print();

            actual.Should().Be(expected);
        }
Exemple #32
0
        /// <summary>
        /// Crea la funcio 'getInstance'
        /// </summary>
        /// <param name="machine">La maquina.</param>
        /// <returns>La declaracio de la funcio.</returns>
        ///
        private FunctionDeclaration MakeGetStateInstanceFunction(Machine machine)
        {
            StatementList statements = new StatementList(
                new ReturnStatement(
                    new SubscriptExpression(
                        new IdentifierExpression("states"),
                        new CastExpression(
                            TypeIdentifier.FromName("int"),
                            new IdentifierExpression("id")
                            )
                        )
                    )
                );

            return(new FunctionDeclaration(
                       "getStateInstance",
                       AccessSpecifier.Public,
                       TypeIdentifier.FromName("State*"),
                       new ArgumentDeclarationList(new ArgumentDeclaration("id", TypeIdentifier.FromName("StateID"))),
                       statements));
        }
Exemple #33
0
        public void ParserTest()
        {
            string     text = @"
            a = 40;
            b = a + 2;
            print(b);";
            SyntaxNode root = ParserWrap.Parse(text);

            var statements = new StatementList();

            statements.Add(new AssignmentStatement(new Identifier("a"), new Int32Const(40)));
            statements.Add(new AssignmentStatement(
                               new Identifier("b"),
                               new BinaryExpression(
                                   new Identifier("a"),
                                   Operation.Add,
                                   new Int32Const(2))));
            statements.Add(new PrintStatement(new Identifier("b"), false));

            Assert.AreEqual(root, new Program(statements));
        }
        /// <summary>
        /// Method returns a list of statements that checks task status.
        /// </summary>
        private static StatementList CreateIfTaskResultIsEqualsTo(
            Parameter taskParameterToCheck, TaskStatus expectedStatus,
            Block endBlock)
        {
            Contract.Ensures(Contract.Result <StatementList>() != null);

            var result = new StatementList();

            // If-statement is slightly different in IL.
            // To get `if (condition) {statements}`
            // we need to generate:
            // if (!condition) goto endBLock; statements; endBlock:

            // This method emits a check that simplifies CheckMethod implementation.

            var statusProperty = GetTaskProperty(taskParameterToCheck, "get_Status");

            Contract.Assert(statusProperty != null, "Can't find Task.Status property");

            // Emitting: var tmpStatus = task.Status;
            var tmpStatus = new Local(statusProperty.ReturnType);

            result.Add(
                new AssignmentStatement(tmpStatus,
                                        new MethodCall(new MemberBinding(taskParameterToCheck, statusProperty),
                                                       new ExpressionList())));

            // if (tmpStatus != expectedStatus)
            // goto endOfMethod;
            // This is an inverted form of the check: if (tmpStatus == expectedStatus) {check}
            result.Add(
                new Branch(
                    new BinaryExpression(
                        tmpStatus,
                        new Literal(expectedStatus),
                        NodeType.Ne),
                    endBlock));

            return(result);
        }
Exemple #35
0
        private CaretCurrentStatement FindCurrentStatement(StatementList statementList, CaretPosition caret)
        {
            if (statementList == null)
            {
                return(null);
            }

            foreach (var statement in statementList.Statements)
            {
                var ft = statementList.ScriptTokenStream[statement.FirstTokenIndex];
                var lt = statementList.ScriptTokenStream[statement.LastTokenIndex];

                if (caret.Line >= ft.Line && caret.Line <= lt.Line)
                {
                    var isBeforeFirstToken = caret.Line == ft.Line && caret.LineCharOffset < ft.Column;
                    var isAfterLastToken   = caret.Line == lt.Line && caret.LineCharOffset > lt.Column + lt.Text.Length;

                    if (!(isBeforeFirstToken || isAfterLastToken))
                    {
                        var currentStatement = new CaretCurrentStatement()
                        {
                            FirstToken = new CaretPosition
                            {
                                Line           = ft.Line,
                                LineCharOffset = ft.Column
                            },

                            LastToken = new CaretPosition
                            {
                                Line           = lt.Line,
                                LineCharOffset = lt.Column + lt.Text.Length
                            }
                        };
                        return(currentStatement);
                    }
                }
            }

            return(null);
        }
Exemple #36
0
        static void Main(string[] args)
        {
            TextReader rdr = new StreamReader(new MemoryStream(
                                                  Encoding.UTF8.GetBytes(
                                                      @"/* comment */ 
                        WITH CteUpdate 
                        AS
                        (
                            SELECT * FROM Table1 
                            WHERE Col1 = 1
                        )
                        UPDATE CteUpdate SET city = ""NY"" WHERE name = ""tom""")
                                                  ));
            TSql110Parser parser = new TSql110Parser(true);

            IList <ParseError> errors;

            StatementList stmtList = parser.ParseStatementList(rdr, out errors);

            // Process errors
            foreach (TSqlStatement stmt in stmtList.Statements)
            {
                Console.WriteLine("Statement type {0}", stmt.GetType());
                if (stmt is SelectStatement)
                {
                    //Process SELECT statment
                }
                else if (stmt is UpdateStatement)
                {
                    //Process UPDATE statment
                    UpdateStatement     stmtUpdate = (UpdateStatement)stmt;
                    NamedTableReference tabRef     = (NamedTableReference)stmtUpdate.UpdateSpecification.Target;
                    Console.Write(" > UPDATE statement > target object {0}", tabRef.SchemaObject.BaseIdentifier.Value);
                }
                else     //Process other statments
                {
                    throw new NotImplementedException();
                }
            }
        }
        public override StatementList VisitStatementList(StatementList statements)
        {
            var oldSL = this.currentSL;
            var oldSLi = this.currentSLindex;
            this.currentSL = statements;

            try
            {
                if (statements == null) return null;
                for (int i = 0, n = statements.Count; i < n; i++)
                {
                    this.currentSLindex = i;
                    statements[i] = (Statement) this.Visit(statements[i]);
                }
                return statements;
            }
            finally
            {
                this.currentSLindex = oldSLi;
                this.currentSL = oldSL;
            }
        }
Exemple #38
0
            internal void Transfer(LocalsStack /*!*/ targetStack, StatementList /*!*/ statements)
            {
                Debug.Assert(targetStack != null);
                if (targetStack == this)
                {
                    return;
                }
                int n = this.top;

                Debug.Assert(n == targetStack.top);
                for (int i = 0; i <= n; i++)
                {
                    Local sloc = this.elements[i];
                    Local tloc = targetStack.elements[i];
                    if (sloc == tloc)
                    {
                        continue;
                    }
                    Debug.Assert(sloc != null && tloc != null);
                    statements.Add(new AssignmentStatement(tloc, sloc));
                }
            }
        public StatementList GetStatementList(TSqlFragment fragment)
        {
            var fragmentTypeName = fragment.GetType().Name;
            var statementList    = new StatementList();

            switch (fragmentTypeName.ToLower())
            {
            case "createprocedurestatement":
                return((fragment as CreateProcedureStatement)?.StatementList);

            case "createviewstatement":
                statementList.Statements.Add((fragment as CreateViewStatement)?.SelectStatement);
                return(statementList);

            case "createfunctionstatement":
                var func = (fragment as CreateFunctionStatement);
                if (func == null)
                {
                    return(null);
                }

                var returnType = func.ReturnType as SelectFunctionReturnType;
                //this is an ITVF, and does not have a statement list, it has one statement in the return block...
                if (func.StatementList == null && returnType != null)
                {
                    statementList.Statements.Add(returnType.SelectStatement);
                    return(statementList);
                }

                return(func.StatementList);

            case "createtriggerstatement":
                return((fragment as CreateTriggerStatement)?.StatementList);

            default:
                //throw new ApplicationException("Unable to determine statement list for fragment type: " + fragmentTypeName);
                return(null);
            }
        }
Exemple #40
0
        public async Task <ActionResult> GetFile(long?fileId)
        {
            Entities.File file = statementBusinessLogic.File_Get(fileId.Value);

            try
            {
                var    filePath = Path.Combine(ConfiguraionProvider.FileStorageFolder, file.FIleUrl);
                byte[] fileContents;
                using (var fs = System.IO.File.OpenRead(filePath))
                {
                    fileContents = new byte[fs.Length];
                    await fs.ReadAsync(fileContents, 0, fileContents.Length);
                }
                return(File(fileContents, System.Net.Mime.MediaTypeNames.Application.Octet, file.FileName));
            }
            catch (Exception ex)
            {
                var exceptionDetails = new ExceptionDetails(ex, "Ошибка при получении файла.");
                var model            = new StatementList(exceptionDetails);
                return(View("Statement", model));
            }
        }
Exemple #41
0
        public Node Loop()
        {
            var result = new Loop()
            {
                AnchorToken = Expect(TokenCategory.LOOP)
            };

            var statementList = new StatementList();

            if (firstOfStatement.Contains(CurrentToken))
            {
                while (firstOfStatement.Contains(CurrentToken))
                {
                    statementList.Add(Statement());
                }
            }
            result.Add(statementList);

            Expect(TokenCategory.END);
            Expect(TokenCategory.SEMICOLON);
            return(result);
        }
Exemple #42
0
        private StatementList ParseChildren(Stream stream)
        {
            StatementList    statement = new StatementList(_host);
            var              open      = stream.Next();
            CloseBracesToken close     = null;

            while (stream.Peek() != null)
            {
                var token = stream.Peek();
                if (token == null)
                {
                    break;
                }

                switch (token.Type)
                {
                case TokenType.Plus:
                    //ignore these?
                    break;

                case TokenType.CloseBrace:
                    //consume closing brace
                    stream.NextNoReturn();
                    goto doneWithChildren;

                default:
                    var statements = ParseStatement(stream);
                    int length     = statements.Count;
                    for (int i = 0; i < length; i++)
                    {
                        statement.Add(statements[i]);
                    }
                    break;
                }
            }

doneWithChildren:
            return(statement);
        }
Exemple #43
0
        private StatementList Invoke(IMethodDefinition member, BoogieVariable receiver)
        {
            Expression receiverObject = receiver;

            if (receiver.Type.Equals(Helpers.BoogieType.Addr))
            {
                AddressExpression addrExpr = new AddressExpression(member.ContainingType, receiver);
                receiverObject = BoogieGenerator.Instance().ReadAddr(addrExpr);
            }

            Expression subtype = Expression.Subtype(Expression.DynamicType(receiverObject), member.ContainingType);

            StatementList     body         = new StatementList();
            List <Expression> argumentList = new List <Expression>();

            argumentList.Add(receiverObject);
            body.Add(BoogieGenerator.Instance().ProcedureCall(BoogieMethod.From(member), argumentList));
            body.Add(BoogieStatement.ReturnStatement);
            var ifExpr = BoogieStatement.If(subtype, body);

            return(ifExpr);
        }
        //public override Block VisitBlock(Block block) {
        //  if(block.Statements != null && block.Statements.Count == 1) {
        //    Return r = block.Statements[0] as Return;
        //    if(r != null) {
        //      Statement s = this.VisitReturn(r);
        //      Block retBlock = s as Block;
        //      if(retBlock != null) {
        //        block.Statements = retBlock.Statements;
        //        return block;
        //      } else {
        //        return base.VisitBlock(block);
        //      }
        //    } else {
        //      return base.VisitBlock(block);
        //    }
        //  } else {
        //    return base.VisitBlock(block);
        //  }
        //}

        public override Statement VisitReturn(Return Return)
        {
            if (Return == null)
            {
                return(null);
            }

            returnCount++;
            this.lastReturnSourceContext = Return.SourceContext;

            StatementList stmts = new StatementList();

            Return.Expression = this.VisitExpression(Return.Expression);

            if (Return.Expression != null)
            {
                MethodCall mc = Return.Expression as MethodCall;
                if (mc != null && mc.IsTailCall)
                {
                    mc.IsTailCall = false;
                }

                var assgnmt = new AssignmentStatement(result, Return.Expression);

                assgnmt.SourceContext = Return.SourceContext;
                stmts.Add(assgnmt);
            }

            // the branch is a "leave" out of the try block that the body will be
            // in.
            var branch = new Branch(null, newExit, false, false, this.leaveExceptionBody);

            branch.SourceContext = Return.SourceContext;

            stmts.Add(branch);

            return(new Block(stmts));
        }
Exemple #45
0
        static void Main(string[] args)
        {
#if debugenabled
            try
            {
#endif
            string Code            = File.ReadAllText("Tests\\Ackermann.cs");
            CodeLexer lexer        = new CodeLexer(Code);
            LexTokenList lexTokens = lexer.Analyze();

            CPreprocessor preProcessor = new CPreprocessor(lexTokens);
            lexTokens = preProcessor.Process();

            Console.WriteLine("LexTokens (post-processed):");
            foreach (LexToken lexToken in lexTokens)
            {
                Console.WriteLine(lexToken.Kind.ToString() + " " + (lexToken.Value == null ? "" : lexToken.Value.ToString()));
            }

            Console.WriteLine("------\nGenerating AST..");

            AstGenerator astGenerator = new AstGenerator(lexTokens);
            StatementList statements  = astGenerator.Generate();

            Console.WriteLine("Generated AST!");

            Console.WriteLine(View.ASTView.GenerateStatements(statements));
#if debugenabled
        }

        catch (Exception ex)
        {
            Console.WriteLine(ex.Message + "\n" + ex.StackTrace);
        }
#endif

            Console.ReadLine();
        }
Exemple #46
0
        public void SetVariableTypes(Type runnerType)
        {
            var stmtList = new StatementList();

            var intVar = stmtList.DeclareSqlVariable <int>("intVar");

            stmtList.SetSqlVariable(intVar, ctx => 1);

            var decimalVar = stmtList.DeclareSqlVariable <decimal>("decimalVar");

            stmtList.SetSqlVariable(decimalVar, ctx => 2.23M);

            var intNullableVar = stmtList.DeclareSqlVariable <int?>("intNullableVar");

            stmtList.SetSqlVariable(intNullableVar, ctx => 42);

            var stringVar = stmtList.DeclareSqlVariable <string>("stringVar");

            stmtList.SetSqlVariable(stringVar, ctx => "test");

            var select = stmtList.Select(ctx => new {
                intVar         = intVar.Value,
                decimalVar     = decimalVar.Value,
                intNullableVar = intNullableVar.Value,
                stringVar      = stringVar.Value
            });
            var runner = (IQueryRunner)Provider.GetRequiredService(runnerType);

            ResetDb(runner);

            var results = runner.ExecuteQuery(select).ToList();

            Assert.AreEqual(1, results.Count, "Should be 1 result");
            Assert.AreEqual(1, results[0].intVar, "intVar should be 1");
            Assert.AreEqual(42, results[0].intNullableVar, "intNullableVar should be 42");
            Assert.AreEqual(2.23M, results[0].decimalVar, "decimalVar should be 2.23");
            Assert.AreEqual("test", results[0].stringVar, "stringVar should be 'test'");
        }
Exemple #47
0
 public int FindUsingInstruction2(StatementList stms, int i, Operator next)
 {
     for (++i; i < stms.Count; ++i)
     {
         if (!(stms[i].Instruction is Assignment ass))
         {
             continue;
         }
         if (!(ass.Src is BinaryExpression bin))
         {
             continue;
         }
         if (bin.Operator == next)
         {
             return(i);
         }
         if (IsCarryFlag(ass.Dst))
         {
             return(-1);
         }
     }
     return(-1);
 }
        //public override Block VisitBlock(Block block) {
        //  if(block.Statements != null && block.Statements.Count == 1) {
        //    Return r = block.Statements[0] as Return;
        //    if(r != null) {
        //      Statement s = this.VisitReturn(r);
        //      Block retBlock = s as Block;
        //      if(retBlock != null) {
        //        block.Statements = retBlock.Statements;
        //        return block;
        //      } else {
        //        return base.VisitBlock(block);
        //      }
        //    } else {
        //      return base.VisitBlock(block);
        //    }
        //  } else {
        //    return base.VisitBlock(block);
        //  }
        //}

        public override Statement VisitReturn(Return Return)
        {
            if (Return == null)
            {
                return null;
            }

            returnCount++;
            this.lastReturnSourceContext = Return.SourceContext;

            StatementList stmts = new StatementList();

            Return.Expression = this.VisitExpression(Return.Expression);

            if (Return.Expression != null)
            {
                MethodCall mc = Return.Expression as MethodCall;
                if (mc != null && mc.IsTailCall)
                {
                    mc.IsTailCall = false;
                }

                var assgnmt = new AssignmentStatement(result, Return.Expression);

                assgnmt.SourceContext = Return.SourceContext;
                stmts.Add(assgnmt);
            }

            // the branch is a "leave" out of the try block that the body will be
            // in.
            var branch = new Branch(null, newExit, false, false, this.leaveExceptionBody);
            branch.SourceContext = Return.SourceContext;

            stmts.Add(branch);

            return new Block(stmts);
        }
        protected void Visit(StatementList statementList)
        {
            for (int i = 0; i < statementList.Count; i++)
            {
                var statement = statementList[i];
                var ifStatement = statement as IfStatement;
                if (ifStatement != null)
                {
                    var result = evaluator.Evaluate(ifStatement.Condition);
                    if (result.HasErrors)
                    {
                        continue;
                    }
                    statementList[i] = result.Value == 1.0 ? ifStatement.Then : ifStatement.Else;
                    if (statementList[i] == null)
                    {
                        statementList.RemoveAt(i);
                    }
                    i--;
                }
            }

            Visit((Node)statementList);
        }
Exemple #50
0
    //================= reader methods ==========================================    
    void AddReadAttributes(TypeNode type, StatementList statements, Identifier reader, Expression target, SchemaValidator validator) {

      if (validator.Attributes != null) {
        Block whileBody = new Block(new StatementList());
        Literal trueLit = Literal.True;
        MethodCall movenext = new MethodCall(new QualifiedIdentifier(reader, Identifier.For("MoveToNextAttribute")), new ExpressionList());
        BinaryExpression condition = new BinaryExpression(movenext, trueLit, NodeType.Eq);
        While w = new While(condition, whileBody);
        statements.Add(w);
        Block lastElseBlock = null;

        Local nameLocal = new Local(SystemTypes.String);
        whileBody.Statements.Add(new AssignmentStatement(nameLocal, new QualifiedIdentifier(reader, Identifier.For("LocalName"))));
        Local nsLocal = new Local(SystemTypes.String);
        whileBody.Statements.Add(new AssignmentStatement(nsLocal, new QualifiedIdentifier(reader, Identifier.For("NamespaceURI"))));

        foreach (SchemaAttDef ad in validator.Attributes) {
          // todo: any way to do tokenized compares?
          BinaryExpression nameEqual = new BinaryExpression(nameLocal,
            new Literal(ad.Name.Name, SystemTypes.String), NodeType.Eq);
          BinaryExpression nsEqual = new BinaryExpression(nsLocal,
            new Literal(ad.Name.Prefix != null ? ad.Name.Prefix.Name : "", SystemTypes.String), NodeType.Eq);
          Block elseBlock = new Block(new StatementList());
          If ifExpr = new If(new BinaryExpression(nameEqual, nsEqual, NodeType.And), new Block(new StatementList()), elseBlock);
          if (lastElseBlock != null) {
            lastElseBlock.Statements.Add(ifExpr);
          } else {
            whileBody.Statements.Add(ifExpr);
          }
          lastElseBlock = elseBlock;

          // body of if test, parse the attribute value as the specified type.
          Debug.Assert(ad.Member is Field || ad.Member is Property);
          AddReadSimpleType(Checker.GetMemberType(ad.Member), ifExpr.TrueBlock.Statements, reader, GetMemberBinding(target, ad.Member), null, true);
        }
        //todo: report unknown attributes?
      }
    }
Exemple #51
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MethodDefinition"/> class.
 /// </summary>
 public MethodDefinition()
 {
     Body = new StatementList();
     declaration = this;
 }
Exemple #52
0
        public override StatementList VisitStatementList(StatementList statements)
        {
            if (statements == null)
            {
                WriteLine(";");
                return null;
            }

            for (int i = 0, n = statements.Count; i < n; i++)
                this.Visit(statements[i]);

            return statements;
        }
Exemple #53
0
 public virtual StatementList VisitStatementList(StatementList statements, StatementList changes, StatementList deletions, StatementList insertions){
   if (statements == null) return changes;
   if (changes != null){
     if (deletions == null || insertions == null)
       Debug.Assert(false);
     else{
     }
   }else if (deletions != null)
     return null;
   return statements;
 }
Exemple #54
0
    void AddReadAllGroup(Class serializer, Block block, TypeNode type, StatementList statements, Identifier reader, 
      Expression target, Expression required, Expression result, ArrayList members, Member mixedMember) {

      // todo: keep track of which members have been read and report error on duplicates
      MethodCall read = new MethodCall(new QualifiedIdentifier(reader, Identifier.For("Read")), new ExpressionList());

      Local sb = new Local(SystemTypes.StringBuilder);
      bool isMixed = mixedMember != null;
      if (isMixed) {
        statements.Add(new AssignmentStatement(sb,
          new Construct(new MemberBinding(null, SystemTypes.StringBuilder), new ExpressionList(), SystemTypes.StringBuilder)));
      }

      Block whileBody = new Block(new StatementList());
      BinaryExpression notEndTag = new BinaryExpression(
        new QualifiedIdentifier(reader, Identifier.For("NodeType")) ,
        new QualifiedIdentifier(Identifier.For("XmlNodeType"), Identifier.For("EndElement")), NodeType.Ne);
      BinaryExpression notEOF = new BinaryExpression(
        new QualifiedIdentifier(reader, Identifier.For("EOF")), Literal.True, NodeType.Ne);
      While w = new While(new BinaryExpression(notEndTag, notEOF, NodeType.And), whileBody);
      statements.Add(w);

      Local nameLocal = new Local(Identifier.For("name"),SystemTypes.String,block);
      Local nsLocal = new Local(Identifier.For("ns"),SystemTypes.String,block);
      Local nodeType = new Local(Identifier.For("nodeType"),Runtime.XmlNodeType,block);

      whileBody.Statements.Add(new AssignmentStatement(nameLocal, new QualifiedIdentifier(reader, Identifier.For("LocalName"))));
      whileBody.Statements.Add(new AssignmentStatement(nsLocal, new QualifiedIdentifier(reader, Identifier.For("NamespaceURI"))));
      whileBody.Statements.Add(new AssignmentStatement(nodeType, new QualifiedIdentifier(reader, Identifier.For("NodeType"))));
      
      Block childBlock = whileBody;

      if (isMixed) {
        // Append the text node to the current StringBuilder contents.
        childBlock = new Block(new StatementList());
        If ifText = new If(IsTextNode(nodeType), new Block(new StatementList()), childBlock);

        whileBody.Statements.Add(ifText);
        ExpressionList args = new ExpressionList();
        args.Add(new QualifiedIdentifier(reader, Identifier.For("Value")));
        ifText.TrueBlock.Statements.Add(new ExpressionStatement(new MethodCall(
          new QualifiedIdentifier(sb, Identifier.For("Append")), args)));
        ifText.TrueBlock.Statements.Add(new ExpressionStatement(read)); // advance to next node
      }      

      If ifElement = new If(new BinaryExpression(nodeType,
        new QualifiedIdentifier(Identifier.For("XmlNodeType"), Identifier.For("Element")), NodeType.Eq),
        new Block(new StatementList()), new Block(new StatementList()));
      childBlock.Statements.Add(ifElement);
      childBlock = ifElement.TrueBlock;

      //AddConsoleWrite(statements, new Literal("name=",SystemTypes.String));
      //AddConsoleWriteLine(statements, nameLocal);
      //AddConsoleWrite(statements, new Literal("nodeType=",SystemTypes.String));
      //AddConsoleWriteLine(statements, nodeType);

      foreach (NamedNode childNode in members) {
        if (!(childNode.Member is Field || childNode.Member is Property)) {
          AddError(statements, reader, RuntimeError.SerializationOfTypeNotSupported, 
            new Literal(childNode.Member.GetType().FullName, SystemTypes.String));
        } else {
          Expression mb = GetMemberBinding(target, childNode.Member);
          childBlock = AddReadChild(block, childBlock.Statements, childNode.Name, childNode.TypeNode, mb, reader, result, true, false).FalseBlock;
          // todo: throw error if child is required. (e.g. NonEmptyIEnumerable...)
        }
      }
      // if it isn't any of the expected elements then throw an error.
      AddError(childBlock.Statements, reader, RuntimeError.NoSuchMember,
        new Expression[2]{new Literal(tempChecker.GetTypeName(type),SystemTypes.String), nameLocal});

      // If it's not an element then consume it anyway to keep the reader advancing.
      // Probably a comment or PI or something.
      ifElement.FalseBlock.Statements.Add(new ExpressionStatement(new MethodCall(
        new QualifiedIdentifier(reader, Identifier.For("Skip")), new ExpressionList())));

      if (isMixed) {
        statements.Add(new AssignmentStatement(GetMemberBinding(target, mixedMember), 
          new MethodCall(new QualifiedIdentifier(sb, Identifier.For("ToString")), new ExpressionList())));         
      }
      statements.Add(new AssignmentStatement(result, Literal.True));

    }
Exemple #55
0
    If AddEmptyElementCheck(StatementList statements, Identifier reader) {
      // make sure the element is not empty.
      If isEmpty = new If(new BinaryExpression(new QualifiedIdentifier(reader, Identifier.For("IsEmptyElement")), Literal.True, NodeType.Eq),
        new Block(new StatementList()), new Block(new StatementList()));

      statements.Add(isEmpty);

      statements = isEmpty.TrueBlock.Statements;
      // consume empty start tag and just return.
      statements.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(reader, Identifier.For("Read")), new ExpressionList())));
  
      return isEmpty;
    }
Exemple #56
0
    void AddReadContentNode(ContentNode n, Block block, StatementList statements, Identifier reader, 
      Expression target, Expression required, Expression result, SchemaValidator validator) {
      if (n.TypeNode == null) {
        Debug.Assert(n is SequenceNode);
        // In the class inheritance case we have two independent left and right children inside
        // a parent sequence that has no unified type or member.
        SequenceNode s = (SequenceNode)n;
        AddReadContentNode(s.LeftChild, block, statements, reader, target, required, result, validator);
        AddReadContentNode(s.RightChild, block, statements, reader, target, required, result, validator);
        return;
      }
      TypeNode ct = n.TypeNode;
      Debug.Assert(ct != null);
      if (n.Member != null && !(n.Member is Method))  {
        target = GetMemberBinding(target, n.Member);
        ct = target.Type;
      }

      // todo: might be content model AND mixed, in which case we have to pass the MixedMember
      // to AddReadTuple, AddReadChoice and AddReadStream.
      if (ct.Template == SystemTypes.GenericBoxed){
        ct = Checker.GetCollectionElementType(ct);
      }
      if (ct is TupleType) {
        AddReadTuple(block, ct as TupleType, statements, reader, target, required, result);
      } else if (ct is TypeUnion) {
        AddReadChoice(block, ct as TypeUnion, statements, reader, target, required, result);
      } else if (IsStream(ct)) {
        AddReadStream(block, ct, statements, reader, target, result);
      } else if (ct is TypeAlias) {
        AddReadAlias(block, ct as TypeAlias, statements, reader, target, required, result);
      } else {
        Identifier name = Checker.GetDefaultElementName(ct);
        AddReadRequiredChild(block, statements, name, ct, target, reader, result, required, true, false);
      }
    }
Exemple #57
0
    void AddReadContent(Class serializer, Block block, TypeNode type, StatementList statements, Identifier reader, 
      Expression target, Expression required, Expression result, SchemaValidator validator) {
    
      // position us in the content.
      statements.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(reader, Identifier.For("MoveToContent")), new ExpressionList())));
      Local elementName = new Local(Identifier.Empty,SystemTypes.String);
      statements.Add(new AssignmentStatement(elementName, new QualifiedIdentifier(reader, Identifier.For("LocalName"))));
      
      // make sure the element is not empty.
      If isEmpty = AddEmptyElementCheck(statements, reader);

      // Read the contents.
      statements = isEmpty.FalseBlock.Statements;
      statements.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(reader, Identifier.For("Read")), new ExpressionList())));
      statements.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(reader, Identifier.For("MoveToContent")), new ExpressionList())));

      ValidationState context = new ValidationState();
      context.ErrorHandler = this.errorHandler;
      validator.validator.InitValidation(context);
      ArrayList members = null;
      if (validator.validator is AllElementsContentValidator) {
        members = validator.validator.ExpectedElements(context, false, false);
        AddReadAllGroup(serializer, block, type, statements, reader, target, required, result, members, validator.validator.MixedMember);
      } else {

        // There should be one root level anonymous Item0 member.
        SequenceNode seq = (SequenceNode)validator.RootNode; // this is a wrapper node.
        if (seq == null) {
          // perhaps it is ContentType.Empty or Mixed.
          if (validator.validator.ContentType == XmlSchemaContentType.Mixed ||
            validator.validator.ContentType == XmlSchemaContentType.TextOnly){
            Debug.Assert(validator.validator.MixedMember != null);
            statements.Add(new AssignmentStatement(GetMemberBinding(target, validator.validator.MixedMember), 
              new MethodCall(new QualifiedIdentifier(reader, Identifier.For("ReadStringElement")), new ExpressionList())));         
          }
          return;
        } else {
          ContentNode n = seq.LeftChild;
          AddReadContentNode(n, block, statements, reader, target, required, result, validator);
        }
      }    

      // consume final end tag
      statements.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(reader, Identifier.For("ReadEndTag")), new ExpressionList(elementName))));
    }
            public override void VisitStatementList(StatementList statements)
            {
                if (statements == null) return;

                for (int i = 0; i < statements.Count; i++)
                {
                    var st = statements[i];
                    if (st != null && st.SourceContext.IsValid)
                    {
                        lastSC = st.SourceContext;
                    }
                    
                    this.Visit(st);
                }
            }
        /// <summary>
        /// Visits the ForEachStatement Node and collects information from it.
        /// </summary>
        /// <param name="forEachStatement">The ForEachStatement</param>
        public override Node Visit(ForEachStatement forEachStatement)
        {
            if (expandForEachStatements)
            {
                // run analysis on collection
                VisitDynamic(forEachStatement.Collection);

                var inference = forEachStatement.Collection.TypeInference.Declaration as Variable;
                if (!(inference != null && inference.Type is ArrayType))
                    return forEachStatement;

                if ((inference.Type as ArrayType).Dimensions.Count > 1)
                {
                    Error(XenkoMessageCode.ErrorMultiDimArray, forEachStatement.Span, inference, forEachStatement, analyzedModuleMixin.MixinName);
                    return forEachStatement;
                }

                var dim = (int)((inference.Type as ArrayType).Dimensions.FirstOrDefault() as LiteralExpression).Value;

                var result = new StatementList();
                for (int i = 0; i < dim; ++i)
                {
                    var cloned = forEachStatement.DeepClone();
                    var replace = new XenkoReplaceExtern(cloned.Variable, new IndexerExpression(cloned.Collection, new LiteralExpression(i)));
                    replace.Run(cloned.Body);
                    result.Add(cloned.Body);
                }

                VisitDynamic(result);
                return result;
            }
            else
            {
                base.Visit(forEachStatement);
                parsingInfo.ForEachStatements.Add(new StatementNodeCouple(forEachStatement, ParentNode));
                return forEachStatement;
            }
        }
Exemple #60
0
    void AddWriteStream(TypeNode type, StatementList statements, TypeNode referringType, Expression src, Identifier writer) {
      // Generate the following code:
      // XxxxSerializer s = new XxxxSerializer();
      // foreach (Xxxx x in src) {
      //    s.Serialize(x,writer);
      // }
      // Where Xxxx is the element type for the given stream type.

      if (type.Template == SystemTypes.GenericNonEmptyIEnumerable) {
        type = Checker.GetIEnumerableTypeFromNonEmptyIEnumerableStruct(this.module, type);
      } else {
        statements = AddCheckForNull(statements, Duplicate(src, referringType), type);
      }
      TypeNode ceType = Checker.GetCollectionElementType(type);  
      //todo: should check that type has an IEnumerator.

      Identifier loopVariable = Identifier.For("e");
      loopVariable.Type = ceType;
      Block body = new Block();
      body.Statements = new StatementList();

      Expression name, ns;
      GetNameAndNamespace(ceType, out name, out ns);

      // call the Serialize method on it, passing the member we're serializing.  
      if (!AddWriteSimpleType(ceType, body.Statements, referringType, writer, loopVariable, name, ns)) {
        AddCallSerializer(ceType, body.Statements, loopVariable, writer, name, ns);
      }

      ForEach fe = new ForEach(ceType, loopVariable, src, body);      
      statements.Add(fe);
    }