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 astconv::{AstConv, Bounds};
18 use constrained_type_params as ctp;
19 use check::intrinsic::intrisic_operation_unsafety;
21 use middle::lang_items::SizedTraitLangItem;
22 use middle::resolve_lifetime as rl;
23 use middle::weak_lang_items;
24 use rustc::mir::mono::Linkage;
25 use rustc::ty::query::Providers;
26 use rustc::ty::subst::Substs;
27 use rustc::ty::util::Discr;
28 use rustc::ty::util::IntTypeExt;
29 use rustc::ty::{self, AdtKind, ToPolyTraitRef, Ty, TyCtxt};
30 use rustc::ty::{ReprOptions, ToPredicate};
31 use rustc::util::captures::Captures;
32 use rustc::util::nodemap::FxHashMap;
33 use rustc_data_structures::sync::Lrc;
34 use rustc_target::spec::abi;
37 use syntax::ast::{Ident, MetaItemKind};
38 use syntax::attr::{InlineAttr, list_contains_name, mark_used};
39 use syntax::source_map::Spanned;
40 use syntax::feature_gate;
41 use syntax::symbol::{keywords, Symbol};
42 use syntax_pos::{Span, DUMMY_SP};
44 use rustc::hir::def::{CtorKind, Def};
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 pub fn collect_item_types<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
59 let mut visitor = CollectItemTypesVisitor { tcx };
62 .visit_all_item_likes(&mut visitor.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,
85 ///////////////////////////////////////////////////////////////////////////
87 /// Context specific to some particular item. This is what implements
88 /// AstConv. It has information about the predicates that are defined
89 /// on the trait. Unfortunately, this predicate information is
90 /// available in various different forms at various points in the
91 /// process. So we can't just store a pointer to e.g., the AST or the
92 /// parsed ty form, we have to be more flexible. To this end, the
93 /// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy
94 /// `get_type_parameter_bounds` requests, drawing the information from
95 /// the AST (`hir::Generics`), recursively.
96 pub struct ItemCtxt<'a, 'tcx: 'a> {
97 tcx: TyCtxt<'a, 'tcx, 'tcx>,
101 ///////////////////////////////////////////////////////////////////////////
103 struct CollectItemTypesVisitor<'a, 'tcx: 'a> {
104 tcx: TyCtxt<'a, 'tcx, 'tcx>,
107 impl<'a, 'tcx> Visitor<'tcx> for CollectItemTypesVisitor<'a, 'tcx> {
108 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
109 NestedVisitorMap::OnlyBodies(&self.tcx.hir())
112 fn visit_item(&mut self, item: &'tcx hir::Item) {
113 convert_item(self.tcx, item.id);
114 intravisit::walk_item(self, item);
117 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
118 for param in &generics.params {
120 hir::GenericParamKind::Lifetime { .. } => {}
121 hir::GenericParamKind::Type {
124 let def_id = self.tcx.hir().local_def_id(param.id);
125 self.tcx.type_of(def_id);
127 hir::GenericParamKind::Type { .. } => {}
130 intravisit::walk_generics(self, generics);
133 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
134 if let hir::ExprKind::Closure(..) = expr.node {
135 let def_id = self.tcx.hir().local_def_id(expr.id);
136 self.tcx.generics_of(def_id);
137 self.tcx.type_of(def_id);
139 intravisit::walk_expr(self, expr);
142 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
143 convert_trait_item(self.tcx, trait_item.id);
144 intravisit::walk_trait_item(self, trait_item);
147 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
148 convert_impl_item(self.tcx, impl_item.id);
149 intravisit::walk_impl_item(self, impl_item);
153 ///////////////////////////////////////////////////////////////////////////
154 // Utility types and common code for the above passes.
156 impl<'a, 'tcx> ItemCtxt<'a, 'tcx> {
157 pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, item_def_id: DefId) -> ItemCtxt<'a, 'tcx> {
158 ItemCtxt { tcx, item_def_id }
162 impl<'a, 'tcx> ItemCtxt<'a, 'tcx> {
163 pub fn to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> {
164 AstConv::ast_ty_to_ty(self, ast_ty)
168 impl<'a, 'tcx> AstConv<'tcx, 'tcx> for ItemCtxt<'a, 'tcx> {
169 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'tcx, 'tcx> {
173 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId)
174 -> Lrc<ty::GenericPredicates<'tcx>> {
177 .type_param_predicates((self.item_def_id, def_id))
183 _def: Option<&ty::GenericParamDef>,
184 ) -> Option<ty::Region<'tcx>> {
188 fn ty_infer(&self, span: Span) -> Ty<'tcx> {
193 "the type placeholder `_` is not allowed within types on item signatures"
194 ).span_label(span, "not allowed in type signatures")
200 fn projected_ty_from_poly_trait_ref(
204 poly_trait_ref: ty::PolyTraitRef<'tcx>,
206 if let Some(trait_ref) = poly_trait_ref.no_bound_vars() {
207 self.tcx().mk_projection(item_def_id, trait_ref.substs)
209 // no late-bound regions, we can just ignore the binder
214 "cannot extract an associated type from a higher-ranked trait bound \
221 fn normalize_ty(&self, _span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
222 // types in item signatures are not normalized, to avoid undue
227 fn set_tainted_by_errors(&self) {
228 // no obvious place to track this, just let it go
231 fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) {
232 // no place to record types from signatures?
236 fn type_param_predicates<'a, 'tcx>(
237 tcx: TyCtxt<'a, 'tcx, 'tcx>,
238 (item_def_id, def_id): (DefId, DefId),
239 ) -> Lrc<ty::GenericPredicates<'tcx>> {
242 // In the AST, bounds can derive from two places. Either
243 // written inline like `<T : Foo>` or in a where clause like
246 let param_id = tcx.hir().as_local_node_id(def_id).unwrap();
247 let param_owner = tcx.hir().ty_param_owner(param_id);
248 let param_owner_def_id = tcx.hir().local_def_id(param_owner);
249 let generics = tcx.generics_of(param_owner_def_id);
250 let index = generics.param_def_id_to_index[&def_id];
251 let ty = tcx.mk_ty_param(index, tcx.hir().ty_param_name(param_id).as_interned_str());
253 // Don't look for bounds where the type parameter isn't in scope.
254 let parent = if item_def_id == param_owner_def_id {
257 tcx.generics_of(item_def_id).parent
260 let mut result = parent.map_or_else(
261 || Lrc::new(ty::GenericPredicates {
266 let icx = ItemCtxt::new(tcx, parent);
267 icx.get_type_parameter_bounds(DUMMY_SP, def_id)
271 let item_node_id = tcx.hir().as_local_node_id(item_def_id).unwrap();
272 let ast_generics = match tcx.hir().get(item_node_id) {
273 Node::TraitItem(item) => &item.generics,
275 Node::ImplItem(item) => &item.generics,
277 Node::Item(item) => {
279 ItemKind::Fn(.., ref generics, _)
280 | ItemKind::Impl(_, _, _, ref generics, ..)
281 | ItemKind::Ty(_, ref generics)
282 | ItemKind::Existential(ExistTy {
287 | ItemKind::Enum(_, ref generics)
288 | ItemKind::Struct(_, ref generics)
289 | ItemKind::Union(_, ref generics) => generics,
290 ItemKind::Trait(_, _, ref generics, ..) => {
291 // Implied `Self: Trait` and supertrait bounds.
292 if param_id == item_node_id {
293 let identity_trait_ref = ty::TraitRef::identity(tcx, item_def_id);
294 Lrc::make_mut(&mut result)
296 .push((identity_trait_ref.to_predicate(), item.span));
304 Node::ForeignItem(item) => match item.node {
305 ForeignItemKind::Fn(_, _, ref generics) => generics,
312 let icx = ItemCtxt::new(tcx, item_def_id);
313 Lrc::make_mut(&mut result)
315 .extend(icx.type_parameter_bounds_in_generics(ast_generics, param_id, ty,
316 OnlySelfBounds(true)));
320 impl<'a, 'tcx> ItemCtxt<'a, 'tcx> {
321 /// Find 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: ast::NodeId,
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.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: ast::NodeId,
375 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = ast_ty.node {
377 Def::SelfTy(Some(def_id), None) | Def::TyParam(def_id) => {
378 def_id == tcx.hir().local_def_id(param_id)
387 fn convert_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item_id: ast::NodeId) {
388 let it = tcx.hir().expect_item(item_id);
389 debug!("convert: item {} with id {}", it.ident, it.id);
390 let def_id = tcx.hir().local_def_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(item.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(f.id);
438 tcx.generics_of(def_id);
440 tcx.predicates_of(def_id);
443 if !struct_def.is_struct() {
444 convert_variant_ctor(tcx, struct_def.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: ast::NodeId) {
470 let trait_item = tcx.hir().expect_trait_item(trait_item_id);
471 let def_id = tcx.hir().local_def_id(trait_item.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: ast::NodeId) {
491 let def_id = tcx.hir().local_def_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: ast::NodeId) {
501 let def_id = tcx.hir().local_def_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(e.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(f.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 convert_variant_ctor(tcx, variant.node.data.id());
557 fn convert_variant<'a, 'tcx>(
558 tcx: TyCtxt<'a, 'tcx, 'tcx>,
561 discr: ty::VariantDiscr,
562 def: &hir::VariantData,
563 adt_kind: ty::AdtKind,
564 attribute_def_id: DefId
565 ) -> ty::VariantDef {
566 let mut seen_fields: FxHashMap<ast::Ident, Span> = Default::default();
567 let node_id = tcx.hir().as_local_node_id(did).unwrap();
572 let fid = tcx.hir().local_def_id(f.id);
573 let dup_span = seen_fields.get(&f.ident.modern()).cloned();
574 if let Some(prev_span) = dup_span {
579 "field `{}` is already declared",
581 ).span_label(f.span, "field already declared")
582 .span_label(prev_span, format!("`{}` first declared here", f.ident))
585 seen_fields.insert(f.ident.modern(), f.span);
591 vis: ty::Visibility::from_hir(&f.vis, node_id, tcx),
595 ty::VariantDef::new(tcx,
601 CtorKind::from_hir(def),
606 fn adt_def<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx ty::AdtDef {
609 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
610 let item = match tcx.hir().get(node_id) {
611 Node::Item(item) => item,
615 let repr = ReprOptions::new(tcx, def_id);
616 let (kind, variants) = match item.node {
617 ItemKind::Enum(ref def, _) => {
618 let mut distance_from_explicit = 0;
624 let did = tcx.hir().local_def_id(v.node.data.id());
625 let discr = if let Some(ref e) = v.node.disr_expr {
626 distance_from_explicit = 0;
627 ty::VariantDiscr::Explicit(tcx.hir().local_def_id(e.id))
629 ty::VariantDiscr::Relative(distance_from_explicit)
631 distance_from_explicit += 1;
633 convert_variant(tcx, did, v.node.ident, discr, &v.node.data, AdtKind::Enum,
639 ItemKind::Struct(ref def, _) => {
640 // Use separate constructor id for unit/tuple structs and reuse did for braced structs.
641 let ctor_id = if !def.is_struct() {
642 Some(tcx.hir().local_def_id(def.id()))
648 std::iter::once(convert_variant(
650 ctor_id.unwrap_or(def_id),
652 ty::VariantDiscr::Relative(0),
659 ItemKind::Union(ref def, _) => (
661 std::iter::once(convert_variant(
665 ty::VariantDiscr::Relative(0),
673 tcx.alloc_adt_def(def_id, kind, variants, repr)
676 /// Ensures that the super-predicates of the trait with def-id
677 /// trait_def_id are converted and stored. This also ensures that
678 /// the transitive super-predicates are converted;
679 fn super_predicates_of<'a, 'tcx>(
680 tcx: TyCtxt<'a, 'tcx, 'tcx>,
682 ) -> Lrc<ty::GenericPredicates<'tcx>> {
683 debug!("super_predicates(trait_def_id={:?})", trait_def_id);
684 let trait_node_id = tcx.hir().as_local_node_id(trait_def_id).unwrap();
686 let item = match tcx.hir().get(trait_node_id) {
687 Node::Item(item) => item,
688 _ => bug!("trait_node_id {} is not an item", trait_node_id),
691 let (generics, bounds) = match item.node {
692 hir::ItemKind::Trait(.., ref generics, ref supertraits, _) => (generics, supertraits),
693 hir::ItemKind::TraitAlias(ref generics, ref supertraits) => (generics, supertraits),
694 _ => span_bug!(item.span, "super_predicates invoked on non-trait"),
697 let icx = ItemCtxt::new(tcx, trait_def_id);
699 // Convert the bounds that follow the colon, e.g., `Bar + Zed` in `trait Foo : Bar + Zed`.
700 let self_param_ty = tcx.mk_self_type();
701 let superbounds1 = compute_bounds(&icx, self_param_ty, bounds, SizedByDefault::No, item.span);
703 let superbounds1 = superbounds1.predicates(tcx, self_param_ty);
705 // Convert any explicit superbounds in the where clause,
706 // e.g., `trait Foo where Self : Bar`.
707 // In the case of trait aliases, however, we include all bounds in the where clause,
708 // so e.g., `trait Foo = where u32: PartialEq<Self>` would include `u32: PartialEq<Self>`
709 // as one of its "superpredicates".
710 let is_trait_alias = ty::is_trait_alias(tcx, trait_def_id);
711 let superbounds2 = icx.type_parameter_bounds_in_generics(
712 generics, item.id, self_param_ty, OnlySelfBounds(!is_trait_alias));
714 // Combine the two lists to form the complete set of superbounds:
715 let superbounds: Vec<_> = superbounds1.into_iter().chain(superbounds2).collect();
717 // Now require that immediate supertraits are converted,
718 // which will, in turn, reach indirect supertraits.
719 for &(pred, span) in &superbounds {
720 debug!("superbound: {:?}", pred);
721 if let ty::Predicate::Trait(bound) = pred {
722 tcx.at(span).super_predicates_of(bound.def_id());
726 Lrc::new(ty::GenericPredicates {
728 predicates: superbounds,
732 fn trait_def<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx ty::TraitDef {
733 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
734 let item = tcx.hir().expect_item(node_id);
736 let (is_auto, unsafety) = match item.node {
737 hir::ItemKind::Trait(is_auto, unsafety, ..) => (is_auto == hir::IsAuto::Yes, unsafety),
738 hir::ItemKind::TraitAlias(..) => (false, hir::Unsafety::Normal),
739 _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
742 let paren_sugar = tcx.has_attr(def_id, "rustc_paren_sugar");
743 if paren_sugar && !tcx.features().unboxed_closures {
744 let mut err = tcx.sess.struct_span_err(
746 "the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \
747 which traits can use parenthetical notation",
751 "add `#![feature(unboxed_closures)]` to \
752 the crate attributes to use it"
757 let is_marker = tcx.has_attr(def_id, "marker");
758 let def_path_hash = tcx.def_path_hash(def_id);
759 let def = ty::TraitDef::new(def_id, unsafety, paren_sugar, is_auto, is_marker, def_path_hash);
760 tcx.alloc_trait_def(def)
763 fn has_late_bound_regions<'a, 'tcx>(
764 tcx: TyCtxt<'a, 'tcx, 'tcx>,
767 struct LateBoundRegionsDetector<'a, 'tcx: 'a> {
768 tcx: TyCtxt<'a, 'tcx, 'tcx>,
769 outer_index: ty::DebruijnIndex,
770 has_late_bound_regions: Option<Span>,
773 impl<'a, 'tcx> Visitor<'tcx> for LateBoundRegionsDetector<'a, 'tcx> {
774 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
775 NestedVisitorMap::None
778 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
779 if self.has_late_bound_regions.is_some() {
783 hir::TyKind::BareFn(..) => {
784 self.outer_index.shift_in(1);
785 intravisit::walk_ty(self, ty);
786 self.outer_index.shift_out(1);
788 _ => intravisit::walk_ty(self, ty),
792 fn visit_poly_trait_ref(
794 tr: &'tcx hir::PolyTraitRef,
795 m: hir::TraitBoundModifier,
797 if self.has_late_bound_regions.is_some() {
800 self.outer_index.shift_in(1);
801 intravisit::walk_poly_trait_ref(self, tr, m);
802 self.outer_index.shift_out(1);
805 fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
806 if self.has_late_bound_regions.is_some() {
810 let hir_id = self.tcx.hir().node_to_hir_id(lt.id);
811 match self.tcx.named_region(hir_id) {
812 Some(rl::Region::Static) | Some(rl::Region::EarlyBound(..)) => {}
813 Some(rl::Region::LateBound(debruijn, _, _))
814 | Some(rl::Region::LateBoundAnon(debruijn, _)) if debruijn < self.outer_index => {}
815 Some(rl::Region::LateBound(..))
816 | Some(rl::Region::LateBoundAnon(..))
817 | Some(rl::Region::Free(..))
819 self.has_late_bound_regions = Some(lt.span);
825 fn has_late_bound_regions<'a, 'tcx>(
826 tcx: TyCtxt<'a, 'tcx, 'tcx>,
827 generics: &'tcx hir::Generics,
828 decl: &'tcx hir::FnDecl,
830 let mut visitor = LateBoundRegionsDetector {
832 outer_index: ty::INNERMOST,
833 has_late_bound_regions: None,
835 for param in &generics.params {
836 if let GenericParamKind::Lifetime { .. } = param.kind {
837 let hir_id = tcx.hir().node_to_hir_id(param.id);
838 if tcx.is_late_bound(hir_id) {
839 return Some(param.span);
843 visitor.visit_fn_decl(decl);
844 visitor.has_late_bound_regions
848 Node::TraitItem(item) => match item.node {
849 hir::TraitItemKind::Method(ref sig, _) => {
850 has_late_bound_regions(tcx, &item.generics, &sig.decl)
854 Node::ImplItem(item) => match item.node {
855 hir::ImplItemKind::Method(ref sig, _) => {
856 has_late_bound_regions(tcx, &item.generics, &sig.decl)
860 Node::ForeignItem(item) => match item.node {
861 hir::ForeignItemKind::Fn(ref fn_decl, _, ref generics) => {
862 has_late_bound_regions(tcx, generics, fn_decl)
866 Node::Item(item) => match item.node {
867 hir::ItemKind::Fn(ref fn_decl, .., ref generics, _) => {
868 has_late_bound_regions(tcx, generics, fn_decl)
876 fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx ty::Generics {
879 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
881 let node = tcx.hir().get(node_id);
882 let parent_def_id = match node {
883 Node::ImplItem(_) | Node::TraitItem(_) | Node::Variant(_)
884 | Node::StructCtor(_) | Node::Field(_) => {
885 let parent_id = tcx.hir().get_parent(node_id);
886 Some(tcx.hir().local_def_id(parent_id))
888 Node::Expr(&hir::Expr {
889 node: hir::ExprKind::Closure(..),
891 }) => Some(tcx.closure_base_def_id(def_id)),
892 Node::Item(item) => match item.node {
893 ItemKind::Existential(hir::ExistTy { impl_trait_fn, .. }) => impl_trait_fn,
899 let mut opt_self = None;
900 let mut allow_defaults = false;
902 let no_generics = hir::Generics::empty();
903 let ast_generics = match node {
904 Node::TraitItem(item) => &item.generics,
906 Node::ImplItem(item) => &item.generics,
908 Node::Item(item) => {
910 ItemKind::Fn(.., ref generics, _) | ItemKind::Impl(_, _, _, ref generics, ..) => {
914 ItemKind::Ty(_, ref generics)
915 | ItemKind::Enum(_, ref generics)
916 | ItemKind::Struct(_, ref generics)
917 | ItemKind::Existential(hir::ExistTy { ref generics, .. })
918 | ItemKind::Union(_, ref generics) => {
919 allow_defaults = true;
923 ItemKind::Trait(_, _, ref generics, ..)
924 | ItemKind::TraitAlias(ref generics, ..) => {
925 // Add in the self type parameter.
927 // Something of a hack: use the node id for the trait, also as
928 // the node id for the Self type parameter.
929 let param_id = item.id;
931 opt_self = Some(ty::GenericParamDef {
933 name: keywords::SelfUpper.name().as_interned_str(),
934 def_id: tcx.hir().local_def_id(param_id),
935 pure_wrt_drop: false,
936 kind: ty::GenericParamDefKind::Type {
938 object_lifetime_default: rl::Set1::Empty,
943 allow_defaults = true;
951 Node::ForeignItem(item) => match item.node {
952 ForeignItemKind::Static(..) => &no_generics,
953 ForeignItemKind::Fn(_, _, ref generics) => generics,
954 ForeignItemKind::Type => &no_generics,
960 let has_self = opt_self.is_some();
961 let mut parent_has_self = false;
962 let mut own_start = has_self as u32;
963 let parent_count = parent_def_id.map_or(0, |def_id| {
964 let generics = tcx.generics_of(def_id);
965 assert_eq!(has_self, false);
966 parent_has_self = generics.has_self;
967 own_start = generics.count() as u32;
968 generics.parent_count + generics.params.len()
971 let mut params: Vec<_> = opt_self.into_iter().collect();
973 let early_lifetimes = early_bound_lifetimes_from_generics(tcx, ast_generics);
977 .map(|(i, param)| ty::GenericParamDef {
978 name: param.name.ident().as_interned_str(),
979 index: own_start + i as u32,
980 def_id: tcx.hir().local_def_id(param.id),
981 pure_wrt_drop: param.pure_wrt_drop,
982 kind: ty::GenericParamDefKind::Lifetime,
986 let hir_id = tcx.hir().node_to_hir_id(node_id);
987 let object_lifetime_defaults = tcx.object_lifetime_defaults(hir_id);
989 // Now create the real type parameters.
990 let type_start = own_start - has_self as u32 + params.len() as u32;
996 .filter_map(|param| match param.kind {
997 GenericParamKind::Type {
1002 if param.name.ident().name == keywords::SelfUpper.name() {
1005 "`Self` should not be the name of a regular parameter"
1009 if !allow_defaults && default.is_some() {
1010 if !tcx.features().default_type_parameter_fallback {
1012 lint::builtin::INVALID_TYPE_PARAM_DEFAULT,
1016 "defaults for type parameters are only allowed in \
1017 `struct`, `enum`, `type`, or `trait` definitions."
1023 let ty_param = ty::GenericParamDef {
1024 index: type_start + i as u32,
1025 name: param.name.ident().as_interned_str(),
1026 def_id: tcx.hir().local_def_id(param.id),
1027 pure_wrt_drop: param.pure_wrt_drop,
1028 kind: ty::GenericParamDefKind::Type {
1029 has_default: default.is_some(),
1030 object_lifetime_default: object_lifetime_defaults
1032 .map_or(rl::Set1::Empty, |o| o[i]),
1043 // provide junk type parameter defs - the only place that
1044 // cares about anything but the length is instantiation,
1045 // and we don't do that for closures.
1046 if let Node::Expr(&hir::Expr {
1047 node: hir::ExprKind::Closure(.., gen),
1051 let dummy_args = if gen.is_some() {
1052 &["<yield_ty>", "<return_ty>", "<witness>"][..]
1054 &["<closure_kind>", "<closure_signature>"][..]
1061 .map(|(i, &arg)| ty::GenericParamDef {
1062 index: type_start + i as u32,
1063 name: Symbol::intern(arg).as_interned_str(),
1065 pure_wrt_drop: false,
1066 kind: ty::GenericParamDefKind::Type {
1068 object_lifetime_default: rl::Set1::Empty,
1074 tcx.with_freevars(node_id, |fv| {
1075 params.extend(fv.iter().zip((dummy_args.len() as u32)..).map(|(_, i)| {
1076 ty::GenericParamDef {
1077 index: type_start + i,
1078 name: Symbol::intern("<upvar>").as_interned_str(),
1080 pure_wrt_drop: false,
1081 kind: ty::GenericParamDefKind::Type {
1083 object_lifetime_default: rl::Set1::Empty,
1091 let param_def_id_to_index = params
1093 .map(|param| (param.def_id, param.index))
1096 tcx.alloc_generics(ty::Generics {
1097 parent: parent_def_id,
1100 param_def_id_to_index,
1101 has_self: has_self || parent_has_self,
1102 has_late_bound_regions: has_late_bound_regions(tcx, node),
1106 fn report_assoc_ty_on_inherent_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, span: Span) {
1111 "associated types are not allowed in inherent impls"
1115 fn type_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Ty<'tcx> {
1118 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
1120 let icx = ItemCtxt::new(tcx, def_id);
1122 match tcx.hir().get(node_id) {
1123 Node::TraitItem(item) => match item.node {
1124 TraitItemKind::Method(..) => {
1125 let substs = Substs::identity_for_item(tcx, def_id);
1126 tcx.mk_fn_def(def_id, substs)
1128 TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => icx.to_ty(ty),
1129 TraitItemKind::Type(_, None) => {
1130 span_bug!(item.span, "associated type missing default");
1134 Node::ImplItem(item) => match item.node {
1135 ImplItemKind::Method(..) => {
1136 let substs = Substs::identity_for_item(tcx, def_id);
1137 tcx.mk_fn_def(def_id, substs)
1139 ImplItemKind::Const(ref ty, _) => icx.to_ty(ty),
1140 ImplItemKind::Existential(_) => {
1142 .impl_trait_ref(tcx.hir().get_parent_did(node_id))
1145 report_assoc_ty_on_inherent_impl(tcx, item.span);
1148 find_existential_constraints(tcx, def_id)
1150 ImplItemKind::Type(ref ty) => {
1152 .impl_trait_ref(tcx.hir().get_parent_did(node_id))
1155 report_assoc_ty_on_inherent_impl(tcx, item.span);
1162 Node::Item(item) => {
1164 ItemKind::Static(ref t, ..)
1165 | ItemKind::Const(ref t, _)
1166 | ItemKind::Ty(ref t, _)
1167 | ItemKind::Impl(.., ref t, _) => icx.to_ty(t),
1168 ItemKind::Fn(..) => {
1169 let substs = Substs::identity_for_item(tcx, def_id);
1170 tcx.mk_fn_def(def_id, substs)
1172 ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
1173 let def = tcx.adt_def(def_id);
1174 let substs = Substs::identity_for_item(tcx, def_id);
1175 tcx.mk_adt(def, substs)
1177 ItemKind::Existential(hir::ExistTy {
1178 impl_trait_fn: None,
1180 }) => find_existential_constraints(tcx, def_id),
1181 // existential types desugared from impl Trait
1182 ItemKind::Existential(hir::ExistTy {
1183 impl_trait_fn: Some(owner),
1186 tcx.typeck_tables_of(owner)
1187 .concrete_existential_types
1190 .unwrap_or_else(|| {
1191 // This can occur if some error in the
1192 // owner fn prevented us from populating
1193 // the `concrete_existential_types` table.
1194 tcx.sess.delay_span_bug(
1197 "owner {:?} has no existential type for {:?} in its tables",
1205 | ItemKind::TraitAlias(..)
1207 | ItemKind::ForeignMod(..)
1208 | ItemKind::GlobalAsm(..)
1209 | ItemKind::ExternCrate(..)
1210 | ItemKind::Use(..) => {
1213 "compute_type_of_item: unexpected item type: {:?}",
1220 Node::ForeignItem(foreign_item) => match foreign_item.node {
1221 ForeignItemKind::Fn(..) => {
1222 let substs = Substs::identity_for_item(tcx, def_id);
1223 tcx.mk_fn_def(def_id, substs)
1225 ForeignItemKind::Static(ref t, _) => icx.to_ty(t),
1226 ForeignItemKind::Type => tcx.mk_foreign(def_id),
1229 Node::StructCtor(&ref def)
1230 | Node::Variant(&Spanned {
1231 node: hir::VariantKind { data: ref def, .. },
1234 VariantData::Unit(..) | VariantData::Struct(..) => {
1235 tcx.type_of(tcx.hir().get_parent_did(node_id))
1237 VariantData::Tuple(..) => {
1238 let substs = Substs::identity_for_item(tcx, def_id);
1239 tcx.mk_fn_def(def_id, substs)
1243 Node::Field(field) => icx.to_ty(&field.ty),
1245 Node::Expr(&hir::Expr {
1246 node: hir::ExprKind::Closure(.., gen),
1250 let hir_id = tcx.hir().node_to_hir_id(node_id);
1251 return tcx.typeck_tables_of(def_id).node_id_to_type(hir_id);
1254 let substs = ty::ClosureSubsts {
1255 substs: Substs::identity_for_item(tcx, def_id),
1258 tcx.mk_closure(def_id, substs)
1261 Node::AnonConst(_) => match tcx.hir().get(tcx.hir().get_parent_node(node_id)) {
1263 node: hir::TyKind::Array(_, ref constant),
1266 | Node::Ty(&hir::Ty {
1267 node: hir::TyKind::Typeof(ref constant),
1270 | Node::Expr(&hir::Expr {
1271 node: ExprKind::Repeat(_, ref constant),
1273 }) if constant.id == node_id =>
1278 Node::Variant(&Spanned {
1281 disr_expr: Some(ref e),
1285 }) if e.id == node_id =>
1287 tcx.adt_def(tcx.hir().get_parent_did(node_id))
1294 bug!("unexpected const parent in type_of_def_id(): {:?}", x);
1298 Node::GenericParam(param) => match param.kind {
1299 hir::GenericParamKind::Type {
1300 default: Some(ref ty),
1303 _ => bug!("unexpected non-type NodeGenericParam"),
1307 bug!("unexpected sort of node in type_of_def_id(): {:?}", x);
1312 fn find_existential_constraints<'a, 'tcx>(
1313 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1318 struct ConstraintLocator<'a, 'tcx: 'a> {
1319 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1321 found: Option<(Span, ty::Ty<'tcx>)>,
1324 impl<'a, 'tcx> ConstraintLocator<'a, 'tcx> {
1325 fn check(&mut self, def_id: DefId) {
1326 trace!("checking {:?}", def_id);
1327 // don't try to check items that cannot possibly constrain the type
1328 if !self.tcx.has_typeck_tables(def_id) {
1329 trace!("no typeck tables for {:?}", def_id);
1334 .typeck_tables_of(def_id)
1335 .concrete_existential_types
1338 if let Some(ty) = ty {
1339 // FIXME(oli-obk): trace the actual span from inference to improve errors
1340 let span = self.tcx.def_span(def_id);
1341 if let Some((prev_span, prev_ty)) = self.found {
1343 // found different concrete types for the existential type
1344 let mut err = self.tcx.sess.struct_span_err(
1346 "defining existential type use differs from previous",
1348 err.span_note(prev_span, "previous use here");
1352 self.found = Some((span, ty));
1358 impl<'a, 'tcx> intravisit::Visitor<'tcx> for ConstraintLocator<'a, 'tcx> {
1359 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
1360 intravisit::NestedVisitorMap::All(&self.tcx.hir())
1362 fn visit_item(&mut self, it: &'tcx Item) {
1363 let def_id = self.tcx.hir().local_def_id(it.id);
1364 // the existential type itself or its children are not within its reveal scope
1365 if def_id != self.def_id {
1367 intravisit::walk_item(self, it);
1370 fn visit_impl_item(&mut self, it: &'tcx ImplItem) {
1371 let def_id = self.tcx.hir().local_def_id(it.id);
1372 // the existential type itself or its children are not within its reveal scope
1373 if def_id != self.def_id {
1375 intravisit::walk_impl_item(self, it);
1378 fn visit_trait_item(&mut self, it: &'tcx TraitItem) {
1379 let def_id = self.tcx.hir().local_def_id(it.id);
1381 intravisit::walk_trait_item(self, it);
1385 let mut locator = ConstraintLocator {
1390 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
1391 let parent = tcx.hir().get_parent(node_id);
1393 trace!("parent_id: {:?}", parent);
1395 if parent == ast::CRATE_NODE_ID {
1396 intravisit::walk_crate(&mut locator, tcx.hir().krate());
1398 trace!("parent: {:?}", tcx.hir().get(parent));
1399 match tcx.hir().get(parent) {
1400 Node::Item(ref it) => intravisit::walk_item(&mut locator, it),
1401 Node::ImplItem(ref it) => intravisit::walk_impl_item(&mut locator, it),
1402 Node::TraitItem(ref it) => intravisit::walk_trait_item(&mut locator, it),
1404 "{:?} is not a valid parent of an existential type item",
1410 match locator.found {
1411 Some((_, ty)) => ty,
1413 let span = tcx.def_span(def_id);
1414 tcx.sess.span_err(span, "could not find defining uses");
1420 fn fn_sig<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> ty::PolyFnSig<'tcx> {
1422 use rustc::hir::Node::*;
1424 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
1426 let icx = ItemCtxt::new(tcx, def_id);
1428 match tcx.hir().get(node_id) {
1429 TraitItem(hir::TraitItem {
1430 node: TraitItemKind::Method(sig, _),
1433 | ImplItem(hir::ImplItem {
1434 node: ImplItemKind::Method(sig, _),
1436 }) => AstConv::ty_of_fn(&icx, sig.header.unsafety, sig.header.abi, &sig.decl),
1439 node: ItemKind::Fn(decl, header, _, _),
1441 }) => AstConv::ty_of_fn(&icx, header.unsafety, header.abi, decl),
1443 ForeignItem(&hir::ForeignItem {
1444 node: ForeignItemKind::Fn(ref fn_decl, _, _),
1447 let abi = tcx.hir().get_foreign_abi(node_id);
1448 compute_sig_of_foreign_fn_decl(tcx, def_id, fn_decl, abi)
1451 StructCtor(&VariantData::Tuple(ref fields, _))
1452 | Variant(&Spanned {
1455 data: VariantData::Tuple(ref fields, _),
1460 let ty = tcx.type_of(tcx.hir().get_parent_did(node_id));
1463 .map(|f| tcx.type_of(tcx.hir().local_def_id(f.id)));
1464 ty::Binder::bind(tcx.mk_fn_sig(
1468 hir::Unsafety::Normal,
1474 node: hir::ExprKind::Closure(..),
1477 // Closure signatures are not like other function
1478 // signatures and cannot be accessed through `fn_sig`. For
1479 // example, a closure signature excludes the `self`
1480 // argument. In any case they are embedded within the
1481 // closure type as part of the `ClosureSubsts`.
1484 // the signature of a closure, you should use the
1485 // `closure_sig` method on the `ClosureSubsts`:
1487 // closure_substs.closure_sig(def_id, tcx)
1489 // or, inside of an inference context, you can use
1491 // infcx.closure_sig(def_id, closure_substs)
1492 bug!("to get the signature of a closure, use `closure_sig()` not `fn_sig()`");
1496 bug!("unexpected sort of node in fn_sig(): {:?}", x);
1501 fn impl_trait_ref<'a, 'tcx>(
1502 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1504 ) -> Option<ty::TraitRef<'tcx>> {
1505 let icx = ItemCtxt::new(tcx, def_id);
1507 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
1508 match tcx.hir().expect_item(node_id).node {
1509 hir::ItemKind::Impl(.., ref opt_trait_ref, _, _) => {
1510 opt_trait_ref.as_ref().map(|ast_trait_ref| {
1511 let selfty = tcx.type_of(def_id);
1512 AstConv::instantiate_mono_trait_ref(&icx, ast_trait_ref, selfty)
1519 fn impl_polarity<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> hir::ImplPolarity {
1520 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
1521 match tcx.hir().expect_item(node_id).node {
1522 hir::ItemKind::Impl(_, polarity, ..) => polarity,
1523 ref item => bug!("impl_polarity: {:?} not an impl", item),
1527 // Is it marked with ?Sized
1528 fn is_unsized<'gcx: 'tcx, 'tcx>(
1529 astconv: &dyn AstConv<'gcx, 'tcx>,
1530 ast_bounds: &[hir::GenericBound],
1533 let tcx = astconv.tcx();
1535 // Try to find an unbound in bounds.
1536 let mut unbound = None;
1537 for ab in ast_bounds {
1538 if let &hir::GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = ab {
1539 if unbound.is_none() {
1540 unbound = Some(ptr.trait_ref.clone());
1546 "type parameter has more than one relaxed default \
1547 bound, only one is supported"
1553 let kind_id = tcx.lang_items().require(SizedTraitLangItem);
1556 // FIXME(#8559) currently requires the unbound to be built-in.
1557 if let Ok(kind_id) = kind_id {
1558 if tpb.path.def != Def::Trait(kind_id) {
1561 "default bound relaxed for a type parameter, but \
1562 this does nothing because the given bound is not \
1563 a default. Only `?Sized` is supported",
1568 _ if kind_id.is_ok() => {
1571 // No lang item for Sized, so we can't add it as a bound.
1578 /// Returns the early-bound lifetimes declared in this generics
1579 /// listing. For anything other than fns/methods, this is just all
1580 /// the lifetimes that are declared. For fns or methods, we have to
1581 /// screen out those that do not appear in any where-clauses etc using
1582 /// `resolve_lifetime::early_bound_lifetimes`.
1583 fn early_bound_lifetimes_from_generics<'a, 'tcx>(
1584 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1585 generics: &'a hir::Generics,
1586 ) -> impl Iterator<Item = &'a hir::GenericParam> + Captures<'tcx> {
1590 .filter(move |param| match param.kind {
1591 GenericParamKind::Lifetime { .. } => {
1592 let hir_id = tcx.hir().node_to_hir_id(param.id);
1593 !tcx.is_late_bound(hir_id)
1599 fn predicates_defined_on<'a, 'tcx>(
1600 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1602 ) -> Lrc<ty::GenericPredicates<'tcx>> {
1603 debug!("predicates_defined_on({:?})", def_id);
1604 let mut result = tcx.explicit_predicates_of(def_id);
1606 "predicates_defined_on: explicit_predicates_of({:?}) = {:?}",
1610 let inferred_outlives = tcx.inferred_outlives_of(def_id);
1611 if !inferred_outlives.is_empty() {
1612 let span = tcx.def_span(def_id);
1614 "predicates_defined_on: inferred_outlives_of({:?}) = {:?}",
1618 Lrc::make_mut(&mut result)
1620 .extend(inferred_outlives.iter().map(|&p| (p, span)));
1622 debug!("predicates_defined_on({:?}) = {:?}", def_id, result);
1626 fn predicates_of<'a, 'tcx>(
1627 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1629 ) -> Lrc<ty::GenericPredicates<'tcx>> {
1630 let mut result = tcx.predicates_defined_on(def_id);
1632 if tcx.is_trait(def_id) {
1633 // For traits, add `Self: Trait` predicate. This is
1634 // not part of the predicates that a user writes, but it
1635 // is something that one must prove in order to invoke a
1636 // method or project an associated type.
1638 // In the chalk setup, this predicate is not part of the
1639 // "predicates" for a trait item. But it is useful in
1640 // rustc because if you directly (e.g.) invoke a trait
1641 // method like `Trait::method(...)`, you must naturally
1642 // prove that the trait applies to the types that were
1643 // used, and adding the predicate into this list ensures
1644 // that this is done.
1645 let span = tcx.def_span(def_id);
1646 Lrc::make_mut(&mut result)
1648 .push((ty::TraitRef::identity(tcx, def_id).to_predicate(), span));
1650 debug!("predicates_of(def_id={:?}) = {:?}", def_id, result);
1654 fn explicit_predicates_of<'a, 'tcx>(
1655 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1657 ) -> Lrc<ty::GenericPredicates<'tcx>> {
1659 use rustc_data_structures::fx::FxHashSet;
1661 debug!("explicit_predicates_of(def_id={:?})", def_id);
1663 /// A data structure with unique elements, which preserves order of insertion.
1664 /// Preserving the order of insertion is important here so as not to break
1665 /// compile-fail UI tests.
1666 struct UniquePredicates<'tcx> {
1667 predicates: Vec<(ty::Predicate<'tcx>, Span)>,
1668 uniques: FxHashSet<(ty::Predicate<'tcx>, Span)>,
1671 impl<'tcx> UniquePredicates<'tcx> {
1675 uniques: FxHashSet::default(),
1679 fn push(&mut self, value: (ty::Predicate<'tcx>, Span)) {
1680 if self.uniques.insert(value) {
1681 self.predicates.push(value);
1685 fn extend<I: IntoIterator<Item = (ty::Predicate<'tcx>, Span)>>(&mut self, iter: I) {
1692 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
1693 let node = tcx.hir().get(node_id);
1695 let mut is_trait = None;
1696 let mut is_default_impl_trait = None;
1698 let icx = ItemCtxt::new(tcx, def_id);
1699 let no_generics = hir::Generics::empty();
1700 let empty_trait_items = HirVec::new();
1702 let mut predicates = UniquePredicates::new();
1704 let ast_generics = match node {
1705 Node::TraitItem(item) => &item.generics,
1707 Node::ImplItem(item) => match item.node {
1708 ImplItemKind::Existential(ref bounds) => {
1709 let substs = Substs::identity_for_item(tcx, def_id);
1710 let opaque_ty = tcx.mk_opaque(def_id, substs);
1712 // Collect the bounds, i.e., the `A+B+'c` in `impl A+B+'c`.
1713 let bounds = compute_bounds(
1717 SizedByDefault::Yes,
1718 tcx.def_span(def_id),
1721 predicates.extend(bounds.predicates(tcx, opaque_ty));
1724 _ => &item.generics,
1727 Node::Item(item) => {
1729 ItemKind::Impl(_, _, defaultness, ref generics, ..) => {
1730 if defaultness.is_default() {
1731 is_default_impl_trait = tcx.impl_trait_ref(def_id);
1735 ItemKind::Fn(.., ref generics, _)
1736 | ItemKind::Ty(_, ref generics)
1737 | ItemKind::Enum(_, ref generics)
1738 | ItemKind::Struct(_, ref generics)
1739 | ItemKind::Union(_, ref generics) => generics,
1741 ItemKind::Trait(_, _, ref generics, .., ref items) => {
1742 is_trait = Some((ty::TraitRef::identity(tcx, def_id), items));
1745 ItemKind::TraitAlias(ref generics, _) => {
1746 is_trait = Some((ty::TraitRef::identity(tcx, def_id), &empty_trait_items));
1749 ItemKind::Existential(ExistTy {
1754 let substs = Substs::identity_for_item(tcx, def_id);
1755 let opaque_ty = tcx.mk_opaque(def_id, substs);
1757 // Collect the bounds, i.e., the `A+B+'c` in `impl A+B+'c`.
1758 let bounds = compute_bounds(
1762 SizedByDefault::Yes,
1763 tcx.def_span(def_id),
1766 if impl_trait_fn.is_some() {
1768 return Lrc::new(ty::GenericPredicates {
1770 predicates: bounds.predicates(tcx, opaque_ty),
1773 // named existential types
1774 predicates.extend(bounds.predicates(tcx, opaque_ty));
1783 Node::ForeignItem(item) => match item.node {
1784 ForeignItemKind::Static(..) => &no_generics,
1785 ForeignItemKind::Fn(_, _, ref generics) => generics,
1786 ForeignItemKind::Type => &no_generics,
1792 let generics = tcx.generics_of(def_id);
1793 let parent_count = generics.parent_count as u32;
1794 let has_own_self = generics.has_self && parent_count == 0;
1796 // Below we'll consider the bounds on the type parameters (including `Self`)
1797 // and the explicit where-clauses, but to get the full set of predicates
1798 // on a trait we need to add in the supertrait bounds and bounds found on
1799 // associated types.
1800 if let Some((_trait_ref, _)) = is_trait {
1801 predicates.extend(tcx.super_predicates_of(def_id).predicates.iter().cloned());
1804 // In default impls, we can assume that the self type implements
1805 // the trait. So in:
1807 // default impl Foo for Bar { .. }
1809 // we add a default where clause `Foo: Bar`. We do a similar thing for traits
1810 // (see below). Recall that a default impl is not itself an impl, but rather a
1811 // set of defaults that can be incorporated into another impl.
1812 if let Some(trait_ref) = is_default_impl_trait {
1813 predicates.push((trait_ref.to_poly_trait_ref().to_predicate(), tcx.def_span(def_id)));
1816 // Collect the region predicates that were declared inline as
1817 // well. In the case of parameters declared on a fn or method, we
1818 // have to be careful to only iterate over early-bound regions.
1819 let mut index = parent_count + has_own_self as u32;
1820 for param in early_bound_lifetimes_from_generics(tcx, ast_generics) {
1821 let region = tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
1822 def_id: tcx.hir().local_def_id(param.id),
1824 name: param.name.ident().as_interned_str(),
1829 GenericParamKind::Lifetime { .. } => {
1830 param.bounds.iter().for_each(|bound| match bound {
1831 hir::GenericBound::Outlives(lt) => {
1832 let bound = AstConv::ast_region_to_region(&icx, <, None);
1833 let outlives = ty::Binder::bind(ty::OutlivesPredicate(region, bound));
1834 predicates.push((outlives.to_predicate(), lt.span));
1843 // Collect the predicates that were written inline by the user on each
1844 // type parameter (e.g., `<T:Foo>`).
1845 for param in &ast_generics.params {
1846 if let GenericParamKind::Type { .. } = param.kind {
1847 let name = param.name.ident().as_interned_str();
1848 let param_ty = ty::ParamTy::new(index, name).to_ty(tcx);
1851 let sized = SizedByDefault::Yes;
1852 let bounds = compute_bounds(&icx, param_ty, ¶m.bounds, sized, param.span);
1853 predicates.extend(bounds.predicates(tcx, param_ty));
1857 // Add in the bounds that appear in the where-clause
1858 let where_clause = &ast_generics.where_clause;
1859 for predicate in &where_clause.predicates {
1861 &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
1862 let ty = icx.to_ty(&bound_pred.bounded_ty);
1864 // Keep the type around in a dummy predicate, in case of no bounds.
1865 // That way, `where Ty:` is not a complete noop (see #53696) and `Ty`
1866 // is still checked for WF.
1867 if bound_pred.bounds.is_empty() {
1868 if let ty::Param(_) = ty.sty {
1869 // This is a `where T:`, which can be in the HIR from the
1870 // transformation that moves `?Sized` to `T`'s declaration.
1871 // We can skip the predicate because type parameters are
1872 // trivially WF, but also we *should*, to avoid exposing
1873 // users who never wrote `where Type:,` themselves, to
1874 // compiler/tooling bugs from not handling WF predicates.
1876 let span = bound_pred.bounded_ty.span;
1877 let predicate = ty::OutlivesPredicate(ty, tcx.mk_region(ty::ReEmpty));
1879 (ty::Predicate::TypeOutlives(ty::Binder::dummy(predicate)), span)
1884 for bound in bound_pred.bounds.iter() {
1886 &hir::GenericBound::Trait(ref poly_trait_ref, _) => {
1887 let mut projections = Vec::new();
1889 let (trait_ref, _) = AstConv::instantiate_poly_trait_ref(
1897 iter::once((trait_ref.to_predicate(), poly_trait_ref.span)).chain(
1898 projections.iter().map(|&(p, span)| (p.to_predicate(), span)
1902 &hir::GenericBound::Outlives(ref lifetime) => {
1903 let region = AstConv::ast_region_to_region(&icx, lifetime, None);
1904 let pred = ty::Binder::bind(ty::OutlivesPredicate(ty, region));
1905 predicates.push((ty::Predicate::TypeOutlives(pred), lifetime.span))
1911 &hir::WherePredicate::RegionPredicate(ref region_pred) => {
1912 let r1 = AstConv::ast_region_to_region(&icx, ®ion_pred.lifetime, None);
1913 predicates.extend(region_pred.bounds.iter().map(|bound| {
1914 let (r2, span) = match bound {
1915 hir::GenericBound::Outlives(lt) => {
1916 (AstConv::ast_region_to_region(&icx, lt, None), lt.span)
1920 let pred = ty::Binder::bind(ty::OutlivesPredicate(r1, r2));
1922 (ty::Predicate::RegionOutlives(pred), span)
1926 &hir::WherePredicate::EqPredicate(..) => {
1932 // Add predicates from associated type bounds.
1933 if let Some((self_trait_ref, trait_items)) = is_trait {
1934 predicates.extend(trait_items.iter().flat_map(|trait_item_ref| {
1935 let trait_item = tcx.hir().trait_item(trait_item_ref.id);
1936 let bounds = match trait_item.node {
1937 hir::TraitItemKind::Type(ref bounds, _) => bounds,
1938 _ => return vec![].into_iter()
1942 tcx.mk_projection(tcx.hir().local_def_id(trait_item.id), self_trait_ref.substs);
1944 let bounds = compute_bounds(
1945 &ItemCtxt::new(tcx, def_id),
1948 SizedByDefault::Yes,
1952 bounds.predicates(tcx, assoc_ty).into_iter()
1956 let mut predicates = predicates.predicates;
1958 // Subtle: before we store the predicates into the tcx, we
1959 // sort them so that predicates like `T: Foo<Item=U>` come
1960 // before uses of `U`. This avoids false ambiguity errors
1961 // in trait checking. See `setup_constraining_predicates`
1963 if let Node::Item(&Item {
1964 node: ItemKind::Impl(..),
1968 let self_ty = tcx.type_of(def_id);
1969 let trait_ref = tcx.impl_trait_ref(def_id);
1970 ctp::setup_constraining_predicates(
1974 &mut ctp::parameters_for_impl(self_ty, trait_ref),
1978 let result = Lrc::new(ty::GenericPredicates {
1979 parent: generics.parent,
1982 debug!("explicit_predicates_of(def_id={:?}) = {:?}", def_id, result);
1986 pub enum SizedByDefault {
1991 /// Translate the AST's notion of ty param bounds (which are an enum consisting of a newtyped `Ty`
1992 /// or a region) to ty's notion of ty param bounds, which can either be user-defined traits, or the
1993 /// built-in trait `Send`.
1994 pub fn compute_bounds<'gcx: 'tcx, 'tcx>(
1995 astconv: &dyn AstConv<'gcx, 'tcx>,
1997 ast_bounds: &[hir::GenericBound],
1998 sized_by_default: SizedByDefault,
2001 let mut region_bounds = Vec::new();
2002 let mut trait_bounds = Vec::new();
2004 for ast_bound in ast_bounds {
2006 hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::None) => trait_bounds.push(b),
2007 hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => {}
2008 hir::GenericBound::Outlives(ref l) => region_bounds.push(l),
2012 let mut projection_bounds = Vec::new();
2014 let mut trait_bounds: Vec<_> = trait_bounds.iter().map(|&bound| {
2015 let (poly_trait_ref, _) = astconv.instantiate_poly_trait_ref(
2018 &mut projection_bounds,
2020 (poly_trait_ref, bound.span)
2023 let region_bounds = region_bounds
2025 .map(|r| (astconv.ast_region_to_region(r, None), r.span))
2028 trait_bounds.sort_by_key(|(t, _)| t.def_id());
2030 let implicitly_sized = if let SizedByDefault::Yes = sized_by_default {
2031 if !is_unsized(astconv, ast_bounds, span) {
2048 /// Converts a specific `GenericBound` from the AST into a set of
2049 /// predicates that apply to the self-type. A vector is returned
2050 /// because this can be anywhere from zero predicates (`T : ?Sized` adds no
2051 /// predicates) to one (`T : Foo`) to many (`T : Bar<X=i32>` adds `T : Bar`
2052 /// and `<T as Bar>::X == i32`).
2053 fn predicates_from_bound<'tcx>(
2054 astconv: &dyn AstConv<'tcx, 'tcx>,
2056 bound: &hir::GenericBound,
2057 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2059 hir::GenericBound::Trait(ref tr, hir::TraitBoundModifier::None) => {
2060 let mut projections = Vec::new();
2061 let (pred, _) = astconv.instantiate_poly_trait_ref(tr, param_ty, &mut projections);
2062 iter::once((pred.to_predicate(), tr.span)).chain(
2065 .map(|(p, span)| (p.to_predicate(), span))
2068 hir::GenericBound::Outlives(ref lifetime) => {
2069 let region = astconv.ast_region_to_region(lifetime, None);
2070 let pred = ty::Binder::bind(ty::OutlivesPredicate(param_ty, region));
2071 vec![(ty::Predicate::TypeOutlives(pred), lifetime.span)]
2073 hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => vec![],
2077 fn compute_sig_of_foreign_fn_decl<'a, 'tcx>(
2078 tcx: TyCtxt<'a, 'tcx, 'tcx>,
2082 ) -> ty::PolyFnSig<'tcx> {
2083 let unsafety = if abi == abi::Abi::RustIntrinsic {
2084 intrisic_operation_unsafety(&*tcx.item_name(def_id).as_str())
2086 hir::Unsafety::Unsafe
2088 let fty = AstConv::ty_of_fn(&ItemCtxt::new(tcx, def_id), unsafety, abi, decl);
2090 // feature gate SIMD types in FFI, since I (huonw) am not sure the
2091 // ABIs are handled at all correctly.
2092 if abi != abi::Abi::RustIntrinsic
2093 && abi != abi::Abi::PlatformIntrinsic
2094 && !tcx.features().simd_ffi
2096 let check = |ast_ty: &hir::Ty, ty: Ty| {
2102 "use of SIMD type `{}` in FFI is highly experimental and \
2103 may result in invalid code",
2104 tcx.hir().node_to_pretty_string(ast_ty.id)
2107 .help("add #![feature(simd_ffi)] to the crate attributes to enable")
2111 for (input, ty) in decl.inputs.iter().zip(*fty.inputs().skip_binder()) {
2114 if let hir::Return(ref ty) = decl.output {
2115 check(&ty, *fty.output().skip_binder())
2122 fn is_foreign_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> bool {
2123 match tcx.hir().get_if_local(def_id) {
2124 Some(Node::ForeignItem(..)) => true,
2126 _ => bug!("is_foreign_item applied to non-local def-id {:?}", def_id),
2130 fn from_target_feature(
2133 attr: &ast::Attribute,
2134 whitelist: &FxHashMap<String, Option<String>>,
2135 target_features: &mut Vec<Symbol>,
2137 let list = match attr.meta_item_list() {
2140 let msg = "#[target_feature] attribute must be of the form \
2141 #[target_feature(..)]";
2142 tcx.sess.span_err(attr.span, &msg);
2146 let rust_features = tcx.features();
2148 // Only `enable = ...` is accepted in the meta item list
2149 if !item.check_name("enable") {
2150 let msg = "#[target_feature(..)] only accepts sub-keys of `enable` \
2152 tcx.sess.span_err(item.span, &msg);
2156 // Must be of the form `enable = "..."` ( a string)
2157 let value = match item.value_str() {
2158 Some(value) => value,
2160 let msg = "#[target_feature] attribute must be of the form \
2161 #[target_feature(enable = \"..\")]";
2162 tcx.sess.span_err(item.span, &msg);
2167 // We allow comma separation to enable multiple features
2168 target_features.extend(value.as_str().split(',').filter_map(|feature| {
2169 // Only allow whitelisted features per platform
2170 let feature_gate = match whitelist.get(feature) {
2174 "the feature named `{}` is not valid for \
2178 let mut err = tcx.sess.struct_span_err(item.span, &msg);
2180 if feature.starts_with("+") {
2181 let valid = whitelist.contains_key(&feature[1..]);
2183 err.help("consider removing the leading `+` in the feature name");
2191 // Only allow features whose feature gates have been enabled
2192 let allowed = match feature_gate.as_ref().map(|s| &**s) {
2193 Some("arm_target_feature") => rust_features.arm_target_feature,
2194 Some("aarch64_target_feature") => rust_features.aarch64_target_feature,
2195 Some("hexagon_target_feature") => rust_features.hexagon_target_feature,
2196 Some("powerpc_target_feature") => rust_features.powerpc_target_feature,
2197 Some("mips_target_feature") => rust_features.mips_target_feature,
2198 Some("avx512_target_feature") => rust_features.avx512_target_feature,
2199 Some("mmx_target_feature") => rust_features.mmx_target_feature,
2200 Some("sse4a_target_feature") => rust_features.sse4a_target_feature,
2201 Some("tbm_target_feature") => rust_features.tbm_target_feature,
2202 Some("wasm_target_feature") => rust_features.wasm_target_feature,
2203 Some("cmpxchg16b_target_feature") => rust_features.cmpxchg16b_target_feature,
2204 Some("adx_target_feature") => rust_features.adx_target_feature,
2205 Some(name) => bug!("unknown target feature gate {}", name),
2208 if !allowed && id.is_local() {
2209 feature_gate::emit_feature_err(
2210 &tcx.sess.parse_sess,
2211 feature_gate.as_ref().unwrap(),
2213 feature_gate::GateIssue::Language,
2214 &format!("the target feature `{}` is currently unstable", feature),
2217 Some(Symbol::intern(feature))
2222 fn linkage_by_name<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId, name: &str) -> Linkage {
2223 use rustc::mir::mono::Linkage::*;
2225 // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
2226 // applicable to variable declarations and may not really make sense for
2227 // Rust code in the first place but whitelist them anyway and trust that
2228 // the user knows what s/he's doing. Who knows, unanticipated use cases
2229 // may pop up in the future.
2231 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
2232 // and don't have to be, LLVM treats them as no-ops.
2234 "appending" => Appending,
2235 "available_externally" => AvailableExternally,
2237 "extern_weak" => ExternalWeak,
2238 "external" => External,
2239 "internal" => Internal,
2240 "linkonce" => LinkOnceAny,
2241 "linkonce_odr" => LinkOnceODR,
2242 "private" => Private,
2244 "weak_odr" => WeakODR,
2246 let span = tcx.hir().span_if_local(def_id);
2247 if let Some(span) = span {
2248 tcx.sess.span_fatal(span, "invalid linkage specified")
2251 .fatal(&format!("invalid linkage specified: {}", name))
2257 fn codegen_fn_attrs<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, id: DefId) -> CodegenFnAttrs {
2258 let attrs = tcx.get_attrs(id);
2260 let mut codegen_fn_attrs = CodegenFnAttrs::new();
2262 let whitelist = tcx.target_features_whitelist(LOCAL_CRATE);
2264 let mut inline_span = None;
2265 for attr in attrs.iter() {
2266 if attr.check_name("cold") {
2267 codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD;
2268 } else if attr.check_name("allocator") {
2269 codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR;
2270 } else if attr.check_name("unwind") {
2271 codegen_fn_attrs.flags |= CodegenFnAttrFlags::UNWIND;
2272 } else if attr.check_name("rustc_allocator_nounwind") {
2273 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND;
2274 } else if attr.check_name("naked") {
2275 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED;
2276 } else if attr.check_name("no_mangle") {
2277 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2278 } else if attr.check_name("rustc_std_internal_symbol") {
2279 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2280 } else if attr.check_name("no_debug") {
2281 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_DEBUG;
2282 } else if attr.check_name("used") {
2283 codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED;
2284 } else if attr.check_name("thread_local") {
2285 codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL;
2286 } else if attr.check_name("inline") {
2287 codegen_fn_attrs.inline = attrs.iter().fold(InlineAttr::None, |ia, attr| {
2288 if attr.path != "inline" {
2291 let meta = match attr.meta() {
2292 Some(meta) => meta.node,
2296 MetaItemKind::Word => {
2300 MetaItemKind::List(ref items) => {
2302 inline_span = Some(attr.span);
2303 if items.len() != 1 {
2305 tcx.sess.diagnostic(),
2308 "expected one argument"
2311 } else if list_contains_name(&items[..], "always") {
2313 } else if list_contains_name(&items[..], "never") {
2317 tcx.sess.diagnostic(),
2329 } else if attr.check_name("export_name") {
2330 if let Some(s) = attr.value_str() {
2331 if s.as_str().contains("\0") {
2332 // `#[export_name = ...]` will be converted to a null-terminated string,
2333 // so it may not contain any null characters.
2338 "`export_name` may not contain null characters"
2341 codegen_fn_attrs.export_name = Some(s);
2347 "`export_name` attribute has invalid format"
2348 ).span_label(attr.span, "did you mean #[export_name=\"*\"]?")
2351 } else if attr.check_name("target_feature") {
2352 if tcx.fn_sig(id).unsafety() == Unsafety::Normal {
2353 let msg = "#[target_feature(..)] can only be applied to \
2355 tcx.sess.span_err(attr.span, msg);
2357 from_target_feature(
2362 &mut codegen_fn_attrs.target_features,
2364 } else if attr.check_name("linkage") {
2365 if let Some(val) = attr.value_str() {
2366 codegen_fn_attrs.linkage = Some(linkage_by_name(tcx, id, &val.as_str()));
2368 } else if attr.check_name("link_section") {
2369 if let Some(val) = attr.value_str() {
2370 if val.as_str().bytes().any(|b| b == 0) {
2372 "illegal null byte in link_section \
2376 tcx.sess.span_err(attr.span, &msg);
2378 codegen_fn_attrs.link_section = Some(val);
2381 } else if attr.check_name("link_name") {
2382 codegen_fn_attrs.link_name = attr.value_str();
2386 // If a function uses #[target_feature] it can't be inlined into general
2387 // purpose functions as they wouldn't have the right target features
2388 // enabled. For that reason we also forbid #[inline(always)] as it can't be
2390 if codegen_fn_attrs.target_features.len() > 0 {
2391 if codegen_fn_attrs.inline == InlineAttr::Always {
2392 if let Some(span) = inline_span {
2395 "cannot use #[inline(always)] with \
2402 // Weak lang items have the same semantics as "std internal" symbols in the
2403 // sense that they're preserved through all our LTO passes and only
2404 // strippable by the linker.
2406 // Additionally weak lang items have predetermined symbol names.
2407 if tcx.is_weak_lang_item(id) {
2408 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2410 if let Some(name) = weak_lang_items::link_name(&attrs) {
2411 codegen_fn_attrs.export_name = Some(name);
2412 codegen_fn_attrs.link_name = Some(name);
2415 // Internal symbols to the standard library all have no_mangle semantics in
2416 // that they have defined symbol names present in the function name. This
2417 // also applies to weak symbols where they all have known symbol names.
2418 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
2419 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;