sage_parser/ast.rs
1//! Abstract Syntax Tree definitions for the Sage language.
2//!
3//! This module defines all AST node types that the parser produces.
4//! Every node carries a `Span` for error reporting.
5
6use sage_types::{Ident, Span, TypeExpr};
7use std::fmt;
8
9// =============================================================================
10// Program (top-level)
11// =============================================================================
12
13/// A complete Sage program (or module).
14#[derive(Debug, Clone, PartialEq)]
15pub struct Program {
16 /// Module declarations (`mod foo`).
17 pub mod_decls: Vec<ModDecl>,
18 /// Use declarations (`use foo::Bar`).
19 pub use_decls: Vec<UseDecl>,
20 /// Record type declarations.
21 pub records: Vec<RecordDecl>,
22 /// Enum type declarations.
23 pub enums: Vec<EnumDecl>,
24 /// Constant declarations.
25 pub consts: Vec<ConstDecl>,
26 /// Tool declarations (RFC-0011).
27 pub tools: Vec<ToolDecl>,
28 /// Agent declarations.
29 pub agents: Vec<AgentDecl>,
30 /// Function declarations.
31 pub functions: Vec<FnDecl>,
32 /// Test declarations (RFC-0012). Only valid in `_test.sg` files.
33 pub tests: Vec<TestDecl>,
34 /// The entry-point agent (from `run AgentName`).
35 /// None for library modules that don't have an entry point.
36 pub run_agent: Option<Ident>,
37 /// Span covering the entire program.
38 pub span: Span,
39}
40
41// =============================================================================
42// Module declarations
43// =============================================================================
44
45/// A module declaration: `mod name` or `pub mod name`
46#[derive(Debug, Clone, PartialEq)]
47pub struct ModDecl {
48 /// Whether this module is public.
49 pub is_pub: bool,
50 /// The module name.
51 pub name: Ident,
52 /// Span covering the declaration.
53 pub span: Span,
54}
55
56/// A use declaration: `use path::to::Item`
57#[derive(Debug, Clone, PartialEq)]
58pub struct UseDecl {
59 /// Whether this is a public re-export (`pub use`).
60 pub is_pub: bool,
61 /// The path segments (e.g., `["agents", "Researcher"]`).
62 pub path: Vec<Ident>,
63 /// The kind of import.
64 pub kind: UseKind,
65 /// Span covering the declaration.
66 pub span: Span,
67}
68
69/// The kind of use declaration.
70#[derive(Debug, Clone, PartialEq)]
71pub enum UseKind {
72 /// Simple import: `use a::B` or `use a::B as C`
73 /// The Option is the alias (e.g., `C` in `use a::B as C`).
74 Simple(Option<Ident>),
75 /// Glob import: `use a::*`
76 Glob,
77 /// Group import: `use a::{B, C as D}`
78 /// Each tuple is (name, optional alias).
79 Group(Vec<(Ident, Option<Ident>)>),
80}
81
82// =============================================================================
83// Type declarations (records, enums)
84// =============================================================================
85
86/// A record declaration: `record Point { x: Int, y: Int }`
87#[derive(Debug, Clone, PartialEq)]
88pub struct RecordDecl {
89 /// Whether this record is public.
90 pub is_pub: bool,
91 /// The record's name.
92 pub name: Ident,
93 /// The record's fields.
94 pub fields: Vec<RecordField>,
95 /// Span covering the declaration.
96 pub span: Span,
97}
98
99/// A field in a record declaration: `name: Type`
100#[derive(Debug, Clone, PartialEq)]
101pub struct RecordField {
102 /// The field's name.
103 pub name: Ident,
104 /// The field's type.
105 pub ty: TypeExpr,
106 /// Span covering the field.
107 pub span: Span,
108}
109
110/// An enum variant with optional payload: `Ok(T)` or `None`
111#[derive(Debug, Clone, PartialEq)]
112pub struct EnumVariant {
113 /// The variant's name.
114 pub name: Ident,
115 /// Optional payload type (e.g., `T` in `Ok(T)`).
116 pub payload: Option<TypeExpr>,
117 /// Span covering the variant.
118 pub span: Span,
119}
120
121/// An enum declaration: `enum Status { Active, Pending, Done }` or `enum Result { Ok(T), Err(E) }`
122#[derive(Debug, Clone, PartialEq)]
123pub struct EnumDecl {
124 /// Whether this enum is public.
125 pub is_pub: bool,
126 /// The enum's name.
127 pub name: Ident,
128 /// The enum's variants.
129 pub variants: Vec<EnumVariant>,
130 /// Span covering the declaration.
131 pub span: Span,
132}
133
134/// A const declaration: `const MAX_RETRIES: Int = 3`
135#[derive(Debug, Clone, PartialEq)]
136pub struct ConstDecl {
137 /// Whether this const is public.
138 pub is_pub: bool,
139 /// The constant's name.
140 pub name: Ident,
141 /// The constant's type.
142 pub ty: TypeExpr,
143 /// The constant's value.
144 pub value: Expr,
145 /// Span covering the declaration.
146 pub span: Span,
147}
148
149// =============================================================================
150// Tool declarations (RFC-0011)
151// =============================================================================
152
153/// A tool declaration: `tool Http { fn get(url: String) -> Result<String, String> }`
154#[derive(Debug, Clone, PartialEq)]
155pub struct ToolDecl {
156 /// Whether this tool is public.
157 pub is_pub: bool,
158 /// The tool's name.
159 pub name: Ident,
160 /// The tool's function signatures.
161 pub functions: Vec<ToolFnDecl>,
162 /// Span covering the declaration.
163 pub span: Span,
164}
165
166/// A function signature in a tool declaration (no body).
167#[derive(Debug, Clone, PartialEq)]
168pub struct ToolFnDecl {
169 /// The function's name.
170 pub name: Ident,
171 /// The function's parameters.
172 pub params: Vec<Param>,
173 /// The return type.
174 pub return_ty: TypeExpr,
175 /// Span covering the declaration.
176 pub span: Span,
177}
178
179// =============================================================================
180// Agent declarations
181// =============================================================================
182
183/// An agent declaration: `agent Name { ... }` or `pub agent Name receives MsgType { ... }`
184#[derive(Debug, Clone, PartialEq)]
185pub struct AgentDecl {
186 /// Whether this agent is public (can be imported by other modules).
187 pub is_pub: bool,
188 /// The agent's name.
189 pub name: Ident,
190 /// The message type this agent receives (for message passing).
191 pub receives: Option<TypeExpr>,
192 /// Tools this agent uses (RFC-0011): `use Http, Fs`
193 pub tool_uses: Vec<Ident>,
194 /// Belief declarations (agent state).
195 pub beliefs: Vec<BeliefDecl>,
196 /// Event handlers.
197 pub handlers: Vec<HandlerDecl>,
198 /// Span covering the entire declaration.
199 pub span: Span,
200}
201
202/// A belief declaration: `belief name: Type`
203#[derive(Debug, Clone, PartialEq)]
204pub struct BeliefDecl {
205 /// The belief's name.
206 pub name: Ident,
207 /// The belief's type.
208 pub ty: TypeExpr,
209 /// Span covering the declaration.
210 pub span: Span,
211}
212
213/// An event handler: `on start { ... }`, `on message(x: T) { ... }`, `on stop { ... }`
214#[derive(Debug, Clone, PartialEq)]
215pub struct HandlerDecl {
216 /// The event kind this handler responds to.
217 pub event: EventKind,
218 /// The handler body.
219 pub body: Block,
220 /// Span covering the entire handler.
221 pub span: Span,
222}
223
224/// The kind of event a handler responds to.
225#[derive(Debug, Clone, PartialEq)]
226pub enum EventKind {
227 /// `on start` — runs when the agent is spawned.
228 Start,
229 /// `on message(param: Type)` — runs when a message is received.
230 Message {
231 /// The parameter name for the incoming message.
232 param_name: Ident,
233 /// The type of the message.
234 param_ty: TypeExpr,
235 },
236 /// `on stop` — runs during graceful shutdown.
237 Stop,
238 /// `on error(e)` — runs when an unhandled error occurs in the agent.
239 Error {
240 /// The parameter name for the error.
241 param_name: Ident,
242 },
243}
244
245impl fmt::Display for EventKind {
246 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
247 match self {
248 EventKind::Start => write!(f, "start"),
249 EventKind::Message {
250 param_name,
251 param_ty,
252 } => {
253 write!(f, "message({param_name}: {param_ty})")
254 }
255 EventKind::Stop => write!(f, "stop"),
256 EventKind::Error { param_name } => {
257 write!(f, "error({param_name})")
258 }
259 }
260 }
261}
262
263// =============================================================================
264// Function declarations
265// =============================================================================
266
267/// A function declaration: `fn name(params) -> ReturnType { ... }` or `fn name(params) -> ReturnType fails { ... }`
268#[derive(Debug, Clone, PartialEq)]
269pub struct FnDecl {
270 /// Whether this function is public (can be imported by other modules).
271 pub is_pub: bool,
272 /// The function's name.
273 pub name: Ident,
274 /// The function's parameters.
275 pub params: Vec<Param>,
276 /// The return type.
277 pub return_ty: TypeExpr,
278 /// Whether this function can fail (marked with `fails`).
279 pub is_fallible: bool,
280 /// The function body.
281 pub body: Block,
282 /// Span covering the entire declaration.
283 pub span: Span,
284}
285
286/// A function parameter: `name: Type`
287#[derive(Debug, Clone, PartialEq)]
288pub struct Param {
289 /// The parameter name.
290 pub name: Ident,
291 /// The parameter type.
292 pub ty: TypeExpr,
293 /// Span covering the parameter.
294 pub span: Span,
295}
296
297/// A closure parameter: `name` or `name: Type`
298#[derive(Debug, Clone, PartialEq)]
299pub struct ClosureParam {
300 /// The parameter name.
301 pub name: Ident,
302 /// Optional type annotation (can be inferred).
303 pub ty: Option<TypeExpr>,
304 /// Span covering the parameter.
305 pub span: Span,
306}
307
308// =============================================================================
309// Test declarations (RFC-0012)
310// =============================================================================
311
312/// A test declaration: `test "description" { ... }` or `@serial test "description" { ... }`
313#[derive(Debug, Clone, PartialEq)]
314pub struct TestDecl {
315 /// The test description (the string after `test`).
316 pub name: String,
317 /// Whether this test must run serially (marked with `@serial`).
318 pub is_serial: bool,
319 /// The test body.
320 pub body: Block,
321 /// Span covering the entire declaration.
322 pub span: Span,
323}
324
325// =============================================================================
326// Blocks and statements
327// =============================================================================
328
329/// A block of statements: `{ stmt* }`
330#[derive(Debug, Clone, PartialEq)]
331pub struct Block {
332 /// The statements in this block.
333 pub stmts: Vec<Stmt>,
334 /// Span covering the entire block (including braces).
335 pub span: Span,
336}
337
338/// A statement.
339#[derive(Debug, Clone, PartialEq)]
340pub enum Stmt {
341 /// Variable binding: `let name: Type = expr` or `let name = expr`
342 Let {
343 /// The variable name.
344 name: Ident,
345 /// Optional type annotation.
346 ty: Option<TypeExpr>,
347 /// The initial value.
348 value: Expr,
349 /// Span covering the statement.
350 span: Span,
351 },
352
353 /// Assignment: `name = expr`
354 Assign {
355 /// The variable being assigned to.
356 name: Ident,
357 /// The new value.
358 value: Expr,
359 /// Span covering the statement.
360 span: Span,
361 },
362
363 /// Return statement: `return expr?`
364 Return {
365 /// The optional return value.
366 value: Option<Expr>,
367 /// Span covering the statement.
368 span: Span,
369 },
370
371 /// If statement: `if cond { ... } else { ... }`
372 If {
373 /// The condition (must be Bool).
374 condition: Expr,
375 /// The then branch.
376 then_block: Block,
377 /// The optional else branch (can be another If for else-if chains).
378 else_block: Option<ElseBranch>,
379 /// Span covering the statement.
380 span: Span,
381 },
382
383 /// For loop: `for x in iter { ... }` or `for (k, v) in map { ... }`
384 For {
385 /// The loop pattern (can be a simple binding or tuple destructuring).
386 pattern: Pattern,
387 /// The iterable expression (List<T> or Map<K, V>).
388 iter: Expr,
389 /// The loop body.
390 body: Block,
391 /// Span covering the statement.
392 span: Span,
393 },
394
395 /// While loop: `while cond { ... }`
396 While {
397 /// The condition (must be Bool).
398 condition: Expr,
399 /// The loop body.
400 body: Block,
401 /// Span covering the statement.
402 span: Span,
403 },
404
405 /// Infinite loop: `loop { ... }`
406 Loop {
407 /// The loop body.
408 body: Block,
409 /// Span covering the statement.
410 span: Span,
411 },
412
413 /// Break statement: `break`
414 Break {
415 /// Span covering the statement.
416 span: Span,
417 },
418
419 /// Expression statement: `expr`
420 Expr {
421 /// The expression.
422 expr: Expr,
423 /// Span covering the statement.
424 span: Span,
425 },
426
427 /// Tuple destructuring: `let (a, b) = expr;`
428 LetTuple {
429 /// The variable names.
430 names: Vec<Ident>,
431 /// Optional type annotation.
432 ty: Option<TypeExpr>,
433 /// The value expression.
434 value: Expr,
435 /// Span covering the statement.
436 span: Span,
437 },
438
439 /// RFC-0012: Mock infer statement: `mock infer -> expr;`
440 MockInfer {
441 /// The mock value expression.
442 value: MockValue,
443 /// Span covering the statement.
444 span: Span,
445 },
446}
447
448/// RFC-0012: A mock value for `mock infer -> value`.
449#[derive(Debug, Clone, PartialEq)]
450pub enum MockValue {
451 /// A literal value: `mock infer -> "string"` or `mock infer -> SomeRecord { ... }`
452 Value(Expr),
453 /// A failure: `mock infer -> fail("error message")`
454 Fail(Expr),
455}
456
457impl Stmt {
458 /// Get the span of this statement.
459 #[must_use]
460 pub fn span(&self) -> &Span {
461 match self {
462 Stmt::Let { span, .. }
463 | Stmt::Assign { span, .. }
464 | Stmt::Return { span, .. }
465 | Stmt::If { span, .. }
466 | Stmt::For { span, .. }
467 | Stmt::While { span, .. }
468 | Stmt::Loop { span, .. }
469 | Stmt::Break { span, .. }
470 | Stmt::Expr { span, .. }
471 | Stmt::LetTuple { span, .. }
472 | Stmt::MockInfer { span, .. } => span,
473 }
474 }
475}
476
477/// The else branch of an if statement.
478#[derive(Debug, Clone, PartialEq)]
479pub enum ElseBranch {
480 /// `else { ... }`
481 Block(Block),
482 /// `else if ...` (chained if)
483 ElseIf(Box<Stmt>),
484}
485
486// =============================================================================
487// Expressions
488// =============================================================================
489
490/// An expression.
491#[derive(Debug, Clone, PartialEq)]
492pub enum Expr {
493 /// LLM inference: `infer("template")` or `infer("template" -> Type)`
494 Infer {
495 /// The prompt template (may contain `{ident}` interpolations).
496 template: StringTemplate,
497 /// Optional result type annotation.
498 result_ty: Option<TypeExpr>,
499 /// Span covering the expression.
500 span: Span,
501 },
502
503 /// Agent spawning: `spawn AgentName { field: value, ... }`
504 Spawn {
505 /// The agent type to spawn.
506 agent: Ident,
507 /// Initial belief values.
508 fields: Vec<FieldInit>,
509 /// Span covering the expression.
510 span: Span,
511 },
512
513 /// Await: `await expr`
514 Await {
515 /// The agent handle to await.
516 handle: Box<Expr>,
517 /// Span covering the expression.
518 span: Span,
519 },
520
521 /// Send message: `send(handle, message)`
522 Send {
523 /// The agent handle to send to.
524 handle: Box<Expr>,
525 /// The message to send.
526 message: Box<Expr>,
527 /// Span covering the expression.
528 span: Span,
529 },
530
531 /// Emit value: `emit(value)`
532 Emit {
533 /// The value to emit to the awaiter.
534 value: Box<Expr>,
535 /// Span covering the expression.
536 span: Span,
537 },
538
539 /// Function call: `name(args)`
540 Call {
541 /// The function name.
542 name: Ident,
543 /// The arguments.
544 args: Vec<Expr>,
545 /// Span covering the expression.
546 span: Span,
547 },
548
549 /// Method call on self: `self.method(args)`
550 SelfMethodCall {
551 /// The method name.
552 method: Ident,
553 /// The arguments.
554 args: Vec<Expr>,
555 /// Span covering the expression.
556 span: Span,
557 },
558
559 /// Self field access: `self.field`
560 SelfField {
561 /// The field (belief) name.
562 field: Ident,
563 /// Span covering the expression.
564 span: Span,
565 },
566
567 /// Binary operation: `left op right`
568 Binary {
569 /// The operator.
570 op: BinOp,
571 /// The left operand.
572 left: Box<Expr>,
573 /// The right operand.
574 right: Box<Expr>,
575 /// Span covering the expression.
576 span: Span,
577 },
578
579 /// Unary operation: `op operand`
580 Unary {
581 /// The operator.
582 op: UnaryOp,
583 /// The operand.
584 operand: Box<Expr>,
585 /// Span covering the expression.
586 span: Span,
587 },
588
589 /// List literal: `[a, b, c]`
590 List {
591 /// The list elements.
592 elements: Vec<Expr>,
593 /// Span covering the expression.
594 span: Span,
595 },
596
597 /// Literal value.
598 Literal {
599 /// The literal value.
600 value: Literal,
601 /// Span covering the expression.
602 span: Span,
603 },
604
605 /// Variable reference.
606 Var {
607 /// The variable name.
608 name: Ident,
609 /// Span covering the expression.
610 span: Span,
611 },
612
613 /// Parenthesized expression: `(expr)`
614 Paren {
615 /// The inner expression.
616 inner: Box<Expr>,
617 /// Span covering the expression (including parens).
618 span: Span,
619 },
620
621 /// Interpolated string: `"Hello, {name}!"`
622 StringInterp {
623 /// The string template with interpolations.
624 template: StringTemplate,
625 /// Span covering the expression.
626 span: Span,
627 },
628
629 /// Match expression: `match expr { Pattern => expr, ... }`
630 Match {
631 /// The scrutinee expression.
632 scrutinee: Box<Expr>,
633 /// The match arms.
634 arms: Vec<MatchArm>,
635 /// Span covering the expression.
636 span: Span,
637 },
638
639 /// Record construction: `Point { x: 1, y: 2 }`
640 RecordConstruct {
641 /// The record type name.
642 name: Ident,
643 /// Field initializations.
644 fields: Vec<FieldInit>,
645 /// Span covering the expression.
646 span: Span,
647 },
648
649 /// Field access: `record.field`
650 FieldAccess {
651 /// The record expression.
652 object: Box<Expr>,
653 /// The field name.
654 field: Ident,
655 /// Span covering the expression.
656 span: Span,
657 },
658
659 /// Receive message from mailbox: `receive()`
660 Receive {
661 /// Span covering the expression.
662 span: Span,
663 },
664
665 /// Try expression: `try expr` — propagates failure upward.
666 Try {
667 /// The expression that may fail.
668 expr: Box<Expr>,
669 /// Span covering the expression.
670 span: Span,
671 },
672
673 /// Catch expression: `expr catch { recovery }` or `expr catch(e) { recovery }`.
674 Catch {
675 /// The expression that may fail.
676 expr: Box<Expr>,
677 /// The optional error binding (e.g., `e` in `catch(e)`).
678 error_bind: Option<Ident>,
679 /// The recovery expression.
680 recovery: Box<Expr>,
681 /// Span covering the expression.
682 span: Span,
683 },
684
685 /// Closure expression: `|params| body`
686 Closure {
687 /// The closure parameters.
688 params: Vec<ClosureParam>,
689 /// The closure body (single expression).
690 body: Box<Expr>,
691 /// Span covering the expression.
692 span: Span,
693 },
694
695 /// Tuple literal: `(a, b, c)`
696 Tuple {
697 /// The tuple elements (at least 2).
698 elements: Vec<Expr>,
699 /// Span covering the expression.
700 span: Span,
701 },
702
703 /// Tuple index access: `tuple.0`
704 TupleIndex {
705 /// The tuple expression.
706 tuple: Box<Expr>,
707 /// The index (0-based).
708 index: usize,
709 /// Span covering the expression.
710 span: Span,
711 },
712
713 /// Map literal: `{ key: value, ... }` or `{}`
714 Map {
715 /// The map entries.
716 entries: Vec<MapEntry>,
717 /// Span covering the expression.
718 span: Span,
719 },
720
721 /// Enum variant construction: `MyEnum.Variant` or `MyEnum.Variant(payload)`
722 VariantConstruct {
723 /// The enum type name.
724 enum_name: Ident,
725 /// The variant name.
726 variant: Ident,
727 /// The optional payload expression.
728 payload: Option<Box<Expr>>,
729 /// Span covering the expression.
730 span: Span,
731 },
732
733 /// Tool function call (RFC-0011): `Http.get(url)`
734 ToolCall {
735 /// The tool name.
736 tool: Ident,
737 /// The function name.
738 function: Ident,
739 /// The arguments.
740 args: Vec<Expr>,
741 /// Span covering the expression.
742 span: Span,
743 },
744}
745
746/// A map entry: `key: value`
747#[derive(Debug, Clone, PartialEq)]
748pub struct MapEntry {
749 /// The key expression.
750 pub key: Expr,
751 /// The value expression.
752 pub value: Expr,
753 /// Span covering the entry.
754 pub span: Span,
755}
756
757impl Expr {
758 /// Get the span of this expression.
759 #[must_use]
760 pub fn span(&self) -> &Span {
761 match self {
762 Expr::Infer { span, .. }
763 | Expr::Spawn { span, .. }
764 | Expr::Await { span, .. }
765 | Expr::Send { span, .. }
766 | Expr::Emit { span, .. }
767 | Expr::Call { span, .. }
768 | Expr::SelfMethodCall { span, .. }
769 | Expr::SelfField { span, .. }
770 | Expr::Binary { span, .. }
771 | Expr::Unary { span, .. }
772 | Expr::List { span, .. }
773 | Expr::Literal { span, .. }
774 | Expr::Var { span, .. }
775 | Expr::Paren { span, .. }
776 | Expr::StringInterp { span, .. }
777 | Expr::Match { span, .. }
778 | Expr::RecordConstruct { span, .. }
779 | Expr::FieldAccess { span, .. }
780 | Expr::Receive { span, .. }
781 | Expr::Try { span, .. }
782 | Expr::Catch { span, .. }
783 | Expr::Closure { span, .. }
784 | Expr::Tuple { span, .. }
785 | Expr::TupleIndex { span, .. }
786 | Expr::Map { span, .. }
787 | Expr::VariantConstruct { span, .. }
788 | Expr::ToolCall { span, .. } => span,
789 }
790 }
791}
792
793/// A field initialization in a spawn or record construction expression: `field: value`
794#[derive(Debug, Clone, PartialEq)]
795pub struct FieldInit {
796 /// The field name.
797 pub name: Ident,
798 /// The initial value.
799 pub value: Expr,
800 /// Span covering the field initialization.
801 pub span: Span,
802}
803
804/// A match arm: `Pattern => expr`
805#[derive(Debug, Clone, PartialEq)]
806pub struct MatchArm {
807 /// The pattern to match.
808 pub pattern: Pattern,
809 /// The expression to evaluate if the pattern matches.
810 pub body: Expr,
811 /// Span covering the arm.
812 pub span: Span,
813}
814
815/// A pattern in a match expression.
816#[derive(Debug, Clone, PartialEq)]
817pub enum Pattern {
818 /// Wildcard pattern: `_`
819 Wildcard {
820 /// Span covering the pattern.
821 span: Span,
822 },
823 /// Enum variant pattern: `Status::Active`, `Ok(x)`, or just `Active`
824 Variant {
825 /// Optional enum type name (for qualified patterns).
826 enum_name: Option<Ident>,
827 /// The variant name.
828 variant: Ident,
829 /// Optional payload binding pattern (e.g., `x` in `Ok(x)`).
830 payload: Option<Box<Pattern>>,
831 /// Span covering the pattern.
832 span: Span,
833 },
834 /// Literal pattern: `42`, `"hello"`, `true`
835 Literal {
836 /// The literal value.
837 value: Literal,
838 /// Span covering the pattern.
839 span: Span,
840 },
841 /// Binding pattern: `x` (binds the matched value to a variable)
842 Binding {
843 /// The variable name.
844 name: Ident,
845 /// Span covering the pattern.
846 span: Span,
847 },
848 /// Tuple pattern: `(a, b, c)`
849 Tuple {
850 /// The element patterns.
851 elements: Vec<Pattern>,
852 /// Span covering the pattern.
853 span: Span,
854 },
855}
856
857impl Pattern {
858 /// Get the span of this pattern.
859 #[must_use]
860 pub fn span(&self) -> &Span {
861 match self {
862 Pattern::Wildcard { span }
863 | Pattern::Variant { span, .. }
864 | Pattern::Literal { span, .. }
865 | Pattern::Binding { span, .. }
866 | Pattern::Tuple { span, .. } => span,
867 }
868 }
869}
870
871// =============================================================================
872// Operators
873// =============================================================================
874
875/// Binary operators.
876#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
877pub enum BinOp {
878 // Arithmetic
879 /// `+`
880 Add,
881 /// `-`
882 Sub,
883 /// `*`
884 Mul,
885 /// `/`
886 Div,
887 /// `%` (remainder/modulo)
888 Rem,
889
890 // Comparison
891 /// `==`
892 Eq,
893 /// `!=`
894 Ne,
895 /// `<`
896 Lt,
897 /// `>`
898 Gt,
899 /// `<=`
900 Le,
901 /// `>=`
902 Ge,
903
904 // Logical
905 /// `&&`
906 And,
907 /// `||`
908 Or,
909
910 // String
911 /// `++` (string concatenation)
912 Concat,
913}
914
915impl BinOp {
916 /// Get the precedence of this operator (higher = binds tighter).
917 #[must_use]
918 pub fn precedence(self) -> u8 {
919 match self {
920 BinOp::Or => 1,
921 BinOp::And => 2,
922 BinOp::Eq | BinOp::Ne => 3,
923 BinOp::Lt | BinOp::Gt | BinOp::Le | BinOp::Ge => 4,
924 BinOp::Concat => 5,
925 BinOp::Add | BinOp::Sub => 6,
926 BinOp::Mul | BinOp::Div | BinOp::Rem => 7,
927 }
928 }
929
930 /// Check if this operator is left-associative.
931 #[must_use]
932 pub fn is_left_assoc(self) -> bool {
933 // All our operators are left-associative
934 true
935 }
936}
937
938impl fmt::Display for BinOp {
939 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
940 match self {
941 BinOp::Add => write!(f, "+"),
942 BinOp::Sub => write!(f, "-"),
943 BinOp::Mul => write!(f, "*"),
944 BinOp::Div => write!(f, "/"),
945 BinOp::Rem => write!(f, "%"),
946 BinOp::Eq => write!(f, "=="),
947 BinOp::Ne => write!(f, "!="),
948 BinOp::Lt => write!(f, "<"),
949 BinOp::Gt => write!(f, ">"),
950 BinOp::Le => write!(f, "<="),
951 BinOp::Ge => write!(f, ">="),
952 BinOp::And => write!(f, "&&"),
953 BinOp::Or => write!(f, "||"),
954 BinOp::Concat => write!(f, "++"),
955 }
956 }
957}
958
959/// Unary operators.
960#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
961pub enum UnaryOp {
962 /// `-` (negation)
963 Neg,
964 /// `!` (logical not)
965 Not,
966}
967
968impl fmt::Display for UnaryOp {
969 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
970 match self {
971 UnaryOp::Neg => write!(f, "-"),
972 UnaryOp::Not => write!(f, "!"),
973 }
974 }
975}
976
977// =============================================================================
978// Literals
979// =============================================================================
980
981/// A literal value.
982#[derive(Debug, Clone, PartialEq)]
983pub enum Literal {
984 /// Integer literal: `42`, `-7`
985 Int(i64),
986 /// Float literal: `3.14`, `-0.5`
987 Float(f64),
988 /// Boolean literal: `true`, `false`
989 Bool(bool),
990 /// String literal: `"hello"`
991 String(String),
992}
993
994impl fmt::Display for Literal {
995 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
996 match self {
997 Literal::Int(n) => write!(f, "{n}"),
998 Literal::Float(n) => write!(f, "{n}"),
999 Literal::Bool(b) => write!(f, "{b}"),
1000 Literal::String(s) => write!(f, "\"{s}\""),
1001 }
1002 }
1003}
1004
1005// =============================================================================
1006// String templates (for interpolation)
1007// =============================================================================
1008
1009/// A string template that may contain interpolations.
1010///
1011/// For example, `"Hello, {name}!"` becomes:
1012/// ```text
1013/// StringTemplate {
1014/// parts: [
1015/// StringPart::Literal("Hello, "),
1016/// StringPart::Interpolation(Ident("name")),
1017/// StringPart::Literal("!"),
1018/// ]
1019/// }
1020/// ```
1021#[derive(Debug, Clone, PartialEq)]
1022pub struct StringTemplate {
1023 /// The parts of the template.
1024 pub parts: Vec<StringPart>,
1025 /// Span covering the entire template string.
1026 pub span: Span,
1027}
1028
1029impl StringTemplate {
1030 /// Create a simple template with no interpolations.
1031 #[must_use]
1032 pub fn literal(s: String, span: Span) -> Self {
1033 Self {
1034 parts: vec![StringPart::Literal(s)],
1035 span,
1036 }
1037 }
1038
1039 /// Check if this template has any interpolations.
1040 #[must_use]
1041 pub fn has_interpolations(&self) -> bool {
1042 self.parts
1043 .iter()
1044 .any(|p| matches!(p, StringPart::Interpolation(_)))
1045 }
1046
1047 /// Get all interpolation expressions.
1048 pub fn interpolations(&self) -> impl Iterator<Item = &InterpExpr> {
1049 self.parts.iter().filter_map(|p| match p {
1050 StringPart::Interpolation(expr) => Some(expr),
1051 StringPart::Literal(_) => None,
1052 })
1053 }
1054}
1055
1056impl fmt::Display for StringTemplate {
1057 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1058 write!(f, "\"")?;
1059 for part in &self.parts {
1060 match part {
1061 StringPart::Literal(s) => write!(f, "{s}")?,
1062 StringPart::Interpolation(expr) => write!(f, "{{{expr}}}")?,
1063 }
1064 }
1065 write!(f, "\"")
1066 }
1067}
1068
1069/// A part of a string template.
1070#[derive(Debug, Clone, PartialEq)]
1071pub enum StringPart {
1072 /// A literal string segment.
1073 Literal(String),
1074 /// An interpolated expression: `{ident}`, `{person.name}`, `{pair.0}`
1075 Interpolation(InterpExpr),
1076}
1077
1078/// An interpolation expression within a string template.
1079/// Supports simple identifiers, field access chains, and tuple indexing.
1080#[derive(Debug, Clone, PartialEq)]
1081pub enum InterpExpr {
1082 /// Simple identifier: `{name}`
1083 Ident(Ident),
1084 /// Field access: `{person.name}`, `{record.field.subfield}`
1085 FieldAccess {
1086 /// The base expression
1087 base: Box<InterpExpr>,
1088 /// The field being accessed
1089 field: Ident,
1090 /// Span covering the entire expression
1091 span: Span,
1092 },
1093 /// Tuple index: `{pair.0}`, `{triple.2}`
1094 TupleIndex {
1095 /// The base expression
1096 base: Box<InterpExpr>,
1097 /// The tuple index (0-based)
1098 index: usize,
1099 /// Span covering the entire expression
1100 span: Span,
1101 },
1102}
1103
1104impl InterpExpr {
1105 /// Get the span of this interpolation expression.
1106 #[must_use]
1107 pub fn span(&self) -> &Span {
1108 match self {
1109 InterpExpr::Ident(ident) => &ident.span,
1110 InterpExpr::FieldAccess { span, .. } => span,
1111 InterpExpr::TupleIndex { span, .. } => span,
1112 }
1113 }
1114
1115 /// Get the base identifier of this expression.
1116 #[must_use]
1117 pub fn base_ident(&self) -> &Ident {
1118 match self {
1119 InterpExpr::Ident(ident) => ident,
1120 InterpExpr::FieldAccess { base, .. } => base.base_ident(),
1121 InterpExpr::TupleIndex { base, .. } => base.base_ident(),
1122 }
1123 }
1124}
1125
1126impl fmt::Display for InterpExpr {
1127 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1128 match self {
1129 InterpExpr::Ident(ident) => write!(f, "{}", ident.name),
1130 InterpExpr::FieldAccess { base, field, .. } => {
1131 write!(f, "{}.{}", base, field.name)
1132 }
1133 InterpExpr::TupleIndex { base, index, .. } => {
1134 write!(f, "{}.{}", base, index)
1135 }
1136 }
1137 }
1138}
1139
1140// =============================================================================
1141// Tests
1142// =============================================================================
1143
1144#[cfg(test)]
1145mod tests {
1146 use super::*;
1147
1148 #[test]
1149 fn binop_precedence() {
1150 // Mul/Div > Add/Sub > Comparison > And > Or
1151 assert!(BinOp::Mul.precedence() > BinOp::Add.precedence());
1152 assert!(BinOp::Add.precedence() > BinOp::Lt.precedence());
1153 assert!(BinOp::Lt.precedence() > BinOp::And.precedence());
1154 assert!(BinOp::And.precedence() > BinOp::Or.precedence());
1155 }
1156
1157 #[test]
1158 fn binop_display() {
1159 assert_eq!(format!("{}", BinOp::Add), "+");
1160 assert_eq!(format!("{}", BinOp::Eq), "==");
1161 assert_eq!(format!("{}", BinOp::Concat), "++");
1162 assert_eq!(format!("{}", BinOp::And), "&&");
1163 }
1164
1165 #[test]
1166 fn unaryop_display() {
1167 assert_eq!(format!("{}", UnaryOp::Neg), "-");
1168 assert_eq!(format!("{}", UnaryOp::Not), "!");
1169 }
1170
1171 #[test]
1172 fn literal_display() {
1173 assert_eq!(format!("{}", Literal::Int(42)), "42");
1174 assert_eq!(format!("{}", Literal::Float(3.14)), "3.14");
1175 assert_eq!(format!("{}", Literal::Bool(true)), "true");
1176 assert_eq!(format!("{}", Literal::String("hello".into())), "\"hello\"");
1177 }
1178
1179 #[test]
1180 fn event_kind_display() {
1181 assert_eq!(format!("{}", EventKind::Start), "start");
1182 assert_eq!(format!("{}", EventKind::Stop), "stop");
1183
1184 let msg = EventKind::Message {
1185 param_name: Ident::dummy("msg"),
1186 param_ty: TypeExpr::String,
1187 };
1188 assert_eq!(format!("{msg}"), "message(msg: String)");
1189 }
1190
1191 #[test]
1192 fn string_template_literal() {
1193 let template = StringTemplate::literal("hello".into(), Span::dummy());
1194 assert!(!template.has_interpolations());
1195 assert_eq!(format!("{template}"), "\"hello\"");
1196 }
1197
1198 #[test]
1199 fn string_template_with_interpolation() {
1200 let template = StringTemplate {
1201 parts: vec![
1202 StringPart::Literal("Hello, ".into()),
1203 StringPart::Interpolation(InterpExpr::Ident(Ident::dummy("name"))),
1204 StringPart::Literal("!".into()),
1205 ],
1206 span: Span::dummy(),
1207 };
1208 assert!(template.has_interpolations());
1209 assert_eq!(format!("{template}"), "\"Hello, {name}!\"");
1210
1211 let interps: Vec<_> = template.interpolations().collect();
1212 assert_eq!(interps.len(), 1);
1213 assert_eq!(interps[0].base_ident().name, "name");
1214 }
1215
1216 #[test]
1217 fn expr_span() {
1218 let span = Span::dummy();
1219 let expr = Expr::Literal {
1220 value: Literal::Int(42),
1221 span: span.clone(),
1222 };
1223 assert_eq!(expr.span(), &span);
1224 }
1225
1226 #[test]
1227 fn stmt_span() {
1228 let span = Span::dummy();
1229 let stmt = Stmt::Return {
1230 value: None,
1231 span: span.clone(),
1232 };
1233 assert_eq!(stmt.span(), &span);
1234 }
1235}