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 *inter-procedural* 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, SizedByDefault};
18 use crate::check::intrinsic::intrinsic_operation_unsafety;
19 use crate::constrained_generic_params as cgp;
21 use crate::middle::lang_items;
22 use crate::middle::resolve_lifetime as rl;
23 use rustc::hir::map::blocks::FnLikeNode;
24 use rustc::hir::map::Map;
25 use rustc::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
26 use rustc::mir::mono::Linkage;
27 use rustc::session::parse::feature_err;
28 use rustc::ty::query::Providers;
29 use rustc::ty::subst::{InternalSubsts, Subst};
30 use rustc::ty::util::Discr;
31 use rustc::ty::util::IntTypeExt;
32 use rustc::ty::{self, AdtKind, Const, ToPolyTraitRef, Ty, TyCtxt};
33 use rustc::ty::{ReprOptions, ToPredicate, WithConstness};
34 use rustc_attr::{list_contains_name, mark_used, InlineAttr, OptimizeAttr};
35 use rustc_data_structures::captures::Captures;
36 use rustc_data_structures::fx::FxHashMap;
37 use rustc_errors::{struct_span_err, Applicability};
39 use rustc_hir::def::{CtorKind, DefKind, Res};
40 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
41 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
42 use rustc_hir::{GenericParamKind, Node, Unsafety};
43 use rustc_span::symbol::{kw, sym, Symbol};
44 use rustc_span::{Span, DUMMY_SP};
45 use rustc_target::spec::abi;
47 use syntax::ast::{Ident, MetaItemKind};
51 struct OnlySelfBounds(bool);
53 ///////////////////////////////////////////////////////////////////////////
56 fn collect_mod_item_types(tcx: TyCtxt<'_>, module_def_id: DefId) {
57 tcx.hir().visit_item_likes_in_module(
59 &mut CollectItemTypesVisitor { tcx }.as_deep_visitor(),
63 pub fn provide(providers: &mut Providers<'_>) {
64 *providers = Providers {
65 type_of: type_of::type_of,
68 predicates_defined_on,
69 explicit_predicates_of,
71 type_param_predicates,
80 collect_mod_item_types,
85 ///////////////////////////////////////////////////////////////////////////
87 /// Context specific to some particular item. This is what implements
88 /// `AstConv`. It has information about the predicates that are defined
89 /// on the trait. Unfortunately, this predicate information is
90 /// available in various different forms at various points in the
91 /// process. So we can't just store a pointer to e.g., the AST or the
92 /// parsed ty form, we have to be more flexible. To this end, the
93 /// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy
94 /// `get_type_parameter_bounds` requests, drawing the information from
95 /// the AST (`hir::Generics`), recursively.
96 pub struct ItemCtxt<'tcx> {
101 ///////////////////////////////////////////////////////////////////////////
104 crate struct PlaceholderHirTyCollector(crate Vec<Span>);
106 impl<'v> Visitor<'v> for PlaceholderHirTyCollector {
109 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
110 NestedVisitorMap::None
112 fn visit_ty(&mut self, t: &'v hir::Ty<'v>) {
113 if let hir::TyKind::Infer = t.kind {
116 intravisit::walk_ty(self, t)
120 struct CollectItemTypesVisitor<'tcx> {
124 /// If there are any placeholder types (`_`), emit an error explaining that this is not allowed
125 /// and suggest adding type parameters in the appropriate place, taking into consideration any and
126 /// all already existing generic type parameters to avoid suggesting a name that is already in use.
127 crate fn placeholder_type_error(
130 generics: &[hir::GenericParam<'_>],
131 placeholder_types: Vec<Span>,
134 if placeholder_types.is_empty() {
137 // This is the whitelist of possible parameter names that we might suggest.
138 let possible_names = ["T", "K", "L", "A", "B", "C"];
139 let used_names = generics
141 .filter_map(|p| match p.name {
142 hir::ParamName::Plain(ident) => Some(ident.name),
145 .collect::<Vec<_>>();
147 let type_name = possible_names
149 .find(|n| !used_names.contains(&Symbol::intern(n)))
150 .unwrap_or(&"ParamName");
152 let mut sugg: Vec<_> =
153 placeholder_types.iter().map(|sp| (*sp, type_name.to_string())).collect();
154 if generics.is_empty() {
155 sugg.push((span, format!("<{}>", type_name)));
156 } else if let Some(arg) = generics.iter().find(|arg| match arg.name {
157 hir::ParamName::Plain(Ident { name: kw::Underscore, .. }) => true,
160 // Account for `_` already present in cases like `struct S<_>(_);` and suggest
161 // `struct S<T>(T);` instead of `struct S<_, T>(T);`.
162 sugg.push((arg.span, format!("{}", type_name)));
165 generics.iter().last().unwrap().span.shrink_to_hi(),
166 format!(", {}", type_name),
169 let mut err = bad_placeholder_type(tcx, placeholder_types);
171 err.multipart_suggestion(
172 "use type parameters instead",
174 Applicability::HasPlaceholders,
180 fn reject_placeholder_type_signatures_in_item(tcx: TyCtxt<'tcx>, item: &'tcx hir::Item<'tcx>) {
181 let (generics, suggest) = match &item.kind {
182 hir::ItemKind::Union(_, generics)
183 | hir::ItemKind::Enum(_, generics)
184 | hir::ItemKind::TraitAlias(generics, _)
185 | hir::ItemKind::Trait(_, _, generics, ..)
186 | hir::ItemKind::Impl { generics, .. }
187 | hir::ItemKind::Struct(_, generics) => (generics, true),
188 hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. })
189 | hir::ItemKind::TyAlias(_, generics) => (generics, false),
190 // `static`, `fn` and `const` are handled elsewhere to suggest appropriate type.
194 let mut visitor = PlaceholderHirTyCollector::default();
195 visitor.visit_item(item);
197 placeholder_type_error(tcx, generics.span, &generics.params[..], visitor.0, suggest);
200 impl Visitor<'tcx> for CollectItemTypesVisitor<'tcx> {
201 type Map = Map<'tcx>;
203 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
204 NestedVisitorMap::OnlyBodies(&self.tcx.hir())
207 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
208 convert_item(self.tcx, item.hir_id);
209 reject_placeholder_type_signatures_in_item(self.tcx, item);
210 intravisit::walk_item(self, item);
213 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
214 for param in generics.params {
216 hir::GenericParamKind::Lifetime { .. } => {}
217 hir::GenericParamKind::Type { default: Some(_), .. } => {
218 let def_id = self.tcx.hir().local_def_id(param.hir_id);
219 self.tcx.type_of(def_id);
221 hir::GenericParamKind::Type { .. } => {}
222 hir::GenericParamKind::Const { .. } => {
223 let def_id = self.tcx.hir().local_def_id(param.hir_id);
224 self.tcx.type_of(def_id);
228 intravisit::walk_generics(self, generics);
231 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
232 if let hir::ExprKind::Closure(..) = expr.kind {
233 let def_id = self.tcx.hir().local_def_id(expr.hir_id);
234 self.tcx.generics_of(def_id);
235 self.tcx.type_of(def_id);
237 intravisit::walk_expr(self, expr);
240 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
241 convert_trait_item(self.tcx, trait_item.hir_id);
242 intravisit::walk_trait_item(self, trait_item);
245 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
246 convert_impl_item(self.tcx, impl_item.hir_id);
247 intravisit::walk_impl_item(self, impl_item);
251 ///////////////////////////////////////////////////////////////////////////
252 // Utility types and common code for the above passes.
254 fn bad_placeholder_type(
256 mut spans: Vec<Span>,
257 ) -> rustc_errors::DiagnosticBuilder<'tcx> {
259 let mut err = struct_span_err!(
263 "the type placeholder `_` is not allowed within types on item signatures",
266 err.span_label(span, "not allowed in type signatures");
271 impl ItemCtxt<'tcx> {
272 pub fn new(tcx: TyCtxt<'tcx>, item_def_id: DefId) -> ItemCtxt<'tcx> {
273 ItemCtxt { tcx, item_def_id }
276 pub fn to_ty(&self, ast_ty: &'tcx hir::Ty<'tcx>) -> Ty<'tcx> {
277 AstConv::ast_ty_to_ty(self, ast_ty)
280 pub fn hir_id(&self) -> hir::HirId {
283 .as_local_hir_id(self.item_def_id)
284 .expect("Non-local call to local provider is_const_fn")
287 pub fn node(&self) -> hir::Node<'tcx> {
288 self.tcx.hir().get(self.hir_id())
292 impl AstConv<'tcx> for ItemCtxt<'tcx> {
293 fn tcx(&self) -> TyCtxt<'tcx> {
297 fn item_def_id(&self) -> Option<DefId> {
298 Some(self.item_def_id)
301 fn default_constness_for_trait_bounds(&self) -> hir::Constness {
302 if let Some(fn_like) = FnLikeNode::from_node(self.node()) {
305 hir::Constness::NotConst
309 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId) -> ty::GenericPredicates<'tcx> {
310 self.tcx.at(span).type_param_predicates((self.item_def_id, def_id))
313 fn re_infer(&self, _: Option<&ty::GenericParamDef>, _: Span) -> Option<ty::Region<'tcx>> {
317 fn allow_ty_infer(&self) -> bool {
321 fn ty_infer(&self, _: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx> {
322 self.tcx().sess.delay_span_bug(span, "bad placeholder type");
329 _: Option<&ty::GenericParamDef>,
331 ) -> &'tcx Const<'tcx> {
332 bad_placeholder_type(self.tcx(), vec![span]).emit();
334 self.tcx().consts.err
337 fn projected_ty_from_poly_trait_ref(
341 item_segment: &hir::PathSegment<'_>,
342 poly_trait_ref: ty::PolyTraitRef<'tcx>,
344 if let Some(trait_ref) = poly_trait_ref.no_bound_vars() {
345 let item_substs = <dyn AstConv<'tcx>>::create_substs_for_associated_item(
353 self.tcx().mk_projection(item_def_id, item_substs)
355 // There are no late-bound regions; we can just ignore the binder.
356 let mut err = struct_span_err!(
360 "cannot extract an associated type from a higher-ranked trait bound \
365 hir::Node::Field(_) | hir::Node::Ctor(_) | hir::Node::Variant(_) => {
367 self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(self.hir_id()));
369 hir::ItemKind::Enum(_, generics)
370 | hir::ItemKind::Struct(_, generics)
371 | hir::ItemKind::Union(_, generics) => {
372 // FIXME: look for an appropriate lt name if `'a` is already used
373 let (lt_sp, sugg) = match &generics.params[..] {
374 [] => (generics.span, "<'a>".to_string()),
375 [bound, ..] => (bound.span.shrink_to_lo(), "'a, ".to_string()),
377 let suggestions = vec![
383 // Replace the existing lifetimes with a new named lifetime.
385 .replace_late_bound_regions(&poly_trait_ref, |_| {
386 self.tcx.mk_region(ty::ReEarlyBound(
387 ty::EarlyBoundRegion {
390 name: Symbol::intern("'a"),
399 err.multipart_suggestion(
400 "use a fully qualified path with explicit lifetimes",
402 Applicability::MaybeIncorrect,
408 hir::Node::Item(hir::Item { kind: hir::ItemKind::Struct(..), .. })
409 | hir::Node::Item(hir::Item { kind: hir::ItemKind::Enum(..), .. })
410 | hir::Node::Item(hir::Item { kind: hir::ItemKind::Union(..), .. }) => {}
412 | hir::Node::ForeignItem(_)
413 | hir::Node::TraitItem(_)
414 | hir::Node::ImplItem(_) => {
417 "use a fully qualified path with inferred lifetimes",
420 // Erase named lt, we want `<A as B<'_>::C`, not `<A as B<'a>::C`.
421 self.tcx.anonymize_late_bound_regions(&poly_trait_ref).skip_binder(),
424 Applicability::MaybeIncorrect,
434 fn normalize_ty(&self, _span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
435 // Types in item signatures are not normalized to avoid undue dependencies.
439 fn set_tainted_by_errors(&self) {
440 // There's no obvious place to track this, so just let it go.
443 fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) {
444 // There's no place to record types from signatures?
448 /// Returns the predicates defined on `item_def_id` of the form
449 /// `X: Foo` where `X` is the type parameter `def_id`.
450 fn type_param_predicates(
452 (item_def_id, def_id): (DefId, DefId),
453 ) -> ty::GenericPredicates<'_> {
456 // In the AST, bounds can derive from two places. Either
457 // written inline like `<T: Foo>` or in a where-clause like
460 let param_id = tcx.hir().as_local_hir_id(def_id).unwrap();
461 let param_owner = tcx.hir().ty_param_owner(param_id);
462 let param_owner_def_id = tcx.hir().local_def_id(param_owner);
463 let generics = tcx.generics_of(param_owner_def_id);
464 let index = generics.param_def_id_to_index[&def_id];
465 let ty = tcx.mk_ty_param(index, tcx.hir().ty_param_name(param_id));
467 // Don't look for bounds where the type parameter isn't in scope.
469 if item_def_id == param_owner_def_id { None } else { tcx.generics_of(item_def_id).parent };
471 let mut result = parent
473 let icx = ItemCtxt::new(tcx, parent);
474 icx.get_type_parameter_bounds(DUMMY_SP, def_id)
476 .unwrap_or_default();
477 let mut extend = None;
479 let item_hir_id = tcx.hir().as_local_hir_id(item_def_id).unwrap();
480 let ast_generics = match tcx.hir().get(item_hir_id) {
481 Node::TraitItem(item) => &item.generics,
483 Node::ImplItem(item) => &item.generics,
485 Node::Item(item) => {
487 ItemKind::Fn(.., ref generics, _)
488 | ItemKind::Impl { ref generics, .. }
489 | ItemKind::TyAlias(_, ref generics)
490 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
491 | ItemKind::Enum(_, ref generics)
492 | ItemKind::Struct(_, ref generics)
493 | ItemKind::Union(_, ref generics) => generics,
494 ItemKind::Trait(_, _, ref generics, ..) => {
495 // Implied `Self: Trait` and supertrait bounds.
496 if param_id == item_hir_id {
497 let identity_trait_ref = ty::TraitRef::identity(tcx, item_def_id);
499 Some((identity_trait_ref.without_const().to_predicate(), item.span));
507 Node::ForeignItem(item) => match item.kind {
508 ForeignItemKind::Fn(_, _, ref generics) => generics,
515 let icx = ItemCtxt::new(tcx, item_def_id);
516 let extra_predicates = extend.into_iter().chain(
517 icx.type_parameter_bounds_in_generics(ast_generics, param_id, ty, OnlySelfBounds(true))
519 .filter(|(predicate, _)| match predicate {
520 ty::Predicate::Trait(ref data, _) => data.skip_binder().self_ty().is_param(index),
525 tcx.arena.alloc_from_iter(result.predicates.iter().copied().chain(extra_predicates));
529 impl ItemCtxt<'tcx> {
530 /// Finds bounds from `hir::Generics`. This requires scanning through the
531 /// AST. We do this to avoid having to convert *all* the bounds, which
532 /// would create artificial cycles. Instead, we can only convert the
533 /// bounds for a type parameter `X` if `X::Foo` is used.
534 fn type_parameter_bounds_in_generics(
536 ast_generics: &'tcx hir::Generics<'tcx>,
537 param_id: hir::HirId,
539 only_self_bounds: OnlySelfBounds,
540 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
541 let constness = self.default_constness_for_trait_bounds();
542 let from_ty_params = ast_generics
545 .filter_map(|param| match param.kind {
546 GenericParamKind::Type { .. } if param.hir_id == param_id => Some(¶m.bounds),
549 .flat_map(|bounds| bounds.iter())
550 .flat_map(|b| predicates_from_bound(self, ty, b, constness));
552 let from_where_clauses = ast_generics
556 .filter_map(|wp| match *wp {
557 hir::WherePredicate::BoundPredicate(ref bp) => Some(bp),
561 let bt = if is_param(self.tcx, &bp.bounded_ty, param_id) {
563 } else if !only_self_bounds.0 {
564 Some(self.to_ty(&bp.bounded_ty))
568 bp.bounds.iter().filter_map(move |b| bt.map(|bt| (bt, b)))
570 .flat_map(|(bt, b)| predicates_from_bound(self, bt, b, constness));
572 from_ty_params.chain(from_where_clauses).collect()
576 /// Tests whether this is the AST for a reference to the type
577 /// parameter with ID `param_id`. We use this so as to avoid running
578 /// `ast_ty_to_ty`, because we want to avoid triggering an all-out
579 /// conversion of the type to avoid inducing unnecessary cycles.
580 fn is_param(tcx: TyCtxt<'_>, ast_ty: &hir::Ty<'_>, param_id: hir::HirId) -> bool {
581 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = ast_ty.kind {
583 Res::SelfTy(Some(def_id), None) | Res::Def(DefKind::TyParam, def_id) => {
584 def_id == tcx.hir().local_def_id(param_id)
593 fn convert_item(tcx: TyCtxt<'_>, item_id: hir::HirId) {
594 let it = tcx.hir().expect_item(item_id);
595 debug!("convert: item {} with id {}", it.ident, it.hir_id);
596 let def_id = tcx.hir().local_def_id(item_id);
598 // These don't define types.
599 hir::ItemKind::ExternCrate(_)
600 | hir::ItemKind::Use(..)
601 | hir::ItemKind::Mod(_)
602 | hir::ItemKind::GlobalAsm(_) => {}
603 hir::ItemKind::ForeignMod(ref foreign_mod) => {
604 for item in foreign_mod.items {
605 let def_id = tcx.hir().local_def_id(item.hir_id);
606 tcx.generics_of(def_id);
608 tcx.predicates_of(def_id);
609 if let hir::ForeignItemKind::Fn(..) = item.kind {
614 hir::ItemKind::Enum(ref enum_definition, _) => {
615 tcx.generics_of(def_id);
617 tcx.predicates_of(def_id);
618 convert_enum_variant_types(tcx, def_id, &enum_definition.variants);
620 hir::ItemKind::Impl { .. } => {
621 tcx.generics_of(def_id);
623 tcx.impl_trait_ref(def_id);
624 tcx.predicates_of(def_id);
626 hir::ItemKind::Trait(..) => {
627 tcx.generics_of(def_id);
628 tcx.trait_def(def_id);
629 tcx.at(it.span).super_predicates_of(def_id);
630 tcx.predicates_of(def_id);
632 hir::ItemKind::TraitAlias(..) => {
633 tcx.generics_of(def_id);
634 tcx.at(it.span).super_predicates_of(def_id);
635 tcx.predicates_of(def_id);
637 hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
638 tcx.generics_of(def_id);
640 tcx.predicates_of(def_id);
642 for f in struct_def.fields() {
643 let def_id = tcx.hir().local_def_id(f.hir_id);
644 tcx.generics_of(def_id);
646 tcx.predicates_of(def_id);
649 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
650 convert_variant_ctor(tcx, ctor_hir_id);
654 // Desugared from `impl Trait`, so visited by the function's return type.
655 hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: Some(_), .. }) => {}
657 hir::ItemKind::OpaqueTy(..)
658 | hir::ItemKind::TyAlias(..)
659 | hir::ItemKind::Static(..)
660 | hir::ItemKind::Const(..)
661 | hir::ItemKind::Fn(..) => {
662 tcx.generics_of(def_id);
664 tcx.predicates_of(def_id);
665 if let hir::ItemKind::Fn(..) = it.kind {
672 fn convert_trait_item(tcx: TyCtxt<'_>, trait_item_id: hir::HirId) {
673 let trait_item = tcx.hir().expect_trait_item(trait_item_id);
674 let def_id = tcx.hir().local_def_id(trait_item.hir_id);
675 tcx.generics_of(def_id);
677 match trait_item.kind {
678 hir::TraitItemKind::Const(..)
679 | hir::TraitItemKind::Type(_, Some(_))
680 | hir::TraitItemKind::Method(..) => {
682 if let hir::TraitItemKind::Method(..) = trait_item.kind {
687 hir::TraitItemKind::Type(_, None) => {}
690 tcx.predicates_of(def_id);
693 fn convert_impl_item(tcx: TyCtxt<'_>, impl_item_id: hir::HirId) {
694 let def_id = tcx.hir().local_def_id(impl_item_id);
695 tcx.generics_of(def_id);
697 tcx.predicates_of(def_id);
698 if let hir::ImplItemKind::Method(..) = tcx.hir().expect_impl_item(impl_item_id).kind {
703 fn convert_variant_ctor(tcx: TyCtxt<'_>, ctor_id: hir::HirId) {
704 let def_id = tcx.hir().local_def_id(ctor_id);
705 tcx.generics_of(def_id);
707 tcx.predicates_of(def_id);
710 fn convert_enum_variant_types(tcx: TyCtxt<'_>, def_id: DefId, variants: &[hir::Variant<'_>]) {
711 let def = tcx.adt_def(def_id);
712 let repr_type = def.repr.discr_type();
713 let initial = repr_type.initial_discriminant(tcx);
714 let mut prev_discr = None::<Discr<'_>>;
716 // fill the discriminant values and field types
717 for variant in variants {
718 let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
720 if let Some(ref e) = variant.disr_expr {
721 let expr_did = tcx.hir().local_def_id(e.hir_id);
722 def.eval_explicit_discr(tcx, expr_did)
723 } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) {
726 struct_span_err!(tcx.sess, variant.span, E0370, "enum discriminant overflowed")
729 format!("overflowed on value after {}", prev_discr.unwrap()),
732 "explicitly set `{} = {}` if that is desired outcome",
733 variant.ident, wrapped_discr
738 .unwrap_or(wrapped_discr),
741 for f in variant.data.fields() {
742 let def_id = tcx.hir().local_def_id(f.hir_id);
743 tcx.generics_of(def_id);
745 tcx.predicates_of(def_id);
748 // Convert the ctor, if any. This also registers the variant as
750 if let Some(ctor_hir_id) = variant.data.ctor_hir_id() {
751 convert_variant_ctor(tcx, ctor_hir_id);
758 variant_did: Option<DefId>,
759 ctor_did: Option<DefId>,
761 discr: ty::VariantDiscr,
762 def: &hir::VariantData<'_>,
763 adt_kind: ty::AdtKind,
765 ) -> ty::VariantDef {
766 let mut seen_fields: FxHashMap<ast::Ident, Span> = Default::default();
767 let hir_id = tcx.hir().as_local_hir_id(variant_did.unwrap_or(parent_did)).unwrap();
772 let fid = tcx.hir().local_def_id(f.hir_id);
773 let dup_span = seen_fields.get(&f.ident.modern()).cloned();
774 if let Some(prev_span) = dup_span {
779 "field `{}` is already declared",
782 .span_label(f.span, "field already declared")
783 .span_label(prev_span, format!("`{}` first declared here", f.ident))
786 seen_fields.insert(f.ident.modern(), f.span);
792 vis: ty::Visibility::from_hir(&f.vis, hir_id, tcx),
796 let recovered = match def {
797 hir::VariantData::Struct(_, r) => *r,
807 CtorKind::from_hir(def),
814 fn adt_def(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::AdtDef {
817 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
818 let item = match tcx.hir().get(hir_id) {
819 Node::Item(item) => item,
823 let repr = ReprOptions::new(tcx, def_id);
824 let (kind, variants) = match item.kind {
825 ItemKind::Enum(ref def, _) => {
826 let mut distance_from_explicit = 0;
831 let variant_did = Some(tcx.hir().local_def_id(v.id));
833 v.data.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
835 let discr = if let Some(ref e) = v.disr_expr {
836 distance_from_explicit = 0;
837 ty::VariantDiscr::Explicit(tcx.hir().local_def_id(e.hir_id))
839 ty::VariantDiscr::Relative(distance_from_explicit)
841 distance_from_explicit += 1;
856 (AdtKind::Enum, variants)
858 ItemKind::Struct(ref def, _) => {
859 let variant_did = None;
860 let ctor_did = def.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
862 let variants = std::iter::once(convert_variant(
867 ty::VariantDiscr::Relative(0),
874 (AdtKind::Struct, variants)
876 ItemKind::Union(ref def, _) => {
877 let variant_did = None;
878 let ctor_did = def.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
880 let variants = std::iter::once(convert_variant(
885 ty::VariantDiscr::Relative(0),
892 (AdtKind::Union, variants)
896 tcx.alloc_adt_def(def_id, kind, variants, repr)
899 /// Ensures that the super-predicates of the trait with a `DefId`
900 /// of `trait_def_id` are converted and stored. This also ensures that
901 /// the transitive super-predicates are converted.
902 fn super_predicates_of(tcx: TyCtxt<'_>, trait_def_id: DefId) -> ty::GenericPredicates<'_> {
903 debug!("super_predicates(trait_def_id={:?})", trait_def_id);
904 let trait_hir_id = tcx.hir().as_local_hir_id(trait_def_id).unwrap();
906 let item = match tcx.hir().get(trait_hir_id) {
907 Node::Item(item) => item,
908 _ => bug!("trait_node_id {} is not an item", trait_hir_id),
911 let (generics, bounds) = match item.kind {
912 hir::ItemKind::Trait(.., ref generics, ref supertraits, _) => (generics, supertraits),
913 hir::ItemKind::TraitAlias(ref generics, ref supertraits) => (generics, supertraits),
914 _ => span_bug!(item.span, "super_predicates invoked on non-trait"),
917 let icx = ItemCtxt::new(tcx, trait_def_id);
919 // Convert the bounds that follow the colon, e.g., `Bar + Zed` in `trait Foo: Bar + Zed`.
920 let self_param_ty = tcx.types.self_param;
922 AstConv::compute_bounds(&icx, self_param_ty, bounds, SizedByDefault::No, item.span);
924 let superbounds1 = superbounds1.predicates(tcx, self_param_ty);
926 // Convert any explicit superbounds in the where-clause,
927 // e.g., `trait Foo where Self: Bar`.
928 // In the case of trait aliases, however, we include all bounds in the where-clause,
929 // so e.g., `trait Foo = where u32: PartialEq<Self>` would include `u32: PartialEq<Self>`
930 // as one of its "superpredicates".
931 let is_trait_alias = tcx.is_trait_alias(trait_def_id);
932 let superbounds2 = icx.type_parameter_bounds_in_generics(
936 OnlySelfBounds(!is_trait_alias),
939 // Combine the two lists to form the complete set of superbounds:
940 let superbounds = &*tcx.arena.alloc_from_iter(superbounds1.into_iter().chain(superbounds2));
942 // Now require that immediate supertraits are converted,
943 // which will, in turn, reach indirect supertraits.
944 for &(pred, span) in superbounds {
945 debug!("superbound: {:?}", pred);
946 if let ty::Predicate::Trait(bound, _) = pred {
947 tcx.at(span).super_predicates_of(bound.def_id());
951 ty::GenericPredicates { parent: None, predicates: superbounds }
954 fn trait_def(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::TraitDef {
955 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
956 let item = tcx.hir().expect_item(hir_id);
958 let (is_auto, unsafety) = match item.kind {
959 hir::ItemKind::Trait(is_auto, unsafety, ..) => (is_auto == hir::IsAuto::Yes, unsafety),
960 hir::ItemKind::TraitAlias(..) => (false, hir::Unsafety::Normal),
961 _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
964 let paren_sugar = tcx.has_attr(def_id, sym::rustc_paren_sugar);
965 if paren_sugar && !tcx.features().unboxed_closures {
969 "the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \
970 which traits can use parenthetical notation",
972 .help("add `#![feature(unboxed_closures)]` to the crate attributes to use it")
976 let is_marker = tcx.has_attr(def_id, sym::marker);
977 let def_path_hash = tcx.def_path_hash(def_id);
978 let def = ty::TraitDef::new(def_id, unsafety, paren_sugar, is_auto, is_marker, def_path_hash);
982 fn has_late_bound_regions<'tcx>(tcx: TyCtxt<'tcx>, node: Node<'tcx>) -> Option<Span> {
983 struct LateBoundRegionsDetector<'tcx> {
985 outer_index: ty::DebruijnIndex,
986 has_late_bound_regions: Option<Span>,
989 impl Visitor<'tcx> for LateBoundRegionsDetector<'tcx> {
990 type Map = Map<'tcx>;
992 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
993 NestedVisitorMap::None
996 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
997 if self.has_late_bound_regions.is_some() {
1001 hir::TyKind::BareFn(..) => {
1002 self.outer_index.shift_in(1);
1003 intravisit::walk_ty(self, ty);
1004 self.outer_index.shift_out(1);
1006 _ => intravisit::walk_ty(self, ty),
1010 fn visit_poly_trait_ref(
1012 tr: &'tcx hir::PolyTraitRef<'tcx>,
1013 m: hir::TraitBoundModifier,
1015 if self.has_late_bound_regions.is_some() {
1018 self.outer_index.shift_in(1);
1019 intravisit::walk_poly_trait_ref(self, tr, m);
1020 self.outer_index.shift_out(1);
1023 fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
1024 if self.has_late_bound_regions.is_some() {
1028 match self.tcx.named_region(lt.hir_id) {
1029 Some(rl::Region::Static) | Some(rl::Region::EarlyBound(..)) => {}
1030 Some(rl::Region::LateBound(debruijn, _, _))
1031 | Some(rl::Region::LateBoundAnon(debruijn, _))
1032 if debruijn < self.outer_index => {}
1033 Some(rl::Region::LateBound(..))
1034 | Some(rl::Region::LateBoundAnon(..))
1035 | Some(rl::Region::Free(..))
1037 self.has_late_bound_regions = Some(lt.span);
1043 fn has_late_bound_regions<'tcx>(
1045 generics: &'tcx hir::Generics<'tcx>,
1046 decl: &'tcx hir::FnDecl<'tcx>,
1048 let mut visitor = LateBoundRegionsDetector {
1050 outer_index: ty::INNERMOST,
1051 has_late_bound_regions: None,
1053 for param in generics.params {
1054 if let GenericParamKind::Lifetime { .. } = param.kind {
1055 if tcx.is_late_bound(param.hir_id) {
1056 return Some(param.span);
1060 visitor.visit_fn_decl(decl);
1061 visitor.has_late_bound_regions
1065 Node::TraitItem(item) => match item.kind {
1066 hir::TraitItemKind::Method(ref sig, _) => {
1067 has_late_bound_regions(tcx, &item.generics, &sig.decl)
1071 Node::ImplItem(item) => match item.kind {
1072 hir::ImplItemKind::Method(ref sig, _) => {
1073 has_late_bound_regions(tcx, &item.generics, &sig.decl)
1077 Node::ForeignItem(item) => match item.kind {
1078 hir::ForeignItemKind::Fn(ref fn_decl, _, ref generics) => {
1079 has_late_bound_regions(tcx, generics, fn_decl)
1083 Node::Item(item) => match item.kind {
1084 hir::ItemKind::Fn(ref sig, .., ref generics, _) => {
1085 has_late_bound_regions(tcx, generics, &sig.decl)
1093 fn generics_of(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::Generics {
1096 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1098 let node = tcx.hir().get(hir_id);
1099 let parent_def_id = match node {
1101 | Node::TraitItem(_)
1104 | Node::Field(_) => {
1105 let parent_id = tcx.hir().get_parent_item(hir_id);
1106 Some(tcx.hir().local_def_id(parent_id))
1108 // FIXME(#43408) enable this always when we get lazy normalization.
1109 Node::AnonConst(_) => {
1110 // HACK(eddyb) this provides the correct generics when
1111 // `feature(const_generics)` is enabled, so that const expressions
1112 // used with const generics, e.g. `Foo<{N+1}>`, can work at all.
1113 if tcx.features().const_generics {
1114 let parent_id = tcx.hir().get_parent_item(hir_id);
1115 Some(tcx.hir().local_def_id(parent_id))
1120 Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => {
1121 Some(tcx.closure_base_def_id(def_id))
1123 Node::Item(item) => match item.kind {
1124 ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn, .. }) => {
1125 impl_trait_fn.or_else(|| {
1126 let parent_id = tcx.hir().get_parent_item(hir_id);
1127 if parent_id != hir_id && parent_id != CRATE_HIR_ID {
1128 debug!("generics_of: parent of opaque ty {:?} is {:?}", def_id, parent_id);
1129 // If this 'impl Trait' is nested inside another 'impl Trait'
1130 // (e.g. `impl Foo<MyType = impl Bar<A>>`), we need to use the 'parent'
1131 // 'impl Trait' for its generic parameters, since we can reference them
1132 // from the 'child' 'impl Trait'
1133 if let Node::Item(hir::Item { kind: ItemKind::OpaqueTy(..), .. }) =
1134 tcx.hir().get(parent_id)
1136 Some(tcx.hir().local_def_id(parent_id))
1150 let mut opt_self = None;
1151 let mut allow_defaults = false;
1153 let no_generics = hir::Generics::empty();
1154 let ast_generics = match node {
1155 Node::TraitItem(item) => &item.generics,
1157 Node::ImplItem(item) => &item.generics,
1159 Node::Item(item) => {
1161 ItemKind::Fn(.., ref generics, _) | ItemKind::Impl { ref generics, .. } => generics,
1163 ItemKind::TyAlias(_, ref generics)
1164 | ItemKind::Enum(_, ref generics)
1165 | ItemKind::Struct(_, ref generics)
1166 | ItemKind::OpaqueTy(hir::OpaqueTy { ref generics, .. })
1167 | ItemKind::Union(_, ref generics) => {
1168 allow_defaults = true;
1172 ItemKind::Trait(_, _, ref generics, ..)
1173 | ItemKind::TraitAlias(ref generics, ..) => {
1174 // Add in the self type parameter.
1176 // Something of a hack: use the node id for the trait, also as
1177 // the node id for the Self type parameter.
1178 let param_id = item.hir_id;
1180 opt_self = Some(ty::GenericParamDef {
1182 name: kw::SelfUpper,
1183 def_id: tcx.hir().local_def_id(param_id),
1184 pure_wrt_drop: false,
1185 kind: ty::GenericParamDefKind::Type {
1187 object_lifetime_default: rl::Set1::Empty,
1192 allow_defaults = true;
1200 Node::ForeignItem(item) => match item.kind {
1201 ForeignItemKind::Static(..) => &no_generics,
1202 ForeignItemKind::Fn(_, _, ref generics) => generics,
1203 ForeignItemKind::Type => &no_generics,
1209 let has_self = opt_self.is_some();
1210 let mut parent_has_self = false;
1211 let mut own_start = has_self as u32;
1212 let parent_count = parent_def_id.map_or(0, |def_id| {
1213 let generics = tcx.generics_of(def_id);
1214 assert_eq!(has_self, false);
1215 parent_has_self = generics.has_self;
1216 own_start = generics.count() as u32;
1217 generics.parent_count + generics.params.len()
1220 let mut params: Vec<_> = opt_self.into_iter().collect();
1222 let early_lifetimes = early_bound_lifetimes_from_generics(tcx, ast_generics);
1223 params.extend(early_lifetimes.enumerate().map(|(i, param)| ty::GenericParamDef {
1224 name: param.name.ident().name,
1225 index: own_start + i as u32,
1226 def_id: tcx.hir().local_def_id(param.hir_id),
1227 pure_wrt_drop: param.pure_wrt_drop,
1228 kind: ty::GenericParamDefKind::Lifetime,
1231 let object_lifetime_defaults = tcx.object_lifetime_defaults(hir_id);
1233 // Now create the real type parameters.
1234 let type_start = own_start - has_self as u32 + params.len() as u32;
1236 params.extend(ast_generics.params.iter().filter_map(|param| {
1237 let kind = match param.kind {
1238 GenericParamKind::Type { ref default, synthetic, .. } => {
1239 if !allow_defaults && default.is_some() {
1240 if !tcx.features().default_type_parameter_fallback {
1241 tcx.struct_span_lint_hir(
1242 lint::builtin::INVALID_TYPE_PARAM_DEFAULT,
1246 lint.build(&format!(
1247 "defaults for type parameters are only allowed in \
1248 `struct`, `enum`, `type`, or `trait` definitions."
1256 ty::GenericParamDefKind::Type {
1257 has_default: default.is_some(),
1258 object_lifetime_default: object_lifetime_defaults
1260 .map_or(rl::Set1::Empty, |o| o[i]),
1264 GenericParamKind::Const { .. } => ty::GenericParamDefKind::Const,
1268 let param_def = ty::GenericParamDef {
1269 index: type_start + i as u32,
1270 name: param.name.ident().name,
1271 def_id: tcx.hir().local_def_id(param.hir_id),
1272 pure_wrt_drop: param.pure_wrt_drop,
1279 // provide junk type parameter defs - the only place that
1280 // cares about anything but the length is instantiation,
1281 // and we don't do that for closures.
1282 if let Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(.., gen), .. }) = node {
1283 let dummy_args = if gen.is_some() {
1284 &["<resume_ty>", "<yield_ty>", "<return_ty>", "<witness>"][..]
1286 &["<closure_kind>", "<closure_signature>"][..]
1289 params.extend(dummy_args.iter().enumerate().map(|(i, &arg)| ty::GenericParamDef {
1290 index: type_start + i as u32,
1291 name: Symbol::intern(arg),
1293 pure_wrt_drop: false,
1294 kind: ty::GenericParamDefKind::Type {
1296 object_lifetime_default: rl::Set1::Empty,
1301 if let Some(upvars) = tcx.upvars(def_id) {
1302 params.extend(upvars.iter().zip((dummy_args.len() as u32)..).map(|(_, i)| {
1303 ty::GenericParamDef {
1304 index: type_start + i,
1305 name: Symbol::intern("<upvar>"),
1307 pure_wrt_drop: false,
1308 kind: ty::GenericParamDefKind::Type {
1310 object_lifetime_default: rl::Set1::Empty,
1318 let param_def_id_to_index = params.iter().map(|param| (param.def_id, param.index)).collect();
1320 tcx.arena.alloc(ty::Generics {
1321 parent: parent_def_id,
1324 param_def_id_to_index,
1325 has_self: has_self || parent_has_self,
1326 has_late_bound_regions: has_late_bound_regions(tcx, node),
1330 fn are_suggestable_generic_args(generic_args: &[hir::GenericArg<'_>]) -> bool {
1333 .filter_map(|arg| match arg {
1334 hir::GenericArg::Type(ty) => Some(ty),
1337 .any(is_suggestable_infer_ty)
1340 /// Whether `ty` is a type with `_` placeholders that can be infered. Used in diagnostics only to
1341 /// use inference to provide suggestions for the appropriate type if possible.
1342 fn is_suggestable_infer_ty(ty: &hir::Ty<'_>) -> bool {
1346 Slice(ty) | Array(ty, _) => is_suggestable_infer_ty(ty),
1347 Tup(tys) => tys.iter().any(is_suggestable_infer_ty),
1348 Ptr(mut_ty) | Rptr(_, mut_ty) => is_suggestable_infer_ty(mut_ty.ty),
1349 Def(_, generic_args) => are_suggestable_generic_args(generic_args),
1350 Path(hir::QPath::TypeRelative(ty, segment)) => {
1351 is_suggestable_infer_ty(ty) || are_suggestable_generic_args(segment.generic_args().args)
1353 Path(hir::QPath::Resolved(ty_opt, hir::Path { segments, .. })) => {
1354 ty_opt.map_or(false, is_suggestable_infer_ty)
1357 .any(|segment| are_suggestable_generic_args(segment.generic_args().args))
1363 pub fn get_infer_ret_ty(output: &'hir hir::FnRetTy<'hir>) -> Option<&'hir hir::Ty<'hir>> {
1364 if let hir::FnRetTy::Return(ref ty) = output {
1365 if is_suggestable_infer_ty(ty) {
1372 fn fn_sig(tcx: TyCtxt<'_>, def_id: DefId) -> ty::PolyFnSig<'_> {
1373 use rustc_hir::Node::*;
1376 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1378 let icx = ItemCtxt::new(tcx, def_id);
1380 match tcx.hir().get(hir_id) {
1381 TraitItem(hir::TraitItem {
1382 kind: TraitItemKind::Method(sig, TraitMethod::Provided(_)),
1387 | ImplItem(hir::ImplItem { kind: ImplItemKind::Method(sig, _), ident, generics, .. })
1388 | Item(hir::Item { kind: ItemKind::Fn(sig, generics, _), ident, .. }) => {
1389 match get_infer_ret_ty(&sig.decl.output) {
1391 let fn_sig = tcx.typeck_tables_of(def_id).liberated_fn_sigs()[hir_id];
1392 let mut visitor = PlaceholderHirTyCollector::default();
1393 visitor.visit_ty(ty);
1394 let mut diag = bad_placeholder_type(tcx, visitor.0);
1395 let ret_ty = fn_sig.output();
1396 if ret_ty != tcx.types.err {
1397 diag.span_suggestion(
1399 "replace with the correct return type",
1401 Applicability::MaybeIncorrect,
1405 ty::Binder::bind(fn_sig)
1407 None => AstConv::ty_of_fn(
1409 sig.header.unsafety,
1412 &generics.params[..],
1418 TraitItem(hir::TraitItem {
1419 kind: TraitItemKind::Method(FnSig { header, decl }, _),
1423 }) => AstConv::ty_of_fn(
1428 &generics.params[..],
1432 ForeignItem(&hir::ForeignItem { kind: ForeignItemKind::Fn(ref fn_decl, _, _), .. }) => {
1433 let abi = tcx.hir().get_foreign_abi(hir_id);
1434 compute_sig_of_foreign_fn_decl(tcx, def_id, fn_decl, abi)
1437 Ctor(data) | Variant(hir::Variant { data, .. }) if data.ctor_hir_id().is_some() => {
1438 let ty = tcx.type_of(tcx.hir().get_parent_did(hir_id));
1440 data.fields().iter().map(|f| tcx.type_of(tcx.hir().local_def_id(f.hir_id)));
1441 ty::Binder::bind(tcx.mk_fn_sig(
1445 hir::Unsafety::Normal,
1450 Expr(&hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => {
1451 // Closure signatures are not like other function
1452 // signatures and cannot be accessed through `fn_sig`. For
1453 // example, a closure signature excludes the `self`
1454 // argument. In any case they are embedded within the
1455 // closure type as part of the `ClosureSubsts`.
1458 // the signature of a closure, you should use the
1459 // `closure_sig` method on the `ClosureSubsts`:
1461 // closure_substs.sig(def_id, tcx)
1463 // or, inside of an inference context, you can use
1465 // infcx.closure_sig(def_id, closure_substs)
1466 bug!("to get the signature of a closure, use `closure_sig()` not `fn_sig()`");
1470 bug!("unexpected sort of node in fn_sig(): {:?}", x);
1475 fn impl_trait_ref(tcx: TyCtxt<'_>, def_id: DefId) -> Option<ty::TraitRef<'_>> {
1476 let icx = ItemCtxt::new(tcx, def_id);
1478 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1479 match tcx.hir().expect_item(hir_id).kind {
1480 hir::ItemKind::Impl { ref of_trait, .. } => of_trait.as_ref().map(|ast_trait_ref| {
1481 let selfty = tcx.type_of(def_id);
1482 AstConv::instantiate_mono_trait_ref(&icx, ast_trait_ref, selfty)
1488 fn impl_polarity(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ImplPolarity {
1489 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1490 let is_rustc_reservation = tcx.has_attr(def_id, sym::rustc_reservation_impl);
1491 let item = tcx.hir().expect_item(hir_id);
1493 hir::ItemKind::Impl { polarity: hir::ImplPolarity::Negative, .. } => {
1494 if is_rustc_reservation {
1495 tcx.sess.span_err(item.span, "reservation impls can't be negative");
1497 ty::ImplPolarity::Negative
1499 hir::ItemKind::Impl { polarity: hir::ImplPolarity::Positive, of_trait: None, .. } => {
1500 if is_rustc_reservation {
1501 tcx.sess.span_err(item.span, "reservation impls can't be inherent");
1503 ty::ImplPolarity::Positive
1505 hir::ItemKind::Impl {
1506 polarity: hir::ImplPolarity::Positive, of_trait: Some(_), ..
1508 if is_rustc_reservation {
1509 ty::ImplPolarity::Reservation
1511 ty::ImplPolarity::Positive
1514 ref item => bug!("impl_polarity: {:?} not an impl", item),
1518 /// Returns the early-bound lifetimes declared in this generics
1519 /// listing. For anything other than fns/methods, this is just all
1520 /// the lifetimes that are declared. For fns or methods, we have to
1521 /// screen out those that do not appear in any where-clauses etc using
1522 /// `resolve_lifetime::early_bound_lifetimes`.
1523 fn early_bound_lifetimes_from_generics<'a, 'tcx: 'a>(
1525 generics: &'a hir::Generics<'a>,
1526 ) -> impl Iterator<Item = &'a hir::GenericParam<'a>> + Captures<'tcx> {
1527 generics.params.iter().filter(move |param| match param.kind {
1528 GenericParamKind::Lifetime { .. } => !tcx.is_late_bound(param.hir_id),
1533 /// Returns a list of type predicates for the definition with ID `def_id`, including inferred
1534 /// lifetime constraints. This includes all predicates returned by `explicit_predicates_of`, plus
1535 /// inferred constraints concerning which regions outlive other regions.
1536 fn predicates_defined_on(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1537 debug!("predicates_defined_on({:?})", def_id);
1538 let mut result = tcx.explicit_predicates_of(def_id);
1539 debug!("predicates_defined_on: explicit_predicates_of({:?}) = {:?}", def_id, result,);
1540 let inferred_outlives = tcx.inferred_outlives_of(def_id);
1541 if !inferred_outlives.is_empty() {
1543 "predicates_defined_on: inferred_outlives_of({:?}) = {:?}",
1544 def_id, inferred_outlives,
1546 if result.predicates.is_empty() {
1547 result.predicates = inferred_outlives;
1549 result.predicates = tcx
1551 .alloc_from_iter(result.predicates.iter().chain(inferred_outlives).copied());
1554 debug!("predicates_defined_on({:?}) = {:?}", def_id, result);
1558 /// Returns a list of all type predicates (explicit and implicit) for the definition with
1559 /// ID `def_id`. This includes all predicates returned by `predicates_defined_on`, plus
1560 /// `Self: Trait` predicates for traits.
1561 fn predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1562 let mut result = tcx.predicates_defined_on(def_id);
1564 if tcx.is_trait(def_id) {
1565 // For traits, add `Self: Trait` predicate. This is
1566 // not part of the predicates that a user writes, but it
1567 // is something that one must prove in order to invoke a
1568 // method or project an associated type.
1570 // In the chalk setup, this predicate is not part of the
1571 // "predicates" for a trait item. But it is useful in
1572 // rustc because if you directly (e.g.) invoke a trait
1573 // method like `Trait::method(...)`, you must naturally
1574 // prove that the trait applies to the types that were
1575 // used, and adding the predicate into this list ensures
1576 // that this is done.
1577 let span = tcx.def_span(def_id);
1579 tcx.arena.alloc_from_iter(result.predicates.iter().copied().chain(std::iter::once((
1580 ty::TraitRef::identity(tcx, def_id).without_const().to_predicate(),
1584 debug!("predicates_of(def_id={:?}) = {:?}", def_id, result);
1588 /// Returns a list of user-specified type predicates for the definition with ID `def_id`.
1589 /// N.B., this does not include any implied/inferred constraints.
1590 fn explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1591 use rustc_data_structures::fx::FxHashSet;
1594 debug!("explicit_predicates_of(def_id={:?})", def_id);
1596 /// A data structure with unique elements, which preserves order of insertion.
1597 /// Preserving the order of insertion is important here so as not to break
1598 /// compile-fail UI tests.
1599 // FIXME(eddyb) just use `IndexSet` from `indexmap`.
1600 struct UniquePredicates<'tcx> {
1601 predicates: Vec<(ty::Predicate<'tcx>, Span)>,
1602 uniques: FxHashSet<(ty::Predicate<'tcx>, Span)>,
1605 impl<'tcx> UniquePredicates<'tcx> {
1607 UniquePredicates { predicates: vec![], uniques: FxHashSet::default() }
1610 fn push(&mut self, value: (ty::Predicate<'tcx>, Span)) {
1611 if self.uniques.insert(value) {
1612 self.predicates.push(value);
1616 fn extend<I: IntoIterator<Item = (ty::Predicate<'tcx>, Span)>>(&mut self, iter: I) {
1623 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1624 let node = tcx.hir().get(hir_id);
1626 let mut is_trait = None;
1627 let mut is_default_impl_trait = None;
1629 let icx = ItemCtxt::new(tcx, def_id);
1630 let constness = icx.default_constness_for_trait_bounds();
1632 const NO_GENERICS: &hir::Generics<'_> = &hir::Generics::empty();
1634 let mut predicates = UniquePredicates::new();
1636 let ast_generics = match node {
1637 Node::TraitItem(item) => &item.generics,
1639 Node::ImplItem(item) => match item.kind {
1640 ImplItemKind::OpaqueTy(ref bounds) => {
1641 ty::print::with_no_queries(|| {
1642 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1643 let opaque_ty = tcx.mk_opaque(def_id, substs);
1645 "explicit_predicates_of({:?}): created opaque type {:?}",
1649 // Collect the bounds, i.e., the `A + B + 'c` in `impl A + B + 'c`.
1650 let bounds = AstConv::compute_bounds(
1654 SizedByDefault::Yes,
1655 tcx.def_span(def_id),
1658 predicates.extend(bounds.predicates(tcx, opaque_ty));
1662 _ => &item.generics,
1665 Node::Item(item) => {
1667 ItemKind::Impl { defaultness, ref generics, .. } => {
1668 if defaultness.is_default() {
1669 is_default_impl_trait = tcx.impl_trait_ref(def_id);
1673 ItemKind::Fn(.., ref generics, _)
1674 | ItemKind::TyAlias(_, ref generics)
1675 | ItemKind::Enum(_, ref generics)
1676 | ItemKind::Struct(_, ref generics)
1677 | ItemKind::Union(_, ref generics) => generics,
1679 ItemKind::Trait(_, _, ref generics, .., items) => {
1680 is_trait = Some((ty::TraitRef::identity(tcx, def_id), items));
1683 ItemKind::TraitAlias(ref generics, _) => {
1684 is_trait = Some((ty::TraitRef::identity(tcx, def_id), &[]));
1687 ItemKind::OpaqueTy(OpaqueTy {
1693 let bounds_predicates = ty::print::with_no_queries(|| {
1694 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1695 let opaque_ty = tcx.mk_opaque(def_id, substs);
1697 // Collect the bounds, i.e., the `A + B + 'c` in `impl A + B + 'c`.
1698 let bounds = AstConv::compute_bounds(
1702 SizedByDefault::Yes,
1703 tcx.def_span(def_id),
1706 bounds.predicates(tcx, opaque_ty)
1708 if impl_trait_fn.is_some() {
1710 return ty::GenericPredicates {
1712 predicates: tcx.arena.alloc_from_iter(bounds_predicates),
1715 // named opaque types
1716 predicates.extend(bounds_predicates);
1725 Node::ForeignItem(item) => match item.kind {
1726 ForeignItemKind::Static(..) => NO_GENERICS,
1727 ForeignItemKind::Fn(_, _, ref generics) => generics,
1728 ForeignItemKind::Type => NO_GENERICS,
1734 let generics = tcx.generics_of(def_id);
1735 let parent_count = generics.parent_count as u32;
1736 let has_own_self = generics.has_self && parent_count == 0;
1738 // Below we'll consider the bounds on the type parameters (including `Self`)
1739 // and the explicit where-clauses, but to get the full set of predicates
1740 // on a trait we need to add in the supertrait bounds and bounds found on
1741 // associated types.
1742 if let Some((_trait_ref, _)) = is_trait {
1743 predicates.extend(tcx.super_predicates_of(def_id).predicates.iter().cloned());
1746 // In default impls, we can assume that the self type implements
1747 // the trait. So in:
1749 // default impl Foo for Bar { .. }
1751 // we add a default where clause `Foo: Bar`. We do a similar thing for traits
1752 // (see below). Recall that a default impl is not itself an impl, but rather a
1753 // set of defaults that can be incorporated into another impl.
1754 if let Some(trait_ref) = is_default_impl_trait {
1756 trait_ref.to_poly_trait_ref().without_const().to_predicate(),
1757 tcx.def_span(def_id),
1761 // Collect the region predicates that were declared inline as
1762 // well. In the case of parameters declared on a fn or method, we
1763 // have to be careful to only iterate over early-bound regions.
1764 let mut index = parent_count + has_own_self as u32;
1765 for param in early_bound_lifetimes_from_generics(tcx, ast_generics) {
1766 let region = tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
1767 def_id: tcx.hir().local_def_id(param.hir_id),
1769 name: param.name.ident().name,
1774 GenericParamKind::Lifetime { .. } => {
1775 param.bounds.iter().for_each(|bound| match bound {
1776 hir::GenericBound::Outlives(lt) => {
1777 let bound = AstConv::ast_region_to_region(&icx, <, None);
1778 let outlives = ty::Binder::bind(ty::OutlivesPredicate(region, bound));
1779 predicates.push((outlives.to_predicate(), lt.span));
1788 // Collect the predicates that were written inline by the user on each
1789 // type parameter (e.g., `<T: Foo>`).
1790 for param in ast_generics.params {
1791 if let GenericParamKind::Type { .. } = param.kind {
1792 let name = param.name.ident().name;
1793 let param_ty = ty::ParamTy::new(index, name).to_ty(tcx);
1796 let sized = SizedByDefault::Yes;
1797 let bounds = AstConv::compute_bounds(&icx, param_ty, ¶m.bounds, sized, param.span);
1798 predicates.extend(bounds.predicates(tcx, param_ty));
1802 // Add in the bounds that appear in the where-clause.
1803 let where_clause = &ast_generics.where_clause;
1804 for predicate in where_clause.predicates {
1806 &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
1807 let ty = icx.to_ty(&bound_pred.bounded_ty);
1809 // Keep the type around in a dummy predicate, in case of no bounds.
1810 // That way, `where Ty:` is not a complete noop (see #53696) and `Ty`
1811 // is still checked for WF.
1812 if bound_pred.bounds.is_empty() {
1813 if let ty::Param(_) = ty.kind {
1814 // This is a `where T:`, which can be in the HIR from the
1815 // transformation that moves `?Sized` to `T`'s declaration.
1816 // We can skip the predicate because type parameters are
1817 // trivially WF, but also we *should*, to avoid exposing
1818 // users who never wrote `where Type:,` themselves, to
1819 // compiler/tooling bugs from not handling WF predicates.
1821 let span = bound_pred.bounded_ty.span;
1822 let re_root_empty = tcx.lifetimes.re_root_empty;
1823 let predicate = ty::OutlivesPredicate(ty, re_root_empty);
1825 ty::Predicate::TypeOutlives(ty::Binder::dummy(predicate)),
1831 for bound in bound_pred.bounds.iter() {
1833 &hir::GenericBound::Trait(ref poly_trait_ref, modifier) => {
1834 let constness = match modifier {
1835 hir::TraitBoundModifier::MaybeConst => hir::Constness::NotConst,
1836 hir::TraitBoundModifier::None => constness,
1837 hir::TraitBoundModifier::Maybe => bug!("this wasn't handled"),
1840 let mut bounds = Bounds::default();
1841 let _ = AstConv::instantiate_poly_trait_ref(
1848 predicates.extend(bounds.predicates(tcx, ty));
1851 &hir::GenericBound::Outlives(ref lifetime) => {
1852 let region = AstConv::ast_region_to_region(&icx, lifetime, None);
1853 let pred = ty::Binder::bind(ty::OutlivesPredicate(ty, region));
1854 predicates.push((ty::Predicate::TypeOutlives(pred), lifetime.span))
1860 &hir::WherePredicate::RegionPredicate(ref region_pred) => {
1861 let r1 = AstConv::ast_region_to_region(&icx, ®ion_pred.lifetime, None);
1862 predicates.extend(region_pred.bounds.iter().map(|bound| {
1863 let (r2, span) = match bound {
1864 hir::GenericBound::Outlives(lt) => {
1865 (AstConv::ast_region_to_region(&icx, lt, None), lt.span)
1869 let pred = ty::Binder::bind(ty::OutlivesPredicate(r1, r2));
1871 (ty::Predicate::RegionOutlives(pred), span)
1875 &hir::WherePredicate::EqPredicate(..) => {
1881 // Add predicates from associated type bounds.
1882 if let Some((self_trait_ref, trait_items)) = is_trait {
1883 predicates.extend(trait_items.iter().flat_map(|trait_item_ref| {
1884 associated_item_predicates(tcx, def_id, self_trait_ref, trait_item_ref)
1888 let mut predicates = predicates.predicates;
1890 // Subtle: before we store the predicates into the tcx, we
1891 // sort them so that predicates like `T: Foo<Item=U>` come
1892 // before uses of `U`. This avoids false ambiguity errors
1893 // in trait checking. See `setup_constraining_predicates`
1895 if let Node::Item(&Item { kind: ItemKind::Impl { .. }, .. }) = node {
1896 let self_ty = tcx.type_of(def_id);
1897 let trait_ref = tcx.impl_trait_ref(def_id);
1898 cgp::setup_constraining_predicates(
1902 &mut cgp::parameters_for_impl(self_ty, trait_ref),
1906 let result = ty::GenericPredicates {
1907 parent: generics.parent,
1908 predicates: tcx.arena.alloc_from_iter(predicates),
1910 debug!("explicit_predicates_of(def_id={:?}) = {:?}", def_id, result);
1914 fn associated_item_predicates(
1917 self_trait_ref: ty::TraitRef<'tcx>,
1918 trait_item_ref: &hir::TraitItemRef,
1919 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
1920 let trait_item = tcx.hir().trait_item(trait_item_ref.id);
1921 let item_def_id = tcx.hir().local_def_id(trait_item_ref.id.hir_id);
1922 let bounds = match trait_item.kind {
1923 hir::TraitItemKind::Type(ref bounds, _) => bounds,
1924 _ => return Vec::new(),
1927 let is_gat = !tcx.generics_of(item_def_id).params.is_empty();
1929 let mut had_error = false;
1931 let mut unimplemented_error = |arg_kind: &str| {
1936 &format!("{}-generic associated types are not yet implemented", arg_kind),
1939 "for more information, see issue #44265 \
1940 <https://github.com/rust-lang/rust/issues/44265> for more information",
1947 let mk_bound_param = |param: &ty::GenericParamDef, _: &_| {
1949 ty::GenericParamDefKind::Lifetime => tcx
1950 .mk_region(ty::RegionKind::ReLateBound(
1952 ty::BoundRegion::BrNamed(param.def_id, param.name),
1955 // FIXME(generic_associated_types): Use bound types and constants
1956 // once they are handled by the trait system.
1957 ty::GenericParamDefKind::Type { .. } => {
1958 unimplemented_error("type");
1959 tcx.types.err.into()
1961 ty::GenericParamDefKind::Const => {
1962 unimplemented_error("const");
1963 tcx.consts.err.into()
1968 let bound_substs = if is_gat {
1971 // trait X<'a, B, const C: usize> {
1972 // type T<'d, E, const F: usize>: Default;
1975 // We need to create predicates on the trait:
1977 // for<'d, E, const F: usize>
1978 // <Self as X<'a, B, const C: usize>>::T<'d, E, const F: usize>: Sized + Default
1980 // We substitute escaping bound parameters for the generic
1981 // arguments to the associated type which are then bound by
1982 // the `Binder` around the the predicate.
1984 // FIXME(generic_associated_types): Currently only lifetimes are handled.
1985 self_trait_ref.substs.extend_to(tcx, item_def_id, mk_bound_param)
1987 self_trait_ref.substs
1990 let assoc_ty = tcx.mk_projection(tcx.hir().local_def_id(trait_item.hir_id), bound_substs);
1992 let bounds = AstConv::compute_bounds(
1993 &ItemCtxt::new(tcx, def_id),
1996 SizedByDefault::Yes,
2000 let predicates = bounds.predicates(tcx, assoc_ty);
2003 // We use shifts to get the regions that we're substituting to
2004 // be bound by the binders in the `Predicate`s rather that
2006 let shifted_in = ty::fold::shift_vars(tcx, &predicates, 1);
2007 let substituted = shifted_in.subst(tcx, bound_substs);
2008 ty::fold::shift_out_vars(tcx, &substituted, 1)
2014 /// Converts a specific `GenericBound` from the AST into a set of
2015 /// predicates that apply to the self type. A vector is returned
2016 /// because this can be anywhere from zero predicates (`T: ?Sized` adds no
2017 /// predicates) to one (`T: Foo`) to many (`T: Bar<X = i32>` adds `T: Bar`
2018 /// and `<T as Bar>::X == i32`).
2019 fn predicates_from_bound<'tcx>(
2020 astconv: &dyn AstConv<'tcx>,
2022 bound: &'tcx hir::GenericBound<'tcx>,
2023 constness: hir::Constness,
2024 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2026 hir::GenericBound::Trait(ref tr, modifier) => {
2027 let constness = match modifier {
2028 hir::TraitBoundModifier::Maybe => return vec![],
2029 hir::TraitBoundModifier::MaybeConst => hir::Constness::NotConst,
2030 hir::TraitBoundModifier::None => constness,
2033 let mut bounds = Bounds::default();
2034 let _ = astconv.instantiate_poly_trait_ref(tr, constness, param_ty, &mut bounds);
2035 bounds.predicates(astconv.tcx(), param_ty)
2037 hir::GenericBound::Outlives(ref lifetime) => {
2038 let region = astconv.ast_region_to_region(lifetime, None);
2039 let pred = ty::Binder::bind(ty::OutlivesPredicate(param_ty, region));
2040 vec![(ty::Predicate::TypeOutlives(pred), lifetime.span)]
2045 fn compute_sig_of_foreign_fn_decl<'tcx>(
2048 decl: &'tcx hir::FnDecl<'tcx>,
2050 ) -> ty::PolyFnSig<'tcx> {
2051 let unsafety = if abi == abi::Abi::RustIntrinsic {
2052 intrinsic_operation_unsafety(&tcx.item_name(def_id).as_str())
2054 hir::Unsafety::Unsafe
2056 let fty = AstConv::ty_of_fn(&ItemCtxt::new(tcx, def_id), unsafety, abi, decl, &[], None);
2058 // Feature gate SIMD types in FFI, since I am not sure that the
2059 // ABIs are handled at all correctly. -huonw
2060 if abi != abi::Abi::RustIntrinsic
2061 && abi != abi::Abi::PlatformIntrinsic
2062 && !tcx.features().simd_ffi
2064 let check = |ast_ty: &hir::Ty<'_>, ty: Ty<'_>| {
2070 "use of SIMD type `{}` in FFI is highly experimental and \
2071 may result in invalid code",
2072 tcx.hir().hir_to_pretty_string(ast_ty.hir_id)
2075 .help("add `#![feature(simd_ffi)]` to the crate attributes to enable")
2079 for (input, ty) in decl.inputs.iter().zip(*fty.inputs().skip_binder()) {
2082 if let hir::FnRetTy::Return(ref ty) = decl.output {
2083 check(&ty, *fty.output().skip_binder())
2090 fn is_foreign_item(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
2091 match tcx.hir().get_if_local(def_id) {
2092 Some(Node::ForeignItem(..)) => true,
2094 _ => bug!("is_foreign_item applied to non-local def-id {:?}", def_id),
2098 fn static_mutability(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::Mutability> {
2099 match tcx.hir().get_if_local(def_id) {
2100 Some(Node::Item(&hir::Item { kind: hir::ItemKind::Static(_, mutbl, _), .. }))
2101 | Some(Node::ForeignItem(&hir::ForeignItem {
2102 kind: hir::ForeignItemKind::Static(_, mutbl),
2106 _ => bug!("static_mutability applied to non-local def-id {:?}", def_id),
2110 fn from_target_feature(
2113 attr: &ast::Attribute,
2114 whitelist: &FxHashMap<String, Option<Symbol>>,
2115 target_features: &mut Vec<Symbol>,
2117 let list = match attr.meta_item_list() {
2121 let bad_item = |span| {
2122 let msg = "malformed `target_feature` attribute input";
2123 let code = "enable = \"..\"".to_owned();
2125 .struct_span_err(span, &msg)
2126 .span_suggestion(span, "must be of the form", code, Applicability::HasPlaceholders)
2129 let rust_features = tcx.features();
2131 // Only `enable = ...` is accepted in the meta-item list.
2132 if !item.check_name(sym::enable) {
2133 bad_item(item.span());
2137 // Must be of the form `enable = "..."` (a string).
2138 let value = match item.value_str() {
2139 Some(value) => value,
2141 bad_item(item.span());
2146 // We allow comma separation to enable multiple features.
2147 target_features.extend(value.as_str().split(',').filter_map(|feature| {
2148 // Only allow whitelisted features per platform.
2149 let feature_gate = match whitelist.get(feature) {
2153 format!("the feature named `{}` is not valid for this target", feature);
2154 let mut err = tcx.sess.struct_span_err(item.span(), &msg);
2157 format!("`{}` is not valid for this target", feature),
2159 if feature.starts_with("+") {
2160 let valid = whitelist.contains_key(&feature[1..]);
2162 err.help("consider removing the leading `+` in the feature name");
2170 // Only allow features whose feature gates have been enabled.
2171 let allowed = match feature_gate.as_ref().map(|s| *s) {
2172 Some(sym::arm_target_feature) => rust_features.arm_target_feature,
2173 Some(sym::aarch64_target_feature) => rust_features.aarch64_target_feature,
2174 Some(sym::hexagon_target_feature) => rust_features.hexagon_target_feature,
2175 Some(sym::powerpc_target_feature) => rust_features.powerpc_target_feature,
2176 Some(sym::mips_target_feature) => rust_features.mips_target_feature,
2177 Some(sym::avx512_target_feature) => rust_features.avx512_target_feature,
2178 Some(sym::mmx_target_feature) => rust_features.mmx_target_feature,
2179 Some(sym::sse4a_target_feature) => rust_features.sse4a_target_feature,
2180 Some(sym::tbm_target_feature) => rust_features.tbm_target_feature,
2181 Some(sym::wasm_target_feature) => rust_features.wasm_target_feature,
2182 Some(sym::cmpxchg16b_target_feature) => rust_features.cmpxchg16b_target_feature,
2183 Some(sym::adx_target_feature) => rust_features.adx_target_feature,
2184 Some(sym::movbe_target_feature) => rust_features.movbe_target_feature,
2185 Some(sym::rtm_target_feature) => rust_features.rtm_target_feature,
2186 Some(sym::f16c_target_feature) => rust_features.f16c_target_feature,
2187 Some(name) => bug!("unknown target feature gate {}", name),
2190 if !allowed && id.is_local() {
2192 &tcx.sess.parse_sess,
2193 feature_gate.unwrap(),
2195 &format!("the target feature `{}` is currently unstable", feature),
2199 Some(Symbol::intern(feature))
2204 fn linkage_by_name(tcx: TyCtxt<'_>, def_id: DefId, name: &str) -> Linkage {
2205 use rustc::mir::mono::Linkage::*;
2207 // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
2208 // applicable to variable declarations and may not really make sense for
2209 // Rust code in the first place but whitelist them anyway and trust that
2210 // the user knows what s/he's doing. Who knows, unanticipated use cases
2211 // may pop up in the future.
2213 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
2214 // and don't have to be, LLVM treats them as no-ops.
2216 "appending" => Appending,
2217 "available_externally" => AvailableExternally,
2219 "extern_weak" => ExternalWeak,
2220 "external" => External,
2221 "internal" => Internal,
2222 "linkonce" => LinkOnceAny,
2223 "linkonce_odr" => LinkOnceODR,
2224 "private" => Private,
2226 "weak_odr" => WeakODR,
2228 let span = tcx.hir().span_if_local(def_id);
2229 if let Some(span) = span {
2230 tcx.sess.span_fatal(span, "invalid linkage specified")
2232 tcx.sess.fatal(&format!("invalid linkage specified: {}", name))
2238 fn codegen_fn_attrs(tcx: TyCtxt<'_>, id: DefId) -> CodegenFnAttrs {
2239 let attrs = tcx.get_attrs(id);
2241 let mut codegen_fn_attrs = CodegenFnAttrs::new();
2243 let whitelist = tcx.target_features_whitelist(LOCAL_CRATE);
2245 let mut inline_span = None;
2246 let mut link_ordinal_span = None;
2247 let mut no_sanitize_span = None;
2248 for attr in attrs.iter() {
2249 if attr.check_name(sym::cold) {
2250 codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD;
2251 } else if attr.check_name(sym::rustc_allocator) {
2252 codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR;
2253 } else if attr.check_name(sym::unwind) {
2254 codegen_fn_attrs.flags |= CodegenFnAttrFlags::UNWIND;
2255 } else if attr.check_name(sym::ffi_returns_twice) {
2256 if tcx.is_foreign_item(id) {
2257 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_RETURNS_TWICE;
2259 // `#[ffi_returns_twice]` is only allowed `extern fn`s.
2264 "`#[ffi_returns_twice]` may only be used on foreign functions"
2268 } else if attr.check_name(sym::rustc_allocator_nounwind) {
2269 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND;
2270 } else if attr.check_name(sym::naked) {
2271 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED;
2272 } else if attr.check_name(sym::no_mangle) {
2273 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2274 } else if attr.check_name(sym::rustc_std_internal_symbol) {
2275 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2276 } else if attr.check_name(sym::no_debug) {
2277 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_DEBUG;
2278 } else if attr.check_name(sym::used) {
2279 codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED;
2280 } else if attr.check_name(sym::thread_local) {
2281 codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL;
2282 } else if attr.check_name(sym::track_caller) {
2283 if tcx.is_closure(id) || tcx.fn_sig(id).abi() != abi::Abi::Rust {
2284 struct_span_err!(tcx.sess, attr.span, E0737, "`#[track_caller]` requires Rust ABI")
2287 codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
2288 } else if attr.check_name(sym::export_name) {
2289 if let Some(s) = attr.value_str() {
2290 if s.as_str().contains("\0") {
2291 // `#[export_name = ...]` will be converted to a null-terminated string,
2292 // so it may not contain any null characters.
2297 "`export_name` may not contain null characters"
2301 codegen_fn_attrs.export_name = Some(s);
2303 } else if attr.check_name(sym::target_feature) {
2304 if tcx.is_closure(id) || tcx.fn_sig(id).unsafety() == Unsafety::Normal {
2305 let msg = "`#[target_feature(..)]` can only be applied to `unsafe` functions";
2307 .struct_span_err(attr.span, msg)
2308 .span_label(attr.span, "can only be applied to `unsafe` functions")
2309 .span_label(tcx.def_span(id), "not an `unsafe` function")
2312 from_target_feature(tcx, id, attr, &whitelist, &mut codegen_fn_attrs.target_features);
2313 } else if attr.check_name(sym::linkage) {
2314 if let Some(val) = attr.value_str() {
2315 codegen_fn_attrs.linkage = Some(linkage_by_name(tcx, id, &val.as_str()));
2317 } else if attr.check_name(sym::link_section) {
2318 if let Some(val) = attr.value_str() {
2319 if val.as_str().bytes().any(|b| b == 0) {
2321 "illegal null byte in link_section \
2325 tcx.sess.span_err(attr.span, &msg);
2327 codegen_fn_attrs.link_section = Some(val);
2330 } else if attr.check_name(sym::link_name) {
2331 codegen_fn_attrs.link_name = attr.value_str();
2332 } else if attr.check_name(sym::link_ordinal) {
2333 link_ordinal_span = Some(attr.span);
2334 if let ordinal @ Some(_) = check_link_ordinal(tcx, attr) {
2335 codegen_fn_attrs.link_ordinal = ordinal;
2337 } else if attr.check_name(sym::no_sanitize) {
2338 no_sanitize_span = Some(attr.span);
2339 if let Some(list) = attr.meta_item_list() {
2340 for item in list.iter() {
2341 if item.check_name(sym::address) {
2342 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_SANITIZE_ADDRESS;
2343 } else if item.check_name(sym::memory) {
2344 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_SANITIZE_MEMORY;
2345 } else if item.check_name(sym::thread) {
2346 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_SANITIZE_THREAD;
2349 .struct_span_err(item.span(), "invalid argument for `no_sanitize`")
2350 .note("expected one of: `address`, `memory` or `thread`")
2358 codegen_fn_attrs.inline = attrs.iter().fold(InlineAttr::None, |ia, attr| {
2359 if !attr.has_name(sym::inline) {
2362 match attr.meta().map(|i| i.kind) {
2363 Some(MetaItemKind::Word) => {
2367 Some(MetaItemKind::List(ref items)) => {
2369 inline_span = Some(attr.span);
2370 if items.len() != 1 {
2372 tcx.sess.diagnostic(),
2375 "expected one argument"
2379 } else if list_contains_name(&items[..], sym::always) {
2381 } else if list_contains_name(&items[..], sym::never) {
2385 tcx.sess.diagnostic(),
2395 Some(MetaItemKind::NameValue(_)) => ia,
2400 codegen_fn_attrs.optimize = attrs.iter().fold(OptimizeAttr::None, |ia, attr| {
2401 if !attr.has_name(sym::optimize) {
2404 let err = |sp, s| struct_span_err!(tcx.sess.diagnostic(), sp, E0722, "{}", s).emit();
2405 match attr.meta().map(|i| i.kind) {
2406 Some(MetaItemKind::Word) => {
2407 err(attr.span, "expected one argument");
2410 Some(MetaItemKind::List(ref items)) => {
2412 inline_span = Some(attr.span);
2413 if items.len() != 1 {
2414 err(attr.span, "expected one argument");
2416 } else if list_contains_name(&items[..], sym::size) {
2418 } else if list_contains_name(&items[..], sym::speed) {
2421 err(items[0].span(), "invalid argument");
2425 Some(MetaItemKind::NameValue(_)) => ia,
2430 // If a function uses #[target_feature] it can't be inlined into general
2431 // purpose functions as they wouldn't have the right target features
2432 // enabled. For that reason we also forbid #[inline(always)] as it can't be
2434 if codegen_fn_attrs.target_features.len() > 0 {
2435 if codegen_fn_attrs.inline == InlineAttr::Always {
2436 if let Some(span) = inline_span {
2439 "cannot use `#[inline(always)]` with \
2440 `#[target_feature]`",
2446 if codegen_fn_attrs.flags.intersects(CodegenFnAttrFlags::NO_SANITIZE_ANY) {
2447 if codegen_fn_attrs.inline == InlineAttr::Always {
2448 if let (Some(no_sanitize_span), Some(inline_span)) = (no_sanitize_span, inline_span) {
2449 let hir_id = tcx.hir().as_local_hir_id(id).unwrap();
2450 tcx.struct_span_lint_hir(
2451 lint::builtin::INLINE_NO_SANITIZE,
2455 lint.build("`no_sanitize` will have no effect after inlining")
2456 .span_note(inline_span, "inlining requested here")
2464 // Weak lang items have the same semantics as "std internal" symbols in the
2465 // sense that they're preserved through all our LTO passes and only
2466 // strippable by the linker.
2468 // Additionally weak lang items have predetermined symbol names.
2469 if tcx.is_weak_lang_item(id) {
2470 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2472 if let Some(name) = lang_items::link_name(&attrs) {
2473 codegen_fn_attrs.export_name = Some(name);
2474 codegen_fn_attrs.link_name = Some(name);
2476 check_link_name_xor_ordinal(tcx, &codegen_fn_attrs, link_ordinal_span);
2478 // Internal symbols to the standard library all have no_mangle semantics in
2479 // that they have defined symbol names present in the function name. This
2480 // also applies to weak symbols where they all have known symbol names.
2481 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
2482 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2488 fn check_link_ordinal(tcx: TyCtxt<'_>, attr: &ast::Attribute) -> Option<usize> {
2489 use syntax::ast::{Lit, LitIntType, LitKind};
2490 let meta_item_list = attr.meta_item_list();
2491 let meta_item_list: Option<&[ast::NestedMetaItem]> = meta_item_list.as_ref().map(Vec::as_ref);
2492 let sole_meta_list = match meta_item_list {
2493 Some([item]) => item.literal(),
2496 if let Some(Lit { kind: LitKind::Int(ordinal, LitIntType::Unsuffixed), .. }) = sole_meta_list {
2497 if *ordinal <= std::usize::MAX as u128 {
2498 Some(*ordinal as usize)
2500 let msg = format!("ordinal value in `link_ordinal` is too large: `{}`", &ordinal);
2502 .struct_span_err(attr.span, &msg)
2503 .note("the value may not exceed `std::usize::MAX`")
2509 .struct_span_err(attr.span, "illegal ordinal format in `link_ordinal`")
2510 .note("an unsuffixed integer value, e.g., `1`, is expected")
2516 fn check_link_name_xor_ordinal(
2518 codegen_fn_attrs: &CodegenFnAttrs,
2519 inline_span: Option<Span>,
2521 if codegen_fn_attrs.link_name.is_none() || codegen_fn_attrs.link_ordinal.is_none() {
2524 let msg = "cannot use `#[link_name]` with `#[link_ordinal]`";
2525 if let Some(span) = inline_span {
2526 tcx.sess.span_err(span, msg);