1
0
Fork 0
mirror of synced 2025-09-24 04:40:05 +00:00

remove strict ordering of declarations, refactor import logic

This commit is contained in:
dark64 2021-05-12 20:03:08 +02:00
parent d4494cb9c2
commit 5539edc16b
45 changed files with 988 additions and 1293 deletions

View file

@ -1,66 +1,68 @@
use crate::absy; use crate::absy;
use crate::imports;
use crate::absy::SymbolDefinition;
use num_bigint::BigUint; use num_bigint::BigUint;
use std::path::Path;
use zokrates_pest_ast as pest; use zokrates_pest_ast as pest;
impl<'ast> From<pest::File<'ast>> for absy::Module<'ast> { impl<'ast> From<pest::File<'ast>> for absy::Module<'ast> {
fn from(prog: pest::File<'ast>) -> absy::Module<'ast> { fn from(file: pest::File<'ast>) -> absy::Module<'ast> {
absy::Module::with_symbols( absy::Module::with_symbols(file.declarations.into_iter().map(|d| match d {
prog.structs pest::SymbolDeclaration::Import(i) => i.into(),
.into_iter() pest::SymbolDeclaration::Constant(c) => c.into(),
.map(absy::SymbolDeclarationNode::from) pest::SymbolDeclaration::Struct(s) => s.into(),
.chain( pest::SymbolDeclaration::Function(f) => f.into(),
prog.constants }))
.into_iter()
.map(absy::SymbolDeclarationNode::from),
)
.chain(
prog.functions
.into_iter()
.map(absy::SymbolDeclarationNode::from),
),
)
.imports(
prog.imports
.into_iter()
.map(absy::ImportDirective::from)
.flatten(),
)
} }
} }
impl<'ast> From<pest::ImportDirective<'ast>> for absy::ImportDirective<'ast> { impl<'ast> From<pest::ImportDirective<'ast>> for absy::SymbolDeclarationNode<'ast> {
fn from(import: pest::ImportDirective<'ast>) -> absy::ImportDirective<'ast> { fn from(import: pest::ImportDirective<'ast>) -> absy::SymbolDeclarationNode<'ast> {
use crate::absy::NodeValue; use crate::absy::NodeValue;
match import { match import {
pest::ImportDirective::Main(import) => absy::ImportDirective::Main( pest::ImportDirective::Main(import) => {
imports::Import::new(None, std::path::Path::new(import.source.span.as_str())) let span = import.span;
.alias(import.alias.map(|a| a.span.as_str())) let source = Path::new(import.source.span.as_str());
.span(import.span),
), let import = absy::MainImport {
pest::ImportDirective::From(import) => absy::ImportDirective::From( source,
import alias: import.alias.map(|a| a.span.as_str()),
.symbols }
.iter() .span(span.clone());
.map(|symbol| {
imports::Import::new( absy::SymbolDeclaration {
Some(symbol.symbol.span.as_str()), id: None,
std::path::Path::new(import.source.span.as_str()), symbol: absy::Symbol::Here(absy::SymbolDefinition::Import(
) absy::ImportDirective::Main(import),
.alias( )),
symbol }
.alias .span(span)
.as_ref() }
.map(|a| a.span.as_str()) pest::ImportDirective::From(import) => {
.or_else(|| Some(symbol.symbol.span.as_str())), let span = import.span;
) let source = Path::new(import.source.span.as_str());
.span(symbol.span.clone())
}) let import = absy::FromImport {
.collect(), source,
), symbols: import
.symbols
.into_iter()
.map(|symbol| absy::SymbolIdentifier {
id: symbol.id.span.as_str(),
alias: symbol.alias.map(|a| a.span.as_str()),
})
.collect(),
}
.span(span.clone());
absy::SymbolDeclaration {
id: None,
symbol: absy::Symbol::Here(absy::SymbolDefinition::Import(
absy::ImportDirective::From(import),
)),
}
.span(span)
}
} }
} }
} }
@ -83,8 +85,8 @@ impl<'ast> From<pest::StructDefinition<'ast>> for absy::SymbolDeclarationNode<'a
.span(span.clone()); .span(span.clone());
absy::SymbolDeclaration { absy::SymbolDeclaration {
id, id: Some(id),
symbol: absy::Symbol::Here(SymbolDefinition::Struct(ty)), symbol: absy::Symbol::Here(absy::SymbolDefinition::Struct(ty)),
} }
.span(span) .span(span)
} }
@ -118,15 +120,15 @@ impl<'ast> From<pest::ConstantDefinition<'ast>> for absy::SymbolDeclarationNode<
.span(span.clone()); .span(span.clone());
absy::SymbolDeclaration { absy::SymbolDeclaration {
id, id: Some(id),
symbol: absy::Symbol::Here(SymbolDefinition::Constant(ty)), symbol: absy::Symbol::Here(absy::SymbolDefinition::Constant(ty)),
} }
.span(span) .span(span)
} }
} }
impl<'ast> From<pest::Function<'ast>> for absy::SymbolDeclarationNode<'ast> { impl<'ast> From<pest::FunctionDefinition<'ast>> for absy::SymbolDeclarationNode<'ast> {
fn from(function: pest::Function<'ast>) -> absy::SymbolDeclarationNode<'ast> { fn from(function: pest::FunctionDefinition<'ast>) -> absy::SymbolDeclarationNode<'ast> {
use crate::absy::NodeValue; use crate::absy::NodeValue;
let span = function.span; let span = function.span;
@ -174,8 +176,8 @@ impl<'ast> From<pest::Function<'ast>> for absy::SymbolDeclarationNode<'ast> {
.span(span.clone()); .span(span.clone());
absy::SymbolDeclaration { absy::SymbolDeclaration {
id, id: Some(id),
symbol: absy::Symbol::Here(SymbolDefinition::Function(function)), symbol: absy::Symbol::Here(absy::SymbolDefinition::Function(function)),
} }
.span(span) .span(span)
} }
@ -780,8 +782,8 @@ mod tests {
let ast = pest::generate_ast(&source).unwrap(); let ast = pest::generate_ast(&source).unwrap();
let expected: absy::Module = absy::Module { let expected: absy::Module = absy::Module {
symbols: vec![absy::SymbolDeclaration { symbols: vec![absy::SymbolDeclaration {
id: &source[4..8], id: Some(&source[4..8]),
symbol: absy::Symbol::Here(SymbolDefinition::Function( symbol: absy::Symbol::Here(absy::SymbolDefinition::Function(
absy::Function { absy::Function {
arguments: vec![], arguments: vec![],
statements: vec![absy::Statement::Return( statements: vec![absy::Statement::Return(
@ -801,7 +803,6 @@ mod tests {
)), )),
} }
.into()], .into()],
imports: vec![],
}; };
assert_eq!(absy::Module::from(ast), expected); assert_eq!(absy::Module::from(ast), expected);
} }
@ -812,8 +813,8 @@ mod tests {
let ast = pest::generate_ast(&source).unwrap(); let ast = pest::generate_ast(&source).unwrap();
let expected: absy::Module = absy::Module { let expected: absy::Module = absy::Module {
symbols: vec![absy::SymbolDeclaration { symbols: vec![absy::SymbolDeclaration {
id: &source[4..8], id: Some(&source[4..8]),
symbol: absy::Symbol::Here(SymbolDefinition::Function( symbol: absy::Symbol::Here(absy::SymbolDefinition::Function(
absy::Function { absy::Function {
arguments: vec![], arguments: vec![],
statements: vec![absy::Statement::Return( statements: vec![absy::Statement::Return(
@ -831,7 +832,6 @@ mod tests {
)), )),
} }
.into()], .into()],
imports: vec![],
}; };
assert_eq!(absy::Module::from(ast), expected); assert_eq!(absy::Module::from(ast), expected);
} }
@ -843,8 +843,8 @@ mod tests {
let expected: absy::Module = absy::Module { let expected: absy::Module = absy::Module {
symbols: vec![absy::SymbolDeclaration { symbols: vec![absy::SymbolDeclaration {
id: &source[4..8], id: Some(&source[4..8]),
symbol: absy::Symbol::Here(SymbolDefinition::Function( symbol: absy::Symbol::Here(absy::SymbolDefinition::Function(
absy::Function { absy::Function {
arguments: vec![ arguments: vec![
absy::Parameter::private( absy::Parameter::private(
@ -884,7 +884,6 @@ mod tests {
)), )),
} }
.into()], .into()],
imports: vec![],
}; };
assert_eq!(absy::Module::from(ast), expected); assert_eq!(absy::Module::from(ast), expected);
@ -897,8 +896,8 @@ mod tests {
fn wrap(ty: UnresolvedType<'static>) -> absy::Module<'static> { fn wrap(ty: UnresolvedType<'static>) -> absy::Module<'static> {
absy::Module { absy::Module {
symbols: vec![absy::SymbolDeclaration { symbols: vec![absy::SymbolDeclaration {
id: "main", id: Some("main"),
symbol: absy::Symbol::Here(SymbolDefinition::Function( symbol: absy::Symbol::Here(absy::SymbolDefinition::Function(
absy::Function { absy::Function {
arguments: vec![absy::Parameter::private( arguments: vec![absy::Parameter::private(
absy::Variable::new("a", ty.clone().mock()).into(), absy::Variable::new("a", ty.clone().mock()).into(),
@ -917,7 +916,6 @@ mod tests {
)), )),
} }
.into()], .into()],
imports: vec![],
} }
} }
@ -971,8 +969,8 @@ mod tests {
fn wrap(expression: absy::Expression<'static>) -> absy::Module { fn wrap(expression: absy::Expression<'static>) -> absy::Module {
absy::Module { absy::Module {
symbols: vec![absy::SymbolDeclaration { symbols: vec![absy::SymbolDeclaration {
id: "main", id: Some("main"),
symbol: absy::Symbol::Here(SymbolDefinition::Function( symbol: absy::Symbol::Here(absy::SymbolDefinition::Function(
absy::Function { absy::Function {
arguments: vec![], arguments: vec![],
statements: vec![absy::Statement::Return( statements: vec![absy::Statement::Return(
@ -988,7 +986,6 @@ mod tests {
)), )),
} }
.into()], .into()],
imports: vec![],
} }
} }

View file

@ -18,8 +18,6 @@ pub use crate::absy::variable::{Variable, VariableNode};
use crate::embed::FlatEmbed; use crate::embed::FlatEmbed;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use crate::imports::ImportDirective;
use crate::imports::ImportNode;
use std::fmt; use std::fmt;
use num_bigint::BigUint; use num_bigint::BigUint;
@ -44,63 +42,173 @@ pub struct Program<'ast> {
pub main: OwnedModuleId, pub main: OwnedModuleId,
} }
/// A declaration of a `FunctionSymbol`, be it from an import or a function definition #[derive(Debug, PartialEq, Clone)]
#[derive(PartialEq, Clone, Debug)] pub struct SymbolIdentifier<'ast> {
pub struct SymbolDeclaration<'ast> {
pub id: Identifier<'ast>, pub id: Identifier<'ast>,
pub alias: Option<Identifier<'ast>>,
}
impl<'ast> From<Identifier<'ast>> for SymbolIdentifier<'ast> {
fn from(id: &'ast str) -> Self {
SymbolIdentifier { id, alias: None }
}
}
impl<'ast> SymbolIdentifier<'ast> {
pub fn alias(mut self, alias: Option<Identifier<'ast>>) -> Self {
self.alias = alias;
self
}
pub fn get_alias(&self) -> Identifier<'ast> {
self.alias.unwrap_or(self.id)
}
}
impl<'ast> fmt::Display for SymbolIdentifier<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{}{}",
self.id,
self.alias.map(|a| format!(" as {}", a)).unwrap_or_default()
)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct MainImport<'ast> {
pub source: &'ast Path,
pub alias: Option<Identifier<'ast>>,
}
pub type MainImportNode<'ast> = Node<MainImport<'ast>>;
impl<'ast> fmt::Display for MainImport<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.alias {
Some(ref alias) => write!(f, "import \"{}\" as {}", self.source.display(), alias),
None => write!(f, "import \"{}\"", self.source.display()),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct FromImport<'ast> {
pub source: &'ast Path,
pub symbols: Vec<SymbolIdentifier<'ast>>,
}
pub type FromImportNode<'ast> = Node<FromImport<'ast>>;
impl<'ast> fmt::Display for FromImport<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"from \"{}\" import {}",
self.source.display(),
self.symbols
.iter()
.map(|s| s.to_string())
.collect::<Vec<_>>()
.join(", ")
)
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum ImportDirective<'ast> {
Main(MainImportNode<'ast>),
From(FromImportNode<'ast>),
}
impl<'ast> fmt::Display for ImportDirective<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ImportDirective::Main(main) => write!(f, "{}", main),
ImportDirective::From(from) => write!(f, "{}", from),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct SymbolImport<'ast> {
pub module_id: OwnedModuleId,
pub symbol_id: SymbolIdentifier<'ast>,
}
pub type SymbolImportNode<'ast> = Node<SymbolImport<'ast>>;
impl<'ast> SymbolImport<'ast> {
pub fn with_id_in_module<S: Into<SymbolIdentifier<'ast>>, U: Into<OwnedModuleId>>(
symbol_id: S,
module_id: U,
) -> Self {
SymbolImport {
symbol_id: symbol_id.into(),
module_id: module_id.into(),
}
}
}
impl<'ast> fmt::Display for SymbolImport<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"from \"{}\" import {}",
self.module_id.display(),
self.symbol_id
)
}
}
/// A declaration of a symbol
#[derive(Debug, PartialEq, Clone)]
pub struct SymbolDeclaration<'ast> {
pub id: Option<Identifier<'ast>>,
pub symbol: Symbol<'ast>, pub symbol: Symbol<'ast>,
} }
#[allow(clippy::large_enum_variant)] #[allow(clippy::large_enum_variant)]
#[derive(PartialEq, Clone)] #[derive(Debug, PartialEq, Clone)]
pub enum SymbolDefinition<'ast> { pub enum SymbolDefinition<'ast> {
Import(ImportDirective<'ast>),
Struct(StructDefinitionNode<'ast>), Struct(StructDefinitionNode<'ast>),
Constant(ConstantDefinitionNode<'ast>), Constant(ConstantDefinitionNode<'ast>),
Function(FunctionNode<'ast>), Function(FunctionNode<'ast>),
} }
impl<'ast> fmt::Debug for SymbolDefinition<'ast> { #[derive(Debug, PartialEq, Clone)]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
SymbolDefinition::Struct(s) => write!(f, "Struct({:?})", s),
SymbolDefinition::Constant(c) => write!(f, "Constant({:?})", c),
SymbolDefinition::Function(func) => write!(f, "Function({:?})", func),
}
}
}
#[derive(PartialEq, Clone)]
pub enum Symbol<'ast> { pub enum Symbol<'ast> {
Here(SymbolDefinition<'ast>), Here(SymbolDefinition<'ast>),
There(SymbolImportNode<'ast>), There(SymbolImportNode<'ast>),
Flat(FlatEmbed), Flat(FlatEmbed),
} }
impl<'ast> fmt::Debug for Symbol<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Symbol::Here(k) => write!(f, "Here({:?})", k),
Symbol::There(i) => write!(f, "There({:?})", i),
Symbol::Flat(flat) => write!(f, "Flat({:?})", flat),
}
}
}
impl<'ast> fmt::Display for SymbolDeclaration<'ast> { impl<'ast> fmt::Display for SymbolDeclaration<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.symbol { match &self.symbol {
Symbol::Here(ref kind) => match kind { Symbol::Here(ref symbol) => match symbol {
SymbolDefinition::Struct(t) => write!(f, "struct {} {}", self.id, t), SymbolDefinition::Import(ref i) => write!(f, "{}", i),
SymbolDefinition::Constant(c) => write!( SymbolDefinition::Struct(ref t) => write!(f, "struct {} {}", self.id.unwrap(), t),
SymbolDefinition::Constant(ref c) => write!(
f, f,
"const {} {} = {}", "const {} {} = {}",
c.value.ty, self.id, c.value.expression c.value.ty,
self.id.unwrap(),
c.value.expression
), ),
SymbolDefinition::Function(func) => write!(f, "def {}{}", self.id, func), SymbolDefinition::Function(ref func) => {
write!(f, "def {}{}", self.id.unwrap(), func)
}
}, },
Symbol::There(ref import) => write!(f, "import {} as {}", import, self.id), Symbol::There(ref i) => write!(f, "{}", i),
Symbol::Flat(ref flat_fun) => { Symbol::Flat(ref flat_fun) => {
write!(f, "def {}{}:\n\t// hidden", self.id, flat_fun.signature()) write!(
f,
"def {}{}:\n\t// hidden",
self.id.unwrap(),
flat_fun.signature()
)
} }
} }
} }
@ -109,25 +217,18 @@ impl<'ast> fmt::Display for SymbolDeclaration<'ast> {
pub type SymbolDeclarationNode<'ast> = Node<SymbolDeclaration<'ast>>; pub type SymbolDeclarationNode<'ast> = Node<SymbolDeclaration<'ast>>;
/// A module as a collection of `FunctionDeclaration`s /// A module as a collection of `FunctionDeclaration`s
#[derive(Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub struct Module<'ast> { pub struct Module<'ast> {
/// Symbols of the module /// Symbols of the module
pub symbols: Declarations<'ast>, pub symbols: Declarations<'ast>,
pub imports: Vec<ImportNode<'ast>>, // we still use `imports` as they are not directly converted into `FunctionDeclaration`s after the importer is done, `imports` is empty
} }
impl<'ast> Module<'ast> { impl<'ast> Module<'ast> {
pub fn with_symbols<I: IntoIterator<Item = SymbolDeclarationNode<'ast>>>(i: I) -> Self { pub fn with_symbols<I: IntoIterator<Item = SymbolDeclarationNode<'ast>>>(i: I) -> Self {
Module { Module {
symbols: i.into_iter().collect(), symbols: i.into_iter().collect(),
imports: vec![],
} }
} }
pub fn imports<I: IntoIterator<Item = ImportNode<'ast>>>(mut self, i: I) -> Self {
self.imports = i.into_iter().collect();
self
}
} }
pub type UnresolvedTypeNode<'ast> = Node<UnresolvedType<'ast>>; pub type UnresolvedTypeNode<'ast> = Node<UnresolvedType<'ast>>;
@ -169,7 +270,7 @@ impl<'ast> fmt::Display for StructDefinitionField<'ast> {
type StructDefinitionFieldNode<'ast> = Node<StructDefinitionField<'ast>>; type StructDefinitionFieldNode<'ast> = Node<StructDefinitionField<'ast>>;
#[derive(Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub struct ConstantDefinition<'ast> { pub struct ConstantDefinition<'ast> {
pub ty: UnresolvedTypeNode<'ast>, pub ty: UnresolvedTypeNode<'ast>,
pub expression: ExpressionNode<'ast>, pub expression: ExpressionNode<'ast>,
@ -183,92 +284,55 @@ impl<'ast> fmt::Display for ConstantDefinition<'ast> {
} }
} }
impl<'ast> fmt::Debug for ConstantDefinition<'ast> { // /// An import
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // #[derive(Debug, Clone, PartialEq)]
write!( // pub struct SymbolImport<'ast> {
f, // /// the id of the symbol in the target module. Note: there may be many candidates as imports statements do not specify the signature. In that case they must all be functions however.
"ConstantDefinition({:?}, {:?})", // pub symbol_id: Identifier<'ast>,
self.ty, self.expression // /// the id of the module to import from
) // pub module_id: OwnedModuleId,
} // }
} //
// type SymbolImportNode<'ast> = Node<SymbolImport<'ast>>;
/// An import //
#[derive(Debug, Clone, PartialEq)] // impl<'ast> SymbolImport<'ast> {
pub struct SymbolImport<'ast> { // pub fn with_id_in_module<S: Into<Identifier<'ast>>, U: Into<OwnedModuleId>>(
/// the id of the symbol in the target module. Note: there may be many candidates as imports statements do not specify the signature. In that case they must all be functions however. // symbol_id: S,
pub symbol_id: Identifier<'ast>, // module_id: U,
/// the id of the module to import from // ) -> Self {
pub module_id: OwnedModuleId, // SymbolImport {
} // symbol_id: symbol_id.into(),
// module_id: module_id.into(),
type SymbolImportNode<'ast> = Node<SymbolImport<'ast>>; // }
// }
impl<'ast> SymbolImport<'ast> { // }
pub fn with_id_in_module<S: Into<Identifier<'ast>>, U: Into<OwnedModuleId>>( //
symbol_id: S, // impl<'ast> fmt::Display for SymbolImport<'ast> {
module_id: U, // fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
) -> Self { // write!(
SymbolImport { // f,
symbol_id: symbol_id.into(), // "from {} import {}",
module_id: module_id.into(), // self.module_id.display().to_string(),
} // self.symbol_id,
} // )
} // }
// }
impl<'ast> fmt::Display for SymbolImport<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{} from {}",
self.symbol_id,
self.module_id.display().to_string()
)
}
}
impl<'ast> fmt::Display for Module<'ast> { impl<'ast> fmt::Display for Module<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut res = vec![]; let res = self
res.extend( .symbols
self.imports .iter()
.iter() .map(|x| format!("{}", x))
.map(|x| format!("{}", x)) .collect::<Vec<_>>();
.collect::<Vec<_>>(),
);
res.extend(
self.symbols
.iter()
.map(|x| format!("{}", x))
.collect::<Vec<_>>(),
);
write!(f, "{}", res.join("\n")) write!(f, "{}", res.join("\n"))
} }
} }
impl<'ast> fmt::Debug for Module<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"module(\n\timports:\n\t\t{}\n\tsymbols:\n\t\t{}\n)",
self.imports
.iter()
.map(|x| format!("{:?}", x))
.collect::<Vec<_>>()
.join("\n\t\t"),
self.symbols
.iter()
.map(|x| format!("{:?}", x))
.collect::<Vec<_>>()
.join("\n\t\t")
)
}
}
pub type ConstantGenericNode<'ast> = Node<Identifier<'ast>>; pub type ConstantGenericNode<'ast> = Node<Identifier<'ast>>;
/// A function defined locally /// A function defined locally
#[derive(Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub struct Function<'ast> { pub struct Function<'ast> {
/// Arguments of the function /// Arguments of the function
pub arguments: Vec<ParameterNode<'ast>>, pub arguments: Vec<ParameterNode<'ast>>,
@ -312,23 +376,8 @@ impl<'ast> fmt::Display for Function<'ast> {
} }
} }
impl<'ast> fmt::Debug for Function<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"Function(arguments: {:?}, ...):\n{}",
self.arguments,
self.statements
.iter()
.map(|x| format!("\t{:?}", x))
.collect::<Vec<_>>()
.join("\n")
)
}
}
/// Something that we can assign to /// Something that we can assign to
#[derive(Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub enum Assignee<'ast> { pub enum Assignee<'ast> {
Identifier(Identifier<'ast>), Identifier(Identifier<'ast>),
Select(Box<AssigneeNode<'ast>>, Box<RangeOrExpression<'ast>>), Select(Box<AssigneeNode<'ast>>, Box<RangeOrExpression<'ast>>),
@ -337,16 +386,6 @@ pub enum Assignee<'ast> {
pub type AssigneeNode<'ast> = Node<Assignee<'ast>>; pub type AssigneeNode<'ast> = Node<Assignee<'ast>>;
impl<'ast> fmt::Debug for Assignee<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Assignee::Identifier(ref s) => write!(f, "Identifier({:?})", s),
Assignee::Select(ref a, ref e) => write!(f, "Select({:?}[{:?}])", a, e),
Assignee::Member(ref s, ref m) => write!(f, "Member({:?}.{:?})", s, m),
}
}
}
impl<'ast> fmt::Display for Assignee<'ast> { impl<'ast> fmt::Display for Assignee<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self { match *self {
@ -359,7 +398,7 @@ impl<'ast> fmt::Display for Assignee<'ast> {
/// A statement in a `Function` /// A statement in a `Function`
#[allow(clippy::large_enum_variant)] #[allow(clippy::large_enum_variant)]
#[derive(Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub enum Statement<'ast> { pub enum Statement<'ast> {
Return(ExpressionListNode<'ast>), Return(ExpressionListNode<'ast>),
Declaration(VariableNode<'ast>), Declaration(VariableNode<'ast>),
@ -403,31 +442,8 @@ impl<'ast> fmt::Display for Statement<'ast> {
} }
} }
impl<'ast> fmt::Debug for Statement<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Statement::Return(ref expr) => write!(f, "Return({:?})", expr),
Statement::Declaration(ref var) => write!(f, "Declaration({:?})", var),
Statement::Definition(ref lhs, ref rhs) => {
write!(f, "Definition({:?}, {:?})", lhs, rhs)
}
Statement::Assertion(ref e) => write!(f, "Assertion({:?})", e),
Statement::For(ref var, ref start, ref stop, ref list) => {
writeln!(f, "for {:?} in {:?}..{:?} do", var, start, stop)?;
for l in list {
writeln!(f, "\t\t{:?}", l)?;
}
write!(f, "\tendfor")
}
Statement::MultipleDefinition(ref lhs, ref rhs) => {
write!(f, "MultipleDefinition({:?}, {:?})", lhs, rhs)
}
}
}
}
/// An element of an inline array, can be a spread `...a` or an expression `a` /// An element of an inline array, can be a spread `...a` or an expression `a`
#[derive(Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub enum SpreadOrExpression<'ast> { pub enum SpreadOrExpression<'ast> {
Spread(SpreadNode<'ast>), Spread(SpreadNode<'ast>),
Expression(ExpressionNode<'ast>), Expression(ExpressionNode<'ast>),
@ -448,17 +464,8 @@ impl<'ast> fmt::Display for SpreadOrExpression<'ast> {
} }
} }
impl<'ast> fmt::Debug for SpreadOrExpression<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
SpreadOrExpression::Spread(ref s) => write!(f, "{:?}", s),
SpreadOrExpression::Expression(ref e) => write!(f, "{:?}", e),
}
}
}
/// The index in an array selector. Can be a range or an expression. /// The index in an array selector. Can be a range or an expression.
#[derive(Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub enum RangeOrExpression<'ast> { pub enum RangeOrExpression<'ast> {
Range(RangeNode<'ast>), Range(RangeNode<'ast>),
Expression(ExpressionNode<'ast>), Expression(ExpressionNode<'ast>),
@ -473,13 +480,10 @@ impl<'ast> fmt::Display for RangeOrExpression<'ast> {
} }
} }
impl<'ast> fmt::Debug for RangeOrExpression<'ast> { /// A spread
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { #[derive(Debug, Clone, PartialEq)]
match *self { pub struct Spread<'ast> {
RangeOrExpression::Range(ref s) => write!(f, "{:?}", s), pub expression: ExpressionNode<'ast>,
RangeOrExpression::Expression(ref e) => write!(f, "{:?}", e),
}
}
} }
pub type SpreadNode<'ast> = Node<Spread<'ast>>; pub type SpreadNode<'ast> = Node<Spread<'ast>>;
@ -490,20 +494,8 @@ impl<'ast> fmt::Display for Spread<'ast> {
} }
} }
impl<'ast> fmt::Debug for Spread<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Spread({:?})", self.expression)
}
}
/// A spread
#[derive(Clone, PartialEq)]
pub struct Spread<'ast> {
pub expression: ExpressionNode<'ast>,
}
/// A range /// A range
#[derive(Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub struct Range<'ast> { pub struct Range<'ast> {
pub from: Option<ExpressionNode<'ast>>, pub from: Option<ExpressionNode<'ast>>,
pub to: Option<ExpressionNode<'ast>>, pub to: Option<ExpressionNode<'ast>>,
@ -528,14 +520,8 @@ impl<'ast> fmt::Display for Range<'ast> {
} }
} }
impl<'ast> fmt::Debug for Range<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Range({:?}, {:?})", self.from, self.to)
}
}
/// An expression /// An expression
#[derive(Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub enum Expression<'ast> { pub enum Expression<'ast> {
IntConstant(BigUint), IntConstant(BigUint),
FieldConstant(BigUint), FieldConstant(BigUint),
@ -672,73 +658,8 @@ impl<'ast> fmt::Display for Expression<'ast> {
} }
} }
impl<'ast> fmt::Debug for Expression<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Expression::U8Constant(ref i) => write!(f, "U8({:x})", i),
Expression::U16Constant(ref i) => write!(f, "U16({:x})", i),
Expression::U32Constant(ref i) => write!(f, "U32({:x})", i),
Expression::U64Constant(ref i) => write!(f, "U64({:x})", i),
Expression::FieldConstant(ref i) => write!(f, "Field({:?})", i),
Expression::IntConstant(ref i) => write!(f, "Int({:?})", i),
Expression::Identifier(ref var) => write!(f, "Ide({})", var),
Expression::Add(ref lhs, ref rhs) => write!(f, "Add({:?}, {:?})", lhs, rhs),
Expression::Sub(ref lhs, ref rhs) => write!(f, "Sub({:?}, {:?})", lhs, rhs),
Expression::Mult(ref lhs, ref rhs) => write!(f, "Mult({:?}, {:?})", lhs, rhs),
Expression::Div(ref lhs, ref rhs) => write!(f, "Div({:?}, {:?})", lhs, rhs),
Expression::Rem(ref lhs, ref rhs) => write!(f, "Rem({:?}, {:?})", lhs, rhs),
Expression::Pow(ref lhs, ref rhs) => write!(f, "Pow({:?}, {:?})", lhs, rhs),
Expression::Neg(ref e) => write!(f, "Neg({:?})", e),
Expression::Pos(ref e) => write!(f, "Pos({:?})", e),
Expression::BooleanConstant(b) => write!(f, "{}", b),
Expression::IfElse(ref condition, ref consequent, ref alternative) => write!(
f,
"IfElse({:?}, {:?}, {:?})",
condition, consequent, alternative
),
Expression::FunctionCall(ref g, ref i, ref p) => {
write!(f, "FunctionCall({:?}, {:?}, (", g, i)?;
f.debug_list().entries(p.iter()).finish()?;
write!(f, ")")
}
Expression::Lt(ref lhs, ref rhs) => write!(f, "Lt({:?}, {:?})", lhs, rhs),
Expression::Le(ref lhs, ref rhs) => write!(f, "Le({:?}, {:?})", lhs, rhs),
Expression::Eq(ref lhs, ref rhs) => write!(f, "Eq({:?}, {:?})", lhs, rhs),
Expression::Ge(ref lhs, ref rhs) => write!(f, "Ge({:?}, {:?})", lhs, rhs),
Expression::Gt(ref lhs, ref rhs) => write!(f, "Gt({:?}, {:?})", lhs, rhs),
Expression::And(ref lhs, ref rhs) => write!(f, "And({:?}, {:?})", lhs, rhs),
Expression::Not(ref exp) => write!(f, "Not({:?})", exp),
Expression::InlineArray(ref exprs) => {
write!(f, "InlineArray([")?;
f.debug_list().entries(exprs.iter()).finish()?;
write!(f, "]")
}
Expression::ArrayInitializer(ref e, ref count) => {
write!(f, "ArrayInitializer({:?}, {:?})", e, count)
}
Expression::InlineStruct(ref id, ref members) => {
write!(f, "InlineStruct({:?}, [", id)?;
f.debug_list().entries(members.iter()).finish()?;
write!(f, "]")
}
Expression::Select(ref array, ref index) => {
write!(f, "Select({:?}, {:?})", array, index)
}
Expression::Member(ref struc, ref id) => write!(f, "Member({:?}, {:?})", struc, id),
Expression::Or(ref lhs, ref rhs) => write!(f, "Or({:?}, {:?})", lhs, rhs),
Expression::BitXor(ref lhs, ref rhs) => write!(f, "BitXor({:?}, {:?})", lhs, rhs),
Expression::BitAnd(ref lhs, ref rhs) => write!(f, "BitAnd({:?}, {:?})", lhs, rhs),
Expression::BitOr(ref lhs, ref rhs) => write!(f, "BitOr({:?}, {:?})", lhs, rhs),
Expression::LeftShift(ref lhs, ref rhs) => write!(f, "LeftShift({:?}, {:?})", lhs, rhs),
Expression::RightShift(ref lhs, ref rhs) => {
write!(f, "RightShift({:?}, {:?})", lhs, rhs)
}
}
}
}
/// A list of expressions, used in return statements /// A list of expressions, used in return statements
#[derive(Clone, PartialEq, Default)] #[derive(Debug, Clone, PartialEq, Default)]
pub struct ExpressionList<'ast> { pub struct ExpressionList<'ast> {
pub expressions: Vec<ExpressionNode<'ast>>, pub expressions: Vec<ExpressionNode<'ast>>,
} }
@ -756,9 +677,3 @@ impl<'ast> fmt::Display for ExpressionList<'ast> {
write!(f, "") write!(f, "")
} }
} }
impl<'ast> fmt::Debug for ExpressionList<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ExpressionList({:?})", self.expressions)
}
}

