Skip to content

Commit

Permalink
Auto merge of rust-lang#13949 - WaffleLapkin:either_ast_node, r=Veykril
Browse files Browse the repository at this point in the history
minor: implement `AstNode` for `Either`

Makes code a little bit nicer
  • Loading branch information
bors committed Jan 14, 2023
2 parents ce86f12 + cfc0115 commit c78b9f0
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 8 deletions.
9 changes: 1 addition & 8 deletions crates/hir/src/semantics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1472,14 +1472,7 @@ impl<'db> SemanticsImpl<'db> {
}

fn is_inside_unsafe(&self, expr: &ast::Expr) -> bool {
let item_or_variant = |ancestor: SyntaxNode| {
if ast::Item::can_cast(ancestor.kind()) {
ast::Item::cast(ancestor).map(Either::Left)
} else {
ast::Variant::cast(ancestor).map(Either::Right)
}
};
let Some(enclosing_item) = expr.syntax().ancestors().find_map(item_or_variant) else { return false };
let Some(enclosing_item) = expr.syntax().ancestors().find_map(Either::<ast::Item, ast::Variant>::cast) else { return false };

let def = match &enclosing_item {
Either::Left(ast::Item::Fn(it)) if it.unsafe_token().is_some() => return true,
Expand Down
30 changes: 30 additions & 0 deletions crates/syntax/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ pub mod prec;

use std::marker::PhantomData;

use itertools::Either;

use crate::{
syntax_node::{SyntaxNode, SyntaxNodeChildren, SyntaxToken},
SyntaxKind,
Expand Down Expand Up @@ -98,6 +100,34 @@ impl<N: AstNode> Iterator for AstChildren<N> {
}
}

impl<L, R> AstNode for Either<L, R>
where
L: AstNode,
R: AstNode,
{
fn can_cast(kind: SyntaxKind) -> bool
where
Self: Sized,
{
L::can_cast(kind) || R::can_cast(kind)
}

fn cast(syntax: SyntaxNode) -> Option<Self>
where
Self: Sized,
{
if L::can_cast(syntax.kind()) {
L::cast(syntax).map(Either::Left)
} else {
R::cast(syntax).map(Either::Right)
}
}

fn syntax(&self) -> &SyntaxNode {
self.as_ref().either(L::syntax, R::syntax)
}
}

mod support {
use super::{AstChildren, AstNode, SyntaxKind, SyntaxNode, SyntaxToken};

Expand Down

0 comments on commit c78b9f0

Please sign in to comment.