1 //! "Collection" is the process of determining the type and other external
2 //! details of each item in Rust. Collection is specifically concerned
3 //! with *interprocedural* things -- for example, for a function
4 //! definition, collection will figure out the type and signature of the
5 //! function, but it will not visit the *body* of the function in any way,
6 //! nor examine type annotations on local variables (that's the job of
9 //! Collecting is ultimately defined by a bundle of queries that
10 //! inquire after various facts about the items in the crate (e.g.,
11 //! `type_of`, `generics_of`, `predicates_of`, etc). See the `provide` function
14 //! At present, however, we do run collection across all items in the
15 //! crate as a kind of pass. This should eventually be factored away.
17 use crate::astconv::{AstConv, Bounds};
18 use crate::constrained_type_params as ctp;
19 use crate::check::intrinsic::intrisic_operation_unsafety;
21 use crate::middle::lang_items::SizedTraitLangItem;
22 use crate::middle::resolve_lifetime as rl;
23 use crate::middle::weak_lang_items;
24 use rustc::mir::mono::Linkage;
25 use rustc::ty::query::Providers;
26 use rustc::ty::subst::Substs;
27 use rustc::ty::util::Discr;
28 use rustc::ty::util::IntTypeExt;
29 use rustc::ty::{self, AdtKind, ToPolyTraitRef, Ty, TyCtxt};
30 use rustc::ty::{ReprOptions, ToPredicate};
31 use rustc::util::captures::Captures;
32 use rustc::util::nodemap::FxHashMap;
33 use rustc_data_structures::sync::Lrc;
34 use rustc_target::spec::abi;
37 use syntax::ast::{Ident, MetaItemKind};
38 use syntax::attr::{InlineAttr, OptimizeAttr, list_contains_name, mark_used};
39 use syntax::source_map::Spanned;
40 use syntax::feature_gate;
41 use syntax::symbol::{keywords, Symbol};
42 use syntax_pos::{Span, DUMMY_SP};
44 use rustc::hir::def::{CtorKind, Def};
46 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
47 use rustc::hir::intravisit::{self, NestedVisitorMap, Visitor};
48 use rustc::hir::GenericParamKind;
49 use rustc::hir::{self, CodegenFnAttrFlags, CodegenFnAttrs, Unsafety};
53 struct OnlySelfBounds(bool);
55 ///////////////////////////////////////////////////////////////////////////
58 pub fn collect_item_types<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
59 for &module in tcx.hir().krate().modules.keys() {
60 tcx.ensure().collect_mod_item_types(tcx.hir().local_def_id(module));
64 fn collect_mod_item_types<'tcx>(tcx: TyCtxt<'_, 'tcx, 'tcx>, module_def_id: DefId) {
65 tcx.hir().visit_item_likes_in_module(
67 &mut CollectItemTypesVisitor { tcx }.as_deep_visitor()
71 pub fn provide(providers: &mut Providers<'_>) {
72 *providers = Providers {
76 predicates_defined_on,
77 explicit_predicates_of,
79 type_param_predicates,
87 collect_mod_item_types,
92 ///////////////////////////////////////////////////////////////////////////
94 /// Context specific to some particular item. This is what implements
95 /// `AstConv`. It has information about the predicates that are defined
96 /// on the trait. Unfortunately, this predicate information is
97 /// available in various different forms at various points in the
98 /// process. So we can't just store a pointer to e.g., the AST or the
99 /// parsed ty form, we have to be more flexible. To this end, the
100 /// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy
101 /// `get_type_parameter_bounds` requests, drawing the information from
102 /// the AST (`hir::Generics`), recursively.
103 pub struct ItemCtxt<'a, 'tcx: 'a> {
104 tcx: TyCtxt<'a, 'tcx, 'tcx>,
108 ///////////////////////////////////////////////////////////////////////////
110 struct CollectItemTypesVisitor<'a, 'tcx: 'a> {
111 tcx: TyCtxt<'a, 'tcx, 'tcx>,
114 impl<'a, 'tcx> Visitor<'tcx> for CollectItemTypesVisitor<'a, 'tcx> {
115 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
116 NestedVisitorMap::OnlyBodies(&self.tcx.hir())
119 fn visit_item(&mut self, item: &'tcx hir::Item) {
120 convert_item(self.tcx, item.id);
121 intravisit::walk_item(self, item);
124 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
125 for param in &generics.params {
127 hir::GenericParamKind::Lifetime { .. } => {}
128 hir::GenericParamKind::Type {
131 let def_id = self.tcx.hir().local_def_id(param.id);
132 self.tcx.type_of(def_id);
134 hir::GenericParamKind::Type { .. } => {}
137 intravisit::walk_generics(self, generics);
140 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
141 if let hir::ExprKind::Closure(..) = expr.node {
142 let def_id = self.tcx.hir().local_def_id(expr.id);
143 self.tcx.generics_of(def_id);
144 self.tcx.type_of(def_id);
146 intravisit::walk_expr(self, expr);
149 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
150 convert_trait_item(self.tcx, trait_item.id);
151 intravisit::walk_trait_item(self, trait_item);
154 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
155 convert_impl_item(self.tcx, impl_item.id);
156 intravisit::walk_impl_item(self, impl_item);
160 ///////////////////////////////////////////////////////////////////////////
161 // Utility types and common code for the above passes.
163 impl<'a, 'tcx> ItemCtxt<'a, 'tcx> {
164 pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, item_def_id: DefId) -> ItemCtxt<'a, 'tcx> {
165 ItemCtxt { tcx, item_def_id }
169 impl<'a, 'tcx> ItemCtxt<'a, 'tcx> {
170 pub fn to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> {
171 AstConv::ast_ty_to_ty(self, ast_ty)
175 impl<'a, 'tcx> AstConv<'tcx, 'tcx> for ItemCtxt<'a, 'tcx> {
176 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'tcx, 'tcx> {
180 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId)
181 -> Lrc<ty::GenericPredicates<'tcx>> {
184 .type_param_predicates((self.item_def_id, def_id))
190 _def: Option<&ty::GenericParamDef>,
191 ) -> Option<ty::Region<'tcx>> {
195 fn ty_infer(&self, span: Span) -> Ty<'tcx> {
200 "the type placeholder `_` is not allowed within types on item signatures"
201 ).span_label(span, "not allowed in type signatures")
207 fn projected_ty_from_poly_trait_ref(
211 poly_trait_ref: ty::PolyTraitRef<'tcx>,
213 if let Some(trait_ref) = poly_trait_ref.no_bound_vars() {
214 self.tcx().mk_projection(item_def_id, trait_ref.substs)
216 // no late-bound regions, we can just ignore the binder
221 "cannot extract an associated type from a higher-ranked trait bound \
228 fn normalize_ty(&self, _span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
229 // types in item signatures are not normalized, to avoid undue
234 fn set_tainted_by_errors(&self) {
235 // no obvious place to track this, just let it go
238 fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) {
239 // no place to record types from signatures?
243 fn type_param_predicates<'a, 'tcx>(
244 tcx: TyCtxt<'a, 'tcx, 'tcx>,
245 (item_def_id, def_id): (DefId, DefId),
246 ) -> Lrc<ty::GenericPredicates<'tcx>> {
249 // In the AST, bounds can derive from two places. Either
250 // written inline like `<T : Foo>` or in a where clause like
253 let param_id = tcx.hir().as_local_node_id(def_id).unwrap();
254 let param_owner = tcx.hir().ty_param_owner(param_id);
255 let param_owner_def_id = tcx.hir().local_def_id(param_owner);
256 let generics = tcx.generics_of(param_owner_def_id);
257 let index = generics.param_def_id_to_index[&def_id];
258 let ty = tcx.mk_ty_param(index, tcx.hir().ty_param_name(param_id).as_interned_str());
260 // Don't look for bounds where the type parameter isn't in scope.
261 let parent = if item_def_id == param_owner_def_id {
264 tcx.generics_of(item_def_id).parent
267 let mut result = parent.map_or_else(
268 || Lrc::new(ty::GenericPredicates {
273 let icx = ItemCtxt::new(tcx, parent);
274 icx.get_type_parameter_bounds(DUMMY_SP, def_id)
278 let item_node_id = tcx.hir().as_local_node_id(item_def_id).unwrap();
279 let ast_generics = match tcx.hir().get(item_node_id) {
280 Node::TraitItem(item) => &item.generics,
282 Node::ImplItem(item) => &item.generics,
284 Node::Item(item) => {
286 ItemKind::Fn(.., ref generics, _)
287 | ItemKind::Impl(_, _, _, ref generics, ..)
288 | ItemKind::Ty(_, ref generics)
289 | ItemKind::Existential(ExistTy {
294 | ItemKind::Enum(_, ref generics)
295 | ItemKind::Struct(_, ref generics)
296 | ItemKind::Union(_, ref generics) => generics,
297 ItemKind::Trait(_, _, ref generics, ..) => {
298 // Implied `Self: Trait` and supertrait bounds.
299 if param_id == item_node_id {
300 let identity_trait_ref = ty::TraitRef::identity(tcx, item_def_id);
301 Lrc::make_mut(&mut result)
303 .push((identity_trait_ref.to_predicate(), item.span));
311 Node::ForeignItem(item) => match item.node {
312 ForeignItemKind::Fn(_, _, ref generics) => generics,
319 let icx = ItemCtxt::new(tcx, item_def_id);
320 Lrc::make_mut(&mut result)
322 .extend(icx.type_parameter_bounds_in_generics(ast_generics, param_id, ty,
323 OnlySelfBounds(true)));
327 impl<'a, 'tcx> ItemCtxt<'a, 'tcx> {
328 /// Finds bounds from `hir::Generics`. This requires scanning through the
329 /// AST. We do this to avoid having to convert *all* the bounds, which
330 /// would create artificial cycles. Instead we can only convert the
331 /// bounds for a type parameter `X` if `X::Foo` is used.
332 fn type_parameter_bounds_in_generics(
334 ast_generics: &hir::Generics,
335 param_id: ast::NodeId,
337 only_self_bounds: OnlySelfBounds,
338 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
339 let from_ty_params = ast_generics
342 .filter_map(|param| match param.kind {
343 GenericParamKind::Type { .. } if param.id == param_id => Some(¶m.bounds),
346 .flat_map(|bounds| bounds.iter())
347 .flat_map(|b| predicates_from_bound(self, ty, b));
349 let from_where_clauses = ast_generics
353 .filter_map(|wp| match *wp {
354 hir::WherePredicate::BoundPredicate(ref bp) => Some(bp),
358 let bt = if is_param(self.tcx, &bp.bounded_ty, param_id) {
360 } else if !only_self_bounds.0 {
361 Some(self.to_ty(&bp.bounded_ty))
365 bp.bounds.iter().filter_map(move |b| bt.map(|bt| (bt, b)))
367 .flat_map(|(bt, b)| predicates_from_bound(self, bt, b));
369 from_ty_params.chain(from_where_clauses).collect()
373 /// Tests whether this is the AST for a reference to the type
374 /// parameter with ID `param_id`. We use this so as to avoid running
375 /// `ast_ty_to_ty`, because we want to avoid triggering an all-out
376 /// conversion of the type to avoid inducing unnecessary cycles.
377 fn is_param<'a, 'tcx>(
378 tcx: TyCtxt<'a, 'tcx, 'tcx>,
380 param_id: ast::NodeId,
382 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = ast_ty.node {
384 Def::SelfTy(Some(def_id), None) | Def::TyParam(def_id) => {
385 def_id == tcx.hir().local_def_id(param_id)
394 fn convert_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item_id: ast::NodeId) {
395 let it = tcx.hir().expect_item(item_id);
396 debug!("convert: item {} with id {}", it.ident, it.id);
397 let def_id = tcx.hir().local_def_id(item_id);
399 // These don't define types.
400 hir::ItemKind::ExternCrate(_)
401 | hir::ItemKind::Use(..)
402 | hir::ItemKind::Mod(_)
403 | hir::ItemKind::GlobalAsm(_) => {}
404 hir::ItemKind::ForeignMod(ref foreign_mod) => {
405 for item in &foreign_mod.items {
406 let def_id = tcx.hir().local_def_id(item.id);
407 tcx.generics_of(def_id);
409 tcx.predicates_of(def_id);
410 if let hir::ForeignItemKind::Fn(..) = item.node {
415 hir::ItemKind::Enum(ref enum_definition, _) => {
416 tcx.generics_of(def_id);
418 tcx.predicates_of(def_id);
419 convert_enum_variant_types(tcx, def_id, &enum_definition.variants);
421 hir::ItemKind::Impl(..) => {
422 tcx.generics_of(def_id);
424 tcx.impl_trait_ref(def_id);
425 tcx.predicates_of(def_id);
427 hir::ItemKind::Trait(..) => {
428 tcx.generics_of(def_id);
429 tcx.trait_def(def_id);
430 tcx.at(it.span).super_predicates_of(def_id);
431 tcx.predicates_of(def_id);
433 hir::ItemKind::TraitAlias(..) => {
434 tcx.generics_of(def_id);
435 tcx.at(it.span).super_predicates_of(def_id);
436 tcx.predicates_of(def_id);
438 hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
439 tcx.generics_of(def_id);
441 tcx.predicates_of(def_id);
443 for f in struct_def.fields() {
444 let def_id = tcx.hir().local_def_id(f.id);
445 tcx.generics_of(def_id);
447 tcx.predicates_of(def_id);
450 if !struct_def.is_struct() {
451 convert_variant_ctor(tcx, struct_def.id());
455 // Desugared from `impl Trait` -> visited by the function's return type
456 hir::ItemKind::Existential(hir::ExistTy {
457 impl_trait_fn: Some(_),
461 hir::ItemKind::Existential(..)
462 | hir::ItemKind::Ty(..)
463 | hir::ItemKind::Static(..)
464 | hir::ItemKind::Const(..)
465 | hir::ItemKind::Fn(..) => {
466 tcx.generics_of(def_id);
468 tcx.predicates_of(def_id);
469 if let hir::ItemKind::Fn(..) = it.node {
476 fn convert_trait_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, trait_item_id: ast::NodeId) {
477 let trait_item = tcx.hir().expect_trait_item(trait_item_id);
478 let def_id = tcx.hir().local_def_id(trait_item.id);
479 tcx.generics_of(def_id);
481 match trait_item.node {
482 hir::TraitItemKind::Const(..)
483 | hir::TraitItemKind::Type(_, Some(_))
484 | hir::TraitItemKind::Method(..) => {
486 if let hir::TraitItemKind::Method(..) = trait_item.node {
491 hir::TraitItemKind::Type(_, None) => {}
494 tcx.predicates_of(def_id);
497 fn convert_impl_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, impl_item_id: ast::NodeId) {
498 let def_id = tcx.hir().local_def_id(impl_item_id);
499 tcx.generics_of(def_id);
501 tcx.predicates_of(def_id);
502 if let hir::ImplItemKind::Method(..) = tcx.hir().expect_impl_item(impl_item_id).node {
507 fn convert_variant_ctor<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ctor_id: ast::NodeId) {
508 let def_id = tcx.hir().local_def_id(ctor_id);
509 tcx.generics_of(def_id);
511 tcx.predicates_of(def_id);
514 fn convert_enum_variant_types<'a, 'tcx>(
515 tcx: TyCtxt<'a, 'tcx, 'tcx>,
517 variants: &[hir::Variant],
519 let def = tcx.adt_def(def_id);
520 let repr_type = def.repr.discr_type();
521 let initial = repr_type.initial_discriminant(tcx);
522 let mut prev_discr = None::<Discr<'tcx>>;
524 // fill the discriminant values and field types
525 for variant in variants {
526 let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
528 if let Some(ref e) = variant.node.disr_expr {
529 let expr_did = tcx.hir().local_def_id(e.id);
530 def.eval_explicit_discr(tcx, expr_did)
531 } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) {
538 "enum discriminant overflowed"
541 format!("overflowed on value after {}", prev_discr.unwrap()),
543 "explicitly set `{} = {}` if that is desired outcome",
544 variant.node.ident, wrapped_discr
548 }.unwrap_or(wrapped_discr),
551 for f in variant.node.data.fields() {
552 let def_id = tcx.hir().local_def_id(f.id);
553 tcx.generics_of(def_id);
555 tcx.predicates_of(def_id);
558 // Convert the ctor, if any. This also registers the variant as
560 convert_variant_ctor(tcx, variant.node.data.id());
564 fn convert_variant<'a, 'tcx>(
565 tcx: TyCtxt<'a, 'tcx, 'tcx>,
568 discr: ty::VariantDiscr,
569 def: &hir::VariantData,
570 adt_kind: ty::AdtKind,
571 attribute_def_id: DefId
572 ) -> ty::VariantDef {
573 let mut seen_fields: FxHashMap<ast::Ident, Span> = Default::default();
574 let node_id = tcx.hir().as_local_node_id(did).unwrap();
579 let fid = tcx.hir().local_def_id(f.id);
580 let dup_span = seen_fields.get(&f.ident.modern()).cloned();
581 if let Some(prev_span) = dup_span {
586 "field `{}` is already declared",
588 ).span_label(f.span, "field already declared")
589 .span_label(prev_span, format!("`{}` first declared here", f.ident))
592 seen_fields.insert(f.ident.modern(), f.span);
598 vis: ty::Visibility::from_hir(&f.vis, node_id, tcx),
602 ty::VariantDef::new(tcx,
608 CtorKind::from_hir(def),
613 fn adt_def<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx ty::AdtDef {
616 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
617 let item = match tcx.hir().get(node_id) {
618 Node::Item(item) => item,
622 let repr = ReprOptions::new(tcx, def_id);
623 let (kind, variants) = match item.node {
624 ItemKind::Enum(ref def, _) => {
625 let mut distance_from_explicit = 0;
631 let did = tcx.hir().local_def_id(v.node.data.id());
632 let discr = if let Some(ref e) = v.node.disr_expr {
633 distance_from_explicit = 0;
634 ty::VariantDiscr::Explicit(tcx.hir().local_def_id(e.id))
636 ty::VariantDiscr::Relative(distance_from_explicit)
638 distance_from_explicit += 1;
640 convert_variant(tcx, did, v.node.ident, discr, &v.node.data, AdtKind::Enum,
646 ItemKind::Struct(ref def, _) => {
647 // Use separate constructor id for unit/tuple structs and reuse did for braced structs.
648 let ctor_id = if !def.is_struct() {
649 Some(tcx.hir().local_def_id(def.id()))
655 std::iter::once(convert_variant(
657 ctor_id.unwrap_or(def_id),
659 ty::VariantDiscr::Relative(0),
666 ItemKind::Union(ref def, _) => (
668 std::iter::once(convert_variant(
672 ty::VariantDiscr::Relative(0),
680 tcx.alloc_adt_def(def_id, kind, variants, repr)
683 /// Ensures that the super-predicates of the trait with `DefId`
684 /// trait_def_id are converted and stored. This also ensures that
685 /// the transitive super-predicates are converted;
686 fn super_predicates_of<'a, 'tcx>(
687 tcx: TyCtxt<'a, 'tcx, 'tcx>,
689 ) -> Lrc<ty::GenericPredicates<'tcx>> {
690 debug!("super_predicates(trait_def_id={:?})", trait_def_id);
691 let trait_node_id = tcx.hir().as_local_node_id(trait_def_id).unwrap();
693 let item = match tcx.hir().get(trait_node_id) {
694 Node::Item(item) => item,
695 _ => bug!("trait_node_id {} is not an item", trait_node_id),
698 let (generics, bounds) = match item.node {
699 hir::ItemKind::Trait(.., ref generics, ref supertraits, _) => (generics, supertraits),
700 hir::ItemKind::TraitAlias(ref generics, ref supertraits) => (generics, supertraits),
701 _ => span_bug!(item.span, "super_predicates invoked on non-trait"),
704 let icx = ItemCtxt::new(tcx, trait_def_id);
706 // Convert the bounds that follow the colon, e.g., `Bar + Zed` in `trait Foo : Bar + Zed`.
707 let self_param_ty = tcx.mk_self_type();
708 let superbounds1 = compute_bounds(&icx, self_param_ty, bounds, SizedByDefault::No, item.span);
710 let superbounds1 = superbounds1.predicates(tcx, self_param_ty);
712 // Convert any explicit superbounds in the where clause,
713 // e.g., `trait Foo where Self : Bar`.
714 // In the case of trait aliases, however, we include all bounds in the where clause,
715 // so e.g., `trait Foo = where u32: PartialEq<Self>` would include `u32: PartialEq<Self>`
716 // as one of its "superpredicates".
717 let is_trait_alias = tcx.is_trait_alias(trait_def_id);
718 let superbounds2 = icx.type_parameter_bounds_in_generics(
719 generics, item.id, self_param_ty, OnlySelfBounds(!is_trait_alias));
721 // Combine the two lists to form the complete set of superbounds:
722 let superbounds: Vec<_> = superbounds1.into_iter().chain(superbounds2).collect();
724 // Now require that immediate supertraits are converted,
725 // which will, in turn, reach indirect supertraits.
726 for &(pred, span) in &superbounds {
727 debug!("superbound: {:?}", pred);
728 if let ty::Predicate::Trait(bound) = pred {
729 tcx.at(span).super_predicates_of(bound.def_id());
733 Lrc::new(ty::GenericPredicates {
735 predicates: superbounds,
739 fn trait_def<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx ty::TraitDef {
740 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
741 let item = tcx.hir().expect_item_by_hir_id(hir_id);
743 let (is_auto, unsafety) = match item.node {
744 hir::ItemKind::Trait(is_auto, unsafety, ..) => (is_auto == hir::IsAuto::Yes, unsafety),
745 hir::ItemKind::TraitAlias(..) => (false, hir::Unsafety::Normal),
746 _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
749 let paren_sugar = tcx.has_attr(def_id, "rustc_paren_sugar");
750 if paren_sugar && !tcx.features().unboxed_closures {
751 let mut err = tcx.sess.struct_span_err(
753 "the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \
754 which traits can use parenthetical notation",
758 "add `#![feature(unboxed_closures)]` to \
759 the crate attributes to use it"
764 let is_marker = tcx.has_attr(def_id, "marker");
765 let def_path_hash = tcx.def_path_hash(def_id);
766 let def = ty::TraitDef::new(def_id, unsafety, paren_sugar, is_auto, is_marker, def_path_hash);
767 tcx.alloc_trait_def(def)
770 fn has_late_bound_regions<'a, 'tcx>(
771 tcx: TyCtxt<'a, 'tcx, 'tcx>,
774 struct LateBoundRegionsDetector<'a, 'tcx: 'a> {
775 tcx: TyCtxt<'a, 'tcx, 'tcx>,
776 outer_index: ty::DebruijnIndex,
777 has_late_bound_regions: Option<Span>,
780 impl<'a, 'tcx> Visitor<'tcx> for LateBoundRegionsDetector<'a, 'tcx> {
781 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
782 NestedVisitorMap::None
785 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
786 if self.has_late_bound_regions.is_some() {
790 hir::TyKind::BareFn(..) => {
791 self.outer_index.shift_in(1);
792 intravisit::walk_ty(self, ty);
793 self.outer_index.shift_out(1);
795 _ => intravisit::walk_ty(self, ty),
799 fn visit_poly_trait_ref(
801 tr: &'tcx hir::PolyTraitRef,
802 m: hir::TraitBoundModifier,
804 if self.has_late_bound_regions.is_some() {
807 self.outer_index.shift_in(1);
808 intravisit::walk_poly_trait_ref(self, tr, m);
809 self.outer_index.shift_out(1);
812 fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
813 if self.has_late_bound_regions.is_some() {
817 match self.tcx.named_region(lt.hir_id) {
818 Some(rl::Region::Static) | Some(rl::Region::EarlyBound(..)) => {}
819 Some(rl::Region::LateBound(debruijn, _, _))
820 | Some(rl::Region::LateBoundAnon(debruijn, _)) if debruijn < self.outer_index => {}
821 Some(rl::Region::LateBound(..))
822 | Some(rl::Region::LateBoundAnon(..))
823 | Some(rl::Region::Free(..))
825 self.has_late_bound_regions = Some(lt.span);
831 fn has_late_bound_regions<'a, 'tcx>(
832 tcx: TyCtxt<'a, 'tcx, 'tcx>,
833 generics: &'tcx hir::Generics,
834 decl: &'tcx hir::FnDecl,
836 let mut visitor = LateBoundRegionsDetector {
838 outer_index: ty::INNERMOST,
839 has_late_bound_regions: None,
841 for param in &generics.params {
842 if let GenericParamKind::Lifetime { .. } = param.kind {
843 if tcx.is_late_bound(param.hir_id) {
844 return Some(param.span);
848 visitor.visit_fn_decl(decl);
849 visitor.has_late_bound_regions
853 Node::TraitItem(item) => match item.node {
854 hir::TraitItemKind::Method(ref sig, _) => {
855 has_late_bound_regions(tcx, &item.generics, &sig.decl)
859 Node::ImplItem(item) => match item.node {
860 hir::ImplItemKind::Method(ref sig, _) => {
861 has_late_bound_regions(tcx, &item.generics, &sig.decl)
865 Node::ForeignItem(item) => match item.node {
866 hir::ForeignItemKind::Fn(ref fn_decl, _, ref generics) => {
867 has_late_bound_regions(tcx, generics, fn_decl)
871 Node::Item(item) => match item.node {
872 hir::ItemKind::Fn(ref fn_decl, .., ref generics, _) => {
873 has_late_bound_regions(tcx, generics, fn_decl)
881 fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx ty::Generics {
884 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
886 let node = tcx.hir().get(node_id);
887 let parent_def_id = match node {
888 Node::ImplItem(_) | Node::TraitItem(_) | Node::Variant(_)
889 | Node::StructCtor(_) | Node::Field(_) => {
890 let parent_id = tcx.hir().get_parent(node_id);
891 Some(tcx.hir().local_def_id(parent_id))
893 Node::Expr(&hir::Expr {
894 node: hir::ExprKind::Closure(..),
896 }) => Some(tcx.closure_base_def_id(def_id)),
897 Node::Item(item) => match item.node {
898 ItemKind::Existential(hir::ExistTy { impl_trait_fn, .. }) => impl_trait_fn,
904 let mut opt_self = None;
905 let mut allow_defaults = false;
907 let no_generics = hir::Generics::empty();
908 let ast_generics = match node {
909 Node::TraitItem(item) => &item.generics,
911 Node::ImplItem(item) => &item.generics,
913 Node::Item(item) => {
915 ItemKind::Fn(.., ref generics, _) | ItemKind::Impl(_, _, _, ref generics, ..) => {
919 ItemKind::Ty(_, ref generics)
920 | ItemKind::Enum(_, ref generics)
921 | ItemKind::Struct(_, ref generics)
922 | ItemKind::Existential(hir::ExistTy { ref generics, .. })
923 | ItemKind::Union(_, ref generics) => {
924 allow_defaults = true;
928 ItemKind::Trait(_, _, ref generics, ..)
929 | ItemKind::TraitAlias(ref generics, ..) => {
930 // Add in the self type parameter.
932 // Something of a hack: use the node id for the trait, also as
933 // the node id for the Self type parameter.
934 let param_id = item.id;
936 opt_self = Some(ty::GenericParamDef {
938 name: keywords::SelfUpper.name().as_interned_str(),
939 def_id: tcx.hir().local_def_id(param_id),
940 pure_wrt_drop: false,
941 kind: ty::GenericParamDefKind::Type {
943 object_lifetime_default: rl::Set1::Empty,
948 allow_defaults = true;
956 Node::ForeignItem(item) => match item.node {
957 ForeignItemKind::Static(..) => &no_generics,
958 ForeignItemKind::Fn(_, _, ref generics) => generics,
959 ForeignItemKind::Type => &no_generics,
965 let has_self = opt_self.is_some();
966 let mut parent_has_self = false;
967 let mut own_start = has_self as u32;
968 let parent_count = parent_def_id.map_or(0, |def_id| {
969 let generics = tcx.generics_of(def_id);
970 assert_eq!(has_self, false);
971 parent_has_self = generics.has_self;
972 own_start = generics.count() as u32;
973 generics.parent_count + generics.params.len()
976 let mut params: Vec<_> = opt_self.into_iter().collect();
978 let early_lifetimes = early_bound_lifetimes_from_generics(tcx, ast_generics);
982 .map(|(i, param)| ty::GenericParamDef {
983 name: param.name.ident().as_interned_str(),
984 index: own_start + i as u32,
985 def_id: tcx.hir().local_def_id(param.id),
986 pure_wrt_drop: param.pure_wrt_drop,
987 kind: ty::GenericParamDefKind::Lifetime,
991 let hir_id = tcx.hir().node_to_hir_id(node_id);
992 let object_lifetime_defaults = tcx.object_lifetime_defaults(hir_id);
994 // Now create the real type parameters.
995 let type_start = own_start - has_self as u32 + params.len() as u32;
1001 .filter_map(|param| match param.kind {
1002 GenericParamKind::Type {
1007 if param.name.ident().name == keywords::SelfUpper.name() {
1010 "`Self` should not be the name of a regular parameter"
1014 if !allow_defaults && default.is_some() {
1015 if !tcx.features().default_type_parameter_fallback {
1017 lint::builtin::INVALID_TYPE_PARAM_DEFAULT,
1021 "defaults for type parameters are only allowed in \
1022 `struct`, `enum`, `type`, or `trait` definitions."
1028 let ty_param = ty::GenericParamDef {
1029 index: type_start + i as u32,
1030 name: param.name.ident().as_interned_str(),
1031 def_id: tcx.hir().local_def_id(param.id),
1032 pure_wrt_drop: param.pure_wrt_drop,
1033 kind: ty::GenericParamDefKind::Type {
1034 has_default: default.is_some(),
1035 object_lifetime_default: object_lifetime_defaults
1037 .map_or(rl::Set1::Empty, |o| o[i]),
1048 // provide junk type parameter defs - the only place that
1049 // cares about anything but the length is instantiation,
1050 // and we don't do that for closures.
1051 if let Node::Expr(&hir::Expr {
1052 node: hir::ExprKind::Closure(.., gen),
1056 let dummy_args = if gen.is_some() {
1057 &["<yield_ty>", "<return_ty>", "<witness>"][..]
1059 &["<closure_kind>", "<closure_signature>"][..]
1066 .map(|(i, &arg)| ty::GenericParamDef {
1067 index: type_start + i as u32,
1068 name: Symbol::intern(arg).as_interned_str(),
1070 pure_wrt_drop: false,
1071 kind: ty::GenericParamDefKind::Type {
1073 object_lifetime_default: rl::Set1::Empty,
1079 tcx.with_freevars(node_id, |fv| {
1080 params.extend(fv.iter().zip((dummy_args.len() as u32)..).map(|(_, i)| {
1081 ty::GenericParamDef {
1082 index: type_start + i,
1083 name: Symbol::intern("<upvar>").as_interned_str(),
1085 pure_wrt_drop: false,
1086 kind: ty::GenericParamDefKind::Type {
1088 object_lifetime_default: rl::Set1::Empty,
1096 let param_def_id_to_index = params
1098 .map(|param| (param.def_id, param.index))
1101 tcx.alloc_generics(ty::Generics {
1102 parent: parent_def_id,
1105 param_def_id_to_index,
1106 has_self: has_self || parent_has_self,
1107 has_late_bound_regions: has_late_bound_regions(tcx, node),
1111 fn report_assoc_ty_on_inherent_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, span: Span) {
1116 "associated types are not yet supported in inherent impls (see #8995)"
1120 fn type_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Ty<'tcx> {
1123 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
1125 let icx = ItemCtxt::new(tcx, def_id);
1127 match tcx.hir().get(node_id) {
1128 Node::TraitItem(item) => match item.node {
1129 TraitItemKind::Method(..) => {
1130 let substs = Substs::identity_for_item(tcx, def_id);
1131 tcx.mk_fn_def(def_id, substs)
1133 TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => icx.to_ty(ty),
1134 TraitItemKind::Type(_, None) => {
1135 span_bug!(item.span, "associated type missing default");
1139 Node::ImplItem(item) => match item.node {
1140 ImplItemKind::Method(..) => {
1141 let substs = Substs::identity_for_item(tcx, def_id);
1142 tcx.mk_fn_def(def_id, substs)
1144 ImplItemKind::Const(ref ty, _) => icx.to_ty(ty),
1145 ImplItemKind::Existential(_) => {
1147 .impl_trait_ref(tcx.hir().get_parent_did(node_id))
1150 report_assoc_ty_on_inherent_impl(tcx, item.span);
1153 find_existential_constraints(tcx, def_id)
1155 ImplItemKind::Type(ref ty) => {
1157 .impl_trait_ref(tcx.hir().get_parent_did(node_id))
1160 report_assoc_ty_on_inherent_impl(tcx, item.span);
1167 Node::Item(item) => {
1169 ItemKind::Static(ref t, ..)
1170 | ItemKind::Const(ref t, _)
1171 | ItemKind::Ty(ref t, _)
1172 | ItemKind::Impl(.., ref t, _) => icx.to_ty(t),
1173 ItemKind::Fn(..) => {
1174 let substs = Substs::identity_for_item(tcx, def_id);
1175 tcx.mk_fn_def(def_id, substs)
1177 ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
1178 let def = tcx.adt_def(def_id);
1179 let substs = Substs::identity_for_item(tcx, def_id);
1180 tcx.mk_adt(def, substs)
1182 ItemKind::Existential(hir::ExistTy {
1183 impl_trait_fn: None,
1185 }) => find_existential_constraints(tcx, def_id),
1186 // existential types desugared from impl Trait
1187 ItemKind::Existential(hir::ExistTy {
1188 impl_trait_fn: Some(owner),
1191 tcx.typeck_tables_of(owner)
1192 .concrete_existential_types
1195 .unwrap_or_else(|| {
1196 // This can occur if some error in the
1197 // owner fn prevented us from populating
1198 // the `concrete_existential_types` table.
1199 tcx.sess.delay_span_bug(
1202 "owner {:?} has no existential type for {:?} in its tables",
1210 | ItemKind::TraitAlias(..)
1212 | ItemKind::ForeignMod(..)
1213 | ItemKind::GlobalAsm(..)
1214 | ItemKind::ExternCrate(..)
1215 | ItemKind::Use(..) => {
1218 "compute_type_of_item: unexpected item type: {:?}",
1225 Node::ForeignItem(foreign_item) => match foreign_item.node {
1226 ForeignItemKind::Fn(..) => {
1227 let substs = Substs::identity_for_item(tcx, def_id);
1228 tcx.mk_fn_def(def_id, substs)
1230 ForeignItemKind::Static(ref t, _) => icx.to_ty(t),
1231 ForeignItemKind::Type => tcx.mk_foreign(def_id),
1234 Node::StructCtor(&ref def)
1235 | Node::Variant(&Spanned {
1236 node: hir::VariantKind { data: ref def, .. },
1239 VariantData::Unit(..) | VariantData::Struct(..) => {
1240 tcx.type_of(tcx.hir().get_parent_did(node_id))
1242 VariantData::Tuple(..) => {
1243 let substs = Substs::identity_for_item(tcx, def_id);
1244 tcx.mk_fn_def(def_id, substs)
1248 Node::Field(field) => icx.to_ty(&field.ty),
1250 Node::Expr(&hir::Expr {
1251 node: hir::ExprKind::Closure(.., gen),
1255 let hir_id = tcx.hir().node_to_hir_id(node_id);
1256 return tcx.typeck_tables_of(def_id).node_type(hir_id);
1259 let substs = ty::ClosureSubsts {
1260 substs: Substs::identity_for_item(tcx, def_id),
1263 tcx.mk_closure(def_id, substs)
1266 Node::AnonConst(_) => match tcx.hir().get(tcx.hir().get_parent_node(node_id)) {
1268 node: hir::TyKind::Array(_, ref constant),
1271 | Node::Ty(&hir::Ty {
1272 node: hir::TyKind::Typeof(ref constant),
1275 | Node::Expr(&hir::Expr {
1276 node: ExprKind::Repeat(_, ref constant),
1278 }) if constant.id == node_id =>
1283 Node::Variant(&Spanned {
1286 disr_expr: Some(ref e),
1290 }) if e.id == node_id =>
1292 tcx.adt_def(tcx.hir().get_parent_did(node_id))
1299 bug!("unexpected const parent in type_of_def_id(): {:?}", x);
1303 Node::GenericParam(param) => match ¶m.kind {
1304 hir::GenericParamKind::Type {
1305 default: Some(ref ty),
1308 x => bug!("unexpected non-type Node::GenericParam: {:?}", x),
1312 bug!("unexpected sort of node in type_of_def_id(): {:?}", x);
1317 fn find_existential_constraints<'a, 'tcx>(
1318 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1323 struct ConstraintLocator<'a, 'tcx: 'a> {
1324 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1326 found: Option<(Span, ty::Ty<'tcx>)>,
1329 impl<'a, 'tcx> ConstraintLocator<'a, 'tcx> {
1330 fn check(&mut self, def_id: DefId) {
1331 trace!("checking {:?}", def_id);
1332 // don't try to check items that cannot possibly constrain the type
1333 if !self.tcx.has_typeck_tables(def_id) {
1334 trace!("no typeck tables for {:?}", def_id);
1339 .typeck_tables_of(def_id)
1340 .concrete_existential_types
1343 if let Some(ty) = ty {
1344 // FIXME(oli-obk): trace the actual span from inference to improve errors
1345 let span = self.tcx.def_span(def_id);
1346 if let Some((prev_span, prev_ty)) = self.found {
1348 // found different concrete types for the existential type
1349 let mut err = self.tcx.sess.struct_span_err(
1351 "defining existential type use differs from previous",
1353 err.span_note(prev_span, "previous use here");
1357 self.found = Some((span, ty));
1363 impl<'a, 'tcx> intravisit::Visitor<'tcx> for ConstraintLocator<'a, 'tcx> {
1364 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
1365 intravisit::NestedVisitorMap::All(&self.tcx.hir())
1367 fn visit_item(&mut self, it: &'tcx Item) {
1368 let def_id = self.tcx.hir().local_def_id(it.id);
1369 // the existential type itself or its children are not within its reveal scope
1370 if def_id != self.def_id {
1372 intravisit::walk_item(self, it);
1375 fn visit_impl_item(&mut self, it: &'tcx ImplItem) {
1376 let def_id = self.tcx.hir().local_def_id(it.id);
1377 // the existential type itself or its children are not within its reveal scope
1378 if def_id != self.def_id {
1380 intravisit::walk_impl_item(self, it);
1383 fn visit_trait_item(&mut self, it: &'tcx TraitItem) {
1384 let def_id = self.tcx.hir().local_def_id(it.id);
1386 intravisit::walk_trait_item(self, it);
1390 let mut locator = ConstraintLocator {
1395 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
1396 let parent = tcx.hir().get_parent(node_id);
1398 trace!("parent_id: {:?}", parent);
1400 if parent == ast::CRATE_NODE_ID {
1401 intravisit::walk_crate(&mut locator, tcx.hir().krate());
1403 trace!("parent: {:?}", tcx.hir().get(parent));
1404 match tcx.hir().get(parent) {
1405 Node::Item(ref it) => intravisit::walk_item(&mut locator, it),
1406 Node::ImplItem(ref it) => intravisit::walk_impl_item(&mut locator, it),
1407 Node::TraitItem(ref it) => intravisit::walk_trait_item(&mut locator, it),
1409 "{:?} is not a valid parent of an existential type item",
1415 match locator.found {
1416 Some((_, ty)) => ty,
1418 let span = tcx.def_span(def_id);
1419 tcx.sess.span_err(span, "could not find defining uses");
1425 fn fn_sig<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> ty::PolyFnSig<'tcx> {
1427 use rustc::hir::Node::*;
1429 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
1431 let icx = ItemCtxt::new(tcx, def_id);
1433 match tcx.hir().get(node_id) {
1434 TraitItem(hir::TraitItem {
1435 node: TraitItemKind::Method(sig, _),
1438 | ImplItem(hir::ImplItem {
1439 node: ImplItemKind::Method(sig, _),
1441 }) => AstConv::ty_of_fn(&icx, sig.header.unsafety, sig.header.abi, &sig.decl),
1444 node: ItemKind::Fn(decl, header, _, _),
1446 }) => AstConv::ty_of_fn(&icx, header.unsafety, header.abi, decl),
1448 ForeignItem(&hir::ForeignItem {
1449 node: ForeignItemKind::Fn(ref fn_decl, _, _),
1452 let abi = tcx.hir().get_foreign_abi(node_id);
1453 compute_sig_of_foreign_fn_decl(tcx, def_id, fn_decl, abi)
1456 StructCtor(&VariantData::Tuple(ref fields, ..))
1457 | Variant(&Spanned {
1460 data: VariantData::Tuple(ref fields, ..),
1465 let ty = tcx.type_of(tcx.hir().get_parent_did(node_id));
1468 .map(|f| tcx.type_of(tcx.hir().local_def_id(f.id)));
1469 ty::Binder::bind(tcx.mk_fn_sig(
1473 hir::Unsafety::Normal,
1479 node: hir::ExprKind::Closure(..),
1482 // Closure signatures are not like other function
1483 // signatures and cannot be accessed through `fn_sig`. For
1484 // example, a closure signature excludes the `self`
1485 // argument. In any case they are embedded within the
1486 // closure type as part of the `ClosureSubsts`.
1489 // the signature of a closure, you should use the
1490 // `closure_sig` method on the `ClosureSubsts`:
1492 // closure_substs.closure_sig(def_id, tcx)
1494 // or, inside of an inference context, you can use
1496 // infcx.closure_sig(def_id, closure_substs)
1497 bug!("to get the signature of a closure, use `closure_sig()` not `fn_sig()`");
1501 bug!("unexpected sort of node in fn_sig(): {:?}", x);
1506 fn impl_trait_ref<'a, 'tcx>(
1507 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1509 ) -> Option<ty::TraitRef<'tcx>> {
1510 let icx = ItemCtxt::new(tcx, def_id);
1512 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1513 match tcx.hir().expect_item_by_hir_id(hir_id).node {
1514 hir::ItemKind::Impl(.., ref opt_trait_ref, _, _) => {
1515 opt_trait_ref.as_ref().map(|ast_trait_ref| {
1516 let selfty = tcx.type_of(def_id);
1517 AstConv::instantiate_mono_trait_ref(&icx, ast_trait_ref, selfty)
1524 fn impl_polarity<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> hir::ImplPolarity {
1525 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1526 match tcx.hir().expect_item_by_hir_id(hir_id).node {
1527 hir::ItemKind::Impl(_, polarity, ..) => polarity,
1528 ref item => bug!("impl_polarity: {:?} not an impl", item),
1532 // Is it marked with ?Sized
1533 fn is_unsized<'gcx: 'tcx, 'tcx>(
1534 astconv: &dyn AstConv<'gcx, 'tcx>,
1535 ast_bounds: &[hir::GenericBound],
1538 let tcx = astconv.tcx();
1540 // Try to find an unbound in bounds.
1541 let mut unbound = None;
1542 for ab in ast_bounds {
1543 if let &hir::GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = ab {
1544 if unbound.is_none() {
1545 unbound = Some(ptr.trait_ref.clone());
1551 "type parameter has more than one relaxed default \
1552 bound, only one is supported"
1558 let kind_id = tcx.lang_items().require(SizedTraitLangItem);
1561 // FIXME(#8559) currently requires the unbound to be built-in.
1562 if let Ok(kind_id) = kind_id {
1563 if tpb.path.def != Def::Trait(kind_id) {
1566 "default bound relaxed for a type parameter, but \
1567 this does nothing because the given bound is not \
1568 a default. Only `?Sized` is supported",
1573 _ if kind_id.is_ok() => {
1576 // No lang item for Sized, so we can't add it as a bound.
1583 /// Returns the early-bound lifetimes declared in this generics
1584 /// listing. For anything other than fns/methods, this is just all
1585 /// the lifetimes that are declared. For fns or methods, we have to
1586 /// screen out those that do not appear in any where-clauses etc using
1587 /// `resolve_lifetime::early_bound_lifetimes`.
1588 fn early_bound_lifetimes_from_generics<'a, 'tcx>(
1589 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1590 generics: &'a hir::Generics,
1591 ) -> impl Iterator<Item = &'a hir::GenericParam> + Captures<'tcx> {
1595 .filter(move |param| match param.kind {
1596 GenericParamKind::Lifetime { .. } => {
1597 let hir_id = tcx.hir().node_to_hir_id(param.id);
1598 !tcx.is_late_bound(hir_id)
1604 /// Returns a list of type predicates for the definition with ID `def_id`, including inferred
1605 /// lifetime constraints. This includes all predicates returned by `explicit_predicates_of`, plus
1606 /// inferred constraints concerning which regions outlive other regions.
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 /// Returns a list of all type predicates (explicit and implicit) for the definition with
1635 /// ID `def_id`. This includes all predicates returned by `predicates_defined_on`, plus
1636 /// `Self: Trait` predicates for traits.
1637 fn predicates_of<'a, 'tcx>(
1638 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1640 ) -> Lrc<ty::GenericPredicates<'tcx>> {
1641 let mut result = tcx.predicates_defined_on(def_id);
1643 if tcx.is_trait(def_id) {
1644 // For traits, add `Self: Trait` predicate. This is
1645 // not part of the predicates that a user writes, but it
1646 // is something that one must prove in order to invoke a
1647 // method or project an associated type.
1649 // In the chalk setup, this predicate is not part of the
1650 // "predicates" for a trait item. But it is useful in
1651 // rustc because if you directly (e.g.) invoke a trait
1652 // method like `Trait::method(...)`, you must naturally
1653 // prove that the trait applies to the types that were
1654 // used, and adding the predicate into this list ensures
1655 // that this is done.
1656 let span = tcx.def_span(def_id);
1657 Lrc::make_mut(&mut result)
1659 .push((ty::TraitRef::identity(tcx, def_id).to_predicate(), span));
1661 debug!("predicates_of(def_id={:?}) = {:?}", def_id, result);
1665 /// Returns a list of user-specified type predicates for the definition with ID `def_id`.
1666 /// N.B., this does not include any implied/inferred constraints.
1667 fn explicit_predicates_of<'a, 'tcx>(
1668 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1670 ) -> Lrc<ty::GenericPredicates<'tcx>> {
1672 use rustc_data_structures::fx::FxHashSet;
1674 debug!("explicit_predicates_of(def_id={:?})", def_id);
1676 /// A data structure with unique elements, which preserves order of insertion.
1677 /// Preserving the order of insertion is important here so as not to break
1678 /// compile-fail UI tests.
1679 struct UniquePredicates<'tcx> {
1680 predicates: Vec<(ty::Predicate<'tcx>, Span)>,
1681 uniques: FxHashSet<(ty::Predicate<'tcx>, Span)>,
1684 impl<'tcx> UniquePredicates<'tcx> {
1688 uniques: FxHashSet::default(),
1692 fn push(&mut self, value: (ty::Predicate<'tcx>, Span)) {
1693 if self.uniques.insert(value) {
1694 self.predicates.push(value);
1698 fn extend<I: IntoIterator<Item = (ty::Predicate<'tcx>, Span)>>(&mut self, iter: I) {
1705 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
1706 let node = tcx.hir().get(node_id);
1708 let mut is_trait = None;
1709 let mut is_default_impl_trait = None;
1711 let icx = ItemCtxt::new(tcx, def_id);
1712 let no_generics = hir::Generics::empty();
1713 let empty_trait_items = HirVec::new();
1715 let mut predicates = UniquePredicates::new();
1717 let ast_generics = match node {
1718 Node::TraitItem(item) => &item.generics,
1720 Node::ImplItem(item) => match item.node {
1721 ImplItemKind::Existential(ref bounds) => {
1722 let substs = Substs::identity_for_item(tcx, def_id);
1723 let opaque_ty = tcx.mk_opaque(def_id, substs);
1725 // Collect the bounds, i.e., the `A+B+'c` in `impl A+B+'c`.
1726 let bounds = compute_bounds(
1730 SizedByDefault::Yes,
1731 tcx.def_span(def_id),
1734 predicates.extend(bounds.predicates(tcx, opaque_ty));
1737 _ => &item.generics,
1740 Node::Item(item) => {
1742 ItemKind::Impl(_, _, defaultness, ref generics, ..) => {
1743 if defaultness.is_default() {
1744 is_default_impl_trait = tcx.impl_trait_ref(def_id);
1748 ItemKind::Fn(.., ref generics, _)
1749 | ItemKind::Ty(_, ref generics)
1750 | ItemKind::Enum(_, ref generics)
1751 | ItemKind::Struct(_, ref generics)
1752 | ItemKind::Union(_, ref generics) => generics,
1754 ItemKind::Trait(_, _, ref generics, .., ref items) => {
1755 is_trait = Some((ty::TraitRef::identity(tcx, def_id), items));
1758 ItemKind::TraitAlias(ref generics, _) => {
1759 is_trait = Some((ty::TraitRef::identity(tcx, def_id), &empty_trait_items));
1762 ItemKind::Existential(ExistTy {
1767 let substs = Substs::identity_for_item(tcx, def_id);
1768 let opaque_ty = tcx.mk_opaque(def_id, substs);
1770 // Collect the bounds, i.e., the `A+B+'c` in `impl A+B+'c`.
1771 let bounds = compute_bounds(
1775 SizedByDefault::Yes,
1776 tcx.def_span(def_id),
1779 if impl_trait_fn.is_some() {
1781 return Lrc::new(ty::GenericPredicates {
1783 predicates: bounds.predicates(tcx, opaque_ty),
1786 // named existential types
1787 predicates.extend(bounds.predicates(tcx, opaque_ty));
1796 Node::ForeignItem(item) => match item.node {
1797 ForeignItemKind::Static(..) => &no_generics,
1798 ForeignItemKind::Fn(_, _, ref generics) => generics,
1799 ForeignItemKind::Type => &no_generics,
1805 let generics = tcx.generics_of(def_id);
1806 let parent_count = generics.parent_count as u32;
1807 let has_own_self = generics.has_self && parent_count == 0;
1809 // Below we'll consider the bounds on the type parameters (including `Self`)
1810 // and the explicit where-clauses, but to get the full set of predicates
1811 // on a trait we need to add in the supertrait bounds and bounds found on
1812 // associated types.
1813 if let Some((_trait_ref, _)) = is_trait {
1814 predicates.extend(tcx.super_predicates_of(def_id).predicates.iter().cloned());
1817 // In default impls, we can assume that the self type implements
1818 // the trait. So in:
1820 // default impl Foo for Bar { .. }
1822 // we add a default where clause `Foo: Bar`. We do a similar thing for traits
1823 // (see below). Recall that a default impl is not itself an impl, but rather a
1824 // set of defaults that can be incorporated into another impl.
1825 if let Some(trait_ref) = is_default_impl_trait {
1826 predicates.push((trait_ref.to_poly_trait_ref().to_predicate(), tcx.def_span(def_id)));
1829 // Collect the region predicates that were declared inline as
1830 // well. In the case of parameters declared on a fn or method, we
1831 // have to be careful to only iterate over early-bound regions.
1832 let mut index = parent_count + has_own_self as u32;
1833 for param in early_bound_lifetimes_from_generics(tcx, ast_generics) {
1834 let region = tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
1835 def_id: tcx.hir().local_def_id(param.id),
1837 name: param.name.ident().as_interned_str(),
1842 GenericParamKind::Lifetime { .. } => {
1843 param.bounds.iter().for_each(|bound| match bound {
1844 hir::GenericBound::Outlives(lt) => {
1845 let bound = AstConv::ast_region_to_region(&icx, <, None);
1846 let outlives = ty::Binder::bind(ty::OutlivesPredicate(region, bound));
1847 predicates.push((outlives.to_predicate(), lt.span));
1856 // Collect the predicates that were written inline by the user on each
1857 // type parameter (e.g., `<T:Foo>`).
1858 for param in &ast_generics.params {
1859 if let GenericParamKind::Type { .. } = param.kind {
1860 let name = param.name.ident().as_interned_str();
1861 let param_ty = ty::ParamTy::new(index, name).to_ty(tcx);
1864 let sized = SizedByDefault::Yes;
1865 let bounds = compute_bounds(&icx, param_ty, ¶m.bounds, sized, param.span);
1866 predicates.extend(bounds.predicates(tcx, param_ty));
1870 // Add in the bounds that appear in the where-clause
1871 let where_clause = &ast_generics.where_clause;
1872 for predicate in &where_clause.predicates {
1874 &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
1875 let ty = icx.to_ty(&bound_pred.bounded_ty);
1877 // Keep the type around in a dummy predicate, in case of no bounds.
1878 // That way, `where Ty:` is not a complete noop (see #53696) and `Ty`
1879 // is still checked for WF.
1880 if bound_pred.bounds.is_empty() {
1881 if let ty::Param(_) = ty.sty {
1882 // This is a `where T:`, which can be in the HIR from the
1883 // transformation that moves `?Sized` to `T`'s declaration.
1884 // We can skip the predicate because type parameters are
1885 // trivially WF, but also we *should*, to avoid exposing
1886 // users who never wrote `where Type:,` themselves, to
1887 // compiler/tooling bugs from not handling WF predicates.
1889 let span = bound_pred.bounded_ty.span;
1890 let predicate = ty::OutlivesPredicate(ty, tcx.mk_region(ty::ReEmpty));
1892 (ty::Predicate::TypeOutlives(ty::Binder::dummy(predicate)), span)
1897 for bound in bound_pred.bounds.iter() {
1899 &hir::GenericBound::Trait(ref poly_trait_ref, _) => {
1900 let mut projections = Vec::new();
1902 let (trait_ref, _) = AstConv::instantiate_poly_trait_ref(
1910 iter::once((trait_ref.to_predicate(), poly_trait_ref.span)).chain(
1911 projections.iter().map(|&(p, span)| (p.to_predicate(), span)
1915 &hir::GenericBound::Outlives(ref lifetime) => {
1916 let region = AstConv::ast_region_to_region(&icx, lifetime, None);
1917 let pred = ty::Binder::bind(ty::OutlivesPredicate(ty, region));
1918 predicates.push((ty::Predicate::TypeOutlives(pred), lifetime.span))
1924 &hir::WherePredicate::RegionPredicate(ref region_pred) => {
1925 let r1 = AstConv::ast_region_to_region(&icx, ®ion_pred.lifetime, None);
1926 predicates.extend(region_pred.bounds.iter().map(|bound| {
1927 let (r2, span) = match bound {
1928 hir::GenericBound::Outlives(lt) => {
1929 (AstConv::ast_region_to_region(&icx, lt, None), lt.span)
1933 let pred = ty::Binder::bind(ty::OutlivesPredicate(r1, r2));
1935 (ty::Predicate::RegionOutlives(pred), span)
1939 &hir::WherePredicate::EqPredicate(..) => {
1945 // Add predicates from associated type bounds.
1946 if let Some((self_trait_ref, trait_items)) = is_trait {
1947 predicates.extend(trait_items.iter().flat_map(|trait_item_ref| {
1948 let trait_item = tcx.hir().trait_item(trait_item_ref.id);
1949 let bounds = match trait_item.node {
1950 hir::TraitItemKind::Type(ref bounds, _) => bounds,
1951 _ => return vec![].into_iter()
1955 tcx.mk_projection(tcx.hir().local_def_id(trait_item.id), self_trait_ref.substs);
1957 let bounds = compute_bounds(
1958 &ItemCtxt::new(tcx, def_id),
1961 SizedByDefault::Yes,
1965 bounds.predicates(tcx, assoc_ty).into_iter()
1969 let mut predicates = predicates.predicates;
1971 // Subtle: before we store the predicates into the tcx, we
1972 // sort them so that predicates like `T: Foo<Item=U>` come
1973 // before uses of `U`. This avoids false ambiguity errors
1974 // in trait checking. See `setup_constraining_predicates`
1976 if let Node::Item(&Item {
1977 node: ItemKind::Impl(..),
1981 let self_ty = tcx.type_of(def_id);
1982 let trait_ref = tcx.impl_trait_ref(def_id);
1983 ctp::setup_constraining_predicates(
1987 &mut ctp::parameters_for_impl(self_ty, trait_ref),
1991 let result = Lrc::new(ty::GenericPredicates {
1992 parent: generics.parent,
1995 debug!("explicit_predicates_of(def_id={:?}) = {:?}", def_id, result);
1999 pub enum SizedByDefault {
2004 /// Translate the AST's notion of ty param bounds (which are an enum consisting of a newtyped `Ty`
2005 /// or a region) to ty's notion of ty param bounds, which can either be user-defined traits, or the
2006 /// built-in trait `Send`.
2007 pub fn compute_bounds<'gcx: 'tcx, 'tcx>(
2008 astconv: &dyn AstConv<'gcx, 'tcx>,
2010 ast_bounds: &[hir::GenericBound],
2011 sized_by_default: SizedByDefault,
2014 let mut region_bounds = Vec::new();
2015 let mut trait_bounds = Vec::new();
2017 for ast_bound in ast_bounds {
2019 hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::None) => trait_bounds.push(b),
2020 hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => {}
2021 hir::GenericBound::Outlives(ref l) => region_bounds.push(l),
2025 let mut projection_bounds = Vec::new();
2027 let mut trait_bounds: Vec<_> = trait_bounds.iter().map(|&bound| {
2028 let (poly_trait_ref, _) = astconv.instantiate_poly_trait_ref(
2031 &mut projection_bounds,
2033 (poly_trait_ref, bound.span)
2036 let region_bounds = region_bounds
2038 .map(|r| (astconv.ast_region_to_region(r, None), r.span))
2041 trait_bounds.sort_by_key(|(t, _)| t.def_id());
2043 let implicitly_sized = if let SizedByDefault::Yes = sized_by_default {
2044 if !is_unsized(astconv, ast_bounds, span) {
2061 /// Converts a specific `GenericBound` from the AST into a set of
2062 /// predicates that apply to the self type. A vector is returned
2063 /// because this can be anywhere from zero predicates (`T: ?Sized` adds no
2064 /// predicates) to one (`T: Foo`) to many (`T: Bar<X=i32>` adds `T: Bar`
2065 /// and `<T as Bar>::X == i32`).
2066 fn predicates_from_bound<'tcx>(
2067 astconv: &dyn AstConv<'tcx, 'tcx>,
2069 bound: &hir::GenericBound,
2070 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2072 hir::GenericBound::Trait(ref tr, hir::TraitBoundModifier::None) => {
2073 let mut projections = Vec::new();
2074 let (pred, _) = astconv.instantiate_poly_trait_ref(tr, param_ty, &mut projections);
2075 iter::once((pred.to_predicate(), tr.span)).chain(
2078 .map(|(p, span)| (p.to_predicate(), span))
2081 hir::GenericBound::Outlives(ref lifetime) => {
2082 let region = astconv.ast_region_to_region(lifetime, None);
2083 let pred = ty::Binder::bind(ty::OutlivesPredicate(param_ty, region));
2084 vec![(ty::Predicate::TypeOutlives(pred), lifetime.span)]
2086 hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => vec![],
2090 fn compute_sig_of_foreign_fn_decl<'a, 'tcx>(
2091 tcx: TyCtxt<'a, 'tcx, 'tcx>,
2095 ) -> ty::PolyFnSig<'tcx> {
2096 let unsafety = if abi == abi::Abi::RustIntrinsic {
2097 intrisic_operation_unsafety(&*tcx.item_name(def_id).as_str())
2099 hir::Unsafety::Unsafe
2101 let fty = AstConv::ty_of_fn(&ItemCtxt::new(tcx, def_id), unsafety, abi, decl);
2103 // feature gate SIMD types in FFI, since I (huonw) am not sure the
2104 // ABIs are handled at all correctly.
2105 if abi != abi::Abi::RustIntrinsic
2106 && abi != abi::Abi::PlatformIntrinsic
2107 && !tcx.features().simd_ffi
2109 let check = |ast_ty: &hir::Ty, ty: Ty| {
2115 "use of SIMD type `{}` in FFI is highly experimental and \
2116 may result in invalid code",
2117 tcx.hir().node_to_pretty_string(ast_ty.id)
2120 .help("add #![feature(simd_ffi)] to the crate attributes to enable")
2124 for (input, ty) in decl.inputs.iter().zip(*fty.inputs().skip_binder()) {
2127 if let hir::Return(ref ty) = decl.output {
2128 check(&ty, *fty.output().skip_binder())
2135 fn is_foreign_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> bool {
2136 match tcx.hir().get_if_local(def_id) {
2137 Some(Node::ForeignItem(..)) => true,
2139 _ => bug!("is_foreign_item applied to non-local def-id {:?}", def_id),
2143 fn from_target_feature(
2146 attr: &ast::Attribute,
2147 whitelist: &FxHashMap<String, Option<String>>,
2148 target_features: &mut Vec<Symbol>,
2150 let list = match attr.meta_item_list() {
2154 let rust_features = tcx.features();
2156 // Only `enable = ...` is accepted in the meta item list
2157 if !item.check_name("enable") {
2158 let msg = "#[target_feature(..)] only accepts sub-keys of `enable` \
2160 tcx.sess.span_err(item.span, &msg);
2164 // Must be of the form `enable = "..."` ( a string)
2165 let value = match item.value_str() {
2166 Some(value) => value,
2168 let msg = "#[target_feature] attribute must be of the form \
2169 #[target_feature(enable = \"..\")]";
2170 tcx.sess.span_err(item.span, &msg);
2175 // We allow comma separation to enable multiple features
2176 target_features.extend(value.as_str().split(',').filter_map(|feature| {
2177 // Only allow whitelisted features per platform
2178 let feature_gate = match whitelist.get(feature) {
2182 "the feature named `{}` is not valid for \
2186 let mut err = tcx.sess.struct_span_err(item.span, &msg);
2188 if feature.starts_with("+") {
2189 let valid = whitelist.contains_key(&feature[1..]);
2191 err.help("consider removing the leading `+` in the feature name");
2199 // Only allow features whose feature gates have been enabled
2200 let allowed = match feature_gate.as_ref().map(|s| &**s) {
2201 Some("arm_target_feature") => rust_features.arm_target_feature,
2202 Some("aarch64_target_feature") => rust_features.aarch64_target_feature,
2203 Some("hexagon_target_feature") => rust_features.hexagon_target_feature,
2204 Some("powerpc_target_feature") => rust_features.powerpc_target_feature,
2205 Some("mips_target_feature") => rust_features.mips_target_feature,
2206 Some("avx512_target_feature") => rust_features.avx512_target_feature,
2207 Some("mmx_target_feature") => rust_features.mmx_target_feature,
2208 Some("sse4a_target_feature") => rust_features.sse4a_target_feature,
2209 Some("tbm_target_feature") => rust_features.tbm_target_feature,
2210 Some("wasm_target_feature") => rust_features.wasm_target_feature,
2211 Some("cmpxchg16b_target_feature") => rust_features.cmpxchg16b_target_feature,
2212 Some("adx_target_feature") => rust_features.adx_target_feature,
2213 Some("movbe_target_feature") => rust_features.movbe_target_feature,
2214 Some(name) => bug!("unknown target feature gate {}", name),
2217 if !allowed && id.is_local() {
2218 feature_gate::emit_feature_err(
2219 &tcx.sess.parse_sess,
2220 feature_gate.as_ref().unwrap(),
2222 feature_gate::GateIssue::Language,
2223 &format!("the target feature `{}` is currently unstable", feature),
2226 Some(Symbol::intern(feature))
2231 fn linkage_by_name<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId, name: &str) -> Linkage {
2232 use rustc::mir::mono::Linkage::*;
2234 // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
2235 // applicable to variable declarations and may not really make sense for
2236 // Rust code in the first place but whitelist them anyway and trust that
2237 // the user knows what s/he's doing. Who knows, unanticipated use cases
2238 // may pop up in the future.
2240 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
2241 // and don't have to be, LLVM treats them as no-ops.
2243 "appending" => Appending,
2244 "available_externally" => AvailableExternally,
2246 "extern_weak" => ExternalWeak,
2247 "external" => External,
2248 "internal" => Internal,
2249 "linkonce" => LinkOnceAny,
2250 "linkonce_odr" => LinkOnceODR,
2251 "private" => Private,
2253 "weak_odr" => WeakODR,
2255 let span = tcx.hir().span_if_local(def_id);
2256 if let Some(span) = span {
2257 tcx.sess.span_fatal(span, "invalid linkage specified")
2260 .fatal(&format!("invalid linkage specified: {}", name))
2266 fn codegen_fn_attrs<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, id: DefId) -> CodegenFnAttrs {
2267 let attrs = tcx.get_attrs(id);
2269 let mut codegen_fn_attrs = CodegenFnAttrs::new();
2271 let whitelist = tcx.target_features_whitelist(LOCAL_CRATE);
2273 let mut inline_span = None;
2274 for attr in attrs.iter() {
2275 if attr.check_name("cold") {
2276 codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD;
2277 } else if attr.check_name("allocator") {
2278 codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR;
2279 } else if attr.check_name("unwind") {
2280 codegen_fn_attrs.flags |= CodegenFnAttrFlags::UNWIND;
2281 } else if attr.check_name("rustc_allocator_nounwind") {
2282 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND;
2283 } else if attr.check_name("naked") {
2284 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED;
2285 } else if attr.check_name("no_mangle") {
2286 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2287 } else if attr.check_name("rustc_std_internal_symbol") {
2288 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2289 } else if attr.check_name("no_debug") {
2290 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_DEBUG;
2291 } else if attr.check_name("used") {
2292 codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED;
2293 } else if attr.check_name("thread_local") {
2294 codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL;
2295 } else if attr.check_name("export_name") {
2296 if let Some(s) = attr.value_str() {
2297 if s.as_str().contains("\0") {
2298 // `#[export_name = ...]` will be converted to a null-terminated string,
2299 // so it may not contain any null characters.
2304 "`export_name` may not contain null characters"
2307 codegen_fn_attrs.export_name = Some(s);
2309 } else if attr.check_name("target_feature") {
2310 if tcx.fn_sig(id).unsafety() == Unsafety::Normal {
2311 let msg = "#[target_feature(..)] can only be applied to \
2313 tcx.sess.span_err(attr.span, msg);
2315 from_target_feature(
2320 &mut codegen_fn_attrs.target_features,
2322 } else if attr.check_name("linkage") {
2323 if let Some(val) = attr.value_str() {
2324 codegen_fn_attrs.linkage = Some(linkage_by_name(tcx, id, &val.as_str()));
2326 } else if attr.check_name("link_section") {
2327 if let Some(val) = attr.value_str() {
2328 if val.as_str().bytes().any(|b| b == 0) {
2330 "illegal null byte in link_section \
2334 tcx.sess.span_err(attr.span, &msg);
2336 codegen_fn_attrs.link_section = Some(val);
2339 } else if attr.check_name("link_name") {
2340 codegen_fn_attrs.link_name = attr.value_str();
2344 codegen_fn_attrs.inline = attrs.iter().fold(InlineAttr::None, |ia, attr| {
2345 if attr.path != "inline" {
2348 match attr.meta().map(|i| i.node) {
2349 Some(MetaItemKind::Word) => {
2353 Some(MetaItemKind::List(ref items)) => {
2355 inline_span = Some(attr.span);
2356 if items.len() != 1 {
2358 tcx.sess.diagnostic(),
2361 "expected one argument"
2364 } else if list_contains_name(&items[..], "always") {
2366 } else if list_contains_name(&items[..], "never") {
2370 tcx.sess.diagnostic(),
2379 Some(MetaItemKind::NameValue(_)) => ia,
2384 codegen_fn_attrs.optimize = attrs.iter().fold(OptimizeAttr::None, |ia, attr| {
2385 if attr.path != "optimize" {
2388 let err = |sp, s| span_err!(tcx.sess.diagnostic(), sp, E0722, "{}", s);
2389 match attr.meta().map(|i| i.node) {
2390 Some(MetaItemKind::Word) => {
2391 err(attr.span, "expected one argument");
2394 Some(MetaItemKind::List(ref items)) => {
2396 inline_span = Some(attr.span);
2397 if items.len() != 1 {
2398 err(attr.span, "expected one argument");
2400 } else if list_contains_name(&items[..], "size") {
2402 } else if list_contains_name(&items[..], "speed") {
2405 err(items[0].span, "invalid argument");
2409 Some(MetaItemKind::NameValue(_)) => ia,
2414 // If a function uses #[target_feature] it can't be inlined into general
2415 // purpose functions as they wouldn't have the right target features
2416 // enabled. For that reason we also forbid #[inline(always)] as it can't be
2418 if codegen_fn_attrs.target_features.len() > 0 {
2419 if codegen_fn_attrs.inline == InlineAttr::Always {
2420 if let Some(span) = inline_span {
2423 "cannot use #[inline(always)] with \
2430 // Weak lang items have the same semantics as "std internal" symbols in the
2431 // sense that they're preserved through all our LTO passes and only
2432 // strippable by the linker.
2434 // Additionally weak lang items have predetermined symbol names.
2435 if tcx.is_weak_lang_item(id) {
2436 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2438 if let Some(name) = weak_lang_items::link_name(&attrs) {
2439 codegen_fn_attrs.export_name = Some(name);
2440 codegen_fn_attrs.link_name = Some(name);
2443 // Internal symbols to the standard library all have no_mangle semantics in
2444 // that they have defined symbol names present in the function name. This
2445 // also applies to weak symbols where they all have known symbol names.
2446 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
2447 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;