rune/ast/
expr_if.rs

1use crate::ast::prelude::*;
2
3#[test]
4#[cfg(not(miri))]
5fn ast_parse() {
6    rt::<ast::ExprIf>("if 0 {  }");
7    rt::<ast::ExprIf>("if 0 {  } else {  }");
8    rt::<ast::ExprIf>("if 0 {  } else if 0 {  } else {  }");
9    rt::<ast::ExprIf>("if let v = v {  }");
10    rt::<ast::ExprIf>("#[attr] if 1 {} else {}");
11}
12
13/// A conditional `if` expression.
14///
15/// * `if cond { true } else { false }`.
16#[derive(Debug, TryClone, PartialEq, Eq, Parse, ToTokens, Spanned)]
17#[rune(parse = "meta_only")]
18#[non_exhaustive]
19pub struct ExprIf {
20    /// The `attributes` of the if statement
21    #[rune(iter, meta)]
22    pub attributes: Vec<ast::Attribute>,
23    /// The `if` token.
24    pub if_: T![if],
25    /// The condition to the if statement.
26    pub condition: Box<ast::Condition>,
27    /// The body of the if statement.
28    pub block: Box<ast::Block>,
29    /// Else if branches.
30    #[rune(iter)]
31    pub expr_else_ifs: Vec<ExprElseIf>,
32    /// The else part of the if expression.
33    #[rune(iter)]
34    pub expr_else: Option<ExprElse>,
35}
36
37expr_parse!(If, ExprIf, "if expression");
38
39/// An else branch of an if expression.
40#[derive(Debug, TryClone, PartialEq, Eq, ToTokens, Parse, Spanned)]
41#[non_exhaustive]
42pub struct ExprElseIf {
43    /// The `else` token.
44    pub else_: T![else],
45    /// The `if` token.
46    pub if_: T![if],
47    /// The condition for the branch.
48    pub condition: Box<ast::Condition>,
49    /// The body of the else statement.
50    pub block: Box<ast::Block>,
51}
52
53impl Peek for ExprElseIf {
54    fn peek(p: &mut Peeker<'_>) -> bool {
55        matches!((p.nth(0), p.nth(1)), (K![else], K![if]))
56    }
57}
58
59/// An else branch of an if expression.
60#[derive(Debug, TryClone, PartialEq, Eq, ToTokens, Parse, Spanned)]
61#[non_exhaustive]
62pub struct ExprElse {
63    /// The `else` token.
64    pub else_: T![else],
65    /// The body of the else statement.
66    pub block: Box<ast::Block>,
67}
68
69impl Peek for ExprElse {
70    fn peek(p: &mut Peeker<'_>) -> bool {
71        matches!(p.nth(0), K![else])
72    }
73}