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, SizedByDefault};
18 use crate::bounds::Bounds;
19 use crate::check::intrinsic::intrinsic_operation_unsafety;
20 use crate::constrained_generic_params as cgp;
21 use crate::middle::resolve_lifetime as rl;
23 use rustc_ast::MetaItemKind;
24 use rustc_attr::{list_contains_name, InlineAttr, OptimizeAttr};
25 use rustc_data_structures::captures::Captures;
26 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
27 use rustc_errors::{struct_span_err, Applicability};
29 use rustc_hir::def::{CtorKind, DefKind, Res};
30 use rustc_hir::def_id::{DefId, LocalDefId, LOCAL_CRATE};
31 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
32 use rustc_hir::weak_lang_items;
33 use rustc_hir::{GenericParamKind, HirId, Node};
34 use rustc_middle::hir::map::blocks::FnLikeNode;
35 use rustc_middle::hir::map::Map;
36 use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
37 use rustc_middle::mir::mono::Linkage;
38 use rustc_middle::ty::query::Providers;
39 use rustc_middle::ty::subst::InternalSubsts;
40 use rustc_middle::ty::util::Discr;
41 use rustc_middle::ty::util::IntTypeExt;
42 use rustc_middle::ty::{self, AdtKind, Const, ToPolyTraitRef, Ty, TyCtxt};
43 use rustc_middle::ty::{ReprOptions, ToPredicate, WithConstness};
44 use rustc_session::config::SanitizerSet;
45 use rustc_session::lint;
46 use rustc_session::parse::feature_err;
47 use rustc_span::symbol::{kw, sym, Ident, Symbol};
48 use rustc_span::{Span, DUMMY_SP};
49 use rustc_target::spec::abi;
50 use rustc_trait_selection::traits::error_reporting::suggestions::NextTypeParamName;
54 struct OnlySelfBounds(bool);
56 ///////////////////////////////////////////////////////////////////////////
59 fn collect_mod_item_types(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
60 tcx.hir().visit_item_likes_in_module(
62 &mut CollectItemTypesVisitor { tcx }.as_deep_visitor(),
66 pub fn provide(providers: &mut Providers) {
67 *providers = Providers {
68 opt_const_param_of: type_of::opt_const_param_of,
69 type_of: type_of::type_of,
72 predicates_defined_on,
73 explicit_predicates_of,
75 type_param_predicates,
85 collect_mod_item_types,
90 ///////////////////////////////////////////////////////////////////////////
92 /// Context specific to some particular item. This is what implements
93 /// `AstConv`. It has information about the predicates that are defined
94 /// on the trait. Unfortunately, this predicate information is
95 /// available in various different forms at various points in the
96 /// process. So we can't just store a pointer to e.g., the AST or the
97 /// parsed ty form, we have to be more flexible. To this end, the
98 /// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy
99 /// `get_type_parameter_bounds` requests, drawing the information from
100 /// the AST (`hir::Generics`), recursively.
101 pub struct ItemCtxt<'tcx> {
106 ///////////////////////////////////////////////////////////////////////////
109 crate struct PlaceholderHirTyCollector(crate Vec<Span>);
111 impl<'v> Visitor<'v> for PlaceholderHirTyCollector {
112 type Map = intravisit::ErasedMap<'v>;
114 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
115 NestedVisitorMap::None
117 fn visit_ty(&mut self, t: &'v hir::Ty<'v>) {
118 if let hir::TyKind::Infer = t.kind {
121 intravisit::walk_ty(self, t)
125 struct CollectItemTypesVisitor<'tcx> {
129 /// If there are any placeholder types (`_`), emit an error explaining that this is not allowed
130 /// and suggest adding type parameters in the appropriate place, taking into consideration any and
131 /// all already existing generic type parameters to avoid suggesting a name that is already in use.
132 crate fn placeholder_type_error(
135 generics: &[hir::GenericParam<'_>],
136 placeholder_types: Vec<Span>,
139 if placeholder_types.is_empty() {
143 let type_name = generics.next_type_param_name(None);
144 let mut sugg: Vec<_> =
145 placeholder_types.iter().map(|sp| (*sp, (*type_name).to_string())).collect();
147 if generics.is_empty() {
148 if let Some(span) = span {
149 sugg.push((span, format!("<{}>", type_name)));
151 } else if let Some(arg) = generics.iter().find(|arg| match arg.name {
152 hir::ParamName::Plain(Ident { name: kw::Underscore, .. }) => true,
155 // Account for `_` already present in cases like `struct S<_>(_);` and suggest
156 // `struct S<T>(T);` instead of `struct S<_, T>(T);`.
157 sugg.push((arg.span, (*type_name).to_string()));
159 let last = generics.iter().last().unwrap();
161 // Account for bounds, we want `fn foo<T: E, K>(_: K)` not `fn foo<T, K: E>(_: K)`.
162 last.bounds_span().unwrap_or(last.span).shrink_to_hi(),
163 format!(", {}", type_name),
167 let mut err = bad_placeholder_type(tcx, placeholder_types);
169 err.multipart_suggestion(
170 "use type parameters instead",
172 Applicability::HasPlaceholders,
178 fn reject_placeholder_type_signatures_in_item(tcx: TyCtxt<'tcx>, item: &'tcx hir::Item<'tcx>) {
179 let (generics, suggest) = match &item.kind {
180 hir::ItemKind::Union(_, generics)
181 | hir::ItemKind::Enum(_, generics)
182 | hir::ItemKind::TraitAlias(generics, _)
183 | hir::ItemKind::Trait(_, _, generics, ..)
184 | hir::ItemKind::Impl { generics, .. }
185 | hir::ItemKind::Struct(_, generics) => (generics, true),
186 hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. })
187 | hir::ItemKind::TyAlias(_, generics) => (generics, false),
188 // `static`, `fn` and `const` are handled elsewhere to suggest appropriate type.
192 let mut visitor = PlaceholderHirTyCollector::default();
193 visitor.visit_item(item);
195 placeholder_type_error(tcx, Some(generics.span), &generics.params[..], visitor.0, suggest);
198 impl Visitor<'tcx> for CollectItemTypesVisitor<'tcx> {
199 type Map = Map<'tcx>;
201 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
202 NestedVisitorMap::OnlyBodies(self.tcx.hir())
205 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
206 convert_item(self.tcx, item.hir_id);
207 reject_placeholder_type_signatures_in_item(self.tcx, item);
208 intravisit::walk_item(self, item);
211 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
212 for param in generics.params {
214 hir::GenericParamKind::Lifetime { .. } => {}
215 hir::GenericParamKind::Type { default: Some(_), .. } => {
216 let def_id = self.tcx.hir().local_def_id(param.hir_id);
217 self.tcx.ensure().type_of(def_id);
219 hir::GenericParamKind::Type { .. } => {}
220 hir::GenericParamKind::Const { .. } => {
221 let def_id = self.tcx.hir().local_def_id(param.hir_id);
222 self.tcx.ensure().type_of(def_id);
226 intravisit::walk_generics(self, generics);
229 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
230 if let hir::ExprKind::Closure(..) = expr.kind {
231 let def_id = self.tcx.hir().local_def_id(expr.hir_id);
232 self.tcx.ensure().generics_of(def_id);
233 self.tcx.ensure().type_of(def_id);
235 intravisit::walk_expr(self, expr);
238 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
239 convert_trait_item(self.tcx, trait_item.hir_id);
240 intravisit::walk_trait_item(self, trait_item);
243 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
244 convert_impl_item(self.tcx, impl_item.hir_id);
245 intravisit::walk_impl_item(self, impl_item);
249 ///////////////////////////////////////////////////////////////////////////
250 // Utility types and common code for the above passes.
252 fn bad_placeholder_type(
254 mut spans: Vec<Span>,
255 ) -> rustc_errors::DiagnosticBuilder<'tcx> {
257 let mut err = struct_span_err!(
261 "the type placeholder `_` is not allowed within types on item signatures",
264 err.span_label(span, "not allowed in type signatures");
269 impl ItemCtxt<'tcx> {
270 pub fn new(tcx: TyCtxt<'tcx>, item_def_id: DefId) -> ItemCtxt<'tcx> {
271 ItemCtxt { tcx, item_def_id }
274 pub fn to_ty(&self, ast_ty: &'tcx hir::Ty<'tcx>) -> Ty<'tcx> {
275 AstConv::ast_ty_to_ty(self, ast_ty)
278 pub fn hir_id(&self) -> hir::HirId {
279 self.tcx.hir().local_def_id_to_hir_id(self.item_def_id.expect_local())
282 pub fn node(&self) -> hir::Node<'tcx> {
283 self.tcx.hir().get(self.hir_id())
287 impl AstConv<'tcx> for ItemCtxt<'tcx> {
288 fn tcx(&self) -> TyCtxt<'tcx> {
292 fn item_def_id(&self) -> Option<DefId> {
293 Some(self.item_def_id)
296 fn default_constness_for_trait_bounds(&self) -> hir::Constness {
297 if let Some(fn_like) = FnLikeNode::from_node(self.node()) {
300 hir::Constness::NotConst
304 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId) -> ty::GenericPredicates<'tcx> {
305 self.tcx.at(span).type_param_predicates((self.item_def_id, def_id.expect_local()))
308 fn re_infer(&self, _: Option<&ty::GenericParamDef>, _: Span) -> Option<ty::Region<'tcx>> {
312 fn allow_ty_infer(&self) -> bool {
316 fn ty_infer(&self, _: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx> {
317 self.tcx().ty_error_with_message(span, "bad_placeholder_type")
323 _: Option<&ty::GenericParamDef>,
325 ) -> &'tcx Const<'tcx> {
326 bad_placeholder_type(self.tcx(), vec![span]).emit();
327 self.tcx().const_error(ty)
330 fn projected_ty_from_poly_trait_ref(
334 item_segment: &hir::PathSegment<'_>,
335 poly_trait_ref: ty::PolyTraitRef<'tcx>,
337 if let Some(trait_ref) = poly_trait_ref.no_bound_vars() {
338 let item_substs = <dyn AstConv<'tcx>>::create_substs_for_associated_item(
346 self.tcx().mk_projection(item_def_id, item_substs)
348 // There are no late-bound regions; we can just ignore the binder.
349 let mut err = struct_span_err!(
353 "cannot extract an associated type from a higher-ranked trait bound \
358 hir::Node::Field(_) | hir::Node::Ctor(_) | hir::Node::Variant(_) => {
360 self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(self.hir_id()));
362 hir::ItemKind::Enum(_, generics)
363 | hir::ItemKind::Struct(_, generics)
364 | hir::ItemKind::Union(_, generics) => {
365 let lt_name = get_new_lifetime_name(self.tcx, poly_trait_ref, generics);
366 let (lt_sp, sugg) = match &generics.params[..] {
367 [] => (generics.span, format!("<{}>", lt_name)),
369 (bound.span.shrink_to_lo(), format!("{}, ", lt_name))
372 let suggestions = vec![
378 // Replace the existing lifetimes with a new named lifetime.
380 .replace_late_bound_regions(&poly_trait_ref, |_| {
381 self.tcx.mk_region(ty::ReEarlyBound(
382 ty::EarlyBoundRegion {
385 name: Symbol::intern(<_name),
394 err.multipart_suggestion(
395 "use a fully qualified path with explicit lifetimes",
397 Applicability::MaybeIncorrect,
403 hir::Node::Item(hir::Item {
405 hir::ItemKind::Struct(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Union(..),
409 | hir::Node::ForeignItem(_)
410 | hir::Node::TraitItem(_)
411 | hir::Node::ImplItem(_) => {
414 "use a fully qualified path with inferred lifetimes",
417 // Erase named lt, we want `<A as B<'_>::C`, not `<A as B<'a>::C`.
418 self.tcx.anonymize_late_bound_regions(&poly_trait_ref).skip_binder(),
421 Applicability::MaybeIncorrect,
427 self.tcx().ty_error()
431 fn normalize_ty(&self, _span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
432 // Types in item signatures are not normalized to avoid undue dependencies.
436 fn set_tainted_by_errors(&self) {
437 // There's no obvious place to track this, so just let it go.
440 fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) {
441 // There's no place to record types from signatures?
445 /// Synthesize a new lifetime name that doesn't clash with any of the lifetimes already present.
446 fn get_new_lifetime_name<'tcx>(
448 poly_trait_ref: ty::PolyTraitRef<'tcx>,
449 generics: &hir::Generics<'tcx>,
451 let existing_lifetimes = tcx
452 .collect_referenced_late_bound_regions(&poly_trait_ref)
455 if let ty::BoundRegion::BrNamed(_, name) = lt {
456 Some(name.as_str().to_string())
461 .chain(generics.params.iter().filter_map(|param| {
462 if let hir::GenericParamKind::Lifetime { .. } = ¶m.kind {
463 Some(param.name.ident().as_str().to_string())
468 .collect::<FxHashSet<String>>();
470 let a_to_z_repeat_n = |n| {
471 (b'a'..=b'z').map(move |c| {
472 let mut s = '\''.to_string();
473 s.extend(std::iter::repeat(char::from(c)).take(n));
478 // If all single char lifetime names are present, we wrap around and double the chars.
479 (1..).flat_map(a_to_z_repeat_n).find(|lt| !existing_lifetimes.contains(lt.as_str())).unwrap()
482 /// Returns the predicates defined on `item_def_id` of the form
483 /// `X: Foo` where `X` is the type parameter `def_id`.
484 fn type_param_predicates(
486 (item_def_id, def_id): (DefId, LocalDefId),
487 ) -> ty::GenericPredicates<'_> {
490 // In the AST, bounds can derive from two places. Either
491 // written inline like `<T: Foo>` or in a where-clause like
494 let param_id = tcx.hir().local_def_id_to_hir_id(def_id);
495 let param_owner = tcx.hir().ty_param_owner(param_id);
496 let param_owner_def_id = tcx.hir().local_def_id(param_owner);
497 let generics = tcx.generics_of(param_owner_def_id);
498 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
499 let ty = tcx.mk_ty_param(index, tcx.hir().ty_param_name(param_id));
501 // Don't look for bounds where the type parameter isn't in scope.
502 let parent = if item_def_id == param_owner_def_id.to_def_id() {
505 tcx.generics_of(item_def_id).parent
508 let mut result = parent
510 let icx = ItemCtxt::new(tcx, parent);
511 icx.get_type_parameter_bounds(DUMMY_SP, def_id.to_def_id())
513 .unwrap_or_default();
514 let mut extend = None;
516 let item_hir_id = tcx.hir().local_def_id_to_hir_id(item_def_id.expect_local());
517 let ast_generics = match tcx.hir().get(item_hir_id) {
518 Node::TraitItem(item) => &item.generics,
520 Node::ImplItem(item) => &item.generics,
522 Node::Item(item) => {
524 ItemKind::Fn(.., ref generics, _)
525 | ItemKind::Impl { ref generics, .. }
526 | ItemKind::TyAlias(_, ref generics)
527 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
528 | ItemKind::Enum(_, ref generics)
529 | ItemKind::Struct(_, ref generics)
530 | ItemKind::Union(_, ref generics) => generics,
531 ItemKind::Trait(_, _, ref generics, ..) => {
532 // Implied `Self: Trait` and supertrait bounds.
533 if param_id == item_hir_id {
534 let identity_trait_ref = ty::TraitRef::identity(tcx, item_def_id);
536 Some((identity_trait_ref.without_const().to_predicate(tcx), item.span));
544 Node::ForeignItem(item) => match item.kind {
545 ForeignItemKind::Fn(_, _, ref generics) => generics,
552 let icx = ItemCtxt::new(tcx, item_def_id);
553 let extra_predicates = extend.into_iter().chain(
554 icx.type_parameter_bounds_in_generics(ast_generics, param_id, ty, OnlySelfBounds(true))
556 .filter(|(predicate, _)| match predicate.skip_binders() {
557 ty::PredicateAtom::Trait(data, _) => data.self_ty().is_param(index),
562 tcx.arena.alloc_from_iter(result.predicates.iter().copied().chain(extra_predicates));
566 impl ItemCtxt<'tcx> {
567 /// Finds bounds from `hir::Generics`. This requires scanning through the
568 /// AST. We do this to avoid having to convert *all* the bounds, which
569 /// would create artificial cycles. Instead, we can only convert the
570 /// bounds for a type parameter `X` if `X::Foo` is used.
571 fn type_parameter_bounds_in_generics(
573 ast_generics: &'tcx hir::Generics<'tcx>,
574 param_id: hir::HirId,
576 only_self_bounds: OnlySelfBounds,
577 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
578 let constness = self.default_constness_for_trait_bounds();
579 let from_ty_params = ast_generics
582 .filter_map(|param| match param.kind {
583 GenericParamKind::Type { .. } if param.hir_id == param_id => Some(¶m.bounds),
586 .flat_map(|bounds| bounds.iter())
587 .flat_map(|b| predicates_from_bound(self, ty, b, constness));
589 let from_where_clauses = ast_generics
593 .filter_map(|wp| match *wp {
594 hir::WherePredicate::BoundPredicate(ref bp) => Some(bp),
598 let bt = if is_param(self.tcx, &bp.bounded_ty, param_id) {
600 } else if !only_self_bounds.0 {
601 Some(self.to_ty(&bp.bounded_ty))
605 bp.bounds.iter().filter_map(move |b| bt.map(|bt| (bt, b)))
607 .flat_map(|(bt, b)| predicates_from_bound(self, bt, b, constness));
609 from_ty_params.chain(from_where_clauses).collect()
613 /// Tests whether this is the AST for a reference to the type
614 /// parameter with ID `param_id`. We use this so as to avoid running
615 /// `ast_ty_to_ty`, because we want to avoid triggering an all-out
616 /// conversion of the type to avoid inducing unnecessary cycles.
617 fn is_param(tcx: TyCtxt<'_>, ast_ty: &hir::Ty<'_>, param_id: hir::HirId) -> bool {
618 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = ast_ty.kind {
620 Res::SelfTy(Some(def_id), None) | Res::Def(DefKind::TyParam, def_id) => {
621 def_id == tcx.hir().local_def_id(param_id).to_def_id()
630 fn convert_item(tcx: TyCtxt<'_>, item_id: hir::HirId) {
631 let it = tcx.hir().expect_item(item_id);
632 debug!("convert: item {} with id {}", it.ident, it.hir_id);
633 let def_id = tcx.hir().local_def_id(item_id);
635 // These don't define types.
636 hir::ItemKind::ExternCrate(_)
637 | hir::ItemKind::Use(..)
638 | hir::ItemKind::Mod(_)
639 | hir::ItemKind::GlobalAsm(_) => {}
640 hir::ItemKind::ForeignMod(ref foreign_mod) => {
641 for item in foreign_mod.items {
642 let def_id = tcx.hir().local_def_id(item.hir_id);
643 tcx.ensure().generics_of(def_id);
644 tcx.ensure().type_of(def_id);
645 tcx.ensure().predicates_of(def_id);
646 if let hir::ForeignItemKind::Fn(..) = item.kind {
647 tcx.ensure().fn_sig(def_id);
651 hir::ItemKind::Enum(ref enum_definition, _) => {
652 tcx.ensure().generics_of(def_id);
653 tcx.ensure().type_of(def_id);
654 tcx.ensure().predicates_of(def_id);
655 convert_enum_variant_types(tcx, def_id.to_def_id(), &enum_definition.variants);
657 hir::ItemKind::Impl { .. } => {
658 tcx.ensure().generics_of(def_id);
659 tcx.ensure().type_of(def_id);
660 tcx.ensure().impl_trait_ref(def_id);
661 tcx.ensure().predicates_of(def_id);
663 hir::ItemKind::Trait(..) => {
664 tcx.ensure().generics_of(def_id);
665 tcx.ensure().trait_def(def_id);
666 tcx.at(it.span).super_predicates_of(def_id);
667 tcx.ensure().predicates_of(def_id);
669 hir::ItemKind::TraitAlias(..) => {
670 tcx.ensure().generics_of(def_id);
671 tcx.at(it.span).super_predicates_of(def_id);
672 tcx.ensure().predicates_of(def_id);
674 hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
675 tcx.ensure().generics_of(def_id);
676 tcx.ensure().type_of(def_id);
677 tcx.ensure().predicates_of(def_id);
679 for f in struct_def.fields() {
680 let def_id = tcx.hir().local_def_id(f.hir_id);
681 tcx.ensure().generics_of(def_id);
682 tcx.ensure().type_of(def_id);
683 tcx.ensure().predicates_of(def_id);
686 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
687 convert_variant_ctor(tcx, ctor_hir_id);
691 // Desugared from `impl Trait`, so visited by the function's return type.
692 hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: Some(_), .. }) => {}
694 hir::ItemKind::OpaqueTy(..)
695 | hir::ItemKind::TyAlias(..)
696 | hir::ItemKind::Static(..)
697 | hir::ItemKind::Const(..)
698 | hir::ItemKind::Fn(..) => {
699 tcx.ensure().generics_of(def_id);
700 tcx.ensure().type_of(def_id);
701 tcx.ensure().predicates_of(def_id);
702 if let hir::ItemKind::Fn(..) = it.kind {
703 tcx.ensure().fn_sig(def_id);
709 fn convert_trait_item(tcx: TyCtxt<'_>, trait_item_id: hir::HirId) {
710 let trait_item = tcx.hir().expect_trait_item(trait_item_id);
711 let def_id = tcx.hir().local_def_id(trait_item.hir_id);
712 tcx.ensure().generics_of(def_id);
714 match trait_item.kind {
715 hir::TraitItemKind::Fn(..) => {
716 tcx.ensure().type_of(def_id);
717 tcx.ensure().fn_sig(def_id);
720 hir::TraitItemKind::Const(.., Some(_)) => {
721 tcx.ensure().type_of(def_id);
724 hir::TraitItemKind::Const(..) | hir::TraitItemKind::Type(_, Some(_)) => {
725 tcx.ensure().type_of(def_id);
726 // Account for `const C: _;` and `type T = _;`.
727 let mut visitor = PlaceholderHirTyCollector::default();
728 visitor.visit_trait_item(trait_item);
729 placeholder_type_error(tcx, None, &[], visitor.0, false);
732 hir::TraitItemKind::Type(_, None) => {
733 // #74612: Visit and try to find bad placeholders
734 // even if there is no concrete type.
735 let mut visitor = PlaceholderHirTyCollector::default();
736 visitor.visit_trait_item(trait_item);
737 placeholder_type_error(tcx, None, &[], visitor.0, false);
741 tcx.ensure().predicates_of(def_id);
744 fn convert_impl_item(tcx: TyCtxt<'_>, impl_item_id: hir::HirId) {
745 let def_id = tcx.hir().local_def_id(impl_item_id);
746 tcx.ensure().generics_of(def_id);
747 tcx.ensure().type_of(def_id);
748 tcx.ensure().predicates_of(def_id);
749 let impl_item = tcx.hir().expect_impl_item(impl_item_id);
750 match impl_item.kind {
751 hir::ImplItemKind::Fn(..) => {
752 tcx.ensure().fn_sig(def_id);
754 hir::ImplItemKind::TyAlias(_) => {
755 // Account for `type T = _;`
756 let mut visitor = PlaceholderHirTyCollector::default();
757 visitor.visit_impl_item(impl_item);
758 placeholder_type_error(tcx, None, &[], visitor.0, false);
760 hir::ImplItemKind::Const(..) => {}
764 fn convert_variant_ctor(tcx: TyCtxt<'_>, ctor_id: hir::HirId) {
765 let def_id = tcx.hir().local_def_id(ctor_id);
766 tcx.ensure().generics_of(def_id);
767 tcx.ensure().type_of(def_id);
768 tcx.ensure().predicates_of(def_id);
771 fn convert_enum_variant_types(tcx: TyCtxt<'_>, def_id: DefId, variants: &[hir::Variant<'_>]) {
772 let def = tcx.adt_def(def_id);
773 let repr_type = def.repr.discr_type();
774 let initial = repr_type.initial_discriminant(tcx);
775 let mut prev_discr = None::<Discr<'_>>;
777 // fill the discriminant values and field types
778 for variant in variants {
779 let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
781 if let Some(ref e) = variant.disr_expr {
782 let expr_did = tcx.hir().local_def_id(e.hir_id);
783 def.eval_explicit_discr(tcx, expr_did.to_def_id())
784 } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) {
787 struct_span_err!(tcx.sess, variant.span, E0370, "enum discriminant overflowed")
790 format!("overflowed on value after {}", prev_discr.unwrap()),
793 "explicitly set `{} = {}` if that is desired outcome",
794 variant.ident, wrapped_discr
799 .unwrap_or(wrapped_discr),
802 for f in variant.data.fields() {
803 let def_id = tcx.hir().local_def_id(f.hir_id);
804 tcx.ensure().generics_of(def_id);
805 tcx.ensure().type_of(def_id);
806 tcx.ensure().predicates_of(def_id);
809 // Convert the ctor, if any. This also registers the variant as
811 if let Some(ctor_hir_id) = variant.data.ctor_hir_id() {
812 convert_variant_ctor(tcx, ctor_hir_id);
819 variant_did: Option<LocalDefId>,
820 ctor_did: Option<LocalDefId>,
822 discr: ty::VariantDiscr,
823 def: &hir::VariantData<'_>,
824 adt_kind: ty::AdtKind,
825 parent_did: LocalDefId,
826 ) -> ty::VariantDef {
827 let mut seen_fields: FxHashMap<Ident, Span> = Default::default();
828 let hir_id = tcx.hir().local_def_id_to_hir_id(variant_did.unwrap_or(parent_did));
833 let fid = tcx.hir().local_def_id(f.hir_id);
834 let dup_span = seen_fields.get(&f.ident.normalize_to_macros_2_0()).cloned();
835 if let Some(prev_span) = dup_span {
840 "field `{}` is already declared",
843 .span_label(f.span, "field already declared")
844 .span_label(prev_span, format!("`{}` first declared here", f.ident))
847 seen_fields.insert(f.ident.normalize_to_macros_2_0(), f.span);
851 did: fid.to_def_id(),
853 vis: ty::Visibility::from_hir(&f.vis, hir_id, tcx),
857 let recovered = match def {
858 hir::VariantData::Struct(_, r) => *r,
863 variant_did.map(LocalDefId::to_def_id),
864 ctor_did.map(LocalDefId::to_def_id),
867 CtorKind::from_hir(def),
869 parent_did.to_def_id(),
871 adt_kind == AdtKind::Struct && tcx.has_attr(parent_did.to_def_id(), sym::non_exhaustive)
872 || variant_did.map_or(false, |variant_did| {
873 tcx.has_attr(variant_did.to_def_id(), sym::non_exhaustive)
878 fn adt_def(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::AdtDef {
881 let def_id = def_id.expect_local();
882 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
883 let item = match tcx.hir().get(hir_id) {
884 Node::Item(item) => item,
888 let repr = ReprOptions::new(tcx, def_id.to_def_id());
889 let (kind, variants) = match item.kind {
890 ItemKind::Enum(ref def, _) => {
891 let mut distance_from_explicit = 0;
896 let variant_did = Some(tcx.hir().local_def_id(v.id));
898 v.data.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
900 let discr = if let Some(ref e) = v.disr_expr {
901 distance_from_explicit = 0;
902 ty::VariantDiscr::Explicit(tcx.hir().local_def_id(e.hir_id).to_def_id())
904 ty::VariantDiscr::Relative(distance_from_explicit)
906 distance_from_explicit += 1;
921 (AdtKind::Enum, variants)
923 ItemKind::Struct(ref def, _) => {
924 let variant_did = None::<LocalDefId>;
925 let ctor_did = def.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
927 let variants = std::iter::once(convert_variant(
932 ty::VariantDiscr::Relative(0),
939 (AdtKind::Struct, variants)
941 ItemKind::Union(ref def, _) => {
942 let variant_did = None;
943 let ctor_did = def.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
945 let variants = std::iter::once(convert_variant(
950 ty::VariantDiscr::Relative(0),
957 (AdtKind::Union, variants)
961 tcx.alloc_adt_def(def_id.to_def_id(), kind, variants, repr)
964 /// Ensures that the super-predicates of the trait with a `DefId`
965 /// of `trait_def_id` are converted and stored. This also ensures that
966 /// the transitive super-predicates are converted.
967 fn super_predicates_of(tcx: TyCtxt<'_>, trait_def_id: DefId) -> ty::GenericPredicates<'_> {
968 debug!("super_predicates(trait_def_id={:?})", trait_def_id);
969 let trait_hir_id = tcx.hir().local_def_id_to_hir_id(trait_def_id.expect_local());
971 let item = match tcx.hir().get(trait_hir_id) {
972 Node::Item(item) => item,
973 _ => bug!("trait_node_id {} is not an item", trait_hir_id),
976 let (generics, bounds) = match item.kind {
977 hir::ItemKind::Trait(.., ref generics, ref supertraits, _) => (generics, supertraits),
978 hir::ItemKind::TraitAlias(ref generics, ref supertraits) => (generics, supertraits),
979 _ => span_bug!(item.span, "super_predicates invoked on non-trait"),
982 let icx = ItemCtxt::new(tcx, trait_def_id);
984 // Convert the bounds that follow the colon, e.g., `Bar + Zed` in `trait Foo: Bar + Zed`.
985 let self_param_ty = tcx.types.self_param;
987 AstConv::compute_bounds(&icx, self_param_ty, bounds, SizedByDefault::No, item.span);
989 let superbounds1 = superbounds1.predicates(tcx, self_param_ty);
991 // Convert any explicit superbounds in the where-clause,
992 // e.g., `trait Foo where Self: Bar`.
993 // In the case of trait aliases, however, we include all bounds in the where-clause,
994 // so e.g., `trait Foo = where u32: PartialEq<Self>` would include `u32: PartialEq<Self>`
995 // as one of its "superpredicates".
996 let is_trait_alias = tcx.is_trait_alias(trait_def_id);
997 let superbounds2 = icx.type_parameter_bounds_in_generics(
1001 OnlySelfBounds(!is_trait_alias),
1004 // Combine the two lists to form the complete set of superbounds:
1005 let superbounds = &*tcx.arena.alloc_from_iter(superbounds1.into_iter().chain(superbounds2));
1007 // Now require that immediate supertraits are converted,
1008 // which will, in turn, reach indirect supertraits.
1009 for &(pred, span) in superbounds {
1010 debug!("superbound: {:?}", pred);
1011 if let ty::PredicateAtom::Trait(bound, _) = pred.skip_binders() {
1012 tcx.at(span).super_predicates_of(bound.def_id());
1016 ty::GenericPredicates { parent: None, predicates: superbounds }
1019 fn trait_def(tcx: TyCtxt<'_>, def_id: DefId) -> ty::TraitDef {
1020 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1021 let item = tcx.hir().expect_item(hir_id);
1023 let (is_auto, unsafety) = match item.kind {
1024 hir::ItemKind::Trait(is_auto, unsafety, ..) => (is_auto == hir::IsAuto::Yes, unsafety),
1025 hir::ItemKind::TraitAlias(..) => (false, hir::Unsafety::Normal),
1026 _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
1029 let paren_sugar = tcx.has_attr(def_id, sym::rustc_paren_sugar);
1030 if paren_sugar && !tcx.features().unboxed_closures {
1034 "the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \
1035 which traits can use parenthetical notation",
1037 .help("add `#![feature(unboxed_closures)]` to the crate attributes to use it")
1041 let is_marker = tcx.has_attr(def_id, sym::marker);
1042 let spec_kind = if tcx.has_attr(def_id, sym::rustc_unsafe_specialization_marker) {
1043 ty::trait_def::TraitSpecializationKind::Marker
1044 } else if tcx.has_attr(def_id, sym::rustc_specialization_trait) {
1045 ty::trait_def::TraitSpecializationKind::AlwaysApplicable
1047 ty::trait_def::TraitSpecializationKind::None
1049 let def_path_hash = tcx.def_path_hash(def_id);
1050 ty::TraitDef::new(def_id, unsafety, paren_sugar, is_auto, is_marker, spec_kind, def_path_hash)
1053 fn has_late_bound_regions<'tcx>(tcx: TyCtxt<'tcx>, node: Node<'tcx>) -> Option<Span> {
1054 struct LateBoundRegionsDetector<'tcx> {
1056 outer_index: ty::DebruijnIndex,
1057 has_late_bound_regions: Option<Span>,
1060 impl Visitor<'tcx> for LateBoundRegionsDetector<'tcx> {
1061 type Map = intravisit::ErasedMap<'tcx>;
1063 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1064 NestedVisitorMap::None
1067 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
1068 if self.has_late_bound_regions.is_some() {
1072 hir::TyKind::BareFn(..) => {
1073 self.outer_index.shift_in(1);
1074 intravisit::walk_ty(self, ty);
1075 self.outer_index.shift_out(1);
1077 _ => intravisit::walk_ty(self, ty),
1081 fn visit_poly_trait_ref(
1083 tr: &'tcx hir::PolyTraitRef<'tcx>,
1084 m: hir::TraitBoundModifier,
1086 if self.has_late_bound_regions.is_some() {
1089 self.outer_index.shift_in(1);
1090 intravisit::walk_poly_trait_ref(self, tr, m);
1091 self.outer_index.shift_out(1);
1094 fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
1095 if self.has_late_bound_regions.is_some() {
1099 match self.tcx.named_region(lt.hir_id) {
1100 Some(rl::Region::Static | rl::Region::EarlyBound(..)) => {}
1102 rl::Region::LateBound(debruijn, _, _) | rl::Region::LateBoundAnon(debruijn, _),
1103 ) if debruijn < self.outer_index => {}
1105 rl::Region::LateBound(..)
1106 | rl::Region::LateBoundAnon(..)
1107 | rl::Region::Free(..),
1110 self.has_late_bound_regions = Some(lt.span);
1116 fn has_late_bound_regions<'tcx>(
1118 generics: &'tcx hir::Generics<'tcx>,
1119 decl: &'tcx hir::FnDecl<'tcx>,
1121 let mut visitor = LateBoundRegionsDetector {
1123 outer_index: ty::INNERMOST,
1124 has_late_bound_regions: None,
1126 for param in generics.params {
1127 if let GenericParamKind::Lifetime { .. } = param.kind {
1128 if tcx.is_late_bound(param.hir_id) {
1129 return Some(param.span);
1133 visitor.visit_fn_decl(decl);
1134 visitor.has_late_bound_regions
1138 Node::TraitItem(item) => match item.kind {
1139 hir::TraitItemKind::Fn(ref sig, _) => {
1140 has_late_bound_regions(tcx, &item.generics, &sig.decl)
1144 Node::ImplItem(item) => match item.kind {
1145 hir::ImplItemKind::Fn(ref sig, _) => {
1146 has_late_bound_regions(tcx, &item.generics, &sig.decl)
1150 Node::ForeignItem(item) => match item.kind {
1151 hir::ForeignItemKind::Fn(ref fn_decl, _, ref generics) => {
1152 has_late_bound_regions(tcx, generics, fn_decl)
1156 Node::Item(item) => match item.kind {
1157 hir::ItemKind::Fn(ref sig, .., ref generics, _) => {
1158 has_late_bound_regions(tcx, generics, &sig.decl)
1166 struct AnonConstInParamListDetector {
1167 in_param_list: bool,
1168 found_anon_const_in_list: bool,
1172 impl<'v> Visitor<'v> for AnonConstInParamListDetector {
1173 type Map = intravisit::ErasedMap<'v>;
1175 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1176 NestedVisitorMap::None
1179 fn visit_generic_param(&mut self, p: &'v hir::GenericParam<'v>) {
1180 let prev = self.in_param_list;
1181 self.in_param_list = true;
1182 intravisit::walk_generic_param(self, p);
1183 self.in_param_list = prev;
1186 fn visit_anon_const(&mut self, c: &'v hir::AnonConst) {
1187 if self.in_param_list && self.ct == c.hir_id {
1188 self.found_anon_const_in_list = true;
1190 intravisit::walk_anon_const(self, c)
1195 fn generics_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::Generics {
1198 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1200 let node = tcx.hir().get(hir_id);
1201 let parent_def_id = match node {
1203 | Node::TraitItem(_)
1206 | Node::Field(_) => {
1207 let parent_id = tcx.hir().get_parent_item(hir_id);
1208 Some(tcx.hir().local_def_id(parent_id).to_def_id())
1210 // FIXME(#43408) always enable this once `lazy_normalization` is
1211 // stable enough and does not need a feature gate anymore.
1212 Node::AnonConst(_) => {
1213 let parent_id = tcx.hir().get_parent_item(hir_id);
1214 let parent_def_id = tcx.hir().local_def_id(parent_id);
1216 let mut in_param_list = false;
1217 for (_parent, node) in tcx.hir().parent_iter(hir_id) {
1218 if let Some(generics) = node.generics() {
1219 let mut visitor = AnonConstInParamListDetector {
1220 in_param_list: false,
1221 found_anon_const_in_list: false,
1225 visitor.visit_generics(generics);
1226 in_param_list = visitor.found_anon_const_in_list;
1232 // We do not allow generic parameters in anon consts if we are inside
1235 // This affects both default type bindings, e.g. `struct<T, U = [u8; std::mem::size_of::<T>()]>(T, U)`,
1236 // and the types of const parameters, e.g. `struct V<const N: usize, const M: [u8; N]>();`.
1238 } else if tcx.lazy_normalization() {
1239 // HACK(eddyb) this provides the correct generics when
1240 // `feature(const_generics)` is enabled, so that const expressions
1241 // used with const generics, e.g. `Foo<{N+1}>`, can work at all.
1243 // Note that we do not supply the parent generics when using
1244 // `feature(min_const_generics)`.
1245 Some(parent_def_id.to_def_id())
1247 let parent_node = tcx.hir().get(tcx.hir().get_parent_node(hir_id));
1249 // HACK(eddyb) this provides the correct generics for repeat
1250 // expressions' count (i.e. `N` in `[x; N]`), and explicit
1251 // `enum` discriminants (i.e. `D` in `enum Foo { Bar = D }`),
1252 // as they shouldn't be able to cause query cycle errors.
1253 Node::Expr(&Expr { kind: ExprKind::Repeat(_, ref constant), .. })
1254 | Node::Variant(Variant { disr_expr: Some(ref constant), .. })
1255 if constant.hir_id == hir_id =>
1257 Some(parent_def_id.to_def_id())
1264 Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => {
1265 Some(tcx.closure_base_def_id(def_id))
1267 Node::Item(item) => match item.kind {
1268 ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn, .. }) => {
1269 impl_trait_fn.or_else(|| {
1270 let parent_id = tcx.hir().get_parent_item(hir_id);
1271 assert!(parent_id != hir_id && parent_id != CRATE_HIR_ID);
1272 debug!("generics_of: parent of opaque ty {:?} is {:?}", def_id, parent_id);
1273 // Opaque types are always nested within another item, and
1274 // inherit the generics of the item.
1275 Some(tcx.hir().local_def_id(parent_id).to_def_id())
1283 let mut opt_self = None;
1284 let mut allow_defaults = false;
1286 let no_generics = hir::Generics::empty();
1287 let ast_generics = match node {
1288 Node::TraitItem(item) => &item.generics,
1290 Node::ImplItem(item) => &item.generics,
1292 Node::Item(item) => {
1294 ItemKind::Fn(.., ref generics, _) | ItemKind::Impl { ref generics, .. } => generics,
1296 ItemKind::TyAlias(_, ref generics)
1297 | ItemKind::Enum(_, ref generics)
1298 | ItemKind::Struct(_, ref generics)
1299 | ItemKind::OpaqueTy(hir::OpaqueTy { ref generics, .. })
1300 | ItemKind::Union(_, ref generics) => {
1301 allow_defaults = true;
1305 ItemKind::Trait(_, _, ref generics, ..)
1306 | ItemKind::TraitAlias(ref generics, ..) => {
1307 // Add in the self type parameter.
1309 // Something of a hack: use the node id for the trait, also as
1310 // the node id for the Self type parameter.
1311 let param_id = item.hir_id;
1313 opt_self = Some(ty::GenericParamDef {
1315 name: kw::SelfUpper,
1316 def_id: tcx.hir().local_def_id(param_id).to_def_id(),
1317 pure_wrt_drop: false,
1318 kind: ty::GenericParamDefKind::Type {
1320 object_lifetime_default: rl::Set1::Empty,
1325 allow_defaults = true;
1333 Node::ForeignItem(item) => match item.kind {
1334 ForeignItemKind::Static(..) => &no_generics,
1335 ForeignItemKind::Fn(_, _, ref generics) => generics,
1336 ForeignItemKind::Type => &no_generics,
1342 let has_self = opt_self.is_some();
1343 let mut parent_has_self = false;
1344 let mut own_start = has_self as u32;
1345 let parent_count = parent_def_id.map_or(0, |def_id| {
1346 let generics = tcx.generics_of(def_id);
1347 assert_eq!(has_self, false);
1348 parent_has_self = generics.has_self;
1349 own_start = generics.count() as u32;
1350 generics.parent_count + generics.params.len()
1353 let mut params: Vec<_> = opt_self.into_iter().collect();
1355 let early_lifetimes = early_bound_lifetimes_from_generics(tcx, ast_generics);
1356 params.extend(early_lifetimes.enumerate().map(|(i, param)| ty::GenericParamDef {
1357 name: param.name.ident().name,
1358 index: own_start + i as u32,
1359 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
1360 pure_wrt_drop: param.pure_wrt_drop,
1361 kind: ty::GenericParamDefKind::Lifetime,
1364 let object_lifetime_defaults = tcx.object_lifetime_defaults(hir_id);
1366 // Now create the real type and const parameters.
1367 let type_start = own_start - has_self as u32 + params.len() as u32;
1370 params.extend(ast_generics.params.iter().filter_map(|param| match param.kind {
1371 GenericParamKind::Lifetime { .. } => None,
1372 GenericParamKind::Type { ref default, synthetic, .. } => {
1373 if !allow_defaults && default.is_some() {
1374 if !tcx.features().default_type_parameter_fallback {
1375 tcx.struct_span_lint_hir(
1376 lint::builtin::INVALID_TYPE_PARAM_DEFAULT,
1381 "defaults for type parameters are only allowed in \
1382 `struct`, `enum`, `type`, or `trait` definitions.",
1390 let kind = ty::GenericParamDefKind::Type {
1391 has_default: default.is_some(),
1392 object_lifetime_default: object_lifetime_defaults
1394 .map_or(rl::Set1::Empty, |o| o[i]),
1398 let param_def = ty::GenericParamDef {
1399 index: type_start + i as u32,
1400 name: param.name.ident().name,
1401 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
1402 pure_wrt_drop: param.pure_wrt_drop,
1408 GenericParamKind::Const { .. } => {
1409 let param_def = ty::GenericParamDef {
1410 index: type_start + i as u32,
1411 name: param.name.ident().name,
1412 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
1413 pure_wrt_drop: param.pure_wrt_drop,
1414 kind: ty::GenericParamDefKind::Const,
1421 // provide junk type parameter defs - the only place that
1422 // cares about anything but the length is instantiation,
1423 // and we don't do that for closures.
1424 if let Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(.., gen), .. }) = node {
1425 let dummy_args = if gen.is_some() {
1426 &["<resume_ty>", "<yield_ty>", "<return_ty>", "<witness>", "<upvars>"][..]
1428 &["<closure_kind>", "<closure_signature>", "<upvars>"][..]
1431 params.extend(dummy_args.iter().enumerate().map(|(i, &arg)| ty::GenericParamDef {
1432 index: type_start + i as u32,
1433 name: Symbol::intern(arg),
1435 pure_wrt_drop: false,
1436 kind: ty::GenericParamDefKind::Type {
1438 object_lifetime_default: rl::Set1::Empty,
1444 let param_def_id_to_index = params.iter().map(|param| (param.def_id, param.index)).collect();
1447 parent: parent_def_id,
1450 param_def_id_to_index,
1451 has_self: has_self || parent_has_self,
1452 has_late_bound_regions: has_late_bound_regions(tcx, node),
1456 fn are_suggestable_generic_args(generic_args: &[hir::GenericArg<'_>]) -> bool {
1459 .filter_map(|arg| match arg {
1460 hir::GenericArg::Type(ty) => Some(ty),
1463 .any(is_suggestable_infer_ty)
1466 /// Whether `ty` is a type with `_` placeholders that can be inferred. Used in diagnostics only to
1467 /// use inference to provide suggestions for the appropriate type if possible.
1468 fn is_suggestable_infer_ty(ty: &hir::Ty<'_>) -> bool {
1472 Slice(ty) | Array(ty, _) => is_suggestable_infer_ty(ty),
1473 Tup(tys) => tys.iter().any(is_suggestable_infer_ty),
1474 Ptr(mut_ty) | Rptr(_, mut_ty) => is_suggestable_infer_ty(mut_ty.ty),
1475 OpaqueDef(_, generic_args) => are_suggestable_generic_args(generic_args),
1476 Path(hir::QPath::TypeRelative(ty, segment)) => {
1477 is_suggestable_infer_ty(ty) || are_suggestable_generic_args(segment.generic_args().args)
1479 Path(hir::QPath::Resolved(ty_opt, hir::Path { segments, .. })) => {
1480 ty_opt.map_or(false, is_suggestable_infer_ty)
1483 .any(|segment| are_suggestable_generic_args(segment.generic_args().args))
1489 pub fn get_infer_ret_ty(output: &'hir hir::FnRetTy<'hir>) -> Option<&'hir hir::Ty<'hir>> {
1490 if let hir::FnRetTy::Return(ref ty) = output {
1491 if is_suggestable_infer_ty(ty) {
1498 fn fn_sig(tcx: TyCtxt<'_>, def_id: DefId) -> ty::PolyFnSig<'_> {
1499 use rustc_hir::Node::*;
1502 let def_id = def_id.expect_local();
1503 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
1505 let icx = ItemCtxt::new(tcx, def_id.to_def_id());
1507 match tcx.hir().get(hir_id) {
1508 TraitItem(hir::TraitItem {
1509 kind: TraitItemKind::Fn(sig, TraitFn::Provided(_)),
1514 | ImplItem(hir::ImplItem { kind: ImplItemKind::Fn(sig, _), ident, generics, .. })
1515 | Item(hir::Item { kind: ItemKind::Fn(sig, generics, _), ident, .. }) => {
1516 match get_infer_ret_ty(&sig.decl.output) {
1518 let fn_sig = tcx.typeck(def_id).liberated_fn_sigs()[hir_id];
1519 let mut visitor = PlaceholderHirTyCollector::default();
1520 visitor.visit_ty(ty);
1521 let mut diag = bad_placeholder_type(tcx, visitor.0);
1522 let ret_ty = fn_sig.output();
1523 if ret_ty != tcx.ty_error() {
1524 diag.span_suggestion(
1526 "replace with the correct return type",
1528 Applicability::MaybeIncorrect,
1532 ty::Binder::bind(fn_sig)
1534 None => AstConv::ty_of_fn(
1536 sig.header.unsafety,
1545 TraitItem(hir::TraitItem {
1546 kind: TraitItemKind::Fn(FnSig { header, decl, span: _ }, _),
1551 AstConv::ty_of_fn(&icx, header.unsafety, header.abi, decl, &generics, Some(ident.span))
1554 ForeignItem(&hir::ForeignItem {
1555 kind: ForeignItemKind::Fn(ref fn_decl, _, _),
1559 let abi = tcx.hir().get_foreign_abi(hir_id);
1560 compute_sig_of_foreign_fn_decl(tcx, def_id.to_def_id(), fn_decl, abi, ident)
1563 Ctor(data) | Variant(hir::Variant { data, .. }) if data.ctor_hir_id().is_some() => {
1564 let ty = tcx.type_of(tcx.hir().get_parent_did(hir_id).to_def_id());
1566 data.fields().iter().map(|f| tcx.type_of(tcx.hir().local_def_id(f.hir_id)));
1567 ty::Binder::bind(tcx.mk_fn_sig(
1571 hir::Unsafety::Normal,
1576 Expr(&hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => {
1577 // Closure signatures are not like other function
1578 // signatures and cannot be accessed through `fn_sig`. For
1579 // example, a closure signature excludes the `self`
1580 // argument. In any case they are embedded within the
1581 // closure type as part of the `ClosureSubsts`.
1583 // To get the signature of a closure, you should use the
1584 // `sig` method on the `ClosureSubsts`:
1586 // substs.as_closure().sig(def_id, tcx)
1588 "to get the signature of a closure, use `substs.as_closure().sig()` not `fn_sig()`",
1593 bug!("unexpected sort of node in fn_sig(): {:?}", x);
1598 fn impl_trait_ref(tcx: TyCtxt<'_>, def_id: DefId) -> Option<ty::TraitRef<'_>> {
1599 let icx = ItemCtxt::new(tcx, def_id);
1601 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1602 match tcx.hir().expect_item(hir_id).kind {
1603 hir::ItemKind::Impl { ref of_trait, .. } => of_trait.as_ref().map(|ast_trait_ref| {
1604 let selfty = tcx.type_of(def_id);
1605 AstConv::instantiate_mono_trait_ref(&icx, ast_trait_ref, selfty)
1611 fn impl_polarity(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ImplPolarity {
1612 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1613 let is_rustc_reservation = tcx.has_attr(def_id, sym::rustc_reservation_impl);
1614 let item = tcx.hir().expect_item(hir_id);
1616 hir::ItemKind::Impl { polarity: hir::ImplPolarity::Negative(span), of_trait, .. } => {
1617 if is_rustc_reservation {
1618 let span = span.to(of_trait.as_ref().map(|t| t.path.span).unwrap_or(*span));
1619 tcx.sess.span_err(span, "reservation impls can't be negative");
1621 ty::ImplPolarity::Negative
1623 hir::ItemKind::Impl { polarity: hir::ImplPolarity::Positive, of_trait: None, .. } => {
1624 if is_rustc_reservation {
1625 tcx.sess.span_err(item.span, "reservation impls can't be inherent");
1627 ty::ImplPolarity::Positive
1629 hir::ItemKind::Impl {
1630 polarity: hir::ImplPolarity::Positive, of_trait: Some(_), ..
1632 if is_rustc_reservation {
1633 ty::ImplPolarity::Reservation
1635 ty::ImplPolarity::Positive
1638 ref item => bug!("impl_polarity: {:?} not an impl", item),
1642 /// Returns the early-bound lifetimes declared in this generics
1643 /// listing. For anything other than fns/methods, this is just all
1644 /// the lifetimes that are declared. For fns or methods, we have to
1645 /// screen out those that do not appear in any where-clauses etc using
1646 /// `resolve_lifetime::early_bound_lifetimes`.
1647 fn early_bound_lifetimes_from_generics<'a, 'tcx: 'a>(
1649 generics: &'a hir::Generics<'a>,
1650 ) -> impl Iterator<Item = &'a hir::GenericParam<'a>> + Captures<'tcx> {
1651 generics.params.iter().filter(move |param| match param.kind {
1652 GenericParamKind::Lifetime { .. } => !tcx.is_late_bound(param.hir_id),
1657 /// Returns a list of type predicates for the definition with ID `def_id`, including inferred
1658 /// lifetime constraints. This includes all predicates returned by `explicit_predicates_of`, plus
1659 /// inferred constraints concerning which regions outlive other regions.
1660 fn predicates_defined_on(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1661 debug!("predicates_defined_on({:?})", def_id);
1662 let mut result = tcx.explicit_predicates_of(def_id);
1663 debug!("predicates_defined_on: explicit_predicates_of({:?}) = {:?}", def_id, result,);
1664 let inferred_outlives = tcx.inferred_outlives_of(def_id);
1665 if !inferred_outlives.is_empty() {
1667 "predicates_defined_on: inferred_outlives_of({:?}) = {:?}",
1668 def_id, inferred_outlives,
1670 if result.predicates.is_empty() {
1671 result.predicates = inferred_outlives;
1673 result.predicates = tcx
1675 .alloc_from_iter(result.predicates.iter().chain(inferred_outlives).copied());
1678 debug!("predicates_defined_on({:?}) = {:?}", def_id, result);
1682 /// Returns a list of all type predicates (explicit and implicit) for the definition with
1683 /// ID `def_id`. This includes all predicates returned by `predicates_defined_on`, plus
1684 /// `Self: Trait` predicates for traits.
1685 fn predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1686 let mut result = tcx.predicates_defined_on(def_id);
1688 if tcx.is_trait(def_id) {
1689 // For traits, add `Self: Trait` predicate. This is
1690 // not part of the predicates that a user writes, but it
1691 // is something that one must prove in order to invoke a
1692 // method or project an associated type.
1694 // In the chalk setup, this predicate is not part of the
1695 // "predicates" for a trait item. But it is useful in
1696 // rustc because if you directly (e.g.) invoke a trait
1697 // method like `Trait::method(...)`, you must naturally
1698 // prove that the trait applies to the types that were
1699 // used, and adding the predicate into this list ensures
1700 // that this is done.
1701 let span = tcx.sess.source_map().guess_head_span(tcx.def_span(def_id));
1703 tcx.arena.alloc_from_iter(result.predicates.iter().copied().chain(std::iter::once((
1704 ty::TraitRef::identity(tcx, def_id).without_const().to_predicate(tcx),
1708 debug!("predicates_of(def_id={:?}) = {:?}", def_id, result);
1712 /// Returns a list of user-specified type predicates for the definition with ID `def_id`.
1713 /// N.B., this does not include any implied/inferred constraints.
1714 fn explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1717 debug!("explicit_predicates_of(def_id={:?})", def_id);
1719 /// A data structure with unique elements, which preserves order of insertion.
1720 /// Preserving the order of insertion is important here so as not to break
1721 /// compile-fail UI tests.
1722 struct UniquePredicates<'tcx> {
1723 predicates: FxIndexSet<(ty::Predicate<'tcx>, Span)>,
1726 impl<'tcx> UniquePredicates<'tcx> {
1728 UniquePredicates { predicates: FxIndexSet::default() }
1731 fn push(&mut self, value: (ty::Predicate<'tcx>, Span)) {
1732 self.predicates.insert(value);
1735 fn extend<I: IntoIterator<Item = (ty::Predicate<'tcx>, Span)>>(&mut self, iter: I) {
1742 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1743 let node = tcx.hir().get(hir_id);
1745 let mut is_trait = None;
1746 let mut is_default_impl_trait = None;
1747 let mut is_trait_associated_type = None;
1749 let icx = ItemCtxt::new(tcx, def_id);
1750 let constness = icx.default_constness_for_trait_bounds();
1752 const NO_GENERICS: &hir::Generics<'_> = &hir::Generics::empty();
1754 let mut predicates = UniquePredicates::new();
1756 let ast_generics = match node {
1757 Node::TraitItem(item) => {
1758 if let hir::TraitItemKind::Type(bounds, _) = item.kind {
1759 is_trait_associated_type = Some((bounds, item.span));
1764 Node::ImplItem(item) => &item.generics,
1766 Node::Item(item) => {
1768 ItemKind::Impl { defaultness, ref generics, .. } => {
1769 if defaultness.is_default() {
1770 is_default_impl_trait = tcx.impl_trait_ref(def_id);
1774 ItemKind::Fn(.., ref generics, _)
1775 | ItemKind::TyAlias(_, ref generics)
1776 | ItemKind::Enum(_, ref generics)
1777 | ItemKind::Struct(_, ref generics)
1778 | ItemKind::Union(_, ref generics) => generics,
1780 ItemKind::Trait(_, _, ref generics, .., items) => {
1781 is_trait = Some((ty::TraitRef::identity(tcx, def_id), items));
1784 ItemKind::TraitAlias(ref generics, _) => {
1785 is_trait = Some((ty::TraitRef::identity(tcx, def_id), &[]));
1788 ItemKind::OpaqueTy(OpaqueTy {
1794 let bounds_predicates = ty::print::with_no_queries(|| {
1795 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1796 let opaque_ty = tcx.mk_opaque(def_id, substs);
1798 // Collect the bounds, i.e., the `A + B + 'c` in `impl A + B + 'c`.
1799 let bounds = AstConv::compute_bounds(
1803 SizedByDefault::Yes,
1804 tcx.def_span(def_id),
1807 bounds.predicates(tcx, opaque_ty)
1809 if impl_trait_fn.is_some() {
1811 return ty::GenericPredicates {
1813 predicates: tcx.arena.alloc_from_iter(bounds_predicates),
1816 // named opaque types
1817 predicates.extend(bounds_predicates);
1826 Node::ForeignItem(item) => match item.kind {
1827 ForeignItemKind::Static(..) => NO_GENERICS,
1828 ForeignItemKind::Fn(_, _, ref generics) => generics,
1829 ForeignItemKind::Type => NO_GENERICS,
1835 let generics = tcx.generics_of(def_id);
1836 let parent_count = generics.parent_count as u32;
1837 let has_own_self = generics.has_self && parent_count == 0;
1839 // Below we'll consider the bounds on the type parameters (including `Self`)
1840 // and the explicit where-clauses, but to get the full set of predicates
1841 // on a trait we need to add in the supertrait bounds and bounds found on
1842 // associated types.
1843 if let Some((_trait_ref, _)) = is_trait {
1844 predicates.extend(tcx.super_predicates_of(def_id).predicates.iter().cloned());
1847 // In default impls, we can assume that the self type implements
1848 // the trait. So in:
1850 // default impl Foo for Bar { .. }
1852 // we add a default where clause `Foo: Bar`. We do a similar thing for traits
1853 // (see below). Recall that a default impl is not itself an impl, but rather a
1854 // set of defaults that can be incorporated into another impl.
1855 if let Some(trait_ref) = is_default_impl_trait {
1857 trait_ref.to_poly_trait_ref().without_const().to_predicate(tcx),
1858 tcx.def_span(def_id),
1862 // Collect the region predicates that were declared inline as
1863 // well. In the case of parameters declared on a fn or method, we
1864 // have to be careful to only iterate over early-bound regions.
1865 let mut index = parent_count + has_own_self as u32;
1866 for param in early_bound_lifetimes_from_generics(tcx, ast_generics) {
1867 let region = tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
1868 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
1870 name: param.name.ident().name,
1875 GenericParamKind::Lifetime { .. } => {
1876 param.bounds.iter().for_each(|bound| match bound {
1877 hir::GenericBound::Outlives(lt) => {
1878 let bound = AstConv::ast_region_to_region(&icx, <, None);
1879 let outlives = ty::Binder::bind(ty::OutlivesPredicate(region, bound));
1880 predicates.push((outlives.to_predicate(tcx), lt.span));
1889 // Collect the predicates that were written inline by the user on each
1890 // type parameter (e.g., `<T: Foo>`).
1891 for param in ast_generics.params {
1893 // We already dealt with early bound lifetimes above.
1894 GenericParamKind::Lifetime { .. } => (),
1895 GenericParamKind::Type { .. } => {
1896 let name = param.name.ident().name;
1897 let param_ty = ty::ParamTy::new(index, name).to_ty(tcx);
1900 let sized = SizedByDefault::Yes;
1902 AstConv::compute_bounds(&icx, param_ty, ¶m.bounds, sized, param.span);
1903 predicates.extend(bounds.predicates(tcx, param_ty));
1905 GenericParamKind::Const { .. } => {
1906 // Bounds on const parameters are currently not possible.
1907 debug_assert!(param.bounds.is_empty());
1913 // Add in the bounds that appear in the where-clause.
1914 let where_clause = &ast_generics.where_clause;
1915 for predicate in where_clause.predicates {
1917 &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
1918 let ty = icx.to_ty(&bound_pred.bounded_ty);
1920 // Keep the type around in a dummy predicate, in case of no bounds.
1921 // That way, `where Ty:` is not a complete noop (see #53696) and `Ty`
1922 // is still checked for WF.
1923 if bound_pred.bounds.is_empty() {
1924 if let ty::Param(_) = ty.kind {
1925 // This is a `where T:`, which can be in the HIR from the
1926 // transformation that moves `?Sized` to `T`'s declaration.
1927 // We can skip the predicate because type parameters are
1928 // trivially WF, but also we *should*, to avoid exposing
1929 // users who never wrote `where Type:,` themselves, to
1930 // compiler/tooling bugs from not handling WF predicates.
1932 let span = bound_pred.bounded_ty.span;
1933 let re_root_empty = tcx.lifetimes.re_root_empty;
1934 let predicate = ty::OutlivesPredicate(ty, re_root_empty);
1936 ty::PredicateAtom::TypeOutlives(predicate)
1937 .potentially_quantified(tcx, ty::PredicateKind::ForAll),
1943 for bound in bound_pred.bounds.iter() {
1945 &hir::GenericBound::Trait(ref poly_trait_ref, modifier) => {
1946 let constness = match modifier {
1947 hir::TraitBoundModifier::MaybeConst => hir::Constness::NotConst,
1948 hir::TraitBoundModifier::None => constness,
1949 hir::TraitBoundModifier::Maybe => bug!("this wasn't handled"),
1952 let mut bounds = Bounds::default();
1953 let _ = AstConv::instantiate_poly_trait_ref(
1960 predicates.extend(bounds.predicates(tcx, ty));
1963 &hir::GenericBound::LangItemTrait(lang_item, span, hir_id, args) => {
1964 let mut bounds = Bounds::default();
1965 AstConv::instantiate_lang_item_trait_ref(
1974 predicates.extend(bounds.predicates(tcx, ty));
1977 &hir::GenericBound::Outlives(ref lifetime) => {
1978 let region = AstConv::ast_region_to_region(&icx, lifetime, None);
1980 ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(ty, region))
1981 .potentially_quantified(tcx, ty::PredicateKind::ForAll),
1989 &hir::WherePredicate::RegionPredicate(ref region_pred) => {
1990 let r1 = AstConv::ast_region_to_region(&icx, ®ion_pred.lifetime, None);
1991 predicates.extend(region_pred.bounds.iter().map(|bound| {
1992 let (r2, span) = match bound {
1993 hir::GenericBound::Outlives(lt) => {
1994 (AstConv::ast_region_to_region(&icx, lt, None), lt.span)
1998 let pred = ty::PredicateAtom::RegionOutlives(ty::OutlivesPredicate(r1, r2));
2000 (pred.potentially_quantified(icx.tcx, ty::PredicateKind::ForAll), span)
2004 &hir::WherePredicate::EqPredicate(..) => {
2010 // Add predicates from associated type bounds (`type X: Bound`)
2011 if tcx.features().generic_associated_types {
2012 // New behavior: bounds declared on associate type are predicates of that
2013 // associated type. Not the default because it needs more testing.
2014 if let Some((bounds, span)) = is_trait_associated_type {
2016 tcx.mk_projection(def_id, InternalSubsts::identity_for_item(tcx, def_id));
2018 predicates.extend(associated_item_bounds(tcx, def_id, bounds, projection_ty, span))
2020 } else if let Some((self_trait_ref, trait_items)) = is_trait {
2021 // Current behavior: bounds declared on associate type are predicates
2022 // of its parent trait.
2023 predicates.extend(trait_items.iter().flat_map(|trait_item_ref| {
2024 trait_associated_item_predicates(tcx, def_id, self_trait_ref, trait_item_ref)
2028 let mut predicates: Vec<_> = predicates.predicates.into_iter().collect();
2030 // Subtle: before we store the predicates into the tcx, we
2031 // sort them so that predicates like `T: Foo<Item=U>` come
2032 // before uses of `U`. This avoids false ambiguity errors
2033 // in trait checking. See `setup_constraining_predicates`
2035 if let Node::Item(&Item { kind: ItemKind::Impl { .. }, .. }) = node {
2036 let self_ty = tcx.type_of(def_id);
2037 let trait_ref = tcx.impl_trait_ref(def_id);
2038 cgp::setup_constraining_predicates(
2042 &mut cgp::parameters_for_impl(self_ty, trait_ref),
2046 let result = ty::GenericPredicates {
2047 parent: generics.parent,
2048 predicates: tcx.arena.alloc_from_iter(predicates),
2050 debug!("explicit_predicates_of(def_id={:?}) = {:?}", def_id, result);
2054 fn trait_associated_item_predicates(
2057 self_trait_ref: ty::TraitRef<'tcx>,
2058 trait_item_ref: &hir::TraitItemRef,
2059 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2060 let trait_item = tcx.hir().trait_item(trait_item_ref.id);
2061 let item_def_id = tcx.hir().local_def_id(trait_item_ref.id.hir_id);
2062 let bounds = match trait_item.kind {
2063 hir::TraitItemKind::Type(ref bounds, _) => bounds,
2064 _ => return Vec::new(),
2067 if !tcx.generics_of(item_def_id).params.is_empty() {
2068 // For GATs the substs provided to the mk_projection call below are
2069 // wrong. We should emit a feature gate error if we get here so skip
2071 tcx.sess.delay_span_bug(trait_item.span, "gats used without feature gate");
2075 let assoc_ty = tcx.mk_projection(
2076 tcx.hir().local_def_id(trait_item.hir_id).to_def_id(),
2077 self_trait_ref.substs,
2080 associated_item_bounds(tcx, def_id, bounds, assoc_ty, trait_item.span)
2083 fn associated_item_bounds(
2086 bounds: &'tcx [hir::GenericBound<'tcx>],
2087 projection_ty: Ty<'tcx>,
2089 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2090 let bounds = AstConv::compute_bounds(
2091 &ItemCtxt::new(tcx, def_id),
2094 SizedByDefault::Yes,
2098 let predicates = bounds.predicates(tcx, projection_ty);
2103 /// Converts a specific `GenericBound` from the AST into a set of
2104 /// predicates that apply to the self type. A vector is returned
2105 /// because this can be anywhere from zero predicates (`T: ?Sized` adds no
2106 /// predicates) to one (`T: Foo`) to many (`T: Bar<X = i32>` adds `T: Bar`
2107 /// and `<T as Bar>::X == i32`).
2108 fn predicates_from_bound<'tcx>(
2109 astconv: &dyn AstConv<'tcx>,
2111 bound: &'tcx hir::GenericBound<'tcx>,
2112 constness: hir::Constness,
2113 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2115 hir::GenericBound::Trait(ref tr, modifier) => {
2116 let constness = match modifier {
2117 hir::TraitBoundModifier::Maybe => return vec![],
2118 hir::TraitBoundModifier::MaybeConst => hir::Constness::NotConst,
2119 hir::TraitBoundModifier::None => constness,
2122 let mut bounds = Bounds::default();
2123 let _ = astconv.instantiate_poly_trait_ref(tr, constness, param_ty, &mut bounds);
2124 bounds.predicates(astconv.tcx(), param_ty)
2126 hir::GenericBound::LangItemTrait(lang_item, span, hir_id, args) => {
2127 let mut bounds = Bounds::default();
2128 astconv.instantiate_lang_item_trait_ref(
2136 bounds.predicates(astconv.tcx(), param_ty)
2138 hir::GenericBound::Outlives(ref lifetime) => {
2139 let region = astconv.ast_region_to_region(lifetime, None);
2140 let pred = ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(param_ty, region))
2141 .potentially_quantified(astconv.tcx(), ty::PredicateKind::ForAll);
2142 vec![(pred, lifetime.span)]
2147 fn compute_sig_of_foreign_fn_decl<'tcx>(
2150 decl: &'tcx hir::FnDecl<'tcx>,
2153 ) -> ty::PolyFnSig<'tcx> {
2154 let unsafety = if abi == abi::Abi::RustIntrinsic {
2155 intrinsic_operation_unsafety(tcx.item_name(def_id))
2157 hir::Unsafety::Unsafe
2159 let fty = AstConv::ty_of_fn(
2160 &ItemCtxt::new(tcx, def_id),
2164 &hir::Generics::empty(),
2168 // Feature gate SIMD types in FFI, since I am not sure that the
2169 // ABIs are handled at all correctly. -huonw
2170 if abi != abi::Abi::RustIntrinsic
2171 && abi != abi::Abi::PlatformIntrinsic
2172 && !tcx.features().simd_ffi
2174 let check = |ast_ty: &hir::Ty<'_>, ty: Ty<'_>| {
2179 .span_to_snippet(ast_ty.span)
2180 .map_or(String::new(), |s| format!(" `{}`", s));
2185 "use of SIMD type{} in FFI is highly experimental and \
2186 may result in invalid code",
2190 .help("add `#![feature(simd_ffi)]` to the crate attributes to enable")
2194 for (input, ty) in decl.inputs.iter().zip(fty.inputs().skip_binder()) {
2197 if let hir::FnRetTy::Return(ref ty) = decl.output {
2198 check(&ty, fty.output().skip_binder())
2205 fn is_foreign_item(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
2206 match tcx.hir().get_if_local(def_id) {
2207 Some(Node::ForeignItem(..)) => true,
2209 _ => bug!("is_foreign_item applied to non-local def-id {:?}", def_id),
2213 fn static_mutability(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::Mutability> {
2214 match tcx.hir().get_if_local(def_id) {
2216 Node::Item(&hir::Item { kind: hir::ItemKind::Static(_, mutbl, _), .. })
2217 | Node::ForeignItem(&hir::ForeignItem {
2218 kind: hir::ForeignItemKind::Static(_, mutbl),
2223 _ => bug!("static_mutability applied to non-local def-id {:?}", def_id),
2227 fn generator_kind(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::GeneratorKind> {
2228 match tcx.hir().get_if_local(def_id) {
2229 Some(Node::Expr(&rustc_hir::Expr {
2230 kind: rustc_hir::ExprKind::Closure(_, _, body_id, _, _),
2232 })) => tcx.hir().body(body_id).generator_kind(),
2234 _ => bug!("generator_kind applied to non-local def-id {:?}", def_id),
2238 fn from_target_feature(
2241 attr: &ast::Attribute,
2242 supported_target_features: &FxHashMap<String, Option<Symbol>>,
2243 target_features: &mut Vec<Symbol>,
2245 let list = match attr.meta_item_list() {
2249 let bad_item = |span| {
2250 let msg = "malformed `target_feature` attribute input";
2251 let code = "enable = \"..\"".to_owned();
2253 .struct_span_err(span, &msg)
2254 .span_suggestion(span, "must be of the form", code, Applicability::HasPlaceholders)
2257 let rust_features = tcx.features();
2259 // Only `enable = ...` is accepted in the meta-item list.
2260 if !item.has_name(sym::enable) {
2261 bad_item(item.span());
2265 // Must be of the form `enable = "..."` (a string).
2266 let value = match item.value_str() {
2267 Some(value) => value,
2269 bad_item(item.span());
2274 // We allow comma separation to enable multiple features.
2275 target_features.extend(value.as_str().split(',').filter_map(|feature| {
2276 let feature_gate = match supported_target_features.get(feature) {
2280 format!("the feature named `{}` is not valid for this target", feature);
2281 let mut err = tcx.sess.struct_span_err(item.span(), &msg);
2284 format!("`{}` is not valid for this target", feature),
2286 if feature.starts_with('+') {
2287 let valid = supported_target_features.contains_key(&feature[1..]);
2289 err.help("consider removing the leading `+` in the feature name");
2297 // Only allow features whose feature gates have been enabled.
2298 let allowed = match feature_gate.as_ref().copied() {
2299 Some(sym::arm_target_feature) => rust_features.arm_target_feature,
2300 Some(sym::aarch64_target_feature) => rust_features.aarch64_target_feature,
2301 Some(sym::hexagon_target_feature) => rust_features.hexagon_target_feature,
2302 Some(sym::powerpc_target_feature) => rust_features.powerpc_target_feature,
2303 Some(sym::mips_target_feature) => rust_features.mips_target_feature,
2304 Some(sym::riscv_target_feature) => rust_features.riscv_target_feature,
2305 Some(sym::avx512_target_feature) => rust_features.avx512_target_feature,
2306 Some(sym::mmx_target_feature) => rust_features.mmx_target_feature,
2307 Some(sym::sse4a_target_feature) => rust_features.sse4a_target_feature,
2308 Some(sym::tbm_target_feature) => rust_features.tbm_target_feature,
2309 Some(sym::wasm_target_feature) => rust_features.wasm_target_feature,
2310 Some(sym::cmpxchg16b_target_feature) => rust_features.cmpxchg16b_target_feature,
2311 Some(sym::adx_target_feature) => rust_features.adx_target_feature,
2312 Some(sym::movbe_target_feature) => rust_features.movbe_target_feature,
2313 Some(sym::rtm_target_feature) => rust_features.rtm_target_feature,
2314 Some(sym::f16c_target_feature) => rust_features.f16c_target_feature,
2315 Some(name) => bug!("unknown target feature gate {}", name),
2318 if !allowed && id.is_local() {
2320 &tcx.sess.parse_sess,
2321 feature_gate.unwrap(),
2323 &format!("the target feature `{}` is currently unstable", feature),
2327 Some(Symbol::intern(feature))
2332 fn linkage_by_name(tcx: TyCtxt<'_>, def_id: DefId, name: &str) -> Linkage {
2333 use rustc_middle::mir::mono::Linkage::*;
2335 // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
2336 // applicable to variable declarations and may not really make sense for
2337 // Rust code in the first place but allow them anyway and trust that the
2338 // user knows what s/he's doing. Who knows, unanticipated use cases may pop
2339 // up in the future.
2341 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
2342 // and don't have to be, LLVM treats them as no-ops.
2344 "appending" => Appending,
2345 "available_externally" => AvailableExternally,
2347 "extern_weak" => ExternalWeak,
2348 "external" => External,
2349 "internal" => Internal,
2350 "linkonce" => LinkOnceAny,
2351 "linkonce_odr" => LinkOnceODR,
2352 "private" => Private,
2354 "weak_odr" => WeakODR,
2356 let span = tcx.hir().span_if_local(def_id);
2357 if let Some(span) = span {
2358 tcx.sess.span_fatal(span, "invalid linkage specified")
2360 tcx.sess.fatal(&format!("invalid linkage specified: {}", name))
2366 fn codegen_fn_attrs(tcx: TyCtxt<'_>, id: DefId) -> CodegenFnAttrs {
2367 let attrs = tcx.get_attrs(id);
2369 let mut codegen_fn_attrs = CodegenFnAttrs::new();
2370 if should_inherit_track_caller(tcx, id) {
2371 codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
2374 let supported_target_features = tcx.supported_target_features(LOCAL_CRATE);
2376 let mut inline_span = None;
2377 let mut link_ordinal_span = None;
2378 let mut no_sanitize_span = None;
2379 for attr in attrs.iter() {
2380 if tcx.sess.check_name(attr, sym::cold) {
2381 codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD;
2382 } else if tcx.sess.check_name(attr, sym::rustc_allocator) {
2383 codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR;
2384 } else if tcx.sess.check_name(attr, sym::unwind) {
2385 codegen_fn_attrs.flags |= CodegenFnAttrFlags::UNWIND;
2386 } else if tcx.sess.check_name(attr, sym::ffi_returns_twice) {
2387 if tcx.is_foreign_item(id) {
2388 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_RETURNS_TWICE;
2390 // `#[ffi_returns_twice]` is only allowed `extern fn`s.
2395 "`#[ffi_returns_twice]` may only be used on foreign functions"
2399 } else if tcx.sess.check_name(attr, sym::ffi_pure) {
2400 if tcx.is_foreign_item(id) {
2401 if attrs.iter().any(|a| tcx.sess.check_name(a, sym::ffi_const)) {
2402 // `#[ffi_const]` functions cannot be `#[ffi_pure]`
2407 "`#[ffi_const]` function cannot be `#[ffi_pure]`"
2411 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_PURE;
2414 // `#[ffi_pure]` is only allowed on foreign functions
2419 "`#[ffi_pure]` may only be used on foreign functions"
2423 } else if tcx.sess.check_name(attr, sym::ffi_const) {
2424 if tcx.is_foreign_item(id) {
2425 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_CONST;
2427 // `#[ffi_const]` is only allowed on foreign functions
2432 "`#[ffi_const]` may only be used on foreign functions"
2436 } else if tcx.sess.check_name(attr, sym::rustc_allocator_nounwind) {
2437 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND;
2438 } else if tcx.sess.check_name(attr, sym::naked) {
2439 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED;
2440 } else if tcx.sess.check_name(attr, sym::no_mangle) {
2441 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2442 } else if tcx.sess.check_name(attr, sym::rustc_std_internal_symbol) {
2443 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2444 } else if tcx.sess.check_name(attr, sym::used) {
2445 codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED;
2446 } else if tcx.sess.check_name(attr, sym::thread_local) {
2447 codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL;
2448 } else if tcx.sess.check_name(attr, sym::track_caller) {
2449 if tcx.is_closure(id) || tcx.fn_sig(id).abi() != abi::Abi::Rust {
2450 struct_span_err!(tcx.sess, attr.span, E0737, "`#[track_caller]` requires Rust ABI")
2453 codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
2454 } else if tcx.sess.check_name(attr, sym::export_name) {
2455 if let Some(s) = attr.value_str() {
2456 if s.as_str().contains('\0') {
2457 // `#[export_name = ...]` will be converted to a null-terminated string,
2458 // so it may not contain any null characters.
2463 "`export_name` may not contain null characters"
2467 codegen_fn_attrs.export_name = Some(s);
2469 } else if tcx.sess.check_name(attr, sym::target_feature) {
2470 if !tcx.features().target_feature_11 {
2471 check_target_feature_safe_fn(tcx, id, attr.span);
2472 } else if let Some(local_id) = id.as_local() {
2473 if tcx.fn_sig(id).unsafety() == hir::Unsafety::Normal {
2474 check_target_feature_trait_unsafe(tcx, local_id, attr.span);
2477 from_target_feature(
2481 &supported_target_features,
2482 &mut codegen_fn_attrs.target_features,
2484 } else if tcx.sess.check_name(attr, sym::linkage) {
2485 if let Some(val) = attr.value_str() {
2486 codegen_fn_attrs.linkage = Some(linkage_by_name(tcx, id, &val.as_str()));
2488 } else if tcx.sess.check_name(attr, sym::link_section) {
2489 if let Some(val) = attr.value_str() {
2490 if val.as_str().bytes().any(|b| b == 0) {
2492 "illegal null byte in link_section \
2496 tcx.sess.span_err(attr.span, &msg);
2498 codegen_fn_attrs.link_section = Some(val);
2501 } else if tcx.sess.check_name(attr, sym::link_name) {
2502 codegen_fn_attrs.link_name = attr.value_str();
2503 } else if tcx.sess.check_name(attr, sym::link_ordinal) {
2504 link_ordinal_span = Some(attr.span);
2505 if let ordinal @ Some(_) = check_link_ordinal(tcx, attr) {
2506 codegen_fn_attrs.link_ordinal = ordinal;
2508 } else if tcx.sess.check_name(attr, sym::no_sanitize) {
2509 no_sanitize_span = Some(attr.span);
2510 if let Some(list) = attr.meta_item_list() {
2511 for item in list.iter() {
2512 if item.has_name(sym::address) {
2513 codegen_fn_attrs.no_sanitize |= SanitizerSet::ADDRESS;
2514 } else if item.has_name(sym::memory) {
2515 codegen_fn_attrs.no_sanitize |= SanitizerSet::MEMORY;
2516 } else if item.has_name(sym::thread) {
2517 codegen_fn_attrs.no_sanitize |= SanitizerSet::THREAD;
2520 .struct_span_err(item.span(), "invalid argument for `no_sanitize`")
2521 .note("expected one of: `address`, `memory` or `thread`")
2529 codegen_fn_attrs.inline = attrs.iter().fold(InlineAttr::None, |ia, attr| {
2530 if !attr.has_name(sym::inline) {
2533 match attr.meta().map(|i| i.kind) {
2534 Some(MetaItemKind::Word) => {
2535 tcx.sess.mark_attr_used(attr);
2538 Some(MetaItemKind::List(ref items)) => {
2539 tcx.sess.mark_attr_used(attr);
2540 inline_span = Some(attr.span);
2541 if items.len() != 1 {
2543 tcx.sess.diagnostic(),
2546 "expected one argument"
2550 } else if list_contains_name(&items[..], sym::always) {
2552 } else if list_contains_name(&items[..], sym::never) {
2556 tcx.sess.diagnostic(),
2566 Some(MetaItemKind::NameValue(_)) => ia,
2571 codegen_fn_attrs.optimize = attrs.iter().fold(OptimizeAttr::None, |ia, attr| {
2572 if !attr.has_name(sym::optimize) {
2575 let err = |sp, s| struct_span_err!(tcx.sess.diagnostic(), sp, E0722, "{}", s).emit();
2576 match attr.meta().map(|i| i.kind) {
2577 Some(MetaItemKind::Word) => {
2578 err(attr.span, "expected one argument");
2581 Some(MetaItemKind::List(ref items)) => {
2582 tcx.sess.mark_attr_used(attr);
2583 inline_span = Some(attr.span);
2584 if items.len() != 1 {
2585 err(attr.span, "expected one argument");
2587 } else if list_contains_name(&items[..], sym::size) {
2589 } else if list_contains_name(&items[..], sym::speed) {
2592 err(items[0].span(), "invalid argument");
2596 Some(MetaItemKind::NameValue(_)) => ia,
2601 // If a function uses #[target_feature] it can't be inlined into general
2602 // purpose functions as they wouldn't have the right target features
2603 // enabled. For that reason we also forbid #[inline(always)] as it can't be
2605 if !codegen_fn_attrs.target_features.is_empty() {
2606 if codegen_fn_attrs.inline == InlineAttr::Always {
2607 if let Some(span) = inline_span {
2610 "cannot use `#[inline(always)]` with \
2611 `#[target_feature]`",
2617 if !codegen_fn_attrs.no_sanitize.is_empty() {
2618 if codegen_fn_attrs.inline == InlineAttr::Always {
2619 if let (Some(no_sanitize_span), Some(inline_span)) = (no_sanitize_span, inline_span) {
2620 let hir_id = tcx.hir().local_def_id_to_hir_id(id.expect_local());
2621 tcx.struct_span_lint_hir(
2622 lint::builtin::INLINE_NO_SANITIZE,
2626 lint.build("`no_sanitize` will have no effect after inlining")
2627 .span_note(inline_span, "inlining requested here")
2635 // Weak lang items have the same semantics as "std internal" symbols in the
2636 // sense that they're preserved through all our LTO passes and only
2637 // strippable by the linker.
2639 // Additionally weak lang items have predetermined symbol names.
2640 if tcx.is_weak_lang_item(id) {
2641 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2643 let check_name = |attr, sym| tcx.sess.check_name(attr, sym);
2644 if let Some(name) = weak_lang_items::link_name(check_name, &attrs) {
2645 codegen_fn_attrs.export_name = Some(name);
2646 codegen_fn_attrs.link_name = Some(name);
2648 check_link_name_xor_ordinal(tcx, &codegen_fn_attrs, link_ordinal_span);
2650 // Internal symbols to the standard library all have no_mangle semantics in
2651 // that they have defined symbol names present in the function name. This
2652 // also applies to weak symbols where they all have known symbol names.
2653 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
2654 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2660 /// Checks if the provided DefId is a method in a trait impl for a trait which has track_caller
2661 /// applied to the method prototype.
2662 fn should_inherit_track_caller(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
2663 if let Some(impl_item) = tcx.opt_associated_item(def_id) {
2664 if let ty::AssocItemContainer::ImplContainer(impl_def_id) = impl_item.container {
2665 if let Some(trait_def_id) = tcx.trait_id_of_impl(impl_def_id) {
2666 if let Some(trait_item) = tcx
2667 .associated_items(trait_def_id)
2668 .filter_by_name_unhygienic(impl_item.ident.name)
2669 .find(move |trait_item| {
2670 trait_item.kind == ty::AssocKind::Fn
2671 && tcx.hygienic_eq(impl_item.ident, trait_item.ident, trait_def_id)
2675 .codegen_fn_attrs(trait_item.def_id)
2677 .intersects(CodegenFnAttrFlags::TRACK_CALLER);
2686 fn check_link_ordinal(tcx: TyCtxt<'_>, attr: &ast::Attribute) -> Option<usize> {
2687 use rustc_ast::{Lit, LitIntType, LitKind};
2688 let meta_item_list = attr.meta_item_list();
2689 let meta_item_list: Option<&[ast::NestedMetaItem]> = meta_item_list.as_ref().map(Vec::as_ref);
2690 let sole_meta_list = match meta_item_list {
2691 Some([item]) => item.literal(),
2694 if let Some(Lit { kind: LitKind::Int(ordinal, LitIntType::Unsuffixed), .. }) = sole_meta_list {
2695 if *ordinal <= usize::MAX as u128 {
2696 Some(*ordinal as usize)
2698 let msg = format!("ordinal value in `link_ordinal` is too large: `{}`", &ordinal);
2700 .struct_span_err(attr.span, &msg)
2701 .note("the value may not exceed `usize::MAX`")
2707 .struct_span_err(attr.span, "illegal ordinal format in `link_ordinal`")
2708 .note("an unsuffixed integer value, e.g., `1`, is expected")
2714 fn check_link_name_xor_ordinal(
2716 codegen_fn_attrs: &CodegenFnAttrs,
2717 inline_span: Option<Span>,
2719 if codegen_fn_attrs.link_name.is_none() || codegen_fn_attrs.link_ordinal.is_none() {
2722 let msg = "cannot use `#[link_name]` with `#[link_ordinal]`";
2723 if let Some(span) = inline_span {
2724 tcx.sess.span_err(span, msg);
2730 /// Checks the function annotated with `#[target_feature]` is unsafe,
2731 /// reporting an error if it isn't.
2732 fn check_target_feature_safe_fn(tcx: TyCtxt<'_>, id: DefId, attr_span: Span) {
2733 if tcx.is_closure(id) || tcx.fn_sig(id).unsafety() == hir::Unsafety::Normal {
2734 let mut err = feature_err(
2735 &tcx.sess.parse_sess,
2736 sym::target_feature_11,
2738 "`#[target_feature(..)]` can only be applied to `unsafe` functions",
2740 err.span_label(tcx.def_span(id), "not an `unsafe` function");
2745 /// Checks the function annotated with `#[target_feature]` is not a safe
2746 /// trait method implementation, reporting an error if it is.
2747 fn check_target_feature_trait_unsafe(tcx: TyCtxt<'_>, id: LocalDefId, attr_span: Span) {
2748 let hir_id = tcx.hir().local_def_id_to_hir_id(id);
2749 let node = tcx.hir().get(hir_id);
2750 if let Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }) = node {
2751 let parent_id = tcx.hir().get_parent_item(hir_id);
2752 let parent_item = tcx.hir().expect_item(parent_id);
2753 if let hir::ItemKind::Impl { of_trait: Some(_), .. } = parent_item.kind {
2757 "`#[target_feature(..)]` cannot be applied to safe trait method",
2759 .span_label(attr_span, "cannot be applied to safe trait method")
2760 .span_label(tcx.def_span(id), "not an `unsafe` function")