code cleanup

This commit is contained in:
gluaxspeed 2021-08-04 00:42:48 -07:00
parent 88e0e32317
commit 162949185f
130 changed files with 1087 additions and 1727 deletions

8
Cargo.lock generated
View File

@ -1210,9 +1210,8 @@ dependencies = [
name = "leo-ast" name = "leo-ast"
version = "1.5.3" version = "1.5.3"
dependencies = [ dependencies = [
"anyhow", "backtrace",
"criterion", "criterion",
"eyre",
"indexmap", "indexmap",
"leo-errors", "leo-errors",
"leo-input", "leo-input",
@ -1220,7 +1219,6 @@ dependencies = [
"serde", "serde",
"serde_json", "serde_json",
"tendril", "tendril",
"thiserror",
] ]
[[package]] [[package]]
@ -1229,7 +1227,6 @@ version = "1.5.3"
dependencies = [ dependencies = [
"backtrace", "backtrace",
"bincode", "bincode",
"eyre",
"hex", "hex",
"indexmap", "indexmap",
"leo-asg", "leo-asg",
@ -1318,6 +1315,7 @@ dependencies = [
"lazy_static", "lazy_static",
"leo-ast", "leo-ast",
"leo-compiler", "leo-compiler",
"leo-errors",
"leo-imports", "leo-imports",
"leo-input", "leo-input",
"leo-package", "leo-package",
@ -1355,7 +1353,6 @@ name = "leo-package"
version = "1.5.3" version = "1.5.3"
dependencies = [ dependencies = [
"backtrace", "backtrace",
"eyre",
"lazy_static", "lazy_static",
"leo-errors", "leo-errors",
"serde", "serde",
@ -1379,7 +1376,6 @@ dependencies = [
"serde_json", "serde_json",
"serde_yaml", "serde_yaml",
"tendril", "tendril",
"thiserror",
"tracing", "tracing",
] ]

View File

@ -50,6 +50,10 @@ version = "1.5.3"
path = "./compiler" path = "./compiler"
version = "1.5.3" version = "1.5.3"
[dependencies.leo-errors]
path = "./errors"
version = "1.5.3"
[dependencies.leo-imports] [dependencies.leo-imports]
path = "./imports" path = "./imports"
version = "1.5.3" version = "1.5.3"

View File

@ -316,56 +316,16 @@ impl ConstInt {
pub fn parse(int_type: &IntegerType, value: &str, span: &Span) -> Result<ConstInt, LeoError> { pub fn parse(int_type: &IntegerType, value: &str, span: &Span) -> Result<ConstInt, LeoError> {
Ok(match int_type { Ok(match int_type {
IntegerType::I8 => ConstInt::I8( IntegerType::I8 => ConstInt::I8(value.parse().map_err(|_| AsgError::invalid_int(value, span))?),
value IntegerType::I16 => ConstInt::I16(value.parse().map_err(|_| AsgError::invalid_int(value, span))?),
.parse() IntegerType::I32 => ConstInt::I32(value.parse().map_err(|_| AsgError::invalid_int(value, span))?),
.map_err(|_| LeoError::from(AsgError::invalid_int(value, span)))?, IntegerType::I64 => ConstInt::I64(value.parse().map_err(|_| AsgError::invalid_int(value, span))?),
), IntegerType::I128 => ConstInt::I128(value.parse().map_err(|_| AsgError::invalid_int(value, span))?),
IntegerType::I16 => ConstInt::I16( IntegerType::U8 => ConstInt::U8(value.parse().map_err(|_| AsgError::invalid_int(value, span))?),
value IntegerType::U16 => ConstInt::U16(value.parse().map_err(|_| AsgError::invalid_int(value, span))?),
.parse() IntegerType::U32 => ConstInt::U32(value.parse().map_err(|_| AsgError::invalid_int(value, span))?),
.map_err(|_| LeoError::from(AsgError::invalid_int(value, span)))?, IntegerType::U64 => ConstInt::U64(value.parse().map_err(|_| AsgError::invalid_int(value, span))?),
), IntegerType::U128 => ConstInt::U128(value.parse().map_err(|_| AsgError::invalid_int(value, span))?),
IntegerType::I32 => ConstInt::I32(
value
.parse()
.map_err(|_| LeoError::from(AsgError::invalid_int(value, span)))?,
),
IntegerType::I64 => ConstInt::I64(
value
.parse()
.map_err(|_| LeoError::from(AsgError::invalid_int(value, span)))?,
),
IntegerType::I128 => ConstInt::I128(
value
.parse()
.map_err(|_| LeoError::from(AsgError::invalid_int(value, span)))?,
),
IntegerType::U8 => ConstInt::U8(
value
.parse()
.map_err(|_| LeoError::from(AsgError::invalid_int(value, span)))?,
),
IntegerType::U16 => ConstInt::U16(
value
.parse()
.map_err(|_| LeoError::from(AsgError::invalid_int(value, span)))?,
),
IntegerType::U32 => ConstInt::U32(
value
.parse()
.map_err(|_| LeoError::from(AsgError::invalid_int(value, span)))?,
),
IntegerType::U64 => ConstInt::U64(
value
.parse()
.map_err(|_| LeoError::from(AsgError::invalid_int(value, span)))?,
),
IntegerType::U128 => ConstInt::U128(
value
.parse()
.map_err(|_| LeoError::from(AsgError::invalid_int(value, span)))?,
),
}) })
} }
} }

View File

@ -93,11 +93,11 @@ impl<'a> FromAst<'a, leo_ast::ArrayAccessExpression> for ArrayAccessExpression<'
let array_len = match array.get_type() { let array_len = match array.get_type() {
Some(Type::Array(_, len)) => len, Some(Type::Array(_, len)) => len,
type_ => { type_ => {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(
"array", "array",
type_.map(|x| x.to_string()).as_deref(), type_.map(|x| x.to_string()).unwrap_or("unknown".to_string()),
&value.span, &value.span,
))); ))?;
} }
}; };
@ -113,10 +113,10 @@ impl<'a> FromAst<'a, leo_ast::ArrayAccessExpression> for ArrayAccessExpression<'
.flatten() .flatten()
{ {
if index >= array_len { if index >= array_len {
return Err(LeoError::from(AsgError::array_index_out_of_bounds( return Err(AsgError::array_index_out_of_bounds(
index, index,
&array.span().cloned().unwrap_or_default(), &array.span().cloned().unwrap_or_default(),
))); ))?;
} }
} }

View File

@ -74,11 +74,7 @@ impl<'a> FromAst<'a, leo_ast::ArrayInitExpression> for ArrayInitExpression<'a> {
Some(PartialType::Array(item, dims)) => (item.map(|x| *x), dims), Some(PartialType::Array(item, dims)) => (item.map(|x| *x), dims),
None => (None, None), None => (None, None),
Some(type_) => { Some(type_) => {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(type_, "array", &value.span))?;
&type_.to_string(),
Some("array"),
&value.span,
)));
} }
}; };
let dimensions = value let dimensions = value
@ -86,22 +82,22 @@ impl<'a> FromAst<'a, leo_ast::ArrayInitExpression> for ArrayInitExpression<'a> {
.0 .0
.iter() .iter()
.map(|x| { .map(|x| {
x.value Ok(x.value
.parse::<usize>() .parse::<usize>()
.map_err(|_| LeoError::from(AsgError::parse_dimension_error(&value.span))) .map_err(|_| AsgError::parse_dimension_error(&value.span))?)
}) })
.collect::<Result<Vec<_>, LeoError>>()?; .collect::<Result<Vec<_>, LeoError>>()?;
let len = *dimensions let len = *dimensions
.get(0) .get(0)
.ok_or_else(|| LeoError::from(AsgError::parse_dimension_error(&value.span)))?; .ok_or_else(|| AsgError::parse_dimension_error(&value.span))?;
if let Some(expected_len) = expected_len { if let Some(expected_len) = expected_len {
if expected_len != len { if expected_len != len {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(
&*format!("array of length {}", expected_len), format!("array of length {}", expected_len),
Some(&*format!("array of length {}", len)), format!("array of length {}", len),
&value.span, &value.span,
))); ))?;
} }
} }
@ -110,11 +106,11 @@ impl<'a> FromAst<'a, leo_ast::ArrayInitExpression> for ArrayInitExpression<'a> {
Some(PartialType::Array(item, len)) => { Some(PartialType::Array(item, len)) => {
if let Some(len) = len { if let Some(len) = len {
if len != dimension { if len != dimension {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(
&*format!("array of length {}", dimension), format!("array of length {}", dimension),
Some(&*format!("array of length {}", len)), format!("array of length {}", len),
&value.span, &value.span,
))); ))?;
} }
} }
@ -122,11 +118,7 @@ impl<'a> FromAst<'a, leo_ast::ArrayInitExpression> for ArrayInitExpression<'a> {
} }
None => None, None => None,
Some(type_) => { Some(type_) => {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type("array", type_, &value.span))?;
"array",
Some(&type_.to_string()),
&value.span,
)));
} }
} }
} }

View File

@ -109,11 +109,7 @@ impl<'a> FromAst<'a, leo_ast::ArrayInlineExpression> for ArrayInlineExpression<'
Some(PartialType::Array(item, dims)) => (item.map(|x| *x), dims), Some(PartialType::Array(item, dims)) => (item.map(|x| *x), dims),
None => (None, None), None => (None, None),
Some(type_) => { Some(type_) => {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(type_, "array", &value.span))?;
&type_.to_string(),
Some("array"),
&value.span,
)));
} }
}; };
@ -170,15 +166,15 @@ impl<'a> FromAst<'a, leo_ast::ArrayInlineExpression> for ArrayInlineExpression<'
len += spread_len; len += spread_len;
} }
type_ => { type_ => {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(
expected_item expected_item
.as_ref() .as_ref()
.map(|x| x.to_string()) .map(|x| x.to_string())
.as_deref() .as_deref()
.unwrap_or("unknown"), .unwrap_or("unknown"),
type_.map(|x| x.to_string()).as_deref(), type_.map(|x| x.to_string()).unwrap_or("unknown".to_string()),
&value.span, &value.span,
))); ))?;
} }
} }
Ok((Cell::new(expr), true)) Ok((Cell::new(expr), true))
@ -188,11 +184,11 @@ impl<'a> FromAst<'a, leo_ast::ArrayInlineExpression> for ArrayInlineExpression<'
}; };
if let Some(expected_len) = expected_len { if let Some(expected_len) = expected_len {
if len != expected_len { if len != expected_len {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(
&*format!("array of length {}", expected_len), format!("array of length {}", expected_len),
Some(&*format!("array of length {}", len)), format!("array of length {}", len),
&value.span, &value.span,
))); ))?;
} }
} }
Ok(output) Ok(output)

View File

@ -108,11 +108,7 @@ impl<'a> FromAst<'a, leo_ast::ArrayRangeAccessExpression> for ArrayRangeAccessEx
Some(PartialType::Array(element, len)) => (Some(PartialType::Array(element, None)), len), Some(PartialType::Array(element, len)) => (Some(PartialType::Array(element, None)), len),
None => (None, None), None => (None, None),
Some(x) => { Some(x) => {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(x, "array", &value.span))?;
&x.to_string(),
Some("array"),
&value.span,
)));
} }
}; };
let array = <&Expression<'a>>::from_ast(scope, &*value.array, expected_array)?; let array = <&Expression<'a>>::from_ast(scope, &*value.array, expected_array)?;
@ -120,11 +116,11 @@ impl<'a> FromAst<'a, leo_ast::ArrayRangeAccessExpression> for ArrayRangeAccessEx
let (parent_element, parent_size) = match array_type { let (parent_element, parent_size) = match array_type {
Some(Type::Array(inner, size)) => (inner, size), Some(Type::Array(inner, size)) => (inner, size),
type_ => { type_ => {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(
"array", "array",
type_.map(|x| x.to_string()).as_deref(), type_.map(|x| x.to_string()).unwrap_or("unknown".to_string()),
&value.span, &value.span,
))); ))?;
} }
}; };
@ -158,10 +154,7 @@ impl<'a> FromAst<'a, leo_ast::ArrayRangeAccessExpression> for ArrayRangeAccessEx
} else { } else {
value.span.clone() value.span.clone()
}; };
return Err(LeoError::from(AsgError::array_index_out_of_bounds( return Err(AsgError::array_index_out_of_bounds(inner_value, &error_span))?;
inner_value,
&error_span,
)));
} else if let Some(left) = const_left { } else if let Some(left) = const_left {
if left > inner_value { if left > inner_value {
let error_span = if let Some(right) = right { let error_span = if let Some(right) = right {
@ -169,10 +162,7 @@ impl<'a> FromAst<'a, leo_ast::ArrayRangeAccessExpression> for ArrayRangeAccessEx
} else { } else {
value.span.clone() value.span.clone()
}; };
return Err(LeoError::from(AsgError::array_index_out_of_bounds( return Err(AsgError::array_index_out_of_bounds(inner_value, &error_span))?;
inner_value,
&error_span,
)));
} }
} }
} }
@ -192,11 +182,11 @@ impl<'a> FromAst<'a, leo_ast::ArrayRangeAccessExpression> for ArrayRangeAccessEx
if let Some(length) = length { if let Some(length) = length {
if length != expected_len { if length != expected_len {
let concrete_type = Type::Array(parent_element, length); let concrete_type = Type::Array(parent_element, length);
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(
&expected_type.as_ref().unwrap().to_string(), expected_type.as_ref().unwrap(),
Some(&concrete_type.to_string()), concrete_type,
&value.span, &value.span,
))); ))?;
} }
} }
if let Some(left_value) = const_left { if let Some(left_value) = const_left {
@ -206,16 +196,13 @@ impl<'a> FromAst<'a, leo_ast::ArrayRangeAccessExpression> for ArrayRangeAccessEx
} else { } else {
value.span.clone() value.span.clone()
}; };
return Err(LeoError::from(AsgError::array_index_out_of_bounds( return Err(AsgError::array_index_out_of_bounds(left_value, &error_span))?;
left_value,
&error_span,
)));
} }
} }
length = Some(expected_len); length = Some(expected_len);
} }
if length.is_none() { if length.is_none() {
return Err(LeoError::from(AsgError::unknown_array_size(&value.span))); return Err(AsgError::unknown_array_size(&value.span))?;
} }
Ok(ArrayRangeAccessExpression { Ok(ArrayRangeAccessExpression {

View File

@ -123,11 +123,7 @@ impl<'a> FromAst<'a, leo_ast::BinaryExpression> for BinaryExpression<'a> {
BinaryOperationClass::Boolean => match expected_type { BinaryOperationClass::Boolean => match expected_type {
Some(PartialType::Type(Type::Boolean)) | None => None, Some(PartialType::Type(Type::Boolean)) | None => None,
Some(x) => { Some(x) => {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(x, Type::Boolean, &value.span))?;
&x.to_string(),
Some(&*Type::Boolean.to_string()),
&value.span,
)));
} }
}, },
BinaryOperationClass::Numeric => match expected_type { BinaryOperationClass::Numeric => match expected_type {
@ -135,11 +131,7 @@ impl<'a> FromAst<'a, leo_ast::BinaryExpression> for BinaryExpression<'a> {
Some(x @ PartialType::Type(Type::Field)) => Some(x), Some(x @ PartialType::Type(Type::Field)) => Some(x),
Some(x @ PartialType::Type(Type::Group)) => Some(x), Some(x @ PartialType::Type(Type::Group)) => Some(x),
Some(x) => { Some(x) => {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(x, "integer, field, or group", &value.span))?;
&x.to_string(),
Some("integer, field, or group"),
&value.span,
)));
} }
None => None, None => None,
}, },
@ -188,33 +180,25 @@ impl<'a> FromAst<'a, leo_ast::BinaryExpression> for BinaryExpression<'a> {
} }
Some(Type::Field) if value.op == BinaryOperation::Mul || value.op == BinaryOperation::Div => (), Some(Type::Field) if value.op == BinaryOperation::Mul || value.op == BinaryOperation::Div => (),
type_ => { type_ => {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(
"integer", "integer",
type_.map(|x| x.to_string()).as_deref(), type_.map(|x| x.to_string()).unwrap_or("unknown".to_string()),
&value.span, &value.span,
))); ))?;
} }
}, },
BinaryOperationClass::Boolean => match &value.op { BinaryOperationClass::Boolean => match &value.op {
BinaryOperation::And | BinaryOperation::Or => match left_type { BinaryOperation::And | BinaryOperation::Or => match left_type {
Some(Type::Boolean) | None => (), Some(Type::Boolean) | None => (),
Some(x) => { Some(x) => {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(x, Type::Boolean, &value.span))?;
&x.to_string(),
Some(&*Type::Boolean.to_string()),
&value.span,
)));
} }
}, },
BinaryOperation::Eq | BinaryOperation::Ne => (), // all types allowed BinaryOperation::Eq | BinaryOperation::Ne => (), // all types allowed
_ => match left_type { _ => match left_type {
Some(Type::Integer(_)) | None => (), Some(Type::Integer(_)) | None => (),
Some(x) => { Some(x) => {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(x, "integer", &value.span))?;
&x.to_string(),
Some("integer"),
&value.span,
)));
} }
}, },
}, },
@ -225,19 +209,11 @@ impl<'a> FromAst<'a, leo_ast::BinaryExpression> for BinaryExpression<'a> {
match (left_type, right_type) { match (left_type, right_type) {
(Some(left_type), Some(right_type)) => { (Some(left_type), Some(right_type)) => {
if !left_type.is_assignable_from(&right_type) { if !left_type.is_assignable_from(&right_type) {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(left_type, right_type, &value.span))?;
&left_type.to_string(),
Some(&*right_type.to_string()),
&value.span,
)));
} }
} }
(None, None) => { (None, None) => {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type("any type", "unknown type", &value.span))?;
"any type",
Some("unknown type"),
&value.span,
)));
} }
(_, _) => (), (_, _) => (),
} }

View File

@ -94,7 +94,7 @@ impl<'a> FromAst<'a, leo_ast::CallExpression> for CallExpression<'a> {
None, None,
scope scope
.resolve_function(&name.name) .resolve_function(&name.name)
.ok_or_else(|| LeoError::from(AsgError::unresolved_function(&name.name, &name.span)))?, .ok_or_else(|| AsgError::unresolved_function(&name.name, &name.span))?,
), ),
leo_ast::Expression::CircuitMemberAccess(leo_ast::CircuitMemberAccessExpression { leo_ast::Expression::CircuitMemberAccess(leo_ast::CircuitMemberAccessExpression {
circuit: ast_circuit, circuit: ast_circuit,
@ -105,41 +105,33 @@ impl<'a> FromAst<'a, leo_ast::CallExpression> for CallExpression<'a> {
let circuit = match target.get_type() { let circuit = match target.get_type() {
Some(Type::Circuit(circuit)) => circuit, Some(Type::Circuit(circuit)) => circuit,
type_ => { type_ => {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(
"circuit", "circuit",
type_.map(|x| x.to_string()).as_deref(), type_.map(|x| x.to_string()).unwrap_or("unknown".to_string()),
span, span,
))); ))?;
} }
}; };
let circuit_name = circuit.name.borrow().name.clone(); let circuit_name = circuit.name.borrow().name.clone();
let member = circuit.members.borrow(); let member = circuit.members.borrow();
let member = member.get(name.name.as_ref()).ok_or_else(|| { let member = member
LeoError::from(AsgError::unresolved_circuit_member(&circuit_name, &name.name, span)) .get(name.name.as_ref())
})?; .ok_or_else(|| AsgError::unresolved_circuit_member(&circuit_name, &name.name, span))?;
match member { match member {
CircuitMember::Function(body) => { CircuitMember::Function(body) => {
if body.qualifier == FunctionQualifier::Static { if body.qualifier == FunctionQualifier::Static {
return Err(LeoError::from(AsgError::circuit_static_call_invalid( return Err(AsgError::circuit_static_call_invalid(&circuit_name, &name.name, span))?;
&circuit_name,
&name.name,
span,
)));
} else if body.qualifier == FunctionQualifier::MutSelfRef && !target.is_mut_ref() { } else if body.qualifier == FunctionQualifier::MutSelfRef && !target.is_mut_ref() {
return Err(LeoError::from(AsgError::circuit_member_mut_call_invalid( return Err(AsgError::circuit_member_mut_call_invalid(
&circuit_name, circuit_name,
&name.name, &name.name,
span, span,
))); ))?;
} }
(Some(target), *body) (Some(target), *body)
} }
CircuitMember::Variable(_) => { CircuitMember::Variable(_) => {
return Err(LeoError::from(AsgError::circuit_variable_call( return Err(AsgError::circuit_variable_call(circuit_name, &name.name, span))?;
&circuit_name,
&name.name,
span,
)));
} }
} }
} }
@ -149,61 +141,49 @@ impl<'a> FromAst<'a, leo_ast::CallExpression> for CallExpression<'a> {
span, span,
}) => { }) => {
let circuit = if let leo_ast::Expression::Identifier(circuit_name) = &**ast_circuit { let circuit = if let leo_ast::Expression::Identifier(circuit_name) = &**ast_circuit {
scope.resolve_circuit(&circuit_name.name).ok_or_else(|| { scope
LeoError::from(AsgError::unresolved_circuit(&circuit_name.name, &circuit_name.span)) .resolve_circuit(&circuit_name.name)
})? .ok_or_else(|| AsgError::unresolved_circuit(&circuit_name.name, &circuit_name.span))?
} else { } else {
return Err(LeoError::from(AsgError::unexpected_type("circuit", None, span))); return Err(AsgError::unexpected_type("circuit", "unknown", span))?;
}; };
let circuit_name = circuit.name.borrow().name.clone(); let circuit_name = circuit.name.borrow().name.clone();
let member = circuit.members.borrow(); let member = circuit.members.borrow();
let member = member.get(name.name.as_ref()).ok_or_else(|| { let member = member
LeoError::from(AsgError::unresolved_circuit_member(&circuit_name, &name.name, span)) .get(name.name.as_ref())
})?; .ok_or_else(|| AsgError::unresolved_circuit_member(&circuit_name, &name.name, span))?;
match member { match member {
CircuitMember::Function(body) => { CircuitMember::Function(body) => {
if body.qualifier != FunctionQualifier::Static { if body.qualifier != FunctionQualifier::Static {
return Err(LeoError::from(AsgError::circuit_member_call_invalid( return Err(AsgError::circuit_member_call_invalid(circuit_name, &name.name, span))?;
&circuit_name,
&name.name,
span,
)));
} }
(None, *body) (None, *body)
} }
CircuitMember::Variable(_) => { CircuitMember::Variable(_) => {
return Err(LeoError::from(AsgError::circuit_variable_call( return Err(AsgError::circuit_variable_call(circuit_name, &name.name, span))?;
&circuit_name,
&name.name,
span,
)));
} }
} }
} }
_ => { _ => {
return Err(LeoError::from(AsgError::illegal_ast_structure( return Err(AsgError::illegal_ast_structure(
"non Identifier/CircuitMemberAccess/CircuitStaticFunctionAccess as call target", "non Identifier/CircuitMemberAccess/CircuitStaticFunctionAccess as call target",
&value.span, &value.span,
))); ))?;
} }
}; };
if let Some(expected) = expected_type { if let Some(expected) = expected_type {
let output: Type = function.output.clone(); let output: Type = function.output.clone();
if !expected.matches(&output) { if !expected.matches(&output) {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(expected, output, &value.span))?;
&expected.to_string(),
Some(&*output.to_string()),
&value.span,
)));
} }
} }
if value.arguments.len() != function.arguments.len() { if value.arguments.len() != function.arguments.len() {
return Err(LeoError::from(AsgError::unexpected_call_argument_count( return Err(AsgError::unexpected_call_argument_count(
function.arguments.len(), function.arguments.len(),
value.arguments.len(), value.arguments.len(),
&value.span, &value.span,
))); ))?;
} }
let arguments = value let arguments = value
@ -214,14 +194,14 @@ impl<'a> FromAst<'a, leo_ast::CallExpression> for CallExpression<'a> {
let argument = argument.get().borrow(); let argument = argument.get().borrow();
let converted = <&Expression<'a>>::from_ast(scope, expr, Some(argument.type_.clone().partial()))?; let converted = <&Expression<'a>>::from_ast(scope, expr, Some(argument.type_.clone().partial()))?;
if argument.const_ && !converted.is_consty() { if argument.const_ && !converted.is_consty() {
return Err(LeoError::from(AsgError::unexpected_nonconst(expr.span()))); return Err(AsgError::unexpected_nonconst(expr.span()))?;
} }
Ok(Cell::new(converted)) Ok(Cell::new(converted))
}) })
.collect::<Result<Vec<_>, LeoError>>()?; .collect::<Result<Vec<_>, LeoError>>()?;
if function.is_test() { if function.is_test() {
return Err(LeoError::from(AsgError::call_test_function(&value.span))); return Err(AsgError::call_test_function(&value.span))?;
} }
Ok(CallExpression { Ok(CallExpression {
parent: Cell::new(None), parent: Cell::new(None),

View File

@ -80,11 +80,7 @@ impl<'a> FromAst<'a, leo_ast::CastExpression> for CastExpression<'a> {
let target_type = scope.resolve_ast_type(&value.target_type, &value.span)?; let target_type = scope.resolve_ast_type(&value.target_type, &value.span)?;
if let Some(expected_type) = &expected_type { if let Some(expected_type) = &expected_type {
if !expected_type.matches(&target_type) { if !expected_type.matches(&target_type) {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(expected_type, target_type, &value.span))?;
&expected_type.to_string(),
Some(&target_type.to_string()),
&value.span,
)));
} }
} }

View File

@ -107,11 +107,11 @@ impl<'a> FromAst<'a, leo_ast::CircuitMemberAccessExpression> for CircuitAccessEx
let circuit = match target.get_type() { let circuit = match target.get_type() {
Some(Type::Circuit(circuit)) => circuit, Some(Type::Circuit(circuit)) => circuit,
x => { x => {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(
"circuit", "circuit",
x.map(|x| x.to_string()).as_deref(), x.map(|x| x.to_string()).unwrap_or("unknown".to_string()),
&value.span, &value.span,
))); ))?;
} }
}; };
@ -122,11 +122,7 @@ impl<'a> FromAst<'a, leo_ast::CircuitMemberAccessExpression> for CircuitAccessEx
if let CircuitMember::Variable(type_) = &member { if let CircuitMember::Variable(type_) = &member {
let type_: Type = type_.clone(); let type_: Type = type_.clone();
if !expected_type.matches(&type_) { if !expected_type.matches(&type_) {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(expected_type, type_, &value.span))?;
&expected_type.to_string(),
Some(&type_.to_string()),
&value.span,
)));
} }
} // used by call expression } // used by call expression
} }
@ -146,18 +142,18 @@ impl<'a> FromAst<'a, leo_ast::CircuitMemberAccessExpression> for CircuitAccessEx
CircuitMember::Variable(expected_type.clone()), CircuitMember::Variable(expected_type.clone()),
); );
} else { } else {
return Err(LeoError::from(AsgError::input_ref_needs_type( return Err(AsgError::input_ref_needs_type(
&circuit.name.borrow().name, &circuit.name.borrow().name,
&value.name.name, &value.name.name,
&value.span, &value.span,
))); ))?;
} }
} else { } else {
return Err(LeoError::from(AsgError::unresolved_circuit_member( return Err(AsgError::unresolved_circuit_member(
&circuit.name.borrow().name, &circuit.name.borrow().name,
&value.name.name, &value.name.name,
&value.span, &value.span,
))); ))?;
} }
Ok(CircuitAccessExpression { Ok(CircuitAccessExpression {
@ -179,32 +175,24 @@ impl<'a> FromAst<'a, leo_ast::CircuitStaticFunctionAccessExpression> for Circuit
let circuit = match &*value.circuit { let circuit = match &*value.circuit {
leo_ast::Expression::Identifier(name) => scope leo_ast::Expression::Identifier(name) => scope
.resolve_circuit(&name.name) .resolve_circuit(&name.name)
.ok_or_else(|| LeoError::from(AsgError::unresolved_circuit(&name.name, &name.span)))?, .ok_or_else(|| AsgError::unresolved_circuit(&name.name, &name.span))?,
_ => { _ => {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type("circuit", "unknown", &value.span))?;
"circuit",
Some("unknown"),
&value.span,
)));
} }
}; };
if let Some(expected_type) = expected_type { if let Some(expected_type) = expected_type {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(expected_type, "none", &value.span))?;
&expected_type.to_string(),
Some("none"),
&value.span,
)));
} }
if let Some(CircuitMember::Function(_)) = circuit.members.borrow().get(value.name.name.as_ref()) { if let Some(CircuitMember::Function(_)) = circuit.members.borrow().get(value.name.name.as_ref()) {
// okay // okay
} else { } else {
return Err(LeoError::from(AsgError::unresolved_circuit_member( return Err(AsgError::unresolved_circuit_member(
&circuit.name.borrow().name, &circuit.name.borrow().name,
&value.name.name, &value.name.name,
&value.span, &value.span,
))); ))?;
} }
Ok(CircuitAccessExpression { Ok(CircuitAccessExpression {

View File

@ -96,16 +96,16 @@ impl<'a> FromAst<'a, leo_ast::CircuitInitExpression> for CircuitInitExpression<'
) -> Result<CircuitInitExpression<'a>, LeoError> { ) -> Result<CircuitInitExpression<'a>, LeoError> {
let circuit = scope let circuit = scope
.resolve_circuit(&value.name.name) .resolve_circuit(&value.name.name)
.ok_or_else(|| LeoError::from(AsgError::unresolved_circuit(&value.name.name, &value.name.span)))?; .ok_or_else(|| AsgError::unresolved_circuit(&value.name.name, &value.name.span))?;
match expected_type { match expected_type {
Some(PartialType::Type(Type::Circuit(expected_circuit))) if expected_circuit == circuit => (), Some(PartialType::Type(Type::Circuit(expected_circuit))) if expected_circuit == circuit => (),
None => (), None => (),
Some(x) => { Some(x) => {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(
&x.to_string(), x,
Some(&circuit.name.borrow().name), circuit.name.borrow().name.to_string(),
&value.span, &value.span,
))); ))?;
} }
} }
let members: IndexMap<&str, (&Identifier, Option<&leo_ast::Expression>)> = value let members: IndexMap<&str, (&Identifier, Option<&leo_ast::Expression>)> = value
@ -121,11 +121,11 @@ impl<'a> FromAst<'a, leo_ast::CircuitInitExpression> for CircuitInitExpression<'
let circuit_members = circuit.members.borrow(); let circuit_members = circuit.members.borrow();
for (name, member) in circuit_members.iter() { for (name, member) in circuit_members.iter() {
if defined_variables.contains(name) { if defined_variables.contains(name) {
return Err(LeoError::from(AsgError::overridden_circuit_member( return Err(AsgError::overridden_circuit_member(
&circuit.name.borrow().name, &circuit.name.borrow().name,
name, name,
&value.span, &value.span,
))); ))?;
} }
defined_variables.insert(name.clone()); defined_variables.insert(name.clone());
let type_: Type = if let CircuitMember::Variable(type_) = &member { let type_: Type = if let CircuitMember::Variable(type_) = &member {
@ -145,21 +145,21 @@ impl<'a> FromAst<'a, leo_ast::CircuitInitExpression> for CircuitInitExpression<'
}; };
values.push(((*identifier).clone(), Cell::new(received))); values.push(((*identifier).clone(), Cell::new(received)));
} else { } else {
return Err(LeoError::from(AsgError::missing_circuit_member( return Err(AsgError::missing_circuit_member(
&circuit.name.borrow().name, &circuit.name.borrow().name,
name, name,
&value.span, &value.span,
))); ))?;
} }
} }
for (name, (identifier, _expression)) in members.iter() { for (name, (identifier, _expression)) in members.iter() {
if circuit_members.get(*name).is_none() { if circuit_members.get(*name).is_none() {
return Err(LeoError::from(AsgError::extra_circuit_member( return Err(AsgError::extra_circuit_member(
&circuit.name.borrow().name, &circuit.name.borrow().name,
*name, name,
&identifier.span, &identifier.span,
))); ))?;
} }
} }
} }

