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::query::queries;
27 use rustc::ty::subst::Substs;
28 use rustc::ty::util::Discr;
29 use rustc::ty::util::IntTypeExt;
30 use rustc::ty::{self, AdtKind, ToPolyTraitRef, Ty, TyCtxt};
31 use rustc::ty::{ReprOptions, ToPredicate};
32 use rustc::util::captures::Captures;
33 use rustc::util::nodemap::FxHashMap;
34 use rustc_data_structures::sync::Lrc;
35 use rustc_target::spec::abi;
38 use syntax::ast::{Ident, MetaItemKind};
39 use syntax::attr::{InlineAttr, OptimizeAttr, list_contains_name, mark_used};
40 use syntax::source_map::Spanned;
41 use syntax::feature_gate;
42 use syntax::symbol::{keywords, Symbol};
43 use syntax_pos::{Span, DUMMY_SP};
45 use rustc::hir::def::{CtorKind, Def};
47 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
48 use rustc::hir::intravisit::{self, NestedVisitorMap, Visitor};
49 use rustc::hir::GenericParamKind;
50 use rustc::hir::{self, CodegenFnAttrFlags, CodegenFnAttrs, Unsafety};
54 struct OnlySelfBounds(bool);
56 ///////////////////////////////////////////////////////////////////////////
59 pub fn collect_item_types<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
60 for &module in tcx.hir().krate().modules.keys() {
61 queries::collect_mod_item_types::ensure(tcx, tcx.hir().local_def_id(module));
65 fn collect_mod_item_types<'tcx>(tcx: TyCtxt<'_, 'tcx, 'tcx>, module_def_id: DefId) {
66 tcx.hir().visit_item_likes_in_module(
68 &mut CollectItemTypesVisitor { tcx }.as_deep_visitor()
72 pub fn provide(providers: &mut Providers) {
73 *providers = Providers {
77 predicates_defined_on,
78 explicit_predicates_of,
80 type_param_predicates,
88 collect_mod_item_types,
93 ///////////////////////////////////////////////////////////////////////////
95 /// Context specific to some particular item. This is what implements
96 /// AstConv. It has information about the predicates that are defined
97 /// on the trait. Unfortunately, this predicate information is
98 /// available in various different forms at various points in the
99 /// process. So we can't just store a pointer to e.g., the AST or the
100 /// parsed ty form, we have to be more flexible. To this end, the
101 /// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy
102 /// `get_type_parameter_bounds` requests, drawing the information from
103 /// the AST (`hir::Generics`), recursively.
104 pub struct ItemCtxt<'a, 'tcx: 'a> {
105 tcx: TyCtxt<'a, 'tcx, 'tcx>,
109 ///////////////////////////////////////////////////////////////////////////
111 struct CollectItemTypesVisitor<'a, 'tcx: 'a> {
112 tcx: TyCtxt<'a, 'tcx, 'tcx>,
115 impl<'a, 'tcx> Visitor<'tcx> for CollectItemTypesVisitor<'a, 'tcx> {
116 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
117 NestedVisitorMap::OnlyBodies(&self.tcx.hir())
120 fn visit_item(&mut self, item: &'tcx hir::Item) {
121 convert_item(self.tcx, item.id);
122 intravisit::walk_item(self, item);
125 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
126 for param in &generics.params {
128 hir::GenericParamKind::Lifetime { .. } => {}
129 hir::GenericParamKind::Type {
132 let def_id = self.tcx.hir().local_def_id(param.id);
133 self.tcx.type_of(def_id);
135 hir::GenericParamKind::Type { .. } => {}
138 intravisit::walk_generics(self, generics);
141 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
142 if let hir::ExprKind::Closure(..) = expr.node {
143 let def_id = self.tcx.hir().local_def_id(expr.id);
144 self.tcx.generics_of(def_id);
145 self.tcx.type_of(def_id);
147 intravisit::walk_expr(self, expr);
150 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
151 convert_trait_item(self.tcx, trait_item.id);
152 intravisit::walk_trait_item(self, trait_item);
155 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
156 convert_impl_item(self.tcx, impl_item.id);
157 intravisit::walk_impl_item(self, impl_item);
161 ///////////////////////////////////////////////////////////////////////////
162 // Utility types and common code for the above passes.
164 impl<'a, 'tcx> ItemCtxt<'a, 'tcx> {
165 pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, item_def_id: DefId) -> ItemCtxt<'a, 'tcx> {
166 ItemCtxt { tcx, item_def_id }
170 impl<'a, 'tcx> ItemCtxt<'a, 'tcx> {
171 pub fn to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> {
172 AstConv::ast_ty_to_ty(self, ast_ty)
176 impl<'a, 'tcx> AstConv<'tcx, 'tcx> for ItemCtxt<'a, 'tcx> {
177 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'tcx, 'tcx> {
181 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId)
182 -> Lrc<ty::GenericPredicates<'tcx>> {
185 .type_param_predicates((self.item_def_id, def_id))
191 _def: Option<&ty::GenericParamDef>,
192 ) -> Option<ty::Region<'tcx>> {
196 fn ty_infer(&self, span: Span) -> Ty<'tcx> {
201 "the type placeholder `_` is not allowed within types on item signatures"
202 ).span_label(span, "not allowed in type signatures")
208 fn projected_ty_from_poly_trait_ref(
212 poly_trait_ref: ty::PolyTraitRef<'tcx>,
214 if let Some(trait_ref) = poly_trait_ref.no_bound_vars() {
215 self.tcx().mk_projection(item_def_id, trait_ref.substs)
217 // no late-bound regions, we can just ignore the binder
222 "cannot extract an associated type from a higher-ranked trait bound \
229 fn normalize_ty(&self, _span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
230 // types in item signatures are not normalized, to avoid undue
235 fn set_tainted_by_errors(&self) {
236 // no obvious place to track this, just let it go
239 fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) {
240 // no place to record types from signatures?
244 fn type_param_predicates<'a, 'tcx>(
245 tcx: TyCtxt<'a, 'tcx, 'tcx>,
246 (item_def_id, def_id): (DefId, DefId),
247 ) -> Lrc<ty::GenericPredicates<'tcx>> {
250 // In the AST, bounds can derive from two places. Either
251 // written inline like `<T : Foo>` or in a where clause like
254 let param_id = tcx.hir().as_local_node_id(def_id).unwrap();
255 let param_owner = tcx.hir().ty_param_owner(param_id);
256 let param_owner_def_id = tcx.hir().local_def_id(param_owner);
257 let generics = tcx.generics_of(param_owner_def_id);
258 let index = generics.param_def_id_to_index[&def_id];
259 let ty = tcx.mk_ty_param(index, tcx.hir().ty_param_name(param_id).as_interned_str());
261 // Don't look for bounds where the type parameter isn't in scope.
262 let parent = if item_def_id == param_owner_def_id {
265 tcx.generics_of(item_def_id).parent
268 let mut result = parent.map_or_else(
269 || Lrc::new(ty::GenericPredicates {
274 let icx = ItemCtxt::new(tcx, parent);
275 icx.get_type_parameter_bounds(DUMMY_SP, def_id)
279 let item_node_id = tcx.hir().as_local_node_id(item_def_id).unwrap();
280 let ast_generics = match tcx.hir().get(item_node_id) {
281 Node::TraitItem(item) => &item.generics,
283 Node::ImplItem(item) => &item.generics,
285 Node::Item(item) => {
287 ItemKind::Fn(.., ref generics, _)
288 | ItemKind::Impl(_, _, _, ref generics, ..)
289 | ItemKind::Ty(_, ref generics)
290 | ItemKind::Existential(ExistTy {
295 | ItemKind::Enum(_, ref generics)
296 | ItemKind::Struct(_, ref generics)
297 | ItemKind::Union(_, ref generics) => generics,
298 ItemKind::Trait(_, _, ref generics, ..) => {
299 // Implied `Self: Trait` and supertrait bounds.
300 if param_id == item_node_id {
301 let identity_trait_ref = ty::TraitRef::identity(tcx, item_def_id);
302 Lrc::make_mut(&mut result)
304 .push((identity_trait_ref.to_predicate(), item.span));
312 Node::ForeignItem(item) => match item.node {
313 ForeignItemKind::Fn(_, _, ref generics) => generics,
320 let icx = ItemCtxt::new(tcx, item_def_id);
321 Lrc::make_mut(&mut result)
323 .extend(icx.type_parameter_bounds_in_generics(ast_generics, param_id, ty,
324 OnlySelfBounds(true)));
328 impl<'a, 'tcx> ItemCtxt<'a, 'tcx> {
329 /// Find bounds from `hir::Generics`. This requires scanning through the
330 /// AST. We do this to avoid having to convert *all* the bounds, which
331 /// would create artificial cycles. Instead we can only convert the
332 /// bounds for a type parameter `X` if `X::Foo` is used.
333 fn type_parameter_bounds_in_generics(
335 ast_generics: &hir::Generics,
336 param_id: ast::NodeId,
338 only_self_bounds: OnlySelfBounds,
339 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
340 let from_ty_params = ast_generics
343 .filter_map(|param| match param.kind {
344 GenericParamKind::Type { .. } if param.id == param_id => Some(¶m.bounds),
347 .flat_map(|bounds| bounds.iter())
348 .flat_map(|b| predicates_from_bound(self, ty, b));
350 let from_where_clauses = ast_generics
354 .filter_map(|wp| match *wp {
355 hir::WherePredicate::BoundPredicate(ref bp) => Some(bp),
359 let bt = if is_param(self.tcx, &bp.bounded_ty, param_id) {
361 } else if !only_self_bounds.0 {
362 Some(self.to_ty(&bp.bounded_ty))
366 bp.bounds.iter().filter_map(move |b| bt.map(|bt| (bt, b)))
368 .flat_map(|(bt, b)| predicates_from_bound(self, bt, b));
370 from_ty_params.chain(from_where_clauses).collect()
374 /// Tests whether this is the AST for a reference to the type
375 /// parameter with id `param_id`. We use this so as to avoid running
376 /// `ast_ty_to_ty`, because we want to avoid triggering an all-out
377 /// conversion of the type to avoid inducing unnecessary cycles.
378 fn is_param<'a, 'tcx>(
379 tcx: TyCtxt<'a, 'tcx, 'tcx>,
381 param_id: ast::NodeId,
383 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = ast_ty.node {
385 Def::SelfTy(Some(def_id), None) | Def::TyParam(def_id) => {
386 def_id == tcx.hir().local_def_id(param_id)
395 fn convert_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item_id: ast::NodeId) {
396 let it = tcx.hir().expect_item(item_id);
397 debug!("convert: item {} with id {}", it.ident, it.id);
398 let def_id = tcx.hir().local_def_id(item_id);
400 // These don't define types.
401 hir::ItemKind::ExternCrate(_)
402 | hir::ItemKind::Use(..)
403 | hir::ItemKind::Mod(_)
404 | hir::ItemKind::GlobalAsm(_) => {}
405 hir::ItemKind::ForeignMod(ref foreign_mod) => {
406 for item in &foreign_mod.items {
407 let def_id = tcx.hir().local_def_id(item.id);
408 tcx.generics_of(def_id);
410 tcx.predicates_of(def_id);
411 if let hir::ForeignItemKind::Fn(..) = item.node {
416 hir::ItemKind::Enum(ref enum_definition, _) => {
417 tcx.generics_of(def_id);
419 tcx.predicates_of(def_id);
420 convert_enum_variant_types(tcx, def_id, &enum_definition.variants);
422 hir::ItemKind::Impl(..) => {
423 tcx.generics_of(def_id);
425 tcx.impl_trait_ref(def_id);
426 tcx.predicates_of(def_id);
428 hir::ItemKind::Trait(..) => {
429 tcx.generics_of(def_id);
430 tcx.trait_def(def_id);
431 tcx.at(it.span).super_predicates_of(def_id);
432 tcx.predicates_of(def_id);
434 hir::ItemKind::TraitAlias(..) => {
435 tcx.generics_of(def_id);
436 tcx.at(it.span).super_predicates_of(def_id);
437 tcx.predicates_of(def_id);
439 hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
440 tcx.generics_of(def_id);
442 tcx.predicates_of(def_id);
444 for f in struct_def.fields() {
445 let def_id = tcx.hir().local_def_id(f.id);
446 tcx.generics_of(def_id);
448 tcx.predicates_of(def_id);
451 if !struct_def.is_struct() {
452 convert_variant_ctor(tcx, struct_def.id());
456 // Desugared from `impl Trait` -> visited by the function's return type
457 hir::ItemKind::Existential(hir::ExistTy {
458 impl_trait_fn: Some(_),
462 hir::ItemKind::Existential(..)
463 | hir::ItemKind::Ty(..)
464 | hir::ItemKind::Static(..)
465 | hir::ItemKind::Const(..)
466 | hir::ItemKind::Fn(..) => {
467 tcx.generics_of(def_id);
469 tcx.predicates_of(def_id);
470 if let hir::ItemKind::Fn(..) = it.node {
477 fn convert_trait_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, trait_item_id: ast::NodeId) {
478 let trait_item = tcx.hir().expect_trait_item(trait_item_id);
479 let def_id = tcx.hir().local_def_id(trait_item.id);
480 tcx.generics_of(def_id);
482 match trait_item.node {
483 hir::TraitItemKind::Const(..)
484 | hir::TraitItemKind::Type(_, Some(_))
485 | hir::TraitItemKind::Method(..) => {
487 if let hir::TraitItemKind::Method(..) = trait_item.node {
492 hir::TraitItemKind::Type(_, None) => {}
495 tcx.predicates_of(def_id);
498 fn convert_impl_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, impl_item_id: ast::NodeId) {
499 let def_id = tcx.hir().local_def_id(impl_item_id);
500 tcx.generics_of(def_id);
502 tcx.predicates_of(def_id);
503 if let hir::ImplItemKind::Method(..) = tcx.hir().expect_impl_item(impl_item_id).node {
508 fn convert_variant_ctor<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ctor_id: ast::NodeId) {
509 let def_id = tcx.hir().local_def_id(ctor_id);
510 tcx.generics_of(def_id);
512 tcx.predicates_of(def_id);
515 fn convert_enum_variant_types<'a, 'tcx>(
516 tcx: TyCtxt<'a, 'tcx, 'tcx>,
518 variants: &[hir::Variant],
520 let def = tcx.adt_def(def_id);
521 let repr_type = def.repr.discr_type();
522 let initial = repr_type.initial_discriminant(tcx);
523 let mut prev_discr = None::<Discr<'tcx>>;
525 // fill the discriminant values and field types
526 for variant in variants {
527 let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
529 if let Some(ref e) = variant.node.disr_expr {
530 let expr_did = tcx.hir().local_def_id(e.id);
531 def.eval_explicit_discr(tcx, expr_did)
532 } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) {
539 "enum discriminant overflowed"
542 format!("overflowed on value after {}", prev_discr.unwrap()),
544 "explicitly set `{} = {}` if that is desired outcome",
545 variant.node.ident, wrapped_discr
549 }.unwrap_or(wrapped_discr),
552 for f in variant.node.data.fields() {
553 let def_id = tcx.hir().local_def_id(f.id);
554 tcx.generics_of(def_id);
556 tcx.predicates_of(def_id);
559 // Convert the ctor, if any. This also registers the variant as
561 convert_variant_ctor(tcx, variant.node.data.id());
565 fn convert_variant<'a, 'tcx>(
566 tcx: TyCtxt<'a, 'tcx, 'tcx>,
569 discr: ty::VariantDiscr,
570 def: &hir::VariantData,
571 adt_kind: ty::AdtKind,
572 attribute_def_id: DefId
573 ) -> ty::VariantDef {
574 let mut seen_fields: FxHashMap<ast::Ident, Span> = Default::default();
575 let node_id = tcx.hir().as_local_node_id(did).unwrap();
580 let fid = tcx.hir().local_def_id(f.id);
581 let dup_span = seen_fields.get(&f.ident.modern()).cloned();
582 if let Some(prev_span) = dup_span {
587 "field `{}` is already declared",
589 ).span_label(f.span, "field already declared")
590 .span_label(prev_span, format!("`{}` first declared here", f.ident))
593 seen_fields.insert(f.ident.modern(), f.span);
599 vis: ty::Visibility::from_hir(&f.vis, node_id, tcx),
603 ty::VariantDef::new(tcx,
609 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.ident, 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 = tcx.is_trait_alias(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 yet supported in inherent impls (see #8995)"
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 ¶m.kind {
1307 hir::GenericParamKind::Type {
1308 default: Some(ref ty),
1311 x => bug!("unexpected non-type Node::GenericParam: {:?}", x),
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)));
1630 debug!("predicates_defined_on({:?}) = {:?}", def_id, result);
1634 fn predicates_of<'a, 'tcx>(
1635 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1637 ) -> Lrc<ty::GenericPredicates<'tcx>> {
1638 let mut result = tcx.predicates_defined_on(def_id);
1640 if tcx.is_trait(def_id) {
1641 // For traits, add `Self: Trait` predicate. This is
1642 // not part of the predicates that a user writes, but it
1643 // is something that one must prove in order to invoke a
1644 // method or project an associated type.
1646 // In the chalk setup, this predicate is not part of the
1647 // "predicates" for a trait item. But it is useful in
1648 // rustc because if you directly (e.g.) invoke a trait
1649 // method like `Trait::method(...)`, you must naturally
1650 // prove that the trait applies to the types that were
1651 // used, and adding the predicate into this list ensures
1652 // that this is done.
1653 let span = tcx.def_span(def_id);
1654 Lrc::make_mut(&mut result)
1656 .push((ty::TraitRef::identity(tcx, def_id).to_predicate(), span));
1658 debug!("predicates_of(def_id={:?}) = {:?}", def_id, result);
1662 fn explicit_predicates_of<'a, 'tcx>(
1663 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1665 ) -> Lrc<ty::GenericPredicates<'tcx>> {
1667 use rustc_data_structures::fx::FxHashSet;
1669 debug!("explicit_predicates_of(def_id={:?})", def_id);
1671 /// A data structure with unique elements, which preserves order of insertion.
1672 /// Preserving the order of insertion is important here so as not to break
1673 /// compile-fail UI tests.
1674 struct UniquePredicates<'tcx> {
1675 predicates: Vec<(ty::Predicate<'tcx>, Span)>,
1676 uniques: FxHashSet<(ty::Predicate<'tcx>, Span)>,
1679 impl<'tcx> UniquePredicates<'tcx> {
1683 uniques: FxHashSet::default(),
1687 fn push(&mut self, value: (ty::Predicate<'tcx>, Span)) {
1688 if self.uniques.insert(value) {
1689 self.predicates.push(value);
1693 fn extend<I: IntoIterator<Item = (ty::Predicate<'tcx>, Span)>>(&mut self, iter: I) {
1700 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
1701 let node = tcx.hir().get(node_id);
1703 let mut is_trait = None;
1704 let mut is_default_impl_trait = None;
1706 let icx = ItemCtxt::new(tcx, def_id);
1707 let no_generics = hir::Generics::empty();
1708 let empty_trait_items = HirVec::new();
1710 let mut predicates = UniquePredicates::new();
1712 let ast_generics = match node {
1713 Node::TraitItem(item) => &item.generics,
1715 Node::ImplItem(item) => match item.node {
1716 ImplItemKind::Existential(ref bounds) => {
1717 let substs = Substs::identity_for_item(tcx, def_id);
1718 let opaque_ty = tcx.mk_opaque(def_id, substs);
1720 // Collect the bounds, i.e., the `A+B+'c` in `impl A+B+'c`.
1721 let bounds = compute_bounds(
1725 SizedByDefault::Yes,
1726 tcx.def_span(def_id),
1729 predicates.extend(bounds.predicates(tcx, opaque_ty));
1732 _ => &item.generics,
1735 Node::Item(item) => {
1737 ItemKind::Impl(_, _, defaultness, ref generics, ..) => {
1738 if defaultness.is_default() {
1739 is_default_impl_trait = tcx.impl_trait_ref(def_id);
1743 ItemKind::Fn(.., ref generics, _)
1744 | ItemKind::Ty(_, ref generics)
1745 | ItemKind::Enum(_, ref generics)
1746 | ItemKind::Struct(_, ref generics)
1747 | ItemKind::Union(_, ref generics) => generics,
1749 ItemKind::Trait(_, _, ref generics, .., ref items) => {
1750 is_trait = Some((ty::TraitRef::identity(tcx, def_id), items));
1753 ItemKind::TraitAlias(ref generics, _) => {
1754 is_trait = Some((ty::TraitRef::identity(tcx, def_id), &empty_trait_items));
1757 ItemKind::Existential(ExistTy {
1762 let substs = Substs::identity_for_item(tcx, def_id);
1763 let opaque_ty = tcx.mk_opaque(def_id, substs);
1765 // Collect the bounds, i.e., the `A+B+'c` in `impl A+B+'c`.
1766 let bounds = compute_bounds(
1770 SizedByDefault::Yes,
1771 tcx.def_span(def_id),
1774 if impl_trait_fn.is_some() {
1776 return Lrc::new(ty::GenericPredicates {
1778 predicates: bounds.predicates(tcx, opaque_ty),
1781 // named existential types
1782 predicates.extend(bounds.predicates(tcx, opaque_ty));
1791 Node::ForeignItem(item) => match item.node {
1792 ForeignItemKind::Static(..) => &no_generics,
1793 ForeignItemKind::Fn(_, _, ref generics) => generics,
1794 ForeignItemKind::Type => &no_generics,
1800 let generics = tcx.generics_of(def_id);
1801 let parent_count = generics.parent_count as u32;
1802 let has_own_self = generics.has_self && parent_count == 0;
1804 // Below we'll consider the bounds on the type parameters (including `Self`)
1805 // and the explicit where-clauses, but to get the full set of predicates
1806 // on a trait we need to add in the supertrait bounds and bounds found on
1807 // associated types.
1808 if let Some((_trait_ref, _)) = is_trait {
1809 predicates.extend(tcx.super_predicates_of(def_id).predicates.iter().cloned());
1812 // In default impls, we can assume that the self type implements
1813 // the trait. So in:
1815 // default impl Foo for Bar { .. }
1817 // we add a default where clause `Foo: Bar`. We do a similar thing for traits
1818 // (see below). Recall that a default impl is not itself an impl, but rather a
1819 // set of defaults that can be incorporated into another impl.
1820 if let Some(trait_ref) = is_default_impl_trait {
1821 predicates.push((trait_ref.to_poly_trait_ref().to_predicate(), tcx.def_span(def_id)));
1824 // Collect the region predicates that were declared inline as
1825 // well. In the case of parameters declared on a fn or method, we
1826 // have to be careful to only iterate over early-bound regions.
1827 let mut index = parent_count + has_own_self as u32;
1828 for param in early_bound_lifetimes_from_generics(tcx, ast_generics) {
1829 let region = tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
1830 def_id: tcx.hir().local_def_id(param.id),
1832 name: param.name.ident().as_interned_str(),
1837 GenericParamKind::Lifetime { .. } => {
1838 param.bounds.iter().for_each(|bound| match bound {
1839 hir::GenericBound::Outlives(lt) => {
1840 let bound = AstConv::ast_region_to_region(&icx, <, None);
1841 let outlives = ty::Binder::bind(ty::OutlivesPredicate(region, bound));
1842 predicates.push((outlives.to_predicate(), lt.span));
1851 // Collect the predicates that were written inline by the user on each
1852 // type parameter (e.g., `<T:Foo>`).
1853 for param in &ast_generics.params {
1854 if let GenericParamKind::Type { .. } = param.kind {
1855 let name = param.name.ident().as_interned_str();
1856 let param_ty = ty::ParamTy::new(index, name).to_ty(tcx);
1859 let sized = SizedByDefault::Yes;
1860 let bounds = compute_bounds(&icx, param_ty, ¶m.bounds, sized, param.span);
1861 predicates.extend(bounds.predicates(tcx, param_ty));
1865 // Add in the bounds that appear in the where-clause
1866 let where_clause = &ast_generics.where_clause;
1867 for predicate in &where_clause.predicates {
1869 &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
1870 let ty = icx.to_ty(&bound_pred.bounded_ty);
1872 // Keep the type around in a dummy predicate, in case of no bounds.
1873 // That way, `where Ty:` is not a complete noop (see #53696) and `Ty`
1874 // is still checked for WF.
1875 if bound_pred.bounds.is_empty() {
1876 if let ty::Param(_) = ty.sty {
1877 // This is a `where T:`, which can be in the HIR from the
1878 // transformation that moves `?Sized` to `T`'s declaration.
1879 // We can skip the predicate because type parameters are
1880 // trivially WF, but also we *should*, to avoid exposing
1881 // users who never wrote `where Type:,` themselves, to
1882 // compiler/tooling bugs from not handling WF predicates.
1884 let span = bound_pred.bounded_ty.span;
1885 let predicate = ty::OutlivesPredicate(ty, tcx.mk_region(ty::ReEmpty));
1887 (ty::Predicate::TypeOutlives(ty::Binder::dummy(predicate)), span)
1892 for bound in bound_pred.bounds.iter() {
1894 &hir::GenericBound::Trait(ref poly_trait_ref, _) => {
1895 let mut projections = Vec::new();
1897 let (trait_ref, _) = AstConv::instantiate_poly_trait_ref(
1905 iter::once((trait_ref.to_predicate(), poly_trait_ref.span)).chain(
1906 projections.iter().map(|&(p, span)| (p.to_predicate(), span)
1910 &hir::GenericBound::Outlives(ref lifetime) => {
1911 let region = AstConv::ast_region_to_region(&icx, lifetime, None);
1912 let pred = ty::Binder::bind(ty::OutlivesPredicate(ty, region));
1913 predicates.push((ty::Predicate::TypeOutlives(pred), lifetime.span))
1919 &hir::WherePredicate::RegionPredicate(ref region_pred) => {
1920 let r1 = AstConv::ast_region_to_region(&icx, ®ion_pred.lifetime, None);
1921 predicates.extend(region_pred.bounds.iter().map(|bound| {
1922 let (r2, span) = match bound {
1923 hir::GenericBound::Outlives(lt) => {
1924 (AstConv::ast_region_to_region(&icx, lt, None), lt.span)
1928 let pred = ty::Binder::bind(ty::OutlivesPredicate(r1, r2));
1930 (ty::Predicate::RegionOutlives(pred), span)
1934 &hir::WherePredicate::EqPredicate(..) => {
1940 // Add predicates from associated type bounds.
1941 if let Some((self_trait_ref, trait_items)) = is_trait {
1942 predicates.extend(trait_items.iter().flat_map(|trait_item_ref| {
1943 let trait_item = tcx.hir().trait_item(trait_item_ref.id);
1944 let bounds = match trait_item.node {
1945 hir::TraitItemKind::Type(ref bounds, _) => bounds,
1946 _ => return vec![].into_iter()
1950 tcx.mk_projection(tcx.hir().local_def_id(trait_item.id), self_trait_ref.substs);
1952 let bounds = compute_bounds(
1953 &ItemCtxt::new(tcx, def_id),
1956 SizedByDefault::Yes,
1960 bounds.predicates(tcx, assoc_ty).into_iter()
1964 let mut predicates = predicates.predicates;
1966 // Subtle: before we store the predicates into the tcx, we
1967 // sort them so that predicates like `T: Foo<Item=U>` come
1968 // before uses of `U`. This avoids false ambiguity errors
1969 // in trait checking. See `setup_constraining_predicates`
1971 if let Node::Item(&Item {
1972 node: ItemKind::Impl(..),
1976 let self_ty = tcx.type_of(def_id);
1977 let trait_ref = tcx.impl_trait_ref(def_id);
1978 ctp::setup_constraining_predicates(
1982 &mut ctp::parameters_for_impl(self_ty, trait_ref),
1986 let result = Lrc::new(ty::GenericPredicates {
1987 parent: generics.parent,
1990 debug!("explicit_predicates_of(def_id={:?}) = {:?}", def_id, result);
1994 pub enum SizedByDefault {
1999 /// Translate the AST's notion of ty param bounds (which are an enum consisting of a newtyped `Ty`
2000 /// or a region) to ty's notion of ty param bounds, which can either be user-defined traits, or the
2001 /// built-in trait `Send`.
2002 pub fn compute_bounds<'gcx: 'tcx, 'tcx>(
2003 astconv: &dyn AstConv<'gcx, 'tcx>,
2005 ast_bounds: &[hir::GenericBound],
2006 sized_by_default: SizedByDefault,
2009 let mut region_bounds = Vec::new();
2010 let mut trait_bounds = Vec::new();
2012 for ast_bound in ast_bounds {
2014 hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::None) => trait_bounds.push(b),
2015 hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => {}
2016 hir::GenericBound::Outlives(ref l) => region_bounds.push(l),
2020 let mut projection_bounds = Vec::new();
2022 let mut trait_bounds: Vec<_> = trait_bounds.iter().map(|&bound| {
2023 let (poly_trait_ref, _) = astconv.instantiate_poly_trait_ref(
2026 &mut projection_bounds,
2028 (poly_trait_ref, bound.span)
2031 let region_bounds = region_bounds
2033 .map(|r| (astconv.ast_region_to_region(r, None), r.span))
2036 trait_bounds.sort_by_key(|(t, _)| t.def_id());
2038 let implicitly_sized = if let SizedByDefault::Yes = sized_by_default {
2039 if !is_unsized(astconv, ast_bounds, span) {
2056 /// Converts a specific `GenericBound` from the AST into a set of
2057 /// predicates that apply to the self-type. A vector is returned
2058 /// because this can be anywhere from zero predicates (`T : ?Sized` adds no
2059 /// predicates) to one (`T : Foo`) to many (`T : Bar<X=i32>` adds `T : Bar`
2060 /// and `<T as Bar>::X == i32`).
2061 fn predicates_from_bound<'tcx>(
2062 astconv: &dyn AstConv<'tcx, 'tcx>,
2064 bound: &hir::GenericBound,
2065 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2067 hir::GenericBound::Trait(ref tr, hir::TraitBoundModifier::None) => {
2068 let mut projections = Vec::new();
2069 let (pred, _) = astconv.instantiate_poly_trait_ref(tr, param_ty, &mut projections);
2070 iter::once((pred.to_predicate(), tr.span)).chain(
2073 .map(|(p, span)| (p.to_predicate(), span))
2076 hir::GenericBound::Outlives(ref lifetime) => {
2077 let region = astconv.ast_region_to_region(lifetime, None);
2078 let pred = ty::Binder::bind(ty::OutlivesPredicate(param_ty, region));
2079 vec![(ty::Predicate::TypeOutlives(pred), lifetime.span)]
2081 hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => vec![],
2085 fn compute_sig_of_foreign_fn_decl<'a, 'tcx>(
2086 tcx: TyCtxt<'a, 'tcx, 'tcx>,
2090 ) -> ty::PolyFnSig<'tcx> {
2091 let unsafety = if abi == abi::Abi::RustIntrinsic {
2092 intrisic_operation_unsafety(&*tcx.item_name(def_id).as_str())
2094 hir::Unsafety::Unsafe
2096 let fty = AstConv::ty_of_fn(&ItemCtxt::new(tcx, def_id), unsafety, abi, decl);
2098 // feature gate SIMD types in FFI, since I (huonw) am not sure the
2099 // ABIs are handled at all correctly.
2100 if abi != abi::Abi::RustIntrinsic
2101 && abi != abi::Abi::PlatformIntrinsic
2102 && !tcx.features().simd_ffi
2104 let check = |ast_ty: &hir::Ty, ty: Ty| {
2110 "use of SIMD type `{}` in FFI is highly experimental and \
2111 may result in invalid code",
2112 tcx.hir().node_to_pretty_string(ast_ty.id)
2115 .help("add #![feature(simd_ffi)] to the crate attributes to enable")
2119 for (input, ty) in decl.inputs.iter().zip(*fty.inputs().skip_binder()) {
2122 if let hir::Return(ref ty) = decl.output {
2123 check(&ty, *fty.output().skip_binder())
2130 fn is_foreign_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> bool {
2131 match tcx.hir().get_if_local(def_id) {
2132 Some(Node::ForeignItem(..)) => true,
2134 _ => bug!("is_foreign_item applied to non-local def-id {:?}", def_id),
2138 fn from_target_feature(
2141 attr: &ast::Attribute,
2142 whitelist: &FxHashMap<String, Option<String>>,
2143 target_features: &mut Vec<Symbol>,
2145 let list = match attr.meta_item_list() {
2149 let rust_features = tcx.features();
2151 // Only `enable = ...` is accepted in the meta item list
2152 if !item.check_name("enable") {
2153 let msg = "#[target_feature(..)] only accepts sub-keys of `enable` \
2155 tcx.sess.span_err(item.span, &msg);
2159 // Must be of the form `enable = "..."` ( a string)
2160 let value = match item.value_str() {
2161 Some(value) => value,
2163 let msg = "#[target_feature] attribute must be of the form \
2164 #[target_feature(enable = \"..\")]";
2165 tcx.sess.span_err(item.span, &msg);
2170 // We allow comma separation to enable multiple features
2171 target_features.extend(value.as_str().split(',').filter_map(|feature| {
2172 // Only allow whitelisted features per platform
2173 let feature_gate = match whitelist.get(feature) {
2177 "the feature named `{}` is not valid for \
2181 let mut err = tcx.sess.struct_span_err(item.span, &msg);
2183 if feature.starts_with("+") {
2184 let valid = whitelist.contains_key(&feature[1..]);
2186 err.help("consider removing the leading `+` in the feature name");
2194 // Only allow features whose feature gates have been enabled
2195 let allowed = match feature_gate.as_ref().map(|s| &**s) {
2196 Some("arm_target_feature") => rust_features.arm_target_feature,
2197 Some("aarch64_target_feature") => rust_features.aarch64_target_feature,
2198 Some("hexagon_target_feature") => rust_features.hexagon_target_feature,
2199 Some("powerpc_target_feature") => rust_features.powerpc_target_feature,
2200 Some("mips_target_feature") => rust_features.mips_target_feature,
2201 Some("avx512_target_feature") => rust_features.avx512_target_feature,
2202 Some("mmx_target_feature") => rust_features.mmx_target_feature,
2203 Some("sse4a_target_feature") => rust_features.sse4a_target_feature,
2204 Some("tbm_target_feature") => rust_features.tbm_target_feature,
2205 Some("wasm_target_feature") => rust_features.wasm_target_feature,
2206 Some("cmpxchg16b_target_feature") => rust_features.cmpxchg16b_target_feature,
2207 Some("adx_target_feature") => rust_features.adx_target_feature,
2208 Some(name) => bug!("unknown target feature gate {}", name),
2211 if !allowed && id.is_local() {
2212 feature_gate::emit_feature_err(
2213 &tcx.sess.parse_sess,
2214 feature_gate.as_ref().unwrap(),
2216 feature_gate::GateIssue::Language,
2217 &format!("the target feature `{}` is currently unstable", feature),
2220 Some(Symbol::intern(feature))
2225 fn linkage_by_name<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId, name: &str) -> Linkage {
2226 use rustc::mir::mono::Linkage::*;
2228 // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
2229 // applicable to variable declarations and may not really make sense for
2230 // Rust code in the first place but whitelist them anyway and trust that
2231 // the user knows what s/he's doing. Who knows, unanticipated use cases
2232 // may pop up in the future.
2234 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
2235 // and don't have to be, LLVM treats them as no-ops.
2237 "appending" => Appending,
2238 "available_externally" => AvailableExternally,
2240 "extern_weak" => ExternalWeak,
2241 "external" => External,
2242 "internal" => Internal,
2243 "linkonce" => LinkOnceAny,
2244 "linkonce_odr" => LinkOnceODR,
2245 "private" => Private,
2247 "weak_odr" => WeakODR,
2249 let span = tcx.hir().span_if_local(def_id);
2250 if let Some(span) = span {
2251 tcx.sess.span_fatal(span, "invalid linkage specified")
2254 .fatal(&format!("invalid linkage specified: {}", name))
2260 fn codegen_fn_attrs<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, id: DefId) -> CodegenFnAttrs {
2261 let attrs = tcx.get_attrs(id);
2263 let mut codegen_fn_attrs = CodegenFnAttrs::new();
2265 let whitelist = tcx.target_features_whitelist(LOCAL_CRATE);
2267 let mut inline_span = None;
2268 for attr in attrs.iter() {
2269 if attr.check_name("cold") {
2270 codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD;
2271 } else if attr.check_name("allocator") {
2272 codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR;
2273 } else if attr.check_name("unwind") {
2274 codegen_fn_attrs.flags |= CodegenFnAttrFlags::UNWIND;
2275 } else if attr.check_name("rustc_allocator_nounwind") {
2276 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND;
2277 } else if attr.check_name("naked") {
2278 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED;
2279 } else if attr.check_name("no_mangle") {
2280 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2281 } else if attr.check_name("rustc_std_internal_symbol") {
2282 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2283 } else if attr.check_name("no_debug") {
2284 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_DEBUG;
2285 } else if attr.check_name("used") {
2286 codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED;
2287 } else if attr.check_name("thread_local") {
2288 codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL;
2289 } else if attr.check_name("export_name") {
2290 if let Some(s) = attr.value_str() {
2291 if s.as_str().contains("\0") {
2292 // `#[export_name = ...]` will be converted to a null-terminated string,
2293 // so it may not contain any null characters.
2298 "`export_name` may not contain null characters"
2301 codegen_fn_attrs.export_name = Some(s);
2303 } else if attr.check_name("target_feature") {
2304 if tcx.fn_sig(id).unsafety() == Unsafety::Normal {
2305 let msg = "#[target_feature(..)] can only be applied to \
2307 tcx.sess.span_err(attr.span, msg);
2309 from_target_feature(
2314 &mut codegen_fn_attrs.target_features,
2316 } else if attr.check_name("linkage") {
2317 if let Some(val) = attr.value_str() {
2318 codegen_fn_attrs.linkage = Some(linkage_by_name(tcx, id, &val.as_str()));
2320 } else if attr.check_name("link_section") {
2321 if let Some(val) = attr.value_str() {
2322 if val.as_str().bytes().any(|b| b == 0) {
2324 "illegal null byte in link_section \
2328 tcx.sess.span_err(attr.span, &msg);
2330 codegen_fn_attrs.link_section = Some(val);
2333 } else if attr.check_name("link_name") {
2334 codegen_fn_attrs.link_name = attr.value_str();
2338 codegen_fn_attrs.inline = attrs.iter().fold(InlineAttr::None, |ia, attr| {
2339 if attr.path != "inline" {
2342 match attr.meta().map(|i| i.node) {
2343 Some(MetaItemKind::Word) => {
2347 Some(MetaItemKind::List(ref items)) => {
2349 inline_span = Some(attr.span);
2350 if items.len() != 1 {
2352 tcx.sess.diagnostic(),
2355 "expected one argument"
2358 } else if list_contains_name(&items[..], "always") {
2360 } else if list_contains_name(&items[..], "never") {
2364 tcx.sess.diagnostic(),
2373 Some(MetaItemKind::NameValue(_)) => ia,
2378 codegen_fn_attrs.optimize = attrs.iter().fold(OptimizeAttr::None, |ia, attr| {
2379 if attr.path != "optimize" {
2382 let err = |sp, s| span_err!(tcx.sess.diagnostic(), sp, E0722, "{}", s);
2383 match attr.meta().map(|i| i.node) {
2384 Some(MetaItemKind::Word) => {
2385 err(attr.span, "expected one argument");
2388 Some(MetaItemKind::List(ref items)) => {
2390 inline_span = Some(attr.span);
2391 if items.len() != 1 {
2392 err(attr.span, "expected one argument");
2394 } else if list_contains_name(&items[..], "size") {
2396 } else if list_contains_name(&items[..], "speed") {
2399 err(items[0].span, "invalid argument");
2403 Some(MetaItemKind::NameValue(_)) => ia,
2408 // If a function uses #[target_feature] it can't be inlined into general
2409 // purpose functions as they wouldn't have the right target features
2410 // enabled. For that reason we also forbid #[inline(always)] as it can't be
2412 if codegen_fn_attrs.target_features.len() > 0 {
2413 if codegen_fn_attrs.inline == InlineAttr::Always {
2414 if let Some(span) = inline_span {
2417 "cannot use #[inline(always)] with \
2424 // Weak lang items have the same semantics as "std internal" symbols in the
2425 // sense that they're preserved through all our LTO passes and only
2426 // strippable by the linker.
2428 // Additionally weak lang items have predetermined symbol names.
2429 if tcx.is_weak_lang_item(id) {
2430 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2432 if let Some(name) = weak_lang_items::link_name(&attrs) {
2433 codegen_fn_attrs.export_name = Some(name);
2434 codegen_fn_attrs.link_name = Some(name);
2437 // Internal symbols to the standard library all have no_mangle semantics in
2438 // that they have defined symbol names present in the function name. This
2439 // also applies to weak symbols where they all have known symbol names.
2440 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
2441 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;