]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/attr.rs
Merge #11107
[rust.git] / crates / hir_def / src / attr.rs
1 //! A higher level attributes based on TokenTree, with also some shortcuts.
2
3 use std::{fmt, hash::Hash, ops, sync::Arc};
4
5 use base_db::CrateId;
6 use cfg::{CfgExpr, CfgOptions};
7 use either::Either;
8 use hir_expand::{hygiene::Hygiene, name::AsName, AstId, HirFileId, InFile};
9 use itertools::Itertools;
10 use la_arena::ArenaMap;
11 use mbe::{syntax_node_to_token_tree, DelimiterKind, Punct};
12 use smallvec::{smallvec, SmallVec};
13 use syntax::{
14     ast::{self, AstNode, HasAttrs, IsString},
15     match_ast, AstPtr, AstToken, SmolStr, SyntaxNode, TextRange, TextSize,
16 };
17 use tt::Subtree;
18
19 use crate::{
20     db::DefDatabase,
21     intern::Interned,
22     item_tree::{ItemTreeId, ItemTreeNode},
23     nameres::ModuleSource,
24     path::{ModPath, PathKind},
25     src::{HasChildSource, HasSource},
26     AdtId, AttrDefId, EnumId, GenericParamId, HasModule, LocalEnumVariantId, LocalFieldId, Lookup,
27     VariantId,
28 };
29
30 /// Holds documentation
31 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
32 pub struct Documentation(String);
33
34 impl Documentation {
35     pub fn new(s: String) -> Self {
36         Documentation(s)
37     }
38
39     pub fn as_str(&self) -> &str {
40         &self.0
41     }
42 }
43
44 impl From<Documentation> for String {
45     fn from(Documentation(string): Documentation) -> Self {
46         string
47     }
48 }
49
50 /// Syntactical attributes, without filtering of `cfg_attr`s.
51 #[derive(Default, Debug, Clone, PartialEq, Eq)]
52 pub(crate) struct RawAttrs {
53     entries: Option<Arc<[Attr]>>,
54 }
55
56 #[derive(Default, Debug, Clone, PartialEq, Eq)]
57 pub struct Attrs(RawAttrs);
58
59 #[derive(Debug, Clone, PartialEq, Eq)]
60 pub struct AttrsWithOwner {
61     attrs: Attrs,
62     owner: AttrDefId,
63 }
64
65 impl ops::Deref for RawAttrs {
66     type Target = [Attr];
67
68     fn deref(&self) -> &[Attr] {
69         match &self.entries {
70             Some(it) => &*it,
71             None => &[],
72         }
73     }
74 }
75
76 impl ops::Deref for Attrs {
77     type Target = [Attr];
78
79     fn deref(&self) -> &[Attr] {
80         match &self.0.entries {
81             Some(it) => &*it,
82             None => &[],
83         }
84     }
85 }
86
87 impl ops::Index<AttrId> for Attrs {
88     type Output = Attr;
89
90     fn index(&self, AttrId { ast_index, .. }: AttrId) -> &Self::Output {
91         &(**self)[ast_index as usize]
92     }
93 }
94
95 impl ops::Deref for AttrsWithOwner {
96     type Target = Attrs;
97
98     fn deref(&self) -> &Attrs {
99         &self.attrs
100     }
101 }
102
103 impl RawAttrs {
104     pub(crate) const EMPTY: Self = Self { entries: None };
105
106     pub(crate) fn new(db: &dyn DefDatabase, owner: &dyn ast::HasAttrs, hygiene: &Hygiene) -> Self {
107         let entries = collect_attrs(owner)
108             .flat_map(|(id, attr)| match attr {
109                 Either::Left(attr) => {
110                     attr.meta().and_then(|meta| Attr::from_src(db, meta, hygiene, id))
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::HasAttrs>) -> 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::HasAttrs))
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 HasAttrs = 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     pub fn has_doc_hidden(&self) -> bool {
295         self.by_key("doc").tt_values().any(|tt| {
296             tt.delimiter_kind() == Some(DelimiterKind::Parenthesis) &&
297                 matches!(&*tt.token_trees, [tt::TokenTree::Leaf(tt::Leaf::Ident(ident))] if ident.text == "hidden")
298         })
299     }
300 }
301
302 impl AttrsWithOwner {
303     pub(crate) fn attrs_query(db: &dyn DefDatabase, def: AttrDefId) -> Self {
304         // FIXME: this should use `Trace` to avoid duplication in `source_map` below
305         let raw_attrs = match def {
306             AttrDefId::ModuleId(module) => {
307                 let def_map = module.def_map(db);
308                 let mod_data = &def_map[module.local_id];
309                 match mod_data.declaration_source(db) {
310                     Some(it) => {
311                         let raw_attrs = RawAttrs::from_attrs_owner(
312                             db,
313                             it.as_ref().map(|it| it as &dyn ast::HasAttrs),
314                         );
315                         match mod_data.definition_source(db) {
316                             InFile { file_id, value: ModuleSource::SourceFile(file) } => raw_attrs
317                                 .merge(RawAttrs::from_attrs_owner(db, InFile::new(file_id, &file))),
318                             _ => raw_attrs,
319                         }
320                     }
321                     None => RawAttrs::from_attrs_owner(
322                         db,
323                         mod_data.definition_source(db).as_ref().map(|src| match src {
324                             ModuleSource::SourceFile(file) => file as &dyn ast::HasAttrs,
325                             ModuleSource::Module(module) => module as &dyn ast::HasAttrs,
326                             ModuleSource::BlockExpr(block) => block as &dyn ast::HasAttrs,
327                         }),
328                     ),
329                 }
330             }
331             AttrDefId::FieldId(it) => {
332                 return Self { attrs: db.fields_attrs(it.parent)[it.local_id].clone(), owner: def };
333             }
334             AttrDefId::EnumVariantId(it) => {
335                 return Self {
336                     attrs: db.variants_attrs(it.parent)[it.local_id].clone(),
337                     owner: def,
338                 };
339             }
340             AttrDefId::AdtId(it) => match it {
341                 AdtId::StructId(it) => attrs_from_item_tree(it.lookup(db).id, db),
342                 AdtId::EnumId(it) => attrs_from_item_tree(it.lookup(db).id, db),
343                 AdtId::UnionId(it) => attrs_from_item_tree(it.lookup(db).id, db),
344             },
345             AttrDefId::TraitId(it) => attrs_from_item_tree(it.lookup(db).id, db),
346             AttrDefId::MacroDefId(it) => it
347                 .ast_id()
348                 .either(|ast_id| attrs_from_ast(ast_id, db), |ast_id| attrs_from_ast(ast_id, db)),
349             AttrDefId::ImplId(it) => attrs_from_item_tree(it.lookup(db).id, db),
350             AttrDefId::ConstId(it) => attrs_from_item_tree(it.lookup(db).id, db),
351             AttrDefId::StaticId(it) => attrs_from_item_tree(it.lookup(db).id, db),
352             AttrDefId::FunctionId(it) => attrs_from_item_tree(it.lookup(db).id, db),
353             AttrDefId::TypeAliasId(it) => attrs_from_item_tree(it.lookup(db).id, db),
354             AttrDefId::GenericParamId(it) => match it {
355                 GenericParamId::TypeParamId(it) => {
356                     let src = it.parent.child_source(db);
357                     RawAttrs::from_attrs_owner(
358                         db,
359                         src.with_value(
360                             src.value[it.local_id].as_ref().either(|it| it as _, |it| it as _),
361                         ),
362                     )
363                 }
364                 GenericParamId::LifetimeParamId(it) => {
365                     let src = it.parent.child_source(db);
366                     RawAttrs::from_attrs_owner(db, src.with_value(&src.value[it.local_id]))
367                 }
368                 GenericParamId::ConstParamId(it) => {
369                     let src = it.parent.child_source(db);
370                     RawAttrs::from_attrs_owner(db, src.with_value(&src.value[it.local_id]))
371                 }
372             },
373             AttrDefId::ExternBlockId(it) => attrs_from_item_tree(it.lookup(db).id, db),
374         };
375
376         let attrs = raw_attrs.filter(db, def.krate(db));
377         Self { attrs, owner: def }
378     }
379
380     pub fn source_map(&self, db: &dyn DefDatabase) -> AttrSourceMap {
381         let owner = match self.owner {
382             AttrDefId::ModuleId(module) => {
383                 // Modules can have 2 attribute owners (the `mod x;` item, and the module file itself).
384
385                 let def_map = module.def_map(db);
386                 let mod_data = &def_map[module.local_id];
387                 match mod_data.declaration_source(db) {
388                     Some(it) => {
389                         let mut map = AttrSourceMap::new(InFile::new(it.file_id, &it.value));
390                         if let InFile { file_id, value: ModuleSource::SourceFile(file) } =
391                             mod_data.definition_source(db)
392                         {
393                             map.merge(AttrSourceMap::new(InFile::new(file_id, &file)));
394                         }
395                         return map;
396                     }
397                     None => {
398                         let InFile { file_id, value } = mod_data.definition_source(db);
399                         let attrs_owner = match &value {
400                             ModuleSource::SourceFile(file) => file as &dyn ast::HasAttrs,
401                             ModuleSource::Module(module) => module as &dyn ast::HasAttrs,
402                             ModuleSource::BlockExpr(block) => block as &dyn ast::HasAttrs,
403                         };
404                         return AttrSourceMap::new(InFile::new(file_id, attrs_owner));
405                     }
406                 }
407             }
408             AttrDefId::FieldId(id) => {
409                 let map = db.fields_attrs_source_map(id.parent);
410                 let file_id = id.parent.file_id(db);
411                 let root = db.parse_or_expand(file_id).unwrap();
412                 let owner = match &map[id.local_id] {
413                     Either::Left(it) => ast::AnyHasAttrs::new(it.to_node(&root)),
414                     Either::Right(it) => ast::AnyHasAttrs::new(it.to_node(&root)),
415                 };
416                 InFile::new(file_id, owner)
417             }
418             AttrDefId::AdtId(adt) => match adt {
419                 AdtId::StructId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
420                 AdtId::UnionId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
421                 AdtId::EnumId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
422             },
423             AttrDefId::FunctionId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
424             AttrDefId::EnumVariantId(id) => {
425                 let map = db.variants_attrs_source_map(id.parent);
426                 let file_id = id.parent.lookup(db).id.file_id();
427                 let root = db.parse_or_expand(file_id).unwrap();
428                 InFile::new(file_id, ast::AnyHasAttrs::new(map[id.local_id].to_node(&root)))
429             }
430             AttrDefId::StaticId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
431             AttrDefId::ConstId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
432             AttrDefId::TraitId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
433             AttrDefId::TypeAliasId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
434             AttrDefId::MacroDefId(id) => id.ast_id().either(
435                 |it| it.with_value(ast::AnyHasAttrs::new(it.to_node(db.upcast()))),
436                 |it| it.with_value(ast::AnyHasAttrs::new(it.to_node(db.upcast()))),
437             ),
438             AttrDefId::ImplId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
439             AttrDefId::GenericParamId(id) => match id {
440                 GenericParamId::TypeParamId(id) => {
441                     id.parent.child_source(db).map(|source| match &source[id.local_id] {
442                         Either::Left(id) => ast::AnyHasAttrs::new(id.clone()),
443                         Either::Right(id) => ast::AnyHasAttrs::new(id.clone()),
444                     })
445                 }
446                 GenericParamId::LifetimeParamId(id) => id
447                     .parent
448                     .child_source(db)
449                     .map(|source| ast::AnyHasAttrs::new(source[id.local_id].clone())),
450                 GenericParamId::ConstParamId(id) => id
451                     .parent
452                     .child_source(db)
453                     .map(|source| ast::AnyHasAttrs::new(source[id.local_id].clone())),
454             },
455             AttrDefId::ExternBlockId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
456         };
457
458         AttrSourceMap::new(owner.as_ref().map(|node| node as &dyn HasAttrs))
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::DocCommentIter::from_syntax_node(it.syntax())),
521             ast::ExternBlock(it) => {
522                 let extern_item_list = it.extern_item_list()?;
523                 (extern_item_list.attrs(), ast::DocCommentIter::from_syntax_node(extern_item_list.syntax()))
524             },
525             ast::Fn(it) => {
526                 let body = it.body()?;
527                 let stmt_list = body.stmt_list()?;
528                 (stmt_list.attrs(), ast::DocCommentIter::from_syntax_node(body.syntax()))
529             },
530             ast::Impl(it) => {
531                 let assoc_item_list = it.assoc_item_list()?;
532                 (assoc_item_list.attrs(), ast::DocCommentIter::from_syntax_node(assoc_item_list.syntax()))
533             },
534             ast::Module(it) => {
535                 let item_list = it.item_list()?;
536                 (item_list.attrs(), ast::DocCommentIter::from_syntax_node(item_list.syntax()))
537             },
538             // FIXME: BlockExpr's only accept inner attributes in specific cases
539             // Excerpt from the reference:
540             // Block expressions accept outer and inner attributes, but only when they are the outer
541             // expression of an expression statement or the final expression of another block expression.
542             ast::BlockExpr(_it) => return None,
543             _ => return None,
544         }
545     };
546     let attrs = attrs.filter(|attr| attr.kind().is_inner());
547     let docs = docs.filter(|doc| doc.is_inner());
548     Some((attrs, docs))
549 }
550
551 #[derive(Debug)]
552 pub struct AttrSourceMap {
553     source: Vec<Either<ast::Attr, ast::Comment>>,
554     file_id: HirFileId,
555 }
556
557 impl AttrSourceMap {
558     fn new(owner: InFile<&dyn ast::HasAttrs>) -> Self {
559         Self {
560             source: collect_attrs(owner.value).map(|(_, it)| it).collect(),
561             file_id: owner.file_id,
562         }
563     }
564
565     fn merge(&mut self, other: Self) {
566         self.source.extend(other.source);
567     }
568
569     /// Maps the lowered `Attr` back to its original syntax node.
570     ///
571     /// `attr` must come from the `owner` used for AttrSourceMap
572     ///
573     /// Note that the returned syntax node might be a `#[cfg_attr]`, or a doc comment, instead of
574     /// the attribute represented by `Attr`.
575     pub fn source_of(&self, attr: &Attr) -> InFile<&Either<ast::Attr, ast::Comment>> {
576         self.source_of_id(attr.id)
577     }
578
579     fn source_of_id(&self, id: AttrId) -> InFile<&Either<ast::Attr, ast::Comment>> {
580         self.source
581             .get(id.ast_index as usize)
582             .map(|it| InFile::new(self.file_id, it))
583             .unwrap_or_else(|| panic!("cannot find attr at index {:?}", id))
584     }
585 }
586
587 /// A struct to map text ranges from [`Documentation`] back to TextRanges in the syntax tree.
588 #[derive(Debug)]
589 pub struct DocsRangeMap {
590     source_map: AttrSourceMap,
591     // (docstring-line-range, attr_index, attr-string-range)
592     // a mapping from the text range of a line of the [`Documentation`] to the attribute index and
593     // the original (untrimmed) syntax doc line
594     mapping: Vec<(TextRange, AttrId, TextRange)>,
595 }
596
597 impl DocsRangeMap {
598     /// Maps a [`TextRange`] relative to the documentation string back to its AST range
599     pub fn map(&self, range: TextRange) -> Option<InFile<TextRange>> {
600         let found = self.mapping.binary_search_by(|(probe, ..)| probe.ordering(range)).ok()?;
601         let (line_docs_range, idx, original_line_src_range) = self.mapping[found];
602         if !line_docs_range.contains_range(range) {
603             return None;
604         }
605
606         let relative_range = range - line_docs_range.start();
607
608         let InFile { file_id, value: source } = self.source_map.source_of_id(idx);
609         match source {
610             Either::Left(attr) => {
611                 let string = get_doc_string_in_attr(&attr)?;
612                 let text_range = string.open_quote_text_range()?;
613                 let range = TextRange::at(
614                     text_range.end() + original_line_src_range.start() + relative_range.start(),
615                     string.syntax().text_range().len().min(range.len()),
616                 );
617                 Some(InFile { file_id, value: range })
618             }
619             Either::Right(comment) => {
620                 let text_range = comment.syntax().text_range();
621                 let range = TextRange::at(
622                     text_range.start()
623                         + TextSize::try_from(comment.prefix().len()).ok()?
624                         + original_line_src_range.start()
625                         + relative_range.start(),
626                     text_range.len().min(range.len()),
627                 );
628                 Some(InFile { file_id, value: range })
629             }
630         }
631     }
632 }
633
634 fn get_doc_string_in_attr(it: &ast::Attr) -> Option<ast::String> {
635     match it.expr() {
636         // #[doc = lit]
637         Some(ast::Expr::Literal(lit)) => match lit.kind() {
638             ast::LiteralKind::String(it) => Some(it),
639             _ => None,
640         },
641         // #[cfg_attr(..., doc = "", ...)]
642         None => {
643             // FIXME: See highlight injection for what to do here
644             None
645         }
646         _ => None,
647     }
648 }
649
650 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
651 pub struct AttrId {
652     pub(crate) ast_index: u32,
653 }
654
655 #[derive(Debug, Clone, PartialEq, Eq)]
656 pub struct Attr {
657     pub(crate) id: AttrId,
658     pub(crate) path: Interned<ModPath>,
659     pub(crate) input: Option<Interned<AttrInput>>,
660 }
661
662 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
663 pub enum AttrInput {
664     /// `#[attr = "string"]`
665     Literal(SmolStr),
666     /// `#[attr(subtree)]`
667     TokenTree(tt::Subtree, mbe::TokenMap),
668 }
669
670 impl fmt::Display for AttrInput {
671     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
672         match self {
673             AttrInput::Literal(lit) => write!(f, " = \"{}\"", lit.escape_debug()),
674             AttrInput::TokenTree(subtree, _) => subtree.fmt(f),
675         }
676     }
677 }
678
679 impl Attr {
680     fn from_src(
681         db: &dyn DefDatabase,
682         ast: ast::Meta,
683         hygiene: &Hygiene,
684         id: AttrId,
685     ) -> Option<Attr> {
686         let path = Interned::new(ModPath::from_src(db, ast.path()?, hygiene)?);
687         let input = if let Some(ast::Expr::Literal(lit)) = ast.expr() {
688             let value = match lit.kind() {
689                 ast::LiteralKind::String(string) => string.value()?.into(),
690                 _ => lit.syntax().first_token()?.text().trim_matches('"').into(),
691             };
692             Some(Interned::new(AttrInput::Literal(value)))
693         } else if let Some(tt) = ast.token_tree() {
694             let (tree, map) = syntax_node_to_token_tree(tt.syntax());
695             Some(Interned::new(AttrInput::TokenTree(tree, map)))
696         } else {
697             None
698         };
699         Some(Attr { id, path, input })
700     }
701
702     fn from_tt(
703         db: &dyn DefDatabase,
704         tt: &tt::Subtree,
705         hygiene: &Hygiene,
706         id: AttrId,
707     ) -> Option<Attr> {
708         let (parse, _) = mbe::token_tree_to_syntax_node(tt, mbe::TopEntryPoint::MetaItem).ok()?;
709         let ast = ast::Meta::cast(parse.syntax_node())?;
710
711         Self::from_src(db, ast, hygiene, id)
712     }
713
714     /// Parses this attribute as a token tree consisting of comma separated paths.
715     pub fn parse_path_comma_token_tree(&self) -> Option<impl Iterator<Item = ModPath> + '_> {
716         let args = match self.input.as_deref() {
717             Some(AttrInput::TokenTree(args, _)) => args,
718             _ => return None,
719         };
720
721         if args.delimiter_kind() != Some(DelimiterKind::Parenthesis) {
722             return None;
723         }
724         let paths = args
725             .token_trees
726             .iter()
727             .group_by(|tt| {
728                 matches!(tt, tt::TokenTree::Leaf(tt::Leaf::Punct(Punct { char: ',', .. })))
729             })
730             .into_iter()
731             .filter(|(comma, _)| !*comma)
732             .map(|(_, tts)| {
733                 let segments = tts.filter_map(|tt| match tt {
734                     tt::TokenTree::Leaf(tt::Leaf::Ident(id)) => Some(id.as_name()),
735                     _ => None,
736                 });
737                 ModPath::from_segments(PathKind::Plain, segments)
738             })
739             .collect::<Vec<_>>();
740
741         Some(paths.into_iter())
742     }
743
744     pub fn path(&self) -> &ModPath {
745         &self.path
746     }
747
748     pub fn string_value(&self) -> Option<&SmolStr> {
749         match self.input.as_deref()? {
750             AttrInput::Literal(it) => Some(it),
751             _ => None,
752         }
753     }
754 }
755
756 #[derive(Debug, Clone, Copy)]
757 pub struct AttrQuery<'a> {
758     attrs: &'a Attrs,
759     key: &'static str,
760 }
761
762 impl<'a> AttrQuery<'a> {
763     pub fn tt_values(self) -> impl Iterator<Item = &'a Subtree> {
764         self.attrs().filter_map(|attr| match attr.input.as_deref()? {
765             AttrInput::TokenTree(it, _) => Some(it),
766             _ => None,
767         })
768     }
769
770     pub fn string_value(self) -> Option<&'a SmolStr> {
771         self.attrs().find_map(|attr| match attr.input.as_deref()? {
772             AttrInput::Literal(it) => Some(it),
773             _ => None,
774         })
775     }
776
777     pub fn exists(self) -> bool {
778         self.attrs().next().is_some()
779     }
780
781     pub fn attrs(self) -> impl Iterator<Item = &'a Attr> + Clone {
782         let key = self.key;
783         self.attrs
784             .iter()
785             .filter(move |attr| attr.path.as_ident().map_or(false, |s| s.to_smol_str() == key))
786     }
787 }
788
789 fn attrs_from_ast<N>(src: AstId<N>, db: &dyn DefDatabase) -> RawAttrs
790 where
791     N: ast::HasAttrs,
792 {
793     let src = InFile::new(src.file_id, src.to_node(db.upcast()));
794     RawAttrs::from_attrs_owner(db, src.as_ref().map(|it| it as &dyn ast::HasAttrs))
795 }
796
797 fn attrs_from_item_tree<N: ItemTreeNode>(id: ItemTreeId<N>, db: &dyn DefDatabase) -> RawAttrs {
798     let tree = id.item_tree(db);
799     let mod_item = N::id_to_mod_item(id.value);
800     tree.raw_attrs(mod_item.into()).clone()
801 }
802
803 fn collect_attrs(
804     owner: &dyn ast::HasAttrs,
805 ) -> impl Iterator<Item = (AttrId, Either<ast::Attr, ast::Comment>)> {
806     let (inner_attrs, inner_docs) = inner_attributes(owner.syntax())
807         .map_or((None, None), |(attrs, docs)| (Some(attrs), Some(docs)));
808
809     let outer_attrs = owner.attrs().filter(|attr| attr.kind().is_outer());
810     let attrs = outer_attrs
811         .chain(inner_attrs.into_iter().flatten())
812         .map(|attr| (attr.syntax().text_range().start(), Either::Left(attr)));
813
814     let outer_docs =
815         ast::DocCommentIter::from_syntax_node(owner.syntax()).filter(ast::Comment::is_outer);
816     let docs = outer_docs
817         .chain(inner_docs.into_iter().flatten())
818         .map(|docs_text| (docs_text.syntax().text_range().start(), Either::Right(docs_text)));
819     // sort here by syntax node offset because the source can have doc attributes and doc strings be interleaved
820     docs.chain(attrs)
821         .sorted_by_key(|&(offset, _)| offset)
822         .enumerate()
823         .map(|(id, (_, attr))| (AttrId { ast_index: id as u32 }, attr))
824 }
825
826 pub(crate) fn variants_attrs_source_map(
827     db: &dyn DefDatabase,
828     def: EnumId,
829 ) -> Arc<ArenaMap<LocalEnumVariantId, AstPtr<ast::Variant>>> {
830     let mut res = ArenaMap::default();
831     let child_source = def.child_source(db);
832
833     for (idx, variant) in child_source.value.iter() {
834         res.insert(idx, AstPtr::new(variant));
835     }
836
837     Arc::new(res)
838 }
839
840 pub(crate) fn fields_attrs_source_map(
841     db: &dyn DefDatabase,
842     def: VariantId,
843 ) -> Arc<ArenaMap<LocalFieldId, Either<AstPtr<ast::TupleField>, AstPtr<ast::RecordField>>>> {
844     let mut res = ArenaMap::default();
845     let child_source = def.child_source(db);
846
847     for (idx, variant) in child_source.value.iter() {
848         res.insert(
849             idx,
850             variant
851                 .as_ref()
852                 .either(|l| Either::Left(AstPtr::new(l)), |r| Either::Right(AstPtr::new(r))),
853         );
854     }
855
856     Arc::new(res)
857 }