]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_analysis/src/collect.rs
Auto merge of #107650 - compiler-errors:rollup-4pntchf, r=compiler-errors
[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::{InferCtxt, 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     fn infcx(&self) -> Option<&InferCtxt<'tcx>> {
522         None
523     }
524 }
525
526 /// Synthesize a new lifetime name that doesn't clash with any of the lifetimes already present.
527 fn get_new_lifetime_name<'tcx>(
528     tcx: TyCtxt<'tcx>,
529     poly_trait_ref: ty::PolyTraitRef<'tcx>,
530     generics: &hir::Generics<'tcx>,
531 ) -> String {
532     let existing_lifetimes = tcx
533         .collect_referenced_late_bound_regions(&poly_trait_ref)
534         .into_iter()
535         .filter_map(|lt| {
536             if let ty::BoundRegionKind::BrNamed(_, name) = lt {
537                 Some(name.as_str().to_string())
538             } else {
539                 None
540             }
541         })
542         .chain(generics.params.iter().filter_map(|param| {
543             if let hir::GenericParamKind::Lifetime { .. } = &param.kind {
544                 Some(param.name.ident().as_str().to_string())
545             } else {
546                 None
547             }
548         }))
549         .collect::<FxHashSet<String>>();
550
551     let a_to_z_repeat_n = |n| {
552         (b'a'..=b'z').map(move |c| {
553             let mut s = '\''.to_string();
554             s.extend(std::iter::repeat(char::from(c)).take(n));
555             s
556         })
557     };
558
559     // If all single char lifetime names are present, we wrap around and double the chars.
560     (1..).flat_map(a_to_z_repeat_n).find(|lt| !existing_lifetimes.contains(lt.as_str())).unwrap()
561 }
562
563 fn convert_item(tcx: TyCtxt<'_>, item_id: hir::ItemId) {
564     let it = tcx.hir().item(item_id);
565     debug!("convert: item {} with id {}", it.ident, it.hir_id());
566     let def_id = item_id.owner_id.def_id;
567
568     match &it.kind {
569         // These don't define types.
570         hir::ItemKind::ExternCrate(_)
571         | hir::ItemKind::Use(..)
572         | hir::ItemKind::Macro(..)
573         | hir::ItemKind::Mod(_)
574         | hir::ItemKind::GlobalAsm(_) => {}
575         hir::ItemKind::ForeignMod { items, .. } => {
576             for item in *items {
577                 let item = tcx.hir().foreign_item(item.id);
578                 tcx.ensure().generics_of(item.owner_id);
579                 tcx.ensure().type_of(item.owner_id);
580                 tcx.ensure().predicates_of(item.owner_id);
581                 match item.kind {
582                     hir::ForeignItemKind::Fn(..) => {
583                         tcx.ensure().codegen_fn_attrs(item.owner_id);
584                         tcx.ensure().fn_sig(item.owner_id)
585                     }
586                     hir::ForeignItemKind::Static(..) => {
587                         tcx.ensure().codegen_fn_attrs(item.owner_id);
588                         let mut visitor = HirPlaceholderCollector::default();
589                         visitor.visit_foreign_item(item);
590                         placeholder_type_error(
591                             tcx,
592                             None,
593                             visitor.0,
594                             false,
595                             None,
596                             "static variable",
597                         );
598                     }
599                     _ => (),
600                 }
601             }
602         }
603         hir::ItemKind::Enum(..) => {
604             tcx.ensure().generics_of(def_id);
605             tcx.ensure().type_of(def_id);
606             tcx.ensure().predicates_of(def_id);
607             convert_enum_variant_types(tcx, def_id.to_def_id());
608         }
609         hir::ItemKind::Impl { .. } => {
610             tcx.ensure().generics_of(def_id);
611             tcx.ensure().type_of(def_id);
612             tcx.ensure().impl_trait_ref(def_id);
613             tcx.ensure().predicates_of(def_id);
614         }
615         hir::ItemKind::Trait(..) => {
616             tcx.ensure().generics_of(def_id);
617             tcx.ensure().trait_def(def_id);
618             tcx.at(it.span).super_predicates_of(def_id);
619             tcx.ensure().predicates_of(def_id);
620         }
621         hir::ItemKind::TraitAlias(..) => {
622             tcx.ensure().generics_of(def_id);
623             tcx.at(it.span).super_predicates_of(def_id);
624             tcx.ensure().predicates_of(def_id);
625         }
626         hir::ItemKind::Struct(struct_def, _) | hir::ItemKind::Union(struct_def, _) => {
627             tcx.ensure().generics_of(def_id);
628             tcx.ensure().type_of(def_id);
629             tcx.ensure().predicates_of(def_id);
630
631             for f in struct_def.fields() {
632                 tcx.ensure().generics_of(f.def_id);
633                 tcx.ensure().type_of(f.def_id);
634                 tcx.ensure().predicates_of(f.def_id);
635             }
636
637             if let Some(ctor_def_id) = struct_def.ctor_def_id() {
638                 convert_variant_ctor(tcx, ctor_def_id);
639             }
640         }
641
642         // Don't call `type_of` on opaque types, since that depends on type
643         // checking function bodies. `check_item_type` ensures that it's called
644         // instead.
645         hir::ItemKind::OpaqueTy(..) => {
646             tcx.ensure().generics_of(def_id);
647             tcx.ensure().predicates_of(def_id);
648             tcx.ensure().explicit_item_bounds(def_id);
649             tcx.ensure().item_bounds(def_id);
650         }
651
652         hir::ItemKind::TyAlias(..) => {
653             tcx.ensure().generics_of(def_id);
654             tcx.ensure().type_of(def_id);
655             tcx.ensure().predicates_of(def_id);
656         }
657
658         hir::ItemKind::Static(ty, ..) | hir::ItemKind::Const(ty, ..) => {
659             tcx.ensure().generics_of(def_id);
660             tcx.ensure().type_of(def_id);
661             tcx.ensure().predicates_of(def_id);
662             if !is_suggestable_infer_ty(ty) {
663                 let mut visitor = HirPlaceholderCollector::default();
664                 visitor.visit_item(it);
665                 placeholder_type_error(tcx, None, visitor.0, false, None, it.kind.descr());
666             }
667         }
668
669         hir::ItemKind::Fn(..) => {
670             tcx.ensure().generics_of(def_id);
671             tcx.ensure().type_of(def_id);
672             tcx.ensure().predicates_of(def_id);
673             tcx.ensure().fn_sig(def_id);
674             tcx.ensure().codegen_fn_attrs(def_id);
675         }
676     }
677 }
678
679 fn convert_trait_item(tcx: TyCtxt<'_>, trait_item_id: hir::TraitItemId) {
680     let trait_item = tcx.hir().trait_item(trait_item_id);
681     let def_id = trait_item_id.owner_id;
682     tcx.ensure().generics_of(def_id);
683
684     match trait_item.kind {
685         hir::TraitItemKind::Fn(..) => {
686             tcx.ensure().codegen_fn_attrs(def_id);
687             tcx.ensure().type_of(def_id);
688             tcx.ensure().fn_sig(def_id);
689         }
690
691         hir::TraitItemKind::Const(.., Some(_)) => {
692             tcx.ensure().type_of(def_id);
693         }
694
695         hir::TraitItemKind::Const(hir_ty, _) => {
696             tcx.ensure().type_of(def_id);
697             // Account for `const C: _;`.
698             let mut visitor = HirPlaceholderCollector::default();
699             visitor.visit_trait_item(trait_item);
700             if !tcx.sess.diagnostic().has_stashed_diagnostic(hir_ty.span, StashKey::ItemNoType) {
701                 placeholder_type_error(tcx, None, visitor.0, false, None, "constant");
702             }
703         }
704
705         hir::TraitItemKind::Type(_, Some(_)) => {
706             tcx.ensure().item_bounds(def_id);
707             tcx.ensure().type_of(def_id);
708             // Account for `type T = _;`.
709             let mut visitor = HirPlaceholderCollector::default();
710             visitor.visit_trait_item(trait_item);
711             placeholder_type_error(tcx, None, visitor.0, false, None, "associated type");
712         }
713
714         hir::TraitItemKind::Type(_, None) => {
715             tcx.ensure().item_bounds(def_id);
716             // #74612: Visit and try to find bad placeholders
717             // even if there is no concrete type.
718             let mut visitor = HirPlaceholderCollector::default();
719             visitor.visit_trait_item(trait_item);
720
721             placeholder_type_error(tcx, None, visitor.0, false, None, "associated type");
722         }
723     };
724
725     tcx.ensure().predicates_of(def_id);
726 }
727
728 fn convert_impl_item(tcx: TyCtxt<'_>, impl_item_id: hir::ImplItemId) {
729     let def_id = impl_item_id.owner_id;
730     tcx.ensure().generics_of(def_id);
731     tcx.ensure().type_of(def_id);
732     tcx.ensure().predicates_of(def_id);
733     let impl_item = tcx.hir().impl_item(impl_item_id);
734     match impl_item.kind {
735         hir::ImplItemKind::Fn(..) => {
736             tcx.ensure().codegen_fn_attrs(def_id);
737             tcx.ensure().fn_sig(def_id);
738         }
739         hir::ImplItemKind::Type(_) => {
740             // Account for `type T = _;`
741             let mut visitor = HirPlaceholderCollector::default();
742             visitor.visit_impl_item(impl_item);
743
744             placeholder_type_error(tcx, None, visitor.0, false, None, "associated type");
745         }
746         hir::ImplItemKind::Const(..) => {}
747     }
748 }
749
750 fn convert_variant_ctor(tcx: TyCtxt<'_>, def_id: LocalDefId) {
751     tcx.ensure().generics_of(def_id);
752     tcx.ensure().type_of(def_id);
753     tcx.ensure().predicates_of(def_id);
754 }
755
756 fn convert_enum_variant_types(tcx: TyCtxt<'_>, def_id: DefId) {
757     let def = tcx.adt_def(def_id);
758     let repr_type = def.repr().discr_type();
759     let initial = repr_type.initial_discriminant(tcx);
760     let mut prev_discr = None::<Discr<'_>>;
761
762     // fill the discriminant values and field types
763     for variant in def.variants() {
764         let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
765         prev_discr = Some(
766             if let ty::VariantDiscr::Explicit(const_def_id) = variant.discr {
767                 def.eval_explicit_discr(tcx, const_def_id)
768             } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) {
769                 Some(discr)
770             } else {
771                 let span = tcx.def_span(variant.def_id);
772                 struct_span_err!(tcx.sess, span, E0370, "enum discriminant overflowed")
773                     .span_label(span, format!("overflowed on value after {}", prev_discr.unwrap()))
774                     .note(&format!(
775                         "explicitly set `{} = {}` if that is desired outcome",
776                         tcx.item_name(variant.def_id),
777                         wrapped_discr
778                     ))
779                     .emit();
780                 None
781             }
782             .unwrap_or(wrapped_discr),
783         );
784
785         for f in &variant.fields {
786             tcx.ensure().generics_of(f.did);
787             tcx.ensure().type_of(f.did);
788             tcx.ensure().predicates_of(f.did);
789         }
790
791         // Convert the ctor, if any. This also registers the variant as
792         // an item.
793         if let Some(ctor_def_id) = variant.ctor_def_id() {
794             convert_variant_ctor(tcx, ctor_def_id.expect_local());
795         }
796     }
797 }
798
799 fn convert_variant(
800     tcx: TyCtxt<'_>,
801     variant_did: Option<LocalDefId>,
802     ident: Ident,
803     discr: ty::VariantDiscr,
804     def: &hir::VariantData<'_>,
805     adt_kind: ty::AdtKind,
806     parent_did: LocalDefId,
807 ) -> ty::VariantDef {
808     let mut seen_fields: FxHashMap<Ident, Span> = Default::default();
809     let fields = def
810         .fields()
811         .iter()
812         .map(|f| {
813             let dup_span = seen_fields.get(&f.ident.normalize_to_macros_2_0()).cloned();
814             if let Some(prev_span) = dup_span {
815                 tcx.sess.emit_err(errors::FieldAlreadyDeclared {
816                     field_name: f.ident,
817                     span: f.span,
818                     prev_span,
819                 });
820             } else {
821                 seen_fields.insert(f.ident.normalize_to_macros_2_0(), f.span);
822             }
823
824             ty::FieldDef {
825                 did: f.def_id.to_def_id(),
826                 name: f.ident.name,
827                 vis: tcx.visibility(f.def_id),
828             }
829         })
830         .collect();
831     let recovered = match def {
832         hir::VariantData::Struct(_, r) => *r,
833         _ => false,
834     };
835     ty::VariantDef::new(
836         ident.name,
837         variant_did.map(LocalDefId::to_def_id),
838         def.ctor().map(|(kind, _, def_id)| (kind, def_id.to_def_id())),
839         discr,
840         fields,
841         adt_kind,
842         parent_did.to_def_id(),
843         recovered,
844         adt_kind == AdtKind::Struct && tcx.has_attr(parent_did.to_def_id(), sym::non_exhaustive)
845             || variant_did.map_or(false, |variant_did| {
846                 tcx.has_attr(variant_did.to_def_id(), sym::non_exhaustive)
847             }),
848     )
849 }
850
851 fn adt_def(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AdtDef<'_> {
852     use rustc_hir::*;
853
854     let def_id = def_id.expect_local();
855     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
856     let Node::Item(item) = tcx.hir().get(hir_id) else {
857         bug!();
858     };
859
860     let repr = tcx.repr_options_of_def(def_id.to_def_id());
861     let (kind, variants) = match &item.kind {
862         ItemKind::Enum(def, _) => {
863             let mut distance_from_explicit = 0;
864             let variants = def
865                 .variants
866                 .iter()
867                 .map(|v| {
868                     let discr = if let Some(e) = &v.disr_expr {
869                         distance_from_explicit = 0;
870                         ty::VariantDiscr::Explicit(e.def_id.to_def_id())
871                     } else {
872                         ty::VariantDiscr::Relative(distance_from_explicit)
873                     };
874                     distance_from_explicit += 1;
875
876                     convert_variant(
877                         tcx,
878                         Some(v.def_id),
879                         v.ident,
880                         discr,
881                         &v.data,
882                         AdtKind::Enum,
883                         def_id,
884                     )
885                 })
886                 .collect();
887
888             (AdtKind::Enum, variants)
889         }
890         ItemKind::Struct(def, _) | ItemKind::Union(def, _) => {
891             let adt_kind = match item.kind {
892                 ItemKind::Struct(..) => AdtKind::Struct,
893                 _ => AdtKind::Union,
894             };
895             let variants = std::iter::once(convert_variant(
896                 tcx,
897                 None,
898                 item.ident,
899                 ty::VariantDiscr::Relative(0),
900                 def,
901                 adt_kind,
902                 def_id,
903             ))
904             .collect();
905
906             (adt_kind, variants)
907         }
908         _ => bug!(),
909     };
910     tcx.alloc_adt_def(def_id.to_def_id(), kind, variants, repr)
911 }
912
913 fn trait_def(tcx: TyCtxt<'_>, def_id: DefId) -> ty::TraitDef {
914     let item = tcx.hir().expect_item(def_id.expect_local());
915
916     let (is_auto, unsafety, items) = match item.kind {
917         hir::ItemKind::Trait(is_auto, unsafety, .., items) => {
918             (is_auto == hir::IsAuto::Yes, unsafety, items)
919         }
920         hir::ItemKind::TraitAlias(..) => (false, hir::Unsafety::Normal, &[][..]),
921         _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
922     };
923
924     let paren_sugar = tcx.has_attr(def_id, sym::rustc_paren_sugar);
925     if paren_sugar && !tcx.features().unboxed_closures {
926         tcx.sess
927             .struct_span_err(
928                 item.span,
929                 "the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \
930                  which traits can use parenthetical notation",
931             )
932             .help("add `#![feature(unboxed_closures)]` to the crate attributes to use it")
933             .emit();
934     }
935
936     let is_marker = tcx.has_attr(def_id, sym::marker);
937     let skip_array_during_method_dispatch =
938         tcx.has_attr(def_id, sym::rustc_skip_array_during_method_dispatch);
939     let spec_kind = if tcx.has_attr(def_id, sym::rustc_unsafe_specialization_marker) {
940         ty::trait_def::TraitSpecializationKind::Marker
941     } else if tcx.has_attr(def_id, sym::rustc_specialization_trait) {
942         ty::trait_def::TraitSpecializationKind::AlwaysApplicable
943     } else {
944         ty::trait_def::TraitSpecializationKind::None
945     };
946     let must_implement_one_of = tcx
947         .get_attr(def_id, sym::rustc_must_implement_one_of)
948         // Check that there are at least 2 arguments of `#[rustc_must_implement_one_of]`
949         // and that they are all identifiers
950         .and_then(|attr| match attr.meta_item_list() {
951             Some(items) if items.len() < 2 => {
952                 tcx.sess
953                     .struct_span_err(
954                         attr.span,
955                         "the `#[rustc_must_implement_one_of]` attribute must be \
956                          used with at least 2 args",
957                     )
958                     .emit();
959
960                 None
961             }
962             Some(items) => items
963                 .into_iter()
964                 .map(|item| item.ident().ok_or(item.span()))
965                 .collect::<Result<Box<[_]>, _>>()
966                 .map_err(|span| {
967                     tcx.sess
968                         .struct_span_err(span, "must be a name of an associated function")
969                         .emit();
970                 })
971                 .ok()
972                 .zip(Some(attr.span)),
973             // Error is reported by `rustc_attr!`
974             None => None,
975         })
976         // Check that all arguments of `#[rustc_must_implement_one_of]` reference
977         // functions in the trait with default implementations
978         .and_then(|(list, attr_span)| {
979             let errors = list.iter().filter_map(|ident| {
980                 let item = items.iter().find(|item| item.ident == *ident);
981
982                 match item {
983                     Some(item) if matches!(item.kind, hir::AssocItemKind::Fn { .. }) => {
984                         if !tcx.impl_defaultness(item.id.owner_id).has_value() {
985                             tcx.sess
986                                 .struct_span_err(
987                                     item.span,
988                                     "function doesn't have a default implementation",
989                                 )
990                                 .span_note(attr_span, "required by this annotation")
991                                 .emit();
992
993                             return Some(());
994                         }
995
996                         return None;
997                     }
998                     Some(item) => {
999                         tcx.sess
1000                             .struct_span_err(item.span, "not a function")
1001                             .span_note(attr_span, "required by this annotation")
1002                             .note(
1003                                 "all `#[rustc_must_implement_one_of]` arguments must be associated \
1004                                  function names",
1005                             )
1006                             .emit();
1007                     }
1008                     None => {
1009                         tcx.sess
1010                             .struct_span_err(ident.span, "function not found in this trait")
1011                             .emit();
1012                     }
1013                 }
1014
1015                 Some(())
1016             });
1017
1018             (errors.count() == 0).then_some(list)
1019         })
1020         // Check for duplicates
1021         .and_then(|list| {
1022             let mut set: FxHashMap<Symbol, Span> = FxHashMap::default();
1023             let mut no_dups = true;
1024
1025             for ident in &*list {
1026                 if let Some(dup) = set.insert(ident.name, ident.span) {
1027                     tcx.sess
1028                         .struct_span_err(vec![dup, ident.span], "functions names are duplicated")
1029                         .note("all `#[rustc_must_implement_one_of]` arguments must be unique")
1030                         .emit();
1031
1032                     no_dups = false;
1033                 }
1034             }
1035
1036             no_dups.then_some(list)
1037         });
1038
1039     ty::TraitDef::new(
1040         def_id,
1041         unsafety,
1042         paren_sugar,
1043         is_auto,
1044         is_marker,
1045         skip_array_during_method_dispatch,
1046         spec_kind,
1047         must_implement_one_of,
1048     )
1049 }
1050
1051 fn are_suggestable_generic_args(generic_args: &[hir::GenericArg<'_>]) -> bool {
1052     generic_args.iter().any(|arg| match arg {
1053         hir::GenericArg::Type(ty) => is_suggestable_infer_ty(ty),
1054         hir::GenericArg::Infer(_) => true,
1055         _ => false,
1056     })
1057 }
1058
1059 /// Whether `ty` is a type with `_` placeholders that can be inferred. Used in diagnostics only to
1060 /// use inference to provide suggestions for the appropriate type if possible.
1061 fn is_suggestable_infer_ty(ty: &hir::Ty<'_>) -> bool {
1062     debug!(?ty);
1063     use hir::TyKind::*;
1064     match &ty.kind {
1065         Infer => true,
1066         Slice(ty) => is_suggestable_infer_ty(ty),
1067         Array(ty, length) => {
1068             is_suggestable_infer_ty(ty) || matches!(length, hir::ArrayLen::Infer(_, _))
1069         }
1070         Tup(tys) => tys.iter().any(is_suggestable_infer_ty),
1071         Ptr(mut_ty) | Ref(_, mut_ty) => is_suggestable_infer_ty(mut_ty.ty),
1072         OpaqueDef(_, generic_args, _) => are_suggestable_generic_args(generic_args),
1073         Path(hir::QPath::TypeRelative(ty, segment)) => {
1074             is_suggestable_infer_ty(ty) || are_suggestable_generic_args(segment.args().args)
1075         }
1076         Path(hir::QPath::Resolved(ty_opt, hir::Path { segments, .. })) => {
1077             ty_opt.map_or(false, is_suggestable_infer_ty)
1078                 || segments.iter().any(|segment| are_suggestable_generic_args(segment.args().args))
1079         }
1080         _ => false,
1081     }
1082 }
1083
1084 pub fn get_infer_ret_ty<'hir>(output: &'hir hir::FnRetTy<'hir>) -> Option<&'hir hir::Ty<'hir>> {
1085     if let hir::FnRetTy::Return(ty) = output {
1086         if is_suggestable_infer_ty(ty) {
1087             return Some(&*ty);
1088         }
1089     }
1090     None
1091 }
1092
1093 #[instrument(level = "debug", skip(tcx))]
1094 fn fn_sig(tcx: TyCtxt<'_>, def_id: DefId) -> ty::EarlyBinder<ty::PolyFnSig<'_>> {
1095     use rustc_hir::Node::*;
1096     use rustc_hir::*;
1097
1098     let def_id = def_id.expect_local();
1099     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
1100
1101     let icx = ItemCtxt::new(tcx, def_id.to_def_id());
1102
1103     let output = match tcx.hir().get(hir_id) {
1104         TraitItem(hir::TraitItem {
1105             kind: TraitItemKind::Fn(sig, TraitFn::Provided(_)),
1106             generics,
1107             ..
1108         })
1109         | Item(hir::Item { kind: ItemKind::Fn(sig, generics, _), .. }) => {
1110             infer_return_ty_for_fn_sig(tcx, sig, generics, def_id, &icx)
1111         }
1112
1113         ImplItem(hir::ImplItem { kind: ImplItemKind::Fn(sig, _), generics, .. }) => {
1114             // Do not try to infer the return type for a impl method coming from a trait
1115             if let Item(hir::Item { kind: ItemKind::Impl(i), .. }) =
1116                 tcx.hir().get_parent(hir_id)
1117                 && i.of_trait.is_some()
1118             {
1119                 icx.astconv().ty_of_fn(
1120                     hir_id,
1121                     sig.header.unsafety,
1122                     sig.header.abi,
1123                     sig.decl,
1124                     Some(generics),
1125                     None,
1126                 )
1127             } else {
1128                 infer_return_ty_for_fn_sig(tcx, sig, generics, def_id, &icx)
1129             }
1130         }
1131
1132         TraitItem(hir::TraitItem {
1133             kind: TraitItemKind::Fn(FnSig { header, decl, span: _ }, _),
1134             generics,
1135             ..
1136         }) => {
1137             icx.astconv().ty_of_fn(hir_id, header.unsafety, header.abi, decl, Some(generics), None)
1138         }
1139
1140         ForeignItem(&hir::ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
1141             let abi = tcx.hir().get_foreign_abi(hir_id);
1142             compute_sig_of_foreign_fn_decl(tcx, def_id.to_def_id(), fn_decl, abi)
1143         }
1144
1145         Ctor(data) | Variant(hir::Variant { data, .. }) if data.ctor().is_some() => {
1146             let ty = tcx.type_of(tcx.hir().get_parent_item(hir_id));
1147             let inputs = data.fields().iter().map(|f| tcx.type_of(f.def_id));
1148             ty::Binder::dummy(tcx.mk_fn_sig(
1149                 inputs,
1150                 ty,
1151                 false,
1152                 hir::Unsafety::Normal,
1153                 abi::Abi::Rust,
1154             ))
1155         }
1156
1157         Expr(&hir::Expr { kind: hir::ExprKind::Closure { .. }, .. }) => {
1158             // Closure signatures are not like other function
1159             // signatures and cannot be accessed through `fn_sig`. For
1160             // example, a closure signature excludes the `self`
1161             // argument. In any case they are embedded within the
1162             // closure type as part of the `ClosureSubsts`.
1163             //
1164             // To get the signature of a closure, you should use the
1165             // `sig` method on the `ClosureSubsts`:
1166             //
1167             //    substs.as_closure().sig(def_id, tcx)
1168             bug!(
1169                 "to get the signature of a closure, use `substs.as_closure().sig()` not `fn_sig()`",
1170             );
1171         }
1172
1173         x => {
1174             bug!("unexpected sort of node in fn_sig(): {:?}", x);
1175         }
1176     };
1177     ty::EarlyBinder(output)
1178 }
1179
1180 fn infer_return_ty_for_fn_sig<'tcx>(
1181     tcx: TyCtxt<'tcx>,
1182     sig: &hir::FnSig<'_>,
1183     generics: &hir::Generics<'_>,
1184     def_id: LocalDefId,
1185     icx: &ItemCtxt<'tcx>,
1186 ) -> ty::PolyFnSig<'tcx> {
1187     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
1188
1189     match get_infer_ret_ty(&sig.decl.output) {
1190         Some(ty) => {
1191             let fn_sig = tcx.typeck(def_id).liberated_fn_sigs()[hir_id];
1192             // Typeck doesn't expect erased regions to be returned from `type_of`.
1193             let fn_sig = tcx.fold_regions(fn_sig, |r, _| match *r {
1194                 ty::ReErased => tcx.lifetimes.re_static,
1195                 _ => r,
1196             });
1197
1198             let mut visitor = HirPlaceholderCollector::default();
1199             visitor.visit_ty(ty);
1200             let mut diag = bad_placeholder(tcx, visitor.0, "return type");
1201             let ret_ty = fn_sig.output();
1202             if let Some(ret_ty) = ret_ty.make_suggestable(tcx, false) {
1203                 diag.span_suggestion(
1204                     ty.span,
1205                     "replace with the correct return type",
1206                     ret_ty,
1207                     Applicability::MachineApplicable,
1208                 );
1209             } else if matches!(ret_ty.kind(), ty::FnDef(..))
1210                 && let Some(fn_sig) = ret_ty.fn_sig(tcx).make_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             } else if let Some(sugg) = suggest_impl_trait(tcx, ret_ty, ty.span, hir_id, def_id) {
1219                 diag.span_suggestion(
1220                     ty.span,
1221                     "replace with an appropriate return type",
1222                     sugg,
1223                     Applicability::MachineApplicable,
1224                 );
1225             } else if ret_ty.is_closure() {
1226                 diag.help("consider using an `Fn`, `FnMut`, or `FnOnce` trait bound");
1227             }
1228             // Also note how `Fn` traits work just in case!
1229             if ret_ty.is_closure() {
1230                 diag.note(
1231                     "for more information on `Fn` traits and closure types, see \
1232                      https://doc.rust-lang.org/book/ch13-01-closures.html",
1233                 );
1234             }
1235             diag.emit();
1236
1237             ty::Binder::dummy(fn_sig)
1238         }
1239         None => icx.astconv().ty_of_fn(
1240             hir_id,
1241             sig.header.unsafety,
1242             sig.header.abi,
1243             sig.decl,
1244             Some(generics),
1245             None,
1246         ),
1247     }
1248 }
1249
1250 // FIXME(vincenzopalazzo): remove the hir item when the refactoring is stable
1251 fn suggest_impl_trait<'tcx>(
1252     tcx: TyCtxt<'tcx>,
1253     ret_ty: Ty<'tcx>,
1254     span: Span,
1255     _hir_id: hir::HirId,
1256     def_id: LocalDefId,
1257 ) -> Option<String> {
1258     let format_as_assoc: fn(_, _, _, _, _) -> _ =
1259         |tcx: TyCtxt<'tcx>,
1260          _: ty::SubstsRef<'tcx>,
1261          trait_def_id: DefId,
1262          assoc_item_def_id: DefId,
1263          item_ty: Ty<'tcx>| {
1264             let trait_name = tcx.item_name(trait_def_id);
1265             let assoc_name = tcx.item_name(assoc_item_def_id);
1266             Some(format!("impl {trait_name}<{assoc_name} = {item_ty}>"))
1267         };
1268     let format_as_parenthesized: fn(_, _, _, _, _) -> _ =
1269         |tcx: TyCtxt<'tcx>,
1270          substs: ty::SubstsRef<'tcx>,
1271          trait_def_id: DefId,
1272          _: DefId,
1273          item_ty: Ty<'tcx>| {
1274             let trait_name = tcx.item_name(trait_def_id);
1275             let args_tuple = substs.type_at(1);
1276             let ty::Tuple(types) = *args_tuple.kind() else { return None; };
1277             let types = types.make_suggestable(tcx, false)?;
1278             let maybe_ret =
1279                 if item_ty.is_unit() { String::new() } else { format!(" -> {item_ty}") };
1280             Some(format!(
1281                 "impl {trait_name}({}){maybe_ret}",
1282                 types.iter().map(|ty| ty.to_string()).collect::<Vec<_>>().join(", ")
1283             ))
1284         };
1285
1286     for (trait_def_id, assoc_item_def_id, formatter) in [
1287         (
1288             tcx.get_diagnostic_item(sym::Iterator),
1289             tcx.get_diagnostic_item(sym::IteratorItem),
1290             format_as_assoc,
1291         ),
1292         (
1293             tcx.lang_items().future_trait(),
1294             tcx.get_diagnostic_item(sym::FutureOutput),
1295             format_as_assoc,
1296         ),
1297         (tcx.lang_items().fn_trait(), tcx.lang_items().fn_once_output(), format_as_parenthesized),
1298         (
1299             tcx.lang_items().fn_mut_trait(),
1300             tcx.lang_items().fn_once_output(),
1301             format_as_parenthesized,
1302         ),
1303         (
1304             tcx.lang_items().fn_once_trait(),
1305             tcx.lang_items().fn_once_output(),
1306             format_as_parenthesized,
1307         ),
1308     ] {
1309         let Some(trait_def_id) = trait_def_id else { continue; };
1310         let Some(assoc_item_def_id) = assoc_item_def_id else { continue; };
1311         if tcx.def_kind(assoc_item_def_id) != DefKind::AssocTy {
1312             continue;
1313         }
1314         let param_env = tcx.param_env(def_id);
1315         let infcx = tcx.infer_ctxt().build();
1316         let substs = ty::InternalSubsts::for_item(tcx, trait_def_id, |param, _| {
1317             if param.index == 0 { ret_ty.into() } else { infcx.var_for_def(span, param) }
1318         });
1319         if !infcx.type_implements_trait(trait_def_id, substs, param_env).must_apply_modulo_regions()
1320         {
1321             continue;
1322         }
1323         let ocx = ObligationCtxt::new_in_snapshot(&infcx);
1324         let item_ty = ocx.normalize(
1325             &ObligationCause::misc(span, def_id),
1326             param_env,
1327             tcx.mk_projection(assoc_item_def_id, substs),
1328         );
1329         // FIXME(compiler-errors): We may benefit from resolving regions here.
1330         if ocx.select_where_possible().is_empty()
1331             && let item_ty = infcx.resolve_vars_if_possible(item_ty)
1332             && let Some(item_ty) = item_ty.make_suggestable(tcx, false)
1333             && let Some(sugg) = formatter(tcx, infcx.resolve_vars_if_possible(substs), trait_def_id, assoc_item_def_id, item_ty)
1334         {
1335             return Some(sugg);
1336         }
1337     }
1338     None
1339 }
1340
1341 fn impl_trait_ref(tcx: TyCtxt<'_>, def_id: DefId) -> Option<ty::EarlyBinder<ty::TraitRef<'_>>> {
1342     let icx = ItemCtxt::new(tcx, def_id);
1343     let impl_ = tcx.hir().expect_item(def_id.expect_local()).expect_impl();
1344     impl_
1345         .of_trait
1346         .as_ref()
1347         .map(|ast_trait_ref| {
1348             let selfty = tcx.type_of(def_id);
1349             icx.astconv().instantiate_mono_trait_ref(
1350                 ast_trait_ref,
1351                 selfty,
1352                 check_impl_constness(tcx, impl_.constness, ast_trait_ref),
1353             )
1354         })
1355         .map(ty::EarlyBinder)
1356 }
1357
1358 fn check_impl_constness(
1359     tcx: TyCtxt<'_>,
1360     constness: hir::Constness,
1361     ast_trait_ref: &hir::TraitRef<'_>,
1362 ) -> ty::BoundConstness {
1363     match constness {
1364         hir::Constness::Const => {
1365             if let Some(trait_def_id) = ast_trait_ref.trait_def_id() && !tcx.has_attr(trait_def_id, sym::const_trait) {
1366                 let trait_name = tcx.item_name(trait_def_id).to_string();
1367                 tcx.sess.emit_err(errors::ConstImplForNonConstTrait {
1368                     trait_ref_span: ast_trait_ref.path.span,
1369                     trait_name,
1370                     local_trait_span: trait_def_id.as_local().map(|_| tcx.def_span(trait_def_id).shrink_to_lo()),
1371                     marking: (),
1372                     adding: (),
1373                 });
1374                 ty::BoundConstness::NotConst
1375             } else {
1376                 ty::BoundConstness::ConstIfConst
1377             }
1378         },
1379         hir::Constness::NotConst => ty::BoundConstness::NotConst,
1380     }
1381 }
1382
1383 fn impl_polarity(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ImplPolarity {
1384     let is_rustc_reservation = tcx.has_attr(def_id, sym::rustc_reservation_impl);
1385     let item = tcx.hir().expect_item(def_id.expect_local());
1386     match &item.kind {
1387         hir::ItemKind::Impl(hir::Impl {
1388             polarity: hir::ImplPolarity::Negative(span),
1389             of_trait,
1390             ..
1391         }) => {
1392             if is_rustc_reservation {
1393                 let span = span.to(of_trait.as_ref().map_or(*span, |t| t.path.span));
1394                 tcx.sess.span_err(span, "reservation impls can't be negative");
1395             }
1396             ty::ImplPolarity::Negative
1397         }
1398         hir::ItemKind::Impl(hir::Impl {
1399             polarity: hir::ImplPolarity::Positive,
1400             of_trait: None,
1401             ..
1402         }) => {
1403             if is_rustc_reservation {
1404                 tcx.sess.span_err(item.span, "reservation impls can't be inherent");
1405             }
1406             ty::ImplPolarity::Positive
1407         }
1408         hir::ItemKind::Impl(hir::Impl {
1409             polarity: hir::ImplPolarity::Positive,
1410             of_trait: Some(_),
1411             ..
1412         }) => {
1413             if is_rustc_reservation {
1414                 ty::ImplPolarity::Reservation
1415             } else {
1416                 ty::ImplPolarity::Positive
1417             }
1418         }
1419         item => bug!("impl_polarity: {:?} not an impl", item),
1420     }
1421 }
1422
1423 /// Returns the early-bound lifetimes declared in this generics
1424 /// listing. For anything other than fns/methods, this is just all
1425 /// the lifetimes that are declared. For fns or methods, we have to
1426 /// screen out those that do not appear in any where-clauses etc using
1427 /// `resolve_lifetime::early_bound_lifetimes`.
1428 fn early_bound_lifetimes_from_generics<'a, 'tcx: 'a>(
1429     tcx: TyCtxt<'tcx>,
1430     generics: &'a hir::Generics<'a>,
1431 ) -> impl Iterator<Item = &'a hir::GenericParam<'a>> + Captures<'tcx> {
1432     generics.params.iter().filter(move |param| match param.kind {
1433         GenericParamKind::Lifetime { .. } => !tcx.is_late_bound(param.hir_id),
1434         _ => false,
1435     })
1436 }
1437
1438 /// Returns a list of type predicates for the definition with ID `def_id`, including inferred
1439 /// lifetime constraints. This includes all predicates returned by `explicit_predicates_of`, plus
1440 /// inferred constraints concerning which regions outlive other regions.
1441 #[instrument(level = "debug", skip(tcx))]
1442 fn predicates_defined_on(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1443     let mut result = tcx.explicit_predicates_of(def_id);
1444     debug!("predicates_defined_on: explicit_predicates_of({:?}) = {:?}", def_id, result,);
1445     let inferred_outlives = tcx.inferred_outlives_of(def_id);
1446     if !inferred_outlives.is_empty() {
1447         debug!(
1448             "predicates_defined_on: inferred_outlives_of({:?}) = {:?}",
1449             def_id, inferred_outlives,
1450         );
1451         let inferred_outlives_iter =
1452             inferred_outlives.iter().map(|(clause, span)| ((*clause).to_predicate(tcx), *span));
1453         if result.predicates.is_empty() {
1454             result.predicates = tcx.arena.alloc_from_iter(inferred_outlives_iter);
1455         } else {
1456             result.predicates = tcx.arena.alloc_from_iter(
1457                 result.predicates.into_iter().copied().chain(inferred_outlives_iter),
1458             );
1459         }
1460     }
1461
1462     debug!("predicates_defined_on({:?}) = {:?}", def_id, result);
1463     result
1464 }
1465
1466 fn compute_sig_of_foreign_fn_decl<'tcx>(
1467     tcx: TyCtxt<'tcx>,
1468     def_id: DefId,
1469     decl: &'tcx hir::FnDecl<'tcx>,
1470     abi: abi::Abi,
1471 ) -> ty::PolyFnSig<'tcx> {
1472     let unsafety = if abi == abi::Abi::RustIntrinsic {
1473         intrinsic_operation_unsafety(tcx, def_id)
1474     } else {
1475         hir::Unsafety::Unsafe
1476     };
1477     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1478     let fty =
1479         ItemCtxt::new(tcx, def_id).astconv().ty_of_fn(hir_id, unsafety, abi, decl, None, None);
1480
1481     // Feature gate SIMD types in FFI, since I am not sure that the
1482     // ABIs are handled at all correctly. -huonw
1483     if abi != abi::Abi::RustIntrinsic
1484         && abi != abi::Abi::PlatformIntrinsic
1485         && !tcx.features().simd_ffi
1486     {
1487         let check = |ast_ty: &hir::Ty<'_>, ty: Ty<'_>| {
1488             if ty.is_simd() {
1489                 let snip = tcx
1490                     .sess
1491                     .source_map()
1492                     .span_to_snippet(ast_ty.span)
1493                     .map_or_else(|_| String::new(), |s| format!(" `{}`", s));
1494                 tcx.sess
1495                     .struct_span_err(
1496                         ast_ty.span,
1497                         &format!(
1498                             "use of SIMD type{} in FFI is highly experimental and \
1499                              may result in invalid code",
1500                             snip
1501                         ),
1502                     )
1503                     .help("add `#![feature(simd_ffi)]` to the crate attributes to enable")
1504                     .emit();
1505             }
1506         };
1507         for (input, ty) in iter::zip(decl.inputs, fty.inputs().skip_binder()) {
1508             check(input, *ty)
1509         }
1510         if let hir::FnRetTy::Return(ty) = decl.output {
1511             check(ty, fty.output().skip_binder())
1512         }
1513     }
1514
1515     fty
1516 }
1517
1518 fn is_foreign_item(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1519     match tcx.hir().get_if_local(def_id) {
1520         Some(Node::ForeignItem(..)) => true,
1521         Some(_) => false,
1522         _ => bug!("is_foreign_item applied to non-local def-id {:?}", def_id),
1523     }
1524 }
1525
1526 fn generator_kind(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::GeneratorKind> {
1527     match tcx.hir().get_if_local(def_id) {
1528         Some(Node::Expr(&rustc_hir::Expr {
1529             kind: rustc_hir::ExprKind::Closure(&rustc_hir::Closure { body, .. }),
1530             ..
1531         })) => tcx.hir().body(body).generator_kind(),
1532         Some(_) => None,
1533         _ => bug!("generator_kind applied to non-local def-id {:?}", def_id),
1534     }
1535 }
1536
1537 fn is_type_alias_impl_trait<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> bool {
1538     match tcx.hir().get_if_local(def_id) {
1539         Some(Node::Item(hir::Item { kind: hir::ItemKind::OpaqueTy(opaque), .. })) => {
1540             matches!(opaque.origin, hir::OpaqueTyOrigin::TyAlias)
1541         }
1542         Some(_) => bug!("tried getting opaque_ty_origin for non-opaque: {:?}", def_id),
1543         _ => bug!("tried getting opaque_ty_origin for non-local def-id {:?}", def_id),
1544     }
1545 }