public BoundForStatement(ForStatementSyntax syntax, BoundVariableDeclaration declaration, ImmutableArray<BoundExpression> initializers, BoundExpression condition, ImmutableArray<BoundExpression> incrementors, BoundStatement body)
     : base(BoundNodeKind.ForStatement, syntax)
 {
     Declaration = declaration;
     Initializers = initializers;
     Condition = condition;
     Incrementors = incrementors;
     Body = body;
 }
Beispiel #2
0
        protected override SyntaxNode VisitForStatement(ForStatementSyntax node)
        {
            if (!node.DescendentNodes().OfType<BlockSyntax>().Any())
            {
                node = node.Update (node.ForKeyword, node.OpenParenToken, node.DeclarationOpt,
                                    node.Initializers, node.FirstSemicolonToken, node.ConditionOpt,
                                    node.SecondSemicolonToken, node.Incrementors, node.CloseParenToken,
                                    Syntax.Block (statements: node.Statement));
            }

            return base.VisitForStatement (node);
        }
Beispiel #3
0
 public BoundForStatement(
     BoundStatement initStatement,
     BoundExpression condition,
     BoundStatement loopStatement,
     BoundScopeStatement boundStatements,
     ForStatementSyntax statementSyntax)
     : base(statementSyntax)
 {
     InitStatement = initStatement;
     Condition = condition;
     LoopStatement = loopStatement;
     BoundStatements = boundStatements;
 }
Beispiel #4
0
        public override void VisitForStatement(ForStatementSyntax node)
        {
            MethodInfo mi = m_MethodInfoStack.Peek();

            mi.TryCatchUsingOrLoopSwitchStack.Push(false);

            ContinueInfo ci = new ContinueInfo();

            ci.Init(node.Statement);
            m_ContinueInfoStack.Push(ci);

            if (null != node.Declaration)
            {
                VisitVariableDeclaration(node.Declaration);
            }
            if (null != node.Initializers && node.Initializers.Count > 0)
            {
                foreach (var exp in node.Initializers)
                {
                    CodeBuilder.AppendFormat("{0}", GetIndentString());
                    VisitToplevelExpression(exp, ";");
                }
            }
            CodeBuilder.AppendFormat("{0}while( ", GetIndentString());
            if (null != node.Condition)
            {
                var oper = m_Model.GetOperationEx(node) as IForLoopOperation;
                IConversionOperation opd = null;
                if (null != oper)
                {
                    opd = oper.Condition as IConversionOperation;
                }
                OutputExpressionSyntax(node.Condition, opd);
            }
            else
            {
                CodeBuilder.Append("true");
            }
            CodeBuilder.AppendLine(" ){");
            if (ci.HaveContinue)
            {
                if (ci.HaveBreak)
                {
                    CodeBuilder.AppendFormat("{0}local({1}); {1} = false;", GetIndentString(), ci.BreakFlagVarName);
                    CodeBuilder.AppendLine();
                }
                CodeBuilder.AppendFormat("{0}do{{", GetIndentString());
                CodeBuilder.AppendLine();
            }
            ++m_Indent;
            node.Statement.Accept(this);
            --m_Indent;
            if (ci.HaveContinue)
            {
                CodeBuilder.AppendFormat("{0}}}while(false);", GetIndentString());
                CodeBuilder.AppendLine();
                if (ci.HaveBreak)
                {
                    CodeBuilder.AppendFormat("{0}if({1}){{break;}};", GetIndentString(), ci.BreakFlagVarName);
                    CodeBuilder.AppendLine();
                }
            }
            foreach (var exp in node.Incrementors)
            {
                CodeBuilder.AppendFormat("{0}", GetIndentString());
                VisitToplevelExpression(exp, ";");
            }
            CodeBuilder.AppendFormat("{0}}};", GetIndentString());
            CodeBuilder.AppendLine();

            m_ContinueInfoStack.Pop();
            mi.TryCatchUsingOrLoopSwitchStack.Pop();
        }
Beispiel #5
0
 public ForLoopBinder(Binder enclosing, ForStatementSyntax syntax)
     : base(enclosing)
 {
     Debug.Assert(syntax != null);
     _syntax = syntax;
 }
