Exemplo n.º 1
0
        public static WhileStatementSyntax AddBraces(WhileStatementSyntax whileStatement)
        {
            Debug.Assert(whileStatement != null && NeedsBraces(whileStatement));

            return whileStatement
                .WithStatement(SyntaxFactory.Block(whileStatement.Statement))
                .WithAdditionalAnnotations(Formatter.Annotation);
        }
Exemplo n.º 2
0
        public BoundWhileStatement BindWhile(WhileStatementSyntax node)
        {
            Debug.Assert(node != null);

            var condition = BindBooleanExpression(node.Condition);
            var loopContext = this.containingMethod.BlockMap.GetValueOrDefault(node);
            Debug.Assert(loopContext != null);
            var analyzer = new SemanticAnalyzer(this.containingMethod, loopContext, this.diagnostics);
            var body = analyzer.BindStatement(node.Statement);
            return new BoundWhileStatement(node, condition, body, loopContext.GetBreakLabel(), loopContext.GetContinueLabel());
        }
        public static void Go(OutputWriter writer, WhileStatementSyntax whileStatement)
        {
            var info = new LoopInfo(whileStatement);

            
            writer.WriteIndent();
            writer.Write("while (");
            Core.Write(writer, whileStatement.Condition);
            writer.Write(")\r\n");

            writer.OpenBrace();
            Core.WriteStatementAsBlock(writer, whileStatement.Statement, false);
            writer.CloseBrace();
        }
        private void BuildWhileStatement(WhileStatementSyntax whileStatement)
        {
            var afterBlock    = currentBlock;
            var loopTempBlock = CreateTemporaryBlock();

            BreakTarget.Push(afterBlock);
            ContinueTargets.Push(loopTempBlock);

            var bodyBlock = CreateBlock(loopTempBlock);

            currentBlock = bodyBlock;
            BuildStatement(whileStatement.Statement);

            BreakTarget.Pop();
            ContinueTargets.Pop();

            currentBlock = CreateBinaryBranchBlock(whileStatement, currentBlock, afterBlock);
            BuildExpression(whileStatement.Condition);
            loopTempBlock.SuccessorBlock = currentBlock;

            currentBlock = CreateBlock(currentBlock);
        }
Exemplo n.º 5
0
        public override BoundNode VisitWhileStatement(BoundWhileStatement node)
        {
            Debug.Assert(node != null);

            var rewrittenCondition = (BoundExpression)Visit(node.Condition);
            var rewrittenBody      = (BoundStatement)Visit(node.Body);

            TextSpan conditionSequencePointSpan = default(TextSpan);

            if (this.generateDebugInfo)
            {
                if (!node.WasCompilerGenerated)
                {
                    WhileStatementSyntax whileSyntax = (WhileStatementSyntax)node.Syntax;
                    conditionSequencePointSpan = TextSpan.FromBounds(
                        whileSyntax.WhileKeyword.Span.Start,
                        whileSyntax.CloseParenToken.Span.End);
                }
            }

            return(RewriteWhileStatement(node.Syntax, rewrittenCondition, conditionSequencePointSpan, rewrittenBody, node.BreakLabel, node.ContinueLabel, node.HasErrors));
        }
        private SyntaxNode normalizeBlockedCode(SyntaxNode node)
        {
            IfStatementSyntax ifStatement = node as IfStatementSyntax;

            if (ifStatement != null)
            {
                return(ifStatement.ChildNodes().First());
            }
            ForStatementSyntax forStatement = node as ForStatementSyntax;

            if (forStatement != null)
            {
                return(forStatement.ChildNodes().First());
            }
            WhileStatementSyntax whileStatement = node as WhileStatementSyntax;

            if (whileStatement != null)
            {
                return(whileStatement.ChildNodes().First());
            }
            return(node);
        }
Exemplo n.º 7
0
        public static void ComputeRefactorings(RefactoringContext context, WhileStatementSyntax whileStatement)
        {
            if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceWhileStatementWithDoStatement) &&
                (whileStatement.WhileKeyword.Span.Contains(context.Span)))
            {
                context.RegisterRefactoring(
                    "Replace while with do",
                    cancellationToken =>
                {
                    return(ReplaceWhileWithDoRefactoring.RefactorAsync(
                               context.Document,
                               whileStatement,
                               cancellationToken));
                });
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceWhileWithFor) &&
                context.Span.IsBetweenSpans(whileStatement))
            {
                ReplaceWhileWithForRefactoring.ComputeRefactoring(context, whileStatement);
            }
        }
