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