private static Task <Document> RefactorAsync(
            Document document,
            StatementsInfo statementsInfo,
            LocalDeclarationStatementSyntax[] localDeclarations,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            LocalDeclarationStatementSyntax localDeclaration = localDeclarations[0];

            SyntaxList <StatementSyntax> statements = statementsInfo.Statements;

            int index = statements.IndexOf(localDeclaration);

            VariableDeclaratorSyntax[] variables = localDeclarations
                                                   .Skip(1)
                                                   .Select(f => f.Declaration)
                                                   .SelectMany(f => f.Variables)
                                                   .ToArray();

            LocalDeclarationStatementSyntax newLocalDeclaration = localDeclaration
                                                                  .AddDeclarationVariables(variables)
                                                                  .WithTrailingTrivia(localDeclarations[localDeclarations.Length - 1].GetTrailingTrivia())
                                                                  .WithFormatterAnnotation();

            SyntaxList <StatementSyntax> newStatements = statements.Replace(
                localDeclaration,
                newLocalDeclaration);

            for (int i = 1; i < localDeclarations.Length; i++)
            {
                newStatements = newStatements.RemoveAt(index + 1);
            }

            return(document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken));
        }
Example #2
0
        public static Task <Document> RefactorAsync(
            Document document,
            AssignmentExpressionSyntax assignmentExpression,
            CancellationToken cancellationToken)
        {
            var statement = (StatementSyntax)assignmentExpression.Parent;

            StatementsInfo statementsInfo = SyntaxInfo.StatementsInfo(statement);

            SyntaxList <StatementSyntax> statements = statementsInfo.Statements;

            int index = statements.IndexOf(statement);

            statements = statements.RemoveAt(index);

            var returnStatement = (ReturnStatementSyntax)statement.NextStatementOrDefault();

            IEnumerable <SyntaxTrivia> trivia = statementsInfo
                                                .Node
                                                .DescendantTrivia(TextSpan.FromBounds(statement.SpanStart, returnStatement.SpanStart))
                                                .Where(f => !f.IsWhitespaceOrEndOfLineTrivia());

            trivia = statement
                     .GetLeadingTrivia()
                     .Concat(trivia);

            returnStatement = returnStatement
                              .WithExpression(assignmentExpression.Right.WithTriviaFrom(returnStatement.Expression))
                              .WithLeadingTrivia(trivia);

            statements = statements.ReplaceAt(index, returnStatement);

            return(document.ReplaceStatementsAsync(statementsInfo, statements, cancellationToken));
        }
Example #3
0
        public static Task <Document> RefactorAsync(
            Document document,
            LocalFunctionStatementSyntax localFunction,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (document == null)
            {
                throw new ArgumentNullException(nameof(document));
            }

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

            StatementsInfo statementsInfos = SyntaxInfo.StatementsInfo(localFunction);

            SyntaxList <StatementSyntax> statements = statementsInfos.Statements;
            int index = statements.IndexOf(localFunction);

            if (index == 0 &&
                statementsInfos.Block.OpenBraceToken.GetFullSpanEndLine() == localFunction.GetFullSpanStartLine())
            {
                localFunction = localFunction.WithLeadingTrivia(localFunction.GetLeadingTrivia().Insert(0, NewLine()));
            }

            SyntaxList <StatementSyntax> newStatements = statements.Insert(index + 1, localFunction.WithNavigationAnnotation());

            return(document.ReplaceStatementsAsync(statementsInfos, newStatements, cancellationToken));
        }
        public static bool TryCreate(StatementsInfo statementsInfo, TextSpan span, out StatementsSelection selectedStatements)
        {
            selectedStatements = null;

            if (span.IsEmpty)
            {
                return(false);
            }

            SyntaxList <StatementSyntax> statements = statementsInfo.Statements;

            if (!statements.Any())
            {
                return(false);
            }

            (int startIndex, int endIndex) = GetIndexes(statements, span);

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

            selectedStatements = new StatementsSelection(statementsInfo, span, startIndex, endIndex);
            return(true);
        }
        public static Task <Document> RefactorAsync(
            Document document,
            StatementsInfo statementsInfo,
            ImmutableArray <IfStatementSyntax> ifStatements,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            IfStatementSyntax newIfStatement = IfStatement(
                CreateCondition(ifStatements),
                Block(CreateStatements(ifStatements)));

            SyntaxList <StatementSyntax> statements = statementsInfo.Statements;

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

            SyntaxList <StatementSyntax> newStatements = statements.Replace(
                ifStatements[0],
                newIfStatement
                .WithLeadingTrivia(ifStatements[0].GetLeadingTrivia())
                .WithTrailingTrivia(ifStatements[ifStatements.Length - 1].GetTrailingTrivia()));

            for (int i = 1; i < ifStatements.Length; i++)
            {
                newStatements = newStatements.RemoveAt(index + 1);
            }

            return(document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken));
        }
