localharness 0.54.0

Agents that own themselves: one Rust crate that's both an agent SDK (streaming, tools, hooks, policies, triggers, MCP) and a wallet-owning, self-sovereign agent that runs in the browser.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
//! SolidityLite parser — a [`SolTok`] stream → a [`Facet`] AST.
//!
//! Recursive-descent in the [`crate::rustlite::parser`] style, INCLUDING the
//! `MAX_RECURSION_DEPTH` guard (`enter`/`leave`): this compiler also runs in the
//! user's browser on agent/LLM-authored source, so deeply-nested adversarial
//! input must return a `CompileError` rather than overflow the wasm stack (an
//! uncatchable tab-killing abort). The floor grammar is shallow, but the guard
//! is wired now so the expression/statement layers added later inherit it for
//! free.
//!
//! Grammar (design §3 floor + the storage / mapping / param / msg.sender stretch):
//! ```text
//! facet  := ("facet"|"contract") Ident "{" (state_var|event_decl)* function+ "}"
//! state_var := Ty Ident ";"                              (scalar slot)
//!            | "mapping" "(" Ty "=>" Ty ")" Ident ";"    (mapping)
//! event_decl := "event" Ident "(" ( Ty "indexed"? Ident
//!                 ("," Ty "indexed"? Ident)* )? ")" ";"  (log signature)
//! params := "(" ( Ty Ident ("," Ty Ident)* )? ")"
//! function := "function" Ident params "external"
//!             ( view? "returns" "(" Ty ")" "{" "return" expr ";" "}"   (view getter)
//!             | "{" stmt* "}" )                          (mutating)
//! stmt   := "require" "(" expr "," StrLit ")" ";"        (guard / revert)
//!         | "emit" Ident "(" ( expr ("," expr)* )? ")" ";"  (LOGn)
//!         | Ident ("[" expr "]")? ("=" | "+=") expr ";"  (scalar / mapping write)
//! expr   := cmp                                          (top level)
//! cmp    := add ( ("<"|">"|"<="|">="|"==") add )?        (non-assoc comparison)
//! add    := term ("+" term)*                             (left-assoc +, binds tighter)
//! term   := IntLit | "msg" "." "sender" | Ident ("[" expr "]")?
//!           (Ident = scalar/param read; Ident[expr] = mapping read)
//! ```

use crate::error_codes as codes;
use crate::rustlite::{CompileError, Span};
use crate::soliditylite::ast::*;
use crate::soliditylite::lexer::{SolKind, SolTok};

/// Hard cap on recursive-descent nesting depth — same rationale as
/// [`crate::rustlite`]'s guard (browser-tab stack-overflow on adversarial input).
const MAX_RECURSION_DEPTH: usize = 96;

/// Parse a token stream into a single [`Facet`].
pub fn parse(tokens: &[SolTok]) -> Result<Facet, CompileError> {
    let mut p = Parser { tokens, pos: 0, depth: 0 };
    let facet = p.parse_facet()?;
    // Reject trailing tokens after the facet (a second top-level item, etc.).
    if !matches!(p.peek(), SolKind::Eof) {
        return Err(CompileError::at_code(
            codes::EXPECTED_ITEM,
            "only a single top-level `facet` is supported in v1".to_string(),
            p.span(),
        ));
    }
    Ok(facet)
}

struct Parser<'a> {
    tokens: &'a [SolTok],
    pos: usize,
    depth: usize,
}