View File

@ -85,11 +85,7 @@ impl<'a> FromAst<'a, leo_ast::ValueExpression> for Constant<'a> {
match expected_type.map(PartialType::full).flatten() { match expected_type.map(PartialType::full).flatten() {
Some(Type::Address) | None => (), Some(Type::Address) | None => (),
Some(x) => { Some(x) => {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(x, Type::Address, span))?;
&x.to_string(),
Some(&*Type::Address.to_string()),
span,
)));
} }
} }
Constant { Constant {
@ -102,11 +98,7 @@ impl<'a> FromAst<'a, leo_ast::ValueExpression> for Constant<'a> {
match expected_type.map(PartialType::full).flatten() { match expected_type.map(PartialType::full).flatten() {
Some(Type::Boolean) | None => (), Some(Type::Boolean) | None => (),
Some(x) => { Some(x) => {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(x, Type::Boolean, span))?;
&x.to_string(),
Some(&*Type::Boolean.to_string()),
span,
)));
} }
} }
Constant { Constant {
@ -115,7 +107,7 @@ impl<'a> FromAst<'a, leo_ast::ValueExpression> for Constant<'a> {
value: ConstValue::Boolean( value: ConstValue::Boolean(
value value
.parse::<bool>() .parse::<bool>()
.map_err(|_| LeoError::from(AsgError::invalid_boolean(value, span)))?, .map_err(|_| AsgError::invalid_boolean(value, span))?,
), ),
} }
} }
@ -123,11 +115,7 @@ impl<'a> FromAst<'a, leo_ast::ValueExpression> for Constant<'a> {
match expected_type.map(PartialType::full).flatten() { match expected_type.map(PartialType::full).flatten() {
Some(Type::Char) | None => (), Some(Type::Char) | None => (),
Some(x) => { Some(x) => {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(x, Type::Char, value.span()))?;
&x.to_string(),
Some(&*Type::Char.to_string()),
value.span(),
)));
} }
} }
@ -141,32 +129,20 @@ impl<'a> FromAst<'a, leo_ast::ValueExpression> for Constant<'a> {
match expected_type.map(PartialType::full).flatten() { match expected_type.map(PartialType::full).flatten() {
Some(Type::Field) | None => (), Some(Type::Field) | None => (),
Some(x) => { Some(x) => {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(x, Type::Field, span))?;
&x.to_string(),
Some(&*Type::Field.to_string()),
span,
)));
} }
} }
Constant { Constant {
parent: Cell::new(None), parent: Cell::new(None),
span: Some(span.clone()), span: Some(span.clone()),
value: ConstValue::Field( value: ConstValue::Field(value.parse().map_err(|_| AsgError::invalid_int(value, span))?),
value
.parse()
.map_err(|_| LeoError::from(AsgError::invalid_int(value, span)))?,
),
} }
} }
Group(value) => { Group(value) => {
match expected_type.map(PartialType::full).flatten() { match expected_type.map(PartialType::full).flatten() {
Some(Type::Group) | None => (), Some(Type::Group) | None => (),
Some(x) => { Some(x) => {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(x, Type::Group, value.span()))?;
&x.to_string(),
Some(&*Type::Group.to_string()),
value.span(),
)));
} }
} }
Constant { Constant {
@ -183,7 +159,7 @@ impl<'a> FromAst<'a, leo_ast::ValueExpression> for Constant<'a> {
} }
} }
Implicit(value, span) => match expected_type { Implicit(value, span) => match expected_type {
None => return Err(LeoError::from(AsgError::unresolved_type("unknown", span))), None => return Err(AsgError::unresolved_type("unknown", span))?,
Some(PartialType::Integer(Some(sub_type), _)) | Some(PartialType::Integer(None, Some(sub_type))) => { Some(PartialType::Integer(Some(sub_type), _)) | Some(PartialType::Integer(None, Some(sub_type))) => {
Constant { Constant {
parent: Cell::new(None), parent: Cell::new(None),
@ -194,11 +170,7 @@ impl<'a> FromAst<'a, leo_ast::ValueExpression> for Constant<'a> {
Some(PartialType::Type(Type::Field)) => Constant { Some(PartialType::Type(Type::Field)) => Constant {
parent: Cell::new(None), parent: Cell::new(None),
span: Some(span.clone()), span: Some(span.clone()),
value: ConstValue::Field( value: ConstValue::Field(value.parse().map_err(|_| AsgError::invalid_int(value, span))?),
value
.parse()
.map_err(|_| LeoError::from(AsgError::invalid_int(value, span)))?,
),
}, },
Some(PartialType::Type(Type::Group)) => Constant { Some(PartialType::Type(Type::Group)) => Constant {
parent: Cell::new(None), parent: Cell::new(None),
@ -211,11 +183,7 @@ impl<'a> FromAst<'a, leo_ast::ValueExpression> for Constant<'a> {
value: ConstValue::Address(value.clone()), value: ConstValue::Address(value.clone()),
}, },
Some(x) => { Some(x) => {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(x, "unknown", span))?;
&x.to_string(),
Some("unknown"),
span,
)));
} }
}, },
Integer(int_type, value, span) => { Integer(int_type, value, span) => {
@ -224,11 +192,7 @@ impl<'a> FromAst<'a, leo_ast::ValueExpression> for Constant<'a> {
Some(PartialType::Integer(None, Some(_))) => (), Some(PartialType::Integer(None, Some(_))) => (),
None => (), None => (),
Some(x) => { Some(x) => {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(x, int_type, span))?;
&x.to_string(),
Some(&*int_type.to_string()),
span,
)));
} }
} }
Constant { Constant {

View File

@ -91,11 +91,7 @@ impl<'a> FromAst<'a, leo_ast::TernaryExpression> for TernaryExpression<'a> {
let right = if_false.get().get_type().unwrap().into(); let right = if_false.get().get_type().unwrap().into();
if left != right { if left != right {
return Err(LeoError::from(AsgError::ternary_different_types( return Err(AsgError::ternary_different_types(left, right, &value.span))?;
&left.to_string(),
&right.to_string(),
&value.span,
)));
} }
Ok(TernaryExpression { Ok(TernaryExpression {

View File

@ -80,7 +80,7 @@ impl<'a> FromAst<'a, leo_ast::TupleAccessExpression> for TupleAccessExpression<'
.index .index
.value .value
.parse::<usize>() .parse::<usize>()
.map_err(|_| LeoError::from(AsgError::parse_index_error(&value.span)))?; .map_err(|_| AsgError::parse_index_error(&value.span))?;
let mut expected_tuple = vec![None; index + 1]; let mut expected_tuple = vec![None; index + 1];
expected_tuple[index] = expected_type; expected_tuple[index] = expected_type;
@ -89,11 +89,11 @@ impl<'a> FromAst<'a, leo_ast::TupleAccessExpression> for TupleAccessExpression<'
let tuple_type = tuple.get_type(); let tuple_type = tuple.get_type();
if let Some(Type::Tuple(_items)) = tuple_type { if let Some(Type::Tuple(_items)) = tuple_type {
} else { } else {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(
"a tuple", "a tuple",
tuple_type.map(|x| x.to_string()).as_deref(), tuple_type.map(|x| x.to_string()).unwrap_or("unknown".to_string()),
&value.span, &value.span,
))); ))?;
} }
Ok(TupleAccessExpression { Ok(TupleAccessExpression {

View File

@ -86,11 +86,11 @@ impl<'a> FromAst<'a, leo_ast::TupleInitExpression> for TupleInitExpression<'a> {
Some(PartialType::Tuple(sub_types)) => Some(sub_types), Some(PartialType::Tuple(sub_types)) => Some(sub_types),
None => None, None => None,
x => { x => {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(
"tuple", "tuple",
x.map(|x| x.to_string()).as_deref(), x.map(|x| x.to_string()).unwrap_or("unknown".to_string()),
&value.span, &value.span,
))); ))?;
} }
}; };
@ -98,11 +98,11 @@ impl<'a> FromAst<'a, leo_ast::TupleInitExpression> for TupleInitExpression<'a> {
// Expected type can be equal or less than actual size of a tuple. // Expected type can be equal or less than actual size of a tuple.
// Size of expected tuple can be based on accessed index. // Size of expected tuple can be based on accessed index.
if tuple_types.len() > value.elements.len() { if tuple_types.len() > value.elements.len() {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(
&*format!("tuple of length {}", tuple_types.len()), format!("tuple of length {}", tuple_types.len()),
Some(&*format!("tuple of length {}", value.elements.len())), format!("tuple of length {}", value.elements.len()),
&value.span, &value.span,
))); ))?;
} }
} }

View File

@ -95,11 +95,7 @@ impl<'a> FromAst<'a, leo_ast::UnaryExpression> for UnaryExpression<'a> {
UnaryOperation::Not => match expected_type.map(|x| x.full()).flatten() { UnaryOperation::Not => match expected_type.map(|x| x.full()).flatten() {
Some(Type::Boolean) | None => Some(Type::Boolean), Some(Type::Boolean) | None => Some(Type::Boolean),
Some(type_) => { Some(type_) => {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(type_, Type::Boolean, &value.span))?;
&type_.to_string(),
Some(&*Type::Boolean.to_string()),
&value.span,
)));
} }
}, },
UnaryOperation::Negate => match expected_type.map(|x| x.full()).flatten() { UnaryOperation::Negate => match expected_type.map(|x| x.full()).flatten() {
@ -108,22 +104,14 @@ impl<'a> FromAst<'a, leo_ast::UnaryExpression> for UnaryExpression<'a> {
Some(Type::Field) => Some(Type::Field), Some(Type::Field) => Some(Type::Field),
None => None, None => None,
Some(type_) => { Some(type_) => {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(type_, "integer, group, field", &value.span))?;
&type_.to_string(),
Some("integer, group, field"),
&value.span,
)));
} }
}, },
UnaryOperation::BitNot => match expected_type.map(|x| x.full()).flatten() { UnaryOperation::BitNot => match expected_type.map(|x| x.full()).flatten() {
Some(type_ @ Type::Integer(_)) => Some(type_), Some(type_ @ Type::Integer(_)) => Some(type_),
None => None, None => None,
Some(type_) => { Some(type_) => {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(type_, "integer", &value.span))?;
&type_.to_string(),
Some("integer"),
&value.span,
)));
} }
}, },
}; };
@ -138,7 +126,7 @@ impl<'a> FromAst<'a, leo_ast::UnaryExpression> for UnaryExpression<'a> {
}) })
.unwrap_or(false); .unwrap_or(false);
if is_expr_unsigned { if is_expr_unsigned {
return Err(LeoError::from(AsgError::unsigned_negation(&value.span))); return Err(AsgError::unsigned_negation(&value.span))?;
} }
} }
Ok(UnaryExpression { Ok(UnaryExpression {

View File

@ -140,10 +140,10 @@ impl<'a> FromAst<'a, leo_ast::Identifier> for &'a Expression<'a> {
if let Some(input) = scope.resolve_input() { if let Some(input) = scope.resolve_input() {
input.container input.container
} else { } else {
return Err(LeoError::from(AsgError::illegal_input_variable_reference( return Err(AsgError::illegal_input_variable_reference(
"attempted to reference input when none is in scope", "attempted to reference input when none is in scope",
&value.span, &value.span,
))); ))?;
} }
} else { } else {
match scope.resolve_variable(&value.name) { match scope.resolve_variable(&value.name) {
@ -156,7 +156,7 @@ impl<'a> FromAst<'a, leo_ast::Identifier> for &'a Expression<'a> {
value: ConstValue::Address(value.name.clone()), value: ConstValue::Address(value.name.clone()),
}))); })));
} }
return Err(LeoError::from(AsgError::unresolved_reference(&value.name, &value.span))); return Err(AsgError::unresolved_reference(&value.name, &value.span))?;
} }
} }
}; };
@ -171,13 +171,9 @@ impl<'a> FromAst<'a, leo_ast::Identifier> for &'a Expression<'a> {
if let Some(expected_type) = expected_type { if let Some(expected_type) = expected_type {
let type_ = expression let type_ = expression
.get_type() .get_type()
.ok_or_else(|| LeoError::from(AsgError::unresolved_reference(&value.name, &value.span)))?; .ok_or_else(|| AsgError::unresolved_reference(&value.name, &value.span))?;
if !expected_type.matches(&type_) { if !expected_type.matches(&type_) {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(expected_type, type_, &value.span))?;
&expected_type.to_string(),
Some(&*type_.to_string()),
&value.span,
)));
} }
} }

View File

