]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_analysis/src/collect.rs
4c1d95a452d5e571c94229e4e11b064f56c4769c
[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, 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                                     "This 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 \
1006                             must be associated 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(
1032                             "All `#[rustc_must_implement_one_of]` arguments \
1033                             must be unique",
1034                         )
1035                         .emit();
1036
1037                     no_dups = false;
1038                 }
1039             }
1040
1041             no_dups.then_some(list)
1042         });
1043
1044     ty::TraitDef::new(
1045         def_id,
1046         unsafety,
1047         paren_sugar,
1048         is_auto,
1049         is_marker,
1050         skip_array_during_method_dispatch,
1051         spec_kind,
1052         must_implement_one_of,
1053     )
1054 }
1055
1056 fn are_suggestable_generic_args(generic_args: &[hir::GenericArg<'_>]) -> bool {
1057     generic_args.iter().any(|arg| match arg {
1058         hir::GenericArg::Type(ty) => is_suggestable_infer_ty(ty),
1059         hir::GenericArg::Infer(_) => true,
1060         _ => false,
1061     })
1062 }
1063
1064 /// Whether `ty` is a type with `_` placeholders that can be inferred. Used in diagnostics only to
1065 /// use inference to provide suggestions for the appropriate type if possible.
1066 fn is_suggestable_infer_ty(ty: &hir::Ty<'_>) -> bool {
1067     debug!(?ty);
1068     use hir::TyKind::*;
1069     match &ty.kind {
1070         Infer => true,
1071         Slice(ty) => is_suggestable_infer_ty(ty),
1072         Array(ty, length) => {
1073             is_suggestable_infer_ty(ty) || matches!(length, hir::ArrayLen::Infer(_, _))
1074         }
1075         Tup(tys) => tys.iter().any(is_suggestable_infer_ty),
1076         Ptr(mut_ty) | Rptr(_, mut_ty) => is_suggestable_infer_ty(mut_ty.ty),
1077         OpaqueDef(_, generic_args, _) => are_suggestable_generic_args(generic_args),
1078         Path(hir::QPath::TypeRelative(ty, segment)) => {
1079             is_suggestable_infer_ty(ty) || are_suggestable_generic_args(segment.args().args)
1080         }
1081         Path(hir::QPath::Resolved(ty_opt, hir::Path { segments, .. })) => {
1082             ty_opt.map_or(false, is_suggestable_infer_ty)
1083                 || segments.iter().any(|segment| are_suggestable_generic_args(segment.args().args))
1084         }
1085         _ => false,
1086     }
1087 }
1088
1089 pub fn get_infer_ret_ty<'hir>(output: &'hir hir::FnRetTy<'hir>) -> Option<&'hir hir::Ty<'hir>> {
1090     if let hir::FnRetTy::Return(ty) = output {
1091         if is_suggestable_infer_ty(ty) {
1092             return Some(&*ty);
1093         }
1094     }
1095     None
1096 }
1097
1098 #[instrument(level = "debug", skip(tcx))]
1099 fn fn_sig(tcx: TyCtxt<'_>, def_id: DefId) -> ty::PolyFnSig<'_> {
1100     use rustc_hir::Node::*;
1101     use rustc_hir::*;
1102
1103     let def_id = def_id.expect_local();
1104     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
1105
1106     let icx = ItemCtxt::new(tcx, def_id.to_def_id());
1107
1108     match tcx.hir().get(hir_id) {
1109         TraitItem(hir::TraitItem {
1110             kind: TraitItemKind::Fn(sig, TraitFn::Provided(_)),
1111             generics,
1112             ..
1113         })
1114         | Item(hir::Item { kind: ItemKind::Fn(sig, generics, _), .. }) => {
1115             infer_return_ty_for_fn_sig(tcx, sig, generics, def_id, &icx)
1116         }
1117
1118         ImplItem(hir::ImplItem { kind: ImplItemKind::Fn(sig, _), generics, .. }) => {
1119             // Do not try to infer the return type for a impl method coming from a trait
1120             if let Item(hir::Item { kind: ItemKind::Impl(i), .. }) =
1121                 tcx.hir().get(tcx.hir().get_parent_node(hir_id))
1122                 && i.of_trait.is_some()
1123             {
1124                 <dyn AstConv<'_>>::ty_of_fn(
1125                     &icx,
1126                     hir_id,
1127                     sig.header.unsafety,
1128                     sig.header.abi,
1129                     sig.decl,
1130                     Some(generics),
1131                     None,
1132                 )
1133             } else {
1134                 infer_return_ty_for_fn_sig(tcx, sig, generics, def_id, &icx)
1135             }
1136         }
1137
1138         TraitItem(hir::TraitItem {
1139             kind: TraitItemKind::Fn(FnSig { header, decl, span: _ }, _),
1140             generics,
1141             ..
1142         }) => <dyn AstConv<'_>>::ty_of_fn(
1143             &icx,
1144             hir_id,
1145             header.unsafety,
1146             header.abi,
1147             decl,
1148             Some(generics),
1149             None,
1150         ),
1151
1152         ForeignItem(&hir::ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
1153             let abi = tcx.hir().get_foreign_abi(hir_id);
1154             compute_sig_of_foreign_fn_decl(tcx, def_id.to_def_id(), fn_decl, abi)
1155         }
1156
1157         Ctor(data) | Variant(hir::Variant { data, .. }) if data.ctor().is_some() => {
1158             let ty = tcx.type_of(tcx.hir().get_parent_item(hir_id));
1159             let inputs = data.fields().iter().map(|f| tcx.type_of(f.def_id));
1160             ty::Binder::dummy(tcx.mk_fn_sig(
1161                 inputs,
1162                 ty,
1163                 false,
1164                 hir::Unsafety::Normal,
1165                 abi::Abi::Rust,
1166             ))
1167         }
1168
1169         Expr(&hir::Expr { kind: hir::ExprKind::Closure { .. }, .. }) => {
1170             // Closure signatures are not like other function
1171             // signatures and cannot be accessed through `fn_sig`. For
1172             // example, a closure signature excludes the `self`
1173             // argument. In any case they are embedded within the
1174             // closure type as part of the `ClosureSubsts`.
1175             //
1176             // To get the signature of a closure, you should use the
1177             // `sig` method on the `ClosureSubsts`:
1178             //
1179             //    substs.as_closure().sig(def_id, tcx)
1180             bug!(
1181                 "to get the signature of a closure, use `substs.as_closure().sig()` not `fn_sig()`",
1182             );
1183         }
1184
1185         x => {
1186             bug!("unexpected sort of node in fn_sig(): {:?}", x);
1187         }
1188     }
1189 }
1190
1191 fn infer_return_ty_for_fn_sig<'tcx>(
1192     tcx: TyCtxt<'tcx>,
1193     sig: &hir::FnSig<'_>,
1194     generics: &hir::Generics<'_>,
1195     def_id: LocalDefId,
1196     icx: &ItemCtxt<'tcx>,
1197 ) -> ty::PolyFnSig<'tcx> {
1198     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
1199
1200     match get_infer_ret_ty(&sig.decl.output) {
1201         Some(ty) => {
1202             let fn_sig = tcx.typeck(def_id).liberated_fn_sigs()[hir_id];
1203             // Typeck doesn't expect erased regions to be returned from `type_of`.
1204             let fn_sig = tcx.fold_regions(fn_sig, |r, _| match *r {
1205                 ty::ReErased => tcx.lifetimes.re_static,
1206                 _ => r,
1207             });
1208             let fn_sig = ty::Binder::dummy(fn_sig);
1209
1210             let mut visitor = HirPlaceholderCollector::default();
1211             visitor.visit_ty(ty);
1212             let mut diag = bad_placeholder(tcx, visitor.0, "return type");
1213             let ret_ty = fn_sig.skip_binder().output();
1214             if ret_ty.is_suggestable(tcx, false) {
1215                 diag.span_suggestion(
1216                     ty.span,
1217                     "replace with the correct return type",
1218                     ret_ty,
1219                     Applicability::MachineApplicable,
1220                 );
1221             } else if matches!(ret_ty.kind(), ty::FnDef(..)) {
1222                 let fn_sig = ret_ty.fn_sig(tcx);
1223                 if fn_sig
1224                     .skip_binder()
1225                     .inputs_and_output
1226                     .iter()
1227                     .all(|t| t.is_suggestable(tcx, false))
1228                 {
1229                     diag.span_suggestion(
1230                         ty.span,
1231                         "replace with the correct return type",
1232                         fn_sig,
1233                         Applicability::MachineApplicable,
1234                     );
1235                 }
1236             } else if ret_ty.is_closure() {
1237                 // We're dealing with a closure, so we should suggest using `impl Fn` or trait bounds
1238                 // to prevent the user from getting a papercut while trying to use the unique closure
1239                 // syntax (e.g. `[closure@src/lib.rs:2:5: 2:9]`).
1240                 diag.help("consider using an `Fn`, `FnMut`, or `FnOnce` trait bound");
1241                 diag.note("for more information on `Fn` traits and closure types, see https://doc.rust-lang.org/book/ch13-01-closures.html");
1242             }
1243             diag.emit();
1244
1245             fn_sig
1246         }
1247         None => <dyn AstConv<'_>>::ty_of_fn(
1248             icx,
1249             hir_id,
1250             sig.header.unsafety,
1251             sig.header.abi,
1252             sig.decl,
1253             Some(generics),
1254             None,
1255         ),
1256     }
1257 }
1258
1259 fn impl_trait_ref(tcx: TyCtxt<'_>, def_id: DefId) -> Option<ty::TraitRef<'_>> {
1260     let icx = ItemCtxt::new(tcx, def_id);
1261     let item = tcx.hir().expect_item(def_id.expect_local());
1262     match item.kind {
1263         hir::ItemKind::Impl(ref impl_) => impl_.of_trait.as_ref().map(|ast_trait_ref| {
1264             let selfty = tcx.type_of(def_id);
1265             <dyn AstConv<'_>>::instantiate_mono_trait_ref(
1266                 &icx,
1267                 ast_trait_ref,
1268                 selfty,
1269                 check_impl_constness(tcx, impl_.constness, ast_trait_ref),
1270             )
1271         }),
1272         _ => bug!(),
1273     }
1274 }
1275
1276 fn check_impl_constness(
1277     tcx: TyCtxt<'_>,
1278     constness: hir::Constness,
1279     ast_trait_ref: &hir::TraitRef<'_>,
1280 ) -> ty::BoundConstness {
1281     match constness {
1282         hir::Constness::Const => {
1283             if let Some(trait_def_id) = ast_trait_ref.trait_def_id() && !tcx.has_attr(trait_def_id, sym::const_trait) {
1284                 let trait_name = tcx.item_name(trait_def_id).to_string();
1285                 tcx.sess.emit_err(errors::ConstImplForNonConstTrait {
1286                     trait_ref_span: ast_trait_ref.path.span,
1287                     trait_name,
1288                     local_trait_span: trait_def_id.as_local().map(|_| tcx.def_span(trait_def_id).shrink_to_lo()),
1289                     marking: (),
1290                     adding: (),
1291                 });
1292                 ty::BoundConstness::NotConst
1293             } else {
1294                 ty::BoundConstness::ConstIfConst
1295             }
1296         },
1297         hir::Constness::NotConst => ty::BoundConstness::NotConst,
1298     }
1299 }
1300
1301 fn impl_polarity(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ImplPolarity {
1302     let is_rustc_reservation = tcx.has_attr(def_id, sym::rustc_reservation_impl);
1303     let item = tcx.hir().expect_item(def_id.expect_local());
1304     match &item.kind {
1305         hir::ItemKind::Impl(hir::Impl {
1306             polarity: hir::ImplPolarity::Negative(span),
1307             of_trait,
1308             ..
1309         }) => {
1310             if is_rustc_reservation {
1311                 let span = span.to(of_trait.as_ref().map_or(*span, |t| t.path.span));
1312                 tcx.sess.span_err(span, "reservation impls can't be negative");
1313             }
1314             ty::ImplPolarity::Negative
1315         }
1316         hir::ItemKind::Impl(hir::Impl {
1317             polarity: hir::ImplPolarity::Positive,
1318             of_trait: None,
1319             ..
1320         }) => {
1321             if is_rustc_reservation {
1322                 tcx.sess.span_err(item.span, "reservation impls can't be inherent");
1323             }
1324             ty::ImplPolarity::Positive
1325         }
1326         hir::ItemKind::Impl(hir::Impl {
1327             polarity: hir::ImplPolarity::Positive,
1328             of_trait: Some(_),
1329             ..
1330         }) => {
1331             if is_rustc_reservation {
1332                 ty::ImplPolarity::Reservation
1333             } else {
1334                 ty::ImplPolarity::Positive
1335             }
1336         }
1337         item => bug!("impl_polarity: {:?} not an impl", item),
1338     }
1339 }
1340
1341 /// Returns the early-bound lifetimes declared in this generics
1342 /// listing. For anything other than fns/methods, this is just all
1343 /// the lifetimes that are declared. For fns or methods, we have to
1344 /// screen out those that do not appear in any where-clauses etc using
1345 /// `resolve_lifetime::early_bound_lifetimes`.
1346 fn early_bound_lifetimes_from_generics<'a, 'tcx: 'a>(
1347     tcx: TyCtxt<'tcx>,
1348     generics: &'a hir::Generics<'a>,
1349 ) -> impl Iterator<Item = &'a hir::GenericParam<'a>> + Captures<'tcx> {
1350     generics.params.iter().filter(move |param| match param.kind {
1351         GenericParamKind::Lifetime { .. } => !tcx.is_late_bound(param.hir_id),
1352         _ => false,
1353     })
1354 }
1355
1356 /// Returns a list of type predicates for the definition with ID `def_id`, including inferred
1357 /// lifetime constraints. This includes all predicates returned by `explicit_predicates_of`, plus
1358 /// inferred constraints concerning which regions outlive other regions.
1359 #[instrument(level = "debug", skip(tcx))]
1360 fn predicates_defined_on(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1361     let mut result = tcx.explicit_predicates_of(def_id);
1362     debug!("predicates_defined_on: explicit_predicates_of({:?}) = {:?}", def_id, result,);
1363     let inferred_outlives = tcx.inferred_outlives_of(def_id);
1364     if !inferred_outlives.is_empty() {
1365         debug!(
1366             "predicates_defined_on: inferred_outlives_of({:?}) = {:?}",
1367             def_id, inferred_outlives,
1368         );
1369         if result.predicates.is_empty() {
1370             result.predicates = inferred_outlives;
1371         } else {
1372             result.predicates = tcx
1373                 .arena
1374                 .alloc_from_iter(result.predicates.iter().chain(inferred_outlives).copied());
1375         }
1376     }
1377
1378     debug!("predicates_defined_on({:?}) = {:?}", def_id, result);
1379     result
1380 }
1381
1382 fn compute_sig_of_foreign_fn_decl<'tcx>(
1383     tcx: TyCtxt<'tcx>,
1384     def_id: DefId,
1385     decl: &'tcx hir::FnDecl<'tcx>,
1386     abi: abi::Abi,
1387 ) -> ty::PolyFnSig<'tcx> {
1388     let unsafety = if abi == abi::Abi::RustIntrinsic {
1389         intrinsic_operation_unsafety(tcx, def_id)
1390     } else {
1391         hir::Unsafety::Unsafe
1392     };
1393     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1394     let fty = <dyn AstConv<'_>>::ty_of_fn(
1395         &ItemCtxt::new(tcx, def_id),
1396         hir_id,
1397         unsafety,
1398         abi,
1399         decl,
1400         None,
1401         None,
1402     );
1403
1404     // Feature gate SIMD types in FFI, since I am not sure that the
1405     // ABIs are handled at all correctly. -huonw
1406     if abi != abi::Abi::RustIntrinsic
1407         && abi != abi::Abi::PlatformIntrinsic
1408         && !tcx.features().simd_ffi
1409     {
1410         let check = |ast_ty: &hir::Ty<'_>, ty: Ty<'_>| {
1411             if ty.is_simd() {
1412                 let snip = tcx
1413                     .sess
1414                     .source_map()
1415                     .span_to_snippet(ast_ty.span)
1416                     .map_or_else(|_| String::new(), |s| format!(" `{}`", s));
1417                 tcx.sess
1418                     .struct_span_err(
1419                         ast_ty.span,
1420                         &format!(
1421                             "use of SIMD type{} in FFI is highly experimental and \
1422                              may result in invalid code",
1423                             snip
1424                         ),
1425                     )
1426                     .help("add `#![feature(simd_ffi)]` to the crate attributes to enable")
1427                     .emit();
1428             }
1429         };
1430         for (input, ty) in iter::zip(decl.inputs, fty.inputs().skip_binder()) {
1431             check(input, *ty)
1432         }
1433         if let hir::FnRetTy::Return(ref ty) = decl.output {
1434             check(ty, fty.output().skip_binder())
1435         }
1436     }
1437
1438     fty
1439 }
1440
1441 fn is_foreign_item(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1442     match tcx.hir().get_if_local(def_id) {
1443         Some(Node::ForeignItem(..)) => true,
1444         Some(_) => false,
1445         _ => bug!("is_foreign_item applied to non-local def-id {:?}", def_id),
1446     }
1447 }
1448
1449 fn generator_kind(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::GeneratorKind> {
1450     match tcx.hir().get_if_local(def_id) {
1451         Some(Node::Expr(&rustc_hir::Expr {
1452             kind: rustc_hir::ExprKind::Closure(&rustc_hir::Closure { body, .. }),
1453             ..
1454         })) => tcx.hir().body(body).generator_kind(),
1455         Some(_) => None,
1456         _ => bug!("generator_kind applied to non-local def-id {:?}", def_id),
1457     }
1458 }
1459
1460 fn from_target_feature(
1461     tcx: TyCtxt<'_>,
1462     attr: &ast::Attribute,
1463     supported_target_features: &FxHashMap<String, Option<Symbol>>,
1464     target_features: &mut Vec<Symbol>,
1465 ) {
1466     let Some(list) = attr.meta_item_list() else { return };
1467     let bad_item = |span| {
1468         let msg = "malformed `target_feature` attribute input";
1469         let code = "enable = \"..\"";
1470         tcx.sess
1471             .struct_span_err(span, msg)
1472             .span_suggestion(span, "must be of the form", code, Applicability::HasPlaceholders)
1473             .emit();
1474     };
1475     let rust_features = tcx.features();
1476     for item in list {
1477         // Only `enable = ...` is accepted in the meta-item list.
1478         if !item.has_name(sym::enable) {
1479             bad_item(item.span());
1480             continue;
1481         }
1482
1483         // Must be of the form `enable = "..."` (a string).
1484         let Some(value) = item.value_str() else {
1485             bad_item(item.span());
1486             continue;
1487         };
1488
1489         // We allow comma separation to enable multiple features.
1490         target_features.extend(value.as_str().split(',').filter_map(|feature| {
1491             let Some(feature_gate) = supported_target_features.get(feature) else {
1492                 let msg =
1493                     format!("the feature named `{}` is not valid for this target", feature);
1494                 let mut err = tcx.sess.struct_span_err(item.span(), &msg);
1495                 err.span_label(
1496                     item.span(),
1497                     format!("`{}` is not valid for this target", feature),
1498                 );
1499                 if let Some(stripped) = feature.strip_prefix('+') {
1500                     let valid = supported_target_features.contains_key(stripped);
1501                     if valid {
1502                         err.help("consider removing the leading `+` in the feature name");
1503                     }
1504                 }
1505                 err.emit();
1506                 return None;
1507             };
1508
1509             // Only allow features whose feature gates have been enabled.
1510             let allowed = match feature_gate.as_ref().copied() {
1511                 Some(sym::arm_target_feature) => rust_features.arm_target_feature,
1512                 Some(sym::hexagon_target_feature) => rust_features.hexagon_target_feature,
1513                 Some(sym::powerpc_target_feature) => rust_features.powerpc_target_feature,
1514                 Some(sym::mips_target_feature) => rust_features.mips_target_feature,
1515                 Some(sym::riscv_target_feature) => rust_features.riscv_target_feature,
1516                 Some(sym::avx512_target_feature) => rust_features.avx512_target_feature,
1517                 Some(sym::sse4a_target_feature) => rust_features.sse4a_target_feature,
1518                 Some(sym::tbm_target_feature) => rust_features.tbm_target_feature,
1519                 Some(sym::wasm_target_feature) => rust_features.wasm_target_feature,
1520                 Some(sym::cmpxchg16b_target_feature) => rust_features.cmpxchg16b_target_feature,
1521                 Some(sym::movbe_target_feature) => rust_features.movbe_target_feature,
1522                 Some(sym::rtm_target_feature) => rust_features.rtm_target_feature,
1523                 Some(sym::f16c_target_feature) => rust_features.f16c_target_feature,
1524                 Some(sym::ermsb_target_feature) => rust_features.ermsb_target_feature,
1525                 Some(sym::bpf_target_feature) => rust_features.bpf_target_feature,
1526                 Some(sym::aarch64_ver_target_feature) => rust_features.aarch64_ver_target_feature,
1527                 Some(name) => bug!("unknown target feature gate {}", name),
1528                 None => true,
1529             };
1530             if !allowed {
1531                 feature_err(
1532                     &tcx.sess.parse_sess,
1533                     feature_gate.unwrap(),
1534                     item.span(),
1535                     &format!("the target feature `{}` is currently unstable", feature),
1536                 )
1537                 .emit();
1538             }
1539             Some(Symbol::intern(feature))
1540         }));
1541     }
1542 }
1543
1544 fn linkage_by_name(tcx: TyCtxt<'_>, def_id: LocalDefId, name: &str) -> Linkage {
1545     use rustc_middle::mir::mono::Linkage::*;
1546
1547     // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
1548     // applicable to variable declarations and may not really make sense for
1549     // Rust code in the first place but allow them anyway and trust that the
1550     // user knows what they're doing. Who knows, unanticipated use cases may pop
1551     // up in the future.
1552     //
1553     // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
1554     // and don't have to be, LLVM treats them as no-ops.
1555     match name {
1556         "appending" => Appending,
1557         "available_externally" => AvailableExternally,
1558         "common" => Common,
1559         "extern_weak" => ExternalWeak,
1560         "external" => External,
1561         "internal" => Internal,
1562         "linkonce" => LinkOnceAny,
1563         "linkonce_odr" => LinkOnceODR,
1564         "private" => Private,
1565         "weak" => WeakAny,
1566         "weak_odr" => WeakODR,
1567         _ => tcx.sess.span_fatal(tcx.def_span(def_id), "invalid linkage specified"),
1568     }
1569 }
1570
1571 fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: DefId) -> CodegenFnAttrs {
1572     if cfg!(debug_assertions) {
1573         let def_kind = tcx.def_kind(did);
1574         assert!(
1575             def_kind.has_codegen_attrs(),
1576             "unexpected `def_kind` in `codegen_fn_attrs`: {def_kind:?}",
1577         );
1578     }
1579
1580     let did = did.expect_local();
1581     let attrs = tcx.hir().attrs(tcx.hir().local_def_id_to_hir_id(did));
1582     let mut codegen_fn_attrs = CodegenFnAttrs::new();
1583     if tcx.should_inherit_track_caller(did) {
1584         codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
1585     }
1586
1587     let supported_target_features = tcx.supported_target_features(LOCAL_CRATE);
1588
1589     let mut inline_span = None;
1590     let mut link_ordinal_span = None;
1591     let mut no_sanitize_span = None;
1592     for attr in attrs.iter() {
1593         if attr.has_name(sym::cold) {
1594             codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD;
1595         } else if attr.has_name(sym::rustc_allocator) {
1596             codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR;
1597         } else if attr.has_name(sym::ffi_returns_twice) {
1598             if tcx.is_foreign_item(did) {
1599                 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_RETURNS_TWICE;
1600             } else {
1601                 // `#[ffi_returns_twice]` is only allowed `extern fn`s.
1602                 struct_span_err!(
1603                     tcx.sess,
1604                     attr.span,
1605                     E0724,
1606                     "`#[ffi_returns_twice]` may only be used on foreign functions"
1607                 )
1608                 .emit();
1609             }
1610         } else if attr.has_name(sym::ffi_pure) {
1611             if tcx.is_foreign_item(did) {
1612                 if attrs.iter().any(|a| a.has_name(sym::ffi_const)) {
1613                     // `#[ffi_const]` functions cannot be `#[ffi_pure]`
1614                     struct_span_err!(
1615                         tcx.sess,
1616                         attr.span,
1617                         E0757,
1618                         "`#[ffi_const]` function cannot be `#[ffi_pure]`"
1619                     )
1620                     .emit();
1621                 } else {
1622                     codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_PURE;
1623                 }
1624             } else {
1625                 // `#[ffi_pure]` is only allowed on foreign functions
1626                 struct_span_err!(
1627                     tcx.sess,
1628                     attr.span,
1629                     E0755,
1630                     "`#[ffi_pure]` may only be used on foreign functions"
1631                 )
1632                 .emit();
1633             }
1634         } else if attr.has_name(sym::ffi_const) {
1635             if tcx.is_foreign_item(did) {
1636                 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_CONST;
1637             } else {
1638                 // `#[ffi_const]` is only allowed on foreign functions
1639                 struct_span_err!(
1640                     tcx.sess,
1641                     attr.span,
1642                     E0756,
1643                     "`#[ffi_const]` may only be used on foreign functions"
1644                 )
1645                 .emit();
1646             }
1647         } else if attr.has_name(sym::rustc_nounwind) {
1648             codegen_fn_attrs.flags |= CodegenFnAttrFlags::NEVER_UNWIND;
1649         } else if attr.has_name(sym::rustc_reallocator) {
1650             codegen_fn_attrs.flags |= CodegenFnAttrFlags::REALLOCATOR;
1651         } else if attr.has_name(sym::rustc_deallocator) {
1652             codegen_fn_attrs.flags |= CodegenFnAttrFlags::DEALLOCATOR;
1653         } else if attr.has_name(sym::rustc_allocator_zeroed) {
1654             codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR_ZEROED;
1655         } else if attr.has_name(sym::naked) {
1656             codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED;
1657         } else if attr.has_name(sym::no_mangle) {
1658             codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
1659         } else if attr.has_name(sym::no_coverage) {
1660             codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_COVERAGE;
1661         } else if attr.has_name(sym::rustc_std_internal_symbol) {
1662             codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
1663         } else if attr.has_name(sym::used) {
1664             let inner = attr.meta_item_list();
1665             match inner.as_deref() {
1666                 Some([item]) if item.has_name(sym::linker) => {
1667                     if !tcx.features().used_with_arg {
1668                         feature_err(
1669                             &tcx.sess.parse_sess,
1670                             sym::used_with_arg,
1671                             attr.span,
1672                             "`#[used(linker)]` is currently unstable",
1673                         )
1674                         .emit();
1675                     }
1676                     codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_LINKER;
1677                 }
1678                 Some([item]) if item.has_name(sym::compiler) => {
1679                     if !tcx.features().used_with_arg {
1680                         feature_err(
1681                             &tcx.sess.parse_sess,
1682                             sym::used_with_arg,
1683                             attr.span,
1684                             "`#[used(compiler)]` is currently unstable",
1685                         )
1686                         .emit();
1687                     }
1688                     codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED;
1689                 }
1690                 Some(_) => {
1691                     tcx.sess.emit_err(errors::ExpectedUsedSymbol { span: attr.span });
1692                 }
1693                 None => {
1694                     // Unfortunately, unconditionally using `llvm.used` causes
1695                     // issues in handling `.init_array` with the gold linker,
1696                     // but using `llvm.compiler.used` caused a nontrival amount
1697                     // of unintentional ecosystem breakage -- particularly on
1698                     // Mach-O targets.
1699                     //
1700                     // As a result, we emit `llvm.compiler.used` only on ELF
1701                     // targets. This is somewhat ad-hoc, but actually follows
1702                     // our pre-LLVM 13 behavior (prior to the ecosystem
1703                     // breakage), and seems to match `clang`'s behavior as well
1704                     // (both before and after LLVM 13), possibly because they
1705                     // have similar compatibility concerns to us. See
1706                     // https://github.com/rust-lang/rust/issues/47384#issuecomment-1019080146
1707                     // and following comments for some discussion of this, as
1708                     // well as the comments in `rustc_codegen_llvm` where these
1709                     // flags are handled.
1710                     //
1711                     // Anyway, to be clear: this is still up in the air
1712                     // somewhat, and is subject to change in the future (which
1713                     // is a good thing, because this would ideally be a bit
1714                     // more firmed up).
1715                     let is_like_elf = !(tcx.sess.target.is_like_osx
1716                         || tcx.sess.target.is_like_windows
1717                         || tcx.sess.target.is_like_wasm);
1718                     codegen_fn_attrs.flags |= if is_like_elf {
1719                         CodegenFnAttrFlags::USED
1720                     } else {
1721                         CodegenFnAttrFlags::USED_LINKER
1722                     };
1723                 }
1724             }
1725         } else if attr.has_name(sym::cmse_nonsecure_entry) {
1726             if !matches!(tcx.fn_sig(did).abi(), abi::Abi::C { .. }) {
1727                 struct_span_err!(
1728                     tcx.sess,
1729                     attr.span,
1730                     E0776,
1731                     "`#[cmse_nonsecure_entry]` requires C ABI"
1732                 )
1733                 .emit();
1734             }
1735             if !tcx.sess.target.llvm_target.contains("thumbv8m") {
1736                 struct_span_err!(tcx.sess, attr.span, E0775, "`#[cmse_nonsecure_entry]` is only valid for targets with the TrustZone-M extension")
1737                     .emit();
1738             }
1739             codegen_fn_attrs.flags |= CodegenFnAttrFlags::CMSE_NONSECURE_ENTRY;
1740         } else if attr.has_name(sym::thread_local) {
1741             codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL;
1742         } else if attr.has_name(sym::track_caller) {
1743             if !tcx.is_closure(did.to_def_id()) && tcx.fn_sig(did).abi() != abi::Abi::Rust {
1744                 struct_span_err!(tcx.sess, attr.span, E0737, "`#[track_caller]` requires Rust ABI")
1745                     .emit();
1746             }
1747             if tcx.is_closure(did.to_def_id()) && !tcx.features().closure_track_caller {
1748                 feature_err(
1749                     &tcx.sess.parse_sess,
1750                     sym::closure_track_caller,
1751                     attr.span,
1752                     "`#[track_caller]` on closures is currently unstable",
1753                 )
1754                 .emit();
1755             }
1756             codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
1757         } else if attr.has_name(sym::export_name) {
1758             if let Some(s) = attr.value_str() {
1759                 if s.as_str().contains('\0') {
1760                     // `#[export_name = ...]` will be converted to a null-terminated string,
1761                     // so it may not contain any null characters.
1762                     struct_span_err!(
1763                         tcx.sess,
1764                         attr.span,
1765                         E0648,
1766                         "`export_name` may not contain null characters"
1767                     )
1768                     .emit();
1769                 }
1770                 codegen_fn_attrs.export_name = Some(s);
1771             }
1772         } else if attr.has_name(sym::target_feature) {
1773             if !tcx.is_closure(did.to_def_id())
1774                 && tcx.fn_sig(did).unsafety() == hir::Unsafety::Normal
1775             {
1776                 if tcx.sess.target.is_like_wasm || tcx.sess.opts.actually_rustdoc {
1777                     // The `#[target_feature]` attribute is allowed on
1778                     // WebAssembly targets on all functions, including safe
1779                     // ones. Other targets require that `#[target_feature]` is
1780                     // only applied to unsafe functions (pending the
1781                     // `target_feature_11` feature) because on most targets
1782                     // execution of instructions that are not supported is
1783                     // considered undefined behavior. For WebAssembly which is a
1784                     // 100% safe target at execution time it's not possible to
1785                     // execute undefined instructions, and even if a future
1786                     // feature was added in some form for this it would be a
1787                     // deterministic trap. There is no undefined behavior when
1788                     // executing WebAssembly so `#[target_feature]` is allowed
1789                     // on safe functions (but again, only for WebAssembly)
1790                     //
1791                     // Note that this is also allowed if `actually_rustdoc` so
1792                     // if a target is documenting some wasm-specific code then
1793                     // it's not spuriously denied.
1794                 } else if !tcx.features().target_feature_11 {
1795                     let mut err = feature_err(
1796                         &tcx.sess.parse_sess,
1797                         sym::target_feature_11,
1798                         attr.span,
1799                         "`#[target_feature(..)]` can only be applied to `unsafe` functions",
1800                     );
1801                     err.span_label(tcx.def_span(did), "not an `unsafe` function");
1802                     err.emit();
1803                 } else {
1804                     check_target_feature_trait_unsafe(tcx, did, attr.span);
1805                 }
1806             }
1807             from_target_feature(
1808                 tcx,
1809                 attr,
1810                 supported_target_features,
1811                 &mut codegen_fn_attrs.target_features,
1812             );
1813         } else if attr.has_name(sym::linkage) {
1814             if let Some(val) = attr.value_str() {
1815                 codegen_fn_attrs.linkage = Some(linkage_by_name(tcx, did, val.as_str()));
1816             }
1817         } else if attr.has_name(sym::link_section) {
1818             if let Some(val) = attr.value_str() {
1819                 if val.as_str().bytes().any(|b| b == 0) {
1820                     let msg = format!(
1821                         "illegal null byte in link_section \
1822                          value: `{}`",
1823                         &val
1824                     );
1825                     tcx.sess.span_err(attr.span, &msg);
1826                 } else {
1827                     codegen_fn_attrs.link_section = Some(val);
1828                 }
1829             }
1830         } else if attr.has_name(sym::link_name) {
1831             codegen_fn_attrs.link_name = attr.value_str();
1832         } else if attr.has_name(sym::link_ordinal) {
1833             link_ordinal_span = Some(attr.span);
1834             if let ordinal @ Some(_) = check_link_ordinal(tcx, attr) {
1835                 codegen_fn_attrs.link_ordinal = ordinal;
1836             }
1837         } else if attr.has_name(sym::no_sanitize) {
1838             no_sanitize_span = Some(attr.span);
1839             if let Some(list) = attr.meta_item_list() {
1840                 for item in list.iter() {
1841                     if item.has_name(sym::address) {
1842                         codegen_fn_attrs.no_sanitize |= SanitizerSet::ADDRESS;
1843                     } else if item.has_name(sym::cfi) {
1844                         codegen_fn_attrs.no_sanitize |= SanitizerSet::CFI;
1845                     } else if item.has_name(sym::memory) {
1846                         codegen_fn_attrs.no_sanitize |= SanitizerSet::MEMORY;
1847                     } else if item.has_name(sym::memtag) {
1848                         codegen_fn_attrs.no_sanitize |= SanitizerSet::MEMTAG;
1849                     } else if item.has_name(sym::shadow_call_stack) {
1850                         codegen_fn_attrs.no_sanitize |= SanitizerSet::SHADOWCALLSTACK;
1851                     } else if item.has_name(sym::thread) {
1852                         codegen_fn_attrs.no_sanitize |= SanitizerSet::THREAD;
1853                     } else if item.has_name(sym::hwaddress) {
1854                         codegen_fn_attrs.no_sanitize |= SanitizerSet::HWADDRESS;
1855                     } else {
1856                         tcx.sess
1857                             .struct_span_err(item.span(), "invalid argument for `no_sanitize`")
1858                             .note("expected one of: `address`, `cfi`, `hwaddress`, `memory`, `memtag`, `shadow-call-stack`, or `thread`")
1859                             .emit();
1860                     }
1861                 }
1862             }
1863         } else if attr.has_name(sym::instruction_set) {
1864             codegen_fn_attrs.instruction_set = match attr.meta_kind() {
1865                 Some(MetaItemKind::List(ref items)) => match items.as_slice() {
1866                     [NestedMetaItem::MetaItem(set)] => {
1867                         let segments =
1868                             set.path.segments.iter().map(|x| x.ident.name).collect::<Vec<_>>();
1869                         match segments.as_slice() {
1870                             [sym::arm, sym::a32] | [sym::arm, sym::t32] => {
1871                                 if !tcx.sess.target.has_thumb_interworking {
1872                                     struct_span_err!(
1873                                         tcx.sess.diagnostic(),
1874                                         attr.span,
1875                                         E0779,
1876                                         "target does not support `#[instruction_set]`"
1877                                     )
1878                                     .emit();
1879                                     None
1880                                 } else if segments[1] == sym::a32 {
1881                                     Some(InstructionSetAttr::ArmA32)
1882                                 } else if segments[1] == sym::t32 {
1883                                     Some(InstructionSetAttr::ArmT32)
1884                                 } else {
1885                                     unreachable!()
1886                                 }
1887                             }
1888                             _ => {
1889                                 struct_span_err!(
1890                                     tcx.sess.diagnostic(),
1891                                     attr.span,
1892                                     E0779,
1893                                     "invalid instruction set specified",
1894                                 )
1895                                 .emit();
1896                                 None
1897                             }
1898                         }
1899                     }
1900                     [] => {
1901                         struct_span_err!(
1902                             tcx.sess.diagnostic(),
1903                             attr.span,
1904                             E0778,
1905                             "`#[instruction_set]` requires an argument"
1906                         )
1907                         .emit();
1908                         None
1909                     }
1910                     _ => {
1911                         struct_span_err!(
1912                             tcx.sess.diagnostic(),
1913                             attr.span,
1914                             E0779,
1915                             "cannot specify more than one instruction set"
1916                         )
1917                         .emit();
1918                         None
1919                     }
1920                 },
1921                 _ => {
1922                     struct_span_err!(
1923                         tcx.sess.diagnostic(),
1924                         attr.span,
1925                         E0778,
1926                         "must specify an instruction set"
1927                     )
1928                     .emit();
1929                     None
1930                 }
1931             };
1932         } else if attr.has_name(sym::repr) {
1933             codegen_fn_attrs.alignment = match attr.meta_item_list() {
1934                 Some(items) => match items.as_slice() {
1935                     [item] => match item.name_value_literal() {
1936                         Some((sym::align, literal)) => {
1937                             let alignment = rustc_attr::parse_alignment(&literal.kind);
1938
1939                             match alignment {
1940                                 Ok(align) => Some(align),
1941                                 Err(msg) => {
1942                                     struct_span_err!(
1943                                         tcx.sess.diagnostic(),
1944                                         attr.span,
1945                                         E0589,
1946                                         "invalid `repr(align)` attribute: {}",
1947                                         msg
1948                                     )
1949                                     .emit();
1950
1951                                     None
1952                                 }
1953                             }
1954                         }
1955                         _ => None,
1956                     },
1957                     [] => None,
1958                     _ => None,
1959                 },
1960                 None => None,
1961             };
1962         }
1963     }
1964
1965     codegen_fn_attrs.inline = attrs.iter().fold(InlineAttr::None, |ia, attr| {
1966         if !attr.has_name(sym::inline) {
1967             return ia;
1968         }
1969         match attr.meta_kind() {
1970             Some(MetaItemKind::Word) => InlineAttr::Hint,
1971             Some(MetaItemKind::List(ref items)) => {
1972                 inline_span = Some(attr.span);
1973                 if items.len() != 1 {
1974                     struct_span_err!(
1975                         tcx.sess.diagnostic(),
1976                         attr.span,
1977                         E0534,
1978                         "expected one argument"
1979                     )
1980                     .emit();
1981                     InlineAttr::None
1982                 } else if list_contains_name(&items, sym::always) {
1983                     InlineAttr::Always
1984                 } else if list_contains_name(&items, sym::never) {
1985                     InlineAttr::Never
1986                 } else {
1987                     struct_span_err!(
1988                         tcx.sess.diagnostic(),
1989                         items[0].span(),
1990                         E0535,
1991                         "invalid argument"
1992                     )
1993                     .help("valid inline arguments are `always` and `never`")
1994                     .emit();
1995
1996                     InlineAttr::None
1997                 }
1998             }
1999             Some(MetaItemKind::NameValue(_)) => ia,
2000             None => ia,
2001         }
2002     });
2003
2004     codegen_fn_attrs.optimize = attrs.iter().fold(OptimizeAttr::None, |ia, attr| {
2005         if !attr.has_name(sym::optimize) {
2006             return ia;
2007         }
2008         let err = |sp, s| struct_span_err!(tcx.sess.diagnostic(), sp, E0722, "{}", s).emit();
2009         match attr.meta_kind() {
2010             Some(MetaItemKind::Word) => {
2011                 err(attr.span, "expected one argument");
2012                 ia
2013             }
2014             Some(MetaItemKind::List(ref items)) => {
2015                 inline_span = Some(attr.span);
2016                 if items.len() != 1 {
2017                     err(attr.span, "expected one argument");
2018                     OptimizeAttr::None
2019                 } else if list_contains_name(&items, sym::size) {
2020                     OptimizeAttr::Size
2021                 } else if list_contains_name(&items, sym::speed) {
2022                     OptimizeAttr::Speed
2023                 } else {
2024                     err(items[0].span(), "invalid argument");
2025                     OptimizeAttr::None
2026                 }
2027             }
2028             Some(MetaItemKind::NameValue(_)) => ia,
2029             None => ia,
2030         }
2031     });
2032
2033     // #73631: closures inherit `#[target_feature]` annotations
2034     if tcx.features().target_feature_11 && tcx.is_closure(did.to_def_id()) {
2035         let owner_id = tcx.parent(did.to_def_id());
2036         if tcx.def_kind(owner_id).has_codegen_attrs() {
2037             codegen_fn_attrs
2038                 .target_features
2039                 .extend(tcx.codegen_fn_attrs(owner_id).target_features.iter().copied());
2040         }
2041     }
2042
2043     // If a function uses #[target_feature] it can't be inlined into general
2044     // purpose functions as they wouldn't have the right target features
2045     // enabled. For that reason we also forbid #[inline(always)] as it can't be
2046     // respected.
2047     if !codegen_fn_attrs.target_features.is_empty() {
2048         if codegen_fn_attrs.inline == InlineAttr::Always {
2049             if let Some(span) = inline_span {
2050                 tcx.sess.span_err(
2051                     span,
2052                     "cannot use `#[inline(always)]` with \
2053                      `#[target_feature]`",
2054                 );
2055             }
2056         }
2057     }
2058
2059     if !codegen_fn_attrs.no_sanitize.is_empty() {
2060         if codegen_fn_attrs.inline == InlineAttr::Always {
2061             if let (Some(no_sanitize_span), Some(inline_span)) = (no_sanitize_span, inline_span) {
2062                 let hir_id = tcx.hir().local_def_id_to_hir_id(did);
2063                 tcx.struct_span_lint_hir(
2064                     lint::builtin::INLINE_NO_SANITIZE,
2065                     hir_id,
2066                     no_sanitize_span,
2067                     "`no_sanitize` will have no effect after inlining",
2068                     |lint| lint.span_note(inline_span, "inlining requested here"),
2069                 )
2070             }
2071         }
2072     }
2073
2074     // Weak lang items have the same semantics as "std internal" symbols in the
2075     // sense that they're preserved through all our LTO passes and only
2076     // strippable by the linker.
2077     //
2078     // Additionally weak lang items have predetermined symbol names.
2079     if WEAK_LANG_ITEMS.iter().any(|&l| tcx.lang_items().get(l) == Some(did.to_def_id())) {
2080         codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2081     }
2082     if let Some((name, _)) = lang_items::extract(attrs)
2083         && let Some(lang_item) = LangItem::from_name(name)
2084         && let Some(link_name) = lang_item.link_name()
2085     {
2086         codegen_fn_attrs.export_name = Some(link_name);
2087         codegen_fn_attrs.link_name = Some(link_name);
2088     }
2089     check_link_name_xor_ordinal(tcx, &codegen_fn_attrs, link_ordinal_span);
2090
2091     // Internal symbols to the standard library all have no_mangle semantics in
2092     // that they have defined symbol names present in the function name. This
2093     // also applies to weak symbols where they all have known symbol names.
2094     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
2095         codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2096     }
2097
2098     // Any linkage to LLVM intrinsics for now forcibly marks them all as never
2099     // unwinds since LLVM sometimes can't handle codegen which `invoke`s
2100     // intrinsic functions.
2101     if let Some(name) = &codegen_fn_attrs.link_name {
2102         if name.as_str().starts_with("llvm.") {
2103             codegen_fn_attrs.flags |= CodegenFnAttrFlags::NEVER_UNWIND;
2104         }
2105     }
2106
2107     codegen_fn_attrs
2108 }
2109
2110 /// Computes the set of target features used in a function for the purposes of
2111 /// inline assembly.
2112 fn asm_target_features<'tcx>(tcx: TyCtxt<'tcx>, did: DefId) -> &'tcx FxHashSet<Symbol> {
2113     let mut target_features = tcx.sess.unstable_target_features.clone();
2114     if tcx.def_kind(did).has_codegen_attrs() {
2115         let attrs = tcx.codegen_fn_attrs(did);
2116         target_features.extend(&attrs.target_features);
2117         match attrs.instruction_set {
2118             None => {}
2119             Some(InstructionSetAttr::ArmA32) => {
2120                 target_features.remove(&sym::thumb_mode);
2121             }
2122             Some(InstructionSetAttr::ArmT32) => {
2123                 target_features.insert(sym::thumb_mode);
2124             }
2125         }
2126     }
2127
2128     tcx.arena.alloc(target_features)
2129 }
2130
2131 /// Checks if the provided DefId is a method in a trait impl for a trait which has track_caller
2132 /// applied to the method prototype.
2133 fn should_inherit_track_caller(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
2134     if let Some(impl_item) = tcx.opt_associated_item(def_id)
2135         && let ty::AssocItemContainer::ImplContainer = impl_item.container
2136         && let Some(trait_item) = impl_item.trait_item_def_id
2137     {
2138         return tcx
2139             .codegen_fn_attrs(trait_item)
2140             .flags
2141             .intersects(CodegenFnAttrFlags::TRACK_CALLER);
2142     }
2143
2144     false
2145 }
2146
2147 fn check_link_ordinal(tcx: TyCtxt<'_>, attr: &ast::Attribute) -> Option<u16> {
2148     use rustc_ast::{Lit, LitIntType, LitKind};
2149     if !tcx.features().raw_dylib && tcx.sess.target.arch == "x86" {
2150         feature_err(
2151             &tcx.sess.parse_sess,
2152             sym::raw_dylib,
2153             attr.span,
2154             "`#[link_ordinal]` is unstable on x86",
2155         )
2156         .emit();
2157     }
2158     let meta_item_list = attr.meta_item_list();
2159     let meta_item_list = meta_item_list.as_deref();
2160     let sole_meta_list = match meta_item_list {
2161         Some([item]) => item.literal(),
2162         Some(_) => {
2163             tcx.sess
2164                 .struct_span_err(attr.span, "incorrect number of arguments to `#[link_ordinal]`")
2165                 .note("the attribute requires exactly one argument")
2166                 .emit();
2167             return None;
2168         }
2169         _ => None,
2170     };
2171     if let Some(Lit { kind: LitKind::Int(ordinal, LitIntType::Unsuffixed), .. }) = sole_meta_list {
2172         // According to the table at https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#import-header,
2173         // the ordinal must fit into 16 bits.  Similarly, the Ordinal field in COFFShortExport (defined
2174         // in llvm/include/llvm/Object/COFFImportFile.h), which we use to communicate import information
2175         // to LLVM for `#[link(kind = "raw-dylib"_])`, is also defined to be uint16_t.
2176         //
2177         // FIXME: should we allow an ordinal of 0?  The MSVC toolchain has inconsistent support for this:
2178         // both LINK.EXE and LIB.EXE signal errors and abort when given a .DEF file that specifies
2179         // a zero ordinal.  However, llvm-dlltool is perfectly happy to generate an import library
2180         // for such a .DEF file, and MSVC's LINK.EXE is also perfectly happy to consume an import
2181         // library produced by LLVM with an ordinal of 0, and it generates an .EXE.  (I don't know yet
2182         // if the resulting EXE runs, as I haven't yet built the necessary DLL -- see earlier comment
2183         // about LINK.EXE failing.)
2184         if *ordinal <= u16::MAX as u128 {
2185             Some(*ordinal as u16)
2186         } else {
2187             let msg = format!("ordinal value in `link_ordinal` is too large: `{}`", &ordinal);
2188             tcx.sess
2189                 .struct_span_err(attr.span, &msg)
2190                 .note("the value may not exceed `u16::MAX`")
2191                 .emit();
2192             None
2193         }
2194     } else {
2195         tcx.sess
2196             .struct_span_err(attr.span, "illegal ordinal format in `link_ordinal`")
2197             .note("an unsuffixed integer value, e.g., `1`, is expected")
2198             .emit();
2199         None
2200     }
2201 }
2202
2203 fn check_link_name_xor_ordinal(
2204     tcx: TyCtxt<'_>,
2205     codegen_fn_attrs: &CodegenFnAttrs,
2206     inline_span: Option<Span>,
2207 ) {
2208     if codegen_fn_attrs.link_name.is_none() || codegen_fn_attrs.link_ordinal.is_none() {
2209         return;
2210     }
2211     let msg = "cannot use `#[link_name]` with `#[link_ordinal]`";
2212     if let Some(span) = inline_span {
2213         tcx.sess.span_err(span, msg);
2214     } else {
2215         tcx.sess.err(msg);
2216     }
2217 }
2218
2219 /// Checks the function annotated with `#[target_feature]` is not a safe
2220 /// trait method implementation, reporting an error if it is.
2221 fn check_target_feature_trait_unsafe(tcx: TyCtxt<'_>, id: LocalDefId, attr_span: Span) {
2222     let hir_id = tcx.hir().local_def_id_to_hir_id(id);
2223     let node = tcx.hir().get(hir_id);
2224     if let Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }) = node {
2225         let parent_id = tcx.hir().get_parent_item(hir_id);
2226         let parent_item = tcx.hir().expect_item(parent_id.def_id);
2227         if let hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) = parent_item.kind {
2228             tcx.sess
2229                 .struct_span_err(
2230                     attr_span,
2231                     "`#[target_feature(..)]` cannot be applied to safe trait method",
2232                 )
2233                 .span_label(attr_span, "cannot be applied to safe trait method")
2234                 .span_label(tcx.def_span(id), "not an `unsafe` function")
2235                 .emit();
2236         }
2237     }
2238 }