Skip to main content

Context

Struct Context 

Source
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

Source

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).

Source

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.

Source

pub fn ext_output( &mut self, op: ExtId, k: usize, args: &[Expr], ) -> Result<Expr, Error>

Output k of the extension call op(args).

Source

pub fn constant(&mut self, v: &BitVec) -> Result<Expr, Error>

A constant.

Source

pub fn constant_u64(&mut self, width: Width, v: u64) -> Result<Expr, Error>

The constant v, which must fit in width bits.

Source

pub fn constant_u128(&mut self, width: Width, v: u128) -> Result<Expr, Error>

The constant v, which must fit in width bits.

Source

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.

Source

pub fn zero(&mut self, width: Width) -> Result<Expr, Error>

Zero.

Source

pub fn one(&mut self, width: Width) -> Result<Expr, Error>

One.

Source

pub fn ones(&mut self, width: Width) -> Result<Expr, Error>

All ones.

Source

pub fn bool(&mut self, b: bool) -> Result<Expr, Error>

A 1-bit constant.

Source

pub fn un(&mut self, op: UnOp, a: Expr) -> Result<Expr, Error>

A unary operator.

Source

pub fn bin(&mut self, op: BinOp, a: Expr, b: Expr) -> Result<Expr, Error>

A binary operator; the operands must have the same width.

Source

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.

Source

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).

Source

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).

Source

pub fn trunc(&mut self, a: Expr, to: Width) -> Result<Expr, Error>

The low to bits.

Source

pub fn extract(&mut self, a: Expr, lo: u16, len: Width) -> Result<Expr, Error>

Bits [lo, lo + len).

Source

pub fn concat(&mut self, hi: Expr, lo: Expr) -> Result<Expr, Error>

hi in the high bits, lo in the low bits.

Source

pub fn select( &mut self, cond: Expr, then: Expr, els: Expr, ) -> Result<Expr, Error>

cond ? then : els; the condition must be 1 bit wide.

Source§

impl Context

Source

pub fn not(&mut self, a: Expr) -> Result<Expr, Error>

Bitwise complement.

Source

pub fn neg(&mut self, a: Expr) -> Result<Expr, Error>

Two’s-complement negation.

Source

pub fn popcnt(&mut self, a: Expr) -> Result<Expr, Error>

Number of set bits.

Source

pub fn clz(&mut self, a: Expr) -> Result<Expr, Error>

Leading zeros (clz(0) = W).

Source

pub fn ctz(&mut self, a: Expr) -> Result<Expr, Error>

Trailing zeros (ctz(0) = W).

Source

pub fn bswap(&mut self, a: Expr) -> Result<Expr, Error>

Byte reversal (W % 8 == 0).

Source

pub fn bitrev(&mut self, a: Expr) -> Result<Expr, Error>

Bit reversal.

Source§

impl Context

Source

