]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/collect.rs
Auto merge of #81461 - JohnTitor:rollup-b0ij25f, r=JohnTitor
[rust.git] / compiler / rustc_typeck / src / collect.rs
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
7 //! type *checking*).
8 //!
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
12 //! for the full set.
13 //!
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.
16
17 use crate::astconv::{AstConv, SizedByDefault};
18 use crate::bounds::Bounds;
19 use crate::check::intrinsic::intrinsic_operation_unsafety;
20 use crate::constrained_generic_params as cgp;
21 use crate::errors;
22 use crate::middle::resolve_lifetime as rl;
23 use rustc_ast as ast;
24 use rustc_ast::{MetaItemKind, NestedMetaItem};
25 use rustc_attr::{list_contains_name, InlineAttr, InstructionSetAttr, OptimizeAttr};
26 use rustc_data_structures::captures::Captures;
27 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
28 use rustc_errors::{struct_span_err, Applicability};
29 use rustc_hir as hir;
30 use rustc_hir::def::{CtorKind, DefKind, Res};
31 use rustc_hir::def_id::{DefId, LocalDefId, LOCAL_CRATE};
32 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
33 use rustc_hir::weak_lang_items;
34 use rustc_hir::{GenericParamKind, HirId, Node};
35 use rustc_middle::hir::map::blocks::FnLikeNode;
36 use rustc_middle::hir::map::Map;
37 use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
38 use rustc_middle::mir::mono::Linkage;
39 use rustc_middle::ty::query::Providers;
40 use rustc_middle::ty::subst::InternalSubsts;
41 use rustc_middle::ty::util::Discr;
42 use rustc_middle::ty::util::IntTypeExt;
43 use rustc_middle::ty::{self, AdtKind, Const, DefIdTree, ToPolyTraitRef, Ty, TyCtxt};
44 use rustc_middle::ty::{ReprOptions, ToPredicate, WithConstness};
45 use rustc_session::config::SanitizerSet;
46 use rustc_session::lint;
47 use rustc_session::parse::feature_err;
48 use rustc_span::symbol::{kw, sym, Ident, Symbol};
49 use rustc_span::{Span, DUMMY_SP};
50 use rustc_target::spec::abi;
51 use rustc_trait_selection::traits::error_reporting::suggestions::NextTypeParamName;
52
53 mod item_bounds;
54 mod type_of;
55
56 struct OnlySelfBounds(bool);
57
58 ///////////////////////////////////////////////////////////////////////////
59 // Main entry point
60
61 fn collect_mod_item_types(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
62     tcx.hir().visit_item_likes_in_module(
63         module_def_id,
64         &mut CollectItemTypesVisitor { tcx }.as_deep_visitor(),
65     );
66 }
67
68 pub fn provide(providers: &mut Providers) {
69     *providers = Providers {
70         opt_const_param_of: type_of::opt_const_param_of,
71         type_of: type_of::type_of,
72         item_bounds: item_bounds::item_bounds,
73         explicit_item_bounds: item_bounds::explicit_item_bounds,
74         generics_of,
75         predicates_of,
76         predicates_defined_on,
77         projection_ty_from_predicates,
78         explicit_predicates_of,
79         super_predicates_of,
80         trait_explicit_predicates_and_bounds,
81         type_param_predicates,
82         trait_def,
83         adt_def,
84         fn_sig,
85         impl_trait_ref,
86         impl_polarity,
87         is_foreign_item,
88         static_mutability,
89         generator_kind,
90         codegen_fn_attrs,
91         collect_mod_item_types,
92         ..*providers
93     };
94 }
95
96 ///////////////////////////////////////////////////////////////////////////
97
98 /// Context specific to some particular item. This is what implements
99 /// `AstConv`. It has information about the predicates that are defined
100 /// on the trait. Unfortunately, this predicate information is
101 /// available in various different forms at various points in the
102 /// process. So we can't just store a pointer to e.g., the AST or the
103 /// parsed ty form, we have to be more flexible. To this end, the
104 /// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy
105 /// `get_type_parameter_bounds` requests, drawing the information from
106 /// the AST (`hir::Generics`), recursively.
107 pub struct ItemCtxt<'tcx> {
108     tcx: TyCtxt<'tcx>,
109     item_def_id: DefId,
110 }
111
112 ///////////////////////////////////////////////////////////////////////////
113
114 #[derive(Default)]
115 crate struct PlaceholderHirTyCollector(crate Vec<Span>);
116
117 impl<'v> Visitor<'v> for PlaceholderHirTyCollector {
118     type Map = intravisit::ErasedMap<'v>;
119
120     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
121         NestedVisitorMap::None
122     }
123     fn visit_ty(&mut self, t: &'v hir::Ty<'v>) {
124         if let hir::TyKind::Infer = t.kind {
125             self.0.push(t.span);
126         }
127         intravisit::walk_ty(self, t)
128     }
129 }
130
131 struct CollectItemTypesVisitor<'tcx> {
132     tcx: TyCtxt<'tcx>,
133 }
134
135 /// If there are any placeholder types (`_`), emit an error explaining that this is not allowed
136 /// and suggest adding type parameters in the appropriate place, taking into consideration any and
137 /// all already existing generic type parameters to avoid suggesting a name that is already in use.
138 crate fn placeholder_type_error(
139     tcx: TyCtxt<'tcx>,
140     span: Option<Span>,
141     generics: &[hir::GenericParam<'_>],
142     placeholder_types: Vec<Span>,
143     suggest: bool,
144 ) {
145     if placeholder_types.is_empty() {
146         return;
147     }
148
149     let type_name = generics.next_type_param_name(None);
150     let mut sugg: Vec<_> =
151         placeholder_types.iter().map(|sp| (*sp, (*type_name).to_string())).collect();
152
153     if generics.is_empty() {
154         if let Some(span) = span {
155             sugg.push((span, format!("<{}>", type_name)));
156         }
157     } else if let Some(arg) = generics
158         .iter()
159         .find(|arg| matches!(arg.name, hir::ParamName::Plain(Ident { name: kw::Underscore, .. })))
160     {
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()));
164     } else {
165         let last = generics.iter().last().unwrap();
166         sugg.push((
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),
170         ));
171     }
172
173     let mut err = bad_placeholder_type(tcx, placeholder_types);
174     if suggest {
175         err.multipart_suggestion(
176             "use type parameters instead",
177             sugg,
178             Applicability::HasPlaceholders,
179         );
180     }
181     err.emit();
182 }
183
184 fn reject_placeholder_type_signatures_in_item(tcx: TyCtxt<'tcx>, item: &'tcx hir::Item<'tcx>) {
185     let (generics, suggest) = match &item.kind {
186         hir::ItemKind::Union(_, generics)
187         | hir::ItemKind::Enum(_, generics)
188         | hir::ItemKind::TraitAlias(generics, _)
189         | hir::ItemKind::Trait(_, _, generics, ..)
190         | hir::ItemKind::Impl(hir::Impl { generics, .. })
191         | hir::ItemKind::Struct(_, generics) => (generics, true),
192         hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. })
193         | hir::ItemKind::TyAlias(_, generics) => (generics, false),
194         // `static`, `fn` and `const` are handled elsewhere to suggest appropriate type.
195         _ => return,
196     };
197
198     let mut visitor = PlaceholderHirTyCollector::default();
199     visitor.visit_item(item);
200
201     placeholder_type_error(tcx, Some(generics.span), &generics.params[..], visitor.0, suggest);
202 }
203
204 impl Visitor<'tcx> for CollectItemTypesVisitor<'tcx> {
205     type Map = Map<'tcx>;
206
207     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
208         NestedVisitorMap::OnlyBodies(self.tcx.hir())
209     }
210
211     fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
212         convert_item(self.tcx, item.hir_id);
213         reject_placeholder_type_signatures_in_item(self.tcx, item);
214         intravisit::walk_item(self, item);
215     }
216
217     fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
218         for param in generics.params {
219             match param.kind {
220                 hir::GenericParamKind::Lifetime { .. } => {}
221                 hir::GenericParamKind::Type { default: Some(_), .. } => {
222                     let def_id = self.tcx.hir().local_def_id(param.hir_id);
223                     self.tcx.ensure().type_of(def_id);
224                 }
225                 hir::GenericParamKind::Type { .. } => {}
226                 hir::GenericParamKind::Const { .. } => {
227                     let def_id = self.tcx.hir().local_def_id(param.hir_id);
228                     self.tcx.ensure().type_of(def_id);
229                     // FIXME(const_generics_defaults)
230                 }
231             }
232         }
233         intravisit::walk_generics(self, generics);
234     }
235
236     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
237         if let hir::ExprKind::Closure(..) = expr.kind {
238             let def_id = self.tcx.hir().local_def_id(expr.hir_id);
239             self.tcx.ensure().generics_of(def_id);
240             self.tcx.ensure().type_of(def_id);
241         }
242         intravisit::walk_expr(self, expr);
243     }
244
245     fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
246         convert_trait_item(self.tcx, trait_item.hir_id);
247         intravisit::walk_trait_item(self, trait_item);
248     }
249
250     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
251         convert_impl_item(self.tcx, impl_item.hir_id);
252         intravisit::walk_impl_item(self, impl_item);
253     }
254 }
255
256 ///////////////////////////////////////////////////////////////////////////
257 // Utility types and common code for the above passes.
258
259 fn bad_placeholder_type(
260     tcx: TyCtxt<'tcx>,
261     mut spans: Vec<Span>,
262 ) -> rustc_errors::DiagnosticBuilder<'tcx> {
263     spans.sort();
264     let mut err = struct_span_err!(
265         tcx.sess,
266         spans.clone(),
267         E0121,
268         "the type placeholder `_` is not allowed within types on item signatures",
269     );
270     for span in spans {
271         err.span_label(span, "not allowed in type signatures");
272     }
273     err
274 }
275
276 impl ItemCtxt<'tcx> {
277     pub fn new(tcx: TyCtxt<'tcx>, item_def_id: DefId) -> ItemCtxt<'tcx> {
278         ItemCtxt { tcx, item_def_id }
279     }
280
281     pub fn to_ty(&self, ast_ty: &'tcx hir::Ty<'tcx>) -> Ty<'tcx> {
282         AstConv::ast_ty_to_ty(self, ast_ty)
283     }
284
285     pub fn hir_id(&self) -> hir::HirId {
286         self.tcx.hir().local_def_id_to_hir_id(self.item_def_id.expect_local())
287     }
288
289     pub fn node(&self) -> hir::Node<'tcx> {
290         self.tcx.hir().get(self.hir_id())
291     }
292 }
293
294 impl AstConv<'tcx> for ItemCtxt<'tcx> {
295     fn tcx(&self) -> TyCtxt<'tcx> {
296         self.tcx
297     }
298
299     fn item_def_id(&self) -> Option<DefId> {
300         Some(self.item_def_id)
301     }
302
303     fn default_constness_for_trait_bounds(&self) -> hir::Constness {
304         if let Some(fn_like) = FnLikeNode::from_node(self.node()) {
305             fn_like.constness()
306         } else {
307             hir::Constness::NotConst
308         }
309     }
310
311     fn get_type_parameter_bounds(&self, span: Span, def_id: DefId) -> ty::GenericPredicates<'tcx> {
312         self.tcx.at(span).type_param_predicates((self.item_def_id, def_id.expect_local()))
313     }
314
315     fn re_infer(&self, _: Option<&ty::GenericParamDef>, _: Span) -> Option<ty::Region<'tcx>> {
316         None
317     }
318
319     fn allow_ty_infer(&self) -> bool {
320         false
321     }
322
323     fn ty_infer(&self, _: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx> {
324         self.tcx().ty_error_with_message(span, "bad_placeholder_type")
325     }
326
327     fn ct_infer(
328         &self,
329         ty: Ty<'tcx>,
330         _: Option<&ty::GenericParamDef>,
331         span: Span,
332     ) -> &'tcx Const<'tcx> {
333         bad_placeholder_type(self.tcx(), vec![span]).emit();
334         self.tcx().const_error(ty)
335     }
336
337     fn projected_ty_from_poly_trait_ref(
338         &self,
339         span: Span,
340         item_def_id: DefId,
341         item_segment: &hir::PathSegment<'_>,
342         poly_trait_ref: ty::PolyTraitRef<'tcx>,
343     ) -> Ty<'tcx> {
344         if let Some(trait_ref) = poly_trait_ref.no_bound_vars() {
345             let item_substs = <dyn AstConv<'tcx>>::create_substs_for_associated_item(
346                 self,
347                 self.tcx,
348                 span,
349                 item_def_id,
350                 item_segment,
351                 trait_ref.substs,
352             );
353             self.tcx().mk_projection(item_def_id, item_substs)
354         } else {
355             // There are no late-bound regions; we can just ignore the binder.
356             let mut err = struct_span_err!(
357                 self.tcx().sess,
358                 span,
359                 E0212,
360                 "cannot use the associated type of a trait \
361                  with uninferred generic parameters"
362             );
363
364             match self.node() {
365                 hir::Node::Field(_) | hir::Node::Ctor(_) | hir::Node::Variant(_) => {
366                     let item =
367                         self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(self.hir_id()));
368                     match &item.kind {
369                         hir::ItemKind::Enum(_, generics)
370                         | hir::ItemKind::Struct(_, generics)
371                         | hir::ItemKind::Union(_, generics) => {
372                             let lt_name = get_new_lifetime_name(self.tcx, poly_trait_ref, generics);
373                             let (lt_sp, sugg) = match &generics.params[..] {
374                                 [] => (generics.span, format!("<{}>", lt_name)),
375                                 [bound, ..] => {
376                                     (bound.span.shrink_to_lo(), format!("{}, ", lt_name))
377                                 }
378                             };
379                             let suggestions = vec![
380                                 (lt_sp, sugg),
381                                 (
382                                     span,
383                                     format!(
384                                         "{}::{}",
385                                         // Replace the existing lifetimes with a new named lifetime.
386                                         self.tcx
387                                             .replace_late_bound_regions(poly_trait_ref, |_| {
388                                                 self.tcx.mk_region(ty::ReEarlyBound(
389                                                     ty::EarlyBoundRegion {
390                                                         def_id: item_def_id,
391                                                         index: 0,
392                                                         name: Symbol::intern(&lt_name),
393                                                     },
394                                                 ))
395                                             })
396                                             .0,
397                                         item_segment.ident
398                                     ),
399                                 ),
400                             ];
401                             err.multipart_suggestion(
402                                 "use a fully qualified path with explicit lifetimes",
403                                 suggestions,
404                                 Applicability::MaybeIncorrect,
405                             );
406                         }
407                         _ => {}
408                     }
409                 }
410                 hir::Node::Item(hir::Item {
411                     kind:
412                         hir::ItemKind::Struct(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Union(..),
413                     ..
414                 }) => {}
415                 hir::Node::Item(_)
416                 | hir::Node::ForeignItem(_)
417                 | hir::Node::TraitItem(_)
418                 | hir::Node::ImplItem(_) => {
419                     err.span_suggestion(
420                         span,
421                         "use a fully qualified path with inferred lifetimes",
422                         format!(
423                             "{}::{}",
424                             // Erase named lt, we want `<A as B<'_>::C`, not `<A as B<'a>::C`.
425                             self.tcx.anonymize_late_bound_regions(poly_trait_ref).skip_binder(),
426                             item_segment.ident
427                         ),
428                         Applicability::MaybeIncorrect,
429                     );
430                 }
431                 _ => {}
432             }
433             err.emit();
434             self.tcx().ty_error()
435         }
436     }
437
438     fn normalize_ty(&self, _span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
439         // Types in item signatures are not normalized to avoid undue dependencies.
440         ty
441     }
442
443     fn set_tainted_by_errors(&self) {
444         // There's no obvious place to track this, so just let it go.
445     }
446
447     fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) {
448         // There's no place to record types from signatures?
449     }
450 }
451
452 /// Synthesize a new lifetime name that doesn't clash with any of the lifetimes already present.
453 fn get_new_lifetime_name<'tcx>(
454     tcx: TyCtxt<'tcx>,
455     poly_trait_ref: ty::PolyTraitRef<'tcx>,
456     generics: &hir::Generics<'tcx>,
457 ) -> String {
458     let existing_lifetimes = tcx
459         .collect_referenced_late_bound_regions(&poly_trait_ref)
460         .into_iter()
461         .filter_map(|lt| {
462             if let ty::BoundRegionKind::BrNamed(_, name) = lt {
463                 Some(name.as_str().to_string())
464             } else {
465                 None
466             }
467         })
468         .chain(generics.params.iter().filter_map(|param| {
469             if let hir::GenericParamKind::Lifetime { .. } = &param.kind {
470                 Some(param.name.ident().as_str().to_string())
471             } else {
472                 None
473             }
474         }))
475         .collect::<FxHashSet<String>>();
476
477     let a_to_z_repeat_n = |n| {
478         (b'a'..=b'z').map(move |c| {
479             let mut s = '\''.to_string();
480             s.extend(std::iter::repeat(char::from(c)).take(n));
481             s
482         })
483     };
484
485     // If all single char lifetime names are present, we wrap around and double the chars.
486     (1..).flat_map(a_to_z_repeat_n).find(|lt| !existing_lifetimes.contains(lt.as_str())).unwrap()
487 }
488
489 /// Returns the predicates defined on `item_def_id` of the form
490 /// `X: Foo` where `X` is the type parameter `def_id`.
491 fn type_param_predicates(
492     tcx: TyCtxt<'_>,
493     (item_def_id, def_id): (DefId, LocalDefId),
494 ) -> ty::GenericPredicates<'_> {
495     use rustc_hir::*;
496
497     // In the AST, bounds can derive from two places. Either
498     // written inline like `<T: Foo>` or in a where-clause like
499     // `where T: Foo`.
500
501     let param_id = tcx.hir().local_def_id_to_hir_id(def_id);
502     let param_owner = tcx.hir().ty_param_owner(param_id);
503     let param_owner_def_id = tcx.hir().local_def_id(param_owner);
504     let generics = tcx.generics_of(param_owner_def_id);
505     let index = generics.param_def_id_to_index[&def_id.to_def_id()];
506     let ty = tcx.mk_ty_param(index, tcx.hir().ty_param_name(param_id));
507
508     // Don't look for bounds where the type parameter isn't in scope.
509     let parent = if item_def_id == param_owner_def_id.to_def_id() {
510         None
511     } else {
512         tcx.generics_of(item_def_id).parent
513     };
514
515     let mut result = parent
516         .map(|parent| {
517             let icx = ItemCtxt::new(tcx, parent);
518             icx.get_type_parameter_bounds(DUMMY_SP, def_id.to_def_id())
519         })
520         .unwrap_or_default();
521     let mut extend = None;
522
523     let item_hir_id = tcx.hir().local_def_id_to_hir_id(item_def_id.expect_local());
524     let ast_generics = match tcx.hir().get(item_hir_id) {
525         Node::TraitItem(item) => &item.generics,
526
527         Node::ImplItem(item) => &item.generics,
528
529         Node::Item(item) => {
530             match item.kind {
531                 ItemKind::Fn(.., ref generics, _)
532                 | ItemKind::Impl(hir::Impl { ref generics, .. })
533                 | ItemKind::TyAlias(_, ref generics)
534                 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
535                 | ItemKind::Enum(_, ref generics)
536                 | ItemKind::Struct(_, ref generics)
537                 | ItemKind::Union(_, ref generics) => generics,
538                 ItemKind::Trait(_, _, ref generics, ..) => {
539                     // Implied `Self: Trait` and supertrait bounds.
540                     if param_id == item_hir_id {
541                         let identity_trait_ref = ty::TraitRef::identity(tcx, item_def_id);
542                         extend =
543                             Some((identity_trait_ref.without_const().to_predicate(tcx), item.span));
544                     }
545                     generics
546                 }
547                 _ => return result,
548             }
549         }
550
551         Node::ForeignItem(item) => match item.kind {
552             ForeignItemKind::Fn(_, _, ref generics) => generics,
553             _ => return result,
554         },
555
556         _ => return result,
557     };
558
559     let icx = ItemCtxt::new(tcx, item_def_id);
560     let extra_predicates = extend.into_iter().chain(
561         icx.type_parameter_bounds_in_generics(ast_generics, param_id, ty, OnlySelfBounds(true))
562             .into_iter()
563             .filter(|(predicate, _)| match predicate.kind().skip_binder() {
564                 ty::PredicateKind::Trait(data, _) => data.self_ty().is_param(index),
565                 _ => false,
566             }),
567     );
568     result.predicates =
569         tcx.arena.alloc_from_iter(result.predicates.iter().copied().chain(extra_predicates));
570     result
571 }
572
573 impl ItemCtxt<'tcx> {
574     /// Finds bounds from `hir::Generics`. This requires scanning through the
575     /// AST. We do this to avoid having to convert *all* the bounds, which
576     /// would create artificial cycles. Instead, we can only convert the
577     /// bounds for a type parameter `X` if `X::Foo` is used.
578     fn type_parameter_bounds_in_generics(
579         &self,
580         ast_generics: &'tcx hir::Generics<'tcx>,
581         param_id: hir::HirId,
582         ty: Ty<'tcx>,
583         only_self_bounds: OnlySelfBounds,
584     ) -> Vec<(ty::Predicate<'tcx>, Span)> {
585         let constness = self.default_constness_for_trait_bounds();
586         let from_ty_params = ast_generics
587             .params
588             .iter()
589             .filter_map(|param| match param.kind {
590                 GenericParamKind::Type { .. } if param.hir_id == param_id => Some(&param.bounds),
591                 _ => None,
592             })
593             .flat_map(|bounds| bounds.iter())
594             .flat_map(|b| predicates_from_bound(self, ty, b, constness));
595
596         let from_where_clauses = ast_generics
597             .where_clause
598             .predicates
599             .iter()
600             .filter_map(|wp| match *wp {
601                 hir::WherePredicate::BoundPredicate(ref bp) => Some(bp),
602                 _ => None,
603             })
604             .flat_map(|bp| {
605                 let bt = if is_param(self.tcx, &bp.bounded_ty, param_id) {
606                     Some(ty)
607                 } else if !only_self_bounds.0 {
608                     Some(self.to_ty(&bp.bounded_ty))
609                 } else {
610                     None
611                 };
612                 bp.bounds.iter().filter_map(move |b| bt.map(|bt| (bt, b)))
613             })
614             .flat_map(|(bt, b)| predicates_from_bound(self, bt, b, constness));
615
616         from_ty_params.chain(from_where_clauses).collect()
617     }
618 }
619
620 /// Tests whether this is the AST for a reference to the type
621 /// parameter with ID `param_id`. We use this so as to avoid running
622 /// `ast_ty_to_ty`, because we want to avoid triggering an all-out
623 /// conversion of the type to avoid inducing unnecessary cycles.
624 fn is_param(tcx: TyCtxt<'_>, ast_ty: &hir::Ty<'_>, param_id: hir::HirId) -> bool {
625     if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = ast_ty.kind {
626         match path.res {
627             Res::SelfTy(Some(def_id), None) | Res::Def(DefKind::TyParam, def_id) => {
628                 def_id == tcx.hir().local_def_id(param_id).to_def_id()
629             }
630             _ => false,
631         }
632     } else {
633         false
634     }
635 }
636
637 fn convert_item(tcx: TyCtxt<'_>, item_id: hir::HirId) {
638     let it = tcx.hir().expect_item(item_id);
639     debug!("convert: item {} with id {}", it.ident, it.hir_id);
640     let def_id = tcx.hir().local_def_id(item_id);
641     match it.kind {
642         // These don't define types.
643         hir::ItemKind::ExternCrate(_)
644         | hir::ItemKind::Use(..)
645         | hir::ItemKind::Mod(_)
646         | hir::ItemKind::GlobalAsm(_) => {}
647         hir::ItemKind::ForeignMod { items, .. } => {
648             for item in items {
649                 let item = tcx.hir().foreign_item(item.id);
650                 let def_id = tcx.hir().local_def_id(item.hir_id);
651                 tcx.ensure().generics_of(def_id);
652                 tcx.ensure().type_of(def_id);
653                 tcx.ensure().predicates_of(def_id);
654                 if let hir::ForeignItemKind::Fn(..) = item.kind {
655                     tcx.ensure().fn_sig(def_id);
656                 }
657             }
658         }
659         hir::ItemKind::Enum(ref enum_definition, _) => {
660             tcx.ensure().generics_of(def_id);
661             tcx.ensure().type_of(def_id);
662             tcx.ensure().predicates_of(def_id);
663             convert_enum_variant_types(tcx, def_id.to_def_id(), &enum_definition.variants);
664         }
665         hir::ItemKind::Impl { .. } => {
666             tcx.ensure().generics_of(def_id);
667             tcx.ensure().type_of(def_id);
668             tcx.ensure().impl_trait_ref(def_id);
669             tcx.ensure().predicates_of(def_id);
670         }
671         hir::ItemKind::Trait(..) => {
672             tcx.ensure().generics_of(def_id);
673             tcx.ensure().trait_def(def_id);
674             tcx.at(it.span).super_predicates_of(def_id);
675             tcx.ensure().predicates_of(def_id);
676         }
677         hir::ItemKind::TraitAlias(..) => {
678             tcx.ensure().generics_of(def_id);
679             tcx.at(it.span).super_predicates_of(def_id);
680             tcx.ensure().predicates_of(def_id);
681         }
682         hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
683             tcx.ensure().generics_of(def_id);
684             tcx.ensure().type_of(def_id);
685             tcx.ensure().predicates_of(def_id);
686
687             for f in struct_def.fields() {
688                 let def_id = tcx.hir().local_def_id(f.hir_id);
689                 tcx.ensure().generics_of(def_id);
690                 tcx.ensure().type_of(def_id);
691                 tcx.ensure().predicates_of(def_id);
692             }
693
694             if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
695                 convert_variant_ctor(tcx, ctor_hir_id);
696             }
697         }
698
699         // Desugared from `impl Trait`, so visited by the function's return type.
700         hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: Some(_), .. }) => {}
701
702         // Don't call `type_of` on opaque types, since that depends on type
703         // checking function bodies. `check_item_type` ensures that it's called
704         // instead.
705         hir::ItemKind::OpaqueTy(..) => {
706             tcx.ensure().generics_of(def_id);
707             tcx.ensure().predicates_of(def_id);
708             tcx.ensure().explicit_item_bounds(def_id);
709         }
710         hir::ItemKind::TyAlias(..)
711         | hir::ItemKind::Static(..)
712         | hir::ItemKind::Const(..)
713         | hir::ItemKind::Fn(..) => {
714             tcx.ensure().generics_of(def_id);
715             tcx.ensure().type_of(def_id);
716             tcx.ensure().predicates_of(def_id);
717             match it.kind {
718                 hir::ItemKind::Fn(..) => tcx.ensure().fn_sig(def_id),
719                 hir::ItemKind::OpaqueTy(..) => tcx.ensure().item_bounds(def_id),
720                 _ => (),
721             }
722         }
723     }
724 }
725
726 fn convert_trait_item(tcx: TyCtxt<'_>, trait_item_id: hir::HirId) {
727     let trait_item = tcx.hir().expect_trait_item(trait_item_id);
728     let def_id = tcx.hir().local_def_id(trait_item.hir_id);
729     tcx.ensure().generics_of(def_id);
730
731     match trait_item.kind {
732         hir::TraitItemKind::Fn(..) => {
733             tcx.ensure().type_of(def_id);
734             tcx.ensure().fn_sig(def_id);
735         }
736
737         hir::TraitItemKind::Const(.., Some(_)) => {
738             tcx.ensure().type_of(def_id);
739         }
740
741         hir::TraitItemKind::Const(..) => {
742             tcx.ensure().type_of(def_id);
743             // Account for `const C: _;`.
744             let mut visitor = PlaceholderHirTyCollector::default();
745             visitor.visit_trait_item(trait_item);
746             placeholder_type_error(tcx, None, &[], visitor.0, false);
747         }
748
749         hir::TraitItemKind::Type(_, Some(_)) => {
750             tcx.ensure().item_bounds(def_id);
751             tcx.ensure().type_of(def_id);
752             // Account for `type T = _;`.
753             let mut visitor = PlaceholderHirTyCollector::default();
754             visitor.visit_trait_item(trait_item);
755             placeholder_type_error(tcx, None, &[], visitor.0, false);
756         }
757
758         hir::TraitItemKind::Type(_, None) => {
759             tcx.ensure().item_bounds(def_id);
760             // #74612: Visit and try to find bad placeholders
761             // even if there is no concrete type.
762             let mut visitor = PlaceholderHirTyCollector::default();
763             visitor.visit_trait_item(trait_item);
764             placeholder_type_error(tcx, None, &[], visitor.0, false);
765         }
766     };
767
768     tcx.ensure().predicates_of(def_id);
769 }
770
771 fn convert_impl_item(tcx: TyCtxt<'_>, impl_item_id: hir::HirId) {
772     let def_id = tcx.hir().local_def_id(impl_item_id);
773     tcx.ensure().generics_of(def_id);
774     tcx.ensure().type_of(def_id);
775     tcx.ensure().predicates_of(def_id);
776     let impl_item = tcx.hir().expect_impl_item(impl_item_id);
777     match impl_item.kind {
778         hir::ImplItemKind::Fn(..) => {
779             tcx.ensure().fn_sig(def_id);
780         }
781         hir::ImplItemKind::TyAlias(_) => {
782             // Account for `type T = _;`
783             let mut visitor = PlaceholderHirTyCollector::default();
784             visitor.visit_impl_item(impl_item);
785             placeholder_type_error(tcx, None, &[], visitor.0, false);
786         }
787         hir::ImplItemKind::Const(..) => {}
788     }
789 }
790
791 fn convert_variant_ctor(tcx: TyCtxt<'_>, ctor_id: hir::HirId) {
792     let def_id = tcx.hir().local_def_id(ctor_id);
793     tcx.ensure().generics_of(def_id);
794     tcx.ensure().type_of(def_id);
795     tcx.ensure().predicates_of(def_id);
796 }
797
798 fn convert_enum_variant_types(tcx: TyCtxt<'_>, def_id: DefId, variants: &[hir::Variant<'_>]) {
799     let def = tcx.adt_def(def_id);
800     let repr_type = def.repr.discr_type();
801     let initial = repr_type.initial_discriminant(tcx);
802     let mut prev_discr = None::<Discr<'_>>;
803
804     // fill the discriminant values and field types
805     for variant in variants {
806         let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
807         prev_discr = Some(
808             if let Some(ref e) = variant.disr_expr {
809                 let expr_did = tcx.hir().local_def_id(e.hir_id);
810                 def.eval_explicit_discr(tcx, expr_did.to_def_id())
811             } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) {
812                 Some(discr)
813             } else {
814                 struct_span_err!(tcx.sess, variant.span, E0370, "enum discriminant overflowed")
815                     .span_label(
816                         variant.span,
817                         format!("overflowed on value after {}", prev_discr.unwrap()),
818                     )
819                     .note(&format!(
820                         "explicitly set `{} = {}` if that is desired outcome",
821                         variant.ident, wrapped_discr
822                     ))
823                     .emit();
824                 None
825             }
826             .unwrap_or(wrapped_discr),
827         );
828
829         for f in variant.data.fields() {
830             let def_id = tcx.hir().local_def_id(f.hir_id);
831             tcx.ensure().generics_of(def_id);
832             tcx.ensure().type_of(def_id);
833             tcx.ensure().predicates_of(def_id);
834         }
835
836         // Convert the ctor, if any. This also registers the variant as
837         // an item.
838         if let Some(ctor_hir_id) = variant.data.ctor_hir_id() {
839             convert_variant_ctor(tcx, ctor_hir_id);
840         }
841     }
842 }
843
844 fn convert_variant(
845     tcx: TyCtxt<'_>,
846     variant_did: Option<LocalDefId>,
847     ctor_did: Option<LocalDefId>,
848     ident: Ident,
849     discr: ty::VariantDiscr,
850     def: &hir::VariantData<'_>,
851     adt_kind: ty::AdtKind,
852     parent_did: LocalDefId,
853 ) -> ty::VariantDef {
854     let mut seen_fields: FxHashMap<Ident, Span> = Default::default();
855     let fields = def
856         .fields()
857         .iter()
858         .map(|f| {
859             let fid = tcx.hir().local_def_id(f.hir_id);
860             let dup_span = seen_fields.get(&f.ident.normalize_to_macros_2_0()).cloned();
861             if let Some(prev_span) = dup_span {
862                 tcx.sess.emit_err(errors::FieldAlreadyDeclared {
863                     field_name: f.ident,
864                     span: f.span,
865                     prev_span,
866                 });
867             } else {
868                 seen_fields.insert(f.ident.normalize_to_macros_2_0(), f.span);
869             }
870
871             ty::FieldDef { did: fid.to_def_id(), ident: f.ident, vis: tcx.visibility(fid) }
872         })
873         .collect();
874     let recovered = match def {
875         hir::VariantData::Struct(_, r) => *r,
876         _ => false,
877     };
878     ty::VariantDef::new(
879         ident,
880         variant_did.map(LocalDefId::to_def_id),
881         ctor_did.map(LocalDefId::to_def_id),
882         discr,
883         fields,
884         CtorKind::from_hir(def),
885         adt_kind,
886         parent_did.to_def_id(),
887         recovered,
888         adt_kind == AdtKind::Struct && tcx.has_attr(parent_did.to_def_id(), sym::non_exhaustive)
889             || variant_did.map_or(false, |variant_did| {
890                 tcx.has_attr(variant_did.to_def_id(), sym::non_exhaustive)
891             }),
892     )
893 }
894
895 fn adt_def(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::AdtDef {
896     use rustc_hir::*;
897
898     let def_id = def_id.expect_local();
899     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
900     let item = match tcx.hir().get(hir_id) {
901         Node::Item(item) => item,
902         _ => bug!(),
903     };
904
905     let repr = ReprOptions::new(tcx, def_id.to_def_id());
906     let (kind, variants) = match item.kind {
907         ItemKind::Enum(ref def, _) => {
908             let mut distance_from_explicit = 0;
909             let variants = def
910                 .variants
911                 .iter()
912                 .map(|v| {
913                     let variant_did = Some(tcx.hir().local_def_id(v.id));
914                     let ctor_did =
915                         v.data.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
916
917                     let discr = if let Some(ref e) = v.disr_expr {
918                         distance_from_explicit = 0;
919                         ty::VariantDiscr::Explicit(tcx.hir().local_def_id(e.hir_id).to_def_id())
920                     } else {
921                         ty::VariantDiscr::Relative(distance_from_explicit)
922                     };
923                     distance_from_explicit += 1;
924
925                     convert_variant(
926                         tcx,
927                         variant_did,
928                         ctor_did,
929                         v.ident,
930                         discr,
931                         &v.data,
932                         AdtKind::Enum,
933                         def_id,
934                     )
935                 })
936                 .collect();
937
938             (AdtKind::Enum, variants)
939         }
940         ItemKind::Struct(ref def, _) => {
941             let variant_did = None::<LocalDefId>;
942             let ctor_did = def.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
943
944             let variants = std::iter::once(convert_variant(
945                 tcx,
946                 variant_did,
947                 ctor_did,
948                 item.ident,
949                 ty::VariantDiscr::Relative(0),
950                 def,
951                 AdtKind::Struct,
952                 def_id,
953             ))
954             .collect();
955
956             (AdtKind::Struct, variants)
957         }
958         ItemKind::Union(ref def, _) => {
959             let variant_did = None;
960             let ctor_did = def.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
961
962             let variants = std::iter::once(convert_variant(
963                 tcx,
964                 variant_did,
965                 ctor_did,
966                 item.ident,
967                 ty::VariantDiscr::Relative(0),
968                 def,
969                 AdtKind::Union,
970                 def_id,
971             ))
972             .collect();
973
974             (AdtKind::Union, variants)
975         }
976         _ => bug!(),
977     };
978     tcx.alloc_adt_def(def_id.to_def_id(), kind, variants, repr)
979 }
980
981 /// Ensures that the super-predicates of the trait with a `DefId`
982 /// of `trait_def_id` are converted and stored. This also ensures that
983 /// the transitive super-predicates are converted.
984 fn super_predicates_of(tcx: TyCtxt<'_>, trait_def_id: DefId) -> ty::GenericPredicates<'_> {
985     debug!("super_predicates(trait_def_id={:?})", trait_def_id);
986     let trait_hir_id = tcx.hir().local_def_id_to_hir_id(trait_def_id.expect_local());
987
988     let item = match tcx.hir().get(trait_hir_id) {
989         Node::Item(item) => item,
990         _ => bug!("trait_node_id {} is not an item", trait_hir_id),
991     };
992
993     let (generics, bounds) = match item.kind {
994         hir::ItemKind::Trait(.., ref generics, ref supertraits, _) => (generics, supertraits),
995         hir::ItemKind::TraitAlias(ref generics, ref supertraits) => (generics, supertraits),
996         _ => span_bug!(item.span, "super_predicates invoked on non-trait"),
997     };
998
999     let icx = ItemCtxt::new(tcx, trait_def_id);
1000
1001     // Convert the bounds that follow the colon, e.g., `Bar + Zed` in `trait Foo: Bar + Zed`.
1002     let self_param_ty = tcx.types.self_param;
1003     let superbounds1 =
1004         AstConv::compute_bounds(&icx, self_param_ty, bounds, SizedByDefault::No, item.span);
1005
1006     let superbounds1 = superbounds1.predicates(tcx, self_param_ty);
1007
1008     // Convert any explicit superbounds in the where-clause,
1009     // e.g., `trait Foo where Self: Bar`.
1010     // In the case of trait aliases, however, we include all bounds in the where-clause,
1011     // so e.g., `trait Foo = where u32: PartialEq<Self>` would include `u32: PartialEq<Self>`
1012     // as one of its "superpredicates".
1013     let is_trait_alias = tcx.is_trait_alias(trait_def_id);
1014     let superbounds2 = icx.type_parameter_bounds_in_generics(
1015         generics,
1016         item.hir_id,
1017         self_param_ty,
1018         OnlySelfBounds(!is_trait_alias),
1019     );
1020
1021     // Combine the two lists to form the complete set of superbounds:
1022     let superbounds = &*tcx.arena.alloc_from_iter(superbounds1.into_iter().chain(superbounds2));
1023
1024     // Now require that immediate supertraits are converted,
1025     // which will, in turn, reach indirect supertraits.
1026     for &(pred, span) in superbounds {
1027         debug!("superbound: {:?}", pred);
1028         if let ty::PredicateKind::Trait(bound, _) = pred.kind().skip_binder() {
1029             tcx.at(span).super_predicates_of(bound.def_id());
1030         }
1031     }
1032
1033     ty::GenericPredicates { parent: None, predicates: superbounds }
1034 }
1035
1036 fn trait_def(tcx: TyCtxt<'_>, def_id: DefId) -> ty::TraitDef {
1037     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1038     let item = tcx.hir().expect_item(hir_id);
1039
1040     let (is_auto, unsafety) = match item.kind {
1041         hir::ItemKind::Trait(is_auto, unsafety, ..) => (is_auto == hir::IsAuto::Yes, unsafety),
1042         hir::ItemKind::TraitAlias(..) => (false, hir::Unsafety::Normal),
1043         _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
1044     };
1045
1046     let paren_sugar = tcx.has_attr(def_id, sym::rustc_paren_sugar);
1047     if paren_sugar && !tcx.features().unboxed_closures {
1048         tcx.sess
1049             .struct_span_err(
1050                 item.span,
1051                 "the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \
1052                  which traits can use parenthetical notation",
1053             )
1054             .help("add `#![feature(unboxed_closures)]` to the crate attributes to use it")
1055             .emit();
1056     }
1057
1058     let is_marker = tcx.has_attr(def_id, sym::marker);
1059     let spec_kind = if tcx.has_attr(def_id, sym::rustc_unsafe_specialization_marker) {
1060         ty::trait_def::TraitSpecializationKind::Marker
1061     } else if tcx.has_attr(def_id, sym::rustc_specialization_trait) {
1062         ty::trait_def::TraitSpecializationKind::AlwaysApplicable
1063     } else {
1064         ty::trait_def::TraitSpecializationKind::None
1065     };
1066     let def_path_hash = tcx.def_path_hash(def_id);
1067     ty::TraitDef::new(def_id, unsafety, paren_sugar, is_auto, is_marker, spec_kind, def_path_hash)
1068 }
1069
1070 fn has_late_bound_regions<'tcx>(tcx: TyCtxt<'tcx>, node: Node<'tcx>) -> Option<Span> {
1071     struct LateBoundRegionsDetector<'tcx> {
1072         tcx: TyCtxt<'tcx>,
1073         outer_index: ty::DebruijnIndex,
1074         has_late_bound_regions: Option<Span>,
1075     }
1076
1077     impl Visitor<'tcx> for LateBoundRegionsDetector<'tcx> {
1078         type Map = intravisit::ErasedMap<'tcx>;
1079
1080         fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1081             NestedVisitorMap::None
1082         }
1083
1084         fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
1085             if self.has_late_bound_regions.is_some() {
1086                 return;
1087             }
1088             match ty.kind {
1089                 hir::TyKind::BareFn(..) => {
1090                     self.outer_index.shift_in(1);
1091                     intravisit::walk_ty(self, ty);
1092                     self.outer_index.shift_out(1);
1093                 }
1094                 _ => intravisit::walk_ty(self, ty),
1095             }
1096         }
1097
1098         fn visit_poly_trait_ref(
1099             &mut self,
1100             tr: &'tcx hir::PolyTraitRef<'tcx>,
1101             m: hir::TraitBoundModifier,
1102         ) {
1103             if self.has_late_bound_regions.is_some() {
1104                 return;
1105             }
1106             self.outer_index.shift_in(1);
1107             intravisit::walk_poly_trait_ref(self, tr, m);
1108             self.outer_index.shift_out(1);
1109         }
1110
1111         fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
1112             if self.has_late_bound_regions.is_some() {
1113                 return;
1114             }
1115
1116             match self.tcx.named_region(lt.hir_id) {
1117                 Some(rl::Region::Static | rl::Region::EarlyBound(..)) => {}
1118                 Some(
1119                     rl::Region::LateBound(debruijn, _, _) | rl::Region::LateBoundAnon(debruijn, _),
1120                 ) if debruijn < self.outer_index => {}
1121                 Some(
1122                     rl::Region::LateBound(..)
1123                     | rl::Region::LateBoundAnon(..)
1124                     | rl::Region::Free(..),
1125                 )
1126                 | None => {
1127                     self.has_late_bound_regions = Some(lt.span);
1128                 }
1129             }
1130         }
1131     }
1132
1133     fn has_late_bound_regions<'tcx>(
1134         tcx: TyCtxt<'tcx>,
1135         generics: &'tcx hir::Generics<'tcx>,
1136         decl: &'tcx hir::FnDecl<'tcx>,
1137     ) -> Option<Span> {
1138         let mut visitor = LateBoundRegionsDetector {
1139             tcx,
1140             outer_index: ty::INNERMOST,
1141             has_late_bound_regions: None,
1142         };
1143         for param in generics.params {
1144             if let GenericParamKind::Lifetime { .. } = param.kind {
1145                 if tcx.is_late_bound(param.hir_id) {
1146                     return Some(param.span);
1147                 }
1148             }
1149         }
1150         visitor.visit_fn_decl(decl);
1151         visitor.has_late_bound_regions
1152     }
1153
1154     match node {
1155         Node::TraitItem(item) => match item.kind {
1156             hir::TraitItemKind::Fn(ref sig, _) => {
1157                 has_late_bound_regions(tcx, &item.generics, &sig.decl)
1158             }
1159             _ => None,
1160         },
1161         Node::ImplItem(item) => match item.kind {
1162             hir::ImplItemKind::Fn(ref sig, _) => {
1163                 has_late_bound_regions(tcx, &item.generics, &sig.decl)
1164             }
1165             _ => None,
1166         },
1167         Node::ForeignItem(item) => match item.kind {
1168             hir::ForeignItemKind::Fn(ref fn_decl, _, ref generics) => {
1169                 has_late_bound_regions(tcx, generics, fn_decl)
1170             }
1171             _ => None,
1172         },
1173         Node::Item(item) => match item.kind {
1174             hir::ItemKind::Fn(ref sig, .., ref generics, _) => {
1175                 has_late_bound_regions(tcx, generics, &sig.decl)
1176             }
1177             _ => None,
1178         },
1179         _ => None,
1180     }
1181 }
1182
1183 struct AnonConstInParamListDetector {
1184     in_param_list: bool,
1185     found_anon_const_in_list: bool,
1186     ct: HirId,
1187 }
1188
1189 impl<'v> Visitor<'v> for AnonConstInParamListDetector {
1190     type Map = intravisit::ErasedMap<'v>;
1191
1192     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1193         NestedVisitorMap::None
1194     }
1195
1196     fn visit_generic_param(&mut self, p: &'v hir::GenericParam<'v>) {
1197         let prev = self.in_param_list;
1198         self.in_param_list = true;
1199         intravisit::walk_generic_param(self, p);
1200         self.in_param_list = prev;
1201     }
1202
1203     fn visit_anon_const(&mut self, c: &'v hir::AnonConst) {
1204         if self.in_param_list && self.ct == c.hir_id {
1205             self.found_anon_const_in_list = true;
1206         } else {
1207             intravisit::walk_anon_const(self, c)
1208         }
1209     }
1210 }
1211
1212 fn generics_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::Generics {
1213     use rustc_hir::*;
1214
1215     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1216
1217     let node = tcx.hir().get(hir_id);
1218     let parent_def_id = match node {
1219         Node::ImplItem(_)
1220         | Node::TraitItem(_)
1221         | Node::Variant(_)
1222         | Node::Ctor(..)
1223         | Node::Field(_) => {
1224             let parent_id = tcx.hir().get_parent_item(hir_id);
1225             Some(tcx.hir().local_def_id(parent_id).to_def_id())
1226         }
1227         // FIXME(#43408) always enable this once `lazy_normalization` is
1228         // stable enough and does not need a feature gate anymore.
1229         Node::AnonConst(_) => {
1230             let parent_id = tcx.hir().get_parent_item(hir_id);
1231             let parent_def_id = tcx.hir().local_def_id(parent_id);
1232
1233             let mut in_param_list = false;
1234             for (_parent, node) in tcx.hir().parent_iter(hir_id) {
1235                 if let Some(generics) = node.generics() {
1236                     let mut visitor = AnonConstInParamListDetector {
1237                         in_param_list: false,
1238                         found_anon_const_in_list: false,
1239                         ct: hir_id,
1240                     };
1241
1242                     visitor.visit_generics(generics);
1243                     in_param_list = visitor.found_anon_const_in_list;
1244                     break;
1245                 }
1246             }
1247
1248             if in_param_list {
1249                 // We do not allow generic parameters in anon consts if we are inside
1250                 // of a param list.
1251                 //
1252                 // This affects both default type bindings, e.g. `struct<T, U = [u8; std::mem::size_of::<T>()]>(T, U)`,
1253                 // and the types of const parameters, e.g. `struct V<const N: usize, const M: [u8; N]>();`.
1254                 None
1255             } else if tcx.lazy_normalization() {
1256                 // HACK(eddyb) this provides the correct generics when
1257                 // `feature(const_generics)` is enabled, so that const expressions
1258                 // used with const generics, e.g. `Foo<{N+1}>`, can work at all.
1259                 //
1260                 // Note that we do not supply the parent generics when using
1261                 // `min_const_generics`.
1262                 Some(parent_def_id.to_def_id())
1263             } else {
1264                 let parent_node = tcx.hir().get(tcx.hir().get_parent_node(hir_id));
1265                 match parent_node {
1266                     // HACK(eddyb) this provides the correct generics for repeat
1267                     // expressions' count (i.e. `N` in `[x; N]`), and explicit
1268                     // `enum` discriminants (i.e. `D` in `enum Foo { Bar = D }`),
1269                     // as they shouldn't be able to cause query cycle errors.
1270                     Node::Expr(&Expr { kind: ExprKind::Repeat(_, ref constant), .. })
1271                     | Node::Variant(Variant { disr_expr: Some(ref constant), .. })
1272                         if constant.hir_id == hir_id =>
1273                     {
1274                         Some(parent_def_id.to_def_id())
1275                     }
1276
1277                     _ => None,
1278                 }
1279             }
1280         }
1281         Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => {
1282             Some(tcx.closure_base_def_id(def_id))
1283         }
1284         Node::Item(item) => match item.kind {
1285             ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn, .. }) => {
1286                 impl_trait_fn.or_else(|| {
1287                     let parent_id = tcx.hir().get_parent_item(hir_id);
1288                     assert!(parent_id != hir_id && parent_id != CRATE_HIR_ID);
1289                     debug!("generics_of: parent of opaque ty {:?} is {:?}", def_id, parent_id);
1290                     // Opaque types are always nested within another item, and
1291                     // inherit the generics of the item.
1292                     Some(tcx.hir().local_def_id(parent_id).to_def_id())
1293                 })
1294             }
1295             _ => None,
1296         },
1297         _ => None,
1298     };
1299
1300     let mut opt_self = None;
1301     let mut allow_defaults = false;
1302
1303     let no_generics = hir::Generics::empty();
1304     let ast_generics = match node {
1305         Node::TraitItem(item) => &item.generics,
1306
1307         Node::ImplItem(item) => &item.generics,
1308
1309         Node::Item(item) => {
1310             match item.kind {
1311                 ItemKind::Fn(.., ref generics, _)
1312                 | ItemKind::Impl(hir::Impl { ref generics, .. }) => generics,
1313
1314                 ItemKind::TyAlias(_, ref generics)
1315                 | ItemKind::Enum(_, ref generics)
1316                 | ItemKind::Struct(_, ref generics)
1317                 | ItemKind::OpaqueTy(hir::OpaqueTy { ref generics, .. })
1318                 | ItemKind::Union(_, ref generics) => {
1319                     allow_defaults = true;
1320                     generics
1321                 }
1322
1323                 ItemKind::Trait(_, _, ref generics, ..)
1324                 | ItemKind::TraitAlias(ref generics, ..) => {
1325                     // Add in the self type parameter.
1326                     //
1327                     // Something of a hack: use the node id for the trait, also as
1328                     // the node id for the Self type parameter.
1329                     let param_id = item.hir_id;
1330
1331                     opt_self = Some(ty::GenericParamDef {
1332                         index: 0,
1333                         name: kw::SelfUpper,
1334                         def_id: tcx.hir().local_def_id(param_id).to_def_id(),
1335                         pure_wrt_drop: false,
1336                         kind: ty::GenericParamDefKind::Type {
1337                             has_default: false,
1338                             object_lifetime_default: rl::Set1::Empty,
1339                             synthetic: None,
1340                         },
1341                     });
1342
1343                     allow_defaults = true;
1344                     generics
1345                 }
1346
1347                 _ => &no_generics,
1348             }
1349         }
1350
1351         Node::ForeignItem(item) => match item.kind {
1352             ForeignItemKind::Static(..) => &no_generics,
1353             ForeignItemKind::Fn(_, _, ref generics) => generics,
1354             ForeignItemKind::Type => &no_generics,
1355         },
1356
1357         _ => &no_generics,
1358     };
1359
1360     let has_self = opt_self.is_some();
1361     let mut parent_has_self = false;
1362     let mut own_start = has_self as u32;
1363     let parent_count = parent_def_id.map_or(0, |def_id| {
1364         let generics = tcx.generics_of(def_id);
1365         assert_eq!(has_self, false);
1366         parent_has_self = generics.has_self;
1367         own_start = generics.count() as u32;
1368         generics.parent_count + generics.params.len()
1369     });
1370
1371     let mut params: Vec<_> = Vec::with_capacity(ast_generics.params.len() + has_self as usize);
1372
1373     if let Some(opt_self) = opt_self {
1374         params.push(opt_self);
1375     }
1376
1377     let early_lifetimes = early_bound_lifetimes_from_generics(tcx, ast_generics);
1378     params.extend(early_lifetimes.enumerate().map(|(i, param)| ty::GenericParamDef {
1379         name: param.name.ident().name,
1380         index: own_start + i as u32,
1381         def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
1382         pure_wrt_drop: param.pure_wrt_drop,
1383         kind: ty::GenericParamDefKind::Lifetime,
1384     }));
1385
1386     let object_lifetime_defaults = tcx.object_lifetime_defaults(hir_id);
1387
1388     // Now create the real type and const parameters.
1389     let type_start = own_start - has_self as u32 + params.len() as u32;
1390     let mut i = 0;
1391
1392     params.extend(ast_generics.params.iter().filter_map(|param| match param.kind {
1393         GenericParamKind::Lifetime { .. } => None,
1394         GenericParamKind::Type { ref default, synthetic, .. } => {
1395             if !allow_defaults && default.is_some() {
1396                 if !tcx.features().default_type_parameter_fallback {
1397                     tcx.struct_span_lint_hir(
1398                         lint::builtin::INVALID_TYPE_PARAM_DEFAULT,
1399                         param.hir_id,
1400                         param.span,
1401                         |lint| {
1402                             lint.build(
1403                                 "defaults for type parameters are only allowed in \
1404                                  `struct`, `enum`, `type`, or `trait` definitions.",
1405                             )
1406                             .emit();
1407                         },
1408                     );
1409                 }
1410             }
1411
1412             let kind = ty::GenericParamDefKind::Type {
1413                 has_default: default.is_some(),
1414                 object_lifetime_default: object_lifetime_defaults
1415                     .as_ref()
1416                     .map_or(rl::Set1::Empty, |o| o[i]),
1417                 synthetic,
1418             };
1419
1420             let param_def = ty::GenericParamDef {
1421                 index: type_start + i as u32,
1422                 name: param.name.ident().name,
1423                 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
1424                 pure_wrt_drop: param.pure_wrt_drop,
1425                 kind,
1426             };
1427             i += 1;
1428             Some(param_def)
1429         }
1430         GenericParamKind::Const { .. } => {
1431             let param_def = ty::GenericParamDef {
1432                 index: type_start + i as u32,
1433                 name: param.name.ident().name,
1434                 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
1435                 pure_wrt_drop: param.pure_wrt_drop,
1436                 kind: ty::GenericParamDefKind::Const,
1437             };
1438             i += 1;
1439             Some(param_def)
1440         }
1441     }));
1442
1443     // provide junk type parameter defs - the only place that
1444     // cares about anything but the length is instantiation,
1445     // and we don't do that for closures.
1446     if let Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(.., gen), .. }) = node {
1447         let dummy_args = if gen.is_some() {
1448             &["<resume_ty>", "<yield_ty>", "<return_ty>", "<witness>", "<upvars>"][..]
1449         } else {
1450             &["<closure_kind>", "<closure_signature>", "<upvars>"][..]
1451         };
1452
1453         params.extend(dummy_args.iter().enumerate().map(|(i, &arg)| ty::GenericParamDef {
1454             index: type_start + i as u32,
1455             name: Symbol::intern(arg),
1456             def_id,
1457             pure_wrt_drop: false,
1458             kind: ty::GenericParamDefKind::Type {
1459                 has_default: false,
1460                 object_lifetime_default: rl::Set1::Empty,
1461                 synthetic: None,
1462             },
1463         }));
1464     }
1465
1466     let param_def_id_to_index = params.iter().map(|param| (param.def_id, param.index)).collect();
1467
1468     ty::Generics {
1469         parent: parent_def_id,
1470         parent_count,
1471         params,
1472         param_def_id_to_index,
1473         has_self: has_self || parent_has_self,
1474         has_late_bound_regions: has_late_bound_regions(tcx, node),
1475     }
1476 }
1477
1478 fn are_suggestable_generic_args(generic_args: &[hir::GenericArg<'_>]) -> bool {
1479     generic_args
1480         .iter()
1481         .filter_map(|arg| match arg {
1482             hir::GenericArg::Type(ty) => Some(ty),
1483             _ => None,
1484         })
1485         .any(is_suggestable_infer_ty)
1486 }
1487
1488 /// Whether `ty` is a type with `_` placeholders that can be inferred. Used in diagnostics only to
1489 /// use inference to provide suggestions for the appropriate type if possible.
1490 fn is_suggestable_infer_ty(ty: &hir::Ty<'_>) -> bool {
1491     use hir::TyKind::*;
1492     match &ty.kind {
1493         Infer => true,
1494         Slice(ty) | Array(ty, _) => is_suggestable_infer_ty(ty),
1495         Tup(tys) => tys.iter().any(is_suggestable_infer_ty),
1496         Ptr(mut_ty) | Rptr(_, mut_ty) => is_suggestable_infer_ty(mut_ty.ty),
1497         OpaqueDef(_, generic_args) => are_suggestable_generic_args(generic_args),
1498         Path(hir::QPath::TypeRelative(ty, segment)) => {
1499             is_suggestable_infer_ty(ty) || are_suggestable_generic_args(segment.args().args)
1500         }
1501         Path(hir::QPath::Resolved(ty_opt, hir::Path { segments, .. })) => {
1502             ty_opt.map_or(false, is_suggestable_infer_ty)
1503                 || segments.iter().any(|segment| are_suggestable_generic_args(segment.args().args))
1504         }
1505         _ => false,
1506     }
1507 }
1508
1509 pub fn get_infer_ret_ty(output: &'hir hir::FnRetTy<'hir>) -> Option<&'hir hir::Ty<'hir>> {
1510     if let hir::FnRetTy::Return(ref ty) = output {
1511         if is_suggestable_infer_ty(ty) {
1512             return Some(&**ty);
1513         }
1514     }
1515     None
1516 }
1517
1518 fn fn_sig(tcx: TyCtxt<'_>, def_id: DefId) -> ty::PolyFnSig<'_> {
1519     use rustc_hir::Node::*;
1520     use rustc_hir::*;
1521
1522     let def_id = def_id.expect_local();
1523     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
1524
1525     let icx = ItemCtxt::new(tcx, def_id.to_def_id());
1526
1527     match tcx.hir().get(hir_id) {
1528         TraitItem(hir::TraitItem {
1529             kind: TraitItemKind::Fn(sig, TraitFn::Provided(_)),
1530             ident,
1531             generics,
1532             ..
1533         })
1534         | ImplItem(hir::ImplItem { kind: ImplItemKind::Fn(sig, _), ident, generics, .. })
1535         | Item(hir::Item { kind: ItemKind::Fn(sig, generics, _), ident, .. }) => {
1536             match get_infer_ret_ty(&sig.decl.output) {
1537                 Some(ty) => {
1538                     let fn_sig = tcx.typeck(def_id).liberated_fn_sigs()[hir_id];
1539                     let mut visitor = PlaceholderHirTyCollector::default();
1540                     visitor.visit_ty(ty);
1541                     let mut diag = bad_placeholder_type(tcx, visitor.0);
1542                     let ret_ty = fn_sig.output();
1543                     if ret_ty != tcx.ty_error() {
1544                         if !ret_ty.is_closure() {
1545                             let ret_ty_str = match ret_ty.kind() {
1546                                 // Suggest a function pointer return type instead of a unique function definition
1547                                 // (e.g. `fn() -> i32` instead of `fn() -> i32 { f }`, the latter of which is invalid
1548                                 // syntax)
1549                                 ty::FnDef(..) => ret_ty.fn_sig(tcx).to_string(),
1550                                 _ => ret_ty.to_string(),
1551                             };
1552                             diag.span_suggestion(
1553                                 ty.span,
1554                                 "replace with the correct return type",
1555                                 ret_ty_str,
1556                                 Applicability::MaybeIncorrect,
1557                             );
1558                         } else {
1559                             // We're dealing with a closure, so we should suggest using `impl Fn` or trait bounds
1560                             // to prevent the user from getting a papercut while trying to use the unique closure
1561                             // syntax (e.g. `[closure@src/lib.rs:2:5: 2:9]`).
1562                             diag.help("consider using an `Fn`, `FnMut`, or `FnOnce` trait bound");
1563                             diag.note("for more information on `Fn` traits and closure types, see https://doc.rust-lang.org/book/ch13-01-closures.html");
1564                         }
1565                     }
1566                     diag.emit();
1567                     ty::Binder::bind(fn_sig)
1568                 }
1569                 None => AstConv::ty_of_fn(
1570                     &icx,
1571                     sig.header.unsafety,
1572                     sig.header.abi,
1573                     &sig.decl,
1574                     &generics,
1575                     Some(ident.span),
1576                 ),
1577             }
1578         }
1579
1580         TraitItem(hir::TraitItem {
1581             kind: TraitItemKind::Fn(FnSig { header, decl, span: _ }, _),
1582             ident,
1583             generics,
1584             ..
1585         }) => {
1586             AstConv::ty_of_fn(&icx, header.unsafety, header.abi, decl, &generics, Some(ident.span))
1587         }
1588
1589         ForeignItem(&hir::ForeignItem {
1590             kind: ForeignItemKind::Fn(ref fn_decl, _, _),
1591             ident,
1592             ..
1593         }) => {
1594             let abi = tcx.hir().get_foreign_abi(hir_id);
1595             compute_sig_of_foreign_fn_decl(tcx, def_id.to_def_id(), fn_decl, abi, ident)
1596         }
1597
1598         Ctor(data) | Variant(hir::Variant { data, .. }) if data.ctor_hir_id().is_some() => {
1599             let ty = tcx.type_of(tcx.hir().get_parent_did(hir_id).to_def_id());
1600             let inputs =
1601                 data.fields().iter().map(|f| tcx.type_of(tcx.hir().local_def_id(f.hir_id)));
1602             ty::Binder::bind(tcx.mk_fn_sig(
1603                 inputs,
1604                 ty,
1605                 false,
1606                 hir::Unsafety::Normal,
1607                 abi::Abi::Rust,
1608             ))
1609         }
1610
1611         Expr(&hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => {
1612             // Closure signatures are not like other function
1613             // signatures and cannot be accessed through `fn_sig`. For
1614             // example, a closure signature excludes the `self`
1615             // argument. In any case they are embedded within the
1616             // closure type as part of the `ClosureSubsts`.
1617             //
1618             // To get the signature of a closure, you should use the
1619             // `sig` method on the `ClosureSubsts`:
1620             //
1621             //    substs.as_closure().sig(def_id, tcx)
1622             bug!(
1623                 "to get the signature of a closure, use `substs.as_closure().sig()` not `fn_sig()`",
1624             );
1625         }
1626
1627         x => {
1628             bug!("unexpected sort of node in fn_sig(): {:?}", x);
1629         }
1630     }
1631 }
1632
1633 fn impl_trait_ref(tcx: TyCtxt<'_>, def_id: DefId) -> Option<ty::TraitRef<'_>> {
1634     let icx = ItemCtxt::new(tcx, def_id);
1635
1636     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1637     match tcx.hir().expect_item(hir_id).kind {
1638         hir::ItemKind::Impl(ref impl_) => impl_.of_trait.as_ref().map(|ast_trait_ref| {
1639             let selfty = tcx.type_of(def_id);
1640             AstConv::instantiate_mono_trait_ref(&icx, ast_trait_ref, selfty)
1641         }),
1642         _ => bug!(),
1643     }
1644 }
1645
1646 fn impl_polarity(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ImplPolarity {
1647     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1648     let is_rustc_reservation = tcx.has_attr(def_id, sym::rustc_reservation_impl);
1649     let item = tcx.hir().expect_item(hir_id);
1650     match &item.kind {
1651         hir::ItemKind::Impl(hir::Impl {
1652             polarity: hir::ImplPolarity::Negative(span),
1653             of_trait,
1654             ..
1655         }) => {
1656             if is_rustc_reservation {
1657                 let span = span.to(of_trait.as_ref().map_or(*span, |t| t.path.span));
1658                 tcx.sess.span_err(span, "reservation impls can't be negative");
1659             }
1660             ty::ImplPolarity::Negative
1661         }
1662         hir::ItemKind::Impl(hir::Impl {
1663             polarity: hir::ImplPolarity::Positive,
1664             of_trait: None,
1665             ..
1666         }) => {
1667             if is_rustc_reservation {
1668                 tcx.sess.span_err(item.span, "reservation impls can't be inherent");
1669             }
1670             ty::ImplPolarity::Positive
1671         }
1672         hir::ItemKind::Impl(hir::Impl {
1673             polarity: hir::ImplPolarity::Positive,
1674             of_trait: Some(_),
1675             ..
1676         }) => {
1677             if is_rustc_reservation {
1678                 ty::ImplPolarity::Reservation
1679             } else {
1680                 ty::ImplPolarity::Positive
1681             }
1682         }
1683         item => bug!("impl_polarity: {:?} not an impl", item),
1684     }
1685 }
1686
1687 /// Returns the early-bound lifetimes declared in this generics
1688 /// listing. For anything other than fns/methods, this is just all
1689 /// the lifetimes that are declared. For fns or methods, we have to
1690 /// screen out those that do not appear in any where-clauses etc using
1691 /// `resolve_lifetime::early_bound_lifetimes`.
1692 fn early_bound_lifetimes_from_generics<'a, 'tcx: 'a>(
1693     tcx: TyCtxt<'tcx>,
1694     generics: &'a hir::Generics<'a>,
1695 ) -> impl Iterator<Item = &'a hir::GenericParam<'a>> + Captures<'tcx> {
1696     generics.params.iter().filter(move |param| match param.kind {
1697         GenericParamKind::Lifetime { .. } => !tcx.is_late_bound(param.hir_id),
1698         _ => false,
1699     })
1700 }
1701
1702 /// Returns a list of type predicates for the definition with ID `def_id`, including inferred
1703 /// lifetime constraints. This includes all predicates returned by `explicit_predicates_of`, plus
1704 /// inferred constraints concerning which regions outlive other regions.
1705 fn predicates_defined_on(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1706     debug!("predicates_defined_on({:?})", def_id);
1707     let mut result = tcx.explicit_predicates_of(def_id);
1708     debug!("predicates_defined_on: explicit_predicates_of({:?}) = {:?}", def_id, result,);
1709     let inferred_outlives = tcx.inferred_outlives_of(def_id);
1710     if !inferred_outlives.is_empty() {
1711         debug!(
1712             "predicates_defined_on: inferred_outlives_of({:?}) = {:?}",
1713             def_id, inferred_outlives,
1714         );
1715         if result.predicates.is_empty() {
1716             result.predicates = inferred_outlives;
1717         } else {
1718             result.predicates = tcx
1719                 .arena
1720                 .alloc_from_iter(result.predicates.iter().chain(inferred_outlives).copied());
1721         }
1722     }
1723
1724     debug!("predicates_defined_on({:?}) = {:?}", def_id, result);
1725     result
1726 }
1727
1728 /// Returns a list of all type predicates (explicit and implicit) for the definition with
1729 /// ID `def_id`. This includes all predicates returned by `predicates_defined_on`, plus
1730 /// `Self: Trait` predicates for traits.
1731 fn predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1732     let mut result = tcx.predicates_defined_on(def_id);
1733
1734     if tcx.is_trait(def_id) {
1735         // For traits, add `Self: Trait` predicate. This is
1736         // not part of the predicates that a user writes, but it
1737         // is something that one must prove in order to invoke a
1738         // method or project an associated type.
1739         //
1740         // In the chalk setup, this predicate is not part of the
1741         // "predicates" for a trait item. But it is useful in
1742         // rustc because if you directly (e.g.) invoke a trait
1743         // method like `Trait::method(...)`, you must naturally
1744         // prove that the trait applies to the types that were
1745         // used, and adding the predicate into this list ensures
1746         // that this is done.
1747         let span = tcx.sess.source_map().guess_head_span(tcx.def_span(def_id));
1748         result.predicates =
1749             tcx.arena.alloc_from_iter(result.predicates.iter().copied().chain(std::iter::once((
1750                 ty::TraitRef::identity(tcx, def_id).without_const().to_predicate(tcx),
1751                 span,
1752             ))));
1753     }
1754     debug!("predicates_of(def_id={:?}) = {:?}", def_id, result);
1755     result
1756 }
1757
1758 /// Returns a list of user-specified type predicates for the definition with ID `def_id`.
1759 /// N.B., this does not include any implied/inferred constraints.
1760 fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1761     use rustc_hir::*;
1762
1763     debug!("explicit_predicates_of(def_id={:?})", def_id);
1764
1765     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1766     let node = tcx.hir().get(hir_id);
1767
1768     let mut is_trait = None;
1769     let mut is_default_impl_trait = None;
1770
1771     let icx = ItemCtxt::new(tcx, def_id);
1772     let constness = icx.default_constness_for_trait_bounds();
1773
1774     const NO_GENERICS: &hir::Generics<'_> = &hir::Generics::empty();
1775
1776     // We use an `IndexSet` to preserves order of insertion.
1777     // Preserving the order of insertion is important here so as not to break UI tests.
1778     let mut predicates: FxIndexSet<(ty::Predicate<'_>, Span)> = FxIndexSet::default();
1779
1780     let ast_generics = match node {
1781         Node::TraitItem(item) => &item.generics,
1782
1783         Node::ImplItem(item) => &item.generics,
1784
1785         Node::Item(item) => {
1786             match item.kind {
1787                 ItemKind::Impl(ref impl_) => {
1788                     if impl_.defaultness.is_default() {
1789                         is_default_impl_trait = tcx.impl_trait_ref(def_id);
1790                     }
1791                     &impl_.generics
1792                 }
1793                 ItemKind::Fn(.., ref generics, _)
1794                 | ItemKind::TyAlias(_, ref generics)
1795                 | ItemKind::Enum(_, ref generics)
1796                 | ItemKind::Struct(_, ref generics)
1797                 | ItemKind::Union(_, ref generics) => generics,
1798
1799                 ItemKind::Trait(_, _, ref generics, ..) => {
1800                     is_trait = Some(ty::TraitRef::identity(tcx, def_id));
1801                     generics
1802                 }
1803                 ItemKind::TraitAlias(ref generics, _) => {
1804                     is_trait = Some(ty::TraitRef::identity(tcx, def_id));
1805                     generics
1806                 }
1807                 ItemKind::OpaqueTy(OpaqueTy {
1808                     bounds: _,
1809                     impl_trait_fn,
1810                     ref generics,
1811                     origin: _,
1812                 }) => {
1813                     if impl_trait_fn.is_some() {
1814                         // return-position impl trait
1815                         //
1816                         // We don't inherit predicates from the parent here:
1817                         // If we have, say `fn f<'a, T: 'a>() -> impl Sized {}`
1818                         // then the return type is `f::<'static, T>::{{opaque}}`.
1819                         //
1820                         // If we inherited the predicates of `f` then we would
1821                         // require that `T: 'static` to show that the return
1822                         // type is well-formed.
1823                         //
1824                         // The only way to have something with this opaque type
1825                         // is from the return type of the containing function,
1826                         // which will ensure that the function's predicates
1827                         // hold.
1828                         return ty::GenericPredicates { parent: None, predicates: &[] };
1829                     } else {
1830                         // type-alias impl trait
1831                         generics
1832                     }
1833                 }
1834
1835                 _ => NO_GENERICS,
1836             }
1837         }
1838
1839         Node::ForeignItem(item) => match item.kind {
1840             ForeignItemKind::Static(..) => NO_GENERICS,
1841             ForeignItemKind::Fn(_, _, ref generics) => generics,
1842             ForeignItemKind::Type => NO_GENERICS,
1843         },
1844
1845         _ => NO_GENERICS,
1846     };
1847
1848     let generics = tcx.generics_of(def_id);
1849     let parent_count = generics.parent_count as u32;
1850     let has_own_self = generics.has_self && parent_count == 0;
1851
1852     // Below we'll consider the bounds on the type parameters (including `Self`)
1853     // and the explicit where-clauses, but to get the full set of predicates
1854     // on a trait we need to add in the supertrait bounds and bounds found on
1855     // associated types.
1856     if let Some(_trait_ref) = is_trait {
1857         predicates.extend(tcx.super_predicates_of(def_id).predicates.iter().cloned());
1858     }
1859
1860     // In default impls, we can assume that the self type implements
1861     // the trait. So in:
1862     //
1863     //     default impl Foo for Bar { .. }
1864     //
1865     // we add a default where clause `Foo: Bar`. We do a similar thing for traits
1866     // (see below). Recall that a default impl is not itself an impl, but rather a
1867     // set of defaults that can be incorporated into another impl.
1868     if let Some(trait_ref) = is_default_impl_trait {
1869         predicates.insert((
1870             trait_ref.to_poly_trait_ref().without_const().to_predicate(tcx),
1871             tcx.def_span(def_id),
1872         ));
1873     }
1874
1875     // Collect the region predicates that were declared inline as
1876     // well. In the case of parameters declared on a fn or method, we
1877     // have to be careful to only iterate over early-bound regions.
1878     let mut index = parent_count + has_own_self as u32;
1879     for param in early_bound_lifetimes_from_generics(tcx, ast_generics) {
1880         let region = tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
1881             def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
1882             index,
1883             name: param.name.ident().name,
1884         }));
1885         index += 1;
1886
1887         match param.kind {
1888             GenericParamKind::Lifetime { .. } => {
1889                 param.bounds.iter().for_each(|bound| match bound {
1890                     hir::GenericBound::Outlives(lt) => {
1891                         let bound = AstConv::ast_region_to_region(&icx, &lt, None);
1892                         let outlives = ty::Binder::bind(ty::OutlivesPredicate(region, bound));
1893                         predicates.insert((outlives.to_predicate(tcx), lt.span));
1894                     }
1895                     _ => bug!(),
1896                 });
1897             }
1898             _ => bug!(),
1899         }
1900     }
1901
1902     // Collect the predicates that were written inline by the user on each
1903     // type parameter (e.g., `<T: Foo>`).
1904     for param in ast_generics.params {
1905         match param.kind {
1906             // We already dealt with early bound lifetimes above.
1907             GenericParamKind::Lifetime { .. } => (),
1908             GenericParamKind::Type { .. } => {
1909                 let name = param.name.ident().name;
1910                 let param_ty = ty::ParamTy::new(index, name).to_ty(tcx);
1911                 index += 1;
1912
1913                 let sized = SizedByDefault::Yes;
1914                 let bounds =
1915                     AstConv::compute_bounds(&icx, param_ty, &param.bounds, sized, param.span);
1916                 predicates.extend(bounds.predicates(tcx, param_ty));
1917             }
1918             GenericParamKind::Const { .. } => {
1919                 // Bounds on const parameters are currently not possible.
1920                 debug_assert!(param.bounds.is_empty());
1921                 index += 1;
1922             }
1923         }
1924     }
1925
1926     // Add in the bounds that appear in the where-clause.
1927     let where_clause = &ast_generics.where_clause;
1928     for predicate in where_clause.predicates {
1929         match predicate {
1930             hir::WherePredicate::BoundPredicate(bound_pred) => {
1931                 let ty = icx.to_ty(&bound_pred.bounded_ty);
1932
1933                 // Keep the type around in a dummy predicate, in case of no bounds.
1934                 // That way, `where Ty:` is not a complete noop (see #53696) and `Ty`
1935                 // is still checked for WF.
1936                 if bound_pred.bounds.is_empty() {
1937                     if let ty::Param(_) = ty.kind() {
1938                         // This is a `where T:`, which can be in the HIR from the
1939                         // transformation that moves `?Sized` to `T`'s declaration.
1940                         // We can skip the predicate because type parameters are
1941                         // trivially WF, but also we *should*, to avoid exposing
1942                         // users who never wrote `where Type:,` themselves, to
1943                         // compiler/tooling bugs from not handling WF predicates.
1944                     } else {
1945                         let span = bound_pred.bounded_ty.span;
1946                         let re_root_empty = tcx.lifetimes.re_root_empty;
1947                         let predicate = ty::Binder::bind(ty::PredicateKind::TypeOutlives(
1948                             ty::OutlivesPredicate(ty, re_root_empty),
1949                         ));
1950                         predicates.insert((predicate.to_predicate(tcx), span));
1951                     }
1952                 }
1953
1954                 for bound in bound_pred.bounds.iter() {
1955                     match bound {
1956                         hir::GenericBound::Trait(poly_trait_ref, modifier) => {
1957                             let constness = match modifier {
1958                                 hir::TraitBoundModifier::MaybeConst => hir::Constness::NotConst,
1959                                 hir::TraitBoundModifier::None => constness,
1960                                 hir::TraitBoundModifier::Maybe => bug!("this wasn't handled"),
1961                             };
1962
1963                             let mut bounds = Bounds::default();
1964                             let _ = AstConv::instantiate_poly_trait_ref(
1965                                 &icx,
1966                                 &poly_trait_ref,
1967                                 constness,
1968                                 ty,
1969                                 &mut bounds,
1970                             );
1971                             predicates.extend(bounds.predicates(tcx, ty));
1972                         }
1973
1974                         &hir::GenericBound::LangItemTrait(lang_item, span, hir_id, args) => {
1975                             let mut bounds = Bounds::default();
1976                             AstConv::instantiate_lang_item_trait_ref(
1977                                 &icx,
1978                                 lang_item,
1979                                 span,
1980                                 hir_id,
1981                                 args,
1982                                 ty,
1983                                 &mut bounds,
1984                             );
1985                             predicates.extend(bounds.predicates(tcx, ty));
1986                         }
1987
1988                         hir::GenericBound::Outlives(lifetime) => {
1989                             let region = AstConv::ast_region_to_region(&icx, lifetime, None);
1990                             predicates.insert((
1991                                 ty::Binder::bind(ty::PredicateKind::TypeOutlives(
1992                                     ty::OutlivesPredicate(ty, region),
1993                                 ))
1994                                 .to_predicate(tcx),
1995                                 lifetime.span,
1996                             ));
1997                         }
1998                     }
1999                 }
2000             }
2001
2002             hir::WherePredicate::RegionPredicate(region_pred) => {
2003                 let r1 = AstConv::ast_region_to_region(&icx, &region_pred.lifetime, None);
2004                 predicates.extend(region_pred.bounds.iter().map(|bound| {
2005                     let (r2, span) = match bound {
2006                         hir::GenericBound::Outlives(lt) => {
2007                             (AstConv::ast_region_to_region(&icx, lt, None), lt.span)
2008                         }
2009                         _ => bug!(),
2010                     };
2011                     let pred = ty::PredicateKind::RegionOutlives(ty::OutlivesPredicate(r1, r2))
2012                         .to_predicate(icx.tcx);
2013
2014                     (pred, span)
2015                 }))
2016             }
2017
2018             hir::WherePredicate::EqPredicate(..) => {
2019                 // FIXME(#20041)
2020             }
2021         }
2022     }
2023
2024     if tcx.features().const_evaluatable_checked {
2025         predicates.extend(const_evaluatable_predicates_of(tcx, def_id.expect_local()));
2026     }
2027
2028     let mut predicates: Vec<_> = predicates.into_iter().collect();
2029
2030     // Subtle: before we store the predicates into the tcx, we
2031     // sort them so that predicates like `T: Foo<Item=U>` come
2032     // before uses of `U`.  This avoids false ambiguity errors
2033     // in trait checking. See `setup_constraining_predicates`
2034     // for details.
2035     if let Node::Item(&Item { kind: ItemKind::Impl { .. }, .. }) = node {
2036         let self_ty = tcx.type_of(def_id);
2037         let trait_ref = tcx.impl_trait_ref(def_id);
2038         cgp::setup_constraining_predicates(
2039             tcx,
2040             &mut predicates,
2041             trait_ref,
2042             &mut cgp::parameters_for_impl(self_ty, trait_ref),
2043         );
2044     }
2045
2046     let result = ty::GenericPredicates {
2047         parent: generics.parent,
2048         predicates: tcx.arena.alloc_from_iter(predicates),
2049     };
2050     debug!("explicit_predicates_of(def_id={:?}) = {:?}", def_id, result);
2051     result
2052 }
2053
2054 fn const_evaluatable_predicates_of<'tcx>(
2055     tcx: TyCtxt<'tcx>,
2056     def_id: LocalDefId,
2057 ) -> FxIndexSet<(ty::Predicate<'tcx>, Span)> {
2058     struct ConstCollector<'tcx> {
2059         tcx: TyCtxt<'tcx>,
2060         preds: FxIndexSet<(ty::Predicate<'tcx>, Span)>,
2061     }
2062
2063     impl<'tcx> intravisit::Visitor<'tcx> for ConstCollector<'tcx> {
2064         type Map = Map<'tcx>;
2065
2066         fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
2067             intravisit::NestedVisitorMap::None
2068         }
2069
2070         fn visit_anon_const(&mut self, c: &'tcx hir::AnonConst) {
2071             let def_id = self.tcx.hir().local_def_id(c.hir_id);
2072             let ct = ty::Const::from_anon_const(self.tcx, def_id);
2073             if let ty::ConstKind::Unevaluated(def, substs, None) = ct.val {
2074                 let span = self.tcx.hir().span(c.hir_id);
2075                 self.preds.insert((
2076                     ty::PredicateKind::ConstEvaluatable(def, substs).to_predicate(self.tcx),
2077                     span,
2078                 ));
2079             }
2080         }
2081     }
2082
2083     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
2084     let node = tcx.hir().get(hir_id);
2085
2086     let mut collector = ConstCollector { tcx, preds: FxIndexSet::default() };
2087     if let hir::Node::Item(item) = node {
2088         if let hir::ItemKind::Impl(ref impl_) = item.kind {
2089             if let Some(of_trait) = &impl_.of_trait {
2090                 debug!("const_evaluatable_predicates_of({:?}): visit impl trait_ref", def_id);
2091                 collector.visit_trait_ref(of_trait);
2092             }
2093
2094             debug!("const_evaluatable_predicates_of({:?}): visit_self_ty", def_id);
2095             collector.visit_ty(impl_.self_ty);
2096         }
2097     }
2098
2099     if let Some(generics) = node.generics() {
2100         debug!("const_evaluatable_predicates_of({:?}): visit_generics", def_id);
2101         collector.visit_generics(generics);
2102     }
2103
2104     if let Some(fn_sig) = tcx.hir().fn_sig_by_hir_id(hir_id) {
2105         debug!("const_evaluatable_predicates_of({:?}): visit_fn_decl", def_id);
2106         collector.visit_fn_decl(fn_sig.decl);
2107     }
2108     debug!("const_evaluatable_predicates_of({:?}) = {:?}", def_id, collector.preds);
2109
2110     collector.preds
2111 }
2112
2113 fn trait_explicit_predicates_and_bounds(
2114     tcx: TyCtxt<'_>,
2115     def_id: LocalDefId,
2116 ) -> ty::GenericPredicates<'_> {
2117     assert_eq!(tcx.def_kind(def_id), DefKind::Trait);
2118     gather_explicit_predicates_of(tcx, def_id.to_def_id())
2119 }
2120
2121 fn explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
2122     if let DefKind::Trait = tcx.def_kind(def_id) {
2123         // Remove bounds on associated types from the predicates, they will be
2124         // returned by `explicit_item_bounds`.
2125         let predicates_and_bounds = tcx.trait_explicit_predicates_and_bounds(def_id.expect_local());
2126         let trait_identity_substs = InternalSubsts::identity_for_item(tcx, def_id);
2127
2128         let is_assoc_item_ty = |ty: Ty<'_>| {
2129             // For a predicate from a where clause to become a bound on an
2130             // associated type:
2131             // * It must use the identity substs of the item.
2132             //     * Since any generic parameters on the item are not in scope,
2133             //       this means that the item is not a GAT, and its identity
2134             //       substs are the same as the trait's.
2135             // * It must be an associated type for this trait (*not* a
2136             //   supertrait).
2137             if let ty::Projection(projection) = ty.kind() {
2138                 projection.substs == trait_identity_substs
2139                     && tcx.associated_item(projection.item_def_id).container.id() == def_id
2140             } else {
2141                 false
2142             }
2143         };
2144
2145         let predicates: Vec<_> = predicates_and_bounds
2146             .predicates
2147             .iter()
2148             .copied()
2149             .filter(|(pred, _)| match pred.kind().skip_binder() {
2150                 ty::PredicateKind::Trait(tr, _) => !is_assoc_item_ty(tr.self_ty()),
2151                 ty::PredicateKind::Projection(proj) => {
2152                     !is_assoc_item_ty(proj.projection_ty.self_ty())
2153                 }
2154                 ty::PredicateKind::TypeOutlives(outlives) => !is_assoc_item_ty(outlives.0),
2155                 _ => true,
2156             })
2157             .collect();
2158         if predicates.len() == predicates_and_bounds.predicates.len() {
2159             predicates_and_bounds
2160         } else {
2161             ty::GenericPredicates {
2162                 parent: predicates_and_bounds.parent,
2163                 predicates: tcx.arena.alloc_slice(&predicates),
2164             }
2165         }
2166     } else {
2167         gather_explicit_predicates_of(tcx, def_id)
2168     }
2169 }
2170
2171 fn projection_ty_from_predicates(
2172     tcx: TyCtxt<'tcx>,
2173     key: (
2174         // ty_def_id
2175         DefId,
2176         // def_id of `N` in `<T as Trait>::N`
2177         DefId,
2178     ),
2179 ) -> Option<ty::ProjectionTy<'tcx>> {
2180     let (ty_def_id, item_def_id) = key;
2181     let mut projection_ty = None;
2182     for (predicate, _) in tcx.predicates_of(ty_def_id).predicates {
2183         if let ty::PredicateKind::Projection(projection_predicate) = predicate.kind().skip_binder()
2184         {
2185             if item_def_id == projection_predicate.projection_ty.item_def_id {
2186                 projection_ty = Some(projection_predicate.projection_ty);
2187                 break;
2188             }
2189         }
2190     }
2191     projection_ty
2192 }
2193
2194 /// Converts a specific `GenericBound` from the AST into a set of
2195 /// predicates that apply to the self type. A vector is returned
2196 /// because this can be anywhere from zero predicates (`T: ?Sized` adds no
2197 /// predicates) to one (`T: Foo`) to many (`T: Bar<X = i32>` adds `T: Bar`
2198 /// and `<T as Bar>::X == i32`).
2199 fn predicates_from_bound<'tcx>(
2200     astconv: &dyn AstConv<'tcx>,
2201     param_ty: Ty<'tcx>,
2202     bound: &'tcx hir::GenericBound<'tcx>,
2203     constness: hir::Constness,
2204 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2205     match *bound {
2206         hir::GenericBound::Trait(ref tr, modifier) => {
2207             let constness = match modifier {
2208                 hir::TraitBoundModifier::Maybe => return vec![],
2209                 hir::TraitBoundModifier::MaybeConst => hir::Constness::NotConst,
2210                 hir::TraitBoundModifier::None => constness,
2211             };
2212
2213             let mut bounds = Bounds::default();
2214             let _ = astconv.instantiate_poly_trait_ref(tr, constness, param_ty, &mut bounds);
2215             bounds.predicates(astconv.tcx(), param_ty)
2216         }
2217         hir::GenericBound::LangItemTrait(lang_item, span, hir_id, args) => {
2218             let mut bounds = Bounds::default();
2219             astconv.instantiate_lang_item_trait_ref(
2220                 lang_item,
2221                 span,
2222                 hir_id,
2223                 args,
2224                 param_ty,
2225                 &mut bounds,
2226             );
2227             bounds.predicates(astconv.tcx(), param_ty)
2228         }
2229         hir::GenericBound::Outlives(ref lifetime) => {
2230             let region = astconv.ast_region_to_region(lifetime, None);
2231             let pred = ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(param_ty, region))
2232                 .to_predicate(astconv.tcx());
2233             vec![(pred, lifetime.span)]
2234         }
2235     }
2236 }
2237
2238 fn compute_sig_of_foreign_fn_decl<'tcx>(
2239     tcx: TyCtxt<'tcx>,
2240     def_id: DefId,
2241     decl: &'tcx hir::FnDecl<'tcx>,
2242     abi: abi::Abi,
2243     ident: Ident,
2244 ) -> ty::PolyFnSig<'tcx> {
2245     let unsafety = if abi == abi::Abi::RustIntrinsic {
2246         intrinsic_operation_unsafety(tcx.item_name(def_id))
2247     } else {
2248         hir::Unsafety::Unsafe
2249     };
2250     let fty = AstConv::ty_of_fn(
2251         &ItemCtxt::new(tcx, def_id),
2252         unsafety,
2253         abi,
2254         decl,
2255         &hir::Generics::empty(),
2256         Some(ident.span),
2257     );
2258
2259     // Feature gate SIMD types in FFI, since I am not sure that the
2260     // ABIs are handled at all correctly. -huonw
2261     if abi != abi::Abi::RustIntrinsic
2262         && abi != abi::Abi::PlatformIntrinsic
2263         && !tcx.features().simd_ffi
2264     {
2265         let check = |ast_ty: &hir::Ty<'_>, ty: Ty<'_>| {
2266             if ty.is_simd() {
2267                 let snip = tcx
2268                     .sess
2269                     .source_map()
2270                     .span_to_snippet(ast_ty.span)
2271                     .map_or(String::new(), |s| format!(" `{}`", s));
2272                 tcx.sess
2273                     .struct_span_err(
2274                         ast_ty.span,
2275                         &format!(
2276                             "use of SIMD type{} in FFI is highly experimental and \
2277                              may result in invalid code",
2278                             snip
2279                         ),
2280                     )
2281                     .help("add `#![feature(simd_ffi)]` to the crate attributes to enable")
2282                     .emit();
2283             }
2284         };
2285         for (input, ty) in decl.inputs.iter().zip(fty.inputs().skip_binder()) {
2286             check(&input, ty)
2287         }
2288         if let hir::FnRetTy::Return(ref ty) = decl.output {
2289             check(&ty, fty.output().skip_binder())
2290         }
2291     }
2292
2293     fty
2294 }
2295
2296 fn is_foreign_item(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
2297     match tcx.hir().get_if_local(def_id) {
2298         Some(Node::ForeignItem(..)) => true,
2299         Some(_) => false,
2300         _ => bug!("is_foreign_item applied to non-local def-id {:?}", def_id),
2301     }
2302 }
2303
2304 fn static_mutability(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::Mutability> {
2305     match tcx.hir().get_if_local(def_id) {
2306         Some(
2307             Node::Item(&hir::Item { kind: hir::ItemKind::Static(_, mutbl, _), .. })
2308             | Node::ForeignItem(&hir::ForeignItem {
2309                 kind: hir::ForeignItemKind::Static(_, mutbl),
2310                 ..
2311             }),
2312         ) => Some(mutbl),
2313         Some(_) => None,
2314         _ => bug!("static_mutability applied to non-local def-id {:?}", def_id),
2315     }
2316 }
2317
2318 fn generator_kind(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::GeneratorKind> {
2319     match tcx.hir().get_if_local(def_id) {
2320         Some(Node::Expr(&rustc_hir::Expr {
2321             kind: rustc_hir::ExprKind::Closure(_, _, body_id, _, _),
2322             ..
2323         })) => tcx.hir().body(body_id).generator_kind(),
2324         Some(_) => None,
2325         _ => bug!("generator_kind applied to non-local def-id {:?}", def_id),
2326     }
2327 }
2328
2329 fn from_target_feature(
2330     tcx: TyCtxt<'_>,
2331     id: DefId,
2332     attr: &ast::Attribute,
2333     supported_target_features: &FxHashMap<String, Option<Symbol>>,
2334     target_features: &mut Vec<Symbol>,
2335 ) {
2336     let list = match attr.meta_item_list() {
2337         Some(list) => list,
2338         None => return,
2339     };
2340     let bad_item = |span| {
2341         let msg = "malformed `target_feature` attribute input";
2342         let code = "enable = \"..\"".to_owned();
2343         tcx.sess
2344             .struct_span_err(span, &msg)
2345             .span_suggestion(span, "must be of the form", code, Applicability::HasPlaceholders)
2346             .emit();
2347     };
2348     let rust_features = tcx.features();
2349     for item in list {
2350         // Only `enable = ...` is accepted in the meta-item list.
2351         if !item.has_name(sym::enable) {
2352             bad_item(item.span());
2353             continue;
2354         }
2355
2356         // Must be of the form `enable = "..."` (a string).
2357         let value = match item.value_str() {
2358             Some(value) => value,
2359             None => {
2360                 bad_item(item.span());
2361                 continue;
2362             }
2363         };
2364
2365         // We allow comma separation to enable multiple features.
2366         target_features.extend(value.as_str().split(',').filter_map(|feature| {
2367             let feature_gate = match supported_target_features.get(feature) {
2368                 Some(g) => g,
2369                 None => {
2370                     let msg =
2371                         format!("the feature named `{}` is not valid for this target", feature);
2372                     let mut err = tcx.sess.struct_span_err(item.span(), &msg);
2373                     err.span_label(
2374                         item.span(),
2375                         format!("`{}` is not valid for this target", feature),
2376                     );
2377                     if let Some(stripped) = feature.strip_prefix('+') {
2378                         let valid = supported_target_features.contains_key(stripped);
2379                         if valid {
2380                             err.help("consider removing the leading `+` in the feature name");
2381                         }
2382                     }
2383                     err.emit();
2384                     return None;
2385                 }
2386             };
2387
2388             // Only allow features whose feature gates have been enabled.
2389             let allowed = match feature_gate.as_ref().copied() {
2390                 Some(sym::arm_target_feature) => rust_features.arm_target_feature,
2391                 Some(sym::aarch64_target_feature) => rust_features.aarch64_target_feature,
2392                 Some(sym::hexagon_target_feature) => rust_features.hexagon_target_feature,
2393                 Some(sym::powerpc_target_feature) => rust_features.powerpc_target_feature,
2394                 Some(sym::mips_target_feature) => rust_features.mips_target_feature,
2395                 Some(sym::riscv_target_feature) => rust_features.riscv_target_feature,
2396                 Some(sym::avx512_target_feature) => rust_features.avx512_target_feature,
2397                 Some(sym::sse4a_target_feature) => rust_features.sse4a_target_feature,
2398                 Some(sym::tbm_target_feature) => rust_features.tbm_target_feature,
2399                 Some(sym::wasm_target_feature) => rust_features.wasm_target_feature,
2400                 Some(sym::cmpxchg16b_target_feature) => rust_features.cmpxchg16b_target_feature,
2401                 Some(sym::adx_target_feature) => rust_features.adx_target_feature,
2402                 Some(sym::movbe_target_feature) => rust_features.movbe_target_feature,
2403                 Some(sym::rtm_target_feature) => rust_features.rtm_target_feature,
2404                 Some(sym::f16c_target_feature) => rust_features.f16c_target_feature,
2405                 Some(sym::ermsb_target_feature) => rust_features.ermsb_target_feature,
2406                 Some(name) => bug!("unknown target feature gate {}", name),
2407                 None => true,
2408             };
2409             if !allowed && id.is_local() {
2410                 feature_err(
2411                     &tcx.sess.parse_sess,
2412                     feature_gate.unwrap(),
2413                     item.span(),
2414                     &format!("the target feature `{}` is currently unstable", feature),
2415                 )
2416                 .emit();
2417             }
2418             Some(Symbol::intern(feature))
2419         }));
2420     }
2421 }
2422
2423 fn linkage_by_name(tcx: TyCtxt<'_>, def_id: DefId, name: &str) -> Linkage {
2424     use rustc_middle::mir::mono::Linkage::*;
2425
2426     // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
2427     // applicable to variable declarations and may not really make sense for
2428     // Rust code in the first place but allow them anyway and trust that the
2429     // user knows what s/he's doing. Who knows, unanticipated use cases may pop
2430     // up in the future.
2431     //
2432     // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
2433     // and don't have to be, LLVM treats them as no-ops.
2434     match name {
2435         "appending" => Appending,
2436         "available_externally" => AvailableExternally,
2437         "common" => Common,
2438         "extern_weak" => ExternalWeak,
2439         "external" => External,
2440         "internal" => Internal,
2441         "linkonce" => LinkOnceAny,
2442         "linkonce_odr" => LinkOnceODR,
2443         "private" => Private,
2444         "weak" => WeakAny,
2445         "weak_odr" => WeakODR,
2446         _ => {
2447             let span = tcx.hir().span_if_local(def_id);
2448             if let Some(span) = span {
2449                 tcx.sess.span_fatal(span, "invalid linkage specified")
2450             } else {
2451                 tcx.sess.fatal(&format!("invalid linkage specified: {}", name))
2452             }
2453         }
2454     }
2455 }
2456
2457 fn codegen_fn_attrs(tcx: TyCtxt<'_>, id: DefId) -> CodegenFnAttrs {
2458     let attrs = tcx.get_attrs(id);
2459
2460     let mut codegen_fn_attrs = CodegenFnAttrs::new();
2461     if should_inherit_track_caller(tcx, id) {
2462         codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
2463     }
2464
2465     let supported_target_features = tcx.supported_target_features(LOCAL_CRATE);
2466
2467     let mut inline_span = None;
2468     let mut link_ordinal_span = None;
2469     let mut no_sanitize_span = None;
2470     for attr in attrs.iter() {
2471         if tcx.sess.check_name(attr, sym::cold) {
2472             codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD;
2473         } else if tcx.sess.check_name(attr, sym::rustc_allocator) {
2474             codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR;
2475         } else if tcx.sess.check_name(attr, sym::unwind) {
2476             codegen_fn_attrs.flags |= CodegenFnAttrFlags::UNWIND;
2477         } else if tcx.sess.check_name(attr, sym::ffi_returns_twice) {
2478             if tcx.is_foreign_item(id) {
2479                 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_RETURNS_TWICE;
2480             } else {
2481                 // `#[ffi_returns_twice]` is only allowed `extern fn`s.
2482                 struct_span_err!(
2483                     tcx.sess,
2484                     attr.span,
2485                     E0724,
2486                     "`#[ffi_returns_twice]` may only be used on foreign functions"
2487                 )
2488                 .emit();
2489             }
2490         } else if tcx.sess.check_name(attr, sym::ffi_pure) {
2491             if tcx.is_foreign_item(id) {
2492                 if attrs.iter().any(|a| tcx.sess.check_name(a, sym::ffi_const)) {
2493                     // `#[ffi_const]` functions cannot be `#[ffi_pure]`
2494                     struct_span_err!(
2495                         tcx.sess,
2496                         attr.span,
2497                         E0757,
2498                         "`#[ffi_const]` function cannot be `#[ffi_pure]`"
2499                     )
2500                     .emit();
2501                 } else {
2502                     codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_PURE;
2503                 }
2504             } else {
2505                 // `#[ffi_pure]` is only allowed on foreign functions
2506                 struct_span_err!(
2507                     tcx.sess,
2508                     attr.span,
2509                     E0755,
2510                     "`#[ffi_pure]` may only be used on foreign functions"
2511                 )
2512                 .emit();
2513             }
2514         } else if tcx.sess.check_name(attr, sym::ffi_const) {
2515             if tcx.is_foreign_item(id) {
2516                 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_CONST;
2517             } else {
2518                 // `#[ffi_const]` is only allowed on foreign functions
2519                 struct_span_err!(
2520                     tcx.sess,
2521                     attr.span,
2522                     E0756,
2523                     "`#[ffi_const]` may only be used on foreign functions"
2524                 )
2525                 .emit();
2526             }
2527         } else if tcx.sess.check_name(attr, sym::rustc_allocator_nounwind) {
2528             codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND;
2529         } else if tcx.sess.check_name(attr, sym::naked) {
2530             codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED;
2531         } else if tcx.sess.check_name(attr, sym::no_mangle) {
2532             codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2533         } else if tcx.sess.check_name(attr, sym::rustc_std_internal_symbol) {
2534             codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2535         } else if tcx.sess.check_name(attr, sym::used) {
2536             codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED;
2537         } else if tcx.sess.check_name(attr, sym::cmse_nonsecure_entry) {
2538             if tcx.fn_sig(id).abi() != abi::Abi::C {
2539                 struct_span_err!(
2540                     tcx.sess,
2541                     attr.span,
2542                     E0776,
2543                     "`#[cmse_nonsecure_entry]` requires C ABI"
2544                 )
2545                 .emit();
2546             }
2547             if !tcx.sess.target.llvm_target.contains("thumbv8m") {
2548                 struct_span_err!(tcx.sess, attr.span, E0775, "`#[cmse_nonsecure_entry]` is only valid for targets with the TrustZone-M extension")
2549                     .emit();
2550             }
2551             codegen_fn_attrs.flags |= CodegenFnAttrFlags::CMSE_NONSECURE_ENTRY;
2552         } else if tcx.sess.check_name(attr, sym::thread_local) {
2553             codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL;
2554         } else if tcx.sess.check_name(attr, sym::track_caller) {
2555             if tcx.is_closure(id) || tcx.fn_sig(id).abi() != abi::Abi::Rust {
2556                 struct_span_err!(tcx.sess, attr.span, E0737, "`#[track_caller]` requires Rust ABI")
2557                     .emit();
2558             }
2559             codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
2560         } else if tcx.sess.check_name(attr, sym::export_name) {
2561             if let Some(s) = attr.value_str() {
2562                 if s.as_str().contains('\0') {
2563                     // `#[export_name = ...]` will be converted to a null-terminated string,
2564                     // so it may not contain any null characters.
2565                     struct_span_err!(
2566                         tcx.sess,
2567                         attr.span,
2568                         E0648,
2569                         "`export_name` may not contain null characters"
2570                     )
2571                     .emit();
2572                 }
2573                 codegen_fn_attrs.export_name = Some(s);
2574             }
2575         } else if tcx.sess.check_name(attr, sym::target_feature) {
2576             if !tcx.is_closure(id) && tcx.fn_sig(id).unsafety() == hir::Unsafety::Normal {
2577                 if !tcx.features().target_feature_11 {
2578                     let mut err = feature_err(
2579                         &tcx.sess.parse_sess,
2580                         sym::target_feature_11,
2581                         attr.span,
2582                         "`#[target_feature(..)]` can only be applied to `unsafe` functions",
2583                     );
2584                     err.span_label(tcx.def_span(id), "not an `unsafe` function");
2585                     err.emit();
2586                 } else if let Some(local_id) = id.as_local() {
2587                     check_target_feature_trait_unsafe(tcx, local_id, attr.span);
2588                 }
2589             }
2590             from_target_feature(
2591                 tcx,
2592                 id,
2593                 attr,
2594                 &supported_target_features,
2595                 &mut codegen_fn_attrs.target_features,
2596             );
2597         } else if tcx.sess.check_name(attr, sym::linkage) {
2598             if let Some(val) = attr.value_str() {
2599                 codegen_fn_attrs.linkage = Some(linkage_by_name(tcx, id, &val.as_str()));
2600             }
2601         } else if tcx.sess.check_name(attr, sym::link_section) {
2602             if let Some(val) = attr.value_str() {
2603                 if val.as_str().bytes().any(|b| b == 0) {
2604                     let msg = format!(
2605                         "illegal null byte in link_section \
2606                          value: `{}`",
2607                         &val
2608                     );
2609                     tcx.sess.span_err(attr.span, &msg);
2610                 } else {
2611                     codegen_fn_attrs.link_section = Some(val);
2612                 }
2613             }
2614         } else if tcx.sess.check_name(attr, sym::link_name) {
2615             codegen_fn_attrs.link_name = attr.value_str();
2616         } else if tcx.sess.check_name(attr, sym::link_ordinal) {
2617             link_ordinal_span = Some(attr.span);
2618             if let ordinal @ Some(_) = check_link_ordinal(tcx, attr) {
2619                 codegen_fn_attrs.link_ordinal = ordinal;
2620             }
2621         } else if tcx.sess.check_name(attr, sym::no_sanitize) {
2622             no_sanitize_span = Some(attr.span);
2623             if let Some(list) = attr.meta_item_list() {
2624                 for item in list.iter() {
2625                     if item.has_name(sym::address) {
2626                         codegen_fn_attrs.no_sanitize |= SanitizerSet::ADDRESS;
2627                     } else if item.has_name(sym::memory) {
2628                         codegen_fn_attrs.no_sanitize |= SanitizerSet::MEMORY;
2629                     } else if item.has_name(sym::thread) {
2630                         codegen_fn_attrs.no_sanitize |= SanitizerSet::THREAD;
2631                     } else {
2632                         tcx.sess
2633                             .struct_span_err(item.span(), "invalid argument for `no_sanitize`")
2634                             .note("expected one of: `address`, `memory` or `thread`")
2635                             .emit();
2636                     }
2637                 }
2638             }
2639         } else if tcx.sess.check_name(attr, sym::instruction_set) {
2640             codegen_fn_attrs.instruction_set = match attr.meta().map(|i| i.kind) {
2641                 Some(MetaItemKind::List(ref items)) => match items.as_slice() {
2642                     [NestedMetaItem::MetaItem(set)] => {
2643                         let segments =
2644                             set.path.segments.iter().map(|x| x.ident.name).collect::<Vec<_>>();
2645                         match segments.as_slice() {
2646                             [sym::arm, sym::a32] | [sym::arm, sym::t32] => {
2647                                 if !tcx.sess.target.has_thumb_interworking {
2648                                     struct_span_err!(
2649                                         tcx.sess.diagnostic(),
2650                                         attr.span,
2651                                         E0779,
2652                                         "target does not support `#[instruction_set]`"
2653                                     )
2654                                     .emit();
2655                                     None
2656                                 } else if segments[1] == sym::a32 {
2657                                     Some(InstructionSetAttr::ArmA32)
2658                                 } else if segments[1] == sym::t32 {
2659                                     Some(InstructionSetAttr::ArmT32)
2660                                 } else {
2661                                     unreachable!()
2662                                 }
2663                             }
2664                             _ => {
2665                                 struct_span_err!(
2666                                     tcx.sess.diagnostic(),
2667                                     attr.span,
2668                                     E0779,
2669                                     "invalid instruction set specified",
2670                                 )
2671                                 .emit();
2672                                 None
2673                             }
2674                         }
2675                     }
2676                     [] => {
2677                         struct_span_err!(
2678                             tcx.sess.diagnostic(),
2679                             attr.span,
2680                             E0778,
2681                             "`#[instruction_set]` requires an argument"
2682                         )
2683                         .emit();
2684                         None
2685                     }
2686                     _ => {
2687                         struct_span_err!(
2688                             tcx.sess.diagnostic(),
2689                             attr.span,
2690                             E0779,
2691                             "cannot specify more than one instruction set"
2692                         )
2693                         .emit();
2694                         None
2695                     }
2696                 },
2697                 _ => {
2698                     struct_span_err!(
2699                         tcx.sess.diagnostic(),
2700                         attr.span,
2701                         E0778,
2702                         "must specify an instruction set"
2703                     )
2704                     .emit();
2705                     None
2706                 }
2707             };
2708         }
2709     }
2710
2711     codegen_fn_attrs.inline = attrs.iter().fold(InlineAttr::None, |ia, attr| {
2712         if !attr.has_name(sym::inline) {
2713             return ia;
2714         }
2715         match attr.meta().map(|i| i.kind) {
2716             Some(MetaItemKind::Word) => {
2717                 tcx.sess.mark_attr_used(attr);
2718                 InlineAttr::Hint
2719             }
2720             Some(MetaItemKind::List(ref items)) => {
2721                 tcx.sess.mark_attr_used(attr);
2722                 inline_span = Some(attr.span);
2723                 if items.len() != 1 {
2724                     struct_span_err!(
2725                         tcx.sess.diagnostic(),
2726                         attr.span,
2727                         E0534,
2728                         "expected one argument"
2729                     )
2730                     .emit();
2731                     InlineAttr::None
2732                 } else if list_contains_name(&items[..], sym::always) {
2733                     InlineAttr::Always
2734                 } else if list_contains_name(&items[..], sym::never) {
2735                     InlineAttr::Never
2736                 } else {
2737                     struct_span_err!(
2738                         tcx.sess.diagnostic(),
2739                         items[0].span(),
2740                         E0535,
2741                         "invalid argument"
2742                     )
2743                     .emit();
2744
2745                     InlineAttr::None
2746                 }
2747             }
2748             Some(MetaItemKind::NameValue(_)) => ia,
2749             None => ia,
2750         }
2751     });
2752
2753     codegen_fn_attrs.optimize = attrs.iter().fold(OptimizeAttr::None, |ia, attr| {
2754         if !attr.has_name(sym::optimize) {
2755             return ia;
2756         }
2757         let err = |sp, s| struct_span_err!(tcx.sess.diagnostic(), sp, E0722, "{}", s).emit();
2758         match attr.meta().map(|i| i.kind) {
2759             Some(MetaItemKind::Word) => {
2760                 err(attr.span, "expected one argument");
2761                 ia
2762             }
2763             Some(MetaItemKind::List(ref items)) => {
2764                 tcx.sess.mark_attr_used(attr);
2765                 inline_span = Some(attr.span);
2766                 if items.len() != 1 {
2767                     err(attr.span, "expected one argument");
2768                     OptimizeAttr::None
2769                 } else if list_contains_name(&items[..], sym::size) {
2770                     OptimizeAttr::Size
2771                 } else if list_contains_name(&items[..], sym::speed) {
2772                     OptimizeAttr::Speed
2773                 } else {
2774                     err(items[0].span(), "invalid argument");
2775                     OptimizeAttr::None
2776                 }
2777             }
2778             Some(MetaItemKind::NameValue(_)) => ia,
2779             None => ia,
2780         }
2781     });
2782
2783     // #73631: closures inherit `#[target_feature]` annotations
2784     if tcx.features().target_feature_11 && tcx.is_closure(id) {
2785         let owner_id = tcx.parent(id).expect("closure should have a parent");
2786         codegen_fn_attrs
2787             .target_features
2788             .extend(tcx.codegen_fn_attrs(owner_id).target_features.iter().copied())
2789     }
2790
2791     // If a function uses #[target_feature] it can't be inlined into general
2792     // purpose functions as they wouldn't have the right target features
2793     // enabled. For that reason we also forbid #[inline(always)] as it can't be
2794     // respected.
2795     if !codegen_fn_attrs.target_features.is_empty() {
2796         if codegen_fn_attrs.inline == InlineAttr::Always {
2797             if let Some(span) = inline_span {
2798                 tcx.sess.span_err(
2799                     span,
2800                     "cannot use `#[inline(always)]` with \
2801                      `#[target_feature]`",
2802                 );
2803             }
2804         }
2805     }
2806
2807     if !codegen_fn_attrs.no_sanitize.is_empty() {
2808         if codegen_fn_attrs.inline == InlineAttr::Always {
2809             if let (Some(no_sanitize_span), Some(inline_span)) = (no_sanitize_span, inline_span) {
2810                 let hir_id = tcx.hir().local_def_id_to_hir_id(id.expect_local());
2811                 tcx.struct_span_lint_hir(
2812                     lint::builtin::INLINE_NO_SANITIZE,
2813                     hir_id,
2814                     no_sanitize_span,
2815                     |lint| {
2816                         lint.build("`no_sanitize` will have no effect after inlining")
2817                             .span_note(inline_span, "inlining requested here")
2818                             .emit();
2819                     },
2820                 )
2821             }
2822         }
2823     }
2824
2825     // Weak lang items have the same semantics as "std internal" symbols in the
2826     // sense that they're preserved through all our LTO passes and only
2827     // strippable by the linker.
2828     //
2829     // Additionally weak lang items have predetermined symbol names.
2830     if tcx.is_weak_lang_item(id) {
2831         codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2832     }
2833     let check_name = |attr, sym| tcx.sess.check_name(attr, sym);
2834     if let Some(name) = weak_lang_items::link_name(check_name, &attrs) {
2835         codegen_fn_attrs.export_name = Some(name);
2836         codegen_fn_attrs.link_name = Some(name);
2837     }
2838     check_link_name_xor_ordinal(tcx, &codegen_fn_attrs, link_ordinal_span);
2839
2840     // Internal symbols to the standard library all have no_mangle semantics in
2841     // that they have defined symbol names present in the function name. This
2842     // also applies to weak symbols where they all have known symbol names.
2843     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
2844         codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2845     }
2846
2847     codegen_fn_attrs
2848 }
2849
2850 /// Checks if the provided DefId is a method in a trait impl for a trait which has track_caller
2851 /// applied to the method prototype.
2852 fn should_inherit_track_caller(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
2853     if let Some(impl_item) = tcx.opt_associated_item(def_id) {
2854         if let ty::AssocItemContainer::ImplContainer(impl_def_id) = impl_item.container {
2855             if let Some(trait_def_id) = tcx.trait_id_of_impl(impl_def_id) {
2856                 if let Some(trait_item) = tcx
2857                     .associated_items(trait_def_id)
2858                     .filter_by_name_unhygienic(impl_item.ident.name)
2859                     .find(move |trait_item| {
2860                         trait_item.kind == ty::AssocKind::Fn
2861                             && tcx.hygienic_eq(impl_item.ident, trait_item.ident, trait_def_id)
2862                     })
2863                 {
2864                     return tcx
2865                         .codegen_fn_attrs(trait_item.def_id)
2866                         .flags
2867                         .intersects(CodegenFnAttrFlags::TRACK_CALLER);
2868                 }
2869             }
2870         }
2871     }
2872
2873     false
2874 }
2875
2876 fn check_link_ordinal(tcx: TyCtxt<'_>, attr: &ast::Attribute) -> Option<usize> {
2877     use rustc_ast::{Lit, LitIntType, LitKind};
2878     let meta_item_list = attr.meta_item_list();
2879     let meta_item_list: Option<&[ast::NestedMetaItem]> = meta_item_list.as_ref().map(Vec::as_ref);
2880     let sole_meta_list = match meta_item_list {
2881         Some([item]) => item.literal(),
2882         _ => None,
2883     };
2884     if let Some(Lit { kind: LitKind::Int(ordinal, LitIntType::Unsuffixed), .. }) = sole_meta_list {
2885         if *ordinal <= usize::MAX as u128 {
2886             Some(*ordinal as usize)
2887         } else {
2888             let msg = format!("ordinal value in `link_ordinal` is too large: `{}`", &ordinal);
2889             tcx.sess
2890                 .struct_span_err(attr.span, &msg)
2891                 .note("the value may not exceed `usize::MAX`")
2892                 .emit();
2893             None
2894         }
2895     } else {
2896         tcx.sess
2897             .struct_span_err(attr.span, "illegal ordinal format in `link_ordinal`")
2898             .note("an unsuffixed integer value, e.g., `1`, is expected")
2899             .emit();
2900         None
2901     }
2902 }
2903
2904 fn check_link_name_xor_ordinal(
2905     tcx: TyCtxt<'_>,
2906     codegen_fn_attrs: &CodegenFnAttrs,
2907     inline_span: Option<Span>,
2908 ) {
2909     if codegen_fn_attrs.link_name.is_none() || codegen_fn_attrs.link_ordinal.is_none() {
2910         return;
2911     }
2912     let msg = "cannot use `#[link_name]` with `#[link_ordinal]`";
2913     if let Some(span) = inline_span {
2914         tcx.sess.span_err(span, msg);
2915     } else {
2916         tcx.sess.err(msg);
2917     }
2918 }
2919
2920 /// Checks the function annotated with `#[target_feature]` is not a safe
2921 /// trait method implementation, reporting an error if it is.
2922 fn check_target_feature_trait_unsafe(tcx: TyCtxt<'_>, id: LocalDefId, attr_span: Span) {
2923     let hir_id = tcx.hir().local_def_id_to_hir_id(id);
2924     let node = tcx.hir().get(hir_id);
2925     if let Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }) = node {
2926         let parent_id = tcx.hir().get_parent_item(hir_id);
2927         let parent_item = tcx.hir().expect_item(parent_id);
2928         if let hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) = parent_item.kind {
2929             tcx.sess
2930                 .struct_span_err(
2931                     attr_span,
2932                     "`#[target_feature(..)]` cannot be applied to safe trait method",
2933                 )
2934                 .span_label(attr_span, "cannot be applied to safe trait method")
2935                 .span_label(tcx.def_span(id), "not an `unsafe` function")
2936                 .emit();
2937         }
2938     }
2939 }