diff options
| author | Hirochika Matsumoto <matsujika@gmail.com> | 2021-01-29 05:43:35 +0900 |
|---|---|---|
| committer | Hirochika Matsumoto <matsujika@gmail.com> | 2021-01-29 06:52:49 +0900 |
| commit | 9e4ed337c783fab801d8a2e37feb58974205cfa3 (patch) | |
| tree | a58f4b38e8b2646843c00772b04587560b968368 /compiler/rustc_infer/src/infer | |
| parent | e32f372c4203b2527221b313cf63b05ea178e8a9 (diff) | |
| download | rust-9e4ed337c783fab801d8a2e37feb58974205cfa3.tar.gz rust-9e4ed337c783fab801d8a2e37feb58974205cfa3.zip | |
Suggest accessing field when code compiles with it
Diffstat (limited to 'compiler/rustc_infer/src/infer')
| -rw-r--r-- | compiler/rustc_infer/src/infer/error_reporting/mod.rs | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/compiler/rustc_infer/src/infer/error_reporting/mod.rs b/compiler/rustc_infer/src/infer/error_reporting/mod.rs index c39daea0811..68ffe3cd70f 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/mod.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/mod.rs @@ -1661,6 +1661,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { debug!("exp_found {:?} terr {:?}", exp_found, terr); if let Some(exp_found) = exp_found { self.suggest_as_ref_where_appropriate(span, &exp_found, diag); + self.suggest_field_where_appropriate(cause, &exp_found, diag); self.suggest_await_on_expect_found(cause, span, &exp_found, diag); } @@ -1819,6 +1820,46 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { } } + fn suggest_field_where_appropriate( + &self, + cause: &ObligationCause<'tcx>, + exp_found: &ty::error::ExpectedFound<Ty<'tcx>>, + diag: &mut DiagnosticBuilder<'tcx>, + ) { + debug!("suggest_field_where_appropriate(cause={:?}, exp_found={:?})", cause, exp_found); + if let ty::Adt(expected_def, expected_substs) = exp_found.expected.kind() { + if expected_def.is_enum() { + return; + } + + if let Some((name, ty)) = expected_def + .non_enum_variant() + .fields + .iter() + .filter(|field| field.vis.is_accessible_from(field.did, self.tcx)) + .map(|field| (field.ident.name, field.ty(self.tcx, expected_substs))) + .inspect(|(name, ty)| { + debug!("suggest_field_where_appropriate: name={:?}, ty={:?}", name, ty) + }) + .find(|(_, ty)| ty::TyS::same_type(ty, exp_found.found)) + { + if let ObligationCauseCode::Pattern { span: Some(span), .. } = cause.code { + if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) { + diag.span_suggestion( + span, + &format!( + "you might have meant to use field `{}` of type `{}`", + name, ty + ), + format!("{}.{}", snippet, name), + Applicability::MaybeIncorrect, + ); + } + } + } + } + } + /// When encountering a case where `.as_ref()` on a `Result` or `Option` would be appropriate, /// suggests it. fn suggest_as_ref_where_appropriate( |
