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