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