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