Rework all errors to provide better help text.
This commit is contained in:
parent
c47c50ffb8
commit
69f060e675
|
@ -80,6 +80,7 @@ dependencies = [
|
|||
"itertools",
|
||||
"miette",
|
||||
"ordinal",
|
||||
"owo-colors",
|
||||
"pretty_assertions",
|
||||
"strum",
|
||||
"thiserror",
|
||||
|
|
|
@ -13,9 +13,11 @@ authors = ["Lucas Rosa <x@rvcas.dev>", "Kasey White <kwhitemsg@gmail.com>"]
|
|||
[dependencies]
|
||||
chumsky = "0.8.0"
|
||||
indexmap = "1.9.1"
|
||||
indoc = "1.0.7"
|
||||
itertools = "0.10.5"
|
||||
miette = "5.2.0"
|
||||
ordinal = "0.3.2"
|
||||
owo-colors = "3.5.0"
|
||||
strum = "0.24.1"
|
||||
thiserror = "1.0.37"
|
||||
uplc = { path = '../uplc', version = "0.0.25" }
|
||||
|
|
|
@ -488,7 +488,7 @@ impl<'comments> Formatter<'comments> {
|
|||
.group()
|
||||
}
|
||||
|
||||
fn type_arguments<'a>(&mut self, args: &'a [Annotation]) -> Document<'a> {
|
||||
pub fn type_arguments<'a>(&mut self, args: &'a [Annotation]) -> Document<'a> {
|
||||
wrap_generics(args.iter().map(|t| self.annotation(t)))
|
||||
}
|
||||
|
||||
|
|
|
@ -80,21 +80,12 @@ impl<T: Into<Pattern>> chumsky::Error<T> for ParseError {
|
|||
|
||||
#[derive(Debug, PartialEq, Eq, Diagnostic, thiserror::Error)]
|
||||
pub enum ErrorKind {
|
||||
#[error("Unexpected end")]
|
||||
#[error("I arrived at the end of the file unexpectedly.")]
|
||||
UnexpectedEnd,
|
||||
#[error("{0}")]
|
||||
#[diagnostic(help("{}", .0.help().unwrap_or_else(|| Box::new(""))))]
|
||||
Unexpected(Pattern),
|
||||
#[error("Unclosed {start}")]
|
||||
Unclosed {
|
||||
start: Pattern,
|
||||
#[label]
|
||||
before_span: Span,
|
||||
before: Option<Pattern>,
|
||||
},
|
||||
#[error("No end branch")]
|
||||
NoEndBranch,
|
||||
#[error("Invalid tuple index")]
|
||||
#[error("I discovered an invalid tuple index.")]
|
||||
#[diagnostic()]
|
||||
InvalidTupleIndex {
|
||||
#[help]
|
||||
|
@ -104,39 +95,39 @@ pub enum ErrorKind {
|
|||
|
||||
#[derive(Debug, PartialEq, Eq, Hash, Diagnostic, thiserror::Error)]
|
||||
pub enum Pattern {
|
||||
#[error("Unexpected {0:?}")]
|
||||
#[diagnostic(help("Try removing it"))]
|
||||
#[error("I found an unexpected char '{0:?}'.")]
|
||||
#[diagnostic(help("Try removing it!"))]
|
||||
Char(char),
|
||||
#[error("Unexpected {0}")]
|
||||
#[diagnostic(help("Try removing it"))]
|
||||
#[error("I found an unexpected token '{0}'.")]
|
||||
#[diagnostic(help("Try removing it!"))]
|
||||
Token(Token),
|
||||
#[error("Unexpected literal")]
|
||||
#[diagnostic(help("Try removing it"))]
|
||||
#[error("I found an unexpected literal value.")]
|
||||
#[diagnostic(help("Try removing it!"))]
|
||||
Literal,
|
||||
#[error("Unexpected type name")]
|
||||
#[diagnostic(help("Try removing it"))]
|
||||
#[error("I found an unexpected type name.")]
|
||||
#[diagnostic(help("Try removing it!"))]
|
||||
TypeIdent,
|
||||
#[error("Unexpected indentifier")]
|
||||
#[diagnostic(help("Try removing it"))]
|
||||
#[error("I found an unexpected indentifier.")]
|
||||
#[diagnostic(help("Try removing it!"))]
|
||||
TermIdent,
|
||||
#[error("Unexpected end of input")]
|
||||
#[error("I found an unexpected end of input.")]
|
||||
End,
|
||||
#[error("Malformed list spread pattern")]
|
||||
#[diagnostic(help("List spread in matches can\nuse have a discard or var"))]
|
||||
#[error("I found a malformed list spread pattern.")]
|
||||
#[diagnostic(help("List spread in matches can use a discard '_' or var."))]
|
||||
Match,
|
||||
#[error("Malformed byte literal")]
|
||||
#[diagnostic(help("Bytes must be between 0-255"))]
|
||||
#[error("I found an out-of-bound byte literal.")]
|
||||
#[diagnostic(help("Bytes must be between 0-255."))]
|
||||
Byte,
|
||||
#[error("Unexpected pattern")]
|
||||
#[error("I found an unexpected pattern.")]
|
||||
#[diagnostic(help(
|
||||
"If no label is provided then only variables\nmatching a field name are allowed"
|
||||
"If no label is provided then only variables\nmatching a field name are allowed."
|
||||
))]
|
||||
RecordPunning,
|
||||
#[error("Unexpected label")]
|
||||
#[diagnostic(help("You can only use labels with curly braces"))]
|
||||
#[error("I found an unexpected label.")]
|
||||
#[diagnostic(help("You can only use labels surrounded by curly braces"))]
|
||||
Label,
|
||||
#[error("Unexpected hole")]
|
||||
#[diagnostic(help("You can only use capture syntax with functions not constructors"))]
|
||||
#[error("I found an unexpected discard '_'.")]
|
||||
#[diagnostic(help("You can only use capture syntax with functions not constructors."))]
|
||||
Discard,
|
||||
}
|
||||
|
||||
|
|
|
@ -146,10 +146,9 @@ impl<'a> Environment<'a> {
|
|||
|
||||
if let Type::Fn { args, ret } = tipo.deref() {
|
||||
return if args.len() != arity {
|
||||
Err(Error::IncorrectArity {
|
||||
Err(Error::IncorrectFunctionCallArity {
|
||||
expected: args.len(),
|
||||
given: arity,
|
||||
labels: vec![],
|
||||
location: call_location,
|
||||
})
|
||||
} else {
|
||||
|
@ -315,8 +314,10 @@ impl<'a> Environment<'a> {
|
|||
location: Span,
|
||||
) -> Result<&ValueConstructor, Error> {
|
||||
match module {
|
||||
None => self.scope.get(name).ok_or_else(|| {
|
||||
Error::unknown_variable_or_type(location, name, self.local_value_names())
|
||||
None => self.scope.get(name).ok_or_else(|| Error::UnknownVariable {
|
||||
location,
|
||||
name: name.to_string(),
|
||||
variables: self.local_value_names(),
|
||||
}),
|
||||
|
||||
Some(m) => {
|
||||
|
@ -770,13 +771,21 @@ impl<'a> Environment<'a> {
|
|||
};
|
||||
} else if !value_imported {
|
||||
// Error if no type or value was found with that name
|
||||
return Err(Error::unknown_module_field(
|
||||
*location,
|
||||
name.clone(),
|
||||
module.join("/"),
|
||||
module_info.values.keys().map(|t| t.to_string()).collect(),
|
||||
module_info.types.keys().map(|t| t.to_string()).collect(),
|
||||
));
|
||||
return Err(Error::UnknownModuleField {
|
||||
location: *location,
|
||||
name: name.clone(),
|
||||
module_name: module.join("/"),
|
||||
value_constructors: module_info
|
||||
.values
|
||||
.keys()
|
||||
.map(|t| t.to_string())
|
||||
.collect(),
|
||||
type_constructors: module_info
|
||||
.types
|
||||
.keys()
|
||||
.map(|t| t.to_string())
|
||||
.collect(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -999,10 +1008,10 @@ impl<'a> Environment<'a> {
|
|||
self.ungeneralised_functions.insert(name.to_string());
|
||||
|
||||
// Create the field map so we can reorder labels for usage of this function
|
||||
let mut field_map = FieldMap::new(args.len());
|
||||
let mut field_map = FieldMap::new(args.len(), true);
|
||||
|
||||
for (i, arg) in args.iter().enumerate() {
|
||||
field_map.insert(arg.arg_name.get_label().clone(), i, location)?;
|
||||
field_map.insert(arg.arg_name.get_label().clone(), i, &arg.location)?;
|
||||
}
|
||||
let field_map = field_map.into_option();
|
||||
|
||||
|
@ -1067,7 +1076,6 @@ impl<'a> Environment<'a> {
|
|||
}
|
||||
|
||||
Definition::DataType(DataType {
|
||||
location,
|
||||
public,
|
||||
opaque,
|
||||
name,
|
||||
|
@ -1105,14 +1113,17 @@ impl<'a> Environment<'a> {
|
|||
for constructor in constructors {
|
||||
assert_unique_value_name(names, &constructor.name, &constructor.location)?;
|
||||
|
||||
let mut field_map = FieldMap::new(constructor.arguments.len());
|
||||
let mut field_map = FieldMap::new(constructor.arguments.len(), false);
|
||||
|
||||
let mut args_types = Vec::with_capacity(constructor.arguments.len());
|
||||
|
||||
for (
|
||||
i,
|
||||
RecordConstructorArg {
|
||||
label, annotation, ..
|
||||
label,
|
||||
annotation,
|
||||
location,
|
||||
..
|
||||
},
|
||||
) in constructor.arguments.iter().enumerate()
|
||||
{
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -112,7 +112,7 @@ impl<'a, 'b> ExprTyper<'a, 'b> {
|
|||
|
||||
// The fun has no field map and so we error if arguments have been labelled
|
||||
None => assert_no_labeled_arguments(&args)
|
||||
.map(|(location, label)| Err(Error::unexpected_labeled_arg(location, label)))
|
||||
.map(|(location, label)| Err(Error::UnexpectedLabeledArg { location, label }))
|
||||
.unwrap_or(Ok(()))?,
|
||||
}
|
||||
|
||||
|
@ -501,7 +501,7 @@ impl<'a, 'b> ExprTyper<'a, 'b> {
|
|||
None => {
|
||||
panic!("Failed to lookup record field after successfully inferring that field",)
|
||||
}
|
||||
Some(p) => arguments.push(TypedRecordUpdateArg {
|
||||
Some((p, _)) => arguments.push(TypedRecordUpdateArg {
|
||||
location,
|
||||
label: label.to_string(),
|
||||
value,
|
||||
|
@ -1354,7 +1354,7 @@ impl<'a, 'b> ExprTyper<'a, 'b> {
|
|||
// The fun has no field map and so we error if arguments have been labelled
|
||||
None => assert_no_labeled_arguments(&args)
|
||||
.map(|(location, label)| {
|
||||
Err(Error::unexpected_labeled_arg(location, label))
|
||||
Err(Error::UnexpectedLabeledArg { location, label })
|
||||
})
|
||||
.unwrap_or(Ok(()))?,
|
||||
}
|
||||
|
@ -1729,7 +1729,10 @@ impl<'a, 'b> ExprTyper<'a, 'b> {
|
|||
Ok(elems[index].clone())
|
||||
}
|
||||
}
|
||||
_ => Err(Error::NotATuple { location }),
|
||||
_ => Err(Error::NotATuple {
|
||||
location,
|
||||
tipo: tuple.tipo(),
|
||||
}),
|
||||
}?;
|
||||
|
||||
Ok(TypedExpr::TupleIndex {
|
||||
|
@ -1787,12 +1790,10 @@ impl<'a, 'b> ExprTyper<'a, 'b> {
|
|||
self.environment
|
||||
.get_variable(name)
|
||||
.cloned()
|
||||
.ok_or_else(|| {
|
||||
Error::unknown_variable_or_type(
|
||||
*location,
|
||||
name,
|
||||
self.environment.local_value_names(),
|
||||
)
|
||||
.ok_or_else(|| Error::UnknownVariable {
|
||||
location: *location,
|
||||
name: name.to_string(),
|
||||
variables: self.environment.local_value_names(),
|
||||
})?;
|
||||
|
||||
// Note whether we are using an ungeneralised function so that we can
|
||||
|
|
|
@ -8,23 +8,34 @@ use crate::ast::{CallArg, Span};
|
|||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct FieldMap {
|
||||
pub arity: usize,
|
||||
pub fields: HashMap<String, usize>,
|
||||
pub fields: HashMap<String, (usize, Span)>,
|
||||
pub is_function: bool,
|
||||
}
|
||||
|
||||
impl FieldMap {
|
||||
pub fn new(arity: usize) -> Self {
|
||||
pub fn new(arity: usize, is_function: bool) -> Self {
|
||||
Self {
|
||||
arity,
|
||||
fields: HashMap::new(),
|
||||
is_function,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn insert(&mut self, label: String, index: usize, location: &Span) -> Result<(), Error> {
|
||||
match self.fields.insert(label.clone(), index) {
|
||||
Some(_) => Err(Error::DuplicateField {
|
||||
label,
|
||||
location: *location,
|
||||
}),
|
||||
match self.fields.insert(label.clone(), (index, *location)) {
|
||||
Some((_, location_other)) => {
|
||||
if self.is_function {
|
||||
Err(Error::DuplicateArgument {
|
||||
label,
|
||||
locations: vec![*location, location_other],
|
||||
})
|
||||
} else {
|
||||
Err(Error::DuplicateField {
|
||||
label,
|
||||
locations: vec![*location, location_other],
|
||||
})
|
||||
}
|
||||
}
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
@ -40,12 +51,12 @@ impl FieldMap {
|
|||
/// Reorder an argument list so that labelled fields supplied out-of-order are
|
||||
/// in the correct order.
|
||||
pub fn reorder<A>(&self, args: &mut [CallArg<A>], location: Span) -> Result<(), Error> {
|
||||
let mut labeled_arguments_given = false;
|
||||
let mut last_labeled_arguments_given: Option<&CallArg<A>> = None;
|
||||
let mut seen_labels = std::collections::HashSet::new();
|
||||
let mut unknown_labels = Vec::new();
|
||||
|
||||
if self.arity != args.len() {
|
||||
return Err(Error::IncorrectArity {
|
||||
return Err(Error::IncorrectFieldsArity {
|
||||
labels: self.incorrect_arity_labels(args),
|
||||
location,
|
||||
expected: self.arity,
|
||||
|
@ -56,13 +67,14 @@ impl FieldMap {
|
|||
for arg in args.iter() {
|
||||
match &arg.label {
|
||||
Some(_) => {
|
||||
labeled_arguments_given = true;
|
||||
last_labeled_arguments_given = Some(arg);
|
||||
}
|
||||
|
||||
None => {
|
||||
if labeled_arguments_given {
|
||||
if let Some(label) = last_labeled_arguments_given {
|
||||
return Err(Error::PositionalArgumentAfterLabeled {
|
||||
location: arg.location,
|
||||
labeled_arg_location: label.location,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
@ -90,7 +102,7 @@ impl FieldMap {
|
|||
}
|
||||
};
|
||||
|
||||
let position = match self.fields.get(label) {
|
||||
let (position, other_location) = match self.fields.get(label) {
|
||||
None => {
|
||||
unknown_labels.push((label.clone(), location));
|
||||
|
||||
|
@ -110,7 +122,7 @@ impl FieldMap {
|
|||
} else {
|
||||
if seen_labels.contains(label) {
|
||||
return Err(Error::DuplicateArgument {
|
||||
location,
|
||||
locations: vec![location, other_location],
|
||||
label: label.to_string(),
|
||||
});
|
||||
}
|
||||
|
|
|
@ -240,12 +240,10 @@ impl<'a, 'b> PatternTyper<'a, 'b> {
|
|||
.environment
|
||||
.get_variable(&name)
|
||||
.cloned()
|
||||
.ok_or_else(|| {
|
||||
Error::unknown_variable_or_type(
|
||||
location,
|
||||
&name,
|
||||
self.environment.local_value_names(),
|
||||
)
|
||||
.ok_or_else(|| Error::UnknownVariable {
|
||||
location,
|
||||
name: name.to_string(),
|
||||
variables: self.environment.local_value_names(),
|
||||
})?;
|
||||
|
||||
self.environment.increment_usage(&name);
|
||||
|
@ -359,8 +357,7 @@ impl<'a, 'b> PatternTyper<'a, 'b> {
|
|||
Pattern::Tuple { elems, location } => match collapse_links(tipo.clone()).deref() {
|
||||
Type::Tuple { elems: type_elems } => {
|
||||
if elems.len() != type_elems.len() {
|
||||
return Err(Error::IncorrectArity {
|
||||
labels: vec![],
|
||||
return Err(Error::IncorrectTupleArity {
|
||||
location,
|
||||
expected: type_elems.len(),
|
||||
given: elems.len(),
|
||||
|
@ -487,14 +484,14 @@ impl<'a, 'b> PatternTyper<'a, 'b> {
|
|||
// The fun has no field map and so we error if arguments have been labelled
|
||||
None => assert_no_labeled_arguments(&pattern_args)
|
||||
.map(|(location, label)| {
|
||||
Err(Error::unexpected_labeled_arg_in_pattern(
|
||||
Err(Error::UnexpectedLabeledArgInPattern {
|
||||
location,
|
||||
label,
|
||||
&name,
|
||||
&pattern_args,
|
||||
&module,
|
||||
name: name.clone(),
|
||||
args: pattern_args.clone(),
|
||||
module: module.clone(),
|
||||
with_spread,
|
||||
))
|
||||
})
|
||||
})
|
||||
.unwrap_or(Ok(()))?,
|
||||
}
|
||||
|
@ -555,11 +552,13 @@ impl<'a, 'b> PatternTyper<'a, 'b> {
|
|||
is_record,
|
||||
})
|
||||
} else {
|
||||
Err(Error::IncorrectArity {
|
||||
labels: vec![],
|
||||
Err(Error::IncorrectPatternArity {
|
||||
location,
|
||||
expected: args.len(),
|
||||
given: pattern_args.len(),
|
||||
given: pattern_args,
|
||||
expected: 0,
|
||||
name: name.clone(),
|
||||
module: module.clone(),
|
||||
is_record,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
@ -583,11 +582,13 @@ impl<'a, 'b> PatternTyper<'a, 'b> {
|
|||
is_record,
|
||||
})
|
||||
} else {
|
||||
Err(Error::IncorrectArity {
|
||||
labels: vec![],
|
||||
Err(Error::IncorrectPatternArity {
|
||||
location,
|
||||
given: pattern_args,
|
||||
expected: 0,
|
||||
given: pattern_args.len(),
|
||||
name: name.clone(),
|
||||
module: module.clone(),
|
||||
is_record,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
@ -972,7 +972,8 @@ impl<'a> CodeGenerator<'a> {
|
|||
.iter()
|
||||
.map(|item| {
|
||||
let label = item.label.clone().unwrap_or_default();
|
||||
let field_index = field_map.fields.get(&label).unwrap_or(&0);
|
||||
let field_index =
|
||||
field_map.fields.get(&label).map(|x| &x.0).unwrap_or(&0);
|
||||
let (discard, var_name) = match &item.value {
|
||||
Pattern::Var { name, .. } => (false, name.clone()),
|
||||
Pattern::Discard { .. } => (true, "".to_string()),
|
||||
|
@ -1316,7 +1317,8 @@ impl<'a> CodeGenerator<'a> {
|
|||
.iter()
|
||||
.map(|item| {
|
||||
let label = item.label.clone().unwrap_or_default();
|
||||
let field_index = field_map.fields.get(&label).unwrap_or(&0);
|
||||
let field_index =
|
||||
field_map.fields.get(&label).map(|x| &x.0).unwrap_or(&0);
|
||||
let (discard, var_name) = match &item.value {
|
||||
Pattern::Var { name, .. } => (false, name.clone()),
|
||||
Pattern::Discard { .. } => (true, "".to_string()),
|
||||
|
@ -2031,7 +2033,11 @@ impl<'a> CodeGenerator<'a> {
|
|||
for field in field_map
|
||||
.fields
|
||||
.iter()
|
||||
.sorted_by(|item1, item2| item1.1.cmp(item2.1))
|
||||
.sorted_by(|item1, item2| {
|
||||
let (a, _) = item1.1;
|
||||
let (b, _) = item2.1;
|
||||
a.cmp(b)
|
||||
})
|
||||
.zip(&args_type)
|
||||
.rev()
|
||||
{
|
||||
|
@ -2092,7 +2098,11 @@ impl<'a> CodeGenerator<'a> {
|
|||
for field in field_map
|
||||
.fields
|
||||
.iter()
|
||||
.sorted_by(|item1, item2| item1.1.cmp(item2.1))
|
||||
.sorted_by(|item1, item2| {
|
||||
let (a, _) = item1.1;
|
||||
let (b, _) = item2.1;
|
||||
a.cmp(b)
|
||||
})
|
||||
.rev()
|
||||
{
|
||||
term = Term::Lambda {
|
||||
|
|
|
@ -18,17 +18,17 @@ use zip_extract::ZipExtractError;
|
|||
#[allow(dead_code)]
|
||||
#[derive(thiserror::Error)]
|
||||
pub enum Error {
|
||||
#[error("Duplicate module\n\n{module}")]
|
||||
#[error("I just found two modules with the same name: '{module}'")]
|
||||
DuplicateModule {
|
||||
module: String,
|
||||
first: PathBuf,
|
||||
second: PathBuf,
|
||||
},
|
||||
|
||||
#[error("File operation failed")]
|
||||
#[error("Some operation on the file-system did fail.")]
|
||||
FileIo { error: io::Error, path: PathBuf },
|
||||
|
||||
#[error("Source code incorrectly formatted")]
|
||||
#[error("I found some files with incorrectly formatted source code.")]
|
||||
Format { problem_files: Vec<Unformatted> },
|
||||
|
||||
#[error(transparent)]
|
||||
|
@ -52,29 +52,26 @@ pub enum Error {
|
|||
help: String,
|
||||
},
|
||||
|
||||
#[error("Missing 'aiken.toml' manifest in {path}")]
|
||||
#[error("I couldn't find any 'aiken.toml' manifest in {path}.")]
|
||||
MissingManifest { path: PathBuf },
|
||||
|
||||
#[error("Cyclical module imports")]
|
||||
#[error("I just found a cycle in module hierarchy!")]
|
||||
ImportCycle { modules: Vec<String> },
|
||||
|
||||
/// Useful for returning many [`Error::Parse`] at once
|
||||
#[error("A list of errors")]
|
||||
List(Vec<Self>),
|
||||
|
||||
#[error("Parsing")]
|
||||
#[error("While parsing files...")]
|
||||
Parse {
|
||||
path: PathBuf,
|
||||
|
||||
src: String,
|
||||
|
||||
named: NamedSource,
|
||||
|
||||
#[source]
|
||||
error: Box<ParseError>,
|
||||
},
|
||||
|
||||
#[error("Type-checking")]
|
||||
#[error("While trying to make sense of your code...")]
|
||||
Type {
|
||||
path: PathBuf,
|
||||
src: String,
|
||||
|
@ -246,7 +243,10 @@ impl Diagnostic for Error {
|
|||
Error::ImportCycle { .. } => Some(Box::new("aiken::module::cyclical")),
|
||||
Error::List(_) => None,
|
||||
Error::Parse { .. } => Some(Box::new("aiken::parser")),
|
||||
Error::Type { .. } => Some(Box::new("aiken::check")),
|
||||
Error::Type { error, .. } => Some(Box::new(format!(
|
||||
"err::aiken::check{}",
|
||||
error.code().map(|s| format!("::{s}")).unwrap_or_default()
|
||||
))),
|
||||
Error::StandardIo(_) => None,
|
||||
Error::MissingManifest { .. } => None,
|
||||
Error::TomlLoading { .. } => Some(Box::new("aiken::loading::toml")),
|
||||
|
|
Loading…
Reference in New Issue