コード例 #1
0
        public async Task <CompilationUnitSyntax> ComputeRoot(CompilationUnitSyntax root)
        {
            var variable = _variableDeclaration.Variables.First();

            var newVariableDeclaration = _variableDeclaration
                                         .WithVariables(variable.WithInitializer(null).ItemToSeparatedList())
                                         .WithType(await GetVariableType(variable));

            var codeBlock = _variableDeclaration.Parent.Parent.As <BlockSyntax>();

            var originalPosition = codeBlock.Statements.IndexOf(_variableDeclaration.Parent.As <StatementSyntax>());

            var variableIdentifier = variable.Identifier.Text.ToIdentifierName();

            var newStatements = codeBlock.Statements
                                .RemoveAt(originalPosition)
                                .Insert(originalPosition,
                                        newVariableDeclaration
                                        .ToLocalDeclaration()
                                        .Nicefy())
                                .Insert(originalPosition + 1,
                                        variableIdentifier.AssignWith(variable.Initializer.Value).Nicefy());

            return(root.ReplaceNode(
                       codeBlock,
                       codeBlock.WithStatements(newStatements)));
        }
コード例 #2
0
        public static LocalDeclarationStatementSyntax DeclareLocalVariable(Type variableType, string name,
                                                                           ExpressionSyntax initValue = null,
                                                                           VariableDeclarationType variableDeclarationType = VariableDeclarationType.ExplicitType)
        {
            VariableDeclaratorSyntax varDeclarator = SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(name));

            if (variableType.IsVsArrayType())
            {
                ObjectCreationExpressionSyntax exp = SyntaxFactory.ObjectCreationExpression(variableType.ToTypeSyntax())
                                                     .WithArgumentList(SyntaxFactory.ArgumentList());
                varDeclarator = varDeclarator.WithInitializer(SyntaxFactory.EqualsValueClause(exp));
            }
            else if (initValue != null)
            {
                varDeclarator = varDeclarator.WithInitializer(SyntaxFactory.EqualsValueClause(initValue));
            }

            VariableDeclarationSyntax varDeclaration = variableDeclarationType == VariableDeclarationType.InferredType
                ? SyntaxFactory.VariableDeclaration(SyntaxFactory.IdentifierName("var"))
                : SyntaxFactory.VariableDeclaration(variableType.ToTypeSyntax());

            varDeclaration = varDeclaration.WithVariables(SyntaxFactory.SingletonSeparatedList(varDeclarator));

            return(SyntaxFactory.LocalDeclarationStatement(varDeclaration));
        }
コード例 #3
0
            public override SyntaxNode VisitVariableDeclaration(VariableDeclarationSyntax node)
            {
                // only local variables!
                var p = node.Parent as LocalDeclarationStatementSyntax;

                if (p == null)
                {
                    return(node);
                }

                if (!NeedsRewrite(node))
                {
                    return(node);
                }

                var list = new List <VariableDeclaratorSyntax>(node.Variables.Count);

                foreach (var v in node.Variables)
                {
                    if (IsGoodVariableName(v.Identifier.Text))
                    {
                        list.Add(v);
                    }
                    else
                    {
                        list.Add(v.WithAdditionalAnnotations(s_markerAnnotation));
                        _count++;
                    }
                }

                return(node.WithVariables(SyntaxFactory.SeparatedList(list)));
            }
