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::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
24 use rustc::mir::mono::Linkage;
25 use rustc::ty::query::Providers;
26 use rustc::ty::subst::GenericArgKind;
27 use rustc::ty::subst::{InternalSubsts, Subst};
28 use rustc::ty::util::Discr;
29 use rustc::ty::util::IntTypeExt;
30 use rustc::ty::{self, AdtKind, Const, DefIdTree, ToPolyTraitRef, Ty, TyCtxt};
31 use rustc::ty::{ReprOptions, ToPredicate};
32 use rustc::util::captures::Captures;
33 use rustc_data_structures::fx::FxHashMap;
34 use rustc_target::spec::abi;
36 use rustc_span::symbol::{kw, sym, Symbol};
37 use rustc_span::{Span, DUMMY_SP};
39 use syntax::ast::{Ident, MetaItemKind};
40 use syntax::attr::{list_contains_name, mark_used, InlineAttr, OptimizeAttr};
41 use syntax::feature_gate;
43 use rustc::hir::def::{CtorKind, DefKind, Res};
44 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
45 use rustc::hir::intravisit::{self, NestedVisitorMap, Visitor};
46 use rustc::hir::GenericParamKind;
48 use rustc::hir::{self, Unsafety};
50 use errors::{Applicability, StashKey};
52 use rustc_error_codes::*;
54 struct OnlySelfBounds(bool);
56 ///////////////////////////////////////////////////////////////////////////
59 fn collect_mod_item_types(tcx: TyCtxt<'_>, module_def_id: DefId) {
60 tcx.hir().visit_item_likes_in_module(
62 &mut CollectItemTypesVisitor { tcx }.as_deep_visitor(),
66 pub fn provide(providers: &mut Providers<'_>) {
67 *providers = Providers {
71 predicates_defined_on,
72 explicit_predicates_of,
74 type_param_predicates,
83 collect_mod_item_types,
88 ///////////////////////////////////////////////////////////////////////////
90 /// Context specific to some particular item. This is what implements
91 /// `AstConv`. It has information about the predicates that are defined
92 /// on the trait. Unfortunately, this predicate information is
93 /// available in various different forms at various points in the
94 /// process. So we can't just store a pointer to e.g., the AST or the
95 /// parsed ty form, we have to be more flexible. To this end, the
96 /// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy
97 /// `get_type_parameter_bounds` requests, drawing the information from
98 /// the AST (`hir::Generics`), recursively.
99 pub struct ItemCtxt<'tcx> {
104 ///////////////////////////////////////////////////////////////////////////
107 crate struct PlaceholderHirTyCollector(crate Vec<Span>);
109 impl<'v> Visitor<'v> for PlaceholderHirTyCollector {
110 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
111 NestedVisitorMap::None
113 fn visit_ty(&mut self, t: &'v hir::Ty<'v>) {
114 if let hir::TyKind::Infer = t.kind {
117 hir::intravisit::walk_ty(self, t)
121 struct CollectItemTypesVisitor<'tcx> {
125 /// If there are any placeholder types (`_`), emit an error explaining that this is not allowed
126 /// and suggest adding type parameters in the appropriate place, taking into consideration any and
127 /// all already existing generic type parameters to avoid suggesting a name that is already in use.
128 crate fn placeholder_type_error(
131 generics: &[hir::GenericParam<'_>],
132 placeholder_types: Vec<Span>,
135 if placeholder_types.is_empty() {
138 // This is the whitelist of possible parameter names that we might suggest.
139 let possible_names = ["T", "K", "L", "A", "B", "C"];
140 let used_names = generics
142 .filter_map(|p| match p.name {
143 hir::ParamName::Plain(ident) => Some(ident.name),
146 .collect::<Vec<_>>();
148 let type_name = possible_names
150 .find(|n| !used_names.contains(&Symbol::intern(n)))
151 .unwrap_or(&"ParamName");
153 let mut sugg: Vec<_> =
154 placeholder_types.iter().map(|sp| (*sp, type_name.to_string())).collect();
155 if generics.is_empty() {
156 sugg.push((ident_span.shrink_to_hi(), format!("<{}>", type_name)));
159 generics.iter().last().unwrap().span.shrink_to_hi(),
160 format!(", {}", type_name),
163 let mut err = bad_placeholder_type(tcx, placeholder_types);
165 err.multipart_suggestion(
166 "use type parameters instead",
168 Applicability::HasPlaceholders,
174 fn reject_placeholder_type_signatures_in_item(tcx: TyCtxt<'tcx>, item: &'tcx hir::Item<'tcx>) {
175 let (generics, suggest) = match &item.kind {
176 hir::ItemKind::Union(_, generics)
177 | hir::ItemKind::Enum(_, generics)
178 | hir::ItemKind::Struct(_, generics) => (&generics.params[..], true),
179 hir::ItemKind::TyAlias(_, generics) => (&generics.params[..], false),
180 // `static`, `fn` and `const` are handled elsewhere to suggest appropriate type.
184 let mut visitor = PlaceholderHirTyCollector::default();
185 visitor.visit_item(item);
187 placeholder_type_error(tcx, item.ident.span, generics, visitor.0, suggest);
190 impl Visitor<'tcx> for CollectItemTypesVisitor<'tcx> {
191 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
192 NestedVisitorMap::OnlyBodies(&self.tcx.hir())
195 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
196 convert_item(self.tcx, item.hir_id);
197 reject_placeholder_type_signatures_in_item(self.tcx, item);
198 intravisit::walk_item(self, item);
201 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
202 for param in generics.params {
204 hir::GenericParamKind::Lifetime { .. } => {}
205 hir::GenericParamKind::Type { default: Some(_), .. } => {
206 let def_id = self.tcx.hir().local_def_id(param.hir_id);
207 self.tcx.type_of(def_id);
209 hir::GenericParamKind::Type { .. } => {}
210 hir::GenericParamKind::Const { .. } => {
211 let def_id = self.tcx.hir().local_def_id(param.hir_id);
212 self.tcx.type_of(def_id);
216 intravisit::walk_generics(self, generics);
219 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
220 if let hir::ExprKind::Closure(..) = expr.kind {
221 let def_id = self.tcx.hir().local_def_id(expr.hir_id);
222 self.tcx.generics_of(def_id);
223 self.tcx.type_of(def_id);
225 intravisit::walk_expr(self, expr);
228 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
229 convert_trait_item(self.tcx, trait_item.hir_id);
230 intravisit::walk_trait_item(self, trait_item);
233 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
234 convert_impl_item(self.tcx, impl_item.hir_id);
235 intravisit::walk_impl_item(self, impl_item);
239 ///////////////////////////////////////////////////////////////////////////
240 // Utility types and common code for the above passes.
242 fn bad_placeholder_type(
244 mut spans: Vec<Span>,
245 ) -> errors::DiagnosticBuilder<'tcx> {
247 let mut err = struct_span_err!(
251 "the type placeholder `_` is not allowed within types on item signatures",
254 err.span_label(span, "not allowed in type signatures");
259 impl ItemCtxt<'tcx> {
260 pub fn new(tcx: TyCtxt<'tcx>, item_def_id: DefId) -> ItemCtxt<'tcx> {
261 ItemCtxt { tcx, item_def_id }
264 pub fn to_ty(&self, ast_ty: &'tcx hir::Ty<'tcx>) -> Ty<'tcx> {
265 AstConv::ast_ty_to_ty(self, ast_ty)
269 impl AstConv<'tcx> for ItemCtxt<'tcx> {
270 fn tcx(&self) -> TyCtxt<'tcx> {
274 fn item_def_id(&self) -> Option<DefId> {
275 Some(self.item_def_id)
278 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId) -> ty::GenericPredicates<'tcx> {
279 self.tcx.at(span).type_param_predicates((self.item_def_id, def_id))
282 fn re_infer(&self, _: Option<&ty::GenericParamDef>, _: Span) -> Option<ty::Region<'tcx>> {
286 fn allow_ty_infer(&self) -> bool {
290 fn ty_infer(&self, _: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx> {
291 self.tcx().sess.delay_span_bug(span, "bad placeholder type");
298 _: Option<&ty::GenericParamDef>,
300 ) -> &'tcx Const<'tcx> {
301 bad_placeholder_type(self.tcx(), vec![span]).emit();
303 self.tcx().consts.err
306 fn projected_ty_from_poly_trait_ref(
310 item_segment: &hir::PathSegment<'_>,
311 poly_trait_ref: ty::PolyTraitRef<'tcx>,
313 if let Some(trait_ref) = poly_trait_ref.no_bound_vars() {
314 let item_substs = <dyn AstConv<'tcx>>::create_substs_for_associated_item(
322 self.tcx().mk_projection(item_def_id, item_substs)
324 // There are no late-bound regions; we can just ignore the binder.
329 "cannot extract an associated type from a higher-ranked trait bound \
336 fn normalize_ty(&self, _span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
337 // Types in item signatures are not normalized to avoid undue dependencies.
341 fn set_tainted_by_errors(&self) {
342 // There's no obvious place to track this, so just let it go.
345 fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) {
346 // There's no place to record types from signatures?
350 /// Returns the predicates defined on `item_def_id` of the form
351 /// `X: Foo` where `X` is the type parameter `def_id`.
352 fn type_param_predicates(
354 (item_def_id, def_id): (DefId, DefId),
355 ) -> ty::GenericPredicates<'_> {
358 // In the AST, bounds can derive from two places. Either
359 // written inline like `<T: Foo>` or in a where-clause like
362 let param_id = tcx.hir().as_local_hir_id(def_id).unwrap();
363 let param_owner = tcx.hir().ty_param_owner(param_id);
364 let param_owner_def_id = tcx.hir().local_def_id(param_owner);
365 let generics = tcx.generics_of(param_owner_def_id);
366 let index = generics.param_def_id_to_index[&def_id];
367 let ty = tcx.mk_ty_param(index, tcx.hir().ty_param_name(param_id));
369 // Don't look for bounds where the type parameter isn't in scope.
371 if item_def_id == param_owner_def_id { None } else { tcx.generics_of(item_def_id).parent };
373 let mut result = parent
375 let icx = ItemCtxt::new(tcx, parent);
376 icx.get_type_parameter_bounds(DUMMY_SP, def_id)
378 .unwrap_or_default();
379 let mut extend = None;
381 let item_hir_id = tcx.hir().as_local_hir_id(item_def_id).unwrap();
382 let ast_generics = match tcx.hir().get(item_hir_id) {
383 Node::TraitItem(item) => &item.generics,
385 Node::ImplItem(item) => &item.generics,
387 Node::Item(item) => {
389 ItemKind::Fn(.., ref generics, _)
390 | ItemKind::Impl(_, _, _, ref generics, ..)
391 | ItemKind::TyAlias(_, ref generics)
392 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
393 | ItemKind::Enum(_, ref generics)
394 | ItemKind::Struct(_, ref generics)
395 | ItemKind::Union(_, ref generics) => generics,
396 ItemKind::Trait(_, _, ref generics, ..) => {
397 // Implied `Self: Trait` and supertrait bounds.
398 if param_id == item_hir_id {
399 let identity_trait_ref = ty::TraitRef::identity(tcx, item_def_id);
400 extend = Some((identity_trait_ref.to_predicate(), item.span));
408 Node::ForeignItem(item) => match item.kind {
409 ForeignItemKind::Fn(_, _, ref generics) => generics,
416 let icx = ItemCtxt::new(tcx, item_def_id);
417 let extra_predicates = extend.into_iter().chain(
418 icx.type_parameter_bounds_in_generics(ast_generics, param_id, ty, OnlySelfBounds(true))
420 .filter(|(predicate, _)| match predicate {
421 ty::Predicate::Trait(ref data) => data.skip_binder().self_ty().is_param(index),
426 tcx.arena.alloc_from_iter(result.predicates.iter().copied().chain(extra_predicates));
430 impl ItemCtxt<'tcx> {
431 /// Finds bounds from `hir::Generics`. This requires scanning through the
432 /// AST. We do this to avoid having to convert *all* the bounds, which
433 /// would create artificial cycles. Instead, we can only convert the
434 /// bounds for a type parameter `X` if `X::Foo` is used.
435 fn type_parameter_bounds_in_generics(
437 ast_generics: &'tcx hir::Generics<'tcx>,
438 param_id: hir::HirId,
440 only_self_bounds: OnlySelfBounds,
441 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
442 let from_ty_params = ast_generics
445 .filter_map(|param| match param.kind {
446 GenericParamKind::Type { .. } if param.hir_id == param_id => Some(¶m.bounds),
449 .flat_map(|bounds| bounds.iter())
450 .flat_map(|b| predicates_from_bound(self, ty, b));
452 let from_where_clauses = ast_generics
456 .filter_map(|wp| match *wp {
457 hir::WherePredicate::BoundPredicate(ref bp) => Some(bp),
461 let bt = if is_param(self.tcx, &bp.bounded_ty, param_id) {
463 } else if !only_self_bounds.0 {
464 Some(self.to_ty(&bp.bounded_ty))
468 bp.bounds.iter().filter_map(move |b| bt.map(|bt| (bt, b)))
470 .flat_map(|(bt, b)| predicates_from_bound(self, bt, b));
472 from_ty_params.chain(from_where_clauses).collect()
476 /// Tests whether this is the AST for a reference to the type
477 /// parameter with ID `param_id`. We use this so as to avoid running
478 /// `ast_ty_to_ty`, because we want to avoid triggering an all-out
479 /// conversion of the type to avoid inducing unnecessary cycles.
480 fn is_param(tcx: TyCtxt<'_>, ast_ty: &hir::Ty<'_>, param_id: hir::HirId) -> bool {
481 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = ast_ty.kind {
483 Res::SelfTy(Some(def_id), None) | Res::Def(DefKind::TyParam, def_id) => {
484 def_id == tcx.hir().local_def_id(param_id)
493 fn convert_item(tcx: TyCtxt<'_>, item_id: hir::HirId) {
494 let it = tcx.hir().expect_item(item_id);
495 debug!("convert: item {} with id {}", it.ident, it.hir_id);
496 let def_id = tcx.hir().local_def_id(item_id);
498 // These don't define types.
499 hir::ItemKind::ExternCrate(_)
500 | hir::ItemKind::Use(..)
501 | hir::ItemKind::Mod(_)
502 | hir::ItemKind::GlobalAsm(_) => {}
503 hir::ItemKind::ForeignMod(ref foreign_mod) => {
504 for item in foreign_mod.items {
505 let def_id = tcx.hir().local_def_id(item.hir_id);
506 tcx.generics_of(def_id);
508 tcx.predicates_of(def_id);
509 if let hir::ForeignItemKind::Fn(..) = item.kind {
514 hir::ItemKind::Enum(ref enum_definition, _) => {
515 tcx.generics_of(def_id);
517 tcx.predicates_of(def_id);
518 convert_enum_variant_types(tcx, def_id, &enum_definition.variants);
520 hir::ItemKind::Impl(..) => {
521 tcx.generics_of(def_id);
523 tcx.impl_trait_ref(def_id);
524 tcx.predicates_of(def_id);
526 hir::ItemKind::Trait(..) => {
527 tcx.generics_of(def_id);
528 tcx.trait_def(def_id);
529 tcx.at(it.span).super_predicates_of(def_id);
530 tcx.predicates_of(def_id);
532 hir::ItemKind::TraitAlias(..) => {
533 tcx.generics_of(def_id);
534 tcx.at(it.span).super_predicates_of(def_id);
535 tcx.predicates_of(def_id);
537 hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
538 tcx.generics_of(def_id);
540 tcx.predicates_of(def_id);
542 for f in struct_def.fields() {
543 let def_id = tcx.hir().local_def_id(f.hir_id);
544 tcx.generics_of(def_id);
546 tcx.predicates_of(def_id);
549 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
550 convert_variant_ctor(tcx, ctor_hir_id);
554 // Desugared from `impl Trait`, so visited by the function's return type.
555 hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: Some(_), .. }) => {}
557 hir::ItemKind::OpaqueTy(..)
558 | hir::ItemKind::TyAlias(..)
559 | hir::ItemKind::Static(..)
560 | hir::ItemKind::Const(..)
561 | hir::ItemKind::Fn(..) => {
562 tcx.generics_of(def_id);
564 tcx.predicates_of(def_id);
565 if let hir::ItemKind::Fn(..) = it.kind {
572 fn convert_trait_item(tcx: TyCtxt<'_>, trait_item_id: hir::HirId) {
573 let trait_item = tcx.hir().expect_trait_item(trait_item_id);
574 let def_id = tcx.hir().local_def_id(trait_item.hir_id);
575 tcx.generics_of(def_id);
577 match trait_item.kind {
578 hir::TraitItemKind::Const(..)
579 | hir::TraitItemKind::Type(_, Some(_))
580 | hir::TraitItemKind::Method(..) => {
582 if let hir::TraitItemKind::Method(..) = trait_item.kind {
587 hir::TraitItemKind::Type(_, None) => {}
590 tcx.predicates_of(def_id);
593 fn convert_impl_item(tcx: TyCtxt<'_>, impl_item_id: hir::HirId) {
594 let def_id = tcx.hir().local_def_id(impl_item_id);
595 tcx.generics_of(def_id);
597 tcx.predicates_of(def_id);
598 if let hir::ImplItemKind::Method(..) = tcx.hir().expect_impl_item(impl_item_id).kind {
603 fn convert_variant_ctor(tcx: TyCtxt<'_>, ctor_id: hir::HirId) {
604 let def_id = tcx.hir().local_def_id(ctor_id);
605 tcx.generics_of(def_id);
607 tcx.predicates_of(def_id);
610 fn convert_enum_variant_types(tcx: TyCtxt<'_>, def_id: DefId, variants: &[hir::Variant<'_>]) {
611 let def = tcx.adt_def(def_id);
612 let repr_type = def.repr.discr_type();
613 let initial = repr_type.initial_discriminant(tcx);
614 let mut prev_discr = None::<Discr<'_>>;
616 // fill the discriminant values and field types
617 for variant in variants {
618 let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
620 if let Some(ref e) = variant.disr_expr {
621 let expr_did = tcx.hir().local_def_id(e.hir_id);
622 def.eval_explicit_discr(tcx, expr_did)
623 } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) {
626 struct_span_err!(tcx.sess, variant.span, E0370, "enum discriminant overflowed")
629 format!("overflowed on value after {}", prev_discr.unwrap()),
632 "explicitly set `{} = {}` if that is desired outcome",
633 variant.ident, wrapped_discr
638 .unwrap_or(wrapped_discr),
641 for f in variant.data.fields() {
642 let def_id = tcx.hir().local_def_id(f.hir_id);
643 tcx.generics_of(def_id);
645 tcx.predicates_of(def_id);
648 // Convert the ctor, if any. This also registers the variant as
650 if let Some(ctor_hir_id) = variant.data.ctor_hir_id() {
651 convert_variant_ctor(tcx, ctor_hir_id);
658 variant_did: Option<DefId>,
659 ctor_did: Option<DefId>,
661 discr: ty::VariantDiscr,
662 def: &hir::VariantData<'_>,
663 adt_kind: ty::AdtKind,
665 ) -> ty::VariantDef {
666 let mut seen_fields: FxHashMap<ast::Ident, Span> = Default::default();
667 let hir_id = tcx.hir().as_local_hir_id(variant_did.unwrap_or(parent_did)).unwrap();
672 let fid = tcx.hir().local_def_id(f.hir_id);
673 let dup_span = seen_fields.get(&f.ident.modern()).cloned();
674 if let Some(prev_span) = dup_span {
679 "field `{}` is already declared",
682 .span_label(f.span, "field already declared")
683 .span_label(prev_span, format!("`{}` first declared here", f.ident))
686 seen_fields.insert(f.ident.modern(), f.span);
692 vis: ty::Visibility::from_hir(&f.vis, hir_id, tcx),
696 let recovered = match def {
697 hir::VariantData::Struct(_, r) => *r,
707 CtorKind::from_hir(def),
714 fn adt_def(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::AdtDef {
717 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
718 let item = match tcx.hir().get(hir_id) {
719 Node::Item(item) => item,
723 let repr = ReprOptions::new(tcx, def_id);
724 let (kind, variants) = match item.kind {
725 ItemKind::Enum(ref def, _) => {
726 let mut distance_from_explicit = 0;
731 let variant_did = Some(tcx.hir().local_def_id(v.id));
733 v.data.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
735 let discr = if let Some(ref e) = v.disr_expr {
736 distance_from_explicit = 0;
737 ty::VariantDiscr::Explicit(tcx.hir().local_def_id(e.hir_id))
739 ty::VariantDiscr::Relative(distance_from_explicit)
741 distance_from_explicit += 1;
756 (AdtKind::Enum, variants)
758 ItemKind::Struct(ref def, _) => {
759 let variant_did = None;
760 let ctor_did = def.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
762 let variants = std::iter::once(convert_variant(
767 ty::VariantDiscr::Relative(0),
774 (AdtKind::Struct, variants)
776 ItemKind::Union(ref def, _) => {
777 let variant_did = None;
778 let ctor_did = def.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
780 let variants = std::iter::once(convert_variant(
785 ty::VariantDiscr::Relative(0),
792 (AdtKind::Union, variants)
796 tcx.alloc_adt_def(def_id, kind, variants, repr)
799 /// Ensures that the super-predicates of the trait with a `DefId`
800 /// of `trait_def_id` are converted and stored. This also ensures that
801 /// the transitive super-predicates are converted.
802 fn super_predicates_of(tcx: TyCtxt<'_>, trait_def_id: DefId) -> ty::GenericPredicates<'_> {
803 debug!("super_predicates(trait_def_id={:?})", trait_def_id);
804 let trait_hir_id = tcx.hir().as_local_hir_id(trait_def_id).unwrap();
806 let item = match tcx.hir().get(trait_hir_id) {
807 Node::Item(item) => item,
808 _ => bug!("trait_node_id {} is not an item", trait_hir_id),
811 let (generics, bounds) = match item.kind {
812 hir::ItemKind::Trait(.., ref generics, ref supertraits, _) => (generics, supertraits),
813 hir::ItemKind::TraitAlias(ref generics, ref supertraits) => (generics, supertraits),
814 _ => span_bug!(item.span, "super_predicates invoked on non-trait"),
817 let icx = ItemCtxt::new(tcx, trait_def_id);
819 // Convert the bounds that follow the colon, e.g., `Bar + Zed` in `trait Foo: Bar + Zed`.
820 let self_param_ty = tcx.types.self_param;
822 AstConv::compute_bounds(&icx, self_param_ty, bounds, SizedByDefault::No, item.span);
824 let superbounds1 = superbounds1.predicates(tcx, self_param_ty);
826 // Convert any explicit superbounds in the where-clause,
827 // e.g., `trait Foo where Self: Bar`.
828 // In the case of trait aliases, however, we include all bounds in the where-clause,
829 // so e.g., `trait Foo = where u32: PartialEq<Self>` would include `u32: PartialEq<Self>`
830 // as one of its "superpredicates".
831 let is_trait_alias = tcx.is_trait_alias(trait_def_id);
832 let superbounds2 = icx.type_parameter_bounds_in_generics(
836 OnlySelfBounds(!is_trait_alias),
839 // Combine the two lists to form the complete set of superbounds:
840 let superbounds = &*tcx.arena.alloc_from_iter(superbounds1.into_iter().chain(superbounds2));
842 // Now require that immediate supertraits are converted,
843 // which will, in turn, reach indirect supertraits.
844 for &(pred, span) in superbounds {
845 debug!("superbound: {:?}", pred);
846 if let ty::Predicate::Trait(bound) = pred {
847 tcx.at(span).super_predicates_of(bound.def_id());
851 ty::GenericPredicates { parent: None, predicates: superbounds }
854 fn trait_def(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::TraitDef {
855 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
856 let item = tcx.hir().expect_item(hir_id);
858 let (is_auto, unsafety) = match item.kind {
859 hir::ItemKind::Trait(is_auto, unsafety, ..) => (is_auto == hir::IsAuto::Yes, unsafety),
860 hir::ItemKind::TraitAlias(..) => (false, hir::Unsafety::Normal),
861 _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
864 let paren_sugar = tcx.has_attr(def_id, sym::rustc_paren_sugar);
865 if paren_sugar && !tcx.features().unboxed_closures {
866 let mut err = tcx.sess.struct_span_err(
868 "the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \
869 which traits can use parenthetical notation",
873 "add `#![feature(unboxed_closures)]` to \
874 the crate attributes to use it"
879 let is_marker = tcx.has_attr(def_id, sym::marker);
880 let def_path_hash = tcx.def_path_hash(def_id);
881 let def = ty::TraitDef::new(def_id, unsafety, paren_sugar, is_auto, is_marker, def_path_hash);
885 fn has_late_bound_regions<'tcx>(tcx: TyCtxt<'tcx>, node: Node<'tcx>) -> Option<Span> {
886 struct LateBoundRegionsDetector<'tcx> {
888 outer_index: ty::DebruijnIndex,
889 has_late_bound_regions: Option<Span>,
892 impl Visitor<'tcx> for LateBoundRegionsDetector<'tcx> {
893 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
894 NestedVisitorMap::None
897 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
898 if self.has_late_bound_regions.is_some() {
902 hir::TyKind::BareFn(..) => {
903 self.outer_index.shift_in(1);
904 intravisit::walk_ty(self, ty);
905 self.outer_index.shift_out(1);
907 _ => intravisit::walk_ty(self, ty),
911 fn visit_poly_trait_ref(
913 tr: &'tcx hir::PolyTraitRef<'tcx>,
914 m: hir::TraitBoundModifier,
916 if self.has_late_bound_regions.is_some() {
919 self.outer_index.shift_in(1);
920 intravisit::walk_poly_trait_ref(self, tr, m);
921 self.outer_index.shift_out(1);
924 fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
925 if self.has_late_bound_regions.is_some() {
929 match self.tcx.named_region(lt.hir_id) {
930 Some(rl::Region::Static) | Some(rl::Region::EarlyBound(..)) => {}
931 Some(rl::Region::LateBound(debruijn, _, _))
932 | Some(rl::Region::LateBoundAnon(debruijn, _))
933 if debruijn < self.outer_index => {}
934 Some(rl::Region::LateBound(..))
935 | Some(rl::Region::LateBoundAnon(..))
936 | Some(rl::Region::Free(..))
938 self.has_late_bound_regions = Some(lt.span);
944 fn has_late_bound_regions<'tcx>(
946 generics: &'tcx hir::Generics<'tcx>,
947 decl: &'tcx hir::FnDecl<'tcx>,
949 let mut visitor = LateBoundRegionsDetector {
951 outer_index: ty::INNERMOST,
952 has_late_bound_regions: None,
954 for param in generics.params {
955 if let GenericParamKind::Lifetime { .. } = param.kind {
956 if tcx.is_late_bound(param.hir_id) {
957 return Some(param.span);
961 visitor.visit_fn_decl(decl);
962 visitor.has_late_bound_regions
966 Node::TraitItem(item) => match item.kind {
967 hir::TraitItemKind::Method(ref sig, _) => {
968 has_late_bound_regions(tcx, &item.generics, &sig.decl)
972 Node::ImplItem(item) => match item.kind {
973 hir::ImplItemKind::Method(ref sig, _) => {
974 has_late_bound_regions(tcx, &item.generics, &sig.decl)
978 Node::ForeignItem(item) => match item.kind {
979 hir::ForeignItemKind::Fn(ref fn_decl, _, ref generics) => {
980 has_late_bound_regions(tcx, generics, fn_decl)
984 Node::Item(item) => match item.kind {
985 hir::ItemKind::Fn(ref sig, .., ref generics, _) => {
986 has_late_bound_regions(tcx, generics, &sig.decl)
994 fn generics_of(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::Generics {
997 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
999 let node = tcx.hir().get(hir_id);
1000 let parent_def_id = match node {
1002 | Node::TraitItem(_)
1005 | Node::Field(_) => {
1006 let parent_id = tcx.hir().get_parent_item(hir_id);
1007 Some(tcx.hir().local_def_id(parent_id))
1009 // FIXME(#43408) enable this always when we get lazy normalization.
1010 Node::AnonConst(_) => {
1011 // HACK(eddyb) this provides the correct generics when
1012 // `feature(const_generics)` is enabled, so that const expressions
1013 // used with const generics, e.g. `Foo<{N+1}>`, can work at all.
1014 if tcx.features().const_generics {
1015 let parent_id = tcx.hir().get_parent_item(hir_id);
1016 Some(tcx.hir().local_def_id(parent_id))
1021 Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => {
1022 Some(tcx.closure_base_def_id(def_id))
1024 Node::Item(item) => match item.kind {
1025 ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn, .. }) => impl_trait_fn,
1031 let mut opt_self = None;
1032 let mut allow_defaults = false;
1034 let no_generics = hir::Generics::empty();
1035 let ast_generics = match node {
1036 Node::TraitItem(item) => &item.generics,
1038 Node::ImplItem(item) => &item.generics,
1040 Node::Item(item) => {
1042 ItemKind::Fn(.., ref generics, _) | ItemKind::Impl(_, _, _, ref generics, ..) => {
1046 ItemKind::TyAlias(_, ref generics)
1047 | ItemKind::Enum(_, ref generics)
1048 | ItemKind::Struct(_, ref generics)
1049 | ItemKind::OpaqueTy(hir::OpaqueTy { ref generics, .. })
1050 | ItemKind::Union(_, ref generics) => {
1051 allow_defaults = true;
1055 ItemKind::Trait(_, _, ref generics, ..)
1056 | ItemKind::TraitAlias(ref generics, ..) => {
1057 // Add in the self type parameter.
1059 // Something of a hack: use the node id for the trait, also as
1060 // the node id for the Self type parameter.
1061 let param_id = item.hir_id;
1063 opt_self = Some(ty::GenericParamDef {
1065 name: kw::SelfUpper,
1066 def_id: tcx.hir().local_def_id(param_id),
1067 pure_wrt_drop: false,
1068 kind: ty::GenericParamDefKind::Type {
1070 object_lifetime_default: rl::Set1::Empty,
1075 allow_defaults = true;
1083 Node::ForeignItem(item) => match item.kind {
1084 ForeignItemKind::Static(..) => &no_generics,
1085 ForeignItemKind::Fn(_, _, ref generics) => generics,
1086 ForeignItemKind::Type => &no_generics,
1092 let has_self = opt_self.is_some();
1093 let mut parent_has_self = false;
1094 let mut own_start = has_self as u32;
1095 let parent_count = parent_def_id.map_or(0, |def_id| {
1096 let generics = tcx.generics_of(def_id);
1097 assert_eq!(has_self, false);
1098 parent_has_self = generics.has_self;
1099 own_start = generics.count() as u32;
1100 generics.parent_count + generics.params.len()
1103 let mut params: Vec<_> = opt_self.into_iter().collect();
1105 let early_lifetimes = early_bound_lifetimes_from_generics(tcx, ast_generics);
1106 params.extend(early_lifetimes.enumerate().map(|(i, param)| ty::GenericParamDef {
1107 name: param.name.ident().name,
1108 index: own_start + i as u32,
1109 def_id: tcx.hir().local_def_id(param.hir_id),
1110 pure_wrt_drop: param.pure_wrt_drop,
1111 kind: ty::GenericParamDefKind::Lifetime,
1114 let object_lifetime_defaults = tcx.object_lifetime_defaults(hir_id);
1116 // Now create the real type parameters.
1117 let type_start = own_start - has_self as u32 + params.len() as u32;
1119 params.extend(ast_generics.params.iter().filter_map(|param| {
1120 let kind = match param.kind {
1121 GenericParamKind::Type { ref default, synthetic, .. } => {
1122 if !allow_defaults && default.is_some() {
1123 if !tcx.features().default_type_parameter_fallback {
1125 lint::builtin::INVALID_TYPE_PARAM_DEFAULT,
1129 "defaults for type parameters are only allowed in \
1130 `struct`, `enum`, `type`, or `trait` definitions."
1136 ty::GenericParamDefKind::Type {
1137 has_default: default.is_some(),
1138 object_lifetime_default: object_lifetime_defaults
1140 .map_or(rl::Set1::Empty, |o| o[i]),
1144 GenericParamKind::Const { .. } => ty::GenericParamDefKind::Const,
1148 let param_def = ty::GenericParamDef {
1149 index: type_start + i as u32,
1150 name: param.name.ident().name,
1151 def_id: tcx.hir().local_def_id(param.hir_id),
1152 pure_wrt_drop: param.pure_wrt_drop,
1159 // provide junk type parameter defs - the only place that
1160 // cares about anything but the length is instantiation,
1161 // and we don't do that for closures.
1162 if let Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(.., gen), .. }) = node {
1163 let dummy_args = if gen.is_some() {
1164 &["<yield_ty>", "<return_ty>", "<witness>"][..]
1166 &["<closure_kind>", "<closure_signature>"][..]
1169 params.extend(dummy_args.iter().enumerate().map(|(i, &arg)| ty::GenericParamDef {
1170 index: type_start + i as u32,
1171 name: Symbol::intern(arg),
1173 pure_wrt_drop: false,
1174 kind: ty::GenericParamDefKind::Type {
1176 object_lifetime_default: rl::Set1::Empty,
1181 if let Some(upvars) = tcx.upvars(def_id) {
1182 params.extend(upvars.iter().zip((dummy_args.len() as u32)..).map(|(_, i)| {
1183 ty::GenericParamDef {
1184 index: type_start + i,
1185 name: Symbol::intern("<upvar>"),
1187 pure_wrt_drop: false,
1188 kind: ty::GenericParamDefKind::Type {
1190 object_lifetime_default: rl::Set1::Empty,
1198 let param_def_id_to_index = params.iter().map(|param| (param.def_id, param.index)).collect();
1200 tcx.arena.alloc(ty::Generics {
1201 parent: parent_def_id,
1204 param_def_id_to_index,
1205 has_self: has_self || parent_has_self,
1206 has_late_bound_regions: has_late_bound_regions(tcx, node),
1210 fn report_assoc_ty_on_inherent_impl(tcx: TyCtxt<'_>, span: Span) {
1215 "associated types are not yet supported in inherent impls (see #8995)"
1219 fn infer_placeholder_type(
1222 body_id: hir::BodyId,
1226 let ty = tcx.diagnostic_only_typeck_tables_of(def_id).node_type(body_id.hir_id);
1228 // If this came from a free `const` or `static mut?` item,
1229 // then the user may have written e.g. `const A = 42;`.
1230 // In this case, the parser has stashed a diagnostic for
1231 // us to improve in typeck so we do that now.
1232 match tcx.sess.diagnostic().steal_diagnostic(span, StashKey::ItemNoType) {
1234 // The parser provided a sub-optimal `HasPlaceholders` suggestion for the type.
1235 // We are typeck and have the real type, so remove that and suggest the actual type.
1236 err.suggestions.clear();
1237 err.span_suggestion(
1239 "provide a type for the item",
1240 format!("{}: {}", item_ident, ty),
1241 Applicability::MachineApplicable,
1246 let mut diag = bad_placeholder_type(tcx, vec![span]);
1247 if ty != tcx.types.err {
1248 diag.span_suggestion(
1250 "replace `_` with the correct type",
1252 Applicability::MaybeIncorrect,
1262 fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> {
1265 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1267 let icx = ItemCtxt::new(tcx, def_id);
1269 match tcx.hir().get(hir_id) {
1270 Node::TraitItem(item) => match item.kind {
1271 TraitItemKind::Method(..) => {
1272 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1273 tcx.mk_fn_def(def_id, substs)
1275 TraitItemKind::Const(ref ty, body_id) => body_id
1276 .and_then(|body_id| {
1277 if is_suggestable_infer_ty(ty) {
1278 Some(infer_placeholder_type(tcx, def_id, body_id, ty.span, item.ident))
1283 .unwrap_or_else(|| icx.to_ty(ty)),
1284 TraitItemKind::Type(_, Some(ref ty)) => icx.to_ty(ty),
1285 TraitItemKind::Type(_, None) => {
1286 span_bug!(item.span, "associated type missing default");
1290 Node::ImplItem(item) => match item.kind {
1291 ImplItemKind::Method(..) => {
1292 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1293 tcx.mk_fn_def(def_id, substs)
1295 ImplItemKind::Const(ref ty, body_id) => {
1296 if is_suggestable_infer_ty(ty) {
1297 infer_placeholder_type(tcx, def_id, body_id, ty.span, item.ident)
1302 ImplItemKind::OpaqueTy(_) => {
1303 if tcx.impl_trait_ref(tcx.hir().get_parent_did(hir_id)).is_none() {
1304 report_assoc_ty_on_inherent_impl(tcx, item.span);
1307 find_opaque_ty_constraints(tcx, def_id)
1309 ImplItemKind::TyAlias(ref ty) => {
1310 if tcx.impl_trait_ref(tcx.hir().get_parent_did(hir_id)).is_none() {
1311 report_assoc_ty_on_inherent_impl(tcx, item.span);
1318 Node::Item(item) => {
1320 ItemKind::Static(ref ty, .., body_id) | ItemKind::Const(ref ty, body_id) => {
1321 if is_suggestable_infer_ty(ty) {
1322 infer_placeholder_type(tcx, def_id, body_id, ty.span, item.ident)
1327 ItemKind::TyAlias(ref ty, _) | ItemKind::Impl(.., ref ty, _) => icx.to_ty(ty),
1328 ItemKind::Fn(..) => {
1329 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1330 tcx.mk_fn_def(def_id, substs)
1332 ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
1333 let def = tcx.adt_def(def_id);
1334 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1335 tcx.mk_adt(def, substs)
1337 ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: None, .. }) => {
1338 find_opaque_ty_constraints(tcx, def_id)
1340 // Opaque types desugared from `impl Trait`.
1341 ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: Some(owner), .. }) => {
1342 tcx.typeck_tables_of(owner)
1343 .concrete_opaque_types
1345 .map(|opaque| opaque.concrete_type)
1346 .unwrap_or_else(|| {
1347 // This can occur if some error in the
1348 // owner fn prevented us from populating
1349 // the `concrete_opaque_types` table.
1350 tcx.sess.delay_span_bug(
1353 "owner {:?} has no opaque type for {:?} in its tables",
1361 | ItemKind::TraitAlias(..)
1363 | ItemKind::ForeignMod(..)
1364 | ItemKind::GlobalAsm(..)
1365 | ItemKind::ExternCrate(..)
1366 | ItemKind::Use(..) => {
1369 "compute_type_of_item: unexpected item type: {:?}",
1376 Node::ForeignItem(foreign_item) => match foreign_item.kind {
1377 ForeignItemKind::Fn(..) => {
1378 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1379 tcx.mk_fn_def(def_id, substs)
1381 ForeignItemKind::Static(ref t, _) => icx.to_ty(t),
1382 ForeignItemKind::Type => tcx.mk_foreign(def_id),
1385 Node::Ctor(&ref def) | Node::Variant(hir::Variant { data: ref def, .. }) => match *def {
1386 VariantData::Unit(..) | VariantData::Struct(..) => {
1387 tcx.type_of(tcx.hir().get_parent_did(hir_id))
1389 VariantData::Tuple(..) => {
1390 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1391 tcx.mk_fn_def(def_id, substs)
1395 Node::Field(field) => icx.to_ty(&field.ty),
1397 Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(.., gen), .. }) => {
1399 return tcx.typeck_tables_of(def_id).node_type(hir_id);
1402 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1403 tcx.mk_closure(def_id, substs)
1406 Node::AnonConst(_) => {
1407 let parent_node = tcx.hir().get(tcx.hir().get_parent_node(hir_id));
1409 Node::Ty(&hir::Ty { kind: hir::TyKind::Array(_, ref constant), .. })
1410 | Node::Ty(&hir::Ty { kind: hir::TyKind::Typeof(ref constant), .. })
1411 | Node::Expr(&hir::Expr { kind: ExprKind::Repeat(_, ref constant), .. })
1412 if constant.hir_id == hir_id =>
1417 Node::Variant(Variant { disr_expr: Some(ref e), .. }) if e.hir_id == hir_id => {
1418 tcx.adt_def(tcx.hir().get_parent_did(hir_id)).repr.discr_type().to_ty(tcx)
1421 Node::Ty(&hir::Ty { kind: hir::TyKind::Path(_), .. })
1422 | Node::Expr(&hir::Expr { kind: ExprKind::Struct(..), .. })
1423 | Node::Expr(&hir::Expr { kind: ExprKind::Path(_), .. })
1424 | Node::TraitRef(..) => {
1425 let path = match parent_node {
1427 kind: hir::TyKind::Path(QPath::Resolved(_, ref path)),
1430 | Node::Expr(&hir::Expr {
1431 kind: ExprKind::Path(QPath::Resolved(_, ref path)),
1433 }) => Some(&**path),
1434 Node::Expr(&hir::Expr { kind: ExprKind::Struct(ref path, ..), .. }) => {
1435 if let QPath::Resolved(_, ref path) = **path {
1441 Node::TraitRef(&hir::TraitRef { ref path, .. }) => Some(&**path),
1445 if let Some(path) = path {
1446 let arg_index = path
1449 .filter_map(|seg| seg.args.as_ref())
1450 .map(|generic_args| generic_args.args.as_ref())
1453 .filter(|arg| arg.is_const())
1455 .filter(|(_, arg)| arg.id() == hir_id)
1456 .map(|(index, _)| index)
1459 .unwrap_or_else(|| {
1460 bug!("no arg matching AnonConst in path");
1463 // We've encountered an `AnonConst` in some path, so we need to
1464 // figure out which generic parameter it corresponds to and return
1465 // the relevant type.
1466 let generics = match path.res {
1467 Res::Def(DefKind::Ctor(..), def_id) => {
1468 tcx.generics_of(tcx.parent(def_id).unwrap())
1470 Res::Def(_, def_id) => tcx.generics_of(def_id),
1471 Res::Err => return tcx.types.err,
1473 tcx.sess.delay_span_bug(
1475 &format!("unexpected const parent path def {:?}", res,),
1477 return tcx.types.err;
1485 if let ty::GenericParamDefKind::Const = param.kind {
1492 .map(|param| tcx.type_of(param.def_id))
1493 // This is no generic parameter associated with the arg. This is
1494 // probably from an extra arg where one is not needed.
1495 .unwrap_or(tcx.types.err)
1497 tcx.sess.delay_span_bug(
1499 &format!("unexpected const parent path {:?}", parent_node,),
1501 return tcx.types.err;
1506 tcx.sess.delay_span_bug(
1508 &format!("unexpected const parent in type_of_def_id(): {:?}", x),
1515 Node::GenericParam(param) => {
1517 hir::GenericParamKind::Type { default: Some(ref ty), .. } => icx.to_ty(ty),
1518 hir::GenericParamKind::Const { ty: ref hir_ty, .. } => {
1519 let ty = icx.to_ty(hir_ty);
1520 if !tcx.features().const_compare_raw_pointers {
1521 let err = match ty.peel_refs().kind {
1522 ty::FnPtr(_) => Some("function pointers"),
1523 ty::RawPtr(_) => Some("raw pointers"),
1526 if let Some(unsupported_type) = err {
1527 feature_gate::feature_err(
1528 &tcx.sess.parse_sess,
1529 sym::const_compare_raw_pointers,
1532 "using {} as const generic parameters is unstable",
1539 if ty::search_for_structural_match_violation(param.hir_id, param.span, tcx, ty)
1546 "the types of const generic parameters must derive `PartialEq` and `Eq`",
1549 format!("`{}` doesn't derive both `PartialEq` and `Eq`", ty),
1554 x => bug!("unexpected non-type Node::GenericParam: {:?}", x),
1559 bug!("unexpected sort of node in type_of_def_id(): {:?}", x);
1564 fn find_opaque_ty_constraints(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> {
1565 use rustc::hir::{ImplItem, Item, TraitItem};
1567 debug!("find_opaque_ty_constraints({:?})", def_id);
1569 struct ConstraintLocator<'tcx> {
1572 // (first found type span, actual type, mapping from the opaque type's generic
1573 // parameters to the concrete type's generic parameters)
1575 // The mapping is an index for each use site of a generic parameter in the concrete type
1577 // The indices index into the generic parameters on the opaque type.
1578 found: Option<(Span, Ty<'tcx>, Vec<usize>)>,
1581 impl ConstraintLocator<'tcx> {
1582 fn check(&mut self, def_id: DefId) {
1583 // Don't try to check items that cannot possibly constrain the type.
1584 if !self.tcx.has_typeck_tables(def_id) {
1586 "find_opaque_ty_constraints: no constraint for `{:?}` at `{:?}`: no tables",
1587 self.def_id, def_id,
1591 let ty = self.tcx.typeck_tables_of(def_id).concrete_opaque_types.get(&self.def_id);
1592 if let Some(ty::ResolvedOpaqueTy { concrete_type, substs }) = ty {
1594 "find_opaque_ty_constraints: found constraint for `{:?}` at `{:?}`: {:?}",
1595 self.def_id, def_id, ty,
1598 // FIXME(oli-obk): trace the actual span from inference to improve errors.
1599 let span = self.tcx.def_span(def_id);
1600 // used to quickly look up the position of a generic parameter
1601 let mut index_map: FxHashMap<ty::ParamTy, usize> = FxHashMap::default();
1602 // Skipping binder is ok, since we only use this to find generic parameters and
1604 for (idx, subst) in substs.iter().enumerate() {
1605 if let GenericArgKind::Type(ty) = subst.unpack() {
1606 if let ty::Param(p) = ty.kind {
1607 if index_map.insert(p, idx).is_some() {
1608 // There was already an entry for `p`, meaning a generic parameter
1610 self.tcx.sess.span_err(
1613 "defining opaque type use restricts opaque \
1614 type by using the generic parameter `{}` twice",
1621 self.tcx.sess.delay_span_bug(
1624 "non-defining opaque ty use in defining scope: {:?}, {:?}",
1625 concrete_type, substs,
1631 // Compute the index within the opaque type for each generic parameter used in
1632 // the concrete type.
1633 let indices = concrete_type
1634 .subst(self.tcx, substs)
1636 .filter_map(|t| match &t.kind {
1637 ty::Param(p) => Some(*index_map.get(p).unwrap()),
1641 let is_param = |ty: Ty<'_>| match ty.kind {
1642 ty::Param(_) => true,
1645 let bad_substs: Vec<_> =
1646 substs.types().enumerate().filter(|(_, ty)| !is_param(ty)).collect();
1647 if !bad_substs.is_empty() {
1648 let identity_substs = InternalSubsts::identity_for_item(self.tcx, self.def_id);
1649 for (i, bad_subst) in bad_substs {
1650 self.tcx.sess.span_err(
1653 "defining opaque type use does not fully define opaque type: \
1654 generic parameter `{}` is specified as concrete type `{}`",
1655 identity_substs.type_at(i),
1660 } else if let Some((prev_span, prev_ty, ref prev_indices)) = self.found {
1661 let mut ty = concrete_type.walk().fuse();
1662 let mut p_ty = prev_ty.walk().fuse();
1663 let iter_eq = (&mut ty).zip(&mut p_ty).all(|(t, p)| match (&t.kind, &p.kind) {
1664 // Type parameters are equal to any other type parameter for the purpose of
1665 // concrete type equality, as it is possible to obtain the same type just
1666 // by passing matching parameters to a function.
1667 (ty::Param(_), ty::Param(_)) => true,
1670 if !iter_eq || ty.next().is_some() || p_ty.next().is_some() {
1671 debug!("find_opaque_ty_constraints: span={:?}", span);
1672 // Found different concrete types for the opaque type.
1673 let mut err = self.tcx.sess.struct_span_err(
1675 "concrete type differs from previous defining opaque type use",
1679 format!("expected `{}`, got `{}`", prev_ty, concrete_type),
1681 err.span_note(prev_span, "previous use here");
1683 } else if indices != *prev_indices {
1684 // Found "same" concrete types, but the generic parameter order differs.
1685 let mut err = self.tcx.sess.struct_span_err(
1687 "concrete type's generic parameters differ from previous defining use",
1689 use std::fmt::Write;
1690 let mut s = String::new();
1691 write!(s, "expected [").unwrap();
1692 let list = |s: &mut String, indices: &Vec<usize>| {
1693 let mut indices = indices.iter().cloned();
1694 if let Some(first) = indices.next() {
1695 write!(s, "`{}`", substs[first]).unwrap();
1697 write!(s, ", `{}`", substs[i]).unwrap();
1701 list(&mut s, prev_indices);
1702 write!(s, "], got [").unwrap();
1703 list(&mut s, &indices);
1704 write!(s, "]").unwrap();
1705 err.span_label(span, s);
1706 err.span_note(prev_span, "previous use here");
1710 self.found = Some((span, concrete_type, indices));
1714 "find_opaque_ty_constraints: no constraint for `{:?}` at `{:?}`",
1715 self.def_id, def_id,
1721 impl<'tcx> intravisit::Visitor<'tcx> for ConstraintLocator<'tcx> {
1722 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
1723 intravisit::NestedVisitorMap::All(&self.tcx.hir())
1725 fn visit_item(&mut self, it: &'tcx Item<'tcx>) {
1726 debug!("find_existential_constraints: visiting {:?}", it);
1727 let def_id = self.tcx.hir().local_def_id(it.hir_id);
1728 // The opaque type itself or its children are not within its reveal scope.
1729 if def_id != self.def_id {
1731 intravisit::walk_item(self, it);
1734 fn visit_impl_item(&mut self, it: &'tcx ImplItem<'tcx>) {
1735 debug!("find_existential_constraints: visiting {:?}", it);
1736 let def_id = self.tcx.hir().local_def_id(it.hir_id);
1737 // The opaque type itself or its children are not within its reveal scope.
1738 if def_id != self.def_id {
1740 intravisit::walk_impl_item(self, it);
1743 fn visit_trait_item(&mut self, it: &'tcx TraitItem<'tcx>) {
1744 debug!("find_existential_constraints: visiting {:?}", it);
1745 let def_id = self.tcx.hir().local_def_id(it.hir_id);
1747 intravisit::walk_trait_item(self, it);
1751 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1752 let scope = tcx.hir().get_defining_scope(hir_id);
1753 let mut locator = ConstraintLocator { def_id, tcx, found: None };
1755 debug!("find_opaque_ty_constraints: scope={:?}", scope);
1757 if scope == hir::CRATE_HIR_ID {
1758 intravisit::walk_crate(&mut locator, tcx.hir().krate());
1760 debug!("find_opaque_ty_constraints: scope={:?}", tcx.hir().get(scope));
1761 match tcx.hir().get(scope) {
1762 // We explicitly call `visit_*` methods, instead of using `intravisit::walk_*` methods
1763 // This allows our visitor to process the defining item itself, causing
1764 // it to pick up any 'sibling' defining uses.
1766 // For example, this code:
1769 // type Blah = impl Debug;
1770 // let my_closure = || -> Blah { true };
1774 // requires us to explicitly process `foo()` in order
1775 // to notice the defining usage of `Blah`.
1776 Node::Item(ref it) => locator.visit_item(it),
1777 Node::ImplItem(ref it) => locator.visit_impl_item(it),
1778 Node::TraitItem(ref it) => locator.visit_trait_item(it),
1779 other => bug!("{:?} is not a valid scope for an opaque type item", other),
1783 match locator.found {
1784 Some((_, ty, _)) => ty,
1786 let span = tcx.def_span(def_id);
1787 tcx.sess.span_err(span, "could not find defining uses");
1793 /// Whether `ty` is a type with `_` placeholders that can be infered. Used in diagnostics only to
1794 /// use inference to provide suggestions for the appropriate type if possible.
1795 fn is_suggestable_infer_ty(ty: &hir::Ty<'_>) -> bool {
1797 hir::TyKind::Infer => true,
1798 hir::TyKind::Slice(ty) | hir::TyKind::Array(ty, _) => is_suggestable_infer_ty(ty),
1799 hir::TyKind::Tup(tys) => tys.iter().any(|ty| is_suggestable_infer_ty(ty)),
1804 pub fn get_infer_ret_ty(output: &'hir hir::FunctionRetTy<'hir>) -> Option<&'hir hir::Ty<'hir>> {
1805 if let hir::FunctionRetTy::Return(ref ty) = output {
1806 if is_suggestable_infer_ty(ty) {
1813 fn fn_sig(tcx: TyCtxt<'_>, def_id: DefId) -> ty::PolyFnSig<'_> {
1814 use rustc::hir::Node::*;
1817 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1819 let icx = ItemCtxt::new(tcx, def_id);
1821 match tcx.hir().get(hir_id) {
1822 TraitItem(hir::TraitItem {
1823 kind: TraitItemKind::Method(sig, TraitMethod::Provided(_)),
1828 | ImplItem(hir::ImplItem { kind: ImplItemKind::Method(sig, _), ident, generics, .. })
1829 | Item(hir::Item { kind: ItemKind::Fn(sig, generics, _), ident, .. }) => {
1830 match get_infer_ret_ty(&sig.decl.output) {
1832 let fn_sig = tcx.typeck_tables_of(def_id).liberated_fn_sigs()[hir_id];
1833 let mut visitor = PlaceholderHirTyCollector::default();
1834 visitor.visit_ty(ty);
1835 let mut diag = bad_placeholder_type(tcx, visitor.0);
1836 let ret_ty = fn_sig.output();
1837 if ret_ty != tcx.types.err {
1838 diag.span_suggestion(
1840 "replace with the correct return type",
1842 Applicability::MaybeIncorrect,
1846 ty::Binder::bind(fn_sig)
1848 None => AstConv::ty_of_fn(
1850 sig.header.unsafety,
1853 &generics.params[..],
1859 TraitItem(hir::TraitItem {
1860 kind: TraitItemKind::Method(FnSig { header, decl }, _),
1864 }) => AstConv::ty_of_fn(
1869 &generics.params[..],
1873 ForeignItem(&hir::ForeignItem { kind: ForeignItemKind::Fn(ref fn_decl, _, _), .. }) => {
1874 let abi = tcx.hir().get_foreign_abi(hir_id);
1875 compute_sig_of_foreign_fn_decl(tcx, def_id, fn_decl, abi)
1878 Ctor(data) | Variant(hir::Variant { data, .. }) if data.ctor_hir_id().is_some() => {
1879 let ty = tcx.type_of(tcx.hir().get_parent_did(hir_id));
1881 data.fields().iter().map(|f| tcx.type_of(tcx.hir().local_def_id(f.hir_id)));
1882 ty::Binder::bind(tcx.mk_fn_sig(
1886 hir::Unsafety::Normal,
1891 Expr(&hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => {
1892 // Closure signatures are not like other function
1893 // signatures and cannot be accessed through `fn_sig`. For
1894 // example, a closure signature excludes the `self`
1895 // argument. In any case they are embedded within the
1896 // closure type as part of the `ClosureSubsts`.
1899 // the signature of a closure, you should use the
1900 // `closure_sig` method on the `ClosureSubsts`:
1902 // closure_substs.sig(def_id, tcx)
1904 // or, inside of an inference context, you can use
1906 // infcx.closure_sig(def_id, closure_substs)
1907 bug!("to get the signature of a closure, use `closure_sig()` not `fn_sig()`");
1911 bug!("unexpected sort of node in fn_sig(): {:?}", x);
1916 fn impl_trait_ref(tcx: TyCtxt<'_>, def_id: DefId) -> Option<ty::TraitRef<'_>> {
1917 let icx = ItemCtxt::new(tcx, def_id);
1919 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1920 match tcx.hir().expect_item(hir_id).kind {
1921 hir::ItemKind::Impl(.., ref opt_trait_ref, _, _) => {
1922 opt_trait_ref.as_ref().map(|ast_trait_ref| {
1923 let selfty = tcx.type_of(def_id);
1924 AstConv::instantiate_mono_trait_ref(&icx, ast_trait_ref, selfty)
1931 fn impl_polarity(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ImplPolarity {
1932 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1933 let is_rustc_reservation = tcx.has_attr(def_id, sym::rustc_reservation_impl);
1934 let item = tcx.hir().expect_item(hir_id);
1936 hir::ItemKind::Impl(_, hir::ImplPolarity::Negative, ..) => {
1937 if is_rustc_reservation {
1938 tcx.sess.span_err(item.span, "reservation impls can't be negative");
1940 ty::ImplPolarity::Negative
1942 hir::ItemKind::Impl(_, hir::ImplPolarity::Positive, _, _, None, _, _) => {
1943 if is_rustc_reservation {
1944 tcx.sess.span_err(item.span, "reservation impls can't be inherent");
1946 ty::ImplPolarity::Positive
1948 hir::ItemKind::Impl(_, hir::ImplPolarity::Positive, _, _, Some(_tr), _, _) => {
1949 if is_rustc_reservation {
1950 ty::ImplPolarity::Reservation
1952 ty::ImplPolarity::Positive
1955 ref item => bug!("impl_polarity: {:?} not an impl", item),
1959 /// Returns the early-bound lifetimes declared in this generics
1960 /// listing. For anything other than fns/methods, this is just all
1961 /// the lifetimes that are declared. For fns or methods, we have to
1962 /// screen out those that do not appear in any where-clauses etc using
1963 /// `resolve_lifetime::early_bound_lifetimes`.
1964 fn early_bound_lifetimes_from_generics<'a, 'tcx: 'a>(
1966 generics: &'a hir::Generics<'a>,
1967 ) -> impl Iterator<Item = &'a hir::GenericParam<'a>> + Captures<'tcx> {
1968 generics.params.iter().filter(move |param| match param.kind {
1969 GenericParamKind::Lifetime { .. } => !tcx.is_late_bound(param.hir_id),
1974 /// Returns a list of type predicates for the definition with ID `def_id`, including inferred
1975 /// lifetime constraints. This includes all predicates returned by `explicit_predicates_of`, plus
1976 /// inferred constraints concerning which regions outlive other regions.
1977 fn predicates_defined_on(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1978 debug!("predicates_defined_on({:?})", def_id);
1979 let mut result = tcx.explicit_predicates_of(def_id);
1980 debug!("predicates_defined_on: explicit_predicates_of({:?}) = {:?}", def_id, result,);
1981 let inferred_outlives = tcx.inferred_outlives_of(def_id);
1982 if !inferred_outlives.is_empty() {
1984 "predicates_defined_on: inferred_outlives_of({:?}) = {:?}",
1985 def_id, inferred_outlives,
1987 if result.predicates.is_empty() {
1988 result.predicates = inferred_outlives;
1990 result.predicates = tcx
1992 .alloc_from_iter(result.predicates.iter().chain(inferred_outlives).copied());
1995 debug!("predicates_defined_on({:?}) = {:?}", def_id, result);
1999 /// Returns a list of all type predicates (explicit and implicit) for the definition with
2000 /// ID `def_id`. This includes all predicates returned by `predicates_defined_on`, plus
2001 /// `Self: Trait` predicates for traits.
2002 fn predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
2003 let mut result = tcx.predicates_defined_on(def_id);
2005 if tcx.is_trait(def_id) {
2006 // For traits, add `Self: Trait` predicate. This is
2007 // not part of the predicates that a user writes, but it
2008 // is something that one must prove in order to invoke a
2009 // method or project an associated type.
2011 // In the chalk setup, this predicate is not part of the
2012 // "predicates" for a trait item. But it is useful in
2013 // rustc because if you directly (e.g.) invoke a trait
2014 // method like `Trait::method(...)`, you must naturally
2015 // prove that the trait applies to the types that were
2016 // used, and adding the predicate into this list ensures
2017 // that this is done.
2018 let span = tcx.def_span(def_id);
2020 tcx.arena.alloc_from_iter(result.predicates.iter().copied().chain(std::iter::once((
2021 ty::TraitRef::identity(tcx, def_id).to_predicate(),
2025 debug!("predicates_of(def_id={:?}) = {:?}", def_id, result);
2029 /// Returns a list of user-specified type predicates for the definition with ID `def_id`.
2030 /// N.B., this does not include any implied/inferred constraints.
2031 fn explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
2033 use rustc_data_structures::fx::FxHashSet;
2035 debug!("explicit_predicates_of(def_id={:?})", def_id);
2037 /// A data structure with unique elements, which preserves order of insertion.
2038 /// Preserving the order of insertion is important here so as not to break
2039 /// compile-fail UI tests.
2040 // FIXME(eddyb) just use `IndexSet` from `indexmap`.
2041 struct UniquePredicates<'tcx> {
2042 predicates: Vec<(ty::Predicate<'tcx>, Span)>,
2043 uniques: FxHashSet<(ty::Predicate<'tcx>, Span)>,
2046 impl<'tcx> UniquePredicates<'tcx> {
2048 UniquePredicates { predicates: vec![], uniques: FxHashSet::default() }
2051 fn push(&mut self, value: (ty::Predicate<'tcx>, Span)) {
2052 if self.uniques.insert(value) {
2053 self.predicates.push(value);
2057 fn extend<I: IntoIterator<Item = (ty::Predicate<'tcx>, Span)>>(&mut self, iter: I) {
2064 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
2065 let node = tcx.hir().get(hir_id);
2067 let mut is_trait = None;
2068 let mut is_default_impl_trait = None;
2070 let icx = ItemCtxt::new(tcx, def_id);
2072 const NO_GENERICS: &hir::Generics<'_> = &hir::Generics::empty();
2074 let mut predicates = UniquePredicates::new();
2076 let ast_generics = match node {
2077 Node::TraitItem(item) => &item.generics,
2079 Node::ImplItem(item) => match item.kind {
2080 ImplItemKind::OpaqueTy(ref bounds) => {
2081 ty::print::with_no_queries(|| {
2082 let substs = InternalSubsts::identity_for_item(tcx, def_id);
2083 let opaque_ty = tcx.mk_opaque(def_id, substs);
2085 "explicit_predicates_of({:?}): created opaque type {:?}",
2089 // Collect the bounds, i.e., the `A + B + 'c` in `impl A + B + 'c`.
2090 let bounds = AstConv::compute_bounds(
2094 SizedByDefault::Yes,
2095 tcx.def_span(def_id),
2098 predicates.extend(bounds.predicates(tcx, opaque_ty));
2102 _ => &item.generics,
2105 Node::Item(item) => {
2107 ItemKind::Impl(_, _, defaultness, ref generics, ..) => {
2108 if defaultness.is_default() {
2109 is_default_impl_trait = tcx.impl_trait_ref(def_id);
2113 ItemKind::Fn(.., ref generics, _)
2114 | ItemKind::TyAlias(_, ref generics)
2115 | ItemKind::Enum(_, ref generics)
2116 | ItemKind::Struct(_, ref generics)
2117 | ItemKind::Union(_, ref generics) => generics,
2119 ItemKind::Trait(_, _, ref generics, .., items) => {
2120 is_trait = Some((ty::TraitRef::identity(tcx, def_id), items));
2123 ItemKind::TraitAlias(ref generics, _) => {
2124 is_trait = Some((ty::TraitRef::identity(tcx, def_id), &[]));
2127 ItemKind::OpaqueTy(OpaqueTy {
2133 let bounds_predicates = ty::print::with_no_queries(|| {
2134 let substs = InternalSubsts::identity_for_item(tcx, def_id);
2135 let opaque_ty = tcx.mk_opaque(def_id, substs);
2137 // Collect the bounds, i.e., the `A + B + 'c` in `impl A + B + 'c`.
2138 let bounds = AstConv::compute_bounds(
2142 SizedByDefault::Yes,
2143 tcx.def_span(def_id),
2146 bounds.predicates(tcx, opaque_ty)
2148 if impl_trait_fn.is_some() {
2150 return ty::GenericPredicates {
2152 predicates: tcx.arena.alloc_from_iter(bounds_predicates),
2155 // named opaque types
2156 predicates.extend(bounds_predicates);
2165 Node::ForeignItem(item) => match item.kind {
2166 ForeignItemKind::Static(..) => NO_GENERICS,
2167 ForeignItemKind::Fn(_, _, ref generics) => generics,
2168 ForeignItemKind::Type => NO_GENERICS,
2174 let generics = tcx.generics_of(def_id);
2175 let parent_count = generics.parent_count as u32;
2176 let has_own_self = generics.has_self && parent_count == 0;
2178 // Below we'll consider the bounds on the type parameters (including `Self`)
2179 // and the explicit where-clauses, but to get the full set of predicates
2180 // on a trait we need to add in the supertrait bounds and bounds found on
2181 // associated types.
2182 if let Some((_trait_ref, _)) = is_trait {
2183 predicates.extend(tcx.super_predicates_of(def_id).predicates.iter().cloned());
2186 // In default impls, we can assume that the self type implements
2187 // the trait. So in:
2189 // default impl Foo for Bar { .. }
2191 // we add a default where clause `Foo: Bar`. We do a similar thing for traits
2192 // (see below). Recall that a default impl is not itself an impl, but rather a
2193 // set of defaults that can be incorporated into another impl.
2194 if let Some(trait_ref) = is_default_impl_trait {
2195 predicates.push((trait_ref.to_poly_trait_ref().to_predicate(), tcx.def_span(def_id)));
2198 // Collect the region predicates that were declared inline as
2199 // well. In the case of parameters declared on a fn or method, we
2200 // have to be careful to only iterate over early-bound regions.
2201 let mut index = parent_count + has_own_self as u32;
2202 for param in early_bound_lifetimes_from_generics(tcx, ast_generics) {
2203 let region = tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
2204 def_id: tcx.hir().local_def_id(param.hir_id),
2206 name: param.name.ident().name,
2211 GenericParamKind::Lifetime { .. } => {
2212 param.bounds.iter().for_each(|bound| match bound {
2213 hir::GenericBound::Outlives(lt) => {
2214 let bound = AstConv::ast_region_to_region(&icx, <, None);
2215 let outlives = ty::Binder::bind(ty::OutlivesPredicate(region, bound));
2216 predicates.push((outlives.to_predicate(), lt.span));
2225 // Collect the predicates that were written inline by the user on each
2226 // type parameter (e.g., `<T: Foo>`).
2227 for param in ast_generics.params {
2228 if let GenericParamKind::Type { .. } = param.kind {
2229 let name = param.name.ident().name;
2230 let param_ty = ty::ParamTy::new(index, name).to_ty(tcx);
2233 let sized = SizedByDefault::Yes;
2234 let bounds = AstConv::compute_bounds(&icx, param_ty, ¶m.bounds, sized, param.span);
2235 predicates.extend(bounds.predicates(tcx, param_ty));
2239 // Add in the bounds that appear in the where-clause.
2240 let where_clause = &ast_generics.where_clause;
2241 for predicate in where_clause.predicates {
2243 &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
2244 let ty = icx.to_ty(&bound_pred.bounded_ty);
2246 // Keep the type around in a dummy predicate, in case of no bounds.
2247 // That way, `where Ty:` is not a complete noop (see #53696) and `Ty`
2248 // is still checked for WF.
2249 if bound_pred.bounds.is_empty() {
2250 if let ty::Param(_) = ty.kind {
2251 // This is a `where T:`, which can be in the HIR from the
2252 // transformation that moves `?Sized` to `T`'s declaration.
2253 // We can skip the predicate because type parameters are
2254 // trivially WF, but also we *should*, to avoid exposing
2255 // users who never wrote `where Type:,` themselves, to
2256 // compiler/tooling bugs from not handling WF predicates.
2258 let span = bound_pred.bounded_ty.span;
2259 let predicate = ty::OutlivesPredicate(ty, tcx.mk_region(ty::ReEmpty));
2261 ty::Predicate::TypeOutlives(ty::Binder::dummy(predicate)),
2267 for bound in bound_pred.bounds.iter() {
2269 &hir::GenericBound::Trait(ref poly_trait_ref, _) => {
2270 let mut bounds = Bounds::default();
2271 let _ = AstConv::instantiate_poly_trait_ref(
2277 predicates.extend(bounds.predicates(tcx, ty));
2280 &hir::GenericBound::Outlives(ref lifetime) => {
2281 let region = AstConv::ast_region_to_region(&icx, lifetime, None);
2282 let pred = ty::Binder::bind(ty::OutlivesPredicate(ty, region));
2283 predicates.push((ty::Predicate::TypeOutlives(pred), lifetime.span))
2289 &hir::WherePredicate::RegionPredicate(ref region_pred) => {
2290 let r1 = AstConv::ast_region_to_region(&icx, ®ion_pred.lifetime, None);
2291 predicates.extend(region_pred.bounds.iter().map(|bound| {
2292 let (r2, span) = match bound {
2293 hir::GenericBound::Outlives(lt) => {
2294 (AstConv::ast_region_to_region(&icx, lt, None), lt.span)
2298 let pred = ty::Binder::bind(ty::OutlivesPredicate(r1, r2));
2300 (ty::Predicate::RegionOutlives(pred), span)
2304 &hir::WherePredicate::EqPredicate(..) => {
2310 // Add predicates from associated type bounds.
2311 if let Some((self_trait_ref, trait_items)) = is_trait {
2312 predicates.extend(trait_items.iter().flat_map(|trait_item_ref| {
2313 associated_item_predicates(tcx, def_id, self_trait_ref, trait_item_ref)
2317 let mut predicates = predicates.predicates;
2319 // Subtle: before we store the predicates into the tcx, we
2320 // sort them so that predicates like `T: Foo<Item=U>` come
2321 // before uses of `U`. This avoids false ambiguity errors
2322 // in trait checking. See `setup_constraining_predicates`
2324 if let Node::Item(&Item { kind: ItemKind::Impl(..), .. }) = node {
2325 let self_ty = tcx.type_of(def_id);
2326 let trait_ref = tcx.impl_trait_ref(def_id);
2327 cgp::setup_constraining_predicates(
2331 &mut cgp::parameters_for_impl(self_ty, trait_ref),
2335 let result = ty::GenericPredicates {
2336 parent: generics.parent,
2337 predicates: tcx.arena.alloc_from_iter(predicates),
2339 debug!("explicit_predicates_of(def_id={:?}) = {:?}", def_id, result);
2343 fn associated_item_predicates(
2346 self_trait_ref: ty::TraitRef<'tcx>,
2347 trait_item_ref: &hir::TraitItemRef,
2348 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2349 let trait_item = tcx.hir().trait_item(trait_item_ref.id);
2350 let item_def_id = tcx.hir().local_def_id(trait_item_ref.id.hir_id);
2351 let bounds = match trait_item.kind {
2352 hir::TraitItemKind::Type(ref bounds, _) => bounds,
2353 _ => return Vec::new(),
2356 let is_gat = !tcx.generics_of(item_def_id).params.is_empty();
2358 let mut had_error = false;
2360 let mut unimplemented_error = |arg_kind: &str| {
2365 &format!("{}-generic associated types are not yet implemented", arg_kind),
2367 .note("for more information, see https://github.com/rust-lang/rust/issues/44265")
2373 let mk_bound_param = |param: &ty::GenericParamDef, _: &_| {
2375 ty::GenericParamDefKind::Lifetime => tcx
2376 .mk_region(ty::RegionKind::ReLateBound(
2378 ty::BoundRegion::BrNamed(param.def_id, param.name),
2381 // FIXME(generic_associated_types): Use bound types and constants
2382 // once they are handled by the trait system.
2383 ty::GenericParamDefKind::Type { .. } => {
2384 unimplemented_error("type");
2385 tcx.types.err.into()
2387 ty::GenericParamDefKind::Const => {
2388 unimplemented_error("const");
2389 tcx.consts.err.into()
2394 let bound_substs = if is_gat {
2397 // trait X<'a, B, const C: usize> {
2398 // type T<'d, E, const F: usize>: Default;
2401 // We need to create predicates on the trait:
2403 // for<'d, E, const F: usize>
2404 // <Self as X<'a, B, const C: usize>>::T<'d, E, const F: usize>: Sized + Default
2406 // We substitute escaping bound parameters for the generic
2407 // arguments to the associated type which are then bound by
2408 // the `Binder` around the the predicate.
2410 // FIXME(generic_associated_types): Currently only lifetimes are handled.
2411 self_trait_ref.substs.extend_to(tcx, item_def_id, mk_bound_param)
2413 self_trait_ref.substs
2416 let assoc_ty = tcx.mk_projection(tcx.hir().local_def_id(trait_item.hir_id), bound_substs);
2418 let bounds = AstConv::compute_bounds(
2419 &ItemCtxt::new(tcx, def_id),
2422 SizedByDefault::Yes,
2426 let predicates = bounds.predicates(tcx, assoc_ty);
2429 // We use shifts to get the regions that we're substituting to
2430 // be bound by the binders in the `Predicate`s rather that
2432 let shifted_in = ty::fold::shift_vars(tcx, &predicates, 1);
2433 let substituted = shifted_in.subst(tcx, bound_substs);
2434 ty::fold::shift_out_vars(tcx, &substituted, 1)
2440 /// Converts a specific `GenericBound` from the AST into a set of
2441 /// predicates that apply to the self type. A vector is returned
2442 /// because this can be anywhere from zero predicates (`T: ?Sized` adds no
2443 /// predicates) to one (`T: Foo`) to many (`T: Bar<X = i32>` adds `T: Bar`
2444 /// and `<T as Bar>::X == i32`).
2445 fn predicates_from_bound<'tcx>(
2446 astconv: &dyn AstConv<'tcx>,
2448 bound: &'tcx hir::GenericBound<'tcx>,
2449 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2451 hir::GenericBound::Trait(ref tr, hir::TraitBoundModifier::None) => {
2452 let mut bounds = Bounds::default();
2453 let _ = astconv.instantiate_poly_trait_ref(tr, param_ty, &mut bounds);
2454 bounds.predicates(astconv.tcx(), param_ty)
2456 hir::GenericBound::Outlives(ref lifetime) => {
2457 let region = astconv.ast_region_to_region(lifetime, None);
2458 let pred = ty::Binder::bind(ty::OutlivesPredicate(param_ty, region));
2459 vec![(ty::Predicate::TypeOutlives(pred), lifetime.span)]
2461 hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => vec![],
2465 fn compute_sig_of_foreign_fn_decl<'tcx>(
2468 decl: &'tcx hir::FnDecl<'tcx>,
2470 ) -> ty::PolyFnSig<'tcx> {
2471 let unsafety = if abi == abi::Abi::RustIntrinsic {
2472 intrinsic_operation_unsafety(&tcx.item_name(def_id).as_str())
2474 hir::Unsafety::Unsafe
2476 let fty = AstConv::ty_of_fn(&ItemCtxt::new(tcx, def_id), unsafety, abi, decl, &[], None);
2478 // Feature gate SIMD types in FFI, since I am not sure that the
2479 // ABIs are handled at all correctly. -huonw
2480 if abi != abi::Abi::RustIntrinsic
2481 && abi != abi::Abi::PlatformIntrinsic
2482 && !tcx.features().simd_ffi
2484 let check = |ast_ty: &hir::Ty<'_>, ty: Ty<'_>| {
2490 "use of SIMD type `{}` in FFI is highly experimental and \
2491 may result in invalid code",
2492 tcx.hir().hir_to_pretty_string(ast_ty.hir_id)
2495 .help("add `#![feature(simd_ffi)]` to the crate attributes to enable")
2499 for (input, ty) in decl.inputs.iter().zip(*fty.inputs().skip_binder()) {
2502 if let hir::FunctionRetTy::Return(ref ty) = decl.output {
2503 check(&ty, *fty.output().skip_binder())
2510 fn is_foreign_item(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
2511 match tcx.hir().get_if_local(def_id) {
2512 Some(Node::ForeignItem(..)) => true,
2514 _ => bug!("is_foreign_item applied to non-local def-id {:?}", def_id),
2518 fn static_mutability(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::Mutability> {
2519 match tcx.hir().get_if_local(def_id) {
2520 Some(Node::Item(&hir::Item { kind: hir::ItemKind::Static(_, mutbl, _), .. }))
2521 | Some(Node::ForeignItem(&hir::ForeignItem {
2522 kind: hir::ForeignItemKind::Static(_, mutbl),
2526 _ => bug!("static_mutability applied to non-local def-id {:?}", def_id),
2530 fn from_target_feature(
2533 attr: &ast::Attribute,
2534 whitelist: &FxHashMap<String, Option<Symbol>>,
2535 target_features: &mut Vec<Symbol>,
2537 let list = match attr.meta_item_list() {
2541 let bad_item = |span| {
2542 let msg = "malformed `target_feature` attribute input";
2543 let code = "enable = \"..\"".to_owned();
2545 .struct_span_err(span, &msg)
2546 .span_suggestion(span, "must be of the form", code, Applicability::HasPlaceholders)
2549 let rust_features = tcx.features();
2551 // Only `enable = ...` is accepted in the meta-item list.
2552 if !item.check_name(sym::enable) {
2553 bad_item(item.span());
2557 // Must be of the form `enable = "..."` (a string).
2558 let value = match item.value_str() {
2559 Some(value) => value,
2561 bad_item(item.span());
2566 // We allow comma separation to enable multiple features.
2567 target_features.extend(value.as_str().split(',').filter_map(|feature| {
2568 // Only allow whitelisted features per platform.
2569 let feature_gate = match whitelist.get(feature) {
2573 format!("the feature named `{}` is not valid for this target", feature);
2574 let mut err = tcx.sess.struct_span_err(item.span(), &msg);
2577 format!("`{}` is not valid for this target", feature),
2579 if feature.starts_with("+") {
2580 let valid = whitelist.contains_key(&feature[1..]);
2582 err.help("consider removing the leading `+` in the feature name");
2590 // Only allow features whose feature gates have been enabled.
2591 let allowed = match feature_gate.as_ref().map(|s| *s) {
2592 Some(sym::arm_target_feature) => rust_features.arm_target_feature,
2593 Some(sym::aarch64_target_feature) => rust_features.aarch64_target_feature,
2594 Some(sym::hexagon_target_feature) => rust_features.hexagon_target_feature,
2595 Some(sym::powerpc_target_feature) => rust_features.powerpc_target_feature,
2596 Some(sym::mips_target_feature) => rust_features.mips_target_feature,
2597 Some(sym::avx512_target_feature) => rust_features.avx512_target_feature,
2598 Some(sym::mmx_target_feature) => rust_features.mmx_target_feature,
2599 Some(sym::sse4a_target_feature) => rust_features.sse4a_target_feature,
2600 Some(sym::tbm_target_feature) => rust_features.tbm_target_feature,
2601 Some(sym::wasm_target_feature) => rust_features.wasm_target_feature,
2602 Some(sym::cmpxchg16b_target_feature) => rust_features.cmpxchg16b_target_feature,
2603 Some(sym::adx_target_feature) => rust_features.adx_target_feature,
2604 Some(sym::movbe_target_feature) => rust_features.movbe_target_feature,
2605 Some(sym::rtm_target_feature) => rust_features.rtm_target_feature,
2606 Some(sym::f16c_target_feature) => rust_features.f16c_target_feature,
2607 Some(name) => bug!("unknown target feature gate {}", name),
2610 if !allowed && id.is_local() {
2611 feature_gate::feature_err(
2612 &tcx.sess.parse_sess,
2613 feature_gate.unwrap(),
2615 &format!("the target feature `{}` is currently unstable", feature),
2619 Some(Symbol::intern(feature))
2624 fn linkage_by_name(tcx: TyCtxt<'_>, def_id: DefId, name: &str) -> Linkage {
2625 use rustc::mir::mono::Linkage::*;
2627 // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
2628 // applicable to variable declarations and may not really make sense for
2629 // Rust code in the first place but whitelist them anyway and trust that
2630 // the user knows what s/he's doing. Who knows, unanticipated use cases
2631 // may pop up in the future.
2633 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
2634 // and don't have to be, LLVM treats them as no-ops.
2636 "appending" => Appending,
2637 "available_externally" => AvailableExternally,
2639 "extern_weak" => ExternalWeak,
2640 "external" => External,
2641 "internal" => Internal,
2642 "linkonce" => LinkOnceAny,
2643 "linkonce_odr" => LinkOnceODR,
2644 "private" => Private,
2646 "weak_odr" => WeakODR,
2648 let span = tcx.hir().span_if_local(def_id);
2649 if let Some(span) = span {
2650 tcx.sess.span_fatal(span, "invalid linkage specified")
2652 tcx.sess.fatal(&format!("invalid linkage specified: {}", name))
2658 fn codegen_fn_attrs(tcx: TyCtxt<'_>, id: DefId) -> CodegenFnAttrs {
2659 let attrs = tcx.get_attrs(id);
2661 let mut codegen_fn_attrs = CodegenFnAttrs::new();
2663 let whitelist = tcx.target_features_whitelist(LOCAL_CRATE);
2665 let mut inline_span = None;
2666 let mut link_ordinal_span = None;
2667 for attr in attrs.iter() {
2668 if attr.check_name(sym::cold) {
2669 codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD;
2670 } else if attr.check_name(sym::rustc_allocator) {
2671 codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR;
2672 } else if attr.check_name(sym::unwind) {
2673 codegen_fn_attrs.flags |= CodegenFnAttrFlags::UNWIND;
2674 } else if attr.check_name(sym::ffi_returns_twice) {
2675 if tcx.is_foreign_item(id) {
2676 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_RETURNS_TWICE;
2678 // `#[ffi_returns_twice]` is only allowed `extern fn`s.
2683 "`#[ffi_returns_twice]` may only be used on foreign functions"
2687 } else if attr.check_name(sym::rustc_allocator_nounwind) {
2688 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND;
2689 } else if attr.check_name(sym::naked) {
2690 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED;
2691 } else if attr.check_name(sym::no_mangle) {
2692 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2693 } else if attr.check_name(sym::rustc_std_internal_symbol) {
2694 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2695 } else if attr.check_name(sym::no_debug) {
2696 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_DEBUG;
2697 } else if attr.check_name(sym::used) {
2698 codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED;
2699 } else if attr.check_name(sym::thread_local) {
2700 codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL;
2701 } else if attr.check_name(sym::track_caller) {
2702 if tcx.fn_sig(id).abi() != abi::Abi::Rust {
2703 struct_span_err!(tcx.sess, attr.span, E0737, "`#[track_caller]` requires Rust ABI")
2706 codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
2707 } else if attr.check_name(sym::export_name) {
2708 if let Some(s) = attr.value_str() {
2709 if s.as_str().contains("\0") {
2710 // `#[export_name = ...]` will be converted to a null-terminated string,
2711 // so it may not contain any null characters.
2716 "`export_name` may not contain null characters"
2720 codegen_fn_attrs.export_name = Some(s);
2722 } else if attr.check_name(sym::target_feature) {
2723 if tcx.fn_sig(id).unsafety() == Unsafety::Normal {
2724 let msg = "`#[target_feature(..)]` can only be applied to `unsafe` functions";
2726 .struct_span_err(attr.span, msg)
2727 .span_label(attr.span, "can only be applied to `unsafe` functions")
2728 .span_label(tcx.def_span(id), "not an `unsafe` function")
2731 from_target_feature(tcx, id, attr, &whitelist, &mut codegen_fn_attrs.target_features);
2732 } else if attr.check_name(sym::linkage) {
2733 if let Some(val) = attr.value_str() {
2734 codegen_fn_attrs.linkage = Some(linkage_by_name(tcx, id, &val.as_str()));
2736 } else if attr.check_name(sym::link_section) {
2737 if let Some(val) = attr.value_str() {
2738 if val.as_str().bytes().any(|b| b == 0) {
2740 "illegal null byte in link_section \
2744 tcx.sess.span_err(attr.span, &msg);
2746 codegen_fn_attrs.link_section = Some(val);
2749 } else if attr.check_name(sym::link_name) {
2750 codegen_fn_attrs.link_name = attr.value_str();
2751 } else if attr.check_name(sym::link_ordinal) {
2752 link_ordinal_span = Some(attr.span);
2753 if let ordinal @ Some(_) = check_link_ordinal(tcx, attr) {
2754 codegen_fn_attrs.link_ordinal = ordinal;
2759 codegen_fn_attrs.inline = attrs.iter().fold(InlineAttr::None, |ia, attr| {
2760 if !attr.has_name(sym::inline) {
2763 match attr.meta().map(|i| i.kind) {
2764 Some(MetaItemKind::Word) => {
2768 Some(MetaItemKind::List(ref items)) => {
2770 inline_span = Some(attr.span);
2771 if items.len() != 1 {
2772 span_err!(tcx.sess.diagnostic(), attr.span, E0534, "expected one argument");
2774 } else if list_contains_name(&items[..], sym::always) {
2776 } else if list_contains_name(&items[..], sym::never) {
2779 span_err!(tcx.sess.diagnostic(), items[0].span(), E0535, "invalid argument");
2784 Some(MetaItemKind::NameValue(_)) => ia,
2789 codegen_fn_attrs.optimize = attrs.iter().fold(OptimizeAttr::None, |ia, attr| {
2790 if !attr.has_name(sym::optimize) {
2793 let err = |sp, s| span_err!(tcx.sess.diagnostic(), sp, E0722, "{}", s);
2794 match attr.meta().map(|i| i.kind) {
2795 Some(MetaItemKind::Word) => {
2796 err(attr.span, "expected one argument");
2799 Some(MetaItemKind::List(ref items)) => {
2801 inline_span = Some(attr.span);
2802 if items.len() != 1 {
2803 err(attr.span, "expected one argument");
2805 } else if list_contains_name(&items[..], sym::size) {
2807 } else if list_contains_name(&items[..], sym::speed) {
2810 err(items[0].span(), "invalid argument");
2814 Some(MetaItemKind::NameValue(_)) => ia,
2819 // If a function uses #[target_feature] it can't be inlined into general
2820 // purpose functions as they wouldn't have the right target features
2821 // enabled. For that reason we also forbid #[inline(always)] as it can't be
2824 if codegen_fn_attrs.target_features.len() > 0 {
2825 if codegen_fn_attrs.inline == InlineAttr::Always {
2826 if let Some(span) = inline_span {
2829 "cannot use `#[inline(always)]` with \
2830 `#[target_feature]`",
2836 // Weak lang items have the same semantics as "std internal" symbols in the
2837 // sense that they're preserved through all our LTO passes and only
2838 // strippable by the linker.
2840 // Additionally weak lang items have predetermined symbol names.
2841 if tcx.is_weak_lang_item(id) {
2842 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2844 if let Some(name) = weak_lang_items::link_name(&attrs) {
2845 codegen_fn_attrs.export_name = Some(name);
2846 codegen_fn_attrs.link_name = Some(name);
2848 check_link_name_xor_ordinal(tcx, &codegen_fn_attrs, link_ordinal_span);
2850 // Internal symbols to the standard library all have no_mangle semantics in
2851 // that they have defined symbol names present in the function name. This
2852 // also applies to weak symbols where they all have known symbol names.
2853 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
2854 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2860 fn check_link_ordinal(tcx: TyCtxt<'_>, attr: &ast::Attribute) -> Option<usize> {
2861 use syntax::ast::{Lit, LitIntType, LitKind};
2862 let meta_item_list = attr.meta_item_list();
2863 let meta_item_list: Option<&[ast::NestedMetaItem]> = meta_item_list.as_ref().map(Vec::as_ref);
2864 let sole_meta_list = match meta_item_list {
2865 Some([item]) => item.literal(),
2868 if let Some(Lit { kind: LitKind::Int(ordinal, LitIntType::Unsuffixed), .. }) = sole_meta_list {
2869 if *ordinal <= std::usize::MAX as u128 {
2870 Some(*ordinal as usize)
2872 let msg = format!("ordinal value in `link_ordinal` is too large: `{}`", &ordinal);
2874 .struct_span_err(attr.span, &msg)
2875 .note("the value may not exceed `std::usize::MAX`")
2881 .struct_span_err(attr.span, "illegal ordinal format in `link_ordinal`")
2882 .note("an unsuffixed integer value, e.g., `1`, is expected")
2888 fn check_link_name_xor_ordinal(
2890 codegen_fn_attrs: &CodegenFnAttrs,
2891 inline_span: Option<Span>,
2893 if codegen_fn_attrs.link_name.is_none() || codegen_fn_attrs.link_ordinal.is_none() {
2896 let msg = "cannot use `#[link_name]` with `#[link_ordinal]`";
2897 if let Some(span) = inline_span {
2898 tcx.sess.span_err(span, msg);