Skip to content

Commit c78b9f0

Browse files
committed
Auto merge of rust-lang#13949 - WaffleLapkin:either_ast_node, r=Veykril
minor: implement `AstNode` for `Either` Makes code a little bit nicer
2 parents ce86f12 + cfc0115 commit c78b9f0

File tree

2 files changed

+31
-8
lines changed

2 files changed

+31
-8
lines changed

crates/hir/src/semantics.rs

+1-8
Original file line numberDiff line numberDiff line change
@@ -1472,14 +1472,7 @@ impl<'db> SemanticsImpl<'db> {
14721472
}
14731473

14741474
fn is_inside_unsafe(&self, expr: &ast::Expr) -> bool {
1475-
let item_or_variant = |ancestor: SyntaxNode| {
1476-
if ast::Item::can_cast(ancestor.kind()) {
1477-
ast::Item::cast(ancestor).map(Either::Left)
1478-
} else {
1479-
ast::Variant::cast(ancestor).map(Either::Right)
1480-
}
1481-
};
1482-
let Some(enclosing_item) = expr.syntax().ancestors().find_map(item_or_variant) else { return false };
1475+
let Some(enclosing_item) = expr.syntax().ancestors().find_map(Either::<ast::Item, ast::Variant>::cast) else { return false };
14831476

14841477
let def = match &enclosing_item {
14851478
Either::Left(ast::Item::Fn(it)) if it.unsafe_token().is_some() => return true,

crates/syntax/src/ast.rs

+30
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ pub mod prec;
1313

1414
use std::marker::PhantomData;
1515

16+
use itertools::Either;
17+
1618
use crate::{
1719
syntax_node::{SyntaxNode, SyntaxNodeChildren, SyntaxToken},
1820
SyntaxKind,
@@ -98,6 +100,34 @@ impl<N: AstNode> Iterator for AstChildren<N> {
98100
}
99101
}
100102

103+
impl<L, R> AstNode for Either<L, R>
104+
where
105+
L: AstNode,
106+
R: AstNode,
107+
{
108+
fn can_cast(kind: SyntaxKind) -> bool
109+
where
110+
Self: Sized,
111+
{
112+
L::can_cast(kind) || R::can_cast(kind)
113+
}
114+
115+
fn cast(syntax: SyntaxNode) -> Option<Self>
116+
where
117+
Self: Sized,
118+
{
119+
if L::can_cast(syntax.kind()) {
120+
L::cast(syntax).map(Either::Left)
121+
} else {
122+
R::cast(syntax).map(Either::Right)
123+
}
124+
}
125+
126+
fn syntax(&self) -> &SyntaxNode {
127+
self.as_ref().either(L::syntax, R::syntax)
128+
}
129+
}
130+
101131
mod support {
102132
use super::{AstChildren, AstNode, SyntaxKind, SyntaxNode, SyntaxToken};
103133

0 commit comments

Comments
 (0)