コード例 #4
0
        private static List <BaseFieldDeclarationSyntax> SplitDeclaration(BaseFieldDeclarationSyntax baseFieldDeclaration)
        {
            var fieldDeclaration = baseFieldDeclaration as FieldDeclarationSyntax;

            if (fieldDeclaration != null)
            {
                VariableDeclarationSyntax declaration = fieldDeclaration.Declaration;
                SeparatedSyntaxList <VariableDeclaratorSyntax> variables = declaration.Variables;
                VariableDeclaratorSyntax first = variables.First();
                var newFieldDeclarations       = new List <BaseFieldDeclarationSyntax>(variables.Count);

                foreach (VariableDeclaratorSyntax variable in variables)
                {
                    var variableDeclarator  = SyntaxFactory.SingletonSeparatedList(variable);
                    var newFieldDeclaration = fieldDeclaration.WithDeclaration(declaration.WithVariables(variableDeclarator));

                    if (variable != first)
                    {
                        var triviaList = newFieldDeclaration.GetLeadingTrivia().WithoutDirectiveTrivia();
                        newFieldDeclaration = newFieldDeclaration.WithLeadingTrivia(triviaList);
                    }

                    newFieldDeclarations.Add(newFieldDeclaration);
                }

                return(newFieldDeclarations);
            }

            var eventFieldDeclaration = baseFieldDeclaration as EventFieldDeclarationSyntax;

            if (eventFieldDeclaration != null)
            {
                VariableDeclarationSyntax declaration = eventFieldDeclaration.Declaration;
                SeparatedSyntaxList <VariableDeclaratorSyntax> variables = declaration.Variables;
                var first = variables.First();
                var newEventFieldDeclarations = new List <BaseFieldDeclarationSyntax>(variables.Count);

                foreach (VariableDeclaratorSyntax variable in variables)
                {
                    var variableDeclarator       = SyntaxFactory.SingletonSeparatedList(variable);
                    var newEventFieldDeclaration = eventFieldDeclaration.WithDeclaration(declaration.WithVariables(variableDeclarator));

                    if (variable != first)
                    {
                        var triviaList = newEventFieldDeclaration.GetLeadingTrivia().WithoutDirectiveTrivia();
                        newEventFieldDeclaration = newEventFieldDeclaration.WithLeadingTrivia(triviaList);
                    }

                    newEventFieldDeclarations.Add(newEventFieldDeclaration);
                }

                return(newEventFieldDeclarations);
            }

            return(null);
        }
        public override SyntaxNode VisitVariableDeclaration(VariableDeclarationSyntax node)
        {
            // determination of the type of the variable(s)
            var typeSymbol = (ITypeSymbol)this.SemanticModel.GetSymbolInfo(node.Type).Symbol;

            bool changed = false;

            // you could declare more than one variable with one expression
            SeparatedSyntaxList <VariableDeclaratorSyntax> vs = node.Variables;
            // we create a space to improve readability
            SyntaxTrivia space = SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, " ");

            for (var i = 0; i < node.Variables.Count; i++)
            {
                // there is not an initialization
                if (this.SemanticModel.GetSymbolInfo(node.Type).Symbol.ToString() == "int" &&
                    node.Variables[i].Initializer == null)
                {
                    // we create a new espression "42"
                    // preceded by the space we create earlier
                    ExpressionSyntax es = SyntaxFactory.ParseExpression("42")
                                          .WithLeadingTrivia(Space);

                    // basically we create an assignment to the espression we just created
                    EqualsValueClauseSyntax evc = SyntaxFactory.EqualsValueClause(es)
                                                  .WithLeadingTrivia(space);

                    // we replace the null initializer with ours
                    vs = vs.Replace(vs.ElementAt(i), vs.ElementAt(i).WithInitializer(evc));

                    changed = true;
                }

                // there is an initialization but it's not to 42
                if (this.SemanticModel.GetSymbolInfo(node.Type).Symbol.ToString() == "int" &&
                    node.Variables[i].Initializer != null &&
                    !node.Variables[i].Initializer.Value.IsEquivalentTo(SyntaxFactory.ParseExpression("42")))
                {
                    ExpressionSyntax es = SyntaxFactory.ParseExpression("42")
                                          .WithLeadingTrivia(Space);

                    EqualsValueClauseSyntax evc = SyntaxFactory.EqualsValueClause(es);

                    vs = vs.Replace(vs.ElementAt(i), vs.ElementAt(i).WithInitializer(evc));

                    changed = true;
                }
            }

            if (changed == true)
            {
                return(node.WithVariables(vs));
            }

            return(base.VisitVariableDeclaration(node));
        }
コード例 #6
0
        static VariableDeclarationSyntax ReplaceStartValue(VariableDeclarationSyntax declaration, ExpressionSyntax newStartValue)
        {
            if (declaration == null)
            {
                return(null);
            }
            var variable = declaration.Variables[0].WithInitializer(SyntaxFactory.EqualsValueClause(newStartValue));

            return(declaration.WithVariables(new SeparatedSyntaxList <VariableDeclaratorSyntax>().Add(variable)));
        }
