-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathInferredNullabilitySyntaxRewriter.cs
172 lines (156 loc) · 8.19 KB
/
InferredNullabilitySyntaxRewriter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
// Copyright (c) 2020 Daniel Grunwald
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace ICSharpCode.NullabilityInference
{
/// <summary>
/// Rewrites a C# syntax tree by replacing nullable reference type syntax with that inferred by our analysis.
/// </summary>
internal sealed class InferredNullabilitySyntaxRewriter : CSharpSyntaxRewriter
{
private readonly SemanticModel semanticModel;
private readonly TypeSystem typeSystem;
private readonly SyntaxToNodeMapping mapping;
private readonly CancellationToken cancellationToken;
private Statistics stats = new Statistics();
public InferredNullabilitySyntaxRewriter(SemanticModel semanticModel, TypeSystem typeSystem, SyntaxToNodeMapping mapping, CancellationToken cancellationToken)
: base(visitIntoStructuredTrivia: true)
{
this.semanticModel = semanticModel;
this.typeSystem = typeSystem;
this.mapping = mapping;
this.cancellationToken = cancellationToken;
}
public ref readonly Statistics Statistics => ref stats;
private bool isActive = true;
public override SyntaxNode? VisitNullableDirectiveTrivia(NullableDirectiveTriviaSyntax node)
{
isActive = node.SettingToken.IsKind(SyntaxKind.RestoreKeyword);
return base.VisitNullableDirectiveTrivia(node);
}
public override SyntaxNode? VisitNullableType(NullableTypeSyntax node)
{
var elementType = node.ElementType.Accept(this);
if (elementType == null)
return null;
var symbolInfo = semanticModel.GetSymbolInfo(node);
if (isActive && symbolInfo.Symbol is ITypeSymbol { IsReferenceType: true }) {
// Remove existing nullable reference types
return elementType.WithTrailingTrivia(node.GetTrailingTrivia());
} else {
return node.ReplaceNode(node.ElementType, elementType);
}
}
public override SyntaxNode? VisitIdentifierName(IdentifierNameSyntax node)
{
return HandleTypeName(node, base.VisitIdentifierName(node));
}
public override SyntaxNode? VisitGenericName(GenericNameSyntax node)
{
return HandleTypeName(node, base.VisitGenericName(node));
}
public override SyntaxNode? VisitPredefinedType(PredefinedTypeSyntax node)
{
return HandleTypeName(node, base.VisitPredefinedType(node));
}
public override SyntaxNode? VisitQualifiedName(QualifiedNameSyntax node)
{
return HandleTypeName(node, base.VisitQualifiedName(node));
}
private SyntaxNode? HandleTypeName(TypeSyntax node, SyntaxNode? newNode)
{
if (!isActive || !GraphBuildingSyntaxVisitor.CanBeMadeNullableSyntax(node)) {
return newNode;
}
var symbolInfo = semanticModel.GetSymbolInfo(node, cancellationToken);
if (symbolInfo.Symbol is ITypeSymbol ty && ty.CanBeMadeNullable() && newNode is TypeSyntax newTypeSyntax) {
var nullNode = mapping[node];
if (nullNode.NullType == NullType.Nullable) {
stats.NullableCount++;
return SyntaxFactory.NullableType(
elementType: newTypeSyntax.WithoutTrailingTrivia(),
questionToken: SyntaxFactory.Token(SyntaxKind.QuestionToken)
).WithTrailingTrivia(newTypeSyntax.GetTrailingTrivia());
} else {
stats.NonNullCount++;
}
}
return newNode;
}
public override SyntaxNode? VisitArrayType(ArrayTypeSyntax node)
{
var newNode = base.VisitArrayType(node);
if (isActive && GraphBuildingSyntaxVisitor.CanBeMadeNullableSyntax(node) && newNode is TypeSyntax newTypeSyntax) {
var nullNode = mapping[node];
if (nullNode.NullType == NullType.Nullable) {
stats.NullableCount++;
return SyntaxFactory.NullableType(
elementType: newTypeSyntax.WithoutTrailingTrivia(),
questionToken: SyntaxFactory.Token(SyntaxKind.QuestionToken)
).WithTrailingTrivia(newTypeSyntax.GetTrailingTrivia());
} else {
stats.NonNullCount++;
}
}
return newNode;
}
public override SyntaxNode? VisitParameter(ParameterSyntax node)
{
var param = semanticModel.GetDeclaredSymbol(node, cancellationToken);
node = (ParameterSyntax)base.VisitParameter(node)!;
if (isActive && param != null && typeSystem.TryGetOutParameterFlowNodes(param, out var pair)) {
if (pair.whenTrue.NullType != pair.whenFalse.NullType) {
Debug.Assert(pair.whenTrue.NullType == NullType.NonNull || pair.whenFalse.NullType == NullType.NonNull);
// Create [NotNullWhen] attribute
bool notNullWhen = (pair.whenTrue.NullType == NullType.NonNull);
var attrArgument = SyntaxFactory.LiteralExpression(notNullWhen ? SyntaxKind.TrueLiteralExpression : SyntaxKind.FalseLiteralExpression);
var newAttribute = SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("NotNullWhen"),
SyntaxFactory.AttributeArgumentList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory.AttributeArgument(attrArgument))));
var newAttributeList = SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(newAttribute));
node = node.AddAttributeLists(newAttributeList.WithTrailingTrivia(SyntaxFactory.Space));
needsUsingCodeAnalysis = true;
stats.NotNullWhenCount++;
}
}
return node;
}
private bool needsUsingCodeAnalysis;
public override SyntaxNode? VisitCompilationUnit(CompilationUnitSyntax node)
{
bool hasUsingCodeAnalysis = false;
foreach (var u in node.Usings) {
var symbolInfo = semanticModel.GetSymbolInfo(u.Name, cancellationToken);
if (symbolInfo.Symbol is INamespaceSymbol ns && ns.GetFullName() == "System.Diagnostics.CodeAnalysis") {
hasUsingCodeAnalysis = true;
}
}
node = (CompilationUnitSyntax)base.VisitCompilationUnit(node)!;
if (needsUsingCodeAnalysis && !hasUsingCodeAnalysis) {
var qname = SyntaxFactory.QualifiedName(SyntaxFactory.QualifiedName(SyntaxFactory.IdentifierName("System"), SyntaxFactory.IdentifierName("Diagnostics")), SyntaxFactory.IdentifierName("CodeAnalysis"));
node = node.AddUsings(SyntaxFactory.UsingDirective(qname.WithLeadingTrivia(SyntaxFactory.Space)));
}
return node;
}
}
}