forked from github/codeql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConstructor.cs
More file actions
289 lines (243 loc) · 11.5 KB
/
Constructor.cs
File metadata and controls
289 lines (243 loc) · 11.5 KB
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Semmle.Util;
namespace Semmle.Extraction.CSharp.Entities
{
internal class Constructor : Method
{
private readonly List<SyntaxNode> declaringReferenceSyntax;
private readonly Lazy<ConstructorDeclarationSyntax?> ordinaryConstructorSyntaxLazy;
private readonly Lazy<TypeDeclarationSyntax?> primaryConstructorSyntaxLazy;
private readonly Lazy<PrimaryConstructorBaseTypeSyntax?> primaryBaseLazy;
private Constructor(Context cx, IMethodSymbol init)
: base(cx, init)
{
declaringReferenceSyntax =
Symbol.DeclaringSyntaxReferences
.Select(r => r.GetSyntax())
.ToList();
ordinaryConstructorSyntaxLazy = new Lazy<ConstructorDeclarationSyntax?>(() =>
declaringReferenceSyntax
.OfType<ConstructorDeclarationSyntax>()
.FirstOrDefault());
primaryConstructorSyntaxLazy = new Lazy<TypeDeclarationSyntax?>(() =>
declaringReferenceSyntax
.OfType<TypeDeclarationSyntax>()
.FirstOrDefault(t => t is ClassDeclarationSyntax or StructDeclarationSyntax or RecordDeclarationSyntax));
primaryBaseLazy = new Lazy<PrimaryConstructorBaseTypeSyntax?>(() =>
PrimaryConstructorSyntax?
.BaseList?
.Types
.OfType<PrimaryConstructorBaseTypeSyntax>()
.FirstOrDefault());
}
private ConstructorDeclarationSyntax? OrdinaryConstructorSyntax => ordinaryConstructorSyntaxLazy.Value;
private TypeDeclarationSyntax? PrimaryConstructorSyntax => primaryConstructorSyntaxLazy.Value;
private PrimaryConstructorBaseTypeSyntax? PrimaryBase => primaryBaseLazy.Value;
public override void Populate(TextWriter trapFile)
{
PopulateMethod(trapFile);
PopulateModifiers(trapFile);
ContainingType!.PopulateGenerics();
trapFile.constructors(this, Symbol.ContainingType.Name, ContainingType, (Constructor)OriginalDefinition);
if (Symbol.IsImplicitlyDeclared)
{
var lineCounts = new LineCounts() { Total = 2, Code = 1, Comment = 0 };
trapFile.numlines(this, lineCounts);
}
ExtractCompilerGenerated(trapFile);
if (Context.OnlyScaffold)
{
return;
}
if (MakeSyntheticBody)
{
// Create a synthetic empty body for primary and default constructors.
Statements.SyntheticEmptyBlock.Create(Context, this, 0, Location);
}
if (Context.ExtractLocation(Symbol) && (!IsDefault || IsBestSourceLocation))
{
WriteLocationToTrap(trapFile.constructor_location, this, Location);
}
}
protected override void ExtractInitializers(TextWriter trapFile)
{
// Do not extract initializers for constructed types.
// Extract initializers for constructors with a body, primary constructors
// and default constructors for classes and structs declared in source code.
if (!HasBody && !MakeSyntheticBody || Context.OnlyScaffold)
{
return;
}
if (OrdinaryConstructorSyntax?.Initializer is ConstructorInitializerSyntax initializer)
{
ITypeSymbol initializerType;
var initializerInfo = Context.GetSymbolInfo(initializer);
switch (initializer.Kind())
{
case SyntaxKind.BaseConstructorInitializer:
initializerType = Symbol.ContainingType.BaseType!;
ExtractObjectInitCall(trapFile);
break;
case SyntaxKind.ThisConstructorInitializer:
initializerType = Symbol.ContainingType;
break;
default:
Context.ModelError(initializer, "Unknown initializer");
return;
}
ExtractSourceInitializer(trapFile, initializerType, (IMethodSymbol?)initializerInfo.Symbol, initializer.ArgumentList, initializer.ThisOrBaseKeyword.GetLocation());
}
else if (PrimaryBase is PrimaryConstructorBaseTypeSyntax primaryInitializer)
{
var primaryInfo = Context.GetSymbolInfo(primaryInitializer);
var primarySymbol = primaryInfo.Symbol;
ExtractObjectInitCall(trapFile);
ExtractSourceInitializer(trapFile, primarySymbol?.ContainingType, (IMethodSymbol?)primarySymbol, primaryInitializer.ArgumentList, primaryInitializer.GetLocation());
}
else if (Symbol.MethodKind is MethodKind.Constructor)
{
ExtractObjectInitCall(trapFile);
var baseType = Symbol.ContainingType.BaseType;
if (baseType is null)
{
if (Symbol.ContainingType.SpecialType != SpecialType.System_Object)
{
Context.ModelError(Symbol, "Unable to resolve base type in implicit constructor initializer");
}
return;
}
var baseConstructor = baseType.InstanceConstructors.FirstOrDefault(c => c.Arity is 0);
if (baseConstructor is null)
{
Context.ModelError(Symbol, "Unable to resolve implicit constructor initializer call");
return;
}
var baseConstructorTarget = Create(Context, baseConstructor);
var info = new ExpressionInfo(Context,
AnnotatedTypeSymbol.CreateNotAnnotated(baseType),
Location,
Kinds.ExprKind.CONSTRUCTOR_INIT,
this,
-1,
isCompilerGenerated: true,
null);
trapFile.expr_call(new Expression(info), baseConstructorTarget);
}
}
private void ExtractObjectInitCall(TextWriter trapFile)
{
var target = ObjectInitMethod.Create(Context, ContainingType!);
var type = Context.Compilation.GetSpecialType(SpecialType.System_Void);
var info = new ExpressionInfo(Context,
AnnotatedTypeSymbol.CreateNotAnnotated(type),
Location,
Kinds.ExprKind.METHOD_INVOCATION,
this,
-2,
isCompilerGenerated: true,
null);
var obinitCall = new Expression(info);
trapFile.expr_call(obinitCall, target);
Expressions.This.CreateImplicit(Context, Symbol.ContainingType, Location, obinitCall, -1);
}
private void ExtractSourceInitializer(TextWriter trapFile, ITypeSymbol? type, IMethodSymbol? symbol, ArgumentListSyntax arguments, Microsoft.CodeAnalysis.Location location)
{
var initInfo = new ExpressionInfo(Context,
AnnotatedTypeSymbol.CreateNotAnnotated(type),
Context.CreateLocation(location),
Kinds.ExprKind.CONSTRUCTOR_INIT,
this,
-1,
false,
null);
var init = new Expression(initInfo);
var target = Constructor.Create(Context, symbol);
if (target is null)
{
Context.ModelError(Symbol, "Unable to resolve call");
return;
}
trapFile.expr_call(init, target);
init.PopulateArguments(trapFile, arguments, 0);
}
private bool IsPrimary => PrimaryConstructorSyntax is not null;
// This is a default constructor in a class or struct declared in source.
private bool IsDefault =>
Symbol.IsImplicitlyDeclared &&
Symbol.ContainingType.FromSource() &&
Symbol.ContainingType.TypeKind is TypeKind.Class or TypeKind.Struct &&
Symbol.ContainingType.IsSourceDeclaration() &&
!Symbol.ContainingType.IsAnonymousType;
/// <summary>
/// Returns true if we consider the reporting location of this constructor entity the best
/// location of the constructor.
/// For partial classes with default constructors, Roslyn consider each partial class declaration
/// as the possible location for the implicit default constructor.
/// </summary>
private bool IsBestSourceLocation => ReportingLocation is not null && Context.IsLocationInContext(ReportingLocation);
private bool MakeSyntheticBody => (IsPrimary || (IsDefault && IsBestSourceLocation)) && !Context.OnlyScaffold;
[return: NotNullIfNotNull(nameof(constructor))]
public static new Constructor? Create(Context cx, IMethodSymbol? constructor)
{
if (constructor is null)
return null;
switch (constructor.MethodKind)
{
case MethodKind.StaticConstructor:
case MethodKind.Constructor:
return ConstructorFactory.Instance.CreateEntityFromSymbol(cx, constructor.GetBodyDeclaringSymbol());
default:
throw new InternalError(constructor, "Attempt to create a Constructor from a symbol that isn't a constructor");
}
}
public override void WriteId(EscapingTextWriter trapFile)
{
if (!SymbolEqualityComparer.Default.Equals(Symbol, Symbol.OriginalDefinition))
{
trapFile.WriteSubId(ContainingType!);
trapFile.Write(".");
trapFile.WriteSubId(OriginalDefinition);
trapFile.Write(";constructor");
return;
}
if (Symbol.IsStatic)
trapFile.Write("static");
trapFile.WriteSubId(ContainingType!);
AddParametersToId(Context, trapFile, Symbol);
trapFile.Write(";constructor");
}
public override Microsoft.CodeAnalysis.Location? FullLocation => ReportingLocation;
public override Microsoft.CodeAnalysis.Location? ReportingLocation
{
get
{
if (OrdinaryConstructorSyntax is not null)
{
return OrdinaryConstructorSyntax.Identifier.GetLocation();
}
if (PrimaryConstructorSyntax is not null)
{
return PrimaryConstructorSyntax.Identifier.GetLocation();
}
if (Symbol.IsImplicitlyDeclared)
{
var best = Symbol.Locations.Where(l => l.IsInSource).BestOrDefault();
return best ?? ContainingType!.ReportingLocation;
}
return Symbol.ContainingType.Locations.FirstOrDefault();
}
}
private class ConstructorFactory : CachedEntityFactory<IMethodSymbol, Constructor>
{
public static ConstructorFactory Instance { get; } = new ConstructorFactory();
public override Constructor Create(Context cx, IMethodSymbol init) => new Constructor(cx, init);
}
}
}