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

View File

@ -50,6 +50,10 @@ version = "1.5.3"
path = "./compiler"
version = "1.5.3"
[dependencies.leo-errors]
path = "./errors"
version = "1.5.3"
[dependencies.leo-imports]
path = "./imports"
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> {
Ok(match int_type {
IntegerType::I8 => ConstInt::I8(
value
.parse()
.map_err(|_| LeoError::from(AsgError::invalid_int(value, span)))?,
),
IntegerType::I16 => ConstInt::I16(
value
.parse()
.map_err(|_| LeoError::from(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)))?,
),
IntegerType::I8 => ConstInt::I8(value.parse().map_err(|_| AsgError::invalid_int(value, span))?),
IntegerType::I16 => ConstInt::I16(value.parse().map_err(|_| AsgError::invalid_int(value, span))?),
IntegerType::I32 => ConstInt::I32(value.parse().map_err(|_| 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::U8 => ConstInt::U8(value.parse().map_err(|_| AsgError::invalid_int(value, span))?),
IntegerType::U16 => ConstInt::U16(value.parse().map_err(|_| AsgError::invalid_int(value, span))?),
IntegerType::U32 => ConstInt::U32(value.parse().map_err(|_| 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))?),
})
}
}

View File

@ -93,11 +93,11 @@ impl<'a> FromAst<'a, leo_ast::ArrayAccessExpression> for ArrayAccessExpression<'
let array_len = match array.get_type() {
Some(Type::Array(_, len)) => len,
type_ => {
return Err(LeoError::from(AsgError::unexpected_type(
return Err(AsgError::unexpected_type(
"array",
type_.map(|x| x.to_string()).as_deref(),
type_.map(|x| x.to_string()).unwrap_or("unknown".to_string()),
&value.span,
)));
))?;
}
};
@ -113,10 +113,10 @@ impl<'a> FromAst<'a, leo_ast::ArrayAccessExpression> for ArrayAccessExpression<'
.flatten()
{
if index >= array_len {
return Err(LeoError::from(AsgError::array_index_out_of_bounds(
return Err(AsgError::array_index_out_of_bounds(
index,
&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),
None => (None, None),
Some(type_) => {
return Err(LeoError::from(AsgError::unexpected_type(
&type_.to_string(),
Some("array"),
&value.span,
)));
return Err(AsgError::unexpected_type(type_, "array", &value.span))?;
}
};
let dimensions = value
@ -86,22 +82,22 @@ impl<'a> FromAst<'a, leo_ast::ArrayInitExpression> for ArrayInitExpression<'a> {
.0
.iter()
.map(|x| {
x.value
Ok(x.value
.parse::<usize>()
.map_err(|_| LeoError::from(AsgError::parse_dimension_error(&value.span)))
.map_err(|_| AsgError::parse_dimension_error(&value.span))?)
})
.collect::<Result<Vec<_>, LeoError>>()?;
let len = *dimensions
.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 expected_len != len {
return Err(LeoError::from(AsgError::unexpected_type(
&*format!("array of length {}", expected_len),
Some(&*format!("array of length {}", len)),
return Err(AsgError::unexpected_type(
format!("array of length {}", expected_len),
format!("array of length {}", len),
&value.span,
)));
))?;
}
}
@ -110,11 +106,11 @@ impl<'a> FromAst<'a, leo_ast::ArrayInitExpression> for ArrayInitExpression<'a> {
Some(PartialType::Array(item, len)) => {
if let Some(len) = len {
if len != dimension {
return Err(LeoError::from(AsgError::unexpected_type(
&*format!("array of length {}", dimension),
Some(&*format!("array of length {}", len)),
return Err(AsgError::unexpected_type(
format!("array of length {}", dimension),
format!("array of length {}", len),
&value.span,
)));
))?;
}
}
@ -122,11 +118,7 @@ impl<'a> FromAst<'a, leo_ast::ArrayInitExpression> for ArrayInitExpression<'a> {
}
None => None,
Some(type_) => {
return Err(LeoError::from(AsgError::unexpected_type(
"array",
Some(&type_.to_string()),
&value.span,
)));
return Err(AsgError::unexpected_type("array", type_, &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),
None => (None, None),
Some(type_) => {
return Err(LeoError::from(AsgError::unexpected_type(
&type_.to_string(),
Some("array"),
&value.span,
)));
return Err(AsgError::unexpected_type(type_, "array", &value.span))?;
}
};
@ -170,15 +166,15 @@ impl<'a> FromAst<'a, leo_ast::ArrayInlineExpression> for ArrayInlineExpression<'
len += spread_len;
}
type_ => {
return Err(LeoError::from(AsgError::unexpected_type(
return Err(AsgError::unexpected_type(
expected_item
.as_ref()
.map(|x| x.to_string())
.as_deref()
.unwrap_or("unknown"),
type_.map(|x| x.to_string()).as_deref(),
type_.map(|x| x.to_string()).unwrap_or("unknown".to_string()),
&value.span,
)));
))?;
}
}
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 len != expected_len {
return Err(LeoError::from(AsgError::unexpected_type(
&*format!("array of length {}", expected_len),
Some(&*format!("array of length {}", len)),
return Err(AsgError::unexpected_type(
format!("array of length {}", expected_len),
format!("array of length {}", len),
&value.span,
)));
))?;
}
}
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),
None => (None, None),
Some(x) => {
return Err(LeoError::from(AsgError::unexpected_type(
&x.to_string(),
Some("array"),
&value.span,
)));
return Err(AsgError::unexpected_type(x, "array", &value.span))?;
}
};
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 {
Some(Type::Array(inner, size)) => (inner, size),
type_ => {
return Err(LeoError::from(AsgError::unexpected_type(
return Err(AsgError::unexpected_type(
"array",
type_.map(|x| x.to_string()).as_deref(),
type_.map(|x| x.to_string()).unwrap_or("unknown".to_string()),
&value.span,
)));
))?;
}
};
@ -158,10 +154,7 @@ impl<'a> FromAst<'a, leo_ast::ArrayRangeAccessExpression> for ArrayRangeAccessEx
} else {
value.span.clone()
};
return Err(LeoError::from(AsgError::array_index_out_of_bounds(
inner_value,
&error_span,
)));
return Err(AsgError::array_index_out_of_bounds(inner_value, &error_span))?;
} else if let Some(left) = const_left {
if left > inner_value {
let error_span = if let Some(right) = right {
@ -169,10 +162,7 @@ impl<'a> FromAst<'a, leo_ast::ArrayRangeAccessExpression> for ArrayRangeAccessEx
} else {
value.span.clone()
};
return Err(LeoError::from(AsgError::array_index_out_of_bounds(
inner_value,
&error_span,
)));
return Err(AsgError::array_index_out_of_bounds(inner_value, &error_span))?;
}
}
}
@ -192,11 +182,11 @@ impl<'a> FromAst<'a, leo_ast::ArrayRangeAccessExpression> for ArrayRangeAccessEx
if let Some(length) = length {
if length != expected_len {
let concrete_type = Type::Array(parent_element, length);
return Err(LeoError::from(AsgError::unexpected_type(
&expected_type.as_ref().unwrap().to_string(),
Some(&concrete_type.to_string()),
return Err(AsgError::unexpected_type(
expected_type.as_ref().unwrap(),
concrete_type,
&value.span,
)));
))?;
}
}
if let Some(left_value) = const_left {
@ -206,16 +196,13 @@ impl<'a> FromAst<'a, leo_ast::ArrayRangeAccessExpression> for ArrayRangeAccessEx
} else {
value.span.clone()
};
return Err(LeoError::from(AsgError::array_index_out_of_bounds(
left_value,
&error_span,
)));
return Err(AsgError::array_index_out_of_bounds(left_value, &error_span))?;
}
}
length = Some(expected_len);
}
if length.is_none() {
return Err(LeoError::from(AsgError::unknown_array_size(&value.span)));
return Err(AsgError::unknown_array_size(&value.span))?;
}
Ok(ArrayRangeAccessExpression {

View File

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

View File

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

View File

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

View File

@ -96,16 +96,16 @@ impl<'a> FromAst<'a, leo_ast::CircuitInitExpression> for CircuitInitExpression<'
) -> Result<CircuitInitExpression<'a>, LeoError> {
let circuit = scope
.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 {
Some(PartialType::Type(Type::Circuit(expected_circuit))) if expected_circuit == circuit => (),
None => (),
Some(x) => {
return Err(LeoError::from(AsgError::unexpected_type(
&x.to_string(),
Some(&circuit.name.borrow().name),
return Err(AsgError::unexpected_type(
x,
circuit.name.borrow().name.to_string(),
&value.span,
)));
))?;
}
}
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();
for (name, member) in circuit_members.iter() {
if defined_variables.contains(name) {
return Err(LeoError::from(AsgError::overridden_circuit_member(
return Err(AsgError::overridden_circuit_member(
&circuit.name.borrow().name,
name,
&value.span,
)));
))?;
}
defined_variables.insert(name.clone());
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)));
} else {
return Err(LeoError::from(AsgError::missing_circuit_member(
return Err(AsgError::missing_circuit_member(
&circuit.name.borrow().name,
name,
&value.span,
)));
))?;
}
}
for (name, (identifier, _expression)) in members.iter() {
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,
*name,
name,
&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() {
Some(Type::Address) | None => (),
Some(x) => {
return Err(LeoError::from(AsgError::unexpected_type(
&x.to_string(),
Some(&*Type::Address.to_string()),
span,
)));
return Err(AsgError::unexpected_type(x, Type::Address, span))?;
}
}
Constant {
@ -102,11 +98,7 @@ impl<'a> FromAst<'a, leo_ast::ValueExpression> for Constant<'a> {
match expected_type.map(PartialType::full).flatten() {
Some(Type::Boolean) | None => (),
Some(x) => {
return Err(LeoError::from(AsgError::unexpected_type(
&x.to_string(),
Some(&*Type::Boolean.to_string()),
span,
)));
return Err(AsgError::unexpected_type(x, Type::Boolean, span))?;
}
}
Constant {
@ -115,7 +107,7 @@ impl<'a> FromAst<'a, leo_ast::ValueExpression> for Constant<'a> {
value: ConstValue::Boolean(
value
.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() {
Some(Type::Char) | None => (),
Some(x) => {
return Err(LeoError::from(AsgError::unexpected_type(
&x.to_string(),
Some(&*Type::Char.to_string()),
value.span(),
)));
return Err(AsgError::unexpected_type(x, Type::Char, value.span()))?;
}
}
@ -141,32 +129,20 @@ impl<'a> FromAst<'a, leo_ast::ValueExpression> for Constant<'a> {
match expected_type.map(PartialType::full).flatten() {
Some(Type::Field) | None => (),
Some(x) => {
return Err(LeoError::from(AsgError::unexpected_type(
&x.to_string(),
Some(&*Type::Field.to_string()),
span,
)));
return Err(AsgError::unexpected_type(x, Type::Field, span))?;
}
}
Constant {
parent: Cell::new(None),
span: Some(span.clone()),
value: ConstValue::Field(
value
.parse()
.map_err(|_| LeoError::from(AsgError::invalid_int(value, span)))?,
),
value: ConstValue::Field(value.parse().map_err(|_| AsgError::invalid_int(value, span))?),
}
}
Group(value) => {
match expected_type.map(PartialType::full).flatten() {
Some(Type::Group) | None => (),
Some(x) => {
return Err(LeoError::from(AsgError::unexpected_type(
&x.to_string(),
Some(&*Type::Group.to_string()),
value.span(),
)));
return Err(AsgError::unexpected_type(x, Type::Group, value.span()))?;
}
}
Constant {
@ -183,7 +159,7 @@ impl<'a> FromAst<'a, leo_ast::ValueExpression> for Constant<'a> {
}
}
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))) => {
Constant {
parent: Cell::new(None),
@ -194,11 +170,7 @@ impl<'a> FromAst<'a, leo_ast::ValueExpression> for Constant<'a> {
Some(PartialType::Type(Type::Field)) => Constant {
parent: Cell::new(None),
span: Some(span.clone()),
value: ConstValue::Field(
value
.parse()
.map_err(|_| LeoError::from(AsgError::invalid_int(value, span)))?,
),
value: ConstValue::Field(value.parse().map_err(|_| AsgError::invalid_int(value, span))?),
},
Some(PartialType::Type(Type::Group)) => Constant {
parent: Cell::new(None),
@ -211,11 +183,7 @@ impl<'a> FromAst<'a, leo_ast::ValueExpression> for Constant<'a> {
value: ConstValue::Address(value.clone()),
},
Some(x) => {
return Err(LeoError::from(AsgError::unexpected_type(
&x.to_string(),
Some("unknown"),
span,
)));
return Err(AsgError::unexpected_type(x, "unknown", 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(_))) => (),
None => (),
Some(x) => {
return Err(LeoError::from(AsgError::unexpected_type(
&x.to_string(),
Some(&*int_type.to_string()),
span,
)));
return Err(AsgError::unexpected_type(x, int_type, span))?;
}
}
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();
if left != right {
return Err(LeoError::from(AsgError::ternary_different_types(
&left.to_string(),
&right.to_string(),
&value.span,
)));
return Err(AsgError::ternary_different_types(left, right, &value.span))?;
}
Ok(TernaryExpression {

View File

@ -80,7 +80,7 @@ impl<'a> FromAst<'a, leo_ast::TupleAccessExpression> for TupleAccessExpression<'
.index
.value
.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];
expected_tuple[index] = expected_type;
@ -89,11 +89,11 @@ impl<'a> FromAst<'a, leo_ast::TupleAccessExpression> for TupleAccessExpression<'
let tuple_type = tuple.get_type();
if let Some(Type::Tuple(_items)) = tuple_type {
} else {
return Err(LeoError::from(AsgError::unexpected_type(
return Err(AsgError::unexpected_type(
"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,
)));
))?;
}
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),
None => None,
x => {
return Err(LeoError::from(AsgError::unexpected_type(
return Err(AsgError::unexpected_type(
"tuple",
x.map(|x| x.to_string()).as_deref(),
x.map(|x| x.to_string()).unwrap_or("unknown".to_string()),
&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.
// Size of expected tuple can be based on accessed index.
if tuple_types.len() > value.elements.len() {
return Err(LeoError::from(AsgError::unexpected_type(
&*format!("tuple of length {}", tuple_types.len()),
Some(&*format!("tuple of length {}", value.elements.len())),
return Err(AsgError::unexpected_type(
format!("tuple of length {}", tuple_types.len()),
format!("tuple of length {}", value.elements.len()),
&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() {
Some(Type::Boolean) | None => Some(Type::Boolean),
Some(type_) => {
return Err(LeoError::from(AsgError::unexpected_type(
&type_.to_string(),
Some(&*Type::Boolean.to_string()),
&value.span,
)));
return Err(AsgError::unexpected_type(type_, Type::Boolean, &value.span))?;
}
},
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),
None => None,
Some(type_) => {
return Err(LeoError::from(AsgError::unexpected_type(
&type_.to_string(),
Some("integer, group, field"),
&value.span,
)));
return Err(AsgError::unexpected_type(type_, "integer, group, field", &value.span))?;
}
},
UnaryOperation::BitNot => match expected_type.map(|x| x.full()).flatten() {
Some(type_ @ Type::Integer(_)) => Some(type_),
None => None,
Some(type_) => {
return Err(LeoError::from(AsgError::unexpected_type(
&type_.to_string(),
Some("integer"),
&value.span,
)));
return Err(AsgError::unexpected_type(type_, "integer", &value.span))?;
}
},
};
@ -138,7 +126,7 @@ impl<'a> FromAst<'a, leo_ast::UnaryExpression> for UnaryExpression<'a> {
})
.unwrap_or(false);
if is_expr_unsigned {
return Err(LeoError::from(AsgError::unsigned_negation(&value.span)));
return Err(AsgError::unsigned_negation(&value.span))?;
}
}
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() {
input.container
} 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",
&value.span,
)));
))?;
}
} else {
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()),
})));
}
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 {
let type_ = expression
.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_) {
return Err(LeoError::from(AsgError::unexpected_type(
&expected_type.to_string(),
Some(&*type_.to_string()),
&value.span,
)));
return Err(AsgError::unexpected_type(expected_type, type_, &value.span))?;
}
}

