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    /// The annotated pattern — what stands *left* of the `::`. Absent for the
692    /// unnamed-argument form `::Int`, where the `::` precedes the only child.
693    pub fn pattern(&self) -> Option<Expr> {
694        let op = self.op()?;
695        support::children::<Expr>(&self.0)
696            .find(|expr| expr.syntax().text_range().end() <= op.text_range().start())
697    }
698
699    /// The declared type — what stands *right* of the `::`.
700    pub fn ty(&self) -> Option<Expr> {
701        let op = self.op()?;
702        support::children::<Expr>(&self.0)
703            .find(|expr| expr.syntax().text_range().start() >= op.text_range().end())
704    }
705}
706
707impl QuoteSym {
708    /// The quoted expression: `x` in `:x`, `(x + 1)` in `:(x + 1)`. Absent for
709    /// a quoted operator or keyword (`:+`, `:if`), which the parser carries as
710    /// a bare token rather than a node.
711    ///
712    /// Note that a `QUOTE_SYM` is not always a `Symbol` at runtime: `:x` is,
713    /// but `:(x + 1)` evaluates to an `Expr`.
714    pub fn expr(&self) -> Option<Expr> {
715        support::child(&self.0)
716    }
717}
718
719impl Parameters {
720    /// The keyword parameters written without a `::` annotation (`y = 1`), in
721    /// source order.
722    ///
723    /// The `;`-block splits by shape rather than by role: a *plain* keyword is
724    /// a `KEYWORD_ARG`, while an annotated parameter (`y::Int = 1`) and the
725    /// call-site shorthand (`f(; verbose)`) both arrive as [`Arg`]s — see
726    /// [`Self::args`].
727    pub fn keyword_args(&self) -> AstChildren<KeywordArg> {
728        support::children(&self.0)
729    }
730
731    /// The `;`-block entries that are not plain `KEYWORD_ARG`s, in source
732    /// order: an annotated keyword parameter (`y::Int = 1`), the call-site
733    /// shorthand (`f(; verbose)`), and a keyword splat (`f(; kw...)`).
734    pub fn args(&self) -> AstChildren<Arg> {
735        support::children(&self.0)
736    }
737}
738
739impl IfExpr {
740    /// The `then` branch block. (The condition is [`HasCondition::condition`](crate::ast::traits::HasCondition::condition).)
741    pub fn then_body(&self) -> Option<Block> {
742        support::child(&self.0)
743    }
744
745    /// The `elseif` clauses, in source order.
746    pub fn elseif_clauses(&self) -> AstChildren<ElseifClause> {
747        support::children(&self.0)
748    }
749
750    /// The trailing `else` clause, if any.
751    pub fn else_clause(&self) -> Option<ElseClause> {
752        support::child(&self.0)
753    }
754}
755
756impl Condition {
757    /// The test expression, unwrapping a single parenthesized layer
758    /// (`if (x) ...` yields the `x`). Centralizes the paren-unwrap that
759    /// condition consumers would otherwise hand-roll.
760    pub fn expr(&self) -> Option<Expr> {
761        match support::child::<Expr>(&self.0)? {
762            Expr::ParenExpr(paren) => paren.expr(),
763            other => Some(other),
764        }
765    }
766}
767
768impl FunctionDef {
769    /// The function signature, e.g. `g(x)`.
770    pub fn signature(&self) -> Option<Signature> {
771        support::child(&self.0)
772    }
773}
774
775impl Signature {
776    /// The signature's core expression (a `CALL_EXPR`, a bare `NAME`, ...).
777    pub fn expr(&self) -> Option<Expr> {
778        support::child(&self.0)
779    }
780}
781
782impl ModuleDef {
783    /// The module's name, e.g. `M` in `module M ... end`. (The body is
784    /// [`HasBody::body`](crate::ast::traits::HasBody::body).)
785    pub fn name(&self) -> Option<Name> {
786        support::child::<Signature>(&self.0).and_then(|sig| support::child(&sig.0))
787    }
788}
789
790impl ForBinding {
791    /// The loop variable/pattern (left of `in`/`=`).
792    pub fn pattern(&self) -> Option<Expr> {
793        support::child(&self.0)
794    }
795
796    /// The iterable expression (right of `in`/`=`).
797    pub fn iterable(&self) -> Option<Expr> {
798        support::children(&self.0).nth(1)
799    }
800}
801
802impl CatchClause {
803    /// The bound exception variable (`catch e`), if named. (The body is
804    /// [`HasBody::body`](crate::ast::traits::HasBody::body).)
805    pub fn variable(&self) -> Option<Name> {
806        support::child(&self.0)
807    }
808}
809
810impl DoExpr {
811    /// The parameters on the `do` line, e.g. `x, y` in `f(a) do x, y`. Absent for
812    /// a bare `do`.
813    pub fn params(&self) -> Option<DoParams> {
814        support::child(&self.0)
815    }
816}
817
818impl Root {
819    /// The top-level items of the file, in source order.
820    pub fn items(&self) -> AstChildren<Expr> {
821        support::children(&self.0)
822    }
823}
824
825#[cfg(test)]
826mod tests {
827    use super::*;
828    use crate::ast::tokens::AstToken;
829    use crate::ast::traits::{HasArgList, HasBody, HasCondition};
830    use crate::parser::parse;
831
832    /// The first node in the parse of `src` castable to `T`.
833    fn find<T: AstNode<Language = JuliaLanguage>>(src: &str) -> T {
834        parse(src)
835            .cst
836            .descendants()
837            .find_map(T::cast)
838            .expect("node of the requested kind present")
839    }
840
841    fn expr_text(expr: Option<Expr>) -> String {
842        expr.expect("expression present")
843            .syntax()
844            .text()
845            .to_string()
846    }
847
848    #[test]
849    fn binary_expr_operands_and_operator() {
850        let bin: BinaryExpr = find("a + b\n");
851        assert_eq!(expr_text(bin.lhs()), "a");
852        assert_eq!(expr_text(bin.rhs()), "b");
853        assert_eq!(bin.op().unwrap().text(), "+");
854    }
855
856    #[test]
857    fn ternary_expr_test_and_arms() {
858        let ternary: TernaryExpr = find("c ? f(1) : g(2)\n");
859        assert_eq!(expr_text(ternary.condition()), "c");
860        assert_eq!(expr_text(ternary.then_branch()), "f(1)");
861        assert_eq!(expr_text(ternary.else_branch()), "g(2)");
862        // An incomplete ternary is still a `TERNARY_EXPR`; the missing arm is
863        // simply absent.
864        let ternary: TernaryExpr = find("c ? a\n");
865        assert_eq!(expr_text(ternary.then_branch()), "a");
866        assert!(ternary.else_branch().is_none());
867    }
868
869    #[test]
870    fn assignment_operands_and_operator() {
871        let assign: AssignmentExpr = find("x = f(1)\n");
872        assert_eq!(expr_text(assign.lhs()), "x");
873        assert!(matches!(assign.rhs(), Some(Expr::CallExpr(_))));
874        assert_eq!(assign.op().unwrap().text(), "=");
875    }
876
877    #[test]
878    fn call_callee_and_args() {
879        let call: CallExpr = find("g(a, b)\n");
880        assert_eq!(expr_text(call.callee()), "g");
881        let args = call.arg_list().expect("arg list");
882        let texts: Vec<String> = args
883            .args()
884            .map(|a| a.expr().unwrap().syntax().text().to_string())
885            .collect();
886        assert_eq!(texts, ["a", "b"]);
887    }
888
889    #[test]
890    fn type_annotation_splits_at_the_colons() {
891        let ann: TypeAnnotation = find("x::Int\n");
892        assert_eq!(expr_text(ann.pattern()), "x");
893        assert_eq!(expr_text(ann.ty()), "Int");
894        // The unnamed-argument form has no pattern.
895        let ann: TypeAnnotation = find("f(::Int) = 1\n");
896        assert!(ann.pattern().is_none());
897        assert_eq!(expr_text(ann.ty()), "Int");
898        // The type may be any expression, not just a name.
899        let ann: TypeAnnotation = find("x::Union{Int,Nothing}\n");
900        assert_eq!(expr_text(ann.ty()), "Union{Int,Nothing}");
901    }
902
903    #[test]
904    fn quote_sym_expr_is_the_quoted_node() {
905        assert_eq!(expr_text(find::<QuoteSym>(":x\n").expr()), "x");
906        assert_eq!(expr_text(find::<QuoteSym>(":(x + 1)\n").expr()), "(x + 1)");
907        // A quoted operator or keyword is a bare token, not a node.
908        assert!(find::<QuoteSym>(":+\n").expr().is_none());
909        assert!(find::<QuoteSym>(":if\n").expr().is_none());
910    }
911
912    #[test]
913    fn parameters_split_plain_keywords_from_the_rest() {
914        // A definition's annotated keyword parameter is an `ARG`, not a
915        // `KEYWORD_ARG`.
916        let params: Parameters = find("f(; y::Int = 1, z = 2) = y\n");
917        let args: Vec<String> = params
918            .args()
919            .map(|a| a.syntax().text().to_string())
920            .collect();
921        assert_eq!(args, ["y::Int = 1"]);
922        let kwargs: Vec<String> = params
923            .keyword_args()
924            .map(|k| k.syntax().text().to_string())
925            .collect();
926        assert_eq!(kwargs, ["z = 2"]);
927        // At a call site, the shorthand and a splat are the `ARG`s.
928        let params: Parameters = find("f(; verbose, kw...)\n");
929        let args: Vec<String> = params
930            .args()
931            .map(|a| a.syntax().text().to_string())
932            .collect();
933        assert_eq!(args, ["verbose", "kw..."]);
934    }
935
936    #[test]
937    fn call_callee_ident_is_bare_names_only() {
938        assert_eq!(
939            find::<CallExpr>("g(a)\n").callee_ident().unwrap().text(),
940            "g"
941        );
942        // A qualified, operator, computed, or `var\"...\"` callee has no bare
943        // identifier to report.
944        assert!(find::<CallExpr>("Base.g(a)\n").callee_ident().is_none());
945        assert!(find::<CallExpr>("(!=)(a, b)\n").callee_ident().is_none());
946        assert!(find::<CallExpr>("(h())(a)\n").callee_ident().is_none());
947        assert!(find::<CallExpr>("var\"q\"(1)\n").callee_ident().is_none());
948    }
949
950    #[test]
951    fn expr_name_ident_reads_bare_name_operands() {
952        let bin: BinaryExpr = find("x == missing\n");
953        assert_eq!(bin.lhs().unwrap().name_ident().unwrap().text(), "x");
954        assert_eq!(bin.rhs().unwrap().name_ident().unwrap().text(), "missing");
955        // Anything that is not a bare `NAME` answers `None`.
956        let bin: BinaryExpr = find("f(x) == 1\n");
957        assert!(bin.lhs().unwrap().name_ident().is_none());
958        assert!(bin.rhs().unwrap().name_ident().is_none());
959    }
960
961    #[test]
962    fn call_callee_operator_shapes() {
963        // Bare, parenthesized, and qualified (`:!=` and `:(==)`) operator
964        // callees all surface the operator token.
965        let call: CallExpr = find("!=(a, b)\n");
966        assert_eq!(call.callee_operator().unwrap().text(), "!=");
967        let call: CallExpr = find("(!=)(a, b)\n");
968        assert_eq!(call.callee_operator().unwrap().text(), "!=");
969        let call: CallExpr = find("Base.:!=(a, b)\n");
970        assert_eq!(call.callee_operator().unwrap().text(), "!=");
971        let call: CallExpr = find("Base.:(==)(a, b)\n");
972        assert_eq!(call.callee_operator().unwrap().text(), "==");
973        // Ordinary callees have no operator name.
974        let call: CallExpr = find("g(a, b)\n");
975        assert!(call.callee_operator().is_none());
976        let call: CallExpr = find("Base.g(a, b)\n");
977        assert!(call.callee_operator().is_none());
978    }
979
980    #[test]
981    fn if_condition_body_and_else() {
982        let if_expr: IfExpr = find("if x\n    1\nelse\n    2\nend\n");
983        let cond = if_expr.condition().expect("condition");
984        assert_eq!(expr_text(cond.expr()), "x");
985        assert!(if_expr.then_body().is_some());
986        assert!(if_expr.else_clause().and_then(|e| e.body()).is_some());
987    }
988
989    #[test]
990    fn literal_bool_token() {
991        assert_eq!(
992            find::<Literal>("true\n").bool_token().unwrap().text(),
993            "true"
994        );
995        assert_eq!(
996            find::<Literal>("false\n").bool_token().unwrap().text(),
997            "false"
998        );
999        assert!(find::<Literal>("1\n").bool_token().is_none());
1000    }
1001
1002    #[test]
1003    fn literal_numeric_token() {
1004        assert_eq!(
1005            find::<Literal>("42\n").numeric_token().unwrap().text(),
1006            "42"
1007        );
1008        assert_eq!(
1009            find::<Literal>("3.5\n").numeric_token().unwrap().text(),
1010            "3.5"
1011        );
1012        assert_eq!(
1013            find::<Literal>("0xff\n").numeric_token().unwrap().text(),
1014            "0xff"
1015        );
1016        // Non-numeric literals have no numeric token.
1017        assert!(find::<Literal>("true\n").numeric_token().is_none());
1018    }
1019
1020    #[test]
1021    fn condition_unwraps_one_paren_layer() {
1022        let cond: Condition = find("if (x = 1)\n    1\nend\n");
1023        // A single paren layer is peeled: the inner assignment surfaces.
1024        assert!(matches!(cond.expr(), Some(Expr::AssignmentExpr(_))));
1025    }
1026
1027    #[test]
1028    fn function_signature_and_body() {
1029        let func: FunctionDef = find("function f(x)\n    x\nend\n");
1030        assert_eq!(expr_text(func.signature().and_then(|s| s.expr())), "f(x)");
1031        assert!(func.body().is_some());
1032    }
1033
1034    #[test]
1035    fn expr_dispatches_known_kinds() {
1036        assert!(matches!(
1037            Expr::cast(find::<CallExpr>("f()\n").syntax().clone()),
1038            Some(Expr::CallExpr(_))
1039        ));
1040        assert!(matches!(
1041            Expr::cast(find::<Name>("x\n").syntax().clone()),
1042            Some(Expr::Name(_))
1043        ));
1044    }
1045
1046    #[test]
1047    fn expr_falls_back_to_other_for_unwrapped_kinds() {
1048        // `a < b < c` parses to COMPARISON_EXPR, an expression kind with no
1049        // dedicated wrapper: it must still round-trip through `Expr::Other`,
1050        // not vanish.
1051        let cmp = parse("a < b < c\n")
1052            .cst
1053            .descendants()
1054            .find(|n| n.kind() == SyntaxKind::COMPARISON_EXPR)
1055            .expect("comparison expr");
1056        assert!(matches!(Expr::cast(cmp), Some(Expr::Other(_))));
1057    }
1058
1059    #[test]
1060    fn non_expression_nodes_do_not_cast_to_expr() {
1061        let sig = find::<FunctionDef>("function f()\nend\n")
1062            .signature()
1063            .unwrap();
1064        assert!(Expr::cast(sig.syntax().clone()).is_none());
1065    }
1066
1067    #[test]
1068    fn module_def_name_and_body() {
1069        let module: ModuleDef = find("module M\nx = 1\nend\n");
1070        assert_eq!(module.name().unwrap().syntax().text(), "M");
1071        assert!(module.body().is_some());
1072        let bare: ModuleDef = find("baremodule B\nend\n");
1073        assert_eq!(bare.name().unwrap().syntax().text(), "B");
1074    }
1075
1076    #[test]
1077    fn missing_children_yield_none() {
1078        // A bare `do` block has no `DO_PARAMS`.
1079        let do_expr: DoExpr = find("f() do\n    1\nend\n");
1080        assert!(do_expr.params().is_none());
1081    }
1082}