@ -71,11 +71,11 @@ impl<'a> Circuit<'a> {
for member in value.members.iter() { for member in value.members.iter() {
if let leo_ast::CircuitMember::CircuitVariable(name, type_) = member { if let leo_ast::CircuitMember::CircuitVariable(name, type_) = member {
if members.contains_key(name.name.as_ref()) { if members.contains_key(name.name.as_ref()) {
return Err(LeoError::from(AsgError::redefined_circuit_member( return Err(AsgError::redefined_circuit_member(
&value.circuit_name.name, &value.circuit_name.name,
&name.name, &name.name,
&name.span, &name.span,
))); ))?;
} }
members.insert( members.insert(
name.name.to_string(), name.name.to_string(),
@ -98,18 +98,16 @@ impl<'a> Circuit<'a> {
for member in value.members.iter() { for member in value.members.iter() {
if let leo_ast::CircuitMember::CircuitFunction(function) = member { if let leo_ast::CircuitMember::CircuitFunction(function) = member {
if members.contains_key(function.identifier.name.as_ref()) { if members.contains_key(function.identifier.name.as_ref()) {
return Err(LeoError::from(AsgError::redefined_circuit_member( return Err(AsgError::redefined_circuit_member(
&value.circuit_name.name, &value.circuit_name.name,
&function.identifier.name, &function.identifier.name,
&function.identifier.span, &function.identifier.span,
))); ))?;
} }
let asg_function = Function::init(new_scope, function)?; let asg_function = Function::init(new_scope, function)?;
asg_function.circuit.replace(Some(circuit)); asg_function.circuit.replace(Some(circuit));
if asg_function.is_test() { if asg_function.is_test() {
return Err(LeoError::from(AsgError::circuit_test_function( return Err(AsgError::circuit_test_function(&function.identifier.span))?;
&function.identifier.span,
)));
} }
members.insert( members.insert(
function.identifier.name.to_string(), function.identifier.name.to_string(),

View File

@ -107,7 +107,7 @@ impl<'a> Function<'a> {
} }
} }
if qualifier != FunctionQualifier::Static && scope.circuit_self.get().is_none() { if qualifier != FunctionQualifier::Static && scope.circuit_self.get().is_none() {
return Err(LeoError::from(AsgError::invalid_self_in_global(&value.span))); return Err(AsgError::invalid_self_in_global(&value.span))?;
} }
let function = scope.context.alloc_function(Function { let function = scope.context.alloc_function(Function {
id: scope.context.get_id(), id: scope.context.get_id(),
@ -151,19 +151,16 @@ impl<'a> Function<'a> {
let main_block = BlockStatement::from_ast(self.scope, &value.block, None)?; let main_block = BlockStatement::from_ast(self.scope, &value.block, None)?;
let mut director = MonoidalDirector::new(ReturnPathReducer::new()); let mut director = MonoidalDirector::new(ReturnPathReducer::new());
if !director.reduce_block(&main_block).0 && !self.output.is_unit() { if !director.reduce_block(&main_block).0 && !self.output.is_unit() {
return Err(LeoError::from(AsgError::function_missing_return( return Err(AsgError::function_missing_return(&self.name.borrow().name, &value.span))?;
&self.name.borrow().name,
&value.span,
)));
} }
#[allow(clippy::never_loop)] // TODO @Protryon: How should we return multiple errors? #[allow(clippy::never_loop)] // TODO @Protryon: How should we return multiple errors?
for (span, error) in director.reducer().errors { for (span, error) in director.reducer().errors {
return Err(LeoError::from(AsgError::function_return_validation( return Err(AsgError::function_return_validation(
&self.name.borrow().name, &self.name.borrow().name,
&error, error,
&span, &span,
))); ))?;
} }
self.body self.body

View File

@ -164,10 +164,7 @@ impl<'a> Program<'a> {
)? { )? {
Some(x) => x, Some(x) => x,
None => { None => {
return Err(LeoError::from(AsgError::unresolved_import( return Err(AsgError::unresolved_import(pretty_package, &Span::default()))?;
&*pretty_package,
&Span::default(),
)));
} }
}; };
@ -199,10 +196,10 @@ impl<'a> Program<'a> {
} else if let Some(global_const) = resolved_package.global_consts.get(&name) { } else if let Some(global_const) = resolved_package.global_consts.get(&name) {
imported_global_consts.insert(name.clone(), *global_const); imported_global_consts.insert(name.clone(), *global_const);
} else { } else {
return Err(LeoError::from(AsgError::unresolved_import( return Err(AsgError::unresolved_import(
&*format!("{}.{}", pretty_package, name), format!("{}.{}", pretty_package, name),
&span, &span,
))); ))?;
} }
} }
ImportSymbol::Alias(name, alias) => { ImportSymbol::Alias(name, alias) => {
@ -213,10 +210,10 @@ impl<'a> Program<'a> {
} else if let Some(global_const) = resolved_package.global_consts.get(&name) { } else if let Some(global_const) = resolved_package.global_consts.get(&name) {
imported_global_consts.insert(alias.clone(), *global_const); imported_global_consts.insert(alias.clone(), *global_const);
} else { } else {
return Err(LeoError::from(AsgError::unresolved_import( return Err(AsgError::unresolved_import(
&*format!("{}.{}", pretty_package, name), format!("{}.{}", pretty_package, name),
&span, &span,
))); ))?;
} }
} }
} }
@ -307,10 +304,7 @@ impl<'a> Program<'a> {
let name = name.name.to_string(); let name = name.name.to_string();
if functions.contains_key(&name) { if functions.contains_key(&name) {
return Err(LeoError::from(AsgError::duplicate_function_definition( return Err(AsgError::duplicate_function_definition(name, &function.span))?;
&name,
&function.span,
)));
} }
functions.insert(name, asg_function); functions.insert(name, asg_function);

View File

@ -189,7 +189,7 @@ impl<'a> Scope<'a> {
let dimension = dimension let dimension = dimension
.value .value
.parse::<usize>() .parse::<usize>()
.map_err(|_| LeoError::from(AsgError::parse_index_error(span)))?; .map_err(|_| AsgError::parse_index_error(span))?;
item = Box::new(Type::Array(item, dimension)); item = Box::new(Type::Array(item, dimension));
} }
*item *item
@ -202,15 +202,15 @@ impl<'a> Scope<'a> {
), ),
Circuit(name) if name.name.as_ref() == "Self" => Type::Circuit( Circuit(name) if name.name.as_ref() == "Self" => Type::Circuit(
self.resolve_circuit_self() self.resolve_circuit_self()
.ok_or_else(|| LeoError::from(AsgError::unresolved_circuit(&name.name, &name.span)))?, .ok_or_else(|| AsgError::unresolved_circuit(&name.name, &name.span))?,
), ),
SelfType => Type::Circuit( SelfType => Type::Circuit(
self.resolve_circuit_self() self.resolve_circuit_self()
.ok_or_else(|| LeoError::from(AsgError::reference_self_outside_circuit(span)))?, .ok_or_else(|| AsgError::reference_self_outside_circuit(span))?,
), ),
Circuit(name) => Type::Circuit( Circuit(name) => Type::Circuit(
self.resolve_circuit(&name.name) self.resolve_circuit(&name.name)
.ok_or_else(|| LeoError::from(AsgError::unresolved_circuit(&name.name, &name.span)))?, .ok_or_else(|| AsgError::unresolved_circuit(&name.name, &name.span))?,
), ),
}) })
} }

View File

@ -66,25 +66,28 @@ impl<'a> FromAst<'a, leo_ast::AssignStatement> for &'a Statement<'a> {
statement: &leo_ast::AssignStatement, statement: &leo_ast::AssignStatement,
_expected_type: Option<PartialType<'a>>, _expected_type: Option<PartialType<'a>>,
) -> Result<Self, LeoError> { ) -> Result<Self, LeoError> {
let (name, span) = (&statement.assignee.identifier.name, &statement.assignee.identifier.span); let (name, span) = (
&statement.assignee.identifier.name.clone(),
&statement.assignee.identifier.span,
);
let variable = if name.as_ref() == "input" { let variable = if name.as_ref() == "input" {
if let Some(input) = scope.resolve_input() { if let Some(input) = scope.resolve_input() {
input.container input.container
} else { } else {
return Err(LeoError::from(AsgError::illegal_input_variable_reference( return Err(AsgError::illegal_input_variable_reference(
"attempted to reference input when none is in scope", "attempted to reference input when none is in scope",
&statement.span, &statement.span,
))); ))?;
} }
} else { } else {
scope scope
.resolve_variable(name) .resolve_variable(name)
.ok_or_else(|| LeoError::from(AsgError::unresolved_reference(name, span)))? .ok_or_else(|| AsgError::unresolved_reference(name, span))?
}; };
if !variable.borrow().mutable { if !variable.borrow().mutable {
return Err(LeoError::from(AsgError::immutable_assignment(name, &statement.span))); return Err(AsgError::immutable_assignment(name, &statement.span))?;
} }
let mut target_type: Option<PartialType> = Some(variable.borrow().type_.clone().into()); let mut target_type: Option<PartialType> = Some(variable.borrow().type_.clone().into());
@ -119,37 +122,29 @@ impl<'a> FromAst<'a, leo_ast::AssignStatement> for &'a Statement<'a> {
) { ) {
let left = match left { let left = match left {
ConstValue::Int(x) => x.to_usize().ok_or_else(|| { ConstValue::Int(x) => x.to_usize().ok_or_else(|| {
LeoError::from(AsgError::invalid_assign_index( AsgError::invalid_assign_index(name, x.to_string(), &statement.span)
name,
&x.to_string(),
&statement.span,
))
})?, })?,
_ => unimplemented!(), _ => unimplemented!(),
}; };
let right = match right { let right = match right {
ConstValue::Int(x) => x.to_usize().ok_or_else(|| { ConstValue::Int(x) => x.to_usize().ok_or_else(|| {
LeoError::from(AsgError::invalid_assign_index( AsgError::invalid_assign_index(name, x.to_string(), &statement.span)
name,
&x.to_string(),
&statement.span,
))
})?, })?,
_ => unimplemented!(), _ => unimplemented!(),
}; };
if right >= left { if right >= left {
target_type = Some(PartialType::Array(item.clone(), Some((right - left) as usize))) target_type = Some(PartialType::Array(item.clone(), Some((right - left) as usize)))
} else { } else {
return Err(LeoError::from(AsgError::invalid_backwards_assignment( return Err(AsgError::invalid_backwards_assignment(
name, name,
left, left,
right, right,
&statement.span, &statement.span,
))); ))?;
} }
} }
} }
_ => return Err(LeoError::from(AsgError::index_into_non_array(name, &statement.span))), _ => return Err(AsgError::index_into_non_array(name, &statement.span))?,
} }
AssignAccess::ArrayRange(Cell::new(left), Cell::new(right)) AssignAccess::ArrayRange(Cell::new(left), Cell::new(right))
@ -157,7 +152,7 @@ impl<'a> FromAst<'a, leo_ast::AssignStatement> for &'a Statement<'a> {
AstAssigneeAccess::ArrayIndex(index) => { AstAssigneeAccess::ArrayIndex(index) => {
target_type = match target_type.clone() { target_type = match target_type.clone() {
Some(PartialType::Array(item, _)) => item.map(|x| *x), Some(PartialType::Array(item, _)) => item.map(|x| *x),
_ => return Err(LeoError::from(AsgError::index_into_non_array(name, &statement.span))), _ => return Err(AsgError::index_into_non_array(name, &statement.span))?,
}; };
AssignAccess::ArrayIndex(Cell::new(<&Expression<'a>>::from_ast( AssignAccess::ArrayIndex(Cell::new(<&Expression<'a>>::from_ast(
scope, scope,
@ -169,12 +164,13 @@ impl<'a> FromAst<'a, leo_ast::AssignStatement> for &'a Statement<'a> {
let index = index let index = index
.value .value
.parse::<usize>() .parse::<usize>()
.map_err(|_| LeoError::from(AsgError::parse_index_error(span)))?; .map_err(|_| AsgError::parse_index_error(span))?;
target_type = match target_type { target_type = match target_type {
Some(PartialType::Tuple(types)) => types.get(index).cloned().ok_or_else(|| { Some(PartialType::Tuple(types)) => types
LeoError::from(AsgError::tuple_index_out_of_bounds(index, &statement.span)) .get(index)
})?, .cloned()
_ => return Err(LeoError::from(AsgError::index_into_non_tuple(name, &statement.span))), .ok_or_else(|| AsgError::tuple_index_out_of_bounds(index, &statement.span))?,
_ => return Err(AsgError::index_into_non_tuple(name, &statement.span))?,
}; };
AssignAccess::Tuple(index) AssignAccess::Tuple(index)
} }
@ -185,29 +181,26 @@ impl<'a> FromAst<'a, leo_ast::AssignStatement> for &'a Statement<'a> {
let members = circuit.members.borrow(); let members = circuit.members.borrow();
let member = members.get(name.name.as_ref()).ok_or_else(|| { let member = members.get(name.name.as_ref()).ok_or_else(|| {
LeoError::from(AsgError::unresolved_circuit_member( AsgError::unresolved_circuit_member(
&circuit.name.borrow().name, &circuit.name.borrow().name,
&name.name, &name.name,
&statement.span, &statement.span,
)) )
})?; })?;
let x = match &member { let x = match &member {
CircuitMember::Variable(type_) => type_.clone(), CircuitMember::Variable(type_) => type_.clone(),
CircuitMember::Function(_) => { CircuitMember::Function(_) => {
return Err(LeoError::from(AsgError::illegal_function_assign( return Err(AsgError::illegal_function_assign(&name.name, &statement.span))?;
&name.name,
&statement.span,
)));
} }
}; };
Some(x.partial()) Some(x.partial())
} }
_ => { _ => {
return Err(LeoError::from(AsgError::index_into_non_tuple( return Err(AsgError::index_into_non_tuple(
&statement.assignee.identifier.name, &statement.assignee.identifier.name,
&statement.span, &statement.span,
))); ))?;
} }
}; };
AssignAccess::Member(name.clone()) AssignAccess::Member(name.clone())

View File

@ -71,10 +71,7 @@ impl<'a> FromAst<'a, leo_ast::DefinitionStatement> for &'a Statement<'a> {
.collect::<Vec<String>>() .collect::<Vec<String>>()
.join(" ,"); .join(" ,");
return Err(LeoError::from(AsgError::invalid_const_assign( return Err(AsgError::invalid_const_assign(var_names, &statement.span))?;
&var_names,
&statement.span,
)));
} }
let type_ = type_.or_else(|| value.get_type()); let type_ = type_.or_else(|| value.get_type());
@ -83,10 +80,10 @@ impl<'a> FromAst<'a, leo_ast::DefinitionStatement> for &'a Statement<'a> {
let mut variables = vec![]; let mut variables = vec![];
if statement.variable_names.is_empty() { if statement.variable_names.is_empty() {
return Err(LeoError::from(AsgError::illegal_ast_structure( return Err(AsgError::illegal_ast_structure(
"cannot have 0 variable names in destructuring tuple", "cannot have 0 variable names in destructuring tuple",
&statement.span, &statement.span,
))); ))?;
} }
if statement.variable_names.len() == 1 { if statement.variable_names.len() == 1 {
// any return type is fine // any return type is fine
@ -98,11 +95,11 @@ impl<'a> FromAst<'a, leo_ast::DefinitionStatement> for &'a Statement<'a> {
output_types.extend(sub_types.clone().into_iter().map(Some).collect::<Vec<_>>()); output_types.extend(sub_types.clone().into_iter().map(Some).collect::<Vec<_>>());
} }
type_ => { type_ => {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(
&*format!("{}-ary tuple", statement.variable_names.len()), format!("{}-ary tuple", statement.variable_names.len()),
type_.map(|x| x.to_string()).as_deref(), type_.map(|x| x.to_string()).unwrap_or("unknown".to_string()),
&statement.span, &statement.span,
))); ))?;
} }
} }
} }
@ -111,9 +108,7 @@ impl<'a> FromAst<'a, leo_ast::DefinitionStatement> for &'a Statement<'a> {
variables.push(&*scope.context.alloc_variable(RefCell::new(InnerVariable { variables.push(&*scope.context.alloc_variable(RefCell::new(InnerVariable {
id: scope.context.get_id(), id: scope.context.get_id(),
name: variable.identifier.clone(), name: variable.identifier.clone(),
type_: type_.ok_or_else(|| { type_: type_.ok_or_else(|| AsgError::unresolved_type(&variable.identifier.name, &statement.span))?,
LeoError::from(AsgError::unresolved_type(&variable.identifier.name, &statement.span))
})?,
mutable: variable.mutable, mutable: variable.mutable,
const_: false, const_: false,
declaration: crate::VariableDeclaration::Definition, declaration: crate::VariableDeclaration::Definition,
@ -126,10 +121,7 @@ impl<'a> FromAst<'a, leo_ast::DefinitionStatement> for &'a Statement<'a> {
let mut variables = scope.variables.borrow_mut(); let mut variables = scope.variables.borrow_mut();
let var_name = variable.borrow().name.name.to_string(); let var_name = variable.borrow().name.name.to_string();
if variables.contains_key(&var_name) { if variables.contains_key(&var_name) {
return Err(LeoError::from(AsgError::duplicate_variable_definition( return Err(AsgError::duplicate_variable_definition(var_name, &statement.span))?;
&var_name,
&statement.span,
)));
} }
variables.insert(var_name, *variable); variables.insert(var_name, *variable);

View File

@ -50,14 +50,12 @@ impl<'a> FromAst<'a, leo_ast::IterationStatement> for &'a Statement<'a> {
// Return an error if start or stop is not constant. // Return an error if start or stop is not constant.
if !start.is_consty() { if !start.is_consty() {
return Err(LeoError::from(AsgError::unexpected_nonconst( return Err(AsgError::unexpected_nonconst(
&start.span().cloned().unwrap_or_default(), &start.span().cloned().unwrap_or_default(),
))); ))?;
} }
if !stop.is_consty() { if !stop.is_consty() {
return Err(LeoError::from(AsgError::unexpected_nonconst( return Err(AsgError::unexpected_nonconst(&stop.span().cloned().unwrap_or_default()))?;
&stop.span().cloned().unwrap_or_default(),
)));
} }
let variable = scope.context.alloc_variable(RefCell::new(InnerVariable { let variable = scope.context.alloc_variable(RefCell::new(InnerVariable {
@ -65,7 +63,7 @@ impl<'a> FromAst<'a, leo_ast::IterationStatement> for &'a Statement<'a> {
name: statement.variable.clone(), name: statement.variable.clone(),
type_: start type_: start
.get_type() .get_type()
.ok_or_else(|| LeoError::from(AsgError::unresolved_type(&statement.variable.name, &statement.span)))?, .ok_or_else(|| AsgError::unresolved_type(&statement.variable.name, &statement.span))?,
mutable: false, mutable: false,
const_: true, const_: true,
declaration: crate::VariableDeclaration::IterationDefinition, declaration: crate::VariableDeclaration::IterationDefinition,

View File

@ -25,9 +25,8 @@ version = "1.5.3"
path = "../errors" path = "../errors"
version = "1.5.3" version = "1.5.3"
[dependencies.eyre] [dependencies.backtrace]
version = "0.6.5" version = "0.3.61"
default-features = false
[dependencies.indexmap] [dependencies.indexmap]
version = "1.7.0" version = "1.7.0"
@ -43,12 +42,6 @@ features = [ "derive", "rc" ]
[dependencies.serde_json] [dependencies.serde_json]
version = "1.0" version = "1.0"
[dependencies.anyhow]
version = "1.0"
[dependencies.thiserror]
version = "1.0"
[dependencies.tendril] [dependencies.tendril]
version = "0.4" version = "0.4"

View File

@ -62,9 +62,9 @@ pub use self::types::*;
mod node; mod node;
pub use node::*; pub use node::*;
use leo_errors::LeoError; use leo_errors::{AstError, LeoError};
use eyre::eyre; use backtrace::Backtrace;
/// The abstract syntax tree (AST) for a Leo program. /// The abstract syntax tree (AST) for a Leo program.
/// ///
@ -100,25 +100,31 @@ impl Ast {
/// Serializes the ast into a JSON string. /// Serializes the ast into a JSON string.
pub fn to_json_string(&self) -> Result<String, LeoError> { pub fn to_json_string(&self) -> Result<String, LeoError> {
Ok(serde_json::to_string_pretty(&self.ast).map_err(|e| eyre!(e))?) Ok(serde_json::to_string_pretty(&self.ast)
.map_err(|e| AstError::failed_to_convert_ast_to_json_string(&e, Backtrace::new()))?)
} }
/// Serializes the ast into a JSON file.
pub fn to_json_file(&self, mut path: std::path::PathBuf, file_name: &str) -> Result<(), LeoError> { pub fn to_json_file(&self, mut path: std::path::PathBuf, file_name: &str) -> Result<(), LeoError> {
path.push(file_name); path.push(file_name);
let file = std::fs::File::create(path).map_err(|e| eyre!(e))?; let file = std::fs::File::create(&path)
.map_err(|e| AstError::failed_to_create_ast_json_file(&path, &e, Backtrace::new()))?;
let writer = std::io::BufWriter::new(file); let writer = std::io::BufWriter::new(file);
serde_json::to_writer_pretty(writer, &self.ast).map_err(|e| eyre!(e))?; Ok(serde_json::to_writer_pretty(writer, &self.ast)
Ok(()) .map_err(|e| AstError::failed_to_write_ast_to_json_file(&path, &e, Backtrace::new()))?)
} }
/// Deserializes the JSON string into a ast. /// Deserializes the JSON string into a ast.
pub fn from_json_string(json: &str) -> Result<Self, LeoError> { pub fn from_json_string(json: &str) -> Result<Self, LeoError> {
let ast: Program = serde_json::from_str(json).map_err(|e| eyre!(e))?; let ast: Program = serde_json::from_str(json)
.map_err(|e| AstError::failed_to_read_json_string_to_ast(&e, Backtrace::new()))?;
Ok(Self { ast }) Ok(Self { ast })
} }
/// Deserializes the JSON string into a ast from a file.
pub fn from_json_file(path: std::path::PathBuf) -> Result<Self, LeoError> { pub fn from_json_file(path: std::path::PathBuf) -> Result<Self, LeoError> {
let data = std::fs::read_to_string(path).map_err(|e| eyre!(e))?; let data = std::fs::read_to_string(&path)
.map_err(|e| AstError::failed_to_read_json_file(&path, &e, Backtrace::new()))?;
Self::from_json_string(&data) Self::from_json_string(&data)
} }
} }

View File

@ -20,7 +20,7 @@ use leo_errors::{AstError, LeoError, Span};
/// Replace Self when it is in a enclosing circuit type. /// Replace Self when it is in a enclosing circuit type.
/// Error when Self is outside an enclosing circuit type. /// Error when Self is outside an enclosing circuit type.
/// Tuple array types and expressions expand to nested arrays. /// Tuple array types and expressions expand to nested arrays.
/// Tuple array types and expressions error if a size of 0 is given.anyhow /// Tuple array types and expressions error if a size of 0 is given.
/// Compound operators become simple assignments. /// Compound operators become simple assignments.
/// Functions missing output type return a empty tuple. /// Functions missing output type return a empty tuple.
pub struct Canonicalizer { pub struct Canonicalizer {
@ -469,7 +469,7 @@ impl ReconstructingReducer for Canonicalizer {
match new { match new {
Type::Array(type_, mut dimensions) => { Type::Array(type_, mut dimensions) => {
if dimensions.is_zero() { if dimensions.is_zero() {
return Err(LeoError::from(AstError::invalid_array_dimension_size(span))); return Err(AstError::invalid_array_dimension_size(span))?;
} }
let mut next = Type::Array(type_, ArrayDimensions(vec![dimensions.remove_last().unwrap()])); let mut next = Type::Array(type_, ArrayDimensions(vec![dimensions.remove_last().unwrap()]));
@ -486,14 +486,14 @@ impl ReconstructingReducer for Canonicalizer {
Ok(array) Ok(array)
} }
Type::SelfType if !self.in_circuit => Err(LeoError::from(AstError::big_self_outside_of_circuit(span))), Type::SelfType if !self.in_circuit => Err(AstError::big_self_outside_of_circuit(span))?,
_ => Ok(new.clone()), _ => Ok(new.clone()),
} }
} }
fn reduce_string(&mut self, string: &[Char], span: &Span) -> Result<Expression, LeoError> { fn reduce_string(&mut self, string: &[Char], span: &Span) -> Result<Expression, LeoError> {
if string.is_empty() { if string.is_empty() {
return Err(LeoError::from(AstError::empty_string(span))); return Err(AstError::empty_string(span))?;
} }
let mut elements = Vec::new(); let mut elements = Vec::new();
@ -552,7 +552,7 @@ impl ReconstructingReducer for Canonicalizer {
element: Expression, element: Expression,
) -> Result<ArrayInitExpression, LeoError> { ) -> Result<ArrayInitExpression, LeoError> {
if array_init.dimensions.is_zero() { if array_init.dimensions.is_zero() {
return Err(LeoError::from(AstError::invalid_array_dimension_size(&array_init.span))); return Err(AstError::invalid_array_dimension_size(&array_init.span))?;
} }
let element = Box::new(element); let element = Box::new(element);

View File

@ -398,7 +398,7 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
match &console_function_call.function { match &console_function_call.function {
ConsoleFunction::Error(_) => ConsoleFunction::Error(formatted), ConsoleFunction::Error(_) => ConsoleFunction::Error(formatted),
ConsoleFunction::Log(_) => ConsoleFunction::Log(formatted), ConsoleFunction::Log(_) => ConsoleFunction::Log(formatted),
_ => return Err(LeoError::from(AstError::impossible_console_assert_call(&args.span))), _ => return Err(AstError::impossible_console_assert_call(&args.span))?,
} }
} }
}; };

View File

@ -90,10 +90,6 @@ version = "0.3.61"
[dependencies.bincode] [dependencies.bincode]
version = "1.3" version = "1.3"
[dependencies.eyre]
version = "0.6.5"
default-features = false
[dependencies.hex] [dependencies.hex]
version = "0.4.2" version = "0.4.2"

View File

@ -27,7 +27,7 @@ use crate::{
pub use leo_asg::{new_context, AsgContext as Context, AsgContext}; pub use leo_asg::{new_context, AsgContext as Context, AsgContext};
use leo_asg::{Asg, AsgPass, Program as AsgProgram}; use leo_asg::{Asg, AsgPass, Program as AsgProgram};
use leo_ast::{Input, MainInput, Program as AstProgram}; use leo_ast::{Input, MainInput, Program as AstProgram};
use leo_errors::{CompilerError, LeoError, SnarkVMError}; use leo_errors::{CompilerError, LeoError};
use leo_input::LeoInputParser; use leo_input::LeoInputParser;
use leo_package::inputs::InputPairs; use leo_package::inputs::InputPairs;
use leo_parser::parse_ast; use leo_parser::parse_ast;
@ -38,7 +38,6 @@ use snarkvm_fields::PrimeField;
use snarkvm_r1cs::{ConstraintSynthesizer, ConstraintSystem, SynthesisError}; use snarkvm_r1cs::{ConstraintSynthesizer, ConstraintSystem, SynthesisError};
use backtrace::Backtrace; use backtrace::Backtrace;
use eyre::eyre;
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
use std::{ use std::{
fs, fs,
@ -227,13 +226,8 @@ impl<'a, F: PrimeField, G: GroupType<F>> Compiler<'a, F, G> {
/// ///
pub fn parse_program(&mut self) -> Result<(), LeoError> { pub fn parse_program(&mut self) -> Result<(), LeoError> {
// Load the program file. // Load the program file.
let content = fs::read_to_string(&self.main_file_path).map_err(|e| { let content = fs::read_to_string(&self.main_file_path)
LeoError::from(CompilerError::file_read_error( .map_err(|e| CompilerError::file_read_error(self.main_file_path.clone(), e, Backtrace::new()))?;
self.main_file_path.clone(),
eyre!(e),
Backtrace::new(),
))
})?;
self.parse_program_from_string(&content) self.parse_program_from_string(&content)
} }
@ -330,13 +324,8 @@ impl<'a, F: PrimeField, G: GroupType<F>> Compiler<'a, F, G> {
/// ///
pub fn checksum(&self) -> Result<String, LeoError> { pub fn checksum(&self) -> Result<String, LeoError> {
// Read in the main file as string // Read in the main file as string
let unparsed_file = fs::read_to_string(&self.main_file_path).map_err(|e| { let unparsed_file = fs::read_to_string(&self.main_file_path)
LeoError::from(CompilerError::file_read_error( .map_err(|e| CompilerError::file_read_error(self.main_file_path.clone(), e, Backtrace::new()))?;
self.main_file_path.clone(),
eyre!(e),
Backtrace::new(),
))
})?;
// Hash the file contents // Hash the file contents
let mut hasher = Sha256::new(); let mut hasher = Sha256::new();
@ -356,8 +345,8 @@ impl<'a, F: PrimeField, G: GroupType<F>> Compiler<'a, F, G> {
system_parameters: &SystemParameters<Components>, system_parameters: &SystemParameters<Components>,
) -> Result<bool, LeoError> { ) -> Result<bool, LeoError> {
// TODO CONVERT STATE ERROR TO LEO ERROR // TODO CONVERT STATE ERROR TO LEO ERROR
let result = verify_local_data_commitment(system_parameters, &self.program_input) let result = verify_local_data_commitment(system_parameters, &self.program_input).unwrap();
.map_err(|e| LeoError::from(SnarkVMError::from(eyre!(e))))?; // .map_err(|e| SnarkVMError::new(e))?;
Ok(result) Ok(result)
} }

View File

@ -45,14 +45,13 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
let result_option = match assert_expression { let result_option = match assert_expression {
ConstrainedValue::Boolean(boolean) => boolean.get_value(), ConstrainedValue::Boolean(boolean) => boolean.get_value(),
_ => { _ => {
return Err(LeoError::from(CompilerError::console_assertion_must_be_boolean(span))); return Err(CompilerError::console_assertion_must_be_boolean(span))?;
} }
}; };
let result_bool = let result_bool = result_option.ok_or_else(|| CompilerError::console_assertion_depends_on_input(span))?;
result_option.ok_or_else(|| LeoError::from(CompilerError::console_assertion_depends_on_input(span)))?;
if !result_bool { if !result_bool {
return Err(LeoError::from(CompilerError::console_assertion_failed(span))); return Err(CompilerError::console_assertion_failed(span))?;
} }
Ok(()) Ok(())

View File

@ -51,13 +51,11 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
let parameter = match args.parameters.get(arg_index) { let parameter = match args.parameters.get(arg_index) {
Some(index) => index, Some(index) => index,
None => { None => {
return Err(LeoError::from( return Err(CompilerError::console_container_parameter_length_mismatch(
CompilerError::console_container_parameter_length_mismatch( arg_index + 1,
arg_index + 1, args.parameters.len(),
args.parameters.len(), &args.span,
&args.span, ))?;
),
));
} }
}; };
out.push(self.enforce_expression(cs, parameter.get())?.to_string()); out.push(self.enforce_expression(cs, parameter.get())?.to_string());
@ -69,16 +67,12 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
substring.push('}'); substring.push('}');
escape_right_bracket = true; escape_right_bracket = true;
} else { } else {
return Err(LeoError::from(CompilerError::console_fmt_expected_escaped_right_brace( return Err(CompilerError::console_fmt_expected_escaped_right_brace(&args.span))?;
&args.span,
)));
} }
} }
} }
_ if in_container => { _ if in_container => {
return Err(LeoError::from(CompilerError::console_fmt_expected_left_or_right_brace( return Err(CompilerError::console_fmt_expected_left_or_right_brace(&args.span))?;
&args.span,
)));
} }
_ => substring.push(*scalar), _ => substring.push(*scalar),
}, },
@ -92,13 +86,11 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
// Check that containers and parameters match // Check that containers and parameters match
if arg_index != args.parameters.len() { if arg_index != args.parameters.len() {
return Err(LeoError::from( return Err(CompilerError::console_container_parameter_length_mismatch(
CompilerError::console_container_parameter_length_mismatch( arg_index,
arg_index, args.parameters.len(),
args.parameters.len(), &args.span,
&args.span, ))?;
),
));
} }
Ok(out.join("")) Ok(out.join(""))

View File

@ -49,7 +49,7 @@ pub fn generate_constraints<'a, F: PrimeField, G: GroupType<F>, CS: ConstraintSy
let result = resolved_program.enforce_main_function(cs, function, input)?; let result = resolved_program.enforce_main_function(cs, function, input)?;
Ok(result) Ok(result)
} }
_ => Err(CompilerError::no_main_function(Backtrace::new()).into()), _ => Err(CompilerError::no_main_function(Backtrace::new()))?,
} }
} }
@ -104,14 +104,11 @@ pub fn generate_test_constraints<'a, F: PrimeField, G: GroupType<F>>(
{ {
Some(pair) => pair.to_owned(), Some(pair) => pair.to_owned(),
None => { None => {
return Err(LeoError::from(CompilerError::invalid_test_context( return Err(CompilerError::invalid_test_context(file_name, Backtrace::new()))?;
file_name.to_string(),
Backtrace::new(),
)));
} }
} }
} }
None => default.ok_or_else(|| LeoError::from(CompilerError::no_test_input(Backtrace::new())))?, None => default.ok_or_else(|| CompilerError::no_test_input(Backtrace::new()))?,
}; };
// parse input files to abstract syntax trees // parse input files to abstract syntax trees

View File

@ -38,9 +38,9 @@ pub fn enforce_add<'a, F: PrimeField, G: GroupType<F>, CS: ConstraintSystem<F>>(
(ConstrainedValue::Group(point_1), ConstrainedValue::Group(point_2)) => { (ConstrainedValue::Group(point_1), ConstrainedValue::Group(point_2)) => {
Ok(ConstrainedValue::Group(point_1.add(cs, &point_2, span)?)) Ok(ConstrainedValue::Group(point_1.add(cs, &point_2, span)?))
} }
(val_1, val_2) => Err(LeoError::from(CompilerError::incompatible_types( (val_1, val_2) => Err(CompilerError::incompatible_types(
format!("{} + {}", val_1, val_2), format!("{} + {}", val_1, val_2),
span, span,
))), ))?,
} }
} }

View File

@ -25,8 +25,5 @@ pub fn evaluate_bit_not<'a, F: PrimeField, G: GroupType<F>>(
value: ConstrainedValue<'a, F, G>, value: ConstrainedValue<'a, F, G>,
span: &Span, span: &Span,
) -> Result<ConstrainedValue<'a, F, G>, LeoError> { ) -> Result<ConstrainedValue<'a, F, G>, LeoError> {
Err(LeoError::from(CompilerError::cannot_evaluate_expression( Err(CompilerError::cannot_evaluate_expression(format!("!{}", value), span))?
format!("!{}", value),
span,
)))
} }

View File

@ -35,9 +35,9 @@ pub fn enforce_div<'a, F: PrimeField, G: GroupType<F>, CS: ConstraintSystem<F>>(
(ConstrainedValue::Field(field_1), ConstrainedValue::Field(field_2)) => { (ConstrainedValue::Field(field_1), ConstrainedValue::Field(field_2)) => {
Ok(ConstrainedValue::Field(field_1.div(cs, &field_2, span)?)) Ok(ConstrainedValue::Field(field_1.div(cs, &field_2, span)?))
} }
(val_1, val_2) => Err(LeoError::from(CompilerError::incompatible_types( (val_1, val_2) => Err(CompilerError::incompatible_types(
format!("{} / {}", val_1, val_2,), format!("{} / {}", val_1, val_2,),
span, span,
))), ))?,
} }
} }

View File

@ -35,9 +35,9 @@ pub fn enforce_mul<'a, F: PrimeField, G: GroupType<F>, CS: ConstraintSystem<F>>(
(ConstrainedValue::Field(field_1), ConstrainedValue::Field(field_2)) => { (ConstrainedValue::Field(field_1), ConstrainedValue::Field(field_2)) => {
Ok(ConstrainedValue::Field(field_1.mul(cs, &field_2, span)?)) Ok(ConstrainedValue::Field(field_1.mul(cs, &field_2, span)?))
} }
(val_1, val_2) => Err(LeoError::from(CompilerError::incompatible_types( (val_1, val_2) => Err(CompilerError::incompatible_types(
format!("{} * {}", val_1, val_2), format!("{} * {}", val_1, val_2),
span, span,
))), ))?,
} }
} }

View File

@ -31,9 +31,6 @@ pub fn enforce_negate<'a, F: PrimeField, G: GroupType<F>, CS: ConstraintSystem<F
ConstrainedValue::Integer(integer) => Ok(ConstrainedValue::Integer(integer.negate(cs, span)?)), ConstrainedValue::Integer(integer) => Ok(ConstrainedValue::Integer(integer.negate(cs, span)?)),
ConstrainedValue::Field(field) => Ok(ConstrainedValue::Field(field.negate(cs, span)?)), ConstrainedValue::Field(field) => Ok(ConstrainedValue::Field(field.negate(cs, span)?)),
ConstrainedValue::Group(group) => Ok(ConstrainedValue::Group(group.negate(cs, span)?)), ConstrainedValue::Group(group) => Ok(ConstrainedValue::Group(group.negate(cs, span)?)),
value => Err(LeoError::from(CompilerError::incompatible_types( value => Err(CompilerError::incompatible_types(format!("-{}", value), span))?,
format!("-{}", value),
span,
))),
} }
} }

View File

@ -32,9 +32,9 @@ pub fn enforce_pow<'a, F: PrimeField, G: GroupType<F>, CS: ConstraintSystem<F>>(
(ConstrainedValue::Integer(num_1), ConstrainedValue::Integer(num_2)) => { (ConstrainedValue::Integer(num_1), ConstrainedValue::Integer(num_2)) => {
Ok(ConstrainedValue::Integer(num_1.pow(cs, num_2, span)?)) Ok(ConstrainedValue::Integer(num_1.pow(cs, num_2, span)?))
} }
(val_1, val_2) => Err(LeoError::from(CompilerError::incompatible_types( (val_1, val_2) => Err(CompilerError::incompatible_types(
format!("{} ** {}", val_1, val_2,), format!("{} ** {}", val_1, val_2,),
span, span,
))), ))?,
} }
} }

View File

@ -38,9 +38,9 @@ pub fn enforce_sub<'a, F: PrimeField, G: GroupType<F>, CS: ConstraintSystem<F>>(
(ConstrainedValue::Group(point_1), ConstrainedValue::Group(point_2)) => { (ConstrainedValue::Group(point_1), ConstrainedValue::Group(point_2)) => {
Ok(ConstrainedValue::Group(point_1.sub(cs, &point_2, span)?)) Ok(ConstrainedValue::Group(point_1.sub(cs, &point_2, span)?))
} }
(val_1, val_2) => Err(LeoError::from(CompilerError::incompatible_types( (val_1, val_2) => Err(CompilerError::incompatible_types(
format!("{} - {}", val_1, val_2), format!("{} - {}", val_1, val_2),
span, span,
))), ))?,
} }
} }

View File

@ -28,7 +28,6 @@ use crate::{
use leo_asg::{ConstInt, Expression}; use leo_asg::{ConstInt, Expression};
use leo_errors::{CompilerError, LeoError, Span}; use leo_errors::{CompilerError, LeoError, Span};
use eyre::eyre;
use snarkvm_fields::PrimeField; use snarkvm_fields::PrimeField;
use snarkvm_gadgets::{ use snarkvm_gadgets::{
boolean::Boolean, boolean::Boolean,
@ -63,13 +62,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
let mut unique_namespace = cs.ns(|| namespace_string); let mut unique_namespace = cs.ns(|| namespace_string);
bounds_check bounds_check
.enforce_equal(&mut unique_namespace, &Boolean::Constant(true)) .enforce_equal(&mut unique_namespace, &Boolean::Constant(true))
.map_err(|e| { .map_err(|e| CompilerError::cannot_enforce_expression("array bounds check", e, span))?;
LeoError::from(CompilerError::cannot_enforce_expression(
"array bounds check".to_string(),
eyre!(e),
span,
))
})?;
Ok(()) Ok(())
} }
@ -83,24 +76,25 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
) -> Result<ConstrainedValue<'a, F, G>, LeoError> { ) -> Result<ConstrainedValue<'a, F, G>, LeoError> {
let mut array = match self.enforce_expression(cs, array)? { let mut array = match self.enforce_expression(cs, array)? {
ConstrainedValue::Array(array) => array, ConstrainedValue::Array(array) => array,
value => return Err(LeoError::from(CompilerError::undefined_array(value.to_string(), span))), value => return Err(CompilerError::undefined_array(value.to_string(), span))?,
}; };
let index_resolved = self.enforce_index(cs, index, span)?; let index_resolved = self.enforce_index(cs, index, span)?;
if let Some(resolved) = index_resolved.to_usize() { if let Some(resolved) = index_resolved.to_usize() {
if resolved >= array.len() { if resolved >= array.len() {
return Err(LeoError::from(CompilerError::array_index_out_of_bounds(resolved, span))); return Err(CompilerError::array_index_out_of_bounds(resolved, span))?;
} }
Ok(array[resolved].to_owned()) Ok(array[resolved].to_owned())
} else { } else {
if array.is_empty() { if array.is_empty() {
return Err(LeoError::from(CompilerError::array_index_out_of_bounds(0, span))); return Err(CompilerError::array_index_out_of_bounds(0, span))?;
} }
{ {
let array_len: u32 = array let array_len: u32 = array
.len() .len()
.try_into() .try_into()
.map_err(|_| LeoError::from(CompilerError::array_length_out_of_bounds(span)))?; .map_err(|_| CompilerError::array_length_out_of_bounds(span))?;
self.array_bounds_check(cs, &index_resolved, array_len, span)?; self.array_bounds_check(cs, &index_resolved, array_len, span)?;
} }
@ -111,23 +105,17 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
let index_bounded = i let index_bounded = i
.try_into() .try_into()
.map_err(|_| LeoError::from(CompilerError::array_index_out_of_legal_bounds(span)))?; .map_err(|_| CompilerError::array_index_out_of_legal_bounds(span))?;
let const_index = ConstInt::U32(index_bounded).cast_to(&index_resolved.get_type()); let const_index = ConstInt::U32(index_bounded).cast_to(&index_resolved.get_type());
let index_comparison = index_resolved let index_comparison = index_resolved
.evaluate_equal(eq_namespace, &Integer::new(&const_index)) .evaluate_equal(eq_namespace, &Integer::new(&const_index))
.map_err(|_| LeoError::from(CompilerError::cannot_evaluate_expression("==".to_string(), span)))?; .map_err(|_| CompilerError::cannot_evaluate_expression("==", span))?;
let unique_namespace = let unique_namespace =
cs.ns(|| format!("select array access {} {}:{}", i, span.line_start, span.col_start)); cs.ns(|| format!("select array access {} {}:{}", i, span.line_start, span.col_start));
let value = let value =
ConstrainedValue::conditionally_select(unique_namespace, &index_comparison, &item, &current_value) ConstrainedValue::conditionally_select(unique_namespace, &index_comparison, &item, &current_value)
.map_err(|e| { .map_err(|e| CompilerError::cannot_enforce_expression("conditional select", e, span))?;
LeoError::from(CompilerError::cannot_enforce_expression(
"conditional select".to_string(),
eyre!(e),
span,
))
})?;
current_value = value; current_value = value;
} }
Ok(current_value) Ok(current_value)
@ -146,7 +134,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
) -> Result<ConstrainedValue<'a, F, G>, LeoError> { ) -> Result<ConstrainedValue<'a, F, G>, LeoError> {
let array = match self.enforce_expression(cs, array)? { let array = match self.enforce_expression(cs, array)? {
ConstrainedValue::Array(array) => array, ConstrainedValue::Array(array) => array,
value => return Err(LeoError::from(CompilerError::undefined_array(value.to_string(), span))), value => return Err(CompilerError::undefined_array(value, span))?,
}; };
let from_resolved = match left { let from_resolved = match left {
@ -159,7 +147,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
let index_bounded: u32 = array let index_bounded: u32 = array
.len() .len()
.try_into() .try_into()
.map_err(|_| LeoError::from(CompilerError::array_length_out_of_bounds(span)))?; .map_err(|_| CompilerError::array_length_out_of_bounds(span))?;
Integer::new(&ConstInt::U32(index_bounded)) Integer::new(&ConstInt::U32(index_bounded))
} // Array slice ends at array length } // Array slice ends at array length
}; };
@ -171,10 +159,10 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
}; };
Ok(if let Some((left, right)) = const_dimensions { Ok(if let Some((left, right)) = const_dimensions {
if right - left != length { if right - left != length {
return Err(LeoError::from(CompilerError::array_invalid_slice_length(span))); return Err(CompilerError::array_invalid_slice_length(span))?;
} }
if right > array.len() { if right > array.len() {
return Err(LeoError::from(CompilerError::array_index_out_of_bounds(right, span))); return Err(CompilerError::array_index_out_of_bounds(right, span))?;
} }
ConstrainedValue::Array(array[left..right].to_owned()) ConstrainedValue::Array(array[left..right].to_owned())
} else { } else {
@ -196,13 +184,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
let mut unique_namespace = cs.ns(|| namespace_string); let mut unique_namespace = cs.ns(|| namespace_string);
calc_len calc_len
.enforce_equal(&mut unique_namespace, &Integer::new(&ConstInt::U32(length as u32))) .enforce_equal(&mut unique_namespace, &Integer::new(&ConstInt::U32(length as u32)))
.map_err(|e| { .map_err(|e| CompilerError::cannot_enforce_expression("array length check", e, span))?;
LeoError::from(CompilerError::cannot_enforce_expression(
"array length check".to_string(),
eyre!(e),
span,
))
})?;
} }
{ {
let bounds_check = evaluate_le::<F, G, _>( let bounds_check = evaluate_le::<F, G, _>(
@ -222,13 +204,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
let mut unique_namespace = cs.ns(|| namespace_string); let mut unique_namespace = cs.ns(|| namespace_string);
bounds_check bounds_check
.enforce_equal(&mut unique_namespace, &Boolean::Constant(true)) .enforce_equal(&mut unique_namespace, &Boolean::Constant(true))
.map_err(|e| { .map_err(|e| CompilerError::cannot_enforce_expression("array bounds check", e, span))?;
LeoError::from(CompilerError::cannot_enforce_expression(
"array bounds check".to_string(),
eyre!(e),
span,
))
})?;
} }
let mut windows = array.windows(length); let mut windows = array.windows(length);
let mut result = ConstrainedValue::Array(vec![]); let mut result = ConstrainedValue::Array(vec![]);
@ -257,13 +233,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
let unique_namespace = let unique_namespace =
unique_namespace.ns(|| format!("array index {} {}:{}", i, span.line_start, span.col_start)); unique_namespace.ns(|| format!("array index {} {}:{}", i, span.line_start, span.col_start));
result = ConstrainedValue::conditionally_select(unique_namespace, &equality, &array_value, &result) result = ConstrainedValue::conditionally_select(unique_namespace, &equality, &array_value, &result)
.map_err(|e| { .map_err(|e| CompilerError::cannot_enforce_expression("conditional select", e, span))?;
LeoError::from(CompilerError::cannot_enforce_expression(
"conditional select".to_string(),
eyre!(e),
span,
))
})?;
} }
result result
}) })

