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