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