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