sage-parser 2.1.0

Parser for the Sage language
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
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
//! Abstract Syntax Tree definitions for the Sage language.
//!
//! This module defines all AST node types that the parser produces.
//! Every node carries a `Span` for error reporting.

use crate::{Ident, Span, TypeExpr};
use std::fmt;

// =============================================================================
// Program (top-level)
// =============================================================================

/// A complete Sage program (or module).
#[derive(Debug, Clone, PartialEq)]
pub struct Program {
    /// Module declarations (`mod foo`).
    pub mod_decls: Vec<ModDecl>,
    /// Use declarations (`use foo::Bar`).
    pub use_decls: Vec<UseDecl>,
    /// Record type declarations.
    pub records: Vec<RecordDecl>,
    /// Enum type declarations.
    pub enums: Vec<EnumDecl>,
    /// Constant declarations.
    pub consts: Vec<ConstDecl>,
    /// Tool declarations (RFC-0011).
    pub tools: Vec<ToolDecl>,
    /// Protocol declarations (Phase 3 session types).
    pub protocols: Vec<ProtocolDecl>,
    /// Effect handler declarations (Phase 3 algebraic effects).
    pub effect_handlers: Vec<EffectHandlerDecl>,
    /// Agent declarations.
    pub agents: Vec<AgentDecl>,
    /// Supervisor declarations (v2 supervision trees).
    pub supervisors: Vec<SupervisorDecl>,
    /// Function declarations.
    pub functions: Vec<FnDecl>,
    /// Extern function declarations (Rust FFI).
    pub extern_fns: Vec<ExternFnDecl>,
    /// Test declarations (RFC-0012). Only valid in `_test.sg` files.
    pub tests: Vec<TestDecl>,
    /// The entry-point agent or supervisor (from `run Name`).
    /// None for library modules that don't have an entry point.
    pub run_agent: Option<Ident>,
    /// Span covering the entire program.
    pub span: Span,
}

// =============================================================================
// Module declarations
// =============================================================================

/// A module declaration: `mod name` or `pub mod name`
#[derive(Debug, Clone, PartialEq)]
pub struct ModDecl {
    /// Whether this module is public.
    pub is_pub: bool,
    /// The module name.
    pub name: Ident,
    /// Span covering the declaration.
    pub span: Span,
}

/// A use declaration: `use path::to::Item`
#[derive(Debug, Clone, PartialEq)]
pub struct UseDecl {
    /// Whether this is a public re-export (`pub use`).
    pub is_pub: bool,
    /// The path segments (e.g., `["agents", "Researcher"]`).
    pub path: Vec<Ident>,
    /// The kind of import.
    pub kind: UseKind,
    /// Span covering the declaration.
    pub span: Span,
}

/// The kind of use declaration.
#[derive(Debug, Clone, PartialEq)]
pub enum UseKind {
    /// Simple import: `use a::B` or `use a::B as C`
    /// The Option is the alias (e.g., `C` in `use a::B as C`).
    Simple(Option<Ident>),
    /// Glob import: `use a::*`
    Glob,
    /// Group import: `use a::{B, C as D}`
    /// Each tuple is (name, optional alias).
    Group(Vec<(Ident, Option<Ident>)>),
}

// =============================================================================
// Type declarations (records, enums)
// =============================================================================

/// A record declaration: `record Point { x: Int, y: Int }` or `record Pair<A, B> { first: A, second: B }`
#[derive(Debug, Clone, PartialEq)]
pub struct RecordDecl {
    /// Whether this record is public.
    pub is_pub: bool,
    /// The record's name.
    pub name: Ident,
    /// Type parameters for generic records (e.g., `<A, B>` in `Pair<A, B>`).
    pub type_params: Vec<Ident>,
    /// The record's fields.
    pub fields: Vec<RecordField>,
    /// Span covering the declaration.
    pub span: Span,
}

/// A field in a record declaration: `name: Type`
#[derive(Debug, Clone, PartialEq)]
pub struct RecordField {
    /// The field's name.
    pub name: Ident,
    /// The field's type.
    pub ty: TypeExpr,
    /// Span covering the field.
    pub span: Span,
}

/// An enum variant with optional payload: `Ok(T)` or `None`
#[derive(Debug, Clone, PartialEq)]
pub struct EnumVariant {
    /// The variant's name.
    pub name: Ident,
    /// Optional payload type (e.g., `T` in `Ok(T)`).
    pub payload: Option<TypeExpr>,
    /// Span covering the variant.
    pub span: Span,
}

/// An enum declaration: `enum Status { Active, Pending, Done }` or `enum Tree<T> { Leaf(T), Node(Tree<T>, Tree<T>) }`
#[derive(Debug, Clone, PartialEq)]
pub struct EnumDecl {
    /// Whether this enum is public.
    pub is_pub: bool,
    /// The enum's name.
    pub name: Ident,
    /// Type parameters for generic enums (e.g., `<T>` in `Tree<T>`).
    pub type_params: Vec<Ident>,
    /// The enum's variants.
    pub variants: Vec<EnumVariant>,
    /// Span covering the declaration.
    pub span: Span,
}

/// A const declaration: `const MAX_RETRIES: Int = 3`
#[derive(Debug, Clone, PartialEq)]
pub struct ConstDecl {
    /// Whether this const is public.
    pub is_pub: bool,
    /// The constant's name.
    pub name: Ident,
    /// The constant's type.
    pub ty: TypeExpr,
    /// The constant's value.
    pub value: Expr,
    /// Span covering the declaration.
    pub span: Span,
}

