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