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 impl ops::Deref for Attrs {
79 fn deref(&self) -> &[Attr] {
80 match &self.0.entries {
87 impl ops::Index<AttrId> for Attrs {
90 fn index(&self, AttrId { ast_index, .. }: AttrId) -> &Self::Output {
91 &(**self)[ast_index as usize]
95 impl ops::Deref for AttrsWithOwner {
98 fn deref(&self) -> &Attrs {
104 pub(crate) const EMPTY: Self = Self { entries: None };
106 pub(crate) fn new(db: &dyn DefDatabase, owner: &dyn ast::HasAttrs, hygiene: &Hygiene) -> Self {
107 let entries = collect_attrs(owner)
108 .flat_map(|(id, attr)| match attr {
109 Either::Left(attr) => {
110 attr.meta().and_then(|meta| Attr::from_src(db, meta, hygiene, id))
112 Either::Right(comment) => comment.doc_comment().map(|doc| Attr {
114 input: Some(Interned::new(AttrInput::Literal(SmolStr::new(doc)))),
115 path: Interned::new(ModPath::from(hir_expand::name!(doc))),
118 .collect::<Arc<_>>();
120 Self { entries: if entries.is_empty() { None } else { Some(entries) } }
123 fn from_attrs_owner(db: &dyn DefDatabase, owner: InFile<&dyn ast::HasAttrs>) -> Self {
124 let hygiene = Hygiene::new(db.upcast(), owner.file_id);
125 Self::new(db, owner.value, &hygiene)
128 pub(crate) fn merge(&self, other: Self) -> Self {
129 // FIXME: This needs to fixup `AttrId`s
130 match (&self.entries, &other.entries) {
131 (None, None) => Self::EMPTY,
132 (Some(entries), None) | (None, Some(entries)) => {
133 Self { entries: Some(entries.clone()) }
135 (Some(a), Some(b)) => {
136 Self { entries: Some(a.iter().chain(b.iter()).cloned().collect()) }
141 /// Processes `cfg_attr`s, returning the resulting semantic `Attrs`.
142 pub(crate) fn filter(self, db: &dyn DefDatabase, krate: CrateId) -> Attrs {
143 let has_cfg_attrs = self.iter().any(|attr| {
144 attr.path.as_ident().map_or(false, |name| *name == hir_expand::name![cfg_attr])
150 let crate_graph = db.crate_graph();
153 .flat_map(|attr| -> SmallVec<[_; 1]> {
155 attr.path.as_ident().map_or(false, |name| *name == hir_expand::name![cfg_attr]);
157 return smallvec![attr.clone()];
160 let subtree = match attr.input.as_deref() {
161 Some(AttrInput::TokenTree(it, _)) => it,
162 _ => return smallvec![attr.clone()],
165 // Input subtree is: `(cfg, $(attr),+)`
166 // Split it up into a `cfg` subtree and the `attr` subtrees.
167 // FIXME: There should be a common API for this.
168 let mut parts = subtree.token_trees.split(
169 |tt| matches!(tt, tt::TokenTree::Leaf(tt::Leaf::Punct(p)) if p.char == ','),
171 let cfg = parts.next().unwrap();
172 let cfg = Subtree { delimiter: subtree.delimiter, token_trees: cfg.to_vec() };
173 let cfg = CfgExpr::parse(&cfg);
175 let attrs = parts.filter(|a| !a.is_empty()).filter_map(|attr| {
176 let tree = Subtree { delimiter: None, token_trees: attr.to_vec() };
178 let hygiene = Hygiene::new_unhygienic();
179 Attr::from_tt(db, &tree, &hygiene, index)
182 let cfg_options = &crate_graph[krate].cfg_options;
183 if cfg_options.check(&cfg) == Some(false) {
186 cov_mark::hit!(cfg_attr_active);
193 Attrs(RawAttrs { entries: Some(new_attrs) })
198 pub const EMPTY: Self = Self(RawAttrs::EMPTY);
200 pub(crate) fn variants_attrs_query(
201 db: &dyn DefDatabase,
203 ) -> Arc<ArenaMap<LocalEnumVariantId, Attrs>> {
204 let krate = e.lookup(db).container.krate;
205 let src = e.child_source(db);
206 let mut res = ArenaMap::default();
208 for (id, var) in src.value.iter() {
209 let attrs = RawAttrs::from_attrs_owner(db, src.with_value(var as &dyn ast::HasAttrs))
212 res.insert(id, attrs)
218 pub(crate) fn fields_attrs_query(
219 db: &dyn DefDatabase,
221 ) -> Arc<ArenaMap<LocalFieldId, Attrs>> {
222 let krate = v.module(db).krate;
223 let src = v.child_source(db);
224 let mut res = ArenaMap::default();
226 for (id, fld) in src.value.iter() {
227 let owner: &dyn HasAttrs = match fld {
228 Either::Left(tuple) => tuple,
229 Either::Right(record) => record,
231 let attrs = RawAttrs::from_attrs_owner(db, src.with_value(owner)).filter(db, krate);
233 res.insert(id, attrs);
239 pub fn by_key(&self, key: &'static str) -> AttrQuery<'_> {
240 AttrQuery { attrs: self, key }
243 pub fn cfg(&self) -> Option<CfgExpr> {
244 let mut cfgs = self.by_key("cfg").tt_values().map(CfgExpr::parse).collect::<Vec<_>>();
247 1 => Some(cfgs.pop().unwrap()),
248 _ => Some(CfgExpr::All(cfgs)),
251 pub(crate) fn is_cfg_enabled(&self, cfg_options: &CfgOptions) -> bool {
254 Some(cfg) => cfg_options.check(&cfg) != Some(false),
258 pub fn docs(&self) -> Option<Documentation> {
259 let docs = self.by_key("doc").attrs().flat_map(|attr| match attr.input.as_deref()? {
260 AttrInput::Literal(s) => Some(s),
261 AttrInput::TokenTree(..) => None,
265 .flat_map(|s| s.lines())
266 .filter(|line| !line.chars().all(|c| c.is_whitespace()))
267 .map(|line| line.chars().take_while(|c| c.is_whitespace()).count())
270 let mut buf = String::new();
272 // str::lines doesn't yield anything for the empty string
274 buf.extend(Itertools::intersperse(
275 doc.lines().map(|line| {
278 .map_or(line, |(offset, _)| &line[offset..])
290 Some(Documentation(buf))
294 pub fn has_doc_hidden(&self) -> bool {
295 self.by_key("doc").tt_values().any(|tt| {
296 tt.delimiter_kind() == Some(DelimiterKind::Parenthesis) &&
297 matches!(&*tt.token_trees, [tt::TokenTree::Leaf(tt::Leaf::Ident(ident))] if ident.text == "hidden")
302 impl AttrsWithOwner {
303 pub(crate) fn attrs_query(db: &dyn DefDatabase, def: AttrDefId) -> Self {
304 // FIXME: this should use `Trace` to avoid duplication in `source_map` below
305 let raw_attrs = match def {
306 AttrDefId::ModuleId(module) => {
307 let def_map = module.def_map(db);
308 let mod_data = &def_map[module.local_id];
309 match mod_data.declaration_source(db) {
311 let raw_attrs = RawAttrs::from_attrs_owner(
313 it.as_ref().map(|it| it as &dyn ast::HasAttrs),
315 match mod_data.definition_source(db) {
316 InFile { file_id, value: ModuleSource::SourceFile(file) } => raw_attrs
317 .merge(RawAttrs::from_attrs_owner(db, InFile::new(file_id, &file))),
321 None => RawAttrs::from_attrs_owner(
323 mod_data.definition_source(db).as_ref().map(|src| match src {
324 ModuleSource::SourceFile(file) => file as &dyn ast::HasAttrs,
325 ModuleSource::Module(module) => module as &dyn ast::HasAttrs,
326 ModuleSource::BlockExpr(block) => block as &dyn ast::HasAttrs,
331 AttrDefId::FieldId(it) => {
332 return Self { attrs: db.fields_attrs(it.parent)[it.local_id].clone(), owner: def };
334 AttrDefId::EnumVariantId(it) => {
336 attrs: db.variants_attrs(it.parent)[it.local_id].clone(),
340 AttrDefId::AdtId(it) => match it {
341 AdtId::StructId(it) => attrs_from_item_tree(it.lookup(db).id, db),
342 AdtId::EnumId(it) => attrs_from_item_tree(it.lookup(db).id, db),
343 AdtId::UnionId(it) => attrs_from_item_tree(it.lookup(db).id, db),
345 AttrDefId::TraitId(it) => attrs_from_item_tree(it.lookup(db).id, db),
346 AttrDefId::MacroDefId(it) => it
348 .either(|ast_id| attrs_from_ast(ast_id, db), |ast_id| attrs_from_ast(ast_id, db)),
349 AttrDefId::ImplId(it) => attrs_from_item_tree(it.lookup(db).id, db),
350 AttrDefId::ConstId(it) => attrs_from_item_tree(it.lookup(db).id, db),
351 AttrDefId::StaticId(it) => attrs_from_item_tree(it.lookup(db).id, db),
352 AttrDefId::FunctionId(it) => attrs_from_item_tree(it.lookup(db).id, db),
353 AttrDefId::TypeAliasId(it) => attrs_from_item_tree(it.lookup(db).id, db),
354 AttrDefId::GenericParamId(it) => match it {
355 GenericParamId::TypeParamId(it) => {
356 let src = it.parent.child_source(db);
357 RawAttrs::from_attrs_owner(
360 src.value[it.local_id].as_ref().either(|it| it as _, |it| it as _),
364 GenericParamId::LifetimeParamId(it) => {
365 let src = it.parent.child_source(db);
366 RawAttrs::from_attrs_owner(db, src.with_value(&src.value[it.local_id]))
368 GenericParamId::ConstParamId(it) => {
369 let src = it.parent.child_source(db);
370 RawAttrs::from_attrs_owner(db, src.with_value(&src.value[it.local_id]))
373 AttrDefId::ExternBlockId(it) => attrs_from_item_tree(it.lookup(db).id, db),
376 let attrs = raw_attrs.filter(db, def.krate(db));
377 Self { attrs, owner: def }
380 pub fn source_map(&self, db: &dyn DefDatabase) -> AttrSourceMap {
381 let owner = match self.owner {
382 AttrDefId::ModuleId(module) => {
383 // Modules can have 2 attribute owners (the `mod x;` item, and the module file itself).
385 let def_map = module.def_map(db);
386 let mod_data = &def_map[module.local_id];
387 match mod_data.declaration_source(db) {
389 let mut map = AttrSourceMap::new(InFile::new(it.file_id, &it.value));
390 if let InFile { file_id, value: ModuleSource::SourceFile(file) } =
391 mod_data.definition_source(db)
393 map.merge(AttrSourceMap::new(InFile::new(file_id, &file)));
398 let InFile { file_id, value } = mod_data.definition_source(db);
399 let attrs_owner = match &value {
400 ModuleSource::SourceFile(file) => file as &dyn ast::HasAttrs,
401 ModuleSource::Module(module) => module as &dyn ast::HasAttrs,
402 ModuleSource::BlockExpr(block) => block as &dyn ast::HasAttrs,
404 return AttrSourceMap::new(InFile::new(file_id, attrs_owner));
408 AttrDefId::FieldId(id) => {
409 let map = db.fields_attrs_source_map(id.parent);
410 let file_id = id.parent.file_id(db);
411 let root = db.parse_or_expand(file_id).unwrap();
412 let owner = match &map[id.local_id] {
413 Either::Left(it) => ast::AnyHasAttrs::new(it.to_node(&root)),
414 Either::Right(it) => ast::AnyHasAttrs::new(it.to_node(&root)),
416 InFile::new(file_id, owner)
418 AttrDefId::AdtId(adt) => match adt {
419 AdtId::StructId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
420 AdtId::UnionId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
421 AdtId::EnumId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
423 AttrDefId::FunctionId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
424 AttrDefId::EnumVariantId(id) => {
425 let map = db.variants_attrs_source_map(id.parent);
426 let file_id = id.parent.lookup(db).id.file_id();
427 let root = db.parse_or_expand(file_id).unwrap();
428 InFile::new(file_id, ast::AnyHasAttrs::new(map[id.local_id].to_node(&root)))
430 AttrDefId::StaticId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
431 AttrDefId::ConstId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
432 AttrDefId::TraitId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
433 AttrDefId::TypeAliasId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
434 AttrDefId::MacroDefId(id) => id.ast_id().either(
435 |it| it.with_value(ast::AnyHasAttrs::new(it.to_node(db.upcast()))),
436 |it| it.with_value(ast::AnyHasAttrs::new(it.to_node(db.upcast()))),
438 AttrDefId::ImplId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
439 AttrDefId::GenericParamId(id) => match id {
440 GenericParamId::TypeParamId(id) => {
441 id.parent.child_source(db).map(|source| match &source[id.local_id] {
442 Either::Left(id) => ast::AnyHasAttrs::new(id.clone()),
443 Either::Right(id) => ast::AnyHasAttrs::new(id.clone()),
446 GenericParamId::LifetimeParamId(id) => id
449 .map(|source| ast::AnyHasAttrs::new(source[id.local_id].clone())),
450 GenericParamId::ConstParamId(id) => id
453 .map(|source| ast::AnyHasAttrs::new(source[id.local_id].clone())),
455 AttrDefId::ExternBlockId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
458 AttrSourceMap::new(owner.as_ref().map(|node| node as &dyn HasAttrs))
461 pub fn docs_with_rangemap(
463 db: &dyn DefDatabase,
464 ) -> Option<(Documentation, DocsRangeMap)> {
465 // FIXME: code duplication in `docs` above
466 let docs = self.by_key("doc").attrs().flat_map(|attr| match attr.input.as_deref()? {
467 AttrInput::Literal(s) => Some((s, attr.id)),
468 AttrInput::TokenTree(..) => None,
472 .flat_map(|(s, _)| s.lines())
473 .filter(|line| !line.chars().all(|c| c.is_whitespace()))
474 .map(|line| line.chars().take_while(|c| c.is_whitespace()).count())
477 let mut buf = String::new();
478 let mut mapping = Vec::new();
479 for (doc, idx) in docs {
481 let mut base_offset = 0;
482 for raw_line in doc.split('\n') {
483 let line = raw_line.trim_end();
484 let line_len = line.len();
485 let (offset, line) = match line.char_indices().nth(indent) {
486 Some((offset, _)) => (offset, &line[offset..]),
489 let buf_offset = buf.len();
492 TextRange::new(buf_offset.try_into().ok()?, buf.len().try_into().ok()?),
495 (base_offset + offset).try_into().ok()?,
496 line_len.try_into().ok()?,
500 base_offset += raw_line.len() + 1;
510 Some((Documentation(buf), DocsRangeMap { mapping, source_map: self.source_map(db) }))
517 ) -> Option<(impl Iterator<Item = ast::Attr>, impl Iterator<Item = ast::Comment>)> {
518 let (attrs, docs) = match_ast! {
520 ast::SourceFile(it) => (it.attrs(), ast::DocCommentIter::from_syntax_node(it.syntax())),
521 ast::ExternBlock(it) => {
522 let extern_item_list = it.extern_item_list()?;
523 (extern_item_list.attrs(), ast::DocCommentIter::from_syntax_node(extern_item_list.syntax()))
526 let body = it.body()?;
527 let stmt_list = body.stmt_list()?;
528 (stmt_list.attrs(), ast::DocCommentIter::from_syntax_node(body.syntax()))
531 let assoc_item_list = it.assoc_item_list()?;
532 (assoc_item_list.attrs(), ast::DocCommentIter::from_syntax_node(assoc_item_list.syntax()))
535 let item_list = it.item_list()?;
536 (item_list.attrs(), ast::DocCommentIter::from_syntax_node(item_list.syntax()))
538 // FIXME: BlockExpr's only accept inner attributes in specific cases
539 // Excerpt from the reference:
540 // Block expressions accept outer and inner attributes, but only when they are the outer
541 // expression of an expression statement or the final expression of another block expression.
542 ast::BlockExpr(_it) => return None,
546 let attrs = attrs.filter(|attr| attr.kind().is_inner());
547 let docs = docs.filter(|doc| doc.is_inner());
552 pub struct AttrSourceMap {
553 source: Vec<Either<ast::Attr, ast::Comment>>,
558 fn new(owner: InFile<&dyn ast::HasAttrs>) -> Self {
560 source: collect_attrs(owner.value).map(|(_, it)| it).collect(),
561 file_id: owner.file_id,
565 fn merge(&mut self, other: Self) {
566 self.source.extend(other.source);
569 /// Maps the lowered `Attr` back to its original syntax node.
571 /// `attr` must come from the `owner` used for AttrSourceMap
573 /// Note that the returned syntax node might be a `#[cfg_attr]`, or a doc comment, instead of
574 /// the attribute represented by `Attr`.
575 pub fn source_of(&self, attr: &Attr) -> InFile<&Either<ast::Attr, ast::Comment>> {
576 self.source_of_id(attr.id)
579 fn source_of_id(&self, id: AttrId) -> InFile<&Either<ast::Attr, ast::Comment>> {
581 .get(id.ast_index as usize)
582 .map(|it| InFile::new(self.file_id, it))
583 .unwrap_or_else(|| panic!("cannot find attr at index {:?}", id))
587 /// A struct to map text ranges from [`Documentation`] back to TextRanges in the syntax tree.
589 pub struct DocsRangeMap {
590 source_map: AttrSourceMap,
591 // (docstring-line-range, attr_index, attr-string-range)
592 // a mapping from the text range of a line of the [`Documentation`] to the attribute index and
593 // the original (untrimmed) syntax doc line
594 mapping: Vec<(TextRange, AttrId, TextRange)>,
598 /// Maps a [`TextRange`] relative to the documentation string back to its AST range
599 pub fn map(&self, range: TextRange) -> Option<InFile<TextRange>> {
600 let found = self.mapping.binary_search_by(|(probe, ..)| probe.ordering(range)).ok()?;
601 let (line_docs_range, idx, original_line_src_range) = self.mapping[found];
602 if !line_docs_range.contains_range(range) {
606 let relative_range = range - line_docs_range.start();
608 let InFile { file_id, value: source } = self.source_map.source_of_id(idx);
610 Either::Left(attr) => {
611 let string = get_doc_string_in_attr(&attr)?;
612 let text_range = string.open_quote_text_range()?;
613 let range = TextRange::at(
614 text_range.end() + original_line_src_range.start() + relative_range.start(),
615 string.syntax().text_range().len().min(range.len()),
617 Some(InFile { file_id, value: range })
619 Either::Right(comment) => {
620 let text_range = comment.syntax().text_range();
621 let range = TextRange::at(
623 + TextSize::try_from(comment.prefix().len()).ok()?
624 + original_line_src_range.start()
625 + relative_range.start(),
626 text_range.len().min(range.len()),
628 Some(InFile { file_id, value: range })
634 fn get_doc_string_in_attr(it: &ast::Attr) -> Option<ast::String> {
637 Some(ast::Expr::Literal(lit)) => match lit.kind() {
638 ast::LiteralKind::String(it) => Some(it),
641 // #[cfg_attr(..., doc = "", ...)]
643 // FIXME: See highlight injection for what to do here
650 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
652 pub(crate) ast_index: u32,
655 #[derive(Debug, Clone, PartialEq, Eq)]
657 pub(crate) id: AttrId,
658 pub(crate) path: Interned<ModPath>,
659 pub(crate) input: Option<Interned<AttrInput>>,
662 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
664 /// `#[attr = "string"]`
666 /// `#[attr(subtree)]`
667 TokenTree(tt::Subtree, mbe::TokenMap),
670 impl fmt::Display for AttrInput {
671 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
673 AttrInput::Literal(lit) => write!(f, " = \"{}\"", lit.escape_debug()),
674 AttrInput::TokenTree(subtree, _) => subtree.fmt(f),
681 db: &dyn DefDatabase,
686 let path = Interned::new(ModPath::from_src(db, ast.path()?, hygiene)?);
687 let input = if let Some(ast::Expr::Literal(lit)) = ast.expr() {
688 let value = match lit.kind() {
689 ast::LiteralKind::String(string) => string.value()?.into(),
690 _ => lit.syntax().first_token()?.text().trim_matches('"').into(),
692 Some(Interned::new(AttrInput::Literal(value)))
693 } else if let Some(tt) = ast.token_tree() {
694 let (tree, map) = syntax_node_to_token_tree(tt.syntax());
695 Some(Interned::new(AttrInput::TokenTree(tree, map)))
699 Some(Attr { id, path, input })
703 db: &dyn DefDatabase,
708 let (parse, _) = mbe::token_tree_to_syntax_node(tt, mbe::TopEntryPoint::MetaItem).ok()?;
709 let ast = ast::Meta::cast(parse.syntax_node())?;
711 Self::from_src(db, ast, hygiene, id)
714 /// Parses this attribute as a token tree consisting of comma separated paths.
715 pub fn parse_path_comma_token_tree(&self) -> Option<impl Iterator<Item = ModPath> + '_> {
716 let args = match self.input.as_deref() {
717 Some(AttrInput::TokenTree(args, _)) => args,
721 if args.delimiter_kind() != Some(DelimiterKind::Parenthesis) {
728 matches!(tt, tt::TokenTree::Leaf(tt::Leaf::Punct(Punct { char: ',', .. })))
731 .filter(|(comma, _)| !*comma)
733 let segments = tts.filter_map(|tt| match tt {
734 tt::TokenTree::Leaf(tt::Leaf::Ident(id)) => Some(id.as_name()),
737 ModPath::from_segments(PathKind::Plain, segments)
739 .collect::<Vec<_>>();
741 Some(paths.into_iter())
744 pub fn path(&self) -> &ModPath {
748 pub fn string_value(&self) -> Option<&SmolStr> {
749 match self.input.as_deref()? {
750 AttrInput::Literal(it) => Some(it),
756 #[derive(Debug, Clone, Copy)]
757 pub struct AttrQuery<'a> {
762 impl<'a> AttrQuery<'a> {
763 pub fn tt_values(self) -> impl Iterator<Item = &'a Subtree> {
764 self.attrs().filter_map(|attr| match attr.input.as_deref()? {
765 AttrInput::TokenTree(it, _) => Some(it),
770 pub fn string_value(self) -> Option<&'a SmolStr> {
771 self.attrs().find_map(|attr| match attr.input.as_deref()? {
772 AttrInput::Literal(it) => Some(it),
777 pub fn exists(self) -> bool {
778 self.attrs().next().is_some()
781 pub fn attrs(self) -> impl Iterator<Item = &'a Attr> + Clone {
785 .filter(move |attr| attr.path.as_ident().map_or(false, |s| s.to_smol_str() == key))
789 fn attrs_from_ast<N>(src: AstId<N>, db: &dyn DefDatabase) -> RawAttrs
793 let src = InFile::new(src.file_id, src.to_node(db.upcast()));
794 RawAttrs::from_attrs_owner(db, src.as_ref().map(|it| it as &dyn ast::HasAttrs))
797 fn attrs_from_item_tree<N: ItemTreeNode>(id: ItemTreeId<N>, db: &dyn DefDatabase) -> RawAttrs {
798 let tree = id.item_tree(db);
799 let mod_item = N::id_to_mod_item(id.value);
800 tree.raw_attrs(mod_item.into()).clone()
804 owner: &dyn ast::HasAttrs,
805 ) -> impl Iterator<Item = (AttrId, Either<ast::Attr, ast::Comment>)> {
806 let (inner_attrs, inner_docs) = inner_attributes(owner.syntax())
807 .map_or((None, None), |(attrs, docs)| (Some(attrs), Some(docs)));
809 let outer_attrs = owner.attrs().filter(|attr| attr.kind().is_outer());
810 let attrs = outer_attrs
811 .chain(inner_attrs.into_iter().flatten())
812 .map(|attr| (attr.syntax().text_range().start(), Either::Left(attr)));
815 ast::DocCommentIter::from_syntax_node(owner.syntax()).filter(ast::Comment::is_outer);
816 let docs = outer_docs
817 .chain(inner_docs.into_iter().flatten())
818 .map(|docs_text| (docs_text.syntax().text_range().start(), Either::Right(docs_text)));
819 // sort here by syntax node offset because the source can have doc attributes and doc strings be interleaved
821 .sorted_by_key(|&(offset, _)| offset)
823 .map(|(id, (_, attr))| (AttrId { ast_index: id as u32 }, attr))
826 pub(crate) fn variants_attrs_source_map(
827 db: &dyn DefDatabase,
829 ) -> Arc<ArenaMap<LocalEnumVariantId, AstPtr<ast::Variant>>> {
830 let mut res = ArenaMap::default();
831 let child_source = def.child_source(db);
833 for (idx, variant) in child_source.value.iter() {
834 res.insert(idx, AstPtr::new(variant));
840 pub(crate) fn fields_attrs_source_map(
841 db: &dyn DefDatabase,
843 ) -> Arc<ArenaMap<LocalFieldId, Either<AstPtr<ast::TupleField>, AstPtr<ast::RecordField>>>> {
844 let mut res = ArenaMap::default();
845 let child_source = def.child_source(db);
847 for (idx, variant) in child_source.value.iter() {
852 .either(|l| Either::Left(AstPtr::new(l)), |r| Either::Right(AstPtr::new(r))),