]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_typeck/src/collect.rs
New upstream version 1.50.0+dfsg1
[rustc.git] / compiler / rustc_typeck / 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, SizedByDefault};
18 use crate::bounds::Bounds;
19 use crate::check::intrinsic::intrinsic_operation_unsafety;
20 use crate::constrained_generic_params as cgp;
21 use crate::errors;
22 use crate::middle::resolve_lifetime as rl;
23 use rustc_ast as ast;
24 use rustc_ast::{MetaItemKind, NestedMetaItem};
25 use rustc_attr::{list_contains_name, InlineAttr, InstructionSetAttr, OptimizeAttr};
26 use rustc_data_structures::captures::Captures;
27 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
28 use rustc_errors::{struct_span_err, Applicability};
29 use rustc_hir as hir;
30 use rustc_hir::def::{CtorKind, DefKind, Res};
31 use rustc_hir::def_id::{DefId, LocalDefId, LOCAL_CRATE};
32 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
33 use rustc_hir::weak_lang_items;
34 use rustc_hir::{GenericParamKind, HirId, Node};
35 use rustc_middle::hir::map::blocks::FnLikeNode;
36 use rustc_middle::hir::map::Map;
37 use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
38 use rustc_middle::mir::mono::Linkage;
39 use rustc_middle::ty::query::Providers;
40 use rustc_middle::ty::subst::InternalSubsts;
41 use rustc_middle::ty::util::Discr;
42 use rustc_middle::ty::util::IntTypeExt;
43 use rustc_middle::ty::{self, AdtKind, Const, DefIdTree, ToPolyTraitRef, Ty, TyCtxt};
44 use rustc_middle::ty::{ReprOptions, ToPredicate, WithConstness};
45 use rustc_session::config::SanitizerSet;
46 use rustc_session::lint;
47 use rustc_session::parse::feature_err;
48 use rustc_span::symbol::{kw, sym, Ident, Symbol};
49 use rustc_span::{Span, DUMMY_SP};
50 use rustc_target::spec::abi;
51 use rustc_trait_selection::traits::error_reporting::suggestions::NextTypeParamName;
52
53 use std::ops::ControlFlow;
54
55 mod item_bounds;
56 mod type_of;
57
58 struct OnlySelfBounds(bool);
59
60 ///////////////////////////////////////////////////////////////////////////
61 // Main entry point
62
63 fn collect_mod_item_types(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
64 tcx.hir().visit_item_likes_in_module(
65 module_def_id,
66 &mut CollectItemTypesVisitor { tcx }.as_deep_visitor(),
67 );
68 }
69
70 pub fn provide(providers: &mut Providers) {
71 *providers = Providers {
72 opt_const_param_of: type_of::opt_const_param_of,
73 type_of: type_of::type_of,
74 item_bounds: item_bounds::item_bounds,
75 explicit_item_bounds: item_bounds::explicit_item_bounds,
76 generics_of,
77 predicates_of,
78 predicates_defined_on,
79 projection_ty_from_predicates,
80 explicit_predicates_of,
81 super_predicates_of,
82 trait_explicit_predicates_and_bounds,
83 type_param_predicates,
84 trait_def,
85 adt_def,
86 fn_sig,
87 impl_trait_ref,
88 impl_polarity,
89 is_foreign_item,
90 static_mutability,
91 generator_kind,
92 codegen_fn_attrs,
93 collect_mod_item_types,
94 ..*providers
95 };
96 }
97
98 ///////////////////////////////////////////////////////////////////////////
99
100 /// Context specific to some particular item. This is what implements
101 /// `AstConv`. It has information about the predicates that are defined
102 /// on the trait. Unfortunately, this predicate information is
103 /// available in various different forms at various points in the
104 /// process. So we can't just store a pointer to e.g., the AST or the
105 /// parsed ty form, we have to be more flexible. To this end, the
106 /// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy
107 /// `get_type_parameter_bounds` requests, drawing the information from
108 /// the AST (`hir::Generics`), recursively.
109 pub struct ItemCtxt<'tcx> {
110 tcx: TyCtxt<'tcx>,
111 item_def_id: DefId,
112 }
113
114 ///////////////////////////////////////////////////////////////////////////
115
116 #[derive(Default)]
117 crate struct PlaceholderHirTyCollector(crate Vec<Span>);
118
119 impl<'v> Visitor<'v> for PlaceholderHirTyCollector {
120 type Map = intravisit::ErasedMap<'v>;
121
122 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
123 NestedVisitorMap::None
124 }
125 fn visit_ty(&mut self, t: &'v hir::Ty<'v>) {
126 if let hir::TyKind::Infer = t.kind {
127 self.0.push(t.span);
128 }
129 intravisit::walk_ty(self, t)
130 }
131 }
132
133 struct CollectItemTypesVisitor<'tcx> {
134 tcx: TyCtxt<'tcx>,
135 }
136
137 /// If there are any placeholder types (`_`), emit an error explaining that this is not allowed
138 /// and suggest adding type parameters in the appropriate place, taking into consideration any and
139 /// all already existing generic type parameters to avoid suggesting a name that is already in use.
140 crate fn placeholder_type_error(
141 tcx: TyCtxt<'tcx>,
142 span: Option<Span>,
143 generics: &[hir::GenericParam<'_>],
144 placeholder_types: Vec<Span>,
145 suggest: bool,
146 ) {
147 if placeholder_types.is_empty() {
148 return;
149 }
150
151 let type_name = generics.next_type_param_name(None);
152 let mut sugg: Vec<_> =
153 placeholder_types.iter().map(|sp| (*sp, (*type_name).to_string())).collect();
154
155 if generics.is_empty() {
156 if let Some(span) = span {
157 sugg.push((span, format!("<{}>", type_name)));
158 }
159 } else if let Some(arg) = generics.iter().find(|arg| match arg.name {
160 hir::ParamName::Plain(Ident { name: kw::Underscore, .. }) => true,
161 _ => false,
162 }) {
163 // Account for `_` already present in cases like `struct S<_>(_);` and suggest
164 // `struct S<T>(T);` instead of `struct S<_, T>(T);`.
165 sugg.push((arg.span, (*type_name).to_string()));
166 } else {
167 let last = generics.iter().last().unwrap();
168 sugg.push((
169 // Account for bounds, we want `fn foo<T: E, K>(_: K)` not `fn foo<T, K: E>(_: K)`.
170 last.bounds_span().unwrap_or(last.span).shrink_to_hi(),
171 format!(", {}", type_name),
172 ));
173 }
174
175 let mut err = bad_placeholder_type(tcx, placeholder_types);
176 if suggest {
177 err.multipart_suggestion(
178 "use type parameters instead",
179 sugg,
180 Applicability::HasPlaceholders,
181 );
182 }
183 err.emit();
184 }
185
186 fn reject_placeholder_type_signatures_in_item(tcx: TyCtxt<'tcx>, item: &'tcx hir::Item<'tcx>) {
187 let (generics, suggest) = match &item.kind {
188 hir::ItemKind::Union(_, generics)
189 | hir::ItemKind::Enum(_, generics)
190 | hir::ItemKind::TraitAlias(generics, _)
191 | hir::ItemKind::Trait(_, _, generics, ..)
192 | hir::ItemKind::Impl { generics, .. }
193 | hir::ItemKind::Struct(_, generics) => (generics, true),
194 hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. })
195 | hir::ItemKind::TyAlias(_, generics) => (generics, false),
196 // `static`, `fn` and `const` are handled elsewhere to suggest appropriate type.
197 _ => return,
198 };
199
200 let mut visitor = PlaceholderHirTyCollector::default();
201 visitor.visit_item(item);
202
203 placeholder_type_error(tcx, Some(generics.span), &generics.params[..], visitor.0, suggest);
204 }
205
206 impl Visitor<'tcx> for CollectItemTypesVisitor<'tcx> {
207 type Map = Map<'tcx>;
208
209 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
210 NestedVisitorMap::OnlyBodies(self.tcx.hir())
211 }
212
213 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
214 convert_item(self.tcx, item.hir_id);
215 reject_placeholder_type_signatures_in_item(self.tcx, item);
216 intravisit::walk_item(self, item);
217 }
218
219 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
220 for param in generics.params {
221 match param.kind {
222 hir::GenericParamKind::Lifetime { .. } => {}
223 hir::GenericParamKind::Type { default: Some(_), .. } => {
224 let def_id = self.tcx.hir().local_def_id(param.hir_id);
225 self.tcx.ensure().type_of(def_id);
226 }
227 hir::GenericParamKind::Type { .. } => {}
228 hir::GenericParamKind::Const { .. } => {
229 let def_id = self.tcx.hir().local_def_id(param.hir_id);
230 self.tcx.ensure().type_of(def_id);
231 // FIXME(const_generics:defaults)
232 }
233 }
234 }
235 intravisit::walk_generics(self, generics);
236 }
237
238 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
239 if let hir::ExprKind::Closure(..) = expr.kind {
240 let def_id = self.tcx.hir().local_def_id(expr.hir_id);
241 self.tcx.ensure().generics_of(def_id);
242 self.tcx.ensure().type_of(def_id);
243 }
244 intravisit::walk_expr(self, expr);
245 }
246
247 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
248 convert_trait_item(self.tcx, trait_item.hir_id);
249 intravisit::walk_trait_item(self, trait_item);
250 }
251
252 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
253 convert_impl_item(self.tcx, impl_item.hir_id);
254 intravisit::walk_impl_item(self, impl_item);
255 }
256 }
257
258 ///////////////////////////////////////////////////////////////////////////
259 // Utility types and common code for the above passes.
260
261 fn bad_placeholder_type(
262 tcx: TyCtxt<'tcx>,
263 mut spans: Vec<Span>,
264 ) -> rustc_errors::DiagnosticBuilder<'tcx> {
265 spans.sort();
266 let mut err = struct_span_err!(
267 tcx.sess,
268 spans.clone(),
269 E0121,
270 "the type placeholder `_` is not allowed within types on item signatures",
271 );
272 for span in spans {
273 err.span_label(span, "not allowed in type signatures");
274 }
275 err
276 }
277
278 impl ItemCtxt<'tcx> {
279 pub fn new(tcx: TyCtxt<'tcx>, item_def_id: DefId) -> ItemCtxt<'tcx> {
280 ItemCtxt { tcx, item_def_id }
281 }
282
283 pub fn to_ty(&self, ast_ty: &'tcx hir::Ty<'tcx>) -> Ty<'tcx> {
284 AstConv::ast_ty_to_ty(self, ast_ty)
285 }
286
287 pub fn hir_id(&self) -> hir::HirId {
288 self.tcx.hir().local_def_id_to_hir_id(self.item_def_id.expect_local())
289 }
290
291 pub fn node(&self) -> hir::Node<'tcx> {
292 self.tcx.hir().get(self.hir_id())
293 }
294 }
295
296 impl AstConv<'tcx> for ItemCtxt<'tcx> {
297 fn tcx(&self) -> TyCtxt<'tcx> {
298 self.tcx
299 }
300
301 fn item_def_id(&self) -> Option<DefId> {
302 Some(self.item_def_id)
303 }
304
305 fn default_constness_for_trait_bounds(&self) -> hir::Constness {
306 if let Some(fn_like) = FnLikeNode::from_node(self.node()) {
307 fn_like.constness()
308 } else {
309 hir::Constness::NotConst
310 }
311 }
312
313 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId) -> ty::GenericPredicates<'tcx> {
314 self.tcx.at(span).type_param_predicates((self.item_def_id, def_id.expect_local()))
315 }
316
317 fn re_infer(&self, _: Option<&ty::GenericParamDef>, _: Span) -> Option<ty::Region<'tcx>> {
318 None
319 }
320
321 fn allow_ty_infer(&self) -> bool {
322 false
323 }
324
325 fn ty_infer(&self, _: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx> {
326 self.tcx().ty_error_with_message(span, "bad_placeholder_type")
327 }
328
329 fn ct_infer(
330 &self,
331 ty: Ty<'tcx>,
332 _: Option<&ty::GenericParamDef>,
333 span: Span,
334 ) -> &'tcx Const<'tcx> {
335 bad_placeholder_type(self.tcx(), vec![span]).emit();
336 self.tcx().const_error(ty)
337 }
338
339 fn projected_ty_from_poly_trait_ref(
340 &self,
341 span: Span,
342 item_def_id: DefId,
343 item_segment: &hir::PathSegment<'_>,
344 poly_trait_ref: ty::PolyTraitRef<'tcx>,
345 ) -> Ty<'tcx> {
346 if let Some(trait_ref) = poly_trait_ref.no_bound_vars() {
347 let item_substs = <dyn AstConv<'tcx>>::create_substs_for_associated_item(
348 self,
349 self.tcx,
350 span,
351 item_def_id,
352 item_segment,
353 trait_ref.substs,
354 );
355 self.tcx().mk_projection(item_def_id, item_substs)
356 } else {
357 // There are no late-bound regions; we can just ignore the binder.
358 let mut err = struct_span_err!(
359 self.tcx().sess,
360 span,
361 E0212,
362 "cannot use the associated type of a trait \
363 with uninferred generic parameters"
364 );
365
366 match self.node() {
367 hir::Node::Field(_) | hir::Node::Ctor(_) | hir::Node::Variant(_) => {
368 let item =
369 self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(self.hir_id()));
370 match &item.kind {
371 hir::ItemKind::Enum(_, generics)
372 | hir::ItemKind::Struct(_, generics)
373 | hir::ItemKind::Union(_, generics) => {
374 let lt_name = get_new_lifetime_name(self.tcx, poly_trait_ref, generics);
375 let (lt_sp, sugg) = match &generics.params[..] {
376 [] => (generics.span, format!("<{}>", lt_name)),
377 [bound, ..] => {
378 (bound.span.shrink_to_lo(), format!("{}, ", lt_name))
379 }
380 };
381 let suggestions = vec![
382 (lt_sp, sugg),
383 (
384 span,
385 format!(
386 "{}::{}",
387 // Replace the existing lifetimes with a new named lifetime.
388 self.tcx
389 .replace_late_bound_regions(poly_trait_ref, |_| {
390 self.tcx.mk_region(ty::ReEarlyBound(
391 ty::EarlyBoundRegion {
392 def_id: item_def_id,
393 index: 0,
394 name: Symbol::intern(&lt_name),
395 },
396 ))
397 })
398 .0,
399 item_segment.ident
400 ),
401 ),
402 ];
403 err.multipart_suggestion(
404 "use a fully qualified path with explicit lifetimes",
405 suggestions,
406 Applicability::MaybeIncorrect,
407 );
408 }
409 _ => {}
410 }
411 }
412 hir::Node::Item(hir::Item {
413 kind:
414 hir::ItemKind::Struct(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Union(..),
415 ..
416 }) => {}
417 hir::Node::Item(_)
418 | hir::Node::ForeignItem(_)
419 | hir::Node::TraitItem(_)
420 | hir::Node::ImplItem(_) => {
421 err.span_suggestion(
422 span,
423 "use a fully qualified path with inferred lifetimes",
424 format!(
425 "{}::{}",
426 // Erase named lt, we want `<A as B<'_>::C`, not `<A as B<'a>::C`.
427 self.tcx.anonymize_late_bound_regions(poly_trait_ref).skip_binder(),
428 item_segment.ident
429 ),
430 Applicability::MaybeIncorrect,
431 );
432 }
433 _ => {}
434 }
435 err.emit();
436 self.tcx().ty_error()
437 }
438 }
439
440 fn normalize_ty(&self, _span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
441 // Types in item signatures are not normalized to avoid undue dependencies.
442 ty
443 }
444
445 fn set_tainted_by_errors(&self) {
446 // There's no obvious place to track this, so just let it go.
447 }
448
449 fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) {
450 // There's no place to record types from signatures?
451 }
452 }
453
454 /// Synthesize a new lifetime name that doesn't clash with any of the lifetimes already present.
455 fn get_new_lifetime_name<'tcx>(
456 tcx: TyCtxt<'tcx>,
457 poly_trait_ref: ty::PolyTraitRef<'tcx>,
458 generics: &hir::Generics<'tcx>,
459 ) -> String {
460 let existing_lifetimes = tcx
461 .collect_referenced_late_bound_regions(&poly_trait_ref)
462 .into_iter()
463 .filter_map(|lt| {
464 if let ty::BoundRegionKind::BrNamed(_, name) = lt {
465 Some(name.as_str().to_string())
466 } else {
467 None
468 }
469 })
470 .chain(generics.params.iter().filter_map(|param| {
471 if let hir::GenericParamKind::Lifetime { .. } = &param.kind {
472 Some(param.name.ident().as_str().to_string())
473 } else {
474 None
475 }
476 }))
477 .collect::<FxHashSet<String>>();
478
479 let a_to_z_repeat_n = |n| {
480 (b'a'..=b'z').map(move |c| {
481 let mut s = '\''.to_string();
482 s.extend(std::iter::repeat(char::from(c)).take(n));
483 s
484 })
485 };
486
487 // If all single char lifetime names are present, we wrap around and double the chars.
488 (1..).flat_map(a_to_z_repeat_n).find(|lt| !existing_lifetimes.contains(lt.as_str())).unwrap()
489 }
490
491 /// Returns the predicates defined on `item_def_id` of the form
492 /// `X: Foo` where `X` is the type parameter `def_id`.
493 fn type_param_predicates(
494 tcx: TyCtxt<'_>,
495 (item_def_id, def_id): (DefId, LocalDefId),
496 ) -> ty::GenericPredicates<'_> {
497 use rustc_hir::*;
498
499 // In the AST, bounds can derive from two places. Either
500 // written inline like `<T: Foo>` or in a where-clause like
501 // `where T: Foo`.
502
503 let param_id = tcx.hir().local_def_id_to_hir_id(def_id);
504 let param_owner = tcx.hir().ty_param_owner(param_id);
505 let param_owner_def_id = tcx.hir().local_def_id(param_owner);
506 let generics = tcx.generics_of(param_owner_def_id);
507 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
508 let ty = tcx.mk_ty_param(index, tcx.hir().ty_param_name(param_id));
509
510 // Don't look for bounds where the type parameter isn't in scope.
511 let parent = if item_def_id == param_owner_def_id.to_def_id() {
512 None
513 } else {
514 tcx.generics_of(item_def_id).parent
515 };
516
517 let mut result = parent
518 .map(|parent| {
519 let icx = ItemCtxt::new(tcx, parent);
520 icx.get_type_parameter_bounds(DUMMY_SP, def_id.to_def_id())
521 })
522 .unwrap_or_default();
523 let mut extend = None;
524
525 let item_hir_id = tcx.hir().local_def_id_to_hir_id(item_def_id.expect_local());
526 let ast_generics = match tcx.hir().get(item_hir_id) {
527 Node::TraitItem(item) => &item.generics,
528
529 Node::ImplItem(item) => &item.generics,
530
531 Node::Item(item) => {
532 match item.kind {
533 ItemKind::Fn(.., ref generics, _)
534 | ItemKind::Impl { ref generics, .. }
535 | ItemKind::TyAlias(_, ref generics)
536 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
537 | ItemKind::Enum(_, ref generics)
538 | ItemKind::Struct(_, ref generics)
539 | ItemKind::Union(_, ref generics) => generics,
540 ItemKind::Trait(_, _, ref generics, ..) => {
541 // Implied `Self: Trait` and supertrait bounds.
542 if param_id == item_hir_id {
543 let identity_trait_ref = ty::TraitRef::identity(tcx, item_def_id);
544 extend =
545 Some((identity_trait_ref.without_const().to_predicate(tcx), item.span));
546 }
547 generics
548 }
549 _ => return result,
550 }
551 }
552
553 Node::ForeignItem(item) => match item.kind {
554 ForeignItemKind::Fn(_, _, ref generics) => generics,
555 _ => return result,
556 },
557
558 _ => return result,
559 };
560
561 let icx = ItemCtxt::new(tcx, item_def_id);
562 let extra_predicates = extend.into_iter().chain(
563 icx.type_parameter_bounds_in_generics(ast_generics, param_id, ty, OnlySelfBounds(true))
564 .into_iter()
565 .filter(|(predicate, _)| match predicate.skip_binders() {
566 ty::PredicateAtom::Trait(data, _) => data.self_ty().is_param(index),
567 _ => false,
568 }),
569 );
570 result.predicates =
571 tcx.arena.alloc_from_iter(result.predicates.iter().copied().chain(extra_predicates));
572 result
573 }
574
575 impl ItemCtxt<'tcx> {
576 /// Finds bounds from `hir::Generics`. This requires scanning through the
577 /// AST. We do this to avoid having to convert *all* the bounds, which
578 /// would create artificial cycles. Instead, we can only convert the
579 /// bounds for a type parameter `X` if `X::Foo` is used.
580 fn type_parameter_bounds_in_generics(
581 &self,
582 ast_generics: &'tcx hir::Generics<'tcx>,
583 param_id: hir::HirId,
584 ty: Ty<'tcx>,
585 only_self_bounds: OnlySelfBounds,
586 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
587 let constness = self.default_constness_for_trait_bounds();
588 let from_ty_params = ast_generics
589 .params
590 .iter()
591 .filter_map(|param| match param.kind {
592 GenericParamKind::Type { .. } if param.hir_id == param_id => Some(&param.bounds),
593 _ => None,
594 })
595 .flat_map(|bounds| bounds.iter())
596 .flat_map(|b| predicates_from_bound(self, ty, b, constness));
597
598 let from_where_clauses = ast_generics
599 .where_clause
600 .predicates
601 .iter()
602 .filter_map(|wp| match *wp {
603 hir::WherePredicate::BoundPredicate(ref bp) => Some(bp),
604 _ => None,
605 })
606 .flat_map(|bp| {
607 let bt = if is_param(self.tcx, &bp.bounded_ty, param_id) {
608 Some(ty)
609 } else if !only_self_bounds.0 {
610 Some(self.to_ty(&bp.bounded_ty))
611 } else {
612 None
613 };
614 bp.bounds.iter().filter_map(move |b| bt.map(|bt| (bt, b)))
615 })
616 .flat_map(|(bt, b)| predicates_from_bound(self, bt, b, constness));
617
618 from_ty_params.chain(from_where_clauses).collect()
619 }
620 }
621
622 /// Tests whether this is the AST for a reference to the type
623 /// parameter with ID `param_id`. We use this so as to avoid running
624 /// `ast_ty_to_ty`, because we want to avoid triggering an all-out
625 /// conversion of the type to avoid inducing unnecessary cycles.
626 fn is_param(tcx: TyCtxt<'_>, ast_ty: &hir::Ty<'_>, param_id: hir::HirId) -> bool {
627 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = ast_ty.kind {
628 match path.res {
629 Res::SelfTy(Some(def_id), None) | Res::Def(DefKind::TyParam, def_id) => {
630 def_id == tcx.hir().local_def_id(param_id).to_def_id()
631 }
632 _ => false,
633 }
634 } else {
635 false
636 }
637 }
638
639 fn convert_item(tcx: TyCtxt<'_>, item_id: hir::HirId) {
640 let it = tcx.hir().expect_item(item_id);
641 debug!("convert: item {} with id {}", it.ident, it.hir_id);
642 let def_id = tcx.hir().local_def_id(item_id);
643 match it.kind {
644 // These don't define types.
645 hir::ItemKind::ExternCrate(_)
646 | hir::ItemKind::Use(..)
647 | hir::ItemKind::Mod(_)
648 | hir::ItemKind::GlobalAsm(_) => {}
649 hir::ItemKind::ForeignMod { items, .. } => {
650 for item in items {
651 let item = tcx.hir().foreign_item(item.id);
652 let def_id = tcx.hir().local_def_id(item.hir_id);
653 tcx.ensure().generics_of(def_id);
654 tcx.ensure().type_of(def_id);
655 tcx.ensure().predicates_of(def_id);
656 if let hir::ForeignItemKind::Fn(..) = item.kind {
657 tcx.ensure().fn_sig(def_id);
658 }
659 }
660 }
661 hir::ItemKind::Enum(ref enum_definition, _) => {
662 tcx.ensure().generics_of(def_id);
663 tcx.ensure().type_of(def_id);
664 tcx.ensure().predicates_of(def_id);
665 convert_enum_variant_types(tcx, def_id.to_def_id(), &enum_definition.variants);
666 }
667 hir::ItemKind::Impl { .. } => {
668 tcx.ensure().generics_of(def_id);
669 tcx.ensure().type_of(def_id);
670 tcx.ensure().impl_trait_ref(def_id);
671 tcx.ensure().predicates_of(def_id);
672 }
673 hir::ItemKind::Trait(..) => {
674 tcx.ensure().generics_of(def_id);
675 tcx.ensure().trait_def(def_id);
676 tcx.at(it.span).super_predicates_of(def_id);
677 tcx.ensure().predicates_of(def_id);
678 }
679 hir::ItemKind::TraitAlias(..) => {
680 tcx.ensure().generics_of(def_id);
681 tcx.at(it.span).super_predicates_of(def_id);
682 tcx.ensure().predicates_of(def_id);
683 }
684 hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
685 tcx.ensure().generics_of(def_id);
686 tcx.ensure().type_of(def_id);
687 tcx.ensure().predicates_of(def_id);
688
689 for f in struct_def.fields() {
690 let def_id = tcx.hir().local_def_id(f.hir_id);
691 tcx.ensure().generics_of(def_id);
692 tcx.ensure().type_of(def_id);
693 tcx.ensure().predicates_of(def_id);
694 }
695
696 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
697 convert_variant_ctor(tcx, ctor_hir_id);
698 }
699 }
700
701 // Desugared from `impl Trait`, so visited by the function's return type.
702 hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: Some(_), .. }) => {}
703
704 // Don't call `type_of` on opaque types, since that depends on type
705 // checking function bodies. `check_item_type` ensures that it's called
706 // instead.
707 hir::ItemKind::OpaqueTy(..) => {
708 tcx.ensure().generics_of(def_id);
709 tcx.ensure().predicates_of(def_id);
710 tcx.ensure().explicit_item_bounds(def_id);
711 }
712 hir::ItemKind::TyAlias(..)
713 | hir::ItemKind::Static(..)
714 | hir::ItemKind::Const(..)
715 | hir::ItemKind::Fn(..) => {
716 tcx.ensure().generics_of(def_id);
717 tcx.ensure().type_of(def_id);
718 tcx.ensure().predicates_of(def_id);
719 match it.kind {
720 hir::ItemKind::Fn(..) => tcx.ensure().fn_sig(def_id),
721 hir::ItemKind::OpaqueTy(..) => tcx.ensure().item_bounds(def_id),
722 _ => (),
723 }
724 }
725 }
726 }
727
728 fn convert_trait_item(tcx: TyCtxt<'_>, trait_item_id: hir::HirId) {
729 let trait_item = tcx.hir().expect_trait_item(trait_item_id);
730 let def_id = tcx.hir().local_def_id(trait_item.hir_id);
731 tcx.ensure().generics_of(def_id);
732
733 match trait_item.kind {
734 hir::TraitItemKind::Fn(..) => {
735 tcx.ensure().type_of(def_id);
736 tcx.ensure().fn_sig(def_id);
737 }
738
739 hir::TraitItemKind::Const(.., Some(_)) => {
740 tcx.ensure().type_of(def_id);
741 }
742
743 hir::TraitItemKind::Const(..) => {
744 tcx.ensure().type_of(def_id);
745 // Account for `const C: _;`.
746 let mut visitor = PlaceholderHirTyCollector::default();
747 visitor.visit_trait_item(trait_item);
748 placeholder_type_error(tcx, None, &[], visitor.0, false);
749 }
750
751 hir::TraitItemKind::Type(_, Some(_)) => {
752 tcx.ensure().item_bounds(def_id);
753 tcx.ensure().type_of(def_id);
754 // Account for `type T = _;`.
755 let mut visitor = PlaceholderHirTyCollector::default();
756 visitor.visit_trait_item(trait_item);
757 placeholder_type_error(tcx, None, &[], visitor.0, false);
758 }
759
760 hir::TraitItemKind::Type(_, None) => {
761 tcx.ensure().item_bounds(def_id);
762 // #74612: Visit and try to find bad placeholders
763 // even if there is no concrete type.
764 let mut visitor = PlaceholderHirTyCollector::default();
765 visitor.visit_trait_item(trait_item);
766 placeholder_type_error(tcx, None, &[], visitor.0, false);
767 }
768 };
769
770 tcx.ensure().predicates_of(def_id);
771 }
772
773 fn convert_impl_item(tcx: TyCtxt<'_>, impl_item_id: hir::HirId) {
774 let def_id = tcx.hir().local_def_id(impl_item_id);
775 tcx.ensure().generics_of(def_id);
776 tcx.ensure().type_of(def_id);
777 tcx.ensure().predicates_of(def_id);
778 let impl_item = tcx.hir().expect_impl_item(impl_item_id);
779 match impl_item.kind {
780 hir::ImplItemKind::Fn(..) => {
781 tcx.ensure().fn_sig(def_id);
782 }
783 hir::ImplItemKind::TyAlias(_) => {
784 // Account for `type T = _;`
785 let mut visitor = PlaceholderHirTyCollector::default();
786 visitor.visit_impl_item(impl_item);
787 placeholder_type_error(tcx, None, &[], visitor.0, false);
788 }
789 hir::ImplItemKind::Const(..) => {}
790 }
791 }
792
793 fn convert_variant_ctor(tcx: TyCtxt<'_>, ctor_id: hir::HirId) {
794 let def_id = tcx.hir().local_def_id(ctor_id);
795 tcx.ensure().generics_of(def_id);
796 tcx.ensure().type_of(def_id);
797 tcx.ensure().predicates_of(def_id);
798 }
799
800 fn convert_enum_variant_types(tcx: TyCtxt<'_>, def_id: DefId, variants: &[hir::Variant<'_>]) {
801 let def = tcx.adt_def(def_id);
802 let repr_type = def.repr.discr_type();
803 let initial = repr_type.initial_discriminant(tcx);
804 let mut prev_discr = None::<Discr<'_>>;
805
806 // fill the discriminant values and field types
807 for variant in variants {
808 let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
809 prev_discr = Some(
810 if let Some(ref e) = variant.disr_expr {
811 let expr_did = tcx.hir().local_def_id(e.hir_id);
812 def.eval_explicit_discr(tcx, expr_did.to_def_id())
813 } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) {
814 Some(discr)
815 } else {
816 struct_span_err!(tcx.sess, variant.span, E0370, "enum discriminant overflowed")
817 .span_label(
818 variant.span,
819 format!("overflowed on value after {}", prev_discr.unwrap()),
820 )
821 .note(&format!(
822 "explicitly set `{} = {}` if that is desired outcome",
823 variant.ident, wrapped_discr
824 ))
825 .emit();
826 None
827 }
828 .unwrap_or(wrapped_discr),
829 );
830
831 for f in variant.data.fields() {
832 let def_id = tcx.hir().local_def_id(f.hir_id);
833 tcx.ensure().generics_of(def_id);
834 tcx.ensure().type_of(def_id);
835 tcx.ensure().predicates_of(def_id);
836 }
837
838 // Convert the ctor, if any. This also registers the variant as
839 // an item.
840 if let Some(ctor_hir_id) = variant.data.ctor_hir_id() {
841 convert_variant_ctor(tcx, ctor_hir_id);
842 }
843 }
844 }
845
846 fn convert_variant(
847 tcx: TyCtxt<'_>,
848 variant_did: Option<LocalDefId>,
849 ctor_did: Option<LocalDefId>,
850 ident: Ident,
851 discr: ty::VariantDiscr,
852 def: &hir::VariantData<'_>,
853 adt_kind: ty::AdtKind,
854 parent_did: LocalDefId,
855 ) -> ty::VariantDef {
856 let mut seen_fields: FxHashMap<Ident, Span> = Default::default();
857 let fields = def
858 .fields()
859 .iter()
860 .map(|f| {
861 let fid = tcx.hir().local_def_id(f.hir_id);
862 let dup_span = seen_fields.get(&f.ident.normalize_to_macros_2_0()).cloned();
863 if let Some(prev_span) = dup_span {
864 tcx.sess.emit_err(errors::FieldAlreadyDeclared {
865 field_name: f.ident,
866 span: f.span,
867 prev_span,
868 });
869 } else {
870 seen_fields.insert(f.ident.normalize_to_macros_2_0(), f.span);
871 }
872
873 ty::FieldDef { did: fid.to_def_id(), ident: f.ident, vis: tcx.visibility(fid) }
874 })
875 .collect();
876 let recovered = match def {
877 hir::VariantData::Struct(_, r) => *r,
878 _ => false,
879 };
880 ty::VariantDef::new(
881 ident,
882 variant_did.map(LocalDefId::to_def_id),
883 ctor_did.map(LocalDefId::to_def_id),
884 discr,
885 fields,
886 CtorKind::from_hir(def),
887 adt_kind,
888 parent_did.to_def_id(),
889 recovered,
890 adt_kind == AdtKind::Struct && tcx.has_attr(parent_did.to_def_id(), sym::non_exhaustive)
891 || variant_did.map_or(false, |variant_did| {
892 tcx.has_attr(variant_did.to_def_id(), sym::non_exhaustive)
893 }),
894 )
895 }
896
897 fn adt_def(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::AdtDef {
898 use rustc_hir::*;
899
900 let def_id = def_id.expect_local();
901 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
902 let item = match tcx.hir().get(hir_id) {
903 Node::Item(item) => item,
904 _ => bug!(),
905 };
906
907 let repr = ReprOptions::new(tcx, def_id.to_def_id());
908 let (kind, variants) = match item.kind {
909 ItemKind::Enum(ref def, _) => {
910 let mut distance_from_explicit = 0;
911 let variants = def
912 .variants
913 .iter()
914 .map(|v| {
915 let variant_did = Some(tcx.hir().local_def_id(v.id));
916 let ctor_did =
917 v.data.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
918
919 let discr = if let Some(ref e) = v.disr_expr {
920 distance_from_explicit = 0;
921 ty::VariantDiscr::Explicit(tcx.hir().local_def_id(e.hir_id).to_def_id())
922 } else {
923 ty::VariantDiscr::Relative(distance_from_explicit)
924 };
925 distance_from_explicit += 1;
926
927 convert_variant(
928 tcx,
929 variant_did,
930 ctor_did,
931 v.ident,
932 discr,
933 &v.data,
934 AdtKind::Enum,
935 def_id,
936 )
937 })
938 .collect();
939
940 (AdtKind::Enum, variants)
941 }
942 ItemKind::Struct(ref def, _) => {
943 let variant_did = None::<LocalDefId>;
944 let ctor_did = def.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
945
946 let variants = std::iter::once(convert_variant(
947 tcx,
948 variant_did,
949 ctor_did,
950 item.ident,
951 ty::VariantDiscr::Relative(0),
952 def,
953 AdtKind::Struct,
954 def_id,
955 ))
956 .collect();
957
958 (AdtKind::Struct, variants)
959 }
960 ItemKind::Union(ref def, _) => {
961 let variant_did = None;
962 let ctor_did = def.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
963
964 let variants = std::iter::once(convert_variant(
965 tcx,
966 variant_did,
967 ctor_did,
968 item.ident,
969 ty::VariantDiscr::Relative(0),
970 def,
971 AdtKind::Union,
972 def_id,
973 ))
974 .collect();
975
976 (AdtKind::Union, variants)
977 }
978 _ => bug!(),
979 };
980 tcx.alloc_adt_def(def_id.to_def_id(), kind, variants, repr)
981 }
982
983 /// Ensures that the super-predicates of the trait with a `DefId`
984 /// of `trait_def_id` are converted and stored. This also ensures that
985 /// the transitive super-predicates are converted.
986 fn super_predicates_of(tcx: TyCtxt<'_>, trait_def_id: DefId) -> ty::GenericPredicates<'_> {
987 debug!("super_predicates(trait_def_id={:?})", trait_def_id);
988 let trait_hir_id = tcx.hir().local_def_id_to_hir_id(trait_def_id.expect_local());
989
990 let item = match tcx.hir().get(trait_hir_id) {
991 Node::Item(item) => item,
992 _ => bug!("trait_node_id {} is not an item", trait_hir_id),
993 };
994
995 let (generics, bounds) = match item.kind {
996 hir::ItemKind::Trait(.., ref generics, ref supertraits, _) => (generics, supertraits),
997 hir::ItemKind::TraitAlias(ref generics, ref supertraits) => (generics, supertraits),
998 _ => span_bug!(item.span, "super_predicates invoked on non-trait"),
999 };
1000
1001 let icx = ItemCtxt::new(tcx, trait_def_id);
1002
1003 // Convert the bounds that follow the colon, e.g., `Bar + Zed` in `trait Foo: Bar + Zed`.
1004 let self_param_ty = tcx.types.self_param;
1005 let superbounds1 =
1006 AstConv::compute_bounds(&icx, self_param_ty, bounds, SizedByDefault::No, item.span);
1007
1008 let superbounds1 = superbounds1.predicates(tcx, self_param_ty);
1009
1010 // Convert any explicit superbounds in the where-clause,
1011 // e.g., `trait Foo where Self: Bar`.
1012 // In the case of trait aliases, however, we include all bounds in the where-clause,
1013 // so e.g., `trait Foo = where u32: PartialEq<Self>` would include `u32: PartialEq<Self>`
1014 // as one of its "superpredicates".
1015 let is_trait_alias = tcx.is_trait_alias(trait_def_id);
1016 let superbounds2 = icx.type_parameter_bounds_in_generics(
1017 generics,
1018 item.hir_id,
1019 self_param_ty,
1020 OnlySelfBounds(!is_trait_alias),
1021 );
1022
1023 // Combine the two lists to form the complete set of superbounds:
1024 let superbounds = &*tcx.arena.alloc_from_iter(superbounds1.into_iter().chain(superbounds2));
1025
1026 // Now require that immediate supertraits are converted,
1027 // which will, in turn, reach indirect supertraits.
1028 for &(pred, span) in superbounds {
1029 debug!("superbound: {:?}", pred);
1030 if let ty::PredicateAtom::Trait(bound, _) = pred.skip_binders() {
1031 tcx.at(span).super_predicates_of(bound.def_id());
1032 }
1033 }
1034
1035 ty::GenericPredicates { parent: None, predicates: superbounds }
1036 }
1037
1038 fn trait_def(tcx: TyCtxt<'_>, def_id: DefId) -> ty::TraitDef {
1039 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1040 let item = tcx.hir().expect_item(hir_id);
1041
1042 let (is_auto, unsafety) = match item.kind {
1043 hir::ItemKind::Trait(is_auto, unsafety, ..) => (is_auto == hir::IsAuto::Yes, unsafety),
1044 hir::ItemKind::TraitAlias(..) => (false, hir::Unsafety::Normal),
1045 _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
1046 };
1047
1048 let paren_sugar = tcx.has_attr(def_id, sym::rustc_paren_sugar);
1049 if paren_sugar && !tcx.features().unboxed_closures {
1050 tcx.sess
1051 .struct_span_err(
1052 item.span,
1053 "the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \
1054 which traits can use parenthetical notation",
1055 )
1056 .help("add `#![feature(unboxed_closures)]` to the crate attributes to use it")
1057 .emit();
1058 }
1059
1060 let is_marker = tcx.has_attr(def_id, sym::marker);
1061 let spec_kind = if tcx.has_attr(def_id, sym::rustc_unsafe_specialization_marker) {
1062 ty::trait_def::TraitSpecializationKind::Marker
1063 } else if tcx.has_attr(def_id, sym::rustc_specialization_trait) {
1064 ty::trait_def::TraitSpecializationKind::AlwaysApplicable
1065 } else {
1066 ty::trait_def::TraitSpecializationKind::None
1067 };
1068 let def_path_hash = tcx.def_path_hash(def_id);
1069 ty::TraitDef::new(def_id, unsafety, paren_sugar, is_auto, is_marker, spec_kind, def_path_hash)
1070 }
1071
1072 fn has_late_bound_regions<'tcx>(tcx: TyCtxt<'tcx>, node: Node<'tcx>) -> Option<Span> {
1073 struct LateBoundRegionsDetector<'tcx> {
1074 tcx: TyCtxt<'tcx>,
1075 outer_index: ty::DebruijnIndex,
1076 has_late_bound_regions: Option<Span>,
1077 }
1078
1079 impl Visitor<'tcx> for LateBoundRegionsDetector<'tcx> {
1080 type Map = intravisit::ErasedMap<'tcx>;
1081
1082 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1083 NestedVisitorMap::None
1084 }
1085
1086 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
1087 if self.has_late_bound_regions.is_some() {
1088 return;
1089 }
1090 match ty.kind {
1091 hir::TyKind::BareFn(..) => {
1092 self.outer_index.shift_in(1);
1093 intravisit::walk_ty(self, ty);
1094 self.outer_index.shift_out(1);
1095 }
1096 _ => intravisit::walk_ty(self, ty),
1097 }
1098 }
1099
1100 fn visit_poly_trait_ref(
1101 &mut self,
1102 tr: &'tcx hir::PolyTraitRef<'tcx>,
1103 m: hir::TraitBoundModifier,
1104 ) {
1105 if self.has_late_bound_regions.is_some() {
1106 return;
1107 }
1108 self.outer_index.shift_in(1);
1109 intravisit::walk_poly_trait_ref(self, tr, m);
1110 self.outer_index.shift_out(1);
1111 }
1112
1113 fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
1114 if self.has_late_bound_regions.is_some() {
1115 return;
1116 }
1117
1118 match self.tcx.named_region(lt.hir_id) {
1119 Some(rl::Region::Static | rl::Region::EarlyBound(..)) => {}
1120 Some(
1121 rl::Region::LateBound(debruijn, _, _) | rl::Region::LateBoundAnon(debruijn, _),
1122 ) if debruijn < self.outer_index => {}
1123 Some(
1124 rl::Region::LateBound(..)
1125 | rl::Region::LateBoundAnon(..)
1126 | rl::Region::Free(..),
1127 )
1128 | None => {
1129 self.has_late_bound_regions = Some(lt.span);
1130 }
1131 }
1132 }
1133 }
1134
1135 fn has_late_bound_regions<'tcx>(
1136 tcx: TyCtxt<'tcx>,
1137 generics: &'tcx hir::Generics<'tcx>,
1138 decl: &'tcx hir::FnDecl<'tcx>,
1139 ) -> Option<Span> {
1140 let mut visitor = LateBoundRegionsDetector {
1141 tcx,
1142 outer_index: ty::INNERMOST,
1143 has_late_bound_regions: None,
1144 };
1145 for param in generics.params {
1146 if let GenericParamKind::Lifetime { .. } = param.kind {
1147 if tcx.is_late_bound(param.hir_id) {
1148 return Some(param.span);
1149 }
1150 }
1151 }
1152 visitor.visit_fn_decl(decl);
1153 visitor.has_late_bound_regions
1154 }
1155
1156 match node {
1157 Node::TraitItem(item) => match item.kind {
1158 hir::TraitItemKind::Fn(ref sig, _) => {
1159 has_late_bound_regions(tcx, &item.generics, &sig.decl)
1160 }
1161 _ => None,
1162 },
1163 Node::ImplItem(item) => match item.kind {
1164 hir::ImplItemKind::Fn(ref sig, _) => {
1165 has_late_bound_regions(tcx, &item.generics, &sig.decl)
1166 }
1167 _ => None,
1168 },
1169 Node::ForeignItem(item) => match item.kind {
1170 hir::ForeignItemKind::Fn(ref fn_decl, _, ref generics) => {
1171 has_late_bound_regions(tcx, generics, fn_decl)
1172 }
1173 _ => None,
1174 },
1175 Node::Item(item) => match item.kind {
1176 hir::ItemKind::Fn(ref sig, .., ref generics, _) => {
1177 has_late_bound_regions(tcx, generics, &sig.decl)
1178 }
1179 _ => None,
1180 },
1181 _ => None,
1182 }
1183 }
1184
1185 struct AnonConstInParamListDetector {
1186 in_param_list: bool,
1187 found_anon_const_in_list: bool,
1188 ct: HirId,
1189 }
1190
1191 impl<'v> Visitor<'v> for AnonConstInParamListDetector {
1192 type Map = intravisit::ErasedMap<'v>;
1193
1194 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1195 NestedVisitorMap::None
1196 }
1197
1198 fn visit_generic_param(&mut self, p: &'v hir::GenericParam<'v>) {
1199 let prev = self.in_param_list;
1200 self.in_param_list = true;
1201 intravisit::walk_generic_param(self, p);
1202 self.in_param_list = prev;
1203 }
1204
1205 fn visit_anon_const(&mut self, c: &'v hir::AnonConst) {
1206 if self.in_param_list && self.ct == c.hir_id {
1207 self.found_anon_const_in_list = true;
1208 } else {
1209 intravisit::walk_anon_const(self, c)
1210 }
1211 }
1212 }
1213
1214 fn generics_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::Generics {
1215 use rustc_hir::*;
1216
1217 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1218
1219 let node = tcx.hir().get(hir_id);
1220 let parent_def_id = match node {
1221 Node::ImplItem(_)
1222 | Node::TraitItem(_)
1223 | Node::Variant(_)
1224 | Node::Ctor(..)
1225 | Node::Field(_) => {
1226 let parent_id = tcx.hir().get_parent_item(hir_id);
1227 Some(tcx.hir().local_def_id(parent_id).to_def_id())
1228 }
1229 // FIXME(#43408) always enable this once `lazy_normalization` is
1230 // stable enough and does not need a feature gate anymore.
1231 Node::AnonConst(_) => {
1232 let parent_id = tcx.hir().get_parent_item(hir_id);
1233 let parent_def_id = tcx.hir().local_def_id(parent_id);
1234
1235 let mut in_param_list = false;
1236 for (_parent, node) in tcx.hir().parent_iter(hir_id) {
1237 if let Some(generics) = node.generics() {
1238 let mut visitor = AnonConstInParamListDetector {
1239 in_param_list: false,
1240 found_anon_const_in_list: false,
1241 ct: hir_id,
1242 };
1243
1244 visitor.visit_generics(generics);
1245 in_param_list = visitor.found_anon_const_in_list;
1246 break;
1247 }
1248 }
1249
1250 if in_param_list {
1251 // We do not allow generic parameters in anon consts if we are inside
1252 // of a param list.
1253 //
1254 // This affects both default type bindings, e.g. `struct<T, U = [u8; std::mem::size_of::<T>()]>(T, U)`,
1255 // and the types of const parameters, e.g. `struct V<const N: usize, const M: [u8; N]>();`.
1256 None
1257 } else if tcx.lazy_normalization() {
1258 // HACK(eddyb) this provides the correct generics when
1259 // `feature(const_generics)` is enabled, so that const expressions
1260 // used with const generics, e.g. `Foo<{N+1}>`, can work at all.
1261 //
1262 // Note that we do not supply the parent generics when using
1263 // `feature(min_const_generics)`.
1264 Some(parent_def_id.to_def_id())
1265 } else {
1266 let parent_node = tcx.hir().get(tcx.hir().get_parent_node(hir_id));
1267 match parent_node {
1268 // HACK(eddyb) this provides the correct generics for repeat
1269 // expressions' count (i.e. `N` in `[x; N]`), and explicit
1270 // `enum` discriminants (i.e. `D` in `enum Foo { Bar = D }`),
1271 // as they shouldn't be able to cause query cycle errors.
1272 Node::Expr(&Expr { kind: ExprKind::Repeat(_, ref constant), .. })
1273 | Node::Variant(Variant { disr_expr: Some(ref constant), .. })
1274 if constant.hir_id == hir_id =>
1275 {
1276 Some(parent_def_id.to_def_id())
1277 }
1278
1279 _ => None,
1280 }
1281 }
1282 }
1283 Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => {
1284 Some(tcx.closure_base_def_id(def_id))
1285 }
1286 Node::Item(item) => match item.kind {
1287 ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn, .. }) => {
1288 impl_trait_fn.or_else(|| {
1289 let parent_id = tcx.hir().get_parent_item(hir_id);
1290 assert!(parent_id != hir_id && parent_id != CRATE_HIR_ID);
1291 debug!("generics_of: parent of opaque ty {:?} is {:?}", def_id, parent_id);
1292 // Opaque types are always nested within another item, and
1293 // inherit the generics of the item.
1294 Some(tcx.hir().local_def_id(parent_id).to_def_id())
1295 })
1296 }
1297 _ => None,
1298 },
1299 _ => None,
1300 };
1301
1302 let mut opt_self = None;
1303 let mut allow_defaults = false;
1304
1305 let no_generics = hir::Generics::empty();
1306 let ast_generics = match node {
1307 Node::TraitItem(item) => &item.generics,
1308
1309 Node::ImplItem(item) => &item.generics,
1310
1311 Node::Item(item) => {
1312 match item.kind {
1313 ItemKind::Fn(.., ref generics, _) | ItemKind::Impl { ref generics, .. } => generics,
1314
1315 ItemKind::TyAlias(_, ref generics)
1316 | ItemKind::Enum(_, ref generics)
1317 | ItemKind::Struct(_, ref generics)
1318 | ItemKind::OpaqueTy(hir::OpaqueTy { ref generics, .. })
1319 | ItemKind::Union(_, ref generics) => {
1320 allow_defaults = true;
1321 generics
1322 }
1323
1324 ItemKind::Trait(_, _, ref generics, ..)
1325 | ItemKind::TraitAlias(ref generics, ..) => {
1326 // Add in the self type parameter.
1327 //
1328 // Something of a hack: use the node id for the trait, also as
1329 // the node id for the Self type parameter.
1330 let param_id = item.hir_id;
1331
1332 opt_self = Some(ty::GenericParamDef {
1333 index: 0,
1334 name: kw::SelfUpper,
1335 def_id: tcx.hir().local_def_id(param_id).to_def_id(),
1336 pure_wrt_drop: false,
1337 kind: ty::GenericParamDefKind::Type {
1338 has_default: false,
1339 object_lifetime_default: rl::Set1::Empty,
1340 synthetic: None,
1341 },
1342 });
1343
1344 allow_defaults = true;
1345 generics
1346 }
1347
1348 _ => &no_generics,
1349 }
1350 }
1351
1352 Node::ForeignItem(item) => match item.kind {
1353 ForeignItemKind::Static(..) => &no_generics,
1354 ForeignItemKind::Fn(_, _, ref generics) => generics,
1355 ForeignItemKind::Type => &no_generics,
1356 },
1357
1358 _ => &no_generics,
1359 };
1360
1361 let has_self = opt_self.is_some();
1362 let mut parent_has_self = false;
1363 let mut own_start = has_self as u32;
1364 let parent_count = parent_def_id.map_or(0, |def_id| {
1365 let generics = tcx.generics_of(def_id);
1366 assert_eq!(has_self, false);
1367 parent_has_self = generics.has_self;
1368 own_start = generics.count() as u32;
1369 generics.parent_count + generics.params.len()
1370 });
1371
1372 let mut params: Vec<_> = Vec::with_capacity(ast_generics.params.len() + has_self as usize);
1373
1374 if let Some(opt_self) = opt_self {
1375 params.push(opt_self);
1376 }
1377
1378 let early_lifetimes = early_bound_lifetimes_from_generics(tcx, ast_generics);
1379 params.extend(early_lifetimes.enumerate().map(|(i, param)| ty::GenericParamDef {
1380 name: param.name.ident().name,
1381 index: own_start + i as u32,
1382 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
1383 pure_wrt_drop: param.pure_wrt_drop,
1384 kind: ty::GenericParamDefKind::Lifetime,
1385 }));
1386
1387 let object_lifetime_defaults = tcx.object_lifetime_defaults(hir_id);
1388
1389 // Now create the real type and const parameters.
1390 let type_start = own_start - has_self as u32 + params.len() as u32;
1391 let mut i = 0;
1392
1393 params.extend(ast_generics.params.iter().filter_map(|param| match param.kind {
1394 GenericParamKind::Lifetime { .. } => None,
1395 GenericParamKind::Type { ref default, synthetic, .. } => {
1396 if !allow_defaults && default.is_some() {
1397 if !tcx.features().default_type_parameter_fallback {
1398 tcx.struct_span_lint_hir(
1399 lint::builtin::INVALID_TYPE_PARAM_DEFAULT,
1400 param.hir_id,
1401 param.span,
1402 |lint| {
1403 lint.build(
1404 "defaults for type parameters are only allowed in \
1405 `struct`, `enum`, `type`, or `trait` definitions.",
1406 )
1407 .emit();
1408 },
1409 );
1410 }
1411 }
1412
1413 let kind = ty::GenericParamDefKind::Type {
1414 has_default: default.is_some(),
1415 object_lifetime_default: object_lifetime_defaults
1416 .as_ref()
1417 .map_or(rl::Set1::Empty, |o| o[i]),
1418 synthetic,
1419 };
1420
1421 let param_def = ty::GenericParamDef {
1422 index: type_start + i as u32,
1423 name: param.name.ident().name,
1424 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
1425 pure_wrt_drop: param.pure_wrt_drop,
1426 kind,
1427 };
1428 i += 1;
1429 Some(param_def)
1430 }
1431 GenericParamKind::Const { .. } => {
1432 let param_def = ty::GenericParamDef {
1433 index: type_start + i as u32,
1434 name: param.name.ident().name,
1435 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
1436 pure_wrt_drop: param.pure_wrt_drop,
1437 kind: ty::GenericParamDefKind::Const,
1438 };
1439 i += 1;
1440 Some(param_def)
1441 }
1442 }));
1443
1444 // provide junk type parameter defs - the only place that
1445 // cares about anything but the length is instantiation,
1446 // and we don't do that for closures.
1447 if let Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(.., gen), .. }) = node {
1448 let dummy_args = if gen.is_some() {
1449 &["<resume_ty>", "<yield_ty>", "<return_ty>", "<witness>", "<upvars>"][..]
1450 } else {
1451 &["<closure_kind>", "<closure_signature>", "<upvars>"][..]
1452 };
1453
1454 params.extend(dummy_args.iter().enumerate().map(|(i, &arg)| ty::GenericParamDef {
1455 index: type_start + i as u32,
1456 name: Symbol::intern(arg),
1457 def_id,
1458 pure_wrt_drop: false,
1459 kind: ty::GenericParamDefKind::Type {
1460 has_default: false,
1461 object_lifetime_default: rl::Set1::Empty,
1462 synthetic: None,
1463 },
1464 }));
1465 }
1466
1467 let param_def_id_to_index = params.iter().map(|param| (param.def_id, param.index)).collect();
1468
1469 ty::Generics {
1470 parent: parent_def_id,
1471 parent_count,
1472 params,
1473 param_def_id_to_index,
1474 has_self: has_self || parent_has_self,
1475 has_late_bound_regions: has_late_bound_regions(tcx, node),
1476 }
1477 }
1478
1479 fn are_suggestable_generic_args(generic_args: &[hir::GenericArg<'_>]) -> bool {
1480 generic_args
1481 .iter()
1482 .filter_map(|arg| match arg {
1483 hir::GenericArg::Type(ty) => Some(ty),
1484 _ => None,
1485 })
1486 .any(is_suggestable_infer_ty)
1487 }
1488
1489 /// Whether `ty` is a type with `_` placeholders that can be inferred. Used in diagnostics only to
1490 /// use inference to provide suggestions for the appropriate type if possible.
1491 fn is_suggestable_infer_ty(ty: &hir::Ty<'_>) -> bool {
1492 use hir::TyKind::*;
1493 match &ty.kind {
1494 Infer => true,
1495 Slice(ty) | Array(ty, _) => is_suggestable_infer_ty(ty),
1496 Tup(tys) => tys.iter().any(is_suggestable_infer_ty),
1497 Ptr(mut_ty) | Rptr(_, mut_ty) => is_suggestable_infer_ty(mut_ty.ty),
1498 OpaqueDef(_, generic_args) => are_suggestable_generic_args(generic_args),
1499 Path(hir::QPath::TypeRelative(ty, segment)) => {
1500 is_suggestable_infer_ty(ty) || are_suggestable_generic_args(segment.generic_args().args)
1501 }
1502 Path(hir::QPath::Resolved(ty_opt, hir::Path { segments, .. })) => {
1503 ty_opt.map_or(false, is_suggestable_infer_ty)
1504 || segments
1505 .iter()
1506 .any(|segment| are_suggestable_generic_args(segment.generic_args().args))
1507 }
1508 _ => false,
1509 }
1510 }
1511
1512 pub fn get_infer_ret_ty(output: &'hir hir::FnRetTy<'hir>) -> Option<&'hir hir::Ty<'hir>> {
1513 if let hir::FnRetTy::Return(ref ty) = output {
1514 if is_suggestable_infer_ty(ty) {
1515 return Some(&**ty);
1516 }
1517 }
1518 None
1519 }
1520
1521 fn fn_sig(tcx: TyCtxt<'_>, def_id: DefId) -> ty::PolyFnSig<'_> {
1522 use rustc_hir::Node::*;
1523 use rustc_hir::*;
1524
1525 let def_id = def_id.expect_local();
1526 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
1527
1528 let icx = ItemCtxt::new(tcx, def_id.to_def_id());
1529
1530 match tcx.hir().get(hir_id) {
1531 TraitItem(hir::TraitItem {
1532 kind: TraitItemKind::Fn(sig, TraitFn::Provided(_)),
1533 ident,
1534 generics,
1535 ..
1536 })
1537 | ImplItem(hir::ImplItem { kind: ImplItemKind::Fn(sig, _), ident, generics, .. })
1538 | Item(hir::Item { kind: ItemKind::Fn(sig, generics, _), ident, .. }) => {
1539 match get_infer_ret_ty(&sig.decl.output) {
1540 Some(ty) => {
1541 let fn_sig = tcx.typeck(def_id).liberated_fn_sigs()[hir_id];
1542 let mut visitor = PlaceholderHirTyCollector::default();
1543 visitor.visit_ty(ty);
1544 let mut diag = bad_placeholder_type(tcx, visitor.0);
1545 let ret_ty = fn_sig.output();
1546 if ret_ty != tcx.ty_error() {
1547 diag.span_suggestion(
1548 ty.span,
1549 "replace with the correct return type",
1550 ret_ty.to_string(),
1551 Applicability::MaybeIncorrect,
1552 );
1553 }
1554 diag.emit();
1555 ty::Binder::bind(fn_sig)
1556 }
1557 None => AstConv::ty_of_fn(
1558 &icx,
1559 sig.header.unsafety,
1560 sig.header.abi,
1561 &sig.decl,
1562 &generics,
1563 Some(ident.span),
1564 ),
1565 }
1566 }
1567
1568 TraitItem(hir::TraitItem {
1569 kind: TraitItemKind::Fn(FnSig { header, decl, span: _ }, _),
1570 ident,
1571 generics,
1572 ..
1573 }) => {
1574 AstConv::ty_of_fn(&icx, header.unsafety, header.abi, decl, &generics, Some(ident.span))
1575 }
1576
1577 ForeignItem(&hir::ForeignItem {
1578 kind: ForeignItemKind::Fn(ref fn_decl, _, _),
1579 ident,
1580 ..
1581 }) => {
1582 let abi = tcx.hir().get_foreign_abi(hir_id);
1583 compute_sig_of_foreign_fn_decl(tcx, def_id.to_def_id(), fn_decl, abi, ident)
1584 }
1585
1586 Ctor(data) | Variant(hir::Variant { data, .. }) if data.ctor_hir_id().is_some() => {
1587 let ty = tcx.type_of(tcx.hir().get_parent_did(hir_id).to_def_id());
1588 let inputs =
1589 data.fields().iter().map(|f| tcx.type_of(tcx.hir().local_def_id(f.hir_id)));
1590 ty::Binder::bind(tcx.mk_fn_sig(
1591 inputs,
1592 ty,
1593 false,
1594 hir::Unsafety::Normal,
1595 abi::Abi::Rust,
1596 ))
1597 }
1598
1599 Expr(&hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => {
1600 // Closure signatures are not like other function
1601 // signatures and cannot be accessed through `fn_sig`. For
1602 // example, a closure signature excludes the `self`
1603 // argument. In any case they are embedded within the
1604 // closure type as part of the `ClosureSubsts`.
1605 //
1606 // To get the signature of a closure, you should use the
1607 // `sig` method on the `ClosureSubsts`:
1608 //
1609 // substs.as_closure().sig(def_id, tcx)
1610 bug!(
1611 "to get the signature of a closure, use `substs.as_closure().sig()` not `fn_sig()`",
1612 );
1613 }
1614
1615 x => {
1616 bug!("unexpected sort of node in fn_sig(): {:?}", x);
1617 }
1618 }
1619 }
1620
1621 fn impl_trait_ref(tcx: TyCtxt<'_>, def_id: DefId) -> Option<ty::TraitRef<'_>> {
1622 let icx = ItemCtxt::new(tcx, def_id);
1623
1624 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1625 match tcx.hir().expect_item(hir_id).kind {
1626 hir::ItemKind::Impl { ref of_trait, .. } => of_trait.as_ref().map(|ast_trait_ref| {
1627 let selfty = tcx.type_of(def_id);
1628 AstConv::instantiate_mono_trait_ref(&icx, ast_trait_ref, selfty)
1629 }),
1630 _ => bug!(),
1631 }
1632 }
1633
1634 fn impl_polarity(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ImplPolarity {
1635 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1636 let is_rustc_reservation = tcx.has_attr(def_id, sym::rustc_reservation_impl);
1637 let item = tcx.hir().expect_item(hir_id);
1638 match &item.kind {
1639 hir::ItemKind::Impl { polarity: hir::ImplPolarity::Negative(span), of_trait, .. } => {
1640 if is_rustc_reservation {
1641 let span = span.to(of_trait.as_ref().map(|t| t.path.span).unwrap_or(*span));
1642 tcx.sess.span_err(span, "reservation impls can't be negative");
1643 }
1644 ty::ImplPolarity::Negative
1645 }
1646 hir::ItemKind::Impl { polarity: hir::ImplPolarity::Positive, of_trait: None, .. } => {
1647 if is_rustc_reservation {
1648 tcx.sess.span_err(item.span, "reservation impls can't be inherent");
1649 }
1650 ty::ImplPolarity::Positive
1651 }
1652 hir::ItemKind::Impl {
1653 polarity: hir::ImplPolarity::Positive, of_trait: Some(_), ..
1654 } => {
1655 if is_rustc_reservation {
1656 ty::ImplPolarity::Reservation
1657 } else {
1658 ty::ImplPolarity::Positive
1659 }
1660 }
1661 ref item => bug!("impl_polarity: {:?} not an impl", item),
1662 }
1663 }
1664
1665 /// Returns the early-bound lifetimes declared in this generics
1666 /// listing. For anything other than fns/methods, this is just all
1667 /// the lifetimes that are declared. For fns or methods, we have to
1668 /// screen out those that do not appear in any where-clauses etc using
1669 /// `resolve_lifetime::early_bound_lifetimes`.
1670 fn early_bound_lifetimes_from_generics<'a, 'tcx: 'a>(
1671 tcx: TyCtxt<'tcx>,
1672 generics: &'a hir::Generics<'a>,
1673 ) -> impl Iterator<Item = &'a hir::GenericParam<'a>> + Captures<'tcx> {
1674 generics.params.iter().filter(move |param| match param.kind {
1675 GenericParamKind::Lifetime { .. } => !tcx.is_late_bound(param.hir_id),
1676 _ => false,
1677 })
1678 }
1679
1680 /// Returns a list of type predicates for the definition with ID `def_id`, including inferred
1681 /// lifetime constraints. This includes all predicates returned by `explicit_predicates_of`, plus
1682 /// inferred constraints concerning which regions outlive other regions.
1683 fn predicates_defined_on(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1684 debug!("predicates_defined_on({:?})", def_id);
1685 let mut result = tcx.explicit_predicates_of(def_id);
1686 debug!("predicates_defined_on: explicit_predicates_of({:?}) = {:?}", def_id, result,);
1687 let inferred_outlives = tcx.inferred_outlives_of(def_id);
1688 if !inferred_outlives.is_empty() {
1689 debug!(
1690 "predicates_defined_on: inferred_outlives_of({:?}) = {:?}",
1691 def_id, inferred_outlives,
1692 );
1693 if result.predicates.is_empty() {
1694 result.predicates = inferred_outlives;
1695 } else {
1696 result.predicates = tcx
1697 .arena
1698 .alloc_from_iter(result.predicates.iter().chain(inferred_outlives).copied());
1699 }
1700 }
1701
1702 debug!("predicates_defined_on({:?}) = {:?}", def_id, result);
1703 result
1704 }
1705
1706 /// Returns a list of all type predicates (explicit and implicit) for the definition with
1707 /// ID `def_id`. This includes all predicates returned by `predicates_defined_on`, plus
1708 /// `Self: Trait` predicates for traits.
1709 fn predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1710 let mut result = tcx.predicates_defined_on(def_id);
1711
1712 if tcx.is_trait(def_id) {
1713 // For traits, add `Self: Trait` predicate. This is
1714 // not part of the predicates that a user writes, but it
1715 // is something that one must prove in order to invoke a
1716 // method or project an associated type.
1717 //
1718 // In the chalk setup, this predicate is not part of the
1719 // "predicates" for a trait item. But it is useful in
1720 // rustc because if you directly (e.g.) invoke a trait
1721 // method like `Trait::method(...)`, you must naturally
1722 // prove that the trait applies to the types that were
1723 // used, and adding the predicate into this list ensures
1724 // that this is done.
1725 let span = tcx.sess.source_map().guess_head_span(tcx.def_span(def_id));
1726 result.predicates =
1727 tcx.arena.alloc_from_iter(result.predicates.iter().copied().chain(std::iter::once((
1728 ty::TraitRef::identity(tcx, def_id).without_const().to_predicate(tcx),
1729 span,
1730 ))));
1731 }
1732 debug!("predicates_of(def_id={:?}) = {:?}", def_id, result);
1733 result
1734 }
1735
1736 /// Returns a list of user-specified type predicates for the definition with ID `def_id`.
1737 /// N.B., this does not include any implied/inferred constraints.
1738 fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1739 use rustc_hir::*;
1740
1741 debug!("explicit_predicates_of(def_id={:?})", def_id);
1742
1743 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1744 let node = tcx.hir().get(hir_id);
1745
1746 let mut is_trait = None;
1747 let mut is_default_impl_trait = None;
1748
1749 let icx = ItemCtxt::new(tcx, def_id);
1750 let constness = icx.default_constness_for_trait_bounds();
1751
1752 const NO_GENERICS: &hir::Generics<'_> = &hir::Generics::empty();
1753
1754 // We use an `IndexSet` to preserves order of insertion.
1755 // Preserving the order of insertion is important here so as not to break
1756 // compile-fail UI tests.
1757 let mut predicates: FxIndexSet<(ty::Predicate<'_>, Span)> = FxIndexSet::default();
1758
1759 let ast_generics = match node {
1760 Node::TraitItem(item) => &item.generics,
1761
1762 Node::ImplItem(item) => &item.generics,
1763
1764 Node::Item(item) => {
1765 match item.kind {
1766 ItemKind::Impl { defaultness, ref generics, .. } => {
1767 if defaultness.is_default() {
1768 is_default_impl_trait = tcx.impl_trait_ref(def_id);
1769 }
1770 generics
1771 }
1772 ItemKind::Fn(.., ref generics, _)
1773 | ItemKind::TyAlias(_, ref generics)
1774 | ItemKind::Enum(_, ref generics)
1775 | ItemKind::Struct(_, ref generics)
1776 | ItemKind::Union(_, ref generics) => generics,
1777
1778 ItemKind::Trait(_, _, ref generics, ..) => {
1779 is_trait = Some(ty::TraitRef::identity(tcx, def_id));
1780 generics
1781 }
1782 ItemKind::TraitAlias(ref generics, _) => {
1783 is_trait = Some(ty::TraitRef::identity(tcx, def_id));
1784 generics
1785 }
1786 ItemKind::OpaqueTy(OpaqueTy {
1787 bounds: _,
1788 impl_trait_fn,
1789 ref generics,
1790 origin: _,
1791 }) => {
1792 if impl_trait_fn.is_some() {
1793 // return-position impl trait
1794 //
1795 // We don't inherit predicates from the parent here:
1796 // If we have, say `fn f<'a, T: 'a>() -> impl Sized {}`
1797 // then the return type is `f::<'static, T>::{{opaque}}`.
1798 //
1799 // If we inherited the predicates of `f` then we would
1800 // require that `T: 'static` to show that the return
1801 // type is well-formed.
1802 //
1803 // The only way to have something with this opaque type
1804 // is from the return type of the containing function,
1805 // which will ensure that the function's predicates
1806 // hold.
1807 return ty::GenericPredicates { parent: None, predicates: &[] };
1808 } else {
1809 // type-alias impl trait
1810 generics
1811 }
1812 }
1813
1814 _ => NO_GENERICS,
1815 }
1816 }
1817
1818 Node::ForeignItem(item) => match item.kind {
1819 ForeignItemKind::Static(..) => NO_GENERICS,
1820 ForeignItemKind::Fn(_, _, ref generics) => generics,
1821 ForeignItemKind::Type => NO_GENERICS,
1822 },
1823
1824 _ => NO_GENERICS,
1825 };
1826
1827 let generics = tcx.generics_of(def_id);
1828 let parent_count = generics.parent_count as u32;
1829 let has_own_self = generics.has_self && parent_count == 0;
1830
1831 // Below we'll consider the bounds on the type parameters (including `Self`)
1832 // and the explicit where-clauses, but to get the full set of predicates
1833 // on a trait we need to add in the supertrait bounds and bounds found on
1834 // associated types.
1835 if let Some(_trait_ref) = is_trait {
1836 predicates.extend(tcx.super_predicates_of(def_id).predicates.iter().cloned());
1837 }
1838
1839 // In default impls, we can assume that the self type implements
1840 // the trait. So in:
1841 //
1842 // default impl Foo for Bar { .. }
1843 //
1844 // we add a default where clause `Foo: Bar`. We do a similar thing for traits
1845 // (see below). Recall that a default impl is not itself an impl, but rather a
1846 // set of defaults that can be incorporated into another impl.
1847 if let Some(trait_ref) = is_default_impl_trait {
1848 predicates.insert((
1849 trait_ref.to_poly_trait_ref().without_const().to_predicate(tcx),
1850 tcx.def_span(def_id),
1851 ));
1852 }
1853
1854 // Collect the region predicates that were declared inline as
1855 // well. In the case of parameters declared on a fn or method, we
1856 // have to be careful to only iterate over early-bound regions.
1857 let mut index = parent_count + has_own_self as u32;
1858 for param in early_bound_lifetimes_from_generics(tcx, ast_generics) {
1859 let region = tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
1860 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
1861 index,
1862 name: param.name.ident().name,
1863 }));
1864 index += 1;
1865
1866 match param.kind {
1867 GenericParamKind::Lifetime { .. } => {
1868 param.bounds.iter().for_each(|bound| match bound {
1869 hir::GenericBound::Outlives(lt) => {
1870 let bound = AstConv::ast_region_to_region(&icx, &lt, None);
1871 let outlives = ty::Binder::bind(ty::OutlivesPredicate(region, bound));
1872 predicates.insert((outlives.to_predicate(tcx), lt.span));
1873 }
1874 _ => bug!(),
1875 });
1876 }
1877 _ => bug!(),
1878 }
1879 }
1880
1881 // Collect the predicates that were written inline by the user on each
1882 // type parameter (e.g., `<T: Foo>`).
1883 for param in ast_generics.params {
1884 match param.kind {
1885 // We already dealt with early bound lifetimes above.
1886 GenericParamKind::Lifetime { .. } => (),
1887 GenericParamKind::Type { .. } => {
1888 let name = param.name.ident().name;
1889 let param_ty = ty::ParamTy::new(index, name).to_ty(tcx);
1890 index += 1;
1891
1892 let sized = SizedByDefault::Yes;
1893 let bounds =
1894 AstConv::compute_bounds(&icx, param_ty, &param.bounds, sized, param.span);
1895 predicates.extend(bounds.predicates(tcx, param_ty));
1896 }
1897 GenericParamKind::Const { .. } => {
1898 // Bounds on const parameters are currently not possible.
1899 debug_assert!(param.bounds.is_empty());
1900 index += 1;
1901 }
1902 }
1903 }
1904
1905 // Add in the bounds that appear in the where-clause.
1906 let where_clause = &ast_generics.where_clause;
1907 for predicate in where_clause.predicates {
1908 match predicate {
1909 &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
1910 let ty = icx.to_ty(&bound_pred.bounded_ty);
1911
1912 // Keep the type around in a dummy predicate, in case of no bounds.
1913 // That way, `where Ty:` is not a complete noop (see #53696) and `Ty`
1914 // is still checked for WF.
1915 if bound_pred.bounds.is_empty() {
1916 if let ty::Param(_) = ty.kind() {
1917 // This is a `where T:`, which can be in the HIR from the
1918 // transformation that moves `?Sized` to `T`'s declaration.
1919 // We can skip the predicate because type parameters are
1920 // trivially WF, but also we *should*, to avoid exposing
1921 // users who never wrote `where Type:,` themselves, to
1922 // compiler/tooling bugs from not handling WF predicates.
1923 } else {
1924 let span = bound_pred.bounded_ty.span;
1925 let re_root_empty = tcx.lifetimes.re_root_empty;
1926 let predicate = ty::Binder::bind(ty::PredicateAtom::TypeOutlives(
1927 ty::OutlivesPredicate(ty, re_root_empty),
1928 ));
1929 predicates.insert((
1930 predicate.potentially_quantified(tcx, ty::PredicateKind::ForAll),
1931 span,
1932 ));
1933 }
1934 }
1935
1936 for bound in bound_pred.bounds.iter() {
1937 match bound {
1938 &hir::GenericBound::Trait(ref poly_trait_ref, modifier) => {
1939 let constness = match modifier {
1940 hir::TraitBoundModifier::MaybeConst => hir::Constness::NotConst,
1941 hir::TraitBoundModifier::None => constness,
1942 hir::TraitBoundModifier::Maybe => bug!("this wasn't handled"),
1943 };
1944
1945 let mut bounds = Bounds::default();
1946 let _ = AstConv::instantiate_poly_trait_ref(
1947 &icx,
1948 poly_trait_ref,
1949 constness,
1950 ty,
1951 &mut bounds,
1952 );
1953 predicates.extend(bounds.predicates(tcx, ty));
1954 }
1955
1956 &hir::GenericBound::LangItemTrait(lang_item, span, hir_id, args) => {
1957 let mut bounds = Bounds::default();
1958 AstConv::instantiate_lang_item_trait_ref(
1959 &icx,
1960 lang_item,
1961 span,
1962 hir_id,
1963 args,
1964 ty,
1965 &mut bounds,
1966 );
1967 predicates.extend(bounds.predicates(tcx, ty));
1968 }
1969
1970 &hir::GenericBound::Outlives(ref lifetime) => {
1971 let region = AstConv::ast_region_to_region(&icx, lifetime, None);
1972 predicates.insert((
1973 ty::Binder::bind(ty::PredicateAtom::TypeOutlives(
1974 ty::OutlivesPredicate(ty, region),
1975 ))
1976 .potentially_quantified(tcx, ty::PredicateKind::ForAll),
1977 lifetime.span,
1978 ));
1979 }
1980 }
1981 }
1982 }
1983
1984 &hir::WherePredicate::RegionPredicate(ref region_pred) => {
1985 let r1 = AstConv::ast_region_to_region(&icx, &region_pred.lifetime, None);
1986 predicates.extend(region_pred.bounds.iter().map(|bound| {
1987 let (r2, span) = match bound {
1988 hir::GenericBound::Outlives(lt) => {
1989 (AstConv::ast_region_to_region(&icx, lt, None), lt.span)
1990 }
1991 _ => bug!(),
1992 };
1993 let pred = ty::PredicateAtom::RegionOutlives(ty::OutlivesPredicate(r1, r2))
1994 .to_predicate(icx.tcx);
1995
1996 (pred, span)
1997 }))
1998 }
1999
2000 &hir::WherePredicate::EqPredicate(..) => {
2001 // FIXME(#20041)
2002 }
2003 }
2004 }
2005
2006 if tcx.features().const_evaluatable_checked {
2007 predicates.extend(const_evaluatable_predicates_of(tcx, def_id.expect_local()));
2008 }
2009
2010 let mut predicates: Vec<_> = predicates.into_iter().collect();
2011
2012 // Subtle: before we store the predicates into the tcx, we
2013 // sort them so that predicates like `T: Foo<Item=U>` come
2014 // before uses of `U`. This avoids false ambiguity errors
2015 // in trait checking. See `setup_constraining_predicates`
2016 // for details.
2017 if let Node::Item(&Item { kind: ItemKind::Impl { .. }, .. }) = node {
2018 let self_ty = tcx.type_of(def_id);
2019 let trait_ref = tcx.impl_trait_ref(def_id);
2020 cgp::setup_constraining_predicates(
2021 tcx,
2022 &mut predicates,
2023 trait_ref,
2024 &mut cgp::parameters_for_impl(self_ty, trait_ref),
2025 );
2026 }
2027
2028 let result = ty::GenericPredicates {
2029 parent: generics.parent,
2030 predicates: tcx.arena.alloc_from_iter(predicates),
2031 };
2032 debug!("explicit_predicates_of(def_id={:?}) = {:?}", def_id, result);
2033 result
2034 }
2035
2036 fn const_evaluatable_predicates_of<'tcx>(
2037 tcx: TyCtxt<'tcx>,
2038 def_id: LocalDefId,
2039 ) -> FxIndexSet<(ty::Predicate<'tcx>, Span)> {
2040 struct ConstCollector<'tcx> {
2041 tcx: TyCtxt<'tcx>,
2042 preds: FxIndexSet<(ty::Predicate<'tcx>, Span)>,
2043 }
2044
2045 impl<'tcx> intravisit::Visitor<'tcx> for ConstCollector<'tcx> {
2046 type Map = Map<'tcx>;
2047
2048 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
2049 intravisit::NestedVisitorMap::None
2050 }
2051
2052 fn visit_anon_const(&mut self, c: &'tcx hir::AnonConst) {
2053 let def_id = self.tcx.hir().local_def_id(c.hir_id);
2054 let ct = ty::Const::from_anon_const(self.tcx, def_id);
2055 if let ty::ConstKind::Unevaluated(def, substs, None) = ct.val {
2056 let span = self.tcx.hir().span(c.hir_id);
2057 self.preds.insert((
2058 ty::PredicateAtom::ConstEvaluatable(def, substs).to_predicate(self.tcx),
2059 span,
2060 ));
2061 }
2062 }
2063
2064 // Look into `TyAlias`.
2065 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
2066 use ty::fold::{TypeFoldable, TypeVisitor};
2067 struct TyAliasVisitor<'a, 'tcx> {
2068 tcx: TyCtxt<'tcx>,
2069 preds: &'a mut FxIndexSet<(ty::Predicate<'tcx>, Span)>,
2070 span: Span,
2071 }
2072
2073 impl<'a, 'tcx> TypeVisitor<'tcx> for TyAliasVisitor<'a, 'tcx> {
2074 fn visit_const(&mut self, ct: &'tcx Const<'tcx>) -> ControlFlow<Self::BreakTy> {
2075 if let ty::ConstKind::Unevaluated(def, substs, None) = ct.val {
2076 self.preds.insert((
2077 ty::PredicateAtom::ConstEvaluatable(def, substs).to_predicate(self.tcx),
2078 self.span,
2079 ));
2080 }
2081 ControlFlow::CONTINUE
2082 }
2083 }
2084
2085 if let hir::TyKind::Path(hir::QPath::Resolved(None, path)) = ty.kind {
2086 if let Res::Def(DefKind::TyAlias, def_id) = path.res {
2087 let mut visitor =
2088 TyAliasVisitor { tcx: self.tcx, preds: &mut self.preds, span: path.span };
2089 self.tcx.type_of(def_id).visit_with(&mut visitor);
2090 }
2091 }
2092
2093 intravisit::walk_ty(self, ty)
2094 }
2095 }
2096
2097 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
2098 let node = tcx.hir().get(hir_id);
2099
2100 let mut collector = ConstCollector { tcx, preds: FxIndexSet::default() };
2101 if let hir::Node::Item(item) = node {
2102 if let hir::ItemKind::Impl { ref of_trait, ref self_ty, .. } = item.kind {
2103 if let Some(of_trait) = of_trait {
2104 debug!("const_evaluatable_predicates_of({:?}): visit impl trait_ref", def_id);
2105 collector.visit_trait_ref(of_trait);
2106 }
2107
2108 debug!("const_evaluatable_predicates_of({:?}): visit_self_ty", def_id);
2109 collector.visit_ty(self_ty);
2110 }
2111 }
2112
2113 if let Some(generics) = node.generics() {
2114 debug!("const_evaluatable_predicates_of({:?}): visit_generics", def_id);
2115 collector.visit_generics(generics);
2116 }
2117
2118 if let Some(fn_sig) = tcx.hir().fn_sig_by_hir_id(hir_id) {
2119 debug!("const_evaluatable_predicates_of({:?}): visit_fn_decl", def_id);
2120 collector.visit_fn_decl(fn_sig.decl);
2121 }
2122 debug!("const_evaluatable_predicates_of({:?}) = {:?}", def_id, collector.preds);
2123
2124 collector.preds
2125 }
2126
2127 fn trait_explicit_predicates_and_bounds(
2128 tcx: TyCtxt<'_>,
2129 def_id: LocalDefId,
2130 ) -> ty::GenericPredicates<'_> {
2131 assert_eq!(tcx.def_kind(def_id), DefKind::Trait);
2132 gather_explicit_predicates_of(tcx, def_id.to_def_id())
2133 }
2134
2135 fn explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
2136 if let DefKind::Trait = tcx.def_kind(def_id) {
2137 // Remove bounds on associated types from the predicates, they will be
2138 // returned by `explicit_item_bounds`.
2139 let predicates_and_bounds = tcx.trait_explicit_predicates_and_bounds(def_id.expect_local());
2140 let trait_identity_substs = InternalSubsts::identity_for_item(tcx, def_id);
2141
2142 let is_assoc_item_ty = |ty: Ty<'_>| {
2143 // For a predicate from a where clause to become a bound on an
2144 // associated type:
2145 // * It must use the identity substs of the item.
2146 // * Since any generic parameters on the item are not in scope,
2147 // this means that the item is not a GAT, and its identity
2148 // substs are the same as the trait's.
2149 // * It must be an associated type for this trait (*not* a
2150 // supertrait).
2151 if let ty::Projection(projection) = ty.kind() {
2152 projection.substs == trait_identity_substs
2153 && tcx.associated_item(projection.item_def_id).container.id() == def_id
2154 } else {
2155 false
2156 }
2157 };
2158
2159 let predicates: Vec<_> = predicates_and_bounds
2160 .predicates
2161 .iter()
2162 .copied()
2163 .filter(|(pred, _)| match pred.skip_binders() {
2164 ty::PredicateAtom::Trait(tr, _) => !is_assoc_item_ty(tr.self_ty()),
2165 ty::PredicateAtom::Projection(proj) => {
2166 !is_assoc_item_ty(proj.projection_ty.self_ty())
2167 }
2168 ty::PredicateAtom::TypeOutlives(outlives) => !is_assoc_item_ty(outlives.0),
2169 _ => true,
2170 })
2171 .collect();
2172 if predicates.len() == predicates_and_bounds.predicates.len() {
2173 predicates_and_bounds
2174 } else {
2175 ty::GenericPredicates {
2176 parent: predicates_and_bounds.parent,
2177 predicates: tcx.arena.alloc_slice(&predicates),
2178 }
2179 }
2180 } else {
2181 gather_explicit_predicates_of(tcx, def_id)
2182 }
2183 }
2184
2185 fn projection_ty_from_predicates(
2186 tcx: TyCtxt<'tcx>,
2187 key: (
2188 // ty_def_id
2189 DefId,
2190 // def_id of `N` in `<T as Trait>::N`
2191 DefId,
2192 ),
2193 ) -> Option<ty::ProjectionTy<'tcx>> {
2194 let (ty_def_id, item_def_id) = key;
2195 let mut projection_ty = None;
2196 for (predicate, _) in tcx.predicates_of(ty_def_id).predicates {
2197 if let ty::PredicateAtom::Projection(projection_predicate) = predicate.skip_binders() {
2198 if item_def_id == projection_predicate.projection_ty.item_def_id {
2199 projection_ty = Some(projection_predicate.projection_ty);
2200 break;
2201 }
2202 }
2203 }
2204 projection_ty
2205 }
2206
2207 /// Converts a specific `GenericBound` from the AST into a set of
2208 /// predicates that apply to the self type. A vector is returned
2209 /// because this can be anywhere from zero predicates (`T: ?Sized` adds no
2210 /// predicates) to one (`T: Foo`) to many (`T: Bar<X = i32>` adds `T: Bar`
2211 /// and `<T as Bar>::X == i32`).
2212 fn predicates_from_bound<'tcx>(
2213 astconv: &dyn AstConv<'tcx>,
2214 param_ty: Ty<'tcx>,
2215 bound: &'tcx hir::GenericBound<'tcx>,
2216 constness: hir::Constness,
2217 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2218 match *bound {
2219 hir::GenericBound::Trait(ref tr, modifier) => {
2220 let constness = match modifier {
2221 hir::TraitBoundModifier::Maybe => return vec![],
2222 hir::TraitBoundModifier::MaybeConst => hir::Constness::NotConst,
2223 hir::TraitBoundModifier::None => constness,
2224 };
2225
2226 let mut bounds = Bounds::default();
2227 let _ = astconv.instantiate_poly_trait_ref(tr, constness, param_ty, &mut bounds);
2228 bounds.predicates(astconv.tcx(), param_ty)
2229 }
2230 hir::GenericBound::LangItemTrait(lang_item, span, hir_id, args) => {
2231 let mut bounds = Bounds::default();
2232 astconv.instantiate_lang_item_trait_ref(
2233 lang_item,
2234 span,
2235 hir_id,
2236 args,
2237 param_ty,
2238 &mut bounds,
2239 );
2240 bounds.predicates(astconv.tcx(), param_ty)
2241 }
2242 hir::GenericBound::Outlives(ref lifetime) => {
2243 let region = astconv.ast_region_to_region(lifetime, None);
2244 let pred = ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(param_ty, region))
2245 .to_predicate(astconv.tcx());
2246 vec![(pred, lifetime.span)]
2247 }
2248 }
2249 }
2250
2251 fn compute_sig_of_foreign_fn_decl<'tcx>(
2252 tcx: TyCtxt<'tcx>,
2253 def_id: DefId,
2254 decl: &'tcx hir::FnDecl<'tcx>,
2255 abi: abi::Abi,
2256 ident: Ident,
2257 ) -> ty::PolyFnSig<'tcx> {
2258 let unsafety = if abi == abi::Abi::RustIntrinsic {
2259 intrinsic_operation_unsafety(tcx.item_name(def_id))
2260 } else {
2261 hir::Unsafety::Unsafe
2262 };
2263 let fty = AstConv::ty_of_fn(
2264 &ItemCtxt::new(tcx, def_id),
2265 unsafety,
2266 abi,
2267 decl,
2268 &hir::Generics::empty(),
2269 Some(ident.span),
2270 );
2271
2272 // Feature gate SIMD types in FFI, since I am not sure that the
2273 // ABIs are handled at all correctly. -huonw
2274 if abi != abi::Abi::RustIntrinsic
2275 && abi != abi::Abi::PlatformIntrinsic
2276 && !tcx.features().simd_ffi
2277 {
2278 let check = |ast_ty: &hir::Ty<'_>, ty: Ty<'_>| {
2279 if ty.is_simd() {
2280 let snip = tcx
2281 .sess
2282 .source_map()
2283 .span_to_snippet(ast_ty.span)
2284 .map_or(String::new(), |s| format!(" `{}`", s));
2285 tcx.sess
2286 .struct_span_err(
2287 ast_ty.span,
2288 &format!(
2289 "use of SIMD type{} in FFI is highly experimental and \
2290 may result in invalid code",
2291 snip
2292 ),
2293 )
2294 .help("add `#![feature(simd_ffi)]` to the crate attributes to enable")
2295 .emit();
2296 }
2297 };
2298 for (input, ty) in decl.inputs.iter().zip(fty.inputs().skip_binder()) {
2299 check(&input, ty)
2300 }
2301 if let hir::FnRetTy::Return(ref ty) = decl.output {
2302 check(&ty, fty.output().skip_binder())
2303 }
2304 }
2305
2306 fty
2307 }
2308
2309 fn is_foreign_item(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
2310 match tcx.hir().get_if_local(def_id) {
2311 Some(Node::ForeignItem(..)) => true,
2312 Some(_) => false,
2313 _ => bug!("is_foreign_item applied to non-local def-id {:?}", def_id),
2314 }
2315 }
2316
2317 fn static_mutability(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::Mutability> {
2318 match tcx.hir().get_if_local(def_id) {
2319 Some(
2320 Node::Item(&hir::Item { kind: hir::ItemKind::Static(_, mutbl, _), .. })
2321 | Node::ForeignItem(&hir::ForeignItem {
2322 kind: hir::ForeignItemKind::Static(_, mutbl),
2323 ..
2324 }),
2325 ) => Some(mutbl),
2326 Some(_) => None,
2327 _ => bug!("static_mutability applied to non-local def-id {:?}", def_id),
2328 }
2329 }
2330
2331 fn generator_kind(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::GeneratorKind> {
2332 match tcx.hir().get_if_local(def_id) {
2333 Some(Node::Expr(&rustc_hir::Expr {
2334 kind: rustc_hir::ExprKind::Closure(_, _, body_id, _, _),
2335 ..
2336 })) => tcx.hir().body(body_id).generator_kind(),
2337 Some(_) => None,
2338 _ => bug!("generator_kind applied to non-local def-id {:?}", def_id),
2339 }
2340 }
2341
2342 fn from_target_feature(
2343 tcx: TyCtxt<'_>,
2344 id: DefId,
2345 attr: &ast::Attribute,
2346 supported_target_features: &FxHashMap<String, Option<Symbol>>,
2347 target_features: &mut Vec<Symbol>,
2348 ) {
2349 let list = match attr.meta_item_list() {
2350 Some(list) => list,
2351 None => return,
2352 };
2353 let bad_item = |span| {
2354 let msg = "malformed `target_feature` attribute input";
2355 let code = "enable = \"..\"".to_owned();
2356 tcx.sess
2357 .struct_span_err(span, &msg)
2358 .span_suggestion(span, "must be of the form", code, Applicability::HasPlaceholders)
2359 .emit();
2360 };
2361 let rust_features = tcx.features();
2362 for item in list {
2363 // Only `enable = ...` is accepted in the meta-item list.
2364 if !item.has_name(sym::enable) {
2365 bad_item(item.span());
2366 continue;
2367 }
2368
2369 // Must be of the form `enable = "..."` (a string).
2370 let value = match item.value_str() {
2371 Some(value) => value,
2372 None => {
2373 bad_item(item.span());
2374 continue;
2375 }
2376 };
2377
2378 // We allow comma separation to enable multiple features.
2379 target_features.extend(value.as_str().split(',').filter_map(|feature| {
2380 let feature_gate = match supported_target_features.get(feature) {
2381 Some(g) => g,
2382 None => {
2383 let msg =
2384 format!("the feature named `{}` is not valid for this target", feature);
2385 let mut err = tcx.sess.struct_span_err(item.span(), &msg);
2386 err.span_label(
2387 item.span(),
2388 format!("`{}` is not valid for this target", feature),
2389 );
2390 if let Some(stripped) = feature.strip_prefix('+') {
2391 let valid = supported_target_features.contains_key(stripped);
2392 if valid {
2393 err.help("consider removing the leading `+` in the feature name");
2394 }
2395 }
2396 err.emit();
2397 return None;
2398 }
2399 };
2400
2401 // Only allow features whose feature gates have been enabled.
2402 let allowed = match feature_gate.as_ref().copied() {
2403 Some(sym::arm_target_feature) => rust_features.arm_target_feature,
2404 Some(sym::aarch64_target_feature) => rust_features.aarch64_target_feature,
2405 Some(sym::hexagon_target_feature) => rust_features.hexagon_target_feature,
2406 Some(sym::powerpc_target_feature) => rust_features.powerpc_target_feature,
2407 Some(sym::mips_target_feature) => rust_features.mips_target_feature,
2408 Some(sym::riscv_target_feature) => rust_features.riscv_target_feature,
2409 Some(sym::avx512_target_feature) => rust_features.avx512_target_feature,
2410 Some(sym::sse4a_target_feature) => rust_features.sse4a_target_feature,
2411 Some(sym::tbm_target_feature) => rust_features.tbm_target_feature,
2412 Some(sym::wasm_target_feature) => rust_features.wasm_target_feature,
2413 Some(sym::cmpxchg16b_target_feature) => rust_features.cmpxchg16b_target_feature,
2414 Some(sym::adx_target_feature) => rust_features.adx_target_feature,
2415 Some(sym::movbe_target_feature) => rust_features.movbe_target_feature,
2416 Some(sym::rtm_target_feature) => rust_features.rtm_target_feature,
2417 Some(sym::f16c_target_feature) => rust_features.f16c_target_feature,
2418 Some(sym::ermsb_target_feature) => rust_features.ermsb_target_feature,
2419 Some(name) => bug!("unknown target feature gate {}", name),
2420 None => true,
2421 };
2422 if !allowed && id.is_local() {
2423 feature_err(
2424 &tcx.sess.parse_sess,
2425 feature_gate.unwrap(),
2426 item.span(),
2427 &format!("the target feature `{}` is currently unstable", feature),
2428 )
2429 .emit();
2430 }
2431 Some(Symbol::intern(feature))
2432 }));
2433 }
2434 }
2435
2436 fn linkage_by_name(tcx: TyCtxt<'_>, def_id: DefId, name: &str) -> Linkage {
2437 use rustc_middle::mir::mono::Linkage::*;
2438
2439 // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
2440 // applicable to variable declarations and may not really make sense for
2441 // Rust code in the first place but allow them anyway and trust that the
2442 // user knows what s/he's doing. Who knows, unanticipated use cases may pop
2443 // up in the future.
2444 //
2445 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
2446 // and don't have to be, LLVM treats them as no-ops.
2447 match name {
2448 "appending" => Appending,
2449 "available_externally" => AvailableExternally,
2450 "common" => Common,
2451 "extern_weak" => ExternalWeak,
2452 "external" => External,
2453 "internal" => Internal,
2454 "linkonce" => LinkOnceAny,
2455 "linkonce_odr" => LinkOnceODR,
2456 "private" => Private,
2457 "weak" => WeakAny,
2458 "weak_odr" => WeakODR,
2459 _ => {
2460 let span = tcx.hir().span_if_local(def_id);
2461 if let Some(span) = span {
2462 tcx.sess.span_fatal(span, "invalid linkage specified")
2463 } else {
2464 tcx.sess.fatal(&format!("invalid linkage specified: {}", name))
2465 }
2466 }
2467 }
2468 }
2469
2470 fn codegen_fn_attrs(tcx: TyCtxt<'_>, id: DefId) -> CodegenFnAttrs {
2471 let attrs = tcx.get_attrs(id);
2472
2473 let mut codegen_fn_attrs = CodegenFnAttrs::new();
2474 if should_inherit_track_caller(tcx, id) {
2475 codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
2476 }
2477
2478 let supported_target_features = tcx.supported_target_features(LOCAL_CRATE);
2479
2480 let mut inline_span = None;
2481 let mut link_ordinal_span = None;
2482 let mut no_sanitize_span = None;
2483 for attr in attrs.iter() {
2484 if tcx.sess.check_name(attr, sym::cold) {
2485 codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD;
2486 } else if tcx.sess.check_name(attr, sym::rustc_allocator) {
2487 codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR;
2488 } else if tcx.sess.check_name(attr, sym::unwind) {
2489 codegen_fn_attrs.flags |= CodegenFnAttrFlags::UNWIND;
2490 } else if tcx.sess.check_name(attr, sym::ffi_returns_twice) {
2491 if tcx.is_foreign_item(id) {
2492 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_RETURNS_TWICE;
2493 } else {
2494 // `#[ffi_returns_twice]` is only allowed `extern fn`s.
2495 struct_span_err!(
2496 tcx.sess,
2497 attr.span,
2498 E0724,
2499 "`#[ffi_returns_twice]` may only be used on foreign functions"
2500 )
2501 .emit();
2502 }
2503 } else if tcx.sess.check_name(attr, sym::ffi_pure) {
2504 if tcx.is_foreign_item(id) {
2505 if attrs.iter().any(|a| tcx.sess.check_name(a, sym::ffi_const)) {
2506 // `#[ffi_const]` functions cannot be `#[ffi_pure]`
2507 struct_span_err!(
2508 tcx.sess,
2509 attr.span,
2510 E0757,
2511 "`#[ffi_const]` function cannot be `#[ffi_pure]`"
2512 )
2513 .emit();
2514 } else {
2515 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_PURE;
2516 }
2517 } else {
2518 // `#[ffi_pure]` is only allowed on foreign functions
2519 struct_span_err!(
2520 tcx.sess,
2521 attr.span,
2522 E0755,
2523 "`#[ffi_pure]` may only be used on foreign functions"
2524 )
2525 .emit();
2526 }
2527 } else if tcx.sess.check_name(attr, sym::ffi_const) {
2528 if tcx.is_foreign_item(id) {
2529 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_CONST;
2530 } else {
2531 // `#[ffi_const]` is only allowed on foreign functions
2532 struct_span_err!(
2533 tcx.sess,
2534 attr.span,
2535 E0756,
2536 "`#[ffi_const]` may only be used on foreign functions"
2537 )
2538 .emit();
2539 }
2540 } else if tcx.sess.check_name(attr, sym::rustc_allocator_nounwind) {
2541 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND;
2542 } else if tcx.sess.check_name(attr, sym::naked) {
2543 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED;
2544 } else if tcx.sess.check_name(attr, sym::no_mangle) {
2545 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2546 } else if tcx.sess.check_name(attr, sym::rustc_std_internal_symbol) {
2547 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2548 } else if tcx.sess.check_name(attr, sym::used) {
2549 codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED;
2550 } else if tcx.sess.check_name(attr, sym::cmse_nonsecure_entry) {
2551 if tcx.fn_sig(id).abi() != abi::Abi::C {
2552 struct_span_err!(
2553 tcx.sess,
2554 attr.span,
2555 E0776,
2556 "`#[cmse_nonsecure_entry]` requires C ABI"
2557 )
2558 .emit();
2559 }
2560 if !tcx.sess.target.llvm_target.contains("thumbv8m") {
2561 struct_span_err!(tcx.sess, attr.span, E0775, "`#[cmse_nonsecure_entry]` is only valid for targets with the TrustZone-M extension")
2562 .emit();
2563 }
2564 codegen_fn_attrs.flags |= CodegenFnAttrFlags::CMSE_NONSECURE_ENTRY;
2565 } else if tcx.sess.check_name(attr, sym::thread_local) {
2566 codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL;
2567 } else if tcx.sess.check_name(attr, sym::track_caller) {
2568 if tcx.is_closure(id) || tcx.fn_sig(id).abi() != abi::Abi::Rust {
2569 struct_span_err!(tcx.sess, attr.span, E0737, "`#[track_caller]` requires Rust ABI")
2570 .emit();
2571 }
2572 codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
2573 } else if tcx.sess.check_name(attr, sym::export_name) {
2574 if let Some(s) = attr.value_str() {
2575 if s.as_str().contains('\0') {
2576 // `#[export_name = ...]` will be converted to a null-terminated string,
2577 // so it may not contain any null characters.
2578 struct_span_err!(
2579 tcx.sess,
2580 attr.span,
2581 E0648,
2582 "`export_name` may not contain null characters"
2583 )
2584 .emit();
2585 }
2586 codegen_fn_attrs.export_name = Some(s);
2587 }
2588 } else if tcx.sess.check_name(attr, sym::target_feature) {
2589 if !tcx.is_closure(id) && tcx.fn_sig(id).unsafety() == hir::Unsafety::Normal {
2590 if !tcx.features().target_feature_11 {
2591 let mut err = feature_err(
2592 &tcx.sess.parse_sess,
2593 sym::target_feature_11,
2594 attr.span,
2595 "`#[target_feature(..)]` can only be applied to `unsafe` functions",
2596 );
2597 err.span_label(tcx.def_span(id), "not an `unsafe` function");
2598 err.emit();
2599 } else if let Some(local_id) = id.as_local() {
2600 check_target_feature_trait_unsafe(tcx, local_id, attr.span);
2601 }
2602 }
2603 from_target_feature(
2604 tcx,
2605 id,
2606 attr,
2607 &supported_target_features,
2608 &mut codegen_fn_attrs.target_features,
2609 );
2610 } else if tcx.sess.check_name(attr, sym::linkage) {
2611 if let Some(val) = attr.value_str() {
2612 codegen_fn_attrs.linkage = Some(linkage_by_name(tcx, id, &val.as_str()));
2613 }
2614 } else if tcx.sess.check_name(attr, sym::link_section) {
2615 if let Some(val) = attr.value_str() {
2616 if val.as_str().bytes().any(|b| b == 0) {
2617 let msg = format!(
2618 "illegal null byte in link_section \
2619 value: `{}`",
2620 &val
2621 );
2622 tcx.sess.span_err(attr.span, &msg);
2623 } else {
2624 codegen_fn_attrs.link_section = Some(val);
2625 }
2626 }
2627 } else if tcx.sess.check_name(attr, sym::link_name) {
2628 codegen_fn_attrs.link_name = attr.value_str();
2629 } else if tcx.sess.check_name(attr, sym::link_ordinal) {
2630 link_ordinal_span = Some(attr.span);
2631 if let ordinal @ Some(_) = check_link_ordinal(tcx, attr) {
2632 codegen_fn_attrs.link_ordinal = ordinal;
2633 }
2634 } else if tcx.sess.check_name(attr, sym::no_sanitize) {
2635 no_sanitize_span = Some(attr.span);
2636 if let Some(list) = attr.meta_item_list() {
2637 for item in list.iter() {
2638 if item.has_name(sym::address) {
2639 codegen_fn_attrs.no_sanitize |= SanitizerSet::ADDRESS;
2640 } else if item.has_name(sym::memory) {
2641 codegen_fn_attrs.no_sanitize |= SanitizerSet::MEMORY;
2642 } else if item.has_name(sym::thread) {
2643 codegen_fn_attrs.no_sanitize |= SanitizerSet::THREAD;
2644 } else {
2645 tcx.sess
2646 .struct_span_err(item.span(), "invalid argument for `no_sanitize`")
2647 .note("expected one of: `address`, `memory` or `thread`")
2648 .emit();
2649 }
2650 }
2651 }
2652 } else if tcx.sess.check_name(attr, sym::instruction_set) {
2653 codegen_fn_attrs.instruction_set = match attr.meta().map(|i| i.kind) {
2654 Some(MetaItemKind::List(ref items)) => match items.as_slice() {
2655 [NestedMetaItem::MetaItem(set)] => {
2656 let segments =
2657 set.path.segments.iter().map(|x| x.ident.name).collect::<Vec<_>>();
2658 match segments.as_slice() {
2659 [sym::arm, sym::a32] | [sym::arm, sym::t32] => {
2660 if !tcx.sess.target.has_thumb_interworking {
2661 struct_span_err!(
2662 tcx.sess.diagnostic(),
2663 attr.span,
2664 E0779,
2665 "target does not support `#[instruction_set]`"
2666 )
2667 .emit();
2668 None
2669 } else if segments[1] == sym::a32 {
2670 Some(InstructionSetAttr::ArmA32)
2671 } else if segments[1] == sym::t32 {
2672 Some(InstructionSetAttr::ArmT32)
2673 } else {
2674 unreachable!()
2675 }
2676 }
2677 _ => {
2678 struct_span_err!(
2679 tcx.sess.diagnostic(),
2680 attr.span,
2681 E0779,
2682 "invalid instruction set specified",
2683 )
2684 .emit();
2685 None
2686 }
2687 }
2688 }
2689 [] => {
2690 struct_span_err!(
2691 tcx.sess.diagnostic(),
2692 attr.span,
2693 E0778,
2694 "`#[instruction_set]` requires an argument"
2695 )
2696 .emit();
2697 None
2698 }
2699 _ => {
2700 struct_span_err!(
2701 tcx.sess.diagnostic(),
2702 attr.span,
2703 E0779,
2704 "cannot specify more than one instruction set"
2705 )
2706 .emit();
2707 None
2708 }
2709 },
2710 _ => {
2711 struct_span_err!(
2712 tcx.sess.diagnostic(),
2713 attr.span,
2714 E0778,
2715 "must specify an instruction set"
2716 )
2717 .emit();
2718 None
2719 }
2720 };
2721 }
2722 }
2723
2724 codegen_fn_attrs.inline = attrs.iter().fold(InlineAttr::None, |ia, attr| {
2725 if !attr.has_name(sym::inline) {
2726 return ia;
2727 }
2728 match attr.meta().map(|i| i.kind) {
2729 Some(MetaItemKind::Word) => {
2730 tcx.sess.mark_attr_used(attr);
2731 InlineAttr::Hint
2732 }
2733 Some(MetaItemKind::List(ref items)) => {
2734 tcx.sess.mark_attr_used(attr);
2735 inline_span = Some(attr.span);
2736 if items.len() != 1 {
2737 struct_span_err!(
2738 tcx.sess.diagnostic(),
2739 attr.span,
2740 E0534,
2741 "expected one argument"
2742 )
2743 .emit();
2744 InlineAttr::None
2745 } else if list_contains_name(&items[..], sym::always) {
2746 InlineAttr::Always
2747 } else if list_contains_name(&items[..], sym::never) {
2748 InlineAttr::Never
2749 } else {
2750 struct_span_err!(
2751 tcx.sess.diagnostic(),
2752 items[0].span(),
2753 E0535,
2754 "invalid argument"
2755 )
2756 .emit();
2757
2758 InlineAttr::None
2759 }
2760 }
2761 Some(MetaItemKind::NameValue(_)) => ia,
2762 None => ia,
2763 }
2764 });
2765
2766 codegen_fn_attrs.optimize = attrs.iter().fold(OptimizeAttr::None, |ia, attr| {
2767 if !attr.has_name(sym::optimize) {
2768 return ia;
2769 }
2770 let err = |sp, s| struct_span_err!(tcx.sess.diagnostic(), sp, E0722, "{}", s).emit();
2771 match attr.meta().map(|i| i.kind) {
2772 Some(MetaItemKind::Word) => {
2773 err(attr.span, "expected one argument");
2774 ia
2775 }
2776 Some(MetaItemKind::List(ref items)) => {
2777 tcx.sess.mark_attr_used(attr);
2778 inline_span = Some(attr.span);
2779 if items.len() != 1 {
2780 err(attr.span, "expected one argument");
2781 OptimizeAttr::None
2782 } else if list_contains_name(&items[..], sym::size) {
2783 OptimizeAttr::Size
2784 } else if list_contains_name(&items[..], sym::speed) {
2785 OptimizeAttr::Speed
2786 } else {
2787 err(items[0].span(), "invalid argument");
2788 OptimizeAttr::None
2789 }
2790 }
2791 Some(MetaItemKind::NameValue(_)) => ia,
2792 None => ia,
2793 }
2794 });
2795
2796 // #73631: closures inherit `#[target_feature]` annotations
2797 if tcx.features().target_feature_11 && tcx.is_closure(id) {
2798 let owner_id = tcx.parent(id).expect("closure should have a parent");
2799 codegen_fn_attrs
2800 .target_features
2801 .extend(tcx.codegen_fn_attrs(owner_id).target_features.iter().copied())
2802 }
2803
2804 // If a function uses #[target_feature] it can't be inlined into general
2805 // purpose functions as they wouldn't have the right target features
2806 // enabled. For that reason we also forbid #[inline(always)] as it can't be
2807 // respected.
2808 if !codegen_fn_attrs.target_features.is_empty() {
2809 if codegen_fn_attrs.inline == InlineAttr::Always {
2810 if let Some(span) = inline_span {
2811 tcx.sess.span_err(
2812 span,
2813 "cannot use `#[inline(always)]` with \
2814 `#[target_feature]`",
2815 );
2816 }
2817 }
2818 }
2819
2820 if !codegen_fn_attrs.no_sanitize.is_empty() {
2821 if codegen_fn_attrs.inline == InlineAttr::Always {
2822 if let (Some(no_sanitize_span), Some(inline_span)) = (no_sanitize_span, inline_span) {
2823 let hir_id = tcx.hir().local_def_id_to_hir_id(id.expect_local());
2824 tcx.struct_span_lint_hir(
2825 lint::builtin::INLINE_NO_SANITIZE,
2826 hir_id,
2827 no_sanitize_span,
2828 |lint| {
2829 lint.build("`no_sanitize` will have no effect after inlining")
2830 .span_note(inline_span, "inlining requested here")
2831 .emit();
2832 },
2833 )
2834 }
2835 }
2836 }
2837
2838 // Weak lang items have the same semantics as "std internal" symbols in the
2839 // sense that they're preserved through all our LTO passes and only
2840 // strippable by the linker.
2841 //
2842 // Additionally weak lang items have predetermined symbol names.
2843 if tcx.is_weak_lang_item(id) {
2844 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2845 }
2846 let check_name = |attr, sym| tcx.sess.check_name(attr, sym);
2847 if let Some(name) = weak_lang_items::link_name(check_name, &attrs) {
2848 codegen_fn_attrs.export_name = Some(name);
2849 codegen_fn_attrs.link_name = Some(name);
2850 }
2851 check_link_name_xor_ordinal(tcx, &codegen_fn_attrs, link_ordinal_span);
2852
2853 // Internal symbols to the standard library all have no_mangle semantics in
2854 // that they have defined symbol names present in the function name. This
2855 // also applies to weak symbols where they all have known symbol names.
2856 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
2857 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2858 }
2859
2860 codegen_fn_attrs
2861 }
2862
2863 /// Checks if the provided DefId is a method in a trait impl for a trait which has track_caller
2864 /// applied to the method prototype.
2865 fn should_inherit_track_caller(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
2866 if let Some(impl_item) = tcx.opt_associated_item(def_id) {
2867 if let ty::AssocItemContainer::ImplContainer(impl_def_id) = impl_item.container {
2868 if let Some(trait_def_id) = tcx.trait_id_of_impl(impl_def_id) {
2869 if let Some(trait_item) = tcx
2870 .associated_items(trait_def_id)
2871 .filter_by_name_unhygienic(impl_item.ident.name)
2872 .find(move |trait_item| {
2873 trait_item.kind == ty::AssocKind::Fn
2874 && tcx.hygienic_eq(impl_item.ident, trait_item.ident, trait_def_id)
2875 })
2876 {
2877 return tcx
2878 .codegen_fn_attrs(trait_item.def_id)
2879 .flags
2880 .intersects(CodegenFnAttrFlags::TRACK_CALLER);
2881 }
2882 }
2883 }
2884 }
2885
2886 false
2887 }
2888
2889 fn check_link_ordinal(tcx: TyCtxt<'_>, attr: &ast::Attribute) -> Option<usize> {
2890 use rustc_ast::{Lit, LitIntType, LitKind};
2891 let meta_item_list = attr.meta_item_list();
2892 let meta_item_list: Option<&[ast::NestedMetaItem]> = meta_item_list.as_ref().map(Vec::as_ref);
2893 let sole_meta_list = match meta_item_list {
2894 Some([item]) => item.literal(),
2895 _ => None,
2896 };
2897 if let Some(Lit { kind: LitKind::Int(ordinal, LitIntType::Unsuffixed), .. }) = sole_meta_list {
2898 if *ordinal <= usize::MAX as u128 {
2899 Some(*ordinal as usize)
2900 } else {
2901 let msg = format!("ordinal value in `link_ordinal` is too large: `{}`", &ordinal);
2902 tcx.sess
2903 .struct_span_err(attr.span, &msg)
2904 .note("the value may not exceed `usize::MAX`")
2905 .emit();
2906 None
2907 }
2908 } else {
2909 tcx.sess
2910 .struct_span_err(attr.span, "illegal ordinal format in `link_ordinal`")
2911 .note("an unsuffixed integer value, e.g., `1`, is expected")
2912 .emit();
2913 None
2914 }
2915 }
2916
2917 fn check_link_name_xor_ordinal(
2918 tcx: TyCtxt<'_>,
2919 codegen_fn_attrs: &CodegenFnAttrs,
2920 inline_span: Option<Span>,
2921 ) {
2922 if codegen_fn_attrs.link_name.is_none() || codegen_fn_attrs.link_ordinal.is_none() {
2923 return;
2924 }
2925 let msg = "cannot use `#[link_name]` with `#[link_ordinal]`";
2926 if let Some(span) = inline_span {
2927 tcx.sess.span_err(span, msg);
2928 } else {
2929 tcx.sess.err(msg);
2930 }
2931 }
2932
2933 /// Checks the function annotated with `#[target_feature]` is not a safe
2934 /// trait method implementation, reporting an error if it is.
2935 fn check_target_feature_trait_unsafe(tcx: TyCtxt<'_>, id: LocalDefId, attr_span: Span) {
2936 let hir_id = tcx.hir().local_def_id_to_hir_id(id);
2937 let node = tcx.hir().get(hir_id);
2938 if let Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }) = node {
2939 let parent_id = tcx.hir().get_parent_item(hir_id);
2940 let parent_item = tcx.hir().expect_item(parent_id);
2941 if let hir::ItemKind::Impl { of_trait: Some(_), .. } = parent_item.kind {
2942 tcx.sess
2943 .struct_span_err(
2944 attr_span,
2945 "`#[target_feature(..)]` cannot be applied to safe trait method",
2946 )
2947 .span_label(attr_span, "cannot be applied to safe trait method")
2948 .span_label(tcx.def_span(id), "not an `unsafe` function")
2949 .emit();
2950 }
2951 }
2952 }