Exemplo n.º 8
0
        internal static void ConvertIfToWhile()
        {
            //get current block
            BlockSyntax block = Root.DescendantNodes().OfType <BlockSyntax>().Where(n => n.HasAnnotation(CurrentBlock)).Single();

            if (!(block.Parent is IfStatementSyntax))
            {
                return;
            }

            //get if statement
            IfStatementSyntax ifStatement = block.Parent as IfStatementSyntax;
            //change it to a while
            WhileStatementSyntax whileStatement = SyntaxFactory.WhileStatement(ifStatement.Condition, ifStatement.Statement);

            //do the replacement
            Root = Root.ReplaceNode(ifStatement, whileStatement);

            BlockSyntax prevBlock = GetPreviousBlock();

            CurrentBlock = prevBlock.GetAnnotations("Block").Single();
        }
Exemplo n.º 9
0
        public static async Task <Document> RefactorAsync(
            Document document,
            BinaryExpressionSyntax condition,
            ExpressionSyntax expression,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            var whileStatement = (WhileStatementSyntax)condition.Parent;

            WhileStatementSyntax newWhileStatement = whileStatement.ReplaceNode(
                expression.Parent,
                ExtractExpressionFromConditionRefactoring.GetNewCondition(condition, expression));

            newWhileStatement = newWhileStatement.WithFormatterAnnotation();

            root = root.ReplaceNode(
                whileStatement,
                ExtractExpressionToNestedIf(expression, whileStatement, newWhileStatement));

            return(document.WithSyntaxRoot(root));
        }
Exemplo n.º 10
0
        private static Task <Document> RefactorAsync(
            Document document,
            WhileStatementSyntax whileStatement,
            List <LocalDeclarationStatementSyntax> localDeclarations,
            CancellationToken cancellationToken)
        {
            IEnumerable <VariableDeclarationSyntax> declarations = localDeclarations
                                                                   .Select(f => f.Declaration);

            TypeSyntax type = declarations.First().Type.TrimTrivia();

            SeparatedSyntaxList <VariableDeclaratorSyntax> variables = declarations
                                                                       .SelectMany(f => f.Variables)
                                                                       .Select(f => f.TrimTrivia())
                                                                       .ToSeparatedSyntaxList();

            VariableDeclarationSyntax declaration = VariableDeclaration(type, variables);

            ForStatementSyntax forStatement = SyntaxRefactorings.ConvertWhileStatementToForStatement(whileStatement, declaration);

            return(RefactorAsync(document, whileStatement, forStatement, localDeclarations, cancellationToken));
        }
        public static async Task <Document> RefactorAsync(
            Document document,
            WhileStatementSyntax whileStatement,
            CancellationToken cancellationToken)
        {
            StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo(whileStatement);

            if (statementsInfo.Success)
            {
                SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

                int index = FindLocalDeclarationStatementIndex(
                    whileStatement,
                    statementsInfo.Statements,
                    startIndex: 0,
                    count: statementsInfo.IndexOf(whileStatement),
                    mustBeReferencedInsideWhileStatement: true,
                    semanticModel: semanticModel,
                    cancellationToken: cancellationToken);

                if (index >= 0)
                {
                    List <LocalDeclarationStatementSyntax> localDeclarations = statementsInfo
                                                                               .Statements
                                                                               .Skip(index)
                                                                               .Take(statementsInfo.IndexOf(whileStatement) - 1)
                                                                               .Cast <LocalDeclarationStatementSyntax>()
                                                                               .ToList();

                    return(await RefactorAsync(document, whileStatement, localDeclarations, cancellationToken).ConfigureAwait(false));
                }
            }

            return(await document.ReplaceNodeAsync(
                       whileStatement,
                       SyntaxRefactorings.ConvertWhileStatementToForStatement(whileStatement),
                       cancellationToken).ConfigureAwait(false));
        }
Exemplo n.º 12
0
        public override void VisitWhileStatement(WhileStatementSyntax node)
        {
            ContinueInfo ci = new ContinueInfo();

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

            CodeBuilder.AppendFormat("{0}while ", GetIndentString());
            VisitExpressionSyntax(node.Condition);
            CodeBuilder.AppendLine(" do");
            if (ci.HaveContinue)
            {
                if (ci.HaveBreak)
                {
                    CodeBuilder.AppendFormat("{0}local {1} = false", GetIndentString(), ci.BreakFlagVarName);
                    CodeBuilder.AppendLine();
                }
                CodeBuilder.AppendFormat("{0}repeat", GetIndentString());
                CodeBuilder.AppendLine();
            }
            ++m_Indent;
            node.Statement.Accept(this);
            --m_Indent;
            if (ci.HaveContinue)
            {
                CodeBuilder.AppendFormat("{0}until true;", GetIndentString());
                CodeBuilder.AppendLine();
                if (ci.HaveBreak)
                {
                    CodeBuilder.AppendFormat("{0}if {1} then break; end;", GetIndentString(), ci.BreakFlagVarName);
                    CodeBuilder.AppendLine();
                }
            }
            CodeBuilder.AppendFormat("{0}end;", GetIndentString());
            CodeBuilder.AppendLine();

            m_ContinueInfoStack.Pop();
        }
