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