From 8969dde2b70272c27f0dc5af436b14356c85e55c Mon Sep 17 00:00:00 2001 From: Matthias Goergens Date: Tue, 26 Nov 2024 09:50:00 +0800 Subject: [PATCH] Same formatting --- .github/workflows/ci.yml | 2 +- circ_blocks/circ_fields/src/ext_field.rs | 2 +- circ_blocks/circ_fields/src/ff_field.rs | 8 +- circ_blocks/circ_fields/src/int_field.rs | 10 +- circ_blocks/circ_fields/src/lib.rs | 14 +- circ_blocks/circ_fields/src/test.rs | 3 +- circ_blocks/circ_hc/examples/u32.rs | 2 +- .../circ_hc/src/hashconsing/example_u8.rs | 3 +- circ_blocks/circ_hc/src/hashconsing/macro_.rs | 3 +- .../circ_hc/src/hashconsing/template.rs | 3 +- circ_blocks/circ_hc/src/lib.rs | 6 +- circ_blocks/circ_hc/src/raw/example_u8.rs | 8 +- circ_blocks/circ_hc/src/raw/macro_.rs | 8 +- circ_blocks/circ_hc/src/raw/template.rs | 10 +- circ_blocks/circ_hc/src/rc/example_u8.rs | 16 +- circ_blocks/circ_hc/src/rc/macro_.rs | 16 +- circ_blocks/circ_hc/src/rc/template.rs | 18 +- circ_blocks/circ_hc/src/test/bench.rs | 2 +- circ_blocks/circ_hc/src/test/gc_hook.rs | 4 +- circ_blocks/circ_hc/src/test/mod.rs | 2 +- circ_blocks/circ_waksman/src/lib.rs | 16 +- circ_blocks/examples/cp.rs | 13 +- circ_blocks/examples/opa_bench.rs | 12 +- circ_blocks/examples/zk.rs | 2 +- circ_blocks/examples/zxc.rs | 172 +++++++++--------- circ_blocks/src/cfg.rs | 7 +- circ_blocks/src/circify/includer.rs | 6 +- circ_blocks/src/circify/mem.rs | 3 +- circ_blocks/src/circify/mod.rs | 43 +++-- circ_blocks/src/front/c/ast_utils.rs | 8 +- circ_blocks/src/front/c/cvisit/cvmut.rs | 6 +- circ_blocks/src/front/c/mod.rs | 37 ++-- circ_blocks/src/front/c/parser.rs | 3 +- circ_blocks/src/front/c/term.rs | 16 +- circ_blocks/src/front/c/types.rs | 13 +- circ_blocks/src/front/datalog/error.rs | 9 +- circ_blocks/src/front/datalog/mod.rs | 22 +-- circ_blocks/src/front/datalog/parser.rs | 15 +- circ_blocks/src/front/datalog/term.rs | 11 +- circ_blocks/src/front/mod.rs | 6 +- circ_blocks/src/front/zsharp/blocks.rs | 41 +++-- .../src/front/zsharp/blocks_optimization.rs | 49 ++--- circ_blocks/src/front/zsharp/interp.rs | 2 +- circ_blocks/src/front/zsharp/mod.rs | 151 +++++++-------- circ_blocks/src/front/zsharp/parser.rs | 11 +- circ_blocks/src/front/zsharp/prover.rs | 85 +++++---- circ_blocks/src/front/zsharp/term.rs | 23 ++- circ_blocks/src/front/zsharp/zvisit/eqtype.rs | 3 +- .../src/front/zsharp/zvisit/zconstlitrw.rs | 69 ++++--- .../src/front/zsharp/zvisit/zgenericinf.rs | 22 +-- .../front/zsharp/zvisit/zstmtwalker/mod.rs | 20 +- .../zsharp/zvisit/zstmtwalker/zexprtyper.rs | 7 +- circ_blocks/src/front/zsharp/zvisit/zvmut.rs | 3 +- circ_blocks/src/ir/opt/cfold.rs | 12 +- circ_blocks/src/ir/opt/chall.rs | 11 +- circ_blocks/src/ir/opt/inline.rs | 13 +- circ_blocks/src/ir/opt/link.rs | 3 +- circ_blocks/src/ir/opt/mem/lin.rs | 8 +- circ_blocks/src/ir/opt/mem/obliv.rs | 5 +- circ_blocks/src/ir/opt/mem/ram.rs | 4 +- circ_blocks/src/ir/opt/mem/ram/checker.rs | 6 +- .../src/ir/opt/mem/ram/checker/permutation.rs | 10 +- circ_blocks/src/ir/opt/mem/ram/checker/rom.rs | 12 +- circ_blocks/src/ir/opt/mem/ram/hash.rs | 2 +- circ_blocks/src/ir/opt/mem/ram/persistent.rs | 3 +- circ_blocks/src/ir/opt/mem/ram/volatile.rs | 4 +- circ_blocks/src/ir/opt/mod.rs | 2 +- circ_blocks/src/ir/opt/scalarize_vars.rs | 3 +- circ_blocks/src/ir/opt/tuple.rs | 4 +- circ_blocks/src/ir/term/bv.rs | 6 +- circ_blocks/src/ir/term/dist.rs | 5 +- circ_blocks/src/ir/term/ext.rs | 3 +- circ_blocks/src/ir/term/ext/haboeck.rs | 3 +- circ_blocks/src/ir/term/ext/map.rs | 3 +- circ_blocks/src/ir/term/ext/poly.rs | 3 +- circ_blocks/src/ir/term/ext/ram.rs | 3 +- circ_blocks/src/ir/term/ext/sort.rs | 3 +- circ_blocks/src/ir/term/ext/waksman.rs | 5 +- circ_blocks/src/ir/term/fmt.rs | 4 +- circ_blocks/src/ir/term/lin.rs | 1 - circ_blocks/src/ir/term/mod.rs | 75 +++----- circ_blocks/src/ir/term/test.rs | 156 +++++++--------- circ_blocks/src/ir/term/text/mod.rs | 8 +- circ_blocks/src/ir/term/ty.rs | 3 +- circ_blocks/src/target/aby/assignment/ilp.rs | 5 +- circ_blocks/src/target/aby/trans.rs | 35 ++-- circ_blocks/src/target/aby/utils.rs | 8 +- circ_blocks/src/target/ilp/mod.rs | 4 +- circ_blocks/src/target/ilp/trans.rs | 29 ++- circ_blocks/src/target/r1cs/bellman.rs | 29 +-- circ_blocks/src/target/r1cs/mirage.rs | 23 +-- circ_blocks/src/target/r1cs/mod.rs | 13 +- circ_blocks/src/target/r1cs/opt.rs | 3 +- circ_blocks/src/target/r1cs/proof.rs | 20 +- circ_blocks/src/target/r1cs/spartan.rs | 20 +- circ_blocks/src/target/r1cs/trans.rs | 38 ++-- circ_blocks/src/target/r1cs/wit_comp.rs | 13 +- circ_blocks/src/target/smt/mod.rs | 22 ++- circ_blocks/src/util/once.rs | 3 +- .../ZoKrates/zokrates_parser/src/lib.rs | 7 +- .../ZoKrates/zokrates_pest_ast/src/lib.rs | 32 ++-- .../ZoKrates/zokrates_stdlib/build.rs | 3 +- ff/ff_derive/src/lib.rs | 27 ++- ff/ff_derive/src/pow_fixed.rs | 2 +- ff/src/lib.rs | 10 +- zok_tests/poseidon_gen/src/poseidon_gen.rs | 3 +- 106 files changed, 866 insertions(+), 912 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 46e7420f..dc7e4291 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -51,7 +51,7 @@ jobs: for cargo_toml in $(git ls-files '**/Cargo.toml'); do ( cd "$(dirname ${cargo_toml})" - cargo fmt --check + cargo +nightly fmt --check cargo check --all-targets ) done diff --git a/circ_blocks/circ_fields/src/ext_field.rs b/circ_blocks/circ_fields/src/ext_field.rs index 4534c1e0..44c8e97e 100644 --- a/circ_blocks/circ_fields/src/ext_field.rs +++ b/circ_blocks/circ_fields/src/ext_field.rs @@ -1,6 +1,6 @@ use ff::{ - derive::subtle::{Choice, ConditionallySelectable, ConstantTimeEq}, Field, + derive::subtle::{Choice, ConditionallySelectable, ConstantTimeEq}, }; use rand::RngCore; use serde::{Deserialize, Serialize}; diff --git a/circ_blocks/circ_fields/src/ff_field.rs b/circ_blocks/circ_fields/src/ff_field.rs index 0619945f..c146463a 100644 --- a/circ_blocks/circ_fields/src/ff_field.rs +++ b/circ_blocks/circ_fields/src/ff_field.rs @@ -85,11 +85,7 @@ macro_rules! def_field { fn from(mut i: i64) -> Self { let u = i.abs_diff(0); let neg = i < 0; - if neg { - -Ft::from(u) - } else { - Ft::from(u) - } + if neg { -Ft::from(u) } else { Ft::from(u) } } } @@ -100,7 +96,7 @@ macro_rules! def_field { #[cfg(test)] mod test { - use super::{Ft, FMOD}; + use super::{FMOD, Ft}; use ff::Field; use rand::thread_rng; use rug::Integer; diff --git a/circ_blocks/circ_fields/src/int_field.rs b/circ_blocks/circ_fields/src/int_field.rs index 89c8d38d..0848d14d 100644 --- a/circ_blocks/circ_fields/src/int_field.rs +++ b/circ_blocks/circ_fields/src/int_field.rs @@ -4,13 +4,15 @@ use datasize::DataSize; use paste::paste; use rug::{ - ops::{RemRounding, RemRoundingAssign}, Integer, + ops::{RemRounding, RemRoundingAssign}, }; use serde::{Deserialize, Serialize}; -use std::fmt::{self, Display, Formatter}; -use std::ops::Deref; -use std::sync::Arc; +use std::{ + fmt::{self, Display, Formatter}, + ops::Deref, + sync::Arc, +}; #[derive(PartialEq, Eq, Clone, Debug, PartialOrd, Ord, Hash, Serialize, Deserialize, DataSize)] pub struct IntField { diff --git a/circ_blocks/circ_fields/src/lib.rs b/circ_blocks/circ_fields/src/lib.rs index 8c0c9789..7b74c810 100644 --- a/circ_blocks/circ_fields/src/lib.rs +++ b/circ_blocks/circ_fields/src/lib.rs @@ -14,10 +14,10 @@ pub mod moduli { } use ext_field::FGoldilocksExt2; -use ff_field::{FBls12381, FBn254, FCurve25519, FGoldilocks}; -use ff_field::{F_BLS12381_FMOD, F_BN254_FMOD, F_CURVE25519_FMOD, F_GOLDILOCKS_FMOD}; use ff_field::{ - F_BLS12381_FMOD_ARC, F_BN254_FMOD_ARC, F_CURVE25519_FMOD_ARC, F_GOLDILOCKS_FMOD_ARC, + F_BLS12381_FMOD, F_BLS12381_FMOD_ARC, F_BN254_FMOD, F_BN254_FMOD_ARC, F_CURVE25519_FMOD, + F_CURVE25519_FMOD_ARC, F_GOLDILOCKS_FMOD, F_GOLDILOCKS_FMOD_ARC, FBls12381, FBn254, + FCurve25519, FGoldilocks, }; use int_field::IntField; @@ -26,9 +26,11 @@ use ff::Field; use paste::paste; use rug::Integer; use serde::{Deserialize, Serialize}; -use std::fmt::{self, Debug, Display, Formatter}; -use std::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign}; -use std::sync::Arc; +use std::{ + fmt::{self, Debug, Display, Formatter}, + ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign}, + sync::Arc, +}; // TODO: rework this using macros? diff --git a/circ_blocks/circ_fields/src/test.rs b/circ_blocks/circ_fields/src/test.rs index 76b2756c..cf3fad45 100644 --- a/circ_blocks/circ_fields/src/test.rs +++ b/circ_blocks/circ_fields/src/test.rs @@ -1,6 +1,5 @@ use super::*; -use rand::thread_rng; -use rand::Rng; +use rand::{Rng, thread_rng}; use rug::ops::RemRounding; #[test] diff --git a/circ_blocks/circ_hc/examples/u32.rs b/circ_blocks/circ_hc/examples/u32.rs index c8ef41aa..afe6bbb3 100644 --- a/circ_blocks/circ_hc/examples/u32.rs +++ b/circ_blocks/circ_hc/examples/u32.rs @@ -1,4 +1,4 @@ -use circ_hc::{generate_hashcons_rc, Node as NodeTrait, Table as TableTrait}; +use circ_hc::{Node as NodeTrait, Table as TableTrait, generate_hashcons_rc}; generate_hashcons_rc!(u32); diff --git a/circ_blocks/circ_hc/src/hashconsing/example_u8.rs b/circ_blocks/circ_hc/src/hashconsing/example_u8.rs index d39c5928..2f9500ce 100644 --- a/circ_blocks/circ_hc/src/hashconsing/example_u8.rs +++ b/circ_blocks/circ_hc/src/hashconsing/example_u8.rs @@ -1,6 +1,5 @@ // Warning: this file is generated from src/template.rs and generate_u8.zsh -use hashconsing::*; -use hashconsing::{HConsed, HashConsign}; +use hashconsing::{HConsed, HashConsign, *}; use crate::Id; diff --git a/circ_blocks/circ_hc/src/hashconsing/macro_.rs b/circ_blocks/circ_hc/src/hashconsing/macro_.rs index 1ad72535..ca9e768d 100644 --- a/circ_blocks/circ_hc/src/hashconsing/macro_.rs +++ b/circ_blocks/circ_hc/src/hashconsing/macro_.rs @@ -2,8 +2,7 @@ #[macro_export] macro_rules! generate_hashcons_hashconsing { ($Op:ty) => { - use hashconsing::*; - use hashconsing::{HConsed, HashConsign}; + use hashconsing::{HConsed, HashConsign, *}; use $crate::Id; diff --git a/circ_blocks/circ_hc/src/hashconsing/template.rs b/circ_blocks/circ_hc/src/hashconsing/template.rs index 2e503136..4dfe91b1 100644 --- a/circ_blocks/circ_hc/src/hashconsing/template.rs +++ b/circ_blocks/circ_hc/src/hashconsing/template.rs @@ -1,5 +1,4 @@ -use hashconsing::*; -use hashconsing::{HConsed, HashConsign}; +use hashconsing::{HConsed, HashConsign, *}; use std::net::SocketAddrV6 as TemplateOp; diff --git a/circ_blocks/circ_hc/src/lib.rs b/circ_blocks/circ_hc/src/lib.rs index f1ac85c6..68c0cc54 100644 --- a/circ_blocks/circ_hc/src/lib.rs +++ b/circ_blocks/circ_hc/src/lib.rs @@ -1,5 +1,7 @@ -use std::cmp::{Eq, Ord, PartialEq, PartialOrd}; -use std::hash::Hash; +use std::{ + cmp::{Eq, Ord, PartialEq, PartialOrd}, + hash::Hash, +}; #[cfg(feature = "hashconsing")] pub mod hashconsing; diff --git a/circ_blocks/circ_hc/src/raw/example_u8.rs b/circ_blocks/circ_hc/src/raw/example_u8.rs index 39875eae..35656ae1 100644 --- a/circ_blocks/circ_hc/src/raw/example_u8.rs +++ b/circ_blocks/circ_hc/src/raw/example_u8.rs @@ -1,9 +1,11 @@ // Warning: this file is generated from src/template.rs and generate_u8.zsh use fxhash::{FxHashMap as HashMap, FxHashSet as HashSet}; -use std::cell::{Cell, RefCell}; -use std::rc::Rc; -use std::thread_local; +use std::{ + cell::{Cell, RefCell}, + rc::Rc, + thread_local, +}; use crate::Id; diff --git a/circ_blocks/circ_hc/src/raw/macro_.rs b/circ_blocks/circ_hc/src/raw/macro_.rs index c11f1898..75b53770 100644 --- a/circ_blocks/circ_hc/src/raw/macro_.rs +++ b/circ_blocks/circ_hc/src/raw/macro_.rs @@ -4,9 +4,11 @@ macro_rules! generate_hashcons_raw { ($Op:ty) => { use fxhash::{FxHashMap as HashMap, FxHashSet as HashSet}; - use std::cell::{Cell, RefCell}; - use std::rc::Rc; - use std::thread_local; + use std::{ + cell::{Cell, RefCell}, + rc::Rc, + thread_local, + }; use $crate::Id; diff --git a/circ_blocks/circ_hc/src/raw/template.rs b/circ_blocks/circ_hc/src/raw/template.rs index e0a9a29a..5b529ef9 100644 --- a/circ_blocks/circ_hc/src/raw/template.rs +++ b/circ_blocks/circ_hc/src/raw/template.rs @@ -1,9 +1,11 @@ use fxhash::{FxHashMap as HashMap, FxHashSet as HashSet}; -use std::cell::{Cell, RefCell}; -use std::net::SocketAddrV6 as TemplateOp; -use std::rc::Rc; -use std::thread_local; +use std::{ + cell::{Cell, RefCell}, + net::SocketAddrV6 as TemplateOp, + rc::Rc, + thread_local, +}; use crate::Id; diff --git a/circ_blocks/circ_hc/src/rc/example_u8.rs b/circ_blocks/circ_hc/src/rc/example_u8.rs index dd43e516..771104bf 100644 --- a/circ_blocks/circ_hc/src/rc/example_u8.rs +++ b/circ_blocks/circ_hc/src/rc/example_u8.rs @@ -3,10 +3,12 @@ use fxhash::FxHashMap as HashMap; use crate::Id; use log::trace; -use std::borrow::Borrow; -use std::cell::{Cell, RefCell}; -use std::rc::Rc; -use std::thread_local; +use std::{ + borrow::Borrow, + cell::{Cell, RefCell}, + rc::Rc, + thread_local, +}; #[allow(dead_code)] struct NodeData { @@ -297,8 +299,10 @@ impl crate::Weak for Weak { mod hash { use super::{Node, NodeData, NodeDataRef, Weak}; - use std::borrow::Borrow; - use std::hash::{Hash, Hasher}; + use std::{ + borrow::Borrow, + hash::{Hash, Hasher}, + }; impl Hash for Node { fn hash(&self, state: &mut H) { diff --git a/circ_blocks/circ_hc/src/rc/macro_.rs b/circ_blocks/circ_hc/src/rc/macro_.rs index 092f23dd..56e88efe 100644 --- a/circ_blocks/circ_hc/src/rc/macro_.rs +++ b/circ_blocks/circ_hc/src/rc/macro_.rs @@ -5,10 +5,12 @@ macro_rules! generate_hashcons_rc { use fxhash::FxHashMap as HashMap; use log::trace; - use std::borrow::Borrow; - use std::cell::{Cell, RefCell}; - use std::rc::Rc; - use std::thread_local; + use std::{ + borrow::Borrow, + cell::{Cell, RefCell}, + rc::Rc, + thread_local, + }; use $crate::Id; #[allow(dead_code)] @@ -300,8 +302,10 @@ macro_rules! generate_hashcons_rc { mod hash { use super::{Node, NodeData, NodeDataRef, Weak}; - use std::borrow::Borrow; - use std::hash::{Hash, Hasher}; + use std::{ + borrow::Borrow, + hash::{Hash, Hasher}, + }; impl Hash for Node { fn hash(&self, state: &mut H) { diff --git a/circ_blocks/circ_hc/src/rc/template.rs b/circ_blocks/circ_hc/src/rc/template.rs index 4fb49225..5d3b6857 100644 --- a/circ_blocks/circ_hc/src/rc/template.rs +++ b/circ_blocks/circ_hc/src/rc/template.rs @@ -2,11 +2,13 @@ use fxhash::FxHashMap as HashMap; use crate::Id; use log::trace; -use std::borrow::Borrow; -use std::cell::{Cell, RefCell}; -use std::net::SocketAddrV6 as TemplateOp; -use std::rc::Rc; -use std::thread_local; +use std::{ + borrow::Borrow, + cell::{Cell, RefCell}, + net::SocketAddrV6 as TemplateOp, + rc::Rc, + thread_local, +}; #[allow(dead_code)] struct NodeData { @@ -297,8 +299,10 @@ impl crate::Weak for Weak { mod hash { use super::{Node, NodeData, NodeDataRef, Weak}; - use std::borrow::Borrow; - use std::hash::{Hash, Hasher}; + use std::{ + borrow::Borrow, + hash::{Hash, Hasher}, + }; impl Hash for Node { fn hash(&self, state: &mut H) { diff --git a/circ_blocks/circ_hc/src/test/bench.rs b/circ_blocks/circ_hc/src/test/bench.rs index 63cdae2a..d568b0bf 100644 --- a/circ_blocks/circ_hc/src/test/bench.rs +++ b/circ_blocks/circ_hc/src/test/bench.rs @@ -6,7 +6,7 @@ fn test_rng() -> ChaChaRng { use crate::{Node, Table}; -use rand::{distributions::Distribution, Rng, SeedableRng}; +use rand::{Rng, SeedableRng, distributions::Distribution}; use rand_distr::Geometric; use std::time::{Duration, Instant}; diff --git a/circ_blocks/circ_hc/src/test/gc_hook.rs b/circ_blocks/circ_hc/src/test/gc_hook.rs index 603ca945..9e57a81e 100644 --- a/circ_blocks/circ_hc/src/test/gc_hook.rs +++ b/circ_blocks/circ_hc/src/test/gc_hook.rs @@ -1,7 +1,5 @@ use crate::{Id, Node, Table}; -use std::cell::RefCell; -use std::collections::HashMap; -use std::rc::Rc; +use std::{cell::RefCell, collections::HashMap, rc::Rc}; /// One step in the test. #[derive(Debug)] diff --git a/circ_blocks/circ_hc/src/test/mod.rs b/circ_blocks/circ_hc/src/test/mod.rs index 53b48198..a1c225ba 100644 --- a/circ_blocks/circ_hc/src/test/mod.rs +++ b/circ_blocks/circ_hc/src/test/mod.rs @@ -167,7 +167,7 @@ mod rc { crate::rc::generate_hashcons!(u8); } use hc_u8::Table; - //use crate::rc::example_u8::Table; + // use crate::rc::example_u8::Table; mod tiny { #[test] diff --git a/circ_blocks/circ_waksman/src/lib.rs b/circ_blocks/circ_waksman/src/lib.rs index 229ab663..1a85d721 100644 --- a/circ_blocks/circ_waksman/src/lib.rs +++ b/circ_blocks/circ_waksman/src/lib.rs @@ -4,12 +4,10 @@ //! //! Reference: "On Arbitrary Waksman Networks and their Vulnerability", by Bruno Beauquier and Eric Darrot. -use fxhash::FxHashMap as HashMap; -use fxhash::FxHashSet as HashSet; +use fxhash::{FxHashMap as HashMap, FxHashSet as HashSet}; use std::collections::VecDeque; -use std::fmt::Debug; -use std::hash::Hash; +use std::{fmt::Debug, hash::Hash}; #[derive(Debug, Clone)] /// A network configuration @@ -268,9 +266,7 @@ pub fn symbolic_apply (T, T)>( mod tests { use super::*; use itertools::Itertools; - use rand::seq::SliceRandom; - use rand::Rng; - use rand::SeedableRng; + use rand::{Rng, SeedableRng, seq::SliceRandom}; fn test_on_data(data: Vec) { let cfg = Config::for_sorting(data.clone()); @@ -417,11 +413,7 @@ mod tests { data, &mut switches, &mut |top: &usize, bot: &usize, cond: bool| { - if cond { - (*bot, *top) - } else { - (*top, *bot) - } + if cond { (*bot, *top) } else { (*top, *bot) } }, ); assert_eq!(apply_normal, apply_sym); diff --git a/circ_blocks/examples/cp.rs b/circ_blocks/examples/cp.rs index ee4de323..fd6b5716 100644 --- a/circ_blocks/examples/cp.rs +++ b/circ_blocks/examples/cp.rs @@ -1,6 +1,6 @@ use circ::cfg::{ - clap::{self, Parser, ValueEnum}, CircOpt, + clap::{self, Parser, ValueEnum}, }; use std::path::PathBuf; @@ -59,13 +59,10 @@ fn main() { Mirage::cp_prove_fs(&opts.prover_key, &opts.inputs, &opts.proof, opts.rands).unwrap(); } ProofAction::Verify => { - assert!(Mirage::cp_verify_fs( - &opts.verifier_key, - &opts.inputs, - &opts.proof, - opts.commits - ) - .unwrap()); + assert!( + Mirage::cp_verify_fs(&opts.verifier_key, &opts.inputs, &opts.proof, opts.commits) + .unwrap() + ); } ProofAction::Commit => { assert_eq!( diff --git a/circ_blocks/examples/opa_bench.rs b/circ_blocks/examples/opa_bench.rs index ffe07b5b..3945689d 100644 --- a/circ_blocks/examples/opa_bench.rs +++ b/circ_blocks/examples/opa_bench.rs @@ -1,7 +1,9 @@ -use circ::cfg::clap::{self, Parser}; -use circ::ir::term::*; -use circ::target::aby::assignment::ilp; -use circ::term; +use circ::{ + cfg::clap::{self, Parser}, + ir::term::*, + target::aby::assignment::ilp, + term, +}; #[derive(Debug, Parser)] #[command( @@ -30,5 +32,5 @@ fn main() { ..Default::default() }; let _assignment = ilp::assign(&cs, "hycc"); - //dbg!(&assignment); + // dbg!(&assignment); } diff --git a/circ_blocks/examples/zk.rs b/circ_blocks/examples/zk.rs index c157885d..dd29a507 100644 --- a/circ_blocks/examples/zk.rs +++ b/circ_blocks/examples/zk.rs @@ -1,6 +1,6 @@ use circ::cfg::{ - clap::{self, Parser, ValueEnum}, CircOpt, + clap::{self, Parser, ValueEnum}, }; use std::path::PathBuf; diff --git a/circ_blocks/examples/zxc.rs b/circ_blocks/examples/zxc.rs index ac73171a..81209809 100644 --- a/circ_blocks/examples/zxc.rs +++ b/circ_blocks/examples/zxc.rs @@ -4,30 +4,32 @@ const PRINT_PROOF: bool = false; const INLINE_SPARTAN_PROOF: bool = false; const TOTAL_NUM_VARS_BOUND: usize = 100000000; -use circ::front::zsharp::{self, ZSharpFE}; -use circ::front::{FrontEnd, Mode}; -use circ::ir::opt::{opt, Opt}; -use circ::target::r1cs::trans::to_r1cs; -use circ::target::r1cs::wit_comp::StagedWitCompEvaluator; -use circ::target::r1cs::ProverData; -use circ::target::r1cs::{Lc, VarType}; +use circ::{ + front::{ + FrontEnd, Mode, + zsharp::{self, ZSharpFE}, + }, + ir::opt::{Opt, opt}, + target::r1cs::{Lc, ProverData, VarType, trans::to_r1cs, wit_comp::StagedWitCompEvaluator}, +}; use core::cmp::min; use rug::Integer; -use std::fs::{create_dir_all, File}; -use std::io::{BufRead, BufReader, Write}; +use std::{ + fs::{File, create_dir_all}, + io::{BufRead, BufReader, Write}, +}; use circ::cfg::{ - cfg, + CircOpt, cfg, clap::{self, Parser, ValueEnum}, - CircOpt, }; use core::cmp::Ordering; use std::path::{Path, PathBuf}; use libspartan::{ - instance::Instance, Assignment, InputsAssignment, MemsAssignment, SNARKGens, VarsAssignment, - SNARK, + Assignment, InputsAssignment, MemsAssignment, SNARK, SNARKGens, VarsAssignment, + instance::Instance, }; use merlin::Transcript; use serde::{Deserialize, Serialize}; @@ -583,30 +585,27 @@ fn get_compile_time_knowledge( }; println!("Optimizing IR... "); - let cs = opt( - cs, - vec![ - Opt::ScalarizeVars, - Opt::Flatten, - Opt::Sha, - Opt::ConstantFold(Box::new([])), - Opt::Flatten, - Opt::Inline, - // Tuples must be eliminated before oblivious array elim - Opt::Tuple, - Opt::ConstantFold(Box::new([])), - Opt::Obliv, - // The obliv elim pass produces more tuples, that must be eliminated - Opt::Tuple, - Opt::LinearScan, - // The linear scan pass produces more tuples, that must be eliminated - Opt::Tuple, - Opt::Flatten, - Opt::ConstantFold(Box::new([])), - Opt::Inline, - Opt::SkolemizeChallenges, - ], - ); + let cs = opt(cs, vec![ + Opt::ScalarizeVars, + Opt::Flatten, + Opt::Sha, + Opt::ConstantFold(Box::new([])), + Opt::Flatten, + Opt::Inline, + // Tuples must be eliminated before oblivious array elim + Opt::Tuple, + Opt::ConstantFold(Box::new([])), + Opt::Obliv, + // The obliv elim pass produces more tuples, that must be eliminated + Opt::Tuple, + Opt::LinearScan, + // The linear scan pass produces more tuples, that must be eliminated + Opt::Tuple, + Opt::Flatten, + Opt::ConstantFold(Box::new([])), + Opt::Inline, + Opt::SkolemizeChallenges, + ]); println!("done."); if VERBOSE { @@ -1011,10 +1010,11 @@ fn get_run_time_knowledge( } } - let inputs = [ - vars[..io_width].to_vec(), - vec![zero.clone(); io_width.next_power_of_two() - io_width], - ] + let inputs = [vars[..io_width].to_vec(), vec![ + zero.clone(); + io_width.next_power_of_two() + - io_width + ]] .concat(); let inputs_assignment = Assignment::new( &inputs @@ -1447,50 +1447,52 @@ fn run_spartan_proof(ctk: CompileTimeKnowledge, rtk: RunTimeKnowledge) { println!("Verifying the proof..."); // verify the proof of satisfiability let mut verifier_transcript = Transcript::new(b"snark_example"); - assert!(proof - .verify( - ctk.input_block_num, - ctk.output_block_num, - &ctk.input_liveness, - ctk.func_input_width, - ctk.input_offset, - ctk.output_offset, - &rtk.input, - &rtk.input_stack, - &rtk.input_mem, - &rtk.output, - rtk.output_exec_num, - num_vars, - num_ios, - max_block_num_phy_ops, - &block_num_phy_ops, - max_block_num_vir_ops, - &block_num_vir_ops, - mem_addr_ts_bits_size, - num_inputs_unpadded, - &ctk.num_vars_per_block, - block_num_instances_bound, - rtk.block_max_num_proofs, - &block_num_proofs, - block_num_cons, - &block_comm_map, - &block_comm_list, - &block_gens, - rtk.consis_num_proofs, - rtk.total_num_init_phy_mem_accesses, - rtk.total_num_init_vir_mem_accesses, - rtk.total_num_phy_mem_accesses, - rtk.total_num_vir_mem_accesses, - pairwise_check_num_cons, - &pairwise_check_comm, - &pairwise_check_gens, - perm_root_num_cons, - &perm_root_comm, - &perm_root_gens, - &vars_gens, - &mut verifier_transcript - ) - .is_ok()); + assert!( + proof + .verify( + ctk.input_block_num, + ctk.output_block_num, + &ctk.input_liveness, + ctk.func_input_width, + ctk.input_offset, + ctk.output_offset, + &rtk.input, + &rtk.input_stack, + &rtk.input_mem, + &rtk.output, + rtk.output_exec_num, + num_vars, + num_ios, + max_block_num_phy_ops, + &block_num_phy_ops, + max_block_num_vir_ops, + &block_num_vir_ops, + mem_addr_ts_bits_size, + num_inputs_unpadded, + &ctk.num_vars_per_block, + block_num_instances_bound, + rtk.block_max_num_proofs, + &block_num_proofs, + block_num_cons, + &block_comm_map, + &block_comm_list, + &block_gens, + rtk.consis_num_proofs, + rtk.total_num_init_phy_mem_accesses, + rtk.total_num_init_vir_mem_accesses, + rtk.total_num_phy_mem_accesses, + rtk.total_num_vir_mem_accesses, + pairwise_check_num_cons, + &pairwise_check_comm, + &pairwise_check_gens, + perm_root_num_cons, + &perm_root_comm, + &perm_root_gens, + &vars_gens, + &mut verifier_transcript + ) + .is_ok() + ); println!("proof verification successful!"); } diff --git a/circ_blocks/src/cfg.rs b/circ_blocks/src/cfg.rs index 4550e14e..29ef7b2d 100644 --- a/circ_blocks/src/cfg.rs +++ b/circ_blocks/src/cfg.rs @@ -13,13 +13,12 @@ use circ_fields::FieldT; use once_cell::sync::OnceCell; use rug::Integer; -use std::convert::From; -use std::default::Default; +use std::{convert::From, default::Default}; -/// Re-export our clap version -pub use circ_opt::clap; /// Re-export our clap [clap::Args] pub use circ_opt::CircOpt; +/// Re-export our clap version +pub use circ_opt::clap; /// A Circ configuration. Contructible [From::from] [CircOpt]. #[derive(Clone, Debug)] diff --git a/circ_blocks/src/circify/includer.rs b/circ_blocks/src/circify/includer.rs index 48b7f118..b9f2f4d6 100644 --- a/circ_blocks/src/circify/includer.rs +++ b/circ_blocks/src/circify/includer.rs @@ -1,7 +1,9 @@ //! Language-agnostic machinery for recursively loading files -use std::collections::{HashMap, VecDeque}; -use std::path::{Path, PathBuf}; +use std::{ + collections::{HashMap, VecDeque}, + path::{Path, PathBuf}, +}; /// A trait which defines a graph of files that can be recursively loaded pub trait Loader: Sized { diff --git a/circ_blocks/src/circify/mem.rs b/circ_blocks/src/circify/mem.rs index 4b1a2982..6e8d47e4 100644 --- a/circ_blocks/src/circify/mem.rs +++ b/circ_blocks/src/circify/mem.rs @@ -159,8 +159,7 @@ impl MemManager { mod test { use super::*; use crate::target::smt::check_sat; - use std::cell::RefCell; - use std::rc::Rc; + use std::{cell::RefCell, rc::Rc}; fn bv_var(s: &str, w: usize) -> Term { leaf_term(Op::Var(s.to_owned(), Sort::BitVector(w))) diff --git a/circ_blocks/src/circify/mod.rs b/circ_blocks/src/circify/mod.rs index 8b492def..3ecc0763 100644 --- a/circ_blocks/src/circify/mod.rs +++ b/circ_blocks/src/circify/mod.rs @@ -1,14 +1,14 @@ //! A library for building front-ends -use crate::circify::mem::AllocId; -use crate::ir::term::*; +use crate::{circify::mem::AllocId, ir::term::*}; use crate::cfg::cfg; use fxhash::FxHashMap; -use std::cell::RefCell; -use std::collections::hash_map::Entry; -use std::collections::HashMap; -use std::fmt::{self, Debug, Display, Formatter}; -use std::rc::Rc; +use std::{ + cell::RefCell, + collections::{HashMap, hash_map::Entry}, + fmt::{self, Debug, Display, Formatter}, + rc::Rc, +}; use thiserror::Error; pub mod includer; @@ -440,7 +440,7 @@ impl Drop for Circify { // a live CirCtx, in which case the Computation's Drop impl // will garbage collect. // - //drop(self.take_ctx()); + // drop(self.take_ctx()); // force garbage collection garbage_collect(); @@ -623,10 +623,11 @@ impl Circify { let t = self .e .declare_input(f, &mut self.cir_ctx, &ty, ssa_name.to_string(), None, None); - assert!(self - .vals - .insert(ssa_name.to_string(), Val::Term(t.clone())) - .is_none()); + assert!( + self.vals + .insert(ssa_name.to_string(), Val::Term(t.clone())) + .is_none() + ); let t = term![Op::PfChallenge(ssa_name, cfg().field().clone())]; self.push(f, t); Ok(()) @@ -666,10 +667,11 @@ impl Circify { }; let ite_val = Val::Term(ite); // TODO: add language-specific coersion here if needed - assert!(self - .vals - .insert(new_name.clone(), ite_val.clone()) - .is_none()); + assert!( + self.vals + .insert(new_name.clone(), ite_val.clone()) + .is_none() + ); Ok(ite_val) } (_, v @ Val::Ref(_)) => { @@ -759,10 +761,11 @@ impl Circify { .unwrap() .clone(); let default_ret_val = self.e.initialize_return(&ty, &ssa_name); - assert!(self - .vals - .insert(ssa_name, Val::Term(default_ret_val)) - .is_none()); + assert!( + self.vals + .insert(ssa_name, Val::Term(default_ret_val)) + .is_none() + ); } } diff --git a/circ_blocks/src/front/c/ast_utils.rs b/circ_blocks/src/front/c/ast_utils.rs index c9840a9a..7f5b20dd 100644 --- a/circ_blocks/src/front/c/ast_utils.rs +++ b/circ_blocks/src/front/c/ast_utils.rs @@ -1,12 +1,8 @@ -use crate::front::c::types::Ty; -use crate::front::c::Expression::Identifier; +use crate::front::c::{Expression::Identifier, types::Ty}; use lang_c::ast::*; use std::fmt::{self, Display, Formatter}; -use crate::front::Mode; -use crate::front::PartyId; -use crate::front::PROVER_VIS; -use crate::front::PUBLIC_VIS; +use crate::front::{Mode, PROVER_VIS, PUBLIC_VIS, PartyId}; #[derive(Clone)] pub struct FnInfo { diff --git a/circ_blocks/src/front/c/cvisit/cvmut.rs b/circ_blocks/src/front/c/cvisit/cvmut.rs index 3537cf72..b2b15407 100644 --- a/circ_blocks/src/front/c/cvisit/cvmut.rs +++ b/circ_blocks/src/front/c/cvisit/cvmut.rs @@ -1,10 +1,8 @@ //! AST Walker for zokrates_pest_ast -use super::walkfns::*; -use super::CVisitorResult; +use super::{CVisitorResult, walkfns::*}; -use lang_c::ast; -use lang_c::span::Node; +use lang_c::{ast, span::Node}; pub trait CVisitorMut<'ast>: Sized { fn visit_translation_unit(&mut self, tu: &mut ast::TranslationUnit) -> CVisitorResult { diff --git a/circ_blocks/src/front/c/mod.rs b/circ_blocks/src/front/c/mod.rs index 9aa46ca6..7f5ac3d1 100644 --- a/circ_blocks/src/front/c/mod.rs +++ b/circ_blocks/src/front/c/mod.rs @@ -7,25 +7,28 @@ mod term; mod types; use super::{FrontEnd, Mode}; -use crate::circify::mem::AllocId; -use crate::circify::{CircError, Circify, Loc, Val}; -use crate::front::c::ast_utils::*; -use crate::front::c::term::*; -use crate::front::c::types::*; -use crate::front::field_list::FieldList; -use crate::ir::opt::cfold::fold; -use crate::ir::proof::ConstraintMetadata; -use crate::ir::term::Node as IrNode; -use crate::ir::term::*; -use lang_c::ast::*; -use lang_c::span::Node; +use crate::{ + circify::{CircError, Circify, Loc, Val, mem::AllocId}, + front::{ + c::{ast_utils::*, term::*, types::*}, + field_list::FieldList, + }, + ir::{ + opt::cfold::fold, + proof::ConstraintMetadata, + term::{Node as IrNode, *}, + }, +}; +use lang_c::{ast::*, span::Node}; use log::debug; use fxhash::FxHashMap; -use std::cell::RefCell; -use std::collections::{HashMap, HashSet}; -use std::fmt::Display; -use std::path::PathBuf; +use std::{ + cell::RefCell, + collections::{HashMap, HashSet}, + fmt::Display, + path::PathBuf, +}; /// Inputs to the C compiler pub struct Inputs { @@ -1017,7 +1020,7 @@ impl CGen { } } - //TODO: This function is not quite right because the loop body could modify the iteration variable. + // TODO: This function is not quite right because the loop body could modify the iteration variable. fn get_const_iters(&mut self, for_stmt: &ForStatement) -> ConstIteration { let init: Option = match &for_stmt.initializer.node { ForInitializer::Declaration(d) => { diff --git a/circ_blocks/src/front/c/parser.rs b/circ_blocks/src/front/c/parser.rs index 15752fe3..2571b23b 100644 --- a/circ_blocks/src/front/c/parser.rs +++ b/circ_blocks/src/front/c/parser.rs @@ -1,7 +1,6 @@ //! Parsing and recursively loading C. -use lang_c::driver::Error; -use lang_c::driver::{parse, Config, Parse}; +use lang_c::driver::{Config, Error, Parse, parse}; use std::path::Path; pub struct CParser { diff --git a/circ_blocks/src/front/c/term.rs b/circ_blocks/src/front/c/term.rs index 7d0a7915..b214c6da 100644 --- a/circ_blocks/src/front/c/term.rs +++ b/circ_blocks/src/front/c/term.rs @@ -1,9 +1,9 @@ //! C Terms -use crate::circify::mem::AllocId; -use crate::circify::{CirCtx, Embeddable, Typed}; -use crate::front::c::types::*; -use crate::front::field_list::FieldList; -use crate::ir::term::*; +use crate::{ + circify::{CirCtx, Embeddable, Typed, mem::AllocId}, + front::{c::types::*, field_list::FieldList}, + ir::term::*, +}; use rug::Integer; use std::fmt::{self, Display, Formatter}; @@ -249,11 +249,7 @@ fn inner_usual_arith_conversions(a: &CTerm, b: &CTerm) -> (CTerm, CTerm) { let ty = Ty::Int(false, s_ty.num_bits()); (cast(Some(ty.clone()), s), cast(Some(ty), u)) }; - if signed_first { - (s_, u_) - } else { - (u_, s_) - } + if signed_first { (s_, u_) } else { (u_, s_) } } } diff --git a/circ_blocks/src/front/c/types.rs b/circ_blocks/src/front/c/types.rs index a806a31b..b017bdc4 100644 --- a/circ_blocks/src/front/c/types.rs +++ b/circ_blocks/src/front/c/types.rs @@ -1,9 +1,12 @@ //! C Types -use crate::circify::CirCtx; -use crate::front::c::term::CTerm; -use crate::front::c::term::CTermData; -use crate::front::field_list::FieldList; -use crate::ir::term::*; +use crate::{ + circify::CirCtx, + front::{ + c::term::{CTerm, CTermData}, + field_list::FieldList, + }, + ir::term::*, +}; use std::fmt::{self, Display, Formatter}; diff --git a/circ_blocks/src/front/datalog/error.rs b/circ_blocks/src/front/datalog/error.rs index a9b423a1..fc0d9839 100644 --- a/circ_blocks/src/front/datalog/error.rs +++ b/circ_blocks/src/front/datalog/error.rs @@ -2,11 +2,12 @@ use thiserror::Error; -use super::parser::ast::Span; -use super::term::T; +use super::{parser::ast::Span, term::T}; -use std::convert::From; -use std::fmt::{self, Display, Formatter}; +use std::{ + convert::From, + fmt::{self, Display, Formatter}, +}; #[derive(Error, Debug)] /// An error in circuit translation diff --git a/circ_blocks/src/front/datalog/mod.rs b/circ_blocks/src/front/datalog/mod.rs index 0f04def4..d32d5fa1 100644 --- a/circ_blocks/src/front/datalog/mod.rs +++ b/circ_blocks/src/front/datalog/mod.rs @@ -1,20 +1,20 @@ //! Datalog implementation -use std::fs::File; -use std::io::Read; -use std::path::PathBuf; -use std::str::FromStr; +use std::{fs::File, io::Read, path::PathBuf, str::FromStr}; use fxhash::FxHashMap; use log::debug; use rug::Integer; -use crate::cfg::cfg; -use crate::circify::{Circify, Loc, Val}; -use crate::front::{PROVER_VIS, PUBLIC_VIS}; -use crate::ir::opt::cfold::fold; -use crate::ir::term::extras::as_uint_constant; -use crate::ir::term::*; +use crate::{ + cfg::cfg, + circify::{Circify, Loc, Val}, + front::{PROVER_VIS, PUBLIC_VIS}, + ir::{ + opt::cfold::fold, + term::{extras::as_uint_constant, *}, + }, +}; use super::FrontEnd; @@ -54,7 +54,7 @@ impl<'ast> Gen<'ast> { /// Returns `false` if doing so would violate the recursion limit. fn enter_function(&mut self, name: &'ast str, dec_value: Option) -> bool { let e = self.stack_by_fn.entry(name).or_default(); - //assert_eq!(e.last().and_then(|l| l.as_ref()).is_some(), dec_value.is_some()); + // assert_eq!(e.last().and_then(|l| l.as_ref()).is_some(), dec_value.is_some()); let do_enter = if let (Some(last_val), Some(this_val)) = (e.last().and_then(|l| l.as_ref()), dec_value.as_ref()) { diff --git a/circ_blocks/src/front/datalog/parser.rs b/circ_blocks/src/front/datalog/parser.rs index 0e02ca6d..22abc412 100644 --- a/circ_blocks/src/front/datalog/parser.rs +++ b/circ_blocks/src/front/datalog/parser.rs @@ -3,8 +3,7 @@ #![allow(clippy::empty_docs)] #![allow(clippy::clone_on_copy)] -use pest::error::Error; -use pest::Parser; +use pest::{Parser, error::Error}; use pest_derive::Parser; // Issue with the proc macro @@ -15,13 +14,13 @@ struct MyParser; pub mod ast { use super::Rule; - use from_pest::ConversionError; - use from_pest::FromPest; - use from_pest::Void; + use from_pest::{ConversionError, FromPest, Void}; use lazy_static::lazy_static; - use pest::iterators::{Pair, Pairs}; - use pest::pratt_parser::{Assoc, Op, PrattParser}; pub use pest::Span; + use pest::{ + iterators::{Pair, Pairs}, + pratt_parser::{Assoc, Op, PrattParser}, + }; use pest_ast::FromPest; fn span_into_str(span: Span) -> &str { @@ -307,7 +306,7 @@ pub mod ast { // Create an Expression from a `term`. // Precondition: `pair` MUST be a term fn build_factor(pair: Pair) -> Box { - //println!("pairs: {:#?}", pair); + // println!("pairs: {:#?}", pair); Box::new(match pair.as_rule() { Rule::term => { // clone the pair to peek into what we should create diff --git a/circ_blocks/src/front/datalog/term.rs b/circ_blocks/src/front/datalog/term.rs index b7226016..feef755d 100644 --- a/circ_blocks/src/front/datalog/term.rs +++ b/circ_blocks/src/front/datalog/term.rs @@ -4,12 +4,13 @@ use std::fmt::{self, Display, Formatter}; use rug::Integer; -use super::error::ErrorKind; -use super::ty::Ty; +use super::{error::ErrorKind, ty::Ty}; -use crate::cfg::cfg; -use crate::circify::{CirCtx, Embeddable, Typed}; -use crate::ir::term::*; +use crate::{ + cfg::cfg, + circify::{CirCtx, Embeddable, Typed}, + ir::term::*, +}; /// A term #[derive(Debug, Clone)] diff --git a/circ_blocks/src/front/mod.rs b/circ_blocks/src/front/mod.rs index e9a0f2fe..b7ecbb91 100644 --- a/circ_blocks/src/front/mod.rs +++ b/circ_blocks/src/front/mod.rs @@ -7,8 +7,10 @@ pub mod datalog; #[cfg(all(feature = "smt", feature = "zok"))] pub mod zsharp; -use crate::ir::proof; -use crate::ir::term::{Computations, PartyId}; +use crate::ir::{ + proof, + term::{Computations, PartyId}, +}; use std::fmt::{self, Display, Formatter}; diff --git a/circ_blocks/src/front/zsharp/blocks.rs b/circ_blocks/src/front/zsharp/blocks.rs index 743198fb..6b9057ec 100644 --- a/circ_blocks/src/front/zsharp/blocks.rs +++ b/circ_blocks/src/front/zsharp/blocks.rs @@ -6,18 +6,17 @@ // Can try eliminate ternaries with a constant condition // What would happen if block 0 is a loop to itself? Many analyses would break down!!! -use blocks_optimization::bl_trans_map; -use blocks_optimization::rp_replacement_stmt; +use blocks_optimization::{bl_trans_map, rp_replacement_stmt}; use log::debug; -use crate::front::field_list::FieldList; -use crate::front::zsharp::pretty::*; -use crate::front::zsharp::PathBuf; -use crate::front::zsharp::Ty; -use crate::front::zsharp::ZGen; -use crate::front::zsharp::*; -use std::collections::{BTreeMap, BTreeSet, HashMap}; -use std::convert::TryInto; +use crate::front::{ + field_list::FieldList, + zsharp::{PathBuf, Ty, ZGen, pretty::*, *}, +}; +use std::{ + collections::{BTreeMap, BTreeSet, HashMap}, + convert::TryInto, +}; use zokrates_pest_ast::*; const STORE: usize = 0; @@ -260,16 +259,16 @@ pub struct Block<'ast> { #[derive(Clone, PartialEq, Debug)] pub enum BlockContent<'ast> { // val type liveness - Witness((String, Ty, bool)), // Dead witnesses will still be provided by the prover, and thus liveness must be explicitly stated + Witness((String, Ty, bool)), /* Dead witnesses will still be provided by the prover, and thus liveness must be explicitly stated */ // val type offset MemPush((String, Ty, usize)), // %PHY[%SP + offset] = val MemPop((String, Ty, usize)), // val = %PHY[%BP + offset] // arr type size_expr read_only ArrayInit((String, Ty, Expression<'ast>, bool)), // val_expr type arr id_expr init? read-only? - Store((Expression<'ast>, Ty, String, Expression<'ast>, bool, bool)), // arr[id] = val, if read-only then no timestamp & load/store + Store((Expression<'ast>, Ty, String, Expression<'ast>, bool, bool)), /* arr[id] = val, if read-only then no timestamp & load/store */ // var type arr id_expr read_only? - Load((String, Ty, String, Expression<'ast>, bool)), // val = arr[id], if read-only then no timestamp & load/store + Load((String, Ty, String, Expression<'ast>, bool)), /* val = arr[id], if read-only then no timestamp & load/store */ // read_only? DummyLoad(bool), Branch( @@ -285,8 +284,8 @@ pub enum BlockContent<'ast> { #[derive(Clone)] // Coda is the number of total types of blocks pub enum BlockTerminator<'ast> { - Transition(Expression<'ast>), // Expression that should be evaluated to either a const int or "rp@" - FuncCall(String), // Placeholders before blocks corresponding to each function has been determined + Transition(Expression<'ast>), /* Expression that should be evaluated to either a const int or "rp@" */ + FuncCall(String), /* Placeholders before blocks corresponding to each function has been determined */ ProgTerm, // The program terminates } @@ -937,7 +936,7 @@ impl<'ast> ZGen<'ast> { &'ast self, mut blks: Vec>, mut blks_len: usize, - args: Vec>, // We do not use &args here because Expressions might be reconstructed + args: Vec>, /* We do not use &args here because Expressions might be reconstructed */ f_path: PathBuf, f_name: String, func_count: usize, @@ -1785,7 +1784,10 @@ impl<'ast> ZGen<'ast> { entry_ty = members.clone().into_map().get(&m.id.value) .ok_or(format!("Array struct {} does not have member {}!", l.id.value, m.id.value))?.clone(); } else { - return Err(format!("Cannot perform member access on non-struct {}!", l.id.value)); + return Err(format!( + "Cannot perform member access on non-struct {}!", + l.id.value + )); } } else { break; @@ -3119,7 +3121,10 @@ impl<'ast> ZGen<'ast> { })? .clone() } else { - return Err(format!("Accessing member {} of a variable {} that is not a struct!", member_name, var_extended_name)); + return Err(format!( + "Accessing member {} of a variable {} that is not a struct!", + member_name, var_extended_name + )); }; member_ty } diff --git a/circ_blocks/src/front/zsharp/blocks_optimization.rs b/circ_blocks/src/front/zsharp/blocks_optimization.rs index e6b93e92..eb765020 100644 --- a/circ_blocks/src/front/zsharp/blocks_optimization.rs +++ b/circ_blocks/src/front/zsharp/blocks_optimization.rs @@ -3,19 +3,22 @@ // PUSH is not equivalent to a change in scope. Instead of popping out the last state, // PUSH should result in the union of the last two states. -use crate::front::zsharp::blocks::*; -use crate::front::zsharp::Ty; +use crate::front::zsharp::{Ty, blocks::*}; use itertools::Itertools; -use std::cmp::max; -use std::collections::VecDeque; -use std::collections::{BTreeMap, BTreeSet}; -use std::iter::FromIterator; +use std::{ + cmp::max, + collections::{BTreeMap, BTreeSet, VecDeque}, + iter::FromIterator, +}; use zokrates_pest_ast::*; -use crate::front::zsharp::ZGen; -use crate::front::zsharp::{cfg, ZSharp}; -use crate::front::Computations; -use crate::target::r1cs::trans::to_r1cs; +use crate::{ + front::{ + Computations, + zsharp::{ZGen, ZSharp, cfg}, + }, + target::r1cs::trans::to_r1cs, +}; const MAX_BLOCK_SIZE: usize = 32768; const CFG_VERBOSE: bool = false; @@ -2104,7 +2107,9 @@ impl<'ast> ZGen<'ast> { } NextBlock::Rp(_) => { if rp_successor.len() == 0 { - panic!("Control flow graph construction fails: reaching end of function point but rp@ not set!") + panic!( + "Control flow graph construction fails: reaching end of function point but rp@ not set!" + ) } // Add everything in rp_successor of cur_bl to successor of cur_bl for i in rp_successor[cur_bl].iter() { @@ -2221,7 +2226,10 @@ impl<'ast> ZGen<'ast> { if let NextBlock::Label(l) = b { entry_bl_fn.insert(*l); } else { - panic!("Blocks {} invokes function calls and cannot terminate to rp@ block.", cur_bl) + panic!( + "Blocks {} invokes function calls and cannot terminate to rp@ block.", + cur_bl + ) } } } @@ -2685,7 +2693,10 @@ impl<'ast> ZGen<'ast> { for (name, ty) in &bl_out[*s] { if let Some(k) = state.get(name) { if *ty != *k { - panic!("Type analysis failed: mismatched types on variable {} of block {}, expected {:?} but obtained {:?}", name, cur_bl, ty, k) + panic!( + "Type analysis failed: mismatched types on variable {} of block {}, expected {:?} but obtained {:?}", + name, cur_bl, ty, k + ) } } if state.get(name) == None { @@ -3492,11 +3503,7 @@ impl<'ast> ZGen<'ast> { .outputs .iter() .fold(None, |a, b| { - if &b.0 == var { - b.1.clone() - } else { - a - } + if &b.0 == var { b.1.clone() } else { a } }); if let Some(var_ty) = var_type { // GEN @@ -3527,11 +3534,7 @@ impl<'ast> ZGen<'ast> { if !oos.contains(var) { let var_type: Option = bls[cur_bl].outputs.iter().fold(None, |a, b| { - if &b.0 == var { - b.1.clone() - } else { - a - } + if &b.0 == var { b.1.clone() } else { a } }); if let Some(var_ty) = var_type { // GEN diff --git a/circ_blocks/src/front/zsharp/interp.rs b/circ_blocks/src/front/zsharp/interp.rs index a4bc1aa7..fe8bccbf 100644 --- a/circ_blocks/src/front/zsharp/interp.rs +++ b/circ_blocks/src/front/zsharp/interp.rs @@ -1,6 +1,6 @@ //! Utilities for interpretting zsharp -use super::term::{Ty, T}; +use super::term::{T, Ty}; use crate::ir::term::*; use fxhash::FxHashMap as HashMap; diff --git a/circ_blocks/src/front/zsharp/mod.rs b/circ_blocks/src/front/zsharp/mod.rs index 490ecea2..36df140e 100644 --- a/circ_blocks/src/front/zsharp/mod.rs +++ b/circ_blocks/src/front/zsharp/mod.rs @@ -11,21 +11,23 @@ pub mod zvisit; mod prover; use super::{FrontEnd, Mode}; -use crate::cfg::cfg; -use crate::circify::{CircError, Circify, Loc, Val}; -use crate::front::proof::PROVER_ID; -use crate::front::zsharp::prover::MemOp; -use crate::ir::proof::ConstraintMetadata; -use crate::ir::term::*; +use crate::{ + cfg::cfg, + circify::{CircError, Circify, Loc, Val}, + front::{proof::PROVER_ID, zsharp::prover::MemOp}, + ir::{proof::ConstraintMetadata, term::*}, +}; use log::{debug, trace, warn}; use rug::Integer; -use std::cell::{Cell, RefCell}; -use std::collections::{BTreeMap, HashMap}; -use std::fmt::Display; -use std::hash::BuildHasherDefault; -use std::path::PathBuf; -use std::str::FromStr; +use std::{ + cell::{Cell, RefCell}, + collections::{BTreeMap, HashMap}, + fmt::Display, + hash::BuildHasherDefault, + path::PathBuf, + str::FromStr, +}; use zokrates_pest_ast as ast; use term::*; @@ -117,9 +119,9 @@ impl ZSharpFE { Vec, // Block IDs Vec>>, // Prog Input | Block Outputs Vec>>, // (PM Vars + VM Vars) per block - Vec>>, // Map of IO name -> IO value, for witness generation - Vec<[Value; 2]>, // Initial physical (read-only) memory accesses, sorted by execution & address (same ordering) - Vec<[Value; 4]>, // Initial virtual memory accesses, sorted by execution & address (same ordering) + Vec>>, /* Map of IO name -> IO value, for witness generation */ + Vec<[Value; 2]>, /* Initial physical (read-only) memory accesses, sorted by execution & address (same ordering) */ + Vec<[Value; 4]>, /* Initial virtual memory accesses, sorted by execution & address (same ordering) */ Vec<(Value, Value)>, // Physical memory accesses, sorted by address Vec<[Value; 4]>, // Virtual memory accesses, sorted by address ) { @@ -301,19 +303,21 @@ impl ZSharpFE { }) .collect(); let block_outputs_list = [ - vec![prog_reg_in - .iter() - .map(|j| { - if let Some(k) = j { - Some( - to_const_value(k.clone()) - .unwrap_or_else(|e| panic!("const_entry_fn failed: {}", e)), - ) - } else { - None - } - }) - .collect()], + vec![ + prog_reg_in + .iter() + .map(|j| { + if let Some(k) = j { + Some( + to_const_value(k.clone()) + .unwrap_or_else(|e| panic!("const_entry_fn failed: {}", e)), + ) + } else { + None + } + }) + .collect(), + ], bl_exec_state .iter() .map(|i| { @@ -751,9 +755,8 @@ impl<'ast> ZGen<'ast> { .map_err(|e| format!("{e}"))? .unwrap_term() }; - let new = - loc_store(old, &zaccs[..], val) - .and_then(|n| if strict { const_val(n) } else { Ok(n) })?; + let new = loc_store(old, &zaccs[..], val) + .and_then(|n| if strict { const_val(n) } else { Ok(n) })?; debug!("Assign: {}", name); if IS_CNST { self.cvar_assign(name, new) @@ -1288,13 +1291,9 @@ impl<'ast> ZGen<'ast> { assert!(!p.accesses.is_empty()); let (val, accs) = if let Some(ast::Access::Call(c)) = p.accesses.first() { let (f_path, f_name) = self.deref_import(&p.id.value); - let exp_ty = self.lhs_ty_take().and_then(|ty| { - if p.accesses.len() > 1 { - None - } else { - Some(ty) - } - }); + let exp_ty = self + .lhs_ty_take() + .and_then(|ty| if p.accesses.len() > 1 { None } else { Some(ty) }); let args = c .arguments .expressions @@ -1888,8 +1887,10 @@ impl<'ast> ZGen<'ast> { } fn visit_imports(&mut self) -> Vec { - use petgraph::algo::toposort; - use petgraph::graph::{DefaultIx, DiGraph, NodeIndex}; + use petgraph::{ + algo::toposort, + graph::{DefaultIx, DiGraph, NodeIndex}, + }; let asts = std::mem::take(&mut self.asts); // we use the graph to toposort the includes and the map to go from PathBuf to NodeIdx @@ -1907,38 +1908,39 @@ impl<'ast> ZGen<'ast> { for d in f.declarations.iter() { // XXX(opt) retain() declarations instead? if we don't need them, saves allocs if let ast::SymbolDeclaration::Import(i) = d { - let (src_path, src_names, dst_names, i_span) = match i { - ast::ImportDirective::Main(m) => ( - m.source.value.clone(), - vec!["main".to_owned()], - vec![m - .alias - .as_ref() - .map(|a| a.value.clone()) - .unwrap_or_else(|| { - PathBuf::from(m.source.value.clone()) - .file_stem() - .unwrap_or_else(|| panic!("Bad import: {}", m.source.value)) - .to_string_lossy() - .to_string() - })], - &m.span, - ), - ast::ImportDirective::From(m) => ( - m.source.value.clone(), - m.symbols.iter().map(|s| s.id.value.clone()).collect(), - m.symbols - .iter() - .map(|s| { - s.alias - .as_ref() - .map(|a| a.value.clone()) - .unwrap_or_else(|| s.id.value.clone()) - }) - .collect(), - &m.span, - ), - }; + let (src_path, src_names, dst_names, i_span) = + match i { + ast::ImportDirective::Main(m) => ( + m.source.value.clone(), + vec!["main".to_owned()], + vec![m.alias.as_ref().map(|a| a.value.clone()).unwrap_or_else( + || { + PathBuf::from(m.source.value.clone()) + .file_stem() + .unwrap_or_else(|| { + panic!("Bad import: {}", m.source.value) + }) + .to_string_lossy() + .to_string() + }, + )], + &m.span, + ), + ast::ImportDirective::From(m) => ( + m.source.value.clone(), + m.symbols.iter().map(|s| s.id.value.clone()).collect(), + m.symbols + .iter() + .map(|s| { + s.alias + .as_ref() + .map(|a| a.value.clone()) + .unwrap_or_else(|| s.id.value.clone()) + }) + .collect(), + &m.span, + ), + }; assert!(!src_names.is_empty()); let abs_src_path = self.stdlib.canonicalize(&self.cur_dir(), src_path.as_str()); debug!( @@ -2184,7 +2186,7 @@ impl<'ast> ZGen<'ast> { Ok(()) } - /*** circify wrapper functions (hides RefCell) ***/ + /// * circify wrapper functions (hides RefCell) ** fn circ_enter_condition(&self, cond: Term) { if self.isolate_asserts { @@ -2270,8 +2272,7 @@ fn span_to_string(span: &ast::Span) -> String { } fn type_span<'ast, 'a>(ty: &'a ast::Type<'ast>) -> &'a ast::Span<'ast> { - use ast::BasicType::*; - use ast::Type::*; + use ast::{BasicType::*, Type::*}; match ty { Array(a) => &a.span, Struct(s) => &s.span, diff --git a/circ_blocks/src/front/zsharp/parser.rs b/circ_blocks/src/front/zsharp/parser.rs index 3152f1da..4c5d9106 100644 --- a/circ_blocks/src/front/zsharp/parser.rs +++ b/circ_blocks/src/front/zsharp/parser.rs @@ -6,13 +6,14 @@ use zokrates_pest_ast as ast; use log::debug; -use std::collections::HashMap; -use std::env::var_os; +use std::{collections::HashMap, env::var_os}; use crate::circify::includer::Loader; -use std::fs::File; -use std::io::Read; -use std::path::{Path, PathBuf}; +use std::{ + fs::File, + io::Read, + path::{Path, PathBuf}, +}; use typed_arena::Arena; /// A representation of the standard libary's location. diff --git a/circ_blocks/src/front/zsharp/prover.rs b/circ_blocks/src/front/zsharp/prover.rs index 159a0825..482b5269 100644 --- a/circ_blocks/src/front/zsharp/prover.rs +++ b/circ_blocks/src/front/zsharp/prover.rs @@ -1,20 +1,12 @@ -use crate::front::zsharp::blocks::*; -use crate::front::zsharp::const_bool; -use crate::front::zsharp::const_val; -use crate::front::zsharp::pretty::pretty_name; -use crate::front::zsharp::span_to_string; -use crate::front::zsharp::Op; -use crate::front::zsharp::Ty; -use crate::front::zsharp::Value; -use crate::front::zsharp::ZGen; -use crate::front::zsharp::T; -use crate::front::zsharp::*; -use crate::ir::term::*; -use log::debug; -use log::warn; -use std::cmp::Ordering; -use std::collections::BTreeMap; -use std::iter::zip; +use crate::{ + front::zsharp::{ + Op, T, Ty, Value, ZGen, blocks::*, const_bool, const_val, pretty::pretty_name, + span_to_string, *, + }, + ir::term::*, +}; +use log::{debug, warn}; +use std::{cmp::Ordering, collections::BTreeMap, iter::zip}; use zokrates_pest_ast::*; use rug::Integer; @@ -138,26 +130,38 @@ impl<'ast> ZGen<'ast> { fn t_to_usize(&self, a: T) -> Result { let t = const_val(a)?; match &t.term.op() { - Op::Const(val) => { - match val { - Value::Field(f) => { - let intg = f.i().to_usize().ok_or("Stack Overflow: array index exceeds usize limit.")?; - return Ok(intg); - } - Value::BitVector(bv) => { - let intg = bv.uint().to_usize().ok_or("Stack Overflow: array index exceeds usize limit.")?; - return Ok(intg); - } - Value::Int(i) => { - let intg = i.to_usize().ok_or("Stack Overflow: array index exceeds usize limit.")?; - return Ok(intg); - } - _ => { - return Err(format!("Fail to evaluate array index: index is not a number.")); - } + Op::Const(val) => match val { + Value::Field(f) => { + let intg = f + .i() + .to_usize() + .ok_or("Stack Overflow: array index exceeds usize limit.")?; + return Ok(intg); + } + Value::BitVector(bv) => { + let intg = bv + .uint() + .to_usize() + .ok_or("Stack Overflow: array index exceeds usize limit.")?; + return Ok(intg); + } + Value::Int(i) => { + let intg = i + .to_usize() + .ok_or("Stack Overflow: array index exceeds usize limit.")?; + return Ok(intg); + } + _ => { + return Err(format!( + "Fail to evaluate array index: index is not a number." + )); } + }, + _ => { + return Err(format!( + "This line should not be triggered unless const_val has been modified. Const_val needs to return Op::Const for Term." + )); } - _ => { return Err(format!("This line should not be triggered unless const_val has been modified. Const_val needs to return Op::Const for Term.")) } } } @@ -662,7 +666,10 @@ impl<'ast> ZGen<'ast> { .ok_or(format!("Push to %PHY failed: %SP is uninitialized."))?; let sp = self.t_to_usize(sp_t)?; if sp + offset != phy_mem.len() { - return Err(format!("Error processing %PHY push: index {sp} + {offset} does not match with stack size {}.", phy_mem.len())); + return Err(format!( + "Error processing %PHY push: index {sp} + {offset} does not match with stack size {}.", + phy_mem.len() + )); } else { let e = self.cvar_lookup(&var).ok_or(format!( "Push to %PHY failed: pushing an out-of-scope variable: {}.", @@ -962,7 +969,7 @@ impl<'ast> ZGen<'ast> { "Const conditional expression eval failed: {} at\n{}", err, span_to_string(cond.span()), - )) + )); } } } @@ -1002,14 +1009,14 @@ impl<'ast> ZGen<'ast> { .map(|m| m.value.as_ref()) .unwrap_or("(no error message given)"), span_to_string(a.expression.span()), - )) + )); } Err(err) => { return Err(format!( "Const assert expression eval failed: {} at\n{}", err, span_to_string(a.expression.span()), - )) + )); } } } diff --git a/circ_blocks/src/front/zsharp/term.rs b/circ_blocks/src/front/zsharp/term.rs index a975f527..a8b29b9b 100644 --- a/circ_blocks/src/front/zsharp/term.rs +++ b/circ_blocks/src/front/zsharp/term.rs @@ -1,14 +1,17 @@ //! Symbolic Z# terms -use std::collections::BTreeMap; -use std::fmt::{self, Display, Formatter}; +use std::{ + collections::BTreeMap, + fmt::{self, Display, Formatter}, +}; use rug::Integer; -use crate::cfg::cfg; -use crate::circify::{CirCtx, Embeddable, Typed}; -use crate::front::field_list::FieldList; -use crate::ir::opt::cfold::fold as constant_fold; -use crate::ir::term::*; +use crate::{ + cfg::cfg, + circify::{CirCtx, Embeddable, Typed}, + front::field_list::FieldList, + ir::{opt::cfold::fold as constant_fold, term::*}, +}; #[derive(Clone, PartialEq, Eq, Hash, Ord, PartialOrd)] pub enum Ty { @@ -1053,7 +1056,11 @@ impl Embeddable for ZSharp { f_ty, field_name(&name, f_name), visibility, - precompute.as_ref().map(|_| unimplemented!("precomputations for declared inputs that are Z# structures")), + precompute.as_ref().map(|_| { + unimplemented!( + "precomputations for declared inputs that are Z# structures" + ) + }), ), ) }) diff --git a/circ_blocks/src/front/zsharp/zvisit/eqtype.rs b/circ_blocks/src/front/zsharp/zvisit/eqtype.rs index de09de2d..d035f3dd 100644 --- a/circ_blocks/src/front/zsharp/zvisit/eqtype.rs +++ b/circ_blocks/src/front/zsharp/zvisit/eqtype.rs @@ -2,8 +2,7 @@ use std::iter::zip; -use super::super::ZGen; -use super::{ZResult, ZVisitorError, ZVisitorResult}; +use super::{super::ZGen, ZResult, ZVisitorError, ZVisitorResult}; use zokrates_pest_ast as ast; diff --git a/circ_blocks/src/front/zsharp/zvisit/zconstlitrw.rs b/circ_blocks/src/front/zsharp/zvisit/zconstlitrw.rs index 6ba5d018..fc471bc2 100644 --- a/circ_blocks/src/front/zsharp/zvisit/zconstlitrw.rs +++ b/circ_blocks/src/front/zsharp/zvisit/zconstlitrw.rs @@ -1,8 +1,6 @@ //! AST Walker for zokrates_pest_ast -use super::super::term::Ty; -use super::walkfns::*; -use super::{ZVisitorError, ZVisitorMut, ZVisitorResult}; +use super::{super::term::Ty, ZVisitorError, ZVisitorMut, ZVisitorResult, walkfns::*}; use zokrates_pest_ast as ast; @@ -30,37 +28,35 @@ impl ZConstLiteralRewriter { } impl<'ast> ZVisitorMut<'ast> for ZConstLiteralRewriter { - /* - Expressions can be any of: - - Binary(BinaryExpression<'ast>), - -> depends on operator. e.g., == outputs Bool but takes in arbitrary l and r - - Ternary(TernaryExpression<'ast>) - -> first expr is Bool, other two are expected type - - Unary(UnaryExpression<'ast>), - -> no change to expected type: each sub-expr should have the expected type - - Postfix(PostfixExpression<'ast>), - -> cannot type Access results, but descend into sub-exprs to type array indices - - Identifier(IdentifierExpression<'ast>), - -> nothing to do (terminal) - - Literal(LiteralExpression<'ast>), - -> literal should have same type as expression - - InlineArray(InlineArrayExpression<'ast>), - -> descend into SpreadOrExpression, looking for either array or element type - - InlineStruct(InlineStructExpression<'ast>), - -> check that struct types are equal - - ArrayInitializer(ArrayInitializerExpression<'ast>), - -> value should have type of value inside Array - -> count should have type Field - */ + // Expressions can be any of: + // + // Binary(BinaryExpression<'ast>), + // -> depends on operator. e.g., == outputs Bool but takes in arbitrary l and r + // + // Ternary(TernaryExpression<'ast>) + // -> first expr is Bool, other two are expected type + // + // Unary(UnaryExpression<'ast>), + // -> no change to expected type: each sub-expr should have the expected type + // + // Postfix(PostfixExpression<'ast>), + // -> cannot type Access results, but descend into sub-exprs to type array indices + // + // Identifier(IdentifierExpression<'ast>), + // -> nothing to do (terminal) + // + // Literal(LiteralExpression<'ast>), + // -> literal should have same type as expression + // + // InlineArray(InlineArrayExpression<'ast>), + // -> descend into SpreadOrExpression, looking for either array or element type + // + // InlineStruct(InlineStructExpression<'ast>), + // -> check that struct types are equal + // + // ArrayInitializer(ArrayInitializerExpression<'ast>), + // -> value should have type of value inside Array + // -> count should have type Field fn visit_ternary_expression( &mut self, @@ -171,7 +167,10 @@ impl<'ast> ZVisitorMut<'ast> for ZConstLiteralRewriter { let ty_map = if let Some(t) = to_ty.as_ref() { if let Ty::Struct(name, ty_map) = t { if name != &ise.ty.value { - Err(format!("ZConstLiteralRewriter: got struct {}, expected {} visiting inline struct expression", &ise.ty.value, name)) + Err(format!( + "ZConstLiteralRewriter: got struct {}, expected {} visiting inline struct expression", + &ise.ty.value, name + )) } else { Ok(Some(ty_map.clone())) } diff --git a/circ_blocks/src/front/zsharp/zvisit/zgenericinf.rs b/circ_blocks/src/front/zsharp/zvisit/zgenericinf.rs index 1921f344..26b18d18 100644 --- a/circ_blocks/src/front/zsharp/zvisit/zgenericinf.rs +++ b/circ_blocks/src/front/zsharp/zvisit/zgenericinf.rs @@ -1,15 +1,15 @@ //! Generic parameter inference -use super::super::term::{cond, const_val, Ty, T}; -use super::super::{span_to_string, ZGen}; -use crate::ir::term::{bv_lit, leaf_term, term, BoolNaryOp, Op, Sort, Term, Value}; +use super::super::{ + ZGen, span_to_string, + term::{T, Ty, cond, const_val}, +}; +use crate::ir::term::{BoolNaryOp, Op, Sort, Term, Value, bv_lit, leaf_term, term}; #[cfg(feature = "smt")] use crate::target::smt::find_unique_model; use log::debug; -use std::cell::RefCell; -use std::collections::HashMap; -use std::path::Path; +use std::{cell::RefCell, collections::HashMap, path::Path}; use zokrates_pest_ast as ast; thread_local! { @@ -183,9 +183,10 @@ impl<'ast, 'gen, const IS_CNST: bool> ZGenericInf<'ast, 'gen, IS_CNST> { } g_name.truncate(self.gens[idx].value.len()); g_name.shrink_to_fit(); - assert!(res - .insert(g_name, T::new(Ty::Uint(32), term![Op::Const(g_val)])) - .is_none()); + assert!( + res.insert(g_name, T::new(Ty::Uint(32), term![Op::Const(g_val)])) + .is_none() + ); } }); if self.constr.is_some() { @@ -314,8 +315,7 @@ impl<'ast, 'gen, const IS_CNST: bool> ZGenericInf<'ast, 'gen, IS_CNST> { { return Err(format!( "Cannot infer generic values for struct {} arg to function {}\nGeneric structs in fn defns must have explicit generics (in terms of fn generic vars)", - &def_ty.id.value, - &self.fdef.id.value, + &def_ty.id.value, &self.fdef.id.value, )); } diff --git a/circ_blocks/src/front/zsharp/zvisit/zstmtwalker/mod.rs b/circ_blocks/src/front/zsharp/zvisit/zstmtwalker/mod.rs index 82d9ee3d..b2ad5939 100644 --- a/circ_blocks/src/front/zsharp/zvisit/zstmtwalker/mod.rs +++ b/circ_blocks/src/front/zsharp/zvisit/zstmtwalker/mod.rs @@ -2,12 +2,11 @@ mod zexprtyper; -use super::super::term::Ty; -use super::super::{span_to_string, ZGen}; -use super::eqtype::*; -use super::walkfns::*; use super::{ - bos_to_type, ZConstLiteralRewriter, ZResult, ZVisitorError, ZVisitorMut, ZVisitorResult, + super::{ZGen, span_to_string, term::Ty}, + ZConstLiteralRewriter, ZResult, ZVisitorError, ZVisitorMut, ZVisitorResult, bos_to_type, + eqtype::*, + walkfns::*, }; use zexprtyper::ZExpressionTyper; @@ -28,10 +27,11 @@ impl<'ast, 'ret> ZStatementWalker<'ast, 'ret> { gens: &'ret [ast::IdentifierExpression<'ast>], zgen: &'ret ZGen<'ast>, ) -> Self { - let vars = vec![prms - .iter() - .map(|p| (p.id.value.clone(), p.ty.clone())) - .collect()]; + let vars = vec![ + prms.iter() + .map(|p| (p.id.value.clone(), p.ty.clone())) + .collect(), + ]; Self { rets, gens, @@ -587,8 +587,8 @@ impl<'ast, 'ret> ZStatementWalker<'ast, 'ret> { where F: Fn(&T) -> ZResult>, { - use ast::Type; use MSAccRef::*; + use ast::Type; let mut acc_dim_offset = 0; for acc in accs { if matches!(ty, Type::Basic(_)) { diff --git a/circ_blocks/src/front/zsharp/zvisit/zstmtwalker/zexprtyper.rs b/circ_blocks/src/front/zsharp/zvisit/zstmtwalker/zexprtyper.rs index 466768dd..578df676 100644 --- a/circ_blocks/src/front/zsharp/zvisit/zstmtwalker/zexprtyper.rs +++ b/circ_blocks/src/front/zsharp/zvisit/zstmtwalker/zexprtyper.rs @@ -1,8 +1,9 @@ //! AST Walker for zokrates_pest_ast -use super::super::eqtype::*; -use super::super::{bos_to_type, ZResult, ZVisitorError, ZVisitorMut, ZVisitorResult}; -use super::ZStatementWalker; +use super::{ + super::{ZResult, ZVisitorError, ZVisitorMut, ZVisitorResult, bos_to_type, eqtype::*}, + ZStatementWalker, +}; use zokrates_pest_ast as ast; diff --git a/circ_blocks/src/front/zsharp/zvisit/zvmut.rs b/circ_blocks/src/front/zsharp/zvisit/zvmut.rs index acbb44ea..ae43741a 100644 --- a/circ_blocks/src/front/zsharp/zvisit/zvmut.rs +++ b/circ_blocks/src/front/zsharp/zvisit/zvmut.rs @@ -1,7 +1,6 @@ //! AST Walker for zokrates_pest_ast -use super::walkfns::*; -use super::ZVisitorResult; +use super::{ZVisitorResult, walkfns::*}; use zokrates_pest_ast as ast; diff --git a/circ_blocks/src/ir/opt/cfold.rs b/circ_blocks/src/ir/opt/cfold.rs index b780dafc..fd9faa3b 100644 --- a/circ_blocks/src/ir/opt/cfold.rs +++ b/circ_blocks/src/ir/opt/cfold.rs @@ -1,14 +1,12 @@ //! Constant folding -use crate::cfg::cfg_or_default as cfg; -use crate::ir::term::*; +use crate::{cfg::cfg_or_default as cfg, ir::term::*}; use circ_fields::FieldV; use circ_opt::FieldToBv; use itertools::Itertools; use rug::Integer; -use std::cell::RefCell; -use std::cmp::Ordering; +use std::{cell::RefCell, cmp::Ordering}; thread_local! { static FOLDS: RefCell> = RefCell::new(TermCache::with_capacity(TERM_CACHE_LIMIT)); @@ -464,11 +462,7 @@ impl NaryFlat for BoolNaryOp { leaf_term(Op::Const(Value::Bool(odd_trues))) } else { let t = safe_nary(XOR, children); - if odd_trues { - term![NOT; t] - } else { - t - } + if odd_trues { term![NOT; t] } else { t } } } } diff --git a/circ_blocks/src/ir/opt/chall.rs b/circ_blocks/src/ir/opt/chall.rs index b9e022d9..e25bf934 100644 --- a/circ_blocks/src/ir/opt/chall.rs +++ b/circ_blocks/src/ir/opt/chall.rs @@ -24,13 +24,12 @@ //! round(v use log::{debug, trace}; -use std::cell::RefCell; -use std::collections::BTreeSet; +use std::{cell::RefCell, collections::BTreeSet}; -use crate::ir::opt::visit::RewritePass; -use crate::ir::proof::PROVER_ID; -use crate::ir::term::*; -use crate::util::ns::Uniquer; +use crate::{ + ir::{opt::visit::RewritePass, proof::PROVER_ID, term::*}, + util::ns::Uniquer, +}; /// Replace witness terms with new variables. pub fn deskolemize_witnesses(comp: &mut Computation) { diff --git a/circ_blocks/src/ir/opt/inline.rs b/circ_blocks/src/ir/opt/inline.rs index 2db12410..2bc41fe5 100644 --- a/circ_blocks/src/ir/opt/inline.rs +++ b/circ_blocks/src/ir/opt/inline.rs @@ -1,15 +1,12 @@ //! Substitutions use super::cfold; -use crate::ir::term::extras::*; -use crate::ir::term::*; +use crate::ir::term::{extras::*, *}; use fxhash::FxHashSet; /// This is a tool for sweeping a list of equations, some of which define new variables as /// functions of previous ones, and eliminating these new variables, by substituting them /// elsewhere. -/// -/// pub struct Inliner<'a> { /// Map from variables to their values. /// Invariant: no key variable in in any value variable. @@ -75,7 +72,9 @@ impl<'a> Inliner<'a> { assert!( self.stale_vars.contains(&child), "{}", - format!("Variable {child} in the substitution cache for {key}, {value} is not marked stale") + format!( + "Variable {child} in the substitution cache for {key}, {value} is not marked stale" + ) ); } } @@ -126,7 +125,7 @@ impl<'a> Inliner<'a> { /// If `t` is not a substitution, then its (substituted variant) is returned. fn ingest_term(&mut self, t: &Term) -> Option { if let Some((var, val)) = self.as_fresh_def(t) { - //debug!(target: "circ::ir::opt::inline", "Inline: {} -> {}", var, val.clone()); + // debug!(target: "circ::ir::opt::inline", "Inline: {} -> {}", var, val.clone()); // Rewrite the substitution let subst_val = self.apply(&val); @@ -143,7 +142,7 @@ impl<'a> Inliner<'a> { .extend(PostOrderIter::new(val).filter(|t| t.is_var())); // Comment out? - //self.check_substs(); + // self.check_substs(); None } else { diff --git a/circ_blocks/src/ir/opt/link.rs b/circ_blocks/src/ir/opt/link.rs index d28eb92a..c2ff7d7e 100644 --- a/circ_blocks/src/ir/opt/link.rs +++ b/circ_blocks/src/ir/opt/link.rs @@ -2,8 +2,7 @@ use fxhash::FxHashMap as HashMap; -use crate::ir::opt::visit::RewritePass; -use crate::ir::term::*; +use crate::ir::{opt::visit::RewritePass, term::*}; /// A recursive linker. struct Linker<'f> { diff --git a/circ_blocks/src/ir/opt/mem/lin.rs b/circ_blocks/src/ir/opt/mem/lin.rs index f795feca..68860a85 100644 --- a/circ_blocks/src/ir/opt/mem/lin.rs +++ b/circ_blocks/src/ir/opt/mem/lin.rs @@ -44,10 +44,10 @@ impl RewritePass for Linearizer { Some(leaf_term(Op::Var(new_name, new_sort))) } Op::Array(..) => Some(term(Op::Tuple, rewritten_children())), - Op::Fill(_, size) => Some(term( - Op::Tuple, - vec![rewritten_children().pop().unwrap(); *size], - )), + Op::Fill(_, size) => Some(term(Op::Tuple, vec![ + rewritten_children().pop().unwrap(); + *size + ])), Op::Select => { let cs = rewritten_children(); let idx = &cs[1]; diff --git a/circ_blocks/src/ir/opt/mem/obliv.rs b/circ_blocks/src/ir/opt/mem/obliv.rs index 9514692b..8fb39d31 100644 --- a/circ_blocks/src/ir/opt/mem/obliv.rs +++ b/circ_blocks/src/ir/opt/mem/obliv.rs @@ -17,8 +17,7 @@ //! We could make the analysis more precise (and/or efficient) with a better data structure for //! tracking information about value locations. -use crate::ir::term::extras::as_uint_constant; -use crate::ir::term::*; +use crate::ir::term::{extras::as_uint_constant, *}; use log::trace; @@ -150,7 +149,7 @@ impl OblivRewriter { }, None, ), - //Op::Tuple => panic!("Tuple in obliv"), + // Op::Tuple => panic!("Tuple in obliv"), _ => (None, None), }; if let Some(tup) = tup_opt { diff --git a/circ_blocks/src/ir/opt/mem/ram.rs b/circ_blocks/src/ir/opt/mem/ram.rs index 3cd49d2a..79d9a526 100644 --- a/circ_blocks/src/ir/opt/mem/ram.rs +++ b/circ_blocks/src/ir/opt/mem/ram.rs @@ -8,8 +8,7 @@ use log::trace; use std::collections::VecDeque; -use crate::ir::opt::visit::RewritePass; -use crate::ir::term::*; +use crate::ir::{opt::visit::RewritePass, term::*}; use circ_fields::FieldT; use circ_opt::RamOpt; @@ -23,7 +22,6 @@ pub mod volatile; /// An access to a RAM /// /// ## Field ordering -/// struct Access { /// The value read or (conditionally) written. pub val: Term, diff --git a/circ_blocks/src/ir/opt/mem/ram/checker.rs b/circ_blocks/src/ir/opt/mem/ram/checker.rs index ab14d34e..b9a33ea7 100644 --- a/circ_blocks/src/ir/opt/mem/ram/checker.rs +++ b/circ_blocks/src/ir/opt/mem/ram/checker.rs @@ -1,8 +1,6 @@ //! RAM checking -use super::hash::MsHasher; -use super::*; -use crate::front::PROVER_VIS; -use crate::util::ns::Namespace; +use super::{hash::MsHasher, *}; +use crate::{front::PROVER_VIS, util::ns::Namespace}; use circ_fields::FieldT; use log::{debug, trace}; diff --git a/circ_blocks/src/ir/opt/mem/ram/checker/permutation.rs b/circ_blocks/src/ir/opt/mem/ram/checker/permutation.rs index b88fbdf4..b35bb8b1 100644 --- a/circ_blocks/src/ir/opt/mem/ram/checker/permutation.rs +++ b/circ_blocks/src/ir/opt/mem/ram/checker/permutation.rs @@ -1,7 +1,11 @@ use super::super::hash::{MsHasher, UniversalHasher}; -use crate::ir::opt::mem::ram::{Access, AccessCfg, Order}; -use crate::ir::term::*; -use crate::util::ns::Namespace; +use crate::{ + ir::{ + opt::mem::ram::{Access, AccessCfg, Order}, + term::*, + }, + util::ns::Namespace, +}; use std::collections::VecDeque; /// Permute the accesses into sorted order using a Waksman network. diff --git a/circ_blocks/src/ir/opt/mem/ram/checker/rom.rs b/circ_blocks/src/ir/opt/mem/ram/checker/rom.rs index dec9554f..ded90227 100644 --- a/circ_blocks/src/ir/opt/mem/ram/checker/rom.rs +++ b/circ_blocks/src/ir/opt/mem/ram/checker/rom.rs @@ -3,12 +3,12 @@ //! Cost: about (N + A)(L + 1) where the ROM size is N, there are A reads, and values have size L. //! If the ROM contents are fixed, cost drops to N + A(L + 1) -use super::super::hash::UniversalHasher; -use super::{Access, Ram}; -use crate::front::PROVER_VIS; -use crate::ir::opt::cfold::fold; -use crate::ir::term::*; -use crate::util::ns::Namespace; +use super::{super::hash::UniversalHasher, Access, Ram}; +use crate::{ + front::PROVER_VIS, + ir::{opt::cfold::fold, term::*}, + util::ns::Namespace, +}; use log::debug; diff --git a/circ_blocks/src/ir/opt/mem/ram/hash.rs b/circ_blocks/src/ir/opt/mem/ram/hash.rs index 0b33c711..4a723985 100644 --- a/circ_blocks/src/ir/opt/mem/ram/hash.rs +++ b/circ_blocks/src/ir/opt/mem/ram/hash.rs @@ -1,6 +1,6 @@ //! Keyed hashes -use crate::ir::term::{pf_lit, term, Op, Term, PF_ADD, PF_MUL}; +use crate::ir::term::{Op, PF_ADD, PF_MUL, Term, pf_lit, term}; use circ_fields::FieldT; /// A multi-set hasher. diff --git a/circ_blocks/src/ir/opt/mem/ram/persistent.rs b/circ_blocks/src/ir/opt/mem/ram/persistent.rs index e1cb4d0b..4ddac461 100644 --- a/circ_blocks/src/ir/opt/mem/ram/persistent.rs +++ b/circ_blocks/src/ir/opt/mem/ram/persistent.rs @@ -1,7 +1,6 @@ //! Represent a persistent array as (committed) scalar values and a RAM. -use super::super::super::visit::RewritePass; -use super::*; +use super::{super::super::visit::RewritePass, *}; use crate::front::PROVER_VIS; use log::debug; diff --git a/circ_blocks/src/ir/opt/mem/ram/volatile.rs b/circ_blocks/src/ir/opt/mem/ram/volatile.rs index 987c5d49..140f5e11 100644 --- a/circ_blocks/src/ir/opt/mem/ram/volatile.rs +++ b/circ_blocks/src/ir/opt/mem/ram/volatile.rs @@ -1,8 +1,7 @@ //! A general-purpose RAM extractor use super::*; -use fxhash::FxHashMap as HashMap; -use fxhash::FxHashSet as HashSet; +use fxhash::{FxHashMap as HashMap, FxHashSet as HashSet}; use std::collections::BinaryHeap; use log::{debug, trace}; @@ -25,7 +24,6 @@ use log::{debug, trace}; /// An array term in the graph is non-RAM if is is connected (undirectedly) in /// the constant-free graph to any node with multiple parents or children in the /// constant-free graph. -/// #[derive(Debug)] struct ArrayGraph { /// Map from array terms to their children (dependencies) diff --git a/circ_blocks/src/ir/opt/mod.rs b/circ_blocks/src/ir/opt/mod.rs index 974e274a..96e76f18 100644 --- a/circ_blocks/src/ir/opt/mod.rs +++ b/circ_blocks/src/ir/opt/mod.rs @@ -149,7 +149,7 @@ pub fn opt>(mut cs: Computations, optimizations: I) } debug!("After {:?}: {} outputs", i, c.outputs.len()); trace!("After {:?}: {}", i, c.outputs[0]); - //debug!("After {:?}: {}", i, Letified(cs.outputs[0].clone())); + // debug!("After {:?}: {}", i, Letified(cs.outputs[0].clone())); debug!("After {:?}: {} terms", i, c.terms()); } if crate::cfg::cfg().ir.frequent_gc { diff --git a/circ_blocks/src/ir/opt/scalarize_vars.rs b/circ_blocks/src/ir/opt/scalarize_vars.rs index 07d296b7..9cae62bf 100644 --- a/circ_blocks/src/ir/opt/scalarize_vars.rs +++ b/circ_blocks/src/ir/opt/scalarize_vars.rs @@ -1,8 +1,7 @@ //! Replacing array and tuple variables with scalars. use log::trace; -use crate::ir::opt::visit::RewritePass; -use crate::ir::term::*; +use crate::ir::{opt::visit::RewritePass, term::*}; struct Pass; diff --git a/circ_blocks/src/ir/opt/tuple.rs b/circ_blocks/src/ir/opt/tuple.rs index b0c4935b..20b2d437 100644 --- a/circ_blocks/src/ir/opt/tuple.rs +++ b/circ_blocks/src/ir/opt/tuple.rs @@ -60,8 +60,8 @@ //! fast vector type, instead of standard terms. This allows for log-time updates. use crate::ir::term::{ - bv_lit, check, leaf_term, term, Array, Computation, Node, Op, PostOrderIter, Sort, Term, - TermMap, Value, AND, + AND, Array, Computation, Node, Op, PostOrderIter, Sort, Term, TermMap, Value, bv_lit, check, + leaf_term, term, }; use std::collections::BTreeMap; diff --git a/circ_blocks/src/ir/term/bv.rs b/circ_blocks/src/ir/term/bv.rs index f6b2eed2..62f3ab43 100644 --- a/circ_blocks/src/ir/term/bv.rs +++ b/circ_blocks/src/ir/term/bv.rs @@ -3,8 +3,10 @@ use rug::Integer; use serde::{Deserialize, Serialize}; -use std::fmt::{self, Display, Formatter}; -use std::ops::{Add, BitAnd, BitOr, BitXor, Mul, Sub}; +use std::{ + fmt::{self, Display, Formatter}, + ops::{Add, BitAnd, BitOr, BitXor, Mul, Sub}, +}; #[derive(Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord, Serialize, Deserialize)] /// A bit-vector constant diff --git a/circ_blocks/src/ir/term/dist.rs b/circ_blocks/src/ir/term/dist.rs index b4d83937..b31c40f8 100644 --- a/circ_blocks/src/ir/term/dist.rs +++ b/circ_blocks/src/ir/term/dist.rs @@ -3,7 +3,7 @@ use super::*; use circ_fields::{FieldT, FieldV}; -use rand::{distributions::Distribution, prelude::SliceRandom, Rng}; +use rand::{Rng, distributions::Distribution, prelude::SliceRandom}; use std::iter::repeat; // A distribution of boolean terms with some size. @@ -318,8 +318,7 @@ pub mod test { use fxhash::FxHashMap as HashMap; use quickcheck::{Arbitrary, Gen}; - use rand::distributions::Distribution; - use rand::SeedableRng; + use rand::{SeedableRng, distributions::Distribution}; #[derive(Clone, Debug)] pub struct PureBool(pub Term, pub FxHashMap); diff --git a/circ_blocks/src/ir/term/ext.rs b/circ_blocks/src/ir/term/ext.rs index e667196c..655d8832 100644 --- a/circ_blocks/src/ir/term/ext.rs +++ b/circ_blocks/src/ir/term/ext.rs @@ -1,7 +1,6 @@ //! IR extensions -use super::ty::TypeErrorReason; -use super::{Sort, Term, Value}; +use super::{Sort, Term, Value, ty::TypeErrorReason}; use circ_hc::Node; use serde::{Deserialize, Serialize}; diff --git a/circ_blocks/src/ir/term/ext/haboeck.rs b/circ_blocks/src/ir/term/ext/haboeck.rs index 5dc7804d..8e9a2227 100644 --- a/circ_blocks/src/ir/term/ext/haboeck.rs +++ b/circ_blocks/src/ir/term/ext/haboeck.rs @@ -7,8 +7,7 @@ //! //! All input and output arrays must be be field -> field -use crate::ir::term::ty::*; -use crate::ir::term::*; +use crate::ir::term::{ty::*, *}; /// Type-check [super::ExtOp::UniqDeriGcd]. pub fn check(arg_sorts: &[&Sort]) -> Result { diff --git a/circ_blocks/src/ir/term/ext/map.rs b/circ_blocks/src/ir/term/ext/map.rs index 2b72d3c9..00374ce9 100644 --- a/circ_blocks/src/ir/term/ext/map.rs +++ b/circ_blocks/src/ir/term/ext/map.rs @@ -1,7 +1,6 @@ //! Oprators for maps -use crate::ir::term::ty::*; -use crate::ir::term::*; +use crate::ir::term::{ty::*, *}; /// Type-check [super::ExtOp::ArrayToMap]. pub fn check_array_to_map(arg_sorts: &[&Sort]) -> Result { diff --git a/circ_blocks/src/ir/term/ext/poly.rs b/circ_blocks/src/ir/term/ext/poly.rs index c098a4b3..bd14ff77 100644 --- a/circ_blocks/src/ir/term/ext/poly.rs +++ b/circ_blocks/src/ir/term/ext/poly.rs @@ -6,8 +6,7 @@ //! Compute f'(X) and s,t s.t. fs + f't = 1. Return an array of coefficients for s and one for t //! (as a tuple). -use crate::ir::term::ty::*; -use crate::ir::term::*; +use crate::ir::term::{ty::*, *}; /// Type-check [super::ExtOp::UniqDeriGcd]. pub fn check(arg_sorts: &[&Sort]) -> Result { diff --git a/circ_blocks/src/ir/term/ext/ram.rs b/circ_blocks/src/ir/term/ext/ram.rs index e8fb63ab..95279405 100644 --- a/circ_blocks/src/ir/term/ext/ram.rs +++ b/circ_blocks/src/ir/term/ext/ram.rs @@ -1,7 +1,6 @@ //! Operator PersistentRamSplit -use crate::ir::term::ty::*; -use crate::ir::term::*; +use crate::ir::term::{ty::*, *}; use fxhash::FxHashSet as HashSet; /// Type-check [super::ExtOp::PersistentRamSplit]. diff --git a/circ_blocks/src/ir/term/ext/sort.rs b/circ_blocks/src/ir/term/ext/sort.rs index 5bc5f59d..4fb852fe 100644 --- a/circ_blocks/src/ir/term/ext/sort.rs +++ b/circ_blocks/src/ir/term/ext/sort.rs @@ -1,7 +1,6 @@ //! Sort operator -use crate::ir::term::ty::*; -use crate::ir::term::*; +use crate::ir::term::{ty::*, *}; /// Type-check [super::ExtOp::Sort]. pub fn check(arg_sorts: &[&Sort]) -> Result { diff --git a/circ_blocks/src/ir/term/ext/waksman.rs b/circ_blocks/src/ir/term/ext/waksman.rs index c14adf02..556330bc 100644 --- a/circ_blocks/src/ir/term/ext/waksman.rs +++ b/circ_blocks/src/ir/term/ext/waksman.rs @@ -2,9 +2,8 @@ //! //! Output order: input switches, upper subnet, lower subnet, output switches -use crate::ir::term::ty::*; -use crate::ir::term::*; -use circ_waksman::{n_switches, Config}; +use crate::ir::term::{ty::*, *}; +use circ_waksman::{Config, n_switches}; use std::iter::FromIterator; /// Type-check [super::ExtOp::Waksman]. diff --git a/circ_blocks/src/ir/term/fmt.rs b/circ_blocks/src/ir/term/fmt.rs index 780c89a2..52aa25aa 100644 --- a/circ_blocks/src/ir/term/fmt.rs +++ b/circ_blocks/src/ir/term/fmt.rs @@ -1,7 +1,7 @@ //! Machinery for formatting IR types use super::{ - check, ext, map::Map, Array, ComputationMetadata, Node, Op, PartyId, PostOrderIter, Sort, Term, - TermMap, Value, VariableMetadata, + Array, ComputationMetadata, Node, Op, PartyId, PostOrderIter, Sort, Term, TermMap, Value, + VariableMetadata, check, ext, map::Map, }; use crate::cfg::{cfg, is_cfg_set}; diff --git a/circ_blocks/src/ir/term/lin.rs b/circ_blocks/src/ir/term/lin.rs index 01229001..45a0171f 100644 --- a/circ_blocks/src/ir/term/lin.rs +++ b/circ_blocks/src/ir/term/lin.rs @@ -7,7 +7,6 @@ use std::convert::From; #[derive(Serialize, Deserialize, Clone)] /// A term represented as a sequence of operator applications (rather than with hash-consing). -/// pub struct LinTerm { steps: Vec<(Op, Vec)>, } diff --git a/circ_blocks/src/ir/term/mod.rs b/circ_blocks/src/ir/term/mod.rs index eda3f327..4b6e420e 100644 --- a/circ_blocks/src/ir/term/mod.rs +++ b/circ_blocks/src/ir/term/mod.rs @@ -19,7 +19,6 @@ //! * [PostOrderIter]: an iterator over the descendents of a term. Children-first. //! * [Computation]: a collection of variables and assertions about them //! * [Value]: a variable-free (and evaluated) term -//! use crate::cfg::cfg_or_default as cfg; use circ_fields::{FieldT, FieldV}; @@ -29,10 +28,12 @@ use fxhash::{FxHashMap, FxHashSet}; use log::{debug, trace}; use rug::Integer; use serde::{Deserialize, Deserializer, Serialize, Serializer}; -use std::borrow::Borrow; -use std::cell::Cell; -use std::collections::BTreeMap; -use std::fmt::{Debug, Display, Formatter, Result as FmtResult}; +use std::{ + borrow::Borrow, + cell::Cell, + collections::BTreeMap, + fmt::{Debug, Display, Formatter, Result as FmtResult}, +}; pub mod bv; pub mod dist; @@ -48,7 +49,7 @@ pub mod ty; pub use bv::BitVector; pub use ext::ExtOp; -pub use ty::{check, check_rec, TypeError, TypeErrorReason}; +pub use ty::{TypeError, TypeErrorReason, check, check_rec}; #[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] /// An operator @@ -106,7 +107,7 @@ pub enum Op { FpUnPred(FpUnPred), /// floating-point unary operator FpUnOp(FpUnOp), - //FpFma, + // FpFma, /// cast bit-vector to floating-point, as bits BvToFp, /// translate the (unsigned) bit-vector number represented by the argument to a floating-point @@ -971,11 +972,7 @@ impl Sort { Box::new( std::iter::successors(Some(Integer::from(0)), move |p| { let q = p.clone() + 1; - if q < lim { - Some(q) - } else { - None - } + if q < lim { Some(q) } else { None } }) .map(move |i| Value::BitVector(BitVector::new(i, w))), ) @@ -986,11 +983,7 @@ impl Sort { Box::new( std::iter::successors(Some(Integer::from(0)), move |p| { let q = p.clone() + 1; - if q < *m { - Some(q) - } else { - None - } + if q < *m { Some(q) } else { None } }) .map(move |i| Value::Field(fty.new_v(i))), ) @@ -1436,16 +1429,13 @@ pub fn eval_op(op: &Op, args: &[&Value], var_vals: &FxHashMap) -> Op::BvNaryOp(o) => Value::BitVector({ let mut xs = args.iter().map(|a| a.as_bv().clone()); let f = xs.next().unwrap(); - xs.fold( - f, - match o { - BvNaryOp::Add => std::ops::Add::add, - BvNaryOp::Mul => std::ops::Mul::mul, - BvNaryOp::Xor => std::ops::BitXor::bitxor, - BvNaryOp::Or => std::ops::BitOr::bitor, - BvNaryOp::And => std::ops::BitAnd::bitand, - }, - ) + xs.fold(f, match o { + BvNaryOp::Add => std::ops::Add::add, + BvNaryOp::Mul => std::ops::Mul::mul, + BvNaryOp::Xor => std::ops::BitXor::bitxor, + BvNaryOp::Or => std::ops::BitOr::bitor, + BvNaryOp::And => std::ops::BitAnd::bitand, + }) }), Op::BvSext(w) => Value::BitVector({ let a = args[0].as_bv().clone(); @@ -1505,13 +1495,10 @@ pub fn eval_op(op: &Op, args: &[&Value], var_vals: &FxHashMap) -> Op::PfNaryOp(o) => Value::Field({ let mut xs = args.iter().map(|a| a.as_pf().clone()); let f = xs.next().unwrap(); - xs.fold( - f, - match o { - PfNaryOp::Add => std::ops::Add::add, - PfNaryOp::Mul => std::ops::Mul::mul, - }, - ) + xs.fold(f, match o { + PfNaryOp::Add => std::ops::Add::add, + PfNaryOp::Mul => std::ops::Mul::mul, + }) }), Op::IntBinPred(o) => Value::Bool({ let a = args[0].as_int(); @@ -1526,13 +1513,10 @@ pub fn eval_op(op: &Op, args: &[&Value], var_vals: &FxHashMap) -> Op::IntNaryOp(o) => Value::Int({ let mut xs = args.iter().map(|a| a.as_int().clone()); let f = xs.next().unwrap(); - xs.fold( - f, - match o { - IntNaryOp::Add => std::ops::Add::add, - IntNaryOp::Mul => std::ops::Mul::mul, - }, - ) + xs.fold(f, match o { + IntNaryOp::Add => std::ops::Add::add, + IntNaryOp::Mul => std::ops::Mul::mul, + }) }), Op::UbvToPf(fty) => Value::Field(fty.new_v(args[0].as_bv().uint())), Op::PfChallenge(name, field) => Value::Field(pf_challenge(name, field)), @@ -2091,7 +2075,6 @@ impl ComputationMetadata { /// ## Returns /// /// A call term with the input arguments in sorted order by argument names. - /// pub fn ordered_call_term( &self, name: String, @@ -2231,7 +2214,10 @@ impl Computation { match input_visiblities.len() { 0 => None, 1 => input_visiblities.into_iter().next().unwrap(), - _ => panic!("Precomputation for new var {} with term\n\t{}\ninvolves multiple input non-public visibilities:\n\t{:?}", new_input_var, precomp, input_visiblities), + _ => panic!( + "Precomputation for new var {} with term\n\t{}\ninvolves multiple input non-public visibilities:\n\t{:?}", + new_input_var, precomp, input_visiblities + ), } }; let sort = check(&precomp); @@ -2386,8 +2372,7 @@ impl Computations { /// Compute a (deterministic) prime-field challenge. pub fn pf_challenge(name: &str, field: &FieldT) -> FieldV { - use rand_chacha::rand_core::SeedableRng; - use rand_chacha::ChaChaRng; + use rand_chacha::{ChaChaRng, rand_core::SeedableRng}; use std::hash::{Hash, Hasher}; // hash the string let mut hasher = fxhash::FxHasher::default(); diff --git a/circ_blocks/src/ir/term/test.rs b/circ_blocks/src/ir/term/test.rs index 28406096..9a99699f 100644 --- a/circ_blocks/src/ir/term/test.rs +++ b/circ_blocks/src/ir/term/test.rs @@ -46,64 +46,56 @@ fn map_test_bool_key() { #[test] fn map_test_bv_key() { - let a1 = make_array( - Sort::BitVector(32), - Sort::Bool, - vec![bool(true), bool(true), bool(false), bool(false)], - ); - let a2 = make_array( - Sort::BitVector(32), - Sort::Bool, - vec![bool(true), bool(false), bool(true), bool(false)], - ); + let a1 = make_array(Sort::BitVector(32), Sort::Bool, vec![ + bool(true), + bool(true), + bool(false), + bool(false), + ]); + let a2 = make_array(Sort::BitVector(32), Sort::Bool, vec![ + bool(true), + bool(false), + bool(true), + bool(false), + ]); let actual = term![Op::Map(Box::new(Op::Eq)); a1, a2]; - let expected = make_array( - Sort::BitVector(32), - Sort::Bool, - vec![bool(true), bool(false), bool(false), bool(true)], - ); + let expected = make_array(Sort::BitVector(32), Sort::Bool, vec![ + bool(true), + bool(false), + bool(false), + bool(true), + ]); assert_eq!( eval(&actual, &FxHashMap::default()), eval(&expected, &FxHashMap::default()) ); - let a1 = make_array( - Sort::BitVector(32), - Sort::BitVector(4), - vec![ - bv_lit(0b0001, 4), - bv_lit(0b0010, 4), - bv_lit(0b0011, 4), - bv_lit(0b0100, 4), - ], - ); - let a2 = make_array( - Sort::BitVector(32), - Sort::BitVector(4), - vec![ - bv_lit(0b0001, 4), - bv_lit(0b0100, 4), - bv_lit(0b1001, 4), - bv_lit(0b0000, 4), - ], - ); + let a1 = make_array(Sort::BitVector(32), Sort::BitVector(4), vec![ + bv_lit(0b0001, 4), + bv_lit(0b0010, 4), + bv_lit(0b0011, 4), + bv_lit(0b0100, 4), + ]); + let a2 = make_array(Sort::BitVector(32), Sort::BitVector(4), vec![ + bv_lit(0b0001, 4), + bv_lit(0b0100, 4), + bv_lit(0b1001, 4), + bv_lit(0b0000, 4), + ]); let actual_eq = term![Op::Map(Box::new(Op::Eq)); a1.clone(), a2.clone()]; let actual_add = term![Op::Map(Box::new(BV_ADD)); a1, a2]; - let expected_eq = make_array( - Sort::BitVector(32), - Sort::Bool, - vec![bool(true), bool(false), bool(false), bool(false)], - ); - let expected_add = make_array( - Sort::BitVector(32), - Sort::BitVector(4), - vec![ - bv_lit(0b0010, 4), - bv_lit(0b0110, 4), - bv_lit(0b1100, 4), - bv_lit(0b0100, 4), - ], - ); + let expected_eq = make_array(Sort::BitVector(32), Sort::Bool, vec![ + bool(true), + bool(false), + bool(false), + bool(false), + ]); + let expected_add = make_array(Sort::BitVector(32), Sort::BitVector(4), vec![ + bv_lit(0b0010, 4), + bv_lit(0b0110, 4), + bv_lit(0b1100, 4), + bv_lit(0b0100, 4), + ]); assert_eq!( eval(&actual_eq, &FxHashMap::default()), @@ -117,46 +109,30 @@ fn map_test_bv_key() { #[test] fn test_rot() { - let a = make_array( - Sort::BitVector(32), - Sort::BitVector(4), - vec![ - bv_lit(0b0001, 4), - bv_lit(0b0010, 4), - bv_lit(0b0011, 4), - bv_lit(0b0100, 4), - ], - ); - let expected_rot_0 = make_array( - Sort::BitVector(32), - Sort::BitVector(4), - vec![ - bv_lit(0b0001, 4), - bv_lit(0b0010, 4), - bv_lit(0b0011, 4), - bv_lit(0b0100, 4), - ], - ); - let expected_rot_1 = make_array( - Sort::BitVector(32), - Sort::BitVector(4), - vec![ - bv_lit(0b0100, 4), - bv_lit(0b0001, 4), - bv_lit(0b0010, 4), - bv_lit(0b0011, 4), - ], - ); - let expected_rot_2 = make_array( - Sort::BitVector(32), - Sort::BitVector(4), - vec![ - bv_lit(0b0011, 4), - bv_lit(0b0100, 4), - bv_lit(0b0001, 4), - bv_lit(0b0010, 4), - ], - ); + let a = make_array(Sort::BitVector(32), Sort::BitVector(4), vec![ + bv_lit(0b0001, 4), + bv_lit(0b0010, 4), + bv_lit(0b0011, 4), + bv_lit(0b0100, 4), + ]); + let expected_rot_0 = make_array(Sort::BitVector(32), Sort::BitVector(4), vec![ + bv_lit(0b0001, 4), + bv_lit(0b0010, 4), + bv_lit(0b0011, 4), + bv_lit(0b0100, 4), + ]); + let expected_rot_1 = make_array(Sort::BitVector(32), Sort::BitVector(4), vec![ + bv_lit(0b0100, 4), + bv_lit(0b0001, 4), + bv_lit(0b0010, 4), + bv_lit(0b0011, 4), + ]); + let expected_rot_2 = make_array(Sort::BitVector(32), Sort::BitVector(4), vec![ + bv_lit(0b0011, 4), + bv_lit(0b0100, 4), + bv_lit(0b0001, 4), + bv_lit(0b0010, 4), + ]); let rot_0 = term![Op::Rot(0); a.clone()]; let rot_1 = term![Op::Rot(1); a.clone()]; diff --git a/circ_blocks/src/ir/term/text/mod.rs b/circ_blocks/src/ir/term/text/mod.rs index 71a8e39b..b88dbd87 100644 --- a/circ_blocks/src/ir/term/text/mod.rs +++ b/circ_blocks/src/ir/term/text/mod.rs @@ -76,9 +76,11 @@ use fxhash::FxHashMap as HashMap; mod lex; use lex::Token; -use std::fmt::{self, Debug, Display, Formatter, Write}; -use std::str::{from_utf8, FromStr}; -use std::sync::Arc; +use std::{ + fmt::{self, Debug, Display, Formatter, Write}, + str::{FromStr, from_utf8}, + sync::Arc, +}; use super::*; diff --git a/circ_blocks/src/ir/term/ty.rs b/circ_blocks/src/ir/term/ty.rs index cf336042..9e37bf76 100644 --- a/circ_blocks/src/ir/term/ty.rs +++ b/circ_blocks/src/ir/term/ty.rs @@ -2,8 +2,7 @@ use super::*; -use std::cell::RefCell; -use std::convert::TryFrom; +use std::{cell::RefCell, convert::TryFrom}; use circ_hc::collections::cache::NodeCache; diff --git a/circ_blocks/src/target/aby/assignment/ilp.rs b/circ_blocks/src/target/aby/assignment/ilp.rs index ec79167a..4e937d9d 100644 --- a/circ_blocks/src/target/aby/assignment/ilp.rs +++ b/circ_blocks/src/target/aby/assignment/ilp.rs @@ -31,9 +31,8 @@ use fxhash::{FxHashMap, FxHashSet}; -use super::{ShareType, SharingMap, SHARE_TYPES}; -use crate::ir::term::*; -use crate::target::aby::assignment::CostModel; +use super::{SHARE_TYPES, ShareType, SharingMap}; +use crate::{ir::term::*, target::aby::assignment::CostModel}; use crate::target::ilp::{Expression, Ilp, Variable}; use good_lp::variable; diff --git a/circ_blocks/src/target/aby/trans.rs b/circ_blocks/src/target/aby/trans.rs index 660db14c..bf25e426 100644 --- a/circ_blocks/src/target/aby/trans.rs +++ b/circ_blocks/src/target/aby/trans.rs @@ -6,23 +6,18 @@ use rug::Integer; -use crate::ir::opt::cfold::fold; -use crate::ir::term::*; #[cfg(feature = "lp")] use crate::target::aby::assignment::ilp::assign; -use crate::target::aby::assignment::SharingMap; -use crate::target::aby::utils::*; -use std::collections::HashMap; -use std::fs; -use std::io; -use std::path::Path; - -use super::assignment::assign_all_boolean; -use super::assignment::assign_all_yao; -use super::assignment::assign_arithmetic_and_boolean; -use super::assignment::assign_arithmetic_and_yao; -use super::assignment::assign_greedy; -use super::assignment::ShareType; +use crate::{ + ir::{opt::cfold::fold, term::*}, + target::aby::{assignment::SharingMap, utils::*}, +}; +use std::{collections::HashMap, fs, io, path::Path}; + +use super::assignment::{ + ShareType, assign_all_boolean, assign_all_yao, assign_arithmetic_and_boolean, + assign_arithmetic_and_yao, assign_greedy, +}; const PUBLIC: u8 = 2; const WRITE_SIZE: usize = 65536; @@ -504,10 +499,10 @@ impl<'a> ToABY<'a> { let const_shift_amount = const_shift_amount_term.as_bv_opt().unwrap().uint(); - let key = ( - t.op().clone(), - vec![a, const_shift_amount.to_i32().unwrap()], - ); + let key = (t.op().clone(), vec![ + a, + const_shift_amount.to_i32().unwrap(), + ]); let s = self.get_share(&t, to_share_type); if let std::collections::hash_map::Entry::Vacant(e) = self.cache.entry(key.clone()) @@ -863,7 +858,7 @@ impl<'a> ToABY<'a> { ) }); - //reset for next function + // reset for next function self.bytecode_input.clear(); self.bytecode_output.clear(); self.inputs.clear(); diff --git a/circ_blocks/src/target/aby/utils.rs b/circ_blocks/src/target/aby/utils.rs index 6fcf4261..139bbd92 100644 --- a/circ_blocks/src/target/aby/utils.rs +++ b/circ_blocks/src/target/aby/utils.rs @@ -1,8 +1,10 @@ //! Utility functions to write compiler output to ABY -use std::fs::{self, File, OpenOptions}; -use std::io::Write; -use std::path::Path; +use std::{ + fs::{self, File, OpenOptions}, + io::Write, + path::Path, +}; /// Given Path `path` and String denominator `lang`, return the filename of the path pub fn get_path(path: &Path, lang: &str, t: &str, create: bool) -> String { diff --git a/circ_blocks/src/target/ilp/mod.rs b/circ_blocks/src/target/ilp/mod.rs index 953d703b..06f9085f 100644 --- a/circ_blocks/src/target/ilp/mod.rs +++ b/circ_blocks/src/target/ilp/mod.rs @@ -139,8 +139,8 @@ pub enum IlpUnsat { mod test { use super::*; use good_lp::{ - default_solver, solvers::lp_solvers::SolverTrait, variable, ProblemVariables, Solution, - SolverModel, + ProblemVariables, Solution, SolverModel, default_solver, solvers::lp_solvers::SolverTrait, + variable, }; #[test] diff --git a/circ_blocks/src/target/ilp/trans.rs b/circ_blocks/src/target/ilp/trans.rs index fbae69b9..12a95b2f 100644 --- a/circ_blocks/src/target/ilp/trans.rs +++ b/circ_blocks/src/target/ilp/trans.rs @@ -1,21 +1,17 @@ //! Translation from IR to MILP -//! -//! // Needed until https://github.com/rust-lang/rust-clippy/pull/8183 is resolved. #![allow(clippy::identity_op)] -use crate::ir::term::*; -use crate::target::bitsize; -use crate::target::ilp::Ilp; +use crate::{ + ir::term::*, + target::{bitsize, ilp::Ilp}, +}; -use good_lp::{variable, Expression}; +use good_lp::{Expression, variable}; use log::debug; -use std::cell::RefCell; -use std::convert::TryInto; -use std::fmt::Display; -use std::rc::Rc; +use std::{cell::RefCell, convert::TryInto, fmt::Display, rc::Rc}; #[derive(Clone)] enum EmbeddedTerm { @@ -332,7 +328,7 @@ impl ToMilp { self.set_bv_bits(bv, res); } BvNaryOp::Add | BvNaryOp::Mul => { - //let f_width = self.ilp.modulus().significant_bits() as usize - 1; + // let f_width = self.ilp.modulus().significant_bits() as usize - 1; let values = bv .cs() .iter() @@ -358,7 +354,7 @@ impl ToMilp { .new_constraint(sum.eq(r.clone() + bv_modulus(n) * q)); self.set_bv_uint(bv, r, n); } - //BvBinOp::Udiv | BvBinOp::Urem => { + // BvBinOp::Udiv | BvBinOp::Urem => { // let b = b.clone(); // let a = a.clone(); // let is_zero = self.is_zero(b.clone()); @@ -536,7 +532,7 @@ impl ToMilp { /// Returns whether `a` is (`strict`ly) (`signed`ly) greater than `b`. /// Assumes they are each `w`-bit bit-vectors. fn bv_cmp(&mut self, w: usize, signed: bool, strict: bool, a: &Term, b: &Term) -> Expression { - //assert!(!signed, "TODO: signed cmp"); + // assert!(!signed, "TODO: signed cmp"); let a = if signed { self.get_bv_signed_int(a) } else { @@ -683,9 +679,10 @@ pub fn to_ilp(cs: Computation) -> Ilp { #[cfg(test)] mod test { use super::*; - use crate::ir::proof::Constraints; - use crate::ir::term::dist::test::PureBool; - use crate::ir::term::test as test_vecs; + use crate::ir::{ + proof::Constraints, + term::{dist::test::PureBool, test as test_vecs}, + }; use approx::assert_abs_diff_eq; use good_lp::default_solver; use quickcheck_macros::quickcheck; diff --git a/circ_blocks/src/target/r1cs/bellman.rs b/circ_blocks/src/target/r1cs/bellman.rs index f251e275..faf5c894 100644 --- a/circ_blocks/src/target/r1cs/bellman.rs +++ b/circ_blocks/src/target/r1cs/bellman.rs @@ -1,5 +1,5 @@ //! Exporting our R1CS to bellman -use ::bellman::{groth16, Circuit, ConstraintSystem, LinearCombination, SynthesisError, Variable}; +use ::bellman::{Circuit, ConstraintSystem, LinearCombination, SynthesisError, Variable, groth16}; use ff::{Field, PrimeField, PrimeFieldBits}; use fxhash::FxHashMap; use group::WnafGroup; @@ -7,18 +7,21 @@ use log::debug; use pairing::{Engine, MultiMillerLoop}; use rayon::prelude::*; use serde::{Deserialize, Serialize}; -use std::collections::HashMap; -use std::fs::File; -use std::io::{BufRead, BufReader}; -use std::marker::PhantomData; -use std::path::Path; -use std::str::FromStr; - -use rug::integer::{IsPrime, Order}; -use rug::Integer; - -use super::proof; -use super::{wit_comp::StagedWitCompEvaluator, Lc, ProverData, Var, VarType, VerifierData}; +use std::{ + collections::HashMap, + fs::File, + io::{BufRead, BufReader}, + marker::PhantomData, + path::Path, + str::FromStr, +}; + +use rug::{ + Integer, + integer::{IsPrime, Order}, +}; + +use super::{Lc, ProverData, Var, VarType, VerifierData, proof, wit_comp::StagedWitCompEvaluator}; use crate::ir::term::Value; /// Convert a (rug) integer to a prime field element. diff --git a/circ_blocks/src/target/r1cs/mirage.rs b/circ_blocks/src/target/r1cs/mirage.rs index 1d611916..cfe5370d 100644 --- a/circ_blocks/src/target/r1cs/mirage.rs +++ b/circ_blocks/src/target/r1cs/mirage.rs @@ -1,27 +1,28 @@ //! Exporting our R1CS to field1ield1ellman #![allow(unused)] use ::bellman::{ + SynthesisError, cc::{CcCircuit, CcConstraintSystem}, - kw15, mirage, SynthesisError, + kw15, mirage, }; use ff::{Field, PrimeField, PrimeFieldBits}; use fxhash::FxHashMap; -use group::GroupEncoding; -use group::WnafGroup; +use group::{GroupEncoding, WnafGroup}; use log::debug; use pairing::{Engine, MultiMillerLoop}; use serde::{Deserialize, Serialize}; -use std::collections::HashMap; -use std::fs::File; -use std::io::{BufRead, BufReader}; -use std::marker::PhantomData; -use std::path::Path; -use std::str::FromStr; +use std::{ + collections::HashMap, + fs::File, + io::{BufRead, BufReader}, + marker::PhantomData, + path::Path, + str::FromStr, +}; use rug::Integer; -use super::proof; -use super::{wit_comp::StagedWitCompEvaluator, ProverData, VarType, VerifierData}; +use super::{ProverData, VarType, VerifierData, proof, wit_comp::StagedWitCompEvaluator}; use crate::ir::term::Value; use super::bellman::{get_modulus, int_to_ff, lc_to_bellman}; diff --git a/circ_blocks/src/target/r1cs/mod.rs b/circ_blocks/src/target/r1cs/mod.rs index 3679547d..51480dea 100644 --- a/circ_blocks/src/target/r1cs/mod.rs +++ b/circ_blocks/src/target/r1cs/mod.rs @@ -7,8 +7,7 @@ use paste::paste; use rayon::prelude::*; use rug::Integer; use serde::{Deserialize, Serialize}; -use std::fmt::Debug; -use std::hash::Hash; +use std::{fmt::Debug, hash::Hash}; use crate::ir::term::*; @@ -341,11 +340,7 @@ impl R1cs { let half_m: Integer = self.modulus().clone() / 2; let abs = |i: Integer| { - if i <= half_m { - i - } else { - self.modulus() - i - } + if i <= half_m { i } else { self.modulus() - i } }; let sign = |i: &Integer| if i < &half_m { "+" } else { "-" }; let format_i = |i: &FieldV| { @@ -930,8 +925,8 @@ impl R1cs { let mut precompute = cs.precomputes.clone(); self.extend_precomputation(&mut precompute, false); // we still need to remove the non-r1cs variables - //use crate::ir::proof::PROVER_ID; - //let all_inputs = cs.metadata.get_inputs_for_party(Some(PROVER_ID)); + // use crate::ir::proof::PROVER_ID; + // let all_inputs = cs.metadata.get_inputs_for_party(Some(PROVER_ID)); let mut precompute_map = precompute.flatten(); let mut vars: HashMap = { PostOrderIter::from_roots_and_skips( diff --git a/circ_blocks/src/target/r1cs/opt.rs b/circ_blocks/src/target/r1cs/opt.rs index e71798d9..17dc2ea2 100644 --- a/circ_blocks/src/target/r1cs/opt.rs +++ b/circ_blocks/src/target/r1cs/opt.rs @@ -5,8 +5,7 @@ use log::debug; use std::collections::hash_map::Entry; use super::*; -use crate::cfg::CircCfg; -use crate::util::once::OnceQueue; +use crate::{cfg::CircCfg, util::once::OnceQueue}; struct LinReducer { r1cs: R1cs, diff --git a/circ_blocks/src/target/r1cs/proof.rs b/circ_blocks/src/target/r1cs/proof.rs index c325ff51..5c55a68d 100644 --- a/circ_blocks/src/target/r1cs/proof.rs +++ b/circ_blocks/src/target/r1cs/proof.rs @@ -1,16 +1,17 @@ //! A trait for CirC-compatible proofs -use std::fs::File; -use std::io::{BufReader, BufWriter}; -use std::path::Path; +use std::{ + fs::File, + io::{BufReader, BufWriter}, + path::Path, +}; use bincode::{deserialize_from, serialize_into}; use fxhash::FxHashMap as HashMap; use serde::{Deserialize, Serialize}; use super::{ProverData, VerifierData}; -use crate::ir::term::text::parse_value_map; -use crate::ir::term::Value; +use crate::ir::term::{Value, text::parse_value_map}; fn serialize_into_file>(data: &S, path: P) -> std::io::Result<()> { let mut file = BufWriter::new(File::create(path.as_ref())?); @@ -94,7 +95,7 @@ pub trait CommitProofSystem { type ComRand: Serialize + for<'a> Deserialize<'a> + Default; /// Setup fn cp_setup(p_data: ProverData, v_data: VerifierData) - -> (Self::ProvingKey, Self::VerifyingKey); + -> (Self::ProvingKey, Self::VerifyingKey); /// Proving fn cp_prove( pk: &Self::ProvingKey, @@ -210,9 +211,7 @@ impl ProofSystem for P { #[cfg(test)] mod test { use super::*; - use crate::cfg::CircCfg; - use crate::ir::term::*; - use crate::target::r1cs; + use crate::{cfg::CircCfg, ir::term::*, target::r1cs}; #[allow(dead_code)] fn test_setup_prove_verify( @@ -230,8 +229,7 @@ mod test { #[cfg(feature = "bellman")] mod mirage { - use super::super::super::mirage::Mirage; - use super::*; + use super::{super::super::mirage::Mirage, *}; // TODO(Matthias): fix this test, and then remove the #[should_panic] attribute #[should_panic] diff --git a/circ_blocks/src/target/r1cs/spartan.rs b/circ_blocks/src/target/r1cs/spartan.rs index 80a1a058..cc1bd29b 100644 --- a/circ_blocks/src/target/r1cs/spartan.rs +++ b/circ_blocks/src/target/r1cs/spartan.rs @@ -4,13 +4,15 @@ use bincode::{deserialize_from, serialize_into}; use curve25519_dalek::scalar::Scalar; use fxhash::FxHashMap as HashMap; use gmp_mpfr_sys::gmp::limb_t; -use libspartan::{Assignment, InputsAssignment, Instance, NIZKGens, VarsAssignment, NIZK}; +use libspartan::{Assignment, InputsAssignment, Instance, NIZK, NIZKGens, VarsAssignment}; use merlin::Transcript; use rug::Integer; -use std::fs::File; -use std::io; -use std::io::{BufReader, BufWriter}; -use std::path::Path; +use std::{ + fs::File, + io, + io::{BufReader, BufWriter}, + path::Path, +}; /// Hold Spartan variables #[derive(Debug)] @@ -63,9 +65,11 @@ pub fn verify>( println!("Verifying with Spartan"); let mut verifier_transcript = Transcript::new(b"nizk_example"); - assert!(proof - .verify(inst, &inputs, &mut verifier_transcript, gens) - .is_ok()); + assert!( + proof + .verify(inst, &inputs, &mut verifier_transcript, gens) + .is_ok() + ); println!("Proof Verification Successful!"); Ok(()) diff --git a/circ_blocks/src/target/r1cs/trans.rs b/circ_blocks/src/target/r1cs/trans.rs index 40fe957c..24607912 100644 --- a/circ_blocks/src/target/r1cs/trans.rs +++ b/circ_blocks/src/target/r1cs/trans.rs @@ -3,21 +3,18 @@ //! [Ben Braun's //! thesis](https://github.com/circify/circ/tree/master/doc/resources/braun-bs-thesis.pdf) //! is a good intro to how this process works. -use crate::cfg::CircCfg; -use crate::ir::term::*; -use crate::target::bitsize; -use crate::target::r1cs::*; +use crate::{ + cfg::CircCfg, + ir::term::*, + target::{bitsize, r1cs::*}, +}; use circ_fields::FieldT; use circ_opt::FieldDivByZero; use log::{debug, trace}; -use rug::ops::Pow; -use rug::Integer; +use rug::{Integer, ops::Pow}; -use std::cell::RefCell; -use std::fmt::Display; -use std::iter::ExactSizeIterator; -use std::rc::Rc; +use std::{cell::RefCell, fmt::Display, iter::ExactSizeIterator, rc::Rc}; struct BvEntry { width: usize, @@ -200,7 +197,7 @@ impl<'cfg> ToR1cs<'cfg> { debug_assert!(matches!(check(&comp), Sort::Bool)); let comp = term![Op::Ite; comp, self.one.0.clone(), self.zero.0.clone()]; let v = self.fresh_var(ctx, comp, VarType::FinalWit); - //debug!("Fresh bit: {}", self.r1cs.format_lc(&v)); + // debug!("Fresh bit: {}", self.r1cs.format_lc(&v)); self.enforce_bit(v.clone()); v } @@ -506,7 +503,7 @@ impl<'cfg> ToR1cs<'cfg> { } fn embed_bool(&mut self, c: Term) -> &TermLc { - //println!("Embed: {}", c); + // println!("Embed: {}", c); debug_assert!(check(&c) == Sort::Bool); // TODO: skip if already embedded if !self.cache.contains_key(&c) { @@ -588,7 +585,7 @@ impl<'cfg> ToR1cs<'cfg> { } fn assert_bool(&mut self, t: &Term) { - //println!("Embed: {}", c); + // println!("Embed: {}", c); // TODO: skip if already embedded if t.op() == &Op::Eq { t.cs().iter().for_each(|c| self.embed(c.clone())); @@ -720,8 +717,8 @@ impl<'cfg> ToR1cs<'cfg> { } fn embed_bv(&mut self, bv: Term) { - //println!("Embed: {}", bv); - //let bv2= bv.clone(); + // println!("Embed: {}", bv); + // let bv2= bv.clone(); if let Sort::BitVector(n) = check(&bv) { if !self.cache.contains_key(&bv) { match &bv.op() { @@ -925,7 +922,7 @@ impl<'cfg> ToR1cs<'cfg> { _ => panic!("Non-bv in embed_bv: {}", bv), } } - //self.r1cs.eval(self.get_bv_uint(&bv2)).map(|v| { + // self.r1cs.eval(self.get_bv_uint(&bv2)).map(|v| { // println!("-> {:b}", v); //}); } else { @@ -1026,7 +1023,7 @@ impl<'cfg> ToR1cs<'cfg> { } fn embed_pf(&mut self, c: Term) -> &TermLc { - //println!("Embed: {}", c); + // println!("Embed: {}", c); // TODO: skip if already embedded if !self.cache.contains_key(&c) { debug!("embed_pf {}", c); @@ -1177,9 +1174,10 @@ pub fn to_r1cs(cs: &Computation, cfg: &CircCfg) -> R1cs { pub mod test { use super::*; - use crate::ir::proof::Constraints; - use crate::ir::term::dist::test::*; - use crate::target::r1cs::opt::reduce_linearities; + use crate::{ + ir::{proof::Constraints, term::dist::test::*}, + target::r1cs::opt::reduce_linearities, + }; use fxhash::FxHashMap; use quickcheck_macros::quickcheck; diff --git a/circ_blocks/src/target/r1cs/wit_comp.rs b/circ_blocks/src/target/r1cs/wit_comp.rs index b035ec49..86d7f632 100644 --- a/circ_blocks/src/target/r1cs/wit_comp.rs +++ b/circ_blocks/src/target/r1cs/wit_comp.rs @@ -130,10 +130,7 @@ impl<'a> StagedWitCompEvaluator<'a> { let value = eval_op(op, &args, &self.variable_values); trace!( "Eval step {}: {} on {:?} -> {}", - next_step_idx, - op, - args, - value + next_step_idx, op, args, value ); self.step_values.push(value); } @@ -214,10 +211,10 @@ mod test { let mut comp = StagedWitComp::default(); let field = FieldT::from(Integer::from(7)); comp.add_stage(mk_inputs(vec![]), vec![pf_lit(field.new_v(0))]); - comp.add_stage( - mk_inputs(vec![]), - vec![pf_lit(field.new_v(1)), pf_lit(field.new_v(4))], - ); + comp.add_stage(mk_inputs(vec![]), vec![ + pf_lit(field.new_v(1)), + pf_lit(field.new_v(4)), + ]); comp.add_stage(mk_inputs(vec![]), vec![pf_lit(field.new_v(6))]); comp.add_stage(mk_inputs(vec![]), vec![pf_lit(field.new_v(0))]); diff --git a/circ_blocks/src/target/smt/mod.rs b/circ_blocks/src/target/smt/mod.rs index e1062d57..e1c9938e 100644 --- a/circ_blocks/src/target/smt/mod.rs +++ b/circ_blocks/src/target/smt/mod.rs @@ -6,16 +6,20 @@ use crate::ir::term::*; -use rsmt2::errors::SmtRes; -use rsmt2::parse::{IdentParser, ModelParser, SmtParser}; -use rsmt2::print::{Expr2Smt, Sort2Smt, Sym2Smt}; +use rsmt2::{ + errors::SmtRes, + parse::{IdentParser, ModelParser, SmtParser}, + print::{Expr2Smt, Sort2Smt, Sym2Smt}, +}; use rug::Integer; -use std::collections::HashMap; -use std::fmt::{self, Display, Formatter}; -use std::io::Write; -use std::str::FromStr; +use std::{ + collections::HashMap, + fmt::{self, Display, Formatter}, + io::Write, + str::FromStr, +}; use ieee754::Ieee754; @@ -320,7 +324,7 @@ impl<'a, Br: ::std::io::BufRead> ModelParser bool { fn get_model_solver(t: &Term, inc: bool) -> rsmt2::Solver { let mut solver = make_solver(Parser, true, inc); - //solver.path_tee("solver_com").unwrap(); + // solver.path_tee("solver_com").unwrap(); for c in PostOrderIter::new(t.clone()) { if let Op::Var(n, s) = &c.op() { solver.declare_const(&SmtSymDisp(n), s).unwrap(); diff --git a/circ_blocks/src/util/once.rs b/circ_blocks/src/util/once.rs index 4a664db3..0cafdd56 100644 --- a/circ_blocks/src/util/once.rs +++ b/circ_blocks/src/util/once.rs @@ -3,8 +3,7 @@ //! A "once queue". use fxhash::FxHashSet; -use std::collections::VecDeque; -use std::hash::Hash; +use std::{collections::VecDeque, hash::Hash}; /// A "once queue", which contains any element at most once. /// diff --git a/circ_blocks/third_party/ZoKrates/zokrates_parser/src/lib.rs b/circ_blocks/third_party/ZoKrates/zokrates_parser/src/lib.rs index 452fc526..c71b514e 100644 --- a/circ_blocks/third_party/ZoKrates/zokrates_parser/src/lib.rs +++ b/circ_blocks/third_party/ZoKrates/zokrates_parser/src/lib.rs @@ -4,9 +4,7 @@ extern crate pest; #[macro_use] extern crate pest_derive; -use pest::error::Error; -use pest::iterators::Pairs; -use pest::Parser; +use pest::{Parser, error::Error, iterators::Pairs}; #[derive(Parser)] #[grammar = "zokrates.pest"] @@ -27,8 +25,7 @@ mod tests { #[test] fn examples_dir() { use glob::glob; - use std::fs; - use std::io::Read; + use std::{fs, io::Read}; // Traverse all .zok files in examples dir for entry in glob("../zokrates_cli/examples/**/*.zok").expect("Failed to read glob pattern") diff --git a/circ_blocks/third_party/ZoKrates/zokrates_pest_ast/src/lib.rs b/circ_blocks/third_party/ZoKrates/zokrates_pest_ast/src/lib.rs index acbe75dc..c753e87c 100644 --- a/circ_blocks/third_party/ZoKrates/zokrates_pest_ast/src/lib.rs +++ b/circ_blocks/third_party/ZoKrates/zokrates_pest_ast/src/lib.rs @@ -1,9 +1,7 @@ use from_pest::FromPest; -use pest::error::Error as PestError; -use pest::iterators::Pairs; +use pest::{error::Error as PestError, iterators::Pairs}; use std::fmt; -use zokrates_parser::parse; -use zokrates_parser::Rule; +use zokrates_parser::{Rule, parse}; #[macro_use] extern crate lazy_static; @@ -13,7 +11,7 @@ pub use ast::{ Assignee, AssigneeAccess, BasicOrStructType, BasicType, BinaryExpression, BinaryOperator, BooleanLiteralExpression, BooleanType, CallAccess, CondStoreStatement, ConditionalStatement, ConstantDefinition, ConstantGenericValue, Curve, DecimalLiteralExpression, DecimalNumber, - DecimalSuffix, DefinitionStatement, DimRO, ExplicitGenerics, Expression, FieldSuffix, + DecimalSuffix, DefinitionStatement, DimRO, EOI, ExplicitGenerics, Expression, FieldSuffix, FieldType, File, FromExpression, FromImportDirective, FuncInline, FunctionDefinition, HexLiteralExpression, HexNumberExpression, IdentifierExpression, ImportDirective, ImportSymbol, InlineArrayExpression, InlineStructExpression, InlineStructMember, IterationStatement, @@ -22,19 +20,19 @@ pub use ast::{ Range, RangeOrExpression, ReturnStatement, Span, Spread, SpreadOrExpression, Statement, StrOperator, StructDefinition, StructField, StructType, SymbolDeclaration, TernaryExpression, ToExpression, ToFieldOperator, Type, TypeDefinition, TypedIdentifier, - TypedIdentifierOrAssignee, U16NumberExpression, U16Suffix, U16Type, U32NumberExpression, - U32Suffix, U32Type, U64NumberExpression, U64Suffix, U64Type, U8NumberExpression, U8Suffix, - U8Type, UnaryExpression, UnaryOperator, Underscore, Visibility, WhileLoopStatement, - WitnessStatement, EOI, + TypedIdentifierOrAssignee, U8NumberExpression, U8Suffix, U8Type, U16NumberExpression, + U16Suffix, U16Type, U32NumberExpression, U32Suffix, U32Type, U64NumberExpression, U64Suffix, + U64Type, UnaryExpression, UnaryOperator, Underscore, Visibility, WhileLoopStatement, + WitnessStatement, }; mod ast { - use from_pest::ConversionError; - use from_pest::FromPest; - use from_pest::Void; - use pest::iterators::{Pair, Pairs}; - use pest::pratt_parser::{Assoc, Op, PrattParser}; + use from_pest::{ConversionError, FromPest, Void}; pub use pest::Span; + use pest::{ + iterators::{Pair, Pairs}, + pratt_parser::{Assoc, Op, PrattParser}, + }; use pest_ast::FromPest; use zokrates_parser::Rule; @@ -1181,15 +1179,13 @@ pub fn generate_ast(input: &str) -> Result { #[cfg(test)] mod tests { - use super::ast::*; - use super::*; + use super::{ast::*, *}; use pest::Span; #[test] fn examples() { use glob::glob; - use std::fs; - use std::io::Read; + use std::{fs, io::Read}; // Traverse all .zok files in examples dir for entry in glob("../zokrates_cli/examples/**/*.zok").expect("Failed to read glob pattern") { diff --git a/circ_blocks/third_party/ZoKrates/zokrates_stdlib/build.rs b/circ_blocks/third_party/ZoKrates/zokrates_stdlib/build.rs index eb23df75..4e89ecb7 100644 --- a/circ_blocks/third_party/ZoKrates/zokrates_stdlib/build.rs +++ b/circ_blocks/third_party/ZoKrates/zokrates_stdlib/build.rs @@ -1,5 +1,4 @@ -use fs_extra::copy_items; -use fs_extra::dir::CopyOptions; +use fs_extra::{copy_items, dir::CopyOptions}; use std::env; fn main() { diff --git a/ff/ff_derive/src/lib.rs b/ff/ff_derive/src/lib.rs index 2cda55b7..525700ec 100644 --- a/ff/ff_derive/src/lib.rs +++ b/ff/ff_derive/src/lib.rs @@ -6,10 +6,8 @@ extern crate proc_macro2; use num_bigint::BigUint; use num_integer::Integer; use num_traits::{One, ToPrimitive, Zero}; -use quote::quote; -use quote::TokenStreamExt; -use std::iter; -use std::str::FromStr; +use quote::{TokenStreamExt, quote}; +use std::{iter, str::FromStr}; mod pow_fixed; @@ -191,15 +189,15 @@ fn validate_struct(ast: &syn::DeriveInput, limbs: usize) -> Option x, - _ => { - return Some( + let fields = + match &variant_data.fields { + syn::Fields::Unnamed(x) if x.unnamed.len() == 1 => x, + _ => return Some( syn::Error::new_spanned( &ast.ident, format!( @@ -208,9 +206,8 @@ fn validate_struct(ast: &syn::DeriveInput, limbs: usize) -> Option Option Option Option { return Some( syn::Error::new_spanned(&field.vis, "Field must not be public.").to_compile_error(), - ) + ); } } diff --git a/ff/ff_derive/src/pow_fixed.rs b/ff/ff_derive/src/pow_fixed.rs index 1d2b37ad..6091e98b 100644 --- a/ff/ff_derive/src/pow_fixed.rs +++ b/ff/ff_derive/src/pow_fixed.rs @@ -1,6 +1,6 @@ //! Fixed-exponent variable-base exponentiation using addition chains. -use addchain::{build_addition_chain, Step}; +use addchain::{Step, build_addition_chain}; use num_bigint::BigUint; use quote::quote; use syn::Ident; diff --git a/ff/src/lib.rs b/ff/src/lib.rs index 4ccd0de8..055d80f2 100644 --- a/ff/src/lib.rs +++ b/ff/src/lib.rs @@ -22,8 +22,10 @@ pub use bitvec::view::BitViewSized; #[cfg(feature = "bits")] use bitvec::{array::BitArray, order::Lsb0}; -use core::fmt; -use core::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign}; +use core::{ + fmt, + ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign}, +}; use rand_core::RngCore; use subtle::{Choice, ConditionallySelectable, ConstantTimeEq, CtOption}; @@ -267,7 +269,9 @@ pub trait PrimeFieldBits: PrimeField { pub mod derive { pub use crate::arith_impl::*; - pub use {byteorder, rand_core, subtle}; + pub use byteorder; + pub use rand_core; + pub use subtle; #[cfg(feature = "bits")] pub use bitvec; diff --git a/zok_tests/poseidon_gen/src/poseidon_gen.rs b/zok_tests/poseidon_gen/src/poseidon_gen.rs index 52348a7d..3320c5a8 100644 --- a/zok_tests/poseidon_gen/src/poseidon_gen.rs +++ b/zok_tests/poseidon_gen/src/poseidon_gen.rs @@ -1,7 +1,6 @@ // Generate a poseidon zok file where every constants are registers use crate::poseidon_constants::*; -use std::fs::File; -use std::io::Write; +use std::{fs::File, io::Write}; pub fn poseidon_gen() { let c = POSEIDON_C;