Skip to content

Commit 924d277

Browse files
committed
Auto merge of rust-lang#14361 - Veykril:if-then-parse, r=Veykril
fix: Fix `ast::IfExpr` child accessors Fixes rust-lang/rust-analyzer#14360
2 parents 8330f8e + 9fe2069 commit 924d277

File tree

3 files changed

+21
-21
lines changed

3 files changed

+21
-21
lines changed

crates/hir-expand/src/fixup.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -636,9 +636,8 @@ fn foo() {
636636
if {}
637637
}
638638
"#,
639-
// the {} gets parsed as the condition, I think?
640639
expect![[r#"
641-
fn foo () {if {} {}}
640+
fn foo () {if __ra_fixup {} {}}
642641
"#]],
643642
)
644643
}

crates/syntax/src/ast/expr_ext.rs

+20-13
Original file line numberDiff line numberDiff line change
@@ -48,23 +48,30 @@ impl From<ast::IfExpr> for ElseBranch {
4848
}
4949

5050
impl ast::IfExpr {
51-
pub fn then_branch(&self) -> Option<ast::BlockExpr> {
52-
self.children_after_condition().next()
51+
pub fn condition(&self) -> Option<ast::Expr> {
52+
// If the condition is a BlockExpr, check if the then body is missing.
53+
// If it is assume the condition is the expression that is missing instead.
54+
let mut exprs = support::children(self.syntax());
55+
let first = exprs.next();
56+
match first {
57+
Some(ast::Expr::BlockExpr(_)) => exprs.next().and(first),
58+
first => first,
59+
}
5360
}
5461

55-
pub fn else_branch(&self) -> Option<ElseBranch> {
56-
let res = match self.children_after_condition().nth(1) {
57-
Some(block) => ElseBranch::Block(block),
58-
None => {
59-
let elif = self.children_after_condition().next()?;
60-
ElseBranch::IfExpr(elif)
61-
}
62-
};
63-
Some(res)
62+
pub fn then_branch(&self) -> Option<ast::BlockExpr> {
63+
match support::children(self.syntax()).nth(1)? {
64+
ast::Expr::BlockExpr(block) => Some(block),
65+
_ => None,
66+
}
6467
}
6568

66-
fn children_after_condition<N: AstNode>(&self) -> impl Iterator<Item = N> {
67-
self.syntax().children().skip(1).filter_map(N::cast)
69+
pub fn else_branch(&self) -> Option<ElseBranch> {
70+
match support::children(self.syntax()).nth(2)? {
71+
ast::Expr::BlockExpr(block) => Some(ElseBranch::Block(block)),
72+
ast::Expr::IfExpr(elif) => Some(ElseBranch::IfExpr(elif)),
73+
_ => None,
74+
}
6875
}
6976
}
7077

crates/syntax/src/ast/node_ext.rs

-6
Original file line numberDiff line numberDiff line change
@@ -937,12 +937,6 @@ impl From<ast::Adt> for ast::Item {
937937
}
938938
}
939939

940-
impl ast::IfExpr {
941-
pub fn condition(&self) -> Option<ast::Expr> {
942-
support::child(&self.syntax)
943-
}
944-
}
945-
946940
impl ast::MatchGuard {
947941
pub fn condition(&self) -> Option<ast::Expr> {
948942
support::child(&self.syntax)

0 commit comments

Comments
 (0)