Beispiel #6
0
        protected override SyntaxNode VisitForStatement(ForStatementSyntax node)
        {
            node = node.Update (node.ForKeyword, node.OpenParenToken, node.DeclarationOpt,
                                node.Initializers, node.FirstSemicolonToken, node.ConditionOpt,
                                node.SecondSemicolonToken, node.Incrementors, node.CloseParenToken,
                                GetLoopBlock (node.Statement));

            this.loopLevel++;
            var statement = base.VisitForStatement ((ForStatementSyntax)node.WithAdditionalAnnotations (this.isLoop));
            this.loopLevel--;
            return statement;
        }
 public override void VisitForStatement(ForStatementSyntax node)
 {
     base.VisitForStatement(node);
     _counter++;
 }
Beispiel #8
0
 public override void VisitForStatement(ForStatementSyntax node)
 {
     parent.IncreaseComplexityByNestingPlusOne(node.ForKeyword);
     parent.VisitWithNesting(node, base.VisitForStatement);
 }
 public virtual void VisitForStatement(ForStatementSyntax node)
 {
     DefaultVisit(node);
 }
Beispiel #10
0
        public override SyntaxNode VisitForStatement(ForStatementSyntax node)
        {
            this.loopLevel++;

            var statement = base.VisitForStatement (node
                                .WithStatement (GetLoopBlock (node.Statement)))
                            .WithAdditionalAnnotations (this.isLoop);

            this.loopLevel--;

            return statement;
        }
        private static async Task <Document> ConvertToIncrementingCounterForLoop(Document document, ForStatementSyntax @for, CancellationToken cancellationToken)
        {
            var condition   = (BinaryExpressionSyntax)@for.Condition;
            var newEndValue = @for.Declaration != null
                ? ((BinaryExpressionSyntax)@for.Declaration.Variables[0].Initializer.Value).Left
                : ((BinaryExpressionSyntax)(@for.Initializers[0] as AssignmentExpressionSyntax).Right).Left;

            var newStartValue   = ((BinaryExpressionSyntax)@for.Condition).Right;
            var newDeclaration  = ReplaceStartValue(@for.Declaration, newStartValue);
            var newInitializers = ReplaceStartValue(@for.Initializers, newStartValue);
            var newCondition    = condition
                                  .WithOperatorToken(SyntaxFactory.Token(SyntaxKind.LessThanToken))
                                  .WithRight(newEndValue);

            return(await ReplaceFor(document, @for,
                                    newDeclaration,
                                    newInitializers,
                                    newCondition,
                                    cancellationToken));
        }
        public static async Task <Document> RefactorAsync(
            Document document,
            ForEachStatementSyntax forEachStatement,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (document == null)
            {
                throw new ArgumentNullException(nameof(document));
            }

            if (forEachStatement == null)
            {
                throw new ArgumentNullException(nameof(forEachStatement));
            }

            SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            IEnumerable <ReferencedSymbol> referencedSymbols = await SymbolFinder.FindReferencesAsync(
                semanticModel.GetDeclaredSymbol(forEachStatement),
                document.Project.Solution,
                cancellationToken).ConfigureAwait(false);

            ForStatementSyntax forStatement = ForStatement(
                declaration: VariableDeclaration(
                    PredefinedType(Token(SyntaxKind.IntKeyword)),
                    SingletonSeparatedList(
                        VariableDeclarator(CounterIdentifierName)
                        .WithInitializer(
                            EqualsValueClause(
                                LiteralExpression(
                                    SyntaxKind.NumericLiteralExpression,
                                    Literal(0)))))),
                initializers: SeparatedList <ExpressionSyntax>(),
                condition: BinaryExpression(
                    SyntaxKind.LessThanExpression,
                    IdentifierName(CounterIdentifierName),
                    MemberAccessExpression(
                        SyntaxKind.SimpleMemberAccessExpression,
                        IdentifierName(forEachStatement.Expression.ToString()),
                        IdentifierName(GetCountOrLengthPropertyName(forEachStatement.Expression, semanticModel)))),
                incrementors: SingletonSeparatedList <ExpressionSyntax>(
                    PostfixUnaryExpression(
                        SyntaxKind.PostIncrementExpression,
                        IdentifierName(CounterIdentifierName))),
                statement: forEachStatement.Statement.ReplaceNodes(
                    GetIdentifiers(root, referencedSymbols),
                    (f, g) =>
            {
                return(ElementAccessExpression(
                           IdentifierName(forEachStatement.Expression.ToString()),
                           BracketedArgumentList(
                               SingletonSeparatedList(Argument(IdentifierName(CounterIdentifierName))))
                           ).WithTriviaFrom(f));
            }));

            forStatement = forStatement
                           .WithTriviaFrom(forEachStatement)
                           .WithFormatterAnnotation();

            root = root.ReplaceNode(forEachStatement, forStatement);

            return(document.WithSyntaxRoot(root));
        }
