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!(Literal, SyntaxKind::LITERAL);
42ast_node!(StringLiteral, SyntaxKind::STRING_LITERAL);
43ast_node!(CmdLiteral, SyntaxKind::CMD_LITERAL);
44ast_node!(NonstandardIdentifier, SyntaxKind::NONSTANDARD_IDENTIFIER);
45ast_node!(Interpolation, SyntaxKind::INTERPOLATION);
46ast_node!(Name, SyntaxKind::NAME);
47ast_node!(BinaryExpr, SyntaxKind::BINARY_EXPR);
48ast_node!(UnaryExpr, SyntaxKind::UNARY_EXPR);
49ast_node!(ParenExpr, SyntaxKind::PAREN_EXPR);
50ast_node!(TupleExpr, SyntaxKind::TUPLE_EXPR);
51ast_node!(VectExpr, SyntaxKind::VECT_EXPR);
52ast_node!(MatrixExpr, SyntaxKind::MATRIX_EXPR);
53ast_node!(MatrixRow, SyntaxKind::MATRIX_ROW);
54ast_node!(Comprehension, SyntaxKind::COMPREHENSION);
55ast_node!(Generator, SyntaxKind::GENERATOR);
56ast_node!(ComprehensionIf, SyntaxKind::COMPREHENSION_IF);
57ast_node!(CallExpr, SyntaxKind::CALL_EXPR);
58ast_node!(IndexExpr, SyntaxKind::INDEX_EXPR);
59ast_node!(DotCallExpr, SyntaxKind::DOT_CALL_EXPR);
60ast_node!(CurlyExpr, SyntaxKind::CURLY_EXPR);
61ast_node!(Braces, SyntaxKind::BRACES);
62ast_node!(ArgList, SyntaxKind::ARG_LIST);
63ast_node!(Arg, SyntaxKind::ARG);
64ast_node!(KeywordArg, SyntaxKind::KEYWORD_ARG);
65ast_node!(Parameters, SyntaxKind::PARAMETERS);
66ast_node!(TypeAnnotation, SyntaxKind::TYPE_ANNOTATION);
67ast_node!(WhereExpr, SyntaxKind::WHERE_EXPR);
68ast_node!(SplatExpr, SyntaxKind::SPLAT_EXPR);
69ast_node!(EndMarker, SyntaxKind::END_MARKER);
70ast_node!(AssignmentExpr, SyntaxKind::ASSIGNMENT_EXPR);
71ast_node!(ArrowExpr, SyntaxKind::ARROW_EXPR);
72ast_node!(TernaryExpr, SyntaxKind::TERNARY_EXPR);
73ast_node!(IfExpr, SyntaxKind::IF_EXPR);
74ast_node!(ElseifClause, SyntaxKind::ELSEIF_CLAUSE);
75ast_node!(ElseClause, SyntaxKind::ELSE_CLAUSE);
76ast_node!(Condition, SyntaxKind::CONDITION);
77ast_node!(FunctionDef, SyntaxKind::FUNCTION_DEF);
78ast_node!(MacroDef, SyntaxKind::MACRO_DEF);
79ast_node!(Signature, SyntaxKind::SIGNATURE);
80ast_node!(Block, SyntaxKind::BLOCK);
81ast_node!(BeginExpr, SyntaxKind::BEGIN_EXPR);
82ast_node!(QuoteExpr, SyntaxKind::QUOTE_EXPR);
83ast_node!(QuoteSym, SyntaxKind::QUOTE_SYM);
84ast_node!(WhileExpr, SyntaxKind::WHILE_EXPR);
85ast_node!(ForExpr, SyntaxKind::FOR_EXPR);
86ast_node!(ForBinding, SyntaxKind::FOR_BINDING);
87ast_node!(LetExpr, SyntaxKind::LET_EXPR);
88ast_node!(LetBindings, SyntaxKind::LET_BINDINGS);
89ast_node!(TryExpr, SyntaxKind::TRY_EXPR);
90ast_node!(CatchClause, SyntaxKind::CATCH_CLAUSE);
91ast_node!(FinallyClause, SyntaxKind::FINALLY_CLAUSE);
92ast_node!(StructDef, SyntaxKind::STRUCT_DEF);
93ast_node!(AbstractDef, SyntaxKind::ABSTRACT_DEF);
94ast_node!(PrimitiveDef, SyntaxKind::PRIMITIVE_DEF);
95ast_node!(ModuleDef, SyntaxKind::MODULE_DEF);
96ast_node!(DoExpr, SyntaxKind::DO_EXPR);
97ast_node!(DoParams, SyntaxKind::DO_PARAMS);
98ast_node!(ReturnExpr, SyntaxKind::RETURN_EXPR);
99ast_node!(BreakExpr, SyntaxKind::BREAK_EXPR);
100ast_node!(ContinueExpr, SyntaxKind::CONTINUE_EXPR);
101ast_node!(ConstStmt, SyntaxKind::CONST_STMT);
102ast_node!(GlobalStmt, SyntaxKind::GLOBAL_STMT);
103ast_node!(LocalStmt, SyntaxKind::LOCAL_STMT);
104ast_node!(ImportStmt, SyntaxKind::IMPORT_STMT);
105ast_node!(UsingStmt, SyntaxKind::USING_STMT);
106ast_node!(ExportStmt, SyntaxKind::EXPORT_STMT);
107ast_node!(MacroCall, SyntaxKind::MACRO_CALL);
108ast_node!(MacroName, SyntaxKind::MACRO_NAME);
109
110/// The expression sum: any node that can appear in value position, cast to a
111/// dedicated variant when one exists and to [`Expr::Other`] otherwise.
112///
113/// `Other` keeps the sum *total* over expression kinds — the Julia grammar is a
114/// growing skeleton, so a kind that has no wrapper yet (e.g. `RANGE_EXPR`,
115/// `COMPARISON_EXPR`) still round-trips through `Expr` instead of being silently
116/// dropped from an operand accessor. Match `Other`'s [`SyntaxNode`] (or its
117/// [`kind`](SyntaxNode::kind)) for those.
118#[derive(Debug, Clone, PartialEq, Eq, Hash)]
119pub enum Expr {
120    Literal(Literal),
121    StringLiteral(StringLiteral),
122    CmdLiteral(CmdLiteral),
123    NonstandardIdentifier(NonstandardIdentifier),
124    Interpolation(Interpolation),
125    Name(Name),
126    BinaryExpr(BinaryExpr),
127    UnaryExpr(UnaryExpr),
128    ParenExpr(ParenExpr),
129    TupleExpr(TupleExpr),
130    VectExpr(VectExpr),
131    MatrixExpr(MatrixExpr),
132    Comprehension(Comprehension),
133    Generator(Generator),
134    CallExpr(CallExpr),
135    IndexExpr(IndexExpr),
136    DotCallExpr(DotCallExpr),
137    CurlyExpr(CurlyExpr),
138    Braces(Braces),
139    AssignmentExpr(AssignmentExpr),
140    ArrowExpr(ArrowExpr),
141    TernaryExpr(TernaryExpr),
142    IfExpr(IfExpr),
143    BeginExpr(BeginExpr),
144    QuoteExpr(QuoteExpr),
145    WhileExpr(WhileExpr),
146    ForExpr(ForExpr),
147    LetExpr(LetExpr),
148    TryExpr(TryExpr),
149    DoExpr(DoExpr),
150    FunctionDef(FunctionDef),
151    MacroCall(MacroCall),
152    SplatExpr(SplatExpr),
153    WhereExpr(WhereExpr),
154    TypeAnnotation(TypeAnnotation),
155    ReturnExpr(ReturnExpr),
156    BreakExpr(BreakExpr),
157    ContinueExpr(ContinueExpr),
158    /// An expression-position node without a dedicated variant (see the type
159    /// docs). Guaranteed to satisfy [`is_expr_kind`].
160    Other(SyntaxNode),
161}
162
163/// Whether `kind` is a node that can occur in expression (value) position. The
164/// complement is the structural scaffolding — clauses, argument lists,
165/// signatures, statements, blocks — plus every token kind.
166pub fn is_expr_kind(kind: SyntaxKind) -> bool {
167    use SyntaxKind::*;
168    matches!(
169        kind,
170        LITERAL
171            | STRING_LITERAL
172            | CMD_LITERAL
173            | NONSTANDARD_IDENTIFIER
174            | INTERPOLATION
175            | NAME
176            | BINARY_EXPR
177            | RANGE_EXPR
178            | COMPARISON_EXPR
179            | UNARY_EXPR
180            | PAREN_EXPR
181            | TUPLE_EXPR
182            | BARE_TUPLE_EXPR
183            | PAREN_BLOCK
184            | VECT_EXPR
185            | MATRIX_EXPR
186            | TYPED_MATRIX_EXPR
187            | BRACESCAT_EXPR
188            | COMPREHENSION
189            | BRACES_COMPREHENSION
190            | TYPED_COMPREHENSION
191            | GENERATOR
192            | CALL_EXPR
193            | INDEX_EXPR
194            | DOT_CALL_EXPR
195            | CURLY_EXPR
196            | BRACES
197            | TYPE_ANNOTATION
198            | WHERE_EXPR
199            | SPLAT_EXPR
200            | POSTFIX_EXPR
201            | OPERATOR_ATOM
202            | ASSIGNMENT_EXPR
203            | ARROW_EXPR
204            | JUXTAPOSE_EXPR
205            | TERNARY_EXPR
206            | IF_EXPR
207            | FUNCTION_DEF
208            | BEGIN_EXPR
209            | WHILE_EXPR
210            | FOR_EXPR
211            | LET_EXPR
212            | QUOTE_EXPR
213            | QUOTE_SYM
214            | TRY_EXPR
215            | STRUCT_DEF
216            | ABSTRACT_DEF
217            | PRIMITIVE_DEF
218            | TYPEGROUP_DEF
219            | MODULE_DEF
220            | DO_EXPR
221            | RETURN_EXPR
222            | BREAK_EXPR
223            | CONTINUE_EXPR
224            | MACRO_CALL
225    )
226}
227
228impl AstNode for Expr {
229    type Language = JuliaLanguage;
230
231    fn can_cast(kind: SyntaxKind) -> bool {
232        is_expr_kind(kind)
233    }
234
235    fn cast(syntax: SyntaxNode) -> Option<Self> {
236        let expr = match syntax.kind() {
237            SyntaxKind::LITERAL => Expr::Literal(Literal(syntax)),
238            SyntaxKind::STRING_LITERAL => Expr::StringLiteral(StringLiteral(syntax)),
239            SyntaxKind::CMD_LITERAL => Expr::CmdLiteral(CmdLiteral(syntax)),
240            SyntaxKind::NONSTANDARD_IDENTIFIER => {
241                Expr::NonstandardIdentifier(NonstandardIdentifier(syntax))
242            }
243            SyntaxKind::INTERPOLATION => Expr::Interpolation(Interpolation(syntax)),
244            SyntaxKind::NAME => Expr::Name(Name(syntax)),
245            SyntaxKind::BINARY_EXPR => Expr::BinaryExpr(BinaryExpr(syntax)),
246            SyntaxKind::UNARY_EXPR => Expr::UnaryExpr(UnaryExpr(syntax)),
247            SyntaxKind::PAREN_EXPR => Expr::ParenExpr(ParenExpr(syntax)),
248            SyntaxKind::TUPLE_EXPR => Expr::TupleExpr(TupleExpr(syntax)),
249            SyntaxKind::VECT_EXPR => Expr::VectExpr(VectExpr(syntax)),
250            SyntaxKind::MATRIX_EXPR => Expr::MatrixExpr(MatrixExpr(syntax)),
251            SyntaxKind::COMPREHENSION => Expr::Comprehension(Comprehension(syntax)),
252            SyntaxKind::GENERATOR => Expr::Generator(Generator(syntax)),
253            SyntaxKind::CALL_EXPR => Expr::CallExpr(CallExpr(syntax)),
254            SyntaxKind::INDEX_EXPR => Expr::IndexExpr(IndexExpr(syntax)),
255            SyntaxKind::DOT_CALL_EXPR => Expr::DotCallExpr(DotCallExpr(syntax)),
256            SyntaxKind::CURLY_EXPR => Expr::CurlyExpr(CurlyExpr(syntax)),
257            SyntaxKind::BRACES => Expr::Braces(Braces(syntax)),
258            SyntaxKind::ASSIGNMENT_EXPR => Expr::AssignmentExpr(AssignmentExpr(syntax)),
259            SyntaxKind::ARROW_EXPR => Expr::ArrowExpr(ArrowExpr(syntax)),
260            SyntaxKind::TERNARY_EXPR => Expr::TernaryExpr(TernaryExpr(syntax)),
261            SyntaxKind::IF_EXPR => Expr::IfExpr(IfExpr(syntax)),
262            SyntaxKind::BEGIN_EXPR => Expr::BeginExpr(BeginExpr(syntax)),
263            SyntaxKind::QUOTE_EXPR => Expr::QuoteExpr(QuoteExpr(syntax)),
264            SyntaxKind::WHILE_EXPR => Expr::WhileExpr(WhileExpr(syntax)),
265            SyntaxKind::FOR_EXPR => Expr::ForExpr(ForExpr(syntax)),
266            SyntaxKind::LET_EXPR => Expr::LetExpr(LetExpr(syntax)),
267            SyntaxKind::TRY_EXPR => Expr::TryExpr(TryExpr(syntax)),
268            SyntaxKind::DO_EXPR => Expr::DoExpr(DoExpr(syntax)),
269            SyntaxKind::FUNCTION_DEF => Expr::FunctionDef(FunctionDef(syntax)),
270            SyntaxKind::MACRO_CALL => Expr::MacroCall(MacroCall(syntax)),
271            SyntaxKind::SPLAT_EXPR => Expr::SplatExpr(SplatExpr(syntax)),
272            SyntaxKind::WHERE_EXPR => Expr::WhereExpr(WhereExpr(syntax)),
273            SyntaxKind::TYPE_ANNOTATION => Expr::TypeAnnotation(TypeAnnotation(syntax)),
274            SyntaxKind::RETURN_EXPR => Expr::ReturnExpr(ReturnExpr(syntax)),
275            SyntaxKind::BREAK_EXPR => Expr::BreakExpr(BreakExpr(syntax)),
276            SyntaxKind::CONTINUE_EXPR => Expr::ContinueExpr(ContinueExpr(syntax)),
277            kind if is_expr_kind(kind) => Expr::Other(syntax),
278            _ => return None,
279        };
280        Some(expr)
281    }
282
283    fn syntax(&self) -> &SyntaxNode {
284        match self {
285            Expr::Literal(it) => it.syntax(),
286            Expr::StringLiteral(it) => it.syntax(),
287            Expr::CmdLiteral(it) => it.syntax(),
288            Expr::NonstandardIdentifier(it) => it.syntax(),
289            Expr::Interpolation(it) => it.syntax(),
290            Expr::Name(it) => it.syntax(),
291            Expr::BinaryExpr(it) => it.syntax(),
292            Expr::UnaryExpr(it) => it.syntax(),
293            Expr::ParenExpr(it) => it.syntax(),
294            Expr::TupleExpr(it) => it.syntax(),
295            Expr::VectExpr(it) => it.syntax(),
296            Expr::MatrixExpr(it) => it.syntax(),
297            Expr::Comprehension(it) => it.syntax(),
298            Expr::Generator(it) => it.syntax(),
299            Expr::CallExpr(it) => it.syntax(),
300            Expr::IndexExpr(it) => it.syntax(),
301            Expr::DotCallExpr(it) => it.syntax(),
302            Expr::CurlyExpr(it) => it.syntax(),
303            Expr::Braces(it) => it.syntax(),
304            Expr::AssignmentExpr(it) => it.syntax(),
305            Expr::ArrowExpr(it) => it.syntax(),
306            Expr::TernaryExpr(it) => it.syntax(),
307            Expr::IfExpr(it) => it.syntax(),
308            Expr::BeginExpr(it) => it.syntax(),
309            Expr::QuoteExpr(it) => it.syntax(),
310            Expr::WhileExpr(it) => it.syntax(),
311            Expr::ForExpr(it) => it.syntax(),
312            Expr::LetExpr(it) => it.syntax(),
313            Expr::TryExpr(it) => it.syntax(),
314            Expr::DoExpr(it) => it.syntax(),
315            Expr::FunctionDef(it) => it.syntax(),
316            Expr::MacroCall(it) => it.syntax(),
317            Expr::SplatExpr(it) => it.syntax(),
318            Expr::WhereExpr(it) => it.syntax(),
319            Expr::TypeAnnotation(it) => it.syntax(),
320            Expr::ReturnExpr(it) => it.syntax(),
321            Expr::BreakExpr(it) => it.syntax(),
322            Expr::ContinueExpr(it) => it.syntax(),
323            Expr::Other(it) => it,
324        }
325    }
326}
327
328impl Expr {
329    /// The identifier token, when this expression is a bare name (`x`). `None`
330    /// for every compound shape, including a qualified path (`M.x`), which is a
331    /// `BINARY_EXPR`, and a `var"..."` identifier, which has no `IDENT` token.
332    pub fn name_ident(&self) -> Option<Ident> {
333        match self {
334            Expr::Name(name) => name.ident(),
335            _ => None,
336        }
337    }
338}
339
340impl Name {
341    /// The identifier token.
342    pub fn ident(&self) -> Option<Ident> {
343        child_token(&self.0)
344    }
345}
346
347impl Literal {
348    /// The `true`/`false` keyword token, when the literal is a boolean.
349    pub fn bool_token(&self) -> Option<SyntaxToken> {
350        support::token(&self.0, SyntaxKind::TRUE_KW)
351            .or_else(|| support::token(&self.0, SyntaxKind::FALSE_KW))
352    }
353
354    /// The numeric value token, when the literal is a number: an integer (any
355    /// base) or a float. `None` for non-numeric literals (booleans, `nothing`).
356    pub fn numeric_token(&self) -> Option<SyntaxToken> {
357        self.0
358            .children_with_tokens()
359            .filter_map(|el| el.into_token())
360            .find(|t| {
361                matches!(
362                    t.kind(),
363                    SyntaxKind::INTEGER
364                        | SyntaxKind::BIN_INT
365                        | SyntaxKind::OCT_INT
366                        | SyntaxKind::HEX_INT
367                        | SyntaxKind::FLOAT
368                        | SyntaxKind::FLOAT32
369                )
370            })
371    }
372}
373
374impl NonstandardIdentifier {
375    /// The quoted body of a `var"..."` identifier (its `STRING_CONTENT` token).
376    pub fn content(&self) -> Option<SyntaxToken> {
377        support::token(&self.0, SyntaxKind::STRING_CONTENT)
378    }
379}
380
381impl StringLiteral {
382    /// The non-standard literal prefix token, e.g. `r` in `r"..."`.
383    pub fn prefix(&self) -> Option<SyntaxToken> {
384        support::token(&self.0, SyntaxKind::STRING_PREFIX)
385    }
386
387    /// The suffix flag token, e.g. `ims` in `r"pat"ims`.
388    pub fn suffix(&self) -> Option<SyntaxToken> {
389        support::token(&self.0, SyntaxKind::STRING_SUFFIX)
390    }
391
392    /// The interpolations embedded in the string, in source order.
393    pub fn interpolations(&self) -> AstChildren<Interpolation> {
394        support::children(&self.0)
395    }
396
397    /// The `STRING_CONTENT` chunks of the literal, in source order. A plain
398    /// (non-interpolated) string joins to its full text.
399    pub fn content_tokens(&self) -> impl Iterator<Item = SyntaxToken> {
400        self.0
401            .children_with_tokens()
402            .filter_map(|el| el.into_token())
403            .filter(|t| t.kind() == SyntaxKind::STRING_CONTENT)
404    }
405}
406
407impl CmdLiteral {
408    /// The non-standard literal prefix token, e.g. `` v `` in `` v`...` ``.
409    pub fn prefix(&self) -> Option<SyntaxToken> {
410        support::token(&self.0, SyntaxKind::STRING_PREFIX)
411    }
412
413    /// The suffix flag token following the closing backtick.
414    pub fn suffix(&self) -> Option<SyntaxToken> {
415        support::token(&self.0, SyntaxKind::STRING_SUFFIX)
416    }
417
418    /// The interpolations embedded in the command, in source order.
419    pub fn interpolations(&self) -> AstChildren<Interpolation> {
420        support::children(&self.0)
421    }
422}
423
424impl Interpolation {
425    /// The bare interpolated identifier token for `$ident` (absent for `$(expr)`).
426    pub fn ident(&self) -> Option<Ident> {
427        child_token(&self.0)
428    }
429
430    /// The interpolated expression for `$(expr)` (absent for `$ident`).
431    pub fn expr(&self) -> Option<Expr> {
432        support::child(&self.0)
433    }
434}
435
436impl BinaryExpr {
437    /// The left operand.
438    pub fn lhs(&self) -> Option<Expr> {
439        support::child(&self.0)
440    }
441
442    /// The right operand.
443    pub fn rhs(&self) -> Option<Expr> {
444        support::children(&self.0).nth(1)
445    }
446
447    /// The operator token (the first operator between the operands).
448    pub fn op(&self) -> Option<Operator> {
449        child_token(&self.0)
450    }
451}
452
453impl AssignmentExpr {
454    /// The assignment target (left of the operator).
455    pub fn lhs(&self) -> Option<Expr> {
456        support::child(&self.0)
457    }
458
459    /// The assigned value (right of the operator).
460    pub fn rhs(&self) -> Option<Expr> {
461        support::children(&self.0).nth(1)
462    }
463
464    /// The assignment operator token (`=`, `+=`, `.=`, ...).
465    pub fn op(&self) -> Option<Operator> {
466        child_token(&self.0)
467    }
468}
469
470impl ArrowExpr {
471    /// The parameter side (left of `->`).
472    pub fn lhs(&self) -> Option<Expr> {
473        support::child(&self.0)
474    }
475
476    /// The body side (right of `->`).
477    pub fn rhs(&self) -> Option<Expr> {
478        support::children(&self.0).nth(1)
479    }
480}
481
482impl TernaryExpr {
483    /// The test (left of `?`).
484    pub fn condition(&self) -> Option<Expr> {
485        support::child(&self.0)
486    }
487
488    /// The arm taken when the test holds (between `?` and `:`).
489    pub fn then_branch(&self) -> Option<Expr> {
490        support::children(&self.0).nth(1)
491    }
492
493    /// The arm taken otherwise (right of `:`). `None` for an incomplete
494    /// ternary, which the parser still shapes as a `TERNARY_EXPR`.
495    pub fn else_branch(&self) -> Option<Expr> {
496        support::children(&self.0).nth(2)
497    }
498}
499
500impl UnaryExpr {
501    /// The operator token.
502    pub fn op(&self) -> Option<Operator> {
503        child_token(&self.0)
504    }
505
506    /// The operand.
507    pub fn operand(&self) -> Option<Expr> {
508        support::child(&self.0)
509    }
510}
511
512impl SplatExpr {
513    /// The splatted expression (the `x` in `x...`).
514    pub fn expr(&self) -> Option<Expr> {
515        support::child(&self.0)
516    }
517}
518
519impl ParenExpr {
520    /// The parenthesized inner expression.
521    pub fn expr(&self) -> Option<Expr> {
522        support::child(&self.0)
523    }
524}
525
526impl CallExpr {
527    /// The callee (the expression being called).
528    pub fn callee(&self) -> Option<Expr> {
529        support::child(&self.0)
530    }
531
532    /// The identifier naming the callee, when the callee is a bare name
533    /// (`f(x)`). `None` for every compound callee: a qualified path
534    /// (`Base.f(x)`), an operator ([`Self::callee_operator`]), a `var"..."`
535    /// name, and a computed one (`g()(x)`).
536    pub fn callee_ident(&self) -> Option<Ident> {
537        match self.callee()? {
538            Expr::Name(name) => name.ident(),
539            _ => None,
540        }
541    }
542
543    /// The operator token naming the callee, when the callee is an operator
544    /// rather than an ordinary expression: bare (`!=(a, b)`), parenthesized
545    /// (`(!=)(a, b)`), or the quoted symbol ending a qualified path
546    /// (`Base.:!=(a, b)`, `Base.:(==)(a, b)`). `None` for every other callee
547    /// shape.
548    pub fn callee_operator(&self) -> Option<Operator> {
549        for el in self.0.children_with_tokens() {
550            match el {
551                rowan::NodeOrToken::Token(token) => {
552                    if let Some(op) = Operator::cast(token) {
553                        return Some(op);
554                    }
555                }
556                rowan::NodeOrToken::Node(node) => {
557                    return match node.kind() {
558                        SyntaxKind::PAREN_EXPR => paren_operator(&node),
559                        // A qualified path callee (`Base.:!=`): the operator is
560                        // the quoted symbol ending the path.
561                        SyntaxKind::BINARY_EXPR => node
562                            .children()
563                            .last()
564                            .filter(|last| last.kind() == SyntaxKind::QUOTE_SYM)
565                            .and_then(|quote| quote_sym_operator(&quote)),
566                        _ => None,
567                    };
568                }
569            }
570        }
571        None
572    }
573}
574
575/// The lone operator inside a `PAREN_EXPR` (`(!=)`, `:(==)`), if any. The
576/// operator is either a direct token or wrapped in an `OPERATOR_ATOM` (the
577/// operator-as-value node a quote-paren builds).
578fn paren_operator(paren: &SyntaxNode) -> Option<Operator> {
579    paren.children_with_tokens().find_map(|el| match el {
580        rowan::NodeOrToken::Token(token) => Operator::cast(token),
581        rowan::NodeOrToken::Node(node) if node.kind() == SyntaxKind::OPERATOR_ATOM => node
582            .children_with_tokens()
583            .filter_map(|el| el.into_token())
584            .find_map(Operator::cast),
585        rowan::NodeOrToken::Node(_) => None,
586    })
587}
588
589/// The operator a `QUOTE_SYM` quotes (`:!=`, `:(==)`), skipping the leading
590/// quoting `:` (itself an operator kind).
591fn quote_sym_operator(quote: &SyntaxNode) -> Option<Operator> {
592    let mut seen_quote_colon = false;
593    for el in quote.children_with_tokens() {
594        match el {
595            rowan::NodeOrToken::Token(token) => {
596                if !seen_quote_colon && token.kind() == SyntaxKind::COLON {
597                    seen_quote_colon = true;
598                } else if let Some(op) = Operator::cast(token) {
599                    return Some(op);
600                }
601            }
602            rowan::NodeOrToken::Node(node) if node.kind() == SyntaxKind::PAREN_EXPR => {
603                return paren_operator(&node);
604            }
605            _ => {}
606        }
607    }
608    None
609}
610
611impl IndexExpr {
612    /// The expression being indexed.
613    pub fn base(&self) -> Option<Expr> {
614        support::child(&self.0)
615    }
616}
617
618impl DotCallExpr {
619    /// The callee of the broadcast call.
620    pub fn callee(&self) -> Option<Expr> {
621        support::child(&self.0)
622    }
623}
624
625impl CurlyExpr {
626    /// The base expression the type parameters apply to, e.g. `Vector` in
627    /// `Vector{T}`.
628    pub fn base(&self) -> Option<Expr> {
629        support::child(&self.0)
630    }
631}
632
633impl ArgList {
634    /// The positional/keyword argument nodes (`ARG`, `KEYWORD_ARG`), in source
635    /// order. Each [`Arg`] wraps the argument expression; keyword arguments are
636    /// reached via [`Self::keyword_args`].
637    pub fn args(&self) -> AstChildren<Arg> {
638        support::children(&self.0)
639    }
640
641    /// The keyword arguments (`x = v`), in source order.
642    pub fn keyword_args(&self) -> AstChildren<KeywordArg> {
643        support::children(&self.0)
644    }
645}
646
647impl Arg {
648    /// The argument's expression.
649    pub fn expr(&self) -> Option<Expr> {
650        support::child(&self.0)
651    }
652}
653
654impl KeywordArg {
655    /// The keyword name (the left of `=`).
656    pub fn name(&self) -> Option<Name> {
657        support::child(&self.0)
658    }
659
660    /// The keyword value (the right of `=`).
661    pub fn value(&self) -> Option<Expr> {
662        support::children(&self.0).nth(1)
663    }
664}
665
666impl MacroCall {
667    /// The macro name, e.g. `@m`, `@.`, or `Base.@time`.
668    pub fn name(&self) -> Option<MacroName> {
669        support::child(&self.0)
670    }
671}
672
673impl MacroName {
674    /// The macro's simple-name token: the final `IDENT` (e.g. `time` in
675    /// `Base.@time`), or the `DOT` for the broadcast macro `@.`.
676    pub fn macro_token(&self) -> Option<SyntaxToken> {
677        self.0
678            .children_with_tokens()
679            .filter_map(|e| e.into_token())
680            .filter(|t| matches!(t.kind(), SyntaxKind::IDENT | SyntaxKind::DOT))
681            .last()
682    }
683}
684
685impl TypeAnnotation {
686    /// The `::` operator token.
687    pub fn op(&self) -> Option<SyntaxToken> {
688        support::token(&self.0, SyntaxKind::COLON_COLON)
689    }
690}
691
692impl IfExpr {
693    /// The `then` branch block. (The condition is [`HasCondition::condition`](crate::ast::traits::HasCondition::condition).)
694    pub fn then_body(&self) -> Option<Block> {
695        support::child(&self.0)
696    }
697
698    /// The `elseif` clauses, in source order.
699    pub fn elseif_clauses(&self) -> AstChildren<ElseifClause> {
700        support::children(&self.0)
701    }
702
703    /// The trailing `else` clause, if any.
704    pub fn else_clause(&self) -> Option<ElseClause> {
705        support::child(&self.0)
706    }
707}
708
709impl Condition {
710    /// The test expression, unwrapping a single parenthesized layer
711    /// (`if (x) ...` yields the `x`). Centralizes the paren-unwrap that
712    /// condition consumers would otherwise hand-roll.
713    pub fn expr(&self) -> Option<Expr> {
714        match support::child::<Expr>(&self.0)? {
715            Expr::ParenExpr(paren) => paren.expr(),
716            other => Some(other),
717        }
718    }
719}
720
721impl FunctionDef {
722    /// The function signature, e.g. `g(x)`.
723    pub fn signature(&self) -> Option<Signature> {
724        support::child(&self.0)
725    }
726}
727
728impl Signature {
729    /// The signature's core expression (a `CALL_EXPR`, a bare `NAME`, ...).
730    pub fn expr(&self) -> Option<Expr> {
731        support::child(&self.0)
732    }
733}
734
735impl ModuleDef {
736    /// The module's name, e.g. `M` in `module M ... end`. (The body is
737    /// [`HasBody::body`](crate::ast::traits::HasBody::body).)
738    pub fn name(&self) -> Option<Name> {
739        support::child::<Signature>(&self.0).and_then(|sig| support::child(&sig.0))
740    }
741}
742
743impl ForBinding {
744    /// The loop variable/pattern (left of `in`/`=`).
745    pub fn pattern(&self) -> Option<Expr> {
746        support::child(&self.0)
747    }
748
749    /// The iterable expression (right of `in`/`=`).
750    pub fn iterable(&self) -> Option<Expr> {
751        support::children(&self.0).nth(1)
752    }
753}
754
755impl CatchClause {
756    /// The bound exception variable (`catch e`), if named. (The body is
757    /// [`HasBody::body`](crate::ast::traits::HasBody::body).)
758    pub fn variable(&self) -> Option<Name> {
759        support::child(&self.0)
760    }
761}
762
763impl DoExpr {
764    /// The parameters on the `do` line, e.g. `x, y` in `f(a) do x, y`. Absent for
765    /// a bare `do`.
766    pub fn params(&self) -> Option<DoParams> {
767        support::child(&self.0)
768    }
769}
770
771impl Root {
772    /// The top-level items of the file, in source order.
773    pub fn items(&self) -> AstChildren<Expr> {
774        support::children(&self.0)
775    }
776}
777
778#[cfg(test)]
779mod tests {
780    use super::*;
781    use crate::ast::tokens::AstToken;
782    use crate::ast::traits::{HasArgList, HasBody, HasCondition};
783    use crate::parser::parse;
784
785    /// The first node in the parse of `src` castable to `T`.
786    fn find<T: AstNode<Language = JuliaLanguage>>(src: &str) -> T {
787        parse(src)
788            .cst
789            .descendants()
790            .find_map(T::cast)
791            .expect("node of the requested kind present")
792    }
793
794    fn expr_text(expr: Option<Expr>) -> String {
795        expr.expect("expression present")
796            .syntax()
797            .text()
798            .to_string()
799    }
800
801    #[test]
802    fn binary_expr_operands_and_operator() {
803        let bin: BinaryExpr = find("a + b\n");
804        assert_eq!(expr_text(bin.lhs()), "a");
805        assert_eq!(expr_text(bin.rhs()), "b");
806        assert_eq!(bin.op().unwrap().text(), "+");
807    }
808
809    #[test]
810    fn ternary_expr_test_and_arms() {
811        let ternary: TernaryExpr = find("c ? f(1) : g(2)\n");
812        assert_eq!(expr_text(ternary.condition()), "c");
813        assert_eq!(expr_text(ternary.then_branch()), "f(1)");
814        assert_eq!(expr_text(ternary.else_branch()), "g(2)");
815        // An incomplete ternary is still a `TERNARY_EXPR`; the missing arm is
816        // simply absent.
817        let ternary: TernaryExpr = find("c ? a\n");
818        assert_eq!(expr_text(ternary.then_branch()), "a");
819        assert!(ternary.else_branch().is_none());
820    }
821
822    #[test]
823    fn assignment_operands_and_operator() {
824        let assign: AssignmentExpr = find("x = f(1)\n");
825        assert_eq!(expr_text(assign.lhs()), "x");
826        assert!(matches!(assign.rhs(), Some(Expr::CallExpr(_))));
827        assert_eq!(assign.op().unwrap().text(), "=");
828    }
829
830    #[test]
831    fn call_callee_and_args() {
832        let call: CallExpr = find("g(a, b)\n");
833        assert_eq!(expr_text(call.callee()), "g");
834        let args = call.arg_list().expect("arg list");
835        let texts: Vec<String> = args
836            .args()
837            .map(|a| a.expr().unwrap().syntax().text().to_string())
838            .collect();
839        assert_eq!(texts, ["a", "b"]);
840    }
841
842    #[test]
843    fn call_callee_ident_is_bare_names_only() {
844        assert_eq!(
845            find::<CallExpr>("g(a)\n").callee_ident().unwrap().text(),
846            "g"
847        );
848        // A qualified, operator, computed, or `var\"...\"` callee has no bare
849        // identifier to report.
850        assert!(find::<CallExpr>("Base.g(a)\n").callee_ident().is_none());
851        assert!(find::<CallExpr>("(!=)(a, b)\n").callee_ident().is_none());
852        assert!(find::<CallExpr>("(h())(a)\n").callee_ident().is_none());
853        assert!(find::<CallExpr>("var\"q\"(1)\n").callee_ident().is_none());
854    }
855
856    #[test]
857    fn expr_name_ident_reads_bare_name_operands() {
858        let bin: BinaryExpr = find("x == missing\n");
859        assert_eq!(bin.lhs().unwrap().name_ident().unwrap().text(), "x");
860        assert_eq!(bin.rhs().unwrap().name_ident().unwrap().text(), "missing");
861        // Anything that is not a bare `NAME` answers `None`.
862        let bin: BinaryExpr = find("f(x) == 1\n");
863        assert!(bin.lhs().unwrap().name_ident().is_none());
864        assert!(bin.rhs().unwrap().name_ident().is_none());
865    }
866
867    #[test]
868    fn call_callee_operator_shapes() {
869        // Bare, parenthesized, and qualified (`:!=` and `:(==)`) operator
870        // callees all surface the operator token.
871        let call: CallExpr = find("!=(a, b)\n");
872        assert_eq!(call.callee_operator().unwrap().text(), "!=");
873        let call: CallExpr = find("(!=)(a, b)\n");
874        assert_eq!(call.callee_operator().unwrap().text(), "!=");
875        let call: CallExpr = find("Base.:!=(a, b)\n");
876        assert_eq!(call.callee_operator().unwrap().text(), "!=");
877        let call: CallExpr = find("Base.:(==)(a, b)\n");
878        assert_eq!(call.callee_operator().unwrap().text(), "==");
879        // Ordinary callees have no operator name.
880        let call: CallExpr = find("g(a, b)\n");
881        assert!(call.callee_operator().is_none());
882        let call: CallExpr = find("Base.g(a, b)\n");
883        assert!(call.callee_operator().is_none());
884    }
885
886    #[test]
887    fn if_condition_body_and_else() {
888        let if_expr: IfExpr = find("if x\n    1\nelse\n    2\nend\n");
889        let cond = if_expr.condition().expect("condition");
890        assert_eq!(expr_text(cond.expr()), "x");
891        assert!(if_expr.then_body().is_some());
892        assert!(if_expr.else_clause().and_then(|e| e.body()).is_some());
893    }
894
895    #[test]
896    fn literal_bool_token() {
897        assert_eq!(
898            find::<Literal>("true\n").bool_token().unwrap().text(),
899            "true"
900        );
901        assert_eq!(
902            find::<Literal>("false\n").bool_token().unwrap().text(),
903            "false"
904        );
905        assert!(find::<Literal>("1\n").bool_token().is_none());
906    }
907
908    #[test]
909    fn literal_numeric_token() {
910        assert_eq!(
911            find::<Literal>("42\n").numeric_token().unwrap().text(),
912            "42"
913        );
914        assert_eq!(
915            find::<Literal>("3.5\n").numeric_token().unwrap().text(),
916            "3.5"
917        );
918        assert_eq!(
919            find::<Literal>("0xff\n").numeric_token().unwrap().text(),
920            "0xff"
921        );
922        // Non-numeric literals have no numeric token.
923        assert!(find::<Literal>("true\n").numeric_token().is_none());
924    }
925
926    #[test]
927    fn condition_unwraps_one_paren_layer() {
928        let cond: Condition = find("if (x = 1)\n    1\nend\n");
929        // A single paren layer is peeled: the inner assignment surfaces.
930        assert!(matches!(cond.expr(), Some(Expr::AssignmentExpr(_))));
931    }
932
933    #[test]
934    fn function_signature_and_body() {
935        let func: FunctionDef = find("function f(x)\n    x\nend\n");
936        assert_eq!(expr_text(func.signature().and_then(|s| s.expr())), "f(x)");
937        assert!(func.body().is_some());
938    }
939
940    #[test]
941    fn expr_dispatches_known_kinds() {
942        assert!(matches!(
943            Expr::cast(find::<CallExpr>("f()\n").syntax().clone()),
944            Some(Expr::CallExpr(_))
945        ));
946        assert!(matches!(
947            Expr::cast(find::<Name>("x\n").syntax().clone()),
948            Some(Expr::Name(_))
949        ));
950    }
951
952    #[test]
953    fn expr_falls_back_to_other_for_unwrapped_kinds() {
954        // `a < b < c` parses to COMPARISON_EXPR, an expression kind with no
955        // dedicated wrapper: it must still round-trip through `Expr::Other`,
956        // not vanish.
957        let cmp = parse("a < b < c\n")
958            .cst
959            .descendants()
960            .find(|n| n.kind() == SyntaxKind::COMPARISON_EXPR)
961            .expect("comparison expr");
962        assert!(matches!(Expr::cast(cmp), Some(Expr::Other(_))));
963    }
964
965    #[test]
966    fn non_expression_nodes_do_not_cast_to_expr() {
967        let sig = find::<FunctionDef>("function f()\nend\n")
968            .signature()
969            .unwrap();
970        assert!(Expr::cast(sig.syntax().clone()).is_none());
971    }
972
973    #[test]
974    fn module_def_name_and_body() {
975        let module: ModuleDef = find("module M\nx = 1\nend\n");
976        assert_eq!(module.name().unwrap().syntax().text(), "M");
977        assert!(module.body().is_some());
978        let bare: ModuleDef = find("baremodule B\nend\n");
979        assert_eq!(bare.name().unwrap().syntax().text(), "B");
980    }
981
982    #[test]
983    fn missing_children_yield_none() {
984        // A bare `do` block has no `DO_PARAMS`.
985        let do_expr: DoExpr = find("f() do\n    1\nend\n");
986        assert!(do_expr.params().is_none());
987    }
988}