]> git.lizzy.rs Git - rust.git/blob - src/tools/rust-analyzer/crates/hir-def/src/data.rs
Rollup merge of #102914 - GuillaumeGomez:migrate-css-highlight-without-change, r...
[rust.git] / src / tools / rust-analyzer / crates / hir-def / src / data.rs
1 //! Contains basic data about various HIR declarations.
2
3 use std::sync::Arc;
4
5 use hir_expand::{name::Name, AstId, ExpandResult, HirFileId, InFile, MacroCallId, MacroDefKind};
6 use smallvec::SmallVec;
7 use syntax::ast;
8
9 use crate::{
10     attr::Attrs,
11     body::{Expander, Mark},
12     db::DefDatabase,
13     intern::Interned,
14     item_tree::{self, AssocItem, FnFlags, ItemTree, ItemTreeId, ModItem, Param, TreeId},
15     nameres::{
16         attr_resolution::ResolvedAttr, diagnostics::DefDiagnostic, proc_macro::ProcMacroKind,
17         DefMap,
18     },
19     type_ref::{TraitRef, TypeBound, TypeRef},
20     visibility::RawVisibility,
21     AssocItemId, AstIdWithPath, ConstId, ConstLoc, FunctionId, FunctionLoc, HasModule, ImplId,
22     Intern, ItemContainerId, ItemLoc, Lookup, Macro2Id, MacroRulesId, ModuleId, ProcMacroId,
23     StaticId, TraitId, TypeAliasId, TypeAliasLoc,
24 };
25
26 #[derive(Debug, Clone, PartialEq, Eq)]
27 pub struct FunctionData {
28     pub name: Name,
29     pub params: Vec<(Option<Name>, Interned<TypeRef>)>,
30     pub ret_type: Interned<TypeRef>,
31     pub async_ret_type: Option<Interned<TypeRef>>,
32     pub attrs: Attrs,
33     pub visibility: RawVisibility,
34     pub abi: Option<Interned<str>>,
35     pub legacy_const_generics_indices: Box<[u32]>,
36     flags: FnFlags,
37 }
38
39 impl FunctionData {
40     pub(crate) fn fn_data_query(db: &dyn DefDatabase, func: FunctionId) -> Arc<FunctionData> {
41         let loc = func.lookup(db);
42         let krate = loc.container.module(db).krate;
43         let crate_graph = db.crate_graph();
44         let cfg_options = &crate_graph[krate].cfg_options;
45         let item_tree = loc.id.item_tree(db);
46         let func = &item_tree[loc.id.value];
47         let visibility = if let ItemContainerId::TraitId(trait_id) = loc.container {
48             db.trait_data(trait_id).visibility.clone()
49         } else {
50             item_tree[func.visibility].clone()
51         };
52
53         let enabled_params = func
54             .params
55             .clone()
56             .filter(|&param| item_tree.attrs(db, krate, param.into()).is_cfg_enabled(cfg_options));
57
58         // If last cfg-enabled param is a `...` param, it's a varargs function.
59         let is_varargs = enabled_params
60             .clone()
61             .next_back()
62             .map_or(false, |param| matches!(item_tree[param], Param::Varargs));
63
64         let mut flags = func.flags;
65         if is_varargs {
66             flags |= FnFlags::IS_VARARGS;
67         }
68         if flags.contains(FnFlags::HAS_SELF_PARAM) {
69             // If there's a self param in the syntax, but it is cfg'd out, remove the flag.
70             let is_cfgd_out = match func.params.clone().next() {
71                 Some(param) => {
72                     !item_tree.attrs(db, krate, param.into()).is_cfg_enabled(cfg_options)
73                 }
74                 None => {
75                     stdx::never!("fn HAS_SELF_PARAM but no parameters allocated");
76                     true
77                 }
78             };
79             if is_cfgd_out {
80                 cov_mark::hit!(cfgd_out_self_param);
81                 flags.remove(FnFlags::HAS_SELF_PARAM);
82             }
83         }
84
85         let legacy_const_generics_indices = item_tree
86             .attrs(db, krate, ModItem::from(loc.id.value).into())
87             .by_key("rustc_legacy_const_generics")
88             .tt_values()
89             .next()
90             .map(parse_rustc_legacy_const_generics)
91             .unwrap_or_default();
92
93         Arc::new(FunctionData {
94             name: func.name.clone(),
95             params: enabled_params
96                 .clone()
97                 .filter_map(|id| match &item_tree[id] {
98                     Param::Normal(name, ty) => Some((name.clone(), ty.clone())),
99                     Param::Varargs => None,
100                 })
101                 .collect(),
102             ret_type: func.ret_type.clone(),
103             async_ret_type: func.async_ret_type.clone(),
104             attrs: item_tree.attrs(db, krate, ModItem::from(loc.id.value).into()),
105             visibility,
106             abi: func.abi.clone(),
107             legacy_const_generics_indices,
108             flags,
109         })
110     }
111
112     pub fn has_body(&self) -> bool {
113         self.flags.contains(FnFlags::HAS_BODY)
114     }
115
116     /// True if the first param is `self`. This is relevant to decide whether this
117     /// can be called as a method.
118     pub fn has_self_param(&self) -> bool {
119         self.flags.contains(FnFlags::HAS_SELF_PARAM)
120     }
121
122     pub fn has_default_kw(&self) -> bool {
123         self.flags.contains(FnFlags::HAS_DEFAULT_KW)
124     }
125
126     pub fn has_const_kw(&self) -> bool {
127         self.flags.contains(FnFlags::HAS_CONST_KW)
128     }
129
130     pub fn has_async_kw(&self) -> bool {
131         self.flags.contains(FnFlags::HAS_ASYNC_KW)
132     }
133
134     pub fn has_unsafe_kw(&self) -> bool {
135         self.flags.contains(FnFlags::HAS_UNSAFE_KW)
136     }
137
138     pub fn is_varargs(&self) -> bool {
139         self.flags.contains(FnFlags::IS_VARARGS)
140     }
141 }
142
143 fn parse_rustc_legacy_const_generics(tt: &tt::Subtree) -> Box<[u32]> {
144     let mut indices = Vec::new();
145     for args in tt.token_trees.chunks(2) {
146         match &args[0] {
147             tt::TokenTree::Leaf(tt::Leaf::Literal(lit)) => match lit.text.parse() {
148                 Ok(index) => indices.push(index),
149                 Err(_) => break,
150             },
151             _ => break,
152         }
153
154         if let Some(comma) = args.get(1) {
155             match comma {
156                 tt::TokenTree::Leaf(tt::Leaf::Punct(punct)) if punct.char == ',' => {}
157                 _ => break,
158             }
159         }
160     }
161
162     indices.into_boxed_slice()
163 }
164
165 #[derive(Debug, Clone, PartialEq, Eq)]
166 pub struct TypeAliasData {
167     pub name: Name,
168     pub type_ref: Option<Interned<TypeRef>>,
169     pub visibility: RawVisibility,
170     pub is_extern: bool,
171     /// Bounds restricting the type alias itself (eg. `type Ty: Bound;` in a trait or impl).
172     pub bounds: Vec<Interned<TypeBound>>,
173 }
174
175 impl TypeAliasData {
176     pub(crate) fn type_alias_data_query(
177         db: &dyn DefDatabase,
178         typ: TypeAliasId,
179     ) -> Arc<TypeAliasData> {
180         let loc = typ.lookup(db);
181         let item_tree = loc.id.item_tree(db);
182         let typ = &item_tree[loc.id.value];
183         let visibility = if let ItemContainerId::TraitId(trait_id) = loc.container {
184             db.trait_data(trait_id).visibility.clone()
185         } else {
186             item_tree[typ.visibility].clone()
187         };
188
189         Arc::new(TypeAliasData {
190             name: typ.name.clone(),
191             type_ref: typ.type_ref.clone(),
192             visibility,
193             is_extern: matches!(loc.container, ItemContainerId::ExternBlockId(_)),
194             bounds: typ.bounds.to_vec(),
195         })
196     }
197 }
198
199 #[derive(Debug, Clone, PartialEq, Eq)]
200 pub struct TraitData {
201     pub name: Name,
202     pub items: Vec<(Name, AssocItemId)>,
203     pub is_auto: bool,
204     pub is_unsafe: bool,
205     pub visibility: RawVisibility,
206     /// Whether the trait has `#[rust_skip_array_during_method_dispatch]`. `hir_ty` will ignore
207     /// method calls to this trait's methods when the receiver is an array and the crate edition is
208     /// 2015 or 2018.
209     pub skip_array_during_method_dispatch: bool,
210     // box it as the vec is usually empty anyways
211     pub attribute_calls: Option<Box<Vec<(AstId<ast::Item>, MacroCallId)>>>,
212 }
213
214 impl TraitData {
215     pub(crate) fn trait_data_query(db: &dyn DefDatabase, tr: TraitId) -> Arc<TraitData> {
216         db.trait_data_with_diagnostics(tr).0
217     }
218
219     pub(crate) fn trait_data_with_diagnostics_query(
220         db: &dyn DefDatabase,
221         tr: TraitId,
222     ) -> (Arc<TraitData>, Arc<[DefDiagnostic]>) {
223         let tr_loc @ ItemLoc { container: module_id, id: tree_id } = tr.lookup(db);
224         let item_tree = tree_id.item_tree(db);
225         let tr_def = &item_tree[tree_id.value];
226         let _cx = stdx::panic_context::enter(format!(
227             "trait_data_query({:?} -> {:?} -> {:?})",
228             tr, tr_loc, tr_def
229         ));
230         let name = tr_def.name.clone();
231         let is_auto = tr_def.is_auto;
232         let is_unsafe = tr_def.is_unsafe;
233         let visibility = item_tree[tr_def.visibility].clone();
234         let skip_array_during_method_dispatch = item_tree
235             .attrs(db, module_id.krate(), ModItem::from(tree_id.value).into())
236             .by_key("rustc_skip_array_during_method_dispatch")
237             .exists();
238
239         let mut collector =
240             AssocItemCollector::new(db, module_id, tree_id.file_id(), ItemContainerId::TraitId(tr));
241         collector.collect(&item_tree, tree_id.tree_id(), &tr_def.items);
242         let (items, attribute_calls, diagnostics) = collector.finish();
243
244         (
245             Arc::new(TraitData {
246                 name,
247                 attribute_calls,
248                 items,
249                 is_auto,
250                 is_unsafe,
251                 visibility,
252                 skip_array_during_method_dispatch,
253             }),
254             diagnostics.into(),
255         )
256     }
257
258     pub fn associated_types(&self) -> impl Iterator<Item = TypeAliasId> + '_ {
259         self.items.iter().filter_map(|(_name, item)| match item {
260             AssocItemId::TypeAliasId(t) => Some(*t),
261             _ => None,
262         })
263     }
264
265     pub fn associated_type_by_name(&self, name: &Name) -> Option<TypeAliasId> {
266         self.items.iter().find_map(|(item_name, item)| match item {
267             AssocItemId::TypeAliasId(t) if item_name == name => Some(*t),
268             _ => None,
269         })
270     }
271
272     pub fn method_by_name(&self, name: &Name) -> Option<FunctionId> {
273         self.items.iter().find_map(|(item_name, item)| match item {
274             AssocItemId::FunctionId(t) if item_name == name => Some(*t),
275             _ => None,
276         })
277     }
278
279     pub fn attribute_calls(&self) -> impl Iterator<Item = (AstId<ast::Item>, MacroCallId)> + '_ {
280         self.attribute_calls.iter().flat_map(|it| it.iter()).copied()
281     }
282 }
283
284 #[derive(Debug, Clone, PartialEq, Eq)]
285 pub struct ImplData {
286     pub target_trait: Option<Interned<TraitRef>>,
287     pub self_ty: Interned<TypeRef>,
288     pub items: Vec<AssocItemId>,
289     pub is_negative: bool,
290     // box it as the vec is usually empty anyways
291     pub attribute_calls: Option<Box<Vec<(AstId<ast::Item>, MacroCallId)>>>,
292 }
293
294 impl ImplData {
295     pub(crate) fn impl_data_query(db: &dyn DefDatabase, id: ImplId) -> Arc<ImplData> {
296         db.impl_data_with_diagnostics(id).0
297     }
298
299     pub(crate) fn impl_data_with_diagnostics_query(
300         db: &dyn DefDatabase,
301         id: ImplId,
302     ) -> (Arc<ImplData>, Arc<[DefDiagnostic]>) {
303         let _p = profile::span("impl_data_with_diagnostics_query");
304         let ItemLoc { container: module_id, id: tree_id } = id.lookup(db);
305
306         let item_tree = tree_id.item_tree(db);
307         let impl_def = &item_tree[tree_id.value];
308         let target_trait = impl_def.target_trait.clone();
309         let self_ty = impl_def.self_ty.clone();
310         let is_negative = impl_def.is_negative;
311
312         let mut collector =
313             AssocItemCollector::new(db, module_id, tree_id.file_id(), ItemContainerId::ImplId(id));
314         collector.collect(&item_tree, tree_id.tree_id(), &impl_def.items);
315
316         let (items, attribute_calls, diagnostics) = collector.finish();
317         let items = items.into_iter().map(|(_, item)| item).collect();
318
319         (
320             Arc::new(ImplData { target_trait, self_ty, items, is_negative, attribute_calls }),
321             diagnostics.into(),
322         )
323     }
324
325     pub fn attribute_calls(&self) -> impl Iterator<Item = (AstId<ast::Item>, MacroCallId)> + '_ {
326         self.attribute_calls.iter().flat_map(|it| it.iter()).copied()
327     }
328 }
329
330 #[derive(Debug, Clone, PartialEq, Eq)]
331 pub struct Macro2Data {
332     pub name: Name,
333     pub visibility: RawVisibility,
334 }
335
336 impl Macro2Data {
337     pub(crate) fn macro2_data_query(db: &dyn DefDatabase, makro: Macro2Id) -> Arc<Macro2Data> {
338         let loc = makro.lookup(db);
339         let item_tree = loc.id.item_tree(db);
340         let makro = &item_tree[loc.id.value];
341
342         Arc::new(Macro2Data {
343             name: makro.name.clone(),
344             visibility: item_tree[makro.visibility].clone(),
345         })
346     }
347 }
348 #[derive(Debug, Clone, PartialEq, Eq)]
349 pub struct MacroRulesData {
350     pub name: Name,
351     pub macro_export: bool,
352 }
353
354 impl MacroRulesData {
355     pub(crate) fn macro_rules_data_query(
356         db: &dyn DefDatabase,
357         makro: MacroRulesId,
358     ) -> Arc<MacroRulesData> {
359         let loc = makro.lookup(db);
360         let item_tree = loc.id.item_tree(db);
361         let makro = &item_tree[loc.id.value];
362
363         let macro_export = item_tree
364             .attrs(db, loc.container.krate(), ModItem::from(loc.id.value).into())
365             .by_key("macro_export")
366             .exists();
367
368         Arc::new(MacroRulesData { name: makro.name.clone(), macro_export })
369     }
370 }
371 #[derive(Debug, Clone, PartialEq, Eq)]
372 pub struct ProcMacroData {
373     pub name: Name,
374     /// Derive helpers, if this is a derive
375     pub helpers: Option<Box<[Name]>>,
376 }
377
378 impl ProcMacroData {
379     pub(crate) fn proc_macro_data_query(
380         db: &dyn DefDatabase,
381         makro: ProcMacroId,
382     ) -> Arc<ProcMacroData> {
383         let loc = makro.lookup(db);
384         let item_tree = loc.id.item_tree(db);
385         let makro = &item_tree[loc.id.value];
386
387         let (name, helpers) = if let Some(def) = item_tree
388             .attrs(db, loc.container.krate(), ModItem::from(loc.id.value).into())
389             .parse_proc_macro_decl(&makro.name)
390         {
391             (
392                 def.name,
393                 match def.kind {
394                     ProcMacroKind::CustomDerive { helpers } => Some(helpers),
395                     ProcMacroKind::FnLike | ProcMacroKind::Attr => None,
396                 },
397             )
398         } else {
399             // eeeh...
400             stdx::never!("proc macro declaration is not a proc macro");
401             (makro.name.clone(), None)
402         };
403         Arc::new(ProcMacroData { name, helpers })
404     }
405 }
406
407 #[derive(Debug, Clone, PartialEq, Eq)]
408 pub struct ConstData {
409     /// `None` for `const _: () = ();`
410     pub name: Option<Name>,
411     pub type_ref: Interned<TypeRef>,
412     pub visibility: RawVisibility,
413 }
414
415 impl ConstData {
416     pub(crate) fn const_data_query(db: &dyn DefDatabase, konst: ConstId) -> Arc<ConstData> {
417         let loc = konst.lookup(db);
418         let item_tree = loc.id.item_tree(db);
419         let konst = &item_tree[loc.id.value];
420         let visibility = if let ItemContainerId::TraitId(trait_id) = loc.container {
421             db.trait_data(trait_id).visibility.clone()
422         } else {
423             item_tree[konst.visibility].clone()
424         };
425
426         Arc::new(ConstData {
427             name: konst.name.clone(),
428             type_ref: konst.type_ref.clone(),
429             visibility,
430         })
431     }
432 }
433
434 #[derive(Debug, Clone, PartialEq, Eq)]
435 pub struct StaticData {
436     pub name: Name,
437     pub type_ref: Interned<TypeRef>,
438     pub visibility: RawVisibility,
439     pub mutable: bool,
440     pub is_extern: bool,
441 }
442
443 impl StaticData {
444     pub(crate) fn static_data_query(db: &dyn DefDatabase, konst: StaticId) -> Arc<StaticData> {
445         let loc = konst.lookup(db);
446         let item_tree = loc.id.item_tree(db);
447         let statik = &item_tree[loc.id.value];
448
449         Arc::new(StaticData {
450             name: statik.name.clone(),
451             type_ref: statik.type_ref.clone(),
452             visibility: item_tree[statik.visibility].clone(),
453             mutable: statik.mutable,
454             is_extern: matches!(loc.container, ItemContainerId::ExternBlockId(_)),
455         })
456     }
457 }
458
459 struct AssocItemCollector<'a> {
460     db: &'a dyn DefDatabase,
461     module_id: ModuleId,
462     def_map: Arc<DefMap>,
463     inactive_diagnostics: Vec<DefDiagnostic>,
464     container: ItemContainerId,
465     expander: Expander,
466
467     items: Vec<(Name, AssocItemId)>,
468     attr_calls: Vec<(AstId<ast::Item>, MacroCallId)>,
469 }
470
471 impl<'a> AssocItemCollector<'a> {
472     fn new(
473         db: &'a dyn DefDatabase,
474         module_id: ModuleId,
475         file_id: HirFileId,
476         container: ItemContainerId,
477     ) -> Self {
478         Self {
479             db,
480             module_id,
481             def_map: module_id.def_map(db),
482             container,
483             expander: Expander::new(db, file_id, module_id),
484             items: Vec::new(),
485             attr_calls: Vec::new(),
486             inactive_diagnostics: Vec::new(),
487         }
488     }
489
490     fn finish(
491         self,
492     ) -> (
493         Vec<(Name, AssocItemId)>,
494         Option<Box<Vec<(AstId<ast::Item>, MacroCallId)>>>,
495         Vec<DefDiagnostic>,
496     ) {
497         (
498             self.items,
499             if self.attr_calls.is_empty() { None } else { Some(Box::new(self.attr_calls)) },
500             self.inactive_diagnostics,
501         )
502     }
503
504     // FIXME: proc-macro diagnostics
505     fn collect(&mut self, item_tree: &ItemTree, tree_id: TreeId, assoc_items: &[AssocItem]) {
506         let container = self.container;
507         self.items.reserve(assoc_items.len());
508
509         'items: for &item in assoc_items {
510             let attrs = item_tree.attrs(self.db, self.module_id.krate, ModItem::from(item).into());
511             if !attrs.is_cfg_enabled(self.expander.cfg_options()) {
512                 self.inactive_diagnostics.push(DefDiagnostic::unconfigured_code(
513                     self.module_id.local_id,
514                     InFile::new(self.expander.current_file_id(), item.ast_id(&item_tree).upcast()),
515                     attrs.cfg().unwrap(),
516                     self.expander.cfg_options().clone(),
517                 ));
518                 continue;
519             }
520
521             'attrs: for attr in &*attrs {
522                 let ast_id =
523                     AstId::new(self.expander.current_file_id(), item.ast_id(&item_tree).upcast());
524                 let ast_id_with_path = AstIdWithPath { path: (*attr.path).clone(), ast_id };
525
526                 if let Ok(ResolvedAttr::Macro(call_id)) = self.def_map.resolve_attr_macro(
527                     self.db,
528                     self.module_id.local_id,
529                     ast_id_with_path,
530                     attr,
531                 ) {
532                     self.attr_calls.push((ast_id, call_id));
533                     // If proc attribute macro expansion is disabled, skip expanding it here
534                     if !self.db.enable_proc_attr_macros() {
535                         continue 'attrs;
536                     }
537                     let loc = self.db.lookup_intern_macro_call(call_id);
538                     if let MacroDefKind::ProcMacro(exp, ..) = loc.def.kind {
539                         // If there's no expander for the proc macro (e.g. the
540                         // proc macro is ignored, or building the proc macro
541                         // crate failed), skip expansion like we would if it was
542                         // disabled. This is analogous to the handling in
543                         // `DefCollector::collect_macros`.
544                         if exp.is_dummy() {
545                             continue 'attrs;
546                         }
547                     }
548                     match self.expander.enter_expand_id::<ast::MacroItems>(self.db, call_id) {
549                         ExpandResult { value: Some((mark, _)), .. } => {
550                             self.collect_macro_items(mark);
551                             continue 'items;
552                         }
553                         ExpandResult { .. } => {}
554                     }
555                 }
556             }
557
558             match item {
559                 AssocItem::Function(id) => {
560                     let item = &item_tree[id];
561
562                     let def =
563                         FunctionLoc { container, id: ItemTreeId::new(tree_id, id) }.intern(self.db);
564                     self.items.push((item.name.clone(), def.into()));
565                 }
566                 AssocItem::Const(id) => {
567                     let item = &item_tree[id];
568
569                     let name = match item.name.clone() {
570                         Some(name) => name,
571                         None => continue,
572                     };
573                     let def =
574                         ConstLoc { container, id: ItemTreeId::new(tree_id, id) }.intern(self.db);
575                     self.items.push((name, def.into()));
576                 }
577                 AssocItem::TypeAlias(id) => {
578                     let item = &item_tree[id];
579
580                     let def = TypeAliasLoc { container, id: ItemTreeId::new(tree_id, id) }
581                         .intern(self.db);
582                     self.items.push((item.name.clone(), def.into()));
583                 }
584                 AssocItem::MacroCall(call) => {
585                     if let Some(root) = self.db.parse_or_expand(self.expander.current_file_id()) {
586                         let call = &item_tree[call];
587
588                         let ast_id_map = self.db.ast_id_map(self.expander.current_file_id());
589                         let call = ast_id_map.get(call.ast_id).to_node(&root);
590                         let _cx = stdx::panic_context::enter(format!(
591                             "collect_items MacroCall: {}",
592                             call
593                         ));
594                         let res = self.expander.enter_expand::<ast::MacroItems>(self.db, call);
595
596                         if let Ok(ExpandResult { value: Some((mark, _)), .. }) = res {
597                             self.collect_macro_items(mark);
598                         }
599                     }
600                 }
601             }
602         }
603     }
604
605     fn collect_macro_items(&mut self, mark: Mark) {
606         let tree_id = item_tree::TreeId::new(self.expander.current_file_id(), None);
607         let item_tree = tree_id.item_tree(self.db);
608         let iter: SmallVec<[_; 2]> =
609             item_tree.top_level_items().iter().filter_map(ModItem::as_assoc_item).collect();
610
611         self.collect(&item_tree, tree_id, &iter);
612
613         self.expander.exit(self.db, mark);
614     }
615 }