Ejemplo n.º 1
0
        private static IEnumerable <LocalDeclarationStatementSyntax> SplitLocalDeclaration(LocalDeclarationStatementSyntax statement)
        {
            SeparatedSyntaxList <VariableDeclaratorSyntax> variables = statement.Declaration.Variables;

            LocalDeclarationStatementSyntax statement2 = statement.WithoutTrivia();

            for (int i = 0; i < variables.Count; i++)
            {
                LocalDeclarationStatementSyntax newStatement = LocalDeclarationStatement(
                    statement2.Modifiers,
                    VariableDeclaration(
                        statement2.Declaration.Type,
                        SingletonSeparatedList(variables[i])));

                if (i == 0)
                {
                    newStatement = newStatement.WithLeadingTrivia(statement.GetLeadingTrivia());
                }

                if (i == variables.Count - 1)
                {
                    newStatement = newStatement.WithTrailingTrivia(statement.GetTrailingTrivia());
                }

                yield return(newStatement.WithFormatterAnnotation());
            }
        }
        private static async Task <Document> RefactorAsync(
            Document document,
            ConditionalExpressionSyntax conditionalExpression,
            LocalDeclarationStatementSyntax localDeclaration,
            CancellationToken cancellationToken)
        {
            SyntaxNode oldRoot = await document.GetSyntaxRootAsync(cancellationToken);

            SemanticModel semanticModel = await document.GetSemanticModelAsync();

            var block = (BlockSyntax)localDeclaration.Parent;

            LocalDeclarationStatementSyntax newLocalDeclaration = GetNewLocalDeclaration(conditionalExpression, localDeclaration, semanticModel)
                                                                  .WithLeadingTrivia(localDeclaration.GetLeadingTrivia())
                                                                  .WithAdditionalAnnotations(Formatter.Annotation);

            var variableDeclarator = (VariableDeclaratorSyntax)conditionalExpression.Parent.Parent;

            IfStatementSyntax ifStatement = ConvertToIfElseWithAssignment(conditionalExpression, IdentifierName(variableDeclarator.Identifier.ToString()))
                                            .WithTrailingTrivia(localDeclaration.GetTrailingTrivia())
                                            .WithAdditionalAnnotations(Formatter.Annotation);

            SyntaxList <StatementSyntax> statements = block.Statements
                                                      .Replace(localDeclaration, newLocalDeclaration)
                                                      .Insert(block.Statements.IndexOf(localDeclaration) + 1, ifStatement);

            SyntaxNode newRoot = oldRoot.ReplaceNode(block, block.WithStatements(statements));

            return(document.WithSyntaxRoot(newRoot));
        }
Ejemplo n.º 3
0
        public SyntaxNode CreateLocalVariableDeclaration(LocalDeclarationStatementSyntax node, string typeToMock)
        {
            var variable = node.Declaration.Variables.FirstOrDefault();

            if (variable == null)
            {
                return(null);
            }

            var stubName = variable.Identifier.ValueText;

            var stubDefDeclaration    = CreateStubDefinitionDeclaration(stubName, typeToMock);
            var symbol                = node.Declaration.GetTypeSymbol(semanticModel) as INamedTypeSymbol;
            var initializerExpression = CreateStubInitializerDeclarations(node, stubName, symbol);
            var stubDeclaration       = CreateStubDeclaration(node, stubName, variable.Identifier.ValueText);

            var statements = new SyntaxList <StatementSyntax>();

            statements = statements.AddRange(new StatementSyntax[] { stubDefDeclaration }.Union(initializerExpression).Union(new StatementSyntax[] { SyntaxFactory.LocalDeclarationStatement(stubDeclaration) }));
            var wrapper = SyntaxFactory.Block(statements);

            wrapper = wrapper.WithOpenBraceToken(SyntaxFactory.MissingToken(SyntaxKind.OpenBraceToken)) // to remove scope {}
                      .WithCloseBraceToken(SyntaxFactory.MissingToken(SyntaxKind.CloseBraceToken));

            return(wrapper
                   .WithLeadingTrivia(node.GetLeadingTrivia())
                   .WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed));
        }
        private static async Task <Document> MergeLocalDeclarationWithReturnStatementAsync(
            Document document,
            LocalDeclarationStatementSyntax localDeclaration,
            ReturnStatementSyntax returnStatement,
            BlockSyntax block,
            CancellationToken cancellationToken)
        {
            SyntaxNode oldRoot = await document.GetSyntaxRootAsync(cancellationToken);

            ReturnStatementSyntax newReturnStatement = returnStatement
                                                       .WithExpression(localDeclaration.Declaration.Variables[0].Initializer.Value.WithoutTrivia())
                                                       .WithLeadingTrivia(localDeclaration.GetLeadingTrivia())
                                                       .WithTrailingTrivia(returnStatement.GetTrailingTrivia())
                                                       .WithAdditionalAnnotations(Formatter.Annotation);

            int index = block.Statements.IndexOf(localDeclaration);

            SyntaxList <StatementSyntax> newStatements = block.Statements
                                                         .RemoveAt(index)
                                                         .RemoveAt(index)
                                                         .Insert(index, newReturnStatement);

            BlockSyntax newBlock = block.WithStatements(newStatements);

            SyntaxNode newRoot = oldRoot.ReplaceNode(block, newBlock);

            return(document.WithSyntaxRoot(newRoot));
        }
