forked from DanielXMoore/Civet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.hera
7809 lines (6841 loc) · 217 KB
/
parser.hera
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
# Civet: A successor to CoffeeScript and alternative to TypeScript
# much more 1-to-1 with es6
# ECMA Reference
# https://262.ecma-international.org/13.0/
```
import {
addPostfixStatement,
adjustBindingElements,
adjustIndexAccess,
attachPostfixStatementAsExpression,
blockWithPrefix,
convertNamedImportsToObject,
convertObjectToJSXAttributes,
dedentBlockString,
dedentBlockSubstitutions,
deepCopy,
dynamizeImportDeclaration,
dynamizeImportDeclarationExpression,
expressionizeTypeIf,
forRange,
gatherBindingCode,
gatherRecursive,
getHelperRef,
getIndentLevel,
getPrecedence,
getTrimmingSpace,
hasAwait,
hasYield,
insertTrimmingSpace,
isEmptyBareBlock,
isWhitespaceOrEmpty,
lastAccessInCallExpression,
literalValue,
makeAmpersandFunction,
makeEmptyBlock,
makeExpressionStatement,
makeGetterMethod,
makeLeftHandSideExpression,
makeRef,
maybeRef,
maybeRefAssignment,
modifyString,
negateCondition,
prepend,
processAssignmentDeclaration,
processBinaryOpExpression,
processCallMemberExpression,
processCoffeeInterpolation,
processForInOf,
processProgram,
processProgramAsync,
processTryBlock,
processUnaryExpression,
quoteString,
reorderBindingRestProperty,
replaceNodes,
skipImplicitArguments,
typeOfJSX,
} from "./parser/lib.civet"
/**
* Globals
*/
let filename; // filename currently being parsed
let initialConfig; // input for parser config
let config; // current parser config after directives
let sync; // synchronous mode: as much as possible without await
export const state = {}; // parser state
export const getState = () => state;
export const getConfig = () => config;
export const getInitialConfig = () => initialConfig;
export const getFilename = () => filename;
export const getSync = () => sync;
Object.defineProperties(state, {
currentIndent: {
get() {
const {indentLevels: l} = state
return l[l.length-1]
},
},
classImplicitCallForbidden: {
get() {
const {forbidClassImplicitCall: s} = state
return s[s.length-1]
},
},
indentedApplicationForbidden: {
get() {
const {forbidIndentedApplication: s} = state
return s[s.length-1]
},
},
bracedApplicationForbidden: {
get() {
const {forbidBracedApplication: s} = state
return s[s.length-1]
},
},
trailingMemberPropertyForbidden: {
get() {
const {forbidTrailingMemberProperty: s} = state
return s[s.length-1]
},
},
newlineBinaryOpForbidden: {
get() {
const {forbidNewlineBinaryOp: s} = state
return s[s.length-1]
},
},
currentJSXTag: {
get() {
const {JSXTagStack: s} = state
return s[s.length-1]
},
},
})
export function parseProgram(input, options) {
filename = options?.filename
initialConfig = options?.parseOptions
sync = options?.sync
const root = parse(input, options)
if (sync) {
filename = initialConfig = sync = null
return root
} else {
return processProgramAsync(root)
.then(() => {
filename = initialConfig = sync = null
return root
})
}
}
```
Program
# EOS allows for initial comment blocks and newlines,
# when Init didn't already consume them.
Reset:reset Init:init EOS?:ws1 TopLevelStatements:statements __:ws2 ->
// NOTE: Wrap top level statements in a bare block so they have a parent
const program = {
type: "BlockStatement",
expressions: statements,
children: [reset, init, ws1, statements, ws2],
bare: true,
root: true,
}
processProgram(program)
return program
TopLevelStatements
# If first line is strictly indented, require all lines to be equally so
# Use TrackIndented instead of PushIndent to avoid requiring leading EOS
TrackIndented:indent TopLevelSingleLineStatements:first NestedTopLevelStatements*:rest PopIndent ->
return [
[indent, ...first[0]],
...first.slice(1).map(s => ["", ...s]),
...rest.flat(),
]
# Unindented case: rely on initial indentLevel of 0
TopLevelSingleLineStatements:first NestedTopLevelStatements*:rest ->
return [
...first.map(s => ["", ...s]),
...rest.flat(),
]
# Empty case
"" -> []
NestedTopLevelStatements
Nested:nested TopLevelSingleLineStatements:statements ->
return [
[nested, ...statements[0]],
...statements.slice(1).map(s => ["", ...s]),
]
# Multiple top-level semicolon-separated statements
TopLevelSingleLineStatements
TopLevelStatement+
TopLevelStatement
# NOTE: !EOS forces semicolon after all but last statement, forbids leading __
# NOTE: _? allows for leading inline comments
!EOS _?:ws ModuleItem:statement StatementDelimiter:delimiter ->
statement = prepend(ws, statement)
return [statement, delimiter]
# Expressions with comma operator, or expressions with If and Switch
ExtendedCommaExpression
NonAssignmentExtendedExpression
CommaExpression
# Expressions with If and Switch, but no comma operator
ExtendedExpression
NonAssignmentExtendedExpression
AssignmentExpression
SingleLineExtendedExpression
NonAssignmentExtendedExpression
SingleLineAssignmentExpression
NonPipelineExtendedExpression
NonAssignmentExtendedExpression
NonPipelineAssignmentExpression
NonAssignmentExtendedExpression
# Check for nested expressionized statements first
NestedNonAssignmentExtendedExpression
__ ExpressionizedStatementWithTrailingCallExpressions ->
return prepend($1, $2)
NestedNonAssignmentExtendedExpression
&EOS PushIndent ( Nested ExpressionizedStatementWithTrailingCallExpressions )?:expression PopIndent AllowedTrailingCallExpressions?:trailing ->
if (!expression) return $skip
if (!trailing) return expression
return {
type: "CallExpression",
children: [ expression, ...trailing.flat() ]
}
ExpressionizedStatementWithTrailingCallExpressions
ExpressionizedStatement AllowedTrailingCallExpressions? ->
if (!$2) return $1
// Some expressionized statements, such as `if`s,
// need to be wrapped in parens
return {
type: "CallExpression",
children: [
makeLeftHandSideExpression($1),
$2,
],
}
ExpressionizedStatement
# perf: assertion to exit early
/(?=async|debugger|if|unless|comptime|do|for|loop|until|while|switch|throw|try)/ StatementExpression:statement ->
return {
type: "StatementExpression",
statement,
children: [statement],
}
StatementExpression
DebuggerStatement
IfStatement ->
// Forbid expressionizing `if condition` with no then or else clause,
// because it might be a postfix `if`
if (!$1.else && isEmptyBareBlock($1.then)) return $skip
return $1
IterationExpression ->
// Forbid expressionizing `while condition` with no block,
// because it might be a postfix `while`
if (isEmptyBareBlock($1.block)) return $skip
return $1
SwitchStatement
ThrowStatement
TryStatement
# https://262.ecma-international.org/#prod-Expression
CommaExpression
# CommaOperator
# https://262.ecma-international.org/#sec-comma-operator
# NOTE: Eliminated left recursion
AssignmentExpression ( CommaDelimiter AssignmentExpression )* ->
if($2.length == 0) return $1
return $0
# https://262.ecma-international.org/#prod-Arguments
Arguments
ExplicitArguments
# Space / indentation based function application
# Function application:
# a b => a(b)
# a b, c, d => a(b, c, d)
# x y z => x(y(z))
ForbidTrailingMemberProperty ImplicitArguments?:args RestoreTrailingMemberProperty ->
if (args) return args
return $skip
ImplicitArguments
ApplicationStart InsertOpenParen:open Trimmed_?:ws NonPipelineArgumentList:args InsertCloseParen:close ->
// Don't treat as call if this is a postfix for/while/until/if/unless
if (skipImplicitArguments(args)) return $skip
return {
type: "Call",
args,
children: [open, ws, args, close]
}
ExplicitArguments
OpenParen:open ( ArgumentList ( __ Comma )? )?:args __:ws CloseParen:close ->
if (args) {
if (args[1]) { // trailing comma
args = [ ...args[0], args[1] ]
} else { // no trailing comma
args = args[0]
}
} else { // no arguments
args = []
}
return {
type: "Call",
args,
children: [open, args, ws, close],
}
# Start of function application, inserts an open parenthesis, maintains spacing and comments when possible
ApplicationStart
IndentedApplicationAllowed &( IndentedFurther !IdentifierBinaryOp !AccessStart )
!EOS &( _ ( BracedApplicationAllowed / !"{" ) !ForbiddenImplicitCalls )
ForbiddenImplicitCalls
# Reserved words that prevent spaced implicit function application
# eg: the 'of' in 'for x of ...'
ReservedBinary
# NOTE: Don't allow non-heregex regexes that begin with a space as first argument without parens
"/ "
# NOTE: Exclude binary & operator with argument
# (which could otherwise be interpreted as an ampersand function)
&( /&(?=\s)/ !( NotDedented ( Ampersand / ReservedBinary ) ) ( IndentedFurther / !EOS ) ) BinaryOpRHS
# Don't treat @@decorator @@decorator class ... as implicit calls
ClassImplicitCallForbidden ( Class / AtAt )
Identifier "=" Whitespace
# NOTE: Custom operators created via `operator`
Identifier:id !"(" ->
if (state.operators.has(id.name)) return $0
return $skip
OmittedNegation _? Identifier:id ->
if (state.operators.has(id.name)) return $0
return $skip
PostfixStatement EmptyStatementBareBlock
# `x ... y` is reserved for a range, but `x ...y` is an implicit call
"... "
# Binary operators that are reserved in that context
ReservedBinary
/(as|of|satisfies|then|when|implements|xor|xnor)(?!\p{ID_Continue}|[\u200C\u200D$])/
ArgumentsWithTrailingMemberExpressions
Arguments:args AllowedTrailingMemberExpressions:trailing ->
return [ args, ...trailing ]
TrailingMemberExpressions
# NOTE: Assert "." to not match "?" or "!" as a member expression on the following line
MemberExpressionRest* ( IndentedAtLeast &( "?"? "." ![0-9] ) MemberExpressionRest )* ->
return $1.concat($2.map(([ws, , memberExpressionRest]) => {
if (Array.isArray(memberExpressionRest)) {
return [ws, ...memberExpressionRest]
}
return {
...memberExpressionRest,
children: [ws, ...memberExpressionRest.children]
}
}))
AllowedTrailingMemberExpressions
TrailingMemberPropertyAllowed TrailingMemberExpressions -> $2
MemberExpressionRest*
TrailingCallExpressions
# NOTE: Assert "." to not match "?" or "!" or string literal
# as a call expression on the following line
( IndentedAtLeast &( "?"? "." ![0-9] ) CallExpressionRest+ )+
AllowedTrailingCallExpressions
TrailingMemberPropertyAllowed TrailingCallExpressions -> $2
CommaDelimiter
NotDedented Comma
# https://262.ecma-international.org/#prod-ArgumentList
# NOTE: Return value should always be an array alternating
# argument, comma, argument, comma, ..., argument, [comma],
# where each comma is a Comma token or an array [whitespace, commaToken]
# (like CommaDelimiter)
ArgumentList
# Check for same line arguments then nested arguments
ArgumentPart ( CommaDelimiter !EOS _? ArgumentPart )* ( CommaDelimiter ( NestedImplicitObjectLiteral / NestedArgumentList ) )+ ->
return [
$1,
...$2.flatMap(([comma, eos, ws, arg]) => [comma, prepend(ws, arg)]),
...$3.flatMap(([comma, args]) =>
Array.isArray(args) ? [comma, ...args] : [comma, args]
),
]
# NOTE: Added nested arguments on separate new lines
NestedImplicitObjectLiteral ->
return [ insertTrimmingSpace($1, '') ]
NestedArgumentList
# NOTE: Eliminated left recursion
_? ArgumentPart ( CommaDelimiter _? ArgumentPart )* ->
return [
prepend($1, $2),
...$3.flatMap(([comma, ws, arg]) => [comma, prepend(ws, arg)]),
]
# NOTE: ArgumentList variant that forbids top-level pipeline operators
NonPipelineArgumentList
# Check for same line arguments then nested arguments
NonPipelineArgumentPart ( CommaDelimiter !EOS _? NonPipelineArgumentPart )* ( CommaDelimiter ( NestedImplicitObjectLiteral / NestedArgumentList ) )+ ->
return [
$1,
...$2.flatMap(([comma, eos, ws, arg]) => [comma, prepend(ws, arg)]),
...$3.flatMap(([comma, args]) =>
Array.isArray(args) ? [comma, ...args] : [comma, args]
)
]
# NOTE: Added nested arguments on separate new lines
NestedImplicitObjectLiteral ->
return [ insertTrimmingSpace($1, '') ]
NestedArgumentList
# NOTE: Eliminated left recursion
_? NonPipelineArgumentPart ( CommaDelimiter _? NonPipelineArgumentPart )* ->
return [
prepend($1, $2),
...$3.flatMap(([comma, ws, arg]) => [comma, prepend(ws, arg)]),
]
NestedArgumentList
PushIndent NestedArgument*:args PopIndent ->
if (!args.length) return $skip
return args.flat()
NestedArgument
Nested:indent SingleLineArgumentExpressions:args ParameterElementDelimiter:comma ->
// Attach indentation to first argument in SingleLineArgumentExpressions
let [ arg0, ...rest ] = args
arg0 = [ indent, ...arg0 ]
return [ arg0, ...rest, comma ]
SingleLineArgumentExpressions
( _? ArgumentPart ) ( ( _? Comma ) ( _? ArgumentPart ) )* ->
return [ $1, ...$2.flat() ]
ArgumentPart
# NOTE: Using ExtendedExpression to allow for If/Switch expressions
# NOTE: Allow leading or trailing dots for argument splats like CoffeeScript
DotDotDot ExtendedExpression
ExtendedExpression DotDotDot? ->
if ($2) {
return [$2, $1]
}
return $1
# NOTE: ArgumentPart variant that forbids top-level pipeline operators
NonPipelineArgumentPart
DotDotDot NonPipelineExtendedExpression
NonPipelineExtendedExpression DotDotDot? ->
if ($2) {
return [$2, $1]
}
return $1
BinaryOpExpression
UnaryExpression BinaryOpRHS* ->
if (!$2.length) return $1
return processBinaryOpExpression($0)
BinaryOpRHS
( _? / IndentedFurther / Nested ):ws1 IsLike:op _?:ws2 PatternExpressionList:patterns ->
return [ ws1, op, ws2, patterns ]
# Snug binary ops a+b
BinaryOp:op RHS:rhs ->
// Insert empty whitespace placeholder to maintan structure
return [[], op, [], rhs]
# Spaced binary ops a + b
# a
# + b
# Does not match
# a
# +b
NewlineBinaryOpAllowed NotDedentedBinaryOp:op WRHS:rhs ->
// NOTE: Flatten NotDedentedBinaryOp into whitespace and operator
return [...op, ...rhs]
!NewlineBinaryOpAllowed SingleLineBinaryOpRHS -> $2
IsLike
Is _? ( Not _? )?:not Like ->
return {
type: "PatternTest",
children: $0,
special: true,
negated: !!not,
}
# Whitespace followed by RHS
WRHS
PushIndent ( Nested RHS )?:wrhs PopIndent ->
if (!wrhs) return $skip
return wrhs
( _ / ( EOS __ )) RHS
SingleLineBinaryOpRHS
# NOTE: It's named single line but that's only for the operator, the RHS can be after a newline
# This is to maintain compatibility with CoffeeScript conditions
_?:ws1 BinaryOp:op ( _ / ( EOS __ ) ):ws2 RHS:rhs ->
return [ws1 || [], op, ws2, rhs]
RHS
# NOTE: Check for comptime block first, to avoid matching as function call
ExpressionizedStatementWithTrailingCallExpressions
UnaryExpression
# https://262.ecma-international.org/#prod-UnaryExpression
UnaryExpression
# NOTE: Merged AwaitExpression with UnaryOp
# https://262.ecma-international.org/#prod-AwaitExpression
# NOTE: Eliminated left recursion
UnaryOp*:pre UnaryBody:exp UnaryPostfix?:post ->
return processUnaryExpression(pre, exp, post)
# NOTE: This is a little hacky to match CoffeeScript's behavior
# https://coffeescript.org/#try:do%20x%20%2B%20y%0Ado%20x%20%3D%20y%0Ado%20-%3E%20x%20%3D%201
CoffeeDoEnabled Do __:ws ( ( LeftHandSideExpression !( __ AssignmentOpSymbol ) ) / ArrowFunction / ExtendedExpression ):exp ->
ws = insertTrimmingSpace(ws, "")
return ["(", ...ws, exp, ")()"]
UnaryWithoutParenthesizedAssignment
UnaryOp*:pre UnaryWithoutParenthesizedAssignmentBody:exp UnaryPostfix?:post ->
return processUnaryExpression(pre, exp, post)
UnaryBody
ParenthesizedAssignment
UpdateExpression
ExpressionizedStatementWithTrailingCallExpressions
NestedNonAssignmentExtendedExpression
UnaryWithoutParenthesizedAssignmentBody
UpdateExpression
ExpressionizedStatementWithTrailingCallExpressions
NestedNonAssignmentExtendedExpression
# NOTE: Parts of AssignmentExpression (specifically AssignmentExpressionTail)
# that make sense as a UnaryBody, e.g. as the RHS of a binary op like `??`
ParenthesizedAssignment
InsertOpenParen ( ActualAssignment / ArrowFunction ) InsertCloseParen
UnaryPostfix
QuestionMark
TypePostfix+
TypePostfix
_:ws NWTypePostfix:postfix ->
return prepend(ws, postfix)
Tuple
"tuple" NonIdContinue ->
return {
$loc,
token: "readonly unknown[] | []"
}
NWTypePostfix
As _ Tuple ->
return {
ts: true,
children: [{ $loc: $1.$loc, token: "satisfies" }, $2, $3]
}
As:as ExclamationPoint?:ex Type:type ->
let children
if (ex) {
children = [{ $loc: ex.$loc, token: "as unknown " }, as, type]
} else {
children = [as, type]
}
return { ts: true, children }
Satisfies Type ->
return { ts: true, children: $0 }
# https://262.ecma-international.org/#prod-UpdateExpression
UpdateExpression
# NOTE: Not allowing whitespace betwen prefix and postfix increment operators and operand
UpdateExpressionSymbol UnaryWithoutParenthesizedAssignment ->
return {
type: "UpdateExpression",
assigned: $2,
children: $0,
}
LeftHandSideExpression ( UpdateExpressionSymbol /(?!\p{ID_Start}|[_$0-9(\[{])/ )? ->
if (!$2) return $1
return {
type: "UpdateExpression",
assigned: $1,
children: [$1, $2[0]],
}
UpdateExpressionSymbol
"++" / "--" ->
return { $loc, token: $1 }
"⧺" ->
return { $loc, token: "++" }
"—" ->
return { $loc, token: "--" }
# https://262.ecma-international.org/#prod-AssignmentExpression
AssignmentExpression
# NOTE: ActualAssignment has highest precedence:
# `x = y |> z` parses as `x = (y |> z)` not `(x = y) |> z`
_?:ws ActualAssignment:assign ->
return prepend(ws, assign)
# NOTE: It is important for pipeline to have higher precedence than
# usual binary operators, so that x |> & + 2 |> & * 3
# is equivalent to x |> (& + 2) |> (& * 3)
PipelineExpression
# TODO If NonPipelineAssignmentExpression or SingleLineAssignmentExpression is used here then behavior changes
# NOTE: Try to match a single line assignment expression before matching newline then assignment expression
SingleLineAssignmentExpression
# TODO: Ideally this wouldn't be needed.
__ AssignmentExpressionTail
# NonPipelineAssignmentExpression
NonPipelineAssignmentExpression
# NOTE: Try to match a single line assignment expression before matching newline then assignment expression
NonPipelineSingleLineAssignmentExpression
__ NonPipelineAssignmentExpressionTail
SingleLineAssignmentExpression
_?:ws AssignmentExpressionTail:tail ->
return prepend(ws, tail)
NonPipelineSingleLineAssignmentExpression
_?:ws NonPipelineAssignmentExpressionTail:tail ->
return prepend(ws, tail)
AssignmentExpressionTail
YieldExpression
ArrowFunction
ActualAssignment
ConditionalExpression
NonPipelineAssignmentExpressionTail
YieldExpression
ArrowFunction
NonPipelineActualAssignment
ConditionalExpression
# An assignment that actually includes an assignment operator, not just passing down to a ConditionalExpression
ActualAssignment
# NOTE: Eliminated left recursion
# NOTE: Consolidated assignment ops
# NOTE: UpdateExpression instead of LeftHandSideExpression to allow
# e.g. ++x *= 2 which we later convert to ++x, x *= 2
( NotDedented UpdateExpression WAssignmentOp )+ ExtendedExpression ->
$1 = $1.map(x => [x[0], x[1], ...x[2]])
$0 = [$1, $2]
return {
type: "AssignmentExpression",
children: $0,
// NOTE: This null marks the assignment for later processing to distinguish it
// from fake assignments that only add a name to a scope
names: null,
lhs: $1,
assigned: $1[0][1],
expression: $2,
}
NonPipelineActualAssignment
# NOTE: Eliminated left recursion
# NOTE: Consolidated assignment ops
# NOTE: UpdateExpression instead of LeftHandSideExpression to allow
# e.g. ++x *= 2 which we later convert to ++x, x *= 2
( NotDedented UpdateExpression WAssignmentOp )+ NonPipelineExtendedExpression ->
$1 = $1.map((x) => [x[0], x[1], ...x[2]])
$0 = [$1, $2]
return {
type: "AssignmentExpression",
children: $0,
// NOTE: This null marks the assignment for later processing to distinguish it
// from fake assignments that only add a name to a scope
names: null,
lhs: $1,
assigned: $1[0][1],
expression: $2,
}
# https://262.ecma-international.org/#prod-YieldExpression
YieldExpression
Yield ( ( _? Star )? MaybeNestedExpression )? ->
if ($2) {
const [ star, expression ] = $2
return {
type: "YieldExpression",
star,
expression,
children: [ $1, star, expression ],
}
}
return {
type: "YieldExpression",
children: [ $1 ],
}
# https://262.ecma-international.org/#prod-ArrowFunction
ArrowFunction
ThinArrowFunction
( Async _ )?:async ArrowParameters:parameters ReturnTypeSuffix?:suffix FatArrow FatArrowBody:expOrBlock ->
if (hasAwait(expOrBlock) && !async) {
async = "async "
}
let error
if (hasYield(expOrBlock)) {
error = {
type: "Error",
message: "Can't use yield inside of => arrow function",
}
}
return {
type: "ArrowFunction",
signature: {
modifier: {
async: !!async,
},
returnType: suffix,
},
parameters,
returnType: suffix,
ts: false,
async,
block: expOrBlock,
children: [async, $0.slice(1), error],
}
FatArrow
# Ensures at least one space before arrow
_?:ws ( "=>" / "⇒" ) ->
if (!ws) return " =>"
return [ $1, "=>" ]
TrailingDeclaration
_? ( ConstAssignment / LetAssignment )
TrailingPipe
_? Pipe
# NOTE Different from
# https://262.ecma-international.org/#prod-ConciseBody
FatArrowBody
# If same-line single expression, avoid wrapping in braces
# NOTE: Skip expressionized statements, so they get braced instead
!EOS !( _? ExpressionizedStatement ) NonPipelinePostfixedExpression:exp !TrailingDeclaration !TrailingPipe !SemicolonDelimiter ->
// Ensure object literal is wrapped in parens
if (exp.type === "ObjectExpression") {
exp = makeLeftHandSideExpression(exp)
}
const expressions = [["", exp]]
return {
type: "BlockStatement",
bare: true,
expressions,
children: [expressions],
implicitlyReturned: true,
}
# Otherwise, wrap block body in braces and insert returns
NoCommaBracedOrEmptyBlock
# https://262.ecma-international.org/#prod-ConditionalExpression
ConditionalExpression
# NOTE: Using ExtendedExpression to allow for If/Switch expressions
ShortCircuitExpression TernaryRest? ->
if ($2) {
return [$1, ...$2]
}
return $1
TernaryRest
NestedTernaryRest
# NOTE: Ternary `a ? b : c` is disabled if CoffeeScript binary existential `a ? b` is enabled
!CoffeeBinaryExistentialEnabled &[ \t] _ QuestionMark ExtendedExpression __ Colon ExtendedExpression ->
return $0.slice(2)
NestedTernaryRest
PushIndent (Nested QuestionMark ExtendedExpression Nested Colon ExtendedExpression)? PopIndent ->
if ($2) return $2
return $skip
# https://262.ecma-international.org/#prod-ShortCircuitExpression
ShortCircuitExpression
# NOTE: We don't need to track the precedence of all the binary operators so they all collapse into this
BinaryOpExpression
PipelineExpression
_?:ws PipelineHeadItem:head ( NotDedented Pipe __ PipelineTailItem )+:body ->
if (head.type === "ArrowFunction" && head.ampersandBlock) {
const expressions = [ {
type: "PipelineExpression",
children: [ ws, head.block.expressions[0], body ],
} ]
const block = { ...head.block, expressions, children: [expressions] }
return {
...head,
block,
body: expressions,
children: [ ...head.children.slice(0, -1), block ],
}
}
return {
type: "PipelineExpression",
children: [ws, head, body]
}
PipelineHeadItem
# Needed to avoid left recursion
NonPipelineExtendedExpression
# Allow a pipeline to be part of first step if within parenthesis
ParenthesizedExpression
PipelineTailItem
AwaitOp !AccessStart -> $1
Yield !AccessStart -> $1
Return !AccessStart -> $1
NWTypePostfix TypePostfix* ->
return makeAmpersandFunction({
body: [" ", $1, ...$2],
})
PipelineHeadItem -> $1
# https://262.ecma-international.org/#prod-PrimaryExpression
PrimaryExpression
ObjectLiteral
ThisLiteral
TemplateLiteral
# NOTE: TemplateLiteral must be before Literal, so that CoffeeScript
# interpolated strings get checked first before StringLiteral.
Literal
ArrayLiteral
FunctionExpression # NOTE: Must be before IdentiferExpression so `async function ...` isn't parsed as `async(function ...)`
IdentifierReference # NOTE: Must be below ObjectLiteral for inline objects `a: 1, b: 2` to not be shadowed by matching the first identifier
ClassExpression
RegularExpressionLiteral
ParenthesizedExpression
Placeholder
# https://facebook.github.io/jsx/#sec-jsx-PrimaryExpression
# NOTE: Modified to parse multiple JSXElement/JSXFragments as one fragment
JSXImplicitFragment
# https://262.ecma-international.org/#prod-ParenthesizedExpression
ParenthesizedExpression
# NOTE: Currently ignoring early error checking in https://262.ecma-international.org/#prod-CoverParenthesizedExpressionAndArrowParameterList
OpenParen:open AllowAll ( PostfixedCommaExpression __ CloseParen )? RestoreAll ->
if (!$3) return $skip
const [exp, ws, close] = $3
switch (exp.type) {
case "StatementExpression":
if (exp.statement.type !== "IterationExpression") break
case "IterationExpression":
// Avoid extra parenthetical wrapping in `(for x in y ...)`
// TODO: losing comments in `ws`
return exp
case "ParenthesizedExpression":
if (exp.implicit) {
return {
...exp,
children: [open, exp.expression, ws, close],
implicit: false,
}
}
break
}
return {
type: "ParenthesizedExpression",
children: [ open, exp, ws, close ],
expression: exp,
}
Placeholder
# Partial function application: f(., x) -> $ => f($, x)
Dot:dot !/(?:\p{ID_Continue}|[\u200C\u200D$.#])/ PlaceholderTypeSuffix?:typeSuffix ->
return {
type: "Placeholder",
subtype: ".",
typeSuffix,
children: [ dot ],
}
# Ruby/Crystal style block shorthand: &+1 -> $ => $+1
Ampersand:amp ![&=] PlaceholderTypeSuffix?:typeSuffix ->
return {
type: "Placeholder",
subtype: "&",
typeSuffix,
children: [ amp ],
}
# .x -> &.x
# NOTE: !NumericLiteral is so we don't match on `.1` etc.
&AccessStart &PropertyAccess !NumericLiteral ->
return {
type: "Placeholder",
subtype: "&",
children: [ { token: "&" } ],
}
PlaceholderTypeSuffix
&( QuestionMark? Colon ) TypeSuffix -> $2
# https://262.ecma-international.org/#prod-ClassDeclaration
ClassDeclaration
# NOTE: skipping syntax directed operation for now
# Wrap nameless function declarations with parens, as needed in JS.
ClassExpression ->
if ($1.id) return $1
return makeLeftHandSideExpression($1)
# https://262.ecma-international.org/#prod-ClassExpression
ClassExpression
Decorators?:decorators ( Abstract __ )?:abstract Class !":" ClassBinding?:binding ClassHeritage?:heritage ClassBody:body ->
return {
decorators,
abstract,
binding,
id: binding?.[0],
heritage,
body,
children: $0,
}
ClassBinding
!EOS BindingIdentifier TypeParameters? -> [$2, $3]
# https://262.ecma-international.org/#prod-ClassHeritage
ClassHeritage
ExtendsClause ImplementsClause?
ImplementsClause
ExtendsClause
ExtendsToken __ ExtendsTarget
ExtendsToken
# NOTE: Added "<" extends shorthand
Loc:l _?:ws ExtendsShorthand:t " "? ->
return {
type: "Extends",
children: [
ws || { $loc: l.$loc, token: " " },
t,
],
}
_? Extends ->
return {
type: "Extends",
children: $0,
}
ExtendsShorthand
"<" ->
return { $loc, token: "extends " }
NotExtendsToken
Loc:l _?:ws1 OmittedNegation:ws2 ExtendsShorthand:t " "? ->
const ws = ws1 && ws2 ? [ws1, ws2] : ws1 || ws2 ||
{ $loc: l.$loc, token: " " }
return {
type: "Extends",
negated: true,
children: [ ws, t ],
}
_? OmittedNegation Extends ->
return {
type: "Extends",
negated: true,
children: $0,
}
OmittedNegation
ExclamationPoint -> ""
Not " "? _? -> $3
ExtendsTarget
LeftHandSideExpressionWithObjectApplicationForbidden:exp ->
return makeLeftHandSideExpression(exp)
ImplementsClause
ImplementsToken ImplementsTarget ( Comma ImplementsTarget )* ->
return {
ts: true,
children: $0,
}
ImplementsToken
# NOTE: Added "<:" implements shorthand
Loc:l __:ws ImplementsShorthand:token " "? ->
const children = [ ...ws, token ]
if (!ws.length) {
children.unshift({ $loc: l.$loc, token: " " })
}
return { children }