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