Exemplo n.º 13
0
        private static Task <Document> RefactorAsync <TNode>(
            Document document,
            WhileStatementSyntax whileStatement,
            ForStatementSyntax forStatement,
            List <TNode> list,
            CancellationToken cancellationToken) where TNode : StatementSyntax
        {
            forStatement = forStatement
                           .TrimLeadingTrivia()
                           .PrependToLeadingTrivia(list[0].GetLeadingTrivia());

            StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo(whileStatement);

            SyntaxList <StatementSyntax> statements = statementsInfo.Statements;

            int index = statements.IndexOf(list[0]);

            IEnumerable <StatementSyntax> newStatements = statements.Take(index)
                                                          .Concat(new ForStatementSyntax[] { forStatement })
                                                          .Concat(statements.Skip(index + list.Count + 1));

            return(document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken));
        }
        private static Task <Document> RefactorAsync <TNode>(
            Document document,
            WhileStatementSyntax whileStatement,
            ForStatementSyntax forStatement,
            List <TNode> list,
            CancellationToken cancellationToken) where TNode : StatementSyntax
        {
            forStatement = forStatement
                           .TrimLeadingTrivia()
                           .PrependToLeadingTrivia(list[0].GetLeadingTrivia());

            StatementContainer container = StatementContainer.Create(whileStatement);

            SyntaxList <StatementSyntax> statements = container.Statements;

            int index = statements.IndexOf(list[0]);

            IEnumerable <StatementSyntax> newStatements = statements.Take(index)
                                                          .Concat(new ForStatementSyntax[] { forStatement })
                                                          .Concat(statements.Skip(index + list.Count + 1));

            return(document.ReplaceNodeAsync(container.Node, container.NodeWithStatements(newStatements), cancellationToken));
        }
Exemplo n.º 15
0
        public override void VisitWhileStatement(WhileStatementSyntax node)
        {
            var topOfLoop = GetNextState();

            GotoState(topOfLoop);
            CurrentState = topOfLoop;

            var afterWhileStatement = GetNextState();
            var bodyState           = NewState();

            var newWhileStatement = Js.While(
                (JsExpression)node.Condition.Accept(Transformer),
                GotoStateBlock(bodyState));

            CurrentState.Add(newWhileStatement);
            GotoState(afterWhileStatement);

            CurrentState = bodyState;
            AcceptStatement(node.Statement, afterWhileStatement, topOfLoop);
            GotoState(topOfLoop);

            CurrentState = afterWhileStatement;
        }
Exemplo n.º 16
0
        public override void VisitWhileStatement(WhileStatementSyntax node)
        {
            if (!YieldChecker.HasSpecialStatement(node))
            {
                currentState.Add(StateMachineThisFixer.Fix(node));
            }
            else
            {
                MaybeCreateNewState();

                var nextState      = GetNextState(node);
                var iterationState = currentState;
                iterationState.NextState  = nextState;
                iterationState.BreakState = nextState;

                node = node.WithStatement(SyntaxFactory.Block(CaptureState(node.Statement, iterationState, nextState)));
                iterationState.Statements.Add(node);

                Close(iterationState);

                currentState = nextState;
            }
        }
