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