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