Exemplo n.º 17
0
        public static Task <Document> RefactorAsync(
            Document document,
            DoStatementSyntax doStatement,
            CancellationToken cancellationToken = default)
        {
            SyntaxTriviaList trailingTrivia = doStatement.Statement
                                              .GetTrailingTrivia()
                                              .EmptyIfWhitespace()
                                              .AddRange(doStatement.CloseParenToken.TrailingTrivia.EmptyIfWhitespace())
                                              .AddRange(doStatement.SemicolonToken.LeadingTrivia.EmptyIfWhitespace())
                                              .AddRange(doStatement.SemicolonToken.TrailingTrivia);

            WhileStatementSyntax newNode = WhileStatement(
                doStatement.WhileKeyword.WithLeadingTrivia(doStatement.DoKeyword.LeadingTrivia),
                doStatement.OpenParenToken,
                doStatement.Condition,
                doStatement.CloseParenToken.WithTrailingTrivia(doStatement.DoKeyword.TrailingTrivia),
                doStatement.Statement.WithTrailingTrivia(trailingTrivia));

            newNode = newNode.WithFormatterAnnotation();

            return(document.ReplaceNodeAsync(doStatement, newNode, cancellationToken));
        }
        public static async Task <Document> RefactorAsync(
            Document document,
            WhileStatementSyntax whileStatement,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            DoStatementSyntax doStatement = DoStatement(
                Token(
                    whileStatement.WhileKeyword.LeadingTrivia,
                    SyntaxKind.DoKeyword,
                    whileStatement.CloseParenToken.TrailingTrivia),
                whileStatement.Statement.WithoutTrailingTrivia(),
                WhileKeyword(),
                whileStatement.OpenParenToken,
                whileStatement.Condition,
                whileStatement.CloseParenToken.WithoutTrailingTrivia(),
                SemicolonToken());

            doStatement = doStatement
                          .WithTriviaFrom(whileStatement)
                          .WithFormatterAnnotation();

            return(await document.ReplaceNodeAsync(whileStatement, doStatement, cancellationToken).ConfigureAwait(false));
        }
Exemplo n.º 19
0
        public static void Go(HaxeWriter writer, WhileStatementSyntax whileStatement)
        {
            writer.WriteIndent();
            writer.Write("while (");
            Core.Write(writer, whileStatement.Condition);
            writer.Write(")\r\n");

            writer.WriteOpenBrace();

            if (whileStatement.Statement is BlockSyntax)
            {
                foreach (var statement in whileStatement.Statement.As <BlockSyntax>().Statements)
                {
                    Core.Write(writer, statement);
                }
            }
            else
            {
                Core.Write(writer, whileStatement.Statement);
            }

            writer.WriteCloseBrace();
        }
            bool IsInConditionExpression(StatementSyntax statement, ISymbol symbol)
            {
                if (statement.Kind == SyntaxKind.IfStatement)
                {
                    IfStatementSyntax ifStatement = (IfStatementSyntax)statement;
                    return(this.model.AnalyzeExpressionDataFlow(ifStatement.Condition).WrittenInside.Contains(symbol));
                }
                else if (statement.Kind == SyntaxKind.WhileStatement)
                {
                    WhileStatementSyntax whileStatement = (WhileStatementSyntax)statement;
                    return(this.model.AnalyzeExpressionDataFlow(whileStatement.Condition).WrittenInside.Contains(symbol));
                }
                else if (statement.Kind == SyntaxKind.DoStatement)
                {
                    DoStatementSyntax doStatement = (DoStatementSyntax)statement;
                    return(this.model.AnalyzeExpressionDataFlow(doStatement.Condition).WrittenInside.Contains(symbol));
                }
                else if (statement.Kind == SyntaxKind.ForStatement)
                {
                    ForStatementSyntax forStatement = (ForStatementSyntax)statement;
                    if (this.model.AnalyzeExpressionDataFlow(forStatement.Condition).WrittenInside.Contains(symbol))
                    {
                        return(true);
                    }

                    if (forStatement.Initializers.Any(n => this.model.AnalyzeExpressionDataFlow(n).WrittenInside.Contains(symbol)))
                    {
                        return(true);
                    }

                    if (forStatement.Incrementors.Any(n => this.model.AnalyzeExpressionDataFlow(n).WrittenInside.Contains(symbol)))
                    {
                        return(true);
                    }
                }
                return(false);
            }
Exemplo n.º 21
0
        private bool TryCompileWhile(WhileStatementSyntax whileSyntax, BasicBlockBuilder builder,
                                     out BasicBlockBuilder newBuilder)
        {
            newBuilder = builder; // Default failure case
            Debug.Assert(_methodInProgress != null);

            // Create a new basic block which will be the backwards branch target
            var conditionBuilder    = builder.CreateSuccessorBlock();
            var conditionBlockIndex = conditionBuilder.Index;

            // Compile the condition
            var conditionValue = ExpressionCompiler.TryCompileExpression(whileSyntax.ConditionSyntax,
                                                                         SimpleType.Bool, _methodInProgress, conditionBuilder, this, _diagnostics);

            if (conditionValue == -1)
            {
                return(false);
            }

            // Then compile the body.
            // The return guarantee is not propagated up as we don't know whether the loop will ever be entered.
            // TODO: Recognizing compile-time constant condition
            var bodyBuilder = conditionBuilder.CreateBranch((ushort)conditionValue);

            if (!TryCompileBlock(whileSyntax.BodySyntax, bodyBuilder, out bodyBuilder, out var _))
            {
                return(false);
            }

            // Create the backwards branch
            bodyBuilder.SetSuccessor(conditionBlockIndex);

            // Create the exit branch
            newBuilder = conditionBuilder.CreateSuccessorBlock();

            return(true);
        }