Beispiel #13
0
 public override void VisitForStatement(ForStatementSyntax node)
 {
     reset();
     isFor = true;
     base.VisitForStatement(node);
 }
        public void VisitForStatement(ForStatementSyntax node)
        {
            if (node == null)
                throw new ArgumentNullException("node");

            node.Validate();

            WriteLeadingTrivia(node);

            _writer.WriteIndent();
            _writer.WriteKeyword(PrinterKeyword.For);

            if (_writer.Configuration.Spaces.BeforeParentheses.ForParentheses)
                _writer.WriteSpace();

            _writer.WriteSyntax(Syntax.OpenParen);

            if (_writer.Configuration.Other.AlignMultiLineConstructs.ForStatementHeader)
                _writer.SetAlignmentBreak(true);

            if (_writer.Configuration.Spaces.WithinParentheses.ForParentheses)
                _writer.WriteSpace();

            bool hadOne = false;

            if (node.Declaration != null)
                node.Declaration.Accept(this);

            foreach (var initializer in node.Initializers)
            {
                if (hadOne)
                    _writer.WriteListSeparator();
                else
                    hadOne = true;

                initializer.Accept(this);
            }

            _writer.WriteStatementSeparator(_writer.Configuration.LineBreaksAndWrapping.LineWrapping.WrapForStatementHeader);

            if (node.Condition != null)
                node.Condition.Accept(this);

            _writer.WriteStatementSeparator(_writer.Configuration.LineBreaksAndWrapping.LineWrapping.WrapForStatementHeader);

            hadOne = false;

            foreach (var incrementor in node.Incrementors)
            {
                if (hadOne)
                    _writer.WriteListSeparator();
                else
                    hadOne = true;

                incrementor.Accept(this);
            }

            if (_writer.Configuration.Spaces.WithinParentheses.ForParentheses)
                _writer.WriteSpace();

            _writer.WriteSyntax(Syntax.CloseParen);

            if (_writer.Configuration.Other.AlignMultiLineConstructs.ForStatementHeader)
                _writer.SetAlignmentBreak(false);

            VisitBlockStatement(node.Statement);

            WriteTrailingTrivia(node);
        }
Beispiel #15
0
        public void Flatten(ForStatementSyntax node, List<FlatStatement> instructions)
        {
            this.PushVariableScope(instructions);

            // variable declarations
            Flatten(node.Declaration, instructions);

            string forPrefix = this.MakeUniqueLabelPrefix("for");

            string conditionCheckLabel = forPrefix + "conditionCheck"; // WHERE THE CONTINUE GOES!

            string incrementLabel = forPrefix + "increment";
            string endForLabel = forPrefix + "end"; // WHERE THE BREAK GOES

            string wasContinue = this.SetContinueLabel(incrementLabel);
            string wasBreak = this.SetBreakLabel(endForLabel);

            string beginForLabel = forPrefix + "begin"; // WHERE YOUR MOM GOES

            // check conditions
            instructions.Add(FlatStatement.LABEL(FlatOperand.LabelRef(conditionCheckLabel)));
            FlattenCondition(node.Condition, forPrefix, false, endForLabel, instructions);

            // drop statement
            instructions.Add(FlatStatement.LABEL(FlatOperand.LabelRef(beginForLabel)));
            this.FlattenStatement(node.Statement, instructions);

            // increment
            instructions.Add(FlatStatement.LABEL(FlatOperand.LabelRef(incrementLabel)));

            foreach (ExpressionSyntax es in node.Incrementors)
            {
                FlatOperand fop_incresult = this.ResolveExpression(es, null, instructions);
            }

            // jump to check conditions
            instructions.Add(FlatStatement.JMP(FlatOperand.LabelRef(conditionCheckLabel)));

            // end
            instructions.Add(FlatStatement.LABEL(FlatOperand.LabelRef(endForLabel)));

            this.PopVariableScope(instructions);

            this.SetContinueLabel(wasContinue);
            this.SetBreakLabel(wasBreak);
        }