pub fn add(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

Addition.

Source

pub fn sub(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

Subtraction.

Source

pub fn mul(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

Multiplication.

Source

pub fn umulhi(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

High half of the unsigned double-width product.

Source

pub fn smulhi(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

High half of the signed double-width product.

Source

pub fn udiv(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

Unsigned division (udiv(x, 0) = ones).

Source

pub fn urem(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

Unsigned remainder (urem(x, 0) = x).

Source

pub fn sdiv(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

Signed division (bvsdiv).

Source

pub fn srem(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

Signed remainder (bvsrem).

Source

pub fn and(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

Bitwise and.

Source

pub fn or(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

Bitwise or.

Source

pub fn xor(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

Bitwise exclusive or.

Source

pub fn shl(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

Left shift (a count >= W gives 0).

Source

pub fn lshr(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

Logical right shift (a count >= W gives 0).

Source

pub fn ashr(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

Arithmetic right shift (a count >= W gives the sign fill).

Source

pub fn rotl(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

Rotate left by count mod W.

Source

pub fn rotr(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

Rotate right by count mod W.

Source

pub fn pdep(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

Parallel bit deposit.

Source

pub fn pext(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

Parallel bit extract.

Source§

impl Context

Source

pub fn eq(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

a == b.

Source

pub fn ne(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

a != b.

Source

pub fn ult(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

Unsigned a < b.

Source

pub fn ule(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

Unsigned a <= b.

Source

pub fn ugt(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

Unsigned a > b.

Source

pub fn uge(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

Unsigned a >= b.

Source

pub fn slt(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

Signed a < b.

Source

pub fn sle(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

Signed a <= b.

Source

pub fn sgt(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

Signed a > b.

Source

pub fn sge(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

Signed a >= b.

Source§

impl Context

Derived constructors: they build existing node kinds.

Source

pub fn umin(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

Unsigned minimum.

Source

pub fn umax(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

Unsigned maximum.

Source

pub fn smin(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

Signed minimum.

Source

pub fn smax(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

Signed maximum.

Source

pub fn andn(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

a & ~b.

Source

pub fn orn(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

a | ~b.

Source

pub fn xnor(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

~(a ^ b).

Source

pub fn bit(&mut self, a: Expr, i: u16) -> Result<Expr, Error>

Bit i as a 1-bit value.

Source

pub fn abs(&mut self, a: Expr) -> Result<Expr, Error>

Absolute value (abs(smin) = smin).

Source

pub fn add_carry(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

The carry out of a + b (1 bit).

Source

pub fn sub_borrow(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

The borrow out of a - b (1 bit).

Source

pub fn sadd_overflow(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

Signed overflow of a + b (1 bit).

Source

pub fn ssub_overflow(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

Signed overflow of a - b (1 bit).

Source

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.

Source

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.

Source

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.

Source

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

pub fn mul_wide_u(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

The full 2W-bit unsigned product (2W <= 512).

Source

pub fn mul_wide_s(&mut self, a: Expr, b: Expr) -> Result<Expr, Error>

The full 2W-bit signed product (2W <= 512).

Source§

impl Context

Source

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?
examples/valeria_rule_audit.rs (line 111)
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}
Source

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.

Source

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

Source

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)");
Source

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).

Source

pub fn fp_neg(&mut self, format: FpFormat, a: Expr) -> Result<Expr, Error>

a with its sign bit flipped (a NaN too): a ^ sign.

Source

pub fn fp_abs(&mut self, format: FpFormat, a: Expr) -> Result<Expr, Error>

a with its sign bit cleared (a NaN too): a & ~sign.

Source

pub fn fp_copysign( &mut self, format: FpFormat, a: Expr, b: Expr, ) -> Result<Expr, Error>

a with the sign bit of b.

Source

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).

Source

pub fn fp_test( &mut self, format: FpFormat, t: FpTest, a: Expr, ) -> Result<Expr, Error>

A classification test (1 bit).

Source

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.

Source

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

Source

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.

Source

pub fn new() -> Self

An empty context with the default configuration. Allocates nothing until the first node.

Examples found in repository?
examples/valeria_rule_audit.rs (line 25)
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
Hide additional examples
examples/engine_corpus.rs (line 60)
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

pub fn with_config(config: ContextConfig) -> Self

An empty context.

Source

pub fn with_registry(config: ContextConfig, registry: Arc<Registry>) -> Self

An empty context that can build the extension operations of registry.

Source

pub fn registry(&self) -> Option<&Registry>

The extension operations this context can build.

Source

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.

Source

pub fn config(&self) -> &ContextConfig

The configuration.

Source

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).

Source

pub fn len(&self) -> usize

The number of nodes.

Source

pub fn is_empty(&self) -> bool

Whether the context has no nodes.

Source

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.

Source

pub fn checkpoint(&self) -> Checkpoint

The state to come back to with rollback: what the context holds now.

Source

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.

Source

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).

Source

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.

Source

pub fn counters(&self) -> ArenaCounters

Node creation counters.

Source

pub fn mark(&self) -> Mark

The current position of the caller-growth counter.

Source

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.

Source

pub fn width(&self, e: Expr) -> Result<Width, Error>

The width of an expression.

Source

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.

Source

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.

Source

pub fn view(&self, e: Expr) -> Result<View, Error>

A read-only view of an expression’s top node.

Examples found in repository?
examples/engine_corpus.rs (line 109)
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

pub fn children( &self, e: Expr, ) -> Result<impl Iterator<Item = Expr> + '_, Error>

The expression’s direct operands, in order.

Source

pub fn as_const(&self, e: Expr) -> Result<Option<BitVec>, Error>

The value, if the expression is a constant node.

Source

pub fn is_leaf(&self, e: Expr) -> Result<bool, Error>

Whether the expression is a constant or a symbol.

Source

pub fn height(&self, e: Expr) -> Result<u32, Error>

Structural depth (leaves are 0), saturating at u32::MAX. O(1).

Source

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?
examples/valeria_rule_audit.rs (line 30)
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}
Source

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.

Source

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.

Source

pub fn find_symbol(&self, key: &SymbolKey) -> Option<Expr>

The symbol for key, if it exists. Never creates.

Source

pub fn symbol_id(&self, e: Expr) -> Result<Option<SymbolId>, Error>

The symbol id, if the expression is a symbol node.

Source

pub fn symbol_key(&self, id: SymbolId) -> Option<&SymbolKey>

A symbol’s key.

Source

pub fn symbol_width(&self, id: SymbolId) -> Option<Width>

A symbol’s width.

Source

pub fn symbol_count(&self) -> usize

The number of symbols.

Source

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);
Source

pub fn declared_known(&self, s: Expr) -> Result<Option<KnownBits>, Error>

The known bits declared for symbol s (declare_known), if any.

Source

pub fn post_order(&mut self, roots: &[Expr]) -> Result<Vec<Expr>, Error>

Every node reachable from roots, each once, children before parents. Iterative.

Source

pub fn symbols_in(&mut self, roots: &[Expr]) -> Result<Vec<SymbolId>, Error>

The symbols reachable from roots, sorted by key.

Source

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?
examples/engine_corpus.rs (line 106)
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

Source

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.

Source

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.

Source

pub fn exact(&mut self, e: Expr) -> Result<Option<BitVec>, Error>

The value of e if its facts pin exactly one.

Source

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.

Source

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.

Source

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.

Source

pub fn prove(&mut self, q: Query<'_>) -> Result<Truth, Error>

Answers a question from facts. Every True/False is proved; Unknown otherwise.

Source

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.

Source

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

Source

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?
examples/valeria_rule_audit.rs (line 28)
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
Hide additional examples
examples/engine_corpus.rs (line 78)
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

Source

pub fn display(&self, e: Expr) -> Display<'_>

The expression in the text syntax, with the default PrintOptions.

Examples found in repository?
examples/valeria_rule_audit.rs (line 37)
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}
Source

pub fn display_with(&self, e: Expr, opts: PrintOptions) -> Display<'_>

The expression in the text syntax.

Trait Implementations§

Source§

impl Debug for Context

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Context

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.