View File

@ -71,11 +71,11 @@ impl<'a> Circuit<'a> {
for member in value.members.iter() {
if let leo_ast::CircuitMember::CircuitVariable(name, type_) = member {
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,
&name.name,
&name.span,
)));
))?;
}
members.insert(
name.name.to_string(),
@ -98,18 +98,16 @@ impl<'a> Circuit<'a> {
for member in value.members.iter() {
if let leo_ast::CircuitMember::CircuitFunction(function) = member {
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,
&function.identifier.name,
&function.identifier.span,
)));
))?;
}
let asg_function = Function::init(new_scope, function)?;
asg_function.circuit.replace(Some(circuit));
if asg_function.is_test() {
return Err(LeoError::from(AsgError::circuit_test_function(
&function.identifier.span,
)));
return Err(AsgError::circuit_test_function(&function.identifier.span))?;
}
members.insert(
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() {
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 {
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 mut director = MonoidalDirector::new(ReturnPathReducer::new());
if !director.reduce_block(&main_block).0 && !self.output.is_unit() {
return Err(LeoError::from(AsgError::function_missing_return(
&self.name.borrow().name,
&value.span,
)));
return Err(AsgError::function_missing_return(&self.name.borrow().name, &value.span))?;
}
#[allow(clippy::never_loop)] // TODO @Protryon: How should we return multiple 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,
&error,
error,
&span,
)));
))?;
}
self.body

View File

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

View File