Exemplo n.º 22
0
        public sealed override void VisitWhileStatement(WhileStatementSyntax whileSyntax)
        {
            var outEdge = this.Context.CurrentNode.GetSingleEdge();

            this.Context.CurrentNode.OutgoingEdges.Clear();
            var condition = this.Context.ReenqueueCurrentNode(whileSyntax.Condition, createDisplayNode: true);

            condition.Flags |= FlowNodeFlags.LoopCondition;
            var statement = this.Context.EnqueueNode(whileSyntax.Statement);

            statement.Flags |= FlowNodeFlags.LoopBody;
            condition.AddEdge(statement, ExpressionFactory.True);
            statement.AddEdge(condition);

            this.Context.CurrentNode.OutgoingEdges.Add(outEdge.WithValueCondition(ExpressionFactory.False));

            // TODO: Handle in a more sophisticated way, not causing "while (boolVar)" to create a helper variable
            if (condition.VariableModel == null)
            {
                condition.VariableModel = this.Context.TryCreateTemporaryVariableModel(whileSyntax.Condition);
            }

            return;
        }
Exemplo n.º 23
0
        public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
        {
            SyntaxNode root = await context.Document.GetSyntaxRootAsync(context.CancellationToken);

            WhileStatementSyntax whileStatement = root
                                                  .FindNode(context.Span, getInnermostNodeForTie: true)?
                                                  .FirstAncestorOrSelf <WhileStatementSyntax>();

            if (whileStatement == null)
            {
                return;
            }

            if (whileStatement.Condition != null &&
                whileStatement.Condition.Span.Contains(context.Span) &&
                context.Document.SupportsSemanticModel)
            {
                SemanticModel semanticModel = await context.Document.GetSemanticModelAsync(context.CancellationToken);

                AddBooleanComparisonRefactoring.Refactor(whileStatement.Condition, context, semanticModel);
            }

            FormatBinaryExpressionRefactoring.Refactor(context, whileStatement);
        }
Exemplo n.º 24
0
        /// <summary>
        /// Handles the given while statement.
        /// </summary>
        /// <param name="stmt">Statement</param>
        /// <param name="successor">Successor</param>
        private void HandleWhileStatement(WhileStatementSyntax stmt, ControlFlowGraphNode successor)
        {
            this.SyntaxNodes.Add(stmt.Condition);
            this.IsLoopHeadNode = true;

            if (successor != null)
            {
                this.ISuccessors.Add(successor);
                successor.IPredecessors.Add(this);
                this.LoopExitNode = successor;
            }

            var whileNode = new ControlFlowGraphNode(this.Summary);
            this.ISuccessors.Add(whileNode);
            whileNode.IPredecessors.Add(this);

            if (stmt.Statement is BlockSyntax)
            {
                whileNode.Construct((stmt.Statement as BlockSyntax).Statements, 0, false, this);
            }
            else
            {
                whileNode.Construct(new SyntaxList<StatementSyntax> { stmt.Statement }, 0, false, this);
            }
        }
Exemplo n.º 25
0
        private BoundStatement BindWhile(WhileStatementSyntax node, DiagnosticBag diagnostics)
        {
            Debug.Assert(node != null);

            var loopBinder = this.GetBinder(node);
            Debug.Assert(loopBinder != null);
            return loopBinder.WrapWithVariablesIfAny(node, loopBinder.BindWhileParts(diagnostics, loopBinder));
        }
Exemplo n.º 26
0
        public override SyntaxNode VisitWhileStatement(WhileStatementSyntax node)
        {
            this.loopLevel++;

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

            this.loopLevel--;

            return statement;
        }
Exemplo n.º 27
0
        public override void VisitWhileStatement(WhileStatementSyntax node)
        {
            Debug.Assert((object)_containingMemberOrLambda == _enclosing.ContainingMemberOrLambda);
            var patternBinder = new PatternVariableBinder(node, _enclosing);
            var whileBinder = new WhileBinder(patternBinder, node);
            AddToMap(node, whileBinder);

            Visit(node.Condition, whileBinder);
            VisitPossibleEmbeddedStatement(node.Statement, whileBinder);
        }
Exemplo n.º 28
0
			public override void VisitWhileStatement(WhileStatementSyntax node)
			{
				base.VisitWhileStatement(node);
				_counter++;
			}
 public override void VisitWhileStatement(WhileStatementSyntax node)
 {
     this.VisitWhileStatementDeclarations(node);
     base.VisitWhileStatement(node);
 }
