-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathScope.spec.ts
More file actions
1433 lines (1269 loc) · 53 KB
/
Scope.spec.ts
File metadata and controls
1433 lines (1269 loc) · 53 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 { expect } from 'chai';
import * as sinonImport from 'sinon';
import { Position, Range } from 'vscode-languageserver';
import util, { standardizePath as s } from './util';
import { DiagnosticMessages } from './DiagnosticMessages';
import { Program } from './Program';
import { ParseMode } from './parser/Parser';
import PluginInterface from './PluginInterface';
import { expectDiagnostics, expectZeroDiagnostics, trim } from './testHelpers.spec';
import { Logger } from './Logger';
import type { BrsFile } from './files/BrsFile';
import type { FunctionStatement, NamespaceStatement } from './parser/Statement';
import type { OnScopeValidateEvent } from './interfaces';
describe('Scope', () => {
let sinon = sinonImport.createSandbox();
let rootDir = process.cwd();
let program: Program;
beforeEach(() => {
program = new Program({
rootDir: rootDir
});
program.createSourceScope();
});
afterEach(() => {
sinon.restore();
program.dispose();
});
it('does not mark namespace functions as collisions with stdlib', () => {
program.setFile({
src: `${rootDir}/source/main.bs`,
dest: `source/main.bs`
}, `
namespace a
function constructor()
end function
end namespace
`);
program.validate();
expectZeroDiagnostics(program);
});
it('builds symbol table with namespace-relative entries', () => {
const file = program.setFile<BrsFile>('source/alpha.bs', `
namespace alpha
class Beta
end class
end namespace
namespace alpha
class Charlie extends Beta
end class
function createBeta()
return new Beta()
end function
end namespace
`);
program.setFile('source/main.bs', `
function main()
alpha.createBeta()
thing = new alpha.Beta()
end function
`);
program.validate();
const scope = program.getScopesForFile('source/alpha.bs')[0];
scope.linkSymbolTable();
const symbolTable = file.parser.references.namespaceStatements[1].getSymbolTable();
//the symbol table should contain the relative names for all items in this namespace across the entire scope
expect(
symbolTable.hasSymbol('Beta')
).to.be.true;
expect(
symbolTable.hasSymbol('Charlie')
).to.be.true;
expect(
symbolTable.hasSymbol('createBeta')
).to.be.true;
expectZeroDiagnostics(program);
});
it('handles variables with javascript prototype names', () => {
program.setFile('source/main.brs', `
sub main()
constructor = true
end sub
`);
program.validate();
expectZeroDiagnostics(program);
});
it('flags parameter with same name as namespace', () => {
program.setFile('source/main.bs', `
namespace NameA.NameB
end namespace
sub main(nameA)
end sub
`);
program.validate();
expectDiagnostics(program, [
DiagnosticMessages.parameterMayNotHaveSameNameAsNamespace('nameA')
]);
});
it('flags assignments with same name as namespace', () => {
program.setFile('source/main.bs', `
namespace NameA.NameB
end namespace
sub main()
namea = 2
NAMEA += 1
end sub
`);
program.validate();
expectDiagnostics(program, [
DiagnosticMessages.variableMayNotHaveSameNameAsNamespace('namea'),
DiagnosticMessages.variableMayNotHaveSameNameAsNamespace('NAMEA')
]);
});
it('allows adding diagnostics', () => {
const source = program.getScopeByName('source');
const expected = [{
message: 'message',
file: undefined,
range: undefined
}];
source.addDiagnostics(expected);
expectDiagnostics(source, expected);
});
it('allows getting all scopes', () => {
const scopes = program.getScopes();
expect(scopes.length).to.equal(2);
});
describe('addFile', () => {
it('detects callables from all loaded files', () => {
const sourceScope = program.getScopeByName('source');
program.setFile({ src: s`${rootDir}/source/main.brs`, dest: s`source/main.brs` }, `
sub Main()
end sub
sub ActionA()
end sub
`);
program.setFile({ src: s`${rootDir}/source/lib.brs`, dest: s`source/lib.brs` }, `
sub ActionB()
end sub
`);
program.validate();
expect(sourceScope.getOwnFiles().map(x => x.srcPath).sort()).eql([
s`${rootDir}/source/lib.brs`,
s`${rootDir}/source/main.brs`
]);
expectZeroDiagnostics(program);
expect(sourceScope.getOwnCallables()).is.lengthOf(3);
expect(sourceScope.getAllCallables()).is.length.greaterThan(3);
});
it('picks up new callables', () => {
program.setFile('source/file.brs', '');
//we have global callables, so get that initial number
let originalLength = program.getScopeByName('source').getAllCallables().length;
program.setFile('source/file.brs', `
function DoA()
print "A"
end function
function DoA()
print "A"
end function
`);
expect(program.getScopeByName('source').getAllCallables().length).to.equal(originalLength + 2);
});
});
describe('removeFile', () => {
it('removes callables from list', () => {
//add the file
let file = program.setFile(`source/file.brs`, `
function DoA()
print "A"
end function
`);
let initCallableCount = program.getScopeByName('source').getAllCallables().length;
//remove the file
program.removeFile(file.srcPath);
expect(program.getScopeByName('source').getAllCallables().length).to.equal(initCallableCount - 1);
});
});
describe('validate', () => {
it('diagnostics are assigned to correct child scope', () => {
program.options.autoImportComponentScript = true;
program.setFile('components/constants.bs', `
namespace constants.alpha.beta
const charlie = "charlie"
end namespace
`);
program.setFile('components/ButtonBase.xml', `<component name="ButtonBase" extends="Scene" />`);
const buttonPrimary = program.setFile('components/ButtonPrimary.bs', `
import "constants.bs"
sub init()
print constants.alpha.delta.charlie
end sub
`);
program.setFile('components/ButtonPrimary.xml', `<component name="ButtonPrimary" extends="ButtonBase" />`);
const buttonSecondary = program.setFile('components/ButtonSecondary.bs', `
import "constants.bs"
sub init()
print constants.alpha.delta.charlie
end sub
`);
program.setFile('components/ButtonSecondary.xml', `<component name="ButtonSecondary" extends="ButtonBase" />`);
program.validate();
expectDiagnostics(program, [
{
message: DiagnosticMessages.cannotFindName('delta').message,
file: {
srcPath: buttonPrimary.srcPath
},
relatedInformation: [{
message: `Not defined in scope '${s('components/ButtonPrimary.xml')}'`
}]
}, {
message: DiagnosticMessages.cannotFindName('delta').message,
file: {
srcPath: buttonSecondary.srcPath
},
relatedInformation: [{
message: `Not defined in scope '${s('components/ButtonSecondary.xml')}'`
}]
}
]);
});
it('recognizes dimmed vars', () => {
program.setFile(`source/file.brs`, `
function buildArray(numItems)
dim result[3]
for i = 0 to numItems
result.push(i)
end for
return result
end function
`);
program.validate();
expectZeroDiagnostics(program);
});
it('detects unknown namespace names', () => {
program.setFile('source/main.bs', `
sub main()
Name1.thing()
Name2.thing()
end sub
namespace Name1
sub thing()
end sub
end namespace
`);
program.validate();
expectDiagnostics(program, [
DiagnosticMessages.cannotFindName('Name2')
]);
});
it('accepts namespace names in their transpiled form in .brs files', () => {
program.setFile('source/ns.bs', `
namespace MyNamespace
sub foo()
end sub
end namespace
namespace A.B.C
sub ga()
end sub
end namespace
`);
program.setFile('source/main.brs', `
sub main()
MyNamespace_foo()
A_B_C_ga()
end sub
`);
program.setFile('source/main.xml', `
<?xml version="1.0" encoding="UTF-8"?>
<component name="MyComponent" extends="Group">
<script type="text/brightscript" uri="main.brs"/>
<script type="text/brightscript" uri="ns.bs"/>
</component>
`);
program.validate();
expectZeroDiagnostics(program);
});
it('Validates NOT too deep nested files', () => {
program.setFile('source/folder2/folder3/folder4/folder5/folder6/folder7/main.brs', ``);
program.setFile('source/folder2/folder3/folder4/folder5/folder6/folder7/main2.bs', ``);
program.setFile('components/folder2/folder3/folder4/folder5/folder6/folder7/ButtonSecondary.xml', `<component name="ButtonSecondary" extends="ButtonBase" />`);
program.validate();
expectZeroDiagnostics(program);
});
it('Validates too deep nested files', () => {
program.setFile('source/folder2/folder3/folder4/folder5/folder6/folder7/folder8/main.brs', ``);
program.setFile('source/folder2/folder3/folder4/folder5/folder6/folder7/folder8/main2.bs', ``);
program.setFile('components/folder2/folder3/folder4/folder5/folder6/folder7/folder8/ButtonSecondary.xml', `<component name="ButtonSecondary" extends="ButtonBase" />`);
program.validate();
expectDiagnostics(program, [
DiagnosticMessages.detectedTooDeepFileSource(8),
DiagnosticMessages.detectedTooDeepFileSource(8),
DiagnosticMessages.detectedTooDeepFileSource(8)
]);
});
it('detects unknown namespace sub-names', () => {
program.setFile('source/main.bs', `
sub main()
Name1.subname.thing()
end sub
namespace Name1
sub thing()
end sub
end namespace
`);
program.validate();
expectDiagnostics(program, [{
...DiagnosticMessages.cannotFindName('subname', 'Name1.subname'),
range: util.createRange(2, 26, 2, 33)
}]);
});
it('detects unknown enum names', () => {
program.setFile('source/main.bs', `
sub main()
print Direction.up
print up.Direction
end sub
enum Direction
up
end enum
`);
program.validate();
expectDiagnostics(program, [
DiagnosticMessages.cannotFindName('up')
]);
});
it('detects unknown function names', () => {
program.setFile('source/main.bs', `
sub main()
print go.toStr()
print go2.toStr()
end sub
function go()
end function
`);
program.validate();
expectDiagnostics(program, [
DiagnosticMessages.cannotFindName('go2')
]);
});
it('detects unknown const in assignment operator', () => {
program.setFile('source/main.bs', `
sub main()
value = ""
value += constants.API_KEY
value += API_URL
end sub
`);
program.validate();
expectDiagnostics(program, [
DiagnosticMessages.cannotFindName('constants'),
DiagnosticMessages.cannotFindName('API_URL')
]);
});
it('detects unknown local var names', () => {
program.setFile('source/lib.bs', `
sub libFunc(param1)
print param1
print param2
name1 = "bob"
print name1
print name2
for each item1 in param1
print item1
print item2
end for
for idx1 = 0 to 10
print idx1
print idx2
end for
try
print 1
catch ex1
print ex1
print ex2
end try
end sub
function go()
end function
`);
program.validate();
expectDiagnostics(program, [
DiagnosticMessages.cannotFindName('param2'),
DiagnosticMessages.cannotFindName('name2'),
DiagnosticMessages.cannotFindName('item2'),
DiagnosticMessages.cannotFindName('idx2'),
DiagnosticMessages.cannotFindName('ex2')
]);
});
describe('createObject', () => {
it('recognizes various scenegraph nodes', () => {
program.setFile(`source/file.brs`, `
sub main()
scene = CreateObject("roSGScreen")
button = CreateObject("roSGNode", "Button")
list = CreateObject("roSGNode", "MarkupList")
end sub
`);
program.validate();
expectZeroDiagnostics(program);
});
it('recognizes valid custom components', () => {
program.setFile('components/comp1.xml', trim`
<?xml version="1.0" encoding="utf-8" ?>
<component name="Comp1" extends="Scene">
</component>
`);
program.setFile('components/comp2.xml', trim`
<?xml version="1.0" encoding="utf-8" ?>
<component name="Comp2" extends="Scene">
</component>
`);
program.setFile(`source/file.brs`, `
sub main()
comp1 = CreateObject("roSGNode", "Comp1")
comp2 = CreateObject("roSGNode", "Comp2")
end sub
`);
program.validate();
expectZeroDiagnostics(program);
});
it('catches unknown roSGNodes', () => {
program.setFile(`source/file.brs`, `
sub main()
scene = CreateObject("roSGNode", "notReal")
button = CreateObject("roSGNode", "alsoNotReal")
list = CreateObject("roSGNode", "definitelyNotReal")
end sub
`);
program.validate();
expectDiagnostics(program, [
DiagnosticMessages.unknownRoSGNode('notReal'),
DiagnosticMessages.unknownRoSGNode('alsoNotReal'),
DiagnosticMessages.unknownRoSGNode('definitelyNotReal')
]);
});
it('only adds a single diagnostic when the file is used in multiple scopes', () => {
program.setFile('components/Comp1.xml', trim`
<?xml version="1.0" encoding="utf-8" ?>
<component name="Comp1" extends="Scene">
<script type="text/brightscript" uri="lib.brs" />
</component>
`);
program.setFile('components/Comp2.xml', trim`
<?xml version="1.0" encoding="utf-8" ?>
<component name="Comp2" extends="Scene">
<script type="text/brightscript" uri="lib.brs" />
</component>
`);
program.setFile('components/lib.brs', `
sub init()
'unknown BrightScript component
createObject("roDateTime_FAKE")
'Wrong number of params
createObject("roDateTime", "this param should not be here")
'unknown roSGNode
createObject("roSGNode", "Rectangle_FAKE")
'deprecated
fontMetrics = CreateObject("roFontMetrics", "someFontName")
end sub
`);
program.validate();
expectDiagnostics(program, [
DiagnosticMessages.unknownBrightScriptComponent('roDateTime_FAKE'),
DiagnosticMessages.mismatchCreateObjectArgumentCount('roDateTime', [1, 1], 2),
DiagnosticMessages.unknownRoSGNode('Rectangle_FAKE'),
DiagnosticMessages.deprecatedBrightScriptComponent('roFontMetrics').code
]);
});
it('disregards component library components', () => {
program.setFile(`source/file.brs`, `
sub main()
scene = CreateObject("roSGNode", "Complib1:MainScene")
button = CreateObject("roSGNode", "buttonlib:Button")
list = CreateObject("roSGNode", "listlib:List")
end sub
`);
program.validate();
expectZeroDiagnostics(program);
});
it('disregards non-literal args', () => {
program.setFile(`source/file.brs`, `
sub main()
sgNodeName = "roSGNode"
compNameAsVar = "Button"
button = CreateObject(sgNodeName, compNameAsVar)
end sub
`);
program.validate();
expectZeroDiagnostics(program);
});
it('recognizes valid BrightScript components', () => {
program.setFile(`source/file.brs`, `
sub main()
timeSpan = CreateObject("roTimespan")
bitmap = CreateObject("roBitmap", {width:10, height:10, AlphaEnable:false, name:"MyBitmapName"})
path = CreateObject("roPath", "ext1:/vid")
region = CreateObject("roRegion", bitmap, 20, 30, 100, 200)
end sub
`);
program.validate();
expectZeroDiagnostics(program);
});
it('catches invalid BrightScript components', () => {
program.setFile(`source/file.brs`, `
sub main()
timeSpan = CreateObject("Thing")
bitmap = CreateObject("OtherThing", {width:10, height:10, AlphaEnable:false, name:"MyBitmapName"})
path = CreateObject("SomethingElse", "ext1:/vid")
region = CreateObject("Button", bitmap, 20, 30, 100, 200)
end sub
`);
program.validate();
expectDiagnostics(program, [
DiagnosticMessages.unknownBrightScriptComponent('Thing'),
DiagnosticMessages.unknownBrightScriptComponent('OtherThing'),
DiagnosticMessages.unknownBrightScriptComponent('SomethingElse'),
DiagnosticMessages.unknownBrightScriptComponent('Button')
]);
});
it('catches wrong number of arguments', () => {
program.setFile(`source/file.brs`, `
sub main()
button = CreateObject("roSGNode", "Button", "extraArg")
bitmap = CreateObject("roBitmap") ' no 2nd arg
timeSpan = CreateObject("roTimespan", 1, 2, 3)
region = CreateObject("roRegion", bitmap, 20, 30, 100) ' missing last arg
end sub
`);
program.validate();
expectDiagnostics(program, [
DiagnosticMessages.mismatchCreateObjectArgumentCount('roSGNode', [2], 3),
DiagnosticMessages.mismatchCreateObjectArgumentCount('roBitmap', [2], 1),
DiagnosticMessages.mismatchCreateObjectArgumentCount('roTimespan', [1], 4),
DiagnosticMessages.mismatchCreateObjectArgumentCount('roRegion', [6], 5)
]);
});
it('catches deprecated components', () => {
program.setFile(`source/file.brs`, `
sub main()
fontMetrics = CreateObject("roFontMetrics", "someFontName")
end sub
`);
program.validate();
// only care about code and `roFontMetrics` match
const diagnostics = program.getDiagnostics();
const expectedDiag = DiagnosticMessages.deprecatedBrightScriptComponent('roFontMetrics');
expect(diagnostics.length).to.eql(1);
expect(diagnostics[0].code).to.eql(expectedDiag.code);
expect(diagnostics[0].message).to.contain(expectedDiag.message);
});
});
it('marks the scope as validated after validation has occurred', () => {
program.setFile({ src: s`${rootDir}/source/main.bs`, dest: s`source/main.bs` }, `
sub main()
end sub
`);
let lib = program.setFile({ src: s`${rootDir}/source/lib.bs`, dest: s`source/lib.bs` }, `
sub libFunc()
end sub
`);
expect(program.getScopesForFile(lib)[0].isValidated).to.be.false;
program.validate();
expect(program.getScopesForFile(lib)[0].isValidated).to.be.true;
lib = program.setFile({ src: s`${rootDir}/source/lib.bs`, dest: s`source/lib.bs` }, `
sub libFunc()
end sub
`);
//scope gets marked as invalidated
expect(program.getScopesForFile(lib)[0].isValidated).to.be.false;
});
it('does not mark same-named-functions in different namespaces as an error', () => {
program.setFile({ src: s`${rootDir}/source/main.bs`, dest: s`source/main.bs` }, `
namespace NameA
sub alert()
end sub
end namespace
namespace NameB
sub alert()
end sub
end namespace
`);
program.validate();
expectZeroDiagnostics(program);
});
it('resolves local-variable function calls', () => {
program.setFile({ src: s`${rootDir}/source/main.brs`, dest: s`source/main.brs` }, `
sub DoSomething()
sayMyName = function(name as string)
end function
sayMyName()
end sub`
);
program.validate();
expectZeroDiagnostics(program);
});
describe('function shadowing', () => {
it('warns when local var function has same name as stdlib function', () => {
program.setFile({ src: s`${rootDir}/source/main.brs`, dest: s`source/main.brs` }, `
sub main()
str = function(p)
return "override"
end function
print str(12345) 'prints "12345" (i.e. our local function is never used)
end sub
`);
program.validate();
expectDiagnostics(program, [{
...DiagnosticMessages.localVarFunctionShadowsParentFunction('stdlib'),
range: Range.create(2, 24, 2, 27)
}]);
});
it('warns when local var has same name as built-in function', () => {
program.setFile({ src: s`${rootDir}/source/main.brs`, dest: s`source/main.brs` }, `
sub main()
str = 12345
print str ' prints "12345" (i.e. our local variable is allowed to shadow the built-in function name)
end sub
`);
program.validate();
expectZeroDiagnostics(program);
});
it('warns when local var has same name as built-in function', () => {
program.setFile({ src: s`${rootDir}/source/main.brs`, dest: s`source/main.brs` }, `
sub main()
str = 6789
print str(12345) ' prints "12345" (i.e. our local variable did not override the callable global function)
end sub
`);
program.validate();
expectZeroDiagnostics(program);
});
it('detects local function with same name as scope function', () => {
program.setFile({ src: s`${rootDir}/source/main.brs`, dest: s`source/main.brs` }, `
sub main()
getHello = function()
return "override"
end function
print getHello() 'prints "hello" (i.e. our local variable is never called)
end sub
function getHello()
return "hello"
end function
`);
program.validate();
expectDiagnostics(program, [{
message: DiagnosticMessages.localVarFunctionShadowsParentFunction('scope').message,
range: Range.create(2, 24, 2, 32)
}]);
});
it('detects local function with same name as scope function', () => {
program.setFile({ src: s`${rootDir}/source/main.brs`, dest: s`source/main.brs` }, `
sub main()
getHello = "override"
print getHello ' prints <Function: gethello> (i.e. local variable override does NOT work for same-scope-defined methods)
end sub
function getHello()
return "hello"
end function
`);
program.validate();
expectDiagnostics(program, [{
message: DiagnosticMessages.localVarShadowedByScopedFunction().message,
range: Range.create(2, 24, 2, 32)
}]);
});
it('flags scope function with same name (but different case) as built-in function', () => {
program.setFile('source/main.brs', `
sub main()
print str(12345) ' prints 12345 (i.e. our str() function below is ignored)
end sub
function STR(num)
return "override"
end function
`);
program.validate();
expectDiagnostics(program, [{
message: DiagnosticMessages.scopeFunctionShadowedByBuiltInFunction().message,
range: Range.create(4, 29, 4, 32)
}]);
});
});
it('detects duplicate callables', () => {
program.setFile('source/file.brs', `
function DoA()
print "A"
end function
function DoA()
print "A"
end function
`);
expectZeroDiagnostics(program);
//validate the scope
program.validate();
//we should have the "DoA declared more than once" error twice (one for each function named "DoA")
expectDiagnostics(program, [
DiagnosticMessages.duplicateFunctionImplementation('DoA', 'source'),
DiagnosticMessages.duplicateFunctionImplementation('DoA', 'source')
]);
});
it('detects calls to unknown callables', () => {
program.setFile('source/file.brs', `
function DoA()
DoB()
end function
`);
expectZeroDiagnostics(program);
//validate the scope
program.validate();
expectDiagnostics(program, [
DiagnosticMessages.cannotFindName('DoB')
]);
});
it('recognizes known callables', () => {
program.setFile('source/file.brs', `
function DoA()
DoB()
end function
function DoB()
DoC()
end function
`);
//validate the scope
program.validate();
expectDiagnostics(program, [
DiagnosticMessages.cannotFindName('DoC')
]);
});
it('does not error with calls to callables in same namespace', () => {
program.setFile('source/file.bs', `
namespace Name.Space
sub a(param as string)
print param
end sub
sub b()
a("hello")
end sub
end namespace
`);
//validate the scope
program.validate();
expectZeroDiagnostics(program);
});
//We don't currently support someObj.callSomething() format, so don't throw errors on those
it('does not fail on object callables', () => {
expectZeroDiagnostics(program);
program.setFile('source/file.brs', `
function DoB()
m.doSomething()
end function
`);
//validate the scope
program.validate();
//shouldn't have any errors
expectZeroDiagnostics(program);
});
it('detects calling functions with too many parameters', () => {
program.setFile('source/file.brs', `
sub a()
end sub
sub b()
a(1)
end sub
`);
program.validate();
expectDiagnostics(program, [
DiagnosticMessages.mismatchArgumentCount(0, 1).message
]);
});
it('detects calling class constructors with too many parameters', () => {
program.setFile('source/main.bs', `
function noop0()
end function
function noop1(p1)
end function
sub main()
noop0(1)
noop1(1,2)
noop1()
end sub
`);
program.validate();
expectDiagnostics(program, [
DiagnosticMessages.mismatchArgumentCount(0, 1),
DiagnosticMessages.mismatchArgumentCount(1, 2),
DiagnosticMessages.mismatchArgumentCount(1, 0)
]);
});
it('detects calling functions with too many parameters', () => {
program.setFile('source/file.brs', `
sub a(name)
end sub
sub b()
a()
end sub
`);
program.validate();
expectDiagnostics(program, [
DiagnosticMessages.mismatchArgumentCount(1, 0)
]);
});
it('allows skipping optional parameter', () => {
program.setFile('source/file.brs', `
sub a(name="Bob")
end sub
sub b()
a()
end sub
`);
program.validate();
//should have an error
expectZeroDiagnostics(program);
});
it('shows expected parameter range in error message', () => {
program.setFile('source/file.brs', `
sub a(age, name="Bob")
end sub
sub b()
a()
end sub
`);
program.validate();
//should have an error
expectDiagnostics(program, [
DiagnosticMessages.mismatchArgumentCount('1-2', 0)
]);
});
it('handles expressions as arguments to a function', () => {
program.setFile('source/file.brs', `
sub a(age, name="Bob")
end sub
sub b()
a("cat" + "dog" + "mouse")
end sub
`);
program.validate();
expectZeroDiagnostics(program);
});
it('Catches extra arguments for expressions as arguments to a function', () => {
program.setFile('source/file.brs', `
sub a(age)
end sub
sub b()
a(m.lib.movies[0], 1)
end sub
`);
program.validate();
//should have an error
expectDiagnostics(program, [
DiagnosticMessages.mismatchArgumentCount(1, 2)
]);
});
it('handles JavaScript reserved names', () => {
program.setFile('source/file.brs', `
sub constructor()
end sub
sub toString()
end sub
sub valueOf()
end sub
sub getPrototypeOf()
end sub
`);
program.validate();
expectZeroDiagnostics(program);
});
it('Emits validation events', () => {
program.setFile('source/file.brs', ``);
program.setFile('components/comp.xml', trim`
<?xml version="1.0" encoding="utf-8" ?>
<component name="comp" extends="Scene">
<script uri="comp.brs"/>
</component>
`);
program.setFile(s`components/comp.brs`, ``);
const sourceScope = program.getScopeByName('source');
const compScope = program.getScopeByName('components/comp.xml');
program.plugins = new PluginInterface([], new Logger());
const plugin = program.plugins.add({
name: 'Emits validation events',
beforeScopeValidate: sinon.spy(),
onScopeValidate: sinon.spy(),
afterScopeValidate: sinon.spy()
});
program.validate();
const scopeNames = program.getScopes().map(x => x.name).filter(x => x !== 'global').sort();
expect(plugin.beforeScopeValidate.callCount).to.equal(2);
expect(plugin.beforeScopeValidate.calledWith(sourceScope)).to.be.true;
expect(plugin.beforeScopeValidate.calledWith(compScope)).to.be.true;
expect(plugin.onScopeValidate.callCount).to.equal(2);
expect(plugin.onScopeValidate.getCalls().map(
x => (x.args[0] as OnScopeValidateEvent).scope.name
).sort()).to.eql(scopeNames);
expect(plugin.afterScopeValidate.callCount).to.equal(2);
expect(plugin.afterScopeValidate.calledWith(sourceScope)).to.be.true;
expect(plugin.afterScopeValidate.calledWith(compScope)).to.be.true;
});
describe('custom types', () => {
it('detects an unknown function return type', () => {
program.setFile({ src: s`${rootDir}/source/main.bs`, dest: s`source/main.bs` }, `
function a()
return invalid
end function
function b() as integer
return 1
end function
function c() as unknownType 'error
return 2
end function
class myClass