📄
core/src/CallGraphBuilder.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
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.FindSymbols; namespace Cfa; internal sealed class CallGraphBuilder { public static async Task<CallGraph> BuildCallGraph( ScannerOptions options, Solution solution, IReadOnlyCollection<Compilation> compilations, ISymbol origin, CancellationToken cancellationToken ) { var builder = new CallGraphBuilder(options, solution, compilations); await builder.FindCallees(origin, cancellationToken); builder.InvertCallees(origin); await builder.FindCallers(origin, cancellationToken); return new CallGraph( origin, builder.ReachableFromSymbols.ToImmutable(), builder.ReachesToSymbols.ToImmutable() ); } private readonly Solution solution; private readonly IReadOnlyCollection<Compilation> compilations; private readonly HashSet<ProjectId> includedProjects; private readonly HashSet<SyntaxTree> includedTrees; private readonly IReadOnlyCollection<INamedTypeSymbol> types; private readonly MessageLinks messageLinks; private readonly HashSet<ISymbol> seenFrom = [with(SymbolEqualityComparer.Default)]; internal ImmutableDictionary<ISymbol, IImmutableList<Call>>.Builder ReachableFromSymbols { get; } = ImmutableDictionary.CreateBuilder<ISymbol, IImmutableList<Call>>(SymbolEqualityComparer.Default); private readonly HashSet<ISymbol> seenTo = [with(SymbolEqualityComparer.Default)]; internal ImmutableDictionary<ISymbol, IImmutableList<Call>>.Builder ReachesToSymbols { get; } = ImmutableDictionary.CreateBuilder<ISymbol, IImmutableList<Call>>(SymbolEqualityComparer.Default); internal CallGraphBuilder(ScannerOptions options, Solution solution, IReadOnlyCollection<Compilation> compilations) { this.solution = solution; this.compilations = compilations; includedProjects = [ .. solution .Projects.Where(project => options.IncludesProject(project.FilePath ?? project.Name)) .Select(project => project.Id), ]; includedTrees = [ .. compilations .SelectMany(compilation => compilation.SyntaxTrees) .Where(tree => solution.GetDocument(tree) is { Project.Id: var projectId } && includedProjects.Contains(projectId) ), ]; types = [ .. compilations .SelectMany(compilation => compilation.GetSymbolsWithName(_ => true, SymbolFilter.Type)) .OfType<INamedTypeSymbol>(), ]; messageLinks = new MessageLinks(options.Messages, compilations, includedTrees, solution); } internal async Task FindCallees(ISymbol symbol, CancellationToken cancellationToken) { if (!seenFrom.Add(symbol)) { return; } var seenCall = new Dictionary<ISymbol, LinkKind>(SymbolEqualityComparer.Default); foreach (var handler in await messageLinks.Targets(symbol, cancellationToken)) { AddCall(handler, LinkKind.Event); } foreach (var reference in symbol.DeclaringSyntaxReferences) { var syntax = reference.GetSyntax(cancellationToken); var semanticModelForSyntax = compilations.GetSemanticModel(syntax.SyntaxTree); var accesses = syntax .DescendantNodesAndSelf(node => node == syntax || node is not AnonymousFunctionExpressionSyntax || semanticModelForSyntax.GetSymbolInfo(node, cancellationToken).Symbol is not { } handler || !messageLinks.IsHandler(handler) ) .Where(node => node is SimpleNameSyntax or ElementAccessExpressionSyntax or ElementBindingExpressionSyntax or BaseObjectCreationExpressionSyntax or ConstructorInitializerSyntax ); foreach (var access in accesses) { if (messageLinks.IsRegistrationArgument(access)) { continue; } var accessedSymbol = semanticModelForSyntax.GetSymbolInfo(access, cancellationToken).Symbol; if (accessedSymbol is not (IMethodSymbol or IPropertySymbol)) { continue; } if (accessedSymbol.IsAbstract || accessedSymbol.IsVirtual) { foreach (var implementation in FindImplementations(accessedSymbol)) { AddCall(implementation, LinkKind.Abstract); } } if (!accessedSymbol.IsAbstract) { AddCall(accessedSymbol, LinkKind.Direct); } } } ReachableFromSymbols.Add(symbol, seenCall.Select(call => new Call(call.Key, call.Value)).ToImmutableList()); foreach (var target in seenCall.Keys) { await FindCallees(target, cancellationToken); } void AddCall(ISymbol target, LinkKind linkKind) { if ( !IsDeclaredInSource(target) || linkKind is LinkKind.Abstract && target.IsAbstract || target is IPropertySymbol property && !HasBody(property, cancellationToken) ) { return; } if (!seenCall.TryAdd(target, linkKind) && linkKind is LinkKind.Direct) { seenCall[target] = LinkKind.Direct; } } } private IEnumerable<ISymbol> FindImplementations(ISymbol member) { foreach (var type in types) { if (member.ContainingType.TypeKind is TypeKind.Interface) { if (type.FindImplementationForInterfaceMember(member) is { } implementation) { yield return implementation; } continue; } foreach (var candidate in type.GetMembers(member.Name)) { for ( var overridden = GetOverriddenMember(candidate); overridden is not null; overridden = GetOverriddenMember(overridden) ) { if (SymbolEqualityComparer.Default.Equals(overridden.OriginalDefinition, member.OriginalDefinition)) { yield return candidate; break; } } } } } internal async Task FindCallers(ISymbol origin, CancellationToken cancellationToken) { if (!seenTo.Add(origin)) { return; } var contracts = new HashSet<ISymbol>(SymbolEqualityComparer.Default); for (var member = GetOverriddenMember(origin); member is not null; member = GetOverriddenMember(member)) { contracts.Add(member.OriginalDefinition); } foreach (var interfaceType in origin.ContainingType.AllInterfaces) { foreach (var member in interfaceType.GetMembers()) { var implementation = origin.ContainingType.FindImplementationForInterfaceMember(member); if ( SymbolEqualityComparer.Default.Equals(implementation?.OriginalDefinition, origin.OriginalDefinition) ) { contracts.Add(member.OriginalDefinition); } } } var seenCall = new Dictionary<ISymbol, LinkKind>(SymbolEqualityComparer.Default); var references = origin is IMethodSymbol { MethodKind: MethodKind.AnonymousFunction } ? [] : await SymbolFinder.FindReferencesAsync(origin, solution, cancellationToken); foreach (var publisher in await messageLinks.Callers(origin, references, cancellationToken)) { if (seenCall.TryAdd(publisher, LinkKind.Event)) { await FindCallers(publisher, cancellationToken); } } foreach (var referencedSymbol in references) { var definition = referencedSymbol.Definition.OriginalDefinition; var linkKind = SymbolEqualityComparer.Default.Equals(definition, origin.OriginalDefinition) ? LinkKind.Direct : LinkKind.Abstract; if (linkKind is not LinkKind.Direct && !contracts.Contains(definition)) { continue; } foreach (var reference in referencedSymbol.Locations) { var root = await reference.Document.GetSyntaxRootAsync(cancellationToken); if ( root is not null && messageLinks.IsRegistrationArgument(root.FindNode(reference.Location.SourceSpan)) ) { continue; } var semanticModel = await reference.Document.GetSemanticModelAsync(cancellationToken); var caller = semanticModel?.GetEnclosingSymbol(reference.Location.SourceSpan.Start, cancellationToken); while ( caller is IMethodSymbol { MethodKind: MethodKind.AnonymousFunction } && !messageLinks.IsHandler(caller) ) { caller = caller.ContainingSymbol; } if (caller is IMethodSymbol { AssociatedSymbol: IPropertySymbol property }) { caller = property; } if (caller is not (IMethodSymbol or IPropertySymbol) || !IsDeclaredInSource(caller)) { continue; } if (seenCall.TryAdd(caller, linkKind)) { await FindCallers(caller, cancellationToken); } else if (linkKind is LinkKind.Direct) { seenCall[caller] = LinkKind.Direct; } } } ReachesToSymbols.Add(origin, seenCall.Select(call => new Call(call.Key, call.Value)).ToImmutableList()); } private static ISymbol? GetOverriddenMember(ISymbol member) => member switch { IMethodSymbol method => method.OverriddenMethod, IPropertySymbol property => property.OverriddenProperty, _ => null, }; private bool IsDeclaredInSource(ISymbol symbol) => (!symbol.IsImplicitlyDeclared || symbol is IMethodSymbol { MethodKind: MethodKind.AnonymousFunction }) && symbol.DeclaringSyntaxReferences.Any(reference => includedTrees.Contains(reference.SyntaxTree)); private static bool HasBody(IPropertySymbol property, CancellationToken cancellationToken) => property.DeclaringSyntaxReferences.Any(reference => reference.GetSyntax(cancellationToken) switch { PropertyDeclarationSyntax { ExpressionBody: not null } => true, IndexerDeclarationSyntax { ExpressionBody: not null } => true, BasePropertyDeclarationSyntax declaration => declaration.AccessorList?.Accessors.Any(accessor => accessor.Body is not null || accessor.ExpressionBody is not null ) is true, _ => false, } ); private void InvertCallees(ISymbol origin) { ReachesToSymbols.AddRange( ReachableFromSymbols.Invert().Where(kvp => !SymbolEqualityComparer.Default.Equals(kvp.Key, origin)) ); seenTo.UnionWith(ReachesToSymbols.Keys); } }