@ -189,7 +189,7 @@ impl<'a> Scope<'a> {
let dimension = dimension
.value
.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
@ -202,15 +202,15 @@ impl<'a> Scope<'a> {
),
Circuit(name) if name.name.as_ref() == "Self" => Type::Circuit(
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(
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(
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,
_expected_type: Option<PartialType<'a>>,
) -> 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" {
if let Some(input) = scope.resolve_input() {
input.container
} 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",
&statement.span,
)));
))?;
}
} else {
scope
.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 {
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());
@ -119,37 +122,29 @@ impl<'a> FromAst<'a, leo_ast::AssignStatement> for &'a Statement<'a> {
) {
let left = match left {
ConstValue::Int(x) => x.to_usize().ok_or_else(|| {
LeoError::from(AsgError::invalid_assign_index(
name,
&x.to_string(),
&statement.span,
))
AsgError::invalid_assign_index(name, x.to_string(), &statement.span)
})?,
_ => unimplemented!(),
};
let right = match right {
ConstValue::Int(x) => x.to_usize().ok_or_else(|| {
LeoError::from(AsgError::invalid_assign_index(
name,
&x.to_string(),
&statement.span,
))
AsgError::invalid_assign_index(name, x.to_string(), &statement.span)
})?,
_ => unimplemented!(),
};
if right >= left {
target_type = Some(PartialType::Array(item.clone(), Some((right - left) as usize)))
} else {
return Err(LeoError::from(AsgError::invalid_backwards_assignment(
return Err(AsgError::invalid_backwards_assignment(
name,
left,
right,
&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))
@ -157,7 +152,7 @@ impl<'a> FromAst<'a, leo_ast::AssignStatement> for &'a Statement<'a> {
AstAssigneeAccess::ArrayIndex(index) => {
target_type = match target_type.clone() {
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(
scope,
@ -169,12 +164,13 @@ impl<'a> FromAst<'a, leo_ast::AssignStatement> for &'a Statement<'a> {
let index = index
.value
.parse::<usize>()
.map_err(|_| LeoError::from(AsgError::parse_index_error(span)))?;
.map_err(|_| AsgError::parse_index_error(span))?;
target_type = match target_type {
Some(PartialType::Tuple(types)) => types.get(index).cloned().ok_or_else(|| {
LeoError::from(AsgError::tuple_index_out_of_bounds(index, &statement.span))
})?,
_ => return Err(LeoError::from(AsgError::index_into_non_tuple(name, &statement.span))),
Some(PartialType::Tuple(types)) => types
.get(index)
.cloned()
.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)
}
@ -185,29 +181,26 @@ impl<'a> FromAst<'a, leo_ast::AssignStatement> for &'a Statement<'a> {
let members = circuit.members.borrow();
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,
&name.name,
&statement.span,
))
)
})?;
let x = match &member {
CircuitMember::Variable(type_) => type_.clone(),
CircuitMember::Function(_) => {
return Err(LeoError::from(AsgError::illegal_function_assign(
&name.name,
&statement.span,
)));
return Err(AsgError::illegal_function_assign(&name.name, &statement.span))?;
}
};
Some(x.partial())
}
_ => {
return Err(LeoError::from(AsgError::index_into_non_tuple(
return Err(AsgError::index_into_non_tuple(
&statement.assignee.identifier.name,
&statement.span,
)));
))?;
}
};
AssignAccess::Member(name.clone())

View File

@ -71,10 +71,7 @@ impl<'a> FromAst<'a, leo_ast::DefinitionStatement> for &'a Statement<'a> {
.collect::<Vec<String>>()
.join(" ,");
return Err(LeoError::from(AsgError::invalid_const_assign(
&var_names,
&statement.span,
)));
return Err(AsgError::invalid_const_assign(var_names, &statement.span))?;
}
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![];
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",
&statement.span,
)));
))?;
}
if statement.variable_names.len() == 1 {
// 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<_>>());
}
type_ => {
return Err(LeoError::from(AsgError::unexpected_type(
&*format!("{}-ary tuple", statement.variable_names.len()),
type_.map(|x| x.to_string()).as_deref(),
return Err(AsgError::unexpected_type(
format!("{}-ary tuple", statement.variable_names.len()),
type_.map(|x| x.to_string()).unwrap_or("unknown".to_string()),
&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 {
id: scope.context.get_id(),
name: variable.identifier.clone(),
type_: type_.ok_or_else(|| {
LeoError::from(AsgError::unresolved_type(&variable.identifier.name, &statement.span))
})?,
type_: type_.ok_or_else(|| AsgError::unresolved_type(&variable.identifier.name, &statement.span))?,
mutable: variable.mutable,
const_: false,
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 var_name = variable.borrow().name.name.to_string();
if variables.contains_key(&var_name) {
return Err(LeoError::from(AsgError::duplicate_variable_definition(
&var_name,
&statement.span,
)));
return Err(AsgError::duplicate_variable_definition(var_name, &statement.span))?;
}
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.
if !start.is_consty() {
return Err(LeoError::from(AsgError::unexpected_nonconst(
return Err(AsgError::unexpected_nonconst(
&start.span().cloned().unwrap_or_default(),
)));
))?;
}
if !stop.is_consty() {
return Err(LeoError::from(AsgError::unexpected_nonconst(
&stop.span().cloned().unwrap_or_default(),
)));
return Err(AsgError::unexpected_nonconst(&stop.span().cloned().unwrap_or_default()))?;
}
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(),
type_: start
.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,
const_: true,
declaration: crate::VariableDeclaration::IterationDefinition,

View File

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

View File

@ -62,9 +62,9 @@ pub use self::types::*;
mod 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.
///
@ -100,25 +100,31 @@ impl Ast {
/// Serializes the ast into a JSON string.
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> {
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);
serde_json::to_writer_pretty(writer, &self.ast).map_err(|e| eyre!(e))?;
Ok(())
Ok(serde_json::to_writer_pretty(writer, &self.ast)
.map_err(|e| AstError::failed_to_write_ast_to_json_file(&path, &e, Backtrace::new()))?)
}
/// Deserializes the JSON string into a ast.
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 })
}
/// Deserializes the JSON string into a ast from a file.
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)
}
}

View File

@ -20,7 +20,7 @@ use leo_errors::{AstError, LeoError, Span};
/// Replace Self when it is in a 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 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.
/// Functions missing output type return a empty tuple.
pub struct Canonicalizer {
@ -469,7 +469,7 @@ impl ReconstructingReducer for Canonicalizer {
match new {
Type::Array(type_, mut dimensions) => {
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()]));
@ -486,14 +486,14 @@ impl ReconstructingReducer for Canonicalizer {
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()),
}
}
fn reduce_string(&mut self, string: &[Char], span: &Span) -> Result<Expression, LeoError> {
if string.is_empty() {
return Err(LeoError::from(AstError::empty_string(span)));
return Err(AstError::empty_string(span))?;
}
let mut elements = Vec::new();
@ -552,7 +552,7 @@ impl ReconstructingReducer for Canonicalizer {
element: Expression,
) -> Result<ArrayInitExpression, LeoError> {
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);

View File

@ -398,7 +398,7 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
match &console_function_call.function {
ConsoleFunction::Error(_) => ConsoleFunction::Error(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]
version = "1.3"
[dependencies.eyre]
version = "0.6.5"
default-features = false
[dependencies.hex]
version = "0.4.2"

View File

@ -27,7 +27,7 @@ use crate::{
pub use leo_asg::{new_context, AsgContext as Context, AsgContext};
use leo_asg::{Asg, AsgPass, Program as AsgProgram};
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_package::inputs::InputPairs;
use leo_parser::parse_ast;
@ -38,7 +38,6 @@ use snarkvm_fields::PrimeField;
use snarkvm_r1cs::{ConstraintSynthesizer, ConstraintSystem, SynthesisError};
use backtrace::Backtrace;
use eyre::eyre;
use sha2::{Digest, Sha256};
use std::{
fs,
@ -227,13 +226,8 @@ impl<'a, F: PrimeField, G: GroupType<F>> Compiler<'a, F, G> {
///
pub fn parse_program(&mut self) -> Result<(), LeoError> {
// Load the program file.
let content = fs::read_to_string(&self.main_file_path).map_err(|e| {
LeoError::from(CompilerError::file_read_error(
self.main_file_path.clone(),
eyre!(e),
Backtrace::new(),
))
})?;
let content = fs::read_to_string(&self.main_file_path)
.map_err(|e| CompilerError::file_read_error(self.main_file_path.clone(), e, Backtrace::new()))?;
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> {
// Read in the main file as string
let unparsed_file = fs::read_to_string(&self.main_file_path).map_err(|e| {
LeoError::from(CompilerError::file_read_error(
self.main_file_path.clone(),
eyre!(e),
Backtrace::new(),
))
})?;
let unparsed_file = fs::read_to_string(&self.main_file_path)
.map_err(|e| CompilerError::file_read_error(self.main_file_path.clone(), e, Backtrace::new()))?;
// Hash the file contents
let mut hasher = Sha256::new();
@ -356,8 +345,8 @@ impl<'a, F: PrimeField, G: GroupType<F>> Compiler<'a, F, G> {
system_parameters: &SystemParameters<Components>,
) -> Result<bool, LeoError> {
// TODO CONVERT STATE ERROR TO LEO ERROR
let result = verify_local_data_commitment(system_parameters, &self.program_input)
.map_err(|e| LeoError::from(SnarkVMError::from(eyre!(e))))?;
let result = verify_local_data_commitment(system_parameters, &self.program_input).unwrap();
// .map_err(|e| SnarkVMError::new(e))?;
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 {
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 =
result_option.ok_or_else(|| LeoError::from(CompilerError::console_assertion_depends_on_input(span)))?;
let result_bool = result_option.ok_or_else(|| CompilerError::console_assertion_depends_on_input(span))?;
if !result_bool {
return Err(LeoError::from(CompilerError::console_assertion_failed(span)));
return Err(CompilerError::console_assertion_failed(span))?;
}
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) {
Some(index) => index,
None => {
return Err(LeoError::from(
CompilerError::console_container_parameter_length_mismatch(
arg_index + 1,
args.parameters.len(),
&args.span,
),
));
return Err(CompilerError::console_container_parameter_length_mismatch(
arg_index + 1,
args.parameters.len(),
&args.span,
))?;
}
};
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('}');
escape_right_bracket = true;
} else {
return Err(LeoError::from(CompilerError::console_fmt_expected_escaped_right_brace(
&args.span,
)));
return Err(CompilerError::console_fmt_expected_escaped_right_brace(&args.span))?;
}
}
}
_ if in_container => {
return Err(LeoError::from(CompilerError::console_fmt_expected_left_or_right_brace(
&args.span,
)));
return Err(CompilerError::console_fmt_expected_left_or_right_brace(&args.span))?;
}
_ => substring.push(*scalar),
},
@ -92,13 +86,11 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
// Check that containers and parameters match
if arg_index != args.parameters.len() {
return Err(LeoError::from(
CompilerError::console_container_parameter_length_mismatch(
arg_index,
args.parameters.len(),
&args.span,
),
));
return Err(CompilerError::console_container_parameter_length_mismatch(
arg_index,
args.parameters.len(),
&args.span,
))?;
}
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)?;
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(),
None => {
return Err(LeoError::from(CompilerError::invalid_test_context(
file_name.to_string(),
Backtrace::new(),
)));
return Err(CompilerError::invalid_test_context(file_name, 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

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)) => {
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),
span,
))),
))?,
}
}