View file

@ -74,7 +74,6 @@ impl<V: NodeValue> From<V> for Node<V> {
use crate::absy::types::UnresolvedType; use crate::absy::types::UnresolvedType;
use crate::absy::*; use crate::absy::*;
use crate::imports::*;
impl<'ast> NodeValue for Expression<'ast> {} impl<'ast> NodeValue for Expression<'ast> {}
impl<'ast> NodeValue for ExpressionList<'ast> {} impl<'ast> NodeValue for ExpressionList<'ast> {}
@ -87,10 +86,11 @@ impl<'ast> NodeValue for StructDefinitionField<'ast> {}
impl<'ast> NodeValue for ConstantDefinition<'ast> {} impl<'ast> NodeValue for ConstantDefinition<'ast> {}
impl<'ast> NodeValue for Function<'ast> {} impl<'ast> NodeValue for Function<'ast> {}
impl<'ast> NodeValue for Module<'ast> {} impl<'ast> NodeValue for Module<'ast> {}
impl<'ast> NodeValue for MainImport<'ast> {}
impl<'ast> NodeValue for FromImport<'ast> {}
impl<'ast> NodeValue for SymbolImport<'ast> {} impl<'ast> NodeValue for SymbolImport<'ast> {}
impl<'ast> NodeValue for Variable<'ast> {} impl<'ast> NodeValue for Variable<'ast> {}
impl<'ast> NodeValue for Parameter<'ast> {} impl<'ast> NodeValue for Parameter<'ast> {}
impl<'ast> NodeValue for Import<'ast> {}
impl<'ast> NodeValue for Spread<'ast> {} impl<'ast> NodeValue for Spread<'ast> {}
impl<'ast> NodeValue for Range<'ast> {} impl<'ast> NodeValue for Range<'ast> {}
impl<'ast> NodeValue for Identifier<'ast> {} impl<'ast> NodeValue for Identifier<'ast> {}

View file

@ -289,7 +289,7 @@ mod test {
assert!(res.unwrap_err().0[0] assert!(res.unwrap_err().0[0]
.value() .value()
.to_string() .to_string()
.contains(&"Can't resolve import without a resolver")); .contains(&"Cannot resolve import without a resolver"));
} }
#[test] #[test]