View File

@ -33,7 +33,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
array: &[(Cell<&'a Expression<'a>>, bool)], array: &[(Cell<&'a Expression<'a>>, bool)],
span: &Span, span: &Span,
) -> Result<ConstrainedValue<'a, F, G>, LeoError> { ) -> Result<ConstrainedValue<'a, F, G>, LeoError> {
let expected_dimension = None; let expected_dimension: Option<usize> = None;
let mut result = vec![]; let mut result = vec![];
for (element, is_spread) in array.iter() { for (element, is_spread) in array.iter() {
@ -52,11 +52,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
if let Some(dimension) = expected_dimension { if let Some(dimension) = expected_dimension {
// Return an error if the expected dimension != the actual dimension. // Return an error if the expected dimension != the actual dimension.
if dimension != result.len() { if dimension != result.len() {
return Err(LeoError::from(CompilerError::unexpected_array_length( return Err(CompilerError::unexpected_array_length(dimension, result.len(), span))?;
dimension,
result.len(),
span,
)));
} }
} }

View File

@ -32,10 +32,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
) -> Result<Integer, LeoError> { ) -> Result<Integer, LeoError> {
match self.enforce_expression(cs, index)? { match self.enforce_expression(cs, index)? {
ConstrainedValue::Integer(number) => Ok(number), ConstrainedValue::Integer(number) => Ok(number),
value => Err(LeoError::from(CompilerError::invalid_index_expression( value => Err(CompilerError::invalid_index_expression(value, span))?,
value.to_string(),
span,
))),
} }
} }
} }

View File

@ -40,20 +40,22 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
Ok(member.1) Ok(member.1)
} else { } else {
Err(CompilerError::undefined_circuit_member_access( Err(CompilerError::undefined_circuit_member_access(
expr.circuit.get().name.borrow().to_string(), expr.circuit.get().name.borrow(),
expr.member.to_string(), &expr.member.name,
&expr.member.span, &expr.member.span,
) ))?
.into())
} }
} }
value => Err(LeoError::from(CompilerError::undefined_circuit( value => Err(CompilerError::undefined_circuit(
value.to_string(), value,
&target.span().cloned().unwrap_or_default(), &target.span().cloned().unwrap_or_default(),
))), ))?,
} }
} else { } else {
Err(CompilerError::invalid_circuit_static_member_access(expr.member.to_string(), &expr.member.span).into()) Err(CompilerError::invalid_circuit_static_member_access(
&expr.member.name,
&expr.member.span,
))?
} }
} }
} }

View File

@ -50,10 +50,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
resolved_members.push(ConstrainedCircuitMember(name.clone(), variable_value)); resolved_members.push(ConstrainedCircuitMember(name.clone(), variable_value));
} }
_ => { _ => {
return Err(LeoError::from(CompilerError::expected_circuit_member( return Err(CompilerError::expected_circuit_member(name, span))?;
name.to_string(),
span,
)));
} }
} }
} }

View File

@ -20,7 +20,6 @@ use crate::{program::ConstrainedProgram, value::ConstrainedValue, GroupType};
use leo_asg::Expression; use leo_asg::Expression;
use leo_errors::{CompilerError, LeoError, Span}; use leo_errors::{CompilerError, LeoError, Span};
use eyre::eyre;
use snarkvm_fields::PrimeField; use snarkvm_fields::PrimeField;
use snarkvm_gadgets::traits::select::CondSelectGadget; use snarkvm_gadgets::traits::select::CondSelectGadget;
use snarkvm_r1cs::ConstraintSystem; use snarkvm_r1cs::ConstraintSystem;
@ -40,10 +39,8 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
ConstrainedValue::Boolean(resolved) => resolved, ConstrainedValue::Boolean(resolved) => resolved,
value => { value => {
return Err(CompilerError::conditional_boolean_expression_fails_to_resolve_to_bool( return Err(CompilerError::conditional_boolean_expression_fails_to_resolve_to_bool(
value.to_string(), value, span,
span, ))?;
)
.into());
} }
}; };
@ -58,9 +55,9 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
) )
}); });
ConstrainedValue::conditionally_select(unique_namespace, &conditional_value, &first_value, &second_value) Ok(
.map_err(|e| { ConstrainedValue::conditionally_select(unique_namespace, &conditional_value, &first_value, &second_value)
CompilerError::cannot_enforce_expression("conditional select".to_string(), eyre!(e), span).into() .map_err(|e| CompilerError::cannot_enforce_expression("conditional select", e, span))?,
}) )
} }
} }

View File

@ -19,7 +19,6 @@
use crate::{value::ConstrainedValue, GroupType}; use crate::{value::ConstrainedValue, GroupType};
use leo_errors::{CompilerError, LeoError, Span}; use leo_errors::{CompilerError, LeoError, Span};
use eyre::eyre;
use snarkvm_fields::PrimeField; use snarkvm_fields::PrimeField;
use snarkvm_gadgets::boolean::Boolean; use snarkvm_gadgets::boolean::Boolean;
use snarkvm_r1cs::ConstraintSystem; use snarkvm_r1cs::ConstraintSystem;
@ -38,16 +37,10 @@ pub fn enforce_and<'a, F: PrimeField, G: GroupType<F>, CS: ConstraintSystem<F>>(
&left_bool, &left_bool,
&right_bool, &right_bool,
) )
.map_err(|e| { .map_err(|e| CompilerError::cannot_enforce_expression("&&", e, span))?;
LeoError::from(CompilerError::cannot_enforce_expression(
"&&".to_string(),
eyre!(e),
span,
))
})?;
return Ok(ConstrainedValue::Boolean(result)); return Ok(ConstrainedValue::Boolean(result));
} }
Err(LeoError::from(CompilerError::cannot_evaluate_expression(name, span))) Err(CompilerError::cannot_evaluate_expression(name, span))?
} }

View File

@ -27,9 +27,6 @@ pub fn evaluate_not<'a, F: PrimeField, G: GroupType<F>>(
) -> Result<ConstrainedValue<'a, F, G>, LeoError> { ) -> Result<ConstrainedValue<'a, F, G>, LeoError> {
match value { match value {
ConstrainedValue::Boolean(boolean) => Ok(ConstrainedValue::Boolean(boolean.not())), ConstrainedValue::Boolean(boolean) => Ok(ConstrainedValue::Boolean(boolean.not())),
value => Err(LeoError::from(CompilerError::cannot_evaluate_expression( value => Err(CompilerError::cannot_evaluate_expression(format!("!{}", value), span))?,
format!("!{}", value),
span,
))),
} }
} }

View File

@ -19,7 +19,6 @@
use crate::{value::ConstrainedValue, GroupType}; use crate::{value::ConstrainedValue, GroupType};
use leo_errors::{CompilerError, LeoError, Span}; use leo_errors::{CompilerError, LeoError, Span};
use eyre::eyre;
use snarkvm_fields::PrimeField; use snarkvm_fields::PrimeField;
use snarkvm_gadgets::boolean::Boolean; use snarkvm_gadgets::boolean::Boolean;
use snarkvm_r1cs::ConstraintSystem; use snarkvm_r1cs::ConstraintSystem;
@ -38,16 +37,10 @@ pub fn enforce_or<'a, F: PrimeField, G: GroupType<F>, CS: ConstraintSystem<F>>(
&left_bool, &left_bool,
&right_bool, &right_bool,
) )
.map_err(|e| { .map_err(|e| CompilerError::cannot_enforce_expression("||", e, span))?;
LeoError::from(CompilerError::cannot_enforce_expression(
"||".to_string(),
eyre!(e),
span,
))
})?;
return Ok(ConstrainedValue::Boolean(result)); return Ok(ConstrainedValue::Boolean(result));
} }
Err(LeoError::from(CompilerError::cannot_evaluate_expression(name, span))) Err(CompilerError::cannot_evaluate_expression(name, span))?
} }

View File

@ -75,14 +75,14 @@ pub fn evaluate_eq<'a, F: PrimeField, G: GroupType<F>, CS: ConstraintSystem<F>>(
return Ok(current); return Ok(current);
} }
(val_1, val_2) => { (val_1, val_2) => {
return Err(CompilerError::incompatible_types(format!("{} == {}", val_1, val_2,), span).into()); return Err(CompilerError::incompatible_types(
format!("{} == {}", val_1, val_2,),
span,
))?;
} }
}; };
let boolean = match constraint_result { let boolean = constraint_result.map_err(|_| CompilerError::cannot_evaluate_expression("==", span))?;
Ok(boolean) => boolean,
_ => return Err(CompilerError::cannot_evaluate_expression("==".to_string(), span).into()),
};
Ok(ConstrainedValue::Boolean(boolean)) Ok(ConstrainedValue::Boolean(boolean))
} }

View File

@ -35,15 +35,14 @@ pub fn evaluate_ge<'a, F: PrimeField, G: GroupType<F>, CS: ConstraintSystem<F>>(
num_1.greater_than_or_equal(unique_namespace, &num_2) num_1.greater_than_or_equal(unique_namespace, &num_2)
} }
(val_1, val_2) => { (val_1, val_2) => {
return Err(LeoError::from(CompilerError::incompatible_types( return Err(CompilerError::incompatible_types(
format!("{} >= {}", val_1, val_2), format!("{} >= {}", val_1, val_2),
span, span,
))); ))?;
} }
}; };
let boolean = constraint_result let boolean = constraint_result.map_err(|_| CompilerError::cannot_evaluate_expression(">=", span))?;
.map_err(|_| LeoError::from(CompilerError::cannot_evaluate_expression(">=".to_string(), span)))?;
Ok(ConstrainedValue::Boolean(boolean)) Ok(ConstrainedValue::Boolean(boolean))
} }

View File

@ -35,15 +35,14 @@ pub fn evaluate_gt<'a, F: PrimeField, G: GroupType<F>, CS: ConstraintSystem<F>>(
num_1.greater_than(unique_namespace, &num_2) num_1.greater_than(unique_namespace, &num_2)
} }
(val_1, val_2) => { (val_1, val_2) => {
return Err(LeoError::from(CompilerError::incompatible_types( return Err(CompilerError::incompatible_types(
format!("{} > {}", val_1, val_2), format!("{} > {}", val_1, val_2),
span, span,
))); ))?;
} }
}; };
let boolean = constraint_result let boolean = constraint_result.map_err(|_| CompilerError::cannot_evaluate_expression(">", span))?;
.map_err(|_| LeoError::from(CompilerError::cannot_evaluate_expression(">".to_string(), span)))?;
Ok(ConstrainedValue::Boolean(boolean)) Ok(ConstrainedValue::Boolean(boolean))
} }

View File

@ -35,15 +35,14 @@ pub fn evaluate_le<'a, F: PrimeField, G: GroupType<F>, CS: ConstraintSystem<F>>(
num_1.less_than_or_equal(unique_namespace, &num_2) num_1.less_than_or_equal(unique_namespace, &num_2)
} }
(val_1, val_2) => { (val_1, val_2) => {
return Err(LeoError::from(CompilerError::incompatible_types( return Err(CompilerError::incompatible_types(
format!("{} <= {}", val_1, val_2), format!("{} <= {}", val_1, val_2),
span, span,
))); ))?;
} }
}; };
let boolean = constraint_result let boolean = constraint_result.map_err(|_| CompilerError::cannot_evaluate_expression("<=", span))?;
.map_err(|_| LeoError::from(CompilerError::cannot_evaluate_expression("<=".to_string(), span)))?;
Ok(ConstrainedValue::Boolean(boolean)) Ok(ConstrainedValue::Boolean(boolean))
} }

View File

@ -35,15 +35,14 @@ pub fn evaluate_lt<'a, F: PrimeField, G: GroupType<F>, CS: ConstraintSystem<F>>(
num_1.less_than(unique_namespace, &num_2) num_1.less_than(unique_namespace, &num_2)
} }
(val_1, val_2) => { (val_1, val_2) => {
return Err(LeoError::from(CompilerError::incompatible_types( return Err(CompilerError::incompatible_types(
format!("{} < {}", val_1, val_2), format!("{} < {}", val_1, val_2),
span, span,
))); ))?;
} }
}; };
let boolean = constraint_result let boolean = constraint_result.map_err(|_| CompilerError::cannot_evaluate_expression("<", span))?;
.map_err(|_| LeoError::from(CompilerError::cannot_evaluate_expression("<".to_string(), span)))?;
Ok(ConstrainedValue::Boolean(boolean)) Ok(ConstrainedValue::Boolean(boolean))
} }

View File

@ -35,13 +35,13 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
// Get the tuple values. // Get the tuple values.
let tuple = match self.enforce_expression(cs, tuple)? { let tuple = match self.enforce_expression(cs, tuple)? {
ConstrainedValue::Tuple(tuple) => tuple, ConstrainedValue::Tuple(tuple) => tuple,
value => return Err(LeoError::from(CompilerError::undefined_array(value.to_string(), span))), value => return Err(CompilerError::undefined_array(value, span))?,
}; };
// Check for out of bounds access. // Check for out of bounds access.
if index > tuple.len() - 1 { if index > tuple.len() - 1 {
// probably safe to be a panic here // probably safe to be a panic here
return Err(LeoError::from(CompilerError::tuple_index_out_of_bounds(index, span))); return Err(CompilerError::tuple_index_out_of_bounds(index, span))?;
} }
Ok(tuple[index].to_owned()) Ok(tuple[index].to_owned())

View File

@ -26,17 +26,16 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
/// Enforce a variable expression by getting the resolved value /// Enforce a variable expression by getting the resolved value
pub fn evaluate_ref(&mut self, variable_ref: &VariableRef) -> Result<ConstrainedValue<'a, F, G>, LeoError> { pub fn evaluate_ref(&mut self, variable_ref: &VariableRef) -> Result<ConstrainedValue<'a, F, G>, LeoError> {
// Evaluate the identifier name in the current function scope // Evaluate the identifier name in the current function scope
let span = variable_ref.span.as_ref(); let span = variable_ref.span.clone();
let variable = variable_ref.variable.borrow(); let variable = variable_ref.variable.borrow();
let result_value = if let Some(value) = self.get(variable.id) { let result_value = if let Some(value) = self.get(variable.id) {
value.clone() value.clone()
} else { } else {
// TODO fix unwrap here. return Err(CompilerError::undefined_identifier(
return Err(LeoError::from(CompilerError::undefined_identifier(
&variable.name.clone().name, &variable.name.clone().name,
span.unwrap(), &span.unwrap_or_default(),
))); ))?;
// todo: probably can be a panic here instead // todo: probably can be a panic here instead
}; };

View File

@ -49,11 +49,10 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
if function.arguments.len() != arguments.len() { if function.arguments.len() != arguments.len() {
return Err(CompilerError::function_input_not_found( return Err(CompilerError::function_input_not_found(
function.name.borrow().name.to_string(), &function.name.borrow().name.to_string(),
"arguments length invalid".to_string(), "arguments length invalid",
&function.span.clone().unwrap_or_default(), &function.span.clone().unwrap_or_default(),
) ))?;
.into());
} }
// Store input values as new variables in resolved program // Store input values as new variables in resolved program

View File

@ -41,11 +41,11 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
match input_value { match input_value {
Some(InputValue::Array(arr)) => { Some(InputValue::Array(arr)) => {
if array_len != arr.len() { if array_len != arr.len() {
return Err(LeoError::from(CompilerError::invalid_input_array_dimensions( return Err(CompilerError::invalid_input_array_dimensions(
arr.len(), arr.len(),
array_len, array_len,
span, span,
))); ))?;
} }
// Allocate each value in the current row // Allocate each value in the current row
@ -70,10 +70,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
} }
} }
_ => { _ => {
return Err(LeoError::from(CompilerError::invalid_function_input_array( return Err(CompilerError::invalid_function_input_array(input_value.unwrap(), span))?;
input_value.unwrap().to_string(),
span,
)));
} }
} }

View File

@ -43,11 +43,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
}; };
let declared_type = self.asg.scope.resolve_ast_type(&parameter.type_, &parameter.span)?; let declared_type = self.asg.scope.resolve_ast_type(&parameter.type_, &parameter.span)?;
if !expected_type.is_assignable_from(&declared_type) { if !expected_type.is_assignable_from(&declared_type) {
return Err(LeoError::from(AsgError::unexpected_type( return Err(AsgError::unexpected_type(expected_type, declared_type, &identifier.span).into());
&expected_type.to_string(),
Some(&declared_type.to_string()),
&identifier.span,
)));
} }
let member_name = parameter.variable.clone(); let member_name = parameter.variable.clone();
let member_value = self.allocate_main_function_input( let member_value = self.allocate_main_function_input(

View File

@ -78,13 +78,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
input_option: Option<InputValue>, input_option: Option<InputValue>,
span: &Span, span: &Span,
) -> Result<ConstrainedValue<'a, F, G>, LeoError> { ) -> Result<ConstrainedValue<'a, F, G>, LeoError> {
let input = input_option.ok_or_else(|| { let input = input_option.ok_or_else(|| CompilerError::function_input_not_found("main", name, span))?;
LeoError::from(CompilerError::function_input_not_found(
"main".to_string(),
name.to_string(),
span,
))
})?;
match (type_, input) { match (type_, input) {
(Type::Address, InputValue::Address(addr)) => Ok(ConstrainedValue::Address(Address::constant(addr, span)?)), (Type::Address, InputValue::Address(addr)) => Ok(ConstrainedValue::Address(Address::constant(addr, span)?)),
@ -114,21 +108,21 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
let parsed_type = parsed.get_int_type(); let parsed_type = parsed.get_int_type();
let input_type = input_type.into(); let input_type = input_type.into();
if std::mem::discriminant(&parsed_type) != std::mem::discriminant(&input_type) { if std::mem::discriminant(&parsed_type) != std::mem::discriminant(&input_type) {
return Err(LeoError::from(CompilerError::integer_value_integer_type_mismatch( return Err(CompilerError::integer_value_integer_type_mismatch(
input_type.to_string(), input_type,
parsed_type.to_string(), parsed_type,
span, span,
))); ))?;
} }
Ok(ConstrainedValue::Integer(Integer::new(&parsed))) Ok(ConstrainedValue::Integer(Integer::new(&parsed)))
} }
(Type::Array(type_, arr_len), InputValue::Array(values)) => { (Type::Array(type_, arr_len), InputValue::Array(values)) => {
if *arr_len != values.len() { if *arr_len != values.len() {
return Err(LeoError::from(CompilerError::invalid_input_array_dimensions( return Err(CompilerError::invalid_input_array_dimensions(
*arr_len, *arr_len,
values.len(), values.len(),
span, span,
))); ))?;
} }
Ok(ConstrainedValue::Array( Ok(ConstrainedValue::Array(
@ -140,11 +134,11 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
} }
(Type::Tuple(types), InputValue::Tuple(values)) => { (Type::Tuple(types), InputValue::Tuple(values)) => {
if values.len() != types.len() { if values.len() != types.len() {
return Err(LeoError::from(CompilerError::input_tuple_size_mismatch( return Err(CompilerError::input_tuple_size_mismatch(
types.len(), types.len(),
values.len(), values.len(),
span, span,
))); ))?;
} }
Ok(ConstrainedValue::Tuple( Ok(ConstrainedValue::Tuple(
@ -160,12 +154,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
(Type::Circuit(_), _) => unimplemented!("main function input not implemented for type {}", type_), // Should not happen. (Type::Circuit(_), _) => unimplemented!("main function input not implemented for type {}", type_), // Should not happen.
// Return an error if the input type and input value do not match. // Return an error if the input type and input value do not match.
(_, input) => Err(LeoError::from(CompilerError::input_variable_type_mismatch( (_, input) => Err(CompilerError::input_variable_type_mismatch(type_, input, name, span))?,
type_.to_string(),
input.to_string(),
name.to_string(),
span,
))),
} }
} }
} }

View File

@ -39,11 +39,11 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
match input_value { match input_value {
Some(InputValue::Tuple(values)) => { Some(InputValue::Tuple(values)) => {
if values.len() != types.len() { if values.len() != types.len() {
return Err(LeoError::from(CompilerError::input_tuple_size_mismatch( return Err(CompilerError::input_tuple_size_mismatch(
types.len(), types.len(),
values.len(), values.len(),
span, span,
))); ))?;
} }
// Allocate each value in the tuple. // Allocate each value in the tuple.
@ -62,10 +62,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
} }
} }
_ => { _ => {
return Err(LeoError::from(CompilerError::invalid_function_input_tuple( return Err(CompilerError::invalid_function_input_tuple(input_value.unwrap(), span))?;
input_value.unwrap().to_string(),
span,
)));
} }
} }

View File

@ -66,10 +66,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
) { ) {
// If variable is in both [main] and [constants] sections - error. // If variable is in both [main] and [constants] sections - error.
(_, Some(_), Some(_)) => { (_, Some(_), Some(_)) => {
return Err(LeoError::from(CompilerError::double_input_declaration( return Err(CompilerError::double_input_declaration(name, &input_variable.name.span))?;
name.to_string(),
&input_variable.name.span,
)));
} }
// If input option is found in [main] section and input is not const. // If input option is found in [main] section and input is not const.
(false, Some(input_option), _) => self.allocate_main_function_input( (false, Some(input_option), _) => self.allocate_main_function_input(
@ -89,25 +86,25 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
)?, )?,
// Function argument is const, input is not. // Function argument is const, input is not.
(true, Some(_), None) => { (true, Some(_), None) => {
return Err(LeoError::from(CompilerError::expected_const_input_variable( return Err(CompilerError::expected_const_input_variable(
name.to_string(), name,
&input_variable.name.span, &input_variable.name.span,
))); ))?;
} }
// Input is const, function argument is not. // Input is const, function argument is not.
(false, None, Some(_)) => { (false, None, Some(_)) => {
return Err(LeoError::from(CompilerError::expected_non_const_input_variable( return Err(CompilerError::expected_non_const_input_variable(
name.to_string(), name,
&input_variable.name.span, &input_variable.name.span,
))); ))?;
} }
// When not found - Error out. // When not found - Error out.
(_, _, _) => { (_, _, _) => {
return Err(LeoError::from(CompilerError::function_input_not_found( return Err(CompilerError::function_input_not_found(
function.name.borrow().name.to_string(), function.name.borrow().name.to_string(),
name.to_string(), name,
&input_variable.name.span, &input_variable.name.span,
))); ))?;
} }
}; };

View File

@ -55,7 +55,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
if get_indicator_value(&indicator) { if get_indicator_value(&indicator) {
// Error if we already have a return value. // Error if we already have a return value.
if return_value.is_some() { if return_value.is_some() {
return Err(CompilerError::statement_multiple_returns(span).into()); return Err(CompilerError::statement_multiple_returns(span))?;
} else { } else {
// Set the function return value. // Set the function return value.
return_value = Some(result); return_value = Some(result);
@ -79,13 +79,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
&result, &result,
value, value,
) )
.map_err(|_| { .map_err(|_| CompilerError::statement_select_fail(result, value, span))?,
LeoError::from(CompilerError::statement_select_fail(
result.to_string(),
value.to_string(),
span,
))
})?,
); );
} else { } else {
return_value = Some(result); // we ignore indicator for default -- questionable return_value = Some(result); // we ignore indicator for default -- questionable
@ -95,8 +89,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
if expected_return.is_unit() { if expected_return.is_unit() {
Ok(ConstrainedValue::Tuple(vec![])) Ok(ConstrainedValue::Tuple(vec![]))
} else { } else {
return_value Ok(return_value.ok_or_else(|| CompilerError::statement_no_returns(expected_return.to_string(), span))?)
.ok_or_else(|| LeoError::from(CompilerError::statement_no_returns(expected_return.to_string(), span)))
} }
} }
} }

View File

