1 // ignore-tidy-filelength
2 //! "Collection" is the process of determining the type and other external
3 //! details of each item in Rust. Collection is specifically concerned
4 //! with *inter-procedural* things -- for example, for a function
5 //! definition, collection will figure out the type and signature of the
6 //! function, but it will not visit the *body* of the function in any way,
7 //! nor examine type annotations on local variables (that's the job of
10 //! Collecting is ultimately defined by a bundle of queries that
11 //! inquire after various facts about the items in the crate (e.g.,
12 //! `type_of`, `generics_of`, `predicates_of`, etc). See the `provide` function
15 //! At present, however, we do run collection across all items in the
16 //! crate as a kind of pass. This should eventually be factored away.
18 use crate::astconv::{AstConv, SizedByDefault};
19 use crate::bounds::Bounds;
20 use crate::check::intrinsic::intrinsic_operation_unsafety;
21 use crate::constrained_generic_params as cgp;
23 use crate::middle::resolve_lifetime as rl;
25 use rustc_ast::{MetaItemKind, NestedMetaItem};
26 use rustc_attr::{list_contains_name, InlineAttr, InstructionSetAttr, OptimizeAttr};
27 use rustc_data_structures::captures::Captures;
28 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
29 use rustc_errors::{struct_span_err, Applicability};
31 use rustc_hir::def::{CtorKind, DefKind, Res};
32 use rustc_hir::def_id::{DefId, LocalDefId, LOCAL_CRATE};
33 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
34 use rustc_hir::weak_lang_items;
35 use rustc_hir::{GenericParamKind, HirId, Node};
36 use rustc_middle::hir::map::blocks::FnLikeNode;
37 use rustc_middle::hir::map::Map;
38 use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
39 use rustc_middle::mir::mono::Linkage;
40 use rustc_middle::ty::query::Providers;
41 use rustc_middle::ty::subst::InternalSubsts;
42 use rustc_middle::ty::util::Discr;
43 use rustc_middle::ty::util::IntTypeExt;
44 use rustc_middle::ty::{self, AdtKind, Const, DefIdTree, ToPolyTraitRef, Ty, TyCtxt};
45 use rustc_middle::ty::{ReprOptions, ToPredicate, WithConstness};
46 use rustc_session::config::SanitizerSet;
47 use rustc_session::lint;
48 use rustc_session::parse::feature_err;
49 use rustc_span::symbol::{kw, sym, Ident, Symbol};
50 use rustc_span::{Span, DUMMY_SP};
51 use rustc_target::spec::abi;
52 use rustc_trait_selection::traits::error_reporting::suggestions::NextTypeParamName;
58 struct OnlySelfBounds(bool);
60 ///////////////////////////////////////////////////////////////////////////
63 fn collect_mod_item_types(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
64 tcx.hir().visit_item_likes_in_module(
66 &mut CollectItemTypesVisitor { tcx }.as_deep_visitor(),
70 pub fn provide(providers: &mut Providers) {
71 *providers = Providers {
72 opt_const_param_of: type_of::opt_const_param_of,
73 type_of: type_of::type_of,
74 item_bounds: item_bounds::item_bounds,
75 explicit_item_bounds: item_bounds::explicit_item_bounds,
78 predicates_defined_on,
79 projection_ty_from_predicates,
80 explicit_predicates_of,
82 super_predicates_that_define_assoc_type,
83 trait_explicit_predicates_and_bounds,
84 type_param_predicates,
94 collect_mod_item_types,
99 ///////////////////////////////////////////////////////////////////////////
101 /// Context specific to some particular item. This is what implements
102 /// `AstConv`. It has information about the predicates that are defined
103 /// on the trait. Unfortunately, this predicate information is
104 /// available in various different forms at various points in the
105 /// process. So we can't just store a pointer to e.g., the AST or the
106 /// parsed ty form, we have to be more flexible. To this end, the
107 /// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy
108 /// `get_type_parameter_bounds` requests, drawing the information from
109 /// the AST (`hir::Generics`), recursively.
110 pub struct ItemCtxt<'tcx> {
115 ///////////////////////////////////////////////////////////////////////////
118 crate struct PlaceholderHirTyCollector(crate Vec<Span>);
120 impl<'v> Visitor<'v> for PlaceholderHirTyCollector {
121 type Map = intravisit::ErasedMap<'v>;
123 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
124 NestedVisitorMap::None
126 fn visit_ty(&mut self, t: &'v hir::Ty<'v>) {
127 if let hir::TyKind::Infer = t.kind {
130 intravisit::walk_ty(self, t)
134 struct CollectItemTypesVisitor<'tcx> {
138 /// If there are any placeholder types (`_`), emit an error explaining that this is not allowed
139 /// and suggest adding type parameters in the appropriate place, taking into consideration any and
140 /// all already existing generic type parameters to avoid suggesting a name that is already in use.
141 crate fn placeholder_type_error(
144 generics: &[hir::GenericParam<'_>],
145 placeholder_types: Vec<Span>,
147 hir_ty: Option<&hir::Ty<'_>>,
149 if placeholder_types.is_empty() {
153 let type_name = generics.next_type_param_name(None);
154 let mut sugg: Vec<_> =
155 placeholder_types.iter().map(|sp| (*sp, (*type_name).to_string())).collect();
157 if generics.is_empty() {
158 if let Some(span) = span {
159 sugg.push((span, format!("<{}>", type_name)));
161 } else if let Some(arg) = generics
163 .find(|arg| matches!(arg.name, hir::ParamName::Plain(Ident { name: kw::Underscore, .. })))
165 // Account for `_` already present in cases like `struct S<_>(_);` and suggest
166 // `struct S<T>(T);` instead of `struct S<_, T>(T);`.
167 sugg.push((arg.span, (*type_name).to_string()));
169 let last = generics.iter().last().unwrap();
171 // Account for bounds, we want `fn foo<T: E, K>(_: K)` not `fn foo<T, K: E>(_: K)`.
172 last.bounds_span().unwrap_or(last.span).shrink_to_hi(),
173 format!(", {}", type_name),
177 let mut err = bad_placeholder_type(tcx, placeholder_types);
179 // Suggest, but only if it is not a function in const or static
181 let mut is_fn = false;
182 let mut is_const = false;
183 let mut is_static = false;
185 if let Some(hir_ty) = hir_ty {
186 if let hir::TyKind::BareFn(_) = hir_ty.kind {
189 // Check if parent is const or static
190 let parent_id = tcx.hir().get_parent_node(hir_ty.hir_id);
191 let parent_node = tcx.hir().get(parent_id);
193 if let hir::Node::Item(item) = parent_node {
194 if let hir::ItemKind::Const(_, _) = item.kind {
196 } else if let hir::ItemKind::Static(_, _, _) = item.kind {
203 // if function is wrapped around a const or static,
204 // then don't show the suggestion
205 if !(is_fn && (is_const || is_static)) {
206 err.multipart_suggestion(
207 "use type parameters instead",
209 Applicability::HasPlaceholders,
216 fn reject_placeholder_type_signatures_in_item(tcx: TyCtxt<'tcx>, item: &'tcx hir::Item<'tcx>) {
217 let (generics, suggest) = match &item.kind {
218 hir::ItemKind::Union(_, generics)
219 | hir::ItemKind::Enum(_, generics)
220 | hir::ItemKind::TraitAlias(generics, _)
221 | hir::ItemKind::Trait(_, _, generics, ..)
222 | hir::ItemKind::Impl(hir::Impl { generics, .. })
223 | hir::ItemKind::Struct(_, generics) => (generics, true),
224 hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. })
225 | hir::ItemKind::TyAlias(_, generics) => (generics, false),
226 // `static`, `fn` and `const` are handled elsewhere to suggest appropriate type.
230 let mut visitor = PlaceholderHirTyCollector::default();
231 visitor.visit_item(item);
233 placeholder_type_error(tcx, Some(generics.span), generics.params, visitor.0, suggest, None);
236 impl Visitor<'tcx> for CollectItemTypesVisitor<'tcx> {
237 type Map = Map<'tcx>;
239 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
240 NestedVisitorMap::OnlyBodies(self.tcx.hir())
243 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
244 convert_item(self.tcx, item.item_id());
245 reject_placeholder_type_signatures_in_item(self.tcx, item);
246 intravisit::walk_item(self, item);
249 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
250 for param in generics.params {
252 hir::GenericParamKind::Lifetime { .. } => {}
253 hir::GenericParamKind::Type { default: Some(_), .. } => {
254 let def_id = self.tcx.hir().local_def_id(param.hir_id);
255 self.tcx.ensure().type_of(def_id);
257 hir::GenericParamKind::Type { .. } => {}
258 hir::GenericParamKind::Const { default, .. } => {
259 let def_id = self.tcx.hir().local_def_id(param.hir_id);
260 self.tcx.ensure().type_of(def_id);
261 if let Some(default) = default {
262 let default_def_id = self.tcx.hir().local_def_id(default.hir_id);
263 // need to store default and type of default
264 self.tcx.ensure().type_of(default_def_id);
265 self.tcx.ensure().const_param_default(def_id);
270 intravisit::walk_generics(self, generics);
273 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
274 if let hir::ExprKind::Closure(..) = expr.kind {
275 let def_id = self.tcx.hir().local_def_id(expr.hir_id);
276 self.tcx.ensure().generics_of(def_id);
277 self.tcx.ensure().type_of(def_id);
279 intravisit::walk_expr(self, expr);
282 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
283 convert_trait_item(self.tcx, trait_item.trait_item_id());
284 intravisit::walk_trait_item(self, trait_item);
287 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
288 convert_impl_item(self.tcx, impl_item.impl_item_id());
289 intravisit::walk_impl_item(self, impl_item);
293 ///////////////////////////////////////////////////////////////////////////
294 // Utility types and common code for the above passes.
296 fn bad_placeholder_type(
298 mut spans: Vec<Span>,
299 ) -> rustc_errors::DiagnosticBuilder<'tcx> {
301 let mut err = struct_span_err!(
305 "the type placeholder `_` is not allowed within types on item signatures",
308 err.span_label(span, "not allowed in type signatures");
313 impl ItemCtxt<'tcx> {
314 pub fn new(tcx: TyCtxt<'tcx>, item_def_id: DefId) -> ItemCtxt<'tcx> {
315 ItemCtxt { tcx, item_def_id }
318 pub fn to_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
319 <dyn AstConv<'_>>::ast_ty_to_ty(self, ast_ty)
322 pub fn hir_id(&self) -> hir::HirId {
323 self.tcx.hir().local_def_id_to_hir_id(self.item_def_id.expect_local())
326 pub fn node(&self) -> hir::Node<'tcx> {
327 self.tcx.hir().get(self.hir_id())
331 impl AstConv<'tcx> for ItemCtxt<'tcx> {
332 fn tcx(&self) -> TyCtxt<'tcx> {
336 fn item_def_id(&self) -> Option<DefId> {
337 Some(self.item_def_id)
340 fn default_constness_for_trait_bounds(&self) -> hir::Constness {
341 if let Some(fn_like) = FnLikeNode::from_node(self.node()) {
344 hir::Constness::NotConst
348 fn get_type_parameter_bounds(
353 ) -> ty::GenericPredicates<'tcx> {
354 self.tcx.at(span).type_param_predicates((
356 def_id.expect_local(),
361 fn re_infer(&self, _: Option<&ty::GenericParamDef>, _: Span) -> Option<ty::Region<'tcx>> {
365 fn allow_ty_infer(&self) -> bool {
369 fn ty_infer(&self, _: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx> {
370 self.tcx().ty_error_with_message(span, "bad_placeholder_type")
376 _: Option<&ty::GenericParamDef>,
378 ) -> &'tcx Const<'tcx> {
379 bad_placeholder_type(self.tcx(), vec![span]).emit();
380 // Typeck doesn't expect erased regions to be returned from `type_of`.
381 let ty = self.tcx.fold_regions(ty, &mut false, |r, _| match r {
382 ty::ReErased => self.tcx.lifetimes.re_static,
385 self.tcx().const_error(ty)
388 fn projected_ty_from_poly_trait_ref(
392 item_segment: &hir::PathSegment<'_>,
393 poly_trait_ref: ty::PolyTraitRef<'tcx>,
395 if let Some(trait_ref) = poly_trait_ref.no_bound_vars() {
396 let item_substs = <dyn AstConv<'tcx>>::create_substs_for_associated_item(
404 self.tcx().mk_projection(item_def_id, item_substs)
406 // There are no late-bound regions; we can just ignore the binder.
407 let mut err = struct_span_err!(
411 "cannot use the associated type of a trait \
412 with uninferred generic parameters"
416 hir::Node::Field(_) | hir::Node::Ctor(_) | hir::Node::Variant(_) => {
418 self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(self.hir_id()));
420 hir::ItemKind::Enum(_, generics)
421 | hir::ItemKind::Struct(_, generics)
422 | hir::ItemKind::Union(_, generics) => {
423 let lt_name = get_new_lifetime_name(self.tcx, poly_trait_ref, generics);
424 let (lt_sp, sugg) = match generics.params {
425 [] => (generics.span, format!("<{}>", lt_name)),
427 (bound.span.shrink_to_lo(), format!("{}, ", lt_name))
430 let suggestions = vec![
436 // Replace the existing lifetimes with a new named lifetime.
438 .replace_late_bound_regions(poly_trait_ref, |_| {
439 self.tcx.mk_region(ty::ReEarlyBound(
440 ty::EarlyBoundRegion {
443 name: Symbol::intern(<_name),
452 err.multipart_suggestion(
453 "use a fully qualified path with explicit lifetimes",
455 Applicability::MaybeIncorrect,
461 hir::Node::Item(hir::Item {
463 hir::ItemKind::Struct(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Union(..),
467 | hir::Node::ForeignItem(_)
468 | hir::Node::TraitItem(_)
469 | hir::Node::ImplItem(_) => {
472 "use a fully qualified path with inferred lifetimes",
475 // Erase named lt, we want `<A as B<'_>::C`, not `<A as B<'a>::C`.
476 self.tcx.anonymize_late_bound_regions(poly_trait_ref).skip_binder(),
479 Applicability::MaybeIncorrect,
485 self.tcx().ty_error()
489 fn normalize_ty(&self, _span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
490 // Types in item signatures are not normalized to avoid undue dependencies.
494 fn set_tainted_by_errors(&self) {
495 // There's no obvious place to track this, so just let it go.
498 fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) {
499 // There's no place to record types from signatures?
503 /// Synthesize a new lifetime name that doesn't clash with any of the lifetimes already present.
504 fn get_new_lifetime_name<'tcx>(
506 poly_trait_ref: ty::PolyTraitRef<'tcx>,
507 generics: &hir::Generics<'tcx>,
509 let existing_lifetimes = tcx
510 .collect_referenced_late_bound_regions(&poly_trait_ref)
513 if let ty::BoundRegionKind::BrNamed(_, name) = lt {
514 Some(name.as_str().to_string())
519 .chain(generics.params.iter().filter_map(|param| {
520 if let hir::GenericParamKind::Lifetime { .. } = ¶m.kind {
521 Some(param.name.ident().as_str().to_string())
526 .collect::<FxHashSet<String>>();
528 let a_to_z_repeat_n = |n| {
529 (b'a'..=b'z').map(move |c| {
530 let mut s = '\''.to_string();
531 s.extend(std::iter::repeat(char::from(c)).take(n));
536 // If all single char lifetime names are present, we wrap around and double the chars.
537 (1..).flat_map(a_to_z_repeat_n).find(|lt| !existing_lifetimes.contains(lt.as_str())).unwrap()
540 /// Returns the predicates defined on `item_def_id` of the form
541 /// `X: Foo` where `X` is the type parameter `def_id`.
542 fn type_param_predicates(
544 (item_def_id, def_id, assoc_name): (DefId, LocalDefId, Ident),
545 ) -> ty::GenericPredicates<'_> {
548 // In the AST, bounds can derive from two places. Either
549 // written inline like `<T: Foo>` or in a where-clause like
552 let param_id = tcx.hir().local_def_id_to_hir_id(def_id);
553 let param_owner = tcx.hir().ty_param_owner(param_id);
554 let param_owner_def_id = tcx.hir().local_def_id(param_owner);
555 let generics = tcx.generics_of(param_owner_def_id);
556 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
557 let ty = tcx.mk_ty_param(index, tcx.hir().ty_param_name(param_id));
559 // Don't look for bounds where the type parameter isn't in scope.
560 let parent = if item_def_id == param_owner_def_id.to_def_id() {
563 tcx.generics_of(item_def_id).parent
566 let mut result = parent
568 let icx = ItemCtxt::new(tcx, parent);
569 icx.get_type_parameter_bounds(DUMMY_SP, def_id.to_def_id(), assoc_name)
571 .unwrap_or_default();
572 let mut extend = None;
574 let item_hir_id = tcx.hir().local_def_id_to_hir_id(item_def_id.expect_local());
575 let ast_generics = match tcx.hir().get(item_hir_id) {
576 Node::TraitItem(item) => &item.generics,
578 Node::ImplItem(item) => &item.generics,
580 Node::Item(item) => {
582 ItemKind::Fn(.., ref generics, _)
583 | ItemKind::Impl(hir::Impl { ref generics, .. })
584 | ItemKind::TyAlias(_, ref generics)
585 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
586 | ItemKind::Enum(_, ref generics)
587 | ItemKind::Struct(_, ref generics)
588 | ItemKind::Union(_, ref generics) => generics,
589 ItemKind::Trait(_, _, ref generics, ..) => {
590 // Implied `Self: Trait` and supertrait bounds.
591 if param_id == item_hir_id {
592 let identity_trait_ref = ty::TraitRef::identity(tcx, item_def_id);
594 Some((identity_trait_ref.without_const().to_predicate(tcx), item.span));
602 Node::ForeignItem(item) => match item.kind {
603 ForeignItemKind::Fn(_, _, ref generics) => generics,
610 let icx = ItemCtxt::new(tcx, item_def_id);
611 let extra_predicates = extend.into_iter().chain(
612 icx.type_parameter_bounds_in_generics(
616 OnlySelfBounds(true),
620 .filter(|(predicate, _)| match predicate.kind().skip_binder() {
621 ty::PredicateKind::Trait(data, _) => data.self_ty().is_param(index),
626 tcx.arena.alloc_from_iter(result.predicates.iter().copied().chain(extra_predicates));
630 impl ItemCtxt<'tcx> {
631 /// Finds bounds from `hir::Generics`. This requires scanning through the
632 /// AST. We do this to avoid having to convert *all* the bounds, which
633 /// would create artificial cycles. Instead, we can only convert the
634 /// bounds for a type parameter `X` if `X::Foo` is used.
635 fn type_parameter_bounds_in_generics(
637 ast_generics: &'tcx hir::Generics<'tcx>,
638 param_id: hir::HirId,
640 only_self_bounds: OnlySelfBounds,
641 assoc_name: Option<Ident>,
642 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
643 let constness = self.default_constness_for_trait_bounds();
644 let from_ty_params = ast_generics
647 .filter_map(|param| match param.kind {
648 GenericParamKind::Type { .. } if param.hir_id == param_id => Some(¶m.bounds),
651 .flat_map(|bounds| bounds.iter())
652 .filter(|b| match assoc_name {
653 Some(assoc_name) => self.bound_defines_assoc_item(b, assoc_name),
656 .flat_map(|b| predicates_from_bound(self, ty, b, constness));
658 let from_where_clauses = ast_generics
662 .filter_map(|wp| match *wp {
663 hir::WherePredicate::BoundPredicate(ref bp) => Some(bp),
667 let bt = if is_param(self.tcx, &bp.bounded_ty, param_id) {
669 } else if !only_self_bounds.0 {
670 Some(self.to_ty(&bp.bounded_ty))
676 .filter(|b| match assoc_name {
677 Some(assoc_name) => self.bound_defines_assoc_item(b, assoc_name),
680 .filter_map(move |b| bt.map(|bt| (bt, b)))
682 .flat_map(|(bt, b)| predicates_from_bound(self, bt, b, constness));
684 from_ty_params.chain(from_where_clauses).collect()
687 fn bound_defines_assoc_item(&self, b: &hir::GenericBound<'_>, assoc_name: Ident) -> bool {
688 debug!("bound_defines_assoc_item(b={:?}, assoc_name={:?})", b, assoc_name);
691 hir::GenericBound::Trait(poly_trait_ref, _) => {
692 let trait_ref = &poly_trait_ref.trait_ref;
693 if let Some(trait_did) = trait_ref.trait_def_id() {
694 self.tcx.trait_may_define_assoc_type(trait_did, assoc_name)
704 /// Tests whether this is the AST for a reference to the type
705 /// parameter with ID `param_id`. We use this so as to avoid running
706 /// `ast_ty_to_ty`, because we want to avoid triggering an all-out
707 /// conversion of the type to avoid inducing unnecessary cycles.
708 fn is_param(tcx: TyCtxt<'_>, ast_ty: &hir::Ty<'_>, param_id: hir::HirId) -> bool {
709 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = ast_ty.kind {
711 Res::SelfTy(Some(def_id), None) | Res::Def(DefKind::TyParam, def_id) => {
712 def_id == tcx.hir().local_def_id(param_id).to_def_id()
721 fn convert_item(tcx: TyCtxt<'_>, item_id: hir::ItemId) {
722 let it = tcx.hir().item(item_id);
723 debug!("convert: item {} with id {}", it.ident, it.hir_id());
724 let def_id = item_id.def_id;
727 // These don't define types.
728 hir::ItemKind::ExternCrate(_)
729 | hir::ItemKind::Use(..)
730 | hir::ItemKind::Mod(_)
731 | hir::ItemKind::GlobalAsm(_) => {}
732 hir::ItemKind::ForeignMod { items, .. } => {
734 let item = tcx.hir().foreign_item(item.id);
735 tcx.ensure().generics_of(item.def_id);
736 tcx.ensure().type_of(item.def_id);
737 tcx.ensure().predicates_of(item.def_id);
738 if let hir::ForeignItemKind::Fn(..) = item.kind {
739 tcx.ensure().fn_sig(item.def_id);
743 hir::ItemKind::Enum(ref enum_definition, _) => {
744 tcx.ensure().generics_of(def_id);
745 tcx.ensure().type_of(def_id);
746 tcx.ensure().predicates_of(def_id);
747 convert_enum_variant_types(tcx, def_id.to_def_id(), &enum_definition.variants);
749 hir::ItemKind::Impl { .. } => {
750 tcx.ensure().generics_of(def_id);
751 tcx.ensure().type_of(def_id);
752 tcx.ensure().impl_trait_ref(def_id);
753 tcx.ensure().predicates_of(def_id);
755 hir::ItemKind::Trait(..) => {
756 tcx.ensure().generics_of(def_id);
757 tcx.ensure().trait_def(def_id);
758 tcx.at(it.span).super_predicates_of(def_id);
759 tcx.ensure().predicates_of(def_id);
761 hir::ItemKind::TraitAlias(..) => {
762 tcx.ensure().generics_of(def_id);
763 tcx.at(it.span).super_predicates_of(def_id);
764 tcx.ensure().predicates_of(def_id);
766 hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
767 tcx.ensure().generics_of(def_id);
768 tcx.ensure().type_of(def_id);
769 tcx.ensure().predicates_of(def_id);
771 for f in struct_def.fields() {
772 let def_id = tcx.hir().local_def_id(f.hir_id);
773 tcx.ensure().generics_of(def_id);
774 tcx.ensure().type_of(def_id);
775 tcx.ensure().predicates_of(def_id);
778 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
779 convert_variant_ctor(tcx, ctor_hir_id);
783 // Desugared from `impl Trait`, so visited by the function's return type.
784 hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: Some(_), .. }) => {}
786 // Don't call `type_of` on opaque types, since that depends on type
787 // checking function bodies. `check_item_type` ensures that it's called
789 hir::ItemKind::OpaqueTy(..) => {
790 tcx.ensure().generics_of(def_id);
791 tcx.ensure().predicates_of(def_id);
792 tcx.ensure().explicit_item_bounds(def_id);
794 hir::ItemKind::TyAlias(..)
795 | hir::ItemKind::Static(..)
796 | hir::ItemKind::Const(..)
797 | hir::ItemKind::Fn(..) => {
798 tcx.ensure().generics_of(def_id);
799 tcx.ensure().type_of(def_id);
800 tcx.ensure().predicates_of(def_id);
802 hir::ItemKind::Fn(..) => tcx.ensure().fn_sig(def_id),
803 hir::ItemKind::OpaqueTy(..) => tcx.ensure().item_bounds(def_id),
810 fn convert_trait_item(tcx: TyCtxt<'_>, trait_item_id: hir::TraitItemId) {
811 let trait_item = tcx.hir().trait_item(trait_item_id);
812 tcx.ensure().generics_of(trait_item_id.def_id);
814 match trait_item.kind {
815 hir::TraitItemKind::Fn(..) => {
816 tcx.ensure().type_of(trait_item_id.def_id);
817 tcx.ensure().fn_sig(trait_item_id.def_id);
820 hir::TraitItemKind::Const(.., Some(_)) => {
821 tcx.ensure().type_of(trait_item_id.def_id);
824 hir::TraitItemKind::Const(..) => {
825 tcx.ensure().type_of(trait_item_id.def_id);
826 // Account for `const C: _;`.
827 let mut visitor = PlaceholderHirTyCollector::default();
828 visitor.visit_trait_item(trait_item);
829 placeholder_type_error(tcx, None, &[], visitor.0, false, None);
832 hir::TraitItemKind::Type(_, Some(_)) => {
833 tcx.ensure().item_bounds(trait_item_id.def_id);
834 tcx.ensure().type_of(trait_item_id.def_id);
835 // Account for `type T = _;`.
836 let mut visitor = PlaceholderHirTyCollector::default();
837 visitor.visit_trait_item(trait_item);
838 placeholder_type_error(tcx, None, &[], visitor.0, false, None);
841 hir::TraitItemKind::Type(_, None) => {
842 tcx.ensure().item_bounds(trait_item_id.def_id);
843 // #74612: Visit and try to find bad placeholders
844 // even if there is no concrete type.
845 let mut visitor = PlaceholderHirTyCollector::default();
846 visitor.visit_trait_item(trait_item);
848 placeholder_type_error(tcx, None, &[], visitor.0, false, None);
852 tcx.ensure().predicates_of(trait_item_id.def_id);
855 fn convert_impl_item(tcx: TyCtxt<'_>, impl_item_id: hir::ImplItemId) {
856 let def_id = impl_item_id.def_id;
857 tcx.ensure().generics_of(def_id);
858 tcx.ensure().type_of(def_id);
859 tcx.ensure().predicates_of(def_id);
860 let impl_item = tcx.hir().impl_item(impl_item_id);
861 match impl_item.kind {
862 hir::ImplItemKind::Fn(..) => {
863 tcx.ensure().fn_sig(def_id);
865 hir::ImplItemKind::TyAlias(_) => {
866 // Account for `type T = _;`
867 let mut visitor = PlaceholderHirTyCollector::default();
868 visitor.visit_impl_item(impl_item);
870 placeholder_type_error(tcx, None, &[], visitor.0, false, None);
872 hir::ImplItemKind::Const(..) => {}
876 fn convert_variant_ctor(tcx: TyCtxt<'_>, ctor_id: hir::HirId) {
877 let def_id = tcx.hir().local_def_id(ctor_id);
878 tcx.ensure().generics_of(def_id);
879 tcx.ensure().type_of(def_id);
880 tcx.ensure().predicates_of(def_id);
883 fn convert_enum_variant_types(tcx: TyCtxt<'_>, def_id: DefId, variants: &[hir::Variant<'_>]) {
884 let def = tcx.adt_def(def_id);
885 let repr_type = def.repr.discr_type();
886 let initial = repr_type.initial_discriminant(tcx);
887 let mut prev_discr = None::<Discr<'_>>;
889 // fill the discriminant values and field types
890 for variant in variants {
891 let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
893 if let Some(ref e) = variant.disr_expr {
894 let expr_did = tcx.hir().local_def_id(e.hir_id);
895 def.eval_explicit_discr(tcx, expr_did.to_def_id())
896 } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) {
899 struct_span_err!(tcx.sess, variant.span, E0370, "enum discriminant overflowed")
902 format!("overflowed on value after {}", prev_discr.unwrap()),
905 "explicitly set `{} = {}` if that is desired outcome",
906 variant.ident, wrapped_discr
911 .unwrap_or(wrapped_discr),
914 for f in variant.data.fields() {
915 let def_id = tcx.hir().local_def_id(f.hir_id);
916 tcx.ensure().generics_of(def_id);
917 tcx.ensure().type_of(def_id);
918 tcx.ensure().predicates_of(def_id);
921 // Convert the ctor, if any. This also registers the variant as
923 if let Some(ctor_hir_id) = variant.data.ctor_hir_id() {
924 convert_variant_ctor(tcx, ctor_hir_id);
931 variant_did: Option<LocalDefId>,
932 ctor_did: Option<LocalDefId>,
934 discr: ty::VariantDiscr,
935 def: &hir::VariantData<'_>,
936 adt_kind: ty::AdtKind,
937 parent_did: LocalDefId,
938 ) -> ty::VariantDef {
939 let mut seen_fields: FxHashMap<Ident, Span> = Default::default();
944 let fid = tcx.hir().local_def_id(f.hir_id);
945 let dup_span = seen_fields.get(&f.ident.normalize_to_macros_2_0()).cloned();
946 if let Some(prev_span) = dup_span {
947 tcx.sess.emit_err(errors::FieldAlreadyDeclared {
953 seen_fields.insert(f.ident.normalize_to_macros_2_0(), f.span);
956 ty::FieldDef { did: fid.to_def_id(), ident: f.ident, vis: tcx.visibility(fid) }
959 let recovered = match def {
960 hir::VariantData::Struct(_, r) => *r,
965 variant_did.map(LocalDefId::to_def_id),
966 ctor_did.map(LocalDefId::to_def_id),
969 CtorKind::from_hir(def),
971 parent_did.to_def_id(),
973 adt_kind == AdtKind::Struct && tcx.has_attr(parent_did.to_def_id(), sym::non_exhaustive)
974 || variant_did.map_or(false, |variant_did| {
975 tcx.has_attr(variant_did.to_def_id(), sym::non_exhaustive)
980 fn adt_def(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::AdtDef {
983 let def_id = def_id.expect_local();
984 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
985 let item = match tcx.hir().get(hir_id) {
986 Node::Item(item) => item,
990 let repr = ReprOptions::new(tcx, def_id.to_def_id());
991 let (kind, variants) = match item.kind {
992 ItemKind::Enum(ref def, _) => {
993 let mut distance_from_explicit = 0;
998 let variant_did = Some(tcx.hir().local_def_id(v.id));
1000 v.data.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
1002 let discr = if let Some(ref e) = v.disr_expr {
1003 distance_from_explicit = 0;
1004 ty::VariantDiscr::Explicit(tcx.hir().local_def_id(e.hir_id).to_def_id())
1006 ty::VariantDiscr::Relative(distance_from_explicit)
1008 distance_from_explicit += 1;
1023 (AdtKind::Enum, variants)
1025 ItemKind::Struct(ref def, _) => {
1026 let variant_did = None::<LocalDefId>;
1027 let ctor_did = def.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
1029 let variants = std::iter::once(convert_variant(
1034 ty::VariantDiscr::Relative(0),
1041 (AdtKind::Struct, variants)
1043 ItemKind::Union(ref def, _) => {
1044 let variant_did = None;
1045 let ctor_did = def.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
1047 let variants = std::iter::once(convert_variant(
1052 ty::VariantDiscr::Relative(0),
1059 (AdtKind::Union, variants)
1063 tcx.alloc_adt_def(def_id.to_def_id(), kind, variants, repr)
1066 /// Ensures that the super-predicates of the trait with a `DefId`
1067 /// of `trait_def_id` are converted and stored. This also ensures that
1068 /// the transitive super-predicates are converted.
1069 fn super_predicates_of(tcx: TyCtxt<'_>, trait_def_id: DefId) -> ty::GenericPredicates<'_> {
1070 debug!("super_predicates(trait_def_id={:?})", trait_def_id);
1071 tcx.super_predicates_that_define_assoc_type((trait_def_id, None))
1074 /// Ensures that the super-predicates of the trait with a `DefId`
1075 /// of `trait_def_id` are converted and stored. This also ensures that
1076 /// the transitive super-predicates are converted.
1077 fn super_predicates_that_define_assoc_type(
1079 (trait_def_id, assoc_name): (DefId, Option<Ident>),
1080 ) -> ty::GenericPredicates<'_> {
1082 "super_predicates_that_define_assoc_type(trait_def_id={:?}, assoc_name={:?})",
1083 trait_def_id, assoc_name
1085 if trait_def_id.is_local() {
1086 debug!("super_predicates_that_define_assoc_type: local trait_def_id={:?}", trait_def_id);
1087 let trait_hir_id = tcx.hir().local_def_id_to_hir_id(trait_def_id.expect_local());
1089 let item = match tcx.hir().get(trait_hir_id) {
1090 Node::Item(item) => item,
1091 _ => bug!("trait_node_id {} is not an item", trait_hir_id),
1094 let (generics, bounds) = match item.kind {
1095 hir::ItemKind::Trait(.., ref generics, ref supertraits, _) => (generics, supertraits),
1096 hir::ItemKind::TraitAlias(ref generics, ref supertraits) => (generics, supertraits),
1097 _ => span_bug!(item.span, "super_predicates invoked on non-trait"),
1100 let icx = ItemCtxt::new(tcx, trait_def_id);
1102 // Convert the bounds that follow the colon, e.g., `Bar + Zed` in `trait Foo: Bar + Zed`.
1103 let self_param_ty = tcx.types.self_param;
1104 let superbounds1 = if let Some(assoc_name) = assoc_name {
1105 <dyn AstConv<'_>>::compute_bounds_that_match_assoc_type(
1114 <dyn AstConv<'_>>::compute_bounds(
1123 let superbounds1 = superbounds1.predicates(tcx, self_param_ty);
1125 // Convert any explicit superbounds in the where-clause,
1126 // e.g., `trait Foo where Self: Bar`.
1127 // In the case of trait aliases, however, we include all bounds in the where-clause,
1128 // so e.g., `trait Foo = where u32: PartialEq<Self>` would include `u32: PartialEq<Self>`
1129 // as one of its "superpredicates".
1130 let is_trait_alias = tcx.is_trait_alias(trait_def_id);
1131 let superbounds2 = icx.type_parameter_bounds_in_generics(
1135 OnlySelfBounds(!is_trait_alias),
1139 // Combine the two lists to form the complete set of superbounds:
1140 let superbounds = &*tcx.arena.alloc_from_iter(superbounds1.into_iter().chain(superbounds2));
1142 // Now require that immediate supertraits are converted,
1143 // which will, in turn, reach indirect supertraits.
1144 if assoc_name.is_none() {
1145 // Now require that immediate supertraits are converted,
1146 // which will, in turn, reach indirect supertraits.
1147 for &(pred, span) in superbounds {
1148 debug!("superbound: {:?}", pred);
1149 if let ty::PredicateKind::Trait(bound, _) = pred.kind().skip_binder() {
1150 tcx.at(span).super_predicates_of(bound.def_id());
1155 ty::GenericPredicates { parent: None, predicates: superbounds }
1157 // if `assoc_name` is None, then the query should've been redirected to an
1158 // external provider
1159 assert!(assoc_name.is_some());
1160 tcx.super_predicates_of(trait_def_id)
1164 fn trait_def(tcx: TyCtxt<'_>, def_id: DefId) -> ty::TraitDef {
1165 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1166 let item = tcx.hir().expect_item(hir_id);
1168 let (is_auto, unsafety) = match item.kind {
1169 hir::ItemKind::Trait(is_auto, unsafety, ..) => (is_auto == hir::IsAuto::Yes, unsafety),
1170 hir::ItemKind::TraitAlias(..) => (false, hir::Unsafety::Normal),
1171 _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
1174 let paren_sugar = tcx.has_attr(def_id, sym::rustc_paren_sugar);
1175 if paren_sugar && !tcx.features().unboxed_closures {
1179 "the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \
1180 which traits can use parenthetical notation",
1182 .help("add `#![feature(unboxed_closures)]` to the crate attributes to use it")
1186 let is_marker = tcx.has_attr(def_id, sym::marker);
1187 let spec_kind = if tcx.has_attr(def_id, sym::rustc_unsafe_specialization_marker) {
1188 ty::trait_def::TraitSpecializationKind::Marker
1189 } else if tcx.has_attr(def_id, sym::rustc_specialization_trait) {
1190 ty::trait_def::TraitSpecializationKind::AlwaysApplicable
1192 ty::trait_def::TraitSpecializationKind::None
1194 let def_path_hash = tcx.def_path_hash(def_id);
1195 ty::TraitDef::new(def_id, unsafety, paren_sugar, is_auto, is_marker, spec_kind, def_path_hash)
1198 fn has_late_bound_regions<'tcx>(tcx: TyCtxt<'tcx>, node: Node<'tcx>) -> Option<Span> {
1199 struct LateBoundRegionsDetector<'tcx> {
1201 outer_index: ty::DebruijnIndex,
1202 has_late_bound_regions: Option<Span>,
1205 impl Visitor<'tcx> for LateBoundRegionsDetector<'tcx> {
1206 type Map = intravisit::ErasedMap<'tcx>;
1208 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1209 NestedVisitorMap::None
1212 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
1213 if self.has_late_bound_regions.is_some() {
1217 hir::TyKind::BareFn(..) => {
1218 self.outer_index.shift_in(1);
1219 intravisit::walk_ty(self, ty);
1220 self.outer_index.shift_out(1);
1222 _ => intravisit::walk_ty(self, ty),
1226 fn visit_poly_trait_ref(
1228 tr: &'tcx hir::PolyTraitRef<'tcx>,
1229 m: hir::TraitBoundModifier,
1231 if self.has_late_bound_regions.is_some() {
1234 self.outer_index.shift_in(1);
1235 intravisit::walk_poly_trait_ref(self, tr, m);
1236 self.outer_index.shift_out(1);
1239 fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
1240 if self.has_late_bound_regions.is_some() {
1244 match self.tcx.named_region(lt.hir_id) {
1245 Some(rl::Region::Static | rl::Region::EarlyBound(..)) => {}
1247 rl::Region::LateBound(debruijn, _, _) | rl::Region::LateBoundAnon(debruijn, _),
1248 ) if debruijn < self.outer_index => {}
1250 rl::Region::LateBound(..)
1251 | rl::Region::LateBoundAnon(..)
1252 | rl::Region::Free(..),
1255 self.has_late_bound_regions = Some(lt.span);
1261 fn has_late_bound_regions<'tcx>(
1263 generics: &'tcx hir::Generics<'tcx>,
1264 decl: &'tcx hir::FnDecl<'tcx>,
1266 let mut visitor = LateBoundRegionsDetector {
1268 outer_index: ty::INNERMOST,
1269 has_late_bound_regions: None,
1271 for param in generics.params {
1272 if let GenericParamKind::Lifetime { .. } = param.kind {
1273 if tcx.is_late_bound(param.hir_id) {
1274 return Some(param.span);
1278 visitor.visit_fn_decl(decl);
1279 visitor.has_late_bound_regions
1283 Node::TraitItem(item) => match item.kind {
1284 hir::TraitItemKind::Fn(ref sig, _) => {
1285 has_late_bound_regions(tcx, &item.generics, &sig.decl)
1289 Node::ImplItem(item) => match item.kind {
1290 hir::ImplItemKind::Fn(ref sig, _) => {
1291 has_late_bound_regions(tcx, &item.generics, &sig.decl)
1295 Node::ForeignItem(item) => match item.kind {
1296 hir::ForeignItemKind::Fn(ref fn_decl, _, ref generics) => {
1297 has_late_bound_regions(tcx, generics, fn_decl)
1301 Node::Item(item) => match item.kind {
1302 hir::ItemKind::Fn(ref sig, .., ref generics, _) => {
1303 has_late_bound_regions(tcx, generics, &sig.decl)
1311 struct AnonConstInParamListDetector {
1312 in_param_list: bool,
1313 found_anon_const_in_list: bool,
1317 impl<'v> Visitor<'v> for AnonConstInParamListDetector {
1318 type Map = intravisit::ErasedMap<'v>;
1320 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1321 NestedVisitorMap::None
1324 fn visit_generic_param(&mut self, p: &'v hir::GenericParam<'v>) {
1325 let prev = self.in_param_list;
1326 self.in_param_list = true;
1327 intravisit::walk_generic_param(self, p);
1328 self.in_param_list = prev;
1331 fn visit_anon_const(&mut self, c: &'v hir::AnonConst) {
1332 if self.in_param_list && self.ct == c.hir_id {
1333 self.found_anon_const_in_list = true;
1335 intravisit::walk_anon_const(self, c)
1340 fn generics_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::Generics {
1343 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1345 let node = tcx.hir().get(hir_id);
1346 let parent_def_id = match node {
1348 | Node::TraitItem(_)
1351 | Node::Field(_) => {
1352 let parent_id = tcx.hir().get_parent_item(hir_id);
1353 Some(tcx.hir().local_def_id(parent_id).to_def_id())
1355 // FIXME(#43408) always enable this once `lazy_normalization` is
1356 // stable enough and does not need a feature gate anymore.
1357 Node::AnonConst(_) => {
1358 let parent_id = tcx.hir().get_parent_item(hir_id);
1359 let parent_def_id = tcx.hir().local_def_id(parent_id);
1361 let mut in_param_list = false;
1362 for (_parent, node) in tcx.hir().parent_iter(hir_id) {
1363 if let Some(generics) = node.generics() {
1364 let mut visitor = AnonConstInParamListDetector {
1365 in_param_list: false,
1366 found_anon_const_in_list: false,
1370 visitor.visit_generics(generics);
1371 in_param_list = visitor.found_anon_const_in_list;
1377 // We do not allow generic parameters in anon consts if we are inside
1380 // This affects both default type bindings, e.g. `struct<T, U = [u8; std::mem::size_of::<T>()]>(T, U)`,
1381 // and the types of const parameters, e.g. `struct V<const N: usize, const M: [u8; N]>();`.
1383 } else if tcx.lazy_normalization() {
1384 // HACK(eddyb) this provides the correct generics when
1385 // `feature(const_generics)` is enabled, so that const expressions
1386 // used with const generics, e.g. `Foo<{N+1}>`, can work at all.
1388 // Note that we do not supply the parent generics when using
1389 // `min_const_generics`.
1390 Some(parent_def_id.to_def_id())
1392 let parent_node = tcx.hir().get(tcx.hir().get_parent_node(hir_id));
1394 // HACK(eddyb) this provides the correct generics for repeat
1395 // expressions' count (i.e. `N` in `[x; N]`), and explicit
1396 // `enum` discriminants (i.e. `D` in `enum Foo { Bar = D }`),
1397 // as they shouldn't be able to cause query cycle errors.
1398 Node::Expr(&Expr { kind: ExprKind::Repeat(_, ref constant), .. })
1399 | Node::Variant(Variant { disr_expr: Some(ref constant), .. })
1400 if constant.hir_id == hir_id =>
1402 Some(parent_def_id.to_def_id())
1409 Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => {
1410 Some(tcx.closure_base_def_id(def_id))
1412 Node::Item(item) => match item.kind {
1413 ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn, .. }) => {
1414 impl_trait_fn.or_else(|| {
1415 let parent_id = tcx.hir().get_parent_item(hir_id);
1416 assert!(parent_id != hir_id && parent_id != CRATE_HIR_ID);
1417 debug!("generics_of: parent of opaque ty {:?} is {:?}", def_id, parent_id);
1418 // Opaque types are always nested within another item, and
1419 // inherit the generics of the item.
1420 Some(tcx.hir().local_def_id(parent_id).to_def_id())
1428 let mut opt_self = None;
1429 let mut allow_defaults = false;
1431 let no_generics = hir::Generics::empty();
1432 let ast_generics = match node {
1433 Node::TraitItem(item) => &item.generics,
1435 Node::ImplItem(item) => &item.generics,
1437 Node::Item(item) => {
1439 ItemKind::Fn(.., ref generics, _)
1440 | ItemKind::Impl(hir::Impl { ref generics, .. }) => generics,
1442 ItemKind::TyAlias(_, ref generics)
1443 | ItemKind::Enum(_, ref generics)
1444 | ItemKind::Struct(_, ref generics)
1445 | ItemKind::OpaqueTy(hir::OpaqueTy { ref generics, .. })
1446 | ItemKind::Union(_, ref generics) => {
1447 allow_defaults = true;
1451 ItemKind::Trait(_, _, ref generics, ..)
1452 | ItemKind::TraitAlias(ref generics, ..) => {
1453 // Add in the self type parameter.
1455 // Something of a hack: use the node id for the trait, also as
1456 // the node id for the Self type parameter.
1457 let param_id = item.def_id;
1459 opt_self = Some(ty::GenericParamDef {
1461 name: kw::SelfUpper,
1462 def_id: param_id.to_def_id(),
1463 pure_wrt_drop: false,
1464 kind: ty::GenericParamDefKind::Type {
1466 object_lifetime_default: rl::Set1::Empty,
1471 allow_defaults = true;
1479 Node::ForeignItem(item) => match item.kind {
1480 ForeignItemKind::Static(..) => &no_generics,
1481 ForeignItemKind::Fn(_, _, ref generics) => generics,
1482 ForeignItemKind::Type => &no_generics,
1488 let has_self = opt_self.is_some();
1489 let mut parent_has_self = false;
1490 let mut own_start = has_self as u32;
1491 let parent_count = parent_def_id.map_or(0, |def_id| {
1492 let generics = tcx.generics_of(def_id);
1493 assert_eq!(has_self, false);
1494 parent_has_self = generics.has_self;
1495 own_start = generics.count() as u32;
1496 generics.parent_count + generics.params.len()
1499 let mut params: Vec<_> = Vec::with_capacity(ast_generics.params.len() + has_self as usize);
1501 if let Some(opt_self) = opt_self {
1502 params.push(opt_self);
1505 let early_lifetimes = early_bound_lifetimes_from_generics(tcx, ast_generics);
1506 params.extend(early_lifetimes.enumerate().map(|(i, param)| ty::GenericParamDef {
1507 name: param.name.ident().name,
1508 index: own_start + i as u32,
1509 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
1510 pure_wrt_drop: param.pure_wrt_drop,
1511 kind: ty::GenericParamDefKind::Lifetime,
1514 let object_lifetime_defaults = tcx.object_lifetime_defaults(hir_id);
1516 // Now create the real type and const parameters.
1517 let type_start = own_start - has_self as u32 + params.len() as u32;
1520 params.extend(ast_generics.params.iter().filter_map(|param| match param.kind {
1521 GenericParamKind::Lifetime { .. } => None,
1522 GenericParamKind::Type { ref default, synthetic, .. } => {
1523 if !allow_defaults && default.is_some() {
1524 if !tcx.features().default_type_parameter_fallback {
1525 tcx.struct_span_lint_hir(
1526 lint::builtin::INVALID_TYPE_PARAM_DEFAULT,
1531 "defaults for type parameters are only allowed in \
1532 `struct`, `enum`, `type`, or `trait` definitions",
1540 let kind = ty::GenericParamDefKind::Type {
1541 has_default: default.is_some(),
1542 object_lifetime_default: object_lifetime_defaults
1544 .map_or(rl::Set1::Empty, |o| o[i]),
1548 let param_def = ty::GenericParamDef {
1549 index: type_start + i as u32,
1550 name: param.name.ident().name,
1551 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
1552 pure_wrt_drop: param.pure_wrt_drop,
1558 GenericParamKind::Const { default, .. } => {
1559 if !allow_defaults && default.is_some() {
1562 "defaults for const parameters are only allowed in \
1563 `struct`, `enum`, `type`, or `trait` definitions",
1567 let param_def = ty::GenericParamDef {
1568 index: type_start + i as u32,
1569 name: param.name.ident().name,
1570 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
1571 pure_wrt_drop: param.pure_wrt_drop,
1572 kind: ty::GenericParamDefKind::Const { has_default: default.is_some() },
1579 // provide junk type parameter defs - the only place that
1580 // cares about anything but the length is instantiation,
1581 // and we don't do that for closures.
1582 if let Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(.., gen), .. }) = node {
1583 let dummy_args = if gen.is_some() {
1584 &["<resume_ty>", "<yield_ty>", "<return_ty>", "<witness>", "<upvars>"][..]
1586 &["<closure_kind>", "<closure_signature>", "<upvars>"][..]
1589 params.extend(dummy_args.iter().enumerate().map(|(i, &arg)| ty::GenericParamDef {
1590 index: type_start + i as u32,
1591 name: Symbol::intern(arg),
1593 pure_wrt_drop: false,
1594 kind: ty::GenericParamDefKind::Type {
1596 object_lifetime_default: rl::Set1::Empty,
1602 let param_def_id_to_index = params.iter().map(|param| (param.def_id, param.index)).collect();
1605 parent: parent_def_id,
1608 param_def_id_to_index,
1609 has_self: has_self || parent_has_self,
1610 has_late_bound_regions: has_late_bound_regions(tcx, node),
1614 fn are_suggestable_generic_args(generic_args: &[hir::GenericArg<'_>]) -> bool {
1617 .filter_map(|arg| match arg {
1618 hir::GenericArg::Type(ty) => Some(ty),
1621 .any(is_suggestable_infer_ty)
1624 /// Whether `ty` is a type with `_` placeholders that can be inferred. Used in diagnostics only to
1625 /// use inference to provide suggestions for the appropriate type if possible.
1626 fn is_suggestable_infer_ty(ty: &hir::Ty<'_>) -> bool {
1630 Slice(ty) | Array(ty, _) => is_suggestable_infer_ty(ty),
1631 Tup(tys) => tys.iter().any(is_suggestable_infer_ty),
1632 Ptr(mut_ty) | Rptr(_, mut_ty) => is_suggestable_infer_ty(mut_ty.ty),
1633 OpaqueDef(_, generic_args) => are_suggestable_generic_args(generic_args),
1634 Path(hir::QPath::TypeRelative(ty, segment)) => {
1635 is_suggestable_infer_ty(ty) || are_suggestable_generic_args(segment.args().args)
1637 Path(hir::QPath::Resolved(ty_opt, hir::Path { segments, .. })) => {
1638 ty_opt.map_or(false, is_suggestable_infer_ty)
1639 || segments.iter().any(|segment| are_suggestable_generic_args(segment.args().args))
1645 pub fn get_infer_ret_ty(output: &'hir hir::FnRetTy<'hir>) -> Option<&'hir hir::Ty<'hir>> {
1646 if let hir::FnRetTy::Return(ref ty) = output {
1647 if is_suggestable_infer_ty(ty) {
1654 fn fn_sig(tcx: TyCtxt<'_>, def_id: DefId) -> ty::PolyFnSig<'_> {
1655 use rustc_hir::Node::*;
1658 let def_id = def_id.expect_local();
1659 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
1661 let icx = ItemCtxt::new(tcx, def_id.to_def_id());
1663 match tcx.hir().get(hir_id) {
1664 TraitItem(hir::TraitItem {
1665 kind: TraitItemKind::Fn(sig, TraitFn::Provided(_)),
1670 | ImplItem(hir::ImplItem { kind: ImplItemKind::Fn(sig, _), ident, generics, .. })
1671 | Item(hir::Item { kind: ItemKind::Fn(sig, generics, _), ident, .. }) => {
1672 match get_infer_ret_ty(&sig.decl.output) {
1674 let fn_sig = tcx.typeck(def_id).liberated_fn_sigs()[hir_id];
1675 // Typeck doesn't expect erased regions to be returned from `type_of`.
1676 let fn_sig = tcx.fold_regions(fn_sig, &mut false, |r, _| match r {
1677 ty::ReErased => tcx.lifetimes.re_static,
1681 let mut visitor = PlaceholderHirTyCollector::default();
1682 visitor.visit_ty(ty);
1683 let mut diag = bad_placeholder_type(tcx, visitor.0);
1684 let ret_ty = fn_sig.output();
1685 if ret_ty != tcx.ty_error() {
1686 if !ret_ty.is_closure() {
1687 let ret_ty_str = match ret_ty.kind() {
1688 // Suggest a function pointer return type instead of a unique function definition
1689 // (e.g. `fn() -> i32` instead of `fn() -> i32 { f }`, the latter of which is invalid
1691 ty::FnDef(..) => ret_ty.fn_sig(tcx).to_string(),
1692 _ => ret_ty.to_string(),
1694 diag.span_suggestion(
1696 "replace with the correct return type",
1698 Applicability::MaybeIncorrect,
1701 // We're dealing with a closure, so we should suggest using `impl Fn` or trait bounds
1702 // to prevent the user from getting a papercut while trying to use the unique closure
1703 // syntax (e.g. `[closure@src/lib.rs:2:5: 2:9]`).
1704 diag.help("consider using an `Fn`, `FnMut`, or `FnOnce` trait bound");
1705 diag.note("for more information on `Fn` traits and closure types, see https://doc.rust-lang.org/book/ch13-01-closures.html");
1710 ty::Binder::bind(fn_sig)
1712 None => <dyn AstConv<'_>>::ty_of_fn(
1714 sig.header.unsafety,
1724 TraitItem(hir::TraitItem {
1725 kind: TraitItemKind::Fn(FnSig { header, decl, span: _ }, _),
1729 }) => <dyn AstConv<'_>>::ty_of_fn(
1739 ForeignItem(&hir::ForeignItem {
1740 kind: ForeignItemKind::Fn(ref fn_decl, _, _),
1744 let abi = tcx.hir().get_foreign_abi(hir_id);
1745 compute_sig_of_foreign_fn_decl(tcx, def_id.to_def_id(), fn_decl, abi, ident)
1748 Ctor(data) | Variant(hir::Variant { data, .. }) if data.ctor_hir_id().is_some() => {
1749 let ty = tcx.type_of(tcx.hir().get_parent_did(hir_id).to_def_id());
1751 data.fields().iter().map(|f| tcx.type_of(tcx.hir().local_def_id(f.hir_id)));
1752 ty::Binder::bind(tcx.mk_fn_sig(
1756 hir::Unsafety::Normal,
1761 Expr(&hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => {
1762 // Closure signatures are not like other function
1763 // signatures and cannot be accessed through `fn_sig`. For
1764 // example, a closure signature excludes the `self`
1765 // argument. In any case they are embedded within the
1766 // closure type as part of the `ClosureSubsts`.
1768 // To get the signature of a closure, you should use the
1769 // `sig` method on the `ClosureSubsts`:
1771 // substs.as_closure().sig(def_id, tcx)
1773 "to get the signature of a closure, use `substs.as_closure().sig()` not `fn_sig()`",
1778 bug!("unexpected sort of node in fn_sig(): {:?}", x);
1783 fn impl_trait_ref(tcx: TyCtxt<'_>, def_id: DefId) -> Option<ty::TraitRef<'_>> {
1784 let icx = ItemCtxt::new(tcx, def_id);
1786 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1787 match tcx.hir().expect_item(hir_id).kind {
1788 hir::ItemKind::Impl(ref impl_) => impl_.of_trait.as_ref().map(|ast_trait_ref| {
1789 let selfty = tcx.type_of(def_id);
1790 <dyn AstConv<'_>>::instantiate_mono_trait_ref(&icx, ast_trait_ref, selfty)
1796 fn impl_polarity(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ImplPolarity {
1797 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1798 let is_rustc_reservation = tcx.has_attr(def_id, sym::rustc_reservation_impl);
1799 let item = tcx.hir().expect_item(hir_id);
1801 hir::ItemKind::Impl(hir::Impl {
1802 polarity: hir::ImplPolarity::Negative(span),
1806 if is_rustc_reservation {
1807 let span = span.to(of_trait.as_ref().map_or(*span, |t| t.path.span));
1808 tcx.sess.span_err(span, "reservation impls can't be negative");
1810 ty::ImplPolarity::Negative
1812 hir::ItemKind::Impl(hir::Impl {
1813 polarity: hir::ImplPolarity::Positive,
1817 if is_rustc_reservation {
1818 tcx.sess.span_err(item.span, "reservation impls can't be inherent");
1820 ty::ImplPolarity::Positive
1822 hir::ItemKind::Impl(hir::Impl {
1823 polarity: hir::ImplPolarity::Positive,
1827 if is_rustc_reservation {
1828 ty::ImplPolarity::Reservation
1830 ty::ImplPolarity::Positive
1833 item => bug!("impl_polarity: {:?} not an impl", item),
1837 /// Returns the early-bound lifetimes declared in this generics
1838 /// listing. For anything other than fns/methods, this is just all
1839 /// the lifetimes that are declared. For fns or methods, we have to
1840 /// screen out those that do not appear in any where-clauses etc using
1841 /// `resolve_lifetime::early_bound_lifetimes`.
1842 fn early_bound_lifetimes_from_generics<'a, 'tcx: 'a>(
1844 generics: &'a hir::Generics<'a>,
1845 ) -> impl Iterator<Item = &'a hir::GenericParam<'a>> + Captures<'tcx> {
1846 generics.params.iter().filter(move |param| match param.kind {
1847 GenericParamKind::Lifetime { .. } => !tcx.is_late_bound(param.hir_id),
1852 /// Returns a list of type predicates for the definition with ID `def_id`, including inferred
1853 /// lifetime constraints. This includes all predicates returned by `explicit_predicates_of`, plus
1854 /// inferred constraints concerning which regions outlive other regions.
1855 fn predicates_defined_on(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1856 debug!("predicates_defined_on({:?})", def_id);
1857 let mut result = tcx.explicit_predicates_of(def_id);
1858 debug!("predicates_defined_on: explicit_predicates_of({:?}) = {:?}", def_id, result,);
1859 let inferred_outlives = tcx.inferred_outlives_of(def_id);
1860 if !inferred_outlives.is_empty() {
1862 "predicates_defined_on: inferred_outlives_of({:?}) = {:?}",
1863 def_id, inferred_outlives,
1865 if result.predicates.is_empty() {
1866 result.predicates = inferred_outlives;
1868 result.predicates = tcx
1870 .alloc_from_iter(result.predicates.iter().chain(inferred_outlives).copied());
1874 debug!("predicates_defined_on({:?}) = {:?}", def_id, result);
1878 /// Returns a list of all type predicates (explicit and implicit) for the definition with
1879 /// ID `def_id`. This includes all predicates returned by `predicates_defined_on`, plus
1880 /// `Self: Trait` predicates for traits.
1881 fn predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1882 let mut result = tcx.predicates_defined_on(def_id);
1884 if tcx.is_trait(def_id) {
1885 // For traits, add `Self: Trait` predicate. This is
1886 // not part of the predicates that a user writes, but it
1887 // is something that one must prove in order to invoke a
1888 // method or project an associated type.
1890 // In the chalk setup, this predicate is not part of the
1891 // "predicates" for a trait item. But it is useful in
1892 // rustc because if you directly (e.g.) invoke a trait
1893 // method like `Trait::method(...)`, you must naturally
1894 // prove that the trait applies to the types that were
1895 // used, and adding the predicate into this list ensures
1896 // that this is done.
1897 let span = tcx.sess.source_map().guess_head_span(tcx.def_span(def_id));
1899 tcx.arena.alloc_from_iter(result.predicates.iter().copied().chain(std::iter::once((
1900 ty::TraitRef::identity(tcx, def_id).without_const().to_predicate(tcx),
1904 debug!("predicates_of(def_id={:?}) = {:?}", def_id, result);
1908 /// Returns a list of user-specified type predicates for the definition with ID `def_id`.
1909 /// N.B., this does not include any implied/inferred constraints.
1910 fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1913 debug!("explicit_predicates_of(def_id={:?})", def_id);
1915 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1916 let node = tcx.hir().get(hir_id);
1918 let mut is_trait = None;
1919 let mut is_default_impl_trait = None;
1921 let icx = ItemCtxt::new(tcx, def_id);
1922 let constness = icx.default_constness_for_trait_bounds();
1924 const NO_GENERICS: &hir::Generics<'_> = &hir::Generics::empty();
1926 // We use an `IndexSet` to preserves order of insertion.
1927 // Preserving the order of insertion is important here so as not to break UI tests.
1928 let mut predicates: FxIndexSet<(ty::Predicate<'_>, Span)> = FxIndexSet::default();
1930 let ast_generics = match node {
1931 Node::TraitItem(item) => &item.generics,
1933 Node::ImplItem(item) => &item.generics,
1935 Node::Item(item) => {
1937 ItemKind::Impl(ref impl_) => {
1938 if impl_.defaultness.is_default() {
1939 is_default_impl_trait = tcx.impl_trait_ref(def_id);
1943 ItemKind::Fn(.., ref generics, _)
1944 | ItemKind::TyAlias(_, ref generics)
1945 | ItemKind::Enum(_, ref generics)
1946 | ItemKind::Struct(_, ref generics)
1947 | ItemKind::Union(_, ref generics) => generics,
1949 ItemKind::Trait(_, _, ref generics, ..) => {
1950 is_trait = Some(ty::TraitRef::identity(tcx, def_id));
1953 ItemKind::TraitAlias(ref generics, _) => {
1954 is_trait = Some(ty::TraitRef::identity(tcx, def_id));
1957 ItemKind::OpaqueTy(OpaqueTy {
1963 if impl_trait_fn.is_some() {
1964 // return-position impl trait
1966 // We don't inherit predicates from the parent here:
1967 // If we have, say `fn f<'a, T: 'a>() -> impl Sized {}`
1968 // then the return type is `f::<'static, T>::{{opaque}}`.
1970 // If we inherited the predicates of `f` then we would
1971 // require that `T: 'static` to show that the return
1972 // type is well-formed.
1974 // The only way to have something with this opaque type
1975 // is from the return type of the containing function,
1976 // which will ensure that the function's predicates
1978 return ty::GenericPredicates { parent: None, predicates: &[] };
1980 // type-alias impl trait
1989 Node::ForeignItem(item) => match item.kind {
1990 ForeignItemKind::Static(..) => NO_GENERICS,
1991 ForeignItemKind::Fn(_, _, ref generics) => generics,
1992 ForeignItemKind::Type => NO_GENERICS,
1998 let generics = tcx.generics_of(def_id);
1999 let parent_count = generics.parent_count as u32;
2000 let has_own_self = generics.has_self && parent_count == 0;
2002 // Below we'll consider the bounds on the type parameters (including `Self`)
2003 // and the explicit where-clauses, but to get the full set of predicates
2004 // on a trait we need to add in the supertrait bounds and bounds found on
2005 // associated types.
2006 if let Some(_trait_ref) = is_trait {
2007 predicates.extend(tcx.super_predicates_of(def_id).predicates.iter().cloned());
2010 // In default impls, we can assume that the self type implements
2011 // the trait. So in:
2013 // default impl Foo for Bar { .. }
2015 // we add a default where clause `Foo: Bar`. We do a similar thing for traits
2016 // (see below). Recall that a default impl is not itself an impl, but rather a
2017 // set of defaults that can be incorporated into another impl.
2018 if let Some(trait_ref) = is_default_impl_trait {
2020 trait_ref.to_poly_trait_ref().without_const().to_predicate(tcx),
2021 tcx.def_span(def_id),
2025 // Collect the region predicates that were declared inline as
2026 // well. In the case of parameters declared on a fn or method, we
2027 // have to be careful to only iterate over early-bound regions.
2028 let mut index = parent_count + has_own_self as u32;
2029 for param in early_bound_lifetimes_from_generics(tcx, ast_generics) {
2030 let region = tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
2031 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
2033 name: param.name.ident().name,
2038 GenericParamKind::Lifetime { .. } => {
2039 param.bounds.iter().for_each(|bound| match bound {
2040 hir::GenericBound::Outlives(lt) => {
2041 let bound = <dyn AstConv<'_>>::ast_region_to_region(&icx, <, None);
2042 let outlives = ty::Binder::bind(ty::OutlivesPredicate(region, bound));
2043 predicates.insert((outlives.to_predicate(tcx), lt.span));
2052 // Collect the predicates that were written inline by the user on each
2053 // type parameter (e.g., `<T: Foo>`).
2054 for param in ast_generics.params {
2056 // We already dealt with early bound lifetimes above.
2057 GenericParamKind::Lifetime { .. } => (),
2058 GenericParamKind::Type { .. } => {
2059 let name = param.name.ident().name;
2060 let param_ty = ty::ParamTy::new(index, name).to_ty(tcx);
2063 let sized = SizedByDefault::Yes;
2064 let bounds = <dyn AstConv<'_>>::compute_bounds(
2071 predicates.extend(bounds.predicates(tcx, param_ty));
2073 GenericParamKind::Const { .. } => {
2074 // Bounds on const parameters are currently not possible.
2075 debug_assert!(param.bounds.is_empty());
2081 // Add in the bounds that appear in the where-clause.
2082 let where_clause = &ast_generics.where_clause;
2083 for predicate in where_clause.predicates {
2085 hir::WherePredicate::BoundPredicate(bound_pred) => {
2086 let ty = icx.to_ty(&bound_pred.bounded_ty);
2088 // Keep the type around in a dummy predicate, in case of no bounds.
2089 // That way, `where Ty:` is not a complete noop (see #53696) and `Ty`
2090 // is still checked for WF.
2091 if bound_pred.bounds.is_empty() {
2092 if let ty::Param(_) = ty.kind() {
2093 // This is a `where T:`, which can be in the HIR from the
2094 // transformation that moves `?Sized` to `T`'s declaration.
2095 // We can skip the predicate because type parameters are
2096 // trivially WF, but also we *should*, to avoid exposing
2097 // users who never wrote `where Type:,` themselves, to
2098 // compiler/tooling bugs from not handling WF predicates.
2100 let span = bound_pred.bounded_ty.span;
2101 let re_root_empty = tcx.lifetimes.re_root_empty;
2102 let predicate = ty::Binder::bind(ty::PredicateKind::TypeOutlives(
2103 ty::OutlivesPredicate(ty, re_root_empty),
2105 predicates.insert((predicate.to_predicate(tcx), span));
2109 for bound in bound_pred.bounds.iter() {
2111 hir::GenericBound::Trait(poly_trait_ref, modifier) => {
2112 let constness = match modifier {
2113 hir::TraitBoundModifier::MaybeConst => hir::Constness::NotConst,
2114 hir::TraitBoundModifier::None => constness,
2115 hir::TraitBoundModifier::Maybe => bug!("this wasn't handled"),
2118 let mut bounds = Bounds::default();
2119 let _ = <dyn AstConv<'_>>::instantiate_poly_trait_ref(
2126 predicates.extend(bounds.predicates(tcx, ty));
2129 &hir::GenericBound::LangItemTrait(lang_item, span, hir_id, args) => {
2130 let mut bounds = Bounds::default();
2131 <dyn AstConv<'_>>::instantiate_lang_item_trait_ref(
2140 predicates.extend(bounds.predicates(tcx, ty));
2143 hir::GenericBound::Outlives(lifetime) => {
2145 <dyn AstConv<'_>>::ast_region_to_region(&icx, lifetime, None);
2147 ty::Binder::bind(ty::PredicateKind::TypeOutlives(
2148 ty::OutlivesPredicate(ty, region),
2158 hir::WherePredicate::RegionPredicate(region_pred) => {
2159 let r1 = <dyn AstConv<'_>>::ast_region_to_region(&icx, ®ion_pred.lifetime, None);
2160 predicates.extend(region_pred.bounds.iter().map(|bound| {
2161 let (r2, span) = match bound {
2162 hir::GenericBound::Outlives(lt) => {
2163 (<dyn AstConv<'_>>::ast_region_to_region(&icx, lt, None), lt.span)
2167 let pred = ty::PredicateKind::RegionOutlives(ty::OutlivesPredicate(r1, r2))
2168 .to_predicate(icx.tcx);
2174 hir::WherePredicate::EqPredicate(..) => {
2180 if tcx.features().const_evaluatable_checked {
2181 predicates.extend(const_evaluatable_predicates_of(tcx, def_id.expect_local()));
2184 let mut predicates: Vec<_> = predicates.into_iter().collect();
2186 // Subtle: before we store the predicates into the tcx, we
2187 // sort them so that predicates like `T: Foo<Item=U>` come
2188 // before uses of `U`. This avoids false ambiguity errors
2189 // in trait checking. See `setup_constraining_predicates`
2191 if let Node::Item(&Item { kind: ItemKind::Impl { .. }, .. }) = node {
2192 let self_ty = tcx.type_of(def_id);
2193 let trait_ref = tcx.impl_trait_ref(def_id);
2194 cgp::setup_constraining_predicates(
2198 &mut cgp::parameters_for_impl(self_ty, trait_ref),
2202 let result = ty::GenericPredicates {
2203 parent: generics.parent,
2204 predicates: tcx.arena.alloc_from_iter(predicates),
2206 debug!("explicit_predicates_of(def_id={:?}) = {:?}", def_id, result);
2210 fn const_evaluatable_predicates_of<'tcx>(
2213 ) -> FxIndexSet<(ty::Predicate<'tcx>, Span)> {
2214 struct ConstCollector<'tcx> {
2216 preds: FxIndexSet<(ty::Predicate<'tcx>, Span)>,
2219 impl<'tcx> intravisit::Visitor<'tcx> for ConstCollector<'tcx> {
2220 type Map = Map<'tcx>;
2222 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
2223 intravisit::NestedVisitorMap::None
2226 fn visit_anon_const(&mut self, c: &'tcx hir::AnonConst) {
2227 let def_id = self.tcx.hir().local_def_id(c.hir_id);
2228 let ct = ty::Const::from_anon_const(self.tcx, def_id);
2229 if let ty::ConstKind::Unevaluated(uv) = ct.val {
2230 assert_eq!(uv.promoted, None);
2231 let span = self.tcx.hir().span(c.hir_id);
2233 ty::PredicateKind::ConstEvaluatable(uv.def, uv.substs).to_predicate(self.tcx),
2240 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
2241 let node = tcx.hir().get(hir_id);
2243 let mut collector = ConstCollector { tcx, preds: FxIndexSet::default() };
2244 if let hir::Node::Item(item) = node {
2245 if let hir::ItemKind::Impl(ref impl_) = item.kind {
2246 if let Some(of_trait) = &impl_.of_trait {
2247 debug!("const_evaluatable_predicates_of({:?}): visit impl trait_ref", def_id);
2248 collector.visit_trait_ref(of_trait);
2251 debug!("const_evaluatable_predicates_of({:?}): visit_self_ty", def_id);
2252 collector.visit_ty(impl_.self_ty);
2256 if let Some(generics) = node.generics() {
2257 debug!("const_evaluatable_predicates_of({:?}): visit_generics", def_id);
2258 collector.visit_generics(generics);
2261 if let Some(fn_sig) = tcx.hir().fn_sig_by_hir_id(hir_id) {
2262 debug!("const_evaluatable_predicates_of({:?}): visit_fn_decl", def_id);
2263 collector.visit_fn_decl(fn_sig.decl);
2265 debug!("const_evaluatable_predicates_of({:?}) = {:?}", def_id, collector.preds);
2270 fn trait_explicit_predicates_and_bounds(
2273 ) -> ty::GenericPredicates<'_> {
2274 assert_eq!(tcx.def_kind(def_id), DefKind::Trait);
2275 gather_explicit_predicates_of(tcx, def_id.to_def_id())
2278 fn explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
2279 if let DefKind::Trait = tcx.def_kind(def_id) {
2280 // Remove bounds on associated types from the predicates, they will be
2281 // returned by `explicit_item_bounds`.
2282 let predicates_and_bounds = tcx.trait_explicit_predicates_and_bounds(def_id.expect_local());
2283 let trait_identity_substs = InternalSubsts::identity_for_item(tcx, def_id);
2285 let is_assoc_item_ty = |ty: Ty<'_>| {
2286 // For a predicate from a where clause to become a bound on an
2288 // * It must use the identity substs of the item.
2289 // * Since any generic parameters on the item are not in scope,
2290 // this means that the item is not a GAT, and its identity
2291 // substs are the same as the trait's.
2292 // * It must be an associated type for this trait (*not* a
2294 if let ty::Projection(projection) = ty.kind() {
2295 projection.substs == trait_identity_substs
2296 && tcx.associated_item(projection.item_def_id).container.id() == def_id
2302 let predicates: Vec<_> = predicates_and_bounds
2306 .filter(|(pred, _)| match pred.kind().skip_binder() {
2307 ty::PredicateKind::Trait(tr, _) => !is_assoc_item_ty(tr.self_ty()),
2308 ty::PredicateKind::Projection(proj) => {
2309 !is_assoc_item_ty(proj.projection_ty.self_ty())
2311 ty::PredicateKind::TypeOutlives(outlives) => !is_assoc_item_ty(outlives.0),
2315 if predicates.len() == predicates_and_bounds.predicates.len() {
2316 predicates_and_bounds
2318 ty::GenericPredicates {
2319 parent: predicates_and_bounds.parent,
2320 predicates: tcx.arena.alloc_slice(&predicates),
2324 gather_explicit_predicates_of(tcx, def_id)
2328 fn projection_ty_from_predicates(
2333 // def_id of `N` in `<T as Trait>::N`
2336 ) -> Option<ty::ProjectionTy<'tcx>> {
2337 let (ty_def_id, item_def_id) = key;
2338 let mut projection_ty = None;
2339 for (predicate, _) in tcx.predicates_of(ty_def_id).predicates {
2340 if let ty::PredicateKind::Projection(projection_predicate) = predicate.kind().skip_binder()
2342 if item_def_id == projection_predicate.projection_ty.item_def_id {
2343 projection_ty = Some(projection_predicate.projection_ty);
2351 /// Converts a specific `GenericBound` from the AST into a set of
2352 /// predicates that apply to the self type. A vector is returned
2353 /// because this can be anywhere from zero predicates (`T: ?Sized` adds no
2354 /// predicates) to one (`T: Foo`) to many (`T: Bar<X = i32>` adds `T: Bar`
2355 /// and `<T as Bar>::X == i32`).
2356 fn predicates_from_bound<'tcx>(
2357 astconv: &dyn AstConv<'tcx>,
2359 bound: &'tcx hir::GenericBound<'tcx>,
2360 constness: hir::Constness,
2361 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2363 hir::GenericBound::Trait(ref tr, modifier) => {
2364 let constness = match modifier {
2365 hir::TraitBoundModifier::Maybe => return vec![],
2366 hir::TraitBoundModifier::MaybeConst => hir::Constness::NotConst,
2367 hir::TraitBoundModifier::None => constness,
2370 let mut bounds = Bounds::default();
2371 let _ = astconv.instantiate_poly_trait_ref(tr, constness, param_ty, &mut bounds);
2372 bounds.predicates(astconv.tcx(), param_ty)
2374 hir::GenericBound::LangItemTrait(lang_item, span, hir_id, args) => {
2375 let mut bounds = Bounds::default();
2376 astconv.instantiate_lang_item_trait_ref(
2384 bounds.predicates(astconv.tcx(), param_ty)
2386 hir::GenericBound::Outlives(ref lifetime) => {
2387 let region = astconv.ast_region_to_region(lifetime, None);
2388 let pred = ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(param_ty, region))
2389 .to_predicate(astconv.tcx());
2390 vec![(pred, lifetime.span)]
2395 fn compute_sig_of_foreign_fn_decl<'tcx>(
2398 decl: &'tcx hir::FnDecl<'tcx>,
2401 ) -> ty::PolyFnSig<'tcx> {
2402 let unsafety = if abi == abi::Abi::RustIntrinsic {
2403 intrinsic_operation_unsafety(tcx.item_name(def_id))
2405 hir::Unsafety::Unsafe
2407 let fty = <dyn AstConv<'_>>::ty_of_fn(
2408 &ItemCtxt::new(tcx, def_id),
2412 &hir::Generics::empty(),
2417 // Feature gate SIMD types in FFI, since I am not sure that the
2418 // ABIs are handled at all correctly. -huonw
2419 if abi != abi::Abi::RustIntrinsic
2420 && abi != abi::Abi::PlatformIntrinsic
2421 && !tcx.features().simd_ffi
2423 let check = |ast_ty: &hir::Ty<'_>, ty: Ty<'_>| {
2428 .span_to_snippet(ast_ty.span)
2429 .map_or_else(|_| String::new(), |s| format!(" `{}`", s));
2434 "use of SIMD type{} in FFI is highly experimental and \
2435 may result in invalid code",
2439 .help("add `#![feature(simd_ffi)]` to the crate attributes to enable")
2443 for (input, ty) in iter::zip(decl.inputs, fty.inputs().skip_binder()) {
2446 if let hir::FnRetTy::Return(ref ty) = decl.output {
2447 check(&ty, fty.output().skip_binder())
2454 fn is_foreign_item(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
2455 match tcx.hir().get_if_local(def_id) {
2456 Some(Node::ForeignItem(..)) => true,
2458 _ => bug!("is_foreign_item applied to non-local def-id {:?}", def_id),
2462 fn static_mutability(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::Mutability> {
2463 match tcx.hir().get_if_local(def_id) {
2465 Node::Item(&hir::Item { kind: hir::ItemKind::Static(_, mutbl, _), .. })
2466 | Node::ForeignItem(&hir::ForeignItem {
2467 kind: hir::ForeignItemKind::Static(_, mutbl),
2472 _ => bug!("static_mutability applied to non-local def-id {:?}", def_id),
2476 fn generator_kind(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::GeneratorKind> {
2477 match tcx.hir().get_if_local(def_id) {
2478 Some(Node::Expr(&rustc_hir::Expr {
2479 kind: rustc_hir::ExprKind::Closure(_, _, body_id, _, _),
2481 })) => tcx.hir().body(body_id).generator_kind(),
2483 _ => bug!("generator_kind applied to non-local def-id {:?}", def_id),
2487 fn from_target_feature(
2490 attr: &ast::Attribute,
2491 supported_target_features: &FxHashMap<String, Option<Symbol>>,
2492 target_features: &mut Vec<Symbol>,
2494 let list = match attr.meta_item_list() {
2498 let bad_item = |span| {
2499 let msg = "malformed `target_feature` attribute input";
2500 let code = "enable = \"..\"".to_owned();
2502 .struct_span_err(span, &msg)
2503 .span_suggestion(span, "must be of the form", code, Applicability::HasPlaceholders)
2506 let rust_features = tcx.features();
2508 // Only `enable = ...` is accepted in the meta-item list.
2509 if !item.has_name(sym::enable) {
2510 bad_item(item.span());
2514 // Must be of the form `enable = "..."` (a string).
2515 let value = match item.value_str() {
2516 Some(value) => value,
2518 bad_item(item.span());
2523 // We allow comma separation to enable multiple features.
2524 target_features.extend(value.as_str().split(',').filter_map(|feature| {
2525 let feature_gate = match supported_target_features.get(feature) {
2529 format!("the feature named `{}` is not valid for this target", feature);
2530 let mut err = tcx.sess.struct_span_err(item.span(), &msg);
2533 format!("`{}` is not valid for this target", feature),
2535 if let Some(stripped) = feature.strip_prefix('+') {
2536 let valid = supported_target_features.contains_key(stripped);
2538 err.help("consider removing the leading `+` in the feature name");
2546 // Only allow features whose feature gates have been enabled.
2547 let allowed = match feature_gate.as_ref().copied() {
2548 Some(sym::arm_target_feature) => rust_features.arm_target_feature,
2549 Some(sym::aarch64_target_feature) => rust_features.aarch64_target_feature,
2550 Some(sym::hexagon_target_feature) => rust_features.hexagon_target_feature,
2551 Some(sym::powerpc_target_feature) => rust_features.powerpc_target_feature,
2552 Some(sym::mips_target_feature) => rust_features.mips_target_feature,
2553 Some(sym::riscv_target_feature) => rust_features.riscv_target_feature,
2554 Some(sym::avx512_target_feature) => rust_features.avx512_target_feature,
2555 Some(sym::sse4a_target_feature) => rust_features.sse4a_target_feature,
2556 Some(sym::tbm_target_feature) => rust_features.tbm_target_feature,
2557 Some(sym::wasm_target_feature) => rust_features.wasm_target_feature,
2558 Some(sym::cmpxchg16b_target_feature) => rust_features.cmpxchg16b_target_feature,
2559 Some(sym::adx_target_feature) => rust_features.adx_target_feature,
2560 Some(sym::movbe_target_feature) => rust_features.movbe_target_feature,
2561 Some(sym::rtm_target_feature) => rust_features.rtm_target_feature,
2562 Some(sym::f16c_target_feature) => rust_features.f16c_target_feature,
2563 Some(sym::ermsb_target_feature) => rust_features.ermsb_target_feature,
2564 Some(name) => bug!("unknown target feature gate {}", name),
2567 if !allowed && id.is_local() {
2569 &tcx.sess.parse_sess,
2570 feature_gate.unwrap(),
2572 &format!("the target feature `{}` is currently unstable", feature),
2576 Some(Symbol::intern(feature))
2581 fn linkage_by_name(tcx: TyCtxt<'_>, def_id: DefId, name: &str) -> Linkage {
2582 use rustc_middle::mir::mono::Linkage::*;
2584 // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
2585 // applicable to variable declarations and may not really make sense for
2586 // Rust code in the first place but allow them anyway and trust that the
2587 // user knows what s/he's doing. Who knows, unanticipated use cases may pop
2588 // up in the future.
2590 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
2591 // and don't have to be, LLVM treats them as no-ops.
2593 "appending" => Appending,
2594 "available_externally" => AvailableExternally,
2596 "extern_weak" => ExternalWeak,
2597 "external" => External,
2598 "internal" => Internal,
2599 "linkonce" => LinkOnceAny,
2600 "linkonce_odr" => LinkOnceODR,
2601 "private" => Private,
2603 "weak_odr" => WeakODR,
2605 let span = tcx.hir().span_if_local(def_id);
2606 if let Some(span) = span {
2607 tcx.sess.span_fatal(span, "invalid linkage specified")
2609 tcx.sess.fatal(&format!("invalid linkage specified: {}", name))
2615 fn codegen_fn_attrs(tcx: TyCtxt<'_>, id: DefId) -> CodegenFnAttrs {
2616 let attrs = tcx.get_attrs(id);
2618 let mut codegen_fn_attrs = CodegenFnAttrs::new();
2619 if should_inherit_track_caller(tcx, id) {
2620 codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
2623 let supported_target_features = tcx.supported_target_features(LOCAL_CRATE);
2625 let mut inline_span = None;
2626 let mut link_ordinal_span = None;
2627 let mut no_sanitize_span = None;
2628 for attr in attrs.iter() {
2629 if tcx.sess.check_name(attr, sym::cold) {
2630 codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD;
2631 } else if tcx.sess.check_name(attr, sym::rustc_allocator) {
2632 codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR;
2633 } else if tcx.sess.check_name(attr, sym::unwind) {
2634 codegen_fn_attrs.flags |= CodegenFnAttrFlags::UNWIND;
2635 } else if tcx.sess.check_name(attr, sym::ffi_returns_twice) {
2636 if tcx.is_foreign_item(id) {
2637 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_RETURNS_TWICE;
2639 // `#[ffi_returns_twice]` is only allowed `extern fn`s.
2644 "`#[ffi_returns_twice]` may only be used on foreign functions"
2648 } else if tcx.sess.check_name(attr, sym::ffi_pure) {
2649 if tcx.is_foreign_item(id) {
2650 if attrs.iter().any(|a| tcx.sess.check_name(a, sym::ffi_const)) {
2651 // `#[ffi_const]` functions cannot be `#[ffi_pure]`
2656 "`#[ffi_const]` function cannot be `#[ffi_pure]`"
2660 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_PURE;
2663 // `#[ffi_pure]` is only allowed on foreign functions
2668 "`#[ffi_pure]` may only be used on foreign functions"
2672 } else if tcx.sess.check_name(attr, sym::ffi_const) {
2673 if tcx.is_foreign_item(id) {
2674 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_CONST;
2676 // `#[ffi_const]` is only allowed on foreign functions
2681 "`#[ffi_const]` may only be used on foreign functions"
2685 } else if tcx.sess.check_name(attr, sym::rustc_allocator_nounwind) {
2686 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND;
2687 } else if tcx.sess.check_name(attr, sym::naked) {
2688 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED;
2689 } else if tcx.sess.check_name(attr, sym::no_mangle) {
2690 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2691 } else if tcx.sess.check_name(attr, sym::rustc_std_internal_symbol) {
2692 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2693 } else if tcx.sess.check_name(attr, sym::used) {
2694 codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED;
2695 } else if tcx.sess.check_name(attr, sym::cmse_nonsecure_entry) {
2696 if !matches!(tcx.fn_sig(id).abi(), abi::Abi::C { .. }) {
2701 "`#[cmse_nonsecure_entry]` requires C ABI"
2705 if !tcx.sess.target.llvm_target.contains("thumbv8m") {
2706 struct_span_err!(tcx.sess, attr.span, E0775, "`#[cmse_nonsecure_entry]` is only valid for targets with the TrustZone-M extension")
2709 codegen_fn_attrs.flags |= CodegenFnAttrFlags::CMSE_NONSECURE_ENTRY;
2710 } else if tcx.sess.check_name(attr, sym::thread_local) {
2711 codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL;
2712 } else if tcx.sess.check_name(attr, sym::track_caller) {
2713 if tcx.is_closure(id) || tcx.fn_sig(id).abi() != abi::Abi::Rust {
2714 struct_span_err!(tcx.sess, attr.span, E0737, "`#[track_caller]` requires Rust ABI")
2717 codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
2718 } else if tcx.sess.check_name(attr, sym::export_name) {
2719 if let Some(s) = attr.value_str() {
2720 if s.as_str().contains('\0') {
2721 // `#[export_name = ...]` will be converted to a null-terminated string,
2722 // so it may not contain any null characters.
2727 "`export_name` may not contain null characters"
2731 codegen_fn_attrs.export_name = Some(s);
2733 } else if tcx.sess.check_name(attr, sym::target_feature) {
2734 if !tcx.is_closure(id) && tcx.fn_sig(id).unsafety() == hir::Unsafety::Normal {
2735 if !tcx.features().target_feature_11 {
2736 let mut err = feature_err(
2737 &tcx.sess.parse_sess,
2738 sym::target_feature_11,
2740 "`#[target_feature(..)]` can only be applied to `unsafe` functions",
2742 err.span_label(tcx.def_span(id), "not an `unsafe` function");
2744 } else if let Some(local_id) = id.as_local() {
2745 check_target_feature_trait_unsafe(tcx, local_id, attr.span);
2748 from_target_feature(
2752 &supported_target_features,
2753 &mut codegen_fn_attrs.target_features,
2755 } else if tcx.sess.check_name(attr, sym::linkage) {
2756 if let Some(val) = attr.value_str() {
2757 codegen_fn_attrs.linkage = Some(linkage_by_name(tcx, id, &val.as_str()));
2759 } else if tcx.sess.check_name(attr, sym::link_section) {
2760 if let Some(val) = attr.value_str() {
2761 if val.as_str().bytes().any(|b| b == 0) {
2763 "illegal null byte in link_section \
2767 tcx.sess.span_err(attr.span, &msg);
2769 codegen_fn_attrs.link_section = Some(val);
2772 } else if tcx.sess.check_name(attr, sym::link_name) {
2773 codegen_fn_attrs.link_name = attr.value_str();
2774 } else if tcx.sess.check_name(attr, sym::link_ordinal) {
2775 link_ordinal_span = Some(attr.span);
2776 if let ordinal @ Some(_) = check_link_ordinal(tcx, attr) {
2777 codegen_fn_attrs.link_ordinal = ordinal;
2779 } else if tcx.sess.check_name(attr, sym::no_sanitize) {
2780 no_sanitize_span = Some(attr.span);
2781 if let Some(list) = attr.meta_item_list() {
2782 for item in list.iter() {
2783 if item.has_name(sym::address) {
2784 codegen_fn_attrs.no_sanitize |= SanitizerSet::ADDRESS;
2785 } else if item.has_name(sym::memory) {
2786 codegen_fn_attrs.no_sanitize |= SanitizerSet::MEMORY;
2787 } else if item.has_name(sym::thread) {
2788 codegen_fn_attrs.no_sanitize |= SanitizerSet::THREAD;
2789 } else if item.has_name(sym::hwaddress) {
2790 codegen_fn_attrs.no_sanitize |= SanitizerSet::HWADDRESS;
2793 .struct_span_err(item.span(), "invalid argument for `no_sanitize`")
2794 .note("expected one of: `address`, `hwaddress`, `memory` or `thread`")
2799 } else if tcx.sess.check_name(attr, sym::instruction_set) {
2800 codegen_fn_attrs.instruction_set = match attr.meta().map(|i| i.kind) {
2801 Some(MetaItemKind::List(ref items)) => match items.as_slice() {
2802 [NestedMetaItem::MetaItem(set)] => {
2804 set.path.segments.iter().map(|x| x.ident.name).collect::<Vec<_>>();
2805 match segments.as_slice() {
2806 [sym::arm, sym::a32] | [sym::arm, sym::t32] => {
2807 if !tcx.sess.target.has_thumb_interworking {
2809 tcx.sess.diagnostic(),
2812 "target does not support `#[instruction_set]`"
2816 } else if segments[1] == sym::a32 {
2817 Some(InstructionSetAttr::ArmA32)
2818 } else if segments[1] == sym::t32 {
2819 Some(InstructionSetAttr::ArmT32)
2826 tcx.sess.diagnostic(),
2829 "invalid instruction set specified",
2838 tcx.sess.diagnostic(),
2841 "`#[instruction_set]` requires an argument"
2848 tcx.sess.diagnostic(),
2851 "cannot specify more than one instruction set"
2859 tcx.sess.diagnostic(),
2862 "must specify an instruction set"
2871 codegen_fn_attrs.inline = attrs.iter().fold(InlineAttr::None, |ia, attr| {
2872 if !attr.has_name(sym::inline) {
2875 match attr.meta().map(|i| i.kind) {
2876 Some(MetaItemKind::Word) => {
2877 tcx.sess.mark_attr_used(attr);
2880 Some(MetaItemKind::List(ref items)) => {
2881 tcx.sess.mark_attr_used(attr);
2882 inline_span = Some(attr.span);
2883 if items.len() != 1 {
2885 tcx.sess.diagnostic(),
2888 "expected one argument"
2892 } else if list_contains_name(&items[..], sym::always) {
2893 if tcx.sess.instrument_coverage() {
2894 // Fixes Issue #82875. Forced inlining allows LLVM to discard functions
2895 // marked with `#[inline(always)]`, which can break coverage reporting if
2896 // that function was referenced from a coverage map.
2898 // FIXME(#83429): Is there a better place, e.g., in codegen, to check and
2899 // convert `Always` to `Hint`?
2904 } else if list_contains_name(&items[..], sym::never) {
2908 tcx.sess.diagnostic(),
2918 Some(MetaItemKind::NameValue(_)) => ia,
2923 codegen_fn_attrs.optimize = attrs.iter().fold(OptimizeAttr::None, |ia, attr| {
2924 if !attr.has_name(sym::optimize) {
2927 let err = |sp, s| struct_span_err!(tcx.sess.diagnostic(), sp, E0722, "{}", s).emit();
2928 match attr.meta().map(|i| i.kind) {
2929 Some(MetaItemKind::Word) => {
2930 err(attr.span, "expected one argument");
2933 Some(MetaItemKind::List(ref items)) => {
2934 tcx.sess.mark_attr_used(attr);
2935 inline_span = Some(attr.span);
2936 if items.len() != 1 {
2937 err(attr.span, "expected one argument");
2939 } else if list_contains_name(&items[..], sym::size) {
2941 } else if list_contains_name(&items[..], sym::speed) {
2944 err(items[0].span(), "invalid argument");
2948 Some(MetaItemKind::NameValue(_)) => ia,
2953 // #73631: closures inherit `#[target_feature]` annotations
2954 if tcx.features().target_feature_11 && tcx.is_closure(id) {
2955 let owner_id = tcx.parent(id).expect("closure should have a parent");
2958 .extend(tcx.codegen_fn_attrs(owner_id).target_features.iter().copied())
2961 // If a function uses #[target_feature] it can't be inlined into general
2962 // purpose functions as they wouldn't have the right target features
2963 // enabled. For that reason we also forbid #[inline(always)] as it can't be
2965 if !codegen_fn_attrs.target_features.is_empty() {
2966 if codegen_fn_attrs.inline == InlineAttr::Always {
2967 if let Some(span) = inline_span {
2970 "cannot use `#[inline(always)]` with \
2971 `#[target_feature]`",
2977 if !codegen_fn_attrs.no_sanitize.is_empty() {
2978 if codegen_fn_attrs.inline == InlineAttr::Always {
2979 if let (Some(no_sanitize_span), Some(inline_span)) = (no_sanitize_span, inline_span) {
2980 let hir_id = tcx.hir().local_def_id_to_hir_id(id.expect_local());
2981 tcx.struct_span_lint_hir(
2982 lint::builtin::INLINE_NO_SANITIZE,
2986 lint.build("`no_sanitize` will have no effect after inlining")
2987 .span_note(inline_span, "inlining requested here")
2995 // Weak lang items have the same semantics as "std internal" symbols in the
2996 // sense that they're preserved through all our LTO passes and only
2997 // strippable by the linker.
2999 // Additionally weak lang items have predetermined symbol names.
3000 if tcx.is_weak_lang_item(id) {
3001 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
3003 let check_name = |attr, sym| tcx.sess.check_name(attr, sym);
3004 if let Some(name) = weak_lang_items::link_name(check_name, &attrs) {
3005 codegen_fn_attrs.export_name = Some(name);
3006 codegen_fn_attrs.link_name = Some(name);
3008 check_link_name_xor_ordinal(tcx, &codegen_fn_attrs, link_ordinal_span);
3010 // Internal symbols to the standard library all have no_mangle semantics in
3011 // that they have defined symbol names present in the function name. This
3012 // also applies to weak symbols where they all have known symbol names.
3013 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
3014 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
3020 /// Checks if the provided DefId is a method in a trait impl for a trait which has track_caller
3021 /// applied to the method prototype.
3022 fn should_inherit_track_caller(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
3023 if let Some(impl_item) = tcx.opt_associated_item(def_id) {
3024 if let ty::AssocItemContainer::ImplContainer(impl_def_id) = impl_item.container {
3025 if let Some(trait_def_id) = tcx.trait_id_of_impl(impl_def_id) {
3026 if let Some(trait_item) = tcx
3027 .associated_items(trait_def_id)
3028 .filter_by_name_unhygienic(impl_item.ident.name)
3029 .find(move |trait_item| {
3030 trait_item.kind == ty::AssocKind::Fn
3031 && tcx.hygienic_eq(impl_item.ident, trait_item.ident, trait_def_id)
3035 .codegen_fn_attrs(trait_item.def_id)
3037 .intersects(CodegenFnAttrFlags::TRACK_CALLER);
3046 fn check_link_ordinal(tcx: TyCtxt<'_>, attr: &ast::Attribute) -> Option<usize> {
3047 use rustc_ast::{Lit, LitIntType, LitKind};
3048 let meta_item_list = attr.meta_item_list();
3049 let meta_item_list: Option<&[ast::NestedMetaItem]> = meta_item_list.as_ref().map(Vec::as_ref);
3050 let sole_meta_list = match meta_item_list {
3051 Some([item]) => item.literal(),
3054 if let Some(Lit { kind: LitKind::Int(ordinal, LitIntType::Unsuffixed), .. }) = sole_meta_list {
3055 if *ordinal <= usize::MAX as u128 {
3056 Some(*ordinal as usize)
3058 let msg = format!("ordinal value in `link_ordinal` is too large: `{}`", &ordinal);
3060 .struct_span_err(attr.span, &msg)
3061 .note("the value may not exceed `usize::MAX`")
3067 .struct_span_err(attr.span, "illegal ordinal format in `link_ordinal`")
3068 .note("an unsuffixed integer value, e.g., `1`, is expected")
3074 fn check_link_name_xor_ordinal(
3076 codegen_fn_attrs: &CodegenFnAttrs,
3077 inline_span: Option<Span>,
3079 if codegen_fn_attrs.link_name.is_none() || codegen_fn_attrs.link_ordinal.is_none() {
3082 let msg = "cannot use `#[link_name]` with `#[link_ordinal]`";
3083 if let Some(span) = inline_span {
3084 tcx.sess.span_err(span, msg);
3090 /// Checks the function annotated with `#[target_feature]` is not a safe
3091 /// trait method implementation, reporting an error if it is.
3092 fn check_target_feature_trait_unsafe(tcx: TyCtxt<'_>, id: LocalDefId, attr_span: Span) {
3093 let hir_id = tcx.hir().local_def_id_to_hir_id(id);
3094 let node = tcx.hir().get(hir_id);
3095 if let Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }) = node {
3096 let parent_id = tcx.hir().get_parent_item(hir_id);
3097 let parent_item = tcx.hir().expect_item(parent_id);
3098 if let hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) = parent_item.kind {
3102 "`#[target_feature(..)]` cannot be applied to safe trait method",
3104 .span_label(attr_span, "cannot be applied to safe trait method")
3105 .span_label(tcx.def_span(id), "not an `unsafe` function")