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 *interprocedural* 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};
18 use crate::constrained_generic_params as cgp;
19 use crate::check::intrinsic::intrisic_operation_unsafety;
21 use crate::middle::lang_items::SizedTraitLangItem;
22 use crate::middle::resolve_lifetime as rl;
23 use crate::middle::weak_lang_items;
24 use rustc::mir::mono::Linkage;
25 use rustc::ty::query::Providers;
26 use rustc::ty::subst::{Subst, InternalSubsts};
27 use rustc::ty::util::Discr;
28 use rustc::ty::util::IntTypeExt;
29 use rustc::ty::subst::UnpackedKind;
30 use rustc::ty::{self, AdtKind, ToPolyTraitRef, Ty, TyCtxt};
31 use rustc::ty::{ReprOptions, ToPredicate};
32 use rustc::util::captures::Captures;
33 use rustc::util::nodemap::FxHashMap;
34 use rustc_target::spec::abi;
37 use syntax::ast::{Ident, MetaItemKind};
38 use syntax::attr::{InlineAttr, OptimizeAttr, list_contains_name, mark_used};
39 use syntax::source_map::Spanned;
40 use syntax::feature_gate;
41 use syntax::symbol::{InternedString, kw, Symbol, sym};
42 use syntax_pos::{Span, DUMMY_SP};
44 use rustc::hir::def::{CtorKind, Res, DefKind};
46 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
47 use rustc::hir::intravisit::{self, NestedVisitorMap, Visitor};
48 use rustc::hir::GenericParamKind;
49 use rustc::hir::{self, CodegenFnAttrFlags, CodegenFnAttrs, Unsafety};
53 struct OnlySelfBounds(bool);
55 ///////////////////////////////////////////////////////////////////////////
58 fn collect_mod_item_types<'tcx>(tcx: TyCtxt<'_, 'tcx, 'tcx>, module_def_id: DefId) {
59 tcx.hir().visit_item_likes_in_module(
61 &mut CollectItemTypesVisitor { tcx }.as_deep_visitor()
65 pub fn provide(providers: &mut Providers<'_>) {
66 *providers = Providers {
70 predicates_defined_on,
71 explicit_predicates_of,
73 type_param_predicates,
82 collect_mod_item_types,
87 ///////////////////////////////////////////////////////////////////////////
89 /// Context specific to some particular item. This is what implements
90 /// `AstConv`. It has information about the predicates that are defined
91 /// on the trait. Unfortunately, this predicate information is
92 /// available in various different forms at various points in the
93 /// process. So we can't just store a pointer to e.g., the AST or the
94 /// parsed ty form, we have to be more flexible. To this end, the
95 /// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy
96 /// `get_type_parameter_bounds` requests, drawing the information from
97 /// the AST (`hir::Generics`), recursively.
98 pub struct ItemCtxt<'a, 'tcx: 'a> {
99 tcx: TyCtxt<'a, 'tcx, 'tcx>,
103 ///////////////////////////////////////////////////////////////////////////
105 struct CollectItemTypesVisitor<'a, 'tcx: 'a> {
106 tcx: TyCtxt<'a, 'tcx, 'tcx>,
109 impl<'a, 'tcx> Visitor<'tcx> for CollectItemTypesVisitor<'a, 'tcx> {
110 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
111 NestedVisitorMap::OnlyBodies(&self.tcx.hir())
114 fn visit_item(&mut self, item: &'tcx hir::Item) {
115 convert_item(self.tcx, item.hir_id);
116 intravisit::walk_item(self, item);
119 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
120 for param in &generics.params {
122 hir::GenericParamKind::Lifetime { .. } => {}
123 hir::GenericParamKind::Type {
126 let def_id = self.tcx.hir().local_def_id_from_hir_id(param.hir_id);
127 self.tcx.type_of(def_id);
129 hir::GenericParamKind::Type { .. } => {}
130 hir::GenericParamKind::Const { .. } => {
131 let def_id = self.tcx.hir().local_def_id_from_hir_id(param.hir_id);
132 self.tcx.type_of(def_id);
136 intravisit::walk_generics(self, generics);
139 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
140 if let hir::ExprKind::Closure(..) = expr.node {
141 let def_id = self.tcx.hir().local_def_id_from_hir_id(expr.hir_id);
142 self.tcx.generics_of(def_id);
143 self.tcx.type_of(def_id);
145 intravisit::walk_expr(self, expr);
148 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
149 convert_trait_item(self.tcx, trait_item.hir_id);
150 intravisit::walk_trait_item(self, trait_item);
153 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
154 convert_impl_item(self.tcx, impl_item.hir_id);
155 intravisit::walk_impl_item(self, impl_item);
159 ///////////////////////////////////////////////////////////////////////////
160 // Utility types and common code for the above passes.
162 impl<'a, 'tcx> ItemCtxt<'a, 'tcx> {
163 pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, item_def_id: DefId) -> ItemCtxt<'a, 'tcx> {
164 ItemCtxt { tcx, item_def_id }
168 impl<'a, 'tcx> ItemCtxt<'a, 'tcx> {
169 pub fn to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> {
170 AstConv::ast_ty_to_ty(self, ast_ty)
174 impl<'a, 'tcx> AstConv<'tcx, 'tcx> for ItemCtxt<'a, 'tcx> {
175 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'tcx, 'tcx> {
179 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId)
180 -> &'tcx ty::GenericPredicates<'tcx> {
183 .type_param_predicates((self.item_def_id, def_id))
189 _def: Option<&ty::GenericParamDef>,
190 ) -> Option<ty::Region<'tcx>> {
194 fn ty_infer(&self, span: Span) -> Ty<'tcx> {
199 "the type placeholder `_` is not allowed within types on item signatures"
200 ).span_label(span, "not allowed in type signatures")
206 fn projected_ty_from_poly_trait_ref(
210 poly_trait_ref: ty::PolyTraitRef<'tcx>,
212 if let Some(trait_ref) = poly_trait_ref.no_bound_vars() {
213 self.tcx().mk_projection(item_def_id, trait_ref.substs)
215 // no late-bound regions, we can just ignore the binder
220 "cannot extract an associated type from a higher-ranked trait bound \
227 fn normalize_ty(&self, _span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
228 // types in item signatures are not normalized, to avoid undue
233 fn set_tainted_by_errors(&self) {
234 // no obvious place to track this, just let it go
237 fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) {
238 // no place to record types from signatures?
242 fn type_param_predicates<'a, 'tcx>(
243 tcx: TyCtxt<'a, 'tcx, 'tcx>,
244 (item_def_id, def_id): (DefId, DefId),
245 ) -> &'tcx ty::GenericPredicates<'tcx> {
248 // In the AST, bounds can derive from two places. Either
249 // written inline like `<T : Foo>` or in a where clause like
252 let param_id = tcx.hir().as_local_hir_id(def_id).unwrap();
253 let param_owner = tcx.hir().ty_param_owner(param_id);
254 let param_owner_def_id = tcx.hir().local_def_id_from_hir_id(param_owner);
255 let generics = tcx.generics_of(param_owner_def_id);
256 let index = generics.param_def_id_to_index[&def_id];
257 let ty = tcx.mk_ty_param(index, tcx.hir().ty_param_name(param_id).as_interned_str());
259 // Don't look for bounds where the type parameter isn't in scope.
260 let parent = if item_def_id == param_owner_def_id {
263 tcx.generics_of(item_def_id).parent
266 let result = parent.map_or(&tcx.common.empty_predicates, |parent| {
267 let icx = ItemCtxt::new(tcx, parent);
268 icx.get_type_parameter_bounds(DUMMY_SP, def_id)
270 let mut extend = None;
272 let item_hir_id = tcx.hir().as_local_hir_id(item_def_id).unwrap();
273 let ast_generics = match tcx.hir().get_by_hir_id(item_hir_id) {
274 Node::TraitItem(item) => &item.generics,
276 Node::ImplItem(item) => &item.generics,
278 Node::Item(item) => {
280 ItemKind::Fn(.., ref generics, _)
281 | ItemKind::Impl(_, _, _, ref generics, ..)
282 | ItemKind::Ty(_, ref generics)
283 | ItemKind::Existential(ExistTy {
288 | ItemKind::Enum(_, ref generics)
289 | ItemKind::Struct(_, ref generics)
290 | ItemKind::Union(_, ref generics) => generics,
291 ItemKind::Trait(_, _, ref generics, ..) => {
292 // Implied `Self: Trait` and supertrait bounds.
293 if param_id == item_hir_id {
294 let identity_trait_ref = ty::TraitRef::identity(tcx, item_def_id);
295 extend = Some((identity_trait_ref.to_predicate(), item.span));
303 Node::ForeignItem(item) => match item.node {
304 ForeignItemKind::Fn(_, _, ref generics) => generics,
311 let icx = ItemCtxt::new(tcx, item_def_id);
312 let mut result = (*result).clone();
313 result.predicates.extend(extend.into_iter());
315 .extend(icx.type_parameter_bounds_in_generics(ast_generics, param_id, ty,
316 OnlySelfBounds(true)));
317 tcx.arena.alloc(result)
320 impl<'a, 'tcx> ItemCtxt<'a, 'tcx> {
321 /// Finds bounds from `hir::Generics`. This requires scanning through the
322 /// AST. We do this to avoid having to convert *all* the bounds, which
323 /// would create artificial cycles. Instead we can only convert the
324 /// bounds for a type parameter `X` if `X::Foo` is used.
325 fn type_parameter_bounds_in_generics(
327 ast_generics: &hir::Generics,
328 param_id: hir::HirId,
330 only_self_bounds: OnlySelfBounds,
331 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
332 let from_ty_params = ast_generics
335 .filter_map(|param| match param.kind {
336 GenericParamKind::Type { .. } if param.hir_id == param_id => Some(¶m.bounds),
339 .flat_map(|bounds| bounds.iter())
340 .flat_map(|b| predicates_from_bound(self, ty, b));
342 let from_where_clauses = ast_generics
346 .filter_map(|wp| match *wp {
347 hir::WherePredicate::BoundPredicate(ref bp) => Some(bp),
351 let bt = if is_param(self.tcx, &bp.bounded_ty, param_id) {
353 } else if !only_self_bounds.0 {
354 Some(self.to_ty(&bp.bounded_ty))
358 bp.bounds.iter().filter_map(move |b| bt.map(|bt| (bt, b)))
360 .flat_map(|(bt, b)| predicates_from_bound(self, bt, b));
362 from_ty_params.chain(from_where_clauses).collect()
366 /// Tests whether this is the AST for a reference to the type
367 /// parameter with ID `param_id`. We use this so as to avoid running
368 /// `ast_ty_to_ty`, because we want to avoid triggering an all-out
369 /// conversion of the type to avoid inducing unnecessary cycles.
370 fn is_param<'a, 'tcx>(
371 tcx: TyCtxt<'a, 'tcx, 'tcx>,
373 param_id: hir::HirId,
375 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = ast_ty.node {
377 Res::SelfTy(Some(def_id), None) | Res::Def(DefKind::TyParam, def_id) => {
378 def_id == tcx.hir().local_def_id_from_hir_id(param_id)
387 fn convert_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item_id: hir::HirId) {
388 let it = tcx.hir().expect_item_by_hir_id(item_id);
389 debug!("convert: item {} with id {}", it.ident, it.hir_id);
390 let def_id = tcx.hir().local_def_id_from_hir_id(item_id);
392 // These don't define types.
393 hir::ItemKind::ExternCrate(_)
394 | hir::ItemKind::Use(..)
395 | hir::ItemKind::Mod(_)
396 | hir::ItemKind::GlobalAsm(_) => {}
397 hir::ItemKind::ForeignMod(ref foreign_mod) => {
398 for item in &foreign_mod.items {
399 let def_id = tcx.hir().local_def_id_from_hir_id(item.hir_id);
400 tcx.generics_of(def_id);
402 tcx.predicates_of(def_id);
403 if let hir::ForeignItemKind::Fn(..) = item.node {
408 hir::ItemKind::Enum(ref enum_definition, _) => {
409 tcx.generics_of(def_id);
411 tcx.predicates_of(def_id);
412 convert_enum_variant_types(tcx, def_id, &enum_definition.variants);
414 hir::ItemKind::Impl(..) => {
415 tcx.generics_of(def_id);
417 tcx.impl_trait_ref(def_id);
418 tcx.predicates_of(def_id);
420 hir::ItemKind::Trait(..) => {
421 tcx.generics_of(def_id);
422 tcx.trait_def(def_id);
423 tcx.at(it.span).super_predicates_of(def_id);
424 tcx.predicates_of(def_id);
426 hir::ItemKind::TraitAlias(..) => {
427 tcx.generics_of(def_id);
428 tcx.at(it.span).super_predicates_of(def_id);
429 tcx.predicates_of(def_id);
431 hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
432 tcx.generics_of(def_id);
434 tcx.predicates_of(def_id);
436 for f in struct_def.fields() {
437 let def_id = tcx.hir().local_def_id_from_hir_id(f.hir_id);
438 tcx.generics_of(def_id);
440 tcx.predicates_of(def_id);
443 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
444 convert_variant_ctor(tcx, ctor_hir_id);
448 // Desugared from `impl Trait` -> visited by the function's return type
449 hir::ItemKind::Existential(hir::ExistTy {
450 impl_trait_fn: Some(_),
454 hir::ItemKind::Existential(..)
455 | hir::ItemKind::Ty(..)
456 | hir::ItemKind::Static(..)
457 | hir::ItemKind::Const(..)
458 | hir::ItemKind::Fn(..) => {
459 tcx.generics_of(def_id);
461 tcx.predicates_of(def_id);
462 if let hir::ItemKind::Fn(..) = it.node {
469 fn convert_trait_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, trait_item_id: hir::HirId) {
470 let trait_item = tcx.hir().expect_trait_item(trait_item_id);
471 let def_id = tcx.hir().local_def_id_from_hir_id(trait_item.hir_id);
472 tcx.generics_of(def_id);
474 match trait_item.node {
475 hir::TraitItemKind::Const(..)
476 | hir::TraitItemKind::Type(_, Some(_))
477 | hir::TraitItemKind::Method(..) => {
479 if let hir::TraitItemKind::Method(..) = trait_item.node {
484 hir::TraitItemKind::Type(_, None) => {}
487 tcx.predicates_of(def_id);
490 fn convert_impl_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, impl_item_id: hir::HirId) {
491 let def_id = tcx.hir().local_def_id_from_hir_id(impl_item_id);
492 tcx.generics_of(def_id);
494 tcx.predicates_of(def_id);
495 if let hir::ImplItemKind::Method(..) = tcx.hir().expect_impl_item(impl_item_id).node {
500 fn convert_variant_ctor<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ctor_id: hir::HirId) {
501 let def_id = tcx.hir().local_def_id_from_hir_id(ctor_id);
502 tcx.generics_of(def_id);
504 tcx.predicates_of(def_id);
507 fn convert_enum_variant_types<'a, 'tcx>(
508 tcx: TyCtxt<'a, 'tcx, 'tcx>,
510 variants: &[hir::Variant],
512 let def = tcx.adt_def(def_id);
513 let repr_type = def.repr.discr_type();
514 let initial = repr_type.initial_discriminant(tcx);
515 let mut prev_discr = None::<Discr<'tcx>>;
517 // fill the discriminant values and field types
518 for variant in variants {
519 let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
521 if let Some(ref e) = variant.node.disr_expr {
522 let expr_did = tcx.hir().local_def_id_from_hir_id(e.hir_id);
523 def.eval_explicit_discr(tcx, expr_did)
524 } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) {
531 "enum discriminant overflowed"
534 format!("overflowed on value after {}", prev_discr.unwrap()),
536 "explicitly set `{} = {}` if that is desired outcome",
537 variant.node.ident, wrapped_discr
541 }.unwrap_or(wrapped_discr),
544 for f in variant.node.data.fields() {
545 let def_id = tcx.hir().local_def_id_from_hir_id(f.hir_id);
546 tcx.generics_of(def_id);
548 tcx.predicates_of(def_id);
551 // Convert the ctor, if any. This also registers the variant as
553 if let Some(ctor_hir_id) = variant.node.data.ctor_hir_id() {
554 convert_variant_ctor(tcx, ctor_hir_id);
559 fn convert_variant<'a, 'tcx>(
560 tcx: TyCtxt<'a, 'tcx, 'tcx>,
561 variant_did: Option<DefId>,
562 ctor_did: Option<DefId>,
564 discr: ty::VariantDiscr,
565 def: &hir::VariantData,
566 adt_kind: ty::AdtKind,
568 ) -> ty::VariantDef {
569 let mut seen_fields: FxHashMap<ast::Ident, Span> = Default::default();
570 let hir_id = tcx.hir().as_local_hir_id(variant_did.unwrap_or(parent_did)).unwrap();
575 let fid = tcx.hir().local_def_id_from_hir_id(f.hir_id);
576 let dup_span = seen_fields.get(&f.ident.modern()).cloned();
577 if let Some(prev_span) = dup_span {
582 "field `{}` is already declared",
584 ).span_label(f.span, "field already declared")
585 .span_label(prev_span, format!("`{}` first declared here", f.ident))
588 seen_fields.insert(f.ident.modern(), f.span);
594 vis: ty::Visibility::from_hir(&f.vis, hir_id, tcx),
598 let recovered = match def {
599 hir::VariantData::Struct(_, r) => *r,
609 CtorKind::from_hir(def),
616 fn adt_def<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx ty::AdtDef {
619 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
620 let item = match tcx.hir().get_by_hir_id(hir_id) {
621 Node::Item(item) => item,
625 let repr = ReprOptions::new(tcx, def_id);
626 let (kind, variants) = match item.node {
627 ItemKind::Enum(ref def, _) => {
628 let mut distance_from_explicit = 0;
629 let variants = def.variants
632 let variant_did = Some(tcx.hir().local_def_id_from_hir_id(v.node.id));
633 let ctor_did = v.node.data.ctor_hir_id()
634 .map(|hir_id| tcx.hir().local_def_id_from_hir_id(hir_id));
636 let discr = if let Some(ref e) = v.node.disr_expr {
637 distance_from_explicit = 0;
638 ty::VariantDiscr::Explicit(tcx.hir().local_def_id_from_hir_id(e.hir_id))
640 ty::VariantDiscr::Relative(distance_from_explicit)
642 distance_from_explicit += 1;
644 convert_variant(tcx, variant_did, ctor_did, v.node.ident, discr,
645 &v.node.data, AdtKind::Enum, def_id)
649 (AdtKind::Enum, variants)
651 ItemKind::Struct(ref def, _) => {
652 let variant_did = None;
653 let ctor_did = def.ctor_hir_id()
654 .map(|hir_id| tcx.hir().local_def_id_from_hir_id(hir_id));
656 let variants = std::iter::once(convert_variant(
657 tcx, variant_did, ctor_did, item.ident, ty::VariantDiscr::Relative(0), def,
658 AdtKind::Struct, def_id,
661 (AdtKind::Struct, variants)
663 ItemKind::Union(ref def, _) => {
664 let variant_did = None;
665 let ctor_did = def.ctor_hir_id()
666 .map(|hir_id| tcx.hir().local_def_id_from_hir_id(hir_id));
668 let variants = std::iter::once(convert_variant(
669 tcx, variant_did, ctor_did, item.ident, ty::VariantDiscr::Relative(0), def,
670 AdtKind::Union, def_id,
673 (AdtKind::Union, variants)
677 tcx.alloc_adt_def(def_id, kind, variants, repr)
680 /// Ensures that the super-predicates of the trait with a `DefId`
681 /// of `trait_def_id` are converted and stored. This also ensures that
682 /// the transitive super-predicates are converted.
683 fn super_predicates_of<'a, 'tcx>(
684 tcx: TyCtxt<'a, 'tcx, 'tcx>,
686 ) -> &'tcx ty::GenericPredicates<'tcx> {
687 debug!("super_predicates(trait_def_id={:?})", trait_def_id);
688 let trait_hir_id = tcx.hir().as_local_hir_id(trait_def_id).unwrap();
690 let item = match tcx.hir().get_by_hir_id(trait_hir_id) {
691 Node::Item(item) => item,
692 _ => bug!("trait_node_id {} is not an item", trait_hir_id),
695 let (generics, bounds) = match item.node {
696 hir::ItemKind::Trait(.., ref generics, ref supertraits, _) => (generics, supertraits),
697 hir::ItemKind::TraitAlias(ref generics, ref supertraits) => (generics, supertraits),
698 _ => span_bug!(item.span, "super_predicates invoked on non-trait"),
701 let icx = ItemCtxt::new(tcx, trait_def_id);
703 // Convert the bounds that follow the colon, e.g., `Bar + Zed` in `trait Foo: Bar + Zed`.
704 let self_param_ty = tcx.mk_self_type();
705 let superbounds1 = compute_bounds(&icx, self_param_ty, bounds, SizedByDefault::No, item.span);
707 let superbounds1 = superbounds1.predicates(tcx, self_param_ty);
709 // Convert any explicit superbounds in the where-clause,
710 // e.g., `trait Foo where Self: Bar`.
711 // In the case of trait aliases, however, we include all bounds in the where-clause,
712 // so e.g., `trait Foo = where u32: PartialEq<Self>` would include `u32: PartialEq<Self>`
713 // as one of its "superpredicates".
714 let is_trait_alias = tcx.is_trait_alias(trait_def_id);
715 let superbounds2 = icx.type_parameter_bounds_in_generics(
716 generics, item.hir_id, self_param_ty, OnlySelfBounds(!is_trait_alias));
718 // Combine the two lists to form the complete set of superbounds:
719 let superbounds: Vec<_> = superbounds1.into_iter().chain(superbounds2).collect();
721 // Now require that immediate supertraits are converted,
722 // which will, in turn, reach indirect supertraits.
723 for &(pred, span) in &superbounds {
724 debug!("superbound: {:?}", pred);
725 if let ty::Predicate::Trait(bound) = pred {
726 tcx.at(span).super_predicates_of(bound.def_id());
730 tcx.arena.alloc(ty::GenericPredicates {
732 predicates: superbounds,
736 fn trait_def<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx ty::TraitDef {
737 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
738 let item = tcx.hir().expect_item_by_hir_id(hir_id);
740 let (is_auto, unsafety) = match item.node {
741 hir::ItemKind::Trait(is_auto, unsafety, ..) => (is_auto == hir::IsAuto::Yes, unsafety),
742 hir::ItemKind::TraitAlias(..) => (false, hir::Unsafety::Normal),
743 _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
746 let paren_sugar = tcx.has_attr(def_id, sym::rustc_paren_sugar);
747 if paren_sugar && !tcx.features().unboxed_closures {
748 let mut err = tcx.sess.struct_span_err(
750 "the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \
751 which traits can use parenthetical notation",
755 "add `#![feature(unboxed_closures)]` to \
756 the crate attributes to use it"
761 let is_marker = tcx.has_attr(def_id, sym::marker);
762 let def_path_hash = tcx.def_path_hash(def_id);
763 let def = ty::TraitDef::new(def_id, unsafety, paren_sugar, is_auto, is_marker, def_path_hash);
764 tcx.alloc_trait_def(def)
767 fn has_late_bound_regions<'a, 'tcx>(
768 tcx: TyCtxt<'a, 'tcx, 'tcx>,
771 struct LateBoundRegionsDetector<'a, 'tcx: 'a> {
772 tcx: TyCtxt<'a, 'tcx, 'tcx>,
773 outer_index: ty::DebruijnIndex,
774 has_late_bound_regions: Option<Span>,
777 impl<'a, 'tcx> Visitor<'tcx> for LateBoundRegionsDetector<'a, 'tcx> {
778 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
779 NestedVisitorMap::None
782 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
783 if self.has_late_bound_regions.is_some() {
787 hir::TyKind::BareFn(..) => {
788 self.outer_index.shift_in(1);
789 intravisit::walk_ty(self, ty);
790 self.outer_index.shift_out(1);
792 _ => intravisit::walk_ty(self, ty),
796 fn visit_poly_trait_ref(
798 tr: &'tcx hir::PolyTraitRef,
799 m: hir::TraitBoundModifier,
801 if self.has_late_bound_regions.is_some() {
804 self.outer_index.shift_in(1);
805 intravisit::walk_poly_trait_ref(self, tr, m);
806 self.outer_index.shift_out(1);
809 fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
810 if self.has_late_bound_regions.is_some() {
814 match self.tcx.named_region(lt.hir_id) {
815 Some(rl::Region::Static) | Some(rl::Region::EarlyBound(..)) => {}
816 Some(rl::Region::LateBound(debruijn, _, _))
817 | Some(rl::Region::LateBoundAnon(debruijn, _)) if debruijn < self.outer_index => {}
818 Some(rl::Region::LateBound(..))
819 | Some(rl::Region::LateBoundAnon(..))
820 | Some(rl::Region::Free(..))
822 self.has_late_bound_regions = Some(lt.span);
828 fn has_late_bound_regions<'a, 'tcx>(
829 tcx: TyCtxt<'a, 'tcx, 'tcx>,
830 generics: &'tcx hir::Generics,
831 decl: &'tcx hir::FnDecl,
833 let mut visitor = LateBoundRegionsDetector {
835 outer_index: ty::INNERMOST,
836 has_late_bound_regions: None,
838 for param in &generics.params {
839 if let GenericParamKind::Lifetime { .. } = param.kind {
840 if tcx.is_late_bound(param.hir_id) {
841 return Some(param.span);
845 visitor.visit_fn_decl(decl);
846 visitor.has_late_bound_regions
850 Node::TraitItem(item) => match item.node {
851 hir::TraitItemKind::Method(ref sig, _) => {
852 has_late_bound_regions(tcx, &item.generics, &sig.decl)
856 Node::ImplItem(item) => match item.node {
857 hir::ImplItemKind::Method(ref sig, _) => {
858 has_late_bound_regions(tcx, &item.generics, &sig.decl)
862 Node::ForeignItem(item) => match item.node {
863 hir::ForeignItemKind::Fn(ref fn_decl, _, ref generics) => {
864 has_late_bound_regions(tcx, generics, fn_decl)
868 Node::Item(item) => match item.node {
869 hir::ItemKind::Fn(ref fn_decl, .., ref generics, _) => {
870 has_late_bound_regions(tcx, generics, fn_decl)
878 fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx ty::Generics {
881 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
883 let node = tcx.hir().get_by_hir_id(hir_id);
884 let parent_def_id = match node {
885 Node::ImplItem(_) | Node::TraitItem(_) | Node::Variant(_) |
886 Node::Ctor(..) | Node::Field(_) => {
887 let parent_id = tcx.hir().get_parent_item(hir_id);
888 Some(tcx.hir().local_def_id_from_hir_id(parent_id))
890 Node::Expr(&hir::Expr {
891 node: hir::ExprKind::Closure(..),
893 }) => Some(tcx.closure_base_def_id(def_id)),
894 Node::Item(item) => match item.node {
895 ItemKind::Existential(hir::ExistTy { impl_trait_fn, .. }) => impl_trait_fn,
901 let mut opt_self = None;
902 let mut allow_defaults = false;
904 let no_generics = hir::Generics::empty();
905 let ast_generics = match node {
906 Node::TraitItem(item) => &item.generics,
908 Node::ImplItem(item) => &item.generics,
910 Node::Item(item) => {
912 ItemKind::Fn(.., ref generics, _) | ItemKind::Impl(_, _, _, ref generics, ..) => {
916 ItemKind::Ty(_, ref generics)
917 | ItemKind::Enum(_, ref generics)
918 | ItemKind::Struct(_, ref generics)
919 | ItemKind::Existential(hir::ExistTy { ref generics, .. })
920 | ItemKind::Union(_, ref generics) => {
921 allow_defaults = true;
925 ItemKind::Trait(_, _, ref generics, ..)
926 | ItemKind::TraitAlias(ref generics, ..) => {
927 // Add in the self type parameter.
929 // Something of a hack: use the node id for the trait, also as
930 // the node id for the Self type parameter.
931 let param_id = item.hir_id;
933 opt_self = Some(ty::GenericParamDef {
935 name: kw::SelfUpper.as_interned_str(),
936 def_id: tcx.hir().local_def_id_from_hir_id(param_id),
937 pure_wrt_drop: false,
938 kind: ty::GenericParamDefKind::Type {
940 object_lifetime_default: rl::Set1::Empty,
945 allow_defaults = true;
953 Node::ForeignItem(item) => match item.node {
954 ForeignItemKind::Static(..) => &no_generics,
955 ForeignItemKind::Fn(_, _, ref generics) => generics,
956 ForeignItemKind::Type => &no_generics,
962 let has_self = opt_self.is_some();
963 let mut parent_has_self = false;
964 let mut own_start = has_self as u32;
965 let parent_count = parent_def_id.map_or(0, |def_id| {
966 let generics = tcx.generics_of(def_id);
967 assert_eq!(has_self, false);
968 parent_has_self = generics.has_self;
969 own_start = generics.count() as u32;
970 generics.parent_count + generics.params.len()
973 let mut params: Vec<_> = opt_self.into_iter().collect();
975 let early_lifetimes = early_bound_lifetimes_from_generics(tcx, ast_generics);
979 .map(|(i, param)| ty::GenericParamDef {
980 name: param.name.ident().as_interned_str(),
981 index: own_start + i as u32,
982 def_id: tcx.hir().local_def_id_from_hir_id(param.hir_id),
983 pure_wrt_drop: param.pure_wrt_drop,
984 kind: ty::GenericParamDefKind::Lifetime,
988 let object_lifetime_defaults = tcx.object_lifetime_defaults(hir_id);
990 // Now create the real type parameters.
991 let type_start = own_start - has_self as u32 + params.len() as u32;
997 .filter_map(|param| {
998 let kind = match param.kind {
999 GenericParamKind::Type {
1004 if param.name.ident().name == kw::SelfUpper {
1007 "`Self` should not be the name of a regular parameter"
1011 if !allow_defaults && default.is_some() {
1012 if !tcx.features().default_type_parameter_fallback {
1014 lint::builtin::INVALID_TYPE_PARAM_DEFAULT,
1018 "defaults for type parameters are only allowed in \
1019 `struct`, `enum`, `type`, or `trait` definitions."
1025 ty::GenericParamDefKind::Type {
1026 has_default: default.is_some(),
1027 object_lifetime_default: object_lifetime_defaults
1029 .map_or(rl::Set1::Empty, |o| o[i]),
1033 GenericParamKind::Const { .. } => {
1034 if param.name.ident().name == kw::SelfUpper {
1037 "`Self` should not be the name of a regular parameter",
1041 ty::GenericParamDefKind::Const
1046 let param_def = ty::GenericParamDef {
1047 index: type_start + i as u32,
1048 name: param.name.ident().as_interned_str(),
1049 def_id: tcx.hir().local_def_id_from_hir_id(param.hir_id),
1050 pure_wrt_drop: param.pure_wrt_drop,
1058 // provide junk type parameter defs - the only place that
1059 // cares about anything but the length is instantiation,
1060 // and we don't do that for closures.
1061 if let Node::Expr(&hir::Expr {
1062 node: hir::ExprKind::Closure(.., gen),
1066 let dummy_args = if gen.is_some() {
1067 &["<yield_ty>", "<return_ty>", "<witness>"][..]
1069 &["<closure_kind>", "<closure_signature>"][..]
1076 .map(|(i, &arg)| ty::GenericParamDef {
1077 index: type_start + i as u32,
1078 name: InternedString::intern(arg),
1080 pure_wrt_drop: false,
1081 kind: ty::GenericParamDefKind::Type {
1083 object_lifetime_default: rl::Set1::Empty,
1089 if let Some(upvars) = tcx.upvars(def_id) {
1090 params.extend(upvars.iter().zip((dummy_args.len() as u32)..).map(|(_, i)| {
1091 ty::GenericParamDef {
1092 index: type_start + i,
1093 name: InternedString::intern("<upvar>"),
1095 pure_wrt_drop: false,
1096 kind: ty::GenericParamDefKind::Type {
1098 object_lifetime_default: rl::Set1::Empty,
1106 let param_def_id_to_index = params
1108 .map(|param| (param.def_id, param.index))
1111 tcx.alloc_generics(ty::Generics {
1112 parent: parent_def_id,
1115 param_def_id_to_index,
1116 has_self: has_self || parent_has_self,
1117 has_late_bound_regions: has_late_bound_regions(tcx, node),
1121 fn report_assoc_ty_on_inherent_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, span: Span) {
1126 "associated types are not yet supported in inherent impls (see #8995)"
1130 fn type_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Ty<'tcx> {
1131 checked_type_of(tcx, def_id, true).unwrap()
1134 /// Same as [`type_of`] but returns [`Option`] instead of failing.
1136 /// If you want to fail anyway, you can set the `fail` parameter to true, but in this case,
1137 /// you'd better just call [`type_of`] directly.
1138 pub fn checked_type_of<'a, 'tcx>(
1139 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1142 ) -> Option<Ty<'tcx>> {
1145 let hir_id = match tcx.hir().as_local_hir_id(def_id) {
1146 Some(hir_id) => hir_id,
1151 bug!("invalid node");
1155 let icx = ItemCtxt::new(tcx, def_id);
1157 Some(match tcx.hir().get_by_hir_id(hir_id) {
1158 Node::TraitItem(item) => match item.node {
1159 TraitItemKind::Method(..) => {
1160 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1161 tcx.mk_fn_def(def_id, substs)
1163 TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => icx.to_ty(ty),
1164 TraitItemKind::Type(_, None) => {
1168 span_bug!(item.span, "associated type missing default");
1172 Node::ImplItem(item) => match item.node {
1173 ImplItemKind::Method(..) => {
1174 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1175 tcx.mk_fn_def(def_id, substs)
1177 ImplItemKind::Const(ref ty, _) => icx.to_ty(ty),
1178 ImplItemKind::Existential(_) => {
1180 .impl_trait_ref(tcx.hir().get_parent_did_by_hir_id(hir_id))
1183 report_assoc_ty_on_inherent_impl(tcx, item.span);
1186 find_existential_constraints(tcx, def_id)
1188 ImplItemKind::Type(ref ty) => {
1190 .impl_trait_ref(tcx.hir().get_parent_did_by_hir_id(hir_id))
1193 report_assoc_ty_on_inherent_impl(tcx, item.span);
1200 Node::Item(item) => {
1202 ItemKind::Static(ref t, ..)
1203 | ItemKind::Const(ref t, _)
1204 | ItemKind::Ty(ref t, _)
1205 | ItemKind::Impl(.., ref t, _) => icx.to_ty(t),
1206 ItemKind::Fn(..) => {
1207 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1208 tcx.mk_fn_def(def_id, substs)
1210 ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
1211 let def = tcx.adt_def(def_id);
1212 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1213 tcx.mk_adt(def, substs)
1215 ItemKind::Existential(hir::ExistTy {
1216 impl_trait_fn: None,
1218 }) => find_existential_constraints(tcx, def_id),
1219 // existential types desugared from impl Trait
1220 ItemKind::Existential(hir::ExistTy {
1221 impl_trait_fn: Some(owner),
1224 tcx.typeck_tables_of(owner)
1225 .concrete_existential_types
1227 .map(|opaque| opaque.concrete_type)
1228 .unwrap_or_else(|| {
1229 // This can occur if some error in the
1230 // owner fn prevented us from populating
1231 // the `concrete_existential_types` table.
1232 tcx.sess.delay_span_bug(
1235 "owner {:?} has no existential type for {:?} in its tables",
1243 | ItemKind::TraitAlias(..)
1245 | ItemKind::ForeignMod(..)
1246 | ItemKind::GlobalAsm(..)
1247 | ItemKind::ExternCrate(..)
1248 | ItemKind::Use(..) => {
1254 "compute_type_of_item: unexpected item type: {:?}",
1261 Node::ForeignItem(foreign_item) => match foreign_item.node {
1262 ForeignItemKind::Fn(..) => {
1263 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1264 tcx.mk_fn_def(def_id, substs)
1266 ForeignItemKind::Static(ref t, _) => icx.to_ty(t),
1267 ForeignItemKind::Type => tcx.mk_foreign(def_id),
1270 Node::Ctor(&ref def) | Node::Variant(&Spanned {
1271 node: hir::VariantKind { data: ref def, .. },
1274 VariantData::Unit(..) | VariantData::Struct(..) => {
1275 tcx.type_of(tcx.hir().get_parent_did_by_hir_id(hir_id))
1277 VariantData::Tuple(..) => {
1278 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1279 tcx.mk_fn_def(def_id, substs)
1283 Node::Field(field) => icx.to_ty(&field.ty),
1285 Node::Expr(&hir::Expr {
1286 node: hir::ExprKind::Closure(.., gen),
1290 return Some(tcx.typeck_tables_of(def_id).node_type(hir_id));
1293 let substs = ty::ClosureSubsts {
1294 substs: InternalSubsts::identity_for_item(tcx, def_id),
1297 tcx.mk_closure(def_id, substs)
1300 Node::AnonConst(_) => {
1301 let parent_node = tcx.hir().get_by_hir_id(tcx.hir().get_parent_node_by_hir_id(hir_id));
1304 node: hir::TyKind::Array(_, ref constant),
1307 | Node::Ty(&hir::Ty {
1308 node: hir::TyKind::Typeof(ref constant),
1311 | Node::Expr(&hir::Expr {
1312 node: ExprKind::Repeat(_, ref constant),
1314 }) if constant.hir_id == hir_id =>
1319 Node::Variant(&Spanned {
1322 disr_expr: Some(ref e),
1326 }) if e.hir_id == hir_id =>
1328 tcx.adt_def(tcx.hir().get_parent_did_by_hir_id(hir_id))
1334 Node::Ty(&hir::Ty { node: hir::TyKind::Path(_), .. }) |
1335 Node::Expr(&hir::Expr { node: ExprKind::Struct(..), .. }) |
1336 Node::Expr(&hir::Expr { node: ExprKind::Path(_), .. }) => {
1337 let path = match parent_node {
1338 Node::Ty(&hir::Ty { node: hir::TyKind::Path(ref path), .. }) |
1339 Node::Expr(&hir::Expr { node: ExprKind::Path(ref path), .. }) => {
1342 Node::Expr(&hir::Expr { node: ExprKind::Struct(ref path, ..), .. }) => {
1345 _ => unreachable!(),
1349 QPath::Resolved(_, ref path) => {
1350 let mut arg_index = 0;
1351 let mut found_const = false;
1352 for seg in &path.segments {
1353 if let Some(generic_args) = &seg.args {
1354 let args = &generic_args.args;
1356 if let GenericArg::Const(ct) = arg {
1357 if ct.value.hir_id == hir_id {
1366 // Sanity check to make sure everything is as expected.
1371 bug!("no arg matching AnonConst in path")
1374 // We've encountered an `AnonConst` in some path, so we need to
1375 // figure out which generic parameter it corresponds to and return
1376 // the relevant type.
1377 Res::Def(DefKind::Struct, def_id)
1378 | Res::Def(DefKind::Union, def_id)
1379 | Res::Def(DefKind::Enum, def_id)
1380 | Res::Def(DefKind::Fn, def_id) => {
1381 let generics = tcx.generics_of(def_id);
1382 let mut param_index = 0;
1383 for param in &generics.params {
1384 if let ty::GenericParamDefKind::Const = param.kind {
1385 if param_index == arg_index {
1386 return Some(tcx.type_of(param.def_id));
1391 // This is no generic parameter associated with the arg. This is
1392 // probably from an extra arg where one is not needed.
1393 return Some(tcx.types.err);
1395 Res::Err => tcx.types.err,
1400 tcx.sess.delay_span_bug(
1403 "unexpected const parent path def {:?}", x
1414 tcx.sess.delay_span_bug(
1417 "unexpected const parent path {:?}", x
1429 tcx.sess.delay_span_bug(
1432 "unexpected const parent in type_of_def_id(): {:?}", x
1440 Node::GenericParam(param) => match ¶m.kind {
1441 hir::GenericParamKind::Type { default: Some(ref ty), .. } |
1442 hir::GenericParamKind::Const { ref ty, .. } => {
1449 bug!("unexpected non-type Node::GenericParam: {:?}", x)
1457 bug!("unexpected sort of node in type_of_def_id(): {:?}", x);
1462 fn find_existential_constraints<'a, 'tcx>(
1463 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1466 use rustc::hir::{ImplItem, Item, TraitItem};
1468 struct ConstraintLocator<'a, 'tcx: 'a> {
1469 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1471 // First found type span, actual type, mapping from the existential type's generic
1472 // parameters to the concrete type's generic parameters
1474 // The mapping is an index for each use site of a generic parameter in the concrete type
1476 // The indices index into the generic parameters on the existential type.
1477 found: Option<(Span, Ty<'tcx>, Vec<usize>)>,
1480 impl<'a, 'tcx> ConstraintLocator<'a, 'tcx> {
1481 fn check(&mut self, def_id: DefId) {
1482 trace!("checking {:?}", def_id);
1483 // don't try to check items that cannot possibly constrain the type
1484 if !self.tcx.has_typeck_tables(def_id) {
1485 trace!("no typeck tables for {:?}", def_id);
1490 .typeck_tables_of(def_id)
1491 .concrete_existential_types
1493 if let Some(ty::ResolvedOpaqueTy { concrete_type, substs }) = ty {
1494 // FIXME(oli-obk): trace the actual span from inference to improve errors
1495 let span = self.tcx.def_span(def_id);
1496 // used to quickly look up the position of a generic parameter
1497 let mut index_map: FxHashMap<ty::ParamTy, usize> = FxHashMap::default();
1498 // skip binder is ok, since we only use this to find generic parameters and their
1500 for (idx, subst) in substs.iter().enumerate() {
1501 if let UnpackedKind::Type(ty) = subst.unpack() {
1502 if let ty::Param(p) = ty.sty {
1503 if index_map.insert(p, idx).is_some() {
1504 // there was already an entry for `p`, meaning a generic parameter
1506 self.tcx.sess.span_err(
1508 &format!("defining existential type use restricts existential \
1509 type by using the generic parameter `{}` twice", p.name),
1514 self.tcx.sess.delay_span_bug(
1517 "non-defining exist ty use in defining scope: {:?}, {:?}",
1518 concrete_type, substs,
1524 // compute the index within the existential type for each generic parameter used in
1525 // the concrete type
1526 let indices = concrete_type
1527 .subst(self.tcx, substs)
1529 .filter_map(|t| match &t.sty {
1530 ty::Param(p) => Some(*index_map.get(p).unwrap()),
1533 let is_param = |ty: Ty<'_>| match ty.sty {
1534 ty::Param(_) => true,
1537 if !substs.types().all(is_param) {
1538 self.tcx.sess.span_err(
1540 "defining existential type use does not fully define existential type",
1542 } else if let Some((prev_span, prev_ty, ref prev_indices)) = self.found {
1543 let mut ty = concrete_type.walk().fuse();
1544 let mut p_ty = prev_ty.walk().fuse();
1545 let iter_eq = (&mut ty).zip(&mut p_ty).all(|(t, p)| match (&t.sty, &p.sty) {
1546 // type parameters are equal to any other type parameter for the purpose of
1547 // concrete type equality, as it is possible to obtain the same type just
1548 // by passing matching parameters to a function.
1549 (ty::Param(_), ty::Param(_)) => true,
1552 if !iter_eq || ty.next().is_some() || p_ty.next().is_some() {
1553 // found different concrete types for the existential type
1554 let mut err = self.tcx.sess.struct_span_err(
1556 "concrete type differs from previous defining existential type use",
1560 format!("expected `{}`, got `{}`", prev_ty, concrete_type),
1562 err.span_note(prev_span, "previous use here");
1564 } else if indices != *prev_indices {
1565 // found "same" concrete types, but the generic parameter order differs
1566 let mut err = self.tcx.sess.struct_span_err(
1568 "concrete type's generic parameters differ from previous defining use",
1570 use std::fmt::Write;
1571 let mut s = String::new();
1572 write!(s, "expected [").unwrap();
1573 let list = |s: &mut String, indices: &Vec<usize>| {
1574 let mut indices = indices.iter().cloned();
1575 if let Some(first) = indices.next() {
1576 write!(s, "`{}`", substs[first]).unwrap();
1578 write!(s, ", `{}`", substs[i]).unwrap();
1582 list(&mut s, prev_indices);
1583 write!(s, "], got [").unwrap();
1584 list(&mut s, &indices);
1585 write!(s, "]").unwrap();
1586 err.span_label(span, s);
1587 err.span_note(prev_span, "previous use here");
1591 self.found = Some((span, concrete_type, indices));
1597 impl<'a, 'tcx> intravisit::Visitor<'tcx> for ConstraintLocator<'a, 'tcx> {
1598 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
1599 intravisit::NestedVisitorMap::All(&self.tcx.hir())
1601 fn visit_item(&mut self, it: &'tcx Item) {
1602 let def_id = self.tcx.hir().local_def_id_from_hir_id(it.hir_id);
1603 // the existential type itself or its children are not within its reveal scope
1604 if def_id != self.def_id {
1606 intravisit::walk_item(self, it);
1609 fn visit_impl_item(&mut self, it: &'tcx ImplItem) {
1610 let def_id = self.tcx.hir().local_def_id_from_hir_id(it.hir_id);
1611 // the existential type itself or its children are not within its reveal scope
1612 if def_id != self.def_id {
1614 intravisit::walk_impl_item(self, it);
1617 fn visit_trait_item(&mut self, it: &'tcx TraitItem) {
1618 let def_id = self.tcx.hir().local_def_id_from_hir_id(it.hir_id);
1620 intravisit::walk_trait_item(self, it);
1624 let mut locator = ConstraintLocator {
1629 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1630 let parent = tcx.hir().get_parent_item(hir_id);
1632 trace!("parent_id: {:?}", parent);
1634 if parent == hir::CRATE_HIR_ID {
1635 intravisit::walk_crate(&mut locator, tcx.hir().krate());
1637 trace!("parent: {:?}", tcx.hir().get_by_hir_id(parent));
1638 match tcx.hir().get_by_hir_id(parent) {
1639 Node::Item(ref it) => intravisit::walk_item(&mut locator, it),
1640 Node::ImplItem(ref it) => intravisit::walk_impl_item(&mut locator, it),
1641 Node::TraitItem(ref it) => intravisit::walk_trait_item(&mut locator, it),
1643 "{:?} is not a valid parent of an existential type item",
1649 match locator.found {
1650 Some((_, ty, _)) => ty,
1652 let span = tcx.def_span(def_id);
1653 tcx.sess.span_err(span, "could not find defining uses");
1659 fn fn_sig<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> ty::PolyFnSig<'tcx> {
1661 use rustc::hir::Node::*;
1663 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1665 let icx = ItemCtxt::new(tcx, def_id);
1667 match tcx.hir().get_by_hir_id(hir_id) {
1668 TraitItem(hir::TraitItem {
1669 node: TraitItemKind::Method(sig, _),
1672 | ImplItem(hir::ImplItem {
1673 node: ImplItemKind::Method(sig, _),
1675 }) => AstConv::ty_of_fn(&icx, sig.header.unsafety, sig.header.abi, &sig.decl),
1678 node: ItemKind::Fn(decl, header, _, _),
1680 }) => AstConv::ty_of_fn(&icx, header.unsafety, header.abi, decl),
1682 ForeignItem(&hir::ForeignItem {
1683 node: ForeignItemKind::Fn(ref fn_decl, _, _),
1686 let abi = tcx.hir().get_foreign_abi_by_hir_id(hir_id);
1687 compute_sig_of_foreign_fn_decl(tcx, def_id, fn_decl, abi)
1690 Ctor(data) | Variant(Spanned {
1691 node: hir::VariantKind { data, .. },
1693 }) if data.ctor_hir_id().is_some() => {
1694 let ty = tcx.type_of(tcx.hir().get_parent_did_by_hir_id(hir_id));
1695 let inputs = data.fields()
1697 .map(|f| tcx.type_of(tcx.hir().local_def_id_from_hir_id(f.hir_id)));
1698 ty::Binder::bind(tcx.mk_fn_sig(
1702 hir::Unsafety::Normal,
1708 node: hir::ExprKind::Closure(..),
1711 // Closure signatures are not like other function
1712 // signatures and cannot be accessed through `fn_sig`. For
1713 // example, a closure signature excludes the `self`
1714 // argument. In any case they are embedded within the
1715 // closure type as part of the `ClosureSubsts`.
1718 // the signature of a closure, you should use the
1719 // `closure_sig` method on the `ClosureSubsts`:
1721 // closure_substs.closure_sig(def_id, tcx)
1723 // or, inside of an inference context, you can use
1725 // infcx.closure_sig(def_id, closure_substs)
1726 bug!("to get the signature of a closure, use `closure_sig()` not `fn_sig()`");
1730 bug!("unexpected sort of node in fn_sig(): {:?}", x);
1735 fn impl_trait_ref<'a, 'tcx>(
1736 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1738 ) -> Option<ty::TraitRef<'tcx>> {
1739 let icx = ItemCtxt::new(tcx, def_id);
1741 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1742 match tcx.hir().expect_item_by_hir_id(hir_id).node {
1743 hir::ItemKind::Impl(.., ref opt_trait_ref, _, _) => {
1744 opt_trait_ref.as_ref().map(|ast_trait_ref| {
1745 let selfty = tcx.type_of(def_id);
1746 AstConv::instantiate_mono_trait_ref(&icx, ast_trait_ref, selfty)
1753 fn impl_polarity<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> hir::ImplPolarity {
1754 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1755 match tcx.hir().expect_item_by_hir_id(hir_id).node {
1756 hir::ItemKind::Impl(_, polarity, ..) => polarity,
1757 ref item => bug!("impl_polarity: {:?} not an impl", item),
1761 // Is it marked with ?Sized
1762 fn is_unsized<'gcx: 'tcx, 'tcx>(
1763 astconv: &dyn AstConv<'gcx, 'tcx>,
1764 ast_bounds: &[hir::GenericBound],
1767 let tcx = astconv.tcx();
1769 // Try to find an unbound in bounds.
1770 let mut unbound = None;
1771 for ab in ast_bounds {
1772 if let &hir::GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = ab {
1773 if unbound.is_none() {
1774 unbound = Some(ptr.trait_ref.clone());
1780 "type parameter has more than one relaxed default \
1781 bound, only one is supported"
1787 let kind_id = tcx.lang_items().require(SizedTraitLangItem);
1790 // FIXME(#8559) currently requires the unbound to be built-in.
1791 if let Ok(kind_id) = kind_id {
1792 if tpb.path.res != Res::Def(DefKind::Trait, kind_id) {
1795 "default bound relaxed for a type parameter, but \
1796 this does nothing because the given bound is not \
1797 a default. Only `?Sized` is supported",
1802 _ if kind_id.is_ok() => {
1805 // No lang item for Sized, so we can't add it as a bound.
1812 /// Returns the early-bound lifetimes declared in this generics
1813 /// listing. For anything other than fns/methods, this is just all
1814 /// the lifetimes that are declared. For fns or methods, we have to
1815 /// screen out those that do not appear in any where-clauses etc using
1816 /// `resolve_lifetime::early_bound_lifetimes`.
1817 fn early_bound_lifetimes_from_generics<'a, 'tcx>(
1818 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1819 generics: &'a hir::Generics,
1820 ) -> impl Iterator<Item = &'a hir::GenericParam> + Captures<'tcx> {
1824 .filter(move |param| match param.kind {
1825 GenericParamKind::Lifetime { .. } => {
1826 !tcx.is_late_bound(param.hir_id)
1832 /// Returns a list of type predicates for the definition with ID `def_id`, including inferred
1833 /// lifetime constraints. This includes all predicates returned by `explicit_predicates_of`, plus
1834 /// inferred constraints concerning which regions outlive other regions.
1835 fn predicates_defined_on<'a, 'tcx>(
1836 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1838 ) -> &'tcx ty::GenericPredicates<'tcx> {
1839 debug!("predicates_defined_on({:?})", def_id);
1840 let mut result = tcx.explicit_predicates_of(def_id);
1842 "predicates_defined_on: explicit_predicates_of({:?}) = {:?}",
1846 let inferred_outlives = tcx.inferred_outlives_of(def_id);
1847 if !inferred_outlives.is_empty() {
1848 let span = tcx.def_span(def_id);
1850 "predicates_defined_on: inferred_outlives_of({:?}) = {:?}",
1854 let mut predicates = (*result).clone();
1855 predicates.predicates.extend(inferred_outlives.iter().map(|&p| (p, span)));
1856 result = tcx.arena.alloc(predicates);
1858 debug!("predicates_defined_on({:?}) = {:?}", def_id, result);
1862 /// Returns a list of all type predicates (explicit and implicit) for the definition with
1863 /// ID `def_id`. This includes all predicates returned by `predicates_defined_on`, plus
1864 /// `Self: Trait` predicates for traits.
1865 fn predicates_of<'a, 'tcx>(
1866 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1868 ) -> &'tcx ty::GenericPredicates<'tcx> {
1869 let mut result = tcx.predicates_defined_on(def_id);
1871 if tcx.is_trait(def_id) {
1872 // For traits, add `Self: Trait` predicate. This is
1873 // not part of the predicates that a user writes, but it
1874 // is something that one must prove in order to invoke a
1875 // method or project an associated type.
1877 // In the chalk setup, this predicate is not part of the
1878 // "predicates" for a trait item. But it is useful in
1879 // rustc because if you directly (e.g.) invoke a trait
1880 // method like `Trait::method(...)`, you must naturally
1881 // prove that the trait applies to the types that were
1882 // used, and adding the predicate into this list ensures
1883 // that this is done.
1884 let span = tcx.def_span(def_id);
1885 let mut predicates = (*result).clone();
1886 predicates.predicates.push((ty::TraitRef::identity(tcx, def_id).to_predicate(), span));
1887 result = tcx.arena.alloc(predicates);
1889 debug!("predicates_of(def_id={:?}) = {:?}", def_id, result);
1893 /// Returns a list of user-specified type predicates for the definition with ID `def_id`.
1894 /// N.B., this does not include any implied/inferred constraints.
1895 fn explicit_predicates_of<'a, 'tcx>(
1896 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1898 ) -> &'tcx ty::GenericPredicates<'tcx> {
1900 use rustc_data_structures::fx::FxHashSet;
1902 debug!("explicit_predicates_of(def_id={:?})", def_id);
1904 /// A data structure with unique elements, which preserves order of insertion.
1905 /// Preserving the order of insertion is important here so as not to break
1906 /// compile-fail UI tests.
1907 struct UniquePredicates<'tcx> {
1908 predicates: Vec<(ty::Predicate<'tcx>, Span)>,
1909 uniques: FxHashSet<(ty::Predicate<'tcx>, Span)>,
1912 impl<'tcx> UniquePredicates<'tcx> {
1916 uniques: FxHashSet::default(),
1920 fn push(&mut self, value: (ty::Predicate<'tcx>, Span)) {
1921 if self.uniques.insert(value) {
1922 self.predicates.push(value);
1926 fn extend<I: IntoIterator<Item = (ty::Predicate<'tcx>, Span)>>(&mut self, iter: I) {
1933 let hir_id = match tcx.hir().as_local_hir_id(def_id) {
1934 Some(hir_id) => hir_id,
1935 None => return tcx.predicates_of(def_id),
1937 let node = tcx.hir().get_by_hir_id(hir_id);
1939 let mut is_trait = None;
1940 let mut is_default_impl_trait = None;
1942 let icx = ItemCtxt::new(tcx, def_id);
1943 let no_generics = hir::Generics::empty();
1944 let empty_trait_items = HirVec::new();
1946 let mut predicates = UniquePredicates::new();
1948 let ast_generics = match node {
1949 Node::TraitItem(item) => &item.generics,
1951 Node::ImplItem(item) => match item.node {
1952 ImplItemKind::Existential(ref bounds) => {
1953 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1954 let opaque_ty = tcx.mk_opaque(def_id, substs);
1956 // Collect the bounds, i.e., the `A+B+'c` in `impl A+B+'c`.
1957 let bounds = compute_bounds(
1961 SizedByDefault::Yes,
1962 tcx.def_span(def_id),
1965 predicates.extend(bounds.predicates(tcx, opaque_ty));
1968 _ => &item.generics,
1971 Node::Item(item) => {
1973 ItemKind::Impl(_, _, defaultness, ref generics, ..) => {
1974 if defaultness.is_default() {
1975 is_default_impl_trait = tcx.impl_trait_ref(def_id);
1979 ItemKind::Fn(.., ref generics, _)
1980 | ItemKind::Ty(_, ref generics)
1981 | ItemKind::Enum(_, ref generics)
1982 | ItemKind::Struct(_, ref generics)
1983 | ItemKind::Union(_, ref generics) => generics,
1985 ItemKind::Trait(_, _, ref generics, .., ref items) => {
1986 is_trait = Some((ty::TraitRef::identity(tcx, def_id), items));
1989 ItemKind::TraitAlias(ref generics, _) => {
1990 is_trait = Some((ty::TraitRef::identity(tcx, def_id), &empty_trait_items));
1993 ItemKind::Existential(ExistTy {
1999 let substs = InternalSubsts::identity_for_item(tcx, def_id);
2000 let opaque_ty = tcx.mk_opaque(def_id, substs);
2002 // Collect the bounds, i.e., the `A+B+'c` in `impl A+B+'c`.
2003 let bounds = compute_bounds(
2007 SizedByDefault::Yes,
2008 tcx.def_span(def_id),
2011 if impl_trait_fn.is_some() {
2013 return tcx.arena.alloc(ty::GenericPredicates {
2015 predicates: bounds.predicates(tcx, opaque_ty),
2018 // named existential types
2019 predicates.extend(bounds.predicates(tcx, opaque_ty));
2028 Node::ForeignItem(item) => match item.node {
2029 ForeignItemKind::Static(..) => &no_generics,
2030 ForeignItemKind::Fn(_, _, ref generics) => generics,
2031 ForeignItemKind::Type => &no_generics,
2037 let generics = tcx.generics_of(def_id);
2038 let parent_count = generics.parent_count as u32;
2039 let has_own_self = generics.has_self && parent_count == 0;
2041 // Below we'll consider the bounds on the type parameters (including `Self`)
2042 // and the explicit where-clauses, but to get the full set of predicates
2043 // on a trait we need to add in the supertrait bounds and bounds found on
2044 // associated types.
2045 if let Some((_trait_ref, _)) = is_trait {
2046 predicates.extend(tcx.super_predicates_of(def_id).predicates.iter().cloned());
2049 // In default impls, we can assume that the self type implements
2050 // the trait. So in:
2052 // default impl Foo for Bar { .. }
2054 // we add a default where clause `Foo: Bar`. We do a similar thing for traits
2055 // (see below). Recall that a default impl is not itself an impl, but rather a
2056 // set of defaults that can be incorporated into another impl.
2057 if let Some(trait_ref) = is_default_impl_trait {
2058 predicates.push((trait_ref.to_poly_trait_ref().to_predicate(), tcx.def_span(def_id)));
2061 // Collect the region predicates that were declared inline as
2062 // well. In the case of parameters declared on a fn or method, we
2063 // have to be careful to only iterate over early-bound regions.
2064 let mut index = parent_count + has_own_self as u32;
2065 for param in early_bound_lifetimes_from_generics(tcx, ast_generics) {
2066 let region = tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
2067 def_id: tcx.hir().local_def_id_from_hir_id(param.hir_id),
2069 name: param.name.ident().as_interned_str(),
2074 GenericParamKind::Lifetime { .. } => {
2075 param.bounds.iter().for_each(|bound| match bound {
2076 hir::GenericBound::Outlives(lt) => {
2077 let bound = AstConv::ast_region_to_region(&icx, <, None);
2078 let outlives = ty::Binder::bind(ty::OutlivesPredicate(region, bound));
2079 predicates.push((outlives.to_predicate(), lt.span));
2088 // Collect the predicates that were written inline by the user on each
2089 // type parameter (e.g., `<T:Foo>`).
2090 for param in &ast_generics.params {
2091 if let GenericParamKind::Type { .. } = param.kind {
2092 let name = param.name.ident().as_interned_str();
2093 let param_ty = ty::ParamTy::new(index, name).to_ty(tcx);
2096 let sized = SizedByDefault::Yes;
2097 let bounds = compute_bounds(&icx, param_ty, ¶m.bounds, sized, param.span);
2098 predicates.extend(bounds.predicates(tcx, param_ty));
2102 // Add in the bounds that appear in the where-clause
2103 let where_clause = &ast_generics.where_clause;
2104 for predicate in &where_clause.predicates {
2106 &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
2107 let ty = icx.to_ty(&bound_pred.bounded_ty);
2109 // Keep the type around in a dummy predicate, in case of no bounds.
2110 // That way, `where Ty:` is not a complete noop (see #53696) and `Ty`
2111 // is still checked for WF.
2112 if bound_pred.bounds.is_empty() {
2113 if let ty::Param(_) = ty.sty {
2114 // This is a `where T:`, which can be in the HIR from the
2115 // transformation that moves `?Sized` to `T`'s declaration.
2116 // We can skip the predicate because type parameters are
2117 // trivially WF, but also we *should*, to avoid exposing
2118 // users who never wrote `where Type:,` themselves, to
2119 // compiler/tooling bugs from not handling WF predicates.
2121 let span = bound_pred.bounded_ty.span;
2122 let predicate = ty::OutlivesPredicate(ty, tcx.mk_region(ty::ReEmpty));
2124 (ty::Predicate::TypeOutlives(ty::Binder::dummy(predicate)), span)
2129 for bound in bound_pred.bounds.iter() {
2131 &hir::GenericBound::Trait(ref poly_trait_ref, _) => {
2132 let mut projections = Vec::new();
2134 let (trait_ref, _) = AstConv::instantiate_poly_trait_ref(
2142 iter::once((trait_ref.to_predicate(), poly_trait_ref.span)).chain(
2143 projections.iter().map(|&(p, span)| (p.to_predicate(), span)
2147 &hir::GenericBound::Outlives(ref lifetime) => {
2148 let region = AstConv::ast_region_to_region(&icx, lifetime, None);
2149 let pred = ty::Binder::bind(ty::OutlivesPredicate(ty, region));
2150 predicates.push((ty::Predicate::TypeOutlives(pred), lifetime.span))
2156 &hir::WherePredicate::RegionPredicate(ref region_pred) => {
2157 let r1 = AstConv::ast_region_to_region(&icx, ®ion_pred.lifetime, None);
2158 predicates.extend(region_pred.bounds.iter().map(|bound| {
2159 let (r2, span) = match bound {
2160 hir::GenericBound::Outlives(lt) => {
2161 (AstConv::ast_region_to_region(&icx, lt, None), lt.span)
2165 let pred = ty::Binder::bind(ty::OutlivesPredicate(r1, r2));
2167 (ty::Predicate::RegionOutlives(pred), span)
2171 &hir::WherePredicate::EqPredicate(..) => {
2177 // Add predicates from associated type bounds.
2178 if let Some((self_trait_ref, trait_items)) = is_trait {
2179 predicates.extend(trait_items.iter().flat_map(|trait_item_ref| {
2180 let trait_item = tcx.hir().trait_item(trait_item_ref.id);
2181 let bounds = match trait_item.node {
2182 hir::TraitItemKind::Type(ref bounds, _) => bounds,
2183 _ => return vec![].into_iter()
2187 tcx.mk_projection(tcx.hir().local_def_id_from_hir_id(trait_item.hir_id),
2188 self_trait_ref.substs);
2190 let bounds = compute_bounds(
2191 &ItemCtxt::new(tcx, def_id),
2194 SizedByDefault::Yes,
2198 bounds.predicates(tcx, assoc_ty).into_iter()
2202 let mut predicates = predicates.predicates;
2204 // Subtle: before we store the predicates into the tcx, we
2205 // sort them so that predicates like `T: Foo<Item=U>` come
2206 // before uses of `U`. This avoids false ambiguity errors
2207 // in trait checking. See `setup_constraining_predicates`
2209 if let Node::Item(&Item {
2210 node: ItemKind::Impl(..),
2214 let self_ty = tcx.type_of(def_id);
2215 let trait_ref = tcx.impl_trait_ref(def_id);
2216 cgp::setup_constraining_predicates(
2220 &mut cgp::parameters_for_impl(self_ty, trait_ref),
2224 let result = tcx.arena.alloc(ty::GenericPredicates {
2225 parent: generics.parent,
2228 debug!("explicit_predicates_of(def_id={:?}) = {:?}", def_id, result);
2232 pub enum SizedByDefault {
2237 /// Translate the AST's notion of ty param bounds (which are an enum consisting of a newtyped `Ty`
2238 /// or a region) to ty's notion of ty param bounds, which can either be user-defined traits, or the
2239 /// built-in trait `Send`.
2240 pub fn compute_bounds<'gcx: 'tcx, 'tcx>(
2241 astconv: &dyn AstConv<'gcx, 'tcx>,
2243 ast_bounds: &[hir::GenericBound],
2244 sized_by_default: SizedByDefault,
2247 let mut region_bounds = Vec::new();
2248 let mut trait_bounds = Vec::new();
2250 for ast_bound in ast_bounds {
2252 hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::None) => trait_bounds.push(b),
2253 hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => {}
2254 hir::GenericBound::Outlives(ref l) => region_bounds.push(l),
2258 let mut projection_bounds = Vec::new();
2260 let mut trait_bounds: Vec<_> = trait_bounds.iter().map(|&bound| {
2261 let (poly_trait_ref, _) = astconv.instantiate_poly_trait_ref(
2264 &mut projection_bounds,
2266 (poly_trait_ref, bound.span)
2269 let region_bounds = region_bounds
2271 .map(|r| (astconv.ast_region_to_region(r, None), r.span))
2274 trait_bounds.sort_by_key(|(t, _)| t.def_id());
2276 let implicitly_sized = if let SizedByDefault::Yes = sized_by_default {
2277 if !is_unsized(astconv, ast_bounds, span) {
2294 /// Converts a specific `GenericBound` from the AST into a set of
2295 /// predicates that apply to the self type. A vector is returned
2296 /// because this can be anywhere from zero predicates (`T: ?Sized` adds no
2297 /// predicates) to one (`T: Foo`) to many (`T: Bar<X=i32>` adds `T: Bar`
2298 /// and `<T as Bar>::X == i32`).
2299 fn predicates_from_bound<'tcx>(
2300 astconv: &dyn AstConv<'tcx, 'tcx>,
2302 bound: &hir::GenericBound,
2303 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2305 hir::GenericBound::Trait(ref tr, hir::TraitBoundModifier::None) => {
2306 let mut projections = Vec::new();
2307 let (pred, _) = astconv.instantiate_poly_trait_ref(tr, param_ty, &mut projections);
2308 iter::once((pred.to_predicate(), tr.span)).chain(
2311 .map(|(p, span)| (p.to_predicate(), span))
2314 hir::GenericBound::Outlives(ref lifetime) => {
2315 let region = astconv.ast_region_to_region(lifetime, None);
2316 let pred = ty::Binder::bind(ty::OutlivesPredicate(param_ty, region));
2317 vec![(ty::Predicate::TypeOutlives(pred), lifetime.span)]
2319 hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => vec![],
2323 fn compute_sig_of_foreign_fn_decl<'a, 'tcx>(
2324 tcx: TyCtxt<'a, 'tcx, 'tcx>,
2328 ) -> ty::PolyFnSig<'tcx> {
2329 let unsafety = if abi == abi::Abi::RustIntrinsic {
2330 intrisic_operation_unsafety(&*tcx.item_name(def_id).as_str())
2332 hir::Unsafety::Unsafe
2334 let fty = AstConv::ty_of_fn(&ItemCtxt::new(tcx, def_id), unsafety, abi, decl);
2336 // feature gate SIMD types in FFI, since I (huonw) am not sure the
2337 // ABIs are handled at all correctly.
2338 if abi != abi::Abi::RustIntrinsic
2339 && abi != abi::Abi::PlatformIntrinsic
2340 && !tcx.features().simd_ffi
2342 let check = |ast_ty: &hir::Ty, ty: Ty<'_>| {
2348 "use of SIMD type `{}` in FFI is highly experimental and \
2349 may result in invalid code",
2350 tcx.hir().hir_to_pretty_string(ast_ty.hir_id)
2353 .help("add #![feature(simd_ffi)] to the crate attributes to enable")
2357 for (input, ty) in decl.inputs.iter().zip(*fty.inputs().skip_binder()) {
2360 if let hir::Return(ref ty) = decl.output {
2361 check(&ty, *fty.output().skip_binder())
2368 fn is_foreign_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> bool {
2369 match tcx.hir().get_if_local(def_id) {
2370 Some(Node::ForeignItem(..)) => true,
2372 _ => bug!("is_foreign_item applied to non-local def-id {:?}", def_id),
2376 fn static_mutability<'a, 'tcx>(
2377 tcx: TyCtxt<'a, 'tcx, 'tcx>,
2379 ) -> Option<hir::Mutability> {
2380 match tcx.hir().get_if_local(def_id) {
2381 Some(Node::Item(&hir::Item {
2382 node: hir::ItemKind::Static(_, mutbl, _), ..
2384 Some(Node::ForeignItem( &hir::ForeignItem {
2385 node: hir::ForeignItemKind::Static(_, mutbl), ..
2388 _ => bug!("static_mutability applied to non-local def-id {:?}", def_id),
2392 fn from_target_feature(
2393 tcx: TyCtxt<'_, '_, '_>,
2395 attr: &ast::Attribute,
2396 whitelist: &FxHashMap<String, Option<Symbol>>,
2397 target_features: &mut Vec<Symbol>,
2399 let list = match attr.meta_item_list() {
2403 let rust_features = tcx.features();
2405 // Only `enable = ...` is accepted in the meta item list
2406 if !item.check_name(sym::enable) {
2407 let msg = "#[target_feature(..)] only accepts sub-keys of `enable` \
2409 tcx.sess.span_err(item.span(), &msg);
2413 // Must be of the form `enable = "..."` ( a string)
2414 let value = match item.value_str() {
2415 Some(value) => value,
2417 let msg = "#[target_feature] attribute must be of the form \
2418 #[target_feature(enable = \"..\")]";
2419 tcx.sess.span_err(item.span(), &msg);
2424 // We allow comma separation to enable multiple features
2425 target_features.extend(value.as_str().split(',').filter_map(|feature| {
2426 // Only allow whitelisted features per platform
2427 let feature_gate = match whitelist.get(feature) {
2431 "the feature named `{}` is not valid for \
2435 let mut err = tcx.sess.struct_span_err(item.span(), &msg);
2437 if feature.starts_with("+") {
2438 let valid = whitelist.contains_key(&feature[1..]);
2440 err.help("consider removing the leading `+` in the feature name");
2448 // Only allow features whose feature gates have been enabled
2449 let allowed = match feature_gate.as_ref().map(|s| *s) {
2450 Some(sym::arm_target_feature) => rust_features.arm_target_feature,
2451 Some(sym::aarch64_target_feature) => rust_features.aarch64_target_feature,
2452 Some(sym::hexagon_target_feature) => rust_features.hexagon_target_feature,
2453 Some(sym::powerpc_target_feature) => rust_features.powerpc_target_feature,
2454 Some(sym::mips_target_feature) => rust_features.mips_target_feature,
2455 Some(sym::avx512_target_feature) => rust_features.avx512_target_feature,
2456 Some(sym::mmx_target_feature) => rust_features.mmx_target_feature,
2457 Some(sym::sse4a_target_feature) => rust_features.sse4a_target_feature,
2458 Some(sym::tbm_target_feature) => rust_features.tbm_target_feature,
2459 Some(sym::wasm_target_feature) => rust_features.wasm_target_feature,
2460 Some(sym::cmpxchg16b_target_feature) => rust_features.cmpxchg16b_target_feature,
2461 Some(sym::adx_target_feature) => rust_features.adx_target_feature,
2462 Some(sym::movbe_target_feature) => rust_features.movbe_target_feature,
2463 Some(sym::rtm_target_feature) => rust_features.rtm_target_feature,
2464 Some(sym::f16c_target_feature) => rust_features.f16c_target_feature,
2465 Some(name) => bug!("unknown target feature gate {}", name),
2468 if !allowed && id.is_local() {
2469 feature_gate::emit_feature_err(
2470 &tcx.sess.parse_sess,
2471 feature_gate.unwrap(),
2473 feature_gate::GateIssue::Language,
2474 &format!("the target feature `{}` is currently unstable", feature),
2477 Some(Symbol::intern(feature))
2482 fn linkage_by_name<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId, name: &str) -> Linkage {
2483 use rustc::mir::mono::Linkage::*;
2485 // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
2486 // applicable to variable declarations and may not really make sense for
2487 // Rust code in the first place but whitelist them anyway and trust that
2488 // the user knows what s/he's doing. Who knows, unanticipated use cases
2489 // may pop up in the future.
2491 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
2492 // and don't have to be, LLVM treats them as no-ops.
2494 "appending" => Appending,
2495 "available_externally" => AvailableExternally,
2497 "extern_weak" => ExternalWeak,
2498 "external" => External,
2499 "internal" => Internal,
2500 "linkonce" => LinkOnceAny,
2501 "linkonce_odr" => LinkOnceODR,
2502 "private" => Private,
2504 "weak_odr" => WeakODR,
2506 let span = tcx.hir().span_if_local(def_id);
2507 if let Some(span) = span {
2508 tcx.sess.span_fatal(span, "invalid linkage specified")
2511 .fatal(&format!("invalid linkage specified: {}", name))
2517 fn codegen_fn_attrs<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, id: DefId) -> CodegenFnAttrs {
2518 let attrs = tcx.get_attrs(id);
2520 let mut codegen_fn_attrs = CodegenFnAttrs::new();
2522 let whitelist = tcx.target_features_whitelist(LOCAL_CRATE);
2524 let mut inline_span = None;
2525 for attr in attrs.iter() {
2526 if attr.check_name(sym::cold) {
2527 codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD;
2528 } else if attr.check_name(sym::allocator) {
2529 codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR;
2530 } else if attr.check_name(sym::unwind) {
2531 codegen_fn_attrs.flags |= CodegenFnAttrFlags::UNWIND;
2532 } else if attr.check_name(sym::ffi_returns_twice) {
2533 if tcx.is_foreign_item(id) {
2534 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_RETURNS_TWICE;
2536 // `#[ffi_returns_twice]` is only allowed `extern fn`s
2541 "`#[ffi_returns_twice]` may only be used on foreign functions"
2544 } else if attr.check_name(sym::rustc_allocator_nounwind) {
2545 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND;
2546 } else if attr.check_name(sym::naked) {
2547 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED;
2548 } else if attr.check_name(sym::no_mangle) {
2549 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2550 } else if attr.check_name(sym::rustc_std_internal_symbol) {
2551 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2552 } else if attr.check_name(sym::no_debug) {
2553 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_DEBUG;
2554 } else if attr.check_name(sym::used) {
2555 codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED;
2556 } else if attr.check_name(sym::thread_local) {
2557 codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL;
2558 } else if attr.check_name(sym::export_name) {
2559 if let Some(s) = attr.value_str() {
2560 if s.as_str().contains("\0") {
2561 // `#[export_name = ...]` will be converted to a null-terminated string,
2562 // so it may not contain any null characters.
2567 "`export_name` may not contain null characters"
2570 codegen_fn_attrs.export_name = Some(s);
2572 } else if attr.check_name(sym::target_feature) {
2573 if tcx.fn_sig(id).unsafety() == Unsafety::Normal {
2574 let msg = "#[target_feature(..)] can only be applied to \
2576 tcx.sess.span_err(attr.span, msg);
2578 from_target_feature(
2583 &mut codegen_fn_attrs.target_features,
2585 } else if attr.check_name(sym::linkage) {
2586 if let Some(val) = attr.value_str() {
2587 codegen_fn_attrs.linkage = Some(linkage_by_name(tcx, id, &val.as_str()));
2589 } else if attr.check_name(sym::link_section) {
2590 if let Some(val) = attr.value_str() {
2591 if val.as_str().bytes().any(|b| b == 0) {
2593 "illegal null byte in link_section \
2597 tcx.sess.span_err(attr.span, &msg);
2599 codegen_fn_attrs.link_section = Some(val);
2602 } else if attr.check_name(sym::link_name) {
2603 codegen_fn_attrs.link_name = attr.value_str();
2607 codegen_fn_attrs.inline = attrs.iter().fold(InlineAttr::None, |ia, attr| {
2608 if attr.path != sym::inline {
2611 match attr.meta().map(|i| i.node) {
2612 Some(MetaItemKind::Word) => {
2616 Some(MetaItemKind::List(ref items)) => {
2618 inline_span = Some(attr.span);
2619 if items.len() != 1 {
2621 tcx.sess.diagnostic(),
2624 "expected one argument"
2627 } else if list_contains_name(&items[..], sym::always) {
2629 } else if list_contains_name(&items[..], sym::never) {
2633 tcx.sess.diagnostic(),
2642 Some(MetaItemKind::NameValue(_)) => ia,
2647 codegen_fn_attrs.optimize = attrs.iter().fold(OptimizeAttr::None, |ia, attr| {
2648 if attr.path != sym::optimize {
2651 let err = |sp, s| span_err!(tcx.sess.diagnostic(), sp, E0722, "{}", s);
2652 match attr.meta().map(|i| i.node) {
2653 Some(MetaItemKind::Word) => {
2654 err(attr.span, "expected one argument");
2657 Some(MetaItemKind::List(ref items)) => {
2659 inline_span = Some(attr.span);
2660 if items.len() != 1 {
2661 err(attr.span, "expected one argument");
2663 } else if list_contains_name(&items[..], sym::size) {
2665 } else if list_contains_name(&items[..], sym::speed) {
2668 err(items[0].span(), "invalid argument");
2672 Some(MetaItemKind::NameValue(_)) => ia,
2677 // If a function uses #[target_feature] it can't be inlined into general
2678 // purpose functions as they wouldn't have the right target features
2679 // enabled. For that reason we also forbid #[inline(always)] as it can't be
2681 if codegen_fn_attrs.target_features.len() > 0 {
2682 if codegen_fn_attrs.inline == InlineAttr::Always {
2683 if let Some(span) = inline_span {
2686 "cannot use #[inline(always)] with \
2693 // Weak lang items have the same semantics as "std internal" symbols in the
2694 // sense that they're preserved through all our LTO passes and only
2695 // strippable by the linker.
2697 // Additionally weak lang items have predetermined symbol names.
2698 if tcx.is_weak_lang_item(id) {
2699 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2701 if let Some(name) = weak_lang_items::link_name(&attrs) {
2702 codegen_fn_attrs.export_name = Some(name);
2703 codegen_fn_attrs.link_name = Some(name);
2706 // Internal symbols to the standard library all have no_mangle semantics in
2707 // that they have defined symbol names present in the function name. This
2708 // also applies to weak symbols where they all have known symbol names.
2709 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
2710 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;