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::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};
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;
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::config::SanitizerSet;
44 use rustc_session::lint;
45 use rustc_session::parse::feature_err;
46 use rustc_span::symbol::{kw, sym, Ident, Symbol};
47 use rustc_span::{Span, DUMMY_SP};
48 use rustc_target::spec::abi;
49 use rustc_trait_selection::traits::error_reporting::suggestions::NextTypeParamName;
53 struct OnlySelfBounds(bool);
55 ///////////////////////////////////////////////////////////////////////////
58 fn collect_mod_item_types(tcx: TyCtxt<'_>, module_def_id: DefId) {
59 tcx.hir().visit_item_likes_in_module(
61 &mut CollectItemTypesVisitor { tcx }.as_deep_visitor(),
65 pub fn provide(providers: &mut Providers<'_>) {
66 *providers = Providers {
67 type_of: type_of::type_of,
70 predicates_defined_on,
71 explicit_predicates_of,
73 type_param_predicates,
83 collect_mod_item_types,
88 ///////////////////////////////////////////////////////////////////////////
90 /// Context specific to some particular item. This is what implements
91 /// `AstConv`. It has information about the predicates that are defined
92 /// on the trait. Unfortunately, this predicate information is
93 /// available in various different forms at various points in the
94 /// process. So we can't just store a pointer to e.g., the AST or the
95 /// parsed ty form, we have to be more flexible. To this end, the
96 /// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy
97 /// `get_type_parameter_bounds` requests, drawing the information from
98 /// the AST (`hir::Generics`), recursively.
99 pub struct ItemCtxt<'tcx> {
104 ///////////////////////////////////////////////////////////////////////////
107 crate struct PlaceholderHirTyCollector(crate Vec<Span>);
109 impl<'v> Visitor<'v> for PlaceholderHirTyCollector {
110 type Map = intravisit::ErasedMap<'v>;
112 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
113 NestedVisitorMap::None
115 fn visit_ty(&mut self, t: &'v hir::Ty<'v>) {
116 if let hir::TyKind::Infer = t.kind {
119 intravisit::walk_ty(self, t)
123 struct CollectItemTypesVisitor<'tcx> {
127 /// If there are any placeholder types (`_`), emit an error explaining that this is not allowed
128 /// and suggest adding type parameters in the appropriate place, taking into consideration any and
129 /// all already existing generic type parameters to avoid suggesting a name that is already in use.
130 crate fn placeholder_type_error(
133 generics: &[hir::GenericParam<'_>],
134 placeholder_types: Vec<Span>,
137 if placeholder_types.is_empty() {
140 let type_name = generics.next_type_param_name(None);
142 let mut sugg: Vec<_> =
143 placeholder_types.iter().map(|sp| (*sp, (*type_name).to_string())).collect();
144 if generics.is_empty() {
145 sugg.push((span, format!("<{}>", type_name)));
146 } else if let Some(arg) = generics.iter().find(|arg| match arg.name {
147 hir::ParamName::Plain(Ident { name: kw::Underscore, .. }) => true,
150 // Account for `_` already present in cases like `struct S<_>(_);` and suggest
151 // `struct S<T>(T);` instead of `struct S<_, T>(T);`.
152 sugg.push((arg.span, (*type_name).to_string()));
154 let last = generics.iter().last().unwrap();
156 // Account for bounds, we want `fn foo<T: E, K>(_: K)` not `fn foo<T, K: E>(_: K)`.
157 last.bounds_span().unwrap_or(last.span).shrink_to_hi(),
158 format!(", {}", type_name),
161 let mut err = bad_placeholder_type(tcx, placeholder_types);
163 err.multipart_suggestion(
164 "use type parameters instead",
166 Applicability::HasPlaceholders,
172 fn reject_placeholder_type_signatures_in_item(tcx: TyCtxt<'tcx>, item: &'tcx hir::Item<'tcx>) {
173 let (generics, suggest) = match &item.kind {
174 hir::ItemKind::Union(_, generics)
175 | hir::ItemKind::Enum(_, generics)
176 | hir::ItemKind::TraitAlias(generics, _)
177 | hir::ItemKind::Trait(_, _, generics, ..)
178 | hir::ItemKind::Impl { generics, .. }
179 | hir::ItemKind::Struct(_, generics) => (generics, true),
180 hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. })
181 | hir::ItemKind::TyAlias(_, generics) => (generics, false),
182 // `static`, `fn` and `const` are handled elsewhere to suggest appropriate type.
186 let mut visitor = PlaceholderHirTyCollector::default();
187 visitor.visit_item(item);
189 placeholder_type_error(tcx, generics.span, &generics.params[..], visitor.0, suggest);
192 impl Visitor<'tcx> for CollectItemTypesVisitor<'tcx> {
193 type Map = Map<'tcx>;
195 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
196 NestedVisitorMap::OnlyBodies(self.tcx.hir())
199 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
200 convert_item(self.tcx, item.hir_id);
201 reject_placeholder_type_signatures_in_item(self.tcx, item);
202 intravisit::walk_item(self, item);
205 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
206 for param in generics.params {
208 hir::GenericParamKind::Lifetime { .. } => {}
209 hir::GenericParamKind::Type { default: Some(_), .. } => {
210 let def_id = self.tcx.hir().local_def_id(param.hir_id);
211 self.tcx.ensure().type_of(def_id);
213 hir::GenericParamKind::Type { .. } => {}
214 hir::GenericParamKind::Const { .. } => {
215 let def_id = self.tcx.hir().local_def_id(param.hir_id);
216 self.tcx.ensure().type_of(def_id);
220 intravisit::walk_generics(self, generics);
223 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
224 if let hir::ExprKind::Closure(..) = expr.kind {
225 let def_id = self.tcx.hir().local_def_id(expr.hir_id);
226 self.tcx.ensure().generics_of(def_id);
227 self.tcx.ensure().type_of(def_id);
229 intravisit::walk_expr(self, expr);
232 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
233 convert_trait_item(self.tcx, trait_item.hir_id);
234 intravisit::walk_trait_item(self, trait_item);
237 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
238 convert_impl_item(self.tcx, impl_item.hir_id);
239 intravisit::walk_impl_item(self, impl_item);
243 ///////////////////////////////////////////////////////////////////////////
244 // Utility types and common code for the above passes.
246 fn bad_placeholder_type(
248 mut spans: Vec<Span>,
249 ) -> rustc_errors::DiagnosticBuilder<'tcx> {
251 let mut err = struct_span_err!(
255 "the type placeholder `_` is not allowed within types on item signatures",
258 err.span_label(span, "not allowed in type signatures");
263 impl ItemCtxt<'tcx> {
264 pub fn new(tcx: TyCtxt<'tcx>, item_def_id: DefId) -> ItemCtxt<'tcx> {
265 ItemCtxt { tcx, item_def_id }
268 pub fn to_ty(&self, ast_ty: &'tcx hir::Ty<'tcx>) -> Ty<'tcx> {
269 AstConv::ast_ty_to_ty(self, ast_ty)
272 pub fn hir_id(&self) -> hir::HirId {
273 self.tcx.hir().as_local_hir_id(self.item_def_id.expect_local())
276 pub fn node(&self) -> hir::Node<'tcx> {
277 self.tcx.hir().get(self.hir_id())
281 impl AstConv<'tcx> for ItemCtxt<'tcx> {
282 fn tcx(&self) -> TyCtxt<'tcx> {
286 fn item_def_id(&self) -> Option<DefId> {
287 Some(self.item_def_id)
290 fn default_constness_for_trait_bounds(&self) -> hir::Constness {
291 if let Some(fn_like) = FnLikeNode::from_node(self.node()) {
294 hir::Constness::NotConst
298 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId) -> ty::GenericPredicates<'tcx> {
299 self.tcx.at(span).type_param_predicates((self.item_def_id, def_id.expect_local()))
302 fn re_infer(&self, _: Option<&ty::GenericParamDef>, _: Span) -> Option<ty::Region<'tcx>> {
306 fn allow_ty_infer(&self) -> bool {
310 fn ty_infer(&self, _: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx> {
311 self.tcx().ty_error_with_message(span, "bad_placeholder_type")
317 _: Option<&ty::GenericParamDef>,
319 ) -> &'tcx Const<'tcx> {
320 bad_placeholder_type(self.tcx(), vec![span]).emit();
321 self.tcx().const_error(ty)
324 fn projected_ty_from_poly_trait_ref(
328 item_segment: &hir::PathSegment<'_>,
329 poly_trait_ref: ty::PolyTraitRef<'tcx>,
331 if let Some(trait_ref) = poly_trait_ref.no_bound_vars() {
332 let item_substs = <dyn AstConv<'tcx>>::create_substs_for_associated_item(
340 self.tcx().mk_projection(item_def_id, item_substs)
342 // There are no late-bound regions; we can just ignore the binder.
343 let mut err = struct_span_err!(
347 "cannot extract an associated type from a higher-ranked trait bound \
352 hir::Node::Field(_) | hir::Node::Ctor(_) | hir::Node::Variant(_) => {
354 self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(self.hir_id()));
356 hir::ItemKind::Enum(_, generics)
357 | hir::ItemKind::Struct(_, generics)
358 | hir::ItemKind::Union(_, generics) => {
359 let lt_name = get_new_lifetime_name(self.tcx, poly_trait_ref, generics);
360 let (lt_sp, sugg) = match &generics.params[..] {
361 [] => (generics.span, format!("<{}>", lt_name)),
363 (bound.span.shrink_to_lo(), format!("{}, ", lt_name))
366 let suggestions = vec![
372 // Replace the existing lifetimes with a new named lifetime.
374 .replace_late_bound_regions(&poly_trait_ref, |_| {
375 self.tcx.mk_region(ty::ReEarlyBound(
376 ty::EarlyBoundRegion {
379 name: Symbol::intern(<_name),
388 err.multipart_suggestion(
389 "use a fully qualified path with explicit lifetimes",
391 Applicability::MaybeIncorrect,
397 hir::Node::Item(hir::Item {
399 hir::ItemKind::Struct(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Union(..),
403 | hir::Node::ForeignItem(_)
404 | hir::Node::TraitItem(_)
405 | hir::Node::ImplItem(_) => {
408 "use a fully qualified path with inferred lifetimes",
411 // Erase named lt, we want `<A as B<'_>::C`, not `<A as B<'a>::C`.
412 self.tcx.anonymize_late_bound_regions(&poly_trait_ref).skip_binder(),
415 Applicability::MaybeIncorrect,
421 self.tcx().ty_error()
425 fn normalize_ty(&self, _span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
426 // Types in item signatures are not normalized to avoid undue dependencies.
430 fn set_tainted_by_errors(&self) {
431 // There's no obvious place to track this, so just let it go.
434 fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) {
435 // There's no place to record types from signatures?
439 /// Synthesize a new lifetime name that doesn't clash with any of the lifetimes already present.
440 fn get_new_lifetime_name<'tcx>(
442 poly_trait_ref: ty::PolyTraitRef<'tcx>,
443 generics: &hir::Generics<'tcx>,
445 let existing_lifetimes = tcx
446 .collect_referenced_late_bound_regions(&poly_trait_ref)
449 if let ty::BoundRegion::BrNamed(_, name) = lt {
450 Some(name.as_str().to_string())
455 .chain(generics.params.iter().filter_map(|param| {
456 if let hir::GenericParamKind::Lifetime { .. } = ¶m.kind {
457 Some(param.name.ident().as_str().to_string())
462 .collect::<FxHashSet<String>>();
464 let a_to_z_repeat_n = |n| {
465 (b'a'..=b'z').map(move |c| {
466 let mut s = '\''.to_string();
467 s.extend(std::iter::repeat(char::from(c)).take(n));
472 // If all single char lifetime names are present, we wrap around and double the chars.
473 (1..).flat_map(a_to_z_repeat_n).find(|lt| !existing_lifetimes.contains(lt.as_str())).unwrap()
476 /// Returns the predicates defined on `item_def_id` of the form
477 /// `X: Foo` where `X` is the type parameter `def_id`.
478 fn type_param_predicates(
480 (item_def_id, def_id): (DefId, LocalDefId),
481 ) -> ty::GenericPredicates<'_> {
484 // In the AST, bounds can derive from two places. Either
485 // written inline like `<T: Foo>` or in a where-clause like
488 let param_id = tcx.hir().as_local_hir_id(def_id);
489 let param_owner = tcx.hir().ty_param_owner(param_id);
490 let param_owner_def_id = tcx.hir().local_def_id(param_owner);
491 let generics = tcx.generics_of(param_owner_def_id);
492 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
493 let ty = tcx.mk_ty_param(index, tcx.hir().ty_param_name(param_id));
495 // Don't look for bounds where the type parameter isn't in scope.
496 let parent = if item_def_id == param_owner_def_id.to_def_id() {
499 tcx.generics_of(item_def_id).parent
502 let mut result = parent
504 let icx = ItemCtxt::new(tcx, parent);
505 icx.get_type_parameter_bounds(DUMMY_SP, def_id.to_def_id())
507 .unwrap_or_default();
508 let mut extend = None;
510 let item_hir_id = tcx.hir().as_local_hir_id(item_def_id.expect_local());
511 let ast_generics = match tcx.hir().get(item_hir_id) {
512 Node::TraitItem(item) => &item.generics,
514 Node::ImplItem(item) => &item.generics,
516 Node::Item(item) => {
518 ItemKind::Fn(.., ref generics, _)
519 | ItemKind::Impl { ref generics, .. }
520 | ItemKind::TyAlias(_, ref generics)
521 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
522 | ItemKind::Enum(_, ref generics)
523 | ItemKind::Struct(_, ref generics)
524 | ItemKind::Union(_, ref generics) => generics,
525 ItemKind::Trait(_, _, ref generics, ..) => {
526 // Implied `Self: Trait` and supertrait bounds.
527 if param_id == item_hir_id {
528 let identity_trait_ref = ty::TraitRef::identity(tcx, item_def_id);
530 Some((identity_trait_ref.without_const().to_predicate(tcx), item.span));
538 Node::ForeignItem(item) => match item.kind {
539 ForeignItemKind::Fn(_, _, ref generics) => generics,
546 let icx = ItemCtxt::new(tcx, item_def_id);
547 let extra_predicates = extend.into_iter().chain(
548 icx.type_parameter_bounds_in_generics(ast_generics, param_id, ty, OnlySelfBounds(true))
550 .filter(|(predicate, _)| match predicate.kind() {
551 ty::PredicateKind::Trait(ref data, _) => {
552 data.skip_binder().self_ty().is_param(index)
558 tcx.arena.alloc_from_iter(result.predicates.iter().copied().chain(extra_predicates));
562 impl ItemCtxt<'tcx> {
563 /// Finds bounds from `hir::Generics`. This requires scanning through the
564 /// AST. We do this to avoid having to convert *all* the bounds, which
565 /// would create artificial cycles. Instead, we can only convert the
566 /// bounds for a type parameter `X` if `X::Foo` is used.
567 fn type_parameter_bounds_in_generics(
569 ast_generics: &'tcx hir::Generics<'tcx>,
570 param_id: hir::HirId,
572 only_self_bounds: OnlySelfBounds,
573 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
574 let constness = self.default_constness_for_trait_bounds();
575 let from_ty_params = ast_generics
578 .filter_map(|param| match param.kind {
579 GenericParamKind::Type { .. } if param.hir_id == param_id => Some(¶m.bounds),
582 .flat_map(|bounds| bounds.iter())
583 .flat_map(|b| predicates_from_bound(self, ty, b, constness));
585 let from_where_clauses = ast_generics
589 .filter_map(|wp| match *wp {
590 hir::WherePredicate::BoundPredicate(ref bp) => Some(bp),
594 let bt = if is_param(self.tcx, &bp.bounded_ty, param_id) {
596 } else if !only_self_bounds.0 {
597 Some(self.to_ty(&bp.bounded_ty))
601 bp.bounds.iter().filter_map(move |b| bt.map(|bt| (bt, b)))
603 .flat_map(|(bt, b)| predicates_from_bound(self, bt, b, constness));
605 from_ty_params.chain(from_where_clauses).collect()
609 /// Tests whether this is the AST for a reference to the type
610 /// parameter with ID `param_id`. We use this so as to avoid running
611 /// `ast_ty_to_ty`, because we want to avoid triggering an all-out
612 /// conversion of the type to avoid inducing unnecessary cycles.
613 fn is_param(tcx: TyCtxt<'_>, ast_ty: &hir::Ty<'_>, param_id: hir::HirId) -> bool {
614 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = ast_ty.kind {
616 Res::SelfTy(Some(def_id), None) | Res::Def(DefKind::TyParam, def_id) => {
617 def_id == tcx.hir().local_def_id(param_id).to_def_id()
626 fn convert_item(tcx: TyCtxt<'_>, item_id: hir::HirId) {
627 let it = tcx.hir().expect_item(item_id);
628 debug!("convert: item {} with id {}", it.ident, it.hir_id);
629 let def_id = tcx.hir().local_def_id(item_id);
631 // These don't define types.
632 hir::ItemKind::ExternCrate(_)
633 | hir::ItemKind::Use(..)
634 | hir::ItemKind::Mod(_)
635 | hir::ItemKind::GlobalAsm(_) => {}
636 hir::ItemKind::ForeignMod(ref foreign_mod) => {
637 for item in foreign_mod.items {
638 let def_id = tcx.hir().local_def_id(item.hir_id);
639 tcx.ensure().generics_of(def_id);
640 tcx.ensure().type_of(def_id);
641 tcx.ensure().predicates_of(def_id);
642 if let hir::ForeignItemKind::Fn(..) = item.kind {
643 tcx.ensure().fn_sig(def_id);
647 hir::ItemKind::Enum(ref enum_definition, _) => {
648 tcx.ensure().generics_of(def_id);
649 tcx.ensure().type_of(def_id);
650 tcx.ensure().predicates_of(def_id);
651 convert_enum_variant_types(tcx, def_id.to_def_id(), &enum_definition.variants);
653 hir::ItemKind::Impl { .. } => {
654 tcx.ensure().generics_of(def_id);
655 tcx.ensure().type_of(def_id);
656 tcx.ensure().impl_trait_ref(def_id);
657 tcx.ensure().predicates_of(def_id);
659 hir::ItemKind::Trait(..) => {
660 tcx.ensure().generics_of(def_id);
661 tcx.ensure().trait_def(def_id);
662 tcx.at(it.span).super_predicates_of(def_id);
663 tcx.ensure().predicates_of(def_id);
665 hir::ItemKind::TraitAlias(..) => {
666 tcx.ensure().generics_of(def_id);
667 tcx.at(it.span).super_predicates_of(def_id);
668 tcx.ensure().predicates_of(def_id);
670 hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
671 tcx.ensure().generics_of(def_id);
672 tcx.ensure().type_of(def_id);
673 tcx.ensure().predicates_of(def_id);
675 for f in struct_def.fields() {
676 let def_id = tcx.hir().local_def_id(f.hir_id);
677 tcx.ensure().generics_of(def_id);
678 tcx.ensure().type_of(def_id);
679 tcx.ensure().predicates_of(def_id);
682 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
683 convert_variant_ctor(tcx, ctor_hir_id);
687 // Desugared from `impl Trait`, so visited by the function's return type.
688 hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: Some(_), .. }) => {}
690 hir::ItemKind::OpaqueTy(..)
691 | hir::ItemKind::TyAlias(..)
692 | hir::ItemKind::Static(..)
693 | hir::ItemKind::Const(..)
694 | hir::ItemKind::Fn(..) => {
695 tcx.ensure().generics_of(def_id);
696 tcx.ensure().type_of(def_id);
697 tcx.ensure().predicates_of(def_id);
698 if let hir::ItemKind::Fn(..) = it.kind {
699 tcx.ensure().fn_sig(def_id);
705 fn convert_trait_item(tcx: TyCtxt<'_>, trait_item_id: hir::HirId) {
706 let trait_item = tcx.hir().expect_trait_item(trait_item_id);
707 let def_id = tcx.hir().local_def_id(trait_item.hir_id);
708 tcx.ensure().generics_of(def_id);
710 match trait_item.kind {
711 hir::TraitItemKind::Fn(..) => {
712 tcx.ensure().type_of(def_id);
713 tcx.ensure().fn_sig(def_id);
716 hir::TraitItemKind::Const(.., Some(_)) => {
717 tcx.ensure().type_of(def_id);
720 hir::TraitItemKind::Const(..) | hir::TraitItemKind::Type(_, Some(_)) => {
721 tcx.ensure().type_of(def_id);
722 // Account for `const C: _;` and `type T = _;`.
723 let mut visitor = PlaceholderHirTyCollector::default();
724 visitor.visit_trait_item(trait_item);
725 placeholder_type_error(tcx, DUMMY_SP, &[], visitor.0, false);
728 hir::TraitItemKind::Type(_, None) => {}
731 tcx.ensure().predicates_of(def_id);
734 fn convert_impl_item(tcx: TyCtxt<'_>, impl_item_id: hir::HirId) {
735 let def_id = tcx.hir().local_def_id(impl_item_id);
736 tcx.ensure().generics_of(def_id);
737 tcx.ensure().type_of(def_id);
738 tcx.ensure().predicates_of(def_id);
739 let impl_item = tcx.hir().expect_impl_item(impl_item_id);
740 match impl_item.kind {
741 hir::ImplItemKind::Fn(..) => {
742 tcx.ensure().fn_sig(def_id);
744 hir::ImplItemKind::TyAlias(_) => {
745 // Account for `type T = _;`
746 let mut visitor = PlaceholderHirTyCollector::default();
747 visitor.visit_impl_item(impl_item);
748 placeholder_type_error(tcx, DUMMY_SP, &[], visitor.0, false);
750 hir::ImplItemKind::Const(..) => {}
754 fn convert_variant_ctor(tcx: TyCtxt<'_>, ctor_id: hir::HirId) {
755 let def_id = tcx.hir().local_def_id(ctor_id);
756 tcx.ensure().generics_of(def_id);
757 tcx.ensure().type_of(def_id);
758 tcx.ensure().predicates_of(def_id);
761 fn convert_enum_variant_types(tcx: TyCtxt<'_>, def_id: DefId, variants: &[hir::Variant<'_>]) {
762 let def = tcx.adt_def(def_id);
763 let repr_type = def.repr.discr_type();
764 let initial = repr_type.initial_discriminant(tcx);
765 let mut prev_discr = None::<Discr<'_>>;
767 // fill the discriminant values and field types
768 for variant in variants {
769 let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
771 if let Some(ref e) = variant.disr_expr {
772 let expr_did = tcx.hir().local_def_id(e.hir_id);
773 def.eval_explicit_discr(tcx, expr_did.to_def_id())
774 } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) {
777 struct_span_err!(tcx.sess, variant.span, E0370, "enum discriminant overflowed")
780 format!("overflowed on value after {}", prev_discr.unwrap()),
783 "explicitly set `{} = {}` if that is desired outcome",
784 variant.ident, wrapped_discr
789 .unwrap_or(wrapped_discr),
792 for f in variant.data.fields() {
793 let def_id = tcx.hir().local_def_id(f.hir_id);
794 tcx.ensure().generics_of(def_id);
795 tcx.ensure().type_of(def_id);
796 tcx.ensure().predicates_of(def_id);
799 // Convert the ctor, if any. This also registers the variant as
801 if let Some(ctor_hir_id) = variant.data.ctor_hir_id() {
802 convert_variant_ctor(tcx, ctor_hir_id);
809 variant_did: Option<LocalDefId>,
810 ctor_did: Option<LocalDefId>,
812 discr: ty::VariantDiscr,
813 def: &hir::VariantData<'_>,
814 adt_kind: ty::AdtKind,
815 parent_did: LocalDefId,
816 ) -> ty::VariantDef {
817 let mut seen_fields: FxHashMap<Ident, Span> = Default::default();
818 let hir_id = tcx.hir().as_local_hir_id(variant_did.unwrap_or(parent_did));
823 let fid = tcx.hir().local_def_id(f.hir_id);
824 let dup_span = seen_fields.get(&f.ident.normalize_to_macros_2_0()).cloned();
825 if let Some(prev_span) = dup_span {
830 "field `{}` is already declared",
833 .span_label(f.span, "field already declared")
834 .span_label(prev_span, format!("`{}` first declared here", f.ident))
837 seen_fields.insert(f.ident.normalize_to_macros_2_0(), f.span);
841 did: fid.to_def_id(),
843 vis: ty::Visibility::from_hir(&f.vis, hir_id, tcx),
847 let recovered = match def {
848 hir::VariantData::Struct(_, r) => *r,
854 variant_did.map(LocalDefId::to_def_id),
855 ctor_did.map(LocalDefId::to_def_id),
858 CtorKind::from_hir(def),
860 parent_did.to_def_id(),
865 fn adt_def(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::AdtDef {
868 let def_id = def_id.expect_local();
869 let hir_id = tcx.hir().as_local_hir_id(def_id);
870 let item = match tcx.hir().get(hir_id) {
871 Node::Item(item) => item,
875 let repr = ReprOptions::new(tcx, def_id.to_def_id());
876 let (kind, variants) = match item.kind {
877 ItemKind::Enum(ref def, _) => {
878 let mut distance_from_explicit = 0;
883 let variant_did = Some(tcx.hir().local_def_id(v.id));
885 v.data.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
887 let discr = if let Some(ref e) = v.disr_expr {
888 distance_from_explicit = 0;
889 ty::VariantDiscr::Explicit(tcx.hir().local_def_id(e.hir_id).to_def_id())
891 ty::VariantDiscr::Relative(distance_from_explicit)
893 distance_from_explicit += 1;
908 (AdtKind::Enum, variants)
910 ItemKind::Struct(ref def, _) => {
911 let variant_did = None::<LocalDefId>;
912 let ctor_did = def.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
914 let variants = std::iter::once(convert_variant(
919 ty::VariantDiscr::Relative(0),
926 (AdtKind::Struct, variants)
928 ItemKind::Union(ref def, _) => {
929 let variant_did = None;
930 let ctor_did = def.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
932 let variants = std::iter::once(convert_variant(
937 ty::VariantDiscr::Relative(0),
944 (AdtKind::Union, variants)
948 tcx.alloc_adt_def(def_id.to_def_id(), kind, variants, repr)
951 /// Ensures that the super-predicates of the trait with a `DefId`
952 /// of `trait_def_id` are converted and stored. This also ensures that
953 /// the transitive super-predicates are converted.
954 fn super_predicates_of(tcx: TyCtxt<'_>, trait_def_id: DefId) -> ty::GenericPredicates<'_> {
955 debug!("super_predicates(trait_def_id={:?})", trait_def_id);
956 let trait_hir_id = tcx.hir().as_local_hir_id(trait_def_id.expect_local());
958 let item = match tcx.hir().get(trait_hir_id) {
959 Node::Item(item) => item,
960 _ => bug!("trait_node_id {} is not an item", trait_hir_id),
963 let (generics, bounds) = match item.kind {
964 hir::ItemKind::Trait(.., ref generics, ref supertraits, _) => (generics, supertraits),
965 hir::ItemKind::TraitAlias(ref generics, ref supertraits) => (generics, supertraits),
966 _ => span_bug!(item.span, "super_predicates invoked on non-trait"),
969 let icx = ItemCtxt::new(tcx, trait_def_id);
971 // Convert the bounds that follow the colon, e.g., `Bar + Zed` in `trait Foo: Bar + Zed`.
972 let self_param_ty = tcx.types.self_param;
974 AstConv::compute_bounds(&icx, self_param_ty, bounds, SizedByDefault::No, item.span);
976 let superbounds1 = superbounds1.predicates(tcx, self_param_ty);
978 // Convert any explicit superbounds in the where-clause,
979 // e.g., `trait Foo where Self: Bar`.
980 // In the case of trait aliases, however, we include all bounds in the where-clause,
981 // so e.g., `trait Foo = where u32: PartialEq<Self>` would include `u32: PartialEq<Self>`
982 // as one of its "superpredicates".
983 let is_trait_alias = tcx.is_trait_alias(trait_def_id);
984 let superbounds2 = icx.type_parameter_bounds_in_generics(
988 OnlySelfBounds(!is_trait_alias),
991 // Combine the two lists to form the complete set of superbounds:
992 let superbounds = &*tcx.arena.alloc_from_iter(superbounds1.into_iter().chain(superbounds2));
994 // Now require that immediate supertraits are converted,
995 // which will, in turn, reach indirect supertraits.
996 for &(pred, span) in superbounds {
997 debug!("superbound: {:?}", pred);
998 if let ty::PredicateKind::Trait(bound, _) = pred.kind() {
999 tcx.at(span).super_predicates_of(bound.def_id());
1003 ty::GenericPredicates { parent: None, predicates: superbounds }
1006 fn trait_def(tcx: TyCtxt<'_>, def_id: DefId) -> ty::TraitDef {
1007 let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local());
1008 let item = tcx.hir().expect_item(hir_id);
1010 let (is_auto, unsafety) = match item.kind {
1011 hir::ItemKind::Trait(is_auto, unsafety, ..) => (is_auto == hir::IsAuto::Yes, unsafety),
1012 hir::ItemKind::TraitAlias(..) => (false, hir::Unsafety::Normal),
1013 _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
1016 let paren_sugar = tcx.has_attr(def_id, sym::rustc_paren_sugar);
1017 if paren_sugar && !tcx.features().unboxed_closures {
1021 "the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \
1022 which traits can use parenthetical notation",
1024 .help("add `#![feature(unboxed_closures)]` to the crate attributes to use it")
1028 let is_marker = tcx.has_attr(def_id, sym::marker);
1029 let spec_kind = if tcx.has_attr(def_id, sym::rustc_unsafe_specialization_marker) {
1030 ty::trait_def::TraitSpecializationKind::Marker
1031 } else if tcx.has_attr(def_id, sym::rustc_specialization_trait) {
1032 ty::trait_def::TraitSpecializationKind::AlwaysApplicable
1034 ty::trait_def::TraitSpecializationKind::None
1036 let def_path_hash = tcx.def_path_hash(def_id);
1037 ty::TraitDef::new(def_id, unsafety, paren_sugar, is_auto, is_marker, spec_kind, def_path_hash)
1040 fn has_late_bound_regions<'tcx>(tcx: TyCtxt<'tcx>, node: Node<'tcx>) -> Option<Span> {
1041 struct LateBoundRegionsDetector<'tcx> {
1043 outer_index: ty::DebruijnIndex,
1044 has_late_bound_regions: Option<Span>,
1047 impl Visitor<'tcx> for LateBoundRegionsDetector<'tcx> {
1048 type Map = intravisit::ErasedMap<'tcx>;
1050 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1051 NestedVisitorMap::None
1054 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
1055 if self.has_late_bound_regions.is_some() {
1059 hir::TyKind::BareFn(..) => {
1060 self.outer_index.shift_in(1);
1061 intravisit::walk_ty(self, ty);
1062 self.outer_index.shift_out(1);
1064 _ => intravisit::walk_ty(self, ty),
1068 fn visit_poly_trait_ref(
1070 tr: &'tcx hir::PolyTraitRef<'tcx>,
1071 m: hir::TraitBoundModifier,
1073 if self.has_late_bound_regions.is_some() {
1076 self.outer_index.shift_in(1);
1077 intravisit::walk_poly_trait_ref(self, tr, m);
1078 self.outer_index.shift_out(1);
1081 fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
1082 if self.has_late_bound_regions.is_some() {
1086 match self.tcx.named_region(lt.hir_id) {
1087 Some(rl::Region::Static | rl::Region::EarlyBound(..)) => {}
1089 rl::Region::LateBound(debruijn, _, _) | rl::Region::LateBoundAnon(debruijn, _),
1090 ) if debruijn < self.outer_index => {}
1092 rl::Region::LateBound(..)
1093 | rl::Region::LateBoundAnon(..)
1094 | rl::Region::Free(..),
1097 self.has_late_bound_regions = Some(lt.span);
1103 fn has_late_bound_regions<'tcx>(
1105 generics: &'tcx hir::Generics<'tcx>,
1106 decl: &'tcx hir::FnDecl<'tcx>,
1108 let mut visitor = LateBoundRegionsDetector {
1110 outer_index: ty::INNERMOST,
1111 has_late_bound_regions: None,
1113 for param in generics.params {
1114 if let GenericParamKind::Lifetime { .. } = param.kind {
1115 if tcx.is_late_bound(param.hir_id) {
1116 return Some(param.span);
1120 visitor.visit_fn_decl(decl);
1121 visitor.has_late_bound_regions
1125 Node::TraitItem(item) => match item.kind {
1126 hir::TraitItemKind::Fn(ref sig, _) => {
1127 has_late_bound_regions(tcx, &item.generics, &sig.decl)
1131 Node::ImplItem(item) => match item.kind {
1132 hir::ImplItemKind::Fn(ref sig, _) => {
1133 has_late_bound_regions(tcx, &item.generics, &sig.decl)
1137 Node::ForeignItem(item) => match item.kind {
1138 hir::ForeignItemKind::Fn(ref fn_decl, _, ref generics) => {
1139 has_late_bound_regions(tcx, generics, fn_decl)
1143 Node::Item(item) => match item.kind {
1144 hir::ItemKind::Fn(ref sig, .., ref generics, _) => {
1145 has_late_bound_regions(tcx, generics, &sig.decl)
1153 fn generics_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::Generics {
1156 let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local());
1158 let node = tcx.hir().get(hir_id);
1159 let parent_def_id = match node {
1161 | Node::TraitItem(_)
1164 | Node::Field(_) => {
1165 let parent_id = tcx.hir().get_parent_item(hir_id);
1166 Some(tcx.hir().local_def_id(parent_id).to_def_id())
1168 // FIXME(#43408) always enable this once `lazy_normalization` is
1169 // stable enough and does not need a feature gate anymore.
1170 Node::AnonConst(_) => {
1171 let parent_id = tcx.hir().get_parent_item(hir_id);
1172 let parent_def_id = tcx.hir().local_def_id(parent_id);
1174 // HACK(eddyb) this provides the correct generics when
1175 // `feature(const_generics)` is enabled, so that const expressions
1176 // used with const generics, e.g. `Foo<{N+1}>`, can work at all.
1177 if tcx.lazy_normalization() {
1178 Some(parent_def_id.to_def_id())
1180 let parent_node = tcx.hir().get(tcx.hir().get_parent_node(hir_id));
1182 // HACK(eddyb) this provides the correct generics for repeat
1183 // expressions' count (i.e. `N` in `[x; N]`), and explicit
1184 // `enum` discriminants (i.e. `D` in `enum Foo { Bar = D }`),
1185 // as they shouldn't be able to cause query cycle errors.
1186 Node::Expr(&Expr { kind: ExprKind::Repeat(_, ref constant), .. })
1187 | Node::Variant(Variant { disr_expr: Some(ref constant), .. })
1188 if constant.hir_id == hir_id =>
1190 Some(parent_def_id.to_def_id())
1197 Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => {
1198 Some(tcx.closure_base_def_id(def_id))
1200 Node::Item(item) => match item.kind {
1201 ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn, .. }) => {
1202 impl_trait_fn.or_else(|| {
1203 let parent_id = tcx.hir().get_parent_item(hir_id);
1204 assert!(parent_id != hir_id && parent_id != CRATE_HIR_ID);
1205 debug!("generics_of: parent of opaque ty {:?} is {:?}", def_id, parent_id);
1206 // Opaque types are always nested within another item, and
1207 // inherit the generics of the item.
1208 Some(tcx.hir().local_def_id(parent_id).to_def_id())
1216 let mut opt_self = None;
1217 let mut allow_defaults = false;
1219 let no_generics = hir::Generics::empty();
1220 let ast_generics = match node {
1221 Node::TraitItem(item) => &item.generics,
1223 Node::ImplItem(item) => &item.generics,
1225 Node::Item(item) => {
1227 ItemKind::Fn(.., ref generics, _) | ItemKind::Impl { ref generics, .. } => generics,
1229 ItemKind::TyAlias(_, ref generics)
1230 | ItemKind::Enum(_, ref generics)
1231 | ItemKind::Struct(_, ref generics)
1232 | ItemKind::OpaqueTy(hir::OpaqueTy { ref generics, .. })
1233 | ItemKind::Union(_, ref generics) => {
1234 allow_defaults = true;
1238 ItemKind::Trait(_, _, ref generics, ..)
1239 | ItemKind::TraitAlias(ref generics, ..) => {
1240 // Add in the self type parameter.
1242 // Something of a hack: use the node id for the trait, also as
1243 // the node id for the Self type parameter.
1244 let param_id = item.hir_id;
1246 opt_self = Some(ty::GenericParamDef {
1248 name: kw::SelfUpper,
1249 def_id: tcx.hir().local_def_id(param_id).to_def_id(),
1250 pure_wrt_drop: false,
1251 kind: ty::GenericParamDefKind::Type {
1253 object_lifetime_default: rl::Set1::Empty,
1258 allow_defaults = true;
1266 Node::ForeignItem(item) => match item.kind {
1267 ForeignItemKind::Static(..) => &no_generics,
1268 ForeignItemKind::Fn(_, _, ref generics) => generics,
1269 ForeignItemKind::Type => &no_generics,
1275 let has_self = opt_self.is_some();
1276 let mut parent_has_self = false;
1277 let mut own_start = has_self as u32;
1278 let parent_count = parent_def_id.map_or(0, |def_id| {
1279 let generics = tcx.generics_of(def_id);
1280 assert_eq!(has_self, false);
1281 parent_has_self = generics.has_self;
1282 own_start = generics.count() as u32;
1283 generics.parent_count + generics.params.len()
1286 let mut params: Vec<_> = opt_self.into_iter().collect();
1288 let early_lifetimes = early_bound_lifetimes_from_generics(tcx, ast_generics);
1289 params.extend(early_lifetimes.enumerate().map(|(i, param)| ty::GenericParamDef {
1290 name: param.name.ident().name,
1291 index: own_start + i as u32,
1292 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
1293 pure_wrt_drop: param.pure_wrt_drop,
1294 kind: ty::GenericParamDefKind::Lifetime,
1297 let object_lifetime_defaults = tcx.object_lifetime_defaults(hir_id);
1299 // Now create the real type and const parameters.
1300 let type_start = own_start - has_self as u32 + params.len() as u32;
1303 // FIXME(const_generics): a few places in the compiler expect generic params
1304 // to be in the order lifetimes, then type params, then const params.
1306 // To prevent internal errors in case const parameters are supplied before
1307 // type parameters we first add all type params, then all const params.
1308 params.extend(ast_generics.params.iter().filter_map(|param| {
1309 if let GenericParamKind::Type { ref default, synthetic, .. } = param.kind {
1310 if !allow_defaults && default.is_some() {
1311 if !tcx.features().default_type_parameter_fallback {
1312 tcx.struct_span_lint_hir(
1313 lint::builtin::INVALID_TYPE_PARAM_DEFAULT,
1318 "defaults for type parameters are only allowed in \
1319 `struct`, `enum`, `type`, or `trait` definitions.",
1327 let kind = ty::GenericParamDefKind::Type {
1328 has_default: default.is_some(),
1329 object_lifetime_default: object_lifetime_defaults
1331 .map_or(rl::Set1::Empty, |o| o[i]),
1335 let param_def = ty::GenericParamDef {
1336 index: type_start + i as u32,
1337 name: param.name.ident().name,
1338 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
1339 pure_wrt_drop: param.pure_wrt_drop,
1349 params.extend(ast_generics.params.iter().filter_map(|param| {
1350 if let GenericParamKind::Const { .. } = param.kind {
1351 let param_def = ty::GenericParamDef {
1352 index: type_start + i as u32,
1353 name: param.name.ident().name,
1354 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
1355 pure_wrt_drop: param.pure_wrt_drop,
1356 kind: ty::GenericParamDefKind::Const,
1365 // provide junk type parameter defs - the only place that
1366 // cares about anything but the length is instantiation,
1367 // and we don't do that for closures.
1368 if let Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(.., gen), .. }) = node {
1369 let dummy_args = if gen.is_some() {
1370 &["<resume_ty>", "<yield_ty>", "<return_ty>", "<witness>", "<upvars>"][..]
1372 &["<closure_kind>", "<closure_signature>", "<upvars>"][..]
1375 params.extend(dummy_args.iter().enumerate().map(|(i, &arg)| ty::GenericParamDef {
1376 index: type_start + i as u32,
1377 name: Symbol::intern(arg),
1379 pure_wrt_drop: false,
1380 kind: ty::GenericParamDefKind::Type {
1382 object_lifetime_default: rl::Set1::Empty,
1388 let param_def_id_to_index = params.iter().map(|param| (param.def_id, param.index)).collect();
1391 parent: parent_def_id,
1394 param_def_id_to_index,
1395 has_self: has_self || parent_has_self,
1396 has_late_bound_regions: has_late_bound_regions(tcx, node),
1400 fn are_suggestable_generic_args(generic_args: &[hir::GenericArg<'_>]) -> bool {
1403 .filter_map(|arg| match arg {
1404 hir::GenericArg::Type(ty) => Some(ty),
1407 .any(is_suggestable_infer_ty)
1410 /// Whether `ty` is a type with `_` placeholders that can be inferred. Used in diagnostics only to
1411 /// use inference to provide suggestions for the appropriate type if possible.
1412 fn is_suggestable_infer_ty(ty: &hir::Ty<'_>) -> bool {
1416 Slice(ty) | Array(ty, _) => is_suggestable_infer_ty(ty),
1417 Tup(tys) => tys.iter().any(is_suggestable_infer_ty),
1418 Ptr(mut_ty) | Rptr(_, mut_ty) => is_suggestable_infer_ty(mut_ty.ty),
1419 OpaqueDef(_, generic_args) => are_suggestable_generic_args(generic_args),
1420 Path(hir::QPath::TypeRelative(ty, segment)) => {
1421 is_suggestable_infer_ty(ty) || are_suggestable_generic_args(segment.generic_args().args)
1423 Path(hir::QPath::Resolved(ty_opt, hir::Path { segments, .. })) => {
1424 ty_opt.map_or(false, is_suggestable_infer_ty)
1427 .any(|segment| are_suggestable_generic_args(segment.generic_args().args))
1433 pub fn get_infer_ret_ty(output: &'hir hir::FnRetTy<'hir>) -> Option<&'hir hir::Ty<'hir>> {
1434 if let hir::FnRetTy::Return(ref ty) = output {
1435 if is_suggestable_infer_ty(ty) {
1442 fn fn_sig(tcx: TyCtxt<'_>, def_id: DefId) -> ty::PolyFnSig<'_> {
1443 use rustc_hir::Node::*;
1446 let def_id = def_id.expect_local();
1447 let hir_id = tcx.hir().as_local_hir_id(def_id);
1449 let icx = ItemCtxt::new(tcx, def_id.to_def_id());
1451 match tcx.hir().get(hir_id) {
1452 TraitItem(hir::TraitItem {
1453 kind: TraitItemKind::Fn(sig, TraitFn::Provided(_)),
1458 | ImplItem(hir::ImplItem { kind: ImplItemKind::Fn(sig, _), ident, generics, .. })
1459 | Item(hir::Item { kind: ItemKind::Fn(sig, generics, _), ident, .. }) => {
1460 match get_infer_ret_ty(&sig.decl.output) {
1462 let fn_sig = tcx.typeck_tables_of(def_id).liberated_fn_sigs()[hir_id];
1463 let mut visitor = PlaceholderHirTyCollector::default();
1464 visitor.visit_ty(ty);
1465 let mut diag = bad_placeholder_type(tcx, visitor.0);
1466 let ret_ty = fn_sig.output();
1467 if ret_ty != tcx.ty_error() {
1468 diag.span_suggestion(
1470 "replace with the correct return type",
1472 Applicability::MaybeIncorrect,
1476 ty::Binder::bind(fn_sig)
1478 None => AstConv::ty_of_fn(
1480 sig.header.unsafety,
1489 TraitItem(hir::TraitItem {
1490 kind: TraitItemKind::Fn(FnSig { header, decl }, _),
1495 AstConv::ty_of_fn(&icx, header.unsafety, header.abi, decl, &generics, Some(ident.span))
1498 ForeignItem(&hir::ForeignItem {
1499 kind: ForeignItemKind::Fn(ref fn_decl, _, _),
1503 let abi = tcx.hir().get_foreign_abi(hir_id);
1504 compute_sig_of_foreign_fn_decl(tcx, def_id.to_def_id(), fn_decl, abi, ident)
1507 Ctor(data) | Variant(hir::Variant { data, .. }) if data.ctor_hir_id().is_some() => {
1508 let ty = tcx.type_of(tcx.hir().get_parent_did(hir_id).to_def_id());
1510 data.fields().iter().map(|f| tcx.type_of(tcx.hir().local_def_id(f.hir_id)));
1511 ty::Binder::bind(tcx.mk_fn_sig(
1515 hir::Unsafety::Normal,
1520 Expr(&hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => {
1521 // Closure signatures are not like other function
1522 // signatures and cannot be accessed through `fn_sig`. For
1523 // example, a closure signature excludes the `self`
1524 // argument. In any case they are embedded within the
1525 // closure type as part of the `ClosureSubsts`.
1527 // To get the signature of a closure, you should use the
1528 // `sig` method on the `ClosureSubsts`:
1530 // substs.as_closure().sig(def_id, tcx)
1532 "to get the signature of a closure, use `substs.as_closure().sig()` not `fn_sig()`",
1537 bug!("unexpected sort of node in fn_sig(): {:?}", x);
1542 fn impl_trait_ref(tcx: TyCtxt<'_>, def_id: DefId) -> Option<ty::TraitRef<'_>> {
1543 let icx = ItemCtxt::new(tcx, def_id);
1545 let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local());
1546 match tcx.hir().expect_item(hir_id).kind {
1547 hir::ItemKind::Impl { ref of_trait, .. } => of_trait.as_ref().map(|ast_trait_ref| {
1548 let selfty = tcx.type_of(def_id);
1549 AstConv::instantiate_mono_trait_ref(&icx, ast_trait_ref, selfty)
1555 fn impl_polarity(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ImplPolarity {
1556 let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local());
1557 let is_rustc_reservation = tcx.has_attr(def_id, sym::rustc_reservation_impl);
1558 let item = tcx.hir().expect_item(hir_id);
1560 hir::ItemKind::Impl { polarity: hir::ImplPolarity::Negative(span), of_trait, .. } => {
1561 if is_rustc_reservation {
1562 let span = span.to(of_trait.as_ref().map(|t| t.path.span).unwrap_or(*span));
1563 tcx.sess.span_err(span, "reservation impls can't be negative");
1565 ty::ImplPolarity::Negative
1567 hir::ItemKind::Impl { polarity: hir::ImplPolarity::Positive, of_trait: None, .. } => {
1568 if is_rustc_reservation {
1569 tcx.sess.span_err(item.span, "reservation impls can't be inherent");
1571 ty::ImplPolarity::Positive
1573 hir::ItemKind::Impl {
1574 polarity: hir::ImplPolarity::Positive, of_trait: Some(_), ..
1576 if is_rustc_reservation {
1577 ty::ImplPolarity::Reservation
1579 ty::ImplPolarity::Positive
1582 ref item => bug!("impl_polarity: {:?} not an impl", item),
1586 /// Returns the early-bound lifetimes declared in this generics
1587 /// listing. For anything other than fns/methods, this is just all
1588 /// the lifetimes that are declared. For fns or methods, we have to
1589 /// screen out those that do not appear in any where-clauses etc using
1590 /// `resolve_lifetime::early_bound_lifetimes`.
1591 fn early_bound_lifetimes_from_generics<'a, 'tcx: 'a>(
1593 generics: &'a hir::Generics<'a>,
1594 ) -> impl Iterator<Item = &'a hir::GenericParam<'a>> + Captures<'tcx> {
1595 generics.params.iter().filter(move |param| match param.kind {
1596 GenericParamKind::Lifetime { .. } => !tcx.is_late_bound(param.hir_id),
1601 /// Returns a list of type predicates for the definition with ID `def_id`, including inferred
1602 /// lifetime constraints. This includes all predicates returned by `explicit_predicates_of`, plus
1603 /// inferred constraints concerning which regions outlive other regions.
1604 fn predicates_defined_on(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1605 debug!("predicates_defined_on({:?})", def_id);
1606 let mut result = tcx.explicit_predicates_of(def_id);
1607 debug!("predicates_defined_on: explicit_predicates_of({:?}) = {:?}", def_id, result,);
1608 let inferred_outlives = tcx.inferred_outlives_of(def_id);
1609 if !inferred_outlives.is_empty() {
1611 "predicates_defined_on: inferred_outlives_of({:?}) = {:?}",
1612 def_id, inferred_outlives,
1614 if result.predicates.is_empty() {
1615 result.predicates = inferred_outlives;
1617 result.predicates = tcx
1619 .alloc_from_iter(result.predicates.iter().chain(inferred_outlives).copied());
1622 debug!("predicates_defined_on({:?}) = {:?}", def_id, result);
1626 /// Returns a list of all type predicates (explicit and implicit) for the definition with
1627 /// ID `def_id`. This includes all predicates returned by `predicates_defined_on`, plus
1628 /// `Self: Trait` predicates for traits.
1629 fn predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1630 let mut result = tcx.predicates_defined_on(def_id);
1632 if tcx.is_trait(def_id) {
1633 // For traits, add `Self: Trait` predicate. This is
1634 // not part of the predicates that a user writes, but it
1635 // is something that one must prove in order to invoke a
1636 // method or project an associated type.
1638 // In the chalk setup, this predicate is not part of the
1639 // "predicates" for a trait item. But it is useful in
1640 // rustc because if you directly (e.g.) invoke a trait
1641 // method like `Trait::method(...)`, you must naturally
1642 // prove that the trait applies to the types that were
1643 // used, and adding the predicate into this list ensures
1644 // that this is done.
1645 let span = tcx.sess.source_map().guess_head_span(tcx.def_span(def_id));
1647 tcx.arena.alloc_from_iter(result.predicates.iter().copied().chain(std::iter::once((
1648 ty::TraitRef::identity(tcx, def_id).without_const().to_predicate(tcx),
1652 debug!("predicates_of(def_id={:?}) = {:?}", def_id, result);
1656 /// Returns a list of user-specified type predicates for the definition with ID `def_id`.
1657 /// N.B., this does not include any implied/inferred constraints.
1658 fn explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1661 debug!("explicit_predicates_of(def_id={:?})", def_id);
1663 /// A data structure with unique elements, which preserves order of insertion.
1664 /// Preserving the order of insertion is important here so as not to break
1665 /// compile-fail UI tests.
1666 // FIXME(eddyb) just use `IndexSet` from `indexmap`.
1667 struct UniquePredicates<'tcx> {
1668 predicates: Vec<(ty::Predicate<'tcx>, Span)>,
1669 uniques: FxHashSet<(ty::Predicate<'tcx>, Span)>,
1672 impl<'tcx> UniquePredicates<'tcx> {
1674 UniquePredicates { predicates: vec![], uniques: FxHashSet::default() }
1677 fn push(&mut self, value: (ty::Predicate<'tcx>, Span)) {
1678 if self.uniques.insert(value) {
1679 self.predicates.push(value);
1683 fn extend<I: IntoIterator<Item = (ty::Predicate<'tcx>, Span)>>(&mut self, iter: I) {
1690 let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local());
1691 let node = tcx.hir().get(hir_id);
1693 let mut is_trait = None;
1694 let mut is_default_impl_trait = None;
1695 let mut is_trait_associated_type = None;
1697 let icx = ItemCtxt::new(tcx, def_id);
1698 let constness = icx.default_constness_for_trait_bounds();
1700 const NO_GENERICS: &hir::Generics<'_> = &hir::Generics::empty();
1702 let mut predicates = UniquePredicates::new();
1704 let ast_generics = match node {
1705 Node::TraitItem(item) => {
1706 if let hir::TraitItemKind::Type(bounds, _) = item.kind {
1707 is_trait_associated_type = Some((bounds, item.span));
1712 Node::ImplItem(item) => &item.generics,
1714 Node::Item(item) => {
1716 ItemKind::Impl { defaultness, ref generics, .. } => {
1717 if defaultness.is_default() {
1718 is_default_impl_trait = tcx.impl_trait_ref(def_id);
1722 ItemKind::Fn(.., ref generics, _)
1723 | ItemKind::TyAlias(_, ref generics)
1724 | ItemKind::Enum(_, ref generics)
1725 | ItemKind::Struct(_, ref generics)
1726 | ItemKind::Union(_, ref generics) => generics,
1728 ItemKind::Trait(_, _, ref generics, .., items) => {
1729 is_trait = Some((ty::TraitRef::identity(tcx, def_id), items));
1732 ItemKind::TraitAlias(ref generics, _) => {
1733 is_trait = Some((ty::TraitRef::identity(tcx, def_id), &[]));
1736 ItemKind::OpaqueTy(OpaqueTy {
1742 let bounds_predicates = ty::print::with_no_queries(|| {
1743 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1744 let opaque_ty = tcx.mk_opaque(def_id, substs);
1746 // Collect the bounds, i.e., the `A + B + 'c` in `impl A + B + 'c`.
1747 let bounds = AstConv::compute_bounds(
1751 SizedByDefault::Yes,
1752 tcx.def_span(def_id),
1755 bounds.predicates(tcx, opaque_ty)
1757 if impl_trait_fn.is_some() {
1759 return ty::GenericPredicates {
1761 predicates: tcx.arena.alloc_from_iter(bounds_predicates),
1764 // named opaque types
1765 predicates.extend(bounds_predicates);
1774 Node::ForeignItem(item) => match item.kind {
1775 ForeignItemKind::Static(..) => NO_GENERICS,
1776 ForeignItemKind::Fn(_, _, ref generics) => generics,
1777 ForeignItemKind::Type => NO_GENERICS,
1783 let generics = tcx.generics_of(def_id);
1784 let parent_count = generics.parent_count as u32;
1785 let has_own_self = generics.has_self && parent_count == 0;
1787 // Below we'll consider the bounds on the type parameters (including `Self`)
1788 // and the explicit where-clauses, but to get the full set of predicates
1789 // on a trait we need to add in the supertrait bounds and bounds found on
1790 // associated types.
1791 if let Some((_trait_ref, _)) = is_trait {
1792 predicates.extend(tcx.super_predicates_of(def_id).predicates.iter().cloned());
1795 // In default impls, we can assume that the self type implements
1796 // the trait. So in:
1798 // default impl Foo for Bar { .. }
1800 // we add a default where clause `Foo: Bar`. We do a similar thing for traits
1801 // (see below). Recall that a default impl is not itself an impl, but rather a
1802 // set of defaults that can be incorporated into another impl.
1803 if let Some(trait_ref) = is_default_impl_trait {
1805 trait_ref.to_poly_trait_ref().without_const().to_predicate(tcx),
1806 tcx.def_span(def_id),
1810 // Collect the region predicates that were declared inline as
1811 // well. In the case of parameters declared on a fn or method, we
1812 // have to be careful to only iterate over early-bound regions.
1813 let mut index = parent_count + has_own_self as u32;
1814 for param in early_bound_lifetimes_from_generics(tcx, ast_generics) {
1815 let region = tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
1816 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
1818 name: param.name.ident().name,
1823 GenericParamKind::Lifetime { .. } => {
1824 param.bounds.iter().for_each(|bound| match bound {
1825 hir::GenericBound::Outlives(lt) => {
1826 let bound = AstConv::ast_region_to_region(&icx, <, None);
1827 let outlives = ty::Binder::bind(ty::OutlivesPredicate(region, bound));
1828 predicates.push((outlives.to_predicate(tcx), lt.span));
1837 // Collect the predicates that were written inline by the user on each
1838 // type parameter (e.g., `<T: Foo>`).
1839 for param in ast_generics.params {
1840 if let GenericParamKind::Type { .. } = param.kind {
1841 let name = param.name.ident().name;
1842 let param_ty = ty::ParamTy::new(index, name).to_ty(tcx);
1845 let sized = SizedByDefault::Yes;
1846 let bounds = AstConv::compute_bounds(&icx, param_ty, ¶m.bounds, sized, param.span);
1847 predicates.extend(bounds.predicates(tcx, param_ty));
1851 // Add in the bounds that appear in the where-clause.
1852 let where_clause = &ast_generics.where_clause;
1853 for predicate in where_clause.predicates {
1855 &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
1856 let ty = icx.to_ty(&bound_pred.bounded_ty);
1858 // Keep the type around in a dummy predicate, in case of no bounds.
1859 // That way, `where Ty:` is not a complete noop (see #53696) and `Ty`
1860 // is still checked for WF.
1861 if bound_pred.bounds.is_empty() {
1862 if let ty::Param(_) = ty.kind {
1863 // This is a `where T:`, which can be in the HIR from the
1864 // transformation that moves `?Sized` to `T`'s declaration.
1865 // We can skip the predicate because type parameters are
1866 // trivially WF, but also we *should*, to avoid exposing
1867 // users who never wrote `where Type:,` themselves, to
1868 // compiler/tooling bugs from not handling WF predicates.
1870 let span = bound_pred.bounded_ty.span;
1871 let re_root_empty = tcx.lifetimes.re_root_empty;
1872 let predicate = ty::OutlivesPredicate(ty, re_root_empty);
1874 ty::PredicateKind::TypeOutlives(ty::Binder::dummy(predicate))
1881 for bound in bound_pred.bounds.iter() {
1883 &hir::GenericBound::Trait(ref poly_trait_ref, modifier) => {
1884 let constness = match modifier {
1885 hir::TraitBoundModifier::MaybeConst => hir::Constness::NotConst,
1886 hir::TraitBoundModifier::None => constness,
1887 hir::TraitBoundModifier::Maybe => bug!("this wasn't handled"),
1890 let mut bounds = Bounds::default();
1891 let _ = AstConv::instantiate_poly_trait_ref(
1898 predicates.extend(bounds.predicates(tcx, ty));
1901 &hir::GenericBound::Outlives(ref lifetime) => {
1902 let region = AstConv::ast_region_to_region(&icx, lifetime, None);
1903 let pred = ty::Binder::bind(ty::OutlivesPredicate(ty, region));
1905 ty::PredicateKind::TypeOutlives(pred).to_predicate(tcx),
1913 &hir::WherePredicate::RegionPredicate(ref region_pred) => {
1914 let r1 = AstConv::ast_region_to_region(&icx, ®ion_pred.lifetime, None);
1915 predicates.extend(region_pred.bounds.iter().map(|bound| {
1916 let (r2, span) = match bound {
1917 hir::GenericBound::Outlives(lt) => {
1918 (AstConv::ast_region_to_region(&icx, lt, None), lt.span)
1922 let pred = ty::Binder::bind(ty::OutlivesPredicate(r1, r2));
1924 (ty::PredicateKind::RegionOutlives(pred).to_predicate(icx.tcx), span)
1928 &hir::WherePredicate::EqPredicate(..) => {
1934 // Add predicates from associated type bounds (`type X: Bound`)
1935 if tcx.features().generic_associated_types {
1936 // New behavior: bounds declared on associate type are predicates of that
1937 // associated type. Not the default because it needs more testing.
1938 if let Some((bounds, span)) = is_trait_associated_type {
1940 tcx.mk_projection(def_id, InternalSubsts::identity_for_item(tcx, def_id));
1942 predicates.extend(associated_item_bounds(tcx, def_id, bounds, projection_ty, span))
1944 } else if let Some((self_trait_ref, trait_items)) = is_trait {
1945 // Current behavior: bounds declared on associate type are predicates
1946 // of its parent trait.
1947 predicates.extend(trait_items.iter().flat_map(|trait_item_ref| {
1948 trait_associated_item_predicates(tcx, def_id, self_trait_ref, trait_item_ref)
1952 let mut predicates = predicates.predicates;
1954 // Subtle: before we store the predicates into the tcx, we
1955 // sort them so that predicates like `T: Foo<Item=U>` come
1956 // before uses of `U`. This avoids false ambiguity errors
1957 // in trait checking. See `setup_constraining_predicates`
1959 if let Node::Item(&Item { kind: ItemKind::Impl { .. }, .. }) = node {
1960 let self_ty = tcx.type_of(def_id);
1961 let trait_ref = tcx.impl_trait_ref(def_id);
1962 cgp::setup_constraining_predicates(
1966 &mut cgp::parameters_for_impl(self_ty, trait_ref),
1970 let result = ty::GenericPredicates {
1971 parent: generics.parent,
1972 predicates: tcx.arena.alloc_from_iter(predicates),
1974 debug!("explicit_predicates_of(def_id={:?}) = {:?}", def_id, result);
1978 fn trait_associated_item_predicates(
1981 self_trait_ref: ty::TraitRef<'tcx>,
1982 trait_item_ref: &hir::TraitItemRef,
1983 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
1984 let trait_item = tcx.hir().trait_item(trait_item_ref.id);
1985 let item_def_id = tcx.hir().local_def_id(trait_item_ref.id.hir_id);
1986 let bounds = match trait_item.kind {
1987 hir::TraitItemKind::Type(ref bounds, _) => bounds,
1988 _ => return Vec::new(),
1991 if !tcx.generics_of(item_def_id).params.is_empty() {
1992 // For GATs the substs provided to the mk_projection call below are
1993 // wrong. We should emit a feature gate error if we get here so skip
1995 tcx.sess.delay_span_bug(trait_item.span, "gats used without feature gate");
1999 let assoc_ty = tcx.mk_projection(
2000 tcx.hir().local_def_id(trait_item.hir_id).to_def_id(),
2001 self_trait_ref.substs,
2004 associated_item_bounds(tcx, def_id, bounds, assoc_ty, trait_item.span)
2007 fn associated_item_bounds(
2010 bounds: &'tcx [hir::GenericBound<'tcx>],
2011 projection_ty: Ty<'tcx>,
2013 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2014 let bounds = AstConv::compute_bounds(
2015 &ItemCtxt::new(tcx, def_id),
2018 SizedByDefault::Yes,
2022 let predicates = bounds.predicates(tcx, projection_ty);
2027 /// Converts a specific `GenericBound` from the AST into a set of
2028 /// predicates that apply to the self type. A vector is returned
2029 /// because this can be anywhere from zero predicates (`T: ?Sized` adds no
2030 /// predicates) to one (`T: Foo`) to many (`T: Bar<X = i32>` adds `T: Bar`
2031 /// and `<T as Bar>::X == i32`).
2032 fn predicates_from_bound<'tcx>(
2033 astconv: &dyn AstConv<'tcx>,
2035 bound: &'tcx hir::GenericBound<'tcx>,
2036 constness: hir::Constness,
2037 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2039 hir::GenericBound::Trait(ref tr, modifier) => {
2040 let constness = match modifier {
2041 hir::TraitBoundModifier::Maybe => return vec![],
2042 hir::TraitBoundModifier::MaybeConst => hir::Constness::NotConst,
2043 hir::TraitBoundModifier::None => constness,
2046 let mut bounds = Bounds::default();
2047 let _ = astconv.instantiate_poly_trait_ref(tr, constness, param_ty, &mut bounds);
2048 bounds.predicates(astconv.tcx(), param_ty)
2050 hir::GenericBound::Outlives(ref lifetime) => {
2051 let region = astconv.ast_region_to_region(lifetime, None);
2052 let pred = ty::Binder::bind(ty::OutlivesPredicate(param_ty, region));
2053 vec![(ty::PredicateKind::TypeOutlives(pred).to_predicate(astconv.tcx()), lifetime.span)]
2058 fn compute_sig_of_foreign_fn_decl<'tcx>(
2061 decl: &'tcx hir::FnDecl<'tcx>,
2064 ) -> ty::PolyFnSig<'tcx> {
2065 let unsafety = if abi == abi::Abi::RustIntrinsic {
2066 intrinsic_operation_unsafety(&tcx.item_name(def_id).as_str())
2068 hir::Unsafety::Unsafe
2070 let fty = AstConv::ty_of_fn(
2071 &ItemCtxt::new(tcx, def_id),
2075 &hir::Generics::empty(),
2079 // Feature gate SIMD types in FFI, since I am not sure that the
2080 // ABIs are handled at all correctly. -huonw
2081 if abi != abi::Abi::RustIntrinsic
2082 && abi != abi::Abi::PlatformIntrinsic
2083 && !tcx.features().simd_ffi
2085 let check = |ast_ty: &hir::Ty<'_>, ty: Ty<'_>| {
2090 .span_to_snippet(ast_ty.span)
2091 .map_or(String::new(), |s| format!(" `{}`", s));
2096 "use of SIMD type{} in FFI is highly experimental and \
2097 may result in invalid code",
2101 .help("add `#![feature(simd_ffi)]` to the crate attributes to enable")
2105 for (input, ty) in decl.inputs.iter().zip(*fty.inputs().skip_binder()) {
2108 if let hir::FnRetTy::Return(ref ty) = decl.output {
2109 check(&ty, *fty.output().skip_binder())
2116 fn is_foreign_item(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
2117 match tcx.hir().get_if_local(def_id) {
2118 Some(Node::ForeignItem(..)) => true,
2120 _ => bug!("is_foreign_item applied to non-local def-id {:?}", def_id),
2124 fn static_mutability(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::Mutability> {
2125 match tcx.hir().get_if_local(def_id) {
2127 Node::Item(&hir::Item { kind: hir::ItemKind::Static(_, mutbl, _), .. })
2128 | Node::ForeignItem(&hir::ForeignItem {
2129 kind: hir::ForeignItemKind::Static(_, mutbl),
2134 _ => bug!("static_mutability applied to non-local def-id {:?}", def_id),
2138 fn generator_kind(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::GeneratorKind> {
2139 match tcx.hir().get_if_local(def_id) {
2140 Some(Node::Expr(&rustc_hir::Expr {
2141 kind: rustc_hir::ExprKind::Closure(_, _, body_id, _, _),
2143 })) => tcx.hir().body(body_id).generator_kind(),
2145 _ => bug!("generator_kind applied to non-local def-id {:?}", def_id),
2149 fn from_target_feature(
2152 attr: &ast::Attribute,
2153 whitelist: &FxHashMap<String, Option<Symbol>>,
2154 target_features: &mut Vec<Symbol>,
2156 let list = match attr.meta_item_list() {
2160 let bad_item = |span| {
2161 let msg = "malformed `target_feature` attribute input";
2162 let code = "enable = \"..\"".to_owned();
2164 .struct_span_err(span, &msg)
2165 .span_suggestion(span, "must be of the form", code, Applicability::HasPlaceholders)
2168 let rust_features = tcx.features();
2170 // Only `enable = ...` is accepted in the meta-item list.
2171 if !item.check_name(sym::enable) {
2172 bad_item(item.span());
2176 // Must be of the form `enable = "..."` (a string).
2177 let value = match item.value_str() {
2178 Some(value) => value,
2180 bad_item(item.span());
2185 // We allow comma separation to enable multiple features.
2186 target_features.extend(value.as_str().split(',').filter_map(|feature| {
2187 // Only allow whitelisted features per platform.
2188 let feature_gate = match whitelist.get(feature) {
2192 format!("the feature named `{}` is not valid for this target", feature);
2193 let mut err = tcx.sess.struct_span_err(item.span(), &msg);
2196 format!("`{}` is not valid for this target", feature),
2198 if feature.starts_with('+') {
2199 let valid = whitelist.contains_key(&feature[1..]);
2201 err.help("consider removing the leading `+` in the feature name");
2209 // Only allow features whose feature gates have been enabled.
2210 let allowed = match feature_gate.as_ref().copied() {
2211 Some(sym::arm_target_feature) => rust_features.arm_target_feature,
2212 Some(sym::aarch64_target_feature) => rust_features.aarch64_target_feature,
2213 Some(sym::hexagon_target_feature) => rust_features.hexagon_target_feature,
2214 Some(sym::powerpc_target_feature) => rust_features.powerpc_target_feature,
2215 Some(sym::mips_target_feature) => rust_features.mips_target_feature,
2216 Some(sym::riscv_target_feature) => rust_features.riscv_target_feature,
2217 Some(sym::avx512_target_feature) => rust_features.avx512_target_feature,
2218 Some(sym::mmx_target_feature) => rust_features.mmx_target_feature,
2219 Some(sym::sse4a_target_feature) => rust_features.sse4a_target_feature,
2220 Some(sym::tbm_target_feature) => rust_features.tbm_target_feature,
2221 Some(sym::wasm_target_feature) => rust_features.wasm_target_feature,
2222 Some(sym::cmpxchg16b_target_feature) => rust_features.cmpxchg16b_target_feature,
2223 Some(sym::adx_target_feature) => rust_features.adx_target_feature,
2224 Some(sym::movbe_target_feature) => rust_features.movbe_target_feature,
2225 Some(sym::rtm_target_feature) => rust_features.rtm_target_feature,
2226 Some(sym::f16c_target_feature) => rust_features.f16c_target_feature,
2227 Some(name) => bug!("unknown target feature gate {}", name),
2230 if !allowed && id.is_local() {
2232 &tcx.sess.parse_sess,
2233 feature_gate.unwrap(),
2235 &format!("the target feature `{}` is currently unstable", feature),
2239 Some(Symbol::intern(feature))
2244 fn linkage_by_name(tcx: TyCtxt<'_>, def_id: DefId, name: &str) -> Linkage {
2245 use rustc_middle::mir::mono::Linkage::*;
2247 // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
2248 // applicable to variable declarations and may not really make sense for
2249 // Rust code in the first place but whitelist them anyway and trust that
2250 // the user knows what s/he's doing. Who knows, unanticipated use cases
2251 // may pop up in the future.
2253 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
2254 // and don't have to be, LLVM treats them as no-ops.
2256 "appending" => Appending,
2257 "available_externally" => AvailableExternally,
2259 "extern_weak" => ExternalWeak,
2260 "external" => External,
2261 "internal" => Internal,
2262 "linkonce" => LinkOnceAny,
2263 "linkonce_odr" => LinkOnceODR,
2264 "private" => Private,
2266 "weak_odr" => WeakODR,
2268 let span = tcx.hir().span_if_local(def_id);
2269 if let Some(span) = span {
2270 tcx.sess.span_fatal(span, "invalid linkage specified")
2272 tcx.sess.fatal(&format!("invalid linkage specified: {}", name))
2278 fn codegen_fn_attrs(tcx: TyCtxt<'_>, id: DefId) -> CodegenFnAttrs {
2279 let attrs = tcx.get_attrs(id);
2281 let mut codegen_fn_attrs = CodegenFnAttrs::new();
2282 if should_inherit_track_caller(tcx, id) {
2283 codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
2286 let whitelist = tcx.target_features_whitelist(LOCAL_CRATE);
2288 let mut inline_span = None;
2289 let mut link_ordinal_span = None;
2290 let mut no_sanitize_span = None;
2291 for attr in attrs.iter() {
2292 if attr.check_name(sym::cold) {
2293 codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD;
2294 } else if attr.check_name(sym::rustc_allocator) {
2295 codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR;
2296 } else if attr.check_name(sym::unwind) {
2297 codegen_fn_attrs.flags |= CodegenFnAttrFlags::UNWIND;
2298 } else if attr.check_name(sym::ffi_returns_twice) {
2299 if tcx.is_foreign_item(id) {
2300 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_RETURNS_TWICE;
2302 // `#[ffi_returns_twice]` is only allowed `extern fn`s.
2307 "`#[ffi_returns_twice]` may only be used on foreign functions"
2311 } else if attr.check_name(sym::ffi_pure) {
2312 if tcx.is_foreign_item(id) {
2313 if attrs.iter().any(|a| a.check_name(sym::ffi_const)) {
2314 // `#[ffi_const]` functions cannot be `#[ffi_pure]`
2319 "`#[ffi_const]` function cannot be `#[ffi_pure]`"
2323 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_PURE;
2326 // `#[ffi_pure]` is only allowed on foreign functions
2331 "`#[ffi_pure]` may only be used on foreign functions"
2335 } else if attr.check_name(sym::ffi_const) {
2336 if tcx.is_foreign_item(id) {
2337 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_CONST;
2339 // `#[ffi_const]` is only allowed on foreign functions
2344 "`#[ffi_const]` may only be used on foreign functions"
2348 } else if attr.check_name(sym::rustc_allocator_nounwind) {
2349 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND;
2350 } else if attr.check_name(sym::naked) {
2351 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED;
2352 } else if attr.check_name(sym::no_mangle) {
2353 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2354 } else if attr.check_name(sym::rustc_std_internal_symbol) {
2355 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2356 } else if attr.check_name(sym::used) {
2357 codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED;
2358 } else if attr.check_name(sym::thread_local) {
2359 codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL;
2360 } else if attr.check_name(sym::track_caller) {
2361 if tcx.is_closure(id) || tcx.fn_sig(id).abi() != abi::Abi::Rust {
2362 struct_span_err!(tcx.sess, attr.span, E0737, "`#[track_caller]` requires Rust ABI")
2365 codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
2366 } else if attr.check_name(sym::export_name) {
2367 if let Some(s) = attr.value_str() {
2368 if s.as_str().contains('\0') {
2369 // `#[export_name = ...]` will be converted to a null-terminated string,
2370 // so it may not contain any null characters.
2375 "`export_name` may not contain null characters"
2379 codegen_fn_attrs.export_name = Some(s);
2381 } else if attr.check_name(sym::target_feature) {
2382 if !tcx.features().target_feature_11 {
2383 check_target_feature_safe_fn(tcx, id, attr.span);
2384 } else if let Some(local_id) = id.as_local() {
2385 if tcx.fn_sig(id).unsafety() == hir::Unsafety::Normal {
2386 check_target_feature_trait_unsafe(tcx, local_id, attr.span);
2389 from_target_feature(tcx, id, attr, &whitelist, &mut codegen_fn_attrs.target_features);
2390 } else if attr.check_name(sym::linkage) {
2391 if let Some(val) = attr.value_str() {
2392 codegen_fn_attrs.linkage = Some(linkage_by_name(tcx, id, &val.as_str()));
2394 } else if attr.check_name(sym::link_section) {
2395 if let Some(val) = attr.value_str() {
2396 if val.as_str().bytes().any(|b| b == 0) {
2398 "illegal null byte in link_section \
2402 tcx.sess.span_err(attr.span, &msg);
2404 codegen_fn_attrs.link_section = Some(val);
2407 } else if attr.check_name(sym::link_name) {
2408 codegen_fn_attrs.link_name = attr.value_str();
2409 } else if attr.check_name(sym::link_ordinal) {
2410 link_ordinal_span = Some(attr.span);
2411 if let ordinal @ Some(_) = check_link_ordinal(tcx, attr) {
2412 codegen_fn_attrs.link_ordinal = ordinal;
2414 } else if attr.check_name(sym::no_sanitize) {
2415 no_sanitize_span = Some(attr.span);
2416 if let Some(list) = attr.meta_item_list() {
2417 for item in list.iter() {
2418 if item.check_name(sym::address) {
2419 codegen_fn_attrs.no_sanitize |= SanitizerSet::ADDRESS;
2420 } else if item.check_name(sym::memory) {
2421 codegen_fn_attrs.no_sanitize |= SanitizerSet::MEMORY;
2422 } else if item.check_name(sym::thread) {
2423 codegen_fn_attrs.no_sanitize |= SanitizerSet::THREAD;
2426 .struct_span_err(item.span(), "invalid argument for `no_sanitize`")
2427 .note("expected one of: `address`, `memory` or `thread`")
2435 codegen_fn_attrs.inline = attrs.iter().fold(InlineAttr::None, |ia, attr| {
2436 if !attr.has_name(sym::inline) {
2439 match attr.meta().map(|i| i.kind) {
2440 Some(MetaItemKind::Word) => {
2444 Some(MetaItemKind::List(ref items)) => {
2446 inline_span = Some(attr.span);
2447 if items.len() != 1 {
2449 tcx.sess.diagnostic(),
2452 "expected one argument"
2456 } else if list_contains_name(&items[..], sym::always) {
2458 } else if list_contains_name(&items[..], sym::never) {
2462 tcx.sess.diagnostic(),
2472 Some(MetaItemKind::NameValue(_)) => ia,
2477 codegen_fn_attrs.optimize = attrs.iter().fold(OptimizeAttr::None, |ia, attr| {
2478 if !attr.has_name(sym::optimize) {
2481 let err = |sp, s| struct_span_err!(tcx.sess.diagnostic(), sp, E0722, "{}", s).emit();
2482 match attr.meta().map(|i| i.kind) {
2483 Some(MetaItemKind::Word) => {
2484 err(attr.span, "expected one argument");
2487 Some(MetaItemKind::List(ref items)) => {
2489 inline_span = Some(attr.span);
2490 if items.len() != 1 {
2491 err(attr.span, "expected one argument");
2493 } else if list_contains_name(&items[..], sym::size) {
2495 } else if list_contains_name(&items[..], sym::speed) {
2498 err(items[0].span(), "invalid argument");
2502 Some(MetaItemKind::NameValue(_)) => ia,
2507 // If a function uses #[target_feature] it can't be inlined into general
2508 // purpose functions as they wouldn't have the right target features
2509 // enabled. For that reason we also forbid #[inline(always)] as it can't be
2511 if !codegen_fn_attrs.target_features.is_empty() {
2512 if codegen_fn_attrs.inline == InlineAttr::Always {
2513 if let Some(span) = inline_span {
2516 "cannot use `#[inline(always)]` with \
2517 `#[target_feature]`",
2523 if !codegen_fn_attrs.no_sanitize.is_empty() {
2524 if codegen_fn_attrs.inline == InlineAttr::Always {
2525 if let (Some(no_sanitize_span), Some(inline_span)) = (no_sanitize_span, inline_span) {
2526 let hir_id = tcx.hir().as_local_hir_id(id.expect_local());
2527 tcx.struct_span_lint_hir(
2528 lint::builtin::INLINE_NO_SANITIZE,
2532 lint.build("`no_sanitize` will have no effect after inlining")
2533 .span_note(inline_span, "inlining requested here")
2541 // Weak lang items have the same semantics as "std internal" symbols in the
2542 // sense that they're preserved through all our LTO passes and only
2543 // strippable by the linker.
2545 // Additionally weak lang items have predetermined symbol names.
2546 if tcx.is_weak_lang_item(id) {
2547 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2549 if let Some(name) = weak_lang_items::link_name(&attrs) {
2550 codegen_fn_attrs.export_name = Some(name);
2551 codegen_fn_attrs.link_name = Some(name);
2553 check_link_name_xor_ordinal(tcx, &codegen_fn_attrs, link_ordinal_span);
2555 // Internal symbols to the standard library all have no_mangle semantics in
2556 // that they have defined symbol names present in the function name. This
2557 // also applies to weak symbols where they all have known symbol names.
2558 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
2559 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2565 /// Checks if the provided DefId is a method in a trait impl for a trait which has track_caller
2566 /// applied to the method prototype.
2567 fn should_inherit_track_caller(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
2568 if let Some(impl_item) = tcx.opt_associated_item(def_id) {
2569 if let ty::AssocItemContainer::ImplContainer(impl_def_id) = impl_item.container {
2570 if let Some(trait_def_id) = tcx.trait_id_of_impl(impl_def_id) {
2571 if let Some(trait_item) = tcx
2572 .associated_items(trait_def_id)
2573 .filter_by_name_unhygienic(impl_item.ident.name)
2574 .find(move |trait_item| {
2575 trait_item.kind == ty::AssocKind::Fn
2576 && tcx.hygienic_eq(impl_item.ident, trait_item.ident, trait_def_id)
2580 .codegen_fn_attrs(trait_item.def_id)
2582 .intersects(CodegenFnAttrFlags::TRACK_CALLER);
2591 fn check_link_ordinal(tcx: TyCtxt<'_>, attr: &ast::Attribute) -> Option<usize> {
2592 use rustc_ast::ast::{Lit, LitIntType, LitKind};
2593 let meta_item_list = attr.meta_item_list();
2594 let meta_item_list: Option<&[ast::NestedMetaItem]> = meta_item_list.as_ref().map(Vec::as_ref);
2595 let sole_meta_list = match meta_item_list {
2596 Some([item]) => item.literal(),
2599 if let Some(Lit { kind: LitKind::Int(ordinal, LitIntType::Unsuffixed), .. }) = sole_meta_list {
2600 if *ordinal <= usize::MAX as u128 {
2601 Some(*ordinal as usize)
2603 let msg = format!("ordinal value in `link_ordinal` is too large: `{}`", &ordinal);
2605 .struct_span_err(attr.span, &msg)
2606 .note("the value may not exceed `usize::MAX`")
2612 .struct_span_err(attr.span, "illegal ordinal format in `link_ordinal`")
2613 .note("an unsuffixed integer value, e.g., `1`, is expected")
2619 fn check_link_name_xor_ordinal(
2621 codegen_fn_attrs: &CodegenFnAttrs,
2622 inline_span: Option<Span>,
2624 if codegen_fn_attrs.link_name.is_none() || codegen_fn_attrs.link_ordinal.is_none() {
2627 let msg = "cannot use `#[link_name]` with `#[link_ordinal]`";
2628 if let Some(span) = inline_span {
2629 tcx.sess.span_err(span, msg);
2635 /// Checks the function annotated with `#[target_feature]` is unsafe,
2636 /// reporting an error if it isn't.
2637 fn check_target_feature_safe_fn(tcx: TyCtxt<'_>, id: DefId, attr_span: Span) {
2638 if tcx.is_closure(id) || tcx.fn_sig(id).unsafety() == hir::Unsafety::Normal {
2639 let mut err = feature_err(
2640 &tcx.sess.parse_sess,
2641 sym::target_feature_11,
2643 "`#[target_feature(..)]` can only be applied to `unsafe` functions",
2645 err.span_label(tcx.def_span(id), "not an `unsafe` function");
2650 /// Checks the function annotated with `#[target_feature]` is not a safe
2651 /// trait method implementation, reporting an error if it is.
2652 fn check_target_feature_trait_unsafe(tcx: TyCtxt<'_>, id: LocalDefId, attr_span: Span) {
2653 let hir_id = tcx.hir().as_local_hir_id(id);
2654 let node = tcx.hir().get(hir_id);
2655 if let Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }) = node {
2656 let parent_id = tcx.hir().get_parent_item(hir_id);
2657 let parent_item = tcx.hir().expect_item(parent_id);
2658 if let hir::ItemKind::Impl { of_trait: Some(_), .. } = parent_item.kind {
2662 "`#[target_feature(..)]` cannot be applied to safe trait method",
2664 .span_label(attr_span, "cannot be applied to safe trait method")
2665 .span_label(tcx.def_span(id), "not an `unsafe` function")