diff --git a/Cargo.lock b/Cargo.lock index 29ebf4fc7e..da2eccdadb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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", ] diff --git a/Cargo.toml b/Cargo.toml index d371ac88a7..ffe2e1880b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" diff --git a/asg/src/const_value.rs b/asg/src/const_value.rs index 81cc84a26e..8f5d33f9f3 100644 --- a/asg/src/const_value.rs +++ b/asg/src/const_value.rs @@ -316,56 +316,16 @@ impl ConstInt { pub fn parse(int_type: &IntegerType, value: &str, span: &Span) -> Result { 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))?), }) } } diff --git a/asg/src/expression/array_access.rs b/asg/src/expression/array_access.rs index 37aa5cf940..7336947fa0 100644 --- a/asg/src/expression/array_access.rs +++ b/asg/src/expression/array_access.rs @@ -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(), - ))); + ))?; } } diff --git a/asg/src/expression/array_init.rs b/asg/src/expression/array_init.rs index e1af3f2bf9..362504d518 100644 --- a/asg/src/expression/array_init.rs +++ b/asg/src/expression/array_init.rs @@ -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::() - .map_err(|_| LeoError::from(AsgError::parse_dimension_error(&value.span))) + .map_err(|_| AsgError::parse_dimension_error(&value.span))?) }) .collect::, 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))?; } } } diff --git a/asg/src/expression/array_inline.rs b/asg/src/expression/array_inline.rs index 54ea10930c..ae26dc4164 100644 --- a/asg/src/expression/array_inline.rs +++ b/asg/src/expression/array_inline.rs @@ -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) diff --git a/asg/src/expression/array_range_access.rs b/asg/src/expression/array_range_access.rs index 99f3701d9f..4fdd32cd5f 100644 --- a/asg/src/expression/array_range_access.rs +++ b/asg/src/expression/array_range_access.rs @@ -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 { diff --git a/asg/src/expression/binary.rs b/asg/src/expression/binary.rs index e20b07b904..df6f444720 100644 --- a/asg/src/expression/binary.rs +++ b/asg/src/expression/binary.rs @@ -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))?; } (_, _) => (), } diff --git a/asg/src/expression/call.rs b/asg/src/expression/call.rs index 24834359cb..51453541a1 100644 --- a/asg/src/expression/call.rs +++ b/asg/src/expression/call.rs @@ -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::, 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), diff --git a/asg/src/expression/cast.rs b/asg/src/expression/cast.rs index ab642693a6..80f53e79c8 100644 --- a/asg/src/expression/cast.rs +++ b/asg/src/expression/cast.rs @@ -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))?; } } diff --git a/asg/src/expression/circuit_access.rs b/asg/src/expression/circuit_access.rs index d14b470a1d..df09cfe0ab 100644 --- a/asg/src/expression/circuit_access.rs +++ b/asg/src/expression/circuit_access.rs @@ -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 { diff --git a/asg/src/expression/circuit_init.rs b/asg/src/expression/circuit_init.rs index 287f5b5cab..249fa77ebb 100644 --- a/asg/src/expression/circuit_init.rs +++ b/asg/src/expression/circuit_init.rs @@ -96,16 +96,16 @@ impl<'a> FromAst<'a, leo_ast::CircuitInitExpression> for CircuitInitExpression<' ) -> Result, 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, - ))); + ))?; } } } diff --git a/asg/src/expression/constant.rs b/asg/src/expression/constant.rs index 13ad0ee3a4..3de0f77d51 100644 --- a/asg/src/expression/constant.rs +++ b/asg/src/expression/constant.rs @@ -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::() - .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 { diff --git a/asg/src/expression/ternary.rs b/asg/src/expression/ternary.rs index faee9fa739..af8956a060 100644 --- a/asg/src/expression/ternary.rs +++ b/asg/src/expression/ternary.rs @@ -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 { diff --git a/asg/src/expression/tuple_access.rs b/asg/src/expression/tuple_access.rs index e556022411..c594c441cf 100644 --- a/asg/src/expression/tuple_access.rs +++ b/asg/src/expression/tuple_access.rs @@ -80,7 +80,7 @@ impl<'a> FromAst<'a, leo_ast::TupleAccessExpression> for TupleAccessExpression<' .index .value .parse::() - .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 { diff --git a/asg/src/expression/tuple_init.rs b/asg/src/expression/tuple_init.rs index e10d93d82b..20c7ff041a 100644 --- a/asg/src/expression/tuple_init.rs +++ b/asg/src/expression/tuple_init.rs @@ -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, - ))); + ))?; } } diff --git a/asg/src/expression/unary.rs b/asg/src/expression/unary.rs index b6873644b3..73809e3dbc 100644 --- a/asg/src/expression/unary.rs +++ b/asg/src/expression/unary.rs @@ -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 { diff --git a/asg/src/expression/variable_ref.rs b/asg/src/expression/variable_ref.rs index 40780c4045..6035a8c4f1 100644 --- a/asg/src/expression/variable_ref.rs +++ b/asg/src/expression/variable_ref.rs @@ -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))?; } } diff --git a/asg/src/program/circuit.rs b/asg/src/program/circuit.rs index e7e1bd6f8b..7f504670f9 100644 --- a/asg/src/program/circuit.rs +++ b/asg/src/program/circuit.rs @@ -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(), diff --git a/asg/src/program/function.rs b/asg/src/program/function.rs index 1c23d064ee..c0c3fc4883 100644 --- a/asg/src/program/function.rs +++ b/asg/src/program/function.rs @@ -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 diff --git a/asg/src/program/mod.rs b/asg/src/program/mod.rs index d21a7a9bea..5f5a446ab6 100644 --- a/asg/src/program/mod.rs +++ b/asg/src/program/mod.rs @@ -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); diff --git a/asg/src/scope.rs b/asg/src/scope.rs index af5c8a79cd..c932021ccc 100644 --- a/asg/src/scope.rs +++ b/asg/src/scope.rs @@ -189,7 +189,7 @@ impl<'a> Scope<'a> { let dimension = dimension .value .parse::() - .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))?, ), }) } diff --git a/asg/src/statement/assign.rs b/asg/src/statement/assign.rs index fa24e9d28a..b697d9a32d 100644 --- a/asg/src/statement/assign.rs +++ b/asg/src/statement/assign.rs @@ -66,25 +66,28 @@ impl<'a> FromAst<'a, leo_ast::AssignStatement> for &'a Statement<'a> { statement: &leo_ast::AssignStatement, _expected_type: Option>, ) -> Result { - 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 = 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::() - .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()) diff --git a/asg/src/statement/definition.rs b/asg/src/statement/definition.rs index 88e7e63759..b6129b8828 100644 --- a/asg/src/statement/definition.rs +++ b/asg/src/statement/definition.rs @@ -71,10 +71,7 @@ impl<'a> FromAst<'a, leo_ast::DefinitionStatement> for &'a Statement<'a> { .collect::>() .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::>()); } 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); diff --git a/asg/src/statement/iteration.rs b/asg/src/statement/iteration.rs index ca4f624713..fd86df130c 100644 --- a/asg/src/statement/iteration.rs +++ b/asg/src/statement/iteration.rs @@ -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, diff --git a/ast/Cargo.toml b/ast/Cargo.toml index 4f817e48fd..96fcd30d0b 100644 --- a/ast/Cargo.toml +++ b/ast/Cargo.toml @@ -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" diff --git a/ast/src/lib.rs b/ast/src/lib.rs index af7e3590ff..be32aba9c0 100644 --- a/ast/src/lib.rs +++ b/ast/src/lib.rs @@ -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 { - 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 { - 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 { - 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) } } diff --git a/ast/src/reducer/canonicalization.rs b/ast/src/reducer/canonicalization.rs index 29c151a884..c15df5feac 100644 --- a/ast/src/reducer/canonicalization.rs +++ b/ast/src/reducer/canonicalization.rs @@ -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 { 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 { 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); diff --git a/ast/src/reducer/reconstructing_director.rs b/ast/src/reducer/reconstructing_director.rs index 95721ffa67..ffc29fecc7 100644 --- a/ast/src/reducer/reconstructing_director.rs +++ b/ast/src/reducer/reconstructing_director.rs @@ -398,7 +398,7 @@ impl ReconstructingDirector { 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))?, } } }; diff --git a/compiler/Cargo.toml b/compiler/Cargo.toml index 156ad14e81..31ed940610 100644 --- a/compiler/Cargo.toml +++ b/compiler/Cargo.toml @@ -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" diff --git a/compiler/src/compiler.rs b/compiler/src/compiler.rs index 0fcdb6d9a4..b5e37be810 100644 --- a/compiler/src/compiler.rs +++ b/compiler/src/compiler.rs @@ -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> 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> Compiler<'a, F, G> { /// pub fn checksum(&self) -> Result { // 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> Compiler<'a, F, G> { system_parameters: &SystemParameters, ) -> Result { // 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) } diff --git a/compiler/src/console/assert.rs b/compiler/src/console/assert.rs index af4e09c573..3e7257a80f 100644 --- a/compiler/src/console/assert.rs +++ b/compiler/src/console/assert.rs @@ -45,14 +45,13 @@ impl<'a, F: PrimeField, G: GroupType> 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(()) diff --git a/compiler/src/console/format.rs b/compiler/src/console/format.rs index e49e8e82b5..fc6c289868 100644 --- a/compiler/src/console/format.rs +++ b/compiler/src/console/format.rs @@ -51,13 +51,11 @@ impl<'a, F: PrimeField, G: GroupType> 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> 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> 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("")) diff --git a/compiler/src/constraints/constraints.rs b/compiler/src/constraints/constraints.rs index 7f12e536cd..95d0853623 100644 --- a/compiler/src/constraints/constraints.rs +++ b/compiler/src/constraints/constraints.rs @@ -49,7 +49,7 @@ pub fn generate_constraints<'a, F: PrimeField, G: GroupType, 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>( { 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 diff --git a/compiler/src/expression/arithmetic/add.rs b/compiler/src/expression/arithmetic/add.rs index 04743e04b2..364fd99f70 100644 --- a/compiler/src/expression/arithmetic/add.rs +++ b/compiler/src/expression/arithmetic/add.rs @@ -38,9 +38,9 @@ pub fn enforce_add<'a, F: PrimeField, G: GroupType, CS: ConstraintSystem>( (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, - ))), + ))?, } } diff --git a/compiler/src/expression/arithmetic/bit_not.rs b/compiler/src/expression/arithmetic/bit_not.rs index ec84560fbc..84df1a3fe6 100644 --- a/compiler/src/expression/arithmetic/bit_not.rs +++ b/compiler/src/expression/arithmetic/bit_not.rs @@ -25,8 +25,5 @@ pub fn evaluate_bit_not<'a, F: PrimeField, G: GroupType>( value: ConstrainedValue<'a, F, G>, span: &Span, ) -> Result, LeoError> { - Err(LeoError::from(CompilerError::cannot_evaluate_expression( - format!("!{}", value), - span, - ))) + Err(CompilerError::cannot_evaluate_expression(format!("!{}", value), span))? } diff --git a/compiler/src/expression/arithmetic/div.rs b/compiler/src/expression/arithmetic/div.rs index 6d611bb459..7f065bc646 100644 --- a/compiler/src/expression/arithmetic/div.rs +++ b/compiler/src/expression/arithmetic/div.rs @@ -35,9 +35,9 @@ pub fn enforce_div<'a, F: PrimeField, G: GroupType, CS: ConstraintSystem>( (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, - ))), + ))?, } } diff --git a/compiler/src/expression/arithmetic/mul.rs b/compiler/src/expression/arithmetic/mul.rs index 4f6e63aae5..34850ce02a 100644 --- a/compiler/src/expression/arithmetic/mul.rs +++ b/compiler/src/expression/arithmetic/mul.rs @@ -35,9 +35,9 @@ pub fn enforce_mul<'a, F: PrimeField, G: GroupType, CS: ConstraintSystem>( (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, - ))), + ))?, } } diff --git a/compiler/src/expression/arithmetic/negate.rs b/compiler/src/expression/arithmetic/negate.rs index 819982df88..9beca482db 100644 --- a/compiler/src/expression/arithmetic/negate.rs +++ b/compiler/src/expression/arithmetic/negate.rs @@ -31,9 +31,6 @@ pub fn enforce_negate<'a, F: PrimeField, G: GroupType, CS: ConstraintSystem 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))?, } } diff --git a/compiler/src/expression/arithmetic/pow.rs b/compiler/src/expression/arithmetic/pow.rs index cd268c56de..fd8bd99e0e 100644 --- a/compiler/src/expression/arithmetic/pow.rs +++ b/compiler/src/expression/arithmetic/pow.rs @@ -32,9 +32,9 @@ pub fn enforce_pow<'a, F: PrimeField, G: GroupType, CS: ConstraintSystem>( (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, - ))), + ))?, } } diff --git a/compiler/src/expression/arithmetic/sub.rs b/compiler/src/expression/arithmetic/sub.rs index 36e7f58bb3..02762450b8 100644 --- a/compiler/src/expression/arithmetic/sub.rs +++ b/compiler/src/expression/arithmetic/sub.rs @@ -38,9 +38,9 @@ pub fn enforce_sub<'a, F: PrimeField, G: GroupType, CS: ConstraintSystem>( (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, - ))), + ))?, } } diff --git a/compiler/src/expression/array/access.rs b/compiler/src/expression/array/access.rs index 97c84e19b4..4f05011deb 100644 --- a/compiler/src/expression/array/access.rs +++ b/compiler/src/expression/array/access.rs @@ -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> 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> ConstrainedProgram<'a, F, G> { ) -> Result, 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> 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, ¤t_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> ConstrainedProgram<'a, F, G> { ) -> Result, 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> 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> 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> 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::( @@ -222,13 +204,7 @@ impl<'a, F: PrimeField, G: GroupType> 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> 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 }) diff --git a/compiler/src/expression/array/array.rs b/compiler/src/expression/array/array.rs index 6b2eee3a98..6a84685424 100644 --- a/compiler/src/expression/array/array.rs +++ b/compiler/src/expression/array/array.rs @@ -33,7 +33,7 @@ impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { array: &[(Cell<&'a Expression<'a>>, bool)], span: &Span, ) -> Result, LeoError> { - let expected_dimension = None; + let expected_dimension: Option = None; let mut result = vec![]; for (element, is_spread) in array.iter() { @@ -52,11 +52,7 @@ impl<'a, F: PrimeField, G: GroupType> 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))?; } } diff --git a/compiler/src/expression/array/index.rs b/compiler/src/expression/array/index.rs index 588e84bc7f..2bd5479ed5 100644 --- a/compiler/src/expression/array/index.rs +++ b/compiler/src/expression/array/index.rs @@ -32,10 +32,7 @@ impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { ) -> Result { 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))?, } } } diff --git a/compiler/src/expression/circuit/access.rs b/compiler/src/expression/circuit/access.rs index fcaad49931..ea0c10120e 100644 --- a/compiler/src/expression/circuit/access.rs +++ b/compiler/src/expression/circuit/access.rs @@ -40,20 +40,22 @@ impl<'a, F: PrimeField, G: GroupType> 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, + ))? } } } diff --git a/compiler/src/expression/circuit/circuit.rs b/compiler/src/expression/circuit/circuit.rs index e2926c9c27..5563d27588 100644 --- a/compiler/src/expression/circuit/circuit.rs +++ b/compiler/src/expression/circuit/circuit.rs @@ -50,10 +50,7 @@ impl<'a, F: PrimeField, G: GroupType> 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))?; } } } diff --git a/compiler/src/expression/conditional/conditional.rs b/compiler/src/expression/conditional/conditional.rs index fae9528672..22e80956f9 100644 --- a/compiler/src/expression/conditional/conditional.rs +++ b/compiler/src/expression/conditional/conditional.rs @@ -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> 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> 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))?, + ) } } diff --git a/compiler/src/expression/logical/and.rs b/compiler/src/expression/logical/and.rs index e4a3400345..f174ff56f4 100644 --- a/compiler/src/expression/logical/and.rs +++ b/compiler/src/expression/logical/and.rs @@ -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, CS: ConstraintSystem>( &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))? } diff --git a/compiler/src/expression/logical/not.rs b/compiler/src/expression/logical/not.rs index 8838ff5d97..31627b41a6 100644 --- a/compiler/src/expression/logical/not.rs +++ b/compiler/src/expression/logical/not.rs @@ -27,9 +27,6 @@ pub fn evaluate_not<'a, F: PrimeField, G: GroupType>( ) -> Result, 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))?, } } diff --git a/compiler/src/expression/logical/or.rs b/compiler/src/expression/logical/or.rs index 799b15f8d2..a742e2d00b 100644 --- a/compiler/src/expression/logical/or.rs +++ b/compiler/src/expression/logical/or.rs @@ -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, CS: ConstraintSystem>( &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))? } diff --git a/compiler/src/expression/relational/eq.rs b/compiler/src/expression/relational/eq.rs index c833523b9c..102418e109 100644 --- a/compiler/src/expression/relational/eq.rs +++ b/compiler/src/expression/relational/eq.rs @@ -75,14 +75,14 @@ pub fn evaluate_eq<'a, F: PrimeField, G: GroupType, CS: ConstraintSystem>( 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)) } diff --git a/compiler/src/expression/relational/ge.rs b/compiler/src/expression/relational/ge.rs index c1443bd33d..ea290d40eb 100644 --- a/compiler/src/expression/relational/ge.rs +++ b/compiler/src/expression/relational/ge.rs @@ -35,15 +35,14 @@ pub fn evaluate_ge<'a, F: PrimeField, G: GroupType, CS: ConstraintSystem>( 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)) } diff --git a/compiler/src/expression/relational/gt.rs b/compiler/src/expression/relational/gt.rs index 8d51d6b45c..3fee6d2db8 100644 --- a/compiler/src/expression/relational/gt.rs +++ b/compiler/src/expression/relational/gt.rs @@ -35,15 +35,14 @@ pub fn evaluate_gt<'a, F: PrimeField, G: GroupType, CS: ConstraintSystem>( 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)) } diff --git a/compiler/src/expression/relational/le.rs b/compiler/src/expression/relational/le.rs index 0e10eb172a..f2f1e13b56 100644 --- a/compiler/src/expression/relational/le.rs +++ b/compiler/src/expression/relational/le.rs @@ -35,15 +35,14 @@ pub fn evaluate_le<'a, F: PrimeField, G: GroupType, CS: ConstraintSystem>( 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)) } diff --git a/compiler/src/expression/relational/lt.rs b/compiler/src/expression/relational/lt.rs index 475a5ad84d..db79393881 100644 --- a/compiler/src/expression/relational/lt.rs +++ b/compiler/src/expression/relational/lt.rs @@ -35,15 +35,14 @@ pub fn evaluate_lt<'a, F: PrimeField, G: GroupType, CS: ConstraintSystem>( 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)) } diff --git a/compiler/src/expression/tuple/access.rs b/compiler/src/expression/tuple/access.rs index 66022e0baf..e5d9e8b3a7 100644 --- a/compiler/src/expression/tuple/access.rs +++ b/compiler/src/expression/tuple/access.rs @@ -35,13 +35,13 @@ impl<'a, F: PrimeField, G: GroupType> 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()) diff --git a/compiler/src/expression/variable_ref/variable_ref.rs b/compiler/src/expression/variable_ref/variable_ref.rs index 26bd081f41..5c5e0cab30 100644 --- a/compiler/src/expression/variable_ref/variable_ref.rs +++ b/compiler/src/expression/variable_ref/variable_ref.rs @@ -26,17 +26,16 @@ impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { /// Enforce a variable expression by getting the resolved value pub fn evaluate_ref(&mut self, variable_ref: &VariableRef) -> Result, 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 }; diff --git a/compiler/src/function/function.rs b/compiler/src/function/function.rs index 501507badb..76fe3b90dd 100644 --- a/compiler/src/function/function.rs +++ b/compiler/src/function/function.rs @@ -49,11 +49,10 @@ impl<'a, F: PrimeField, G: GroupType> 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 diff --git a/compiler/src/function/input/array.rs b/compiler/src/function/input/array.rs index 3b346a83c6..fde60bfb84 100644 --- a/compiler/src/function/input/array.rs +++ b/compiler/src/function/input/array.rs @@ -41,11 +41,11 @@ impl<'a, F: PrimeField, G: GroupType> 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> 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))?; } } diff --git a/compiler/src/function/input/input_section.rs b/compiler/src/function/input/input_section.rs index 47102850ad..e3b81e23b6 100644 --- a/compiler/src/function/input/input_section.rs +++ b/compiler/src/function/input/input_section.rs @@ -43,11 +43,7 @@ impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { }; let declared_type = self.asg.scope.resolve_ast_type(¶meter.type_, ¶meter.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( diff --git a/compiler/src/function/input/main_function_input.rs b/compiler/src/function/input/main_function_input.rs index 308573b201..acac9fc358 100644 --- a/compiler/src/function/input/main_function_input.rs +++ b/compiler/src/function/input/main_function_input.rs @@ -78,13 +78,7 @@ impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { input_option: Option, span: &Span, ) -> Result, 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> 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> 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> 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))?, } } } diff --git a/compiler/src/function/input/tuple.rs b/compiler/src/function/input/tuple.rs index 1bed0a3d2f..c751d21866 100644 --- a/compiler/src/function/input/tuple.rs +++ b/compiler/src/function/input/tuple.rs @@ -39,11 +39,11 @@ impl<'a, F: PrimeField, G: GroupType> 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> 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))?; } } diff --git a/compiler/src/function/main_function.rs b/compiler/src/function/main_function.rs index a37baa21f2..d8547d4692 100644 --- a/compiler/src/function/main_function.rs +++ b/compiler/src/function/main_function.rs @@ -66,10 +66,7 @@ impl<'a, F: PrimeField, G: GroupType> 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> 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, - ))); + ))?; } }; diff --git a/compiler/src/function/result/result.rs b/compiler/src/function/result/result.rs index 5f8b6040fa..9e9e47fbeb 100644 --- a/compiler/src/function/result/result.rs +++ b/compiler/src/function/result/result.rs @@ -55,7 +55,7 @@ impl<'a, F: PrimeField, G: GroupType> 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> 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> 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))?) } } } diff --git a/compiler/src/output/mod.rs b/compiler/src/output/mod.rs index 9df736a661..be7c673c21 100644 --- a/compiler/src/output/mod.rs +++ b/compiler/src/output/mod.rs @@ -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 { diff --git a/compiler/src/output/output_bytes.rs b/compiler/src/output/output_bytes.rs index 66ae4f8ccc..5e9349cac7 100644 --- a/compiler/src/output/output_bytes.rs +++ b/compiler/src/output/output_bytes.rs @@ -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(); diff --git a/compiler/src/output/output_file.rs b/compiler/src/output/output_file.rs index 28a502dc1c..03d702213e 100644 --- a/compiler/src/output/output_file.rs +++ b/compiler/src/output/output_file.rs @@ -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) } diff --git a/compiler/src/prelude/blake2s.rs b/compiler/src/prelude/blake2s.rs index 328410d27b..efc353bc59 100644 --- a/compiler/src/prelude/blake2s.rs +++ b/compiler/src/prelude/blake2s.rs @@ -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> 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 ToBytes".to_owned(), - eyre!(e), - span, - )) - })? + .map_err(|e| CompilerError::cannot_enforce_expression("Vec ToBytes", e, span))? .into_iter() .map(Integer::U8) .map(ConstrainedValue::Integer) diff --git a/compiler/src/statement/assign/assign.rs b/compiler/src/statement/assign/assign.rs index 3d5349dbf0..d1d34829cf 100644 --- a/compiler/src/statement/assign/assign.rs +++ b/compiler/src/statement/assign/assign.rs @@ -59,13 +59,7 @@ impl<'a, F: PrimeField, G: GroupType> 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(()) diff --git a/compiler/src/statement/assign/assignee/array_index.rs b/compiler/src/statement/assign/assignee/array_index.rs index 52ee0d1421..413b97995c 100644 --- a/compiler/src/statement/assign/assignee/array_index.rs +++ b/compiler/src/statement/assign/assignee/array_index.rs @@ -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> 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> 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> 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> 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> 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> 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> 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))? } } } diff --git a/compiler/src/statement/assign/assignee/array_range_index.rs b/compiler/src/statement/assign/assignee/array_range_index.rs index 1312becf28..acdefb8caa 100644 --- a/compiler/src/statement/assign/assignee/array_range_index.rs +++ b/compiler/src/statement/assign/assignee/array_range_index.rs @@ -38,7 +38,7 @@ impl<'a, F: PrimeField, G: GroupType> 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> 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> 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 diff --git a/compiler/src/statement/assign/assignee/member.rs b/compiler/src/statement/assign/assignee/member.rs index 4e12879d2d..081c84f68c 100644 --- a/compiler/src/statement/assign/assignee/member.rs +++ b/compiler/src/statement/assign/assignee/member.rs @@ -31,9 +31,7 @@ impl<'a, F: PrimeField, G: GroupType> 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> 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))?, } } } diff --git a/compiler/src/statement/assign/assignee/mod.rs b/compiler/src/statement/assign/assignee/mod.rs index 2500dc7132..cbe0a9a688 100644 --- a/compiler/src/statement/assign/assignee/mod.rs +++ b/compiler/src/statement/assign/assignee/mod.rs @@ -116,22 +116,22 @@ impl<'a, F: PrimeField, G: GroupType> 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(()) } diff --git a/compiler/src/statement/assign/assignee/tuple.rs b/compiler/src/statement/assign/assignee/tuple.rs index 150b4ffbe6..45c89feaf7 100644 --- a/compiler/src/statement/assign/assignee/tuple.rs +++ b/compiler/src/statement/assign/assignee/tuple.rs @@ -30,26 +30,22 @@ impl<'a, F: PrimeField, G: GroupType> 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))?, } } } diff --git a/compiler/src/statement/conditional/conditional.rs b/compiler/src/statement/conditional/conditional.rs index 1049c130a8..b165405b00 100644 --- a/compiler/src/statement/conditional/conditional.rs +++ b/compiler/src/statement/conditional/conditional.rs @@ -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> 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> 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> 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() { diff --git a/compiler/src/statement/definition/definition.rs b/compiler/src/statement/definition/definition.rs index a84c0d09d3..437630a891 100644 --- a/compiler/src/statement/definition/definition.rs +++ b/compiler/src/statement/definition/definition.rs @@ -31,11 +31,11 @@ impl<'a, F: PrimeField, G: GroupType> 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> 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))?; } }; diff --git a/compiler/src/statement/iteration/iteration.rs b/compiler/src/statement/iteration/iteration.rs index 16bcd2e5da..801811e4be 100644 --- a/compiler/src/statement/iteration/iteration.rs +++ b/compiler/src/statement/iteration/iteration.rs @@ -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> 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> = match (from < to, statement.inclusive) { (true, true) => Box::new(from..=to), diff --git a/compiler/src/statement/statement.rs b/compiler/src/statement/statement.rs index 93462864f4..06cf561fc5 100644 --- a/compiler/src/statement/statement.rs +++ b/compiler/src/statement/statement.rs @@ -82,9 +82,9 @@ impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { } } _ => { - return Err(LeoError::from(CompilerError::statement_unassigned( + return Err(CompilerError::statement_unassigned( &statement.span.clone().unwrap_or_default(), - ))); + ))?; } } } diff --git a/compiler/src/value/address/address.rs b/compiler/src/value/address/address.rs index afe8c57b8a..da2e7c66eb 100644 --- a/compiler/src/value/address/address.rs +++ b/compiler/src/value/address/address.rs @@ -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 { - 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)) } diff --git a/compiler/src/value/boolean/input.rs b/compiler/src/value/boolean/input.rs index 3557f95560..648ce5f2d4 100644 --- a/compiler/src/value/boolean/input.rs +++ b/compiler/src/value/boolean/input.rs @@ -30,16 +30,11 @@ pub(crate) fn allocate_bool>( option: Option, span: &Span, ) -> Result { - 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, CS: ConstraintSystem>( @@ -54,10 +49,7 @@ pub(crate) fn bool_from_input<'a, F: PrimeField, G: GroupType, 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, diff --git a/compiler/src/value/char/char.rs b/compiler/src/value/char/char.rs index ae131e1a97..2a4c97e70e 100644 --- a/compiler/src/value/char/char.rs +++ b/compiler/src/value/char/char.rs @@ -160,10 +160,7 @@ pub(crate) fn char_from_input<'a, F: PrimeField, G: GroupType, 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), diff --git a/compiler/src/value/field/field_type.rs b/compiler/src/value/field/field_type.rs index 4e49368370..1753c5af08 100644 --- a/compiler/src/value/field/field_type.rs +++ b/compiler/src/value/field/field_type.rs @@ -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 FieldType { 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 FieldType { 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>(&self, cs: CS, other: &Self, span: &Span) -> Result { - 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>(&self, cs: CS, other: &Self, span: &Span) -> Result { - 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>(&self, cs: CS, other: &Self, span: &Span) -> Result { - 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>(&self, cs: CS, span: &Span) -> Result { - 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)) } diff --git a/compiler/src/value/field/input.rs b/compiler/src/value/field/input.rs index 7d71cd1639..fee726de68 100644 --- a/compiler/src/value/field/input.rs +++ b/compiler/src/value/field/input.rs @@ -40,13 +40,8 @@ pub(crate) fn allocate_field>( || 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>( 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, 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, diff --git a/compiler/src/value/group/input.rs b/compiler/src/value/group/input.rs index 86c7471191..35438ce814 100644 --- a/compiler/src/value/group/input.rs +++ b/compiler/src/value/group/input.rs @@ -30,16 +30,11 @@ pub(crate) fn allocate_group, CS: ConstraintSyste option: Option, span: &Span, ) -> Result { - 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, CS: ConstraintSystem>( @@ -54,10 +49,7 @@ pub(crate) fn group_from_input<'a, F: PrimeField, G: GroupType, 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, diff --git a/compiler/src/value/group/targets/edwards_bls12.rs b/compiler/src/value/group/targets/edwards_bls12.rs index e136747082..edcd29fe9d 100644 --- a/compiler/src/value/group/targets/edwards_bls12.rs +++ b/compiler/src/value/group/targets/edwards_bls12.rs @@ -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 for EdwardsGroupType { } fn to_allocated>(&self, mut cs: CS, span: &Span) -> Result { - 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>(&self, cs: CS, span: &Span) -> Result { @@ -71,7 +71,7 @@ impl GroupType for EdwardsGroupType { EdwardsGroupType::Constant(group) => Ok(EdwardsGroupType::Constant(group.neg())), EdwardsGroupType::Allocated(group) => { let result = , 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 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 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 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 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 { 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 { 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 { 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))? } } diff --git a/compiler/src/value/integer/integer.rs b/compiler/src/value/integer/integer.rs index 1a1ffb3f2e..9beeb0e913 100644 --- a/compiler/src/value/integer/integer.rs +++ b/compiler/src/value/integer/integer.rs @@ -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>( @@ -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>( @@ -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>( @@ -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>( @@ -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>( @@ -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))?) } } diff --git a/compiler/src/value/integer/macros.rs b/compiler/src/value/integer/macros.rs index bdaae8c6c6..67ae416946 100644 --- a/compiler/src/value/integer/macros.rs +++ b/compiler/src/value/integer/macros.rs @@ -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) diff --git a/errors/src/asg/asg_errors.rs b/errors/src/asg/asg_errors.rs index b2a6b01f66..beb74d0b13 100644 --- a/errors/src/asg/asg_errors.rs +++ b/errors/src/asg/asg_errors.rs @@ -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, } diff --git a/errors/src/ast/ast_errors.rs b/errors/src/ast/ast_errors.rs index 3648e92e1c..9f9f3fb00e 100644 --- a/errors/src/ast/ast_errors.rs +++ b/errors/src/ast/ast_errors.rs @@ -15,12 +15,48 @@ // along with the Leo library. If not, see . 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: (), diff --git a/errors/src/common/backtraced.rs b/errors/src/common/backtraced.rs index 9a96847040..aa1333b303 100644 --- a/errors/src/common/backtraced.rs +++ b/errors/src/common/backtraced.rs @@ -35,7 +35,7 @@ pub struct BacktracedError { pub message: String, pub help: Option, 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( message: S, - help: Option, + help: Option, 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(()) } } diff --git a/errors/src/common/formatted.rs b/errors/src/common/formatted.rs index 07184f2f72..580a475271 100644 --- a/errors/src/common/formatted.rs +++ b/errors/src/common/formatted.rs @@ -42,9 +42,9 @@ pub struct FormattedError { impl FormattedError { pub fn new_from_span( message: S, - help: Option, + help: Option, 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(()) } } diff --git a/errors/src/common/macros.rs b/errors/src/common/macros.rs index 98b1a69b2b..cf84897fa9 100644 --- a/errors/src/common/macros.rs +++ b/errors/src/common/macros.rs @@ -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(message: S, help: Option, exit_code: u32, backtrace: Backtrace) -> Self - where - S: ToString { - BacktracedError::new_from_backtrace( - message, + fn new_from_backtrace(message: S, help: Option, 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(message: S, help: Option, exit_code: u32, span: &Span) -> Self + fn new_from_span(message: S, help: Option, exit_code: u32, span: &Span) -> Self where S: ToString { FormattedError::new_from_span( message, diff --git a/errors/src/common/mod.rs b/errors/src/common/mod.rs index 79ee8225cb..fe9dcb1cf9 100644 --- a/errors/src/common/mod.rs +++ b/errors/src/common/mod.rs @@ -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; diff --git a/errors/src/common/traits.rs b/errors/src/common/traits.rs index 57486748f2..0bb3bda30a 100644 --- a/errors/src/common/traits.rs +++ b/errors/src/common/traits.rs @@ -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(message: S, help: Option, exit_code: u32, backtrace: Backtrace) -> Self + fn new_from_backtrace(message: S, help: Option, exit_code: u32, backtrace: Backtrace) -> Self where S: ToString; - fn new_from_span(message: S, help: Option, exit_code: u32, span: &Span) -> Self + fn new_from_span(message: S, help: Option, 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 } } diff --git a/errors/src/compiler/compiler_errors.rs b/errors/src/compiler/compiler_errors.rs index 2667e3eb6f..a064320113 100644 --- a/errors/src/compiler/compiler_errors.rs +++ b/errors/src/compiler/compiler_errors.rs @@ -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, } diff --git a/errors/src/import/import_errors.rs b/errors/src/import/import_errors.rs index d01d36f34c..eaabadcd6f 100644 --- a/errors/src/import/import_errors.rs +++ b/errors/src/import/import_errors.rs @@ -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, } diff --git a/errors/src/lib.rs b/errors/src/lib.rs index aff03bc907..1d1fcf3a11 100644 --- a/errors/src/lib.rs +++ b/errors/src/lib.rs @@ -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] diff --git a/errors/src/package/package_errors.rs b/errors/src/package/package_errors.rs index 3a84b4927f..719f8b03c0 100644 --- a/errors/src/package/package_errors.rs +++ b/errors/src/package/package_errors.rs @@ -15,9 +15,11 @@ // along with the Leo library. If not, see . 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, } diff --git a/errors/src/parser/parser_errors.rs b/errors/src/parser/parser_errors.rs index 4792dcea16..bb192d79eb 100644 --- a/errors/src/parser/parser_errors.rs +++ b/errors/src/parser/parser_errors.rs @@ -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, } diff --git a/imports/src/parser/import_parser.rs b/imports/src/parser/import_parser.rs index d4ed1edf27..163e789bcc 100644 --- a/imports/src/parser/import_parser.rs +++ b/imports/src/parser/import_parser.rs @@ -50,7 +50,7 @@ impl<'a> ImportResolver<'a> for ImportParser<'a> { ) -> Result>, 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())); diff --git a/imports/src/parser/parse_package.rs b/imports/src/parser/parse_package.rs index f2be60ce71..1d3b39fe55 100644 --- a/imports/src/parser/parse_package.rs +++ b/imports/src/parser/parse_package.rs @@ -83,9 +83,9 @@ impl<'a> ImportParser<'a> { // Get a vector of all packages in the source directory. let entries = fs::read_dir(path) - .map_err(|error| LeoError::from(ImportError::directory_error(error, &error_path, span)))? + .map_err(|error| ImportError::directory_error(error, &error_path, span))? .collect::, std::io::Error>>() - .map_err(|error| LeoError::from(ImportError::directory_error(error, &error_path, span)))?; + .map_err(|error| ImportError::directory_error(error, &error_path, span))?; // Check if the imported package name is in the source directory. let matched_source_entry = entries.into_iter().find(|entry| { @@ -100,9 +100,9 @@ impl<'a> ImportParser<'a> { if imports_directory.exists() { // Get a vector of all packages in the imports directory. let entries = fs::read_dir(imports_directory) - .map_err(|error| LeoError::from(ImportError::directory_error(error, &error_path, span)))? + .map_err(|error| ImportError::directory_error(error, &error_path, span))? .collect::, std::io::Error>>() - .map_err(|error| LeoError::from(ImportError::directory_error(error, &error_path, span)))?; + .map_err(|error| ImportError::directory_error(error, error_path, span))?; // Check if the imported package name is in the imports directory. let matched_import_entry = entries @@ -111,16 +111,16 @@ impl<'a> ImportParser<'a> { // Check if the package name was found in both the source and imports directory. match (matched_source_entry, matched_import_entry) { - (Some(_), Some(_)) => Err(LeoError::from(ImportError::conflicting_imports(package_name, span))), + (Some(_), Some(_)) => Err(ImportError::conflicting_imports(package_name, span).into()), (Some(source_entry), None) => self.parse_package_access(context, &source_entry, &segments[1..], span), (None, Some(import_entry)) => self.parse_package_access(context, &import_entry, &segments[1..], span), - (None, None) => Err(LeoError::from(ImportError::unknown_package(package_name, span))), + (None, None) => Err(ImportError::unknown_package(package_name, span).into()), } } else { // Enforce local package access with no found imports directory match matched_source_entry { Some(source_entry) => self.parse_package_access(context, &source_entry, &segments[1..], span), - None => Err(LeoError::from(ImportError::unknown_package(package_name, span))), + None => Err(ImportError::unknown_package(package_name, span).into()), } } } diff --git a/imports/src/parser/parse_symbol.rs b/imports/src/parser/parse_symbol.rs index 3c43615f46..2863f437c0 100644 --- a/imports/src/parser/parse_symbol.rs +++ b/imports/src/parser/parse_symbol.rs @@ -32,29 +32,26 @@ impl<'a> ImportParser<'a> { // Get the package file type. let file_type = package .file_type() - .map_err(|error| LeoError::from(ImportError::directory_error(error, &package.path(), span)))?; + .map_err(|error| ImportError::directory_error(error, package.path(), span))?; let file_name = package .file_name() .into_string() - .map_err(|_| LeoError::from(ImportError::convert_os_string(span)))?; + .map_err(|_| ImportError::convert_os_string(span))?; let mut file_path = package.path(); if file_type.is_dir() { file_path.push(MAIN_FILE); if !file_path.exists() { - return Err(LeoError::from(ImportError::expected_main_file( - format!("{:?}", file_path.as_path()), - span, - ))); + return Err(ImportError::expected_main_file(file_path.as_path(), span).into()); } } let file_path_str = file_path.to_str().unwrap_or_default(); // Build the package abstract syntax tree. - let program_string = &std::fs::read_to_string(&file_path) - .map_err(|x| LeoError::from(ImportError::io_error(file_path_str, x, span)))?; + let program_string = + &std::fs::read_to_string(&file_path).map_err(|x| ImportError::io_error(file_path_str, x, span))?; let mut program = leo_parser::parse(file_path_str, program_string)?; program.name = file_name; let mut ast = leo_ast::Ast::new(program); diff --git a/leo/main.rs b/leo/main.rs index 5b633f1634..a71589459e 100644 --- a/leo/main.rs +++ b/leo/main.rs @@ -38,6 +38,7 @@ use commands::{ Watch, }; +// TODO remove anyhow::Result for a LeoResult use anyhow::Result; use colored::Colorize; use std::{path::PathBuf, process::exit}; diff --git a/package/Cargo.toml b/package/Cargo.toml index d8f051020a..507d05acf4 100644 --- a/package/Cargo.toml +++ b/package/Cargo.toml @@ -21,10 +21,6 @@ edition = "2018" path = "../errors" version = "1.5.3" -[dependencies.eyre] -version = "0.6.5" -default-features = false - [dependencies.backtrace] version = "0.3.61" diff --git a/package/src/imports/directory.rs b/package/src/imports/directory.rs index 82ef4afe75..c7db6cbaef 100644 --- a/package/src/imports/directory.rs +++ b/package/src/imports/directory.rs @@ -19,7 +19,6 @@ use leo_errors::{LeoError, PackageError}; use std::{borrow::Cow, fs, path::Path}; use backtrace::Backtrace; -use eyre::eyre; pub static IMPORTS_DIRECTORY_NAME: &str = "imports/"; @@ -33,8 +32,8 @@ impl ImportsDirectory { path.to_mut().push(IMPORTS_DIRECTORY_NAME); } - fs::create_dir_all(&path) - .map_err(|e| PackageError::failed_to_create_imports_directory(eyre!(e), Backtrace::new()).into()) + fs::create_dir_all(&path).map_err(|e| PackageError::failed_to_create_imports_directory(e, Backtrace::new()))?; + Ok(()) } /// Removes an imported package in the imports directory at the provided path. @@ -47,11 +46,10 @@ impl ImportsDirectory { path.to_mut().push(package_name); if !path.exists() || !path.is_dir() { - return Err(PackageError::import_does_not_exist(package_name.into(), Backtrace::new()).into()); + return Err(PackageError::import_does_not_exist(package_name, Backtrace::new()))?; } - fs::remove_dir_all(&path) - .map_err(|e| PackageError::failed_to_remove_imports_directory(eyre!(e), Backtrace::new()))?; + fs::remove_dir_all(&path).map_err(|e| PackageError::failed_to_remove_imports_directory(e, Backtrace::new()))?; Ok(()) } diff --git a/package/src/inputs/directory.rs b/package/src/inputs/directory.rs index 3b85b1aaee..0aec0af922 100644 --- a/package/src/inputs/directory.rs +++ b/package/src/inputs/directory.rs @@ -24,7 +24,6 @@ use std::{ }; use backtrace::Backtrace; -use eyre::eyre; pub static INPUTS_DIRECTORY_NAME: &str = "inputs/"; @@ -38,8 +37,8 @@ impl InputsDirectory { path.to_mut().push(INPUTS_DIRECTORY_NAME); } - fs::create_dir_all(&path) - .map_err(|e| PackageError::failed_to_create_inputs_directory(eyre!(e), Backtrace::new()).into()) + fs::create_dir_all(&path).map_err(|e| PackageError::failed_to_create_inputs_directory(e, Backtrace::new()))?; + Ok(()) } /// Returns a list of files in the input directory. @@ -47,12 +46,8 @@ impl InputsDirectory { let mut path = path.to_owned(); path.push(INPUTS_DIRECTORY_NAME); - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - let directory = match fs::read_dir(&path) { - Ok(read_dir) => read_dir, - Err(e) => return Err(PackageError::failed_to_read_inputs_directory(eyre!(e), Backtrace::new()).into()), - }; - + let directory = + fs::read_dir(&path).map_err(|e| PackageError::failed_to_read_inputs_directory(e, Backtrace::new()))?; let mut file_paths = Vec::new(); parse_file_paths(directory, &mut file_paths)?; @@ -62,23 +57,16 @@ impl InputsDirectory { fn parse_file_paths(directory: ReadDir, file_paths: &mut Vec) -> Result<(), LeoError> { for file_entry in directory.into_iter() { - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - let file_entry = match file_entry { - Ok(dir_entry) => dir_entry, - Err(e) => return Err(PackageError::failed_to_get_input_file_entry(eyre!(e), Backtrace::new()).into()), - }; + let file_entry = file_entry.map_err(|e| PackageError::failed_to_get_input_file_entry(e, Backtrace::new()))?; let file_path = file_entry.path(); // Verify that the entry is structured as a valid file or directory let file_type = file_entry.file_type().map_err(|e| { - PackageError::failed_to_get_input_file_type(file_path.as_os_str().to_owned(), eyre!(e), Backtrace::new()) + PackageError::failed_to_get_input_file_type(file_path.as_os_str().to_owned(), e, Backtrace::new()) })?; if file_type.is_dir() { - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - let directory = match fs::read_dir(&file_path) { - Ok(read_dir) => read_dir, - Err(e) => return Err(PackageError::failed_to_read_inputs_directory(eyre!(e), Backtrace::new()).into()), - }; + let directory = fs::read_dir(&file_path) + .map_err(|e| PackageError::failed_to_read_inputs_directory(e, Backtrace::new()))?; parse_file_paths(directory, file_paths)?; continue; @@ -87,8 +75,7 @@ fn parse_file_paths(directory: ReadDir, file_paths: &mut Vec) -> Result file_path.as_os_str().to_owned(), file_type, Backtrace::new(), - ) - .into()); + ))?; } file_paths.push(file_path); diff --git a/package/src/inputs/input.rs b/package/src/inputs/input.rs index a51a31a705..15fc95c751 100644 --- a/package/src/inputs/input.rs +++ b/package/src/inputs/input.rs @@ -21,7 +21,6 @@ use crate::inputs::INPUTS_DIRECTORY_NAME; use leo_errors::{LeoError, PackageError}; use backtrace::Backtrace; -use eyre::eyre; use serde::Deserialize; use std::{ borrow::Cow, @@ -60,27 +59,19 @@ impl InputFile { pub fn read_from<'a>(&self, path: &'a Path) -> Result<(String, Cow<'a, Path>), LeoError> { let path = self.setup_file_path(path); - match fs::read_to_string(&path) { - Ok(input) => Ok((input, path)), - Err(_) => Err(PackageError::failed_to_read_input_file(path.into_owned(), Backtrace::new()).into()), - } + let input = fs::read_to_string(&path) + .map_err(|_| PackageError::failed_to_read_input_file(path.clone().into_owned(), Backtrace::new()))?; + Ok((input, path)) } /// Writes the standard input format to a file. pub fn write_to(self, path: &Path) -> Result<(), LeoError> { let path = self.setup_file_path(path); + let mut file = File::create(&path).map_err(|e| PackageError::io_error_input_file(e, Backtrace::new()))?; - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - let mut file = match File::create(&path) { - Ok(file) => file, - Err(e) => return Err(PackageError::io_error_input_file(eyre!(e), Backtrace::new()).into()), - }; - - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - match file.write_all(self.template().as_bytes()) { - Ok(_) => Ok(()), - Err(e) => Err(PackageError::io_error_input_file(eyre!(e), Backtrace::new()).into()), - } + file.write_all(self.template().as_bytes()) + .map_err(|e| PackageError::io_error_input_file(e, Backtrace::new()))?; + Ok(()) } fn template(&self) -> String { diff --git a/package/src/inputs/pairs.rs b/package/src/inputs/pairs.rs index adf1acbdcf..c68b531329 100644 --- a/package/src/inputs/pairs.rs +++ b/package/src/inputs/pairs.rs @@ -61,18 +61,16 @@ impl TryFrom<&Path> for InputPairs { Some(file_name) => file_name, None => { return Err(PackageError::failed_to_get_input_file_name( - file.as_os_str().to_owned(), + file.as_os_str(), Backtrace::new(), - ) - .into()); + ))?; } }, None => { return Err(PackageError::failed_to_get_input_file_name( - file.as_os_str().to_owned(), + file.as_os_str(), Backtrace::new(), - ) - .into()); + ))?; } }; diff --git a/package/src/inputs/state.rs b/package/src/inputs/state.rs index 18f8dd420f..588c33fc8d 100644 --- a/package/src/inputs/state.rs +++ b/package/src/inputs/state.rs @@ -20,7 +20,6 @@ use crate::inputs::INPUTS_DIRECTORY_NAME; use leo_errors::{LeoError, PackageError}; use backtrace::Backtrace; -use eyre::eyre; use serde::Deserialize; use std::{ borrow::Cow, @@ -59,27 +58,19 @@ impl StateFile { pub fn read_from<'a>(&self, path: &'a Path) -> Result<(String, Cow<'a, Path>), LeoError> { let path = self.setup_file_path(path); - match fs::read_to_string(&path) { - Ok(input) => Ok((input, path)), - Err(_) => Err(PackageError::failed_to_read_state_file(path.into_owned(), Backtrace::new()).into()), - } + let input = fs::read_to_string(&path) + .map_err(|_| PackageError::failed_to_read_state_file(path.clone().into_owned(), Backtrace::new()))?; + Ok((input, path)) } /// Writes the standard input format to a file. pub fn write_to(self, path: &Path) -> Result<(), LeoError> { let path = self.setup_file_path(path); + let mut file = File::create(&path).map_err(|e| PackageError::io_error_state_file(e, Backtrace::new()))?; - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - let mut file = match File::create(&path) { - Ok(file) => file, - Err(e) => return Err(PackageError::io_error_state_file(eyre!(e), Backtrace::new()).into()), - }; - - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - match file.write_all(self.template().as_bytes()) { - Ok(_) => Ok(()), - Err(e) => Err(PackageError::io_error_state_file(eyre!(e), Backtrace::new()).into()), - } + Ok(file + .write_all(self.template().as_bytes()) + .map_err(|e| PackageError::io_error_state_file(e, Backtrace::new()))?) } fn template(&self) -> String { diff --git a/package/src/outputs/checksum.rs b/package/src/outputs/checksum.rs index 59c31eb9fd..f93ad885ef 100644 --- a/package/src/outputs/checksum.rs +++ b/package/src/outputs/checksum.rs @@ -20,7 +20,6 @@ use crate::outputs::OUTPUTS_DIRECTORY_NAME; use leo_errors::{LeoError, PackageError}; use backtrace::Backtrace; -use eyre::eyre; use serde::Deserialize; use std::{ borrow::Cow, @@ -55,25 +54,19 @@ impl ChecksumFile { pub fn read_from(&self, path: &Path) -> Result { let path = self.setup_file_path(path); - fs::read_to_string(&path) - .map_err(|_| PackageError::failed_to_read_checksum_file(path.into_owned(), Backtrace::new()).into()) + let string = fs::read_to_string(&path) + .map_err(|_| PackageError::failed_to_read_checksum_file(path.into_owned(), Backtrace::new()))?; + Ok(string) } /// Writes the given checksum to a file. pub fn write_to(&self, path: &Path, checksum: String) -> Result<(), LeoError> { let path = self.setup_file_path(path); + let mut file = File::create(&path).map_err(|e| PackageError::io_error_checksum_file(e, Backtrace::new()))?; - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - let mut file = match File::create(&path) { - Ok(file) => file, - Err(e) => return Err(PackageError::io_error_checksum_file(eyre!(e), Backtrace::new()).into()), - }; - - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - match file.write_all(checksum.as_bytes()) { - Ok(v) => Ok(v), - Err(e) => Err(PackageError::io_error_checksum_file(eyre!(e), Backtrace::new()).into()), - } + file.write_all(checksum.as_bytes()) + .map_err(|e| PackageError::io_error_checksum_file(e, Backtrace::new()))?; + Ok(()) } /// Removes the checksum at the given path if it exists. Returns `true` on success, @@ -84,11 +77,9 @@ impl ChecksumFile { return Ok(false); } - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - match fs::remove_file(&path) { - Ok(_) => Ok(true), - Err(_) => Err(PackageError::failed_to_remove_checksum_file(path.into_owned(), Backtrace::new()).into()), - } + fs::remove_file(&path) + .map_err(|_| PackageError::failed_to_remove_checksum_file(path.into_owned(), Backtrace::new()))?; + Ok(true) } fn setup_file_path<'a>(&self, path: &'a Path) -> Cow<'a, Path> { diff --git a/package/src/outputs/circuit.rs b/package/src/outputs/circuit.rs index 62a161043c..42601616d2 100644 --- a/package/src/outputs/circuit.rs +++ b/package/src/outputs/circuit.rs @@ -20,7 +20,6 @@ use crate::outputs::OUTPUTS_DIRECTORY_NAME; use leo_errors::{LeoError, PackageError}; use backtrace::Backtrace; -use eyre::eyre; use serde::Deserialize; use std::{ borrow::Cow, @@ -55,25 +54,19 @@ impl CircuitFile { pub fn read_from(&self, path: &Path) -> Result { let path = self.setup_file_path(path); - fs::read_to_string(&path) - .map_err(|_| PackageError::failed_to_read_circuit_file(path.into_owned(), Backtrace::new()).into()) + let string = fs::read_to_string(&path) + .map_err(|_| PackageError::failed_to_read_circuit_file(path.into_owned(), Backtrace::new()))?; + Ok(string) } /// Writes the given serialized circuit to a file. pub fn write_to(&self, path: &Path, circuit: String) -> Result<(), LeoError> { let path = self.setup_file_path(path); + let mut file = File::create(&path).map_err(|e| PackageError::io_error_circuit_file(e, Backtrace::new()))?; - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - let mut file = match File::create(&path) { - Ok(file) => file, - Err(e) => return Err(PackageError::io_error_circuit_file(eyre!(e), Backtrace::new()).into()), - }; - - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - match file.write_all(circuit.as_bytes()) { - Ok(_) => Ok(()), - Err(e) => Err(PackageError::io_error_circuit_file(eyre!(e), Backtrace::new()).into()), - } + file.write_all(circuit.as_bytes()) + .map_err(|e| PackageError::io_error_circuit_file(e, Backtrace::new()))?; + Ok(()) } /// Removes the serialized circuit at the given path if it exists. Returns `true` on success, @@ -84,11 +77,8 @@ impl CircuitFile { return Ok(false); } - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - match fs::remove_file(&path) { - Ok(_) => Ok(true), - Err(_) => Err(PackageError::failed_to_remove_circuit_file(path.into_owned(), Backtrace::new()).into()), - } + fs::remove_file(&path).map_err(|_| PackageError::failed_to_remove_circuit_file(path, Backtrace::new()))?; + Ok(true) } fn setup_file_path<'a>(&self, path: &'a Path) -> Cow<'a, Path> { diff --git a/package/src/outputs/directory.rs b/package/src/outputs/directory.rs index 05088d92c1..4fb3898803 100644 --- a/package/src/outputs/directory.rs +++ b/package/src/outputs/directory.rs @@ -17,7 +17,6 @@ use leo_errors::{LeoError, PackageError}; use backtrace::Backtrace; -use eyre::eyre; use std::{borrow::Cow, fs, path::Path}; pub static OUTPUTS_DIRECTORY_NAME: &str = "outputs/"; @@ -32,8 +31,8 @@ impl OutputsDirectory { path.to_mut().push(OUTPUTS_DIRECTORY_NAME); } - fs::create_dir_all(&path) - .map_err(|e| PackageError::failed_to_create_inputs_directory(eyre!(e), Backtrace::new()).into()) + fs::create_dir_all(&path).map_err(|e| PackageError::failed_to_create_inputs_directory(e, Backtrace::new()))?; + Ok(()) } /// Removes the directory at the provided path. @@ -44,9 +43,8 @@ impl OutputsDirectory { } if path.exists() { - if let Err(e) = fs::remove_dir_all(&path) { - return Err(PackageError::failed_to_create_inputs_directory(eyre!(e), Backtrace::new()).into()); - } + fs::remove_dir_all(&path) + .map_err(|e| PackageError::failed_to_create_inputs_directory(e, Backtrace::new()))?; } Ok(()) diff --git a/package/src/outputs/proof.rs b/package/src/outputs/proof.rs index 6150c07dcc..d4fd3ff83b 100644 --- a/package/src/outputs/proof.rs +++ b/package/src/outputs/proof.rs @@ -20,7 +20,6 @@ use crate::outputs::OUTPUTS_DIRECTORY_NAME; use leo_errors::{LeoError, PackageError}; use backtrace::Backtrace; -use eyre::eyre; use serde::Deserialize; use std::{ borrow::Cow, @@ -55,25 +54,18 @@ impl ProofFile { pub fn read_from(&self, path: &Path) -> Result { let path = self.setup_file_path(path); - fs::read_to_string(&path) - .map_err(|_| PackageError::failed_to_read_proof_file(path.into_owned(), Backtrace::new()).into()) + let string = fs::read_to_string(&path) + .map_err(|_| PackageError::failed_to_read_proof_file(path.into_owned(), Backtrace::new()))?; + Ok(string) } /// Writes the given proof to a file. pub fn write_to(&self, path: &Path, proof: &[u8]) -> Result<(), LeoError> { let path = self.setup_file_path(path); + let mut file = File::create(&path).map_err(|e| PackageError::io_error_proof_file(e, Backtrace::new()))?; - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - let mut file = match File::create(&path) { - Ok(file) => file, - Err(e) => return Err(PackageError::io_error_proof_file(eyre!(e), Backtrace::new()).into()), - }; - - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - if let Err(e) = file.write_all(proof) { - return Err(PackageError::io_error_proof_file(eyre!(e), Backtrace::new()).into()); - }; - + file.write_all(proof) + .map_err(|e| PackageError::io_error_proof_file(e, Backtrace::new()))?; tracing::info!("Saving proof... ({:?})", path); Ok(()) @@ -87,11 +79,8 @@ impl ProofFile { return Ok(false); } - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - match fs::remove_file(&path) { - Ok(_) => Ok(true), - Err(_) => Err(PackageError::failed_to_remove_proof_file(path.into_owned(), Backtrace::new()).into()), - } + fs::remove_file(&path).map_err(|_| PackageError::failed_to_remove_proof_file(path, Backtrace::new()))?; + Ok(true) } fn setup_file_path<'a>(&self, path: &'a Path) -> Cow<'a, Path> { diff --git a/package/src/outputs/proving_key.rs b/package/src/outputs/proving_key.rs index 30b0577073..0cba0066cb 100644 --- a/package/src/outputs/proving_key.rs +++ b/package/src/outputs/proving_key.rs @@ -20,7 +20,6 @@ use crate::outputs::OUTPUTS_DIRECTORY_NAME; use leo_errors::{LeoError, PackageError}; use backtrace::Backtrace; -use eyre::eyre; use serde::Deserialize; use std::{ borrow::Cow, @@ -59,25 +58,19 @@ impl ProvingKeyFile { pub fn read_from(&self, path: &Path) -> Result, LeoError> { let path = self.setup_file_path(path); - fs::read(&path) - .map_err(|_| PackageError::failed_to_read_proving_key_file(path.into_owned(), Backtrace::new()).into()) + let bytes = + fs::read(&path).map_err(|_| PackageError::failed_to_read_proving_key_file(path, Backtrace::new()))?; + Ok(bytes) } /// Writes the given proving key to a file. pub fn write_to<'a>(&self, path: &'a Path, proving_key: &[u8]) -> Result, LeoError> { let path = self.setup_file_path(path); + let mut file = File::create(&path).map_err(|e| PackageError::io_error_proving_key_file(e, Backtrace::new()))?; - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - let mut file = match File::create(&path) { - Ok(file) => file, - Err(e) => return Err(PackageError::io_error_proving_key_file(eyre!(e), Backtrace::new()).into()), - }; - - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - match file.write_all(proving_key) { - Ok(_) => Ok(path), - Err(e) => Err(PackageError::io_error_proving_key_file(eyre!(e), Backtrace::new()).into()), - } + file.write_all(proving_key) + .map_err(|e| PackageError::io_error_proving_key_file(e, Backtrace::new()))?; + Ok(path) } /// Removes the proving key at the given path if it exists. Returns `true` on success, @@ -88,11 +81,8 @@ impl ProvingKeyFile { return Ok(false); } - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - match fs::remove_file(&path) { - Ok(_) => Ok(true), - Err(_) => Err(PackageError::failed_to_remove_proving_key_file(path.into_owned(), Backtrace::new()).into()), - } + fs::remove_file(&path).map_err(|_| PackageError::failed_to_remove_proving_key_file(path, Backtrace::new()))?; + Ok(true) } fn setup_file_path<'a>(&self, path: &'a Path) -> Cow<'a, Path> { diff --git a/package/src/outputs/verification_key.rs b/package/src/outputs/verification_key.rs index 6c6a4e61f7..d09e21e7c5 100644 --- a/package/src/outputs/verification_key.rs +++ b/package/src/outputs/verification_key.rs @@ -20,7 +20,6 @@ use crate::outputs::OUTPUTS_DIRECTORY_NAME; use leo_errors::{LeoError, PackageError}; use backtrace::Backtrace; -use eyre::eyre; use serde::Deserialize; use std::{ borrow::Cow, @@ -59,25 +58,20 @@ impl VerificationKeyFile { pub fn read_from(&self, path: &Path) -> Result, LeoError> { let path = self.setup_file_path(path); - fs::read(&path) - .map_err(|_| PackageError::failed_to_read_verification_key_file(path.into_owned(), Backtrace::new()).into()) + let bytes = fs::read(&path) + .map_err(|_| PackageError::failed_to_read_verification_key_file(path.into_owned(), Backtrace::new()))?; + Ok(bytes) } /// Writes the given verification key to a file. pub fn write_to<'a>(&self, path: &'a Path, verification_key: &[u8]) -> Result, LeoError> { let path = self.setup_file_path(path); + let mut file = + File::create(&path).map_err(|e| PackageError::io_error_verification_key_file(e, Backtrace::new()))?; - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - let mut file = match File::create(&path) { - Ok(file) => file, - Err(e) => return Err(PackageError::io_error_verification_key_file(eyre!(e), Backtrace::new()).into()), - }; - - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - match file.write_all(verification_key) { - Ok(_) => Ok(path), - Err(e) => Err(PackageError::io_error_verification_key_file(eyre!(e), Backtrace::new()).into()), - } + file.write_all(verification_key) + .map_err(|e| PackageError::io_error_verification_key_file(e, Backtrace::new()))?; + Ok(path) } /// Removes the verification key at the given path if it exists. Returns `true` on success, @@ -88,13 +82,9 @@ impl VerificationKeyFile { return Ok(false); } - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - match fs::remove_file(&path) { - Ok(_) => Ok(true), - Err(_) => { - Err(PackageError::failed_to_remove_verification_key_file(path.into_owned(), Backtrace::new()).into()) - } - } + fs::remove_file(&path) + .map_err(|_| PackageError::failed_to_remove_verification_key_file(path, Backtrace::new()))?; + Ok(true) } fn setup_file_path<'a>(&self, path: &'a Path) -> Cow<'a, Path> { diff --git a/package/src/package.rs b/package/src/package.rs index bd62c914b4..c5d2e9f279 100644 --- a/package/src/package.rs +++ b/package/src/package.rs @@ -39,7 +39,7 @@ impl Package { pub fn new(package_name: &str) -> Result { // Check that the package name is valid. if !Self::is_package_name_valid(package_name) { - return Err(PackageError::invalid_package_name(package_name.to_string(), Backtrace::new()).into()); + return Err(PackageError::invalid_package_name(package_name, Backtrace::new()))?; } Ok(Self { @@ -189,11 +189,10 @@ impl Package { { if !Self::can_initialize(package_name, path) { return Err(PackageError::failed_to_initialize_package( - package_name.to_owned(), - path.as_os_str().to_owned(), + package_name, + path.as_os_str(), Backtrace::new(), - ) - .into()); + ))?; } } // Next, initialize this directory as a Leo package. @@ -232,11 +231,10 @@ impl Package { { if !Self::is_initialized(package_name, path) { return Err(PackageError::failed_to_initialize_package( - package_name.to_owned(), - path.as_os_str().to_owned(), + package_name, + path.as_os_str(), Backtrace::new(), - ) - .into()); + ))?; } } @@ -245,7 +243,7 @@ impl Package { /// Removes the package at the given path pub fn remove_imported_package(package_name: &str, path: &Path) -> Result<(), LeoError> { - ImportsDirectory::remove_import(path, package_name) + Ok(ImportsDirectory::remove_import(path, package_name)?) } } diff --git a/package/src/root/gitignore.rs b/package/src/root/gitignore.rs index dd18daf4e6..8190eb239a 100644 --- a/package/src/root/gitignore.rs +++ b/package/src/root/gitignore.rs @@ -19,7 +19,6 @@ use leo_errors::{LeoError, PackageError}; use backtrace::Backtrace; -use eyre::eyre; use serde::Deserialize; use std::{borrow::Cow, fs::File, io::Write, path::Path}; @@ -47,17 +46,10 @@ impl Gitignore { path.to_mut().push(GITIGNORE_FILENAME); } - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - let mut file = match File::create(&path) { - Ok(file) => file, - Err(e) => return Err(PackageError::io_error_gitignore_file(eyre!(e), Backtrace::new()).into()), - }; - - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - match file.write_all(self.template().as_bytes()) { - Ok(v) => Ok(v), - Err(e) => Err(PackageError::io_error_gitignore_file(eyre!(e), Backtrace::new()).into()), - } + let mut file = File::create(&path).map_err(|e| PackageError::io_error_gitignore_file(e, Backtrace::new()))?; + file.write_all(self.template().as_bytes()) + .map_err(|e| PackageError::io_error_gitignore_file(e, Backtrace::new()))?; + Ok(()) } fn template(&self) -> String { diff --git a/package/src/root/manifest.rs b/package/src/root/manifest.rs index e06908f8e9..e281f5b0d3 100644 --- a/package/src/root/manifest.rs +++ b/package/src/root/manifest.rs @@ -18,7 +18,6 @@ use crate::package::Package; use leo_errors::{LeoError, PackageError}; use backtrace::Backtrace; -use eyre::eyre; use serde::Deserialize; use std::{ borrow::Cow, @@ -88,27 +87,12 @@ impl Manifest { path.to_mut().push(MANIFEST_FILENAME); } - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - let mut file = match File::create(&path) { - Ok(file) => file, - Err(e) => { - return Err(PackageError::failed_to_create_manifest_file( - MANIFEST_FILENAME, - eyre!(e), - Backtrace::new(), - ) - .into()); - } - }; + let mut file = File::create(&path) + .map_err(|e| PackageError::failed_to_create_manifest_file(MANIFEST_FILENAME, e, Backtrace::new()))?; - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - match file.write_all(self.template().as_bytes()) { - Ok(v) => Ok(v), - Err(e) => Err(LeoError::from(PackageError::io_error_manifest_file( - eyre!(e), - Backtrace::new(), - ))), - } + file.write_all(self.template().as_bytes()) + .map_err(|e| PackageError::io_error_manifest_file(e, Backtrace::new()))?; + Ok(()) } fn template(&self) -> String { @@ -142,39 +126,18 @@ impl TryFrom<&Path> for Manifest { path.to_mut().push(MANIFEST_FILENAME); } - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - let mut file = match File::open(path.clone()) { - Ok(file) => file, - Err(e) => { - return Err(PackageError::failed_to_open_manifest_file( - MANIFEST_FILENAME, - eyre!(e), - Backtrace::new(), - )); - } - }; + let mut file = File::open(path.clone()) + .map_err(|e| PackageError::failed_to_open_manifest_file(MANIFEST_FILENAME, e, Backtrace::new()))?; - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - let size = match file.metadata() { - Ok(metadata) => metadata.len() as usize, - Err(e) => { - return Err(PackageError::failed_to_get_manifest_metadata_file( - MANIFEST_FILENAME, - eyre!(e), - Backtrace::new(), - )); - } - }; + let size = file + .metadata() + .map_err(|e| PackageError::failed_to_get_manifest_metadata_file(MANIFEST_FILENAME, e, Backtrace::new()))? + .len() as usize; let mut buffer = String::with_capacity(size); - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - if let Err(e) = file.read_to_string(&mut buffer) { - return Err(PackageError::failed_to_read_manifest_file( - MANIFEST_FILENAME, - eyre!(e), - Backtrace::new(), - )); - } + + file.read_to_string(&mut buffer) + .map_err(|e| PackageError::failed_to_read_manifest_file(MANIFEST_FILENAME, e, Backtrace::new()))?; // Determine if the old remote format is being used, and update to new convention @@ -260,29 +223,15 @@ author = "{author}" // Rewrite the toml file if it has been updated if buffer != refactored_toml { - let mut file = match File::create(&path) { - Ok(file) => file, - Err(e) => { - return Err(PackageError::failed_to_create_manifest_file( - MANIFEST_FILENAME, - eyre!(e), - Backtrace::new(), - )); - } - }; + let mut file = File::create(&path) + .map_err(|e| PackageError::failed_to_create_manifest_file(MANIFEST_FILENAME, e, Backtrace::new()))?; - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - if let Err(e) = file.write_all(refactored_toml.as_bytes()) { - return Err(PackageError::failed_to_write_manifest_file( - MANIFEST_FILENAME, - eyre!(e), - Backtrace::new(), - )); - } + file.write_all(refactored_toml.as_bytes()) + .map_err(|e| PackageError::failed_to_write_manifest_file(MANIFEST_FILENAME, e, Backtrace::new()))?; } // Read the toml file toml::from_str(&final_toml) - .map_err(|e| PackageError::failed_to_parse_manifest_file(MANIFEST_FILENAME, eyre!(e), Backtrace::new())) + .map_err(|e| PackageError::failed_to_parse_manifest_file(MANIFEST_FILENAME, e, Backtrace::new())) } } diff --git a/package/src/root/readme.rs b/package/src/root/readme.rs index 1cd5865e02..cfe0872d57 100644 --- a/package/src/root/readme.rs +++ b/package/src/root/readme.rs @@ -20,7 +20,6 @@ use leo_errors::{LeoError, PackageError}; use backtrace::Backtrace; -use eyre::eyre; use serde::Deserialize; use std::{borrow::Cow, fs::File, io::Write, path::Path}; @@ -56,17 +55,11 @@ impl README { path.to_mut().push(README_FILENAME); } - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - let mut file = match File::create(&path) { - Ok(file) => file, - Err(e) => return Err(PackageError::io_error_readme_file(eyre!(e), Backtrace::new()).into()), - }; + let mut file = File::create(&path).map_err(|e| PackageError::io_error_readme_file(e, Backtrace::new()))?; - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - match file.write_all(self.template().as_bytes()) { - Ok(v) => Ok(v), - Err(e) => Err(PackageError::io_error_readme_file(eyre!(e), Backtrace::new()).into()), - } + file.write_all(self.template().as_bytes()) + .map_err(|e| PackageError::io_error_readme_file(e, Backtrace::new()))?; + Ok(()) } fn template(&self) -> String { diff --git a/package/src/root/zip.rs b/package/src/root/zip.rs index 1cfe219649..002ca5a92e 100644 --- a/package/src/root/zip.rs +++ b/package/src/root/zip.rs @@ -33,7 +33,6 @@ use crate::{ use leo_errors::{LeoError, PackageError}; use backtrace::Backtrace; -use eyre::eyre; use serde::Deserialize; use std::{ @@ -86,11 +85,7 @@ impl ZipFile { // Create zip file let path = self.setup_file_path(src_dir); - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - let file = match File::create(&path) { - Ok(file) => file, - Err(e) => return Err(PackageError::failed_to_create_zip_file(eyre!(e), Backtrace::new()).into()), - }; + let file = File::create(&path).map_err(|e| PackageError::failed_to_create_zip_file(e, Backtrace::new()))?; let mut zip = ZipWriter::new(file); let options = FileOptions::default() .compression_method(zip::CompressionMethod::Stored) @@ -114,26 +109,14 @@ impl ZipFile { if path.is_file() { tracing::info!("Adding file {:?} as {:?}", path, name); #[allow(deprecated)] - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - if let Err(e) = zip.start_file_from_path(name, options) { - return Err(PackageError::io_error_zip_file(eyre!(e), Backtrace::new()).into()); - } + zip.start_file_from_path(name, options) + .map_err(|e| PackageError::io_error_zip_file(e, Backtrace::new()))?; - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - let mut f = match File::open(path) { - Ok(file) => file, - Err(e) => return Err(PackageError::failed_to_open_zip_file(eyre!(e), Backtrace::new()).into()), - }; - - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - if let Err(e) = f.read_to_end(&mut buffer) { - return Err(PackageError::failed_to_read_zip_file(eyre!(e), Backtrace::new()).into()); - } - - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - if let Err(e) = zip.write_all(&*buffer) { - return Err(PackageError::failed_to_write_zip_file(eyre!(e), Backtrace::new()).into()); - } + let mut f = File::open(path).map_err(|e| PackageError::failed_to_open_zip_file(e, Backtrace::new()))?; + f.read_to_end(&mut buffer) + .map_err(|e| PackageError::failed_to_read_zip_file(e, Backtrace::new()))?; + zip.write_all(&*buffer) + .map_err(|e| PackageError::failed_to_write_zip_file(e, Backtrace::new()))?; buffer.clear(); } else if !name.as_os_str().is_empty() { @@ -141,16 +124,13 @@ impl ZipFile { // and mapname conversion failed error on unzip tracing::info!("Adding directory {:?} as {:?}", path, name); #[allow(deprecated)] - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - if let Err(e) = zip.add_directory_from_path(name, options) { - return Err(PackageError::io_error_zip_file(eyre!(e), Backtrace::new()).into()); - } + zip.add_directory_from_path(name, options) + .map_err(|e| PackageError::io_error_zip_file(e, Backtrace::new()))?; } } - if let Err(e) = zip.finish() { - return Err(PackageError::io_error_zip_file(eyre!(e), Backtrace::new()).into()); - } + zip.finish() + .map_err(|e| PackageError::io_error_zip_file(e, Backtrace::new()))?; tracing::info!("Package zip file created successfully {:?}", path); @@ -165,11 +145,7 @@ impl ZipFile { return Ok(false); } - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - if fs::remove_file(&path).is_err() { - return Err(PackageError::failed_to_remove_zip_file(path.into_owned(), Backtrace::new()).into()); - } - + fs::remove_file(&path).map_err(|_| PackageError::failed_to_remove_zip_file(path, Backtrace::new()))?; Ok(true) } diff --git a/package/src/source/directory.rs b/package/src/source/directory.rs index c238fb36cf..8d243c654d 100644 --- a/package/src/source/directory.rs +++ b/package/src/source/directory.rs @@ -23,7 +23,6 @@ use std::{ }; use backtrace::Backtrace; -use eyre::eyre; pub static SOURCE_DIRECTORY_NAME: &str = "src/"; @@ -39,8 +38,8 @@ impl SourceDirectory { path.to_mut().push(SOURCE_DIRECTORY_NAME); } - fs::create_dir_all(&path) - .map_err(|e| PackageError::failed_to_create_source_directory(eyre!(e), Backtrace::new()).into()) + fs::create_dir_all(&path).map_err(|e| PackageError::failed_to_create_source_directory(e, Backtrace::new()))?; + Ok(()) } /// Returns a list of files in the source directory. @@ -48,33 +47,25 @@ impl SourceDirectory { let mut path = Cow::from(path); path.to_mut().push(SOURCE_DIRECTORY_NAME); - // Have to handle error mapping this way because of rust error: https://github.com/rust-lang/rust/issues/42424. - let directory = match fs::read_dir(&path) { - Ok(read_dir) => read_dir, - Err(e) => return Err(PackageError::failed_to_read_inputs_directory(eyre!(e), Backtrace::new()).into()), - }; + let directory = + fs::read_dir(&path).map_err(|e| PackageError::failed_to_read_inputs_directory(e, Backtrace::new()))?; let mut file_paths = Vec::new(); for file_entry in directory.into_iter() { let file_entry = - file_entry.map_err(|e| PackageError::failed_to_get_source_file_entry(eyre!(e), Backtrace::new()))?; + file_entry.map_err(|e| PackageError::failed_to_get_source_file_entry(e, Backtrace::new()))?; let file_path = file_entry.path(); // Verify that the entry is structured as a valid file let file_type = file_entry.file_type().map_err(|e| { - PackageError::failed_to_get_source_file_type( - file_path.as_os_str().to_owned(), - eyre!(e), - Backtrace::new(), - ) + PackageError::failed_to_get_source_file_type(file_path.as_os_str().to_owned(), e, Backtrace::new()) })?; if !file_type.is_file() { return Err(PackageError::invalid_source_file_type( file_path.as_os_str().to_owned(), file_type, Backtrace::new(), - ) - .into()); + ))?; } // Verify that the file has the default file extension @@ -86,8 +77,7 @@ impl SourceDirectory { file_path.as_os_str().to_owned(), file_extension.to_owned(), Backtrace::new(), - ) - .into()); + ))?; } file_paths.push(file_path); diff --git a/package/src/source/main.rs b/package/src/source/main.rs index d0beab8f63..4d8d5d6b17 100644 --- a/package/src/source/main.rs +++ b/package/src/source/main.rs @@ -20,7 +20,6 @@ use crate::source::directory::SOURCE_DIRECTORY_NAME; use leo_errors::{LeoError, PackageError}; use backtrace::Backtrace; -use eyre::eyre; use serde::Deserialize; use std::{borrow::Cow, fs::File, io::Write, path::Path}; @@ -62,10 +61,10 @@ impl MainFile { path.to_mut().push(MAIN_FILENAME); } - let mut file = File::create(&path).map_err(|e| PackageError::io_error_main_file(eyre!(e), Backtrace::new()))?; + let mut file = File::create(&path).map_err(|e| PackageError::io_error_main_file(e, Backtrace::new()))?; Ok(file .write_all(self.template().as_bytes()) - .map_err(|e| PackageError::io_error_main_file(eyre!(e), Backtrace::new()))?) + .map_err(|e| PackageError::io_error_main_file(e, Backtrace::new()))?) } fn template(&self) -> String { diff --git a/parser/Cargo.toml b/parser/Cargo.toml index 1732acbc6c..63f9430ab9 100644 --- a/parser/Cargo.toml +++ b/parser/Cargo.toml @@ -40,9 +40,6 @@ features = [ "derive" ] [dependencies.serde_json] version = "1.0" -[dependencies.thiserror] -version = "1.0" - [dependencies.tracing] version = "0.1" diff --git a/parser/src/parser/context.rs b/parser/src/parser/context.rs index 94eee223fa..4721cd3b22 100644 --- a/parser/src/parser/context.rs +++ b/parser/src/parser/context.rs @@ -64,7 +64,7 @@ impl ParserContext { /// Returns an unexpected end of function [`SyntaxError`]. /// pub fn eof(&self) -> LeoError { - LeoError::from(ParserError::unexpected_eof(&self.end_span)) + ParserError::unexpected_eof(&self.end_span).into() } /// @@ -300,11 +300,7 @@ impl ParserContext { if &token == inner { Ok(self.tokens.pop().unwrap().span) } else { - Err(LeoError::from(ParserError::unexpected( - inner.to_string(), - token.to_string(), - span, - ))) + Err(ParserError::unexpected(inner, token, span))? } } else { Err(self.eof()) @@ -319,11 +315,11 @@ impl ParserContext { if token.iter().any(|x| x == inner) { Ok(self.tokens.pop().unwrap()) } else { - Err(LeoError::from(ParserError::unexpected( - inner.to_string(), + Err(ParserError::unexpected( + inner, token.iter().map(|x| format!("'{}'", x)).collect::>().join(", "), span, - ))) + ))? } } else { Err(self.eof()) @@ -364,11 +360,7 @@ impl ParserContext { unimplemented!() } } else { - Err(LeoError::from(ParserError::unexpected_str( - inner.to_string(), - "ident", - span, - ))) + Err(ParserError::unexpected_str(inner, "ident", span))? } } else { Err(self.eof()) diff --git a/parser/src/parser/expression.rs b/parser/src/parser/expression.rs index 3578499031..61aff85c74 100644 --- a/parser/src/parser/expression.rs +++ b/parser/src/parser/expression.rs @@ -16,7 +16,7 @@ use tendril::format_tendril; -use leo_errors::{LeoError, ParserError}; +use leo_errors::ParserError; use super::*; @@ -461,11 +461,7 @@ impl ParserContext { }); } else { let next = self.peek()?; - return Err(LeoError::from(ParserError::unexpected_str( - next.token.to_string(), - "int or ident", - &next.span, - ))); + return Err(ParserError::unexpected_str(&next.token, "int or ident", &next.span))?; } } Token::LeftParen => { @@ -612,7 +608,7 @@ impl ParserContext { let first = match first { SpreadOrExpression::Spread(first) => { let span = span + first.span(); - return Err(LeoError::from(ParserError::spread_in_array_init(&span))); + return Err(ParserError::spread_in_array_init(&span))?; } SpreadOrExpression::Expression(x) => x, }; @@ -729,11 +725,7 @@ impl ParserContext { Expression::Identifier(ident) } token => { - return Err(LeoError::from(ParserError::unexpected_str( - token.to_string(), - "expression", - &span, - ))); + return Err(ParserError::unexpected_str(token, "expression", &span))?; } }) } diff --git a/parser/src/parser/file.rs b/parser/src/parser/file.rs index 8582be17d1..1e970d3874 100644 --- a/parser/src/parser/file.rs +++ b/parser/src/parser/file.rs @@ -16,7 +16,7 @@ use tendril::format_tendril; -use leo_errors::{LeoError, ParserError}; +use leo_errors::ParserError; use crate::KEYWORD_TOKENS; @@ -48,7 +48,7 @@ impl ParserContext { functions.insert(id, function); } Token::Ident(ident) if ident.as_ref() == "test" => { - return Err(LeoError::from(ParserError::test_function(&token.span))); + return Err(ParserError::test_function(&token.span))?; // self.expect(Token::Test)?; // let (id, function) = self.parse_function_declaration()?; // tests.insert(id, TestFunction { @@ -61,8 +61,8 @@ impl ParserContext { global_consts.insert(name, global_const); } _ => { - return Err(LeoError::from(ParserError::unexpected( - token.token.to_string(), + return Err(ParserError::unexpected( + &token.token, [ Token::Import, Token::Circuit, @@ -75,7 +75,7 @@ impl ParserContext { .collect::>() .join(", "), &token.span, - ))); + ))?; } } } @@ -96,7 +96,7 @@ impl ParserContext { let start = self.expect(Token::At)?; let name = self.expect_ident()?; if name.name.as_ref() == "context" { - return Err(LeoError::from(ParserError::context_annotation(&name.span))); + return Err(ParserError::context_annotation(&name.span).into()); } assert_no_whitespace(&start, &name.span, &name.name, "@")?; @@ -108,15 +108,15 @@ impl ParserContext { loop { if let Some(end) = self.eat(Token::RightParen) { if comma { - return Err(LeoError::from(ParserError::unexpected( - Token::RightParen.to_string(), + return Err(ParserError::unexpected( + Token::RightParen, [Token::Ident("identifier".into()), Token::Int("number".into())] .iter() .map(|x| format!("'{}'", x)) .collect::>() .join(", "), &end.span, - ))); + ))?; } end_span = end.span; break; @@ -128,11 +128,7 @@ impl ParserContext { args.push(int.value); } else { let token = self.peek()?; - return Err(LeoError::from(ParserError::unexpected_str( - token.token.to_string(), - "ident or int", - &token.span, - ))); + return Err(ParserError::unexpected_str(&token.token, "ident or int", &token.span))?; } if self.eat(Token::Comma).is_none() && !comma { end_span = self.expect(Token::RightParen)?; @@ -169,7 +165,7 @@ impl ParserContext { } if out.is_empty() { - return Err(LeoError::from(ParserError::invalid_import_list(span))); + return Err(ParserError::invalid_import_list(span))?; } Ok(out) @@ -248,11 +244,7 @@ impl ParserContext { // Return an error if the package name contains a keyword. if let Some(token) = KEYWORD_TOKENS.iter().find(|x| x.to_string() == base.name.as_ref()) { - return Err(LeoError::from(ParserError::unexpected_str( - token.to_string(), - "package name", - &base.span, - ))); + return Err(ParserError::unexpected_str(token, "package name", &base.span))?; } // Return an error if the package name contains invalid characters. @@ -261,7 +253,7 @@ impl ParserContext { .chars() .all(|x| x.is_ascii_lowercase() || x.is_ascii_digit() || x == '-' || x == '_') { - return Err(LeoError::from(ParserError::invalid_package_name(&base.span))); + return Err(ParserError::invalid_package_name(&base.span))?; } // Return the package name. @@ -323,14 +315,14 @@ impl ParserContext { let peeked = &self.peek()?; if peeked.token == Token::Semicolon { if commas { - return Err(LeoError::from(ParserError::mixed_commas_and_semicolons(&peeked.span))); + return Err(ParserError::mixed_commas_and_semicolons(&peeked.span))?; } semi_colons = true; self.expect(Token::Semicolon)?; } else { if semi_colons { - return Err(LeoError::from(ParserError::mixed_commas_and_semicolons(&peeked.span))); + return Err(ParserError::mixed_commas_and_semicolons(&peeked.span))?; } commas = true; @@ -374,21 +366,20 @@ impl ParserContext { /// Returns a [`CircuitMember`] AST node if the next tokens represent a circuit member function. /// pub fn parse_member_function_declaration(&mut self) -> SyntaxResult { - let peeked = &self.peek()?; - let peeked_token = &peeked.token; - if peeked_token == &Token::Function || peeked_token == &Token::At { + let peeked = self.peek()?.clone(); + if &peeked.token == &Token::Function || &peeked.token == &Token::At { let function = self.parse_function_declaration()?; Ok(CircuitMember::CircuitFunction(Box::new(function.1))) } else { - Err(LeoError::from(ParserError::unexpected( - peeked_token.to_string(), + Err(ParserError::unexpected( + &peeked.token, [Token::Function, Token::At] .iter() .map(|x| format!("'{}'", x)) .collect::>() .join(", "), &peeked.span, - ))) + ))? } } @@ -441,9 +432,7 @@ impl ParserContext { } if let Some(mutable) = &mutable { - return Err(LeoError::from(ParserError::mut_function_input( - &(&mutable.span + &name.span), - ))); + return Err(ParserError::mut_function_input(&(&mutable.span + &name.span)))?; } self.expect(Token::Colon)?; diff --git a/parser/src/parser/mod.rs b/parser/src/parser/mod.rs index a195eb0067..8b6eff0e1c 100644 --- a/parser/src/parser/mod.rs +++ b/parser/src/parser/mod.rs @@ -41,11 +41,7 @@ pub(crate) fn assert_no_whitespace(left_span: &Span, right_span: &Span, left: &s let mut error_span = left_span + right_span; error_span.col_start = left_span.col_stop - 1; error_span.col_stop = right_span.col_start - 1; - return Err(LeoError::from(ParserError::unexpected_whitespace( - left, - right, - &error_span, - ))); + return Err(ParserError::unexpected_whitespace(left, right, &error_span))?; } Ok(()) diff --git a/parser/src/parser/statement.rs b/parser/src/parser/statement.rs index 7676e4508c..2f4419aeb3 100644 --- a/parser/src/parser/statement.rs +++ b/parser/src/parser/statement.rs @@ -16,7 +16,7 @@ use super::*; -use leo_errors::{LeoError, ParserError}; +use leo_errors::ParserError; const ASSIGN_TOKENS: &[Token] = &[ Token::Assign, @@ -64,7 +64,7 @@ impl ParserContext { accesses.push(AssigneeAccess::ArrayIndex(*expr.index)); } Expression::Identifier(id) => identifier = id, - _ => return Err(LeoError::from(ParserError::invalid_assignment_target(expr.span()))), + _ => return Err(ParserError::invalid_assignment_target(expr.span()))?, } Ok(identifier) } @@ -191,11 +191,7 @@ impl ParserContext { match s { Statement::Block(_) | Statement::Conditional(_) => Some(Box::new(s)), s => { - return Err(LeoError::from(ParserError::unexpected_statement( - s.to_string(), - "Block or Conditional", - s.span(), - ))); + return Err(ParserError::unexpected_statement(&s, "Block or Conditional", s.span()))?; } } } else { @@ -249,11 +245,7 @@ impl ParserContext { chars } SpannedToken { token, span } => { - return Err(LeoError::from(ParserError::unexpected_str( - token.to_string(), - "formatted string", - &span, - ))); + return Err(ParserError::unexpected_str(token, "formatted string", &span))?; } }; @@ -288,11 +280,11 @@ impl ParserContext { "error" => ConsoleFunction::Error(self.parse_console_args()?), "log" => ConsoleFunction::Log(self.parse_console_args()?), x => { - return Err(LeoError::from(ParserError::unexpected_ident( + return Err(ParserError::unexpected_ident( x, &["assert", "error", "log"], &function.span, - ))); + ))?; } }; self.expect(Token::RightParen)?; @@ -311,9 +303,7 @@ impl ParserContext { pub fn parse_variable_name(&mut self, span: &SpannedToken) -> SyntaxResult { let mutable = self.eat(Token::Mut); if let Some(mutable) = &mutable { - return Err(LeoError::from(ParserError::let_mut_statement( - &(&mutable.span + &span.span), - ))); + return Err(ParserError::let_mut_statement(&(&mutable.span + &span.span)))?; } let name = self.expect_ident()?; diff --git a/parser/src/parser/type_.rs b/parser/src/parser/type_.rs index 10fd83cdf6..c72af90179 100644 --- a/parser/src/parser/type_.rs +++ b/parser/src/parser/type_.rs @@ -15,7 +15,7 @@ // along with the Leo library. If not, see . use super::*; -use leo_errors::{LeoError, ParserError}; +use leo_errors::ParserError; const TYPE_TOKENS: &[Token] = &[ Token::I8, @@ -69,11 +69,7 @@ impl ParserContext { dimensions.push(int); } else { let token = self.peek()?; - return Err(LeoError::from(ParserError::unexpected_str( - token.token.to_string(), - "int", - &token.span, - ))); + return Err(ParserError::unexpected_str(&token.token, "int", &token.span))?; } if self.eat(Token::Comma).is_none() { break; diff --git a/parser/src/tokenizer/mod.rs b/parser/src/tokenizer/mod.rs index f840838128..3543ac5479 100644 --- a/parser/src/tokenizer/mod.rs +++ b/parser/src/tokenizer/mod.rs @@ -70,7 +70,7 @@ pub(crate) fn tokenize(path: &str, input: StrTendril) -> Result { if !check_address(address) { - return Err(LeoError::from(ParserError::invalid_address_lit(address, &span))); + return Err(ParserError::invalid_address_lit(address, &span))?; } } _ => (), @@ -82,8 +82,8 @@ pub(crate) fn tokenize(path: &str, input: StrTendril) -> Result Result