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