Beispiel #16
0
 private bool IsEmptyForStatement(ForStatementSyntax forStatement) =>
 forStatement.Initializers.Count == 0 &&
 forStatement.Declaration == null &&
 forStatement.Condition == null &&
 forStatement.Incrementors.Count == 0;
Beispiel #17
0
 private static bool CaretIsInForStatementInitializers(int caretPosition, ForStatementSyntax forStatementSyntax)
 => forStatementSyntax.Initializers.Count != 0 &&
 caretPosition > forStatementSyntax.Initializers.Span.Start &&
 caretPosition <= forStatementSyntax.Initializers.Span.End;
Beispiel #18
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="node"></param>
 /// <remarks>
 /// Statements will cause an AST walker to be created, thus we don't need to go further deeper in the
 /// tree by visiting the node.
 /// </remarks>
 public override void VisitForStatement(ForStatementSyntax node)
 {
     this.VisitStatement(node);
 }
Beispiel #19
0
 public override void VisitForStatement(ForStatementSyntax node)
 {
 }
Beispiel #20
0
 private void HighlightForStatement(ForStatementSyntax statement, List <TextSpan> spans)
 {
     spans.Add(statement.ForKeyword.Span);
 }
Beispiel #21
0
        public override SyntaxNode VisitForStatement(ForStatementSyntax node)
        {
            node = (ForStatementSyntax)base.VisitForStatement(node);

            if (!node.CloseParenToken.IsMissing && node.Statement.Kind != SyntaxKind.Block)
            {
                return CodeAnnotations.Formatting.AddAnnotationTo(
                    Syntax.ForStatement(
                        node.ForKeyword,
                        node.OpenParenToken,
                        node.Declaration,
                        node.Initializers,
                        node.FirstSemicolonToken,
                        node.Condition,
                        node.SecondSemicolonToken,
                        node.Incrementors,
                        node.CloseParenToken,
                        WrapStatementWithBlock(node.Statement)));
            }
            else
            {
                return node;
            }
        }
 public override void VisitForStatement(ForStatementSyntax node)
 {
     VisitStatementIfNotNull(node.Statement);
 }
Beispiel #23
0
 public virtual void Visit(ForStatementSyntax forStatementSyntax)
 {
     Visit(forStatementSyntax.InitStatement);
     Visit(forStatementSyntax.CondExpression);
     Visit(forStatementSyntax.LoopStatement);
     Visit(forStatementSyntax.Statements);
 }
Beispiel #24
0
 public override void VisitForStatement(ForStatementSyntax node)
 {
     Emit <ForBlock, ForStatementSyntax>(node);
 }
Beispiel #25
0
 public override SyntaxNode VisitForStatement(ForStatementSyntax node)
 {
     return(node);
 }
 public ForStatementInterpreter(StatementInterpreterHandler statementInterpreterHandler, ForStatementSyntax forStatementSyntax)
 {
     this.statementInterpreterHandler = statementInterpreterHandler;
     this.forStatementSyntax          = forStatementSyntax;
 }
Beispiel #27
0
 public virtual void VisitForStatement(ForStatementSyntax node)
 {
     DefaultVisit(node);
 }
