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