]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/attr.rs
Replace more Name::to_string usages with Name::to_smol_str
[rust.git] / crates / hir_def / src / attr.rs
1 //! A higher level attributes based on TokenTree, with also some shortcuts.
2
3 use std::{fmt, hash::Hash, ops, sync::Arc};
4
5 use base_db::CrateId;
6 use cfg::{CfgExpr, CfgOptions};
7 use either::Either;
8 use hir_expand::{hygiene::Hygiene, name::AsName, AstId, InFile};
9 use itertools::Itertools;
10 use la_arena::ArenaMap;
11 use mbe::{syntax_node_to_token_tree, DelimiterKind};
12 use smallvec::{smallvec, SmallVec};
13 use syntax::{
14     ast::{self, AstNode, HasAttrs, IsString},
15     match_ast, AstPtr, AstToken, SmolStr, SyntaxNode, TextRange, TextSize,
16 };
17 use tt::Subtree;
18
19 use crate::{
20     db::DefDatabase,
21     intern::Interned,
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,
27     VariantId,
28 };
29
30 /// Holds documentation
31 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
32 pub struct Documentation(String);
33
34 impl Documentation {
35     pub fn new(s: String) -> Self {
36         Documentation(s)
37     }
38
39     pub fn as_str(&self) -> &str {
40         &self.0
41     }
42 }
43
44 impl From<Documentation> for String {
45     fn from(Documentation(string): Documentation) -> Self {
46         string
47     }
48 }
49
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]>>,
54 }
55
56 #[derive(Default, Debug, Clone, PartialEq, Eq)]
57 pub struct Attrs(RawAttrs);
58
59 #[derive(Debug, Clone, PartialEq, Eq)]
60 pub struct AttrsWithOwner {
61     attrs: Attrs,
62     owner: AttrDefId,
63 }
64
65 impl ops::Deref for RawAttrs {
66     type Target = [Attr];
67
68     fn deref(&self) -> &[Attr] {
69         match &self.entries {
70             Some(it) => &*it,
71             None => &[],
72         }
73     }
74 }
75
76 impl ops::Deref for Attrs {
77     type Target = [Attr];
78
79     fn deref(&self) -> &[Attr] {
80         match &self.0.entries {
81             Some(it) => &*it,
82             None => &[],
83         }
84     }
85 }
86
87 impl ops::Deref for AttrsWithOwner {
88     type Target = Attrs;
89
90     fn deref(&self) -> &Attrs {
91         &self.attrs
92     }
93 }
94
95 impl RawAttrs {
96     pub(crate) const EMPTY: Self = Self { entries: None };
97
98     pub(crate) fn new(db: &dyn DefDatabase, owner: &dyn ast::HasAttrs, hygiene: &Hygiene) -> Self {
99         let entries = collect_attrs(owner)
100             .flat_map(|(id, attr)| match attr {
101                 Either::Left(attr) => {
102                     attr.meta().and_then(|meta| Attr::from_src(db, meta, hygiene, id))
103                 }
104                 Either::Right(comment) => comment.doc_comment().map(|doc| Attr {
105                     id,
106                     input: Some(Interned::new(AttrInput::Literal(SmolStr::new(doc)))),
107                     path: Interned::new(ModPath::from(hir_expand::name!(doc))),
108                 }),
109             })
110             .collect::<Arc<_>>();
111
112         Self { entries: if entries.is_empty() { None } else { Some(entries) } }
113     }
114
115     fn from_attrs_owner(db: &dyn DefDatabase, owner: InFile<&dyn ast::HasAttrs>) -> Self {
116         let hygiene = Hygiene::new(db.upcast(), owner.file_id);
117         Self::new(db, owner.value, &hygiene)
118     }
119
120     pub(crate) fn merge(&self, other: Self) -> Self {
121         // FIXME: This needs to fixup `AttrId`s
122         match (&self.entries, &other.entries) {
123             (None, None) => Self::EMPTY,
124             (Some(entries), None) | (None, Some(entries)) => {
125                 Self { entries: Some(entries.clone()) }
126             }
127             (Some(a), Some(b)) => {
128                 Self { entries: Some(a.iter().chain(b.iter()).cloned().collect()) }
129             }
130         }
131     }
132
133     /// Processes `cfg_attr`s, returning the resulting semantic `Attrs`.
134     pub(crate) fn filter(self, db: &dyn DefDatabase, krate: CrateId) -> Attrs {
135         let has_cfg_attrs = self.iter().any(|attr| {
136             attr.path.as_ident().map_or(false, |name| *name == hir_expand::name![cfg_attr])
137         });
138         if !has_cfg_attrs {
139             return Attrs(self);
140         }
141
142         let crate_graph = db.crate_graph();
143         let new_attrs = self
144             .iter()
145             .flat_map(|attr| -> SmallVec<[_; 1]> {
146                 let is_cfg_attr =
147                     attr.path.as_ident().map_or(false, |name| *name == hir_expand::name![cfg_attr]);
148                 if !is_cfg_attr {
149                     return smallvec![attr.clone()];
150                 }
151
152                 let subtree = match attr.input.as_deref() {
153                     Some(AttrInput::TokenTree(it, _)) => it,
154                     _ => return smallvec![attr.clone()],
155                 };
156
157                 // Input subtree is: `(cfg, $(attr),+)`
158                 // Split it up into a `cfg` subtree and the `attr` subtrees.
159                 // FIXME: There should be a common API for this.
160                 let mut parts = subtree.token_trees.split(
161                     |tt| matches!(tt, tt::TokenTree::Leaf(tt::Leaf::Punct(p)) if p.char == ','),
162                 );
163                 let cfg = parts.next().unwrap();
164                 let cfg = Subtree { delimiter: subtree.delimiter, token_trees: cfg.to_vec() };
165                 let cfg = CfgExpr::parse(&cfg);
166                 let index = attr.id;
167                 let attrs = parts.filter(|a| !a.is_empty()).filter_map(|attr| {
168                     let tree = Subtree { delimiter: None, token_trees: attr.to_vec() };
169                     // FIXME hygiene
170                     let hygiene = Hygiene::new_unhygienic();
171                     Attr::from_tt(db, &tree, &hygiene, index)
172                 });
173
174                 let cfg_options = &crate_graph[krate].cfg_options;
175                 if cfg_options.check(&cfg) == Some(false) {
176                     smallvec![]
177                 } else {
178                     cov_mark::hit!(cfg_attr_active);
179
180                     attrs.collect()
181                 }
182             })
183             .collect();
184
185         Attrs(RawAttrs { entries: Some(new_attrs) })
186     }
187 }
188
189 impl Attrs {
190     pub const EMPTY: Self = Self(RawAttrs::EMPTY);
191
192     pub(crate) fn variants_attrs_query(
193         db: &dyn DefDatabase,
194         e: EnumId,
195     ) -> Arc<ArenaMap<LocalEnumVariantId, Attrs>> {
196         let krate = e.lookup(db).container.krate;
197         let src = e.child_source(db);
198         let mut res = ArenaMap::default();
199
200         for (id, var) in src.value.iter() {
201             let attrs = RawAttrs::from_attrs_owner(db, src.with_value(var as &dyn ast::HasAttrs))
202                 .filter(db, krate);
203
204             res.insert(id, attrs)
205         }
206
207         Arc::new(res)
208     }
209
210     pub(crate) fn fields_attrs_query(
211         db: &dyn DefDatabase,
212         v: VariantId,
213     ) -> Arc<ArenaMap<LocalFieldId, Attrs>> {
214         let krate = v.module(db).krate;
215         let src = v.child_source(db);
216         let mut res = ArenaMap::default();
217
218         for (id, fld) in src.value.iter() {
219             let owner: &dyn HasAttrs = match fld {
220                 Either::Left(tuple) => tuple,
221                 Either::Right(record) => record,
222             };
223             let attrs = RawAttrs::from_attrs_owner(db, src.with_value(owner)).filter(db, krate);
224
225             res.insert(id, attrs);
226         }
227
228         Arc::new(res)
229     }
230
231     pub fn by_key(&self, key: &'static str) -> AttrQuery<'_> {
232         AttrQuery { attrs: self, key }
233     }
234
235     pub fn cfg(&self) -> Option<CfgExpr> {
236         let mut cfgs = self.by_key("cfg").tt_values().map(CfgExpr::parse).collect::<Vec<_>>();
237         match cfgs.len() {
238             0 => None,
239             1 => Some(cfgs.pop().unwrap()),
240             _ => Some(CfgExpr::All(cfgs)),
241         }
242     }
243     pub(crate) fn is_cfg_enabled(&self, cfg_options: &CfgOptions) -> bool {
244         match self.cfg() {
245             None => true,
246             Some(cfg) => cfg_options.check(&cfg) != Some(false),
247         }
248     }
249
250     pub fn docs(&self) -> Option<Documentation> {
251         let docs = self.by_key("doc").attrs().flat_map(|attr| match attr.input.as_deref()? {
252             AttrInput::Literal(s) => Some(s),
253             AttrInput::TokenTree(..) => None,
254         });
255         let indent = docs
256             .clone()
257             .flat_map(|s| s.lines())
258             .filter(|line| !line.chars().all(|c| c.is_whitespace()))
259             .map(|line| line.chars().take_while(|c| c.is_whitespace()).count())
260             .min()
261             .unwrap_or(0);
262         let mut buf = String::new();
263         for doc in docs {
264             // str::lines doesn't yield anything for the empty string
265             if !doc.is_empty() {
266                 buf.extend(Itertools::intersperse(
267                     doc.lines().map(|line| {
268                         line.char_indices()
269                             .nth(indent)
270                             .map_or(line, |(offset, _)| &line[offset..])
271                             .trim_end()
272                     }),
273                     "\n",
274                 ));
275             }
276             buf.push('\n');
277         }
278         buf.pop();
279         if buf.is_empty() {
280             None
281         } else {
282             Some(Documentation(buf))
283         }
284     }
285
286     pub fn has_doc_hidden(&self) -> bool {
287         self.by_key("doc").tt_values().any(|tt| {
288             tt.delimiter_kind() == Some(DelimiterKind::Parenthesis) &&
289                 matches!(&*tt.token_trees, [tt::TokenTree::Leaf(tt::Leaf::Ident(ident))] if ident.text == "hidden")
290         })
291     }
292 }
293
294 impl AttrsWithOwner {
295     pub(crate) fn attrs_query(db: &dyn DefDatabase, def: AttrDefId) -> Self {
296         // FIXME: this should use `Trace` to avoid duplication in `source_map` below
297         let raw_attrs = match def {
298             AttrDefId::ModuleId(module) => {
299                 let def_map = module.def_map(db);
300                 let mod_data = &def_map[module.local_id];
301                 match mod_data.declaration_source(db) {
302                     Some(it) => {
303                         let raw_attrs = RawAttrs::from_attrs_owner(
304                             db,
305                             it.as_ref().map(|it| it as &dyn ast::HasAttrs),
306                         );
307                         match mod_data.definition_source(db) {
308                             InFile { file_id, value: ModuleSource::SourceFile(file) } => raw_attrs
309                                 .merge(RawAttrs::from_attrs_owner(db, InFile::new(file_id, &file))),
310                             _ => raw_attrs,
311                         }
312                     }
313                     None => RawAttrs::from_attrs_owner(
314                         db,
315                         mod_data.definition_source(db).as_ref().map(|src| match src {
316                             ModuleSource::SourceFile(file) => file as &dyn ast::HasAttrs,
317                             ModuleSource::Module(module) => module as &dyn ast::HasAttrs,
318                             ModuleSource::BlockExpr(block) => block as &dyn ast::HasAttrs,
319                         }),
320                     ),
321                 }
322             }
323             AttrDefId::FieldId(it) => {
324                 return Self { attrs: db.fields_attrs(it.parent)[it.local_id].clone(), owner: def };
325             }
326             AttrDefId::EnumVariantId(it) => {
327                 return Self {
328                     attrs: db.variants_attrs(it.parent)[it.local_id].clone(),
329                     owner: def,
330                 };
331             }
332             AttrDefId::AdtId(it) => match it {
333                 AdtId::StructId(it) => attrs_from_item_tree(it.lookup(db).id, db),
334                 AdtId::EnumId(it) => attrs_from_item_tree(it.lookup(db).id, db),
335                 AdtId::UnionId(it) => attrs_from_item_tree(it.lookup(db).id, db),
336             },
337             AttrDefId::TraitId(it) => attrs_from_item_tree(it.lookup(db).id, db),
338             AttrDefId::MacroDefId(it) => it
339                 .ast_id()
340                 .either(|ast_id| attrs_from_ast(ast_id, db), |ast_id| attrs_from_ast(ast_id, db)),
341             AttrDefId::ImplId(it) => attrs_from_item_tree(it.lookup(db).id, db),
342             AttrDefId::ConstId(it) => attrs_from_item_tree(it.lookup(db).id, db),
343             AttrDefId::StaticId(it) => attrs_from_item_tree(it.lookup(db).id, db),
344             AttrDefId::FunctionId(it) => attrs_from_item_tree(it.lookup(db).id, db),
345             AttrDefId::TypeAliasId(it) => attrs_from_item_tree(it.lookup(db).id, db),
346             AttrDefId::GenericParamId(it) => match it {
347                 GenericParamId::TypeParamId(it) => {
348                     let src = it.parent.child_source(db);
349                     RawAttrs::from_attrs_owner(
350                         db,
351                         src.with_value(
352                             src.value[it.local_id].as_ref().either(|it| it as _, |it| it as _),
353                         ),
354                     )
355                 }
356                 GenericParamId::LifetimeParamId(it) => {
357                     let src = it.parent.child_source(db);
358                     RawAttrs::from_attrs_owner(db, src.with_value(&src.value[it.local_id]))
359                 }
360                 GenericParamId::ConstParamId(it) => {
361                     let src = it.parent.child_source(db);
362                     RawAttrs::from_attrs_owner(db, src.with_value(&src.value[it.local_id]))
363                 }
364             },
365         };
366
367         let attrs = raw_attrs.filter(db, def.krate(db));
368         Self { attrs, owner: def }
369     }
370
371     pub fn source_map(&self, db: &dyn DefDatabase) -> AttrSourceMap {
372         let owner = match self.owner {
373             AttrDefId::ModuleId(module) => {
374                 // Modules can have 2 attribute owners (the `mod x;` item, and the module file itself).
375
376                 let def_map = module.def_map(db);
377                 let mod_data = &def_map[module.local_id];
378                 match mod_data.declaration_source(db) {
379                     Some(it) => {
380                         let mut map = AttrSourceMap::new(InFile::new(it.file_id, &it.value));
381                         if let InFile { file_id, value: ModuleSource::SourceFile(file) } =
382                             mod_data.definition_source(db)
383                         {
384                             map.merge(AttrSourceMap::new(InFile::new(file_id, &file)));
385                         }
386                         return map;
387                     }
388                     None => {
389                         let InFile { file_id, value } = mod_data.definition_source(db);
390                         let attrs_owner = match &value {
391                             ModuleSource::SourceFile(file) => file as &dyn ast::HasAttrs,
392                             ModuleSource::Module(module) => module as &dyn ast::HasAttrs,
393                             ModuleSource::BlockExpr(block) => block as &dyn ast::HasAttrs,
394                         };
395                         return AttrSourceMap::new(InFile::new(file_id, attrs_owner));
396                     }
397                 }
398             }
399             AttrDefId::FieldId(id) => {
400                 let map = db.fields_attrs_source_map(id.parent);
401                 let file_id = id.parent.file_id(db);
402                 let root = db.parse_or_expand(file_id).unwrap();
403                 let owner = match &map[id.local_id] {
404                     Either::Left(it) => ast::AnyHasAttrs::new(it.to_node(&root)),
405                     Either::Right(it) => ast::AnyHasAttrs::new(it.to_node(&root)),
406                 };
407                 InFile::new(file_id, owner)
408             }
409             AttrDefId::AdtId(adt) => match adt {
410                 AdtId::StructId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
411                 AdtId::UnionId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
412                 AdtId::EnumId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
413             },
414             AttrDefId::FunctionId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
415             AttrDefId::EnumVariantId(id) => {
416                 let map = db.variants_attrs_source_map(id.parent);
417                 let file_id = id.parent.lookup(db).id.file_id();
418                 let root = db.parse_or_expand(file_id).unwrap();
419                 InFile::new(file_id, ast::AnyHasAttrs::new(map[id.local_id].to_node(&root)))
420             }
421             AttrDefId::StaticId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
422             AttrDefId::ConstId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
423             AttrDefId::TraitId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
424             AttrDefId::TypeAliasId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
425             AttrDefId::MacroDefId(id) => id.ast_id().either(
426                 |it| it.with_value(ast::AnyHasAttrs::new(it.to_node(db.upcast()))),
427                 |it| it.with_value(ast::AnyHasAttrs::new(it.to_node(db.upcast()))),
428             ),
429             AttrDefId::ImplId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
430             AttrDefId::GenericParamId(id) => match id {
431                 GenericParamId::TypeParamId(id) => {
432                     id.parent.child_source(db).map(|source| match &source[id.local_id] {
433                         Either::Left(id) => ast::AnyHasAttrs::new(id.clone()),
434                         Either::Right(id) => ast::AnyHasAttrs::new(id.clone()),
435                     })
436                 }
437                 GenericParamId::LifetimeParamId(id) => id
438                     .parent
439                     .child_source(db)
440                     .map(|source| ast::AnyHasAttrs::new(source[id.local_id].clone())),
441                 GenericParamId::ConstParamId(id) => id
442                     .parent
443                     .child_source(db)
444                     .map(|source| ast::AnyHasAttrs::new(source[id.local_id].clone())),
445             },
446         };
447
448         AttrSourceMap::new(owner.as_ref().map(|node| node as &dyn HasAttrs))
449     }
450
451     pub fn docs_with_rangemap(
452         &self,
453         db: &dyn DefDatabase,
454     ) -> Option<(Documentation, DocsRangeMap)> {
455         // FIXME: code duplication in `docs` above
456         let docs = self.by_key("doc").attrs().flat_map(|attr| match attr.input.as_deref()? {
457             AttrInput::Literal(s) => Some((s, attr.id)),
458             AttrInput::TokenTree(..) => None,
459         });
460         let indent = docs
461             .clone()
462             .flat_map(|(s, _)| s.lines())
463             .filter(|line| !line.chars().all(|c| c.is_whitespace()))
464             .map(|line| line.chars().take_while(|c| c.is_whitespace()).count())
465             .min()
466             .unwrap_or(0);
467         let mut buf = String::new();
468         let mut mapping = Vec::new();
469         for (doc, idx) in docs {
470             if !doc.is_empty() {
471                 let mut base_offset = 0;
472                 for raw_line in doc.split('\n') {
473                     let line = raw_line.trim_end();
474                     let line_len = line.len();
475                     let (offset, line) = match line.char_indices().nth(indent) {
476                         Some((offset, _)) => (offset, &line[offset..]),
477                         None => (0, line),
478                     };
479                     let buf_offset = buf.len();
480                     buf.push_str(line);
481                     mapping.push((
482                         TextRange::new(buf_offset.try_into().ok()?, buf.len().try_into().ok()?),
483                         idx,
484                         TextRange::at(
485                             (base_offset + offset).try_into().ok()?,
486                             line_len.try_into().ok()?,
487                         ),
488                     ));
489                     buf.push('\n');
490                     base_offset += raw_line.len() + 1;
491                 }
492             } else {
493                 buf.push('\n');
494             }
495         }
496         buf.pop();
497         if buf.is_empty() {
498             None
499         } else {
500             Some((Documentation(buf), DocsRangeMap { mapping, source_map: self.source_map(db) }))
501         }
502     }
503 }
504
505 fn inner_attributes(
506     syntax: &SyntaxNode,
507 ) -> Option<(impl Iterator<Item = ast::Attr>, impl Iterator<Item = ast::Comment>)> {
508     let (attrs, docs) = match_ast! {
509         match syntax {
510             ast::SourceFile(it) => (it.attrs(), ast::CommentIter::from_syntax_node(it.syntax())),
511             ast::ExternBlock(it) => {
512                 let extern_item_list = it.extern_item_list()?;
513                 (extern_item_list.attrs(), ast::CommentIter::from_syntax_node(extern_item_list.syntax()))
514             },
515             ast::Fn(it) => {
516                 let body = it.body()?;
517                 let stmt_list = body.stmt_list()?;
518                 (stmt_list.attrs(), ast::CommentIter::from_syntax_node(body.syntax()))
519             },
520             ast::Impl(it) => {
521                 let assoc_item_list = it.assoc_item_list()?;
522                 (assoc_item_list.attrs(), ast::CommentIter::from_syntax_node(assoc_item_list.syntax()))
523             },
524             ast::Module(it) => {
525                 let item_list = it.item_list()?;
526                 (item_list.attrs(), ast::CommentIter::from_syntax_node(item_list.syntax()))
527             },
528             // FIXME: BlockExpr's only accept inner attributes in specific cases
529             // Excerpt from the reference:
530             // Block expressions accept outer and inner attributes, but only when they are the outer
531             // expression of an expression statement or the final expression of another block expression.
532             ast::BlockExpr(_it) => return None,
533             _ => return None,
534         }
535     };
536     let attrs = attrs.filter(|attr| attr.kind().is_inner());
537     let docs = docs.filter(|doc| doc.is_inner());
538     Some((attrs, docs))
539 }
540
541 #[derive(Debug)]
542 pub struct AttrSourceMap {
543     attrs: Vec<InFile<ast::Attr>>,
544     doc_comments: Vec<InFile<ast::Comment>>,
545 }
546
547 impl AttrSourceMap {
548     fn new(owner: InFile<&dyn ast::HasAttrs>) -> Self {
549         let mut attrs = Vec::new();
550         let mut doc_comments = Vec::new();
551         for (_, attr) in collect_attrs(owner.value) {
552             match attr {
553                 Either::Left(attr) => attrs.push(owner.with_value(attr)),
554                 Either::Right(comment) => doc_comments.push(owner.with_value(comment)),
555             }
556         }
557
558         Self { attrs, doc_comments }
559     }
560
561     fn merge(&mut self, other: Self) {
562         self.attrs.extend(other.attrs);
563         self.doc_comments.extend(other.doc_comments);
564     }
565
566     /// Maps the lowered `Attr` back to its original syntax node.
567     ///
568     /// `attr` must come from the `owner` used for AttrSourceMap
569     ///
570     /// Note that the returned syntax node might be a `#[cfg_attr]`, or a doc comment, instead of
571     /// the attribute represented by `Attr`.
572     pub fn source_of(&self, attr: &Attr) -> InFile<Either<ast::Attr, ast::Comment>> {
573         self.source_of_id(attr.id)
574     }
575
576     fn source_of_id(&self, id: AttrId) -> InFile<Either<ast::Attr, ast::Comment>> {
577         if id.is_doc_comment {
578             self.doc_comments
579                 .get(id.ast_index as usize)
580                 .unwrap_or_else(|| panic!("cannot find doc comment at index {:?}", id))
581                 .clone()
582                 .map(Either::Right)
583         } else {
584             self.attrs
585                 .get(id.ast_index as usize)
586                 .unwrap_or_else(|| panic!("cannot find `Attr` at index {:?}", id))
587                 .clone()
588                 .map(Either::Left)
589         }
590     }
591 }
592
593 /// A struct to map text ranges from [`Documentation`] back to TextRanges in the syntax tree.
594 #[derive(Debug)]
595 pub struct DocsRangeMap {
596     source_map: AttrSourceMap,
597     // (docstring-line-range, attr_index, attr-string-range)
598     // a mapping from the text range of a line of the [`Documentation`] to the attribute index and
599     // the original (untrimmed) syntax doc line
600     mapping: Vec<(TextRange, AttrId, TextRange)>,
601 }
602
603 impl DocsRangeMap {
604     /// Maps a [`TextRange`] relative to the documentation string back to its AST range
605     pub fn map(&self, range: TextRange) -> Option<InFile<TextRange>> {
606         let found = self.mapping.binary_search_by(|(probe, ..)| probe.ordering(range)).ok()?;
607         let (line_docs_range, idx, original_line_src_range) = self.mapping[found];
608         if !line_docs_range.contains_range(range) {
609             return None;
610         }
611
612         let relative_range = range - line_docs_range.start();
613
614         let InFile { file_id, value: source } = self.source_map.source_of_id(idx);
615         match source {
616             Either::Left(attr) => {
617                 let string = get_doc_string_in_attr(&attr)?;
618                 let text_range = string.open_quote_text_range()?;
619                 let range = TextRange::at(
620                     text_range.end() + original_line_src_range.start() + relative_range.start(),
621                     string.syntax().text_range().len().min(range.len()),
622                 );
623                 Some(InFile { file_id, value: range })
624             }
625             Either::Right(comment) => {
626                 let text_range = comment.syntax().text_range();
627                 let range = TextRange::at(
628                     text_range.start()
629                         + TextSize::try_from(comment.prefix().len()).ok()?
630                         + original_line_src_range.start()
631                         + relative_range.start(),
632                     text_range.len().min(range.len()),
633                 );
634                 Some(InFile { file_id, value: range })
635             }
636         }
637     }
638 }
639
640 fn get_doc_string_in_attr(it: &ast::Attr) -> Option<ast::String> {
641     match it.expr() {
642         // #[doc = lit]
643         Some(ast::Expr::Literal(lit)) => match lit.kind() {
644             ast::LiteralKind::String(it) => Some(it),
645             _ => None,
646         },
647         // #[cfg_attr(..., doc = "", ...)]
648         None => {
649             // FIXME: See highlight injection for what to do here
650             None
651         }
652         _ => None,
653     }
654 }
655
656 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
657 pub(crate) struct AttrId {
658     is_doc_comment: bool,
659     pub(crate) ast_index: u32,
660 }
661
662 #[derive(Debug, Clone, PartialEq, Eq)]
663 pub struct Attr {
664     pub(crate) id: AttrId,
665     pub(crate) path: Interned<ModPath>,
666     pub(crate) input: Option<Interned<AttrInput>>,
667 }
668
669 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
670 pub enum AttrInput {
671     /// `#[attr = "string"]`
672     Literal(SmolStr),
673     /// `#[attr(subtree)]`
674     TokenTree(tt::Subtree, mbe::TokenMap),
675 }
676
677 impl fmt::Display for AttrInput {
678     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
679         match self {
680             AttrInput::Literal(lit) => write!(f, " = \"{}\"", lit.escape_debug()),
681             AttrInput::TokenTree(subtree, _) => subtree.fmt(f),
682         }
683     }
684 }
685
686 impl Attr {
687     fn from_src(
688         db: &dyn DefDatabase,
689         ast: ast::Meta,
690         hygiene: &Hygiene,
691         id: AttrId,
692     ) -> Option<Attr> {
693         let path = Interned::new(ModPath::from_src(db, ast.path()?, hygiene)?);
694         let input = if let Some(ast::Expr::Literal(lit)) = ast.expr() {
695             let value = match lit.kind() {
696                 ast::LiteralKind::String(string) => string.value()?.into(),
697                 _ => lit.syntax().first_token()?.text().trim_matches('"').into(),
698             };
699             Some(Interned::new(AttrInput::Literal(value)))
700         } else if let Some(tt) = ast.token_tree() {
701             let (tree, map) = syntax_node_to_token_tree(tt.syntax());
702             Some(Interned::new(AttrInput::TokenTree(tree, map)))
703         } else {
704             None
705         };
706         Some(Attr { id, path, input })
707     }
708
709     fn from_tt(
710         db: &dyn DefDatabase,
711         tt: &tt::Subtree,
712         hygiene: &Hygiene,
713         id: AttrId,
714     ) -> Option<Attr> {
715         let (parse, _) =
716             mbe::token_tree_to_syntax_node(tt, mbe::ParserEntryPoint::MetaItem).ok()?;
717         let ast = ast::Meta::cast(parse.syntax_node())?;
718
719         Self::from_src(db, ast, hygiene, id)
720     }
721
722     /// Parses this attribute as a `#[derive]`, returns an iterator that yields all contained paths
723     /// to derive macros.
724     ///
725     /// Returns `None` when the attribute is not a well-formed `#[derive]` attribute.
726     pub(crate) fn parse_derive(&self) -> Option<impl Iterator<Item = ModPath>> {
727         if self.path.as_ident() != Some(&hir_expand::name![derive]) {
728             return None;
729         }
730
731         match self.input.as_deref() {
732             Some(AttrInput::TokenTree(args, _)) => {
733                 let mut counter = 0;
734                 let paths = args
735                     .token_trees
736                     .iter()
737                     .group_by(move |tt| {
738                         match tt {
739                             tt::TokenTree::Leaf(tt::Leaf::Punct(p)) if p.char == ',' => {
740                                 counter += 1;
741                             }
742                             _ => {}
743                         }
744                         counter
745                     })
746                     .into_iter()
747                     .map(|(_, tts)| {
748                         let segments = tts.filter_map(|tt| match tt {
749                             tt::TokenTree::Leaf(tt::Leaf::Ident(id)) => Some(id.as_name()),
750                             _ => None,
751                         });
752                         ModPath::from_segments(PathKind::Plain, segments)
753                     })
754                     .collect::<Vec<_>>();
755
756                 Some(paths.into_iter())
757             }
758             _ => None,
759         }
760     }
761
762     pub fn string_value(&self) -> Option<&SmolStr> {
763         match self.input.as_deref()? {
764             AttrInput::Literal(it) => Some(it),
765             _ => None,
766         }
767     }
768 }
769
770 #[derive(Debug, Clone, Copy)]
771 pub struct AttrQuery<'a> {
772     attrs: &'a Attrs,
773     key: &'static str,
774 }
775
776 impl<'a> AttrQuery<'a> {
777     pub fn tt_values(self) -> impl Iterator<Item = &'a Subtree> {
778         self.attrs().filter_map(|attr| match attr.input.as_deref()? {
779             AttrInput::TokenTree(it, _) => Some(it),
780             _ => None,
781         })
782     }
783
784     pub fn string_value(self) -> Option<&'a SmolStr> {
785         self.attrs().find_map(|attr| match attr.input.as_deref()? {
786             AttrInput::Literal(it) => Some(it),
787             _ => None,
788         })
789     }
790
791     pub fn exists(self) -> bool {
792         self.attrs().next().is_some()
793     }
794
795     pub fn attrs(self) -> impl Iterator<Item = &'a Attr> + Clone {
796         let key = self.key;
797         self.attrs
798             .iter()
799             .filter(move |attr| attr.path.as_ident().map_or(false, |s| s.to_smol_str() == key))
800     }
801 }
802
803 fn attrs_from_ast<N>(src: AstId<N>, db: &dyn DefDatabase) -> RawAttrs
804 where
805     N: ast::HasAttrs,
806 {
807     let src = InFile::new(src.file_id, src.to_node(db.upcast()));
808     RawAttrs::from_attrs_owner(db, src.as_ref().map(|it| it as &dyn ast::HasAttrs))
809 }
810
811 fn attrs_from_item_tree<N: ItemTreeNode>(id: ItemTreeId<N>, db: &dyn DefDatabase) -> RawAttrs {
812     let tree = id.item_tree(db);
813     let mod_item = N::id_to_mod_item(id.value);
814     tree.raw_attrs(mod_item.into()).clone()
815 }
816
817 fn collect_attrs(
818     owner: &dyn ast::HasAttrs,
819 ) -> impl Iterator<Item = (AttrId, Either<ast::Attr, ast::Comment>)> {
820     let (inner_attrs, inner_docs) = inner_attributes(owner.syntax())
821         .map_or((None, None), |(attrs, docs)| (Some(attrs), Some(docs)));
822
823     let outer_attrs = owner.attrs().filter(|attr| attr.kind().is_outer());
824     let attrs =
825         outer_attrs.chain(inner_attrs.into_iter().flatten()).enumerate().map(|(idx, attr)| {
826             (
827                 AttrId { ast_index: idx as u32, is_doc_comment: false },
828                 attr.syntax().text_range().start(),
829                 Either::Left(attr),
830             )
831         });
832
833     let outer_docs =
834         ast::CommentIter::from_syntax_node(owner.syntax()).filter(ast::Comment::is_outer);
835     let docs =
836         outer_docs.chain(inner_docs.into_iter().flatten()).enumerate().map(|(idx, docs_text)| {
837             (
838                 AttrId { ast_index: idx as u32, is_doc_comment: true },
839                 docs_text.syntax().text_range().start(),
840                 Either::Right(docs_text),
841             )
842         });
843     // sort here by syntax node offset because the source can have doc attributes and doc strings be interleaved
844     docs.chain(attrs).sorted_by_key(|&(_, offset, _)| offset).map(|(id, _, attr)| (id, attr))
845 }
846
847 pub(crate) fn variants_attrs_source_map(
848     db: &dyn DefDatabase,
849     def: EnumId,
850 ) -> Arc<ArenaMap<LocalEnumVariantId, AstPtr<ast::Variant>>> {
851     let mut res = ArenaMap::default();
852     let child_source = def.child_source(db);
853
854     for (idx, variant) in child_source.value.iter() {
855         res.insert(idx, AstPtr::new(variant));
856     }
857
858     Arc::new(res)
859 }
860
861 pub(crate) fn fields_attrs_source_map(
862     db: &dyn DefDatabase,
863     def: VariantId,
864 ) -> Arc<ArenaMap<LocalFieldId, Either<AstPtr<ast::TupleField>, AstPtr<ast::RecordField>>>> {
865     let mut res = ArenaMap::default();
866     let child_source = def.child_source(db);
867
868     for (idx, variant) in child_source.value.iter() {
869         res.insert(
870             idx,
871             variant
872                 .as_ref()
873                 .either(|l| Either::Left(AstPtr::new(l)), |r| Either::Right(AstPtr::new(r))),
874         );
875     }
876
877     Arc::new(res)
878 }