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