]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_analysis/src/collect.rs
Rollup merge of #102794 - dtolnay:termination, r=thomcc
[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 rustc_ast as ast;
21 use rustc_ast::{MetaItemKind, NestedMetaItem};
22 use rustc_attr::{list_contains_name, InlineAttr, InstructionSetAttr, OptimizeAttr};
23 use rustc_data_structures::captures::Captures;
24 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
25 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, ErrorGuaranteed, StashKey};
26 use rustc_hir as hir;
27 use rustc_hir::def::CtorKind;
28 use rustc_hir::def_id::{DefId, LocalDefId, LOCAL_CRATE};
29 use rustc_hir::intravisit::{self, Visitor};
30 use rustc_hir::weak_lang_items;
31 use rustc_hir::{GenericParamKind, Node};
32 use rustc_middle::hir::nested_filter;
33 use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
34 use rustc_middle::mir::mono::Linkage;
35 use rustc_middle::ty::query::Providers;
36 use rustc_middle::ty::util::{Discr, IntTypeExt};
37 use rustc_middle::ty::ReprOptions;
38 use rustc_middle::ty::{self, AdtKind, Const, DefIdTree, IsSuggestable, Ty, TyCtxt};
39 use rustc_session::lint;
40 use rustc_session::parse::feature_err;
41 use rustc_span::symbol::{kw, sym, Ident, Symbol};
42 use rustc_span::Span;
43 use rustc_target::spec::{abi, SanitizerSet};
44 use rustc_trait_selection::traits::error_reporting::suggestions::NextTypeParamName;
45 use std::iter;
46
47 mod generics_of;
48 mod item_bounds;
49 mod predicates_of;
50 mod type_of;
51
52 ///////////////////////////////////////////////////////////////////////////
53 // Main entry point
54
55 fn collect_mod_item_types(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
56     tcx.hir().visit_item_likes_in_module(module_def_id, &mut CollectItemTypesVisitor { tcx });
57 }
58
59 pub fn provide(providers: &mut Providers) {
60     *providers = Providers {
61         opt_const_param_of: type_of::opt_const_param_of,
62         type_of: type_of::type_of,
63         item_bounds: item_bounds::item_bounds,
64         explicit_item_bounds: item_bounds::explicit_item_bounds,
65         generics_of: generics_of::generics_of,
66         predicates_of: predicates_of::predicates_of,
67         predicates_defined_on,
68         explicit_predicates_of: predicates_of::explicit_predicates_of,
69         super_predicates_of: predicates_of::super_predicates_of,
70         super_predicates_that_define_assoc_type:
71             predicates_of::super_predicates_that_define_assoc_type,
72         trait_explicit_predicates_and_bounds: predicates_of::trait_explicit_predicates_and_bounds,
73         type_param_predicates: predicates_of::type_param_predicates,
74         trait_def,
75         adt_def,
76         fn_sig,
77         impl_trait_ref,
78         impl_polarity,
79         is_foreign_item,
80         generator_kind,
81         codegen_fn_attrs,
82         asm_target_features,
83         collect_mod_item_types,
84         should_inherit_track_caller,
85         ..*providers
86     };
87 }
88
89 ///////////////////////////////////////////////////////////////////////////
90
91 /// Context specific to some particular item. This is what implements
92 /// [`AstConv`].
93 ///
94 /// # `ItemCtxt` vs `FnCtxt`
95 ///
96 /// `ItemCtxt` is primarily used to type-check item signatures and lower them
97 /// from HIR to their [`ty::Ty`] representation, which is exposed using [`AstConv`].
98 /// It's also used for the bodies of items like structs where the body (the fields)
99 /// are just signatures.
100 ///
101 /// This is in contrast to [`FnCtxt`], which is used to type-check bodies of
102 /// functions, closures, and `const`s -- anywhere that expressions and statements show up.
103 ///
104 /// An important thing to note is that `ItemCtxt` does no inference -- it has no [`InferCtxt`] --
105 /// while `FnCtxt` does do inference.
106 ///
107 /// [`FnCtxt`]: crate::check::FnCtxt
108 /// [`InferCtxt`]: rustc_infer::infer::InferCtxt
109 ///
110 /// # Trait predicates
111 ///
112 /// `ItemCtxt` has information about the predicates that are defined
113 /// on the trait. Unfortunately, this predicate information is
114 /// available in various different forms at various points in the
115 /// process. So we can't just store a pointer to e.g., the AST or the
116 /// parsed ty form, we have to be more flexible. To this end, the
117 /// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy
118 /// `get_type_parameter_bounds` requests, drawing the information from
119 /// the AST (`hir::Generics`), recursively.
120 pub struct ItemCtxt<'tcx> {
121     tcx: TyCtxt<'tcx>,
122     item_def_id: DefId,
123 }
124
125 ///////////////////////////////////////////////////////////////////////////
126
127 #[derive(Default)]
128 pub(crate) struct HirPlaceholderCollector(pub(crate) Vec<Span>);
129
130 impl<'v> Visitor<'v> for HirPlaceholderCollector {
131     fn visit_ty(&mut self, t: &'v hir::Ty<'v>) {
132         if let hir::TyKind::Infer = t.kind {
133             self.0.push(t.span);
134         }
135         intravisit::walk_ty(self, t)
136     }
137     fn visit_generic_arg(&mut self, generic_arg: &'v hir::GenericArg<'v>) {
138         match generic_arg {
139             hir::GenericArg::Infer(inf) => {
140                 self.0.push(inf.span);
141                 intravisit::walk_inf(self, inf);
142             }
143             hir::GenericArg::Type(t) => self.visit_ty(t),
144             _ => {}
145         }
146     }
147     fn visit_array_length(&mut self, length: &'v hir::ArrayLen) {
148         if let &hir::ArrayLen::Infer(_, span) = length {
149             self.0.push(span);
150         }
151         intravisit::walk_array_len(self, length)
152     }
153 }
154
155 struct CollectItemTypesVisitor<'tcx> {
156     tcx: TyCtxt<'tcx>,
157 }
158
159 /// If there are any placeholder types (`_`), emit an error explaining that this is not allowed
160 /// and suggest adding type parameters in the appropriate place, taking into consideration any and
161 /// all already existing generic type parameters to avoid suggesting a name that is already in use.
162 pub(crate) fn placeholder_type_error<'tcx>(
163     tcx: TyCtxt<'tcx>,
164     generics: Option<&hir::Generics<'_>>,
165     placeholder_types: Vec<Span>,
166     suggest: bool,
167     hir_ty: Option<&hir::Ty<'_>>,
168     kind: &'static str,
169 ) {
170     if placeholder_types.is_empty() {
171         return;
172     }
173
174     placeholder_type_error_diag(tcx, generics, placeholder_types, vec![], suggest, hir_ty, kind)
175         .emit();
176 }
177
178 pub(crate) fn placeholder_type_error_diag<'tcx>(
179     tcx: TyCtxt<'tcx>,
180     generics: Option<&hir::Generics<'_>>,
181     placeholder_types: Vec<Span>,
182     additional_spans: Vec<Span>,
183     suggest: bool,
184     hir_ty: Option<&hir::Ty<'_>>,
185     kind: &'static str,
186 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
187     if placeholder_types.is_empty() {
188         return bad_placeholder(tcx, additional_spans, kind);
189     }
190
191     let params = generics.map(|g| g.params).unwrap_or_default();
192     let type_name = params.next_type_param_name(None);
193     let mut sugg: Vec<_> =
194         placeholder_types.iter().map(|sp| (*sp, (*type_name).to_string())).collect();
195
196     if let Some(generics) = generics {
197         if let Some(arg) = params.iter().find(|arg| {
198             matches!(arg.name, hir::ParamName::Plain(Ident { name: kw::Underscore, .. }))
199         }) {
200             // Account for `_` already present in cases like `struct S<_>(_);` and suggest
201             // `struct S<T>(T);` instead of `struct S<_, T>(T);`.
202             sugg.push((arg.span, (*type_name).to_string()));
203         } else if let Some(span) = generics.span_for_param_suggestion() {
204             // Account for bounds, we want `fn foo<T: E, K>(_: K)` not `fn foo<T, K: E>(_: K)`.
205             sugg.push((span, format!(", {}", type_name)));
206         } else {
207             sugg.push((generics.span, format!("<{}>", type_name)));
208         }
209     }
210
211     let mut err =
212         bad_placeholder(tcx, placeholder_types.into_iter().chain(additional_spans).collect(), kind);
213
214     // Suggest, but only if it is not a function in const or static
215     if suggest {
216         let mut is_fn = false;
217         let mut is_const_or_static = false;
218
219         if let Some(hir_ty) = hir_ty && let hir::TyKind::BareFn(_) = hir_ty.kind {
220             is_fn = true;
221
222             // Check if parent is const or static
223             let parent_id = tcx.hir().get_parent_node(hir_ty.hir_id);
224             let parent_node = tcx.hir().get(parent_id);
225
226             is_const_or_static = matches!(
227                 parent_node,
228                 Node::Item(&hir::Item {
229                     kind: hir::ItemKind::Const(..) | hir::ItemKind::Static(..),
230                     ..
231                 }) | Node::TraitItem(&hir::TraitItem {
232                     kind: hir::TraitItemKind::Const(..),
233                     ..
234                 }) | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Const(..), .. })
235             );
236         }
237
238         // if function is wrapped around a const or static,
239         // then don't show the suggestion
240         if !(is_fn && is_const_or_static) {
241             err.multipart_suggestion(
242                 "use type parameters instead",
243                 sugg,
244                 Applicability::HasPlaceholders,
245             );
246         }
247     }
248
249     err
250 }
251
252 fn reject_placeholder_type_signatures_in_item<'tcx>(
253     tcx: TyCtxt<'tcx>,
254     item: &'tcx hir::Item<'tcx>,
255 ) {
256     let (generics, suggest) = match &item.kind {
257         hir::ItemKind::Union(_, generics)
258         | hir::ItemKind::Enum(_, generics)
259         | hir::ItemKind::TraitAlias(generics, _)
260         | hir::ItemKind::Trait(_, _, generics, ..)
261         | hir::ItemKind::Impl(hir::Impl { generics, .. })
262         | hir::ItemKind::Struct(_, generics) => (generics, true),
263         hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. })
264         | hir::ItemKind::TyAlias(_, generics) => (generics, false),
265         // `static`, `fn` and `const` are handled elsewhere to suggest appropriate type.
266         _ => return,
267     };
268
269     let mut visitor = HirPlaceholderCollector::default();
270     visitor.visit_item(item);
271
272     placeholder_type_error(tcx, Some(generics), visitor.0, suggest, None, item.kind.descr());
273 }
274
275 impl<'tcx> Visitor<'tcx> for CollectItemTypesVisitor<'tcx> {
276     type NestedFilter = nested_filter::OnlyBodies;
277
278     fn nested_visit_map(&mut self) -> Self::Map {
279         self.tcx.hir()
280     }
281
282     fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
283         convert_item(self.tcx, item.item_id());
284         reject_placeholder_type_signatures_in_item(self.tcx, item);
285         intravisit::walk_item(self, item);
286     }
287
288     fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
289         for param in generics.params {
290             match param.kind {
291                 hir::GenericParamKind::Lifetime { .. } => {}
292                 hir::GenericParamKind::Type { default: Some(_), .. } => {
293                     let def_id = self.tcx.hir().local_def_id(param.hir_id);
294                     self.tcx.ensure().type_of(def_id);
295                 }
296                 hir::GenericParamKind::Type { .. } => {}
297                 hir::GenericParamKind::Const { default, .. } => {
298                     let def_id = self.tcx.hir().local_def_id(param.hir_id);
299                     self.tcx.ensure().type_of(def_id);
300                     if let Some(default) = default {
301                         let default_def_id = self.tcx.hir().local_def_id(default.hir_id);
302                         // need to store default and type of default
303                         self.tcx.ensure().type_of(default_def_id);
304                         self.tcx.ensure().const_param_default(def_id);
305                     }
306                 }
307             }
308         }
309         intravisit::walk_generics(self, generics);
310     }
311
312     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
313         if let hir::ExprKind::Closure { .. } = expr.kind {
314             let def_id = self.tcx.hir().local_def_id(expr.hir_id);
315             self.tcx.ensure().generics_of(def_id);
316             // We do not call `type_of` for closures here as that
317             // depends on typecheck and would therefore hide
318             // any further errors in case one typeck fails.
319         }
320         intravisit::walk_expr(self, expr);
321     }
322
323     fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
324         convert_trait_item(self.tcx, trait_item.trait_item_id());
325         intravisit::walk_trait_item(self, trait_item);
326     }
327
328     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
329         convert_impl_item(self.tcx, impl_item.impl_item_id());
330         intravisit::walk_impl_item(self, impl_item);
331     }
332 }
333
334 ///////////////////////////////////////////////////////////////////////////
335 // Utility types and common code for the above passes.
336
337 fn bad_placeholder<'tcx>(
338     tcx: TyCtxt<'tcx>,
339     mut spans: Vec<Span>,
340     kind: &'static str,
341 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
342     let kind = if kind.ends_with('s') { format!("{}es", kind) } else { format!("{}s", kind) };
343
344     spans.sort();
345     let mut err = struct_span_err!(
346         tcx.sess,
347         spans.clone(),
348         E0121,
349         "the placeholder `_` is not allowed within types on item signatures for {}",
350         kind
351     );
352     for span in spans {
353         err.span_label(span, "not allowed in type signatures");
354     }
355     err
356 }
357
358 impl<'tcx> ItemCtxt<'tcx> {
359     pub fn new(tcx: TyCtxt<'tcx>, item_def_id: DefId) -> ItemCtxt<'tcx> {
360         ItemCtxt { tcx, item_def_id }
361     }
362
363     pub fn to_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
364         <dyn AstConv<'_>>::ast_ty_to_ty(self, ast_ty)
365     }
366
367     pub fn hir_id(&self) -> hir::HirId {
368         self.tcx.hir().local_def_id_to_hir_id(self.item_def_id.expect_local())
369     }
370
371     pub fn node(&self) -> hir::Node<'tcx> {
372         self.tcx.hir().get(self.hir_id())
373     }
374 }
375
376 impl<'tcx> AstConv<'tcx> for ItemCtxt<'tcx> {
377     fn tcx(&self) -> TyCtxt<'tcx> {
378         self.tcx
379     }
380
381     fn item_def_id(&self) -> Option<DefId> {
382         Some(self.item_def_id)
383     }
384
385     fn get_type_parameter_bounds(
386         &self,
387         span: Span,
388         def_id: DefId,
389         assoc_name: Ident,
390     ) -> ty::GenericPredicates<'tcx> {
391         self.tcx.at(span).type_param_predicates((
392             self.item_def_id,
393             def_id.expect_local(),
394             assoc_name,
395         ))
396     }
397
398     fn re_infer(&self, _: Option<&ty::GenericParamDef>, _: Span) -> Option<ty::Region<'tcx>> {
399         None
400     }
401
402     fn allow_ty_infer(&self) -> bool {
403         false
404     }
405
406     fn ty_infer(&self, _: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx> {
407         self.tcx().ty_error_with_message(span, "bad placeholder type")
408     }
409
410     fn ct_infer(&self, ty: Ty<'tcx>, _: Option<&ty::GenericParamDef>, span: Span) -> Const<'tcx> {
411         let ty = self.tcx.fold_regions(ty, |r, _| match *r {
412             ty::ReErased => self.tcx.lifetimes.re_static,
413             _ => r,
414         });
415         self.tcx().const_error_with_message(ty, span, "bad placeholder constant")
416     }
417
418     fn projected_ty_from_poly_trait_ref(
419         &self,
420         span: Span,
421         item_def_id: DefId,
422         item_segment: &hir::PathSegment<'_>,
423         poly_trait_ref: ty::PolyTraitRef<'tcx>,
424     ) -> Ty<'tcx> {
425         if let Some(trait_ref) = poly_trait_ref.no_bound_vars() {
426             let item_substs = <dyn AstConv<'tcx>>::create_substs_for_associated_item(
427                 self,
428                 span,
429                 item_def_id,
430                 item_segment,
431                 trait_ref.substs,
432             );
433             self.tcx().mk_projection(item_def_id, item_substs)
434         } else {
435             // There are no late-bound regions; we can just ignore the binder.
436             let mut err = struct_span_err!(
437                 self.tcx().sess,
438                 span,
439                 E0212,
440                 "cannot use the associated type of a trait \
441                  with uninferred generic parameters"
442             );
443
444             match self.node() {
445                 hir::Node::Field(_) | hir::Node::Ctor(_) | hir::Node::Variant(_) => {
446                     let item = self
447                         .tcx
448                         .hir()
449                         .expect_item(self.tcx.hir().get_parent_item(self.hir_id()).def_id);
450                     match &item.kind {
451                         hir::ItemKind::Enum(_, generics)
452                         | hir::ItemKind::Struct(_, generics)
453                         | hir::ItemKind::Union(_, generics) => {
454                             let lt_name = get_new_lifetime_name(self.tcx, poly_trait_ref, generics);
455                             let (lt_sp, sugg) = match generics.params {
456                                 [] => (generics.span, format!("<{}>", lt_name)),
457                                 [bound, ..] => {
458                                     (bound.span.shrink_to_lo(), format!("{}, ", lt_name))
459                                 }
460                             };
461                             let suggestions = vec![
462                                 (lt_sp, sugg),
463                                 (
464                                     span.with_hi(item_segment.ident.span.lo()),
465                                     format!(
466                                         "{}::",
467                                         // Replace the existing lifetimes with a new named lifetime.
468                                         self.tcx.replace_late_bound_regions_uncached(
469                                             poly_trait_ref,
470                                             |_| {
471                                                 self.tcx.mk_region(ty::ReEarlyBound(
472                                                     ty::EarlyBoundRegion {
473                                                         def_id: item_def_id,
474                                                         index: 0,
475                                                         name: Symbol::intern(&lt_name),
476                                                     },
477                                                 ))
478                                             }
479                                         ),
480                                     ),
481                                 ),
482                             ];
483                             err.multipart_suggestion(
484                                 "use a fully qualified path with explicit lifetimes",
485                                 suggestions,
486                                 Applicability::MaybeIncorrect,
487                             );
488                         }
489                         _ => {}
490                     }
491                 }
492                 hir::Node::Item(hir::Item {
493                     kind:
494                         hir::ItemKind::Struct(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Union(..),
495                     ..
496                 }) => {}
497                 hir::Node::Item(_)
498                 | hir::Node::ForeignItem(_)
499                 | hir::Node::TraitItem(_)
500                 | hir::Node::ImplItem(_) => {
501                     err.span_suggestion_verbose(
502                         span.with_hi(item_segment.ident.span.lo()),
503                         "use a fully qualified path with inferred lifetimes",
504                         format!(
505                             "{}::",
506                             // Erase named lt, we want `<A as B<'_>::C`, not `<A as B<'a>::C`.
507                             self.tcx.anonymize_late_bound_regions(poly_trait_ref).skip_binder(),
508                         ),
509                         Applicability::MaybeIncorrect,
510                     );
511                 }
512                 _ => {}
513             }
514             err.emit();
515             self.tcx().ty_error()
516         }
517     }
518
519     fn normalize_ty(&self, _span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
520         // Types in item signatures are not normalized to avoid undue dependencies.
521         ty
522     }
523
524     fn set_tainted_by_errors(&self) {
525         // There's no obvious place to track this, so just let it go.
526     }
527
528     fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) {
529         // There's no place to record types from signatures?
530     }
531 }
532
533 /// Synthesize a new lifetime name that doesn't clash with any of the lifetimes already present.
534 fn get_new_lifetime_name<'tcx>(
535     tcx: TyCtxt<'tcx>,
536     poly_trait_ref: ty::PolyTraitRef<'tcx>,
537     generics: &hir::Generics<'tcx>,
538 ) -> String {
539     let existing_lifetimes = tcx
540         .collect_referenced_late_bound_regions(&poly_trait_ref)
541         .into_iter()
542         .filter_map(|lt| {
543             if let ty::BoundRegionKind::BrNamed(_, name) = lt {
544                 Some(name.as_str().to_string())
545             } else {
546                 None
547             }
548         })
549         .chain(generics.params.iter().filter_map(|param| {
550             if let hir::GenericParamKind::Lifetime { .. } = &param.kind {
551                 Some(param.name.ident().as_str().to_string())
552             } else {
553                 None
554             }
555         }))
556         .collect::<FxHashSet<String>>();
557
558     let a_to_z_repeat_n = |n| {
559         (b'a'..=b'z').map(move |c| {
560             let mut s = '\''.to_string();
561             s.extend(std::iter::repeat(char::from(c)).take(n));
562             s
563         })
564     };
565
566     // If all single char lifetime names are present, we wrap around and double the chars.
567     (1..).flat_map(a_to_z_repeat_n).find(|lt| !existing_lifetimes.contains(lt.as_str())).unwrap()
568 }
569
570 fn convert_item(tcx: TyCtxt<'_>, item_id: hir::ItemId) {
571     let it = tcx.hir().item(item_id);
572     debug!("convert: item {} with id {}", it.ident, it.hir_id());
573     let def_id = item_id.def_id.def_id;
574
575     match it.kind {
576         // These don't define types.
577         hir::ItemKind::ExternCrate(_)
578         | hir::ItemKind::Use(..)
579         | hir::ItemKind::Macro(..)
580         | hir::ItemKind::Mod(_)
581         | hir::ItemKind::GlobalAsm(_) => {}
582         hir::ItemKind::ForeignMod { items, .. } => {
583             for item in items {
584                 let item = tcx.hir().foreign_item(item.id);
585                 tcx.ensure().generics_of(item.def_id);
586                 tcx.ensure().type_of(item.def_id);
587                 tcx.ensure().predicates_of(item.def_id);
588                 match item.kind {
589                     hir::ForeignItemKind::Fn(..) => tcx.ensure().fn_sig(item.def_id),
590                     hir::ForeignItemKind::Static(..) => {
591                         let mut visitor = HirPlaceholderCollector::default();
592                         visitor.visit_foreign_item(item);
593                         placeholder_type_error(
594                             tcx,
595                             None,
596                             visitor.0,
597                             false,
598                             None,
599                             "static variable",
600                         );
601                     }
602                     _ => (),
603                 }
604             }
605         }
606         hir::ItemKind::Enum(ref enum_definition, _) => {
607             tcx.ensure().generics_of(def_id);
608             tcx.ensure().type_of(def_id);
609             tcx.ensure().predicates_of(def_id);
610             convert_enum_variant_types(tcx, def_id.to_def_id(), enum_definition.variants);
611         }
612         hir::ItemKind::Impl { .. } => {
613             tcx.ensure().generics_of(def_id);
614             tcx.ensure().type_of(def_id);
615             tcx.ensure().impl_trait_ref(def_id);
616             tcx.ensure().predicates_of(def_id);
617         }
618         hir::ItemKind::Trait(..) => {
619             tcx.ensure().generics_of(def_id);
620             tcx.ensure().trait_def(def_id);
621             tcx.at(it.span).super_predicates_of(def_id);
622             tcx.ensure().predicates_of(def_id);
623         }
624         hir::ItemKind::TraitAlias(..) => {
625             tcx.ensure().generics_of(def_id);
626             tcx.at(it.span).super_predicates_of(def_id);
627             tcx.ensure().predicates_of(def_id);
628         }
629         hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
630             tcx.ensure().generics_of(def_id);
631             tcx.ensure().type_of(def_id);
632             tcx.ensure().predicates_of(def_id);
633
634             for f in struct_def.fields() {
635                 let def_id = tcx.hir().local_def_id(f.hir_id);
636                 tcx.ensure().generics_of(def_id);
637                 tcx.ensure().type_of(def_id);
638                 tcx.ensure().predicates_of(def_id);
639             }
640
641             if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
642                 convert_variant_ctor(tcx, ctor_hir_id);
643             }
644         }
645
646         // Desugared from `impl Trait`, so visited by the function's return type.
647         hir::ItemKind::OpaqueTy(hir::OpaqueTy {
648             origin: hir::OpaqueTyOrigin::FnReturn(..) | hir::OpaqueTyOrigin::AsyncFn(..),
649             ..
650         }) => {}
651
652         // Don't call `type_of` on opaque types, since that depends on type
653         // checking function bodies. `check_item_type` ensures that it's called
654         // instead.
655         hir::ItemKind::OpaqueTy(..) => {
656             tcx.ensure().generics_of(def_id);
657             tcx.ensure().predicates_of(def_id);
658             tcx.ensure().explicit_item_bounds(def_id);
659         }
660         hir::ItemKind::TyAlias(..)
661         | hir::ItemKind::Static(..)
662         | hir::ItemKind::Const(..)
663         | hir::ItemKind::Fn(..) => {
664             tcx.ensure().generics_of(def_id);
665             tcx.ensure().type_of(def_id);
666             tcx.ensure().predicates_of(def_id);
667             match it.kind {
668                 hir::ItemKind::Fn(..) => tcx.ensure().fn_sig(def_id),
669                 hir::ItemKind::OpaqueTy(..) => tcx.ensure().item_bounds(def_id),
670                 hir::ItemKind::Const(ty, ..) | hir::ItemKind::Static(ty, ..) => {
671                     if !is_suggestable_infer_ty(ty) {
672                         let mut visitor = HirPlaceholderCollector::default();
673                         visitor.visit_item(it);
674                         placeholder_type_error(tcx, None, visitor.0, false, None, it.kind.descr());
675                     }
676                 }
677                 _ => (),
678             }
679         }
680     }
681 }
682
683 fn convert_trait_item(tcx: TyCtxt<'_>, trait_item_id: hir::TraitItemId) {
684     let trait_item = tcx.hir().trait_item(trait_item_id);
685     let def_id = trait_item_id.def_id;
686     tcx.ensure().generics_of(def_id);
687
688     match trait_item.kind {
689         hir::TraitItemKind::Fn(..) => {
690             tcx.ensure().type_of(def_id);
691             tcx.ensure().fn_sig(def_id);
692         }
693
694         hir::TraitItemKind::Const(.., Some(_)) => {
695             tcx.ensure().type_of(def_id);
696         }
697
698         hir::TraitItemKind::Const(hir_ty, _) => {
699             tcx.ensure().type_of(def_id);
700             // Account for `const C: _;`.
701             let mut visitor = HirPlaceholderCollector::default();
702             visitor.visit_trait_item(trait_item);
703             if !tcx.sess.diagnostic().has_stashed_diagnostic(hir_ty.span, StashKey::ItemNoType) {
704                 placeholder_type_error(tcx, None, visitor.0, false, None, "constant");
705             }
706         }
707
708         hir::TraitItemKind::Type(_, Some(_)) => {
709             tcx.ensure().item_bounds(def_id);
710             tcx.ensure().type_of(def_id);
711             // Account for `type T = _;`.
712             let mut visitor = HirPlaceholderCollector::default();
713             visitor.visit_trait_item(trait_item);
714             placeholder_type_error(tcx, None, visitor.0, false, None, "associated type");
715         }
716
717         hir::TraitItemKind::Type(_, None) => {
718             tcx.ensure().item_bounds(def_id);
719             // #74612: Visit and try to find bad placeholders
720             // even if there is no concrete type.
721             let mut visitor = HirPlaceholderCollector::default();
722             visitor.visit_trait_item(trait_item);
723
724             placeholder_type_error(tcx, None, visitor.0, false, None, "associated type");
725         }
726     };
727
728     tcx.ensure().predicates_of(def_id);
729 }
730
731 fn convert_impl_item(tcx: TyCtxt<'_>, impl_item_id: hir::ImplItemId) {
732     let def_id = impl_item_id.def_id;
733     tcx.ensure().generics_of(def_id);
734     tcx.ensure().type_of(def_id);
735     tcx.ensure().predicates_of(def_id);
736     let impl_item = tcx.hir().impl_item(impl_item_id);
737     match impl_item.kind {
738         hir::ImplItemKind::Fn(..) => {
739             tcx.ensure().fn_sig(def_id);
740         }
741         hir::ImplItemKind::Type(_) => {
742             // Account for `type T = _;`
743             let mut visitor = HirPlaceholderCollector::default();
744             visitor.visit_impl_item(impl_item);
745
746             placeholder_type_error(tcx, None, visitor.0, false, None, "associated type");
747         }
748         hir::ImplItemKind::Const(..) => {}
749     }
750 }
751
752 fn convert_variant_ctor(tcx: TyCtxt<'_>, ctor_id: hir::HirId) {
753     let def_id = tcx.hir().local_def_id(ctor_id);
754     tcx.ensure().generics_of(def_id);
755     tcx.ensure().type_of(def_id);
756     tcx.ensure().predicates_of(def_id);
757 }
758
759 fn convert_enum_variant_types(tcx: TyCtxt<'_>, def_id: DefId, variants: &[hir::Variant<'_>]) {
760     let def = tcx.adt_def(def_id);
761     let repr_type = def.repr().discr_type();
762     let initial = repr_type.initial_discriminant(tcx);
763     let mut prev_discr = None::<Discr<'_>>;
764
765     // fill the discriminant values and field types
766     for variant in variants {
767         let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
768         prev_discr = Some(
769             if let Some(ref e) = variant.disr_expr {
770                 let expr_did = tcx.hir().local_def_id(e.hir_id);
771                 def.eval_explicit_discr(tcx, expr_did.to_def_id())
772             } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) {
773                 Some(discr)
774             } else {
775                 struct_span_err!(tcx.sess, variant.span, E0370, "enum discriminant overflowed")
776                     .span_label(
777                         variant.span,
778                         format!("overflowed on value after {}", prev_discr.unwrap()),
779                     )
780                     .note(&format!(
781                         "explicitly set `{} = {}` if that is desired outcome",
782                         variant.ident, wrapped_discr
783                     ))
784                     .emit();
785                 None
786             }
787             .unwrap_or(wrapped_discr),
788         );
789
790         for f in variant.data.fields() {
791             let def_id = tcx.hir().local_def_id(f.hir_id);
792             tcx.ensure().generics_of(def_id);
793             tcx.ensure().type_of(def_id);
794             tcx.ensure().predicates_of(def_id);
795         }
796
797         // Convert the ctor, if any. This also registers the variant as
798         // an item.
799         if let Some(ctor_hir_id) = variant.data.ctor_hir_id() {
800             convert_variant_ctor(tcx, ctor_hir_id);
801         }
802     }
803 }
804
805 fn convert_variant(
806     tcx: TyCtxt<'_>,
807     variant_did: Option<LocalDefId>,
808     ctor_did: Option<LocalDefId>,
809     ident: Ident,
810     discr: ty::VariantDiscr,
811     def: &hir::VariantData<'_>,
812     adt_kind: ty::AdtKind,
813     parent_did: LocalDefId,
814 ) -> ty::VariantDef {
815     let mut seen_fields: FxHashMap<Ident, Span> = Default::default();
816     let fields = def
817         .fields()
818         .iter()
819         .map(|f| {
820             let fid = tcx.hir().local_def_id(f.hir_id);
821             let dup_span = seen_fields.get(&f.ident.normalize_to_macros_2_0()).cloned();
822             if let Some(prev_span) = dup_span {
823                 tcx.sess.emit_err(errors::FieldAlreadyDeclared {
824                     field_name: f.ident,
825                     span: f.span,
826                     prev_span,
827                 });
828             } else {
829                 seen_fields.insert(f.ident.normalize_to_macros_2_0(), f.span);
830             }
831
832             ty::FieldDef { did: fid.to_def_id(), name: f.ident.name, vis: tcx.visibility(fid) }
833         })
834         .collect();
835     let recovered = match def {
836         hir::VariantData::Struct(_, r) => *r,
837         _ => false,
838     };
839     ty::VariantDef::new(
840         ident.name,
841         variant_did.map(LocalDefId::to_def_id),
842         ctor_did.map(LocalDefId::to_def_id),
843         discr,
844         fields,
845         CtorKind::from_hir(def),
846         adt_kind,
847         parent_did.to_def_id(),
848         recovered,
849         adt_kind == AdtKind::Struct && tcx.has_attr(parent_did.to_def_id(), sym::non_exhaustive)
850             || variant_did.map_or(false, |variant_did| {
851                 tcx.has_attr(variant_did.to_def_id(), sym::non_exhaustive)
852             }),
853     )
854 }
855
856 fn adt_def<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> ty::AdtDef<'tcx> {
857     use rustc_hir::*;
858
859     let def_id = def_id.expect_local();
860     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
861     let Node::Item(item) = tcx.hir().get(hir_id) else {
862         bug!();
863     };
864
865     let repr = ReprOptions::new(tcx, def_id.to_def_id());
866     let (kind, variants) = match item.kind {
867         ItemKind::Enum(ref def, _) => {
868             let mut distance_from_explicit = 0;
869             let variants = def
870                 .variants
871                 .iter()
872                 .map(|v| {
873                     let variant_did = Some(tcx.hir().local_def_id(v.id));
874                     let ctor_did =
875                         v.data.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
876
877                     let discr = if let Some(ref e) = v.disr_expr {
878                         distance_from_explicit = 0;
879                         ty::VariantDiscr::Explicit(tcx.hir().local_def_id(e.hir_id).to_def_id())
880                     } else {
881                         ty::VariantDiscr::Relative(distance_from_explicit)
882                     };
883                     distance_from_explicit += 1;
884
885                     convert_variant(
886                         tcx,
887                         variant_did,
888                         ctor_did,
889                         v.ident,
890                         discr,
891                         &v.data,
892                         AdtKind::Enum,
893                         def_id,
894                     )
895                 })
896                 .collect();
897
898             (AdtKind::Enum, variants)
899         }
900         ItemKind::Struct(ref def, _) => {
901             let variant_did = None::<LocalDefId>;
902             let ctor_did = def.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
903
904             let variants = std::iter::once(convert_variant(
905                 tcx,
906                 variant_did,
907                 ctor_did,
908                 item.ident,
909                 ty::VariantDiscr::Relative(0),
910                 def,
911                 AdtKind::Struct,
912                 def_id,
913             ))
914             .collect();
915
916             (AdtKind::Struct, variants)
917         }
918         ItemKind::Union(ref def, _) => {
919             let variant_did = None;
920             let ctor_did = def.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
921
922             let variants = std::iter::once(convert_variant(
923                 tcx,
924                 variant_did,
925                 ctor_did,
926                 item.ident,
927                 ty::VariantDiscr::Relative(0),
928                 def,
929                 AdtKind::Union,
930                 def_id,
931             ))
932             .collect();
933
934             (AdtKind::Union, variants)
935         }
936         _ => bug!(),
937     };
938     tcx.alloc_adt_def(def_id.to_def_id(), kind, variants, repr)
939 }
940
941 fn trait_def(tcx: TyCtxt<'_>, def_id: DefId) -> ty::TraitDef {
942     let item = tcx.hir().expect_item(def_id.expect_local());
943
944     let (is_auto, unsafety, items) = match item.kind {
945         hir::ItemKind::Trait(is_auto, unsafety, .., items) => {
946             (is_auto == hir::IsAuto::Yes, unsafety, items)
947         }
948         hir::ItemKind::TraitAlias(..) => (false, hir::Unsafety::Normal, &[][..]),
949         _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
950     };
951
952     let paren_sugar = tcx.has_attr(def_id, sym::rustc_paren_sugar);
953     if paren_sugar && !tcx.features().unboxed_closures {
954         tcx.sess
955             .struct_span_err(
956                 item.span,
957                 "the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \
958                  which traits can use parenthetical notation",
959             )
960             .help("add `#![feature(unboxed_closures)]` to the crate attributes to use it")
961             .emit();
962     }
963
964     let is_marker = tcx.has_attr(def_id, sym::marker);
965     let skip_array_during_method_dispatch =
966         tcx.has_attr(def_id, sym::rustc_skip_array_during_method_dispatch);
967     let spec_kind = if tcx.has_attr(def_id, sym::rustc_unsafe_specialization_marker) {
968         ty::trait_def::TraitSpecializationKind::Marker
969     } else if tcx.has_attr(def_id, sym::rustc_specialization_trait) {
970         ty::trait_def::TraitSpecializationKind::AlwaysApplicable
971     } else {
972         ty::trait_def::TraitSpecializationKind::None
973     };
974     let must_implement_one_of = tcx
975         .get_attr(def_id, sym::rustc_must_implement_one_of)
976         // Check that there are at least 2 arguments of `#[rustc_must_implement_one_of]`
977         // and that they are all identifiers
978         .and_then(|attr| match attr.meta_item_list() {
979             Some(items) if items.len() < 2 => {
980                 tcx.sess
981                     .struct_span_err(
982                         attr.span,
983                         "the `#[rustc_must_implement_one_of]` attribute must be \
984                         used with at least 2 args",
985                     )
986                     .emit();
987
988                 None
989             }
990             Some(items) => items
991                 .into_iter()
992                 .map(|item| item.ident().ok_or(item.span()))
993                 .collect::<Result<Box<[_]>, _>>()
994                 .map_err(|span| {
995                     tcx.sess
996                         .struct_span_err(span, "must be a name of an associated function")
997                         .emit();
998                 })
999                 .ok()
1000                 .zip(Some(attr.span)),
1001             // Error is reported by `rustc_attr!`
1002             None => None,
1003         })
1004         // Check that all arguments of `#[rustc_must_implement_one_of]` reference
1005         // functions in the trait with default implementations
1006         .and_then(|(list, attr_span)| {
1007             let errors = list.iter().filter_map(|ident| {
1008                 let item = items.iter().find(|item| item.ident == *ident);
1009
1010                 match item {
1011                     Some(item) if matches!(item.kind, hir::AssocItemKind::Fn { .. }) => {
1012                         if !tcx.impl_defaultness(item.id.def_id).has_value() {
1013                             tcx.sess
1014                                 .struct_span_err(
1015                                     item.span,
1016                                     "This function doesn't have a default implementation",
1017                                 )
1018                                 .span_note(attr_span, "required by this annotation")
1019                                 .emit();
1020
1021                             return Some(());
1022                         }
1023
1024                         return None;
1025                     }
1026                     Some(item) => {
1027                         tcx.sess
1028                             .struct_span_err(item.span, "Not a function")
1029                             .span_note(attr_span, "required by this annotation")
1030                             .note(
1031                                 "All `#[rustc_must_implement_one_of]` arguments \
1032                             must be associated function names",
1033                             )
1034                             .emit();
1035                     }
1036                     None => {
1037                         tcx.sess
1038                             .struct_span_err(ident.span, "Function not found in this trait")
1039                             .emit();
1040                     }
1041                 }
1042
1043                 Some(())
1044             });
1045
1046             (errors.count() == 0).then_some(list)
1047         })
1048         // Check for duplicates
1049         .and_then(|list| {
1050             let mut set: FxHashMap<Symbol, Span> = FxHashMap::default();
1051             let mut no_dups = true;
1052
1053             for ident in &*list {
1054                 if let Some(dup) = set.insert(ident.name, ident.span) {
1055                     tcx.sess
1056                         .struct_span_err(vec![dup, ident.span], "Functions names are duplicated")
1057                         .note(
1058                             "All `#[rustc_must_implement_one_of]` arguments \
1059                             must be unique",
1060                         )
1061                         .emit();
1062
1063                     no_dups = false;
1064                 }
1065             }
1066
1067             no_dups.then_some(list)
1068         });
1069
1070     ty::TraitDef::new(
1071         def_id,
1072         unsafety,
1073         paren_sugar,
1074         is_auto,
1075         is_marker,
1076         skip_array_during_method_dispatch,
1077         spec_kind,
1078         must_implement_one_of,
1079     )
1080 }
1081
1082 fn are_suggestable_generic_args(generic_args: &[hir::GenericArg<'_>]) -> bool {
1083     generic_args.iter().any(|arg| match arg {
1084         hir::GenericArg::Type(ty) => is_suggestable_infer_ty(ty),
1085         hir::GenericArg::Infer(_) => true,
1086         _ => false,
1087     })
1088 }
1089
1090 /// Whether `ty` is a type with `_` placeholders that can be inferred. Used in diagnostics only to
1091 /// use inference to provide suggestions for the appropriate type if possible.
1092 fn is_suggestable_infer_ty(ty: &hir::Ty<'_>) -> bool {
1093     debug!(?ty);
1094     use hir::TyKind::*;
1095     match &ty.kind {
1096         Infer => true,
1097         Slice(ty) => is_suggestable_infer_ty(ty),
1098         Array(ty, length) => {
1099             is_suggestable_infer_ty(ty) || matches!(length, hir::ArrayLen::Infer(_, _))
1100         }
1101         Tup(tys) => tys.iter().any(is_suggestable_infer_ty),
1102         Ptr(mut_ty) | Rptr(_, mut_ty) => is_suggestable_infer_ty(mut_ty.ty),
1103         OpaqueDef(_, generic_args, _) => are_suggestable_generic_args(generic_args),
1104         Path(hir::QPath::TypeRelative(ty, segment)) => {
1105             is_suggestable_infer_ty(ty) || are_suggestable_generic_args(segment.args().args)
1106         }
1107         Path(hir::QPath::Resolved(ty_opt, hir::Path { segments, .. })) => {
1108             ty_opt.map_or(false, is_suggestable_infer_ty)
1109                 || segments.iter().any(|segment| are_suggestable_generic_args(segment.args().args))
1110         }
1111         _ => false,
1112     }
1113 }
1114
1115 pub fn get_infer_ret_ty<'hir>(output: &'hir hir::FnRetTy<'hir>) -> Option<&'hir hir::Ty<'hir>> {
1116     if let hir::FnRetTy::Return(ty) = output {
1117         if is_suggestable_infer_ty(ty) {
1118             return Some(&*ty);
1119         }
1120     }
1121     None
1122 }
1123
1124 #[instrument(level = "debug", skip(tcx))]
1125 fn fn_sig(tcx: TyCtxt<'_>, def_id: DefId) -> ty::PolyFnSig<'_> {
1126     use rustc_hir::Node::*;
1127     use rustc_hir::*;
1128
1129     let def_id = def_id.expect_local();
1130     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
1131
1132     let icx = ItemCtxt::new(tcx, def_id.to_def_id());
1133
1134     match tcx.hir().get(hir_id) {
1135         TraitItem(hir::TraitItem {
1136             kind: TraitItemKind::Fn(sig, TraitFn::Provided(_)),
1137             generics,
1138             ..
1139         })
1140         | Item(hir::Item { kind: ItemKind::Fn(sig, generics, _), .. }) => {
1141             infer_return_ty_for_fn_sig(tcx, sig, generics, def_id, &icx)
1142         }
1143
1144         ImplItem(hir::ImplItem { kind: ImplItemKind::Fn(sig, _), generics, .. }) => {
1145             // Do not try to inference the return type for a impl method coming from a trait
1146             if let Item(hir::Item { kind: ItemKind::Impl(i), .. }) =
1147                 tcx.hir().get(tcx.hir().get_parent_node(hir_id))
1148                 && i.of_trait.is_some()
1149             {
1150                 <dyn AstConv<'_>>::ty_of_fn(
1151                     &icx,
1152                     hir_id,
1153                     sig.header.unsafety,
1154                     sig.header.abi,
1155                     sig.decl,
1156                     Some(generics),
1157                     None,
1158                 )
1159             } else {
1160                 infer_return_ty_for_fn_sig(tcx, sig, generics, def_id, &icx)
1161             }
1162         }
1163
1164         TraitItem(hir::TraitItem {
1165             kind: TraitItemKind::Fn(FnSig { header, decl, span: _ }, _),
1166             generics,
1167             ..
1168         }) => <dyn AstConv<'_>>::ty_of_fn(
1169             &icx,
1170             hir_id,
1171             header.unsafety,
1172             header.abi,
1173             decl,
1174             Some(generics),
1175             None,
1176         ),
1177
1178         ForeignItem(&hir::ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
1179             let abi = tcx.hir().get_foreign_abi(hir_id);
1180             compute_sig_of_foreign_fn_decl(tcx, def_id.to_def_id(), fn_decl, abi)
1181         }
1182
1183         Ctor(data) | Variant(hir::Variant { data, .. }) if data.ctor_hir_id().is_some() => {
1184             let ty = tcx.type_of(tcx.hir().get_parent_item(hir_id));
1185             let inputs =
1186                 data.fields().iter().map(|f| tcx.type_of(tcx.hir().local_def_id(f.hir_id)));
1187             ty::Binder::dummy(tcx.mk_fn_sig(
1188                 inputs,
1189                 ty,
1190                 false,
1191                 hir::Unsafety::Normal,
1192                 abi::Abi::Rust,
1193             ))
1194         }
1195
1196         Expr(&hir::Expr { kind: hir::ExprKind::Closure { .. }, .. }) => {
1197             // Closure signatures are not like other function
1198             // signatures and cannot be accessed through `fn_sig`. For
1199             // example, a closure signature excludes the `self`
1200             // argument. In any case they are embedded within the
1201             // closure type as part of the `ClosureSubsts`.
1202             //
1203             // To get the signature of a closure, you should use the
1204             // `sig` method on the `ClosureSubsts`:
1205             //
1206             //    substs.as_closure().sig(def_id, tcx)
1207             bug!(
1208                 "to get the signature of a closure, use `substs.as_closure().sig()` not `fn_sig()`",
1209             );
1210         }
1211
1212         x => {
1213             bug!("unexpected sort of node in fn_sig(): {:?}", x);
1214         }
1215     }
1216 }
1217
1218 fn infer_return_ty_for_fn_sig<'tcx>(
1219     tcx: TyCtxt<'tcx>,
1220     sig: &hir::FnSig<'_>,
1221     generics: &hir::Generics<'_>,
1222     def_id: LocalDefId,
1223     icx: &ItemCtxt<'tcx>,
1224 ) -> ty::PolyFnSig<'tcx> {
1225     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
1226
1227     match get_infer_ret_ty(&sig.decl.output) {
1228         Some(ty) => {
1229             let fn_sig = tcx.typeck(def_id).liberated_fn_sigs()[hir_id];
1230             // Typeck doesn't expect erased regions to be returned from `type_of`.
1231             let fn_sig = tcx.fold_regions(fn_sig, |r, _| match *r {
1232                 ty::ReErased => tcx.lifetimes.re_static,
1233                 _ => r,
1234             });
1235             let fn_sig = ty::Binder::dummy(fn_sig);
1236
1237             let mut visitor = HirPlaceholderCollector::default();
1238             visitor.visit_ty(ty);
1239             let mut diag = bad_placeholder(tcx, visitor.0, "return type");
1240             let ret_ty = fn_sig.skip_binder().output();
1241             if ret_ty.is_suggestable(tcx, false) {
1242                 diag.span_suggestion(
1243                     ty.span,
1244                     "replace with the correct return type",
1245                     ret_ty,
1246                     Applicability::MachineApplicable,
1247                 );
1248             } else if matches!(ret_ty.kind(), ty::FnDef(..)) {
1249                 let fn_sig = ret_ty.fn_sig(tcx);
1250                 if fn_sig
1251                     .skip_binder()
1252                     .inputs_and_output
1253                     .iter()
1254                     .all(|t| t.is_suggestable(tcx, false))
1255                 {
1256                     diag.span_suggestion(
1257                         ty.span,
1258                         "replace with the correct return type",
1259                         fn_sig,
1260                         Applicability::MachineApplicable,
1261                     );
1262                 }
1263             } else if ret_ty.is_closure() {
1264                 // We're dealing with a closure, so we should suggest using `impl Fn` or trait bounds
1265                 // to prevent the user from getting a papercut while trying to use the unique closure
1266                 // syntax (e.g. `[closure@src/lib.rs:2:5: 2:9]`).
1267                 diag.help("consider using an `Fn`, `FnMut`, or `FnOnce` trait bound");
1268                 diag.note("for more information on `Fn` traits and closure types, see https://doc.rust-lang.org/book/ch13-01-closures.html");
1269             }
1270             diag.emit();
1271
1272             fn_sig
1273         }
1274         None => <dyn AstConv<'_>>::ty_of_fn(
1275             icx,
1276             hir_id,
1277             sig.header.unsafety,
1278             sig.header.abi,
1279             sig.decl,
1280             Some(generics),
1281             None,
1282         ),
1283     }
1284 }
1285
1286 fn impl_trait_ref(tcx: TyCtxt<'_>, def_id: DefId) -> Option<ty::TraitRef<'_>> {
1287     let icx = ItemCtxt::new(tcx, def_id);
1288     match tcx.hir().expect_item(def_id.expect_local()).kind {
1289         hir::ItemKind::Impl(ref impl_) => impl_.of_trait.as_ref().map(|ast_trait_ref| {
1290             let selfty = tcx.type_of(def_id);
1291             <dyn AstConv<'_>>::instantiate_mono_trait_ref(&icx, ast_trait_ref, selfty)
1292         }),
1293         _ => bug!(),
1294     }
1295 }
1296
1297 fn impl_polarity(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ImplPolarity {
1298     let is_rustc_reservation = tcx.has_attr(def_id, sym::rustc_reservation_impl);
1299     let item = tcx.hir().expect_item(def_id.expect_local());
1300     match &item.kind {
1301         hir::ItemKind::Impl(hir::Impl {
1302             polarity: hir::ImplPolarity::Negative(span),
1303             of_trait,
1304             ..
1305         }) => {
1306             if is_rustc_reservation {
1307                 let span = span.to(of_trait.as_ref().map_or(*span, |t| t.path.span));
1308                 tcx.sess.span_err(span, "reservation impls can't be negative");
1309             }
1310             ty::ImplPolarity::Negative
1311         }
1312         hir::ItemKind::Impl(hir::Impl {
1313             polarity: hir::ImplPolarity::Positive,
1314             of_trait: None,
1315             ..
1316         }) => {
1317             if is_rustc_reservation {
1318                 tcx.sess.span_err(item.span, "reservation impls can't be inherent");
1319             }
1320             ty::ImplPolarity::Positive
1321         }
1322         hir::ItemKind::Impl(hir::Impl {
1323             polarity: hir::ImplPolarity::Positive,
1324             of_trait: Some(_),
1325             ..
1326         }) => {
1327             if is_rustc_reservation {
1328                 ty::ImplPolarity::Reservation
1329             } else {
1330                 ty::ImplPolarity::Positive
1331             }
1332         }
1333         item => bug!("impl_polarity: {:?} not an impl", item),
1334     }
1335 }
1336
1337 /// Returns the early-bound lifetimes declared in this generics
1338 /// listing. For anything other than fns/methods, this is just all
1339 /// the lifetimes that are declared. For fns or methods, we have to
1340 /// screen out those that do not appear in any where-clauses etc using
1341 /// `resolve_lifetime::early_bound_lifetimes`.
1342 fn early_bound_lifetimes_from_generics<'a, 'tcx: 'a>(
1343     tcx: TyCtxt<'tcx>,
1344     generics: &'a hir::Generics<'a>,
1345 ) -> impl Iterator<Item = &'a hir::GenericParam<'a>> + Captures<'tcx> {
1346     generics.params.iter().filter(move |param| match param.kind {
1347         GenericParamKind::Lifetime { .. } => !tcx.is_late_bound(param.hir_id),
1348         _ => false,
1349     })
1350 }
1351
1352 /// Returns a list of type predicates for the definition with ID `def_id`, including inferred
1353 /// lifetime constraints. This includes all predicates returned by `explicit_predicates_of`, plus
1354 /// inferred constraints concerning which regions outlive other regions.
1355 #[instrument(level = "debug", skip(tcx))]
1356 fn predicates_defined_on(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1357     let mut result = tcx.explicit_predicates_of(def_id);
1358     debug!("predicates_defined_on: explicit_predicates_of({:?}) = {:?}", def_id, result,);
1359     let inferred_outlives = tcx.inferred_outlives_of(def_id);
1360     if !inferred_outlives.is_empty() {
1361         debug!(
1362             "predicates_defined_on: inferred_outlives_of({:?}) = {:?}",
1363             def_id, inferred_outlives,
1364         );
1365         if result.predicates.is_empty() {
1366             result.predicates = inferred_outlives;
1367         } else {
1368             result.predicates = tcx
1369                 .arena
1370                 .alloc_from_iter(result.predicates.iter().chain(inferred_outlives).copied());
1371         }
1372     }
1373
1374     debug!("predicates_defined_on({:?}) = {:?}", def_id, result);
1375     result
1376 }
1377
1378 fn compute_sig_of_foreign_fn_decl<'tcx>(
1379     tcx: TyCtxt<'tcx>,
1380     def_id: DefId,
1381     decl: &'tcx hir::FnDecl<'tcx>,
1382     abi: abi::Abi,
1383 ) -> ty::PolyFnSig<'tcx> {
1384     let unsafety = if abi == abi::Abi::RustIntrinsic {
1385         intrinsic_operation_unsafety(tcx, def_id)
1386     } else {
1387         hir::Unsafety::Unsafe
1388     };
1389     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1390     let fty = <dyn AstConv<'_>>::ty_of_fn(
1391         &ItemCtxt::new(tcx, def_id),
1392         hir_id,
1393         unsafety,
1394         abi,
1395         decl,
1396         None,
1397         None,
1398     );
1399
1400     // Feature gate SIMD types in FFI, since I am not sure that the
1401     // ABIs are handled at all correctly. -huonw
1402     if abi != abi::Abi::RustIntrinsic
1403         && abi != abi::Abi::PlatformIntrinsic
1404         && !tcx.features().simd_ffi
1405     {
1406         let check = |ast_ty: &hir::Ty<'_>, ty: Ty<'_>| {
1407             if ty.is_simd() {
1408                 let snip = tcx
1409                     .sess
1410                     .source_map()
1411                     .span_to_snippet(ast_ty.span)
1412                     .map_or_else(|_| String::new(), |s| format!(" `{}`", s));
1413                 tcx.sess
1414                     .struct_span_err(
1415                         ast_ty.span,
1416                         &format!(
1417                             "use of SIMD type{} in FFI is highly experimental and \
1418                              may result in invalid code",
1419                             snip
1420                         ),
1421                     )
1422                     .help("add `#![feature(simd_ffi)]` to the crate attributes to enable")
1423                     .emit();
1424             }
1425         };
1426         for (input, ty) in iter::zip(decl.inputs, fty.inputs().skip_binder()) {
1427             check(input, *ty)
1428         }
1429         if let hir::FnRetTy::Return(ref ty) = decl.output {
1430             check(ty, fty.output().skip_binder())
1431         }
1432     }
1433
1434     fty
1435 }
1436
1437 fn is_foreign_item(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1438     match tcx.hir().get_if_local(def_id) {
1439         Some(Node::ForeignItem(..)) => true,
1440         Some(_) => false,
1441         _ => bug!("is_foreign_item applied to non-local def-id {:?}", def_id),
1442     }
1443 }
1444
1445 fn generator_kind(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::GeneratorKind> {
1446     match tcx.hir().get_if_local(def_id) {
1447         Some(Node::Expr(&rustc_hir::Expr {
1448             kind: rustc_hir::ExprKind::Closure(&rustc_hir::Closure { body, .. }),
1449             ..
1450         })) => tcx.hir().body(body).generator_kind(),
1451         Some(_) => None,
1452         _ => bug!("generator_kind applied to non-local def-id {:?}", def_id),
1453     }
1454 }
1455
1456 fn from_target_feature(
1457     tcx: TyCtxt<'_>,
1458     attr: &ast::Attribute,
1459     supported_target_features: &FxHashMap<String, Option<Symbol>>,
1460     target_features: &mut Vec<Symbol>,
1461 ) {
1462     let Some(list) = attr.meta_item_list() else { return };
1463     let bad_item = |span| {
1464         let msg = "malformed `target_feature` attribute input";
1465         let code = "enable = \"..\"";
1466         tcx.sess
1467             .struct_span_err(span, msg)
1468             .span_suggestion(span, "must be of the form", code, Applicability::HasPlaceholders)
1469             .emit();
1470     };
1471     let rust_features = tcx.features();
1472     for item in list {
1473         // Only `enable = ...` is accepted in the meta-item list.
1474         if !item.has_name(sym::enable) {
1475             bad_item(item.span());
1476             continue;
1477         }
1478
1479         // Must be of the form `enable = "..."` (a string).
1480         let Some(value) = item.value_str() else {
1481             bad_item(item.span());
1482             continue;
1483         };
1484
1485         // We allow comma separation to enable multiple features.
1486         target_features.extend(value.as_str().split(',').filter_map(|feature| {
1487             let Some(feature_gate) = supported_target_features.get(feature) else {
1488                 let msg =
1489                     format!("the feature named `{}` is not valid for this target", feature);
1490                 let mut err = tcx.sess.struct_span_err(item.span(), &msg);
1491                 err.span_label(
1492                     item.span(),
1493                     format!("`{}` is not valid for this target", feature),
1494                 );
1495                 if let Some(stripped) = feature.strip_prefix('+') {
1496                     let valid = supported_target_features.contains_key(stripped);
1497                     if valid {
1498                         err.help("consider removing the leading `+` in the feature name");
1499                     }
1500                 }
1501                 err.emit();
1502                 return None;
1503             };
1504
1505             // Only allow features whose feature gates have been enabled.
1506             let allowed = match feature_gate.as_ref().copied() {
1507                 Some(sym::arm_target_feature) => rust_features.arm_target_feature,
1508                 Some(sym::hexagon_target_feature) => rust_features.hexagon_target_feature,
1509                 Some(sym::powerpc_target_feature) => rust_features.powerpc_target_feature,
1510                 Some(sym::mips_target_feature) => rust_features.mips_target_feature,
1511                 Some(sym::riscv_target_feature) => rust_features.riscv_target_feature,
1512                 Some(sym::avx512_target_feature) => rust_features.avx512_target_feature,
1513                 Some(sym::sse4a_target_feature) => rust_features.sse4a_target_feature,
1514                 Some(sym::tbm_target_feature) => rust_features.tbm_target_feature,
1515                 Some(sym::wasm_target_feature) => rust_features.wasm_target_feature,
1516                 Some(sym::cmpxchg16b_target_feature) => rust_features.cmpxchg16b_target_feature,
1517                 Some(sym::movbe_target_feature) => rust_features.movbe_target_feature,
1518                 Some(sym::rtm_target_feature) => rust_features.rtm_target_feature,
1519                 Some(sym::f16c_target_feature) => rust_features.f16c_target_feature,
1520                 Some(sym::ermsb_target_feature) => rust_features.ermsb_target_feature,
1521                 Some(sym::bpf_target_feature) => rust_features.bpf_target_feature,
1522                 Some(sym::aarch64_ver_target_feature) => rust_features.aarch64_ver_target_feature,
1523                 Some(name) => bug!("unknown target feature gate {}", name),
1524                 None => true,
1525             };
1526             if !allowed {
1527                 feature_err(
1528                     &tcx.sess.parse_sess,
1529                     feature_gate.unwrap(),
1530                     item.span(),
1531                     &format!("the target feature `{}` is currently unstable", feature),
1532                 )
1533                 .emit();
1534             }
1535             Some(Symbol::intern(feature))
1536         }));
1537     }
1538 }
1539
1540 fn linkage_by_name(tcx: TyCtxt<'_>, def_id: LocalDefId, name: &str) -> Linkage {
1541     use rustc_middle::mir::mono::Linkage::*;
1542
1543     // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
1544     // applicable to variable declarations and may not really make sense for
1545     // Rust code in the first place but allow them anyway and trust that the
1546     // user knows what they're doing. Who knows, unanticipated use cases may pop
1547     // up in the future.
1548     //
1549     // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
1550     // and don't have to be, LLVM treats them as no-ops.
1551     match name {
1552         "appending" => Appending,
1553         "available_externally" => AvailableExternally,
1554         "common" => Common,
1555         "extern_weak" => ExternalWeak,
1556         "external" => External,
1557         "internal" => Internal,
1558         "linkonce" => LinkOnceAny,
1559         "linkonce_odr" => LinkOnceODR,
1560         "private" => Private,
1561         "weak" => WeakAny,
1562         "weak_odr" => WeakODR,
1563         _ => tcx.sess.span_fatal(tcx.def_span(def_id), "invalid linkage specified"),
1564     }
1565 }
1566
1567 fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: DefId) -> CodegenFnAttrs {
1568     if cfg!(debug_assertions) {
1569         let def_kind = tcx.def_kind(did);
1570         assert!(
1571             def_kind.has_codegen_attrs(),
1572             "unexpected `def_kind` in `codegen_fn_attrs`: {def_kind:?}",
1573         );
1574     }
1575
1576     let did = did.expect_local();
1577     let attrs = tcx.hir().attrs(tcx.hir().local_def_id_to_hir_id(did));
1578     let mut codegen_fn_attrs = CodegenFnAttrs::new();
1579     if tcx.should_inherit_track_caller(did) {
1580         codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
1581     }
1582
1583     // The panic_no_unwind function called by TerminatorKind::Abort will never
1584     // unwind. If the panic handler that it invokes unwind then it will simply
1585     // call the panic handler again.
1586     if Some(did.to_def_id()) == tcx.lang_items().panic_no_unwind() {
1587         codegen_fn_attrs.flags |= CodegenFnAttrFlags::NEVER_UNWIND;
1588     }
1589
1590     let supported_target_features = tcx.supported_target_features(LOCAL_CRATE);
1591
1592     let mut inline_span = None;
1593     let mut link_ordinal_span = None;
1594     let mut no_sanitize_span = None;
1595     for attr in attrs.iter() {
1596         if attr.has_name(sym::cold) {
1597             codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD;
1598         } else if attr.has_name(sym::rustc_allocator) {
1599             codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR;
1600         } else if attr.has_name(sym::ffi_returns_twice) {
1601             if tcx.is_foreign_item(did) {
1602                 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_RETURNS_TWICE;
1603             } else {
1604                 // `#[ffi_returns_twice]` is only allowed `extern fn`s.
1605                 struct_span_err!(
1606                     tcx.sess,
1607                     attr.span,
1608                     E0724,
1609                     "`#[ffi_returns_twice]` may only be used on foreign functions"
1610                 )
1611                 .emit();
1612             }
1613         } else if attr.has_name(sym::ffi_pure) {
1614             if tcx.is_foreign_item(did) {
1615                 if attrs.iter().any(|a| a.has_name(sym::ffi_const)) {
1616                     // `#[ffi_const]` functions cannot be `#[ffi_pure]`
1617                     struct_span_err!(
1618                         tcx.sess,
1619                         attr.span,
1620                         E0757,
1621                         "`#[ffi_const]` function cannot be `#[ffi_pure]`"
1622                     )
1623                     .emit();
1624                 } else {
1625                     codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_PURE;
1626                 }
1627             } else {
1628                 // `#[ffi_pure]` is only allowed on foreign functions
1629                 struct_span_err!(
1630                     tcx.sess,
1631                     attr.span,
1632                     E0755,
1633                     "`#[ffi_pure]` may only be used on foreign functions"
1634                 )
1635                 .emit();
1636             }
1637         } else if attr.has_name(sym::ffi_const) {
1638             if tcx.is_foreign_item(did) {
1639                 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_CONST;
1640             } else {
1641                 // `#[ffi_const]` is only allowed on foreign functions
1642                 struct_span_err!(
1643                     tcx.sess,
1644                     attr.span,
1645                     E0756,
1646                     "`#[ffi_const]` may only be used on foreign functions"
1647                 )
1648                 .emit();
1649             }
1650         } else if attr.has_name(sym::rustc_allocator_nounwind) {
1651             codegen_fn_attrs.flags |= CodegenFnAttrFlags::NEVER_UNWIND;
1652         } else if attr.has_name(sym::rustc_reallocator) {
1653             codegen_fn_attrs.flags |= CodegenFnAttrFlags::REALLOCATOR;
1654         } else if attr.has_name(sym::rustc_deallocator) {
1655             codegen_fn_attrs.flags |= CodegenFnAttrFlags::DEALLOCATOR;
1656         } else if attr.has_name(sym::rustc_allocator_zeroed) {
1657             codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR_ZEROED;
1658         } else if attr.has_name(sym::naked) {
1659             codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED;
1660         } else if attr.has_name(sym::no_mangle) {
1661             codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
1662         } else if attr.has_name(sym::no_coverage) {
1663             codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_COVERAGE;
1664         } else if attr.has_name(sym::rustc_std_internal_symbol) {
1665             codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
1666         } else if attr.has_name(sym::used) {
1667             let inner = attr.meta_item_list();
1668             match inner.as_deref() {
1669                 Some([item]) if item.has_name(sym::linker) => {
1670                     if !tcx.features().used_with_arg {
1671                         feature_err(
1672                             &tcx.sess.parse_sess,
1673                             sym::used_with_arg,
1674                             attr.span,
1675                             "`#[used(linker)]` is currently unstable",
1676                         )
1677                         .emit();
1678                     }
1679                     codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_LINKER;
1680                 }
1681                 Some([item]) if item.has_name(sym::compiler) => {
1682                     if !tcx.features().used_with_arg {
1683                         feature_err(
1684                             &tcx.sess.parse_sess,
1685                             sym::used_with_arg,
1686                             attr.span,
1687                             "`#[used(compiler)]` is currently unstable",
1688                         )
1689                         .emit();
1690                     }
1691                     codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED;
1692                 }
1693                 Some(_) => {
1694                     tcx.sess.emit_err(errors::ExpectedUsedSymbol { span: attr.span });
1695                 }
1696                 None => {
1697                     // Unfortunately, unconditionally using `llvm.used` causes
1698                     // issues in handling `.init_array` with the gold linker,
1699                     // but using `llvm.compiler.used` caused a nontrival amount
1700                     // of unintentional ecosystem breakage -- particularly on
1701                     // Mach-O targets.
1702                     //
1703                     // As a result, we emit `llvm.compiler.used` only on ELF
1704                     // targets. This is somewhat ad-hoc, but actually follows
1705                     // our pre-LLVM 13 behavior (prior to the ecosystem
1706                     // breakage), and seems to match `clang`'s behavior as well
1707                     // (both before and after LLVM 13), possibly because they
1708                     // have similar compatibility concerns to us. See
1709                     // https://github.com/rust-lang/rust/issues/47384#issuecomment-1019080146
1710                     // and following comments for some discussion of this, as
1711                     // well as the comments in `rustc_codegen_llvm` where these
1712                     // flags are handled.
1713                     //
1714                     // Anyway, to be clear: this is still up in the air
1715                     // somewhat, and is subject to change in the future (which
1716                     // is a good thing, because this would ideally be a bit
1717                     // more firmed up).
1718                     let is_like_elf = !(tcx.sess.target.is_like_osx
1719                         || tcx.sess.target.is_like_windows
1720                         || tcx.sess.target.is_like_wasm);
1721                     codegen_fn_attrs.flags |= if is_like_elf {
1722                         CodegenFnAttrFlags::USED
1723                     } else {
1724                         CodegenFnAttrFlags::USED_LINKER
1725                     };
1726                 }
1727             }
1728         } else if attr.has_name(sym::cmse_nonsecure_entry) {
1729             if !matches!(tcx.fn_sig(did).abi(), abi::Abi::C { .. }) {
1730                 struct_span_err!(
1731                     tcx.sess,
1732                     attr.span,
1733                     E0776,
1734                     "`#[cmse_nonsecure_entry]` requires C ABI"
1735                 )
1736                 .emit();
1737             }
1738             if !tcx.sess.target.llvm_target.contains("thumbv8m") {
1739                 struct_span_err!(tcx.sess, attr.span, E0775, "`#[cmse_nonsecure_entry]` is only valid for targets with the TrustZone-M extension")
1740                     .emit();
1741             }
1742             codegen_fn_attrs.flags |= CodegenFnAttrFlags::CMSE_NONSECURE_ENTRY;
1743         } else if attr.has_name(sym::thread_local) {
1744             codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL;
1745         } else if attr.has_name(sym::track_caller) {
1746             if !tcx.is_closure(did.to_def_id()) && tcx.fn_sig(did).abi() != abi::Abi::Rust {
1747                 struct_span_err!(tcx.sess, attr.span, E0737, "`#[track_caller]` requires Rust ABI")
1748                     .emit();
1749             }
1750             if tcx.is_closure(did.to_def_id()) && !tcx.features().closure_track_caller {
1751                 feature_err(
1752                     &tcx.sess.parse_sess,
1753                     sym::closure_track_caller,
1754                     attr.span,
1755                     "`#[track_caller]` on closures is currently unstable",
1756                 )
1757                 .emit();
1758             }
1759             codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
1760         } else if attr.has_name(sym::export_name) {
1761             if let Some(s) = attr.value_str() {
1762                 if s.as_str().contains('\0') {
1763                     // `#[export_name = ...]` will be converted to a null-terminated string,
1764                     // so it may not contain any null characters.
1765                     struct_span_err!(
1766                         tcx.sess,
1767                         attr.span,
1768                         E0648,
1769                         "`export_name` may not contain null characters"
1770                     )
1771                     .emit();
1772                 }
1773                 codegen_fn_attrs.export_name = Some(s);
1774             }
1775         } else if attr.has_name(sym::target_feature) {
1776             if !tcx.is_closure(did.to_def_id())
1777                 && tcx.fn_sig(did).unsafety() == hir::Unsafety::Normal
1778             {
1779                 if tcx.sess.target.is_like_wasm || tcx.sess.opts.actually_rustdoc {
1780                     // The `#[target_feature]` attribute is allowed on
1781                     // WebAssembly targets on all functions, including safe
1782                     // ones. Other targets require that `#[target_feature]` is
1783                     // only applied to unsafe functions (pending the
1784                     // `target_feature_11` feature) because on most targets
1785                     // execution of instructions that are not supported is
1786                     // considered undefined behavior. For WebAssembly which is a
1787                     // 100% safe target at execution time it's not possible to
1788                     // execute undefined instructions, and even if a future
1789                     // feature was added in some form for this it would be a
1790                     // deterministic trap. There is no undefined behavior when
1791                     // executing WebAssembly so `#[target_feature]` is allowed
1792                     // on safe functions (but again, only for WebAssembly)
1793                     //
1794                     // Note that this is also allowed if `actually_rustdoc` so
1795                     // if a target is documenting some wasm-specific code then
1796                     // it's not spuriously denied.
1797                 } else if !tcx.features().target_feature_11 {
1798                     let mut err = feature_err(
1799                         &tcx.sess.parse_sess,
1800                         sym::target_feature_11,
1801                         attr.span,
1802                         "`#[target_feature(..)]` can only be applied to `unsafe` functions",
1803                     );
1804                     err.span_label(tcx.def_span(did), "not an `unsafe` function");
1805                     err.emit();
1806                 } else {
1807                     check_target_feature_trait_unsafe(tcx, did, attr.span);
1808                 }
1809             }
1810             from_target_feature(
1811                 tcx,
1812                 attr,
1813                 supported_target_features,
1814                 &mut codegen_fn_attrs.target_features,
1815             );
1816         } else if attr.has_name(sym::linkage) {
1817             if let Some(val) = attr.value_str() {
1818                 codegen_fn_attrs.linkage = Some(linkage_by_name(tcx, did, val.as_str()));
1819             }
1820         } else if attr.has_name(sym::link_section) {
1821             if let Some(val) = attr.value_str() {
1822                 if val.as_str().bytes().any(|b| b == 0) {
1823                     let msg = format!(
1824                         "illegal null byte in link_section \
1825                          value: `{}`",
1826                         &val
1827                     );
1828                     tcx.sess.span_err(attr.span, &msg);
1829                 } else {
1830                     codegen_fn_attrs.link_section = Some(val);
1831                 }
1832             }
1833         } else if attr.has_name(sym::link_name) {
1834             codegen_fn_attrs.link_name = attr.value_str();
1835         } else if attr.has_name(sym::link_ordinal) {
1836             link_ordinal_span = Some(attr.span);
1837             if let ordinal @ Some(_) = check_link_ordinal(tcx, attr) {
1838                 codegen_fn_attrs.link_ordinal = ordinal;
1839             }
1840         } else if attr.has_name(sym::no_sanitize) {
1841             no_sanitize_span = Some(attr.span);
1842             if let Some(list) = attr.meta_item_list() {
1843                 for item in list.iter() {
1844                     if item.has_name(sym::address) {
1845                         codegen_fn_attrs.no_sanitize |= SanitizerSet::ADDRESS;
1846                     } else if item.has_name(sym::cfi) {
1847                         codegen_fn_attrs.no_sanitize |= SanitizerSet::CFI;
1848                     } else if item.has_name(sym::memory) {
1849                         codegen_fn_attrs.no_sanitize |= SanitizerSet::MEMORY;
1850                     } else if item.has_name(sym::memtag) {
1851                         codegen_fn_attrs.no_sanitize |= SanitizerSet::MEMTAG;
1852                     } else if item.has_name(sym::shadow_call_stack) {
1853                         codegen_fn_attrs.no_sanitize |= SanitizerSet::SHADOWCALLSTACK;
1854                     } else if item.has_name(sym::thread) {
1855                         codegen_fn_attrs.no_sanitize |= SanitizerSet::THREAD;
1856                     } else if item.has_name(sym::hwaddress) {
1857                         codegen_fn_attrs.no_sanitize |= SanitizerSet::HWADDRESS;
1858                     } else {
1859                         tcx.sess
1860                             .struct_span_err(item.span(), "invalid argument for `no_sanitize`")
1861                             .note("expected one of: `address`, `cfi`, `hwaddress`, `memory`, `memtag`, `shadow-call-stack`, or `thread`")
1862                             .emit();
1863                     }
1864                 }
1865             }
1866         } else if attr.has_name(sym::instruction_set) {
1867             codegen_fn_attrs.instruction_set = match attr.meta_kind() {
1868                 Some(MetaItemKind::List(ref items)) => match items.as_slice() {
1869                     [NestedMetaItem::MetaItem(set)] => {
1870                         let segments =
1871                             set.path.segments.iter().map(|x| x.ident.name).collect::<Vec<_>>();
1872                         match segments.as_slice() {
1873                             [sym::arm, sym::a32] | [sym::arm, sym::t32] => {
1874                                 if !tcx.sess.target.has_thumb_interworking {
1875                                     struct_span_err!(
1876                                         tcx.sess.diagnostic(),
1877                                         attr.span,
1878                                         E0779,
1879                                         "target does not support `#[instruction_set]`"
1880                                     )
1881                                     .emit();
1882                                     None
1883                                 } else if segments[1] == sym::a32 {
1884                                     Some(InstructionSetAttr::ArmA32)
1885                                 } else if segments[1] == sym::t32 {
1886                                     Some(InstructionSetAttr::ArmT32)
1887                                 } else {
1888                                     unreachable!()
1889                                 }
1890                             }
1891                             _ => {
1892                                 struct_span_err!(
1893                                     tcx.sess.diagnostic(),
1894                                     attr.span,
1895                                     E0779,
1896                                     "invalid instruction set specified",
1897                                 )
1898                                 .emit();
1899                                 None
1900                             }
1901                         }
1902                     }
1903                     [] => {
1904                         struct_span_err!(
1905                             tcx.sess.diagnostic(),
1906                             attr.span,
1907                             E0778,
1908                             "`#[instruction_set]` requires an argument"
1909                         )
1910                         .emit();
1911                         None
1912                     }
1913                     _ => {
1914                         struct_span_err!(
1915                             tcx.sess.diagnostic(),
1916                             attr.span,
1917                             E0779,
1918                             "cannot specify more than one instruction set"
1919                         )
1920                         .emit();
1921                         None
1922                     }
1923                 },
1924                 _ => {
1925                     struct_span_err!(
1926                         tcx.sess.diagnostic(),
1927                         attr.span,
1928                         E0778,
1929                         "must specify an instruction set"
1930                     )
1931                     .emit();
1932                     None
1933                 }
1934             };
1935         } else if attr.has_name(sym::repr) {
1936             codegen_fn_attrs.alignment = match attr.meta_item_list() {
1937                 Some(items) => match items.as_slice() {
1938                     [item] => match item.name_value_literal() {
1939                         Some((sym::align, literal)) => {
1940                             let alignment = rustc_attr::parse_alignment(&literal.kind);
1941
1942                             match alignment {
1943                                 Ok(align) => Some(align),
1944                                 Err(msg) => {
1945                                     struct_span_err!(
1946                                         tcx.sess.diagnostic(),
1947                                         attr.span,
1948                                         E0589,
1949                                         "invalid `repr(align)` attribute: {}",
1950                                         msg
1951                                     )
1952                                     .emit();
1953
1954                                     None
1955                                 }
1956                             }
1957                         }
1958                         _ => None,
1959                     },
1960                     [] => None,
1961                     _ => None,
1962                 },
1963                 None => None,
1964             };
1965         }
1966     }
1967
1968     codegen_fn_attrs.inline = attrs.iter().fold(InlineAttr::None, |ia, attr| {
1969         if !attr.has_name(sym::inline) {
1970             return ia;
1971         }
1972         match attr.meta_kind() {
1973             Some(MetaItemKind::Word) => InlineAttr::Hint,
1974             Some(MetaItemKind::List(ref items)) => {
1975                 inline_span = Some(attr.span);
1976                 if items.len() != 1 {
1977                     struct_span_err!(
1978                         tcx.sess.diagnostic(),
1979                         attr.span,
1980                         E0534,
1981                         "expected one argument"
1982                     )
1983                     .emit();
1984                     InlineAttr::None
1985                 } else if list_contains_name(&items, sym::always) {
1986                     InlineAttr::Always
1987                 } else if list_contains_name(&items, sym::never) {
1988                     InlineAttr::Never
1989                 } else {
1990                     struct_span_err!(
1991                         tcx.sess.diagnostic(),
1992                         items[0].span(),
1993                         E0535,
1994                         "invalid argument"
1995                     )
1996                     .help("valid inline arguments are `always` and `never`")
1997                     .emit();
1998
1999                     InlineAttr::None
2000                 }
2001             }
2002             Some(MetaItemKind::NameValue(_)) => ia,
2003             None => ia,
2004         }
2005     });
2006
2007     codegen_fn_attrs.optimize = attrs.iter().fold(OptimizeAttr::None, |ia, attr| {
2008         if !attr.has_name(sym::optimize) {
2009             return ia;
2010         }
2011         let err = |sp, s| struct_span_err!(tcx.sess.diagnostic(), sp, E0722, "{}", s).emit();
2012         match attr.meta_kind() {
2013             Some(MetaItemKind::Word) => {
2014                 err(attr.span, "expected one argument");
2015                 ia
2016             }
2017             Some(MetaItemKind::List(ref items)) => {
2018                 inline_span = Some(attr.span);
2019                 if items.len() != 1 {
2020                     err(attr.span, "expected one argument");
2021                     OptimizeAttr::None
2022                 } else if list_contains_name(&items, sym::size) {
2023                     OptimizeAttr::Size
2024                 } else if list_contains_name(&items, sym::speed) {
2025                     OptimizeAttr::Speed
2026                 } else {
2027                     err(items[0].span(), "invalid argument");
2028                     OptimizeAttr::None
2029                 }
2030             }
2031             Some(MetaItemKind::NameValue(_)) => ia,
2032             None => ia,
2033         }
2034     });
2035
2036     // #73631: closures inherit `#[target_feature]` annotations
2037     if tcx.features().target_feature_11 && tcx.is_closure(did.to_def_id()) {
2038         let owner_id = tcx.parent(did.to_def_id());
2039         if tcx.def_kind(owner_id).has_codegen_attrs() {
2040             codegen_fn_attrs
2041                 .target_features
2042                 .extend(tcx.codegen_fn_attrs(owner_id).target_features.iter().copied());
2043         }
2044     }
2045
2046     // If a function uses #[target_feature] it can't be inlined into general
2047     // purpose functions as they wouldn't have the right target features
2048     // enabled. For that reason we also forbid #[inline(always)] as it can't be
2049     // respected.
2050     if !codegen_fn_attrs.target_features.is_empty() {
2051         if codegen_fn_attrs.inline == InlineAttr::Always {
2052             if let Some(span) = inline_span {
2053                 tcx.sess.span_err(
2054                     span,
2055                     "cannot use `#[inline(always)]` with \
2056                      `#[target_feature]`",
2057                 );
2058             }
2059         }
2060     }
2061
2062     if !codegen_fn_attrs.no_sanitize.is_empty() {
2063         if codegen_fn_attrs.inline == InlineAttr::Always {
2064             if let (Some(no_sanitize_span), Some(inline_span)) = (no_sanitize_span, inline_span) {
2065                 let hir_id = tcx.hir().local_def_id_to_hir_id(did);
2066                 tcx.struct_span_lint_hir(
2067                     lint::builtin::INLINE_NO_SANITIZE,
2068                     hir_id,
2069                     no_sanitize_span,
2070                     "`no_sanitize` will have no effect after inlining",
2071                     |lint| lint.span_note(inline_span, "inlining requested here"),
2072                 )
2073             }
2074         }
2075     }
2076
2077     // Weak lang items have the same semantics as "std internal" symbols in the
2078     // sense that they're preserved through all our LTO passes and only
2079     // strippable by the linker.
2080     //
2081     // Additionally weak lang items have predetermined symbol names.
2082     if tcx.is_weak_lang_item(did.to_def_id()) {
2083         codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2084     }
2085     if let Some(name) = weak_lang_items::link_name(attrs) {
2086         codegen_fn_attrs.export_name = Some(name);
2087         codegen_fn_attrs.link_name = Some(name);
2088     }
2089     check_link_name_xor_ordinal(tcx, &codegen_fn_attrs, link_ordinal_span);
2090
2091     // Internal symbols to the standard library all have no_mangle semantics in
2092     // that they have defined symbol names present in the function name. This
2093     // also applies to weak symbols where they all have known symbol names.
2094     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
2095         codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2096     }
2097
2098     // Any linkage to LLVM intrinsics for now forcibly marks them all as never
2099     // unwinds since LLVM sometimes can't handle codegen which `invoke`s
2100     // intrinsic functions.
2101     if let Some(name) = &codegen_fn_attrs.link_name {
2102         if name.as_str().starts_with("llvm.") {
2103             codegen_fn_attrs.flags |= CodegenFnAttrFlags::NEVER_UNWIND;
2104         }
2105     }
2106
2107     codegen_fn_attrs
2108 }
2109
2110 /// Computes the set of target features used in a function for the purposes of
2111 /// inline assembly.
2112 fn asm_target_features<'tcx>(tcx: TyCtxt<'tcx>, did: DefId) -> &'tcx FxHashSet<Symbol> {
2113     let mut target_features = tcx.sess.unstable_target_features.clone();
2114     if tcx.def_kind(did).has_codegen_attrs() {
2115         let attrs = tcx.codegen_fn_attrs(did);
2116         target_features.extend(&attrs.target_features);
2117         match attrs.instruction_set {
2118             None => {}
2119             Some(InstructionSetAttr::ArmA32) => {
2120                 target_features.remove(&sym::thumb_mode);
2121             }
2122             Some(InstructionSetAttr::ArmT32) => {
2123                 target_features.insert(sym::thumb_mode);
2124             }
2125         }
2126     }
2127
2128     tcx.arena.alloc(target_features)
2129 }
2130
2131 /// Checks if the provided DefId is a method in a trait impl for a trait which has track_caller
2132 /// applied to the method prototype.
2133 fn should_inherit_track_caller(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
2134     if let Some(impl_item) = tcx.opt_associated_item(def_id)
2135         && let ty::AssocItemContainer::ImplContainer = impl_item.container
2136         && let Some(trait_item) = impl_item.trait_item_def_id
2137     {
2138         return tcx
2139             .codegen_fn_attrs(trait_item)
2140             .flags
2141             .intersects(CodegenFnAttrFlags::TRACK_CALLER);
2142     }
2143
2144     false
2145 }
2146
2147 fn check_link_ordinal(tcx: TyCtxt<'_>, attr: &ast::Attribute) -> Option<u16> {
2148     use rustc_ast::{Lit, LitIntType, LitKind};
2149     if !tcx.features().raw_dylib && tcx.sess.target.arch == "x86" {
2150         feature_err(
2151             &tcx.sess.parse_sess,
2152             sym::raw_dylib,
2153             attr.span,
2154             "`#[link_ordinal]` is unstable on x86",
2155         )
2156         .emit();
2157     }
2158     let meta_item_list = attr.meta_item_list();
2159     let meta_item_list: Option<&[ast::NestedMetaItem]> = meta_item_list.as_ref().map(Vec::as_ref);
2160     let sole_meta_list = match meta_item_list {
2161         Some([item]) => item.literal(),
2162         Some(_) => {
2163             tcx.sess
2164                 .struct_span_err(attr.span, "incorrect number of arguments to `#[link_ordinal]`")
2165                 .note("the attribute requires exactly one argument")
2166                 .emit();
2167             return None;
2168         }
2169         _ => None,
2170     };
2171     if let Some(Lit { kind: LitKind::Int(ordinal, LitIntType::Unsuffixed), .. }) = sole_meta_list {
2172         // According to the table at https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#import-header,
2173         // the ordinal must fit into 16 bits.  Similarly, the Ordinal field in COFFShortExport (defined
2174         // in llvm/include/llvm/Object/COFFImportFile.h), which we use to communicate import information
2175         // to LLVM for `#[link(kind = "raw-dylib"_])`, is also defined to be uint16_t.
2176         //
2177         // FIXME: should we allow an ordinal of 0?  The MSVC toolchain has inconsistent support for this:
2178         // both LINK.EXE and LIB.EXE signal errors and abort when given a .DEF file that specifies
2179         // a zero ordinal.  However, llvm-dlltool is perfectly happy to generate an import library
2180         // for such a .DEF file, and MSVC's LINK.EXE is also perfectly happy to consume an import
2181         // library produced by LLVM with an ordinal of 0, and it generates an .EXE.  (I don't know yet
2182         // if the resulting EXE runs, as I haven't yet built the necessary DLL -- see earlier comment
2183         // about LINK.EXE failing.)
2184         if *ordinal <= u16::MAX as u128 {
2185             Some(*ordinal as u16)
2186         } else {
2187             let msg = format!("ordinal value in `link_ordinal` is too large: `{}`", &ordinal);
2188             tcx.sess
2189                 .struct_span_err(attr.span, &msg)
2190                 .note("the value may not exceed `u16::MAX`")
2191                 .emit();
2192             None
2193         }
2194     } else {
2195         tcx.sess
2196             .struct_span_err(attr.span, "illegal ordinal format in `link_ordinal`")
2197             .note("an unsuffixed integer value, e.g., `1`, is expected")
2198             .emit();
2199         None
2200     }
2201 }
2202
2203 fn check_link_name_xor_ordinal(
2204     tcx: TyCtxt<'_>,
2205     codegen_fn_attrs: &CodegenFnAttrs,
2206     inline_span: Option<Span>,
2207 ) {
2208     if codegen_fn_attrs.link_name.is_none() || codegen_fn_attrs.link_ordinal.is_none() {
2209         return;
2210     }
2211     let msg = "cannot use `#[link_name]` with `#[link_ordinal]`";
2212     if let Some(span) = inline_span {
2213         tcx.sess.span_err(span, msg);
2214     } else {
2215         tcx.sess.err(msg);
2216     }
2217 }
2218
2219 /// Checks the function annotated with `#[target_feature]` is not a safe
2220 /// trait method implementation, reporting an error if it is.
2221 fn check_target_feature_trait_unsafe(tcx: TyCtxt<'_>, id: LocalDefId, attr_span: Span) {
2222     let hir_id = tcx.hir().local_def_id_to_hir_id(id);
2223     let node = tcx.hir().get(hir_id);
2224     if let Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }) = node {
2225         let parent_id = tcx.hir().get_parent_item(hir_id);
2226         let parent_item = tcx.hir().expect_item(parent_id.def_id);
2227         if let hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) = parent_item.kind {
2228             tcx.sess
2229                 .struct_span_err(
2230                     attr_span,
2231                     "`#[target_feature(..)]` cannot be applied to safe trait method",
2232                 )
2233                 .span_label(attr_span, "cannot be applied to safe trait method")
2234                 .span_label(tcx.def_span(id), "not an `unsafe` function")
2235                 .emit();
2236         }
2237     }
2238 }