pub struct Context { /* private fields */ }Expand description
A hash-consed expression arena.
A context owns every node it creates. Nodes are immutable and appended in creation order,
and every child index is lower than its parent’s, so ascending index order is a topological
order. Structurally equal expressions are the same node (“equal handle implies equal
value”; the converse does not hold). Every node is in canonical form: constants are folded,
commutative operands are ordered (constants last) independently of construction order, and
a fixed set of O(1) identities and cast collapses is applied (see docs/design.md §4.3).
use bitwright::{Context, Width};
let mut cx = Context::new();
let x = cx.symbol("x", Width::W32)?;
let one = cx.one(Width::W32)?;
let a = cx.add(one, x)?;
let b = cx.add(x, one)?;
assert_eq!(a, b);
let z = cx.xor(a, b)?;
assert_eq!(cx.as_const(z)?.map(|v| v.is_zero()), Some(true));Implementations§
Source§impl Context
impl Context
Sourcepub fn import(
&mut self,
src: &Context,
roots: &[Expr],
) -> Result<Vec<Expr>, Error>
pub fn import( &mut self, src: &Context, roots: &[Expr], ) -> Result<Vec<Expr>, Error>
Copies roots of the context src into this one: roots[i] of the result is equal to
roots[i] of src. Nodes are rebuilt through the constructors, so the copies are in
this context’s canonical form and share whatever it already holds. Symbols keep their
keys (a key this context has at another width is an error); an extension operation must
be in this context’s registry at the position it has in src’s (as
extend_registry keeps it).
Sourcepub fn ext(&mut self, op: ExtId, args: &[Expr]) -> Result<Vec<Expr>, Error>
pub fn ext(&mut self, op: ExtId, args: &[Expr]) -> Result<Vec<Expr>, Error>
Every output of the extension call op(args) (1 to 3 arguments), in order. Needs a
context built with a registry holding op
(with_registry); outputs of calls on constants are
constants.
Sourcepub fn ext_output(
&mut self,
op: ExtId,
k: usize,
args: &[Expr],
) -> Result<Expr, Error>
pub fn ext_output( &mut self, op: ExtId, k: usize, args: &[Expr], ) -> Result<Expr, Error>
Output k of the extension call op(args).
Sourcepub fn constant_u64(&mut self, width: Width, v: u64) -> Result<Expr, Error>
pub fn constant_u64(&mut self, width: Width, v: u64) -> Result<Expr, Error>
The constant v, which must fit in width bits.
Sourcepub fn constant_u128(&mut self, width: Width, v: u128) -> Result<Expr, Error>
pub fn constant_u128(&mut self, width: Width, v: u128) -> Result<Expr, Error>
The constant v, which must fit in width bits.
Sourcepub fn constant_i128(&mut self, width: Width, v: i128) -> Result<Expr, Error>
pub fn constant_i128(&mut self, width: Width, v: i128) -> Result<Expr, Error>
The constant v, which must be representable as a signed width-bit value.
Sourcepub fn bin(&mut self, op: BinOp, a: Expr, b: Expr) -> Result<Expr, Error>
pub fn bin(&mut self, op: BinOp, a: Expr, b: Expr) -> Result<Expr, Error>
A binary operator; the operands must have the same width.
Sourcepub fn cmp(
&mut self,
op: impl Into<CmpOpExt>,
a: Expr,
b: Expr,
) -> Result<Expr, Error>
pub fn cmp( &mut self, op: impl Into<CmpOpExt>, a: Expr, b: Expr, ) -> Result<Expr, Error>
A comparison (1-bit result); the operands must have the same width.
Sourcepub fn zext(&mut self, a: Expr, to: Width) -> Result<Expr, Error>
pub fn zext(&mut self, a: Expr, to: Width) -> Result<Expr, Error>
Zero extension to to (at least the operand’s width; equal width is the identity).
Sourcepub fn sext(&mut self, a: Expr, to: Width) -> Result<Expr, Error>
pub fn sext(&mut self, a: Expr, to: Width) -> Result<Expr, Error>
Sign extension to to (at least the operand’s width; equal width is the identity).
Sourcepub fn extract(&mut self, a: Expr, lo: u16, len: Width) -> Result<Expr, Error>
pub fn extract(&mut self, a: Expr, lo: u16, len: Width) -> Result<Expr, Error>
Bits [lo, lo + len).
Source§impl Context
impl Context
Sourcepub fn umulhi(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>
pub fn umulhi(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>
High half of the unsigned double-width product.
Sourcepub fn smulhi(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>
pub fn smulhi(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>
High half of the signed double-width product.
Sourcepub fn udiv(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>
pub fn udiv(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>
Unsigned division (udiv(x, 0) = ones).
Sourcepub fn urem(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>
pub fn urem(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>
Unsigned remainder (urem(x, 0) = x).
Sourcepub fn shl(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>
pub fn shl(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>
Left shift (a count >= W gives 0).
Sourcepub fn lshr(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>
pub fn lshr(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>
Logical right shift (a count >= W gives 0).
Source§impl Context
Derived constructors: they build existing node kinds.
impl Context
Derived constructors: they build existing node kinds.
Sourcepub fn add_carry(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>
pub fn add_carry(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>
The carry out of a + b (1 bit).
Sourcepub fn sub_borrow(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>
pub fn sub_borrow(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>
The borrow out of a - b (1 bit).
Sourcepub fn sadd_overflow(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>
pub fn sadd_overflow(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>
Signed overflow of a + b (1 bit).
Sourcepub fn ssub_overflow(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>
pub fn ssub_overflow(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>
Signed overflow of a - b (1 bit).
Sourcepub fn add_sat_u(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>
pub fn add_sat_u(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>
a + b clamped to the unsigned range: all ones when the sum carries out.
Sourcepub fn sub_sat_u(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>
pub fn sub_sat_u(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>
a - b clamped to the unsigned range: 0 when b exceeds a.
Sourcepub fn add_sat_s(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>
pub fn add_sat_s(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>
a + b clamped to the signed range: the signed minimum or maximum on overflow.
Sourcepub fn sub_sat_s(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>
pub fn sub_sat_s(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>
a - b clamped to the signed range: the signed minimum or maximum on overflow.
Source§impl Context
impl Context
Sourcepub fn eval(
&mut self,
roots: &[Expr],
env: &(impl Env + ?Sized),
) -> Result<Vec<BitVec>, Error>
pub fn eval( &mut self, roots: &[Expr], env: &(impl Env + ?Sized), ) -> Result<Vec<BitVec>, Error>
Evaluates roots under env. Iterative and memoized per call: a shared node is
evaluated once. Repeating the same root set reuses its evaluation schedule and
register storage; symbol values are read from env on every call.
Examples found in repository?
88fn agrees(cx: &mut Context, roots: &[bitwright::Expr]) -> Result<bool, bitwright::Error> {
89 for seed in 0..32_u64 {
90 let env = FnEnv(|key: &SymbolKey, width: Width| {
91 let mut state = format!("{key:?}")
92 .bytes()
93 .fold(seed.wrapping_mul(0x9e3779b97f4a7c15), |state, byte| {
94 state.wrapping_mul(0x100000001b3) ^ u64::from(byte)
95 });
96 let limbs: Vec<_> = (0..width.bits().div_ceil(64))
97 .map(|_| {
98 state = state.wrapping_add(0x9e3779b97f4a7c15);
99 let mut value = state;
100 value = (value ^ (value >> 30)).wrapping_mul(0xbf58476d1ce4e5b9);
101 value = (value ^ (value >> 27)).wrapping_mul(0x94d049bb133111eb);
102 value ^ (value >> 31)
103 })
104 .collect();
105 Some(match seed {
106 0 => BitVec::zero(width),
107 1 => BitVec::ones(width),
108 _ => BitVec::wrapping_from_limbs(width, &limbs),
109 })
110 });
111 let values = cx.eval(roots, &env)?;
112 if values.iter().any(|v| *v != values[0]) {
113 return Ok(false);
114 }
115 }
116 Ok(true)
117}Sourcepub fn substitute(
&mut self,
roots: &[Expr],
map: &[(Expr, Expr)],
) -> Result<Vec<Expr>, Error>
pub fn substitute( &mut self, roots: &[Expr], map: &[(Expr, Expr)], ) -> Result<Vec<Expr>, Error>
Simultaneously replaces every occurrence of each from by its to in roots
(replacements are not substituted again), rebuilding through the canonicalizing
constructors. Each pair must have equal widths.
Sourcepub fn substitute_bounded(
&mut self,
roots: &[Expr],
s: &mut Substitution,
max_visits: u64,
) -> Result<Option<Vec<Expr>>, Error>
pub fn substitute_bounded( &mut self, roots: &[Expr], s: &mut Substitution, max_visits: u64, ) -> Result<Option<Vec<Expr>>, Error>
Applies the substitution s to roots, working on at most max_visits nodes not
already in its memo. Ok(None) when that limit stops it first: the progress is kept in
s, so a later call continues where this one stopped. The walk never descends below a
replaced node or a node the memo already answers.
Source§impl Context
impl Context
Sourcepub fn fp(
&mut self,
op: FpOp,
format: FpFormat,
args: &[Expr],
) -> Result<Expr, Error>
pub fn fp( &mut self, op: FpOp, format: FpFormat, args: &[Expr], ) -> Result<Expr, Error>
The floating-point operation op of format on args (1 to 3 operands, as
FpOp::arity says). The floating-point operands must be format’s width; the
operand of FpOp::FromSInt and FpOp::FromUInt may be any width (format is
then the result’s). Operations on constants are folded.
use bitwright::fp::{FpFormat, FpOp, RoundingMode};
use bitwright::{BitVec, Context, Width};
let mut cx = Context::new();
let x = cx.symbol("x", Width::W64)?;
let three = cx.constant(&BitVec::from_f64(3.0))?;
let e = cx.fp(FpOp::Mul(RoundingMode::Rne), FpFormat::F64, &[x, three])?;
assert_eq!(cx.display(e).to_string(), "fp.mul.rne.f64(x, 0x4008000000000000)");Sourcepub fn fp_sub(
&mut self,
format: FpFormat,
rm: RoundingMode,
a: Expr,
b: Expr,
) -> Result<Expr, Error>
pub fn fp_sub( &mut self, format: FpFormat, rm: RoundingMode, a: Expr, b: Expr, ) -> Result<Expr, Error>
a − b, built as a + neg(b) (the same function, bit for bit).
Sourcepub fn fp_neg(&mut self, format: FpFormat, a: Expr) -> Result<Expr, Error>
pub fn fp_neg(&mut self, format: FpFormat, a: Expr) -> Result<Expr, Error>
a with its sign bit flipped (a NaN too): a ^ sign.
Sourcepub fn fp_abs(&mut self, format: FpFormat, a: Expr) -> Result<Expr, Error>
pub fn fp_abs(&mut self, format: FpFormat, a: Expr) -> Result<Expr, Error>
a with its sign bit cleared (a NaN too): a & ~sign.
Sourcepub fn fp_copysign(
&mut self,
format: FpFormat,
a: Expr,
b: Expr,
) -> Result<Expr, Error>
pub fn fp_copysign( &mut self, format: FpFormat, a: Expr, b: Expr, ) -> Result<Expr, Error>
a with the sign bit of b.
Sourcepub fn fp_cmp(
&mut self,
format: FpFormat,
op: FpCmpOp,
a: Expr,
b: Expr,
) -> Result<Expr, Error>
pub fn fp_cmp( &mut self, format: FpFormat, op: FpCmpOp, a: Expr, b: Expr, ) -> Result<Expr, Error>
A comparison (1 bit; false when either operand is a NaN).
Sourcepub fn fp_test(
&mut self,
format: FpFormat,
t: FpTest,
a: Expr,
) -> Result<Expr, Error>
pub fn fp_test( &mut self, format: FpFormat, t: FpTest, a: Expr, ) -> Result<Expr, Error>
A classification test (1 bit).
Sourcepub fn x87_load(&mut self, a: Expr) -> Result<Expr, Error>
pub fn x87_load(&mut self, a: Expr) -> Result<Expr, Error>
The x87 load of an 80-bit extended-precision encoding, as a value of
FpFormat::X87; see crate::fp::x87_load.
Sourcepub fn x87_store(&mut self, a: Expr) -> Result<Expr, Error>
pub fn x87_store(&mut self, a: Expr) -> Result<Expr, Error>
The x87 store of a value of FpFormat::X87 as its 80-bit encoding; see
crate::fp::x87_store.
Source§impl Context
impl Context
Sourcepub fn fork(&self) -> Self
pub fn fork(&self) -> Self
An independent copy that accepts every expression already built in this context.
The immutable evaluation schedule is a cache and is rebuilt on demand. Expressions built after the fork belong only to the context that built them and must not cross between the two.
Sourcepub fn new() -> Self
pub fn new() -> Self
An empty context with the default configuration. Allocates nothing until the first node.
Examples found in repository?
7fn main() {
8 let strategy = if std::env::args().any(|a| a == "--deobfuscate") {
9 Strategy::deobfuscate()
10 } else {
11 Strategy::standard()
12 };
13 let engine = Engine::builder()
14 .builtin()
15 .strategy(strategy)
16 .build()
17 .unwrap();
18 let mut invalid = false;
19 for line in io::stdin().lock().lines() {
20 let line = line.unwrap();
21 let fields: Vec<_> = line.split('\t').collect();
22 if fields.len() != 4 {
23 panic!("expected id/width/input/reference");
24 }
25 let mut cx = Context::new();
26 let options = ParseOptions::width(Width::new(fields[1].parse().unwrap()).unwrap());
27 let result = (|| -> Result<_, Box<dyn std::error::Error>> {
28 let input = cx.parse(fields[2], &options)?;
29 let reference = cx.parse(fields[3], &options)?;
30 let before = cx.tree_size(input)?;
31 if !agrees(&mut cx, &[input, reference])? {
32 return Ok((
33 "invalid-reference",
34 before,
35 before,
36 cx.tree_size(reference)?,
37 cx.display(input).to_string().replace(['\n', '\t'], " "),
38 cx.display(reference).to_string().replace(['\n', '\t'], " "),
39 ));
40 }
41 let output = engine.simplify(&mut cx, input)?.expr;
42 let want = engine.simplify(&mut cx, reference)?.expr;
43 let after = cx.tree_size(output)?;
44 let target = cx.tree_size(want)?;
45 let status = if !agrees(&mut cx, &[input, reference, output, want])? {
46 "invalid-output"
47 } else if output == want {
48 "covered"
49 } else if after > target {
50 "gap"
51 } else {
52 "different-form"
53 };
54 Ok((
55 status,
56 before,
57 after,
58 target,
59 cx.display(output).to_string().replace(['\n', '\t'], " "),
60 cx.display(want).to_string().replace(['\n', '\t'], " "),
61 ))
62 })();
63 match result {
64 Ok((status, before, after, target, output, want)) => {
65 invalid |= status.starts_with("invalid-");
66 println!(
67 "{}\t{}\t{status}\t{before}\t{after}\t{target}\t{output}\t{want}",
68 fields[0], fields[1]
69 );
70 }
71 Err(error) => {
72 invalid = true;
73 println!(
74 "{}\t{}\terror\t{}",
75 fields[0],
76 fields[1],
77 error.to_string().replace(['\n', '\t'], " ")
78 );
79 }
80 }
81 }
82 if invalid {
83 std::process::exit(1);
84 }
85}More examples
25fn main() {
26 let mut args = std::env::args_os().skip(1);
27 let dir = args.next().expect("directory [--default-strategy]");
28 let default_strategy = match args.next() {
29 None => false,
30 Some(arg) if arg == "--default-strategy" && args.next().is_none() => true,
31 _ => panic!("usage: engine_corpus DIR [--default-strategy]"),
32 };
33 let mut files: Vec<_> = std::fs::read_dir(&dir)
34 .expect("read dir")
35 .filter_map(|e| e.ok().map(|e| e.path()))
36 .collect();
37 files.sort();
38 let solver: Arc<dyn MbaSolver> = Arc::new(NormalFormSolver::new(
39 NfOptions::default()
40 .with_memo(1 << 14)
41 .with_basis_sums(default_strategy),
42 ));
43 let build = |m| {
44 let strategy = Strategy::deobfuscate().with_mba(m);
45 let strategy = if default_strategy {
46 strategy
47 } else {
48 strategy.with_basis_sums(false).with_kept_steps(1 << 12)
49 };
50 Engine::builder()
51 .builtin()
52 .strategy(strategy)
53 .mba_solver(Arc::clone(&solver))
54 .build()
55 .unwrap()
56 };
57 let (stock_engine, forms_engine) = (build(stock()), build(forms()));
58 let mut missing_assumptions = 0usize;
59 for f in files {
60 let mut cx = Context::new();
61 let text = std::fs::read_to_string(&f).unwrap();
62 if text.lines().any(|line| line == "# assumptions: true") {
63 missing_assumptions += 1;
64 }
65 let what = text
66 .lines()
67 .find_map(|l| l.strip_prefix("# engine: "))
68 .unwrap_or("deep")
69 .to_owned();
70 let fuel: u64 = text
71 .lines()
72 .find_map(|l| l.strip_prefix("# fuel: "))
73 .and_then(|v| v.parse().ok())
74 .unwrap_or(1 << 19);
75 let Some(root) = text.split("## root 0\n").nth(1) else {
76 continue;
77 };
78 let e = match cx.parse(root.trim(), &ParseOptions::width(Width::W64)) {
79 Ok(e) => e,
80 Err(err) => {
81 println!("{} parse-error {err}", f.display());
82 continue;
83 }
84 };
85 let engine = if what == "forms" {
86 &forms_engine
87 } else {
88 &stock_engine
89 };
90 let t = std::time::Instant::now();
91 let out = engine.run(
92 &mut cx,
93 &[e],
94 Run::default().with_per_call(Budget::fuel(fuel)),
95 );
96 let ms = t.elapsed().as_secs_f64() * 1e3;
97 let name = f.file_name().unwrap().to_string_lossy();
98 let o = match out {
99 Ok(o) => o,
100 Err(err) => {
101 println!("{name} {what} {ms:.2} error={err}");
102 continue;
103 }
104 };
105 let r = o.roots[0].expr;
106 let Bounded::Exact(nodes) = cx.dag_size(&[r], u32::MAX).expect("a result") else {
107 unreachable!("the arena's node indices fit in u32")
108 };
109 match cx.view(r).expect("a result") {
110 View::Const(v) => println!("{name} {what} {ms:.2} nodes={nodes} constant={v}"),
111 _ => println!("{name} {what} {ms:.2} nodes={nodes} constant=-"),
112 }
113 }
114 if missing_assumptions > 0 {
115 eprintln!("{missing_assumptions} inputs marked as assumed were replayed unconstrained");
116 }
117}Sourcepub fn with_config(config: ContextConfig) -> Self
pub fn with_config(config: ContextConfig) -> Self
An empty context.
Sourcepub fn with_registry(config: ContextConfig, registry: Arc<Registry>) -> Self
pub fn with_registry(config: ContextConfig, registry: Arc<Registry>) -> Self
An empty context that can build the extension operations of registry.
Sourcepub fn extend_registry(&mut self, registry: Arc<Registry>) -> Result<(), Error>
pub fn extend_registry(&mut self, registry: Arc<Registry>) -> Result<(), Error>
Replaces the registry by one that extends it: every operation of the current registry is
at the same position in registry (same name, revision and traits), so every existing
node keeps its meaning and canonical form. Otherwise an error, and nothing changes.
Sourcepub fn config(&self) -> &ContextConfig
pub fn config(&self) -> &ContextConfig
The configuration.
Sourcepub fn set_max_nodes(&mut self, n: u32)
pub fn set_max_nodes(&mut self, n: u32)
Changes the node limit (ContextConfig::max_nodes). Existing nodes stay; a limit
below the current size only stops new nodes from being created (lookups of existing
structure still succeed).
Sourcepub fn clear(&mut self)
pub fn clear(&mut self)
Removes every node and symbol, keeping allocations. Handles created before the call
become stale and are rejected with Error::StaleExpr.
Sourcepub fn checkpoint(&self) -> Checkpoint
pub fn checkpoint(&self) -> Checkpoint
The state to come back to with rollback: what the context holds
now.
Sourcepub fn rollback(&mut self, at: Checkpoint) -> Result<(), Error>
pub fn rollback(&mut self, at: Checkpoint) -> Result<(), Error>
Removes every node and symbol created since at and gives their memory back to the
context: the expressions of a query against a state that stays (a path condition and
what it is built from), without the context growing with each query.
Handles created before the checkpoint stay valid and mean what they meant. Handles
created after it must not be used again: one is refused (Error::ForeignExpr)
until the context has grown past its index, and names another node after that, which
no check can tell. Drop everything that holds such handles first (a
Solver does with
forget_since).
What the library remembers of the removed nodes goes with them; of the others, the
facts stay, and the simplifier’s remembered results are dropped (they may name
removed nodes). An error, and nothing changes, when the checkpoint is of another
context, of before a clear, or of a state this context has already
been rolled back past.
Sourcepub fn forget_results(&mut self)
pub fn forget_results(&mut self)
Forgets the results the engine keeps for the expressions of this context (what it made of each node the last times it ran), and nothing else: the next run simplifies as in a context that had only been built.
A result is kept for a node, whatever the root it was found under, and the passes that read a node’s surroundings (how often it is used, which of its bits are read) may make something else of it under another root. So in a context that lives long, what the engine makes of an expression can depend on the expressions it was given before that share parts with it: always an equal expression, not always the same one. A host that wants results that depend less on what came before calls this between its questions, and pays for the results it would have had.
Less, not never. The passes count a node’s uses over the nodes of the expression and
the nodes the run creates, and a node an earlier run left in the context is not created
again, so the count of what it uses can differ. For the same result as in a context of
its own, a question is asked between a checkpoint and a
rollback, which removes what it built (the result is taken out
first, as text or by import into another context).
Sourcepub fn reserve(&mut self, additional: usize)
pub fn reserve(&mut self, additional: usize)
Makes room for at least additional more nodes without reallocating (a host that knows
the size of the function it is about to build). Nodes are still created only on demand,
and ContextConfig::max_nodes still bounds them.
Sourcepub fn counters(&self) -> ArenaCounters
pub fn counters(&self) -> ArenaCounters
Node creation counters.
Sourcepub fn caller_growth_since(&self, mark: Mark) -> u64
pub fn caller_growth_since(&self, mark: Mark) -> u64
New nodes created by the caller since mark (all of them, if the mark is from another
context or from before a clear()). Nodes created by the library itself are not counted.
Sourcepub fn structural_hash(&self, e: Expr) -> Result<u64, Error>
pub fn structural_hash(&self, e: Expr) -> Result<u64, Error>
The structural hash of an expression: a function of the expression alone (its
operators, widths, constants and symbol keys), the same in every context and
whatever was built before it, under one HASH_VERSION. Equal
expressions hash alike; as with any hash, different ones may too. A fresh symbol
(fresh_symbol) hashes by its number, which is of its context.
Sourcepub fn shape_hashes(&mut self, roots: &[Expr]) -> Result<Vec<u64>, Error>
pub fn shape_hashes(&mut self, roots: &[Expr]) -> Result<Vec<u64>, Error>
The hash of each root’s shape: its operators and widths with every constant read as
“a constant of its width” and every symbol as “a symbol of its width”, and the
operands of a commutative operator in no order. Expressions that differ only in
constants, in which symbols they read, or in the order construction gave such
operands (it depends on both) have one shape: the key under which what was learned
from one is looked up for the others. A function of the expression alone, under one
HASH_VERSION.
Sourcepub fn view(&self, e: Expr) -> Result<View, Error>
pub fn view(&self, e: Expr) -> Result<View, Error>
A read-only view of an expression’s top node.
Examples found in repository?
25fn main() {
26 let mut args = std::env::args_os().skip(1);
27 let dir = args.next().expect("directory [--default-strategy]");
28 let default_strategy = match args.next() {
29 None => false,
30 Some(arg) if arg == "--default-strategy" && args.next().is_none() => true,
31 _ => panic!("usage: engine_corpus DIR [--default-strategy]"),
32 };
33 let mut files: Vec<_> = std::fs::read_dir(&dir)
34 .expect("read dir")
35 .filter_map(|e| e.ok().map(|e| e.path()))
36 .collect();
37 files.sort();
38 let solver: Arc<dyn MbaSolver> = Arc::new(NormalFormSolver::new(
39 NfOptions::default()
40 .with_memo(1 << 14)
41 .with_basis_sums(default_strategy),
42 ));
43 let build = |m| {
44 let strategy = Strategy::deobfuscate().with_mba(m);
45 let strategy = if default_strategy {
46 strategy
47 } else {
48 strategy.with_basis_sums(false).with_kept_steps(1 << 12)
49 };
50 Engine::builder()
51 .builtin()
52 .strategy(strategy)
53 .mba_solver(Arc::clone(&solver))
54 .build()
55 .unwrap()
56 };
57 let (stock_engine, forms_engine) = (build(stock()), build(forms()));
58 let mut missing_assumptions = 0usize;
59 for f in files {
60 let mut cx = Context::new();
61 let text = std::fs::read_to_string(&f).unwrap();
62 if text.lines().any(|line| line == "# assumptions: true") {
63 missing_assumptions += 1;
64 }
65 let what = text
66 .lines()
67 .find_map(|l| l.strip_prefix("# engine: "))
68 .unwrap_or("deep")
69 .to_owned();
70 let fuel: u64 = text
71 .lines()
72 .find_map(|l| l.strip_prefix("# fuel: "))
73 .and_then(|v| v.parse().ok())
74 .unwrap_or(1 << 19);
75 let Some(root) = text.split("## root 0\n").nth(1) else {
76 continue;
77 };
78 let e = match cx.parse(root.trim(), &ParseOptions::width(Width::W64)) {
79 Ok(e) => e,
80 Err(err) => {
81 println!("{} parse-error {err}", f.display());
82 continue;
83 }
84 };
85 let engine = if what == "forms" {
86 &forms_engine
87 } else {
88 &stock_engine
89 };
90 let t = std::time::Instant::now();
91 let out = engine.run(
92 &mut cx,
93 &[e],
94 Run::default().with_per_call(Budget::fuel(fuel)),
95 );
96 let ms = t.elapsed().as_secs_f64() * 1e3;
97 let name = f.file_name().unwrap().to_string_lossy();
98 let o = match out {
99 Ok(o) => o,
100 Err(err) => {
101 println!("{name} {what} {ms:.2} error={err}");
102 continue;
103 }
104 };
105 let r = o.roots[0].expr;
106 let Bounded::Exact(nodes) = cx.dag_size(&[r], u32::MAX).expect("a result") else {
107 unreachable!("the arena's node indices fit in u32")
108 };
109 match cx.view(r).expect("a result") {
110 View::Const(v) => println!("{name} {what} {ms:.2} nodes={nodes} constant={v}"),
111 _ => println!("{name} {what} {ms:.2} nodes={nodes} constant=-"),
112 }
113 }
114 if missing_assumptions > 0 {
115 eprintln!("{missing_assumptions} inputs marked as assumed were replayed unconstrained");
116 }
117}Sourcepub fn children(
&self,
e: Expr,
) -> Result<impl Iterator<Item = Expr> + '_, Error>
pub fn children( &self, e: Expr, ) -> Result<impl Iterator<Item = Expr> + '_, Error>
The expression’s direct operands, in order.
Sourcepub fn as_const(&self, e: Expr) -> Result<Option<BitVec>, Error>
pub fn as_const(&self, e: Expr) -> Result<Option<BitVec>, Error>
The value, if the expression is a constant node.
Sourcepub fn is_leaf(&self, e: Expr) -> Result<bool, Error>
pub fn is_leaf(&self, e: Expr) -> Result<bool, Error>
Whether the expression is a constant or a symbol.
Sourcepub fn height(&self, e: Expr) -> Result<u32, Error>
pub fn height(&self, e: Expr) -> Result<u32, Error>
Structural depth (leaves are 0), saturating at u32::MAX. O(1).
Sourcepub fn tree_size(&self, e: Expr) -> Result<u32, Error>
pub fn tree_size(&self, e: Expr) -> Result<u32, Error>
The size of the expression unfolded as a tree, saturating at u32::MAX. O(1).
Examples found in repository?
7fn main() {
8 let strategy = if std::env::args().any(|a| a == "--deobfuscate") {
9 Strategy::deobfuscate()
10 } else {
11 Strategy::standard()
12 };
13 let engine = Engine::builder()
14 .builtin()
15 .strategy(strategy)
16 .build()
17 .unwrap();
18 let mut invalid = false;
19 for line in io::stdin().lock().lines() {
20 let line = line.unwrap();
21 let fields: Vec<_> = line.split('\t').collect();
22 if fields.len() != 4 {
23 panic!("expected id/width/input/reference");
24 }
25 let mut cx = Context::new();
26 let options = ParseOptions::width(Width::new(fields[1].parse().unwrap()).unwrap());
27 let result = (|| -> Result<_, Box<dyn std::error::Error>> {
28 let input = cx.parse(fields[2], &options)?;
29 let reference = cx.parse(fields[3], &options)?;
30 let before = cx.tree_size(input)?;
31 if !agrees(&mut cx, &[input, reference])? {
32 return Ok((
33 "invalid-reference",
34 before,
35 before,
36 cx.tree_size(reference)?,
37 cx.display(input).to_string().replace(['\n', '\t'], " "),
38 cx.display(reference).to_string().replace(['\n', '\t'], " "),
39 ));
40 }
41 let output = engine.simplify(&mut cx, input)?.expr;
42 let want = engine.simplify(&mut cx, reference)?.expr;
43 let after = cx.tree_size(output)?;
44 let target = cx.tree_size(want)?;
45 let status = if !agrees(&mut cx, &[input, reference, output, want])? {
46 "invalid-output"
47 } else if output == want {
48 "covered"
49 } else if after > target {
50 "gap"
51 } else {
52 "different-form"
53 };
54 Ok((
55 status,
56 before,
57 after,
58 target,
59 cx.display(output).to_string().replace(['\n', '\t'], " "),
60 cx.display(want).to_string().replace(['\n', '\t'], " "),
61 ))
62 })();
63 match result {
64 Ok((status, before, after, target, output, want)) => {
65 invalid |= status.starts_with("invalid-");
66 println!(
67 "{}\t{}\t{status}\t{before}\t{after}\t{target}\t{output}\t{want}",
68 fields[0], fields[1]
69 );
70 }
71 Err(error) => {
72 invalid = true;
73 println!(
74 "{}\t{}\terror\t{}",
75 fields[0],
76 fields[1],
77 error.to_string().replace(['\n', '\t'], " ")
78 );
79 }
80 }
81 }
82 if invalid {
83 std::process::exit(1);
84 }
85}Sourcepub fn symbol(
&mut self,
key: impl Into<SymbolKey>,
width: Width,
) -> Result<Expr, Error>
pub fn symbol( &mut self, key: impl Into<SymbolKey>, width: Width, ) -> Result<Expr, Error>
The symbol for key, created at width width on first use. A key has exactly one
width per context.
Sourcepub fn fresh_symbol(&mut self, width: Width) -> Result<Expr, Error>
pub fn fresh_symbol(&mut self, width: Width) -> Result<Expr, Error>
A new symbol with a key that is not yet used in this context.
Sourcepub fn find_symbol(&self, key: &SymbolKey) -> Option<Expr>
pub fn find_symbol(&self, key: &SymbolKey) -> Option<Expr>
The symbol for key, if it exists. Never creates.
Sourcepub fn symbol_id(&self, e: Expr) -> Result<Option<SymbolId>, Error>
pub fn symbol_id(&self, e: Expr) -> Result<Option<SymbolId>, Error>
The symbol id, if the expression is a symbol node.
Sourcepub fn symbol_key(&self, id: SymbolId) -> Option<&SymbolKey>
pub fn symbol_key(&self, id: SymbolId) -> Option<&SymbolKey>
A symbol’s key.
Sourcepub fn symbol_width(&self, id: SymbolId) -> Option<Width>
pub fn symbol_width(&self, id: SymbolId) -> Option<Width>
A symbol’s width.
Sourcepub fn symbol_count(&self) -> usize
pub fn symbol_count(&self) -> usize
The number of symbols.
Sourcepub fn declare_known(&mut self, s: Expr, known: KnownBits) -> Result<(), Error>
pub fn declare_known(&mut self, s: Expr, known: KnownBits) -> Result<(), Error>
Declares what the host knows of the value of symbol s: every bit known has as zero
or one is that bit of every value the symbol stands for (a compiler’s known bits of a
parameter, a load or a call result). It replaces any earlier declaration;
KnownBits::unknown withdraws it.
The declaration becomes part of the symbol’s meaning. Facts, proofs and the simplifier
use it, and a result is equal to its input for every value of the symbols that agrees
with their declarations, not for others. Evaluating at a value that does not agree is
the host’s error. A declaration drops the context’s facts and simplification memo
(both may depend on it), so declare right after creating the symbol. Existing assumption
sets are repropagated from their original constraints when subsequently queried;
Assumptions::refresh also updates their diagnostics.
use bitwright::{BitVec, Context, KnownBits, ParseOptions, Query, Truth, Width};
let mut cx = Context::new();
let x = cx.symbol("x", Width::W8)?;
// The top four bits of `x` are zero.
let zero = BitVec::from_u64(Width::W8, 0xf0)?;
cx.declare_known(x, KnownBits::new(zero, BitVec::zero(Width::W8)).unwrap())?;
let high = cx.parse("x >>u 4", &ParseOptions::width(Width::W8))?;
assert_eq!(cx.prove(Query::IsZero(high))?, Truth::True);Sourcepub fn declared_known(&self, s: Expr) -> Result<Option<KnownBits>, Error>
pub fn declared_known(&self, s: Expr) -> Result<Option<KnownBits>, Error>
The known bits declared for symbol s (declare_known), if any.
Sourcepub fn post_order(&mut self, roots: &[Expr]) -> Result<Vec<Expr>, Error>
pub fn post_order(&mut self, roots: &[Expr]) -> Result<Vec<Expr>, Error>
Every node reachable from roots, each once, children before parents. Iterative.
Sourcepub fn symbols_in(&mut self, roots: &[Expr]) -> Result<Vec<SymbolId>, Error>
pub fn symbols_in(&mut self, roots: &[Expr]) -> Result<Vec<SymbolId>, Error>
The symbols reachable from roots, sorted by key.
Sourcepub fn dag_size(&mut self, roots: &[Expr], cap: u32) -> Result<Bounded, Error>
pub fn dag_size(&mut self, roots: &[Expr], cap: u32) -> Result<Bounded, Error>
The number of distinct nodes reachable from roots, walking at most cap + 1 nodes.
Exact single-root results are cached.
Examples found in repository?
25fn main() {
26 let mut args = std::env::args_os().skip(1);
27 let dir = args.next().expect("directory [--default-strategy]");
28 let default_strategy = match args.next() {
29 None => false,
30 Some(arg) if arg == "--default-strategy" && args.next().is_none() => true,
31 _ => panic!("usage: engine_corpus DIR [--default-strategy]"),
32 };
33 let mut files: Vec<_> = std::fs::read_dir(&dir)
34 .expect("read dir")
35 .filter_map(|e| e.ok().map(|e| e.path()))
36 .collect();
37 files.sort();
38 let solver: Arc<dyn MbaSolver> = Arc::new(NormalFormSolver::new(
39 NfOptions::default()
40 .with_memo(1 << 14)
41 .with_basis_sums(default_strategy),
42 ));
43 let build = |m| {
44 let strategy = Strategy::deobfuscate().with_mba(m);
45 let strategy = if default_strategy {
46 strategy
47 } else {
48 strategy.with_basis_sums(false).with_kept_steps(1 << 12)
49 };
50 Engine::builder()
51 .builtin()
52 .strategy(strategy)
53 .mba_solver(Arc::clone(&solver))
54 .build()
55 .unwrap()
56 };
57 let (stock_engine, forms_engine) = (build(stock()), build(forms()));
58 let mut missing_assumptions = 0usize;
59 for f in files {
60 let mut cx = Context::new();
61 let text = std::fs::read_to_string(&f).unwrap();
62 if text.lines().any(|line| line == "# assumptions: true") {
63 missing_assumptions += 1;
64 }
65 let what = text
66 .lines()
67 .find_map(|l| l.strip_prefix("# engine: "))
68 .unwrap_or("deep")
69 .to_owned();
70 let fuel: u64 = text
71 .lines()
72 .find_map(|l| l.strip_prefix("# fuel: "))
73 .and_then(|v| v.parse().ok())
74 .unwrap_or(1 << 19);
75 let Some(root) = text.split("## root 0\n").nth(1) else {
76 continue;
77 };
78 let e = match cx.parse(root.trim(), &ParseOptions::width(Width::W64)) {
79 Ok(e) => e,
80 Err(err) => {
81 println!("{} parse-error {err}", f.display());
82 continue;
83 }
84 };
85 let engine = if what == "forms" {
86 &forms_engine
87 } else {
88 &stock_engine
89 };
90 let t = std::time::Instant::now();
91 let out = engine.run(
92 &mut cx,
93 &[e],
94 Run::default().with_per_call(Budget::fuel(fuel)),
95 );
96 let ms = t.elapsed().as_secs_f64() * 1e3;
97 let name = f.file_name().unwrap().to_string_lossy();
98 let o = match out {
99 Ok(o) => o,
100 Err(err) => {
101 println!("{name} {what} {ms:.2} error={err}");
102 continue;
103 }
104 };
105 let r = o.roots[0].expr;
106 let Bounded::Exact(nodes) = cx.dag_size(&[r], u32::MAX).expect("a result") else {
107 unreachable!("the arena's node indices fit in u32")
108 };
109 match cx.view(r).expect("a result") {
110 View::Const(v) => println!("{name} {what} {ms:.2} nodes={nodes} constant={v}"),
111 _ => println!("{name} {what} {ms:.2} nodes={nodes} constant=-"),
112 }
113 }
114 if missing_assumptions > 0 {
115 eprintln!("{missing_assumptions} inputs marked as assumed were replayed unconstrained");
116 }
117}Source§impl Context
impl Context
Sourcepub fn facts(&mut self, e: Expr) -> Result<Facts, Error>
pub fn facts(&mut self, e: Expr) -> Result<Facts, Error>
Facts about e. If the per-query work cap (ContextConfig::fact_work) is reached,
the answer is Facts::top (sound, just imprecise); see Context::try_facts.
Sourcepub fn try_facts(&mut self, e: Expr) -> Result<Option<Facts>, Error>
pub fn try_facts(&mut self, e: Expr) -> Result<Option<Facts>, Error>
Facts about e, or None if the per-query work cap was reached first. Progress is
kept: repeating the call for the same expression continues where it stopped.
Sourcepub fn exact(&mut self, e: Expr) -> Result<Option<BitVec>, Error>
pub fn exact(&mut self, e: Expr) -> Result<Option<BitVec>, Error>
The value of e if its facts pin exactly one.
Sourcepub fn enumerate_values(
&mut self,
e: Expr,
limit: u32,
) -> Result<Option<Vec<BitVec>>, Error>
pub fn enumerate_values( &mut self, e: Expr, limit: u32, ) -> Result<Option<Vec<BitVec>>, Error>
The values e’s facts allow, if there are at most limit of them (and at most 2^20
candidates to examine). Every value e can take is included; some included values may
be impossible, since facts over-approximate.
Sourcepub fn facts_with(
&mut self,
e: Expr,
assumptions: &Assumptions,
) -> Result<Option<Facts>, Error>
pub fn facts_with( &mut self, e: Expr, assumptions: &Assumptions, ) -> Result<Option<Facts>, Error>
Facts about e under assumptions, or None if the assumptions are infeasible for
the part of the expression that e depends on. Never pollutes the base cache.
Sourcepub fn facts_under(
&mut self,
e: Expr,
assumptions: &Assumptions,
) -> Result<Option<(Facts, Reliance)>, Error>
pub fn facts_under( &mut self, e: Expr, assumptions: &Assumptions, ) -> Result<Option<(Facts, Reliance)>, Error>
Facts about e under assumptions, with the constraints they rely on; None if the
assumptions are infeasible. Never pollutes the base cache.
Sourcepub fn prove(&mut self, q: Query<'_>) -> Result<Truth, Error>
pub fn prove(&mut self, q: Query<'_>) -> Result<Truth, Error>
Answers a question from facts. Every True/False is proved; Unknown otherwise.
Sourcepub fn prove_with(
&mut self,
q: Query<'_>,
assumptions: &Assumptions,
) -> Result<Truth, Error>
pub fn prove_with( &mut self, q: Query<'_>, assumptions: &Assumptions, ) -> Result<Truth, Error>
Answers a question from facts under assumptions. Infeasible assumptions prove
anything: every well-formed question is answered True.
Sourcepub fn prove_under(
&mut self,
q: Query<'_>,
assumptions: &Assumptions,
) -> Result<Proof, Error>
pub fn prove_under( &mut self, q: Query<'_>, assumptions: &Assumptions, ) -> Result<Proof, Error>
Context::prove_with, also reporting the constraints the answer relies on.
Source§impl Context
impl Context
Sourcepub fn parse(&mut self, src: &str, opts: &ParseOptions) -> Result<Expr, Error>
pub fn parse(&mut self, src: &str, opts: &ParseOptions) -> Result<Expr, Error>
Parses an expression in the text syntax (see docs/design.md §7.1), creating symbols
as needed, and builds it through the canonicalizing constructors.
use bitwright::{Context, ParseOptions, Width};
let mut cx = Context::new();
let e = cx.parse("(y | x) + (y & x)", &ParseOptions::width(Width::W64))?;
// Built canonically: operands of commutative operators in one order.
assert_eq!(cx.display(e).to_string(), "(x & y) + (x | y)");Examples found in repository?
7fn main() {
8 let strategy = if std::env::args().any(|a| a == "--deobfuscate") {
9 Strategy::deobfuscate()
10 } else {
11 Strategy::standard()
12 };
13 let engine = Engine::builder()
14 .builtin()
15 .strategy(strategy)
16 .build()
17 .unwrap();
18 let mut invalid = false;
19 for line in io::stdin().lock().lines() {
20 let line = line.unwrap();
21 let fields: Vec<_> = line.split('\t').collect();
22 if fields.len() != 4 {
23 panic!("expected id/width/input/reference");
24 }
25 let mut cx = Context::new();
26 let options = ParseOptions::width(Width::new(fields[1].parse().unwrap()).unwrap());
27 let result = (|| -> Result<_, Box<dyn std::error::Error>> {
28 let input = cx.parse(fields[2], &options)?;
29 let reference = cx.parse(fields[3], &options)?;
30 let before = cx.tree_size(input)?;
31 if !agrees(&mut cx, &[input, reference])? {
32 return Ok((
33 "invalid-reference",
34 before,
35 before,
36 cx.tree_size(reference)?,
37 cx.display(input).to_string().replace(['\n', '\t'], " "),
38 cx.display(reference).to_string().replace(['\n', '\t'], " "),
39 ));
40 }
41 let output = engine.simplify(&mut cx, input)?.expr;
42 let want = engine.simplify(&mut cx, reference)?.expr;
43 let after = cx.tree_size(output)?;
44 let target = cx.tree_size(want)?;
45 let status = if !agrees(&mut cx, &[input, reference, output, want])? {
46 "invalid-output"
47 } else if output == want {
48 "covered"
49 } else if after > target {
50 "gap"
51 } else {
52 "different-form"
53 };
54 Ok((
55 status,
56 before,
57 after,
58 target,
59 cx.display(output).to_string().replace(['\n', '\t'], " "),
60 cx.display(want).to_string().replace(['\n', '\t'], " "),
61 ))
62 })();
63 match result {
64 Ok((status, before, after, target, output, want)) => {
65 invalid |= status.starts_with("invalid-");
66 println!(
67 "{}\t{}\t{status}\t{before}\t{after}\t{target}\t{output}\t{want}",
68 fields[0], fields[1]
69 );
70 }
71 Err(error) => {
72 invalid = true;
73 println!(
74 "{}\t{}\terror\t{}",
75 fields[0],
76 fields[1],
77 error.to_string().replace(['\n', '\t'], " ")
78 );
79 }
80 }
81 }
82 if invalid {
83 std::process::exit(1);
84 }
85}More examples
25fn main() {
26 let mut args = std::env::args_os().skip(1);
27 let dir = args.next().expect("directory [--default-strategy]");
28 let default_strategy = match args.next() {
29 None => false,
30 Some(arg) if arg == "--default-strategy" && args.next().is_none() => true,
31 _ => panic!("usage: engine_corpus DIR [--default-strategy]"),
32 };
33 let mut files: Vec<_> = std::fs::read_dir(&dir)
34 .expect("read dir")
35 .filter_map(|e| e.ok().map(|e| e.path()))
36 .collect();
37 files.sort();
38 let solver: Arc<dyn MbaSolver> = Arc::new(NormalFormSolver::new(
39 NfOptions::default()
40 .with_memo(1 << 14)
41 .with_basis_sums(default_strategy),
42 ));
43 let build = |m| {
44 let strategy = Strategy::deobfuscate().with_mba(m);
45 let strategy = if default_strategy {
46 strategy
47 } else {
48 strategy.with_basis_sums(false).with_kept_steps(1 << 12)
49 };
50 Engine::builder()
51 .builtin()
52 .strategy(strategy)
53 .mba_solver(Arc::clone(&solver))
54 .build()
55 .unwrap()
56 };
57 let (stock_engine, forms_engine) = (build(stock()), build(forms()));
58 let mut missing_assumptions = 0usize;
59 for f in files {
60 let mut cx = Context::new();
61 let text = std::fs::read_to_string(&f).unwrap();
62 if text.lines().any(|line| line == "# assumptions: true") {
63 missing_assumptions += 1;
64 }
65 let what = text
66 .lines()
67 .find_map(|l| l.strip_prefix("# engine: "))
68 .unwrap_or("deep")
69 .to_owned();
70 let fuel: u64 = text
71 .lines()
72 .find_map(|l| l.strip_prefix("# fuel: "))
73 .and_then(|v| v.parse().ok())
74 .unwrap_or(1 << 19);
75 let Some(root) = text.split("## root 0\n").nth(1) else {
76 continue;
77 };
78 let e = match cx.parse(root.trim(), &ParseOptions::width(Width::W64)) {
79 Ok(e) => e,
80 Err(err) => {
81 println!("{} parse-error {err}", f.display());
82 continue;
83 }
84 };
85 let engine = if what == "forms" {
86 &forms_engine
87 } else {
88 &stock_engine
89 };
90 let t = std::time::Instant::now();
91 let out = engine.run(
92 &mut cx,
93 &[e],
94 Run::default().with_per_call(Budget::fuel(fuel)),
95 );
96 let ms = t.elapsed().as_secs_f64() * 1e3;
97 let name = f.file_name().unwrap().to_string_lossy();
98 let o = match out {
99 Ok(o) => o,
100 Err(err) => {
101 println!("{name} {what} {ms:.2} error={err}");
102 continue;
103 }
104 };
105 let r = o.roots[0].expr;
106 let Bounded::Exact(nodes) = cx.dag_size(&[r], u32::MAX).expect("a result") else {
107 unreachable!("the arena's node indices fit in u32")
108 };
109 match cx.view(r).expect("a result") {
110 View::Const(v) => println!("{name} {what} {ms:.2} nodes={nodes} constant={v}"),
111 _ => println!("{name} {what} {ms:.2} nodes={nodes} constant=-"),
112 }
113 }
114 if missing_assumptions > 0 {
115 eprintln!("{missing_assumptions} inputs marked as assumed were replayed unconstrained");
116 }
117}Source§impl Context
impl Context
Sourcepub fn display(&self, e: Expr) -> Display<'_>
pub fn display(&self, e: Expr) -> Display<'_>
The expression in the text syntax, with the default PrintOptions.
Examples found in repository?
7fn main() {
8 let strategy = if std::env::args().any(|a| a == "--deobfuscate") {
9 Strategy::deobfuscate()
10 } else {
11 Strategy::standard()
12 };
13 let engine = Engine::builder()
14 .builtin()
15 .strategy(strategy)
16 .build()
17 .unwrap();
18 let mut invalid = false;
19 for line in io::stdin().lock().lines() {
20 let line = line.unwrap();
21 let fields: Vec<_> = line.split('\t').collect();
22 if fields.len() != 4 {
23 panic!("expected id/width/input/reference");
24 }
25 let mut cx = Context::new();
26 let options = ParseOptions::width(Width::new(fields[1].parse().unwrap()).unwrap());
27 let result = (|| -> Result<_, Box<dyn std::error::Error>> {
28 let input = cx.parse(fields[2], &options)?;
29 let reference = cx.parse(fields[3], &options)?;
30 let before = cx.tree_size(input)?;
31 if !agrees(&mut cx, &[input, reference])? {
32 return Ok((
33 "invalid-reference",
34 before,
35 before,
36 cx.tree_size(reference)?,
37 cx.display(input).to_string().replace(['\n', '\t'], " "),
38 cx.display(reference).to_string().replace(['\n', '\t'], " "),
39 ));
40 }
41 let output = engine.simplify(&mut cx, input)?.expr;
42 let want = engine.simplify(&mut cx, reference)?.expr;
43 let after = cx.tree_size(output)?;
44 let target = cx.tree_size(want)?;
45 let status = if !agrees(&mut cx, &[input, reference, output, want])? {
46 "invalid-output"
47 } else if output == want {
48 "covered"
49 } else if after > target {
50 "gap"
51 } else {
52 "different-form"
53 };
54 Ok((
55 status,
56 before,
57 after,
58 target,
59 cx.display(output).to_string().replace(['\n', '\t'], " "),
60 cx.display(want).to_string().replace(['\n', '\t'], " "),
61 ))
62 })();
63 match result {
64 Ok((status, before, after, target, output, want)) => {
65 invalid |= status.starts_with("invalid-");
66 println!(
67 "{}\t{}\t{status}\t{before}\t{after}\t{target}\t{output}\t{want}",
68 fields[0], fields[1]
69 );
70 }
71 Err(error) => {
72 invalid = true;
73 println!(
74 "{}\t{}\terror\t{}",
75 fields[0],
76 fields[1],
77 error.to_string().replace(['\n', '\t'], " ")
78 );
79 }
80 }
81 }
82 if invalid {
83 std::process::exit(1);
84 }
85}Sourcepub fn display_with(&self, e: Expr, opts: PrintOptions) -> Display<'_>
pub fn display_with(&self, e: Expr, opts: PrintOptions) -> Display<'_>
The expression in the text syntax.