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