// =============================================================================
// Tool declarations (RFC-0011)
// =============================================================================

/// A tool declaration: `tool Http { fn get(url: String) -> Result<String, String> }`
#[derive(Debug, Clone, PartialEq)]
pub struct ToolDecl {
    /// Whether this tool is public.
    pub is_pub: bool,
    /// The tool's name.
    pub name: Ident,
    /// The tool's function signatures.
    pub functions: Vec<ToolFnDecl>,
    /// Span covering the declaration.
    pub span: Span,
}

/// A function signature in a tool declaration (no body).
#[derive(Debug, Clone, PartialEq)]
pub struct ToolFnDecl {
    /// The function's name.
    pub name: Ident,
    /// The function's parameters.
    pub params: Vec<Param>,
    /// The return type.
    pub return_ty: TypeExpr,
    /// Span covering the declaration.
    pub span: Span,
}

// =============================================================================
// Agent declarations
// =============================================================================

/// An agent declaration: `agent Name { ... }` or `pub agent Name receives MsgType { ... }`
#[derive(Debug, Clone, PartialEq)]
pub struct AgentDecl {
    /// Whether this agent is public (can be imported by other modules).
    pub is_pub: bool,
    /// The agent's name.
    pub name: Ident,
    /// The message type this agent receives (for message passing).
    pub receives: Option<TypeExpr>,
    /// Protocol roles this agent follows (Phase 3): `follows Protocol as Role`
    pub follows: Vec<ProtocolRole>,
    /// Tools this agent uses (RFC-0011): `use Http, Fs`
    pub tool_uses: Vec<Ident>,
    /// Belief declarations (agent state).
    pub beliefs: Vec<BeliefDecl>,
    /// Event handlers.
    pub handlers: Vec<HandlerDecl>,
    /// Span covering the entire declaration.
    pub span: Span,
}

/// A belief declaration: `name: Type` or `@persistent name: Type`
#[derive(Debug, Clone, PartialEq)]
pub struct BeliefDecl {
    /// Whether this field is persistent (checkpointed across restarts).
    pub is_persistent: bool,
    /// The belief's name.
    pub name: Ident,
    /// The belief's type.
    pub ty: TypeExpr,
    /// Span covering the declaration.
    pub span: Span,
}

/// An event handler: `on start { ... }`, `on message(x: T) { ... }`, `on stop { ... }`
#[derive(Debug, Clone, PartialEq)]
pub struct HandlerDecl {
    /// The event kind this handler responds to.
    pub event: EventKind,
    /// The handler body.
    pub body: Block,
    /// Span covering the entire handler.
    pub span: Span,
}

/// The kind of event a handler responds to.
#[derive(Debug, Clone, PartialEq)]
pub enum EventKind {
    /// `on waking` — runs before start, after persistent state loaded (v2 lifecycle).
    Waking,
    /// `on start` — runs when the agent is spawned.
    Start,
    /// `on message(param: Type)` — runs when a message is received.
    Message {
        /// The parameter name for the incoming message.
        param_name: Ident,
        /// The type of the message.
        param_ty: TypeExpr,
    },
    /// `on pause` — runs when supervisor signals graceful pause (v2 lifecycle).
    Pause,
    /// `on resume` — runs when agent is unpaused (v2 lifecycle).
    Resume,
    /// `on stop` — runs during graceful shutdown.
    Stop,
    /// `on resting` — alias for stop (v2 terminology).
    Resting,
    /// `on error(e)` — runs when an unhandled error occurs in the agent.
    Error {
        /// The parameter name for the error.
        param_name: Ident,
    },
}

impl fmt::Display for EventKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            EventKind::Waking => write!(f, "waking"),
            EventKind::Start => write!(f, "start"),
            EventKind::Message {
                param_name,
                param_ty,
            } => {
                write!(f, "message({param_name}: {param_ty})")
            }
            EventKind::Pause => write!(f, "pause"),
            EventKind::Resume => write!(f, "resume"),
            EventKind::Stop => write!(f, "stop"),
            EventKind::Resting => write!(f, "resting"),
            EventKind::Error { param_name } => {
                write!(f, "error({param_name})")
            }
        }
    }
}

// =============================================================================
// Function declarations
// =============================================================================

/// A function declaration: `fn name(params) -> ReturnType { ... }` or `fn map<T, U>(list: List<T>, f: Fn(T) -> U) -> List<U> { ... }`
#[derive(Debug, Clone, PartialEq)]
pub struct FnDecl {
    /// Whether this function is public (can be imported by other modules).
    pub is_pub: bool,
    /// The function's name.
    pub name: Ident,
    /// Type parameters for generic functions (e.g., `<T, U>` in `map<T, U>`).
    pub type_params: Vec<Ident>,
    /// The function's parameters.
    pub params: Vec<Param>,
    /// The return type.
    pub return_ty: TypeExpr,
    /// Whether this function can fail (marked with `fails`).
    pub is_fallible: bool,
    /// The function body.
    pub body: Block,
    /// Span covering the entire declaration.
    pub span: Span,
}