Ejemplo n.º 5
0
        public static async Task <Document> RefactorAsync(
            Document document,
            LocalDeclarationStatementSyntax localDeclaration,
            CancellationToken cancellationToken)
        {
            var block = (BlockSyntax)localDeclaration.Parent;

            SyntaxList <StatementSyntax> statements = block.Statements;

            int index = statements.IndexOf(localDeclaration);

            var returnStatement = (ReturnStatementSyntax)statements[index + 1];

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

            ExpressionSyntax expression = GetExpressionToInline(localDeclaration, semanticModel, cancellationToken);

            ReturnStatementSyntax newReturnStatement = returnStatement
                                                       .WithExpression(expression)
                                                       .WithLeadingTrivia(localDeclaration.GetLeadingTrivia())
                                                       .WithTrailingTrivia(returnStatement.GetTrailingTrivia())
                                                       .WithFormatterAnnotation();

            SyntaxList <StatementSyntax> newStatements = statements
                                                         .Replace(returnStatement, newReturnStatement)
                                                         .RemoveAt(index);

            BlockSyntax newBlock = block.WithStatements(newStatements);

            return(await document.ReplaceNodeAsync(block, newBlock, cancellationToken).ConfigureAwait(false));
        }
        public static async Task <Document> RefactorAsync(
            Document document,
            LocalDeclarationStatementSyntax localDeclaration,
            CancellationToken cancellationToken)
        {
            var block = (BlockSyntax)localDeclaration.Parent;

            SyntaxList <StatementSyntax> statements = block.Statements;

            int index = statements.IndexOf(localDeclaration);

            var returnStatement = (ReturnStatementSyntax)statements[index + 1];

            ReturnStatementSyntax newReturnStatement = returnStatement
                                                       .WithExpression(localDeclaration.Declaration.Variables[0].Initializer.Value.WithoutTrivia())
                                                       .WithLeadingTrivia(localDeclaration.GetLeadingTrivia())
                                                       .WithTrailingTrivia(returnStatement.GetTrailingTrivia())
                                                       .WithFormatterAnnotation();

            SyntaxList <StatementSyntax> newStatements = statements
                                                         .RemoveAt(index)
                                                         .RemoveAt(index)
                                                         .Insert(index, newReturnStatement);

            BlockSyntax newBlock = block.WithStatements(newStatements);

            return(await document.ReplaceNodeAsync(block, newBlock, cancellationToken).ConfigureAwait(false));
        }
Ejemplo n.º 7
0
        public static async Task <Document> RefactorAsync(
            Document document,
            LocalDeclarationStatementSyntax localDeclaration,
            CancellationToken cancellationToken)
        {
            TypeSyntax type = localDeclaration.Declaration.Type;

            LocalDeclarationStatementSyntax newNode = localDeclaration;

            if (type.IsVar)
            {
                SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

                ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(type, cancellationToken);

                TypeSyntax newType = typeSymbol.ToMinimalTypeSyntax(semanticModel, localDeclaration.SpanStart);

                newNode = newNode.ReplaceNode(type, newType.WithTriviaFrom(type));
            }

            Debug.Assert(!newNode.Modifiers.Any(), newNode.Modifiers.ToString());

            if (newNode.Modifiers.Any())
            {
                newNode = newNode.InsertModifier(SyntaxKind.ConstKeyword, ModifierComparer.Instance);
            }
            else
            {
                newNode = newNode
                          .WithoutLeadingTrivia()
                          .WithModifiers(TokenList(ConstKeyword().WithLeadingTrivia(newNode.GetLeadingTrivia())));
            }

            return(await document.ReplaceNodeAsync(localDeclaration, newNode).ConfigureAwait(false));
        }
Ejemplo n.º 8
0
        private static async Task <Document> ApplyAddUsingFixAsync(CodeFixContext context, LocalDeclarationStatementSyntax statement, ITypeSymbol type, CancellationToken cancellationToken)
        {
            var editor = await DocumentEditor.CreateAsync(context.Document, cancellationToken).ConfigureAwait(false);

            var containingType      = statement.FirstAncestor <TypeDeclarationSyntax>();
            var usesUnderscoreNames = containingType.UsesUnderscoreNames(editor.SemanticModel, cancellationToken);
            var variableDeclarator  = statement.Declaration.Variables[0];
            var identifier          = variableDeclarator.Identifier;
            var field = editor.AddField(
                containingType,
                usesUnderscoreNames
                    ? "_" + identifier.ValueText
                    : identifier.ValueText,
                Accessibility.Private,
                DeclarationModifiers.ReadOnly,
                type,
                CancellationToken.None);

            var fieldAccess = usesUnderscoreNames
                ? SyntaxFactory.IdentifierName(field.Name())
                : SyntaxFactory.ParseExpression($"this.{field.Name()}");

            editor.ReplaceNode(
                statement,
                SyntaxFactory.ExpressionStatement(
                    (ExpressionSyntax)editor.Generator.AssignmentStatement(
                        fieldAccess,
                        variableDeclarator.Initializer.Value))
                .WithLeadingTrivia(statement.GetLeadingTrivia())
                .WithTrailingTrivia(statement.GetTrailingTrivia()));

            return(editor.GetChangedDocument());
        }
