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