View File

@ -25,8 +25,5 @@ pub fn evaluate_bit_not<'a, F: PrimeField, G: GroupType<F>>(
value: ConstrainedValue<'a, F, G>,
span: &Span,
) -> Result<ConstrainedValue<'a, F, G>, LeoError> {
Err(LeoError::from(CompilerError::cannot_evaluate_expression(
format!("!{}", value),
span,
)))
Err(CompilerError::cannot_evaluate_expression(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)) => {
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,),
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)) => {
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),
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::Field(field) => Ok(ConstrainedValue::Field(field.negate(cs, span)?)),
ConstrainedValue::Group(group) => Ok(ConstrainedValue::Group(group.negate(cs, span)?)),
value => Err(LeoError::from(CompilerError::incompatible_types(
format!("-{}", value),
span,
))),
value => Err(CompilerError::incompatible_types(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)) => {
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,),
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)) => {
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),
span,
))),
))?,
}
}

View File

@ -28,7 +28,6 @@ use crate::{
use leo_asg::{ConstInt, Expression};
use leo_errors::{CompilerError, LeoError, Span};
use eyre::eyre;
use snarkvm_fields::PrimeField;
use snarkvm_gadgets::{
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);
bounds_check
.enforce_equal(&mut unique_namespace, &Boolean::Constant(true))
.map_err(|e| {
LeoError::from(CompilerError::cannot_enforce_expression(
"array bounds check".to_string(),
eyre!(e),
span,
))
})?;
.map_err(|e| CompilerError::cannot_enforce_expression("array bounds check", e, span))?;
Ok(())
}
@ -83,24 +76,25 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
) -> Result<ConstrainedValue<'a, F, G>, LeoError> {
let mut array = match self.enforce_expression(cs, 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)?;
if let Some(resolved) = index_resolved.to_usize() {
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())
} else {
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
.len()
.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)?;
}
@ -111,23 +105,17 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
let index_bounded = i
.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 index_comparison = index_resolved
.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 =
cs.ns(|| format!("select array access {} {}:{}", i, span.line_start, span.col_start));
let value =
ConstrainedValue::conditionally_select(unique_namespace, &index_comparison, &item, &current_value)
.map_err(|e| {
LeoError::from(CompilerError::cannot_enforce_expression(
"conditional select".to_string(),
eyre!(e),
span,
))
})?;
.map_err(|e| CompilerError::cannot_enforce_expression("conditional select", e, span))?;
current_value = 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> {
let array = match self.enforce_expression(cs, 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 {
@ -159,7 +147,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
let index_bounded: u32 = array
.len()
.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))
} // 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 {
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() {
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())
} else {
@ -196,13 +184,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
let mut unique_namespace = cs.ns(|| namespace_string);
calc_len
.enforce_equal(&mut unique_namespace, &Integer::new(&ConstInt::U32(length as u32)))
.map_err(|e| {
LeoError::from(CompilerError::cannot_enforce_expression(
"array length check".to_string(),
eyre!(e),
span,
))
})?;
.map_err(|e| CompilerError::cannot_enforce_expression("array length check", e, span))?;
}
{
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);
bounds_check
.enforce_equal(&mut unique_namespace, &Boolean::Constant(true))
.map_err(|e| {
LeoError::from(CompilerError::cannot_enforce_expression(
"array bounds check".to_string(),
eyre!(e),
span,
))
})?;
.map_err(|e| CompilerError::cannot_enforce_expression("array bounds check", e, span))?;
}
let mut windows = array.windows(length);
let mut result = ConstrainedValue::Array(vec![]);
@ -257,13 +233,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
let unique_namespace =
unique_namespace.ns(|| format!("array index {} {}:{}", i, span.line_start, span.col_start));
result = ConstrainedValue::conditionally_select(unique_namespace, &equality, &array_value, &result)
.map_err(|e| {
LeoError::from(CompilerError::cannot_enforce_expression(
"conditional select".to_string(),
eyre!(e),
span,
))
})?;
.map_err(|e| CompilerError::cannot_enforce_expression("conditional select", e, span))?;
}
result
})

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -19,7 +19,6 @@
use crate::{value::ConstrainedValue, GroupType};
use leo_errors::{CompilerError, LeoError, Span};
use eyre::eyre;
use snarkvm_fields::PrimeField;
use snarkvm_gadgets::boolean::Boolean;
use snarkvm_r1cs::ConstraintSystem;
@ -38,16 +37,10 @@ pub fn enforce_or<'a, F: PrimeField, G: GroupType<F>, CS: ConstraintSystem<F>>(
&left_bool,
&right_bool,
)
.map_err(|e| {
LeoError::from(CompilerError::cannot_enforce_expression(
"||".to_string(),
eyre!(e),
span,
))
})?;
.map_err(|e| CompilerError::cannot_enforce_expression("||", e, span))?;
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);
}
(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 {
Ok(boolean) => boolean,
_ => return Err(CompilerError::cannot_evaluate_expression("==".to_string(), span).into()),
};
let boolean = constraint_result.map_err(|_| CompilerError::cannot_evaluate_expression("==", span))?;
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)
}
(val_1, val_2) => {
return Err(LeoError::from(CompilerError::incompatible_types(
return Err(CompilerError::incompatible_types(
format!("{} >= {}", val_1, val_2),
span,
)));
))?;
}
};
let boolean = constraint_result
.map_err(|_| LeoError::from(CompilerError::cannot_evaluate_expression(">=".to_string(), span)))?;
let boolean = constraint_result.map_err(|_| CompilerError::cannot_evaluate_expression(">=", span))?;
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)
}
(val_1, val_2) => {
return Err(LeoError::from(CompilerError::incompatible_types(
return Err(CompilerError::incompatible_types(
format!("{} > {}", val_1, val_2),
span,
)));
))?;
}
};
let boolean = constraint_result
.map_err(|_| LeoError::from(CompilerError::cannot_evaluate_expression(">".to_string(), span)))?;
let boolean = constraint_result.map_err(|_| CompilerError::cannot_evaluate_expression(">", span))?;
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)
}
(val_1, val_2) => {
return Err(LeoError::from(CompilerError::incompatible_types(
return Err(CompilerError::incompatible_types(
format!("{} <= {}", val_1, val_2),
span,
)));
))?;
}
};
let boolean = constraint_result
.map_err(|_| LeoError::from(CompilerError::cannot_evaluate_expression("<=".to_string(), span)))?;
let boolean = constraint_result.map_err(|_| CompilerError::cannot_evaluate_expression("<=", span))?;
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)
}
(val_1, val_2) => {
return Err(LeoError::from(CompilerError::incompatible_types(
return Err(CompilerError::incompatible_types(
format!("{} < {}", val_1, val_2),
span,
)));
))?;
}
};
let boolean = constraint_result
.map_err(|_| LeoError::from(CompilerError::cannot_evaluate_expression("<".to_string(), span)))?;
let boolean = constraint_result.map_err(|_| CompilerError::cannot_evaluate_expression("<", span))?;
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.
let tuple = match self.enforce_expression(cs, 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.
if index > tuple.len() - 1 {
// 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())

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
pub fn evaluate_ref(&mut self, variable_ref: &VariableRef) -> Result<ConstrainedValue<'a, F, G>, LeoError> {
// 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 result_value = if let Some(value) = self.get(variable.id) {
value.clone()
} else {
// TODO fix unwrap here.
return Err(LeoError::from(CompilerError::undefined_identifier(
return Err(CompilerError::undefined_identifier(
&variable.name.clone().name,
span.unwrap(),
)));
&span.unwrap_or_default(),
))?;
// 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() {
return Err(CompilerError::function_input_not_found(
function.name.borrow().name.to_string(),
"arguments length invalid".to_string(),
&function.name.borrow().name.to_string(),
"arguments length invalid",
&function.span.clone().unwrap_or_default(),
)
.into());
))?;
}
// 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 {
Some(InputValue::Array(arr)) => {
if array_len != arr.len() {
return Err(LeoError::from(CompilerError::invalid_input_array_dimensions(
return Err(CompilerError::invalid_input_array_dimensions(
arr.len(),
array_len,
span,
)));
))?;
}
// 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(
input_value.unwrap().to_string(),
span,
)));
return Err(CompilerError::invalid_function_input_array(input_value.unwrap(), 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)?;
if !expected_type.is_assignable_from(&declared_type) {
return Err(LeoError::from(AsgError::unexpected_type(
&expected_type.to_string(),
Some(&declared_type.to_string()),
&identifier.span,
)));
return Err(AsgError::unexpected_type(expected_type, declared_type, &identifier.span).into());
}
let member_name = parameter.variable.clone();
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>,
span: &Span,
) -> Result<ConstrainedValue<'a, F, G>, LeoError> {
let input = input_option.ok_or_else(|| {
LeoError::from(CompilerError::function_input_not_found(
"main".to_string(),
name.to_string(),
span,
))
})?;
let input = input_option.ok_or_else(|| CompilerError::function_input_not_found("main", name, span))?;
match (type_, input) {
(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 input_type = input_type.into();
if std::mem::discriminant(&parsed_type) != std::mem::discriminant(&input_type) {
return Err(LeoError::from(CompilerError::integer_value_integer_type_mismatch(
input_type.to_string(),
parsed_type.to_string(),
return Err(CompilerError::integer_value_integer_type_mismatch(
input_type,
parsed_type,
span,
)));
))?;
}
Ok(ConstrainedValue::Integer(Integer::new(&parsed)))
}
(Type::Array(type_, arr_len), InputValue::Array(values)) => {
if *arr_len != values.len() {
return Err(LeoError::from(CompilerError::invalid_input_array_dimensions(
return Err(CompilerError::invalid_input_array_dimensions(
*arr_len,
values.len(),
span,
)));
))?;
}
Ok(ConstrainedValue::Array(
@ -140,11 +134,11 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
}
(Type::Tuple(types), InputValue::Tuple(values)) => {
if values.len() != types.len() {
return Err(LeoError::from(CompilerError::input_tuple_size_mismatch(
return Err(CompilerError::input_tuple_size_mismatch(
types.len(),
values.len(),
span,
)));
))?;
}
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.
// Return an error if the input type and input value do not match.
(_, input) => Err(LeoError::from(CompilerError::input_variable_type_mismatch(
type_.to_string(),
input.to_string(),
name.to_string(),
span,
))),
(_, input) => Err(CompilerError::input_variable_type_mismatch(type_, input, name, span))?,
}
}
}

View File

@ -39,11 +39,11 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
match input_value {
Some(InputValue::Tuple(values)) => {
if values.len() != types.len() {
return Err(LeoError::from(CompilerError::input_tuple_size_mismatch(
return Err(CompilerError::input_tuple_size_mismatch(
types.len(),
values.len(),
span,
)));
))?;
}
// 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(
input_value.unwrap().to_string(),
span,
)));
return Err(CompilerError::invalid_function_input_tuple(input_value.unwrap(), 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.
(_, Some(_), Some(_)) => {
return Err(LeoError::from(CompilerError::double_input_declaration(
name.to_string(),
&input_variable.name.span,
)));
return Err(CompilerError::double_input_declaration(name, &input_variable.name.span))?;
}
// If input option is found in [main] section and input is not const.
(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.
(true, Some(_), None) => {
return Err(LeoError::from(CompilerError::expected_const_input_variable(
name.to_string(),
return Err(CompilerError::expected_const_input_variable(
name,
&input_variable.name.span,
)));
))?;
}
// Input is const, function argument is not.
(false, None, Some(_)) => {
return Err(LeoError::from(CompilerError::expected_non_const_input_variable(
name.to_string(),
return Err(CompilerError::expected_non_const_input_variable(
name,
&input_variable.name.span,
)));
))?;
}
// 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(),
name.to_string(),
name,
&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) {
// Error if we already have a return value.
if return_value.is_some() {
return Err(CompilerError::statement_multiple_returns(span).into());
return Err(CompilerError::statement_multiple_returns(span))?;
} else {
// Set the function return value.
return_value = Some(result);
@ -79,13 +79,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
&result,
value,
)
.map_err(|_| {
LeoError::from(CompilerError::statement_select_fail(
result.to_string(),
value.to_string(),
span,
))
})?,
.map_err(|_| CompilerError::statement_select_fail(result, value, span))?,
);
} else {
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() {
Ok(ConstrainedValue::Tuple(vec![]))
} else {
return_value
.ok_or_else(|| LeoError::from(CompilerError::statement_no_returns(expected_return.to_string(), span)))
Ok(return_value.ok_or_else(|| 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
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();
@ -119,11 +119,11 @@ impl Output {
let return_value_type = value.to_type(span)?;
if !register_type.is_assignable_from(&return_value_type) {
return Err(LeoError::from(CompilerError::output_mismatched_types(
register_type.to_string(),
return_value_type.to_string(),
return Err(CompilerError::output_mismatched_types(
register_type,
return_value_type,
span,
)));
))?;
}
let value = match value {

View File

@ -55,7 +55,7 @@ impl OutputBytes {
// Return an error if we do not have enough return registers
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
@ -73,11 +73,11 @@ impl OutputBytes {
let return_value_type = value.to_type(span)?;
if !register_type.is_assignable_from(&return_value_type) {
return Err(LeoError::from(CompilerError::output_mismatched_types(
register_type.to_string(),
return_value_type.to_string(),
return Err(CompilerError::output_mismatched_types(
register_type,
return_value_type,
span,
)));
))?;
}
let value = value.to_string();

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -24,7 +24,7 @@ use crate::{
StatementResult,
};
use leo_asg::ConditionalStatement;
use leo_errors::{CompilerError, LeoError};
use leo_errors::CompilerError;
use snarkvm_fields::PrimeField;
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())? {
ConstrainedValue::Boolean(resolved) => resolved,
value => {
return Err(LeoError::from(
CompilerError::conditional_boolean_expression_fails_to_resolve_to_bool(value.to_string(), &span),
));
return Err(CompilerError::conditional_boolean_expression_fails_to_resolve_to_bool(
value.to_string(),
&span,
))?;
}
};
@ -75,7 +76,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
outer_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![];
@ -96,7 +97,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
outer_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
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,
) -> Result<(), LeoError> {
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(),
variable_names.len(),
span,
)));
))?;
}
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::Tuple(values) => values,
value => {
return Err(LeoError::from(CompilerError::statement_multiple_definition(
value.to_string(),
&span,
)));
return Err(CompilerError::statement_multiple_definition(value, &span))?;
}
};

View File

@ -26,7 +26,7 @@ use crate::{
StatementResult,
};
use leo_asg::IterationStatement;
use leo_errors::{CompilerError, LeoError};
use leo_errors::CompilerError;
use snarkvm_fields::PrimeField;
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
.enforce_index(cs, statement.start.get(), &span)?
.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
.enforce_index(cs, statement.stop.get(), &span)?
.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) {
(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(),
)));
))?;
}
}
}

