-
Notifications
You must be signed in to change notification settings - Fork 29.8k
/
tap_parser.js
980 lines (825 loc) Β· 27.9 KB
/
tap_parser.js
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
'use strict';
const Transform = require('internal/streams/transform');
const { TapLexer, TokenKind } = require('internal/test_runner/tap_lexer');
const { TapChecker } = require('internal/test_runner/tap_checker');
const {
codes: { ERR_TAP_VALIDATION_ERROR, ERR_TAP_PARSER_ERROR },
} = require('internal/errors');
const { kEmptyObject } = require('internal/util');
const {
ArrayPrototypeFilter,
ArrayPrototypeForEach,
ArrayPrototypeJoin,
ArrayPrototypeMap,
ArrayPrototypePush,
ArrayPrototypeIncludes,
ArrayPrototypeSplice,
Boolean,
Number,
RegExpPrototypeExec,
RegExpPrototypeSymbolReplace,
String,
StringPrototypeTrim,
StringPrototypeSplit,
} = primordials;
/**
*
* TAP14 specifications
*
* See https://testanything.org/tap-version-14-specification.html
*
* Note that the following grammar is intended as a rough "pseudocode" guidance.
* It is not strict EBNF:
*
* TAPDocument := Version Plan Body | Version Body Plan
* Version := "TAP version 14\n"
* Plan := "1.." (Number) (" # " Reason)? "\n"
* Body := (TestPoint | BailOut | Pragma | Comment | Anything | Empty | Subtest)*
* TestPoint := ("not ")? "ok" (" " Number)? ((" -")? (" " Description) )? (" " Directive)? "\n" (YAMLBlock)?
* Directive := " # " ("todo" | "skip") (" " Reason)?
* YAMLBlock := " ---\n" (YAMLLine)* " ...\n"
* YAMLLine := " " (YAML)* "\n"
* BailOut := "Bail out!" (" " Reason)? "\n"
* Reason := [^\n]+
* Pragma := "pragma " [+-] PragmaKey "\n"
* PragmaKey := ([a-zA-Z0-9_-])+
* Subtest := ("# Subtest" (": " SubtestName)?)? "\n" SubtestDocument TestPoint
* Comment := ^ (" ")* "#" [^\n]* "\n"
* Empty := [\s\t]* "\n"
* Anything := [^\n]+ "\n"
*
*/
/**
* An LL(1) parser for TAP14/TAP13.
*/
class TapParser extends Transform {
#checker = null;
#lexer = null;
#currentToken = null;
#input = '';
#currentChunkAsString = '';
#lastLine = '';
#tokens = [[]];
#flatAST = [];
#bufferedComments = [];
#bufferedTestPoints = [];
#lastTestPointDetails = {};
#yamlBlockBuffer = [];
#currentTokenIndex = 0;
#currentTokenChunk = 0;
#subTestNestingLevel = 0;
#yamlCurrentIndentationLevel = 0;
#kSubtestBlockIndentationFactor = 4;
#isYAMLBlock = false;
#isSyncParsingEnabled = false;
constructor({ specs = TapChecker.TAP13 } = kEmptyObject) {
super({ __proto__: null, readableObjectMode: true });
this.#checker = new TapChecker({ specs });
}
// ----------------------------------------------------------------------//
// ----------------------------- Public API -----------------------------//
// ----------------------------------------------------------------------//
parse(chunkAsString = '', callback = null) {
this.#isSyncParsingEnabled = false;
this.#currentTokenChunk = 0;
this.#currentTokenIndex = 0;
// Note: we are overwriting the input on each stream call
// This is fine because we don't want to parse previous chunks
this.#input = chunkAsString;
this.#lexer = new TapLexer(chunkAsString);
try {
this.#tokens = this.#scanTokens();
this.#parseTokens(callback);
} catch (error) {
callback(null, error);
}
}
parseSync(input = '', callback = null) {
if (typeof input !== 'string' || input === '') {
return [];
}
this.#isSyncParsingEnabled = true;
this.#input = input;
this.#lexer = new TapLexer(input);
this.#tokens = this.#scanTokens();
this.#parseTokens(callback);
if (this.#isYAMLBlock) {
// Looks like we have a non-ending YAML block
this.#error('Expected end of YAML block');
}
// Manually flush the remaining buffered comments and test points
this._flush();
return this.#flatAST;
}
// Check if the TAP content is semantically valid
// Note: Validating the TAP content requires the whole AST to be available.
check() {
if (this.#isSyncParsingEnabled) {
return this.#checker.check(this.#flatAST);
}
// TODO(@manekinekko): when running in async mode, it doesn't make sense to
// validate the current chunk. Validation needs to whole AST to be available.
throw new ERR_TAP_VALIDATION_ERROR(
'TAP validation is not supported for async parsing'
);
}
// ----------------------------------------------------------------------//
// --------------------------- Transform API ----------------------------//
// ----------------------------------------------------------------------//
processChunk(chunk) {
const str = this.#lastLine + chunk.toString('utf8');
const lines = StringPrototypeSplit(str, '\n');
this.#lastLine = ArrayPrototypeSplice(lines, lines.length - 1, 1)[0];
let chunkAsString = lines.join('\n');
// Special case where chunk is emitted by a child process
chunkAsString = RegExpPrototypeSymbolReplace(
/\[out\] /g,
chunkAsString,
''
);
chunkAsString = RegExpPrototypeSymbolReplace(
/\[err\] /g,
chunkAsString,
''
);
chunkAsString = RegExpPrototypeSymbolReplace(/\n$/, chunkAsString, '');
chunkAsString = RegExpPrototypeSymbolReplace(/EOF$/, chunkAsString, '');
return chunkAsString;
}
_transform(chunk, _encoding, next) {
const chunkAsString = this.processChunk(chunk);
if (!chunkAsString) {
// Ignore empty chunks
next();
return;
}
this.parse(chunkAsString, (node, error) => {
if (error) {
next(error);
return;
}
if (node.kind === TokenKind.EOF) {
// Emit when the current chunk is fully processed and consumed
next();
}
});
}
// Flush the remaining buffered comments and test points
// This will be called automatically when the stream is closed
// We also call this method manually when we reach the end of the sync parsing
_flush(next = null) {
if (!this.#lastLine) {
this.#__flushPendingTestPointsAndComments();
next?.();
return;
}
// Parse the remaining line
this.parse(this.#lastLine, (node, error) => {
this.#lastLine = '';
if (error) {
next?.(error);
return;
}
if (node.kind === TokenKind.EOF) {
this.#__flushPendingTestPointsAndComments();
next?.();
}
});
}
#__flushPendingTestPointsAndComments() {
ArrayPrototypeForEach(this.#bufferedTestPoints, (node) => {
this.#emit(node);
});
ArrayPrototypeForEach(this.#bufferedComments, (node) => {
this.#emit(node);
});
// Clean up
this.#bufferedTestPoints = [];
this.#bufferedComments = [];
}
// ----------------------------------------------------------------------//
// ----------------------------- Private API ----------------------------//
// ----------------------------------------------------------------------//
#scanTokens() {
return this.#lexer.scan();
}
#parseTokens(callback = null) {
for (let index = 0; index < this.#tokens.length; index++) {
const chunk = this.#tokens[index];
this.#parseChunk(chunk);
}
callback?.({ kind: TokenKind.EOF });
}
#parseChunk(chunk) {
this.#subTestNestingLevel = this.#getCurrentIndentationLevel(chunk);
// We compute the current index of the token in the chunk
// based on the indentation level (number of spaces).
// We also need to take into account if we are in a YAML block or not.
// If we are in a YAML block, we compute the current index of the token
// based on the indentation level of the YAML block (start block).
if (this.#isYAMLBlock) {
this.#currentTokenIndex =
this.#yamlCurrentIndentationLevel *
this.#kSubtestBlockIndentationFactor;
} else {
this.#currentTokenIndex =
this.#subTestNestingLevel * this.#kSubtestBlockIndentationFactor;
this.#yamlCurrentIndentationLevel = this.#subTestNestingLevel;
}
// Parse current chunk
const node = this.#TAPDocument(chunk);
// Emit the parsed node to both the stream and the AST
this.#emitOrBufferCurrentNode(node);
// Move pointers to the next chunk and reset the current token index
this.#currentTokenChunk++;
this.#currentTokenIndex = 0;
}
#error(message) {
if (!this.#isSyncParsingEnabled) {
// When async parsing is enabled, don't throw.
// Unrecognized tokens would be ignored.
return;
}
const token = this.#currentToken || { value: '', kind: '' };
// Escape NewLine characters
if (token.value === '\n') {
token.value = '\\n';
}
throw new ERR_TAP_PARSER_ERROR(
message,
`, received "${token.value}" (${token.kind})`,
token,
this.#input
);
}
#peek(shouldSkipBlankTokens = true) {
if (shouldSkipBlankTokens) {
this.#skip(TokenKind.WHITESPACE);
}
return this.#tokens[this.#currentTokenChunk][this.#currentTokenIndex];
}
#next(shouldSkipBlankTokens = true) {
if (shouldSkipBlankTokens) {
this.#skip(TokenKind.WHITESPACE);
}
if (this.#tokens[this.#currentTokenChunk]) {
this.#currentToken =
this.#tokens[this.#currentTokenChunk][this.#currentTokenIndex++];
} else {
this.#currentToken = null;
}
return this.#currentToken;
}
// Skip the provided tokens in the current chunk
#skip(...tokensToSkip) {
let token = this.#tokens[this.#currentTokenChunk][this.#currentTokenIndex];
while (token && ArrayPrototypeIncludes(tokensToSkip, token.kind)) {
// pre-increment to skip current tokens but make sure we don't advance index on the last iteration
token = this.#tokens[this.#currentTokenChunk][++this.#currentTokenIndex];
}
}
#readNextLiterals() {
const literals = [];
let nextToken = this.#peek(false);
// Read all literal, numeric, whitespace and escape tokens until we hit a different token
// or reach end of current chunk
while (
nextToken &&
ArrayPrototypeIncludes(
[
TokenKind.LITERAL,
TokenKind.NUMERIC,
TokenKind.DASH,
TokenKind.PLUS,
TokenKind.WHITESPACE,
TokenKind.ESCAPE,
],
nextToken.kind
)
) {
const word = this.#next(false).value;
// Don't output escaped characters
if (nextToken.kind !== TokenKind.ESCAPE) {
ArrayPrototypePush(literals, word);
}
nextToken = this.#peek(false);
}
return ArrayPrototypeJoin(literals, '');
}
#countLeadingSpacesInCurrentChunk(chunk) {
// Count the number of whitespace tokens in the chunk, starting from the first token
let whitespaceCount = 0;
while (chunk?.[whitespaceCount]?.kind === TokenKind.WHITESPACE) {
whitespaceCount++;
}
return whitespaceCount;
}
#addDiagnosticsToLastTestPoint(currentNode) {
const lastTestPoint = this.#bufferedTestPoints.at(-1);
// Diagnostic nodes are only added to Test points of the same nesting level
if (lastTestPoint && lastTestPoint.nesting === currentNode.nesting) {
lastTestPoint.node.time = this.#lastTestPointDetails.duration;
// TODO(@manekinekko): figure out where to put the other diagnostic properties
// See https://github.com/nodejs/node/pull/44952
lastTestPoint.node.diagnostics ||= [];
ArrayPrototypeForEach(currentNode.node.diagnostics, (diagnostic) => {
// Avoid adding empty diagnostics
if (diagnostic) {
ArrayPrototypePush(lastTestPoint.node.diagnostics, diagnostic);
}
});
this.#bufferedTestPoints = [];
}
return lastTestPoint;
}
#flushBufferedTestPointNode(shouldClearBuffer = true) {
if (this.#bufferedTestPoints.length > 0) {
this.#emit(this.#bufferedTestPoints.at(0));
if (shouldClearBuffer) {
this.#bufferedTestPoints = [];
}
}
}
#addCommentsToCurrentNode(currentNode) {
if (this.#bufferedComments.length > 0) {
currentNode.comments = ArrayPrototypeMap(
this.#bufferedComments,
(c) => c.node.comment
);
this.#bufferedComments = [];
}
return currentNode;
}
#flushBufferedComments(shouldClearBuffer = true) {
if (this.#bufferedComments.length > 0) {
ArrayPrototypeForEach(this.#bufferedComments, (node) => {
this.#emit(node);
});
if (shouldClearBuffer) {
this.#bufferedComments = [];
}
}
}
#getCurrentIndentationLevel(chunk) {
const whitespaceCount = this.#countLeadingSpacesInCurrentChunk(chunk);
return (whitespaceCount / this.#kSubtestBlockIndentationFactor) | 0;
}
#emit(node) {
if (node.kind !== TokenKind.EOF) {
ArrayPrototypePush(this.#flatAST, node);
this.push({
__proto__: null,
...node,
});
}
}
#emitOrBufferCurrentNode(currentNode) {
currentNode = {
...currentNode,
nesting: this.#subTestNestingLevel,
lexeme: this.#currentChunkAsString,
};
switch (currentNode.kind) {
// Emit these nodes
case TokenKind.UNKNOWN:
if (!currentNode.node.value) {
// Ignore unrecognized and empty nodes
break;
}
// Otherwise continue and process node
// eslint no-fallthrough
case TokenKind.TAP_PLAN:
case TokenKind.TAP_PRAGMA:
case TokenKind.TAP_VERSION:
case TokenKind.TAP_BAIL_OUT:
case TokenKind.TAP_SUBTEST_POINT:
// Check if we have a buffered test point, and if so, emit it
this.#flushBufferedTestPointNode();
// If we have buffered comments, add them to the current node
currentNode = this.#addCommentsToCurrentNode(currentNode);
// Emit the current node
this.#emit(currentNode);
break;
// By default, we buffer the next test point node in case we have a diagnostic
// to add to it in the next iteration
// Note: in case we hit and EOF, we flush the comments buffer (see _flush())
case TokenKind.TAP_TEST_POINT:
// In case of an already buffered test point, we flush it and buffer the current one
// Because diagnostic nodes are only added to the last processed test point
this.#flushBufferedTestPointNode();
// Buffer this node (and also add any pending comments to it)
ArrayPrototypePush(
this.#bufferedTestPoints,
this.#addCommentsToCurrentNode(currentNode)
);
break;
// Keep buffering comments until we hit a non-comment node, then add them to the that node
// Note: in case we hit and EOF, we flush the comments buffer (see _flush())
case TokenKind.COMMENT:
ArrayPrototypePush(this.#bufferedComments, currentNode);
break;
// Diagnostic nodes are added to Test points of the same nesting level
case TokenKind.TAP_YAML_END:
// Emit either the last updated test point (w/ diagnostics) or the current diagnostics node alone
this.#emit(
this.#addDiagnosticsToLastTestPoint(currentNode) || currentNode
);
break;
// In case we hit an EOF, we emit it to indicate the end of the stream
case TokenKind.EOF:
this.#emit(currentNode);
break;
}
}
#serializeChunk(chunk) {
return ArrayPrototypeJoin(
ArrayPrototypeMap(
// Exclude NewLine and EOF tokens
ArrayPrototypeFilter(
chunk,
(token) =>
token.kind !== TokenKind.NEWLINE && token.kind !== TokenKind.EOF
),
(token) => token.value
),
''
);
}
// --------------------------------------------------------------------------//
// ------------------------------ Parser rules ------------------------------//
// --------------------------------------------------------------------------//
// TAPDocument := Version Plan Body | Version Body Plan
#TAPDocument(tokenChunks) {
this.#currentChunkAsString = this.#serializeChunk(tokenChunks);
const firstToken = this.#peek(false);
if (firstToken) {
const { kind } = firstToken;
switch (kind) {
case TokenKind.TAP:
return this.#Version();
case TokenKind.NUMERIC:
return this.#Plan();
case TokenKind.TAP_TEST_OK:
case TokenKind.TAP_TEST_NOTOK:
return this.#TestPoint();
case TokenKind.COMMENT:
case TokenKind.HASH:
return this.#Comment();
case TokenKind.TAP_PRAGMA:
return this.#Pragma();
case TokenKind.WHITESPACE:
return this.#YAMLBlock();
case TokenKind.LITERAL:
// Check for "Bail out!" literal (case insensitive)
if (
RegExpPrototypeExec(/^Bail\s+out!/i, this.#currentChunkAsString)
) {
return this.#Bailout();
} else if (this.#isYAMLBlock) {
return this.#YAMLBlock();
}
// Read token because error needs the last token details
this.#next(false);
this.#error('Expected a valid token');
break;
case TokenKind.EOF:
return firstToken;
case TokenKind.NEWLINE:
// Consume and ignore NewLine token
return this.#next(false);
default:
// Read token because error needs the last token details
this.#next(false);
this.#error('Expected a valid token');
}
}
const node = {
kind: TokenKind.UNKNOWN,
node: {
value: this.#currentChunkAsString,
},
};
// We make sure the emitted node has the same shape
// both in sync and async parsing (for the stream interface)
return node;
}
// ----------------Version----------------
// Version := "TAP version Number\n"
#Version() {
const tapToken = this.#peek();
if (tapToken.kind === TokenKind.TAP) {
this.#next(); // Consume the TAP token
} else {
this.#error('Expected "TAP" keyword');
}
const versionToken = this.#peek();
if (versionToken?.kind === TokenKind.TAP_VERSION) {
this.#next(); // Consume the version token
} else {
this.#error('Expected "version" keyword');
}
const numberToken = this.#peek();
if (numberToken?.kind === TokenKind.NUMERIC) {
const version = this.#next().value;
const node = { kind: TokenKind.TAP_VERSION, node: { version } };
return node;
}
this.#error('Expected a version number');
}
// ----------------Plan----------------
// Plan := "1.." (Number) (" # " Reason)? "\n"
#Plan() {
// Even if specs mention plan starts at 1, we need to make sure we read the plan start value
// in case of a missing or invalid plan start value
const planStart = this.#next();
if (planStart.kind !== TokenKind.NUMERIC) {
this.#error('Expected a plan start count');
}
const planToken = this.#next();
if (planToken?.kind !== TokenKind.TAP_PLAN) {
this.#error('Expected ".." symbol');
}
const planEnd = this.#next();
if (planEnd?.kind !== TokenKind.NUMERIC) {
this.#error('Expected a plan end count');
}
const plan = {
start: planStart.value,
end: planEnd.value,
};
// Read optional reason
const hashToken = this.#peek();
if (hashToken) {
if (hashToken.kind === TokenKind.HASH) {
this.#next(); // skip hash
plan.reason = StringPrototypeTrim(this.#readNextLiterals());
} else if (hashToken.kind === TokenKind.LITERAL) {
this.#error('Expected "#" symbol before a reason');
}
}
const node = {
kind: TokenKind.TAP_PLAN,
node: plan,
};
return node;
}
// ----------------TestPoint----------------
// TestPoint := ("not ")? "ok" (" " Number)? ((" -")? (" " Description) )? (" " Directive)? "\n" (YAMLBlock)?
// Directive := " # " ("todo" | "skip") (" " Reason)?
// YAMLBlock := " ---\n" (YAMLLine)* " ...\n"
// YAMLLine := " " (YAML)* "\n"
// Test Status: ok/not ok (required)
// Test number (recommended)
// Description (recommended, prefixed by " - ")
// Directive (only when necessary)
#TestPoint() {
const notToken = this.#peek();
let isTestFailed = false;
if (notToken.kind === TokenKind.TAP_TEST_NOTOK) {
this.#next(); // skip "not" token
isTestFailed = true;
}
const okToken = this.#next();
if (okToken.kind !== TokenKind.TAP_TEST_OK) {
this.#error('Expected "ok" or "not ok" keyword');
}
// Read optional test number
let numberToken = this.#peek();
if (numberToken && numberToken.kind === TokenKind.NUMERIC) {
numberToken = this.#next().value;
} else {
numberToken = ''; // Set an empty ID to indicate that the test hasn't provider an ID
}
const test = {
// Output both failed and passed properties to make it easier for the checker to detect the test status
status: {
fail: isTestFailed,
pass: !isTestFailed,
todo: false,
skip: false,
},
id: numberToken,
description: '',
reason: '',
time: 0,
diagnostics: [],
};
// Read optional description prefix " - "
const descriptionDashToken = this.#peek();
if (descriptionDashToken && descriptionDashToken.kind === TokenKind.DASH) {
this.#next(); // skip dash
}
// Read optional description
if (this.#peek()) {
const description = StringPrototypeTrim(this.#readNextLiterals());
if (description) {
test.description = description;
}
}
// Read optional directive and reason
const hashToken = this.#peek();
if (hashToken && hashToken.kind === TokenKind.HASH) {
this.#next(); // skip hash
}
let todoOrSkipToken = this.#peek();
if (todoOrSkipToken && todoOrSkipToken.kind === TokenKind.LITERAL) {
if (RegExpPrototypeExec(/todo/i, todoOrSkipToken.value)) {
todoOrSkipToken = 'todo';
this.#next(); // skip token
} else if (RegExpPrototypeExec(/skip/i, todoOrSkipToken.value)) {
todoOrSkipToken = 'skip';
this.#next(); // skip token
}
}
const reason = StringPrototypeTrim(this.#readNextLiterals());
if (todoOrSkipToken) {
if (reason) {
test.reason = reason;
}
test.status.todo = todoOrSkipToken === 'todo';
test.status.skip = todoOrSkipToken === 'skip';
}
const node = {
kind: TokenKind.TAP_TEST_POINT,
node: test,
};
return node;
}
// ----------------Bailout----------------
// BailOut := "Bail out!" (" " Reason)? "\n"
#Bailout() {
this.#next(); // skip "Bail"
this.#next(); // skip "out!"
// Read optional reason
const hashToken = this.#peek();
if (hashToken && hashToken.kind === TokenKind.HASH) {
this.#next(); // skip hash
}
const reason = StringPrototypeTrim(this.#readNextLiterals());
const node = {
kind: TokenKind.TAP_BAIL_OUT,
node: { bailout: true, reason },
};
return node;
}
// ----------------Comment----------------
// Comment := ^ (" ")* "#" [^\n]* "\n"
#Comment() {
const commentToken = this.#next();
if (
commentToken.kind !== TokenKind.COMMENT &&
commentToken.kind !== TokenKind.HASH
) {
this.#error('Expected "#" symbol');
}
const commentContent = this.#peek();
if (commentContent) {
if (/^Subtest:/i.test(commentContent.value)) {
this.#next(); // skip subtest keyword
const name = StringPrototypeTrim(this.#readNextLiterals());
const node = {
kind: TokenKind.TAP_SUBTEST_POINT,
node: {
name,
},
};
return node;
}
const comment = StringPrototypeTrim(this.#readNextLiterals());
const node = {
kind: TokenKind.COMMENT,
node: { comment },
};
return node;
}
// If there is no comment content, then we ignore the current node
}
// ----------------YAMLBlock----------------
// YAMLBlock := " ---\n" (YAMLLine)* " ...\n"
#YAMLBlock() {
const space1 = this.#peek(false);
if (space1 && space1.kind === TokenKind.WHITESPACE) {
this.#next(false); // skip 1st space
}
const space2 = this.#peek(false);
if (space2 && space2.kind === TokenKind.WHITESPACE) {
this.#next(false); // skip 2nd space
}
const yamlBlockSymbol = this.#peek(false);
if (yamlBlockSymbol.kind === TokenKind.WHITESPACE) {
if (this.#isYAMLBlock === false) {
this.#next(false); // skip 3rd space
this.#error('Expected valid YAML indentation (2 spaces)');
}
}
if (yamlBlockSymbol.kind === TokenKind.TAP_YAML_START) {
if (this.#isYAMLBlock) {
// Looks like we have another YAML start block, but we didn't close the previous one
this.#error('Unexpected YAML start marker');
}
this.#isYAMLBlock = true;
this.#yamlCurrentIndentationLevel = this.#subTestNestingLevel;
this.#lastTestPointDetails = {};
// Consume the YAML start marker
this.#next(false); // skip "---"
// No need to pass this token to the stream interface
return;
} else if (yamlBlockSymbol.kind === TokenKind.TAP_YAML_END) {
this.#next(false); // skip "..."
if (!this.#isYAMLBlock) {
// Looks like we have an YAML end block, but we didn't encounter any YAML start marker
this.#error('Unexpected YAML end marker');
}
this.#isYAMLBlock = false;
const diagnostics = this.#yamlBlockBuffer;
this.#yamlBlockBuffer = []; // Free the buffer for the next YAML block
const node = {
kind: TokenKind.TAP_YAML_END,
node: {
diagnostics,
},
};
return node;
}
if (this.#isYAMLBlock) {
this.#YAMLLine();
} else {
return {
kind: TokenKind.UNKNOWN,
node: {
value: yamlBlockSymbol.value,
},
};
}
}
// ----------------YAMLLine----------------
// YAMLLine := " " (YAML)* "\n"
#YAMLLine() {
const yamlLiteral = this.#readNextLiterals();
const { 0: key, 1: value } = StringPrototypeSplit(yamlLiteral, ':');
// Note that this.#lastTestPointDetails has been cleared when we encounter a YAML start marker
switch (key) {
case 'duration_ms':
this.#lastTestPointDetails.duration = Number(value);
break;
// Below are diagnostic properties introduced in https://github.com/nodejs/node/pull/44952
case 'expected':
this.#lastTestPointDetails.expected = Boolean(value);
break;
case 'actual':
this.#lastTestPointDetails.actual = Boolean(value);
break;
case 'operator':
this.#lastTestPointDetails.operator = String(value);
break;
}
ArrayPrototypePush(this.#yamlBlockBuffer, yamlLiteral);
}
// ----------------PRAGMA----------------
// Pragma := "pragma " [+-] PragmaKey "\n"
// PragmaKey := ([a-zA-Z0-9_-])+
// TODO(@manekinekko): pragmas are parsed but not used yet! TapChecker() should take care of that.
#Pragma() {
const pragmaToken = this.#next();
if (pragmaToken.kind !== TokenKind.TAP_PRAGMA) {
this.#error('Expected "pragma" keyword');
}
const pragmas = {};
let nextToken = this.#peek();
while (
nextToken &&
ArrayPrototypeIncludes(
[TokenKind.NEWLINE, TokenKind.EOF, TokenKind.EOL],
nextToken.kind
) === false
) {
let isEnabled = true;
const pragmaKeySign = this.#next();
if (pragmaKeySign.kind === TokenKind.PLUS) {
isEnabled = true;
} else if (pragmaKeySign.kind === TokenKind.DASH) {
isEnabled = false;
} else {
this.#error('Expected "+" or "-" before pragma keys');
}
const pragmaKeyToken = this.#peek();
if (pragmaKeyToken.kind !== TokenKind.LITERAL) {
this.#error('Expected pragma key');
}
let pragmaKey = this.#next().value;
// In some cases, pragma key can be followed by a comma separator,
// so we need to remove it
pragmaKey = RegExpPrototypeSymbolReplace(/,/g, pragmaKey, '');
pragmas[pragmaKey] = isEnabled;
nextToken = this.#peek();
}
const node = {
kind: TokenKind.TAP_PRAGMA,
node: {
pragmas,
},
};
return node;
}
}
module.exports = { TapParser };