Example #6
0
        public static Task <Document> RefactorAsync(
            Document document,
            UsingStatementSyntax usingStatement,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            StatementsInfo statementsInfo = SyntaxInfo.StatementsInfo(usingStatement);

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

            StatementsInfo newStatementsInfo = statementsInfo.RemoveAt(index);

            var statements = new List <StatementSyntax>()
            {
                SyntaxFactory.LocalDeclarationStatement(usingStatement.Declaration)
            };

            statements.AddRange(GetStatements(usingStatement));

            if (statements.Count > 0)
            {
                statements[0] = statements[0]
                                .WithLeadingTrivia(usingStatement.GetLeadingTrivia());

                statements[statements.Count - 1] = statements[statements.Count - 1]
                                                   .WithTrailingTrivia(usingStatement.GetTrailingTrivia());
            }

            newStatementsInfo = newStatementsInfo.WithStatements(newStatementsInfo.Statements.InsertRange(index, statements));

            return(document.ReplaceNodeAsync(statementsInfo.Node, newStatementsInfo.Node.WithFormatterAnnotation(), cancellationToken));
        }
        private static Task <Document> RefactorAsync(
            Document document,
            ExpressionSyntax expression,
            SyntaxList <StatementSyntax> statements,
            StatementsInfo statementsInfo,
            int statementIndex,
            int lastStatementIndex,
            CancellationToken cancellationToken)
        {
            IEnumerable <StatementSyntax> blockStatements = statements
                                                            .Skip(statementIndex + 1)
                                                            .Take(lastStatementIndex - statementIndex);

            IfStatementSyntax ifStatement = CreateNullCheck(expression, List(blockStatements));

            if (lastStatementIndex < statements.Count - 1)
            {
                ifStatement = ifStatement.AppendToTrailingTrivia(NewLine());
            }

            IEnumerable <StatementSyntax> newStatements = statements.Take(statementIndex + 1)
                                                          .Concat(new IfStatementSyntax[] { ifStatement })
                                                          .Concat(statements.Skip(lastStatementIndex + 1));

            return(document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken));
        }
        private static Task <Document> RefactorAsync(
            Document document,
            SingleLocalDeclarationStatementInfo localInfo,
            SemanticModel semanticModel,
            CancellationToken cancellationToken)
        {
            StatementsInfo statementsInfo = SyntaxInfo.StatementsInfo(localInfo.Statement);

            var localSymbol = (ILocalSymbol)semanticModel.GetDeclaredSymbol(localInfo.Declarator, cancellationToken);

            IdentifierNameSyntax identifierName = FindLastReference(localSymbol, statementsInfo.Node, semanticModel, cancellationToken);

            TextSpan span;

            if (identifierName == null)
            {
                span = localInfo.Statement.Span;
            }
            else
            {
                int position = identifierName.SpanStart;
                span = TextSpan.FromBounds(localInfo.Statement.SpanStart, statementsInfo.First(f => f.Span.Contains(position)).Span.End);
            }

            StatementsSelection selectedStatements = StatementsSelection.Create(statementsInfo, span);

            var refactoring = new WrapStatements.WrapInUsingStatementRefactoring();

            return(refactoring.RefactorAsync(document, selectedStatements, cancellationToken));
        }
        private static bool NullCheckExists(ExpressionSyntax expression, StatementSyntax statement)
        {
            StatementsInfo statementsInfo = SyntaxInfo.StatementsInfo(statement);

            if (!statementsInfo.Success)
            {
                return(false);
            }

            SyntaxList <StatementSyntax> statements = statementsInfo.Statements;

            int index = statements.IndexOf(statement);

            if (index >= statements.Count - 1)
            {
                return(false);
            }

            StatementSyntax nextStatement = statements[index + 1];

            if (!(nextStatement is IfStatementSyntax ifStatement))
            {
                return(false);
            }

            NullCheckExpressionInfo nullCheck = SyntaxInfo.NullCheckExpressionInfo(ifStatement.Condition, NullCheckKind.NotEqualsToNull);

            if (!nullCheck.Success)
            {
                return(false);
            }

            return(SyntaxComparer.AreEquivalent(expression, nullCheck.Expression));
        }
        public static Task <Document> RefactorAsync(
            Document document,
            ObjectCreationExpressionSyntax objectCreation,
            StatementsSelection selectedStatements,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            StatementsInfo statementsInfo = selectedStatements.Info;

            ExpressionStatementSyntax[] expressionStatements = selectedStatements
                                                               .Skip(1)
                                                               .Cast <ExpressionStatementSyntax>()
                                                               .ToArray();

            StatementSyntax firstStatement = selectedStatements.First();

            SyntaxList <StatementSyntax> newStatements = statementsInfo.Statements.Replace(
                firstStatement,
                firstStatement.ReplaceNode(
                    objectCreation,
                    objectCreation.WithInitializer(CreateInitializer(objectCreation, expressionStatements))));

            int count = expressionStatements.Length;
            int index = selectedStatements.StartIndex + 1;

            while (count > 0)
            {
                newStatements = newStatements.RemoveAt(index);
                count--;
            }

            return(document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken));
        }
        public override async Task <Document> RefactorAsync(Document document, CancellationToken cancellationToken = default(CancellationToken))
        {
            StatementsInfo statementsInfo = SyntaxInfo.StatementsInfo(IfStatement);

            SyntaxList <StatementSyntax> statements = statementsInfo.Statements;

            int index = statements.IndexOf(IfStatement);

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

            ExpressionSyntax expression = IfRefactoringHelper.GetBooleanExpression(
                IfStatement.Condition,
                Expression1,
                Expression2,
                semanticModel,
                cancellationToken);

            StatementSyntax newStatement = CreateStatement(expression)
                                           .WithLeadingTrivia(IfStatement.GetLeadingTrivia())
                                           .WithTrailingTrivia(statements[index + 1].GetTrailingTrivia())
                                           .WithFormatterAnnotation();

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

            return(await document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken).ConfigureAwait(false));
        }
Example #12
0
        public virtual Task <Document> InlineAsync(
            ExpressionStatementSyntax expressionStatement,
            SyntaxList <StatementSyntax> statements,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            int count = statements.Count;

            StatementSyntax[] newStatements = RewriteStatements(statements);

            newStatements[0]         = newStatements[0].WithLeadingTrivia(expressionStatement.GetLeadingTrivia());
            newStatements[count - 1] = newStatements[count - 1].WithTrailingTrivia(expressionStatement.GetTrailingTrivia());

            StatementsInfo statementsInfo = SyntaxInfo.StatementsInfo(expressionStatement);

            if (statementsInfo.Success)
            {
                StatementsInfo newInfo = statementsInfo.WithStatements(statementsInfo.Statements.ReplaceRange(expressionStatement, newStatements));

                return(Document.ReplaceNodeAsync(statementsInfo.Node, newInfo.Node, cancellationToken));
            }
            else
            {
                return(Document.ReplaceNodeAsync(expressionStatement, Block(newStatements), cancellationToken));
            }
        }
        private static Task <Document> DuplicateStatementAsync(
            Document document,
            StatementSyntax statement,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            StatementsInfo statementsInfo = SyntaxInfo.StatementsInfo(statement);

            if (statementsInfo.Success)
            {
                int index = statementsInfo.Statements.IndexOf(statement);

                if (index == 0 &&
                    statementsInfo.IsInBlock &&
                    statementsInfo.Block.OpenBraceToken.GetFullSpanEndLine() == statement.GetFullSpanStartLine())
                {
                    statement = statement.PrependToLeadingTrivia(CSharpFactory.NewLine());
                }

                SyntaxList <StatementSyntax> newStatements = statementsInfo.Statements.Insert(index + 1, statement.WithNavigationAnnotation());

                StatementsInfo newInfo = statementsInfo.WithStatements(newStatements);

                return(document.ReplaceNodeAsync(statementsInfo.Node, newInfo.Node, cancellationToken));
            }
            else
            {
                SyntaxList <StatementSyntax> statements = SyntaxFactory.List(new StatementSyntax[] { statement, statement.WithNavigationAnnotation() });

                BlockSyntax block = SyntaxFactory.Block(statements);

                return(document.ReplaceNodeAsync(statement, block, cancellationToken));
            }
        }
Example #14
0
        public static async Task ComputeRefactoringAsync(
            RefactoringContext context,
            LocalDeclarationStatementSyntax localDeclaration)
        {
            StatementsInfo statementsInfo = SyntaxInfo.StatementsInfo(localDeclaration);

            if (!statementsInfo.Success)
            {
                return;
            }

            SingleLocalDeclarationStatementInfo localInfo = SyntaxInfo.SingleLocalDeclarationStatementInfo(localDeclaration);

            if (!localInfo.Success)
            {
                return;
            }

            if (!context.Span.IsEmptyAndContainedInSpan(localInfo.EqualsToken))
            {
                return;
            }

            ExpressionSyntax value = localInfo.Initializer?.Value;

            if (value == null)
            {
                return;
            }

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

            TypeSyntax type = localInfo.Type;

            if (type.IsVar)
            {
                ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(value, context.CancellationToken);

                if (typeSymbol?.SupportsExplicitDeclaration() != true)
                {
                    return;
                }

                type = typeSymbol.ToMinimalTypeSyntax(semanticModel, type.SpanStart);
            }
            else
            {
                ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(type, context.CancellationToken);

                if (typeSymbol?.IsErrorType() != false)
                {
                    return;
                }
            }

            context.RegisterRefactoring(
                "Split declaration and initialization",
                cancellationToken => RefactorAsync(context.Document, localInfo, type, statementsInfo, cancellationToken));
        }
Example #15
0
 internal static Task <Document> ReplaceStatementsAsync(
     this Document document,
     StatementsInfo statementsInfo,
     SyntaxList <StatementSyntax> newStatements,
     CancellationToken cancellationToken)
 {
     return(document.ReplaceNodeAsync(statementsInfo.Node, statementsInfo.WithStatements(newStatements).Node, cancellationToken));
 }
Example #16
0
 internal static Task <Document> ReplaceStatementsAsync(
     this Document document,
     StatementsInfo statementsInfo,
     IEnumerable <StatementSyntax> newStatements,
     CancellationToken cancellationToken)
 {
     return(ReplaceStatementsAsync(document, statementsInfo, SyntaxFactory.List(newStatements), cancellationToken));
 }
            private SyntaxNode Rewrite(StatementsInfo statementsInfo)
            {
                _statementsInfo = statementsInfo;

                var ifStatement = (IfStatementSyntax)_statementsInfo.Statements.LastButOne();

                return(Rewrite(_statementsInfo, ifStatement));
            }
Example #18
0
        private static Task <Document> RefactorAsync(
            Document document,
            StatementsInfo statementsInfo,
            StatementSyntax statement,
            InitializerExpressionSyntax initializer,
            ExpressionSyntax initializedExpression,
            CancellationToken cancellationToken)
        {
            ExpressionStatementSyntax[] expressions = CreateExpressionStatements(initializer, initializedExpression).ToArray();

            expressions[expressions.Length - 1] = expressions[expressions.Length - 1]
                                                  .WithTrailingTrivia(statement.GetTrailingTrivia());

            var objectCreationExpression = (ObjectCreationExpressionSyntax)initializer.Parent;

            ObjectCreationExpressionSyntax newObjectCreationExpression = objectCreationExpression.WithInitializer(null);

            if (newObjectCreationExpression.ArgumentList == null)
            {
                TypeSyntax type = newObjectCreationExpression.Type;

                newObjectCreationExpression = newObjectCreationExpression
                                              .WithArgumentList(ArgumentList().WithTrailingTrivia(type.GetTrailingTrivia()))
                                              .WithType(type.WithoutTrailingTrivia());
            }

            SyntaxList <StatementSyntax> statements = statementsInfo.Statements;

            int index = statements.IndexOf(statement);

            StatementSyntax newStatement = statement.ReplaceNode(objectCreationExpression, newObjectCreationExpression);

            SyntaxKind statementKind = statement.Kind();

            if (statementKind == SyntaxKind.ExpressionStatement)
            {
                var expressionStatement = (ExpressionStatementSyntax)newStatement;

                newStatement = expressionStatement
                               .WithExpression(expressionStatement.Expression.WithoutTrailingTrivia());
            }
            else if (statementKind == SyntaxKind.LocalDeclarationStatement)
            {
                var localDeclaration = (LocalDeclarationStatementSyntax)newStatement;

                newStatement = localDeclaration
                               .WithDeclaration(localDeclaration.Declaration.WithoutTrailingTrivia());
            }

            SyntaxList <StatementSyntax> newStatements = statements.Replace(statement, newStatement);

            SyntaxNode newNode = statementsInfo
                                 .WithStatements(newStatements.InsertRange(index + 1, expressions))
                                 .Node
                                 .WithFormatterAnnotation();

            return(document.ReplaceNodeAsync(statementsInfo.Node, newNode, cancellationToken));
        }
        internal static void ComputeRefactoring(RefactoringContext context, BinaryExpressionSelection binaryExpressionSelection)
        {
            BinaryExpressionSyntax binaryExpression = binaryExpressionSelection.BinaryExpression;

            SyntaxKind kind = binaryExpression.Kind();

            if (kind == SyntaxKind.LogicalAndExpression ||
                kind == SyntaxKind.LogicalOrExpression)
            {
                BinaryExpressionSyntax condition = GetCondition(binaryExpression);

                if (condition != null)
                {
                    SyntaxNode parent = condition.Parent;

                    switch (parent?.Kind())
                    {
                    case SyntaxKind.IfStatement:
                    {
                        if (kind == SyntaxKind.LogicalAndExpression)
                        {
                            var refactoring = new ExtractConditionFromIfToNestedIfRefactoring();
                            context.RegisterRefactoring(
                                refactoring.Title,
                                cancellationToken => refactoring.RefactorAsync(context.Document, (IfStatementSyntax)parent, condition, binaryExpressionSelection, cancellationToken));
                        }
                        else if (kind == SyntaxKind.LogicalOrExpression)
                        {
                            StatementsInfo statementsInfo = SyntaxInfo.StatementsInfo((StatementSyntax)parent);
                            if (statementsInfo.Success)
                            {
                                var refactoring = new ExtractConditionFromIfToIfRefactoring();
                                context.RegisterRefactoring(
                                    refactoring.Title,
                                    cancellationToken => refactoring.RefactorAsync(context.Document, statementsInfo, condition, binaryExpressionSelection, cancellationToken));
                            }
                        }

                        break;
                    }

                    case SyntaxKind.WhileStatement:
                    {
                        if (kind == SyntaxKind.LogicalAndExpression)
                        {
                            var refactoring = new ExtractConditionFromWhileToNestedIfRefactoring();
                            context.RegisterRefactoring(
                                refactoring.Title,
                                cancellationToken => refactoring.RefactorAsync(context.Document, (WhileStatementSyntax)parent, condition, binaryExpressionSelection, cancellationToken));
                        }

                        break;
                    }
                    }
                }
            }
        }
Example #20
0
        public static Task <Document> RefactorAsync(
            Document document,
            VariableDeclaratorSyntax declarator,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            var declaration = (VariableDeclarationSyntax)declarator.Parent;

            var localDeclaration = (LocalDeclarationStatementSyntax)declaration.Parent;

            StatementsInfo statementsInfo = SyntaxInfo.StatementsInfo(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));
        }
        public bool Analyze(
            MemberInvocationExpressionInfo invocationInfo,
            StatementSyntax statement,
            string name,
            SemanticModel semanticModel,
            CancellationToken cancellationToken)
        {
            if (statement.SpanOrTrailingTriviaContainsDirectives())
            {
                return(false);
            }

            StatementsInfo statementsInfo = SyntaxInfo.StatementsInfo(statement);

            if (!statementsInfo.Success)
            {
                return(false);
            }

            SyntaxList <StatementSyntax> statements = statementsInfo.Statements;

            if (statements.Count == 1)
            {
                return(false);
            }

            if (!semanticModel.TryGetMethodInfo(invocationInfo.InvocationExpression, out MethodInfo methodInfo, cancellationToken))
            {
                return(false);
            }

            ITypeSymbol typeSymbol = methodInfo.ReturnType;

            int i = statements.IndexOf(statement);

            if (i != 0 &&
                IsFixableStatement(statements[i - 1], name, typeSymbol, semanticModel, cancellationToken))
            {
                return(false);
            }

            int j = i;

            while (j < statements.Count - 1)
            {
                if (!IsFixableStatement(statements[j + 1], name, typeSymbol, semanticModel, cancellationToken))
                {
                    break;
                }

                j++;
            }

            return(j > i);
        }
        public static StatementsSelection Create(BlockSyntax block, TextSpan span)
        {
            if (block == null)
            {
                throw new ArgumentNullException(nameof(block));
            }

            var info = new StatementsInfo(block);

            return(Create(info, span));
        }
        public static async Task ComputeRefactoringAsync(RefactoringContext context, VariableDeclarationSyntax variableDeclaration)
        {
            if (!(variableDeclaration.Parent is LocalDeclarationStatementSyntax localDeclaration))
            {
                return;
            }

            if (!StatementsInfo.CanCreate(localDeclaration))
            {
                return;
            }

            SingleLocalDeclarationStatementInfo localInfo = SyntaxInfo.SingleLocalDeclarationStatementInfo(localDeclaration);

            if (!localInfo.Success)
            {
                return;
            }

            if (!context.Span.IsEmptyAndContainedInSpan(localInfo.Identifier))
            {
                return;
            }

            ExpressionSyntax value = localInfo.Initializer?.Value;

            if (value == null)
            {
                return;
            }

            if (value.Kind() == SyntaxKind.DefaultExpression)
            {
                return;
            }

            if (value is LiteralExpressionSyntax)
            {
                return;
            }

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

            var typeSymbol = semanticModel.GetTypeSymbol(localInfo.Type, context.CancellationToken) as INamedTypeSymbol;

            if (typeSymbol?.Implements(SpecialType.System_IDisposable, allInterfaces: true) != true)
            {
                return;
            }

            context.RegisterRefactoring(
                $"Using '{localInfo.IdentifierText}'",
                cancellationToken => RefactorAsync(context.Document, localInfo, semanticModel, cancellationToken));
        }
        public static StatementsSelection Create(SwitchSectionSyntax switchSection, TextSpan span)
        {
            if (switchSection == null)
            {
                throw new ArgumentNullException(nameof(switchSection));
            }

            var info = new StatementsInfo(switchSection);

            return(Create(info, span));
        }
        public static bool TryCreate(BlockSyntax block, TextSpan span, out StatementsSelection selectedStatements)
        {
            StatementsInfo info = SyntaxInfo.StatementsInfo(block);

            if (!info.Success)
            {
                selectedStatements = null;
                return(false);
            }

            return(TryCreate(info, span, out selectedStatements));
        }
        public static bool TryCreate(SwitchSectionSyntax switchSection, TextSpan span, out StatementsSelection selectedStatements)
        {
            StatementsInfo info = SyntaxInfo.StatementsInfo(switchSection);

            if (!info.Success)
            {
                selectedStatements = null;
                return(false);
            }

            return(TryCreate(info, span, out selectedStatements));
        }
Example #27
0
        public Task <Document> RefactorAsync(
            Document document,
            StatementsInfo statementsInfo,
            BinaryExpressionSyntax condition,
            ExpressionSyntax expression,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            var ifStatement = (IfStatementSyntax)condition.Parent;

            IfStatementSyntax newIfStatement = RemoveExpressionFromCondition(ifStatement, condition, expression)
                                               .WithFormatterAnnotation();

            SyntaxNode newNode = AddNextIf(statementsInfo, ifStatement, newIfStatement, expression);

            return(document.ReplaceNodeAsync(statementsInfo.Node, newNode, cancellationToken));
        }
        private static async Task <Document> RefactorAsync(
            Document document,
            ExpressionSyntax expression,
            StatementSyntax statement,
            CancellationToken cancellationToken)
        {
            if (statement.IsEmbedded())
            {
                return(await document.ReplaceNodeAsync(statement, Block(statement, CreateNullCheck(expression)), cancellationToken).ConfigureAwait(false));
            }
            else
            {
                StatementsInfo statementsInfo           = SyntaxInfo.StatementsInfo(statement);
                SyntaxList <StatementSyntax> statements = statementsInfo.Statements;

                int statementIndex = statements.IndexOf(statement);

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

                ISymbol symbol = (statement is LocalDeclarationStatementSyntax localDeclaration)
                    ? semanticModel.GetDeclaredSymbol(localDeclaration.Declaration.Variables.First(), cancellationToken)
                    : semanticModel.GetSymbol(expression, cancellationToken);

                int lastStatementIndex = IncludeAllReferencesOfSymbol(symbol, expression.Kind(), statements, statementIndex + 1, semanticModel, cancellationToken);

                if (lastStatementIndex != -1)
                {
                    if (lastStatementIndex < statements.Count - 1)
                    {
                        lastStatementIndex = IncludeAllReferencesOfVariablesDeclared(statements, statementIndex + 1, lastStatementIndex, semanticModel, cancellationToken);
                    }

                    return(await RefactorAsync(
                               document,
                               expression,
                               statements,
                               statementsInfo,
                               statementIndex,
                               lastStatementIndex,
                               cancellationToken).ConfigureAwait(false));
                }
            }

            return(await document.InsertNodeAfterAsync(statement, CreateNullCheck(expression), cancellationToken).ConfigureAwait(false));
        }
        public override async Task <Document> RefactorAsync(Document document, CancellationToken cancellationToken = default(CancellationToken))
        {
            SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            int position = IfStatement.SpanStart;

            ITypeSymbol targetType = GetTargetType(position, semanticModel, cancellationToken);

            BinaryExpressionSyntax coalesceExpression = RefactoringHelper.CreateCoalesceExpression(
                targetType,
                Left.WithoutTrivia(),
                Right.WithoutTrivia(),
                position,
                semanticModel);

            StatementSyntax statement = CreateStatement(coalesceExpression);

            if (IfStatement.IsSimpleIf())
            {
                StatementsInfo statementsInfo = SyntaxInfo.StatementsInfo(IfStatement);

                SyntaxList <StatementSyntax> statements = statementsInfo.Statements;

                int index = statements.IndexOf(IfStatement);

                StatementSyntax newNode = statement
                                          .WithLeadingTrivia(IfStatement.GetLeadingTrivia())
                                          .WithTrailingTrivia(statements[index + 1].GetTrailingTrivia())
                                          .WithFormatterAnnotation();

                SyntaxList <StatementSyntax> newStatements = statements
                                                             .RemoveAt(index)
                                                             .ReplaceAt(index, newNode);

                return(await document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken).ConfigureAwait(false));
            }
            else
            {
                StatementSyntax newNode = statement
                                          .WithTriviaFrom(IfStatement)
                                          .WithFormatterAnnotation();

                return(await document.ReplaceNodeAsync(IfStatement, newNode, cancellationToken).ConfigureAwait(false));
            }
        }
Example #30
0
        public override Task <Document> RefactorAsync(
            Document document,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            StatementsInfo statementsInfo = SyntaxInfo.StatementsInfo(IfStatement);

            SyntaxList <StatementSyntax> statements = statementsInfo.Statements;

            int index = statements.IndexOf(IfStatement);

            TStatement newStatement = CreateNewStatement();

            SyntaxList <StatementSyntax> newStatements = statements
                                                         .RemoveAt(index)
                                                         .ReplaceAt(index - 1, newStatement);

            return(document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken));
        }