mirror of
https://github.com/rust-lang/rust-analyzer
synced 2025-01-14 14:13:58 +00:00
Show pattern mismatch diagnostics
This commit is contained in:
parent
9b441b9c67
commit
fc2b395e00
8 changed files with 117 additions and 71 deletions
|
@ -771,6 +771,15 @@ impl<T> InFile<Option<T>> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl<L, R> InFile<Either<L, R>> {
|
||||||
|
pub fn transpose(self) -> Either<InFile<L>, InFile<R>> {
|
||||||
|
match self.value {
|
||||||
|
Either::Left(l) => Either::Left(InFile::new(self.file_id, l)),
|
||||||
|
Either::Right(r) => Either::Right(InFile::new(self.file_id, r)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl<'a> InFile<&'a SyntaxNode> {
|
impl<'a> InFile<&'a SyntaxNode> {
|
||||||
pub fn ancestors_with_macros(
|
pub fn ancestors_with_macros(
|
||||||
self,
|
self,
|
||||||
|
|
|
@ -389,18 +389,15 @@ impl InferenceResult {
|
||||||
pub fn type_mismatch_for_pat(&self, pat: PatId) -> Option<&TypeMismatch> {
|
pub fn type_mismatch_for_pat(&self, pat: PatId) -> Option<&TypeMismatch> {
|
||||||
self.type_mismatches.get(&pat.into())
|
self.type_mismatches.get(&pat.into())
|
||||||
}
|
}
|
||||||
|
pub fn type_mismatches(&self) -> impl Iterator<Item = (ExprOrPatId, &TypeMismatch)> {
|
||||||
|
self.type_mismatches.iter().map(|(expr_or_pat, mismatch)| (*expr_or_pat, mismatch))
|
||||||
|
}
|
||||||
pub fn expr_type_mismatches(&self) -> impl Iterator<Item = (ExprId, &TypeMismatch)> {
|
pub fn expr_type_mismatches(&self) -> impl Iterator<Item = (ExprId, &TypeMismatch)> {
|
||||||
self.type_mismatches.iter().filter_map(|(expr_or_pat, mismatch)| match *expr_or_pat {
|
self.type_mismatches.iter().filter_map(|(expr_or_pat, mismatch)| match *expr_or_pat {
|
||||||
ExprOrPatId::ExprId(expr) => Some((expr, mismatch)),
|
ExprOrPatId::ExprId(expr) => Some((expr, mismatch)),
|
||||||
_ => None,
|
_ => None,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
pub fn pat_type_mismatches(&self) -> impl Iterator<Item = (PatId, &TypeMismatch)> {
|
|
||||||
self.type_mismatches.iter().filter_map(|(expr_or_pat, mismatch)| match *expr_or_pat {
|
|
||||||
ExprOrPatId::PatId(pat) => Some((pat, mismatch)),
|
|
||||||
_ => None,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Index<ExprId> for InferenceResult {
|
impl Index<ExprId> for InferenceResult {
|
||||||
|
|
|
@ -196,12 +196,7 @@ impl<'a> InferenceContext<'a> {
|
||||||
Pat::Ref { pat, mutability } => {
|
Pat::Ref { pat, mutability } => {
|
||||||
let mutability = lower_to_chalk_mutability(*mutability);
|
let mutability = lower_to_chalk_mutability(*mutability);
|
||||||
let expectation = match expected.as_reference() {
|
let expectation = match expected.as_reference() {
|
||||||
Some((inner_ty, _lifetime, exp_mut)) => {
|
Some((inner_ty, _lifetime, exp_mut)) => inner_ty.clone(),
|
||||||
if mutability != exp_mut {
|
|
||||||
// FIXME: emit type error?
|
|
||||||
}
|
|
||||||
inner_ty.clone()
|
|
||||||
}
|
|
||||||
_ => self.result.standard_types.unknown.clone(),
|
_ => self.result.standard_types.unknown.clone(),
|
||||||
};
|
};
|
||||||
let subty = self.infer_pat(*pat, &expectation, default_bm);
|
let subty = self.infer_pat(*pat, &expectation, default_bm);
|
||||||
|
|
|
@ -191,30 +191,11 @@ fn check_impl(ra_fixture: &str, allow_none: bool, only_types: bool, display_sour
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for (pat, mismatch) in inference_result.pat_type_mismatches() {
|
for (expr_or_pat, mismatch) in inference_result.type_mismatches() {
|
||||||
let node = match pat_node(&body_source_map, pat, &db) {
|
let Some(node) = (match expr_or_pat {
|
||||||
Some(value) => value,
|
hir_def::expr::ExprOrPatId::ExprId(expr) => expr_node(&body_source_map, expr, &db),
|
||||||
None => continue,
|
hir_def::expr::ExprOrPatId::PatId(pat) => pat_node(&body_source_map, pat, &db),
|
||||||
};
|
}) else { continue; };
|
||||||
let range = node.as_ref().original_file_range(&db);
|
|
||||||
let actual = format!(
|
|
||||||
"expected {}, got {}",
|
|
||||||
mismatch.expected.display_test(&db),
|
|
||||||
mismatch.actual.display_test(&db)
|
|
||||||
);
|
|
||||||
match mismatches.remove(&range) {
|
|
||||||
Some(annotation) => assert_eq!(actual, annotation),
|
|
||||||
None => format_to!(unexpected_type_mismatches, "{:?}: {}\n", range.range, actual),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (expr, mismatch) in inference_result.expr_type_mismatches() {
|
|
||||||
let node = match body_source_map.expr_syntax(expr) {
|
|
||||||
Ok(sp) => {
|
|
||||||
let root = db.parse_or_expand(sp.file_id).unwrap();
|
|
||||||
sp.map(|ptr| ptr.to_node(&root).syntax().clone())
|
|
||||||
}
|
|
||||||
Err(SyntheticSyntax) => continue,
|
|
||||||
};
|
|
||||||
let range = node.as_ref().original_file_range(&db);
|
let range = node.as_ref().original_file_range(&db);
|
||||||
let actual = format!(
|
let actual = format!(
|
||||||
"expected {}, got {}",
|
"expected {}, got {}",
|
||||||
|
|
|
@ -1092,3 +1092,19 @@ fn my_fn(foo: ...) {}
|
||||||
"#,
|
"#,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ref_pat_mutability() {
|
||||||
|
check(
|
||||||
|
r#"
|
||||||
|
fn foo() {
|
||||||
|
let &() = &();
|
||||||
|
let &mut () = &mut ();
|
||||||
|
let &mut () = &();
|
||||||
|
//^^^^^^^ expected &(), got &mut ()
|
||||||
|
let &() = &mut ();
|
||||||
|
//^^^ expected &mut (), got &()
|
||||||
|
}
|
||||||
|
"#,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
|
@ -178,8 +178,7 @@ pub struct MissingMatchArms {
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct TypeMismatch {
|
pub struct TypeMismatch {
|
||||||
// FIXME: add mismatches in patterns as well
|
pub expr_or_pat: Either<InFile<AstPtr<ast::Expr>>, InFile<AstPtr<ast::Pat>>>,
|
||||||
pub expr: InFile<AstPtr<ast::Expr>>,
|
|
||||||
pub expected: Type,
|
pub expected: Type,
|
||||||
pub actual: Type,
|
pub actual: Type,
|
||||||
}
|
}
|
||||||
|
|
|
@ -1413,14 +1413,22 @@ impl DefWithBody {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (expr, mismatch) in infer.expr_type_mismatches() {
|
for (pat_or_expr, mismatch) in infer.type_mismatches() {
|
||||||
let expr = match source_map.expr_syntax(expr) {
|
let expr_or_pat = match pat_or_expr {
|
||||||
Ok(expr) => expr,
|
ExprOrPatId::ExprId(expr) => source_map.expr_syntax(expr).map(Either::Left),
|
||||||
Err(SyntheticSyntax) => continue,
|
ExprOrPatId::PatId(pat) => source_map.pat_syntax(pat).map(Either::Right),
|
||||||
};
|
};
|
||||||
|
let expr_or_pat = match expr_or_pat {
|
||||||
|
Ok(Either::Left(expr)) => Either::Left(expr),
|
||||||
|
Ok(Either::Right(InFile { file_id, value: Either::Left(pat) })) => {
|
||||||
|
Either::Right(InFile { file_id, value: pat })
|
||||||
|
}
|
||||||
|
Ok(Either::Right(_)) | Err(SyntheticSyntax) => continue,
|
||||||
|
};
|
||||||
|
|
||||||
acc.push(
|
acc.push(
|
||||||
TypeMismatch {
|
TypeMismatch {
|
||||||
expr,
|
expr_or_pat,
|
||||||
expected: Type::new(db, DefWithBodyId::from(self), mismatch.expected.clone()),
|
expected: Type::new(db, DefWithBodyId::from(self), mismatch.expected.clone()),
|
||||||
actual: Type::new(db, DefWithBodyId::from(self), mismatch.actual.clone()),
|
actual: Type::new(db, DefWithBodyId::from(self), mismatch.actual.clone()),
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,8 +1,9 @@
|
||||||
use hir::{db::AstDatabase, HirDisplay, Type};
|
use either::Either;
|
||||||
|
use hir::{db::AstDatabase, HirDisplay, InFile, Type};
|
||||||
use ide_db::{famous_defs::FamousDefs, source_change::SourceChange};
|
use ide_db::{famous_defs::FamousDefs, source_change::SourceChange};
|
||||||
use syntax::{
|
use syntax::{
|
||||||
ast::{self, BlockExpr, ExprStmt},
|
ast::{self, BlockExpr, ExprStmt},
|
||||||
AstNode,
|
AstNode, AstPtr,
|
||||||
};
|
};
|
||||||
use text_edit::TextEdit;
|
use text_edit::TextEdit;
|
||||||
|
|
||||||
|
@ -10,19 +11,23 @@ use crate::{adjusted_display_range, fix, Assist, Diagnostic, DiagnosticsContext}
|
||||||
|
|
||||||
// Diagnostic: type-mismatch
|
// Diagnostic: type-mismatch
|
||||||
//
|
//
|
||||||
// This diagnostic is triggered when the type of an expression does not match
|
// This diagnostic is triggered when the type of an expression or pattern does not match
|
||||||
// the expected type.
|
// the expected type.
|
||||||
pub(crate) fn type_mismatch(ctx: &DiagnosticsContext<'_>, d: &hir::TypeMismatch) -> Diagnostic {
|
pub(crate) fn type_mismatch(ctx: &DiagnosticsContext<'_>, d: &hir::TypeMismatch) -> Diagnostic {
|
||||||
let display_range = adjusted_display_range::<ast::BlockExpr>(
|
let display_range = match &d.expr_or_pat {
|
||||||
ctx,
|
Either::Left(expr) => adjusted_display_range::<ast::BlockExpr>(
|
||||||
d.expr.clone().map(|it| it.into()),
|
ctx,
|
||||||
&|block| {
|
expr.clone().map(|it| it.into()),
|
||||||
let r_curly_range = block.stmt_list()?.r_curly_token()?.text_range();
|
&|block| {
|
||||||
cov_mark::hit!(type_mismatch_on_block);
|
let r_curly_range = block.stmt_list()?.r_curly_token()?.text_range();
|
||||||
Some(r_curly_range)
|
cov_mark::hit!(type_mismatch_on_block);
|
||||||
},
|
Some(r_curly_range)
|
||||||
);
|
},
|
||||||
|
),
|
||||||
|
Either::Right(pat) => {
|
||||||
|
ctx.sema.diagnostics_display_range(pat.clone().map(|it| it.into())).range
|
||||||
|
}
|
||||||
|
};
|
||||||
let mut diag = Diagnostic::new(
|
let mut diag = Diagnostic::new(
|
||||||
"type-mismatch",
|
"type-mismatch",
|
||||||
format!(
|
format!(
|
||||||
|
@ -42,10 +47,15 @@ pub(crate) fn type_mismatch(ctx: &DiagnosticsContext<'_>, d: &hir::TypeMismatch)
|
||||||
fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::TypeMismatch) -> Option<Vec<Assist>> {
|
fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::TypeMismatch) -> Option<Vec<Assist>> {
|
||||||
let mut fixes = Vec::new();
|
let mut fixes = Vec::new();
|
||||||
|
|
||||||
add_reference(ctx, d, &mut fixes);
|
match &d.expr_or_pat {
|
||||||
add_missing_ok_or_some(ctx, d, &mut fixes);
|
Either::Left(expr_ptr) => {
|
||||||
remove_semicolon(ctx, d, &mut fixes);
|
add_reference(ctx, d, expr_ptr, &mut fixes);
|
||||||
str_ref_to_owned(ctx, d, &mut fixes);
|
add_missing_ok_or_some(ctx, d, expr_ptr, &mut fixes);
|
||||||
|
remove_semicolon(ctx, d, expr_ptr, &mut fixes);
|
||||||
|
str_ref_to_owned(ctx, d, expr_ptr, &mut fixes);
|
||||||
|
}
|
||||||
|
Either::Right(_pat_ptr) => (),
|
||||||
|
}
|
||||||
|
|
||||||
if fixes.is_empty() {
|
if fixes.is_empty() {
|
||||||
None
|
None
|
||||||
|
@ -53,13 +63,22 @@ fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::TypeMismatch) -> Option<Vec<Assi
|
||||||
Some(fixes)
|
Some(fixes)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
fn add_reference_pat(
|
||||||
|
ctx: &DiagnosticsContext<'_>,
|
||||||
|
d: &hir::TypeMismatch,
|
||||||
|
expr_ptr: &InFile<AstPtr<ast::Pat>>,
|
||||||
|
acc: &mut Vec<Assist>,
|
||||||
|
) -> Option<()> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
fn add_reference(
|
fn add_reference(
|
||||||
ctx: &DiagnosticsContext<'_>,
|
ctx: &DiagnosticsContext<'_>,
|
||||||
d: &hir::TypeMismatch,
|
d: &hir::TypeMismatch,
|
||||||
|
expr_ptr: &InFile<AstPtr<ast::Expr>>,
|
||||||
acc: &mut Vec<Assist>,
|
acc: &mut Vec<Assist>,
|
||||||
) -> Option<()> {
|
) -> Option<()> {
|
||||||
let range = ctx.sema.diagnostics_display_range(d.expr.clone().map(|it| it.into())).range;
|
let range = ctx.sema.diagnostics_display_range(expr_ptr.clone().map(|it| it.into())).range;
|
||||||
|
|
||||||
let (_, mutability) = d.expected.as_reference()?;
|
let (_, mutability) = d.expected.as_reference()?;
|
||||||
let actual_with_ref = Type::reference(&d.actual, mutability);
|
let actual_with_ref = Type::reference(&d.actual, mutability);
|
||||||
|
@ -71,7 +90,7 @@ fn add_reference(
|
||||||
|
|
||||||
let edit = TextEdit::insert(range.start(), ampersands);
|
let edit = TextEdit::insert(range.start(), ampersands);
|
||||||
let source_change =
|
let source_change =
|
||||||
SourceChange::from_text_edit(d.expr.file_id.original_file(ctx.sema.db), edit);
|
SourceChange::from_text_edit(expr_ptr.file_id.original_file(ctx.sema.db), edit);
|
||||||
acc.push(fix("add_reference_here", "Add reference here", source_change, range));
|
acc.push(fix("add_reference_here", "Add reference here", source_change, range));
|
||||||
Some(())
|
Some(())
|
||||||
}
|
}
|
||||||
|
@ -79,10 +98,11 @@ fn add_reference(
|
||||||
fn add_missing_ok_or_some(
|
fn add_missing_ok_or_some(
|
||||||
ctx: &DiagnosticsContext<'_>,
|
ctx: &DiagnosticsContext<'_>,
|
||||||
d: &hir::TypeMismatch,
|
d: &hir::TypeMismatch,
|
||||||
|
expr_ptr: &InFile<AstPtr<ast::Expr>>,
|
||||||
acc: &mut Vec<Assist>,
|
acc: &mut Vec<Assist>,
|
||||||
) -> Option<()> {
|
) -> Option<()> {
|
||||||
let root = ctx.sema.db.parse_or_expand(d.expr.file_id)?;
|
let root = ctx.sema.db.parse_or_expand(expr_ptr.file_id)?;
|
||||||
let expr = d.expr.value.to_node(&root);
|
let expr = expr_ptr.value.to_node(&root);
|
||||||
let expr_range = expr.syntax().text_range();
|
let expr_range = expr.syntax().text_range();
|
||||||
let scope = ctx.sema.scope(expr.syntax())?;
|
let scope = ctx.sema.scope(expr.syntax())?;
|
||||||
|
|
||||||
|
@ -109,7 +129,7 @@ fn add_missing_ok_or_some(
|
||||||
builder.insert(expr.syntax().text_range().start(), format!("{variant_name}("));
|
builder.insert(expr.syntax().text_range().start(), format!("{variant_name}("));
|
||||||
builder.insert(expr.syntax().text_range().end(), ")".to_string());
|
builder.insert(expr.syntax().text_range().end(), ")".to_string());
|
||||||
let source_change =
|
let source_change =
|
||||||
SourceChange::from_text_edit(d.expr.file_id.original_file(ctx.sema.db), builder.finish());
|
SourceChange::from_text_edit(expr_ptr.file_id.original_file(ctx.sema.db), builder.finish());
|
||||||
let name = format!("Wrap in {variant_name}");
|
let name = format!("Wrap in {variant_name}");
|
||||||
acc.push(fix("wrap_in_constructor", &name, source_change, expr_range));
|
acc.push(fix("wrap_in_constructor", &name, source_change, expr_range));
|
||||||
Some(())
|
Some(())
|
||||||
|
@ -118,10 +138,11 @@ fn add_missing_ok_or_some(
|
||||||
fn remove_semicolon(
|
fn remove_semicolon(
|
||||||
ctx: &DiagnosticsContext<'_>,
|
ctx: &DiagnosticsContext<'_>,
|
||||||
d: &hir::TypeMismatch,
|
d: &hir::TypeMismatch,
|
||||||
|
expr_ptr: &InFile<AstPtr<ast::Expr>>,
|
||||||
acc: &mut Vec<Assist>,
|
acc: &mut Vec<Assist>,
|
||||||
) -> Option<()> {
|
) -> Option<()> {
|
||||||
let root = ctx.sema.db.parse_or_expand(d.expr.file_id)?;
|
let root = ctx.sema.db.parse_or_expand(expr_ptr.file_id)?;
|
||||||
let expr = d.expr.value.to_node(&root);
|
let expr = expr_ptr.value.to_node(&root);
|
||||||
if !d.actual.is_unit() {
|
if !d.actual.is_unit() {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
|
@ -136,7 +157,7 @@ fn remove_semicolon(
|
||||||
|
|
||||||
let edit = TextEdit::delete(semicolon_range);
|
let edit = TextEdit::delete(semicolon_range);
|
||||||
let source_change =
|
let source_change =
|
||||||
SourceChange::from_text_edit(d.expr.file_id.original_file(ctx.sema.db), edit);
|
SourceChange::from_text_edit(expr_ptr.file_id.original_file(ctx.sema.db), edit);
|
||||||
|
|
||||||
acc.push(fix("remove_semicolon", "Remove this semicolon", source_change, semicolon_range));
|
acc.push(fix("remove_semicolon", "Remove this semicolon", source_change, semicolon_range));
|
||||||
Some(())
|
Some(())
|
||||||
|
@ -145,24 +166,26 @@ fn remove_semicolon(
|
||||||
fn str_ref_to_owned(
|
fn str_ref_to_owned(
|
||||||
ctx: &DiagnosticsContext<'_>,
|
ctx: &DiagnosticsContext<'_>,
|
||||||
d: &hir::TypeMismatch,
|
d: &hir::TypeMismatch,
|
||||||
|
expr_ptr: &InFile<AstPtr<ast::Expr>>,
|
||||||
acc: &mut Vec<Assist>,
|
acc: &mut Vec<Assist>,
|
||||||
) -> Option<()> {
|
) -> Option<()> {
|
||||||
let expected = d.expected.display(ctx.sema.db);
|
let expected = d.expected.display(ctx.sema.db);
|
||||||
let actual = d.actual.display(ctx.sema.db);
|
let actual = d.actual.display(ctx.sema.db);
|
||||||
|
|
||||||
|
// FIXME do this properly
|
||||||
if expected.to_string() != "String" || actual.to_string() != "&str" {
|
if expected.to_string() != "String" || actual.to_string() != "&str" {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
|
|
||||||
let root = ctx.sema.db.parse_or_expand(d.expr.file_id)?;
|
let root = ctx.sema.db.parse_or_expand(expr_ptr.file_id)?;
|
||||||
let expr = d.expr.value.to_node(&root);
|
let expr = expr_ptr.value.to_node(&root);
|
||||||
let expr_range = expr.syntax().text_range();
|
let expr_range = expr.syntax().text_range();
|
||||||
|
|
||||||
let to_owned = format!(".to_owned()");
|
let to_owned = format!(".to_owned()");
|
||||||
|
|
||||||
let edit = TextEdit::insert(expr.syntax().text_range().end(), to_owned);
|
let edit = TextEdit::insert(expr.syntax().text_range().end(), to_owned);
|
||||||
let source_change =
|
let source_change =
|
||||||
SourceChange::from_text_edit(d.expr.file_id.original_file(ctx.sema.db), edit);
|
SourceChange::from_text_edit(expr_ptr.file_id.original_file(ctx.sema.db), edit);
|
||||||
acc.push(fix("str_ref_to_owned", "Add .to_owned() here", source_change, expr_range));
|
acc.push(fix("str_ref_to_owned", "Add .to_owned() here", source_change, expr_range));
|
||||||
|
|
||||||
Some(())
|
Some(())
|
||||||
|
@ -592,6 +615,24 @@ fn f() -> i32 {
|
||||||
let _ = x + y;
|
let _ = x + y;
|
||||||
}
|
}
|
||||||
//^ error: expected i32, found ()
|
//^ error: expected i32, found ()
|
||||||
|
"#,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn type_mismatch_pat_smoke_test() {
|
||||||
|
check_diagnostics(
|
||||||
|
r#"
|
||||||
|
fn f() {
|
||||||
|
let &() = &mut ();
|
||||||
|
//^^^ error: expected &mut (), found &()
|
||||||
|
match &() {
|
||||||
|
&9 => ()
|
||||||
|
//^^ error: expected &(), found &i32
|
||||||
|
//^ error: expected (), found i32
|
||||||
|
//^ error: expected (), found i32
|
||||||
|
}
|
||||||
|
}
|
||||||
"#,
|
"#,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue