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