Ejemplo n.º 9
0
        private static async Task <Document> RefactorAsync(
            Document document,
            LocalDeclarationStatementSyntax localDeclaration,
            ConditionalExpressionSyntax conditionalExpression,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            SemanticModel semanticModel = await document.GetSemanticModelAsync().ConfigureAwait(false);

            TypeSyntax type = localDeclaration.Declaration.Type;

            LocalDeclarationStatementSyntax newLocalDeclaration = localDeclaration.RemoveNode(conditionalExpression.Parent, SyntaxRemoveOptions.KeepExteriorTrivia);

            if (type.IsVar)
            {
                ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(conditionalExpression);

                if (typeSymbol?.IsErrorType() == false)
                {
                    newLocalDeclaration = newLocalDeclaration.ReplaceNode(
                        newLocalDeclaration.Declaration.Type,
                        typeSymbol.ToMinimalTypeSyntax(semanticModel, type.SpanStart).WithSimplifierAnnotation());
                }
            }

            newLocalDeclaration = newLocalDeclaration
                                  .WithLeadingTrivia(localDeclaration.GetLeadingTrivia())
                                  .WithFormatterAnnotation();

            IfStatementSyntax ifStatement = CreateIfStatement(conditionalExpression)
                                            .WithTrailingTrivia(localDeclaration.GetTrailingTrivia())
                                            .WithFormatterAnnotation();

            SyntaxNode parent = localDeclaration.Parent;

            if (parent.IsKind(SyntaxKind.SwitchSection))
            {
                var section = (SwitchSectionSyntax)parent;

                SyntaxList <StatementSyntax> statements = section.Statements;

                statements = statements
                             .Replace(localDeclaration, newLocalDeclaration)
                             .Insert(statements.IndexOf(localDeclaration) + 1, ifStatement);

                return(await document.ReplaceNodeAsync(section, section.WithStatements(statements), cancellationToken).ConfigureAwait(false));
            }
            else
            {
                var block = (BlockSyntax)parent;

                SyntaxList <StatementSyntax> statements = block.Statements;

                statements = statements
                             .Replace(localDeclaration, newLocalDeclaration)
                             .Insert(statements.IndexOf(localDeclaration) + 1, ifStatement);

                return(await document.ReplaceNodeAsync(block, block.WithStatements(statements), cancellationToken).ConfigureAwait(false));
            }
        }
Ejemplo n.º 10
0
 public override SyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node)
 {
     if (RemoveTestTriviaAnnotation(node.GetLeadingTrivia()))
     {
         return(null);
     }
     return(base.VisitLocalDeclarationStatement(node));
 }
Ejemplo n.º 11
0
        private static Task <Document> RefactorAsync(
            Document document,
            LocalDeclarationStatementSyntax localDeclaration,
            CancellationToken cancellationToken)
        {
            VariableDeclaratorSyntax variableDeclarator = localDeclaration
                                                          .Declaration
                                                          .Variables
                                                          .Single();

            ExpressionSyntax expression = variableDeclarator
                                          .Initializer
                                          .Value
                                          .WalkDownParentheses();

            AsExpressionInfo asExpressionInfo = SyntaxInfo.AsExpressionInfo(expression);

            PrefixUnaryExpressionSyntax newCondition = LogicalNotExpression(
                ParenthesizedExpression(
                    IsPatternExpression(
                        asExpressionInfo.Expression,
                        DeclarationPattern(
                            asExpressionInfo.Type,
                            SingleVariableDesignation(variableDeclarator.Identifier)))));

            StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo(localDeclaration);

            int index = statementsInfo.IndexOf(localDeclaration);

            var ifStatement = (IfStatementSyntax)statementsInfo[index + 1];

            SyntaxTriviaList leadingTrivia = statementsInfo.Parent
                                             .DescendantTrivia(TextSpan.FromBounds(localDeclaration.SpanStart, ifStatement.SpanStart))
                                             .ToSyntaxTriviaList()
                                             .EmptyIfWhitespace();

            leadingTrivia = localDeclaration.GetLeadingTrivia().AddRange(leadingTrivia);

            StatementSyntax newStatement = ifStatement.Statement;

            if (ifStatement.SingleNonBlockStatementOrDefault() is ReturnStatementSyntax returnStatement &&
                returnStatement.Expression?.WalkDownParentheses() is IdentifierNameSyntax identifierName &&
                string.Equals(identifierName.Identifier.ValueText, variableDeclarator.Identifier.ValueText, System.StringComparison.Ordinal))
            {
                newStatement = newStatement.ReplaceNode(returnStatement.Expression, NullLiteralExpression().WithTriviaFrom(returnStatement.Expression));
            }

            IfStatementSyntax newIfStatement = ifStatement
                                               .WithCondition(newCondition.WithTriviaFrom(ifStatement.Condition))
                                               .WithStatement(newStatement)
                                               .WithLeadingTrivia(leadingTrivia)
                                               .WithFormatterAnnotation();

            SyntaxList <StatementSyntax> newStatements = statementsInfo.Statements.ReplaceRange(index, 2, newIfStatement);

            return(document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken));
        }
