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