View file

@ -12,7 +12,7 @@ use crate::parser::Position;
use std::collections::HashMap; use std::collections::HashMap;
use std::fmt; use std::fmt;
use std::io; use std::io;
use std::path::{Path, PathBuf}; use std::path::PathBuf;
use typed_arena::Arena; use typed_arena::Arena;
use zokrates_common::Resolver; use zokrates_common::Resolver;
@ -56,94 +56,6 @@ impl From<io::Error> for Error {
} }
} }
#[derive(PartialEq, Clone)]
pub enum ImportDirective<'ast> {
Main(ImportNode<'ast>),
From(Vec<ImportNode<'ast>>),
}
impl<'ast> IntoIterator for ImportDirective<'ast> {
type Item = ImportNode<'ast>;
type IntoIter = std::vec::IntoIter<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
let vec = match self {
ImportDirective::Main(v) => vec![v],
ImportDirective::From(v) => v,
};
vec.into_iter()
}
}
type ImportPath<'ast> = &'ast Path;
#[derive(PartialEq, Clone)]
pub struct Import<'ast> {
source: ImportPath<'ast>,
symbol: Option<Identifier<'ast>>,
alias: Option<Identifier<'ast>>,
}
pub type ImportNode<'ast> = Node<Import<'ast>>;
impl<'ast> Import<'ast> {
pub fn new(symbol: Option<Identifier<'ast>>, source: ImportPath<'ast>) -> Import<'ast> {
Import {
symbol,
source,
alias: None,
}
}
pub fn get_alias(&self) -> &Option<Identifier<'ast>> {
&self.alias
}
pub fn new_with_alias(
symbol: Option<Identifier<'ast>>,
source: ImportPath<'ast>,
alias: Identifier<'ast>,
) -> Import<'ast> {
Import {
symbol,
source,
alias: Some(alias),
}
}
pub fn alias(mut self, alias: Option<Identifier<'ast>>) -> Self {
self.alias = alias;
self
}
pub fn get_source(&self) -> &ImportPath<'ast> {
&self.source
}
}
impl<'ast> fmt::Display for Import<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.alias {
Some(ref alias) => write!(f, "import {} as {}", self.source.display(), alias),
None => write!(f, "import {}", self.source.display()),
}
}
}
impl<'ast> fmt::Debug for Import<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.alias {
Some(ref alias) => write!(
f,
"import(source: {}, alias: {})",
self.source.display(),
alias
),
None => write!(f, "import(source: {})", self.source.display()),
}
}
}
pub struct Importer; pub struct Importer;
impl Importer { impl Importer {
@ -156,253 +68,261 @@ impl Importer {
) -> Result<Module<'ast>, CompileErrors> { ) -> Result<Module<'ast>, CompileErrors> {
let mut symbols: Vec<_> = vec![]; let mut symbols: Vec<_> = vec![];
for import in destination.imports { for symbol in destination.symbols {
let pos = import.pos(); match symbol.value.symbol {
let import = import.value; Symbol::Here(ref s) => match s {
let alias = import.alias; SymbolDefinition::Import(ImportDirective::Main(main)) => {
// handle the case of special bellman and packing imports let pos = main.pos();
if import.source.starts_with("EMBED") { let module_id = &main.value.source;
match import.source.to_str().unwrap() {
#[cfg(feature = "bellman")] match resolver {
"EMBED/sha256round" => { Some(res) => {
if T::id() != Bn128Field::id() { match res.resolve(location.clone(), module_id.to_path_buf()) {
return Err(CompileErrorInner::ImportError( Ok((source, new_location)) => {
Error::new(format!( // generate an alias from the imported path if none was given explicitly
"Embed sha256round cannot be used with curve {}", let alias = main.value.alias.or(
T::name() module_id
.file_stem()
.ok_or_else(|| {
CompileErrors::from(
CompileErrorInner::ImportError(Error::new(
format!(
"Could not determine alias for import {}",
module_id.display()
),
))
.in_file(&location),
)
})?
.to_str()
);
match modules.get(&new_location) {
Some(_) => {}
None => {
let source = arena.alloc(source);
let compiled = compile_module::<T, E>(
source,
new_location.clone(),
resolver,
modules,
&arena,
)?;
assert!(modules
.insert(new_location.clone(), compiled)
.is_none());
}
};
symbols.push(
SymbolDeclaration {
id: alias,
symbol: Symbol::There(
SymbolImport::with_id_in_module(
"main",
new_location,
)
.start_end(pos.0, pos.1),
),
}
.start_end(pos.0, pos.1),
);
}
Err(err) => {
return Err(CompileErrorInner::ImportError(
err.into().with_pos(Some(pos)),
)
.in_file(&location)
.into());
}
}
}
None => {
return Err(CompileErrorInner::from(Error::new(
"Cannot resolve import without a resolver",
)) ))
.with_pos(Some(pos)), .in_file(&location)
) .into());
.in_file(&location) }
.into());
} else {
let alias = alias.unwrap_or("sha256round");
symbols.push(
SymbolDeclaration {
id: &alias,
symbol: Symbol::Flat(FlatEmbed::Sha256Round),
}
.start_end(pos.0, pos.1),
);
} }
} }
"EMBED/unpack" => { SymbolDefinition::Import(ImportDirective::From(from)) => {
let alias = alias.unwrap_or("unpack"); let pos = from.pos();
let module_id = &from.value.source;
symbols.push( match module_id.to_str().unwrap() {
SymbolDeclaration { "EMBED" => {
id: &alias, for symbol in &from.value.symbols {
symbol: Symbol::Flat(FlatEmbed::Unpack), match symbol.id {
} #[cfg(feature = "bellman")]
.start_end(pos.0, pos.1), "sha256round" => {
); if T::id() != Bn128Field::id() {
} return Err(CompileErrorInner::ImportError(
"EMBED/u64_to_bits" => { Error::new(format!(
let alias = alias.unwrap_or("u64_to_bits"); "Embed sha256round cannot be used with curve {}",
T::name()
symbols.push( ))
SymbolDeclaration { .with_pos(Some(pos)),
id: &alias, ).in_file(&location).into());
symbol: Symbol::Flat(FlatEmbed::U64ToBits), } else {
} symbols.push(
.start_end(pos.0, pos.1), SymbolDeclaration {
); id: Some(symbol.get_alias()),
} symbol: Symbol::Flat(
"EMBED/u32_to_bits" => { FlatEmbed::Sha256Round,
let alias = alias.unwrap_or("u32_to_bits"); ),
}
symbols.push( .start_end(pos.0, pos.1),
SymbolDeclaration { )
id: &alias, }
symbol: Symbol::Flat(FlatEmbed::U32ToBits), }
} "unpack" => symbols.push(
.start_end(pos.0, pos.1), SymbolDeclaration {
); id: Some(symbol.get_alias()),
} symbol: Symbol::Flat(FlatEmbed::Unpack),
"EMBED/u16_to_bits" => { }
let alias = alias.unwrap_or("u16_to_bits"); .start_end(pos.0, pos.1),
),
symbols.push( "u64_to_bits" => symbols.push(
SymbolDeclaration { SymbolDeclaration {
id: &alias, id: Some(symbol.get_alias()),
symbol: Symbol::Flat(FlatEmbed::U16ToBits), symbol: Symbol::Flat(FlatEmbed::U64ToBits),
} }
.start_end(pos.0, pos.1), .start_end(pos.0, pos.1),
); ),
} "u32_to_bits" => symbols.push(
"EMBED/u8_to_bits" => { SymbolDeclaration {
let alias = alias.unwrap_or("u8_to_bits"); id: Some(symbol.get_alias()),
symbol: Symbol::Flat(FlatEmbed::U32ToBits),
symbols.push( }
SymbolDeclaration { .start_end(pos.0, pos.1),
id: &alias, ),
symbol: Symbol::Flat(FlatEmbed::U8ToBits), "u16_to_bits" => symbols.push(
} SymbolDeclaration {
.start_end(pos.0, pos.1), id: Some(symbol.get_alias()),
); symbol: Symbol::Flat(FlatEmbed::U16ToBits),
} }
"EMBED/u64_from_bits" => { .start_end(pos.0, pos.1),
let alias = alias.unwrap_or("u64_from_bits"); ),
"u8_to_bits" => symbols.push(
symbols.push( SymbolDeclaration {
SymbolDeclaration { id: Some(symbol.get_alias()),
id: &alias, symbol: Symbol::Flat(FlatEmbed::U8ToBits),
symbol: Symbol::Flat(FlatEmbed::U64FromBits), }
} .start_end(pos.0, pos.1),
.start_end(pos.0, pos.1), ),
); "u64_from_bits" => symbols.push(
} SymbolDeclaration {
"EMBED/u32_from_bits" => { id: Some(symbol.get_alias()),
let alias = alias.unwrap_or("u32_from_bits"); symbol: Symbol::Flat(FlatEmbed::U64FromBits),
}
symbols.push( .start_end(pos.0, pos.1),
SymbolDeclaration { ),
id: &alias, "u32_from_bits" => symbols.push(
symbol: Symbol::Flat(FlatEmbed::U32FromBits), SymbolDeclaration {
} id: Some(symbol.get_alias()),
.start_end(pos.0, pos.1), symbol: Symbol::Flat(FlatEmbed::U32FromBits),
); }
} .start_end(pos.0, pos.1),
"EMBED/u16_from_bits" => { ),
let alias = alias.unwrap_or("u16_from_bits"); "u16_from_bits" => symbols.push(
SymbolDeclaration {
symbols.push( id: Some(symbol.get_alias()),
SymbolDeclaration { symbol: Symbol::Flat(FlatEmbed::U16FromBits),
id: &alias, }
symbol: Symbol::Flat(FlatEmbed::U16FromBits), .start_end(pos.0, pos.1),
} ),
.start_end(pos.0, pos.1), "u8_from_bits" => symbols.push(
); SymbolDeclaration {
} id: Some(symbol.get_alias()),
"EMBED/u8_from_bits" => { symbol: Symbol::Flat(FlatEmbed::U8FromBits),
let alias = alias.unwrap_or("u8_from_bits"); }
.start_end(pos.0, pos.1),
symbols.push( ),
SymbolDeclaration { s => {
id: &alias, return Err(CompileErrorInner::ImportError(
symbol: Symbol::Flat(FlatEmbed::U8FromBits), Error::new(format!("Embed {} not found", s))
} .with_pos(Some(pos)),
.start_end(pos.0, pos.1), )
); .in_file(&location)
} .into())
s => { }
return Err(CompileErrorInner::ImportError( }
Error::new(format!("Embed {} not found", s)).with_pos(Some(pos)),
)
.in_file(&location)
.into());
}
}
} else {
// to resolve imports, we need a resolver
match resolver {
Some(res) => match res.resolve(location.clone(), import.source.to_path_buf()) {
Ok((source, new_location)) => {
// generate an alias from the imported path if none was given explicitely
let alias = import.alias.unwrap_or(
std::path::Path::new(import.source)
.file_stem()
.ok_or_else(|| {
CompileErrors::from(
CompileErrorInner::ImportError(Error::new(format!(
"Could not determine alias for import {}",
import.source.display()
)))
.in_file(&location),
)
})?
.to_str()
.unwrap(),
);
match modules.get(&new_location) {
Some(_) => {}
None => {
let source = arena.alloc(source);
let compiled = compile_module::<T, E>(
source,
new_location.clone(),
resolver,
modules,
&arena,
)?;
assert!(modules
.insert(new_location.clone(), compiled)
.is_none());
} }
}; }
_ => {
for symbol in &from.value.symbols {
match resolver {
Some(res) => {
match res
.resolve(location.clone(), module_id.to_path_buf())
{
Ok((source, new_location)) => {
match modules.get(&new_location) {
Some(_) => {}
None => {
let source = arena.alloc(source);
symbols.push( let compiled = compile_module::<T, E>(
SymbolDeclaration { source,
id: &alias, new_location.clone(),
symbol: Symbol::There( resolver,
SymbolImport::with_id_in_module( modules,
import.symbol.unwrap_or("main"), &arena,
new_location.display().to_string(), )?;
)
.start_end(pos.0, pos.1), assert!(modules
), .insert(
new_location.clone(),
compiled
)
.is_none());
}
};
symbols.push(
SymbolDeclaration {
id: Some(symbol.get_alias()),
symbol: Symbol::There(
SymbolImport::with_id_in_module(
symbol.id,
new_location,
)
.start_end(pos.0, pos.1),
),
}
.start_end(pos.0, pos.1),
);
}
Err(err) => {
return Err(CompileErrorInner::ImportError(
err.into().with_pos(Some(pos)),
)
.in_file(&location)
.into());
}
}
}
None => {
return Err(CompileErrorInner::from(Error::new(
"Cannot resolve import without a resolver",
))
.in_file(&location)
.into());
}
}
} }
.start_end(pos.0, pos.1), }
);
} }
Err(err) => {
return Err(CompileErrorInner::ImportError(
err.into().with_pos(Some(pos)),
)
.in_file(&location)
.into());
}
},
None => {
return Err(CompileErrorInner::from(Error::new(
"Can't resolve import without a resolver",
))
.in_file(&location)
.into());
} }
} _ => symbols.push(symbol),
},
_ => unreachable!(),
} }
} }
symbols.extend(destination.symbols); Ok(Module::with_symbols(symbols))
Ok(Module {
imports: vec![],
symbols,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn create_with_no_alias() {
assert_eq!(
Import::new(None, Path::new("./foo/bar/baz.zok")),
Import {
symbol: None,
source: Path::new("./foo/bar/baz.zok"),
alias: None,
}
);
}
#[test]
fn create_with_alias() {
assert_eq!(
Import::new_with_alias(None, Path::new("./foo/bar/baz.zok"), &"myalias"),
Import {
symbol: None,
source: Path::new("./foo/bar/baz.zok"),
alias: Some("myalias"),
}
);
} }
} }

View file

@ -452,130 +452,128 @@ impl<'ast, T: Field> Checker<'ast, T> {
let pos = declaration.pos(); let pos = declaration.pos();
let declaration = declaration.value; let declaration = declaration.value;
let declaration_id = declaration.id.unwrap();
match declaration.symbol.clone() { match declaration.symbol.clone() {
Symbol::Here(kind) => match kind { Symbol::Here(SymbolDefinition::Struct(t)) => {
SymbolDefinition::Struct(t) => { match self.check_struct_type_declaration(
match self.check_struct_type_declaration( declaration_id.to_string(),
declaration.id.to_string(), t.clone(),
t.clone(), module_id,
module_id, &state.types,
&state.types, ) {
) { Ok(ty) => {
Ok(ty) => { match symbol_unifier.insert_type(declaration_id) {
match symbol_unifier.insert_type(declaration.id) { false => errors.push(
false => errors.push( ErrorInner {
ErrorInner { pos: Some(pos),
pos: Some(pos), message: format!(
message: format!( "{} conflicts with another symbol",
"{} conflicts with another symbol", declaration_id
declaration.id, ),
),
}
.in_file(module_id),
),
true => {
// there should be no entry in the map for this type yet
assert!(state
.types
.entry(module_id.to_path_buf())
.or_default()
.insert(declaration.id.to_string(), ty)
.is_none());
} }
}; .in_file(module_id),
} ),
Err(e) => errors.extend(e.into_iter().map(|inner| Error { true => {
inner, // there should be no entry in the map for this type yet
module_id: module_id.to_path_buf(), assert!(state
})), .types
.entry(module_id.to_path_buf())
.or_default()
.insert(declaration_id.to_string(), ty)
.is_none());
}
};
}
Err(e) => errors.extend(e.into_iter().map(|inner| Error {
inner,
module_id: module_id.to_path_buf(),
})),
}
}
Symbol::Here(SymbolDefinition::Constant(c)) => {
match self.check_constant_definition(declaration_id, c, module_id, &state.types) {
Ok(c) => {
match symbol_unifier.insert_constant(declaration_id) {
false => errors.push(
ErrorInner {
pos: Some(pos),
message: format!(
"{} conflicts with another symbol",
declaration_id
),
}
.in_file(module_id),
),
true => {
constants
.insert(declaration_id, TypedConstantSymbol::Here(c.clone()));
self.insert_into_scope(Variable::with_id_and_type(
declaration_id,
c.get_type(),
));
assert!(state
.constants
.entry(module_id.to_path_buf())
.or_default()
.insert(declaration_id, c.get_type())
.is_none());
}
};
}
Err(e) => {
errors.push(e.in_file(module_id));
} }
} }
SymbolDefinition::Constant(c) => { }
match self.check_constant_definition(declaration.id, c, module_id, &state.types) Symbol::Here(SymbolDefinition::Function(f)) => {
{ match self.check_function(f, module_id, &state.types) {
Ok(c) => { Ok(funct) => {
match symbol_unifier.insert_constant(declaration.id) { match symbol_unifier
false => errors.push( .insert_function(declaration_id, funct.signature.clone())
ErrorInner { {
pos: Some(pos), false => errors.push(
message: format!( ErrorInner {
"{} conflicts with another symbol", pos: Some(pos),
declaration.id, message: format!(
), "{} conflicts with another symbol",
} declaration_id
.in_file(module_id), ),
),
true => {
constants.insert(
declaration.id,
TypedConstantSymbol::Here(c.clone()),
);
self.insert_into_scope(Variable::with_id_and_type(
declaration.id,
c.get_type(),
));
assert!(state
.constants
.entry(module_id.to_path_buf())
.or_default()
.insert(declaration.id, c.get_type())
.is_none());
} }
}; .in_file(module_id),
} ),
Err(e) => { true => {}
errors.push(e.in_file(module_id)); };
}
}
}
SymbolDefinition::Function(f) => {
match self.check_function(f, module_id, &state.types) {
Ok(funct) => {
match symbol_unifier
.insert_function(declaration.id, funct.signature.clone())
{
false => errors.push(
ErrorInner {
pos: Some(pos),
message: format!(
"{} conflicts with another symbol",
declaration.id,
),
}
.in_file(module_id),
),
true => {}
};
self.functions.insert( self.functions.insert(
DeclarationFunctionKey::with_location( DeclarationFunctionKey::with_location(
module_id.to_path_buf(), module_id.to_path_buf(),
declaration.id, declaration_id,
) )
.signature(funct.signature.clone()), .signature(funct.signature.clone()),
); );
functions.insert( functions.insert(
DeclarationFunctionKey::with_location( DeclarationFunctionKey::with_location(
module_id.to_path_buf(), module_id.to_path_buf(),
declaration.id, declaration_id,
) )
.signature(funct.signature.clone()), .signature(funct.signature.clone()),
TypedFunctionSymbol::Here(funct), TypedFunctionSymbol::Here(funct),
); );
} }
Err(e) => { Err(e) => {
errors.extend(e.into_iter().map(|inner| inner.in_file(module_id))); errors.extend(e.into_iter().map(|inner| inner.in_file(module_id)));
}
} }
} }
}, }
Symbol::There(import) => { Symbol::There(import) => {
let pos = import.pos(); let pos = import.pos();
let import = import.value; let import = import.value;
match Checker::new().check_module(&import.module_id, state) { match Checker::new().check_module(&import.module_id, state) {
Ok(()) => { Ok(()) => {
let symbol_id = import.symbol_id.get_alias();
// find candidates in the checked module // find candidates in the checked module
let function_candidates: Vec<_> = state let function_candidates: Vec<_> = state
.typed_modules .typed_modules
@ -583,10 +581,10 @@ impl<'ast, T: Field> Checker<'ast, T> {
.unwrap() .unwrap()
.functions .functions
.iter() .iter()
.filter(|(k, _)| k.id == import.symbol_id) .filter(|(k, _)| k.id == symbol_id)
.map(|(_, v)| DeclarationFunctionKey { .map(|(_, v)| DeclarationFunctionKey {
module: import.module_id.to_path_buf(), module: import.module_id.to_path_buf(),
id: import.symbol_id, id: symbol_id,
signature: v.signature(&state.typed_modules).clone(), signature: v.signature(&state.typed_modules).clone(),
}) })
.collect(); .collect();
@ -596,7 +594,7 @@ impl<'ast, T: Field> Checker<'ast, T> {
.types .types
.entry(import.module_id.to_path_buf()) .entry(import.module_id.to_path_buf())
.or_default() .or_default()
.get(import.symbol_id) .get(symbol_id)
.cloned(); .cloned();
// find constant definition candidate // find constant definition candidate
@ -604,7 +602,7 @@ impl<'ast, T: Field> Checker<'ast, T> {
.constants .constants
.entry(import.module_id.to_path_buf()) .entry(import.module_id.to_path_buf())
.or_default() .or_default()
.get(import.symbol_id) .get(symbol_id)
.cloned(); .cloned();
match (function_candidates.len(), type_candidate, const_candidate) { match (function_candidates.len(), type_candidate, const_candidate) {
@ -614,7 +612,7 @@ impl<'ast, T: Field> Checker<'ast, T> {
let t = match t { let t = match t {
DeclarationType::Struct(t) => DeclarationType::Struct(DeclarationStructType { DeclarationType::Struct(t) => DeclarationType::Struct(DeclarationStructType {
location: Some(StructLocation { location: Some(StructLocation {
name: declaration.id.into(), name: declaration_id.into(),
module: module_id.to_path_buf() module: module_id.to_path_buf()
}), }),
..t ..t
@ -623,28 +621,7 @@ impl<'ast, T: Field> Checker<'ast, T> {
}; };
// we imported a type, so the symbol it gets bound to should not already exist // we imported a type, so the symbol it gets bound to should not already exist
match symbol_unifier.insert_type(declaration.id) { match symbol_unifier.insert_type(declaration_id) {
false => {
errors.push(Error {
module_id: module_id.to_path_buf(),
inner: ErrorInner {
pos: Some(pos),
message: format!(
"{} conflicts with another symbol",
declaration.id,
),
}});
}
true => {}
};
state
.types
.entry(module_id.to_path_buf())
.or_default()
.insert(declaration.id.to_string(), t);
}
(0, None, Some(ty)) => {
match symbol_unifier.insert_constant(declaration.id) {
false => { false => {
errors.push(Error { errors.push(Error {
module_id: module_id.to_path_buf(), module_id: module_id.to_path_buf(),
@ -652,19 +629,40 @@ impl<'ast, T: Field> Checker<'ast, T> {
pos: Some(pos), pos: Some(pos),
message: format!( message: format!(
"{} conflicts with another symbol", "{} conflicts with another symbol",
declaration.id, declaration_id,
),
}});
}
true => {}
};
state
.types
.entry(module_id.to_path_buf())
.or_default()
.insert(declaration_id.to_string(), t);
}
(0, None, Some(ty)) => {
match symbol_unifier.insert_constant(declaration_id) {
false => {
errors.push(Error {
module_id: module_id.to_path_buf(),
inner: ErrorInner {
pos: Some(pos),
message: format!(
"{} conflicts with another symbol",
declaration_id,
), ),
}}); }});
} }
true => { true => {
constants.insert(declaration.id, TypedConstantSymbol::There(import.module_id, import.symbol_id)); constants.insert(declaration_id, TypedConstantSymbol::There(import.module_id.to_path_buf(), symbol_id));
self.insert_into_scope(Variable::with_id_and_type(declaration.id, ty.clone())); self.insert_into_scope(Variable::with_id_and_type(declaration_id, ty.clone()));
state state
.constants .constants
.entry(module_id.to_path_buf()) .entry(module_id.to_path_buf())
.or_default() .or_default()
.insert(declaration.id, ty); .insert(declaration_id, ty);
} }
}; };
} }
@ -673,7 +671,7 @@ impl<'ast, T: Field> Checker<'ast, T> {
pos: Some(pos), pos: Some(pos),
message: format!( message: format!(
"Could not find symbol {} in module {}", "Could not find symbol {} in module {}",
import.symbol_id, import.module_id.display(), symbol_id, import.module_id.display(),
), ),
}.in_file(module_id)); }.in_file(module_id));
} }
@ -681,20 +679,20 @@ impl<'ast, T: Field> Checker<'ast, T> {
_ => { _ => {
for candidate in function_candidates { for candidate in function_candidates {
match symbol_unifier.insert_function(declaration.id, candidate.signature.clone()) { match symbol_unifier.insert_function(declaration_id, candidate.signature.clone()) {
false => { false => {
errors.push(ErrorInner { errors.push(ErrorInner {
pos: Some(pos), pos: Some(pos),
message: format!( message: format!(
"{} conflicts with another symbol", "{} conflicts with another symbol",
declaration.id, declaration_id,
), ),
}.in_file(module_id)); }.in_file(module_id));
}, },
true => {} true => {}
}; };
let local_key = candidate.clone().id(declaration.id).module(module_id.to_path_buf()); let local_key = candidate.clone().id(declaration_id).module(module_id.to_path_buf());
self.functions.insert(local_key.clone()); self.functions.insert(local_key.clone());
functions.insert( functions.insert(
@ -712,14 +710,14 @@ impl<'ast, T: Field> Checker<'ast, T> {
}; };
} }
Symbol::Flat(funct) => { Symbol::Flat(funct) => {
match symbol_unifier.insert_function(declaration.id, funct.signature()) { match symbol_unifier.insert_function(declaration_id, funct.signature()) {
false => { false => {
errors.push( errors.push(
ErrorInner { ErrorInner {
pos: Some(pos), pos: Some(pos),
message: format!( message: format!(
"{} conflicts with another symbol", "{} conflicts with another symbol",
declaration.id, declaration_id
), ),
} }
.in_file(module_id), .in_file(module_id),
@ -729,15 +727,16 @@ impl<'ast, T: Field> Checker<'ast, T> {
}; };
self.functions.insert( self.functions.insert(
DeclarationFunctionKey::with_location(module_id.to_path_buf(), declaration.id) DeclarationFunctionKey::with_location(module_id.to_path_buf(), declaration_id)
.signature(funct.signature()), .signature(funct.signature()),
); );
functions.insert( functions.insert(
DeclarationFunctionKey::with_location(module_id.to_path_buf(), declaration.id) DeclarationFunctionKey::with_location(module_id.to_path_buf(), declaration_id)
.signature(funct.signature()), .signature(funct.signature()),
TypedFunctionSymbol::Flat(funct), TypedFunctionSymbol::Flat(funct),
); );
} }
_ => unreachable!(),
}; };
// return if any errors occured // return if any errors occured
@ -762,8 +761,6 @@ impl<'ast, T: Field> Checker<'ast, T> {
None => None, None => None,
// if it was not, check it // if it was not, check it
Some(module) => { Some(module) => {
assert_eq!(module.imports.len(), 0);
// we need to create an entry in the types map to store types for this module // we need to create an entry in the types map to store types for this module
state.types.entry(module_id.to_path_buf()).or_default(); state.types.entry(module_id.to_path_buf()).or_default();
@ -3245,20 +3242,18 @@ mod tests {
let foo: Module = Module { let foo: Module = Module {
symbols: vec![SymbolDeclaration { symbols: vec![SymbolDeclaration {
id: "main", id: Some("main"),
symbol: Symbol::Here(SymbolDefinition::Function(function0())), symbol: Symbol::Here(SymbolDefinition::Function(function0())),
} }
.mock()], .mock()],
imports: vec![],
}; };
let bar: Module = Module { let bar: Module = Module {
symbols: vec![SymbolDeclaration { symbols: vec![SymbolDeclaration {
id: "main", id: Some("main"),
symbol: Symbol::There(SymbolImport::with_id_in_module("main", "foo").mock()), symbol: Symbol::There(SymbolImport::with_id_in_module("main", "foo").mock()),
} }
.mock()], .mock()],
imports: vec![],
}; };
let mut state = State::<Bn128Field>::new( let mut state = State::<Bn128Field>::new(
@ -3303,17 +3298,16 @@ mod tests {
let module = Module { let module = Module {
symbols: vec![ symbols: vec![
SymbolDeclaration { SymbolDeclaration {
id: "foo", id: Some("foo"),
symbol: Symbol::Here(SymbolDefinition::Function(function0())), symbol: Symbol::Here(SymbolDefinition::Function(function0())),
} }
.mock(), .mock(),
SymbolDeclaration { SymbolDeclaration {
id: "foo", id: Some("foo"),
symbol: Symbol::Here(SymbolDefinition::Function(function0())), symbol: Symbol::Here(SymbolDefinition::Function(function0())),
} }
.mock(), .mock(),
], ],
imports: vec![],
}; };
let mut state = State::<Bn128Field>::new( let mut state = State::<Bn128Field>::new(
@ -3382,17 +3376,16 @@ mod tests {
let module = Module { let module = Module {
symbols: vec![ symbols: vec![
SymbolDeclaration { SymbolDeclaration {
id: "foo", id: Some("foo"),
symbol: Symbol::Here(SymbolDefinition::Function(f0)), symbol: Symbol::Here(SymbolDefinition::Function(f0)),
} }
.mock(), .mock(),
SymbolDeclaration { SymbolDeclaration {
id: "foo", id: Some("foo"),
symbol: Symbol::Here(SymbolDefinition::Function(f1)), symbol: Symbol::Here(SymbolDefinition::Function(f1)),
} }
.mock(), .mock(),
], ],
imports: vec![],
}; };
let mut state = State::new(vec![((*MODULE_ID).clone(), module)].into_iter().collect()); let mut state = State::new(vec![((*MODULE_ID).clone(), module)].into_iter().collect());
@ -3420,17 +3413,16 @@ mod tests {
let module = Module { let module = Module {
symbols: vec![ symbols: vec![
SymbolDeclaration { SymbolDeclaration {
id: "foo", id: Some("foo"),
symbol: Symbol::Here(SymbolDefinition::Function(foo)), symbol: Symbol::Here(SymbolDefinition::Function(foo)),
} }
.mock(), .mock(),
SymbolDeclaration { SymbolDeclaration {
id: "main", id: Some("main"),
symbol: Symbol::Here(SymbolDefinition::Function(function0())), symbol: Symbol::Here(SymbolDefinition::Function(function0())),
} }
.mock(), .mock(),
], ],
imports: vec![],
}; };
let mut state = let mut state =
@ -3473,17 +3465,16 @@ mod tests {
let module = Module { let module = Module {
symbols: vec![ symbols: vec![
SymbolDeclaration { SymbolDeclaration {
id: "foo", id: Some("foo"),
symbol: Symbol::Here(SymbolDefinition::Function(foo)), symbol: Symbol::Here(SymbolDefinition::Function(foo)),
} }
.mock(), .mock(),
SymbolDeclaration { SymbolDeclaration {
id: "main", id: Some("main"),
symbol: Symbol::Here(SymbolDefinition::Function(function0())), symbol: Symbol::Here(SymbolDefinition::Function(function0())),
} }
.mock(), .mock(),
], ],
imports: vec![],
}; };
let mut state = let mut state =
@ -3513,17 +3504,16 @@ mod tests {
let module = Module { let module = Module {
symbols: vec![ symbols: vec![
SymbolDeclaration { SymbolDeclaration {
id: "foo", id: Some("foo"),
symbol: Symbol::Here(SymbolDefinition::Function(function0())), symbol: Symbol::Here(SymbolDefinition::Function(function0())),
} }
.mock(), .mock(),
SymbolDeclaration { SymbolDeclaration {
id: "foo", id: Some("foo"),
symbol: Symbol::Here(SymbolDefinition::Function(function1())), symbol: Symbol::Here(SymbolDefinition::Function(function1())),
} }
.mock(), .mock(),
], ],
imports: vec![],
}; };
let mut state = State::<Bn128Field>::new( let mut state = State::<Bn128Field>::new(
@ -3563,17 +3553,16 @@ mod tests {
let module: Module = Module { let module: Module = Module {
symbols: vec![ symbols: vec![
SymbolDeclaration { SymbolDeclaration {
id: "foo", id: Some("foo"),
symbol: Symbol::Here(SymbolDefinition::Struct(struct0())), symbol: Symbol::Here(SymbolDefinition::Struct(struct0())),
} }
.mock(), .mock(),
SymbolDeclaration { SymbolDeclaration {
id: "foo", id: Some("foo"),
symbol: Symbol::Here(SymbolDefinition::Struct(struct1())), symbol: Symbol::Here(SymbolDefinition::Struct(struct1())),
} }
.mock(), .mock(),
], ],
imports: vec![],
}; };
let mut state = State::<Bn128Field>::new( let mut state = State::<Bn128Field>::new(
@ -3600,19 +3589,18 @@ mod tests {
let module = Module { let module = Module {
symbols: vec![ symbols: vec![
SymbolDeclaration { SymbolDeclaration {
id: "foo", id: Some("foo"),
symbol: Symbol::Here(SymbolDefinition::Function(function0())), symbol: Symbol::Here(SymbolDefinition::Function(function0())),
} }
.mock(), .mock(),
SymbolDeclaration { SymbolDeclaration {
id: "foo", id: Some("foo"),
symbol: Symbol::Here(SymbolDefinition::Struct( symbol: Symbol::Here(SymbolDefinition::Struct(
StructDefinition { fields: vec![] }.mock(), StructDefinition { fields: vec![] }.mock(),
)), )),
} }
.mock(), .mock(),
], ],
imports: vec![],
}; };
let mut state = State::<Bn128Field>::new( let mut state = State::<Bn128Field>::new(
@ -3642,7 +3630,7 @@ mod tests {
// should fail // should fail
let bar = Module::with_symbols(vec![SymbolDeclaration { let bar = Module::with_symbols(vec![SymbolDeclaration {
id: "main", id: Some("main"),
symbol: Symbol::Here(SymbolDefinition::Function(function0())), symbol: Symbol::Here(SymbolDefinition::Function(function0())),
} }
.mock()]); .mock()]);
@ -3650,19 +3638,18 @@ mod tests {
let main = Module { let main = Module {
symbols: vec![ symbols: vec![
SymbolDeclaration { SymbolDeclaration {
id: "foo", id: Some("foo"),
symbol: Symbol::There( symbol: Symbol::There(
SymbolImport::with_id_in_module("main", "bar").mock(), SymbolImport::with_id_in_module("main", "bar").mock(),
), ),
} }
.mock(), .mock(),
SymbolDeclaration { SymbolDeclaration {
id: "foo", id: Some("foo"),
symbol: Symbol::Here(SymbolDefinition::Struct(struct0())), symbol: Symbol::Here(SymbolDefinition::Struct(struct0())),
} }
.mock(), .mock(),
], ],
imports: vec![],
}; };
let mut state = State::<Bn128Field>::new( let mut state = State::<Bn128Field>::new(
@ -3691,7 +3678,7 @@ mod tests {
// should fail // should fail
let bar = Module::with_symbols(vec![SymbolDeclaration { let bar = Module::with_symbols(vec![SymbolDeclaration {
id: "main", id: Some("main"),
symbol: Symbol::Here(SymbolDefinition::Function(function0())), symbol: Symbol::Here(SymbolDefinition::Function(function0())),
} }
.mock()]); .mock()]);
@ -3699,19 +3686,18 @@ mod tests {
let main = Module { let main = Module {
symbols: vec![ symbols: vec![
SymbolDeclaration { SymbolDeclaration {
id: "foo", id: Some("foo"),
symbol: Symbol::Here(SymbolDefinition::Struct(struct0())), symbol: Symbol::Here(SymbolDefinition::Struct(struct0())),
} }
.mock(), .mock(),
SymbolDeclaration { SymbolDeclaration {
id: "foo", id: Some("foo"),
symbol: Symbol::There( symbol: Symbol::There(
SymbolImport::with_id_in_module("main", "bar").mock(), SymbolImport::with_id_in_module("main", "bar").mock(),
), ),
} }
.mock(), .mock(),
], ],
imports: vec![],
}; };
let mut state = State::<Bn128Field>::new( let mut state = State::<Bn128Field>::new(
@ -3919,20 +3905,17 @@ mod tests {
let symbols = vec![ let symbols = vec![
SymbolDeclaration { SymbolDeclaration {
id: "foo", id: Some("foo"),
symbol: Symbol::Here(SymbolDefinition::Function(foo)), symbol: Symbol::Here(SymbolDefinition::Function(foo)),
} }
.mock(), .mock(),
SymbolDeclaration { SymbolDeclaration {
id: "bar", id: Some("bar"),
symbol: Symbol::Here(SymbolDefinition::Function(bar)), symbol: Symbol::Here(SymbolDefinition::Function(bar)),
} }
.mock(), .mock(),
]; ];
let module = Module { let module = Module { symbols };
symbols,
imports: vec![],
};
let mut state = let mut state =
State::<Bn128Field>::new(vec![((*MODULE_ID).clone(), module)].into_iter().collect()); State::<Bn128Field>::new(vec![((*MODULE_ID).clone(), module)].into_iter().collect());
@ -4034,25 +4017,22 @@ mod tests {
let symbols = vec![ let symbols = vec![
SymbolDeclaration { SymbolDeclaration {
id: "foo", id: Some("foo"),
symbol: Symbol::Here(SymbolDefinition::Function(foo)), symbol: Symbol::Here(SymbolDefinition::Function(foo)),
} }
.mock(), .mock(),
SymbolDeclaration { SymbolDeclaration {
id: "bar", id: Some("bar"),
symbol: Symbol::Here(SymbolDefinition::Function(bar)), symbol: Symbol::Here(SymbolDefinition::Function(bar)),
} }
.mock(), .mock(),
SymbolDeclaration { SymbolDeclaration {
id: "main", id: Some("main"),
symbol: Symbol::Here(SymbolDefinition::Function(main)), symbol: Symbol::Here(SymbolDefinition::Function(main)),
} }
.mock(), .mock(),
]; ];
let module = Module { let module = Module { symbols };
symbols,
imports: vec![],
};
let mut state = let mut state =
State::<Bn128Field>::new(vec![((*MODULE_ID).clone(), module)].into_iter().collect()); State::<Bn128Field>::new(vec![((*MODULE_ID).clone(), module)].into_iter().collect());
@ -4422,17 +4402,16 @@ mod tests {
let module = Module { let module = Module {
symbols: vec![ symbols: vec![
SymbolDeclaration { SymbolDeclaration {
id: "foo", id: Some("foo"),
symbol: Symbol::Here(SymbolDefinition::Function(foo)), symbol: Symbol::Here(SymbolDefinition::Function(foo)),
} }
.mock(), .mock(),
SymbolDeclaration { SymbolDeclaration {
id: "main", id: Some("main"),
symbol: Symbol::Here(SymbolDefinition::Function(main)), symbol: Symbol::Here(SymbolDefinition::Function(main)),
} }
.mock(), .mock(),
], ],
imports: vec![],
}; };
let mut state = let mut state =
@ -4509,17 +4488,16 @@ mod tests {
let module = Module { let module = Module {
symbols: vec![ symbols: vec![
SymbolDeclaration { SymbolDeclaration {
id: "foo", id: Some("foo"),
symbol: Symbol::Here(SymbolDefinition::Function(foo)), symbol: Symbol::Here(SymbolDefinition::Function(foo)),
} }
.mock(), .mock(),
SymbolDeclaration { SymbolDeclaration {
id: "main", id: Some("main"),
symbol: Symbol::Here(SymbolDefinition::Function(main)), symbol: Symbol::Here(SymbolDefinition::Function(main)),
} }
.mock(), .mock(),
], ],
imports: vec![],
}; };
let mut state = let mut state =
@ -4625,17 +4603,16 @@ mod tests {
let module = Module { let module = Module {
symbols: vec![ symbols: vec![
SymbolDeclaration { SymbolDeclaration {
id: "foo", id: Some("foo"),
symbol: Symbol::Here(SymbolDefinition::Function(foo)), symbol: Symbol::Here(SymbolDefinition::Function(foo)),
} }
.mock(), .mock(),
SymbolDeclaration { SymbolDeclaration {
id: "main", id: Some("main"),
symbol: Symbol::Here(SymbolDefinition::Function(main)), symbol: Symbol::Here(SymbolDefinition::Function(main)),
} }
.mock(), .mock(),
], ],
imports: vec![],
}; };
let mut state = let mut state =
@ -4918,21 +4895,18 @@ mod tests {
let symbols = vec![ let symbols = vec![
SymbolDeclaration { SymbolDeclaration {
id: "main", id: Some("main"),
symbol: Symbol::Here(SymbolDefinition::Function(main1)), symbol: Symbol::Here(SymbolDefinition::Function(main1)),
} }
.mock(), .mock(),
SymbolDeclaration { SymbolDeclaration {
id: "main", id: Some("main"),
symbol: Symbol::Here(SymbolDefinition::Function(main2)), symbol: Symbol::Here(SymbolDefinition::Function(main2)),
} }
.mock(), .mock(),
]; ];
let main_module = Module { let main_module = Module { symbols };
symbols,
imports: vec![],
};
let program = Program { let program = Program {
modules: vec![((*MODULE_ID).clone(), main_module)] modules: vec![((*MODULE_ID).clone(), main_module)]
@ -5034,9 +5008,8 @@ mod tests {
s: StructDefinition<'static>, s: StructDefinition<'static>,
) -> (Checker<Bn128Field>, State<Bn128Field>) { ) -> (Checker<Bn128Field>, State<Bn128Field>) {
let module: Module = Module { let module: Module = Module {
imports: vec![],
symbols: vec![SymbolDeclaration { symbols: vec![SymbolDeclaration {
id: "Foo", id: Some("Foo"),
symbol: Symbol::Here(SymbolDefinition::Struct(s.mock())), symbol: Symbol::Here(SymbolDefinition::Struct(s.mock())),
} }
.mock()], .mock()],
@ -5163,10 +5136,9 @@ mod tests {
// struct Bar = { foo: Foo } // struct Bar = { foo: Foo }
let module: Module = Module { let module: Module = Module {
imports: vec![],
symbols: vec![ symbols: vec![
SymbolDeclaration { SymbolDeclaration {
id: "Foo", id: Some("Foo"),
symbol: Symbol::Here(SymbolDefinition::Struct( symbol: Symbol::Here(SymbolDefinition::Struct(
StructDefinition { StructDefinition {
fields: vec![StructDefinitionField { fields: vec![StructDefinitionField {
@ -5180,7 +5152,7 @@ mod tests {
} }
.mock(), .mock(),
SymbolDeclaration { SymbolDeclaration {
id: "Bar", id: Some("Bar"),
symbol: Symbol::Here(SymbolDefinition::Struct( symbol: Symbol::Here(SymbolDefinition::Struct(
StructDefinition { StructDefinition {
fields: vec![StructDefinitionField { fields: vec![StructDefinitionField {
@ -5233,9 +5205,8 @@ mod tests {
// struct Bar = { foo: Foo } // struct Bar = { foo: Foo }
let module: Module = Module { let module: Module = Module {
imports: vec![],
symbols: vec![SymbolDeclaration { symbols: vec![SymbolDeclaration {
id: "Bar", id: Some("Bar"),
symbol: Symbol::Here(SymbolDefinition::Struct( symbol: Symbol::Here(SymbolDefinition::Struct(
StructDefinition { StructDefinition {
fields: vec![StructDefinitionField { fields: vec![StructDefinitionField {
@ -5266,9 +5237,8 @@ mod tests {
// struct Foo = { foo: Foo } // struct Foo = { foo: Foo }
let module: Module = Module { let module: Module = Module {
imports: vec![],
symbols: vec![SymbolDeclaration { symbols: vec![SymbolDeclaration {
id: "Foo", id: Some("Foo"),
symbol: Symbol::Here(SymbolDefinition::Struct( symbol: Symbol::Here(SymbolDefinition::Struct(
StructDefinition { StructDefinition {
fields: vec![StructDefinitionField { fields: vec![StructDefinitionField {
@ -5300,10 +5270,9 @@ mod tests {
// struct Bar = { foo: Foo } // struct Bar = { foo: Foo }
let module: Module = Module { let module: Module = Module {
imports: vec![],
symbols: vec![ symbols: vec![
SymbolDeclaration { SymbolDeclaration {
id: "Foo", id: Some("Foo"),
symbol: Symbol::Here(SymbolDefinition::Struct( symbol: Symbol::Here(SymbolDefinition::Struct(
StructDefinition { StructDefinition {
fields: vec![StructDefinitionField { fields: vec![StructDefinitionField {
@ -5317,7 +5286,7 @@ mod tests {
} }
.mock(), .mock(),
SymbolDeclaration { SymbolDeclaration {
id: "Bar", id: Some("Bar"),
symbol: Symbol::Here(SymbolDefinition::Struct( symbol: Symbol::Here(SymbolDefinition::Struct(
StructDefinition { StructDefinition {
fields: vec![StructDefinitionField { fields: vec![StructDefinitionField {
@ -5795,17 +5764,17 @@ mod tests {
let m = Module::with_symbols(vec![ let m = Module::with_symbols(vec![
absy::SymbolDeclaration { absy::SymbolDeclaration {
id: "foo", id: Some("foo"),
symbol: Symbol::Here(SymbolDefinition::Function(foo_field)), symbol: Symbol::Here(SymbolDefinition::Function(foo_field)),
} }
.mock(), .mock(),
absy::SymbolDeclaration { absy::SymbolDeclaration {
id: "foo", id: Some("foo"),
symbol: Symbol::Here(SymbolDefinition::Function(foo_u32)), symbol: Symbol::Here(SymbolDefinition::Function(foo_u32)),
} }
.mock(), .mock(),
absy::SymbolDeclaration { absy::SymbolDeclaration {
id: "main", id: Some("main"),
symbol: Symbol::Here(SymbolDefinition::Function(main)), symbol: Symbol::Here(SymbolDefinition::Function(main)),
} }
.mock(), .mock(),

View file

@ -1,4 +1,4 @@
import "EMBED/unpack" as unpack from "EMBED" import unpack
def main(field x): def main(field x):
bool[1] bits = unpack(x) bool[1] bits = unpack(x)

View file

@ -1,5 +1,5 @@
import "EMBED/u32_to_bits" as to_bits import "utils/casts/u32_to_bits" as to_bits
import "EMBED/u32_from_bits" as from_bits import "utils/casts/u32_from_bits" as from_bits
def rotl32<N>(u32 e) -> u32: def rotl32<N>(u32 e) -> u32:
bool[32] b = to_bits(e) bool[32] b = to_bits(e)

View file

@ -1,5 +1,5 @@
import "EMBED/u32_to_bits" as to_bits import "utils/casts/u32_to_bits" as to_bits
import "EMBED/u32_from_bits" as from_bits import "utils/casts/u32_from_bits" as from_bits
def rotr32<N>(u32 e) -> u32: def rotr32<N>(u32 e) -> u32:
bool[32] b = to_bits(e) bool[32] b = to_bits(e)

View file

@ -1,4 +1,4 @@
import "EMBED/unpack" from "EMBED" import unpack
def main(field a) -> (bool[255]): def main(field a) -> (bool[255]):

View file

@ -1,4 +1,4 @@
import "EMBED/unpack" from "EMBED" import unpack
def main(field a) -> (bool[254]): def main(field a) -> (bool[254]):

View file

@ -1,5 +1,5 @@
import "EMBED/u32_to_bits" as to_bits import "utils/casts/u32_to_bits" as to_bits
import "EMBED/u32_from_bits" as from_bits import "utils/casts/u32_from_bits" as from_bits
def right_rotate_2(u32 e) -> u32: def right_rotate_2(u32 e) -> u32:
bool[32] b = to_bits(e) bool[32] b = to_bits(e)

View file

@ -1,11 +1,11 @@
import "EMBED/u64_to_bits" as to_bits_64 import "utils/casts/u64_to_bits" as to_bits_64
import "EMBED/u64_from_bits" as from_bits_64 import "utils/casts/u64_from_bits" as from_bits_64
import "EMBED/u32_to_bits" as to_bits_32 import "utils/casts/u32_to_bits" as to_bits_32
import "EMBED/u32_from_bits" as from_bits_32 import "utils/casts/u32_from_bits" as from_bits_32
import "EMBED/u16_to_bits" as to_bits_16 import "utils/casts/u16_to_bits" as to_bits_16
import "EMBED/u16_from_bits" as from_bits_16 import "utils/casts/u16_from_bits" as from_bits_16
import "EMBED/u8_to_bits" as to_bits_8 import "utils/casts/u8_to_bits" as to_bits_8
import "EMBED/u8_from_bits" as from_bits_8 import "utils/casts/u8_from_bits" as from_bits_8
def main(u64 d, u32 e, u16 f, u8 g) -> (u64, u32, u16, u8): def main(u64 d, u32 e, u16 f, u8 g) -> (u64, u32, u16, u8):
bool[64] d_bits = to_bits_64(d) bool[64] d_bits = to_bits_64(d)

View file

@ -1,5 +1,5 @@
import "EMBED/u32_to_bits" as to_bits import "utils/casts/u32_to_bits" as to_bits
import "EMBED/u32_from_bits" as from_bits import "utils/casts/u32_from_bits" as from_bits
def right_rotate_2(u32 e) -> u32: def right_rotate_2(u32 e) -> u32:
bool[32] b = to_bits(e) bool[32] b = to_bits(e)

View file

@ -1,60 +1,9 @@
import "EMBED/u32_to_bits" as to_bits from "EMBED" import u32_to_bits as to_bits
import "EMBED/u32_from_bits" as from_bits from "EMBED" import u32_from_bits as from_bits
def right_rotate_2(u32 e) -> u32: def right_rotate<N>(u32 e) -> u32:
bool[32] b = to_bits(e) bool[32] b = to_bits(e)
u32 res = from_bits([...b[30..], ...b[..30]]) u32 res = from_bits([...b[32-N..], ...b[..32-N]])
return res
def right_rotate_4(u32 e) -> u32:
bool[32] b = to_bits(e)
u32 res = from_bits([...b[28..], ...b[..28]])
return res
def right_rotate_6(u32 e) -> u32:
bool[32] b = to_bits(e)
u32 res = from_bits([...b[26..], ...b[..26]])
return res
def right_rotate_7(u32 e) -> u32:
bool[32] b = to_bits(e)
u32 res = from_bits([...b[25..], ...b[..25]])
return res
def right_rotate_11(u32 e) -> u32:
bool[32] b = to_bits(e)
u32 res = from_bits([...b[21..], ...b[..21]])
return res
def right_rotate_13(u32 e) -> u32:
bool[32] b = to_bits(e)
u32 res = from_bits([...b[19..], ...b[..19]])
return res
def right_rotate_17(u32 e) -> u32:
bool[32] b = to_bits(e)
u32 res = from_bits([...b[15..], ...b[..15]])
return res
def right_rotate_18(u32 e) -> u32:
bool[32] b = to_bits(e)
u32 res = from_bits([...b[14..], ...b[..14]])
return res
def right_rotate_19(u32 e) -> u32:
bool[32] b = to_bits(e)
u32 res = from_bits([...b[13..], ...b[..13]])
return res
def right_rotate_22(u32 e) -> u32:
bool[32] b = to_bits(e)
u32 res = from_bits([...b[10..], ...b[..10]])
return res
def right_rotate_25(u32 e) -> u32:
bool[32] b = to_bits(e)
u32 res = from_bits([...b[7..], ...b[..7]])
return res return res
def main(): def main():
@ -62,7 +11,7 @@ def main():
u32 f = 0x01234567 u32 f = 0x01234567
// rotate // rotate
u32 rotated = right_rotate_4(e) u32 rotated = right_rotate::<4>(e)
assert(rotated == 0x81234567) assert(rotated == 0x81234567)
// and // and
@ -93,16 +42,16 @@ def main():
assert(f == from_bits(expected2)) assert(f == from_bits(expected2))
// S0 // S0
u32 e2 = right_rotate_2(e) u32 e2 = right_rotate::<2>(e)
u32 e13 = right_rotate_13(e) u32 e13 = right_rotate::<13>(e)
u32 e22 = right_rotate_22(e) u32 e22 = right_rotate::<22>(e)
u32 S0 = e2 ^ e13 ^ e22 u32 S0 = e2 ^ e13 ^ e22
assert(S0 == 0x66146474) assert(S0 == 0x66146474)
// S1 // S1
u32 e6 = right_rotate_6(e) u32 e6 = right_rotate::<6>(e)
u32 e11 = right_rotate_11(e) u32 e11 = right_rotate::<11>(e)
u32 e25 = right_rotate_25(e) u32 e25 = right_rotate::<25>(e)
u32 S1 = e6 ^ e11 ^ e25 u32 S1 = e6 ^ e11 ^ e25
assert(S1 == 0x3561abda) assert(S1 == 0x3561abda)

View file

@ -1,5 +1,5 @@
import "EMBED/u32_to_bits" as to_bits import "utils/casts/u32_to_bits" as to_bits
import "EMBED/u32_from_bits" as from_bits import "utils/casts/u32_from_bits" as from_bits
def right_rotate_4(u32 e) -> u32: def right_rotate_4(u32 e) -> u32:
bool[32] b = to_bits(e) bool[32] b = to_bits(e)

View file

@ -1,49 +1,9 @@
import "EMBED/u32_to_bits" as to_bits def right_rotate<N>(u32 x) -> u32:
import "EMBED/u32_from_bits" as from_bits return (x >> N) | (x << (32 - N))
def right_rotate_2(u32 e) -> u32:
bool[32] b = to_bits(e)
return from_bits([...b[30..], ...b[..30]])
def right_rotate_6(u32 e) -> u32:
bool[32] b = to_bits(e)
return from_bits([...b[26..], ...b[..26]])
def right_rotate_7(u32 e) -> u32:
bool[32] b = to_bits(e)
return from_bits([...b[25..], ...b[..25]])
def right_rotate_11(u32 e) -> u32:
bool[32] b = to_bits(e)
return from_bits([...b[21..], ...b[..21]])
def right_rotate_13(u32 e) -> u32:
bool[32] b = to_bits(e)
return from_bits([...b[19..], ...b[..19]])
def right_rotate_17(u32 e) -> u32:
bool[32] b = to_bits(e)
return from_bits([...b[15..], ...b[..15]])
def right_rotate_18(u32 e) -> u32:
bool[32] b = to_bits(e)
return from_bits([...b[14..], ...b[..14]])
def right_rotate_19(u32 e) -> u32:
bool[32] b = to_bits(e)
return from_bits([...b[13..], ...b[..13]])
def right_rotate_22(u32 e) -> u32:
bool[32] b = to_bits(e)
return from_bits([...b[10..], ...b[..10]])
def right_rotate_25(u32 e) -> u32:
bool[32] b = to_bits(e)
return from_bits([...b[7..], ...b[..7]])
def extend(u32[64] w, u32 i) -> u32: def extend(u32[64] w, u32 i) -> u32:
u32 s0 = right_rotate_7(w[i-15]) ^ right_rotate_18(w[i-15]) ^ (w[i-15] >> 3) u32 s0 = right_rotate::<7>(w[i-15]) ^ right_rotate::<18>(w[i-15]) ^ (w[i-15] >> 3)
u32 s1 = right_rotate_17(w[i-2]) ^ right_rotate_19(w[i-2]) ^ (w[i-2] >> 10) u32 s1 = right_rotate::<17>(w[i-2]) ^ right_rotate::<19>(w[i-2]) ^ (w[i-2] >> 10)
return w[i-16] + s0 + w[i-7] + s1 return w[i-16] + s0 + w[i-7] + s1
def temp1(u32 e, u32 f, u32 g, u32 h, u32 k, u32 w) -> u32: def temp1(u32 e, u32 f, u32 g, u32 h, u32 k, u32 w) -> u32:
@ -51,7 +11,7 @@ def temp1(u32 e, u32 f, u32 g, u32 h, u32 k, u32 w) -> u32:
u32 ch = (e & f) ^ ((!e) & g) u32 ch = (e & f) ^ ((!e) & g)
// S1 := (e rightrotate 6) xor (e rightrotate 11) xor (e rightrotate 25) // S1 := (e rightrotate 6) xor (e rightrotate 11) xor (e rightrotate 25)
u32 S1 = right_rotate_6(e) ^ right_rotate_11(e) ^ right_rotate_25(e) u32 S1 = right_rotate::<6>(e) ^ right_rotate::<11>(e) ^ right_rotate::<25>(e)
// temp1 := h + S1 + ch + k + w // temp1 := h + S1 + ch + k + w
return h + S1 + ch + k + w return h + S1 + ch + k + w
@ -61,7 +21,7 @@ def temp2(u32 a, u32 b, u32 c) -> u32:
u32 maj = (a & b) ^ (a & c) ^ (b & c) u32 maj = (a & b) ^ (a & c) ^ (b & c)
// S0 := (a rightrotate 2) xor (a rightrotate 13) xor (a rightrotate 22) // S0 := (a rightrotate 2) xor (a rightrotate 13) xor (a rightrotate 22)
u32 S0 = right_rotate_2(a) ^ right_rotate_13(a) ^ right_rotate_22(a) u32 S0 = right_rotate::<2>(a) ^ right_rotate::<13>(a) ^ right_rotate::<22>(a)
// temp2 := S0 + maj // temp2 := S0 + maj
return S0 + maj return S0 + maj

View file

@ -1,17 +1,5 @@
import "EMBED/u32_to_bits" as to_bits def right_rotate<N>(u32 x) -> u32:
import "EMBED/u32_from_bits" as from_bits return (x >> N) | (x << (32 - N))
def right_rotate_6(u32 e) -> u32:
bool[32] b = to_bits(e)
return from_bits([...b[26..], ...b[..26]])
def right_rotate_11(u32 e) -> u32:
bool[32] b = to_bits(e)
return from_bits([...b[21..], ...b[..21]])
def right_rotate_25(u32 e) -> u32:
bool[32] b = to_bits(e)
return from_bits([...b[7..], ...b[..7]])
// input constraining costs 6 * 33 = 198 constraints, the rest 200 // input constraining costs 6 * 33 = 198 constraints, the rest 200
def main(u32 e, u32 f, u32 g, u32 h, u32 k, u32 w) -> u32: def main(u32 e, u32 f, u32 g, u32 h, u32 k, u32 w) -> u32:
@ -19,7 +7,7 @@ def main(u32 e, u32 f, u32 g, u32 h, u32 k, u32 w) -> u32:
u32 ch = (e & f) ^ ((!e) & g) // should be 100 constraints u32 ch = (e & f) ^ ((!e) & g) // should be 100 constraints
// S1 := (e rightrotate 6) xor (e rightrotate 11) xor (e rightrotate 25) // S1 := (e rightrotate 6) xor (e rightrotate 11) xor (e rightrotate 25)
u32 S1 = right_rotate_6(e) ^ right_rotate_11(e) ^ right_rotate_25(e) // should be 66 constraints u32 S1 = right_rotate::<6>(e) ^ right_rotate::<11>(e) ^ right_rotate::<25>(e) // should be 66 constraints
// temp1 := h + S1 + ch + k + w // temp1 := h + S1 + ch + k + w
return h + S1 + ch + k + w // should be 35 constraints return h + S1 + ch + k + w // should be 35 constraints

View file

@ -1,17 +1,5 @@
import "EMBED/u32_to_bits" as to_bits def right_rotate<N>(u32 x) -> u32:
import "EMBED/u32_from_bits" as from_bits return (x >> N) | (x << (32 - N))
def right_rotate_2(u32 e) -> u32:
bool[32] b = to_bits(e)
return from_bits([...b[30..], ...b[..30]])
def right_rotate_13(u32 e) -> u32:
bool[32] b = to_bits(e)
return from_bits([...b[19..], ...b[..19]])
def right_rotate_22(u32 e) -> u32:
bool[32] b = to_bits(e)
return from_bits([...b[10..], ...b[..10]])
// input constraining is 99 constraints, the rest is 265 -> total 364 // input constraining is 99 constraints, the rest is 265 -> total 364
def main(u32 a, u32 b, u32 c) -> u32: def main(u32 a, u32 b, u32 c) -> u32:
@ -19,7 +7,7 @@ def main(u32 a, u32 b, u32 c) -> u32:
u32 maj = (a & b) ^ (a & c) ^ (b & c) // 165 constraints u32 maj = (a & b) ^ (a & c) ^ (b & c) // 165 constraints
// S0 := (a rightrotate 2) xor (a rightrotate 13) xor (a rightrotate 22) // S0 := (a rightrotate 2) xor (a rightrotate 13) xor (a rightrotate 22)
u32 S0 = right_rotate_2(a) ^ right_rotate_13(a) ^ right_rotate_22(a) // 66 constraints u32 S0 = right_rotate::<2>(a) ^ right_rotate::<13>(a) ^ right_rotate::<22>(a) // 66 constraints
// temp2 := S0 + maj // temp2 := S0 + maj
return S0 + maj // 34 constraints return S0 + maj // 34 constraints

View file

@ -1,9 +1,11 @@
file = { SOI ~ NEWLINE* ~ pragma? ~ NEWLINE* ~ import_directive* ~ NEWLINE* ~ ty_struct_definition* ~ NEWLINE* ~ const_definition* ~ NEWLINE* ~ function_definition* ~ EOI } file = { SOI ~ NEWLINE* ~ pragma? ~ NEWLINE* ~ symbol_declaration* ~ EOI }
pragma = { "#pragma" ~ "curve" ~ curve } pragma = { "#pragma" ~ "curve" ~ curve }
curve = @{ (ASCII_ALPHANUMERIC | "_") * } curve = @{ (ASCII_ALPHANUMERIC | "_") * }
symbol_declaration = { (import_directive | ty_struct_definition | const_definition | function_definition) ~ NEWLINE* }
import_directive = { main_import_directive | from_import_directive } import_directive = { main_import_directive | from_import_directive }
from_import_directive = { "from" ~ "\"" ~ import_source ~ "\"" ~ "import" ~ import_symbol_list ~ NEWLINE* } from_import_directive = { "from" ~ "\"" ~ import_source ~ "\"" ~ "import" ~ import_symbol_list ~ NEWLINE* }
main_import_directive = { "import" ~ "\"" ~ import_source ~ "\"" ~ ("as" ~ identifier)? ~ NEWLINE+ } main_import_directive = { "import" ~ "\"" ~ import_source ~ "\"" ~ ("as" ~ identifier)? ~ NEWLINE+ }

View file

@ -12,12 +12,13 @@ pub use ast::{
Assignee, AssigneeAccess, BasicOrStructType, BasicType, BinaryExpression, BinaryOperator, Assignee, AssigneeAccess, BasicOrStructType, BasicType, BinaryExpression, BinaryOperator,
CallAccess, ConstantDefinition, ConstantGenericValue, DecimalLiteralExpression, DecimalNumber, CallAccess, ConstantDefinition, ConstantGenericValue, DecimalLiteralExpression, DecimalNumber,
DecimalSuffix, DefinitionStatement, ExplicitGenerics, Expression, FieldType, File, DecimalSuffix, DefinitionStatement, ExplicitGenerics, Expression, FieldType, File,
FromExpression, Function, HexLiteralExpression, HexNumberExpression, IdentifierExpression, FromExpression, FunctionDefinition, HexLiteralExpression, HexNumberExpression,
ImportDirective, ImportSource, ImportSymbol, InlineArrayExpression, InlineStructExpression, IdentifierExpression, ImportDirective, ImportSource, ImportSymbol, InlineArrayExpression,
InlineStructMember, IterationStatement, LiteralExpression, OptionallyTypedAssignee, Parameter, InlineStructExpression, InlineStructMember, IterationStatement, LiteralExpression,
PostfixExpression, Range, RangeOrExpression, ReturnStatement, Span, Spread, SpreadOrExpression, OptionallyTypedAssignee, Parameter, PostfixExpression, Range, RangeOrExpression,
Statement, StructDefinition, StructField, TernaryExpression, ToExpression, Type, ReturnStatement, Span, Spread, SpreadOrExpression, Statement, StructDefinition, StructField,
UnaryExpression, UnaryOperator, Underscore, Visibility, SymbolDeclaration, TernaryExpression, ToExpression, Type, UnaryExpression, UnaryOperator,
Underscore, Visibility,
}; };
mod ast { mod ast {
@ -109,10 +110,7 @@ mod ast {
#[pest_ast(rule(Rule::file))] #[pest_ast(rule(Rule::file))]
pub struct File<'ast> { pub struct File<'ast> {
pub pragma: Option<Pragma<'ast>>, pub pragma: Option<Pragma<'ast>>,
pub imports: Vec<ImportDirective<'ast>>, pub declarations: Vec<SymbolDeclaration<'ast>>,
pub structs: Vec<StructDefinition<'ast>>,
pub constants: Vec<ConstantDefinition<'ast>>,
pub functions: Vec<Function<'ast>>,
pub eoi: EOI, pub eoi: EOI,
#[pest_ast(outer())] #[pest_ast(outer())]
pub span: Span<'ast>, pub span: Span<'ast>,
@ -135,6 +133,16 @@ mod ast {
pub span: Span<'ast>, pub span: Span<'ast>,
} }
#[allow(clippy::large_enum_variant)]
#[derive(Debug, FromPest, PartialEq, Clone)]
#[pest_ast(rule(Rule::symbol_declaration))]
pub enum SymbolDeclaration<'ast> {
Import(ImportDirective<'ast>),
Constant(ConstantDefinition<'ast>),
Struct(StructDefinition<'ast>),
Function(FunctionDefinition<'ast>),
}
#[derive(Debug, FromPest, PartialEq, Clone)] #[derive(Debug, FromPest, PartialEq, Clone)]
#[pest_ast(rule(Rule::ty_struct_definition))] #[pest_ast(rule(Rule::ty_struct_definition))]
pub struct StructDefinition<'ast> { pub struct StructDefinition<'ast> {
@ -155,7 +163,7 @@ mod ast {
#[derive(Debug, FromPest, PartialEq, Clone)] #[derive(Debug, FromPest, PartialEq, Clone)]
#[pest_ast(rule(Rule::function_definition))] #[pest_ast(rule(Rule::function_definition))]
pub struct Function<'ast> { pub struct FunctionDefinition<'ast> {
pub id: IdentifierExpression<'ast>, pub id: IdentifierExpression<'ast>,
pub generics: Vec<IdentifierExpression<'ast>>, pub generics: Vec<IdentifierExpression<'ast>>,
pub parameters: Vec<Parameter<'ast>>, pub parameters: Vec<Parameter<'ast>>,
@ -194,7 +202,7 @@ mod ast {
#[derive(Debug, FromPest, PartialEq, Clone)] #[derive(Debug, FromPest, PartialEq, Clone)]
#[pest_ast(rule(Rule::import_symbol))] #[pest_ast(rule(Rule::import_symbol))]
pub struct ImportSymbol<'ast> { pub struct ImportSymbol<'ast> {
pub symbol: IdentifierExpression<'ast>, pub id: IdentifierExpression<'ast>,
pub alias: Option<IdentifierExpression<'ast>>, pub alias: Option<IdentifierExpression<'ast>>,
#[pest_ast(outer())] #[pest_ast(outer())]
pub span: Span<'ast>, pub span: Span<'ast>,
@ -1057,52 +1065,52 @@ mod tests {
generate_ast(&source), generate_ast(&source),
Ok(File { Ok(File {
pragma: None, pragma: None,
structs: vec![], declarations: vec![
constants: vec![], SymbolDeclaration::Import(ImportDirective::Main(MainImportDirective {
functions: vec![Function { source: ImportSource {
generics: vec![], value: String::from("foo"),
id: IdentifierExpression { span: Span::new(&source, 8, 11).unwrap()
value: String::from("main"), },
span: Span::new(&source, 33, 37).unwrap() alias: None,
}, span: Span::new(&source, 0, 29).unwrap()
parameters: vec![], })),
returns: vec![Type::Basic(BasicType::Field(FieldType { SymbolDeclaration::Function(FunctionDefinition {
span: Span::new(&source, 44, 49).unwrap() generics: vec![],
}))], id: IdentifierExpression {
statements: vec![Statement::Return(ReturnStatement { value: String::from("main"),
expressions: vec![Expression::add( span: Span::new(&source, 33, 37).unwrap()
Expression::Literal(LiteralExpression::DecimalLiteral( },
DecimalLiteralExpression { parameters: vec![],
value: DecimalNumber { returns: vec![Type::Basic(BasicType::Field(FieldType {
span: Span::new(&source, 44, 49).unwrap()
}))],
statements: vec![Statement::Return(ReturnStatement {
expressions: vec![Expression::add(
Expression::Literal(LiteralExpression::DecimalLiteral(
DecimalLiteralExpression {
value: DecimalNumber {
span: Span::new(&source, 59, 60).unwrap()
},
suffix: None,
span: Span::new(&source, 59, 60).unwrap() span: Span::new(&source, 59, 60).unwrap()
}, }
suffix: None, )),
span: Span::new(&source, 59, 60).unwrap() Expression::Literal(LiteralExpression::DecimalLiteral(
} DecimalLiteralExpression {
)), value: DecimalNumber {
Expression::Literal(LiteralExpression::DecimalLiteral( span: Span::new(&source, 63, 64).unwrap()
DecimalLiteralExpression { },
value: DecimalNumber { suffix: None,
span: Span::new(&source, 63, 64).unwrap() span: Span::new(&source, 63, 64).unwrap()
}, }
suffix: None, )),
span: Span::new(&source, 63, 64).unwrap() Span::new(&source, 59, 64).unwrap()
} )],
)), span: Span::new(&source, 52, 64).unwrap(),
Span::new(&source, 59, 64).unwrap() })],
)], span: Span::new(&source, 29, source.len()).unwrap(),
span: Span::new(&source, 52, 64).unwrap(), })
})], ],
span: Span::new(&source, 29, source.len()).unwrap(),
}],
imports: vec![ImportDirective::Main(MainImportDirective {
source: ImportSource {
value: String::from("foo"),
span: Span::new(&source, 8, 11).unwrap()
},
alias: None,
span: Span::new(&source, 0, 29).unwrap()
})],
eoi: EOI {}, eoi: EOI {},
span: Span::new(&source, 0, 65).unwrap() span: Span::new(&source, 0, 65).unwrap()
}) })
@ -1118,76 +1126,76 @@ mod tests {
generate_ast(&source), generate_ast(&source),
Ok(File { Ok(File {
pragma: None, pragma: None,
structs: vec![], declarations: vec![
constants: vec![], SymbolDeclaration::Import(ImportDirective::Main(MainImportDirective {
functions: vec![Function { source: ImportSource {
generics: vec![], value: String::from("foo"),
id: IdentifierExpression { span: Span::new(&source, 8, 11).unwrap()
value: String::from("main"), },
span: Span::new(&source, 33, 37).unwrap() alias: None,
}, span: Span::new(&source, 0, 29).unwrap()
parameters: vec![], })),
returns: vec![Type::Basic(BasicType::Field(FieldType { SymbolDeclaration::Function(FunctionDefinition {
span: Span::new(&source, 44, 49).unwrap() generics: vec![],
}))], id: IdentifierExpression {
statements: vec![Statement::Return(ReturnStatement { value: String::from("main"),
expressions: vec![Expression::add( span: Span::new(&source, 33, 37).unwrap()
Expression::Literal(LiteralExpression::DecimalLiteral( },
DecimalLiteralExpression { parameters: vec![],
suffix: None, returns: vec![Type::Basic(BasicType::Field(FieldType {
value: DecimalNumber { span: Span::new(&source, 44, 49).unwrap()
span: Span::new(&source, 59, 60).unwrap() }))],
}, statements: vec![Statement::Return(ReturnStatement {
span: Span::new(&source, 59, 60).unwrap() expressions: vec![Expression::add(
}
)),
Expression::mul(
Expression::Literal(LiteralExpression::DecimalLiteral( Expression::Literal(LiteralExpression::DecimalLiteral(
DecimalLiteralExpression { DecimalLiteralExpression {
suffix: None, suffix: None,
value: DecimalNumber { value: DecimalNumber {
span: Span::new(&source, 63, 64).unwrap() span: Span::new(&source, 59, 60).unwrap()
}, },
span: Span::new(&source, 63, 64).unwrap() span: Span::new(&source, 59, 60).unwrap()
} }
)), )),
Expression::pow( Expression::mul(
Expression::Literal(LiteralExpression::DecimalLiteral( Expression::Literal(LiteralExpression::DecimalLiteral(
DecimalLiteralExpression { DecimalLiteralExpression {
suffix: None, suffix: None,
value: DecimalNumber { value: DecimalNumber {
span: Span::new(&source, 63, 64).unwrap()
},
span: Span::new(&source, 63, 64).unwrap()
}
)),
Expression::pow(
Expression::Literal(LiteralExpression::DecimalLiteral(
DecimalLiteralExpression {
suffix: None,
value: DecimalNumber {
span: Span::new(&source, 67, 68).unwrap()
},
span: Span::new(&source, 67, 68).unwrap() span: Span::new(&source, 67, 68).unwrap()
}, }
span: Span::new(&source, 67, 68).unwrap() )),
} Expression::Literal(LiteralExpression::DecimalLiteral(
)), DecimalLiteralExpression {
Expression::Literal(LiteralExpression::DecimalLiteral( suffix: None,
DecimalLiteralExpression { value: DecimalNumber {
suffix: None, span: Span::new(&source, 72, 73).unwrap()
value: DecimalNumber { },
span: Span::new(&source, 72, 73).unwrap() span: Span::new(&source, 72, 73).unwrap()
}, }
span: Span::new(&source, 72, 73).unwrap() )),
} Span::new(&source, 67, 73).unwrap()
)), ),
Span::new(&source, 67, 73).unwrap() Span::new(&source, 63, 73).unwrap()
), ),
Span::new(&source, 63, 73).unwrap() Span::new(&source, 59, 73).unwrap()
), )],
Span::new(&source, 59, 73).unwrap() span: Span::new(&source, 52, 73).unwrap(),
)], })],
span: Span::new(&source, 52, 73).unwrap(), span: Span::new(&source, 29, 74).unwrap(),
})], })
span: Span::new(&source, 29, 74).unwrap(), ],
}],
imports: vec![ImportDirective::Main(MainImportDirective {
source: ImportSource {
value: String::from("foo"),
span: Span::new(&source, 8, 11).unwrap()
},
alias: None,
span: Span::new(&source, 0, 29).unwrap()
})],
eoi: EOI {}, eoi: EOI {},
span: Span::new(&source, 0, 74).unwrap() span: Span::new(&source, 0, 74).unwrap()
}) })
@ -1203,61 +1211,61 @@ mod tests {
generate_ast(&source), generate_ast(&source),
Ok(File { Ok(File {
pragma: None, pragma: None,
structs: vec![], declarations: vec![
constants: vec![], SymbolDeclaration::Import(ImportDirective::Main(MainImportDirective {
functions: vec![Function { source: ImportSource {
generics: vec![], value: String::from("foo"),
id: IdentifierExpression { span: Span::new(&source, 8, 11).unwrap()
value: String::from("main"), },
span: Span::new(&source, 33, 37).unwrap() alias: None,
}, span: Span::new(&source, 0, 29).unwrap()
parameters: vec![], })),
returns: vec![Type::Basic(BasicType::Field(FieldType { SymbolDeclaration::Function(FunctionDefinition {
span: Span::new(&source, 44, 49).unwrap() generics: vec![],
}))], id: IdentifierExpression {
statements: vec![Statement::Return(ReturnStatement { value: String::from("main"),
expressions: vec![Expression::if_else( span: Span::new(&source, 33, 37).unwrap()
Expression::Literal(LiteralExpression::DecimalLiteral( },
DecimalLiteralExpression { parameters: vec![],
suffix: None, returns: vec![Type::Basic(BasicType::Field(FieldType {
value: DecimalNumber { span: Span::new(&source, 44, 49).unwrap()
}))],
statements: vec![Statement::Return(ReturnStatement {
expressions: vec![Expression::if_else(
Expression::Literal(LiteralExpression::DecimalLiteral(
DecimalLiteralExpression {
suffix: None,
value: DecimalNumber {
span: Span::new(&source, 62, 63).unwrap()
},
span: Span::new(&source, 62, 63).unwrap() span: Span::new(&source, 62, 63).unwrap()
}, }
span: Span::new(&source, 62, 63).unwrap() )),
} Expression::Literal(LiteralExpression::DecimalLiteral(
)), DecimalLiteralExpression {
Expression::Literal(LiteralExpression::DecimalLiteral( suffix: None,
DecimalLiteralExpression { value: DecimalNumber {
suffix: None, span: Span::new(&source, 69, 70).unwrap()
value: DecimalNumber { },
span: Span::new(&source, 69, 70).unwrap() span: Span::new(&source, 69, 70).unwrap()
}, }
span: Span::new(&source, 69, 70).unwrap() )),
} Expression::Literal(LiteralExpression::DecimalLiteral(
)), DecimalLiteralExpression {
Expression::Literal(LiteralExpression::DecimalLiteral( suffix: None,
DecimalLiteralExpression { value: DecimalNumber {
suffix: None, span: Span::new(&source, 76, 77).unwrap()
value: DecimalNumber { },
span: Span::new(&source, 76, 77).unwrap() span: Span::new(&source, 76, 77).unwrap()
}, }
span: Span::new(&source, 76, 77).unwrap() )),
} Span::new(&source, 59, 80).unwrap()
)), )],
Span::new(&source, 59, 80).unwrap() span: Span::new(&source, 52, 80).unwrap(),
)], })],
span: Span::new(&source, 52, 80).unwrap(), span: Span::new(&source, 29, 81).unwrap(),
})], })
span: Span::new(&source, 29, 81).unwrap(), ],
}],
imports: vec![ImportDirective::Main(MainImportDirective {
source: ImportSource {
value: String::from("foo"),
span: Span::new(&source, 8, 11).unwrap()
},
alias: None,
span: Span::new(&source, 0, 29).unwrap()
})],
eoi: EOI {}, eoi: EOI {},
span: Span::new(&source, 0, 81).unwrap() span: Span::new(&source, 0, 81).unwrap()
}) })
@ -1272,9 +1280,7 @@ mod tests {
generate_ast(&source), generate_ast(&source),
Ok(File { Ok(File {
pragma: None, pragma: None,
structs: vec![], declarations: vec![SymbolDeclaration::Function(FunctionDefinition {
constants: vec![],
functions: vec![Function {
generics: vec![], generics: vec![],
id: IdentifierExpression { id: IdentifierExpression {
value: String::from("main"), value: String::from("main"),
@ -1297,8 +1303,7 @@ mod tests {
span: Span::new(&source, 23, 33).unwrap(), span: Span::new(&source, 23, 33).unwrap(),
})], })],
span: Span::new(&source, 0, 34).unwrap(), span: Span::new(&source, 0, 34).unwrap(),
}], })],
imports: vec![],
eoi: EOI {}, eoi: EOI {},
span: Span::new(&source, 0, 34).unwrap() span: Span::new(&source, 0, 34).unwrap()
}) })
@ -1313,9 +1318,7 @@ mod tests {
generate_ast(&source), generate_ast(&source),
Ok(File { Ok(File {
pragma: None, pragma: None,
structs: vec![], declarations: vec![SymbolDeclaration::Function(FunctionDefinition {
constants: vec![],
functions: vec![Function {
generics: vec![], generics: vec![],
id: IdentifierExpression { id: IdentifierExpression {
value: String::from("main"), value: String::from("main"),
@ -1403,8 +1406,7 @@ mod tests {
span: Span::new(&source, 23, 49).unwrap() span: Span::new(&source, 23, 49).unwrap()
})], })],
span: Span::new(&source, 0, 50).unwrap(), span: Span::new(&source, 0, 50).unwrap(),
}], })],
imports: vec![],
eoi: EOI {}, eoi: EOI {},
span: Span::new(&source, 0, 50).unwrap() span: Span::new(&source, 0, 50).unwrap()
}) })

View file

@ -1,7 +1,7 @@
// https://tools.ietf.org/html/rfc7693 // https://tools.ietf.org/html/rfc7693
import "EMBED/u32_to_bits" as to_bits import "utils/casts/u32_to_bits"
import "EMBED/u32_from_bits" as from_bits import "utils/casts/u32_from_bits"
def rotr32<N>(u32 x) -> u32: def rotr32<N>(u32 x) -> u32:
return (x >> N) | (x << (32 - N)) return (x >> N) | (x << (32 - N))

View file

@ -1,6 +1,6 @@
import "./512bitBool.zok" as pedersen import "./512bitBool.zok" as pedersen
import "EMBED/u32_to_bits" as to_bits import "utils/casts/u32_to_bits" as to_bits
import "EMBED/u32_from_bits" as from_bits import "utils/casts/u32_from_bits" as from_bits
def main(u32[16] inputs) -> u32[8]: def main(u32[16] inputs) -> u32[8]:
bool[512] e = [\ bool[512] e = [\

View file

@ -1,5 +1,5 @@
#pragma curve bn128 #pragma curve bn128
import "EMBED/sha256round" as sha256round from "EMBED" import sha256round
// a and b is NOT checked to be 0 or 1 // a and b is NOT checked to be 0 or 1
// the return value is checked to be 0 or 1 // the return value is checked to be 0 or 1

View file

@ -1,4 +1,4 @@
import "EMBED/u32_from_bits" as from_bits from "EMBED" import u32_from_bits
// convert an array of bool to an array of u32 // convert an array of bool to an array of u32
// the sizes must match (one u32 for 32 bool) otherwise an error will happen // the sizes must match (one u32 for 32 bool) otherwise an error will happen
@ -9,7 +9,7 @@ def main<N, P>(bool[N] bits) -> u32[P]:
u32[P] res = [0; P] u32[P] res = [0; P]
for u32 i in 0..P do for u32 i in 0..P do
res[i] = from_bits(bits[32 * i..32 * (i + 1)]) res[i] = u32_from_bits(bits[32 * i..32 * (i + 1)])
endfor endfor
return res return res

View file

@ -1,6 +1,5 @@
import "EMBED/unpack" as unpack from "EMBED" import unpack, u16_from_bits
import "EMBED/u16_from_bits" as from_bits
def main(field i) -> u16: def main(field i) -> u16:
bool[16] bits = unpack(i) bool[16] bits = unpack(i)
return from_bits(bits) return u16_from_bits(bits)

View file

@ -1,6 +1,5 @@
import "EMBED/unpack" as unpack from "EMBED" import unpack, u32_from_bits
import "EMBED/u32_from_bits" as from_bits
def main(field i) -> u32: def main(field i) -> u32:
bool[32] bits = unpack(i) bool[32] bits = unpack(i)
return from_bits(bits) return u32_from_bits(bits)

View file

@ -1,6 +1,5 @@
import "EMBED/unpack" as unpack from "EMBED" import unpack, u64_from_bits
import "EMBED/u64_from_bits" as from_bits
def main(field i) -> u64: def main(field i) -> u64:
bool[64] bits = unpack(i) bool[64] bits = unpack(i)
return from_bits(bits) return u64_from_bits(bits)

View file

@ -1,6 +1,5 @@
import "EMBED/unpack" as unpack from "EMBED" import unpack, u8_from_bits
import "EMBED/u8_from_bits" as from_bits
def main(field i) -> u8: def main(field i) -> u8:
bool[8] bits = unpack(i) bool[8] bits = unpack(i)
return from_bits(bits) return u8_from_bits(bits)

View file

@ -1,4 +1,4 @@
import "EMBED/u16_from_bits" as from_bits from "EMBED" import u16_from_bits
def main(bool[16] a) -> u16: def main(bool[16] a) -> u16:
return from_bits(a) return u16_from_bits(a)

View file

@ -1,4 +1,4 @@
import "EMBED/u16_to_bits" as to_bits from "EMBED" import u16_to_bits
def main(u16 a) -> bool[16]: def main(u16 a) -> bool[16]:
return to_bits(a) return u16_to_bits(a)

View file

@ -1,7 +1,7 @@
import "EMBED/u16_to_bits" as to_bits from "EMBED" import u16_to_bits
def main(u16 i) -> field: def main(u16 i) -> field:
bool[16] bits = to_bits(i) bool[16] bits = u16_to_bits(i)
field res = 0 field res = 0
for u32 j in 0..16 do for u32 j in 0..16 do
u32 exponent = 16 - j - 1 u32 exponent = 16 - j - 1

View file

@ -1,4 +1,4 @@
import "EMBED/u32_to_bits" as to_bits from "EMBED" import u32_to_bits
def main<N, P>(u32[N] input) -> bool[P]: def main<N, P>(u32[N] input) -> bool[P]:
assert(P == 32 * N) assert(P == 32 * N)
@ -6,7 +6,7 @@ def main<N, P>(u32[N] input) -> bool[P]:
bool[P] res = [false; P] bool[P] res = [false; P]
for u32 i in 0..N do for u32 i in 0..N do
bool[32] bits = to_bits(input[i]) bool[32] bits = u32_to_bits(input[i])
for u32 j in 0..32 do for u32 j in 0..32 do
res[i * 32 + j] = bits[j] res[i * 32 + j] = bits[j]
endfor endfor

View file

@ -1,4 +1,4 @@
import "EMBED/u32_from_bits" as from_bits from "EMBED" import u32_from_bits
def main(bool[32] a) -> u32: def main(bool[32] a) -> u32:
return from_bits(a) return u32_from_bits(a)

View file

@ -1,4 +1,4 @@
import "EMBED/u32_to_bits" as to_bits from "EMBED" import u32_to_bits
def main(u32 a) -> bool[32]: def main(u32 a) -> bool[32]:
return to_bits(a) return u32_to_bits(a)

View file

@ -1,7 +1,7 @@
import "EMBED/u32_to_bits" as to_bits from "EMBED" import u32_to_bits
def main(u32 i) -> field: def main(u32 i) -> field:
bool[32] bits = to_bits(i) bool[32] bits = u32_to_bits(i)
field res = 0 field res = 0
for u32 j in 0..32 do for u32 j in 0..32 do
u32 exponent = 32 - j - 1 u32 exponent = 32 - j - 1

View file

@ -1,4 +1,4 @@
import "EMBED/u64_from_bits" as from_bits from "EMBED" import u64_from_bits
def main(bool[64] a) -> u64: def main(bool[64] a) -> u64:
return from_bits(a) return u64_from_bits(a)

View file

@ -1,4 +1,4 @@
import "EMBED/u64_to_bits" as to_bits from "EMBED" import u64_to_bits
def main(u64 a) -> bool[64]: def main(u64 a) -> bool[64]:
return to_bits(a) return u64_to_bits(a)

View file

@ -1,7 +1,7 @@
import "EMBED/u64_to_bits" as to_bits from "EMBED" import u64_to_bits
def main(u64 i) -> field: def main(u64 i) -> field:
bool[64] bits = to_bits(i) bool[64] bits = u64_to_bits(i)
field res = 0 field res = 0
for u32 j in 0..64 do for u32 j in 0..64 do
u32 exponent = 64 - j - 1 u32 exponent = 64 - j - 1

View file

@ -1,4 +1,4 @@
import "EMBED/u8_from_bits" as from_bits from "EMBED" import u8_from_bits
def main(bool[8] a) -> u8: def main(bool[8] a) -> u8:
return from_bits(a) return u8_from_bits(a)

View file

@ -1,4 +1,4 @@
import "EMBED/u8_to_bits" as to_bits from "EMBED" import u8_to_bits
def main(u8 a) -> bool[8]: def main(u8 a) -> bool[8]:
return to_bits(a) return u8_to_bits(a)

View file

@ -1,7 +1,7 @@
import "EMBED/u8_to_bits" as to_bits from "EMBED" import u8_to_bits
def main(u8 i) -> field: def main(u8 i) -> field:
bool[8] bits = to_bits(i) bool[8] bits = u8_to_bits(i)
field res = 0 field res = 0
for u32 j in 0..8 do for u32 j in 0..8 do
u32 exponent = 8 - j - 1 u32 exponent = 8 - j - 1

View file

@ -1,12 +1,12 @@
#pragma curve bn128 #pragma curve bn128
import "EMBED/unpack" as unpack import "./unpack" as unpack
// Unpack a field element as 256 big-endian bits // Unpack a field element as 256 big-endian bits
// Note: uniqueness of the output is not guaranteed // Note: uniqueness of the output is not guaranteed
// For example, `0` can map to `[0, 0, ..., 0]` or to `bits(p)` // For example, `0` can map to `[0, 0, ..., 0]` or to `bits(p)`
def main(field i) -> bool[256]: def main(field i) -> bool[256]:
bool[254] b = unpack(i) bool[254] b = unpack::<254>(i)
return [false, false, ...b] return [false, false, ...b]

View file

@ -1,6 +1,6 @@
#pragma curve bn128 #pragma curve bn128
import "EMBED/unpack" as unpack from "EMBED" import unpack
// Unpack a field element as N big endian bits // Unpack a field element as N big endian bits
def main<N>(field i) -> bool[N]: def main<N>(field i) -> bool[N]:

View file

@ -1,11 +1,20 @@
import "EMBED/u32_to_bits" as to_bits import "../../casts/u32_to_bits"
from "../bool/pack256.zok" import main as pack256 import "../bool/pack256"
// pack 256 big-endian bits into one field element // pack 256 big-endian bits into one field element
// Note: This is not a injective operation as `p` is smaller than `2**256 - 1 for bn128 // Note: This is not a injective operation as `p` is smaller than `2**256 - 1 for bn128
// For example, `[0, 0,..., 0]` and `bits(p)` both point to `0` // For example, `[0, 0,..., 0]` and `bits(p)` both point to `0`
def main(u32[8] input) -> field: def main(u32[8] input) -> field:
bool[256] bits = [...to_bits(input[0]), ...to_bits(input[1]), ...to_bits(input[2]), ...to_bits(input[3]), ...to_bits(input[4]), ...to_bits(input[5]), ...to_bits(input[6]), ...to_bits(input[7])] bool[256] bits = [
...u32_to_bits(input[0]),
...u32_to_bits(input[1]),
...u32_to_bits(input[2]),
...u32_to_bits(input[3]),
...u32_to_bits(input[4]),
...u32_to_bits(input[5]),
...u32_to_bits(input[6]),
...u32_to_bits(input[7])
]
return pack256(bits) return pack256(bits)