1 //! "Collection" is the process of determining the type and other external
2 //! details of each item in Rust. Collection is specifically concerned
3 //! with *inter-procedural* things -- for example, for a function
4 //! definition, collection will figure out the type and signature of the
5 //! function, but it will not visit the *body* of the function in any way,
6 //! nor examine type annotations on local variables (that's the job of
9 //! Collecting is ultimately defined by a bundle of queries that
10 //! inquire after various facts about the items in the crate (e.g.,
11 //! `type_of`, `generics_of`, `predicates_of`, etc). See the `provide` function
14 //! At present, however, we do run collection across all items in the
15 //! crate as a kind of pass. This should eventually be factored away.
17 use crate::astconv::{AstConv, Bounds, SizedByDefault};
18 use crate::check::intrinsic::intrinsic_operation_unsafety;
19 use crate::constrained_generic_params as cgp;
21 use crate::middle::resolve_lifetime as rl;
22 use crate::middle::weak_lang_items;
23 use rustc::mir::mono::Linkage;
24 use rustc::ty::query::Providers;
25 use rustc::ty::subst::GenericArgKind;
26 use rustc::ty::subst::{InternalSubsts, Subst};
27 use rustc::ty::util::Discr;
28 use rustc::ty::util::IntTypeExt;
29 use rustc::ty::{self, AdtKind, Const, DefIdTree, ToPolyTraitRef, Ty, TyCtxt};
30 use rustc::ty::{ReprOptions, ToPredicate};
31 use rustc::util::captures::Captures;
32 use rustc::util::nodemap::FxHashMap;
33 use rustc_target::spec::abi;
36 use syntax::ast::{Ident, MetaItemKind};
37 use syntax::attr::{list_contains_name, mark_used, InlineAttr, OptimizeAttr};
38 use syntax::feature_gate;
39 use syntax::symbol::{kw, sym, Symbol};
40 use syntax_pos::{Span, DUMMY_SP};
42 use rustc::hir::def::{CtorKind, DefKind, Res};
43 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
44 use rustc::hir::intravisit::{self, NestedVisitorMap, Visitor};
45 use rustc::hir::GenericParamKind;
47 use rustc::hir::{self, CodegenFnAttrFlags, CodegenFnAttrs, Unsafety};
49 use errors::{Applicability, StashKey};
51 use rustc_error_codes::*;
53 struct OnlySelfBounds(bool);
55 ///////////////////////////////////////////////////////////////////////////
58 fn collect_mod_item_types(tcx: TyCtxt<'_>, module_def_id: DefId) {
59 tcx.hir().visit_item_likes_in_module(
61 &mut CollectItemTypesVisitor { tcx }.as_deep_visitor(),
65 pub fn provide(providers: &mut Providers<'_>) {
66 *providers = Providers {
70 predicates_defined_on,
71 explicit_predicates_of,
73 type_param_predicates,
82 collect_mod_item_types,
87 ///////////////////////////////////////////////////////////////////////////
89 /// Context specific to some particular item. This is what implements
90 /// `AstConv`. It has information about the predicates that are defined
91 /// on the trait. Unfortunately, this predicate information is
92 /// available in various different forms at various points in the
93 /// process. So we can't just store a pointer to e.g., the AST or the
94 /// parsed ty form, we have to be more flexible. To this end, the
95 /// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy
96 /// `get_type_parameter_bounds` requests, drawing the information from
97 /// the AST (`hir::Generics`), recursively.
98 pub struct ItemCtxt<'tcx> {
103 ///////////////////////////////////////////////////////////////////////////
105 struct CollectItemTypesVisitor<'tcx> {
109 impl Visitor<'tcx> for CollectItemTypesVisitor<'tcx> {
110 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
111 NestedVisitorMap::OnlyBodies(&self.tcx.hir())
114 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
115 convert_item(self.tcx, item.hir_id);
116 intravisit::walk_item(self, item);
119 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
120 for param in &generics.params {
122 hir::GenericParamKind::Lifetime { .. } => {}
123 hir::GenericParamKind::Type { default: Some(_), .. } => {
124 let def_id = self.tcx.hir().local_def_id(param.hir_id);
125 self.tcx.type_of(def_id);
127 hir::GenericParamKind::Type { .. } => {}
128 hir::GenericParamKind::Const { .. } => {
129 let def_id = self.tcx.hir().local_def_id(param.hir_id);
130 self.tcx.type_of(def_id);
134 intravisit::walk_generics(self, generics);
137 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
138 if let hir::ExprKind::Closure(..) = expr.kind {
139 let def_id = self.tcx.hir().local_def_id(expr.hir_id);
140 self.tcx.generics_of(def_id);
141 self.tcx.type_of(def_id);
143 intravisit::walk_expr(self, expr);
146 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
147 convert_trait_item(self.tcx, trait_item.hir_id);
148 intravisit::walk_trait_item(self, trait_item);
151 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
152 convert_impl_item(self.tcx, impl_item.hir_id);
153 intravisit::walk_impl_item(self, impl_item);
157 ///////////////////////////////////////////////////////////////////////////
158 // Utility types and common code for the above passes.
160 fn bad_placeholder_type(tcx: TyCtxt<'tcx>, span: Span) -> errors::DiagnosticBuilder<'tcx> {
161 let mut diag = struct_span_err!(
165 "the type placeholder `_` is not allowed within types on item signatures",
167 diag.span_label(span, "not allowed in type signatures");
171 impl ItemCtxt<'tcx> {
172 pub fn new(tcx: TyCtxt<'tcx>, item_def_id: DefId) -> ItemCtxt<'tcx> {
173 ItemCtxt { tcx, item_def_id }
176 pub fn to_ty(&self, ast_ty: &'tcx hir::Ty<'tcx>) -> Ty<'tcx> {
177 AstConv::ast_ty_to_ty(self, ast_ty)
181 impl AstConv<'tcx> for ItemCtxt<'tcx> {
182 fn tcx(&self) -> TyCtxt<'tcx> {
186 fn item_def_id(&self) -> Option<DefId> {
187 Some(self.item_def_id)
190 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId) -> ty::GenericPredicates<'tcx> {
191 self.tcx.at(span).type_param_predicates((self.item_def_id, def_id))
194 fn re_infer(&self, _: Option<&ty::GenericParamDef>, _: Span) -> Option<ty::Region<'tcx>> {
198 fn allow_ty_infer(&self) -> bool {
202 fn ty_infer(&self, _: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx> {
203 bad_placeholder_type(self.tcx(), span).emit();
211 _: Option<&ty::GenericParamDef>,
213 ) -> &'tcx Const<'tcx> {
214 bad_placeholder_type(self.tcx(), span).emit();
216 self.tcx().consts.err
219 fn projected_ty_from_poly_trait_ref(
223 item_segment: &hir::PathSegment<'_>,
224 poly_trait_ref: ty::PolyTraitRef<'tcx>,
226 if let Some(trait_ref) = poly_trait_ref.no_bound_vars() {
227 let item_substs = <dyn AstConv<'tcx>>::create_substs_for_associated_item(
235 self.tcx().mk_projection(item_def_id, item_substs)
237 // There are no late-bound regions; we can just ignore the binder.
242 "cannot extract an associated type from a higher-ranked trait bound \
249 fn normalize_ty(&self, _span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
250 // Types in item signatures are not normalized to avoid undue dependencies.
254 fn set_tainted_by_errors(&self) {
255 // There's no obvious place to track this, so just let it go.
258 fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) {
259 // There's no place to record types from signatures?
263 /// Returns the predicates defined on `item_def_id` of the form
264 /// `X: Foo` where `X` is the type parameter `def_id`.
265 fn type_param_predicates(
267 (item_def_id, def_id): (DefId, DefId),
268 ) -> ty::GenericPredicates<'_> {
271 // In the AST, bounds can derive from two places. Either
272 // written inline like `<T: Foo>` or in a where-clause like
275 let param_id = tcx.hir().as_local_hir_id(def_id).unwrap();
276 let param_owner = tcx.hir().ty_param_owner(param_id);
277 let param_owner_def_id = tcx.hir().local_def_id(param_owner);
278 let generics = tcx.generics_of(param_owner_def_id);
279 let index = generics.param_def_id_to_index[&def_id];
280 let ty = tcx.mk_ty_param(index, tcx.hir().ty_param_name(param_id));
282 // Don't look for bounds where the type parameter isn't in scope.
284 if item_def_id == param_owner_def_id { None } else { tcx.generics_of(item_def_id).parent };
286 let mut result = parent
288 let icx = ItemCtxt::new(tcx, parent);
289 icx.get_type_parameter_bounds(DUMMY_SP, def_id)
291 .unwrap_or_default();
292 let mut extend = None;
294 let item_hir_id = tcx.hir().as_local_hir_id(item_def_id).unwrap();
295 let ast_generics = match tcx.hir().get(item_hir_id) {
296 Node::TraitItem(item) => &item.generics,
298 Node::ImplItem(item) => &item.generics,
300 Node::Item(item) => {
302 ItemKind::Fn(.., ref generics, _)
303 | ItemKind::Impl(_, _, _, ref generics, ..)
304 | ItemKind::TyAlias(_, ref generics)
305 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
306 | ItemKind::Enum(_, ref generics)
307 | ItemKind::Struct(_, ref generics)
308 | ItemKind::Union(_, ref generics) => generics,
309 ItemKind::Trait(_, _, ref generics, ..) => {
310 // Implied `Self: Trait` and supertrait bounds.
311 if param_id == item_hir_id {
312 let identity_trait_ref = ty::TraitRef::identity(tcx, item_def_id);
313 extend = Some((identity_trait_ref.to_predicate(), item.span));
321 Node::ForeignItem(item) => match item.kind {
322 ForeignItemKind::Fn(_, _, ref generics) => generics,
329 let icx = ItemCtxt::new(tcx, item_def_id);
330 let extra_predicates = extend.into_iter().chain(
331 icx.type_parameter_bounds_in_generics(ast_generics, param_id, ty, OnlySelfBounds(true))
333 .filter(|(predicate, _)| match predicate {
334 ty::Predicate::Trait(ref data) => data.skip_binder().self_ty().is_param(index),
339 tcx.arena.alloc_from_iter(result.predicates.iter().copied().chain(extra_predicates));
343 impl ItemCtxt<'tcx> {
344 /// Finds bounds from `hir::Generics`. This requires scanning through the
345 /// AST. We do this to avoid having to convert *all* the bounds, which
346 /// would create artificial cycles. Instead, we can only convert the
347 /// bounds for a type parameter `X` if `X::Foo` is used.
348 fn type_parameter_bounds_in_generics(
350 ast_generics: &'tcx hir::Generics<'tcx>,
351 param_id: hir::HirId,
353 only_self_bounds: OnlySelfBounds,
354 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
355 let from_ty_params = ast_generics
358 .filter_map(|param| match param.kind {
359 GenericParamKind::Type { .. } if param.hir_id == param_id => Some(¶m.bounds),
362 .flat_map(|bounds| bounds.iter())
363 .flat_map(|b| predicates_from_bound(self, ty, b));
365 let from_where_clauses = ast_generics
369 .filter_map(|wp| match *wp {
370 hir::WherePredicate::BoundPredicate(ref bp) => Some(bp),
374 let bt = if is_param(self.tcx, &bp.bounded_ty, param_id) {
376 } else if !only_self_bounds.0 {
377 Some(self.to_ty(&bp.bounded_ty))
381 bp.bounds.iter().filter_map(move |b| bt.map(|bt| (bt, b)))
383 .flat_map(|(bt, b)| predicates_from_bound(self, bt, b));
385 from_ty_params.chain(from_where_clauses).collect()
389 /// Tests whether this is the AST for a reference to the type
390 /// parameter with ID `param_id`. We use this so as to avoid running
391 /// `ast_ty_to_ty`, because we want to avoid triggering an all-out
392 /// conversion of the type to avoid inducing unnecessary cycles.
393 fn is_param(tcx: TyCtxt<'_>, ast_ty: &hir::Ty<'_>, param_id: hir::HirId) -> bool {
394 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = ast_ty.kind {
396 Res::SelfTy(Some(def_id), None) | Res::Def(DefKind::TyParam, def_id) => {
397 def_id == tcx.hir().local_def_id(param_id)
406 fn convert_item(tcx: TyCtxt<'_>, item_id: hir::HirId) {
407 let it = tcx.hir().expect_item(item_id);
408 debug!("convert: item {} with id {}", it.ident, it.hir_id);
409 let def_id = tcx.hir().local_def_id(item_id);
411 // These don't define types.
412 hir::ItemKind::ExternCrate(_)
413 | hir::ItemKind::Use(..)
414 | hir::ItemKind::Mod(_)
415 | hir::ItemKind::GlobalAsm(_) => {}
416 hir::ItemKind::ForeignMod(ref foreign_mod) => {
417 for item in foreign_mod.items {
418 let def_id = tcx.hir().local_def_id(item.hir_id);
419 tcx.generics_of(def_id);
421 tcx.predicates_of(def_id);
422 if let hir::ForeignItemKind::Fn(..) = item.kind {
427 hir::ItemKind::Enum(ref enum_definition, _) => {
428 tcx.generics_of(def_id);
430 tcx.predicates_of(def_id);
431 convert_enum_variant_types(tcx, def_id, &enum_definition.variants);
433 hir::ItemKind::Impl(..) => {
434 tcx.generics_of(def_id);
436 tcx.impl_trait_ref(def_id);
437 tcx.predicates_of(def_id);
439 hir::ItemKind::Trait(..) => {
440 tcx.generics_of(def_id);
441 tcx.trait_def(def_id);
442 tcx.at(it.span).super_predicates_of(def_id);
443 tcx.predicates_of(def_id);
445 hir::ItemKind::TraitAlias(..) => {
446 tcx.generics_of(def_id);
447 tcx.at(it.span).super_predicates_of(def_id);
448 tcx.predicates_of(def_id);
450 hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
451 tcx.generics_of(def_id);
453 tcx.predicates_of(def_id);
455 for f in struct_def.fields() {
456 let def_id = tcx.hir().local_def_id(f.hir_id);
457 tcx.generics_of(def_id);
459 tcx.predicates_of(def_id);
462 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
463 convert_variant_ctor(tcx, ctor_hir_id);
467 // Desugared from `impl Trait`, so visited by the function's return type.
468 hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: Some(_), .. }) => {}
470 hir::ItemKind::OpaqueTy(..)
471 | hir::ItemKind::TyAlias(..)
472 | hir::ItemKind::Static(..)
473 | hir::ItemKind::Const(..)
474 | hir::ItemKind::Fn(..) => {
475 tcx.generics_of(def_id);
477 tcx.predicates_of(def_id);
478 if let hir::ItemKind::Fn(..) = it.kind {
485 fn convert_trait_item(tcx: TyCtxt<'_>, trait_item_id: hir::HirId) {
486 let trait_item = tcx.hir().expect_trait_item(trait_item_id);
487 let def_id = tcx.hir().local_def_id(trait_item.hir_id);
488 tcx.generics_of(def_id);
490 match trait_item.kind {
491 hir::TraitItemKind::Const(..)
492 | hir::TraitItemKind::Type(_, Some(_))
493 | hir::TraitItemKind::Method(..) => {
495 if let hir::TraitItemKind::Method(..) = trait_item.kind {
500 hir::TraitItemKind::Type(_, None) => {}
503 tcx.predicates_of(def_id);
506 fn convert_impl_item(tcx: TyCtxt<'_>, impl_item_id: hir::HirId) {
507 let def_id = tcx.hir().local_def_id(impl_item_id);
508 tcx.generics_of(def_id);
510 tcx.predicates_of(def_id);
511 if let hir::ImplItemKind::Method(..) = tcx.hir().expect_impl_item(impl_item_id).kind {
516 fn convert_variant_ctor(tcx: TyCtxt<'_>, ctor_id: hir::HirId) {
517 let def_id = tcx.hir().local_def_id(ctor_id);
518 tcx.generics_of(def_id);
520 tcx.predicates_of(def_id);
523 fn convert_enum_variant_types(tcx: TyCtxt<'_>, def_id: DefId, variants: &[hir::Variant<'_>]) {
524 let def = tcx.adt_def(def_id);
525 let repr_type = def.repr.discr_type();
526 let initial = repr_type.initial_discriminant(tcx);
527 let mut prev_discr = None::<Discr<'_>>;
529 // fill the discriminant values and field types
530 for variant in variants {
531 let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
533 if let Some(ref e) = variant.disr_expr {
534 let expr_did = tcx.hir().local_def_id(e.hir_id);
535 def.eval_explicit_discr(tcx, expr_did)
536 } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) {
539 struct_span_err!(tcx.sess, variant.span, E0370, "enum discriminant overflowed")
542 format!("overflowed on value after {}", prev_discr.unwrap()),
545 "explicitly set `{} = {}` if that is desired outcome",
546 variant.ident, wrapped_discr
551 .unwrap_or(wrapped_discr),
554 for f in variant.data.fields() {
555 let def_id = tcx.hir().local_def_id(f.hir_id);
556 tcx.generics_of(def_id);
558 tcx.predicates_of(def_id);
561 // Convert the ctor, if any. This also registers the variant as
563 if let Some(ctor_hir_id) = variant.data.ctor_hir_id() {
564 convert_variant_ctor(tcx, ctor_hir_id);
571 variant_did: Option<DefId>,
572 ctor_did: Option<DefId>,
574 discr: ty::VariantDiscr,
575 def: &hir::VariantData<'_>,
576 adt_kind: ty::AdtKind,
578 ) -> ty::VariantDef {
579 let mut seen_fields: FxHashMap<ast::Ident, Span> = Default::default();
580 let hir_id = tcx.hir().as_local_hir_id(variant_did.unwrap_or(parent_did)).unwrap();
585 let fid = tcx.hir().local_def_id(f.hir_id);
586 let dup_span = seen_fields.get(&f.ident.modern()).cloned();
587 if let Some(prev_span) = dup_span {
592 "field `{}` is already declared",
595 .span_label(f.span, "field already declared")
596 .span_label(prev_span, format!("`{}` first declared here", f.ident))
599 seen_fields.insert(f.ident.modern(), f.span);
605 vis: ty::Visibility::from_hir(&f.vis, hir_id, tcx),
609 let recovered = match def {
610 hir::VariantData::Struct(_, r) => *r,
620 CtorKind::from_hir(def),
627 fn adt_def(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::AdtDef {
630 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
631 let item = match tcx.hir().get(hir_id) {
632 Node::Item(item) => item,
636 let repr = ReprOptions::new(tcx, def_id);
637 let (kind, variants) = match item.kind {
638 ItemKind::Enum(ref def, _) => {
639 let mut distance_from_explicit = 0;
644 let variant_did = Some(tcx.hir().local_def_id(v.id));
646 v.data.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
648 let discr = if let Some(ref e) = v.disr_expr {
649 distance_from_explicit = 0;
650 ty::VariantDiscr::Explicit(tcx.hir().local_def_id(e.hir_id))
652 ty::VariantDiscr::Relative(distance_from_explicit)
654 distance_from_explicit += 1;
669 (AdtKind::Enum, variants)
671 ItemKind::Struct(ref def, _) => {
672 let variant_did = None;
673 let ctor_did = def.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
675 let variants = std::iter::once(convert_variant(
680 ty::VariantDiscr::Relative(0),
687 (AdtKind::Struct, variants)
689 ItemKind::Union(ref def, _) => {
690 let variant_did = None;
691 let ctor_did = def.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
693 let variants = std::iter::once(convert_variant(
698 ty::VariantDiscr::Relative(0),
705 (AdtKind::Union, variants)
709 tcx.alloc_adt_def(def_id, kind, variants, repr)
712 /// Ensures that the super-predicates of the trait with a `DefId`
713 /// of `trait_def_id` are converted and stored. This also ensures that
714 /// the transitive super-predicates are converted.
715 fn super_predicates_of(tcx: TyCtxt<'_>, trait_def_id: DefId) -> ty::GenericPredicates<'_> {
716 debug!("super_predicates(trait_def_id={:?})", trait_def_id);
717 let trait_hir_id = tcx.hir().as_local_hir_id(trait_def_id).unwrap();
719 let item = match tcx.hir().get(trait_hir_id) {
720 Node::Item(item) => item,
721 _ => bug!("trait_node_id {} is not an item", trait_hir_id),
724 let (generics, bounds) = match item.kind {
725 hir::ItemKind::Trait(.., ref generics, ref supertraits, _) => (generics, supertraits),
726 hir::ItemKind::TraitAlias(ref generics, ref supertraits) => (generics, supertraits),
727 _ => span_bug!(item.span, "super_predicates invoked on non-trait"),
730 let icx = ItemCtxt::new(tcx, trait_def_id);
732 // Convert the bounds that follow the colon, e.g., `Bar + Zed` in `trait Foo: Bar + Zed`.
733 let self_param_ty = tcx.types.self_param;
735 AstConv::compute_bounds(&icx, self_param_ty, bounds, SizedByDefault::No, item.span);
737 let superbounds1 = superbounds1.predicates(tcx, self_param_ty);
739 // Convert any explicit superbounds in the where-clause,
740 // e.g., `trait Foo where Self: Bar`.
741 // In the case of trait aliases, however, we include all bounds in the where-clause,
742 // so e.g., `trait Foo = where u32: PartialEq<Self>` would include `u32: PartialEq<Self>`
743 // as one of its "superpredicates".
744 let is_trait_alias = tcx.is_trait_alias(trait_def_id);
745 let superbounds2 = icx.type_parameter_bounds_in_generics(
749 OnlySelfBounds(!is_trait_alias),
752 // Combine the two lists to form the complete set of superbounds:
753 let superbounds = &*tcx.arena.alloc_from_iter(superbounds1.into_iter().chain(superbounds2));
755 // Now require that immediate supertraits are converted,
756 // which will, in turn, reach indirect supertraits.
757 for &(pred, span) in superbounds {
758 debug!("superbound: {:?}", pred);
759 if let ty::Predicate::Trait(bound) = pred {
760 tcx.at(span).super_predicates_of(bound.def_id());
764 ty::GenericPredicates { parent: None, predicates: superbounds }
767 fn trait_def(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::TraitDef {
768 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
769 let item = tcx.hir().expect_item(hir_id);
771 let (is_auto, unsafety) = match item.kind {
772 hir::ItemKind::Trait(is_auto, unsafety, ..) => (is_auto == hir::IsAuto::Yes, unsafety),
773 hir::ItemKind::TraitAlias(..) => (false, hir::Unsafety::Normal),
774 _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
777 let paren_sugar = tcx.has_attr(def_id, sym::rustc_paren_sugar);
778 if paren_sugar && !tcx.features().unboxed_closures {
779 let mut err = tcx.sess.struct_span_err(
781 "the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \
782 which traits can use parenthetical notation",
786 "add `#![feature(unboxed_closures)]` to \
787 the crate attributes to use it"
792 let is_marker = tcx.has_attr(def_id, sym::marker);
793 let def_path_hash = tcx.def_path_hash(def_id);
794 let def = ty::TraitDef::new(def_id, unsafety, paren_sugar, is_auto, is_marker, def_path_hash);
798 fn has_late_bound_regions<'tcx>(tcx: TyCtxt<'tcx>, node: Node<'tcx>) -> Option<Span> {
799 struct LateBoundRegionsDetector<'tcx> {
801 outer_index: ty::DebruijnIndex,
802 has_late_bound_regions: Option<Span>,
805 impl Visitor<'tcx> for LateBoundRegionsDetector<'tcx> {
806 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
807 NestedVisitorMap::None
810 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
811 if self.has_late_bound_regions.is_some() {
815 hir::TyKind::BareFn(..) => {
816 self.outer_index.shift_in(1);
817 intravisit::walk_ty(self, ty);
818 self.outer_index.shift_out(1);
820 _ => intravisit::walk_ty(self, ty),
824 fn visit_poly_trait_ref(
826 tr: &'tcx hir::PolyTraitRef<'tcx>,
827 m: hir::TraitBoundModifier,
829 if self.has_late_bound_regions.is_some() {
832 self.outer_index.shift_in(1);
833 intravisit::walk_poly_trait_ref(self, tr, m);
834 self.outer_index.shift_out(1);
837 fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
838 if self.has_late_bound_regions.is_some() {
842 match self.tcx.named_region(lt.hir_id) {
843 Some(rl::Region::Static) | Some(rl::Region::EarlyBound(..)) => {}
844 Some(rl::Region::LateBound(debruijn, _, _))
845 | Some(rl::Region::LateBoundAnon(debruijn, _))
846 if debruijn < self.outer_index => {}
847 Some(rl::Region::LateBound(..))
848 | Some(rl::Region::LateBoundAnon(..))
849 | Some(rl::Region::Free(..))
851 self.has_late_bound_regions = Some(lt.span);
857 fn has_late_bound_regions<'tcx>(
859 generics: &'tcx hir::Generics<'tcx>,
860 decl: &'tcx hir::FnDecl<'tcx>,
862 let mut visitor = LateBoundRegionsDetector {
864 outer_index: ty::INNERMOST,
865 has_late_bound_regions: None,
867 for param in &generics.params {
868 if let GenericParamKind::Lifetime { .. } = param.kind {
869 if tcx.is_late_bound(param.hir_id) {
870 return Some(param.span);
874 visitor.visit_fn_decl(decl);
875 visitor.has_late_bound_regions
879 Node::TraitItem(item) => match item.kind {
880 hir::TraitItemKind::Method(ref sig, _) => {
881 has_late_bound_regions(tcx, &item.generics, &sig.decl)
885 Node::ImplItem(item) => match item.kind {
886 hir::ImplItemKind::Method(ref sig, _) => {
887 has_late_bound_regions(tcx, &item.generics, &sig.decl)
891 Node::ForeignItem(item) => match item.kind {
892 hir::ForeignItemKind::Fn(ref fn_decl, _, ref generics) => {
893 has_late_bound_regions(tcx, generics, fn_decl)
897 Node::Item(item) => match item.kind {
898 hir::ItemKind::Fn(ref sig, .., ref generics, _) => {
899 has_late_bound_regions(tcx, generics, &sig.decl)
907 fn generics_of(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::Generics {
910 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
912 let node = tcx.hir().get(hir_id);
913 let parent_def_id = match node {
918 | Node::Field(_) => {
919 let parent_id = tcx.hir().get_parent_item(hir_id);
920 Some(tcx.hir().local_def_id(parent_id))
922 // FIXME(#43408) enable this always when we get lazy normalization.
923 Node::AnonConst(_) => {
924 // HACK(eddyb) this provides the correct generics when
925 // `feature(const_generics)` is enabled, so that const expressions
926 // used with const generics, e.g. `Foo<{N+1}>`, can work at all.
927 if tcx.features().const_generics {
928 let parent_id = tcx.hir().get_parent_item(hir_id);
929 Some(tcx.hir().local_def_id(parent_id))
934 Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => {
935 Some(tcx.closure_base_def_id(def_id))
937 Node::Item(item) => match item.kind {
938 ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn, .. }) => impl_trait_fn,
944 let mut opt_self = None;
945 let mut allow_defaults = false;
947 let no_generics = hir::Generics::empty();
948 let ast_generics = match node {
949 Node::TraitItem(item) => &item.generics,
951 Node::ImplItem(item) => &item.generics,
953 Node::Item(item) => {
955 ItemKind::Fn(.., ref generics, _) | ItemKind::Impl(_, _, _, ref generics, ..) => {
959 ItemKind::TyAlias(_, ref generics)
960 | ItemKind::Enum(_, ref generics)
961 | ItemKind::Struct(_, ref generics)
962 | ItemKind::OpaqueTy(hir::OpaqueTy { ref generics, .. })
963 | ItemKind::Union(_, ref generics) => {
964 allow_defaults = true;
968 ItemKind::Trait(_, _, ref generics, ..)
969 | ItemKind::TraitAlias(ref generics, ..) => {
970 // Add in the self type parameter.
972 // Something of a hack: use the node id for the trait, also as
973 // the node id for the Self type parameter.
974 let param_id = item.hir_id;
976 opt_self = Some(ty::GenericParamDef {
979 def_id: tcx.hir().local_def_id(param_id),
980 pure_wrt_drop: false,
981 kind: ty::GenericParamDefKind::Type {
983 object_lifetime_default: rl::Set1::Empty,
988 allow_defaults = true;
996 Node::ForeignItem(item) => match item.kind {
997 ForeignItemKind::Static(..) => &no_generics,
998 ForeignItemKind::Fn(_, _, ref generics) => generics,
999 ForeignItemKind::Type => &no_generics,
1005 let has_self = opt_self.is_some();
1006 let mut parent_has_self = false;
1007 let mut own_start = has_self as u32;
1008 let parent_count = parent_def_id.map_or(0, |def_id| {
1009 let generics = tcx.generics_of(def_id);
1010 assert_eq!(has_self, false);
1011 parent_has_self = generics.has_self;
1012 own_start = generics.count() as u32;
1013 generics.parent_count + generics.params.len()
1016 let mut params: Vec<_> = opt_self.into_iter().collect();
1018 let early_lifetimes = early_bound_lifetimes_from_generics(tcx, ast_generics);
1019 params.extend(early_lifetimes.enumerate().map(|(i, param)| ty::GenericParamDef {
1020 name: param.name.ident().name,
1021 index: own_start + i as u32,
1022 def_id: tcx.hir().local_def_id(param.hir_id),
1023 pure_wrt_drop: param.pure_wrt_drop,
1024 kind: ty::GenericParamDefKind::Lifetime,
1027 let object_lifetime_defaults = tcx.object_lifetime_defaults(hir_id);
1029 // Now create the real type parameters.
1030 let type_start = own_start - has_self as u32 + params.len() as u32;
1032 params.extend(ast_generics.params.iter().filter_map(|param| {
1033 let kind = match param.kind {
1034 GenericParamKind::Type { ref default, synthetic, .. } => {
1035 if !allow_defaults && default.is_some() {
1036 if !tcx.features().default_type_parameter_fallback {
1038 lint::builtin::INVALID_TYPE_PARAM_DEFAULT,
1042 "defaults for type parameters are only allowed in \
1043 `struct`, `enum`, `type`, or `trait` definitions."
1049 ty::GenericParamDefKind::Type {
1050 has_default: default.is_some(),
1051 object_lifetime_default: object_lifetime_defaults
1053 .map_or(rl::Set1::Empty, |o| o[i]),
1057 GenericParamKind::Const { .. } => ty::GenericParamDefKind::Const,
1061 let param_def = ty::GenericParamDef {
1062 index: type_start + i as u32,
1063 name: param.name.ident().name,
1064 def_id: tcx.hir().local_def_id(param.hir_id),
1065 pure_wrt_drop: param.pure_wrt_drop,
1072 // provide junk type parameter defs - the only place that
1073 // cares about anything but the length is instantiation,
1074 // and we don't do that for closures.
1075 if let Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(.., gen), .. }) = node {
1076 let dummy_args = if gen.is_some() {
1077 &["<yield_ty>", "<return_ty>", "<witness>"][..]
1079 &["<closure_kind>", "<closure_signature>"][..]
1082 params.extend(dummy_args.iter().enumerate().map(|(i, &arg)| ty::GenericParamDef {
1083 index: type_start + i as u32,
1084 name: Symbol::intern(arg),
1086 pure_wrt_drop: false,
1087 kind: ty::GenericParamDefKind::Type {
1089 object_lifetime_default: rl::Set1::Empty,
1094 if let Some(upvars) = tcx.upvars(def_id) {
1095 params.extend(upvars.iter().zip((dummy_args.len() as u32)..).map(|(_, i)| {
1096 ty::GenericParamDef {
1097 index: type_start + i,
1098 name: Symbol::intern("<upvar>"),
1100 pure_wrt_drop: false,
1101 kind: ty::GenericParamDefKind::Type {
1103 object_lifetime_default: rl::Set1::Empty,
1111 let param_def_id_to_index = params.iter().map(|param| (param.def_id, param.index)).collect();
1113 tcx.arena.alloc(ty::Generics {
1114 parent: parent_def_id,
1117 param_def_id_to_index,
1118 has_self: has_self || parent_has_self,
1119 has_late_bound_regions: has_late_bound_regions(tcx, node),
1123 fn report_assoc_ty_on_inherent_impl(tcx: TyCtxt<'_>, span: Span) {
1128 "associated types are not yet supported in inherent impls (see #8995)"
1132 fn infer_placeholder_type(
1135 body_id: hir::BodyId,
1139 let ty = tcx.typeck_tables_of(def_id).node_type(body_id.hir_id);
1141 // If this came from a free `const` or `static mut?` item,
1142 // then the user may have written e.g. `const A = 42;`.
1143 // In this case, the parser has stashed a diagnostic for
1144 // us to improve in typeck so we do that now.
1145 match tcx.sess.diagnostic().steal_diagnostic(span, StashKey::ItemNoType) {
1147 // The parser provided a sub-optimal `HasPlaceholders` suggestion for the type.
1148 // We are typeck and have the real type, so remove that and suggest the actual type.
1149 err.suggestions.clear();
1150 err.span_suggestion(
1152 "provide a type for the item",
1153 format!("{}: {}", item_ident, ty),
1154 Applicability::MachineApplicable,
1159 let mut diag = bad_placeholder_type(tcx, span);
1160 if ty != tcx.types.err {
1161 diag.span_suggestion(
1163 "replace `_` with the correct type",
1165 Applicability::MaybeIncorrect,
1175 fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> {
1178 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1180 let icx = ItemCtxt::new(tcx, def_id);
1182 match tcx.hir().get(hir_id) {
1183 Node::TraitItem(item) => match item.kind {
1184 TraitItemKind::Method(..) => {
1185 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1186 tcx.mk_fn_def(def_id, substs)
1188 TraitItemKind::Const(ref ty, body_id) => body_id
1189 .and_then(|body_id| {
1190 if let hir::TyKind::Infer = ty.kind {
1191 Some(infer_placeholder_type(tcx, def_id, body_id, ty.span, item.ident))
1196 .unwrap_or_else(|| icx.to_ty(ty)),
1197 TraitItemKind::Type(_, Some(ref ty)) => icx.to_ty(ty),
1198 TraitItemKind::Type(_, None) => {
1199 span_bug!(item.span, "associated type missing default");
1203 Node::ImplItem(item) => match item.kind {
1204 ImplItemKind::Method(..) => {
1205 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1206 tcx.mk_fn_def(def_id, substs)
1208 ImplItemKind::Const(ref ty, body_id) => {
1209 if let hir::TyKind::Infer = ty.kind {
1210 infer_placeholder_type(tcx, def_id, body_id, ty.span, item.ident)
1215 ImplItemKind::OpaqueTy(_) => {
1216 if tcx.impl_trait_ref(tcx.hir().get_parent_did(hir_id)).is_none() {
1217 report_assoc_ty_on_inherent_impl(tcx, item.span);
1220 find_opaque_ty_constraints(tcx, def_id)
1222 ImplItemKind::TyAlias(ref ty) => {
1223 if tcx.impl_trait_ref(tcx.hir().get_parent_did(hir_id)).is_none() {
1224 report_assoc_ty_on_inherent_impl(tcx, item.span);
1231 Node::Item(item) => {
1233 ItemKind::Static(ref ty, .., body_id) | ItemKind::Const(ref ty, body_id) => {
1234 if let hir::TyKind::Infer = ty.kind {
1235 infer_placeholder_type(tcx, def_id, body_id, ty.span, item.ident)
1240 ItemKind::TyAlias(ref ty, _) | ItemKind::Impl(.., ref ty, _) => icx.to_ty(ty),
1241 ItemKind::Fn(..) => {
1242 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1243 tcx.mk_fn_def(def_id, substs)
1245 ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
1246 let def = tcx.adt_def(def_id);
1247 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1248 tcx.mk_adt(def, substs)
1250 ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: None, .. }) => {
1251 find_opaque_ty_constraints(tcx, def_id)
1253 // Opaque types desugared from `impl Trait`.
1254 ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: Some(owner), .. }) => {
1255 tcx.typeck_tables_of(owner)
1256 .concrete_opaque_types
1258 .map(|opaque| opaque.concrete_type)
1259 .unwrap_or_else(|| {
1260 // This can occur if some error in the
1261 // owner fn prevented us from populating
1262 // the `concrete_opaque_types` table.
1263 tcx.sess.delay_span_bug(
1266 "owner {:?} has no opaque type for {:?} in its tables",
1274 | ItemKind::TraitAlias(..)
1276 | ItemKind::ForeignMod(..)
1277 | ItemKind::GlobalAsm(..)
1278 | ItemKind::ExternCrate(..)
1279 | ItemKind::Use(..) => {
1282 "compute_type_of_item: unexpected item type: {:?}",
1289 Node::ForeignItem(foreign_item) => match foreign_item.kind {
1290 ForeignItemKind::Fn(..) => {
1291 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1292 tcx.mk_fn_def(def_id, substs)
1294 ForeignItemKind::Static(ref t, _) => icx.to_ty(t),
1295 ForeignItemKind::Type => tcx.mk_foreign(def_id),
1298 Node::Ctor(&ref def) | Node::Variant(hir::Variant { data: ref def, .. }) => match *def {
1299 VariantData::Unit(..) | VariantData::Struct(..) => {
1300 tcx.type_of(tcx.hir().get_parent_did(hir_id))
1302 VariantData::Tuple(..) => {
1303 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1304 tcx.mk_fn_def(def_id, substs)
1308 Node::Field(field) => icx.to_ty(&field.ty),
1310 Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(.., gen), .. }) => {
1312 return tcx.typeck_tables_of(def_id).node_type(hir_id);
1315 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1316 tcx.mk_closure(def_id, substs)
1319 Node::AnonConst(_) => {
1320 let parent_node = tcx.hir().get(tcx.hir().get_parent_node(hir_id));
1322 Node::Ty(&hir::Ty { kind: hir::TyKind::Array(_, ref constant), .. })
1323 | Node::Ty(&hir::Ty { kind: hir::TyKind::Typeof(ref constant), .. })
1324 | Node::Expr(&hir::Expr { kind: ExprKind::Repeat(_, ref constant), .. })
1325 if constant.hir_id == hir_id =>
1330 Node::Variant(Variant { disr_expr: Some(ref e), .. }) if e.hir_id == hir_id => {
1331 tcx.adt_def(tcx.hir().get_parent_did(hir_id)).repr.discr_type().to_ty(tcx)
1334 Node::Ty(&hir::Ty { kind: hir::TyKind::Path(_), .. })
1335 | Node::Expr(&hir::Expr { kind: ExprKind::Struct(..), .. })
1336 | Node::Expr(&hir::Expr { kind: ExprKind::Path(_), .. })
1337 | Node::TraitRef(..) => {
1338 let path = match parent_node {
1340 kind: hir::TyKind::Path(QPath::Resolved(_, ref path)),
1343 | Node::Expr(&hir::Expr {
1344 kind: ExprKind::Path(QPath::Resolved(_, ref path)),
1346 }) => Some(&**path),
1347 Node::Expr(&hir::Expr { kind: ExprKind::Struct(ref path, ..), .. }) => {
1348 if let QPath::Resolved(_, ref path) = **path {
1354 Node::TraitRef(&hir::TraitRef { ref path, .. }) => Some(&**path),
1358 if let Some(path) = path {
1359 let arg_index = path
1362 .filter_map(|seg| seg.args.as_ref())
1363 .map(|generic_args| generic_args.args.as_ref())
1366 .filter(|arg| arg.is_const())
1368 .filter(|(_, arg)| arg.id() == hir_id)
1369 .map(|(index, _)| index)
1372 .unwrap_or_else(|| {
1373 bug!("no arg matching AnonConst in path");
1376 // We've encountered an `AnonConst` in some path, so we need to
1377 // figure out which generic parameter it corresponds to and return
1378 // the relevant type.
1379 let generics = match path.res {
1380 Res::Def(DefKind::Ctor(..), def_id) => {
1381 tcx.generics_of(tcx.parent(def_id).unwrap())
1383 Res::Def(_, def_id) => tcx.generics_of(def_id),
1384 Res::Err => return tcx.types.err,
1386 tcx.sess.delay_span_bug(
1388 &format!("unexpected const parent path def {:?}", res,),
1390 return tcx.types.err;
1398 if let ty::GenericParamDefKind::Const = param.kind {
1405 .map(|param| tcx.type_of(param.def_id))
1406 // This is no generic parameter associated with the arg. This is
1407 // probably from an extra arg where one is not needed.
1408 .unwrap_or(tcx.types.err)
1410 tcx.sess.delay_span_bug(
1412 &format!("unexpected const parent path {:?}", parent_node,),
1414 return tcx.types.err;
1419 tcx.sess.delay_span_bug(
1421 &format!("unexpected const parent in type_of_def_id(): {:?}", x),
1428 Node::GenericParam(param) => {
1430 hir::GenericParamKind::Type { default: Some(ref ty), .. } => icx.to_ty(ty),
1431 hir::GenericParamKind::Const { ty: ref hir_ty, .. } => {
1432 let ty = icx.to_ty(hir_ty);
1433 if !tcx.features().const_compare_raw_pointers {
1434 let err = match ty.peel_refs().kind {
1435 ty::FnPtr(_) => Some("function pointers"),
1436 ty::RawPtr(_) => Some("raw pointers"),
1439 if let Some(unsupported_type) = err {
1440 feature_gate::feature_err(
1441 &tcx.sess.parse_sess,
1442 sym::const_compare_raw_pointers,
1445 "using {} as const generic parameters is unstable",
1452 if ty::search_for_structural_match_violation(param.hir_id, param.span, tcx, ty)
1459 "the types of const generic parameters must derive `PartialEq` and `Eq`",
1462 format!("`{}` doesn't derive both `PartialEq` and `Eq`", ty),
1467 x => bug!("unexpected non-type Node::GenericParam: {:?}", x),
1472 bug!("unexpected sort of node in type_of_def_id(): {:?}", x);
1477 fn find_opaque_ty_constraints(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> {
1478 use rustc::hir::{ImplItem, Item, TraitItem};
1480 debug!("find_opaque_ty_constraints({:?})", def_id);
1482 struct ConstraintLocator<'tcx> {
1485 // (first found type span, actual type, mapping from the opaque type's generic
1486 // parameters to the concrete type's generic parameters)
1488 // The mapping is an index for each use site of a generic parameter in the concrete type
1490 // The indices index into the generic parameters on the opaque type.
1491 found: Option<(Span, Ty<'tcx>, Vec<usize>)>,
1494 impl ConstraintLocator<'tcx> {
1495 fn check(&mut self, def_id: DefId) {
1496 // Don't try to check items that cannot possibly constrain the type.
1497 if !self.tcx.has_typeck_tables(def_id) {
1499 "find_opaque_ty_constraints: no constraint for `{:?}` at `{:?}`: no tables",
1500 self.def_id, def_id,
1504 let ty = self.tcx.typeck_tables_of(def_id).concrete_opaque_types.get(&self.def_id);
1505 if let Some(ty::ResolvedOpaqueTy { concrete_type, substs }) = ty {
1507 "find_opaque_ty_constraints: found constraint for `{:?}` at `{:?}`: {:?}",
1508 self.def_id, def_id, ty,
1511 // FIXME(oli-obk): trace the actual span from inference to improve errors.
1512 let span = self.tcx.def_span(def_id);
1513 // used to quickly look up the position of a generic parameter
1514 let mut index_map: FxHashMap<ty::ParamTy, usize> = FxHashMap::default();
1515 // Skipping binder is ok, since we only use this to find generic parameters and
1517 for (idx, subst) in substs.iter().enumerate() {
1518 if let GenericArgKind::Type(ty) = subst.unpack() {
1519 if let ty::Param(p) = ty.kind {
1520 if index_map.insert(p, idx).is_some() {
1521 // There was already an entry for `p`, meaning a generic parameter
1523 self.tcx.sess.span_err(
1526 "defining opaque type use restricts opaque \
1527 type by using the generic parameter `{}` twice",
1534 self.tcx.sess.delay_span_bug(
1537 "non-defining opaque ty use in defining scope: {:?}, {:?}",
1538 concrete_type, substs,
1544 // Compute the index within the opaque type for each generic parameter used in
1545 // the concrete type.
1546 let indices = concrete_type
1547 .subst(self.tcx, substs)
1549 .filter_map(|t| match &t.kind {
1550 ty::Param(p) => Some(*index_map.get(p).unwrap()),
1554 let is_param = |ty: Ty<'_>| match ty.kind {
1555 ty::Param(_) => true,
1558 let bad_substs: Vec<_> =
1559 substs.types().enumerate().filter(|(_, ty)| !is_param(ty)).collect();
1560 if !bad_substs.is_empty() {
1561 let identity_substs = InternalSubsts::identity_for_item(self.tcx, self.def_id);
1562 for (i, bad_subst) in bad_substs {
1563 self.tcx.sess.span_err(
1566 "defining opaque type use does not fully define opaque type: \
1567 generic parameter `{}` is specified as concrete type `{}`",
1568 identity_substs.type_at(i),
1573 } else if let Some((prev_span, prev_ty, ref prev_indices)) = self.found {
1574 let mut ty = concrete_type.walk().fuse();
1575 let mut p_ty = prev_ty.walk().fuse();
1576 let iter_eq = (&mut ty).zip(&mut p_ty).all(|(t, p)| match (&t.kind, &p.kind) {
1577 // Type parameters are equal to any other type parameter for the purpose of
1578 // concrete type equality, as it is possible to obtain the same type just
1579 // by passing matching parameters to a function.
1580 (ty::Param(_), ty::Param(_)) => true,
1583 if !iter_eq || ty.next().is_some() || p_ty.next().is_some() {
1584 debug!("find_opaque_ty_constraints: span={:?}", span);
1585 // Found different concrete types for the opaque type.
1586 let mut err = self.tcx.sess.struct_span_err(
1588 "concrete type differs from previous defining opaque type use",
1592 format!("expected `{}`, got `{}`", prev_ty, concrete_type),
1594 err.span_note(prev_span, "previous use here");
1596 } else if indices != *prev_indices {
1597 // Found "same" concrete types, but the generic parameter order differs.
1598 let mut err = self.tcx.sess.struct_span_err(
1600 "concrete type's generic parameters differ from previous defining use",
1602 use std::fmt::Write;
1603 let mut s = String::new();
1604 write!(s, "expected [").unwrap();
1605 let list = |s: &mut String, indices: &Vec<usize>| {
1606 let mut indices = indices.iter().cloned();
1607 if let Some(first) = indices.next() {
1608 write!(s, "`{}`", substs[first]).unwrap();
1610 write!(s, ", `{}`", substs[i]).unwrap();
1614 list(&mut s, prev_indices);
1615 write!(s, "], got [").unwrap();
1616 list(&mut s, &indices);
1617 write!(s, "]").unwrap();
1618 err.span_label(span, s);
1619 err.span_note(prev_span, "previous use here");
1623 self.found = Some((span, concrete_type, indices));
1627 "find_opaque_ty_constraints: no constraint for `{:?}` at `{:?}`",
1628 self.def_id, def_id,
1634 impl<'tcx> intravisit::Visitor<'tcx> for ConstraintLocator<'tcx> {
1635 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
1636 intravisit::NestedVisitorMap::All(&self.tcx.hir())
1638 fn visit_item(&mut self, it: &'tcx Item<'tcx>) {
1639 debug!("find_existential_constraints: visiting {:?}", it);
1640 let def_id = self.tcx.hir().local_def_id(it.hir_id);
1641 // The opaque type itself or its children are not within its reveal scope.
1642 if def_id != self.def_id {
1644 intravisit::walk_item(self, it);
1647 fn visit_impl_item(&mut self, it: &'tcx ImplItem<'tcx>) {
1648 debug!("find_existential_constraints: visiting {:?}", it);
1649 let def_id = self.tcx.hir().local_def_id(it.hir_id);
1650 // The opaque type itself or its children are not within its reveal scope.
1651 if def_id != self.def_id {
1653 intravisit::walk_impl_item(self, it);
1656 fn visit_trait_item(&mut self, it: &'tcx TraitItem<'tcx>) {
1657 debug!("find_existential_constraints: visiting {:?}", it);
1658 let def_id = self.tcx.hir().local_def_id(it.hir_id);
1660 intravisit::walk_trait_item(self, it);
1664 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1665 let scope = tcx.hir().get_defining_scope(hir_id);
1666 let mut locator = ConstraintLocator { def_id, tcx, found: None };
1668 debug!("find_opaque_ty_constraints: scope={:?}", scope);
1670 if scope == hir::CRATE_HIR_ID {
1671 intravisit::walk_crate(&mut locator, tcx.hir().krate());
1673 debug!("find_opaque_ty_constraints: scope={:?}", tcx.hir().get(scope));
1674 match tcx.hir().get(scope) {
1675 // We explicitly call `visit_*` methods, instead of using `intravisit::walk_*` methods
1676 // This allows our visitor to process the defining item itself, causing
1677 // it to pick up any 'sibling' defining uses.
1679 // For example, this code:
1682 // type Blah = impl Debug;
1683 // let my_closure = || -> Blah { true };
1687 // requires us to explicitly process `foo()` in order
1688 // to notice the defining usage of `Blah`.
1689 Node::Item(ref it) => locator.visit_item(it),
1690 Node::ImplItem(ref it) => locator.visit_impl_item(it),
1691 Node::TraitItem(ref it) => locator.visit_trait_item(it),
1692 other => bug!("{:?} is not a valid scope for an opaque type item", other),
1696 match locator.found {
1697 Some((_, ty, _)) => ty,
1699 let span = tcx.def_span(def_id);
1700 tcx.sess.span_err(span, "could not find defining uses");
1706 fn is_infer_ty(ty: &hir::Ty<'_>) -> bool {
1708 hir::TyKind::Infer => true,
1709 hir::TyKind::Slice(ty) | hir::TyKind::Array(ty, _) => is_infer_ty(ty),
1710 hir::TyKind::Tup(tys)
1712 && tys.iter().all(|ty| match ty.kind {
1713 hir::TyKind::Infer => true,
1723 pub fn get_infer_ret_ty(output: &'hir hir::FunctionRetTy<'hir>) -> Option<&'hir hir::Ty<'hir>> {
1724 if let hir::FunctionRetTy::Return(ref ty) = output {
1725 if is_infer_ty(ty) {
1732 fn fn_sig(tcx: TyCtxt<'_>, def_id: DefId) -> ty::PolyFnSig<'_> {
1733 use rustc::hir::Node::*;
1736 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1738 let icx = ItemCtxt::new(tcx, def_id);
1740 match tcx.hir().get(hir_id) {
1741 TraitItem(hir::TraitItem {
1742 kind: TraitItemKind::Method(sig, TraitMethod::Provided(_)),
1747 | ImplItem(hir::ImplItem { kind: ImplItemKind::Method(sig, _), ident, generics, .. })
1748 | Item(hir::Item { kind: ItemKind::Fn(sig, generics, _), ident, .. }) => {
1749 match get_infer_ret_ty(&sig.decl.output) {
1751 let fn_sig = tcx.typeck_tables_of(def_id).liberated_fn_sigs()[hir_id];
1752 let mut diag = bad_placeholder_type(tcx, ty.span);
1753 let ret_ty = fn_sig.output();
1754 if ret_ty != tcx.types.err {
1755 diag.span_suggestion(
1757 "replace this with the correct return type",
1759 Applicability::MaybeIncorrect,
1763 ty::Binder::bind(fn_sig)
1765 None => AstConv::ty_of_fn(
1767 sig.header.unsafety,
1770 &generics.params[..],
1776 TraitItem(hir::TraitItem {
1777 kind: TraitItemKind::Method(FnSig { header, decl }, _),
1781 }) => AstConv::ty_of_fn(
1786 &generics.params[..],
1790 ForeignItem(&hir::ForeignItem { kind: ForeignItemKind::Fn(ref fn_decl, _, _), .. }) => {
1791 let abi = tcx.hir().get_foreign_abi(hir_id);
1792 compute_sig_of_foreign_fn_decl(tcx, def_id, fn_decl, abi)
1795 Ctor(data) | Variant(hir::Variant { data, .. }) if data.ctor_hir_id().is_some() => {
1796 let ty = tcx.type_of(tcx.hir().get_parent_did(hir_id));
1798 data.fields().iter().map(|f| tcx.type_of(tcx.hir().local_def_id(f.hir_id)));
1799 ty::Binder::bind(tcx.mk_fn_sig(
1803 hir::Unsafety::Normal,
1808 Expr(&hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => {
1809 // Closure signatures are not like other function
1810 // signatures and cannot be accessed through `fn_sig`. For
1811 // example, a closure signature excludes the `self`
1812 // argument. In any case they are embedded within the
1813 // closure type as part of the `ClosureSubsts`.
1816 // the signature of a closure, you should use the
1817 // `closure_sig` method on the `ClosureSubsts`:
1819 // closure_substs.sig(def_id, tcx)
1821 // or, inside of an inference context, you can use
1823 // infcx.closure_sig(def_id, closure_substs)
1824 bug!("to get the signature of a closure, use `closure_sig()` not `fn_sig()`");
1828 bug!("unexpected sort of node in fn_sig(): {:?}", x);
1833 fn impl_trait_ref(tcx: TyCtxt<'_>, def_id: DefId) -> Option<ty::TraitRef<'_>> {
1834 let icx = ItemCtxt::new(tcx, def_id);
1836 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1837 match tcx.hir().expect_item(hir_id).kind {
1838 hir::ItemKind::Impl(.., ref opt_trait_ref, _, _) => {
1839 opt_trait_ref.as_ref().map(|ast_trait_ref| {
1840 let selfty = tcx.type_of(def_id);
1841 AstConv::instantiate_mono_trait_ref(&icx, ast_trait_ref, selfty)
1848 fn impl_polarity(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ImplPolarity {
1849 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1850 let is_rustc_reservation = tcx.has_attr(def_id, sym::rustc_reservation_impl);
1851 let item = tcx.hir().expect_item(hir_id);
1853 hir::ItemKind::Impl(_, hir::ImplPolarity::Negative, ..) => {
1854 if is_rustc_reservation {
1855 tcx.sess.span_err(item.span, "reservation impls can't be negative");
1857 ty::ImplPolarity::Negative
1859 hir::ItemKind::Impl(_, hir::ImplPolarity::Positive, _, _, None, _, _) => {
1860 if is_rustc_reservation {
1861 tcx.sess.span_err(item.span, "reservation impls can't be inherent");
1863 ty::ImplPolarity::Positive
1865 hir::ItemKind::Impl(_, hir::ImplPolarity::Positive, _, _, Some(_tr), _, _) => {
1866 if is_rustc_reservation {
1867 ty::ImplPolarity::Reservation
1869 ty::ImplPolarity::Positive
1872 ref item => bug!("impl_polarity: {:?} not an impl", item),
1876 /// Returns the early-bound lifetimes declared in this generics
1877 /// listing. For anything other than fns/methods, this is just all
1878 /// the lifetimes that are declared. For fns or methods, we have to
1879 /// screen out those that do not appear in any where-clauses etc using
1880 /// `resolve_lifetime::early_bound_lifetimes`.
1881 fn early_bound_lifetimes_from_generics<'a, 'tcx: 'a>(
1883 generics: &'a hir::Generics<'a>,
1884 ) -> impl Iterator<Item = &'a hir::GenericParam<'a>> + Captures<'tcx> {
1885 generics.params.iter().filter(move |param| match param.kind {
1886 GenericParamKind::Lifetime { .. } => !tcx.is_late_bound(param.hir_id),
1891 /// Returns a list of type predicates for the definition with ID `def_id`, including inferred
1892 /// lifetime constraints. This includes all predicates returned by `explicit_predicates_of`, plus
1893 /// inferred constraints concerning which regions outlive other regions.
1894 fn predicates_defined_on(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1895 debug!("predicates_defined_on({:?})", def_id);
1896 let mut result = tcx.explicit_predicates_of(def_id);
1897 debug!("predicates_defined_on: explicit_predicates_of({:?}) = {:?}", def_id, result,);
1898 let inferred_outlives = tcx.inferred_outlives_of(def_id);
1899 if !inferred_outlives.is_empty() {
1901 "predicates_defined_on: inferred_outlives_of({:?}) = {:?}",
1902 def_id, inferred_outlives,
1904 if result.predicates.is_empty() {
1905 result.predicates = inferred_outlives;
1907 result.predicates = tcx
1909 .alloc_from_iter(result.predicates.iter().chain(inferred_outlives).copied());
1912 debug!("predicates_defined_on({:?}) = {:?}", def_id, result);
1916 /// Returns a list of all type predicates (explicit and implicit) for the definition with
1917 /// ID `def_id`. This includes all predicates returned by `predicates_defined_on`, plus
1918 /// `Self: Trait` predicates for traits.
1919 fn predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1920 let mut result = tcx.predicates_defined_on(def_id);
1922 if tcx.is_trait(def_id) {
1923 // For traits, add `Self: Trait` predicate. This is
1924 // not part of the predicates that a user writes, but it
1925 // is something that one must prove in order to invoke a
1926 // method or project an associated type.
1928 // In the chalk setup, this predicate is not part of the
1929 // "predicates" for a trait item. But it is useful in
1930 // rustc because if you directly (e.g.) invoke a trait
1931 // method like `Trait::method(...)`, you must naturally
1932 // prove that the trait applies to the types that were
1933 // used, and adding the predicate into this list ensures
1934 // that this is done.
1935 let span = tcx.def_span(def_id);
1937 tcx.arena.alloc_from_iter(result.predicates.iter().copied().chain(std::iter::once((
1938 ty::TraitRef::identity(tcx, def_id).to_predicate(),
1942 debug!("predicates_of(def_id={:?}) = {:?}", def_id, result);
1946 /// Returns a list of user-specified type predicates for the definition with ID `def_id`.
1947 /// N.B., this does not include any implied/inferred constraints.
1948 fn explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1950 use rustc_data_structures::fx::FxHashSet;
1952 debug!("explicit_predicates_of(def_id={:?})", def_id);
1954 /// A data structure with unique elements, which preserves order of insertion.
1955 /// Preserving the order of insertion is important here so as not to break
1956 /// compile-fail UI tests.
1957 // FIXME(eddyb) just use `IndexSet` from `indexmap`.
1958 struct UniquePredicates<'tcx> {
1959 predicates: Vec<(ty::Predicate<'tcx>, Span)>,
1960 uniques: FxHashSet<(ty::Predicate<'tcx>, Span)>,
1963 impl<'tcx> UniquePredicates<'tcx> {
1965 UniquePredicates { predicates: vec![], uniques: FxHashSet::default() }
1968 fn push(&mut self, value: (ty::Predicate<'tcx>, Span)) {
1969 if self.uniques.insert(value) {
1970 self.predicates.push(value);
1974 fn extend<I: IntoIterator<Item = (ty::Predicate<'tcx>, Span)>>(&mut self, iter: I) {
1981 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1982 let node = tcx.hir().get(hir_id);
1984 let mut is_trait = None;
1985 let mut is_default_impl_trait = None;
1987 let icx = ItemCtxt::new(tcx, def_id);
1989 const NO_GENERICS: &hir::Generics<'_> = &hir::Generics::empty();
1991 let mut predicates = UniquePredicates::new();
1993 let ast_generics = match node {
1994 Node::TraitItem(item) => &item.generics,
1996 Node::ImplItem(item) => match item.kind {
1997 ImplItemKind::OpaqueTy(ref bounds) => {
1998 ty::print::with_no_queries(|| {
1999 let substs = InternalSubsts::identity_for_item(tcx, def_id);
2000 let opaque_ty = tcx.mk_opaque(def_id, substs);
2002 "explicit_predicates_of({:?}): created opaque type {:?}",
2006 // Collect the bounds, i.e., the `A + B + 'c` in `impl A + B + 'c`.
2007 let bounds = AstConv::compute_bounds(
2011 SizedByDefault::Yes,
2012 tcx.def_span(def_id),
2015 predicates.extend(bounds.predicates(tcx, opaque_ty));
2019 _ => &item.generics,
2022 Node::Item(item) => {
2024 ItemKind::Impl(_, _, defaultness, ref generics, ..) => {
2025 if defaultness.is_default() {
2026 is_default_impl_trait = tcx.impl_trait_ref(def_id);
2030 ItemKind::Fn(.., ref generics, _)
2031 | ItemKind::TyAlias(_, ref generics)
2032 | ItemKind::Enum(_, ref generics)
2033 | ItemKind::Struct(_, ref generics)
2034 | ItemKind::Union(_, ref generics) => generics,
2036 ItemKind::Trait(_, _, ref generics, .., items) => {
2037 is_trait = Some((ty::TraitRef::identity(tcx, def_id), items));
2040 ItemKind::TraitAlias(ref generics, _) => {
2041 is_trait = Some((ty::TraitRef::identity(tcx, def_id), &[]));
2044 ItemKind::OpaqueTy(OpaqueTy {
2050 let bounds_predicates = ty::print::with_no_queries(|| {
2051 let substs = InternalSubsts::identity_for_item(tcx, def_id);
2052 let opaque_ty = tcx.mk_opaque(def_id, substs);
2054 // Collect the bounds, i.e., the `A + B + 'c` in `impl A + B + 'c`.
2055 let bounds = AstConv::compute_bounds(
2059 SizedByDefault::Yes,
2060 tcx.def_span(def_id),
2063 bounds.predicates(tcx, opaque_ty)
2065 if impl_trait_fn.is_some() {
2067 return ty::GenericPredicates {
2069 predicates: tcx.arena.alloc_from_iter(bounds_predicates),
2072 // named opaque types
2073 predicates.extend(bounds_predicates);
2082 Node::ForeignItem(item) => match item.kind {
2083 ForeignItemKind::Static(..) => NO_GENERICS,
2084 ForeignItemKind::Fn(_, _, ref generics) => generics,
2085 ForeignItemKind::Type => NO_GENERICS,
2091 let generics = tcx.generics_of(def_id);
2092 let parent_count = generics.parent_count as u32;
2093 let has_own_self = generics.has_self && parent_count == 0;
2095 // Below we'll consider the bounds on the type parameters (including `Self`)
2096 // and the explicit where-clauses, but to get the full set of predicates
2097 // on a trait we need to add in the supertrait bounds and bounds found on
2098 // associated types.
2099 if let Some((_trait_ref, _)) = is_trait {
2100 predicates.extend(tcx.super_predicates_of(def_id).predicates.iter().cloned());
2103 // In default impls, we can assume that the self type implements
2104 // the trait. So in:
2106 // default impl Foo for Bar { .. }
2108 // we add a default where clause `Foo: Bar`. We do a similar thing for traits
2109 // (see below). Recall that a default impl is not itself an impl, but rather a
2110 // set of defaults that can be incorporated into another impl.
2111 if let Some(trait_ref) = is_default_impl_trait {
2112 predicates.push((trait_ref.to_poly_trait_ref().to_predicate(), tcx.def_span(def_id)));
2115 // Collect the region predicates that were declared inline as
2116 // well. In the case of parameters declared on a fn or method, we
2117 // have to be careful to only iterate over early-bound regions.
2118 let mut index = parent_count + has_own_self as u32;
2119 for param in early_bound_lifetimes_from_generics(tcx, ast_generics) {
2120 let region = tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
2121 def_id: tcx.hir().local_def_id(param.hir_id),
2123 name: param.name.ident().name,
2128 GenericParamKind::Lifetime { .. } => {
2129 param.bounds.iter().for_each(|bound| match bound {
2130 hir::GenericBound::Outlives(lt) => {
2131 let bound = AstConv::ast_region_to_region(&icx, <, None);
2132 let outlives = ty::Binder::bind(ty::OutlivesPredicate(region, bound));
2133 predicates.push((outlives.to_predicate(), lt.span));
2142 // Collect the predicates that were written inline by the user on each
2143 // type parameter (e.g., `<T: Foo>`).
2144 for param in &ast_generics.params {
2145 if let GenericParamKind::Type { .. } = param.kind {
2146 let name = param.name.ident().name;
2147 let param_ty = ty::ParamTy::new(index, name).to_ty(tcx);
2150 let sized = SizedByDefault::Yes;
2151 let bounds = AstConv::compute_bounds(&icx, param_ty, ¶m.bounds, sized, param.span);
2152 predicates.extend(bounds.predicates(tcx, param_ty));
2156 // Add in the bounds that appear in the where-clause.
2157 let where_clause = &ast_generics.where_clause;
2158 for predicate in where_clause.predicates {
2160 &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
2161 let ty = icx.to_ty(&bound_pred.bounded_ty);
2163 // Keep the type around in a dummy predicate, in case of no bounds.
2164 // That way, `where Ty:` is not a complete noop (see #53696) and `Ty`
2165 // is still checked for WF.
2166 if bound_pred.bounds.is_empty() {
2167 if let ty::Param(_) = ty.kind {
2168 // This is a `where T:`, which can be in the HIR from the
2169 // transformation that moves `?Sized` to `T`'s declaration.
2170 // We can skip the predicate because type parameters are
2171 // trivially WF, but also we *should*, to avoid exposing
2172 // users who never wrote `where Type:,` themselves, to
2173 // compiler/tooling bugs from not handling WF predicates.
2175 let span = bound_pred.bounded_ty.span;
2176 let predicate = ty::OutlivesPredicate(ty, tcx.mk_region(ty::ReEmpty));
2178 ty::Predicate::TypeOutlives(ty::Binder::dummy(predicate)),
2184 for bound in bound_pred.bounds.iter() {
2186 &hir::GenericBound::Trait(ref poly_trait_ref, _) => {
2187 let mut bounds = Bounds::default();
2188 let _ = AstConv::instantiate_poly_trait_ref(
2194 predicates.extend(bounds.predicates(tcx, ty));
2197 &hir::GenericBound::Outlives(ref lifetime) => {
2198 let region = AstConv::ast_region_to_region(&icx, lifetime, None);
2199 let pred = ty::Binder::bind(ty::OutlivesPredicate(ty, region));
2200 predicates.push((ty::Predicate::TypeOutlives(pred), lifetime.span))
2206 &hir::WherePredicate::RegionPredicate(ref region_pred) => {
2207 let r1 = AstConv::ast_region_to_region(&icx, ®ion_pred.lifetime, None);
2208 predicates.extend(region_pred.bounds.iter().map(|bound| {
2209 let (r2, span) = match bound {
2210 hir::GenericBound::Outlives(lt) => {
2211 (AstConv::ast_region_to_region(&icx, lt, None), lt.span)
2215 let pred = ty::Binder::bind(ty::OutlivesPredicate(r1, r2));
2217 (ty::Predicate::RegionOutlives(pred), span)
2221 &hir::WherePredicate::EqPredicate(..) => {
2227 // Add predicates from associated type bounds.
2228 if let Some((self_trait_ref, trait_items)) = is_trait {
2229 predicates.extend(trait_items.iter().flat_map(|trait_item_ref| {
2230 associated_item_predicates(tcx, def_id, self_trait_ref, trait_item_ref)
2234 let mut predicates = predicates.predicates;
2236 // Subtle: before we store the predicates into the tcx, we
2237 // sort them so that predicates like `T: Foo<Item=U>` come
2238 // before uses of `U`. This avoids false ambiguity errors
2239 // in trait checking. See `setup_constraining_predicates`
2241 if let Node::Item(&Item { kind: ItemKind::Impl(..), .. }) = node {
2242 let self_ty = tcx.type_of(def_id);
2243 let trait_ref = tcx.impl_trait_ref(def_id);
2244 cgp::setup_constraining_predicates(
2248 &mut cgp::parameters_for_impl(self_ty, trait_ref),
2252 let result = ty::GenericPredicates {
2253 parent: generics.parent,
2254 predicates: tcx.arena.alloc_from_iter(predicates),
2256 debug!("explicit_predicates_of(def_id={:?}) = {:?}", def_id, result);
2260 fn associated_item_predicates(
2263 self_trait_ref: ty::TraitRef<'tcx>,
2264 trait_item_ref: &hir::TraitItemRef,
2265 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2266 let trait_item = tcx.hir().trait_item(trait_item_ref.id);
2267 let item_def_id = tcx.hir().local_def_id(trait_item_ref.id.hir_id);
2268 let bounds = match trait_item.kind {
2269 hir::TraitItemKind::Type(ref bounds, _) => bounds,
2270 _ => return Vec::new(),
2273 let is_gat = !tcx.generics_of(item_def_id).params.is_empty();
2275 let mut had_error = false;
2277 let mut unimplemented_error = |arg_kind: &str| {
2282 &format!("{}-generic associated types are not yet implemented", arg_kind),
2284 .note("for more information, see https://github.com/rust-lang/rust/issues/44265")
2290 let mk_bound_param = |param: &ty::GenericParamDef, _: &_| {
2292 ty::GenericParamDefKind::Lifetime => tcx
2293 .mk_region(ty::RegionKind::ReLateBound(
2295 ty::BoundRegion::BrNamed(param.def_id, param.name),
2298 // FIXME(generic_associated_types): Use bound types and constants
2299 // once they are handled by the trait system.
2300 ty::GenericParamDefKind::Type { .. } => {
2301 unimplemented_error("type");
2302 tcx.types.err.into()
2304 ty::GenericParamDefKind::Const => {
2305 unimplemented_error("const");
2306 tcx.consts.err.into()
2311 let bound_substs = if is_gat {
2314 // trait X<'a, B, const C: usize> {
2315 // type T<'d, E, const F: usize>: Default;
2318 // We need to create predicates on the trait:
2320 // for<'d, E, const F: usize>
2321 // <Self as X<'a, B, const C: usize>>::T<'d, E, const F: usize>: Sized + Default
2323 // We substitute escaping bound parameters for the generic
2324 // arguments to the associated type which are then bound by
2325 // the `Binder` around the the predicate.
2327 // FIXME(generic_associated_types): Currently only lifetimes are handled.
2328 self_trait_ref.substs.extend_to(tcx, item_def_id, mk_bound_param)
2330 self_trait_ref.substs
2333 let assoc_ty = tcx.mk_projection(tcx.hir().local_def_id(trait_item.hir_id), bound_substs);
2335 let bounds = AstConv::compute_bounds(
2336 &ItemCtxt::new(tcx, def_id),
2339 SizedByDefault::Yes,
2343 let predicates = bounds.predicates(tcx, assoc_ty);
2346 // We use shifts to get the regions that we're substituting to
2347 // be bound by the binders in the `Predicate`s rather that
2349 let shifted_in = ty::fold::shift_vars(tcx, &predicates, 1);
2350 let substituted = shifted_in.subst(tcx, bound_substs);
2351 ty::fold::shift_out_vars(tcx, &substituted, 1)
2357 /// Converts a specific `GenericBound` from the AST into a set of
2358 /// predicates that apply to the self type. A vector is returned
2359 /// because this can be anywhere from zero predicates (`T: ?Sized` adds no
2360 /// predicates) to one (`T: Foo`) to many (`T: Bar<X = i32>` adds `T: Bar`
2361 /// and `<T as Bar>::X == i32`).
2362 fn predicates_from_bound<'tcx>(
2363 astconv: &dyn AstConv<'tcx>,
2365 bound: &'tcx hir::GenericBound<'tcx>,
2366 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2368 hir::GenericBound::Trait(ref tr, hir::TraitBoundModifier::None) => {
2369 let mut bounds = Bounds::default();
2370 let _ = astconv.instantiate_poly_trait_ref(tr, param_ty, &mut bounds);
2371 bounds.predicates(astconv.tcx(), param_ty)
2373 hir::GenericBound::Outlives(ref lifetime) => {
2374 let region = astconv.ast_region_to_region(lifetime, None);
2375 let pred = ty::Binder::bind(ty::OutlivesPredicate(param_ty, region));
2376 vec![(ty::Predicate::TypeOutlives(pred), lifetime.span)]
2378 hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => vec![],
2382 fn compute_sig_of_foreign_fn_decl<'tcx>(
2385 decl: &'tcx hir::FnDecl<'tcx>,
2387 ) -> ty::PolyFnSig<'tcx> {
2388 let unsafety = if abi == abi::Abi::RustIntrinsic {
2389 intrinsic_operation_unsafety(&tcx.item_name(def_id).as_str())
2391 hir::Unsafety::Unsafe
2393 let fty = AstConv::ty_of_fn(&ItemCtxt::new(tcx, def_id), unsafety, abi, decl, &[], None);
2395 // Feature gate SIMD types in FFI, since I am not sure that the
2396 // ABIs are handled at all correctly. -huonw
2397 if abi != abi::Abi::RustIntrinsic
2398 && abi != abi::Abi::PlatformIntrinsic
2399 && !tcx.features().simd_ffi
2401 let check = |ast_ty: &hir::Ty<'_>, ty: Ty<'_>| {
2407 "use of SIMD type `{}` in FFI is highly experimental and \
2408 may result in invalid code",
2409 tcx.hir().hir_to_pretty_string(ast_ty.hir_id)
2412 .help("add `#![feature(simd_ffi)]` to the crate attributes to enable")
2416 for (input, ty) in decl.inputs.iter().zip(*fty.inputs().skip_binder()) {
2419 if let hir::Return(ref ty) = decl.output {
2420 check(&ty, *fty.output().skip_binder())
2427 fn is_foreign_item(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
2428 match tcx.hir().get_if_local(def_id) {
2429 Some(Node::ForeignItem(..)) => true,
2431 _ => bug!("is_foreign_item applied to non-local def-id {:?}", def_id),
2435 fn static_mutability(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::Mutability> {
2436 match tcx.hir().get_if_local(def_id) {
2437 Some(Node::Item(&hir::Item { kind: hir::ItemKind::Static(_, mutbl, _), .. }))
2438 | Some(Node::ForeignItem(&hir::ForeignItem {
2439 kind: hir::ForeignItemKind::Static(_, mutbl),
2443 _ => bug!("static_mutability applied to non-local def-id {:?}", def_id),
2447 fn from_target_feature(
2450 attr: &ast::Attribute,
2451 whitelist: &FxHashMap<String, Option<Symbol>>,
2452 target_features: &mut Vec<Symbol>,
2454 let list = match attr.meta_item_list() {
2458 let bad_item = |span| {
2459 let msg = "malformed `target_feature` attribute input";
2460 let code = "enable = \"..\"".to_owned();
2462 .struct_span_err(span, &msg)
2463 .span_suggestion(span, "must be of the form", code, Applicability::HasPlaceholders)
2466 let rust_features = tcx.features();
2468 // Only `enable = ...` is accepted in the meta-item list.
2469 if !item.check_name(sym::enable) {
2470 bad_item(item.span());
2474 // Must be of the form `enable = "..."` (a string).
2475 let value = match item.value_str() {
2476 Some(value) => value,
2478 bad_item(item.span());
2483 // We allow comma separation to enable multiple features.
2484 target_features.extend(value.as_str().split(',').filter_map(|feature| {
2485 // Only allow whitelisted features per platform.
2486 let feature_gate = match whitelist.get(feature) {
2490 format!("the feature named `{}` is not valid for this target", feature);
2491 let mut err = tcx.sess.struct_span_err(item.span(), &msg);
2494 format!("`{}` is not valid for this target", feature),
2496 if feature.starts_with("+") {
2497 let valid = whitelist.contains_key(&feature[1..]);
2499 err.help("consider removing the leading `+` in the feature name");
2507 // Only allow features whose feature gates have been enabled.
2508 let allowed = match feature_gate.as_ref().map(|s| *s) {
2509 Some(sym::arm_target_feature) => rust_features.arm_target_feature,
2510 Some(sym::aarch64_target_feature) => rust_features.aarch64_target_feature,
2511 Some(sym::hexagon_target_feature) => rust_features.hexagon_target_feature,
2512 Some(sym::powerpc_target_feature) => rust_features.powerpc_target_feature,
2513 Some(sym::mips_target_feature) => rust_features.mips_target_feature,
2514 Some(sym::avx512_target_feature) => rust_features.avx512_target_feature,
2515 Some(sym::mmx_target_feature) => rust_features.mmx_target_feature,
2516 Some(sym::sse4a_target_feature) => rust_features.sse4a_target_feature,
2517 Some(sym::tbm_target_feature) => rust_features.tbm_target_feature,
2518 Some(sym::wasm_target_feature) => rust_features.wasm_target_feature,
2519 Some(sym::cmpxchg16b_target_feature) => rust_features.cmpxchg16b_target_feature,
2520 Some(sym::adx_target_feature) => rust_features.adx_target_feature,
2521 Some(sym::movbe_target_feature) => rust_features.movbe_target_feature,
2522 Some(sym::rtm_target_feature) => rust_features.rtm_target_feature,
2523 Some(sym::f16c_target_feature) => rust_features.f16c_target_feature,
2524 Some(name) => bug!("unknown target feature gate {}", name),
2527 if !allowed && id.is_local() {
2528 feature_gate::feature_err(
2529 &tcx.sess.parse_sess,
2530 feature_gate.unwrap(),
2532 &format!("the target feature `{}` is currently unstable", feature),
2536 Some(Symbol::intern(feature))
2541 fn linkage_by_name(tcx: TyCtxt<'_>, def_id: DefId, name: &str) -> Linkage {
2542 use rustc::mir::mono::Linkage::*;
2544 // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
2545 // applicable to variable declarations and may not really make sense for
2546 // Rust code in the first place but whitelist them anyway and trust that
2547 // the user knows what s/he's doing. Who knows, unanticipated use cases
2548 // may pop up in the future.
2550 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
2551 // and don't have to be, LLVM treats them as no-ops.
2553 "appending" => Appending,
2554 "available_externally" => AvailableExternally,
2556 "extern_weak" => ExternalWeak,
2557 "external" => External,
2558 "internal" => Internal,
2559 "linkonce" => LinkOnceAny,
2560 "linkonce_odr" => LinkOnceODR,
2561 "private" => Private,
2563 "weak_odr" => WeakODR,
2565 let span = tcx.hir().span_if_local(def_id);
2566 if let Some(span) = span {
2567 tcx.sess.span_fatal(span, "invalid linkage specified")
2569 tcx.sess.fatal(&format!("invalid linkage specified: {}", name))
2575 fn codegen_fn_attrs(tcx: TyCtxt<'_>, id: DefId) -> CodegenFnAttrs {
2576 let attrs = tcx.get_attrs(id);
2578 let mut codegen_fn_attrs = CodegenFnAttrs::new();
2580 let whitelist = tcx.target_features_whitelist(LOCAL_CRATE);
2582 let mut inline_span = None;
2583 let mut link_ordinal_span = None;
2584 for attr in attrs.iter() {
2585 if attr.check_name(sym::cold) {
2586 codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD;
2587 } else if attr.check_name(sym::rustc_allocator) {
2588 codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR;
2589 } else if attr.check_name(sym::unwind) {
2590 codegen_fn_attrs.flags |= CodegenFnAttrFlags::UNWIND;
2591 } else if attr.check_name(sym::ffi_returns_twice) {
2592 if tcx.is_foreign_item(id) {
2593 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_RETURNS_TWICE;
2595 // `#[ffi_returns_twice]` is only allowed `extern fn`s.
2600 "`#[ffi_returns_twice]` may only be used on foreign functions"
2604 } else if attr.check_name(sym::rustc_allocator_nounwind) {
2605 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND;
2606 } else if attr.check_name(sym::naked) {
2607 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED;
2608 } else if attr.check_name(sym::no_mangle) {
2609 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2610 } else if attr.check_name(sym::rustc_std_internal_symbol) {
2611 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2612 } else if attr.check_name(sym::no_debug) {
2613 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_DEBUG;
2614 } else if attr.check_name(sym::used) {
2615 codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED;
2616 } else if attr.check_name(sym::thread_local) {
2617 codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL;
2618 } else if attr.check_name(sym::track_caller) {
2619 if tcx.fn_sig(id).abi() != abi::Abi::Rust {
2620 struct_span_err!(tcx.sess, attr.span, E0737, "`#[track_caller]` requires Rust ABI")
2623 codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
2624 } else if attr.check_name(sym::export_name) {
2625 if let Some(s) = attr.value_str() {
2626 if s.as_str().contains("\0") {
2627 // `#[export_name = ...]` will be converted to a null-terminated string,
2628 // so it may not contain any null characters.
2633 "`export_name` may not contain null characters"
2637 codegen_fn_attrs.export_name = Some(s);
2639 } else if attr.check_name(sym::target_feature) {
2640 if tcx.fn_sig(id).unsafety() == Unsafety::Normal {
2641 let msg = "`#[target_feature(..)]` can only be applied to `unsafe` functions";
2643 .struct_span_err(attr.span, msg)
2644 .span_label(attr.span, "can only be applied to `unsafe` functions")
2645 .span_label(tcx.def_span(id), "not an `unsafe` function")
2648 from_target_feature(tcx, id, attr, &whitelist, &mut codegen_fn_attrs.target_features);
2649 } else if attr.check_name(sym::linkage) {
2650 if let Some(val) = attr.value_str() {
2651 codegen_fn_attrs.linkage = Some(linkage_by_name(tcx, id, &val.as_str()));
2653 } else if attr.check_name(sym::link_section) {
2654 if let Some(val) = attr.value_str() {
2655 if val.as_str().bytes().any(|b| b == 0) {
2657 "illegal null byte in link_section \
2661 tcx.sess.span_err(attr.span, &msg);
2663 codegen_fn_attrs.link_section = Some(val);
2666 } else if attr.check_name(sym::link_name) {
2667 codegen_fn_attrs.link_name = attr.value_str();
2668 } else if attr.check_name(sym::link_ordinal) {
2669 link_ordinal_span = Some(attr.span);
2670 if let ordinal @ Some(_) = check_link_ordinal(tcx, attr) {
2671 codegen_fn_attrs.link_ordinal = ordinal;
2676 codegen_fn_attrs.inline = attrs.iter().fold(InlineAttr::None, |ia, attr| {
2677 if !attr.has_name(sym::inline) {
2680 match attr.meta().map(|i| i.kind) {
2681 Some(MetaItemKind::Word) => {
2685 Some(MetaItemKind::List(ref items)) => {
2687 inline_span = Some(attr.span);
2688 if items.len() != 1 {
2689 span_err!(tcx.sess.diagnostic(), attr.span, E0534, "expected one argument");
2691 } else if list_contains_name(&items[..], sym::always) {
2693 } else if list_contains_name(&items[..], sym::never) {
2696 span_err!(tcx.sess.diagnostic(), items[0].span(), E0535, "invalid argument");
2701 Some(MetaItemKind::NameValue(_)) => ia,
2706 codegen_fn_attrs.optimize = attrs.iter().fold(OptimizeAttr::None, |ia, attr| {
2707 if !attr.has_name(sym::optimize) {
2710 let err = |sp, s| span_err!(tcx.sess.diagnostic(), sp, E0722, "{}", s);
2711 match attr.meta().map(|i| i.kind) {
2712 Some(MetaItemKind::Word) => {
2713 err(attr.span, "expected one argument");
2716 Some(MetaItemKind::List(ref items)) => {
2718 inline_span = Some(attr.span);
2719 if items.len() != 1 {
2720 err(attr.span, "expected one argument");
2722 } else if list_contains_name(&items[..], sym::size) {
2724 } else if list_contains_name(&items[..], sym::speed) {
2727 err(items[0].span(), "invalid argument");
2731 Some(MetaItemKind::NameValue(_)) => ia,
2736 // If a function uses #[target_feature] it can't be inlined into general
2737 // purpose functions as they wouldn't have the right target features
2738 // enabled. For that reason we also forbid #[inline(always)] as it can't be
2741 if codegen_fn_attrs.target_features.len() > 0 {
2742 if codegen_fn_attrs.inline == InlineAttr::Always {
2743 if let Some(span) = inline_span {
2746 "cannot use `#[inline(always)]` with \
2747 `#[target_feature]`",
2753 // Weak lang items have the same semantics as "std internal" symbols in the
2754 // sense that they're preserved through all our LTO passes and only
2755 // strippable by the linker.
2757 // Additionally weak lang items have predetermined symbol names.
2758 if tcx.is_weak_lang_item(id) {
2759 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2761 if let Some(name) = weak_lang_items::link_name(&attrs) {
2762 codegen_fn_attrs.export_name = Some(name);
2763 codegen_fn_attrs.link_name = Some(name);
2765 check_link_name_xor_ordinal(tcx, &codegen_fn_attrs, link_ordinal_span);
2767 // Internal symbols to the standard library all have no_mangle semantics in
2768 // that they have defined symbol names present in the function name. This
2769 // also applies to weak symbols where they all have known symbol names.
2770 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
2771 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2777 fn check_link_ordinal(tcx: TyCtxt<'_>, attr: &ast::Attribute) -> Option<usize> {
2778 use syntax::ast::{Lit, LitIntType, LitKind};
2779 let meta_item_list = attr.meta_item_list();
2780 let meta_item_list: Option<&[ast::NestedMetaItem]> = meta_item_list.as_ref().map(Vec::as_ref);
2781 let sole_meta_list = match meta_item_list {
2782 Some([item]) => item.literal(),
2785 if let Some(Lit { kind: LitKind::Int(ordinal, LitIntType::Unsuffixed), .. }) = sole_meta_list {
2786 if *ordinal <= std::usize::MAX as u128 {
2787 Some(*ordinal as usize)
2789 let msg = format!("ordinal value in `link_ordinal` is too large: `{}`", &ordinal);
2791 .struct_span_err(attr.span, &msg)
2792 .note("the value may not exceed `std::usize::MAX`")
2798 .struct_span_err(attr.span, "illegal ordinal format in `link_ordinal`")
2799 .note("an unsuffixed integer value, e.g., `1`, is expected")
2805 fn check_link_name_xor_ordinal(
2807 codegen_fn_attrs: &CodegenFnAttrs,
2808 inline_span: Option<Span>,
2810 if codegen_fn_attrs.link_name.is_none() || codegen_fn_attrs.link_ordinal.is_none() {
2813 let msg = "cannot use `#[link_name]` with `#[link_ordinal]`";
2814 if let Some(span) = inline_span {
2815 tcx.sess.span_err(span, msg);