fix negative fields, add test for them

This commit is contained in:
gluax 2021-02-12 15:20:58 -05:00
parent 217ecca4d6
commit 500a3e76d2
6 changed files with 45 additions and 1 deletions

View File

@ -40,6 +40,8 @@ use snarkvm_models::{
use std::{borrow::Borrow, cmp::Ordering};
#[derive(Clone, Debug)]
// Isn't this redudant?
// PrimeField already implements Field.
pub enum FieldType<F: Field + PrimeField> {
Constant(F),
Allocated(FpGadget<F>),
@ -54,7 +56,22 @@ impl<F: Field + PrimeField> FieldType<F> {
}
pub fn constant(string: String, span: &Span) -> Result<Self, FieldError> {
let value = F::from_str(&string).map_err(|_| FieldError::invalid_field(string, span.to_owned()))?;
let first_char = string.chars().next().unwrap();
let new_string: &str;
let value;
// Check if first symbol is a negative.
// If so strip it, parse rest of string and then negate it.
if first_char == '-' {
new_string = string
.chars()
.next()
.map(|c| &string[c.len_utf8()..])
.ok_or(FieldError::invalid_field(string.clone(), span.to_owned()))?;
value = -F::from_str(&new_string).map_err(|_| FieldError::invalid_field(string, span.to_owned()))?;
} else {
value = F::from_str(&string).map_err(|_| FieldError::invalid_field(string, span.to_owned()))?;
}
Ok(FieldType::Constant(value))
}

View File

@ -66,6 +66,14 @@ fn test_negate() {
}
}
#[test]
fn test_negative_declaration() {
let program_string = include_str!("negative_declaration.leo");
let mut program = parse_program(program_string).unwrap();
assert_satisfied(program)
}
#[test]
fn test_add() {
use std::ops::Add;

View File

@ -0,0 +1,3 @@
function main() {
let negOneField: field = -1field;
}

View File

@ -0,0 +1,2 @@
[main]
a: field = 1;

View File

@ -0,0 +1,4 @@
function main(a: field) {
// Change to assert when == is implemented for field.
console.log("a: {}", a);
}

View File

@ -93,3 +93,13 @@ fn test_input_array_dimensions_mismatch() {
expect_fail(program);
}
#[test]
fn test_field_input() {
let program_string = include_str!("main_field.leo");
let input_string = include_str!("input/main_field.in");
let program = parse_program_with_input(program_string, input_string).unwrap();
assert_satisfied(program);
}