77using Microsoft . CodeAnalysis ;
88using Microsoft . CodeAnalysis . CSharp ;
99using Microsoft . CodeAnalysis . CSharp . Syntax ;
10+ using Microsoft . CodeAnalysis . Simplification ;
1011
1112namespace Microsoft . DotNet . CodeFormatting . Rules
1213{
@@ -17,6 +18,12 @@ private sealed class ExplicitThisRewriter : CSharpSyntaxRewriter
1718 {
1819 private readonly SemanticModel _semanticModel ;
1920 private readonly CancellationToken _cancellationToken ;
21+ private bool _addedAnnotations ;
22+
23+ internal bool AddedAnnotations
24+ {
25+ get { return _addedAnnotations ; }
26+ }
2027
2128 internal ExplicitThisRewriter ( SemanticModel semanticModel , CancellationToken cancellationToken )
2229 {
@@ -38,25 +45,14 @@ public override SyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyn
3845 var field = ( IFieldSymbol ) symbolInfo . Symbol ;
3946 if ( field . DeclaredAccessibility == Accessibility . Private )
4047 {
41- return RemoveQualification ( node ) ;
48+ _addedAnnotations = true ;
49+ return node . WithAdditionalAnnotations ( Simplifier . Annotation ) ;
4250 }
4351 }
4452 }
4553
4654 return node ;
4755 }
48-
49- private static NameSyntax RemoveQualification ( MemberAccessExpressionSyntax memberSyntax )
50- {
51- var thisSyntax = memberSyntax . Expression ;
52- var nameSyntax = memberSyntax . Name ;
53- var triviaList = thisSyntax
54- . GetLeadingTrivia ( )
55- . AddRange ( thisSyntax . GetTrailingTrivia ( ) )
56- . AddRange ( memberSyntax . OperatorToken . GetAllTrivia ( ) )
57- . AddRange ( nameSyntax . GetLeadingTrivia ( ) ) ;
58- return nameSyntax . WithLeadingTrivia ( triviaList ) ;
59- }
6056 }
6157
6258 public async Task < Document > ProcessAsync ( Document document , CancellationToken cancellationToken )
@@ -70,7 +66,12 @@ public async Task<Document> ProcessAsync(Document document, CancellationToken ca
7066 var semanticModel = await document . GetSemanticModelAsync ( cancellationToken ) ;
7167 var rewriter = new ExplicitThisRewriter ( semanticModel , cancellationToken ) ;
7268 var newNode = rewriter . Visit ( syntaxNode ) ;
73- return document . WithSyntaxRoot ( newNode ) ;
69+ if ( ! rewriter . AddedAnnotations )
70+ {
71+ return document ;
72+ }
73+
74+ return await Simplifier . ReduceAsync ( document . WithSyntaxRoot ( newNode ) , cancellationToken : cancellationToken ) ;
7475 }
7576 }
7677}
0 commit comments