private static void ApplyObserveEventMethodFix(
            DocumentEditor editor,
            AssignmentExpressionSyntax assignment,
            MethodDeclarationSyntax methodDeclaration,
            CancellationToken cancellationToken)
        {
            var usesArg = false;

            if (methodDeclaration.ParameterList.Parameters.Any())
            {
                using (var pooled = IdentifierNameWalker.Borrow((SyntaxNode)methodDeclaration.Body ?? methodDeclaration.ExpressionBody))
                {
                    foreach (var name in pooled.IdentifierNames)
                    {
                        if (name.Identifier.ValueText == methodDeclaration.ParameterList.Parameters[0].Identifier.ValueText)
                        {
                            if (methodDeclaration.ParameterList.Parameters.Count == 1)
                            {
                                usesArg = true;
                                continue;
                            }

                            return;
                        }

                        if (methodDeclaration.ParameterList.Parameters.Count == 2 &&
                            name.Identifier.ValueText == methodDeclaration.ParameterList.Parameters[1]
                            .Identifier.ValueText)
                        {
                            usesArg = true;
                        }
                    }
                }
            }

            var eventSymbol      = (IEventSymbol)editor.SemanticModel.GetSymbolSafe(assignment.Left, cancellationToken);
            var observeSubscribe = GetObservableFromEventString(eventSymbol)
                                   .Replace("HANDLERTYPE", eventSymbol.Type.ToMinimalDisplayString(editor.SemanticModel, assignment.SpanStart))
                                   .Replace("ARGTYPE", ArgType(eventSymbol))
                                   .Replace("LEFT", assignment.Left.ToString())
                                   .Replace("LAMBDA", Lambda(methodDeclaration, usesArg));

            editor.AddUsing(SystemReactiveLinq)
            .ReplaceNode(
                assignment,
                SyntaxFactory.ParseExpression(observeSubscribe)
                .WithTriviaFrom(assignment)
                .WithSimplifiedNames()
                .WithAdditionalAnnotations(Formatter.Annotation, Simplifier.Annotation));
            if (methodDeclaration.ParameterList.Parameters.Count == 2)
            {
                editor.RemoveNode(methodDeclaration.ParameterList.Parameters[0]);
            }

            if (!usesArg &&
                methodDeclaration.ParameterList.Parameters.Any())
            {
                editor.RemoveNode(methodDeclaration.ParameterList.Parameters.Last());
            }
        }
        public async Task <Solution> InlineAndRemoveMethodAsync(InvocationExpressionSyntax invocation, ExpressionSyntax expression)
        {
            if (invocation.SyntaxTree == MethodDeclaration.SyntaxTree)
            {
                DocumentEditor editor = await DocumentEditor.CreateAsync(Document, CancellationToken).ConfigureAwait(false);

                ExpressionSyntax newExpression = RewriteExpression(invocation, expression);

                editor.ReplaceNode(invocation, newExpression);

                editor.RemoveNode(MethodDeclaration);

                return(editor.GetChangedDocument().Solution());
            }
            else
            {
                Document newDocument = await InlineMethodAsync(invocation, expression).ConfigureAwait(false);

                DocumentId documentId = Document.Solution().GetDocumentId(MethodDeclaration.SyntaxTree);

                newDocument = await newDocument.Solution().GetDocument(documentId).RemoveMemberAsync(MethodDeclaration, CancellationToken).ConfigureAwait(false);

                return(newDocument.Solution());
            }
        }
