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