1 use crate::middle::resolve_lifetime as rl;
3 intravisit::{self, Visitor},
4 GenericParamKind, HirId, Node,
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};
14 pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::Generics {
17 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
19 let node = tcx.hir().get(hir_id);
20 let parent_def_id = match node {
26 let parent_id = tcx.hir().get_parent_item(hir_id);
27 Some(parent_id.to_def_id())
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);
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 {
39 found_anon_const_in_param_ty: false,
43 visitor.visit_generics(generics);
44 in_param_ty = visitor.found_anon_const_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.
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:
57 // struct Foo<const N: usize = { .. }>;
58 // ^^^ ^ ^^^^^^ def id of this anon const
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])`.
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.
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)
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 }>;
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[¶m_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();
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,
94 param_def_id_to_index,
95 has_self: generics.has_self,
96 has_late_bound_regions: generics.has_late_bound_regions,
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.
104 // Note that we do not supply the parent generics when using
105 // `min_const_generics`.
106 Some(parent_def_id.to_def_id())
108 let parent_node = tcx.hir().get(tcx.hir().get_parent_node(hir_id));
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 =>
117 Some(parent_def_id.to_def_id())
119 Node::Variant(Variant { disr_expr: Some(ref constant), .. })
120 if constant.hir_id == hir_id =>
122 Some(parent_def_id.to_def_id())
124 Node::Expr(&Expr { kind: ExprKind::ConstBlock(_), .. }) => {
125 Some(tcx.typeck_root_def_id(def_id))
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
137 Some(parent_def_id.to_def_id())
143 Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure { .. }, .. }) => {
144 Some(tcx.typeck_root_def_id(def_id))
146 Node::Item(item) => match item.kind {
147 ItemKind::OpaqueTy(hir::OpaqueTy {
149 hir::OpaqueTyOrigin::FnReturn(fn_def_id) | hir::OpaqueTyOrigin::AsyncFn(fn_def_id),
154 assert!(matches!(tcx.def_kind(fn_def_id), DefKind::AssocFn))
156 assert!(matches!(tcx.def_kind(fn_def_id), DefKind::AssocFn | DefKind::Fn))
158 Some(fn_def_id.to_def_id())
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())
176 FutureCompatDisallowed,
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) => {
185 ItemKind::Trait(..) | ItemKind::TraitAlias(..) => {
186 // Add in the self type parameter.
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 {
194 pure_wrt_drop: false,
195 kind: ty::GenericParamDefKind::Type {
201 (opt_self, Defaults::Allowed)
203 ItemKind::TyAlias(..)
205 | ItemKind::Struct(..)
206 | ItemKind::OpaqueTy(..)
207 | ItemKind::Union(..) => (None, Defaults::Allowed),
208 _ => (None, Defaults::FutureCompatDisallowed),
213 Node::TraitItem(item) if matches!(item.kind, TraitItemKind::Type(..)) => {
214 (None, Defaults::Deny)
216 Node::ImplItem(item) if matches!(item.kind, ImplItemKind::Type(..)) => {
217 (None, Defaults::Deny)
220 _ => (None, Defaults::FutureCompatDisallowed),
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);
229 parent_has_self = generics.has_self;
230 own_start = generics.count() as u32;
231 generics.parent_count + generics.params.len()
234 let mut params: Vec<_> = Vec::with_capacity(ast_generics.params.len() + has_self as usize);
236 if let Some(opt_self) = opt_self {
237 params.push(opt_self);
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,
249 // Now create the real type and const parameters.
250 let type_start = own_start - has_self as u32 + params.len() as u32;
252 let mut next_index = || {
255 prev as u32 + type_start
258 const TYPE_DEFAULT_NOT_ALLOWED: &'static str = "defaults for type parameters are only allowed in \
259 `struct`, `enum`, `type`, or `trait` definitions";
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,
274 TYPE_DEFAULT_NOT_ALLOWED,
279 tcx.sess.span_err(param.span, TYPE_DEFAULT_NOT_ALLOWED);
284 let kind = ty::GenericParamDefKind::Type { has_default: default.is_some(), synthetic };
286 Some(ty::GenericParamDef {
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,
294 GenericParamKind::Const { default, .. } => {
295 if !matches!(allow_defaults, Defaults::Allowed) && default.is_some() {
298 "defaults for const parameters are only allowed in \
299 `struct`, `enum`, `type`, or `trait` definitions",
303 Some(ty::GenericParamDef {
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() },
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, .. }),
321 let dummy_args = if gen.is_some() {
322 &["<resume_ty>", "<yield_ty>", "<return_ty>", "<witness>", "<upvars>"][..]
324 &["<closure_kind>", "<closure_signature>", "<upvars>"][..]
327 params.extend(dummy_args.iter().map(|&arg| ty::GenericParamDef {
329 name: Symbol::intern(arg),
331 pure_wrt_drop: false,
332 kind: ty::GenericParamDefKind::Type { has_default: false, synthetic: false },
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 {
342 name: Symbol::intern("<const_ty>"),
344 pure_wrt_drop: false,
345 kind: ty::GenericParamDefKind::Type { has_default: false, synthetic: false },
350 let param_def_id_to_index = params.iter().map(|param| (param.def_id, param.index)).collect();
353 parent: parent_def_id,
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),
362 fn has_late_bound_regions<'tcx>(tcx: TyCtxt<'tcx>, node: Node<'tcx>) -> Option<Span> {
363 struct LateBoundRegionsDetector<'tcx> {
365 outer_index: ty::DebruijnIndex,
366 has_late_bound_regions: Option<Span>,
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() {
375 hir::TyKind::BareFn(..) => {
376 self.outer_index.shift_in(1);
377 intravisit::walk_ty(self, ty);
378 self.outer_index.shift_out(1);
380 _ => intravisit::walk_ty(self, ty),
384 fn visit_poly_trait_ref(&mut self, tr: &'tcx hir::PolyTraitRef<'tcx>) {
385 if self.has_late_bound_regions.is_some() {
388 self.outer_index.shift_in(1);
389 intravisit::walk_poly_trait_ref(self, tr);
390 self.outer_index.shift_out(1);
393 fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
394 if self.has_late_bound_regions.is_some() {
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);
408 fn has_late_bound_regions<'tcx>(
410 generics: &'tcx hir::Generics<'tcx>,
411 decl: &'tcx hir::FnDecl<'tcx>,
413 let mut visitor = LateBoundRegionsDetector {
415 outer_index: ty::INNERMOST,
416 has_late_bound_regions: None,
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);
425 visitor.visit_fn_decl(decl);
426 visitor.has_late_bound_regions
430 Node::TraitItem(item) => match item.kind {
431 hir::TraitItemKind::Fn(ref sig, _) => {
432 has_late_bound_regions(tcx, &item.generics, sig.decl)
436 Node::ImplItem(item) => match item.kind {
437 hir::ImplItemKind::Fn(ref sig, _) => {
438 has_late_bound_regions(tcx, &item.generics, sig.decl)
442 Node::ForeignItem(item) => match item.kind {
443 hir::ForeignItemKind::Fn(fn_decl, _, ref generics) => {
444 has_late_bound_regions(tcx, generics, fn_decl)
448 Node::Item(item) => match item.kind {
449 hir::ItemKind::Fn(ref sig, .., ref generics, _) => {
450 has_late_bound_regions(tcx, generics, sig.decl)
458 struct AnonConstInParamTyDetector {
460 found_anon_const_in_param_ty: bool,
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;
470 self.in_param_ty = prev;
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;
478 intravisit::walk_anon_const(self, c)