-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathCrossScopeValidator.ts
More file actions
730 lines (643 loc) · 33.8 KB
/
CrossScopeValidator.ts
File metadata and controls
730 lines (643 loc) · 33.8 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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
import type { UnresolvedSymbol } from './AstValidationSegmenter';
import type { Scope } from './Scope';
import type { BrsFile, ProvidedSymbol } from './files/BrsFile';
import { DiagnosticMessages } from './DiagnosticMessages';
import type { Program } from './Program';
import { util } from './util';
import { SymbolTypeFlag } from './SymbolTypeFlag';
import type { BscSymbol } from './SymbolTable';
import { isCallExpression, isConstStatement, isEnumStatement, isEnumType, isFunctionStatement, isInheritableType, isInterfaceStatement, isNamespaceStatement, isNamespaceType, isReferenceType, isTypedFunctionType, isUnionType } from './astUtils/reflection';
import type { ReferenceType } from './types/ReferenceType';
import { getAllRequiredSymbolNames } from './types/ReferenceType';
import type { TypeChainEntry, TypeChainProcessResult } from './interfaces';
import { BscTypeKind } from './types/BscTypeKind';
import { getAllTypesFromCompoundType } from './types/helpers';
import type { BscType } from './types/BscType';
import type { BscFile } from './files/BscFile';
import type { ClassStatement, ConstStatement, EnumMemberStatement, EnumStatement, InterfaceStatement, NamespaceStatement } from './parser/Statement';
import { ParseMode } from './parser/Parser';
import { globalFile } from './globalCallables';
import type { DottedGetExpression, VariableExpression } from './parser/Expression';
import type { InheritableType } from './types';
interface FileSymbolPair {
file: BscFile;
symbol: BscSymbol;
}
interface SymbolLookupKeys {
potentialTypeKey: string;
key: string;
namespacedKey: string;
namespacedPotentialTypeKey: string;
}
const CrossScopeValidatorDiagnosticTag = 'CrossScopeValidator';
export class ProvidedNode {
namespaces = new Map<string, ProvidedNode>();
symbols = new Map<string, FileSymbolPair>();
constructor(public key: string = '', private componentsMap?: Map<string, FileSymbolPair>) { }
getSymbolByKey(symbolKeys: SymbolLookupKeys): FileSymbolPair {
return this.getSymbol(symbolKeys.namespacedKey) ??
this.getSymbol(symbolKeys.key) ??
this.getSymbol(symbolKeys.namespacedPotentialTypeKey) ??
this.getSymbol(symbolKeys.potentialTypeKey);
}
getSymbol(symbolName: string): FileSymbolPair {
if (!symbolName) {
return;
}
const lowerSymbolName = symbolName.toLowerCase();
if (this.componentsMap?.has(lowerSymbolName)) {
return this.componentsMap.get(lowerSymbolName);
}
let lowerSymbolNameParts = lowerSymbolName.split('.');
return this.getSymbolByNameParts(lowerSymbolNameParts, this);
}
getNamespace(namespaceName: string): ProvidedNode {
let lowerSymbolNameParts = namespaceName.toLowerCase().split('.');
return this.getNamespaceByNameParts(lowerSymbolNameParts);
}
getSymbolByNameParts(lowerSymbolNameParts: string[], root: ProvidedNode): FileSymbolPair {
const first = lowerSymbolNameParts?.[0];
const rest = lowerSymbolNameParts.slice(1);
if (!first) {
return;
}
if (this.symbols.has(first)) {
let result = this.symbols.get(first);
let currentType = result.symbol.type;
for (const namePart of rest) {
if (isTypedFunctionType(currentType)) {
const returnType = currentType.returnType;
if (returnType.isResolvable()) {
currentType = returnType;
} else if (isReferenceType(returnType)) {
const fullName = returnType.fullName;
if (fullName.includes('.')) {
currentType = root.getSymbol(fullName)?.symbol?.type;
} else {
currentType = this.getSymbol(fullName)?.symbol?.type ??
root.getSymbol(fullName)?.symbol?.type;
}
}
}
let typesToTry = [currentType];
if (isEnumType(currentType)) {
typesToTry.push(currentType.defaultMemberType);
}
if (isInheritableType(currentType)) {
let inheritableType = currentType;
while (inheritableType?.parentType) {
let parentType = inheritableType.parentType as BscType;
if (isReferenceType(inheritableType.parentType)) {
const fullName = inheritableType.parentType.fullName;
if (fullName.includes('.')) {
parentType = root.getSymbol(fullName)?.symbol?.type;
} else {
parentType = this.getSymbol(fullName)?.symbol?.type ??
root.getSymbol(fullName)?.symbol?.type;
}
}
typesToTry.push(parentType);
inheritableType = parentType as InheritableType;
}
}
const extraData = {};
for (const curType of typesToTry) {
currentType = curType?.getMemberType(namePart, { flags: SymbolTypeFlag.runtime, data: extraData });
if (isReferenceType(currentType)) {
const memberLookup = currentType.fullName;
currentType = this.getSymbol(memberLookup.toLowerCase())?.symbol?.type ?? root.getSymbol(memberLookup.toLowerCase())?.symbol?.type;
}
if (currentType) {
break;
}
}
if (!currentType) {
return;
}
// get specific member
result = {
...result, symbol: { name: namePart, type: currentType, data: extraData, flags: SymbolTypeFlag.runtime }
};
}
return result;
} else if (rest && this.namespaces.has(first)) {
const node = this.namespaces.get(first);
const parts = node.getSymbolByNameParts(rest, root);
return parts;
}
}
getNamespaceByNameParts(lowerSymbolNameParts: string[]): ProvidedNode {
const first = lowerSymbolNameParts?.[0]?.toLowerCase();
const rest = lowerSymbolNameParts.slice(1);
if (!first) {
return;
}
if (this.namespaces.has(first)) {
const node = this.namespaces.get(first);
const result = rest?.length > 0 ? node.getNamespaceByNameParts(rest) : node;
return result;
}
}
addSymbol(symbolName: string, symbolPair: FileSymbolPair) {
let lowerSymbolNameParts = symbolName.toLowerCase().split('.');
return this.addSymbolByNameParts(lowerSymbolNameParts, symbolPair);
}
private addSymbolByNameParts(lowerSymbolNameParts: string[], symbolPair: FileSymbolPair) {
const first = lowerSymbolNameParts?.[0];
const rest = lowerSymbolNameParts?.slice(1);
let isDuplicate = false;
if (!first) {
return;
}
if (rest?.length > 0) {
// first must be a namespace
let namespaceNode = this.namespaces.get(first);
if (!namespaceNode) {
namespaceNode = new ProvidedNode(first);
this.namespaces.set(first, namespaceNode);
}
return namespaceNode.addSymbolByNameParts(rest, symbolPair);
} else {
if (this.namespaces.get(first)) {
// trying to add a symbol that already exists as a namespace - this is a duplicate
return true;
}
// just add it to the symbols
const existingSymbolPair = this.symbols.get(first);
if (!existingSymbolPair) {
this.symbols.set(first, symbolPair);
} else {
isDuplicate = existingSymbolPair.symbol.data?.definingNode !== symbolPair.symbol.data?.definingNode;
}
}
return isDuplicate;
}
}
export class CrossScopeValidator {
constructor(public program: Program) { }
private symbolMapKeys(symbol: UnresolvedSymbol): SymbolLookupKeys[] {
let keysArray = new Array<SymbolLookupKeys>();
let unnamespacedNameLowers: string[] = [];
function joinTypeChainForKey(typeChain: TypeChainEntry[], firstType?: BscType) {
firstType ||= typeChain[0].type;
const unnamespacedNameLower = typeChain.map((tce, i) => {
if (i === 0) {
if (isReferenceType(firstType)) {
return firstType.fullName;
} else if (isInheritableType(firstType)) {
return tce.type.toString();
}
return tce.name;
}
return tce.name;
}).join('.').toLowerCase();
return unnamespacedNameLower;
}
if (isUnionType(symbol.typeChain[0].type) && symbol.typeChain[0].data.isInstance) {
const allUnifiedTypes = getAllTypesFromCompoundType(symbol.typeChain[0].type);
for (const unifiedType of allUnifiedTypes) {
unnamespacedNameLowers.push(joinTypeChainForKey(symbol.typeChain, unifiedType));
}
} else {
unnamespacedNameLowers.push(joinTypeChainForKey(symbol.typeChain));
}
for (const unnamespacedNameLower of unnamespacedNameLowers) {
const lowerFirst = symbol.typeChain[0]?.name?.toLowerCase() ?? '';
let namespacedName = '';
let lowerNamespacePrefix = '';
let namespacedPotentialTypeKey = '';
if (symbol.containingNamespaces?.length > 0 && symbol.typeChain[0]?.name.toLowerCase() !== symbol.containingNamespaces[0].toLowerCase()) {
lowerNamespacePrefix = `${(symbol.containingNamespaces ?? []).join('.')}`.toLowerCase();
}
if (lowerNamespacePrefix) {
namespacedName = `${lowerNamespacePrefix}.${unnamespacedNameLower}`;
namespacedPotentialTypeKey = `${lowerNamespacePrefix}.${lowerFirst}`;
}
keysArray.push({
potentialTypeKey: lowerFirst, // first entry in type chain (useful for enum types, typecasts, etc.)
key: unnamespacedNameLower, //full name used in code (useful for namespaced symbols)
namespacedKey: namespacedName, // full name including namespaces (useful for relative symbols in a namespace)
namespacedPotentialTypeKey: namespacedPotentialTypeKey //first entry in chain, prefixed with current namespace
});
}
return keysArray;
}
resolutionsMap = new Map<UnresolvedSymbol, Set<{ scope: Scope; sourceFile: BscFile; providedSymbol: BscSymbol }>>();
providedTreeMap = new Map<string, { duplicatesMap: Map<string, Set<FileSymbolPair>>; providedTree: ProvidedNode }>();
private componentsMap = new Map<string, FileSymbolPair>();
getRequiredMap(scope: Scope) {
const map = new Map<SymbolLookupKeys, UnresolvedSymbol>();
scope.enumerateBrsFiles((file) => {
for (const symbol of file.requiredSymbols) {
const symbolKeysArray = this.symbolMapKeys(symbol);
for (const symbolKeys of symbolKeysArray) {
map.set(symbolKeys, symbol);
}
}
});
return map;
}
getProvidedTree(scope: Scope) {
if (this.providedTreeMap.has(scope.name)) {
return this.providedTreeMap.get(scope.name);
}
const providedTree = new ProvidedNode('', this.componentsMap);
const duplicatesMap = new Map<string, Set<FileSymbolPair>>();
const referenceTypesMap = new Map<{ symbolName: string; file: BscFile; symbolObj: ProvidedSymbol }, Array<{ name: string; namespacedName?: string }>>();
const addSymbolWithDuplicates = (symbolName: string, file: BscFile, symbolObj: ProvidedSymbol) => {
// eslint-disable-next-line no-bitwise
const globalSymbol = this.program.globalScope.symbolTable.getSymbol(symbolName, SymbolTypeFlag.typetime | SymbolTypeFlag.runtime);
const symbolIsNamespace = providedTree.getNamespace(symbolName);
const isDupe = providedTree.addSymbol(symbolName, { file: file, symbol: symbolObj.symbol });
if (symbolIsNamespace || globalSymbol || isDupe || symbolObj.duplicates.length > 0) {
let dupesSet = duplicatesMap.get(symbolName);
if (!dupesSet) {
dupesSet = new Set<{ file: BrsFile; symbol: BscSymbol }>();
duplicatesMap.set(symbolName, dupesSet);
const existing = providedTree.getSymbol(symbolName);
if (existing) {
dupesSet.add(existing);
}
}
if (!dupesSet.has({ file: file, symbol: symbolObj.symbol })) {
dupesSet.add({ file: file, symbol: symbolObj.symbol });
}
if (symbolIsNamespace) {
const namespaceContainer = scope.getNamespace(symbolName);
const nsNode = namespaceContainer?.namespaceStatements?.[0];
if (nsNode) {
const nsFile = namespaceContainer.file;
const nsType = nsNode.getType({ flags: SymbolTypeFlag.typetime });
let nsSymbol: BscSymbol = {
name: nsNode.getName(ParseMode.BrighterScript),
type: nsType,
data: { definingNode: nsNode },
flags: SymbolTypeFlag.typetime
};
if (nsSymbol && !dupesSet.has({ file: nsFile, symbol: nsSymbol })) {
dupesSet.add({ file: nsFile, symbol: nsSymbol });
}
}
}
for (const providedDupeSymbol of symbolObj.duplicates) {
if (!dupesSet.has({ file: file, symbol: providedDupeSymbol })) {
dupesSet.add({ file: file, symbol: providedDupeSymbol });
}
}
if (globalSymbol) {
dupesSet.add({ file: globalFile, symbol: globalSymbol[0] });
}
}
};
scope.enumerateBrsFiles((file) => {
for (const [_, nameMap] of file.providedSymbols.symbolMap.entries()) {
for (const [symbolName, symbolObj] of nameMap.entries()) {
if (isNamespaceType(symbolObj.symbol.type)) {
continue;
}
addSymbolWithDuplicates(symbolName, file, symbolObj);
}
}
// find all "provided symbols" that are reference types
for (const [_, nameMap] of file.providedSymbols.referenceSymbolMap.entries()) {
for (const [symbolName, symbolObj] of nameMap.entries()) {
const symbolType = symbolObj.symbol.type;
const namespaceLower = symbolObj.symbol.data?.definingNode?.findAncestor<NamespaceStatement>(isNamespaceStatement)?.getName(ParseMode.BrighterScript).toLowerCase();
const allNames = getAllRequiredSymbolNames(symbolType, namespaceLower);
referenceTypesMap.set({ symbolName: symbolName, file: file, symbolObj: symbolObj }, allNames);
}
}
});
// check provided reference types to see if they exist yet!
while (referenceTypesMap.size > 0) {
let addedSymbol = false;
for (const [refTypeDetails, neededNames] of referenceTypesMap.entries()) {
let foundNames = 0;
for (const neededName of neededNames) {
// check if name exists or namespaced version exists
if (providedTree.getSymbol(neededName.name) ?? providedTree.getSymbol(neededName.namespacedName)) {
foundNames++;
}
}
if (neededNames.length === foundNames) {
//found all that were needed
addSymbolWithDuplicates(refTypeDetails.symbolName, refTypeDetails.file, refTypeDetails.symbolObj);
referenceTypesMap.delete(refTypeDetails);
addedSymbol = true;
}
}
if (!addedSymbol) {
break;
}
}
const result = { duplicatesMap: duplicatesMap, providedTree: providedTree };
this.providedTreeMap.set(scope.name, result);
return result;
}
getIssuesForScope(scope: Scope) {
const requiredMap = this.getRequiredMap(scope);
const { providedTree, duplicatesMap } = this.getProvidedTree(scope);
const missingSymbols = new Set<UnresolvedSymbol>();
for (const [symbolKeys, unresolvedSymbol] of requiredMap.entries()) {
// check global scope for components
if (unresolvedSymbol.typeChain.length === 1 && this.program.globalScope.symbolTable.getSymbol(unresolvedSymbol.typeChain[0].name, unresolvedSymbol.flags)) {
//symbol is available in global scope. ignore it
continue;
}
let foundSymbol = providedTree.getSymbolByKey(symbolKeys);
if (foundSymbol) {
if (!unresolvedSymbol.typeChain[0].data?.isInstance) {
let resolvedListForSymbol = this.resolutionsMap.get(unresolvedSymbol);
if (!resolvedListForSymbol) {
resolvedListForSymbol = new Set<{ scope: Scope; sourceFile: BrsFile; providedSymbol: BscSymbol }>();
this.resolutionsMap.set(unresolvedSymbol, resolvedListForSymbol);
}
resolvedListForSymbol.add({
scope: scope,
sourceFile: foundSymbol.file,
providedSymbol: foundSymbol.symbol
});
}
} else {
let foundNamespace = providedTree.getNamespace(symbolKeys.key);
if (foundNamespace) {
// this symbol turned out to be a namespace. This is allowed for alias statements
// TODO: add check to make sure this usage is from an alias statement
} else {
// did not find symbol!
const missing = { ...unresolvedSymbol };
let namespaceNode = providedTree;
let currentKnownType;
for (const chainEntry of missing.typeChain) {
if (!chainEntry.isResolved) {
// for each unresolved part of a chain, see if we can resolve it with stuff from the provided tree
// and if so, mark it as resolved
const lookupName = (chainEntry.type as ReferenceType)?.fullName ?? chainEntry.name;
if (!currentKnownType) {
namespaceNode = namespaceNode?.getNamespaceByNameParts([chainEntry.name]);
}
if (namespaceNode) {
chainEntry.isResolved = true;
} else {
if (currentKnownType) {
currentKnownType = currentKnownType.getMemberType(chainEntry.name, { flags: SymbolTypeFlag.runtime });
} else {
currentKnownType = providedTree.getSymbol(lookupName.toLowerCase())?.symbol?.type;
}
if (currentKnownType?.isResolvable()) {
chainEntry.isResolved = true;
} else {
break;
}
}
}
}
missingSymbols.add(unresolvedSymbol);
}
}
}
return { missingSymbols: missingSymbols, duplicatesMap: duplicatesMap };
}
clearResolutionsForFile(file: BrsFile) {
for (const symbol of this.resolutionsMap.keys()) {
if (symbol.file === file) {
this.resolutionsMap.delete(symbol);
}
}
}
clearResolutionsForScopes(scopes: Scope[]) {
const lowerScopeNames = new Set(scopes.map(scope => scope.name.toLowerCase()));
for (const [symbol, resolutionInfos] of this.resolutionsMap.entries()) {
for (const info of resolutionInfos.values()) {
if (lowerScopeNames.has(info.scope.name.toLowerCase())) {
resolutionInfos.delete(info);
}
}
if (resolutionInfos.size === 0) {
this.resolutionsMap.delete(symbol);
}
}
}
getFilesRequiringChangedSymbol(scopes: Scope[], changedSymbols: Map<SymbolTypeFlag, Set<string>>) {
const filesThatNeedRevalidation = new Set<BscFile>();
const filesThatDoNotNeedRevalidation = new Set<BscFile>();
for (const scope of scopes) {
scope.enumerateBrsFiles((file) => {
if (filesThatNeedRevalidation.has(file) || filesThatDoNotNeedRevalidation.has(file)) {
return;
}
if (util.hasAnyRequiredSymbolChanged(file.requiredSymbols, changedSymbols)) {
filesThatNeedRevalidation.add(file);
return;
}
filesThatDoNotNeedRevalidation.add(file);
});
}
return filesThatNeedRevalidation;
}
getScopesRequiringChangedSymbol(scopes: Scope[], changedSymbols: Map<SymbolTypeFlag, Set<string>>) {
const scopesThatNeedRevalidation = new Set<Scope>();
const filesAlreadyChecked = new Set<BrsFile>();
for (const scope of scopes) {
scope.enumerateBrsFiles((file) => {
if (filesAlreadyChecked.has(file) || scopesThatNeedRevalidation.has(scope)) {
return;
}
filesAlreadyChecked.add(file);
if (util.hasAnyRequiredSymbolChanged(file.requiredSymbols, changedSymbols)) {
scopesThatNeedRevalidation.add(scope);
}
});
}
return scopesThatNeedRevalidation;
}
buildComponentsMap() {
this.componentsMap.clear();
// Add custom components
for (let componentName of this.program.getSortedComponentNames()) {
const typeName = 'rosgnode' + componentName;
const component = this.program.getComponent(componentName);
const componentSymbol = this.program.globalScope.symbolTable.getSymbol(typeName, SymbolTypeFlag.typetime)?.[0];
if (componentSymbol && component) {
this.componentsMap.set(typeName, { file: component.file, symbol: componentSymbol });
}
}
}
addDiagnosticsForScopes(scopes: Scope[]) { //, changedFiles: BrsFile[]) {
const addDuplicateSymbolDiagnostics = true;
const missingSymbolInScope = new Map<UnresolvedSymbol, Set<Scope>>();
this.providedTreeMap.clear();
this.clearResolutionsForScopes(scopes);
// Check scope for duplicates and missing symbols
for (const scope of scopes) {
this.program.diagnostics.clearByFilter({
scope: scope,
tag: CrossScopeValidatorDiagnosticTag
});
const { missingSymbols, duplicatesMap } = this.getIssuesForScope(scope);
if (addDuplicateSymbolDiagnostics) {
for (const [_flag, dupeSet] of duplicatesMap.entries()) {
if (dupeSet.size > 1) {
const dupesArray = [...dupeSet.values()];
for (let i = 0; i < dupesArray.length; i++) {
const dupe = dupesArray[i];
const dupeNode = dupe?.symbol?.data?.definingNode;
if (!dupeNode) {
continue;
}
let thisName = dupe.symbol?.name;
const wrappingNameSpace = dupeNode?.findAncestor<NamespaceStatement>(isNamespaceStatement);
if (wrappingNameSpace) {
thisName = `${wrappingNameSpace.getName(ParseMode.BrighterScript)}.` + thisName;
}
const thisNodeKindName = util.getAstNodeFriendlyName(dupeNode) ?? 'Item';
for (let j = 0; j < dupesArray.length; j++) {
if (i === j) {
continue;
}
const otherDupe = dupesArray[j];
if (!otherDupe || dupe.symbol === otherDupe.symbol) {
continue;
}
const otherDupeNode = otherDupe.symbol.data?.definingNode;
const otherIsGlobal = otherDupe.file.srcPath === 'global';
if (isFunctionStatement(dupeNode) && isFunctionStatement(otherDupeNode)) {
// duplicate functions are handled in ScopeValidator
continue;
}
if (otherIsGlobal &&
(isInterfaceStatement(dupeNode) ||
isEnumStatement(dupeNode) ||
isConstStatement(dupeNode))) {
// these are allowed to shadow global functions
continue;
}
let thatName = otherDupe.symbol?.name;
if (otherDupeNode) {
const otherWrappingNameSpace = otherDupeNode?.findAncestor<NamespaceStatement>(isNamespaceStatement);
if (otherWrappingNameSpace) {
thatName = `${otherWrappingNameSpace.getName(ParseMode.BrighterScript)}.` + thatName;
}
}
type AstNodeWithName = VariableExpression | DottedGetExpression | EnumStatement | ClassStatement | ConstStatement | EnumMemberStatement | InterfaceStatement;
const thatNodeKindName = otherIsGlobal ? 'Global Function' : util.getAstNodeFriendlyName(otherDupeNode) ?? 'Item';
let thisNameRange = (dupeNode as AstNodeWithName)?.tokens?.name?.location?.range ?? dupeNode.location?.range;
let thatNameRange = (otherDupeNode as AstNodeWithName)?.tokens?.name?.location?.range ?? otherDupeNode?.location?.range;
const relatedInformation = thatNameRange ? [{
message: `${thatNodeKindName} declared here`,
location: util.createLocationFromFileRange(otherDupe.file, thatNameRange)
}] : undefined;
this.program.diagnostics.register({
...DiagnosticMessages.nameCollision(thisNodeKindName, thatNodeKindName, thatName),
location: util.createLocationFromFileRange(dupe.file, thisNameRange),
relatedInformation: relatedInformation
}, {
scope: scope,
tags: [CrossScopeValidatorDiagnosticTag]
});
}
}
}
}
}
// build map of the symbols and scopes where the symbols are missing per file
for (const missingSymbol of missingSymbols) {
let scopesWithMissingSymbol = missingSymbolInScope.get(missingSymbol);
if (!scopesWithMissingSymbol) {
scopesWithMissingSymbol = new Set<Scope>();
missingSymbolInScope.set(missingSymbol, scopesWithMissingSymbol);
}
scopesWithMissingSymbol.add(scope);
}
}
// If symbols are missing in SOME scopes, add diagnostic
for (const [symbol, scopeList] of missingSymbolInScope.entries()) {
const typeChainResult = util.processTypeChain(symbol.typeChain);
for (const scope of scopeList) {
this.program.diagnostics.register({
...this.getCannotFindDiagnostic(scope, symbol, typeChainResult),
location: typeChainResult.location
}, {
scope: scope,
tags: [CrossScopeValidatorDiagnosticTag]
});
}
}
for (const resolution of this.getIncompatibleSymbolResolutions()) {
const symbol = resolution.symbol;
const incompatibleScopes = resolution.incompatibleScopes;
if (incompatibleScopes.size > 1) {
const typeChainResult = util.processTypeChain(symbol.typeChain);
const scopeList = [...incompatibleScopes.values()].map(s => s.name);
this.program.diagnostics.register({
...DiagnosticMessages.incompatibleSymbolDefinition(typeChainResult.fullChainName, { scopes: scopeList }),
location: typeChainResult.location
}, {
tags: [CrossScopeValidatorDiagnosticTag]
});
}
}
}
getIncompatibleSymbolResolutions() {
const incompatibleResolutions = new Array<{ symbol: UnresolvedSymbol; incompatibleScopes: Set<Scope> }>();
// check all resolutions and check if there are resolutions that are not compatible across scopes
for (const [symbol, resolutionDetails] of this.resolutionsMap.entries()) {
if (resolutionDetails.size < 2) {
// there is only one resolution... no worries
continue;
}
const resolutionsList = [...resolutionDetails];
const prime = resolutionsList[0];
let incompatibleScopes = new Set<Scope>();
let addedPrime = false;
for (let i = 1; i < resolutionsList.length; i++) {
let providedSymbolType = prime.providedSymbol.type;
const symbolInThisScope = resolutionsList[i].providedSymbol;
//get more general type
if (providedSymbolType.isEqual(symbolInThisScope.type)) {
//type in this scope is the same as one we're already checking
} else if (providedSymbolType.isTypeCompatible(symbolInThisScope.type)) {
//type in this scope is compatible with one we're storing. use most generic
providedSymbolType = symbolInThisScope.type;
} else if (symbolInThisScope.type.isTypeCompatible(providedSymbolType)) {
// type we're storing is more generic that the type in this scope
} else {
// type in this scope is not compatible with other types for this symbol
if (!addedPrime) {
incompatibleScopes.add(prime.scope);
addedPrime = true;
}
incompatibleScopes.add(resolutionsList[i].scope);
}
}
if (incompatibleScopes.size > 1) {
incompatibleResolutions.push({
symbol: symbol,
incompatibleScopes: incompatibleScopes
});
}
}
return incompatibleResolutions;
}
private getCannotFindDiagnostic(scope: Scope, unresolvedSymbol: UnresolvedSymbol, typeChainResult: TypeChainProcessResult) {
const parentDescriptor = this.getParentTypeDescriptor(this.getProvidedTree(scope)?.providedTree, typeChainResult);
const symbolType = typeChainResult.astNode?.getType({ flags: unresolvedSymbol.flags });
if (isReferenceType(symbolType)) {
const circularReferenceInfo = symbolType.getCircularReferenceInfo();
if (circularReferenceInfo.isCircularReference) {
let diagnosticDetail = util.getCircularReferenceDiagnosticDetail(circularReferenceInfo, typeChainResult.fullNameOfItem);
return DiagnosticMessages.circularReferenceDetected(diagnosticDetail);
}
}
if (isCallExpression(typeChainResult.astNode?.parent) && typeChainResult.astNode?.parent.callee === typeChainResult.astNode) {
return DiagnosticMessages.cannotFindFunction(typeChainResult.itemName, typeChainResult.fullNameOfItem, typeChainResult.itemParentTypeName, parentDescriptor);
}
return DiagnosticMessages.cannotFindName(typeChainResult.itemName, typeChainResult.fullNameOfItem, typeChainResult.itemParentTypeName, parentDescriptor);
}
private getParentTypeDescriptor(provided: ProvidedNode, typeChainResult: TypeChainProcessResult) {
if (typeChainResult.itemParentTypeKind === BscTypeKind.NamespaceType || provided?.getNamespace(typeChainResult.itemParentTypeName)) {
return 'namespace';
}
return 'type';
}
}