Beispiel #28
0
        private BoundForStatement BindForStatement(ForStatementSyntax syntax, Symbol parent)
        {
            BindAttributes(syntax.Attributes);

            var forStatementBinder = new Binder(_sharedBinderState, this);

            // Note that we bind declarations in the current scope, not the for statement scope.

            return new BoundForStatement(
                syntax.Declaration != null ? Bind(syntax.Declaration, x => BindForStatementDeclaration(x, parent)) : null,
                syntax.Initializer != null ? forStatementBinder.Bind(syntax.Initializer, forStatementBinder.BindExpression) : null,
                forStatementBinder.Bind(syntax.Condition, forStatementBinder.BindExpression),
                syntax.Incrementor != null ? forStatementBinder.Bind(syntax.Incrementor, forStatementBinder.BindExpression) : null,
                forStatementBinder.Bind(syntax.Statement, x => forStatementBinder.BindStatement(x, parent)));
        }
        public static Task <Document> RefactorAsync(
            Document document,
            ForEachStatementSyntax forEachStatement,
            SemanticModel semanticModel,
            bool reverseLoop = false,
            CancellationToken cancellationToken = default)
        {
            string name = NameGenerator.Default.EnsureUniqueLocalName(
                DefaultNames.ForVariable,
                semanticModel,
                forEachStatement.Statement.SpanStart,
                cancellationToken: cancellationToken);

            SyntaxToken identifier = Identifier(name);

            if (name != DefaultNames.ForVariable)
            {
                identifier = identifier.WithRenameAnnotation();
            }

            ExpressionSyntax forEachExpression = forEachStatement.Expression;

            MemberAccessExpressionSyntax countOrLengthMemberAccess = SimpleMemberAccessExpression(
                forEachExpression.WithoutTrivia(),
                IdentifierName(CSharpUtility.GetCountOrLengthPropertyName(forEachExpression, semanticModel, cancellationToken)));

            VariableDeclarationSyntax    declaration;
            BinaryExpressionSyntax       condition;
            PostfixUnaryExpressionSyntax incrementor;

            if (reverseLoop)
            {
                declaration = VariableDeclaration(
                    IntType(),
                    identifier,
                    EqualsValueClause(
                        SubtractExpression(
                            countOrLengthMemberAccess,
                            NumericLiteralExpression(1))));

                condition = GreaterThanOrEqualExpression(IdentifierName(name), NumericLiteralExpression(0));

                incrementor = PostDecrementExpression(IdentifierName(name));
            }
            else
            {
                declaration = VariableDeclaration(
                    IntType(),
                    identifier,
                    EqualsValueClause(NumericLiteralExpression(0)));

                condition = LessThanExpression(
                    IdentifierName(name),
                    countOrLengthMemberAccess);

                incrementor = PostIncrementExpression(IdentifierName(name));
            }

            StatementSyntax statement = forEachStatement.Statement.ReplaceNodes(
                GetVariableReferences(forEachStatement, semanticModel, cancellationToken),
                (node, _) =>
            {
                return(ElementAccessExpression(
                           forEachExpression.WithoutTrivia(),
                           BracketedArgumentList(SingletonSeparatedList(Argument(IdentifierName(name))))
                           ).WithTriviaFrom(node));
            });

            ForStatementSyntax forStatement = ForStatement(
                declaration: declaration,
                initializers: default(SeparatedSyntaxList <ExpressionSyntax>),
                condition: condition,
                incrementors: SingletonSeparatedList <ExpressionSyntax>(incrementor),
                statement: statement);

            forStatement = forStatement
                           .WithTriviaFrom(forEachStatement)
                           .WithFormatterAnnotation();

            return(document.ReplaceNodeAsync(forEachStatement, forStatement, cancellationToken));
        }
Beispiel #30
0
 public ForLoopBinder(MethodSymbol owner, Binder enclosing, ForStatementSyntax syntax)
     : base(owner, enclosing)
 {
     Debug.Assert(syntax != null);
     this.syntax = syntax;
 }
Beispiel #31
0
        private static void RegisterForStatementConditionRemoval(CodeFixContext context, SyntaxNode root, ForStatementSyntax forStatement)
        {
            context.RegisterCodeFix(
                CodeAction.Create(
                    Title,
                    c =>
            {
                var newRoot = root.ReplaceNode(
                    forStatement,
                    forStatement.WithCondition(null).WithAdditionalAnnotations(Formatter.Annotation));

                return(Task.FromResult(context.Document.WithSyntaxRoot(newRoot)));
            }),
                context.Diagnostics);
        }