/// An extern function declaration: `extern fn name(params) -> Type`
/// The implementation is provided by external Rust code.
#[derive(Debug, Clone, PartialEq)]
pub struct ExternFnDecl {
    /// The function's name.
    pub name: Ident,
    /// The function's parameters.
    pub params: Vec<Param>,
    /// The return type.
    pub return_ty: TypeExpr,
    /// Whether this function can fail (marked with `fails`).
    pub is_fallible: bool,
    /// Span covering the entire declaration.
    pub span: Span,
}

/// A function parameter: `name: Type`
#[derive(Debug, Clone, PartialEq)]
pub struct Param {
    /// The parameter name.
    pub name: Ident,
    /// The parameter type.
    pub ty: TypeExpr,
    /// Span covering the parameter.
    pub span: Span,
}

/// A closure parameter: `name` or `name: Type`
#[derive(Debug, Clone, PartialEq)]
pub struct ClosureParam {
    /// The parameter name.
    pub name: Ident,
    /// Optional type annotation (can be inferred).
    pub ty: Option<TypeExpr>,
    /// Span covering the parameter.
    pub span: Span,
}

// =============================================================================
// Test declarations (RFC-0012)
// =============================================================================

/// A test declaration: `test "description" { ... }` or `@serial test "description" { ... }`
#[derive(Debug, Clone, PartialEq)]
pub struct TestDecl {
    /// The test description (the string after `test`).
    pub name: String,
    /// Whether this test must run serially (marked with `@serial`).
    pub is_serial: bool,
    /// The test body.
    pub body: Block,
    /// Span covering the entire declaration.
    pub span: Span,
}

// =============================================================================
// Supervision tree declarations (v2)
// =============================================================================

/// A supervisor declaration for OTP-style supervision trees.
///
/// Example:
/// ```sage
/// supervisor AppSupervisor {
///     strategy: OneForOne
///     children {
///         DatabaseSteward { restart: Permanent, schema_version: 0 }
///         APISteward { restart: Transient, routes_generated: false }
///     }
/// }
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct SupervisorDecl {
    /// Whether this supervisor is public.
    pub is_pub: bool,
    /// The supervisor's name.
    pub name: Ident,
    /// The supervision strategy.
    pub strategy: SupervisionStrategy,
    /// Child specifications.
    pub children: Vec<ChildSpec>,
    /// Span covering the declaration.
    pub span: Span,
}

/// Supervision strategy (inspired by Erlang/OTP).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SupervisionStrategy {
    /// Restart only the failed child.
    OneForOne,
    /// Restart all children if one fails.
    OneForAll,
    /// Restart the failed child and all children started after it.
    RestForOne,
}

impl fmt::Display for SupervisionStrategy {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SupervisionStrategy::OneForOne => write!(f, "OneForOne"),
            SupervisionStrategy::OneForAll => write!(f, "OneForAll"),
            SupervisionStrategy::RestForOne => write!(f, "RestForOne"),
        }
    }
}

/// Restart policy for supervised children.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum RestartPolicy {
    /// Always restart, regardless of exit reason.
    #[default]
    Permanent,
    /// Restart only on abnormal termination (error).
    Transient,
    /// Never restart.
    Temporary,
}

impl fmt::Display for RestartPolicy {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            RestartPolicy::Permanent => write!(f, "Permanent"),
            RestartPolicy::Transient => write!(f, "Transient"),
            RestartPolicy::Temporary => write!(f, "Temporary"),
        }
    }
}

/// A child specification within a supervisor.
///
/// Example:
/// ```sage
/// DatabaseSteward { restart: Permanent, schema_version: 0 }
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct ChildSpec {
    /// The agent type to spawn.
    pub agent_name: Ident,
    /// Restart policy for this child.
    pub restart: RestartPolicy,
    /// Initial belief values.
    pub beliefs: Vec<FieldInit>,
    /// Effect handler assignments (Phase 3): `handler Infer: FastLLM`
    pub handler_assignments: Vec<HandlerAssignment>,
    /// Span covering the child spec.
    pub span: Span,
}

// =============================================================================
// Protocol declarations (Phase 3 session types)
// =============================================================================

/// A protocol declaration for session types.
///
/// Example:
/// ```sage
/// protocol SchemaSync {
///     DatabaseSteward -> APISteward: SchemaChanged
///     APISteward -> DatabaseSteward: Acknowledged
/// }
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct ProtocolDecl {
    /// Whether this protocol is public.
    pub is_pub: bool,
    /// The protocol's name.
    pub name: Ident,
    /// The protocol steps.
    pub steps: Vec<ProtocolStep>,
    /// Span covering the declaration.
    pub span: Span,
}

/// A single step in a protocol: `Sender -> Receiver: MessageType`
#[derive(Debug, Clone, PartialEq)]
pub struct ProtocolStep {
    /// The sender role.
    pub sender: Ident,
    /// The receiver role.
    pub receiver: Ident,
    /// The message type for this step.
    pub message_type: TypeExpr,
    /// Span covering the step.
    pub span: Span,
}

/// A protocol role assignment: `follows ProtocolName as RoleName`
#[derive(Debug, Clone, PartialEq)]
pub struct ProtocolRole {
    /// The protocol being followed.
    pub protocol: Ident,
    /// The role this agent plays in the protocol.
    pub role: Ident,
    /// Span covering the role assignment.
    pub span: Span,
}

// =============================================================================
// Effect handler declarations (Phase 3 algebraic effects)
// =============================================================================