Ejemplo n.º 12
0
        public static Task <Document> RemoveRedundantAssignmentAfterLocalDeclarationAsync(
            Document document,
            VariableDeclaratorSyntax declarator,
            CancellationToken cancellationToken = default)
        {
            var declaration = (VariableDeclarationSyntax)declarator.Parent;

            var localDeclaration = (LocalDeclarationStatementSyntax)declaration.Parent;

            StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo(localDeclaration);

            SyntaxList <StatementSyntax> statements = statementsInfo.Statements;

            int index = statements.IndexOf(localDeclaration);

            StatementSyntax nextStatement = statements[index + 1];

            var expressionStatement = (ExpressionStatementSyntax)nextStatement;

            var assignment = (AssignmentExpressionSyntax)expressionStatement.Expression;

            ExpressionSyntax right = assignment.Right;

            EqualsValueClauseSyntax initializer = declarator.Initializer;

            ExpressionSyntax value = initializer?.Value;

            VariableDeclaratorSyntax newDeclarator = (value != null)
                ? declarator.ReplaceNode(value, right)
                : declarator.WithInitializer(EqualsValueClause(right));

            LocalDeclarationStatementSyntax newLocalDeclaration = localDeclaration.ReplaceNode(declarator, newDeclarator);

            SyntaxTriviaList trailingTrivia = localDeclaration.GetTrailingTrivia();

            if (!trailingTrivia.IsEmptyOrWhitespace())
            {
                newLocalDeclaration = newLocalDeclaration.WithTrailingTrivia(trailingTrivia.Concat(nextStatement.GetTrailingTrivia()));
            }
            else
            {
                newLocalDeclaration = newLocalDeclaration.WithTrailingTrivia(nextStatement.GetTrailingTrivia());
            }

            SyntaxTriviaList leadingTrivia = nextStatement.GetLeadingTrivia();

            if (!leadingTrivia.IsEmptyOrWhitespace())
            {
                newLocalDeclaration = newLocalDeclaration.WithLeadingTrivia(newLocalDeclaration.GetLeadingTrivia().Concat(leadingTrivia));
            }

            SyntaxList <StatementSyntax> newStatements = statements
                                                         .Replace(localDeclaration, newLocalDeclaration)
                                                         .RemoveAt(index + 1);

            return(document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken));
        }
Ejemplo n.º 13
0
        public static Task <Document> RefactorAsync(
            Document document,
            VariableDeclaratorSyntax declarator,
            CancellationToken cancellationToken)
        {
            var declaration = (VariableDeclarationSyntax)declarator.Parent;

            var localDeclaration = (LocalDeclarationStatementSyntax)declaration.Parent;

            StatementContainer container = StatementContainer.Create(localDeclaration);

            SyntaxList <StatementSyntax> statements = container.Statements;

            int index = statements.IndexOf(localDeclaration);

            StatementSyntax nextStatement = statements[index + 1];

            var expressionStatement = (ExpressionStatementSyntax)nextStatement;

            var assignment = (AssignmentExpressionSyntax)expressionStatement.Expression;

            ExpressionSyntax right = assignment.Right;

            EqualsValueClauseSyntax initializer = declarator.Initializer;

            ExpressionSyntax value = initializer?.Value;

            VariableDeclaratorSyntax newDeclarator = (value != null)
                ? declarator.ReplaceNode(value, right)
                : declarator.WithInitializer(EqualsValueClause(right));

            LocalDeclarationStatementSyntax newLocalDeclaration = localDeclaration.ReplaceNode(declarator, newDeclarator);

            SyntaxTriviaList trailingTrivia = localDeclaration.GetTrailingTrivia();

            if (trailingTrivia.Any(f => !f.IsWhitespaceOrEndOfLineTrivia()))
            {
                newLocalDeclaration = newLocalDeclaration.WithTrailingTrivia(trailingTrivia.Concat(nextStatement.GetTrailingTrivia()));
            }
            else
            {
                newLocalDeclaration = newLocalDeclaration.WithTrailingTrivia(nextStatement.GetTrailingTrivia());
            }

            SyntaxTriviaList leadingTrivia = nextStatement.GetLeadingTrivia();

            if (leadingTrivia.Any(f => !f.IsWhitespaceOrEndOfLineTrivia()))
            {
                newLocalDeclaration = newLocalDeclaration.WithLeadingTrivia(newLocalDeclaration.GetLeadingTrivia().Concat(leadingTrivia));
            }

            SyntaxList <StatementSyntax> newStatements = statements
                                                         .Replace(localDeclaration, newLocalDeclaration)
                                                         .RemoveAt(index + 1);

            return(document.ReplaceNodeAsync(container.Node, container.NodeWithStatements(newStatements), cancellationToken));
        }
