1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! "Collection" is the process of determining the type and other external
12 //! details of each item in Rust. Collection is specifically concerned
13 //! with *interprocedural* things -- for example, for a function
14 //! definition, collection will figure out the type and signature of the
15 //! function, but it will not visit the *body* of the function in any way,
16 //! nor examine type annotations on local variables (that's the job of
19 //! Collecting is ultimately defined by a bundle of queries that
20 //! inquire after various facts about the items in the crate (e.g.,
21 //! `type_of`, `generics_of`, `predicates_of`, etc). See the `provide` function
24 //! At present, however, we do run collection across all items in the
25 //! crate as a kind of pass. This should eventually be factored away.
27 use astconv::{AstConv, Bounds};
28 use constrained_type_params as ctp;
30 use middle::lang_items::SizedTraitLangItem;
31 use middle::resolve_lifetime as rl;
32 use middle::weak_lang_items;
33 use rustc::mir::mono::Linkage;
34 use rustc::ty::query::Providers;
35 use rustc::ty::subst::Substs;
36 use rustc::ty::util::Discr;
37 use rustc::ty::util::IntTypeExt;
38 use rustc::ty::{self, AdtKind, ToPolyTraitRef, Ty, TyCtxt};
39 use rustc::ty::{ReprOptions, ToPredicate};
40 use rustc::util::captures::Captures;
41 use rustc::util::nodemap::FxHashMap;
42 use rustc_data_structures::sync::Lrc;
43 use rustc_target::spec::abi;
46 use syntax::ast::MetaItemKind;
47 use syntax::attr::{InlineAttr, list_contains_name, mark_used};
48 use syntax::source_map::Spanned;
49 use syntax::feature_gate;
50 use syntax::symbol::{keywords, Symbol};
51 use syntax_pos::{Span, DUMMY_SP};
53 use rustc::hir::def::{CtorKind, Def};
55 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
56 use rustc::hir::intravisit::{self, NestedVisitorMap, Visitor};
57 use rustc::hir::GenericParamKind;
58 use rustc::hir::{self, CodegenFnAttrFlags, CodegenFnAttrs, Unsafety};
62 struct OnlySelfBounds(bool);
64 ///////////////////////////////////////////////////////////////////////////
67 pub fn collect_item_types<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
68 let mut visitor = CollectItemTypesVisitor { tcx };
71 .visit_all_item_likes(&mut visitor.as_deep_visitor());
74 pub fn provide(providers: &mut Providers) {
75 *providers = Providers {
79 predicates_defined_on,
80 explicit_predicates_of,
82 type_param_predicates,
94 ///////////////////////////////////////////////////////////////////////////
96 /// Context specific to some particular item. This is what implements
97 /// AstConv. It has information about the predicates that are defined
98 /// on the trait. Unfortunately, this predicate information is
99 /// available in various different forms at various points in the
100 /// process. So we can't just store a pointer to e.g. the AST or the
101 /// parsed ty form, we have to be more flexible. To this end, the
102 /// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy
103 /// `get_type_parameter_bounds` requests, drawing the information from
104 /// the AST (`hir::Generics`), recursively.
105 pub struct ItemCtxt<'a, 'tcx: 'a> {
106 tcx: TyCtxt<'a, 'tcx, 'tcx>,
110 ///////////////////////////////////////////////////////////////////////////
112 struct CollectItemTypesVisitor<'a, 'tcx: 'a> {
113 tcx: TyCtxt<'a, 'tcx, 'tcx>,
116 impl<'a, 'tcx> Visitor<'tcx> for CollectItemTypesVisitor<'a, 'tcx> {
117 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
118 NestedVisitorMap::OnlyBodies(&self.tcx.hir())
121 fn visit_item(&mut self, item: &'tcx hir::Item) {
122 convert_item(self.tcx, item.id);
123 intravisit::walk_item(self, item);
126 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
127 for param in &generics.params {
129 hir::GenericParamKind::Lifetime { .. } => {}
130 hir::GenericParamKind::Type {
133 let def_id = self.tcx.hir().local_def_id(param.id);
134 self.tcx.type_of(def_id);
136 hir::GenericParamKind::Type { .. } => {}
139 intravisit::walk_generics(self, generics);
142 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
143 if let hir::ExprKind::Closure(..) = expr.node {
144 let def_id = self.tcx.hir().local_def_id(expr.id);
145 self.tcx.generics_of(def_id);
146 self.tcx.type_of(def_id);
148 intravisit::walk_expr(self, expr);
151 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
152 convert_trait_item(self.tcx, trait_item.id);
153 intravisit::walk_trait_item(self, trait_item);
156 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
157 convert_impl_item(self.tcx, impl_item.id);
158 intravisit::walk_impl_item(self, impl_item);
162 ///////////////////////////////////////////////////////////////////////////
163 // Utility types and common code for the above passes.
165 impl<'a, 'tcx> ItemCtxt<'a, 'tcx> {
166 pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, item_def_id: DefId) -> ItemCtxt<'a, 'tcx> {
167 ItemCtxt { tcx, item_def_id }
171 impl<'a, 'tcx> ItemCtxt<'a, 'tcx> {
172 pub fn to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> {
173 AstConv::ast_ty_to_ty(self, ast_ty)
177 impl<'a, 'tcx> AstConv<'tcx, 'tcx> for ItemCtxt<'a, 'tcx> {
178 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'tcx, 'tcx> {
182 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId)
183 -> Lrc<ty::GenericPredicates<'tcx>> {
186 .type_param_predicates((self.item_def_id, def_id))
192 _def: Option<&ty::GenericParamDef>,
193 ) -> Option<ty::Region<'tcx>> {
197 fn ty_infer(&self, span: Span) -> Ty<'tcx> {
202 "the type placeholder `_` is not allowed within types on item signatures"
203 ).span_label(span, "not allowed in type signatures")
209 fn projected_ty_from_poly_trait_ref(
213 poly_trait_ref: ty::PolyTraitRef<'tcx>,
215 if let Some(trait_ref) = poly_trait_ref.no_bound_vars() {
216 self.tcx().mk_projection(item_def_id, trait_ref.substs)
218 // no late-bound regions, we can just ignore the binder
223 "cannot extract an associated type from a higher-ranked trait bound \
230 fn normalize_ty(&self, _span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
231 // types in item signatures are not normalized, to avoid undue
236 fn set_tainted_by_errors(&self) {
237 // no obvious place to track this, just let it go
240 fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) {
241 // no place to record types from signatures?
245 fn type_param_predicates<'a, 'tcx>(
246 tcx: TyCtxt<'a, 'tcx, 'tcx>,
247 (item_def_id, def_id): (DefId, DefId),
248 ) -> Lrc<ty::GenericPredicates<'tcx>> {
251 // In the AST, bounds can derive from two places. Either
252 // written inline like `<T : Foo>` or in a where clause like
255 let param_id = tcx.hir().as_local_node_id(def_id).unwrap();
256 let param_owner = tcx.hir().ty_param_owner(param_id);
257 let param_owner_def_id = tcx.hir().local_def_id(param_owner);
258 let generics = tcx.generics_of(param_owner_def_id);
259 let index = generics.param_def_id_to_index[&def_id];
260 let ty = tcx.mk_ty_param(index, tcx.hir().ty_param_name(param_id).as_interned_str());
262 // Don't look for bounds where the type parameter isn't in scope.
263 let parent = if item_def_id == param_owner_def_id {
266 tcx.generics_of(item_def_id).parent
269 let mut result = parent.map_or_else(
270 || Lrc::new(ty::GenericPredicates {
275 let icx = ItemCtxt::new(tcx, parent);
276 icx.get_type_parameter_bounds(DUMMY_SP, def_id)
280 let item_node_id = tcx.hir().as_local_node_id(item_def_id).unwrap();
281 let ast_generics = match tcx.hir().get(item_node_id) {
282 Node::TraitItem(item) => &item.generics,
284 Node::ImplItem(item) => &item.generics,
286 Node::Item(item) => {
288 ItemKind::Fn(.., ref generics, _)
289 | ItemKind::Impl(_, _, _, ref generics, ..)
290 | ItemKind::Ty(_, ref generics)
291 | ItemKind::Existential(ExistTy {
296 | ItemKind::Enum(_, ref generics)
297 | ItemKind::Struct(_, ref generics)
298 | ItemKind::Union(_, ref generics) => generics,
299 ItemKind::Trait(_, _, ref generics, ..) => {
300 // Implied `Self: Trait` and supertrait bounds.
301 if param_id == item_node_id {
302 let identity_trait_ref = ty::TraitRef::identity(tcx, item_def_id);
303 Lrc::make_mut(&mut result)
305 .push((identity_trait_ref.to_predicate(), item.span));
313 Node::ForeignItem(item) => match item.node {
314 ForeignItemKind::Fn(_, _, ref generics) => generics,
321 let icx = ItemCtxt::new(tcx, item_def_id);
322 Lrc::make_mut(&mut result)
324 .extend(icx.type_parameter_bounds_in_generics(ast_generics, param_id, ty,
325 OnlySelfBounds(true)));
329 impl<'a, 'tcx> ItemCtxt<'a, 'tcx> {
330 /// Find bounds from `hir::Generics`. This requires scanning through the
331 /// AST. We do this to avoid having to convert *all* the bounds, which
332 /// would create artificial cycles. Instead we can only convert the
333 /// bounds for a type parameter `X` if `X::Foo` is used.
334 fn type_parameter_bounds_in_generics(
336 ast_generics: &hir::Generics,
337 param_id: ast::NodeId,
339 only_self_bounds: OnlySelfBounds,
340 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
341 let from_ty_params = ast_generics
344 .filter_map(|param| match param.kind {
345 GenericParamKind::Type { .. } if param.id == param_id => Some(¶m.bounds),
348 .flat_map(|bounds| bounds.iter())
349 .flat_map(|b| predicates_from_bound(self, ty, b));
351 let from_where_clauses = ast_generics
355 .filter_map(|wp| match *wp {
356 hir::WherePredicate::BoundPredicate(ref bp) => Some(bp),
360 let bt = if is_param(self.tcx, &bp.bounded_ty, param_id) {
362 } else if !only_self_bounds.0 {
363 Some(self.to_ty(&bp.bounded_ty))
367 bp.bounds.iter().filter_map(move |b| bt.map(|bt| (bt, b)))
369 .flat_map(|(bt, b)| predicates_from_bound(self, bt, b));
371 from_ty_params.chain(from_where_clauses).collect()
375 /// Tests whether this is the AST for a reference to the type
376 /// parameter with id `param_id`. We use this so as to avoid running
377 /// `ast_ty_to_ty`, because we want to avoid triggering an all-out
378 /// conversion of the type to avoid inducing unnecessary cycles.
379 fn is_param<'a, 'tcx>(
380 tcx: TyCtxt<'a, 'tcx, 'tcx>,
382 param_id: ast::NodeId,
384 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = ast_ty.node {
386 Def::SelfTy(Some(def_id), None) | Def::TyParam(def_id) => {
387 def_id == tcx.hir().local_def_id(param_id)
396 fn convert_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item_id: ast::NodeId) {
397 let it = tcx.hir().expect_item(item_id);
398 debug!("convert: item {} with id {}", it.name, it.id);
399 let def_id = tcx.hir().local_def_id(item_id);
401 // These don't define types.
402 hir::ItemKind::ExternCrate(_)
403 | hir::ItemKind::Use(..)
404 | hir::ItemKind::Mod(_)
405 | hir::ItemKind::GlobalAsm(_) => {}
406 hir::ItemKind::ForeignMod(ref foreign_mod) => {
407 for item in &foreign_mod.items {
408 let def_id = tcx.hir().local_def_id(item.id);
409 tcx.generics_of(def_id);
411 tcx.predicates_of(def_id);
412 if let hir::ForeignItemKind::Fn(..) = item.node {
417 hir::ItemKind::Enum(ref enum_definition, _) => {
418 tcx.generics_of(def_id);
420 tcx.predicates_of(def_id);
421 convert_enum_variant_types(tcx, def_id, &enum_definition.variants);
423 hir::ItemKind::Impl(..) => {
424 tcx.generics_of(def_id);
426 tcx.impl_trait_ref(def_id);
427 tcx.predicates_of(def_id);
429 hir::ItemKind::Trait(..) => {
430 tcx.generics_of(def_id);
431 tcx.trait_def(def_id);
432 tcx.at(it.span).super_predicates_of(def_id);
433 tcx.predicates_of(def_id);
435 hir::ItemKind::TraitAlias(..) => {
436 tcx.generics_of(def_id);
437 tcx.at(it.span).super_predicates_of(def_id);
438 tcx.predicates_of(def_id);
440 hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
441 tcx.generics_of(def_id);
443 tcx.predicates_of(def_id);
445 for f in struct_def.fields() {
446 let def_id = tcx.hir().local_def_id(f.id);
447 tcx.generics_of(def_id);
449 tcx.predicates_of(def_id);
452 if !struct_def.is_struct() {
453 convert_variant_ctor(tcx, struct_def.id());
457 // Desugared from `impl Trait` -> visited by the function's return type
458 hir::ItemKind::Existential(hir::ExistTy {
459 impl_trait_fn: Some(_),
463 hir::ItemKind::Existential(..)
464 | hir::ItemKind::Ty(..)
465 | hir::ItemKind::Static(..)
466 | hir::ItemKind::Const(..)
467 | hir::ItemKind::Fn(..) => {
468 tcx.generics_of(def_id);
470 tcx.predicates_of(def_id);
471 if let hir::ItemKind::Fn(..) = it.node {
478 fn convert_trait_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, trait_item_id: ast::NodeId) {
479 let trait_item = tcx.hir().expect_trait_item(trait_item_id);
480 let def_id = tcx.hir().local_def_id(trait_item.id);
481 tcx.generics_of(def_id);
483 match trait_item.node {
484 hir::TraitItemKind::Const(..)
485 | hir::TraitItemKind::Type(_, Some(_))
486 | hir::TraitItemKind::Method(..) => {
488 if let hir::TraitItemKind::Method(..) = trait_item.node {
493 hir::TraitItemKind::Type(_, None) => {}
496 tcx.predicates_of(def_id);
499 fn convert_impl_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, impl_item_id: ast::NodeId) {
500 let def_id = tcx.hir().local_def_id(impl_item_id);
501 tcx.generics_of(def_id);
503 tcx.predicates_of(def_id);
504 if let hir::ImplItemKind::Method(..) = tcx.hir().expect_impl_item(impl_item_id).node {
509 fn convert_variant_ctor<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ctor_id: ast::NodeId) {
510 let def_id = tcx.hir().local_def_id(ctor_id);
511 tcx.generics_of(def_id);
513 tcx.predicates_of(def_id);
516 fn convert_enum_variant_types<'a, 'tcx>(
517 tcx: TyCtxt<'a, 'tcx, 'tcx>,
519 variants: &[hir::Variant],
521 let def = tcx.adt_def(def_id);
522 let repr_type = def.repr.discr_type();
523 let initial = repr_type.initial_discriminant(tcx);
524 let mut prev_discr = None::<Discr<'tcx>>;
526 // fill the discriminant values and field types
527 for variant in variants {
528 let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
530 if let Some(ref e) = variant.node.disr_expr {
531 let expr_did = tcx.hir().local_def_id(e.id);
532 def.eval_explicit_discr(tcx, expr_did)
533 } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) {
540 "enum discriminant overflowed"
543 format!("overflowed on value after {}", prev_discr.unwrap()),
545 "explicitly set `{} = {}` if that is desired outcome",
546 variant.node.name, wrapped_discr
550 }.unwrap_or(wrapped_discr),
553 for f in variant.node.data.fields() {
554 let def_id = tcx.hir().local_def_id(f.id);
555 tcx.generics_of(def_id);
557 tcx.predicates_of(def_id);
560 // Convert the ctor, if any. This also registers the variant as
562 convert_variant_ctor(tcx, variant.node.data.id());
566 fn convert_variant<'a, 'tcx>(
567 tcx: TyCtxt<'a, 'tcx, 'tcx>,
570 discr: ty::VariantDiscr,
571 def: &hir::VariantData,
572 adt_kind: ty::AdtKind,
573 attribute_def_id: DefId
574 ) -> ty::VariantDef {
575 let mut seen_fields: FxHashMap<ast::Ident, Span> = Default::default();
576 let node_id = tcx.hir().as_local_node_id(did).unwrap();
581 let fid = tcx.hir().local_def_id(f.id);
582 let dup_span = seen_fields.get(&f.ident.modern()).cloned();
583 if let Some(prev_span) = dup_span {
588 "field `{}` is already declared",
590 ).span_label(f.span, "field already declared")
591 .span_label(prev_span, format!("`{}` first declared here", f.ident))
594 seen_fields.insert(f.ident.modern(), f.span);
600 vis: ty::Visibility::from_hir(&f.vis, node_id, tcx),
604 ty::VariantDef::new(tcx,
610 CtorKind::from_hir(def),
614 fn adt_def<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx ty::AdtDef {
617 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
618 let item = match tcx.hir().get(node_id) {
619 Node::Item(item) => item,
623 let repr = ReprOptions::new(tcx, def_id);
624 let (kind, variants) = match item.node {
625 ItemKind::Enum(ref def, _) => {
626 let mut distance_from_explicit = 0;
632 let did = tcx.hir().local_def_id(v.node.data.id());
633 let discr = if let Some(ref e) = v.node.disr_expr {
634 distance_from_explicit = 0;
635 ty::VariantDiscr::Explicit(tcx.hir().local_def_id(e.id))
637 ty::VariantDiscr::Relative(distance_from_explicit)
639 distance_from_explicit += 1;
641 convert_variant(tcx, did, v.node.name, discr, &v.node.data, AdtKind::Enum,
647 ItemKind::Struct(ref def, _) => {
648 // Use separate constructor id for unit/tuple structs and reuse did for braced structs.
649 let ctor_id = if !def.is_struct() {
650 Some(tcx.hir().local_def_id(def.id()))
656 std::iter::once(convert_variant(
658 ctor_id.unwrap_or(def_id),
660 ty::VariantDiscr::Relative(0),
667 ItemKind::Union(ref def, _) => (
669 std::iter::once(convert_variant(
673 ty::VariantDiscr::Relative(0),
681 tcx.alloc_adt_def(def_id, kind, variants, repr)
684 /// Ensures that the super-predicates of the trait with def-id
685 /// trait_def_id are converted and stored. This also ensures that
686 /// the transitive super-predicates are converted;
687 fn super_predicates_of<'a, 'tcx>(
688 tcx: TyCtxt<'a, 'tcx, 'tcx>,
690 ) -> Lrc<ty::GenericPredicates<'tcx>> {
691 debug!("super_predicates(trait_def_id={:?})", trait_def_id);
692 let trait_node_id = tcx.hir().as_local_node_id(trait_def_id).unwrap();
694 let item = match tcx.hir().get(trait_node_id) {
695 Node::Item(item) => item,
696 _ => bug!("trait_node_id {} is not an item", trait_node_id),
699 let (generics, bounds) = match item.node {
700 hir::ItemKind::Trait(.., ref generics, ref supertraits, _) => (generics, supertraits),
701 hir::ItemKind::TraitAlias(ref generics, ref supertraits) => (generics, supertraits),
702 _ => span_bug!(item.span, "super_predicates invoked on non-trait"),
705 let icx = ItemCtxt::new(tcx, trait_def_id);
707 // Convert the bounds that follow the colon, e.g. `Bar + Zed` in `trait Foo : Bar + Zed`.
708 let self_param_ty = tcx.mk_self_type();
709 let superbounds1 = compute_bounds(&icx, self_param_ty, bounds, SizedByDefault::No, item.span);
711 let superbounds1 = superbounds1.predicates(tcx, self_param_ty);
713 // Convert any explicit superbounds in the where clause,
714 // e.g. `trait Foo where Self : Bar`.
715 // In the case of trait aliases, however, we include all bounds in the where clause,
716 // so e.g. `trait Foo = where u32: PartialEq<Self>` would include `u32: PartialEq<Self>`
717 // as one of its "superpredicates".
718 let is_trait_alias = ty::is_trait_alias(tcx, trait_def_id);
719 let superbounds2 = icx.type_parameter_bounds_in_generics(
720 generics, item.id, self_param_ty, OnlySelfBounds(!is_trait_alias));
722 // Combine the two lists to form the complete set of superbounds:
723 let superbounds: Vec<_> = superbounds1.into_iter().chain(superbounds2).collect();
725 // Now require that immediate supertraits are converted,
726 // which will, in turn, reach indirect supertraits.
727 for &(pred, span) in &superbounds {
728 debug!("superbound: {:?}", pred);
729 if let ty::Predicate::Trait(bound) = pred {
730 tcx.at(span).super_predicates_of(bound.def_id());
734 Lrc::new(ty::GenericPredicates {
736 predicates: superbounds,
740 fn trait_def<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx ty::TraitDef {
741 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
742 let item = tcx.hir().expect_item(node_id);
744 let (is_auto, unsafety) = match item.node {
745 hir::ItemKind::Trait(is_auto, unsafety, ..) => (is_auto == hir::IsAuto::Yes, unsafety),
746 hir::ItemKind::TraitAlias(..) => (false, hir::Unsafety::Normal),
747 _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
750 let paren_sugar = tcx.has_attr(def_id, "rustc_paren_sugar");
751 if paren_sugar && !tcx.features().unboxed_closures {
752 let mut err = tcx.sess.struct_span_err(
754 "the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \
755 which traits can use parenthetical notation",
759 "add `#![feature(unboxed_closures)]` to \
760 the crate attributes to use it"
765 let is_marker = tcx.has_attr(def_id, "marker");
766 let def_path_hash = tcx.def_path_hash(def_id);
767 let def = ty::TraitDef::new(def_id, unsafety, paren_sugar, is_auto, is_marker, def_path_hash);
768 tcx.alloc_trait_def(def)
771 fn has_late_bound_regions<'a, 'tcx>(
772 tcx: TyCtxt<'a, 'tcx, 'tcx>,
775 struct LateBoundRegionsDetector<'a, 'tcx: 'a> {
776 tcx: TyCtxt<'a, 'tcx, 'tcx>,
777 outer_index: ty::DebruijnIndex,
778 has_late_bound_regions: Option<Span>,
781 impl<'a, 'tcx> Visitor<'tcx> for LateBoundRegionsDetector<'a, 'tcx> {
782 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
783 NestedVisitorMap::None
786 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
787 if self.has_late_bound_regions.is_some() {
791 hir::TyKind::BareFn(..) => {
792 self.outer_index.shift_in(1);
793 intravisit::walk_ty(self, ty);
794 self.outer_index.shift_out(1);
796 _ => intravisit::walk_ty(self, ty),
800 fn visit_poly_trait_ref(
802 tr: &'tcx hir::PolyTraitRef,
803 m: hir::TraitBoundModifier,
805 if self.has_late_bound_regions.is_some() {
808 self.outer_index.shift_in(1);
809 intravisit::walk_poly_trait_ref(self, tr, m);
810 self.outer_index.shift_out(1);
813 fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
814 if self.has_late_bound_regions.is_some() {
818 let hir_id = self.tcx.hir().node_to_hir_id(lt.id);
819 match self.tcx.named_region(hir_id) {
820 Some(rl::Region::Static) | Some(rl::Region::EarlyBound(..)) => {}
821 Some(rl::Region::LateBound(debruijn, _, _))
822 | Some(rl::Region::LateBoundAnon(debruijn, _)) if debruijn < self.outer_index => {}
823 Some(rl::Region::LateBound(..))
824 | Some(rl::Region::LateBoundAnon(..))
825 | Some(rl::Region::Free(..))
827 self.has_late_bound_regions = Some(lt.span);
833 fn has_late_bound_regions<'a, 'tcx>(
834 tcx: TyCtxt<'a, 'tcx, 'tcx>,
835 generics: &'tcx hir::Generics,
836 decl: &'tcx hir::FnDecl,
838 let mut visitor = LateBoundRegionsDetector {
840 outer_index: ty::INNERMOST,
841 has_late_bound_regions: None,
843 for param in &generics.params {
844 if let GenericParamKind::Lifetime { .. } = param.kind {
845 let hir_id = tcx.hir().node_to_hir_id(param.id);
846 if tcx.is_late_bound(hir_id) {
847 return Some(param.span);
851 visitor.visit_fn_decl(decl);
852 visitor.has_late_bound_regions
856 Node::TraitItem(item) => match item.node {
857 hir::TraitItemKind::Method(ref sig, _) => {
858 has_late_bound_regions(tcx, &item.generics, &sig.decl)
862 Node::ImplItem(item) => match item.node {
863 hir::ImplItemKind::Method(ref sig, _) => {
864 has_late_bound_regions(tcx, &item.generics, &sig.decl)
868 Node::ForeignItem(item) => match item.node {
869 hir::ForeignItemKind::Fn(ref fn_decl, _, ref generics) => {
870 has_late_bound_regions(tcx, generics, fn_decl)
874 Node::Item(item) => match item.node {
875 hir::ItemKind::Fn(ref fn_decl, .., ref generics, _) => {
876 has_late_bound_regions(tcx, generics, fn_decl)
884 fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx ty::Generics {
887 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
889 let node = tcx.hir().get(node_id);
890 let parent_def_id = match node {
891 Node::ImplItem(_) | Node::TraitItem(_) | Node::Variant(_)
892 | Node::StructCtor(_) | Node::Field(_) => {
893 let parent_id = tcx.hir().get_parent(node_id);
894 Some(tcx.hir().local_def_id(parent_id))
896 Node::Expr(&hir::Expr {
897 node: hir::ExprKind::Closure(..),
899 }) => Some(tcx.closure_base_def_id(def_id)),
900 Node::Item(item) => match item.node {
901 ItemKind::Existential(hir::ExistTy { impl_trait_fn, .. }) => impl_trait_fn,
907 let mut opt_self = None;
908 let mut allow_defaults = false;
910 let no_generics = hir::Generics::empty();
911 let ast_generics = match node {
912 Node::TraitItem(item) => &item.generics,
914 Node::ImplItem(item) => &item.generics,
916 Node::Item(item) => {
918 ItemKind::Fn(.., ref generics, _) | ItemKind::Impl(_, _, _, ref generics, ..) => {
922 ItemKind::Ty(_, ref generics)
923 | ItemKind::Enum(_, ref generics)
924 | ItemKind::Struct(_, ref generics)
925 | ItemKind::Existential(hir::ExistTy { ref generics, .. })
926 | ItemKind::Union(_, ref generics) => {
927 allow_defaults = true;
931 ItemKind::Trait(_, _, ref generics, ..)
932 | ItemKind::TraitAlias(ref generics, ..) => {
933 // Add in the self type parameter.
935 // Something of a hack: use the node id for the trait, also as
936 // the node id for the Self type parameter.
937 let param_id = item.id;
939 opt_self = Some(ty::GenericParamDef {
941 name: keywords::SelfUpper.name().as_interned_str(),
942 def_id: tcx.hir().local_def_id(param_id),
943 pure_wrt_drop: false,
944 kind: ty::GenericParamDefKind::Type {
946 object_lifetime_default: rl::Set1::Empty,
951 allow_defaults = true;
959 Node::ForeignItem(item) => match item.node {
960 ForeignItemKind::Static(..) => &no_generics,
961 ForeignItemKind::Fn(_, _, ref generics) => generics,
962 ForeignItemKind::Type => &no_generics,
968 let has_self = opt_self.is_some();
969 let mut parent_has_self = false;
970 let mut own_start = has_self as u32;
971 let parent_count = parent_def_id.map_or(0, |def_id| {
972 let generics = tcx.generics_of(def_id);
973 assert_eq!(has_self, false);
974 parent_has_self = generics.has_self;
975 own_start = generics.count() as u32;
976 generics.parent_count + generics.params.len()
979 let mut params: Vec<_> = opt_self.into_iter().collect();
981 let early_lifetimes = early_bound_lifetimes_from_generics(tcx, ast_generics);
985 .map(|(i, param)| ty::GenericParamDef {
986 name: param.name.ident().as_interned_str(),
987 index: own_start + i as u32,
988 def_id: tcx.hir().local_def_id(param.id),
989 pure_wrt_drop: param.pure_wrt_drop,
990 kind: ty::GenericParamDefKind::Lifetime,
994 let hir_id = tcx.hir().node_to_hir_id(node_id);
995 let object_lifetime_defaults = tcx.object_lifetime_defaults(hir_id);
997 // Now create the real type parameters.
998 let type_start = own_start - has_self as u32 + params.len() as u32;
1004 .filter_map(|param| match param.kind {
1005 GenericParamKind::Type {
1010 if param.name.ident().name == keywords::SelfUpper.name() {
1013 "`Self` should not be the name of a regular parameter"
1017 if !allow_defaults && default.is_some() {
1018 if !tcx.features().default_type_parameter_fallback {
1020 lint::builtin::INVALID_TYPE_PARAM_DEFAULT,
1024 "defaults for type parameters are only allowed in \
1025 `struct`, `enum`, `type`, or `trait` definitions."
1031 let ty_param = ty::GenericParamDef {
1032 index: type_start + i as u32,
1033 name: param.name.ident().as_interned_str(),
1034 def_id: tcx.hir().local_def_id(param.id),
1035 pure_wrt_drop: param.pure_wrt_drop,
1036 kind: ty::GenericParamDefKind::Type {
1037 has_default: default.is_some(),
1038 object_lifetime_default: object_lifetime_defaults
1040 .map_or(rl::Set1::Empty, |o| o[i]),
1051 // provide junk type parameter defs - the only place that
1052 // cares about anything but the length is instantiation,
1053 // and we don't do that for closures.
1054 if let Node::Expr(&hir::Expr {
1055 node: hir::ExprKind::Closure(.., gen),
1059 let dummy_args = if gen.is_some() {
1060 &["<yield_ty>", "<return_ty>", "<witness>"][..]
1062 &["<closure_kind>", "<closure_signature>"][..]
1069 .map(|(i, &arg)| ty::GenericParamDef {
1070 index: type_start + i as u32,
1071 name: Symbol::intern(arg).as_interned_str(),
1073 pure_wrt_drop: false,
1074 kind: ty::GenericParamDefKind::Type {
1076 object_lifetime_default: rl::Set1::Empty,
1082 tcx.with_freevars(node_id, |fv| {
1083 params.extend(fv.iter().zip((dummy_args.len() as u32)..).map(|(_, i)| {
1084 ty::GenericParamDef {
1085 index: type_start + i,
1086 name: Symbol::intern("<upvar>").as_interned_str(),
1088 pure_wrt_drop: false,
1089 kind: ty::GenericParamDefKind::Type {
1091 object_lifetime_default: rl::Set1::Empty,
1099 let param_def_id_to_index = params
1101 .map(|param| (param.def_id, param.index))
1104 tcx.alloc_generics(ty::Generics {
1105 parent: parent_def_id,
1108 param_def_id_to_index,
1109 has_self: has_self || parent_has_self,
1110 has_late_bound_regions: has_late_bound_regions(tcx, node),
1114 fn report_assoc_ty_on_inherent_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, span: Span) {
1119 "associated types are not allowed in inherent impls"
1123 fn type_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Ty<'tcx> {
1126 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
1128 let icx = ItemCtxt::new(tcx, def_id);
1130 match tcx.hir().get(node_id) {
1131 Node::TraitItem(item) => match item.node {
1132 TraitItemKind::Method(..) => {
1133 let substs = Substs::identity_for_item(tcx, def_id);
1134 tcx.mk_fn_def(def_id, substs)
1136 TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => icx.to_ty(ty),
1137 TraitItemKind::Type(_, None) => {
1138 span_bug!(item.span, "associated type missing default");
1142 Node::ImplItem(item) => match item.node {
1143 ImplItemKind::Method(..) => {
1144 let substs = Substs::identity_for_item(tcx, def_id);
1145 tcx.mk_fn_def(def_id, substs)
1147 ImplItemKind::Const(ref ty, _) => icx.to_ty(ty),
1148 ImplItemKind::Existential(_) => {
1150 .impl_trait_ref(tcx.hir().get_parent_did(node_id))
1153 report_assoc_ty_on_inherent_impl(tcx, item.span);
1156 find_existential_constraints(tcx, def_id)
1158 ImplItemKind::Type(ref ty) => {
1160 .impl_trait_ref(tcx.hir().get_parent_did(node_id))
1163 report_assoc_ty_on_inherent_impl(tcx, item.span);
1170 Node::Item(item) => {
1172 ItemKind::Static(ref t, ..)
1173 | ItemKind::Const(ref t, _)
1174 | ItemKind::Ty(ref t, _)
1175 | ItemKind::Impl(.., ref t, _) => icx.to_ty(t),
1176 ItemKind::Fn(..) => {
1177 let substs = Substs::identity_for_item(tcx, def_id);
1178 tcx.mk_fn_def(def_id, substs)
1180 ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
1181 let def = tcx.adt_def(def_id);
1182 let substs = Substs::identity_for_item(tcx, def_id);
1183 tcx.mk_adt(def, substs)
1185 ItemKind::Existential(hir::ExistTy {
1186 impl_trait_fn: None,
1188 }) => find_existential_constraints(tcx, def_id),
1189 // existential types desugared from impl Trait
1190 ItemKind::Existential(hir::ExistTy {
1191 impl_trait_fn: Some(owner),
1194 tcx.typeck_tables_of(owner)
1195 .concrete_existential_types
1198 .unwrap_or_else(|| {
1199 // This can occur if some error in the
1200 // owner fn prevented us from populating
1201 // the `concrete_existential_types` table.
1202 tcx.sess.delay_span_bug(
1205 "owner {:?} has no existential type for {:?} in its tables",
1213 | ItemKind::TraitAlias(..)
1215 | ItemKind::ForeignMod(..)
1216 | ItemKind::GlobalAsm(..)
1217 | ItemKind::ExternCrate(..)
1218 | ItemKind::Use(..) => {
1221 "compute_type_of_item: unexpected item type: {:?}",
1228 Node::ForeignItem(foreign_item) => match foreign_item.node {
1229 ForeignItemKind::Fn(..) => {
1230 let substs = Substs::identity_for_item(tcx, def_id);
1231 tcx.mk_fn_def(def_id, substs)
1233 ForeignItemKind::Static(ref t, _) => icx.to_ty(t),
1234 ForeignItemKind::Type => tcx.mk_foreign(def_id),
1237 Node::StructCtor(&ref def)
1238 | Node::Variant(&Spanned {
1239 node: hir::VariantKind { data: ref def, .. },
1242 VariantData::Unit(..) | VariantData::Struct(..) => {
1243 tcx.type_of(tcx.hir().get_parent_did(node_id))
1245 VariantData::Tuple(..) => {
1246 let substs = Substs::identity_for_item(tcx, def_id);
1247 tcx.mk_fn_def(def_id, substs)
1251 Node::Field(field) => icx.to_ty(&field.ty),
1253 Node::Expr(&hir::Expr {
1254 node: hir::ExprKind::Closure(.., gen),
1258 let hir_id = tcx.hir().node_to_hir_id(node_id);
1259 return tcx.typeck_tables_of(def_id).node_id_to_type(hir_id);
1262 let substs = ty::ClosureSubsts {
1263 substs: Substs::identity_for_item(tcx, def_id),
1266 tcx.mk_closure(def_id, substs)
1269 Node::AnonConst(_) => match tcx.hir().get(tcx.hir().get_parent_node(node_id)) {
1271 node: hir::TyKind::Array(_, ref constant),
1274 | Node::Ty(&hir::Ty {
1275 node: hir::TyKind::Typeof(ref constant),
1278 | Node::Expr(&hir::Expr {
1279 node: ExprKind::Repeat(_, ref constant),
1281 }) if constant.id == node_id =>
1286 Node::Variant(&Spanned {
1289 disr_expr: Some(ref e),
1293 }) if e.id == node_id =>
1295 tcx.adt_def(tcx.hir().get_parent_did(node_id))
1302 bug!("unexpected const parent in type_of_def_id(): {:?}", x);
1306 Node::GenericParam(param) => match param.kind {
1307 hir::GenericParamKind::Type {
1308 default: Some(ref ty),
1311 _ => bug!("unexpected non-type NodeGenericParam"),
1315 bug!("unexpected sort of node in type_of_def_id(): {:?}", x);
1320 fn find_existential_constraints<'a, 'tcx>(
1321 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1326 struct ConstraintLocator<'a, 'tcx: 'a> {
1327 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1329 found: Option<(Span, ty::Ty<'tcx>)>,
1332 impl<'a, 'tcx> ConstraintLocator<'a, 'tcx> {
1333 fn check(&mut self, def_id: DefId) {
1334 trace!("checking {:?}", def_id);
1335 // don't try to check items that cannot possibly constrain the type
1336 if !self.tcx.has_typeck_tables(def_id) {
1337 trace!("no typeck tables for {:?}", def_id);
1342 .typeck_tables_of(def_id)
1343 .concrete_existential_types
1346 if let Some(ty) = ty {
1347 // FIXME(oli-obk): trace the actual span from inference to improve errors
1348 let span = self.tcx.def_span(def_id);
1349 if let Some((prev_span, prev_ty)) = self.found {
1351 // found different concrete types for the existential type
1352 let mut err = self.tcx.sess.struct_span_err(
1354 "defining existential type use differs from previous",
1356 err.span_note(prev_span, "previous use here");
1360 self.found = Some((span, ty));
1366 impl<'a, 'tcx> intravisit::Visitor<'tcx> for ConstraintLocator<'a, 'tcx> {
1367 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
1368 intravisit::NestedVisitorMap::All(&self.tcx.hir())
1370 fn visit_item(&mut self, it: &'tcx Item) {
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_item(self, it);
1378 fn visit_impl_item(&mut self, it: &'tcx ImplItem) {
1379 let def_id = self.tcx.hir().local_def_id(it.id);
1380 // the existential type itself or its children are not within its reveal scope
1381 if def_id != self.def_id {
1383 intravisit::walk_impl_item(self, it);
1386 fn visit_trait_item(&mut self, it: &'tcx TraitItem) {
1387 let def_id = self.tcx.hir().local_def_id(it.id);
1389 intravisit::walk_trait_item(self, it);
1393 let mut locator = ConstraintLocator {
1398 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
1399 let parent = tcx.hir().get_parent(node_id);
1401 trace!("parent_id: {:?}", parent);
1403 if parent == ast::CRATE_NODE_ID {
1404 intravisit::walk_crate(&mut locator, tcx.hir().krate());
1406 trace!("parent: {:?}", tcx.hir().get(parent));
1407 match tcx.hir().get(parent) {
1408 Node::Item(ref it) => intravisit::walk_item(&mut locator, it),
1409 Node::ImplItem(ref it) => intravisit::walk_impl_item(&mut locator, it),
1410 Node::TraitItem(ref it) => intravisit::walk_trait_item(&mut locator, it),
1412 "{:?} is not a valid parent of an existential type item",
1418 match locator.found {
1419 Some((_, ty)) => ty,
1421 let span = tcx.def_span(def_id);
1422 tcx.sess.span_err(span, "could not find defining uses");
1428 fn fn_sig<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> ty::PolyFnSig<'tcx> {
1430 use rustc::hir::Node::*;
1432 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
1434 let icx = ItemCtxt::new(tcx, def_id);
1436 match tcx.hir().get(node_id) {
1437 TraitItem(hir::TraitItem {
1438 node: TraitItemKind::Method(sig, _),
1441 | ImplItem(hir::ImplItem {
1442 node: ImplItemKind::Method(sig, _),
1444 }) => AstConv::ty_of_fn(&icx, sig.header.unsafety, sig.header.abi, &sig.decl),
1447 node: ItemKind::Fn(decl, header, _, _),
1449 }) => AstConv::ty_of_fn(&icx, header.unsafety, header.abi, decl),
1451 ForeignItem(&hir::ForeignItem {
1452 node: ForeignItemKind::Fn(ref fn_decl, _, _),
1455 let abi = tcx.hir().get_foreign_abi(node_id);
1456 compute_sig_of_foreign_fn_decl(tcx, def_id, fn_decl, abi)
1459 StructCtor(&VariantData::Tuple(ref fields, _))
1460 | Variant(&Spanned {
1463 data: VariantData::Tuple(ref fields, _),
1468 let ty = tcx.type_of(tcx.hir().get_parent_did(node_id));
1471 .map(|f| tcx.type_of(tcx.hir().local_def_id(f.id)));
1472 ty::Binder::bind(tcx.mk_fn_sig(
1476 hir::Unsafety::Normal,
1482 node: hir::ExprKind::Closure(..),
1485 // Closure signatures are not like other function
1486 // signatures and cannot be accessed through `fn_sig`. For
1487 // example, a closure signature excludes the `self`
1488 // argument. In any case they are embedded within the
1489 // closure type as part of the `ClosureSubsts`.
1492 // the signature of a closure, you should use the
1493 // `closure_sig` method on the `ClosureSubsts`:
1495 // closure_substs.closure_sig(def_id, tcx)
1497 // or, inside of an inference context, you can use
1499 // infcx.closure_sig(def_id, closure_substs)
1500 bug!("to get the signature of a closure, use `closure_sig()` not `fn_sig()`");
1504 bug!("unexpected sort of node in fn_sig(): {:?}", x);
1509 fn impl_trait_ref<'a, 'tcx>(
1510 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1512 ) -> Option<ty::TraitRef<'tcx>> {
1513 let icx = ItemCtxt::new(tcx, def_id);
1515 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
1516 match tcx.hir().expect_item(node_id).node {
1517 hir::ItemKind::Impl(.., ref opt_trait_ref, _, _) => {
1518 opt_trait_ref.as_ref().map(|ast_trait_ref| {
1519 let selfty = tcx.type_of(def_id);
1520 AstConv::instantiate_mono_trait_ref(&icx, ast_trait_ref, selfty)
1527 fn impl_polarity<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> hir::ImplPolarity {
1528 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
1529 match tcx.hir().expect_item(node_id).node {
1530 hir::ItemKind::Impl(_, polarity, ..) => polarity,
1531 ref item => bug!("impl_polarity: {:?} not an impl", item),
1535 // Is it marked with ?Sized
1536 fn is_unsized<'gcx: 'tcx, 'tcx>(
1537 astconv: &dyn AstConv<'gcx, 'tcx>,
1538 ast_bounds: &[hir::GenericBound],
1541 let tcx = astconv.tcx();
1543 // Try to find an unbound in bounds.
1544 let mut unbound = None;
1545 for ab in ast_bounds {
1546 if let &hir::GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = ab {
1547 if unbound.is_none() {
1548 unbound = Some(ptr.trait_ref.clone());
1554 "type parameter has more than one relaxed default \
1555 bound, only one is supported"
1561 let kind_id = tcx.lang_items().require(SizedTraitLangItem);
1564 // FIXME(#8559) currently requires the unbound to be built-in.
1565 if let Ok(kind_id) = kind_id {
1566 if tpb.path.def != Def::Trait(kind_id) {
1569 "default bound relaxed for a type parameter, but \
1570 this does nothing because the given bound is not \
1571 a default. Only `?Sized` is supported",
1576 _ if kind_id.is_ok() => {
1579 // No lang item for Sized, so we can't add it as a bound.
1586 /// Returns the early-bound lifetimes declared in this generics
1587 /// listing. For anything other than fns/methods, this is just all
1588 /// the lifetimes that are declared. For fns or methods, we have to
1589 /// screen out those that do not appear in any where-clauses etc using
1590 /// `resolve_lifetime::early_bound_lifetimes`.
1591 fn early_bound_lifetimes_from_generics<'a, 'tcx>(
1592 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1593 generics: &'a hir::Generics,
1594 ) -> impl Iterator<Item = &'a hir::GenericParam> + Captures<'tcx> {
1598 .filter(move |param| match param.kind {
1599 GenericParamKind::Lifetime { .. } => {
1600 let hir_id = tcx.hir().node_to_hir_id(param.id);
1601 !tcx.is_late_bound(hir_id)
1607 fn predicates_defined_on<'a, 'tcx>(
1608 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1610 ) -> Lrc<ty::GenericPredicates<'tcx>> {
1611 debug!("predicates_defined_on({:?})", def_id);
1612 let mut result = tcx.explicit_predicates_of(def_id);
1614 "predicates_defined_on: explicit_predicates_of({:?}) = {:?}",
1618 let inferred_outlives = tcx.inferred_outlives_of(def_id);
1619 if !inferred_outlives.is_empty() {
1620 let span = tcx.def_span(def_id);
1622 "predicates_defined_on: inferred_outlives_of({:?}) = {:?}",
1626 Lrc::make_mut(&mut result)
1628 .extend(inferred_outlives.iter().map(|&p| (p, span)));
1633 fn predicates_of<'a, 'tcx>(
1634 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1636 ) -> Lrc<ty::GenericPredicates<'tcx>> {
1637 let mut result = tcx.predicates_defined_on(def_id);
1639 if tcx.is_trait(def_id) {
1640 // For traits, add `Self: Trait` predicate. This is
1641 // not part of the predicates that a user writes, but it
1642 // is something that one must prove in order to invoke a
1643 // method or project an associated type.
1645 // In the chalk setup, this predicate is not part of the
1646 // "predicates" for a trait item. But it is useful in
1647 // rustc because if you directly (e.g.) invoke a trait
1648 // method like `Trait::method(...)`, you must naturally
1649 // prove that the trait applies to the types that were
1650 // used, and adding the predicate into this list ensures
1651 // that this is done.
1652 let span = tcx.def_span(def_id);
1653 Lrc::make_mut(&mut result)
1655 .push((ty::TraitRef::identity(tcx, def_id).to_predicate(), span));
1660 fn explicit_predicates_of<'a, 'tcx>(
1661 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1663 ) -> Lrc<ty::GenericPredicates<'tcx>> {
1665 use rustc_data_structures::fx::FxHashSet;
1667 debug!("explicit_predicates_of(def_id={:?})", def_id);
1669 /// A data structure with unique elements, which preserves order of insertion.
1670 /// Preserving the order of insertion is important here so as not to break
1671 /// compile-fail UI tests.
1672 struct UniquePredicates<'tcx> {
1673 predicates: Vec<(ty::Predicate<'tcx>, Span)>,
1674 uniques: FxHashSet<(ty::Predicate<'tcx>, Span)>,
1677 impl<'tcx> UniquePredicates<'tcx> {
1681 uniques: FxHashSet::default(),
1685 fn push(&mut self, value: (ty::Predicate<'tcx>, Span)) {
1686 if self.uniques.insert(value) {
1687 self.predicates.push(value);
1691 fn extend<I: IntoIterator<Item = (ty::Predicate<'tcx>, Span)>>(&mut self, iter: I) {
1698 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
1699 let node = tcx.hir().get(node_id);
1701 let mut is_trait = None;
1702 let mut is_default_impl_trait = None;
1704 let icx = ItemCtxt::new(tcx, def_id);
1705 let no_generics = hir::Generics::empty();
1706 let empty_trait_items = HirVec::new();
1708 let mut predicates = UniquePredicates::new();
1710 let ast_generics = match node {
1711 Node::TraitItem(item) => &item.generics,
1713 Node::ImplItem(item) => match item.node {
1714 ImplItemKind::Existential(ref bounds) => {
1715 let substs = Substs::identity_for_item(tcx, def_id);
1716 let opaque_ty = tcx.mk_opaque(def_id, substs);
1718 // Collect the bounds, i.e. the `A+B+'c` in `impl A+B+'c`.
1719 let bounds = compute_bounds(
1723 SizedByDefault::Yes,
1724 tcx.def_span(def_id),
1727 predicates.extend(bounds.predicates(tcx, opaque_ty));
1730 _ => &item.generics,
1733 Node::Item(item) => {
1735 ItemKind::Impl(_, _, defaultness, ref generics, ..) => {
1736 if defaultness.is_default() {
1737 is_default_impl_trait = tcx.impl_trait_ref(def_id);
1741 ItemKind::Fn(.., ref generics, _)
1742 | ItemKind::Ty(_, ref generics)
1743 | ItemKind::Enum(_, ref generics)
1744 | ItemKind::Struct(_, ref generics)
1745 | ItemKind::Union(_, ref generics) => generics,
1747 ItemKind::Trait(_, _, ref generics, .., ref items) => {
1748 is_trait = Some((ty::TraitRef::identity(tcx, def_id), items));
1751 ItemKind::TraitAlias(ref generics, _) => {
1752 is_trait = Some((ty::TraitRef::identity(tcx, def_id), &empty_trait_items));
1755 ItemKind::Existential(ExistTy {
1760 let substs = Substs::identity_for_item(tcx, def_id);
1761 let opaque_ty = tcx.mk_opaque(def_id, substs);
1763 // Collect the bounds, i.e. the `A+B+'c` in `impl A+B+'c`.
1764 let bounds = compute_bounds(
1768 SizedByDefault::Yes,
1769 tcx.def_span(def_id),
1772 if impl_trait_fn.is_some() {
1774 return Lrc::new(ty::GenericPredicates {
1776 predicates: bounds.predicates(tcx, opaque_ty),
1779 // named existential types
1780 predicates.extend(bounds.predicates(tcx, opaque_ty));
1789 Node::ForeignItem(item) => match item.node {
1790 ForeignItemKind::Static(..) => &no_generics,
1791 ForeignItemKind::Fn(_, _, ref generics) => generics,
1792 ForeignItemKind::Type => &no_generics,
1798 let generics = tcx.generics_of(def_id);
1799 let parent_count = generics.parent_count as u32;
1800 let has_own_self = generics.has_self && parent_count == 0;
1802 // Below we'll consider the bounds on the type parameters (including `Self`)
1803 // and the explicit where-clauses, but to get the full set of predicates
1804 // on a trait we need to add in the supertrait bounds and bounds found on
1805 // associated types.
1806 if let Some((_trait_ref, _)) = is_trait {
1807 predicates.extend(tcx.super_predicates_of(def_id).predicates.iter().cloned());
1810 // In default impls, we can assume that the self type implements
1811 // the trait. So in:
1813 // default impl Foo for Bar { .. }
1815 // we add a default where clause `Foo: Bar`. We do a similar thing for traits
1816 // (see below). Recall that a default impl is not itself an impl, but rather a
1817 // set of defaults that can be incorporated into another impl.
1818 if let Some(trait_ref) = is_default_impl_trait {
1819 predicates.push((trait_ref.to_poly_trait_ref().to_predicate(), tcx.def_span(def_id)));
1822 // Collect the region predicates that were declared inline as
1823 // well. In the case of parameters declared on a fn or method, we
1824 // have to be careful to only iterate over early-bound regions.
1825 let mut index = parent_count + has_own_self as u32;
1826 for param in early_bound_lifetimes_from_generics(tcx, ast_generics) {
1827 let region = tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
1828 def_id: tcx.hir().local_def_id(param.id),
1830 name: param.name.ident().as_interned_str(),
1835 GenericParamKind::Lifetime { .. } => {
1836 param.bounds.iter().for_each(|bound| match bound {
1837 hir::GenericBound::Outlives(lt) => {
1838 let bound = AstConv::ast_region_to_region(&icx, <, None);
1839 let outlives = ty::Binder::bind(ty::OutlivesPredicate(region, bound));
1840 predicates.push((outlives.to_predicate(), lt.span));
1849 // Collect the predicates that were written inline by the user on each
1850 // type parameter (e.g., `<T:Foo>`).
1851 for param in &ast_generics.params {
1852 if let GenericParamKind::Type { .. } = param.kind {
1853 let name = param.name.ident().as_interned_str();
1854 let param_ty = ty::ParamTy::new(index, name).to_ty(tcx);
1857 let sized = SizedByDefault::Yes;
1858 let bounds = compute_bounds(&icx, param_ty, ¶m.bounds, sized, param.span);
1859 predicates.extend(bounds.predicates(tcx, param_ty));
1863 // Add in the bounds that appear in the where-clause
1864 let where_clause = &ast_generics.where_clause;
1865 for predicate in &where_clause.predicates {
1867 &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
1868 let ty = icx.to_ty(&bound_pred.bounded_ty);
1870 // Keep the type around in a dummy predicate, in case of no bounds.
1871 // That way, `where Ty:` is not a complete noop (see #53696) and `Ty`
1872 // is still checked for WF.
1873 if bound_pred.bounds.is_empty() {
1874 if let ty::Param(_) = ty.sty {
1875 // This is a `where T:`, which can be in the HIR from the
1876 // transformation that moves `?Sized` to `T`'s declaration.
1877 // We can skip the predicate because type parameters are
1878 // trivially WF, but also we *should*, to avoid exposing
1879 // users who never wrote `where Type:,` themselves, to
1880 // compiler/tooling bugs from not handling WF predicates.
1882 let span = bound_pred.bounded_ty.span;
1883 let predicate = ty::OutlivesPredicate(ty, tcx.mk_region(ty::ReEmpty));
1885 (ty::Predicate::TypeOutlives(ty::Binder::dummy(predicate)), span)
1890 for bound in bound_pred.bounds.iter() {
1892 &hir::GenericBound::Trait(ref poly_trait_ref, _) => {
1893 let mut projections = Vec::new();
1895 let (trait_ref, _) = AstConv::instantiate_poly_trait_ref(
1903 iter::once((trait_ref.to_predicate(), poly_trait_ref.span)).chain(
1904 projections.iter().map(|&(p, span)| (p.to_predicate(), span)
1908 &hir::GenericBound::Outlives(ref lifetime) => {
1909 let region = AstConv::ast_region_to_region(&icx, lifetime, None);
1910 let pred = ty::Binder::bind(ty::OutlivesPredicate(ty, region));
1911 predicates.push((ty::Predicate::TypeOutlives(pred), lifetime.span))
1917 &hir::WherePredicate::RegionPredicate(ref region_pred) => {
1918 let r1 = AstConv::ast_region_to_region(&icx, ®ion_pred.lifetime, None);
1919 predicates.extend(region_pred.bounds.iter().map(|bound| {
1920 let (r2, span) = match bound {
1921 hir::GenericBound::Outlives(lt) => {
1922 (AstConv::ast_region_to_region(&icx, lt, None), lt.span)
1926 let pred = ty::Binder::bind(ty::OutlivesPredicate(r1, r2));
1928 (ty::Predicate::RegionOutlives(pred), span)
1932 &hir::WherePredicate::EqPredicate(..) => {
1938 // Add predicates from associated type bounds.
1939 if let Some((self_trait_ref, trait_items)) = is_trait {
1940 predicates.extend(trait_items.iter().flat_map(|trait_item_ref| {
1941 let trait_item = tcx.hir().trait_item(trait_item_ref.id);
1942 let bounds = match trait_item.node {
1943 hir::TraitItemKind::Type(ref bounds, _) => bounds,
1944 _ => return vec![].into_iter()
1948 tcx.mk_projection(tcx.hir().local_def_id(trait_item.id), self_trait_ref.substs);
1950 let bounds = compute_bounds(
1951 &ItemCtxt::new(tcx, def_id),
1954 SizedByDefault::Yes,
1958 bounds.predicates(tcx, assoc_ty).into_iter()
1962 let mut predicates = predicates.predicates;
1964 // Subtle: before we store the predicates into the tcx, we
1965 // sort them so that predicates like `T: Foo<Item=U>` come
1966 // before uses of `U`. This avoids false ambiguity errors
1967 // in trait checking. See `setup_constraining_predicates`
1969 if let Node::Item(&Item {
1970 node: ItemKind::Impl(..),
1974 let self_ty = tcx.type_of(def_id);
1975 let trait_ref = tcx.impl_trait_ref(def_id);
1976 ctp::setup_constraining_predicates(
1980 &mut ctp::parameters_for_impl(self_ty, trait_ref),
1984 Lrc::new(ty::GenericPredicates {
1985 parent: generics.parent,
1990 pub enum SizedByDefault {
1995 /// Translate the AST's notion of ty param bounds (which are an enum consisting of a newtyped `Ty`
1996 /// or a region) to ty's notion of ty param bounds, which can either be user-defined traits, or the
1997 /// built-in trait `Send`.
1998 pub fn compute_bounds<'gcx: 'tcx, 'tcx>(
1999 astconv: &dyn AstConv<'gcx, 'tcx>,
2001 ast_bounds: &[hir::GenericBound],
2002 sized_by_default: SizedByDefault,
2005 let mut region_bounds = Vec::new();
2006 let mut trait_bounds = Vec::new();
2008 for ast_bound in ast_bounds {
2010 hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::None) => trait_bounds.push(b),
2011 hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => {}
2012 hir::GenericBound::Outlives(ref l) => region_bounds.push(l),
2016 let mut projection_bounds = Vec::new();
2018 let mut trait_bounds: Vec<_> = trait_bounds.iter().map(|&bound| {
2019 let (poly_trait_ref, _) = astconv.instantiate_poly_trait_ref(
2022 &mut projection_bounds,
2024 (poly_trait_ref, bound.span)
2027 let region_bounds = region_bounds
2029 .map(|r| (astconv.ast_region_to_region(r, None), r.span))
2032 trait_bounds.sort_by_key(|(t, _)| t.def_id());
2034 let implicitly_sized = if let SizedByDefault::Yes = sized_by_default {
2035 if !is_unsized(astconv, ast_bounds, span) {
2052 /// Converts a specific `GenericBound` from the AST into a set of
2053 /// predicates that apply to the self-type. A vector is returned
2054 /// because this can be anywhere from zero predicates (`T : ?Sized` adds no
2055 /// predicates) to one (`T : Foo`) to many (`T : Bar<X=i32>` adds `T : Bar`
2056 /// and `<T as Bar>::X == i32`).
2057 fn predicates_from_bound<'tcx>(
2058 astconv: &dyn AstConv<'tcx, 'tcx>,
2060 bound: &hir::GenericBound,
2061 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2063 hir::GenericBound::Trait(ref tr, hir::TraitBoundModifier::None) => {
2064 let mut projections = Vec::new();
2065 let (pred, _) = astconv.instantiate_poly_trait_ref(tr, param_ty, &mut projections);
2066 iter::once((pred.to_predicate(), tr.span)).chain(
2069 .map(|(p, span)| (p.to_predicate(), span))
2072 hir::GenericBound::Outlives(ref lifetime) => {
2073 let region = astconv.ast_region_to_region(lifetime, None);
2074 let pred = ty::Binder::bind(ty::OutlivesPredicate(param_ty, region));
2075 vec![(ty::Predicate::TypeOutlives(pred), lifetime.span)]
2077 hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => vec![],
2081 fn compute_sig_of_foreign_fn_decl<'a, 'tcx>(
2082 tcx: TyCtxt<'a, 'tcx, 'tcx>,
2086 ) -> ty::PolyFnSig<'tcx> {
2087 let unsafety = if abi == abi::Abi::RustIntrinsic {
2088 match &*tcx.item_name(def_id).as_str() {
2089 "size_of" | "min_align_of" | "needs_drop" => hir::Unsafety::Normal,
2090 _ => hir::Unsafety::Unsafe,
2093 hir::Unsafety::Unsafe
2095 let fty = AstConv::ty_of_fn(&ItemCtxt::new(tcx, def_id), unsafety, abi, decl);
2097 // feature gate SIMD types in FFI, since I (huonw) am not sure the
2098 // ABIs are handled at all correctly.
2099 if abi != abi::Abi::RustIntrinsic
2100 && abi != abi::Abi::PlatformIntrinsic
2101 && !tcx.features().simd_ffi
2103 let check = |ast_ty: &hir::Ty, ty: Ty| {
2109 "use of SIMD type `{}` in FFI is highly experimental and \
2110 may result in invalid code",
2111 tcx.hir().node_to_pretty_string(ast_ty.id)
2114 .help("add #![feature(simd_ffi)] to the crate attributes to enable")
2118 for (input, ty) in decl.inputs.iter().zip(*fty.inputs().skip_binder()) {
2121 if let hir::Return(ref ty) = decl.output {
2122 check(&ty, *fty.output().skip_binder())
2129 fn is_foreign_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> bool {
2130 match tcx.hir().get_if_local(def_id) {
2131 Some(Node::ForeignItem(..)) => true,
2133 _ => bug!("is_foreign_item applied to non-local def-id {:?}", def_id),
2137 fn from_target_feature(
2140 attr: &ast::Attribute,
2141 whitelist: &FxHashMap<String, Option<String>>,
2142 target_features: &mut Vec<Symbol>,
2144 let list = match attr.meta_item_list() {
2147 let msg = "#[target_feature] attribute must be of the form \
2148 #[target_feature(..)]";
2149 tcx.sess.span_err(attr.span, &msg);
2153 let rust_features = tcx.features();
2155 // Only `enable = ...` is accepted in the meta item list
2156 if !item.check_name("enable") {
2157 let msg = "#[target_feature(..)] only accepts sub-keys of `enable` \
2159 tcx.sess.span_err(item.span, &msg);
2163 // Must be of the form `enable = "..."` ( a string)
2164 let value = match item.value_str() {
2165 Some(value) => value,
2167 let msg = "#[target_feature] attribute must be of the form \
2168 #[target_feature(enable = \"..\")]";
2169 tcx.sess.span_err(item.span, &msg);
2174 // We allow comma separation to enable multiple features
2175 target_features.extend(value.as_str().split(',').filter_map(|feature| {
2176 // Only allow whitelisted features per platform
2177 let feature_gate = match whitelist.get(feature) {
2181 "the feature named `{}` is not valid for \
2185 let mut err = tcx.sess.struct_span_err(item.span, &msg);
2187 if feature.starts_with("+") {
2188 let valid = whitelist.contains_key(&feature[1..]);
2190 err.help("consider removing the leading `+` in the feature name");
2198 // Only allow features whose feature gates have been enabled
2199 let allowed = match feature_gate.as_ref().map(|s| &**s) {
2200 Some("arm_target_feature") => rust_features.arm_target_feature,
2201 Some("aarch64_target_feature") => rust_features.aarch64_target_feature,
2202 Some("hexagon_target_feature") => rust_features.hexagon_target_feature,
2203 Some("powerpc_target_feature") => rust_features.powerpc_target_feature,
2204 Some("mips_target_feature") => rust_features.mips_target_feature,
2205 Some("avx512_target_feature") => rust_features.avx512_target_feature,
2206 Some("mmx_target_feature") => rust_features.mmx_target_feature,
2207 Some("sse4a_target_feature") => rust_features.sse4a_target_feature,
2208 Some("tbm_target_feature") => rust_features.tbm_target_feature,
2209 Some("wasm_target_feature") => rust_features.wasm_target_feature,
2210 Some(name) => bug!("unknown target feature gate {}", name),
2213 if !allowed && id.is_local() {
2214 feature_gate::emit_feature_err(
2215 &tcx.sess.parse_sess,
2216 feature_gate.as_ref().unwrap(),
2218 feature_gate::GateIssue::Language,
2219 &format!("the target feature `{}` is currently unstable", feature),
2223 Some(Symbol::intern(feature))
2228 fn linkage_by_name<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId, name: &str) -> Linkage {
2229 use rustc::mir::mono::Linkage::*;
2231 // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
2232 // applicable to variable declarations and may not really make sense for
2233 // Rust code in the first place but whitelist them anyway and trust that
2234 // the user knows what s/he's doing. Who knows, unanticipated use cases
2235 // may pop up in the future.
2237 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
2238 // and don't have to be, LLVM treats them as no-ops.
2240 "appending" => Appending,
2241 "available_externally" => AvailableExternally,
2243 "extern_weak" => ExternalWeak,
2244 "external" => External,
2245 "internal" => Internal,
2246 "linkonce" => LinkOnceAny,
2247 "linkonce_odr" => LinkOnceODR,
2248 "private" => Private,
2250 "weak_odr" => WeakODR,
2252 let span = tcx.hir().span_if_local(def_id);
2253 if let Some(span) = span {
2254 tcx.sess.span_fatal(span, "invalid linkage specified")
2257 .fatal(&format!("invalid linkage specified: {}", name))
2263 fn codegen_fn_attrs<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, id: DefId) -> CodegenFnAttrs {
2264 let attrs = tcx.get_attrs(id);
2266 let mut codegen_fn_attrs = CodegenFnAttrs::new();
2268 let whitelist = tcx.target_features_whitelist(LOCAL_CRATE);
2270 let mut inline_span = None;
2271 for attr in attrs.iter() {
2272 if attr.check_name("cold") {
2273 codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD;
2274 } else if attr.check_name("allocator") {
2275 codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR;
2276 } else if attr.check_name("unwind") {
2277 codegen_fn_attrs.flags |= CodegenFnAttrFlags::UNWIND;
2278 } else if attr.check_name("rustc_allocator_nounwind") {
2279 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND;
2280 } else if attr.check_name("naked") {
2281 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED;
2282 } else if attr.check_name("no_mangle") {
2283 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2284 } else if attr.check_name("rustc_std_internal_symbol") {
2285 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2286 } else if attr.check_name("no_debug") {
2287 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_DEBUG;
2288 } else if attr.check_name("used") {
2289 codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED;
2290 } else if attr.check_name("thread_local") {
2291 codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL;
2292 } else if attr.check_name("inline") {
2293 codegen_fn_attrs.inline = attrs.iter().fold(InlineAttr::None, |ia, attr| {
2294 if attr.path != "inline" {
2297 let meta = match attr.meta() {
2298 Some(meta) => meta.node,
2302 MetaItemKind::Word => {
2306 MetaItemKind::List(ref items) => {
2308 inline_span = Some(attr.span);
2309 if items.len() != 1 {
2311 tcx.sess.diagnostic(),
2314 "expected one argument"
2317 } else if list_contains_name(&items[..], "always") {
2319 } else if list_contains_name(&items[..], "never") {
2323 tcx.sess.diagnostic(),
2335 } else if attr.check_name("export_name") {
2336 if let Some(s) = attr.value_str() {
2337 if s.as_str().contains("\0") {
2338 // `#[export_name = ...]` will be converted to a null-terminated string,
2339 // so it may not contain any null characters.
2344 "`export_name` may not contain null characters"
2347 codegen_fn_attrs.export_name = Some(s);
2353 "`export_name` attribute has invalid format"
2354 ).span_label(attr.span, "did you mean #[export_name=\"*\"]?")
2357 } else if attr.check_name("target_feature") {
2358 if tcx.fn_sig(id).unsafety() == Unsafety::Normal {
2359 let msg = "#[target_feature(..)] can only be applied to \
2361 tcx.sess.span_err(attr.span, msg);
2363 from_target_feature(
2368 &mut codegen_fn_attrs.target_features,
2370 } else if attr.check_name("linkage") {
2371 if let Some(val) = attr.value_str() {
2372 codegen_fn_attrs.linkage = Some(linkage_by_name(tcx, id, &val.as_str()));
2374 } else if attr.check_name("link_section") {
2375 if let Some(val) = attr.value_str() {
2376 if val.as_str().bytes().any(|b| b == 0) {
2378 "illegal null byte in link_section \
2382 tcx.sess.span_err(attr.span, &msg);
2384 codegen_fn_attrs.link_section = Some(val);
2387 } else if attr.check_name("link_name") {
2388 codegen_fn_attrs.link_name = attr.value_str();
2392 // If a function uses #[target_feature] it can't be inlined into general
2393 // purpose functions as they wouldn't have the right target features
2394 // enabled. For that reason we also forbid #[inline(always)] as it can't be
2396 if codegen_fn_attrs.target_features.len() > 0 {
2397 if codegen_fn_attrs.inline == InlineAttr::Always {
2398 if let Some(span) = inline_span {
2401 "cannot use #[inline(always)] with \
2408 // Weak lang items have the same semantics as "std internal" symbols in the
2409 // sense that they're preserved through all our LTO passes and only
2410 // strippable by the linker.
2412 // Additionally weak lang items have predetermined symbol names.
2413 if tcx.is_weak_lang_item(id) {
2414 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2416 if let Some(name) = weak_lang_items::link_name(&attrs) {
2417 codegen_fn_attrs.export_name = Some(name);
2418 codegen_fn_attrs.link_name = Some(name);
2421 // Internal symbols to the standard library all have no_mangle semantics in
2422 // that they have defined symbol names present in the function name. This
2423 // also applies to weak symbols where they all have known symbol names.
2424 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
2425 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;