Merge pull request #601 from AleoHQ/remove-mutable-value

Remove mutable ConstrainedValue
This commit is contained in:
Howard Wu 2021-02-03 11:24:39 -08:00 committed by GitHub
commit 0e74f9e10f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
18 changed files with 35 additions and 110 deletions

View File

@ -22,12 +22,8 @@ use leo_asg::Variable;
use snarkvm_models::curves::{Field, PrimeField}; use snarkvm_models::curves::{Field, PrimeField};
impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> { impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
pub fn store_definition(&mut self, variable: &Variable, mut value: ConstrainedValue<F, G>) { pub fn store_definition(&mut self, variable: &Variable, value: ConstrainedValue<F, G>) {
let variable = variable.borrow(); let variable = variable.borrow();
// Store with given mutability
if variable.mutable {
value = ConstrainedValue::Mutable(Box::new(value));
}
self.store(variable.id, value); self.store(variable.id, value);
} }

View File

@ -34,7 +34,7 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
index: &Arc<Expression>, index: &Arc<Expression>,
span: &Span, span: &Span,
) -> Result<ConstrainedValue<F, G>, ExpressionError> { ) -> Result<ConstrainedValue<F, G>, ExpressionError> {
let array = match self.enforce_operand(cs, array)? { let array = match self.enforce_expression(cs, array)? {
ConstrainedValue::Array(array) => array, ConstrainedValue::Array(array) => array,
value => return Err(ExpressionError::undefined_array(value.to_string(), span.to_owned())), value => return Err(ExpressionError::undefined_array(value.to_string(), span.to_owned())),
}; };
@ -52,7 +52,7 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
right: Option<&Arc<Expression>>, right: Option<&Arc<Expression>>,
span: &Span, span: &Span,
) -> Result<ConstrainedValue<F, G>, ExpressionError> { ) -> Result<ConstrainedValue<F, G>, ExpressionError> {
let array = match self.enforce_operand(cs, array)? { let array = match self.enforce_expression(cs, array)? {
ConstrainedValue::Array(array) => array, ConstrainedValue::Array(array) => array,
value => return Err(ExpressionError::undefined_array(value.to_string(), span.to_owned())), value => return Err(ExpressionError::undefined_array(value.to_string(), span.to_owned())),
}; };

View File

@ -32,7 +32,7 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
index: &Arc<Expression>, index: &Arc<Expression>,
span: &Span, span: &Span,
) -> Result<usize, ExpressionError> { ) -> Result<usize, ExpressionError> {
match self.enforce_operand(cs, index)? { match self.enforce_expression(cs, index)? {
ConstrainedValue::Integer(number) => Ok(number.to_usize(span)?), ConstrainedValue::Integer(number) => Ok(number.to_usize(span)?),
value => Err(ExpressionError::invalid_index(value.to_string(), span)), value => Err(ExpressionError::invalid_index(value.to_string(), span)),
} }

View File

@ -35,8 +35,8 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
left: &Arc<Expression>, left: &Arc<Expression>,
right: &Arc<Expression>, right: &Arc<Expression>,
) -> Result<ConstrainedValuePair<F, G>, ExpressionError> { ) -> Result<ConstrainedValuePair<F, G>, ExpressionError> {
let resolved_left = self.enforce_operand(cs, left)?; let resolved_left = self.enforce_expression(cs, left)?;
let resolved_right = self.enforce_operand(cs, right)?; let resolved_right = self.enforce_expression(cs, right)?;
Ok((resolved_left, resolved_right)) Ok((resolved_left, resolved_right))
} }

View File

@ -18,6 +18,3 @@
pub mod binary; pub mod binary;
pub use self::binary::*; pub use self::binary::*;
pub mod operand;
pub use self::operand::*;

View File

@ -1,43 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
//! Enforces one operand in a binary expression in a compiled Leo program.
use crate::{errors::ExpressionError, program::ConstrainedProgram, value::ConstrainedValue, GroupType};
use leo_asg::Expression;
use std::sync::Arc;
use snarkvm_models::{
curves::{Field, PrimeField},
gadgets::r1cs::ConstraintSystem,
};
impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
/// Enforce an operand of a binary expression.
/// We don't care about mutability because we are not changing any variables.
/// We try to resolve unresolved types here if the type is given explicitly.
pub fn enforce_operand<CS: ConstraintSystem<F>>(
&mut self,
cs: &mut CS,
expression: &Arc<Expression>,
) -> Result<ConstrainedValue<F, G>, ExpressionError> {
let mut branch = self.enforce_expression(cs, expression)?;
branch.get_inner_mut();
Ok(branch)
}
}

