Scale back the traits

This commit is contained in:
Aleksey Kladov 2020-04-09 10:47:05 +02:00
parent 68196ccc10
commit 8f01e62bb9
3 changed files with 3061 additions and 245 deletions

View file

@ -11,10 +11,7 @@ pub mod make;
use std::marker::PhantomData;
use crate::{
syntax_node::{
NodeOrToken, SyntaxElement, SyntaxElementChildren, SyntaxNode, SyntaxNodeChildren,
SyntaxToken,
},
syntax_node::{SyntaxNode, SyntaxNodeChildren, SyntaxToken},
SmolStr, SyntaxKind,
};
@ -33,24 +30,16 @@ pub use self::{
/// conversion itself has zero runtime cost: ast and syntax nodes have exactly
/// the same representation: a pointer to the tree root and a pointer to the
/// node itself.
pub trait AstNode: AstElement {
pub trait AstNode {
fn can_cast(kind: SyntaxKind) -> bool
where
Self: Sized;
fn cast_or_return(syntax: SyntaxNode) -> Result<Self, SyntaxNode>
where
Self: Sized;
fn cast(syntax: SyntaxNode) -> Option<Self>
where
Self: Sized,
{
<Self as AstNode>::cast_or_return(syntax).ok()
}
Self: Sized;
fn syntax(&self) -> &SyntaxNode;
fn into_syntax(self) -> SyntaxNode;
}
#[test]
@ -59,51 +48,22 @@ fn assert_ast_is_object_safe() {
}
/// Like `AstNode`, but wraps tokens rather than interior nodes.
pub trait AstToken: AstElement {
pub trait AstToken {
fn can_cast(token: SyntaxKind) -> bool
where
Self: Sized;
fn cast_or_return(syntax: SyntaxToken) -> Result<Self, SyntaxToken>
where
Self: Sized;
fn cast(syntax: SyntaxToken) -> Option<Self>
where
Self: Sized,
{
<Self as AstToken>::cast_or_return(syntax).ok()
}
Self: Sized;
fn syntax(&self) -> &SyntaxToken;
fn into_syntax(self) -> SyntaxToken;
fn text(&self) -> &SmolStr {
self.syntax().text()
}
}
/// Like `AstNode`, but wraps either nodes or tokens rather than interior nodes.
pub trait AstElement: std::fmt::Display {
fn can_cast_element(kind: SyntaxKind) -> bool
where
Self: Sized;
fn cast_or_return_element(syntax: SyntaxElement) -> Result<Self, SyntaxElement>
where
Self: Sized;
fn cast_element(syntax: SyntaxElement) -> Option<Self>
where
Self: Sized,
{
<Self as AstElement>::cast_or_return_element(syntax).ok()
}
fn syntax_element(&self) -> NodeOrToken<&SyntaxNode, &SyntaxToken>;
fn into_syntax_element(self) -> SyntaxElement;
}
/// An iterator over `SyntaxNode` children of a particular AST type.
#[derive(Debug, Clone)]
pub struct AstChildren<N> {
@ -132,64 +92,6 @@ fn children<P: AstNode + ?Sized, C: AstNode>(parent: &P) -> AstChildren<C> {
AstChildren::new(parent.syntax())
}
/// An iterator over `SyntaxToken` children of a particular AST type.
#[derive(Debug, Clone)]
pub struct AstChildTokens<N> {
inner: SyntaxElementChildren,
ph: PhantomData<N>,
}
impl<N> AstChildTokens<N> {
fn new(parent: &SyntaxNode) -> Self {
AstChildTokens { inner: parent.children_with_tokens(), ph: PhantomData }
}
}
impl<N: AstToken> Iterator for AstChildTokens<N> {
type Item = N;
fn next(&mut self) -> Option<N> {
self.inner.by_ref().filter_map(|x| x.into_token()).find_map(N::cast)
}
}
fn child_token_opt<P: AstNode + ?Sized, C: AstToken>(parent: &P) -> Option<C> {
child_tokens(parent).next()
}
fn child_tokens<P: AstNode + ?Sized, C: AstToken>(parent: &P) -> AstChildTokens<C> {
AstChildTokens::new(parent.syntax())
}
/// An iterator over `SyntaxNode` children of a particular AST type.
#[derive(Debug, Clone)]
pub struct AstChildElements<N> {
inner: SyntaxElementChildren,
ph: PhantomData<N>,
}
impl<N> AstChildElements<N> {
fn new(parent: &SyntaxNode) -> Self {
AstChildElements { inner: parent.children_with_tokens(), ph: PhantomData }
}
}
impl<N: AstElement> Iterator for AstChildElements<N> {
type Item = N;
fn next(&mut self) -> Option<N> {
self.inner.by_ref().find_map(N::cast_element)
}
}
#[allow(dead_code)]
fn child_element_opt<P: AstNode + ?Sized, C: AstElement>(parent: &P) -> Option<C> {
child_elements(parent).next()
}
#[allow(dead_code)]
fn child_elements<P: AstNode + ?Sized, C: AstElement>(parent: &P) -> AstChildElements<C> {
AstChildElements::new(parent.syntax())
}
#[test]
fn test_doc_comment_none() {
let file = SourceFile::parse(

File diff suppressed because it is too large Load diff

View file

@ -97,11 +97,13 @@ fn generate_ast(kinds: KindsSrc<'_>, grammar: AstSrc<'_>) -> Result<String> {
let name = format_ident!("{}", to_pascal_case(kind_str));
quote! {
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct #name(SyntaxToken);
pub struct #name {
pub(crate) syntax: SyntaxToken,
}
impl std::fmt::Display for #name {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
std::fmt::Display::fmt(&self.syntax, f)
}
}
@ -112,29 +114,10 @@ fn generate_ast(kinds: KindsSrc<'_>, grammar: AstSrc<'_>) -> Result<String> {
_ => false,
}
}
fn cast_or_return(syntax: SyntaxToken) -> Result<Self, SyntaxToken> {
if Self::can_cast(syntax.kind()) { Ok(Self(syntax)) } else { Err(syntax) }
}
fn syntax(&self) -> &SyntaxToken { &self.0 }
fn into_syntax(self) -> SyntaxToken { self.0 }
}
impl AstElement for #name {
fn can_cast_element(kind: SyntaxKind) -> bool {
match kind {
#kind => true,
_ => false,
}
}
fn cast_or_return_element(syntax: SyntaxElement) -> Result<Self, SyntaxElement> {
if Self::can_cast_element(syntax.kind()) { Ok(Self(syntax.into_token().unwrap())) } else { Err(syntax) }
}
fn syntax_element(&self) -> NodeOrToken<&SyntaxNode, &SyntaxToken> {
NodeOrToken::Token(&self.0)
}
fn into_syntax_element(self) -> SyntaxElement {
NodeOrToken::Token(self.0)
fn cast(syntax: SyntaxToken) -> Option<Self> {
if Self::can_cast(syntax.kind()) { Some(Self { syntax }) } else { None }
}
fn syntax(&self) -> &SyntaxToken { &self.syntax }
}
}
});
@ -156,28 +139,21 @@ fn generate_ast(kinds: KindsSrc<'_>, grammar: AstSrc<'_>) -> Result<String> {
FieldSrc::Optional(ty) | FieldSrc::Many(ty) => ty,
FieldSrc::Shorthand => name,
};
let element_kinds = &element_kinds_map.get(*ty).unwrap_or_else(|| panic!("type not found: {}", *ty));
let iter = if !element_kinds.has_tokens {
format_ident!("AstChildren")
} else if !element_kinds.has_nodes {
format_ident!("AstChildTokens")
} else {
format_ident!("AstChildElements")
};
let ty = format_ident!("{}", ty);
match field {
FieldSrc::Many(_) => {
quote! {
pub fn #method_name(&self) -> #iter<#ty> {
#iter::new(&self.syntax)
pub fn #method_name(&self) -> AstChildren<#ty> {
AstChildren::new(&self.syntax)
}
}
}
FieldSrc::Optional(_) | FieldSrc::Shorthand => {
quote! {
pub fn #method_name(&self) -> Option<#ty> {
#iter::new(&self.syntax).next()
AstChildren::new(&self.syntax).next()
}
}
}
@ -203,29 +179,10 @@ fn generate_ast(kinds: KindsSrc<'_>, grammar: AstSrc<'_>) -> Result<String> {
_ => false,
}
}
fn cast_or_return(syntax: SyntaxNode) -> Result<Self, SyntaxNode> {
if Self::can_cast(syntax.kind()) { Ok(Self { syntax }) } else { Err(syntax) }
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) { Some(Self { syntax }) } else { None }
}
fn syntax(&self) -> &SyntaxNode { &self.syntax }
fn into_syntax(self) -> SyntaxNode { self.syntax }
}
impl AstElement for #name {
fn can_cast_element(kind: SyntaxKind) -> bool {
match kind {
#kind => true,
_ => false,
}
}
fn cast_or_return_element(syntax: SyntaxElement) -> Result<Self, SyntaxElement> {
if Self::can_cast_element(syntax.kind()) { Ok(Self { syntax: syntax.into_node().unwrap() }) } else { Err(syntax) }
}
fn syntax_element(&self) -> NodeOrToken<&SyntaxNode, &SyntaxToken> {
NodeOrToken::Node(&self.syntax)
}
fn into_syntax_element(self) -> SyntaxElement {
NodeOrToken::Node(self.syntax)
}
}
#(#traits)*
@ -238,71 +195,16 @@ fn generate_ast(kinds: KindsSrc<'_>, grammar: AstSrc<'_>) -> Result<String> {
let enums = grammar.enums.iter().map(|en| {
let variants = en.variants.iter().map(|var| format_ident!("{}", var)).collect::<Vec<_>>();
let element_kinds = &element_kinds_map[&en.name.to_string()];
let name = format_ident!("{}", en.name);
let kinds = en.variants
let kinds = variants
.iter()
.map(|name| {
element_kinds_map[*name].kinds.iter().collect::<Vec<_>>()
})
.map(|name| format_ident!("{}", to_upper_snake_case(&name.to_string())))
.collect::<Vec<_>>();
let traits = en.traits.iter().map(|trait_name| {
let trait_name = format_ident!("{}", trait_name);
quote!(impl ast::#trait_name for #name {})
});
let all_kinds = &element_kinds.kinds;
let specific_ast_trait = if element_kinds.has_nodes != element_kinds.has_tokens {
let (ast_trait, syntax_type) = if element_kinds.has_tokens {
(
quote!(AstToken),
quote!(SyntaxToken),
)
} else {
(
quote!(AstNode),
quote!(SyntaxNode),
)
};
quote! {
impl #ast_trait for #name {
fn can_cast(kind: SyntaxKind) -> bool {
match kind {
#(#all_kinds)|* => true,
_ => false,
}
}
#[allow(unreachable_patterns)]
fn cast_or_return(syntax: #syntax_type) -> Result<Self, #syntax_type> {
match syntax.kind() {
#(
#(#kinds)|* => #variants::cast_or_return(syntax).map(|x| #name::#variants(x)),
)*
_ => Err(syntax),
}
}
fn syntax(&self) -> &#syntax_type {
match self {
#(
#name::#variants(it) => it.syntax(),
)*
}
}
fn into_syntax(self) -> #syntax_type {
match self {
#(
#name::#variants(it) => it.into_syntax(),
)*
}
}
}
}
} else {
Default::default()
};
quote! {
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum #name {
@ -319,48 +221,34 @@ fn generate_ast(kinds: KindsSrc<'_>, grammar: AstSrc<'_>) -> Result<String> {
impl std::fmt::Display for #name {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
#(
#name::#variants(it) => std::fmt::Display::fmt(it, f),
)*
}
std::fmt::Display::fmt(self.syntax(), f)
}
}
#specific_ast_trait
impl AstElement for #name {
fn can_cast_element(kind: SyntaxKind) -> bool {
impl AstNode for #name {
fn can_cast(kind: SyntaxKind) -> bool {
match kind {
#(#all_kinds)|* => true,
#(#kinds)|* => true,
_ => false,
}
}
#[allow(unreachable_patterns)]
fn cast_or_return_element(syntax: SyntaxElement) -> Result<Self, SyntaxElement> {
match syntax.kind() {
fn cast(syntax: SyntaxNode) -> Option<Self> {
let res = match syntax.kind() {
#(
#(#kinds)|* => #variants::cast_or_return_element(syntax).map(|x| #name::#variants(x)),
#kinds => #name::#variants(#variants { syntax }),
)*
_ => Err(syntax),
}
_ => return None,
};
Some(res)
}
fn syntax_element(&self) -> NodeOrToken<&SyntaxNode, &SyntaxToken> {
fn syntax(&self) -> &SyntaxNode {
match self {
#(
#name::#variants(it) => it.syntax_element(),
)*
}
}
fn into_syntax_element(self) -> SyntaxElement {
match self {
#(
#name::#variants(it) => it.into_syntax_element(),
#name::#variants(it) => &it.syntax,
)*
}
}
}
#(#traits)*
}
});
@ -380,7 +268,7 @@ fn generate_ast(kinds: KindsSrc<'_>, grammar: AstSrc<'_>) -> Result<String> {
#[allow(unused_imports)]
use crate::{
SyntaxNode, SyntaxToken, SyntaxElement, NodeOrToken, SyntaxKind::{self, *},
ast::{self, AstNode, AstToken, AstElement, AstChildren, AstChildTokens, AstChildElements},
ast::{self, AstNode, AstToken, AstChildren},
};
#(#tokens)*