コード例 #7
0
        public static FieldDeclarationSyntax DeclareField(TypeSyntax typeSyntax, string name, AccessibilityFlags accessibility)
        {
            VariableDeclarationSyntax varDeclaration = SyntaxFactory.VariableDeclaration(typeSyntax);
            var varDeclarator = SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(name));

            FieldDeclarationSyntax fieldDeclaration = SyntaxFactory.FieldDeclaration(
                varDeclaration.WithVariables(SyntaxFactory.SingletonSeparatedList(varDeclarator)))
                                                      .WithModifiers(SyntaxFactory.TokenList(AccessibilityToSyntaxToken(accessibility).ToArray()));

            return(fieldDeclaration);
        }
コード例 #8
0
        private static List <BaseFieldDeclarationSyntax> DeclarationSplitter(
            Document document,
            VariableDeclarationSyntax declaration,
            Func <VariableDeclarationSyntax, BaseFieldDeclarationSyntax> declarationFactory,
            SyntaxTriviaList declarationTrailingTrivia)
        {
            SeparatedSyntaxList <VariableDeclaratorSyntax> variables = declaration.Variables;
            VariableDeclaratorSyntax   first    = variables.First();
            BaseFieldDeclarationSyntax previous = null;
            var newFieldDeclarations            = new List <BaseFieldDeclarationSyntax>(variables.Count);

            foreach (SyntaxNodeOrToken nodeOrToken in variables.GetWithSeparators())
            {
                if (previous == null)
                {
                    VariableDeclaratorSyntax variable = (VariableDeclaratorSyntax)nodeOrToken.AsNode();
                    variable = variable.WithIdentifier(variable.Identifier.WithoutLeadingWhitespace());
                    var variableDeclarator = SyntaxFactory.SingletonSeparatedList(variable);
                    previous = declarationFactory(declaration.WithVariables(variableDeclarator));

                    if (variable != first)
                    {
                        var triviaList = previous.GetLeadingTrivia().WithoutDirectiveTrivia();
                        previous = previous.WithLeadingTrivia(triviaList);
                    }
                }
                else
                {
                    SyntaxToken      commaToken     = nodeOrToken.AsToken();
                    SyntaxTriviaList trailingTrivia = commaToken.TrailingTrivia;
                    if (trailingTrivia.Any())
                    {
                        if (!trailingTrivia.Last().IsKind(SyntaxKind.EndOfLineTrivia))
                        {
                            trailingTrivia = trailingTrivia.WithoutTrailingWhitespace().Add(FormattingHelper.GetNewLineTrivia(document));
                        }
                    }
                    else
                    {
                        trailingTrivia = SyntaxTriviaList.Create(FormattingHelper.GetNewLineTrivia(document));
                    }

                    newFieldDeclarations.Add(previous.WithTrailingTrivia(trailingTrivia));
                    previous = null;
                }
            }

            newFieldDeclarations.Add(previous.WithTrailingTrivia(declarationTrailingTrivia));
            return(newFieldDeclarations);
        }