View File

@ -33,7 +33,7 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
) -> Result<ConstrainedValue<F, G>, ExpressionError> { ) -> Result<ConstrainedValue<F, G>, ExpressionError> {
if let Some(target) = &expr.target { if let Some(target) = &expr.target {
//todo: we can prob pass values by ref here to avoid copying the entire circuit on access //todo: we can prob pass values by ref here to avoid copying the entire circuit on access
let target_value = self.enforce_operand(cs, target)?; let target_value = self.enforce_expression(cs, target)?;
match target_value { match target_value {
ConstrainedValue::CircuitExpression(def, members) => { ConstrainedValue::CircuitExpression(def, members) => {
assert!(def.circuit == expr.circuit); assert!(def.circuit == expr.circuit);

View File

@ -41,9 +41,9 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
value => return Err(ExpressionError::conditional_boolean(value.to_string(), span.to_owned())), value => return Err(ExpressionError::conditional_boolean(value.to_string(), span.to_owned())),
}; };
let first_value = self.enforce_operand(cs, first)?; let first_value = self.enforce_expression(cs, first)?;
let second_value = self.enforce_operand(cs, second)?; let second_value = self.enforce_expression(cs, second)?;
let unique_namespace = cs.ns(|| { let unique_namespace = cs.ns(|| {
format!( format!(

View File

@ -92,7 +92,7 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
let resolved_inner = self.enforce_expression(cs, inner)?; let resolved_inner = self.enforce_expression(cs, inner)?;
enforce_negate(cs, resolved_inner, &span) enforce_negate(cs, resolved_inner, &span)
} }
UnaryOperation::Not => Ok(evaluate_not(self.enforce_operand(cs, inner)?, &span)?), UnaryOperation::Not => Ok(evaluate_not(self.enforce_expression(cs, inner)?, &span)?),
}, },
Expression::Ternary(TernaryExpression { Expression::Ternary(TernaryExpression {

View File

@ -35,7 +35,7 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
span: &Span, span: &Span,
) -> Result<ConstrainedValue<F, G>, ExpressionError> { ) -> Result<ConstrainedValue<F, G>, ExpressionError> {
// Get the tuple values. // Get the tuple values.
let tuple = match self.enforce_operand(cs, tuple)? { let tuple = match self.enforce_expression(cs, tuple)? {
ConstrainedValue::Tuple(tuple) => tuple, ConstrainedValue::Tuple(tuple) => tuple,
value => return Err(ExpressionError::undefined_array(value.to_string(), span.to_owned())), value => return Err(ExpressionError::undefined_array(value.to_string(), span.to_owned())),
}; };

View File

@ -61,13 +61,9 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
// Store input values as new variables in resolved program // Store input values as new variables in resolved program
for (variable, input_expression) in function.arguments.iter().zip(arguments.iter()) { for (variable, input_expression) in function.arguments.iter().zip(arguments.iter()) {
let mut input_value = self.enforce_expression(cs, input_expression)?; let input_value = self.enforce_expression(cs, input_expression)?;
let variable = variable.borrow(); let variable = variable.borrow();
if variable.mutable {
input_value = ConstrainedValue::Mutable(Box::new(input_value))
}
self.store(variable.id, input_value); self.store(variable.id, input_value);
} }

View File

@ -109,10 +109,7 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
let variable = variable.borrow(); let variable = variable.borrow();
let mut result = vec![match self.get_mut(&variable.id) { let mut result = vec![match self.get_mut(&variable.id) {
Some(value) => match value { Some(value) => value,
ConstrainedValue::Mutable(mutable) => &mut **mutable,
_ => return Err(StatementError::immutable_assign(variable.name.to_string(), span)),
},
None => return Err(StatementError::undefined_variable(variable.name.to_string(), span)), None => return Err(StatementError::undefined_variable(variable.name.to_string(), span)),
}]; }];

View File

@ -31,8 +31,7 @@ use snarkvm_models::{
pub struct Blake2s; pub struct Blake2s;
fn unwrap_argument<F: Field + PrimeField, G: GroupType<F>>(mut arg: ConstrainedValue<F, G>) -> Vec<UInt8> { fn unwrap_argument<F: Field + PrimeField, G: GroupType<F>>(arg: ConstrainedValue<F, G>) -> Vec<UInt8> {
arg.get_inner_mut();
if let ConstrainedValue::Array(args) = arg { if let ConstrainedValue::Array(args) = arg {
assert_eq!(args.len(), 32); // asg enforced assert_eq!(args.len(), 32); // asg enforced
args.into_iter() args.into_iter()

View File

@ -67,10 +67,7 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
let variable = assignee.target_variable.borrow(); let variable = assignee.target_variable.borrow();
let mut result = vec![match self.get_mut(&variable.id) { let mut result = vec![match self.get_mut(&variable.id) {
Some(value) => match value { Some(value) => value,
ConstrainedValue::Mutable(mutable) => &mut **mutable,
_ => return Err(StatementError::immutable_assign(variable.name.to_string(), span)),
},
None => return Err(StatementError::undefined_variable(variable.name.to_string(), span)), None => return Err(StatementError::undefined_variable(variable.name.to_string(), span)),
}]; }];
@ -101,14 +98,6 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
} }
} }
// discards unnecessary mutable wrappers
fn unwrap_mutable(input: &mut ConstrainedValue<F, G>) -> &mut ConstrainedValue<F, G> {
match input {
ConstrainedValue::Mutable(x) => Self::unwrap_mutable(&mut **x),
x => x,
}
}
// todo: this can prob have most of its error checking removed // todo: this can prob have most of its error checking removed
pub(crate) fn resolve_assignee_access<'a>( pub(crate) fn resolve_assignee_access<'a>(
access: ResolvedAssigneeAccess, access: ResolvedAssigneeAccess,
@ -120,7 +109,7 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
if value.len() != 1 { if value.len() != 1 {
return Err(StatementError::array_assign_interior_index(span.clone())); return Err(StatementError::array_assign_interior_index(span.clone()));
} }
match Self::unwrap_mutable(value.remove(0)) { match value.remove(0) {
ConstrainedValue::Array(old) => { ConstrainedValue::Array(old) => {
if index > old.len() { if index > old.len() {
Err(StatementError::array_assign_index_bounds( Err(StatementError::array_assign_index_bounds(
@ -140,7 +129,7 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
if value.len() == 1 { if value.len() == 1 {
// not a range of a range // not a range of a range
match Self::unwrap_mutable(value.remove(0)) { match value.remove(0) {
ConstrainedValue::Array(old) => { ConstrainedValue::Array(old) => {
let stop_index = stop_index.unwrap_or(old.len()); let stop_index = stop_index.unwrap_or(old.len());
Self::check_range_index(start_index, stop_index, old.len(), &span)?; Self::check_range_index(start_index, stop_index, old.len(), &span)?;
@ -154,14 +143,14 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
let stop_index = stop_index.unwrap_or(value.len()); let stop_index = stop_index.unwrap_or(value.len());
Self::check_range_index(start_index, stop_index, value.len(), &span)?; Self::check_range_index(start_index, stop_index, value.len(), &span)?;
Ok(value.drain(start_index..stop_index).map(Self::unwrap_mutable).collect()) Ok(value.drain(start_index..stop_index).collect())
} }
} }
ResolvedAssigneeAccess::Tuple(index, span) => { ResolvedAssigneeAccess::Tuple(index, span) => {
if value.len() != 1 { if value.len() != 1 {
return Err(StatementError::array_assign_interior_index(span)); return Err(StatementError::array_assign_interior_index(span));
} }
match Self::unwrap_mutable(value.remove(0)) { match value.remove(0) {
ConstrainedValue::Tuple(old) => { ConstrainedValue::Tuple(old) => {
if index > old.len() { if index > old.len() {
Err(StatementError::tuple_assign_index_bounds(index, old.len(), span)) Err(StatementError::tuple_assign_index_bounds(index, old.len(), span))
@ -176,7 +165,7 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
if value.len() != 1 { if value.len() != 1 {
return Err(StatementError::array_assign_interior_index(span.clone())); return Err(StatementError::array_assign_interior_index(span.clone()));
} }
match Self::unwrap_mutable(value.remove(0)) { match value.remove(0) {
ConstrainedValue::CircuitExpression(_variable, members) => { ConstrainedValue::CircuitExpression(_variable, members) => {
// Modify the circuit variable in place // Modify the circuit variable in place
let matched_variable = members.iter_mut().find(|member| member.0 == name); let matched_variable = members.iter_mut().find(|member| member.0 == name);

View File

@ -30,7 +30,7 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
cs: &mut CS, cs: &mut CS,
statement: &ReturnStatement, statement: &ReturnStatement,
) -> Result<ConstrainedValue<F, G>, StatementError> { ) -> Result<ConstrainedValue<F, G>, StatementError> {
let result = self.enforce_operand(cs, &statement.expression)?; let result = self.enforce_expression(cs, &statement.expression)?;
Ok(result) Ok(result)
} }
} }

View File

@ -49,9 +49,6 @@ pub enum ConstrainedValue<F: Field + PrimeField, G: GroupType<F>> {
// Circuits // Circuits
CircuitExpression(Arc<CircuitBody>, Vec<ConstrainedCircuitMember<F, G>>), CircuitExpression(Arc<CircuitBody>, Vec<ConstrainedCircuitMember<F, G>>),
// Modifiers
Mutable(Box<ConstrainedValue<F, G>>),
} }
impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedValue<F, G> { impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedValue<F, G> {
@ -81,22 +78,8 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedValue<F, G> {
Type::Tuple(types) Type::Tuple(types)
} }
ConstrainedValue::CircuitExpression(id, _members) => Type::Circuit(id.circuit.clone()), ConstrainedValue::CircuitExpression(id, _members) => Type::Circuit(id.circuit.clone()),
ConstrainedValue::Mutable(value) => return value.to_type(span),
}) })
} }
///
/// Modifies the `self` [ConstrainedValue] so there are no `mut` keywords wrapping the `self` value.
///
pub(crate) fn get_inner_mut(&mut self) {
if let ConstrainedValue::Mutable(inner) = self {
// Recursively remove `mut` keywords.
inner.get_inner_mut();
// Modify the value.
*self = *inner.clone()
}
}
} }
impl<F: Field + PrimeField, G: GroupType<F>> fmt::Display for ConstrainedValue<F, G> { impl<F: Field + PrimeField, G: GroupType<F>> fmt::Display for ConstrainedValue<F, G> {
@ -142,7 +125,6 @@ impl<F: Field + PrimeField, G: GroupType<F>> fmt::Display for ConstrainedValue<F
} }
write!(f, "}}") write!(f, "}}")
} }
ConstrainedValue::Mutable(ref value) => write!(f, "{}", value),
} }
} }
} }
@ -265,8 +247,6 @@ impl<F: Field + PrimeField, G: GroupType<F>> CondSelectGadget<F> for Constrained
ConstrainedValue::CircuitExpression(identifier.clone(), members) ConstrainedValue::CircuitExpression(identifier.clone(), members)
} }
(ConstrainedValue::Mutable(first), _) => Self::conditionally_select(cs, cond, first, second)?,
(_, ConstrainedValue::Mutable(second)) => Self::conditionally_select(cs, cond, first, second)?,
(_, _) => return Err(SynthesisError::Unsatisfiable), (_, _) => return Err(SynthesisError::Unsatisfiable),
}) })
} }

View File

@ -0,0 +1,6 @@
function main () {
let mut x = true;
if x {
let y = 0u8;
}
}

View File

@ -101,6 +101,14 @@ fn test_not_mutable() {
assert_satisfied(program); assert_satisfied(program);
} }
#[test]
fn test_conditional_mut() {
let program_string = include_str!("conditional_mut.leo");
let program = parse_program(program_string).unwrap();
assert_satisfied(program);
}
#[test] #[test]
fn test_not_u32() { fn test_not_u32() {
let program_string = include_str!("not_u32.leo"); let program_string = include_str!("not_u32.leo");