Exemplo n.º 30
0
 public override void VisitWhileStatement(WhileStatementSyntax node) => this.counter.CheckNesting(node.WhileKeyword, () => base.VisitWhileStatement(node));
Exemplo n.º 31
0
        public override SyntaxNode VisitWhileStatement(WhileStatementSyntax node)
        {
            _output.Write(node.WhileKeyword, "while (");
            this.VisitExpression(node.Condition);
            _output.TrivialWriteLine(") {");

            _output.IncreaseIndent();
            this.Visit(node.Statement);
            this.AppendCompensateSemicolon(node.Statement);
            _output.DecreaseIndent();

            _output.TrivialWrite('}');
            return node;
        }
 public WhileStatementInterpreter(StatementInterpreterHandler statementInterpreterHandler, WhileStatementSyntax whileStatementSyntax)
 {
     this.statementInterpreterHandler = statementInterpreterHandler;
     this.whileStatementSyntax        = whileStatementSyntax;
 }
 public override void VisitWhileStatement(WhileStatementSyntax node)
 {
     _builder.Add(node);
     base.VisitWhileStatement(node);
 }
        public override SyntaxNode VisitWhileStatement(WhileStatementSyntax node)
        {
            SyntaxNode rewrittenNode = null;

            if (node.Statement != null)
                rewrittenNode = RewriteWithBlockIfRequired(node, node.Statement);

            return base.VisitWhileStatement((WhileStatementSyntax)rewrittenNode ?? node);
        }
Exemplo n.º 35
0
        public BoundWhileStatement BindWhile(WhileStatementSyntax node, DiagnosticBag diagnostics)
        {
            Debug.Assert(node != null);

            var condition = BindBooleanExpression(node.Condition, diagnostics);
            var loopBinder = this.GetBinder(node);
            Debug.Assert(loopBinder != null);
            var body = loopBinder.BindPossibleEmbeddedStatement(node.Statement, diagnostics);
            return new BoundWhileStatement(node, condition, body, loopBinder.BreakLabel, loopBinder.ContinueLabel);
        }
            public override void VisitWhileStatement(WhileStatementSyntax node)
            {
                var saveCurrentScope = currentScope;
                currentScope = new DeclarationScope(currentScope);

                Visit(node.Condition);
                VisitPossibleEmbeddedStatement(node.Statement);

                Debug.Assert(currentScope.Parent == saveCurrentScope);
                currentScope = saveCurrentScope;
            }
            private IEnumerable<ITypeSymbol> InferTypeInWhileStatement(WhileStatementSyntax whileStatement, SyntaxToken? previousToken = null)
            {
                // If we're position based, then we have to be after the "while("
                if (previousToken.HasValue && previousToken.Value != whileStatement.OpenParenToken)
                {
                    return SpecializedCollections.EmptyEnumerable<ITypeSymbol>();
                }

                return SpecializedCollections.SingletonEnumerable(this.Compilation.GetSpecialType(SpecialType.System_Boolean));
            }
 override public void VisitWhileStatement(WhileStatementSyntax node)
 {
     Complexity++;
     base.VisitWhileStatement(node);
 }
Exemplo n.º 39
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 VisitWhileStatement(WhileStatementSyntax node)
 {
     this.VisitStatement(node);
 }
Exemplo n.º 40
0
        protected override SyntaxNode VisitWhileStatement(WhileStatementSyntax node)
        {
            node = node.Update (node.WhileKeyword, node.OpenParenToken, node.Condition, node.CloseParenToken,
                                GetLoopBlock (node.Statement));

            return base.VisitWhileStatement ((WhileStatementSyntax)node.WithAdditionalAnnotations (this.isLoop));
        }
Exemplo n.º 41
0
        public override void VisitWhileStatement(WhileStatementSyntax node)
        {
            var token = CreateBlock($"while ({node.Condition})", SDNodeRole.WhileLoop);
            _tokenList.Add(token);

            VisitChildren(token.Statements, node.Statement);
        }
Exemplo n.º 42
0
 public override void VisitWhileStatement(WhileStatementSyntax node)
 {
     Emit("while ({0})", node.Condition.ToString());
     using (IndentedBracketScope(node.Statement))
         Visit(node.Statement);
 }
Exemplo n.º 43
0
        protected override void VisitWhileStatement(WhileStatementSyntax node)
        {
            Consider(node.Condition);

            base.VisitWhileStatement(node);
        }
Exemplo n.º 44
0
 public override void VisitWhileStatement(WhileStatementSyntax node)
 {
     Visit(node.Condition);
 }
