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::lang_items;
21 use crate::middle::resolve_lifetime as rl;
23 use rustc_ast::ast::{Ident, MetaItemKind};
24 use rustc_attr::{list_contains_name, mark_used, InlineAttr, OptimizeAttr};
25 use rustc_data_structures::captures::Captures;
26 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
27 use rustc_errors::{struct_span_err, Applicability};
29 use rustc_hir::def::{CtorKind, DefKind, Res};
30 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
31 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
32 use rustc_hir::{GenericParamKind, Node, Unsafety};
33 use rustc_middle::hir::map::blocks::FnLikeNode;
34 use rustc_middle::hir::map::Map;
35 use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
36 use rustc_middle::mir::mono::Linkage;
37 use rustc_middle::ty::query::Providers;
38 use rustc_middle::ty::subst::{InternalSubsts, Subst};
39 use rustc_middle::ty::util::Discr;
40 use rustc_middle::ty::util::IntTypeExt;
41 use rustc_middle::ty::{self, AdtKind, Const, ToPolyTraitRef, Ty, TyCtxt};
42 use rustc_middle::ty::{ReprOptions, ToPredicate, WithConstness};
43 use rustc_session::lint;
44 use rustc_session::parse::feature_err;
45 use rustc_span::symbol::{kw, sym, Symbol};
46 use rustc_span::{Span, DUMMY_SP};
47 use rustc_target::spec::abi;
51 struct OnlySelfBounds(bool);
53 ///////////////////////////////////////////////////////////////////////////
56 fn collect_mod_item_types(tcx: TyCtxt<'_>, module_def_id: DefId) {
57 tcx.hir().visit_item_likes_in_module(
59 &mut CollectItemTypesVisitor { tcx }.as_deep_visitor(),
63 pub fn provide(providers: &mut Providers<'_>) {
64 *providers = Providers {
65 type_of: type_of::type_of,
68 predicates_defined_on,
69 explicit_predicates_of,
71 type_param_predicates,
81 collect_mod_item_types,
86 ///////////////////////////////////////////////////////////////////////////
88 /// Context specific to some particular item. This is what implements
89 /// `AstConv`. It has information about the predicates that are defined
90 /// on the trait. Unfortunately, this predicate information is
91 /// available in various different forms at various points in the
92 /// process. So we can't just store a pointer to e.g., the AST or the
93 /// parsed ty form, we have to be more flexible. To this end, the
94 /// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy
95 /// `get_type_parameter_bounds` requests, drawing the information from
96 /// the AST (`hir::Generics`), recursively.
97 pub struct ItemCtxt<'tcx> {
102 ///////////////////////////////////////////////////////////////////////////
105 crate struct PlaceholderHirTyCollector(crate Vec<Span>);
107 impl<'v> Visitor<'v> for PlaceholderHirTyCollector {
108 type Map = intravisit::ErasedMap<'v>;
110 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
111 NestedVisitorMap::None
113 fn visit_ty(&mut self, t: &'v hir::Ty<'v>) {
114 if let hir::TyKind::Infer = t.kind {
117 intravisit::walk_ty(self, t)
121 struct CollectItemTypesVisitor<'tcx> {
125 /// If there are any placeholder types (`_`), emit an error explaining that this is not allowed
126 /// and suggest adding type parameters in the appropriate place, taking into consideration any and
127 /// all already existing generic type parameters to avoid suggesting a name that is already in use.
128 crate fn placeholder_type_error(
131 generics: &[hir::GenericParam<'_>],
132 placeholder_types: Vec<Span>,
135 if placeholder_types.is_empty() {
138 // This is the whitelist of possible parameter names that we might suggest.
139 let possible_names = ["T", "K", "L", "A", "B", "C"];
140 let used_names = generics
142 .filter_map(|p| match p.name {
143 hir::ParamName::Plain(ident) => Some(ident.name),
146 .collect::<Vec<_>>();
148 let type_name = possible_names
150 .find(|n| !used_names.contains(&Symbol::intern(n)))
151 .unwrap_or(&"ParamName");
153 let mut sugg: Vec<_> =
154 placeholder_types.iter().map(|sp| (*sp, (*type_name).to_string())).collect();
155 if generics.is_empty() {
156 sugg.push((span, format!("<{}>", type_name)));
157 } else if let Some(arg) = generics.iter().find(|arg| match arg.name {
158 hir::ParamName::Plain(Ident { name: kw::Underscore, .. }) => true,
161 // Account for `_` already present in cases like `struct S<_>(_);` and suggest
162 // `struct S<T>(T);` instead of `struct S<_, T>(T);`.
163 sugg.push((arg.span, (*type_name).to_string()));
165 let last = generics.iter().last().unwrap();
167 // Account for bounds, we want `fn foo<T: E, K>(_: K)` not `fn foo<T, K: E>(_: K)`.
168 last.bounds_span().unwrap_or(last.span).shrink_to_hi(),
169 format!(", {}", type_name),
172 let mut err = bad_placeholder_type(tcx, placeholder_types);
174 err.multipart_suggestion(
175 "use type parameters instead",
177 Applicability::HasPlaceholders,
183 fn reject_placeholder_type_signatures_in_item(tcx: TyCtxt<'tcx>, item: &'tcx hir::Item<'tcx>) {
184 let (generics, suggest) = match &item.kind {
185 hir::ItemKind::Union(_, generics)
186 | hir::ItemKind::Enum(_, generics)
187 | hir::ItemKind::TraitAlias(generics, _)
188 | hir::ItemKind::Trait(_, _, generics, ..)
189 | hir::ItemKind::Impl { generics, .. }
190 | hir::ItemKind::Struct(_, generics) => (generics, true),
191 hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. })
192 | hir::ItemKind::TyAlias(_, generics) => (generics, false),
193 // `static`, `fn` and `const` are handled elsewhere to suggest appropriate type.
197 let mut visitor = PlaceholderHirTyCollector::default();
198 visitor.visit_item(item);
200 placeholder_type_error(tcx, generics.span, &generics.params[..], visitor.0, suggest);
203 impl Visitor<'tcx> for CollectItemTypesVisitor<'tcx> {
204 type Map = Map<'tcx>;
206 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
207 NestedVisitorMap::OnlyBodies(self.tcx.hir())
210 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
211 convert_item(self.tcx, item.hir_id);
212 reject_placeholder_type_signatures_in_item(self.tcx, item);
213 intravisit::walk_item(self, item);
216 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
217 for param in generics.params {
219 hir::GenericParamKind::Lifetime { .. } => {}
220 hir::GenericParamKind::Type { default: Some(_), .. } => {
221 let def_id = self.tcx.hir().local_def_id(param.hir_id);
222 self.tcx.type_of(def_id);
224 hir::GenericParamKind::Type { .. } => {}
225 hir::GenericParamKind::Const { .. } => {
226 let def_id = self.tcx.hir().local_def_id(param.hir_id);
227 self.tcx.type_of(def_id);
231 intravisit::walk_generics(self, generics);
234 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
235 if let hir::ExprKind::Closure(..) = expr.kind {
236 let def_id = self.tcx.hir().local_def_id(expr.hir_id);
237 self.tcx.generics_of(def_id);
238 self.tcx.type_of(def_id);
240 intravisit::walk_expr(self, expr);
243 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
244 convert_trait_item(self.tcx, trait_item.hir_id);
245 intravisit::walk_trait_item(self, trait_item);
248 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
249 convert_impl_item(self.tcx, impl_item.hir_id);
250 intravisit::walk_impl_item(self, impl_item);
254 ///////////////////////////////////////////////////////////////////////////
255 // Utility types and common code for the above passes.
257 fn bad_placeholder_type(
259 mut spans: Vec<Span>,
260 ) -> rustc_errors::DiagnosticBuilder<'tcx> {
262 let mut err = struct_span_err!(
266 "the type placeholder `_` is not allowed within types on item signatures",
269 err.span_label(span, "not allowed in type signatures");
274 impl ItemCtxt<'tcx> {
275 pub fn new(tcx: TyCtxt<'tcx>, item_def_id: DefId) -> ItemCtxt<'tcx> {
276 ItemCtxt { tcx, item_def_id }
279 pub fn to_ty(&self, ast_ty: &'tcx hir::Ty<'tcx>) -> Ty<'tcx> {
280 AstConv::ast_ty_to_ty(self, ast_ty)
283 pub fn hir_id(&self) -> hir::HirId {
286 .as_local_hir_id(self.item_def_id)
287 .expect("Non-local call to local provider is_const_fn")
290 pub fn node(&self) -> hir::Node<'tcx> {
291 self.tcx.hir().get(self.hir_id())
295 impl AstConv<'tcx> for ItemCtxt<'tcx> {
296 fn tcx(&self) -> TyCtxt<'tcx> {
300 fn item_def_id(&self) -> Option<DefId> {
301 Some(self.item_def_id)
304 fn default_constness_for_trait_bounds(&self) -> hir::Constness {
305 if let Some(fn_like) = FnLikeNode::from_node(self.node()) {
308 hir::Constness::NotConst
312 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId) -> ty::GenericPredicates<'tcx> {
313 self.tcx.at(span).type_param_predicates((self.item_def_id, def_id))
316 fn re_infer(&self, _: Option<&ty::GenericParamDef>, _: Span) -> Option<ty::Region<'tcx>> {
320 fn allow_ty_infer(&self) -> bool {
324 fn ty_infer(&self, _: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx> {
325 self.tcx().sess.delay_span_bug(span, "bad placeholder type");
332 _: Option<&ty::GenericParamDef>,
334 ) -> &'tcx Const<'tcx> {
335 bad_placeholder_type(self.tcx(), vec![span]).emit();
337 self.tcx().consts.err
340 fn projected_ty_from_poly_trait_ref(
344 item_segment: &hir::PathSegment<'_>,
345 poly_trait_ref: ty::PolyTraitRef<'tcx>,
347 if let Some(trait_ref) = poly_trait_ref.no_bound_vars() {
348 let item_substs = <dyn AstConv<'tcx>>::create_substs_for_associated_item(
356 self.tcx().mk_projection(item_def_id, item_substs)
358 // There are no late-bound regions; we can just ignore the binder.
359 let mut err = struct_span_err!(
363 "cannot extract an associated type from a higher-ranked trait bound \
368 hir::Node::Field(_) | hir::Node::Ctor(_) | hir::Node::Variant(_) => {
370 self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(self.hir_id()));
372 hir::ItemKind::Enum(_, generics)
373 | hir::ItemKind::Struct(_, generics)
374 | hir::ItemKind::Union(_, generics) => {
375 let lt_name = get_new_lifetime_name(self.tcx, poly_trait_ref, generics);
376 let (lt_sp, sugg) = match &generics.params[..] {
377 [] => (generics.span, format!("<{}>", lt_name)),
379 (bound.span.shrink_to_lo(), format!("{}, ", lt_name))
382 let suggestions = vec![
388 // Replace the existing lifetimes with a new named lifetime.
390 .replace_late_bound_regions(&poly_trait_ref, |_| {
391 self.tcx.mk_region(ty::ReEarlyBound(
392 ty::EarlyBoundRegion {
395 name: Symbol::intern(<_name),
404 err.multipart_suggestion(
405 "use a fully qualified path with explicit lifetimes",
407 Applicability::MaybeIncorrect,
413 hir::Node::Item(hir::Item { kind: hir::ItemKind::Struct(..), .. })
414 | hir::Node::Item(hir::Item { kind: hir::ItemKind::Enum(..), .. })
415 | hir::Node::Item(hir::Item { kind: hir::ItemKind::Union(..), .. }) => {}
417 | hir::Node::ForeignItem(_)
418 | hir::Node::TraitItem(_)
419 | hir::Node::ImplItem(_) => {
422 "use a fully qualified path with inferred lifetimes",
425 // Erase named lt, we want `<A as B<'_>::C`, not `<A as B<'a>::C`.
426 self.tcx.anonymize_late_bound_regions(&poly_trait_ref).skip_binder(),
429 Applicability::MaybeIncorrect,
439 fn normalize_ty(&self, _span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
440 // Types in item signatures are not normalized to avoid undue dependencies.
444 fn set_tainted_by_errors(&self) {
445 // There's no obvious place to track this, so just let it go.
448 fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) {
449 // There's no place to record types from signatures?
453 /// Synthesize a new lifetime name that doesn't clash with any of the lifetimes already present.
454 fn get_new_lifetime_name<'tcx>(
456 poly_trait_ref: ty::PolyTraitRef<'tcx>,
457 generics: &hir::Generics<'tcx>,
459 let existing_lifetimes = tcx
460 .collect_referenced_late_bound_regions(&poly_trait_ref)
463 if let ty::BoundRegion::BrNamed(_, name) = lt {
464 Some(name.as_str().to_string())
469 .chain(generics.params.iter().filter_map(|param| {
470 if let hir::GenericParamKind::Lifetime { .. } = ¶m.kind {
471 Some(param.name.ident().as_str().to_string())
476 .collect::<FxHashSet<String>>();
478 let a_to_z_repeat_n = |n| {
479 (b'a'..=b'z').map(move |c| {
480 let mut s = '\''.to_string();
481 s.extend(std::iter::repeat(char::from(c)).take(n));
486 // If all single char lifetime names are present, we wrap around and double the chars.
487 (1..).flat_map(a_to_z_repeat_n).find(|lt| !existing_lifetimes.contains(lt.as_str())).unwrap()
490 /// Returns the predicates defined on `item_def_id` of the form
491 /// `X: Foo` where `X` is the type parameter `def_id`.
492 fn type_param_predicates(
494 (item_def_id, def_id): (DefId, DefId),
495 ) -> ty::GenericPredicates<'_> {
498 // In the AST, bounds can derive from two places. Either
499 // written inline like `<T: Foo>` or in a where-clause like
502 let param_id = tcx.hir().as_local_hir_id(def_id).unwrap();
503 let param_owner = tcx.hir().ty_param_owner(param_id);
504 let param_owner_def_id = tcx.hir().local_def_id(param_owner);
505 let generics = tcx.generics_of(param_owner_def_id);
506 let index = generics.param_def_id_to_index[&def_id];
507 let ty = tcx.mk_ty_param(index, tcx.hir().ty_param_name(param_id));
509 // Don't look for bounds where the type parameter isn't in scope.
511 if item_def_id == param_owner_def_id { None } else { tcx.generics_of(item_def_id).parent };
513 let mut result = parent
515 let icx = ItemCtxt::new(tcx, parent);
516 icx.get_type_parameter_bounds(DUMMY_SP, def_id)
518 .unwrap_or_default();
519 let mut extend = None;
521 let item_hir_id = tcx.hir().as_local_hir_id(item_def_id).unwrap();
522 let ast_generics = match tcx.hir().get(item_hir_id) {
523 Node::TraitItem(item) => &item.generics,
525 Node::ImplItem(item) => &item.generics,
527 Node::Item(item) => {
529 ItemKind::Fn(.., ref generics, _)
530 | ItemKind::Impl { ref generics, .. }
531 | ItemKind::TyAlias(_, ref generics)
532 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
533 | ItemKind::Enum(_, ref generics)
534 | ItemKind::Struct(_, ref generics)
535 | ItemKind::Union(_, ref generics) => generics,
536 ItemKind::Trait(_, _, ref generics, ..) => {
537 // Implied `Self: Trait` and supertrait bounds.
538 if param_id == item_hir_id {
539 let identity_trait_ref = ty::TraitRef::identity(tcx, item_def_id);
541 Some((identity_trait_ref.without_const().to_predicate(), item.span));
549 Node::ForeignItem(item) => match item.kind {
550 ForeignItemKind::Fn(_, _, ref generics) => generics,
557 let icx = ItemCtxt::new(tcx, item_def_id);
558 let extra_predicates = extend.into_iter().chain(
559 icx.type_parameter_bounds_in_generics(ast_generics, param_id, ty, OnlySelfBounds(true))
561 .filter(|(predicate, _)| match predicate {
562 ty::Predicate::Trait(ref data, _) => data.skip_binder().self_ty().is_param(index),
567 tcx.arena.alloc_from_iter(result.predicates.iter().copied().chain(extra_predicates));
571 impl ItemCtxt<'tcx> {
572 /// Finds bounds from `hir::Generics`. This requires scanning through the
573 /// AST. We do this to avoid having to convert *all* the bounds, which
574 /// would create artificial cycles. Instead, we can only convert the
575 /// bounds for a type parameter `X` if `X::Foo` is used.
576 fn type_parameter_bounds_in_generics(
578 ast_generics: &'tcx hir::Generics<'tcx>,
579 param_id: hir::HirId,
581 only_self_bounds: OnlySelfBounds,
582 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
583 let constness = self.default_constness_for_trait_bounds();
584 let from_ty_params = ast_generics
587 .filter_map(|param| match param.kind {
588 GenericParamKind::Type { .. } if param.hir_id == param_id => Some(¶m.bounds),
591 .flat_map(|bounds| bounds.iter())
592 .flat_map(|b| predicates_from_bound(self, ty, b, constness));
594 let from_where_clauses = ast_generics
598 .filter_map(|wp| match *wp {
599 hir::WherePredicate::BoundPredicate(ref bp) => Some(bp),
603 let bt = if is_param(self.tcx, &bp.bounded_ty, param_id) {
605 } else if !only_self_bounds.0 {
606 Some(self.to_ty(&bp.bounded_ty))
610 bp.bounds.iter().filter_map(move |b| bt.map(|bt| (bt, b)))
612 .flat_map(|(bt, b)| predicates_from_bound(self, bt, b, constness));
614 from_ty_params.chain(from_where_clauses).collect()
618 /// Tests whether this is the AST for a reference to the type
619 /// parameter with ID `param_id`. We use this so as to avoid running
620 /// `ast_ty_to_ty`, because we want to avoid triggering an all-out
621 /// conversion of the type to avoid inducing unnecessary cycles.
622 fn is_param(tcx: TyCtxt<'_>, ast_ty: &hir::Ty<'_>, param_id: hir::HirId) -> bool {
623 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = ast_ty.kind {
625 Res::SelfTy(Some(def_id), None) | Res::Def(DefKind::TyParam, def_id) => {
626 def_id == tcx.hir().local_def_id(param_id)
635 fn convert_item(tcx: TyCtxt<'_>, item_id: hir::HirId) {
636 let it = tcx.hir().expect_item(item_id);
637 debug!("convert: item {} with id {}", it.ident, it.hir_id);
638 let def_id = tcx.hir().local_def_id(item_id);
640 // These don't define types.
641 hir::ItemKind::ExternCrate(_)
642 | hir::ItemKind::Use(..)
643 | hir::ItemKind::Mod(_)
644 | hir::ItemKind::GlobalAsm(_) => {}
645 hir::ItemKind::ForeignMod(ref foreign_mod) => {
646 for item in foreign_mod.items {
647 let def_id = tcx.hir().local_def_id(item.hir_id);
648 tcx.generics_of(def_id);
650 tcx.predicates_of(def_id);
651 if let hir::ForeignItemKind::Fn(..) = item.kind {
656 hir::ItemKind::Enum(ref enum_definition, _) => {
657 tcx.generics_of(def_id);
659 tcx.predicates_of(def_id);
660 convert_enum_variant_types(tcx, def_id, &enum_definition.variants);
662 hir::ItemKind::Impl { .. } => {
663 tcx.generics_of(def_id);
665 tcx.impl_trait_ref(def_id);
666 tcx.predicates_of(def_id);
668 hir::ItemKind::Trait(..) => {
669 tcx.generics_of(def_id);
670 tcx.trait_def(def_id);
671 tcx.at(it.span).super_predicates_of(def_id);
672 tcx.predicates_of(def_id);
674 hir::ItemKind::TraitAlias(..) => {
675 tcx.generics_of(def_id);
676 tcx.at(it.span).super_predicates_of(def_id);
677 tcx.predicates_of(def_id);
679 hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
680 tcx.generics_of(def_id);
682 tcx.predicates_of(def_id);
684 for f in struct_def.fields() {
685 let def_id = tcx.hir().local_def_id(f.hir_id);
686 tcx.generics_of(def_id);
688 tcx.predicates_of(def_id);
691 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
692 convert_variant_ctor(tcx, ctor_hir_id);
696 // Desugared from `impl Trait`, so visited by the function's return type.
697 hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: Some(_), .. }) => {}
699 hir::ItemKind::OpaqueTy(..)
700 | hir::ItemKind::TyAlias(..)
701 | hir::ItemKind::Static(..)
702 | hir::ItemKind::Const(..)
703 | hir::ItemKind::Fn(..) => {
704 tcx.generics_of(def_id);
706 tcx.predicates_of(def_id);
707 if let hir::ItemKind::Fn(..) = it.kind {
714 fn convert_trait_item(tcx: TyCtxt<'_>, trait_item_id: hir::HirId) {
715 let trait_item = tcx.hir().expect_trait_item(trait_item_id);
716 let def_id = tcx.hir().local_def_id(trait_item.hir_id);
717 tcx.generics_of(def_id);
719 match trait_item.kind {
720 hir::TraitItemKind::Fn(..) => {
725 hir::TraitItemKind::Const(.., Some(_)) => {
729 hir::TraitItemKind::Const(..) | hir::TraitItemKind::Type(_, Some(_)) => {
731 // Account for `const C: _;` and `type T = _;`.
732 let mut visitor = PlaceholderHirTyCollector::default();
733 visitor.visit_trait_item(trait_item);
734 placeholder_type_error(tcx, DUMMY_SP, &[], visitor.0, false);
737 hir::TraitItemKind::Type(_, None) => {}
740 tcx.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.generics_of(def_id);
747 tcx.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(..) => {
753 hir::ImplItemKind::TyAlias(_) | hir::ImplItemKind::OpaqueTy(_) => {
754 // Account for `type T = _;`
755 let mut visitor = PlaceholderHirTyCollector::default();
756 visitor.visit_impl_item(impl_item);
757 placeholder_type_error(tcx, DUMMY_SP, &[], 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.generics_of(def_id);
767 tcx.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)
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.generics_of(def_id);
805 tcx.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<DefId>,
819 ctor_did: Option<DefId>,
821 discr: ty::VariantDiscr,
822 def: &hir::VariantData<'_>,
823 adt_kind: ty::AdtKind,
825 ) -> ty::VariantDef {
826 let mut seen_fields: FxHashMap<ast::Ident, Span> = Default::default();
827 let hir_id = tcx.hir().as_local_hir_id(variant_did.unwrap_or(parent_did)).unwrap();
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);
852 vis: ty::Visibility::from_hir(&f.vis, hir_id, tcx),
856 let recovered = match def {
857 hir::VariantData::Struct(_, r) => *r,
867 CtorKind::from_hir(def),
874 fn adt_def(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::AdtDef {
877 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
878 let item = match tcx.hir().get(hir_id) {
879 Node::Item(item) => item,
883 let repr = ReprOptions::new(tcx, def_id);
884 let (kind, variants) = match item.kind {
885 ItemKind::Enum(ref def, _) => {
886 let mut distance_from_explicit = 0;
891 let variant_did = Some(tcx.hir().local_def_id(v.id));
893 v.data.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
895 let discr = if let Some(ref e) = v.disr_expr {
896 distance_from_explicit = 0;
897 ty::VariantDiscr::Explicit(tcx.hir().local_def_id(e.hir_id))
899 ty::VariantDiscr::Relative(distance_from_explicit)
901 distance_from_explicit += 1;
916 (AdtKind::Enum, variants)
918 ItemKind::Struct(ref def, _) => {
919 let variant_did = None;
920 let ctor_did = def.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
922 let variants = std::iter::once(convert_variant(
927 ty::VariantDiscr::Relative(0),
934 (AdtKind::Struct, variants)
936 ItemKind::Union(ref def, _) => {
937 let variant_did = None;
938 let ctor_did = def.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
940 let variants = std::iter::once(convert_variant(
945 ty::VariantDiscr::Relative(0),
952 (AdtKind::Union, variants)
956 tcx.alloc_adt_def(def_id, kind, variants, repr)
959 /// Ensures that the super-predicates of the trait with a `DefId`
960 /// of `trait_def_id` are converted and stored. This also ensures that
961 /// the transitive super-predicates are converted.
962 fn super_predicates_of(tcx: TyCtxt<'_>, trait_def_id: DefId) -> ty::GenericPredicates<'_> {
963 debug!("super_predicates(trait_def_id={:?})", trait_def_id);
964 let trait_hir_id = tcx.hir().as_local_hir_id(trait_def_id).unwrap();
966 let item = match tcx.hir().get(trait_hir_id) {
967 Node::Item(item) => item,
968 _ => bug!("trait_node_id {} is not an item", trait_hir_id),
971 let (generics, bounds) = match item.kind {
972 hir::ItemKind::Trait(.., ref generics, ref supertraits, _) => (generics, supertraits),
973 hir::ItemKind::TraitAlias(ref generics, ref supertraits) => (generics, supertraits),
974 _ => span_bug!(item.span, "super_predicates invoked on non-trait"),
977 let icx = ItemCtxt::new(tcx, trait_def_id);
979 // Convert the bounds that follow the colon, e.g., `Bar + Zed` in `trait Foo: Bar + Zed`.
980 let self_param_ty = tcx.types.self_param;
982 AstConv::compute_bounds(&icx, self_param_ty, bounds, SizedByDefault::No, item.span);
984 let superbounds1 = superbounds1.predicates(tcx, self_param_ty);
986 // Convert any explicit superbounds in the where-clause,
987 // e.g., `trait Foo where Self: Bar`.
988 // In the case of trait aliases, however, we include all bounds in the where-clause,
989 // so e.g., `trait Foo = where u32: PartialEq<Self>` would include `u32: PartialEq<Self>`
990 // as one of its "superpredicates".
991 let is_trait_alias = tcx.is_trait_alias(trait_def_id);
992 let superbounds2 = icx.type_parameter_bounds_in_generics(
996 OnlySelfBounds(!is_trait_alias),
999 // Combine the two lists to form the complete set of superbounds:
1000 let superbounds = &*tcx.arena.alloc_from_iter(superbounds1.into_iter().chain(superbounds2));
1002 // Now require that immediate supertraits are converted,
1003 // which will, in turn, reach indirect supertraits.
1004 for &(pred, span) in superbounds {
1005 debug!("superbound: {:?}", pred);
1006 if let ty::Predicate::Trait(bound, _) = pred {
1007 tcx.at(span).super_predicates_of(bound.def_id());
1011 ty::GenericPredicates { parent: None, predicates: superbounds }
1014 fn trait_def(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::TraitDef {
1015 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1016 let item = tcx.hir().expect_item(hir_id);
1018 let (is_auto, unsafety) = match item.kind {
1019 hir::ItemKind::Trait(is_auto, unsafety, ..) => (is_auto == hir::IsAuto::Yes, unsafety),
1020 hir::ItemKind::TraitAlias(..) => (false, hir::Unsafety::Normal),
1021 _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
1024 let paren_sugar = tcx.has_attr(def_id, sym::rustc_paren_sugar);
1025 if paren_sugar && !tcx.features().unboxed_closures {
1029 "the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \
1030 which traits can use parenthetical notation",
1032 .help("add `#![feature(unboxed_closures)]` to the crate attributes to use it")
1036 let is_marker = tcx.has_attr(def_id, sym::marker);
1037 let spec_kind = if tcx.has_attr(def_id, sym::rustc_unsafe_specialization_marker) {
1038 ty::trait_def::TraitSpecializationKind::Marker
1039 } else if tcx.has_attr(def_id, sym::rustc_specialization_trait) {
1040 ty::trait_def::TraitSpecializationKind::AlwaysApplicable
1042 ty::trait_def::TraitSpecializationKind::None
1044 let def_path_hash = tcx.def_path_hash(def_id);
1045 let def = ty::TraitDef::new(
1054 tcx.arena.alloc(def)
1057 fn has_late_bound_regions<'tcx>(tcx: TyCtxt<'tcx>, node: Node<'tcx>) -> Option<Span> {
1058 struct LateBoundRegionsDetector<'tcx> {
1060 outer_index: ty::DebruijnIndex,
1061 has_late_bound_regions: Option<Span>,
1064 impl Visitor<'tcx> for LateBoundRegionsDetector<'tcx> {
1065 type Map = intravisit::ErasedMap<'tcx>;
1067 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1068 NestedVisitorMap::None
1071 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
1072 if self.has_late_bound_regions.is_some() {
1076 hir::TyKind::BareFn(..) => {
1077 self.outer_index.shift_in(1);
1078 intravisit::walk_ty(self, ty);
1079 self.outer_index.shift_out(1);
1081 _ => intravisit::walk_ty(self, ty),
1085 fn visit_poly_trait_ref(
1087 tr: &'tcx hir::PolyTraitRef<'tcx>,
1088 m: hir::TraitBoundModifier,
1090 if self.has_late_bound_regions.is_some() {
1093 self.outer_index.shift_in(1);
1094 intravisit::walk_poly_trait_ref(self, tr, m);
1095 self.outer_index.shift_out(1);
1098 fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
1099 if self.has_late_bound_regions.is_some() {
1103 match self.tcx.named_region(lt.hir_id) {
1104 Some(rl::Region::Static) | Some(rl::Region::EarlyBound(..)) => {}
1105 Some(rl::Region::LateBound(debruijn, _, _))
1106 | Some(rl::Region::LateBoundAnon(debruijn, _))
1107 if debruijn < self.outer_index => {}
1108 Some(rl::Region::LateBound(..))
1109 | Some(rl::Region::LateBoundAnon(..))
1110 | Some(rl::Region::Free(..))
1112 self.has_late_bound_regions = Some(lt.span);
1118 fn has_late_bound_regions<'tcx>(
1120 generics: &'tcx hir::Generics<'tcx>,
1121 decl: &'tcx hir::FnDecl<'tcx>,
1123 let mut visitor = LateBoundRegionsDetector {
1125 outer_index: ty::INNERMOST,
1126 has_late_bound_regions: None,
1128 for param in generics.params {
1129 if let GenericParamKind::Lifetime { .. } = param.kind {
1130 if tcx.is_late_bound(param.hir_id) {
1131 return Some(param.span);
1135 visitor.visit_fn_decl(decl);
1136 visitor.has_late_bound_regions
1140 Node::TraitItem(item) => match item.kind {
1141 hir::TraitItemKind::Fn(ref sig, _) => {
1142 has_late_bound_regions(tcx, &item.generics, &sig.decl)
1146 Node::ImplItem(item) => match item.kind {
1147 hir::ImplItemKind::Fn(ref sig, _) => {
1148 has_late_bound_regions(tcx, &item.generics, &sig.decl)
1152 Node::ForeignItem(item) => match item.kind {
1153 hir::ForeignItemKind::Fn(ref fn_decl, _, ref generics) => {
1154 has_late_bound_regions(tcx, generics, fn_decl)
1158 Node::Item(item) => match item.kind {
1159 hir::ItemKind::Fn(ref sig, .., ref generics, _) => {
1160 has_late_bound_regions(tcx, generics, &sig.decl)
1168 fn generics_of(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::Generics {
1171 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1173 let node = tcx.hir().get(hir_id);
1174 let parent_def_id = match node {
1176 | Node::TraitItem(_)
1179 | Node::Field(_) => {
1180 let parent_id = tcx.hir().get_parent_item(hir_id);
1181 Some(tcx.hir().local_def_id(parent_id))
1183 // FIXME(#43408) enable this always when we get lazy normalization.
1184 Node::AnonConst(_) => {
1185 // HACK(eddyb) this provides the correct generics when
1186 // `feature(const_generics)` is enabled, so that const expressions
1187 // used with const generics, e.g. `Foo<{N+1}>`, can work at all.
1188 if tcx.features().const_generics {
1189 let parent_id = tcx.hir().get_parent_item(hir_id);
1190 Some(tcx.hir().local_def_id(parent_id))
1195 Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => {
1196 Some(tcx.closure_base_def_id(def_id))
1198 Node::Item(item) => match item.kind {
1199 ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn, .. }) => {
1200 impl_trait_fn.or_else(|| {
1201 let parent_id = tcx.hir().get_parent_item(hir_id);
1202 if parent_id != hir_id && parent_id != CRATE_HIR_ID {
1203 debug!("generics_of: parent of opaque ty {:?} is {:?}", def_id, parent_id);
1204 // If this 'impl Trait' is nested inside another 'impl Trait'
1205 // (e.g. `impl Foo<MyType = impl Bar<A>>`), we need to use the 'parent'
1206 // 'impl Trait' for its generic parameters, since we can reference them
1207 // from the 'child' 'impl Trait'
1208 if let Node::Item(hir::Item { kind: ItemKind::OpaqueTy(..), .. }) =
1209 tcx.hir().get(parent_id)
1211 Some(tcx.hir().local_def_id(parent_id))
1225 let mut opt_self = None;
1226 let mut allow_defaults = false;
1228 let no_generics = hir::Generics::empty();
1229 let ast_generics = match node {
1230 Node::TraitItem(item) => &item.generics,
1232 Node::ImplItem(item) => &item.generics,
1234 Node::Item(item) => {
1236 ItemKind::Fn(.., ref generics, _) | ItemKind::Impl { ref generics, .. } => generics,
1238 ItemKind::TyAlias(_, ref generics)
1239 | ItemKind::Enum(_, ref generics)
1240 | ItemKind::Struct(_, ref generics)
1241 | ItemKind::OpaqueTy(hir::OpaqueTy { ref generics, .. })
1242 | ItemKind::Union(_, ref generics) => {
1243 allow_defaults = true;
1247 ItemKind::Trait(_, _, ref generics, ..)
1248 | ItemKind::TraitAlias(ref generics, ..) => {
1249 // Add in the self type parameter.
1251 // Something of a hack: use the node id for the trait, also as
1252 // the node id for the Self type parameter.
1253 let param_id = item.hir_id;
1255 opt_self = Some(ty::GenericParamDef {
1257 name: kw::SelfUpper,
1258 def_id: tcx.hir().local_def_id(param_id),
1259 pure_wrt_drop: false,
1260 kind: ty::GenericParamDefKind::Type {
1262 object_lifetime_default: rl::Set1::Empty,
1267 allow_defaults = true;
1275 Node::ForeignItem(item) => match item.kind {
1276 ForeignItemKind::Static(..) => &no_generics,
1277 ForeignItemKind::Fn(_, _, ref generics) => generics,
1278 ForeignItemKind::Type => &no_generics,
1284 let has_self = opt_self.is_some();
1285 let mut parent_has_self = false;
1286 let mut own_start = has_self as u32;
1287 let parent_count = parent_def_id.map_or(0, |def_id| {
1288 let generics = tcx.generics_of(def_id);
1289 assert_eq!(has_self, false);
1290 parent_has_self = generics.has_self;
1291 own_start = generics.count() as u32;
1292 generics.parent_count + generics.params.len()
1295 let mut params: Vec<_> = opt_self.into_iter().collect();
1297 let early_lifetimes = early_bound_lifetimes_from_generics(tcx, ast_generics);
1298 params.extend(early_lifetimes.enumerate().map(|(i, param)| ty::GenericParamDef {
1299 name: param.name.ident().name,
1300 index: own_start + i as u32,
1301 def_id: tcx.hir().local_def_id(param.hir_id),
1302 pure_wrt_drop: param.pure_wrt_drop,
1303 kind: ty::GenericParamDefKind::Lifetime,
1306 let object_lifetime_defaults = tcx.object_lifetime_defaults(hir_id);
1308 // Now create the real type and const parameters.
1309 let type_start = own_start - has_self as u32 + params.len() as u32;
1312 // FIXME(const_generics): a few places in the compiler expect generic params
1313 // to be in the order lifetimes, then type params, then const params.
1315 // To prevent internal errors in case const parameters are supplied before
1316 // type parameters we first add all type params, then all const params.
1317 params.extend(ast_generics.params.iter().filter_map(|param| {
1318 if let GenericParamKind::Type { ref default, synthetic, .. } = param.kind {
1319 if !allow_defaults && default.is_some() {
1320 if !tcx.features().default_type_parameter_fallback {
1321 tcx.struct_span_lint_hir(
1322 lint::builtin::INVALID_TYPE_PARAM_DEFAULT,
1327 "defaults for type parameters are only allowed in \
1328 `struct`, `enum`, `type`, or `trait` definitions.",
1336 let kind = ty::GenericParamDefKind::Type {
1337 has_default: default.is_some(),
1338 object_lifetime_default: object_lifetime_defaults
1340 .map_or(rl::Set1::Empty, |o| o[i]),
1344 let param_def = ty::GenericParamDef {
1345 index: type_start + i as u32,
1346 name: param.name.ident().name,
1347 def_id: tcx.hir().local_def_id(param.hir_id),
1348 pure_wrt_drop: param.pure_wrt_drop,
1358 params.extend(ast_generics.params.iter().filter_map(|param| {
1359 if let GenericParamKind::Const { .. } = param.kind {
1360 let param_def = ty::GenericParamDef {
1361 index: type_start + i as u32,
1362 name: param.name.ident().name,
1363 def_id: tcx.hir().local_def_id(param.hir_id),
1364 pure_wrt_drop: param.pure_wrt_drop,
1365 kind: ty::GenericParamDefKind::Const,
1374 // provide junk type parameter defs - the only place that
1375 // cares about anything but the length is instantiation,
1376 // and we don't do that for closures.
1377 if let Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(.., gen), .. }) = node {
1378 let dummy_args = if gen.is_some() {
1379 &["<resume_ty>", "<yield_ty>", "<return_ty>", "<witness>", "<upvars>"][..]
1381 &["<closure_kind>", "<closure_signature>", "<upvars>"][..]
1384 params.extend(dummy_args.iter().enumerate().map(|(i, &arg)| ty::GenericParamDef {
1385 index: type_start + i as u32,
1386 name: Symbol::intern(arg),
1388 pure_wrt_drop: false,
1389 kind: ty::GenericParamDefKind::Type {
1391 object_lifetime_default: rl::Set1::Empty,
1397 let param_def_id_to_index = params.iter().map(|param| (param.def_id, param.index)).collect();
1399 tcx.arena.alloc(ty::Generics {
1400 parent: parent_def_id,
1403 param_def_id_to_index,
1404 has_self: has_self || parent_has_self,
1405 has_late_bound_regions: has_late_bound_regions(tcx, node),
1409 fn are_suggestable_generic_args(generic_args: &[hir::GenericArg<'_>]) -> bool {
1412 .filter_map(|arg| match arg {
1413 hir::GenericArg::Type(ty) => Some(ty),
1416 .any(is_suggestable_infer_ty)
1419 /// Whether `ty` is a type with `_` placeholders that can be inferred. Used in diagnostics only to
1420 /// use inference to provide suggestions for the appropriate type if possible.
1421 fn is_suggestable_infer_ty(ty: &hir::Ty<'_>) -> bool {
1425 Slice(ty) | Array(ty, _) => is_suggestable_infer_ty(ty),
1426 Tup(tys) => tys.iter().any(is_suggestable_infer_ty),
1427 Ptr(mut_ty) | Rptr(_, mut_ty) => is_suggestable_infer_ty(mut_ty.ty),
1428 Def(_, generic_args) => are_suggestable_generic_args(generic_args),
1429 Path(hir::QPath::TypeRelative(ty, segment)) => {
1430 is_suggestable_infer_ty(ty) || are_suggestable_generic_args(segment.generic_args().args)
1432 Path(hir::QPath::Resolved(ty_opt, hir::Path { segments, .. })) => {
1433 ty_opt.map_or(false, is_suggestable_infer_ty)
1436 .any(|segment| are_suggestable_generic_args(segment.generic_args().args))
1442 pub fn get_infer_ret_ty(output: &'hir hir::FnRetTy<'hir>) -> Option<&'hir hir::Ty<'hir>> {
1443 if let hir::FnRetTy::Return(ref ty) = output {
1444 if is_suggestable_infer_ty(ty) {
1451 fn fn_sig(tcx: TyCtxt<'_>, def_id: DefId) -> ty::PolyFnSig<'_> {
1452 use rustc_hir::Node::*;
1455 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1457 let icx = ItemCtxt::new(tcx, def_id);
1459 match tcx.hir().get(hir_id) {
1460 TraitItem(hir::TraitItem {
1461 kind: TraitItemKind::Fn(sig, TraitFn::Provided(_)),
1466 | ImplItem(hir::ImplItem { kind: ImplItemKind::Fn(sig, _), ident, generics, .. })
1467 | Item(hir::Item { kind: ItemKind::Fn(sig, generics, _), ident, .. }) => {
1468 match get_infer_ret_ty(&sig.decl.output) {
1470 let fn_sig = tcx.typeck_tables_of(def_id).liberated_fn_sigs()[hir_id];
1471 let mut visitor = PlaceholderHirTyCollector::default();
1472 visitor.visit_ty(ty);
1473 let mut diag = bad_placeholder_type(tcx, visitor.0);
1474 let ret_ty = fn_sig.output();
1475 if ret_ty != tcx.types.err {
1476 diag.span_suggestion(
1478 "replace with the correct return type",
1480 Applicability::MaybeIncorrect,
1484 ty::Binder::bind(fn_sig)
1486 None => AstConv::ty_of_fn(
1488 sig.header.unsafety,
1497 TraitItem(hir::TraitItem {
1498 kind: TraitItemKind::Fn(FnSig { header, decl }, _),
1503 AstConv::ty_of_fn(&icx, header.unsafety, header.abi, decl, &generics, Some(ident.span))
1506 ForeignItem(&hir::ForeignItem {
1507 kind: ForeignItemKind::Fn(ref fn_decl, _, _),
1511 let abi = tcx.hir().get_foreign_abi(hir_id);
1512 compute_sig_of_foreign_fn_decl(tcx, def_id, fn_decl, abi, ident)
1515 Ctor(data) | Variant(hir::Variant { data, .. }) if data.ctor_hir_id().is_some() => {
1516 let ty = tcx.type_of(tcx.hir().get_parent_did(hir_id));
1518 data.fields().iter().map(|f| tcx.type_of(tcx.hir().local_def_id(f.hir_id)));
1519 ty::Binder::bind(tcx.mk_fn_sig(
1523 hir::Unsafety::Normal,
1528 Expr(&hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => {
1529 // Closure signatures are not like other function
1530 // signatures and cannot be accessed through `fn_sig`. For
1531 // example, a closure signature excludes the `self`
1532 // argument. In any case they are embedded within the
1533 // closure type as part of the `ClosureSubsts`.
1535 // To get the signature of a closure, you should use the
1536 // `sig` method on the `ClosureSubsts`:
1538 // substs.as_closure().sig(def_id, tcx)
1540 "to get the signature of a closure, use `substs.as_closure().sig()` not `fn_sig()`",
1545 bug!("unexpected sort of node in fn_sig(): {:?}", x);
1550 fn impl_trait_ref(tcx: TyCtxt<'_>, def_id: DefId) -> Option<ty::TraitRef<'_>> {
1551 let icx = ItemCtxt::new(tcx, def_id);
1553 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1554 match tcx.hir().expect_item(hir_id).kind {
1555 hir::ItemKind::Impl { ref of_trait, .. } => of_trait.as_ref().map(|ast_trait_ref| {
1556 let selfty = tcx.type_of(def_id);
1557 AstConv::instantiate_mono_trait_ref(&icx, ast_trait_ref, selfty)
1563 fn impl_polarity(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ImplPolarity {
1564 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1565 let is_rustc_reservation = tcx.has_attr(def_id, sym::rustc_reservation_impl);
1566 let item = tcx.hir().expect_item(hir_id);
1568 hir::ItemKind::Impl { polarity: hir::ImplPolarity::Negative(span), of_trait, .. } => {
1569 if is_rustc_reservation {
1570 let span = span.to(of_trait.as_ref().map(|t| t.path.span).unwrap_or(*span));
1571 tcx.sess.span_err(span, "reservation impls can't be negative");
1573 ty::ImplPolarity::Negative
1575 hir::ItemKind::Impl { polarity: hir::ImplPolarity::Positive, of_trait: None, .. } => {
1576 if is_rustc_reservation {
1577 tcx.sess.span_err(item.span, "reservation impls can't be inherent");
1579 ty::ImplPolarity::Positive
1581 hir::ItemKind::Impl {
1582 polarity: hir::ImplPolarity::Positive, of_trait: Some(_), ..
1584 if is_rustc_reservation {
1585 ty::ImplPolarity::Reservation
1587 ty::ImplPolarity::Positive
1590 ref item => bug!("impl_polarity: {:?} not an impl", item),
1594 /// Returns the early-bound lifetimes declared in this generics
1595 /// listing. For anything other than fns/methods, this is just all
1596 /// the lifetimes that are declared. For fns or methods, we have to
1597 /// screen out those that do not appear in any where-clauses etc using
1598 /// `resolve_lifetime::early_bound_lifetimes`.
1599 fn early_bound_lifetimes_from_generics<'a, 'tcx: 'a>(
1601 generics: &'a hir::Generics<'a>,
1602 ) -> impl Iterator<Item = &'a hir::GenericParam<'a>> + Captures<'tcx> {
1603 generics.params.iter().filter(move |param| match param.kind {
1604 GenericParamKind::Lifetime { .. } => !tcx.is_late_bound(param.hir_id),
1609 /// Returns a list of type predicates for the definition with ID `def_id`, including inferred
1610 /// lifetime constraints. This includes all predicates returned by `explicit_predicates_of`, plus
1611 /// inferred constraints concerning which regions outlive other regions.
1612 fn predicates_defined_on(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1613 debug!("predicates_defined_on({:?})", def_id);
1614 let mut result = tcx.explicit_predicates_of(def_id);
1615 debug!("predicates_defined_on: explicit_predicates_of({:?}) = {:?}", def_id, result,);
1616 let inferred_outlives = tcx.inferred_outlives_of(def_id);
1617 if !inferred_outlives.is_empty() {
1619 "predicates_defined_on: inferred_outlives_of({:?}) = {:?}",
1620 def_id, inferred_outlives,
1622 if result.predicates.is_empty() {
1623 result.predicates = inferred_outlives;
1625 result.predicates = tcx
1627 .alloc_from_iter(result.predicates.iter().chain(inferred_outlives).copied());
1630 debug!("predicates_defined_on({:?}) = {:?}", def_id, result);
1634 /// Returns a list of all type predicates (explicit and implicit) for the definition with
1635 /// ID `def_id`. This includes all predicates returned by `predicates_defined_on`, plus
1636 /// `Self: Trait` predicates for traits.
1637 fn predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1638 let mut result = tcx.predicates_defined_on(def_id);
1640 if tcx.is_trait(def_id) {
1641 // For traits, add `Self: Trait` predicate. This is
1642 // not part of the predicates that a user writes, but it
1643 // is something that one must prove in order to invoke a
1644 // method or project an associated type.
1646 // In the chalk setup, this predicate is not part of the
1647 // "predicates" for a trait item. But it is useful in
1648 // rustc because if you directly (e.g.) invoke a trait
1649 // method like `Trait::method(...)`, you must naturally
1650 // prove that the trait applies to the types that were
1651 // used, and adding the predicate into this list ensures
1652 // that this is done.
1653 let span = tcx.def_span(def_id);
1655 tcx.arena.alloc_from_iter(result.predicates.iter().copied().chain(std::iter::once((
1656 ty::TraitRef::identity(tcx, def_id).without_const().to_predicate(),
1660 debug!("predicates_of(def_id={:?}) = {:?}", def_id, result);
1664 /// Returns a list of user-specified type predicates for the definition with ID `def_id`.
1665 /// N.B., this does not include any implied/inferred constraints.
1666 fn explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1669 debug!("explicit_predicates_of(def_id={:?})", def_id);
1671 /// A data structure with unique elements, which preserves order of insertion.
1672 /// Preserving the order of insertion is important here so as not to break
1673 /// compile-fail UI tests.
1674 // FIXME(eddyb) just use `IndexSet` from `indexmap`.
1675 struct UniquePredicates<'tcx> {
1676 predicates: Vec<(ty::Predicate<'tcx>, Span)>,
1677 uniques: FxHashSet<(ty::Predicate<'tcx>, Span)>,
1680 impl<'tcx> UniquePredicates<'tcx> {
1682 UniquePredicates { predicates: vec![], uniques: FxHashSet::default() }
1685 fn push(&mut self, value: (ty::Predicate<'tcx>, Span)) {
1686 if self.uniques.insert(value) {
1687 self.predicates.push(value);
1691 fn extend<I: IntoIterator<Item = (ty::Predicate<'tcx>, Span)>>(&mut self, iter: I) {
1698 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1699 let node = tcx.hir().get(hir_id);
1701 let mut is_trait = None;
1702 let mut is_default_impl_trait = None;
1704 let icx = ItemCtxt::new(tcx, def_id);
1705 let constness = icx.default_constness_for_trait_bounds();
1707 const NO_GENERICS: &hir::Generics<'_> = &hir::Generics::empty();
1709 let mut predicates = UniquePredicates::new();
1711 let ast_generics = match node {
1712 Node::TraitItem(item) => &item.generics,
1714 Node::ImplItem(item) => match item.kind {
1715 ImplItemKind::OpaqueTy(ref bounds) => {
1716 ty::print::with_no_queries(|| {
1717 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1718 let opaque_ty = tcx.mk_opaque(def_id, substs);
1720 "explicit_predicates_of({:?}): created opaque type {:?}",
1724 // Collect the bounds, i.e., the `A + B + 'c` in `impl A + B + 'c`.
1725 let bounds = AstConv::compute_bounds(
1729 SizedByDefault::Yes,
1730 tcx.def_span(def_id),
1733 predicates.extend(bounds.predicates(tcx, opaque_ty));
1737 _ => &item.generics,
1740 Node::Item(item) => {
1742 ItemKind::Impl { defaultness, ref generics, .. } => {
1743 if defaultness.is_default() {
1744 is_default_impl_trait = tcx.impl_trait_ref(def_id);
1748 ItemKind::Fn(.., ref generics, _)
1749 | ItemKind::TyAlias(_, ref generics)
1750 | ItemKind::Enum(_, ref generics)
1751 | ItemKind::Struct(_, ref generics)
1752 | ItemKind::Union(_, ref generics) => generics,
1754 ItemKind::Trait(_, _, ref generics, .., items) => {
1755 is_trait = Some((ty::TraitRef::identity(tcx, def_id), items));
1758 ItemKind::TraitAlias(ref generics, _) => {
1759 is_trait = Some((ty::TraitRef::identity(tcx, def_id), &[]));
1762 ItemKind::OpaqueTy(OpaqueTy {
1768 let bounds_predicates = ty::print::with_no_queries(|| {
1769 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1770 let opaque_ty = tcx.mk_opaque(def_id, substs);
1772 // Collect the bounds, i.e., the `A + B + 'c` in `impl A + B + 'c`.
1773 let bounds = AstConv::compute_bounds(
1777 SizedByDefault::Yes,
1778 tcx.def_span(def_id),
1781 bounds.predicates(tcx, opaque_ty)
1783 if impl_trait_fn.is_some() {
1785 return ty::GenericPredicates {
1787 predicates: tcx.arena.alloc_from_iter(bounds_predicates),
1790 // named opaque types
1791 predicates.extend(bounds_predicates);
1800 Node::ForeignItem(item) => match item.kind {
1801 ForeignItemKind::Static(..) => NO_GENERICS,
1802 ForeignItemKind::Fn(_, _, ref generics) => generics,
1803 ForeignItemKind::Type => NO_GENERICS,
1809 let generics = tcx.generics_of(def_id);
1810 let parent_count = generics.parent_count as u32;
1811 let has_own_self = generics.has_self && parent_count == 0;
1813 // Below we'll consider the bounds on the type parameters (including `Self`)
1814 // and the explicit where-clauses, but to get the full set of predicates
1815 // on a trait we need to add in the supertrait bounds and bounds found on
1816 // associated types.
1817 if let Some((_trait_ref, _)) = is_trait {
1818 predicates.extend(tcx.super_predicates_of(def_id).predicates.iter().cloned());
1821 // In default impls, we can assume that the self type implements
1822 // the trait. So in:
1824 // default impl Foo for Bar { .. }
1826 // we add a default where clause `Foo: Bar`. We do a similar thing for traits
1827 // (see below). Recall that a default impl is not itself an impl, but rather a
1828 // set of defaults that can be incorporated into another impl.
1829 if let Some(trait_ref) = is_default_impl_trait {
1831 trait_ref.to_poly_trait_ref().without_const().to_predicate(),
1832 tcx.def_span(def_id),
1836 // Collect the region predicates that were declared inline as
1837 // well. In the case of parameters declared on a fn or method, we
1838 // have to be careful to only iterate over early-bound regions.
1839 let mut index = parent_count + has_own_self as u32;
1840 for param in early_bound_lifetimes_from_generics(tcx, ast_generics) {
1841 let region = tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
1842 def_id: tcx.hir().local_def_id(param.hir_id),
1844 name: param.name.ident().name,
1849 GenericParamKind::Lifetime { .. } => {
1850 param.bounds.iter().for_each(|bound| match bound {
1851 hir::GenericBound::Outlives(lt) => {
1852 let bound = AstConv::ast_region_to_region(&icx, <, None);
1853 let outlives = ty::Binder::bind(ty::OutlivesPredicate(region, bound));
1854 predicates.push((outlives.to_predicate(), lt.span));
1863 // Collect the predicates that were written inline by the user on each
1864 // type parameter (e.g., `<T: Foo>`).
1865 for param in ast_generics.params {
1866 if let GenericParamKind::Type { .. } = param.kind {
1867 let name = param.name.ident().name;
1868 let param_ty = ty::ParamTy::new(index, name).to_ty(tcx);
1871 let sized = SizedByDefault::Yes;
1872 let bounds = AstConv::compute_bounds(&icx, param_ty, ¶m.bounds, sized, param.span);
1873 predicates.extend(bounds.predicates(tcx, param_ty));
1877 // Add in the bounds that appear in the where-clause.
1878 let where_clause = &ast_generics.where_clause;
1879 for predicate in where_clause.predicates {
1881 &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
1882 let ty = icx.to_ty(&bound_pred.bounded_ty);
1884 // Keep the type around in a dummy predicate, in case of no bounds.
1885 // That way, `where Ty:` is not a complete noop (see #53696) and `Ty`
1886 // is still checked for WF.
1887 if bound_pred.bounds.is_empty() {
1888 if let ty::Param(_) = ty.kind {
1889 // This is a `where T:`, which can be in the HIR from the
1890 // transformation that moves `?Sized` to `T`'s declaration.
1891 // We can skip the predicate because type parameters are
1892 // trivially WF, but also we *should*, to avoid exposing
1893 // users who never wrote `where Type:,` themselves, to
1894 // compiler/tooling bugs from not handling WF predicates.
1896 let span = bound_pred.bounded_ty.span;
1897 let re_root_empty = tcx.lifetimes.re_root_empty;
1898 let predicate = ty::OutlivesPredicate(ty, re_root_empty);
1900 ty::Predicate::TypeOutlives(ty::Binder::dummy(predicate)),
1906 for bound in bound_pred.bounds.iter() {
1908 &hir::GenericBound::Trait(ref poly_trait_ref, modifier) => {
1909 let constness = match modifier {
1910 hir::TraitBoundModifier::MaybeConst => hir::Constness::NotConst,
1911 hir::TraitBoundModifier::None => constness,
1912 hir::TraitBoundModifier::Maybe => bug!("this wasn't handled"),
1915 let mut bounds = Bounds::default();
1916 let _ = AstConv::instantiate_poly_trait_ref(
1923 predicates.extend(bounds.predicates(tcx, ty));
1926 &hir::GenericBound::Outlives(ref lifetime) => {
1927 let region = AstConv::ast_region_to_region(&icx, lifetime, None);
1928 let pred = ty::Binder::bind(ty::OutlivesPredicate(ty, region));
1929 predicates.push((ty::Predicate::TypeOutlives(pred), lifetime.span))
1935 &hir::WherePredicate::RegionPredicate(ref region_pred) => {
1936 let r1 = AstConv::ast_region_to_region(&icx, ®ion_pred.lifetime, None);
1937 predicates.extend(region_pred.bounds.iter().map(|bound| {
1938 let (r2, span) = match bound {
1939 hir::GenericBound::Outlives(lt) => {
1940 (AstConv::ast_region_to_region(&icx, lt, None), lt.span)
1944 let pred = ty::Binder::bind(ty::OutlivesPredicate(r1, r2));
1946 (ty::Predicate::RegionOutlives(pred), span)
1950 &hir::WherePredicate::EqPredicate(..) => {
1956 // Add predicates from associated type bounds.
1957 if let Some((self_trait_ref, trait_items)) = is_trait {
1958 predicates.extend(trait_items.iter().flat_map(|trait_item_ref| {
1959 associated_item_predicates(tcx, def_id, self_trait_ref, trait_item_ref)
1963 let mut predicates = predicates.predicates;
1965 // Subtle: before we store the predicates into the tcx, we
1966 // sort them so that predicates like `T: Foo<Item=U>` come
1967 // before uses of `U`. This avoids false ambiguity errors
1968 // in trait checking. See `setup_constraining_predicates`
1970 if let Node::Item(&Item { kind: ItemKind::Impl { .. }, .. }) = node {
1971 let self_ty = tcx.type_of(def_id);
1972 let trait_ref = tcx.impl_trait_ref(def_id);
1973 cgp::setup_constraining_predicates(
1977 &mut cgp::parameters_for_impl(self_ty, trait_ref),
1981 let result = ty::GenericPredicates {
1982 parent: generics.parent,
1983 predicates: tcx.arena.alloc_from_iter(predicates),
1985 debug!("explicit_predicates_of(def_id={:?}) = {:?}", def_id, result);
1989 fn associated_item_predicates(
1992 self_trait_ref: ty::TraitRef<'tcx>,
1993 trait_item_ref: &hir::TraitItemRef,
1994 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
1995 let trait_item = tcx.hir().trait_item(trait_item_ref.id);
1996 let item_def_id = tcx.hir().local_def_id(trait_item_ref.id.hir_id);
1997 let bounds = match trait_item.kind {
1998 hir::TraitItemKind::Type(ref bounds, _) => bounds,
1999 _ => return Vec::new(),
2002 let is_gat = !tcx.generics_of(item_def_id).params.is_empty();
2004 let mut had_error = false;
2006 let mut unimplemented_error = |arg_kind: &str| {
2011 &format!("{}-generic associated types are not yet implemented", arg_kind),
2014 "for more information, see issue #44265 \
2015 <https://github.com/rust-lang/rust/issues/44265> for more information",
2022 let mk_bound_param = |param: &ty::GenericParamDef, _: &_| {
2024 ty::GenericParamDefKind::Lifetime => tcx
2025 .mk_region(ty::RegionKind::ReLateBound(
2027 ty::BoundRegion::BrNamed(param.def_id, param.name),
2030 // FIXME(generic_associated_types): Use bound types and constants
2031 // once they are handled by the trait system.
2032 ty::GenericParamDefKind::Type { .. } => {
2033 unimplemented_error("type");
2034 tcx.types.err.into()
2036 ty::GenericParamDefKind::Const => {
2037 unimplemented_error("const");
2038 tcx.consts.err.into()
2043 let bound_substs = if is_gat {
2046 // trait X<'a, B, const C: usize> {
2047 // type T<'d, E, const F: usize>: Default;
2050 // We need to create predicates on the trait:
2052 // for<'d, E, const F: usize>
2053 // <Self as X<'a, B, const C: usize>>::T<'d, E, const F: usize>: Sized + Default
2055 // We substitute escaping bound parameters for the generic
2056 // arguments to the associated type which are then bound by
2057 // the `Binder` around the the predicate.
2059 // FIXME(generic_associated_types): Currently only lifetimes are handled.
2060 self_trait_ref.substs.extend_to(tcx, item_def_id, mk_bound_param)
2062 self_trait_ref.substs
2065 let assoc_ty = tcx.mk_projection(tcx.hir().local_def_id(trait_item.hir_id), bound_substs);
2067 let bounds = AstConv::compute_bounds(
2068 &ItemCtxt::new(tcx, def_id),
2071 SizedByDefault::Yes,
2075 let predicates = bounds.predicates(tcx, assoc_ty);
2078 // We use shifts to get the regions that we're substituting to
2079 // be bound by the binders in the `Predicate`s rather that
2081 let shifted_in = ty::fold::shift_vars(tcx, &predicates, 1);
2082 let substituted = shifted_in.subst(tcx, bound_substs);
2083 ty::fold::shift_out_vars(tcx, &substituted, 1)
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::Binder::bind(ty::OutlivesPredicate(param_ty, region));
2115 vec![(ty::Predicate::TypeOutlives(pred), lifetime.span)]
2120 fn compute_sig_of_foreign_fn_decl<'tcx>(
2123 decl: &'tcx hir::FnDecl<'tcx>,
2126 ) -> ty::PolyFnSig<'tcx> {
2127 let unsafety = if abi == abi::Abi::RustIntrinsic {
2128 intrinsic_operation_unsafety(&tcx.item_name(def_id).as_str())
2130 hir::Unsafety::Unsafe
2132 let fty = AstConv::ty_of_fn(
2133 &ItemCtxt::new(tcx, def_id),
2137 &hir::Generics::empty(),
2141 // Feature gate SIMD types in FFI, since I am not sure that the
2142 // ABIs are handled at all correctly. -huonw
2143 if abi != abi::Abi::RustIntrinsic
2144 && abi != abi::Abi::PlatformIntrinsic
2145 && !tcx.features().simd_ffi
2147 let check = |ast_ty: &hir::Ty<'_>, ty: Ty<'_>| {
2152 .span_to_snippet(ast_ty.span)
2153 .map_or(String::new(), |s| format!(" `{}`", s));
2158 "use of SIMD type{} in FFI is highly experimental and \
2159 may result in invalid code",
2163 .help("add `#![feature(simd_ffi)]` to the crate attributes to enable")
2167 for (input, ty) in decl.inputs.iter().zip(*fty.inputs().skip_binder()) {
2170 if let hir::FnRetTy::Return(ref ty) = decl.output {
2171 check(&ty, *fty.output().skip_binder())
2178 fn is_foreign_item(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
2179 match tcx.hir().get_if_local(def_id) {
2180 Some(Node::ForeignItem(..)) => true,
2182 _ => bug!("is_foreign_item applied to non-local def-id {:?}", def_id),
2186 fn static_mutability(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::Mutability> {
2187 match tcx.hir().get_if_local(def_id) {
2188 Some(Node::Item(&hir::Item { kind: hir::ItemKind::Static(_, mutbl, _), .. }))
2189 | Some(Node::ForeignItem(&hir::ForeignItem {
2190 kind: hir::ForeignItemKind::Static(_, mutbl),
2194 _ => bug!("static_mutability applied to non-local def-id {:?}", def_id),
2198 fn generator_kind(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::GeneratorKind> {
2199 match tcx.hir().get_if_local(def_id) {
2200 Some(Node::Expr(&rustc_hir::Expr {
2201 kind: rustc_hir::ExprKind::Closure(_, _, body_id, _, _),
2203 })) => tcx.hir().body(body_id).generator_kind(),
2205 _ => bug!("generator_kind applied to non-local def-id {:?}", def_id),
2209 fn from_target_feature(
2212 attr: &ast::Attribute,
2213 whitelist: &FxHashMap<String, Option<Symbol>>,
2214 target_features: &mut Vec<Symbol>,
2216 let list = match attr.meta_item_list() {
2220 let bad_item = |span| {
2221 let msg = "malformed `target_feature` attribute input";
2222 let code = "enable = \"..\"".to_owned();
2224 .struct_span_err(span, &msg)
2225 .span_suggestion(span, "must be of the form", code, Applicability::HasPlaceholders)
2228 let rust_features = tcx.features();
2230 // Only `enable = ...` is accepted in the meta-item list.
2231 if !item.check_name(sym::enable) {
2232 bad_item(item.span());
2236 // Must be of the form `enable = "..."` (a string).
2237 let value = match item.value_str() {
2238 Some(value) => value,
2240 bad_item(item.span());
2245 // We allow comma separation to enable multiple features.
2246 target_features.extend(value.as_str().split(',').filter_map(|feature| {
2247 // Only allow whitelisted features per platform.
2248 let feature_gate = match whitelist.get(feature) {
2252 format!("the feature named `{}` is not valid for this target", feature);
2253 let mut err = tcx.sess.struct_span_err(item.span(), &msg);
2256 format!("`{}` is not valid for this target", feature),
2258 if feature.starts_with('+') {
2259 let valid = whitelist.contains_key(&feature[1..]);
2261 err.help("consider removing the leading `+` in the feature name");
2269 // Only allow features whose feature gates have been enabled.
2270 let allowed = match feature_gate.as_ref().copied() {
2271 Some(sym::arm_target_feature) => rust_features.arm_target_feature,
2272 Some(sym::aarch64_target_feature) => rust_features.aarch64_target_feature,
2273 Some(sym::hexagon_target_feature) => rust_features.hexagon_target_feature,
2274 Some(sym::powerpc_target_feature) => rust_features.powerpc_target_feature,
2275 Some(sym::mips_target_feature) => rust_features.mips_target_feature,
2276 Some(sym::avx512_target_feature) => rust_features.avx512_target_feature,
2277 Some(sym::mmx_target_feature) => rust_features.mmx_target_feature,
2278 Some(sym::sse4a_target_feature) => rust_features.sse4a_target_feature,
2279 Some(sym::tbm_target_feature) => rust_features.tbm_target_feature,
2280 Some(sym::wasm_target_feature) => rust_features.wasm_target_feature,
2281 Some(sym::cmpxchg16b_target_feature) => rust_features.cmpxchg16b_target_feature,
2282 Some(sym::adx_target_feature) => rust_features.adx_target_feature,
2283 Some(sym::movbe_target_feature) => rust_features.movbe_target_feature,
2284 Some(sym::rtm_target_feature) => rust_features.rtm_target_feature,
2285 Some(sym::f16c_target_feature) => rust_features.f16c_target_feature,
2286 Some(name) => bug!("unknown target feature gate {}", name),
2289 if !allowed && id.is_local() {
2291 &tcx.sess.parse_sess,
2292 feature_gate.unwrap(),
2294 &format!("the target feature `{}` is currently unstable", feature),
2298 Some(Symbol::intern(feature))
2303 fn linkage_by_name(tcx: TyCtxt<'_>, def_id: DefId, name: &str) -> Linkage {
2304 use rustc_middle::mir::mono::Linkage::*;
2306 // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
2307 // applicable to variable declarations and may not really make sense for
2308 // Rust code in the first place but whitelist them anyway and trust that
2309 // the user knows what s/he's doing. Who knows, unanticipated use cases
2310 // may pop up in the future.
2312 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
2313 // and don't have to be, LLVM treats them as no-ops.
2315 "appending" => Appending,
2316 "available_externally" => AvailableExternally,
2318 "extern_weak" => ExternalWeak,
2319 "external" => External,
2320 "internal" => Internal,
2321 "linkonce" => LinkOnceAny,
2322 "linkonce_odr" => LinkOnceODR,
2323 "private" => Private,
2325 "weak_odr" => WeakODR,
2327 let span = tcx.hir().span_if_local(def_id);
2328 if let Some(span) = span {
2329 tcx.sess.span_fatal(span, "invalid linkage specified")
2331 tcx.sess.fatal(&format!("invalid linkage specified: {}", name))
2337 fn codegen_fn_attrs(tcx: TyCtxt<'_>, id: DefId) -> CodegenFnAttrs {
2338 let attrs = tcx.get_attrs(id);
2340 let mut codegen_fn_attrs = CodegenFnAttrs::new();
2341 if should_inherit_track_caller(tcx, id) {
2342 codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
2345 let whitelist = tcx.target_features_whitelist(LOCAL_CRATE);
2347 let mut inline_span = None;
2348 let mut link_ordinal_span = None;
2349 let mut no_sanitize_span = None;
2350 for attr in attrs.iter() {
2351 if attr.check_name(sym::cold) {
2352 codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD;
2353 } else if attr.check_name(sym::rustc_allocator) {
2354 codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR;
2355 } else if attr.check_name(sym::unwind) {
2356 codegen_fn_attrs.flags |= CodegenFnAttrFlags::UNWIND;
2357 } else if attr.check_name(sym::ffi_returns_twice) {
2358 if tcx.is_foreign_item(id) {
2359 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_RETURNS_TWICE;
2361 // `#[ffi_returns_twice]` is only allowed `extern fn`s.
2366 "`#[ffi_returns_twice]` may only be used on foreign functions"
2370 } else if attr.check_name(sym::rustc_allocator_nounwind) {
2371 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND;
2372 } else if attr.check_name(sym::naked) {
2373 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED;
2374 } else if attr.check_name(sym::no_mangle) {
2375 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2376 } else if attr.check_name(sym::rustc_std_internal_symbol) {
2377 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2378 } else if attr.check_name(sym::used) {
2379 codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED;
2380 } else if attr.check_name(sym::thread_local) {
2381 codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL;
2382 } else if attr.check_name(sym::track_caller) {
2383 if tcx.is_closure(id) || tcx.fn_sig(id).abi() != abi::Abi::Rust {
2384 struct_span_err!(tcx.sess, attr.span, E0737, "`#[track_caller]` requires Rust ABI")
2387 codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
2388 } else if attr.check_name(sym::export_name) {
2389 if let Some(s) = attr.value_str() {
2390 if s.as_str().contains('\0') {
2391 // `#[export_name = ...]` will be converted to a null-terminated string,
2392 // so it may not contain any null characters.
2397 "`export_name` may not contain null characters"
2401 codegen_fn_attrs.export_name = Some(s);
2403 } else if attr.check_name(sym::target_feature) {
2404 if tcx.is_closure(id) || tcx.fn_sig(id).unsafety() == Unsafety::Normal {
2405 let msg = "`#[target_feature(..)]` can only be applied to `unsafe` functions";
2407 .struct_span_err(attr.span, msg)
2408 .span_label(attr.span, "can only be applied to `unsafe` functions")
2409 .span_label(tcx.def_span(id), "not an `unsafe` function")
2412 from_target_feature(tcx, id, attr, &whitelist, &mut codegen_fn_attrs.target_features);
2413 } else if attr.check_name(sym::linkage) {
2414 if let Some(val) = attr.value_str() {
2415 codegen_fn_attrs.linkage = Some(linkage_by_name(tcx, id, &val.as_str()));
2417 } else if attr.check_name(sym::link_section) {
2418 if let Some(val) = attr.value_str() {
2419 if val.as_str().bytes().any(|b| b == 0) {
2421 "illegal null byte in link_section \
2425 tcx.sess.span_err(attr.span, &msg);
2427 codegen_fn_attrs.link_section = Some(val);
2430 } else if attr.check_name(sym::link_name) {
2431 codegen_fn_attrs.link_name = attr.value_str();
2432 } else if attr.check_name(sym::link_ordinal) {
2433 link_ordinal_span = Some(attr.span);
2434 if let ordinal @ Some(_) = check_link_ordinal(tcx, attr) {
2435 codegen_fn_attrs.link_ordinal = ordinal;
2437 } else if attr.check_name(sym::no_sanitize) {
2438 no_sanitize_span = Some(attr.span);
2439 if let Some(list) = attr.meta_item_list() {
2440 for item in list.iter() {
2441 if item.check_name(sym::address) {
2442 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_SANITIZE_ADDRESS;
2443 } else if item.check_name(sym::memory) {
2444 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_SANITIZE_MEMORY;
2445 } else if item.check_name(sym::thread) {
2446 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_SANITIZE_THREAD;
2449 .struct_span_err(item.span(), "invalid argument for `no_sanitize`")
2450 .note("expected one of: `address`, `memory` or `thread`")
2458 codegen_fn_attrs.inline = attrs.iter().fold(InlineAttr::None, |ia, attr| {
2459 if !attr.has_name(sym::inline) {
2462 match attr.meta().map(|i| i.kind) {
2463 Some(MetaItemKind::Word) => {
2467 Some(MetaItemKind::List(ref items)) => {
2469 inline_span = Some(attr.span);
2470 if items.len() != 1 {
2472 tcx.sess.diagnostic(),
2475 "expected one argument"
2479 } else if list_contains_name(&items[..], sym::always) {
2481 } else if list_contains_name(&items[..], sym::never) {
2485 tcx.sess.diagnostic(),
2495 Some(MetaItemKind::NameValue(_)) => ia,
2500 codegen_fn_attrs.optimize = attrs.iter().fold(OptimizeAttr::None, |ia, attr| {
2501 if !attr.has_name(sym::optimize) {
2504 let err = |sp, s| struct_span_err!(tcx.sess.diagnostic(), sp, E0722, "{}", s).emit();
2505 match attr.meta().map(|i| i.kind) {
2506 Some(MetaItemKind::Word) => {
2507 err(attr.span, "expected one argument");
2510 Some(MetaItemKind::List(ref items)) => {
2512 inline_span = Some(attr.span);
2513 if items.len() != 1 {
2514 err(attr.span, "expected one argument");
2516 } else if list_contains_name(&items[..], sym::size) {
2518 } else if list_contains_name(&items[..], sym::speed) {
2521 err(items[0].span(), "invalid argument");
2525 Some(MetaItemKind::NameValue(_)) => ia,
2530 // If a function uses #[target_feature] it can't be inlined into general
2531 // purpose functions as they wouldn't have the right target features
2532 // enabled. For that reason we also forbid #[inline(always)] as it can't be
2534 if !codegen_fn_attrs.target_features.is_empty() {
2535 if codegen_fn_attrs.inline == InlineAttr::Always {
2536 if let Some(span) = inline_span {
2539 "cannot use `#[inline(always)]` with \
2540 `#[target_feature]`",
2546 if codegen_fn_attrs.flags.intersects(CodegenFnAttrFlags::NO_SANITIZE_ANY) {
2547 if codegen_fn_attrs.inline == InlineAttr::Always {
2548 if let (Some(no_sanitize_span), Some(inline_span)) = (no_sanitize_span, inline_span) {
2549 let hir_id = tcx.hir().as_local_hir_id(id).unwrap();
2550 tcx.struct_span_lint_hir(
2551 lint::builtin::INLINE_NO_SANITIZE,
2555 lint.build("`no_sanitize` will have no effect after inlining")
2556 .span_note(inline_span, "inlining requested here")
2564 // Weak lang items have the same semantics as "std internal" symbols in the
2565 // sense that they're preserved through all our LTO passes and only
2566 // strippable by the linker.
2568 // Additionally weak lang items have predetermined symbol names.
2569 if tcx.is_weak_lang_item(id) {
2570 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2572 if let Some(name) = lang_items::link_name(&attrs) {
2573 codegen_fn_attrs.export_name = Some(name);
2574 codegen_fn_attrs.link_name = Some(name);
2576 check_link_name_xor_ordinal(tcx, &codegen_fn_attrs, link_ordinal_span);
2578 // Internal symbols to the standard library all have no_mangle semantics in
2579 // that they have defined symbol names present in the function name. This
2580 // also applies to weak symbols where they all have known symbol names.
2581 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
2582 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2588 /// Checks if the provided DefId is a method in a trait impl for a trait which has track_caller
2589 /// applied to the method prototype.
2590 fn should_inherit_track_caller(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
2591 if let Some(impl_item) = tcx.opt_associated_item(def_id) {
2592 if let ty::AssocItemContainer::ImplContainer(impl_def_id) = impl_item.container {
2593 if let Some(trait_def_id) = tcx.trait_id_of_impl(impl_def_id) {
2594 if let Some(trait_item) = tcx
2595 .associated_items(trait_def_id)
2596 .filter_by_name_unhygienic(impl_item.ident.name)
2597 .find(move |trait_item| {
2598 trait_item.kind == ty::AssocKind::Method
2599 && tcx.hygienic_eq(impl_item.ident, trait_item.ident, trait_def_id)
2603 .codegen_fn_attrs(trait_item.def_id)
2605 .intersects(CodegenFnAttrFlags::TRACK_CALLER);
2614 fn check_link_ordinal(tcx: TyCtxt<'_>, attr: &ast::Attribute) -> Option<usize> {
2615 use rustc_ast::ast::{Lit, LitIntType, LitKind};
2616 let meta_item_list = attr.meta_item_list();
2617 let meta_item_list: Option<&[ast::NestedMetaItem]> = meta_item_list.as_ref().map(Vec::as_ref);
2618 let sole_meta_list = match meta_item_list {
2619 Some([item]) => item.literal(),
2622 if let Some(Lit { kind: LitKind::Int(ordinal, LitIntType::Unsuffixed), .. }) = sole_meta_list {
2623 if *ordinal <= std::usize::MAX as u128 {
2624 Some(*ordinal as usize)
2626 let msg = format!("ordinal value in `link_ordinal` is too large: `{}`", &ordinal);
2628 .struct_span_err(attr.span, &msg)
2629 .note("the value may not exceed `std::usize::MAX`")
2635 .struct_span_err(attr.span, "illegal ordinal format in `link_ordinal`")
2636 .note("an unsuffixed integer value, e.g., `1`, is expected")
2642 fn check_link_name_xor_ordinal(
2644 codegen_fn_attrs: &CodegenFnAttrs,
2645 inline_span: Option<Span>,
2647 if codegen_fn_attrs.link_name.is_none() || codegen_fn_attrs.link_ordinal.is_none() {
2650 let msg = "cannot use `#[link_name]` with `#[link_ordinal]`";
2651 if let Some(span) = inline_span {
2652 tcx.sess.span_err(span, msg);