/// An effect handler declaration for per-agent configuration.
///
/// Example:
/// ```sage
/// handler DefaultLLM handles Infer {
///     model: "gpt-4o"
///     temperature: 0.7
///     max_tokens: 1024
/// }
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct EffectHandlerDecl {
    /// Whether this handler is public.
    pub is_pub: bool,
    /// The handler's name.
    pub name: Ident,
    /// The effect being handled (e.g., "Infer").
    pub effect: Ident,
    /// Configuration key-value pairs.
    pub config: Vec<HandlerConfig>,
    /// Span covering the declaration.
    pub span: Span,
}

/// A configuration entry in an effect handler.
#[derive(Debug, Clone, PartialEq)]
pub struct HandlerConfig {
    /// The configuration key.
    pub key: Ident,
    /// The configuration value.
    pub value: Literal,
    /// Span covering the entry.
    pub span: Span,
}

/// An effect handler assignment in a child spec: `handler Effect: HandlerName`
#[derive(Debug, Clone, PartialEq)]
pub struct HandlerAssignment {
    /// The effect being assigned (e.g., "Infer").
    pub effect: Ident,
    /// The handler to use for this effect.
    pub handler: Ident,
    /// Span covering the assignment.
    pub span: Span,
}

// =============================================================================
// Blocks and statements
// =============================================================================

/// A block of statements: `{ stmt* }`
#[derive(Debug, Clone, PartialEq)]
pub struct Block {
    /// The statements in this block.
    pub stmts: Vec<Stmt>,
    /// Span covering the entire block (including braces).
    pub span: Span,
}

/// A statement.
#[derive(Debug, Clone, PartialEq)]
pub enum Stmt {
    /// Variable binding: `let name: Type = expr` or `let name = expr`
    Let {
        /// The variable name.
        name: Ident,
        /// Optional type annotation.
        ty: Option<TypeExpr>,
        /// The initial value.
        value: Expr,
        /// Span covering the statement.
        span: Span,
    },

    /// Assignment: `name = expr`
    Assign {
        /// The variable being assigned to.
        name: Ident,
        /// The new value.
        value: Expr,
        /// Span covering the statement.
        span: Span,
    },

    /// Return statement: `return expr?`
    Return {
        /// The optional return value.
        value: Option<Expr>,
        /// Span covering the statement.
        span: Span,
    },

    /// If statement: `if cond { ... } else { ... }`
    If {
        /// The condition (must be Bool).
        condition: Expr,
        /// The then branch.
        then_block: Block,
        /// The optional else branch (can be another If for else-if chains).
        else_block: Option<ElseBranch>,
        /// Span covering the statement.
        span: Span,
    },

    /// For loop: `for x in iter { ... }` or `for (k, v) in map { ... }`
    For {
        /// The loop pattern (can be a simple binding or tuple destructuring).
        pattern: Pattern,
        /// The iterable expression (List<T> or Map<K, V>).
        iter: Expr,
        /// The loop body.
        body: Block,
        /// Span covering the statement.
        span: Span,
    },

    /// While loop: `while cond { ... }`
    While {
        /// The condition (must be Bool).
        condition: Expr,
        /// The loop body.
        body: Block,
        /// Span covering the statement.
        span: Span,
    },

    /// Infinite loop: `loop { ... }`
    Loop {
        /// The loop body.
        body: Block,
        /// Span covering the statement.
        span: Span,
    },

    /// Break statement: `break`
    Break {
        /// Span covering the statement.
        span: Span,
    },

    /// Span block: `span "name" { body }` for timed observability blocks.
    /// Records start/end times and emits trace events.
    SpanBlock {
        /// The span name (should be a string literal or expression).
        name: Expr,
        /// The block body.
        body: Block,
        /// Span covering the statement.
        span: Span,
    },

    /// Explicit checkpoint statement: `checkpoint();`
    /// Forces an immediate checkpoint of all @persistent beliefs.
    /// Only valid inside agent handler bodies.
    Checkpoint {
        /// Span covering the statement.
        span: Span,
    },

    /// Expression statement: `expr`
    Expr {
        /// The expression.
        expr: Expr,
        /// Span covering the statement.
        span: Span,
    },

    /// Tuple destructuring: `let (a, b) = expr;`
    LetTuple {
        /// The variable names.
        names: Vec<Ident>,
        /// Optional type annotation.
        ty: Option<TypeExpr>,
        /// The value expression.
        value: Expr,
        /// Span covering the statement.
        span: Span,
    },

    /// RFC-0012: Mock divine statement: `mock divine -> expr;`
    MockDivine {
        /// The mock value expression.
        value: MockValue,
        /// Span covering the statement.
        span: Span,
    },

    /// Mock tool statement: `mock tool Http.get -> value;`
    MockTool {
        /// The tool name.
        tool_name: Ident,
        /// The function name.
        fn_name: Ident,
        /// The mock value expression.
        value: MockValue,
        /// Span covering the statement.
        span: Span,
    },
}

/// RFC-0012: A mock value for `mock divine -> value`.
#[derive(Debug, Clone, PartialEq)]
pub enum MockValue {
    /// A literal value: `mock divine -> "string"` or `mock divine -> SomeRecord { ... }`
    Value(Expr),
    /// A failure: `mock divine -> fail("error message")`
    Fail(Expr),
}

