Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proper error message for non exhaustive match #1772

Merged
merged 1 commit into from
Jan 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions cli/tests/snapshot/inputs/errors/non_exhaustive_match.ncl
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# capture = 'stderr'
# command = ['eval']

# Ensure that a non-exhaustive pattern matching applied to a non-matching
# argument produces a proper error message.
let x = if true then 'a else 'b in
let f = match {
'c => "hello",
'd => "adios",
}
in

f x
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
---
source: cli/tests/snapshot/main.rs
expression: err
---
error: non-exhaustive pattern matching
┌─ [INPUTS_PATH]/errors/non_exhaustive_match.ncl:7:9
6 │ let x = if true then 'a else 'b in
│ -- this value doesn't match any branch
7 │ let f = match {
│ ╭─────────^
8 │ │ 'c => "hello",
9 │ │ 'd => "adios",
10 │ │ }
│ ╰─^ in this match expression
= This match expression isn't exhaustive, matching only the following pattern(s): `'c, 'd`
= But it has been applied to an argument which doesn't match any of those patterns


44 changes: 43 additions & 1 deletion core/src/error/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ use crate::{
position::{RawSpan, TermPos},
repl,
serialize::ExportFormat,
term::{record::FieldMetadata, Number, RichTerm},
term::{record::FieldMetadata, Number, RichTerm, Term},
typ::{Type, TypeF, VarKindDiscriminant},
};

Expand Down Expand Up @@ -148,6 +148,15 @@ pub enum EvalError {
},
/// A non-equatable term was compared for equality.
EqError { eq_pos: TermPos, term: RichTerm },
/// A value didn't match any branch of a `match` expression at runtime.
NonExhaustiveMatch {
/// The list of expected patterns. Currently, those are just enum tags.
expected: Vec<LocIdent>,
/// The original term matched
found: RichTerm,
/// The position of the `match` expression
pos: TermPos,
},
/// Tried to query a field of something that wasn't a record.
QueryNonRecord {
/// Position of the original unevaluated expression.
Expand Down Expand Up @@ -1241,6 +1250,39 @@ impl IntoDiagnostics<FileId> for EvalError {
.with_message("cannot compare values for equality")
.with_labels(labels)]
}
EvalError::NonExhaustiveMatch {
expected,
found,
pos,
} => {
let tag_list = expected
.into_iter()
.map(|tag| {
// We let the pretty printer handle proper formatting
RichTerm::from(Term::Enum(tag)).to_string()
})
.collect::<Vec<_>>()
.join(", ");

let mut labels = Vec::new();

if let Some(span) = pos.into_opt() {
labels.push(primary(&span).with_message("in this match expression"));
}

labels.push(
secondary_term(&found, files)
.with_message("this value doesn't match any branch"),
);

vec![Diagnostic::error()
.with_message("non-exhaustive pattern matching")
.with_labels(labels)
.with_notes(vec![
format!("This match expression isn't exhaustive, matching only the following pattern(s): `{tag_list}`"),
"But it has been applied to an argument which doesn't match any of those patterns".to_owned(),
])]
}
EvalError::IllegalPolymorphicTailAccess {
action,
label: contract_label,
Expand Down
9 changes: 6 additions & 3 deletions core/src/eval/operation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,7 @@ impl<R: ImportResolver, C: Cache> VirtualMachine<R, C> {
.stack
.pop_arg(&self.cache)
.expect("missing arg for match");

let default = if has_default {
Some(
self.stack
Expand Down Expand Up @@ -351,9 +352,11 @@ impl<R: ImportResolver, C: Cache> VirtualMachine<R, C> {
env: cases_env,
})
.or(default)
.ok_or_else(||
// ? We should have a dedicated error for unmatched pattern
mk_type_error!("match", "Enum"))
.ok_or_else(|| EvalError::NonExhaustiveMatch {
expected: cases.keys().copied().collect(),
found: RichTerm::new(Term::Enum(*en), pos),
pos: pos_op_inh,
})
} else if let Some(clos) = default {
Ok(clos)
} else {
Expand Down
Loading