Esempio n. 3
0
        private void RemoveDeclaration(string variableName, BlockSyntax block, DocumentEditor editor)
        {
            var node         = block.GetLocalDeclaredVariables().SingleVariable(variableName);
            var nodeToDelete = node.AncestorsAndSelf().OfType <LocalDeclarationStatementSyntax>().First();

            editor.RemoveNode(nodeToDelete);
        }
        private void ReplaceImportStatements()
        {
            HashSet <string> alreadyAddedImportsStatements             = new HashSet <string>();
            IEnumerable <ImportsStatementSyntax> importsStatementNodes = tree.GetRoot().DescendantNodes().OfType <ImportsStatementSyntax>();

            foreach (ImportsStatementSyntax oldImportsStatementNode in importsStatementNodes) // iterate over all qualified names in the file
            {
                // could be problems if this import statement isn't simple, however even if an alias is used in the import it's still simple
                SimpleImportsClauseSyntax oldSimpleImportsNode = oldImportsStatementNode.DescendantNodes().OfType <SimpleImportsClauseSyntax>().First();
                var oldNamespace = oldSimpleImportsNode.WithoutTrivia().Name.GetText().ToString();
                List <namespace_map> namespaces = NSMappingSQLConnector.GetInstance().GetNamespaceMapsFromOldNamespace(TransformProject.sdkId, oldNamespace);
                if (namespaces != null)
                {
                    foreach (namespace_map nsMap in namespaces)
                    {
                        var newNamespace = nsMap.new_namespace;
                        if (!alreadyAddedImportsStatements.Contains(newNamespace))
                        {
                            alreadyAddedImportsStatements.Add(newNamespace);
                            NameSyntax newIdentifierNode    = IdentifierName(newNamespace);
                            var        newSimpleImportsNode = oldSimpleImportsNode.WithName(newIdentifierNode);
                            SeparatedSyntaxList <ImportsClauseSyntax> simpleImportsList = new SeparatedSyntaxList <ImportsClauseSyntax>().Add(newSimpleImportsNode);
                            ImportsStatementSyntax newImportsStatementNode = ImportsStatement(simpleImportsList).WithTriviaFrom(oldImportsStatementNode);
                            newImportsStatementNode = newImportsStatementNode.WithImportsKeyword(oldImportsStatementNode.ImportsKeyword);
                            documentEditor.InsertAfter(oldImportsStatementNode, newImportsStatementNode);
                        }
                    }
                    documentEditor.RemoveNode(oldImportsStatementNode);
                }
            }
        }
 private static void ReplaceWithUsing(DocumentEditor editor, InvocationExpressionSyntax invocation, CancellationToken cancellationToken)
 {
     if (DisposeCall.TryGetDisposedRootMember(invocation, editor.SemanticModel, cancellationToken, out var root) &&
         editor.SemanticModel.TryGetSymbol(root, cancellationToken, out ILocalSymbol local) &&
         local.TrySingleDeclaration(cancellationToken, out VariableDeclarationSyntax declaration) &&
         invocation.TryFirstAncestor(out ExpressionStatementSyntax expressionStatement) &&
         declaration.Parent is LocalDeclarationStatementSyntax localDeclarationStatement)
     {
         if (expressionStatement.Parent is BlockSyntax finallyBlock &&
             finallyBlock.Parent is FinallyClauseSyntax finallyClause &&
             finallyClause.Parent is TryStatementSyntax tryStatement &&
             !tryStatement.Catches.Any())
         {
             if (declaration.Variables.TrySingle(out var declarator) &&
                 declarator.Initializer?.Value.IsKind(SyntaxKind.NullLiteralExpression) == true &&
                 tryStatement.Block.Statements.TryFirst(out var statement) &&
                 statement is ExpressionStatementSyntax assignExpressionStatement &&
                 assignExpressionStatement.Expression is AssignmentExpressionSyntax assignment)
             {
                 editor.ReplaceNode(
                     tryStatement,
                     SyntaxFactory.UsingStatement(
                         SyntaxFactory.VariableDeclaration(
                             SyntaxFactory.ParseTypeName("var"),
                             SyntaxFactory.SingletonSeparatedList(
                                 declarator.WithInitializer(SyntaxFactory.EqualsValueClause(assignment.Right)))),
                         null,
                         tryStatement.Block.WithStatements(tryStatement.Block.Statements.RemoveAt(0))));
                 editor.RemoveNode(localDeclarationStatement);
             }
        private void ReplaceUsingStatements()
        {
            HashSet <string> alreadyAddedUsingStatements           = new HashSet <string>();
            IEnumerable <UsingDirectiveSyntax> usingDirectiveNodes = tree.GetRoot().DescendantNodes().OfType <UsingDirectiveSyntax>();

            foreach (UsingDirectiveSyntax oldUsingDirectiveNode in usingDirectiveNodes) // iterate over all qualified names in the file
            {
                var oldNamespace = oldUsingDirectiveNode.Name.GetText().ToString();
                List <namespace_map> namespaces = NSMappingSQLConnector.GetInstance().GetNamespaceMapsFromOldNamespace(TransformProject.sdkId, oldNamespace);
                if (namespaces != null)
                {
                    foreach (namespace_map nsMap in namespaces)
                    {
                        var newNamespace = nsMap.new_namespace;
                        if (!alreadyAddedUsingStatements.Contains(newNamespace))
                        {
                            alreadyAddedUsingStatements.Add(newNamespace);
                            NameSyntax newIdentifierNode     = IdentifierName(newNamespace);
                            var        newUsingDirectiveNode = oldUsingDirectiveNode.WithName(newIdentifierNode);
                            documentEditor.InsertAfter(oldUsingDirectiveNode, newUsingDirectiveNode);
                        }
                    }
                    documentEditor.RemoveNode(oldUsingDirectiveNode);
                }
            }
        }
        private static void AddUsingToEndOfBlock(DocumentEditor editor, BlockSyntax block, ExpressionSyntax expression)
        {
            foreach (var statementSyntax in block.Statements)
            {
                editor.RemoveNode(statementSyntax);
            }

            editor.ReplaceNode(
                block,
                SyntaxFactory.Block(
                    SyntaxFactory.UsingStatement(
                        declaration: null,
                        expression: GetExpression(),
                        statement: block.WithAdditionalAnnotations(Formatter.Annotation))));

            ExpressionSyntax GetExpression()
            {
                if (expression is DeclarationExpressionSyntax declaration &&
                    declaration.Designation is SingleVariableDesignationSyntax singleVariable)
                {
                    return(SyntaxFactory.IdentifierName(singleVariable.Identifier));
                }

                return(expression);
            }
        }
Esempio n. 8
0
        public virtual async Task <Solution> InlineAndRemoveAsync(
            SyntaxNode node,
            ExpressionSyntax expression,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (node.SyntaxTree == Declaration.SyntaxTree)
            {
                DocumentEditor editor = await DocumentEditor.CreateAsync(Document, cancellationToken).ConfigureAwait(false);

                ExpressionSyntax newExpression = RewriteExpression(node, expression);

                editor.ReplaceNode(node, newExpression);

                editor.RemoveNode(Declaration);

                return(editor.GetChangedDocument().Solution());
            }
            else
            {
                Document newDocument = await InlineAsync(node, expression, cancellationToken).ConfigureAwait(false);

                DocumentId documentId = Document.Solution().GetDocumentId(Declaration.SyntaxTree);

                newDocument = await newDocument.Solution().GetDocument(documentId).RemoveMemberAsync(Declaration, cancellationToken).ConfigureAwait(false);

                return(newDocument.Solution());
            }
        }
        /// <summary>
        /// Move <paramref name="toMove"></paramref> before <paramref name="statement">.</paramref>.
        /// </summary>
        /// <param name="editor">The <see cref="DocumentEditor"/>.</param>
        /// <param name="toMove">The <see cref="StatementSyntax"/> to move.</param>
        /// <param name="statement">The <see cref="StatementSyntax"/>.</param>
        /// <returns>The <see cref="DocumentEditor"/> that was passed in.</returns>
        public static DocumentEditor MoveAfter(this DocumentEditor editor, StatementSyntax toMove, StatementSyntax statement)
        {
            if (editor is null)
            {
                throw new ArgumentNullException(nameof(editor));
            }

            if (toMove is null)
            {
                throw new ArgumentNullException(nameof(toMove));
            }

            if (statement is null)
            {
                throw new ArgumentNullException(nameof(statement));
            }

            editor.RemoveNode(toMove);
            editor.InsertAfter(statement, ToMove());
            return(editor);

            StatementSyntax ToMove()
            {
                if (statement.GetLastToken().IsKind(SyntaxKind.CloseBraceToken))
                {
                    return(toMove.WithLeadingLineFeed());
                }

                return(toMove);
            }
        }
Esempio n. 10
0
 private static void RemoveMethod(DocumentEditor editor, IMethodSymbol method, MethodDeclarationSyntax declaration, CancellationToken cancellationToken)
 {
     if (method.DeclaredAccessibility == Accessibility.Private &&
         method.IsInvokedOnce(editor.SemanticModel, cancellationToken))
     {
         editor.RemoveNode(declaration);
     }
 }
        private static async Task <Document> RemoveField(Document document, SyntaxNode node, CancellationToken cancellationToken)
        {
            DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);

            node = editor.Generator.GetDeclaration(node);
            editor.RemoveNode(node);
            return(editor.GetChangedDocument());
        }
        private static async Task <Document> RemoveFinalizerAsync(Document document, SyntaxNode node, CancellationToken cancellationToken)
        {
            DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);

            // Get the declaration so that we step up to the methodblocksyntax and not the methodstatementsyntax for VB.
            node = editor.Generator.GetDeclaration(node);
            editor.RemoveNode(node);
            return(editor.GetChangedDocument());
        }
        private static void AddToIf(DocumentEditor editor, IfStatementSyntax ifSetAndRaise, ExpressionStatementSyntax invocation)
        {
            if (ifSetAndRaise.Statement is BlockSyntax body)
            {
                editor.RemoveNode(invocation);
                if (body.Statements.Count == 0)
                {
                    editor.ReplaceNode(
                        body,
                        body.AddStatements(invocation.WithLeadingElasticLineFeed()));
                }
                else
                {
                    editor.InsertAfter(body.Statements.Last(), invocation.WithLeadingElasticLineFeed());
                }
            }
            else
            {
                if (ifSetAndRaise.Statement == null)
                {
                    editor.RemoveNode(invocation);
                    editor.ReplaceNode(
                        ifSetAndRaise,
                        (x, _) => ((IfStatementSyntax)x)
                        .WithStatement(SyntaxFactory.Block(ifSetAndRaise.Statement, invocation))
                        .WithSimplifiedNames()
                        .WithTrailingElasticLineFeed()
                        .WithAdditionalAnnotations(Formatter.Annotation));
                }
                else
                {
                    editor.RemoveNode(invocation);
                    editor.ReplaceNode(
                        ifSetAndRaise.Statement,
                        (x, _) => SyntaxFactory.Block(ifSetAndRaise.Statement, invocation)
                        .WithSimplifiedNames()
                        .WithTrailingElasticLineFeed()
                        .WithAdditionalAnnotations(Formatter.Annotation));
                }
            }

            editor.FormatNode(ifSetAndRaise);
        }
Esempio n. 14
0
        private static async Task <Solution> InlineAndRemoveMethodAsync(
            Document document,
            ExpressionStatementSyntax expressionStatement,
            MethodDeclarationSyntax methodDeclaration,
            StatementSyntax[] statements,
            ParameterInfo[] parameterInfos,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (expressionStatement.SyntaxTree.Equals(methodDeclaration.SyntaxTree))
            {
                DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);

                Solution solution = document.Project.Solution;

                StatementSyntax[] newStatements = await ReplaceParameterExpressionWithArgumentExpressionAsync(
                    parameterInfos,
                    statements,
                    solution,
                    cancellationToken).ConfigureAwait(false);

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

                if (expressionStatement.Parent.IsKind(SyntaxKind.Block))
                {
                    var block = (BlockSyntax)expressionStatement.Parent;

                    BlockSyntax newBlock = block.WithStatements(block.Statements.ReplaceRange(expressionStatement, newStatements));

                    editor.ReplaceNode(block, newBlock);
                }
                else
                {
                    editor.ReplaceNode(expressionStatement, Block(newStatements));
                }

                editor.RemoveNode(methodDeclaration);

                document = editor.GetChangedDocument();

                return(document.Project.Solution);
            }
            else
            {
                Solution solution = document.Project.Solution;

                document = await InlineMethodAsync(document, expressionStatement, statements, parameterInfos, cancellationToken).ConfigureAwait(false);

                DocumentId documentId = solution.GetDocumentId(methodDeclaration.SyntaxTree);

                solution = document.Project.Solution;

                return(await RemoveMethodAsync(solution.GetDocument(documentId), methodDeclaration, cancellationToken).ConfigureAwait(false));
            }
        }
 private static void AddToExisting(DocumentEditor editor, ExpressionStatementSyntax statement, IFieldSymbol field)
 {
     if (TryGetPreviousStatement(out var previous) &&
         TryGetCreateCompositeDisposable(out var compositeDisposableCreation))
     {
         editor.RemoveNode(statement);
         editor.AddItemToCollectionInitializer(
             compositeDisposableCreation,
             statement.Expression,
             statement.GetTrailingTrivia());
     }
Esempio n. 16
0
 public override void RemoveNode(DocumentEditor editor, SyntaxNode node)
 {
     if (node.Kind() == SyntaxKind.SimpleAssignmentExpression)
     {
         editor.ReplaceNode(node, ((AssignmentExpressionSyntax)node).Right);
     }
     else
     {
         editor.RemoveNode(node);
     }
 }
        private void RemoveLocal(ExpressionSyntax expression, DocumentEditor editor)
        {
            var variableDeclaration = expression.Ancestors().OfType <VariableDeclarationSyntax>().FirstOrDefault();

            if (variableDeclaration == null)
            {
                return;
            }

            if (variableDeclaration.Variables.Count > 1)
            {
                // Remove the appropriate variabledeclarator
                var declaratorToRemove = expression.Ancestors().OfType <VariableDeclaratorSyntax>().First();
                editor.RemoveNode(declaratorToRemove);
            }
            else
            {
                // Remove the entire variabledeclaration
                editor.RemoveNode(variableDeclaration.Ancestors().OfType <LocalDeclarationStatementSyntax>().First());
            }
        }
Esempio n. 18
0
        private static void ChangeEventToPublicAndNonStatic(
            ICodeGenerationService codeGenerationService,
            DocumentEditor editor,
            IEventSymbol eventSymbol,
            SyntaxNode eventDeclaration,
            DeclarationModifiers modifiers
            )
        {
            var declaration = editor.Generator.GetDeclaration(eventDeclaration);
            var isEventHasExplicitAddOrRemoveMethod =
                (eventSymbol.AddMethod != null && !eventSymbol.AddMethod.IsImplicitlyDeclared) ||
                (
                    eventSymbol.RemoveMethod != null &&
                    !eventSymbol.RemoveMethod.IsImplicitlyDeclared
                );

            // There are three situations here:
            // 1. Single Event.
            // 2. Several events exist in one declaration.
            // 3. Event has add or remove method(user declared).
            // For situation 1, declaration is EventFieldDeclaration, eventDeclaration is variableDeclaration.
            // For situation 2, declaration and eventDeclaration are both EventDeclaration, which are same.
            // For situation 3, it is same as situation 2, but has add or remove method.
            if (declaration.Equals(eventDeclaration) && !isEventHasExplicitAddOrRemoveMethod)
            {
                // Several events are declared in same line
                var publicAndNonStaticSymbol = CodeGenerationSymbolFactory.CreateEventSymbol(
                    eventSymbol,
                    accessibility: Accessibility.Public,
                    modifiers: modifiers
                    );
                var options = new CodeGenerationOptions(generateMethodBodies: false);
                var publicAndNonStaticSyntax = codeGenerationService.CreateEventDeclaration(
                    publicAndNonStaticSymbol,
                    destination: CodeGenerationDestination.ClassType,
                    options: options
                    );
                // Insert a new declaration and remove the original declaration
                editor.InsertAfter(declaration, publicAndNonStaticSyntax);
                editor.RemoveNode(eventDeclaration);
            }
            else
            {
                // Handle both single event and event has add or remove method
                editor.SetAccessibility(declaration, Accessibility.Public);
                editor.SetModifiers(declaration, modifiers);
            }
        }
Esempio n. 19
0
        private async Task <Document> MakeClassStatic(Document document, ClassDeclarationSyntax classDeclaration, CancellationToken ct)
        {
            DocumentEditor editor = await DocumentEditor.CreateAsync(document, ct).ConfigureAwait(false);

            DeclarationModifiers modifiers = editor.Generator.GetModifiers(classDeclaration);

            editor.SetModifiers(classDeclaration, modifiers - DeclarationModifiers.Sealed + DeclarationModifiers.Static);

            SyntaxList <MemberDeclarationSyntax> members = classDeclaration.Members;
            MemberDeclarationSyntax defaultConstructor   = members.FirstOrDefault(m => m.IsDefaultConstructor());

            if (defaultConstructor != null)
            {
                editor.RemoveNode(defaultConstructor);
            }

            return(editor.GetChangedDocument());
        }
        internal static void MoveOnPropertyChangedInside(this DocumentEditor editor, IfStatementSyntax ifTrySet, ExpressionStatementSyntax onPropertyChanged)
        {
            editor.RemoveNode(onPropertyChanged);
            editor.AddOnPropertyChanged(ifTrySet, OnPropertyChanged());

            ExpressionStatementSyntax OnPropertyChanged()
            {
                if (onPropertyChanged.HasLeadingTrivia &&
                    onPropertyChanged.GetLeadingTrivia() is { } leadingTrivia&&
                    leadingTrivia.TryFirst(out var first) &&
                    first.IsKind(SyntaxKind.EndOfLineTrivia))
                {
                    onPropertyChanged = onPropertyChanged.WithLeadingTrivia(leadingTrivia.Remove(first));
                }

                return(onPropertyChanged.WithAdditionalAnnotations(Formatter.Annotation));
            }
        }
Esempio n. 21
0
        public virtual async Task <Solution> InlineAndRemoveAsync(
            ExpressionStatementSyntax expressionStatement,
            SyntaxList <StatementSyntax> statements,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (expressionStatement.SyntaxTree == Declaration.SyntaxTree)
            {
                DocumentEditor editor = await DocumentEditor.CreateAsync(Document, cancellationToken).ConfigureAwait(false);

                StatementSyntax[] newStatements = RewriteStatements(statements);

                int count = statements.Count;

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

                StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo(expressionStatement);

                if (statementsInfo.Success)
                {
                    StatementListInfo newStatementsInfo = statementsInfo.WithStatements(statementsInfo.Statements.ReplaceRange(expressionStatement, newStatements));

                    editor.ReplaceNode(statementsInfo.Parent, newStatementsInfo.Parent);
                }
                else
                {
                    editor.ReplaceNode(expressionStatement, Block(newStatements));
                }

                editor.RemoveNode(Declaration);

                return(editor.GetChangedDocument().Solution());
            }
            else
            {
                Document newDocument = await InlineAsync(expressionStatement, statements, cancellationToken).ConfigureAwait(false);

                DocumentId documentId = Document.Solution().GetDocumentId(Declaration.SyntaxTree);

                newDocument = await newDocument.Solution().GetDocument(documentId).RemoveMemberAsync(Declaration, cancellationToken).ConfigureAwait(false);

                return(newDocument.Solution());
            }
        }
        /// <summary>
        /// Move <paramref name="toMove"></paramref> before <paramref name="member">.</paramref>.
        /// </summary>
        /// <param name="editor">The <see cref="DocumentEditor"/>.</param>
        /// <param name="toMove">The <see cref="MemberDeclarationSyntax"/> to move.</param>
        /// <param name="member">The <see cref="MemberDeclarationSyntax"/>.</param>
        /// <returns>The <see cref="DocumentEditor"/> that was passed in.</returns>
        public static DocumentEditor MoveAfter(this DocumentEditor editor, MemberDeclarationSyntax toMove, MemberDeclarationSyntax member)
        {
            if (editor is null)
            {
                throw new ArgumentNullException(nameof(editor));
            }

            if (toMove is null)
            {
                throw new ArgumentNullException(nameof(toMove));
            }

            if (member is null)
            {
                throw new ArgumentNullException(nameof(member));
            }

            editor.RemoveNode(toMove);
            editor.InsertAfter(member, ToMove());
            editor.ReplaceNode(member, Member());
            return(editor);

            MemberDeclarationSyntax ToMove()
            {
                return(toMove.AdjustLeadingNewLine(member));
            }

            MemberDeclarationSyntax Member()
            {
                if (member.Parent is TypeDeclarationSyntax typeDeclaration)
                {
                    var index = typeDeclaration.Members.IndexOf(member) - 1;
                    if (typeDeclaration.Members.IndexOf(toMove) == index)
                    {
                        index--;
                    }

                    return(member.AdjustLeadingNewLine(typeDeclaration.Members.ElementAtOrDefault(index)));
                }

                return(toMove);
            }
        }
Esempio n. 23
0
        private static void AddUsingToEndOfBlock(DocumentEditor editor, BlockSyntax block, ExpressionStatementSyntax statement)
        {
            var statements = block.Statements
                             .Where(s => s.SpanStart > statement.SpanStart)
                             .ToArray();

            foreach (var statementSyntax in statements)
            {
                editor.RemoveNode(statementSyntax);
            }

            editor.ReplaceNode(
                statement,
                SyntaxFactory.UsingStatement(
                    declaration: null,
                    expression: statement.Expression,
                    statement: SyntaxFactory.Block(SyntaxFactory.List(statements))
                    .WithAdditionalAnnotations(Formatter.Annotation)));
        }
Esempio n. 24
0
        public async Task <Solution> InlineAndRemoveMethodAsync(
            ExpressionStatementSyntax expressionStatement,
            SyntaxList <StatementSyntax> statements)
        {
            if (expressionStatement.SyntaxTree == MethodDeclaration.SyntaxTree)
            {
                DocumentEditor editor = await DocumentEditor.CreateAsync(Document, CancellationToken).ConfigureAwait(false);

                StatementSyntax[] newStatements = RewriteStatements(statements);

                int count = statements.Count;

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

                StatementContainer container;
                if (StatementContainer.TryCreate(expressionStatement, out container))
                {
                    SyntaxNode newNode = container.NodeWithStatements(container.Statements.ReplaceRange(expressionStatement, newStatements));

                    editor.ReplaceNode(container.Node, newNode);
                }
                else
                {
                    editor.ReplaceNode(expressionStatement, Block(newStatements));
                }

                editor.RemoveNode(MethodDeclaration);

                return(editor.GetChangedDocument().Solution());
            }
            else
            {
                Document newDocument = await InlineMethodAsync(expressionStatement, statements).ConfigureAwait(false);

                DocumentId documentId = Document.Solution().GetDocumentId(MethodDeclaration.SyntaxTree);

                newDocument = await newDocument.Solution().GetDocument(documentId).RemoveMemberAsync(MethodDeclaration, CancellationToken).ConfigureAwait(false);

                return(newDocument.Solution());
            }
        }
Esempio n. 25
0
        private async Task <Solution> RemoveNodes(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
        {
            var solution = document.Project.Solution;
            var pairs    = await GetNodesToRemoveAsync(document, diagnostic, cancellationToken).ConfigureAwait(false);

            foreach (var group in pairs.GroupBy(p => p.Key))
            {
                DocumentEditor editor = await DocumentEditor.CreateAsync(solution.GetDocument(group.Key), cancellationToken).ConfigureAwait(false);

                // Start removing from bottom to top to keep spans of nodes that are removed later.
                foreach (var value in group.OrderByDescending(v => v.Value.SpanStart))
                {
                    editor.RemoveNode(value.Value);
                }

                solution = solution.WithDocumentSyntaxRoot(group.Key, editor.GetChangedRoot());
            }

            return(solution);
        }
Esempio n. 26
0
        private static void AddUsingToEndOfBlock(DocumentEditor editor, BlockSyntax block, LocalDeclarationStatementSyntax statement)
        {
            var statements = block.Statements
                             .Where(s => s.SpanStart > statement.SpanStart)
                             .TakeWhile(s => !(s is LocalFunctionStatementSyntax))
                             .ToArray();

            foreach (var statementSyntax in statements)
            {
                editor.RemoveNode(statementSyntax);
            }

            editor.ReplaceNode(
                statement,
                SyntaxFactory.UsingStatement(
                    declaration: statement.Declaration.WithoutLeadingTrivia(),
                    expression: null,
                    statement: SyntaxFactory.Block(SyntaxFactory.List(statements))
                    .WithAdditionalAnnotations(Formatter.Annotation))
                .WithLeadingTriviaFrom(statement.Declaration));
        }
Esempio n. 27
0
        private static void AddUsingToEndOfBlock(DocumentEditor editor, SwitchSectionSyntax switchSection, LocalDeclarationStatementSyntax statement)
        {
            var statements = switchSection.Statements
                             .Where(s => s.SpanStart > statement.SpanStart)
                             .Where(s => !(s == switchSection.Statements.Last() &&
                                           s is BreakStatementSyntax))
                             .ToArray();

            foreach (var statementSyntax in statements)
            {
                editor.RemoveNode(statementSyntax);
            }

            editor.ReplaceNode(
                statement,
                SyntaxFactory.UsingStatement(
                    declaration: statement.Declaration,
                    expression: null,
                    statement: SyntaxFactory.Block(SyntaxFactory.List(statements))
                    .WithAdditionalAnnotations(Formatter.Annotation)));
        }
        private static void CreateIf(DocumentEditor editor, ExpressionStatementSyntax setAndRaise, ExpressionStatementSyntax invocation)
        {
            editor.RemoveNode(setAndRaise);
            editor.ReplaceNode(
                invocation,
                (node, _) =>
            {
                var code = StringBuilderPool.Borrow()
                           .AppendLine($"if ({setAndRaise.ToFullString().TrimEnd('\r', '\n', ';')})")
                           .AppendLine("{")
                           .AppendLine($"    {invocation.ToFullString().TrimEnd('\r', '\n')}")
                           .AppendLine("}")
                           .Return();

                return(SyntaxFactory.ParseStatement(code)
                       .WithSimplifiedNames()
                       .WithLeadingElasticLineFeed()
                       .WithTrailingElasticLineFeed()
                       .WithAdditionalAnnotations(Formatter.Annotation));
            });
        }
Esempio n. 29
0
        private static async Task <Solution> InlineAndRemoveMethodAsync(
            Document document,
            InvocationExpressionSyntax invocation,
            MethodDeclarationSyntax methodDeclaration,
            ExpressionSyntax expression,
            ParameterInfo[] parameterInfos,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (invocation.SyntaxTree.Equals(methodDeclaration.SyntaxTree))
            {
                DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);

                Solution solution = document.Project.Solution;

                expression = await ReplaceParameterExpressionWithArgumentExpressionAsync(parameterInfos, expression, solution, cancellationToken).ConfigureAwait(false);

                editor.ReplaceNode(invocation, expression);

                editor.RemoveNode(methodDeclaration);

                document = editor.GetChangedDocument();

                return(document.Project.Solution);
            }
            else
            {
                Solution solution = document.Project.Solution;

                document = await InlineMethodAsync(document, invocation, expression, parameterInfos, cancellationToken).ConfigureAwait(false);

                DocumentId documentId = solution.GetDocumentId(methodDeclaration.SyntaxTree);

                solution = document.Project.Solution;

                return(await RemoveMethodAsync(solution.GetDocument(documentId), methodDeclaration, cancellationToken).ConfigureAwait(false));
            }
        }
 private static void ApplyRemoveSetterFix(DocumentEditor editor, AccessorDeclarationSyntax setter)
 {
     editor.RemoveNode(setter, SyntaxRemoveOptions.AddElasticMarker);
 }