@ -106,7 +106,7 @@ impl Output {
// Return an error if we do not have enough return registers // Return an error if we do not have enough return registers
if register_values.len() < return_values.len() { if register_values.len() < return_values.len() {
return Err(LeoError::from(CompilerError::output_not_enough_registers(span))); return Err(CompilerError::output_not_enough_registers(span))?;
} }
let mut registers = BTreeMap::new(); let mut registers = BTreeMap::new();
@ -119,11 +119,11 @@ impl Output {
let return_value_type = value.to_type(span)?; let return_value_type = value.to_type(span)?;
if !register_type.is_assignable_from(&return_value_type) { if !register_type.is_assignable_from(&return_value_type) {
return Err(LeoError::from(CompilerError::output_mismatched_types( return Err(CompilerError::output_mismatched_types(
register_type.to_string(), register_type,
return_value_type.to_string(), return_value_type,
span, span,
))); ))?;
} }
let value = match value { let value = match value {

View File

@ -55,7 +55,7 @@ impl OutputBytes {
// Return an error if we do not have enough return registers // Return an error if we do not have enough return registers
if register_values.len() < return_values.len() { if register_values.len() < return_values.len() {
return Err(LeoError::from(CompilerError::output_not_enough_registers(span))); return Err(CompilerError::output_not_enough_registers(span))?;
} }
// Manually construct result string // Manually construct result string
@ -73,11 +73,11 @@ impl OutputBytes {
let return_value_type = value.to_type(span)?; let return_value_type = value.to_type(span)?;
if !register_type.is_assignable_from(&return_value_type) { if !register_type.is_assignable_from(&return_value_type) {
return Err(LeoError::from(CompilerError::output_mismatched_types( return Err(CompilerError::output_mismatched_types(
register_type.to_string(), register_type,
return_value_type.to_string(), return_value_type,
span, span,
))); ))?;
} }
let value = value.to_string(); let value = value.to_string();

View File

@ -19,7 +19,6 @@
use leo_errors::{CompilerError, LeoError}; use leo_errors::{CompilerError, LeoError};
use backtrace::Backtrace; use backtrace::Backtrace;
use eyre::eyre;
use std::{ use std::{
borrow::Cow, borrow::Cow,
@ -49,11 +48,11 @@ impl OutputFile {
pub fn write(&self, path: &Path, bytes: &[u8]) -> Result<(), LeoError> { pub fn write(&self, path: &Path, bytes: &[u8]) -> Result<(), LeoError> {
// create output file // create output file
let path = self.setup_file_path(path); let path = self.setup_file_path(path);
let mut file = File::create(&path) let mut file = File::create(&path).map_err(|e| CompilerError::output_file_io_error(e, Backtrace::new()))?;
.map_err(|e| LeoError::from(CompilerError::output_file_io_error(eyre!(e), Backtrace::new())))?;
file.write_all(bytes) Ok(file
.map_err(|e| LeoError::from(CompilerError::output_file_io_error(eyre!(e), Backtrace::new()))) .write_all(bytes)
.map_err(|e| CompilerError::output_file_io_error(e, Backtrace::new()))?)
} }
/// Removes the output file at the given path if it exists. Returns `true` on success, /// Removes the output file at the given path if it exists. Returns `true` on success,
@ -64,12 +63,7 @@ impl OutputFile {
return Ok(false); return Ok(false);
} }
fs::remove_file(&path).map_err(|_| { fs::remove_file(&path).map_err(|_| CompilerError::output_file_cannot_remove(path, Backtrace::new()))?;
LeoError::from(CompilerError::output_file_cannot_remove(
path.into_owned(),
Backtrace::new(),
))
})?;
Ok(true) Ok(true)
} }

View File

@ -19,7 +19,6 @@ use crate::{ConstrainedValue, GroupType, Integer};
use leo_asg::Function; use leo_asg::Function;
use leo_errors::{CompilerError, LeoError, Span}; use leo_errors::{CompilerError, LeoError, Span};
use eyre::eyre;
use snarkvm_fields::PrimeField; use snarkvm_fields::PrimeField;
use snarkvm_gadgets::{ use snarkvm_gadgets::{
algorithms::prf::Blake2sGadget, algorithms::prf::Blake2sGadget,
@ -63,25 +62,13 @@ impl<'a, F: PrimeField, G: GroupType<F>> CoreCircuit<'a, F, G> for Blake2s {
let input = unwrap_argument(arguments.remove(1)); let input = unwrap_argument(arguments.remove(1));
let seed = unwrap_argument(arguments.remove(0)); let seed = unwrap_argument(arguments.remove(0));
let digest = let digest = Blake2sGadget::check_evaluation_gadget(cs.ns(|| "blake2s hash"), &seed[..], &input[..])
Blake2sGadget::check_evaluation_gadget(cs.ns(|| "blake2s hash"), &seed[..], &input[..]).map_err(|e| { .map_err(|e| CompilerError::cannot_enforce_expression("Blake2s check evaluation gadget", e, span))?;
LeoError::from(CompilerError::cannot_enforce_expression(
"Blake2s check evaluation gadget".to_owned(),
eyre!(e),
span,
))
})?;
Ok(ConstrainedValue::Array( Ok(ConstrainedValue::Array(
digest digest
.to_bytes(cs) .to_bytes(cs)
.map_err(|e| { .map_err(|e| CompilerError::cannot_enforce_expression("Vec<UInt8> ToBytes", e, span))?
LeoError::from(CompilerError::cannot_enforce_expression(
"Vec<UInt8> ToBytes".to_owned(),
eyre!(e),
span,
))
})?
.into_iter() .into_iter()
.map(Integer::U8) .map(Integer::U8)
.map(ConstrainedValue::Integer) .map(ConstrainedValue::Integer)

View File

@ -59,13 +59,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
_ => unimplemented!("unimplemented assign operator"), _ => unimplemented!("unimplemented assign operator"),
}; };
let selected_value = ConstrainedValue::conditionally_select(cs.ns(|| scope), condition, &new_value, target) let selected_value = ConstrainedValue::conditionally_select(cs.ns(|| scope), condition, &new_value, target)
.map_err(|_| { .map_err(|_| CompilerError::statement_select_fail(new_value, target.clone(), span))?;
LeoError::from(CompilerError::statement_select_fail(
new_value.to_string(),
target.to_string(),
span,
))
})?;
*target = selected_value; *target = selected_value;
Ok(()) Ok(())

View File

@ -22,7 +22,6 @@ use crate::{program::ConstrainedProgram, value::ConstrainedValue, GroupType, Int
use leo_asg::{ConstInt, Expression, Node}; use leo_asg::{ConstInt, Expression, Node};
use leo_errors::{CompilerError, LeoError}; use leo_errors::{CompilerError, LeoError};
use eyre::eyre;
use snarkvm_fields::PrimeField; use snarkvm_fields::PrimeField;
use snarkvm_gadgets::traits::{eq::EvaluateEqGadget, select::CondSelectGadget}; use snarkvm_gadgets::traits::{eq::EvaluateEqGadget, select::CondSelectGadget};
use snarkvm_r1cs::ConstraintSystem; use snarkvm_r1cs::ConstraintSystem;
@ -44,11 +43,11 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
ConstrainedValue::Array(input) => { ConstrainedValue::Array(input) => {
if let Some(index) = index_resolved.to_usize() { if let Some(index) = index_resolved.to_usize() {
if index >= input.len() { if index >= input.len() {
Err(LeoError::from(CompilerError::statement_array_assign_index_bounds( Err(CompilerError::statement_array_assign_index_bounds(
index, index,
input.len(), input.len(),
&context.span, &context.span,
))) ))?
} else { } else {
let target = input.get_mut(index).unwrap(); let target = input.get_mut(index).unwrap();
if context.remaining_accesses.is_empty() { if context.remaining_accesses.is_empty() {
@ -64,7 +63,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
let array_len: u32 = input let array_len: u32 = input
.len() .len()
.try_into() .try_into()
.map_err(|_| LeoError::from(CompilerError::array_length_out_of_bounds(&span)))?; .map_err(|_| CompilerError::array_length_out_of_bounds(&span))?;
self.array_bounds_check(cs, &index_resolved, array_len, &span)?; self.array_bounds_check(cs, &index_resolved, array_len, &span)?;
} }
@ -77,13 +76,11 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
let index_bounded = i let index_bounded = i
.try_into() .try_into()
.map_err(|_| LeoError::from(CompilerError::array_index_out_of_legal_bounds(&span)))?; .map_err(|_| CompilerError::array_index_out_of_legal_bounds(&span))?;
let const_index = ConstInt::U32(index_bounded).cast_to(&index_resolved.get_type()); let const_index = ConstInt::U32(index_bounded).cast_to(&index_resolved.get_type());
let index_comparison = index_resolved let index_comparison = index_resolved
.evaluate_equal(eq_namespace, &Integer::new(&const_index)) .evaluate_equal(eq_namespace, &Integer::new(&const_index))
.map_err(|_| { .map_err(|_| CompilerError::cannot_evaluate_expression("==", &span))?;
LeoError::from(CompilerError::cannot_evaluate_expression("==".to_string(), &span))
})?;
let mut unique_namespace = cs.ns(|| { let mut unique_namespace = cs.ns(|| {
format!( format!(
@ -116,31 +113,23 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
&temp_item, &temp_item,
item, item,
) )
.map_err(|e| { .map_err(|e| CompilerError::cannot_enforce_expression("conditional select", e, &span))?;
LeoError::from(CompilerError::cannot_enforce_expression(
"conditional select".to_string(),
eyre!(e),
&span,
))
})?;
*item = value; *item = value;
} }
Ok(()) Ok(())
} }
} }
_ => Err(LeoError::from(CompilerError::statement_array_assign_interior_index( _ => Err(CompilerError::statement_array_assign_interior_index(&context.span))?,
&context.span,
))),
} }
} else if context.from_range && input_len != 0 { } else if context.from_range && input_len != 0 {
context.from_range = false; context.from_range = false;
if let Some(index) = index_resolved.to_usize() { if let Some(index) = index_resolved.to_usize() {
if index >= input_len { if index >= input_len {
return Err(LeoError::from(CompilerError::statement_array_assign_index_bounds( return Err(CompilerError::statement_array_assign_index_bounds(
index, index,
input_len, input_len,
&context.span, &context.span,
))); ))?;
} }
let target = context.input.remove(index); let target = context.input.remove(index);
@ -158,7 +147,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
.input .input
.len() .len()
.try_into() .try_into()
.map_err(|_| LeoError::from(CompilerError::array_length_out_of_bounds(&span)))?; .map_err(|_| CompilerError::array_length_out_of_bounds(&span))?;
self.array_bounds_check(cs, &index_resolved, array_len, &span)?; self.array_bounds_check(cs, &index_resolved, array_len, &span)?;
} }
@ -171,13 +160,11 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
let index_bounded = i let index_bounded = i
.try_into() .try_into()
.map_err(|_| LeoError::from(CompilerError::array_index_out_of_legal_bounds(&span)))?; .map_err(|_| CompilerError::array_index_out_of_legal_bounds(&span))?;
let const_index = ConstInt::U32(index_bounded).cast_to(&index_resolved.get_type()); let const_index = ConstInt::U32(index_bounded).cast_to(&index_resolved.get_type());
let index_comparison = index_resolved let index_comparison = index_resolved
.evaluate_equal(eq_namespace, &Integer::new(&const_index)) .evaluate_equal(eq_namespace, &Integer::new(&const_index))
.map_err(|_| { .map_err(|_| CompilerError::cannot_evaluate_expression("==", &span))?;
LeoError::from(CompilerError::cannot_evaluate_expression("==".to_string(), &span))
})?;
let mut unique_namespace = cs.ns(|| { let mut unique_namespace = cs.ns(|| {
format!( format!(
@ -206,21 +193,13 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
}; };
let value = let value =
ConstrainedValue::conditionally_select(unique_namespace, &index_comparison, &temp_item, item) ConstrainedValue::conditionally_select(unique_namespace, &index_comparison, &temp_item, item)
.map_err(|e| { .map_err(|e| CompilerError::cannot_enforce_expression("conditional select", e, &span))?;
LeoError::from(CompilerError::cannot_enforce_expression(
"conditional select".to_string(),
eyre!(e),
&span,
))
})?;
**item = value; **item = value;
} }
Ok(()) Ok(())
} }
} else { } else {
Err(LeoError::from(CompilerError::statement_array_assign_interior_index( Err(CompilerError::statement_array_assign_interior_index(&context.span))?
&context.span,
)))
} }
} }
} }

View File

@ -38,7 +38,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
.transpose()? .transpose()?
.map(|x| { .map(|x| {
x.to_usize() x.to_usize()
.ok_or_else(|| LeoError::from(CompilerError::statement_array_assign_index_const(&context.span))) .ok_or_else(|| CompilerError::statement_array_assign_index_const(&context.span))
}) })
.transpose()?; .transpose()?;
let stop_index = stop let stop_index = stop
@ -46,7 +46,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
.transpose()? .transpose()?
.map(|x| { .map(|x| {
x.to_usize() x.to_usize()
.ok_or_else(|| LeoError::from(CompilerError::statement_array_assign_index_const(&context.span))) .ok_or_else(|| CompilerError::statement_array_assign_index_const(&context.span))
}) })
.transpose()?; .transpose()?;
let start_index = start_index.unwrap_or(0); let start_index = start_index.unwrap_or(0);
@ -75,9 +75,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
} }
Ok(()) Ok(())
} }
_ => Err(LeoError::from(CompilerError::statement_array_assign_index( _ => Err(CompilerError::statement_array_assign_index(&context.span))?,
&context.span,
))),
} }
} else { } else {
// range of a range // range of a range

View File

@ -31,9 +31,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
name: &Identifier, name: &Identifier,
) -> Result<(), LeoError> { ) -> Result<(), LeoError> {
if context.input.len() != 1 { if context.input.len() != 1 {
return Err(LeoError::from(CompilerError::statement_array_assign_interior_index( return Err(CompilerError::statement_array_assign_interior_index(&context.span))?;
&context.span,
)));
} }
match context.input.remove(0) { match context.input.remove(0) {
ConstrainedValue::CircuitExpression(_variable, members) => { ConstrainedValue::CircuitExpression(_variable, members) => {
@ -47,18 +45,12 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
} }
None => { None => {
// Throw an error if the circuit variable does not exist in the circuit // Throw an error if the circuit variable does not exist in the circuit
Err(LeoError::from(CompilerError::statement_undefined_circuit_variable( Err(CompilerError::statement_undefined_circuit_variable(name, &context.span))?
name.to_string(),
&context.span,
)))
} }
} }
} }
// Throw an error if the circuit definition does not exist in the file // Throw an error if the circuit definition does not exist in the file
x => Err(LeoError::from(CompilerError::undefined_circuit( x => Err(CompilerError::undefined_circuit(x, &context.span))?,
x.to_string(),
&context.span,
))),
} }
} }
} }

View File

@ -116,22 +116,22 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
span: &Span, span: &Span,
) -> Result<(), LeoError> { ) -> Result<(), LeoError> {
if stop_index < start_index { if stop_index < start_index {
Err(LeoError::from(CompilerError::statement_array_assign_range_order( Err(CompilerError::statement_array_assign_range_order(
start_index, start_index,
stop_index, stop_index,
len, len,
span, span,
))) ))?
} else if start_index > len { } else if start_index > len {
Err(LeoError::from(CompilerError::statement_array_assign_index_bounds( Err(CompilerError::statement_array_assign_index_bounds(
start_index, start_index,
len, len,
span, span,
))) ))?
} else if stop_index > len { } else if stop_index > len {
Err(LeoError::from(CompilerError::statement_array_assign_index_bounds( Err(CompilerError::statement_array_assign_index_bounds(
stop_index, len, span, stop_index, len, span,
))) ))?
} else { } else {
Ok(()) Ok(())
} }

View File

@ -30,26 +30,22 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
index: usize, index: usize,
) -> Result<(), LeoError> { ) -> Result<(), LeoError> {
if context.input.len() != 1 { if context.input.len() != 1 {
return Err(LeoError::from(CompilerError::statement_array_assign_interior_index( return Err(CompilerError::statement_array_assign_interior_index(&context.span))?;
&context.span,
)));
} }
match context.input.remove(0) { match context.input.remove(0) {
ConstrainedValue::Tuple(old) => { ConstrainedValue::Tuple(old) => {
if index > old.len() { if index > old.len() {
Err(LeoError::from(CompilerError::statement_tuple_assign_index_bounds( Err(CompilerError::statement_tuple_assign_index_bounds(
index, index,
old.len(), old.len(),
&context.span, &context.span,
))) ))?
} else { } else {
context.input = vec![&mut old[index]]; context.input = vec![&mut old[index]];
self.resolve_target_access(cs, context) self.resolve_target_access(cs, context)
} }
} }
_ => Err(LeoError::from(CompilerError::statement_tuple_assign_index( _ => Err(CompilerError::statement_tuple_assign_index(&context.span))?,
&context.span,
))),
} }
} }
} }

View File

@ -24,7 +24,7 @@ use crate::{
StatementResult, StatementResult,
}; };
use leo_asg::ConditionalStatement; use leo_asg::ConditionalStatement;
use leo_errors::{CompilerError, LeoError}; use leo_errors::CompilerError;
use snarkvm_fields::PrimeField; use snarkvm_fields::PrimeField;
use snarkvm_gadgets::boolean::Boolean; use snarkvm_gadgets::boolean::Boolean;
@ -57,9 +57,10 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
let inner_indicator = match self.enforce_expression(cs, statement.condition.get())? { let inner_indicator = match self.enforce_expression(cs, statement.condition.get())? {
ConstrainedValue::Boolean(resolved) => resolved, ConstrainedValue::Boolean(resolved) => resolved,
value => { value => {
return Err(LeoError::from( return Err(CompilerError::conditional_boolean_expression_fails_to_resolve_to_bool(
CompilerError::conditional_boolean_expression_fails_to_resolve_to_bool(value.to_string(), &span), value.to_string(),
)); &span,
))?;
} }
}; };
@ -75,7 +76,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
outer_indicator, outer_indicator,
&inner_indicator, &inner_indicator,
) )
.map_err(|_| LeoError::from(CompilerError::statement_indicator_calculation(branch_1_name, &span)))?; .map_err(|_| CompilerError::statement_indicator_calculation(branch_1_name, &span))?;
let mut results = vec![]; let mut results = vec![];
@ -96,7 +97,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
outer_indicator, outer_indicator,
&inner_indicator, &inner_indicator,
) )
.map_err(|_| LeoError::from(CompilerError::statement_indicator_calculation(branch_2_name, &span)))?; .map_err(|_| CompilerError::statement_indicator_calculation(branch_2_name, &span))?;
// Evaluate branch 2 // Evaluate branch 2
let mut branch_2_result = match statement.next.get() { let mut branch_2_result = match statement.next.get() {

View File

@ -31,11 +31,11 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
span: &Span, span: &Span,
) -> Result<(), LeoError> { ) -> Result<(), LeoError> {
if values.len() != variable_names.len() { if values.len() != variable_names.len() {
return Err(LeoError::from(CompilerError::statement_invalid_number_of_definitions( return Err(CompilerError::statement_invalid_number_of_definitions(
values.len(), values.len(),
variable_names.len(), variable_names.len(),
span, span,
))); ))?;
} }
for (variable, value) in variable_names.iter().zip(values.into_iter()) { for (variable, value) in variable_names.iter().zip(values.into_iter()) {
@ -65,10 +65,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
// ConstrainedValue::Return(values) => values, // ConstrainedValue::Return(values) => values,
ConstrainedValue::Tuple(values) => values, ConstrainedValue::Tuple(values) => values,
value => { value => {
return Err(LeoError::from(CompilerError::statement_multiple_definition( return Err(CompilerError::statement_multiple_definition(value, &span))?;
value.to_string(),
&span,
)));
} }
}; };

View File

@ -26,7 +26,7 @@ use crate::{
StatementResult, StatementResult,
}; };
use leo_asg::IterationStatement; use leo_asg::IterationStatement;
use leo_errors::{CompilerError, LeoError}; use leo_errors::CompilerError;
use snarkvm_fields::PrimeField; use snarkvm_fields::PrimeField;
use snarkvm_gadgets::{boolean::Boolean, integers::uint::UInt32}; use snarkvm_gadgets::{boolean::Boolean, integers::uint::UInt32};
@ -47,11 +47,11 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
let from = self let from = self
.enforce_index(cs, statement.start.get(), &span)? .enforce_index(cs, statement.start.get(), &span)?
.to_usize() .to_usize()
.ok_or_else(|| LeoError::from(CompilerError::statement_loop_index_const(&span)))?; .ok_or_else(|| CompilerError::statement_loop_index_const(&span))?;
let to = self let to = self
.enforce_index(cs, statement.stop.get(), &span)? .enforce_index(cs, statement.stop.get(), &span)?
.to_usize() .to_usize()
.ok_or_else(|| LeoError::from(CompilerError::statement_loop_index_const(&span)))?; .ok_or_else(|| CompilerError::statement_loop_index_const(&span))?;
let iter: Box<dyn Iterator<Item = usize>> = match (from < to, statement.inclusive) { let iter: Box<dyn Iterator<Item = usize>> = match (from < to, statement.inclusive) {
(true, true) => Box::new(from..=to), (true, true) => Box::new(from..=to),

View File

@ -82,9 +82,9 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
} }
} }
_ => { _ => {
return Err(LeoError::from(CompilerError::statement_unassigned( return Err(CompilerError::statement_unassigned(
&statement.span.clone().unwrap_or_default(), &statement.span.clone().unwrap_or_default(),
))); ))?;
} }
} }
} }

View File

@ -18,7 +18,6 @@ use crate::{ConstrainedValue, GroupType, IntegerTrait};
use leo_ast::InputValue; use leo_ast::InputValue;
use leo_errors::{CompilerError, LeoError, Span}; use leo_errors::{CompilerError, LeoError, Span};
use eyre::eyre;
use snarkvm_dpc::{account::Address as AleoAddress, testnet1::instantiated::Components}; use snarkvm_dpc::{account::Address as AleoAddress, testnet1::instantiated::Components};
use snarkvm_fields::PrimeField; use snarkvm_fields::PrimeField;
use snarkvm_gadgets::{ use snarkvm_gadgets::{
@ -43,8 +42,8 @@ pub struct Address {
impl Address { impl Address {
pub(crate) fn constant(address: String, span: &Span) -> Result<Self, LeoError> { pub(crate) fn constant(address: String, span: &Span) -> Result<Self, LeoError> {
let address = AleoAddress::from_str(&address) let address =
.map_err(|e| LeoError::from(CompilerError::address_value_account_error(eyre!(e), span)))?; AleoAddress::from_str(&address).map_err(|e| CompilerError::address_value_account_error(e, span))?;
let mut address_bytes = vec![]; let mut address_bytes = vec![];
address.write_le(&mut address_bytes).unwrap(); address.write_le(&mut address_bytes).unwrap();
@ -73,10 +72,7 @@ impl Address {
if let InputValue::Address(string) = input { if let InputValue::Address(string) = input {
Some(string) Some(string)
} else { } else {
return Err(LeoError::from(CompilerError::address_value_invalid_address( return Err(CompilerError::address_value_invalid_address(name, span))?;
name.to_owned(),
span,
)));
} }
} }
None => None, None => None,
@ -86,7 +82,7 @@ impl Address {
cs.ns(|| format!("`{}: address` {}:{}", name, span.line_start, span.col_start)), cs.ns(|| format!("`{}: address` {}:{}", name, span.line_start, span.col_start)),
|| address_value.ok_or(SynthesisError::AssignmentMissing), || address_value.ok_or(SynthesisError::AssignmentMissing),
) )
.map_err(|_| LeoError::from(CompilerError::address_value_missing_address(span)))?; .map_err(|_| CompilerError::address_value_missing_address(span))?;
Ok(ConstrainedValue::Address(address)) Ok(ConstrainedValue::Address(address))
} }

View File

@ -30,16 +30,11 @@ pub(crate) fn allocate_bool<F: PrimeField, CS: ConstraintSystem<F>>(
option: Option<bool>, option: Option<bool>,
span: &Span, span: &Span,
) -> Result<Boolean, LeoError> { ) -> Result<Boolean, LeoError> {
Boolean::alloc( Ok(Boolean::alloc(
cs.ns(|| format!("`{}: bool` {}:{}", name, span.line_start, span.col_start)), cs.ns(|| format!("`{}: bool` {}:{}", name, span.line_start, span.col_start)),
|| option.ok_or(SynthesisError::AssignmentMissing), || option.ok_or(SynthesisError::AssignmentMissing),
) )
.map_err(|_| { .map_err(|_| CompilerError::boolean_value_missing_boolean(format!("{}: bool", name), span))?)
LeoError::from(CompilerError::boolean_value_missing_boolean(
format!("{}: bool", name),
span,
))
})
} }
pub(crate) fn bool_from_input<'a, F: PrimeField, G: GroupType<F>, CS: ConstraintSystem<F>>( pub(crate) fn bool_from_input<'a, F: PrimeField, G: GroupType<F>, CS: ConstraintSystem<F>>(
@ -54,10 +49,7 @@ pub(crate) fn bool_from_input<'a, F: PrimeField, G: GroupType<F>, CS: Constraint
if let InputValue::Boolean(bool) = input { if let InputValue::Boolean(bool) = input {
Some(bool) Some(bool)
} else { } else {
return Err(LeoError::from(CompilerError::boolean_value_invalid_boolean( return Err(CompilerError::boolean_value_invalid_boolean(name, span))?;
name.to_owned(),
span,
)));
} }
} }
None => None, None => None,

View File

@ -160,10 +160,7 @@ pub(crate) fn char_from_input<'a, F: PrimeField, G: GroupType<F>, CS: Constraint
} }
} }
} else { } else {
return Err(LeoError::from(CompilerError::char_value_invalid_char( return Err(CompilerError::char_value_invalid_char(input, span))?;
input.to_string(),
span,
)));
} }
} }
None => (CharType::Scalar(0 as char), None), None => (CharType::Scalar(0 as char), None),

View File

@ -19,7 +19,6 @@
use crate::number_string_typing; use crate::number_string_typing;
use leo_errors::{CompilerError, LeoError, Span}; use leo_errors::{CompilerError, LeoError, Span};
use eyre::eyre;
use snarkvm_fields::PrimeField; use snarkvm_fields::PrimeField;
use snarkvm_gadgets::{ use snarkvm_gadgets::{
bits::{ToBitsBEGadget, ToBytesGadget}, bits::{ToBitsBEGadget, ToBytesGadget},
@ -51,14 +50,16 @@ impl<F: PrimeField> FieldType<F> {
let number_info = number_string_typing(&string); let number_info = number_string_typing(&string);
let value = match number_info { let value = match number_info {
(number, neg) if neg => -F::from_str(&number) (number, neg) if neg => {
.map_err(|_| LeoError::from(CompilerError::field_value_invalid_field(string.clone(), span)))?, -F::from_str(&number).map_err(|_| CompilerError::field_value_invalid_field(string.clone(), span))?
(number, _) => F::from_str(&number) }
.map_err(|_| LeoError::from(CompilerError::field_value_invalid_field(string.clone(), span)))?, (number, _) => {
F::from_str(&number).map_err(|_| CompilerError::field_value_invalid_field(string.clone(), span))?
}
}; };
let value = FpGadget::alloc_constant(cs, || Ok(value)) let value = FpGadget::alloc_constant(cs, || Ok(value))
.map_err(|_| LeoError::from(CompilerError::field_value_invalid_field(string, span)))?; .map_err(|_| CompilerError::field_value_invalid_field(string, span))?;
Ok(FieldType(value)) Ok(FieldType(value))
} }
@ -68,59 +69,47 @@ impl<F: PrimeField> FieldType<F> {
let result = self let result = self
.0 .0
.negate(cs) .negate(cs)
.map_err(|e| LeoError::from(CompilerError::field_value_negate_operation(eyre!(e), span)))?; .map_err(|e| CompilerError::field_value_negate_operation(e, span))?;
Ok(FieldType(result)) Ok(FieldType(result))
} }
/// Returns a new `FieldType` by calling the `FpGadget` `add` function. /// Returns a new `FieldType` by calling the `FpGadget` `add` function.
pub fn add<CS: ConstraintSystem<F>>(&self, cs: CS, other: &Self, span: &Span) -> Result<Self, LeoError> { pub fn add<CS: ConstraintSystem<F>>(&self, cs: CS, other: &Self, span: &Span) -> Result<Self, LeoError> {
let value = self.0.add(cs, &other.0).map_err(|e| { let value = self
LeoError::from(CompilerError::field_value_binary_operation( .0
"+".to_string(), .add(cs, &other.0)
eyre!(e), .map_err(|e| CompilerError::field_value_binary_operation("+", e, span))?;
span,
))
})?;
Ok(FieldType(value)) Ok(FieldType(value))
} }
/// Returns a new `FieldType` by calling the `FpGadget` `sub` function. /// Returns a new `FieldType` by calling the `FpGadget` `sub` function.
pub fn sub<CS: ConstraintSystem<F>>(&self, cs: CS, other: &Self, span: &Span) -> Result<Self, LeoError> { pub fn sub<CS: ConstraintSystem<F>>(&self, cs: CS, other: &Self, span: &Span) -> Result<Self, LeoError> {
let value = self.0.sub(cs, &other.0).map_err(|e| { let value = self
LeoError::from(CompilerError::field_value_binary_operation( .0
"-".to_string(), .sub(cs, &other.0)
eyre!(e), .map_err(|e| CompilerError::field_value_binary_operation("-", e, span))?;
span,
))
})?;
Ok(FieldType(value)) Ok(FieldType(value))
} }
/// Returns a new `FieldType` by calling the `FpGadget` `mul` function. /// Returns a new `FieldType` by calling the `FpGadget` `mul` function.
pub fn mul<CS: ConstraintSystem<F>>(&self, cs: CS, other: &Self, span: &Span) -> Result<Self, LeoError> { pub fn mul<CS: ConstraintSystem<F>>(&self, cs: CS, other: &Self, span: &Span) -> Result<Self, LeoError> {
let value = self.0.mul(cs, &other.0).map_err(|e| { let value = self
LeoError::from(CompilerError::field_value_binary_operation( .0
"*".to_string(), .mul(cs, &other.0)
eyre!(e), .map_err(|e| CompilerError::field_value_binary_operation("*", e, span))?;
span,
))
})?;
Ok(FieldType(value)) Ok(FieldType(value))
} }
/// Returns a new `FieldType` by calling the `FpGadget` `inverse` function. /// Returns a new `FieldType` by calling the `FpGadget` `inverse` function.
pub fn inverse<CS: ConstraintSystem<F>>(&self, cs: CS, span: &Span) -> Result<Self, LeoError> { pub fn inverse<CS: ConstraintSystem<F>>(&self, cs: CS, span: &Span) -> Result<Self, LeoError> {
let value = self.0.inverse(cs).map_err(|e| { let value = self
LeoError::from(CompilerError::field_value_binary_operation( .0
"inv".to_string(), .inverse(cs)
eyre!(e), .map_err(|e| CompilerError::field_value_binary_operation("inv", e, span))?;
span,
))
})?;
Ok(FieldType(value)) Ok(FieldType(value))
} }

View File

@ -40,13 +40,8 @@ pub(crate) fn allocate_field<F: PrimeField, CS: ConstraintSystem<F>>(
|| Some(number).ok_or(SynthesisError::AssignmentMissing), || Some(number).ok_or(SynthesisError::AssignmentMissing),
) )
.map(|value| value.negate(cs, span)) .map(|value| value.negate(cs, span))
.map_err(|_| { .map_err(|_| CompilerError::field_value_missing_field(format!("{}: field", name), span))?,
LeoError::from(CompilerError::field_value_missing_field( (number, _) => Ok(FieldType::alloc(
format!("{}: field", name),
span,
))
})?,
(number, _) => FieldType::alloc(
cs.ns(|| format!("`{}: field` {}:{}", name, span.line_start, span.col_start)), cs.ns(|| format!("`{}: field` {}:{}", name, span.line_start, span.col_start)),
|| Some(number).ok_or(SynthesisError::AssignmentMissing), || Some(number).ok_or(SynthesisError::AssignmentMissing),
) )
@ -55,13 +50,13 @@ pub(crate) fn allocate_field<F: PrimeField, CS: ConstraintSystem<F>>(
format!("{}: field", name), format!("{}: field", name),
span, span,
)) ))
}), })?),
} }
} }
None => Err(LeoError::from(CompilerError::field_value_missing_field( None => Err(CompilerError::field_value_missing_field(
format!("{}: field", name), format!("{}: field", name),
span, span,
))), ))?,
} }
} }
@ -77,10 +72,7 @@ pub(crate) fn field_from_input<'a, F: PrimeField, G: GroupType<F>, CS: Constrain
if let InputValue::Field(string) = input { if let InputValue::Field(string) = input {
Some(string) Some(string)
} else { } else {
return Err(LeoError::from(CompilerError::field_value_invalid_field( return Err(CompilerError::field_value_invalid_field(input, span))?;
input.to_string(),
span,
)));
} }
} }
None => None, None => None,

View File

@ -30,16 +30,11 @@ pub(crate) fn allocate_group<F: PrimeField, G: GroupType<F>, CS: ConstraintSyste
option: Option<GroupValue>, option: Option<GroupValue>,
span: &Span, span: &Span,
) -> Result<G, LeoError> { ) -> Result<G, LeoError> {
G::alloc( Ok(G::alloc(
cs.ns(|| format!("`{}: group` {}:{}", name, span.line_start, span.col_start)), cs.ns(|| format!("`{}: group` {}:{}", name, span.line_start, span.col_start)),
|| option.ok_or(SynthesisError::AssignmentMissing), || option.ok_or(SynthesisError::AssignmentMissing),
) )
.map_err(|_| { .map_err(|_| CompilerError::group_value_missing_group(format!("{}: group", name), span))?)
LeoError::from(CompilerError::group_value_missing_group(
format!("{}: group", name),
span,
))
})
} }
pub(crate) fn group_from_input<'a, F: PrimeField, G: GroupType<F>, CS: ConstraintSystem<F>>( pub(crate) fn group_from_input<'a, F: PrimeField, G: GroupType<F>, CS: ConstraintSystem<F>>(
@ -54,10 +49,7 @@ pub(crate) fn group_from_input<'a, F: PrimeField, G: GroupType<F>, CS: Constrain
if let InputValue::Group(string) = input { if let InputValue::Group(string) = input {
Some(string) Some(string)
} else { } else {
return Err(LeoError::from(CompilerError::group_value_missing_group( return Err(CompilerError::group_value_missing_group(input, span))?;
input.to_string(),
span,
)));
} }
} }
None => None, None => None,

View File

