1 //! A higher level attributes based on TokenTree, with also some shortcuts.
3 use std::{fmt, hash::Hash, ops, sync::Arc};
6 use cfg::{CfgExpr, CfgOptions};
8 use hir_expand::{hygiene::Hygiene, name::AsName, AstId, HirFileId, InFile};
9 use itertools::Itertools;
10 use la_arena::ArenaMap;
11 use mbe::{syntax_node_to_token_tree, DelimiterKind, Punct};
12 use smallvec::{smallvec, SmallVec};
14 ast::{self, AstNode, HasAttrs, IsString},
15 match_ast, AstPtr, AstToken, SmolStr, SyntaxNode, TextRange, TextSize,
22 item_tree::{ItemTreeId, ItemTreeNode},
23 nameres::ModuleSource,
24 path::{ModPath, PathKind},
25 src::{HasChildSource, HasSource},
26 AdtId, AttrDefId, EnumId, GenericParamId, HasModule, LocalEnumVariantId, LocalFieldId, Lookup,
30 /// Holds documentation
31 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
32 pub struct Documentation(String);
35 pub fn new(s: String) -> Self {
39 pub fn as_str(&self) -> &str {
44 impl From<Documentation> for String {
45 fn from(Documentation(string): Documentation) -> Self {
50 /// Syntactical attributes, without filtering of `cfg_attr`s.
51 #[derive(Default, Debug, Clone, PartialEq, Eq)]
52 pub(crate) struct RawAttrs {
53 entries: Option<Arc<[Attr]>>,
56 #[derive(Default, Debug, Clone, PartialEq, Eq)]
57 pub struct Attrs(RawAttrs);
59 #[derive(Debug, Clone, PartialEq, Eq)]
60 pub struct AttrsWithOwner {
65 impl ops::Deref for RawAttrs {
68 fn deref(&self) -> &[Attr] {
76 pub fn get(&self, id: AttrId) -> Option<&Attr> {
77 (**self).iter().find(|attr| attr.id == id)
81 impl ops::Deref for Attrs {
84 fn deref(&self) -> &[Attr] {
85 match &self.0.entries {
92 impl ops::Deref for AttrsWithOwner {
95 fn deref(&self) -> &Attrs {
101 pub(crate) const EMPTY: Self = Self { entries: None };
103 pub(crate) fn new(db: &dyn DefDatabase, owner: &dyn ast::HasAttrs, hygiene: &Hygiene) -> Self {
104 let entries = collect_attrs(owner)
105 .filter_map(|(id, attr)| match attr {
106 Either::Left(attr) => {
107 attr.meta().and_then(|meta| Attr::from_src(db, meta, hygiene, id))
109 Either::Right(comment) => comment.doc_comment().map(|doc| Attr {
111 input: Some(Interned::new(AttrInput::Literal(SmolStr::new(doc)))),
112 path: Interned::new(ModPath::from(hir_expand::name!(doc))),
115 .collect::<Arc<_>>();
117 Self { entries: if entries.is_empty() { None } else { Some(entries) } }
120 fn from_attrs_owner(db: &dyn DefDatabase, owner: InFile<&dyn ast::HasAttrs>) -> Self {
121 let hygiene = Hygiene::new(db.upcast(), owner.file_id);
122 Self::new(db, owner.value, &hygiene)
125 pub(crate) fn merge(&self, other: Self) -> Self {
126 // FIXME: This needs to fixup `AttrId`s
127 match (&self.entries, &other.entries) {
128 (None, None) => Self::EMPTY,
129 (Some(entries), None) | (None, Some(entries)) => {
130 Self { entries: Some(entries.clone()) }
132 (Some(a), Some(b)) => {
133 Self { entries: Some(a.iter().chain(b.iter()).cloned().collect()) }
138 /// Processes `cfg_attr`s, returning the resulting semantic `Attrs`.
139 pub(crate) fn filter(self, db: &dyn DefDatabase, krate: CrateId) -> Attrs {
140 let has_cfg_attrs = self.iter().any(|attr| {
141 attr.path.as_ident().map_or(false, |name| *name == hir_expand::name![cfg_attr])
147 let crate_graph = db.crate_graph();
150 .flat_map(|attr| -> SmallVec<[_; 1]> {
152 attr.path.as_ident().map_or(false, |name| *name == hir_expand::name![cfg_attr]);
154 return smallvec![attr.clone()];
157 let subtree = match attr.input.as_deref() {
158 Some(AttrInput::TokenTree(it, _)) => it,
159 _ => return smallvec![attr.clone()],
162 // Input subtree is: `(cfg, $(attr),+)`
163 // Split it up into a `cfg` subtree and the `attr` subtrees.
164 // FIXME: There should be a common API for this.
165 let mut parts = subtree.token_trees.split(
166 |tt| matches!(tt, tt::TokenTree::Leaf(tt::Leaf::Punct(p)) if p.char == ','),
168 let cfg = parts.next().unwrap();
169 let cfg = Subtree { delimiter: subtree.delimiter, token_trees: cfg.to_vec() };
170 let cfg = CfgExpr::parse(&cfg);
172 let attrs = parts.filter(|a| !a.is_empty()).filter_map(|attr| {
173 let tree = Subtree { delimiter: None, token_trees: attr.to_vec() };
175 let hygiene = Hygiene::new_unhygienic();
176 Attr::from_tt(db, &tree, &hygiene, index)
179 let cfg_options = &crate_graph[krate].cfg_options;
180 if cfg_options.check(&cfg) == Some(false) {
183 cov_mark::hit!(cfg_attr_active);
190 Attrs(RawAttrs { entries: Some(new_attrs) })
195 pub const EMPTY: Self = Self(RawAttrs::EMPTY);
197 pub(crate) fn variants_attrs_query(
198 db: &dyn DefDatabase,
200 ) -> Arc<ArenaMap<LocalEnumVariantId, Attrs>> {
201 let krate = e.lookup(db).container.krate;
202 let src = e.child_source(db);
203 let mut res = ArenaMap::default();
205 for (id, var) in src.value.iter() {
206 let attrs = RawAttrs::from_attrs_owner(db, src.with_value(var as &dyn ast::HasAttrs))
209 res.insert(id, attrs)
215 pub(crate) fn fields_attrs_query(
216 db: &dyn DefDatabase,
218 ) -> Arc<ArenaMap<LocalFieldId, Attrs>> {
219 let krate = v.module(db).krate;
220 let src = v.child_source(db);
221 let mut res = ArenaMap::default();
223 for (id, fld) in src.value.iter() {
224 let owner: &dyn HasAttrs = match fld {
225 Either::Left(tuple) => tuple,
226 Either::Right(record) => record,
228 let attrs = RawAttrs::from_attrs_owner(db, src.with_value(owner)).filter(db, krate);
230 res.insert(id, attrs);
236 pub fn by_key(&self, key: &'static str) -> AttrQuery<'_> {
237 AttrQuery { attrs: self, key }
242 pub fn cfg(&self) -> Option<CfgExpr> {
243 let mut cfgs = self.by_key("cfg").tt_values().map(CfgExpr::parse).collect::<Vec<_>>();
246 1 => Some(cfgs.pop().unwrap()),
247 _ => Some(CfgExpr::All(cfgs)),
250 pub(crate) fn is_cfg_enabled(&self, cfg_options: &CfgOptions) -> bool {
253 Some(cfg) => cfg_options.check(&cfg) != Some(false),
257 pub fn lang(&self) -> Option<&SmolStr> {
258 self.by_key("lang").string_value()
261 pub fn docs(&self) -> Option<Documentation> {
262 let docs = self.by_key("doc").attrs().flat_map(|attr| match attr.input.as_deref()? {
263 AttrInput::Literal(s) => Some(s),
264 AttrInput::TokenTree(..) => None,
268 .flat_map(|s| s.lines())
269 .filter(|line| !line.chars().all(|c| c.is_whitespace()))
270 .map(|line| line.chars().take_while(|c| c.is_whitespace()).count())
273 let mut buf = String::new();
275 // str::lines doesn't yield anything for the empty string
277 buf.extend(Itertools::intersperse(
278 doc.lines().map(|line| {
281 .map_or(line, |(offset, _)| &line[offset..])
293 Some(Documentation(buf))
297 pub fn has_doc_hidden(&self) -> bool {
298 self.by_key("doc").tt_values().any(|tt| {
299 tt.delimiter_kind() == Some(DelimiterKind::Parenthesis) &&
300 matches!(&*tt.token_trees, [tt::TokenTree::Leaf(tt::Leaf::Ident(ident))] if ident.text == "hidden")
304 pub fn is_proc_macro(&self) -> bool {
305 self.by_key("proc_macro").exists()
308 pub fn is_proc_macro_attribute(&self) -> bool {
309 self.by_key("proc_macro_attribute").exists()
312 pub fn is_proc_macro_derive(&self) -> bool {
313 self.by_key("proc_macro_derive").exists()
317 impl AttrsWithOwner {
318 pub(crate) fn attrs_query(db: &dyn DefDatabase, def: AttrDefId) -> Self {
319 // FIXME: this should use `Trace` to avoid duplication in `source_map` below
320 let raw_attrs = match def {
321 AttrDefId::ModuleId(module) => {
322 let def_map = module.def_map(db);
323 let mod_data = &def_map[module.local_id];
324 match mod_data.declaration_source(db) {
326 let raw_attrs = RawAttrs::from_attrs_owner(
328 it.as_ref().map(|it| it as &dyn ast::HasAttrs),
330 match mod_data.definition_source(db) {
331 InFile { file_id, value: ModuleSource::SourceFile(file) } => raw_attrs
332 .merge(RawAttrs::from_attrs_owner(db, InFile::new(file_id, &file))),
336 None => RawAttrs::from_attrs_owner(
338 mod_data.definition_source(db).as_ref().map(|src| match src {
339 ModuleSource::SourceFile(file) => file as &dyn ast::HasAttrs,
340 ModuleSource::Module(module) => module as &dyn ast::HasAttrs,
341 ModuleSource::BlockExpr(block) => block as &dyn ast::HasAttrs,
346 AttrDefId::FieldId(it) => {
347 return Self { attrs: db.fields_attrs(it.parent)[it.local_id].clone(), owner: def };
349 AttrDefId::EnumVariantId(it) => {
351 attrs: db.variants_attrs(it.parent)[it.local_id].clone(),
355 AttrDefId::AdtId(it) => match it {
356 AdtId::StructId(it) => attrs_from_item_tree(it.lookup(db).id, db),
357 AdtId::EnumId(it) => attrs_from_item_tree(it.lookup(db).id, db),
358 AdtId::UnionId(it) => attrs_from_item_tree(it.lookup(db).id, db),
360 AttrDefId::TraitId(it) => attrs_from_item_tree(it.lookup(db).id, db),
361 AttrDefId::MacroDefId(it) => it
363 .either(|ast_id| attrs_from_ast(ast_id, db), |ast_id| attrs_from_ast(ast_id, db)),
364 AttrDefId::ImplId(it) => attrs_from_item_tree(it.lookup(db).id, db),
365 AttrDefId::ConstId(it) => attrs_from_item_tree(it.lookup(db).id, db),
366 AttrDefId::StaticId(it) => attrs_from_item_tree(it.lookup(db).id, db),
367 AttrDefId::FunctionId(it) => attrs_from_item_tree(it.lookup(db).id, db),
368 AttrDefId::TypeAliasId(it) => attrs_from_item_tree(it.lookup(db).id, db),
369 AttrDefId::GenericParamId(it) => match it {
370 GenericParamId::TypeParamId(it) => {
371 let src = it.parent.child_source(db);
372 RawAttrs::from_attrs_owner(
375 src.value[it.local_id].as_ref().either(|it| it as _, |it| it as _),
379 GenericParamId::LifetimeParamId(it) => {
380 let src = it.parent.child_source(db);
381 RawAttrs::from_attrs_owner(db, src.with_value(&src.value[it.local_id]))
383 GenericParamId::ConstParamId(it) => {
384 let src = it.parent.child_source(db);
385 RawAttrs::from_attrs_owner(db, src.with_value(&src.value[it.local_id]))
388 AttrDefId::ExternBlockId(it) => attrs_from_item_tree(it.lookup(db).id, db),
391 let attrs = raw_attrs.filter(db, def.krate(db));
392 Self { attrs, owner: def }
395 pub fn source_map(&self, db: &dyn DefDatabase) -> AttrSourceMap {
396 let owner = match self.owner {
397 AttrDefId::ModuleId(module) => {
398 // Modules can have 2 attribute owners (the `mod x;` item, and the module file itself).
400 let def_map = module.def_map(db);
401 let mod_data = &def_map[module.local_id];
402 match mod_data.declaration_source(db) {
404 let mut map = AttrSourceMap::new(InFile::new(it.file_id, &it.value));
405 if let InFile { file_id, value: ModuleSource::SourceFile(file) } =
406 mod_data.definition_source(db)
408 map.append_module_inline_attrs(AttrSourceMap::new(InFile::new(
415 let InFile { file_id, value } = mod_data.definition_source(db);
416 let attrs_owner = match &value {
417 ModuleSource::SourceFile(file) => file as &dyn ast::HasAttrs,
418 ModuleSource::Module(module) => module as &dyn ast::HasAttrs,
419 ModuleSource::BlockExpr(block) => block as &dyn ast::HasAttrs,
421 return AttrSourceMap::new(InFile::new(file_id, attrs_owner));
425 AttrDefId::FieldId(id) => {
426 let map = db.fields_attrs_source_map(id.parent);
427 let file_id = id.parent.file_id(db);
428 let root = db.parse_or_expand(file_id).unwrap();
429 let owner = match &map[id.local_id] {
430 Either::Left(it) => ast::AnyHasAttrs::new(it.to_node(&root)),
431 Either::Right(it) => ast::AnyHasAttrs::new(it.to_node(&root)),
433 InFile::new(file_id, owner)
435 AttrDefId::AdtId(adt) => match adt {
436 AdtId::StructId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
437 AdtId::UnionId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
438 AdtId::EnumId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
440 AttrDefId::FunctionId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
441 AttrDefId::EnumVariantId(id) => {
442 let map = db.variants_attrs_source_map(id.parent);
443 let file_id = id.parent.lookup(db).id.file_id();
444 let root = db.parse_or_expand(file_id).unwrap();
445 InFile::new(file_id, ast::AnyHasAttrs::new(map[id.local_id].to_node(&root)))
447 AttrDefId::StaticId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
448 AttrDefId::ConstId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
449 AttrDefId::TraitId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
450 AttrDefId::TypeAliasId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
451 AttrDefId::MacroDefId(id) => id.ast_id().either(
452 |it| it.with_value(ast::AnyHasAttrs::new(it.to_node(db.upcast()))),
453 |it| it.with_value(ast::AnyHasAttrs::new(it.to_node(db.upcast()))),
455 AttrDefId::ImplId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
456 AttrDefId::GenericParamId(id) => match id {
457 GenericParamId::TypeParamId(id) => {
458 id.parent.child_source(db).map(|source| match &source[id.local_id] {
459 Either::Left(id) => ast::AnyHasAttrs::new(id.clone()),
460 Either::Right(id) => ast::AnyHasAttrs::new(id.clone()),
463 GenericParamId::LifetimeParamId(id) => id
466 .map(|source| ast::AnyHasAttrs::new(source[id.local_id].clone())),
467 GenericParamId::ConstParamId(id) => id
470 .map(|source| ast::AnyHasAttrs::new(source[id.local_id].clone())),
472 AttrDefId::ExternBlockId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
475 AttrSourceMap::new(owner.as_ref().map(|node| node as &dyn HasAttrs))
478 pub fn docs_with_rangemap(
480 db: &dyn DefDatabase,
481 ) -> Option<(Documentation, DocsRangeMap)> {
482 // FIXME: code duplication in `docs` above
483 let docs = self.by_key("doc").attrs().flat_map(|attr| match attr.input.as_deref()? {
484 AttrInput::Literal(s) => Some((s, attr.id)),
485 AttrInput::TokenTree(..) => None,
489 .flat_map(|(s, _)| s.lines())
490 .filter(|line| !line.chars().all(|c| c.is_whitespace()))
491 .map(|line| line.chars().take_while(|c| c.is_whitespace()).count())
494 let mut buf = String::new();
495 let mut mapping = Vec::new();
496 for (doc, idx) in docs {
498 let mut base_offset = 0;
499 for raw_line in doc.split('\n') {
500 let line = raw_line.trim_end();
501 let line_len = line.len();
502 let (offset, line) = match line.char_indices().nth(indent) {
503 Some((offset, _)) => (offset, &line[offset..]),
506 let buf_offset = buf.len();
509 TextRange::new(buf_offset.try_into().ok()?, buf.len().try_into().ok()?),
512 (base_offset + offset).try_into().ok()?,
513 line_len.try_into().ok()?,
517 base_offset += raw_line.len() + 1;
527 Some((Documentation(buf), DocsRangeMap { mapping, source_map: self.source_map(db) }))
534 ) -> Option<impl Iterator<Item = Either<ast::Attr, ast::Comment>>> {
535 let node = match_ast! {
537 ast::SourceFile(_) => syntax.clone(),
538 ast::ExternBlock(it) => it.extern_item_list()?.syntax().clone(),
539 ast::Fn(it) => it.body()?.stmt_list()?.syntax().clone(),
540 ast::Impl(it) => it.assoc_item_list()?.syntax().clone(),
541 ast::Module(it) => it.item_list()?.syntax().clone(),
542 ast::BlockExpr(it) => {
543 use syntax::SyntaxKind::{BLOCK_EXPR , EXPR_STMT};
544 // Block expressions accept outer and inner attributes, but only when they are the outer
545 // expression of an expression statement or the final expression of another block expression.
546 let may_carry_attributes = matches!(
547 it.syntax().parent().map(|it| it.kind()),
548 Some(BLOCK_EXPR | EXPR_STMT)
550 if !may_carry_attributes {
559 let attrs = ast::AttrDocCommentIter::from_syntax_node(&node).filter(|el| match el {
560 Either::Left(attr) => attr.kind().is_inner(),
561 Either::Right(comment) => comment.is_inner(),
567 pub struct AttrSourceMap {
568 source: Vec<Either<ast::Attr, ast::Comment>>,
570 /// If this map is for a module, this will be the [`HirFileId`] of the module's definition site,
571 /// while `file_id` will be the one of the module declaration site.
572 /// The usize is the index into `source` from which point on the entries reside in the def site
574 mod_def_site_file_id: Option<(HirFileId, usize)>,
578 fn new(owner: InFile<&dyn ast::HasAttrs>) -> Self {
580 source: collect_attrs(owner.value).map(|(_, it)| it).collect(),
581 file_id: owner.file_id,
582 mod_def_site_file_id: None,
586 /// Append a second source map to this one, this is required for modules, whose outline and inline
587 /// attributes can reside in different files
588 fn append_module_inline_attrs(&mut self, other: Self) {
589 assert!(self.mod_def_site_file_id.is_none() && other.mod_def_site_file_id.is_none());
590 let len = self.source.len();
591 self.source.extend(other.source);
592 if other.file_id != self.file_id {
593 self.mod_def_site_file_id = Some((other.file_id, len));
597 /// Maps the lowered `Attr` back to its original syntax node.
599 /// `attr` must come from the `owner` used for AttrSourceMap
601 /// Note that the returned syntax node might be a `#[cfg_attr]`, or a doc comment, instead of
602 /// the attribute represented by `Attr`.
603 pub fn source_of(&self, attr: &Attr) -> InFile<&Either<ast::Attr, ast::Comment>> {
604 self.source_of_id(attr.id)
607 fn source_of_id(&self, id: AttrId) -> InFile<&Either<ast::Attr, ast::Comment>> {
608 let ast_idx = id.ast_index as usize;
609 let file_id = match self.mod_def_site_file_id {
610 Some((file_id, def_site_cut)) if def_site_cut <= ast_idx => file_id,
616 .map(|it| InFile::new(file_id, it))
617 .unwrap_or_else(|| panic!("cannot find attr at index {:?}", id))
621 /// A struct to map text ranges from [`Documentation`] back to TextRanges in the syntax tree.
623 pub struct DocsRangeMap {
624 source_map: AttrSourceMap,
625 // (docstring-line-range, attr_index, attr-string-range)
626 // a mapping from the text range of a line of the [`Documentation`] to the attribute index and
627 // the original (untrimmed) syntax doc line
628 mapping: Vec<(TextRange, AttrId, TextRange)>,
632 /// Maps a [`TextRange`] relative to the documentation string back to its AST range
633 pub fn map(&self, range: TextRange) -> Option<InFile<TextRange>> {
634 let found = self.mapping.binary_search_by(|(probe, ..)| probe.ordering(range)).ok()?;
635 let (line_docs_range, idx, original_line_src_range) = self.mapping[found];
636 if !line_docs_range.contains_range(range) {
640 let relative_range = range - line_docs_range.start();
642 let InFile { file_id, value: source } = self.source_map.source_of_id(idx);
644 Either::Left(attr) => {
645 let string = get_doc_string_in_attr(&attr)?;
646 let text_range = string.open_quote_text_range()?;
647 let range = TextRange::at(
648 text_range.end() + original_line_src_range.start() + relative_range.start(),
649 string.syntax().text_range().len().min(range.len()),
651 Some(InFile { file_id, value: range })
653 Either::Right(comment) => {
654 let text_range = comment.syntax().text_range();
655 let range = TextRange::at(
657 + TextSize::try_from(comment.prefix().len()).ok()?
658 + original_line_src_range.start()
659 + relative_range.start(),
660 text_range.len().min(range.len()),
662 Some(InFile { file_id, value: range })
668 fn get_doc_string_in_attr(it: &ast::Attr) -> Option<ast::String> {
671 Some(ast::Expr::Literal(lit)) => match lit.kind() {
672 ast::LiteralKind::String(it) => Some(it),
675 // #[cfg_attr(..., doc = "", ...)]
677 // FIXME: See highlight injection for what to do here
684 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
686 pub(crate) ast_index: u32,
689 #[derive(Debug, Clone, PartialEq, Eq)]
691 pub(crate) id: AttrId,
692 pub(crate) path: Interned<ModPath>,
693 pub(crate) input: Option<Interned<AttrInput>>,
696 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
698 /// `#[attr = "string"]`
700 /// `#[attr(subtree)]`
701 TokenTree(tt::Subtree, mbe::TokenMap),
704 impl fmt::Display for AttrInput {
705 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
707 AttrInput::Literal(lit) => write!(f, " = \"{}\"", lit.escape_debug()),
708 AttrInput::TokenTree(subtree, _) => subtree.fmt(f),
715 db: &dyn DefDatabase,
720 let path = Interned::new(ModPath::from_src(db.upcast(), ast.path()?, hygiene)?);
721 let input = if let Some(ast::Expr::Literal(lit)) = ast.expr() {
722 let value = match lit.kind() {
723 ast::LiteralKind::String(string) => string.value()?.into(),
724 _ => lit.syntax().first_token()?.text().trim_matches('"').into(),
726 Some(Interned::new(AttrInput::Literal(value)))
727 } else if let Some(tt) = ast.token_tree() {
728 let (tree, map) = syntax_node_to_token_tree(tt.syntax());
729 Some(Interned::new(AttrInput::TokenTree(tree, map)))
733 Some(Attr { id, path, input })
737 db: &dyn DefDatabase,
742 let (parse, _) = mbe::token_tree_to_syntax_node(tt, mbe::TopEntryPoint::MetaItem);
743 let ast = ast::Meta::cast(parse.syntax_node())?;
745 Self::from_src(db, ast, hygiene, id)
748 /// Parses this attribute as a token tree consisting of comma separated paths.
749 pub fn parse_path_comma_token_tree(&self) -> Option<impl Iterator<Item = ModPath> + '_> {
750 let args = match self.input.as_deref() {
751 Some(AttrInput::TokenTree(args, _)) => args,
755 if args.delimiter_kind() != Some(DelimiterKind::Parenthesis) {
762 matches!(tt, tt::TokenTree::Leaf(tt::Leaf::Punct(Punct { char: ',', .. })))
765 .filter(|(comma, _)| !*comma)
767 let segments = tts.filter_map(|tt| match tt {
768 tt::TokenTree::Leaf(tt::Leaf::Ident(id)) => Some(id.as_name()),
771 ModPath::from_segments(PathKind::Plain, segments)
773 .collect::<Vec<_>>();
775 Some(paths.into_iter())
778 pub fn path(&self) -> &ModPath {
782 pub fn string_value(&self) -> Option<&SmolStr> {
783 match self.input.as_deref()? {
784 AttrInput::Literal(it) => Some(it),
790 #[derive(Debug, Clone, Copy)]
791 pub struct AttrQuery<'attr> {
796 impl<'attr> AttrQuery<'attr> {
797 pub fn tt_values(self) -> impl Iterator<Item = &'attr Subtree> {
798 self.attrs().filter_map(|attr| match attr.input.as_deref()? {
799 AttrInput::TokenTree(it, _) => Some(it),
804 pub fn string_value(self) -> Option<&'attr SmolStr> {
805 self.attrs().find_map(|attr| match attr.input.as_deref()? {
806 AttrInput::Literal(it) => Some(it),
811 pub fn exists(self) -> bool {
812 self.attrs().next().is_some()
815 pub fn attrs(self) -> impl Iterator<Item = &'attr Attr> + Clone {
819 .filter(move |attr| attr.path.as_ident().map_or(false, |s| s.to_smol_str() == key))
823 fn attrs_from_ast<N>(src: AstId<N>, db: &dyn DefDatabase) -> RawAttrs
827 let src = InFile::new(src.file_id, src.to_node(db.upcast()));
828 RawAttrs::from_attrs_owner(db, src.as_ref().map(|it| it as &dyn ast::HasAttrs))
831 fn attrs_from_item_tree<N: ItemTreeNode>(id: ItemTreeId<N>, db: &dyn DefDatabase) -> RawAttrs {
832 let tree = id.item_tree(db);
833 let mod_item = N::id_to_mod_item(id.value);
834 tree.raw_attrs(mod_item.into()).clone()
838 owner: &dyn ast::HasAttrs,
839 ) -> impl Iterator<Item = (AttrId, Either<ast::Attr, ast::Comment>)> {
840 let inner_attrs = inner_attributes(owner.syntax()).into_iter().flatten();
842 ast::AttrDocCommentIter::from_syntax_node(owner.syntax()).filter(|el| match el {
843 Either::Left(attr) => attr.kind().is_outer(),
844 Either::Right(comment) => comment.is_outer(),
849 .map(|(id, attr)| (AttrId { ast_index: id as u32 }, attr))
852 pub(crate) fn variants_attrs_source_map(
853 db: &dyn DefDatabase,
855 ) -> Arc<ArenaMap<LocalEnumVariantId, AstPtr<ast::Variant>>> {
856 let mut res = ArenaMap::default();
857 let child_source = def.child_source(db);
859 for (idx, variant) in child_source.value.iter() {
860 res.insert(idx, AstPtr::new(variant));
866 pub(crate) fn fields_attrs_source_map(
867 db: &dyn DefDatabase,
869 ) -> Arc<ArenaMap<LocalFieldId, Either<AstPtr<ast::TupleField>, AstPtr<ast::RecordField>>>> {
870 let mut res = ArenaMap::default();
871 let child_source = def.child_source(db);
873 for (idx, variant) in child_source.value.iter() {
878 .either(|l| Either::Left(AstPtr::new(l)), |r| Either::Right(AstPtr::new(r))),