コード例 #9
0
            public override SyntaxList <StatementSyntax> VisitForBlock(VBSyntax.ForBlockSyntax node)
            {
                var stmt = node.ForStatement;
                ExpressionSyntax          startValue  = (ExpressionSyntax)stmt.FromValue.Accept(nodesVisitor);
                VariableDeclarationSyntax declaration = null;
                ExpressionSyntax          id;

                if (stmt.ControlVariable is VBSyntax.VariableDeclaratorSyntax)
                {
                    var v = (VBSyntax.VariableDeclaratorSyntax)stmt.ControlVariable;
                    declaration = SplitVariableDeclarations(v, nodesVisitor, semanticModel).Values.Single();
                    declaration = declaration.WithVariables(SyntaxFactory.SingletonSeparatedList(declaration.Variables[0].WithInitializer(SyntaxFactory.EqualsValueClause(startValue))));
                    id          = SyntaxFactory.IdentifierName(declaration.Variables[0].Identifier);
                }
                else
                {
                    var v = (ExpressionSyntax)stmt.ControlVariable.Accept(nodesVisitor);
                    startValue = SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, v, startValue);
                    id         = v;
                }

                var step = (ExpressionSyntax)stmt.StepClause?.StepValue.Accept(nodesVisitor);
                PrefixUnaryExpressionSyntax value = step.SkipParens() as PrefixUnaryExpressionSyntax;
                ExpressionSyntax            condition;

                if (value == null)
                {
                    condition = SyntaxFactory.BinaryExpression(SyntaxKind.LessThanOrEqualExpression, id, (ExpressionSyntax)stmt.ToValue.Accept(nodesVisitor));
                }
                else
                {
                    condition = SyntaxFactory.BinaryExpression(SyntaxKind.GreaterThanOrEqualExpression, id, (ExpressionSyntax)stmt.ToValue.Accept(nodesVisitor));
                }
                if (step == null)
                {
                    step = SyntaxFactory.PostfixUnaryExpression(SyntaxKind.PostIncrementExpression, id);
                }
                else
                {
                    step = SyntaxFactory.AssignmentExpression(SyntaxKind.AddAssignmentExpression, id, step);
                }
                var block = SyntaxFactory.Block(node.Statements.SelectMany(s => s.Accept(this)));

                return(SingleStatement(SyntaxFactory.ForStatement(
                                           declaration,
                                           declaration != null ? SyntaxFactory.SeparatedList <ExpressionSyntax>() : SyntaxFactory.SingletonSeparatedList(startValue),
                                           condition,
                                           SyntaxFactory.SingletonSeparatedList(step),
                                           block)));
            }
            public override SyntaxNode VisitVariableDeclaration(VariableDeclarationSyntax node)
            {
                // anonymize variable names in variable declaration
                // var varList = new SeparatedSyntaxList<VariableDeclaratorSyntax>();
                var varList = new List <VariableDeclaratorSyntax>();

                foreach (var varNode in node.Variables)
                {
                    var varName = varNode.Identifier.ValueText;
                    var newName = RegisterNewReanmedVariable(varName);
                    varList.Add(varNode.WithIdentifier(SyntaxFactory.Identifier(newName)));
                }
                var newNode = node.WithVariables(SyntaxFactory.SeparatedList(varList));

                return(base.VisitVariableDeclaration(newNode));
            }
コード例 #11
0
        public static FieldDeclarationSyntax DeclareField(TypeSyntax typeSyntax, string name, AccessibilityFlags accessibility, EqualsValueClauseSyntax defaultValue = null)
        {
            VariableDeclarationSyntax varDeclaration = SyntaxFactory.VariableDeclaration(typeSyntax);
            var varDeclarator = SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(name));

            if (defaultValue != null)
            {
                varDeclarator = varDeclarator.WithInitializer(defaultValue);
            }

            FieldDeclarationSyntax fieldDeclaration = SyntaxFactory.FieldDeclaration(
                varDeclaration.WithVariables(SyntaxFactory.SingletonSeparatedList(varDeclarator)))
                                                      .WithModifiers(SyntaxFactory.TokenList(AccessibilityToSyntaxToken(accessibility).ToArray()));

            return(fieldDeclaration);
        }
コード例 #12
0
        public static LocalDeclarationStatementSyntax DeclareLocalVariable(string typeName, string variableName,
                                                                           ExpressionSyntax initValue = null,
                                                                           VariableDeclarationType variableDeclarationType = VariableDeclarationType.ExplicitType)
        {
            VariableDeclaratorSyntax varDeclarator = SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(variableName));

            if (initValue != null)
            {
                varDeclarator = varDeclarator.WithInitializer(SyntaxFactory.EqualsValueClause(initValue));
            }

            VariableDeclarationSyntax varDeclaration = variableDeclarationType == VariableDeclarationType.InferredType
                ? SyntaxFactory.VariableDeclaration(SyntaxFactory.IdentifierName("var"))
                : SyntaxFactory.VariableDeclaration(SyntaxFactory.IdentifierName(typeName));

            varDeclaration = varDeclaration.WithVariables(SyntaxFactory.SingletonSeparatedList(varDeclarator));

            return(SyntaxFactory.LocalDeclarationStatement(varDeclaration));
        }
コード例 #13
0
        public static FieldDeclarationSyntax DeclareField(Type fieldType, string name,
                                                          AccessibilityFlags accessibility = AccessibilityFlags.Default)
        {
            VariableDeclarationSyntax varDeclaration = SyntaxFactory.VariableDeclaration(fieldType.ToTypeSyntax());
            VariableDeclaratorSyntax  varDeclarator  = SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(name));

            if (fieldType.IsVsArrayType())
            {
                ObjectCreationExpressionSyntax exp = SyntaxFactory.ObjectCreationExpression(fieldType.ToTypeSyntax())
                                                     .WithArgumentList(SyntaxFactory.ArgumentList());
                varDeclarator = varDeclarator.WithInitializer(SyntaxFactory.EqualsValueClause(exp));
            }

            FieldDeclarationSyntax fieldDeclaration = SyntaxFactory.FieldDeclaration(
                varDeclaration.WithVariables(SyntaxFactory.SingletonSeparatedList(varDeclarator)))
                                                      .WithModifiers(SyntaxFactory.TokenList(AccessibilityToSyntaxToken(accessibility).ToArray()));

            return(fieldDeclaration);
        }
