X-Git-Url: https://git.lizzy.rs/?a=blobdiff_plain;f=src%2Flibrustc_typeck%2Fcheck%2Fmod.rs;h=fe742a74fffec7e49f35590cc07d05bb3a06e297;hb=e8a88f7d4330c62bc039c21831894c2758a43e60;hp=427c5faa991722edf2728f97a1be5906323ac4aa;hpb=d67db0042c1f4e163292ea59bdfac546c67f7001;p=rust.git diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index 427c5faa991..fb7d681a72d 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -93,6 +93,7 @@ use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE}; use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap}; use rustc::hir::itemlikevisit::ItemLikeVisitor; +use rustc::hir::ptr::P; use crate::middle::lang_items; use crate::namespace::Namespace; use rustc::infer::{self, InferCtxt, InferOk, InferResult}; @@ -122,7 +123,6 @@ use syntax::ast; use syntax::attr; use syntax::feature_gate::{GateIssue, emit_feature_err}; -use syntax::ptr::P; use syntax::source_map::{DUMMY_SP, original_sp}; use syntax::symbol::{kw, sym}; @@ -160,7 +160,7 @@ pub struct LocalTy<'tcx> { /// A wrapper for `InferCtxt`'s `in_progress_tables` field. #[derive(Copy, Clone)] -struct MaybeInProgressTables<'a, 'tcx: 'a> { +struct MaybeInProgressTables<'a, 'tcx> { maybe_tables: Option<&'a RefCell>>, } @@ -193,7 +193,7 @@ fn borrow_mut(self) -> RefMut<'a, ty::TypeckTables<'tcx>> { /// Here, the function `foo()` and the closure passed to /// `bar()` will each have their own `FnCtxt`, but they will /// share the inherited fields. -pub struct Inherited<'a, 'tcx: 'a> { +pub struct Inherited<'a, 'tcx> { infcx: InferCtxt<'a, 'tcx>, tables: MaybeInProgressTables<'a, 'tcx>, @@ -512,7 +512,7 @@ fn find_breakable(&mut self, target_id: hir::HirId) -> &mut BreakableCtxt<'tcx> } } -pub struct FnCtxt<'a, 'tcx: 'a> { +pub struct FnCtxt<'a, 'tcx> { body_id: hir::HirId, /// The parameter environment used for proving trait obligations @@ -527,6 +527,8 @@ pub struct FnCtxt<'a, 'tcx: 'a> { /// checking this function. On exit, if we find that *more* errors /// have been reported, we will skip regionck and other work that /// expects the types within the function to be consistent. + // FIXME(matthewjasper) This should not exist, and it's not correct + // if type checking is run in parallel. err_count_on_creation: usize, ret_coercion: Option>>, @@ -622,7 +624,7 @@ impl Inherited<'a, 'tcx> { fn new(infcx: InferCtxt<'a, 'tcx>, def_id: DefId) -> Self { let tcx = infcx.tcx; let item_id = tcx.hir().as_local_hir_id(def_id); - let body_id = item_id.and_then(|id| tcx.hir().maybe_body_owned_by_by_hir_id(id)); + let body_id = item_id.and_then(|id| tcx.hir().maybe_body_owned_by(id)); let implicit_region_bound = body_id.map(|body_id| { let body = tcx.hir().body(body_id); tcx.mk_region(ty::ReScope(region::Scope { @@ -696,33 +698,31 @@ fn visit_trait_item(&mut self, _: &'tcx hir::TraitItem) { } fn visit_impl_item(&mut self, _: &'tcx hir::ImplItem) { } } -pub fn check_wf_new<'tcx>(tcx: TyCtxt<'tcx>) -> Result<(), ErrorReported> { - tcx.sess.track_errors(|| { - let mut visit = wfcheck::CheckTypeWellFormedVisitor::new(tcx); - tcx.hir().krate().par_visit_all_item_likes(&mut visit); - }) +pub fn check_wf_new(tcx: TyCtxt<'_>) { + let mut visit = wfcheck::CheckTypeWellFormedVisitor::new(tcx); + tcx.hir().krate().par_visit_all_item_likes(&mut visit); } -fn check_mod_item_types<'tcx>(tcx: TyCtxt<'tcx>, module_def_id: DefId) { +fn check_mod_item_types(tcx: TyCtxt<'_>, module_def_id: DefId) { tcx.hir().visit_item_likes_in_module(module_def_id, &mut CheckItemTypesVisitor { tcx }); } -fn typeck_item_bodies<'tcx>(tcx: TyCtxt<'tcx>, crate_num: CrateNum) { +fn typeck_item_bodies(tcx: TyCtxt<'_>, crate_num: CrateNum) { debug_assert!(crate_num == LOCAL_CRATE); tcx.par_body_owners(|body_owner_def_id| { tcx.ensure().typeck_tables_of(body_owner_def_id); }); } -fn check_item_well_formed<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) { +fn check_item_well_formed(tcx: TyCtxt<'_>, def_id: DefId) { wfcheck::check_item_well_formed(tcx, def_id); } -fn check_trait_item_well_formed<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) { +fn check_trait_item_well_formed(tcx: TyCtxt<'_>, def_id: DefId) { wfcheck::check_trait_item(tcx, def_id); } -fn check_impl_item_well_formed<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) { +fn check_impl_item_well_formed(tcx: TyCtxt<'_>, def_id: DefId) { wfcheck::check_impl_item(tcx, def_id); } @@ -742,7 +742,7 @@ pub fn provide(providers: &mut Providers<'_>) { }; } -fn adt_destructor<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> Option { +fn adt_destructor(tcx: TyCtxt<'_>, def_id: DefId) -> Option { tcx.calculate_dtor(def_id, &mut dropck::check_drop_impl) } @@ -755,11 +755,11 @@ fn adt_destructor<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> Option( - tcx: TyCtxt<'tcx>, +fn primary_body_of( + tcx: TyCtxt<'_>, id: hir::HirId, -) -> Option<(hir::BodyId, Option<&'tcx hir::FnDecl>)> { - match tcx.hir().get_by_hir_id(id) { +) -> Option<(hir::BodyId, Option<&hir::FnDecl>)> { + match tcx.hir().get(id) { Node::Item(item) => { match item.node { hir::ItemKind::Const(_, body) | @@ -796,7 +796,7 @@ fn primary_body_of<'tcx>( } } -fn has_typeck_tables<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> bool { +fn has_typeck_tables(tcx: TyCtxt<'_>, def_id: DefId) -> bool { // Closures' tables come from their outermost function, // as they are part of the same "inference environment". let outer_def_id = tcx.closure_base_def_id(def_id); @@ -808,11 +808,11 @@ fn has_typeck_tables<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> bool { primary_body_of(tcx, id).is_some() } -fn used_trait_imports<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> &'tcx DefIdSet { +fn used_trait_imports(tcx: TyCtxt<'_>, def_id: DefId) -> &DefIdSet { &*tcx.typeck_tables_of(def_id).used_trait_imports } -fn typeck_tables_of<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> &'tcx ty::TypeckTables<'tcx> { +fn typeck_tables_of(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::TypeckTables<'_> { // Closures' tables come from their outermost function, // as they are part of the same "inference environment". let outer_def_id = tcx.closure_base_def_id(def_id); @@ -821,7 +821,7 @@ fn typeck_tables_of<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> &'tcx ty::TypeckT } let id = tcx.hir().as_local_hir_id(def_id).unwrap(); - let span = tcx.hir().span_by_hir_id(id); + let span = tcx.hir().span(id); // Figure out what primary body this item has. let (body_id, fn_decl) = primary_body_of(tcx, id).unwrap_or_else(|| { @@ -856,7 +856,8 @@ fn typeck_tables_of<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> &'tcx ty::TypeckT let revealed_ty = if tcx.features().impl_trait_in_bindings { fcx.instantiate_opaque_types_from_value( id, - &expected_type + &expected_type, + body.value.span, ) } else { expected_type @@ -912,14 +913,14 @@ fn typeck_tables_of<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> &'tcx ty::TypeckT tables } -fn check_abi<'tcx>(tcx: TyCtxt<'tcx>, span: Span, abi: Abi) { +fn check_abi(tcx: TyCtxt<'_>, span: Span, abi: Abi) { if !tcx.sess.target.target.is_abi_supported(abi) { struct_span_err!(tcx.sess, span, E0570, "The ABI `{}` is not supported for the current target", abi).emit() } } -struct GatherLocalsVisitor<'a, 'tcx: 'a> { +struct GatherLocalsVisitor<'a, 'tcx> { fcx: &'a FnCtxt<'a, 'tcx>, parent_id: hir::HirId, } @@ -962,7 +963,8 @@ fn visit_local(&mut self, local: &'tcx hir::Local) { let revealed_ty = if self.fcx.tcx.features().impl_trait_in_bindings { self.fcx.instantiate_opaque_types_from_value( self.parent_id, - &o_ty + &o_ty, + ty.span, ) } else { o_ty @@ -993,10 +995,9 @@ fn visit_pat(&mut self, p: &'tcx hir::Pat) { if let PatKind::Binding(_, _, ident, _) = p.node { let var_ty = self.assign(p.span, p.hir_id, None); - let node_id = self.fcx.tcx.hir().hir_to_node_id(p.hir_id); if !self.fcx.tcx.features().unsized_locals { self.fcx.require_type_is_sized(var_ty, p.span, - traits::VariableType(node_id)); + traits::VariableType(p.hir_id)); } debug!("Pattern binding {} is assigned to {} with type {:?}", @@ -1059,7 +1060,11 @@ fn check_fn<'a, 'tcx>( let declared_ret_ty = fn_sig.output(); fcx.require_type_is_sized(declared_ret_ty, decl.output.span(), traits::SizedReturnType); - let revealed_ret_ty = fcx.instantiate_opaque_types_from_value(fn_id, &declared_ret_ty); + let revealed_ret_ty = fcx.instantiate_opaque_types_from_value( + fn_id, + &declared_ret_ty, + decl.output.span(), + ); fcx.ret_coercion = Some(RefCell::new(CoerceMany::new(revealed_ret_ty))); fn_sig = fcx.tcx.mk_fn_sig( fn_sig.inputs().iter().cloned(), @@ -1193,7 +1198,7 @@ fn check_fn<'a, 'tcx>( } let inputs = fn_sig.inputs(); - let span = fcx.tcx.hir().span_by_hir_id(fn_id); + let span = fcx.tcx.hir().span(fn_id); if inputs.len() == 1 { let arg_is_panic_info = match inputs[0].sty { ty::Ref(region, ty, mutbl) => match ty.sty { @@ -1214,7 +1219,7 @@ fn check_fn<'a, 'tcx>( ); } - if let Node::Item(item) = fcx.tcx.hir().get_by_hir_id(fn_id) { + if let Node::Item(item) = fcx.tcx.hir().get(fn_id) { if let ItemKind::Fn(_, _, ref generics, _) = item.node { if !generics.params.is_empty() { fcx.tcx.sess.span_err( @@ -1246,7 +1251,7 @@ fn check_fn<'a, 'tcx>( } let inputs = fn_sig.inputs(); - let span = fcx.tcx.hir().span_by_hir_id(fn_id); + let span = fcx.tcx.hir().span(fn_id); if inputs.len() == 1 { let arg_is_alloc_layout = match inputs[0].sty { ty::Adt(ref adt, _) => { @@ -1262,7 +1267,7 @@ fn check_fn<'a, 'tcx>( ); } - if let Node::Item(item) = fcx.tcx.hir().get_by_hir_id(fn_id) { + if let Node::Item(item) = fcx.tcx.hir().get(fn_id) { if let ItemKind::Fn(_, _, ref generics, _) = item.node { if !generics.params.is_empty() { fcx.tcx.sess.span_err( @@ -1286,7 +1291,7 @@ fn check_fn<'a, 'tcx>( (fcx, gen_ty) } -fn check_struct<'tcx>(tcx: TyCtxt<'tcx>, id: hir::HirId, span: Span) { +fn check_struct(tcx: TyCtxt<'_>, id: hir::HirId, span: Span) { let def_id = tcx.hir().local_def_id_from_hir_id(id); let def = tcx.adt_def(def_id); def.destructor(tcx); // force the destructor to be evaluated @@ -1300,7 +1305,7 @@ fn check_struct<'tcx>(tcx: TyCtxt<'tcx>, id: hir::HirId, span: Span) { check_packed(tcx, span, def_id); } -fn check_union<'tcx>(tcx: TyCtxt<'tcx>, id: hir::HirId, span: Span) { +fn check_union(tcx: TyCtxt<'_>, id: hir::HirId, span: Span) { let def_id = tcx.hir().local_def_id_from_hir_id(id); let def = tcx.adt_def(def_id); def.destructor(tcx); // force the destructor to be evaluated @@ -1448,8 +1453,8 @@ fn maybe_check_static_with_link_section(tcx: TyCtxt<'_>, id: DefId, span: Span) }; let param_env = ty::ParamEnv::reveal_all(); if let Ok(static_) = tcx.const_eval(param_env.and(cid)) { - let alloc = if let ConstValue::ByRef(_, allocation) = static_.val { - allocation + let alloc = if let ConstValue::ByRef { alloc, .. } = static_.val { + alloc } else { bug!("Matching on non-ByRef static") }; @@ -1462,14 +1467,14 @@ fn maybe_check_static_with_link_section(tcx: TyCtxt<'_>, id: DefId, span: Span) } } -fn check_on_unimplemented<'tcx>(tcx: TyCtxt<'tcx>, trait_def_id: DefId, item: &hir::Item) { +fn check_on_unimplemented(tcx: TyCtxt<'_>, trait_def_id: DefId, item: &hir::Item) { let item_def_id = tcx.hir().local_def_id_from_hir_id(item.hir_id); // an error would be reported if this fails. let _ = traits::OnUnimplementedDirective::of_item(tcx, trait_def_id, item_def_id); } -fn report_forbidden_specialization<'tcx>( - tcx: TyCtxt<'tcx>, +fn report_forbidden_specialization( + tcx: TyCtxt<'_>, impl_item: &hir::ImplItem, parent_impl: DefId, ) { @@ -1685,7 +1690,7 @@ fn check_impl_items_against_trait<'tcx>( /// Checks whether a type can be represented in memory. In particular, it /// identifies types that contain themselves without indirection through a /// pointer, which would mean their size is unbounded. -fn check_representable<'tcx>(tcx: TyCtxt<'tcx>, sp: Span, item_def_id: DefId) -> bool { +fn check_representable(tcx: TyCtxt<'_>, sp: Span, item_def_id: DefId) -> bool { let rty = tcx.type_of(item_def_id); // Check that it is possible to represent this type. This call identifies @@ -1707,7 +1712,7 @@ fn check_representable<'tcx>(tcx: TyCtxt<'tcx>, sp: Span, item_def_id: DefId) -> return true; } -pub fn check_simd<'tcx>(tcx: TyCtxt<'tcx>, sp: Span, def_id: DefId) { +pub fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: DefId) { let t = tcx.type_of(def_id); if let ty::Adt(def, substs) = t.sty { if def.is_struct() { @@ -1736,7 +1741,7 @@ pub fn check_simd<'tcx>(tcx: TyCtxt<'tcx>, sp: Span, def_id: DefId) { } } -fn check_packed<'tcx>(tcx: TyCtxt<'tcx>, sp: Span, def_id: DefId) { +fn check_packed(tcx: TyCtxt<'_>, sp: Span, def_id: DefId) { let repr = tcx.adt_def(def_id).repr; if repr.packed() { for attr in tcx.get_attrs(def_id).iter() { @@ -1760,7 +1765,7 @@ fn check_packed<'tcx>(tcx: TyCtxt<'tcx>, sp: Span, def_id: DefId) { } } -fn check_packed_inner<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, stack: &mut Vec) -> bool { +fn check_packed_inner(tcx: TyCtxt<'_>, def_id: DefId, stack: &mut Vec) -> bool { let t = tcx.type_of(def_id); if stack.contains(&def_id) { debug!("check_packed_inner: {:?} is recursive", t); @@ -1788,32 +1793,71 @@ fn check_packed_inner<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, stack: &mut Vec(tcx: TyCtxt<'tcx>, sp: Span, def_id: DefId) { +/// Emit an error when encountering more or less than one variant in a transparent enum. +fn bad_variant_count<'tcx>(tcx: TyCtxt<'tcx>, adt: &'tcx ty::AdtDef, sp: Span, did: DefId) { + let variant_spans: Vec<_> = adt.variants.iter().map(|variant| { + tcx.hir().span_if_local(variant.def_id).unwrap() + }).collect(); + let msg = format!( + "needs exactly one variant, but has {}", + adt.variants.len(), + ); + let mut err = struct_span_err!(tcx.sess, sp, E0731, "transparent enum {}", msg); + err.span_label(sp, &msg); + if let &[ref start.., ref end] = &variant_spans[..] { + for variant_span in start { + err.span_label(*variant_span, ""); + } + err.span_label(*end, &format!("too many variants in `{}`", tcx.def_path_str(did))); + } + err.emit(); +} + +/// Emit an error when encountering more or less than one non-zero-sized field in a transparent +/// enum. +fn bad_non_zero_sized_fields<'tcx>( + tcx: TyCtxt<'tcx>, + adt: &'tcx ty::AdtDef, + field_count: usize, + field_spans: impl Iterator, + sp: Span, +) { + let msg = format!("needs exactly one non-zero-sized field, but has {}", field_count); + let mut err = struct_span_err!( + tcx.sess, + sp, + E0690, + "{}transparent {} {}", + if adt.is_enum() { "the variant of a " } else { "" }, + adt.descr(), + msg, + ); + err.span_label(sp, &msg); + for sp in field_spans { + err.span_label(sp, "this field is non-zero-sized"); + } + err.emit(); +} + +fn check_transparent(tcx: TyCtxt<'_>, sp: Span, def_id: DefId) { let adt = tcx.adt_def(def_id); if !adt.repr.transparent() { return; } + let sp = tcx.sess.source_map().def_span(sp); if adt.is_enum() { if !tcx.features().transparent_enums { - emit_feature_err(&tcx.sess.parse_sess, - sym::transparent_enums, - sp, - GateIssue::Language, - "transparent enums are unstable"); + emit_feature_err( + &tcx.sess.parse_sess, + sym::transparent_enums, + sp, + GateIssue::Language, + "transparent enums are unstable", + ); } if adt.variants.len() != 1 { - let variant_spans: Vec<_> = adt.variants.iter().map(|variant| { - tcx.hir().span_if_local(variant.def_id).unwrap() - }).collect(); - let mut err = struct_span_err!(tcx.sess, sp, E0731, - "transparent enum needs exactly one variant, but has {}", - adt.variants.len()); - if !variant_spans.is_empty() { - err.span_note(variant_spans, &format!("the following variants exist on `{}`", - tcx.def_path_str(def_id))); - } - err.emit(); + bad_variant_count(tcx, adt, sp, def_id); if adt.variants.is_empty() { // Don't bother checking the fields. No variants (and thus no fields) exist. return; @@ -1841,28 +1885,24 @@ fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, sp: Span, def_id: DefId) { (span, zst, align1) }); - let non_zst_fields = field_infos.clone().filter(|(_span, zst, _align1)| !*zst); + let non_zst_fields = field_infos.clone().filter_map(|(span, zst, _align1)| if !zst { + Some(span) + } else { + None + }); let non_zst_count = non_zst_fields.clone().count(); if non_zst_count != 1 { - let field_spans: Vec<_> = non_zst_fields.map(|(span, _zst, _align1)| span).collect(); - - let mut err = struct_span_err!(tcx.sess, sp, E0690, - "{}transparent {} needs exactly one non-zero-sized field, but has {}", - if adt.is_enum() { "the variant of a " } else { "" }, - adt.descr(), - non_zst_count); - if !field_spans.is_empty() { - err.span_note(field_spans, - &format!("the following non-zero-sized fields exist on `{}`:", - tcx.def_path_str(def_id))); - } - err.emit(); + bad_non_zero_sized_fields(tcx, adt, non_zst_count, non_zst_fields, sp); } for (span, zst, align1) in field_infos { if zst && !align1 { - span_err!(tcx.sess, span, E0691, - "zero-sized field in transparent {} has alignment larger than 1", - adt.descr()); + struct_span_err!( + tcx.sess, + span, + E0691, + "zero-sized field in transparent {} has alignment larger than 1", + adt.descr(), + ).span_label(span, "has alignment larger than 1").emit(); } } } @@ -1901,6 +1941,25 @@ pub fn check_enum<'tcx>(tcx: TyCtxt<'tcx>, sp: Span, vs: &'tcx [hir::Variant], i } } + if tcx.adt_def(def_id).repr.int.is_none() && tcx.features().arbitrary_enum_discriminant { + let is_unit = + |var: &hir::Variant| match var.node.data { + hir::VariantData::Unit(..) => true, + _ => false + }; + + let has_disr = |var: &hir::Variant| var.node.disr_expr.is_some(); + let has_non_units = vs.iter().any(|var| !is_unit(var)); + let disr_units = vs.iter().any(|var| is_unit(&var) && has_disr(&var)); + let disr_non_unit = vs.iter().any(|var| !is_unit(&var) && has_disr(&var)); + + if disr_non_unit || (disr_units && has_non_units) { + let mut err = struct_span_err!(tcx.sess, sp, E0732, + "`#[repr(inttype)]` must be specified"); + err.emit(); + } + } + let mut disr_vals: Vec> = Vec::with_capacity(vs.len()); for ((_, discr), v) in def.discriminants(tcx).zip(vs) { // Check for duplicate discriminant values @@ -1909,11 +1968,11 @@ pub fn check_enum<'tcx>(tcx: TyCtxt<'tcx>, sp: Span, vs: &'tcx [hir::Variant], i let variant_i_hir_id = tcx.hir().as_local_hir_id(variant_did).unwrap(); let variant_i = tcx.hir().expect_variant(variant_i_hir_id); let i_span = match variant_i.node.disr_expr { - Some(ref expr) => tcx.hir().span_by_hir_id(expr.hir_id), - None => tcx.hir().span_by_hir_id(variant_i_hir_id) + Some(ref expr) => tcx.hir().span(expr.hir_id), + None => tcx.hir().span(variant_i_hir_id) }; let span = match v.node.disr_expr { - Some(ref expr) => tcx.hir().span_by_hir_id(expr.hir_id), + Some(ref expr) => tcx.hir().span(expr.hir_id), None => v.span }; struct_span_err!(tcx.sess, span, E0081, @@ -1929,7 +1988,7 @@ pub fn check_enum<'tcx>(tcx: TyCtxt<'tcx>, sp: Span, vs: &'tcx [hir::Variant], i check_transparent(tcx, sp, def_id); } -fn report_unexpected_variant_res<'tcx>(tcx: TyCtxt<'tcx>, res: Res, span: Span, qpath: &QPath) { +fn report_unexpected_variant_res(tcx: TyCtxt<'_>, res: Res, span: Span, qpath: &QPath) { span_err!(tcx.sess, span, E0533, "expected unit struct/variant or constant, found {} `{}`", res.descr(), @@ -2094,8 +2153,8 @@ pub fn sess(&self) -> &Session { &self.tcx.sess } - pub fn err_count_since_creation(&self) -> usize { - self.tcx.sess.err_count() - self.err_count_on_creation + pub fn errors_reported_since_creation(&self) -> bool { + self.tcx.sess.err_count() > self.err_count_on_creation } /// Produces warning on the given node, if the current point in the @@ -2181,7 +2240,7 @@ pub fn tag(&self) -> String { pub fn local_ty(&self, span: Span, nid: hir::HirId) -> LocalTy<'tcx> { self.locals.borrow().get(&nid).cloned().unwrap_or_else(|| span_bug!(span, "no type for local variable {}", - self.tcx.hir().hir_to_string(nid)) + self.tcx.hir().node_to_string(nid)) ) } @@ -2392,6 +2451,7 @@ fn instantiate_opaque_types_from_value>( &self, parent_id: hir::HirId, value: &T, + value_span: Span, ) -> T { let parent_def_id = self.tcx.hir().local_def_id_from_hir_id(parent_id); debug!("instantiate_opaque_types_from_value(parent_def_id={:?}, value={:?})", @@ -2404,6 +2464,7 @@ fn instantiate_opaque_types_from_value>( self.body_id, self.param_env, value, + value_span, ) ); @@ -2517,9 +2578,8 @@ pub fn node_ty(&self, id: hir::HirId) -> Ty<'tcx> { Some(&t) => t, None if self.is_tainted_by_errors() => self.tcx.types.err, None => { - let node_id = self.tcx.hir().hir_to_node_id(id); bug!("no type for node {}: {} in fcx {}", - node_id, self.tcx.hir().node_to_string(node_id), + id, self.tcx.hir().node_to_string(id), self.tag()); } } @@ -3643,7 +3703,7 @@ fn check_block_with_expected( } fn parent_item_span(&self, id: hir::HirId) -> Option { - let node = self.tcx.hir().get_by_hir_id(self.tcx.hir().get_parent_item(id)); + let node = self.tcx.hir().get(self.tcx.hir().get_parent_item(id)); match node { Node::Item(&hir::Item { node: hir::ItemKind::Fn(_, _, _, body_id), .. @@ -3662,43 +3722,43 @@ fn parent_item_span(&self, id: hir::HirId) -> Option { } /// Given a function block's `HirId`, returns its `FnDecl` if it exists, or `None` otherwise. - fn get_parent_fn_decl(&self, blk_id: hir::HirId) -> Option<(hir::FnDecl, ast::Ident)> { - let parent = self.tcx.hir().get_by_hir_id(self.tcx.hir().get_parent_item(blk_id)); + fn get_parent_fn_decl(&self, blk_id: hir::HirId) -> Option<(&'tcx hir::FnDecl, ast::Ident)> { + let parent = self.tcx.hir().get(self.tcx.hir().get_parent_item(blk_id)); self.get_node_fn_decl(parent).map(|(fn_decl, ident, _)| (fn_decl, ident)) } /// Given a function `Node`, return its `FnDecl` if it exists, or `None` otherwise. - fn get_node_fn_decl(&self, node: Node<'_>) -> Option<(hir::FnDecl, ast::Ident, bool)> { + fn get_node_fn_decl(&self, node: Node<'tcx>) -> Option<(&'tcx hir::FnDecl, ast::Ident, bool)> { match node { Node::Item(&hir::Item { ident, node: hir::ItemKind::Fn(ref decl, ..), .. - }) => decl.clone().and_then(|decl| { + }) => { // This is less than ideal, it will not suggest a return type span on any // method called `main`, regardless of whether it is actually the entry point, // but it will still present it as the reason for the expected type. Some((decl, ident, ident.name != sym::main)) - }), + } Node::TraitItem(&hir::TraitItem { ident, node: hir::TraitItemKind::Method(hir::MethodSig { ref decl, .. }, ..), .. - }) => decl.clone().and_then(|decl| Some((decl, ident, true))), + }) => Some((decl, ident, true)), Node::ImplItem(&hir::ImplItem { ident, node: hir::ImplItemKind::Method(hir::MethodSig { ref decl, .. }, ..), .. - }) => decl.clone().and_then(|decl| Some((decl, ident, false))), + }) => Some((decl, ident, false)), _ => None, } } /// Given a `HirId`, return the `FnDecl` of the method it is enclosed by and whether a /// suggestion can be made, `None` otherwise. - pub fn get_fn_decl(&self, blk_id: hir::HirId) -> Option<(hir::FnDecl, bool)> { + pub fn get_fn_decl(&self, blk_id: hir::HirId) -> Option<(&'tcx hir::FnDecl, bool)> { // Get enclosing Fn, if it is a function or a trait method, unless there's a `loop` or // `while` before reaching it, as block tail returns are not available in them. self.tcx.hir().get_return_block(blk_id).and_then(|blk_id| { - let parent = self.tcx.hir().get_by_hir_id(blk_id); + let parent = self.tcx.hir().get(blk_id); self.get_node_fn_decl(parent).map(|(fn_decl, _, is_main)| (fn_decl, is_main)) }) } @@ -3880,6 +3940,72 @@ fn suggest_missing_return_type( } } + /// A possible error is to forget to add `.await` when using futures: + /// + /// ``` + /// #![feature(async_await)] + /// + /// async fn make_u32() -> u32 { + /// 22 + /// } + /// + /// fn take_u32(x: u32) {} + /// + /// async fn foo() { + /// let x = make_u32(); + /// take_u32(x); + /// } + /// ``` + /// + /// This routine checks if the found type `T` implements `Future` where `U` is the + /// expected type. If this is the case, and we are inside of an async body, it suggests adding + /// `.await` to the tail of the expression. + fn suggest_missing_await( + &self, + err: &mut DiagnosticBuilder<'tcx>, + expr: &hir::Expr, + expected: Ty<'tcx>, + found: Ty<'tcx>, + ) { + // `.await` is not permitted outside of `async` bodies, so don't bother to suggest if the + // body isn't `async`. + let item_id = self.tcx().hir().get_parent_node(self.body_id); + if let Some(body_id) = self.tcx().hir().maybe_body_owned_by(item_id) { + let body = self.tcx().hir().body(body_id); + if let Some(hir::GeneratorKind::Async) = body.generator_kind { + let sp = expr.span; + // Check for `Future` implementations by constructing a predicate to + // prove: `::Output == U` + let future_trait = self.tcx.lang_items().future_trait().unwrap(); + let item_def_id = self.tcx.associated_items(future_trait).next().unwrap().def_id; + let predicate = ty::Predicate::Projection(ty::Binder::bind(ty::ProjectionPredicate { + // `::Output` + projection_ty: ty::ProjectionTy { + // `T` + substs: self.tcx.mk_substs_trait( + found, + self.fresh_substs_for_item(sp, item_def_id) + ), + // `Future::Output` + item_def_id, + }, + ty: expected, + })); + let obligation = traits::Obligation::new(self.misc(sp), self.param_env, predicate); + if self.infcx.predicate_may_hold(&obligation) { + if let Ok(code) = self.sess().source_map().span_to_snippet(sp) { + err.span_suggestion( + sp, + "consider using `.await` here", + format!("{}.await", code), + Applicability::MaybeIncorrect, + ); + } + } + } + } + } + /// A common error is to add an extra semicolon: /// /// ``` @@ -3923,52 +4049,6 @@ fn could_remove_semicolon(&self, blk: &'tcx hir::Block, expected_ty: Ty<'tcx>) - Some(original_span.with_lo(original_span.hi() - BytePos(1))) } - // Rewrite `SelfCtor` to `Ctor` - pub fn rewrite_self_ctor( - &self, - res: Res, - span: Span, - ) -> Result { - let tcx = self.tcx; - if let Res::SelfCtor(impl_def_id) = res { - let ty = self.impl_self_ty(span, impl_def_id).ty; - let adt_def = ty.ty_adt_def(); - - match adt_def { - Some(adt_def) if adt_def.has_ctor() => { - let variant = adt_def.non_enum_variant(); - let ctor_def_id = variant.ctor_def_id.unwrap(); - Ok(Res::Def(DefKind::Ctor(CtorOf::Struct, variant.ctor_kind), ctor_def_id)) - } - _ => { - let mut err = tcx.sess.struct_span_err(span, - "the `Self` constructor can only be used with tuple or unit structs"); - if let Some(adt_def) = adt_def { - match adt_def.adt_kind() { - AdtKind::Enum => { - err.help("did you mean to use one of the enum's variants?"); - }, - AdtKind::Struct | - AdtKind::Union => { - err.span_suggestion( - span, - "use curly brackets", - String::from("Self { /* fields */ }"), - Applicability::HasPlaceholders, - ); - } - } - } - err.emit(); - - Err(ErrorReported) - } - } - } else { - Ok(res) - } - } - // Instantiates the given path, which must refer to an item with the given // number of type parameters and type. pub fn instantiate_value_path(&self, @@ -3988,12 +4068,8 @@ pub fn instantiate_value_path(&self, let tcx = self.tcx; - let res = match self.rewrite_self_ctor(res, span) { - Ok(res) => res, - Err(ErrorReported) => return (tcx.types.err, res), - }; let path_segs = match res { - Res::Local(_) => vec![], + Res::Local(_) | Res::SelfCtor(_) => vec![], Res::Def(kind, def_id) => AstConv::def_ids_for_value_path_segments(self, segments, self_ty, kind, def_id), _ => bug!("instantiate_value_path on {:?}", res), @@ -4098,13 +4174,53 @@ pub fn instantiate_value_path(&self, tcx.generics_of(*def_id).has_self }).unwrap_or(false); + let (res, self_ctor_substs) = if let Res::SelfCtor(impl_def_id) = res { + let ty = self.impl_self_ty(span, impl_def_id).ty; + let adt_def = ty.ty_adt_def(); + + match ty.sty { + ty::Adt(adt_def, substs) if adt_def.has_ctor() => { + let variant = adt_def.non_enum_variant(); + let ctor_def_id = variant.ctor_def_id.unwrap(); + ( + Res::Def(DefKind::Ctor(CtorOf::Struct, variant.ctor_kind), ctor_def_id), + Some(substs), + ) + } + _ => { + let mut err = tcx.sess.struct_span_err(span, + "the `Self` constructor can only be used with tuple or unit structs"); + if let Some(adt_def) = adt_def { + match adt_def.adt_kind() { + AdtKind::Enum => { + err.help("did you mean to use one of the enum's variants?"); + }, + AdtKind::Struct | + AdtKind::Union => { + err.span_suggestion( + span, + "use curly brackets", + String::from("Self { /* fields */ }"), + Applicability::HasPlaceholders, + ); + } + } + } + err.emit(); + + return (tcx.types.err, res) + } + } + } else { + (res, None) + }; let def_id = res.def_id(); // The things we are substituting into the type should not contain // escaping late-bound regions, and nor should the base type scheme. let ty = tcx.type_of(def_id); - let substs = AstConv::create_substs_for_generic_args( + let substs = self_ctor_substs.unwrap_or_else(|| AstConv::create_substs_for_generic_args( tcx, def_id, &[][..], @@ -4174,7 +4290,7 @@ pub fn instantiate_value_path(&self, } } }, - ); + )); assert!(!substs.has_escaping_bound_vars()); assert!(!ty.has_escaping_bound_vars()); @@ -4235,8 +4351,8 @@ fn check_rustc_args_require_const(&self, // If our calling expression is indeed the function itself, we're good! // If not, generate an error that this can only be called directly. - if let Node::Expr(expr) = self.tcx.hir().get_by_hir_id( - self.tcx.hir().get_parent_node_by_hir_id(hir_id)) + if let Node::Expr(expr) = self.tcx.hir().get( + self.tcx.hir().get_parent_node(hir_id)) { if let ExprKind::Call(ref callee, ..) = expr.node { if callee.hir_id == hir_id { @@ -4311,7 +4427,7 @@ fn expr_in_place(&self, mut expr_id: hir::HirId) -> bool { let mut contained_in_place = false; while let hir::Node::Expr(parent_expr) = - self.tcx.hir().get_by_hir_id(self.tcx.hir().get_parent_node_by_hir_id(expr_id)) + self.tcx.hir().get(self.tcx.hir().get_parent_node(expr_id)) { match &parent_expr.node { hir::ExprKind::Assign(lhs, ..) | hir::ExprKind::AssignOp(_, lhs, ..) => { @@ -4352,7 +4468,7 @@ pub fn check_bounds_are_used<'tcx>(tcx: TyCtxt<'tcx>, generics: &ty::Generics, t } else if let ty::Error = leaf_ty.sty { // If there is already another error, do not emit // an error for not using a type Parameter. - assert!(tcx.sess.err_count() > 0); + assert!(tcx.sess.has_errors()); return; } } @@ -4364,7 +4480,7 @@ pub fn check_bounds_are_used<'tcx>(tcx: TyCtxt<'tcx>, generics: &ty::Generics, t for (&used, param) in types_used.iter().zip(types) { if !used { let id = tcx.hir().as_local_hir_id(param.def_id).unwrap(); - let span = tcx.hir().span_by_hir_id(id); + let span = tcx.hir().span(id); struct_span_err!(tcx.sess, span, E0091, "type parameter `{}` is unused", param.name) .span_label(span, "unused type parameter") .emit();