]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_analysis/src/collect/generics_of.rs
Auto merge of #102233 - petrochenkov:effvis, r=jackh726
[rust.git] / compiler / rustc_hir_analysis / src / collect / generics_of.rs
1 use crate::middle::resolve_lifetime as rl;
2 use hir::{
3     intravisit::{self, Visitor},
4     GenericParamKind, HirId, Node,
5 };
6 use rustc_hir as hir;
7 use rustc_hir::def::DefKind;
8 use rustc_hir::def_id::DefId;
9 use rustc_middle::ty::{self, TyCtxt};
10 use rustc_session::lint;
11 use rustc_span::symbol::{kw, Symbol};
12 use rustc_span::Span;
13
14 pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::Generics {
15     use rustc_hir::*;
16
17     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
18
19     let node = tcx.hir().get(hir_id);
20     let parent_def_id = match node {
21         Node::ImplItem(_)
22         | Node::TraitItem(_)
23         | Node::Variant(_)
24         | Node::Ctor(..)
25         | Node::Field(_) => {
26             let parent_id = tcx.hir().get_parent_item(hir_id);
27             Some(parent_id.to_def_id())
28         }
29         // FIXME(#43408) always enable this once `lazy_normalization` is
30         // stable enough and does not need a feature gate anymore.
31         Node::AnonConst(_) => {
32             let parent_def_id = tcx.hir().get_parent_item(hir_id);
33
34             let mut in_param_ty = false;
35             for (_parent, node) in tcx.hir().parent_iter(hir_id) {
36                 if let Some(generics) = node.generics() {
37                     let mut visitor = AnonConstInParamTyDetector {
38                         in_param_ty: false,
39                         found_anon_const_in_param_ty: false,
40                         ct: hir_id,
41                     };
42
43                     visitor.visit_generics(generics);
44                     in_param_ty = visitor.found_anon_const_in_param_ty;
45                     break;
46                 }
47             }
48
49             if in_param_ty {
50                 // We do not allow generic parameters in anon consts if we are inside
51                 // of a const parameter type, e.g. `struct Foo<const N: usize, const M: [u8; N]>` is not allowed.
52                 None
53             } else if tcx.lazy_normalization() {
54                 if let Some(param_id) = tcx.hir().opt_const_param_default_param_hir_id(hir_id) {
55                     // If the def_id we are calling generics_of on is an anon ct default i.e:
56                     //
57                     // struct Foo<const N: usize = { .. }>;
58                     //        ^^^       ^          ^^^^^^ def id of this anon const
59                     //        ^         ^ param_id
60                     //        ^ parent_def_id
61                     //
62                     // then we only want to return generics for params to the left of `N`. If we don't do that we
63                     // end up with that const looking like: `ty::ConstKind::Unevaluated(def_id, substs: [N#0])`.
64                     //
65                     // This causes ICEs (#86580) when building the substs for Foo in `fn foo() -> Foo { .. }` as
66                     // we substitute the defaults with the partially built substs when we build the substs. Subst'ing
67                     // the `N#0` on the unevaluated const indexes into the empty substs we're in the process of building.
68                     //
69                     // We fix this by having this function return the parent's generics ourselves and truncating the
70                     // generics to only include non-forward declared params (with the exception of the `Self` ty)
71                     //
72                     // For the above code example that means we want `substs: []`
73                     // For the following struct def we want `substs: [N#0]` when generics_of is called on
74                     // the def id of the `{ N + 1 }` anon const
75                     // struct Foo<const N: usize, const M: usize = { N + 1 }>;
76                     //
77                     // This has some implications for how we get the predicates available to the anon const
78                     // see `explicit_predicates_of` for more information on this
79                     let generics = tcx.generics_of(parent_def_id.to_def_id());
80                     let param_def = tcx.hir().local_def_id(param_id).to_def_id();
81                     let param_def_idx = generics.param_def_id_to_index[&param_def];
82                     // In the above example this would be .params[..N#0]
83                     let params = generics.params[..param_def_idx as usize].to_owned();
84                     let param_def_id_to_index =
85                         params.iter().map(|param| (param.def_id, param.index)).collect();
86
87                     return ty::Generics {
88                         // we set the parent of these generics to be our parent's parent so that we
89                         // dont end up with substs: [N, M, N] for the const default on a struct like this:
90                         // struct Foo<const N: usize, const M: usize = { ... }>;
91                         parent: generics.parent,
92                         parent_count: generics.parent_count,
93                         params,
94                         param_def_id_to_index,
95                         has_self: generics.has_self,
96                         has_late_bound_regions: generics.has_late_bound_regions,
97                     };
98                 }
99
100                 // HACK(eddyb) this provides the correct generics when
101                 // `feature(generic_const_expressions)` is enabled, so that const expressions
102                 // used with const generics, e.g. `Foo<{N+1}>`, can work at all.
103                 //
104                 // Note that we do not supply the parent generics when using
105                 // `min_const_generics`.
106                 Some(parent_def_id.to_def_id())
107             } else {
108                 let parent_node = tcx.hir().get(tcx.hir().get_parent_node(hir_id));
109                 match parent_node {
110                     // HACK(eddyb) this provides the correct generics for repeat
111                     // expressions' count (i.e. `N` in `[x; N]`), and explicit
112                     // `enum` discriminants (i.e. `D` in `enum Foo { Bar = D }`),
113                     // as they shouldn't be able to cause query cycle errors.
114                     Node::Expr(&Expr { kind: ExprKind::Repeat(_, ref constant), .. })
115                         if constant.hir_id() == hir_id =>
116                     {
117                         Some(parent_def_id.to_def_id())
118                     }
119                     Node::Variant(Variant { disr_expr: Some(ref constant), .. })
120                         if constant.hir_id == hir_id =>
121                     {
122                         Some(parent_def_id.to_def_id())
123                     }
124                     Node::Expr(&Expr { kind: ExprKind::ConstBlock(_), .. }) => {
125                         Some(tcx.typeck_root_def_id(def_id))
126                     }
127                     // Exclude `GlobalAsm` here which cannot have generics.
128                     Node::Expr(&Expr { kind: ExprKind::InlineAsm(asm), .. })
129                         if asm.operands.iter().any(|(op, _op_sp)| match op {
130                             hir::InlineAsmOperand::Const { anon_const }
131                             | hir::InlineAsmOperand::SymFn { anon_const } => {
132                                 anon_const.hir_id == hir_id
133                             }
134                             _ => false,
135                         }) =>
136                     {
137                         Some(parent_def_id.to_def_id())
138                     }
139                     _ => None,
140                 }
141             }
142         }
143         Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure { .. }, .. }) => {
144             Some(tcx.typeck_root_def_id(def_id))
145         }
146         Node::Item(item) => match item.kind {
147             ItemKind::OpaqueTy(hir::OpaqueTy {
148                 origin:
149                     hir::OpaqueTyOrigin::FnReturn(fn_def_id) | hir::OpaqueTyOrigin::AsyncFn(fn_def_id),
150                 in_trait,
151                 ..
152             }) => {
153                 if in_trait {
154                     assert!(matches!(tcx.def_kind(fn_def_id), DefKind::AssocFn))
155                 } else {
156                     assert!(matches!(tcx.def_kind(fn_def_id), DefKind::AssocFn | DefKind::Fn))
157                 }
158                 Some(fn_def_id.to_def_id())
159             }
160             ItemKind::OpaqueTy(hir::OpaqueTy { origin: hir::OpaqueTyOrigin::TyAlias, .. }) => {
161                 let parent_id = tcx.hir().get_parent_item(hir_id);
162                 assert_ne!(parent_id, hir::CRATE_OWNER_ID);
163                 debug!("generics_of: parent of opaque ty {:?} is {:?}", def_id, parent_id);
164                 // Opaque types are always nested within another item, and
165                 // inherit the generics of the item.
166                 Some(parent_id.to_def_id())
167             }
168             _ => None,
169         },
170         _ => None,
171     };
172
173     enum Defaults {
174         Allowed,
175         // See #36887
176         FutureCompatDisallowed,
177         Deny,
178     }
179
180     let no_generics = hir::Generics::empty();
181     let ast_generics = node.generics().unwrap_or(&no_generics);
182     let (opt_self, allow_defaults) = match node {
183         Node::Item(item) => {
184             match item.kind {
185                 ItemKind::Trait(..) | ItemKind::TraitAlias(..) => {
186                     // Add in the self type parameter.
187                     //
188                     // Something of a hack: use the node id for the trait, also as
189                     // the node id for the Self type parameter.
190                     let opt_self = Some(ty::GenericParamDef {
191                         index: 0,
192                         name: kw::SelfUpper,
193                         def_id,
194                         pure_wrt_drop: false,
195                         kind: ty::GenericParamDefKind::Type {
196                             has_default: false,
197                             synthetic: false,
198                         },
199                     });
200
201                     (opt_self, Defaults::Allowed)
202                 }
203                 ItemKind::TyAlias(..)
204                 | ItemKind::Enum(..)
205                 | ItemKind::Struct(..)
206                 | ItemKind::OpaqueTy(..)
207                 | ItemKind::Union(..) => (None, Defaults::Allowed),
208                 _ => (None, Defaults::FutureCompatDisallowed),
209             }
210         }
211
212         // GATs
213         Node::TraitItem(item) if matches!(item.kind, TraitItemKind::Type(..)) => {
214             (None, Defaults::Deny)
215         }
216         Node::ImplItem(item) if matches!(item.kind, ImplItemKind::Type(..)) => {
217             (None, Defaults::Deny)
218         }
219
220         _ => (None, Defaults::FutureCompatDisallowed),
221     };
222
223     let has_self = opt_self.is_some();
224     let mut parent_has_self = false;
225     let mut own_start = has_self as u32;
226     let parent_count = parent_def_id.map_or(0, |def_id| {
227         let generics = tcx.generics_of(def_id);
228         assert!(!has_self);
229         parent_has_self = generics.has_self;
230         own_start = generics.count() as u32;
231         generics.parent_count + generics.params.len()
232     });
233
234     let mut params: Vec<_> = Vec::with_capacity(ast_generics.params.len() + has_self as usize);
235
236     if let Some(opt_self) = opt_self {
237         params.push(opt_self);
238     }
239
240     let early_lifetimes = super::early_bound_lifetimes_from_generics(tcx, ast_generics);
241     params.extend(early_lifetimes.enumerate().map(|(i, param)| ty::GenericParamDef {
242         name: param.name.ident().name,
243         index: own_start + i as u32,
244         def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
245         pure_wrt_drop: param.pure_wrt_drop,
246         kind: ty::GenericParamDefKind::Lifetime,
247     }));
248
249     // Now create the real type and const parameters.
250     let type_start = own_start - has_self as u32 + params.len() as u32;
251     let mut i = 0;
252     let mut next_index = || {
253         let prev = i;
254         i += 1;
255         prev as u32 + type_start
256     };
257
258     const TYPE_DEFAULT_NOT_ALLOWED: &'static str = "defaults for type parameters are only allowed in \
259     `struct`, `enum`, `type`, or `trait` definitions";
260
261     params.extend(ast_generics.params.iter().filter_map(|param| match param.kind {
262         GenericParamKind::Lifetime { .. } => None,
263         GenericParamKind::Type { ref default, synthetic, .. } => {
264             if default.is_some() {
265                 match allow_defaults {
266                     Defaults::Allowed => {}
267                     Defaults::FutureCompatDisallowed
268                         if tcx.features().default_type_parameter_fallback => {}
269                     Defaults::FutureCompatDisallowed => {
270                         tcx.struct_span_lint_hir(
271                             lint::builtin::INVALID_TYPE_PARAM_DEFAULT,
272                             param.hir_id,
273                             param.span,
274                             TYPE_DEFAULT_NOT_ALLOWED,
275                             |lint| lint,
276                         );
277                     }
278                     Defaults::Deny => {
279                         tcx.sess.span_err(param.span, TYPE_DEFAULT_NOT_ALLOWED);
280                     }
281                 }
282             }
283
284             let kind = ty::GenericParamDefKind::Type { has_default: default.is_some(), synthetic };
285
286             Some(ty::GenericParamDef {
287                 index: next_index(),
288                 name: param.name.ident().name,
289                 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
290                 pure_wrt_drop: param.pure_wrt_drop,
291                 kind,
292             })
293         }
294         GenericParamKind::Const { default, .. } => {
295             if !matches!(allow_defaults, Defaults::Allowed) && default.is_some() {
296                 tcx.sess.span_err(
297                     param.span,
298                     "defaults for const parameters are only allowed in \
299                     `struct`, `enum`, `type`, or `trait` definitions",
300                 );
301             }
302
303             Some(ty::GenericParamDef {
304                 index: next_index(),
305                 name: param.name.ident().name,
306                 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
307                 pure_wrt_drop: param.pure_wrt_drop,
308                 kind: ty::GenericParamDefKind::Const { has_default: default.is_some() },
309             })
310         }
311     }));
312
313     // provide junk type parameter defs - the only place that
314     // cares about anything but the length is instantiation,
315     // and we don't do that for closures.
316     if let Node::Expr(&hir::Expr {
317         kind: hir::ExprKind::Closure(hir::Closure { movability: gen, .. }),
318         ..
319     }) = node
320     {
321         let dummy_args = if gen.is_some() {
322             &["<resume_ty>", "<yield_ty>", "<return_ty>", "<witness>", "<upvars>"][..]
323         } else {
324             &["<closure_kind>", "<closure_signature>", "<upvars>"][..]
325         };
326
327         params.extend(dummy_args.iter().map(|&arg| ty::GenericParamDef {
328             index: next_index(),
329             name: Symbol::intern(arg),
330             def_id,
331             pure_wrt_drop: false,
332             kind: ty::GenericParamDefKind::Type { has_default: false, synthetic: false },
333         }));
334     }
335
336     // provide junk type parameter defs for const blocks.
337     if let Node::AnonConst(_) = node {
338         let parent_node = tcx.hir().get(tcx.hir().get_parent_node(hir_id));
339         if let Node::Expr(&Expr { kind: ExprKind::ConstBlock(_), .. }) = parent_node {
340             params.push(ty::GenericParamDef {
341                 index: next_index(),
342                 name: Symbol::intern("<const_ty>"),
343                 def_id,
344                 pure_wrt_drop: false,
345                 kind: ty::GenericParamDefKind::Type { has_default: false, synthetic: false },
346             });
347         }
348     }
349
350     let param_def_id_to_index = params.iter().map(|param| (param.def_id, param.index)).collect();
351
352     ty::Generics {
353         parent: parent_def_id,
354         parent_count,
355         params,
356         param_def_id_to_index,
357         has_self: has_self || parent_has_self,
358         has_late_bound_regions: has_late_bound_regions(tcx, node),
359     }
360 }
361
362 fn has_late_bound_regions<'tcx>(tcx: TyCtxt<'tcx>, node: Node<'tcx>) -> Option<Span> {
363     struct LateBoundRegionsDetector<'tcx> {
364         tcx: TyCtxt<'tcx>,
365         outer_index: ty::DebruijnIndex,
366         has_late_bound_regions: Option<Span>,
367     }
368
369     impl<'tcx> Visitor<'tcx> for LateBoundRegionsDetector<'tcx> {
370         fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
371             if self.has_late_bound_regions.is_some() {
372                 return;
373             }
374             match ty.kind {
375                 hir::TyKind::BareFn(..) => {
376                     self.outer_index.shift_in(1);
377                     intravisit::walk_ty(self, ty);
378                     self.outer_index.shift_out(1);
379                 }
380                 _ => intravisit::walk_ty(self, ty),
381             }
382         }
383
384         fn visit_poly_trait_ref(&mut self, tr: &'tcx hir::PolyTraitRef<'tcx>) {
385             if self.has_late_bound_regions.is_some() {
386                 return;
387             }
388             self.outer_index.shift_in(1);
389             intravisit::walk_poly_trait_ref(self, tr);
390             self.outer_index.shift_out(1);
391         }
392
393         fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
394             if self.has_late_bound_regions.is_some() {
395                 return;
396             }
397
398             match self.tcx.named_region(lt.hir_id) {
399                 Some(rl::Region::Static | rl::Region::EarlyBound(..)) => {}
400                 Some(rl::Region::LateBound(debruijn, _, _)) if debruijn < self.outer_index => {}
401                 Some(rl::Region::LateBound(..) | rl::Region::Free(..)) | None => {
402                     self.has_late_bound_regions = Some(lt.span);
403                 }
404             }
405         }
406     }
407
408     fn has_late_bound_regions<'tcx>(
409         tcx: TyCtxt<'tcx>,
410         generics: &'tcx hir::Generics<'tcx>,
411         decl: &'tcx hir::FnDecl<'tcx>,
412     ) -> Option<Span> {
413         let mut visitor = LateBoundRegionsDetector {
414             tcx,
415             outer_index: ty::INNERMOST,
416             has_late_bound_regions: None,
417         };
418         for param in generics.params {
419             if let GenericParamKind::Lifetime { .. } = param.kind {
420                 if tcx.is_late_bound(param.hir_id) {
421                     return Some(param.span);
422                 }
423             }
424         }
425         visitor.visit_fn_decl(decl);
426         visitor.has_late_bound_regions
427     }
428
429     match node {
430         Node::TraitItem(item) => match item.kind {
431             hir::TraitItemKind::Fn(ref sig, _) => {
432                 has_late_bound_regions(tcx, &item.generics, sig.decl)
433             }
434             _ => None,
435         },
436         Node::ImplItem(item) => match item.kind {
437             hir::ImplItemKind::Fn(ref sig, _) => {
438                 has_late_bound_regions(tcx, &item.generics, sig.decl)
439             }
440             _ => None,
441         },
442         Node::ForeignItem(item) => match item.kind {
443             hir::ForeignItemKind::Fn(fn_decl, _, ref generics) => {
444                 has_late_bound_regions(tcx, generics, fn_decl)
445             }
446             _ => None,
447         },
448         Node::Item(item) => match item.kind {
449             hir::ItemKind::Fn(ref sig, .., ref generics, _) => {
450                 has_late_bound_regions(tcx, generics, sig.decl)
451             }
452             _ => None,
453         },
454         _ => None,
455     }
456 }
457
458 struct AnonConstInParamTyDetector {
459     in_param_ty: bool,
460     found_anon_const_in_param_ty: bool,
461     ct: HirId,
462 }
463
464 impl<'v> Visitor<'v> for AnonConstInParamTyDetector {
465     fn visit_generic_param(&mut self, p: &'v hir::GenericParam<'v>) {
466         if let GenericParamKind::Const { ty, default: _ } = p.kind {
467             let prev = self.in_param_ty;
468             self.in_param_ty = true;
469             self.visit_ty(ty);
470             self.in_param_ty = prev;
471         }
472     }
473
474     fn visit_anon_const(&mut self, c: &'v hir::AnonConst) {
475         if self.in_param_ty && self.ct == c.hir_id {
476             self.found_anon_const_in_param_ty = true;
477         } else {
478             intravisit::walk_anon_const(self, c)
479         }
480     }
481 }