impl Stmt {
    /// Get the span of this statement.
    #[must_use]
    pub fn span(&self) -> &Span {
        match self {
            Stmt::Let { span, .. }
            | Stmt::Assign { span, .. }
            | Stmt::Return { span, .. }
            | Stmt::If { span, .. }
            | Stmt::For { span, .. }
            | Stmt::While { span, .. }
            | Stmt::Loop { span, .. }
            | Stmt::Break { span, .. }
            | Stmt::SpanBlock { span, .. }
            | Stmt::Checkpoint { span, .. }
            | Stmt::Expr { span, .. }
            | Stmt::LetTuple { span, .. }
            | Stmt::MockDivine { span, .. }
            | Stmt::MockTool { span, .. } => span,
        }
    }
}

/// The else branch of an if statement.
#[derive(Debug, Clone, PartialEq)]
pub enum ElseBranch {
    /// `else { ... }`
    Block(Block),
    /// `else if ...` (chained if)
    ElseIf(Box<Stmt>),
}

// =============================================================================
// Expressions
// =============================================================================

/// An expression.
#[derive(Debug, Clone, PartialEq)]
pub enum Expr {
    /// LLM divination: `divine("template")` or `divine("template" -> Type)`
    Divine {
        /// The prompt template (may contain `{ident}` interpolations).
        template: StringTemplate,
        /// Optional result type annotation.
        result_ty: Option<TypeExpr>,
        /// Span covering the expression.
        span: Span,
    },

    /// Agent summoning: `summon AgentName { field: value, ... }`
    Summon {
        /// The agent type to spawn.
        agent: Ident,
        /// Initial belief values.
        fields: Vec<FieldInit>,
        /// Span covering the expression.
        span: Span,
    },

    /// Await: `await expr` or `await expr timeout(ms)`
    Await {
        /// The agent handle to await.
        handle: Box<Expr>,
        /// Optional timeout in milliseconds.
        timeout: Option<Box<Expr>>,
        /// Span covering the expression.
        span: Span,
    },

    /// Send message: `send(handle, message)`
    Send {
        /// The agent handle to send to.
        handle: Box<Expr>,
        /// The message to send.
        message: Box<Expr>,
        /// Span covering the expression.
        span: Span,
    },

    /// Yield value: `yield(value)`
    Yield {
        /// The value to emit to the awaiter.
        value: Box<Expr>,
        /// Span covering the expression.
        span: Span,
    },

    /// Function call: `name(args)` or `name::<T, U>(args)` (turbofish)
    Call {
        /// The function name.
        name: Ident,
        /// Explicit type arguments (turbofish syntax): `foo::<Int, String>(...)`
        type_args: Vec<TypeExpr>,
        /// The arguments.
        args: Vec<Expr>,
        /// Span covering the expression.
        span: Span,
    },

    /// Apply expression: call an arbitrary expression as a function.
    /// Used for method calls on values: `expr.method(args)` becomes
    /// `Apply { callee: FieldAccess { object: expr, field: method }, args }`
    Apply {
        /// The expression being called (typically a FieldAccess for method calls).
        callee: Box<Expr>,
        /// The arguments.
        args: Vec<Expr>,
        /// Span covering the expression.
        span: Span,
    },

    /// Method call on self: `self.method(args)`
    SelfMethodCall {
        /// The method name.
        method: Ident,
        /// The arguments.
        args: Vec<Expr>,
        /// Span covering the expression.
        span: Span,
    },

    /// Self field access: `self.field`
    SelfField {
        /// The field (belief) name.
        field: Ident,
        /// Span covering the expression.
        span: Span,
    },

    /// Binary operation: `left op right`
    Binary {
        /// The operator.
        op: BinOp,
        /// The left operand.
        left: Box<Expr>,
        /// The right operand.
        right: Box<Expr>,
        /// Span covering the expression.
        span: Span,
    },

    /// Unary operation: `op operand`
    Unary {
        /// The operator.
        op: UnaryOp,
        /// The operand.
        operand: Box<Expr>,
        /// Span covering the expression.
        span: Span,
    },

    /// List literal: `[a, b, c]`
    List {
        /// The list elements.
        elements: Vec<Expr>,
        /// Span covering the expression.
        span: Span,
    },

    /// Literal value.
    Literal {
        /// The literal value.
        value: Literal,
        /// Span covering the expression.
        span: Span,
    },

    /// Variable reference.
    Var {
        /// The variable name.
        name: Ident,
        /// Span covering the expression.
        span: Span,
    },

    /// Parenthesized expression: `(expr)`
    Paren {
        /// The inner expression.
        inner: Box<Expr>,
        /// Span covering the expression (including parens).
        span: Span,
    },

    /// Interpolated string: `"Hello, {name}!"`
    StringInterp {
        /// The string template with interpolations.
        template: StringTemplate,
        /// Span covering the expression.
        span: Span,
    },

    /// Match expression: `match expr { Pattern => expr, ... }`
    Match {
        /// The scrutinee expression.
        scrutinee: Box<Expr>,
        /// The match arms.
        arms: Vec<MatchArm>,
        /// Span covering the expression.
        span: Span,
    },

    /// Record construction: `Point { x: 1, y: 2 }` or `Pair::<Int, String> { first: 1, second: "hi" }`
    RecordConstruct {
        /// The record type name.
        name: Ident,
        /// Explicit type arguments (turbofish syntax): `Pair::<Int, String> { ... }`
        type_args: Vec<TypeExpr>,
        /// Field initializations.
        fields: Vec<FieldInit>,
        /// Span covering the expression.
        span: Span,
    },

