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