Skip to main content

rewrite

Function rewrite 

Source
pub fn rewrite(
    r: &dyn Rewrite,
    inputs: &[&str],
    cfg: &RewriteCheckConfig,
) -> Result<RewriteReport, RewriteFailure>
Expand description

Checks host rewrite r on inputs (text in the expression syntax): a report of what was covered, or the first failure found. The evidence a host gathers in its own test suite before it links the rewrite with EngineBuilder::trusted_rewrite.

Arbitrary code cannot be proved the way a .bwr rule is, so the checker tests it where it applies:

  • at every node of every input, at every width the input parses at, and on variations of it with other constants;
  • each result compared with its node at every assignment of their symbols when those have few bits, and at boundary-biased random points otherwise;
  • what the engine relies on: the result has the node’s width, the same node gives the same result, and the result is smaller in the termination order (else the engine never commits it).

This is testing, not proof, and it covers only the shapes the inputs exercise: give inputs where the rewrite applies and where it nearly does.

use bitwright::check::{RewriteCheckConfig, RewriteFailure, rewrite};
use bitwright::engine::{Rewrite, Site};
use bitwright::{BinOp, Expr, View};

/// `(x ^ c) ^ c` as `x`: right.
struct XorTwice;
impl Rewrite for XorTwice {
    fn name(&self) -> &str { "acme.xor_twice" }
    fn rewrite(&self, site: &mut Site<'_>, e: Expr) -> Option<Expr> {
        let View::Bin(BinOp::Xor, a, c) = site.view(e)? else { return None };
        let View::Bin(BinOp::Xor, x, d) = site.view(a)? else { return None };
        (c == d).then_some(x)
    }
}
let report = rewrite(&XorTwice, &["(x ^ 5) ^ 5", "((y + z) ^ 12) ^ 12"], &RewriteCheckConfig::default())?;
assert!(report.applications > 0);

/// `(x + c) - c` as `x + c`: wrong.
struct Wrong;
impl Rewrite for Wrong {
    fn name(&self) -> &str { "acme.wrong" }
    fn rewrite(&self, site: &mut Site<'_>, e: Expr) -> Option<Expr> {
        let View::Bin(BinOp::Add, a, _) = site.view(e)? else { return None };
        matches!(site.view(a)?, View::Bin(BinOp::Add, ..)).then_some(a)
    }
}
let failure = rewrite(&Wrong, &["(x + 3) - 3"], &RewriteCheckConfig::default()).unwrap_err();
assert!(matches!(failure, RewriteFailure::Differs { .. }));