-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathBrsFile.ts
More file actions
1459 lines (1306 loc) · 57.8 KB
/
Copy pathBrsFile.ts
File metadata and controls
1459 lines (1306 loc) · 57.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
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { CodeWithSourceMap } from 'source-map';
import { SourceNode } from 'source-map';
import type { CompletionItem, Position, Location, Diagnostic } from 'vscode-languageserver';
import { CancellationTokenSource } from 'vscode-languageserver';
import { CompletionItemKind, TextEdit } from 'vscode-languageserver';
import chalk from 'chalk';
import * as path from 'path';
import { Scope } from '../Scope';
import { DiagnosticCodeMap, diagnosticCodes, DiagnosticMessages } from '../DiagnosticMessages';
import { FunctionScope } from '../FunctionScope';
import type { Callable, CallableArg, CallableParam, CommentFlag, FunctionCall, BsDiagnostic, FileReference, FileLink, BscFile } from '../interfaces';
import type { Token } from '../lexer/Token';
import { Lexer } from '../lexer/Lexer';
import { TokenKind, AllowedLocalIdentifiers, Keywords } from '../lexer/TokenKind';
import { Parser, ParseMode } from '../parser/Parser';
import type { FunctionExpression, VariableExpression } from '../parser/Expression';
import type { ClassStatement, NamespaceStatement, AssignmentStatement, MethodStatement, FieldStatement } from '../parser/Statement';
import type { Program } from '../Program';
import { DynamicType } from '../types/DynamicType';
import { FunctionType } from '../types/FunctionType';
import { VoidType } from '../types/VoidType';
import { standardizePath as s, util } from '../util';
import { BrsTranspileState } from '../parser/BrsTranspileState';
import { Preprocessor } from '../preprocessor/Preprocessor';
import { serializeError } from 'serialize-error';
import { isCallExpression, isMethodStatement, isClassStatement, isDottedGetExpression, isFunctionExpression, isFunctionStatement, isFunctionType, isLiteralExpression, isNamespaceStatement, isStringType, isVariableExpression, isImportStatement, isFieldStatement, isEnumStatement, isConstStatement } from '../astUtils/reflection';
import type { BscType } from '../types/BscType';
import { createVisitor, WalkMode } from '../astUtils/visitors';
import type { DependencyGraph } from '../DependencyGraph';
import { CommentFlagProcessor } from '../CommentFlagProcessor';
import type { AstNode, Expression } from '../parser/AstNode';
import { DefinitionProvider } from '../bscPlugin/definition/DefinitionProvider';
import { ReferencesProvider } from '../bscPlugin/references/ReferencesProvider';
import { DocumentSymbolProcessor } from '../bscPlugin/symbols/DocumentSymbolProcessor';
import { WorkspaceSymbolProcessor } from '../bscPlugin/symbols/WorkspaceSymbolProcessor';
/**
* Holds all details about this file within the scope of the whole program
*/
export class BrsFile {
constructor(
public srcPath: string,
/**
* The full pkg path to this file
*/
public pkgPath: string,
public program: Program
) {
this.srcPath = s`${this.srcPath}`;
this.pkgPath = s`${this.pkgPath}`;
this.dependencyGraphKey = this.pkgPath.toLowerCase();
this.extension = util.getExtension(this.srcPath);
//all BrighterScript files need to be transpiled
if (this.extension?.endsWith('.bs') || program?.options?.allowBrighterScriptInBrightScript) {
this.needsTranspiled = true;
this.parseMode = ParseMode.BrighterScript;
}
this.isTypedef = this.extension === '.d.bs';
if (!this.isTypedef) {
this.typedefKey = util.getTypedefPath(this.srcPath);
}
//global file doesn't have a program, so only resolve typedef info if we have a program
if (this.program) {
this.resolveTypedef();
}
}
/**
* The absolute path to the source location for this file
* @deprecated use `srcPath` instead
*/
public get pathAbsolute() {
return this.srcPath;
}
public set pathAbsolute(value) {
this.srcPath = value;
}
/**
* Will this file result in only comment or whitespace output? If so, it can be excluded from the output if that bsconfig setting is enabled.
*/
public get canBePruned() {
let canPrune = true;
this.ast.walk(createVisitor({
FunctionStatement: () => {
canPrune = false;
},
ClassStatement: () => {
canPrune = false;
}
}), {
walkMode: WalkMode.visitStatements
});
return canPrune;
}
/**
* The parseMode used for the parser for this file
*/
public parseMode = ParseMode.BrightScript;
/**
* The key used to identify this file in the dependency graph
*/
public dependencyGraphKey: string;
/**
* Indicates whether this file needs to be validated.
* Files are only ever validated a single time
*/
public isValidated = false;
/**
* The all-lowercase extension for this file (including the leading dot)
*/
public extension: string;
/**
* A collection of diagnostics related to this file
*/
public diagnostics = [] as BsDiagnostic[];
public getDiagnostics() {
return [...this.diagnostics];
}
public addDiagnostic(diagnostic: Diagnostic & { file?: BscFile }) {
this.addDiagnostics([diagnostic as BsDiagnostic]);
}
public addDiagnostics(diagnostics: BsDiagnostic[]) {
for (const diagnostic of diagnostics) {
if (!diagnostic.file) {
diagnostic.file = this;
}
this.diagnostics.push(diagnostic as any);
}
}
public commentFlags = [] as CommentFlag[];
public callables = [] as Callable[];
public functionCalls = [] as FunctionCall[];
private _functionScopes: FunctionScope[];
public get functionScopes(): FunctionScope[] {
if (!this._functionScopes) {
this.createFunctionScopes();
}
return this._functionScopes;
}
private get cache() {
// eslint-disable-next-line @typescript-eslint/dot-notation
return this._parser?.references['cache'];
}
/**
* files referenced by import statements
*/
public get ownScriptImports() {
const result = this.cache?.getOrAdd('BrsFile_ownScriptImports', () => {
const result = [] as FileReference[];
for (const statement of this.parser?.references?.importStatements ?? []) {
//register import statements
if (isImportStatement(statement) && statement.filePathToken) {
result.push({
filePathRange: statement.filePathToken.range,
pkgPath: util.getPkgPathFromTarget(this.pkgPath, statement.filePath),
sourceFile: this,
text: statement.filePathToken?.text
});
}
}
return result;
}) ?? [];
return result;
}
/**
* Does this file need to be transpiled?
*/
public needsTranspiled = false;
/**
* The AST for this file
*/
public get ast() {
return this.parser.ast;
}
/**
* Get the token at the specified position
*/
public getTokenAt(position: Position) {
for (let token of this.parser.tokens) {
if (util.rangeContains(token.range, position)) {
return token;
}
}
}
/**
* Walk the AST and find the expression that this token is most specifically contained within
*/
public getClosestExpression(position: Position) {
if (typeof position?.line !== 'number') {
return undefined;
}
const handle = new CancellationTokenSource();
let containingNode: AstNode;
this.ast.walk((node) => {
const latestContainer = containingNode;
//bsc walks depth-first
if (util.rangeContains(node.range, position)) {
containingNode = node;
}
//we had a match before, and don't now. this means we've finished walking down the whole way, and found our match
if (latestContainer && !containingNode) {
containingNode = latestContainer;
handle.cancel();
}
}, {
walkMode: WalkMode.visitAllRecursive,
cancel: handle.token
});
return containingNode;
}
public get parser() {
if (!this._parser) {
//remove the typedef file (if it exists)
this.hasTypedef = false;
this.typedefFile = undefined;
//parse the file (it should parse fully since there's no linked typedef
this.parse(this.fileContents);
//re-link the typedef (if it exists...which it should)
this.resolveTypedef();
}
return this._parser;
}
private _parser: Parser;
public fileContents: string;
/**
* If this is a typedef file
*/
public isTypedef: boolean;
/**
* The key to find the typedef file in the program's files map.
* A falsey value means this file is ineligable for a typedef
*/
public typedefKey?: string;
/**
* If the file was given type definitions during parse
*/
public hasTypedef;
/**
* A reference to the typedef file (if one exists)
*/
public typedefFile?: BrsFile;
/**
* An unsubscribe function for the dependencyGraph subscription
*/
private unsubscribeFromDependencyGraph: () => void;
/**
* Find and set the typedef variables (if a matching typedef file exists)
*/
private resolveTypedef() {
this.typedefFile = this.program.getFile<BrsFile>(this.typedefKey);
this.hasTypedef = !!this.typedefFile;
}
/**
* Attach the file to the dependency graph so it can monitor changes.
* Also notify the dependency graph of our current dependencies so other dependents can be notified.
*/
public attachDependencyGraph(dependencyGraph: DependencyGraph) {
this.unsubscribeFromDependencyGraph?.();
//event that fires anytime a dependency changes
this.unsubscribeFromDependencyGraph = dependencyGraph.onchange(this.dependencyGraphKey, () => {
this.resolveTypedef();
});
const dependencies = this.ownScriptImports.filter(x => !!x.pkgPath).map(x => x.pkgPath.toLowerCase());
//if this is a .brs file, watch for typedef changes
if (this.extension === '.brs') {
dependencies.push(
util.getTypedefPath(this.pkgPath)
);
}
dependencyGraph.addOrReplace(this.dependencyGraphKey, dependencies);
}
/**
* Calculate the AST for this file
* @param fileContents the raw source code to parse
*/
public parse(fileContents: string) {
try {
this.fileContents = fileContents;
this.diagnostics = [];
//if we have a typedef file, skip parsing this file
if (this.hasTypedef) {
//skip validation since the typedef is shadowing this file
this.isValidated = true;
return;
}
//tokenize the input file
let lexer = this.program.logger.time('debug', ['lexer.lex', chalk.green(this.srcPath)], () => {
return Lexer.scan(fileContents, {
includeWhitespace: false
});
});
this.getCommentFlags(lexer.tokens);
let preprocessor = new Preprocessor();
//remove all code inside false-resolved conditional compilation statements.
//TODO preprocessor should go away in favor of the AST handling this internally (because it affects transpile)
//currently the preprocessor throws exceptions on syntax errors...so we need to catch it
try {
this.program.logger.time('debug', ['preprocessor.process', chalk.green(this.srcPath)], () => {
preprocessor.process(lexer.tokens, this.program.getManifest());
});
} catch (error: any) {
//if the thrown error is DIFFERENT than any errors from the preprocessor, add that error to the list as well
if (this.diagnostics.find((x) => x === error) === undefined) {
this.diagnostics.push(error);
}
}
//if the preprocessor generated tokens, use them.
let tokens = preprocessor.processedTokens.length > 0 ? preprocessor.processedTokens : lexer.tokens;
this.program.logger.time('debug', ['parser.parse', chalk.green(this.srcPath)], () => {
this._parser = Parser.parse(tokens, {
mode: this.parseMode,
logger: this.program.logger
});
});
//absorb all lexing/preprocessing/parsing diagnostics
this.diagnostics.push(
...lexer.diagnostics as BsDiagnostic[],
...preprocessor.diagnostics as BsDiagnostic[],
...this._parser.diagnostics as BsDiagnostic[]
);
//extract all callables from this file
this.findCallables();
//find all places where a sub/function is being called
this.findFunctionCalls();
//attach this file to every diagnostic
for (let diagnostic of this.diagnostics) {
diagnostic.file = this;
}
} catch (e) {
this._parser = new Parser();
this.diagnostics.push({
file: this,
range: util.createRange(0, 0, 0, Number.MAX_VALUE),
...DiagnosticMessages.genericParserMessage('Critical error parsing file: ' + JSON.stringify(serializeError(e)))
});
}
}
/**
* @deprecated logic has moved into BrsFileValidator, this is now an empty function
*/
public validate() {
}
/**
* Find a class. This scans all scopes for this file, and returns the first matching class that is found.
* Returns undefined if not found.
* @param className - The class name, including the namespace of the class if possible
* @param containingNamespace - The namespace used to resolve relative class names. (i.e. the namespace around the current statement trying to find a class)
* @returns the first class in the first scope found, or undefined if not found
*/
public getClassFileLink(className: string, containingNamespace?: string): FileLink<ClassStatement> {
const lowerClassName = className.toLowerCase();
const lowerContainingNamespace = containingNamespace?.toLowerCase();
const scopes = this.program.getScopesForFile(this);
//find the first class in the first scope that has it
for (let scope of scopes) {
const cls = scope.getClassFileLink(lowerClassName, lowerContainingNamespace);
if (cls) {
return cls;
}
}
}
public findPropertyNameCompletions(): CompletionItem[] {
//Build completion items from all the "properties" found in the file
const { propertyHints } = this.parser.references;
const results = [] as CompletionItem[];
for (const key of Object.keys(propertyHints)) {
results.push({
label: propertyHints[key],
kind: CompletionItemKind.Text
});
}
return results;
}
private _propertyNameCompletions: CompletionItem[];
public get propertyNameCompletions(): CompletionItem[] {
if (!this._propertyNameCompletions) {
this._propertyNameCompletions = this.findPropertyNameCompletions();
}
return this._propertyNameCompletions;
}
/**
* Find all comment flags in the source code. These enable or disable diagnostic messages.
* @param tokens - an array of tokens of which to find `TokenKind.Comment` from
*/
public getCommentFlags(tokens: Token[]) {
const processor = new CommentFlagProcessor(this, ['rem', `'`], diagnosticCodes, [DiagnosticCodeMap.unknownDiagnosticCode]);
this.commentFlags = [];
for (let token of tokens) {
if (token.kind === TokenKind.Comment) {
processor.tryAdd(token.text, token.range);
}
}
this.commentFlags.push(...processor.commentFlags);
this.diagnostics.push(...processor.diagnostics);
}
public scopesByFunc = new Map<FunctionExpression, FunctionScope>();
/**
* Create a scope for every function in this file
*/
private createFunctionScopes() {
//find every function
let functions = this.parser.references.functionExpressions;
//create a functionScope for every function
this._functionScopes = [];
for (let func of functions) {
let scope = new FunctionScope(func);
//find parent function, and add this scope to it if found
{
let parentScope = this.scopesByFunc.get(func.parentFunction);
//add this child scope to its parent
if (parentScope) {
parentScope.childrenScopes.push(scope);
}
//store the parent scope for this scope
scope.parentScope = parentScope;
}
//add every parameter
for (let param of func.parameters) {
scope.variableDeclarations.push({
nameRange: param.name.range,
lineIndex: param.name.range?.start.line,
name: param.name.text,
type: param.type
});
}
//add all of ForEachStatement loop varibales
func.body?.walk(createVisitor({
ForEachStatement: (stmt) => {
scope.variableDeclarations.push({
nameRange: stmt.item.range,
lineIndex: stmt.item.range?.start.line,
name: stmt.item.text,
type: new DynamicType()
});
},
LabelStatement: (stmt) => {
const { identifier } = stmt.tokens;
scope.labelStatements.push({
nameRange: identifier.range,
lineIndex: identifier.range?.start.line,
name: identifier.text
});
}
}), {
walkMode: WalkMode.visitStatements
});
this.scopesByFunc.set(func, scope);
//find every statement in the scope
this._functionScopes.push(scope);
}
//find every variable assignment in the whole file
let assignmentStatements = this.parser.references.assignmentStatements;
for (let statement of assignmentStatements) {
//find this statement's function scope
let scope = this.scopesByFunc.get(statement.containingFunction);
//skip variable declarations that are outside of any scope
if (scope) {
scope.variableDeclarations.push({
nameRange: statement.name.range,
lineIndex: statement.name.range?.start.line,
name: statement.name.text,
type: this.getBscTypeFromAssignment(statement, scope)
});
}
}
}
private getBscTypeFromAssignment(assignment: AssignmentStatement, scope: FunctionScope): BscType {
try {
//function
if (isFunctionExpression(assignment.value)) {
let functionType = new FunctionType(assignment.value.returnType);
functionType.isSub = assignment.value.functionType.text === 'sub';
if (functionType.isSub) {
functionType.returnType = new VoidType();
}
functionType.setName(assignment.name.text);
for (let param of assignment.value.parameters) {
let isOptional = !!param.defaultValue;
//TODO compute optional parameters
functionType.addParameter(param.name.text, param.type, isOptional);
}
return functionType;
//literal
} else if (isLiteralExpression(assignment.value)) {
return assignment.value.type;
//function call
} else if (isCallExpression(assignment.value)) {
let calleeName = (assignment.value.callee as any)?.name?.text;
if (calleeName) {
let func = this.getCallableByName(calleeName);
if (func) {
return func.type.returnType;
}
}
} else if (isVariableExpression(assignment.value)) {
let variableName = assignment.value?.name?.text;
let variable = scope.getVariableByName(variableName);
return variable.type;
}
} catch (e) {
//do nothing. Just return dynamic
}
//fallback to dynamic
return new DynamicType();
}
private getCallableByName(name: string) {
name = name ? name.toLowerCase() : undefined;
if (!name) {
return;
}
for (let func of this.callables) {
if (func.name.toLowerCase() === name) {
return func;
}
}
}
private findCallables() {
for (let statement of this.parser.references.functionStatements ?? []) {
let functionType = new FunctionType(statement.func.returnType);
functionType.setName(statement.name.text);
functionType.isSub = statement.func.functionType.text.toLowerCase() === 'sub';
if (functionType.isSub) {
functionType.returnType = new VoidType();
}
//extract the parameters
let params = [] as CallableParam[];
for (let param of statement.func.parameters) {
let callableParam = {
name: param.name.text,
type: param.type,
isOptional: !!param.defaultValue,
isRestArgument: false
};
params.push(callableParam);
let isOptional = !!param.defaultValue;
functionType.addParameter(callableParam.name, callableParam.type, isOptional);
}
// Extract documentation from comment tokens
const documentation = util.getTokenDocumentation(this.parser.tokens, statement.func.functionType);
this.callables.push({
isSub: statement.func.functionType.text.toLowerCase() === 'sub',
name: statement.name.text,
nameRange: statement.name.range,
file: this,
params: params,
range: statement.func.range,
type: functionType,
getName: statement.getName.bind(statement),
hasNamespace: !!statement.findAncestor<NamespaceStatement>(isNamespaceStatement),
functionStatement: statement,
shortDescription: documentation
});
}
}
private findFunctionCalls() {
this.functionCalls = [];
//for every function in the file
for (let func of this._parser.references.functionExpressions) {
//for all function calls in this function
for (let expression of func.callExpressions) {
if (
//filter out dotted function invocations (i.e. object.doSomething()) (not currently supported. TODO support it)
(expression.callee as any).obj ||
//filter out method calls on method calls for now (i.e. getSomething().getSomethingElse())
(expression.callee as any).callee ||
//filter out callees without a name (immediately-invoked function expressions)
!(expression.callee as any).name
) {
continue;
}
let functionName = (expression.callee as any).name.text;
//callee is the name of the function being called
let callee = expression.callee as VariableExpression;
let columnIndexBegin = callee.range.start.character;
let columnIndexEnd = callee.range.end.character;
let args = [] as CallableArg[];
//TODO convert if stmts to use instanceof instead
for (let arg of expression.args as any) {
//is a literal parameter value
if (isLiteralExpression(arg)) {
args.push({
range: arg.range,
type: arg.type,
text: arg.token.text,
expression: arg,
typeToken: undefined
});
//is variable being passed into argument
} else if (arg.name) {
args.push({
range: arg.range,
//TODO - look up the data type of the actual variable
type: new DynamicType(),
text: arg.name.text,
expression: arg,
typeToken: undefined
});
} else if (arg.value) {
let text = '';
/* istanbul ignore next: TODO figure out why value is undefined sometimes */
if (arg.value.value) {
text = arg.value.value.toString();
}
let callableArg = {
range: arg.range,
//TODO not sure what to do here
type: new DynamicType(), // util.valueKindToBrsType(arg.value.kind),
text: text,
expression: arg,
typeToken: undefined
};
//wrap the value in quotes because that's how it appears in the code
if (isStringType(callableArg.type)) {
callableArg.text = '"' + callableArg.text + '"';
}
args.push(callableArg);
} else {
args.push({
range: arg.range,
type: new DynamicType(),
//TODO get text from other types of args
text: '',
expression: arg,
typeToken: undefined
});
}
}
let functionCall: FunctionCall = {
range: expression.range,
functionScope: this.getFunctionScopeAtPosition(callee.range.start),
file: this,
name: functionName,
nameRange: util.createRange(callee.range.start.line, columnIndexBegin, callee.range.start.line, columnIndexEnd),
//TODO keep track of parameters
args: args
};
this.functionCalls.push(functionCall);
}
}
}
/**
* Find the function scope at the given position.
* @param position the position used to find the deepest scope that contains it
*/
public getFunctionScopeAtPosition(position: Position): FunctionScope {
return this.cache.getOrAdd(`functionScope-${position.line}:${position.character}`, () => {
return this._getFunctionScopeAtPosition(position, this.functionScopes);
});
}
public _getFunctionScopeAtPosition(position: Position, functionScopes?: FunctionScope[]): FunctionScope {
if (!functionScopes) {
functionScopes = this.functionScopes;
}
for (let scope of functionScopes) {
if (util.rangeContains(scope.range, position)) {
//see if any of that scope's children match the position also, and give them priority
let childScope = this._getFunctionScopeAtPosition(position, scope.childrenScopes);
if (childScope) {
return childScope;
} else {
return scope;
}
}
}
}
/**
* Find the NamespaceStatement enclosing the given position
*/
public getNamespaceStatementForPosition(position: Position): NamespaceStatement {
if (position) {
return this.cache.getOrAdd(`namespaceStatementForPosition-${position.line}:${position.character}`, () => {
for (const statement of this.parser.references.namespaceStatements) {
if (util.rangeContains(statement.range, position)) {
return statement;
}
}
});
}
}
/**
* Get completions available at the given cursor. This aggregates all values from this file and the current scope.
*/
public getCompletions(position: Position, scope?: Scope): CompletionItem[] {
let result = [] as CompletionItem[];
//a map of lower-case names of all added options
let names = {} as Record<string, boolean>;
//handle script import completions
let scriptImport = util.getScriptImportAtPosition(this.ownScriptImports, position);
if (scriptImport) {
return this.program.getScriptImportCompletions(this.pkgPath, scriptImport);
}
//if cursor is within a comment, disable completions
let currentToken = this.getTokenAt(position);
const tokenKind = currentToken?.kind;
if (tokenKind === TokenKind.Comment) {
return [];
} else if (tokenKind === TokenKind.StringLiteral || tokenKind === TokenKind.TemplateStringQuasi) {
const match = /^("?)(pkg|libpkg):/.exec(currentToken.text);
if (match) {
const [, openingQuote, fileProtocol] = match;
//include every absolute file path from this scope
for (const file of scope.getAllFiles()) {
const pkgPath = `${fileProtocol}:/${file.pkgPath.replace(/\\/g, '/')}`;
result.push({
label: pkgPath,
textEdit: TextEdit.replace(
util.createRange(
currentToken.range.start.line,
//+1 to step past the opening quote
currentToken.range.start.character + (openingQuote ? 1 : 0),
currentToken.range.end.line,
//-1 to exclude the closing quotemark (or the end character if there is no closing quotemark)
currentToken.range.end.character + (currentToken.text.endsWith('"') ? -1 : 0)
),
pkgPath
),
kind: CompletionItemKind.File
});
}
return result;
} else {
//do nothing. we don't want to show completions inside of strings...
return [];
}
}
const namespaceCompletions = this.getNamespaceCompletions(currentToken, this.parseMode, scope);
if (namespaceCompletions.length > 0) {
return [...namespaceCompletions];
}
const enumMemberCompletions = this.getEnumMemberStatementCompletions(currentToken, this.parseMode, scope);
if (enumMemberCompletions.length > 0) {
// no other completion is valid in this case
return enumMemberCompletions;
}
//determine if cursor is inside a function
let functionScope = this.getFunctionScopeAtPosition(position);
if (!functionScope) {
//we aren't in any function scope, so return the keyword completions and namespaces
if (this.getTokenBefore(currentToken, TokenKind.New)) {
// there's a new keyword, so only class types are viable here
return [...this.getGlobalClassStatementCompletions(currentToken, this.parseMode)];
} else {
return [
...KeywordCompletions,
...this.getGlobalClassStatementCompletions(currentToken, this.parseMode),
...namespaceCompletions,
...this.getNonNamespacedEnumStatementCompletions(currentToken, this.parseMode, scope)
];
}
}
const classNameCompletions = this.getGlobalClassStatementCompletions(currentToken, this.parseMode);
const newToken = this.getTokenBefore(currentToken, TokenKind.New);
if (newToken) {
//we are after a new keyword; so we can only be top-level namespaces or classes at this point
result.push(...classNameCompletions);
result.push(...namespaceCompletions);
return result;
}
if (this.tokenFollows(currentToken, TokenKind.Goto)) {
return this.getLabelCompletion(functionScope);
}
if (this.isPositionNextToTokenKind(position, TokenKind.Dot)) {
const selfClassMemberCompletions = this.getClassMemberCompletions(position, currentToken, functionScope, scope);
if (selfClassMemberCompletions.size > 0) {
return [...selfClassMemberCompletions.values()].filter((i) => i.label !== 'new');
}
if (!this.getClassFromMReference(position, currentToken, functionScope)) {
//and anything from any class in scope to a non m class
let classMemberCompletions = scope.getAllClassMemberCompletions();
result.push(...classMemberCompletions.values());
result.push(...scope.getPropertyNameCompletions().filter((i) => !classMemberCompletions.has(i.label)));
} else {
result.push(...scope.getPropertyNameCompletions());
}
} else {
result.push(
//include namespaces
...namespaceCompletions,
//include class names
...classNameCompletions,
//include enums
...this.getNonNamespacedEnumStatementCompletions(currentToken, this.parseMode, scope),
//include constants
...this.getNonNamespacedConstStatementCompletions(currentToken, this.parseMode, scope),
//include the global callables
...scope.getCallablesAsCompletions(this.parseMode)
);
//add `m` because that's always valid within a function
result.push({
label: 'm',
kind: CompletionItemKind.Variable
});
names.m = true;
result.push(...KeywordCompletions);
//include local variables
let variables = functionScope.variableDeclarations;
for (let variable of variables) {
//skip duplicate variable names
if (names[variable.name.toLowerCase()]) {
continue;
}
names[variable.name.toLowerCase()] = true;
result.push({
label: variable.name,
kind: isFunctionType(variable.type) ? CompletionItemKind.Function : CompletionItemKind.Variable
});
}
if (this.parseMode === ParseMode.BrighterScript) {
//include the first part of namespaces
let namespaces = scope.getAllNamespaceStatements();
for (let stmt of namespaces) {
let firstPart = stmt.nameExpression.getNameParts().shift();
//skip duplicate namespace names
if (names[firstPart.toLowerCase()]) {
continue;
}
names[firstPart.toLowerCase()] = true;
result.push({
label: firstPart,
kind: CompletionItemKind.Module
});
}
}
}
return result;
}
private getLabelCompletion(functionScope: FunctionScope) {
return functionScope.labelStatements.map(label => ({
label: label.name,
kind: CompletionItemKind.Reference
}));
}
private getClassMemberCompletions(position: Position, currentToken: Token, functionScope: FunctionScope, scope: Scope) {
let classStatement = this.getClassFromMReference(position, currentToken, functionScope);
let results = new Map<string, CompletionItem>();
if (classStatement) {
let classes = scope.getClassHierarchy(classStatement.item.getName(ParseMode.BrighterScript).toLowerCase());
for (let cs of classes) {
for (let member of [...cs?.item?.fields ?? [], ...cs?.item?.methods ?? []]) {
if (!results.has(member.name.text.toLowerCase())) {
results.set(member.name.text.toLowerCase(), {
label: member.name.text,
kind: isFieldStatement(member) ? CompletionItemKind.Field : CompletionItemKind.Function
});
}
}
}
}
return results;
}
public getClassFromMReference(position: Position, currentToken: Token, functionScope: FunctionScope): FileLink<ClassStatement> | undefined {
let previousToken = this.getPreviousToken(currentToken);
if (previousToken?.kind === TokenKind.Dot) {
previousToken = this.getPreviousToken(previousToken);
}
if (previousToken?.kind === TokenKind.Identifier && previousToken?.text.toLowerCase() === 'm' && isMethodStatement(functionScope.func.functionStatement)) {
return { item: this.parser.references.classStatements.find((cs) => util.rangeContains(cs.range, position)), file: this };
}
return undefined;
}
private getGlobalClassStatementCompletions(currentToken: Token, parseMode: ParseMode): CompletionItem[] {
if (parseMode === ParseMode.BrightScript) {
return [];
}
let results = new Map<string, CompletionItem>();
let completionName = this.getPartialVariableName(currentToken, [TokenKind.New])?.toLowerCase();
if (completionName?.includes('.')) {
return [];
}
let scopes = this.program.getScopesForFile(this);
for (let scope of scopes) {
let classMap = scope.getClassMap();
for (const key of [...classMap.keys()]) {
let cs = classMap.get(key).item;
if (!results.has(cs.name.text)) {
results.set(cs.name.text, {
label: cs.name.text,
kind: CompletionItemKind.Class
});
}
}
}
return [...results.values()];
}