]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/attr.rs
Merge #11210
[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 lang(&self) -> Option<&SmolStr> {
259         self.by_key("lang").string_value()
260     }
261
262     pub fn docs(&self) -> Option<Documentation> {
263         let docs = self.by_key("doc").attrs().flat_map(|attr| match attr.input.as_deref()? {
264             AttrInput::Literal(s) => Some(s),
265             AttrInput::TokenTree(..) => None,
266         });
267         let indent = docs
268             .clone()
269             .flat_map(|s| s.lines())
270             .filter(|line| !line.chars().all(|c| c.is_whitespace()))
271             .map(|line| line.chars().take_while(|c| c.is_whitespace()).count())
272             .min()
273             .unwrap_or(0);
274         let mut buf = String::new();
275         for doc in docs {
276             // str::lines doesn't yield anything for the empty string
277             if !doc.is_empty() {
278                 buf.extend(Itertools::intersperse(
279                     doc.lines().map(|line| {
280                         line.char_indices()
281                             .nth(indent)
282                             .map_or(line, |(offset, _)| &line[offset..])
283                             .trim_end()
284                     }),
285                     "\n",
286                 ));
287             }
288             buf.push('\n');
289         }
290         buf.pop();
291         if buf.is_empty() {
292             None
293         } else {
294             Some(Documentation(buf))
295         }
296     }
297
298     pub fn has_doc_hidden(&self) -> bool {
299         self.by_key("doc").tt_values().any(|tt| {
300             tt.delimiter_kind() == Some(DelimiterKind::Parenthesis) &&
301                 matches!(&*tt.token_trees, [tt::TokenTree::Leaf(tt::Leaf::Ident(ident))] if ident.text == "hidden")
302         })
303     }
304 }
305
306 impl AttrsWithOwner {
307     pub(crate) fn attrs_query(db: &dyn DefDatabase, def: AttrDefId) -> Self {
308         // FIXME: this should use `Trace` to avoid duplication in `source_map` below
309         let raw_attrs = match def {
310             AttrDefId::ModuleId(module) => {
311                 let def_map = module.def_map(db);
312                 let mod_data = &def_map[module.local_id];
313                 match mod_data.declaration_source(db) {
314                     Some(it) => {
315                         let raw_attrs = RawAttrs::from_attrs_owner(
316                             db,
317                             it.as_ref().map(|it| it as &dyn ast::HasAttrs),
318                         );
319                         match mod_data.definition_source(db) {
320                             InFile { file_id, value: ModuleSource::SourceFile(file) } => raw_attrs
321                                 .merge(RawAttrs::from_attrs_owner(db, InFile::new(file_id, &file))),
322                             _ => raw_attrs,
323                         }
324                     }
325                     None => RawAttrs::from_attrs_owner(
326                         db,
327                         mod_data.definition_source(db).as_ref().map(|src| match src {
328                             ModuleSource::SourceFile(file) => file as &dyn ast::HasAttrs,
329                             ModuleSource::Module(module) => module as &dyn ast::HasAttrs,
330                             ModuleSource::BlockExpr(block) => block as &dyn ast::HasAttrs,
331                         }),
332                     ),
333                 }
334             }
335             AttrDefId::FieldId(it) => {
336                 return Self { attrs: db.fields_attrs(it.parent)[it.local_id].clone(), owner: def };
337             }
338             AttrDefId::EnumVariantId(it) => {
339                 return Self {
340                     attrs: db.variants_attrs(it.parent)[it.local_id].clone(),
341                     owner: def,
342                 };
343             }
344             AttrDefId::AdtId(it) => match it {
345                 AdtId::StructId(it) => attrs_from_item_tree(it.lookup(db).id, db),
346                 AdtId::EnumId(it) => attrs_from_item_tree(it.lookup(db).id, db),
347                 AdtId::UnionId(it) => attrs_from_item_tree(it.lookup(db).id, db),
348             },
349             AttrDefId::TraitId(it) => attrs_from_item_tree(it.lookup(db).id, db),
350             AttrDefId::MacroDefId(it) => it
351                 .ast_id()
352                 .either(|ast_id| attrs_from_ast(ast_id, db), |ast_id| attrs_from_ast(ast_id, db)),
353             AttrDefId::ImplId(it) => attrs_from_item_tree(it.lookup(db).id, db),
354             AttrDefId::ConstId(it) => attrs_from_item_tree(it.lookup(db).id, db),
355             AttrDefId::StaticId(it) => attrs_from_item_tree(it.lookup(db).id, db),
356             AttrDefId::FunctionId(it) => attrs_from_item_tree(it.lookup(db).id, db),
357             AttrDefId::TypeAliasId(it) => attrs_from_item_tree(it.lookup(db).id, db),
358             AttrDefId::GenericParamId(it) => match it {
359                 GenericParamId::TypeParamId(it) => {
360                     let src = it.parent.child_source(db);
361                     RawAttrs::from_attrs_owner(
362                         db,
363                         src.with_value(
364                             src.value[it.local_id].as_ref().either(|it| it as _, |it| it as _),
365                         ),
366                     )
367                 }
368                 GenericParamId::LifetimeParamId(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                 GenericParamId::ConstParamId(it) => {
373                     let src = it.parent.child_source(db);
374                     RawAttrs::from_attrs_owner(db, src.with_value(&src.value[it.local_id]))
375                 }
376             },
377             AttrDefId::ExternBlockId(it) => attrs_from_item_tree(it.lookup(db).id, db),
378         };
379
380         let attrs = raw_attrs.filter(db, def.krate(db));
381         Self { attrs, owner: def }
382     }
383
384     pub fn source_map(&self, db: &dyn DefDatabase) -> AttrSourceMap {
385         let owner = match self.owner {
386             AttrDefId::ModuleId(module) => {
387                 // Modules can have 2 attribute owners (the `mod x;` item, and the module file itself).
388
389                 let def_map = module.def_map(db);
390                 let mod_data = &def_map[module.local_id];
391                 match mod_data.declaration_source(db) {
392                     Some(it) => {
393                         let mut map = AttrSourceMap::new(InFile::new(it.file_id, &it.value));
394                         if let InFile { file_id, value: ModuleSource::SourceFile(file) } =
395                             mod_data.definition_source(db)
396                         {
397                             map.append_module_inline_attrs(AttrSourceMap::new(InFile::new(
398                                 file_id, &file,
399                             )));
400                         }
401                         return map;
402                     }
403                     None => {
404                         let InFile { file_id, value } = mod_data.definition_source(db);
405                         let attrs_owner = match &value {
406                             ModuleSource::SourceFile(file) => file as &dyn ast::HasAttrs,
407                             ModuleSource::Module(module) => module as &dyn ast::HasAttrs,
408                             ModuleSource::BlockExpr(block) => block as &dyn ast::HasAttrs,
409                         };
410                         return AttrSourceMap::new(InFile::new(file_id, attrs_owner));
411                     }
412                 }
413             }
414             AttrDefId::FieldId(id) => {
415                 let map = db.fields_attrs_source_map(id.parent);
416                 let file_id = id.parent.file_id(db);
417                 let root = db.parse_or_expand(file_id).unwrap();
418                 let owner = match &map[id.local_id] {
419                     Either::Left(it) => ast::AnyHasAttrs::new(it.to_node(&root)),
420                     Either::Right(it) => ast::AnyHasAttrs::new(it.to_node(&root)),
421                 };
422                 InFile::new(file_id, owner)
423             }
424             AttrDefId::AdtId(adt) => match adt {
425                 AdtId::StructId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
426                 AdtId::UnionId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
427                 AdtId::EnumId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
428             },
429             AttrDefId::FunctionId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
430             AttrDefId::EnumVariantId(id) => {
431                 let map = db.variants_attrs_source_map(id.parent);
432                 let file_id = id.parent.lookup(db).id.file_id();
433                 let root = db.parse_or_expand(file_id).unwrap();
434                 InFile::new(file_id, ast::AnyHasAttrs::new(map[id.local_id].to_node(&root)))
435             }
436             AttrDefId::StaticId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
437             AttrDefId::ConstId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
438             AttrDefId::TraitId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
439             AttrDefId::TypeAliasId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
440             AttrDefId::MacroDefId(id) => id.ast_id().either(
441                 |it| it.with_value(ast::AnyHasAttrs::new(it.to_node(db.upcast()))),
442                 |it| it.with_value(ast::AnyHasAttrs::new(it.to_node(db.upcast()))),
443             ),
444             AttrDefId::ImplId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
445             AttrDefId::GenericParamId(id) => match id {
446                 GenericParamId::TypeParamId(id) => {
447                     id.parent.child_source(db).map(|source| match &source[id.local_id] {
448                         Either::Left(id) => ast::AnyHasAttrs::new(id.clone()),
449                         Either::Right(id) => ast::AnyHasAttrs::new(id.clone()),
450                     })
451                 }
452                 GenericParamId::LifetimeParamId(id) => id
453                     .parent
454                     .child_source(db)
455                     .map(|source| ast::AnyHasAttrs::new(source[id.local_id].clone())),
456                 GenericParamId::ConstParamId(id) => id
457                     .parent
458                     .child_source(db)
459                     .map(|source| ast::AnyHasAttrs::new(source[id.local_id].clone())),
460             },
461             AttrDefId::ExternBlockId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),
462         };
463
464         AttrSourceMap::new(owner.as_ref().map(|node| node as &dyn HasAttrs))
465     }
466
467     pub fn docs_with_rangemap(
468         &self,
469         db: &dyn DefDatabase,
470     ) -> Option<(Documentation, DocsRangeMap)> {
471         // FIXME: code duplication in `docs` above
472         let docs = self.by_key("doc").attrs().flat_map(|attr| match attr.input.as_deref()? {
473             AttrInput::Literal(s) => Some((s, attr.id)),
474             AttrInput::TokenTree(..) => None,
475         });
476         let indent = docs
477             .clone()
478             .flat_map(|(s, _)| s.lines())
479             .filter(|line| !line.chars().all(|c| c.is_whitespace()))
480             .map(|line| line.chars().take_while(|c| c.is_whitespace()).count())
481             .min()
482             .unwrap_or(0);
483         let mut buf = String::new();
484         let mut mapping = Vec::new();
485         for (doc, idx) in docs {
486             if !doc.is_empty() {
487                 let mut base_offset = 0;
488                 for raw_line in doc.split('\n') {
489                     let line = raw_line.trim_end();
490                     let line_len = line.len();
491                     let (offset, line) = match line.char_indices().nth(indent) {
492                         Some((offset, _)) => (offset, &line[offset..]),
493                         None => (0, line),
494                     };
495                     let buf_offset = buf.len();
496                     buf.push_str(line);
497                     mapping.push((
498                         TextRange::new(buf_offset.try_into().ok()?, buf.len().try_into().ok()?),
499                         idx,
500                         TextRange::at(
501                             (base_offset + offset).try_into().ok()?,
502                             line_len.try_into().ok()?,
503                         ),
504                     ));
505                     buf.push('\n');
506                     base_offset += raw_line.len() + 1;
507                 }
508             } else {
509                 buf.push('\n');
510             }
511         }
512         buf.pop();
513         if buf.is_empty() {
514             None
515         } else {
516             Some((Documentation(buf), DocsRangeMap { mapping, source_map: self.source_map(db) }))
517         }
518     }
519 }
520
521 fn inner_attributes(
522     syntax: &SyntaxNode,
523 ) -> Option<(impl Iterator<Item = ast::Attr>, impl Iterator<Item = ast::Comment>)> {
524     let (attrs, docs) = match_ast! {
525         match syntax {
526             ast::SourceFile(it) => (it.attrs(), ast::DocCommentIter::from_syntax_node(it.syntax())),
527             ast::ExternBlock(it) => {
528                 let extern_item_list = it.extern_item_list()?;
529                 (extern_item_list.attrs(), ast::DocCommentIter::from_syntax_node(extern_item_list.syntax()))
530             },
531             ast::Fn(it) => {
532                 let body = it.body()?;
533                 let stmt_list = body.stmt_list()?;
534                 (stmt_list.attrs(), ast::DocCommentIter::from_syntax_node(body.syntax()))
535             },
536             ast::Impl(it) => {
537                 let assoc_item_list = it.assoc_item_list()?;
538                 (assoc_item_list.attrs(), ast::DocCommentIter::from_syntax_node(assoc_item_list.syntax()))
539             },
540             ast::Module(it) => {
541                 let item_list = it.item_list()?;
542                 (item_list.attrs(), ast::DocCommentIter::from_syntax_node(item_list.syntax()))
543             },
544             // FIXME: BlockExpr's only accept inner attributes in specific cases
545             // Excerpt from the reference:
546             // Block expressions accept outer and inner attributes, but only when they are the outer
547             // expression of an expression statement or the final expression of another block expression.
548             ast::BlockExpr(_it) => return None,
549             _ => return None,
550         }
551     };
552     let attrs = attrs.filter(|attr| attr.kind().is_inner());
553     let docs = docs.filter(|doc| doc.is_inner());
554     Some((attrs, docs))
555 }
556
557 #[derive(Debug)]
558 pub struct AttrSourceMap {
559     source: Vec<Either<ast::Attr, ast::Comment>>,
560     file_id: HirFileId,
561     /// If this map is for a module, this will be the [`HirFileId`] of the module's definition site,
562     /// while `file_id` will be the one of the module declaration site.
563     /// The usize is the index into `source` from which point on the entries reside in the def site
564     /// file.
565     mod_def_site_file_id: Option<(HirFileId, usize)>,
566 }
567
568 impl AttrSourceMap {
569     fn new(owner: InFile<&dyn ast::HasAttrs>) -> Self {
570         Self {
571             source: collect_attrs(owner.value).map(|(_, it)| it).collect(),
572             file_id: owner.file_id,
573             mod_def_site_file_id: None,
574         }
575     }
576
577     /// Append a second source map to this one, this is required for modules, whose outline and inline
578     /// attributes can reside in different files
579     fn append_module_inline_attrs(&mut self, other: Self) {
580         assert!(self.mod_def_site_file_id.is_none() && other.mod_def_site_file_id.is_none());
581         let len = self.source.len();
582         self.source.extend(other.source);
583         if other.file_id != self.file_id {
584             self.mod_def_site_file_id = Some((other.file_id, len));
585         }
586     }
587
588     /// Maps the lowered `Attr` back to its original syntax node.
589     ///
590     /// `attr` must come from the `owner` used for AttrSourceMap
591     ///
592     /// Note that the returned syntax node might be a `#[cfg_attr]`, or a doc comment, instead of
593     /// the attribute represented by `Attr`.
594     pub fn source_of(&self, attr: &Attr) -> InFile<&Either<ast::Attr, ast::Comment>> {
595         self.source_of_id(attr.id)
596     }
597
598     fn source_of_id(&self, id: AttrId) -> InFile<&Either<ast::Attr, ast::Comment>> {
599         let ast_idx = id.ast_index as usize;
600         let file_id = match self.mod_def_site_file_id {
601             Some((file_id, def_site_cut)) if def_site_cut <= ast_idx => file_id,
602             _ => self.file_id,
603         };
604
605         self.source
606             .get(ast_idx)
607             .map(|it| InFile::new(file_id, it))
608             .unwrap_or_else(|| panic!("cannot find attr at index {:?}", id))
609     }
610 }
611
612 /// A struct to map text ranges from [`Documentation`] back to TextRanges in the syntax tree.
613 #[derive(Debug)]
614 pub struct DocsRangeMap {
615     source_map: AttrSourceMap,
616     // (docstring-line-range, attr_index, attr-string-range)
617     // a mapping from the text range of a line of the [`Documentation`] to the attribute index and
618     // the original (untrimmed) syntax doc line
619     mapping: Vec<(TextRange, AttrId, TextRange)>,
620 }
621
622 impl DocsRangeMap {
623     /// Maps a [`TextRange`] relative to the documentation string back to its AST range
624     pub fn map(&self, range: TextRange) -> Option<InFile<TextRange>> {
625         let found = self.mapping.binary_search_by(|(probe, ..)| probe.ordering(range)).ok()?;
626         let (line_docs_range, idx, original_line_src_range) = self.mapping[found];
627         if !line_docs_range.contains_range(range) {
628             return None;
629         }
630
631         let relative_range = range - line_docs_range.start();
632
633         let InFile { file_id, value: source } = self.source_map.source_of_id(idx);
634         match source {
635             Either::Left(attr) => {
636                 let string = get_doc_string_in_attr(&attr)?;
637                 let text_range = string.open_quote_text_range()?;
638                 let range = TextRange::at(
639                     text_range.end() + original_line_src_range.start() + relative_range.start(),
640                     string.syntax().text_range().len().min(range.len()),
641                 );
642                 Some(InFile { file_id, value: range })
643             }
644             Either::Right(comment) => {
645                 let text_range = comment.syntax().text_range();
646                 let range = TextRange::at(
647                     text_range.start()
648                         + TextSize::try_from(comment.prefix().len()).ok()?
649                         + original_line_src_range.start()
650                         + relative_range.start(),
651                     text_range.len().min(range.len()),
652                 );
653                 Some(InFile { file_id, value: range })
654             }
655         }
656     }
657 }
658
659 fn get_doc_string_in_attr(it: &ast::Attr) -> Option<ast::String> {
660     match it.expr() {
661         // #[doc = lit]
662         Some(ast::Expr::Literal(lit)) => match lit.kind() {
663             ast::LiteralKind::String(it) => Some(it),
664             _ => None,
665         },
666         // #[cfg_attr(..., doc = "", ...)]
667         None => {
668             // FIXME: See highlight injection for what to do here
669             None
670         }
671         _ => None,
672     }
673 }
674
675 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
676 pub struct AttrId {
677     pub(crate) ast_index: u32,
678 }
679
680 #[derive(Debug, Clone, PartialEq, Eq)]
681 pub struct Attr {
682     pub(crate) id: AttrId,
683     pub(crate) path: Interned<ModPath>,
684     pub(crate) input: Option<Interned<AttrInput>>,
685 }
686
687 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
688 pub enum AttrInput {
689     /// `#[attr = "string"]`
690     Literal(SmolStr),
691     /// `#[attr(subtree)]`
692     TokenTree(tt::Subtree, mbe::TokenMap),
693 }
694
695 impl fmt::Display for AttrInput {
696     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
697         match self {
698             AttrInput::Literal(lit) => write!(f, " = \"{}\"", lit.escape_debug()),
699             AttrInput::TokenTree(subtree, _) => subtree.fmt(f),
700         }
701     }
702 }
703
704 impl Attr {
705     fn from_src(
706         db: &dyn DefDatabase,
707         ast: ast::Meta,
708         hygiene: &Hygiene,
709         id: AttrId,
710     ) -> Option<Attr> {
711         let path = Interned::new(ModPath::from_src(db, ast.path()?, hygiene)?);
712         let input = if let Some(ast::Expr::Literal(lit)) = ast.expr() {
713             let value = match lit.kind() {
714                 ast::LiteralKind::String(string) => string.value()?.into(),
715                 _ => lit.syntax().first_token()?.text().trim_matches('"').into(),
716             };
717             Some(Interned::new(AttrInput::Literal(value)))
718         } else if let Some(tt) = ast.token_tree() {
719             let (tree, map) = syntax_node_to_token_tree(tt.syntax());
720             Some(Interned::new(AttrInput::TokenTree(tree, map)))
721         } else {
722             None
723         };
724         Some(Attr { id, path, input })
725     }
726
727     fn from_tt(
728         db: &dyn DefDatabase,
729         tt: &tt::Subtree,
730         hygiene: &Hygiene,
731         id: AttrId,
732     ) -> Option<Attr> {
733         let (parse, _) = mbe::token_tree_to_syntax_node(tt, mbe::TopEntryPoint::MetaItem).ok()?;
734         let ast = ast::Meta::cast(parse.syntax_node())?;
735
736         Self::from_src(db, ast, hygiene, id)
737     }
738
739     /// Parses this attribute as a token tree consisting of comma separated paths.
740     pub fn parse_path_comma_token_tree(&self) -> Option<impl Iterator<Item = ModPath> + '_> {
741         let args = match self.input.as_deref() {
742             Some(AttrInput::TokenTree(args, _)) => args,
743             _ => return None,
744         };
745
746         if args.delimiter_kind() != Some(DelimiterKind::Parenthesis) {
747             return None;
748         }
749         let paths = args
750             .token_trees
751             .iter()
752             .group_by(|tt| {
753                 matches!(tt, tt::TokenTree::Leaf(tt::Leaf::Punct(Punct { char: ',', .. })))
754             })
755             .into_iter()
756             .filter(|(comma, _)| !*comma)
757             .map(|(_, tts)| {
758                 let segments = tts.filter_map(|tt| match tt {
759                     tt::TokenTree::Leaf(tt::Leaf::Ident(id)) => Some(id.as_name()),
760                     _ => None,
761                 });
762                 ModPath::from_segments(PathKind::Plain, segments)
763             })
764             .collect::<Vec<_>>();
765
766         Some(paths.into_iter())
767     }
768
769     pub fn path(&self) -> &ModPath {
770         &self.path
771     }
772
773     pub fn string_value(&self) -> Option<&SmolStr> {
774         match self.input.as_deref()? {
775             AttrInput::Literal(it) => Some(it),
776             _ => None,
777         }
778     }
779 }
780
781 #[derive(Debug, Clone, Copy)]
782 pub struct AttrQuery<'attr> {
783     attrs: &'attr Attrs,
784     key: &'static str,
785 }
786
787 impl<'attr> AttrQuery<'attr> {
788     pub fn tt_values(self) -> impl Iterator<Item = &'attr Subtree> {
789         self.attrs().filter_map(|attr| match attr.input.as_deref()? {
790             AttrInput::TokenTree(it, _) => Some(it),
791             _ => None,
792         })
793     }
794
795     pub fn string_value(self) -> Option<&'attr SmolStr> {
796         self.attrs().find_map(|attr| match attr.input.as_deref()? {
797             AttrInput::Literal(it) => Some(it),
798             _ => None,
799         })
800     }
801
802     pub fn exists(self) -> bool {
803         self.attrs().next().is_some()
804     }
805
806     pub fn attrs(self) -> impl Iterator<Item = &'attr Attr> + Clone {
807         let key = self.key;
808         self.attrs
809             .iter()
810             .filter(move |attr| attr.path.as_ident().map_or(false, |s| s.to_smol_str() == key))
811     }
812 }
813
814 fn attrs_from_ast<N>(src: AstId<N>, db: &dyn DefDatabase) -> RawAttrs
815 where
816     N: ast::HasAttrs,
817 {
818     let src = InFile::new(src.file_id, src.to_node(db.upcast()));
819     RawAttrs::from_attrs_owner(db, src.as_ref().map(|it| it as &dyn ast::HasAttrs))
820 }
821
822 fn attrs_from_item_tree<N: ItemTreeNode>(id: ItemTreeId<N>, db: &dyn DefDatabase) -> RawAttrs {
823     let tree = id.item_tree(db);
824     let mod_item = N::id_to_mod_item(id.value);
825     tree.raw_attrs(mod_item.into()).clone()
826 }
827
828 fn collect_attrs(
829     owner: &dyn ast::HasAttrs,
830 ) -> impl Iterator<Item = (AttrId, Either<ast::Attr, ast::Comment>)> {
831     let (inner_attrs, inner_docs) = inner_attributes(owner.syntax())
832         .map_or((None, None), |(attrs, docs)| (Some(attrs), Some(docs)));
833
834     let outer_attrs = owner.attrs().filter(|attr| attr.kind().is_outer());
835     let attrs = outer_attrs
836         .chain(inner_attrs.into_iter().flatten())
837         .map(|attr| (attr.syntax().text_range().start(), Either::Left(attr)));
838
839     let outer_docs =
840         ast::DocCommentIter::from_syntax_node(owner.syntax()).filter(ast::Comment::is_outer);
841     let docs = outer_docs
842         .chain(inner_docs.into_iter().flatten())
843         .map(|docs_text| (docs_text.syntax().text_range().start(), Either::Right(docs_text)));
844     // sort here by syntax node offset because the source can have doc attributes and doc strings be interleaved
845     docs.chain(attrs)
846         .sorted_by_key(|&(offset, _)| offset)
847         .enumerate()
848         .map(|(id, (_, attr))| (AttrId { ast_index: id as u32 }, attr))
849 }
850
851 pub(crate) fn variants_attrs_source_map(
852     db: &dyn DefDatabase,
853     def: EnumId,
854 ) -> Arc<ArenaMap<LocalEnumVariantId, AstPtr<ast::Variant>>> {
855     let mut res = ArenaMap::default();
856     let child_source = def.child_source(db);
857
858     for (idx, variant) in child_source.value.iter() {
859         res.insert(idx, AstPtr::new(variant));
860     }
861
862     Arc::new(res)
863 }
864
865 pub(crate) fn fields_attrs_source_map(
866     db: &dyn DefDatabase,
867     def: VariantId,
868 ) -> Arc<ArenaMap<LocalFieldId, Either<AstPtr<ast::TupleField>, AstPtr<ast::RecordField>>>> {
869     let mut res = ArenaMap::default();
870     let child_source = def.child_source(db);
871
872     for (idx, variant) in child_source.value.iter() {
873         res.insert(
874             idx,
875             variant
876                 .as_ref()
877                 .either(|l| Either::Left(AstPtr::new(l)), |r| Either::Right(AstPtr::new(r))),
878         );
879     }
880
881     Arc::new(res)
882 }