    /// Field access: `record.field`
    FieldAccess {
        /// The record expression.
        object: Box<Expr>,
        /// The field name.
        field: Ident,
        /// Span covering the expression.
        span: Span,
    },

    /// Receive message from mailbox: `receive()`
    Receive {
        /// Span covering the expression.
        span: Span,
    },

    /// Try expression: `try expr` — propagates failure upward.
    Try {
        /// The expression that may fail.
        expr: Box<Expr>,
        /// Span covering the expression.
        span: Span,
    },

    /// Catch expression: `expr catch { recovery }` or `expr catch(e) { recovery }`.
    Catch {
        /// The expression that may fail.
        expr: Box<Expr>,
        /// The optional error binding (e.g., `e` in `catch(e)`).
        error_bind: Option<Ident>,
        /// The recovery expression.
        recovery: Box<Expr>,
        /// Span covering the expression.
        span: Span,
    },

    /// Fail expression: `fail "message"` or `fail Error { ... }`.
    /// Type is `Never` - this expression never returns.
    Fail {
        /// The error value (either a string message or an Error record).
        error: Box<Expr>,
        /// Span covering the expression.
        span: Span,
    },

    /// Retry expression: `retry(3) { ... }` or `retry(3, delay: 1000) { ... }`
    Retry {
        /// Number of retry attempts (1-10).
        count: Box<Expr>,
        /// Optional delay between attempts in milliseconds.
        delay: Option<Box<Expr>>,
        /// Optional list of error kinds to retry on.
        on_errors: Option<Vec<Expr>>,
        /// The body to retry.
        body: Box<Expr>,
        /// Span covering the expression.
        span: Span,
    },

    /// Trace expression: `trace("message")` for emitting trace events.
    Trace {
        /// The message to trace (must be a string).
        message: Box<Expr>,
        /// Span covering the expression.
        span: Span,
    },

    /// Closure expression: `|params| body`
    Closure {
        /// The closure parameters.
        params: Vec<ClosureParam>,
        /// The closure body (single expression).
        body: Box<Expr>,
        /// Span covering the expression.
        span: Span,
    },

    /// Tuple literal: `(a, b, c)`
    Tuple {
        /// The tuple elements (at least 2).
        elements: Vec<Expr>,
        /// Span covering the expression.
        span: Span,
    },

    /// Tuple index access: `tuple.0`
    TupleIndex {
        /// The tuple expression.
        tuple: Box<Expr>,
        /// The index (0-based).
        index: usize,
        /// Span covering the expression.
        span: Span,
    },

    /// Map literal: `{ key: value, ... }` or `{}`
    Map {
        /// The map entries.
        entries: Vec<MapEntry>,
        /// Span covering the expression.
        span: Span,
    },

    /// Enum variant construction: `MyEnum.Variant` or `Either::<L, R>.Left(payload)`
    VariantConstruct {
        /// The enum type name.
        enum_name: Ident,
        /// Explicit type arguments (turbofish syntax): `Either::<L, R>.Left(...)`
        type_args: Vec<TypeExpr>,
        /// The variant name.
        variant: Ident,
        /// The optional payload expression.
        payload: Option<Box<Expr>>,
        /// Span covering the expression.
        span: Span,
    },

    /// Tool function call (RFC-0011): `Http.get(url)`
    ToolCall {
        /// The tool name.
        tool: Ident,
        /// The function name.
        function: Ident,
        /// The arguments.
        args: Vec<Expr>,
        /// Span covering the expression.
        span: Span,
    },

    /// Reply to current message (Phase 3 session types): `reply(message)`
    ///
    /// Only valid inside `on message` handlers when the agent follows a protocol.
    Reply {
        /// The message to send back.
        message: Box<Expr>,
        /// Span covering the expression.
        span: Span,
    },
}

/// A map entry: `key: value`
#[derive(Debug, Clone, PartialEq)]
pub struct MapEntry {
    /// The key expression.
    pub key: Expr,
    /// The value expression.
    pub value: Expr,
    /// Span covering the entry.
    pub span: Span,
}

impl Expr {
    /// Get the span of this expression.
    #[must_use]
    pub fn span(&self) -> &Span {
        match self {
            Expr::Divine { span, .. }
            | Expr::Summon { span, .. }
            | Expr::Await { span, .. }
            | Expr::Send { span, .. }
            | Expr::Yield { span, .. }
            | Expr::Call { span, .. }
            | Expr::Apply { span, .. }
            | Expr::SelfMethodCall { span, .. }
            | Expr::SelfField { span, .. }
            | Expr::Binary { span, .. }
            | Expr::Unary { span, .. }
            | Expr::List { span, .. }
            | Expr::Literal { span, .. }
            | Expr::Var { span, .. }
            | Expr::Paren { span, .. }
            | Expr::StringInterp { span, .. }
            | Expr::Match { span, .. }
            | Expr::RecordConstruct { span, .. }
            | Expr::FieldAccess { span, .. }
            | Expr::Receive { span, .. }
            | Expr::Try { span, .. }
            | Expr::Catch { span, .. }
            | Expr::Fail { span, .. }
            | Expr::Retry { span, .. }
            | Expr::Trace { span, .. }
            | Expr::Closure { span, .. }
            | Expr::Tuple { span, .. }
            | Expr::TupleIndex { span, .. }
            | Expr::Map { span, .. }
            | Expr::VariantConstruct { span, .. }
            | Expr::ToolCall { span, .. }
            | Expr::Reply { span, .. } => span,
        }
    }
}

