Skip to content
This repository was archived by the owner on Jul 12, 2022. It is now read-only.

Commit 445a69b

Browse files
committed
Fix trivia handling while removing this.
1 parent 8290cef commit 445a69b

File tree

2 files changed

+70
-5
lines changed

2 files changed

+70
-5
lines changed

src/Microsoft.DotNet.CodeFormatting.Tests/Rules/ExplicitThisRuleTests.cs

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,66 @@ void M()
9494
this.field3 = null;
9595
}
9696
}
97+
";
98+
Verify(text, expected, runFormatter: false);
99+
}
100+
101+
[Fact]
102+
public void TestFieldAssignmentWithTrivia()
103+
{
104+
var text = @"
105+
class C1
106+
{
107+
int _field;
108+
109+
void M()
110+
{
111+
this. /* comment1 */ _field /* comment 2 */ = 0;
112+
}
113+
}
114+
";
115+
116+
var expected = @"
117+
class C1
118+
{
119+
int _field;
120+
121+
void M()
122+
{
123+
/* comment1 */ _field /* comment 2 */ = 0;
124+
}
125+
}
126+
";
127+
Verify(text, expected, runFormatter: false);
128+
}
129+
130+
[Fact]
131+
public void TestFieldBadName()
132+
{
133+
var text = @"
134+
class C1
135+
{
136+
int _field;
137+
138+
void M()
139+
{
140+
// Not a valid field access, can't reliably remove this.
141+
this.field1 = 0;
142+
}
143+
}
144+
";
145+
146+
var expected = @"
147+
class C1
148+
{
149+
int _field;
150+
151+
void M()
152+
{
153+
// Not a valid field access, can't reliably remove this.
154+
this.field1 = 0;
155+
}
156+
}
97157
";
98158
Verify(text, expected, runFormatter: false);
99159
}

src/Microsoft.DotNet.CodeFormatting/Rules/ExplicitThisRule.cs

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -37,19 +37,24 @@ public override SyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyn
3737
var field = (IFieldSymbol)symbolInfo.Symbol;
3838
if (field.DeclaredAccessibility == Accessibility.Private)
3939
{
40-
return node.Name
41-
.WithLeadingTrivia(node.GetLeadingTrivia())
42-
.WithTrailingTrivia(node.GetTrailingTrivia());
40+
return RemoveQualification(node);
4341
}
4442
}
4543
}
4644

4745
return node;
4846
}
4947

50-
public override SyntaxNode VisitAssignmentExpression(AssignmentExpressionSyntax node)
48+
private static NameSyntax RemoveQualification(MemberAccessExpressionSyntax memberSyntax)
5149
{
52-
return base.VisitAssignmentExpression(node);
50+
var thisSyntax = memberSyntax.Expression;
51+
var nameSyntax = memberSyntax.Name;
52+
var triviaList = thisSyntax
53+
.GetLeadingTrivia()
54+
.AddRange(thisSyntax.GetTrailingTrivia())
55+
.AddRange(memberSyntax.OperatorToken.GetAllTrivia())
56+
.AddRange(nameSyntax.GetLeadingTrivia());
57+
return nameSyntax.WithLeadingTrivia(triviaList);
5358
}
5459
}
5560

0 commit comments

Comments
 (0)