Expand description
egg (e-graphs good) is a e-graph library optimized for equality saturation.
This is the API documentation.
The tutorial is a good starting point if you’re new to e-graphs, equality saturation, or Rust.
The tests on Github provide some more elaborate examples.
There is also a paper
describing egg and some of its technical novelties.
§Logging
Many parts of egg dump useful logging info using the log crate.
The easiest way to see this info is to use the env_logger
crate in your binary or test.
The simplest way to enable env_logger is to put the following line near the top of your main:
env_logger::init();.
Then, set the environment variable RUST_LOG=egg=info, or use warn or debug instead of info
for less or more logging.
§Simple Example
use egg::*;
define_language! {
enum SimpleLanguage {
Num(i32),
"+" = Add([Id; 2]),
"*" = Mul([Id; 2]),
Symbol(Symbol),
}
}
fn make_rules() -> Vec<Rewrite<SimpleLanguage, ()>> {
vec![
rewrite!("commute-add"; "(+ ?a ?b)" => "(+ ?b ?a)"),
rewrite!("commute-mul"; "(* ?a ?b)" => "(* ?b ?a)"),
rewrite!("add-0"; "(+ ?a 0)" => "?a"),
rewrite!("mul-0"; "(* ?a 0)" => "0"),
rewrite!("mul-1"; "(* ?a 1)" => "?a"),
]
}
/// parse an expression, simplify it using egg, and pretty print it back out
fn simplify(s: &str) -> String {
// parse the expression, the type annotation tells it which Language to use
let expr: RecExpr<SimpleLanguage> = s.parse().unwrap();
// simplify the expression using a Runner, which creates an e-graph with
// the given expression and runs the given rules over it
let runner = Runner::default().with_expr(&expr).run(&make_rules());
// the Runner knows which e-class the expression given with `with_expr` is in
let root = runner.roots[0];
// use an Extractor to pick the best element of the root eclass
let extractor = Extractor::new(&runner.egraph, AstSize);
let (best_cost, best) = extractor.find_best(root);
println!("Simplified {} to {} with cost {}", expr, best, best_cost);
best.to_string()
}
#[test]
fn simple_tests() {
assert_eq!(simplify("(* 0 42)"), "0");
assert_eq!(simplify("(+ 0 (* 1 foo))"), "foo");
}Modules§
- tutorials
- A Guide-level Explanation of
egg
Macros§
- define_
language - A macro to easily create a
Language. - multi_
rewrite - A macro to easily make
Rewrites usingMultiPatterns. - rewrite
- A macro to easily make
Rewrites. - test_fn
- Utility to make a test proving expressions equivalent
Structs§
- AstDepth
- A simple
CostFunctionthat counts maximum AST depth. - AstSize
- A simple
CostFunctionthat counts total AST size. - Backoff
Scheduler - A
RewriteSchedulerthat implements exponentional rule backoff. - Condition
Equal - A
Conditionthat checks if two terms are equivalent. - Conditional
Applier - An
Applierthat checks aConditionbefore applying. - DidMerge
- Result of
Analysis::mergeindicating which of the inputs are different from the merged result. - Dot
- A wrapper for an
EGraphthat can output GraphViz for visualization. - EClass
- An equivalence class of enodes.
- EGraph
- A data structure to keep track of equalities between expressions.
- Explanation
- A data structure representing an explanation that two terms are equivalent.
- Extractor
- Extracting a single
RecExprfrom anEGraph. - Flat
Term - A single term in an flattened explanation.
After the first term in a
FlatExplanation, each term will be annotated with exactly onebackward_ruleor oneforward_rule. This can appear in childrenFlatTerms, indicating that the child is being rewritten. - From
OpError - A generic error for failing to parse an operator. This is the error type
used by
define_language!forFromOp::Error, and is a sensible choice when implementingFromOpmanually. - Id
- A key to identify
EClasses within anEGraph. - Iteration
- Data generated by running a
Runnerone iteration. - LpExtractor
lp - A structure to perform extraction using integer linear programming.
This uses the
cbcsolver. You must have it installed on your machine to use this feature. You can install it using: - Multi
Pattern - A set of open expressions bound to variables.
- Pattern
- A pattern that can function as either a
SearcherorApplier. - RecExpr
- A recursive expression from a user-defined
Language. - Report
- A report containing data about an entire
Runnerrun. - Rewrite
- A rewrite that searches for the lefthand side and applies the righthand side.
- Runner
- Faciliates running rewrites over an
EGraph. - Runner
Limits - Describes the limits that would stop a
Runner. - Search
Matches - The result of searching a
Searcherover one eclass. - Simple
Language Mapper - An implementation of
LanguageMapperthat can convert anEGraphover one language into anEGraphover a different language in common cases. - Simple
Scheduler - A very simple
RewriteSchedulerthat runs every rewrite every time. - Subst
- A substitution mapping
Vars to eclassIds. - Symbol
- An interned string.
- Symbol
Lang - A simple language used for testing.
- Tree
Term - An explanation for a term and its equivalent children.
Each child is a proof transforming the initial child into the final child term.
The initial term is given by taking each first sub-term
in each
child_proofsrecursively. The final term is given by all of the final terms in eachchild_proofs. - Var
- A variable for use in
Patterns orSubsts.
Enums§
- ENode
OrVar - The language of
Patterns. - Justification
- A justification for a union, either via a rule or congruence. A direct union with a justification is also stored as a rule.
- Multi
Pattern Parse Error - An error raised when parsing a
MultiPattern - RecExpr
Parse Error - An error type for failures when attempting to parse an s-expression as a
RecExpr<L>. - Stop
Reason - Error returned by
Runnerwhen it stops.
Traits§
- Analysis
- Arbitrary data associated with an
EClass. - Applier
- The righthand side of a
Rewrite. - Condition
- A condition to check in a
ConditionalApplier. - Cost
Function - A cost function that can be used by an
Extractor. - FromOp
- A trait for parsing e-nodes. This is implemented automatically by
define_language!. - Iteration
Data - Custom data to inject into the
Iterations recorded by aRunner - Language
- Trait that defines a Language whose terms will be in the
EGraph. - Language
Children - A marker that defines acceptable children types for
define_language!. - Language
Mapper - Translates
EGraph<L, A>intoEGraph<L2, A2>. For common cases, you don’t need to implement this manually. See the providedSimpleLanguageMapper. - LpCost
Function lp - A cost function to be used by an
LpExtractor. - Rewrite
Scheduler - A way to customize how a
RunnerrunsRewrites. - Searcher
- The lefthand side of a
Rewrite.
Functions§
- merge_
max - A utility for implementing
Analysis::mergewhen theDatatype has a total ordering. This will take the maximum of the two values. - merge_
min - A utility for implementing
Analysis::mergewhen theDatatype has a total ordering. This will take the minimum of the two values. - merge_
option - A utility for implementing
Analysis::mergewhen theDatatype is anOption.
Type Aliases§
- Flat
Explanation - FlatExplanation are the simpler, expanded representation
showing one term being rewritten to another.
Each step contains a full
FlatTerm. Each flat term is connected to the previous by exactly one rewrite. - Pattern
Ast - A
RecExprthat represents aPattern. - Runner
Result - Type alias for the result of a
Runner. - Tree
Explanation - Explanation trees are the compact representation showing how one term can be rewritten to another.
- Union
Equalities - A vector of equalities based on enode ids. Each entry represents two enode ids that are equal and why.