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