@ -18,7 +18,6 @@ use crate::{number_string_typing, GroupType};
use leo_asg::{GroupCoordinate, GroupValue}; use leo_asg::{GroupCoordinate, GroupValue};
use leo_errors::{CompilerError, LeoError, Span}; use leo_errors::{CompilerError, LeoError, Span};
use eyre::eyre;
use snarkvm_curves::{ use snarkvm_curves::{
edwards_bls12::{EdwardsAffine, EdwardsParameters, Fq}, edwards_bls12::{EdwardsAffine, EdwardsParameters, Fq},
templates::twisted_edwards_extended::Affine, templates::twisted_edwards_extended::Affine,
@ -61,9 +60,10 @@ impl GroupType<Fq> for EdwardsGroupType {
} }
fn to_allocated<CS: ConstraintSystem<Fq>>(&self, mut cs: CS, span: &Span) -> Result<Self, LeoError> { fn to_allocated<CS: ConstraintSystem<Fq>>(&self, mut cs: CS, span: &Span) -> Result<Self, LeoError> {
self.allocated(cs.ns(|| format!("allocate affine point {}:{}", span.line_start, span.col_start))) Ok(self
.allocated(cs.ns(|| format!("allocate affine point {}:{}", span.line_start, span.col_start)))
.map(|ebg| EdwardsGroupType::Allocated(Box::new(ebg))) .map(|ebg| EdwardsGroupType::Allocated(Box::new(ebg)))
.map_err(|e| LeoError::from(CompilerError::group_value_synthesis_error(eyre!(e), span))) .map_err(|e| CompilerError::group_value_synthesis_error(e, span))?)
} }
fn negate<CS: ConstraintSystem<Fq>>(&self, cs: CS, span: &Span) -> Result<Self, LeoError> { fn negate<CS: ConstraintSystem<Fq>>(&self, cs: CS, span: &Span) -> Result<Self, LeoError> {
@ -71,7 +71,7 @@ impl GroupType<Fq> for EdwardsGroupType {
EdwardsGroupType::Constant(group) => Ok(EdwardsGroupType::Constant(group.neg())), EdwardsGroupType::Constant(group) => Ok(EdwardsGroupType::Constant(group.neg())),
EdwardsGroupType::Allocated(group) => { EdwardsGroupType::Allocated(group) => {
let result = <EdwardsBls12Gadget as GroupGadget<Affine<EdwardsParameters>, Fq>>::negate(group, cs) let result = <EdwardsBls12Gadget as GroupGadget<Affine<EdwardsParameters>, Fq>>::negate(group, cs)
.map_err(|e| LeoError::from(CompilerError::group_value_negate_operation(eyre!(e), span)))?; .map_err(|e| CompilerError::group_value_negate_operation(e, span))?;
Ok(EdwardsGroupType::Allocated(Box::new(result))) Ok(EdwardsGroupType::Allocated(Box::new(result)))
} }
@ -90,13 +90,7 @@ impl GroupType<Fq> for EdwardsGroupType {
cs, cs,
other_value, other_value,
) )
.map_err(|e| { .map_err(|e| CompilerError::group_value_binary_operation("+", e, span))?;
LeoError::from(CompilerError::group_value_binary_operation(
"+".to_string(),
eyre!(e),
span,
))
})?;
Ok(EdwardsGroupType::Allocated(Box::new(result))) Ok(EdwardsGroupType::Allocated(Box::new(result)))
} }
@ -104,13 +98,9 @@ impl GroupType<Fq> for EdwardsGroupType {
(EdwardsGroupType::Constant(constant_value), EdwardsGroupType::Allocated(allocated_value)) (EdwardsGroupType::Constant(constant_value), EdwardsGroupType::Allocated(allocated_value))
| (EdwardsGroupType::Allocated(allocated_value), EdwardsGroupType::Constant(constant_value)) => { | (EdwardsGroupType::Allocated(allocated_value), EdwardsGroupType::Constant(constant_value)) => {
Ok(EdwardsGroupType::Allocated(Box::new( Ok(EdwardsGroupType::Allocated(Box::new(
allocated_value.add_constant(cs, constant_value).map_err(|e| { allocated_value
LeoError::from(CompilerError::group_value_binary_operation( .add_constant(cs, constant_value)
"+".to_string(), .map_err(|e| CompilerError::group_value_binary_operation("+", e, span))?,
eyre!(e),
span,
))
})?,
))) )))
} }
} }
@ -128,13 +118,7 @@ impl GroupType<Fq> for EdwardsGroupType {
cs, cs,
other_value, other_value,
) )
.map_err(|e| { .map_err(|e| CompilerError::group_value_binary_operation("-", e, span))?;
LeoError::from(CompilerError::group_value_binary_operation(
"-".to_string(),
eyre!(e),
span,
))
})?;
Ok(EdwardsGroupType::Allocated(Box::new(result))) Ok(EdwardsGroupType::Allocated(Box::new(result)))
} }
@ -142,13 +126,9 @@ impl GroupType<Fq> for EdwardsGroupType {
(EdwardsGroupType::Constant(constant_value), EdwardsGroupType::Allocated(allocated_value)) (EdwardsGroupType::Constant(constant_value), EdwardsGroupType::Allocated(allocated_value))
| (EdwardsGroupType::Allocated(allocated_value), EdwardsGroupType::Constant(constant_value)) => { | (EdwardsGroupType::Allocated(allocated_value), EdwardsGroupType::Constant(constant_value)) => {
Ok(EdwardsGroupType::Allocated(Box::new( Ok(EdwardsGroupType::Allocated(Box::new(
allocated_value.sub_constant(cs, constant_value).map_err(|e| { allocated_value
LeoError::from(CompilerError::group_value_binary_operation( .sub_constant(cs, constant_value)
"-".to_string(), .map_err(|e| CompilerError::group_value_binary_operation("-", e, span))?,
eyre!(e),
span,
))
})?,
))) )))
} }
} }
@ -171,10 +151,12 @@ impl EdwardsGroupType {
} else { } else {
let one = edwards_affine_one(); let one = edwards_affine_one();
let number_value = match number_info { let number_value = match number_info {
(number, neg) if neg => -Fp256::from_str(&number) (number, neg) if neg => {
.map_err(|_| LeoError::from(CompilerError::group_value_n_group(number, span)))?, -Fp256::from_str(&number).map_err(|_| CompilerError::group_value_n_group(number, span))?
(number, _) => Fp256::from_str(&number) }
.map_err(|_| LeoError::from(CompilerError::group_value_n_group(number, span)))?, (number, _) => {
Fp256::from_str(&number).map_err(|_| CompilerError::group_value_n_group(number, span))?
}
}; };
let result: EdwardsAffine = one.mul(number_value); let result: EdwardsAffine = one.mul(number_value);
@ -225,10 +207,10 @@ impl EdwardsGroupType {
Self::edwards_affine_from_y_str(number_string_typing(&y_string), span, None, span) Self::edwards_affine_from_y_str(number_string_typing(&y_string), span, None, span)
} }
// Invalid // Invalid
(x, y) => Err(LeoError::from(CompilerError::group_value_invalid_group( (x, y) => Err(CompilerError::group_value_invalid_group(
format!("({}, {})", x, y), format!("({}, {})", x, y),
span, span,
))), ))?,
} }
} }
@ -239,17 +221,16 @@ impl EdwardsGroupType {
element_span: &Span, element_span: &Span,
) -> Result<EdwardsAffine, LeoError> { ) -> Result<EdwardsAffine, LeoError> {
let x = match x_info { let x = match x_info {
(x_str, neg) if neg => -Fq::from_str(&x_str) (x_str, neg) if neg => {
.map_err(|_| LeoError::from(CompilerError::group_value_x_invalid(x_str, x_span)))?, -Fq::from_str(&x_str).map_err(|_| CompilerError::group_value_x_invalid(x_str, x_span))?
(x_str, _) => {
Fq::from_str(&x_str).map_err(|_| LeoError::from(CompilerError::group_value_x_invalid(x_str, x_span)))?
} }
(x_str, _) => Fq::from_str(&x_str).map_err(|_| CompilerError::group_value_x_invalid(x_str, x_span))?,
}; };
match greatest { match greatest {
// Sign provided // Sign provided
Some(greatest) => EdwardsAffine::from_x_coordinate(x, greatest) Some(greatest) => Ok(EdwardsAffine::from_x_coordinate(x, greatest)
.ok_or_else(|| LeoError::from(CompilerError::group_value_x_recover(element_span))), .ok_or_else(|| CompilerError::group_value_x_recover(element_span))?),
// Sign inferred // Sign inferred
None => { None => {
// Attempt to recover with a sign_low bit. // Attempt to recover with a sign_low bit.
@ -263,7 +244,7 @@ impl EdwardsGroupType {
} }
// Otherwise return error. // Otherwise return error.
Err(LeoError::from(CompilerError::group_value_x_recover(element_span))) Err(CompilerError::group_value_x_recover(element_span))?
} }
} }
} }
@ -275,17 +256,16 @@ impl EdwardsGroupType {
element_span: &Span, element_span: &Span,
) -> Result<EdwardsAffine, LeoError> { ) -> Result<EdwardsAffine, LeoError> {
let y = match y_info { let y = match y_info {
(y_str, neg) if neg => -Fq::from_str(&y_str) (y_str, neg) if neg => {
.map_err(|_| LeoError::from(CompilerError::group_value_y_invalid(y_str, y_span)))?, -Fq::from_str(&y_str).map_err(|_| CompilerError::group_value_y_invalid(y_str, y_span))?
(y_str, _) => {
Fq::from_str(&y_str).map_err(|_| LeoError::from(CompilerError::group_value_y_invalid(y_str, y_span)))?
} }
(y_str, _) => Fq::from_str(&y_str).map_err(|_| CompilerError::group_value_y_invalid(y_str, y_span))?,
}; };
match greatest { match greatest {
// Sign provided // Sign provided
Some(greatest) => EdwardsAffine::from_y_coordinate(y, greatest) Some(greatest) => Ok(EdwardsAffine::from_y_coordinate(y, greatest)
.ok_or_else(|| LeoError::from(CompilerError::group_value_y_recover(element_span))), .ok_or_else(|| CompilerError::group_value_y_recover(element_span))?),
// Sign inferred // Sign inferred
None => { None => {
// Attempt to recover with a sign_low bit. // Attempt to recover with a sign_low bit.
@ -299,7 +279,7 @@ impl EdwardsGroupType {
} }
// Otherwise return error. // Otherwise return error.
Err(LeoError::from(CompilerError::group_value_y_recover(element_span))) Err(CompilerError::group_value_y_recover(element_span))?
} }
} }
} }
@ -312,17 +292,17 @@ impl EdwardsGroupType {
element_span: &Span, element_span: &Span,
) -> Result<EdwardsAffine, LeoError> { ) -> Result<EdwardsAffine, LeoError> {
let x = match x_info { let x = match x_info {
(x_str, neg) if neg => -Fq::from_str(&x_str) (x_str, neg) if neg => {
.map_err(|_| LeoError::from(CompilerError::group_value_x_invalid(x_str.to_string(), x_span)))?, -Fq::from_str(&x_str).map_err(|_| CompilerError::group_value_x_invalid(x_str, x_span))?
(x_str, _) => Fq::from_str(&x_str) }
.map_err(|_| LeoError::from(CompilerError::group_value_x_invalid(x_str.to_string(), x_span)))?, (x_str, _) => Fq::from_str(&x_str).map_err(|_| CompilerError::group_value_x_invalid(x_str, x_span))?,
}; };
let y = match y_info { let y = match y_info {
(y_str, neg) if neg => -Fq::from_str(&y_str) (y_str, neg) if neg => {
.map_err(|_| LeoError::from(CompilerError::group_value_y_invalid(y_str.to_string(), y_span)))?, -Fq::from_str(&y_str).map_err(|_| CompilerError::group_value_y_invalid(y_str, y_span))?
(y_str, _) => Fq::from_str(&y_str) }
.map_err(|_| LeoError::from(CompilerError::group_value_y_invalid(y_str.to_string(), y_span)))?, (y_str, _) => Fq::from_str(&y_str).map_err(|_| CompilerError::group_value_y_invalid(y_str, y_span))?,
}; };
let element = EdwardsAffine::new(x, y); let element = EdwardsAffine::new(x, y);
@ -330,10 +310,7 @@ impl EdwardsGroupType {
if element.is_on_curve() { if element.is_on_curve() {
Ok(element) Ok(element)
} else { } else {
Err(LeoError::from(CompilerError::group_value_not_on_curve( Err(CompilerError::group_value_not_on_curve(element, element_span))?
element.to_string(),
element_span,
)))
} }
} }

View File