/// A field initialization in a spawn or record construction expression: `field: value`
#[derive(Debug, Clone, PartialEq)]
pub struct FieldInit {
    /// The field name.
    pub name: Ident,
    /// The initial value.
    pub value: Expr,
    /// Span covering the field initialization.
    pub span: Span,
}

/// A match arm: `Pattern => expr`
#[derive(Debug, Clone, PartialEq)]
pub struct MatchArm {
    /// The pattern to match.
    pub pattern: Pattern,
    /// The expression to evaluate if the pattern matches.
    pub body: Expr,
    /// Span covering the arm.
    pub span: Span,
}

/// A pattern in a match expression.
#[derive(Debug, Clone, PartialEq)]
pub enum Pattern {
    /// Wildcard pattern: `_`
    Wildcard {
        /// Span covering the pattern.
        span: Span,
    },
    /// Enum variant pattern: `Status::Active`, `Ok(x)`, or just `Active`
    Variant {
        /// Optional enum type name (for qualified patterns).
        enum_name: Option<Ident>,
        /// The variant name.
        variant: Ident,
        /// Optional payload binding pattern (e.g., `x` in `Ok(x)`).
        payload: Option<Box<Pattern>>,
        /// Span covering the pattern.
        span: Span,
    },
    /// Literal pattern: `42`, `"hello"`, `true`
    Literal {
        /// The literal value.
        value: Literal,
        /// Span covering the pattern.
        span: Span,
    },
    /// Binding pattern: `x` (binds the matched value to a variable)
    Binding {
        /// The variable name.
        name: Ident,
        /// Span covering the pattern.
        span: Span,
    },
    /// Tuple pattern: `(a, b, c)`
    Tuple {
        /// The element patterns.
        elements: Vec<Pattern>,
        /// Span covering the pattern.
        span: Span,
    },
}

impl Pattern {
    /// Get the span of this pattern.
    #[must_use]
    pub fn span(&self) -> &Span {
        match self {
            Pattern::Wildcard { span }
            | Pattern::Variant { span, .. }
            | Pattern::Literal { span, .. }
            | Pattern::Binding { span, .. }
            | Pattern::Tuple { span, .. } => span,
        }
    }
}

// =============================================================================
// Operators
// =============================================================================

/// Binary operators.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BinOp {
    // Arithmetic
    /// `+`
    Add,
    /// `-`
    Sub,
    /// `*`
    Mul,
    /// `/`
    Div,
    /// `%` (remainder/modulo)
    Rem,

    // Comparison
    /// `==`
    Eq,
    /// `!=`
    Ne,
    /// `<`
    Lt,
    /// `>`
    Gt,
    /// `<=`
    Le,
    /// `>=`
    Ge,

    // Logical
    /// `&&`
    And,
    /// `||`
    Or,

    // String
    /// `++` (string concatenation)
    Concat,
}

impl BinOp {
    /// Get the precedence of this operator (higher = binds tighter).
    #[must_use]
    pub fn precedence(self) -> u8 {
        match self {
            BinOp::Or => 1,
            BinOp::And => 2,
            BinOp::Eq | BinOp::Ne => 3,
            BinOp::Lt | BinOp::Gt | BinOp::Le | BinOp::Ge => 4,
            BinOp::Concat => 5,
            BinOp::Add | BinOp::Sub => 6,
            BinOp::Mul | BinOp::Div | BinOp::Rem => 7,
        }
    }

    /// Check if this operator is left-associative.
    #[must_use]
    pub fn is_left_assoc(self) -> bool {
        // All our operators are left-associative
        true
    }
}

impl fmt::Display for BinOp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            BinOp::Add => write!(f, "+"),
            BinOp::Sub => write!(f, "-"),
            BinOp::Mul => write!(f, "*"),
            BinOp::Div => write!(f, "/"),
            BinOp::Rem => write!(f, "%"),
            BinOp::Eq => write!(f, "=="),
            BinOp::Ne => write!(f, "!="),
            BinOp::Lt => write!(f, "<"),
            BinOp::Gt => write!(f, ">"),
            BinOp::Le => write!(f, "<="),
            BinOp::Ge => write!(f, ">="),
            BinOp::And => write!(f, "&&"),
            BinOp::Or => write!(f, "||"),
            BinOp::Concat => write!(f, "++"),
        }
    }
}

/// Unary operators.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum UnaryOp {
    /// `-` (negation)
    Neg,
    /// `!` (logical not)
    Not,
}

impl fmt::Display for UnaryOp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            UnaryOp::Neg => write!(f, "-"),
            UnaryOp::Not => write!(f, "!"),
        }
    }
}

// =============================================================================
// Literals
// =============================================================================

/// A literal value.
#[derive(Debug, Clone, PartialEq)]
pub enum Literal {
    /// Integer literal: `42`, `-7`
    Int(i64),
    /// Float literal: `3.14`, `-0.5`
    Float(f64),
    /// Boolean literal: `true`, `false`
    Bool(bool),
    /// String literal: `"hello"`
    String(String),
}

