Skip to content

Commit

Permalink
Cache panic results when building circuits
Browse files Browse the repository at this point in the history
  • Loading branch information
fkettelhoit committed Dec 3, 2024
1 parent 1bf95b7 commit 7dbf606
Show file tree
Hide file tree
Showing 5 changed files with 13 additions and 80 deletions.
14 changes: 6 additions & 8 deletions src/circuit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -263,8 +263,8 @@ pub(crate) struct CircuitBuilder {
gates_optimized: usize,
gate_counter: usize,
panic_gates: PanicResult,
panic_wires: HashMap<usize, PanicResult>,
consts: HashMap<String, usize>,
panic_enabled: bool,
}

pub(crate) const USIZE_BITS: usize = 32;
Expand Down Expand Up @@ -389,11 +389,7 @@ impl PanicReason {
}

impl CircuitBuilder {
pub fn new(
input_gates: Vec<usize>,
consts: HashMap<String, usize>,
panic_enabled: bool,
) -> Self {
pub fn new(input_gates: Vec<usize>, consts: HashMap<String, usize>) -> Self {
let mut gate_counter = 2; // for const true and false
for input_gates_of_party in input_gates.iter() {
gate_counter += input_gates_of_party;
Expand All @@ -407,8 +403,8 @@ impl CircuitBuilder {
gates_optimized: 0,
gate_counter,
panic_gates: PanicResult::ok(),
panic_wires: HashMap::new(),
consts,
panic_enabled,
}
}

Expand Down Expand Up @@ -584,7 +580,8 @@ impl CircuitBuilder {
}

pub fn push_panic_if(&mut self, cond: GateIndex, reason: PanicReason, meta: MetaInfo) {
if !self.panic_enabled {
if let Some(existing_panic) = self.panic_wires.get(&cond) {
self.panic_gates = existing_panic.clone();
return;
}
let already_panicked = self.panic_gates.has_panicked;
Expand Down Expand Up @@ -626,6 +623,7 @@ impl CircuitBuilder {
current.panic_type[i],
);
}
self.panic_wires.insert(cond, self.panic_gates.clone());
}

pub fn peek_panic(&self) -> &PanicResult {
Expand Down
35 changes: 1 addition & 34 deletions src/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,18 +86,6 @@ impl TypedProgram {
.map(|(c, f, _)| (c, f))
}

/// Compiles the (type-checked) program, _silently ignoring panics_.
///
/// Assumes that the input program has been correctly type-checked and **panics** if
/// incompatible types are found that should have been caught by the type-checker.
pub fn compile_ignore_panic(
&self,
fn_name: &str,
) -> Result<(Circuit, &TypedFnDef), Vec<CompilerError>> {
self.compile_with_constants_ignore_panic(fn_name, HashMap::new())
.map(|(c, f, _)| (c, f))
}

/// Compiles the (type-checked) program with provided constants, producing a circuit of gates.
///
/// Assumes that the input program has been correctly type-checked and **panics** if
Expand All @@ -106,27 +94,6 @@ impl TypedProgram {
&self,
fn_name: &str,
consts: HashMap<String, HashMap<String, Literal>>,
) -> Result<CompiledProgram, Vec<CompilerError>> {
self.comp_with_constants(fn_name, consts, true)
}

/// Compiles the (type-checked) program with provided constants, _silently ignoring panics_.
///
/// Assumes that the input program has been correctly type-checked and **panics** if
/// incompatible types are found that should have been caught by the type-checker.
pub fn compile_with_constants_ignore_panic(
&self,
fn_name: &str,
consts: HashMap<String, HashMap<String, Literal>>,
) -> Result<CompiledProgram, Vec<CompilerError>> {
self.comp_with_constants(fn_name, consts, false)
}

fn comp_with_constants(
&self,
fn_name: &str,
consts: HashMap<String, HashMap<String, Literal>>,
panic_enabled: bool,
) -> Result<CompiledProgram, Vec<CompilerError>> {
let mut env = Env::new();
let mut const_sizes = HashMap::new();
Expand Down Expand Up @@ -282,7 +249,7 @@ impl TypedProgram {
input_gates.push(type_size);
env.let_in_current_scope(param.name.clone(), wires);
}
let mut circuit = CircuitBuilder::new(input_gates, const_sizes.clone(), panic_enabled);
let mut circuit = CircuitBuilder::new(input_gates, const_sizes.clone());
for (const_name, const_def) in self.const_defs.iter() {
let ConstExpr(expr, _) = &const_def.value;
match expr {
Expand Down
32 changes: 0 additions & 32 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,20 +110,6 @@ pub fn compile(prg: &str) -> Result<GarbleProgram, Error> {
})
}

/// Scans, parses, type-checks and then compiles the `"main"` fn of a program to a boolean circuit.
pub fn compile_ignore_panic(prg: &str) -> Result<GarbleProgram, Error> {
let program = check(prg)?;
let (circuit, main) = program.compile_ignore_panic("main")?;
let main = main.clone();
Ok(GarbleProgram {
program,
main,
circuit,
consts: HashMap::new(),
const_sizes: HashMap::new(),
})
}

/// Scans, parses, type-checks and then compiles the `"main"` fn of a program to a boolean circuit.
pub fn compile_with_constants(
prg: &str,
Expand All @@ -141,24 +127,6 @@ pub fn compile_with_constants(
})
}

/// Scans, parses, type-checks and then compiles the `"main"` fn of a program to a boolean circuit.
pub fn compile_with_constants_ignore_panic(
prg: &str,
consts: HashMap<String, HashMap<String, Literal>>,
) -> Result<GarbleProgram, Error> {
let program = check(prg)?;
let (circuit, main, const_sizes) =
program.compile_with_constants_ignore_panic("main", consts.clone())?;
let main = main.clone();
Ok(GarbleProgram {
program,
main,
circuit,
consts,
const_sizes,
})
}

/// The result of type-checking and compiling a Garble program.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
Expand Down
10 changes: 5 additions & 5 deletions tests/circuit.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use garble_lang::{compile, compile_ignore_panic};
use garble_lang::compile;

#[test]
fn optimize_or() -> Result<(), String> {
Expand Down Expand Up @@ -79,8 +79,8 @@ pub fn main(b: bool, x: i32) -> i32 {
if b { y } else { y }
}
";
let unoptimized = compile_ignore_panic(unoptimized).map_err(|e| e.prettify(unoptimized))?;
let optimized = compile_ignore_panic(optimized).map_err(|e| e.prettify(optimized))?;
let unoptimized = compile(unoptimized).map_err(|e| e.prettify(unoptimized))?;
let optimized = compile(optimized).map_err(|e| e.prettify(optimized))?;
assert_eq!(
unoptimized.circuit.gates.len(),
optimized.circuit.gates.len()
Expand Down Expand Up @@ -119,8 +119,8 @@ fn add(a: i8, b: i8) -> i8 {
a + b
}
";
let unoptimized = compile_ignore_panic(unoptimized).map_err(|e| e.prettify(unoptimized))?;
let optimized = compile_ignore_panic(optimized).map_err(|e| e.prettify(optimized))?;
let unoptimized = compile(unoptimized).map_err(|e| e.prettify(unoptimized))?;
let optimized = compile(optimized).map_err(|e| e.prettify(optimized))?;
assert_eq!(
unoptimized.circuit.gates.len(),
optimized.circuit.gates.len()
Expand Down
2 changes: 1 addition & 1 deletion tests/panic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -333,7 +333,7 @@ fn expect_panic(eval_result: Result<EvalOutput, EvalError>, expected: PanicReaso
let eval_output = Vec::<bool>::try_from(eval_result.unwrap());
assert!(eval_output.is_err());
match eval_output.unwrap_err() {
EvalError::Panic(EvalPanic { reason, .. }) => assert_eq!(expected, reason),
EvalError::Panic(EvalPanic { reason, .. }) => assert_eq!(reason, expected),
e => panic!("Expected a panic, but found {e:?}"),
}
}
Expand Down

0 comments on commit 7dbf606

Please sign in to comment.