From e52bdc55ef05bae8e647a5a0a9f8c3605c4cdd34 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Tue, 16 Feb 2021 19:27:08 +0100 Subject: Implement ast::AstNode for NameLike and move it to node_ext --- crates/syntax/src/ast.rs | 2 +- crates/syntax/src/ast/node_ext.rs | 46 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) (limited to 'crates/syntax') diff --git a/crates/syntax/src/ast.rs b/crates/syntax/src/ast.rs index a25ff655e..b3a24d39d 100644 --- a/crates/syntax/src/ast.rs +++ b/crates/syntax/src/ast.rs @@ -19,7 +19,7 @@ pub use self::{ expr_ext::{ArrayExprKind, BinOp, Effect, ElseBranch, LiteralKind, PrefixOp, RangeOp}, generated::{nodes::*, tokens::*}, node_ext::{ - AttrKind, FieldKind, Macro, NameOrNameRef, PathSegmentKind, SelfParamKind, + AttrKind, FieldKind, Macro, NameLike, NameOrNameRef, PathSegmentKind, SelfParamKind, SlicePatComponents, StructKind, TypeBoundKind, VisibilityKind, }, token_ext::*, diff --git a/crates/syntax/src/ast/node_ext.rs b/crates/syntax/src/ast/node_ext.rs index 307e150e9..2fa7b8c1e 100644 --- a/crates/syntax/src/ast/node_ext.rs +++ b/crates/syntax/src/ast/node_ext.rs @@ -297,6 +297,52 @@ impl ast::RecordExprField { } } +#[derive(Debug, Clone)] +pub enum NameLike { + NameRef(ast::NameRef), + Name(ast::Name), + Lifetime(ast::Lifetime), +} + +impl NameLike { + pub fn as_name_ref(&self) -> Option<&ast::NameRef> { + match self { + NameLike::NameRef(name_ref) => Some(name_ref), + _ => None, + } + } +} + +impl ast::AstNode for NameLike { + fn can_cast(kind: SyntaxKind) -> bool { + matches!(kind, SyntaxKind::NAME | SyntaxKind::NAME_REF | SyntaxKind::LIFETIME) + } + fn cast(syntax: SyntaxNode) -> Option { + let res = match syntax.kind() { + SyntaxKind::NAME => NameLike::Name(ast::Name { syntax }), + SyntaxKind::NAME_REF => NameLike::NameRef(ast::NameRef { syntax }), + SyntaxKind::LIFETIME => NameLike::Lifetime(ast::Lifetime { syntax }), + _ => return None, + }; + Some(res) + } + fn syntax(&self) -> &SyntaxNode { + match self { + NameLike::NameRef(it) => it.syntax(), + NameLike::Name(it) => it.syntax(), + NameLike::Lifetime(it) => it.syntax(), + } + } +} + +mod __ { + use super::{ + ast::{Lifetime, Name, NameRef}, + NameLike, + }; + stdx::impl_from!(NameRef, Name, Lifetime for NameLike); +} + #[derive(Debug, Clone, PartialEq)] pub enum NameOrNameRef { Name(ast::Name), -- cgit v1.2.3