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;
21 use crate::middle::lang_items;
22 use crate::middle::resolve_lifetime as rl;
23 use rustc::hir::map::blocks::FnLikeNode;
24 use rustc::hir::map::Map;
25 use rustc::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
26 use rustc::mir::mono::Linkage;
27 use rustc::session::parse::feature_err;
28 use rustc::ty::query::Providers;
29 use rustc::ty::subst::{InternalSubsts, Subst};
30 use rustc::ty::util::Discr;
31 use rustc::ty::util::IntTypeExt;
32 use rustc::ty::{self, AdtKind, Const, ToPolyTraitRef, Ty, TyCtxt};
33 use rustc::ty::{ReprOptions, ToPredicate, WithConstness};
34 use rustc_attr::{list_contains_name, mark_used, InlineAttr, OptimizeAttr};
35 use rustc_data_structures::captures::Captures;
36 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
37 use rustc_errors::{struct_span_err, Applicability};
39 use rustc_hir::def::{CtorKind, DefKind, Res};
40 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
41 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
42 use rustc_hir::{GenericParamKind, Node, Unsafety};
43 use rustc_span::symbol::{kw, sym, Symbol};
44 use rustc_span::{Span, DUMMY_SP};
45 use rustc_target::spec::abi;
47 use syntax::ast::{Ident, MetaItemKind};
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 {
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, format!("{}", type_name)));
166 generics.iter().last().unwrap().span.shrink_to_hi(),
167 format!(", {}", type_name),
170 let mut err = bad_placeholder_type(tcx, placeholder_types);
172 err.multipart_suggestion(
173 "use type parameters instead",
175 Applicability::HasPlaceholders,
181 fn reject_placeholder_type_signatures_in_item(tcx: TyCtxt<'tcx>, item: &'tcx hir::Item<'tcx>) {
182 let (generics, suggest) = match &item.kind {
183 hir::ItemKind::Union(_, generics)
184 | hir::ItemKind::Enum(_, generics)
185 | hir::ItemKind::TraitAlias(generics, _)
186 | hir::ItemKind::Trait(_, _, generics, ..)
187 | hir::ItemKind::Impl { generics, .. }
188 | hir::ItemKind::Struct(_, generics) => (generics, true),
189 hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. })
190 | hir::ItemKind::TyAlias(_, generics) => (generics, false),
191 // `static`, `fn` and `const` are handled elsewhere to suggest appropriate type.
195 let mut visitor = PlaceholderHirTyCollector::default();
196 visitor.visit_item(item);
198 placeholder_type_error(tcx, generics.span, &generics.params[..], visitor.0, suggest);
201 impl Visitor<'tcx> for CollectItemTypesVisitor<'tcx> {
202 type Map = Map<'tcx>;
204 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
205 NestedVisitorMap::OnlyBodies(&self.tcx.hir())
208 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
209 convert_item(self.tcx, item.hir_id);
210 reject_placeholder_type_signatures_in_item(self.tcx, item);
211 intravisit::walk_item(self, item);
214 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
215 for param in generics.params {
217 hir::GenericParamKind::Lifetime { .. } => {}
218 hir::GenericParamKind::Type { default: Some(_), .. } => {
219 let def_id = self.tcx.hir().local_def_id(param.hir_id);
220 self.tcx.type_of(def_id);
222 hir::GenericParamKind::Type { .. } => {}
223 hir::GenericParamKind::Const { .. } => {
224 let def_id = self.tcx.hir().local_def_id(param.hir_id);
225 self.tcx.type_of(def_id);
229 intravisit::walk_generics(self, generics);
232 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
233 if let hir::ExprKind::Closure(..) = expr.kind {
234 let def_id = self.tcx.hir().local_def_id(expr.hir_id);
235 self.tcx.generics_of(def_id);
236 self.tcx.type_of(def_id);
238 intravisit::walk_expr(self, expr);
241 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
242 convert_trait_item(self.tcx, trait_item.hir_id);
243 intravisit::walk_trait_item(self, trait_item);
246 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
247 convert_impl_item(self.tcx, impl_item.hir_id);
248 intravisit::walk_impl_item(self, impl_item);
252 ///////////////////////////////////////////////////////////////////////////
253 // Utility types and common code for the above passes.
255 fn bad_placeholder_type(
257 mut spans: Vec<Span>,
258 ) -> rustc_errors::DiagnosticBuilder<'tcx> {
260 let mut err = struct_span_err!(
264 "the type placeholder `_` is not allowed within types on item signatures",
267 err.span_label(span, "not allowed in type signatures");
272 impl ItemCtxt<'tcx> {
273 pub fn new(tcx: TyCtxt<'tcx>, item_def_id: DefId) -> ItemCtxt<'tcx> {
274 ItemCtxt { tcx, item_def_id }
277 pub fn to_ty(&self, ast_ty: &'tcx hir::Ty<'tcx>) -> Ty<'tcx> {
278 AstConv::ast_ty_to_ty(self, ast_ty)
281 pub fn hir_id(&self) -> hir::HirId {
284 .as_local_hir_id(self.item_def_id)
285 .expect("Non-local call to local provider is_const_fn")
288 pub fn node(&self) -> hir::Node<'tcx> {
289 self.tcx.hir().get(self.hir_id())
293 impl AstConv<'tcx> for ItemCtxt<'tcx> {
294 fn tcx(&self) -> TyCtxt<'tcx> {
298 fn item_def_id(&self) -> Option<DefId> {
299 Some(self.item_def_id)
302 fn default_constness_for_trait_bounds(&self) -> hir::Constness {
303 if let Some(fn_like) = FnLikeNode::from_node(self.node()) {
306 hir::Constness::NotConst
310 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId) -> ty::GenericPredicates<'tcx> {
311 self.tcx.at(span).type_param_predicates((self.item_def_id, def_id))
314 fn re_infer(&self, _: Option<&ty::GenericParamDef>, _: Span) -> Option<ty::Region<'tcx>> {
318 fn allow_ty_infer(&self) -> bool {
322 fn ty_infer(&self, _: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx> {
323 self.tcx().sess.delay_span_bug(span, "bad placeholder type");
330 _: Option<&ty::GenericParamDef>,
332 ) -> &'tcx Const<'tcx> {
333 bad_placeholder_type(self.tcx(), vec![span]).emit();
335 self.tcx().consts.err
338 fn projected_ty_from_poly_trait_ref(
342 item_segment: &hir::PathSegment<'_>,
343 poly_trait_ref: ty::PolyTraitRef<'tcx>,
345 if let Some(trait_ref) = poly_trait_ref.no_bound_vars() {
346 let item_substs = <dyn AstConv<'tcx>>::create_substs_for_associated_item(
354 self.tcx().mk_projection(item_def_id, item_substs)
356 // There are no late-bound regions; we can just ignore the binder.
357 let mut err = struct_span_err!(
361 "cannot extract an associated type from a higher-ranked trait bound \
366 hir::Node::Field(_) | hir::Node::Ctor(_) | hir::Node::Variant(_) => {
368 self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(self.hir_id()));
370 hir::ItemKind::Enum(_, generics)
371 | hir::ItemKind::Struct(_, generics)
372 | hir::ItemKind::Union(_, generics) => {
373 let lt_name = get_new_lifetime_name(self.tcx, poly_trait_ref, generics);
374 let (lt_sp, sugg) = match &generics.params[..] {
375 [] => (generics.span, format!("<{}>", lt_name)),
377 (bound.span.shrink_to_lo(), format!("{}, ", lt_name))
380 let suggestions = vec![
386 // Replace the existing lifetimes with a new named lifetime.
388 .replace_late_bound_regions(&poly_trait_ref, |_| {
389 self.tcx.mk_region(ty::ReEarlyBound(
390 ty::EarlyBoundRegion {
393 name: Symbol::intern(<_name),
402 err.multipart_suggestion(
403 "use a fully qualified path with explicit lifetimes",
405 Applicability::MaybeIncorrect,
411 hir::Node::Item(hir::Item { kind: hir::ItemKind::Struct(..), .. })
412 | hir::Node::Item(hir::Item { kind: hir::ItemKind::Enum(..), .. })
413 | hir::Node::Item(hir::Item { kind: hir::ItemKind::Union(..), .. }) => {}
415 | hir::Node::ForeignItem(_)
416 | hir::Node::TraitItem(_)
417 | hir::Node::ImplItem(_) => {
420 "use a fully qualified path with inferred lifetimes",
423 // Erase named lt, we want `<A as B<'_>::C`, not `<A as B<'a>::C`.
424 self.tcx.anonymize_late_bound_regions(&poly_trait_ref).skip_binder(),
427 Applicability::MaybeIncorrect,
437 fn normalize_ty(&self, _span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
438 // Types in item signatures are not normalized to avoid undue dependencies.
442 fn set_tainted_by_errors(&self) {
443 // There's no obvious place to track this, so just let it go.
446 fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) {
447 // There's no place to record types from signatures?
451 /// Synthesize a new lifetime name that doesn't clash with any of the lifetimes already present.
452 fn get_new_lifetime_name<'tcx>(
454 poly_trait_ref: ty::PolyTraitRef<'tcx>,
455 generics: &hir::Generics<'tcx>,
457 let existing_lifetimes = tcx
458 .collect_referenced_late_bound_regions(&poly_trait_ref)
461 if let ty::BoundRegion::BrNamed(_, name) = lt {
462 Some(name.as_str().to_string())
467 .chain(generics.params.iter().filter_map(|param| {
468 if let hir::GenericParamKind::Lifetime { .. } = ¶m.kind {
469 Some(param.name.ident().as_str().to_string())
474 .collect::<FxHashSet<String>>();
476 let a_to_z_repeat_n = |n| {
477 (b'a'..=b'z').map(move |c| {
478 let mut s = format!("'");
479 s.extend(std::iter::repeat(char::from(c)).take(n));
484 // If all single char lifetime names are present, we wrap around and double the chars.
485 (1..).flat_map(a_to_z_repeat_n).find(|lt| !existing_lifetimes.contains(lt.as_str())).unwrap()
488 /// Returns the predicates defined on `item_def_id` of the form
489 /// `X: Foo` where `X` is the type parameter `def_id`.
490 fn type_param_predicates(
492 (item_def_id, def_id): (DefId, DefId),
493 ) -> ty::GenericPredicates<'_> {
496 // In the AST, bounds can derive from two places. Either
497 // written inline like `<T: Foo>` or in a where-clause like
500 let param_id = tcx.hir().as_local_hir_id(def_id).unwrap();
501 let param_owner = tcx.hir().ty_param_owner(param_id);
502 let param_owner_def_id = tcx.hir().local_def_id(param_owner);
503 let generics = tcx.generics_of(param_owner_def_id);
504 let index = generics.param_def_id_to_index[&def_id];
505 let ty = tcx.mk_ty_param(index, tcx.hir().ty_param_name(param_id));
507 // Don't look for bounds where the type parameter isn't in scope.
509 if item_def_id == param_owner_def_id { None } else { tcx.generics_of(item_def_id).parent };
511 let mut result = parent
513 let icx = ItemCtxt::new(tcx, parent);
514 icx.get_type_parameter_bounds(DUMMY_SP, def_id)
516 .unwrap_or_default();
517 let mut extend = None;
519 let item_hir_id = tcx.hir().as_local_hir_id(item_def_id).unwrap();
520 let ast_generics = match tcx.hir().get(item_hir_id) {
521 Node::TraitItem(item) => &item.generics,
523 Node::ImplItem(item) => &item.generics,
525 Node::Item(item) => {
527 ItemKind::Fn(.., ref generics, _)
528 | ItemKind::Impl { ref generics, .. }
529 | ItemKind::TyAlias(_, ref generics)
530 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
531 | ItemKind::Enum(_, ref generics)
532 | ItemKind::Struct(_, ref generics)
533 | ItemKind::Union(_, ref generics) => generics,
534 ItemKind::Trait(_, _, ref generics, ..) => {
535 // Implied `Self: Trait` and supertrait bounds.
536 if param_id == item_hir_id {
537 let identity_trait_ref = ty::TraitRef::identity(tcx, item_def_id);
539 Some((identity_trait_ref.without_const().to_predicate(), item.span));
547 Node::ForeignItem(item) => match item.kind {
548 ForeignItemKind::Fn(_, _, ref generics) => generics,
555 let icx = ItemCtxt::new(tcx, item_def_id);
556 let extra_predicates = extend.into_iter().chain(
557 icx.type_parameter_bounds_in_generics(ast_generics, param_id, ty, OnlySelfBounds(true))
559 .filter(|(predicate, _)| match predicate {
560 ty::Predicate::Trait(ref data, _) => data.skip_binder().self_ty().is_param(index),
565 tcx.arena.alloc_from_iter(result.predicates.iter().copied().chain(extra_predicates));
569 impl ItemCtxt<'tcx> {
570 /// Finds bounds from `hir::Generics`. This requires scanning through the
571 /// AST. We do this to avoid having to convert *all* the bounds, which
572 /// would create artificial cycles. Instead, we can only convert the
573 /// bounds for a type parameter `X` if `X::Foo` is used.
574 fn type_parameter_bounds_in_generics(
576 ast_generics: &'tcx hir::Generics<'tcx>,
577 param_id: hir::HirId,
579 only_self_bounds: OnlySelfBounds,
580 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
581 let constness = self.default_constness_for_trait_bounds();
582 let from_ty_params = ast_generics
585 .filter_map(|param| match param.kind {
586 GenericParamKind::Type { .. } if param.hir_id == param_id => Some(¶m.bounds),
589 .flat_map(|bounds| bounds.iter())
590 .flat_map(|b| predicates_from_bound(self, ty, b, constness));
592 let from_where_clauses = ast_generics
596 .filter_map(|wp| match *wp {
597 hir::WherePredicate::BoundPredicate(ref bp) => Some(bp),
601 let bt = if is_param(self.tcx, &bp.bounded_ty, param_id) {
603 } else if !only_self_bounds.0 {
604 Some(self.to_ty(&bp.bounded_ty))
608 bp.bounds.iter().filter_map(move |b| bt.map(|bt| (bt, b)))
610 .flat_map(|(bt, b)| predicates_from_bound(self, bt, b, constness));
612 from_ty_params.chain(from_where_clauses).collect()
616 /// Tests whether this is the AST for a reference to the type
617 /// parameter with ID `param_id`. We use this so as to avoid running
618 /// `ast_ty_to_ty`, because we want to avoid triggering an all-out
619 /// conversion of the type to avoid inducing unnecessary cycles.
620 fn is_param(tcx: TyCtxt<'_>, ast_ty: &hir::Ty<'_>, param_id: hir::HirId) -> bool {
621 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = ast_ty.kind {
623 Res::SelfTy(Some(def_id), None) | Res::Def(DefKind::TyParam, def_id) => {
624 def_id == tcx.hir().local_def_id(param_id)
633 fn convert_item(tcx: TyCtxt<'_>, item_id: hir::HirId) {
634 let it = tcx.hir().expect_item(item_id);
635 debug!("convert: item {} with id {}", it.ident, it.hir_id);
636 let def_id = tcx.hir().local_def_id(item_id);
638 // These don't define types.
639 hir::ItemKind::ExternCrate(_)
640 | hir::ItemKind::Use(..)
641 | hir::ItemKind::Mod(_)
642 | hir::ItemKind::GlobalAsm(_) => {}
643 hir::ItemKind::ForeignMod(ref foreign_mod) => {
644 for item in foreign_mod.items {
645 let def_id = tcx.hir().local_def_id(item.hir_id);
646 tcx.generics_of(def_id);
648 tcx.predicates_of(def_id);
649 if let hir::ForeignItemKind::Fn(..) = item.kind {
654 hir::ItemKind::Enum(ref enum_definition, _) => {
655 tcx.generics_of(def_id);
657 tcx.predicates_of(def_id);
658 convert_enum_variant_types(tcx, def_id, &enum_definition.variants);
660 hir::ItemKind::Impl { .. } => {
661 tcx.generics_of(def_id);
663 tcx.impl_trait_ref(def_id);
664 tcx.predicates_of(def_id);
666 hir::ItemKind::Trait(..) => {
667 tcx.generics_of(def_id);
668 tcx.trait_def(def_id);
669 tcx.at(it.span).super_predicates_of(def_id);
670 tcx.predicates_of(def_id);
672 hir::ItemKind::TraitAlias(..) => {
673 tcx.generics_of(def_id);
674 tcx.at(it.span).super_predicates_of(def_id);
675 tcx.predicates_of(def_id);
677 hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
678 tcx.generics_of(def_id);
680 tcx.predicates_of(def_id);
682 for f in struct_def.fields() {
683 let def_id = tcx.hir().local_def_id(f.hir_id);
684 tcx.generics_of(def_id);
686 tcx.predicates_of(def_id);
689 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
690 convert_variant_ctor(tcx, ctor_hir_id);
694 // Desugared from `impl Trait`, so visited by the function's return type.
695 hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: Some(_), .. }) => {}
697 hir::ItemKind::OpaqueTy(..)
698 | hir::ItemKind::TyAlias(..)
699 | hir::ItemKind::Static(..)
700 | hir::ItemKind::Const(..)
701 | hir::ItemKind::Fn(..) => {
702 tcx.generics_of(def_id);
704 tcx.predicates_of(def_id);
705 if let hir::ItemKind::Fn(..) = it.kind {
712 fn convert_trait_item(tcx: TyCtxt<'_>, trait_item_id: hir::HirId) {
713 let trait_item = tcx.hir().expect_trait_item(trait_item_id);
714 let def_id = tcx.hir().local_def_id(trait_item.hir_id);
715 tcx.generics_of(def_id);
717 match trait_item.kind {
718 hir::TraitItemKind::Method(..) => {
723 hir::TraitItemKind::Const(.., Some(_)) => {
727 hir::TraitItemKind::Const(..) | hir::TraitItemKind::Type(_, Some(_)) => {
729 // Account for `const C: _;` and `type T = _;`.
730 let mut visitor = PlaceholderHirTyCollector::default();
731 visitor.visit_trait_item(trait_item);
732 placeholder_type_error(tcx, DUMMY_SP, &[], visitor.0, false);
735 hir::TraitItemKind::Type(_, None) => {}
738 tcx.predicates_of(def_id);
741 fn convert_impl_item(tcx: TyCtxt<'_>, impl_item_id: hir::HirId) {
742 let def_id = tcx.hir().local_def_id(impl_item_id);
743 tcx.generics_of(def_id);
745 tcx.predicates_of(def_id);
746 let impl_item = tcx.hir().expect_impl_item(impl_item_id);
747 match impl_item.kind {
748 hir::ImplItemKind::Method(..) => {
751 hir::ImplItemKind::TyAlias(_) | hir::ImplItemKind::OpaqueTy(_) => {
752 // Account for `type T = _;`
753 let mut visitor = PlaceholderHirTyCollector::default();
754 visitor.visit_impl_item(impl_item);
755 placeholder_type_error(tcx, DUMMY_SP, &[], visitor.0, false);
757 hir::ImplItemKind::Const(..) => {}
761 fn convert_variant_ctor(tcx: TyCtxt<'_>, ctor_id: hir::HirId) {
762 let def_id = tcx.hir().local_def_id(ctor_id);
763 tcx.generics_of(def_id);
765 tcx.predicates_of(def_id);
768 fn convert_enum_variant_types(tcx: TyCtxt<'_>, def_id: DefId, variants: &[hir::Variant<'_>]) {
769 let def = tcx.adt_def(def_id);
770 let repr_type = def.repr.discr_type();
771 let initial = repr_type.initial_discriminant(tcx);
772 let mut prev_discr = None::<Discr<'_>>;
774 // fill the discriminant values and field types
775 for variant in variants {
776 let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
778 if let Some(ref e) = variant.disr_expr {
779 let expr_did = tcx.hir().local_def_id(e.hir_id);
780 def.eval_explicit_discr(tcx, expr_did)
781 } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) {
784 struct_span_err!(tcx.sess, variant.span, E0370, "enum discriminant overflowed")
787 format!("overflowed on value after {}", prev_discr.unwrap()),
790 "explicitly set `{} = {}` if that is desired outcome",
791 variant.ident, wrapped_discr
796 .unwrap_or(wrapped_discr),
799 for f in variant.data.fields() {
800 let def_id = tcx.hir().local_def_id(f.hir_id);
801 tcx.generics_of(def_id);
803 tcx.predicates_of(def_id);
806 // Convert the ctor, if any. This also registers the variant as
808 if let Some(ctor_hir_id) = variant.data.ctor_hir_id() {
809 convert_variant_ctor(tcx, ctor_hir_id);
816 variant_did: Option<DefId>,
817 ctor_did: Option<DefId>,
819 discr: ty::VariantDiscr,
820 def: &hir::VariantData<'_>,
821 adt_kind: ty::AdtKind,
823 ) -> ty::VariantDef {
824 let mut seen_fields: FxHashMap<ast::Ident, Span> = Default::default();
825 let hir_id = tcx.hir().as_local_hir_id(variant_did.unwrap_or(parent_did)).unwrap();
830 let fid = tcx.hir().local_def_id(f.hir_id);
831 let dup_span = seen_fields.get(&f.ident.modern()).cloned();
832 if let Some(prev_span) = dup_span {
837 "field `{}` is already declared",
840 .span_label(f.span, "field already declared")
841 .span_label(prev_span, format!("`{}` first declared here", f.ident))
844 seen_fields.insert(f.ident.modern(), f.span);
850 vis: ty::Visibility::from_hir(&f.vis, hir_id, tcx),
854 let recovered = match def {
855 hir::VariantData::Struct(_, r) => *r,
865 CtorKind::from_hir(def),
872 fn adt_def(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::AdtDef {
875 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
876 let item = match tcx.hir().get(hir_id) {
877 Node::Item(item) => item,
881 let repr = ReprOptions::new(tcx, def_id);
882 let (kind, variants) = match item.kind {
883 ItemKind::Enum(ref def, _) => {
884 let mut distance_from_explicit = 0;
889 let variant_did = Some(tcx.hir().local_def_id(v.id));
891 v.data.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
893 let discr = if let Some(ref e) = v.disr_expr {
894 distance_from_explicit = 0;
895 ty::VariantDiscr::Explicit(tcx.hir().local_def_id(e.hir_id))
897 ty::VariantDiscr::Relative(distance_from_explicit)
899 distance_from_explicit += 1;
914 (AdtKind::Enum, variants)
916 ItemKind::Struct(ref def, _) => {
917 let variant_did = None;
918 let ctor_did = def.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
920 let variants = std::iter::once(convert_variant(
925 ty::VariantDiscr::Relative(0),
932 (AdtKind::Struct, variants)
934 ItemKind::Union(ref def, _) => {
935 let variant_did = None;
936 let ctor_did = def.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
938 let variants = std::iter::once(convert_variant(
943 ty::VariantDiscr::Relative(0),
950 (AdtKind::Union, variants)
954 tcx.alloc_adt_def(def_id, kind, variants, repr)
957 /// Ensures that the super-predicates of the trait with a `DefId`
958 /// of `trait_def_id` are converted and stored. This also ensures that
959 /// the transitive super-predicates are converted.
960 fn super_predicates_of(tcx: TyCtxt<'_>, trait_def_id: DefId) -> ty::GenericPredicates<'_> {
961 debug!("super_predicates(trait_def_id={:?})", trait_def_id);
962 let trait_hir_id = tcx.hir().as_local_hir_id(trait_def_id).unwrap();
964 let item = match tcx.hir().get(trait_hir_id) {
965 Node::Item(item) => item,
966 _ => bug!("trait_node_id {} is not an item", trait_hir_id),
969 let (generics, bounds) = match item.kind {
970 hir::ItemKind::Trait(.., ref generics, ref supertraits, _) => (generics, supertraits),
971 hir::ItemKind::TraitAlias(ref generics, ref supertraits) => (generics, supertraits),
972 _ => span_bug!(item.span, "super_predicates invoked on non-trait"),
975 let icx = ItemCtxt::new(tcx, trait_def_id);
977 // Convert the bounds that follow the colon, e.g., `Bar + Zed` in `trait Foo: Bar + Zed`.
978 let self_param_ty = tcx.types.self_param;
980 AstConv::compute_bounds(&icx, self_param_ty, bounds, SizedByDefault::No, item.span);
982 let superbounds1 = superbounds1.predicates(tcx, self_param_ty);
984 // Convert any explicit superbounds in the where-clause,
985 // e.g., `trait Foo where Self: Bar`.
986 // In the case of trait aliases, however, we include all bounds in the where-clause,
987 // so e.g., `trait Foo = where u32: PartialEq<Self>` would include `u32: PartialEq<Self>`
988 // as one of its "superpredicates".
989 let is_trait_alias = tcx.is_trait_alias(trait_def_id);
990 let superbounds2 = icx.type_parameter_bounds_in_generics(
994 OnlySelfBounds(!is_trait_alias),
997 // Combine the two lists to form the complete set of superbounds:
998 let superbounds = &*tcx.arena.alloc_from_iter(superbounds1.into_iter().chain(superbounds2));
1000 // Now require that immediate supertraits are converted,
1001 // which will, in turn, reach indirect supertraits.
1002 for &(pred, span) in superbounds {
1003 debug!("superbound: {:?}", pred);
1004 if let ty::Predicate::Trait(bound, _) = pred {
1005 tcx.at(span).super_predicates_of(bound.def_id());
1009 ty::GenericPredicates { parent: None, predicates: superbounds }
1012 fn trait_def(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::TraitDef {
1013 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1014 let item = tcx.hir().expect_item(hir_id);
1016 let (is_auto, unsafety) = match item.kind {
1017 hir::ItemKind::Trait(is_auto, unsafety, ..) => (is_auto == hir::IsAuto::Yes, unsafety),
1018 hir::ItemKind::TraitAlias(..) => (false, hir::Unsafety::Normal),
1019 _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
1022 let paren_sugar = tcx.has_attr(def_id, sym::rustc_paren_sugar);
1023 if paren_sugar && !tcx.features().unboxed_closures {
1027 "the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \
1028 which traits can use parenthetical notation",
1030 .help("add `#![feature(unboxed_closures)]` to the crate attributes to use it")
1034 let is_marker = tcx.has_attr(def_id, sym::marker);
1035 let def_path_hash = tcx.def_path_hash(def_id);
1036 let def = ty::TraitDef::new(def_id, unsafety, paren_sugar, is_auto, is_marker, def_path_hash);
1037 tcx.arena.alloc(def)
1040 fn has_late_bound_regions<'tcx>(tcx: TyCtxt<'tcx>, node: Node<'tcx>) -> Option<Span> {
1041 struct LateBoundRegionsDetector<'tcx> {
1043 outer_index: ty::DebruijnIndex,
1044 has_late_bound_regions: Option<Span>,
1047 impl Visitor<'tcx> for LateBoundRegionsDetector<'tcx> {
1048 type Map = Map<'tcx>;
1050 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
1051 NestedVisitorMap::None
1054 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
1055 if self.has_late_bound_regions.is_some() {
1059 hir::TyKind::BareFn(..) => {
1060 self.outer_index.shift_in(1);
1061 intravisit::walk_ty(self, ty);
1062 self.outer_index.shift_out(1);
1064 _ => intravisit::walk_ty(self, ty),
1068 fn visit_poly_trait_ref(
1070 tr: &'tcx hir::PolyTraitRef<'tcx>,
1071 m: hir::TraitBoundModifier,
1073 if self.has_late_bound_regions.is_some() {
1076 self.outer_index.shift_in(1);
1077 intravisit::walk_poly_trait_ref(self, tr, m);
1078 self.outer_index.shift_out(1);
1081 fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
1082 if self.has_late_bound_regions.is_some() {
1086 match self.tcx.named_region(lt.hir_id) {
1087 Some(rl::Region::Static) | Some(rl::Region::EarlyBound(..)) => {}
1088 Some(rl::Region::LateBound(debruijn, _, _))
1089 | Some(rl::Region::LateBoundAnon(debruijn, _))
1090 if debruijn < self.outer_index => {}
1091 Some(rl::Region::LateBound(..))
1092 | Some(rl::Region::LateBoundAnon(..))
1093 | Some(rl::Region::Free(..))
1095 self.has_late_bound_regions = Some(lt.span);
1101 fn has_late_bound_regions<'tcx>(
1103 generics: &'tcx hir::Generics<'tcx>,
1104 decl: &'tcx hir::FnDecl<'tcx>,
1106 let mut visitor = LateBoundRegionsDetector {
1108 outer_index: ty::INNERMOST,
1109 has_late_bound_regions: None,
1111 for param in generics.params {
1112 if let GenericParamKind::Lifetime { .. } = param.kind {
1113 if tcx.is_late_bound(param.hir_id) {
1114 return Some(param.span);
1118 visitor.visit_fn_decl(decl);
1119 visitor.has_late_bound_regions
1123 Node::TraitItem(item) => match item.kind {
1124 hir::TraitItemKind::Method(ref sig, _) => {
1125 has_late_bound_regions(tcx, &item.generics, &sig.decl)
1129 Node::ImplItem(item) => match item.kind {
1130 hir::ImplItemKind::Method(ref sig, _) => {
1131 has_late_bound_regions(tcx, &item.generics, &sig.decl)
1135 Node::ForeignItem(item) => match item.kind {
1136 hir::ForeignItemKind::Fn(ref fn_decl, _, ref generics) => {
1137 has_late_bound_regions(tcx, generics, fn_decl)
1141 Node::Item(item) => match item.kind {
1142 hir::ItemKind::Fn(ref sig, .., ref generics, _) => {
1143 has_late_bound_regions(tcx, generics, &sig.decl)
1151 fn generics_of(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::Generics {
1154 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1156 let node = tcx.hir().get(hir_id);
1157 let parent_def_id = match node {
1159 | Node::TraitItem(_)
1162 | Node::Field(_) => {
1163 let parent_id = tcx.hir().get_parent_item(hir_id);
1164 Some(tcx.hir().local_def_id(parent_id))
1166 // FIXME(#43408) enable this always when we get lazy normalization.
1167 Node::AnonConst(_) => {
1168 // HACK(eddyb) this provides the correct generics when
1169 // `feature(const_generics)` is enabled, so that const expressions
1170 // used with const generics, e.g. `Foo<{N+1}>`, can work at all.
1171 if tcx.features().const_generics {
1172 let parent_id = tcx.hir().get_parent_item(hir_id);
1173 Some(tcx.hir().local_def_id(parent_id))
1178 Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => {
1179 Some(tcx.closure_base_def_id(def_id))
1181 Node::Item(item) => match item.kind {
1182 ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn, .. }) => {
1183 impl_trait_fn.or_else(|| {
1184 let parent_id = tcx.hir().get_parent_item(hir_id);
1185 if parent_id != hir_id && parent_id != CRATE_HIR_ID {
1186 debug!("generics_of: parent of opaque ty {:?} is {:?}", def_id, parent_id);
1187 // If this 'impl Trait' is nested inside another 'impl Trait'
1188 // (e.g. `impl Foo<MyType = impl Bar<A>>`), we need to use the 'parent'
1189 // 'impl Trait' for its generic parameters, since we can reference them
1190 // from the 'child' 'impl Trait'
1191 if let Node::Item(hir::Item { kind: ItemKind::OpaqueTy(..), .. }) =
1192 tcx.hir().get(parent_id)
1194 Some(tcx.hir().local_def_id(parent_id))
1208 let mut opt_self = None;
1209 let mut allow_defaults = false;
1211 let no_generics = hir::Generics::empty();
1212 let ast_generics = match node {
1213 Node::TraitItem(item) => &item.generics,
1215 Node::ImplItem(item) => &item.generics,
1217 Node::Item(item) => {
1219 ItemKind::Fn(.., ref generics, _) | ItemKind::Impl { ref generics, .. } => generics,
1221 ItemKind::TyAlias(_, ref generics)
1222 | ItemKind::Enum(_, ref generics)
1223 | ItemKind::Struct(_, ref generics)
1224 | ItemKind::OpaqueTy(hir::OpaqueTy { ref generics, .. })
1225 | ItemKind::Union(_, ref generics) => {
1226 allow_defaults = true;
1230 ItemKind::Trait(_, _, ref generics, ..)
1231 | ItemKind::TraitAlias(ref generics, ..) => {
1232 // Add in the self type parameter.
1234 // Something of a hack: use the node id for the trait, also as
1235 // the node id for the Self type parameter.
1236 let param_id = item.hir_id;
1238 opt_self = Some(ty::GenericParamDef {
1240 name: kw::SelfUpper,
1241 def_id: tcx.hir().local_def_id(param_id),
1242 pure_wrt_drop: false,
1243 kind: ty::GenericParamDefKind::Type {
1245 object_lifetime_default: rl::Set1::Empty,
1250 allow_defaults = true;
1258 Node::ForeignItem(item) => match item.kind {
1259 ForeignItemKind::Static(..) => &no_generics,
1260 ForeignItemKind::Fn(_, _, ref generics) => generics,
1261 ForeignItemKind::Type => &no_generics,
1267 let has_self = opt_self.is_some();
1268 let mut parent_has_self = false;
1269 let mut own_start = has_self as u32;
1270 let parent_count = parent_def_id.map_or(0, |def_id| {
1271 let generics = tcx.generics_of(def_id);
1272 assert_eq!(has_self, false);
1273 parent_has_self = generics.has_self;
1274 own_start = generics.count() as u32;
1275 generics.parent_count + generics.params.len()
1278 let mut params: Vec<_> = opt_self.into_iter().collect();
1280 let early_lifetimes = early_bound_lifetimes_from_generics(tcx, ast_generics);
1281 params.extend(early_lifetimes.enumerate().map(|(i, param)| ty::GenericParamDef {
1282 name: param.name.ident().name,
1283 index: own_start + i as u32,
1284 def_id: tcx.hir().local_def_id(param.hir_id),
1285 pure_wrt_drop: param.pure_wrt_drop,
1286 kind: ty::GenericParamDefKind::Lifetime,
1289 let object_lifetime_defaults = tcx.object_lifetime_defaults(hir_id);
1291 // Now create the real type and const parameters.
1292 let type_start = own_start - has_self as u32 + params.len() as u32;
1294 params.extend(ast_generics.params.iter().filter_map(|param| {
1295 let kind = match param.kind {
1296 GenericParamKind::Type { ref default, synthetic, .. } => {
1297 if !allow_defaults && default.is_some() {
1298 if !tcx.features().default_type_parameter_fallback {
1299 tcx.struct_span_lint_hir(
1300 lint::builtin::INVALID_TYPE_PARAM_DEFAULT,
1304 lint.build(&format!(
1305 "defaults for type parameters are only allowed in \
1306 `struct`, `enum`, `type`, or `trait` definitions."
1314 ty::GenericParamDefKind::Type {
1315 has_default: default.is_some(),
1316 object_lifetime_default: object_lifetime_defaults
1318 .map_or(rl::Set1::Empty, |o| o[i]),
1322 GenericParamKind::Const { .. } => ty::GenericParamDefKind::Const,
1326 let param_def = ty::GenericParamDef {
1327 index: type_start + i as u32,
1328 name: param.name.ident().name,
1329 def_id: tcx.hir().local_def_id(param.hir_id),
1330 pure_wrt_drop: param.pure_wrt_drop,
1337 // provide junk type parameter defs - the only place that
1338 // cares about anything but the length is instantiation,
1339 // and we don't do that for closures.
1340 if let Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(.., gen), .. }) = node {
1341 let dummy_args = if gen.is_some() {
1342 &["<resume_ty>", "<yield_ty>", "<return_ty>", "<witness>"][..]
1344 &["<closure_kind>", "<closure_signature>"][..]
1347 params.extend(dummy_args.iter().enumerate().map(|(i, &arg)| ty::GenericParamDef {
1348 index: type_start + i as u32,
1349 name: Symbol::intern(arg),
1351 pure_wrt_drop: false,
1352 kind: ty::GenericParamDefKind::Type {
1354 object_lifetime_default: rl::Set1::Empty,
1359 if let Some(upvars) = tcx.upvars(def_id) {
1360 params.extend(upvars.iter().zip((dummy_args.len() as u32)..).map(|(_, i)| {
1361 ty::GenericParamDef {
1362 index: type_start + i,
1363 name: Symbol::intern("<upvar>"),
1365 pure_wrt_drop: false,
1366 kind: ty::GenericParamDefKind::Type {
1368 object_lifetime_default: rl::Set1::Empty,
1376 let param_def_id_to_index = params.iter().map(|param| (param.def_id, param.index)).collect();
1378 tcx.arena.alloc(ty::Generics {
1379 parent: parent_def_id,
1382 param_def_id_to_index,
1383 has_self: has_self || parent_has_self,
1384 has_late_bound_regions: has_late_bound_regions(tcx, node),
1388 fn are_suggestable_generic_args(generic_args: &[hir::GenericArg<'_>]) -> bool {
1391 .filter_map(|arg| match arg {
1392 hir::GenericArg::Type(ty) => Some(ty),
1395 .any(is_suggestable_infer_ty)
1398 /// Whether `ty` is a type with `_` placeholders that can be infered. Used in diagnostics only to
1399 /// use inference to provide suggestions for the appropriate type if possible.
1400 fn is_suggestable_infer_ty(ty: &hir::Ty<'_>) -> bool {
1404 Slice(ty) | Array(ty, _) => is_suggestable_infer_ty(ty),
1405 Tup(tys) => tys.iter().any(is_suggestable_infer_ty),
1406 Ptr(mut_ty) | Rptr(_, mut_ty) => is_suggestable_infer_ty(mut_ty.ty),
1407 Def(_, generic_args) => are_suggestable_generic_args(generic_args),
1408 Path(hir::QPath::TypeRelative(ty, segment)) => {
1409 is_suggestable_infer_ty(ty) || are_suggestable_generic_args(segment.generic_args().args)
1411 Path(hir::QPath::Resolved(ty_opt, hir::Path { segments, .. })) => {
1412 ty_opt.map_or(false, is_suggestable_infer_ty)
1415 .any(|segment| are_suggestable_generic_args(segment.generic_args().args))
1421 pub fn get_infer_ret_ty(output: &'hir hir::FnRetTy<'hir>) -> Option<&'hir hir::Ty<'hir>> {
1422 if let hir::FnRetTy::Return(ref ty) = output {
1423 if is_suggestable_infer_ty(ty) {
1430 fn fn_sig(tcx: TyCtxt<'_>, def_id: DefId) -> ty::PolyFnSig<'_> {
1431 use rustc_hir::Node::*;
1434 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1436 let icx = ItemCtxt::new(tcx, def_id);
1438 match tcx.hir().get(hir_id) {
1439 TraitItem(hir::TraitItem {
1440 kind: TraitItemKind::Method(sig, TraitMethod::Provided(_)),
1445 | ImplItem(hir::ImplItem { kind: ImplItemKind::Method(sig, _), ident, generics, .. })
1446 | Item(hir::Item { kind: ItemKind::Fn(sig, generics, _), ident, .. }) => {
1447 match get_infer_ret_ty(&sig.decl.output) {
1449 let fn_sig = tcx.typeck_tables_of(def_id).liberated_fn_sigs()[hir_id];
1450 let mut visitor = PlaceholderHirTyCollector::default();
1451 visitor.visit_ty(ty);
1452 let mut diag = bad_placeholder_type(tcx, visitor.0);
1453 let ret_ty = fn_sig.output();
1454 if ret_ty != tcx.types.err {
1455 diag.span_suggestion(
1457 "replace with the correct return type",
1459 Applicability::MaybeIncorrect,
1463 ty::Binder::bind(fn_sig)
1465 None => AstConv::ty_of_fn(
1467 sig.header.unsafety,
1470 &generics.params[..],
1476 TraitItem(hir::TraitItem {
1477 kind: TraitItemKind::Method(FnSig { header, decl }, _),
1481 }) => AstConv::ty_of_fn(
1486 &generics.params[..],
1490 ForeignItem(&hir::ForeignItem { kind: ForeignItemKind::Fn(ref fn_decl, _, _), .. }) => {
1491 let abi = tcx.hir().get_foreign_abi(hir_id);
1492 compute_sig_of_foreign_fn_decl(tcx, def_id, fn_decl, abi)
1495 Ctor(data) | Variant(hir::Variant { data, .. }) if data.ctor_hir_id().is_some() => {
1496 let ty = tcx.type_of(tcx.hir().get_parent_did(hir_id));
1498 data.fields().iter().map(|f| tcx.type_of(tcx.hir().local_def_id(f.hir_id)));
1499 ty::Binder::bind(tcx.mk_fn_sig(
1503 hir::Unsafety::Normal,
1508 Expr(&hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => {
1509 // Closure signatures are not like other function
1510 // signatures and cannot be accessed through `fn_sig`. For
1511 // example, a closure signature excludes the `self`
1512 // argument. In any case they are embedded within the
1513 // closure type as part of the `ClosureSubsts`.
1516 // the signature of a closure, you should use the
1517 // `closure_sig` method on the `ClosureSubsts`:
1519 // closure_substs.sig(def_id, tcx)
1521 // or, inside of an inference context, you can use
1523 // infcx.closure_sig(def_id, closure_substs)
1524 bug!("to get the signature of a closure, use `closure_sig()` not `fn_sig()`");
1528 bug!("unexpected sort of node in fn_sig(): {:?}", x);
1533 fn impl_trait_ref(tcx: TyCtxt<'_>, def_id: DefId) -> Option<ty::TraitRef<'_>> {
1534 let icx = ItemCtxt::new(tcx, def_id);
1536 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1537 match tcx.hir().expect_item(hir_id).kind {
1538 hir::ItemKind::Impl { ref of_trait, .. } => of_trait.as_ref().map(|ast_trait_ref| {
1539 let selfty = tcx.type_of(def_id);
1540 AstConv::instantiate_mono_trait_ref(&icx, ast_trait_ref, selfty)
1546 fn impl_polarity(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ImplPolarity {
1547 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1548 let is_rustc_reservation = tcx.has_attr(def_id, sym::rustc_reservation_impl);
1549 let item = tcx.hir().expect_item(hir_id);
1551 hir::ItemKind::Impl { polarity: hir::ImplPolarity::Negative, .. } => {
1552 if is_rustc_reservation {
1553 tcx.sess.span_err(item.span, "reservation impls can't be negative");
1555 ty::ImplPolarity::Negative
1557 hir::ItemKind::Impl { polarity: hir::ImplPolarity::Positive, of_trait: None, .. } => {
1558 if is_rustc_reservation {
1559 tcx.sess.span_err(item.span, "reservation impls can't be inherent");
1561 ty::ImplPolarity::Positive
1563 hir::ItemKind::Impl {
1564 polarity: hir::ImplPolarity::Positive, of_trait: Some(_), ..
1566 if is_rustc_reservation {
1567 ty::ImplPolarity::Reservation
1569 ty::ImplPolarity::Positive
1572 ref item => bug!("impl_polarity: {:?} not an impl", item),
1576 /// Returns the early-bound lifetimes declared in this generics
1577 /// listing. For anything other than fns/methods, this is just all
1578 /// the lifetimes that are declared. For fns or methods, we have to
1579 /// screen out those that do not appear in any where-clauses etc using
1580 /// `resolve_lifetime::early_bound_lifetimes`.
1581 fn early_bound_lifetimes_from_generics<'a, 'tcx: 'a>(
1583 generics: &'a hir::Generics<'a>,
1584 ) -> impl Iterator<Item = &'a hir::GenericParam<'a>> + Captures<'tcx> {
1585 generics.params.iter().filter(move |param| match param.kind {
1586 GenericParamKind::Lifetime { .. } => !tcx.is_late_bound(param.hir_id),
1591 /// Returns a list of type predicates for the definition with ID `def_id`, including inferred
1592 /// lifetime constraints. This includes all predicates returned by `explicit_predicates_of`, plus
1593 /// inferred constraints concerning which regions outlive other regions.
1594 fn predicates_defined_on(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1595 debug!("predicates_defined_on({:?})", def_id);
1596 let mut result = tcx.explicit_predicates_of(def_id);
1597 debug!("predicates_defined_on: explicit_predicates_of({:?}) = {:?}", def_id, result,);
1598 let inferred_outlives = tcx.inferred_outlives_of(def_id);
1599 if !inferred_outlives.is_empty() {
1601 "predicates_defined_on: inferred_outlives_of({:?}) = {:?}",
1602 def_id, inferred_outlives,
1604 if result.predicates.is_empty() {
1605 result.predicates = inferred_outlives;
1607 result.predicates = tcx
1609 .alloc_from_iter(result.predicates.iter().chain(inferred_outlives).copied());
1612 debug!("predicates_defined_on({:?}) = {:?}", def_id, result);
1616 /// Returns a list of all type predicates (explicit and implicit) for the definition with
1617 /// ID `def_id`. This includes all predicates returned by `predicates_defined_on`, plus
1618 /// `Self: Trait` predicates for traits.
1619 fn predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1620 let mut result = tcx.predicates_defined_on(def_id);
1622 if tcx.is_trait(def_id) {
1623 // For traits, add `Self: Trait` predicate. This is
1624 // not part of the predicates that a user writes, but it
1625 // is something that one must prove in order to invoke a
1626 // method or project an associated type.
1628 // In the chalk setup, this predicate is not part of the
1629 // "predicates" for a trait item. But it is useful in
1630 // rustc because if you directly (e.g.) invoke a trait
1631 // method like `Trait::method(...)`, you must naturally
1632 // prove that the trait applies to the types that were
1633 // used, and adding the predicate into this list ensures
1634 // that this is done.
1635 let span = tcx.def_span(def_id);
1637 tcx.arena.alloc_from_iter(result.predicates.iter().copied().chain(std::iter::once((
1638 ty::TraitRef::identity(tcx, def_id).without_const().to_predicate(),
1642 debug!("predicates_of(def_id={:?}) = {:?}", def_id, result);
1646 /// Returns a list of user-specified type predicates for the definition with ID `def_id`.
1647 /// N.B., this does not include any implied/inferred constraints.
1648 fn explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1651 debug!("explicit_predicates_of(def_id={:?})", def_id);
1653 /// A data structure with unique elements, which preserves order of insertion.
1654 /// Preserving the order of insertion is important here so as not to break
1655 /// compile-fail UI tests.
1656 // FIXME(eddyb) just use `IndexSet` from `indexmap`.
1657 struct UniquePredicates<'tcx> {
1658 predicates: Vec<(ty::Predicate<'tcx>, Span)>,
1659 uniques: FxHashSet<(ty::Predicate<'tcx>, Span)>,
1662 impl<'tcx> UniquePredicates<'tcx> {
1664 UniquePredicates { predicates: vec![], uniques: FxHashSet::default() }
1667 fn push(&mut self, value: (ty::Predicate<'tcx>, Span)) {
1668 if self.uniques.insert(value) {
1669 self.predicates.push(value);
1673 fn extend<I: IntoIterator<Item = (ty::Predicate<'tcx>, Span)>>(&mut self, iter: I) {
1680 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1681 let node = tcx.hir().get(hir_id);
1683 let mut is_trait = None;
1684 let mut is_default_impl_trait = None;
1686 let icx = ItemCtxt::new(tcx, def_id);
1687 let constness = icx.default_constness_for_trait_bounds();
1689 const NO_GENERICS: &hir::Generics<'_> = &hir::Generics::empty();
1691 let mut predicates = UniquePredicates::new();
1693 let ast_generics = match node {
1694 Node::TraitItem(item) => &item.generics,
1696 Node::ImplItem(item) => match item.kind {
1697 ImplItemKind::OpaqueTy(ref bounds) => {
1698 ty::print::with_no_queries(|| {
1699 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1700 let opaque_ty = tcx.mk_opaque(def_id, substs);
1702 "explicit_predicates_of({:?}): created opaque type {:?}",
1706 // Collect the bounds, i.e., the `A + B + 'c` in `impl A + B + 'c`.
1707 let bounds = AstConv::compute_bounds(
1711 SizedByDefault::Yes,
1712 tcx.def_span(def_id),
1715 predicates.extend(bounds.predicates(tcx, opaque_ty));
1719 _ => &item.generics,
1722 Node::Item(item) => {
1724 ItemKind::Impl { defaultness, ref generics, .. } => {
1725 if defaultness.is_default() {
1726 is_default_impl_trait = tcx.impl_trait_ref(def_id);
1730 ItemKind::Fn(.., ref generics, _)
1731 | ItemKind::TyAlias(_, ref generics)
1732 | ItemKind::Enum(_, ref generics)
1733 | ItemKind::Struct(_, ref generics)
1734 | ItemKind::Union(_, ref generics) => generics,
1736 ItemKind::Trait(_, _, ref generics, .., items) => {
1737 is_trait = Some((ty::TraitRef::identity(tcx, def_id), items));
1740 ItemKind::TraitAlias(ref generics, _) => {
1741 is_trait = Some((ty::TraitRef::identity(tcx, def_id), &[]));
1744 ItemKind::OpaqueTy(OpaqueTy {
1750 let bounds_predicates = ty::print::with_no_queries(|| {
1751 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1752 let opaque_ty = tcx.mk_opaque(def_id, substs);
1754 // Collect the bounds, i.e., the `A + B + 'c` in `impl A + B + 'c`.
1755 let bounds = AstConv::compute_bounds(
1759 SizedByDefault::Yes,
1760 tcx.def_span(def_id),
1763 bounds.predicates(tcx, opaque_ty)
1765 if impl_trait_fn.is_some() {
1767 return ty::GenericPredicates {
1769 predicates: tcx.arena.alloc_from_iter(bounds_predicates),
1772 // named opaque types
1773 predicates.extend(bounds_predicates);
1782 Node::ForeignItem(item) => match item.kind {
1783 ForeignItemKind::Static(..) => NO_GENERICS,
1784 ForeignItemKind::Fn(_, _, ref generics) => generics,
1785 ForeignItemKind::Type => NO_GENERICS,
1791 let generics = tcx.generics_of(def_id);
1792 let parent_count = generics.parent_count as u32;
1793 let has_own_self = generics.has_self && parent_count == 0;
1795 // Below we'll consider the bounds on the type parameters (including `Self`)
1796 // and the explicit where-clauses, but to get the full set of predicates
1797 // on a trait we need to add in the supertrait bounds and bounds found on
1798 // associated types.
1799 if let Some((_trait_ref, _)) = is_trait {
1800 predicates.extend(tcx.super_predicates_of(def_id).predicates.iter().cloned());
1803 // In default impls, we can assume that the self type implements
1804 // the trait. So in:
1806 // default impl Foo for Bar { .. }
1808 // we add a default where clause `Foo: Bar`. We do a similar thing for traits
1809 // (see below). Recall that a default impl is not itself an impl, but rather a
1810 // set of defaults that can be incorporated into another impl.
1811 if let Some(trait_ref) = is_default_impl_trait {
1813 trait_ref.to_poly_trait_ref().without_const().to_predicate(),
1814 tcx.def_span(def_id),
1818 // Collect the region predicates that were declared inline as
1819 // well. In the case of parameters declared on a fn or method, we
1820 // have to be careful to only iterate over early-bound regions.
1821 let mut index = parent_count + has_own_self as u32;
1822 for param in early_bound_lifetimes_from_generics(tcx, ast_generics) {
1823 let region = tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
1824 def_id: tcx.hir().local_def_id(param.hir_id),
1826 name: param.name.ident().name,
1831 GenericParamKind::Lifetime { .. } => {
1832 param.bounds.iter().for_each(|bound| match bound {
1833 hir::GenericBound::Outlives(lt) => {
1834 let bound = AstConv::ast_region_to_region(&icx, <, None);
1835 let outlives = ty::Binder::bind(ty::OutlivesPredicate(region, bound));
1836 predicates.push((outlives.to_predicate(), lt.span));
1845 // Collect the predicates that were written inline by the user on each
1846 // type parameter (e.g., `<T: Foo>`).
1847 for param in ast_generics.params {
1848 if let GenericParamKind::Type { .. } = param.kind {
1849 let name = param.name.ident().name;
1850 let param_ty = ty::ParamTy::new(index, name).to_ty(tcx);
1853 let sized = SizedByDefault::Yes;
1854 let bounds = AstConv::compute_bounds(&icx, param_ty, ¶m.bounds, sized, param.span);
1855 predicates.extend(bounds.predicates(tcx, param_ty));
1859 // Add in the bounds that appear in the where-clause.
1860 let where_clause = &ast_generics.where_clause;
1861 for predicate in where_clause.predicates {
1863 &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
1864 let ty = icx.to_ty(&bound_pred.bounded_ty);
1866 // Keep the type around in a dummy predicate, in case of no bounds.
1867 // That way, `where Ty:` is not a complete noop (see #53696) and `Ty`
1868 // is still checked for WF.
1869 if bound_pred.bounds.is_empty() {
1870 if let ty::Param(_) = ty.kind {
1871 // This is a `where T:`, which can be in the HIR from the
1872 // transformation that moves `?Sized` to `T`'s declaration.
1873 // We can skip the predicate because type parameters are
1874 // trivially WF, but also we *should*, to avoid exposing
1875 // users who never wrote `where Type:,` themselves, to
1876 // compiler/tooling bugs from not handling WF predicates.
1878 let span = bound_pred.bounded_ty.span;
1879 let re_root_empty = tcx.lifetimes.re_root_empty;
1880 let predicate = ty::OutlivesPredicate(ty, re_root_empty);
1882 ty::Predicate::TypeOutlives(ty::Binder::dummy(predicate)),
1888 for bound in bound_pred.bounds.iter() {
1890 &hir::GenericBound::Trait(ref poly_trait_ref, modifier) => {
1891 let constness = match modifier {
1892 hir::TraitBoundModifier::MaybeConst => hir::Constness::NotConst,
1893 hir::TraitBoundModifier::None => constness,
1894 hir::TraitBoundModifier::Maybe => bug!("this wasn't handled"),
1897 let mut bounds = Bounds::default();
1898 let _ = AstConv::instantiate_poly_trait_ref(
1905 predicates.extend(bounds.predicates(tcx, ty));
1908 &hir::GenericBound::Outlives(ref lifetime) => {
1909 let region = AstConv::ast_region_to_region(&icx, lifetime, None);
1910 let pred = ty::Binder::bind(ty::OutlivesPredicate(ty, region));
1911 predicates.push((ty::Predicate::TypeOutlives(pred), lifetime.span))
1917 &hir::WherePredicate::RegionPredicate(ref region_pred) => {
1918 let r1 = AstConv::ast_region_to_region(&icx, ®ion_pred.lifetime, None);
1919 predicates.extend(region_pred.bounds.iter().map(|bound| {
1920 let (r2, span) = match bound {
1921 hir::GenericBound::Outlives(lt) => {
1922 (AstConv::ast_region_to_region(&icx, lt, None), lt.span)
1926 let pred = ty::Binder::bind(ty::OutlivesPredicate(r1, r2));
1928 (ty::Predicate::RegionOutlives(pred), span)
1932 &hir::WherePredicate::EqPredicate(..) => {
1938 // Add predicates from associated type bounds.
1939 if let Some((self_trait_ref, trait_items)) = is_trait {
1940 predicates.extend(trait_items.iter().flat_map(|trait_item_ref| {
1941 associated_item_predicates(tcx, def_id, self_trait_ref, trait_item_ref)
1945 let mut predicates = predicates.predicates;
1947 // Subtle: before we store the predicates into the tcx, we
1948 // sort them so that predicates like `T: Foo<Item=U>` come
1949 // before uses of `U`. This avoids false ambiguity errors
1950 // in trait checking. See `setup_constraining_predicates`
1952 if let Node::Item(&Item { kind: ItemKind::Impl { .. }, .. }) = node {
1953 let self_ty = tcx.type_of(def_id);
1954 let trait_ref = tcx.impl_trait_ref(def_id);
1955 cgp::setup_constraining_predicates(
1959 &mut cgp::parameters_for_impl(self_ty, trait_ref),
1963 let result = ty::GenericPredicates {
1964 parent: generics.parent,
1965 predicates: tcx.arena.alloc_from_iter(predicates),
1967 debug!("explicit_predicates_of(def_id={:?}) = {:?}", def_id, result);
1971 fn associated_item_predicates(
1974 self_trait_ref: ty::TraitRef<'tcx>,
1975 trait_item_ref: &hir::TraitItemRef,
1976 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
1977 let trait_item = tcx.hir().trait_item(trait_item_ref.id);
1978 let item_def_id = tcx.hir().local_def_id(trait_item_ref.id.hir_id);
1979 let bounds = match trait_item.kind {
1980 hir::TraitItemKind::Type(ref bounds, _) => bounds,
1981 _ => return Vec::new(),
1984 let is_gat = !tcx.generics_of(item_def_id).params.is_empty();
1986 let mut had_error = false;
1988 let mut unimplemented_error = |arg_kind: &str| {
1993 &format!("{}-generic associated types are not yet implemented", arg_kind),
1996 "for more information, see issue #44265 \
1997 <https://github.com/rust-lang/rust/issues/44265> for more information",
2004 let mk_bound_param = |param: &ty::GenericParamDef, _: &_| {
2006 ty::GenericParamDefKind::Lifetime => tcx
2007 .mk_region(ty::RegionKind::ReLateBound(
2009 ty::BoundRegion::BrNamed(param.def_id, param.name),
2012 // FIXME(generic_associated_types): Use bound types and constants
2013 // once they are handled by the trait system.
2014 ty::GenericParamDefKind::Type { .. } => {
2015 unimplemented_error("type");
2016 tcx.types.err.into()
2018 ty::GenericParamDefKind::Const => {
2019 unimplemented_error("const");
2020 tcx.consts.err.into()
2025 let bound_substs = if is_gat {
2028 // trait X<'a, B, const C: usize> {
2029 // type T<'d, E, const F: usize>: Default;
2032 // We need to create predicates on the trait:
2034 // for<'d, E, const F: usize>
2035 // <Self as X<'a, B, const C: usize>>::T<'d, E, const F: usize>: Sized + Default
2037 // We substitute escaping bound parameters for the generic
2038 // arguments to the associated type which are then bound by
2039 // the `Binder` around the the predicate.
2041 // FIXME(generic_associated_types): Currently only lifetimes are handled.
2042 self_trait_ref.substs.extend_to(tcx, item_def_id, mk_bound_param)
2044 self_trait_ref.substs
2047 let assoc_ty = tcx.mk_projection(tcx.hir().local_def_id(trait_item.hir_id), bound_substs);
2049 let bounds = AstConv::compute_bounds(
2050 &ItemCtxt::new(tcx, def_id),
2053 SizedByDefault::Yes,
2057 let predicates = bounds.predicates(tcx, assoc_ty);
2060 // We use shifts to get the regions that we're substituting to
2061 // be bound by the binders in the `Predicate`s rather that
2063 let shifted_in = ty::fold::shift_vars(tcx, &predicates, 1);
2064 let substituted = shifted_in.subst(tcx, bound_substs);
2065 ty::fold::shift_out_vars(tcx, &substituted, 1)
2071 /// Converts a specific `GenericBound` from the AST into a set of
2072 /// predicates that apply to the self type. A vector is returned
2073 /// because this can be anywhere from zero predicates (`T: ?Sized` adds no
2074 /// predicates) to one (`T: Foo`) to many (`T: Bar<X = i32>` adds `T: Bar`
2075 /// and `<T as Bar>::X == i32`).
2076 fn predicates_from_bound<'tcx>(
2077 astconv: &dyn AstConv<'tcx>,
2079 bound: &'tcx hir::GenericBound<'tcx>,
2080 constness: hir::Constness,
2081 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2083 hir::GenericBound::Trait(ref tr, modifier) => {
2084 let constness = match modifier {
2085 hir::TraitBoundModifier::Maybe => return vec![],
2086 hir::TraitBoundModifier::MaybeConst => hir::Constness::NotConst,
2087 hir::TraitBoundModifier::None => constness,
2090 let mut bounds = Bounds::default();
2091 let _ = astconv.instantiate_poly_trait_ref(tr, constness, param_ty, &mut bounds);
2092 bounds.predicates(astconv.tcx(), param_ty)
2094 hir::GenericBound::Outlives(ref lifetime) => {
2095 let region = astconv.ast_region_to_region(lifetime, None);
2096 let pred = ty::Binder::bind(ty::OutlivesPredicate(param_ty, region));
2097 vec![(ty::Predicate::TypeOutlives(pred), lifetime.span)]
2102 fn compute_sig_of_foreign_fn_decl<'tcx>(
2105 decl: &'tcx hir::FnDecl<'tcx>,
2107 ) -> ty::PolyFnSig<'tcx> {
2108 let unsafety = if abi == abi::Abi::RustIntrinsic {
2109 intrinsic_operation_unsafety(&tcx.item_name(def_id).as_str())
2111 hir::Unsafety::Unsafe
2113 let fty = AstConv::ty_of_fn(&ItemCtxt::new(tcx, def_id), unsafety, abi, decl, &[], None);
2115 // Feature gate SIMD types in FFI, since I am not sure that the
2116 // ABIs are handled at all correctly. -huonw
2117 if abi != abi::Abi::RustIntrinsic
2118 && abi != abi::Abi::PlatformIntrinsic
2119 && !tcx.features().simd_ffi
2121 let check = |ast_ty: &hir::Ty<'_>, ty: Ty<'_>| {
2127 "use of SIMD type `{}` in FFI is highly experimental and \
2128 may result in invalid code",
2129 tcx.hir().hir_to_pretty_string(ast_ty.hir_id)
2132 .help("add `#![feature(simd_ffi)]` to the crate attributes to enable")
2136 for (input, ty) in decl.inputs.iter().zip(*fty.inputs().skip_binder()) {
2139 if let hir::FnRetTy::Return(ref ty) = decl.output {
2140 check(&ty, *fty.output().skip_binder())
2147 fn is_foreign_item(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
2148 match tcx.hir().get_if_local(def_id) {
2149 Some(Node::ForeignItem(..)) => true,
2151 _ => bug!("is_foreign_item applied to non-local def-id {:?}", def_id),
2155 fn static_mutability(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::Mutability> {
2156 match tcx.hir().get_if_local(def_id) {
2157 Some(Node::Item(&hir::Item { kind: hir::ItemKind::Static(_, mutbl, _), .. }))
2158 | Some(Node::ForeignItem(&hir::ForeignItem {
2159 kind: hir::ForeignItemKind::Static(_, mutbl),
2163 _ => bug!("static_mutability applied to non-local def-id {:?}", def_id),
2167 fn generator_kind(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::GeneratorKind> {
2168 match tcx.hir().get_if_local(def_id) {
2169 Some(Node::Expr(&rustc_hir::Expr {
2170 kind: rustc_hir::ExprKind::Closure(_, _, body_id, _, _),
2172 })) => tcx.hir().body(body_id).generator_kind(),
2174 _ => bug!("generator_kind applied to non-local def-id {:?}", def_id),
2178 fn from_target_feature(
2181 attr: &ast::Attribute,
2182 whitelist: &FxHashMap<String, Option<Symbol>>,
2183 target_features: &mut Vec<Symbol>,
2185 let list = match attr.meta_item_list() {
2189 let bad_item = |span| {
2190 let msg = "malformed `target_feature` attribute input";
2191 let code = "enable = \"..\"".to_owned();
2193 .struct_span_err(span, &msg)
2194 .span_suggestion(span, "must be of the form", code, Applicability::HasPlaceholders)
2197 let rust_features = tcx.features();
2199 // Only `enable = ...` is accepted in the meta-item list.
2200 if !item.check_name(sym::enable) {
2201 bad_item(item.span());
2205 // Must be of the form `enable = "..."` (a string).
2206 let value = match item.value_str() {
2207 Some(value) => value,
2209 bad_item(item.span());
2214 // We allow comma separation to enable multiple features.
2215 target_features.extend(value.as_str().split(',').filter_map(|feature| {
2216 // Only allow whitelisted features per platform.
2217 let feature_gate = match whitelist.get(feature) {
2221 format!("the feature named `{}` is not valid for this target", feature);
2222 let mut err = tcx.sess.struct_span_err(item.span(), &msg);
2225 format!("`{}` is not valid for this target", feature),
2227 if feature.starts_with("+") {
2228 let valid = whitelist.contains_key(&feature[1..]);
2230 err.help("consider removing the leading `+` in the feature name");
2238 // Only allow features whose feature gates have been enabled.
2239 let allowed = match feature_gate.as_ref().map(|s| *s) {
2240 Some(sym::arm_target_feature) => rust_features.arm_target_feature,
2241 Some(sym::aarch64_target_feature) => rust_features.aarch64_target_feature,
2242 Some(sym::hexagon_target_feature) => rust_features.hexagon_target_feature,
2243 Some(sym::powerpc_target_feature) => rust_features.powerpc_target_feature,
2244 Some(sym::mips_target_feature) => rust_features.mips_target_feature,
2245 Some(sym::avx512_target_feature) => rust_features.avx512_target_feature,
2246 Some(sym::mmx_target_feature) => rust_features.mmx_target_feature,
2247 Some(sym::sse4a_target_feature) => rust_features.sse4a_target_feature,
2248 Some(sym::tbm_target_feature) => rust_features.tbm_target_feature,
2249 Some(sym::wasm_target_feature) => rust_features.wasm_target_feature,
2250 Some(sym::cmpxchg16b_target_feature) => rust_features.cmpxchg16b_target_feature,
2251 Some(sym::adx_target_feature) => rust_features.adx_target_feature,
2252 Some(sym::movbe_target_feature) => rust_features.movbe_target_feature,
2253 Some(sym::rtm_target_feature) => rust_features.rtm_target_feature,
2254 Some(sym::f16c_target_feature) => rust_features.f16c_target_feature,
2255 Some(name) => bug!("unknown target feature gate {}", name),
2258 if !allowed && id.is_local() {
2260 &tcx.sess.parse_sess,
2261 feature_gate.unwrap(),
2263 &format!("the target feature `{}` is currently unstable", feature),
2267 Some(Symbol::intern(feature))
2272 fn linkage_by_name(tcx: TyCtxt<'_>, def_id: DefId, name: &str) -> Linkage {
2273 use rustc::mir::mono::Linkage::*;
2275 // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
2276 // applicable to variable declarations and may not really make sense for
2277 // Rust code in the first place but whitelist them anyway and trust that
2278 // the user knows what s/he's doing. Who knows, unanticipated use cases
2279 // may pop up in the future.
2281 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
2282 // and don't have to be, LLVM treats them as no-ops.
2284 "appending" => Appending,
2285 "available_externally" => AvailableExternally,
2287 "extern_weak" => ExternalWeak,
2288 "external" => External,
2289 "internal" => Internal,
2290 "linkonce" => LinkOnceAny,
2291 "linkonce_odr" => LinkOnceODR,
2292 "private" => Private,
2294 "weak_odr" => WeakODR,
2296 let span = tcx.hir().span_if_local(def_id);
2297 if let Some(span) = span {
2298 tcx.sess.span_fatal(span, "invalid linkage specified")
2300 tcx.sess.fatal(&format!("invalid linkage specified: {}", name))
2306 fn codegen_fn_attrs(tcx: TyCtxt<'_>, id: DefId) -> CodegenFnAttrs {
2307 let attrs = tcx.get_attrs(id);
2309 let mut codegen_fn_attrs = CodegenFnAttrs::new();
2311 let whitelist = tcx.target_features_whitelist(LOCAL_CRATE);
2313 let mut inline_span = None;
2314 let mut link_ordinal_span = None;
2315 let mut no_sanitize_span = None;
2316 for attr in attrs.iter() {
2317 if attr.check_name(sym::cold) {
2318 codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD;
2319 } else if attr.check_name(sym::rustc_allocator) {
2320 codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR;
2321 } else if attr.check_name(sym::unwind) {
2322 codegen_fn_attrs.flags |= CodegenFnAttrFlags::UNWIND;
2323 } else if attr.check_name(sym::ffi_returns_twice) {
2324 if tcx.is_foreign_item(id) {
2325 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_RETURNS_TWICE;
2327 // `#[ffi_returns_twice]` is only allowed `extern fn`s.
2332 "`#[ffi_returns_twice]` may only be used on foreign functions"
2336 } else if attr.check_name(sym::rustc_allocator_nounwind) {
2337 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND;
2338 } else if attr.check_name(sym::naked) {
2339 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED;
2340 } else if attr.check_name(sym::no_mangle) {
2341 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2342 } else if attr.check_name(sym::rustc_std_internal_symbol) {
2343 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2344 } else if attr.check_name(sym::no_debug) {
2345 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_DEBUG;
2346 } else if attr.check_name(sym::used) {
2347 codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED;
2348 } else if attr.check_name(sym::thread_local) {
2349 codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL;
2350 } else if attr.check_name(sym::track_caller) {
2351 if tcx.is_closure(id) || tcx.fn_sig(id).abi() != abi::Abi::Rust {
2352 struct_span_err!(tcx.sess, attr.span, E0737, "`#[track_caller]` requires Rust ABI")
2355 codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
2356 } else if attr.check_name(sym::export_name) {
2357 if let Some(s) = attr.value_str() {
2358 if s.as_str().contains("\0") {
2359 // `#[export_name = ...]` will be converted to a null-terminated string,
2360 // so it may not contain any null characters.
2365 "`export_name` may not contain null characters"
2369 codegen_fn_attrs.export_name = Some(s);
2371 } else if attr.check_name(sym::target_feature) {
2372 if tcx.is_closure(id) || tcx.fn_sig(id).unsafety() == Unsafety::Normal {
2373 let msg = "`#[target_feature(..)]` can only be applied to `unsafe` functions";
2375 .struct_span_err(attr.span, msg)
2376 .span_label(attr.span, "can only be applied to `unsafe` functions")
2377 .span_label(tcx.def_span(id), "not an `unsafe` function")
2380 from_target_feature(tcx, id, attr, &whitelist, &mut codegen_fn_attrs.target_features);
2381 } else if attr.check_name(sym::linkage) {
2382 if let Some(val) = attr.value_str() {
2383 codegen_fn_attrs.linkage = Some(linkage_by_name(tcx, id, &val.as_str()));
2385 } else if attr.check_name(sym::link_section) {
2386 if let Some(val) = attr.value_str() {
2387 if val.as_str().bytes().any(|b| b == 0) {
2389 "illegal null byte in link_section \
2393 tcx.sess.span_err(attr.span, &msg);
2395 codegen_fn_attrs.link_section = Some(val);
2398 } else if attr.check_name(sym::link_name) {
2399 codegen_fn_attrs.link_name = attr.value_str();
2400 } else if attr.check_name(sym::link_ordinal) {
2401 link_ordinal_span = Some(attr.span);
2402 if let ordinal @ Some(_) = check_link_ordinal(tcx, attr) {
2403 codegen_fn_attrs.link_ordinal = ordinal;
2405 } else if attr.check_name(sym::no_sanitize) {
2406 no_sanitize_span = Some(attr.span);
2407 if let Some(list) = attr.meta_item_list() {
2408 for item in list.iter() {
2409 if item.check_name(sym::address) {
2410 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_SANITIZE_ADDRESS;
2411 } else if item.check_name(sym::memory) {
2412 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_SANITIZE_MEMORY;
2413 } else if item.check_name(sym::thread) {
2414 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_SANITIZE_THREAD;
2417 .struct_span_err(item.span(), "invalid argument for `no_sanitize`")
2418 .note("expected one of: `address`, `memory` or `thread`")
2426 codegen_fn_attrs.inline = attrs.iter().fold(InlineAttr::None, |ia, attr| {
2427 if !attr.has_name(sym::inline) {
2430 match attr.meta().map(|i| i.kind) {
2431 Some(MetaItemKind::Word) => {
2435 Some(MetaItemKind::List(ref items)) => {
2437 inline_span = Some(attr.span);
2438 if items.len() != 1 {
2440 tcx.sess.diagnostic(),
2443 "expected one argument"
2447 } else if list_contains_name(&items[..], sym::always) {
2449 } else if list_contains_name(&items[..], sym::never) {
2453 tcx.sess.diagnostic(),
2463 Some(MetaItemKind::NameValue(_)) => ia,
2468 codegen_fn_attrs.optimize = attrs.iter().fold(OptimizeAttr::None, |ia, attr| {
2469 if !attr.has_name(sym::optimize) {
2472 let err = |sp, s| struct_span_err!(tcx.sess.diagnostic(), sp, E0722, "{}", s).emit();
2473 match attr.meta().map(|i| i.kind) {
2474 Some(MetaItemKind::Word) => {
2475 err(attr.span, "expected one argument");
2478 Some(MetaItemKind::List(ref items)) => {
2480 inline_span = Some(attr.span);
2481 if items.len() != 1 {
2482 err(attr.span, "expected one argument");
2484 } else if list_contains_name(&items[..], sym::size) {
2486 } else if list_contains_name(&items[..], sym::speed) {
2489 err(items[0].span(), "invalid argument");
2493 Some(MetaItemKind::NameValue(_)) => ia,
2498 // If a function uses #[target_feature] it can't be inlined into general
2499 // purpose functions as they wouldn't have the right target features
2500 // enabled. For that reason we also forbid #[inline(always)] as it can't be
2502 if codegen_fn_attrs.target_features.len() > 0 {
2503 if codegen_fn_attrs.inline == InlineAttr::Always {
2504 if let Some(span) = inline_span {
2507 "cannot use `#[inline(always)]` with \
2508 `#[target_feature]`",
2514 if codegen_fn_attrs.flags.intersects(CodegenFnAttrFlags::NO_SANITIZE_ANY) {
2515 if codegen_fn_attrs.inline == InlineAttr::Always {
2516 if let (Some(no_sanitize_span), Some(inline_span)) = (no_sanitize_span, inline_span) {
2517 let hir_id = tcx.hir().as_local_hir_id(id).unwrap();
2518 tcx.struct_span_lint_hir(
2519 lint::builtin::INLINE_NO_SANITIZE,
2523 lint.build("`no_sanitize` will have no effect after inlining")
2524 .span_note(inline_span, "inlining requested here")
2532 // Weak lang items have the same semantics as "std internal" symbols in the
2533 // sense that they're preserved through all our LTO passes and only
2534 // strippable by the linker.
2536 // Additionally weak lang items have predetermined symbol names.
2537 if tcx.is_weak_lang_item(id) {
2538 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2540 if let Some(name) = lang_items::link_name(&attrs) {
2541 codegen_fn_attrs.export_name = Some(name);
2542 codegen_fn_attrs.link_name = Some(name);
2544 check_link_name_xor_ordinal(tcx, &codegen_fn_attrs, link_ordinal_span);
2546 // Internal symbols to the standard library all have no_mangle semantics in
2547 // that they have defined symbol names present in the function name. This
2548 // also applies to weak symbols where they all have known symbol names.
2549 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
2550 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2556 fn check_link_ordinal(tcx: TyCtxt<'_>, attr: &ast::Attribute) -> Option<usize> {
2557 use syntax::ast::{Lit, LitIntType, LitKind};
2558 let meta_item_list = attr.meta_item_list();
2559 let meta_item_list: Option<&[ast::NestedMetaItem]> = meta_item_list.as_ref().map(Vec::as_ref);
2560 let sole_meta_list = match meta_item_list {
2561 Some([item]) => item.literal(),
2564 if let Some(Lit { kind: LitKind::Int(ordinal, LitIntType::Unsuffixed), .. }) = sole_meta_list {
2565 if *ordinal <= std::usize::MAX as u128 {
2566 Some(*ordinal as usize)
2568 let msg = format!("ordinal value in `link_ordinal` is too large: `{}`", &ordinal);
2570 .struct_span_err(attr.span, &msg)
2571 .note("the value may not exceed `std::usize::MAX`")
2577 .struct_span_err(attr.span, "illegal ordinal format in `link_ordinal`")
2578 .note("an unsuffixed integer value, e.g., `1`, is expected")
2584 fn check_link_name_xor_ordinal(
2586 codegen_fn_attrs: &CodegenFnAttrs,
2587 inline_span: Option<Span>,
2589 if codegen_fn_attrs.link_name.is_none() || codegen_fn_attrs.link_ordinal.is_none() {
2592 let msg = "cannot use `#[link_name]` with `#[link_ordinal]`";
2593 if let Some(span) = inline_span {
2594 tcx.sess.span_err(span, msg);