Exemplo n.º 45
0
 private bool AnalyzeWhileStatement(WhileStatementSyntax whileStatement) =>
 !whileStatement.Statement.IsKind(SyntaxKind.Block);
Exemplo n.º 46
0
        public BoundWhileStatement BindWhile(WhileStatementSyntax node, DiagnosticBag diagnostics)
        {
            Debug.Assert(node != null);

            var loopBinder = this.GetBinder(node);
            Debug.Assert(loopBinder != null);
            return loopBinder.BindWhileParts(diagnostics, loopBinder);
        }
Exemplo n.º 47
0
 public virtual void VisitWhileStatement(WhileStatementSyntax node)
 {
     DefaultVisit(node);
 }
            public override SyntaxNode VisitWhileStatement(WhileStatementSyntax node)
            {
                node = (WhileStatementSyntax)base.VisitWhileStatement(node);

                if (!node.Statement.IsKind(SyntaxKind.Block))
                {
                    this.addedAnnotations = true;
                    node = node.WithStatement(SyntaxFactory.Block(node.Statement));
                }

                return node;
            }
        private static async Task <Document> RefactorAsync(
            Document document,
            ForEachStatementSyntax forEachStatement,
            CancellationToken cancellationToken)
        {
            int position = forEachStatement.SpanStart;

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

            string name = NameGenerator.Default.EnsureUniqueLocalName(DefaultNames.EnumeratorVariable, semanticModel, position, cancellationToken: cancellationToken);

            InvocationExpressionSyntax expression = SimpleMemberInvocationExpression(forEachStatement.Expression, IdentifierName(WellKnownMemberNames.GetEnumeratorMethodName));

            VariableDeclarationSyntax variableDeclaration = VariableDeclaration(VarType(), Identifier(name).WithRenameAnnotation(), expression);

            MemberAccessExpressionSyntax currentExpression = SimpleMemberAccessExpression(IdentifierName(name), IdentifierName("Current"));

            ILocalSymbol localSymbol = semanticModel.GetDeclaredSymbol(forEachStatement, cancellationToken);

            StatementSyntax statement = forEachStatement.Statement;

            StatementSyntax newStatement = statement.ReplaceNodes(
                statement
                .DescendantNodes()
                .Where(node => node.Kind() == SyntaxKind.IdentifierName && localSymbol.Equals(semanticModel.GetSymbol(node, cancellationToken))),
                (node, _) => currentExpression.WithTriviaFrom(node));

            WhileStatementSyntax whileStatement = WhileStatement(
                SimpleMemberInvocationExpression(IdentifierName(name), IdentifierName("MoveNext")),
                newStatement);

            if (semanticModel
                .GetSpeculativeMethodSymbol(position, expression)?
                .ReturnType
                .Implements(SpecialType.System_IDisposable, allInterfaces: true) == true)
            {
                UsingStatementSyntax usingStatement = UsingStatement(
                    variableDeclaration,
                    default(ExpressionSyntax),
                    Block(whileStatement));

                usingStatement = usingStatement
                                 .WithLeadingTrivia(forEachStatement.GetLeadingTrivia())
                                 .WithFormatterAnnotation();

                return(await document.ReplaceNodeAsync(forEachStatement, usingStatement, cancellationToken).ConfigureAwait(false));
            }
            else
            {
                LocalDeclarationStatementSyntax localDeclaration = LocalDeclarationStatement(variableDeclaration)
                                                                   .WithLeadingTrivia(forEachStatement.GetLeadingTrivia())
                                                                   .WithFormatterAnnotation();

                var newStatements = new StatementSyntax[] { localDeclaration, whileStatement.WithFormatterAnnotation() };

                if (forEachStatement.IsEmbedded())
                {
                    BlockSyntax block = Block(newStatements).WithFormatterAnnotation();

                    return(await document.ReplaceNodeAsync(forEachStatement, block, cancellationToken).ConfigureAwait(false));
                }

                return(await document.ReplaceNodeAsync(forEachStatement, newStatements, cancellationToken).ConfigureAwait(false));
            }
        }
Exemplo n.º 50
0
 public override void VisitWhileStatement(WhileStatementSyntax node)
 {
     Visit(node.Condition);
 }