Beispiel #32
0
        static async Task <Document> ReplaceForAsync(Document document, ForStatementSyntax oldFor, ForStatementSyntax newFor, CancellationToken cancellationToken)
        {
            var root = await document.GetSyntaxRootAsync(cancellationToken);

            var newRoot = root.ReplaceNode(oldFor, newFor);

            return(document.WithSyntaxRoot(newRoot));
        }
Beispiel #33
0
 private static bool CaretIsInForStatementDeclaration(int caretPosition, ForStatementSyntax forStatementSyntax)
 => forStatementSyntax.Declaration != null &&
 caretPosition > forStatementSyntax.Declaration.Span.Start &&
 caretPosition <= forStatementSyntax.Declaration.Span.End;
Beispiel #34
0
        private static async Task <Document> ConvertToDecrementingCounterForLoopAsync(Document document, ForStatementSyntax @for, CancellationToken cancellationToken)
        {
            var condition   = (BinaryExpressionSyntax)@for.Condition;
            var newEndValue = @for.Declaration != null
                ? @for.Declaration.Variables[0].Initializer.Value
                : (@for.Initializers[0] as AssignmentExpressionSyntax).Right;
            var newStartValue   = SyntaxFactory.BinaryExpression(SyntaxKind.SubtractExpression, condition.Right, One);
            var newDeclaration  = ReplaceStartValue(@for.Declaration, newStartValue);
            var newInitializers = ReplaceStartValue(@for.Initializers, newStartValue);
            var newCondition    = condition
                                  .WithOperatorToken(SyntaxFactory.Token(SyntaxKind.GreaterThanEqualsToken))
                                  .WithRight(newEndValue);

            return(await ReplaceForAsync(document, @for,
                                         newDeclaration,
                                         newInitializers,
                                         newCondition,
                                         cancellationToken));
        }
Beispiel #35
0
 public override void VisitForStatement(ForStatementSyntax node)
 {
     AddLocation(node.ForKeyword);
     base.VisitForStatement(node);
 }
        private Doc PrintForStatementSyntax(ForStatementSyntax node)
        {
            var parts = new Parts(
                this.PrintExtraNewLines(node),
                this.PrintSyntaxToken(node.ForKeyword, " "),
                this.PrintSyntaxToken(node.OpenParenToken)
                );
            var innerGroup = new Parts();

            innerGroup.Push(SoftLine);
            if (node.Declaration != null)
            {
                innerGroup.Push(
                    this.PrintVariableDeclarationSyntax(node.Declaration)
                    );
            }
            innerGroup.Push(
                this.PrintSeparatedSyntaxList(
                    node.Initializers,
                    this.Print,
                    " "
                    )
                );
            innerGroup.Push(this.PrintSyntaxToken(node.FirstSemicolonToken));
            if (node.Condition != null)
            {
                innerGroup.Push(Line, this.Print(node.Condition));
            }
            else
            {
                innerGroup.Push(SoftLine);
            }

            innerGroup.Push(this.PrintSyntaxToken(node.SecondSemicolonToken));
            if (node.Incrementors.Any())
            {
                innerGroup.Push(Line);
            }
            else
            {
                innerGroup.Push(SoftLine);
            }
            innerGroup.Push(
                Indent(
                    this.PrintSeparatedSyntaxList(
                        node.Incrementors,
                        this.Print,
                        Line
                        )
                    )
                );
            parts.Push(Group(Indent(innerGroup.ToArray())));
            parts.Push(this.PrintSyntaxToken(node.CloseParenToken));
            var statement = this.Print(node.Statement);

            if (node.Statement is BlockSyntax)
            {
                parts.Push(statement);
            }
            else
            {
                // TODO 1 force braces? we do in if and else
                parts.Push(Indent(Concat(HardLine, statement)));
            }

            return(Concat(parts));
        }
 public override void VisitForStatement(ForStatementSyntax node) => counter.CheckNesting(node.ForKeyword, () => base.VisitForStatement(node));
Beispiel #38
0
 public override void VisitForStatement(ForStatementSyntax node) => IncrementComplexity(() => base.VisitForStatement(node));