View File

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

View File

@ -30,16 +30,11 @@ pub(crate) fn allocate_bool<F: PrimeField, CS: ConstraintSystem<F>>(
option: Option<bool>,
span: &Span,
) -> Result<Boolean, LeoError> {
Boolean::alloc(
Ok(Boolean::alloc(
cs.ns(|| format!("`{}: bool` {}:{}", name, span.line_start, span.col_start)),
|| option.ok_or(SynthesisError::AssignmentMissing),
)
.map_err(|_| {
LeoError::from(CompilerError::boolean_value_missing_boolean(
format!("{}: bool", name),
span,
))
})
.map_err(|_| CompilerError::boolean_value_missing_boolean(format!("{}: bool", name), span))?)
}
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 {
Some(bool)
} else {
return Err(LeoError::from(CompilerError::boolean_value_invalid_boolean(
name.to_owned(),
span,
)));
return Err(CompilerError::boolean_value_invalid_boolean(name, span))?;
}
}
None => None,

View File

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

View File

@ -19,7 +19,6 @@
use crate::number_string_typing;
use leo_errors::{CompilerError, LeoError, Span};
use eyre::eyre;
use snarkvm_fields::PrimeField;
use snarkvm_gadgets::{
bits::{ToBitsBEGadget, ToBytesGadget},
@ -51,14 +50,16 @@ impl<F: PrimeField> FieldType<F> {
let number_info = number_string_typing(&string);
let value = match number_info {
(number, neg) if neg => -F::from_str(&number)
.map_err(|_| LeoError::from(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, neg) if neg => {
-F::from_str(&number).map_err(|_| 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))
.map_err(|_| LeoError::from(CompilerError::field_value_invalid_field(string, span)))?;
.map_err(|_| CompilerError::field_value_invalid_field(string, span))?;
Ok(FieldType(value))
}
@ -68,59 +69,47 @@ impl<F: PrimeField> FieldType<F> {
let result = self
.0
.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))
}
/// 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> {
let value = self.0.add(cs, &other.0).map_err(|e| {
LeoError::from(CompilerError::field_value_binary_operation(
"+".to_string(),
eyre!(e),
span,
))
})?;
let value = self
.0
.add(cs, &other.0)
.map_err(|e| CompilerError::field_value_binary_operation("+", e, span))?;
Ok(FieldType(value))
}
/// 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> {
let value = self.0.sub(cs, &other.0).map_err(|e| {
LeoError::from(CompilerError::field_value_binary_operation(
"-".to_string(),
eyre!(e),
span,
))
})?;
let value = self
.0
.sub(cs, &other.0)
.map_err(|e| CompilerError::field_value_binary_operation("-", e, span))?;
Ok(FieldType(value))
}
/// 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> {
let value = self.0.mul(cs, &other.0).map_err(|e| {
LeoError::from(CompilerError::field_value_binary_operation(
"*".to_string(),
eyre!(e),
span,
))
})?;
let value = self
.0
.mul(cs, &other.0)
.map_err(|e| CompilerError::field_value_binary_operation("*", e, span))?;
Ok(FieldType(value))
}
/// Returns a new `FieldType` by calling the `FpGadget` `inverse` function.
pub fn inverse<CS: ConstraintSystem<F>>(&self, cs: CS, span: &Span) -> Result<Self, LeoError> {
let value = self.0.inverse(cs).map_err(|e| {
LeoError::from(CompilerError::field_value_binary_operation(
"inv".to_string(),
eyre!(e),
span,
))
})?;
let value = self
.0
.inverse(cs)
.map_err(|e| CompilerError::field_value_binary_operation("inv", e, span))?;
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),
)
.map(|value| value.negate(cs, span))
.map_err(|_| {
LeoError::from(CompilerError::field_value_missing_field(
format!("{}: field", name),
span,
))
})?,
(number, _) => FieldType::alloc(
.map_err(|_| CompilerError::field_value_missing_field(format!("{}: field", name), span))?,
(number, _) => Ok(FieldType::alloc(
cs.ns(|| format!("`{}: field` {}:{}", name, span.line_start, span.col_start)),
|| Some(number).ok_or(SynthesisError::AssignmentMissing),
)
@ -55,13 +50,13 @@ pub(crate) fn allocate_field<F: PrimeField, CS: ConstraintSystem<F>>(
format!("{}: field", name),
span,
))
}),
})?),
}
}
None => Err(LeoError::from(CompilerError::field_value_missing_field(
None => Err(CompilerError::field_value_missing_field(
format!("{}: field", name),
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 {
Some(string)
} else {
return Err(LeoError::from(CompilerError::field_value_invalid_field(
input.to_string(),
span,
)));
return Err(CompilerError::field_value_invalid_field(input, span))?;
}
}
None => None,

View File

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

View File

@ -18,7 +18,6 @@ use crate::{number_string_typing, GroupType};
use leo_asg::{GroupCoordinate, GroupValue};
use leo_errors::{CompilerError, LeoError, Span};
use eyre::eyre;
use snarkvm_curves::{
edwards_bls12::{EdwardsAffine, EdwardsParameters, Fq},
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> {
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_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> {
@ -71,7 +71,7 @@ impl GroupType<Fq> for EdwardsGroupType {
EdwardsGroupType::Constant(group) => Ok(EdwardsGroupType::Constant(group.neg())),
EdwardsGroupType::Allocated(group) => {
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)))
}
@ -90,13 +90,7 @@ impl GroupType<Fq> for EdwardsGroupType {
cs,
other_value,
)
.map_err(|e| {
LeoError::from(CompilerError::group_value_binary_operation(
"+".to_string(),
eyre!(e),
span,
))
})?;
.map_err(|e| CompilerError::group_value_binary_operation("+", e, span))?;
Ok(EdwardsGroupType::Allocated(Box::new(result)))
}
@ -104,13 +98,9 @@ impl GroupType<Fq> for EdwardsGroupType {
(EdwardsGroupType::Constant(constant_value), EdwardsGroupType::Allocated(allocated_value))
| (EdwardsGroupType::Allocated(allocated_value), EdwardsGroupType::Constant(constant_value)) => {
Ok(EdwardsGroupType::Allocated(Box::new(
allocated_value.add_constant(cs, constant_value).map_err(|e| {
LeoError::from(CompilerError::group_value_binary_operation(
"+".to_string(),
eyre!(e),
span,
))
})?,
allocated_value
.add_constant(cs, constant_value)
.map_err(|e| CompilerError::group_value_binary_operation("+", e, span))?,
)))
}
}
@ -128,13 +118,7 @@ impl GroupType<Fq> for EdwardsGroupType {
cs,
other_value,
)
.map_err(|e| {
LeoError::from(CompilerError::group_value_binary_operation(
"-".to_string(),
eyre!(e),
span,
))
})?;
.map_err(|e| CompilerError::group_value_binary_operation("-", e, span))?;
Ok(EdwardsGroupType::Allocated(Box::new(result)))
}
@ -142,13 +126,9 @@ impl GroupType<Fq> for EdwardsGroupType {
(EdwardsGroupType::Constant(constant_value), EdwardsGroupType::Allocated(allocated_value))
| (EdwardsGroupType::Allocated(allocated_value), EdwardsGroupType::Constant(constant_value)) => {
Ok(EdwardsGroupType::Allocated(Box::new(
allocated_value.sub_constant(cs, constant_value).map_err(|e| {
LeoError::from(CompilerError::group_value_binary_operation(
"-".to_string(),
eyre!(e),
span,
))
})?,
allocated_value
.sub_constant(cs, constant_value)
.map_err(|e| CompilerError::group_value_binary_operation("-", e, span))?,
)))
}
}
@ -171,10 +151,12 @@ impl EdwardsGroupType {
} else {
let one = edwards_affine_one();
let number_value = match number_info {
(number, neg) if neg => -Fp256::from_str(&number)
.map_err(|_| LeoError::from(CompilerError::group_value_n_group(number, span)))?,
(number, _) => Fp256::from_str(&number)
.map_err(|_| LeoError::from(CompilerError::group_value_n_group(number, span)))?,
(number, neg) if neg => {
-Fp256::from_str(&number).map_err(|_| 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);
@ -225,10 +207,10 @@ impl EdwardsGroupType {
Self::edwards_affine_from_y_str(number_string_typing(&y_string), span, None, span)
}
// Invalid
(x, y) => Err(LeoError::from(CompilerError::group_value_invalid_group(
(x, y) => Err(CompilerError::group_value_invalid_group(
format!("({}, {})", x, y),
span,
))),
))?,
}
}
@ -239,17 +221,16 @@ impl EdwardsGroupType {
element_span: &Span,
) -> Result<EdwardsAffine, LeoError> {
let x = match x_info {
(x_str, neg) if neg => -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(|_| LeoError::from(CompilerError::group_value_x_invalid(x_str, x_span)))?
(x_str, neg) if neg => {
-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(|_| CompilerError::group_value_x_invalid(x_str, x_span))?,
};
match greatest {
// Sign provided
Some(greatest) => EdwardsAffine::from_x_coordinate(x, greatest)
.ok_or_else(|| LeoError::from(CompilerError::group_value_x_recover(element_span))),
Some(greatest) => Ok(EdwardsAffine::from_x_coordinate(x, greatest)
.ok_or_else(|| CompilerError::group_value_x_recover(element_span))?),
// Sign inferred
None => {
// Attempt to recover with a sign_low bit.
@ -263,7 +244,7 @@ impl EdwardsGroupType {
}
// 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,
) -> Result<EdwardsAffine, LeoError> {
let y = match y_info {
(y_str, neg) if neg => -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(|_| LeoError::from(CompilerError::group_value_y_invalid(y_str, y_span)))?
(y_str, neg) if neg => {
-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(|_| CompilerError::group_value_y_invalid(y_str, y_span))?,
};
match greatest {
// Sign provided
Some(greatest) => EdwardsAffine::from_y_coordinate(y, greatest)
.ok_or_else(|| LeoError::from(CompilerError::group_value_y_recover(element_span))),
Some(greatest) => Ok(EdwardsAffine::from_y_coordinate(y, greatest)
.ok_or_else(|| CompilerError::group_value_y_recover(element_span))?),
// Sign inferred
None => {
// Attempt to recover with a sign_low bit.
@ -299,7 +279,7 @@ impl EdwardsGroupType {
}
// 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,
) -> Result<EdwardsAffine, LeoError> {
let x = match x_info {
(x_str, neg) if neg => -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(|_| LeoError::from(CompilerError::group_value_x_invalid(x_str.to_string(), x_span)))?,
(x_str, neg) if neg => {
-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(|_| CompilerError::group_value_x_invalid(x_str, x_span))?,
};
let y = match y_info {
(y_str, neg) if neg => -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(|_| LeoError::from(CompilerError::group_value_y_invalid(y_str.to_string(), y_span)))?,
(y_str, neg) if neg => {
-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(|_| CompilerError::group_value_y_invalid(y_str, y_span))?,
};
let element = EdwardsAffine::new(x, y);
@ -330,10 +310,7 @@ impl EdwardsGroupType {
if element.is_on_curve() {
Ok(element)
} else {
Err(LeoError::from(CompilerError::group_value_not_on_curve(
element.to_string(),
element_span,
)))
Err(CompilerError::group_value_not_on_curve(element, element_span))?
}
}

View File

@ -20,7 +20,6 @@ use leo_asg::{ConstInt, IntegerType};
use leo_ast::InputValue;
use leo_errors::{CompilerError, LeoError, Span};
use eyre::eyre;
use snarkvm_fields::{Field, PrimeField};
use snarkvm_gadgets::{
boolean::Boolean,
@ -162,18 +161,15 @@ impl Integer {
if let InputValue::Integer(type_, number) = input {
let asg_type = IntegerType::from(type_);
if std::mem::discriminant(&asg_type) != std::mem::discriminant(integer_type) {
return Err(LeoError::from(CompilerError::integer_value_integer_type_mismatch(
integer_type.to_string(),
asg_type.to_string(),
return Err(CompilerError::integer_value_integer_type_mismatch(
integer_type,
asg_type,
span,
)));
))?;
}
Some(number)
} else {
return Err(LeoError::from(CompilerError::integer_value_invalid_integer(
input.to_string(),
span,
)));
return Err(CompilerError::integer_value_invalid_integer(input, span))?;
}
}
None => None,
@ -189,7 +185,7 @@ impl Integer {
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>>(
@ -205,7 +201,7 @@ impl Integer {
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>>(
@ -221,7 +217,7 @@ impl Integer {
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>>(
@ -237,7 +233,7 @@ impl Integer {
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>>(
@ -253,7 +249,7 @@ impl Integer {
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>>(
@ -269,7 +265,7 @@ impl Integer {
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 {
($integer: ident, $span: ident => $expression: expr) => {
match $integer {
Integer::I8($integer) => {
Some(Integer::I8($expression.map_err(|e| {
LeoError::from(CompilerError::integer_value_signed(eyre!(e), $span))
})?))
}
Integer::I16($integer) => {
Some(Integer::I16($expression.map_err(|e| {
LeoError::from(CompilerError::integer_value_signed(eyre!(e), $span))
})?))
}
Integer::I32($integer) => {
Some(Integer::I32($expression.map_err(|e| {
LeoError::from(CompilerError::integer_value_signed(eyre!(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))
})?))
}
Integer::I8($integer) => Some(Integer::I8(
$expression.map_err(|e| CompilerError::integer_value_signed(e, $span))?,
)),
Integer::I16($integer) => Some(Integer::I16(
$expression.map_err(|e| CompilerError::integer_value_signed(e, $span))?,
)),
Integer::I32($integer) => Some(Integer::I32(
$expression.map_err(|e| CompilerError::integer_value_signed(e, $span))?,
)),
Integer::I64($integer) => Some(Integer::I64(
$expression.map_err(|e| CompilerError::integer_value_signed(e, $span))?,
)),
Integer::I128($integer) => Some(Integer::I128(
$expression.map_err(|e| CompilerError::integer_value_signed(e, $span))?,
)),
_ => None,
}
@ -110,57 +100,37 @@ macro_rules! match_integers {
macro_rules! match_integers_span {
(($a: ident, $b: ident), $span: ident => $expression:expr) => {
match ($a, $b) {
(Integer::U8($a), Integer::U8($b)) => {
Some(Integer::U8($expression.map_err(|e| {
LeoError::from(CompilerError::integer_value_unsigned(eyre!(e), $span))
})?))
}
(Integer::U16($a), Integer::U16($b)) => {
Some(Integer::U16($expression.map_err(|e| {
LeoError::from(CompilerError::integer_value_unsigned(eyre!(e), $span))
})?))
}
(Integer::U32($a), Integer::U32($b)) => {
Some(Integer::U32($expression.map_err(|e| {
LeoError::from(CompilerError::integer_value_unsigned(eyre!(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::U8($a), Integer::U8($b)) => Some(Integer::U8(
$expression.map_err(|e| CompilerError::integer_value_unsigned(e, $span))?,
)),
(Integer::U16($a), Integer::U16($b)) => Some(Integer::U16(
$expression.map_err(|e| CompilerError::integer_value_unsigned(e, $span))?,
)),
(Integer::U32($a), Integer::U32($b)) => Some(Integer::U32(
$expression.map_err(|e| CompilerError::integer_value_unsigned(e, $span))?,
)),
(Integer::U64($a), Integer::U64($b)) => Some(Integer::U64(
$expression.map_err(|e| CompilerError::integer_value_unsigned(e, $span))?,
)),
(Integer::U128($a), Integer::U128($b)) => Some(Integer::U128(
$expression.map_err(|e| CompilerError::integer_value_unsigned(e, $span))?,
)),
(Integer::I8($a), Integer::I8($b)) => {
Some(Integer::I8($expression.map_err(|e| {
LeoError::from(CompilerError::integer_value_unsigned(eyre!(e), $span))
})?))
}
(Integer::I16($a), Integer::I16($b)) => {
Some(Integer::I16($expression.map_err(|e| {
LeoError::from(CompilerError::integer_value_unsigned(eyre!(e), $span))
})?))
}
(Integer::I32($a), Integer::I32($b)) => {
Some(Integer::I32($expression.map_err(|e| {
LeoError::from(CompilerError::integer_value_unsigned(eyre!(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))
})?))
}
(Integer::I8($a), Integer::I8($b)) => Some(Integer::I8(
$expression.map_err(|e| CompilerError::integer_value_unsigned(e, $span))?,
)),
(Integer::I16($a), Integer::I16($b)) => Some(Integer::I16(
$expression.map_err(|e| CompilerError::integer_value_unsigned(e, $span))?,
)),
(Integer::I32($a), Integer::I32($b)) => Some(Integer::I32(
$expression.map_err(|e| CompilerError::integer_value_unsigned(e, $span))?,
)),
(Integer::I64($a), Integer::I64($b)) => Some(Integer::I64(
$expression.map_err(|e| CompilerError::integer_value_unsigned(e, $span))?,
)),
(Integer::I128($a), Integer::I128($b)) => Some(Integer::I128(
$expression.map_err(|e| CompilerError::integer_value_unsigned(e, $span))?,
)),
(_, _) => None,
}
};
@ -171,7 +141,7 @@ macro_rules! allocate_type {
let option = $option
.map(|s| {
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()?;
@ -188,10 +158,10 @@ macro_rules! allocate_type {
|| option.ok_or(SynthesisError::AssignmentMissing),
)
.map_err(|_| {
LeoError::from(CompilerError::integer_value_missing_integer(
CompilerError::integer_value_missing_integer(
format!("{}: {}", $name.to_string(), stringify!($rust_ty)),
$span,
))
)
})?;
$leo_ty(result)

View File

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

View File

@ -15,12 +15,48 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::create_errors;
use std::{error::Error as ErrorArg, fmt::Debug};
create_errors!(
AstError,
exit_code_mask: 1000u32,
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
big_self_outside_of_circuit {
args: (),

View File

@ -35,7 +35,7 @@ pub struct BacktracedError {
pub message: String,
pub help: Option<String>,
pub exit_code: u32,
pub code_identifier: String,
pub code_identifier: u32,
pub error_type: String,
#[derivative(PartialEq = "ignore")]
#[derivative(Hash = "ignore")]
@ -45,9 +45,9 @@ pub struct BacktracedError {
impl BacktracedError {
pub fn new_from_backtrace<S>(
message: S,
help: Option<S>,
help: Option<String>,
exit_code: u32,
code_identifier: String,
code_identifier: u32,
error_type: String,
backtrace: Backtrace,
) -> Self
@ -63,12 +63,16 @@ impl BacktracedError {
backtrace,
}
}
pub fn exit_code(&self) -> u32 {
0
}
}
impl fmt::Display for BacktracedError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
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,
error_type = self.error_type,
@ -83,7 +87,11 @@ impl fmt::Display for BacktracedError {
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 {
pub fn new_from_span<S>(
message: S,
help: Option<S>,
help: Option<String>,
exit_code: u32,
code_identifier: String,
code_identifier: u32,
error_type: String,
span: &Span,
) -> Self
@ -68,6 +68,10 @@ impl FormattedError {
),
}
}
pub fn exit_code(&self) -> u32 {
0
}
}
impl fmt::Display for FormattedError {
@ -91,11 +95,11 @@ impl fmt::Display for FormattedError {
underline
};
let underlined = underline(self.col_start, self.col_start);
let underlined = underline(self.col_start, self.col_stop);
let error_message = format!(
"[E{error_type}{code_identifier}{exit_code:0>4}]: {message}\n\
--> {path}:{line_start}:{start}\n\
"[E{error_type}{code_identifier:0>3}{exit_code:0>4}]: {message}\n \
--> {path}:{line_start}:{start}\n\
{indent } ",
indent = INDENT,
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, "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;
#[derive(Debug, Error)]
pub enum $error_type {
#[error(transparent)]
@ -34,6 +35,19 @@ macro_rules! create_errors {
impl LeoErrorCode 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)]
fn exit_code_mask() -> u32 {
$exit_code_mask
@ -44,20 +58,20 @@ macro_rules! create_errors {
$error_code_prefix.to_string()
}
fn new_from_backtrace<S>(message: S, help: Option<S>, exit_code: u32, backtrace: Backtrace) -> Self
where
S: ToString {
BacktracedError::new_from_backtrace(
message,
fn new_from_backtrace<S>(message: S, help: Option<String>, exit_code: u32, backtrace: Backtrace) -> Self
where
S: ToString {
BacktracedError::new_from_backtrace(
message,
help,
exit_code + Self::exit_code_mask(),
Self::code_identifier(),
Self::error_type(),
backtrace,
).into()
}
Self::error_type(),
backtrace,
).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 {
FormattedError::new_from_span(
message,

View File

@ -32,3 +32,8 @@ pub use self::tendril_json::*;
pub mod 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;
pub trait ErrorCode: Sized {
fn exit_code(&self) -> u32;
fn exit_code_mask() -> u32;
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
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
S: ToString;
}
pub trait LeoErrorCode: ErrorCode {
#[inline(always)]
fn code_identifier() -> String {
"037".to_string()
fn code_identifier() -> u32 {
037
}
}

View File

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

View File

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

View File

@ -47,8 +47,6 @@ extern crate thiserror;
use leo_input::InputParserError;
use eyre::ErrReport;
#[derive(Debug, Error)]
pub enum LeoError {
#[error(transparent)]
@ -73,10 +71,28 @@ pub enum LeoError {
ParserError(#[from] ParserError),
#[error(transparent)]
RustError(#[from] ErrReport),
SnarkVMError(#[from] SnarkVMError),
#[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]

View File

@ -15,9 +15,11 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::create_errors;
use std::{ffi::OsString, path::PathBuf};
use eyre::ErrReport;
use std::{
error::Error as ErrorArg,
fmt::{Debug, Display},
};
create_errors!(
PackageError,
@ -26,399 +28,399 @@ create_errors!(
@backtraced
failed_to_create_imports_directory {
args: (error: ErrReport),
args: (error: impl ErrorArg),
msg: format!("failed creating imports directory {}", error),
help: None,
}
@backtraced
import_does_not_exist {
args: (package: String),
args: (package: impl Display),
msg: format!("package {} does not exist as an import", package),
help: None,
}
@backtraced
failed_to_remove_imports_directory {
args: (error: ErrReport),
args: (error: impl ErrorArg),
msg: format!("failed removing imports directory {}", error),
help: None,
}
@backtraced
failed_to_create_inputs_directory {
args: (error: ErrReport),
args: (error: impl ErrorArg),
msg: format!("failed creating inputs directory {}", error),
help: None,
}
@backtraced
failed_to_get_input_file_entry {
args: (error: ErrReport),
args: (error: impl ErrorArg),
msg: format!("failed to get input file entry: {}", error),
help: None,
}
@backtraced
failed_to_get_input_file_name {
args: (file: OsString),
args: (file: impl Debug),
msg: format!("failed to get input file name: {:?}", file),
help: None,
}
@backtraced
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),
help: None,
}
@backtraced
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_),
help: None,
}
@backtraced
failed_to_read_inputs_directory {
args: (error: ErrReport),
args: (error: impl ErrorArg),
msg: format!("failed reading inputs directory {}", error),
help: None,
}
@backtraced
failed_to_read_input_file {
args: (path: PathBuf),
args: (path: impl Debug),
msg: format!("Cannot read input file from the provided file path - {:?}", path),
help: None,
}
@backtraced
io_error_input_file {
args: (error: ErrReport),
args: (error: impl ErrorArg),
msg: format!("IO error input file from the provided file path - {}", error),
help: None,
}
@backtraced
failed_to_read_state_file {
args: (path: PathBuf),
args: (path: impl Debug),
msg: format!("Cannot read state file from the provided file path - {:?}", path),
help: None,
}
@backtraced
io_error_state_file {
args: (error: ErrReport),
args: (error: impl ErrorArg),
msg: format!("IO error state file from the provided file path - {}", error),
help: None,
}
@backtraced
failed_to_read_checksum_file {
args: (path: PathBuf),
args: (path: impl Debug),
msg: format!("Cannot read checksum file from the provided file path - {:?}", path),
help: None,
}
@backtraced
failed_to_remove_checksum_file {
args: (path: PathBuf),
args: (path: impl Debug),
msg: format!("Cannot remove checksum file from the provided file path - {:?}", path),
help: None,
}
@backtraced
io_error_checksum_file {
args: (error: ErrReport),
args: (error: impl ErrorArg),
msg: format!("IO cannot read checksum file from the provided file path - {}", error),
help: None,
}
@backtraced
failed_to_read_circuit_file {
args: (path: PathBuf),
args: (path: impl Debug),
msg: format!("Cannot read circuit file from the provided file path - {:?}", path),
help: None,
}
@backtraced
failed_to_remove_circuit_file {
args: (path: PathBuf),
args: (path: impl Debug),
msg: format!("Cannot remove circuit file from the provided file path - {:?}", path),
help: None,
}
@backtraced
io_error_circuit_file {
args: (error: ErrReport),
args: (error: impl ErrorArg),
msg: format!("IO error circuit file from the provided file path - {}", error),
help: None,
}
@backtraced
failed_to_create_outputs_directory {
args: (error: ErrReport),
args: (error: impl ErrorArg),
msg: format!("failed creating outputs directory {}", error),
help: None,
}
@backtraced
failed_to_remove_outputs_directory {
args: (error: ErrReport),
args: (error: impl ErrorArg),
msg: format!("failed removing outputs directory {}", error),
help: None,
}
@backtraced
failed_to_read_proof_file {
args: (path: PathBuf),
args: (path: impl Debug),
msg: format!("Cannot read proof file from the provided file path - {:?}", path),
help: None,
}
@backtraced
failed_to_remove_proof_file {
args: (path: PathBuf),
args: (path: impl Debug),
msg: format!("Cannot remove proof file from the provided file path - {:?}", path),
help: None,
}
@backtraced
io_error_proof_file {
args: (error: ErrReport),
args: (error: impl ErrorArg),
msg: format!("IO error proof file from the provided file path - {}", error),
help: None,
}
@backtraced
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),
help: None,
}
@backtraced
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),
help: None,
}
@backtraced
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),
help: None,
}
@backtraced
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),
help: None,
}
@backtraced
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),
help: None,
}
@backtraced
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),
help: None,
}
@backtraced
io_error_gitignore_file {
args: (error: ErrReport),
args: (error: impl ErrorArg),
msg: format!("IO error gitignore file from the provided file path - {}", error),
help: None,
}
@backtraced
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),
help: None,
}
@backtraced
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),
help: None,
}
@backtraced
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),
help: None,
}
@backtraced
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),
help: None,
}
@backtraced
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),
help: None,
}
@backtraced
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),
help: None,
}
@backtraced
io_error_manifest_file {
args: (error: ErrReport),
args: (error: impl ErrorArg),
msg: format!("IO error manifest file from the provided file path - {}", error),
help: None,
}
@backtraced
io_error_readme_file {
args: (error: ErrReport),
args: (error: impl ErrorArg),
msg: format!("IO error readme file from the provided file path - {}", error),
help: None,
}
@backtraced
failed_to_create_zip_file {
args: (error: ErrReport),
args: (error: impl ErrorArg),
msg: format!("failed creating zip file {}", error),
help: None,
}
@backtraced
failed_to_open_zip_file {
args: (error: ErrReport),
args: (error: impl ErrorArg),
msg: format!("failed opening zip file {}", error),
help: None,
}
@backtraced
failed_to_read_zip_file {
args: (error: ErrReport),
args: (error: impl ErrorArg),
msg: format!("failed reading zip file {}", error),
help: None,
}
@backtraced
failed_to_write_zip_file {
args: (error: ErrReport),
args: (error: impl ErrorArg),
msg: format!("failed writing zip file {}", error),
help: None,
}
@backtraced
failed_to_remove_zip_file {
args: (path: PathBuf),
args: (path: impl Debug),
msg: format!("failed removing zip file from the provided file path - {:?}", path),
help: None,
}
@backtraced
failed_to_zip {
args: (error: ErrReport),
args: (error: impl ErrorArg),
msg: error,
help: None,
}
@backtraced
io_error_zip_file {
args: (error: ErrReport),
args: (error: impl ErrorArg),
msg: format!("IO error zip file from the provided file path - {}", error),
help: None,
}
@backtraced
io_error_library_file {
args: (error: ErrReport),
args: (error: impl ErrorArg),
msg: format!("IO error library file from the provided file path - {}", error),
help: None,
}
@backtraced
io_error_main_file {
args: (error: ErrReport),
args: (error: impl ErrorArg),
msg: format!("IO error main file from the provided file path - {}", error),
help: None,
}
@backtraced
failed_to_create_source_directory {
args: (error: ErrReport),
args: (error: impl ErrorArg),
msg: format!("failed creating source directory {}", error),
help: None,
}
@backtraced
failed_to_get_source_file_entry {
args: (error: ErrReport),
args: (error: impl ErrorArg),
msg: format!("failed to get input file entry: {}", error),
help: None,
}
@backtraced
failed_to_get_source_file_extension {
args: (extension: OsString),
args: (extension: impl Debug),
msg: format!("failed to get source file extension: {:?}", extension),
help: None,
}
@backtraced
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),
help: None,
}
@backtraced
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),
help: None,
}
@backtraced
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_),
help: None,
}
@backtraced
failed_to_read_source_directory {
args: (error: ErrReport),
args: (error: impl ErrorArg),
msg: format!("failed reading source directory {}", error),
help: None,
}
@backtraced
failed_to_initialize_package {
args: (package: String, path: OsString),
args: (package: impl Display, path: impl Debug),
msg: format!("failed to initialize package {} {:?}", package, path),
help: None,
}
@backtraced
invalid_package_name {
args: (package: String),
args: (package: impl Display),
msg: format!("invalid project name {}", package),
help: None,
}

View File

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

View File

@ -50,7 +50,7 @@ impl<'a> ImportResolver<'a> for ImportParser<'a> {
) -> Result<Option<Program<'a>>, LeoError> {
let full_path = package_segments.join(".");
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) {
return Ok(Some(program.clone()));

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