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