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