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