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