]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_analysis/src/collect/generics_of.rs
Rollup merge of #102412 - joboet:dont_panic, r=m-ou-se
[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
253     const TYPE_DEFAULT_NOT_ALLOWED: &'static str = "defaults for type parameters are only allowed in \
254     `struct`, `enum`, `type`, or `trait` definitions";
255
256     params.extend(ast_generics.params.iter().filter_map(|param| match param.kind {
257         GenericParamKind::Lifetime { .. } => None,
258         GenericParamKind::Type { ref default, synthetic, .. } => {
259             if default.is_some() {
260                 match allow_defaults {
261                     Defaults::Allowed => {}
262                     Defaults::FutureCompatDisallowed
263                         if tcx.features().default_type_parameter_fallback => {}
264                     Defaults::FutureCompatDisallowed => {
265                         tcx.struct_span_lint_hir(
266                             lint::builtin::INVALID_TYPE_PARAM_DEFAULT,
267                             param.hir_id,
268                             param.span,
269                             TYPE_DEFAULT_NOT_ALLOWED,
270                             |lint| lint,
271                         );
272                     }
273                     Defaults::Deny => {
274                         tcx.sess.span_err(param.span, TYPE_DEFAULT_NOT_ALLOWED);
275                     }
276                 }
277             }
278
279             let kind = ty::GenericParamDefKind::Type { has_default: default.is_some(), synthetic };
280
281             let param_def = ty::GenericParamDef {
282                 index: type_start + i as u32,
283                 name: param.name.ident().name,
284                 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
285                 pure_wrt_drop: param.pure_wrt_drop,
286                 kind,
287             };
288             i += 1;
289             Some(param_def)
290         }
291         GenericParamKind::Const { default, .. } => {
292             if !matches!(allow_defaults, Defaults::Allowed) && default.is_some() {
293                 tcx.sess.span_err(
294                     param.span,
295                     "defaults for const parameters are only allowed in \
296                     `struct`, `enum`, `type`, or `trait` definitions",
297                 );
298             }
299
300             let param_def = ty::GenericParamDef {
301                 index: type_start + i as u32,
302                 name: param.name.ident().name,
303                 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
304                 pure_wrt_drop: param.pure_wrt_drop,
305                 kind: ty::GenericParamDefKind::Const { has_default: default.is_some() },
306             };
307             i += 1;
308             Some(param_def)
309         }
310     }));
311
312     // provide junk type parameter defs - the only place that
313     // cares about anything but the length is instantiation,
314     // and we don't do that for closures.
315     if let Node::Expr(&hir::Expr {
316         kind: hir::ExprKind::Closure(hir::Closure { movability: gen, .. }),
317         ..
318     }) = node
319     {
320         let dummy_args = if gen.is_some() {
321             &["<resume_ty>", "<yield_ty>", "<return_ty>", "<witness>", "<upvars>"][..]
322         } else {
323             &["<closure_kind>", "<closure_signature>", "<upvars>"][..]
324         };
325
326         params.extend(dummy_args.iter().enumerate().map(|(i, &arg)| ty::GenericParamDef {
327             index: type_start + i as u32,
328             name: Symbol::intern(arg),
329             def_id,
330             pure_wrt_drop: false,
331             kind: ty::GenericParamDefKind::Type { has_default: false, synthetic: false },
332         }));
333     }
334
335     // provide junk type parameter defs for const blocks.
336     if let Node::AnonConst(_) = node {
337         let parent_node = tcx.hir().get(tcx.hir().get_parent_node(hir_id));
338         if let Node::Expr(&Expr { kind: ExprKind::ConstBlock(_), .. }) = parent_node {
339             params.push(ty::GenericParamDef {
340                 index: type_start,
341                 name: Symbol::intern("<const_ty>"),
342                 def_id,
343                 pure_wrt_drop: false,
344                 kind: ty::GenericParamDefKind::Type { has_default: false, synthetic: false },
345             });
346         }
347     }
348
349     let param_def_id_to_index = params.iter().map(|param| (param.def_id, param.index)).collect();
350
351     ty::Generics {
352         parent: parent_def_id,
353         parent_count,
354         params,
355         param_def_id_to_index,
356         has_self: has_self || parent_has_self,
357         has_late_bound_regions: has_late_bound_regions(tcx, node),
358     }
359 }
360
361 fn has_late_bound_regions<'tcx>(tcx: TyCtxt<'tcx>, node: Node<'tcx>) -> Option<Span> {
362     struct LateBoundRegionsDetector<'tcx> {
363         tcx: TyCtxt<'tcx>,
364         outer_index: ty::DebruijnIndex,
365         has_late_bound_regions: Option<Span>,
366     }
367
368     impl<'tcx> Visitor<'tcx> for LateBoundRegionsDetector<'tcx> {
369         fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
370             if self.has_late_bound_regions.is_some() {
371                 return;
372             }
373             match ty.kind {
374                 hir::TyKind::BareFn(..) => {
375                     self.outer_index.shift_in(1);
376                     intravisit::walk_ty(self, ty);
377                     self.outer_index.shift_out(1);
378                 }
379                 _ => intravisit::walk_ty(self, ty),
380             }
381         }
382
383         fn visit_poly_trait_ref(&mut self, tr: &'tcx hir::PolyTraitRef<'tcx>) {
384             if self.has_late_bound_regions.is_some() {
385                 return;
386             }
387             self.outer_index.shift_in(1);
388             intravisit::walk_poly_trait_ref(self, tr);
389             self.outer_index.shift_out(1);
390         }
391
392         fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
393             if self.has_late_bound_regions.is_some() {
394                 return;
395             }
396
397             match self.tcx.named_region(lt.hir_id) {
398                 Some(rl::Region::Static | rl::Region::EarlyBound(..)) => {}
399                 Some(rl::Region::LateBound(debruijn, _, _)) if debruijn < self.outer_index => {}
400                 Some(rl::Region::LateBound(..) | rl::Region::Free(..)) | None => {
401                     self.has_late_bound_regions = Some(lt.span);
402                 }
403             }
404         }
405     }
406
407     fn has_late_bound_regions<'tcx>(
408         tcx: TyCtxt<'tcx>,
409         generics: &'tcx hir::Generics<'tcx>,
410         decl: &'tcx hir::FnDecl<'tcx>,
411     ) -> Option<Span> {
412         let mut visitor = LateBoundRegionsDetector {
413             tcx,
414             outer_index: ty::INNERMOST,
415             has_late_bound_regions: None,
416         };
417         for param in generics.params {
418             if let GenericParamKind::Lifetime { .. } = param.kind {
419                 if tcx.is_late_bound(param.hir_id) {
420                     return Some(param.span);
421                 }
422             }
423         }
424         visitor.visit_fn_decl(decl);
425         visitor.has_late_bound_regions
426     }
427
428     match node {
429         Node::TraitItem(item) => match item.kind {
430             hir::TraitItemKind::Fn(ref sig, _) => {
431                 has_late_bound_regions(tcx, &item.generics, sig.decl)
432             }
433             _ => None,
434         },
435         Node::ImplItem(item) => match item.kind {
436             hir::ImplItemKind::Fn(ref sig, _) => {
437                 has_late_bound_regions(tcx, &item.generics, sig.decl)
438             }
439             _ => None,
440         },
441         Node::ForeignItem(item) => match item.kind {
442             hir::ForeignItemKind::Fn(fn_decl, _, ref generics) => {
443                 has_late_bound_regions(tcx, generics, fn_decl)
444             }
445             _ => None,
446         },
447         Node::Item(item) => match item.kind {
448             hir::ItemKind::Fn(ref sig, .., ref generics, _) => {
449                 has_late_bound_regions(tcx, generics, sig.decl)
450             }
451             _ => None,
452         },
453         _ => None,
454     }
455 }
456
457 struct AnonConstInParamTyDetector {
458     in_param_ty: bool,
459     found_anon_const_in_param_ty: bool,
460     ct: HirId,
461 }
462
463 impl<'v> Visitor<'v> for AnonConstInParamTyDetector {
464     fn visit_generic_param(&mut self, p: &'v hir::GenericParam<'v>) {
465         if let GenericParamKind::Const { ty, default: _ } = p.kind {
466             let prev = self.in_param_ty;
467             self.in_param_ty = true;
468             self.visit_ty(ty);
469             self.in_param_ty = prev;
470         }
471     }
472
473     fn visit_anon_const(&mut self, c: &'v hir::AnonConst) {
474         if self.in_param_ty && self.ct == c.hir_id {
475             self.found_anon_const_in_param_ty = true;
476         } else {
477             intravisit::walk_anon_const(self, c)
478         }
479     }
480 }