-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathParser.spec.ts
More file actions
1918 lines (1733 loc) · 74.3 KB
/
Parser.spec.ts
File metadata and controls
1918 lines (1733 loc) · 74.3 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, assert } from '../chai-config.spec';
import { Lexer } from '../lexer/Lexer';
import { ReservedWords, TokenKind } from '../lexer/TokenKind';
import type { AAMemberExpression } from './Expression';
import { TernaryExpression, NewExpression, IndexedGetExpression, DottedGetExpression, XmlAttributeGetExpression, CallfuncExpression, AnnotationExpression, CallExpression, FunctionExpression } from './Expression';
import { Parser, ParseMode } from './Parser';
import type { AliasStatement, AssignmentStatement, ClassStatement, TypecastStatement, TypeStatement } from './Statement';
import { PrintStatement, FunctionStatement, NamespaceStatement, ImportStatement } from './Statement';
import { Range } from 'vscode-languageserver';
import { DiagnosticMessages } from '../DiagnosticMessages';
import { isAliasStatement, isBlock, isCommentStatement, isFunctionStatement, isIfStatement, isIndexedGetExpression, isTypecastStatement, isTypeStatement } from '../astUtils/reflection';
import { expectDiagnostics, expectDiagnosticsIncludes, expectZeroDiagnostics } from '../testHelpers.spec';
import { BrsTranspileState } from './BrsTranspileState';
import { SourceNode } from 'source-map';
import { BrsFile } from '../files/BrsFile';
import { Program } from '../Program';
import { createVisitor, WalkMode } from '../astUtils/visitors';
import type { Expression, Statement } from './AstNode';
describe('parser', () => {
it('emits empty object when empty token list is provided', () => {
expect(Parser.parse([])).to.deep.include({
statements: [],
diagnostics: []
});
});
describe('findReferences', () => {
it('gets called if references are missing', () => {
const parser = Parser.parse(`
sub main()
end sub
sub UnusedFunction()
end sub
`);
expect(parser.references.functionStatements.map(x => x.name.text)).to.eql([
'main',
'UnusedFunction'
]);
//simulate a tree-shaking plugin by removing the `UnusedFunction`
parser.ast.statements.splice(1);
//tell the parser we modified the AST and need to regenerate references
parser.invalidateReferences();
expect(parser['_references']).not.to.exist;
//calling `references` automatically regenerates the references
expect(parser.references.functionStatements.map(x => x.name.text)).to.eql([
'main'
]);
});
function expressionsToStrings(expressions: Set<Expression>) {
return [...expressions.values()].map(x => {
const file = new BrsFile('', '', new Program({} as any));
const state = new BrsTranspileState(file);
return new SourceNode(null, null, null, x.transpile(state) as any).toString();
});
}
it('works for references.expressions', () => {
const parser = Parser.parse(`
b += "plus-equal"
a += 1 + 2
b += getValue1() + getValue2()
increment++
decrement--
bravo(3 + 4).jump(callMe())
obj = {
val1: someValue
}
arr = [
one
]
thing = alpha.bravo
alpha.charlie()
delta(alpha.delta)
call1().a.b.call2()
class Person
name as string = "bob"
end class
function thing(p1 = name.space.getSomething())
end function
`);
const expected = [
'"plus-equal"',
'b',
'b += "plus-equal"',
'1',
'2',
'a',
'a += 1 + 2',
'getValue1()',
'getValue2()',
'b',
'b += getValue1() + getValue2()',
'increment++',
'decrement--',
//currently the "toString" does a transpile, so that's why this is different.
'some.node.callfunc("doCallfunc", invalid)',
'3',
'4',
'3 + 4',
'callMe()',
'bravo(3 + 4).jump(callMe())',
'someValue',
'{\n val1: someValue\n}',
'one',
'[\n one\n]',
'alpha.bravo',
'alpha.charlie()',
'alpha.delta',
'delta(alpha.delta)',
'call1().a.b.call2()',
'"bob"',
'name.space.getSomething()'
];
expect(
expressionsToStrings(parser.references.expressions)
).to.eql(expected);
//tell the parser we modified the AST and need to regenerate references
parser.invalidateReferences();
expect(
expressionsToStrings(parser.references.expressions).sort()
).to.eql(expected.sort());
});
it('works for references.expressions', () => {
const parser = Parser.parse(`
value = true or type(true) = "something" or Enums.A.Value = "value" and Enum1.Value = Name.Space.Enum2.Value
`);
const expected = [
'true',
'type(true)',
'"something"',
'true',
'Enums.A.Value',
'"value"',
'Enum1.Value',
'Name.Space.Enum2.Value',
'true or type(true) = "something" or Enums.A.Value = "value" and Enum1.Value = Name.Space.Enum2.Value'
];
expect(
expressionsToStrings(parser.references.expressions)
).to.eql(expected);
//tell the parser we modified the AST and need to regenerate references
parser.invalidateReferences();
expect(
expressionsToStrings(parser.references.expressions).sort()
).to.eql(expected.sort());
});
it('works for logical expression', () => {
const parser = Parser.parse(`
value = Enums.A.Value = "value"
`);
const expected = [
'Enums.A.Value',
'"value"',
'Enums.A.Value = "value"'
];
expect(
expressionsToStrings(parser.references.expressions)
).to.eql(expected);
//tell the parser we modified the AST and need to regenerate references
parser.invalidateReferences();
expect(
expressionsToStrings(parser.references.expressions).sort()
).to.eql(expected.sort());
});
});
describe('callfunc operator', () => {
it('is not allowed in brightscript mode', () => {
let parser = parse(`
sub main(node as dynamic)
[email protected](1, 2)
end sub
`, ParseMode.BrightScript);
expect(
parser.diagnostics[0]?.message
).to.equal(
DiagnosticMessages.bsFeatureNotSupportedInBrsFiles('callfunc operator').message
);
});
it('does not cause parse errors', () => {
let parser = parse(`
sub main(node as dynamic)
[email protected](1, 2)
end sub
`, ParseMode.BrighterScript);
expect(parser.diagnostics[0]?.message).not.to.exist;
expect((parser as any).statements[0]?.func?.body?.statements[0]?.expression).to.be.instanceof(CallfuncExpression);
});
});
describe('optional chaining operator', () => {
function getExpression<T>(text: string, options?: { matcher?: any; parseMode?: ParseMode }) {
const parser = parse(text, options?.parseMode);
expectZeroDiagnostics(parser);
const expressions = [...parser.references.expressions];
if (options?.matcher) {
return expressions.find(options.matcher) as unknown as T;
} else {
return expressions[0] as unknown as T;
}
}
it('works for ?.', () => {
const expression = getExpression<DottedGetExpression>(`value = person?.name`);
expect(expression).to.be.instanceOf(DottedGetExpression);
expect(expression.dot.kind).to.eql(TokenKind.QuestionDot);
});
it('works for ?[', () => {
const expression = getExpression<IndexedGetExpression>(`value = person?["name"]`, { matcher: isIndexedGetExpression });
expect(expression).to.be.instanceOf(IndexedGetExpression);
expect(expression.openingSquare.kind).to.eql(TokenKind.QuestionLeftSquare);
expect(expression.questionDotToken).not.to.exist;
});
it('works for ?.[', () => {
const expression = getExpression<IndexedGetExpression>(`value = person?.["name"]`, { matcher: isIndexedGetExpression });
expect(expression).to.be.instanceOf(IndexedGetExpression);
expect(expression.openingSquare.kind).to.eql(TokenKind.LeftSquareBracket);
expect(expression.questionDotToken?.kind).to.eql(TokenKind.QuestionDot);
});
it('works for ?@', () => {
const expression = getExpression<XmlAttributeGetExpression>(`value = someXml?@someAttr`);
expect(expression).to.be.instanceOf(XmlAttributeGetExpression);
expect(expression.at.kind).to.eql(TokenKind.QuestionAt);
});
it('works for ?(', () => {
const expression = getExpression<CallExpression>(`value = person.getName?()`);
expect(expression).to.be.instanceOf(CallExpression);
expect(expression.openingParen.kind).to.eql(TokenKind.QuestionLeftParen);
});
it('works for print statements using question mark', () => {
const { statements } = parse(`
?[1]
?(1+1)
`);
expect(statements[0]).to.be.instanceOf(PrintStatement);
expect(statements[1]).to.be.instanceOf(PrintStatement);
});
//TODO enable this once we properly parse IIFEs
it.skip('works for ?( in anonymous function', () => {
const expression = getExpression<CallExpression>(`thing = (function() : end function)?()`);
expect(expression).to.be.instanceOf(CallExpression);
expect(expression.openingParen.kind).to.eql(TokenKind.QuestionLeftParen);
});
it('works for ?( in new call', () => {
const expression = getExpression<NewExpression>(`thing = new Person?()`, { parseMode: ParseMode.BrighterScript });
expect(expression).to.be.instanceOf(NewExpression);
expect(expression.call.openingParen.kind).to.eql(TokenKind.QuestionLeftParen);
});
it('distinguishes between optional chaining and ternary expression', () => {
const parser = parse(`
sub main()
name = person?["name"]
isTrue = true
key = isTrue ? ["name"] : ["age"]
end sub
`, ParseMode.BrighterScript);
expect(parser.references.assignmentStatements[0].value).is.instanceof(IndexedGetExpression);
expect(parser.references.assignmentStatements[2].value).is.instanceof(TernaryExpression);
});
it('distinguishes between optional chaining and ternary expression', () => {
const parser = parse(`
sub main()
'optional chain. the lack of whitespace between ? and [ matters
key = isTrue ?["name"] : getDefault()
'ternary
key = isTrue ? ["name"] : getDefault()
end sub
`, ParseMode.BrighterScript);
expect(parser.references.assignmentStatements[0].value).is.instanceof(IndexedGetExpression);
expect(parser.references.assignmentStatements[1].value).is.instanceof(TernaryExpression);
});
});
describe('diagnostic locations', () => {
it('tracks basic diagnostic locations', () => {
expect(parse(`
sub main()
call()a
end sub
`).diagnostics.map(x => rangeToArray(x.range))).to.eql([
[2, 26, 2, 27],
[2, 27, 2, 28]
]);
});
it.skip('handles edge cases', () => {
let diagnostics = parse(`
function BuildCommit()
return "6c5cdf1"
end functionasdf
`).diagnostics;
expect(diagnostics[0]?.message).to.exist.and.to.eql(
DiagnosticMessages.expectedStatementOrFunctionCallButReceivedExpression().message
);
expect(diagnostics[0]?.range).to.eql(
Range.create(3, 20, 3, 32)
);
});
});
describe('parse', () => {
it('supports ungrouped iife in assignment', () => {
const parser = parse(`
sub main()
result = sub()
end sub()
result = function()
end function()
end sub
`);
expectZeroDiagnostics(parser);
});
it('supports grouped iife in assignment', () => {
const parser = parse(`
sub main()
result = (sub()
end sub)()
result = (function()
end function)()
end sub
`);
expectZeroDiagnostics(parser);
});
it('supports returning iife call', () => {
const parser = parse(`
sub main()
return (sub()
end sub)()
end sub
`);
expectZeroDiagnostics(parser);
});
it('supports using "interface" as parameter name', () => {
expect(parse(`
sub main(interface as object)
end sub
`, ParseMode.BrighterScript).diagnostics[0]?.message).not.to.exist;
});
it('does not scrap the entire function when encountering unknown parameter type', () => {
const parser = parse(`
sub test(param1 as unknownType)
end sub
`);
expectDiagnostics(parser, [{
...DiagnosticMessages.functionParameterTypeIsInvalid('param1', 'unknownType')
}]);
expect(
isFunctionStatement(parser.ast.statements[0])
).to.be.true;
});
describe('namespace', () => {
it('allows namespaces declared inside other namespaces', () => {
const parser = parse(`
namespace Level1
namespace Level2.Level3
sub main()
end sub
end namespace
end namespace
`, ParseMode.BrighterScript);
expectZeroDiagnostics(parser);
// We expect these names to be "as given" in this context, because we aren't evaluating a full program.
expect(parser.references.namespaceStatements.map(statement => statement.getName(ParseMode.BrighterScript))).to.deep.equal([
'Level1.Level2.Level3',
'Level1'
]);
});
it('parses empty namespace', () => {
let { statements, diagnostics } =
parse(`
namespace Name.Space
end namespace
`, ParseMode.BrighterScript);
expect(diagnostics[0]?.message).not.to.exist;
expect(statements[0]).to.be.instanceof(NamespaceStatement);
});
it('includes body', () => {
let { statements, diagnostics } =
parse(`
namespace Name.Space
sub main()
end sub
end namespace
`, ParseMode.BrighterScript);
expect(diagnostics[0]?.message).not.to.exist;
expect(statements[0]).to.be.instanceof(NamespaceStatement);
expect((statements[0] as NamespaceStatement).body.statements[0]).to.be.instanceof(FunctionStatement);
});
it('supports comments and newlines', () => {
let { diagnostics } =
parse(`
namespace Name.Space 'comment
'comment
sub main() 'comment
end sub 'comment
'comment
'comment
end namespace 'comment
`, ParseMode.BrighterScript);
expect(diagnostics[0]?.message).not.to.exist;
});
it('catches missing name', () => {
let { diagnostics } =
parse(`
namespace
end namespace
`, ParseMode.BrighterScript);
expect(diagnostics[0]?.message).to.equal(
DiagnosticMessages.expectedIdentifierAfterKeyword('namespace').message
);
});
it('recovers after missing `end namespace`', () => {
let parser = parse(`
namespace Name.Space
sub main()
end sub
`, ParseMode.BrighterScript);
expect(parser.ast.statements[0]).to.be.instanceof(NamespaceStatement);
expect(parser.diagnostics[0]?.message).to.equal(
DiagnosticMessages.couldNotFindMatchingEndKeyword('namespace').message
);
expect((parser.ast.statements[0] as NamespaceStatement)?.body?.statements[0]).to.be.instanceof(FunctionStatement);
});
it('adds diagnostic when encountering namespace in brightscript mode', () => {
let parser = Parser.parse(`
namespace Name.Space
end namespace
`);
expect(parser.diagnostics[0]?.message).to.equal(
DiagnosticMessages.bsFeatureNotSupportedInBrsFiles('namespace').message
);
});
});
it('supports << operator', () => {
expect(parse(`
sub main()
print ((r << 24) + (g << 16) + (b << 8) + a)
end sub
`).diagnostics[0]?.message).not.to.exist;
});
it('supports >> operator', () => {
expect(parse(`
sub main()
print ((r >> 24) + (g >> 16) + (b >> 8) + a)
end sub
`).diagnostics[0]?.message).not.to.exist;
});
it('allows global function names with same as token to be called', () => {
expect(parse(`
sub main()
print string(123)
end sub
`).diagnostics[0]?.message).not.to.exist;
});
it('supports @ symbol between names', () => {
let parser = parse(`
sub main()
firstName = personXml@firstName
age = personXml.firstChild@age
end sub
`);
expect(parser.diagnostics[0]?.message).to.not.exist;
let statements = (parser.statements[0] as FunctionStatement).func.body.statements as AssignmentStatement[];
let first = statements[0].value as XmlAttributeGetExpression;
expect(first).to.be.instanceof(XmlAttributeGetExpression);
expect(first.name.text).to.equal('firstName');
expect(first.at.text).to.equal('@');
expect((first.obj as any).name.text).to.equal('personXml');
let second = statements[1].value as XmlAttributeGetExpression;
expect(second).to.be.instanceof(XmlAttributeGetExpression);
expect(second.name.text).to.equal('age');
expect(second.at.text).to.equal('@');
expect((second.obj as any).name.text).to.equal('firstChild');
});
it('does not allow chaining of @ symbols', () => {
let parser = parse(`
sub main()
personXml = invalid
name = personXml@name@age@shoeSize
end sub
`);
expect(parser.diagnostics).not.to.be.empty;
});
it('unknown function type does not invalidate rest of function', () => {
let { statements, diagnostics } = parse(`
function log() as UNKNOWN_TYPE
end function
`, ParseMode.BrightScript);
expect(diagnostics.length).to.be.greaterThan(0);
expect(statements[0]).to.exist;
});
it('unknown function type is not a problem in Brighterscript mode', () => {
let { statements, diagnostics } = parse(`
function log() as UNKNOWN_TYPE
end function
`, ParseMode.BrighterScript);
expect(diagnostics.length).to.equal(0);
expect(statements[0]).to.exist;
});
it('allows namespaced function type in Brighterscript mode', () => {
let { statements, diagnostics } = parse(`
function log() as SOME_NAMESPACE.UNKNOWN_TYPE
end function
`, ParseMode.BrighterScript);
expect(diagnostics.length).to.equal(0);
expect(statements[0]).to.exist;
});
it('allows custom parameter types in BrighterscriptMode', () => {
let { statements, diagnostics } = parse(`
sub foo(value as UNKNOWN_TYPE)
end sub
`, ParseMode.BrighterScript);
expect(diagnostics.length).to.equal(0);
expect(statements[0]).to.exist;
});
it('does not allow custom parameter types in Brightscript Mode', () => {
let { diagnostics } = parse(`
sub foo(value as UNKNOWN_TYPE)
end sub
`, ParseMode.BrightScript);
expect(diagnostics.length).not.to.equal(0);
});
it('allows custom namespaced parameter types in BrighterscriptMode', () => {
let { statements, diagnostics } = parse(`
sub foo(value as SOME_NAMESPACE.UNKNOWN_TYPE)
end sub
`, ParseMode.BrighterScript);
expect(diagnostics.length).to.equal(0);
expect(statements[0]).to.exist;
});
it('works with conditionals', () => {
expect(parse(`
function printNumber()
if true then
print 1
else if true
return false
end if
end function
`).diagnostics[0]?.message).not.to.exist;
});
it('supports single-line if statements', () => {
expect(parse(`If true Then print "error" : Stop`).diagnostics[0]?.message).to.not.exist;
});
it('works with excess newlines', () => {
let { tokens } = Lexer.scan(
'function boolToNumber() as string\n\n' +
' if true then\n\n' +
' print 1\n\n' +
' elseif true then\n\n' +
' print 0\n\n' +
' else\n\n' +
' print 1\n\n' +
' end if\n\n' +
'end function\n\n'
);
expect(Parser.parse(tokens).diagnostics[0]?.message).to.not.exist;
});
it('does not invalidate entire file when line ends with a period', () => {
let { tokens } = Lexer.scan(`
sub main()
person.a
end sub
`);
let { diagnostics } = Parser.parse(tokens) as any;
expect(diagnostics).to.be.lengthOf(1, 'Error count should be 0');
});
it.skip('allows printing object with trailing period', () => {
let { tokens } = Lexer.scan(`print a.`);
let { statements, diagnostics } = Parser.parse(tokens);
let printStatement = statements[0] as PrintStatement;
expect(diagnostics).to.be.empty;
expect(printStatement).to.be.instanceof(PrintStatement);
expect(printStatement.expressions[0]).to.be.instanceof(DottedGetExpression);
});
describe('comments', () => {
it('combines multi-line comments', () => {
let { tokens } = Lexer.scan(`
'line 1
'line 2
'line 3
`);
let { diagnostics, statements } = Parser.parse(tokens) as any;
expect(diagnostics).to.be.lengthOf(0, 'Error count should be 0');
expect(statements[0].text).to.equal(`'line 1\n'line 2\n'line 3`);
});
it('does not combile comments separated by newlines', () => {
let { tokens } = Lexer.scan(`
'line 1
'line 2
'line 3
`);
let { diagnostics, statements } = Parser.parse(tokens) as any;
expect(diagnostics).to.be.lengthOf(0, 'Error count should be 0');
expect(statements).to.be.lengthOf(3);
expect(statements[0].text).to.equal(`'line 1`);
expect(statements[1].text).to.equal(`'line 2`);
expect(statements[2].text).to.equal(`'line 3`);
});
it('works after print statement', () => {
let { tokens } = Lexer.scan(`
sub main()
print "hi" 'comment 1
end sub
`);
let { diagnostics, statements } = Parser.parse(tokens);
expect(diagnostics).to.be.lengthOf(0, 'Error count should be 0');
expect((statements as any)[0].func.body.statements[1].text).to.equal(`'comment 1`);
});
it('declaration-level', () => {
let { tokens } = Lexer.scan(`
'comment 1
function a()
end function
'comment 2
`);
let { diagnostics, statements } = Parser.parse(tokens);
expect(diagnostics).to.be.lengthOf(0, 'Error count should be 0');
expect((statements as any)[0].text).to.equal(`'comment 1`);
expect((statements as any)[2].text).to.equal(`'comment 2`);
});
it('works in aa literal as its own statement', () => {
let { tokens } = Lexer.scan(`
obj = {
"name": true,
'comment
}
`);
let { diagnostics } = Parser.parse(tokens);
expect(diagnostics).to.be.lengthOf(0, 'Error count should be 0');
});
it('parses after function call', () => {
let { tokens } = Lexer.scan(`
sub Main()
name = "Hello"
DoSomething(name) 'comment 1
end sub
`);
let { diagnostics, statements } = Parser.parse(tokens) as any;
expect(diagnostics).to.be.lengthOf(0, 'Should have zero diagnostics');
expect(statements[0].func.body.statements[2].text).to.equal(`'comment 1`);
});
it('function', () => {
let { tokens } = Lexer.scan(`
function a() 'comment 1
'comment 2
num = 1
'comment 3
end function 'comment 4
`);
let { diagnostics, statements } = Parser.parse(tokens) as any;
expect(diagnostics).to.be.lengthOf(0, 'Should have zero diagnostics');
expect(statements[0].func.body.statements[0].text).to.equal(`'comment 1`);
expect(statements[0].func.body.statements[1].text).to.equal(`'comment 2`);
expect(statements[0].func.body.statements[3].text).to.equal(`'comment 3`);
expect(statements[1].text).to.equal(`'comment 4`);
});
it('if statement`', () => {
let { tokens } = Lexer.scan(`
function a()
if true then 'comment 1
'comment 2
print "hello"
'comment 3
else if true then 'comment 4
'comment 5
print "hello"
'comment 6
else 'comment 7
'comment 8
print "hello"
'comment 9
end if 'comment 10
end function
`);
let { diagnostics, statements } = Parser.parse(tokens);
expect(diagnostics).to.be.lengthOf(0, 'Should have zero diagnostics');
let fnSmt = statements[0];
if (isFunctionStatement(fnSmt)) {
let ifStmt = fnSmt.func.body.statements[0];
if (isIfStatement(ifStmt)) {
expectCommentWithText(ifStmt.thenBranch.statements[0], `'comment 1`);
expectCommentWithText(ifStmt.thenBranch.statements[1], `'comment 2`);
expectCommentWithText(ifStmt.thenBranch.statements[3], `'comment 3`);
let elseIfBranch = ifStmt.elseBranch!;
if (isIfStatement(elseIfBranch)) {
expectCommentWithText(elseIfBranch.thenBranch.statements[0], `'comment 4`);
expectCommentWithText(elseIfBranch.thenBranch.statements[1], `'comment 5`);
expectCommentWithText(elseIfBranch.thenBranch.statements[3], `'comment 6`);
let elseBranch = elseIfBranch.elseBranch!;
if (isBlock(elseBranch)) {
expectCommentWithText(elseBranch.statements[0], `'comment 7`);
expectCommentWithText(elseBranch.statements[1], `'comment 8`);
expectCommentWithText(elseBranch.statements[3], `'comment 9`);
} else {
failStatementType(elseBranch, 'Block');
}
} else {
failStatementType(elseIfBranch, 'If');
}
expectCommentWithText(fnSmt.func.body.statements[1], `'comment 10`);
} else {
failStatementType(ifStmt, 'If');
}
} else {
failStatementType(fnSmt, 'Function');
}
});
it('while', () => {
let { tokens } = Lexer.scan(`
function a()
while true 'comment 1
'comment 2
print "true"
'comment 3
end while 'comment 4
end function
`);
let { diagnostics, statements } = Parser.parse(tokens) as any;
expect(diagnostics).to.be.lengthOf(0, 'Error count should be zero');
let stmt = statements[0].func.body.statements[0];
expect(stmt.body.statements[0].text).to.equal(`'comment 1`);
expect(stmt.body.statements[1].text).to.equal(`'comment 2`);
expect(stmt.body.statements[3].text).to.equal(`'comment 3`);
expect(statements[0].func.body.statements[1].text).to.equal(`'comment 4`);
});
it('for', () => {
let { tokens } = Lexer.scan(`
function a()
for i = 0 to 10 step 1 'comment 1
'comment 2
print 1
'comment 3
end for 'comment 4
end function
`);
let { diagnostics, statements } = Parser.parse(tokens) as any;
expect(diagnostics).to.be.lengthOf(0, 'Error count should be zero');
let stmt = statements[0].func.body.statements[0];
expect(stmt.body.statements[0].text).to.equal(`'comment 1`);
expect(stmt.body.statements[1].text).to.equal(`'comment 2`);
expect(stmt.body.statements[3].text).to.equal(`'comment 3`);
expect(statements[0].func.body.statements[1].text).to.equal(`'comment 4`);
});
it('for each', () => {
let { tokens } = Lexer.scan(`
function a()
for each val in [1,2,3] 'comment 1
'comment 2
print 1
'comment 3
end for 'comment 4
end function
`);
let { diagnostics, statements } = Parser.parse(tokens) as any;
expect(diagnostics).to.be.lengthOf(0, 'Error count should be zero');
let stmt = statements[0].func.body.statements[0];
expect(stmt.body.statements[0].text).to.equal(`'comment 1`);
expect(stmt.body.statements[1].text).to.equal(`'comment 2`);
expect(stmt.body.statements[3].text).to.equal(`'comment 3`);
expect(statements[0].func.body.statements[1].text).to.equal(`'comment 4`);
});
});
});
describe('reservedWords', () => {
describe('`then`', () => {
it('is not allowed as a local identifier', () => {
let { diagnostics } = parse(`
sub main()
then = true
end sub
`);
expect(diagnostics).to.be.lengthOf(1);
});
it('is allowed as an AA property name', () => {
let { diagnostics } = parse(`
sub main()
person = {
then: true
}
person.then = false
print person.then
end sub
`);
expect(diagnostics[0]?.message).not.to.exist;
});
it('allows `mod` as an AA literal property', () => {
const parser = parse(`
sub main()
person = {
mod: true
}
person.mod = false
print person.mod
end sub
`);
expectZeroDiagnostics(parser);
});
it('converts aa literal property TokenKind to Identifier', () => {
const parser = parse(`
sub main()
person = {
mod: true
and: true
}
end sub
`);
expectZeroDiagnostics(parser);
const elements = [] as AAMemberExpression[];
parser.ast.walk(createVisitor({
AAMemberExpression: (node) => {
elements.push(node as any);
}
}), {
walkMode: WalkMode.visitAllRecursive
});
expect(
elements.map(x => x.keyToken.kind)
).to.eql(
[TokenKind.Identifier, TokenKind.Identifier]
);
});
});
it('"end" is not allowed as a local identifier', () => {
let { diagnostics } = parse(`
sub main()
end = true
end sub
`);
expect(diagnostics).to.be.length.greaterThan(0);
});
it('none of them can be used as local variables', () => {
let reservedWords = new Set(ReservedWords);
//remove the rem keyword because it's a comment...won't cause error
reservedWords.delete('rem');
for (let reservedWord of reservedWords) {
let { tokens } = Lexer.scan(`
sub main()
${reservedWord} = true
end sub
`);
let { diagnostics } = Parser.parse(tokens);
expect(diagnostics, `assigning to reserved word "${reservedWord}" should have been an error`).to.be.length.greaterThan(0);
}
});
});
describe('import keyword', () => {
it('parses without errors', () => {
let { statements, diagnostics } = parse(`
import "somePath"
`, ParseMode.BrighterScript);
expect(diagnostics[0]?.message).not.to.exist;
expect(statements[0]).to.be.instanceof(ImportStatement);
});
it('catches import statements used in brightscript files', () => {
let { statements, diagnostics } = parse(`
import "somePath"
`, ParseMode.BrightScript);
expect(diagnostics[0]?.message).to.eql(
DiagnosticMessages.bsFeatureNotSupportedInBrsFiles('import statements').message
);
expect(statements[0]).to.be.instanceof(ImportStatement);
});
it('catchs missing file path', () => {
let { statements, diagnostics } = parse(`
import
`, ParseMode.BrighterScript);
expect(diagnostics[0]?.message).to.equal(
DiagnosticMessages.expectedStringLiteralAfterKeyword('import').message
);
expect(statements[0]).to.be.instanceof(ImportStatement);
});
});
describe('Annotations', () => {
it('parses with error if malformed', () => {
let { diagnostics } = parse(`
@
sub main()
end sub
`, ParseMode.BrighterScript);
expect(diagnostics[0]?.message).to.equal(DiagnosticMessages.unexpectedToken('@').message);
});
it('properly handles empty annotation above class method', () => {
//this code used to cause an infinite loop, so the fact that the test passes/fails on its own is a success!
let { diagnostics } = parse(`
class Person
@
sub new()
end sub
end class
`, ParseMode.BrighterScript);
expect(diagnostics[0]?.message).to.equal(DiagnosticMessages.expectedIdentifier().message);
});
it('parses with error if annotation is not followed by a statement', () => {
let { diagnostics } = parse(`
sub main()
@meta2
end sub
class MyClass
@meta3
@meta4
end class
@meta1
`, ParseMode.BrighterScript);
expect(diagnostics.length).to.equal(4);
expect(diagnostics[0]?.message).to.equal(
DiagnosticMessages.unusedAnnotation().message
);