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, AttrId { ast_index, .. }: AttrId) -> Option<&Attr> {
77 (**self).get(ast_index as usize)
81 impl ops::Deref for Attrs {
84 fn deref(&self) -> &[Attr] {
85 match &self.0.entries {
92 impl ops::Index<AttrId> for Attrs {
95 fn index(&self, AttrId { ast_index, .. }: AttrId) -> &Self::Output {
96 &(**self)[ast_index as usize]
100 impl ops::Deref for AttrsWithOwner {
103 fn deref(&self) -> &Attrs {
109 pub(crate) const EMPTY: Self = Self { entries: None };
111 pub(crate) fn new(db: &dyn DefDatabase, owner: &dyn ast::HasAttrs, hygiene: &Hygiene) -> Self {
112 let entries = collect_attrs(owner)
113 .flat_map(|(id, attr)| match attr {
114 Either::Left(attr) => {
115 attr.meta().and_then(|meta| Attr::from_src(db, meta, hygiene, id))
117 Either::Right(comment) => comment.doc_comment().map(|doc| Attr {
119 input: Some(Interned::new(AttrInput::Literal(SmolStr::new(doc)))),
120 path: Interned::new(ModPath::from(hir_expand::name!(doc))),
123 .collect::<Arc<_>>();
125 Self { entries: if entries.is_empty() { None } else { Some(entries) } }
128 fn from_attrs_owner(db: &dyn DefDatabase, owner: InFile<&dyn ast::HasAttrs>) -> Self {
129 let hygiene = Hygiene::new(db.upcast(), owner.file_id);
130 Self::new(db, owner.value, &hygiene)
133 pub(crate) fn merge(&self, other: Self) -> Self {
134 // FIXME: This needs to fixup `AttrId`s
135 match (&self.entries, &other.entries) {
136 (None, None) => Self::EMPTY,
137 (Some(entries), None) | (None, Some(entries)) => {
138 Self { entries: Some(entries.clone()) }
140 (Some(a), Some(b)) => {
141 Self { entries: Some(a.iter().chain(b.iter()).cloned().collect()) }
146 /// Processes `cfg_attr`s, returning the resulting semantic `Attrs`.
147 pub(crate) fn filter(self, db: &dyn DefDatabase, krate: CrateId) -> Attrs {
148 let has_cfg_attrs = self.iter().any(|attr| {
149 attr.path.as_ident().map_or(false, |name| *name == hir_expand::name![cfg_attr])
155 let crate_graph = db.crate_graph();
158 .flat_map(|attr| -> SmallVec<[_; 1]> {
160 attr.path.as_ident().map_or(false, |name| *name == hir_expand::name![cfg_attr]);
162 return smallvec![attr.clone()];
165 let subtree = match attr.input.as_deref() {
166 Some(AttrInput::TokenTree(it, _)) => it,
167 _ => return smallvec![attr.clone()],
170 // Input subtree is: `(cfg, $(attr),+)`
171 // Split it up into a `cfg` subtree and the `attr` subtrees.
172 // FIXME: There should be a common API for this.
173 let mut parts = subtree.token_trees.split(
174 |tt| matches!(tt, tt::TokenTree::Leaf(tt::Leaf::Punct(p)) if p.char == ','),
176 let cfg = parts.next().unwrap();
177 let cfg = Subtree { delimiter: subtree.delimiter, token_trees: cfg.to_vec() };
178 let cfg = CfgExpr::parse(&cfg);
180 let attrs = parts.filter(|a| !a.is_empty()).filter_map(|attr| {
181 let tree = Subtree { delimiter: None, token_trees: attr.to_vec() };
183 let hygiene = Hygiene::new_unhygienic();
184 Attr::from_tt(db, &tree, &hygiene, index)
187 let cfg_options = &crate_graph[krate].cfg_options;
188 if cfg_options.check(&cfg) == Some(false) {
191 cov_mark::hit!(cfg_attr_active);
198 Attrs(RawAttrs { entries: Some(new_attrs) })
203 pub const EMPTY: Self = Self(RawAttrs::EMPTY);
205 pub(crate) fn variants_attrs_query(
206 db: &dyn DefDatabase,
208 ) -> Arc<ArenaMap<LocalEnumVariantId, Attrs>> {
209 let krate = e.lookup(db).container.krate;
210 let src = e.child_source(db);
211 let mut res = ArenaMap::default();
213 for (id, var) in src.value.iter() {
214 let attrs = RawAttrs::from_attrs_owner(db, src.with_value(var as &dyn ast::HasAttrs))
217 res.insert(id, attrs)
223 pub(crate) fn fields_attrs_query(
224 db: &dyn DefDatabase,
226 ) -> Arc<ArenaMap<LocalFieldId, Attrs>> {
227 let krate = v.module(db).krate;
228 let src = v.child_source(db);
229 let mut res = ArenaMap::default();
231 for (id, fld) in src.value.iter() {
232 let owner: &dyn HasAttrs = match fld {
233 Either::Left(tuple) => tuple,
234 Either::Right(record) => record,
236 let attrs = RawAttrs::from_attrs_owner(db, src.with_value(owner)).filter(db, krate);
238 res.insert(id, attrs);
244 pub fn by_key(&self, key: &'static str) -> AttrQuery<'_> {
245 AttrQuery { attrs: self, key }
248 pub fn cfg(&self) -> Option<CfgExpr> {
249 let mut cfgs = self.by_key("cfg").tt_values().map(CfgExpr::parse).collect::<Vec<_>>();
252 1 => Some(cfgs.pop().unwrap()),
253 _ => Some(CfgExpr::All(cfgs)),
256 pub(crate) fn is_cfg_enabled(&self, cfg_options: &CfgOptions) -> bool {
259 Some(cfg) => cfg_options.check(&cfg) != Some(false),
263 pub fn lang(&self) -> Option<&SmolStr> {
264 self.by_key("lang").string_value()
267 pub fn docs(&self) -> Option<Documentation> {
268 let docs = self.by_key("doc").attrs().flat_map(|attr| match attr.input.as_deref()? {
269 AttrInput::Literal(s) => Some(s),
270 AttrInput::TokenTree(..) => None,
274 .flat_map(|s| s.lines())
275 .filter(|line| !line.chars().all(|c| c.is_whitespace()))
276 .map(|line| line.chars().take_while(|c| c.is_whitespace()).count())
279 let mut buf = String::new();
281 // str::lines doesn't yield anything for the empty string
283 buf.extend(Itertools::intersperse(
284 doc.lines().map(|line| {
287 .map_or(line, |(offset, _)| &line[offset..])
299 Some(Documentation(buf))
303 pub fn has_doc_hidden(&self) -> bool {
304 self.by_key("doc").tt_values().any(|tt| {
305 tt.delimiter_kind() == Some(DelimiterKind::Parenthesis) &&
306 matches!(&*tt.token_trees, [tt::TokenTree::Leaf(tt::Leaf::Ident(ident))] if ident.text == "hidden")
311 impl AttrsWithOwner {
312 pub(crate) fn attrs_query(db: &dyn DefDatabase, def: AttrDefId) -> Self {
313 // FIXME: this should use `Trace` to avoid duplication in `source_map` below
314 let raw_attrs = match def {
315 AttrDefId::ModuleId(module) => {
316 let def_map = module.def_map(db);
317 let mod_data = &def_map[module.local_id];
318 match mod_data.declaration_source(db) {
320 let raw_attrs = RawAttrs::from_attrs_owner(
322 it.as_ref().map(|it| it as &dyn ast::HasAttrs),
324 match mod_data.definition_source(db) {
325 InFile { file_id, value: ModuleSource::SourceFile(file) } => raw_attrs
326 .merge(RawAttrs::from_attrs_owner(db, InFile::new(file_id, &file))),
330 None => RawAttrs::from_attrs_owner(
332 mod_data.definition_source(db).as_ref().map(|src| match src {
333 ModuleSource::SourceFile(file) => file as &dyn ast::HasAttrs,
334 ModuleSource::Module(module) => module as &dyn ast::HasAttrs,
335 ModuleSource::BlockExpr(block) => block as &dyn ast::HasAttrs,
340 AttrDefId::FieldId(it) => {
341 return Self { attrs: db.fields_attrs(it.parent)[it.local_id].clone(), owner: def };
343 AttrDefId::EnumVariantId(it) => {
345 attrs: db.variants_attrs(it.parent)[it.local_id].clone(),
349 AttrDefId::AdtId(it) => match it {
350 AdtId::StructId(it) => attrs_from_item_tree(it.lookup(db).id, db),
351 AdtId::EnumId(it) => attrs_from_item_tree(it.lookup(db).id, db),
352 AdtId::UnionId(it) => attrs_from_item_tree(it.lookup(db).id, db),
354 AttrDefId::TraitId(it) => attrs_from_item_tree(it.lookup(db).id, db),
355 AttrDefId::MacroDefId(it) => it
357 .either(|ast_id| attrs_from_ast(ast_id, db), |ast_id| attrs_from_ast(ast_id, db)),
358 AttrDefId::ImplId(it) => attrs_from_item_tree(it.lookup(db).id, db),
359 AttrDefId::ConstId(it) => attrs_from_item_tree(it.lookup(db).id, db),
360 AttrDefId::StaticId(it) => attrs_from_item_tree(it.lookup(db).id, db),
361 AttrDefId::FunctionId(it) => attrs_from_item_tree(it.lookup(db).id, db),
362 AttrDefId::TypeAliasId(it) => attrs_from_item_tree(it.lookup(db).id, db),
363 AttrDefId::GenericParamId(it) => match it {
364 GenericParamId::TypeParamId(it) => {
365 let src = it.parent.child_source(db);
366 RawAttrs::from_attrs_owner(
369 src.value[it.local_id].as_ref().either(|it| it as _, |it| it as _),
373 GenericParamId::LifetimeParamId(it) => {
374 let src = it.parent.child_source(db);
375 RawAttrs::from_attrs_owner(db, src.with_value(&src.value[it.local_id]))
377 GenericParamId::ConstParamId(it) => {
378 let src = it.parent.child_source(db);
379 RawAttrs::from_attrs_owner(db, src.with_value(&src.value[it.local_id]))
382 AttrDefId::ExternBlockId(it) => attrs_from_item_tree(it.lookup(db).id, db),
385 let attrs = raw_attrs.filter(db, def.krate(db));
386 Self { attrs, owner: def }
389 pub fn source_map(&self, db: &dyn DefDatabase) -> AttrSourceMap {
390 let owner = match self.owner {
391 AttrDefId::ModuleId(module) => {
392 // Modules can have 2 attribute owners (the `mod x;` item, and the module file itself).
394 let def_map = module.def_map(db);
395 let mod_data = &def_map[module.local_id];
396 match mod_data.declaration_source(db) {
398 let mut map = AttrSourceMap::new(InFile::new(it.file_id, &it.value));
399 if let InFile { file_id, value: ModuleSource::SourceFile(file) } =
400 mod_data.definition_source(db)
402 map.append_module_inline_attrs(AttrSourceMap::new(InFile::new(
409 let InFile { file_id, value } = mod_data.definition_source(db);
410 let attrs_owner = match &value {
411 ModuleSource::SourceFile(file) => file as &dyn ast::HasAttrs,
412 ModuleSource::Module(module) => module as &dyn ast::HasAttrs,
413 ModuleSource::BlockExpr(block) => block as &dyn ast::HasAttrs,
415 return AttrSourceMap::new(InFile::new(file_id, attrs_owner));
419 AttrDefId::FieldId(id) => {
420 let map = db.fields_attrs_source_map(id.parent);
421 let file_id = id.parent.file_id(db);
422 let root = db.parse_or_expand(file_id).unwrap();
423 let owner = match &map[id.local_id] {
424 Either::Left(it) => ast::AnyHasAttrs::new(it.to_node(&root)),
425 Either::Right(it) => ast::AnyHasAttrs::new(it.to_node(&root)),
427 InFile::new(file_id, owner)
429 AttrDefId::AdtId(adt) => match adt {
430 AdtId::StructId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
431 AdtId::UnionId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
432 AdtId::EnumId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
434 AttrDefId::FunctionId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
435 AttrDefId::EnumVariantId(id) => {
436 let map = db.variants_attrs_source_map(id.parent);
437 let file_id = id.parent.lookup(db).id.file_id();
438 let root = db.parse_or_expand(file_id).unwrap();
439 InFile::new(file_id, ast::AnyHasAttrs::new(map[id.local_id].to_node(&root)))
441 AttrDefId::StaticId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
442 AttrDefId::ConstId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
443 AttrDefId::TraitId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
444 AttrDefId::TypeAliasId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
445 AttrDefId::MacroDefId(id) => id.ast_id().either(
446 |it| it.with_value(ast::AnyHasAttrs::new(it.to_node(db.upcast()))),
447 |it| it.with_value(ast::AnyHasAttrs::new(it.to_node(db.upcast()))),
449 AttrDefId::ImplId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
450 AttrDefId::GenericParamId(id) => match id {
451 GenericParamId::TypeParamId(id) => {
452 id.parent.child_source(db).map(|source| match &source[id.local_id] {
453 Either::Left(id) => ast::AnyHasAttrs::new(id.clone()),
454 Either::Right(id) => ast::AnyHasAttrs::new(id.clone()),
457 GenericParamId::LifetimeParamId(id) => id
460 .map(|source| ast::AnyHasAttrs::new(source[id.local_id].clone())),
461 GenericParamId::ConstParamId(id) => id
464 .map(|source| ast::AnyHasAttrs::new(source[id.local_id].clone())),
466 AttrDefId::ExternBlockId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
469 AttrSourceMap::new(owner.as_ref().map(|node| node as &dyn HasAttrs))
472 pub fn docs_with_rangemap(
474 db: &dyn DefDatabase,
475 ) -> Option<(Documentation, DocsRangeMap)> {
476 // FIXME: code duplication in `docs` above
477 let docs = self.by_key("doc").attrs().flat_map(|attr| match attr.input.as_deref()? {
478 AttrInput::Literal(s) => Some((s, attr.id)),
479 AttrInput::TokenTree(..) => None,
483 .flat_map(|(s, _)| s.lines())
484 .filter(|line| !line.chars().all(|c| c.is_whitespace()))
485 .map(|line| line.chars().take_while(|c| c.is_whitespace()).count())
488 let mut buf = String::new();
489 let mut mapping = Vec::new();
490 for (doc, idx) in docs {
492 let mut base_offset = 0;
493 for raw_line in doc.split('\n') {
494 let line = raw_line.trim_end();
495 let line_len = line.len();
496 let (offset, line) = match line.char_indices().nth(indent) {
497 Some((offset, _)) => (offset, &line[offset..]),
500 let buf_offset = buf.len();
503 TextRange::new(buf_offset.try_into().ok()?, buf.len().try_into().ok()?),
506 (base_offset + offset).try_into().ok()?,
507 line_len.try_into().ok()?,
511 base_offset += raw_line.len() + 1;
521 Some((Documentation(buf), DocsRangeMap { mapping, source_map: self.source_map(db) }))
528 ) -> Option<(impl Iterator<Item = ast::Attr>, impl Iterator<Item = ast::Comment>)> {
529 let (attrs, docs) = match_ast! {
531 ast::SourceFile(it) => (it.attrs(), ast::DocCommentIter::from_syntax_node(it.syntax())),
532 ast::ExternBlock(it) => {
533 let extern_item_list = it.extern_item_list()?;
534 (extern_item_list.attrs(), ast::DocCommentIter::from_syntax_node(extern_item_list.syntax()))
537 let body = it.body()?;
538 let stmt_list = body.stmt_list()?;
539 (stmt_list.attrs(), ast::DocCommentIter::from_syntax_node(body.syntax()))
542 let assoc_item_list = it.assoc_item_list()?;
543 (assoc_item_list.attrs(), ast::DocCommentIter::from_syntax_node(assoc_item_list.syntax()))
546 let item_list = it.item_list()?;
547 (item_list.attrs(), ast::DocCommentIter::from_syntax_node(item_list.syntax()))
549 // FIXME: BlockExpr's only accept inner attributes in specific cases
550 // Excerpt from the reference:
551 // Block expressions accept outer and inner attributes, but only when they are the outer
552 // expression of an expression statement or the final expression of another block expression.
553 ast::BlockExpr(_it) => return None,
557 let attrs = attrs.filter(|attr| attr.kind().is_inner());
558 let docs = docs.filter(|doc| doc.is_inner());
563 pub struct AttrSourceMap {
564 source: Vec<Either<ast::Attr, ast::Comment>>,
566 /// If this map is for a module, this will be the [`HirFileId`] of the module's definition site,
567 /// while `file_id` will be the one of the module declaration site.
568 /// The usize is the index into `source` from which point on the entries reside in the def site
570 mod_def_site_file_id: Option<(HirFileId, usize)>,
574 fn new(owner: InFile<&dyn ast::HasAttrs>) -> Self {
576 source: collect_attrs(owner.value).map(|(_, it)| it).collect(),
577 file_id: owner.file_id,
578 mod_def_site_file_id: None,
582 /// Append a second source map to this one, this is required for modules, whose outline and inline
583 /// attributes can reside in different files
584 fn append_module_inline_attrs(&mut self, other: Self) {
585 assert!(self.mod_def_site_file_id.is_none() && other.mod_def_site_file_id.is_none());
586 let len = self.source.len();
587 self.source.extend(other.source);
588 if other.file_id != self.file_id {
589 self.mod_def_site_file_id = Some((other.file_id, len));
593 /// Maps the lowered `Attr` back to its original syntax node.
595 /// `attr` must come from the `owner` used for AttrSourceMap
597 /// Note that the returned syntax node might be a `#[cfg_attr]`, or a doc comment, instead of
598 /// the attribute represented by `Attr`.
599 pub fn source_of(&self, attr: &Attr) -> InFile<&Either<ast::Attr, ast::Comment>> {
600 self.source_of_id(attr.id)
603 fn source_of_id(&self, id: AttrId) -> InFile<&Either<ast::Attr, ast::Comment>> {
604 let ast_idx = id.ast_index as usize;
605 let file_id = match self.mod_def_site_file_id {
606 Some((file_id, def_site_cut)) if def_site_cut <= ast_idx => file_id,
612 .map(|it| InFile::new(file_id, it))
613 .unwrap_or_else(|| panic!("cannot find attr at index {:?}", id))
617 /// A struct to map text ranges from [`Documentation`] back to TextRanges in the syntax tree.
619 pub struct DocsRangeMap {
620 source_map: AttrSourceMap,
621 // (docstring-line-range, attr_index, attr-string-range)
622 // a mapping from the text range of a line of the [`Documentation`] to the attribute index and
623 // the original (untrimmed) syntax doc line
624 mapping: Vec<(TextRange, AttrId, TextRange)>,
628 /// Maps a [`TextRange`] relative to the documentation string back to its AST range
629 pub fn map(&self, range: TextRange) -> Option<InFile<TextRange>> {
630 let found = self.mapping.binary_search_by(|(probe, ..)| probe.ordering(range)).ok()?;
631 let (line_docs_range, idx, original_line_src_range) = self.mapping[found];
632 if !line_docs_range.contains_range(range) {
636 let relative_range = range - line_docs_range.start();
638 let InFile { file_id, value: source } = self.source_map.source_of_id(idx);
640 Either::Left(attr) => {
641 let string = get_doc_string_in_attr(&attr)?;
642 let text_range = string.open_quote_text_range()?;
643 let range = TextRange::at(
644 text_range.end() + original_line_src_range.start() + relative_range.start(),
645 string.syntax().text_range().len().min(range.len()),
647 Some(InFile { file_id, value: range })
649 Either::Right(comment) => {
650 let text_range = comment.syntax().text_range();
651 let range = TextRange::at(
653 + TextSize::try_from(comment.prefix().len()).ok()?
654 + original_line_src_range.start()
655 + relative_range.start(),
656 text_range.len().min(range.len()),
658 Some(InFile { file_id, value: range })
664 fn get_doc_string_in_attr(it: &ast::Attr) -> Option<ast::String> {
667 Some(ast::Expr::Literal(lit)) => match lit.kind() {
668 ast::LiteralKind::String(it) => Some(it),
671 // #[cfg_attr(..., doc = "", ...)]
673 // FIXME: See highlight injection for what to do here
680 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
682 pub(crate) ast_index: u32,
685 #[derive(Debug, Clone, PartialEq, Eq)]
687 pub(crate) id: AttrId,
688 pub(crate) path: Interned<ModPath>,
689 pub(crate) input: Option<Interned<AttrInput>>,
692 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
694 /// `#[attr = "string"]`
696 /// `#[attr(subtree)]`
697 TokenTree(tt::Subtree, mbe::TokenMap),
700 impl fmt::Display for AttrInput {
701 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
703 AttrInput::Literal(lit) => write!(f, " = \"{}\"", lit.escape_debug()),
704 AttrInput::TokenTree(subtree, _) => subtree.fmt(f),
711 db: &dyn DefDatabase,
716 let path = Interned::new(ModPath::from_src(db, ast.path()?, hygiene)?);
717 let input = if let Some(ast::Expr::Literal(lit)) = ast.expr() {
718 let value = match lit.kind() {
719 ast::LiteralKind::String(string) => string.value()?.into(),
720 _ => lit.syntax().first_token()?.text().trim_matches('"').into(),
722 Some(Interned::new(AttrInput::Literal(value)))
723 } else if let Some(tt) = ast.token_tree() {
724 let (tree, map) = syntax_node_to_token_tree(tt.syntax());
725 Some(Interned::new(AttrInput::TokenTree(tree, map)))
729 Some(Attr { id, path, input })
733 db: &dyn DefDatabase,
738 let (parse, _) = mbe::token_tree_to_syntax_node(tt, mbe::TopEntryPoint::MetaItem).ok()?;
739 let ast = ast::Meta::cast(parse.syntax_node())?;
741 Self::from_src(db, ast, hygiene, id)
744 /// Parses this attribute as a token tree consisting of comma separated paths.
745 pub fn parse_path_comma_token_tree(&self) -> Option<impl Iterator<Item = ModPath> + '_> {
746 let args = match self.input.as_deref() {
747 Some(AttrInput::TokenTree(args, _)) => args,
751 if args.delimiter_kind() != Some(DelimiterKind::Parenthesis) {
758 matches!(tt, tt::TokenTree::Leaf(tt::Leaf::Punct(Punct { char: ',', .. })))
761 .filter(|(comma, _)| !*comma)
763 let segments = tts.filter_map(|tt| match tt {
764 tt::TokenTree::Leaf(tt::Leaf::Ident(id)) => Some(id.as_name()),
767 ModPath::from_segments(PathKind::Plain, segments)
769 .collect::<Vec<_>>();
771 Some(paths.into_iter())
774 pub fn path(&self) -> &ModPath {
778 pub fn string_value(&self) -> Option<&SmolStr> {
779 match self.input.as_deref()? {
780 AttrInput::Literal(it) => Some(it),
786 #[derive(Debug, Clone, Copy)]
787 pub struct AttrQuery<'attr> {
792 impl<'attr> AttrQuery<'attr> {
793 pub fn tt_values(self) -> impl Iterator<Item = &'attr Subtree> {
794 self.attrs().filter_map(|attr| match attr.input.as_deref()? {
795 AttrInput::TokenTree(it, _) => Some(it),
800 pub fn string_value(self) -> Option<&'attr SmolStr> {
801 self.attrs().find_map(|attr| match attr.input.as_deref()? {
802 AttrInput::Literal(it) => Some(it),
807 pub fn exists(self) -> bool {
808 self.attrs().next().is_some()
811 pub fn attrs(self) -> impl Iterator<Item = &'attr Attr> + Clone {
815 .filter(move |attr| attr.path.as_ident().map_or(false, |s| s.to_smol_str() == key))
819 fn attrs_from_ast<N>(src: AstId<N>, db: &dyn DefDatabase) -> RawAttrs
823 let src = InFile::new(src.file_id, src.to_node(db.upcast()));
824 RawAttrs::from_attrs_owner(db, src.as_ref().map(|it| it as &dyn ast::HasAttrs))
827 fn attrs_from_item_tree<N: ItemTreeNode>(id: ItemTreeId<N>, db: &dyn DefDatabase) -> RawAttrs {
828 let tree = id.item_tree(db);
829 let mod_item = N::id_to_mod_item(id.value);
830 tree.raw_attrs(mod_item.into()).clone()
834 owner: &dyn ast::HasAttrs,
835 ) -> impl Iterator<Item = (AttrId, Either<ast::Attr, ast::Comment>)> {
836 let (inner_attrs, inner_docs) = inner_attributes(owner.syntax())
837 .map_or((None, None), |(attrs, docs)| (Some(attrs), Some(docs)));
839 let outer_attrs = owner.attrs().filter(|attr| attr.kind().is_outer());
840 let attrs = outer_attrs
841 .chain(inner_attrs.into_iter().flatten())
842 .map(|attr| (attr.syntax().text_range().start(), Either::Left(attr)));
845 ast::DocCommentIter::from_syntax_node(owner.syntax()).filter(ast::Comment::is_outer);
846 let docs = outer_docs
847 .chain(inner_docs.into_iter().flatten())
848 .map(|docs_text| (docs_text.syntax().text_range().start(), Either::Right(docs_text)));
849 // sort here by syntax node offset because the source can have doc attributes and doc strings be interleaved
851 .sorted_by_key(|&(offset, _)| offset)
853 .map(|(id, (_, attr))| (AttrId { ast_index: id as u32 }, attr))
856 pub(crate) fn variants_attrs_source_map(
857 db: &dyn DefDatabase,
859 ) -> Arc<ArenaMap<LocalEnumVariantId, AstPtr<ast::Variant>>> {
860 let mut res = ArenaMap::default();
861 let child_source = def.child_source(db);
863 for (idx, variant) in child_source.value.iter() {
864 res.insert(idx, AstPtr::new(variant));
870 pub(crate) fn fields_attrs_source_map(
871 db: &dyn DefDatabase,
873 ) -> Arc<ArenaMap<LocalFieldId, Either<AstPtr<ast::TupleField>, AstPtr<ast::RecordField>>>> {
874 let mut res = ArenaMap::default();
875 let child_source = def.child_source(db);
877 for (idx, variant) in child_source.value.iter() {
882 .either(|l| Either::Left(AstPtr::new(l)), |r| Either::Right(AstPtr::new(r))),