]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_analysis/src/collect.rs
Rollup merge of #107168 - Nilstrieb:if-a-tait-falls-in-the-forest,can-we-know-it...
[rust.git] / compiler / rustc_hir_analysis / 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::check::intrinsic::intrinsic_operation_unsafety;
19 use crate::errors;
20 use hir::def::DefKind;
21 use rustc_data_structures::captures::Captures;
22 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
23 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, ErrorGuaranteed, StashKey};
24 use rustc_hir as hir;
25 use rustc_hir::def_id::{DefId, LocalDefId};
26 use rustc_hir::intravisit::{self, Visitor};
27 use rustc_hir::{GenericParamKind, Node};
28 use rustc_infer::infer::TyCtxtInferExt;
29 use rustc_infer::traits::ObligationCause;
30 use rustc_middle::hir::nested_filter;
31 use rustc_middle::ty::query::Providers;
32 use rustc_middle::ty::util::{Discr, IntTypeExt};
33 use rustc_middle::ty::{self, AdtKind, Const, IsSuggestable, ToPredicate, Ty, TyCtxt};
34 use rustc_span::symbol::{kw, sym, Ident, Symbol};
35 use rustc_span::Span;
36 use rustc_target::spec::abi;
37 use rustc_trait_selection::infer::InferCtxtExt;
38 use rustc_trait_selection::traits::error_reporting::suggestions::NextTypeParamName;
39 use rustc_trait_selection::traits::ObligationCtxt;
40 use std::iter;
41
42 mod generics_of;
43 mod item_bounds;
44 mod lifetimes;
45 mod predicates_of;
46 mod type_of;
47
48 ///////////////////////////////////////////////////////////////////////////
49 // Main entry point
50
51 fn collect_mod_item_types(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
52     tcx.hir().visit_item_likes_in_module(module_def_id, &mut CollectItemTypesVisitor { tcx });
53 }
54
55 pub fn provide(providers: &mut Providers) {
56     lifetimes::provide(providers);
57     *providers = Providers {
58         opt_const_param_of: type_of::opt_const_param_of,
59         type_of: type_of::type_of,
60         item_bounds: item_bounds::item_bounds,
61         explicit_item_bounds: item_bounds::explicit_item_bounds,
62         generics_of: generics_of::generics_of,
63         predicates_of: predicates_of::predicates_of,
64         predicates_defined_on,
65         explicit_predicates_of: predicates_of::explicit_predicates_of,
66         super_predicates_of: predicates_of::super_predicates_of,
67         super_predicates_that_define_assoc_type:
68             predicates_of::super_predicates_that_define_assoc_type,
69         trait_explicit_predicates_and_bounds: predicates_of::trait_explicit_predicates_and_bounds,
70         type_param_predicates: predicates_of::type_param_predicates,
71         trait_def,
72         adt_def,
73         fn_sig,
74         impl_trait_ref,
75         impl_polarity,
76         is_foreign_item,
77         generator_kind,
78         collect_mod_item_types,
79         is_type_alias_impl_trait,
80         ..*providers
81     };
82 }
83
84 ///////////////////////////////////////////////////////////////////////////
85
86 /// Context specific to some particular item. This is what implements
87 /// [`AstConv`].
88 ///
89 /// # `ItemCtxt` vs `FnCtxt`
90 ///
91 /// `ItemCtxt` is primarily used to type-check item signatures and lower them
92 /// from HIR to their [`ty::Ty`] representation, which is exposed using [`AstConv`].
93 /// It's also used for the bodies of items like structs where the body (the fields)
94 /// are just signatures.
95 ///
96 /// This is in contrast to `FnCtxt`, which is used to type-check bodies of
97 /// functions, closures, and `const`s -- anywhere that expressions and statements show up.
98 ///
99 /// An important thing to note is that `ItemCtxt` does no inference -- it has no [`InferCtxt`] --
100 /// while `FnCtxt` does do inference.
101 ///
102 /// [`InferCtxt`]: rustc_infer::infer::InferCtxt
103 ///
104 /// # Trait predicates
105 ///
106 /// `ItemCtxt` has information about the predicates that are defined
107 /// on the trait. Unfortunately, this predicate information is
108 /// available in various different forms at various points in the
109 /// process. So we can't just store a pointer to e.g., the AST or the
110 /// parsed ty form, we have to be more flexible. To this end, the
111 /// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy
112 /// `get_type_parameter_bounds` requests, drawing the information from
113 /// the AST (`hir::Generics`), recursively.
114 pub struct ItemCtxt<'tcx> {
115     tcx: TyCtxt<'tcx>,
116     item_def_id: DefId,
117 }
118
119 ///////////////////////////////////////////////////////////////////////////
120
121 #[derive(Default)]
122 pub(crate) struct HirPlaceholderCollector(pub(crate) Vec<Span>);
123
124 impl<'v> Visitor<'v> for HirPlaceholderCollector {
125     fn visit_ty(&mut self, t: &'v hir::Ty<'v>) {
126         if let hir::TyKind::Infer = t.kind {
127             self.0.push(t.span);
128         }
129         intravisit::walk_ty(self, t)
130     }
131     fn visit_generic_arg(&mut self, generic_arg: &'v hir::GenericArg<'v>) {
132         match generic_arg {
133             hir::GenericArg::Infer(inf) => {
134                 self.0.push(inf.span);
135                 intravisit::walk_inf(self, inf);
136             }
137             hir::GenericArg::Type(t) => self.visit_ty(t),
138             _ => {}
139         }
140     }
141     fn visit_array_length(&mut self, length: &'v hir::ArrayLen) {
142         if let &hir::ArrayLen::Infer(_, span) = length {
143             self.0.push(span);
144         }
145         intravisit::walk_array_len(self, length)
146     }
147 }
148
149 struct CollectItemTypesVisitor<'tcx> {
150     tcx: TyCtxt<'tcx>,
151 }
152
153 /// If there are any placeholder types (`_`), emit an error explaining that this is not allowed
154 /// and suggest adding type parameters in the appropriate place, taking into consideration any and
155 /// all already existing generic type parameters to avoid suggesting a name that is already in use.
156 pub(crate) fn placeholder_type_error<'tcx>(
157     tcx: TyCtxt<'tcx>,
158     generics: Option<&hir::Generics<'_>>,
159     placeholder_types: Vec<Span>,
160     suggest: bool,
161     hir_ty: Option<&hir::Ty<'_>>,
162     kind: &'static str,
163 ) {
164     if placeholder_types.is_empty() {
165         return;
166     }
167
168     placeholder_type_error_diag(tcx, generics, placeholder_types, vec![], suggest, hir_ty, kind)
169         .emit();
170 }
171
172 pub(crate) fn placeholder_type_error_diag<'tcx>(
173     tcx: TyCtxt<'tcx>,
174     generics: Option<&hir::Generics<'_>>,
175     placeholder_types: Vec<Span>,
176     additional_spans: Vec<Span>,
177     suggest: bool,
178     hir_ty: Option<&hir::Ty<'_>>,
179     kind: &'static str,
180 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
181     if placeholder_types.is_empty() {
182         return bad_placeholder(tcx, additional_spans, kind);
183     }
184
185     let params = generics.map(|g| g.params).unwrap_or_default();
186     let type_name = params.next_type_param_name(None);
187     let mut sugg: Vec<_> =
188         placeholder_types.iter().map(|sp| (*sp, (*type_name).to_string())).collect();
189
190     if let Some(generics) = generics {
191         if let Some(arg) = params.iter().find(|arg| {
192             matches!(arg.name, hir::ParamName::Plain(Ident { name: kw::Underscore, .. }))
193         }) {
194             // Account for `_` already present in cases like `struct S<_>(_);` and suggest
195             // `struct S<T>(T);` instead of `struct S<_, T>(T);`.
196             sugg.push((arg.span, (*type_name).to_string()));
197         } else if let Some(span) = generics.span_for_param_suggestion() {
198             // Account for bounds, we want `fn foo<T: E, K>(_: K)` not `fn foo<T, K: E>(_: K)`.
199             sugg.push((span, format!(", {}", type_name)));
200         } else {
201             sugg.push((generics.span, format!("<{}>", type_name)));
202         }
203     }
204
205     let mut err =
206         bad_placeholder(tcx, placeholder_types.into_iter().chain(additional_spans).collect(), kind);
207
208     // Suggest, but only if it is not a function in const or static
209     if suggest {
210         let mut is_fn = false;
211         let mut is_const_or_static = false;
212
213         if let Some(hir_ty) = hir_ty && let hir::TyKind::BareFn(_) = hir_ty.kind {
214             is_fn = true;
215
216             // Check if parent is const or static
217             let parent_id = tcx.hir().parent_id(hir_ty.hir_id);
218             let parent_node = tcx.hir().get(parent_id);
219
220             is_const_or_static = matches!(
221                 parent_node,
222                 Node::Item(&hir::Item {
223                     kind: hir::ItemKind::Const(..) | hir::ItemKind::Static(..),
224                     ..
225                 }) | Node::TraitItem(&hir::TraitItem {
226                     kind: hir::TraitItemKind::Const(..),
227                     ..
228                 }) | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Const(..), .. })
229             );
230         }
231
232         // if function is wrapped around a const or static,
233         // then don't show the suggestion
234         if !(is_fn && is_const_or_static) {
235             err.multipart_suggestion(
236                 "use type parameters instead",
237                 sugg,
238                 Applicability::HasPlaceholders,
239             );
240         }
241     }
242
243     err
244 }
245
246 fn reject_placeholder_type_signatures_in_item<'tcx>(
247     tcx: TyCtxt<'tcx>,
248     item: &'tcx hir::Item<'tcx>,
249 ) {
250     let (generics, suggest) = match &item.kind {
251         hir::ItemKind::Union(_, generics)
252         | hir::ItemKind::Enum(_, generics)
253         | hir::ItemKind::TraitAlias(generics, _)
254         | hir::ItemKind::Trait(_, _, generics, ..)
255         | hir::ItemKind::Impl(hir::Impl { generics, .. })
256         | hir::ItemKind::Struct(_, generics) => (generics, true),
257         hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. })
258         | hir::ItemKind::TyAlias(_, generics) => (generics, false),
259         // `static`, `fn` and `const` are handled elsewhere to suggest appropriate type.
260         _ => return,
261     };
262
263     let mut visitor = HirPlaceholderCollector::default();
264     visitor.visit_item(item);
265
266     placeholder_type_error(tcx, Some(generics), visitor.0, suggest, None, item.kind.descr());
267 }
268
269 impl<'tcx> Visitor<'tcx> for CollectItemTypesVisitor<'tcx> {
270     type NestedFilter = nested_filter::OnlyBodies;
271
272     fn nested_visit_map(&mut self) -> Self::Map {
273         self.tcx.hir()
274     }
275
276     fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
277         convert_item(self.tcx, item.item_id());
278         reject_placeholder_type_signatures_in_item(self.tcx, item);
279         intravisit::walk_item(self, item);
280     }
281
282     fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
283         for param in generics.params {
284             match param.kind {
285                 hir::GenericParamKind::Lifetime { .. } => {}
286                 hir::GenericParamKind::Type { default: Some(_), .. } => {
287                     self.tcx.ensure().type_of(param.def_id);
288                 }
289                 hir::GenericParamKind::Type { .. } => {}
290                 hir::GenericParamKind::Const { default, .. } => {
291                     self.tcx.ensure().type_of(param.def_id);
292                     if let Some(default) = default {
293                         // need to store default and type of default
294                         self.tcx.ensure().type_of(default.def_id);
295                         self.tcx.ensure().const_param_default(param.def_id);
296                     }
297                 }
298             }
299         }
300         intravisit::walk_generics(self, generics);
301     }
302
303     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
304         if let hir::ExprKind::Closure(closure) = expr.kind {
305             self.tcx.ensure().generics_of(closure.def_id);
306             self.tcx.ensure().codegen_fn_attrs(closure.def_id);
307             // We do not call `type_of` for closures here as that
308             // depends on typecheck and would therefore hide
309             // any further errors in case one typeck fails.
310         }
311         intravisit::walk_expr(self, expr);
312     }
313
314     fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
315         convert_trait_item(self.tcx, trait_item.trait_item_id());
316         intravisit::walk_trait_item(self, trait_item);
317     }
318
319     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
320         convert_impl_item(self.tcx, impl_item.impl_item_id());
321         intravisit::walk_impl_item(self, impl_item);
322     }
323 }
324
325 ///////////////////////////////////////////////////////////////////////////
326 // Utility types and common code for the above passes.
327
328 fn bad_placeholder<'tcx>(
329     tcx: TyCtxt<'tcx>,
330     mut spans: Vec<Span>,
331     kind: &'static str,
332 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
333     let kind = if kind.ends_with('s') { format!("{}es", kind) } else { format!("{}s", kind) };
334
335     spans.sort();
336     let mut err = struct_span_err!(
337         tcx.sess,
338         spans.clone(),
339         E0121,
340         "the placeholder `_` is not allowed within types on item signatures for {}",
341         kind
342     );
343     for span in spans {
344         err.span_label(span, "not allowed in type signatures");
345     }
346     err
347 }
348
349 impl<'tcx> ItemCtxt<'tcx> {
350     pub fn new(tcx: TyCtxt<'tcx>, item_def_id: DefId) -> ItemCtxt<'tcx> {
351         ItemCtxt { tcx, item_def_id }
352     }
353
354     pub fn to_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
355         self.astconv().ast_ty_to_ty(ast_ty)
356     }
357
358     pub fn hir_id(&self) -> hir::HirId {
359         self.tcx.hir().local_def_id_to_hir_id(self.item_def_id.expect_local())
360     }
361
362     pub fn node(&self) -> hir::Node<'tcx> {
363         self.tcx.hir().get(self.hir_id())
364     }
365 }
366
367 impl<'tcx> AstConv<'tcx> for ItemCtxt<'tcx> {
368     fn tcx(&self) -> TyCtxt<'tcx> {
369         self.tcx
370     }
371
372     fn item_def_id(&self) -> DefId {
373         self.item_def_id
374     }
375
376     fn get_type_parameter_bounds(
377         &self,
378         span: Span,
379         def_id: DefId,
380         assoc_name: Ident,
381     ) -> ty::GenericPredicates<'tcx> {
382         self.tcx.at(span).type_param_predicates((
383             self.item_def_id,
384             def_id.expect_local(),
385             assoc_name,
386         ))
387     }
388
389     fn re_infer(&self, _: Option<&ty::GenericParamDef>, _: Span) -> Option<ty::Region<'tcx>> {
390         None
391     }
392
393     fn allow_ty_infer(&self) -> bool {
394         false
395     }
396
397     fn ty_infer(&self, _: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx> {
398         self.tcx().ty_error_with_message(span, "bad placeholder type")
399     }
400
401     fn ct_infer(&self, ty: Ty<'tcx>, _: Option<&ty::GenericParamDef>, span: Span) -> Const<'tcx> {
402         let ty = self.tcx.fold_regions(ty, |r, _| match *r {
403             ty::ReErased => self.tcx.lifetimes.re_static,
404             _ => r,
405         });
406         self.tcx().const_error_with_message(ty, span, "bad placeholder constant")
407     }
408
409     fn projected_ty_from_poly_trait_ref(
410         &self,
411         span: Span,
412         item_def_id: DefId,
413         item_segment: &hir::PathSegment<'_>,
414         poly_trait_ref: ty::PolyTraitRef<'tcx>,
415     ) -> Ty<'tcx> {
416         if let Some(trait_ref) = poly_trait_ref.no_bound_vars() {
417             let item_substs = self.astconv().create_substs_for_associated_item(
418                 span,
419                 item_def_id,
420                 item_segment,
421                 trait_ref.substs,
422             );
423             self.tcx().mk_projection(item_def_id, item_substs)
424         } else {
425             // There are no late-bound regions; we can just ignore the binder.
426             let mut err = struct_span_err!(
427                 self.tcx().sess,
428                 span,
429                 E0212,
430                 "cannot use the associated type of a trait \
431                  with uninferred generic parameters"
432             );
433
434             match self.node() {
435                 hir::Node::Field(_) | hir::Node::Ctor(_) | hir::Node::Variant(_) => {
436                     let item = self
437                         .tcx
438                         .hir()
439                         .expect_item(self.tcx.hir().get_parent_item(self.hir_id()).def_id);
440                     match &item.kind {
441                         hir::ItemKind::Enum(_, generics)
442                         | hir::ItemKind::Struct(_, generics)
443                         | hir::ItemKind::Union(_, generics) => {
444                             let lt_name = get_new_lifetime_name(self.tcx, poly_trait_ref, generics);
445                             let (lt_sp, sugg) = match generics.params {
446                                 [] => (generics.span, format!("<{}>", lt_name)),
447                                 [bound, ..] => {
448                                     (bound.span.shrink_to_lo(), format!("{}, ", lt_name))
449                                 }
450                             };
451                             let suggestions = vec![
452                                 (lt_sp, sugg),
453                                 (
454                                     span.with_hi(item_segment.ident.span.lo()),
455                                     format!(
456                                         "{}::",
457                                         // Replace the existing lifetimes with a new named lifetime.
458                                         self.tcx.replace_late_bound_regions_uncached(
459                                             poly_trait_ref,
460                                             |_| {
461                                                 self.tcx.mk_region(ty::ReEarlyBound(
462                                                     ty::EarlyBoundRegion {
463                                                         def_id: item_def_id,
464                                                         index: 0,
465                                                         name: Symbol::intern(&lt_name),
466                                                     },
467                                                 ))
468                                             }
469                                         ),
470                                     ),
471                                 ),
472                             ];
473                             err.multipart_suggestion(
474                                 "use a fully qualified path with explicit lifetimes",
475                                 suggestions,
476                                 Applicability::MaybeIncorrect,
477                             );
478                         }
479                         _ => {}
480                     }
481                 }
482                 hir::Node::Item(hir::Item {
483                     kind:
484                         hir::ItemKind::Struct(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Union(..),
485                     ..
486                 }) => {}
487                 hir::Node::Item(_)
488                 | hir::Node::ForeignItem(_)
489                 | hir::Node::TraitItem(_)
490                 | hir::Node::ImplItem(_) => {
491                     err.span_suggestion_verbose(
492                         span.with_hi(item_segment.ident.span.lo()),
493                         "use a fully qualified path with inferred lifetimes",
494                         format!(
495                             "{}::",
496                             // Erase named lt, we want `<A as B<'_>::C`, not `<A as B<'a>::C`.
497                             self.tcx.anonymize_bound_vars(poly_trait_ref).skip_binder(),
498                         ),
499                         Applicability::MaybeIncorrect,
500                     );
501                 }
502                 _ => {}
503             }
504             self.tcx().ty_error_with_guaranteed(err.emit())
505         }
506     }
507
508     fn probe_adt(&self, _span: Span, ty: Ty<'tcx>) -> Option<ty::AdtDef<'tcx>> {
509         // FIXME(#103640): Should we handle the case where `ty` is a projection?
510         ty.ty_adt_def()
511     }
512
513     fn set_tainted_by_errors(&self, _: ErrorGuaranteed) {
514         // There's no obvious place to track this, so just let it go.
515     }
516
517     fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) {
518         // There's no place to record types from signatures?
519     }
520 }
521
522 /// Synthesize a new lifetime name that doesn't clash with any of the lifetimes already present.
523 fn get_new_lifetime_name<'tcx>(
524     tcx: TyCtxt<'tcx>,
525     poly_trait_ref: ty::PolyTraitRef<'tcx>,
526     generics: &hir::Generics<'tcx>,
527 ) -> String {
528     let existing_lifetimes = tcx
529         .collect_referenced_late_bound_regions(&poly_trait_ref)
530         .into_iter()
531         .filter_map(|lt| {
532             if let ty::BoundRegionKind::BrNamed(_, name) = lt {
533                 Some(name.as_str().to_string())
534             } else {
535                 None
536             }
537         })
538         .chain(generics.params.iter().filter_map(|param| {
539             if let hir::GenericParamKind::Lifetime { .. } = &param.kind {
540                 Some(param.name.ident().as_str().to_string())
541             } else {
542                 None
543             }
544         }))
545         .collect::<FxHashSet<String>>();
546
547     let a_to_z_repeat_n = |n| {
548         (b'a'..=b'z').map(move |c| {
549             let mut s = '\''.to_string();
550             s.extend(std::iter::repeat(char::from(c)).take(n));
551             s
552         })
553     };
554
555     // If all single char lifetime names are present, we wrap around and double the chars.
556     (1..).flat_map(a_to_z_repeat_n).find(|lt| !existing_lifetimes.contains(lt.as_str())).unwrap()
557 }
558
559 fn convert_item(tcx: TyCtxt<'_>, item_id: hir::ItemId) {
560     let it = tcx.hir().item(item_id);
561     debug!("convert: item {} with id {}", it.ident, it.hir_id());
562     let def_id = item_id.owner_id.def_id;
563
564     match &it.kind {
565         // These don't define types.
566         hir::ItemKind::ExternCrate(_)
567         | hir::ItemKind::Use(..)
568         | hir::ItemKind::Macro(..)
569         | hir::ItemKind::Mod(_)
570         | hir::ItemKind::GlobalAsm(_) => {}
571         hir::ItemKind::ForeignMod { items, .. } => {
572             for item in *items {
573                 let item = tcx.hir().foreign_item(item.id);
574                 tcx.ensure().generics_of(item.owner_id);
575                 tcx.ensure().type_of(item.owner_id);
576                 tcx.ensure().predicates_of(item.owner_id);
577                 match item.kind {
578                     hir::ForeignItemKind::Fn(..) => {
579                         tcx.ensure().codegen_fn_attrs(item.owner_id);
580                         tcx.ensure().fn_sig(item.owner_id)
581                     }
582                     hir::ForeignItemKind::Static(..) => {
583                         tcx.ensure().codegen_fn_attrs(item.owner_id);
584                         let mut visitor = HirPlaceholderCollector::default();
585                         visitor.visit_foreign_item(item);
586                         placeholder_type_error(
587                             tcx,
588                             None,
589                             visitor.0,
590                             false,
591                             None,
592                             "static variable",
593                         );
594                     }
595                     _ => (),
596                 }
597             }
598         }
599         hir::ItemKind::Enum(..) => {
600             tcx.ensure().generics_of(def_id);
601             tcx.ensure().type_of(def_id);
602             tcx.ensure().predicates_of(def_id);
603             convert_enum_variant_types(tcx, def_id.to_def_id());
604         }
605         hir::ItemKind::Impl { .. } => {
606             tcx.ensure().generics_of(def_id);
607             tcx.ensure().type_of(def_id);
608             tcx.ensure().impl_trait_ref(def_id);
609             tcx.ensure().predicates_of(def_id);
610         }
611         hir::ItemKind::Trait(..) => {
612             tcx.ensure().generics_of(def_id);
613             tcx.ensure().trait_def(def_id);
614             tcx.at(it.span).super_predicates_of(def_id);
615             tcx.ensure().predicates_of(def_id);
616         }
617         hir::ItemKind::TraitAlias(..) => {
618             tcx.ensure().generics_of(def_id);
619             tcx.at(it.span).super_predicates_of(def_id);
620             tcx.ensure().predicates_of(def_id);
621         }
622         hir::ItemKind::Struct(struct_def, _) | hir::ItemKind::Union(struct_def, _) => {
623             tcx.ensure().generics_of(def_id);
624             tcx.ensure().type_of(def_id);
625             tcx.ensure().predicates_of(def_id);
626
627             for f in struct_def.fields() {
628                 tcx.ensure().generics_of(f.def_id);
629                 tcx.ensure().type_of(f.def_id);
630                 tcx.ensure().predicates_of(f.def_id);
631             }
632
633             if let Some(ctor_def_id) = struct_def.ctor_def_id() {
634                 convert_variant_ctor(tcx, ctor_def_id);
635             }
636         }
637
638         // Don't call `type_of` on opaque types, since that depends on type
639         // checking function bodies. `check_item_type` ensures that it's called
640         // instead.
641         hir::ItemKind::OpaqueTy(..) => {
642             tcx.ensure().generics_of(def_id);
643             tcx.ensure().predicates_of(def_id);
644             tcx.ensure().explicit_item_bounds(def_id);
645             tcx.ensure().item_bounds(def_id);
646         }
647
648         hir::ItemKind::TyAlias(..) => {
649             tcx.ensure().generics_of(def_id);
650             tcx.ensure().type_of(def_id);
651             tcx.ensure().predicates_of(def_id);
652         }
653
654         hir::ItemKind::Static(ty, ..) | hir::ItemKind::Const(ty, ..) => {
655             tcx.ensure().generics_of(def_id);
656             tcx.ensure().type_of(def_id);
657             tcx.ensure().predicates_of(def_id);
658             if !is_suggestable_infer_ty(ty) {
659                 let mut visitor = HirPlaceholderCollector::default();
660                 visitor.visit_item(it);
661                 placeholder_type_error(tcx, None, visitor.0, false, None, it.kind.descr());
662             }
663         }
664
665         hir::ItemKind::Fn(..) => {
666             tcx.ensure().generics_of(def_id);
667             tcx.ensure().type_of(def_id);
668             tcx.ensure().predicates_of(def_id);
669             tcx.ensure().fn_sig(def_id);
670             tcx.ensure().codegen_fn_attrs(def_id);
671         }
672     }
673 }
674
675 fn convert_trait_item(tcx: TyCtxt<'_>, trait_item_id: hir::TraitItemId) {
676     let trait_item = tcx.hir().trait_item(trait_item_id);
677     let def_id = trait_item_id.owner_id;
678     tcx.ensure().generics_of(def_id);
679
680     match trait_item.kind {
681         hir::TraitItemKind::Fn(..) => {
682             tcx.ensure().codegen_fn_attrs(def_id);
683             tcx.ensure().type_of(def_id);
684             tcx.ensure().fn_sig(def_id);
685         }
686
687         hir::TraitItemKind::Const(.., Some(_)) => {
688             tcx.ensure().type_of(def_id);
689         }
690
691         hir::TraitItemKind::Const(hir_ty, _) => {
692             tcx.ensure().type_of(def_id);
693             // Account for `const C: _;`.
694             let mut visitor = HirPlaceholderCollector::default();
695             visitor.visit_trait_item(trait_item);
696             if !tcx.sess.diagnostic().has_stashed_diagnostic(hir_ty.span, StashKey::ItemNoType) {
697                 placeholder_type_error(tcx, None, visitor.0, false, None, "constant");
698             }
699         }
700
701         hir::TraitItemKind::Type(_, Some(_)) => {
702             tcx.ensure().item_bounds(def_id);
703             tcx.ensure().type_of(def_id);
704             // Account for `type T = _;`.
705             let mut visitor = HirPlaceholderCollector::default();
706             visitor.visit_trait_item(trait_item);
707             placeholder_type_error(tcx, None, visitor.0, false, None, "associated type");
708         }
709
710         hir::TraitItemKind::Type(_, None) => {
711             tcx.ensure().item_bounds(def_id);
712             // #74612: Visit and try to find bad placeholders
713             // even if there is no concrete type.
714             let mut visitor = HirPlaceholderCollector::default();
715             visitor.visit_trait_item(trait_item);
716
717             placeholder_type_error(tcx, None, visitor.0, false, None, "associated type");
718         }
719     };
720
721     tcx.ensure().predicates_of(def_id);
722 }
723
724 fn convert_impl_item(tcx: TyCtxt<'_>, impl_item_id: hir::ImplItemId) {
725     let def_id = impl_item_id.owner_id;
726     tcx.ensure().generics_of(def_id);
727     tcx.ensure().type_of(def_id);
728     tcx.ensure().predicates_of(def_id);
729     let impl_item = tcx.hir().impl_item(impl_item_id);
730     match impl_item.kind {
731         hir::ImplItemKind::Fn(..) => {
732             tcx.ensure().codegen_fn_attrs(def_id);
733             tcx.ensure().fn_sig(def_id);
734         }
735         hir::ImplItemKind::Type(_) => {
736             // Account for `type T = _;`
737             let mut visitor = HirPlaceholderCollector::default();
738             visitor.visit_impl_item(impl_item);
739
740             placeholder_type_error(tcx, None, visitor.0, false, None, "associated type");
741         }
742         hir::ImplItemKind::Const(..) => {}
743     }
744 }
745
746 fn convert_variant_ctor(tcx: TyCtxt<'_>, def_id: LocalDefId) {
747     tcx.ensure().generics_of(def_id);
748     tcx.ensure().type_of(def_id);
749     tcx.ensure().predicates_of(def_id);
750 }
751
752 fn convert_enum_variant_types(tcx: TyCtxt<'_>, def_id: DefId) {
753     let def = tcx.adt_def(def_id);
754     let repr_type = def.repr().discr_type();
755     let initial = repr_type.initial_discriminant(tcx);
756     let mut prev_discr = None::<Discr<'_>>;
757
758     // fill the discriminant values and field types
759     for variant in def.variants() {
760         let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
761         prev_discr = Some(
762             if let ty::VariantDiscr::Explicit(const_def_id) = variant.discr {
763                 def.eval_explicit_discr(tcx, const_def_id)
764             } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) {
765                 Some(discr)
766             } else {
767                 let span = tcx.def_span(variant.def_id);
768                 struct_span_err!(tcx.sess, span, E0370, "enum discriminant overflowed")
769                     .span_label(span, format!("overflowed on value after {}", prev_discr.unwrap()))
770                     .note(&format!(
771                         "explicitly set `{} = {}` if that is desired outcome",
772                         tcx.item_name(variant.def_id),
773                         wrapped_discr
774                     ))
775                     .emit();
776                 None
777             }
778             .unwrap_or(wrapped_discr),
779         );
780
781         for f in &variant.fields {
782             tcx.ensure().generics_of(f.did);
783             tcx.ensure().type_of(f.did);
784             tcx.ensure().predicates_of(f.did);
785         }
786
787         // Convert the ctor, if any. This also registers the variant as
788         // an item.
789         if let Some(ctor_def_id) = variant.ctor_def_id() {
790             convert_variant_ctor(tcx, ctor_def_id.expect_local());
791         }
792     }
793 }
794
795 fn convert_variant(
796     tcx: TyCtxt<'_>,
797     variant_did: Option<LocalDefId>,
798     ident: Ident,
799     discr: ty::VariantDiscr,
800     def: &hir::VariantData<'_>,
801     adt_kind: ty::AdtKind,
802     parent_did: LocalDefId,
803 ) -> ty::VariantDef {
804     let mut seen_fields: FxHashMap<Ident, Span> = Default::default();
805     let fields = def
806         .fields()
807         .iter()
808         .map(|f| {
809             let dup_span = seen_fields.get(&f.ident.normalize_to_macros_2_0()).cloned();
810             if let Some(prev_span) = dup_span {
811                 tcx.sess.emit_err(errors::FieldAlreadyDeclared {
812                     field_name: f.ident,
813                     span: f.span,
814                     prev_span,
815                 });
816             } else {
817                 seen_fields.insert(f.ident.normalize_to_macros_2_0(), f.span);
818             }
819
820             ty::FieldDef {
821                 did: f.def_id.to_def_id(),
822                 name: f.ident.name,
823                 vis: tcx.visibility(f.def_id),
824             }
825         })
826         .collect();
827     let recovered = match def {
828         hir::VariantData::Struct(_, r) => *r,
829         _ => false,
830     };
831     ty::VariantDef::new(
832         ident.name,
833         variant_did.map(LocalDefId::to_def_id),
834         def.ctor().map(|(kind, _, def_id)| (kind, def_id.to_def_id())),
835         discr,
836         fields,
837         adt_kind,
838         parent_did.to_def_id(),
839         recovered,
840         adt_kind == AdtKind::Struct && tcx.has_attr(parent_did.to_def_id(), sym::non_exhaustive)
841             || variant_did.map_or(false, |variant_did| {
842                 tcx.has_attr(variant_did.to_def_id(), sym::non_exhaustive)
843             }),
844     )
845 }
846
847 fn adt_def(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AdtDef<'_> {
848     use rustc_hir::*;
849
850     let def_id = def_id.expect_local();
851     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
852     let Node::Item(item) = tcx.hir().get(hir_id) else {
853         bug!();
854     };
855
856     let repr = tcx.repr_options_of_def(def_id.to_def_id());
857     let (kind, variants) = match &item.kind {
858         ItemKind::Enum(def, _) => {
859             let mut distance_from_explicit = 0;
860             let variants = def
861                 .variants
862                 .iter()
863                 .map(|v| {
864                     let discr = if let Some(e) = &v.disr_expr {
865                         distance_from_explicit = 0;
866                         ty::VariantDiscr::Explicit(e.def_id.to_def_id())
867                     } else {
868                         ty::VariantDiscr::Relative(distance_from_explicit)
869                     };
870                     distance_from_explicit += 1;
871
872                     convert_variant(
873                         tcx,
874                         Some(v.def_id),
875                         v.ident,
876                         discr,
877                         &v.data,
878                         AdtKind::Enum,
879                         def_id,
880                     )
881                 })
882                 .collect();
883
884             (AdtKind::Enum, variants)
885         }
886         ItemKind::Struct(def, _) | ItemKind::Union(def, _) => {
887             let adt_kind = match item.kind {
888                 ItemKind::Struct(..) => AdtKind::Struct,
889                 _ => AdtKind::Union,
890             };
891             let variants = std::iter::once(convert_variant(
892                 tcx,
893                 None,
894                 item.ident,
895                 ty::VariantDiscr::Relative(0),
896                 def,
897                 adt_kind,
898                 def_id,
899             ))
900             .collect();
901
902             (adt_kind, variants)
903         }
904         _ => bug!(),
905     };
906     tcx.alloc_adt_def(def_id.to_def_id(), kind, variants, repr)
907 }
908
909 fn trait_def(tcx: TyCtxt<'_>, def_id: DefId) -> ty::TraitDef {
910     let item = tcx.hir().expect_item(def_id.expect_local());
911
912     let (is_auto, unsafety, items) = match item.kind {
913         hir::ItemKind::Trait(is_auto, unsafety, .., items) => {
914             (is_auto == hir::IsAuto::Yes, unsafety, items)
915         }
916         hir::ItemKind::TraitAlias(..) => (false, hir::Unsafety::Normal, &[][..]),
917         _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
918     };
919
920     let paren_sugar = tcx.has_attr(def_id, sym::rustc_paren_sugar);
921     if paren_sugar && !tcx.features().unboxed_closures {
922         tcx.sess
923             .struct_span_err(
924                 item.span,
925                 "the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \
926                  which traits can use parenthetical notation",
927             )
928             .help("add `#![feature(unboxed_closures)]` to the crate attributes to use it")
929             .emit();
930     }
931
932     let is_marker = tcx.has_attr(def_id, sym::marker);
933     let skip_array_during_method_dispatch =
934         tcx.has_attr(def_id, sym::rustc_skip_array_during_method_dispatch);
935     let spec_kind = if tcx.has_attr(def_id, sym::rustc_unsafe_specialization_marker) {
936         ty::trait_def::TraitSpecializationKind::Marker
937     } else if tcx.has_attr(def_id, sym::rustc_specialization_trait) {
938         ty::trait_def::TraitSpecializationKind::AlwaysApplicable
939     } else {
940         ty::trait_def::TraitSpecializationKind::None
941     };
942     let must_implement_one_of = tcx
943         .get_attr(def_id, sym::rustc_must_implement_one_of)
944         // Check that there are at least 2 arguments of `#[rustc_must_implement_one_of]`
945         // and that they are all identifiers
946         .and_then(|attr| match attr.meta_item_list() {
947             Some(items) if items.len() < 2 => {
948                 tcx.sess
949                     .struct_span_err(
950                         attr.span,
951                         "the `#[rustc_must_implement_one_of]` attribute must be \
952                          used with at least 2 args",
953                     )
954                     .emit();
955
956                 None
957             }
958             Some(items) => items
959                 .into_iter()
960                 .map(|item| item.ident().ok_or(item.span()))
961                 .collect::<Result<Box<[_]>, _>>()
962                 .map_err(|span| {
963                     tcx.sess
964                         .struct_span_err(span, "must be a name of an associated function")
965                         .emit();
966                 })
967                 .ok()
968                 .zip(Some(attr.span)),
969             // Error is reported by `rustc_attr!`
970             None => None,
971         })
972         // Check that all arguments of `#[rustc_must_implement_one_of]` reference
973         // functions in the trait with default implementations
974         .and_then(|(list, attr_span)| {
975             let errors = list.iter().filter_map(|ident| {
976                 let item = items.iter().find(|item| item.ident == *ident);
977
978                 match item {
979                     Some(item) if matches!(item.kind, hir::AssocItemKind::Fn { .. }) => {
980                         if !tcx.impl_defaultness(item.id.owner_id).has_value() {
981                             tcx.sess
982                                 .struct_span_err(
983                                     item.span,
984                                     "function doesn't have a default implementation",
985                                 )
986                                 .span_note(attr_span, "required by this annotation")
987                                 .emit();
988
989                             return Some(());
990                         }
991
992                         return None;
993                     }
994                     Some(item) => {
995                         tcx.sess
996                             .struct_span_err(item.span, "not a function")
997                             .span_note(attr_span, "required by this annotation")
998                             .note(
999                                 "all `#[rustc_must_implement_one_of]` arguments must be associated \
1000                                  function names",
1001                             )
1002                             .emit();
1003                     }
1004                     None => {
1005                         tcx.sess
1006                             .struct_span_err(ident.span, "function not found in this trait")
1007                             .emit();
1008                     }
1009                 }
1010
1011                 Some(())
1012             });
1013
1014             (errors.count() == 0).then_some(list)
1015         })
1016         // Check for duplicates
1017         .and_then(|list| {
1018             let mut set: FxHashMap<Symbol, Span> = FxHashMap::default();
1019             let mut no_dups = true;
1020
1021             for ident in &*list {
1022                 if let Some(dup) = set.insert(ident.name, ident.span) {
1023                     tcx.sess
1024                         .struct_span_err(vec![dup, ident.span], "functions names are duplicated")
1025                         .note("all `#[rustc_must_implement_one_of]` arguments must be unique")
1026                         .emit();
1027
1028                     no_dups = false;
1029                 }
1030             }
1031
1032             no_dups.then_some(list)
1033         });
1034
1035     ty::TraitDef::new(
1036         def_id,
1037         unsafety,
1038         paren_sugar,
1039         is_auto,
1040         is_marker,
1041         skip_array_during_method_dispatch,
1042         spec_kind,
1043         must_implement_one_of,
1044     )
1045 }
1046
1047 fn are_suggestable_generic_args(generic_args: &[hir::GenericArg<'_>]) -> bool {
1048     generic_args.iter().any(|arg| match arg {
1049         hir::GenericArg::Type(ty) => is_suggestable_infer_ty(ty),
1050         hir::GenericArg::Infer(_) => true,
1051         _ => false,
1052     })
1053 }
1054
1055 /// Whether `ty` is a type with `_` placeholders that can be inferred. Used in diagnostics only to
1056 /// use inference to provide suggestions for the appropriate type if possible.
1057 fn is_suggestable_infer_ty(ty: &hir::Ty<'_>) -> bool {
1058     debug!(?ty);
1059     use hir::TyKind::*;
1060     match &ty.kind {
1061         Infer => true,
1062         Slice(ty) => is_suggestable_infer_ty(ty),
1063         Array(ty, length) => {
1064             is_suggestable_infer_ty(ty) || matches!(length, hir::ArrayLen::Infer(_, _))
1065         }
1066         Tup(tys) => tys.iter().any(is_suggestable_infer_ty),
1067         Ptr(mut_ty) | Ref(_, mut_ty) => is_suggestable_infer_ty(mut_ty.ty),
1068         OpaqueDef(_, generic_args, _) => are_suggestable_generic_args(generic_args),
1069         Path(hir::QPath::TypeRelative(ty, segment)) => {
1070             is_suggestable_infer_ty(ty) || are_suggestable_generic_args(segment.args().args)
1071         }
1072         Path(hir::QPath::Resolved(ty_opt, hir::Path { segments, .. })) => {
1073             ty_opt.map_or(false, is_suggestable_infer_ty)
1074                 || segments.iter().any(|segment| are_suggestable_generic_args(segment.args().args))
1075         }
1076         _ => false,
1077     }
1078 }
1079
1080 pub fn get_infer_ret_ty<'hir>(output: &'hir hir::FnRetTy<'hir>) -> Option<&'hir hir::Ty<'hir>> {
1081     if let hir::FnRetTy::Return(ty) = output {
1082         if is_suggestable_infer_ty(ty) {
1083             return Some(&*ty);
1084         }
1085     }
1086     None
1087 }
1088
1089 #[instrument(level = "debug", skip(tcx))]
1090 fn fn_sig(tcx: TyCtxt<'_>, def_id: DefId) -> ty::PolyFnSig<'_> {
1091     use rustc_hir::Node::*;
1092     use rustc_hir::*;
1093
1094     let def_id = def_id.expect_local();
1095     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
1096
1097     let icx = ItemCtxt::new(tcx, def_id.to_def_id());
1098
1099     match tcx.hir().get(hir_id) {
1100         TraitItem(hir::TraitItem {
1101             kind: TraitItemKind::Fn(sig, TraitFn::Provided(_)),
1102             generics,
1103             ..
1104         })
1105         | Item(hir::Item { kind: ItemKind::Fn(sig, generics, _), .. }) => {
1106             infer_return_ty_for_fn_sig(tcx, sig, generics, def_id, &icx)
1107         }
1108
1109         ImplItem(hir::ImplItem { kind: ImplItemKind::Fn(sig, _), generics, .. }) => {
1110             // Do not try to infer the return type for a impl method coming from a trait
1111             if let Item(hir::Item { kind: ItemKind::Impl(i), .. }) =
1112                 tcx.hir().get_parent(hir_id)
1113                 && i.of_trait.is_some()
1114             {
1115                 icx.astconv().ty_of_fn(
1116                     hir_id,
1117                     sig.header.unsafety,
1118                     sig.header.abi,
1119                     sig.decl,
1120                     Some(generics),
1121                     None,
1122                 )
1123             } else {
1124                 infer_return_ty_for_fn_sig(tcx, sig, generics, def_id, &icx)
1125             }
1126         }
1127
1128         TraitItem(hir::TraitItem {
1129             kind: TraitItemKind::Fn(FnSig { header, decl, span: _ }, _),
1130             generics,
1131             ..
1132         }) => {
1133             icx.astconv().ty_of_fn(hir_id, header.unsafety, header.abi, decl, Some(generics), None)
1134         }
1135
1136         ForeignItem(&hir::ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
1137             let abi = tcx.hir().get_foreign_abi(hir_id);
1138             compute_sig_of_foreign_fn_decl(tcx, def_id.to_def_id(), fn_decl, abi)
1139         }
1140
1141         Ctor(data) | Variant(hir::Variant { data, .. }) if data.ctor().is_some() => {
1142             let ty = tcx.type_of(tcx.hir().get_parent_item(hir_id));
1143             let inputs = data.fields().iter().map(|f| tcx.type_of(f.def_id));
1144             ty::Binder::dummy(tcx.mk_fn_sig(
1145                 inputs,
1146                 ty,
1147                 false,
1148                 hir::Unsafety::Normal,
1149                 abi::Abi::Rust,
1150             ))
1151         }
1152
1153         Expr(&hir::Expr { kind: hir::ExprKind::Closure { .. }, .. }) => {
1154             // Closure signatures are not like other function
1155             // signatures and cannot be accessed through `fn_sig`. For
1156             // example, a closure signature excludes the `self`
1157             // argument. In any case they are embedded within the
1158             // closure type as part of the `ClosureSubsts`.
1159             //
1160             // To get the signature of a closure, you should use the
1161             // `sig` method on the `ClosureSubsts`:
1162             //
1163             //    substs.as_closure().sig(def_id, tcx)
1164             bug!(
1165                 "to get the signature of a closure, use `substs.as_closure().sig()` not `fn_sig()`",
1166             );
1167         }
1168
1169         x => {
1170             bug!("unexpected sort of node in fn_sig(): {:?}", x);
1171         }
1172     }
1173 }
1174
1175 fn infer_return_ty_for_fn_sig<'tcx>(
1176     tcx: TyCtxt<'tcx>,
1177     sig: &hir::FnSig<'_>,
1178     generics: &hir::Generics<'_>,
1179     def_id: LocalDefId,
1180     icx: &ItemCtxt<'tcx>,
1181 ) -> ty::PolyFnSig<'tcx> {
1182     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
1183
1184     match get_infer_ret_ty(&sig.decl.output) {
1185         Some(ty) => {
1186             let fn_sig = tcx.typeck(def_id).liberated_fn_sigs()[hir_id];
1187             // Typeck doesn't expect erased regions to be returned from `type_of`.
1188             let fn_sig = tcx.fold_regions(fn_sig, |r, _| match *r {
1189                 ty::ReErased => tcx.lifetimes.re_static,
1190                 _ => r,
1191             });
1192
1193             let mut visitor = HirPlaceholderCollector::default();
1194             visitor.visit_ty(ty);
1195             let mut diag = bad_placeholder(tcx, visitor.0, "return type");
1196             let ret_ty = fn_sig.output();
1197             if ret_ty.is_suggestable(tcx, false) {
1198                 diag.span_suggestion(
1199                     ty.span,
1200                     "replace with the correct return type",
1201                     ret_ty,
1202                     Applicability::MachineApplicable,
1203                 );
1204             } else if matches!(ret_ty.kind(), ty::FnDef(..)) {
1205                 let fn_sig = ret_ty.fn_sig(tcx);
1206                 if fn_sig
1207                     .skip_binder()
1208                     .inputs_and_output
1209                     .iter()
1210                     .all(|t| t.is_suggestable(tcx, false))
1211                 {
1212                     diag.span_suggestion(
1213                         ty.span,
1214                         "replace with the correct return type",
1215                         fn_sig,
1216                         Applicability::MachineApplicable,
1217                     );
1218                 }
1219             } else if let Some(sugg) = suggest_impl_trait(tcx, ret_ty, ty.span, hir_id, def_id) {
1220                 diag.span_suggestion(
1221                     ty.span,
1222                     "replace with an appropriate return type",
1223                     sugg,
1224                     Applicability::MachineApplicable,
1225                 );
1226             } else if ret_ty.is_closure() {
1227                 diag.help("consider using an `Fn`, `FnMut`, or `FnOnce` trait bound");
1228             }
1229             // Also note how `Fn` traits work just in case!
1230             if ret_ty.is_closure() {
1231                 diag.note(
1232                     "for more information on `Fn` traits and closure types, see \
1233                      https://doc.rust-lang.org/book/ch13-01-closures.html",
1234                 );
1235             }
1236             diag.emit();
1237
1238             ty::Binder::dummy(fn_sig)
1239         }
1240         None => icx.astconv().ty_of_fn(
1241             hir_id,
1242             sig.header.unsafety,
1243             sig.header.abi,
1244             sig.decl,
1245             Some(generics),
1246             None,
1247         ),
1248     }
1249 }
1250
1251 // FIXME(vincenzopalazzo): remove the hir item when the refactoring is stable
1252 fn suggest_impl_trait<'tcx>(
1253     tcx: TyCtxt<'tcx>,
1254     ret_ty: Ty<'tcx>,
1255     span: Span,
1256     _hir_id: hir::HirId,
1257     def_id: LocalDefId,
1258 ) -> Option<String> {
1259     let format_as_assoc: fn(_, _, _, _, _) -> _ =
1260         |tcx: TyCtxt<'tcx>,
1261          _: ty::SubstsRef<'tcx>,
1262          trait_def_id: DefId,
1263          assoc_item_def_id: DefId,
1264          item_ty: Ty<'tcx>| {
1265             let trait_name = tcx.item_name(trait_def_id);
1266             let assoc_name = tcx.item_name(assoc_item_def_id);
1267             Some(format!("impl {trait_name}<{assoc_name} = {item_ty}>"))
1268         };
1269     let format_as_parenthesized: fn(_, _, _, _, _) -> _ =
1270         |tcx: TyCtxt<'tcx>,
1271          substs: ty::SubstsRef<'tcx>,
1272          trait_def_id: DefId,
1273          _: DefId,
1274          item_ty: Ty<'tcx>| {
1275             let trait_name = tcx.item_name(trait_def_id);
1276             let args_tuple = substs.type_at(1);
1277             let ty::Tuple(types) = *args_tuple.kind() else { return None; };
1278             if !types.is_suggestable(tcx, false) {
1279                 return None;
1280             }
1281             let maybe_ret =
1282                 if item_ty.is_unit() { String::new() } else { format!(" -> {item_ty}") };
1283             Some(format!(
1284                 "impl {trait_name}({}){maybe_ret}",
1285                 types.iter().map(|ty| ty.to_string()).collect::<Vec<_>>().join(", ")
1286             ))
1287         };
1288
1289     for (trait_def_id, assoc_item_def_id, formatter) in [
1290         (
1291             tcx.get_diagnostic_item(sym::Iterator),
1292             tcx.get_diagnostic_item(sym::IteratorItem),
1293             format_as_assoc,
1294         ),
1295         (
1296             tcx.lang_items().future_trait(),
1297             tcx.get_diagnostic_item(sym::FutureOutput),
1298             format_as_assoc,
1299         ),
1300         (tcx.lang_items().fn_trait(), tcx.lang_items().fn_once_output(), format_as_parenthesized),
1301         (
1302             tcx.lang_items().fn_mut_trait(),
1303             tcx.lang_items().fn_once_output(),
1304             format_as_parenthesized,
1305         ),
1306         (
1307             tcx.lang_items().fn_once_trait(),
1308             tcx.lang_items().fn_once_output(),
1309             format_as_parenthesized,
1310         ),
1311     ] {
1312         let Some(trait_def_id) = trait_def_id else { continue; };
1313         let Some(assoc_item_def_id) = assoc_item_def_id else { continue; };
1314         if tcx.def_kind(assoc_item_def_id) != DefKind::AssocTy {
1315             continue;
1316         }
1317         let param_env = tcx.param_env(def_id);
1318         let infcx = tcx.infer_ctxt().build();
1319         let substs = ty::InternalSubsts::for_item(tcx, trait_def_id, |param, _| {
1320             if param.index == 0 { ret_ty.into() } else { infcx.var_for_def(span, param) }
1321         });
1322         if !infcx.type_implements_trait(trait_def_id, substs, param_env).must_apply_modulo_regions()
1323         {
1324             continue;
1325         }
1326         let ocx = ObligationCtxt::new_in_snapshot(&infcx);
1327         let item_ty = ocx.normalize(
1328             &ObligationCause::misc(span, def_id),
1329             param_env,
1330             tcx.mk_projection(assoc_item_def_id, substs),
1331         );
1332         // FIXME(compiler-errors): We may benefit from resolving regions here.
1333         if ocx.select_where_possible().is_empty()
1334             && let item_ty = infcx.resolve_vars_if_possible(item_ty)
1335             && item_ty.is_suggestable(tcx, false)
1336             && let Some(sugg) = formatter(tcx, infcx.resolve_vars_if_possible(substs), trait_def_id, assoc_item_def_id, item_ty)
1337         {
1338             return Some(sugg);
1339         }
1340     }
1341     None
1342 }
1343
1344 fn impl_trait_ref(tcx: TyCtxt<'_>, def_id: DefId) -> Option<ty::EarlyBinder<ty::TraitRef<'_>>> {
1345     let icx = ItemCtxt::new(tcx, def_id);
1346     let item = tcx.hir().expect_item(def_id.expect_local());
1347     let hir::ItemKind::Impl(impl_) = item.kind else { bug!() };
1348     impl_
1349         .of_trait
1350         .as_ref()
1351         .map(|ast_trait_ref| {
1352             let selfty = tcx.type_of(def_id);
1353             icx.astconv().instantiate_mono_trait_ref(
1354                 ast_trait_ref,
1355                 selfty,
1356                 check_impl_constness(tcx, impl_.constness, ast_trait_ref),
1357             )
1358         })
1359         .map(ty::EarlyBinder)
1360 }
1361
1362 fn check_impl_constness(
1363     tcx: TyCtxt<'_>,
1364     constness: hir::Constness,
1365     ast_trait_ref: &hir::TraitRef<'_>,
1366 ) -> ty::BoundConstness {
1367     match constness {
1368         hir::Constness::Const => {
1369             if let Some(trait_def_id) = ast_trait_ref.trait_def_id() && !tcx.has_attr(trait_def_id, sym::const_trait) {
1370                 let trait_name = tcx.item_name(trait_def_id).to_string();
1371                 tcx.sess.emit_err(errors::ConstImplForNonConstTrait {
1372                     trait_ref_span: ast_trait_ref.path.span,
1373                     trait_name,
1374                     local_trait_span: trait_def_id.as_local().map(|_| tcx.def_span(trait_def_id).shrink_to_lo()),
1375                     marking: (),
1376                     adding: (),
1377                 });
1378                 ty::BoundConstness::NotConst
1379             } else {
1380                 ty::BoundConstness::ConstIfConst
1381             }
1382         },
1383         hir::Constness::NotConst => ty::BoundConstness::NotConst,
1384     }
1385 }
1386
1387 fn impl_polarity(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ImplPolarity {
1388     let is_rustc_reservation = tcx.has_attr(def_id, sym::rustc_reservation_impl);
1389     let item = tcx.hir().expect_item(def_id.expect_local());
1390     match &item.kind {
1391         hir::ItemKind::Impl(hir::Impl {
1392             polarity: hir::ImplPolarity::Negative(span),
1393             of_trait,
1394             ..
1395         }) => {
1396             if is_rustc_reservation {
1397                 let span = span.to(of_trait.as_ref().map_or(*span, |t| t.path.span));
1398                 tcx.sess.span_err(span, "reservation impls can't be negative");
1399             }
1400             ty::ImplPolarity::Negative
1401         }
1402         hir::ItemKind::Impl(hir::Impl {
1403             polarity: hir::ImplPolarity::Positive,
1404             of_trait: None,
1405             ..
1406         }) => {
1407             if is_rustc_reservation {
1408                 tcx.sess.span_err(item.span, "reservation impls can't be inherent");
1409             }
1410             ty::ImplPolarity::Positive
1411         }
1412         hir::ItemKind::Impl(hir::Impl {
1413             polarity: hir::ImplPolarity::Positive,
1414             of_trait: Some(_),
1415             ..
1416         }) => {
1417             if is_rustc_reservation {
1418                 ty::ImplPolarity::Reservation
1419             } else {
1420                 ty::ImplPolarity::Positive
1421             }
1422         }
1423         item => bug!("impl_polarity: {:?} not an impl", item),
1424     }
1425 }
1426
1427 /// Returns the early-bound lifetimes declared in this generics
1428 /// listing. For anything other than fns/methods, this is just all
1429 /// the lifetimes that are declared. For fns or methods, we have to
1430 /// screen out those that do not appear in any where-clauses etc using
1431 /// `resolve_lifetime::early_bound_lifetimes`.
1432 fn early_bound_lifetimes_from_generics<'a, 'tcx: 'a>(
1433     tcx: TyCtxt<'tcx>,
1434     generics: &'a hir::Generics<'a>,
1435 ) -> impl Iterator<Item = &'a hir::GenericParam<'a>> + Captures<'tcx> {
1436     generics.params.iter().filter(move |param| match param.kind {
1437         GenericParamKind::Lifetime { .. } => !tcx.is_late_bound(param.hir_id),
1438         _ => false,
1439     })
1440 }
1441
1442 /// Returns a list of type predicates for the definition with ID `def_id`, including inferred
1443 /// lifetime constraints. This includes all predicates returned by `explicit_predicates_of`, plus
1444 /// inferred constraints concerning which regions outlive other regions.
1445 #[instrument(level = "debug", skip(tcx))]
1446 fn predicates_defined_on(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1447     let mut result = tcx.explicit_predicates_of(def_id);
1448     debug!("predicates_defined_on: explicit_predicates_of({:?}) = {:?}", def_id, result,);
1449     let inferred_outlives = tcx.inferred_outlives_of(def_id);
1450     if !inferred_outlives.is_empty() {
1451         debug!(
1452             "predicates_defined_on: inferred_outlives_of({:?}) = {:?}",
1453             def_id, inferred_outlives,
1454         );
1455         let inferred_outlives_iter =
1456             inferred_outlives.iter().map(|(clause, span)| ((*clause).to_predicate(tcx), *span));
1457         if result.predicates.is_empty() {
1458             result.predicates = tcx.arena.alloc_from_iter(inferred_outlives_iter);
1459         } else {
1460             result.predicates = tcx.arena.alloc_from_iter(
1461                 result.predicates.into_iter().copied().chain(inferred_outlives_iter),
1462             );
1463         }
1464     }
1465
1466     debug!("predicates_defined_on({:?}) = {:?}", def_id, result);
1467     result
1468 }
1469
1470 fn compute_sig_of_foreign_fn_decl<'tcx>(
1471     tcx: TyCtxt<'tcx>,
1472     def_id: DefId,
1473     decl: &'tcx hir::FnDecl<'tcx>,
1474     abi: abi::Abi,
1475 ) -> ty::PolyFnSig<'tcx> {
1476     let unsafety = if abi == abi::Abi::RustIntrinsic {
1477         intrinsic_operation_unsafety(tcx, def_id)
1478     } else {
1479         hir::Unsafety::Unsafe
1480     };
1481     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1482     let fty =
1483         ItemCtxt::new(tcx, def_id).astconv().ty_of_fn(hir_id, unsafety, abi, decl, None, None);
1484
1485     // Feature gate SIMD types in FFI, since I am not sure that the
1486     // ABIs are handled at all correctly. -huonw
1487     if abi != abi::Abi::RustIntrinsic
1488         && abi != abi::Abi::PlatformIntrinsic
1489         && !tcx.features().simd_ffi
1490     {
1491         let check = |ast_ty: &hir::Ty<'_>, ty: Ty<'_>| {
1492             if ty.is_simd() {
1493                 let snip = tcx
1494                     .sess
1495                     .source_map()
1496                     .span_to_snippet(ast_ty.span)
1497                     .map_or_else(|_| String::new(), |s| format!(" `{}`", s));
1498                 tcx.sess
1499                     .struct_span_err(
1500                         ast_ty.span,
1501                         &format!(
1502                             "use of SIMD type{} in FFI is highly experimental and \
1503                              may result in invalid code",
1504                             snip
1505                         ),
1506                     )
1507                     .help("add `#![feature(simd_ffi)]` to the crate attributes to enable")
1508                     .emit();
1509             }
1510         };
1511         for (input, ty) in iter::zip(decl.inputs, fty.inputs().skip_binder()) {
1512             check(input, *ty)
1513         }
1514         if let hir::FnRetTy::Return(ty) = decl.output {
1515             check(ty, fty.output().skip_binder())
1516         }
1517     }
1518
1519     fty
1520 }
1521
1522 fn is_foreign_item(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1523     match tcx.hir().get_if_local(def_id) {
1524         Some(Node::ForeignItem(..)) => true,
1525         Some(_) => false,
1526         _ => bug!("is_foreign_item applied to non-local def-id {:?}", def_id),
1527     }
1528 }
1529
1530 fn generator_kind(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::GeneratorKind> {
1531     match tcx.hir().get_if_local(def_id) {
1532         Some(Node::Expr(&rustc_hir::Expr {
1533             kind: rustc_hir::ExprKind::Closure(&rustc_hir::Closure { body, .. }),
1534             ..
1535         })) => tcx.hir().body(body).generator_kind(),
1536         Some(_) => None,
1537         _ => bug!("generator_kind applied to non-local def-id {:?}", def_id),
1538     }
1539 }
1540
1541 fn is_type_alias_impl_trait<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> bool {
1542     match tcx.hir().get_if_local(def_id) {
1543         Some(Node::Item(hir::Item { kind: hir::ItemKind::OpaqueTy(opaque), .. })) => {
1544             matches!(opaque.origin, hir::OpaqueTyOrigin::TyAlias)
1545         }
1546         Some(_) => bug!("tried getting opaque_ty_origin for non-opaque: {:?}", def_id),
1547         _ => bug!("tried getting opaque_ty_origin for non-local def-id {:?}", def_id),
1548     }
1549 }