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