Reduce allocations in attribute collection

This commit is contained in:
Lukas Wirth 2022-01-30 22:18:32 +01:00
parent c08df0f1f5
commit cc04cfc982
9 changed files with 61 additions and 70 deletions

View file

@ -160,14 +160,9 @@ impl ast::Attr {
}
pub fn kind(&self) -> AttrKind {
let first_token = self.syntax().first_token();
let first_token_kind = first_token.as_ref().map(SyntaxToken::kind);
let second_token_kind =
first_token.and_then(|token| token.next_token()).as_ref().map(SyntaxToken::kind);
match (first_token_kind, second_token_kind) {
(Some(T![#]), Some(T![!])) => AttrKind::Inner,
_ => AttrKind::Outer,
match self.excl_token() {
Some(_) => AttrKind::Inner,
None => AttrKind::Outer,
}
}

View file

@ -76,8 +76,8 @@ pub trait HasDocComments: HasAttrs {
fn doc_comments(&self) -> DocCommentIter {
DocCommentIter { iter: self.syntax().children_with_tokens() }
}
fn doc_comments_and_attrs(&self) -> AttrCommentIter {
AttrCommentIter { iter: self.syntax().children_with_tokens() }
fn doc_comments_and_attrs(&self) -> AttrDocCommentIter {
AttrDocCommentIter { iter: self.syntax().children_with_tokens() }
}
}
@ -113,17 +113,23 @@ impl Iterator for DocCommentIter {
}
}
pub struct AttrCommentIter {
pub struct AttrDocCommentIter {
iter: SyntaxElementChildren,
}
impl Iterator for AttrCommentIter {
type Item = Either<ast::Comment, ast::Attr>;
impl AttrDocCommentIter {
pub fn from_syntax_node(syntax_node: &ast::SyntaxNode) -> AttrDocCommentIter {
AttrDocCommentIter { iter: syntax_node.children_with_tokens() }
}
}
impl Iterator for AttrDocCommentIter {
type Item = Either<ast::Attr, ast::Comment>;
fn next(&mut self) -> Option<Self::Item> {
self.iter.by_ref().find_map(|el| match el {
SyntaxElement::Node(node) => ast::Attr::cast(node).map(Either::Right),
SyntaxElement::Node(node) => ast::Attr::cast(node).map(Either::Left),
SyntaxElement::Token(tok) => {
ast::Comment::cast(tok).filter(ast::Comment::is_doc).map(Either::Left)
ast::Comment::cast(tok).filter(ast::Comment::is_doc).map(Either::Right)
}
})
}