コード例 #14
0
        public override SyntaxNode VisitVariableDeclaration(VariableDeclarationSyntax node)
        {
            return(node.WithVariables(
                       SyntaxFactory.SeparatedList(node
                                                   .Variables
                                                   .Select(v => {
                var symbol = GetMonitorableSymbol(v);
                if (symbol == null)
                {
                    return v;
                }

                return v.WithInitializer(
                    v.Initializer.WithValue(
                        InvokeAssignmentMonitor(
                            symbol,
                            v,
                            v.Initializer.Value)));
            }))));
        }
コード例 #15
0
        public override SyntaxNode VisitVariableDeclaration(VariableDeclarationSyntax node)
        {
            var changed = false;

            // you could declare more than one variable with one expression
            var vs = node.Variables;

            // we create a space to improve readability
            var space = SyntaxTrivia(SyntaxKind.WhitespaceTrivia, " ");

            for (var i = 0; i < node.Variables.Count; i++)
            {
                // there is not an initialization or there is an initialization but it's not to 411
                if (_semanticModel.GetSymbolInfo(node.Type).Symbol?.ToString() == "int" &&
                    (node.Variables[i].Initializer == null || (node.Variables[i].Initializer != null
                                                               &&
                                                               !node.Variables[i].Initializer.Value.IsEquivalentTo(ParseExpression("411")))
                    ))
                {
                    // we create a new expression "411"
                    var es = ParseExpression("411").WithLeadingTrivia(space);

                    // basically we create an assignment to the expression we just created
                    var evc = EqualsValueClause(es).WithLeadingTrivia(space);

                    // we replace the null initializer with ours
                    vs = vs.Replace(vs.ElementAt(i), vs.ElementAt(i).WithInitializer(evc));

                    changed = true;
                }
            }

            if (changed)
            {
                return(node.WithVariables(vs));
            }

            return(base.VisitVariableDeclaration(node));
        }
コード例 #16
0
            public override SyntaxList <StatementSyntax> VisitForBlock(VBSyntax.ForBlockSyntax node)
            {
                var stmt = node.ForStatement;
                ExpressionSyntax          startValue  = (ExpressionSyntax)stmt.FromValue.Accept(_nodesVisitor);
                VariableDeclarationSyntax declaration = null;
                ExpressionSyntax          id;

                if (stmt.ControlVariable is VBSyntax.VariableDeclaratorSyntax)
                {
                    var v = (VBSyntax.VariableDeclaratorSyntax)stmt.ControlVariable;
                    declaration = CommonConversions.SplitVariableDeclarations(v).Values.Single();
                    declaration = declaration.WithVariables(SyntaxFactory.SingletonSeparatedList(declaration.Variables[0].WithInitializer(SyntaxFactory.EqualsValueClause(startValue))));
                    id          = SyntaxFactory.IdentifierName(declaration.Variables[0].Identifier);
                }
                else
                {
                    id = (ExpressionSyntax)stmt.ControlVariable.Accept(_nodesVisitor);
                    var symbol = _semanticModel.GetSymbolInfo(stmt.ControlVariable).Symbol;
                    if (symbol != null && !_semanticModel.LookupSymbols(node.FullSpan.Start, name: symbol.Name).Any())
                    {
                        declaration = CommonConversions.CreateVariableDeclarationAndAssignment(symbol.Name, startValue);
                    }
                    else
                    {
                        startValue = SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, id, startValue);
                    }
                }

                var step = (ExpressionSyntax)stmt.StepClause?.StepValue.Accept(_nodesVisitor);
                PrefixUnaryExpressionSyntax value = step.SkipParens() as PrefixUnaryExpressionSyntax;
                ExpressionSyntax            condition;

                // In Visual Basic, the To expression is only evaluated once, but in C# will be evaluated every loop.
                // If it could evaluate differently or has side effects, it must be extracted as a variable
                var preLoopStatements = new List <SyntaxNode>();
                var csToValue         = (ExpressionSyntax)stmt.ToValue.Accept(_nodesVisitor);

                if (!_semanticModel.GetConstantValue(stmt.ToValue).HasValue)
                {
                    var loopToVariableName = GetUniqueVariableNameInScope(node, "loopTo");
                    var loopEndDeclaration = SyntaxFactory.LocalDeclarationStatement(CommonConversions.CreateVariableDeclarationAndAssignment(loopToVariableName, csToValue));
                    // Does not do anything about porting newline trivia upwards to maintain spacing above the loop
                    preLoopStatements.Add(loopEndDeclaration);
                    csToValue = SyntaxFactory.IdentifierName(loopToVariableName);
                }
                ;

                if (value == null)
                {
                    condition = SyntaxFactory.BinaryExpression(SyntaxKind.LessThanOrEqualExpression, id, csToValue);
                }
                else
                {
                    condition = SyntaxFactory.BinaryExpression(SyntaxKind.GreaterThanOrEqualExpression, id, csToValue);
                }
                if (step == null)
                {
                    step = SyntaxFactory.PostfixUnaryExpression(SyntaxKind.PostIncrementExpression, id);
                }
                else
                {
                    step = SyntaxFactory.AssignmentExpression(SyntaxKind.AddAssignmentExpression, id, step);
                }
                var block = SyntaxFactory.Block(node.Statements.SelectMany(s => s.Accept(CommentConvertingVisitor)));
                var forStatementSyntax = SyntaxFactory.ForStatement(
                    declaration,
                    declaration != null
                        ? SyntaxFactory.SeparatedList <ExpressionSyntax>()
                        : SyntaxFactory.SingletonSeparatedList(startValue),
                    condition,
                    SyntaxFactory.SingletonSeparatedList(step),
                    block.UnpackNonNestedBlock());

                return(SyntaxFactory.List(preLoopStatements.Concat(new[] { forStatementSyntax })));
            }
