Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace toml_map_to_field and toml_remap with traits to map between InputValues and TomlTypes #677

Merged
merged 6 commits into from
Jan 31, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 10 additions & 0 deletions crates/iter-extended/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,13 @@ where
{
iterable.into_iter().map(f).collect()
}

/// Equivalent to .into_iter().map(f).collect::<Result<BTreeMap<_, _>,_>>()
pub fn try_btree_map<T, K, V, E, F>(iterable: T, f: F) -> Result<BTreeMap<K, V>, E>
where
T: IntoIterator,
K: std::cmp::Ord,
F: FnMut(T::Item) -> Result<(K, V), E>,
{
iterable.into_iter().map(f).collect()
}
1 change: 1 addition & 0 deletions crates/noirc_abi/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ edition.workspace = true

[dependencies]
acvm.workspace = true
iter-extended.workspace = true
toml.workspace = true
serde.workspace = true
serde_derive.workspace = true
Expand Down
190 changes: 80 additions & 110 deletions crates/noirc_abi/src/input_parser/toml.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use super::InputValue;
use crate::{errors::InputParserError, Abi, AbiType};
use acvm::FieldElement;
use iter_extended::{btree_map, try_btree_map, try_vecmap, vecmap};
use serde::Serialize;
use serde_derive::Deserialize;
use std::collections::BTreeMap;
Expand All @@ -9,7 +10,7 @@ pub(crate) fn parse_toml(
input_string: &str,
abi: Abi,
) -> Result<BTreeMap<String, InputValue>, InputParserError> {
// Parse input.toml into a BTreeMap, converting the argument to field elements
// Parse input.toml into a BTreeMap.
let data: BTreeMap<String, TomlTypes> = toml::from_str(input_string)?;

// The toml map is stored in an ordered BTreeMap. As the keys are strings the map is in alphanumerical order.
Expand All @@ -18,30 +19,22 @@ pub(crate) fn parse_toml(
// in the abi are already stored in a BTreeMap.
let abi_map = abi.to_btree_map();

let toml_map = toml_map_to_field(data, abi_map)?;
Ok(toml_map)
// Convert arguments to field elements.
try_btree_map(data, |(key, value)| {
InputValue::try_from_toml(value, &abi_map[&key]).map(|input_value| (key, input_value))
})
}

pub(crate) fn serialise_to_toml(
w_map: &BTreeMap<String, InputValue>,
) -> Result<String, InputParserError> {
let to_map = toml_remap(w_map);

// Toml requires that values be emitted before tables. Thus, we must reorder our map in case a TomlTypes::Table comes before any other values in the toml map
// BTreeMap orders by key and we need the name of the input as our key, so we must split our maps in case a table type has a name that is alphanumerically less
// than any other value type
let mut tables_map = BTreeMap::new();
let to_map: BTreeMap<String, TomlTypes> = to_map
.into_iter()
.filter(|(k, v)| {
if matches!(v, TomlTypes::Table(_)) {
tables_map.insert(k.clone(), v.clone());
false
} else {
true
}
})
.collect();
let (tables_map, to_map): (BTreeMap<String, TomlTypes>, BTreeMap<String, TomlTypes>) = w_map
.iter()
.map(|(key, value)| (key.to_owned(), TomlTypes::from(value.clone())))
.partition(|(_, v)| matches!(v, TomlTypes::Table(_)));

let mut toml_string = toml::to_string(&to_map)?;
let toml_string_tables = toml::to_string(&tables_map)?;
Expand All @@ -51,30 +44,63 @@ pub(crate) fn serialise_to_toml(
Ok(toml_string)
}

/// Converts the Toml mapping to the native representation that the compiler
/// understands for Inputs
fn toml_map_to_field(
toml_map: BTreeMap<String, TomlTypes>,
abi_map: BTreeMap<String, AbiType>,
) -> Result<BTreeMap<String, InputValue>, InputParserError> {
let mut field_map = BTreeMap::new();
for (parameter, value) in toml_map {
let mapped_value = match value {
TomlTypes::String(string) => {
let param_type = abi_map.get(&parameter).unwrap();
match param_type {
AbiType::String { .. } => InputValue::String(string),
AbiType::Field | AbiType::Integer { .. } => {
let new_value = parse_str_to_field(&string)?;
if let Some(field_element) = new_value {
InputValue::Field(field_element)
} else {
InputValue::Undefined
}
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(untagged)]
enum TomlTypes {
// This is most likely going to be a hex string
// But it is possible to support UTF-8
String(String),
// Just a regular integer, that can fit in 128 bits
Integer(u64),
// Simple boolean flag
Bool(bool),
// Array of regular integers
ArrayNum(Vec<u64>),
// Array of hexadecimal integers
ArrayString(Vec<String>),
// Struct of TomlTypes
Table(BTreeMap<String, TomlTypes>),
}

impl From<InputValue> for TomlTypes {
fn from(value: InputValue) -> Self {
match value {
InputValue::Field(f) => {
let f_str = format!("0x{}", f.to_hex());
TomlTypes::String(f_str)
}
InputValue::Vec(v) => {
let array = v.iter().map(|i| format!("0x{}", i.to_hex())).collect();
TomlTypes::ArrayString(array)
}
InputValue::String(s) => TomlTypes::String(s),
InputValue::Struct(map) => {
let map_with_toml_types =
btree_map(map, |(key, value)| (key, TomlTypes::from(value)));
TomlTypes::Table(map_with_toml_types)
}
InputValue::Undefined => unreachable!(),
}
}
}

impl InputValue {
fn try_from_toml(
value: TomlTypes,
param_type: &AbiType,
) -> Result<InputValue, InputParserError> {
let input_value = match value {
TomlTypes::String(string) => match param_type {
AbiType::String { .. } => InputValue::String(string),
AbiType::Field | AbiType::Integer { .. } => {
if string.is_empty() {
InputValue::Undefined
} else {
InputValue::Field(parse_str_to_field(&string)?)
}
_ => return Err(InputParserError::AbiTypeMismatch(param_type.clone())),
}
}
_ => return Err(InputParserError::AbiTypeMismatch(param_type.clone())),
},
TomlTypes::Integer(integer) => {
let new_value = FieldElement::from(i128::from(integer));

Expand All @@ -86,97 +112,41 @@ fn toml_map_to_field(
InputValue::Field(new_value)
}
TomlTypes::ArrayNum(arr_num) => {
let array_elements: Vec<_> = arr_num
.into_iter()
.map(|elem_num| FieldElement::from(i128::from(elem_num)))
.collect();
let array_elements =
vecmap(arr_num, |elem_num| FieldElement::from(i128::from(elem_num)));

InputValue::Vec(array_elements)
}
TomlTypes::ArrayString(arr_str) => {
let array_elements: Vec<_> = arr_str
.into_iter()
.map(|elem_str| parse_str_to_field(&elem_str).unwrap().unwrap())
.collect();
let array_elements = try_vecmap(arr_str, |elem_str| parse_str_to_field(&elem_str))?;

InputValue::Vec(array_elements)
}
TomlTypes::Table(table) => {
let param_type = abi_map.get(&parameter).unwrap();
let fields = match param_type {
AbiType::Struct { fields } => fields.clone(),
AbiType::Struct { fields } => fields,
_ => return Err(InputParserError::AbiTypeMismatch(param_type.clone())),
};
let native_table = toml_map_to_field(table, fields)?;
let native_table = try_btree_map(table, |(key, value)| {
InputValue::try_from_toml(value, &fields[&key])
.map(|input_value| (key, input_value))
})?;

InputValue::Struct(native_table)
}
};

if field_map.insert(parameter.clone(), mapped_value).is_some() {
return Err(InputParserError::DuplicateVariableName(parameter));
};
}

Ok(field_map)
}

fn toml_remap(map: &BTreeMap<String, InputValue>) -> BTreeMap<String, TomlTypes> {
let mut toml_map = BTreeMap::new();
for (parameter, value) in map {
let mapped_value = match value {
InputValue::Field(f) => {
let f_str = format!("0x{}", f.to_hex());
TomlTypes::String(f_str)
}
InputValue::Vec(v) => {
let array = v.iter().map(|i| format!("0x{}", i.to_hex())).collect();
TomlTypes::ArrayString(array)
}
InputValue::String(s) => TomlTypes::String(s.clone()),
InputValue::Struct(map) => {
let map_with_toml_types = toml_remap(map);
TomlTypes::Table(map_with_toml_types)
}
InputValue::Undefined => unreachable!(),
};
toml_map.insert(parameter.clone(), mapped_value);
Ok(input_value)
}
toml_map
}

#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(untagged)]
enum TomlTypes {
// This is most likely going to be a hex string
// But it is possible to support UTF-8
String(String),
// Just a regular integer, that can fit in 128 bits
Integer(u64),
// Simple boolean flag
Bool(bool),
// Array of regular integers
ArrayNum(Vec<u64>),
// Array of hexadecimal integers
ArrayString(Vec<String>),
// Struct of TomlTypes
Table(BTreeMap<String, TomlTypes>),
}

fn parse_str_to_field(value: &str) -> Result<Option<FieldElement>, InputParserError> {
if value.is_empty() {
Ok(None)
} else if value.starts_with("0x") {
let result = FieldElement::from_hex(value);
if result.is_some() {
Ok(result)
} else {
Err(InputParserError::ParseHexStr(value.to_owned()))
}
fn parse_str_to_field(value: &str) -> Result<FieldElement, InputParserError> {
if value.starts_with("0x") {
FieldElement::from_hex(value).ok_or_else(|| InputParserError::ParseHexStr(value.to_owned()))
} else {
let val: i128 = value
value
.parse::<i128>()
.map_err(|err_msg| InputParserError::ParseStr(err_msg.to_string()))?;
Ok(Some(FieldElement::from(val)))
.map_err(|err_msg| InputParserError::ParseStr(err_msg.to_string()))
.map(FieldElement::from)
}
}