-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.mly
More file actions
1350 lines (1206 loc) · 61.1 KB
/
Copy pathparser.mly
File metadata and controls
1350 lines (1206 loc) · 61.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Menhir parser for AffineScript */
%{
open Ast
let mk_span startpos endpos =
let file = startpos.Lexing.pos_fname in
let start_pos = {
Span.line = startpos.Lexing.pos_lnum;
col = startpos.Lexing.pos_cnum - startpos.Lexing.pos_bol + 1;
offset = startpos.Lexing.pos_cnum;
} in
let end_pos = {
Span.line = endpos.Lexing.pos_lnum;
col = endpos.Lexing.pos_cnum - endpos.Lexing.pos_bol + 1;
offset = endpos.Lexing.pos_cnum;
} in
Span.make ~file ~start_pos ~end_pos
let mk_ident name startpos endpos =
{ name; span = mk_span startpos endpos }
(* issue #122 v2: inherent-impl support. The old grammar pre-committed to
`impl_trait_ref? self_ty` where both alternatives start with an ident,
so `impl Counter {` (inherent) was a parse error at `{`. The rule now
parses one type_expr unconditionally, then an optional `FOR type_expr`;
when the `FOR` is present the leading type was the trait. This recovers
the trait name/args from that leading type_expr. *)
let trait_ref_of_type_expr (t : type_expr) : trait_ref =
match t with
| TyCon id | TyVar id -> { tr_name = id; tr_args = [] }
| TyApp (id, args) -> { tr_name = id; tr_args = args }
| _ -> failwith "impl: trait reference must be a named type"
(* Fold a non-empty comma-separated braced effect row `{E1, E2, ...}`
into the binary EffUnion AST. Right-associated; union is
order-insensitive downstream so association is immaterial. *)
let rec effect_union_of_list = function
| [] -> assert false (* separated_nonempty_list guarantees >= 1 *)
| [e] -> e
| e :: rest -> EffUnion (e, effect_union_of_list rest)
%}
/* Tokens with values */
%token <int> INT
%token <float> FLOAT
%token <char> CHAR
%token <string> STRING
%token <string> LOWER_IDENT
%token <string> UPPER_IDENT
%token <string> ROW_VAR
/* Literal keywords */
%token TRUE FALSE
/* Keywords */
%token SELF_KW
%token FN LET CONST MUT OWN REF TYPE STRUCT ENUM TRAIT IMPL
%token EFFECT HANDLE RESUME MATCH IF ELSE WHILE FOR
%token RETURN BREAK CONTINUE IN WHERE TOTAL MODULE USE
%token PUB AS EXTERN UNSAFE ASSUME TRANSMUTE FORGET TRY CATCH FINALLY
/* Built-in types */
%token NAT INT_T BOOL FLOAT_T STRING_T CHAR_T TYPE_K ROW NEVER
/* Punctuation */
%token LPAREN RPAREN LBRACE RBRACE LBRACKET RBRACKET
%token HASH_LBRACE /* `#{` record-literal opener (affinescript#215) */
%token COMMA SEMICOLON COLON COLONCOLON DOT DOTDOT
%token ARROW FAT_ARROW PIPE AT UNDERSCORE BACKSLASH QUESTION
/* Quantity */
%token ZERO ONE OMEGA
/* Operators */
%token PLUS PLUSPLUS MINUS STAR SLASH PERCENT
%token EQ EQEQ NE LT LE GT GE
%token AMPAMP PIPEPIPE BANG
%token AMP CARET TILDE LTLT GTGT
%token PLUSEQ MINUSEQ STAREQ SLASHEQ
/* End of file */
%token EOF
/* Precedence (lowest to highest) */
/* `LOWEST_TYPE_ARROW` is a pseudo-token (never lexed) carrying the
lowest precedence. It tags the base `type_expr_arrow -> type_expr_primary`
reduction so that in state 41 — after a `type_expr_primary`, lookahead
`ARROW` (continue an arrow type) or `MINUS` (open the legacy `-{E}->`
effect row) — the parser SHIFTS rather than reducing the base case.
Shift was already Menhir's (correct) arbitrary resolution there (a
bare type can never be followed by `->`/`-{` *and* want to stop), so
declaring this precedence is parse-behaviour-preserving and only
silences the spurious conflict. `ARROW` has no precedence elsewhere
and is a conflict lookahead ONLY in state 41 (verified via
`menhir --explain`), so giving it precedence here is side-effect-free.
See affinescript#215 (family A). */
%nonassoc LOWEST_TYPE_ARROW
%nonassoc ARROW
%left PIPEPIPE
%left AMPAMP
%left PIPE
%left CARET
%left AMP
%left EQEQ NE
%left LT LE GT GE
%left LTLT GTGT
%left PLUS PLUSPLUS MINUS
%left STAR SLASH PERCENT
/* Removed (affinescript#215 family F): the assignment-op level
(EQ PLUSEQ MINUSEQ STAREQ SLASHEQ), the unary level
(BANG TILDE UMINUS UREF UDEREF), and the postfix level
(DOT LBRACKET LPAREN) — Menhir certified every one of these
precedence levels "never useful" (they resolve no conflict; the
expr cascade disambiguates structurally). Removal is
parse-behaviour-neutral, proven by the unchanged conflict counts
and the green 257-test gate. UMINUS/UREF/UDEREF were pseudo-tokens
used only by the now-removed `%prec` on the unary rules. */
/* Entry point */
%start <Ast.program> program
%start <Ast.expr> expr_only
%%
/* ========== Program ========== */
program:
| module_decl = module_decl? imports = list(import_decl) decls = list(top_level) EOF
{ { prog_module = module_decl; prog_imports = imports; prog_decls = decls } }
module_decl:
| MODULE path = module_path SEMICOLON { path }
module_path:
| id = ident { [id] }
| path = module_path DOT id = ident { path @ [id] }
/* ADR-014 (#228): module-qualified type/effect path. Separator is `.` or
`::` (mixed permitted); `::` is canonical (consistent with ADR-011 value
paths). A qualified name is >=2 `upper_ident` segments; it is folded to a
single canonical `::`-joined string so downstream (resolve/typecheck/all
codegens, formatter) sees one ident and needs no change — the formatter
prints the stored `::` form, normalising any `.` input for free.
Right-recursive + restricted to `upper_ident` so it only adds
`DOT`/`COLONCOLON` lookahead after a type/effect-position `upper_ident`
(no prior reduce action there — that void is the `parse error at .`
#228 reports), introducing zero new LR conflicts. */
%inline qsep:
| DOT { () }
| COLONCOLON { () }
qualified_type_name:
| head = upper_ident qsep rest = qualified_type_name_rest
{ head ^ "::" ^ rest }
/* #448 item 1: stdlib has lowercase module names (json, option,
prelude, dict, …) that must be representable as qualifier heads
at type/effect position. Same right-recursive shape, lookahead
at qsep (`.`/`::`) disambiguates against the bare lower_ident →
TyVar reduce; `qualified_type_name_rest` stays upper_ident-only
so a tail segment like `.value` still parse-errors. */
| head = lower_ident qsep rest = qualified_type_name_rest
{ head ^ "::" ^ rest }
qualified_type_name_rest:
| name = upper_ident { name }
| name = upper_ident qsep rest = qualified_type_name_rest
{ name ^ "::" ^ rest }
/* ========== Imports ========== */
import_decl:
| USE path = module_path SEMICOLON
{ ImportSimple (path, None) }
| USE path = module_path AS alias = ident SEMICOLON
{ ImportSimple (path, Some alias) }
| USE path = module_path COLONCOLON LBRACE items = separated_list(COMMA, import_item) RBRACE SEMICOLON
{ ImportList (path, items) }
| USE path = module_path COLONCOLON STAR SEMICOLON
{ ImportGlob path }
import_item:
| name = ident { { ii_name = name; ii_alias = None } }
| name = ident AS alias = ident { { ii_name = name; ii_alias = Some alias } }
/* ========== Top-level declarations ========== */
top_level:
| f = fn_decl { TopFn f }
| t = type_decl { TopType t }
| e = effect_decl { TopEffect e }
| tr = trait_decl { TopTrait tr }
| i = impl_block { TopImpl i }
| c = const_decl { c }
| f = extern_fn_decl { TopFn f }
| t = extern_type_decl { TopType t }
/* `extern fn name[T..](params) -> Ret;` — host-supplied implementation,
no body, terminated by SEMICOLON. The fn_decl carries FnExtern as its
body so downstream passes can detect the extern shape. */
extern_fn_decl:
| vis = visibility? EXTERN FN name = ident
type_params = type_params?
LPAREN params = param_list_trailing_comma RPAREN
ret = return_type?
SEMICOLON
{ { fd_vis = Option.value vis ~default:Private;
fd_total = false;
fd_name = name;
fd_type_params = Option.value type_params ~default:[];
fd_params = params;
fd_ret_ty = fst (Option.value ret ~default:(None, None));
fd_eff = snd (Option.value ret ~default:(None, None));
fd_where = [];
fd_body = FnExtern } }
/* `extern type Name[T..];` — opaque host-supplied type. */
extern_type_decl:
| vis = visibility? EXTERN TYPE name = ident
type_params = type_params?
SEMICOLON
{ { td_vis = Option.value vis ~default:Private;
td_name = name;
td_type_params = Option.value type_params ~default:[];
td_body = TyExtern } }
const_decl:
| vis = visibility? CONST name = ident COLON ty = type_expr EQ value = expr SEMICOLON
{ TopConst { tc_vis = Option.value vis ~default:Private;
tc_mut = false;
tc_name = name; tc_ty = ty; tc_value = value } }
/* #548: `const mut <name>: T = init;` — mutable module-level binding.
Mirrors the function-scope `let mut <name>: T = init;` shape (handled
in let_stmt / let_expr) one level up to module scope. The MUT token
here is the same one already accepted in let_stmt's `LET mut_ = MUT?`
prefix; no new token, no new keyword. Lowering emits JS `let` instead
of JS `const` so the binding is JS-mutable; writes from inside any
function body go through the existing StmtAssign path (which already
compiles to `name = value;` and was already valid for module-level
`let`-style bindings on the codegen side). */
| vis = visibility? CONST MUT name = ident COLON ty = type_expr EQ value = expr SEMICOLON
{ TopConst { tc_vis = Option.value vis ~default:Private;
tc_mut = true;
tc_name = name; tc_ty = ty; tc_value = value } }
fn_decl:
| vis = visibility? total = TOTAL? FN name = ident
type_params = type_params?
LPAREN params = param_list_trailing_comma RPAREN
ret = return_type?
where_clause = where_clause?
body = fn_body
{ { fd_vis = Option.value vis ~default:Private;
fd_total = Option.is_some total;
fd_name = name;
fd_type_params = Option.value type_params ~default:[];
fd_params = params;
fd_ret_ty = fst (Option.value ret ~default:(None, None));
fd_eff = snd (Option.value ret ~default:(None, None));
fd_where = Option.value where_clause ~default:[];
fd_body = body } }
return_type:
| ARROW ty = type_expr { (Some ty, None) }
| MINUS LBRACE eff = effect_expr RBRACE ARROW ty = type_expr { (Some ty, Some eff) }
/* `-> T / E` — the ADR-008 canonical effect-row return annotation
(issue #135 slice 3). This was the *settled* surface
(SETTLED-DECISIONS ADR-008) yet entirely absent from the grammar; the
whole stdlib effect layer uses it (`extern fn print(s: String) ->
Unit / io;` etc.) and even a normal `fn ... -> T / io` could not be
written. Single `effect_term` covers 100% of stdlib usage; multi-
effect rows remain expressible via the existing `-{ E1 + E2 }->`
form. Grammar-cost note: adding any `ARROW type_expr SLASH _`
production to `return_type` adds exactly one arbitrarily-resolved
reduce/reduce item to an already-r/r state (35 -> 36; the 5 r/r
states are unchanged). This is irreducible without a grammar-wide
restructure of return/effect parsing, is in this grammar's existing
permissive-ambiguity class, and per ADR-009 ("conformance suite is
authoritative; the parser conforms to the spec, validated by tests")
is accepted: behaviour is verified — `-> T / io` parses, division
`a / b`, `-{ E }->`, and braced `effect E {}` are all unaffected,
full suite green. ADR-008 mandates this syntax; it is not sugar. */
| ARROW ty = type_expr SLASH eff = effect_term { (Some ty, Some eff) }
/* `-> T / {E1, E2, ...}` — braced comma-separated effect row. This is
the surface the effects-migration-stance guide uses verbatim
(`/{IO}`, `/{IO, Async}`); previously only the bare single-term
`-> T / E` and the prefix `-{ E1 + E2 }->` forms parsed, so migrators
could not write the documented syntax. The `SLASH LBRACE` prefix is
unambiguous: bare `-> T / E` continues on IDENT, the prefix row uses
`MINUS LBRACE`, and `{` cannot open a division operand in type
position — so this adds no new reduce/reduce item beyond the existing
ADR-008/ADR-009 permissive-ambiguity class (verified by conflict
count + full suite). */
| ARROW ty = type_expr SLASH LBRACE effs = separated_nonempty_list(COMMA, effect_term) RBRACE
{ (Some ty, Some (effect_union_of_list effs)) }
fn_body:
| blk = block { FnBlock blk }
| EQ e = expr SEMICOLON { FnExpr e }
visibility:
| PUB { Public }
| PUB LPAREN LOWER_IDENT RPAREN
{ match $3 with
| "crate" -> PubCrate
| "super" -> PubSuper
| _ -> failwith "Expected 'crate' or 'super'" }
type_params:
| LBRACKET params = separated_nonempty_list(COMMA, type_param) RBRACKET { params }
/* Angle-bracket alias matching the type-application syntax: `fn f<T>` ≡
`fn f[T]`, `type Option<T> = ...` ≡ `type Option[T] = ...`. */
| LT params = separated_nonempty_list(COMMA, type_param) GT { params }
type_param:
| qty = quantity? name = ident kind = kind_annotation?
{ { tp_quantity = qty; tp_name = name; tp_kind = kind } }
(* Row variable type parameter, e.g. `[..r]` — lexed as a single ROW_VAR token *)
| rv = ROW_VAR
{ { tp_quantity = None;
tp_name = mk_ident rv $startpos $endpos;
tp_kind = Some KRow } }
kind_annotation:
| COLON k = kind { k }
kind:
| TYPE_K { KType }
| ROW { KRow }
| k1 = kind ARROW k2 = kind { KArrow (k1, k2) }
| LPAREN k = kind RPAREN { k }
quantity:
| ZERO { QZero }
| ONE { QOne }
| OMEGA { QOmega }
(* ADR-007 Option C — primary attribute form for quantity annotations.
`@linear` ≡ QOne, `@erased` ≡ QZero, `@unrestricted` ≡ QOmega.
Rejects unknown attribute names with a parse error. *)
quantity_attr:
| AT name = lower_ident
{ match name with
| "linear" -> QOne
| "erased" -> QZero
| "unrestricted" -> QOmega
| other ->
let msg = Printf.sprintf
"unknown quantity attribute '@%s'; expected @linear, @erased, or @unrestricted"
other in
raise (Parser_errors.Parse_action_error (msg, $startpos, $endpos)) }
(* ADR-007 Option B — sugar form for quantity annotations on let/stmt_let.
Reads as `:1`, `:0`, or `:ω` immediately after the pattern. The lexer
emits INT for `0` and `1`, so we accept INT here and validate the value
at parse time, rejecting any integer outside {0, 1}. OMEGA is the
`omega` keyword or `ω` codepoint. *)
quantity_b_sugar:
| COLON n = INT
{ match n with
| 0 -> QZero
| 1 -> QOne
| other ->
let msg = Printf.sprintf
"invalid quantity literal '%d'; expected 0, 1, or ω (omega)"
other in
raise (Parser_errors.Parse_action_error (msg, $startpos, $endpos)) }
| COLON OMEGA { QOmega }
param:
(* Self receiver: bare `self` — SELF_KW is a distinct keyword token.
No COLON or type annotation; type defaults to `Self`.
Four forms below cover all quantity × ownership × self combinations
that are LR(1) without option() conflicts. *)
| SELF_KW
{ { p_quantity = None; p_ownership = None;
p_name = mk_ident "self" $startpos $endpos;
p_ty = TyCon (mk_ident "Self" $startpos $endpos) } }
| own = ownership SELF_KW
{ { p_quantity = None; p_ownership = Some own;
p_name = mk_ident "self" $startpos $endpos;
p_ty = TyCon (mk_ident "Self" $startpos $endpos) } }
(* Normal params: explicit combinations to avoid option() LR(1) conflicts.
Tokens sets are disjoint: SELF_KW / ownership (REF|OWN|MUT) / quantity
(ZERO|ONE|OMEGA) / AT / ident (LOWER_IDENT|UPPER_IDENT). *)
| name = ident COLON ty = type_expr
{ { p_quantity = None; p_ownership = None; p_name = name; p_ty = ty } }
| own = ownership name = ident COLON ty = type_expr
{ { p_quantity = None; p_ownership = Some own; p_name = name; p_ty = ty } }
| qty = quantity name = ident COLON ty = type_expr
{ { p_quantity = Some qty; p_ownership = None; p_name = name; p_ty = ty } }
| qty = quantity own = ownership name = ident COLON ty = type_expr
{ { p_quantity = Some qty; p_ownership = Some own; p_name = name; p_ty = ty } }
(* ADR-007 Option C: @linear / @erased / @unrestricted attribute form *)
| qty_attr = quantity_attr name = ident COLON ty = type_expr
{ { p_quantity = Some qty_attr; p_ownership = None; p_name = name; p_ty = ty } }
| qty_attr = quantity_attr own = ownership name = ident COLON ty = type_expr
{ { p_quantity = Some qty_attr; p_ownership = Some own; p_name = name; p_ty = ty } }
ownership:
| OWN { Own }
| REF { Ref }
| MUT { Mut }
/* `param_list_trailing_comma` — comma-separated param list that also
accepts an optional trailing comma before the closing RPAREN, per the
Rust-likes estate convention. Hand-rolled right-recursive form
(rather than `separated_list(COMMA, param) COMMA?`) so the trailing
COMMA is absorbed inside the recursion: after each `param`, the LR(1)
choice on COMMA is unambiguous (shift into the recursive tail, whose
body may be empty when RPAREN follows). Adds no new s/r or r/r
conflicts beyond the grammar's existing baseline. */
param_list_trailing_comma:
| /* empty */ { [] }
| p = param { [p] }
| p = param COMMA rest = param_list_trailing_comma { p :: rest }
/* `expr_list_trailing_comma` — comma-separated expression list that also
accepts an optional trailing comma before the closing delimiter. Used by
array literals (`[a, b, c,]`) and function-call argument lists
(`f(a, b, c,)`). Same right-recursive shape as
`param_list_trailing_comma` (above): the COMMA-after-`expr` is absorbed
inside the recursive tail, whose body may be empty when the closing
token (RBRACKET / RPAREN) follows. Conflict-neutral: the existing rules
used `separated_list(COMMA, expr)`, which already inspects COMMA in the
same lookahead position; only the post-final-COMMA branch is new and
has no other production to compete with. Added 2026-05-26 (Refs
hyperpolymath/gitbot-fleet#148: sustainabot hand-port —
`json::encode_object([("k", v),])` and `f(..., last_arg,)`). */
expr_list_trailing_comma:
| /* empty */ { [] }
| e = expr { [e] }
| e = expr COMMA rest = expr_list_trailing_comma { e :: rest }
where_clause:
| WHERE constraints = separated_nonempty_list(COMMA, constraint_) { constraints }
constraint_:
| id = ident COLON bounds = separated_nonempty_list(PLUS, trait_bound)
{ ConstraintTrait (id, bounds) }
trait_bound:
| name = ident { { tb_name = name; tb_args = [] } }
| name = ident LBRACKET args = separated_list(COMMA, type_arg) RBRACKET
{ { tb_name = name; tb_args = args } }
/* ========== Types ========== */
type_decl:
/* Type alias: `type Foo = Bar` — semicolon is optional (conformance spec omits it) */
| vis = visibility? TYPE name = ident type_params = type_params? EQ ty = type_expr SEMICOLON?
{ { td_vis = Option.value vis ~default:Private;
td_name = name;
td_type_params = Option.value type_params ~default:[];
td_body = TyAlias ty } }
/* Inline variant syntax with optional leading pipe:
type X = A | B | C(Int) (no leading pipe — classic style)
type X = | A | B | C(Int) (leading pipe — spec style)
Semicolon is optional in both forms (conformance spec omits it). */
| vis = visibility? TYPE name = ident type_params = type_params? EQ
first = variant_decl PIPE rest = separated_nonempty_list(PIPE, variant_decl) SEMICOLON?
{ { td_vis = Option.value vis ~default:Private;
td_name = name;
td_type_params = Option.value type_params ~default:[];
td_body = TyEnum (first :: rest) } }
| vis = visibility? TYPE name = ident type_params = type_params? EQ
PIPE first = variant_decl rest = list(preceded(PIPE, variant_decl)) SEMICOLON?
{ { td_vis = Option.value vis ~default:Private;
td_name = name;
td_type_params = Option.value type_params ~default:[];
td_body = TyEnum (first :: rest) } }
| vis = visibility? STRUCT name = ident type_params = type_params?
LBRACE fields = separated_list(COMMA, struct_field) RBRACE
{ { td_vis = Option.value vis ~default:Private;
td_name = name;
td_type_params = Option.value type_params ~default:[];
td_body = TyStruct fields } }
| vis = visibility? ENUM name = ident type_params = type_params?
LBRACE variants = separated_list(COMMA, variant_decl) RBRACE
{ { td_vis = Option.value vis ~default:Private;
td_name = name;
td_type_params = Option.value type_params ~default:[];
td_body = TyEnum variants } }
struct_field:
| vis = visibility? name = field_name COLON ty = type_expr
{ { sf_vis = Option.value vis ~default:Private; sf_name = name; sf_ty = ty } }
variant_decl:
| name = ident { { vd_name = name; vd_fields = []; vd_ret_ty = None } }
| name = ident LPAREN fields = separated_list(COMMA, type_expr) RPAREN
{ { vd_name = name; vd_fields = fields; vd_ret_ty = None } }
| name = ident LPAREN fields = separated_list(COMMA, type_expr) RPAREN COLON ret = type_expr
{ { vd_name = name; vd_fields = fields; vd_ret_ty = Some ret } }
/* ========== Type Expressions ========== */
type_expr:
| ty = type_expr_arrow { ty }
type_expr_arrow:
| arg = type_expr_primary ARROW ret = type_expr_arrow
{ TyArrow (arg, None, ret, None) }
| arg = type_expr_primary MINUS LBRACE eff = effect_expr RBRACE ARROW ret = type_expr_arrow
{ TyArrow (arg, None, ret, Some eff) }
/* #547: slash-effect-row trailing form `T -> R / { E1, ... }` and
single-effect `T -> R / E`. Mirrors the return_type slash forms
in fn-decl signatures (lines 271-282) one level up to type-
expression position, closing the parser asymmetry surfaced in
#547: until this PR the `fn(...) -> R / { E }` syntax accepted
in fn-decl signatures parse-errored in record-field / type-alias
positions, forcing every effectful function-typed record field
to fall back to the older `-{E}->` arrow form. Both spellings
remain accepted; the slash form is the canonical effect-row
spelling from the Frontier Guide. Effect attaches to the
outermost arrow (the position of the slash); inner-arrow
attachment is still expressible via `-{E}->`. */
| arg = type_expr_primary ARROW ret = type_expr_arrow SLASH LBRACE effs = separated_nonempty_list(COMMA, effect_term) RBRACE
{ TyArrow (arg, None, ret, Some (effect_union_of_list effs)) }
| arg = type_expr_primary ARROW ret = type_expr_arrow SLASH single = effect_term
{ TyArrow (arg, None, ret, Some single) }
/* `(A, B, ...) -> R` lowers to the curried arrow `A -> B -> ... -> R`
so user source can write multi-arg fn types without manual currying.
The existing tuple-as-type rule (LPAREN ty COMMA tys RPAREN) still
applies when no ARROW follows — disambiguated at the first lookahead
past the closing RPAREN. */
| LPAREN ty1 = type_expr COMMA tys = separated_nonempty_list(COMMA, type_expr) RPAREN ARROW ret = type_expr_arrow
{ List.fold_right (fun p acc -> TyArrow (p, None, acc, None)) (ty1 :: tys) ret }
| ty = type_expr_primary %prec LOWEST_TYPE_ARROW { ty }
type_expr_primary:
| LPAREN RPAREN { TyTuple [] }
| LPAREN ty = type_expr RPAREN { ty }
| LPAREN ty = type_expr COMMA tys = separated_nonempty_list(COMMA, type_expr) RPAREN
{ TyTuple (ty :: tys) }
| UNDERSCORE { TyHole }
| OWN ty = type_expr_primary { TyOwn ty }
| REF ty = type_expr_primary { TyRef ty }
| MUT ty = type_expr_primary { TyMut ty }
| name = lower_ident { TyVar (mk_ident name $startpos $endpos) }
| name = upper_ident { TyCon (mk_ident name $startpos $endpos) }
/* ADR-014 (#228): module-qualified type name. `Pkg.Type` and
`Pkg::Type` (and deeper, `A.B.C` / `A::B::C`, mixed separators) are
accepted; the segments are folded into a single canonical name joined
by `::`, so `::` is the canonical form on print with no formatter
change and `.` is silently normalised. Conflict-safe: this only adds
`DOT`/`COLONCOLON` as lookahead after a type-position `upper_ident`,
where no reduce action previously existed (that absence is exactly the
`parse error at .` #228 reports), so it introduces no new LR conflict.
Resolution treats the `::`-joined name as a qualified reference. */
| name = qualified_type_name { TyCon (mk_ident name $startpos $endpos) }
| name = qualified_type_name LBRACKET args = separated_nonempty_list(COMMA, type_arg) RBRACKET
{ TyApp (mk_ident name $startpos $endpos, args) }
| name = qualified_type_name LT args = separated_nonempty_list(COMMA, type_arg) GT
{ TyApp (mk_ident name $startpos $endpos, args) }
| name = upper_ident LBRACKET args = separated_nonempty_list(COMMA, type_arg) RBRACKET
{ TyApp (mk_ident name $startpos(name) $endpos(name), args) }
/* Angle-bracket alias for type application: `Option<T>` ≡ `Option[T]`,
`Result<T, E>` ≡ `Result[T, E]`. Type contexts don't admit comparison
operators so `<` / `>` are unambiguous here even though the lexer's
LT/GT tokens are shared with expression-position less-than. */
| name = upper_ident LT args = separated_nonempty_list(COMMA, type_arg) GT
{ TyApp (mk_ident name $startpos(name) $endpos(name), args) }
/* Array sugar: `[T]` desugars to `Array[T]` (issues-drafts/02; #40). The
element type can be any type_expr (recursive), so `[[Int]]` means
Array[Array[Int]] and `[Result[T, E]]` works as expected. This is the
syntax stdlib has used all along (`fn map<T, U>(arr: [T], ...)`). The
typechecker (lib/typecheck.ml ~724, 813, 1024) canonicalises array
literals/operations on `TApp (TCon "Array", ...)`, so `Array` is the
right desugar target — `List` here would trigger a
`Unify.TypeMismatch (List, Array)` at check time. */
| LBRACKET elem = type_expr RBRACKET
{ TyApp (mk_ident "Array" $startpos $endpos, [TyArg elem]) }
/* Function-type-as-type: `fn(A, B) -> C` lowers to the curried arrow
chain `A -> B -> C`. Zero-arg `fn() -> T` lowers to `Unit -> T`
(modelled as `TyTuple [] -> T`). Required for higher-order signatures
like `f: fn() -> T` in stdlib/Option.affine. */
| FN LPAREN params = separated_list(COMMA, type_expr) RPAREN ARROW
ret = type_expr_arrow
{ match params with
| [] -> TyArrow (TyTuple [], None, ret, None)
| _ -> List.fold_right (fun p acc -> TyArrow (p, None, acc, None)) params ret }
/* #547: slash-effect-row form for fn-type, single + braced. Mirrors
the `MINUS LBRACE ... ARROW` variant immediately below it. The
effect attaches to the innermost arrow (the one whose result is
ret) to match the existing prefix-row semantics. */
| FN LPAREN params = separated_list(COMMA, type_expr) RPAREN ARROW
ret = type_expr_arrow SLASH LBRACE effs = separated_nonempty_list(COMMA, effect_term) RBRACE
{ let eff = effect_union_of_list effs in
match params with
| [] -> TyArrow (TyTuple [], None, ret, Some eff)
| _ ->
let rev_params = List.rev params in
(match rev_params with
| [] -> assert false
| last :: earlier_rev ->
let innermost = TyArrow (last, None, ret, Some eff) in
List.fold_left
(fun acc p -> TyArrow (p, None, acc, None))
innermost
earlier_rev) }
| FN LPAREN params = separated_list(COMMA, type_expr) RPAREN ARROW
ret = type_expr_arrow SLASH single = effect_term
{ match params with
| [] -> TyArrow (TyTuple [], None, ret, Some single)
| _ ->
let rev_params = List.rev params in
(match rev_params with
| [] -> assert false
| last :: earlier_rev ->
let innermost = TyArrow (last, None, ret, Some single) in
List.fold_left
(fun acc p -> TyArrow (p, None, acc, None))
innermost
earlier_rev) }
/* Effect-row variant: `fn(A, B) -{E}-> C`. Mirrors the prefix-row arrow
already accepted in `type_expr_arrow` and in `return_type`, and is
required by hand-ports such as `fn(Http::Request) -{IO}-> Http::Response`
(gitbot-fleet#148 Router.affine). For multi-arg `fn`, the row attaches
to the *final* (innermost) arrow — that is where the call actually
performs the effect, and it matches the single-arg case where
`A -{E}-> R` puts the row on the lone arrow. Lowering:
`fn(A, B) -{E}-> R` ≡ `A -> (B -{E}-> R)`. Grammar-cost: the
`FN LPAREN ... RPAREN` prefix already disambiguates against every
other type-position production, so adding the `MINUS LBRACE eff
RBRACE ARROW` continuation here introduces no new lookahead conflict
beyond the existing `type_expr_arrow` row-arrow rule it mirrors. */
| FN LPAREN params = separated_list(COMMA, type_expr) RPAREN
MINUS LBRACE eff = effect_expr RBRACE ARROW
ret = type_expr_arrow
{ match params with
| [] -> TyArrow (TyTuple [], None, ret, Some eff)
| _ ->
(* Attach eff to the innermost arrow (the one whose result is ret). *)
let rev_params = List.rev params in
(match rev_params with
| [] -> assert false
| last :: earlier_rev ->
let innermost = TyArrow (last, None, ret, Some eff) in
List.fold_left
(fun acc p -> TyArrow (p, None, acc, None))
innermost
earlier_rev) }
/* Row-polymorphic record type. We use a custom recursive rule rather than
`separated_list` because Menhir's separated_list greedily consumes the
COMMA separator and then cannot backtrack when the next token (ROW_VAR)
is not a valid row_field start. ty_record_body / ty_record_rest parse
the interior in one pass without lookahead conflicts. */
| LBRACE body = ty_record_body RBRACE
{ TyRecord (fst body, snd body) }
/* Built-in types */
| NAT { TyCon (mk_ident "Nat" $startpos $endpos) }
| INT_T { TyCon (mk_ident "Int" $startpos $endpos) }
| BOOL { TyCon (mk_ident "Bool" $startpos $endpos) }
| FLOAT_T { TyCon (mk_ident "Float" $startpos $endpos) }
| STRING_T { TyCon (mk_ident "String" $startpos $endpos) }
| CHAR_T { TyCon (mk_ident "Char" $startpos $endpos) }
| NEVER { TyCon (mk_ident "Never" $startpos $endpos) }
/* ty_record_body / ty_record_rest: recursive rules for the interior of a
row-polymorphic record type `{ f1: T1, f2: T2, ..r }`.
Using `separated_list` would cause an LALR(1) conflict: after parsing the
COMMA that separates a row_field from a ROW_VAR tail, the separator has
already been consumed and the parser cannot determine whether the next
production should be a row_field continuation or the row tail. These
rules shift that decision to the token AFTER the comma. */
ty_record_body:
(* empty record: {} *)
|
{ ([], None) }
(* record with only a row tail: {..r} *)
| rv = ROW_VAR
{ ([], Some (mk_ident rv $startpos $endpos)) }
(* record starting with a named field: {name: T, ...} *)
| field = row_field rest = ty_record_rest
{ (field :: fst rest, snd rest) }
ty_record_rest:
(* end — no trailing comma, no row tail *)
|
{ ([], None) }
(* trailing comma only *)
| COMMA
{ ([], None) }
(* row tail after comma: , ..r *)
| COMMA rv = ROW_VAR
{ ([], Some (mk_ident rv $startpos(rv) $endpos(rv))) }
(* another named field after comma: , name: T ... *)
| COMMA field = row_field rest = ty_record_rest
{ (field :: fst rest, snd rest) }
row_field:
| name = field_name COLON ty = type_expr
{ { rf_name = name; rf_ty = ty } }
type_arg:
| ty = type_expr { TyArg ty }
/* ========== Effects ========== */
effect_decl:
| vis = visibility? EFFECT name = ident type_params = type_params?
LBRACE ops = list(effect_op_decl) RBRACE
{ { ed_vis = Option.value vis ~default:Private;
ed_name = name;
ed_type_params = Option.value type_params ~default:[];
ed_ops = ops } }
/* Bare forward-declaration form `effect <name>;` (issue #135 slice 3).
stdlib/effects.affine declares `effect io;` / `effect state;` etc. and
supplies the operations separately as `extern fn ... / io;`. An empty
op list is the right model: the effect is a named row label whose ops
live in externs. */
| vis = visibility? EFFECT name = ident type_params = type_params? SEMICOLON
{ { ed_vis = Option.value vis ~default:Private;
ed_name = name;
ed_type_params = Option.value type_params ~default:[];
ed_ops = [] } }
effect_op_decl:
(* Type parameters on effect operations are allowed: `fn await[T](promise: Promise[T]) -> T;` *)
| FN name = ident _type_params = type_params? LPAREN params = param_list_trailing_comma RPAREN ret = return_type? SEMICOLON
{ { eod_name = name;
eod_params = params;
eod_ret_ty = fst (Option.value ret ~default:(None, None)) } }
effect_expr:
| e = effect_term { e }
| e1 = effect_expr PLUS e2 = effect_term { EffUnion (e1, e2) }
effect_term:
| name = ident { EffVar name }
| name = ident LBRACKET args = separated_list(COMMA, type_arg) RBRACKET
{ EffCon (name, args) }
/* ADR-014 (#228): module-qualified effect, e.g. `-{Externs.Net}->` /
`-{Externs::Net}->`. Same canonical `::`-fold as qualified types. */
| name = qualified_type_name
{ EffVar (mk_ident name $startpos $endpos) }
| name = qualified_type_name LBRACKET args = separated_list(COMMA, type_arg) RBRACKET
{ EffCon (mk_ident name $startpos $endpos, args) }
/* ========== Traits ========== */
trait_decl:
| vis = visibility? TRAIT name = ident type_params = type_params?
super = supertraits?
_where_clause = where_clause?
LBRACE items = list(trait_item) RBRACE
{ { trd_vis = Option.value vis ~default:Private;
trd_name = name;
trd_type_params = Option.value type_params ~default:[];
trd_super = Option.value super ~default:[];
trd_items = items } }
supertraits:
| COLON bounds = separated_nonempty_list(PLUS, trait_bound) { bounds }
trait_item:
| sig_ = fn_sig SEMICOLON { TraitFn sig_ }
/* Trait method *default body* (issue #135 slice 5). Previously the two
forms were `fn_sig SEMICOLON` vs a whole `fn_decl`, which share the
long prefix `visibility? FN name params return_type?`; the LR conflict
resolved toward the signature form, so `pub fn ne(ref self, ...) ->
Bool { ... }` (stdlib/traits.affine) failed at the `{`. Left-factor:
parse `fn_sig` once, then branch on SEMICOLON vs fn_body — no shared-
prefix ambiguity (the two now differ purely on the next token).
Trait defaults don't use `total`/`where` (none in stdlib); fd_total
= false, fd_where = []. */
| sig_ = fn_sig body = fn_body
{ TraitFnDefault { fd_vis = sig_.fs_vis;
fd_total = false;
fd_name = sig_.fs_name;
fd_type_params = sig_.fs_type_params;
fd_params = sig_.fs_params;
fd_ret_ty = sig_.fs_ret_ty;
fd_eff = sig_.fs_eff;
fd_where = [];
fd_body = body } }
| TYPE name = ident kind = kind_annotation? default = type_default? SEMICOLON
{ TraitType { tt_name = name; tt_kind = kind; tt_default = default } }
type_default:
| EQ ty = type_expr { ty }
fn_sig:
| vis = visibility? FN name = ident
type_params = type_params?
LPAREN params = param_list_trailing_comma RPAREN
ret = return_type?
{ { fs_vis = Option.value vis ~default:Private;
fs_name = name;
fs_type_params = Option.value type_params ~default:[];
fs_params = params;
fs_ret_ty = fst (Option.value ret ~default:(None, None));
fs_eff = snd (Option.value ret ~default:(None, None)) } }
/* ========== Impl ========== */
impl_block:
| IMPL type_params = type_params?
head = type_expr
forspec = impl_for?
where_clause = where_clause?
LBRACE items = list(impl_item) RBRACE
{ let trait_ref, self_ty =
match forspec with
| Some st -> (Some (trait_ref_of_type_expr head), st)
| None -> (None, head)
in
{ ib_type_params = Option.value type_params ~default:[];
ib_trait_ref = trait_ref;
ib_self_ty = self_ty;
ib_where = Option.value where_clause ~default:[];
ib_items = items } }
impl_for:
| FOR self_ty = type_expr { self_ty }
impl_item:
| f = fn_decl { ImplFn f }
| TYPE name = ident EQ ty = type_expr SEMICOLON { ImplType (name, ty) }
/* ========== Expressions ========== */
expr_only:
| e = expr EOF { e }
expr:
| e = expr_assign { e }
expr_assign:
/* `return`/`resume` are diverging prefix expressions: they greedily
consume the whole trailing expression and are NOT operands of
binary operators (affinescript#215 family B). Hoisting them here,
out of expr_primary, removes the ~12 per-precedence-level S/R
conflicts. `(return a) + b` now needs the explicit parens — which
is correct, since `return` diverges and was never a useful operand. */
| RETURN e = expr? { ExprReturn e }
| RESUME e = expr? { ExprResume e }
| BREAK { ExprBreak (mk_span $startpos $endpos) }
| CONTINUE { ExprContinue (mk_span $startpos $endpos) }
| lhs = expr_or EQ rhs = expr_assign
{ ExprLet { el_mut = false; el_quantity = None;
el_pat = PatVar (mk_ident "_" $startpos(lhs) $endpos(lhs));
el_ty = None; el_value = lhs; el_body = Some rhs } }
| e = expr_or { e }
expr_or:
| e1 = expr_or PIPEPIPE e2 = expr_and { ExprBinary (e1, OpOr, e2) }
| e = expr_and { e }
expr_and:
| e1 = expr_and AMPAMP e2 = expr_bitor { ExprBinary (e1, OpAnd, e2) }
| e = expr_bitor { e }
expr_bitor:
| e1 = expr_bitor PIPE e2 = expr_bitxor { ExprBinary (e1, OpBitOr, e2) }
| e = expr_bitxor { e }
expr_bitxor:
| e1 = expr_bitxor CARET e2 = expr_bitand { ExprBinary (e1, OpBitXor, e2) }
| e = expr_bitand { e }
expr_bitand:
| e1 = expr_bitand AMP e2 = expr_cmp { ExprBinary (e1, OpBitAnd, e2) }
| e = expr_cmp { e }
expr_cmp:
| e1 = expr_cmp EQEQ e2 = expr_shift { ExprBinary (e1, OpEq, e2) }
| e1 = expr_cmp NE e2 = expr_shift { ExprBinary (e1, OpNe, e2) }
| e1 = expr_cmp LT e2 = expr_shift { ExprBinary (e1, OpLt, e2) }
| e1 = expr_cmp LE e2 = expr_shift { ExprBinary (e1, OpLe, e2) }
| e1 = expr_cmp GT e2 = expr_shift { ExprBinary (e1, OpGt, e2) }
| e1 = expr_cmp GE e2 = expr_shift { ExprBinary (e1, OpGe, e2) }
| e = expr_shift { e }
expr_shift:
| e1 = expr_shift LTLT e2 = expr_add { ExprBinary (e1, OpShl, e2) }
| e1 = expr_shift GTGT e2 = expr_add { ExprBinary (e1, OpShr, e2) }
| e = expr_add { e }
expr_add:
| e1 = expr_add PLUS e2 = expr_mul { ExprBinary (e1, OpAdd, e2) }
| e1 = expr_add PLUSPLUS e2 = expr_mul { ExprBinary (e1, OpConcat, e2) }
| e1 = expr_add MINUS e2 = expr_mul { ExprBinary (e1, OpSub, e2) }
| e = expr_mul { e }
expr_mul:
| e1 = expr_mul STAR e2 = expr_unary { ExprBinary (e1, OpMul, e2) }
| e1 = expr_mul SLASH e2 = expr_unary { ExprBinary (e1, OpDiv, e2) }
| e1 = expr_mul PERCENT e2 = expr_unary { ExprBinary (e1, OpMod, e2) }
| e = expr_unary { e }
expr_unary:
| MINUS e = expr_unary { ExprUnary (OpNeg, e) }
| BANG e = expr_unary { ExprUnary (OpNot, e) }
| TILDE e = expr_unary { ExprUnary (OpBitNot, e) }
| AMP MUT e = expr_unary { ExprUnary (OpMutRef, e) }
| AMP e = expr_unary { ExprUnary (OpRef, e) }
| STAR e = expr_unary { ExprUnary (OpDeref, e) }
| e = expr_postfix { e }
expr_postfix:
/* field_name used here so that `r.handle` parses even though `handle` is a
keyword; field access is unambiguous after DOT. */
| e = expr_postfix DOT field = field_name { ExprField (e, field) }
| e = expr_postfix DOT n = INT { ExprTupleIndex (e, n) }
| e = expr_postfix LBRACKET idx = expr RBRACKET { ExprIndex (e, idx) }
/* Slice / range index (issue #135 slice 2): `e[a:b]`, `e[a:]`, `e[:b]`,
`e[:]`. Desugars to the `slice` builtin (a -> Int -> Int -> a; lowered
to JS `.slice` on the Deno-ESM backend, like `len`). No new AST node:
missing low = 0, missing high = `len(e)`. Used by stdlib/option.affine
(`list[1:]`) and stdlib/collections.affine. */
| e = expr_postfix LBRACKET lo = expr COLON hi = expr RBRACKET
{ ExprApp (ExprVar (mk_ident "slice" $startpos $endpos), [e; lo; hi]) }
| e = expr_postfix LBRACKET lo = expr COLON RBRACKET
{ ExprApp (ExprVar (mk_ident "slice" $startpos $endpos),
[e; lo; ExprApp (ExprVar (mk_ident "len" $startpos $endpos), [e])]) }
| e = expr_postfix LBRACKET COLON hi = expr RBRACKET
{ ExprApp (ExprVar (mk_ident "slice" $startpos $endpos),
[e; ExprLit (LitInt (0, mk_span $startpos $endpos)); hi]) }
| e = expr_postfix LBRACKET COLON RBRACKET
{ ExprApp (ExprVar (mk_ident "slice" $startpos $endpos),
[e; ExprLit (LitInt (0, mk_span $startpos $endpos));
ExprApp (ExprVar (mk_ident "len" $startpos $endpos), [e])]) }
| e = expr_postfix LPAREN args = expr_list_trailing_comma RPAREN { ExprApp (e, args) }
| e = expr_postfix BACKSLASH field = field_name { ExprRowRestrict (e, field) }
| e = expr_postfix QUESTION { ExprTry { et_body = { blk_stmts = []; blk_expr = Some e };
et_catch = None; et_finally = None } }
| e = expr_primary { e }
expr_primary:
/* Literals */
| n = INT { ExprLit (LitInt (n, mk_span $startpos $endpos)) }
| f = FLOAT { ExprLit (LitFloat (f, mk_span $startpos $endpos)) }
| c = CHAR { ExprLit (LitChar (c, mk_span $startpos $endpos)) }
| s = STRING { ExprLit (LitString (s, mk_span $startpos $endpos)) }
| TRUE { ExprLit (LitBool (true, mk_span $startpos $endpos)) }
| FALSE { ExprLit (LitBool (false, mk_span $startpos $endpos)) }
/* Identifiers */
/* `self` in expression position (issue #122 v2). The method-receiver
param productions already bind a parameter named "self"; this lets
the body actually reference it (`self.field`, `self.method(x)`).
Without this production SELF_KW had no expression form, so every
method body referencing self was a parse error — even
stdlib/traits.affine failed to parse. Resolves/typechecks as an
ordinary parameter binding named "self". */
| SELF_KW { ExprVar (mk_ident "self" $startpos $endpos) }
| name = lower_ident { ExprVar (mk_ident name $startpos $endpos) }
/* Struct literal: `Point #{ x: v, y: w }` (affinescript#215). The `#{`
sigil makes this unambiguous against a bare block and removes the
Rust-style struct-literal-in-`if`/`match`-scrutinee hazard entirely;
no production-ordering hack needed any more. */
| _ty = upper_ident HASH_LBRACE b = expr_record_body RBRACE
{ ExprRecord { er_fields = fst b; er_spread = snd b } }
| name = upper_ident { ExprVar (mk_ident name $startpos $endpos) }
| ty = upper_ident COLONCOLON variant = upper_ident
{ ExprVariant (mk_ident ty $startpos(ty) $endpos(ty),
mk_ident variant $startpos(variant) $endpos(variant)) }
/* INT-01 follow-up (Refs #178): module-qualified value path in
value-expression position, e.g. `Mod::fn(x)` or `Mod::CONST`. We
emit the same `ExprField (ExprVar Mod, lower_ident)` shape that
the `Mod.fn` form already produces, so [Resolve.lower_qualified
_value_paths] handles both syntaxes identically (canonical
`::`-fold; no resolver change required). Disambiguated from the
`Type::Variant` rule above by lower_ident vs upper_ident. */
| modu = upper_ident COLONCOLON fname = lower_ident
{ ExprField (ExprVar (mk_ident modu $startpos(modu) $endpos(modu)),
mk_ident fname $startpos(fname) $endpos(fname)) }
/* Builtin-type-qualified value path: `Int::to_string(n)`, `String::len(s)`,
etc. The built-in type names are reserved keyword tokens (INT_T, STRING_T,
...) rather than UPPER_IDENT, so the `upper_ident COLONCOLON lower_ident`
production above never fires for them. We replicate the same
`ExprField (ExprVar TypeName, lower_ident)` shape so [Resolve] sees a
uniform qualified-path AST. The lookahead after COLONCOLON (a lower_ident)
distinguishes this from any type-position use of the same keyword.
Added 2026-05-26 (Refs gitbot-fleet#148 sustainabot hand-port:
Int::to_string, Int::from_string, Float::to_string, etc.). */
| NAT COLONCOLON fname = lower_ident
{ ExprField (ExprVar (mk_ident "Nat" $startpos($1) $endpos($1)),
mk_ident fname $startpos(fname) $endpos(fname)) }
| INT_T COLONCOLON fname = lower_ident
{ ExprField (ExprVar (mk_ident "Int" $startpos($1) $endpos($1)),
mk_ident fname $startpos(fname) $endpos(fname)) }
| BOOL COLONCOLON fname = lower_ident
{ ExprField (ExprVar (mk_ident "Bool" $startpos($1) $endpos($1)),
mk_ident fname $startpos(fname) $endpos(fname)) }
| FLOAT_T COLONCOLON fname = lower_ident
{ ExprField (ExprVar (mk_ident "Float" $startpos($1) $endpos($1)),
mk_ident fname $startpos(fname) $endpos(fname)) }
| STRING_T COLONCOLON fname = lower_ident
{ ExprField (ExprVar (mk_ident "String" $startpos($1) $endpos($1)),
mk_ident fname $startpos(fname) $endpos(fname)) }
| CHAR_T COLONCOLON fname = lower_ident
{ ExprField (ExprVar (mk_ident "Char" $startpos($1) $endpos($1)),