Exemplo n.º 51
0
 private static bool AreEquivalentActiveStatements(WhileStatementSyntax oldNode, WhileStatementSyntax newNode)
 {
     // only check the condition, edits in the body are allowed:
     return AreEquivalentIgnoringLambdaBodies(oldNode.Condition, newNode.Condition);
 }
        public override void VisitWhileStatement(WhileStatementSyntax node)
        {
            if (!YieldChecker.HasSpecialStatement(node))
            {
                currentState.Add(StateMachineThisFixer.Fix(node));
            }
            else
            {
                MaybeCreateNewState();

                var nextState = GetNextState(node);
                var iterationState = currentState;
                iterationState.NextState = nextState;
                iterationState.BreakState = nextState;

                node = node.WithStatement(SyntaxFactory.Block(CaptureState(node.Statement, iterationState, nextState)));
                iterationState.Statements.Add(node);

                Close(iterationState);

                currentState = nextState;
            }
        }
Exemplo n.º 53
0
        public override void VisitWhileStatement(WhileStatementSyntax node)
        {
            Debug.Assert((object)_method == _enclosing.ContainingMemberOrLambda);
            var whileBinder = new WhileBinder(_enclosing, node);
            AddToMap(node, whileBinder);

            VisitPossibleEmbeddedStatement(node.Statement, whileBinder);
        }
Exemplo n.º 54
0
 private void HighlightWhileStatement(WhileStatementSyntax statement, List <TextSpan> spans)
 {
     spans.Add(statement.WhileKeyword.Span);
 }
Exemplo n.º 55
0
        private static int FindLocalDeclarationStatementIndex(
            WhileStatementSyntax whileStatement,
            SyntaxList <StatementSyntax> statements,
            int startIndex,
            int count,
            bool mustBeReferencedInsideWhileStatement,
            SemanticModel semanticModel,
            CancellationToken cancellationToken = default)
        {
            int         resultIndex         = -1;
            int         whileStatementIndex = -1;
            ITypeSymbol typeSymbol          = null;

            for (int i = count - 1; i >= startIndex; i--)
            {
                StatementSyntax statement = statements[i];

                if (!(statement is LocalDeclarationStatementSyntax localDeclaration))
                {
                    return(resultIndex);
                }

                VariableDeclarationSyntax declaration = localDeclaration.Declaration;

                foreach (VariableDeclaratorSyntax variable in declaration.Variables)
                {
                    var symbol = (ILocalSymbol)semanticModel.GetDeclaredSymbol(variable, cancellationToken);

                    if (symbol == null)
                    {
                        continue;
                    }

                    if (symbol.Type.IsErrorType())
                    {
                        continue;
                    }

                    if (typeSymbol == null)
                    {
                        typeSymbol = symbol.Type;
                    }
                    else if (!SymbolEqualityComparer.Default.Equals(typeSymbol, symbol.Type))
                    {
                        return(resultIndex);
                    }

                    ContainsLocalOrParameterReferenceWalker walker = null;

                    try
                    {
                        walker = ContainsLocalOrParameterReferenceWalker.GetInstance(symbol, semanticModel, cancellationToken);

                        if (mustBeReferencedInsideWhileStatement)
                        {
                            walker.VisitWhileStatement(whileStatement);

                            if (!walker.Result)
                            {
                                ContainsLocalOrParameterReferenceWalker.Free(walker);
                                return(resultIndex);
                            }
                        }

                        walker.Result = false;

                        if (whileStatementIndex == -1)
                        {
                            whileStatementIndex = statements.IndexOf(whileStatement);
                        }

                        walker.VisitList(statements, whileStatementIndex + 1);

                        if (walker.Result)
                        {
                            return(resultIndex);
                        }
                    }
                    finally
                    {
                        if (walker != null)
                        {
                            ContainsLocalOrParameterReferenceWalker.Free(walker);
                        }
                    }

                    resultIndex = i;
                }
            }

            return(resultIndex);
        }
Exemplo n.º 56
0
        public override void VisitWhileStatement(WhileStatementSyntax node)
        {
            var whileBinder = new WhileBinder(this.method, enclosing, node);
            AddToMap(node, whileBinder);

            VisitPossibleEmbeddedStatement(node.Statement, whileBinder);
        }
 public override void VisitWhileStatement(WhileStatementSyntax node)
 {
     IncreaseComplexityByNestingPlusOne(node.WhileKeyword);
     VisitWithNesting(node, base.VisitWhileStatement);
 }
 public override void VisitWhileStatement(WhileStatementSyntax node) => CheckNesting(node.WhileKeyword, () => base.VisitWhileStatement(node));
 private bool AnalyzeWhileStatement(WhileStatementSyntax whileStatement) =>
     !whileStatement.Statement.IsKind(SyntaxKind.Block);
 public WhileStatementTranslation(WhileStatementSyntax syntax, SyntaxTranslation parent) : base(syntax, parent)
 {
     Condition = syntax.Condition.Get<ExpressionTranslation>(this);
     Statement = syntax.Statement.Get<StatementTranslation>(this);
 }