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;
20 use crate::middle::resolve_lifetime as rl;
22 use rustc_ast::ast::{Ident, MetaItemKind};
23 use rustc_attr::{list_contains_name, mark_used, InlineAttr, OptimizeAttr};
24 use rustc_data_structures::captures::Captures;
25 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
26 use rustc_errors::{struct_span_err, Applicability};
28 use rustc_hir::def::{CtorKind, DefKind, Res};
29 use rustc_hir::def_id::{DefId, LocalDefId, LOCAL_CRATE};
30 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
31 use rustc_hir::weak_lang_items;
32 use rustc_hir::{GenericParamKind, Node, Unsafety};
33 use rustc_middle::hir::map::blocks::FnLikeNode;
34 use rustc_middle::hir::map::Map;
35 use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
36 use rustc_middle::mir::mono::Linkage;
37 use rustc_middle::ty::query::Providers;
38 use rustc_middle::ty::subst::{InternalSubsts, Subst};
39 use rustc_middle::ty::util::Discr;
40 use rustc_middle::ty::util::IntTypeExt;
41 use rustc_middle::ty::{self, AdtKind, Const, ToPolyTraitRef, Ty, TyCtxt};
42 use rustc_middle::ty::{ReprOptions, ToPredicate, WithConstness};
43 use rustc_session::lint;
44 use rustc_session::parse::feature_err;
45 use rustc_span::symbol::{kw, sym, Symbol};
46 use rustc_span::{Span, DUMMY_SP};
47 use rustc_target::spec::abi;
48 use rustc_trait_selection::traits::error_reporting::suggestions::NextTypeParamName;
52 struct OnlySelfBounds(bool);
54 ///////////////////////////////////////////////////////////////////////////
57 fn collect_mod_item_types(tcx: TyCtxt<'_>, module_def_id: DefId) {
58 tcx.hir().visit_item_likes_in_module(
60 &mut CollectItemTypesVisitor { tcx }.as_deep_visitor(),
64 pub fn provide(providers: &mut Providers<'_>) {
65 *providers = Providers {
66 type_of: type_of::type_of,
69 predicates_defined_on,
70 explicit_predicates_of,
72 type_param_predicates,
82 collect_mod_item_types,
87 ///////////////////////////////////////////////////////////////////////////
89 /// Context specific to some particular item. This is what implements
90 /// `AstConv`. It has information about the predicates that are defined
91 /// on the trait. Unfortunately, this predicate information is
92 /// available in various different forms at various points in the
93 /// process. So we can't just store a pointer to e.g., the AST or the
94 /// parsed ty form, we have to be more flexible. To this end, the
95 /// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy
96 /// `get_type_parameter_bounds` requests, drawing the information from
97 /// the AST (`hir::Generics`), recursively.
98 pub struct ItemCtxt<'tcx> {
103 ///////////////////////////////////////////////////////////////////////////
106 crate struct PlaceholderHirTyCollector(crate Vec<Span>);
108 impl<'v> Visitor<'v> for PlaceholderHirTyCollector {
109 type Map = intravisit::ErasedMap<'v>;
111 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
112 NestedVisitorMap::None
114 fn visit_ty(&mut self, t: &'v hir::Ty<'v>) {
115 if let hir::TyKind::Infer = t.kind {
118 intravisit::walk_ty(self, t)
122 struct CollectItemTypesVisitor<'tcx> {
126 /// If there are any placeholder types (`_`), emit an error explaining that this is not allowed
127 /// and suggest adding type parameters in the appropriate place, taking into consideration any and
128 /// all already existing generic type parameters to avoid suggesting a name that is already in use.
129 crate fn placeholder_type_error(
132 generics: &[hir::GenericParam<'_>],
133 placeholder_types: Vec<Span>,
136 if placeholder_types.is_empty() {
139 let type_name = generics.next_type_param_name(None);
141 let mut sugg: Vec<_> =
142 placeholder_types.iter().map(|sp| (*sp, (*type_name).to_string())).collect();
143 if generics.is_empty() {
144 sugg.push((span, format!("<{}>", type_name)));
145 } else if let Some(arg) = generics.iter().find(|arg| match arg.name {
146 hir::ParamName::Plain(Ident { name: kw::Underscore, .. }) => true,
149 // Account for `_` already present in cases like `struct S<_>(_);` and suggest
150 // `struct S<T>(T);` instead of `struct S<_, T>(T);`.
151 sugg.push((arg.span, (*type_name).to_string()));
153 let last = generics.iter().last().unwrap();
155 // Account for bounds, we want `fn foo<T: E, K>(_: K)` not `fn foo<T, K: E>(_: K)`.
156 last.bounds_span().unwrap_or(last.span).shrink_to_hi(),
157 format!(", {}", type_name),
160 let mut err = bad_placeholder_type(tcx, placeholder_types);
162 err.multipart_suggestion(
163 "use type parameters instead",
165 Applicability::HasPlaceholders,
171 fn reject_placeholder_type_signatures_in_item(tcx: TyCtxt<'tcx>, item: &'tcx hir::Item<'tcx>) {
172 let (generics, suggest) = match &item.kind {
173 hir::ItemKind::Union(_, generics)
174 | hir::ItemKind::Enum(_, generics)
175 | hir::ItemKind::TraitAlias(generics, _)
176 | hir::ItemKind::Trait(_, _, generics, ..)
177 | hir::ItemKind::Impl { generics, .. }
178 | hir::ItemKind::Struct(_, generics) => (generics, true),
179 hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. })
180 | hir::ItemKind::TyAlias(_, generics) => (generics, false),
181 // `static`, `fn` and `const` are handled elsewhere to suggest appropriate type.
185 let mut visitor = PlaceholderHirTyCollector::default();
186 visitor.visit_item(item);
188 placeholder_type_error(tcx, generics.span, &generics.params[..], visitor.0, suggest);
191 impl Visitor<'tcx> for CollectItemTypesVisitor<'tcx> {
192 type Map = Map<'tcx>;
194 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
195 NestedVisitorMap::OnlyBodies(self.tcx.hir())
198 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
199 convert_item(self.tcx, item.hir_id);
200 reject_placeholder_type_signatures_in_item(self.tcx, item);
201 intravisit::walk_item(self, item);
204 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
205 for param in generics.params {
207 hir::GenericParamKind::Lifetime { .. } => {}
208 hir::GenericParamKind::Type { default: Some(_), .. } => {
209 let def_id = self.tcx.hir().local_def_id(param.hir_id);
210 self.tcx.type_of(def_id);
212 hir::GenericParamKind::Type { .. } => {}
213 hir::GenericParamKind::Const { .. } => {
214 let def_id = self.tcx.hir().local_def_id(param.hir_id);
215 self.tcx.type_of(def_id);
219 intravisit::walk_generics(self, generics);
222 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
223 if let hir::ExprKind::Closure(..) = expr.kind {
224 let def_id = self.tcx.hir().local_def_id(expr.hir_id);
225 self.tcx.generics_of(def_id);
226 self.tcx.type_of(def_id);
228 intravisit::walk_expr(self, expr);
231 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
232 convert_trait_item(self.tcx, trait_item.hir_id);
233 intravisit::walk_trait_item(self, trait_item);
236 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
237 convert_impl_item(self.tcx, impl_item.hir_id);
238 intravisit::walk_impl_item(self, impl_item);
242 ///////////////////////////////////////////////////////////////////////////
243 // Utility types and common code for the above passes.
245 fn bad_placeholder_type(
247 mut spans: Vec<Span>,
248 ) -> rustc_errors::DiagnosticBuilder<'tcx> {
250 let mut err = struct_span_err!(
254 "the type placeholder `_` is not allowed within types on item signatures",
257 err.span_label(span, "not allowed in type signatures");
262 impl ItemCtxt<'tcx> {
263 pub fn new(tcx: TyCtxt<'tcx>, item_def_id: DefId) -> ItemCtxt<'tcx> {
264 ItemCtxt { tcx, item_def_id }
267 pub fn to_ty(&self, ast_ty: &'tcx hir::Ty<'tcx>) -> Ty<'tcx> {
268 AstConv::ast_ty_to_ty(self, ast_ty)
271 pub fn hir_id(&self) -> hir::HirId {
272 self.tcx.hir().as_local_hir_id(self.item_def_id.expect_local())
275 pub fn node(&self) -> hir::Node<'tcx> {
276 self.tcx.hir().get(self.hir_id())
280 impl AstConv<'tcx> for ItemCtxt<'tcx> {
281 fn tcx(&self) -> TyCtxt<'tcx> {
285 fn item_def_id(&self) -> Option<DefId> {
286 Some(self.item_def_id)
289 fn default_constness_for_trait_bounds(&self) -> hir::Constness {
290 if let Some(fn_like) = FnLikeNode::from_node(self.node()) {
293 hir::Constness::NotConst
297 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId) -> ty::GenericPredicates<'tcx> {
298 self.tcx.at(span).type_param_predicates((self.item_def_id, def_id.expect_local()))
301 fn re_infer(&self, _: Option<&ty::GenericParamDef>, _: Span) -> Option<ty::Region<'tcx>> {
305 fn allow_ty_infer(&self) -> bool {
309 fn ty_infer(&self, _: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx> {
310 self.tcx().sess.delay_span_bug(span, "bad placeholder type");
317 _: Option<&ty::GenericParamDef>,
319 ) -> &'tcx Const<'tcx> {
320 bad_placeholder_type(self.tcx(), vec![span]).emit();
322 self.tcx().mk_const(ty::Const { val: ty::ConstKind::Error, ty })
325 fn projected_ty_from_poly_trait_ref(
329 item_segment: &hir::PathSegment<'_>,
330 poly_trait_ref: ty::PolyTraitRef<'tcx>,
332 if let Some(trait_ref) = poly_trait_ref.no_bound_vars() {
333 let item_substs = <dyn AstConv<'tcx>>::create_substs_for_associated_item(
341 self.tcx().mk_projection(item_def_id, item_substs)
343 // There are no late-bound regions; we can just ignore the binder.
344 let mut err = struct_span_err!(
348 "cannot extract an associated type from a higher-ranked trait bound \
353 hir::Node::Field(_) | hir::Node::Ctor(_) | hir::Node::Variant(_) => {
355 self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(self.hir_id()));
357 hir::ItemKind::Enum(_, generics)
358 | hir::ItemKind::Struct(_, generics)
359 | hir::ItemKind::Union(_, generics) => {
360 let lt_name = get_new_lifetime_name(self.tcx, poly_trait_ref, generics);
361 let (lt_sp, sugg) = match &generics.params[..] {
362 [] => (generics.span, format!("<{}>", lt_name)),
364 (bound.span.shrink_to_lo(), format!("{}, ", lt_name))
367 let suggestions = vec![
373 // Replace the existing lifetimes with a new named lifetime.
375 .replace_late_bound_regions(&poly_trait_ref, |_| {
376 self.tcx.mk_region(ty::ReEarlyBound(
377 ty::EarlyBoundRegion {
380 name: Symbol::intern(<_name),
389 err.multipart_suggestion(
390 "use a fully qualified path with explicit lifetimes",
392 Applicability::MaybeIncorrect,
398 hir::Node::Item(hir::Item {
400 hir::ItemKind::Struct(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Union(..),
404 | hir::Node::ForeignItem(_)
405 | hir::Node::TraitItem(_)
406 | hir::Node::ImplItem(_) => {
409 "use a fully qualified path with inferred lifetimes",
412 // Erase named lt, we want `<A as B<'_>::C`, not `<A as B<'a>::C`.
413 self.tcx.anonymize_late_bound_regions(&poly_trait_ref).skip_binder(),
416 Applicability::MaybeIncorrect,
426 fn normalize_ty(&self, _span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
427 // Types in item signatures are not normalized to avoid undue dependencies.
431 fn set_tainted_by_errors(&self) {
432 // There's no obvious place to track this, so just let it go.
435 fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) {
436 // There's no place to record types from signatures?
440 /// Synthesize a new lifetime name that doesn't clash with any of the lifetimes already present.
441 fn get_new_lifetime_name<'tcx>(
443 poly_trait_ref: ty::PolyTraitRef<'tcx>,
444 generics: &hir::Generics<'tcx>,
446 let existing_lifetimes = tcx
447 .collect_referenced_late_bound_regions(&poly_trait_ref)
450 if let ty::BoundRegion::BrNamed(_, name) = lt {
451 Some(name.as_str().to_string())
456 .chain(generics.params.iter().filter_map(|param| {
457 if let hir::GenericParamKind::Lifetime { .. } = ¶m.kind {
458 Some(param.name.ident().as_str().to_string())
463 .collect::<FxHashSet<String>>();
465 let a_to_z_repeat_n = |n| {
466 (b'a'..=b'z').map(move |c| {
467 let mut s = '\''.to_string();
468 s.extend(std::iter::repeat(char::from(c)).take(n));
473 // If all single char lifetime names are present, we wrap around and double the chars.
474 (1..).flat_map(a_to_z_repeat_n).find(|lt| !existing_lifetimes.contains(lt.as_str())).unwrap()
477 /// Returns the predicates defined on `item_def_id` of the form
478 /// `X: Foo` where `X` is the type parameter `def_id`.
479 fn type_param_predicates(
481 (item_def_id, def_id): (DefId, LocalDefId),
482 ) -> ty::GenericPredicates<'_> {
485 // In the AST, bounds can derive from two places. Either
486 // written inline like `<T: Foo>` or in a where-clause like
489 let param_id = tcx.hir().as_local_hir_id(def_id);
490 let param_owner = tcx.hir().ty_param_owner(param_id);
491 let param_owner_def_id = tcx.hir().local_def_id(param_owner);
492 let generics = tcx.generics_of(param_owner_def_id);
493 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
494 let ty = tcx.mk_ty_param(index, tcx.hir().ty_param_name(param_id));
496 // Don't look for bounds where the type parameter isn't in scope.
497 let parent = if item_def_id == param_owner_def_id.to_def_id() {
500 tcx.generics_of(item_def_id).parent
503 let mut result = parent
505 let icx = ItemCtxt::new(tcx, parent);
506 icx.get_type_parameter_bounds(DUMMY_SP, def_id.to_def_id())
508 .unwrap_or_default();
509 let mut extend = None;
511 let item_hir_id = tcx.hir().as_local_hir_id(item_def_id.expect_local());
512 let ast_generics = match tcx.hir().get(item_hir_id) {
513 Node::TraitItem(item) => &item.generics,
515 Node::ImplItem(item) => &item.generics,
517 Node::Item(item) => {
519 ItemKind::Fn(.., ref generics, _)
520 | ItemKind::Impl { ref generics, .. }
521 | ItemKind::TyAlias(_, ref generics)
522 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
523 | ItemKind::Enum(_, ref generics)
524 | ItemKind::Struct(_, ref generics)
525 | ItemKind::Union(_, ref generics) => generics,
526 ItemKind::Trait(_, _, ref generics, ..) => {
527 // Implied `Self: Trait` and supertrait bounds.
528 if param_id == item_hir_id {
529 let identity_trait_ref = ty::TraitRef::identity(tcx, item_def_id);
531 Some((identity_trait_ref.without_const().to_predicate(), item.span));
539 Node::ForeignItem(item) => match item.kind {
540 ForeignItemKind::Fn(_, _, ref generics) => generics,
547 let icx = ItemCtxt::new(tcx, item_def_id);
548 let extra_predicates = extend.into_iter().chain(
549 icx.type_parameter_bounds_in_generics(ast_generics, param_id, ty, OnlySelfBounds(true))
551 .filter(|(predicate, _)| match predicate {
552 ty::Predicate::Trait(ref data, _) => data.skip_binder().self_ty().is_param(index),
557 tcx.arena.alloc_from_iter(result.predicates.iter().copied().chain(extra_predicates));
561 impl ItemCtxt<'tcx> {
562 /// Finds bounds from `hir::Generics`. This requires scanning through the
563 /// AST. We do this to avoid having to convert *all* the bounds, which
564 /// would create artificial cycles. Instead, we can only convert the
565 /// bounds for a type parameter `X` if `X::Foo` is used.
566 fn type_parameter_bounds_in_generics(
568 ast_generics: &'tcx hir::Generics<'tcx>,
569 param_id: hir::HirId,
571 only_self_bounds: OnlySelfBounds,
572 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
573 let constness = self.default_constness_for_trait_bounds();
574 let from_ty_params = ast_generics
577 .filter_map(|param| match param.kind {
578 GenericParamKind::Type { .. } if param.hir_id == param_id => Some(¶m.bounds),
581 .flat_map(|bounds| bounds.iter())
582 .flat_map(|b| predicates_from_bound(self, ty, b, constness));
584 let from_where_clauses = ast_generics
588 .filter_map(|wp| match *wp {
589 hir::WherePredicate::BoundPredicate(ref bp) => Some(bp),
593 let bt = if is_param(self.tcx, &bp.bounded_ty, param_id) {
595 } else if !only_self_bounds.0 {
596 Some(self.to_ty(&bp.bounded_ty))
600 bp.bounds.iter().filter_map(move |b| bt.map(|bt| (bt, b)))
602 .flat_map(|(bt, b)| predicates_from_bound(self, bt, b, constness));
604 from_ty_params.chain(from_where_clauses).collect()
608 /// Tests whether this is the AST for a reference to the type
609 /// parameter with ID `param_id`. We use this so as to avoid running
610 /// `ast_ty_to_ty`, because we want to avoid triggering an all-out
611 /// conversion of the type to avoid inducing unnecessary cycles.
612 fn is_param(tcx: TyCtxt<'_>, ast_ty: &hir::Ty<'_>, param_id: hir::HirId) -> bool {
613 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = ast_ty.kind {
615 Res::SelfTy(Some(def_id), None) | Res::Def(DefKind::TyParam, def_id) => {
616 def_id == tcx.hir().local_def_id(param_id).to_def_id()
625 fn convert_item(tcx: TyCtxt<'_>, item_id: hir::HirId) {
626 let it = tcx.hir().expect_item(item_id);
627 debug!("convert: item {} with id {}", it.ident, it.hir_id);
628 let def_id = tcx.hir().local_def_id(item_id);
630 // These don't define types.
631 hir::ItemKind::ExternCrate(_)
632 | hir::ItemKind::Use(..)
633 | hir::ItemKind::Mod(_)
634 | hir::ItemKind::GlobalAsm(_) => {}
635 hir::ItemKind::ForeignMod(ref foreign_mod) => {
636 for item in foreign_mod.items {
637 let def_id = tcx.hir().local_def_id(item.hir_id);
638 tcx.generics_of(def_id);
640 tcx.predicates_of(def_id);
641 if let hir::ForeignItemKind::Fn(..) = item.kind {
646 hir::ItemKind::Enum(ref enum_definition, _) => {
647 tcx.generics_of(def_id);
649 tcx.predicates_of(def_id);
650 convert_enum_variant_types(tcx, def_id.to_def_id(), &enum_definition.variants);
652 hir::ItemKind::Impl { .. } => {
653 tcx.generics_of(def_id);
655 tcx.impl_trait_ref(def_id);
656 tcx.predicates_of(def_id);
658 hir::ItemKind::Trait(..) => {
659 tcx.generics_of(def_id);
660 tcx.trait_def(def_id);
661 tcx.at(it.span).super_predicates_of(def_id);
662 tcx.predicates_of(def_id);
664 hir::ItemKind::TraitAlias(..) => {
665 tcx.generics_of(def_id);
666 tcx.at(it.span).super_predicates_of(def_id);
667 tcx.predicates_of(def_id);
669 hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
670 tcx.generics_of(def_id);
672 tcx.predicates_of(def_id);
674 for f in struct_def.fields() {
675 let def_id = tcx.hir().local_def_id(f.hir_id);
676 tcx.generics_of(def_id);
678 tcx.predicates_of(def_id);
681 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
682 convert_variant_ctor(tcx, ctor_hir_id);
686 // Desugared from `impl Trait`, so visited by the function's return type.
687 hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: Some(_), .. }) => {}
689 hir::ItemKind::OpaqueTy(..)
690 | hir::ItemKind::TyAlias(..)
691 | hir::ItemKind::Static(..)
692 | hir::ItemKind::Const(..)
693 | hir::ItemKind::Fn(..) => {
694 tcx.generics_of(def_id);
696 tcx.predicates_of(def_id);
697 if let hir::ItemKind::Fn(..) = it.kind {
704 fn convert_trait_item(tcx: TyCtxt<'_>, trait_item_id: hir::HirId) {
705 let trait_item = tcx.hir().expect_trait_item(trait_item_id);
706 let def_id = tcx.hir().local_def_id(trait_item.hir_id);
707 tcx.generics_of(def_id);
709 match trait_item.kind {
710 hir::TraitItemKind::Fn(..) => {
715 hir::TraitItemKind::Const(.., Some(_)) => {
719 hir::TraitItemKind::Const(..) | hir::TraitItemKind::Type(_, Some(_)) => {
721 // Account for `const C: _;` and `type T = _;`.
722 let mut visitor = PlaceholderHirTyCollector::default();
723 visitor.visit_trait_item(trait_item);
724 placeholder_type_error(tcx, DUMMY_SP, &[], visitor.0, false);
727 hir::TraitItemKind::Type(_, None) => {}
730 tcx.predicates_of(def_id);
733 fn convert_impl_item(tcx: TyCtxt<'_>, impl_item_id: hir::HirId) {
734 let def_id = tcx.hir().local_def_id(impl_item_id);
735 tcx.generics_of(def_id);
737 tcx.predicates_of(def_id);
738 let impl_item = tcx.hir().expect_impl_item(impl_item_id);
739 match impl_item.kind {
740 hir::ImplItemKind::Fn(..) => {
743 hir::ImplItemKind::TyAlias(_) | hir::ImplItemKind::OpaqueTy(_) => {
744 // Account for `type T = _;`
745 let mut visitor = PlaceholderHirTyCollector::default();
746 visitor.visit_impl_item(impl_item);
747 placeholder_type_error(tcx, DUMMY_SP, &[], visitor.0, false);
749 hir::ImplItemKind::Const(..) => {}
753 fn convert_variant_ctor(tcx: TyCtxt<'_>, ctor_id: hir::HirId) {
754 let def_id = tcx.hir().local_def_id(ctor_id);
755 tcx.generics_of(def_id);
757 tcx.predicates_of(def_id);
760 fn convert_enum_variant_types(tcx: TyCtxt<'_>, def_id: DefId, variants: &[hir::Variant<'_>]) {
761 let def = tcx.adt_def(def_id);
762 let repr_type = def.repr.discr_type();
763 let initial = repr_type.initial_discriminant(tcx);
764 let mut prev_discr = None::<Discr<'_>>;
766 // fill the discriminant values and field types
767 for variant in variants {
768 let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
770 if let Some(ref e) = variant.disr_expr {
771 let expr_did = tcx.hir().local_def_id(e.hir_id);
772 def.eval_explicit_discr(tcx, expr_did.to_def_id())
773 } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) {
776 struct_span_err!(tcx.sess, variant.span, E0370, "enum discriminant overflowed")
779 format!("overflowed on value after {}", prev_discr.unwrap()),
782 "explicitly set `{} = {}` if that is desired outcome",
783 variant.ident, wrapped_discr
788 .unwrap_or(wrapped_discr),
791 for f in variant.data.fields() {
792 let def_id = tcx.hir().local_def_id(f.hir_id);
793 tcx.generics_of(def_id);
795 tcx.predicates_of(def_id);
798 // Convert the ctor, if any. This also registers the variant as
800 if let Some(ctor_hir_id) = variant.data.ctor_hir_id() {
801 convert_variant_ctor(tcx, ctor_hir_id);
808 variant_did: Option<LocalDefId>,
809 ctor_did: Option<LocalDefId>,
811 discr: ty::VariantDiscr,
812 def: &hir::VariantData<'_>,
813 adt_kind: ty::AdtKind,
814 parent_did: LocalDefId,
815 ) -> ty::VariantDef {
816 let mut seen_fields: FxHashMap<ast::Ident, Span> = Default::default();
817 let hir_id = tcx.hir().as_local_hir_id(variant_did.unwrap_or(parent_did));
822 let fid = tcx.hir().local_def_id(f.hir_id);
823 let dup_span = seen_fields.get(&f.ident.normalize_to_macros_2_0()).cloned();
824 if let Some(prev_span) = dup_span {
829 "field `{}` is already declared",
832 .span_label(f.span, "field already declared")
833 .span_label(prev_span, format!("`{}` first declared here", f.ident))
836 seen_fields.insert(f.ident.normalize_to_macros_2_0(), f.span);
840 did: fid.to_def_id(),
842 vis: ty::Visibility::from_hir(&f.vis, hir_id, tcx),
846 let recovered = match def {
847 hir::VariantData::Struct(_, r) => *r,
853 variant_did.map(LocalDefId::to_def_id),
854 ctor_did.map(LocalDefId::to_def_id),
857 CtorKind::from_hir(def),
859 parent_did.to_def_id(),
864 fn adt_def(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::AdtDef {
867 let def_id = def_id.expect_local();
868 let hir_id = tcx.hir().as_local_hir_id(def_id);
869 let item = match tcx.hir().get(hir_id) {
870 Node::Item(item) => item,
874 let repr = ReprOptions::new(tcx, def_id.to_def_id());
875 let (kind, variants) = match item.kind {
876 ItemKind::Enum(ref def, _) => {
877 let mut distance_from_explicit = 0;
882 let variant_did = Some(tcx.hir().local_def_id(v.id));
884 v.data.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
886 let discr = if let Some(ref e) = v.disr_expr {
887 distance_from_explicit = 0;
888 ty::VariantDiscr::Explicit(tcx.hir().local_def_id(e.hir_id).to_def_id())
890 ty::VariantDiscr::Relative(distance_from_explicit)
892 distance_from_explicit += 1;
907 (AdtKind::Enum, variants)
909 ItemKind::Struct(ref def, _) => {
910 let variant_did = None::<LocalDefId>;
911 let ctor_did = def.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
913 let variants = std::iter::once(convert_variant(
918 ty::VariantDiscr::Relative(0),
925 (AdtKind::Struct, variants)
927 ItemKind::Union(ref def, _) => {
928 let variant_did = None;
929 let ctor_did = def.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
931 let variants = std::iter::once(convert_variant(
936 ty::VariantDiscr::Relative(0),
943 (AdtKind::Union, variants)
947 tcx.alloc_adt_def(def_id.to_def_id(), kind, variants, repr)
950 /// Ensures that the super-predicates of the trait with a `DefId`
951 /// of `trait_def_id` are converted and stored. This also ensures that
952 /// the transitive super-predicates are converted.
953 fn super_predicates_of(tcx: TyCtxt<'_>, trait_def_id: DefId) -> ty::GenericPredicates<'_> {
954 debug!("super_predicates(trait_def_id={:?})", trait_def_id);
955 let trait_hir_id = tcx.hir().as_local_hir_id(trait_def_id.expect_local());
957 let item = match tcx.hir().get(trait_hir_id) {
958 Node::Item(item) => item,
959 _ => bug!("trait_node_id {} is not an item", trait_hir_id),
962 let (generics, bounds) = match item.kind {
963 hir::ItemKind::Trait(.., ref generics, ref supertraits, _) => (generics, supertraits),
964 hir::ItemKind::TraitAlias(ref generics, ref supertraits) => (generics, supertraits),
965 _ => span_bug!(item.span, "super_predicates invoked on non-trait"),
968 let icx = ItemCtxt::new(tcx, trait_def_id);
970 // Convert the bounds that follow the colon, e.g., `Bar + Zed` in `trait Foo: Bar + Zed`.
971 let self_param_ty = tcx.types.self_param;
973 AstConv::compute_bounds(&icx, self_param_ty, bounds, SizedByDefault::No, item.span);
975 let superbounds1 = superbounds1.predicates(tcx, self_param_ty);
977 // Convert any explicit superbounds in the where-clause,
978 // e.g., `trait Foo where Self: Bar`.
979 // In the case of trait aliases, however, we include all bounds in the where-clause,
980 // so e.g., `trait Foo = where u32: PartialEq<Self>` would include `u32: PartialEq<Self>`
981 // as one of its "superpredicates".
982 let is_trait_alias = tcx.is_trait_alias(trait_def_id);
983 let superbounds2 = icx.type_parameter_bounds_in_generics(
987 OnlySelfBounds(!is_trait_alias),
990 // Combine the two lists to form the complete set of superbounds:
991 let superbounds = &*tcx.arena.alloc_from_iter(superbounds1.into_iter().chain(superbounds2));
993 // Now require that immediate supertraits are converted,
994 // which will, in turn, reach indirect supertraits.
995 for &(pred, span) in superbounds {
996 debug!("superbound: {:?}", pred);
997 if let ty::Predicate::Trait(bound, _) = pred {
998 tcx.at(span).super_predicates_of(bound.def_id());
1002 ty::GenericPredicates { parent: None, predicates: superbounds }
1005 fn trait_def(tcx: TyCtxt<'_>, def_id: DefId) -> ty::TraitDef {
1006 let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local());
1007 let item = tcx.hir().expect_item(hir_id);
1009 let (is_auto, unsafety) = match item.kind {
1010 hir::ItemKind::Trait(is_auto, unsafety, ..) => (is_auto == hir::IsAuto::Yes, unsafety),
1011 hir::ItemKind::TraitAlias(..) => (false, hir::Unsafety::Normal),
1012 _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
1015 let paren_sugar = tcx.has_attr(def_id, sym::rustc_paren_sugar);
1016 if paren_sugar && !tcx.features().unboxed_closures {
1020 "the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \
1021 which traits can use parenthetical notation",
1023 .help("add `#![feature(unboxed_closures)]` to the crate attributes to use it")
1027 let is_marker = tcx.has_attr(def_id, sym::marker);
1028 let spec_kind = if tcx.has_attr(def_id, sym::rustc_unsafe_specialization_marker) {
1029 ty::trait_def::TraitSpecializationKind::Marker
1030 } else if tcx.has_attr(def_id, sym::rustc_specialization_trait) {
1031 ty::trait_def::TraitSpecializationKind::AlwaysApplicable
1033 ty::trait_def::TraitSpecializationKind::None
1035 let def_path_hash = tcx.def_path_hash(def_id);
1036 ty::TraitDef::new(def_id, unsafety, paren_sugar, is_auto, is_marker, spec_kind, def_path_hash)
1039 fn has_late_bound_regions<'tcx>(tcx: TyCtxt<'tcx>, node: Node<'tcx>) -> Option<Span> {
1040 struct LateBoundRegionsDetector<'tcx> {
1042 outer_index: ty::DebruijnIndex,
1043 has_late_bound_regions: Option<Span>,
1046 impl Visitor<'tcx> for LateBoundRegionsDetector<'tcx> {
1047 type Map = intravisit::ErasedMap<'tcx>;
1049 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1050 NestedVisitorMap::None
1053 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
1054 if self.has_late_bound_regions.is_some() {
1058 hir::TyKind::BareFn(..) => {
1059 self.outer_index.shift_in(1);
1060 intravisit::walk_ty(self, ty);
1061 self.outer_index.shift_out(1);
1063 _ => intravisit::walk_ty(self, ty),
1067 fn visit_poly_trait_ref(
1069 tr: &'tcx hir::PolyTraitRef<'tcx>,
1070 m: hir::TraitBoundModifier,
1072 if self.has_late_bound_regions.is_some() {
1075 self.outer_index.shift_in(1);
1076 intravisit::walk_poly_trait_ref(self, tr, m);
1077 self.outer_index.shift_out(1);
1080 fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
1081 if self.has_late_bound_regions.is_some() {
1085 match self.tcx.named_region(lt.hir_id) {
1086 Some(rl::Region::Static | rl::Region::EarlyBound(..)) => {}
1088 rl::Region::LateBound(debruijn, _, _) | rl::Region::LateBoundAnon(debruijn, _),
1089 ) if debruijn < self.outer_index => {}
1091 rl::Region::LateBound(..)
1092 | rl::Region::LateBoundAnon(..)
1093 | rl::Region::Free(..),
1096 self.has_late_bound_regions = Some(lt.span);
1102 fn has_late_bound_regions<'tcx>(
1104 generics: &'tcx hir::Generics<'tcx>,
1105 decl: &'tcx hir::FnDecl<'tcx>,
1107 let mut visitor = LateBoundRegionsDetector {
1109 outer_index: ty::INNERMOST,
1110 has_late_bound_regions: None,
1112 for param in generics.params {
1113 if let GenericParamKind::Lifetime { .. } = param.kind {
1114 if tcx.is_late_bound(param.hir_id) {
1115 return Some(param.span);
1119 visitor.visit_fn_decl(decl);
1120 visitor.has_late_bound_regions
1124 Node::TraitItem(item) => match item.kind {
1125 hir::TraitItemKind::Fn(ref sig, _) => {
1126 has_late_bound_regions(tcx, &item.generics, &sig.decl)
1130 Node::ImplItem(item) => match item.kind {
1131 hir::ImplItemKind::Fn(ref sig, _) => {
1132 has_late_bound_regions(tcx, &item.generics, &sig.decl)
1136 Node::ForeignItem(item) => match item.kind {
1137 hir::ForeignItemKind::Fn(ref fn_decl, _, ref generics) => {
1138 has_late_bound_regions(tcx, generics, fn_decl)
1142 Node::Item(item) => match item.kind {
1143 hir::ItemKind::Fn(ref sig, .., ref generics, _) => {
1144 has_late_bound_regions(tcx, generics, &sig.decl)
1152 fn generics_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::Generics {
1155 let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local());
1157 let node = tcx.hir().get(hir_id);
1158 let parent_def_id = match node {
1160 | Node::TraitItem(_)
1163 | Node::Field(_) => {
1164 let parent_id = tcx.hir().get_parent_item(hir_id);
1165 Some(tcx.hir().local_def_id(parent_id).to_def_id())
1167 // FIXME(#43408) enable this always when we get lazy normalization.
1168 Node::AnonConst(_) => {
1169 let parent_id = tcx.hir().get_parent_item(hir_id);
1170 let parent_def_id = tcx.hir().local_def_id(parent_id);
1172 // HACK(eddyb) this provides the correct generics when
1173 // `feature(const_generics)` is enabled, so that const expressions
1174 // used with const generics, e.g. `Foo<{N+1}>`, can work at all.
1175 if tcx.features().const_generics {
1176 Some(parent_def_id.to_def_id())
1178 let parent_node = tcx.hir().get(tcx.hir().get_parent_node(hir_id));
1180 // HACK(eddyb) this provides the correct generics for repeat
1181 // expressions' count (i.e. `N` in `[x; N]`), and explicit
1182 // `enum` discriminants (i.e. `D` in `enum Foo { Bar = D }`),
1183 // as they shouldn't be able to cause query cycle errors.
1184 Node::Expr(&Expr { kind: ExprKind::Repeat(_, ref constant), .. })
1185 | Node::Variant(Variant { disr_expr: Some(ref constant), .. })
1186 if constant.hir_id == hir_id =>
1188 Some(parent_def_id.to_def_id())
1195 Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => {
1196 Some(tcx.closure_base_def_id(def_id))
1198 Node::Item(item) => match item.kind {
1199 ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn, .. }) => {
1200 impl_trait_fn.or_else(|| {
1201 let parent_id = tcx.hir().get_parent_item(hir_id);
1202 if parent_id != hir_id && parent_id != CRATE_HIR_ID {
1203 debug!("generics_of: parent of opaque ty {:?} is {:?}", def_id, parent_id);
1204 // If this 'impl Trait' is nested inside another 'impl Trait'
1205 // (e.g. `impl Foo<MyType = impl Bar<A>>`), we need to use the 'parent'
1206 // 'impl Trait' for its generic parameters, since we can reference them
1207 // from the 'child' 'impl Trait'
1208 if let Node::Item(hir::Item { kind: ItemKind::OpaqueTy(..), .. }) =
1209 tcx.hir().get(parent_id)
1211 Some(tcx.hir().local_def_id(parent_id).to_def_id())
1225 let mut opt_self = None;
1226 let mut allow_defaults = false;
1228 let no_generics = hir::Generics::empty();
1229 let ast_generics = match node {
1230 Node::TraitItem(item) => &item.generics,
1232 Node::ImplItem(item) => &item.generics,
1234 Node::Item(item) => {
1236 ItemKind::Fn(.., ref generics, _) | ItemKind::Impl { ref generics, .. } => generics,
1238 ItemKind::TyAlias(_, ref generics)
1239 | ItemKind::Enum(_, ref generics)
1240 | ItemKind::Struct(_, ref generics)
1241 | ItemKind::OpaqueTy(hir::OpaqueTy { ref generics, .. })
1242 | ItemKind::Union(_, ref generics) => {
1243 allow_defaults = true;
1247 ItemKind::Trait(_, _, ref generics, ..)
1248 | ItemKind::TraitAlias(ref generics, ..) => {
1249 // Add in the self type parameter.
1251 // Something of a hack: use the node id for the trait, also as
1252 // the node id for the Self type parameter.
1253 let param_id = item.hir_id;
1255 opt_self = Some(ty::GenericParamDef {
1257 name: kw::SelfUpper,
1258 def_id: tcx.hir().local_def_id(param_id).to_def_id(),
1259 pure_wrt_drop: false,
1260 kind: ty::GenericParamDefKind::Type {
1262 object_lifetime_default: rl::Set1::Empty,
1267 allow_defaults = true;
1275 Node::ForeignItem(item) => match item.kind {
1276 ForeignItemKind::Static(..) => &no_generics,
1277 ForeignItemKind::Fn(_, _, ref generics) => generics,
1278 ForeignItemKind::Type => &no_generics,
1284 let has_self = opt_self.is_some();
1285 let mut parent_has_self = false;
1286 let mut own_start = has_self as u32;
1287 let parent_count = parent_def_id.map_or(0, |def_id| {
1288 let generics = tcx.generics_of(def_id);
1289 assert_eq!(has_self, false);
1290 parent_has_self = generics.has_self;
1291 own_start = generics.count() as u32;
1292 generics.parent_count + generics.params.len()
1295 let mut params: Vec<_> = opt_self.into_iter().collect();
1297 let early_lifetimes = early_bound_lifetimes_from_generics(tcx, ast_generics);
1298 params.extend(early_lifetimes.enumerate().map(|(i, param)| ty::GenericParamDef {
1299 name: param.name.ident().name,
1300 index: own_start + i as u32,
1301 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
1302 pure_wrt_drop: param.pure_wrt_drop,
1303 kind: ty::GenericParamDefKind::Lifetime,
1306 let object_lifetime_defaults = tcx.object_lifetime_defaults(hir_id);
1308 // Now create the real type and const parameters.
1309 let type_start = own_start - has_self as u32 + params.len() as u32;
1312 // FIXME(const_generics): a few places in the compiler expect generic params
1313 // to be in the order lifetimes, then type params, then const params.
1315 // To prevent internal errors in case const parameters are supplied before
1316 // type parameters we first add all type params, then all const params.
1317 params.extend(ast_generics.params.iter().filter_map(|param| {
1318 if let GenericParamKind::Type { ref default, synthetic, .. } = param.kind {
1319 if !allow_defaults && default.is_some() {
1320 if !tcx.features().default_type_parameter_fallback {
1321 tcx.struct_span_lint_hir(
1322 lint::builtin::INVALID_TYPE_PARAM_DEFAULT,
1327 "defaults for type parameters are only allowed in \
1328 `struct`, `enum`, `type`, or `trait` definitions.",
1336 let kind = ty::GenericParamDefKind::Type {
1337 has_default: default.is_some(),
1338 object_lifetime_default: object_lifetime_defaults
1340 .map_or(rl::Set1::Empty, |o| o[i]),
1344 let param_def = ty::GenericParamDef {
1345 index: type_start + i as u32,
1346 name: param.name.ident().name,
1347 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
1348 pure_wrt_drop: param.pure_wrt_drop,
1358 params.extend(ast_generics.params.iter().filter_map(|param| {
1359 if let GenericParamKind::Const { .. } = param.kind {
1360 let param_def = ty::GenericParamDef {
1361 index: type_start + i as u32,
1362 name: param.name.ident().name,
1363 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
1364 pure_wrt_drop: param.pure_wrt_drop,
1365 kind: ty::GenericParamDefKind::Const,
1374 // provide junk type parameter defs - the only place that
1375 // cares about anything but the length is instantiation,
1376 // and we don't do that for closures.
1377 if let Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(.., gen), .. }) = node {
1378 let dummy_args = if gen.is_some() {
1379 &["<resume_ty>", "<yield_ty>", "<return_ty>", "<witness>", "<upvars>"][..]
1381 &["<closure_kind>", "<closure_signature>", "<upvars>"][..]
1384 params.extend(dummy_args.iter().enumerate().map(|(i, &arg)| ty::GenericParamDef {
1385 index: type_start + i as u32,
1386 name: Symbol::intern(arg),
1388 pure_wrt_drop: false,
1389 kind: ty::GenericParamDefKind::Type {
1391 object_lifetime_default: rl::Set1::Empty,
1397 let param_def_id_to_index = params.iter().map(|param| (param.def_id, param.index)).collect();
1400 parent: parent_def_id,
1403 param_def_id_to_index,
1404 has_self: has_self || parent_has_self,
1405 has_late_bound_regions: has_late_bound_regions(tcx, node),
1409 fn are_suggestable_generic_args(generic_args: &[hir::GenericArg<'_>]) -> bool {
1412 .filter_map(|arg| match arg {
1413 hir::GenericArg::Type(ty) => Some(ty),
1416 .any(is_suggestable_infer_ty)
1419 /// Whether `ty` is a type with `_` placeholders that can be inferred. Used in diagnostics only to
1420 /// use inference to provide suggestions for the appropriate type if possible.
1421 fn is_suggestable_infer_ty(ty: &hir::Ty<'_>) -> bool {
1425 Slice(ty) | Array(ty, _) => is_suggestable_infer_ty(ty),
1426 Tup(tys) => tys.iter().any(is_suggestable_infer_ty),
1427 Ptr(mut_ty) | Rptr(_, mut_ty) => is_suggestable_infer_ty(mut_ty.ty),
1428 Def(_, generic_args) => are_suggestable_generic_args(generic_args),
1429 Path(hir::QPath::TypeRelative(ty, segment)) => {
1430 is_suggestable_infer_ty(ty) || are_suggestable_generic_args(segment.generic_args().args)
1432 Path(hir::QPath::Resolved(ty_opt, hir::Path { segments, .. })) => {
1433 ty_opt.map_or(false, is_suggestable_infer_ty)
1436 .any(|segment| are_suggestable_generic_args(segment.generic_args().args))
1442 pub fn get_infer_ret_ty(output: &'hir hir::FnRetTy<'hir>) -> Option<&'hir hir::Ty<'hir>> {
1443 if let hir::FnRetTy::Return(ref ty) = output {
1444 if is_suggestable_infer_ty(ty) {
1451 fn fn_sig(tcx: TyCtxt<'_>, def_id: DefId) -> ty::PolyFnSig<'_> {
1452 use rustc_hir::Node::*;
1455 let def_id = def_id.expect_local();
1456 let hir_id = tcx.hir().as_local_hir_id(def_id);
1458 let icx = ItemCtxt::new(tcx, def_id.to_def_id());
1460 match tcx.hir().get(hir_id) {
1461 TraitItem(hir::TraitItem {
1462 kind: TraitItemKind::Fn(sig, TraitFn::Provided(_)),
1467 | ImplItem(hir::ImplItem { kind: ImplItemKind::Fn(sig, _), ident, generics, .. })
1468 | Item(hir::Item { kind: ItemKind::Fn(sig, generics, _), ident, .. }) => {
1469 match get_infer_ret_ty(&sig.decl.output) {
1471 let fn_sig = tcx.typeck_tables_of(def_id).liberated_fn_sigs()[hir_id];
1472 let mut visitor = PlaceholderHirTyCollector::default();
1473 visitor.visit_ty(ty);
1474 let mut diag = bad_placeholder_type(tcx, visitor.0);
1475 let ret_ty = fn_sig.output();
1476 if ret_ty != tcx.types.err {
1477 diag.span_suggestion(
1479 "replace with the correct return type",
1481 Applicability::MaybeIncorrect,
1485 ty::Binder::bind(fn_sig)
1487 None => AstConv::ty_of_fn(
1489 sig.header.unsafety,
1498 TraitItem(hir::TraitItem {
1499 kind: TraitItemKind::Fn(FnSig { header, decl }, _),
1504 AstConv::ty_of_fn(&icx, header.unsafety, header.abi, decl, &generics, Some(ident.span))
1507 ForeignItem(&hir::ForeignItem {
1508 kind: ForeignItemKind::Fn(ref fn_decl, _, _),
1512 let abi = tcx.hir().get_foreign_abi(hir_id);
1513 compute_sig_of_foreign_fn_decl(tcx, def_id.to_def_id(), fn_decl, abi, ident)
1516 Ctor(data) | Variant(hir::Variant { data, .. }) if data.ctor_hir_id().is_some() => {
1517 let ty = tcx.type_of(tcx.hir().get_parent_did(hir_id).to_def_id());
1519 data.fields().iter().map(|f| tcx.type_of(tcx.hir().local_def_id(f.hir_id)));
1520 ty::Binder::bind(tcx.mk_fn_sig(
1524 hir::Unsafety::Normal,
1529 Expr(&hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => {
1530 // Closure signatures are not like other function
1531 // signatures and cannot be accessed through `fn_sig`. For
1532 // example, a closure signature excludes the `self`
1533 // argument. In any case they are embedded within the
1534 // closure type as part of the `ClosureSubsts`.
1536 // To get the signature of a closure, you should use the
1537 // `sig` method on the `ClosureSubsts`:
1539 // substs.as_closure().sig(def_id, tcx)
1541 "to get the signature of a closure, use `substs.as_closure().sig()` not `fn_sig()`",
1546 bug!("unexpected sort of node in fn_sig(): {:?}", x);
1551 fn impl_trait_ref(tcx: TyCtxt<'_>, def_id: DefId) -> Option<ty::TraitRef<'_>> {
1552 let icx = ItemCtxt::new(tcx, def_id);
1554 let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local());
1555 match tcx.hir().expect_item(hir_id).kind {
1556 hir::ItemKind::Impl { ref of_trait, .. } => of_trait.as_ref().map(|ast_trait_ref| {
1557 let selfty = tcx.type_of(def_id);
1558 AstConv::instantiate_mono_trait_ref(&icx, ast_trait_ref, selfty)
1564 fn impl_polarity(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ImplPolarity {
1565 let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local());
1566 let is_rustc_reservation = tcx.has_attr(def_id, sym::rustc_reservation_impl);
1567 let item = tcx.hir().expect_item(hir_id);
1569 hir::ItemKind::Impl { polarity: hir::ImplPolarity::Negative(span), of_trait, .. } => {
1570 if is_rustc_reservation {
1571 let span = span.to(of_trait.as_ref().map(|t| t.path.span).unwrap_or(*span));
1572 tcx.sess.span_err(span, "reservation impls can't be negative");
1574 ty::ImplPolarity::Negative
1576 hir::ItemKind::Impl { polarity: hir::ImplPolarity::Positive, of_trait: None, .. } => {
1577 if is_rustc_reservation {
1578 tcx.sess.span_err(item.span, "reservation impls can't be inherent");
1580 ty::ImplPolarity::Positive
1582 hir::ItemKind::Impl {
1583 polarity: hir::ImplPolarity::Positive, of_trait: Some(_), ..
1585 if is_rustc_reservation {
1586 ty::ImplPolarity::Reservation
1588 ty::ImplPolarity::Positive
1591 ref item => bug!("impl_polarity: {:?} not an impl", item),
1595 /// Returns the early-bound lifetimes declared in this generics
1596 /// listing. For anything other than fns/methods, this is just all
1597 /// the lifetimes that are declared. For fns or methods, we have to
1598 /// screen out those that do not appear in any where-clauses etc using
1599 /// `resolve_lifetime::early_bound_lifetimes`.
1600 fn early_bound_lifetimes_from_generics<'a, 'tcx: 'a>(
1602 generics: &'a hir::Generics<'a>,
1603 ) -> impl Iterator<Item = &'a hir::GenericParam<'a>> + Captures<'tcx> {
1604 generics.params.iter().filter(move |param| match param.kind {
1605 GenericParamKind::Lifetime { .. } => !tcx.is_late_bound(param.hir_id),
1610 /// Returns a list of type predicates for the definition with ID `def_id`, including inferred
1611 /// lifetime constraints. This includes all predicates returned by `explicit_predicates_of`, plus
1612 /// inferred constraints concerning which regions outlive other regions.
1613 fn predicates_defined_on(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1614 debug!("predicates_defined_on({:?})", def_id);
1615 let mut result = tcx.explicit_predicates_of(def_id);
1616 debug!("predicates_defined_on: explicit_predicates_of({:?}) = {:?}", def_id, result,);
1617 let inferred_outlives = tcx.inferred_outlives_of(def_id);
1618 if !inferred_outlives.is_empty() {
1620 "predicates_defined_on: inferred_outlives_of({:?}) = {:?}",
1621 def_id, inferred_outlives,
1623 if result.predicates.is_empty() {
1624 result.predicates = inferred_outlives;
1626 result.predicates = tcx
1628 .alloc_from_iter(result.predicates.iter().chain(inferred_outlives).copied());
1631 debug!("predicates_defined_on({:?}) = {:?}", def_id, result);
1635 /// Returns a list of all type predicates (explicit and implicit) for the definition with
1636 /// ID `def_id`. This includes all predicates returned by `predicates_defined_on`, plus
1637 /// `Self: Trait` predicates for traits.
1638 fn predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1639 let mut result = tcx.predicates_defined_on(def_id);
1641 if tcx.is_trait(def_id) {
1642 // For traits, add `Self: Trait` predicate. This is
1643 // not part of the predicates that a user writes, but it
1644 // is something that one must prove in order to invoke a
1645 // method or project an associated type.
1647 // In the chalk setup, this predicate is not part of the
1648 // "predicates" for a trait item. But it is useful in
1649 // rustc because if you directly (e.g.) invoke a trait
1650 // method like `Trait::method(...)`, you must naturally
1651 // prove that the trait applies to the types that were
1652 // used, and adding the predicate into this list ensures
1653 // that this is done.
1654 let span = tcx.sess.source_map().guess_head_span(tcx.def_span(def_id));
1656 tcx.arena.alloc_from_iter(result.predicates.iter().copied().chain(std::iter::once((
1657 ty::TraitRef::identity(tcx, def_id).without_const().to_predicate(),
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(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1670 debug!("explicit_predicates_of(def_id={:?})", def_id);
1672 /// A data structure with unique elements, which preserves order of insertion.
1673 /// Preserving the order of insertion is important here so as not to break
1674 /// compile-fail UI tests.
1675 // FIXME(eddyb) just use `IndexSet` from `indexmap`.
1676 struct UniquePredicates<'tcx> {
1677 predicates: Vec<(ty::Predicate<'tcx>, Span)>,
1678 uniques: FxHashSet<(ty::Predicate<'tcx>, Span)>,
1681 impl<'tcx> UniquePredicates<'tcx> {
1683 UniquePredicates { predicates: vec![], uniques: FxHashSet::default() }
1686 fn push(&mut self, value: (ty::Predicate<'tcx>, Span)) {
1687 if self.uniques.insert(value) {
1688 self.predicates.push(value);
1692 fn extend<I: IntoIterator<Item = (ty::Predicate<'tcx>, Span)>>(&mut self, iter: I) {
1699 let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local());
1700 let node = tcx.hir().get(hir_id);
1702 let mut is_trait = None;
1703 let mut is_default_impl_trait = None;
1705 let icx = ItemCtxt::new(tcx, def_id);
1706 let constness = icx.default_constness_for_trait_bounds();
1708 const NO_GENERICS: &hir::Generics<'_> = &hir::Generics::empty();
1710 let mut predicates = UniquePredicates::new();
1712 let ast_generics = match node {
1713 Node::TraitItem(item) => &item.generics,
1715 Node::ImplItem(item) => match item.kind {
1716 ImplItemKind::OpaqueTy(ref bounds) => {
1717 ty::print::with_no_queries(|| {
1718 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1719 let opaque_ty = tcx.mk_opaque(def_id, substs);
1721 "explicit_predicates_of({:?}): created opaque type {:?}",
1725 // Collect the bounds, i.e., the `A + B + 'c` in `impl A + B + 'c`.
1726 let bounds = AstConv::compute_bounds(
1730 SizedByDefault::Yes,
1731 tcx.def_span(def_id),
1734 predicates.extend(bounds.predicates(tcx, opaque_ty));
1738 _ => &item.generics,
1741 Node::Item(item) => {
1743 ItemKind::Impl { defaultness, ref generics, .. } => {
1744 if defaultness.is_default() {
1745 is_default_impl_trait = tcx.impl_trait_ref(def_id);
1749 ItemKind::Fn(.., ref generics, _)
1750 | ItemKind::TyAlias(_, ref generics)
1751 | ItemKind::Enum(_, ref generics)
1752 | ItemKind::Struct(_, ref generics)
1753 | ItemKind::Union(_, ref generics) => generics,
1755 ItemKind::Trait(_, _, ref generics, .., items) => {
1756 is_trait = Some((ty::TraitRef::identity(tcx, def_id), items));
1759 ItemKind::TraitAlias(ref generics, _) => {
1760 is_trait = Some((ty::TraitRef::identity(tcx, def_id), &[]));
1763 ItemKind::OpaqueTy(OpaqueTy {
1769 let bounds_predicates = ty::print::with_no_queries(|| {
1770 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1771 let opaque_ty = tcx.mk_opaque(def_id, substs);
1773 // Collect the bounds, i.e., the `A + B + 'c` in `impl A + B + 'c`.
1774 let bounds = AstConv::compute_bounds(
1778 SizedByDefault::Yes,
1779 tcx.def_span(def_id),
1782 bounds.predicates(tcx, opaque_ty)
1784 if impl_trait_fn.is_some() {
1786 return ty::GenericPredicates {
1788 predicates: tcx.arena.alloc_from_iter(bounds_predicates),
1791 // named opaque types
1792 predicates.extend(bounds_predicates);
1801 Node::ForeignItem(item) => match item.kind {
1802 ForeignItemKind::Static(..) => NO_GENERICS,
1803 ForeignItemKind::Fn(_, _, ref generics) => generics,
1804 ForeignItemKind::Type => NO_GENERICS,
1810 let generics = tcx.generics_of(def_id);
1811 let parent_count = generics.parent_count as u32;
1812 let has_own_self = generics.has_self && parent_count == 0;
1814 // Below we'll consider the bounds on the type parameters (including `Self`)
1815 // and the explicit where-clauses, but to get the full set of predicates
1816 // on a trait we need to add in the supertrait bounds and bounds found on
1817 // associated types.
1818 if let Some((_trait_ref, _)) = is_trait {
1819 predicates.extend(tcx.super_predicates_of(def_id).predicates.iter().cloned());
1822 // In default impls, we can assume that the self type implements
1823 // the trait. So in:
1825 // default impl Foo for Bar { .. }
1827 // we add a default where clause `Foo: Bar`. We do a similar thing for traits
1828 // (see below). Recall that a default impl is not itself an impl, but rather a
1829 // set of defaults that can be incorporated into another impl.
1830 if let Some(trait_ref) = is_default_impl_trait {
1832 trait_ref.to_poly_trait_ref().without_const().to_predicate(),
1833 tcx.def_span(def_id),
1837 // Collect the region predicates that were declared inline as
1838 // well. In the case of parameters declared on a fn or method, we
1839 // have to be careful to only iterate over early-bound regions.
1840 let mut index = parent_count + has_own_self as u32;
1841 for param in early_bound_lifetimes_from_generics(tcx, ast_generics) {
1842 let region = tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
1843 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
1845 name: param.name.ident().name,
1850 GenericParamKind::Lifetime { .. } => {
1851 param.bounds.iter().for_each(|bound| match bound {
1852 hir::GenericBound::Outlives(lt) => {
1853 let bound = AstConv::ast_region_to_region(&icx, <, None);
1854 let outlives = ty::Binder::bind(ty::OutlivesPredicate(region, bound));
1855 predicates.push((outlives.to_predicate(), lt.span));
1864 // Collect the predicates that were written inline by the user on each
1865 // type parameter (e.g., `<T: Foo>`).
1866 for param in ast_generics.params {
1867 if let GenericParamKind::Type { .. } = param.kind {
1868 let name = param.name.ident().name;
1869 let param_ty = ty::ParamTy::new(index, name).to_ty(tcx);
1872 let sized = SizedByDefault::Yes;
1873 let bounds = AstConv::compute_bounds(&icx, param_ty, ¶m.bounds, sized, param.span);
1874 predicates.extend(bounds.predicates(tcx, param_ty));
1878 // Add in the bounds that appear in the where-clause.
1879 let where_clause = &ast_generics.where_clause;
1880 for predicate in where_clause.predicates {
1882 &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
1883 let ty = icx.to_ty(&bound_pred.bounded_ty);
1885 // Keep the type around in a dummy predicate, in case of no bounds.
1886 // That way, `where Ty:` is not a complete noop (see #53696) and `Ty`
1887 // is still checked for WF.
1888 if bound_pred.bounds.is_empty() {
1889 if let ty::Param(_) = ty.kind {
1890 // This is a `where T:`, which can be in the HIR from the
1891 // transformation that moves `?Sized` to `T`'s declaration.
1892 // We can skip the predicate because type parameters are
1893 // trivially WF, but also we *should*, to avoid exposing
1894 // users who never wrote `where Type:,` themselves, to
1895 // compiler/tooling bugs from not handling WF predicates.
1897 let span = bound_pred.bounded_ty.span;
1898 let re_root_empty = tcx.lifetimes.re_root_empty;
1899 let predicate = ty::OutlivesPredicate(ty, re_root_empty);
1901 ty::Predicate::TypeOutlives(ty::Binder::dummy(predicate)),
1907 for bound in bound_pred.bounds.iter() {
1909 &hir::GenericBound::Trait(ref poly_trait_ref, modifier) => {
1910 let constness = match modifier {
1911 hir::TraitBoundModifier::MaybeConst => hir::Constness::NotConst,
1912 hir::TraitBoundModifier::None => constness,
1913 hir::TraitBoundModifier::Maybe => bug!("this wasn't handled"),
1916 let mut bounds = Bounds::default();
1917 let _ = AstConv::instantiate_poly_trait_ref(
1924 predicates.extend(bounds.predicates(tcx, ty));
1927 &hir::GenericBound::Outlives(ref lifetime) => {
1928 let region = AstConv::ast_region_to_region(&icx, lifetime, None);
1929 let pred = ty::Binder::bind(ty::OutlivesPredicate(ty, region));
1930 predicates.push((ty::Predicate::TypeOutlives(pred), lifetime.span))
1936 &hir::WherePredicate::RegionPredicate(ref region_pred) => {
1937 let r1 = AstConv::ast_region_to_region(&icx, ®ion_pred.lifetime, None);
1938 predicates.extend(region_pred.bounds.iter().map(|bound| {
1939 let (r2, span) = match bound {
1940 hir::GenericBound::Outlives(lt) => {
1941 (AstConv::ast_region_to_region(&icx, lt, None), lt.span)
1945 let pred = ty::Binder::bind(ty::OutlivesPredicate(r1, r2));
1947 (ty::Predicate::RegionOutlives(pred), span)
1951 &hir::WherePredicate::EqPredicate(..) => {
1957 // Add predicates from associated type bounds.
1958 if let Some((self_trait_ref, trait_items)) = is_trait {
1959 predicates.extend(trait_items.iter().flat_map(|trait_item_ref| {
1960 associated_item_predicates(tcx, def_id, self_trait_ref, trait_item_ref)
1964 let mut predicates = predicates.predicates;
1966 // Subtle: before we store the predicates into the tcx, we
1967 // sort them so that predicates like `T: Foo<Item=U>` come
1968 // before uses of `U`. This avoids false ambiguity errors
1969 // in trait checking. See `setup_constraining_predicates`
1971 if let Node::Item(&Item { kind: ItemKind::Impl { .. }, .. }) = node {
1972 let self_ty = tcx.type_of(def_id);
1973 let trait_ref = tcx.impl_trait_ref(def_id);
1974 cgp::setup_constraining_predicates(
1978 &mut cgp::parameters_for_impl(self_ty, trait_ref),
1982 let result = ty::GenericPredicates {
1983 parent: generics.parent,
1984 predicates: tcx.arena.alloc_from_iter(predicates),
1986 debug!("explicit_predicates_of(def_id={:?}) = {:?}", def_id, result);
1990 fn associated_item_predicates(
1993 self_trait_ref: ty::TraitRef<'tcx>,
1994 trait_item_ref: &hir::TraitItemRef,
1995 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
1996 let trait_item = tcx.hir().trait_item(trait_item_ref.id);
1997 let item_def_id = tcx.hir().local_def_id(trait_item_ref.id.hir_id);
1998 let bounds = match trait_item.kind {
1999 hir::TraitItemKind::Type(ref bounds, _) => bounds,
2000 _ => return Vec::new(),
2003 let is_gat = !tcx.generics_of(item_def_id).params.is_empty();
2005 let mut had_error = false;
2007 let mut unimplemented_error = |arg_kind: &str| {
2012 &format!("{}-generic associated types are not yet implemented", arg_kind),
2015 "for more information, see issue #44265 \
2016 <https://github.com/rust-lang/rust/issues/44265> for more information",
2023 let mk_bound_param = |param: &ty::GenericParamDef, _: &_| {
2025 ty::GenericParamDefKind::Lifetime => tcx
2026 .mk_region(ty::RegionKind::ReLateBound(
2028 ty::BoundRegion::BrNamed(param.def_id, param.name),
2031 // FIXME(generic_associated_types): Use bound types and constants
2032 // once they are handled by the trait system.
2033 ty::GenericParamDefKind::Type { .. } => {
2034 unimplemented_error("type");
2035 tcx.types.err.into()
2037 ty::GenericParamDefKind::Const => {
2038 unimplemented_error("const");
2039 tcx.mk_const(ty::Const { val: ty::ConstKind::Error, ty: tcx.type_of(param.def_id) })
2045 let bound_substs = if is_gat {
2048 // trait X<'a, B, const C: usize> {
2049 // type T<'d, E, const F: usize>: Default;
2052 // We need to create predicates on the trait:
2054 // for<'d, E, const F: usize>
2055 // <Self as X<'a, B, const C: usize>>::T<'d, E, const F: usize>: Sized + Default
2057 // We substitute escaping bound parameters for the generic
2058 // arguments to the associated type which are then bound by
2059 // the `Binder` around the the predicate.
2061 // FIXME(generic_associated_types): Currently only lifetimes are handled.
2062 self_trait_ref.substs.extend_to(tcx, item_def_id.to_def_id(), mk_bound_param)
2064 self_trait_ref.substs
2068 tcx.mk_projection(tcx.hir().local_def_id(trait_item.hir_id).to_def_id(), bound_substs);
2070 let bounds = AstConv::compute_bounds(
2071 &ItemCtxt::new(tcx, def_id),
2074 SizedByDefault::Yes,
2078 let predicates = bounds.predicates(tcx, assoc_ty);
2081 // We use shifts to get the regions that we're substituting to
2082 // be bound by the binders in the `Predicate`s rather that
2084 let shifted_in = ty::fold::shift_vars(tcx, &predicates, 1);
2085 let substituted = shifted_in.subst(tcx, bound_substs);
2086 ty::fold::shift_out_vars(tcx, &substituted, 1)
2092 /// Converts a specific `GenericBound` from the AST into a set of
2093 /// predicates that apply to the self type. A vector is returned
2094 /// because this can be anywhere from zero predicates (`T: ?Sized` adds no
2095 /// predicates) to one (`T: Foo`) to many (`T: Bar<X = i32>` adds `T: Bar`
2096 /// and `<T as Bar>::X == i32`).
2097 fn predicates_from_bound<'tcx>(
2098 astconv: &dyn AstConv<'tcx>,
2100 bound: &'tcx hir::GenericBound<'tcx>,
2101 constness: hir::Constness,
2102 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2104 hir::GenericBound::Trait(ref tr, modifier) => {
2105 let constness = match modifier {
2106 hir::TraitBoundModifier::Maybe => return vec![],
2107 hir::TraitBoundModifier::MaybeConst => hir::Constness::NotConst,
2108 hir::TraitBoundModifier::None => constness,
2111 let mut bounds = Bounds::default();
2112 let _ = astconv.instantiate_poly_trait_ref(tr, constness, param_ty, &mut bounds);
2113 bounds.predicates(astconv.tcx(), param_ty)
2115 hir::GenericBound::Outlives(ref lifetime) => {
2116 let region = astconv.ast_region_to_region(lifetime, None);
2117 let pred = ty::Binder::bind(ty::OutlivesPredicate(param_ty, region));
2118 vec![(ty::Predicate::TypeOutlives(pred), lifetime.span)]
2123 fn compute_sig_of_foreign_fn_decl<'tcx>(
2126 decl: &'tcx hir::FnDecl<'tcx>,
2129 ) -> ty::PolyFnSig<'tcx> {
2130 let unsafety = if abi == abi::Abi::RustIntrinsic {
2131 intrinsic_operation_unsafety(&tcx.item_name(def_id).as_str())
2133 hir::Unsafety::Unsafe
2135 let fty = AstConv::ty_of_fn(
2136 &ItemCtxt::new(tcx, def_id),
2140 &hir::Generics::empty(),
2144 // Feature gate SIMD types in FFI, since I am not sure that the
2145 // ABIs are handled at all correctly. -huonw
2146 if abi != abi::Abi::RustIntrinsic
2147 && abi != abi::Abi::PlatformIntrinsic
2148 && !tcx.features().simd_ffi
2150 let check = |ast_ty: &hir::Ty<'_>, ty: Ty<'_>| {
2155 .span_to_snippet(ast_ty.span)
2156 .map_or(String::new(), |s| format!(" `{}`", s));
2161 "use of SIMD type{} in FFI is highly experimental and \
2162 may result in invalid code",
2166 .help("add `#![feature(simd_ffi)]` to the crate attributes to enable")
2170 for (input, ty) in decl.inputs.iter().zip(*fty.inputs().skip_binder()) {
2173 if let hir::FnRetTy::Return(ref ty) = decl.output {
2174 check(&ty, *fty.output().skip_binder())
2181 fn is_foreign_item(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
2182 match tcx.hir().get_if_local(def_id) {
2183 Some(Node::ForeignItem(..)) => true,
2185 _ => bug!("is_foreign_item applied to non-local def-id {:?}", def_id),
2189 fn static_mutability(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::Mutability> {
2190 match tcx.hir().get_if_local(def_id) {
2192 Node::Item(&hir::Item { kind: hir::ItemKind::Static(_, mutbl, _), .. })
2193 | Node::ForeignItem(&hir::ForeignItem {
2194 kind: hir::ForeignItemKind::Static(_, mutbl),
2199 _ => bug!("static_mutability applied to non-local def-id {:?}", def_id),
2203 fn generator_kind(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::GeneratorKind> {
2204 match tcx.hir().get_if_local(def_id) {
2205 Some(Node::Expr(&rustc_hir::Expr {
2206 kind: rustc_hir::ExprKind::Closure(_, _, body_id, _, _),
2208 })) => tcx.hir().body(body_id).generator_kind(),
2210 _ => bug!("generator_kind applied to non-local def-id {:?}", def_id),
2214 fn from_target_feature(
2217 attr: &ast::Attribute,
2218 whitelist: &FxHashMap<String, Option<Symbol>>,
2219 target_features: &mut Vec<Symbol>,
2221 let list = match attr.meta_item_list() {
2225 let bad_item = |span| {
2226 let msg = "malformed `target_feature` attribute input";
2227 let code = "enable = \"..\"".to_owned();
2229 .struct_span_err(span, &msg)
2230 .span_suggestion(span, "must be of the form", code, Applicability::HasPlaceholders)
2233 let rust_features = tcx.features();
2235 // Only `enable = ...` is accepted in the meta-item list.
2236 if !item.check_name(sym::enable) {
2237 bad_item(item.span());
2241 // Must be of the form `enable = "..."` (a string).
2242 let value = match item.value_str() {
2243 Some(value) => value,
2245 bad_item(item.span());
2250 // We allow comma separation to enable multiple features.
2251 target_features.extend(value.as_str().split(',').filter_map(|feature| {
2252 // Only allow whitelisted features per platform.
2253 let feature_gate = match whitelist.get(feature) {
2257 format!("the feature named `{}` is not valid for this target", feature);
2258 let mut err = tcx.sess.struct_span_err(item.span(), &msg);
2261 format!("`{}` is not valid for this target", feature),
2263 if feature.starts_with('+') {
2264 let valid = whitelist.contains_key(&feature[1..]);
2266 err.help("consider removing the leading `+` in the feature name");
2274 // Only allow features whose feature gates have been enabled.
2275 let allowed = match feature_gate.as_ref().copied() {
2276 Some(sym::arm_target_feature) => rust_features.arm_target_feature,
2277 Some(sym::aarch64_target_feature) => rust_features.aarch64_target_feature,
2278 Some(sym::hexagon_target_feature) => rust_features.hexagon_target_feature,
2279 Some(sym::powerpc_target_feature) => rust_features.powerpc_target_feature,
2280 Some(sym::mips_target_feature) => rust_features.mips_target_feature,
2281 Some(sym::avx512_target_feature) => rust_features.avx512_target_feature,
2282 Some(sym::mmx_target_feature) => rust_features.mmx_target_feature,
2283 Some(sym::sse4a_target_feature) => rust_features.sse4a_target_feature,
2284 Some(sym::tbm_target_feature) => rust_features.tbm_target_feature,
2285 Some(sym::wasm_target_feature) => rust_features.wasm_target_feature,
2286 Some(sym::cmpxchg16b_target_feature) => rust_features.cmpxchg16b_target_feature,
2287 Some(sym::adx_target_feature) => rust_features.adx_target_feature,
2288 Some(sym::movbe_target_feature) => rust_features.movbe_target_feature,
2289 Some(sym::rtm_target_feature) => rust_features.rtm_target_feature,
2290 Some(sym::f16c_target_feature) => rust_features.f16c_target_feature,
2291 Some(name) => bug!("unknown target feature gate {}", name),
2294 if !allowed && id.is_local() {
2296 &tcx.sess.parse_sess,
2297 feature_gate.unwrap(),
2299 &format!("the target feature `{}` is currently unstable", feature),
2303 Some(Symbol::intern(feature))
2308 fn linkage_by_name(tcx: TyCtxt<'_>, def_id: DefId, name: &str) -> Linkage {
2309 use rustc_middle::mir::mono::Linkage::*;
2311 // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
2312 // applicable to variable declarations and may not really make sense for
2313 // Rust code in the first place but whitelist them anyway and trust that
2314 // the user knows what s/he's doing. Who knows, unanticipated use cases
2315 // may pop up in the future.
2317 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
2318 // and don't have to be, LLVM treats them as no-ops.
2320 "appending" => Appending,
2321 "available_externally" => AvailableExternally,
2323 "extern_weak" => ExternalWeak,
2324 "external" => External,
2325 "internal" => Internal,
2326 "linkonce" => LinkOnceAny,
2327 "linkonce_odr" => LinkOnceODR,
2328 "private" => Private,
2330 "weak_odr" => WeakODR,
2332 let span = tcx.hir().span_if_local(def_id);
2333 if let Some(span) = span {
2334 tcx.sess.span_fatal(span, "invalid linkage specified")
2336 tcx.sess.fatal(&format!("invalid linkage specified: {}", name))
2342 fn codegen_fn_attrs(tcx: TyCtxt<'_>, id: DefId) -> CodegenFnAttrs {
2343 let attrs = tcx.get_attrs(id);
2345 let mut codegen_fn_attrs = CodegenFnAttrs::new();
2346 if should_inherit_track_caller(tcx, id) {
2347 codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
2350 let whitelist = tcx.target_features_whitelist(LOCAL_CRATE);
2352 let mut inline_span = None;
2353 let mut link_ordinal_span = None;
2354 let mut no_sanitize_span = None;
2355 for attr in attrs.iter() {
2356 if attr.check_name(sym::cold) {
2357 codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD;
2358 } else if attr.check_name(sym::rustc_allocator) {
2359 codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR;
2360 } else if attr.check_name(sym::unwind) {
2361 codegen_fn_attrs.flags |= CodegenFnAttrFlags::UNWIND;
2362 } else if attr.check_name(sym::ffi_returns_twice) {
2363 if tcx.is_foreign_item(id) {
2364 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_RETURNS_TWICE;
2366 // `#[ffi_returns_twice]` is only allowed `extern fn`s.
2371 "`#[ffi_returns_twice]` may only be used on foreign functions"
2375 } else if attr.check_name(sym::rustc_allocator_nounwind) {
2376 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND;
2377 } else if attr.check_name(sym::naked) {
2378 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED;
2379 } else if attr.check_name(sym::no_mangle) {
2380 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2381 } else if attr.check_name(sym::rustc_std_internal_symbol) {
2382 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2383 } else if attr.check_name(sym::used) {
2384 codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED;
2385 } else if attr.check_name(sym::thread_local) {
2386 codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL;
2387 } else if attr.check_name(sym::track_caller) {
2388 if tcx.is_closure(id) || tcx.fn_sig(id).abi() != abi::Abi::Rust {
2389 struct_span_err!(tcx.sess, attr.span, E0737, "`#[track_caller]` requires Rust ABI")
2392 codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
2393 } else if attr.check_name(sym::export_name) {
2394 if let Some(s) = attr.value_str() {
2395 if s.as_str().contains('\0') {
2396 // `#[export_name = ...]` will be converted to a null-terminated string,
2397 // so it may not contain any null characters.
2402 "`export_name` may not contain null characters"
2406 codegen_fn_attrs.export_name = Some(s);
2408 } else if attr.check_name(sym::target_feature) {
2409 if tcx.is_closure(id) || tcx.fn_sig(id).unsafety() == Unsafety::Normal {
2410 let msg = "`#[target_feature(..)]` can only be applied to `unsafe` functions";
2412 .struct_span_err(attr.span, msg)
2413 .span_label(attr.span, "can only be applied to `unsafe` functions")
2414 .span_label(tcx.def_span(id), "not an `unsafe` function")
2417 from_target_feature(tcx, id, attr, &whitelist, &mut codegen_fn_attrs.target_features);
2418 } else if attr.check_name(sym::linkage) {
2419 if let Some(val) = attr.value_str() {
2420 codegen_fn_attrs.linkage = Some(linkage_by_name(tcx, id, &val.as_str()));
2422 } else if attr.check_name(sym::link_section) {
2423 if let Some(val) = attr.value_str() {
2424 if val.as_str().bytes().any(|b| b == 0) {
2426 "illegal null byte in link_section \
2430 tcx.sess.span_err(attr.span, &msg);
2432 codegen_fn_attrs.link_section = Some(val);
2435 } else if attr.check_name(sym::link_name) {
2436 codegen_fn_attrs.link_name = attr.value_str();
2437 } else if attr.check_name(sym::link_ordinal) {
2438 link_ordinal_span = Some(attr.span);
2439 if let ordinal @ Some(_) = check_link_ordinal(tcx, attr) {
2440 codegen_fn_attrs.link_ordinal = ordinal;
2442 } else if attr.check_name(sym::no_sanitize) {
2443 no_sanitize_span = Some(attr.span);
2444 if let Some(list) = attr.meta_item_list() {
2445 for item in list.iter() {
2446 if item.check_name(sym::address) {
2447 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_SANITIZE_ADDRESS;
2448 } else if item.check_name(sym::memory) {
2449 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_SANITIZE_MEMORY;
2450 } else if item.check_name(sym::thread) {
2451 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_SANITIZE_THREAD;
2454 .struct_span_err(item.span(), "invalid argument for `no_sanitize`")
2455 .note("expected one of: `address`, `memory` or `thread`")
2463 codegen_fn_attrs.inline = attrs.iter().fold(InlineAttr::None, |ia, attr| {
2464 if !attr.has_name(sym::inline) {
2467 match attr.meta().map(|i| i.kind) {
2468 Some(MetaItemKind::Word) => {
2472 Some(MetaItemKind::List(ref items)) => {
2474 inline_span = Some(attr.span);
2475 if items.len() != 1 {
2477 tcx.sess.diagnostic(),
2480 "expected one argument"
2484 } else if list_contains_name(&items[..], sym::always) {
2486 } else if list_contains_name(&items[..], sym::never) {
2490 tcx.sess.diagnostic(),
2500 Some(MetaItemKind::NameValue(_)) => ia,
2505 codegen_fn_attrs.optimize = attrs.iter().fold(OptimizeAttr::None, |ia, attr| {
2506 if !attr.has_name(sym::optimize) {
2509 let err = |sp, s| struct_span_err!(tcx.sess.diagnostic(), sp, E0722, "{}", s).emit();
2510 match attr.meta().map(|i| i.kind) {
2511 Some(MetaItemKind::Word) => {
2512 err(attr.span, "expected one argument");
2515 Some(MetaItemKind::List(ref items)) => {
2517 inline_span = Some(attr.span);
2518 if items.len() != 1 {
2519 err(attr.span, "expected one argument");
2521 } else if list_contains_name(&items[..], sym::size) {
2523 } else if list_contains_name(&items[..], sym::speed) {
2526 err(items[0].span(), "invalid argument");
2530 Some(MetaItemKind::NameValue(_)) => ia,
2535 // If a function uses #[target_feature] it can't be inlined into general
2536 // purpose functions as they wouldn't have the right target features
2537 // enabled. For that reason we also forbid #[inline(always)] as it can't be
2539 if !codegen_fn_attrs.target_features.is_empty() {
2540 if codegen_fn_attrs.inline == InlineAttr::Always {
2541 if let Some(span) = inline_span {
2544 "cannot use `#[inline(always)]` with \
2545 `#[target_feature]`",
2551 if codegen_fn_attrs.flags.intersects(CodegenFnAttrFlags::NO_SANITIZE_ANY) {
2552 if codegen_fn_attrs.inline == InlineAttr::Always {
2553 if let (Some(no_sanitize_span), Some(inline_span)) = (no_sanitize_span, inline_span) {
2554 let hir_id = tcx.hir().as_local_hir_id(id.expect_local());
2555 tcx.struct_span_lint_hir(
2556 lint::builtin::INLINE_NO_SANITIZE,
2560 lint.build("`no_sanitize` will have no effect after inlining")
2561 .span_note(inline_span, "inlining requested here")
2569 // Weak lang items have the same semantics as "std internal" symbols in the
2570 // sense that they're preserved through all our LTO passes and only
2571 // strippable by the linker.
2573 // Additionally weak lang items have predetermined symbol names.
2574 if tcx.is_weak_lang_item(id) {
2575 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2577 if let Some(name) = weak_lang_items::link_name(&attrs) {
2578 codegen_fn_attrs.export_name = Some(name);
2579 codegen_fn_attrs.link_name = Some(name);
2581 check_link_name_xor_ordinal(tcx, &codegen_fn_attrs, link_ordinal_span);
2583 // Internal symbols to the standard library all have no_mangle semantics in
2584 // that they have defined symbol names present in the function name. This
2585 // also applies to weak symbols where they all have known symbol names.
2586 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
2587 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2593 /// Checks if the provided DefId is a method in a trait impl for a trait which has track_caller
2594 /// applied to the method prototype.
2595 fn should_inherit_track_caller(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
2596 if let Some(impl_item) = tcx.opt_associated_item(def_id) {
2597 if let ty::AssocItemContainer::ImplContainer(impl_def_id) = impl_item.container {
2598 if let Some(trait_def_id) = tcx.trait_id_of_impl(impl_def_id) {
2599 if let Some(trait_item) = tcx
2600 .associated_items(trait_def_id)
2601 .filter_by_name_unhygienic(impl_item.ident.name)
2602 .find(move |trait_item| {
2603 trait_item.kind == ty::AssocKind::Fn
2604 && tcx.hygienic_eq(impl_item.ident, trait_item.ident, trait_def_id)
2608 .codegen_fn_attrs(trait_item.def_id)
2610 .intersects(CodegenFnAttrFlags::TRACK_CALLER);
2619 fn check_link_ordinal(tcx: TyCtxt<'_>, attr: &ast::Attribute) -> Option<usize> {
2620 use rustc_ast::ast::{Lit, LitIntType, LitKind};
2621 let meta_item_list = attr.meta_item_list();
2622 let meta_item_list: Option<&[ast::NestedMetaItem]> = meta_item_list.as_ref().map(Vec::as_ref);
2623 let sole_meta_list = match meta_item_list {
2624 Some([item]) => item.literal(),
2627 if let Some(Lit { kind: LitKind::Int(ordinal, LitIntType::Unsuffixed), .. }) = sole_meta_list {
2628 if *ordinal <= usize::MAX as u128 {
2629 Some(*ordinal as usize)
2631 let msg = format!("ordinal value in `link_ordinal` is too large: `{}`", &ordinal);
2633 .struct_span_err(attr.span, &msg)
2634 .note("the value may not exceed `usize::MAX`")
2640 .struct_span_err(attr.span, "illegal ordinal format in `link_ordinal`")
2641 .note("an unsuffixed integer value, e.g., `1`, is expected")
2647 fn check_link_name_xor_ordinal(
2649 codegen_fn_attrs: &CodegenFnAttrs,
2650 inline_span: Option<Span>,
2652 if codegen_fn_attrs.link_name.is_none() || codegen_fn_attrs.link_ordinal.is_none() {
2655 let msg = "cannot use `#[link_name]` with `#[link_ordinal]`";
2656 if let Some(span) = inline_span {
2657 tcx.sess.span_err(span, msg);