Skip to main content

fatou_parser/ast/
nodes.rs

1//! Typed AST node wrappers generated by the `ast_node!` macro, plus their
2//! convenience accessors and the [`Expr`] expression sum. These are thin views
3//! over the CST — no allocation, no semantic analysis.
4//!
5//! Accessors return typed wrappers (a child [`AstNode`], an [`Expr`], or a typed
6//! [token](super::tokens)) rather than raw [`SyntaxNode`]s wherever the child
7//! has a wrapper, and fall back to `Option`/iterator shapes that degrade
8//! gracefully on malformed input. The underlying [`SyntaxNode`] is always
9//! reachable through [`AstNode::syntax`].
10
11use rowan::ast::{AstChildren, AstNode, support};
12
13use super::tokens::{AstToken, Ident, Operator, child_token};
14use crate::syntax::{JuliaLanguage, SyntaxKind, SyntaxNode, SyntaxToken};
15
16macro_rules! ast_node {
17    ($(#[$meta:meta])* $name:ident, $kind:expr) => {
18        $(#[$meta])*
19        #[derive(Debug, Clone, PartialEq, Eq, Hash)]
20        pub struct $name(SyntaxNode);
21
22        impl AstNode for $name {
23            type Language = JuliaLanguage;
24
25            fn can_cast(kind: SyntaxKind) -> bool {
26                kind == $kind
27            }
28
29            fn cast(syntax: SyntaxNode) -> Option<Self> {
30                Self::can_cast(syntax.kind()).then_some(Self(syntax))
31            }
32
33            fn syntax(&self) -> &SyntaxNode {
34                &self.0
35            }
36        }
37    };
38}
39
40ast_node!(Root, SyntaxKind::ROOT);
41ast_node!(Doc, SyntaxKind::DOC);
42ast_node!(Literal, SyntaxKind::LITERAL);
43ast_node!(StringLiteral, SyntaxKind::STRING_LITERAL);
44ast_node!(CmdLiteral, SyntaxKind::CMD_LITERAL);
45ast_node!(NonstandardIdentifier, SyntaxKind::NONSTANDARD_IDENTIFIER);
46ast_node!(Interpolation, SyntaxKind::INTERPOLATION);
47ast_node!(Name, SyntaxKind::NAME);
48ast_node!(BinaryExpr, SyntaxKind::BINARY_EXPR);
49ast_node!(UnaryExpr, SyntaxKind::UNARY_EXPR);
50ast_node!(ParenExpr, SyntaxKind::PAREN_EXPR);
51ast_node!(TupleExpr, SyntaxKind::TUPLE_EXPR);
52ast_node!(VectExpr, SyntaxKind::VECT_EXPR);
53ast_node!(MatrixExpr, SyntaxKind::MATRIX_EXPR);
54ast_node!(MatrixRow, SyntaxKind::MATRIX_ROW);
55ast_node!(Comprehension, SyntaxKind::COMPREHENSION);
56ast_node!(Generator, SyntaxKind::GENERATOR);
57ast_node!(ComprehensionIf, SyntaxKind::COMPREHENSION_IF);
58ast_node!(CallExpr, SyntaxKind::CALL_EXPR);
59ast_node!(IndexExpr, SyntaxKind::INDEX_EXPR);
60ast_node!(DotCallExpr, SyntaxKind::DOT_CALL_EXPR);
61ast_node!(CurlyExpr, SyntaxKind::CURLY_EXPR);
62ast_node!(Braces, SyntaxKind::BRACES);
63ast_node!(ArgList, SyntaxKind::ARG_LIST);
64ast_node!(Arg, SyntaxKind::ARG);
65ast_node!(KeywordArg, SyntaxKind::KEYWORD_ARG);
66ast_node!(Parameters, SyntaxKind::PARAMETERS);
67ast_node!(TypeAnnotation, SyntaxKind::TYPE_ANNOTATION);
68ast_node!(WhereExpr, SyntaxKind::WHERE_EXPR);
69ast_node!(SplatExpr, SyntaxKind::SPLAT_EXPR);
70ast_node!(EndMarker, SyntaxKind::END_MARKER);
71ast_node!(AssignmentExpr, SyntaxKind::ASSIGNMENT_EXPR);
72ast_node!(ArrowExpr, SyntaxKind::ARROW_EXPR);
73ast_node!(TernaryExpr, SyntaxKind::TERNARY_EXPR);
74ast_node!(IfExpr, SyntaxKind::IF_EXPR);
75ast_node!(ElseifClause, SyntaxKind::ELSEIF_CLAUSE);
76ast_node!(ElseClause, SyntaxKind::ELSE_CLAUSE);
77ast_node!(Condition, SyntaxKind::CONDITION);
78ast_node!(FunctionDef, SyntaxKind::FUNCTION_DEF);
79ast_node!(MacroDef, SyntaxKind::MACRO_DEF);
80ast_node!(Signature, SyntaxKind::SIGNATURE);
81ast_node!(Block, SyntaxKind::BLOCK);
82ast_node!(BeginExpr, SyntaxKind::BEGIN_EXPR);
83ast_node!(QuoteExpr, SyntaxKind::QUOTE_EXPR);
84ast_node!(QuoteSym, SyntaxKind::QUOTE_SYM);
85ast_node!(WhileExpr, SyntaxKind::WHILE_EXPR);
86ast_node!(ForExpr, SyntaxKind::FOR_EXPR);
87ast_node!(ForBinding, SyntaxKind::FOR_BINDING);
88ast_node!(LetExpr, SyntaxKind::LET_EXPR);
89ast_node!(LetBindings, SyntaxKind::LET_BINDINGS);
90ast_node!(TryExpr, SyntaxKind::TRY_EXPR);
91ast_node!(CatchClause, SyntaxKind::CATCH_CLAUSE);
92ast_node!(FinallyClause, SyntaxKind::FINALLY_CLAUSE);
93ast_node!(StructDef, SyntaxKind::STRUCT_DEF);
94ast_node!(AbstractDef, SyntaxKind::ABSTRACT_DEF);
95ast_node!(PrimitiveDef, SyntaxKind::PRIMITIVE_DEF);
96ast_node!(ModuleDef, SyntaxKind::MODULE_DEF);
97ast_node!(DoExpr, SyntaxKind::DO_EXPR);
98ast_node!(DoParams, SyntaxKind::DO_PARAMS);
99ast_node!(ReturnExpr, SyntaxKind::RETURN_EXPR);
100ast_node!(BreakExpr, SyntaxKind::BREAK_EXPR);
101ast_node!(ContinueExpr, SyntaxKind::CONTINUE_EXPR);
102ast_node!(ConstStmt, SyntaxKind::CONST_STMT);
103ast_node!(GlobalStmt, SyntaxKind::GLOBAL_STMT);
104ast_node!(LocalStmt, SyntaxKind::LOCAL_STMT);
105ast_node!(ImportStmt, SyntaxKind::IMPORT_STMT);
106ast_node!(UsingStmt, SyntaxKind::USING_STMT);
107ast_node!(ExportStmt, SyntaxKind::EXPORT_STMT);
108ast_node!(MacroCall, SyntaxKind::MACRO_CALL);
109ast_node!(MacroName, SyntaxKind::MACRO_NAME);
110
111/// The expression sum: any node that can appear in value position, cast to a
112/// dedicated variant when one exists and to [`Expr::Other`] otherwise.
113///
114/// `Other` keeps the sum *total* over expression kinds — the Julia grammar is a
115/// growing skeleton, so a kind that has no wrapper yet (e.g. `RANGE_EXPR`,
116/// `COMPARISON_EXPR`) still round-trips through `Expr` instead of being silently
117/// dropped from an operand accessor. Match `Other`'s [`SyntaxNode`] (or its
118/// [`kind`](SyntaxNode::kind)) for those.
119#[derive(Debug, Clone, PartialEq, Eq, Hash)]
120pub enum Expr {
121    Literal(Literal),
122    StringLiteral(StringLiteral),
123    CmdLiteral(CmdLiteral),
124    NonstandardIdentifier(NonstandardIdentifier),
125    Interpolation(Interpolation),
126    Name(Name),
127    BinaryExpr(BinaryExpr),
128    UnaryExpr(UnaryExpr),
129    ParenExpr(ParenExpr),
130    TupleExpr(TupleExpr),
131    VectExpr(VectExpr),
132    MatrixExpr(MatrixExpr),
133    Comprehension(Comprehension),
134    Generator(Generator),
135    CallExpr(CallExpr),
136    IndexExpr(IndexExpr),
137    DotCallExpr(DotCallExpr),
138    CurlyExpr(CurlyExpr),
139    Braces(Braces),
140    AssignmentExpr(AssignmentExpr),
141    ArrowExpr(ArrowExpr),
142    TernaryExpr(TernaryExpr),
143    IfExpr(IfExpr),
144    BeginExpr(BeginExpr),
145    QuoteExpr(QuoteExpr),
146    WhileExpr(WhileExpr),
147    ForExpr(ForExpr),
148    LetExpr(LetExpr),
149    TryExpr(TryExpr),
150    DoExpr(DoExpr),
151    FunctionDef(FunctionDef),
152    MacroCall(MacroCall),
153    SplatExpr(SplatExpr),
154    WhereExpr(WhereExpr),
155    TypeAnnotation(TypeAnnotation),
156    ReturnExpr(ReturnExpr),
157    BreakExpr(BreakExpr),
158    ContinueExpr(ContinueExpr),
159    QuoteSym(QuoteSym),
160    StructDef(StructDef),
161    AbstractDef(AbstractDef),
162    PrimitiveDef(PrimitiveDef),
163    ModuleDef(ModuleDef),
164    /// An expression-position node without a dedicated variant (see the type
165    /// docs). Guaranteed to satisfy [`is_expr_kind`].
166    Other(SyntaxNode),
167}
168
169/// Whether `kind` is a node that can occur in expression (value) position. The
170/// complement is the structural scaffolding — clauses, argument lists,
171/// signatures, statements, blocks — plus every token kind.
172pub fn is_expr_kind(kind: SyntaxKind) -> bool {
173    use SyntaxKind::*;
174    matches!(
175        kind,
176        LITERAL
177            | STRING_LITERAL
178            | CMD_LITERAL
179            | NONSTANDARD_IDENTIFIER
180            | INTERPOLATION
181            | NAME
182            | BINARY_EXPR
183            | RANGE_EXPR
184            | COMPARISON_EXPR
185            | UNARY_EXPR
186            | PAREN_EXPR
187            | TUPLE_EXPR
188            | BARE_TUPLE_EXPR
189            | PAREN_BLOCK
190            | VECT_EXPR
191            | MATRIX_EXPR
192            | TYPED_MATRIX_EXPR
193            | BRACESCAT_EXPR
194            | COMPREHENSION
195            | BRACES_COMPREHENSION
196            | TYPED_COMPREHENSION
197            | GENERATOR
198            | CALL_EXPR
199            | INDEX_EXPR
200            | DOT_CALL_EXPR
201            | CURLY_EXPR
202            | BRACES
203            | TYPE_ANNOTATION
204            | WHERE_EXPR
205            | SPLAT_EXPR
206            | POSTFIX_EXPR
207            | OPERATOR_ATOM
208            | ASSIGNMENT_EXPR
209            | ARROW_EXPR
210            | JUXTAPOSE_EXPR
211            | TERNARY_EXPR
212            | IF_EXPR
213            | FUNCTION_DEF
214            | BEGIN_EXPR
215            | WHILE_EXPR
216            | FOR_EXPR
217            | LET_EXPR
218            | QUOTE_EXPR
219            | QUOTE_SYM
220            | TRY_EXPR
221            | STRUCT_DEF
222            | ABSTRACT_DEF
223            | PRIMITIVE_DEF
224            | TYPEGROUP_DEF
225            | MODULE_DEF
226            | DO_EXPR
227            | RETURN_EXPR
228            | BREAK_EXPR
229            | CONTINUE_EXPR
230            | MACRO_CALL
231    )
232}
233
234impl AstNode for Expr {
235    type Language = JuliaLanguage;
236
237    fn can_cast(kind: SyntaxKind) -> bool {
238        is_expr_kind(kind)
239    }
240
241    fn cast(syntax: SyntaxNode) -> Option<Self> {
242        let expr = match syntax.kind() {
243            SyntaxKind::LITERAL => Expr::Literal(Literal(syntax)),
244            SyntaxKind::STRING_LITERAL => Expr::StringLiteral(StringLiteral(syntax)),
245            SyntaxKind::CMD_LITERAL => Expr::CmdLiteral(CmdLiteral(syntax)),
246            SyntaxKind::NONSTANDARD_IDENTIFIER => {
247                Expr::NonstandardIdentifier(NonstandardIdentifier(syntax))
248            }
249            SyntaxKind::INTERPOLATION => Expr::Interpolation(Interpolation(syntax)),
250            SyntaxKind::NAME => Expr::Name(Name(syntax)),
251            SyntaxKind::BINARY_EXPR => Expr::BinaryExpr(BinaryExpr(syntax)),
252            SyntaxKind::UNARY_EXPR => Expr::UnaryExpr(UnaryExpr(syntax)),
253            SyntaxKind::PAREN_EXPR => Expr::ParenExpr(ParenExpr(syntax)),
254            SyntaxKind::TUPLE_EXPR => Expr::TupleExpr(TupleExpr(syntax)),
255            SyntaxKind::VECT_EXPR => Expr::VectExpr(VectExpr(syntax)),
256            SyntaxKind::MATRIX_EXPR => Expr::MatrixExpr(MatrixExpr(syntax)),
257            SyntaxKind::COMPREHENSION => Expr::Comprehension(Comprehension(syntax)),
258            SyntaxKind::GENERATOR => Expr::Generator(Generator(syntax)),
259            SyntaxKind::CALL_EXPR => Expr::CallExpr(CallExpr(syntax)),
260            SyntaxKind::INDEX_EXPR => Expr::IndexExpr(IndexExpr(syntax)),
261            SyntaxKind::DOT_CALL_EXPR => Expr::DotCallExpr(DotCallExpr(syntax)),
262            SyntaxKind::CURLY_EXPR => Expr::CurlyExpr(CurlyExpr(syntax)),
263            SyntaxKind::BRACES => Expr::Braces(Braces(syntax)),
264            SyntaxKind::ASSIGNMENT_EXPR => Expr::AssignmentExpr(AssignmentExpr(syntax)),
265            SyntaxKind::ARROW_EXPR => Expr::ArrowExpr(ArrowExpr(syntax)),
266            SyntaxKind::TERNARY_EXPR => Expr::TernaryExpr(TernaryExpr(syntax)),
267            SyntaxKind::IF_EXPR => Expr::IfExpr(IfExpr(syntax)),
268            SyntaxKind::BEGIN_EXPR => Expr::BeginExpr(BeginExpr(syntax)),
269            SyntaxKind::QUOTE_EXPR => Expr::QuoteExpr(QuoteExpr(syntax)),
270            SyntaxKind::WHILE_EXPR => Expr::WhileExpr(WhileExpr(syntax)),
271            SyntaxKind::FOR_EXPR => Expr::ForExpr(ForExpr(syntax)),
272            SyntaxKind::LET_EXPR => Expr::LetExpr(LetExpr(syntax)),
273            SyntaxKind::TRY_EXPR => Expr::TryExpr(TryExpr(syntax)),
274            SyntaxKind::DO_EXPR => Expr::DoExpr(DoExpr(syntax)),
275            SyntaxKind::FUNCTION_DEF => Expr::FunctionDef(FunctionDef(syntax)),
276            SyntaxKind::MACRO_CALL => Expr::MacroCall(MacroCall(syntax)),
277            SyntaxKind::SPLAT_EXPR => Expr::SplatExpr(SplatExpr(syntax)),
278            SyntaxKind::WHERE_EXPR => Expr::WhereExpr(WhereExpr(syntax)),
279            SyntaxKind::TYPE_ANNOTATION => Expr::TypeAnnotation(TypeAnnotation(syntax)),
280            SyntaxKind::RETURN_EXPR => Expr::ReturnExpr(ReturnExpr(syntax)),
281            SyntaxKind::BREAK_EXPR => Expr::BreakExpr(BreakExpr(syntax)),
282            SyntaxKind::CONTINUE_EXPR => Expr::ContinueExpr(ContinueExpr(syntax)),
283            SyntaxKind::QUOTE_SYM => Expr::QuoteSym(QuoteSym(syntax)),
284            SyntaxKind::STRUCT_DEF => Expr::StructDef(StructDef(syntax)),
285            SyntaxKind::ABSTRACT_DEF => Expr::AbstractDef(AbstractDef(syntax)),
286            SyntaxKind::PRIMITIVE_DEF => Expr::PrimitiveDef(PrimitiveDef(syntax)),
287            SyntaxKind::MODULE_DEF => Expr::ModuleDef(ModuleDef(syntax)),
288            // `TYPEGROUP_DEF` is an expression kind with no wrapper of its own,
289            // so it is the one kind that reaches consumers as `Other` by design.
290            kind if is_expr_kind(kind) => Expr::Other(syntax),
291            _ => return None,
292        };
293        Some(expr)
294    }
295
296    fn syntax(&self) -> &SyntaxNode {
297        match self {
298            Expr::Literal(it) => it.syntax(),
299            Expr::StringLiteral(it) => it.syntax(),
300            Expr::CmdLiteral(it) => it.syntax(),
301            Expr::NonstandardIdentifier(it) => it.syntax(),
302            Expr::Interpolation(it) => it.syntax(),
303            Expr::Name(it) => it.syntax(),
304            Expr::BinaryExpr(it) => it.syntax(),
305            Expr::UnaryExpr(it) => it.syntax(),
306            Expr::ParenExpr(it) => it.syntax(),
307            Expr::TupleExpr(it) => it.syntax(),
308            Expr::VectExpr(it) => it.syntax(),
309            Expr::MatrixExpr(it) => it.syntax(),
310            Expr::Comprehension(it) => it.syntax(),
311            Expr::Generator(it) => it.syntax(),
312            Expr::CallExpr(it) => it.syntax(),
313            Expr::IndexExpr(it) => it.syntax(),
314            Expr::DotCallExpr(it) => it.syntax(),
315            Expr::CurlyExpr(it) => it.syntax(),
316            Expr::Braces(it) => it.syntax(),
317            Expr::AssignmentExpr(it) => it.syntax(),
318            Expr::ArrowExpr(it) => it.syntax(),
319            Expr::TernaryExpr(it) => it.syntax(),
320            Expr::IfExpr(it) => it.syntax(),
321            Expr::BeginExpr(it) => it.syntax(),
322            Expr::QuoteExpr(it) => it.syntax(),
323            Expr::WhileExpr(it) => it.syntax(),
324            Expr::ForExpr(it) => it.syntax(),
325            Expr::LetExpr(it) => it.syntax(),
326            Expr::TryExpr(it) => it.syntax(),
327            Expr::DoExpr(it) => it.syntax(),
328            Expr::FunctionDef(it) => it.syntax(),
329            Expr::MacroCall(it) => it.syntax(),
330            Expr::SplatExpr(it) => it.syntax(),
331            Expr::WhereExpr(it) => it.syntax(),
332            Expr::TypeAnnotation(it) => it.syntax(),
333            Expr::ReturnExpr(it) => it.syntax(),
334            Expr::BreakExpr(it) => it.syntax(),
335            Expr::ContinueExpr(it) => it.syntax(),
336            Expr::QuoteSym(it) => it.syntax(),
337            Expr::StructDef(it) => it.syntax(),
338            Expr::AbstractDef(it) => it.syntax(),
339            Expr::PrimitiveDef(it) => it.syntax(),
340            Expr::ModuleDef(it) => it.syntax(),
341            Expr::Other(it) => it,
342        }
343    }
344}
345
346impl Expr {
347    /// The identifier token, when this expression is a bare name (`x`). `None`
348    /// for every compound shape, including a qualified path (`M.x`), which is a
349    /// `BINARY_EXPR`, and a `var"..."` identifier, which has no `IDENT` token.
350    pub fn name_ident(&self) -> Option<Ident> {
351        match self {
352            Expr::Name(name) => name.ident(),
353            _ => None,
354        }
355    }
356}
357
358impl Name {
359    /// The identifier token.
360    pub fn ident(&self) -> Option<Ident> {
361        child_token(&self.0)
362    }
363}
364
365impl Literal {
366    /// The `true`/`false` keyword token, when the literal is a boolean.
367    pub fn bool_token(&self) -> Option<SyntaxToken> {
368        support::token(&self.0, SyntaxKind::TRUE_KW)
369            .or_else(|| support::token(&self.0, SyntaxKind::FALSE_KW))
370    }
371
372    /// The numeric value token, when the literal is a number: an integer (any
373    /// base) or a float. `None` for non-numeric literals (booleans, `nothing`).
374    pub fn numeric_token(&self) -> Option<SyntaxToken> {
375        self.0
376            .children_with_tokens()
377            .filter_map(|el| el.into_token())
378            .find(|t| {
379                matches!(
380                    t.kind(),
381                    SyntaxKind::INTEGER
382                        | SyntaxKind::BIN_INT
383                        | SyntaxKind::OCT_INT
384                        | SyntaxKind::HEX_INT
385                        | SyntaxKind::FLOAT
386                        | SyntaxKind::FLOAT32
387                )
388            })
389    }
390}
391
392impl NonstandardIdentifier {
393    /// The quoted body of a `var"..."` identifier (its `STRING_CONTENT` token).
394    pub fn content(&self) -> Option<SyntaxToken> {
395        support::token(&self.0, SyntaxKind::STRING_CONTENT)
396    }
397}
398
399impl StringLiteral {
400    /// The non-standard literal prefix token, e.g. `r` in `r"..."`.
401    pub fn prefix(&self) -> Option<SyntaxToken> {
402        support::token(&self.0, SyntaxKind::STRING_PREFIX)
403    }
404
405    /// The suffix flag token, e.g. `ims` in `r"pat"ims`.
406    pub fn suffix(&self) -> Option<SyntaxToken> {
407        support::token(&self.0, SyntaxKind::STRING_SUFFIX)
408    }
409
410    /// The interpolations embedded in the string, in source order.
411    pub fn interpolations(&self) -> AstChildren<Interpolation> {
412        support::children(&self.0)
413    }
414
415    /// The `STRING_CONTENT` chunks of the literal, in source order. A plain
416    /// (non-interpolated) string joins to its full text.
417    pub fn content_tokens(&self) -> impl Iterator<Item = SyntaxToken> {
418        self.0
419            .children_with_tokens()
420            .filter_map(|el| el.into_token())
421            .filter(|t| t.kind() == SyntaxKind::STRING_CONTENT)
422    }
423}
424
425impl Doc {
426    /// The ordinary string literal supplying this docstring's content.
427    pub fn literal(&self) -> Option<StringLiteral> {
428        support::child(&self.0)
429    }
430
431    /// The expression or statement documented by this string.
432    ///
433    /// Julia permits several structurally unrelated target kinds, so the
434    /// attachment wrapper keeps the target as a lossless syntax node rather
435    /// than pretending they share an expression shape.
436    pub fn target(&self) -> Option<super::documentation::DocTarget> {
437        self.0
438            .children()
439            .nth(1)
440            .map(super::documentation::DocTarget::new)
441    }
442}
443
444impl CmdLiteral {
445    /// The non-standard literal prefix token, e.g. `` v `` in `` v`...` ``.
446    pub fn prefix(&self) -> Option<SyntaxToken> {
447        support::token(&self.0, SyntaxKind::STRING_PREFIX)
448    }
449
450    /// The suffix flag token following the closing backtick.
451    pub fn suffix(&self) -> Option<SyntaxToken> {
452        support::token(&self.0, SyntaxKind::STRING_SUFFIX)
453    }
454
455    /// The interpolations embedded in the command, in source order.
456    pub fn interpolations(&self) -> AstChildren<Interpolation> {
457        support::children(&self.0)
458    }
459}
460
461impl Interpolation {
462    /// The bare interpolated identifier token for `$ident` (absent for `$(expr)`).
463    pub fn ident(&self) -> Option<Ident> {
464        child_token(&self.0)
465    }
466
467    /// The interpolated expression for `$(expr)` (absent for `$ident`).
468    pub fn expr(&self) -> Option<Expr> {
469        support::child(&self.0)
470    }
471}
472
473impl BinaryExpr {
474    /// The left operand.
475    pub fn lhs(&self) -> Option<Expr> {
476        support::child(&self.0)
477    }
478
479    /// The right operand.
480    pub fn rhs(&self) -> Option<Expr> {
481        support::children(&self.0).nth(1)
482    }
483
484    /// The operator token (the first operator between the operands).
485    pub fn op(&self) -> Option<Operator> {
486        child_token(&self.0)
487    }
488
489    /// The word operator (`in` or `isa`) between the operands.
490    ///
491    /// Julia lexes these operators as identifiers, so they deliberately do not
492    /// cast to [`Operator`]. Operand identifiers are nested inside their own
493    /// nodes; only the word operator is a direct token of this node.
494    pub fn word_op(&self) -> Option<Ident> {
495        self.0
496            .children_with_tokens()
497            .filter_map(|element| element.into_token())
498            .find(|token| token.kind() == SyntaxKind::IDENT && matches!(token.text(), "in" | "isa"))
499            .and_then(Ident::cast)
500    }
501
502    /// Whether this binary expression uses Julia's comparison precedence tier.
503    ///
504    /// The answer includes the word operators `in`/`isa` and uses the parser's
505    /// generated classification for Unicode operators, so AST consumers do not
506    /// need to duplicate the precedence table.
507    pub fn is_comparison(&self) -> bool {
508        self.word_op().is_some()
509            || self
510                .op()
511                .is_some_and(|op| crate::parser::is_comparison_operator_text(op.text()))
512    }
513}
514
515impl AssignmentExpr {
516    /// The assignment target (left of the operator).
517    pub fn lhs(&self) -> Option<Expr> {
518        support::child(&self.0)
519    }
520
521    /// The assigned value (right of the operator).
522    pub fn rhs(&self) -> Option<Expr> {
523        support::children(&self.0).nth(1)
524    }
525
526    /// The assignment operator token (`=`, `+=`, `.=`, ...).
527    pub fn op(&self) -> Option<Operator> {
528        child_token(&self.0)
529    }
530}
531
532impl ArrowExpr {
533    /// The parameter side (left of `->`).
534    pub fn lhs(&self) -> Option<Expr> {
535        support::child(&self.0)
536    }
537
538    /// The body side (right of `->`).
539    pub fn rhs(&self) -> Option<Expr> {
540        support::children(&self.0).nth(1)
541    }
542}
543
544impl TernaryExpr {
545    /// The test (left of `?`).
546    pub fn condition(&self) -> Option<Expr> {
547        support::child(&self.0)
548    }
549
550    /// The arm taken when the test holds (between `?` and `:`).
551    pub fn then_branch(&self) -> Option<Expr> {
552        support::children(&self.0).nth(1)
553    }
554
555    /// The arm taken otherwise (right of `:`). `None` for an incomplete
556    /// ternary, which the parser still shapes as a `TERNARY_EXPR`.
557    pub fn else_branch(&self) -> Option<Expr> {
558        support::children(&self.0).nth(2)
559    }
560}
561
562impl UnaryExpr {
563    /// The operator token.
564    pub fn op(&self) -> Option<Operator> {
565        child_token(&self.0)
566    }
567
568    /// The operand.
569    pub fn operand(&self) -> Option<Expr> {
570        support::child(&self.0)
571    }
572}
573
574impl SplatExpr {
575    /// The splatted expression (the `x` in `x...`).
576    pub fn expr(&self) -> Option<Expr> {
577        support::child(&self.0)
578    }
579}
580
581impl ParenExpr {
582    /// The parenthesized inner expression.
583    pub fn expr(&self) -> Option<Expr> {
584        support::child(&self.0)
585    }
586}
587
588impl CallExpr {
589    /// The callee (the expression being called).
590    pub fn callee(&self) -> Option<Expr> {
591        support::child(&self.0)
592    }
593
594    /// The identifier naming the callee, when the callee is a bare name
595    /// (`f(x)`). `None` for every compound callee: a qualified path
596    /// (`Base.f(x)`), an operator ([`Self::callee_operator`]), a `var"..."`
597    /// name, and a computed one (`g()(x)`).
598    pub fn callee_ident(&self) -> Option<Ident> {
599        match self.callee()? {
600            Expr::Name(name) => name.ident(),
601            _ => None,
602        }
603    }
604
605    /// The operator token naming the callee, when the callee is an operator
606    /// rather than an ordinary expression: bare (`!=(a, b)`), parenthesized
607    /// (`(!=)(a, b)`), or the quoted symbol ending a qualified path
608    /// (`Base.:!=(a, b)`, `Base.:(==)(a, b)`). `None` for every other callee
609    /// shape.
610    pub fn callee_operator(&self) -> Option<Operator> {
611        for el in self.0.children_with_tokens() {
612            match el {
613                rowan::NodeOrToken::Token(token) => {
614                    if let Some(op) = Operator::cast(token) {
615                        return Some(op);
616                    }
617                }
618                rowan::NodeOrToken::Node(node) => {
619                    return match node.kind() {
620                        SyntaxKind::PAREN_EXPR => paren_operator(&node),
621                        // A qualified path callee (`Base.:!=`): the operator is
622                        // the quoted symbol ending the path.
623                        SyntaxKind::BINARY_EXPR => node
624                            .children()
625                            .last()
626                            .filter(|last| last.kind() == SyntaxKind::QUOTE_SYM)
627                            .and_then(|quote| quote_sym_operator(&quote)),
628                        _ => None,
629                    };
630                }
631            }
632        }
633        None
634    }
635}
636
637/// The lone operator inside a `PAREN_EXPR` (`(!=)`, `:(==)`), if any. The
638/// operator is either a direct token or wrapped in an `OPERATOR_ATOM` (the
639/// operator-as-value node a quote-paren builds).
640fn paren_operator(paren: &SyntaxNode) -> Option<Operator> {
641    paren.children_with_tokens().find_map(|el| match el {
642        rowan::NodeOrToken::Token(token) => Operator::cast(token),
643        rowan::NodeOrToken::Node(node) if node.kind() == SyntaxKind::OPERATOR_ATOM => node
644            .children_with_tokens()
645            .filter_map(|el| el.into_token())
646            .find_map(Operator::cast),
647        rowan::NodeOrToken::Node(_) => None,
648    })
649}
650
651/// The operator a `QUOTE_SYM` quotes (`:!=`, `:(==)`), skipping the leading
652/// quoting `:` (itself an operator kind).
653fn quote_sym_operator(quote: &SyntaxNode) -> Option<Operator> {
654    let mut seen_quote_colon = false;
655    for el in quote.children_with_tokens() {
656        match el {
657            rowan::NodeOrToken::Token(token) => {
658                if !seen_quote_colon && token.kind() == SyntaxKind::COLON {
659                    seen_quote_colon = true;
660                } else if let Some(op) = Operator::cast(token) {
661                    return Some(op);
662                }
663            }
664            rowan::NodeOrToken::Node(node) if node.kind() == SyntaxKind::PAREN_EXPR => {
665                return paren_operator(&node);
666            }
667            _ => {}
668        }
669    }
670    None
671}
672
673impl IndexExpr {
674    /// The expression being indexed.
675    pub fn base(&self) -> Option<Expr> {
676        support::child(&self.0)
677    }
678}
679
680impl DotCallExpr {
681    /// The callee of the broadcast call.
682    pub fn callee(&self) -> Option<Expr> {
683        support::child(&self.0)
684    }
685}
686
687impl CurlyExpr {
688    /// The base expression the type parameters apply to, e.g. `Vector` in
689    /// `Vector{T}`.
690    pub fn base(&self) -> Option<Expr> {
691        support::child(&self.0)
692    }
693}
694
695impl ArgList {
696    /// The positional/keyword argument nodes (`ARG`, `KEYWORD_ARG`), in source
697    /// order. Each [`Arg`] wraps the argument expression; keyword arguments are
698    /// reached via [`Self::keyword_args`].
699    pub fn args(&self) -> AstChildren<Arg> {
700        support::children(&self.0)
701    }
702
703    /// The keyword arguments (`x = v`), in source order.
704    pub fn keyword_args(&self) -> AstChildren<KeywordArg> {
705        support::children(&self.0)
706    }
707}
708
709impl Arg {
710    /// The argument's expression.
711    pub fn expr(&self) -> Option<Expr> {
712        support::child(&self.0)
713    }
714}
715
716impl KeywordArg {
717    /// The keyword name (the left of `=`).
718    pub fn name(&self) -> Option<Name> {
719        support::child(&self.0)
720    }
721
722    /// The keyword value (the right of `=`).
723    pub fn value(&self) -> Option<Expr> {
724        support::children(&self.0).nth(1)
725    }
726}
727
728impl MacroCall {
729    /// The macro name, e.g. `@m`, `@.`, or `Base.@time`.
730    pub fn name(&self) -> Option<MacroName> {
731        support::child(&self.0)
732    }
733}
734
735impl MacroName {
736    /// The macro's simple-name token: the final `IDENT` (e.g. `time` in
737    /// `Base.@time`), or the `DOT` for the broadcast macro `@.`.
738    pub fn macro_token(&self) -> Option<SyntaxToken> {
739        self.0
740            .children_with_tokens()
741            .filter_map(|e| e.into_token())
742            .filter(|t| matches!(t.kind(), SyntaxKind::IDENT | SyntaxKind::DOT))
743            .last()
744    }
745
746    /// The identifier components of the macro name in source order.
747    ///
748    /// This yields just `m` for `@m`, and `Base`, `time` for both
749    /// `Base.@time` and `@Base.time`. The `@.` broadcast macro has no identifier
750    /// components.
751    pub fn ident_tokens(&self) -> impl Iterator<Item = Ident> + '_ {
752        self.0
753            .descendants_with_tokens()
754            .filter_map(|element| element.into_token())
755            .filter_map(Ident::cast)
756    }
757}
758
759impl TypeAnnotation {
760    /// The `::` operator token. Private: unlike the other `op()` accessors this
761    /// returns a raw token rather than a typed [`Operator`], and it exists only
762    /// to split the children in [`Self::pattern`] and [`Self::ty`].
763    fn op(&self) -> Option<SyntaxToken> {
764        support::token(&self.0, SyntaxKind::COLON_COLON)
765    }
766
767    /// The annotated pattern — what stands *left* of the `::`. Absent for the
768    /// unnamed-argument form `::Int`, where the `::` precedes the only child.
769    pub fn pattern(&self) -> Option<Expr> {
770        let op = self.op()?;
771        support::children::<Expr>(&self.0)
772            .find(|expr| expr.syntax().text_range().end() <= op.text_range().start())
773    }
774
775    /// The declared type — what stands *right* of the `::`.
776    pub fn ty(&self) -> Option<Expr> {
777        let op = self.op()?;
778        support::children::<Expr>(&self.0)
779            .find(|expr| expr.syntax().text_range().start() >= op.text_range().end())
780    }
781}
782
783impl QuoteSym {
784    /// The quoted expression: `x` in `:x`, `(x + 1)` in `:(x + 1)`. Absent for
785    /// a quoted operator or keyword (`:+`, `:if`), which the parser carries as
786    /// a bare token rather than a node.
787    ///
788    /// Note that a `QUOTE_SYM` is not always a `Symbol` at runtime: `:x` is,
789    /// but `:(x + 1)` evaluates to an `Expr`.
790    pub fn expr(&self) -> Option<Expr> {
791        support::child(&self.0)
792    }
793}
794
795impl Parameters {
796    /// The keyword parameters written without a `::` annotation (`y = 1`), in
797    /// source order.
798    ///
799    /// The `;`-block splits by shape rather than by role: a *plain* keyword is
800    /// a `KEYWORD_ARG`, while an annotated parameter (`y::Int = 1`) and the
801    /// call-site shorthand (`f(; verbose)`) both arrive as [`Arg`]s — see
802    /// [`Self::args`].
803    pub fn keyword_args(&self) -> AstChildren<KeywordArg> {
804        support::children(&self.0)
805    }
806
807    /// The `;`-block entries that are not plain `KEYWORD_ARG`s, in source
808    /// order: an annotated keyword parameter (`y::Int = 1`), the call-site
809    /// shorthand (`f(; verbose)`), and a keyword splat (`f(; kw...)`).
810    pub fn args(&self) -> AstChildren<Arg> {
811        support::children(&self.0)
812    }
813}
814
815impl IfExpr {
816    /// The `then` branch block. (The condition is [`HasCondition::condition`](crate::ast::traits::HasCondition::condition).)
817    pub fn then_body(&self) -> Option<Block> {
818        support::child(&self.0)
819    }
820
821    /// The `elseif` clauses, in source order.
822    pub fn elseif_clauses(&self) -> AstChildren<ElseifClause> {
823        support::children(&self.0)
824    }
825
826    /// The trailing `else` clause, if any.
827    pub fn else_clause(&self) -> Option<ElseClause> {
828        support::child(&self.0)
829    }
830}
831
832impl Condition {
833    /// The test expression, unwrapping a single parenthesized layer
834    /// (`if (x) ...` yields the `x`). Centralizes the paren-unwrap that
835    /// condition consumers would otherwise hand-roll.
836    pub fn expr(&self) -> Option<Expr> {
837        match support::child::<Expr>(&self.0)? {
838            Expr::ParenExpr(paren) => paren.expr(),
839            other => Some(other),
840        }
841    }
842}
843
844impl FunctionDef {
845    /// The function signature, e.g. `g(x)`.
846    pub fn signature(&self) -> Option<Signature> {
847        support::child(&self.0)
848    }
849}
850
851impl Signature {
852    /// The signature's core expression (a `CALL_EXPR`, a bare `NAME`, ...).
853    pub fn expr(&self) -> Option<Expr> {
854        support::child(&self.0)
855    }
856}
857
858impl ModuleDef {
859    /// The module's name, e.g. `M` in `module M ... end`. (The body is
860    /// [`HasBody::body`](crate::ast::traits::HasBody::body).)
861    pub fn name(&self) -> Option<Name> {
862        support::child::<Signature>(&self.0).and_then(|sig| support::child(&sig.0))
863    }
864}
865
866impl ForBinding {
867    /// The loop variable/pattern (left of `in`/`=`).
868    pub fn pattern(&self) -> Option<Expr> {
869        support::child(&self.0)
870    }
871
872    /// The iterable expression (right of `in`/`=`).
873    pub fn iterable(&self) -> Option<Expr> {
874        support::children(&self.0).nth(1)
875    }
876}
877
878impl CatchClause {
879    /// The bound exception variable (`catch e`), if named. (The body is
880    /// [`HasBody::body`](crate::ast::traits::HasBody::body).)
881    pub fn variable(&self) -> Option<Name> {
882        support::child(&self.0)
883    }
884}
885
886impl DoExpr {
887    /// The parameters on the `do` line, e.g. `x, y` in `f(a) do x, y`. Absent for
888    /// a bare `do`.
889    pub fn params(&self) -> Option<DoParams> {
890        support::child(&self.0)
891    }
892}
893
894impl Root {
895    /// The top-level items of the file, in source order.
896    pub fn items(&self) -> AstChildren<Expr> {
897        support::children(&self.0)
898    }
899}
900
901#[cfg(test)]
902mod tests {
903    use super::*;
904    use crate::ast::tokens::AstToken;
905    use crate::ast::traits::{HasArgList, HasBody, HasCondition};
906    use crate::parser::parse;
907
908    /// The first node in the parse of `src` castable to `T`.
909    fn find<T: AstNode<Language = JuliaLanguage>>(src: &str) -> T {
910        parse(src)
911            .cst
912            .descendants()
913            .find_map(T::cast)
914            .expect("node of the requested kind present")
915    }
916
917    fn expr_text(expr: Option<Expr>) -> String {
918        expr.expect("expression present")
919            .syntax()
920            .text()
921            .to_string()
922    }
923
924    #[test]
925    fn binary_expr_operands_and_operator() {
926        let bin: BinaryExpr = find("a + b\n");
927        assert_eq!(expr_text(bin.lhs()), "a");
928        assert_eq!(expr_text(bin.rhs()), "b");
929        assert_eq!(bin.op().unwrap().text(), "+");
930
931        let bin: BinaryExpr = find("x isa T\n");
932        assert_eq!(bin.word_op().unwrap().text(), "isa");
933        assert!(bin.op().is_none());
934        assert!(bin.is_comparison());
935
936        let bin: BinaryExpr = find("x ≈ y\n");
937        assert!(bin.is_comparison());
938        let bin: BinaryExpr = find("x ⊗ y\n");
939        assert!(!bin.is_comparison());
940    }
941
942    #[test]
943    fn macro_name_identifier_components() {
944        let call: MacroCall = find("@Base.time f()\n");
945        let parts: Vec<_> = call
946            .name()
947            .unwrap()
948            .ident_tokens()
949            .map(|ident| ident.text().to_string())
950            .collect();
951        assert_eq!(parts, ["Base", "time"]);
952
953        let call: MacroCall = find("Base.@time f()\n");
954        let parts: Vec<_> = call
955            .name()
956            .unwrap()
957            .ident_tokens()
958            .map(|ident| ident.text().to_string())
959            .collect();
960        assert_eq!(parts, ["Base", "time"]);
961    }
962
963    #[test]
964    fn ternary_expr_test_and_arms() {
965        let ternary: TernaryExpr = find("c ? f(1) : g(2)\n");
966        assert_eq!(expr_text(ternary.condition()), "c");
967        assert_eq!(expr_text(ternary.then_branch()), "f(1)");
968        assert_eq!(expr_text(ternary.else_branch()), "g(2)");
969        // An incomplete ternary is still a `TERNARY_EXPR`; the missing arm is
970        // simply absent.
971        let ternary: TernaryExpr = find("c ? a\n");
972        assert_eq!(expr_text(ternary.then_branch()), "a");
973        assert!(ternary.else_branch().is_none());
974    }
975
976    #[test]
977    fn assignment_operands_and_operator() {
978        let assign: AssignmentExpr = find("x = f(1)\n");
979        assert_eq!(expr_text(assign.lhs()), "x");
980        assert!(matches!(assign.rhs(), Some(Expr::CallExpr(_))));
981        assert_eq!(assign.op().unwrap().text(), "=");
982    }
983
984    #[test]
985    fn call_callee_and_args() {
986        let call: CallExpr = find("g(a, b)\n");
987        assert_eq!(expr_text(call.callee()), "g");
988        let args = call.arg_list().expect("arg list");
989        let texts: Vec<String> = args
990            .args()
991            .map(|a| a.expr().unwrap().syntax().text().to_string())
992            .collect();
993        assert_eq!(texts, ["a", "b"]);
994    }
995
996    #[test]
997    fn type_annotation_splits_at_the_colons() {
998        let ann: TypeAnnotation = find("x::Int\n");
999        assert_eq!(expr_text(ann.pattern()), "x");
1000        assert_eq!(expr_text(ann.ty()), "Int");
1001        // The unnamed-argument form has no pattern.
1002        let ann: TypeAnnotation = find("f(::Int) = 1\n");
1003        assert!(ann.pattern().is_none());
1004        assert_eq!(expr_text(ann.ty()), "Int");
1005        // The type may be any expression, not just a name.
1006        let ann: TypeAnnotation = find("x::Union{Int,Nothing}\n");
1007        assert_eq!(expr_text(ann.ty()), "Union{Int,Nothing}");
1008    }
1009
1010    #[test]
1011    fn quote_sym_expr_is_the_quoted_node() {
1012        assert_eq!(expr_text(find::<QuoteSym>(":x\n").expr()), "x");
1013        assert_eq!(expr_text(find::<QuoteSym>(":(x + 1)\n").expr()), "(x + 1)");
1014        // A quoted operator or keyword is a bare token, not a node.
1015        assert!(find::<QuoteSym>(":+\n").expr().is_none());
1016        assert!(find::<QuoteSym>(":if\n").expr().is_none());
1017    }
1018
1019    #[test]
1020    fn parameters_split_plain_keywords_from_the_rest() {
1021        // A definition's annotated keyword parameter is an `ARG`, not a
1022        // `KEYWORD_ARG`.
1023        let params: Parameters = find("f(; y::Int = 1, z = 2) = y\n");
1024        let args: Vec<String> = params
1025            .args()
1026            .map(|a| a.syntax().text().to_string())
1027            .collect();
1028        assert_eq!(args, ["y::Int = 1"]);
1029        let kwargs: Vec<String> = params
1030            .keyword_args()
1031            .map(|k| k.syntax().text().to_string())
1032            .collect();
1033        assert_eq!(kwargs, ["z = 2"]);
1034        // At a call site, the shorthand and a splat are the `ARG`s.
1035        let params: Parameters = find("f(; verbose, kw...)\n");
1036        let args: Vec<String> = params
1037            .args()
1038            .map(|a| a.syntax().text().to_string())
1039            .collect();
1040        assert_eq!(args, ["verbose", "kw..."]);
1041    }
1042
1043    #[test]
1044    fn call_callee_ident_is_bare_names_only() {
1045        assert_eq!(
1046            find::<CallExpr>("g(a)\n").callee_ident().unwrap().text(),
1047            "g"
1048        );
1049        // A qualified, operator, computed, or `var\"...\"` callee has no bare
1050        // identifier to report.
1051        assert!(find::<CallExpr>("Base.g(a)\n").callee_ident().is_none());
1052        assert!(find::<CallExpr>("(!=)(a, b)\n").callee_ident().is_none());
1053        assert!(find::<CallExpr>("(h())(a)\n").callee_ident().is_none());
1054        assert!(find::<CallExpr>("var\"q\"(1)\n").callee_ident().is_none());
1055    }
1056
1057    #[test]
1058    fn expr_name_ident_reads_bare_name_operands() {
1059        let bin: BinaryExpr = find("x == missing\n");
1060        assert_eq!(bin.lhs().unwrap().name_ident().unwrap().text(), "x");
1061        assert_eq!(bin.rhs().unwrap().name_ident().unwrap().text(), "missing");
1062        // Anything that is not a bare `NAME` answers `None`.
1063        let bin: BinaryExpr = find("f(x) == 1\n");
1064        assert!(bin.lhs().unwrap().name_ident().is_none());
1065        assert!(bin.rhs().unwrap().name_ident().is_none());
1066    }
1067
1068    #[test]
1069    fn call_callee_operator_shapes() {
1070        // Bare, parenthesized, and qualified (`:!=` and `:(==)`) operator
1071        // callees all surface the operator token.
1072        let call: CallExpr = find("!=(a, b)\n");
1073        assert_eq!(call.callee_operator().unwrap().text(), "!=");
1074        let call: CallExpr = find("(!=)(a, b)\n");
1075        assert_eq!(call.callee_operator().unwrap().text(), "!=");
1076        let call: CallExpr = find("Base.:!=(a, b)\n");
1077        assert_eq!(call.callee_operator().unwrap().text(), "!=");
1078        let call: CallExpr = find("Base.:(==)(a, b)\n");
1079        assert_eq!(call.callee_operator().unwrap().text(), "==");
1080        // Ordinary callees have no operator name.
1081        let call: CallExpr = find("g(a, b)\n");
1082        assert!(call.callee_operator().is_none());
1083        let call: CallExpr = find("Base.g(a, b)\n");
1084        assert!(call.callee_operator().is_none());
1085    }
1086
1087    #[test]
1088    fn if_condition_body_and_else() {
1089        let if_expr: IfExpr = find("if x\n    1\nelse\n    2\nend\n");
1090        let cond = if_expr.condition().expect("condition");
1091        assert_eq!(expr_text(cond.expr()), "x");
1092        assert!(if_expr.then_body().is_some());
1093        assert!(if_expr.else_clause().and_then(|e| e.body()).is_some());
1094    }
1095
1096    #[test]
1097    fn literal_bool_token() {
1098        assert_eq!(
1099            find::<Literal>("true\n").bool_token().unwrap().text(),
1100            "true"
1101        );
1102        assert_eq!(
1103            find::<Literal>("false\n").bool_token().unwrap().text(),
1104            "false"
1105        );
1106        assert!(find::<Literal>("1\n").bool_token().is_none());
1107    }
1108
1109    #[test]
1110    fn literal_numeric_token() {
1111        assert_eq!(
1112            find::<Literal>("42\n").numeric_token().unwrap().text(),
1113            "42"
1114        );
1115        assert_eq!(
1116            find::<Literal>("3.5\n").numeric_token().unwrap().text(),
1117            "3.5"
1118        );
1119        assert_eq!(
1120            find::<Literal>("0xff\n").numeric_token().unwrap().text(),
1121            "0xff"
1122        );
1123        // Non-numeric literals have no numeric token.
1124        assert!(find::<Literal>("true\n").numeric_token().is_none());
1125    }
1126
1127    #[test]
1128    fn condition_unwraps_one_paren_layer() {
1129        let cond: Condition = find("if (x = 1)\n    1\nend\n");
1130        // A single paren layer is peeled: the inner assignment surfaces.
1131        assert!(matches!(cond.expr(), Some(Expr::AssignmentExpr(_))));
1132    }
1133
1134    #[test]
1135    fn function_signature_and_body() {
1136        let func: FunctionDef = find("function f(x)\n    x\nend\n");
1137        assert_eq!(expr_text(func.signature().and_then(|s| s.expr())), "f(x)");
1138        assert!(func.body().is_some());
1139    }
1140
1141    #[test]
1142    fn expr_dispatches_known_kinds() {
1143        assert!(matches!(
1144            Expr::cast(find::<CallExpr>("f()\n").syntax().clone()),
1145            Some(Expr::CallExpr(_))
1146        ));
1147        assert!(matches!(
1148            Expr::cast(find::<Name>("x\n").syntax().clone()),
1149            Some(Expr::Name(_))
1150        ));
1151    }
1152
1153    #[test]
1154    fn expr_falls_back_to_other_for_unwrapped_kinds() {
1155        // `a < b < c` parses to COMPARISON_EXPR, an expression kind with no
1156        // dedicated wrapper: it must still round-trip through `Expr::Other`,
1157        // not vanish.
1158        let cmp = parse("a < b < c\n")
1159            .cst
1160            .descendants()
1161            .find(|n| n.kind() == SyntaxKind::COMPARISON_EXPR)
1162            .expect("comparison expr");
1163        assert!(matches!(Expr::cast(cmp), Some(Expr::Other(_))));
1164    }
1165
1166    #[test]
1167    fn non_expression_nodes_do_not_cast_to_expr() {
1168        let sig = find::<FunctionDef>("function f()\nend\n")
1169            .signature()
1170            .unwrap();
1171        assert!(Expr::cast(sig.syntax().clone()).is_none());
1172    }
1173
1174    #[test]
1175    fn module_def_name_and_body() {
1176        let module: ModuleDef = find("module M\nx = 1\nend\n");
1177        assert_eq!(module.name().unwrap().syntax().text(), "M");
1178        assert!(module.body().is_some());
1179        let bare: ModuleDef = find("baremodule B\nend\n");
1180        assert_eq!(bare.name().unwrap().syntax().text(), "B");
1181    }
1182
1183    #[test]
1184    fn missing_children_yield_none() {
1185        // A bare `do` block has no `DO_PARAMS`.
1186        let do_expr: DoExpr = find("f() do\n    1\nend\n");
1187        assert!(do_expr.params().is_none());
1188    }
1189
1190    /// Every expression kind that has a wrapper must reach [`Expr`] through its
1191    /// own variant, never through `Other`. These five were accepted by
1192    /// [`is_expr_kind`] while `Expr::cast` had no arm for them, so they arrived
1193    /// as `Other` and callers hand-rolled a `SyntaxKind` check to recover them.
1194    #[test]
1195    fn wrapped_kinds_cast_to_their_own_variant() {
1196        /// Cast the first `kind` node in `src`.
1197        fn cast_first(src: &str, kind: SyntaxKind) -> Expr {
1198            let node = parse(src)
1199                .cst
1200                .descendants()
1201                .find(|n| n.kind() == kind)
1202                .unwrap_or_else(|| panic!("{kind:?} present in {src:?}"));
1203            Expr::cast(node).unwrap_or_else(|| panic!("{kind:?} casts to Expr"))
1204        }
1205
1206        assert!(matches!(
1207            cast_first(":x\n", SyntaxKind::QUOTE_SYM),
1208            Expr::QuoteSym(_)
1209        ));
1210        assert!(matches!(
1211            cast_first("struct S\nx\nend\n", SyntaxKind::STRUCT_DEF),
1212            Expr::StructDef(_)
1213        ));
1214        assert!(matches!(
1215            cast_first("abstract type T end\n", SyntaxKind::ABSTRACT_DEF),
1216            Expr::AbstractDef(_)
1217        ));
1218        assert!(matches!(
1219            cast_first("primitive type P 8 end\n", SyntaxKind::PRIMITIVE_DEF),
1220            Expr::PrimitiveDef(_)
1221        ));
1222        assert!(matches!(
1223            cast_first("module M\nend\n", SyntaxKind::MODULE_DEF),
1224            Expr::ModuleDef(_)
1225        ));
1226    }
1227
1228    /// `TYPEGROUP_DEF` is the one expression kind with no wrapper, so it is the
1229    /// only kind that legitimately reaches a consumer as `Expr::Other`.
1230    #[test]
1231    fn typegroup_def_is_the_only_wrapperless_expr_kind() {
1232        let node = parse("abstract type T end\n")
1233            .cst
1234            .descendants()
1235            .find(|n| n.kind() == SyntaxKind::TYPEGROUP_DEF);
1236        if let Some(node) = node {
1237            assert!(matches!(Expr::cast(node), Some(Expr::Other(_))));
1238        }
1239    }
1240
1241    #[test]
1242    fn body_of_and_condition_of_match_the_traits() {
1243        use crate::ast::traits::{body_of, condition_of};
1244
1245        let func: FunctionDef = find("function f()\n    1\nend\n");
1246        assert_eq!(
1247            body_of(func.syntax()).map(|b| b.text().to_string()),
1248            func.body().map(|b| b.syntax().text().to_string()),
1249        );
1250
1251        let while_expr: WhileExpr = find("while c\n    1\nend\n");
1252        assert_eq!(
1253            condition_of(while_expr.syntax()).map(|c| c.text().to_string()),
1254            while_expr
1255                .condition()
1256                .map(|c| c.syntax().text().to_string()),
1257        );
1258
1259        // A node with neither shape yields `None` rather than a stray child.
1260        let name: Name = find("x\n");
1261        assert!(body_of(name.syntax()).is_none());
1262        assert!(condition_of(name.syntax()).is_none());
1263    }
1264}