impl fmt::Display for Literal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Literal::Int(n) => write!(f, "{n}"),
            Literal::Float(n) => write!(f, "{n}"),
            Literal::Bool(b) => write!(f, "{b}"),
            Literal::String(s) => write!(f, "\"{s}\""),
        }
    }
}

// =============================================================================
// String templates (for interpolation)
// =============================================================================

/// A string template that may contain interpolations.
///
/// For example, `"Hello, {name}!"` becomes:
/// ```text
/// StringTemplate {
///     parts: [
///         StringPart::Literal("Hello, "),
///         StringPart::Interpolation(Ident("name")),
///         StringPart::Literal("!"),
///     ]
/// }
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct StringTemplate {
    /// The parts of the template.
    pub parts: Vec<StringPart>,
    /// Span covering the entire template string.
    pub span: Span,
}

impl StringTemplate {
    /// Create a simple template with no interpolations.
    #[must_use]
    pub fn literal(s: String, span: Span) -> Self {
        Self {
            parts: vec![StringPart::Literal(s)],
            span,
        }
    }

    /// Check if this template has any interpolations.
    #[must_use]
    pub fn has_interpolations(&self) -> bool {
        self.parts
            .iter()
            .any(|p| matches!(p, StringPart::Interpolation(_)))
    }

    /// Get all interpolation expressions.
    pub fn interpolations(&self) -> impl Iterator<Item = &Expr> {
        self.parts.iter().filter_map(|p| match p {
            StringPart::Interpolation(expr) => Some(expr.as_ref()),
            StringPart::Literal(_) => None,
        })
    }
}

impl fmt::Display for StringTemplate {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "\"")?;
        for part in &self.parts {
            match part {
                StringPart::Literal(s) => write!(f, "{s}")?,
                StringPart::Interpolation(_) => write!(f, "{{...}}")?,
            }
        }
        write!(f, "\"")
    }
}

/// A part of a string template.
#[derive(Debug, Clone, PartialEq)]
pub enum StringPart {
    /// A literal string segment.
    Literal(String),
    /// An interpolated expression: `{ident}`, `{a + b}`, `{foo()}`
    Interpolation(Box<Expr>),
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn binop_precedence() {
        // Mul/Div > Add/Sub > Comparison > And > Or
        assert!(BinOp::Mul.precedence() > BinOp::Add.precedence());
        assert!(BinOp::Add.precedence() > BinOp::Lt.precedence());
        assert!(BinOp::Lt.precedence() > BinOp::And.precedence());
        assert!(BinOp::And.precedence() > BinOp::Or.precedence());
    }

    #[test]
    fn binop_display() {
        assert_eq!(format!("{}", BinOp::Add), "+");
        assert_eq!(format!("{}", BinOp::Eq), "==");
        assert_eq!(format!("{}", BinOp::Concat), "++");
        assert_eq!(format!("{}", BinOp::And), "&&");
    }

    #[test]
    fn unaryop_display() {
        assert_eq!(format!("{}", UnaryOp::Neg), "-");
        assert_eq!(format!("{}", UnaryOp::Not), "!");
    }

    #[test]
    fn literal_display() {
        assert_eq!(format!("{}", Literal::Int(42)), "42");
        assert_eq!(format!("{}", Literal::Float(3.14)), "3.14");
        assert_eq!(format!("{}", Literal::Bool(true)), "true");
        assert_eq!(format!("{}", Literal::String("hello".into())), "\"hello\"");
    }

    #[test]
    fn event_kind_display() {
        assert_eq!(format!("{}", EventKind::Start), "start");
        assert_eq!(format!("{}", EventKind::Stop), "stop");

        let msg = EventKind::Message {
            param_name: Ident::dummy("msg"),
            param_ty: TypeExpr::String,
        };
        assert_eq!(format!("{msg}"), "message(msg: String)");
    }

    #[test]
    fn string_template_literal() {
        let template = StringTemplate::literal("hello".into(), Span::dummy());
        assert!(!template.has_interpolations());
        assert_eq!(format!("{template}"), "\"hello\"");
    }

    #[test]
    fn string_template_with_interpolation() {
        let template = StringTemplate {
            parts: vec![
                StringPart::Literal("Hello, ".into()),
                StringPart::Interpolation(Box::new(Expr::Var {
                    name: Ident::dummy("name"),
                    span: Span::dummy(),
                })),
                StringPart::Literal("!".into()),
            ],
            span: Span::dummy(),
        };
        assert!(template.has_interpolations());
        assert_eq!(format!("{template}"), "\"Hello, {...}!\"");

        let interps: Vec<_> = template.interpolations().collect();
        assert_eq!(interps.len(), 1);
        // Verify it's a Var expression with name "name"
        if let Expr::Var { name, .. } = interps[0] {
            assert_eq!(name.name, "name");
        } else {
            panic!("Expected Var expression");
        }
    }

    #[test]
    fn expr_span() {
        let span = Span::dummy();
        let expr = Expr::Literal {
            value: Literal::Int(42),
            span: span.clone(),
        };
        assert_eq!(expr.span(), &span);
    }

    #[test]
    fn stmt_span() {
        let span = Span::dummy();
        let stmt = Stmt::Return {
            value: None,
            span: span.clone(),
        };
        assert_eq!(stmt.span(), &span);
    }
}