impl Parser<'_> {
    fn peek(&self) -> &SolKind {
        // The stream always ends with Eof, so indexing is safe; clamp defensively.
        &self.tokens[self.pos.min(self.tokens.len() - 1)].kind
    }

    /// Peek `offset` tokens ahead (clamped to the trailing `Eof`). Used for the
    /// one-token lookahead that distinguishes `require(` from a bare `require` ref.
    fn peek_at(&self, offset: usize) -> &SolKind {
        &self.tokens[(self.pos + offset).min(self.tokens.len() - 1)].kind
    }

    fn span(&self) -> Span {
        self.tokens[self.pos.min(self.tokens.len() - 1)].span
    }

    fn advance(&mut self) -> &SolTok {
        let tok = &self.tokens[self.pos.min(self.tokens.len() - 1)];
        if self.pos + 1 < self.tokens.len() {
            self.pos += 1;
        }
        tok
    }

    /// Enter one recursion level; error past the cap instead of overflowing.
    fn enter(&mut self) -> Result<(), CompileError> {
        self.depth += 1;
        if self.depth > MAX_RECURSION_DEPTH {
            return Err(CompileError::at_code(
                codes::NESTING_TOO_DEEP,
                "nesting too deep".to_string(),
                self.span(),
            ));
        }
        Ok(())
    }

    fn leave(&mut self) {
        self.depth = self.depth.saturating_sub(1);
    }

    /// Consume a token of the expected kind (by discriminant) or error.
    fn expect(&mut self, want: &SolKind, what: &str) -> Result<SolTok, CompileError> {
        if std::mem::discriminant(self.peek()) == std::mem::discriminant(want) {
            Ok(self.advance().clone())
        } else {
            Err(CompileError::at_code(
                codes::UNEXPECTED_TOKEN,
                format!("expected {what}, got {:?}", self.peek()),
                self.span(),
            ))
        }
    }

    fn expect_ident(&mut self) -> Result<String, CompileError> {
        match self.peek().clone() {
            SolKind::Ident(name) => {
                self.advance();
                Ok(name)
            }
            other => Err(CompileError::at_code(
                codes::UNEXPECTED_TOKEN,
                format!("expected an identifier, got {other:?}"),
                self.span(),
            )),
        }
    }

    fn parse_facet(&mut self) -> Result<Facet, CompileError> {
        let facet_span = self.span();
        self.expect(&SolKind::Facet, "`facet`")?;
        let name = self.expect_ident()?;
        self.expect(&SolKind::LBrace, "`{`")?;

        let mut state_vars = Vec::new();
        let mut events = Vec::new();
        let mut functions = Vec::new();
        // Members: state vars (TypeName-led), event decls (contextual `event`),
        // then functions (`function`-led), in any interleaving the grammar admits.
        // `event` is a CONTEXTUAL keyword (a plain identifier elsewhere): it only
        // leads an event declaration when followed by `<Name> (` at facet top-level.
        loop {
            match self.peek() {
                SolKind::Function => functions.push(self.parse_function()?),
                SolKind::Mapping => state_vars.push(self.parse_mapping_var()?),
                SolKind::TypeName(_) => state_vars.push(self.parse_state_var()?),
                SolKind::Ident(name)
                    if name == "event"
                        && matches!(self.peek_at(1), SolKind::Ident(_))
                        && matches!(self.peek_at(2), SolKind::LParen) =>
                {
                    events.push(self.parse_event_decl()?)
                }
                SolKind::RBrace => break,
                other => {
                    return Err(CompileError::at_code(
                        codes::UNEXPECTED_TOKEN,
                        format!("expected `function`, a state-var type, an `event`, or `}}`, got {other:?}"),
                        self.span(),
                    ))
                }
            }
        }
        self.expect(&SolKind::RBrace, "`}`")?;

        if functions.is_empty() {
            return Err(CompileError::at_code(
                codes::EXPECTED_ITEM,
                "a facet must declare at least one function".to_string(),
                facet_span,
            ));
        }
        Ok(Facet { name, state_vars, events, functions, span: facet_span })
    }

    fn parse_ty(&mut self) -> Result<Ty, CompileError> {
        match self.peek().clone() {
            SolKind::TypeName(name) => {
                let span = self.span();
                self.advance();
                match name.as_str() {
                    "uint256" => Ok(Ty::Uint256),
                    "address" => Ok(Ty::Address),
                    "bool" => Ok(Ty::Bool),
                    "bytes32" => Ok(Ty::Bytes32),
                    // The dynamic types (#37): valid as a state var, a parameter, and
                    // a return type. `parse_state_var` routes a dynamic type to a
                    // `DynamicBytes` kind; other positions handle the single Ty.
                    "string" => Ok(Ty::String),
                    "bytes" => Ok(Ty::Bytes),
                    _ => Err(CompileError::at_code(codes::UNKNOWN_TYPE, format!("unknown type `{name}`"), span)),
                }
            }
            other => Err(CompileError::at_code(
                codes::EXPECTED_TYPE,
                format!("expected a type, got {other:?}"),
                self.span(),
            )),
        }
    }

    fn parse_state_var(&mut self) -> Result<StateVar, CompileError> {
        let span = self.span();
        let elem = self.parse_ty()?;
        // `<elem>[] <name>;` — a dynamic array; otherwise a scalar `<ty> <name>;` or,
        // for the dynamic types, a `string`/`bytes` state var (#37).
        let kind = if matches!(self.peek(), SolKind::LBracket) {
            self.advance(); // `[`
            self.expect(&SolKind::RBracket, "`]` (dynamic array; fixed-size `[N]` is unsupported in v1)")?;
            // A dynamic-element array (`string[]`/`bytes[]`) is deferred in v1.
            if elem.is_dynamic() {
                return Err(CompileError::at_code(
                    codes::UNSUPPORTED_FEATURE,
                    "arrays of `string`/`bytes` are unsupported in v1".to_string(),
                    span,
                ));
            }
            StateVarKind::Array { elem }
        } else if elem.is_dynamic() {
            StateVarKind::DynamicBytes { is_string: elem == Ty::String }
        } else {
            StateVarKind::Scalar(elem)
        };
        let name = self.expect_ident()?;
        self.expect(&SolKind::Semi, "`;`")?;
        Ok(StateVar { kind, name, span })
    }

    /// Parse a mapping state var: `mapping ( <key> => <value> ) <name> ;`.
    fn parse_mapping_var(&mut self) -> Result<StateVar, CompileError> {
        let span = self.span();
        self.expect(&SolKind::Mapping, "`mapping`")?;
        self.expect(&SolKind::LParen, "`(`")?;
        let key = self.parse_ty()?;
        self.expect(&SolKind::FatArrow, "`=>`")?;
        let value = self.parse_ty()?;
        self.expect(&SolKind::RParen, "`)`")?;
        let name = self.expect_ident()?;
        self.expect(&SolKind::Semi, "`;`")?;
        Ok(StateVar { kind: StateVarKind::Mapping { key, value }, name, span })
    }

    /// Parse an event declaration: `event <Name> ( <ty> [indexed] <name>
    /// ("," <ty> [indexed] <name>)* ) ;`. `event` (the contextual keyword) and the
    /// leading `<Name> (` are already confirmed by the caller's lookahead.
    fn parse_event_decl(&mut self) -> Result<EventDecl, CompileError> {
        let span = self.span();
        self.advance(); // `event` (the contextual keyword)
        let name = self.expect_ident()?;
        self.expect(&SolKind::LParen, "`(`")?;
        let mut args = Vec::new();
        if !matches!(self.peek(), SolKind::RParen) {
            loop {
                let arg_span = self.span();
                let ty = self.parse_ty()?;
                // Optional `indexed` modifier (a contextual keyword) before the name.
                let indexed = matches!(self.peek(), SolKind::Ident(kw) if kw == "indexed");
                if indexed {
                    self.advance(); // `indexed`
                }
                let arg_name = self.expect_ident()?;
                args.push(EventArg { ty, indexed, name: arg_name, span: arg_span });
                if matches!(self.peek(), SolKind::Comma) {
                    self.advance(); // `,`
                    continue;
                }
                break;
            }
        }
        self.expect(&SolKind::RParen, "`)`")?;
        self.expect(&SolKind::Semi, "`;`")?;
        Ok(EventDecl { name, args, span })
    }

    /// Parse a function parameter list `( )` or `( <ty> <name> ("," <ty> <name>)* )`.
    /// Each parameter is a value type plus a name; trailing commas are rejected.
    fn parse_param_list(&mut self) -> Result<Vec<Param>, CompileError> {
        self.expect(&SolKind::LParen, "`(`")?;
        let mut params = Vec::new();
        if !matches!(self.peek(), SolKind::RParen) {
            loop {
                let span = self.span();
                let ty = self.parse_ty()?;
                let name = self.expect_ident()?;
                params.push(Param { ty, name, span });
                if matches!(self.peek(), SolKind::Comma) {
                    self.advance(); // `,`
                    continue;
                }
                break;
            }
        }
        self.expect(&SolKind::RParen, "`)`")?;
        Ok(params)
    }

    fn parse_function(&mut self) -> Result<Function, CompileError> {
        self.enter()?;
        let result = self.parse_function_inner();
        self.leave();
        result
    }

    fn parse_function_inner(&mut self) -> Result<Function, CompileError> {
        let span = self.span();
        self.expect(&SolKind::Function, "`function`")?;
        let name = self.expect_ident()?;
        // Parameter list `( <ty> <name> ("," <ty> <name>)* )` (possibly empty).
        let params = self.parse_param_list()?;
        // `external` is required by the floor grammar.
        self.expect(&SolKind::External, "`external`")?;
        // Optional mutability (`view`/`pure`).
        let mutability = match self.peek() {
            SolKind::View => {
                self.advance();
                Mutability::View
            }
            SolKind::Pure => {
                self.advance();
                Mutability::Pure
            }
            _ => Mutability::NonPayable,
        };
        // Two shapes: a view getter (`returns (Ty) { return e; }`) or a mutating
        // function (no `returns`, body is `{ assign* }` — the write stretch).
        if matches!(self.peek(), SolKind::Returns) {
            // `returns ( <ty> )` — the getter always returns one word.
            self.advance(); // `returns`
            self.expect(&SolKind::LParen, "`(`")?;
            // Any value type, including the dynamic `string`/`bytes` (#37): a
            // `returns (string|bytes)` body is a constant literal OR an echo of a
            // dynamic parameter (handled at codegen).
            let returns = self.parse_ty()?;
            self.expect(&SolKind::RParen, "`)`")?;
            // Body: `{ return <expr> ; }`.
            self.expect(&SolKind::LBrace, "`{`")?;
            let body = self.parse_return_stmt()?;
            self.expect(&SolKind::RBrace, "`}`")?;
            Ok(Function { name, params, mutability, returns: Some(returns), body, span })
        } else {
            // Mutating function: no `returns`, body is a block of assignments.
            let body = self.parse_mutating_block()?;
            Ok(Function { name, params, mutability, returns: None, body, span })
        }
    }

    fn parse_return_stmt(&mut self) -> Result<Stmt, CompileError> {
        self.expect(&SolKind::Return, "`return`")?;
        let expr = self.parse_expr()?;
        self.expect(&SolKind::Semi, "`;`")?;
        Ok(Stmt::Return(expr))
    }

    /// Parse a mutating function body `{ <assign>* }` into a [`Stmt::Block`]. Each
    /// statement is a state-var assignment (`<ident> = <expr> ;`); zero statements
    /// (an empty body) is allowed.
    fn parse_mutating_block(&mut self) -> Result<Stmt, CompileError> {
        self.enter()?;
        let result = self.parse_mutating_block_inner();
        self.leave();
        result
    }

    fn parse_mutating_block_inner(&mut self) -> Result<Stmt, CompileError> {
        Ok(Stmt::Block(self.parse_brace_block()?))
    }

    /// Parse a `{ <stmt>* }` brace block into its statement list (reused by the
    /// function body and by both `if`/`else` branches). The braces are required.
    fn parse_brace_block(&mut self) -> Result<Vec<Stmt>, CompileError> {
        self.expect(&SolKind::LBrace, "`{`")?;
        let mut stmts = Vec::new();
        while !matches!(self.peek(), SolKind::RBrace) {
            stmts.push(self.parse_stmt()?);
        }
        self.expect(&SolKind::RBrace, "`}`")?;
        Ok(stmts)
    }

    /// Parse `if ( <cond> ) { <stmt>* } [ else ( { <stmt>* } | <if> ) ]`. `if` and
    /// `else` are contextual identifiers (reserved nowhere else in the v1 grammar).
    /// An `else if` chains by recursing, so the else branch is a single nested `If`.
    /// `enter`/`leave` bound nesting depth so deeply-nested `if`s error cleanly.
    fn parse_if_stmt(&mut self) -> Result<Stmt, CompileError> {
        self.enter()?;
        let span = self.span();
        self.advance(); // `if`
        self.expect(&SolKind::LParen, "`(`")?;
        let cond = self.parse_expr()?;
        self.expect(&SolKind::RParen, "`)`")?;
        let then_body = self.parse_brace_block()?;
        let else_body = if matches!(self.peek(), SolKind::Ident(name) if name == "else") {
            self.advance(); // `else`
            if matches!(self.peek(), SolKind::Ident(name) if name == "if")
                && matches!(self.peek_at(1), SolKind::LParen)
            {
                vec![self.parse_if_stmt()?] // `else if` → nested If
            } else {
                self.parse_brace_block()?
            }
        } else {
            Vec::new()
        };
        self.leave();
        Ok(Stmt::If { cond, then_body, else_body, span })
    }

    /// Parse one statement inside a mutating body: a `require(...)` guard or an
    /// assignment. `require` is a contextual keyword (a plain identifier elsewhere),
    /// recognized only when it leads a statement and is followed by `(`.
    fn parse_stmt(&mut self) -> Result<Stmt, CompileError> {
        // `if` is contextual (a plain identifier elsewhere): it leads an `if`
        // statement only when followed by `(`.
        if matches!(self.peek(), SolKind::Ident(name) if name == "if")
            && matches!(self.peek_at(1), SolKind::LParen)
        {
            return self.parse_if_stmt();
        }
        if matches!(self.peek(), SolKind::Ident(name) if name == "require")
            && matches!(self.peek_at(1), SolKind::LParen)
        {
            return self.parse_require_stmt();
        }
        // `emit` is contextual (a plain identifier elsewhere): it leads an emit
        // statement only when followed by `<Name> (`.
        if matches!(self.peek(), SolKind::Ident(name) if name == "emit")
            && matches!(self.peek_at(1), SolKind::Ident(_))
            && matches!(self.peek_at(2), SolKind::LParen)
        {
            return self.parse_emit_stmt();
        }
        // `delete <arr>[<i>];` — a dynamic-array element clear.
        if matches!(self.peek(), SolKind::Delete) {
            return self.parse_delete_stmt();
        }
        // `<arr>.push(<expr>);` — a dynamic-array append: `<ident> . push (`.
        if matches!(self.peek(), SolKind::Ident(_))
            && matches!(self.peek_at(1), SolKind::Dot)
            && matches!(self.peek_at(2), SolKind::Ident(m) if m == "push")
            && matches!(self.peek_at(3), SolKind::LParen)
        {
            return self.parse_push_stmt();
        }
        // `<arr>.pop();` — a dynamic-array remove-last: `<ident> . pop ( )`.
        if matches!(self.peek(), SolKind::Ident(_))
            && matches!(self.peek_at(1), SolKind::Dot)
            && matches!(self.peek_at(2), SolKind::Ident(m) if m == "pop")
            && matches!(self.peek_at(3), SolKind::LParen)
        {
            return self.parse_pop_stmt();
        }
        self.parse_assign_stmt()
    }

    /// Parse `emit <Name> ( <expr> ("," <expr>)* ) ;`. The argument count is checked
    /// against the event declaration at codegen (the parser doesn't know the
    /// declared events). Each argument is an expression in the same lattice as a
    /// `return`/assignment value.
    fn parse_emit_stmt(&mut self) -> Result<Stmt, CompileError> {
        let span = self.span();
        self.advance(); // `emit` (the contextual keyword)
        let name = self.expect_ident()?;
        self.expect(&SolKind::LParen, "`(`")?;
        let mut args = Vec::new();
        if !matches!(self.peek(), SolKind::RParen) {
            loop {
                args.push(self.parse_expr()?);
                if matches!(self.peek(), SolKind::Comma) {
                    self.advance(); // `,`
                    continue;
                }
                break;
            }
        }
        self.expect(&SolKind::RParen, "`)`")?;
        self.expect(&SolKind::Semi, "`;`")?;
        Ok(Stmt::Emit { name, args, span })
    }

    /// Parse `<arr> . push ( <expr> ) ;` — a dynamic-array append. The leading
    /// `<ident> . push (` is already confirmed by the caller's lookahead; the array
    /// name is resolved against the facet's state vars (it must be an array) at
    /// codegen.
    fn parse_push_stmt(&mut self) -> Result<Stmt, CompileError> {
        let span = self.span();
        let base = self.expect_ident()?; // the array name
        self.advance(); // `.`
        self.advance(); // `push`
        self.expect(&SolKind::LParen, "`(`")?;
        let value = self.parse_expr()?;
        self.expect(&SolKind::RParen, "`)`")?;
        self.expect(&SolKind::Semi, "`;`")?;
        Ok(Stmt::Push { base, value, span })
    }

    /// Parse `<arr> . pop ( ) ;` — a dynamic-array remove-last. The leading
    /// `<ident> . pop (` is already confirmed by the caller's lookahead; `pop` takes
    /// no arguments. The array name is resolved against the facet's state vars (it
    /// must be an array) at codegen.
    fn parse_pop_stmt(&mut self) -> Result<Stmt, CompileError> {
        let span = self.span();
        let base = self.expect_ident()?; // the array name
        self.advance(); // `.`
        self.advance(); // `pop`
        self.expect(&SolKind::LParen, "`(`")?;
        self.expect(&SolKind::RParen, "`)` (pop takes no arguments)")?;
        self.expect(&SolKind::Semi, "`;`")?;
        Ok(Stmt::Pop { base, span })
    }

    /// Parse `delete <arr> [ <i> ] ;` — a dynamic-array element clear (zeroes the
    /// element, leaving the length unchanged). The `delete` keyword is already
    /// consumed-on-confirm by the caller; the target must be an indexed array.
    fn parse_delete_stmt(&mut self) -> Result<Stmt, CompileError> {
        let span = self.span();
        self.advance(); // `delete`
        let base = self.expect_ident()?; // the array name
        self.expect(&SolKind::LBracket, "`[` (only `delete <array>[<i>];` is supported in v1)")?;
        let key = self.parse_expr()?;
        self.expect(&SolKind::RBracket, "`]`")?;
        self.expect(&SolKind::Semi, "`;`")?;
        Ok(Stmt::DeleteIndex { base, key, span })
    }

    /// Parse `require ( <cond> , <strlit> ) ;`. The condition can be any expression
    /// (typically a comparison). The message string is required by the floor grammar
    /// but DISCARDED by codegen (an empty-data revert aborts the call regardless).
    fn parse_require_stmt(&mut self) -> Result<Stmt, CompileError> {
        let span = self.span();
        self.advance(); // `require` (the contextual keyword)
        self.expect(&SolKind::LParen, "`(`")?;
        let cond = self.parse_expr()?;
        self.expect(&SolKind::Comma, "`,`")?;
        // The message: a string literal (consumed, then ignored by codegen).
        match self.peek().clone() {
            SolKind::Str(_) => {
                self.advance();
            }
            other => {
                return Err(CompileError::at_code(
                    codes::EXPECTED_EXPRESSION,
                    format!("expected a string message in `require(cond, \"\")`, got {other:?}"),
                    self.span(),
                ))
            }
        }
        self.expect(&SolKind::RParen, "`)`")?;
        self.expect(&SolKind::Semi, "`;`")?;
        Ok(Stmt::Require { cond, span })
    }

    /// Parse one assignment: `<stateVar> = <expr> ;` or `<mapping>[<key>] = <expr> ;`.
    /// The target must be a bare identifier (optionally followed by an `[<key>]`
    /// index) — a literal/expression on the left is an invalid assign target.
    fn parse_assign_stmt(&mut self) -> Result<Stmt, CompileError> {
        let span = self.span();
        let name = match self.peek().clone() {
            SolKind::Ident(name) => {
                self.advance();
                name
            }
            other => {
                return Err(CompileError::at_code(
                    codes::INVALID_ASSIGN_TARGET,
                    format!("assignment target must be a state variable, got {other:?}"),
                    span,
                ))
            }
        };
        // Optional index `[<key>]` for a mapping-entry assignment.
        let index_key = if matches!(self.peek(), SolKind::LBracket) {
            self.advance(); // `[`
            let key = self.parse_expr()?;
            self.expect(&SolKind::RBracket, "`]`")?;
            Some(key)
        } else {
            None
        };
        // Either `=` (plain assign) or `+=` (compound, lexed as `+` then `=`). The
        // compound form desugars `t += e` to `t = t + e`, reusing the target as a
        // read of itself (`x += e` → `x = x + e`; `m[k] += e` → `m[k] = m[k] + e`).
        let compound = matches!(self.peek(), SolKind::Plus)
            && matches!(self.peek_at(1), SolKind::Assign);
        if compound {
            self.advance(); // `+`
            self.advance(); // `=`
        } else {
            self.expect(&SolKind::Assign, "`=` or `+=`")?;
        }
        let rhs = self.parse_expr()?;
        self.expect(&SolKind::Semi, "`;`")?;
        let value = if compound {
            // Desugar: build `<target_read> + <rhs>`.
            let target_read = match &index_key {
                Some(key) => Expr::Index { base: name.clone(), key: Box::new(key.clone()), span },
                None => Expr::StateVar { name: name.clone(), span },
            };
            Expr::Add { lhs: Box::new(target_read), rhs: Box::new(rhs), span }
        } else {
            rhs
        };
        match index_key {
            Some(key) => Ok(Stmt::IndexAssign { base: name, key, value, span }),
            None => Ok(Stmt::Assign { name, value, span }),
        }
    }

    /// Parse an expression. The top level is a comparison (binds loosest), which in
    /// turn parses additions (bind tighter), which parse terms.
    fn parse_expr(&mut self) -> Result<Expr, CompileError> {
        self.enter()?;
        let result = self.parse_cmp();
        self.leave();
        result
    }

    /// `add ( <cmp_op> add )?` — a single, NON-associative comparison (`a > b`).
    /// Comparisons bind LOOSER than `+`, so `n + 1 > 0` is `(n + 1) > 0`. Chaining
    /// (`a < b < c`) is not part of the grammar; a second comparison operator is a
    /// clean error at the enclosing `;`/`)` rather than silently mis-associating.
    fn parse_cmp(&mut self) -> Result<Expr, CompileError> {
        let lhs = self.parse_add()?;
        let op = match self.peek() {
            SolKind::Gt => CmpOp::Gt,
            SolKind::Lt => CmpOp::Lt,
            SolKind::Ge => CmpOp::Ge,
            SolKind::Le => CmpOp::Le,
            SolKind::EqEq => CmpOp::Eq,
            SolKind::BangEq => CmpOp::Neq,
            _ => return Ok(lhs),
        };
        let op_span = self.span();
        self.advance(); // the comparison operator
        let rhs = self.parse_add()?;
        Ok(Expr::Cmp { op, lhs: Box::new(lhs), rhs: Box::new(rhs), span: op_span })
    }

    /// `term ("+" term)*` — folds left so `a + b + c` parses as `(a + b) + c`.
    fn parse_add(&mut self) -> Result<Expr, CompileError> {
        let mut lhs = self.parse_mul()?;
        loop {
            let op_span = self.span();
            match self.peek() {
                SolKind::Plus => {
                    self.advance(); // `+`
                    let rhs = self.parse_mul()?;
                    lhs = Expr::Add { lhs: Box::new(lhs), rhs: Box::new(rhs), span: op_span };
                }
                SolKind::Minus => {
                    self.advance(); // `-`
                    let rhs = self.parse_mul()?;
                    lhs = Expr::Sub { lhs: Box::new(lhs), rhs: Box::new(rhs), span: op_span };
                }
                _ => break,
            }
        }
        Ok(lhs)
    }

    /// `primary ( ("*"|"/"|"%") primary )*` — the multiplicative tier, binding
    /// TIGHTER than `+`/`-` so `a + b * c` is `a + (b * c)`. Left-associative.
    fn parse_mul(&mut self) -> Result<Expr, CompileError> {
        let mut lhs = self.parse_primary()?;
        loop {
            let op_span = self.span();
            match self.peek() {
                SolKind::Star => {
                    self.advance(); // `*`
                    let rhs = self.parse_primary()?;
                    lhs = Expr::Mul { lhs: Box::new(lhs), rhs: Box::new(rhs), span: op_span };
                }
                SolKind::Slash => {
                    self.advance(); // `/`
                    let rhs = self.parse_primary()?;
                    lhs = Expr::Div { lhs: Box::new(lhs), rhs: Box::new(rhs), span: op_span };
                }
                SolKind::Percent => {
                    self.advance(); // `%`
                    let rhs = self.parse_primary()?;
                    lhs = Expr::Mod { lhs: Box::new(lhs), rhs: Box::new(rhs), span: op_span };
                }
                _ => break,
            }
        }
        Ok(lhs)
    }

    fn parse_primary(&mut self) -> Result<Expr, CompileError> {
        match self.peek().clone() {
            SolKind::Int(word) => {
                let span = self.span();
                self.advance();
                Ok(Expr::IntLit { value_be32: word, span })
            }
            // A string literal — valid only as a whole `return "…";` (enforced at
            // codegen); the decoded UTF-8 bytes ride along for `Body::ConstString`.
            SolKind::Str(s) => {
                let span = self.span();
                self.advance();
                Ok(Expr::StrLit { value: s.into_bytes(), span })
            }
            // An identifier is `msg.sender`, a `<mapping>[<key>]` index, a bare
            // state-variable read, or a bare parameter reference (the last two are
            // both `Expr::StateVar`, disambiguated at codegen).
            SolKind::Ident(name) => {
                let span = self.span();
                self.advance();
                // `msg.sender`: `msg` is a plain identifier, then `.` `sender`.
                if name == "msg" && matches!(self.peek(), SolKind::Dot) {
                    self.advance(); // `.`
                    let member = self.expect_ident()?;
                    if member != "sender" {
                        return Err(CompileError::at_code(
                            codes::UNSUPPORTED_FEATURE,
                            format!("only `msg.sender` is supported, got `msg.{member}`"),
                            span,
                        ));
                    }
                    return Ok(Expr::MsgSender { span });
                }
                // `block.timestamp` / `block.number`: `block` is a plain identifier.
                if name == "block" && matches!(self.peek(), SolKind::Dot) {
                    self.advance(); // `.`
                    let member = self.expect_ident()?;
                    return match member.as_str() {
                        "timestamp" => Ok(Expr::BlockTimestamp { span }),
                        "number" => Ok(Expr::BlockNumber { span }),
                        other => Err(CompileError::at_code(
                            codes::UNSUPPORTED_FEATURE,
                            format!("only `block.timestamp` and `block.number` are supported, got `block.{other}`"),
                            span,
                        )),
                    };
                }
                // `<mapping>[<key>]` / `<arr>[<i>]` index read.
                if matches!(self.peek(), SolKind::LBracket) {
                    self.advance(); // `[`
                    let key = self.parse_expr()?;
                    self.expect(&SolKind::RBracket, "`]`")?;
                    return Ok(Expr::Index { base: name, key: Box::new(key), span });
                }
                // `<arr>.length` — a dynamic array's length (the only `.member` on a
                // bare state var in v1). Anything else after `.` is a clean error.
                if matches!(self.peek(), SolKind::Dot) {
                    self.advance(); // `.`
                    let member = self.expect_ident()?;
                    if member != "length" {
                        return Err(CompileError::at_code(
                            codes::UNSUPPORTED_FEATURE,
                            format!("only `<array>.length` is supported, got `{name}.{member}`"),
                            span,
                        ));
                    }
                    return Ok(Expr::ArrayLen { base: name, span });
                }
                Ok(Expr::StateVar { name, span })
            }
            other => Err(CompileError::at_code(
                codes::EXPECTED_EXPRESSION,
                format!("expected an integer literal or a state variable, got {other:?}"),
                self.span(),
            )),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::soliditylite::lexer::lex;

    fn parse_src(src: &str) -> Result<Facet, CompileError> {
        let toks = lex(src)?;
        parse(&toks)
    }

    #[test]
    fn parses_the_floor_grammar() {
        let f = parse_src(
            "facet C { function get() external view returns (uint256) { return 42; } }",
        )
        .unwrap();
        assert_eq!(f.name, "C");
        assert_eq!(f.functions.len(), 1);
        let func = &f.functions[0];
        assert_eq!(func.name, "get");
        assert_eq!(func.mutability, Mutability::View);
        assert_eq!(func.returns, Some(Ty::Uint256));
        match &func.body {
            Stmt::Return(Expr::IntLit { value_be32, .. }) => {
                let mut w = [0u8; 32];
                w[31] = 42;
                assert_eq!(value_be32, &w);
            }
            other => panic!("unexpected body {other:?}"),
        }
    }

    #[test]
    fn parses_two_functions() {
        let f = parse_src(
            "facet Two { function a() external view returns (uint256) { return 1; } \
             function b() external view returns (uint256) { return 2; } }",
        )
        .unwrap();
        assert_eq!(f.functions.len(), 2);
        assert_eq!(f.functions[0].name, "a");
        assert_eq!(f.functions[1].name, "b");
    }

    #[test]
    fn empty_facet_is_rejected() {
        let e = parse_src("facet C { }").unwrap_err();
        assert_eq!(e.code, Some(codes::EXPECTED_ITEM));
    }

    #[test]
    fn missing_semicolon_is_a_clean_error() {
        let e = parse_src(
            "facet C { function get() external view returns (uint256) { return 42 } }",
        )
        .unwrap_err();
        assert_eq!(e.code, Some(codes::UNEXPECTED_TOKEN));
    }

    #[test]
    fn function_parameters_parse() {
        // Parameters are now supported: one `uint256 x` arg, referenced in the body.
        let f = parse_src(
            "facet C { function get(uint256 x) external view returns (uint256) { return x; } }",
        )
        .unwrap();
        let func = &f.functions[0];
        assert_eq!(func.params.len(), 1);
        assert_eq!(func.params[0].name, "x");
        assert_eq!(func.params[0].ty, Ty::Uint256);
        // The bare `x` in the body is a (param) StateVar reference.
        match &func.body {
            Stmt::Return(Expr::StateVar { name, .. }) => assert_eq!(name, "x"),
            other => panic!("unexpected body {other:?}"),
        }
    }

    #[test]
    fn multiple_parameters_parse_comma_separated() {
        let f = parse_src(
            "facet C { function f(uint256 a, address b) external { } }",
        )
        .unwrap();
        let params = &f.functions[0].params;
        assert_eq!(params.len(), 2);
        assert_eq!(params[0].name, "a");
        assert_eq!(params[0].ty, Ty::Uint256);
        assert_eq!(params[1].name, "b");
        assert_eq!(params[1].ty, Ty::Address);
    }

    #[test]
    fn trailing_item_after_facet_is_rejected() {
        let e = parse_src(
            "facet C { function get() external view returns (uint256) { return 1; } } facet D {}",
        )
        .unwrap_err();
        assert_eq!(e.code, Some(codes::EXPECTED_ITEM));
    }

    #[test]
    fn recursion_guard_errors_past_the_cap() {
        // Drive the guard directly: entering `MAX_RECURSION_DEPTH` levels is fine,
        // the next `enter` must return NESTING_TOO_DEEP instead of recursing (the
        // floor grammar's flat exprs can't naturally nest this deep, so the guard
        // is exercised at the mechanism level — same as rustlite's guard unit test).
        let toks = lex("facet C { function get() external view returns (uint256) { return 1; } }")
            .unwrap();
        let mut p = Parser { tokens: &toks, pos: 0, depth: 0 };
        for _ in 0..MAX_RECURSION_DEPTH {
            p.enter().expect("entering up to the cap is allowed");
        }
        let e = p.enter().expect_err("one past the cap must error, not overflow");
        assert_eq!(e.code, Some(codes::NESTING_TOO_DEEP));
        // And `leave` unwinds without underflowing past zero.
        for _ in 0..(MAX_RECURSION_DEPTH + 10) {
            p.leave();
        }
        assert_eq!(p.depth, 0);
    }

    #[test]
    fn parses_a_state_var_then_function() {
        let f = parse_src(
            "facet S { uint256 total; function get() external view returns (uint256) { return total; } }",
        )
        .unwrap();
        assert_eq!(f.state_vars.len(), 1);
        assert_eq!(f.state_vars[0].name, "total");
        match &f.functions[0].body {
            Stmt::Return(Expr::StateVar { name, .. }) => assert_eq!(name, "total"),
            other => panic!("unexpected body {other:?}"),
        }
    }

    #[test]
    fn parses_a_dynamic_array_var_with_length_index_and_push() {
        let f = parse_src(
            "facet C { uint256[] xs; \
             function add(uint256 v) external { xs.push(v); } \
             function set(uint256 i, uint256 v) external { xs[i] = v; } \
             function at(uint256 i) external view returns (uint256) { return xs[i]; } \
             function len() external view returns (uint256) { return xs.length; } }",
        )
        .unwrap();
        // The state var parses as an `Array { elem: uint256 }`.
        assert_eq!(f.state_vars.len(), 1);
        assert_eq!(f.state_vars[0].name, "xs");
        assert_eq!(f.state_vars[0].kind, StateVarKind::Array { elem: Ty::Uint256 });
        // add(): `xs.push(v);` → a Push statement.
        match &f.functions[0].body {
            Stmt::Block(stmts) => match &stmts[0] {
                Stmt::Push { base, value, .. } => {
                    assert_eq!(base, "xs");
                    assert!(matches!(value, Expr::StateVar { name, .. } if name == "v"));
                }
                other => panic!("expected a Push, got {other:?}"),
            },
            other => panic!("unexpected body {other:?}"),
        }
        // set(): `xs[i] = v;` → an IndexAssign (array vs mapping is a codegen concern).
        match &f.functions[1].body {
            Stmt::Block(stmts) => assert!(matches!(&stmts[0], Stmt::IndexAssign { base, .. } if base == "xs")),
            other => panic!("unexpected body {other:?}"),
        }
        // at(): `return xs[i];` → an Index read.
        assert!(matches!(&f.functions[2].body, Stmt::Return(Expr::Index { base, .. }) if base == "xs"));
        // len(): `return xs.length;` → an ArrayLen read.
        assert!(matches!(&f.functions[3].body, Stmt::Return(Expr::ArrayLen { base, .. }) if base == "xs"));
    }

    #[test]
    fn parses_dynamic_string_and_bytes_state_vars_and_params() {
        // `string`/`bytes` state vars parse to a `DynamicBytes` kind (#37).
        let f = parse_src(
            "facet D { string s; bytes b; \
             function get() external view returns (string) { return s; } }",
        )
        .unwrap();
        assert_eq!(f.state_vars.len(), 2);
        assert_eq!(f.state_vars[0].kind, StateVarKind::DynamicBytes { is_string: true });
        assert_eq!(f.state_vars[1].kind, StateVarKind::DynamicBytes { is_string: false });
        // A `string` parameter + a dynamic return type parse (previously a hard error).
        let f = parse_src(
            "facet E { function echo(string s) external pure returns (string) { return s; } }",
        )
        .unwrap();
        let p = &f.functions[0].params[0];
        assert_eq!(p.name, "s");
        assert_eq!(p.ty, Ty::String);
        assert_eq!(f.functions[0].returns, Some(Ty::String));
        // A `bytes` parameter likewise.
        let f = parse_src(
            "facet E { function echo(bytes b) external pure returns (bytes) { return b; } }",
        )
        .unwrap();
        assert_eq!(f.functions[0].params[0].ty, Ty::Bytes);
        assert_eq!(f.functions[0].returns, Some(Ty::Bytes));
    }

    #[test]
    fn dynamic_element_array_is_a_clean_error() {
        // `string[]` / `bytes[]` are deferred in v1 → a clean UNSUPPORTED_FEATURE.
        let e = parse_src(
            "facet C { string[] xs; function f() external view returns (uint256) { return 1; } }",
        )
        .unwrap_err();
        assert_eq!(e.code, Some(codes::UNSUPPORTED_FEATURE));
    }

    #[test]
    fn parses_array_pop_and_delete() {
        // `.pop()` → a Pop statement; `delete xs[i];` → a DeleteIndex statement.
        let f = parse_src(
            "facet C { uint256[] xs; \
             function pop() external { xs.pop(); } \
             function clear(uint256 i) external { delete xs[i]; } }",
        )
        .unwrap();
        // pop(): `xs.pop();`
        match &f.functions[0].body {
            Stmt::Block(stmts) => match &stmts[0] {
                Stmt::Pop { base, .. } => assert_eq!(base, "xs"),
                other => panic!("expected a Pop, got {other:?}"),
            },
            other => panic!("unexpected body {other:?}"),
        }
        // clear(): `delete xs[i];`
        match &f.functions[1].body {
            Stmt::Block(stmts) => match &stmts[0] {
                Stmt::DeleteIndex { base, key, .. } => {
                    assert_eq!(base, "xs");
                    assert!(matches!(key, Expr::StateVar { name, .. } if name == "i"));
                }
                other => panic!("expected a DeleteIndex, got {other:?}"),
            },
            other => panic!("unexpected body {other:?}"),
        }
    }

    #[test]
    fn pop_with_an_argument_is_a_clean_error() {
        // `xs.pop(1)` — pop takes no arguments.
        let e = parse_src("facet C { uint256[] xs; function f() external { xs.pop(1); } }")
            .unwrap_err();
        assert_eq!(e.code, Some(codes::UNEXPECTED_TOKEN));
    }

    #[test]
    fn delete_without_an_index_is_a_clean_error() {
        // `delete xs;` — v1 only supports `delete <array>[<i>];`.
        let e = parse_src("facet C { uint256[] xs; function f() external { delete xs; } }")
            .unwrap_err();
        assert_eq!(e.code, Some(codes::UNEXPECTED_TOKEN));
    }

    #[test]
    fn pop_is_usable_as_an_identifier() {
        // A bare `pop` (not `<arr>.pop(`) is a normal name (function name here).
        let f = parse_src(
            "facet C { uint256 pop; function get() external view returns (uint256) { return pop; } }",
        )
        .unwrap();
        assert_eq!(f.state_vars[0].name, "pop");
    }

    #[test]
    fn parses_the_tally_facet() {
        // A mutating `bump()` (assignment + `n + 1`) plus a view `get()`.
        let f = parse_src(
            "facet Tally { uint256 n; \
             function bump() external { n = n + 1; } \
             function get() external view returns (uint256) { return n; } }",
        )
        .unwrap();
        assert_eq!(f.state_vars.len(), 1);
        assert_eq!(f.state_vars[0].name, "n");
        assert_eq!(f.functions.len(), 2);

        // bump(): mutating (no `returns`), body is a single `n = n + 1;` assignment.
        let bump = &f.functions[0];
        assert_eq!(bump.name, "bump");
        assert_eq!(bump.mutability, Mutability::NonPayable);
        assert_eq!(bump.returns, None);
        match &bump.body {
            Stmt::Block(stmts) => {
                assert_eq!(stmts.len(), 1);
                match &stmts[0] {
                    Stmt::Assign { name, value, .. } => {
                        assert_eq!(name, "n");
                        // value is `n + 1`: Add(StateVar n, IntLit 1).
                        match value {
                            Expr::Add { lhs, rhs, .. } => {
                                assert!(matches!(**lhs, Expr::StateVar { .. }));
                                assert!(matches!(**rhs, Expr::IntLit { .. }));
                            }
                            other => panic!("expected an Add, got {other:?}"),
                        }
                    }
                    other => panic!("expected an assignment, got {other:?}"),
                }
            }
            other => panic!("expected a block body, got {other:?}"),
        }

        // get(): a view getter returning the state var.
        let get = &f.functions[1];
        assert_eq!(get.name, "get");
        assert_eq!(get.mutability, Mutability::View);
        assert_eq!(get.returns, Some(Ty::Uint256));
        assert!(matches!(get.body, Stmt::Return(Expr::StateVar { .. })));
    }

    #[test]
    fn empty_mutating_body_is_allowed() {
        let f = parse_src("facet E { function noop() external { } }").unwrap();
        assert_eq!(f.functions[0].returns, None);
        match &f.functions[0].body {
            Stmt::Block(stmts) => assert!(stmts.is_empty()),
            other => panic!("expected an empty block, got {other:?}"),
        }
    }

    #[test]
    fn left_associative_addition_parses() {
        // `a + b + c` folds left: Add(Add(a, b), c).
        let f = parse_src(
            "facet A { uint256 a; uint256 b; uint256 c; \
             function set() external { a = a + b + c; } }",
        )
        .unwrap();
        match &f.functions[0].body {
            Stmt::Block(stmts) => match &stmts[0] {
                Stmt::Assign { value: Expr::Add { lhs, rhs, .. }, .. } => {
                    // top-level rhs is `c`, lhs is `a + b`.
                    assert!(matches!(**rhs, Expr::StateVar { .. }));
                    assert!(matches!(**lhs, Expr::Add { .. }));
                }
                other => panic!("unexpected stmt {other:?}"),
            },
            other => panic!("unexpected body {other:?}"),
        }
    }

    #[test]
    fn assignment_to_a_literal_is_a_clean_error() {
        let e = parse_src("facet C { function f() external { 1 = 2; } }").unwrap_err();
        assert_eq!(e.code, Some(codes::INVALID_ASSIGN_TARGET));
    }

    #[test]
    fn missing_semicolon_in_assignment_is_a_clean_error() {
        let e = parse_src("facet C { function f() external { n = 1 } }").unwrap_err();
        assert_eq!(e.code, Some(codes::UNEXPECTED_TOKEN));
    }

    #[test]
    fn mapping_state_var_parses() {
        let f = parse_src(
            "facet L { mapping(address => uint256) bal; \
             function get() external view returns (uint256) { return 0; } }",
        )
        .unwrap();
        assert_eq!(f.state_vars.len(), 1);
        assert_eq!(f.state_vars[0].name, "bal");
        match &f.state_vars[0].kind {
            StateVarKind::Mapping { key, value } => {
                assert_eq!(*key, Ty::Address);
                assert_eq!(*value, Ty::Uint256);
            }
            other => panic!("expected a mapping, got {other:?}"),
        }
    }

    #[test]
    fn index_expr_and_msg_sender_parse() {
        // `bal[msg.sender]` as a return value: an Index whose key is MsgSender.
        let f = parse_src(
            "facet L { mapping(address => uint256) bal; \
             function mine() external view returns (uint256) { return bal[msg.sender]; } }",
        )
        .unwrap();
        match &f.functions[0].body {
            Stmt::Return(Expr::Index { base, key, .. }) => {
                assert_eq!(base, "bal");
                assert!(matches!(**key, Expr::MsgSender { .. }));
            }
            other => panic!("unexpected body {other:?}"),
        }
    }

    #[test]
    fn index_assignment_parses() {
        // `bal[msg.sender] = bal[msg.sender] + amt;` is an IndexAssign.
        let f = parse_src(
            "facet L { mapping(address => uint256) bal; \
             function add(uint256 amt) external { bal[msg.sender] = bal[msg.sender] + amt; } }",
        )
        .unwrap();
        match &f.functions[0].body {
            Stmt::Block(stmts) => match &stmts[0] {
                Stmt::IndexAssign { base, key, value, .. } => {
                    assert_eq!(base, "bal");
                    assert!(matches!(*key, Expr::MsgSender { .. }));
                    // value is `bal[msg.sender] + amt`: Add(Index, StateVar amt).
                    match value {
                        Expr::Add { lhs, rhs, .. } => {
                            assert!(matches!(**lhs, Expr::Index { .. }));
                            assert!(matches!(**rhs, Expr::StateVar { .. }));
                        }
                        other => panic!("expected an Add, got {other:?}"),
                    }
                }
                other => panic!("expected an IndexAssign, got {other:?}"),
            },
            other => panic!("unexpected body {other:?}"),
        }
    }

    #[test]
    fn bare_msg_member_other_than_sender_is_rejected() {
        let e = parse_src(
            "facet C { function f() external view returns (uint256) { return msg.value; } }",
        )
        .unwrap_err();
        assert_eq!(e.code, Some(codes::UNSUPPORTED_FEATURE));
    }

    #[test]
    fn parameter_without_a_name_is_a_clean_error() {
        // `function f(uint256) external` — a type with no parameter name. The param
        // parser expects an identifier after the type; this is a clean error, not a
        // panic (covers malformed/wrong-arity parameter lists).
        let e = parse_src("facet C { function f(uint256) external { } }").unwrap_err();
        assert_eq!(e.code, Some(codes::UNEXPECTED_TOKEN));
    }

    #[test]
    fn trailing_comma_in_param_list_is_a_clean_error() {
        let e = parse_src("facet C { function f(uint256 a,) external { } }").unwrap_err();
        // After the comma the parser expects a type, but sees `)`.
        assert_eq!(e.code, Some(codes::EXPECTED_TYPE));
    }

    #[test]
    fn comparison_parses_below_addition() {
        // `n + 1 > 0` parses as `(n + 1) > 0`: a Cmp whose lhs is an Add.
        let f = parse_src(
            "facet C { uint256 n; function f() external view returns (uint256) { return n + 1 > 0; } }",
        )
        .unwrap();
        match &f.functions[0].body {
            Stmt::Return(Expr::Cmp { op, lhs, rhs, .. }) => {
                assert_eq!(*op, CmpOp::Gt);
                assert!(matches!(**lhs, Expr::Add { .. }), "lhs must be the `n + 1` Add");
                assert!(matches!(**rhs, Expr::IntLit { .. }), "rhs is the literal 0");
            }
            other => panic!("expected a Cmp(Add, IntLit), got {other:?}"),
        }
    }

    #[test]
    fn all_comparison_operators_parse() {
        for (src_op, want) in [
            (">", CmpOp::Gt),
            ("<", CmpOp::Lt),
            (">=", CmpOp::Ge),
            ("<=", CmpOp::Le),
            ("==", CmpOp::Eq),
        ] {
            let src = format!(
                "facet C {{ function f(uint256 a) external view returns (uint256) {{ return a {src_op} 1; }} }}"
            );
            let f = parse_src(&src).unwrap();
            match &f.functions[0].body {
                Stmt::Return(Expr::Cmp { op, .. }) => assert_eq!(*op, want, "for `{src_op}`"),
                other => panic!("`{src_op}` did not parse to a Cmp: {other:?}"),
            }
        }
    }

    #[test]
    fn require_statement_parses() {
        let f = parse_src(
            "facet C { function f(uint256 n) external { require(n > 0, \"zero\"); } }",
        )
        .unwrap();
        match &f.functions[0].body {
            Stmt::Block(stmts) => {
                assert_eq!(stmts.len(), 1);
                match &stmts[0] {
                    Stmt::Require { cond: Expr::Cmp { op, .. }, .. } => assert_eq!(*op, CmpOp::Gt),
                    other => panic!("expected a Require(Cmp), got {other:?}"),
                }
            }
            other => panic!("unexpected body {other:?}"),
        }
    }

    #[test]
    fn require_then_assignment_parses_in_order() {
        // Two requires followed by a mapping write — the CounterFacet incrementBy shape.
        let f = parse_src(
            "facet C { mapping(address => uint256) count; uint256 total; \
             function incrementBy(uint256 n) external { require(n > 0, \"zero\"); \
             require(n <= 100, \"too big\"); count[msg.sender] = count[msg.sender] + n; \
             total = total + n; } }",
        )
        .unwrap();
        match &f.functions[0].body {
            Stmt::Block(stmts) => {
                assert_eq!(stmts.len(), 4);
                assert!(matches!(stmts[0], Stmt::Require { .. }));
                assert!(matches!(stmts[1], Stmt::Require { .. }));
                assert!(matches!(stmts[2], Stmt::IndexAssign { .. }));
                assert!(matches!(stmts[3], Stmt::Assign { .. }));
            }
            other => panic!("unexpected body {other:?}"),
        }
    }

    #[test]
    fn require_without_a_message_is_a_clean_error() {
        // `require(n > 0)` — missing the message operand. A clean error, not a panic.
        let e = parse_src("facet C { function f(uint256 n) external { require(n > 0); } }")
            .unwrap_err();
        assert!(e.code.is_some(), "must carry an LH code");
    }

    #[test]
    fn bad_comparison_rhs_is_a_clean_error() {
        // `n > ;` — a comparison with no right operand. Clean error, no panic.
        let e = parse_src("facet C { function f(uint256 n) external { require(n > , \"x\"); } }")
            .unwrap_err();
        assert_eq!(e.code, Some(codes::EXPECTED_EXPRESSION));
    }

    #[test]
    fn require_is_still_usable_as_a_plain_identifier() {
        // `require` is contextual: a bare `require` (not followed by `(`) is a normal
        // state-var reference, NOT the keyword. (Edge-case robustness.)
        let f = parse_src(
            "facet C { uint256 require; function f() external view returns (uint256) { return require; } }",
        )
        .unwrap();
        match &f.functions[0].body {
            Stmt::Return(Expr::StateVar { name, .. }) => assert_eq!(name, "require"),
            other => panic!("unexpected body {other:?}"),
        }
    }

    #[test]
    fn compound_plus_assign_desugars() {
        // `total += n` parses to `total = total + n`.
        let f = parse_src(
            "facet C { uint256 total; function f(uint256 n) external { total += n; } }",
        )
        .unwrap();
        match &f.functions[0].body {
            Stmt::Block(stmts) => match &stmts[0] {
                Stmt::Assign { name, value: Expr::Add { lhs, rhs, .. }, .. } => {
                    assert_eq!(name, "total");
                    // lhs is a read of `total`; rhs is `n`.
                    assert!(matches!(**lhs, Expr::StateVar { .. }));
                    assert!(matches!(**rhs, Expr::StateVar { .. }));
                }
                other => panic!("expected a desugared Assign(Add), got {other:?}"),
            },
            other => panic!("unexpected body {other:?}"),
        }
    }

    #[test]
    fn event_declaration_parses_with_indexed_and_data_args() {
        let f = parse_src(
            "facet C { event Incremented(address indexed who, uint256 newCount, uint256 newTotal); \
             function f() external { } }",
        )
        .unwrap();
        assert_eq!(f.events.len(), 1);
        let ev = &f.events[0];
        assert_eq!(ev.name, "Incremented");
        assert_eq!(ev.args.len(), 3);
        // who is indexed; the two counts are not.
        assert_eq!(ev.args[0].ty, Ty::Address);
        assert!(ev.args[0].indexed, "who is indexed");
        assert_eq!(ev.args[0].name, "who");
        assert_eq!(ev.args[1].ty, Ty::Uint256);
        assert!(!ev.args[1].indexed, "newCount is data");
        assert!(!ev.args[2].indexed, "newTotal is data");
    }

    #[test]
    fn event_with_no_args_parses() {
        let f = parse_src("facet C { event Pinged(); function f() external { } }").unwrap();
        assert_eq!(f.events.len(), 1);
        assert_eq!(f.events[0].name, "Pinged");
        assert!(f.events[0].args.is_empty());
    }

    #[test]
    fn emit_statement_parses() {
        let f = parse_src(
            "facet C { event E(address indexed a, uint256 b); \
             function f(uint256 n) external { emit E(msg.sender, n); } }",
        )
        .unwrap();
        match &f.functions[0].body {
            Stmt::Block(stmts) => match &stmts[0] {
                Stmt::Emit { name, args, .. } => {
                    assert_eq!(name, "E");
                    assert_eq!(args.len(), 2);
                    assert!(matches!(args[0], Expr::MsgSender { .. }));
                    assert!(matches!(args[1], Expr::StateVar { .. }));
                }
                other => panic!("expected an Emit, got {other:?}"),
            },
            other => panic!("unexpected body {other:?}"),
        }
    }

    #[test]
    fn emit_is_contextual_and_usable_as_an_identifier() {
        // `emit` not followed by `<Name> (` is a normal state-var reference.
        let f = parse_src(
            "facet C { uint256 emit; function f() external view returns (uint256) { return emit; } }",
        )
        .unwrap();
        match &f.functions[0].body {
            Stmt::Return(Expr::StateVar { name, .. }) => assert_eq!(name, "emit"),
            other => panic!("unexpected body {other:?}"),
        }
    }

    #[test]
    fn event_is_contextual_and_usable_as_an_identifier() {
        // `event` not followed by `<Name> (` is a normal state-var type/name pair.
        let f = parse_src(
            "facet C { uint256 event; function f() external view returns (uint256) { return event; } }",
        )
        .unwrap();
        assert_eq!(f.state_vars.len(), 1);
        assert_eq!(f.state_vars[0].name, "event");
        assert!(f.events.is_empty());
    }

    #[test]
    fn compound_plus_assign_on_a_mapping_desugars() {
        // `count[msg.sender] += n` parses to `count[msg.sender] = count[msg.sender] + n`.
        let f = parse_src(
            "facet C { mapping(address => uint256) count; \
             function f(uint256 n) external { count[msg.sender] += n; } }",
        )
        .unwrap();
        match &f.functions[0].body {
            Stmt::Block(stmts) => match &stmts[0] {
                Stmt::IndexAssign { base, value: Expr::Add { lhs, rhs, .. }, .. } => {
                    assert_eq!(base, "count");
                    assert!(matches!(**lhs, Expr::Index { .. }), "lhs is a read of count[..]");
                    assert!(matches!(**rhs, Expr::StateVar { .. }), "rhs is `n`");
                }
                other => panic!("expected a desugared IndexAssign(Add), got {other:?}"),
            },
            other => panic!("unexpected body {other:?}"),
        }
    }
}