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 crate::{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` or `await expr timeout(ms)`
514 Await {
515 /// The agent handle to await.
516 handle: Box<Expr>,
517 /// Optional timeout in milliseconds.
518 timeout: Option<Box<Expr>>,
519 /// Span covering the expression.
520 span: Span,
521 },
522
523 /// Send message: `send(handle, message)`
524 Send {
525 /// The agent handle to send to.
526 handle: Box<Expr>,
527 /// The message to send.
528 message: Box<Expr>,
529 /// Span covering the expression.
530 span: Span,
531 },
532
533 /// Emit value: `emit(value)`
534 Emit {
535 /// The value to emit to the awaiter.
536 value: Box<Expr>,
537 /// Span covering the expression.
538 span: Span,
539 },
540
541 /// Function call: `name(args)`
542 Call {
543 /// The function name.
544 name: Ident,
545 /// The arguments.
546 args: Vec<Expr>,
547 /// Span covering the expression.
548 span: Span,
549 },
550
551 /// Method call on self: `self.method(args)`
552 SelfMethodCall {
553 /// The method name.
554 method: Ident,
555 /// The arguments.
556 args: Vec<Expr>,
557 /// Span covering the expression.
558 span: Span,
559 },
560
561 /// Self field access: `self.field`
562 SelfField {
563 /// The field (belief) name.
564 field: Ident,
565 /// Span covering the expression.
566 span: Span,
567 },
568
569 /// Binary operation: `left op right`
570 Binary {
571 /// The operator.
572 op: BinOp,
573 /// The left operand.
574 left: Box<Expr>,
575 /// The right operand.
576 right: Box<Expr>,
577 /// Span covering the expression.
578 span: Span,
579 },
580
581 /// Unary operation: `op operand`
582 Unary {
583 /// The operator.
584 op: UnaryOp,
585 /// The operand.
586 operand: Box<Expr>,
587 /// Span covering the expression.
588 span: Span,
589 },
590
591 /// List literal: `[a, b, c]`
592 List {
593 /// The list elements.
594 elements: Vec<Expr>,
595 /// Span covering the expression.
596 span: Span,
597 },
598
599 /// Literal value.
600 Literal {
601 /// The literal value.
602 value: Literal,
603 /// Span covering the expression.
604 span: Span,
605 },
606
607 /// Variable reference.
608 Var {
609 /// The variable name.
610 name: Ident,
611 /// Span covering the expression.
612 span: Span,
613 },
614
615 /// Parenthesized expression: `(expr)`
616 Paren {
617 /// The inner expression.
618 inner: Box<Expr>,
619 /// Span covering the expression (including parens).
620 span: Span,
621 },
622
623 /// Interpolated string: `"Hello, {name}!"`
624 StringInterp {
625 /// The string template with interpolations.
626 template: StringTemplate,
627 /// Span covering the expression.
628 span: Span,
629 },
630
631 /// Match expression: `match expr { Pattern => expr, ... }`
632 Match {
633 /// The scrutinee expression.
634 scrutinee: Box<Expr>,
635 /// The match arms.
636 arms: Vec<MatchArm>,
637 /// Span covering the expression.
638 span: Span,
639 },
640
641 /// Record construction: `Point { x: 1, y: 2 }`
642 RecordConstruct {
643 /// The record type name.
644 name: Ident,
645 /// Field initializations.
646 fields: Vec<FieldInit>,
647 /// Span covering the expression.
648 span: Span,
649 },
650
651 /// Field access: `record.field`
652 FieldAccess {
653 /// The record expression.
654 object: Box<Expr>,
655 /// The field name.
656 field: Ident,
657 /// Span covering the expression.
658 span: Span,
659 },
660
661 /// Receive message from mailbox: `receive()`
662 Receive {
663 /// Span covering the expression.
664 span: Span,
665 },
666
667 /// Try expression: `try expr` — propagates failure upward.
668 Try {
669 /// The expression that may fail.
670 expr: Box<Expr>,
671 /// Span covering the expression.
672 span: Span,
673 },
674
675 /// Catch expression: `expr catch { recovery }` or `expr catch(e) { recovery }`.
676 Catch {
677 /// The expression that may fail.
678 expr: Box<Expr>,
679 /// The optional error binding (e.g., `e` in `catch(e)`).
680 error_bind: Option<Ident>,
681 /// The recovery expression.
682 recovery: Box<Expr>,
683 /// Span covering the expression.
684 span: Span,
685 },
686
687 /// Fail expression: `fail "message"` or `fail Error { ... }`.
688 /// Type is `Never` - this expression never returns.
689 Fail {
690 /// The error value (either a string message or an Error record).
691 error: Box<Expr>,
692 /// Span covering the expression.
693 span: Span,
694 },
695
696 /// Retry expression: `retry(3) { ... }` or `retry(3, delay: 1000) { ... }`
697 Retry {
698 /// Number of retry attempts (1-10).
699 count: Box<Expr>,
700 /// Optional delay between attempts in milliseconds.
701 delay: Option<Box<Expr>>,
702 /// Optional list of error kinds to retry on.
703 on_errors: Option<Vec<Expr>>,
704 /// The body to retry.
705 body: Box<Expr>,
706 /// Span covering the expression.
707 span: Span,
708 },
709
710 /// Trace expression: `trace("message")` for emitting trace events.
711 Trace {
712 /// The message to trace (must be a string).
713 message: Box<Expr>,
714 /// Span covering the expression.
715 span: Span,
716 },
717
718 /// Closure expression: `|params| body`
719 Closure {
720 /// The closure parameters.
721 params: Vec<ClosureParam>,
722 /// The closure body (single expression).
723 body: Box<Expr>,
724 /// Span covering the expression.
725 span: Span,
726 },
727
728 /// Tuple literal: `(a, b, c)`
729 Tuple {
730 /// The tuple elements (at least 2).
731 elements: Vec<Expr>,
732 /// Span covering the expression.
733 span: Span,
734 },
735
736 /// Tuple index access: `tuple.0`
737 TupleIndex {
738 /// The tuple expression.
739 tuple: Box<Expr>,
740 /// The index (0-based).
741 index: usize,
742 /// Span covering the expression.
743 span: Span,
744 },
745
746 /// Map literal: `{ key: value, ... }` or `{}`
747 Map {
748 /// The map entries.
749 entries: Vec<MapEntry>,
750 /// Span covering the expression.
751 span: Span,
752 },
753
754 /// Enum variant construction: `MyEnum.Variant` or `MyEnum.Variant(payload)`
755 VariantConstruct {
756 /// The enum type name.
757 enum_name: Ident,
758 /// The variant name.
759 variant: Ident,
760 /// The optional payload expression.
761 payload: Option<Box<Expr>>,
762 /// Span covering the expression.
763 span: Span,
764 },
765
766 /// Tool function call (RFC-0011): `Http.get(url)`
767 ToolCall {
768 /// The tool name.
769 tool: Ident,
770 /// The function name.
771 function: Ident,
772 /// The arguments.
773 args: Vec<Expr>,
774 /// Span covering the expression.
775 span: Span,
776 },
777}
778
779/// A map entry: `key: value`
780#[derive(Debug, Clone, PartialEq)]
781pub struct MapEntry {
782 /// The key expression.
783 pub key: Expr,
784 /// The value expression.
785 pub value: Expr,
786 /// Span covering the entry.
787 pub span: Span,
788}
789
790impl Expr {
791 /// Get the span of this expression.
792 #[must_use]
793 pub fn span(&self) -> &Span {
794 match self {
795 Expr::Infer { span, .. }
796 | Expr::Spawn { span, .. }
797 | Expr::Await { span, .. }
798 | Expr::Send { span, .. }
799 | Expr::Emit { span, .. }
800 | Expr::Call { span, .. }
801 | Expr::SelfMethodCall { span, .. }
802 | Expr::SelfField { span, .. }
803 | Expr::Binary { span, .. }
804 | Expr::Unary { span, .. }
805 | Expr::List { span, .. }
806 | Expr::Literal { span, .. }
807 | Expr::Var { span, .. }
808 | Expr::Paren { span, .. }
809 | Expr::StringInterp { span, .. }
810 | Expr::Match { span, .. }
811 | Expr::RecordConstruct { span, .. }
812 | Expr::FieldAccess { span, .. }
813 | Expr::Receive { span, .. }
814 | Expr::Try { span, .. }
815 | Expr::Catch { span, .. }
816 | Expr::Fail { span, .. }
817 | Expr::Retry { span, .. }
818 | Expr::Trace { span, .. }
819 | Expr::Closure { span, .. }
820 | Expr::Tuple { span, .. }
821 | Expr::TupleIndex { span, .. }
822 | Expr::Map { span, .. }
823 | Expr::VariantConstruct { span, .. }
824 | Expr::ToolCall { span, .. } => span,
825 }
826 }
827}
828
829/// A field initialization in a spawn or record construction expression: `field: value`
830#[derive(Debug, Clone, PartialEq)]
831pub struct FieldInit {
832 /// The field name.
833 pub name: Ident,
834 /// The initial value.
835 pub value: Expr,
836 /// Span covering the field initialization.
837 pub span: Span,
838}
839
840/// A match arm: `Pattern => expr`
841#[derive(Debug, Clone, PartialEq)]
842pub struct MatchArm {
843 /// The pattern to match.
844 pub pattern: Pattern,
845 /// The expression to evaluate if the pattern matches.
846 pub body: Expr,
847 /// Span covering the arm.
848 pub span: Span,
849}
850
851/// A pattern in a match expression.
852#[derive(Debug, Clone, PartialEq)]
853pub enum Pattern {
854 /// Wildcard pattern: `_`
855 Wildcard {
856 /// Span covering the pattern.
857 span: Span,
858 },
859 /// Enum variant pattern: `Status::Active`, `Ok(x)`, or just `Active`
860 Variant {
861 /// Optional enum type name (for qualified patterns).
862 enum_name: Option<Ident>,
863 /// The variant name.
864 variant: Ident,
865 /// Optional payload binding pattern (e.g., `x` in `Ok(x)`).
866 payload: Option<Box<Pattern>>,
867 /// Span covering the pattern.
868 span: Span,
869 },
870 /// Literal pattern: `42`, `"hello"`, `true`
871 Literal {
872 /// The literal value.
873 value: Literal,
874 /// Span covering the pattern.
875 span: Span,
876 },
877 /// Binding pattern: `x` (binds the matched value to a variable)
878 Binding {
879 /// The variable name.
880 name: Ident,
881 /// Span covering the pattern.
882 span: Span,
883 },
884 /// Tuple pattern: `(a, b, c)`
885 Tuple {
886 /// The element patterns.
887 elements: Vec<Pattern>,
888 /// Span covering the pattern.
889 span: Span,
890 },
891}
892
893impl Pattern {
894 /// Get the span of this pattern.
895 #[must_use]
896 pub fn span(&self) -> &Span {
897 match self {
898 Pattern::Wildcard { span }
899 | Pattern::Variant { span, .. }
900 | Pattern::Literal { span, .. }
901 | Pattern::Binding { span, .. }
902 | Pattern::Tuple { span, .. } => span,
903 }
904 }
905}
906
907// =============================================================================
908// Operators
909// =============================================================================
910
911/// Binary operators.
912#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
913pub enum BinOp {
914 // Arithmetic
915 /// `+`
916 Add,
917 /// `-`
918 Sub,
919 /// `*`
920 Mul,
921 /// `/`
922 Div,
923 /// `%` (remainder/modulo)
924 Rem,
925
926 // Comparison
927 /// `==`
928 Eq,
929 /// `!=`
930 Ne,
931 /// `<`
932 Lt,
933 /// `>`
934 Gt,
935 /// `<=`
936 Le,
937 /// `>=`
938 Ge,
939
940 // Logical
941 /// `&&`
942 And,
943 /// `||`
944 Or,
945
946 // String
947 /// `++` (string concatenation)
948 Concat,
949}
950
951impl BinOp {
952 /// Get the precedence of this operator (higher = binds tighter).
953 #[must_use]
954 pub fn precedence(self) -> u8 {
955 match self {
956 BinOp::Or => 1,
957 BinOp::And => 2,
958 BinOp::Eq | BinOp::Ne => 3,
959 BinOp::Lt | BinOp::Gt | BinOp::Le | BinOp::Ge => 4,
960 BinOp::Concat => 5,
961 BinOp::Add | BinOp::Sub => 6,
962 BinOp::Mul | BinOp::Div | BinOp::Rem => 7,
963 }
964 }
965
966 /// Check if this operator is left-associative.
967 #[must_use]
968 pub fn is_left_assoc(self) -> bool {
969 // All our operators are left-associative
970 true
971 }
972}
973
974impl fmt::Display for BinOp {
975 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
976 match self {
977 BinOp::Add => write!(f, "+"),
978 BinOp::Sub => write!(f, "-"),
979 BinOp::Mul => write!(f, "*"),
980 BinOp::Div => write!(f, "/"),
981 BinOp::Rem => write!(f, "%"),
982 BinOp::Eq => write!(f, "=="),
983 BinOp::Ne => write!(f, "!="),
984 BinOp::Lt => write!(f, "<"),
985 BinOp::Gt => write!(f, ">"),
986 BinOp::Le => write!(f, "<="),
987 BinOp::Ge => write!(f, ">="),
988 BinOp::And => write!(f, "&&"),
989 BinOp::Or => write!(f, "||"),
990 BinOp::Concat => write!(f, "++"),
991 }
992 }
993}
994
995/// Unary operators.
996#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
997pub enum UnaryOp {
998 /// `-` (negation)
999 Neg,
1000 /// `!` (logical not)
1001 Not,
1002}
1003
1004impl fmt::Display for UnaryOp {
1005 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1006 match self {
1007 UnaryOp::Neg => write!(f, "-"),
1008 UnaryOp::Not => write!(f, "!"),
1009 }
1010 }
1011}
1012
1013// =============================================================================
1014// Literals
1015// =============================================================================
1016
1017/// A literal value.
1018#[derive(Debug, Clone, PartialEq)]
1019pub enum Literal {
1020 /// Integer literal: `42`, `-7`
1021 Int(i64),
1022 /// Float literal: `3.14`, `-0.5`
1023 Float(f64),
1024 /// Boolean literal: `true`, `false`
1025 Bool(bool),
1026 /// String literal: `"hello"`
1027 String(String),
1028}
1029
1030impl fmt::Display for Literal {
1031 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1032 match self {
1033 Literal::Int(n) => write!(f, "{n}"),
1034 Literal::Float(n) => write!(f, "{n}"),
1035 Literal::Bool(b) => write!(f, "{b}"),
1036 Literal::String(s) => write!(f, "\"{s}\""),
1037 }
1038 }
1039}
1040
1041// =============================================================================
1042// String templates (for interpolation)
1043// =============================================================================
1044
1045/// A string template that may contain interpolations.
1046///
1047/// For example, `"Hello, {name}!"` becomes:
1048/// ```text
1049/// StringTemplate {
1050/// parts: [
1051/// StringPart::Literal("Hello, "),
1052/// StringPart::Interpolation(Ident("name")),
1053/// StringPart::Literal("!"),
1054/// ]
1055/// }
1056/// ```
1057#[derive(Debug, Clone, PartialEq)]
1058pub struct StringTemplate {
1059 /// The parts of the template.
1060 pub parts: Vec<StringPart>,
1061 /// Span covering the entire template string.
1062 pub span: Span,
1063}
1064
1065impl StringTemplate {
1066 /// Create a simple template with no interpolations.
1067 #[must_use]
1068 pub fn literal(s: String, span: Span) -> Self {
1069 Self {
1070 parts: vec![StringPart::Literal(s)],
1071 span,
1072 }
1073 }
1074
1075 /// Check if this template has any interpolations.
1076 #[must_use]
1077 pub fn has_interpolations(&self) -> bool {
1078 self.parts
1079 .iter()
1080 .any(|p| matches!(p, StringPart::Interpolation(_)))
1081 }
1082
1083 /// Get all interpolation expressions.
1084 pub fn interpolations(&self) -> impl Iterator<Item = &InterpExpr> {
1085 self.parts.iter().filter_map(|p| match p {
1086 StringPart::Interpolation(expr) => Some(expr),
1087 StringPart::Literal(_) => None,
1088 })
1089 }
1090}
1091
1092impl fmt::Display for StringTemplate {
1093 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1094 write!(f, "\"")?;
1095 for part in &self.parts {
1096 match part {
1097 StringPart::Literal(s) => write!(f, "{s}")?,
1098 StringPart::Interpolation(expr) => write!(f, "{{{expr}}}")?,
1099 }
1100 }
1101 write!(f, "\"")
1102 }
1103}
1104
1105/// A part of a string template.
1106#[derive(Debug, Clone, PartialEq)]
1107pub enum StringPart {
1108 /// A literal string segment.
1109 Literal(String),
1110 /// An interpolated expression: `{ident}`, `{person.name}`, `{pair.0}`
1111 Interpolation(InterpExpr),
1112}
1113
1114/// An interpolation expression within a string template.
1115/// Supports simple identifiers, field access chains, and tuple indexing.
1116#[derive(Debug, Clone, PartialEq)]
1117pub enum InterpExpr {
1118 /// Simple identifier: `{name}`
1119 Ident(Ident),
1120 /// Field access: `{person.name}`, `{record.field.subfield}`
1121 FieldAccess {
1122 /// The base expression
1123 base: Box<InterpExpr>,
1124 /// The field being accessed
1125 field: Ident,
1126 /// Span covering the entire expression
1127 span: Span,
1128 },
1129 /// Tuple index: `{pair.0}`, `{triple.2}`
1130 TupleIndex {
1131 /// The base expression
1132 base: Box<InterpExpr>,
1133 /// The tuple index (0-based)
1134 index: usize,
1135 /// Span covering the entire expression
1136 span: Span,
1137 },
1138}
1139
1140impl InterpExpr {
1141 /// Get the span of this interpolation expression.
1142 #[must_use]
1143 pub fn span(&self) -> &Span {
1144 match self {
1145 InterpExpr::Ident(ident) => &ident.span,
1146 InterpExpr::FieldAccess { span, .. } => span,
1147 InterpExpr::TupleIndex { span, .. } => span,
1148 }
1149 }
1150
1151 /// Get the base identifier of this expression.
1152 #[must_use]
1153 pub fn base_ident(&self) -> &Ident {
1154 match self {
1155 InterpExpr::Ident(ident) => ident,
1156 InterpExpr::FieldAccess { base, .. } => base.base_ident(),
1157 InterpExpr::TupleIndex { base, .. } => base.base_ident(),
1158 }
1159 }
1160}
1161
1162impl fmt::Display for InterpExpr {
1163 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1164 match self {
1165 InterpExpr::Ident(ident) => write!(f, "{}", ident.name),
1166 InterpExpr::FieldAccess { base, field, .. } => {
1167 write!(f, "{}.{}", base, field.name)
1168 }
1169 InterpExpr::TupleIndex { base, index, .. } => {
1170 write!(f, "{}.{}", base, index)
1171 }
1172 }
1173 }
1174}
1175
1176// =============================================================================
1177// Tests
1178// =============================================================================
1179
1180#[cfg(test)]
1181mod tests {
1182 use super::*;
1183
1184 #[test]
1185 fn binop_precedence() {
1186 // Mul/Div > Add/Sub > Comparison > And > Or
1187 assert!(BinOp::Mul.precedence() > BinOp::Add.precedence());
1188 assert!(BinOp::Add.precedence() > BinOp::Lt.precedence());
1189 assert!(BinOp::Lt.precedence() > BinOp::And.precedence());
1190 assert!(BinOp::And.precedence() > BinOp::Or.precedence());
1191 }
1192
1193 #[test]
1194 fn binop_display() {
1195 assert_eq!(format!("{}", BinOp::Add), "+");
1196 assert_eq!(format!("{}", BinOp::Eq), "==");
1197 assert_eq!(format!("{}", BinOp::Concat), "++");
1198 assert_eq!(format!("{}", BinOp::And), "&&");
1199 }
1200
1201 #[test]
1202 fn unaryop_display() {
1203 assert_eq!(format!("{}", UnaryOp::Neg), "-");
1204 assert_eq!(format!("{}", UnaryOp::Not), "!");
1205 }
1206
1207 #[test]
1208 fn literal_display() {
1209 assert_eq!(format!("{}", Literal::Int(42)), "42");
1210 assert_eq!(format!("{}", Literal::Float(3.14)), "3.14");
1211 assert_eq!(format!("{}", Literal::Bool(true)), "true");
1212 assert_eq!(format!("{}", Literal::String("hello".into())), "\"hello\"");
1213 }
1214
1215 #[test]
1216 fn event_kind_display() {
1217 assert_eq!(format!("{}", EventKind::Start), "start");
1218 assert_eq!(format!("{}", EventKind::Stop), "stop");
1219
1220 let msg = EventKind::Message {
1221 param_name: Ident::dummy("msg"),
1222 param_ty: TypeExpr::String,
1223 };
1224 assert_eq!(format!("{msg}"), "message(msg: String)");
1225 }
1226
1227 #[test]
1228 fn string_template_literal() {
1229 let template = StringTemplate::literal("hello".into(), Span::dummy());
1230 assert!(!template.has_interpolations());
1231 assert_eq!(format!("{template}"), "\"hello\"");
1232 }
1233
1234 #[test]
1235 fn string_template_with_interpolation() {
1236 let template = StringTemplate {
1237 parts: vec![
1238 StringPart::Literal("Hello, ".into()),
1239 StringPart::Interpolation(InterpExpr::Ident(Ident::dummy("name"))),
1240 StringPart::Literal("!".into()),
1241 ],
1242 span: Span::dummy(),
1243 };
1244 assert!(template.has_interpolations());
1245 assert_eq!(format!("{template}"), "\"Hello, {name}!\"");
1246
1247 let interps: Vec<_> = template.interpolations().collect();
1248 assert_eq!(interps.len(), 1);
1249 assert_eq!(interps[0].base_ident().name, "name");
1250 }
1251
1252 #[test]
1253 fn expr_span() {
1254 let span = Span::dummy();
1255 let expr = Expr::Literal {
1256 value: Literal::Int(42),
1257 span: span.clone(),
1258 };
1259 assert_eq!(expr.span(), &span);
1260 }
1261
1262 #[test]
1263 fn stmt_span() {
1264 let span = Span::dummy();
1265 let stmt = Stmt::Return {
1266 value: None,
1267 span: span.clone(),
1268 };
1269 assert_eq!(stmt.span(), &span);
1270 }
1271}