コード例 #17
0
            public override SyntaxList <StatementSyntax> VisitForBlock(VBSyntax.ForBlockSyntax node)
            {
                var stmt = node.ForStatement;
                ExpressionSyntax          startValue  = (ExpressionSyntax)stmt.FromValue.Accept(_nodesVisitor);
                VariableDeclarationSyntax declaration = null;
                ExpressionSyntax          id;

                if (stmt.ControlVariable is VBSyntax.VariableDeclaratorSyntax)
                {
                    var v = (VBSyntax.VariableDeclaratorSyntax)stmt.ControlVariable;
                    declaration = VisualBasicConverter.SplitVariableDeclarations(v, _nodesVisitor, _semanticModel).Values.Single();
                    declaration = declaration.WithVariables(SyntaxFactory.SingletonSeparatedList(declaration.Variables[0].WithInitializer(SyntaxFactory.EqualsValueClause(startValue))));
                    id          = SyntaxFactory.IdentifierName(declaration.Variables[0].Identifier);
                }
                else
                {
                    id = (ExpressionSyntax)stmt.ControlVariable.Accept(_nodesVisitor);
                    var symbol = _semanticModel.GetSymbolInfo(stmt.ControlVariable).Symbol;
                    if (!_semanticModel.LookupSymbols(node.FullSpan.Start, name: symbol.Name).Any())
                    {
                        var variableDeclaratorSyntax = SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(symbol.Name), null,
                                                                                        SyntaxFactory.EqualsValueClause(startValue));
                        declaration = SyntaxFactory.VariableDeclaration(
                            SyntaxFactory.IdentifierName("var"),
                            SyntaxFactory.SingletonSeparatedList(variableDeclaratorSyntax));
                    }
                    else
                    {
                        startValue = SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, id, startValue);
                    }
                }

                var step = (ExpressionSyntax)stmt.StepClause?.StepValue.Accept(_nodesVisitor);
                PrefixUnaryExpressionSyntax value = step.SkipParens() as PrefixUnaryExpressionSyntax;
                ExpressionSyntax            condition;

                if (value == null)
                {
                    condition = SyntaxFactory.BinaryExpression(SyntaxKind.LessThanOrEqualExpression, id, (ExpressionSyntax)stmt.ToValue.Accept(_nodesVisitor));
                }
                else
                {
                    condition = SyntaxFactory.BinaryExpression(SyntaxKind.GreaterThanOrEqualExpression, id, (ExpressionSyntax)stmt.ToValue.Accept(_nodesVisitor));
                }
                if (step == null)
                {
                    step = SyntaxFactory.PostfixUnaryExpression(SyntaxKind.PostIncrementExpression, id);
                }
                else
                {
                    step = SyntaxFactory.AssignmentExpression(SyntaxKind.AddAssignmentExpression, id, step);
                }
                var block = SyntaxFactory.Block(node.Statements.SelectMany(s => s.Accept(CommentConvertingVisitor)));

                return(SingleStatement(SyntaxFactory.ForStatement(
                                           declaration,
                                           declaration != null ? SyntaxFactory.SeparatedList <ExpressionSyntax>() : SyntaxFactory.SingletonSeparatedList(startValue),
                                           condition,
                                           SyntaxFactory.SingletonSeparatedList(step),
                                           block.UnpackNonNestedBlock())));
            }