Ejemplo n.º 14
0
        public override SyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node)
        {
            node = (LocalDeclarationStatementSyntax)base.VisitLocalDeclarationStatement(node);

            if (AttributeMatchUtil.HasTriviaAnnotationSimple(node.GetLeadingTrivia(), CountAttributeName))
            {
                node = node.WithDeclaration(node.Declaration.WithType(NarrowIntegerType(node.Declaration.Type)));
            }

            return node;
        }
        private static async Task <Document> ApplyAddUsingFixAsync(CodeFixContext context, LocalDeclarationStatementSyntax statement, ITypeSymbol type)
        {
            var editor = await DocumentEditor.CreateAsync(context.Document).ConfigureAwait(false);

            var usesUnderscoreNames = editor.SemanticModel.SyntaxTree.GetRoot().UsesUnderscoreNames(editor.SemanticModel, CancellationToken.None);
            var identifier          = statement.Declaration.Variables[0].Identifier;
            var name = usesUnderscoreNames
                ? "_" + identifier.ValueText
                : identifier.ValueText;
            var containingType = statement.FirstAncestor <TypeDeclarationSyntax>();
            var declaredSymbol = editor.SemanticModel.GetDeclaredSymbol(containingType);

            while (declaredSymbol.MemberNames.Contains(name))
            {
                name += "_";
            }

            var newField = (FieldDeclarationSyntax)editor.Generator.FieldDeclaration(
                name,
                accessibility: Accessibility.Private,
                modifiers: DeclarationModifiers.ReadOnly,
                type: SyntaxFactory.ParseTypeName(type.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)));
            var members = containingType.Members;

            if (members.TryGetFirst(x => x is FieldDeclarationSyntax, out MemberDeclarationSyntax field))
            {
                editor.InsertBefore(field, new[] { newField });
            }
            else if (members.TryGetFirst(out field))
            {
                editor.InsertBefore(field, new[] { newField });
            }
            else
            {
                editor.AddMember(containingType, newField);
            }

            var fieldAccess = usesUnderscoreNames
                ? SyntaxFactory.IdentifierName(name)
                : SyntaxFactory.ParseExpression($"this.{name}");

            editor.ReplaceNode(
                statement,
                SyntaxFactory.ExpressionStatement(
                    (ExpressionSyntax)editor.Generator.AssignmentStatement(
                        fieldAccess,
                        statement.Declaration.Variables[0].Initializer.Value))
                .WithLeadingTrivia(statement.GetLeadingTrivia())
                .WithTrailingTrivia(statement.GetTrailingTrivia()));
            return(editor.GetChangedDocument());
        }
        public static async Task <Document> RefactorAsync(
            Document document,
            LocalDeclarationStatementSyntax localDeclaration,
            CancellationToken cancellationToken)
        {
            StatementContainer container;

            if (StatementContainer.TryCreate(localDeclaration, out container))
            {
                SyntaxList <StatementSyntax> statements = container.Statements;

                int index = statements.IndexOf(localDeclaration);

                ExpressionSyntax value = localDeclaration
                                         .Declaration
                                         .Variables
                                         .First()
                                         .Initializer
                                         .Value;

                StatementSyntax nextStatement = statements[index + 1];

                StatementSyntax newStatement = GetStatementWithReplacedValue(nextStatement, value);

                SyntaxTriviaList leadingTrivia = localDeclaration.GetLeadingTrivia();

                IEnumerable <SyntaxTrivia> trivia = container
                                                    .Node
                                                    .DescendantTrivia(TextSpan.FromBounds(localDeclaration.SpanStart, nextStatement.Span.Start));

                if (!trivia.All(f => f.IsWhitespaceOrEndOfLineTrivia()))
                {
                    newStatement = newStatement.WithLeadingTrivia(leadingTrivia.Concat(trivia));
                }
                else
                {
                    newStatement = newStatement.WithLeadingTrivia(leadingTrivia);
                }

                SyntaxList <StatementSyntax> newStatements = statements
                                                             .Replace(nextStatement, newStatement)
                                                             .RemoveAt(index);

                return(await document.ReplaceNodeAsync(container.Node, container.NodeWithStatements(newStatements), cancellationToken).ConfigureAwait(false));
            }

            Debug.Assert(false, "");

            return(document);
        }
