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