-
Notifications
You must be signed in to change notification settings - Fork 0
/
nodes.ts
2103 lines (1761 loc) · 81.3 KB
/
nodes.ts
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 { end, ownStart, start } from "../utils/ast";
import { AssertTypesEq, getLineChar, getLineIndex, urlAt } from "../utils/common";
import { createLocArray, mockNode } from "./helpers";
import { ParserOptions } from "./options";
//#region ================================================[ Types ]===========================================================``--.
// <generated>
// prettier-ignore
export enum NodeType {
MissingNode, SourceFile, Shebang, Program, Snippet, Comment, Identifier, Index, LbIdentifier, McIdentifier, Literal, ItemPath,
PunctuationToken, DelimGroup, Attribute, DocCommentAttribute, MacroInvocation, MacroRulesDeclaration, MacroDeclaration,
MacroRuleDeclaration, MacroInlineRuleDeclaration, MacroGroup, MacroParameterDeclaration, PubSpecifier, ExternSpecifier,
ExpressionStatement, UseStatement, NamedImport, AmbientImport, AnonymousImport, DestructuredImport, ExternCrateStatement,
ExternBlockDeclaration, TypeAliasDeclaration, ConstVariableDeclaration, StaticVariableDeclaration, LetVariableDeclaration,
ModuleDeclaration, FunctionDeclaration, FunctionSelfParameterDeclaration, FunctionParameterDeclaration, FunctionSpread,
StructDeclaration, TupleStructDeclaration, StructPropertyDeclaration, TupleStructItemDeclaration, UnionDeclaration, EnumDeclaration,
EnumMemberDeclaration, EnumMemberTupleDeclaration, EnumMemberStructDeclaration, TraitDeclaration, AutoTraitDeclaration,
TraitAliasDeclaration, ImplDeclaration, NegativeImplDeclaration, ExpressionTypeSelector, ExpressionTypeCast, ExpressionPath,
ExpressionAsTypeCast, ReturnExpression, BreakExpression, ContinueExpression, YieldExpression, CallExpression, MemberExpression,
AwaitExpression, UnwrapExpression, ParenthesizedExpression, MinusExpression, NotExpression, OrExpression, AndExpression,
ReassignmentExpression, UnassignedExpression, OperationExpression, ReassignmentOperationExpression, ComparisonExpression, LetScrutinee,
ClosureFunctionExpression, ClosureFunctionParameterDeclaration, BlockExpression, LoopBlockExpression, WhileBlockExpression,
ForInBlockExpression, TryBlockExpression, IfBlockExpression, MatchExpression, MatchExpressionCase, RangeLiteral, StructLiteral,
StructLiteralProperty, StructLiteralPropertyShorthand, StructLiteralPropertySpread, StructLiteralRestUnassigned, TupleLiteral,
ArrayLiteral, SizedArrayLiteral, ReferenceExpression, RawReferenceExpression, DereferenceExpression, BoxExpression, UnionPattern,
ParenthesizedPattern, RestPattern, WildcardPattern, PatternVariableDeclaration, StructPattern, StructPatternPropertyDestructured,
StructPatternPropertyShorthand, TuplePattern, ArrayPattern, ReferencePattern, BoxPattern, MinusPattern, RangePattern, TypePath,
TypeCall, TypeCallNamedArgument, TypeCallNamedBound, LtIdentifier, LtElided, LtStatic, TypeNever, TypeInferred,
GenericTypeParameterDeclaration, ConstTypeParameterDeclaration, GenericLtParameterDeclaration, WhereTypeBoundDeclaration,
WhereLtBoundDeclaration, TypeTraitBound, TypeDynBounds, TypeImplBounds, TypeFnPointer, TypeFnPointerParameter, TypeFunction, TypeTuple,
TypeSizedArray, TypeSlice, TypeReference, TypeDereferenceConst, TypeDereferenceMut, TypeParenthesized
}
// prettier-ignore
export type Node = MissingNode | SourceFile | Shebang | Program | Snippet | Comment | Identifier | Index | LbIdentifier | McIdentifier |
Literal | ItemPath | PunctuationToken | DelimGroup | Attribute | DocCommentAttribute | MacroInvocation | MacroRulesDeclaration |
MacroDeclaration | MacroRuleDeclaration | MacroInlineRuleDeclaration | MacroGroup | MacroParameterDeclaration | PubSpecifier |
ExternSpecifier | ExpressionStatement | UseStatement | NamedImport | AmbientImport | AnonymousImport | DestructuredImport |
ExternCrateStatement | ExternBlockDeclaration | TypeAliasDeclaration | ConstVariableDeclaration | StaticVariableDeclaration |
LetVariableDeclaration | ModuleDeclaration | FunctionDeclaration | FunctionSelfParameterDeclaration | FunctionParameterDeclaration |
FunctionSpread | StructDeclaration | TupleStructDeclaration | StructPropertyDeclaration | TupleStructItemDeclaration | UnionDeclaration |
EnumDeclaration | EnumMemberDeclaration | EnumMemberTupleDeclaration | EnumMemberStructDeclaration | TraitDeclaration |
AutoTraitDeclaration | TraitAliasDeclaration | ImplDeclaration | NegativeImplDeclaration | ExpressionTypeSelector | ExpressionTypeCast |
ExpressionPath | ExpressionAsTypeCast | ReturnExpression | BreakExpression | ContinueExpression | YieldExpression | CallExpression |
MemberExpression | AwaitExpression | UnwrapExpression | ParenthesizedExpression | MinusExpression | NotExpression | OrExpression |
AndExpression | ReassignmentExpression | UnassignedExpression | OperationExpression | ReassignmentOperationExpression |
ComparisonExpression | LetScrutinee | ClosureFunctionExpression | ClosureFunctionParameterDeclaration | BlockExpression |
LoopBlockExpression | WhileBlockExpression | ForInBlockExpression | TryBlockExpression | IfBlockExpression | MatchExpression |
MatchExpressionCase | RangeLiteral | StructLiteral | StructLiteralProperty | StructLiteralPropertyShorthand |
StructLiteralPropertySpread | StructLiteralRestUnassigned | TupleLiteral | ArrayLiteral | SizedArrayLiteral | ReferenceExpression |
RawReferenceExpression | DereferenceExpression | BoxExpression | UnionPattern | ParenthesizedPattern | RestPattern | WildcardPattern |
PatternVariableDeclaration | StructPattern | StructPatternPropertyDestructured | StructPatternPropertyShorthand | TuplePattern |
ArrayPattern | ReferencePattern | BoxPattern | MinusPattern | RangePattern | TypePath | TypeCall | TypeCallNamedArgument |
TypeCallNamedBound | LtIdentifier | LtElided | LtStatic | TypeNever | TypeInferred | GenericTypeParameterDeclaration |
ConstTypeParameterDeclaration | GenericLtParameterDeclaration | WhereTypeBoundDeclaration | WhereLtBoundDeclaration | TypeTraitBound |
TypeDynBounds | TypeImplBounds | TypeFnPointer | TypeFnPointerParameter | TypeFunction | TypeTuple | TypeSizedArray | TypeSlice |
TypeReference | TypeDereferenceConst | TypeDereferenceMut | TypeParenthesized;
// prettier-ignore
export interface NTMap {
0: MissingNode; 1: SourceFile; 2: Shebang; 3: Program; 4: Snippet; 5: Comment; 6: Identifier; 7: Index; 8: LbIdentifier;
9: McIdentifier; 10: Literal; 11: ItemPath; 12: PunctuationToken; 13: DelimGroup; 14: Attribute; 15: DocCommentAttribute;
16: MacroInvocation; 17: MacroRulesDeclaration; 18: MacroDeclaration; 19: MacroRuleDeclaration; 20: MacroInlineRuleDeclaration;
21: MacroGroup; 22: MacroParameterDeclaration; 23: PubSpecifier; 24: ExternSpecifier; 25: ExpressionStatement; 26: UseStatement;
27: NamedImport; 28: AmbientImport; 29: AnonymousImport; 30: DestructuredImport; 31: ExternCrateStatement; 32: ExternBlockDeclaration;
33: TypeAliasDeclaration; 34: ConstVariableDeclaration; 35: StaticVariableDeclaration; 36: LetVariableDeclaration;
37: ModuleDeclaration; 38: FunctionDeclaration; 39: FunctionSelfParameterDeclaration; 40: FunctionParameterDeclaration;
41: FunctionSpread; 42: StructDeclaration; 43: TupleStructDeclaration; 44: StructPropertyDeclaration; 45: TupleStructItemDeclaration;
46: UnionDeclaration; 47: EnumDeclaration; 48: EnumMemberDeclaration; 49: EnumMemberTupleDeclaration; 50: EnumMemberStructDeclaration;
51: TraitDeclaration; 52: AutoTraitDeclaration; 53: TraitAliasDeclaration; 54: ImplDeclaration; 55: NegativeImplDeclaration;
56: ExpressionTypeSelector; 57: ExpressionTypeCast; 58: ExpressionPath; 59: ExpressionAsTypeCast; 60: ReturnExpression;
61: BreakExpression; 62: ContinueExpression; 63: YieldExpression; 64: CallExpression; 65: MemberExpression; 66: AwaitExpression;
67: UnwrapExpression; 68: ParenthesizedExpression; 69: MinusExpression; 70: NotExpression; 71: OrExpression; 72: AndExpression;
73: ReassignmentExpression; 74: UnassignedExpression; 75: OperationExpression; 76: ReassignmentOperationExpression;
77: ComparisonExpression; 78: LetScrutinee; 79: ClosureFunctionExpression; 80: ClosureFunctionParameterDeclaration;
81: BlockExpression; 82: LoopBlockExpression; 83: WhileBlockExpression; 84: ForInBlockExpression; 85: TryBlockExpression;
86: IfBlockExpression; 87: MatchExpression; 88: MatchExpressionCase; 89: RangeLiteral; 90: StructLiteral; 91: StructLiteralProperty;
92: StructLiteralPropertyShorthand; 93: StructLiteralPropertySpread; 94: StructLiteralRestUnassigned; 95: TupleLiteral;
96: ArrayLiteral; 97: SizedArrayLiteral; 98: ReferenceExpression; 99: RawReferenceExpression; 100: DereferenceExpression;
101: BoxExpression; 102: UnionPattern; 103: ParenthesizedPattern; 104: RestPattern; 105: WildcardPattern;
106: PatternVariableDeclaration; 107: StructPattern; 108: StructPatternPropertyDestructured; 109: StructPatternPropertyShorthand;
110: TuplePattern; 111: ArrayPattern; 112: ReferencePattern; 113: BoxPattern; 114: MinusPattern; 115: RangePattern; 116: TypePath;
117: TypeCall; 118: TypeCallNamedArgument; 119: TypeCallNamedBound; 120: LtIdentifier; 121: LtElided; 122: LtStatic; 123: TypeNever;
124: TypeInferred; 125: GenericTypeParameterDeclaration; 126: ConstTypeParameterDeclaration; 127: GenericLtParameterDeclaration;
128: WhereTypeBoundDeclaration; 129: WhereLtBoundDeclaration; 130: TypeTraitBound; 131: TypeDynBounds; 132: TypeImplBounds;
133: TypeFnPointer; 134: TypeFnPointerParameter; 135: TypeFunction; 136: TypeTuple; 137: TypeSizedArray; 138: TypeSlice;
139: TypeReference; 140: TypeDereferenceConst; 141: TypeDereferenceMut; 142: TypeParenthesized;
}
// </generated>
//#---------------------------------------------------+ Feature Gated +-------------------------------------------------------.
// prettier-ignore
export const enum Feature {
/** `crate ...` */ crate_visibility_modifier = "crate_visibility_modifier",
/** `macro foo(...) { ... }` */ decl_macro = "decl_macro",
/** `impl<...> const ... for ...` | `~const ...` */ const_trait_impl = "const_trait_impl",
/** `impl<...> !... for ... {}` */ negative_impls = "negative_impls",
/** `auto trait ... {}` */ auto_traits = "auto_traits",
/** `trait ... = ...` */ trait_alias = "trait_alias",
/** `enum ... { Foo(...) = discriminant }` */ arbitrary_enum_discriminant = "arbitrary_enum_discriminant",
/** `<const ... = ...>` */ const_generics_defaults = "const_generics_defaults",
/** `Foo<...: typeBounds>` */ associated_type_bounds = "associated_type_bounds",
/** `static || { ... }` | `yield ...` */ generators = "generators",
/** `async || { ... }` */ async_closure = "async_closure",
/** `try { ... }` */ try_blocks = "try_blocks",
/** `min..max` */ exclusive_range_pattern = "exclusive_range_pattern",
/** `..max` | `..=max` | `...max` */ half_open_range_patterns = "half_open_range_patterns",
/** `Color { r: _, g, .. } = ...` */ destructuring_assignment = "destructuring_assignment",
/** `let ... = ... else { ... }` */ let_else = "let_else",
/** `let ... && let ...` */ let_chains = "let_chains",
/** `match ... { ... if let ... = ... => ... }` */ if_let_guard = "if_let_guard",
/** `&raw mut ...` | `&raw const ...` */ raw_ref_op = "raw_ref_op",
/** `const { ... }` */ inline_const = "inline_const",
/** `const { ... }` */ inline_const_pat = "inline_const_pat",
/** `box ...` */ box_patterns = "box_patterns",
/** `box ...` */ box_syntax = "box_syntax",
}
// compiler\rustc_feature\src\active.rs
// specialization = "specialization",
// const_extern_fn = "const_extern_fn",
// ellipsis_inclusive_range_patterns = "ellipsis_inclusive_range_patterns",
// illegal_floating_point_literal_pattern = "illegal_floating_point_literal_pattern",
// more_qualified_paths = "more_qualified_paths",
// type_ascription = "type_ascription",
export interface FG_Map {
[Feature.crate_visibility_modifier]: PubSpecifier;
[Feature.decl_macro]: MacroDeclaration | MacroInlineRuleDeclaration;
[Feature.const_trait_impl]: TypeTraitBound | ImplDeclaration;
[Feature.negative_impls]: NegativeImplDeclaration;
[Feature.auto_traits]: AutoTraitDeclaration;
[Feature.trait_alias]: TraitAliasDeclaration;
[Feature.arbitrary_enum_discriminant]: EnumMemberStructDeclaration | EnumMemberTupleDeclaration;
[Feature.const_generics_defaults]: ConstTypeParameterDeclaration;
[Feature.associated_type_bounds]: TypeCallNamedBound;
[Feature.generators]: YieldExpression | ClosureFunctionExpression;
[Feature.async_closure]: ClosureFunctionExpression;
[Feature.try_blocks]: TryBlockExpression;
[Feature.exclusive_range_pattern]: RangePattern;
[Feature.half_open_range_patterns]: RangePattern;
[Feature.destructuring_assignment]: ReassignmentExpression | StructLiteralRestUnassigned | UnassignedExpression;
[Feature.let_else]: LetVariableDeclaration;
[Feature.let_chains]: NodeWithCondition;
[Feature.if_let_guard]: MatchExpressionCase;
[Feature.raw_ref_op]: RawReferenceExpression;
[Feature.inline_const]: BlockExpression;
[Feature.inline_const_pat]: BlockExpression;
[Feature.box_patterns]: BoxPattern | StructPatternPropertyShorthand;
[Feature.box_syntax]: BoxExpression;
}
export const enum PRCD {
ScrutineeDefault,
"Scrutinee ||",
"Scrutinee &&",
Default,
"=",
"..",
"||",
"&&",
"==", // different in Javascript
"|",
"^",
"&",
// Javascript:
// ["==", "!="],
// ["<", ">", "<=", ">="],
">>",
"+-",
"*/%",
"as",
Unary,
Top,
}
//#--------------------------------------------------+ Contextual Types +-----------------------------------------------------.
export type missing = MissingNode;
export type Segment = AttrSegment | MacroInvokeSegment | MacroMatchSegment | MacroTransformSegment;
export type AttrSegment = TokenNode | DelimGroup<AttrSegment>;
export type MacroInvokeSegment = TokenNode | DelimGroup<MacroInvokeSegment>;
export type MacroMatchSegment = TokenNode | DelimGroup<MacroMatchSegment> | MacroGroup<MacroMatchSegment> | MacroParameterDeclaration;
export type MacroTransformSegment = TokenNode | DelimGroup<MacroTransformSegment> | MacroGroup<MacroTransformSegment> | McIdentifier;
/**/ export type TokenNode = PunctuationToken | Literal | Identifier | LtIdentifier;
/**/ export type MacroSeparator = TokenNode;
export type ImportNode =
| NamedImport //
| AmbientImport
| AnonymousImport
| DestructuredImport;
export type StatementNode =
// expressions
| ExpressionStatement
// macro
| MacroRulesDeclaration
| MacroDeclaration
// import
| UseStatement
// extern
| ExternCrateStatement
| ExternBlockDeclaration
// mod
| ModuleDeclaration
// var
| TypeAliasDeclaration
| LetVariableDeclaration
| ConstVariableDeclaration
| StaticVariableDeclaration
// function
| FunctionDeclaration
// struct
| StructDeclaration
| TupleStructDeclaration
// trait
| TraitDeclaration
| AutoTraitDeclaration
| TraitAliasDeclaration
// impl
| ImplDeclaration
| NegativeImplDeclaration
// enum
| EnumDeclaration
| UnionDeclaration;
export type ExpressionNode =
// common
| MacroInvocation
| Identifier
| Literal
// path
| ExpressionPath
| ExpressionTypeCast
| ExpressionTypeSelector
| ExpressionAsTypeCast
// flow control
| ReturnExpression
| BreakExpression
| ContinueExpression
| YieldExpression
// derivative
| CallExpression
| MemberExpression
| MemberExpression
| AwaitExpression
| UnwrapExpression
// unary
| MinusExpression
| NotExpression
// closure
| ClosureFunctionExpression
// block like
| BlockExpression
| LoopBlockExpression
| WhileBlockExpression
| ForInBlockExpression
| TryBlockExpression
| IfBlockExpression
| MatchExpression
// op like
| OrExpression<ExpressionNode, ExpressionNode>
| AndExpression<ExpressionNode, ExpressionNode>
| ReassignmentExpression
| OperationExpression
| ReassignmentOperationExpression
| ComparisonExpression
// literal
| RangeLiteral
| StructLiteral
| TupleLiteral
| ArrayLiteral
| SizedArrayLiteral
// memory
| ReferenceExpression
| RawReferenceExpression
| DereferenceExpression
| BoxExpression
// misc
| ParenthesizedExpression<ExpressionNode>;
export type PatternNode =
// common
| MacroInvocation
| Identifier
| Literal
// path
| ExpressionPath
| ExpressionTypeCast
| ExpressionTypeSelector
// value
| MinusPattern<Literal>
| RangePattern
| BlockExpression // const { ... } #[feature(inline_const_pat)]
// variable
| PatternVariableDeclaration
// destructuring
| StructPattern
| TuplePattern
| ArrayPattern
// wildcard
| RestPattern
| WildcardPattern
// memory
| ReferencePattern
| BoxPattern
// misc
| UnionPattern
| ParenthesizedPattern<PatternNode>;
export type TypeNode =
// common
| MacroInvocation
| Identifier
// path
| TypePath
| TypeCall
| ExpressionTypeSelector
// special
| TypeNever
| TypeInferred
// bounds
| TypeDynBounds
| TypeImplBounds
// functions
| TypeFnPointer
| TypeFunction
// literals
| TypeSizedArray
| TypeSlice
| TypeTuple
// memory
| TypeReference
| TypeDereferenceMut
| TypeDereferenceConst
// misc
| TypeParenthesized<TypeNode>;
//#------------------------------------------------+ Contextual Subtypes +----------------------------------------------------.
export type AttributeOrComment = Comment | Attribute | DocCommentAttribute;
export type AttributeOrDocComment = Attribute | DocCommentAttribute;
export type CommentOrDocComment = Comment | DocCommentAttribute;
export type IdentifierOrIndex = Identifier | Index;
export type IdentifierOrItemPath = Identifier | ItemPath;
//#--------------------------------------------------+ Rust Ref aliases +-----------------------------------------------------.
/**/ export type _PathBase = Identifier | ExpressionTypeSelector;
/** What can be on the left of 'PathExprSegment' */
/**/ export type _ExprPathSource<T extends _PathBase> = T | ExpressionPath<T> | ExpressionTypeCast<T>;
/** What can be on the left of 'TypePathSegment' */
/**/ export type _TypePathSource<T extends _PathBase> = T | TypePath<T> | TypeCall<T> | TypeFunction<T>;
/** 'PathInExpression' */
export type ExpressionNamespaceTargetNoSelector = _ExprPathSource<Identifier>;
/** 'TypePath' */
export type TypeNamespaceTargetNoSelector = _TypePathSource<Identifier>;
/** 'PathExpression' === ('PathInExpression' | 'QualifiedPathInExpression') === 'PathPattern' */
export type ExpressionNamespaceTarget = _ExprPathSource<_PathBase>;
/** 'TypePath' | 'QualifiedTypeInExpression' */
export type TypeNamespaceTarget = _TypePathSource<_PathBase>;
/** 'PatternNoTopAlt */
export type PatternNoUnion = Exclude<PatternNode, UnionPattern>;
/** 'PatternWithoutRange' */
export type PatternNoUnionNoRange = Exclude<PatternNoUnion, RangePattern>;
//#----------------------------------------------------+ Type helpers +-------------------------------------------------------.
export type MaybePubNode = Extract<Node, PubTarget>;
export type MaybeExternNode = Extract<Node, ExternTarget>;
export type MaybeConstNode = Extract<Node, ConstModifier>;
export type MaybeAsyncNode = Extract<Node, AsyncModifier>;
export type MaybeMoveNode = Extract<Node, MoveModifier>;
export type MaybeUnsafeNode = Extract<Node, UnsafeModifier>;
export type MaybeStaticNode = Extract<Node, StaticModifier>;
export type PathNode = ItemPath | ExpressionPath | TypePath;
export type RangeNode = RangeLiteral | RangePattern;
export type FunctionNode = FunctionDeclaration | ClosureFunctionExpression;
export type TypeFunctionNode = TypeFunction | TypeFnPointer;
export type ParenthesizedNode = ParenthesizedExpression | ParenthesizedPattern | TypeParenthesized;
export type ObjectNode = Extract<Node, MaybeObjectLike>;
export type ArrayLikeNode = Extract<Node, ArrayLike>;
export type ArrayOrTupleLiteral = ArrayLiteral | TupleLiteral;
export type TupleNode = TupleStructDeclaration | EnumMemberTupleDeclaration | TupleLiteral | TuplePattern | TypeTuple;
__DEV__: AssertTypesEq<TupleNode, Extract<Node, TupleLike>>();
export type DeclarationNode = Extract<Node, DeclarationLike>;
export type TraitDeclarationNode = TraitDeclaration | AutoTraitDeclaration | TraitAliasDeclaration;
export type ImplDeclarationNode = ImplDeclaration | NegativeImplDeclaration;
export type NodeWithSegments = Extract<Node, DelimitedSequence<any, any>>;
export type NodeWithBody = Extract<Node, MaybeBlockBody>;
export type NodeWithBodyOrCases = NodeWithBody | MatchExpression;
export type NodeWithBodyNoBody = AutoTraitDeclaration | NegativeImplDeclaration;
export type NodeWithCondition = Extract<Node, MaybeConditionBody>;
export type ImplicitReturnAbleNode = FunctionDeclaration | BlockExpression | IfBlockExpression | MatchExpression | TryBlockExpression;
export type ExpressionWithBody = Extract<ExpressionNode, MaybeBlockBody>;
export type ExpressionWithBodyOrCases = ExpressionWithBody | MatchExpression;
export type LogicalExpression = OrExpression | AndExpression;
export type LeftRightExpression = Extract<Node, LeftRightLike>;
export type FlowControlExpression = ReturnExpression | ContinueExpression | BreakExpression | YieldExpression;
// prettier-ignore
export type UnaryExpression = NotExpression | MinusExpression | ReferenceExpression | DereferenceExpression | RawReferenceExpression | BoxExpression;
export type UnaryPattern = ReferencePattern | BoxPattern | MinusPattern;
export type PostfixExpression = UnwrapExpression | AwaitExpression;
export type VariableDeclarationNode = LetScrutinee | LetVariableDeclaration | ConstVariableDeclaration | StaticVariableDeclaration;
export type ReassignmentNode = ReassignmentExpression | ReassignmentOperationExpression;
export type NodeWithTypeBounds = Extract<Node, TypeBoundsConstaint>;
export type TypeBoundsStandaloneNode = Extract<TypeNode, TypeBoundsStandalone>;
export type FunctionLikeNode = Extract<Node, FunctionLike>;
export type FunctionParameterNode =
| FunctionSelfParameterDeclaration
| FunctionParameterDeclaration
| ClosureFunctionParameterDeclaration
| TypeFnPointerParameter
| TypeNode
| FunctionSpread;
__DEV__: AssertTypesEq<FunctionParameterNode, FunctionLikeNode["parameters"][number] | FunctionSelfParameterDeclaration>();
// prettier-ignore
export type NodeWithMaybePatternNoUnionBody = LetVariableDeclaration | ConstVariableDeclaration | StaticVariableDeclaration |
FunctionParameterDeclaration | ClosureFunctionParameterDeclaration | PatternVariableDeclaration | UnaryPattern;
__DEV__: AssertTypesEq<NodeWithMaybePatternNoUnionBody, Extract<Node, MaybePatternNoUnionBody>>();
//#endregion ===============================================================================================================================..--'
//#region ==============================================[ Interfaces ]========================================================``--.
//#--------------------------------------------------------+ Loc +------------------------------------------------------------.
// prettier-ignore
export interface Located { loc: Loc; }
// prettier-ignore
export interface Delimited<K extends keyof DelimKindMap = DelimKind> { dk: DelimKindMap[K]; }
// prettier-ignore
export interface LocArray<T extends Node = Node, K extends keyof DelimKindMap = keyof DelimKindMap> extends Array<T>, Located, Delimited<K> {}
// prettier-ignore
export interface DelimitedSequence<T extends Segment, TK extends keyof DelimKindMap = "()" | "[]" | "{}"> { segments: LocArray<T, TK>; }
//#------------------------------------------------------+ Program +----------------------------------------------------------.
// prettier-ignore
export interface __DevonlyObject { stats: { [statsName: string]: string | number }; }
export interface ProgramLike {
ast: Node | LocArray<any, any>;
danglingAttributes: AttributeOrDocComment[];
comments: Comment[];
__devonly?: __DevonlyObject;
}
//#-----------------------------------------------------+ Identifier +--------------------------------------------------------.
export interface IdentifierLike {
name: string;
}
export interface MaybeIdentifiable<T extends IdentifierLike = Identifier> {
id: T | undefined;
}
export interface Identifiable<T extends IdentifierLike = Identifier> extends MaybeIdentifiable<T> {
id: T;
}
export interface LtIdentifiable {
id: LtIdentifier;
}
export interface PathLike {
namespace: Identifier | unknown | undefined;
segment: Identifier;
}
//#------------------------------------------------------+ Optional +---------------------------------------------------------.
export interface AttributeTarget {
attributes?: AttributeOrDocComment[];
}
export interface PubTarget {
pub?: PubSpecifier;
}
export interface ExternTarget {
extern?: ExternSpecifier;
}
export interface ConstModifier {
const?: true;
}
export interface AsyncModifier {
async?: true;
}
export interface MoveModifier {
move?: true;
}
export interface UnsafeModifier {
unsafe?: true;
}
export interface StaticModifier {
static?: true;
}
//#-------------------------------------------------------+ Memory +----------------------------------------------------------.
// prettier-ignore
export interface RefAble { ref: boolean; }
// prettier-ignore
export interface MutAble { mut: boolean; }
// prettier-ignore
export interface LtAble { lt: Lifetime | undefined; }
// prettier-ignore
export interface TargetsLifetime { ltTarget: Lifetime; }
// prettier-ignore
export interface MaybeHasLtBounds { ltBounds: Lifetime[] | undefined; }
// prettier-ignore
export interface HasLtBounds extends MaybeHasLtBounds { ltBounds: Lifetime[]; }
export interface ForLtParametersBody {
// for<...ltParameters>? ...
ltParameters: LocArray<GenericLtParameterDeclaration, "<>"> | undefined;
}
//#-------------------------------------------------------+ Common +----------------------------------------------------------.
export interface CommentLike {
line: boolean;
value: string;
}
export interface AttributeLike extends DelimitedSequence<AttrSegment, "None" | "[]"> {
inner: boolean;
segments: LocArray<AttrSegment, "None" | "[]">;
}
export interface AbiTarget {
abi: Literal | undefined;
}
//#-------------------------------------------------+ Expression Context +----------------------------------------------------.
export interface Callable {
callee: Node;
arguments: LocArray<Node, "()">;
}
export interface MaybeLabelTarget {
label: LbIdentifier | undefined;
}
export interface MaybeBlockBody {
body: LocArray<StatementNode, "None" | "{}"> | undefined;
}
export interface BlockBody extends MaybeBlockBody {
body: LocArray<StatementNode, "None" | "{}">;
}
export interface BlockLike extends MaybeLabelTarget, BlockBody {}
export interface MaybeConditionBody {
condition: ConditionExpressionXS | undefined;
}
export interface ConditionBody extends MaybeConditionBody {
condition: ConditionExpressionXS;
}
export interface MaybeExpressionBody {
expression: ExpressionNode | undefined;
}
export interface ExpressionBody extends MaybeExpressionBody {
expression: ExpressionNode;
}
export interface LeftRightLike {
kind: keyof typeof TK;
left: Node | undefined;
tk: TK;
right: Node | undefined;
}
export interface RangeLike {
lower: Node | undefined;
last: boolean;
upper: Node | undefined;
}
export interface SizeExpressionBody {
sizeExpression: ExpressionNode;
}
export interface ArrayLike {
items: LocArray<Node, "()" | "[]">;
}
export interface TupleLike extends ArrayLike {
items: LocArray<Node, "()">;
}
export interface MaybeObjectLike {
properties: LocArray<Node, "{}"> | undefined;
}
export interface ObjectLike extends MaybeObjectLike {
properties: LocArray<Node, "{}">;
}
// prettier-ignore
export interface PropertyLike { key: IdentifierOrIndex; }
//#----------------------------------------------------+ Type Context +-------------------------------------------------------.
export interface MaybeReturnTypeConstraint {
returnType: TypeNode | undefined;
}
export interface FunctionLike extends MaybeReturnTypeConstraint {
// (...parameters) -> returnType?
// |...parameters| -> returnType?
parameters: LocArray<Node, "()" | "||">;
returnType: TypeNode | undefined;
}
export interface MaybeGenericArgsTarget {
typeArguments: LocArray<TypeCallArgument, "<>"> | undefined;
}
export interface GenericArgsTarget extends MaybeGenericArgsTarget {
// ...::<...typeArguments>
// ...<...typeArguments>
typeArguments: LocArray<TypeCallArgument, "<>">;
}
export interface TypeCallable<T = TypeNode> extends GenericArgsTarget {
// typeCallee<...typeArguments>
typeCallee: T;
}
/**/ export interface MaybeGenericsDeclaration {
// <...generics>?
generics: LocArray<GenericParameterDeclaration, "<>"> | undefined;
}
/**/ export interface MaybeWhereBoundsDeclaration {
// where ...whereBounds?
whereBounds: LocArray<WhereBoundDeclaration, "None"> | undefined;
}
export interface DeclarationLike extends MaybeWhereBoundsDeclaration, MaybeWhereBoundsDeclaration {
// ...<...generics>? ... where ...whereBounds?
}
export interface TypeTargetConstraint {
typeTarget: TypeNode;
}
export interface MaybeTypeExpressionBody<T = TypeNode> {
typeExpression: T | undefined;
}
export interface TypeExpressionBody<T = TypeNode> extends MaybeTypeExpressionBody<T> {
typeExpression: T;
}
export interface MaybeTypeAnnotationTarget<T = TypeNode> {
typeAnnotation: T | undefined;
}
export interface TypeAnnotationTarget<T = TypeNode> extends MaybeTypeAnnotationTarget<T> {
typeAnnotation: T;
}
export interface TypeBoundsConstaint {
// ...: ...typeBounds?
// ...= ...typeBounds?
typeBounds: TypeBound[] | undefined; // allows trailing "+", allows empty value
}
export interface TypeBoundsStandalone extends TypeBoundsConstaint {
typeBounds: TypeBound[]; // allows trailing "+"
}
//#--------------------------------------------------+ Pattern Context +------------------------------------------------------.
export interface MaybePatternBody {
pattern: PatternNode | undefined;
}
export interface PatternBody extends MaybePatternBody {
pattern: PatternNode;
}
export interface MaybePatternNoUnionBody extends MaybePatternBody {
pattern: PatternNoUnion | undefined;
}
export interface PatternNoUnionBody extends MaybePatternBody {
pattern: PatternNoUnion;
}
//#endregion ===============================================================================================================================..--'
//#region ================================================[ Enums ]===========================================================``--.
// prettier-ignore
export const enum TK { None, ".", "&&", "||", "=", "+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "==", "!=", ">", ">=", "<", "<=", "+=",
"-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", "$", "@", "_", "..", "...", "..=", ",", ";", ":", "::", "#", "?", "!", "=>", "->", "~" }
// prettier-ignore
const str_TK = ["", ".", "&&", "||", "=", "+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "==", "!=", ">", ">=", "<", "<=", "+=", "-=",
"*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", "$", "@", "_", "..", "...", "..=", ",", ";", ":", "::", "#", "?", "!", "=>", "->", "~"] as const;
// prettier-ignore
type ReaOpExpr = typeof TK["+="] | typeof TK["-="] | typeof TK["*="] | typeof TK["/="] | typeof TK["%="] | typeof TK["&="] | typeof TK["|="] | typeof TK["^="] | typeof TK["<<="] | typeof TK[">>="];
// prettier-ignore
type OpExpr = typeof TK["+"] | typeof TK["-"] | typeof TK["*"] | typeof TK["/"] | typeof TK["%"] | typeof TK["&"] | typeof TK["|"] | typeof TK["^"] | typeof TK["<<"] | typeof TK[">>"];
type CompExpr = typeof TK["=="] | typeof TK["!="] | typeof TK[">"] | typeof TK[">="] | typeof TK["<"] | typeof TK["<="];
// prettier-ignore
/**/ export interface DelimKindMap { "None": 0; "()": 1; "[]": 2; "{}": 3; "<>": 4; "||": 5; 0: 0; 1: 1; 2: 2; 3: 3; 4: 4; 5: 5; }
// prettier-ignore
/**/ export interface DelimNameMap { 0: "None"; 1: "()"; 2: "[]"; 3: "{}"; 4: "<>"; 5: "||"; }
// prettier-ignore
/**/ export const enum DelimKind { None, "()", "[]", "{}", "<>", "||" }
export const enum TyMacroMatch {
/** undefined */ None,
/** anything */ "tt",
/** Attribute */ "meta",
/** PubSpecifier */ "vis",
/** Identifier */ "ident",
/** LtIdentifier */ "lifetime",
/** Literal | MinusExpression<Literal> */ "literal",
/** StatementNode */ "stmt",
/** StatementNode subset valid in Toplevel */ "item",
/** ExpressionNode */ "expr",
/** ExpressionNode & BlockLike */ "block",
/** PatternNode (PatternNoUnion pre edition 2021) */ "pat",
/** PatternNoUnion */ "pat_param",
/** TypeNode */ "ty",
/** TypeNamespaceTargetNoSelector */ "path",
}
export const enum LiteralKind {
/** i.e. `false` */ False,
/** i.e. `true` */ True,
/** e.g. `'A'` */ Char,
/** e.g. `b'A'` */ bChar,
/** e.g. `b"ABCDE"` */ bString,
/** e.g. `br#"AAAA"#` */ brString,
/** e.g. `r#"hello"#` */ rString,
/** e.g. `"hello"` */ String,
/** e.g. `0b1111_0000` (int suffix) */ Binary,
/** e.g. `0xff` (int suffix) */ Hex,
/** e.g. `0o77` (int suffix) */ Octal,
/** e.g. `123` (int suffix) */ Integer,
/** e.g. `7.6e+54` (float suffix) */ Float,
}
//#endregion ===============================================================================================================================..--'
//#region =================================================[ Base ]===========================================================``--.
//#--------------------------------------------------------+ Loc +------------------------------------------------------------.
// prettier-ignore
export class Loc {
declare readonly src: SourceFile;
protected declare readonly 0: number;
protected declare readonly 1: number;
protected declare readonly ownStart?: number;
constructor(src: SourceFile, start: number, end: number) {
this.src = src;
this[0] = start;
this[1] = end;
}
len() { return this[1] - this[0]; }
isBefore(target: Located) { return this[1] <= start(target); }
isAfter(target: Located) { return this[0] >= end(target); }
contains(target: Located) { return this[0] <= start(target) && this[1] >= end(target); }
ownContains(target: Located) { return (this.ownStart ?? this[0]) <= start(target) && this[1] >= end(target); }
isBetween(left: Located, right: Located) { return this[0] >= end(left) && this[1] <= start(right); }
url() { return this.src.url(this[0]); }
getText() { return this.src.code.slice(this[0], this[1]); }
getOwnText() { return this.src.code.slice(this.ownStart ?? this[0], this[1]); }
sliceText(startIndex?: number, endIndex?: number) { return this.src.code.slice(this[0], this[1]).slice(startIndex, endIndex); }
clone() { return new Loc(this.src, this.ownStart ?? this[0], this[1]); }
cloneFrom(startPos: number) { return new Loc(this.src, startPos, this[1]); }
[Symbol.for("nodejs.util.inspect.custom")]() { return this.url(); }
toJSON() { const { src, ...rest } = this; return rest; }
}
//#------------------------------------------------------+ BaseNode +---------------------------------------------------------.
// prettier-ignore
export class BaseNode<NT extends NodeType = NodeType> implements Located {
get type() { return NodeType[this.nodeType]; }
declare readonly nodeType: NT;
declare readonly loc: Loc;
constructor(nodeType: NT, loc: Loc) { this.nodeType = nodeType; this.loc = loc; }
toJSON() {
var obj: any = { type: NodeType[this.nodeType], ...(this as any) };
if ("name" in this) obj.name = (this as any).name;
if ("value" in this) obj.value = (this as any).value;
if ("kind" in this) obj.kind = (this as any).kind;
if ("token" in this) obj.token = (this as any).token;
return obj;
}
}
// prettier-ignore
export class MissingNode extends BaseNode<0> implements IdentifierLike {
get name(): "" { return ""; }
}
//#-----------------------------------------------------+ SourceFile +--------------------------------------------------------.
// prettier-ignore
export class SourceFile extends BaseNode<1> {
code: string;
filepath: string | undefined;
parserOptions: ParserOptions;
lineStarts: number[];
program: Program;
declare UTF8BOM?: true;
declare shebang?: Shebang;
l(index: number) { return getLineIndex(this.lineStarts, index); }
lc(index: number) { return getLineChar(this.lineStarts, index); }
url(index?: number) { return urlAt(this.filepath ?? "undefined", this.lineStarts, index); }
}
// prettier-ignore
/**/ export class Shebang extends BaseNode<2> {
// #!value (e.g. "#!/usr/bin/env rustx")
get value() { return this.loc.sliceText(2).trim(); }
}
//#------------------------------------------------------+ Program +----------------------------------------------------------.
// const enum SnippetContext { Statements, Arguments, Expression, Type, Pattern, }
// prettier-ignore
export class Program extends BaseNode<3> implements ProgramLike, BlockBody, AttributeTarget {
// ...body
get body() { return this.ast; }
ast: LocArray<StatementNode, "None">;
danglingAttributes: AttributeOrDocComment[];
comments: Comment[];
declare attributes?: AttributeOrDocComment[];
declare __devonly?: __DevonlyObject;
}
// prettier-ignore
export class Snippet<T extends Node | LocArray = Node | LocArray> extends BaseNode<4> implements ProgramLike, AttributeTarget {
ast: T;
danglingAttributes: AttributeOrDocComment[];
comments: Comment[];
declare attributes?: AttributeOrDocComment[]; // only when reading statements
declare __devonly?: __DevonlyObject;
}
//#endregion ===============================================================================================================================..--'
//#region ===============================================[ Comments ]=========================================================``--.
// prettier-ignore
export class Comment extends BaseNode<5> implements CommentLike {
line: boolean;
get value() { return this.loc.sliceText(2, this.line ? undefined : -2); }
}
//#endregion ===============================================================================================================================..--'
//#region =========================================[ Identifier & Literal ]===================================================``--.
// prettier-ignore
export class Identifier extends BaseNode<6> implements IdentifierLike {
get name() { return this.loc.getOwnText() as string | `r#${string}`; }
}
// prettier-ignore
export class Index extends BaseNode<7> implements IdentifierLike {
get name() { return this.loc.getOwnText() as `${number}`; }
}
// prettier-ignore
export class LbIdentifier extends BaseNode<8> implements IdentifierLike {
get name() { return this.loc.getOwnText() as `'${string}`; }
}
// prettier-ignore
export class McIdentifier extends BaseNode<9> implements IdentifierLike {
get name() { return this.loc.getOwnText() as `$${string}`; }
}
// prettier-ignore
export class Literal extends BaseNode<10> {
kind: LiteralKind;
get value() { return "suffix" in this ? this.loc.src.code.slice(ownStart(this), start(this.suffix)) : this.loc.getOwnText(); }
declare suffix?: Identifier;
}
//#endregion ===============================================================================================================================..--'
//#region ================================================[ Macro ]===========================================================``--.
//#-------------------------------------------------------+ Common +----------------------------------------------------------.
export class ItemPath extends BaseNode<11> implements PathLike {
// namespace?::segment
namespace: IdentifierOrItemPath | undefined;
segment: Identifier;
}
// prettier-ignore
/**/ export class PunctuationToken extends BaseNode<12> {
// token
tk: TK;
get token() { return str_TK[this.tk] as typeof str_TK[number]; }
}
/**/ export class DelimGroup<T extends Segment = Segment> extends BaseNode<13> implements DelimitedSequence<T> {
segments: LocArray<T, "()" | "[]" | "{}">;
}
//#-----------------------------------------------------+ Invocation +--------------------------------------------------------.
// prettier-ignore
export class Attribute extends BaseNode<14> implements AttributeLike, CommentLike {
// #!?[expression] ...
inner: boolean;
segments: LocArray<AttrSegment, "[]">;
get value() { return this.segments.loc.sliceText(1, -1); }
get line() { return this.inner; }
}
// prettier-ignore
export class DocCommentAttribute extends BaseNode<15> implements DelimitedSequence<AttrSegment, "None">, AttributeLike, CommentLike {
// /// ...
// /** ... */
// //! ... (inner)
// /*! ... */ (inner)
inner: boolean;
line: boolean;
get value() { return this.loc.sliceText(3, this.line ? undefined : -2); }
get segments() {
const loc = new Loc(this.loc.src, start(this) + 3, end(this) + (this.line ? 0 : -2));
return createLocArray(
DelimKind.None,
loc, //
[mockNode(NodeType.Literal, loc.clone(), { kind: LiteralKind.String, value: this.value })]
);
}
}
export class MacroInvocation extends BaseNode<16> implements DelimitedSequence<MacroInvokeSegment> {
// callee!(...segments);?
// callee![...segments];?
// callee! { ...segments }
callee: Identifier | PathNode;
segments: LocArray<MacroInvokeSegment, "()" | "[]" | "{}">;
}
//#----------------------------------------------------+ Declaration +--------------------------------------------------------.
export class MacroRulesDeclaration extends BaseNode<17> implements Identifiable, AttributeTarget {
// macro_rules! id { ...rules }
id: Identifier;
rules: LocArray<MacroRuleDeclaration, "()" | "[]" | "{}">;
declare attributes?: AttributeOrDocComment[];