MoveDeclarationNearReferenceCodeRefactoringProvider.Rewriter.cs 1.9 KB
Newer Older
S
Sam Harwell 已提交
1
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.
2 3 4 5 6 7 8 9 10 11 12

using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;

namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.MoveDeclarationNearReference
{
    internal partial class MoveDeclarationNearReferenceCodeRefactoringProvider
    {
        private class Rewriter : CSharpSyntaxRewriter
        {
13 14 15 16
            private readonly BlockSyntax _oldInnermostBlock;
            private readonly BlockSyntax _newInnermostBlock;
            private readonly BlockSyntax _oldOutermostBlock;
            private readonly LocalDeclarationStatementSyntax _declarationStatement;
17 18 19 20 21 22 23

            public Rewriter(
                BlockSyntax oldInnermostBlock,
                BlockSyntax newInnermostBlock,
                BlockSyntax oldOutermostBlock,
                LocalDeclarationStatementSyntax declarationStatement)
            {
24 25 26 27
                _oldInnermostBlock = oldInnermostBlock;
                _newInnermostBlock = newInnermostBlock;
                _oldOutermostBlock = oldOutermostBlock;
                _declarationStatement = declarationStatement;
28 29 30 31
            }

            public override SyntaxNode VisitBlock(BlockSyntax oldBlock)
            {
32
                if (oldBlock == _oldInnermostBlock)
33
                {
34
                    return _newInnermostBlock;
35 36
                }

37
                if (oldBlock == _oldOutermostBlock)
38
                {
39
                    var statements = SyntaxFactory.List(oldBlock.Statements.Where(s => s != _declarationStatement).Select(this.Visit));
40 41 42 43 44 45 46 47
                    return oldBlock.WithStatements(statements).WithAdditionalAnnotations(Formatter.Annotation);
                }

                return base.VisitBlock(oldBlock);
            }
        }
    }
}