Ejemplo n.º 17
0
        private static async Task <Document> RefactorAsync(
            Document document,
            ConditionalExpressionSyntax conditionalExpression,
            LocalDeclarationStatementSyntax localDeclaration,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

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

            LocalDeclarationStatementSyntax newLocalDeclaration = GetNewLocalDeclaration(conditionalExpression, localDeclaration, semanticModel)
                                                                  .WithLeadingTrivia(localDeclaration.GetLeadingTrivia())
                                                                  .WithFormatterAnnotation();

            var variableDeclarator = (VariableDeclaratorSyntax)conditionalExpression.Parent.Parent;

            IfStatementSyntax ifStatement = ReplaceWithIfElseWithAssignment(conditionalExpression, IdentifierName(variableDeclarator.Identifier.ValueText))
                                            .WithTrailingTrivia(localDeclaration.GetTrailingTrivia())
                                            .WithFormatterAnnotation();

            SyntaxNode parent = localDeclaration.Parent;

            if (parent.IsKind(SyntaxKind.SwitchSection))
            {
                var section = (SwitchSectionSyntax)parent;

                SyntaxList <StatementSyntax> statements = section.Statements;

                statements = statements
                             .Replace(localDeclaration, newLocalDeclaration)
                             .Insert(statements.IndexOf(localDeclaration) + 1, ifStatement);

                root = root.ReplaceNode(section, section.WithStatements(statements));
            }
            else
            {
                var block = (BlockSyntax)parent;

                SyntaxList <StatementSyntax> statements = block.Statements;

                statements = statements
                             .Replace(localDeclaration, newLocalDeclaration)
                             .Insert(statements.IndexOf(localDeclaration) + 1, ifStatement);

                root = root.ReplaceNode(block, block.WithStatements(statements));
            }

            return(document.WithSyntaxRoot(root));
        }
Ejemplo n.º 18
0
        private async Task <Document> AddSecureFlags(Document document, Diagnostic diagnostic, CancellationToken cancellationToken, string[] propertyNames)
        {
            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            var variableDeclarator = root.FindToken(diagnostic.Location.SourceSpan.Start).Parent as VariableDeclaratorSyntax;

            if (variableDeclarator == null)
            {
                return(document);                            //Abort!
            }
            VariableDeclarationSyntax       variableDeclaration = variableDeclarator.Parent as VariableDeclarationSyntax;
            LocalDeclarationStatementSyntax parentDeclaration   = variableDeclaration.Parent as LocalDeclarationStatementSyntax;

            if (variableDeclaration == null || parentDeclaration == null)
            {
                return(document);                                                          //Abort!
            }
            var identifierCookie = variableDeclaration.Variables[0];

            //Building the nodes model

            var nodes = new List <SyntaxNode>();

            foreach (var property in propertyNames)
            {
                var newAssignment = SF.ExpressionStatement(
                    SF.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
                                            SF.MemberAccessExpression(
                                                SyntaxKind.SimpleMemberAccessExpression,
                                                SF.IdentifierName(identifierCookie.Identifier),
                                                SF.IdentifierName(property))
                                            ,
                                            SF.LiteralExpression(SyntaxKind.TrueLiteralExpression)
                                            ))
                                    .WithLeadingTrivia(CodeFixUtil.KeepLastLine(parentDeclaration.GetLeadingTrivia()));

                /*
                 * .WithLeadingTrivia(parentDeclaration.GetLeadingTrivia()
                 *  .Insert(0, SF.ElasticEndOfLine(Environment.NewLine))
                 * );*/
                nodes.Add(newAssignment);
            }

            //Inserting the nodes
            var newRoot = root.InsertNodesAfter(parentDeclaration, nodes);

            return(document.WithSyntaxRoot(newRoot));
        }
Ejemplo n.º 19
0
        public override SyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node)
        {
            node = (LocalDeclarationStatementSyntax)base.VisitLocalDeclarationStatement(node);

            if (AttributeMatchUtil.HasTriviaAnnotationSimple(node.GetLeadingTrivia(), WidenAttributeName))
            {
                if (node.Declaration.Type.IsKind(SyntaxKind.PredefinedType))
                {
                    node = node.WithDeclaration(
                        node.Declaration.WithType(
                            WidenType(node.Declaration.Type)).WithTriviaFrom(node.Declaration.Type));
                }
            }

            return(node);
        }
