1 //! "Collection" is the process of determining the type and other external
2 //! details of each item in Rust. Collection is specifically concerned
3 //! with *inter-procedural* things -- for example, for a function
4 //! definition, collection will figure out the type and signature of the
5 //! function, but it will not visit the *body* of the function in any way,
6 //! nor examine type annotations on local variables (that's the job of
9 //! Collecting is ultimately defined by a bundle of queries that
10 //! inquire after various facts about the items in the crate (e.g.,
11 //! `type_of`, `generics_of`, `predicates_of`, etc). See the `provide` function
14 //! At present, however, we do run collection across all items in the
15 //! crate as a kind of pass. This should eventually be factored away.
17 use crate::astconv::{AstConv, Bounds, SizedByDefault};
18 use crate::check::intrinsic::intrinsic_operation_unsafety;
19 use crate::constrained_generic_params as cgp;
20 use crate::middle::resolve_lifetime as rl;
22 use rustc_ast::ast::MetaItemKind;
23 use rustc_attr::{list_contains_name, mark_used, InlineAttr, OptimizeAttr};
24 use rustc_data_structures::captures::Captures;
25 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
26 use rustc_errors::{struct_span_err, Applicability};
28 use rustc_hir::def::{CtorKind, DefKind, Res};
29 use rustc_hir::def_id::{DefId, LocalDefId, LOCAL_CRATE};
30 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
31 use rustc_hir::weak_lang_items;
32 use rustc_hir::{GenericParamKind, HirId, Node};
33 use rustc_middle::hir::map::blocks::FnLikeNode;
34 use rustc_middle::hir::map::Map;
35 use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
36 use rustc_middle::mir::mono::Linkage;
37 use rustc_middle::ty::query::Providers;
38 use rustc_middle::ty::subst::InternalSubsts;
39 use rustc_middle::ty::util::Discr;
40 use rustc_middle::ty::util::IntTypeExt;
41 use rustc_middle::ty::{self, AdtKind, Const, ToPolyTraitRef, Ty, TyCtxt};
42 use rustc_middle::ty::{ReprOptions, ToPredicate, WithConstness};
43 use rustc_session::config::SanitizerSet;
44 use rustc_session::lint;
45 use rustc_session::parse::feature_err;
46 use rustc_span::symbol::{kw, sym, Ident, Symbol};
47 use rustc_span::{Span, DUMMY_SP};
48 use rustc_target::spec::abi;
49 use rustc_trait_selection::traits::error_reporting::suggestions::NextTypeParamName;
53 struct OnlySelfBounds(bool);
55 ///////////////////////////////////////////////////////////////////////////
58 fn collect_mod_item_types(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
59 tcx.hir().visit_item_likes_in_module(
61 &mut CollectItemTypesVisitor { tcx }.as_deep_visitor(),
65 pub fn provide(providers: &mut Providers) {
66 *providers = Providers {
67 opt_const_param_of: type_of::opt_const_param_of,
68 type_of: type_of::type_of,
71 predicates_defined_on,
72 explicit_predicates_of,
74 type_param_predicates,
84 collect_mod_item_types,
89 ///////////////////////////////////////////////////////////////////////////
91 /// Context specific to some particular item. This is what implements
92 /// `AstConv`. It has information about the predicates that are defined
93 /// on the trait. Unfortunately, this predicate information is
94 /// available in various different forms at various points in the
95 /// process. So we can't just store a pointer to e.g., the AST or the
96 /// parsed ty form, we have to be more flexible. To this end, the
97 /// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy
98 /// `get_type_parameter_bounds` requests, drawing the information from
99 /// the AST (`hir::Generics`), recursively.
100 pub struct ItemCtxt<'tcx> {
105 ///////////////////////////////////////////////////////////////////////////
108 crate struct PlaceholderHirTyCollector(crate Vec<Span>);
110 impl<'v> Visitor<'v> for PlaceholderHirTyCollector {
111 type Map = intravisit::ErasedMap<'v>;
113 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
114 NestedVisitorMap::None
116 fn visit_ty(&mut self, t: &'v hir::Ty<'v>) {
117 if let hir::TyKind::Infer = t.kind {
120 intravisit::walk_ty(self, t)
124 struct CollectItemTypesVisitor<'tcx> {
128 /// If there are any placeholder types (`_`), emit an error explaining that this is not allowed
129 /// and suggest adding type parameters in the appropriate place, taking into consideration any and
130 /// all already existing generic type parameters to avoid suggesting a name that is already in use.
131 crate fn placeholder_type_error(
134 generics: &[hir::GenericParam<'_>],
135 placeholder_types: Vec<Span>,
138 if placeholder_types.is_empty() {
142 let type_name = generics.next_type_param_name(None);
143 let mut sugg: Vec<_> =
144 placeholder_types.iter().map(|sp| (*sp, (*type_name).to_string())).collect();
146 if generics.is_empty() {
147 if let Some(span) = span {
148 sugg.push((span, format!("<{}>", type_name)));
150 } else if let Some(arg) = generics.iter().find(|arg| match arg.name {
151 hir::ParamName::Plain(Ident { name: kw::Underscore, .. }) => true,
154 // Account for `_` already present in cases like `struct S<_>(_);` and suggest
155 // `struct S<T>(T);` instead of `struct S<_, T>(T);`.
156 sugg.push((arg.span, (*type_name).to_string()));
158 let last = generics.iter().last().unwrap();
160 // Account for bounds, we want `fn foo<T: E, K>(_: K)` not `fn foo<T, K: E>(_: K)`.
161 last.bounds_span().unwrap_or(last.span).shrink_to_hi(),
162 format!(", {}", type_name),
166 let mut err = bad_placeholder_type(tcx, placeholder_types);
168 err.multipart_suggestion(
169 "use type parameters instead",
171 Applicability::HasPlaceholders,
177 fn reject_placeholder_type_signatures_in_item(tcx: TyCtxt<'tcx>, item: &'tcx hir::Item<'tcx>) {
178 let (generics, suggest) = match &item.kind {
179 hir::ItemKind::Union(_, generics)
180 | hir::ItemKind::Enum(_, generics)
181 | hir::ItemKind::TraitAlias(generics, _)
182 | hir::ItemKind::Trait(_, _, generics, ..)
183 | hir::ItemKind::Impl { generics, .. }
184 | hir::ItemKind::Struct(_, generics) => (generics, true),
185 hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. })
186 | hir::ItemKind::TyAlias(_, generics) => (generics, false),
187 // `static`, `fn` and `const` are handled elsewhere to suggest appropriate type.
191 let mut visitor = PlaceholderHirTyCollector::default();
192 visitor.visit_item(item);
194 placeholder_type_error(tcx, Some(generics.span), &generics.params[..], visitor.0, suggest);
197 impl Visitor<'tcx> for CollectItemTypesVisitor<'tcx> {
198 type Map = Map<'tcx>;
200 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
201 NestedVisitorMap::OnlyBodies(self.tcx.hir())
204 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
205 convert_item(self.tcx, item.hir_id);
206 reject_placeholder_type_signatures_in_item(self.tcx, item);
207 intravisit::walk_item(self, item);
210 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
211 for param in generics.params {
213 hir::GenericParamKind::Lifetime { .. } => {}
214 hir::GenericParamKind::Type { default: Some(_), .. } => {
215 let def_id = self.tcx.hir().local_def_id(param.hir_id);
216 self.tcx.ensure().type_of(def_id);
218 hir::GenericParamKind::Type { .. } => {}
219 hir::GenericParamKind::Const { .. } => {
220 let def_id = self.tcx.hir().local_def_id(param.hir_id);
221 self.tcx.ensure().type_of(def_id);
225 intravisit::walk_generics(self, generics);
228 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
229 if let hir::ExprKind::Closure(..) = expr.kind {
230 let def_id = self.tcx.hir().local_def_id(expr.hir_id);
231 self.tcx.ensure().generics_of(def_id);
232 self.tcx.ensure().type_of(def_id);
234 intravisit::walk_expr(self, expr);
237 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
238 convert_trait_item(self.tcx, trait_item.hir_id);
239 intravisit::walk_trait_item(self, trait_item);
242 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
243 convert_impl_item(self.tcx, impl_item.hir_id);
244 intravisit::walk_impl_item(self, impl_item);
248 ///////////////////////////////////////////////////////////////////////////
249 // Utility types and common code for the above passes.
251 fn bad_placeholder_type(
253 mut spans: Vec<Span>,
254 ) -> rustc_errors::DiagnosticBuilder<'tcx> {
256 let mut err = struct_span_err!(
260 "the type placeholder `_` is not allowed within types on item signatures",
263 err.span_label(span, "not allowed in type signatures");
268 impl ItemCtxt<'tcx> {
269 pub fn new(tcx: TyCtxt<'tcx>, item_def_id: DefId) -> ItemCtxt<'tcx> {
270 ItemCtxt { tcx, item_def_id }
273 pub fn to_ty(&self, ast_ty: &'tcx hir::Ty<'tcx>) -> Ty<'tcx> {
274 AstConv::ast_ty_to_ty(self, ast_ty)
277 pub fn hir_id(&self) -> hir::HirId {
278 self.tcx.hir().as_local_hir_id(self.item_def_id.expect_local())
281 pub fn node(&self) -> hir::Node<'tcx> {
282 self.tcx.hir().get(self.hir_id())
286 impl AstConv<'tcx> for ItemCtxt<'tcx> {
287 fn tcx(&self) -> TyCtxt<'tcx> {
291 fn item_def_id(&self) -> Option<DefId> {
292 Some(self.item_def_id)
295 fn default_constness_for_trait_bounds(&self) -> hir::Constness {
296 if let Some(fn_like) = FnLikeNode::from_node(self.node()) {
299 hir::Constness::NotConst
303 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId) -> ty::GenericPredicates<'tcx> {
304 self.tcx.at(span).type_param_predicates((self.item_def_id, def_id.expect_local()))
307 fn re_infer(&self, _: Option<&ty::GenericParamDef>, _: Span) -> Option<ty::Region<'tcx>> {
311 fn allow_ty_infer(&self) -> bool {
315 fn ty_infer(&self, _: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx> {
316 self.tcx().ty_error_with_message(span, "bad_placeholder_type")
322 _: Option<&ty::GenericParamDef>,
324 ) -> &'tcx Const<'tcx> {
325 bad_placeholder_type(self.tcx(), vec![span]).emit();
326 self.tcx().const_error(ty)
329 fn projected_ty_from_poly_trait_ref(
333 item_segment: &hir::PathSegment<'_>,
334 poly_trait_ref: ty::PolyTraitRef<'tcx>,
336 if let Some(trait_ref) = poly_trait_ref.no_bound_vars() {
337 let item_substs = <dyn AstConv<'tcx>>::create_substs_for_associated_item(
345 self.tcx().mk_projection(item_def_id, item_substs)
347 // There are no late-bound regions; we can just ignore the binder.
348 let mut err = struct_span_err!(
352 "cannot extract an associated type from a higher-ranked trait bound \
357 hir::Node::Field(_) | hir::Node::Ctor(_) | hir::Node::Variant(_) => {
359 self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(self.hir_id()));
361 hir::ItemKind::Enum(_, generics)
362 | hir::ItemKind::Struct(_, generics)
363 | hir::ItemKind::Union(_, generics) => {
364 let lt_name = get_new_lifetime_name(self.tcx, poly_trait_ref, generics);
365 let (lt_sp, sugg) = match &generics.params[..] {
366 [] => (generics.span, format!("<{}>", lt_name)),
368 (bound.span.shrink_to_lo(), format!("{}, ", lt_name))
371 let suggestions = vec![
377 // Replace the existing lifetimes with a new named lifetime.
379 .replace_late_bound_regions(&poly_trait_ref, |_| {
380 self.tcx.mk_region(ty::ReEarlyBound(
381 ty::EarlyBoundRegion {
384 name: Symbol::intern(<_name),
393 err.multipart_suggestion(
394 "use a fully qualified path with explicit lifetimes",
396 Applicability::MaybeIncorrect,
402 hir::Node::Item(hir::Item {
404 hir::ItemKind::Struct(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Union(..),
408 | hir::Node::ForeignItem(_)
409 | hir::Node::TraitItem(_)
410 | hir::Node::ImplItem(_) => {
413 "use a fully qualified path with inferred lifetimes",
416 // Erase named lt, we want `<A as B<'_>::C`, not `<A as B<'a>::C`.
417 self.tcx.anonymize_late_bound_regions(&poly_trait_ref).skip_binder(),
420 Applicability::MaybeIncorrect,
426 self.tcx().ty_error()
430 fn normalize_ty(&self, _span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
431 // Types in item signatures are not normalized to avoid undue dependencies.
435 fn set_tainted_by_errors(&self) {
436 // There's no obvious place to track this, so just let it go.
439 fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) {
440 // There's no place to record types from signatures?
444 /// Synthesize a new lifetime name that doesn't clash with any of the lifetimes already present.
445 fn get_new_lifetime_name<'tcx>(
447 poly_trait_ref: ty::PolyTraitRef<'tcx>,
448 generics: &hir::Generics<'tcx>,
450 let existing_lifetimes = tcx
451 .collect_referenced_late_bound_regions(&poly_trait_ref)
454 if let ty::BoundRegion::BrNamed(_, name) = lt {
455 Some(name.as_str().to_string())
460 .chain(generics.params.iter().filter_map(|param| {
461 if let hir::GenericParamKind::Lifetime { .. } = ¶m.kind {
462 Some(param.name.ident().as_str().to_string())
467 .collect::<FxHashSet<String>>();
469 let a_to_z_repeat_n = |n| {
470 (b'a'..=b'z').map(move |c| {
471 let mut s = '\''.to_string();
472 s.extend(std::iter::repeat(char::from(c)).take(n));
477 // If all single char lifetime names are present, we wrap around and double the chars.
478 (1..).flat_map(a_to_z_repeat_n).find(|lt| !existing_lifetimes.contains(lt.as_str())).unwrap()
481 /// Returns the predicates defined on `item_def_id` of the form
482 /// `X: Foo` where `X` is the type parameter `def_id`.
483 fn type_param_predicates(
485 (item_def_id, def_id): (DefId, LocalDefId),
486 ) -> ty::GenericPredicates<'_> {
489 // In the AST, bounds can derive from two places. Either
490 // written inline like `<T: Foo>` or in a where-clause like
493 let param_id = tcx.hir().as_local_hir_id(def_id);
494 let param_owner = tcx.hir().ty_param_owner(param_id);
495 let param_owner_def_id = tcx.hir().local_def_id(param_owner);
496 let generics = tcx.generics_of(param_owner_def_id);
497 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
498 let ty = tcx.mk_ty_param(index, tcx.hir().ty_param_name(param_id));
500 // Don't look for bounds where the type parameter isn't in scope.
501 let parent = if item_def_id == param_owner_def_id.to_def_id() {
504 tcx.generics_of(item_def_id).parent
507 let mut result = parent
509 let icx = ItemCtxt::new(tcx, parent);
510 icx.get_type_parameter_bounds(DUMMY_SP, def_id.to_def_id())
512 .unwrap_or_default();
513 let mut extend = None;
515 let item_hir_id = tcx.hir().as_local_hir_id(item_def_id.expect_local());
516 let ast_generics = match tcx.hir().get(item_hir_id) {
517 Node::TraitItem(item) => &item.generics,
519 Node::ImplItem(item) => &item.generics,
521 Node::Item(item) => {
523 ItemKind::Fn(.., ref generics, _)
524 | ItemKind::Impl { ref generics, .. }
525 | ItemKind::TyAlias(_, ref generics)
526 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
527 | ItemKind::Enum(_, ref generics)
528 | ItemKind::Struct(_, ref generics)
529 | ItemKind::Union(_, ref generics) => generics,
530 ItemKind::Trait(_, _, ref generics, ..) => {
531 // Implied `Self: Trait` and supertrait bounds.
532 if param_id == item_hir_id {
533 let identity_trait_ref = ty::TraitRef::identity(tcx, item_def_id);
535 Some((identity_trait_ref.without_const().to_predicate(tcx), item.span));
543 Node::ForeignItem(item) => match item.kind {
544 ForeignItemKind::Fn(_, _, ref generics) => generics,
551 let icx = ItemCtxt::new(tcx, item_def_id);
552 let extra_predicates = extend.into_iter().chain(
553 icx.type_parameter_bounds_in_generics(ast_generics, param_id, ty, OnlySelfBounds(true))
555 .filter(|(predicate, _)| match predicate.ignore_qualifiers(tcx).skip_binder().kind() {
556 ty::PredicateKind::Trait(data, _) => data.self_ty().is_param(index),
561 tcx.arena.alloc_from_iter(result.predicates.iter().copied().chain(extra_predicates));
565 impl ItemCtxt<'tcx> {
566 /// Finds bounds from `hir::Generics`. This requires scanning through the
567 /// AST. We do this to avoid having to convert *all* the bounds, which
568 /// would create artificial cycles. Instead, we can only convert the
569 /// bounds for a type parameter `X` if `X::Foo` is used.
570 fn type_parameter_bounds_in_generics(
572 ast_generics: &'tcx hir::Generics<'tcx>,
573 param_id: hir::HirId,
575 only_self_bounds: OnlySelfBounds,
576 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
577 let constness = self.default_constness_for_trait_bounds();
578 let from_ty_params = ast_generics
581 .filter_map(|param| match param.kind {
582 GenericParamKind::Type { .. } if param.hir_id == param_id => Some(¶m.bounds),
585 .flat_map(|bounds| bounds.iter())
586 .flat_map(|b| predicates_from_bound(self, ty, b, constness));
588 let from_where_clauses = ast_generics
592 .filter_map(|wp| match *wp {
593 hir::WherePredicate::BoundPredicate(ref bp) => Some(bp),
597 let bt = if is_param(self.tcx, &bp.bounded_ty, param_id) {
599 } else if !only_self_bounds.0 {
600 Some(self.to_ty(&bp.bounded_ty))
604 bp.bounds.iter().filter_map(move |b| bt.map(|bt| (bt, b)))
606 .flat_map(|(bt, b)| predicates_from_bound(self, bt, b, constness));
608 from_ty_params.chain(from_where_clauses).collect()
612 /// Tests whether this is the AST for a reference to the type
613 /// parameter with ID `param_id`. We use this so as to avoid running
614 /// `ast_ty_to_ty`, because we want to avoid triggering an all-out
615 /// conversion of the type to avoid inducing unnecessary cycles.
616 fn is_param(tcx: TyCtxt<'_>, ast_ty: &hir::Ty<'_>, param_id: hir::HirId) -> bool {
617 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = ast_ty.kind {
619 Res::SelfTy(Some(def_id), None) | Res::Def(DefKind::TyParam, def_id) => {
620 def_id == tcx.hir().local_def_id(param_id).to_def_id()
629 fn convert_item(tcx: TyCtxt<'_>, item_id: hir::HirId) {
630 let it = tcx.hir().expect_item(item_id);
631 debug!("convert: item {} with id {}", it.ident, it.hir_id);
632 let def_id = tcx.hir().local_def_id(item_id);
634 // These don't define types.
635 hir::ItemKind::ExternCrate(_)
636 | hir::ItemKind::Use(..)
637 | hir::ItemKind::Mod(_)
638 | hir::ItemKind::GlobalAsm(_) => {}
639 hir::ItemKind::ForeignMod(ref foreign_mod) => {
640 for item in foreign_mod.items {
641 let def_id = tcx.hir().local_def_id(item.hir_id);
642 tcx.ensure().generics_of(def_id);
643 tcx.ensure().type_of(def_id);
644 tcx.ensure().predicates_of(def_id);
645 if let hir::ForeignItemKind::Fn(..) = item.kind {
646 tcx.ensure().fn_sig(def_id);
650 hir::ItemKind::Enum(ref enum_definition, _) => {
651 tcx.ensure().generics_of(def_id);
652 tcx.ensure().type_of(def_id);
653 tcx.ensure().predicates_of(def_id);
654 convert_enum_variant_types(tcx, def_id.to_def_id(), &enum_definition.variants);
656 hir::ItemKind::Impl { .. } => {
657 tcx.ensure().generics_of(def_id);
658 tcx.ensure().type_of(def_id);
659 tcx.ensure().impl_trait_ref(def_id);
660 tcx.ensure().predicates_of(def_id);
662 hir::ItemKind::Trait(..) => {
663 tcx.ensure().generics_of(def_id);
664 tcx.ensure().trait_def(def_id);
665 tcx.at(it.span).super_predicates_of(def_id);
666 tcx.ensure().predicates_of(def_id);
668 hir::ItemKind::TraitAlias(..) => {
669 tcx.ensure().generics_of(def_id);
670 tcx.at(it.span).super_predicates_of(def_id);
671 tcx.ensure().predicates_of(def_id);
673 hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
674 tcx.ensure().generics_of(def_id);
675 tcx.ensure().type_of(def_id);
676 tcx.ensure().predicates_of(def_id);
678 for f in struct_def.fields() {
679 let def_id = tcx.hir().local_def_id(f.hir_id);
680 tcx.ensure().generics_of(def_id);
681 tcx.ensure().type_of(def_id);
682 tcx.ensure().predicates_of(def_id);
685 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
686 convert_variant_ctor(tcx, ctor_hir_id);
690 // Desugared from `impl Trait`, so visited by the function's return type.
691 hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: Some(_), .. }) => {}
693 hir::ItemKind::OpaqueTy(..)
694 | hir::ItemKind::TyAlias(..)
695 | hir::ItemKind::Static(..)
696 | hir::ItemKind::Const(..)
697 | hir::ItemKind::Fn(..) => {
698 tcx.ensure().generics_of(def_id);
699 tcx.ensure().type_of(def_id);
700 tcx.ensure().predicates_of(def_id);
701 if let hir::ItemKind::Fn(..) = it.kind {
702 tcx.ensure().fn_sig(def_id);
708 fn convert_trait_item(tcx: TyCtxt<'_>, trait_item_id: hir::HirId) {
709 let trait_item = tcx.hir().expect_trait_item(trait_item_id);
710 let def_id = tcx.hir().local_def_id(trait_item.hir_id);
711 tcx.ensure().generics_of(def_id);
713 match trait_item.kind {
714 hir::TraitItemKind::Fn(..) => {
715 tcx.ensure().type_of(def_id);
716 tcx.ensure().fn_sig(def_id);
719 hir::TraitItemKind::Const(.., Some(_)) => {
720 tcx.ensure().type_of(def_id);
723 hir::TraitItemKind::Const(..) | hir::TraitItemKind::Type(_, Some(_)) => {
724 tcx.ensure().type_of(def_id);
725 // Account for `const C: _;` and `type T = _;`.
726 let mut visitor = PlaceholderHirTyCollector::default();
727 visitor.visit_trait_item(trait_item);
728 placeholder_type_error(tcx, None, &[], visitor.0, false);
731 hir::TraitItemKind::Type(_, None) => {
732 // #74612: Visit and try to find bad placeholders
733 // even if there is no concrete type.
734 let mut visitor = PlaceholderHirTyCollector::default();
735 visitor.visit_trait_item(trait_item);
736 placeholder_type_error(tcx, None, &[], visitor.0, false);
740 tcx.ensure().predicates_of(def_id);
743 fn convert_impl_item(tcx: TyCtxt<'_>, impl_item_id: hir::HirId) {
744 let def_id = tcx.hir().local_def_id(impl_item_id);
745 tcx.ensure().generics_of(def_id);
746 tcx.ensure().type_of(def_id);
747 tcx.ensure().predicates_of(def_id);
748 let impl_item = tcx.hir().expect_impl_item(impl_item_id);
749 match impl_item.kind {
750 hir::ImplItemKind::Fn(..) => {
751 tcx.ensure().fn_sig(def_id);
753 hir::ImplItemKind::TyAlias(_) => {
754 // Account for `type T = _;`
755 let mut visitor = PlaceholderHirTyCollector::default();
756 visitor.visit_impl_item(impl_item);
757 placeholder_type_error(tcx, None, &[], visitor.0, false);
759 hir::ImplItemKind::Const(..) => {}
763 fn convert_variant_ctor(tcx: TyCtxt<'_>, ctor_id: hir::HirId) {
764 let def_id = tcx.hir().local_def_id(ctor_id);
765 tcx.ensure().generics_of(def_id);
766 tcx.ensure().type_of(def_id);
767 tcx.ensure().predicates_of(def_id);
770 fn convert_enum_variant_types(tcx: TyCtxt<'_>, def_id: DefId, variants: &[hir::Variant<'_>]) {
771 let def = tcx.adt_def(def_id);
772 let repr_type = def.repr.discr_type();
773 let initial = repr_type.initial_discriminant(tcx);
774 let mut prev_discr = None::<Discr<'_>>;
776 // fill the discriminant values and field types
777 for variant in variants {
778 let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
780 if let Some(ref e) = variant.disr_expr {
781 let expr_did = tcx.hir().local_def_id(e.hir_id);
782 def.eval_explicit_discr(tcx, expr_did.to_def_id())
783 } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) {
786 struct_span_err!(tcx.sess, variant.span, E0370, "enum discriminant overflowed")
789 format!("overflowed on value after {}", prev_discr.unwrap()),
792 "explicitly set `{} = {}` if that is desired outcome",
793 variant.ident, wrapped_discr
798 .unwrap_or(wrapped_discr),
801 for f in variant.data.fields() {
802 let def_id = tcx.hir().local_def_id(f.hir_id);
803 tcx.ensure().generics_of(def_id);
804 tcx.ensure().type_of(def_id);
805 tcx.ensure().predicates_of(def_id);
808 // Convert the ctor, if any. This also registers the variant as
810 if let Some(ctor_hir_id) = variant.data.ctor_hir_id() {
811 convert_variant_ctor(tcx, ctor_hir_id);
818 variant_did: Option<LocalDefId>,
819 ctor_did: Option<LocalDefId>,
821 discr: ty::VariantDiscr,
822 def: &hir::VariantData<'_>,
823 adt_kind: ty::AdtKind,
824 parent_did: LocalDefId,
825 ) -> ty::VariantDef {
826 let mut seen_fields: FxHashMap<Ident, Span> = Default::default();
827 let hir_id = tcx.hir().as_local_hir_id(variant_did.unwrap_or(parent_did));
832 let fid = tcx.hir().local_def_id(f.hir_id);
833 let dup_span = seen_fields.get(&f.ident.normalize_to_macros_2_0()).cloned();
834 if let Some(prev_span) = dup_span {
839 "field `{}` is already declared",
842 .span_label(f.span, "field already declared")
843 .span_label(prev_span, format!("`{}` first declared here", f.ident))
846 seen_fields.insert(f.ident.normalize_to_macros_2_0(), f.span);
850 did: fid.to_def_id(),
852 vis: ty::Visibility::from_hir(&f.vis, hir_id, tcx),
856 let recovered = match def {
857 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(),
874 fn adt_def(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::AdtDef {
877 let def_id = def_id.expect_local();
878 let hir_id = tcx.hir().as_local_hir_id(def_id);
879 let item = match tcx.hir().get(hir_id) {
880 Node::Item(item) => item,
884 let repr = ReprOptions::new(tcx, def_id.to_def_id());
885 let (kind, variants) = match item.kind {
886 ItemKind::Enum(ref def, _) => {
887 let mut distance_from_explicit = 0;
892 let variant_did = Some(tcx.hir().local_def_id(v.id));
894 v.data.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
896 let discr = if let Some(ref e) = v.disr_expr {
897 distance_from_explicit = 0;
898 ty::VariantDiscr::Explicit(tcx.hir().local_def_id(e.hir_id).to_def_id())
900 ty::VariantDiscr::Relative(distance_from_explicit)
902 distance_from_explicit += 1;
917 (AdtKind::Enum, variants)
919 ItemKind::Struct(ref def, _) => {
920 let variant_did = None::<LocalDefId>;
921 let ctor_did = def.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
923 let variants = std::iter::once(convert_variant(
928 ty::VariantDiscr::Relative(0),
935 (AdtKind::Struct, variants)
937 ItemKind::Union(ref def, _) => {
938 let variant_did = None;
939 let ctor_did = def.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
941 let variants = std::iter::once(convert_variant(
946 ty::VariantDiscr::Relative(0),
953 (AdtKind::Union, variants)
957 tcx.alloc_adt_def(def_id.to_def_id(), kind, variants, repr)
960 /// Ensures that the super-predicates of the trait with a `DefId`
961 /// of `trait_def_id` are converted and stored. This also ensures that
962 /// the transitive super-predicates are converted.
963 fn super_predicates_of(tcx: TyCtxt<'_>, trait_def_id: DefId) -> ty::GenericPredicates<'_> {
964 debug!("super_predicates(trait_def_id={:?})", trait_def_id);
965 let trait_hir_id = tcx.hir().as_local_hir_id(trait_def_id.expect_local());
967 let item = match tcx.hir().get(trait_hir_id) {
968 Node::Item(item) => item,
969 _ => bug!("trait_node_id {} is not an item", trait_hir_id),
972 let (generics, bounds) = match item.kind {
973 hir::ItemKind::Trait(.., ref generics, ref supertraits, _) => (generics, supertraits),
974 hir::ItemKind::TraitAlias(ref generics, ref supertraits) => (generics, supertraits),
975 _ => span_bug!(item.span, "super_predicates invoked on non-trait"),
978 let icx = ItemCtxt::new(tcx, trait_def_id);
980 // Convert the bounds that follow the colon, e.g., `Bar + Zed` in `trait Foo: Bar + Zed`.
981 let self_param_ty = tcx.types.self_param;
983 AstConv::compute_bounds(&icx, self_param_ty, bounds, SizedByDefault::No, item.span);
985 let superbounds1 = superbounds1.predicates(tcx, self_param_ty);
987 // Convert any explicit superbounds in the where-clause,
988 // e.g., `trait Foo where Self: Bar`.
989 // In the case of trait aliases, however, we include all bounds in the where-clause,
990 // so e.g., `trait Foo = where u32: PartialEq<Self>` would include `u32: PartialEq<Self>`
991 // as one of its "superpredicates".
992 let is_trait_alias = tcx.is_trait_alias(trait_def_id);
993 let superbounds2 = icx.type_parameter_bounds_in_generics(
997 OnlySelfBounds(!is_trait_alias),
1000 // Combine the two lists to form the complete set of superbounds:
1001 let superbounds = &*tcx.arena.alloc_from_iter(superbounds1.into_iter().chain(superbounds2));
1003 // Now require that immediate supertraits are converted,
1004 // which will, in turn, reach indirect supertraits.
1005 for &(pred, span) in superbounds {
1006 debug!("superbound: {:?}", pred);
1007 if let ty::PredicateKind::Trait(bound, _) = pred.ignore_qualifiers(tcx).skip_binder().kind()
1009 tcx.at(span).super_predicates_of(bound.def_id());
1013 ty::GenericPredicates { parent: None, predicates: superbounds }
1016 fn trait_def(tcx: TyCtxt<'_>, def_id: DefId) -> ty::TraitDef {
1017 let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local());
1018 let item = tcx.hir().expect_item(hir_id);
1020 let (is_auto, unsafety) = match item.kind {
1021 hir::ItemKind::Trait(is_auto, unsafety, ..) => (is_auto == hir::IsAuto::Yes, unsafety),
1022 hir::ItemKind::TraitAlias(..) => (false, hir::Unsafety::Normal),
1023 _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
1026 let paren_sugar = tcx.has_attr(def_id, sym::rustc_paren_sugar);
1027 if paren_sugar && !tcx.features().unboxed_closures {
1031 "the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \
1032 which traits can use parenthetical notation",
1034 .help("add `#![feature(unboxed_closures)]` to the crate attributes to use it")
1038 let is_marker = tcx.has_attr(def_id, sym::marker);
1039 let spec_kind = if tcx.has_attr(def_id, sym::rustc_unsafe_specialization_marker) {
1040 ty::trait_def::TraitSpecializationKind::Marker
1041 } else if tcx.has_attr(def_id, sym::rustc_specialization_trait) {
1042 ty::trait_def::TraitSpecializationKind::AlwaysApplicable
1044 ty::trait_def::TraitSpecializationKind::None
1046 let def_path_hash = tcx.def_path_hash(def_id);
1047 ty::TraitDef::new(def_id, unsafety, paren_sugar, is_auto, is_marker, spec_kind, def_path_hash)
1050 fn has_late_bound_regions<'tcx>(tcx: TyCtxt<'tcx>, node: Node<'tcx>) -> Option<Span> {
1051 struct LateBoundRegionsDetector<'tcx> {
1053 outer_index: ty::DebruijnIndex,
1054 has_late_bound_regions: Option<Span>,
1057 impl Visitor<'tcx> for LateBoundRegionsDetector<'tcx> {
1058 type Map = intravisit::ErasedMap<'tcx>;
1060 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1061 NestedVisitorMap::None
1064 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
1065 if self.has_late_bound_regions.is_some() {
1069 hir::TyKind::BareFn(..) => {
1070 self.outer_index.shift_in(1);
1071 intravisit::walk_ty(self, ty);
1072 self.outer_index.shift_out(1);
1074 _ => intravisit::walk_ty(self, ty),
1078 fn visit_poly_trait_ref(
1080 tr: &'tcx hir::PolyTraitRef<'tcx>,
1081 m: hir::TraitBoundModifier,
1083 if self.has_late_bound_regions.is_some() {
1086 self.outer_index.shift_in(1);
1087 intravisit::walk_poly_trait_ref(self, tr, m);
1088 self.outer_index.shift_out(1);
1091 fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
1092 if self.has_late_bound_regions.is_some() {
1096 match self.tcx.named_region(lt.hir_id) {
1097 Some(rl::Region::Static | rl::Region::EarlyBound(..)) => {}
1099 rl::Region::LateBound(debruijn, _, _) | rl::Region::LateBoundAnon(debruijn, _),
1100 ) if debruijn < self.outer_index => {}
1102 rl::Region::LateBound(..)
1103 | rl::Region::LateBoundAnon(..)
1104 | rl::Region::Free(..),
1107 self.has_late_bound_regions = Some(lt.span);
1113 fn has_late_bound_regions<'tcx>(
1115 generics: &'tcx hir::Generics<'tcx>,
1116 decl: &'tcx hir::FnDecl<'tcx>,
1118 let mut visitor = LateBoundRegionsDetector {
1120 outer_index: ty::INNERMOST,
1121 has_late_bound_regions: None,
1123 for param in generics.params {
1124 if let GenericParamKind::Lifetime { .. } = param.kind {
1125 if tcx.is_late_bound(param.hir_id) {
1126 return Some(param.span);
1130 visitor.visit_fn_decl(decl);
1131 visitor.has_late_bound_regions
1135 Node::TraitItem(item) => match item.kind {
1136 hir::TraitItemKind::Fn(ref sig, _) => {
1137 has_late_bound_regions(tcx, &item.generics, &sig.decl)
1141 Node::ImplItem(item) => match item.kind {
1142 hir::ImplItemKind::Fn(ref sig, _) => {
1143 has_late_bound_regions(tcx, &item.generics, &sig.decl)
1147 Node::ForeignItem(item) => match item.kind {
1148 hir::ForeignItemKind::Fn(ref fn_decl, _, ref generics) => {
1149 has_late_bound_regions(tcx, generics, fn_decl)
1153 Node::Item(item) => match item.kind {
1154 hir::ItemKind::Fn(ref sig, .., ref generics, _) => {
1155 has_late_bound_regions(tcx, generics, &sig.decl)
1163 struct AnonConstInParamListDetector {
1164 in_param_list: bool,
1165 found_anon_const_in_list: bool,
1169 impl<'v> Visitor<'v> for AnonConstInParamListDetector {
1170 type Map = intravisit::ErasedMap<'v>;
1172 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1173 NestedVisitorMap::None
1176 fn visit_generic_param(&mut self, p: &'v hir::GenericParam<'v>) {
1177 let prev = self.in_param_list;
1178 self.in_param_list = true;
1179 intravisit::walk_generic_param(self, p);
1180 self.in_param_list = prev;
1183 fn visit_anon_const(&mut self, c: &'v hir::AnonConst) {
1184 if self.in_param_list && self.ct == c.hir_id {
1185 self.found_anon_const_in_list = true;
1187 intravisit::walk_anon_const(self, c)
1192 fn generics_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::Generics {
1195 let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local());
1197 let node = tcx.hir().get(hir_id);
1198 let parent_def_id = match node {
1200 | Node::TraitItem(_)
1203 | Node::Field(_) => {
1204 let parent_id = tcx.hir().get_parent_item(hir_id);
1205 Some(tcx.hir().local_def_id(parent_id).to_def_id())
1207 // FIXME(#43408) always enable this once `lazy_normalization` is
1208 // stable enough and does not need a feature gate anymore.
1209 Node::AnonConst(_) => {
1210 let parent_id = tcx.hir().get_parent_item(hir_id);
1211 let parent_def_id = tcx.hir().local_def_id(parent_id);
1213 let mut in_param_list = false;
1214 for (_parent, node) in tcx.hir().parent_iter(hir_id) {
1215 if let Some(generics) = node.generics() {
1216 let mut visitor = AnonConstInParamListDetector {
1217 in_param_list: false,
1218 found_anon_const_in_list: false,
1222 visitor.visit_generics(generics);
1223 in_param_list = visitor.found_anon_const_in_list;
1229 // We do not allow generic parameters in anon consts if we are inside
1232 // This affects both default type bindings, e.g. `struct<T, U = [u8; std::mem::size_of::<T>()]>(T, U)`,
1233 // and the types of const parameters, e.g. `struct V<const N: usize, const M: [u8; N]>();`.
1235 } else if tcx.lazy_normalization() {
1236 // HACK(eddyb) this provides the correct generics when
1237 // `feature(const_generics)` is enabled, so that const expressions
1238 // used with const generics, e.g. `Foo<{N+1}>`, can work at all.
1239 Some(parent_def_id.to_def_id())
1241 let parent_node = tcx.hir().get(tcx.hir().get_parent_node(hir_id));
1243 // HACK(eddyb) this provides the correct generics for repeat
1244 // expressions' count (i.e. `N` in `[x; N]`), and explicit
1245 // `enum` discriminants (i.e. `D` in `enum Foo { Bar = D }`),
1246 // as they shouldn't be able to cause query cycle errors.
1247 Node::Expr(&Expr { kind: ExprKind::Repeat(_, ref constant), .. })
1248 | Node::Variant(Variant { disr_expr: Some(ref constant), .. })
1249 if constant.hir_id == hir_id =>
1251 Some(parent_def_id.to_def_id())
1258 Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => {
1259 Some(tcx.closure_base_def_id(def_id))
1261 Node::Item(item) => match item.kind {
1262 ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn, .. }) => {
1263 impl_trait_fn.or_else(|| {
1264 let parent_id = tcx.hir().get_parent_item(hir_id);
1265 assert!(parent_id != hir_id && parent_id != CRATE_HIR_ID);
1266 debug!("generics_of: parent of opaque ty {:?} is {:?}", def_id, parent_id);
1267 // Opaque types are always nested within another item, and
1268 // inherit the generics of the item.
1269 Some(tcx.hir().local_def_id(parent_id).to_def_id())
1277 let mut opt_self = None;
1278 let mut allow_defaults = false;
1280 let no_generics = hir::Generics::empty();
1281 let ast_generics = match node {
1282 Node::TraitItem(item) => &item.generics,
1284 Node::ImplItem(item) => &item.generics,
1286 Node::Item(item) => {
1288 ItemKind::Fn(.., ref generics, _) | ItemKind::Impl { ref generics, .. } => generics,
1290 ItemKind::TyAlias(_, ref generics)
1291 | ItemKind::Enum(_, ref generics)
1292 | ItemKind::Struct(_, ref generics)
1293 | ItemKind::OpaqueTy(hir::OpaqueTy { ref generics, .. })
1294 | ItemKind::Union(_, ref generics) => {
1295 allow_defaults = true;
1299 ItemKind::Trait(_, _, ref generics, ..)
1300 | ItemKind::TraitAlias(ref generics, ..) => {
1301 // Add in the self type parameter.
1303 // Something of a hack: use the node id for the trait, also as
1304 // the node id for the Self type parameter.
1305 let param_id = item.hir_id;
1307 opt_self = Some(ty::GenericParamDef {
1309 name: kw::SelfUpper,
1310 def_id: tcx.hir().local_def_id(param_id).to_def_id(),
1311 pure_wrt_drop: false,
1312 kind: ty::GenericParamDefKind::Type {
1314 object_lifetime_default: rl::Set1::Empty,
1319 allow_defaults = true;
1327 Node::ForeignItem(item) => match item.kind {
1328 ForeignItemKind::Static(..) => &no_generics,
1329 ForeignItemKind::Fn(_, _, ref generics) => generics,
1330 ForeignItemKind::Type => &no_generics,
1336 let has_self = opt_self.is_some();
1337 let mut parent_has_self = false;
1338 let mut own_start = has_self as u32;
1339 let parent_count = parent_def_id.map_or(0, |def_id| {
1340 let generics = tcx.generics_of(def_id);
1341 assert_eq!(has_self, false);
1342 parent_has_self = generics.has_self;
1343 own_start = generics.count() as u32;
1344 generics.parent_count + generics.params.len()
1347 let mut params: Vec<_> = opt_self.into_iter().collect();
1349 let early_lifetimes = early_bound_lifetimes_from_generics(tcx, ast_generics);
1350 params.extend(early_lifetimes.enumerate().map(|(i, param)| ty::GenericParamDef {
1351 name: param.name.ident().name,
1352 index: own_start + i as u32,
1353 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
1354 pure_wrt_drop: param.pure_wrt_drop,
1355 kind: ty::GenericParamDefKind::Lifetime,
1358 let object_lifetime_defaults = tcx.object_lifetime_defaults(hir_id);
1360 // Now create the real type and const parameters.
1361 let type_start = own_start - has_self as u32 + params.len() as u32;
1364 params.extend(ast_generics.params.iter().filter_map(|param| match param.kind {
1365 GenericParamKind::Lifetime { .. } => None,
1366 GenericParamKind::Type { ref default, synthetic, .. } => {
1367 if !allow_defaults && default.is_some() {
1368 if !tcx.features().default_type_parameter_fallback {
1369 tcx.struct_span_lint_hir(
1370 lint::builtin::INVALID_TYPE_PARAM_DEFAULT,
1375 "defaults for type parameters are only allowed in \
1376 `struct`, `enum`, `type`, or `trait` definitions.",
1384 let kind = ty::GenericParamDefKind::Type {
1385 has_default: default.is_some(),
1386 object_lifetime_default: object_lifetime_defaults
1388 .map_or(rl::Set1::Empty, |o| o[i]),
1392 let param_def = ty::GenericParamDef {
1393 index: type_start + i as u32,
1394 name: param.name.ident().name,
1395 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
1396 pure_wrt_drop: param.pure_wrt_drop,
1402 GenericParamKind::Const { .. } => {
1403 let param_def = ty::GenericParamDef {
1404 index: type_start + i as u32,
1405 name: param.name.ident().name,
1406 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
1407 pure_wrt_drop: param.pure_wrt_drop,
1408 kind: ty::GenericParamDefKind::Const,
1415 // provide junk type parameter defs - the only place that
1416 // cares about anything but the length is instantiation,
1417 // and we don't do that for closures.
1418 if let Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(.., gen), .. }) = node {
1419 let dummy_args = if gen.is_some() {
1420 &["<resume_ty>", "<yield_ty>", "<return_ty>", "<witness>", "<upvars>"][..]
1422 &["<closure_kind>", "<closure_signature>", "<upvars>"][..]
1425 params.extend(dummy_args.iter().enumerate().map(|(i, &arg)| ty::GenericParamDef {
1426 index: type_start + i as u32,
1427 name: Symbol::intern(arg),
1429 pure_wrt_drop: false,
1430 kind: ty::GenericParamDefKind::Type {
1432 object_lifetime_default: rl::Set1::Empty,
1438 let param_def_id_to_index = params.iter().map(|param| (param.def_id, param.index)).collect();
1441 parent: parent_def_id,
1444 param_def_id_to_index,
1445 has_self: has_self || parent_has_self,
1446 has_late_bound_regions: has_late_bound_regions(tcx, node),
1450 fn are_suggestable_generic_args(generic_args: &[hir::GenericArg<'_>]) -> bool {
1453 .filter_map(|arg| match arg {
1454 hir::GenericArg::Type(ty) => Some(ty),
1457 .any(is_suggestable_infer_ty)
1460 /// Whether `ty` is a type with `_` placeholders that can be inferred. Used in diagnostics only to
1461 /// use inference to provide suggestions for the appropriate type if possible.
1462 fn is_suggestable_infer_ty(ty: &hir::Ty<'_>) -> bool {
1466 Slice(ty) | Array(ty, _) => is_suggestable_infer_ty(ty),
1467 Tup(tys) => tys.iter().any(is_suggestable_infer_ty),
1468 Ptr(mut_ty) | Rptr(_, mut_ty) => is_suggestable_infer_ty(mut_ty.ty),
1469 OpaqueDef(_, generic_args) => are_suggestable_generic_args(generic_args),
1470 Path(hir::QPath::TypeRelative(ty, segment)) => {
1471 is_suggestable_infer_ty(ty) || are_suggestable_generic_args(segment.generic_args().args)
1473 Path(hir::QPath::Resolved(ty_opt, hir::Path { segments, .. })) => {
1474 ty_opt.map_or(false, is_suggestable_infer_ty)
1477 .any(|segment| are_suggestable_generic_args(segment.generic_args().args))
1483 pub fn get_infer_ret_ty(output: &'hir hir::FnRetTy<'hir>) -> Option<&'hir hir::Ty<'hir>> {
1484 if let hir::FnRetTy::Return(ref ty) = output {
1485 if is_suggestable_infer_ty(ty) {
1492 fn fn_sig(tcx: TyCtxt<'_>, def_id: DefId) -> ty::PolyFnSig<'_> {
1493 use rustc_hir::Node::*;
1496 let def_id = def_id.expect_local();
1497 let hir_id = tcx.hir().as_local_hir_id(def_id);
1499 let icx = ItemCtxt::new(tcx, def_id.to_def_id());
1501 match tcx.hir().get(hir_id) {
1502 TraitItem(hir::TraitItem {
1503 kind: TraitItemKind::Fn(sig, TraitFn::Provided(_)),
1508 | ImplItem(hir::ImplItem { kind: ImplItemKind::Fn(sig, _), ident, generics, .. })
1509 | Item(hir::Item { kind: ItemKind::Fn(sig, generics, _), ident, .. }) => {
1510 match get_infer_ret_ty(&sig.decl.output) {
1512 let fn_sig = tcx.typeck(def_id).liberated_fn_sigs()[hir_id];
1513 let mut visitor = PlaceholderHirTyCollector::default();
1514 visitor.visit_ty(ty);
1515 let mut diag = bad_placeholder_type(tcx, visitor.0);
1516 let ret_ty = fn_sig.output();
1517 if ret_ty != tcx.ty_error() {
1518 diag.span_suggestion(
1520 "replace with the correct return type",
1522 Applicability::MaybeIncorrect,
1526 ty::Binder::bind(fn_sig)
1528 None => AstConv::ty_of_fn(
1530 sig.header.unsafety,
1539 TraitItem(hir::TraitItem {
1540 kind: TraitItemKind::Fn(FnSig { header, decl }, _),
1545 AstConv::ty_of_fn(&icx, header.unsafety, header.abi, decl, &generics, Some(ident.span))
1548 ForeignItem(&hir::ForeignItem {
1549 kind: ForeignItemKind::Fn(ref fn_decl, _, _),
1553 let abi = tcx.hir().get_foreign_abi(hir_id);
1554 compute_sig_of_foreign_fn_decl(tcx, def_id.to_def_id(), fn_decl, abi, ident)
1557 Ctor(data) | Variant(hir::Variant { data, .. }) if data.ctor_hir_id().is_some() => {
1558 let ty = tcx.type_of(tcx.hir().get_parent_did(hir_id).to_def_id());
1560 data.fields().iter().map(|f| tcx.type_of(tcx.hir().local_def_id(f.hir_id)));
1561 ty::Binder::bind(tcx.mk_fn_sig(
1565 hir::Unsafety::Normal,
1570 Expr(&hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => {
1571 // Closure signatures are not like other function
1572 // signatures and cannot be accessed through `fn_sig`. For
1573 // example, a closure signature excludes the `self`
1574 // argument. In any case they are embedded within the
1575 // closure type as part of the `ClosureSubsts`.
1577 // To get the signature of a closure, you should use the
1578 // `sig` method on the `ClosureSubsts`:
1580 // substs.as_closure().sig(def_id, tcx)
1582 "to get the signature of a closure, use `substs.as_closure().sig()` not `fn_sig()`",
1587 bug!("unexpected sort of node in fn_sig(): {:?}", x);
1592 fn impl_trait_ref(tcx: TyCtxt<'_>, def_id: DefId) -> Option<ty::TraitRef<'_>> {
1593 let icx = ItemCtxt::new(tcx, def_id);
1595 let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local());
1596 match tcx.hir().expect_item(hir_id).kind {
1597 hir::ItemKind::Impl { ref of_trait, .. } => of_trait.as_ref().map(|ast_trait_ref| {
1598 let selfty = tcx.type_of(def_id);
1599 AstConv::instantiate_mono_trait_ref(&icx, ast_trait_ref, selfty)
1605 fn impl_polarity(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ImplPolarity {
1606 let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local());
1607 let is_rustc_reservation = tcx.has_attr(def_id, sym::rustc_reservation_impl);
1608 let item = tcx.hir().expect_item(hir_id);
1610 hir::ItemKind::Impl { polarity: hir::ImplPolarity::Negative(span), of_trait, .. } => {
1611 if is_rustc_reservation {
1612 let span = span.to(of_trait.as_ref().map(|t| t.path.span).unwrap_or(*span));
1613 tcx.sess.span_err(span, "reservation impls can't be negative");
1615 ty::ImplPolarity::Negative
1617 hir::ItemKind::Impl { polarity: hir::ImplPolarity::Positive, of_trait: None, .. } => {
1618 if is_rustc_reservation {
1619 tcx.sess.span_err(item.span, "reservation impls can't be inherent");
1621 ty::ImplPolarity::Positive
1623 hir::ItemKind::Impl {
1624 polarity: hir::ImplPolarity::Positive, of_trait: Some(_), ..
1626 if is_rustc_reservation {
1627 ty::ImplPolarity::Reservation
1629 ty::ImplPolarity::Positive
1632 ref item => bug!("impl_polarity: {:?} not an impl", item),
1636 /// Returns the early-bound lifetimes declared in this generics
1637 /// listing. For anything other than fns/methods, this is just all
1638 /// the lifetimes that are declared. For fns or methods, we have to
1639 /// screen out those that do not appear in any where-clauses etc using
1640 /// `resolve_lifetime::early_bound_lifetimes`.
1641 fn early_bound_lifetimes_from_generics<'a, 'tcx: 'a>(
1643 generics: &'a hir::Generics<'a>,
1644 ) -> impl Iterator<Item = &'a hir::GenericParam<'a>> + Captures<'tcx> {
1645 generics.params.iter().filter(move |param| match param.kind {
1646 GenericParamKind::Lifetime { .. } => !tcx.is_late_bound(param.hir_id),
1651 /// Returns a list of type predicates for the definition with ID `def_id`, including inferred
1652 /// lifetime constraints. This includes all predicates returned by `explicit_predicates_of`, plus
1653 /// inferred constraints concerning which regions outlive other regions.
1654 fn predicates_defined_on(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1655 debug!("predicates_defined_on({:?})", def_id);
1656 let mut result = tcx.explicit_predicates_of(def_id);
1657 debug!("predicates_defined_on: explicit_predicates_of({:?}) = {:?}", def_id, result,);
1658 let inferred_outlives = tcx.inferred_outlives_of(def_id);
1659 if !inferred_outlives.is_empty() {
1661 "predicates_defined_on: inferred_outlives_of({:?}) = {:?}",
1662 def_id, inferred_outlives,
1664 if result.predicates.is_empty() {
1665 result.predicates = inferred_outlives;
1667 result.predicates = tcx
1669 .alloc_from_iter(result.predicates.iter().chain(inferred_outlives).copied());
1672 debug!("predicates_defined_on({:?}) = {:?}", def_id, result);
1676 /// Returns a list of all type predicates (explicit and implicit) for the definition with
1677 /// ID `def_id`. This includes all predicates returned by `predicates_defined_on`, plus
1678 /// `Self: Trait` predicates for traits.
1679 fn predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1680 let mut result = tcx.predicates_defined_on(def_id);
1682 if tcx.is_trait(def_id) {
1683 // For traits, add `Self: Trait` predicate. This is
1684 // not part of the predicates that a user writes, but it
1685 // is something that one must prove in order to invoke a
1686 // method or project an associated type.
1688 // In the chalk setup, this predicate is not part of the
1689 // "predicates" for a trait item. But it is useful in
1690 // rustc because if you directly (e.g.) invoke a trait
1691 // method like `Trait::method(...)`, you must naturally
1692 // prove that the trait applies to the types that were
1693 // used, and adding the predicate into this list ensures
1694 // that this is done.
1695 let span = tcx.sess.source_map().guess_head_span(tcx.def_span(def_id));
1697 tcx.arena.alloc_from_iter(result.predicates.iter().copied().chain(std::iter::once((
1698 ty::TraitRef::identity(tcx, def_id).without_const().to_predicate(tcx),
1702 debug!("predicates_of(def_id={:?}) = {:?}", def_id, result);
1706 /// Returns a list of user-specified type predicates for the definition with ID `def_id`.
1707 /// N.B., this does not include any implied/inferred constraints.
1708 fn explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1711 debug!("explicit_predicates_of(def_id={:?})", def_id);
1713 /// A data structure with unique elements, which preserves order of insertion.
1714 /// Preserving the order of insertion is important here so as not to break
1715 /// compile-fail UI tests.
1716 // FIXME(eddyb) just use `IndexSet` from `indexmap`.
1717 struct UniquePredicates<'tcx> {
1718 predicates: Vec<(ty::Predicate<'tcx>, Span)>,
1719 uniques: FxHashSet<(ty::Predicate<'tcx>, Span)>,
1722 impl<'tcx> UniquePredicates<'tcx> {
1724 UniquePredicates { predicates: vec![], uniques: FxHashSet::default() }
1727 fn push(&mut self, value: (ty::Predicate<'tcx>, Span)) {
1728 if self.uniques.insert(value) {
1729 self.predicates.push(value);
1733 fn extend<I: IntoIterator<Item = (ty::Predicate<'tcx>, Span)>>(&mut self, iter: I) {
1740 let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local());
1741 let node = tcx.hir().get(hir_id);
1743 let mut is_trait = None;
1744 let mut is_default_impl_trait = None;
1745 let mut is_trait_associated_type = None;
1747 let icx = ItemCtxt::new(tcx, def_id);
1748 let constness = icx.default_constness_for_trait_bounds();
1750 const NO_GENERICS: &hir::Generics<'_> = &hir::Generics::empty();
1752 let mut predicates = UniquePredicates::new();
1754 let ast_generics = match node {
1755 Node::TraitItem(item) => {
1756 if let hir::TraitItemKind::Type(bounds, _) = item.kind {
1757 is_trait_associated_type = Some((bounds, item.span));
1762 Node::ImplItem(item) => &item.generics,
1764 Node::Item(item) => {
1766 ItemKind::Impl { defaultness, ref generics, .. } => {
1767 if defaultness.is_default() {
1768 is_default_impl_trait = tcx.impl_trait_ref(def_id);
1772 ItemKind::Fn(.., ref generics, _)
1773 | ItemKind::TyAlias(_, ref generics)
1774 | ItemKind::Enum(_, ref generics)
1775 | ItemKind::Struct(_, ref generics)
1776 | ItemKind::Union(_, ref generics) => generics,
1778 ItemKind::Trait(_, _, ref generics, .., items) => {
1779 is_trait = Some((ty::TraitRef::identity(tcx, def_id), items));
1782 ItemKind::TraitAlias(ref generics, _) => {
1783 is_trait = Some((ty::TraitRef::identity(tcx, def_id), &[]));
1786 ItemKind::OpaqueTy(OpaqueTy {
1792 let bounds_predicates = ty::print::with_no_queries(|| {
1793 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1794 let opaque_ty = tcx.mk_opaque(def_id, substs);
1796 // Collect the bounds, i.e., the `A + B + 'c` in `impl A + B + 'c`.
1797 let bounds = AstConv::compute_bounds(
1801 SizedByDefault::Yes,
1802 tcx.def_span(def_id),
1805 bounds.predicates(tcx, opaque_ty)
1807 if impl_trait_fn.is_some() {
1809 return ty::GenericPredicates {
1811 predicates: tcx.arena.alloc_from_iter(bounds_predicates),
1814 // named opaque types
1815 predicates.extend(bounds_predicates);
1824 Node::ForeignItem(item) => match item.kind {
1825 ForeignItemKind::Static(..) => NO_GENERICS,
1826 ForeignItemKind::Fn(_, _, ref generics) => generics,
1827 ForeignItemKind::Type => NO_GENERICS,
1833 let generics = tcx.generics_of(def_id);
1834 let parent_count = generics.parent_count as u32;
1835 let has_own_self = generics.has_self && parent_count == 0;
1837 // Below we'll consider the bounds on the type parameters (including `Self`)
1838 // and the explicit where-clauses, but to get the full set of predicates
1839 // on a trait we need to add in the supertrait bounds and bounds found on
1840 // associated types.
1841 if let Some((_trait_ref, _)) = is_trait {
1842 predicates.extend(tcx.super_predicates_of(def_id).predicates.iter().cloned());
1845 // In default impls, we can assume that the self type implements
1846 // the trait. So in:
1848 // default impl Foo for Bar { .. }
1850 // we add a default where clause `Foo: Bar`. We do a similar thing for traits
1851 // (see below). Recall that a default impl is not itself an impl, but rather a
1852 // set of defaults that can be incorporated into another impl.
1853 if let Some(trait_ref) = is_default_impl_trait {
1855 trait_ref.to_poly_trait_ref().without_const().to_predicate(tcx),
1856 tcx.def_span(def_id),
1860 // Collect the region predicates that were declared inline as
1861 // well. In the case of parameters declared on a fn or method, we
1862 // have to be careful to only iterate over early-bound regions.
1863 let mut index = parent_count + has_own_self as u32;
1864 for param in early_bound_lifetimes_from_generics(tcx, ast_generics) {
1865 let region = tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
1866 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
1868 name: param.name.ident().name,
1873 GenericParamKind::Lifetime { .. } => {
1874 param.bounds.iter().for_each(|bound| match bound {
1875 hir::GenericBound::Outlives(lt) => {
1876 let bound = AstConv::ast_region_to_region(&icx, <, None);
1877 let outlives = ty::Binder::bind(ty::OutlivesPredicate(region, bound));
1878 predicates.push((outlives.to_predicate(tcx), lt.span));
1887 // Collect the predicates that were written inline by the user on each
1888 // type parameter (e.g., `<T: Foo>`).
1889 for param in ast_generics.params {
1891 // We already dealt with early bound lifetimes above.
1892 GenericParamKind::Lifetime { .. } => (),
1893 GenericParamKind::Type { .. } => {
1894 let name = param.name.ident().name;
1895 let param_ty = ty::ParamTy::new(index, name).to_ty(tcx);
1898 let sized = SizedByDefault::Yes;
1900 AstConv::compute_bounds(&icx, param_ty, ¶m.bounds, sized, param.span);
1901 predicates.extend(bounds.predicates(tcx, param_ty));
1903 GenericParamKind::Const { .. } => {
1904 // Bounds on const parameters are currently not possible.
1905 debug_assert!(param.bounds.is_empty());
1911 // Add in the bounds that appear in the where-clause.
1912 let where_clause = &ast_generics.where_clause;
1913 for predicate in where_clause.predicates {
1915 &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
1916 let ty = icx.to_ty(&bound_pred.bounded_ty);
1918 // Keep the type around in a dummy predicate, in case of no bounds.
1919 // That way, `where Ty:` is not a complete noop (see #53696) and `Ty`
1920 // is still checked for WF.
1921 if bound_pred.bounds.is_empty() {
1922 if let ty::Param(_) = ty.kind {
1923 // This is a `where T:`, which can be in the HIR from the
1924 // transformation that moves `?Sized` to `T`'s declaration.
1925 // We can skip the predicate because type parameters are
1926 // trivially WF, but also we *should*, to avoid exposing
1927 // users who never wrote `where Type:,` themselves, to
1928 // compiler/tooling bugs from not handling WF predicates.
1930 let span = bound_pred.bounded_ty.span;
1931 let re_root_empty = tcx.lifetimes.re_root_empty;
1932 let predicate = ty::OutlivesPredicate(ty, re_root_empty);
1934 ty::PredicateKind::TypeOutlives(ty::Binder::bind(predicate))
1941 for bound in bound_pred.bounds.iter() {
1943 &hir::GenericBound::Trait(ref poly_trait_ref, modifier) => {
1944 let constness = match modifier {
1945 hir::TraitBoundModifier::MaybeConst => hir::Constness::NotConst,
1946 hir::TraitBoundModifier::None => constness,
1947 hir::TraitBoundModifier::Maybe => bug!("this wasn't handled"),
1950 let mut bounds = Bounds::default();
1951 let _ = AstConv::instantiate_poly_trait_ref(
1958 predicates.extend(bounds.predicates(tcx, ty));
1961 &hir::GenericBound::Outlives(ref lifetime) => {
1962 let region = AstConv::ast_region_to_region(&icx, lifetime, None);
1964 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, region))
1966 .potentially_qualified(tcx, ty::PredicateKind::ForAll),
1974 &hir::WherePredicate::RegionPredicate(ref region_pred) => {
1975 let r1 = AstConv::ast_region_to_region(&icx, ®ion_pred.lifetime, None);
1976 predicates.extend(region_pred.bounds.iter().map(|bound| {
1977 let (r2, span) = match bound {
1978 hir::GenericBound::Outlives(lt) => {
1979 (AstConv::ast_region_to_region(&icx, lt, None), lt.span)
1983 let pred = ty::PredicateKind::RegionOutlives(ty::OutlivesPredicate(r1, r2))
1984 .to_predicate(icx.tcx);
1986 (pred.potentially_qualified(icx.tcx, ty::PredicateKind::ForAll), span)
1990 &hir::WherePredicate::EqPredicate(..) => {
1996 // Add predicates from associated type bounds (`type X: Bound`)
1997 if tcx.features().generic_associated_types {
1998 // New behavior: bounds declared on associate type are predicates of that
1999 // associated type. Not the default because it needs more testing.
2000 if let Some((bounds, span)) = is_trait_associated_type {
2002 tcx.mk_projection(def_id, InternalSubsts::identity_for_item(tcx, def_id));
2004 predicates.extend(associated_item_bounds(tcx, def_id, bounds, projection_ty, span))
2006 } else if let Some((self_trait_ref, trait_items)) = is_trait {
2007 // Current behavior: bounds declared on associate type are predicates
2008 // of its parent trait.
2009 predicates.extend(trait_items.iter().flat_map(|trait_item_ref| {
2010 trait_associated_item_predicates(tcx, def_id, self_trait_ref, trait_item_ref)
2014 let mut predicates = predicates.predicates;
2016 // Subtle: before we store the predicates into the tcx, we
2017 // sort them so that predicates like `T: Foo<Item=U>` come
2018 // before uses of `U`. This avoids false ambiguity errors
2019 // in trait checking. See `setup_constraining_predicates`
2021 if let Node::Item(&Item { kind: ItemKind::Impl { .. }, .. }) = node {
2022 let self_ty = tcx.type_of(def_id);
2023 let trait_ref = tcx.impl_trait_ref(def_id);
2024 cgp::setup_constraining_predicates(
2028 &mut cgp::parameters_for_impl(self_ty, trait_ref),
2032 let result = ty::GenericPredicates {
2033 parent: generics.parent,
2034 predicates: tcx.arena.alloc_from_iter(predicates),
2036 debug!("explicit_predicates_of(def_id={:?}) = {:?}", def_id, result);
2040 fn trait_associated_item_predicates(
2043 self_trait_ref: ty::TraitRef<'tcx>,
2044 trait_item_ref: &hir::TraitItemRef,
2045 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2046 let trait_item = tcx.hir().trait_item(trait_item_ref.id);
2047 let item_def_id = tcx.hir().local_def_id(trait_item_ref.id.hir_id);
2048 let bounds = match trait_item.kind {
2049 hir::TraitItemKind::Type(ref bounds, _) => bounds,
2050 _ => return Vec::new(),
2053 if !tcx.generics_of(item_def_id).params.is_empty() {
2054 // For GATs the substs provided to the mk_projection call below are
2055 // wrong. We should emit a feature gate error if we get here so skip
2057 tcx.sess.delay_span_bug(trait_item.span, "gats used without feature gate");
2061 let assoc_ty = tcx.mk_projection(
2062 tcx.hir().local_def_id(trait_item.hir_id).to_def_id(),
2063 self_trait_ref.substs,
2066 associated_item_bounds(tcx, def_id, bounds, assoc_ty, trait_item.span)
2069 fn associated_item_bounds(
2072 bounds: &'tcx [hir::GenericBound<'tcx>],
2073 projection_ty: Ty<'tcx>,
2075 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2076 let bounds = AstConv::compute_bounds(
2077 &ItemCtxt::new(tcx, def_id),
2080 SizedByDefault::Yes,
2084 let predicates = bounds.predicates(tcx, projection_ty);
2089 /// Converts a specific `GenericBound` from the AST into a set of
2090 /// predicates that apply to the self type. A vector is returned
2091 /// because this can be anywhere from zero predicates (`T: ?Sized` adds no
2092 /// predicates) to one (`T: Foo`) to many (`T: Bar<X = i32>` adds `T: Bar`
2093 /// and `<T as Bar>::X == i32`).
2094 fn predicates_from_bound<'tcx>(
2095 astconv: &dyn AstConv<'tcx>,
2097 bound: &'tcx hir::GenericBound<'tcx>,
2098 constness: hir::Constness,
2099 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2101 hir::GenericBound::Trait(ref tr, modifier) => {
2102 let constness = match modifier {
2103 hir::TraitBoundModifier::Maybe => return vec![],
2104 hir::TraitBoundModifier::MaybeConst => hir::Constness::NotConst,
2105 hir::TraitBoundModifier::None => constness,
2108 let mut bounds = Bounds::default();
2109 let _ = astconv.instantiate_poly_trait_ref(tr, constness, param_ty, &mut bounds);
2110 bounds.predicates(astconv.tcx(), param_ty)
2112 hir::GenericBound::Outlives(ref lifetime) => {
2113 let region = astconv.ast_region_to_region(lifetime, None);
2114 let pred = ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(param_ty, region))
2115 .to_predicate(astconv.tcx())
2116 .potentially_qualified(astconv.tcx(), ty::PredicateKind::ForAll);
2117 vec![(pred, lifetime.span)]
2122 fn compute_sig_of_foreign_fn_decl<'tcx>(
2125 decl: &'tcx hir::FnDecl<'tcx>,
2128 ) -> ty::PolyFnSig<'tcx> {
2129 let unsafety = if abi == abi::Abi::RustIntrinsic {
2130 intrinsic_operation_unsafety(tcx.item_name(def_id))
2132 hir::Unsafety::Unsafe
2134 let fty = AstConv::ty_of_fn(
2135 &ItemCtxt::new(tcx, def_id),
2139 &hir::Generics::empty(),
2143 // Feature gate SIMD types in FFI, since I am not sure that the
2144 // ABIs are handled at all correctly. -huonw
2145 if abi != abi::Abi::RustIntrinsic
2146 && abi != abi::Abi::PlatformIntrinsic
2147 && !tcx.features().simd_ffi
2149 let check = |ast_ty: &hir::Ty<'_>, ty: Ty<'_>| {
2154 .span_to_snippet(ast_ty.span)
2155 .map_or(String::new(), |s| format!(" `{}`", s));
2160 "use of SIMD type{} in FFI is highly experimental and \
2161 may result in invalid code",
2165 .help("add `#![feature(simd_ffi)]` to the crate attributes to enable")
2169 for (input, ty) in decl.inputs.iter().zip(fty.inputs().skip_binder()) {
2172 if let hir::FnRetTy::Return(ref ty) = decl.output {
2173 check(&ty, fty.output().skip_binder())
2180 fn is_foreign_item(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
2181 match tcx.hir().get_if_local(def_id) {
2182 Some(Node::ForeignItem(..)) => true,
2184 _ => bug!("is_foreign_item applied to non-local def-id {:?}", def_id),
2188 fn static_mutability(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::Mutability> {
2189 match tcx.hir().get_if_local(def_id) {
2191 Node::Item(&hir::Item { kind: hir::ItemKind::Static(_, mutbl, _), .. })
2192 | Node::ForeignItem(&hir::ForeignItem {
2193 kind: hir::ForeignItemKind::Static(_, mutbl),
2198 _ => bug!("static_mutability applied to non-local def-id {:?}", def_id),
2202 fn generator_kind(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::GeneratorKind> {
2203 match tcx.hir().get_if_local(def_id) {
2204 Some(Node::Expr(&rustc_hir::Expr {
2205 kind: rustc_hir::ExprKind::Closure(_, _, body_id, _, _),
2207 })) => tcx.hir().body(body_id).generator_kind(),
2209 _ => bug!("generator_kind applied to non-local def-id {:?}", def_id),
2213 fn from_target_feature(
2216 attr: &ast::Attribute,
2217 supported_target_features: &FxHashMap<String, Option<Symbol>>,
2218 target_features: &mut Vec<Symbol>,
2220 let list = match attr.meta_item_list() {
2224 let bad_item = |span| {
2225 let msg = "malformed `target_feature` attribute input";
2226 let code = "enable = \"..\"".to_owned();
2228 .struct_span_err(span, &msg)
2229 .span_suggestion(span, "must be of the form", code, Applicability::HasPlaceholders)
2232 let rust_features = tcx.features();
2234 // Only `enable = ...` is accepted in the meta-item list.
2235 if !item.check_name(sym::enable) {
2236 bad_item(item.span());
2240 // Must be of the form `enable = "..."` (a string).
2241 let value = match item.value_str() {
2242 Some(value) => value,
2244 bad_item(item.span());
2249 // We allow comma separation to enable multiple features.
2250 target_features.extend(value.as_str().split(',').filter_map(|feature| {
2251 let feature_gate = match supported_target_features.get(feature) {
2255 format!("the feature named `{}` is not valid for this target", feature);
2256 let mut err = tcx.sess.struct_span_err(item.span(), &msg);
2259 format!("`{}` is not valid for this target", feature),
2261 if feature.starts_with('+') {
2262 let valid = supported_target_features.contains_key(&feature[1..]);
2264 err.help("consider removing the leading `+` in the feature name");
2272 // Only allow features whose feature gates have been enabled.
2273 let allowed = match feature_gate.as_ref().copied() {
2274 Some(sym::arm_target_feature) => rust_features.arm_target_feature,
2275 Some(sym::aarch64_target_feature) => rust_features.aarch64_target_feature,
2276 Some(sym::hexagon_target_feature) => rust_features.hexagon_target_feature,
2277 Some(sym::powerpc_target_feature) => rust_features.powerpc_target_feature,
2278 Some(sym::mips_target_feature) => rust_features.mips_target_feature,
2279 Some(sym::riscv_target_feature) => rust_features.riscv_target_feature,
2280 Some(sym::avx512_target_feature) => rust_features.avx512_target_feature,
2281 Some(sym::mmx_target_feature) => rust_features.mmx_target_feature,
2282 Some(sym::sse4a_target_feature) => rust_features.sse4a_target_feature,
2283 Some(sym::tbm_target_feature) => rust_features.tbm_target_feature,
2284 Some(sym::wasm_target_feature) => rust_features.wasm_target_feature,
2285 Some(sym::cmpxchg16b_target_feature) => rust_features.cmpxchg16b_target_feature,
2286 Some(sym::adx_target_feature) => rust_features.adx_target_feature,
2287 Some(sym::movbe_target_feature) => rust_features.movbe_target_feature,
2288 Some(sym::rtm_target_feature) => rust_features.rtm_target_feature,
2289 Some(sym::f16c_target_feature) => rust_features.f16c_target_feature,
2290 Some(name) => bug!("unknown target feature gate {}", name),
2293 if !allowed && id.is_local() {
2295 &tcx.sess.parse_sess,
2296 feature_gate.unwrap(),
2298 &format!("the target feature `{}` is currently unstable", feature),
2302 Some(Symbol::intern(feature))
2307 fn linkage_by_name(tcx: TyCtxt<'_>, def_id: DefId, name: &str) -> Linkage {
2308 use rustc_middle::mir::mono::Linkage::*;
2310 // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
2311 // applicable to variable declarations and may not really make sense for
2312 // Rust code in the first place but allow them anyway and trust that the
2313 // user knows what s/he's doing. Who knows, unanticipated use cases may pop
2314 // up in the future.
2316 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
2317 // and don't have to be, LLVM treats them as no-ops.
2319 "appending" => Appending,
2320 "available_externally" => AvailableExternally,
2322 "extern_weak" => ExternalWeak,
2323 "external" => External,
2324 "internal" => Internal,
2325 "linkonce" => LinkOnceAny,
2326 "linkonce_odr" => LinkOnceODR,
2327 "private" => Private,
2329 "weak_odr" => WeakODR,
2331 let span = tcx.hir().span_if_local(def_id);
2332 if let Some(span) = span {
2333 tcx.sess.span_fatal(span, "invalid linkage specified")
2335 tcx.sess.fatal(&format!("invalid linkage specified: {}", name))
2341 fn codegen_fn_attrs(tcx: TyCtxt<'_>, id: DefId) -> CodegenFnAttrs {
2342 let attrs = tcx.get_attrs(id);
2344 let mut codegen_fn_attrs = CodegenFnAttrs::new();
2345 if should_inherit_track_caller(tcx, id) {
2346 codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
2349 let supported_target_features = tcx.supported_target_features(LOCAL_CRATE);
2351 let mut inline_span = None;
2352 let mut link_ordinal_span = None;
2353 let mut no_sanitize_span = None;
2354 for attr in attrs.iter() {
2355 if attr.check_name(sym::cold) {
2356 codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD;
2357 } else if attr.check_name(sym::rustc_allocator) {
2358 codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR;
2359 } else if attr.check_name(sym::unwind) {
2360 codegen_fn_attrs.flags |= CodegenFnAttrFlags::UNWIND;
2361 } else if attr.check_name(sym::ffi_returns_twice) {
2362 if tcx.is_foreign_item(id) {
2363 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_RETURNS_TWICE;
2365 // `#[ffi_returns_twice]` is only allowed `extern fn`s.
2370 "`#[ffi_returns_twice]` may only be used on foreign functions"
2374 } else if attr.check_name(sym::ffi_pure) {
2375 if tcx.is_foreign_item(id) {
2376 if attrs.iter().any(|a| a.check_name(sym::ffi_const)) {
2377 // `#[ffi_const]` functions cannot be `#[ffi_pure]`
2382 "`#[ffi_const]` function cannot be `#[ffi_pure]`"
2386 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_PURE;
2389 // `#[ffi_pure]` is only allowed on foreign functions
2394 "`#[ffi_pure]` may only be used on foreign functions"
2398 } else if attr.check_name(sym::ffi_const) {
2399 if tcx.is_foreign_item(id) {
2400 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_CONST;
2402 // `#[ffi_const]` is only allowed on foreign functions
2407 "`#[ffi_const]` may only be used on foreign functions"
2411 } else if attr.check_name(sym::rustc_allocator_nounwind) {
2412 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND;
2413 } else if attr.check_name(sym::naked) {
2414 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED;
2415 } else if attr.check_name(sym::no_mangle) {
2416 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2417 } else if attr.check_name(sym::rustc_std_internal_symbol) {
2418 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2419 } else if attr.check_name(sym::used) {
2420 codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED;
2421 } else if attr.check_name(sym::thread_local) {
2422 codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL;
2423 } else if attr.check_name(sym::track_caller) {
2424 if tcx.is_closure(id) || tcx.fn_sig(id).abi() != abi::Abi::Rust {
2425 struct_span_err!(tcx.sess, attr.span, E0737, "`#[track_caller]` requires Rust ABI")
2428 codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
2429 } else if attr.check_name(sym::export_name) {
2430 if let Some(s) = attr.value_str() {
2431 if s.as_str().contains('\0') {
2432 // `#[export_name = ...]` will be converted to a null-terminated string,
2433 // so it may not contain any null characters.
2438 "`export_name` may not contain null characters"
2442 codegen_fn_attrs.export_name = Some(s);
2444 } else if attr.check_name(sym::target_feature) {
2445 if !tcx.features().target_feature_11 {
2446 check_target_feature_safe_fn(tcx, id, attr.span);
2447 } else if let Some(local_id) = id.as_local() {
2448 if tcx.fn_sig(id).unsafety() == hir::Unsafety::Normal {
2449 check_target_feature_trait_unsafe(tcx, local_id, attr.span);
2452 from_target_feature(
2456 &supported_target_features,
2457 &mut codegen_fn_attrs.target_features,
2459 } else if attr.check_name(sym::linkage) {
2460 if let Some(val) = attr.value_str() {
2461 codegen_fn_attrs.linkage = Some(linkage_by_name(tcx, id, &val.as_str()));
2463 } else if attr.check_name(sym::link_section) {
2464 if let Some(val) = attr.value_str() {
2465 if val.as_str().bytes().any(|b| b == 0) {
2467 "illegal null byte in link_section \
2471 tcx.sess.span_err(attr.span, &msg);
2473 codegen_fn_attrs.link_section = Some(val);
2476 } else if attr.check_name(sym::link_name) {
2477 codegen_fn_attrs.link_name = attr.value_str();
2478 } else if attr.check_name(sym::link_ordinal) {
2479 link_ordinal_span = Some(attr.span);
2480 if let ordinal @ Some(_) = check_link_ordinal(tcx, attr) {
2481 codegen_fn_attrs.link_ordinal = ordinal;
2483 } else if attr.check_name(sym::no_sanitize) {
2484 no_sanitize_span = Some(attr.span);
2485 if let Some(list) = attr.meta_item_list() {
2486 for item in list.iter() {
2487 if item.check_name(sym::address) {
2488 codegen_fn_attrs.no_sanitize |= SanitizerSet::ADDRESS;
2489 } else if item.check_name(sym::memory) {
2490 codegen_fn_attrs.no_sanitize |= SanitizerSet::MEMORY;
2491 } else if item.check_name(sym::thread) {
2492 codegen_fn_attrs.no_sanitize |= SanitizerSet::THREAD;
2495 .struct_span_err(item.span(), "invalid argument for `no_sanitize`")
2496 .note("expected one of: `address`, `memory` or `thread`")
2504 codegen_fn_attrs.inline = attrs.iter().fold(InlineAttr::None, |ia, attr| {
2505 if !attr.has_name(sym::inline) {
2508 match attr.meta().map(|i| i.kind) {
2509 Some(MetaItemKind::Word) => {
2513 Some(MetaItemKind::List(ref items)) => {
2515 inline_span = Some(attr.span);
2516 if items.len() != 1 {
2518 tcx.sess.diagnostic(),
2521 "expected one argument"
2525 } else if list_contains_name(&items[..], sym::always) {
2527 } else if list_contains_name(&items[..], sym::never) {
2531 tcx.sess.diagnostic(),
2541 Some(MetaItemKind::NameValue(_)) => ia,
2546 codegen_fn_attrs.optimize = attrs.iter().fold(OptimizeAttr::None, |ia, attr| {
2547 if !attr.has_name(sym::optimize) {
2550 let err = |sp, s| struct_span_err!(tcx.sess.diagnostic(), sp, E0722, "{}", s).emit();
2551 match attr.meta().map(|i| i.kind) {
2552 Some(MetaItemKind::Word) => {
2553 err(attr.span, "expected one argument");
2556 Some(MetaItemKind::List(ref items)) => {
2558 inline_span = Some(attr.span);
2559 if items.len() != 1 {
2560 err(attr.span, "expected one argument");
2562 } else if list_contains_name(&items[..], sym::size) {
2564 } else if list_contains_name(&items[..], sym::speed) {
2567 err(items[0].span(), "invalid argument");
2571 Some(MetaItemKind::NameValue(_)) => ia,
2576 // If a function uses #[target_feature] it can't be inlined into general
2577 // purpose functions as they wouldn't have the right target features
2578 // enabled. For that reason we also forbid #[inline(always)] as it can't be
2580 if !codegen_fn_attrs.target_features.is_empty() {
2581 if codegen_fn_attrs.inline == InlineAttr::Always {
2582 if let Some(span) = inline_span {
2585 "cannot use `#[inline(always)]` with \
2586 `#[target_feature]`",
2592 if !codegen_fn_attrs.no_sanitize.is_empty() {
2593 if codegen_fn_attrs.inline == InlineAttr::Always {
2594 if let (Some(no_sanitize_span), Some(inline_span)) = (no_sanitize_span, inline_span) {
2595 let hir_id = tcx.hir().as_local_hir_id(id.expect_local());
2596 tcx.struct_span_lint_hir(
2597 lint::builtin::INLINE_NO_SANITIZE,
2601 lint.build("`no_sanitize` will have no effect after inlining")
2602 .span_note(inline_span, "inlining requested here")
2610 // Weak lang items have the same semantics as "std internal" symbols in the
2611 // sense that they're preserved through all our LTO passes and only
2612 // strippable by the linker.
2614 // Additionally weak lang items have predetermined symbol names.
2615 if tcx.is_weak_lang_item(id) {
2616 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2618 if let Some(name) = weak_lang_items::link_name(&attrs) {
2619 codegen_fn_attrs.export_name = Some(name);
2620 codegen_fn_attrs.link_name = Some(name);
2622 check_link_name_xor_ordinal(tcx, &codegen_fn_attrs, link_ordinal_span);
2624 // Internal symbols to the standard library all have no_mangle semantics in
2625 // that they have defined symbol names present in the function name. This
2626 // also applies to weak symbols where they all have known symbol names.
2627 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
2628 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2634 /// Checks if the provided DefId is a method in a trait impl for a trait which has track_caller
2635 /// applied to the method prototype.
2636 fn should_inherit_track_caller(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
2637 if let Some(impl_item) = tcx.opt_associated_item(def_id) {
2638 if let ty::AssocItemContainer::ImplContainer(impl_def_id) = impl_item.container {
2639 if let Some(trait_def_id) = tcx.trait_id_of_impl(impl_def_id) {
2640 if let Some(trait_item) = tcx
2641 .associated_items(trait_def_id)
2642 .filter_by_name_unhygienic(impl_item.ident.name)
2643 .find(move |trait_item| {
2644 trait_item.kind == ty::AssocKind::Fn
2645 && tcx.hygienic_eq(impl_item.ident, trait_item.ident, trait_def_id)
2649 .codegen_fn_attrs(trait_item.def_id)
2651 .intersects(CodegenFnAttrFlags::TRACK_CALLER);
2660 fn check_link_ordinal(tcx: TyCtxt<'_>, attr: &ast::Attribute) -> Option<usize> {
2661 use rustc_ast::ast::{Lit, LitIntType, LitKind};
2662 let meta_item_list = attr.meta_item_list();
2663 let meta_item_list: Option<&[ast::NestedMetaItem]> = meta_item_list.as_ref().map(Vec::as_ref);
2664 let sole_meta_list = match meta_item_list {
2665 Some([item]) => item.literal(),
2668 if let Some(Lit { kind: LitKind::Int(ordinal, LitIntType::Unsuffixed), .. }) = sole_meta_list {
2669 if *ordinal <= usize::MAX as u128 {
2670 Some(*ordinal as usize)
2672 let msg = format!("ordinal value in `link_ordinal` is too large: `{}`", &ordinal);
2674 .struct_span_err(attr.span, &msg)
2675 .note("the value may not exceed `usize::MAX`")
2681 .struct_span_err(attr.span, "illegal ordinal format in `link_ordinal`")
2682 .note("an unsuffixed integer value, e.g., `1`, is expected")
2688 fn check_link_name_xor_ordinal(
2690 codegen_fn_attrs: &CodegenFnAttrs,
2691 inline_span: Option<Span>,
2693 if codegen_fn_attrs.link_name.is_none() || codegen_fn_attrs.link_ordinal.is_none() {
2696 let msg = "cannot use `#[link_name]` with `#[link_ordinal]`";
2697 if let Some(span) = inline_span {
2698 tcx.sess.span_err(span, msg);
2704 /// Checks the function annotated with `#[target_feature]` is unsafe,
2705 /// reporting an error if it isn't.
2706 fn check_target_feature_safe_fn(tcx: TyCtxt<'_>, id: DefId, attr_span: Span) {
2707 if tcx.is_closure(id) || tcx.fn_sig(id).unsafety() == hir::Unsafety::Normal {
2708 let mut err = feature_err(
2709 &tcx.sess.parse_sess,
2710 sym::target_feature_11,
2712 "`#[target_feature(..)]` can only be applied to `unsafe` functions",
2714 err.span_label(tcx.def_span(id), "not an `unsafe` function");
2719 /// Checks the function annotated with `#[target_feature]` is not a safe
2720 /// trait method implementation, reporting an error if it is.
2721 fn check_target_feature_trait_unsafe(tcx: TyCtxt<'_>, id: LocalDefId, attr_span: Span) {
2722 let hir_id = tcx.hir().as_local_hir_id(id);
2723 let node = tcx.hir().get(hir_id);
2724 if let Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }) = node {
2725 let parent_id = tcx.hir().get_parent_item(hir_id);
2726 let parent_item = tcx.hir().expect_item(parent_id);
2727 if let hir::ItemKind::Impl { of_trait: Some(_), .. } = parent_item.kind {
2731 "`#[target_feature(..)]` cannot be applied to safe trait method",
2733 .span_label(attr_span, "cannot be applied to safe trait method")
2734 .span_label(tcx.def_span(id), "not an `unsafe` function")