Beispiel #39
0
 internal static void Analyze(SyntaxNodeAnalysisContext context, ForStatementSyntax forStatement)
 {
     Analyze(context, forStatement, forStatement.CloseParenToken, forStatement.Statement);
 }
Beispiel #40
0
        public static void Go(OutputWriter writer, ForStatementSyntax forStatement)
        {
            //   writer.WriteLine(); // Beautify the code ...

            var tempWriter = new TempWriter();

            tempWriter.Indent = writer.Indent;

            var initializers = forStatement.Initializers;
            var initCount    = initializers.Count + (forStatement.Declaration != null?forStatement.Declaration.Variables.Count :0);

            if (initCount > 1)
            {
                tempWriter.WriteLine("//For loop");
                tempWriter.OpenBrace();
                foreach (var init in initializers)
                {
                    tempWriter.WriteLine(Core.WriteString(init, false, tempWriter.Indent) + ";");
                }

                if (forStatement.Declaration != null)
                {
                    var variables = forStatement.Declaration.Variables;
                    foreach (var variable in variables)
                    {
                        var vardec = (TypeProcessor.ConvertType(forStatement.Declaration.Type) + " ");
                        vardec += (WriteIdentifierName.TransformIdentifier(variable.Identifier.Text));

                        if (variable.Initializer != null)
                        {
                            vardec += (" = ");
                            vardec += Core.WriteString(variable.Initializer.Value, false, tempWriter.Indent);
                        }


                        tempWriter.WriteLine(vardec + ";");
                    }
                }
            }

            tempWriter.Write("\r\n");
            tempWriter.WriteIndent();
            tempWriter.Write("for (");

            if (initCount == 1)
            {
                foreach (var init in initializers)
                {
                    Core.Write(tempWriter, init);
                    if (init != initializers.Last())
                    {
                        tempWriter.Write(",");
                    }
                }

                if (forStatement.Declaration != null)
                {
                    var variables = forStatement.Declaration.Variables;
                    foreach (var variable in variables)
                    {
                        //                    writer.WriteIndent();
                        tempWriter.Write(TypeProcessor.ConvertType(forStatement.Declaration.Type) + " ");
                        tempWriter.Write(WriteIdentifierName.TransformIdentifier(variable.Identifier.Text));

                        if (variable.Initializer != null)
                        {
                            tempWriter.Write(" = ");
                            Core.Write(tempWriter, variable.Initializer.Value);
                        }

                        if (variable != variables.LastOrDefault())
                        {
                            tempWriter.Write(",");
                        }
                    }
                }
            }


            tempWriter.Write(";");

            if (forStatement.Condition == null)
            {
                tempWriter.Write("true");
            }
            else
            {
                Core.Write(tempWriter, forStatement.Condition);
            }

            tempWriter.Write(";");

            foreach (var iterator in forStatement.Incrementors)
            {
                Core.Write(tempWriter, iterator);

                if (iterator != forStatement.Incrementors.LastOrDefault())
                {
                    tempWriter.Write(",");
                }
            }

            tempWriter.Write(")");

            writer.WriteLine(tempWriter.ToString());
            writer.OpenBrace();
            Core.WriteStatementAsBlock(writer, forStatement.Statement, false);
            writer.CloseBrace();

            if (initCount > 1)
            {
                writer.CloseBrace();
                writer.WriteLine("//End of for loop");
            }
            //  writer.WriteLine(); // Beautify the code ...
        }
 internal ForInitializerBlock(ForStatementSyntax forNode, Block successor)
     : base(successor)
 {
     ForNode = forNode ?? throw new ArgumentNullException(nameof(forNode));
 }
Beispiel #42
0
        private BoundStatement BindForStatement(ForStatementSyntax syntax)
        {
            var boundInitStatement = BindStatement(syntax.InitStatement);
            var boundCondition = BindExpression(syntax.CondExpression);
            Ensure(() => TypeEquals(boundCondition.Type, new BoolCompilerGeneratedType()), "For condition must be of Type Bool");

            var boundLoopStatement = BindStatement(syntax.LoopStatement);
            var boundStatements = BindScope(syntax.Statements);
            return new BoundForStatement(boundInitStatement, boundCondition, boundLoopStatement, boundStatements, syntax);
        }