Ejemplo n.º 20
0
        private static Task <Document> RefactorAsync(
            Document document,
            LocalDeclarationStatementSyntax localDeclaration,
            CancellationToken cancellationToken)
        {
            VariableDeclaratorSyntax variableDeclarator = localDeclaration
                                                          .Declaration
                                                          .Variables
                                                          .Single();

            ExpressionSyntax expression = variableDeclarator
                                          .Initializer
                                          .Value
                                          .WalkDownParentheses();

            AsExpressionInfo asExpressionInfo = SyntaxInfo.AsExpressionInfo(expression);

            PrefixUnaryExpressionSyntax newCondition = LogicalNotExpression(
                ParenthesizedExpression(
                    IsPatternExpression(
                        asExpressionInfo.Expression,
                        DeclarationPattern(
                            asExpressionInfo.Type,
                            SingleVariableDesignation(variableDeclarator.Identifier)))));

            StatementListInfo statements = SyntaxInfo.StatementListInfo(localDeclaration);

            int index = statements.IndexOf(localDeclaration);

            var ifStatement = (IfStatementSyntax)statements[index + 1];

            SyntaxTriviaList leadingTrivia = localDeclaration
                                             .DescendantTrivia(TextSpan.FromBounds(localDeclaration.SpanStart, ifStatement.SpanStart))
                                             .ToSyntaxTriviaList()
                                             .EmptyIfWhitespace();

            leadingTrivia = localDeclaration.GetLeadingTrivia().AddRange(leadingTrivia);

            IfStatementSyntax newIfStatement = ifStatement
                                               .WithCondition(newCondition.WithTriviaFrom(ifStatement.Condition))
                                               .WithLeadingTrivia(leadingTrivia);

            StatementListInfo newStatements = statements.RemoveAt(index).ReplaceAt(index, newIfStatement);

            return(document.ReplaceStatementsAsync(statements, newStatements, cancellationToken));
        }
        private static async Task <Document> RefactorAsync(
            Document document,
            LocalDeclarationStatementSyntax localDeclaration,
            CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo(localDeclaration);

            int index = statementsInfo.Statements.IndexOf(localDeclaration);

            StatementSyntax nextStatement = statementsInfo.Statements[index + 1];

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

            ExpressionSyntax value = GetExpressionToInline(localDeclaration, semanticModel, cancellationToken);

            StatementSyntax newStatement = GetStatementWithInlinedExpression(nextStatement, value);

            SyntaxTriviaList leadingTrivia = localDeclaration.GetLeadingTrivia();

            IEnumerable <SyntaxTrivia> trivia = statementsInfo
                                                .Parent
                                                .DescendantTrivia(TextSpan.FromBounds(localDeclaration.SpanStart, nextStatement.SpanStart));

            if (!trivia.All(f => f.IsWhitespaceOrEndOfLineTrivia()))
            {
                newStatement = newStatement.WithLeadingTrivia(leadingTrivia.Concat(trivia));
            }
            else
            {
                newStatement = newStatement.WithLeadingTrivia(leadingTrivia);
            }

            SyntaxList <StatementSyntax> newStatements = statementsInfo.Statements
                                                         .Replace(nextStatement, newStatement)
                                                         .RemoveAt(index);

            return(await document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken).ConfigureAwait(false));
        }
        private async Task <Document> MakeConstantAsync(Document document, LocalDeclarationStatementSyntax localDeclaration, CancellationToken cancellationToken)
        {
            var declaration = localDeclaration.Declaration;
            var typeName    = declaration.Type;

            if (typeName.IsVar)
            {
                var semanticModel = await document.GetSemanticModelAsync(cancellationToken);

                var aliasInfo = semanticModel.GetAliasInfo(typeName);
                if (aliasInfo == null)
                {
                    var type = semanticModel.GetTypeInfo(typeName).ConvertedType;
                    if (type.Name != "var")
                    {
                        var newtypeName = SyntaxFactory.ParseTypeName(type.ToDisplayString());
                        declaration = declaration.WithType(newtypeName);
                    }
                }
            }

            var @const = SyntaxFactory.Token(SyntaxKind.ConstKeyword)
                         .WithLeadingTrivia(localDeclaration.GetLeadingTrivia());

            var modifiers = localDeclaration.Modifiers.Insert(0, @const);

            var newLocalDeclaration = localDeclaration
                                      .WithModifiers(modifiers)
                                      .WithDeclaration(declaration.WithoutLeadingTrivia())
                                      .WithTrailingTrivia(localDeclaration.GetTrailingTrivia())
                                      .WithAdditionalAnnotations(Formatter.Annotation);

            var root = await document.GetSyntaxRootAsync(cancellationToken);

            var newRoot = root.ReplaceNode(localDeclaration, newLocalDeclaration);

            return(document.WithSyntaxRoot(newRoot));
        }
        public static async Task <Document> RefactorAsync(
            Document document,
            LocalDeclarationStatementSyntax localDeclaration,
            CancellationToken cancellationToken)
        {
            StatementContainer container = StatementContainer.Create(localDeclaration);

            int index = container.Statements.IndexOf(localDeclaration);

            StatementSyntax nextStatement = container.Statements[index + 1];

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

            ExpressionSyntax value = GetExpressionToInline(localDeclaration, semanticModel, cancellationToken);

            StatementSyntax newStatement = GetStatementWithInlinedExpression(nextStatement, value);

            SyntaxTriviaList leadingTrivia = localDeclaration.GetLeadingTrivia();

            IEnumerable <SyntaxTrivia> trivia = container
                                                .Node
                                                .DescendantTrivia(TextSpan.FromBounds(localDeclaration.SpanStart, nextStatement.Span.Start));

            if (!trivia.All(f => f.IsWhitespaceOrEndOfLineTrivia()))
            {
                newStatement = newStatement.WithLeadingTrivia(leadingTrivia.Concat(trivia));
            }
            else
            {
                newStatement = newStatement.WithLeadingTrivia(leadingTrivia);
            }

            SyntaxList <StatementSyntax> newStatements = container.Statements
                                                         .Replace(nextStatement, newStatement)
                                                         .RemoveAt(index);

            return(await document.ReplaceNodeAsync(container.Node, container.NodeWithStatements(newStatements), cancellationToken).ConfigureAwait(false));
        }
        private static Task <Document> UsePatternMatchingAsync(
            Document document,
            SwitchStatementSyntax switchStatement,
            CancellationToken cancellationToken)
        {
            SyntaxList <SwitchSectionSyntax> newSections = switchStatement.Sections.Select(section =>
            {
                if (!(section.Labels.Single() is CaseSwitchLabelSyntax label))
                {
                    return(section);
                }

                SyntaxList <StatementSyntax> statements = section.Statements;

                StatementSyntax statement = statements[0];

                if (statement is BlockSyntax block)
                {
                    statement = block.Statements.FirstOrDefault();
                }

                SingleLocalDeclarationStatementInfo localInfo = SyntaxInfo.SingleLocalDeclarationStatementInfo((LocalDeclarationStatementSyntax)statement);

                var castExpression = (CastExpressionSyntax)localInfo.Value;

                CasePatternSwitchLabelSyntax newLabel = CasePatternSwitchLabel(
                    DeclarationPattern(
                        castExpression.Type,
                        SingleVariableDesignation(localInfo.Identifier)),
                    label.ColonToken);

                SwitchSectionSyntax newSection = section.RemoveStatement(localInfo.Statement);

                newSection = newSection.WithLabels(newSection.Labels.ReplaceAt(0, newLabel));

                return(newSection.WithFormatterAnnotation());
            })
                                                           .ToSyntaxList();

            ExpressionSyntax expression = switchStatement.Expression;

            ExpressionSyntax newExpression = expression;

            LocalDeclarationStatementSyntax localDeclaration = null;

            if (expression.IsKind(SyntaxKind.InvocationExpression))
            {
                SimpleMemberInvocationExpressionInfo invocationInfo = SyntaxInfo.SimpleMemberInvocationExpressionInfo(expression);

                newExpression = invocationInfo.Expression;
            }
            else
            {
                localDeclaration = (LocalDeclarationStatementSyntax)switchStatement.PreviousStatement();

                SingleLocalDeclarationStatementInfo localInfo = SyntaxInfo.SingleLocalDeclarationStatementInfo(localDeclaration);

                SimpleMemberInvocationExpressionInfo invocationInfo = SyntaxInfo.SimpleMemberInvocationExpressionInfo(localInfo.Value);

                newExpression = invocationInfo.Expression;
            }

            SwitchStatementSyntax newSwitchStatement = switchStatement
                                                       .WithExpression(newExpression.WithTriviaFrom(expression))
                                                       .WithSections(newSections);

            if (localDeclaration != null)
            {
                StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo(switchStatement);

                newSwitchStatement = newSwitchStatement.WithLeadingTrivia(localDeclaration.GetLeadingTrivia());

                SyntaxList <StatementSyntax> newStatements = statementsInfo.Statements
                                                             .Replace(switchStatement, newSwitchStatement)
                                                             .RemoveAt(statementsInfo.IndexOf(localDeclaration));

                return(document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken));
            }
            else
            {
                return(document.ReplaceNodeAsync(switchStatement, newSwitchStatement, cancellationToken));
            }
        }
        private static async Task <Document> MarkLocalVariableAsConstAsync(
            Document document,
            LocalDeclarationStatementSyntax localDeclaration,
            CancellationToken cancellationToken)
        {
            TypeSyntax type = localDeclaration.Declaration.Type;

            LocalDeclarationStatementSyntax newNode = localDeclaration;

            if (type.IsVar)
            {
                SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

                ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(type, cancellationToken);

                TypeSyntax newType = typeSymbol.ToMinimalTypeSyntax(semanticModel, localDeclaration.SpanStart, SymbolDisplayFormats.FullName_WithoutNullableReferenceTypeModifier);

                newNode = newNode.ReplaceNode(type, newType.WithTriviaFrom(type));
            }

            Debug.Assert(!newNode.Modifiers.Any(), newNode.Modifiers.ToString());

            if (newNode.Modifiers.Any())
            {
                newNode = newNode.InsertModifier(SyntaxKind.ConstKeyword);
            }
            else
            {
                newNode = newNode
                          .WithoutLeadingTrivia()
                          .WithModifiers(TokenList(Token(SyntaxKind.ConstKeyword).WithLeadingTrivia(newNode.GetLeadingTrivia())));
            }

            return(await document.ReplaceNodeAsync(localDeclaration, newNode, cancellationToken).ConfigureAwait(false));
        }