Skip to main content

mq_lang/ast/
node.rs

1use super::{Program, TokenId};
2#[cfg(feature = "ast-json")]
3use crate::arena::ArenaId;
4use crate::{Ident, Shared, Token, arena::Arena, number::Number, range::Range, selector::Selector};
5#[cfg(feature = "ast-json")]
6use serde::{Deserialize, Serialize};
7use smallvec::SmallVec;
8use smol_str::SmolStr;
9use std::{
10    fmt::{self, Display, Formatter},
11    hash::{Hash, Hasher},
12};
13use thin_vec::ThinVec;
14
15/// Represents a function parameter with an optional default value
16#[cfg_attr(feature = "ast-json", derive(Serialize, Deserialize))]
17#[derive(PartialEq, PartialOrd, Debug, Clone)]
18pub struct Param {
19    pub ident: IdentWithToken,
20    pub default: Option<Shared<Node>>,
21    pub is_variadic: bool,
22}
23
24impl Display for Param {
25    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
26        if self.is_variadic {
27            write!(f, "*{}", self.ident)
28        } else {
29            write!(f, "{}", self.ident)
30        }
31    }
32}
33
34impl Param {
35    pub fn new(name: IdentWithToken) -> Self {
36        Self::with_default(name, None)
37    }
38
39    pub fn with_default(name: IdentWithToken, default_value: Option<Shared<Node>>) -> Self {
40        Self {
41            ident: name,
42            default: default_value,
43            is_variadic: false,
44        }
45    }
46
47    /// Creates a variadic parameter (e.g., `*args`)
48    pub fn variadic(name: IdentWithToken) -> Self {
49        Self {
50            ident: name,
51            default: None,
52            is_variadic: true,
53        }
54    }
55}
56
57/// Function parameters.
58pub type Params = ThinVec<Param>;
59pub type Args = SmallVec<[Shared<Node>; 2]>;
60pub type Cond = (Option<Shared<Node>>, Shared<Node>);
61pub type Branches = ThinVec<Cond>;
62pub type MatchArms = ThinVec<MatchArm>;
63
64/// An AST node: an expression plus the id of the token it was parsed from.
65#[derive(PartialEq, PartialOrd, Debug, Clone)]
66#[cfg_attr(feature = "ast-json", derive(Serialize, Deserialize))]
67pub struct Node {
68    /// Id of the node's main token in the token arena.
69    #[cfg_attr(
70        feature = "ast-json",
71        serde(skip_serializing, skip_deserializing, default = "default_token_id")
72    )]
73    pub token_id: TokenId,
74    /// The expression this node holds.
75    pub expr: Expr,
76}
77
78#[cfg(feature = "ast-json")]
79fn default_token_id() -> TokenId {
80    ArenaId::new(0)
81}
82
83impl Node {
84    /// Serializes the node to pretty-printed JSON.
85    #[cfg(feature = "ast-json")]
86    pub fn to_json(&self) -> Result<String, serde_json::Error> {
87        serde_json::to_string_pretty(self)
88    }
89
90    /// Deserializes a node from JSON; token ids are not restored.
91    #[cfg(feature = "ast-json")]
92    pub fn from_json(json_str: &str) -> Result<Self, serde_json::Error> {
93        serde_json::from_str(json_str)
94    }
95
96    /// Source range of the node, computed from its token and children.
97    pub fn range(&self, arena: Shared<Arena<Token>>) -> Range {
98        match &self.expr {
99            Expr::Block(program)
100            | Expr::Def(_, _, program)
101            | Expr::Fn(_, program)
102            | Expr::While(_, program)
103            | Expr::Until(_, program)
104            | Expr::Loop(program)
105            | Expr::Module(_, program)
106            | Expr::Foreach(_, _, program) => {
107                let start = program
108                    .first()
109                    .map(|node| node.range(Shared::clone(&arena)).start)
110                    .unwrap_or_default();
111                let end = program
112                    .last()
113                    .map(|node| node.range(Shared::clone(&arena)).end)
114                    .unwrap_or_default();
115                Range { start, end }
116            }
117            Expr::Call(_, args) | Expr::Array(args) | Expr::Dict(args) => {
118                let start = args
119                    .first()
120                    .map(|node| node.range(Shared::clone(&arena)).start)
121                    .unwrap_or_default();
122                let end = args
123                    .last()
124                    .map(|node| node.range(Shared::clone(&arena)).end)
125                    .unwrap_or_default();
126                Range { start, end }
127            }
128            Expr::CallDynamic(callable, args) => {
129                let start = callable.range(Shared::clone(&arena)).start;
130                let end = args
131                    .last()
132                    .map(|node| node.range(Shared::clone(&arena)).end)
133                    .unwrap_or_else(|| callable.range(Shared::clone(&arena)).end);
134                Range { start, end }
135            }
136            Expr::As(_, node)
137            | Expr::Let(_, node)
138            | Expr::Var(_, node)
139            | Expr::Assign(_, node)
140            | Expr::IndexAssign(_, _, node)
141            | Expr::PathAssign(_, _, node) => node.range(Shared::clone(&arena)),
142            Expr::If(nodes) | Expr::Unless(nodes) => {
143                if let (Some(first), Some(last)) = (nodes.first(), nodes.last()) {
144                    let start = first.1.range(Shared::clone(&arena));
145                    let end = last.1.range(Shared::clone(&arena));
146                    Range {
147                        start: start.start,
148                        end: end.end,
149                    }
150                } else {
151                    // Fallback to token range if no branches exist
152                    arena[self.token_id].range
153                }
154            }
155            Expr::Match(value, arms) => {
156                let start = value.range(Shared::clone(&arena)).start;
157                let end = arms
158                    .last()
159                    .map(|arm| arm.body.range(Shared::clone(&arena)).end)
160                    .unwrap_or_else(|| arena[self.token_id].range.end);
161                Range { start, end }
162            }
163            Expr::Paren(node) => node.range(Shared::clone(&arena)),
164            Expr::Try(try_expr, _, catch_expr) => {
165                let start = try_expr.range(Shared::clone(&arena)).start;
166                let end = catch_expr.range(Shared::clone(&arena)).end;
167                Range { start, end }
168            }
169            Expr::And(exprs) | Expr::Or(exprs) => {
170                if let (Some(first), Some(last)) = (exprs.first(), exprs.last()) {
171                    Range {
172                        start: first.range(Shared::clone(&arena)).start,
173                        end: last.range(Shared::clone(&arena)).end,
174                    }
175                } else {
176                    arena[self.token_id].range
177                }
178            }
179            Expr::Index(target, index) => Range {
180                start: target.range(Shared::clone(&arena)).start,
181                end: index.range(Shared::clone(&arena)).end,
182            },
183            Expr::Slice(target, start, end) => Range {
184                start: target.range(Shared::clone(&arena)).start,
185                end: end.as_ref().unwrap_or(start).range(Shared::clone(&arena)).end,
186            },
187            Expr::BinaryOp(_, lhs, rhs) => Range {
188                start: lhs.range(Shared::clone(&arena)).start,
189                end: rhs.range(Shared::clone(&arena)).end,
190            },
191            Expr::UnaryOp(_, operand) => Range {
192                start: arena[self.token_id].range.start,
193                end: operand.range(Shared::clone(&arena)).end,
194            },
195            Expr::Break(Some(value_node)) | Expr::Yield(Some(value_node)) => {
196                let start = arena[self.token_id].range.start;
197                let end = value_node.range(Shared::clone(&arena)).end;
198                Range { start, end }
199            }
200            Expr::SelectorCall(_, args) => {
201                let start = arena[self.token_id].range.start;
202                let end = args
203                    .last()
204                    .map(|node| node.range(Shared::clone(&arena)).end)
205                    .unwrap_or_else(|| arena[self.token_id].range.end);
206                Range { start, end }
207            }
208            Expr::Literal(_)
209            | Expr::Ident(_)
210            | Expr::Env(_)
211            | Expr::Selector(_)
212            | Expr::Include(_)
213            | Expr::Import(_, _)
214            | Expr::InterpolatedString(_)
215            | Expr::QualifiedAccess(_, _)
216            | Expr::Nodes
217            | Expr::Self_
218            | Expr::Break(None)
219            | Expr::Continue
220            | Expr::Yield(None) => arena[self.token_id].range,
221        }
222    }
223
224    /// Whether this node is the `nodes` keyword.
225    pub fn is_nodes(&self) -> bool {
226        matches!(&self.expr, Expr::Nodes)
227    }
228}
229
230/// An identifier paired with the token it was parsed from.
231#[cfg_attr(feature = "ast-json", derive(Serialize, Deserialize))]
232#[derive(PartialEq, Debug, Eq, Clone)]
233pub struct IdentWithToken {
234    /// The identifier name.
235    pub name: Ident,
236    /// Id of the identifier token, if known.
237    #[cfg_attr(feature = "ast-json", serde(skip_serializing, skip_deserializing, default))]
238    pub token: Option<TokenId>,
239}
240
241impl Hash for IdentWithToken {
242    fn hash<H: Hasher>(&self, state: &mut H) {
243        self.name.hash(state);
244    }
245}
246
247impl Ord for IdentWithToken {
248    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
249        self.name.cmp(&other.name)
250    }
251}
252
253impl PartialOrd for IdentWithToken {
254    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
255        Some(self.cmp(other))
256    }
257}
258
259impl IdentWithToken {
260    /// Creates an identifier with no token.
261    pub fn new(name: &str) -> Self {
262        Self::new_with_token(name, None)
263    }
264
265    /// Creates an identifier bound to `token`.
266    pub fn new_with_token(name: &str, token: Option<TokenId>) -> Self {
267        Self {
268            name: name.into(),
269            token,
270        }
271    }
272}
273
274impl Display for IdentWithToken {
275    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
276        write!(f, "{}", self.name)
277    }
278}
279
280#[cfg_attr(feature = "ast-json", derive(Serialize, Deserialize))]
281#[derive(Debug, Clone, PartialOrd, PartialEq)]
282pub enum StringSegment {
283    Text(String),
284    Expr(Shared<Node>),
285    Env(SmolStr),
286    Self_,
287}
288
289/// A pattern used by `match`, `let` and `var`.
290#[cfg_attr(feature = "ast-json", derive(Serialize, Deserialize))]
291#[derive(PartialEq, PartialOrd, Debug, Clone)]
292pub enum Pattern {
293    /// A literal value.
294    Literal(Box<Literal>),
295    /// Binds the matched value to a name.
296    Ident(IdentWithToken),
297    /// `_`, matches anything.
298    Wildcard,
299    /// `[p1, p2]`, matches an array element-wise.
300    Array(ThinVec<Pattern>),
301    /// Array pattern with a rest binding: the patterns before `..` and the rest binding.
302    ArrayRest(ThinVec<Pattern>, IdentWithToken), // patterns before .., rest binding
303    /// `{key: pattern}`, matches a dict by key.
304    Dict(ThinVec<(IdentWithToken, Pattern)>),
305    /// A type pattern such as `:string` or `:number`.
306    Type(Ident), // :string, :number, etc.
307    /// `p1 || p2`, matches if any alternative matches.
308    Or(ThinVec<Pattern>), // p1 || p2 || p3
309}
310
311#[cfg_attr(feature = "ast-json", derive(Serialize, Deserialize))]
312#[derive(PartialEq, PartialOrd, Debug, Clone)]
313pub struct MatchArm {
314    pub pattern: Pattern,
315    pub guard: Option<Shared<Node>>,
316    pub body: Shared<Node>,
317}
318
319/// A literal value.
320#[cfg_attr(feature = "ast-json", derive(Serialize, Deserialize))]
321#[derive(PartialEq, PartialOrd, Debug, Clone)]
322pub enum Literal {
323    /// A string literal.
324    String(Box<str>),
325    /// A bytes literal.
326    Bytes(Box<[u8]>),
327    /// A number literal.
328    Number(Number),
329    /// A `:name` symbol.
330    Symbol(Ident),
331    /// A boolean literal.
332    Bool(bool),
333    /// The `None` literal.
334    None,
335}
336
337impl From<&str> for Literal {
338    fn from(s: &str) -> Self {
339        Literal::String(s.into())
340    }
341}
342
343#[cfg_attr(feature = "ast-json", derive(Serialize, Deserialize))]
344#[derive(PartialEq, PartialOrd, Debug, Clone)]
345pub enum AccessTarget {
346    Call(IdentWithToken, Box<Args>),
347    Ident(IdentWithToken),
348}
349
350impl Display for Literal {
351    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
352        match self {
353            Literal::String(s) => write!(f, "{}", s),
354            Literal::Bytes(b) => {
355                write!(f, "b\"")?;
356                for byte in b {
357                    if byte.is_ascii_graphic() && *byte != b'"' && *byte != b'\\' {
358                        write!(f, "{}", *byte as char)?;
359                    } else {
360                        write!(f, "\\x{:02x}", byte)?;
361                    }
362                }
363                write!(f, "\"")
364            }
365            Literal::Number(n) => write!(f, "{}", n),
366            Literal::Symbol(i) => write!(f, "{}", i),
367            Literal::Bool(b) => write!(f, "{}", b),
368            Literal::None => write!(f, "none"),
369        }
370    }
371}
372
373/// A binary arithmetic or comparison operator (`+ - * / % == != < <= > >=`).
374/// Compiles directly to a VM opcode; see `Expr::BinaryOp`.
375#[cfg_attr(feature = "ast-json", derive(Serialize, Deserialize))]
376#[derive(PartialEq, PartialOrd, Debug, Clone, Copy)]
377pub enum BinaryOp {
378    /// `+`
379    Add,
380    /// `-`
381    Sub,
382    /// `*`
383    Mul,
384    /// `/`
385    Div,
386    /// `%`
387    Mod,
388    /// `==`
389    Eq,
390    /// `!=`
391    Ne,
392    /// `<`
393    Lt,
394    /// `<=`
395    Le,
396    /// `>`
397    Gt,
398    /// `>=`
399    Ge,
400}
401
402impl BinaryOp {
403    /// The operator as written in source.
404    pub fn as_str(self) -> &'static str {
405        match self {
406            Self::Add => "+",
407            Self::Sub => "-",
408            Self::Mul => "*",
409            Self::Div => "/",
410            Self::Mod => "%",
411            Self::Eq => "==",
412            Self::Ne => "!=",
413            Self::Lt => "<",
414            Self::Le => "<=",
415            Self::Gt => ">",
416            Self::Ge => ">=",
417        }
418    }
419}
420
421impl Display for BinaryOp {
422    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
423        write!(f, "{}", self.as_str())
424    }
425}
426
427/// A prefix operator (`!` or `-`). Compiles directly to a VM opcode; see `Expr::UnaryOp`.
428#[cfg_attr(feature = "ast-json", derive(Serialize, Deserialize))]
429#[derive(PartialEq, PartialOrd, Debug, Clone, Copy)]
430pub enum UnaryOp {
431    /// `!`
432    Not,
433    /// `-`
434    Neg,
435}
436
437impl UnaryOp {
438    /// The operator as written in source.
439    pub fn as_str(self) -> &'static str {
440        match self {
441            Self::Not => "!",
442            Self::Neg => "-",
443        }
444    }
445}
446
447impl Display for UnaryOp {
448    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
449        write!(f, "{}", self.as_str())
450    }
451}
452
453/// An expression in the AST.
454#[cfg_attr(feature = "ast-json", derive(Serialize, Deserialize))]
455#[derive(PartialEq, PartialOrd, Debug, Clone)]
456pub enum Expr {
457    /// `expr as name`, binding the value of the expression.
458    As(IdentWithToken, Shared<Node>),
459    /// A `do ... end` block or pipeline group.
460    Block(Program),
461    /// A call to a named function.
462    Call(IdentWithToken, Args),
463    /// `lhs op rhs`. Never desugared into `Call`, so it compiles to a direct VM opcode
464    /// regardless of name resolution/shadowing.
465    BinaryOp(BinaryOp, Shared<Node>, Shared<Node>),
466    /// `target[index]`. Never desugared into `Call`, so a user `def get` cannot capture it.
467    Index(Shared<Node>, Shared<Node>),
468    /// `target[start:end]`; `end` is `None` for an open-ended `target[start:]`. Never desugared
469    /// into `Call`, so a user `def slice` cannot capture it.
470    Slice(Shared<Node>, Shared<Node>, Option<Shared<Node>>),
471    /// `!operand` / `-operand`. Never desugared into `Call`, so it compiles to a direct VM
472    /// opcode regardless of name resolution/shadowing.
473    UnaryOp(UnaryOp, Shared<Node>),
474    /// An `[...]` array literal. Each spread element (`...expr`) remains a nested
475    /// `Call` on `constants::builtins::SPREAD`.
476    Array(Args),
477    /// A `{...}` dict literal. Each entry is a nested `Array` of `[key, value]`,
478    /// except spread entries (`...expr`), which remain a nested `Call` on `SPREAD`.
479    Dict(Args),
480    /// A call whose callee is an arbitrary expression.
481    CallDynamic(Shared<Node>, Args),
482    /// A named function definition.
483    Def(IdentWithToken, Params, Program),
484    /// An anonymous function.
485    Fn(Params, Program),
486    /// An immutable binding.
487    Let(Pattern, Shared<Node>),
488    /// An unbounded `loop`.
489    Loop(Program),
490    /// A mutable binding.
491    Var(Pattern, Shared<Node>),
492    /// Assignment to an existing variable.
493    Assign(IdentWithToken, Shared<Node>),
494    /// `ident[index] = value`: sets one element of the variable's array or dict. Never desugared
495    /// into `Assign(ident, set(ident, ..))`, so the VM can update the variable in place.
496    IndexAssign(IdentWithToken, Shared<Node>, Shared<Node>),
497    /// `ident[k1][k2]... = value` with at least two keys. Each key is evaluated once, left to
498    /// right, so the VM can update the nested containers in place.
499    PathAssign(IdentWithToken, ThinVec<Shared<Node>>, Shared<Node>),
500    /// Short-circuiting `&&` over its operands.
501    And(ThinVec<Shared<Node>>),
502    /// Short-circuiting `||` over its operands.
503    Or(ThinVec<Shared<Node>>),
504    /// A literal value.
505    Literal(Literal),
506    /// A variable or function reference.
507    Ident(IdentWithToken),
508    /// An environment variable reference (`$NAME`), read when the program runs.
509    Env(SmolStr),
510    /// A string with `${...}` segments.
511    InterpolatedString(ThinVec<StringSegment>),
512    /// A Markdown selector such as `.h1`.
513    Selector(Selector),
514    /// A selector with runtime-evaluated arguments for filtered matching.
515    ///
516    /// Supports `.h(1..2)`, `.h(1, 2)`, `.code("rust")`, etc.
517    SelectorCall(Box<Selector>, Args),
518    /// A `while` loop.
519    While(Shared<Node>, Program),
520    /// An `until` loop.
521    Until(Shared<Node>, Program),
522    /// A `foreach` loop over a collection.
523    Foreach(IdentWithToken, Shared<Node>, Program),
524    /// Condition and body pairs; the final pair has no condition for `else`.
525    If(Branches),
526    /// Like `If`, with the first condition negated.
527    Unless(Branches),
528    /// A `match` on a value with its arms.
529    Match(Shared<Node>, MatchArms),
530    /// An `include` of another file.
531    Include(Literal),
532    /// `import "path"` or `import "path" as alias`; the alias rebinds the module name.
533    Import(Literal, Option<IdentWithToken>),
534    /// An inline module definition.
535    Module(IdentWithToken, Program),
536    /// `module::name` access: the module path and the accessed target.
537    QualifiedAccess(ThinVec<IdentWithToken>, AccessTarget),
538    /// The implicit `self` value.
539    Self_,
540    /// The `nodes` keyword.
541    Nodes,
542    /// A parenthesized expression.
543    Paren(Shared<Node>),
544    /// `try <expr> catch: <expr>` or `try <expr> catch(<binder>): <expr>`.
545    /// When present, `binder` is bound to a dict describing the failure (currently `{"message": ...}`)
546    /// while evaluating the catch expression.
547    Try(Shared<Node>, Option<IdentWithToken>, Shared<Node>),
548    /// `break`, with an optional value.
549    Break(Option<Shared<Node>>),
550    /// `continue`.
551    Continue,
552    /// `yield`, with an optional value.
553    Yield(Option<Shared<Node>>),
554}
555
556#[cfg(feature = "debugger")]
557impl Display for Expr {
558    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
559        match self {
560            Expr::Call(ident, args) => {
561                write!(f, "{}(", ident)?;
562                for (i, arg) in args.iter().enumerate() {
563                    if i > 0 {
564                        write!(f, ", ")?;
565                    }
566                    write!(f, "{}", arg.expr)?;
567                }
568                write!(f, ")")
569            }
570            Expr::CallDynamic(callable, args) => {
571                write!(f, "{}(", callable.expr)?;
572                for (i, arg) in args.iter().enumerate() {
573                    if i > 0 {
574                        write!(f, ", ")?;
575                    }
576                    write!(f, "{}", arg.expr)?;
577                }
578                write!(f, ")")
579            }
580            Expr::Literal(literal) => write!(f, "{}", literal),
581            Expr::Ident(ident) => write!(f, "{}", ident),
582            Expr::Self_ => write!(f, "self"),
583            Expr::Env(name) => write!(f, "${}", name),
584            _ => write!(f, ""),
585        }
586    }
587}
588
589#[cfg(test)]
590mod tests {
591    use super::*;
592    use crate::{Position, TokenKind, arena::ArenaId};
593    use rstest::rstest;
594    use smallvec::smallvec;
595    use thin_vec::thin_vec;
596
597    fn create_token(range: Range) -> Token {
598        Token {
599            range,
600            kind: TokenKind::Eof,
601            module_id: ArenaId::new(0),
602        }
603    }
604
605    #[rstest]
606    #[case(
607        Expr::CallDynamic(
608            Shared::new(Node {
609                token_id: ArenaId::new(1),
610                expr: Expr::Literal(Literal::String("callee".into())),
611            }),
612            smallvec![
613                Shared::new(Node {
614                    token_id: ArenaId::new(0),
615                    expr: Expr::Literal(Literal::String("arg1".into())),
616                }),
617                Shared::new(Node {
618                    token_id: ArenaId::new(1),
619                    expr: Expr::Literal(Literal::String("arg2".into())),
620                }),
621            ]
622        ),
623        vec![
624            (0, Range { start: Position::new(1, 1), end: Position::new(1, 5) }),
625            (1, Range { start: Position::new(2, 1), end: Position::new(2, 5) }),
626        ],
627        Range { start: Position::new(2, 1), end: Position::new(2, 5) }
628    )]
629    #[case(
630        Expr::Match(
631            Shared::new(Node {
632                token_id: ArenaId::new(0),
633                expr: Expr::Literal(Literal::String("val".into())),
634            }),
635            thin_vec![
636                MatchArm {
637                    pattern: Pattern::Literal(Box::new(Literal::String("a".into()))),
638                    guard: None,
639                    body: Shared::new(Node {
640                        token_id: ArenaId::new(1),
641                        expr: Expr::Literal(Literal::String("body1".into())),
642                    }),
643                },
644                MatchArm {
645                    pattern: Pattern::Literal(Box::new(Literal::String("b".into()))),
646                    guard: None,
647                    body: Shared::new(Node {
648                        token_id: ArenaId::new(2),
649                        expr: Expr::Literal(Literal::String("body2".into())),
650                    }),
651                },
652            ]
653        ),
654        vec![
655            (0, Range { start: Position::new(10, 1), end: Position::new(10, 5) }),
656            (1, Range { start: Position::new(11, 1), end: Position::new(11, 5) }),
657            (2, Range { start: Position::new(12, 1), end: Position::new(12, 5) }),
658        ],
659        Range { start: Position::new(10, 1), end: Position::new(12, 5) }
660    )]
661    #[case(
662        Expr::Try(
663            Shared::new(Node {
664                token_id: ArenaId::new(0),
665                expr: Expr::Literal(Literal::String("try".into())),
666            }),
667            None,
668            Shared::new(Node {
669                token_id: ArenaId::new(1),
670                expr: Expr::Literal(Literal::String("catch".into())),
671            })
672        ),
673        vec![
674            (0, Range { start: Position::new(20, 1), end: Position::new(20, 5) }),
675            (1, Range { start: Position::new(21, 1), end: Position::new(21, 5) }),
676        ],
677        Range { start: Position::new(20, 1), end: Position::new(21, 5) }
678    )]
679    #[case(
680        Expr::Let(
681            Pattern::Ident(IdentWithToken::new("x")),
682            Shared::new(Node {
683                token_id: ArenaId::new(0),
684                expr: Expr::Literal(Literal::String("letval".into())),
685            })
686        ),
687        vec![
688            (0, Range { start: Position::new(30, 1), end: Position::new(30, 5) }),
689        ],
690        Range { start: Position::new(30, 1), end: Position::new(30, 5) }
691    )]
692    #[case(
693        Expr::Paren(
694            Shared::new(Node {
695                token_id: ArenaId::new(0),
696                expr: Expr::Literal(Literal::String("paren".into())),
697            })
698        ),
699        vec![
700            (0, Range { start: Position::new(40, 1), end: Position::new(40, 5) }),
701        ],
702        Range { start: Position::new(40, 1), end: Position::new(40, 5) }
703    )]
704    #[case(
705        Expr::Block(thin_vec![
706            Shared::new(Node {
707                token_id: ArenaId::new(0),
708                expr: Expr::Literal(Literal::String("block1".into())),
709            }),
710            Shared::new(Node {
711                token_id: ArenaId::new(1),
712                expr: Expr::Literal(Literal::String("block2".into())),
713            }),
714        ]),
715        vec![
716            (0, Range { start: Position::new(50, 1), end: Position::new(50, 5) }),
717            (1, Range { start: Position::new(51, 1), end: Position::new(51, 5) }),
718        ],
719        Range { start: Position::new(50, 1), end: Position::new(51, 5) }
720    )]
721    #[case(
722        Expr::Def(
723            IdentWithToken::new("f"),
724            thin_vec![],
725            thin_vec![
726                Shared::new(Node {
727                    token_id: ArenaId::new(0),
728                    expr: Expr::Literal(Literal::String("def1".into())),
729                }),
730                Shared::new(Node {
731                    token_id: ArenaId::new(1),
732                    expr: Expr::Literal(Literal::String("def2".into())),
733                }),
734            ]
735        ),
736        vec![
737            (0, Range { start: Position::new(60, 1), end: Position::new(60, 5) }),
738            (1, Range { start: Position::new(61, 1), end: Position::new(61, 5) }),
739        ],
740        Range { start: Position::new(60, 1), end: Position::new(61, 5) }
741    )]
742    #[case(
743        Expr::Fn(
744            thin_vec![],
745            thin_vec![
746                Shared::new(Node {
747                    token_id: ArenaId::new(0),
748                    expr: Expr::Literal(Literal::String("fn1".into())),
749                }),
750                Shared::new(Node {
751                    token_id: ArenaId::new(1),
752                    expr: Expr::Literal(Literal::String("fn2".into())),
753                }),
754            ]
755        ),
756        vec![
757            (0, Range { start: Position::new(70, 1), end: Position::new(70, 5) }),
758            (1, Range { start: Position::new(71, 1), end: Position::new(71, 5) }),
759        ],
760        Range { start: Position::new(70, 1), end: Position::new(71, 5) }
761    )]
762    #[case(
763        Expr::While(
764            Shared::new(Node {
765                token_id: ArenaId::new(0),
766                expr: Expr::Literal(Literal::String("cond".into())),
767            }),
768            thin_vec![
769                Shared::new(Node {
770                    token_id: ArenaId::new(1),
771                    expr: Expr::Literal(Literal::String("while1".into())),
772                }),
773                Shared::new(Node {
774                    token_id: ArenaId::new(2),
775                    expr: Expr::Literal(Literal::String("while2".into())),
776                }),
777            ]
778        ),
779        vec![
780            (0, Range { start: Position::new(81, 1), end: Position::new(81, 5) }),
781            (1, Range { start: Position::new(82, 1), end: Position::new(82, 5) }),
782            (2, Range { start: Position::new(82, 1), end: Position::new(82, 5) }),
783        ],
784        Range { start: Position::new(82, 1), end: Position::new(82, 5) }
785    )]
786    #[case(
787        Expr::Until(
788            Shared::new(Node {
789                token_id: ArenaId::new(0),
790                expr: Expr::Literal(Literal::String("cond".into())),
791            }),
792            thin_vec![
793                Shared::new(Node {
794                    token_id: ArenaId::new(1),
795                    expr: Expr::Literal(Literal::String("until1".into())),
796                }),
797                Shared::new(Node {
798                    token_id: ArenaId::new(2),
799                    expr: Expr::Literal(Literal::String("until2".into())),
800                }),
801            ]
802        ),
803        vec![
804            (0, Range { start: Position::new(83, 1), end: Position::new(83, 5) }),
805            (1, Range { start: Position::new(84, 1), end: Position::new(84, 5) }),
806            (2, Range { start: Position::new(84, 1), end: Position::new(84, 5) }),
807        ],
808        Range { start: Position::new(84, 1), end: Position::new(84, 5) }
809    )]
810    #[case(
811        Expr::Foreach(
812            IdentWithToken::new("item"),
813            Shared::new(Node {
814                token_id: ArenaId::new(0),
815                expr: Expr::Literal(Literal::String("iter".into())),
816            }),
817            thin_vec![
818                Shared::new(Node {
819                    token_id: ArenaId::new(1),
820                    expr: Expr::Literal(Literal::String("foreach1".into())),
821                }),
822                Shared::new(Node {
823                    token_id: ArenaId::new(2),
824                    expr: Expr::Literal(Literal::String("foreach2".into())),
825                }),
826            ]
827        ),
828        vec![
829            (0, Range { start: Position::new(101, 1), end: Position::new(101, 5) }),
830            (1, Range { start: Position::new(102, 1), end: Position::new(102, 5) }),
831            (2, Range { start: Position::new(102, 1), end: Position::new(102, 5) }),
832        ],
833        Range { start: Position::new(102, 1), end: Position::new(102, 5) }
834    )]
835    #[case(
836        Expr::If(thin_vec![
837            (
838                Some(Shared::new(Node {
839                    token_id: ArenaId::new(0),
840                    expr: Expr::Literal(Literal::String("cond1".into())),
841                })),
842                Shared::new(Node {
843                    token_id: ArenaId::new(1),
844                    expr: Expr::Literal(Literal::String("if1".into())),
845                })
846            ),
847            (
848                Some(Shared::new(Node {
849                    token_id: ArenaId::new(2),
850                    expr: Expr::Literal(Literal::String("cond2".into())),
851                })),
852                Shared::new(Node {
853                    token_id: ArenaId::new(3),
854                    expr: Expr::Literal(Literal::String("if2".into())),
855                })
856            ),
857        ]),
858        vec![
859            (0, Range { start: Position::new(111, 1), end: Position::new(111, 5) }),
860            (1, Range { start: Position::new(113, 1), end: Position::new(113, 5) }),
861            (2, Range { start: Position::new(114, 1), end: Position::new(115, 5) }),
862            (3, Range { start: Position::new(116, 1), end: Position::new(117, 5) }),
863        ],
864        Range { start: Position::new(113, 1), end: Position::new(117, 5) }
865    )]
866    #[case(
867        Expr::Unless(thin_vec![
868            (
869                Some(Shared::new(Node {
870                    token_id: ArenaId::new(0),
871                    expr: Expr::Literal(Literal::String("cond1".into())),
872                })),
873                Shared::new(Node {
874                    token_id: ArenaId::new(1),
875                    expr: Expr::Literal(Literal::String("unless1".into())),
876                })
877            ),
878        ]),
879        vec![
880            (0, Range { start: Position::new(121, 1), end: Position::new(121, 5) }),
881            (1, Range { start: Position::new(123, 1), end: Position::new(123, 5) }),
882        ],
883        Range { start: Position::new(123, 1), end: Position::new(123, 5) }
884    )]
885    #[case(
886        Expr::Call(
887            IdentWithToken::new("func"),
888            smallvec![
889                Shared::new(Node {
890                    token_id: ArenaId::new(0),
891                    expr: Expr::Literal(Literal::String("arg1".into())),
892                }),
893                Shared::new(Node {
894                    token_id: ArenaId::new(1),
895                    expr: Expr::Literal(Literal::String("arg2".into())),
896                }),
897            ]
898        ),
899        vec![
900            (0, Range { start: Position::new(120, 1), end: Position::new(120, 5) }),
901            (1, Range { start: Position::new(121, 1), end: Position::new(121, 5) }),
902        ],
903        Range { start: Position::new(120, 1), end: Position::new(121, 5) }
904    )]
905    fn test_node_range_various_exprs(
906        #[case] expr: Expr,
907        #[case] token_ranges: Vec<(usize, Range)>,
908        #[case] expected: Range,
909    ) {
910        let mut arena = Arena::new(150);
911        for (_, range) in &token_ranges {
912            let token = create_token(*range);
913            let _ = arena.alloc(token);
914        }
915        let node = Node {
916            token_id: ArenaId::new(0),
917            expr,
918        };
919        assert_eq!(node.range(Shared::new(arena)), expected);
920    }
921
922    fn make_node(token_id: u32) -> Shared<Node> {
923        Shared::new(Node {
924            token_id: ArenaId::new(token_id),
925            expr: Expr::Literal(Literal::None),
926        })
927    }
928
929    fn single_token_arena(range: Range) -> Shared<Arena<Token>> {
930        let mut arena = Arena::new(10);
931        arena.alloc(create_token(range));
932        Shared::new(arena)
933    }
934
935    #[test]
936    fn test_range_loop_uses_program() {
937        let r0 = Range {
938            start: Position::new(1, 1),
939            end: Position::new(1, 5),
940        };
941        let r1 = Range {
942            start: Position::new(2, 1),
943            end: Position::new(2, 5),
944        };
945        let mut arena = Arena::new(10);
946        arena.alloc(create_token(r0));
947        arena.alloc(create_token(r1));
948        let expr = Expr::Loop(thin_vec![make_node(0), make_node(1)]);
949        let node = Node {
950            token_id: ArenaId::new(0),
951            expr,
952        };
953        let got = node.range(Shared::new(arena));
954        assert_eq!(got.start, r0.start);
955        assert_eq!(got.end, r1.end);
956    }
957
958    #[test]
959    fn test_range_module_uses_program() {
960        let r0 = Range {
961            start: Position::new(10, 1),
962            end: Position::new(10, 5),
963        };
964        let r1 = Range {
965            start: Position::new(11, 1),
966            end: Position::new(11, 5),
967        };
968        let mut arena = Arena::new(10);
969        arena.alloc(create_token(r0));
970        arena.alloc(create_token(r1));
971        let expr = Expr::Module(IdentWithToken::new("m"), thin_vec![make_node(0), make_node(1)]);
972        let node = Node {
973            token_id: ArenaId::new(0),
974            expr,
975        };
976        let got = node.range(Shared::new(arena));
977        assert_eq!(got.start, r0.start);
978        assert_eq!(got.end, r1.end);
979    }
980
981    #[test]
982    fn test_range_empty_block_uses_default() {
983        let r0 = Range {
984            start: Position::new(5, 1),
985            end: Position::new(5, 5),
986        };
987        let arena = single_token_arena(r0);
988        let expr = Expr::Block(thin_vec![]);
989        let node = Node {
990            token_id: ArenaId::new(0),
991            expr,
992        };
993        let got = node.range(arena);
994        assert_eq!(got, Range::default());
995    }
996
997    #[test]
998    fn test_range_as_delegates_to_inner() {
999        let r0 = Range {
1000            start: Position::new(20, 1),
1001            end: Position::new(20, 8),
1002        };
1003        let arena = single_token_arena(r0);
1004        let expr = Expr::As(IdentWithToken::new("x"), make_node(0));
1005        let node = Node {
1006            token_id: ArenaId::new(0),
1007            expr,
1008        };
1009        assert_eq!(node.range(arena), r0);
1010    }
1011
1012    #[test]
1013    fn test_range_var_delegates_to_inner() {
1014        let r0 = Range {
1015            start: Position::new(21, 1),
1016            end: Position::new(21, 8),
1017        };
1018        let arena = single_token_arena(r0);
1019        let expr = Expr::Var(Pattern::Wildcard, make_node(0));
1020        let node = Node {
1021            token_id: ArenaId::new(0),
1022            expr,
1023        };
1024        assert_eq!(node.range(arena), r0);
1025    }
1026
1027    #[test]
1028    fn test_range_assign_delegates_to_inner() {
1029        let r0 = Range {
1030            start: Position::new(22, 1),
1031            end: Position::new(22, 8),
1032        };
1033        let arena = single_token_arena(r0);
1034        let expr = Expr::Assign(IdentWithToken::new("v"), make_node(0));
1035        let node = Node {
1036            token_id: ArenaId::new(0),
1037            expr,
1038        };
1039        assert_eq!(node.range(arena), r0);
1040    }
1041
1042    #[test]
1043    fn test_range_and_empty_falls_back_to_token() {
1044        let r0 = Range {
1045            start: Position::new(30, 1),
1046            end: Position::new(30, 5),
1047        };
1048        let arena = single_token_arena(r0);
1049        let expr = Expr::And(thin_vec![]);
1050        let node = Node {
1051            token_id: ArenaId::new(0),
1052            expr,
1053        };
1054        assert_eq!(node.range(arena), r0);
1055    }
1056
1057    #[test]
1058    fn test_range_or_empty_falls_back_to_token() {
1059        let r0 = Range {
1060            start: Position::new(31, 1),
1061            end: Position::new(31, 5),
1062        };
1063        let arena = single_token_arena(r0);
1064        let expr = Expr::Or(thin_vec![]);
1065        let node = Node {
1066            token_id: ArenaId::new(0),
1067            expr,
1068        };
1069        assert_eq!(node.range(arena), r0);
1070    }
1071
1072    #[test]
1073    fn test_range_unary_op_spans_operator_and_operand() {
1074        let r0 = Range {
1075            start: Position::new(40, 1),
1076            end: Position::new(40, 2),
1077        };
1078        let r1 = Range {
1079            start: Position::new(40, 2),
1080            end: Position::new(40, 6),
1081        };
1082        let mut arena = Arena::new(10);
1083        arena.alloc(create_token(r0));
1084        arena.alloc(create_token(r1));
1085        let node = Node {
1086            token_id: ArenaId::new(0),
1087            expr: Expr::UnaryOp(UnaryOp::Not, make_node(1)),
1088        };
1089        let got = node.range(Shared::new(arena));
1090        assert_eq!(got.start, r0.start);
1091        assert_eq!(got.end, r1.end);
1092    }
1093
1094    #[test]
1095    fn test_range_and_non_empty() {
1096        let r0 = Range {
1097            start: Position::new(40, 1),
1098            end: Position::new(40, 5),
1099        };
1100        let r1 = Range {
1101            start: Position::new(41, 1),
1102            end: Position::new(41, 5),
1103        };
1104        let mut arena = Arena::new(10);
1105        arena.alloc(create_token(r0));
1106        arena.alloc(create_token(r1));
1107        let expr = Expr::And(thin_vec![make_node(0), make_node(1)]);
1108        let node = Node {
1109            token_id: ArenaId::new(0),
1110            expr,
1111        };
1112        let got = node.range(Shared::new(arena));
1113        assert_eq!(got.start, r0.start);
1114        assert_eq!(got.end, r1.end);
1115    }
1116
1117    #[test]
1118    fn test_range_break_with_value() {
1119        let r0 = Range {
1120            start: Position::new(50, 1),
1121            end: Position::new(50, 3),
1122        };
1123        let r1 = Range {
1124            start: Position::new(50, 5),
1125            end: Position::new(50, 8),
1126        };
1127        let mut arena = Arena::new(10);
1128        arena.alloc(create_token(r0));
1129        arena.alloc(create_token(r1));
1130        let expr = Expr::Break(Some(make_node(1)));
1131        let node = Node {
1132            token_id: ArenaId::new(0),
1133            expr,
1134        };
1135        let got = node.range(Shared::new(arena));
1136        assert_eq!(got.start, r0.start);
1137        assert_eq!(got.end, r1.end);
1138    }
1139
1140    #[test]
1141    fn test_range_selector_call_with_args() {
1142        use crate::selector::Selector;
1143        let r0 = Range {
1144            start: Position::new(60, 1),
1145            end: Position::new(60, 3),
1146        };
1147        let r1 = Range {
1148            start: Position::new(60, 4),
1149            end: Position::new(60, 6),
1150        };
1151        let mut arena = Arena::new(10);
1152        arena.alloc(create_token(r0));
1153        arena.alloc(create_token(r1));
1154        let expr = Expr::SelectorCall(Box::new(Selector::Heading(None)), smallvec![make_node(1)]);
1155        let node = Node {
1156            token_id: ArenaId::new(0),
1157            expr,
1158        };
1159        let got = node.range(Shared::new(arena));
1160        assert_eq!(got.start, r0.start);
1161        assert_eq!(got.end, r1.end);
1162    }
1163
1164    #[test]
1165    fn test_range_terminal_exprs_use_token() {
1166        let r0 = Range {
1167            start: Position::new(70, 1),
1168            end: Position::new(70, 5),
1169        };
1170
1171        for expr in [
1172            Expr::Literal(Literal::None),
1173            Expr::Nodes,
1174            Expr::Self_,
1175            Expr::Break(None),
1176            Expr::Continue,
1177        ] {
1178            let arena = single_token_arena(r0);
1179            let node = Node {
1180                token_id: ArenaId::new(0),
1181                expr,
1182            };
1183            assert_eq!(node.range(arena), r0, "terminal expr should use token range");
1184        }
1185    }
1186
1187    #[test]
1188    fn test_range_call_empty_args_is_default() {
1189        let r0 = Range {
1190            start: Position::new(1, 1),
1191            end: Position::new(1, 5),
1192        };
1193        let arena = single_token_arena(r0);
1194        let expr = Expr::Call(IdentWithToken::new("f"), smallvec![]);
1195        let node = Node {
1196            token_id: ArenaId::new(0),
1197            expr,
1198        };
1199        assert_eq!(node.range(arena), Range::default());
1200    }
1201
1202    #[test]
1203    fn test_is_nodes() {
1204        let r = Range::default();
1205        let arena = single_token_arena(r);
1206        let nodes_node = Node {
1207            token_id: ArenaId::new(0),
1208            expr: Expr::Nodes,
1209        };
1210        assert!(nodes_node.is_nodes());
1211        let other = Node {
1212            token_id: ArenaId::new(0),
1213            expr: Expr::Self_,
1214        };
1215        assert!(!other.is_nodes());
1216        let _ = arena;
1217    }
1218
1219    #[test]
1220    fn test_param_new_and_display() {
1221        let p = Param::new(IdentWithToken::new("x"));
1222        assert_eq!(p.to_string(), "x");
1223        assert!(!p.is_variadic);
1224        assert!(p.default.is_none());
1225    }
1226
1227    #[test]
1228    fn test_param_variadic_display() {
1229        let p = Param::variadic(IdentWithToken::new("args"));
1230        assert!(p.is_variadic);
1231        assert_eq!(p.to_string(), "*args");
1232    }
1233
1234    #[test]
1235    fn test_param_with_default() {
1236        let default_node = make_node(0);
1237        let p = Param::with_default(IdentWithToken::new("x"), Some(default_node));
1238        assert!(p.default.is_some());
1239    }
1240
1241    #[rstest]
1242    #[case(Literal::String("hello".into()), "hello")]
1243    #[case(Literal::Number(crate::number::Number::from(42.0)), "42")]
1244    #[case(Literal::Bool(true), "true")]
1245    #[case(Literal::Bool(false), "false")]
1246    #[case(Literal::None, "none")]
1247    fn test_literal_display(#[case] lit: Literal, #[case] expected: &str) {
1248        assert_eq!(lit.to_string(), expected);
1249    }
1250
1251    #[test]
1252    fn test_literal_bytes_display_ascii() {
1253        let lit = Literal::Bytes(b"hello".as_slice().into());
1254        assert_eq!(lit.to_string(), "b\"hello\"");
1255    }
1256
1257    #[test]
1258    fn test_literal_bytes_display_non_ascii() {
1259        let lit = Literal::Bytes(vec![0x00, 0xff].into());
1260        assert_eq!(lit.to_string(), "b\"\\x00\\xff\"");
1261    }
1262
1263    #[test]
1264    fn test_ident_with_token_display() {
1265        let ident = IdentWithToken::new("foo");
1266        assert_eq!(ident.to_string(), "foo");
1267    }
1268
1269    #[test]
1270    fn test_ident_with_token_ord() {
1271        let a = IdentWithToken::new("a");
1272        let b = IdentWithToken::new("b");
1273        assert!(a < b);
1274    }
1275
1276    #[cfg(feature = "debugger")]
1277    #[test]
1278    fn test_expr_display_call() {
1279        let call = Expr::Call(IdentWithToken::new("func"), smallvec![make_node(0), make_node(1)]);
1280        let s = format!("{call}");
1281        assert!(s.starts_with("func("), "expected func(...), got: {s}");
1282    }
1283
1284    #[cfg(feature = "debugger")]
1285    #[test]
1286    fn test_expr_display_call_dynamic() {
1287        let callee = Shared::new(Node {
1288            token_id: ArenaId::new(0),
1289            expr: Expr::Literal(Literal::None),
1290        });
1291        let dynamic = Expr::CallDynamic(callee, smallvec![]);
1292        let s = format!("{dynamic}");
1293        assert!(s.contains('('), "expected parens in: {s}");
1294    }
1295
1296    #[cfg(feature = "debugger")]
1297    #[test]
1298    fn test_expr_display_literal() {
1299        let lit = Expr::Literal(Literal::None);
1300        assert_eq!(format!("{lit}"), "none");
1301        let lit = Expr::Literal(Literal::Number(crate::number::Number::from(42.0)));
1302        assert_eq!(format!("{lit}"), "42");
1303    }
1304
1305    #[cfg(feature = "debugger")]
1306    #[test]
1307    fn test_expr_display_ident() {
1308        let ident = Expr::Ident(IdentWithToken::new("x"));
1309        assert_eq!(format!("{ident}"), "x");
1310    }
1311
1312    #[cfg(feature = "debugger")]
1313    #[test]
1314    fn test_expr_display_self() {
1315        assert_eq!(format!("{}", Expr::Self_), "self");
1316    }
1317
1318    #[cfg(feature = "debugger")]
1319    #[test]
1320    fn test_expr_display_other_is_empty() {
1321        assert_eq!(format!("{}", Expr::Continue), "");
1322    }
1323
1324    #[test]
1325    fn test_node_size_stays_small() {
1326        // Every node is its own allocation, so one large variant enlarges all of them.
1327        assert!(
1328            std::mem::size_of::<Expr>() <= 40,
1329            "Expr is {} bytes",
1330            std::mem::size_of::<Expr>()
1331        );
1332        assert!(
1333            std::mem::size_of::<Node>() <= 48,
1334            "Node is {} bytes",
1335            std::mem::size_of::<Node>()
1336        );
1337    }
1338}