@ -20,7 +20,6 @@ use leo_asg::{ConstInt, IntegerType};
use leo_ast::InputValue; use leo_ast::InputValue;
use leo_errors::{CompilerError, LeoError, Span}; use leo_errors::{CompilerError, LeoError, Span};
use eyre::eyre;
use snarkvm_fields::{Field, PrimeField}; use snarkvm_fields::{Field, PrimeField};
use snarkvm_gadgets::{ use snarkvm_gadgets::{
boolean::Boolean, boolean::Boolean,
@ -162,18 +161,15 @@ impl Integer {
if let InputValue::Integer(type_, number) = input { if let InputValue::Integer(type_, number) = input {
let asg_type = IntegerType::from(type_); let asg_type = IntegerType::from(type_);
if std::mem::discriminant(&asg_type) != std::mem::discriminant(integer_type) { if std::mem::discriminant(&asg_type) != std::mem::discriminant(integer_type) {
return Err(LeoError::from(CompilerError::integer_value_integer_type_mismatch( return Err(CompilerError::integer_value_integer_type_mismatch(
integer_type.to_string(), integer_type,
asg_type.to_string(), asg_type,
span, span,
))); ))?;
} }
Some(number) Some(number)
} else { } else {
return Err(LeoError::from(CompilerError::integer_value_invalid_integer( return Err(CompilerError::integer_value_invalid_integer(input, span))?;
input.to_string(),
span,
)));
} }
} }
None => None, None => None,
@ -189,7 +185,7 @@ impl Integer {
let result = match_signed_integer!(a, span => a.neg(cs.ns(|| unique_namespace))); let result = match_signed_integer!(a, span => a.neg(cs.ns(|| unique_namespace)));
result.ok_or_else(|| LeoError::from(CompilerError::integer_value_negate_operation(span))) Ok(result.ok_or_else(|| CompilerError::integer_value_negate_operation(span))?)
} }
pub fn add<F: PrimeField, CS: ConstraintSystem<F>>( pub fn add<F: PrimeField, CS: ConstraintSystem<F>>(
@ -205,7 +201,7 @@ impl Integer {
let result = match_integers_span!((a, b), span => a.add(cs.ns(|| unique_namespace), &b)); let result = match_integers_span!((a, b), span => a.add(cs.ns(|| unique_namespace), &b));
result.ok_or_else(|| LeoError::from(CompilerError::integer_value_binary_operation("+".to_string(), span))) Ok(result.ok_or_else(|| CompilerError::integer_value_binary_operation("+", span))?)
} }
pub fn sub<F: PrimeField, CS: ConstraintSystem<F>>( pub fn sub<F: PrimeField, CS: ConstraintSystem<F>>(
@ -221,7 +217,7 @@ impl Integer {
let result = match_integers_span!((a, b), span => a.sub(cs.ns(|| unique_namespace), &b)); let result = match_integers_span!((a, b), span => a.sub(cs.ns(|| unique_namespace), &b));
result.ok_or_else(|| LeoError::from(CompilerError::integer_value_binary_operation("-".to_string(), span))) Ok(result.ok_or_else(|| CompilerError::integer_value_binary_operation("-", span))?)
} }
pub fn mul<F: PrimeField, CS: ConstraintSystem<F>>( pub fn mul<F: PrimeField, CS: ConstraintSystem<F>>(
@ -237,7 +233,7 @@ impl Integer {
let result = match_integers_span!((a, b), span => a.mul(cs.ns(|| unique_namespace), &b)); let result = match_integers_span!((a, b), span => a.mul(cs.ns(|| unique_namespace), &b));
result.ok_or_else(|| LeoError::from(CompilerError::integer_value_binary_operation("*".to_string(), span))) Ok(result.ok_or_else(|| CompilerError::integer_value_binary_operation("*", span))?)
} }
pub fn div<F: PrimeField, CS: ConstraintSystem<F>>( pub fn div<F: PrimeField, CS: ConstraintSystem<F>>(
@ -253,7 +249,7 @@ impl Integer {
let result = match_integers_span!((a, b), span => a.div(cs.ns(|| unique_namespace), &b)); let result = match_integers_span!((a, b), span => a.div(cs.ns(|| unique_namespace), &b));
result.ok_or_else(|| LeoError::from(CompilerError::integer_value_binary_operation("÷".to_string(), span))) Ok(result.ok_or_else(|| CompilerError::integer_value_binary_operation("÷", span))?)
} }
pub fn pow<F: PrimeField, CS: ConstraintSystem<F>>( pub fn pow<F: PrimeField, CS: ConstraintSystem<F>>(
@ -269,7 +265,7 @@ impl Integer {
let result = match_integers_span!((a, b), span => a.pow(cs.ns(|| unique_namespace), &b)); let result = match_integers_span!((a, b), span => a.pow(cs.ns(|| unique_namespace), &b));
result.ok_or_else(|| LeoError::from(CompilerError::integer_value_binary_operation("**".to_string(), span))) Ok(result.ok_or_else(|| CompilerError::integer_value_binary_operation("**", span))?)
} }
} }

View File

@ -55,31 +55,21 @@ macro_rules! match_unsigned_integer {
macro_rules! match_signed_integer { macro_rules! match_signed_integer {
($integer: ident, $span: ident => $expression: expr) => { ($integer: ident, $span: ident => $expression: expr) => {
match $integer { match $integer {
Integer::I8($integer) => { Integer::I8($integer) => Some(Integer::I8(
Some(Integer::I8($expression.map_err(|e| { $expression.map_err(|e| CompilerError::integer_value_signed(e, $span))?,
LeoError::from(CompilerError::integer_value_signed(eyre!(e), $span)) )),
})?)) Integer::I16($integer) => Some(Integer::I16(
} $expression.map_err(|e| CompilerError::integer_value_signed(e, $span))?,
Integer::I16($integer) => { )),
Some(Integer::I16($expression.map_err(|e| { Integer::I32($integer) => Some(Integer::I32(
LeoError::from(CompilerError::integer_value_signed(eyre!(e), $span)) $expression.map_err(|e| CompilerError::integer_value_signed(e, $span))?,
})?)) )),
} Integer::I64($integer) => Some(Integer::I64(
Integer::I32($integer) => { $expression.map_err(|e| CompilerError::integer_value_signed(e, $span))?,
Some(Integer::I32($expression.map_err(|e| { )),
LeoError::from(CompilerError::integer_value_signed(eyre!(e), $span)) Integer::I128($integer) => Some(Integer::I128(
})?)) $expression.map_err(|e| CompilerError::integer_value_signed(e, $span))?,
} )),
Integer::I64($integer) => {
Some(Integer::I64($expression.map_err(|e| {
LeoError::from(CompilerError::integer_value_signed(eyre!(e), $span))
})?))
}
Integer::I128($integer) => {
Some(Integer::I128($expression.map_err(|e| {
LeoError::from(CompilerError::integer_value_signed(eyre!(e), $span))
})?))
}
_ => None, _ => None,
} }
@ -110,57 +100,37 @@ macro_rules! match_integers {
macro_rules! match_integers_span { macro_rules! match_integers_span {
(($a: ident, $b: ident), $span: ident => $expression:expr) => { (($a: ident, $b: ident), $span: ident => $expression:expr) => {
match ($a, $b) { match ($a, $b) {
(Integer::U8($a), Integer::U8($b)) => { (Integer::U8($a), Integer::U8($b)) => Some(Integer::U8(
Some(Integer::U8($expression.map_err(|e| { $expression.map_err(|e| CompilerError::integer_value_unsigned(e, $span))?,
LeoError::from(CompilerError::integer_value_unsigned(eyre!(e), $span)) )),
})?)) (Integer::U16($a), Integer::U16($b)) => Some(Integer::U16(
} $expression.map_err(|e| CompilerError::integer_value_unsigned(e, $span))?,
(Integer::U16($a), Integer::U16($b)) => { )),
Some(Integer::U16($expression.map_err(|e| { (Integer::U32($a), Integer::U32($b)) => Some(Integer::U32(
LeoError::from(CompilerError::integer_value_unsigned(eyre!(e), $span)) $expression.map_err(|e| CompilerError::integer_value_unsigned(e, $span))?,
})?)) )),
} (Integer::U64($a), Integer::U64($b)) => Some(Integer::U64(
(Integer::U32($a), Integer::U32($b)) => { $expression.map_err(|e| CompilerError::integer_value_unsigned(e, $span))?,
Some(Integer::U32($expression.map_err(|e| { )),
LeoError::from(CompilerError::integer_value_unsigned(eyre!(e), $span)) (Integer::U128($a), Integer::U128($b)) => Some(Integer::U128(
})?)) $expression.map_err(|e| CompilerError::integer_value_unsigned(e, $span))?,
} )),
(Integer::U64($a), Integer::U64($b)) => {
Some(Integer::U64($expression.map_err(|e| {
LeoError::from(CompilerError::integer_value_unsigned(eyre!(e), $span))
})?))
}
(Integer::U128($a), Integer::U128($b)) => {
Some(Integer::U128($expression.map_err(|e| {
LeoError::from(CompilerError::integer_value_unsigned(eyre!(e), $span))
})?))
}
(Integer::I8($a), Integer::I8($b)) => { (Integer::I8($a), Integer::I8($b)) => Some(Integer::I8(
Some(Integer::I8($expression.map_err(|e| { $expression.map_err(|e| CompilerError::integer_value_unsigned(e, $span))?,
LeoError::from(CompilerError::integer_value_unsigned(eyre!(e), $span)) )),
})?)) (Integer::I16($a), Integer::I16($b)) => Some(Integer::I16(
} $expression.map_err(|e| CompilerError::integer_value_unsigned(e, $span))?,
(Integer::I16($a), Integer::I16($b)) => { )),
Some(Integer::I16($expression.map_err(|e| { (Integer::I32($a), Integer::I32($b)) => Some(Integer::I32(
LeoError::from(CompilerError::integer_value_unsigned(eyre!(e), $span)) $expression.map_err(|e| CompilerError::integer_value_unsigned(e, $span))?,
})?)) )),
} (Integer::I64($a), Integer::I64($b)) => Some(Integer::I64(
(Integer::I32($a), Integer::I32($b)) => { $expression.map_err(|e| CompilerError::integer_value_unsigned(e, $span))?,
Some(Integer::I32($expression.map_err(|e| { )),
LeoError::from(CompilerError::integer_value_unsigned(eyre!(e), $span)) (Integer::I128($a), Integer::I128($b)) => Some(Integer::I128(
})?)) $expression.map_err(|e| CompilerError::integer_value_unsigned(e, $span))?,
} )),
(Integer::I64($a), Integer::I64($b)) => {
Some(Integer::I64($expression.map_err(|e| {
LeoError::from(CompilerError::integer_value_unsigned(eyre!(e), $span))
})?))
}
(Integer::I128($a), Integer::I128($b)) => {
Some(Integer::I128($expression.map_err(|e| {
LeoError::from(CompilerError::integer_value_unsigned(eyre!(e), $span))
})?))
}
(_, _) => None, (_, _) => None,
} }
}; };
@ -171,7 +141,7 @@ macro_rules! allocate_type {
let option = $option let option = $option
.map(|s| { .map(|s| {
s.parse::<$rust_ty>() s.parse::<$rust_ty>()
.map_err(|_| LeoError::from(CompilerError::integer_value_invalid_integer(s, $span))) .map_err(|_| CompilerError::integer_value_invalid_integer(s, $span))
}) })
.transpose()?; .transpose()?;
@ -188,10 +158,10 @@ macro_rules! allocate_type {
|| option.ok_or(SynthesisError::AssignmentMissing), || option.ok_or(SynthesisError::AssignmentMissing),
) )
.map_err(|_| { .map_err(|_| {
LeoError::from(CompilerError::integer_value_missing_integer( CompilerError::integer_value_missing_integer(
format!("{}: {}", $name.to_string(), stringify!($rust_ty)), format!("{}: {}", $name.to_string(), stringify!($rust_ty)),
$span, $span,
)) )
})?; })?;
$leo_ty(result) $leo_ty(result)

View File

@ -16,6 +16,8 @@
use crate::create_errors; use crate::create_errors;
use std::fmt::{Debug, Display};
create_errors!( create_errors!(
AsgError, AsgError,
exit_code_mask: 0u32, exit_code_mask: 0u32,
@ -23,21 +25,21 @@ create_errors!(
@formatted @formatted
unresolved_circuit { unresolved_circuit {
args: (name: &str), args: (name: impl Display),
msg: format!("failed to resolve circuit: '{}'", name), msg: format!("failed to resolve circuit: '{}'", name),
help: None, help: None,
} }
@formatted @formatted
unresolved_import { unresolved_import {
args: (name: &str), args: (name: impl Display),
msg: format!("failed to resolve import: '{}'", name), msg: format!("failed to resolve import: '{}'", name),
help: None, help: None,
} }
@formatted @formatted
unresolved_circuit_member { unresolved_circuit_member {
args: (circuit_name: &str, name: &str), args: (circuit_name: impl Display, name: impl Display),
msg: format!( msg: format!(
"illegal reference to non-existant member '{}' of circuit '{}'", "illegal reference to non-existant member '{}' of circuit '{}'",
name, circuit_name name, circuit_name
@ -47,7 +49,7 @@ create_errors!(
@formatted @formatted
missing_circuit_member { missing_circuit_member {
args: (circuit_name: &str, name: &str), args: (circuit_name: impl Display, name: impl Display),
msg: format!( msg: format!(
"missing circuit member '{}' for initialization of circuit '{}'", "missing circuit member '{}' for initialization of circuit '{}'",
name, circuit_name name, circuit_name
@ -57,7 +59,7 @@ create_errors!(
@formatted @formatted
overridden_circuit_member { overridden_circuit_member {
args: (circuit_name: &str, name: &str), args: (circuit_name: impl Display, name: impl Display),
msg: format!( msg: format!(
"cannot declare circuit member '{}' more than once for initialization of circuit '{}'", "cannot declare circuit member '{}' more than once for initialization of circuit '{}'",
name, circuit_name name, circuit_name
@ -67,7 +69,7 @@ create_errors!(
@formatted @formatted
redefined_circuit_member { redefined_circuit_member {
args: (circuit_name: &str, name: &str), args: (circuit_name: impl Display, name: impl Display),
msg: format!( msg: format!(
"cannot declare circuit member '{}' multiple times in circuit '{}'", "cannot declare circuit member '{}' multiple times in circuit '{}'",
name, circuit_name name, circuit_name
@ -77,7 +79,7 @@ create_errors!(
@formatted @formatted
extra_circuit_member { extra_circuit_member {
args: (circuit_name: &str, name: &str), args: (circuit_name: impl Display, name: impl Display),
msg: format!( msg: format!(
"extra circuit member '{}' for initialization of circuit '{}' is not allowed", "extra circuit member '{}' for initialization of circuit '{}' is not allowed",
name, circuit_name name, circuit_name
@ -87,21 +89,21 @@ create_errors!(
@formatted @formatted
illegal_function_assign { illegal_function_assign {
args: (name: &str), args: (name: impl Display),
msg: format!("attempt to assign to function '{}'", name), msg: format!("attempt to assign to function '{}'", name),
help: None, help: None,
} }
@formatted @formatted
circuit_variable_call { circuit_variable_call {
args: (circuit_name: &str, name: &str), args: (circuit_name: impl Display, name: impl Display),
msg: format!("cannot call variable member '{}' of circuit '{}'", name, circuit_name), msg: format!("cannot call variable member '{}' of circuit '{}'", name, circuit_name),
help: None, help: None,
} }
@formatted @formatted
circuit_static_call_invalid { circuit_static_call_invalid {
args: (circuit_name: &str, name: &str), args: (circuit_name: impl Display, name: impl Display),
msg: format!( msg: format!(
"cannot call static function '{}' of circuit '{}' from target", "cannot call static function '{}' of circuit '{}' from target",
name, circuit_name name, circuit_name
@ -111,7 +113,7 @@ create_errors!(
@formatted @formatted
circuit_member_mut_call_invalid { circuit_member_mut_call_invalid {
args: (circuit_name: &str, name: &str), args: (circuit_name: impl Display, name: impl Display),
msg: format!( msg: format!(
"cannot call mutable member function '{}' of circuit '{}' from immutable context", "cannot call mutable member function '{}' of circuit '{}' from immutable context",
name, circuit_name name, circuit_name
@ -121,7 +123,7 @@ create_errors!(
@formatted @formatted
circuit_member_call_invalid { circuit_member_call_invalid {
args: (circuit_name: &str, name: &str), args: (circuit_name: impl Display, name: impl Display),
msg: format!( msg: format!(
"cannot call member function '{}' of circuit '{}' from static context", "cannot call member function '{}' of circuit '{}' from static context",
name, circuit_name name, circuit_name
@ -131,7 +133,7 @@ create_errors!(
@formatted @formatted
circuit_function_ref { circuit_function_ref {
args: (circuit_name: &str, name: &str), args: (circuit_name: impl Display, name: impl Display),
msg: format!( msg: format!(
"cannot reference function member '{}' of circuit '{}' as value", "cannot reference function member '{}' of circuit '{}' as value",
name, circuit_name name, circuit_name
@ -141,21 +143,21 @@ create_errors!(
@formatted @formatted
index_into_non_array { index_into_non_array {
args: (name: &str), args: (name: impl Display),
msg: format!("failed to index into non-array '{}'", name), msg: format!("failed to index into non-array '{}'", name),
help: None, help: None,
} }
@formatted @formatted
invalid_assign_index { invalid_assign_index {
args: (name: &str, num: &str), args: (name: impl Display, num: impl Display),
msg: format!("failed to index array with invalid integer '{}'[{}]", name, num), msg: format!("failed to index array with invalid integer '{}'[{}]", name, num),
help: None, help: None,
} }
@formatted @formatted
invalid_backwards_assignment { invalid_backwards_assignment {
args: (name: &str, left: usize, right: usize), args: (name: impl Display, left: impl Display, right: impl Display),
msg: format!( msg: format!(
"failed to index array range for assignment with left > right '{}'[{}..{}]", "failed to index array range for assignment with left > right '{}'[{}..{}]",
name, left, right name, left, right
@ -165,7 +167,7 @@ create_errors!(
@formatted @formatted
invalid_const_assign { invalid_const_assign {
args: (name: &str), args: (name: impl Display),
msg: format!( msg: format!(
"failed to create const variable(s) '{}' with non constant values.", "failed to create const variable(s) '{}' with non constant values.",
name name
@ -175,42 +177,42 @@ create_errors!(
@formatted @formatted
duplicate_function_definition { duplicate_function_definition {
args: (name: &str), args: (name: impl Display),
msg: format!("a function named \"{}\" already exists in this scope", name), msg: format!("a function named \"{}\" already exists in this scope", name),
help: None, help: None,
} }
@formatted @formatted
duplicate_variable_definition { duplicate_variable_definition {
args: (name: &str), args: (name: impl Display),
msg: format!("a variable named \"{}\" already exists in this scope", name), msg: format!("a variable named \"{}\" already exists in this scope", name),
help: None, help: None,
} }
@formatted @formatted
index_into_non_tuple { index_into_non_tuple {
args: (name: &str), args: (name: impl Display),
msg: format!("failed to index into non-tuple '{}'", name), msg: format!("failed to index into non-tuple '{}'", name),
help: None, help: None,
} }
@formatted @formatted
tuple_index_out_of_bounds { tuple_index_out_of_bounds {
args: (index: usize), args: (index: impl Display),
msg: format!("tuple index out of bounds: '{}'", index), msg: format!("tuple index out of bounds: '{}'", index),
help: None, help: None,
} }
@formatted @formatted
array_index_out_of_bounds { array_index_out_of_bounds {
args: (index: usize), args: (index: impl Display),
msg: format!("array index out of bounds: '{}'", index), msg: format!("array index out of bounds: '{}'", index),
help: None, help: None,
} }
@formatted @formatted
ternary_different_types { ternary_different_types {
args: (left: &str, right: &str), args: (left: impl Display, right: impl Display),
msg: format!("ternary sides had different types: left {}, right {}", left, right), msg: format!("ternary sides had different types: left {}, right {}", left, right),
help: None, help: None,
} }
@ -224,32 +226,32 @@ create_errors!(
@formatted @formatted
unexpected_call_argument_count { unexpected_call_argument_count {
args: (expected: usize, got: usize), args: (expected: impl Display, got: impl Display),
msg: format!("function call expected {} arguments, got {}", expected, got), msg: format!("function call expected {} arguments, got {}", expected, got),
help: None, help: None,
} }
@formatted @formatted
unresolved_function { unresolved_function {
args: (name: &str), args: (name: impl Display),
msg: format!("failed to resolve function: '{}'", name), msg: format!("failed to resolve function: '{}'", name),
help: None, help: None,
} }
@formatted @formatted
unresolved_type { unresolved_type {
args: (name: &str), args: (name: impl Display),
msg: format!("failed to resolve type for variable definition '{}'", name), msg: format!("failed to resolve type for variable definition '{}'", name),
help: None, help: None,
} }
@formatted @formatted
unexpected_type { unexpected_type {
args: (expected: &str, received: Option<&str>), args: (expected: impl Display, received: impl Display),
msg: format!( msg: format!(
"unexpected type, expected: '{}', received: '{}'", "unexpected type, expected: '{}', received: '{}'",
expected, expected,
received.unwrap_or("unknown") received,
), ),
help: None, help: None,
} }
@ -263,28 +265,28 @@ create_errors!(
@formatted @formatted
unresolved_reference { unresolved_reference {
args: (name: &str), args: (name: impl Display),
msg: format!("failed to resolve variable reference '{}'", name), msg: format!("failed to resolve variable reference '{}'", name),
help: None, help: None,
} }
@formatted @formatted
invalid_boolean { invalid_boolean {
args: (value: &str), args: (value: impl Display),
msg: format!("failed to parse boolean value '{}'", value), msg: format!("failed to parse boolean value '{}'", value),
help: None, help: None,
} }
@formatted @formatted
invalid_char { invalid_char {
args: (value: &str), args: (value: impl Display),
msg: format!("failed to parse char value '{}'", value), msg: format!("failed to parse char value '{}'", value),
help: None, help: None,
} }
@formatted @formatted
invalid_int { invalid_int {
args: (value: &str), args: (value: impl Display),
msg: format!("failed to parse int value '{}'", value), msg: format!("failed to parse int value '{}'", value),
help: None, help: None,
} }
@ -298,28 +300,28 @@ create_errors!(
@formatted @formatted
immutable_assignment { immutable_assignment {
args: (name: &str), args: (name: impl Display),
msg: format!("illegal assignment to immutable variable '{}'", name), msg: format!("illegal assignment to immutable variable '{}'", name),
help: None, help: None,
} }
@formatted @formatted
function_missing_return { function_missing_return {
args: (name: &str), args: (name: impl Display),
msg: format!("function '{}' missing return for all paths", name), msg: format!("function '{}' missing return for all paths", name),
help: None, help: None,
} }
@formatted @formatted
function_return_validation { function_return_validation {
args: (name: &str, description: &str), args: (name: impl Display, description: impl Display),
msg: format!("function '{}' failed to validate return path: '{}'", name, description), msg: format!("function '{}' failed to validate return path: '{}'", name, description),
help: None, help: None,
} }
@formatted @formatted
input_ref_needs_type { input_ref_needs_type {
args: (category: &str, name: &str), args: (category: impl Display, name: impl Display),
msg: format!("could not infer type for input in '{}': '{}'", category, name), msg: format!("could not infer type for input in '{}': '{}'", category, name),
help: None, help: None,
} }
@ -368,14 +370,14 @@ create_errors!(
@formatted @formatted
illegal_ast_structure { illegal_ast_structure {
args: (details: &str), args: (details: impl Display),
msg: format!("illegal ast structure: {}", details), msg: format!("illegal ast structure: {}", details),
help: None, help: None,
} }
@formatted @formatted
illegal_input_variable_reference { illegal_input_variable_reference {
args: (details: &str), args: (details: impl Display),
msg: format!("illegal ast structure: {}", details), msg: format!("illegal ast structure: {}", details),
help: None, help: None,
} }

View File

@ -15,12 +15,48 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>. // along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::create_errors; use crate::create_errors;
use std::{error::Error as ErrorArg, fmt::Debug};
create_errors!( create_errors!(
AstError, AstError,
exit_code_mask: 1000u32, exit_code_mask: 1000u32,
error_code_prefix: "T", error_code_prefix: "T",
@backtraced
failed_to_convert_ast_to_json_string {
args: (error: impl ErrorArg),
msg: format!("failed to convert ast to a json string {}", error),
help: None,
}
@backtraced
failed_to_create_ast_json_file {
args: (path: impl Debug, error: impl ErrorArg),
msg: format!("failed to creat ast json file `{:?}` {}", path, error),
help: None,
}
@backtraced
failed_to_write_ast_to_json_file {
args: (path: impl Debug, error: impl ErrorArg),
msg: format!("failed to write ast to a json file `{:?}` {}", path, error),
help: None,
}
@backtraced
failed_to_read_json_string_to_ast {
args: (error: impl ErrorArg),
msg: format!("failed to convert json stirng to an ast {}", error),
help: None,
}
@backtraced
failed_to_read_json_file {
args: (path: impl Debug, error: impl ErrorArg),
msg: format!("failed to convert json file `{:?}` to an ast {}", path, error),
help: None,
}
@formatted @formatted
big_self_outside_of_circuit { big_self_outside_of_circuit {
args: (), args: (),

View File

@ -35,7 +35,7 @@ pub struct BacktracedError {
pub message: String, pub message: String,
pub help: Option<String>, pub help: Option<String>,
pub exit_code: u32, pub exit_code: u32,
pub code_identifier: String, pub code_identifier: u32,
pub error_type: String, pub error_type: String,
#[derivative(PartialEq = "ignore")] #[derivative(PartialEq = "ignore")]
#[derivative(Hash = "ignore")] #[derivative(Hash = "ignore")]
@ -45,9 +45,9 @@ pub struct BacktracedError {
impl BacktracedError { impl BacktracedError {
pub fn new_from_backtrace<S>( pub fn new_from_backtrace<S>(
message: S, message: S,
help: Option<S>, help: Option<String>,
exit_code: u32, exit_code: u32,
code_identifier: String, code_identifier: u32,
error_type: String, error_type: String,
backtrace: Backtrace, backtrace: Backtrace,
) -> Self ) -> Self
@ -63,12 +63,16 @@ impl BacktracedError {
backtrace, backtrace,
} }
} }
pub fn exit_code(&self) -> u32 {
0
}
} }
impl fmt::Display for BacktracedError { impl fmt::Display for BacktracedError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let error_message = format!( let error_message = format!(
"{indent }[E{error_type}{code_identifier}{exit_code}]: {message}\ "[E{error_type}{code_identifier:0>3}{exit_code:0>4}]: {message}\
{indent } ", {indent } ",
indent = INDENT, indent = INDENT,
error_type = self.error_type, error_type = self.error_type,
@ -83,7 +87,11 @@ impl fmt::Display for BacktracedError {
write!(f, "{indent } = {help}", indent = INDENT, help = help)?; write!(f, "{indent } = {help}", indent = INDENT, help = help)?;
} }
write!(f, "stack backtrace:\n{:?}", self.backtrace) if std::env::var("LEO_BACKTRACE").unwrap_or_default().trim() == "1" {
write!(f, "stack backtrace:\n{:?}", self.backtrace)?;
}
Ok(())
} }
} }

View File

@ -42,9 +42,9 @@ pub struct FormattedError {
impl FormattedError { impl FormattedError {
pub fn new_from_span<S>( pub fn new_from_span<S>(
message: S, message: S,
help: Option<S>, help: Option<String>,
exit_code: u32, exit_code: u32,
code_identifier: String, code_identifier: u32,
error_type: String, error_type: String,
span: &Span, span: &Span,
) -> Self ) -> Self
@ -68,6 +68,10 @@ impl FormattedError {
), ),
} }
} }
pub fn exit_code(&self) -> u32 {
0
}
} }
impl fmt::Display for FormattedError { impl fmt::Display for FormattedError {
@ -91,11 +95,11 @@ impl fmt::Display for FormattedError {
underline underline
}; };
let underlined = underline(self.col_start, self.col_start); let underlined = underline(self.col_start, self.col_stop);
let error_message = format!( let error_message = format!(
"[E{error_type}{code_identifier}{exit_code:0>4}]: {message}\n\ "[E{error_type}{code_identifier:0>3}{exit_code:0>4}]: {message}\n \
--> {path}:{line_start}:{start}\n\ --> {path}:{line_start}:{start}\n\
{indent } ", {indent } ",
indent = INDENT, indent = INDENT,
error_type = self.backtrace.error_type, error_type = self.backtrace.error_type,
@ -131,7 +135,11 @@ impl fmt::Display for FormattedError {
write!(f, "{indent } = {help}", indent = INDENT, help = help)?; write!(f, "{indent } = {help}", indent = INDENT, help = help)?;
} }
write!(f, "stack backtrace:\n{:?}", self.backtrace.backtrace) if std::env::var("LEO_BACKTRACE").unwrap_or_default().trim() == "1" {
write!(f, "stack backtrace:\n{:?}", self.backtrace.backtrace)?;
}
Ok(())
} }
} }

View File

@ -22,6 +22,7 @@ macro_rules! create_errors {
use backtrace::Backtrace; use backtrace::Backtrace;
#[derive(Debug, Error)] #[derive(Debug, Error)]
pub enum $error_type { pub enum $error_type {
#[error(transparent)] #[error(transparent)]
@ -34,6 +35,19 @@ macro_rules! create_errors {
impl LeoErrorCode for $error_type {} impl LeoErrorCode for $error_type {}
impl ErrorCode for $error_type { impl ErrorCode for $error_type {
#[inline(always)]
fn exit_code(&self) -> u32 {
match self {
Self::FormattedError(formatted) => {
formatted.exit_code()
},
Self::BacktracedError(backtraced) => {
backtraced.exit_code()
}
}
}
#[inline(always)] #[inline(always)]
fn exit_code_mask() -> u32 { fn exit_code_mask() -> u32 {
$exit_code_mask $exit_code_mask
@ -44,20 +58,20 @@ macro_rules! create_errors {
$error_code_prefix.to_string() $error_code_prefix.to_string()
} }
fn new_from_backtrace<S>(message: S, help: Option<S>, exit_code: u32, backtrace: Backtrace) -> Self fn new_from_backtrace<S>(message: S, help: Option<String>, exit_code: u32, backtrace: Backtrace) -> Self
where where
S: ToString { S: ToString {
BacktracedError::new_from_backtrace( BacktracedError::new_from_backtrace(
message, message,
help, help,
exit_code + Self::exit_code_mask(), exit_code + Self::exit_code_mask(),
Self::code_identifier(), Self::code_identifier(),
Self::error_type(), Self::error_type(),
backtrace, backtrace,
).into() ).into()
} }
fn new_from_span<S>(message: S, help: Option<S>, exit_code: u32, span: &Span) -> Self fn new_from_span<S>(message: S, help: Option<String>, exit_code: u32, span: &Span) -> Self
where S: ToString { where S: ToString {
FormattedError::new_from_span( FormattedError::new_from_span(
message, message,

View File

@ -32,3 +32,8 @@ pub use self::tendril_json::*;
pub mod traits; pub mod traits;
pub use self::traits::*; pub use self::traits::*;
// Can make the args cleaner once https://github.com/rust-lang/rust/issues/41517 or https://github.com/rust-lang/rust/issues/63063 hits stable.
// pub(crate) type DisplayArg = impl std::fmt::Display;
// pub(crate) type DebugArg = impl std::fmt::Debug;
// pub(crate) type ErrorArg = impl std::error::Error;

View File

@ -19,22 +19,24 @@ use crate::Span;
use backtrace::Backtrace; use backtrace::Backtrace;
pub trait ErrorCode: Sized { pub trait ErrorCode: Sized {
fn exit_code(&self) -> u32;
fn exit_code_mask() -> u32; fn exit_code_mask() -> u32;
fn error_type() -> String; fn error_type() -> String;
fn new_from_backtrace<S>(message: S, help: Option<S>, exit_code: u32, backtrace: Backtrace) -> Self fn new_from_backtrace<S>(message: S, help: Option<String>, exit_code: u32, backtrace: Backtrace) -> Self
where where
S: ToString; S: ToString;
fn new_from_span<S>(message: S, help: Option<S>, exit_code: u32, span: &Span) -> Self fn new_from_span<S>(message: S, help: Option<String>, exit_code: u32, span: &Span) -> Self
where where
S: ToString; S: ToString;
} }
pub trait LeoErrorCode: ErrorCode { pub trait LeoErrorCode: ErrorCode {
#[inline(always)] #[inline(always)]
fn code_identifier() -> String { fn code_identifier() -> u32 {
"037".to_string() 037
} }
} }

View File

@ -16,7 +16,10 @@
use crate::create_errors; use crate::create_errors;
use eyre::ErrReport; use std::{
error::Error as ErrorArg,
fmt::{Debug, Display},
};
create_errors!( create_errors!(
CompilerError, CompilerError,
@ -25,14 +28,14 @@ create_errors!(
@backtraced @backtraced
invalid_test_context { invalid_test_context {
args: (name: String), args: (name: impl Display),
msg: format!("Cannot find input files with context name `{}`", name), msg: format!("Cannot find input files with context name `{}`", name),
help: None, help: None,
} }
@backtraced @backtraced
file_read_error { file_read_error {
args: (path: std::path::PathBuf, error: ErrReport), args: (path: impl Debug, error: impl ErrorArg),
msg: format!("Cannot read from the provided file path '{:?}': {}", path, error), msg: format!("Cannot read from the provided file path '{:?}': {}", path, error),
help: None, help: None,
} }
@ -67,7 +70,7 @@ create_errors!(
@formatted @formatted
console_container_parameter_length_mismatch { console_container_parameter_length_mismatch {
args: (containers: usize, parameters: usize), args: (containers: impl Display, parameters: impl Display),
msg: format!( msg: format!(
"Formatter given {} containers and found {} parameters", "Formatter given {} containers and found {} parameters",
containers, parameters containers, parameters
@ -99,7 +102,7 @@ create_errors!(
@formatted @formatted
cannot_enforce_expression { cannot_enforce_expression {
args: (operation: String, error: ErrReport), args: (operation: impl Display, error: impl ErrorArg),
msg: format!( msg: format!(
"the gadget operation `{}` failed due to synthesis error `{:?}`", "the gadget operation `{}` failed due to synthesis error `{:?}`",
operation, error, operation, error,
@ -109,7 +112,7 @@ create_errors!(
@formatted @formatted
cannot_evaluate_expression { cannot_evaluate_expression {
args: (operation: String), args: (operation: impl Display),
msg: format!("Mismatched types found for operation `{}`", operation), msg: format!("Mismatched types found for operation `{}`", operation),
help: None, help: None,
} }
@ -130,35 +133,35 @@ create_errors!(
@formatted @formatted
conditional_boolean_expression_fails_to_resolve_to_bool { conditional_boolean_expression_fails_to_resolve_to_bool {
args: (actual: String), args: (actual: impl Display),
msg: format!("if, else conditional must resolve to a boolean, found `{}`", actual), msg: format!("if, else conditional must resolve to a boolean, found `{}`", actual),
help: None, help: None,
} }
@formatted @formatted
expected_circuit_member { expected_circuit_member {
args: (expected: String), args: (expected: impl Display),
msg: format!("expected circuit member `{}`, not found", expected), msg: format!("expected circuit member `{}`, not found", expected),
help: None, help: None,
} }
@formatted @formatted
incompatible_types { incompatible_types {
args: (operation: String), args: (operation: impl Display),
msg: format!("no implementation for `{}`", operation), msg: format!("no implementation for `{}`", operation),
help: None, help: None,
} }
@formatted @formatted
tuple_index_out_of_bounds { tuple_index_out_of_bounds {
args: (index: usize), args: (index: impl Display),
msg: format!("cannot access index {} of tuple out of bounds", index), msg: format!("cannot access index {} of tuple out of bounds", index),
help: None, help: None,
} }
@formatted @formatted
array_index_out_of_bounds { array_index_out_of_bounds {
args: (index: usize), args: (index: impl Display),
msg: format!("cannot access index {} of array out of bounds", index), msg: format!("cannot access index {} of array out of bounds", index),
help: None, help: None,
} }
@ -172,35 +175,35 @@ create_errors!(
@formatted @formatted
invalid_index_expression { invalid_index_expression {
args: (actual: String), args: (actual: impl Display),
msg: format!("index must resolve to an integer, found `{}`", actual), msg: format!("index must resolve to an integer, found `{}`", actual),
help: None, help: None,
} }
@formatted @formatted
unexpected_array_length { unexpected_array_length {
args: (expected: usize, actual: usize), args: (expected: impl Display, actual: impl Display),
msg: format!("expected array length {}, found one with length {}", expected, actual), msg: format!("expected array length {}, found one with length {}", expected, actual),
help: None, help: None,
} }
@formatted @formatted
invalid_circuit_static_member_access { invalid_circuit_static_member_access {
args: (member: String), args: (member: impl Display),
msg: format!("invalid circuit static member `{}` must be accessed using `::` syntax", member), msg: format!("invalid circuit static member `{}` must be accessed using `::` syntax", member),
help: None, help: None,
} }
@formatted @formatted
undefined_array { undefined_array {
args: (actual: String), args: (actual: impl Display),
msg: format!("array `{}` must be declared before it is used in an expression", actual), msg: format!("array `{}` must be declared before it is used in an expression", actual),
help: None, help: None,
} }
@formatted @formatted
undefined_circuit { undefined_circuit {
args: (actual: String), args: (actual: impl Display),
msg: format!( msg: format!(
"circuit `{}` must be declared before it is used in an expression", "circuit `{}` must be declared before it is used in an expression",
actual actual
@ -210,21 +213,21 @@ create_errors!(
@formatted @formatted
undefined_identifier { undefined_identifier {
args: (name: &str), args: (name: impl Display),
msg: format!("Cannot find value `{}` in this scope", name), msg: format!("Cannot find value `{}` in this scope", name),
help: None, help: None,
} }
@formatted @formatted
undefined_circuit_member_access { undefined_circuit_member_access {
args: (circuit: String, member: String), args: (circuit: impl Display, member: impl Display),
msg: format!("Circuit `{}` has no member `{}`", circuit, member), msg: format!("Circuit `{}` has no member `{}`", circuit, member),
help: None, help: None,
} }
@formatted @formatted
input_variable_type_mismatch { input_variable_type_mismatch {
args: (expected: String, actual: String, variable: String), args: (expected: impl Display, actual: impl Display, variable: impl Display),
msg: format!( msg: format!(
"Expected input variable `{}` to be type `{}`, found type `{}`", "Expected input variable `{}` to be type `{}`, found type `{}`",
variable, expected, actual variable, expected, actual
@ -234,7 +237,7 @@ create_errors!(
@formatted @formatted
expected_const_input_variable { expected_const_input_variable {
args: (variable: String), args: (variable: impl Display),
msg: format!( msg: format!(
"Expected input variable `{}` to be constant. Move input variable `{}` to [constants] section of input file", "Expected input variable `{}` to be constant. Move input variable `{}` to [constants] section of input file",
variable, variable variable, variable
@ -244,7 +247,7 @@ create_errors!(
@formatted @formatted
expected_non_const_input_variable { expected_non_const_input_variable {
args: (variable: String), args: (variable: impl Display),
msg: format!( msg: format!(
"Expected input variable `{}` to be non-constant. Move input variable `{}` to [main] section of input file", "Expected input variable `{}` to be non-constant. Move input variable `{}` to [main] section of input file",
variable, variable variable, variable
@ -254,14 +257,14 @@ create_errors!(
@formatted @formatted
invalid_function_input_array { invalid_function_input_array {
args: (actual: String), args: (actual: impl Display),
msg: format!("Expected function input array, found `{}`", actual), msg: format!("Expected function input array, found `{}`", actual),
help: None, help: None,
} }
@formatted @formatted
invalid_input_array_dimensions { invalid_input_array_dimensions {
args: (expected: usize, actual: usize), args: (expected: impl Display, actual: impl Display),
msg: format!( msg: format!(
"Input array dimensions mismatch expected {}, found array dimensions {}", "Input array dimensions mismatch expected {}, found array dimensions {}",
expected, actual expected, actual
@ -271,7 +274,7 @@ create_errors!(
@formatted @formatted
input_tuple_size_mismatch { input_tuple_size_mismatch {
args: (expected: usize, actual: usize), args: (expected: impl Display, actual: impl Display),
msg: format!( msg: format!(
"Input tuple size mismatch expected {}, found tuple with length {}", "Input tuple size mismatch expected {}, found tuple with length {}",
expected, actual expected, actual
@ -281,21 +284,21 @@ create_errors!(
@formatted @formatted
invalid_function_input_tuple { invalid_function_input_tuple {
args: (actual: String), args: (actual: impl Display),
msg: format!("Expected function input tuple, found `{}`", actual), msg: format!("Expected function input tuple, found `{}`", actual),
help: None, help: None,
} }
@formatted @formatted
function_input_not_found { function_input_not_found {
args: (function: String, expected: String), args: (function: impl Display, expected: impl Display),
msg: format!("function `{}` input {} not found", function, expected), msg: format!("function `{}` input {} not found", function, expected),
help: None, help: None,
} }
@formatted @formatted
double_input_declaration { double_input_declaration {
args: (input_name: String), args: (input_name: impl Display),
msg: format!("Input variable {} declared twice", input_name), msg: format!("Input variable {} declared twice", input_name),
help: None, help: None,
} }
@ -309,7 +312,7 @@ create_errors!(
@formatted @formatted
output_mismatched_types { output_mismatched_types {
args: (left: String, right: String), args: (left: impl Display, right: impl Display),
msg: format!( msg: format!(
"Mismatched types. Expected register output type `{}`, found type `{}`.", "Mismatched types. Expected register output type `{}`, found type `{}`.",
left, right left, right
@ -319,28 +322,28 @@ create_errors!(
@backtraced @backtraced
output_file_error { output_file_error {
args: (error: ErrReport), args: (error: impl ErrorArg),
msg: error, msg: error,
help: None, help: None,
} }
@backtraced @backtraced
output_file_io_error { output_file_io_error {
args: (error: ErrReport), args: (error: impl ErrorArg),
msg: error, msg: error,
help: None, help: None,
} }
@backtraced @backtraced
output_file_cannot_read { output_file_cannot_read {
args: (path: std::path::PathBuf), args: (path: impl Debug),
msg: format!("Cannot read the provided ouput file - {:?}", path), msg: format!("Cannot read the provided ouput file - {:?}", path),
help: None, help: None,
} }
@backtraced @backtraced
output_file_cannot_remove { output_file_cannot_remove {
args: (path: std::path::PathBuf), args: (path: impl Debug),
msg: format!("Cannot remove the provided ouput file - {:?}", path), msg: format!("Cannot remove the provided ouput file - {:?}", path),
help: None, help: None,
} }
@ -375,7 +378,7 @@ create_errors!(
@formatted @formatted
statement_array_assign_index_bounds { statement_array_assign_index_bounds {
args: (index: usize, length: usize), args: (index: impl Display, length: impl Display),
msg: format!( msg: format!(
"Array assign index `{}` out of range for array of length `{}`", "Array assign index `{}` out of range for array of length `{}`",
index, length index, length
@ -385,7 +388,7 @@ create_errors!(
@formatted @formatted
statement_array_assign_range_order { statement_array_assign_range_order {
args: (start: usize, stop: usize, length: usize), args: (start: impl Display, stop: impl Display, length: impl Display),
msg: format!( msg: format!(
"Array assign range `{}`..`{}` out of range for array of length `{}`", "Array assign range `{}`..`{}` out of range for array of length `{}`",
start, stop, length start, stop, length
@ -395,14 +398,14 @@ create_errors!(
@formatted @formatted
statement_conditional_boolean_fails_to_resolve_to_boolean { statement_conditional_boolean_fails_to_resolve_to_boolean {
args: (actual: String), args: (actual: impl Display),
msg: format!("If, else conditional must resolve to a boolean, found `{}`", actual), msg: format!("If, else conditional must resolve to a boolean, found `{}`", actual),
help: None, help: None,
} }
@formatted @formatted
statement_indicator_calculation { statement_indicator_calculation {
args: (name: String), args: (name: impl Display),
msg: format!( msg: format!(
"Constraint system failed to evaluate branch selection indicator `{}`", "Constraint system failed to evaluate branch selection indicator `{}`",
name name
@ -412,7 +415,7 @@ create_errors!(
@formatted @formatted
statement_invalid_number_of_definitions { statement_invalid_number_of_definitions {
args: (expected: usize, actual: usize), args: (expected: impl Display, actual: impl Display),
msg: format!( msg: format!(
"Multiple definition statement expected {} return values, found {} values", "Multiple definition statement expected {} return values, found {} values",
expected, actual expected, actual
@ -422,7 +425,7 @@ create_errors!(
@formatted @formatted
statement_multiple_definition { statement_multiple_definition {
args: (value: String), args: (value: impl Display),
msg: format!("cannot assign multiple variables to a single value: {}", value), msg: format!("cannot assign multiple variables to a single value: {}", value),
help: None, help: None,
} }
@ -436,7 +439,7 @@ create_errors!(
@formatted @formatted
statement_no_returns { statement_no_returns {
args: (expected: String), args: (expected: impl Display),
msg: format!( msg: format!(
"function expected `{}` return type but no valid branches returned a result", "function expected `{}` return type but no valid branches returned a result",
expected expected
@ -446,7 +449,7 @@ create_errors!(
@formatted @formatted
statement_select_fail { statement_select_fail {
args: (first: String, second: String), args: (first: impl Display, second: impl Display),
msg: format!( msg: format!(
"Conditional select gadget failed to select between `{}` or `{}`", "Conditional select gadget failed to select between `{}` or `{}`",
first, second first, second
@ -463,7 +466,7 @@ create_errors!(
@formatted @formatted
statement_tuple_assign_index_bounds { statement_tuple_assign_index_bounds {
args: (index: usize, length: usize), args: (index: impl Display, length: impl Display),
msg: format!( msg: format!(
"Tuple assign index `{}` out of range for tuple of length `{}`", "Tuple assign index `{}` out of range for tuple of length `{}`",
index, length index, length
@ -480,14 +483,14 @@ create_errors!(
@formatted @formatted
statement_undefined_variable { statement_undefined_variable {
args: (name: String), args: (name: impl Display),
msg: format!("Attempted to assign to unknown variable `{}`", name), msg: format!("Attempted to assign to unknown variable `{}`", name),
help: None, help: None,
} }
@formatted @formatted
statement_undefined_circuit_variable { statement_undefined_circuit_variable {
args: (name: String), args: (name: impl Display),
msg: format!("Attempted to assign to unknown circuit member variable `{}`", name), msg: format!("Attempted to assign to unknown circuit member variable `{}`", name),
help: None, help: None,
} }
@ -501,14 +504,14 @@ create_errors!(
@formatted @formatted
address_value_account_error { address_value_account_error {
args: (error: ErrReport), args: (error: impl ErrorArg),
msg: format!("account creation failed due to `{}`", error), msg: format!("account creation failed due to `{}`", error),
help: None, help: None,
} }
@formatted @formatted
address_value_invalid_address { address_value_invalid_address {
args: (actual: String), args: (actual: impl Display),
msg: format!("expected address input type, found `{}`", actual), msg: format!("expected address input type, found `{}`", actual),
help: None, help: None,
} }
@ -522,7 +525,7 @@ create_errors!(
@formatted @formatted
boolean_value_cannot_enforce { boolean_value_cannot_enforce {
args: (operation: String, error: ErrReport), args: (operation: impl Display, error: impl ErrorArg),
msg: format!( msg: format!(
"the boolean operation `{}` failed due to the synthesis error `{}`", "the boolean operation `{}` failed due to the synthesis error `{}`",
operation, error, operation, error,
@ -532,42 +535,42 @@ create_errors!(
@formatted @formatted
boolean_value_cannot_evaluate { boolean_value_cannot_evaluate {
args: (operation: String), args: (operation: impl Display),
msg: format!("no implementation found for `{}`", operation), msg: format!("no implementation found for `{}`", operation),
help: None, help: None,
} }
@formatted @formatted
boolean_value_invalid_boolean { boolean_value_invalid_boolean {
args: (actual: String), args: (actual: impl Display),
msg: format!("expected boolean input type, found `{}`", actual), msg: format!("expected boolean input type, found `{}`", actual),
help: None, help: None,
} }
@formatted @formatted
boolean_value_missing_boolean { boolean_value_missing_boolean {
args: (expected: String), args: (expected: impl Display),
msg: format!("expected boolean input `{}` not found", expected), msg: format!("expected boolean input `{}` not found", expected),
help: None, help: None,
} }
@formatted @formatted
char_value_invalid_char { char_value_invalid_char {
args: (actual: String), args: (actual: impl Display),
msg: format!("expected char element input type, found `{}`", actual), msg: format!("expected char element input type, found `{}`", actual),
help: None, help: None,
} }
@formatted @formatted
field_value_negate_operation { field_value_negate_operation {
args: (error: ErrReport), args: (error: impl ErrorArg),
msg: format!("field negation failed due to synthesis error `{}`", error), msg: format!("field negation failed due to synthesis error `{}`", error),
help: None, help: None,
} }
@formatted @formatted
field_value_binary_operation { field_value_binary_operation {
args: (operation: String, error: ErrReport), args: (operation: impl Display, error: impl ErrorArg),
msg: format!( msg: format!(
"the field binary operation `{}` failed due to synthesis error `{}`", "the field binary operation `{}` failed due to synthesis error `{}`",
operation, error, operation, error,
@ -577,35 +580,35 @@ create_errors!(
@formatted @formatted
field_value_invalid_field { field_value_invalid_field {
args: (actual: String), args: (actual: impl Display),
msg: format!("expected field element input type, found `{}`", actual), msg: format!("expected field element input type, found `{}`", actual),
help: None, help: None,
} }
@formatted @formatted
field_value_missing_field { field_value_missing_field {
args: (expected: String), args: (expected: impl Display),
msg: format!("expected field input `{}` not found", expected), msg: format!("expected field input `{}` not found", expected),
help: None, help: None,
} }
@formatted @formatted
field_value_no_inverse { field_value_no_inverse {
args: (field: String), args: (field: impl Display),
msg: format!("no multiplicative inverse found for field `{}`", field), msg: format!("no multiplicative inverse found for field `{}`", field),
help: None, help: None,
} }
@formatted @formatted
group_value_negate_operation { group_value_negate_operation {
args: (error: ErrReport), args: (error: impl ErrorArg),
msg: format!("group negation failed due to the synthesis error `{}`", error), msg: format!("group negation failed due to the synthesis error `{}`", error),
help: None, help: None,
} }
@formatted @formatted
group_value_binary_operation { group_value_binary_operation {
args: (operation: String, error: ErrReport), args: (operation: impl Display, error: impl ErrorArg),
msg: format!( msg: format!(
"the group binary operation `{}` failed due to the synthesis error `{}`", "the group binary operation `{}` failed due to the synthesis error `{}`",
operation, error, operation, error,
@ -615,42 +618,42 @@ create_errors!(
@formatted @formatted
group_value_invalid_group { group_value_invalid_group {
args: (actual: String), args: (actual: impl Display),
msg: format!("expected group affine point input type, found `{}`", actual), msg: format!("expected group affine point input type, found `{}`", actual),
help: None, help: None,
} }
@formatted @formatted
group_value_missing_group { group_value_missing_group {
args: (expected: String), args: (expected: impl Display),
msg: format!("expected group input `{}` not found", expected), msg: format!("expected group input `{}` not found", expected),
help: None, help: None,
} }
@formatted @formatted
group_value_synthesis_error { group_value_synthesis_error {
args: (error: ErrReport), args: (error: impl ErrorArg),
msg: format!("compilation failed due to group synthesis error `{}`", error), msg: format!("compilation failed due to group synthesis error `{}`", error),
help: None, help: None,
} }
@formatted @formatted
group_value_x_invalid { group_value_x_invalid {
args: (x: String), args: (x: impl Display),
msg: format!("invalid x coordinate `{}`", x), msg: format!("invalid x coordinate `{}`", x),
help: None, help: None,
} }
@formatted @formatted
group_value_y_invalid { group_value_y_invalid {
args: (y: String), args: (y: impl Display),
msg: format!("invalid y coordinate `{}`", y), msg: format!("invalid y coordinate `{}`", y),
help: None, help: None,
} }
@formatted @formatted
group_value_not_on_curve { group_value_not_on_curve {
args: (element: String), args: (element: impl Display),
msg: format!("group element `{}` is not on the supported curve", element), msg: format!("group element `{}` is not on the supported curve", element),
help: None, help: None,
} }
@ -671,21 +674,21 @@ create_errors!(
@formatted @formatted
group_value_n_group { group_value_n_group {
args: (number: String), args: (number: impl Display),
msg: format!("cannot multiply group generator by \"{}\"", number), msg: format!("cannot multiply group generator by \"{}\"", number),
help: None, help: None,
} }
@formatted @formatted
integer_value_signed { integer_value_signed {
args: (error: ErrReport), args: (error: impl ErrorArg),
msg: format!("integer operation failed due to the signed integer error `{}`", error), msg: format!("integer operation failed due to the signed integer error `{}`", error),
help: None, help: None,
} }
@formatted @formatted
integer_value_unsigned { integer_value_unsigned {
args: (error: ErrReport), args: (error: impl ErrorArg),
msg: format!( msg: format!(
"integer operation failed due to the unsigned integer error `{}`", "integer operation failed due to the unsigned integer error `{}`",
error error
@ -695,7 +698,7 @@ create_errors!(
@formatted @formatted
integer_value_synthesis { integer_value_synthesis {
args: (error: ErrReport), args: (error: impl ErrorArg),
msg: format!("integer operation failed due to the synthesis error `{}`", error), msg: format!("integer operation failed due to the synthesis error `{}`", error),
help: None, help: None,
} }
@ -709,7 +712,7 @@ create_errors!(
@formatted @formatted
integer_value_binary_operation { integer_value_binary_operation {
args: (operation: String), args: (operation: impl Display),
msg: format!( msg: format!(
"the integer binary operation `{}` can only be enforced on integers of the same type", "the integer binary operation `{}` can only be enforced on integers of the same type",
operation operation
@ -719,28 +722,28 @@ create_errors!(
@formatted @formatted
integer_value_integer_type_mismatch { integer_value_integer_type_mismatch {
args: (expected: String, received: String), args: (expected: impl Display, received: impl Display),
msg: format!("expected data type `{}`, found `{}`", expected, received), msg: format!("expected data type `{}`, found `{}`", expected, received),
help: None, help: None,
} }
@formatted @formatted
integer_value_invalid_integer { integer_value_invalid_integer {
args: (actual: String), args: (actual: impl Display),
msg: format!("failed to parse `{}` as expected integer type", actual), msg: format!("failed to parse `{}` as expected integer type", actual),
help: None, help: None,
} }
@formatted @formatted
integer_value_missing_integer { integer_value_missing_integer {
args: (expected: String), args: (expected: impl Display),
msg: format!("expected integer input `{}` not found", expected), msg: format!("expected integer input `{}` not found", expected),
help: None, help: None,
} }
@formatted @formatted
integer_value_cannot_evaluate { integer_value_cannot_evaluate {
args: (operation: String), args: (operation: impl Display),
msg: format!("no implementation found for `{}`", operation), msg: format!("no implementation found for `{}`", operation),
help: None, help: None,
} }

View File

@ -16,6 +16,11 @@
use crate::create_errors; use crate::create_errors;
use std::{
error::Error as ErrorArg,
fmt::{Debug, Display},
};
create_errors!( create_errors!(
ImportError, ImportError,
exit_code_mask: 3000u32, exit_code_mask: 3000u32,
@ -24,14 +29,14 @@ create_errors!(
// An imported package has the same name as an imported core_package. // An imported package has the same name as an imported core_package.
@formatted @formatted
conflicting_imports { conflicting_imports {
args: (name: &str), args: (name: impl Display),
msg: format!("conflicting imports found for `{}`.", name), msg: format!("conflicting imports found for `{}`.", name),
help: None, help: None,
} }
@formatted @formatted
recursive_imports { recursive_imports {
args: (package: &str), args: (package: impl Display),
msg: format!("recursive imports for `{}`.", package), msg: format!("recursive imports for `{}`.", package),
help: None, help: None,
} }
@ -47,7 +52,7 @@ create_errors!(
// Failed to find the directory of the current file. // Failed to find the directory of the current file.
@formatted @formatted
current_directory_error { current_directory_error {
args: (error: std::io::Error), args: (error: impl ErrorArg),
msg: format!("Compilation failed trying to find current directory - {:?}.", error), msg: format!("Compilation failed trying to find current directory - {:?}.", error),
help: None, help: None,
} }
@ -55,10 +60,10 @@ create_errors!(
// Failed to open or get the name of a directory. // Failed to open or get the name of a directory.
@formatted @formatted
directory_error { directory_error {
args: (error: std::io::Error, path: &std::path::Path), args: (error: impl ErrorArg, path:impl Debug),
msg: format!( msg: format!(
"Compilation failed due to directory error @ '{}' - {:?}.", "Compilation failed due to directory error @ '{:?}' - {:?}.",
path.to_str().unwrap_or_default(), path,
error error
), ),
help: None, help: None,
@ -67,15 +72,15 @@ create_errors!(
// Failed to find a main file for the current package. // Failed to find a main file for the current package.
@formatted @formatted
expected_main_file { expected_main_file {
args: (entry: String), args: (entry: impl Debug),
msg: format!("Expected main file at `{}`.", entry), msg: format!("Expected main file at `{:?}`.", entry),
help: None, help: None,
} }
// Failed to import a package name. // Failed to import a package name.
@formatted @formatted
unknown_package { unknown_package {
args: (name: &str), args: (name: impl Display),
msg: format!( msg: format!(
"Cannot find imported package `{}` in source files or import directory.", "Cannot find imported package `{}` in source files or import directory.",
name name
@ -85,7 +90,7 @@ create_errors!(
@formatted @formatted
io_error { io_error {
args: (path: &str, error: std::io::Error), args: (path: impl Display, error: impl ErrorArg),
msg: format!("cannot read imported file '{}': {:?}", path, error), msg: format!("cannot read imported file '{}': {:?}", path, error),
help: None, help: None,
} }

View File

@ -47,8 +47,6 @@ extern crate thiserror;
use leo_input::InputParserError; use leo_input::InputParserError;
use eyre::ErrReport;
#[derive(Debug, Error)] #[derive(Debug, Error)]
pub enum LeoError { pub enum LeoError {
#[error(transparent)] #[error(transparent)]
@ -73,10 +71,28 @@ pub enum LeoError {
ParserError(#[from] ParserError), ParserError(#[from] ParserError),
#[error(transparent)] #[error(transparent)]
RustError(#[from] ErrReport), SnarkVMError(#[from] SnarkVMError),
#[error(transparent)] #[error(transparent)]
SnarkVMError(#[from] SnarkVMError), StateError(#[from] StateError),
}
impl LeoError {
pub fn exit_code(&self) -> u32 {
use LeoError::*;
match self {
AsgError(error) => error.exit_code(),
AstError(error) => error.exit_code(),
CompilerError(error) => error.exit_code(),
ImportError(error) => error.exit_code(),
InputError(_error) => 0, // TODO migrate me.
PackageError(error) => error.exit_code(),
ParserError(error) => error.exit_code(),
SnarkVMError(_error) => 0, // TODO update once snarkvm implments a global top level error similar to LeoError.
StateError(error) => error.exit_code(),
}
}
} }
// #[test] // #[test]

View File

@ -15,9 +15,11 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>. // along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::create_errors; use crate::create_errors;
use std::{ffi::OsString, path::PathBuf};
use eyre::ErrReport; use std::{
error::Error as ErrorArg,
fmt::{Debug, Display},
};
create_errors!( create_errors!(
PackageError, PackageError,
@ -26,399 +28,399 @@ create_errors!(
@backtraced @backtraced
failed_to_create_imports_directory { failed_to_create_imports_directory {
args: (error: ErrReport), args: (error: impl ErrorArg),
msg: format!("failed creating imports directory {}", error), msg: format!("failed creating imports directory {}", error),
help: None, help: None,
} }
@backtraced @backtraced
import_does_not_exist { import_does_not_exist {
args: (package: String), args: (package: impl Display),
msg: format!("package {} does not exist as an import", package), msg: format!("package {} does not exist as an import", package),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_remove_imports_directory { failed_to_remove_imports_directory {
args: (error: ErrReport), args: (error: impl ErrorArg),
msg: format!("failed removing imports directory {}", error), msg: format!("failed removing imports directory {}", error),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_create_inputs_directory { failed_to_create_inputs_directory {
args: (error: ErrReport), args: (error: impl ErrorArg),
msg: format!("failed creating inputs directory {}", error), msg: format!("failed creating inputs directory {}", error),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_get_input_file_entry { failed_to_get_input_file_entry {
args: (error: ErrReport), args: (error: impl ErrorArg),
msg: format!("failed to get input file entry: {}", error), msg: format!("failed to get input file entry: {}", error),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_get_input_file_name { failed_to_get_input_file_name {
args: (file: OsString), args: (file: impl Debug),
msg: format!("failed to get input file name: {:?}", file), msg: format!("failed to get input file name: {:?}", file),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_get_input_file_type { failed_to_get_input_file_type {
args: (file: OsString, error: ErrReport), args: (file: impl Debug, error: impl ErrorArg),
msg: format!("failed to get input file `{:?}` type: {}", file, error), msg: format!("failed to get input file `{:?}` type: {}", file, error),
help: None, help: None,
} }
@backtraced @backtraced
invalid_input_file_type { invalid_input_file_type {
args: (file: OsString, type_: std::fs::FileType), args: (file: impl Debug, type_: std::fs::FileType),
msg: format!("input file `{:?}` has invalid type: {:?}", file, type_), msg: format!("input file `{:?}` has invalid type: {:?}", file, type_),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_read_inputs_directory { failed_to_read_inputs_directory {
args: (error: ErrReport), args: (error: impl ErrorArg),
msg: format!("failed reading inputs directory {}", error), msg: format!("failed reading inputs directory {}", error),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_read_input_file { failed_to_read_input_file {
args: (path: PathBuf), args: (path: impl Debug),
msg: format!("Cannot read input file from the provided file path - {:?}", path), msg: format!("Cannot read input file from the provided file path - {:?}", path),
help: None, help: None,
} }
@backtraced @backtraced
io_error_input_file { io_error_input_file {
args: (error: ErrReport), args: (error: impl ErrorArg),
msg: format!("IO error input file from the provided file path - {}", error), msg: format!("IO error input file from the provided file path - {}", error),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_read_state_file { failed_to_read_state_file {
args: (path: PathBuf), args: (path: impl Debug),
msg: format!("Cannot read state file from the provided file path - {:?}", path), msg: format!("Cannot read state file from the provided file path - {:?}", path),
help: None, help: None,
} }
@backtraced @backtraced
io_error_state_file { io_error_state_file {
args: (error: ErrReport), args: (error: impl ErrorArg),
msg: format!("IO error state file from the provided file path - {}", error), msg: format!("IO error state file from the provided file path - {}", error),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_read_checksum_file { failed_to_read_checksum_file {
args: (path: PathBuf), args: (path: impl Debug),
msg: format!("Cannot read checksum file from the provided file path - {:?}", path), msg: format!("Cannot read checksum file from the provided file path - {:?}", path),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_remove_checksum_file { failed_to_remove_checksum_file {
args: (path: PathBuf), args: (path: impl Debug),
msg: format!("Cannot remove checksum file from the provided file path - {:?}", path), msg: format!("Cannot remove checksum file from the provided file path - {:?}", path),
help: None, help: None,
} }
@backtraced @backtraced
io_error_checksum_file { io_error_checksum_file {
args: (error: ErrReport), args: (error: impl ErrorArg),
msg: format!("IO cannot read checksum file from the provided file path - {}", error), msg: format!("IO cannot read checksum file from the provided file path - {}", error),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_read_circuit_file { failed_to_read_circuit_file {
args: (path: PathBuf), args: (path: impl Debug),
msg: format!("Cannot read circuit file from the provided file path - {:?}", path), msg: format!("Cannot read circuit file from the provided file path - {:?}", path),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_remove_circuit_file { failed_to_remove_circuit_file {
args: (path: PathBuf), args: (path: impl Debug),
msg: format!("Cannot remove circuit file from the provided file path - {:?}", path), msg: format!("Cannot remove circuit file from the provided file path - {:?}", path),
help: None, help: None,
} }
@backtraced @backtraced
io_error_circuit_file { io_error_circuit_file {
args: (error: ErrReport), args: (error: impl ErrorArg),
msg: format!("IO error circuit file from the provided file path - {}", error), msg: format!("IO error circuit file from the provided file path - {}", error),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_create_outputs_directory { failed_to_create_outputs_directory {
args: (error: ErrReport), args: (error: impl ErrorArg),
msg: format!("failed creating outputs directory {}", error), msg: format!("failed creating outputs directory {}", error),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_remove_outputs_directory { failed_to_remove_outputs_directory {
args: (error: ErrReport), args: (error: impl ErrorArg),
msg: format!("failed removing outputs directory {}", error), msg: format!("failed removing outputs directory {}", error),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_read_proof_file { failed_to_read_proof_file {
args: (path: PathBuf), args: (path: impl Debug),
msg: format!("Cannot read proof file from the provided file path - {:?}", path), msg: format!("Cannot read proof file from the provided file path - {:?}", path),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_remove_proof_file { failed_to_remove_proof_file {
args: (path: PathBuf), args: (path: impl Debug),
msg: format!("Cannot remove proof file from the provided file path - {:?}", path), msg: format!("Cannot remove proof file from the provided file path - {:?}", path),
help: None, help: None,
} }
@backtraced @backtraced
io_error_proof_file { io_error_proof_file {
args: (error: ErrReport), args: (error: impl ErrorArg),
msg: format!("IO error proof file from the provided file path - {}", error), msg: format!("IO error proof file from the provided file path - {}", error),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_read_proving_key_file { failed_to_read_proving_key_file {
args: (path: PathBuf), args: (path: impl Debug),
msg: format!("Cannot read prooving key file from the provided file path - {:?}", path), msg: format!("Cannot read prooving key file from the provided file path - {:?}", path),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_remove_proving_key_file { failed_to_remove_proving_key_file {
args: (path: PathBuf), args: (path: impl Debug),
msg: format!("Cannot remove prooving key file from the provided file path - {:?}", path), msg: format!("Cannot remove prooving key file from the provided file path - {:?}", path),
help: None, help: None,
} }
@backtraced @backtraced
io_error_proving_key_file { io_error_proving_key_file {
args: (error: ErrReport), args: (error: impl ErrorArg),
msg: format!("IO error prooving key file from the provided file path - {}", error), msg: format!("IO error prooving key file from the provided file path - {}", error),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_read_verification_key_file { failed_to_read_verification_key_file {
args: (path: PathBuf), args: (path: impl Debug),
msg: format!("Cannot read verification key file from the provided file path - {:?}", path), msg: format!("Cannot read verification key file from the provided file path - {:?}", path),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_remove_verification_key_file { failed_to_remove_verification_key_file {
args: (path: PathBuf), args: (path: impl Debug),
msg: format!("Cannot remove verification key file from the provided file path - {:?}", path), msg: format!("Cannot remove verification key file from the provided file path - {:?}", path),
help: None, help: None,
} }
@backtraced @backtraced
io_error_verification_key_file { io_error_verification_key_file {
args: (error: ErrReport), args: (error: impl ErrorArg),
msg: format!("IO error verification key file from the provided file path - {}", error), msg: format!("IO error verification key file from the provided file path - {}", error),
help: None, help: None,
} }
@backtraced @backtraced
io_error_gitignore_file { io_error_gitignore_file {
args: (error: ErrReport), args: (error: impl ErrorArg),
msg: format!("IO error gitignore file from the provided file path - {}", error), msg: format!("IO error gitignore file from the provided file path - {}", error),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_create_manifest_file { failed_to_create_manifest_file {
args: (filename: &str, error: ErrReport), args: (filename: impl Display, error: impl ErrorArg),
msg: format!("failed creating manifest file `{}` {}", filename, error), msg: format!("failed creating manifest file `{}` {}", filename, error),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_get_manifest_metadata_file { failed_to_get_manifest_metadata_file {
args: (filename: &str, error: ErrReport), args: (filename: impl Display, error: impl ErrorArg),
msg: format!("failed getting manifest file metadata `{}` {}", filename, error), msg: format!("failed getting manifest file metadata `{}` {}", filename, error),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_open_manifest_file { failed_to_open_manifest_file {
args: (filename: &str, error: ErrReport), args: (filename: impl Display, error: impl ErrorArg),
msg: format!("failed openining manifest file `{}` {}", filename, error), msg: format!("failed openining manifest file `{}` {}", filename, error),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_parse_manifest_file { failed_to_parse_manifest_file {
args: (filename: &str, error: ErrReport), args: (filename: impl Display, error: impl ErrorArg),
msg: format!("failed parsing manifest file `{}` {}", filename, error), msg: format!("failed parsing manifest file `{}` {}", filename, error),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_read_manifest_file { failed_to_read_manifest_file {
args: (filename: &str, error: ErrReport), args: (filename: impl Display, error: impl ErrorArg),
msg: format!("failed reading manifest file `{}` {}", filename, error), msg: format!("failed reading manifest file `{}` {}", filename, error),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_write_manifest_file { failed_to_write_manifest_file {
args: (filename: &str, error: ErrReport), args: (filename: impl Display, error: impl ErrorArg),
msg: format!("failed writing manifest file `{}` {}", filename, error), msg: format!("failed writing manifest file `{}` {}", filename, error),
help: None, help: None,
} }
@backtraced @backtraced
io_error_manifest_file { io_error_manifest_file {
args: (error: ErrReport), args: (error: impl ErrorArg),
msg: format!("IO error manifest file from the provided file path - {}", error), msg: format!("IO error manifest file from the provided file path - {}", error),
help: None, help: None,
} }
@backtraced @backtraced
io_error_readme_file { io_error_readme_file {
args: (error: ErrReport), args: (error: impl ErrorArg),
msg: format!("IO error readme file from the provided file path - {}", error), msg: format!("IO error readme file from the provided file path - {}", error),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_create_zip_file { failed_to_create_zip_file {
args: (error: ErrReport), args: (error: impl ErrorArg),
msg: format!("failed creating zip file {}", error), msg: format!("failed creating zip file {}", error),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_open_zip_file { failed_to_open_zip_file {
args: (error: ErrReport), args: (error: impl ErrorArg),
msg: format!("failed opening zip file {}", error), msg: format!("failed opening zip file {}", error),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_read_zip_file { failed_to_read_zip_file {
args: (error: ErrReport), args: (error: impl ErrorArg),
msg: format!("failed reading zip file {}", error), msg: format!("failed reading zip file {}", error),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_write_zip_file { failed_to_write_zip_file {
args: (error: ErrReport), args: (error: impl ErrorArg),
msg: format!("failed writing zip file {}", error), msg: format!("failed writing zip file {}", error),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_remove_zip_file { failed_to_remove_zip_file {
args: (path: PathBuf), args: (path: impl Debug),
msg: format!("failed removing zip file from the provided file path - {:?}", path), msg: format!("failed removing zip file from the provided file path - {:?}", path),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_zip { failed_to_zip {
args: (error: ErrReport), args: (error: impl ErrorArg),
msg: error, msg: error,
help: None, help: None,
} }
@backtraced @backtraced
io_error_zip_file { io_error_zip_file {
args: (error: ErrReport), args: (error: impl ErrorArg),
msg: format!("IO error zip file from the provided file path - {}", error), msg: format!("IO error zip file from the provided file path - {}", error),
help: None, help: None,
} }
@backtraced @backtraced
io_error_library_file { io_error_library_file {
args: (error: ErrReport), args: (error: impl ErrorArg),
msg: format!("IO error library file from the provided file path - {}", error), msg: format!("IO error library file from the provided file path - {}", error),
help: None, help: None,
} }
@backtraced @backtraced
io_error_main_file { io_error_main_file {
args: (error: ErrReport), args: (error: impl ErrorArg),
msg: format!("IO error main file from the provided file path - {}", error), msg: format!("IO error main file from the provided file path - {}", error),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_create_source_directory { failed_to_create_source_directory {
args: (error: ErrReport), args: (error: impl ErrorArg),
msg: format!("failed creating source directory {}", error), msg: format!("failed creating source directory {}", error),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_get_source_file_entry { failed_to_get_source_file_entry {
args: (error: ErrReport), args: (error: impl ErrorArg),
msg: format!("failed to get input file entry: {}", error), msg: format!("failed to get input file entry: {}", error),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_get_source_file_extension { failed_to_get_source_file_extension {
args: (extension: OsString), args: (extension: impl Debug),
msg: format!("failed to get source file extension: {:?}", extension), msg: format!("failed to get source file extension: {:?}", extension),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_get_source_file_type { failed_to_get_source_file_type {
args: (file: OsString, error: ErrReport), args: (file: impl Debug, error: impl ErrorArg),
msg: format!("failed to get source file `{:?}` type: {}", file, error), msg: format!("failed to get source file `{:?}` type: {}", file, error),
help: None, help: None,
} }
@backtraced @backtraced
invalid_source_file_extension { invalid_source_file_extension {
args: (file: OsString, extension: OsString), args: (file: impl Debug, extension: impl Debug),
msg: format!("source file `{:?}` has invalid extension: {:?}", file, extension), msg: format!("source file `{:?}` has invalid extension: {:?}", file, extension),
help: None, help: None,
} }
@backtraced @backtraced
invalid_source_file_type { invalid_source_file_type {
args: (file: OsString, type_: std::fs::FileType), args: (file: impl Debug, type_: std::fs::FileType),
msg: format!("source file `{:?}` has invalid type: {:?}", file, type_), msg: format!("source file `{:?}` has invalid type: {:?}", file, type_),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_read_source_directory { failed_to_read_source_directory {
args: (error: ErrReport), args: (error: impl ErrorArg),
msg: format!("failed reading source directory {}", error), msg: format!("failed reading source directory {}", error),
help: None, help: None,
} }
@backtraced @backtraced
failed_to_initialize_package { failed_to_initialize_package {
args: (package: String, path: OsString), args: (package: impl Display, path: impl Debug),
msg: format!("failed to initialize package {} {:?}", package, path), msg: format!("failed to initialize package {} {:?}", package, path),
help: None, help: None,
} }
@backtraced @backtraced
invalid_package_name { invalid_package_name {
args: (package: String), args: (package: impl Display),
msg: format!("invalid project name {}", package), msg: format!("invalid project name {}", package),
help: None, help: None,
} }

View File

@ -16,6 +16,8 @@
use crate::create_errors; use crate::create_errors;
use std::fmt::Display;
create_errors!( create_errors!(
ParserError, ParserError,
exit_code_mask: 5000u32, exit_code_mask: 5000u32,
@ -23,14 +25,14 @@ create_errors!(
@formatted @formatted
unexpected_token { unexpected_token {
args: (message: String, help: String), args: (message: impl Display, help: String),
msg: message, msg: message,
help: Some(help), help: Some(help),
} }
@formatted @formatted
invalid_address_lit { invalid_address_lit {
args: (token: &str), args: (token: impl Display),
msg: format!("invalid address literal: '{}'", token), msg: format!("invalid address literal: '{}'", token),
help: None, help: None,
} }
@ -51,14 +53,14 @@ create_errors!(
@formatted @formatted
unexpected_whitespace { unexpected_whitespace {
args: (left: &str, right: &str), args: (left: impl Display, right: impl Display),
msg: format!("Unexpected white space between terms {} and {}", left, right), msg: format!("Unexpected white space between terms {} and {}", left, right),
help: None, help: None,
} }
@formatted @formatted
unexpected { unexpected {
args: (got: String, expected: String), args: (got: impl Display, expected: impl Display),
msg: format!("expected {} -- got '{}'", expected, got), msg: format!("expected {} -- got '{}'", expected, got),
help: None, help: None,
} }
@ -72,7 +74,7 @@ create_errors!(
@formatted @formatted
unexpected_ident { unexpected_ident {
args: (got: &str, expected: &[&str]), args: (got: impl Display, expected: &[impl Display]),
msg: format!( msg: format!(
"unexpected identifier: expected {} -- got '{}'", "unexpected identifier: expected {} -- got '{}'",
expected expected
@ -87,14 +89,14 @@ create_errors!(
@formatted @formatted
unexpected_statement { unexpected_statement {
args: (got: String, expected: &str), args: (got: impl Display, expected: impl Display),
msg: format!("unexpected statement: expected '{}', got '{}'", expected, got), msg: format!("unexpected statement: expected '{}', got '{}'", expected, got),
help: None, help: None,
} }
@formatted @formatted
unexpected_str { unexpected_str {
args: (got: String, expected: &str), args: (got: impl Display, expected: impl Display),
msg: format!("unexpected string: expected '{}', got '{}'", expected, got), msg: format!("unexpected string: expected '{}', got '{}'", expected, got),
help: None, help: None,
} }

View File

@ -50,7 +50,7 @@ impl<'a> ImportResolver<'a> for ImportParser<'a> {
) -> Result<Option<Program<'a>>, LeoError> { ) -> Result<Option<Program<'a>>, LeoError> {
let full_path = package_segments.join("."); let full_path = package_segments.join(".");
if self.partial_imports.contains(&full_path) { if self.partial_imports.contains(&full_path) {
return Err(LeoError::from(ImportError::recursive_imports(&full_path, span))); return Err(ImportError::recursive_imports(full_path, span).into());
} }
if let Some(program) = self.imports.get(&full_path) { if let Some(program) = self.imports.get(&full_path) {
return Ok(Some(program.clone())); return Ok(Some(program.clone()));

Some files were not shown because too many files have changed in this diff Show More