Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Rust's if-else AST use different types for then and else?

Tags:

rust

I was writing Rust lint plugin when I found that Rust uses different types to represent the then (Block) and else (Expr) parts of an if statement in both libsyntax::ast::ExprKind and librustc::hir::Expr_.

I need them both to have common types.

Should I just use an explicit match over hir::Expr_::ExprBlock, or else part could be something else, and I need to make more smart comparison?

From the source:

// ...
pub enum Expr_ {
    // ...
    /// An `if` block, with an optional else block
    ///
    /// `if expr { block } else { expr }`
    ExprIf(P<Expr>, P<Block>, Option<P<Expr>>),
    // ...
}
// ...
like image 786
Cpud36 Avatar asked Jul 11 '16 16:07

Cpud36


1 Answers

This is so we can distinguish

if x {
    foo();
} else if y {
    bar();
}

from

if x {
    foo();
} else { // note the block
    if y {
        bar();
    }
}

The first has an ExprIf in the node of the else-Expr whereas the second has an ExprBlock containing a single ExprIf-expression.

like image 142
llogiq Avatar answered Oct 17 '22 03:10

llogiq