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 errors::{struct_span_err, Applicability, StashKey};
24 use rustc::hir::map::Map;
25 use rustc::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
26 use rustc::mir::mono::Linkage;
28 use rustc::ty::query::Providers;
29 use rustc::ty::subst::GenericArgKind;
30 use rustc::ty::subst::{InternalSubsts, Subst};
31 use rustc::ty::util::Discr;
32 use rustc::ty::util::IntTypeExt;
33 use rustc::ty::{self, AdtKind, Const, DefIdTree, ToPolyTraitRef, Ty, TyCtxt};
34 use rustc::ty::{ReprOptions, ToPredicate};
35 use rustc_data_structures::captures::Captures;
36 use rustc_data_structures::fx::FxHashMap;
38 use rustc_hir::def::{CtorKind, DefKind, Res};
39 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
40 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
41 use rustc_hir::{GenericParamKind, Node, Unsafety};
42 use rustc_span::symbol::{kw, sym, Symbol};
43 use rustc_span::{Span, DUMMY_SP};
44 use rustc_target::spec::abi;
46 use syntax::ast::{Ident, MetaItemKind};
47 use syntax::attr::{list_contains_name, mark_used, InlineAttr, OptimizeAttr};
48 use syntax::feature_gate;
50 use rustc_error_codes::*;
52 struct OnlySelfBounds(bool);
54 ///////////////////////////////////////////////////////////////////////////
57 fn collect_mod_item_types(tcx: TyCtxt<'_>, module_def_id: DefId) {
58 tcx.hir().visit_item_likes_in_module(
60 &mut CollectItemTypesVisitor { tcx }.as_deep_visitor(),
64 pub fn provide(providers: &mut Providers<'_>) {
65 *providers = Providers {
69 predicates_defined_on,
70 explicit_predicates_of,
72 type_param_predicates,
81 collect_mod_item_types,
86 ///////////////////////////////////////////////////////////////////////////
88 /// Context specific to some particular item. This is what implements
89 /// `AstConv`. It has information about the predicates that are defined
90 /// on the trait. Unfortunately, this predicate information is
91 /// available in various different forms at various points in the
92 /// process. So we can't just store a pointer to e.g., the AST or the
93 /// parsed ty form, we have to be more flexible. To this end, the
94 /// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy
95 /// `get_type_parameter_bounds` requests, drawing the information from
96 /// the AST (`hir::Generics`), recursively.
97 pub struct ItemCtxt<'tcx> {
102 ///////////////////////////////////////////////////////////////////////////
105 crate struct PlaceholderHirTyCollector(crate Vec<Span>);
107 impl<'v> Visitor<'v> for PlaceholderHirTyCollector {
110 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
111 NestedVisitorMap::None
113 fn visit_ty(&mut self, t: &'v hir::Ty<'v>) {
114 if let hir::TyKind::Infer = t.kind {
117 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 type Map = Map<'tcx>;
193 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
194 NestedVisitorMap::OnlyBodies(&self.tcx.hir())
197 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
198 convert_item(self.tcx, item.hir_id);
199 reject_placeholder_type_signatures_in_item(self.tcx, item);
200 intravisit::walk_item(self, item);
203 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
204 for param in generics.params {
206 hir::GenericParamKind::Lifetime { .. } => {}
207 hir::GenericParamKind::Type { default: Some(_), .. } => {
208 let def_id = self.tcx.hir().local_def_id(param.hir_id);
209 self.tcx.type_of(def_id);
211 hir::GenericParamKind::Type { .. } => {}
212 hir::GenericParamKind::Const { .. } => {
213 let def_id = self.tcx.hir().local_def_id(param.hir_id);
214 self.tcx.type_of(def_id);
218 intravisit::walk_generics(self, generics);
221 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
222 if let hir::ExprKind::Closure(..) = expr.kind {
223 let def_id = self.tcx.hir().local_def_id(expr.hir_id);
224 self.tcx.generics_of(def_id);
225 self.tcx.type_of(def_id);
227 intravisit::walk_expr(self, expr);
230 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
231 convert_trait_item(self.tcx, trait_item.hir_id);
232 intravisit::walk_trait_item(self, trait_item);
235 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
236 convert_impl_item(self.tcx, impl_item.hir_id);
237 intravisit::walk_impl_item(self, impl_item);
241 ///////////////////////////////////////////////////////////////////////////
242 // Utility types and common code for the above passes.
244 fn bad_placeholder_type(
246 mut spans: Vec<Span>,
247 ) -> errors::DiagnosticBuilder<'tcx> {
249 let mut err = struct_span_err!(
253 "the type placeholder `_` is not allowed within types on item signatures",
256 err.span_label(span, "not allowed in type signatures");
261 impl ItemCtxt<'tcx> {
262 pub fn new(tcx: TyCtxt<'tcx>, item_def_id: DefId) -> ItemCtxt<'tcx> {
263 ItemCtxt { tcx, item_def_id }
266 pub fn to_ty(&self, ast_ty: &'tcx hir::Ty<'tcx>) -> Ty<'tcx> {
267 AstConv::ast_ty_to_ty(self, ast_ty)
271 impl AstConv<'tcx> for ItemCtxt<'tcx> {
272 fn tcx(&self) -> TyCtxt<'tcx> {
276 fn item_def_id(&self) -> Option<DefId> {
277 Some(self.item_def_id)
280 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId) -> ty::GenericPredicates<'tcx> {
281 self.tcx.at(span).type_param_predicates((self.item_def_id, def_id))
284 fn re_infer(&self, _: Option<&ty::GenericParamDef>, _: Span) -> Option<ty::Region<'tcx>> {
288 fn allow_ty_infer(&self) -> bool {
292 fn ty_infer(&self, _: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx> {
293 self.tcx().sess.delay_span_bug(span, "bad placeholder type");
300 _: Option<&ty::GenericParamDef>,
302 ) -> &'tcx Const<'tcx> {
303 bad_placeholder_type(self.tcx(), vec![span]).emit();
305 self.tcx().consts.err
308 fn projected_ty_from_poly_trait_ref(
312 item_segment: &hir::PathSegment<'_>,
313 poly_trait_ref: ty::PolyTraitRef<'tcx>,
315 if let Some(trait_ref) = poly_trait_ref.no_bound_vars() {
316 let item_substs = <dyn AstConv<'tcx>>::create_substs_for_associated_item(
324 self.tcx().mk_projection(item_def_id, item_substs)
326 // There are no late-bound regions; we can just ignore the binder.
331 "cannot extract an associated type from a higher-ranked trait bound \
339 fn normalize_ty(&self, _span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
340 // Types in item signatures are not normalized to avoid undue dependencies.
344 fn set_tainted_by_errors(&self) {
345 // There's no obvious place to track this, so just let it go.
348 fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) {
349 // There's no place to record types from signatures?
353 /// Returns the predicates defined on `item_def_id` of the form
354 /// `X: Foo` where `X` is the type parameter `def_id`.
355 fn type_param_predicates(
357 (item_def_id, def_id): (DefId, DefId),
358 ) -> ty::GenericPredicates<'_> {
361 // In the AST, bounds can derive from two places. Either
362 // written inline like `<T: Foo>` or in a where-clause like
365 let param_id = tcx.hir().as_local_hir_id(def_id).unwrap();
366 let param_owner = tcx.hir().ty_param_owner(param_id);
367 let param_owner_def_id = tcx.hir().local_def_id(param_owner);
368 let generics = tcx.generics_of(param_owner_def_id);
369 let index = generics.param_def_id_to_index[&def_id];
370 let ty = tcx.mk_ty_param(index, tcx.hir().ty_param_name(param_id));
372 // Don't look for bounds where the type parameter isn't in scope.
374 if item_def_id == param_owner_def_id { None } else { tcx.generics_of(item_def_id).parent };
376 let mut result = parent
378 let icx = ItemCtxt::new(tcx, parent);
379 icx.get_type_parameter_bounds(DUMMY_SP, def_id)
381 .unwrap_or_default();
382 let mut extend = None;
384 let item_hir_id = tcx.hir().as_local_hir_id(item_def_id).unwrap();
385 let ast_generics = match tcx.hir().get(item_hir_id) {
386 Node::TraitItem(item) => &item.generics,
388 Node::ImplItem(item) => &item.generics,
390 Node::Item(item) => {
392 ItemKind::Fn(.., ref generics, _)
393 | ItemKind::Impl(_, _, _, ref generics, ..)
394 | ItemKind::TyAlias(_, ref generics)
395 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
396 | ItemKind::Enum(_, ref generics)
397 | ItemKind::Struct(_, ref generics)
398 | ItemKind::Union(_, ref generics) => generics,
399 ItemKind::Trait(_, _, ref generics, ..) => {
400 // Implied `Self: Trait` and supertrait bounds.
401 if param_id == item_hir_id {
402 let identity_trait_ref = ty::TraitRef::identity(tcx, item_def_id);
403 extend = Some((identity_trait_ref.to_predicate(), item.span));
411 Node::ForeignItem(item) => match item.kind {
412 ForeignItemKind::Fn(_, _, ref generics) => generics,
419 let icx = ItemCtxt::new(tcx, item_def_id);
420 let extra_predicates = extend.into_iter().chain(
421 icx.type_parameter_bounds_in_generics(ast_generics, param_id, ty, OnlySelfBounds(true))
423 .filter(|(predicate, _)| match predicate {
424 ty::Predicate::Trait(ref data) => data.skip_binder().self_ty().is_param(index),
429 tcx.arena.alloc_from_iter(result.predicates.iter().copied().chain(extra_predicates));
433 impl ItemCtxt<'tcx> {
434 /// Finds bounds from `hir::Generics`. This requires scanning through the
435 /// AST. We do this to avoid having to convert *all* the bounds, which
436 /// would create artificial cycles. Instead, we can only convert the
437 /// bounds for a type parameter `X` if `X::Foo` is used.
438 fn type_parameter_bounds_in_generics(
440 ast_generics: &'tcx hir::Generics<'tcx>,
441 param_id: hir::HirId,
443 only_self_bounds: OnlySelfBounds,
444 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
445 let from_ty_params = ast_generics
448 .filter_map(|param| match param.kind {
449 GenericParamKind::Type { .. } if param.hir_id == param_id => Some(¶m.bounds),
452 .flat_map(|bounds| bounds.iter())
453 .flat_map(|b| predicates_from_bound(self, ty, b));
455 let from_where_clauses = ast_generics
459 .filter_map(|wp| match *wp {
460 hir::WherePredicate::BoundPredicate(ref bp) => Some(bp),
464 let bt = if is_param(self.tcx, &bp.bounded_ty, param_id) {
466 } else if !only_self_bounds.0 {
467 Some(self.to_ty(&bp.bounded_ty))
471 bp.bounds.iter().filter_map(move |b| bt.map(|bt| (bt, b)))
473 .flat_map(|(bt, b)| predicates_from_bound(self, bt, b));
475 from_ty_params.chain(from_where_clauses).collect()
479 /// Tests whether this is the AST for a reference to the type
480 /// parameter with ID `param_id`. We use this so as to avoid running
481 /// `ast_ty_to_ty`, because we want to avoid triggering an all-out
482 /// conversion of the type to avoid inducing unnecessary cycles.
483 fn is_param(tcx: TyCtxt<'_>, ast_ty: &hir::Ty<'_>, param_id: hir::HirId) -> bool {
484 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = ast_ty.kind {
486 Res::SelfTy(Some(def_id), None) | Res::Def(DefKind::TyParam, def_id) => {
487 def_id == tcx.hir().local_def_id(param_id)
496 fn convert_item(tcx: TyCtxt<'_>, item_id: hir::HirId) {
497 let it = tcx.hir().expect_item(item_id);
498 debug!("convert: item {} with id {}", it.ident, it.hir_id);
499 let def_id = tcx.hir().local_def_id(item_id);
501 // These don't define types.
502 hir::ItemKind::ExternCrate(_)
503 | hir::ItemKind::Use(..)
504 | hir::ItemKind::Mod(_)
505 | hir::ItemKind::GlobalAsm(_) => {}
506 hir::ItemKind::ForeignMod(ref foreign_mod) => {
507 for item in foreign_mod.items {
508 let def_id = tcx.hir().local_def_id(item.hir_id);
509 tcx.generics_of(def_id);
511 tcx.predicates_of(def_id);
512 if let hir::ForeignItemKind::Fn(..) = item.kind {
517 hir::ItemKind::Enum(ref enum_definition, _) => {
518 tcx.generics_of(def_id);
520 tcx.predicates_of(def_id);
521 convert_enum_variant_types(tcx, def_id, &enum_definition.variants);
523 hir::ItemKind::Impl(..) => {
524 tcx.generics_of(def_id);
526 tcx.impl_trait_ref(def_id);
527 tcx.predicates_of(def_id);
529 hir::ItemKind::Trait(..) => {
530 tcx.generics_of(def_id);
531 tcx.trait_def(def_id);
532 tcx.at(it.span).super_predicates_of(def_id);
533 tcx.predicates_of(def_id);
535 hir::ItemKind::TraitAlias(..) => {
536 tcx.generics_of(def_id);
537 tcx.at(it.span).super_predicates_of(def_id);
538 tcx.predicates_of(def_id);
540 hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
541 tcx.generics_of(def_id);
543 tcx.predicates_of(def_id);
545 for f in struct_def.fields() {
546 let def_id = tcx.hir().local_def_id(f.hir_id);
547 tcx.generics_of(def_id);
549 tcx.predicates_of(def_id);
552 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
553 convert_variant_ctor(tcx, ctor_hir_id);
557 // Desugared from `impl Trait`, so visited by the function's return type.
558 hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: Some(_), .. }) => {}
560 hir::ItemKind::OpaqueTy(..)
561 | hir::ItemKind::TyAlias(..)
562 | hir::ItemKind::Static(..)
563 | hir::ItemKind::Const(..)
564 | hir::ItemKind::Fn(..) => {
565 tcx.generics_of(def_id);
567 tcx.predicates_of(def_id);
568 if let hir::ItemKind::Fn(..) = it.kind {
575 fn convert_trait_item(tcx: TyCtxt<'_>, trait_item_id: hir::HirId) {
576 let trait_item = tcx.hir().expect_trait_item(trait_item_id);
577 let def_id = tcx.hir().local_def_id(trait_item.hir_id);
578 tcx.generics_of(def_id);
580 match trait_item.kind {
581 hir::TraitItemKind::Const(..)
582 | hir::TraitItemKind::Type(_, Some(_))
583 | hir::TraitItemKind::Method(..) => {
585 if let hir::TraitItemKind::Method(..) = trait_item.kind {
590 hir::TraitItemKind::Type(_, None) => {}
593 tcx.predicates_of(def_id);
596 fn convert_impl_item(tcx: TyCtxt<'_>, impl_item_id: hir::HirId) {
597 let def_id = tcx.hir().local_def_id(impl_item_id);
598 tcx.generics_of(def_id);
600 tcx.predicates_of(def_id);
601 if let hir::ImplItemKind::Method(..) = tcx.hir().expect_impl_item(impl_item_id).kind {
606 fn convert_variant_ctor(tcx: TyCtxt<'_>, ctor_id: hir::HirId) {
607 let def_id = tcx.hir().local_def_id(ctor_id);
608 tcx.generics_of(def_id);
610 tcx.predicates_of(def_id);
613 fn convert_enum_variant_types(tcx: TyCtxt<'_>, def_id: DefId, variants: &[hir::Variant<'_>]) {
614 let def = tcx.adt_def(def_id);
615 let repr_type = def.repr.discr_type();
616 let initial = repr_type.initial_discriminant(tcx);
617 let mut prev_discr = None::<Discr<'_>>;
619 // fill the discriminant values and field types
620 for variant in variants {
621 let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
623 if let Some(ref e) = variant.disr_expr {
624 let expr_did = tcx.hir().local_def_id(e.hir_id);
625 def.eval_explicit_discr(tcx, expr_did)
626 } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) {
629 struct_span_err!(tcx.sess, variant.span, E0370, "enum discriminant overflowed")
632 format!("overflowed on value after {}", prev_discr.unwrap()),
635 "explicitly set `{} = {}` if that is desired outcome",
636 variant.ident, wrapped_discr
641 .unwrap_or(wrapped_discr),
644 for f in variant.data.fields() {
645 let def_id = tcx.hir().local_def_id(f.hir_id);
646 tcx.generics_of(def_id);
648 tcx.predicates_of(def_id);
651 // Convert the ctor, if any. This also registers the variant as
653 if let Some(ctor_hir_id) = variant.data.ctor_hir_id() {
654 convert_variant_ctor(tcx, ctor_hir_id);
661 variant_did: Option<DefId>,
662 ctor_did: Option<DefId>,
664 discr: ty::VariantDiscr,
665 def: &hir::VariantData<'_>,
666 adt_kind: ty::AdtKind,
668 ) -> ty::VariantDef {
669 let mut seen_fields: FxHashMap<ast::Ident, Span> = Default::default();
670 let hir_id = tcx.hir().as_local_hir_id(variant_did.unwrap_or(parent_did)).unwrap();
675 let fid = tcx.hir().local_def_id(f.hir_id);
676 let dup_span = seen_fields.get(&f.ident.modern()).cloned();
677 if let Some(prev_span) = dup_span {
682 "field `{}` is already declared",
685 .span_label(f.span, "field already declared")
686 .span_label(prev_span, format!("`{}` first declared here", f.ident))
689 seen_fields.insert(f.ident.modern(), f.span);
695 vis: ty::Visibility::from_hir(&f.vis, hir_id, tcx),
699 let recovered = match def {
700 hir::VariantData::Struct(_, r) => *r,
710 CtorKind::from_hir(def),
717 fn adt_def(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::AdtDef {
720 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
721 let item = match tcx.hir().get(hir_id) {
722 Node::Item(item) => item,
726 let repr = ReprOptions::new(tcx, def_id);
727 let (kind, variants) = match item.kind {
728 ItemKind::Enum(ref def, _) => {
729 let mut distance_from_explicit = 0;
734 let variant_did = Some(tcx.hir().local_def_id(v.id));
736 v.data.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
738 let discr = if let Some(ref e) = v.disr_expr {
739 distance_from_explicit = 0;
740 ty::VariantDiscr::Explicit(tcx.hir().local_def_id(e.hir_id))
742 ty::VariantDiscr::Relative(distance_from_explicit)
744 distance_from_explicit += 1;
759 (AdtKind::Enum, variants)
761 ItemKind::Struct(ref def, _) => {
762 let variant_did = None;
763 let ctor_did = def.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
765 let variants = std::iter::once(convert_variant(
770 ty::VariantDiscr::Relative(0),
777 (AdtKind::Struct, variants)
779 ItemKind::Union(ref def, _) => {
780 let variant_did = None;
781 let ctor_did = def.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
783 let variants = std::iter::once(convert_variant(
788 ty::VariantDiscr::Relative(0),
795 (AdtKind::Union, variants)
799 tcx.alloc_adt_def(def_id, kind, variants, repr)
802 /// Ensures that the super-predicates of the trait with a `DefId`
803 /// of `trait_def_id` are converted and stored. This also ensures that
804 /// the transitive super-predicates are converted.
805 fn super_predicates_of(tcx: TyCtxt<'_>, trait_def_id: DefId) -> ty::GenericPredicates<'_> {
806 debug!("super_predicates(trait_def_id={:?})", trait_def_id);
807 let trait_hir_id = tcx.hir().as_local_hir_id(trait_def_id).unwrap();
809 let item = match tcx.hir().get(trait_hir_id) {
810 Node::Item(item) => item,
811 _ => bug!("trait_node_id {} is not an item", trait_hir_id),
814 let (generics, bounds) = match item.kind {
815 hir::ItemKind::Trait(.., ref generics, ref supertraits, _) => (generics, supertraits),
816 hir::ItemKind::TraitAlias(ref generics, ref supertraits) => (generics, supertraits),
817 _ => span_bug!(item.span, "super_predicates invoked on non-trait"),
820 let icx = ItemCtxt::new(tcx, trait_def_id);
822 // Convert the bounds that follow the colon, e.g., `Bar + Zed` in `trait Foo: Bar + Zed`.
823 let self_param_ty = tcx.types.self_param;
825 AstConv::compute_bounds(&icx, self_param_ty, bounds, SizedByDefault::No, item.span);
827 let superbounds1 = superbounds1.predicates(tcx, self_param_ty);
829 // Convert any explicit superbounds in the where-clause,
830 // e.g., `trait Foo where Self: Bar`.
831 // In the case of trait aliases, however, we include all bounds in the where-clause,
832 // so e.g., `trait Foo = where u32: PartialEq<Self>` would include `u32: PartialEq<Self>`
833 // as one of its "superpredicates".
834 let is_trait_alias = tcx.is_trait_alias(trait_def_id);
835 let superbounds2 = icx.type_parameter_bounds_in_generics(
839 OnlySelfBounds(!is_trait_alias),
842 // Combine the two lists to form the complete set of superbounds:
843 let superbounds = &*tcx.arena.alloc_from_iter(superbounds1.into_iter().chain(superbounds2));
845 // Now require that immediate supertraits are converted,
846 // which will, in turn, reach indirect supertraits.
847 for &(pred, span) in superbounds {
848 debug!("superbound: {:?}", pred);
849 if let ty::Predicate::Trait(bound) = pred {
850 tcx.at(span).super_predicates_of(bound.def_id());
854 ty::GenericPredicates { parent: None, predicates: superbounds }
857 fn trait_def(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::TraitDef {
858 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
859 let item = tcx.hir().expect_item(hir_id);
861 let (is_auto, unsafety) = match item.kind {
862 hir::ItemKind::Trait(is_auto, unsafety, ..) => (is_auto == hir::IsAuto::Yes, unsafety),
863 hir::ItemKind::TraitAlias(..) => (false, hir::Unsafety::Normal),
864 _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
867 let paren_sugar = tcx.has_attr(def_id, sym::rustc_paren_sugar);
868 if paren_sugar && !tcx.features().unboxed_closures {
872 "the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \
873 which traits can use parenthetical notation",
875 .help("add `#![feature(unboxed_closures)]` to 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 type Map = Map<'tcx>;
895 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
896 NestedVisitorMap::None
899 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
900 if self.has_late_bound_regions.is_some() {
904 hir::TyKind::BareFn(..) => {
905 self.outer_index.shift_in(1);
906 intravisit::walk_ty(self, ty);
907 self.outer_index.shift_out(1);
909 _ => intravisit::walk_ty(self, ty),
913 fn visit_poly_trait_ref(
915 tr: &'tcx hir::PolyTraitRef<'tcx>,
916 m: hir::TraitBoundModifier,
918 if self.has_late_bound_regions.is_some() {
921 self.outer_index.shift_in(1);
922 intravisit::walk_poly_trait_ref(self, tr, m);
923 self.outer_index.shift_out(1);
926 fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
927 if self.has_late_bound_regions.is_some() {
931 match self.tcx.named_region(lt.hir_id) {
932 Some(rl::Region::Static) | Some(rl::Region::EarlyBound(..)) => {}
933 Some(rl::Region::LateBound(debruijn, _, _))
934 | Some(rl::Region::LateBoundAnon(debruijn, _))
935 if debruijn < self.outer_index => {}
936 Some(rl::Region::LateBound(..))
937 | Some(rl::Region::LateBoundAnon(..))
938 | Some(rl::Region::Free(..))
940 self.has_late_bound_regions = Some(lt.span);
946 fn has_late_bound_regions<'tcx>(
948 generics: &'tcx hir::Generics<'tcx>,
949 decl: &'tcx hir::FnDecl<'tcx>,
951 let mut visitor = LateBoundRegionsDetector {
953 outer_index: ty::INNERMOST,
954 has_late_bound_regions: None,
956 for param in generics.params {
957 if let GenericParamKind::Lifetime { .. } = param.kind {
958 if tcx.is_late_bound(param.hir_id) {
959 return Some(param.span);
963 visitor.visit_fn_decl(decl);
964 visitor.has_late_bound_regions
968 Node::TraitItem(item) => match item.kind {
969 hir::TraitItemKind::Method(ref sig, _) => {
970 has_late_bound_regions(tcx, &item.generics, &sig.decl)
974 Node::ImplItem(item) => match item.kind {
975 hir::ImplItemKind::Method(ref sig, _) => {
976 has_late_bound_regions(tcx, &item.generics, &sig.decl)
980 Node::ForeignItem(item) => match item.kind {
981 hir::ForeignItemKind::Fn(ref fn_decl, _, ref generics) => {
982 has_late_bound_regions(tcx, generics, fn_decl)
986 Node::Item(item) => match item.kind {
987 hir::ItemKind::Fn(ref sig, .., ref generics, _) => {
988 has_late_bound_regions(tcx, generics, &sig.decl)
996 fn generics_of(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::Generics {
999 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1001 let node = tcx.hir().get(hir_id);
1002 let parent_def_id = match node {
1004 | Node::TraitItem(_)
1007 | Node::Field(_) => {
1008 let parent_id = tcx.hir().get_parent_item(hir_id);
1009 Some(tcx.hir().local_def_id(parent_id))
1011 // FIXME(#43408) enable this always when we get lazy normalization.
1012 Node::AnonConst(_) => {
1013 // HACK(eddyb) this provides the correct generics when
1014 // `feature(const_generics)` is enabled, so that const expressions
1015 // used with const generics, e.g. `Foo<{N+1}>`, can work at all.
1016 if tcx.features().const_generics {
1017 let parent_id = tcx.hir().get_parent_item(hir_id);
1018 Some(tcx.hir().local_def_id(parent_id))
1023 Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => {
1024 Some(tcx.closure_base_def_id(def_id))
1026 Node::Item(item) => match item.kind {
1027 ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn, .. }) => impl_trait_fn,
1033 let mut opt_self = None;
1034 let mut allow_defaults = false;
1036 let no_generics = hir::Generics::empty();
1037 let ast_generics = match node {
1038 Node::TraitItem(item) => &item.generics,
1040 Node::ImplItem(item) => &item.generics,
1042 Node::Item(item) => {
1044 ItemKind::Fn(.., ref generics, _) | ItemKind::Impl(_, _, _, ref generics, ..) => {
1048 ItemKind::TyAlias(_, ref generics)
1049 | ItemKind::Enum(_, ref generics)
1050 | ItemKind::Struct(_, ref generics)
1051 | ItemKind::OpaqueTy(hir::OpaqueTy { ref generics, .. })
1052 | ItemKind::Union(_, ref generics) => {
1053 allow_defaults = true;
1057 ItemKind::Trait(_, _, ref generics, ..)
1058 | ItemKind::TraitAlias(ref generics, ..) => {
1059 // Add in the self type parameter.
1061 // Something of a hack: use the node id for the trait, also as
1062 // the node id for the Self type parameter.
1063 let param_id = item.hir_id;
1065 opt_self = Some(ty::GenericParamDef {
1067 name: kw::SelfUpper,
1068 def_id: tcx.hir().local_def_id(param_id),
1069 pure_wrt_drop: false,
1070 kind: ty::GenericParamDefKind::Type {
1072 object_lifetime_default: rl::Set1::Empty,
1077 allow_defaults = true;
1085 Node::ForeignItem(item) => match item.kind {
1086 ForeignItemKind::Static(..) => &no_generics,
1087 ForeignItemKind::Fn(_, _, ref generics) => generics,
1088 ForeignItemKind::Type => &no_generics,
1094 let has_self = opt_self.is_some();
1095 let mut parent_has_self = false;
1096 let mut own_start = has_self as u32;
1097 let parent_count = parent_def_id.map_or(0, |def_id| {
1098 let generics = tcx.generics_of(def_id);
1099 assert_eq!(has_self, false);
1100 parent_has_self = generics.has_self;
1101 own_start = generics.count() as u32;
1102 generics.parent_count + generics.params.len()
1105 let mut params: Vec<_> = opt_self.into_iter().collect();
1107 let early_lifetimes = early_bound_lifetimes_from_generics(tcx, ast_generics);
1108 params.extend(early_lifetimes.enumerate().map(|(i, param)| ty::GenericParamDef {
1109 name: param.name.ident().name,
1110 index: own_start + i as u32,
1111 def_id: tcx.hir().local_def_id(param.hir_id),
1112 pure_wrt_drop: param.pure_wrt_drop,
1113 kind: ty::GenericParamDefKind::Lifetime,
1116 let object_lifetime_defaults = tcx.object_lifetime_defaults(hir_id);
1118 // Now create the real type parameters.
1119 let type_start = own_start - has_self as u32 + params.len() as u32;
1121 params.extend(ast_generics.params.iter().filter_map(|param| {
1122 let kind = match param.kind {
1123 GenericParamKind::Type { ref default, synthetic, .. } => {
1124 if !allow_defaults && default.is_some() {
1125 if !tcx.features().default_type_parameter_fallback {
1127 lint::builtin::INVALID_TYPE_PARAM_DEFAULT,
1131 "defaults for type parameters are only allowed in \
1132 `struct`, `enum`, `type`, or `trait` definitions."
1138 ty::GenericParamDefKind::Type {
1139 has_default: default.is_some(),
1140 object_lifetime_default: object_lifetime_defaults
1142 .map_or(rl::Set1::Empty, |o| o[i]),
1146 GenericParamKind::Const { .. } => ty::GenericParamDefKind::Const,
1150 let param_def = ty::GenericParamDef {
1151 index: type_start + i as u32,
1152 name: param.name.ident().name,
1153 def_id: tcx.hir().local_def_id(param.hir_id),
1154 pure_wrt_drop: param.pure_wrt_drop,
1161 // provide junk type parameter defs - the only place that
1162 // cares about anything but the length is instantiation,
1163 // and we don't do that for closures.
1164 if let Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(.., gen), .. }) = node {
1165 let dummy_args = if gen.is_some() {
1166 &["<yield_ty>", "<return_ty>", "<witness>"][..]
1168 &["<closure_kind>", "<closure_signature>"][..]
1171 params.extend(dummy_args.iter().enumerate().map(|(i, &arg)| ty::GenericParamDef {
1172 index: type_start + i as u32,
1173 name: Symbol::intern(arg),
1175 pure_wrt_drop: false,
1176 kind: ty::GenericParamDefKind::Type {
1178 object_lifetime_default: rl::Set1::Empty,
1183 if let Some(upvars) = tcx.upvars(def_id) {
1184 params.extend(upvars.iter().zip((dummy_args.len() as u32)..).map(|(_, i)| {
1185 ty::GenericParamDef {
1186 index: type_start + i,
1187 name: Symbol::intern("<upvar>"),
1189 pure_wrt_drop: false,
1190 kind: ty::GenericParamDefKind::Type {
1192 object_lifetime_default: rl::Set1::Empty,
1200 let param_def_id_to_index = params.iter().map(|param| (param.def_id, param.index)).collect();
1202 tcx.arena.alloc(ty::Generics {
1203 parent: parent_def_id,
1206 param_def_id_to_index,
1207 has_self: has_self || parent_has_self,
1208 has_late_bound_regions: has_late_bound_regions(tcx, node),
1212 fn report_assoc_ty_on_inherent_impl(tcx: TyCtxt<'_>, span: Span) {
1217 "associated types are not yet supported in inherent impls (see #8995)"
1222 fn infer_placeholder_type(
1225 body_id: hir::BodyId,
1229 let ty = tcx.diagnostic_only_typeck_tables_of(def_id).node_type(body_id.hir_id);
1231 // If this came from a free `const` or `static mut?` item,
1232 // then the user may have written e.g. `const A = 42;`.
1233 // In this case, the parser has stashed a diagnostic for
1234 // us to improve in typeck so we do that now.
1235 match tcx.sess.diagnostic().steal_diagnostic(span, StashKey::ItemNoType) {
1237 // The parser provided a sub-optimal `HasPlaceholders` suggestion for the type.
1238 // We are typeck and have the real type, so remove that and suggest the actual type.
1239 err.suggestions.clear();
1240 err.span_suggestion(
1242 "provide a type for the item",
1243 format!("{}: {}", item_ident, ty),
1244 Applicability::MachineApplicable,
1249 let mut diag = bad_placeholder_type(tcx, vec![span]);
1250 if ty != tcx.types.err {
1251 diag.span_suggestion(
1253 "replace `_` with the correct type",
1255 Applicability::MaybeIncorrect,
1265 fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> {
1268 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1270 let icx = ItemCtxt::new(tcx, def_id);
1272 match tcx.hir().get(hir_id) {
1273 Node::TraitItem(item) => match item.kind {
1274 TraitItemKind::Method(..) => {
1275 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1276 tcx.mk_fn_def(def_id, substs)
1278 TraitItemKind::Const(ref ty, body_id) => body_id
1279 .and_then(|body_id| {
1280 if is_suggestable_infer_ty(ty) {
1281 Some(infer_placeholder_type(tcx, def_id, body_id, ty.span, item.ident))
1286 .unwrap_or_else(|| icx.to_ty(ty)),
1287 TraitItemKind::Type(_, Some(ref ty)) => icx.to_ty(ty),
1288 TraitItemKind::Type(_, None) => {
1289 span_bug!(item.span, "associated type missing default");
1293 Node::ImplItem(item) => match item.kind {
1294 ImplItemKind::Method(..) => {
1295 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1296 tcx.mk_fn_def(def_id, substs)
1298 ImplItemKind::Const(ref ty, body_id) => {
1299 if is_suggestable_infer_ty(ty) {
1300 infer_placeholder_type(tcx, def_id, body_id, ty.span, item.ident)
1305 ImplItemKind::OpaqueTy(_) => {
1306 if tcx.impl_trait_ref(tcx.hir().get_parent_did(hir_id)).is_none() {
1307 report_assoc_ty_on_inherent_impl(tcx, item.span);
1310 find_opaque_ty_constraints(tcx, def_id)
1312 ImplItemKind::TyAlias(ref ty) => {
1313 if tcx.impl_trait_ref(tcx.hir().get_parent_did(hir_id)).is_none() {
1314 report_assoc_ty_on_inherent_impl(tcx, item.span);
1321 Node::Item(item) => {
1323 ItemKind::Static(ref ty, .., body_id) | ItemKind::Const(ref ty, body_id) => {
1324 if is_suggestable_infer_ty(ty) {
1325 infer_placeholder_type(tcx, def_id, body_id, ty.span, item.ident)
1330 ItemKind::TyAlias(ref ty, _) | ItemKind::Impl(.., ref ty, _) => icx.to_ty(ty),
1331 ItemKind::Fn(..) => {
1332 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1333 tcx.mk_fn_def(def_id, substs)
1335 ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
1336 let def = tcx.adt_def(def_id);
1337 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1338 tcx.mk_adt(def, substs)
1340 ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: None, .. }) => {
1341 find_opaque_ty_constraints(tcx, def_id)
1343 // Opaque types desugared from `impl Trait`.
1344 ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: Some(owner), .. }) => {
1345 tcx.typeck_tables_of(owner)
1346 .concrete_opaque_types
1348 .map(|opaque| opaque.concrete_type)
1349 .unwrap_or_else(|| {
1350 // This can occur if some error in the
1351 // owner fn prevented us from populating
1352 // the `concrete_opaque_types` table.
1353 tcx.sess.delay_span_bug(
1356 "owner {:?} has no opaque type for {:?} in its tables",
1364 | ItemKind::TraitAlias(..)
1366 | ItemKind::ForeignMod(..)
1367 | ItemKind::GlobalAsm(..)
1368 | ItemKind::ExternCrate(..)
1369 | ItemKind::Use(..) => {
1372 "compute_type_of_item: unexpected item type: {:?}",
1379 Node::ForeignItem(foreign_item) => match foreign_item.kind {
1380 ForeignItemKind::Fn(..) => {
1381 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1382 tcx.mk_fn_def(def_id, substs)
1384 ForeignItemKind::Static(ref t, _) => icx.to_ty(t),
1385 ForeignItemKind::Type => tcx.mk_foreign(def_id),
1388 Node::Ctor(&ref def) | Node::Variant(hir::Variant { data: ref def, .. }) => match *def {
1389 VariantData::Unit(..) | VariantData::Struct(..) => {
1390 tcx.type_of(tcx.hir().get_parent_did(hir_id))
1392 VariantData::Tuple(..) => {
1393 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1394 tcx.mk_fn_def(def_id, substs)
1398 Node::Field(field) => icx.to_ty(&field.ty),
1400 Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(.., gen), .. }) => {
1402 return tcx.typeck_tables_of(def_id).node_type(hir_id);
1405 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1406 tcx.mk_closure(def_id, substs)
1409 Node::AnonConst(_) => {
1410 let parent_node = tcx.hir().get(tcx.hir().get_parent_node(hir_id));
1412 Node::Ty(&hir::Ty { kind: hir::TyKind::Array(_, ref constant), .. })
1413 | Node::Ty(&hir::Ty { kind: hir::TyKind::Typeof(ref constant), .. })
1414 | Node::Expr(&hir::Expr { kind: ExprKind::Repeat(_, ref constant), .. })
1415 if constant.hir_id == hir_id =>
1420 Node::Variant(Variant { disr_expr: Some(ref e), .. }) if e.hir_id == hir_id => {
1421 tcx.adt_def(tcx.hir().get_parent_did(hir_id)).repr.discr_type().to_ty(tcx)
1424 Node::Ty(&hir::Ty { kind: hir::TyKind::Path(_), .. })
1425 | Node::Expr(&hir::Expr { kind: ExprKind::Struct(..), .. })
1426 | Node::Expr(&hir::Expr { kind: ExprKind::Path(_), .. })
1427 | Node::TraitRef(..) => {
1428 let path = match parent_node {
1430 kind: hir::TyKind::Path(QPath::Resolved(_, ref path)),
1433 | Node::Expr(&hir::Expr {
1434 kind: ExprKind::Path(QPath::Resolved(_, ref path)),
1436 }) => Some(&**path),
1437 Node::Expr(&hir::Expr { kind: ExprKind::Struct(ref path, ..), .. }) => {
1438 if let QPath::Resolved(_, ref path) = **path {
1444 Node::TraitRef(&hir::TraitRef { ref path, .. }) => Some(&**path),
1448 if let Some(path) = path {
1449 let arg_index = path
1452 .filter_map(|seg| seg.args.as_ref())
1453 .map(|generic_args| generic_args.args.as_ref())
1456 .filter(|arg| arg.is_const())
1458 .filter(|(_, arg)| arg.id() == hir_id)
1459 .map(|(index, _)| index)
1462 .unwrap_or_else(|| {
1463 bug!("no arg matching AnonConst in path");
1466 // We've encountered an `AnonConst` in some path, so we need to
1467 // figure out which generic parameter it corresponds to and return
1468 // the relevant type.
1469 let generics = match path.res {
1470 Res::Def(DefKind::Ctor(..), def_id) => {
1471 tcx.generics_of(tcx.parent(def_id).unwrap())
1473 Res::Def(_, def_id) => tcx.generics_of(def_id),
1474 Res::Err => return tcx.types.err,
1476 tcx.sess.delay_span_bug(
1478 &format!("unexpected const parent path def {:?}", res,),
1480 return tcx.types.err;
1488 if let ty::GenericParamDefKind::Const = param.kind {
1495 .map(|param| tcx.type_of(param.def_id))
1496 // This is no generic parameter associated with the arg. This is
1497 // probably from an extra arg where one is not needed.
1498 .unwrap_or(tcx.types.err)
1500 tcx.sess.delay_span_bug(
1502 &format!("unexpected const parent path {:?}", parent_node,),
1504 return tcx.types.err;
1509 tcx.sess.delay_span_bug(
1511 &format!("unexpected const parent in type_of_def_id(): {:?}", x),
1518 Node::GenericParam(param) => match ¶m.kind {
1519 hir::GenericParamKind::Type { default: Some(ref ty), .. } => icx.to_ty(ty),
1520 hir::GenericParamKind::Const { ty: ref hir_ty, .. } => {
1521 let ty = icx.to_ty(hir_ty);
1522 if !tcx.features().const_compare_raw_pointers {
1523 let err = match ty.peel_refs().kind {
1524 ty::FnPtr(_) => Some("function pointers"),
1525 ty::RawPtr(_) => Some("raw pointers"),
1528 if let Some(unsupported_type) = err {
1529 feature_gate::feature_err(
1530 &tcx.sess.parse_sess,
1531 sym::const_compare_raw_pointers,
1534 "using {} as const generic parameters is unstable",
1541 if traits::search_for_structural_match_violation(param.hir_id, param.span, tcx, ty)
1548 "the types of const generic parameters must derive `PartialEq` and `Eq`",
1552 format!("`{}` doesn't derive both `PartialEq` and `Eq`", ty),
1558 x => bug!("unexpected non-type Node::GenericParam: {:?}", x),
1562 bug!("unexpected sort of node in type_of_def_id(): {:?}", x);
1567 fn find_opaque_ty_constraints(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> {
1568 use rustc_hir::{ImplItem, Item, TraitItem};
1570 debug!("find_opaque_ty_constraints({:?})", def_id);
1572 struct ConstraintLocator<'tcx> {
1575 // (first found type span, actual type, mapping from the opaque type's generic
1576 // parameters to the concrete type's generic parameters)
1578 // The mapping is an index for each use site of a generic parameter in the concrete type
1580 // The indices index into the generic parameters on the opaque type.
1581 found: Option<(Span, Ty<'tcx>, Vec<usize>)>,
1584 impl ConstraintLocator<'tcx> {
1585 fn check(&mut self, def_id: DefId) {
1586 // Don't try to check items that cannot possibly constrain the type.
1587 if !self.tcx.has_typeck_tables(def_id) {
1589 "find_opaque_ty_constraints: no constraint for `{:?}` at `{:?}`: no tables",
1590 self.def_id, def_id,
1594 let ty = self.tcx.typeck_tables_of(def_id).concrete_opaque_types.get(&self.def_id);
1595 if let Some(ty::ResolvedOpaqueTy { concrete_type, substs }) = ty {
1597 "find_opaque_ty_constraints: found constraint for `{:?}` at `{:?}`: {:?}",
1598 self.def_id, def_id, ty,
1601 // FIXME(oli-obk): trace the actual span from inference to improve errors.
1602 let span = self.tcx.def_span(def_id);
1603 // used to quickly look up the position of a generic parameter
1604 let mut index_map: FxHashMap<ty::ParamTy, usize> = FxHashMap::default();
1605 // Skipping binder is ok, since we only use this to find generic parameters and
1607 for (idx, subst) in substs.iter().enumerate() {
1608 if let GenericArgKind::Type(ty) = subst.unpack() {
1609 if let ty::Param(p) = ty.kind {
1610 if index_map.insert(p, idx).is_some() {
1611 // There was already an entry for `p`, meaning a generic parameter
1613 self.tcx.sess.span_err(
1616 "defining opaque type use restricts opaque \
1617 type by using the generic parameter `{}` twice",
1624 self.tcx.sess.delay_span_bug(
1627 "non-defining opaque ty use in defining scope: {:?}, {:?}",
1628 concrete_type, substs,
1634 // Compute the index within the opaque type for each generic parameter used in
1635 // the concrete type.
1636 let indices = concrete_type
1637 .subst(self.tcx, substs)
1639 .filter_map(|t| match &t.kind {
1640 ty::Param(p) => Some(*index_map.get(p).unwrap()),
1644 let is_param = |ty: Ty<'_>| match ty.kind {
1645 ty::Param(_) => true,
1648 let bad_substs: Vec<_> =
1649 substs.types().enumerate().filter(|(_, ty)| !is_param(ty)).collect();
1650 if !bad_substs.is_empty() {
1651 let identity_substs = InternalSubsts::identity_for_item(self.tcx, self.def_id);
1652 for (i, bad_subst) in bad_substs {
1653 self.tcx.sess.span_err(
1656 "defining opaque type use does not fully define opaque type: \
1657 generic parameter `{}` is specified as concrete type `{}`",
1658 identity_substs.type_at(i),
1663 } else if let Some((prev_span, prev_ty, ref prev_indices)) = self.found {
1664 let mut ty = concrete_type.walk().fuse();
1665 let mut p_ty = prev_ty.walk().fuse();
1666 let iter_eq = (&mut ty).zip(&mut p_ty).all(|(t, p)| match (&t.kind, &p.kind) {
1667 // Type parameters are equal to any other type parameter for the purpose of
1668 // concrete type equality, as it is possible to obtain the same type just
1669 // by passing matching parameters to a function.
1670 (ty::Param(_), ty::Param(_)) => true,
1673 if !iter_eq || ty.next().is_some() || p_ty.next().is_some() {
1674 debug!("find_opaque_ty_constraints: span={:?}", span);
1675 // Found different concrete types for the opaque type.
1676 let mut err = self.tcx.sess.struct_span_err(
1678 "concrete type differs from previous defining opaque type use",
1682 format!("expected `{}`, got `{}`", prev_ty, concrete_type),
1684 err.span_note(prev_span, "previous use here");
1686 } else if indices != *prev_indices {
1687 // Found "same" concrete types, but the generic parameter order differs.
1688 let mut err = self.tcx.sess.struct_span_err(
1690 "concrete type's generic parameters differ from previous defining use",
1692 use std::fmt::Write;
1693 let mut s = String::new();
1694 write!(s, "expected [").unwrap();
1695 let list = |s: &mut String, indices: &Vec<usize>| {
1696 let mut indices = indices.iter().cloned();
1697 if let Some(first) = indices.next() {
1698 write!(s, "`{}`", substs[first]).unwrap();
1700 write!(s, ", `{}`", substs[i]).unwrap();
1704 list(&mut s, prev_indices);
1705 write!(s, "], got [").unwrap();
1706 list(&mut s, &indices);
1707 write!(s, "]").unwrap();
1708 err.span_label(span, s);
1709 err.span_note(prev_span, "previous use here");
1713 self.found = Some((span, concrete_type, indices));
1717 "find_opaque_ty_constraints: no constraint for `{:?}` at `{:?}`",
1718 self.def_id, def_id,
1724 impl<'tcx> intravisit::Visitor<'tcx> for ConstraintLocator<'tcx> {
1725 type Map = Map<'tcx>;
1727 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<'_, Self::Map> {
1728 intravisit::NestedVisitorMap::All(&self.tcx.hir())
1730 fn visit_item(&mut self, it: &'tcx Item<'tcx>) {
1731 debug!("find_existential_constraints: visiting {:?}", it);
1732 let def_id = self.tcx.hir().local_def_id(it.hir_id);
1733 // The opaque type itself or its children are not within its reveal scope.
1734 if def_id != self.def_id {
1736 intravisit::walk_item(self, it);
1739 fn visit_impl_item(&mut self, it: &'tcx ImplItem<'tcx>) {
1740 debug!("find_existential_constraints: visiting {:?}", it);
1741 let def_id = self.tcx.hir().local_def_id(it.hir_id);
1742 // The opaque type itself or its children are not within its reveal scope.
1743 if def_id != self.def_id {
1745 intravisit::walk_impl_item(self, it);
1748 fn visit_trait_item(&mut self, it: &'tcx TraitItem<'tcx>) {
1749 debug!("find_existential_constraints: visiting {:?}", it);
1750 let def_id = self.tcx.hir().local_def_id(it.hir_id);
1752 intravisit::walk_trait_item(self, it);
1756 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1757 let scope = tcx.hir().get_defining_scope(hir_id);
1758 let mut locator = ConstraintLocator { def_id, tcx, found: None };
1760 debug!("find_opaque_ty_constraints: scope={:?}", scope);
1762 if scope == hir::CRATE_HIR_ID {
1763 intravisit::walk_crate(&mut locator, tcx.hir().krate());
1765 debug!("find_opaque_ty_constraints: scope={:?}", tcx.hir().get(scope));
1766 match tcx.hir().get(scope) {
1767 // We explicitly call `visit_*` methods, instead of using `intravisit::walk_*` methods
1768 // This allows our visitor to process the defining item itself, causing
1769 // it to pick up any 'sibling' defining uses.
1771 // For example, this code:
1774 // type Blah = impl Debug;
1775 // let my_closure = || -> Blah { true };
1779 // requires us to explicitly process `foo()` in order
1780 // to notice the defining usage of `Blah`.
1781 Node::Item(ref it) => locator.visit_item(it),
1782 Node::ImplItem(ref it) => locator.visit_impl_item(it),
1783 Node::TraitItem(ref it) => locator.visit_trait_item(it),
1784 other => bug!("{:?} is not a valid scope for an opaque type item", other),
1788 match locator.found {
1789 Some((_, ty, _)) => ty,
1791 let span = tcx.def_span(def_id);
1792 tcx.sess.span_err(span, "could not find defining uses");
1798 /// Whether `ty` is a type with `_` placeholders that can be infered. Used in diagnostics only to
1799 /// use inference to provide suggestions for the appropriate type if possible.
1800 fn is_suggestable_infer_ty(ty: &hir::Ty<'_>) -> bool {
1802 hir::TyKind::Infer => true,
1803 hir::TyKind::Slice(ty) | hir::TyKind::Array(ty, _) => is_suggestable_infer_ty(ty),
1804 hir::TyKind::Tup(tys) => tys.iter().any(|ty| is_suggestable_infer_ty(ty)),
1809 pub fn get_infer_ret_ty(output: &'hir hir::FunctionRetTy<'hir>) -> Option<&'hir hir::Ty<'hir>> {
1810 if let hir::FunctionRetTy::Return(ref ty) = output {
1811 if is_suggestable_infer_ty(ty) {
1818 fn fn_sig(tcx: TyCtxt<'_>, def_id: DefId) -> ty::PolyFnSig<'_> {
1819 use rustc_hir::Node::*;
1822 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1824 let icx = ItemCtxt::new(tcx, def_id);
1826 match tcx.hir().get(hir_id) {
1827 TraitItem(hir::TraitItem {
1828 kind: TraitItemKind::Method(sig, TraitMethod::Provided(_)),
1833 | ImplItem(hir::ImplItem { kind: ImplItemKind::Method(sig, _), ident, generics, .. })
1834 | Item(hir::Item { kind: ItemKind::Fn(sig, generics, _), ident, .. }) => {
1835 match get_infer_ret_ty(&sig.decl.output) {
1837 let fn_sig = tcx.typeck_tables_of(def_id).liberated_fn_sigs()[hir_id];
1838 let mut visitor = PlaceholderHirTyCollector::default();
1839 visitor.visit_ty(ty);
1840 let mut diag = bad_placeholder_type(tcx, visitor.0);
1841 let ret_ty = fn_sig.output();
1842 if ret_ty != tcx.types.err {
1843 diag.span_suggestion(
1845 "replace with the correct return type",
1847 Applicability::MaybeIncorrect,
1851 ty::Binder::bind(fn_sig)
1853 None => AstConv::ty_of_fn(
1855 sig.header.unsafety,
1858 &generics.params[..],
1864 TraitItem(hir::TraitItem {
1865 kind: TraitItemKind::Method(FnSig { header, decl }, _),
1869 }) => AstConv::ty_of_fn(
1874 &generics.params[..],
1878 ForeignItem(&hir::ForeignItem { kind: ForeignItemKind::Fn(ref fn_decl, _, _), .. }) => {
1879 let abi = tcx.hir().get_foreign_abi(hir_id);
1880 compute_sig_of_foreign_fn_decl(tcx, def_id, fn_decl, abi)
1883 Ctor(data) | Variant(hir::Variant { data, .. }) if data.ctor_hir_id().is_some() => {
1884 let ty = tcx.type_of(tcx.hir().get_parent_did(hir_id));
1886 data.fields().iter().map(|f| tcx.type_of(tcx.hir().local_def_id(f.hir_id)));
1887 ty::Binder::bind(tcx.mk_fn_sig(
1891 hir::Unsafety::Normal,
1896 Expr(&hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => {
1897 // Closure signatures are not like other function
1898 // signatures and cannot be accessed through `fn_sig`. For
1899 // example, a closure signature excludes the `self`
1900 // argument. In any case they are embedded within the
1901 // closure type as part of the `ClosureSubsts`.
1904 // the signature of a closure, you should use the
1905 // `closure_sig` method on the `ClosureSubsts`:
1907 // closure_substs.sig(def_id, tcx)
1909 // or, inside of an inference context, you can use
1911 // infcx.closure_sig(def_id, closure_substs)
1912 bug!("to get the signature of a closure, use `closure_sig()` not `fn_sig()`");
1916 bug!("unexpected sort of node in fn_sig(): {:?}", x);
1921 fn impl_trait_ref(tcx: TyCtxt<'_>, def_id: DefId) -> Option<ty::TraitRef<'_>> {
1922 let icx = ItemCtxt::new(tcx, def_id);
1924 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1925 match tcx.hir().expect_item(hir_id).kind {
1926 hir::ItemKind::Impl(.., ref opt_trait_ref, _, _) => {
1927 opt_trait_ref.as_ref().map(|ast_trait_ref| {
1928 let selfty = tcx.type_of(def_id);
1929 AstConv::instantiate_mono_trait_ref(&icx, ast_trait_ref, selfty)
1936 fn impl_polarity(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ImplPolarity {
1937 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1938 let is_rustc_reservation = tcx.has_attr(def_id, sym::rustc_reservation_impl);
1939 let item = tcx.hir().expect_item(hir_id);
1941 hir::ItemKind::Impl(_, hir::ImplPolarity::Negative, ..) => {
1942 if is_rustc_reservation {
1943 tcx.sess.span_err(item.span, "reservation impls can't be negative");
1945 ty::ImplPolarity::Negative
1947 hir::ItemKind::Impl(_, hir::ImplPolarity::Positive, _, _, None, _, _) => {
1948 if is_rustc_reservation {
1949 tcx.sess.span_err(item.span, "reservation impls can't be inherent");
1951 ty::ImplPolarity::Positive
1953 hir::ItemKind::Impl(_, hir::ImplPolarity::Positive, _, _, Some(_tr), _, _) => {
1954 if is_rustc_reservation {
1955 ty::ImplPolarity::Reservation
1957 ty::ImplPolarity::Positive
1960 ref item => bug!("impl_polarity: {:?} not an impl", item),
1964 /// Returns the early-bound lifetimes declared in this generics
1965 /// listing. For anything other than fns/methods, this is just all
1966 /// the lifetimes that are declared. For fns or methods, we have to
1967 /// screen out those that do not appear in any where-clauses etc using
1968 /// `resolve_lifetime::early_bound_lifetimes`.
1969 fn early_bound_lifetimes_from_generics<'a, 'tcx: 'a>(
1971 generics: &'a hir::Generics<'a>,
1972 ) -> impl Iterator<Item = &'a hir::GenericParam<'a>> + Captures<'tcx> {
1973 generics.params.iter().filter(move |param| match param.kind {
1974 GenericParamKind::Lifetime { .. } => !tcx.is_late_bound(param.hir_id),
1979 /// Returns a list of type predicates for the definition with ID `def_id`, including inferred
1980 /// lifetime constraints. This includes all predicates returned by `explicit_predicates_of`, plus
1981 /// inferred constraints concerning which regions outlive other regions.
1982 fn predicates_defined_on(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1983 debug!("predicates_defined_on({:?})", def_id);
1984 let mut result = tcx.explicit_predicates_of(def_id);
1985 debug!("predicates_defined_on: explicit_predicates_of({:?}) = {:?}", def_id, result,);
1986 let inferred_outlives = tcx.inferred_outlives_of(def_id);
1987 if !inferred_outlives.is_empty() {
1989 "predicates_defined_on: inferred_outlives_of({:?}) = {:?}",
1990 def_id, inferred_outlives,
1992 if result.predicates.is_empty() {
1993 result.predicates = inferred_outlives;
1995 result.predicates = tcx
1997 .alloc_from_iter(result.predicates.iter().chain(inferred_outlives).copied());
2000 debug!("predicates_defined_on({:?}) = {:?}", def_id, result);
2004 /// Returns a list of all type predicates (explicit and implicit) for the definition with
2005 /// ID `def_id`. This includes all predicates returned by `predicates_defined_on`, plus
2006 /// `Self: Trait` predicates for traits.
2007 fn predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
2008 let mut result = tcx.predicates_defined_on(def_id);
2010 if tcx.is_trait(def_id) {
2011 // For traits, add `Self: Trait` predicate. This is
2012 // not part of the predicates that a user writes, but it
2013 // is something that one must prove in order to invoke a
2014 // method or project an associated type.
2016 // In the chalk setup, this predicate is not part of the
2017 // "predicates" for a trait item. But it is useful in
2018 // rustc because if you directly (e.g.) invoke a trait
2019 // method like `Trait::method(...)`, you must naturally
2020 // prove that the trait applies to the types that were
2021 // used, and adding the predicate into this list ensures
2022 // that this is done.
2023 let span = tcx.def_span(def_id);
2025 tcx.arena.alloc_from_iter(result.predicates.iter().copied().chain(std::iter::once((
2026 ty::TraitRef::identity(tcx, def_id).to_predicate(),
2030 debug!("predicates_of(def_id={:?}) = {:?}", def_id, result);
2034 /// Returns a list of user-specified type predicates for the definition with ID `def_id`.
2035 /// N.B., this does not include any implied/inferred constraints.
2036 fn explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
2037 use rustc_data_structures::fx::FxHashSet;
2040 debug!("explicit_predicates_of(def_id={:?})", def_id);
2042 /// A data structure with unique elements, which preserves order of insertion.
2043 /// Preserving the order of insertion is important here so as not to break
2044 /// compile-fail UI tests.
2045 // FIXME(eddyb) just use `IndexSet` from `indexmap`.
2046 struct UniquePredicates<'tcx> {
2047 predicates: Vec<(ty::Predicate<'tcx>, Span)>,
2048 uniques: FxHashSet<(ty::Predicate<'tcx>, Span)>,
2051 impl<'tcx> UniquePredicates<'tcx> {
2053 UniquePredicates { predicates: vec![], uniques: FxHashSet::default() }
2056 fn push(&mut self, value: (ty::Predicate<'tcx>, Span)) {
2057 if self.uniques.insert(value) {
2058 self.predicates.push(value);
2062 fn extend<I: IntoIterator<Item = (ty::Predicate<'tcx>, Span)>>(&mut self, iter: I) {
2069 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
2070 let node = tcx.hir().get(hir_id);
2072 let mut is_trait = None;
2073 let mut is_default_impl_trait = None;
2075 let icx = ItemCtxt::new(tcx, def_id);
2077 const NO_GENERICS: &hir::Generics<'_> = &hir::Generics::empty();
2079 let mut predicates = UniquePredicates::new();
2081 let ast_generics = match node {
2082 Node::TraitItem(item) => &item.generics,
2084 Node::ImplItem(item) => match item.kind {
2085 ImplItemKind::OpaqueTy(ref bounds) => {
2086 ty::print::with_no_queries(|| {
2087 let substs = InternalSubsts::identity_for_item(tcx, def_id);
2088 let opaque_ty = tcx.mk_opaque(def_id, substs);
2090 "explicit_predicates_of({:?}): created opaque type {:?}",
2094 // Collect the bounds, i.e., the `A + B + 'c` in `impl A + B + 'c`.
2095 let bounds = AstConv::compute_bounds(
2099 SizedByDefault::Yes,
2100 tcx.def_span(def_id),
2103 predicates.extend(bounds.predicates(tcx, opaque_ty));
2107 _ => &item.generics,
2110 Node::Item(item) => {
2112 ItemKind::Impl(_, _, defaultness, ref generics, ..) => {
2113 if defaultness.is_default() {
2114 is_default_impl_trait = tcx.impl_trait_ref(def_id);
2118 ItemKind::Fn(.., ref generics, _)
2119 | ItemKind::TyAlias(_, ref generics)
2120 | ItemKind::Enum(_, ref generics)
2121 | ItemKind::Struct(_, ref generics)
2122 | ItemKind::Union(_, ref generics) => generics,
2124 ItemKind::Trait(_, _, ref generics, .., items) => {
2125 is_trait = Some((ty::TraitRef::identity(tcx, def_id), items));
2128 ItemKind::TraitAlias(ref generics, _) => {
2129 is_trait = Some((ty::TraitRef::identity(tcx, def_id), &[]));
2132 ItemKind::OpaqueTy(OpaqueTy {
2138 let bounds_predicates = ty::print::with_no_queries(|| {
2139 let substs = InternalSubsts::identity_for_item(tcx, def_id);
2140 let opaque_ty = tcx.mk_opaque(def_id, substs);
2142 // Collect the bounds, i.e., the `A + B + 'c` in `impl A + B + 'c`.
2143 let bounds = AstConv::compute_bounds(
2147 SizedByDefault::Yes,
2148 tcx.def_span(def_id),
2151 bounds.predicates(tcx, opaque_ty)
2153 if impl_trait_fn.is_some() {
2155 return ty::GenericPredicates {
2157 predicates: tcx.arena.alloc_from_iter(bounds_predicates),
2160 // named opaque types
2161 predicates.extend(bounds_predicates);
2170 Node::ForeignItem(item) => match item.kind {
2171 ForeignItemKind::Static(..) => NO_GENERICS,
2172 ForeignItemKind::Fn(_, _, ref generics) => generics,
2173 ForeignItemKind::Type => NO_GENERICS,
2179 let generics = tcx.generics_of(def_id);
2180 let parent_count = generics.parent_count as u32;
2181 let has_own_self = generics.has_self && parent_count == 0;
2183 // Below we'll consider the bounds on the type parameters (including `Self`)
2184 // and the explicit where-clauses, but to get the full set of predicates
2185 // on a trait we need to add in the supertrait bounds and bounds found on
2186 // associated types.
2187 if let Some((_trait_ref, _)) = is_trait {
2188 predicates.extend(tcx.super_predicates_of(def_id).predicates.iter().cloned());
2191 // In default impls, we can assume that the self type implements
2192 // the trait. So in:
2194 // default impl Foo for Bar { .. }
2196 // we add a default where clause `Foo: Bar`. We do a similar thing for traits
2197 // (see below). Recall that a default impl is not itself an impl, but rather a
2198 // set of defaults that can be incorporated into another impl.
2199 if let Some(trait_ref) = is_default_impl_trait {
2200 predicates.push((trait_ref.to_poly_trait_ref().to_predicate(), tcx.def_span(def_id)));
2203 // Collect the region predicates that were declared inline as
2204 // well. In the case of parameters declared on a fn or method, we
2205 // have to be careful to only iterate over early-bound regions.
2206 let mut index = parent_count + has_own_self as u32;
2207 for param in early_bound_lifetimes_from_generics(tcx, ast_generics) {
2208 let region = tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
2209 def_id: tcx.hir().local_def_id(param.hir_id),
2211 name: param.name.ident().name,
2216 GenericParamKind::Lifetime { .. } => {
2217 param.bounds.iter().for_each(|bound| match bound {
2218 hir::GenericBound::Outlives(lt) => {
2219 let bound = AstConv::ast_region_to_region(&icx, <, None);
2220 let outlives = ty::Binder::bind(ty::OutlivesPredicate(region, bound));
2221 predicates.push((outlives.to_predicate(), lt.span));
2230 // Collect the predicates that were written inline by the user on each
2231 // type parameter (e.g., `<T: Foo>`).
2232 for param in ast_generics.params {
2233 if let GenericParamKind::Type { .. } = param.kind {
2234 let name = param.name.ident().name;
2235 let param_ty = ty::ParamTy::new(index, name).to_ty(tcx);
2238 let sized = SizedByDefault::Yes;
2239 let bounds = AstConv::compute_bounds(&icx, param_ty, ¶m.bounds, sized, param.span);
2240 predicates.extend(bounds.predicates(tcx, param_ty));
2244 // Add in the bounds that appear in the where-clause.
2245 let where_clause = &ast_generics.where_clause;
2246 for predicate in where_clause.predicates {
2248 &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
2249 let ty = icx.to_ty(&bound_pred.bounded_ty);
2251 // Keep the type around in a dummy predicate, in case of no bounds.
2252 // That way, `where Ty:` is not a complete noop (see #53696) and `Ty`
2253 // is still checked for WF.
2254 if bound_pred.bounds.is_empty() {
2255 if let ty::Param(_) = ty.kind {
2256 // This is a `where T:`, which can be in the HIR from the
2257 // transformation that moves `?Sized` to `T`'s declaration.
2258 // We can skip the predicate because type parameters are
2259 // trivially WF, but also we *should*, to avoid exposing
2260 // users who never wrote `where Type:,` themselves, to
2261 // compiler/tooling bugs from not handling WF predicates.
2263 let span = bound_pred.bounded_ty.span;
2264 let predicate = ty::OutlivesPredicate(ty, tcx.mk_region(ty::ReEmpty));
2266 ty::Predicate::TypeOutlives(ty::Binder::dummy(predicate)),
2272 for bound in bound_pred.bounds.iter() {
2274 &hir::GenericBound::Trait(ref poly_trait_ref, _) => {
2275 let mut bounds = Bounds::default();
2276 let _ = AstConv::instantiate_poly_trait_ref(
2282 predicates.extend(bounds.predicates(tcx, ty));
2285 &hir::GenericBound::Outlives(ref lifetime) => {
2286 let region = AstConv::ast_region_to_region(&icx, lifetime, None);
2287 let pred = ty::Binder::bind(ty::OutlivesPredicate(ty, region));
2288 predicates.push((ty::Predicate::TypeOutlives(pred), lifetime.span))
2294 &hir::WherePredicate::RegionPredicate(ref region_pred) => {
2295 let r1 = AstConv::ast_region_to_region(&icx, ®ion_pred.lifetime, None);
2296 predicates.extend(region_pred.bounds.iter().map(|bound| {
2297 let (r2, span) = match bound {
2298 hir::GenericBound::Outlives(lt) => {
2299 (AstConv::ast_region_to_region(&icx, lt, None), lt.span)
2303 let pred = ty::Binder::bind(ty::OutlivesPredicate(r1, r2));
2305 (ty::Predicate::RegionOutlives(pred), span)
2309 &hir::WherePredicate::EqPredicate(..) => {
2315 // Add predicates from associated type bounds.
2316 if let Some((self_trait_ref, trait_items)) = is_trait {
2317 predicates.extend(trait_items.iter().flat_map(|trait_item_ref| {
2318 associated_item_predicates(tcx, def_id, self_trait_ref, trait_item_ref)
2322 let mut predicates = predicates.predicates;
2324 // Subtle: before we store the predicates into the tcx, we
2325 // sort them so that predicates like `T: Foo<Item=U>` come
2326 // before uses of `U`. This avoids false ambiguity errors
2327 // in trait checking. See `setup_constraining_predicates`
2329 if let Node::Item(&Item { kind: ItemKind::Impl(..), .. }) = node {
2330 let self_ty = tcx.type_of(def_id);
2331 let trait_ref = tcx.impl_trait_ref(def_id);
2332 cgp::setup_constraining_predicates(
2336 &mut cgp::parameters_for_impl(self_ty, trait_ref),
2340 let result = ty::GenericPredicates {
2341 parent: generics.parent,
2342 predicates: tcx.arena.alloc_from_iter(predicates),
2344 debug!("explicit_predicates_of(def_id={:?}) = {:?}", def_id, result);
2348 fn associated_item_predicates(
2351 self_trait_ref: ty::TraitRef<'tcx>,
2352 trait_item_ref: &hir::TraitItemRef,
2353 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2354 let trait_item = tcx.hir().trait_item(trait_item_ref.id);
2355 let item_def_id = tcx.hir().local_def_id(trait_item_ref.id.hir_id);
2356 let bounds = match trait_item.kind {
2357 hir::TraitItemKind::Type(ref bounds, _) => bounds,
2358 _ => return Vec::new(),
2361 let is_gat = !tcx.generics_of(item_def_id).params.is_empty();
2363 let mut had_error = false;
2365 let mut unimplemented_error = |arg_kind: &str| {
2370 &format!("{}-generic associated types are not yet implemented", arg_kind),
2372 .note("for more information, see https://github.com/rust-lang/rust/issues/44265")
2378 let mk_bound_param = |param: &ty::GenericParamDef, _: &_| {
2380 ty::GenericParamDefKind::Lifetime => tcx
2381 .mk_region(ty::RegionKind::ReLateBound(
2383 ty::BoundRegion::BrNamed(param.def_id, param.name),
2386 // FIXME(generic_associated_types): Use bound types and constants
2387 // once they are handled by the trait system.
2388 ty::GenericParamDefKind::Type { .. } => {
2389 unimplemented_error("type");
2390 tcx.types.err.into()
2392 ty::GenericParamDefKind::Const => {
2393 unimplemented_error("const");
2394 tcx.consts.err.into()
2399 let bound_substs = if is_gat {
2402 // trait X<'a, B, const C: usize> {
2403 // type T<'d, E, const F: usize>: Default;
2406 // We need to create predicates on the trait:
2408 // for<'d, E, const F: usize>
2409 // <Self as X<'a, B, const C: usize>>::T<'d, E, const F: usize>: Sized + Default
2411 // We substitute escaping bound parameters for the generic
2412 // arguments to the associated type which are then bound by
2413 // the `Binder` around the the predicate.
2415 // FIXME(generic_associated_types): Currently only lifetimes are handled.
2416 self_trait_ref.substs.extend_to(tcx, item_def_id, mk_bound_param)
2418 self_trait_ref.substs
2421 let assoc_ty = tcx.mk_projection(tcx.hir().local_def_id(trait_item.hir_id), bound_substs);
2423 let bounds = AstConv::compute_bounds(
2424 &ItemCtxt::new(tcx, def_id),
2427 SizedByDefault::Yes,
2431 let predicates = bounds.predicates(tcx, assoc_ty);
2434 // We use shifts to get the regions that we're substituting to
2435 // be bound by the binders in the `Predicate`s rather that
2437 let shifted_in = ty::fold::shift_vars(tcx, &predicates, 1);
2438 let substituted = shifted_in.subst(tcx, bound_substs);
2439 ty::fold::shift_out_vars(tcx, &substituted, 1)
2445 /// Converts a specific `GenericBound` from the AST into a set of
2446 /// predicates that apply to the self type. A vector is returned
2447 /// because this can be anywhere from zero predicates (`T: ?Sized` adds no
2448 /// predicates) to one (`T: Foo`) to many (`T: Bar<X = i32>` adds `T: Bar`
2449 /// and `<T as Bar>::X == i32`).
2450 fn predicates_from_bound<'tcx>(
2451 astconv: &dyn AstConv<'tcx>,
2453 bound: &'tcx hir::GenericBound<'tcx>,
2454 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2456 hir::GenericBound::Trait(ref tr, hir::TraitBoundModifier::None) => {
2457 let mut bounds = Bounds::default();
2458 let _ = astconv.instantiate_poly_trait_ref(tr, param_ty, &mut bounds);
2459 bounds.predicates(astconv.tcx(), param_ty)
2461 hir::GenericBound::Outlives(ref lifetime) => {
2462 let region = astconv.ast_region_to_region(lifetime, None);
2463 let pred = ty::Binder::bind(ty::OutlivesPredicate(param_ty, region));
2464 vec![(ty::Predicate::TypeOutlives(pred), lifetime.span)]
2466 hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => vec![],
2470 fn compute_sig_of_foreign_fn_decl<'tcx>(
2473 decl: &'tcx hir::FnDecl<'tcx>,
2475 ) -> ty::PolyFnSig<'tcx> {
2476 let unsafety = if abi == abi::Abi::RustIntrinsic {
2477 intrinsic_operation_unsafety(&tcx.item_name(def_id).as_str())
2479 hir::Unsafety::Unsafe
2481 let fty = AstConv::ty_of_fn(&ItemCtxt::new(tcx, def_id), unsafety, abi, decl, &[], None);
2483 // Feature gate SIMD types in FFI, since I am not sure that the
2484 // ABIs are handled at all correctly. -huonw
2485 if abi != abi::Abi::RustIntrinsic
2486 && abi != abi::Abi::PlatformIntrinsic
2487 && !tcx.features().simd_ffi
2489 let check = |ast_ty: &hir::Ty<'_>, ty: Ty<'_>| {
2495 "use of SIMD type `{}` in FFI is highly experimental and \
2496 may result in invalid code",
2497 tcx.hir().hir_to_pretty_string(ast_ty.hir_id)
2500 .help("add `#![feature(simd_ffi)]` to the crate attributes to enable")
2504 for (input, ty) in decl.inputs.iter().zip(*fty.inputs().skip_binder()) {
2507 if let hir::FunctionRetTy::Return(ref ty) = decl.output {
2508 check(&ty, *fty.output().skip_binder())
2515 fn is_foreign_item(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
2516 match tcx.hir().get_if_local(def_id) {
2517 Some(Node::ForeignItem(..)) => true,
2519 _ => bug!("is_foreign_item applied to non-local def-id {:?}", def_id),
2523 fn static_mutability(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::Mutability> {
2524 match tcx.hir().get_if_local(def_id) {
2525 Some(Node::Item(&hir::Item { kind: hir::ItemKind::Static(_, mutbl, _), .. }))
2526 | Some(Node::ForeignItem(&hir::ForeignItem {
2527 kind: hir::ForeignItemKind::Static(_, mutbl),
2531 _ => bug!("static_mutability applied to non-local def-id {:?}", def_id),
2535 fn from_target_feature(
2538 attr: &ast::Attribute,
2539 whitelist: &FxHashMap<String, Option<Symbol>>,
2540 target_features: &mut Vec<Symbol>,
2542 let list = match attr.meta_item_list() {
2546 let bad_item = |span| {
2547 let msg = "malformed `target_feature` attribute input";
2548 let code = "enable = \"..\"".to_owned();
2550 .struct_span_err(span, &msg)
2551 .span_suggestion(span, "must be of the form", code, Applicability::HasPlaceholders)
2554 let rust_features = tcx.features();
2556 // Only `enable = ...` is accepted in the meta-item list.
2557 if !item.check_name(sym::enable) {
2558 bad_item(item.span());
2562 // Must be of the form `enable = "..."` (a string).
2563 let value = match item.value_str() {
2564 Some(value) => value,
2566 bad_item(item.span());
2571 // We allow comma separation to enable multiple features.
2572 target_features.extend(value.as_str().split(',').filter_map(|feature| {
2573 // Only allow whitelisted features per platform.
2574 let feature_gate = match whitelist.get(feature) {
2578 format!("the feature named `{}` is not valid for this target", feature);
2579 let mut err = tcx.sess.struct_span_err(item.span(), &msg);
2582 format!("`{}` is not valid for this target", feature),
2584 if feature.starts_with("+") {
2585 let valid = whitelist.contains_key(&feature[1..]);
2587 err.help("consider removing the leading `+` in the feature name");
2595 // Only allow features whose feature gates have been enabled.
2596 let allowed = match feature_gate.as_ref().map(|s| *s) {
2597 Some(sym::arm_target_feature) => rust_features.arm_target_feature,
2598 Some(sym::aarch64_target_feature) => rust_features.aarch64_target_feature,
2599 Some(sym::hexagon_target_feature) => rust_features.hexagon_target_feature,
2600 Some(sym::powerpc_target_feature) => rust_features.powerpc_target_feature,
2601 Some(sym::mips_target_feature) => rust_features.mips_target_feature,
2602 Some(sym::avx512_target_feature) => rust_features.avx512_target_feature,
2603 Some(sym::mmx_target_feature) => rust_features.mmx_target_feature,
2604 Some(sym::sse4a_target_feature) => rust_features.sse4a_target_feature,
2605 Some(sym::tbm_target_feature) => rust_features.tbm_target_feature,
2606 Some(sym::wasm_target_feature) => rust_features.wasm_target_feature,
2607 Some(sym::cmpxchg16b_target_feature) => rust_features.cmpxchg16b_target_feature,
2608 Some(sym::adx_target_feature) => rust_features.adx_target_feature,
2609 Some(sym::movbe_target_feature) => rust_features.movbe_target_feature,
2610 Some(sym::rtm_target_feature) => rust_features.rtm_target_feature,
2611 Some(sym::f16c_target_feature) => rust_features.f16c_target_feature,
2612 Some(name) => bug!("unknown target feature gate {}", name),
2615 if !allowed && id.is_local() {
2616 feature_gate::feature_err(
2617 &tcx.sess.parse_sess,
2618 feature_gate.unwrap(),
2620 &format!("the target feature `{}` is currently unstable", feature),
2624 Some(Symbol::intern(feature))
2629 fn linkage_by_name(tcx: TyCtxt<'_>, def_id: DefId, name: &str) -> Linkage {
2630 use rustc::mir::mono::Linkage::*;
2632 // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
2633 // applicable to variable declarations and may not really make sense for
2634 // Rust code in the first place but whitelist them anyway and trust that
2635 // the user knows what s/he's doing. Who knows, unanticipated use cases
2636 // may pop up in the future.
2638 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
2639 // and don't have to be, LLVM treats them as no-ops.
2641 "appending" => Appending,
2642 "available_externally" => AvailableExternally,
2644 "extern_weak" => ExternalWeak,
2645 "external" => External,
2646 "internal" => Internal,
2647 "linkonce" => LinkOnceAny,
2648 "linkonce_odr" => LinkOnceODR,
2649 "private" => Private,
2651 "weak_odr" => WeakODR,
2653 let span = tcx.hir().span_if_local(def_id);
2654 if let Some(span) = span {
2655 tcx.sess.span_fatal(span, "invalid linkage specified")
2657 tcx.sess.fatal(&format!("invalid linkage specified: {}", name))
2663 fn codegen_fn_attrs(tcx: TyCtxt<'_>, id: DefId) -> CodegenFnAttrs {
2664 let attrs = tcx.get_attrs(id);
2666 let mut codegen_fn_attrs = CodegenFnAttrs::new();
2668 let whitelist = tcx.target_features_whitelist(LOCAL_CRATE);
2670 let mut inline_span = None;
2671 let mut link_ordinal_span = None;
2672 for attr in attrs.iter() {
2673 if attr.check_name(sym::cold) {
2674 codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD;
2675 } else if attr.check_name(sym::rustc_allocator) {
2676 codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR;
2677 } else if attr.check_name(sym::unwind) {
2678 codegen_fn_attrs.flags |= CodegenFnAttrFlags::UNWIND;
2679 } else if attr.check_name(sym::ffi_returns_twice) {
2680 if tcx.is_foreign_item(id) {
2681 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_RETURNS_TWICE;
2683 // `#[ffi_returns_twice]` is only allowed `extern fn`s.
2688 "`#[ffi_returns_twice]` may only be used on foreign functions"
2692 } else if attr.check_name(sym::rustc_allocator_nounwind) {
2693 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND;
2694 } else if attr.check_name(sym::naked) {
2695 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED;
2696 } else if attr.check_name(sym::no_mangle) {
2697 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2698 } else if attr.check_name(sym::rustc_std_internal_symbol) {
2699 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2700 } else if attr.check_name(sym::no_debug) {
2701 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_DEBUG;
2702 } else if attr.check_name(sym::used) {
2703 codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED;
2704 } else if attr.check_name(sym::thread_local) {
2705 codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL;
2706 } else if attr.check_name(sym::track_caller) {
2707 if tcx.fn_sig(id).abi() != abi::Abi::Rust {
2708 struct_span_err!(tcx.sess, attr.span, E0737, "`#[track_caller]` requires Rust ABI")
2711 codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
2712 } else if attr.check_name(sym::export_name) {
2713 if let Some(s) = attr.value_str() {
2714 if s.as_str().contains("\0") {
2715 // `#[export_name = ...]` will be converted to a null-terminated string,
2716 // so it may not contain any null characters.
2721 "`export_name` may not contain null characters"
2725 codegen_fn_attrs.export_name = Some(s);
2727 } else if attr.check_name(sym::target_feature) {
2728 if tcx.fn_sig(id).unsafety() == Unsafety::Normal {
2729 let msg = "`#[target_feature(..)]` can only be applied to `unsafe` functions";
2731 .struct_span_err(attr.span, msg)
2732 .span_label(attr.span, "can only be applied to `unsafe` functions")
2733 .span_label(tcx.def_span(id), "not an `unsafe` function")
2736 from_target_feature(tcx, id, attr, &whitelist, &mut codegen_fn_attrs.target_features);
2737 } else if attr.check_name(sym::linkage) {
2738 if let Some(val) = attr.value_str() {
2739 codegen_fn_attrs.linkage = Some(linkage_by_name(tcx, id, &val.as_str()));
2741 } else if attr.check_name(sym::link_section) {
2742 if let Some(val) = attr.value_str() {
2743 if val.as_str().bytes().any(|b| b == 0) {
2745 "illegal null byte in link_section \
2749 tcx.sess.span_err(attr.span, &msg);
2751 codegen_fn_attrs.link_section = Some(val);
2754 } else if attr.check_name(sym::link_name) {
2755 codegen_fn_attrs.link_name = attr.value_str();
2756 } else if attr.check_name(sym::link_ordinal) {
2757 link_ordinal_span = Some(attr.span);
2758 if let ordinal @ Some(_) = check_link_ordinal(tcx, attr) {
2759 codegen_fn_attrs.link_ordinal = ordinal;
2764 codegen_fn_attrs.inline = attrs.iter().fold(InlineAttr::None, |ia, attr| {
2765 if !attr.has_name(sym::inline) {
2768 match attr.meta().map(|i| i.kind) {
2769 Some(MetaItemKind::Word) => {
2773 Some(MetaItemKind::List(ref items)) => {
2775 inline_span = Some(attr.span);
2776 if items.len() != 1 {
2778 tcx.sess.diagnostic(),
2781 "expected one argument"
2785 } else if list_contains_name(&items[..], sym::always) {
2787 } else if list_contains_name(&items[..], sym::never) {
2791 tcx.sess.diagnostic(),
2801 Some(MetaItemKind::NameValue(_)) => ia,
2806 codegen_fn_attrs.optimize = attrs.iter().fold(OptimizeAttr::None, |ia, attr| {
2807 if !attr.has_name(sym::optimize) {
2810 let err = |sp, s| struct_span_err!(tcx.sess.diagnostic(), sp, E0722, "{}", s).emit();
2811 match attr.meta().map(|i| i.kind) {
2812 Some(MetaItemKind::Word) => {
2813 err(attr.span, "expected one argument");
2816 Some(MetaItemKind::List(ref items)) => {
2818 inline_span = Some(attr.span);
2819 if items.len() != 1 {
2820 err(attr.span, "expected one argument");
2822 } else if list_contains_name(&items[..], sym::size) {
2824 } else if list_contains_name(&items[..], sym::speed) {
2827 err(items[0].span(), "invalid argument");
2831 Some(MetaItemKind::NameValue(_)) => ia,
2836 // If a function uses #[target_feature] it can't be inlined into general
2837 // purpose functions as they wouldn't have the right target features
2838 // enabled. For that reason we also forbid #[inline(always)] as it can't be
2841 if codegen_fn_attrs.target_features.len() > 0 {
2842 if codegen_fn_attrs.inline == InlineAttr::Always {
2843 if let Some(span) = inline_span {
2846 "cannot use `#[inline(always)]` with \
2847 `#[target_feature]`",
2853 // Weak lang items have the same semantics as "std internal" symbols in the
2854 // sense that they're preserved through all our LTO passes and only
2855 // strippable by the linker.
2857 // Additionally weak lang items have predetermined symbol names.
2858 if tcx.is_weak_lang_item(id) {
2859 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2861 if let Some(name) = weak_lang_items::link_name(&attrs) {
2862 codegen_fn_attrs.export_name = Some(name);
2863 codegen_fn_attrs.link_name = Some(name);
2865 check_link_name_xor_ordinal(tcx, &codegen_fn_attrs, link_ordinal_span);
2867 // Internal symbols to the standard library all have no_mangle semantics in
2868 // that they have defined symbol names present in the function name. This
2869 // also applies to weak symbols where they all have known symbol names.
2870 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
2871 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2877 fn check_link_ordinal(tcx: TyCtxt<'_>, attr: &ast::Attribute) -> Option<usize> {
2878 use syntax::ast::{Lit, LitIntType, LitKind};
2879 let meta_item_list = attr.meta_item_list();
2880 let meta_item_list: Option<&[ast::NestedMetaItem]> = meta_item_list.as_ref().map(Vec::as_ref);
2881 let sole_meta_list = match meta_item_list {
2882 Some([item]) => item.literal(),
2885 if let Some(Lit { kind: LitKind::Int(ordinal, LitIntType::Unsuffixed), .. }) = sole_meta_list {
2886 if *ordinal <= std::usize::MAX as u128 {
2887 Some(*ordinal as usize)
2889 let msg = format!("ordinal value in `link_ordinal` is too large: `{}`", &ordinal);
2891 .struct_span_err(attr.span, &msg)
2892 .note("the value may not exceed `std::usize::MAX`")
2898 .struct_span_err(attr.span, "illegal ordinal format in `link_ordinal`")
2899 .note("an unsuffixed integer value, e.g., `1`, is expected")
2905 fn check_link_name_xor_ordinal(
2907 codegen_fn_attrs: &CodegenFnAttrs,
2908 inline_span: Option<Span>,
2910 if codegen_fn_attrs.link_name.is_none() || codegen_fn_attrs.link_ordinal.is_none() {
2913 let msg = "cannot use `#[link_name]` with `#[link_ordinal]`";
2914 if let Some(span) = inline_span {
2915 tcx.sess.span_err(span, msg);