Skip to main content

syntax/ast/
expr_ext.rs

1//! Various extension methods to ast Expr Nodes, which are hard to code-generate.
2//!
3//! These methods should only do simple, shallow tasks related to the syntax of the node itself.
4
5use crate::{
6    AstToken,
7    SyntaxKind::{self, *},
8    SyntaxNode, SyntaxToken, T,
9    ast::{
10        self, ArgList, AstChildren, AstNode, BlockExpr, ClosureExpr, Const, Expr, Fn,
11        FormatArgsArg, FormatArgsExpr, MacroDef, Static, TokenTree,
12        operators::{ArithOp, BinaryOp, CmpOp, LogicOp, Ordering, RangeOp, UnaryOp},
13        support,
14    },
15    match_ast,
16};
17
18use super::RangeItem;
19
20impl ast::HasAttrs for ast::Expr {}
21
22impl ast::Expr {
23    pub fn is_block_like(&self) -> bool {
24        matches!(
25            self,
26            ast::Expr::IfExpr(_)
27                | ast::Expr::LoopExpr(_)
28                | ast::Expr::ForExpr(_)
29                | ast::Expr::WhileExpr(_)
30                | ast::Expr::BlockExpr(_)
31                | ast::Expr::MatchExpr(_)
32        )
33    }
34}
35
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub enum ElseBranch {
38    Block(ast::BlockExpr),
39    IfExpr(ast::IfExpr),
40}
41
42impl From<ast::BlockExpr> for ElseBranch {
43    fn from(block_expr: ast::BlockExpr) -> Self {
44        Self::Block(block_expr)
45    }
46}
47
48impl From<ast::IfExpr> for ElseBranch {
49    fn from(if_expr: ast::IfExpr) -> Self {
50        Self::IfExpr(if_expr)
51    }
52}
53
54impl AstNode for ElseBranch {
55    fn can_cast(kind: SyntaxKind) -> bool {
56        ast::BlockExpr::can_cast(kind) || ast::IfExpr::can_cast(kind)
57    }
58
59    fn cast(syntax: SyntaxNode) -> Option<Self> {
60        match_ast!(match syntax {
61            ast::BlockExpr(it) => Some(Self::Block(it)),
62            ast::IfExpr(it) => Some(Self::IfExpr(it)),
63            _ => None,
64        })
65    }
66
67    fn syntax(&self) -> &SyntaxNode {
68        match self {
69            ElseBranch::Block(block_expr) => block_expr.syntax(),
70            ElseBranch::IfExpr(if_expr) => if_expr.syntax(),
71        }
72    }
73}
74
75impl ast::IfExpr {
76    pub fn condition(&self) -> Option<ast::Expr> {
77        // If the condition is a BlockExpr, check if the then body is missing.
78        // If it is assume the condition is the expression that is missing instead.
79        let mut exprs = support::children(self.syntax());
80        let first = exprs.next();
81        match first {
82            Some(ast::Expr::BlockExpr(_)) => exprs.next().and(first),
83            first => first,
84        }
85    }
86
87    pub fn then_branch(&self) -> Option<ast::BlockExpr> {
88        match support::children(self.syntax()).nth(1)? {
89            ast::Expr::BlockExpr(block) => Some(block),
90            _ => None,
91        }
92    }
93
94    pub fn else_branch(&self) -> Option<ElseBranch> {
95        match support::children(self.syntax()).nth(2)? {
96            ast::Expr::BlockExpr(block) => Some(ElseBranch::Block(block)),
97            ast::Expr::IfExpr(elif) => Some(ElseBranch::IfExpr(elif)),
98            _ => None,
99        }
100    }
101}
102
103#[test]
104fn if_block_condition() {
105    let parse = ast::SourceFile::parse(
106        r#"
107        fn test() {
108            if { true } { "if" }
109            else if { false } { "first elif" }
110            else if true { "second elif" }
111            else if (true) { "third elif" }
112            else { "else" }
113        }
114        "#,
115        parser::Edition::CURRENT,
116    );
117    let if_ = parse.tree().syntax().descendants().find_map(ast::IfExpr::cast).unwrap();
118    assert_eq!(if_.then_branch().unwrap().syntax().text(), r#"{ "if" }"#);
119    let elif = match if_.else_branch().unwrap() {
120        ElseBranch::IfExpr(elif) => elif,
121        ElseBranch::Block(_) => panic!("should be `else if`"),
122    };
123    assert_eq!(elif.then_branch().unwrap().syntax().text(), r#"{ "first elif" }"#);
124    let elif = match elif.else_branch().unwrap() {
125        ElseBranch::IfExpr(elif) => elif,
126        ElseBranch::Block(_) => panic!("should be `else if`"),
127    };
128    assert_eq!(elif.then_branch().unwrap().syntax().text(), r#"{ "second elif" }"#);
129    let elif = match elif.else_branch().unwrap() {
130        ElseBranch::IfExpr(elif) => elif,
131        ElseBranch::Block(_) => panic!("should be `else if`"),
132    };
133    assert_eq!(elif.then_branch().unwrap().syntax().text(), r#"{ "third elif" }"#);
134    let else_ = match elif.else_branch().unwrap() {
135        ElseBranch::Block(else_) => else_,
136        ElseBranch::IfExpr(_) => panic!("should be `else`"),
137    };
138    assert_eq!(else_.syntax().text(), r#"{ "else" }"#);
139}
140
141#[test]
142fn if_condition_with_if_inside() {
143    let parse = ast::SourceFile::parse(
144        r#"
145        fn test() {
146            if if true { true } else { false } { "if" }
147            else { "else" }
148        }
149        "#,
150        parser::Edition::CURRENT,
151    );
152    let if_ = parse.tree().syntax().descendants().find_map(ast::IfExpr::cast).unwrap();
153    assert_eq!(if_.then_branch().unwrap().syntax().text(), r#"{ "if" }"#);
154    let else_ = match if_.else_branch().unwrap() {
155        ElseBranch::Block(else_) => else_,
156        ElseBranch::IfExpr(_) => panic!("should be `else`"),
157    };
158    assert_eq!(else_.syntax().text(), r#"{ "else" }"#);
159}
160
161impl ast::PrefixExpr {
162    pub fn op_kind(&self) -> Option<UnaryOp> {
163        let res = match self.op_token()?.kind() {
164            T![*] => UnaryOp::Deref,
165            T![!] => UnaryOp::Not,
166            T![-] => UnaryOp::Neg,
167            _ => return None,
168        };
169        Some(res)
170    }
171
172    pub fn op_token(&self) -> Option<SyntaxToken> {
173        self.syntax().first_child_or_token()?.into_token()
174    }
175}
176
177impl ast::BinExpr {
178    pub fn op_details(&self) -> Option<(SyntaxToken, BinaryOp)> {
179        self.syntax().children_with_tokens().filter_map(|it| it.into_token()).find_map(|c| {
180            #[rustfmt::skip]
181            let bin_op = match c.kind() {
182                T![||] => BinaryOp::LogicOp(LogicOp::Or),
183                T![&&] => BinaryOp::LogicOp(LogicOp::And),
184
185                T![==] => BinaryOp::CmpOp(CmpOp::Eq { negated: false }),
186                T![!=] => BinaryOp::CmpOp(CmpOp::Eq { negated: true }),
187                T![<=] => BinaryOp::CmpOp(CmpOp::Ord { ordering: Ordering::Less,    strict: false }),
188                T![>=] => BinaryOp::CmpOp(CmpOp::Ord { ordering: Ordering::Greater, strict: false }),
189                T![<]  => BinaryOp::CmpOp(CmpOp::Ord { ordering: Ordering::Less,    strict: true }),
190                T![>]  => BinaryOp::CmpOp(CmpOp::Ord { ordering: Ordering::Greater, strict: true }),
191
192                T![+]  => BinaryOp::ArithOp(ArithOp::Add),
193                T![*]  => BinaryOp::ArithOp(ArithOp::Mul),
194                T![-]  => BinaryOp::ArithOp(ArithOp::Sub),
195                T![/]  => BinaryOp::ArithOp(ArithOp::Div),
196                T![%]  => BinaryOp::ArithOp(ArithOp::Rem),
197                T![<<] => BinaryOp::ArithOp(ArithOp::Shl),
198                T![>>] => BinaryOp::ArithOp(ArithOp::Shr),
199                T![^]  => BinaryOp::ArithOp(ArithOp::BitXor),
200                T![|]  => BinaryOp::ArithOp(ArithOp::BitOr),
201                T![&]  => BinaryOp::ArithOp(ArithOp::BitAnd),
202
203                T![=]   => BinaryOp::Assignment { op: None },
204                T![+=]  => BinaryOp::Assignment { op: Some(ArithOp::Add) },
205                T![*=]  => BinaryOp::Assignment { op: Some(ArithOp::Mul) },
206                T![-=]  => BinaryOp::Assignment { op: Some(ArithOp::Sub) },
207                T![/=]  => BinaryOp::Assignment { op: Some(ArithOp::Div) },
208                T![%=]  => BinaryOp::Assignment { op: Some(ArithOp::Rem) },
209                T![<<=] => BinaryOp::Assignment { op: Some(ArithOp::Shl) },
210                T![>>=] => BinaryOp::Assignment { op: Some(ArithOp::Shr) },
211                T![^=]  => BinaryOp::Assignment { op: Some(ArithOp::BitXor) },
212                T![|=]  => BinaryOp::Assignment { op: Some(ArithOp::BitOr) },
213                T![&=]  => BinaryOp::Assignment { op: Some(ArithOp::BitAnd) },
214
215                _ => return None,
216            };
217            Some((c, bin_op))
218        })
219    }
220
221    pub fn op_kind(&self) -> Option<BinaryOp> {
222        self.op_details().map(|t| t.1)
223    }
224
225    pub fn op_token(&self) -> Option<SyntaxToken> {
226        self.op_details().map(|t| t.0)
227    }
228
229    pub fn lhs(&self) -> Option<ast::Expr> {
230        support::children(self.syntax()).next()
231    }
232
233    pub fn rhs(&self) -> Option<ast::Expr> {
234        support::children(self.syntax()).nth(1)
235    }
236
237    pub fn sub_exprs(&self) -> (Option<ast::Expr>, Option<ast::Expr>) {
238        let mut children = support::children(self.syntax());
239        let first = children.next();
240        let second = children.next();
241        (first, second)
242    }
243}
244
245impl ast::RangeExpr {
246    fn op_details(&self) -> Option<(usize, SyntaxToken, RangeOp)> {
247        self.syntax().children_with_tokens().enumerate().find_map(|(ix, child)| {
248            let token = child.into_token()?;
249            let bin_op = match token.kind() {
250                T![..] => RangeOp::Exclusive,
251                T![..=] => RangeOp::Inclusive,
252                _ => return None,
253            };
254            Some((ix, token, bin_op))
255        })
256    }
257
258    pub fn is_range_full(&self) -> bool {
259        support::children::<Expr>(&self.syntax).next().is_none()
260    }
261}
262
263impl RangeItem for ast::RangeExpr {
264    type Bound = ast::Expr;
265
266    fn start(&self) -> Option<ast::Expr> {
267        let op_ix = self.op_details()?.0;
268        self.syntax()
269            .children_with_tokens()
270            .take(op_ix)
271            .find_map(|it| ast::Expr::cast(it.into_node()?))
272    }
273
274    fn end(&self) -> Option<ast::Expr> {
275        let op_ix = self.op_details()?.0;
276        self.syntax()
277            .children_with_tokens()
278            .skip(op_ix + 1)
279            .find_map(|it| ast::Expr::cast(it.into_node()?))
280    }
281
282    fn op_token(&self) -> Option<SyntaxToken> {
283        self.op_details().map(|t| t.1)
284    }
285
286    fn op_kind(&self) -> Option<RangeOp> {
287        self.op_details().map(|t| t.2)
288    }
289}
290
291impl ast::IndexExpr {
292    pub fn base(&self) -> Option<ast::Expr> {
293        support::children(self.syntax()).next()
294    }
295    pub fn index(&self) -> Option<ast::Expr> {
296        support::children(self.syntax()).nth(1)
297    }
298}
299
300pub enum ArrayExprKind {
301    Repeat { initializer: Option<ast::Expr>, repeat: Option<ast::Expr> },
302    ElementList(AstChildren<ast::Expr>),
303}
304
305impl ast::ArrayExpr {
306    pub fn kind(&self) -> ArrayExprKind {
307        if self.is_repeat() {
308            ArrayExprKind::Repeat {
309                initializer: support::children(self.syntax()).next(),
310                repeat: support::children(self.syntax()).nth(1),
311            }
312        } else {
313            ArrayExprKind::ElementList(support::children(self.syntax()))
314        }
315    }
316
317    fn is_repeat(&self) -> bool {
318        self.semicolon_token().is_some()
319    }
320}
321
322#[derive(Clone, Debug, PartialEq, Eq, Hash)]
323pub enum LiteralKind {
324    String(ast::String),
325    ByteString(ast::ByteString),
326    CString(ast::CString),
327    IntNumber(ast::IntNumber),
328    FloatNumber(ast::FloatNumber),
329    Char(ast::Char),
330    Byte(ast::Byte),
331    Bool(bool),
332}
333
334impl ast::Literal {
335    pub fn token(&self) -> SyntaxToken {
336        self.syntax()
337            .children_with_tokens()
338            .find(|e| !ast::AnyAttr::can_cast(e.kind()) && !e.kind().is_trivia())
339            .and_then(|e| e.into_token())
340            .unwrap()
341    }
342
343    pub fn kind(&self) -> LiteralKind {
344        let token = self.token();
345
346        match_ast!(match token {
347            ast::IntNumber(t) => LiteralKind::IntNumber(t),
348            ast::FloatNumber(t) => LiteralKind::FloatNumber(t),
349            ast::String(t) => LiteralKind::String(t),
350            ast::ByteString(t) => LiteralKind::ByteString(t),
351            ast::CString(t) => LiteralKind::CString(t),
352            ast::Char(t) => LiteralKind::Char(t),
353            ast::Byte(t) => LiteralKind::Byte(t),
354            _ => match token.kind() {
355                T![true] => LiteralKind::Bool(true),
356                T![false] => LiteralKind::Bool(false),
357                _ => unreachable!(),
358            },
359        })
360    }
361}
362
363pub enum BlockModifier {
364    Async(SyntaxToken),
365    Unsafe(SyntaxToken),
366    Try {
367        try_token: SyntaxToken,
368        bikeshed_token: Option<SyntaxToken>,
369        result_type: Option<ast::Type>,
370    },
371    Const(SyntaxToken),
372    AsyncGen(SyntaxToken),
373    Gen(SyntaxToken),
374    Label(ast::Label),
375}
376
377impl ast::BlockExpr {
378    pub fn modifier(&self) -> Option<BlockModifier> {
379        self.gen_token()
380            .map(|v| {
381                if self.async_token().is_some() {
382                    BlockModifier::AsyncGen(v)
383                } else {
384                    BlockModifier::Gen(v)
385                }
386            })
387            .or_else(|| self.async_token().map(BlockModifier::Async))
388            .or_else(|| self.unsafe_token().map(BlockModifier::Unsafe))
389            .or_else(|| {
390                let modifier = self.try_block_modifier()?;
391                let try_token = modifier.try_token()?;
392                let bikeshed_token = modifier.bikeshed_token();
393                let result_type = modifier.ty();
394                Some(BlockModifier::Try { try_token, bikeshed_token, result_type })
395            })
396            .or_else(|| self.const_token().map(BlockModifier::Const))
397            .or_else(|| self.label().map(BlockModifier::Label))
398    }
399    /// false if the block is an intrinsic part of the syntax and can't be
400    /// replaced with arbitrary expression.
401    ///
402    /// ```not_rust
403    /// fn foo() { not_stand_alone }
404    /// const FOO: () = { stand_alone };
405    /// ```
406    pub fn is_standalone(&self) -> bool {
407        let parent = match self.syntax().parent() {
408            Some(it) => it,
409            None => return true,
410        };
411        match parent.kind() {
412            FOR_EXPR | IF_EXPR => parent
413                .children()
414                .find(|it| ast::Expr::can_cast(it.kind()))
415                .is_none_or(|it| it == *self.syntax()),
416            LET_ELSE | FN | WHILE_EXPR | LOOP_EXPR | CONST_BLOCK_PAT => false,
417            _ => true,
418        }
419    }
420}
421
422#[test]
423fn test_literal_with_attr() {
424    let parse =
425        ast::SourceFile::parse(r#"const _: &str = { #[attr] "Hello" };"#, parser::Edition::CURRENT);
426    let lit = parse.tree().syntax().descendants().find_map(ast::Literal::cast).unwrap();
427    assert_eq!(lit.token().text(), r#""Hello""#);
428}
429
430impl ast::RecordExprField {
431    pub fn parent_record_lit(&self) -> ast::RecordExpr {
432        self.syntax().ancestors().find_map(ast::RecordExpr::cast).unwrap()
433    }
434}
435
436#[derive(Debug, Clone, PartialEq, Eq, Hash)]
437pub enum CallableExpr {
438    Call(ast::CallExpr),
439    MethodCall(ast::MethodCallExpr),
440}
441
442impl ast::HasAttrs for CallableExpr {}
443impl ast::HasArgList for CallableExpr {}
444
445impl AstNode for CallableExpr {
446    fn can_cast(kind: parser::SyntaxKind) -> bool
447    where
448        Self: Sized,
449    {
450        ast::CallExpr::can_cast(kind) || ast::MethodCallExpr::can_cast(kind)
451    }
452
453    fn cast(syntax: SyntaxNode) -> Option<Self>
454    where
455        Self: Sized,
456    {
457        if let Some(it) = ast::CallExpr::cast(syntax.clone()) {
458            Some(Self::Call(it))
459        } else {
460            ast::MethodCallExpr::cast(syntax).map(Self::MethodCall)
461        }
462    }
463
464    fn syntax(&self) -> &SyntaxNode {
465        match self {
466            Self::Call(it) => it.syntax(),
467            Self::MethodCall(it) => it.syntax(),
468        }
469    }
470}
471
472impl MacroDef {
473    fn tts(&self) -> (Option<ast::TokenTree>, Option<ast::TokenTree>) {
474        let mut types = support::children(self.syntax());
475        let first = types.next();
476        let second = types.next();
477        (first, second)
478    }
479
480    pub fn args(&self) -> Option<TokenTree> {
481        match self.tts() {
482            (Some(args), Some(_)) => Some(args),
483            _ => None,
484        }
485    }
486
487    pub fn body(&self) -> Option<TokenTree> {
488        match self.tts() {
489            (Some(body), None) | (_, Some(body)) => Some(body),
490            _ => None,
491        }
492    }
493}
494
495impl ClosureExpr {
496    pub fn body(&self) -> Option<Expr> {
497        support::child(&self.syntax)
498    }
499}
500impl Const {
501    pub fn body(&self) -> Option<Expr> {
502        support::child(&self.syntax)
503    }
504}
505impl Fn {
506    pub fn body(&self) -> Option<BlockExpr> {
507        support::child(&self.syntax)
508    }
509}
510impl Static {
511    pub fn body(&self) -> Option<Expr> {
512        support::child(&self.syntax)
513    }
514}
515impl FormatArgsExpr {
516    pub fn args(&self) -> AstChildren<FormatArgsArg> {
517        support::children(&self.syntax)
518    }
519}
520impl ArgList {
521    pub fn args(&self) -> AstChildren<Expr> {
522        support::children(&self.syntax)
523    }
524}