コード例 #18
0
        private static List <BaseFieldDeclarationSyntax> DeclarationSplitter(
            Document document,
            VariableDeclarationSyntax declaration,
            Func <VariableDeclarationSyntax, BaseFieldDeclarationSyntax> declarationFactory,
            SyntaxTriviaList declarationTrailingTrivia)
        {
            SeparatedSyntaxList <VariableDeclaratorSyntax> variables = declaration.Variables;
            VariableDeclaratorSyntax   first    = variables.First();
            BaseFieldDeclarationSyntax previous = null;
            var newFieldDeclarations            = new List <BaseFieldDeclarationSyntax>(variables.Count);

            foreach (SyntaxNodeOrToken nodeOrToken in variables.GetWithSeparators())
            {
                if (previous == null)
                {
                    VariableDeclaratorSyntax variable = (VariableDeclaratorSyntax)nodeOrToken.AsNode();
                    variable = variable.WithIdentifier(variable.Identifier.WithoutLeadingWhitespace());
                    var variableDeclarator = SyntaxFactory.SingletonSeparatedList(variable);
                    previous = declarationFactory(declaration.WithVariables(variableDeclarator));

                    if (variable != first)
                    {
                        var triviaList = previous.GetLeadingTrivia().WithoutDirectiveTrivia();

                        // Remove all leading blank lines
                        var nonBlankLinetriviaIndex = TriviaHelper.IndexOfFirstNonBlankLineTrivia(triviaList);
                        if (nonBlankLinetriviaIndex > 0)
                        {
                            triviaList = triviaList.RemoveRange(0, nonBlankLinetriviaIndex);
                        }

                        // Add a blank line if the first line contains a comment.
                        var nonWhitespaceTriviaIndex = TriviaHelper.IndexOfFirstNonWhitespaceTrivia(triviaList, false);
                        if (nonWhitespaceTriviaIndex >= 0)
                        {
                            switch (triviaList[nonWhitespaceTriviaIndex].Kind())
                            {
                            case SyntaxKind.SingleLineCommentTrivia:
                            case SyntaxKind.MultiLineCommentTrivia:
                                triviaList = triviaList.Insert(0, SyntaxFactory.CarriageReturnLineFeed);
                                break;
                            }
                        }

                        previous = previous.WithLeadingTrivia(triviaList);
                    }
                }
                else
                {
                    SyntaxToken      commaToken     = nodeOrToken.AsToken();
                    SyntaxTriviaList trailingTrivia = commaToken.TrailingTrivia;
                    if (trailingTrivia.Any())
                    {
                        if (!trailingTrivia.Last().IsKind(SyntaxKind.EndOfLineTrivia))
                        {
                            trailingTrivia = trailingTrivia.WithoutTrailingWhitespace().Add(FormattingHelper.GetNewLineTrivia(document));
                        }
                    }
                    else
                    {
                        trailingTrivia = SyntaxTriviaList.Create(FormattingHelper.GetNewLineTrivia(document));
                    }

                    newFieldDeclarations.Add(previous.WithTrailingTrivia(trailingTrivia));
                    previous = null;
                }
            }

            newFieldDeclarations.Add(previous.WithTrailingTrivia(declarationTrailingTrivia));
            return(newFieldDeclarations);
        }
コード例 #19
0
 public static VariableDeclarationSyntax WithVariables(this VariableDeclarationSyntax syntax, params VariableDeclaratorSyntax[] variables)
 {
     return(syntax.WithVariables(SyntaxFactory.SeparatedList(variables)));
 }