EGraph

Struct EGraph 

Source
pub struct EGraph {
    pub parser: Parser,
    pub fact_directory: Option<PathBuf>,
    pub seminaive: bool,
    pub no_decomp: bool,
    /* private fields */
}

Fields§

§parser: Parser§fact_directory: Option<PathBuf>§seminaive: bool§no_decomp: bool

Implementations§

Source§

impl EGraph

Source

pub fn repl(&mut self, mode: RunMode) -> Result<()>

Start a Read-Eval-Print Loop with standard I/O.

Source

pub fn repl_with<R, W>( &mut self, input: R, output: W, mode: RunMode, is_terminal: bool, ) -> Result<()>
where R: Read, W: Write,

Start a Read-Eval-Print Loop with the given input and output channel.

Source§

impl EGraph

Source

pub fn extract_value( &self, sort: &ArcSort, value: Value, ) -> Result<(TermDag, TermId, DefaultCost), Error>

Extract a value to a TermDag and TermId in the TermDag using the default cost model. See also EGraph::extract_value_with_cost_model for more control.

Source

pub fn extract_value_with_cost_model<CM: CostModel<DefaultCost> + 'static>( &self, sort: &ArcSort, value: Value, cost_model: CM, ) -> Result<(TermDag, TermId, DefaultCost), Error>

Extract a value to a TermDag and TermId in the TermDag. Note that the TermDag may contain a superset of the nodes referenced by the returned TermId. See also EGraph::extract_value_to_string for convenience.

Source

pub fn extract_value_to_string( &self, sort: &ArcSort, value: Value, ) -> Result<(String, DefaultCost), Error>

Extract a value to a string for printing. See also EGraph::extract_value for more control.

Source

pub fn function_to_dag( &self, sym: &str, n: usize, include_output: bool, ) -> Result<(Vec<TermId>, Option<Vec<TermId>>, TermDag), Error>

For constructors and relations, the output column can be ignored

Source§

impl EGraph

Source

pub fn add_scheduler(&mut self, scheduler: Box<dyn Scheduler>) -> SchedulerId

Register a new scheduler and return its id.

Source

pub fn remove_scheduler( &mut self, scheduler_id: SchedulerId, ) -> Option<Box<dyn Scheduler>>

Removes a scheduler

Source

pub fn step_rules_with_scheduler( &mut self, scheduler_id: SchedulerId, ruleset: &str, ) -> Result<RunReport, Error>

Runs a ruleset for one iteration using the given ruleset

Source§

impl EGraph

Source

pub fn serialize(&self, config: SerializeConfig) -> SerializeOutput

Serialize the egraph into a format that can be read by the egraph-serialize crate.

There are multiple different semantically valid ways to do this. This is how this implementation does it:

For node costs:

  • Primitives: 1.0
  • Function without costs: 1.0
  • Function with costs: the cost
  • Omitted nodes: infinite

For node IDs:

  • Functions: Function name + hash of input values
  • Args which are eq sorts: Choose one ID from the e-class, distribute roughly evenly.
  • Args and outputs values which are primitives: Sort name + hash of value

For e-classes IDs:

  • tag and value of canonicalized value

This is to achieve the following properties:

  • Equivalent primitive values will show up once in the e-graph.
  • Functions which return primitive values will be added to the e-class of that value.
  • Nodes will have consistant IDs throughout execution of e-graph (used for animating changes in the visualization)
  • Edges in the visualization will be well distributed (used for animating changes in the visualization) (Note that this will be changed in <https://github.com/egraphs-good/egglog/pull/158> so that edges point to exact nodes instead of looking up the e-class)
Source

pub fn value_to_class_id(&self, sort: &ArcSort, value: Value) -> ClassId

Gets the serialized class ID for a value.

Source

pub fn class_id_to_value(&self, eclass_id: &ClassId) -> Value

Gets the value for a serialized class ID.

Source

pub fn to_node_id(&self, sort: Option<&ArcSort>, node: SerializedNode) -> NodeId

Gets the serialized node ID for the primitive, omitted, or function value.

Source

pub fn from_node_id(&self, node_id: &NodeId) -> SerializedNode

Gets the serialized node for the node ID.

Source§

impl EGraph

Source

pub fn add_sort<S: Sort + 'static>( &mut self, sort: S, span: Span, ) -> Result<(), TypeError>

Add a user-defined sort to the e-graph.

Also look at prelude::add_base_sort for a convenience method for adding user-defined sorts

Source

pub fn declare_sort( &mut self, name: impl Into<String>, presort_and_args: &Option<(String, Vec<Expr>)>, span: Span, ) -> Result<(), TypeError>

Declare a sort. This corresponds to the sort keyword in egglog. It can either declares a new EqSort if presort_and_args is not provided, or an instantiation of a presort (e.g., containers like Vec).

Source

pub fn add_arcsort( &mut self, sort: ArcSort, span: Span, ) -> Result<(), TypeError>

Add a user-defined sort to the e-graph.

Source

pub fn add_pure_primitive<T>( &mut self, x: T, validator: Option<PrimitiveValidator>, )
where T: PurePrim + Clone,

Register a PurePrim. Pass None for the validator if not using the proof checker.

Pick the trait whose state wrapper matches the body’s needs: PurePrim for pure ops, WritePrim for writes, ReadPrim for table reads, FullPrim for both. The Rust type checker enforces the body only uses methods the chosen state allows.

Source

pub fn add_write_primitive<T>( &mut self, x: T, validator: Option<PrimitiveValidator>, )
where T: WritePrim + Clone,

Register a WritePrim. Pass None for the validator if not using the proof checker.

Source

pub fn add_read_primitive<T>( &mut self, x: T, validator: Option<PrimitiveValidator>, )
where T: ReadPrim + Clone,

Register a ReadPrim. Pass None for the validator if not using the proof checker.

Source

pub fn add_full_primitive<T>( &mut self, x: T, validator: Option<PrimitiveValidator>, )
where T: FullPrim + Clone,

Register a FullPrim. Pass None for the validator if not using the proof checker.

Source§

impl EGraph

Source

pub fn new_with_term_encoding() -> Self

Create a new e-graph with the term-encoding pipeline enabled.

In term-encoding mode the e-graph eagerly instruments every constructor and function with auxiliary term tables, view tables, and per-sort union-finds so that canonical representatives and their justifications are materialized explicitly. This makes it possible to record and emit equality proofs while preserving the observable behaviour of supported commands.

Source

pub fn new_with_proofs() -> Self

Create a new e-graph with proof generation enabled.

Source

pub fn with_proof_testing(self) -> Self

Enable testing of getting proofs for all check commands.

Source

pub fn set_num_threads(num_threads: usize)

Set the number of threads used for parallel operations.

This is a helper that simply configures the global rayon thread pool. It can only be called once per process; subsequent calls will be ignored.

§Panics

Panics on wasm if num_threads > 1.

Source

pub fn num_threads(&self) -> usize

Return the number of threads in the rayon thread pool.

Source

pub fn extension_state<T>(&self) -> Option<&T>
where T: Send + Sync + 'static,

Return extension-owned state stored on this e-graph.

Extension state is keyed by Rust type and follows the same lifecycle as the rest of the e-graph: cloning an EGraph clones the state, and push/pop snapshots and restores it.

Source

pub fn extension_state_or_default<T>(&mut self) -> &mut T
where T: Default + Clone + Send + Sync + 'static,

Return mutable extension-owned state, inserting T::default() when absent.

Source

pub fn type_info(&mut self) -> &mut TypeInfo

Add a user-defined command to the e-graph Get the type information for this e-graph

Source

pub fn command_macros(&self) -> &CommandMacroRegistry

Get read-only access to the command macro registry

Source

pub fn command_macros_mut(&mut self) -> &mut CommandMacroRegistry

Get mutable access to the command macro registry

Source

pub fn add_command( &mut self, name: String, command: Arc<dyn UserDefinedCommand>, ) -> Result<(), Error>

Source

pub fn set_strict_mode(&mut self, strict_mode: bool)

Configure whether globals missing the required $ prefix are treated as errors.

Source

pub fn strict_mode(&self) -> bool

Returns true when missing $ prefixes on globals are treated as errors.

Source

pub fn push(&mut self)

Push a snapshot of the e-graph into the stack.

See EGraph::pop.

Source

pub fn pop(&mut self) -> Result<(), Error>

Pop the current egraph off the stack, replacing it with the previously pushed egraph. It preserves the run report and messages from the popped egraph.

Source

pub fn print_function( &mut self, sym: &str, n: Option<usize>, file: Option<File>, mode: PrintFunctionMode, ) -> Result<Option<CommandOutput>, Error>

Extract rows of a table using the default cost model with name sym The include_output parameter controls whether the output column is always extracted For functions, the output column is usually useful Print up to n the tuples in a given function. Print all tuples if n is not provided.

Source

pub fn print_size(&self, sym: Option<&str>) -> Result<CommandOutput, Error>

Print the size of a function. If no function name is provided, print the size of all non-hidden functions as an s-expression list of (name size) pairs, e.g. ((name size) ...).

Source

pub fn step_rules(&mut self, ruleset: &str) -> Result<RunReport, Error>

Runs a ruleset for an iteration.

This applies every match it finds (under semi-naive). See EGraph::step_rules_with_scheduler for more fine-grained control.

This will return an error if an egglog primitive returns None in an action.

Source

pub fn get_function_names(&self) -> Vec<String>

Get the list of all functions in the e-graph.

Source

pub fn functions_iter(&self) -> impl Iterator<Item = (&String, &Function)>

Iterate over every (name, function) pair registered in the e-graph, in registration order.

Source

pub fn function_for_each( &self, func_name: &str, f: impl FnMut(FunctionRow<'_>), ) -> Result<(), Error>

Read the contents of the given function. The callback f is called with each row and its subsumption status.

Raises an error if the function does not exist.

Source

pub fn clear_function(&mut self, func_name: &str) -> Result<(), Error>

Remove every row from the named function in bulk.

This is intended as a faster alternative to issuing a (delete …) for every row of the function: it drops the backing row storage in O(1)-in-row-count time, rather than O(n) per-row teardown. Any pending staged inserts/removes for this function are dropped as part of the clear, so callers that have staged updates they want to land first should arrange for those to be flushed beforehand.

Cached indexes and subsets that reference this table are invalidated by a generation bump and are lazily rebuilt against the now-empty table on next access.

Raises an error if the function does not exist.

Source

pub fn eval_expr(&mut self, expr: &Expr) -> Result<(ArcSort, Value), Error>

Evaluates an expression, returns the sort of the expression and the evaluation result.

Source

pub fn are_proofs_enabled(&self) -> bool

Returns true if proofs are enabled.

Source

pub fn run_program( &mut self, program: Vec<Command>, ) -> Result<Vec<CommandOutput>, Error>

Run a program, represented as an AST. Return a list of messages.

Source

pub fn resolve_program( &mut self, filename: Option<String>, input: &str, ) -> Result<Vec<ResolvedCommand>, Error>

Resolves an egglog program by parsing, typechecking, and desugaring each command. Outputs a new egglog program without any syntactic sugar, either user provided (CommandMacro) or built-in (e.g., rewrite commands). Also removes globals from the program by replacing with new constructors.

Source

pub fn parse_program( &mut self, filename: Option<String>, input: &str, ) -> Result<Vec<Command>, Error>

Takes a source program input and parses it into a list of Commands.

Source

pub fn parse_and_run_program( &mut self, filename: Option<String>, input: &str, ) -> Result<Vec<CommandOutput>, Error>

Takes a source program input, parses it, runs it, and returns a list of messages.

filename is an optional argument to indicate the source of the program for error reporting. If filename is None, a default name will be used.

Source

pub fn num_tuples(&self) -> usize

Get the number of tuples in the database.

Source

pub fn get_sort<S: Sort>(&self) -> Arc<S>

Returns a sort based on the type.

Source

pub fn get_sort_by<S: Sort>(&self, f: impl Fn(&Arc<S>) -> bool) -> Arc<S>

Returns a sort that satisfies the type and predicate.

Source

pub fn get_sorts<S: Sort>(&self) -> Vec<Arc<S>>

Returns all sorts based on the type.

Source

pub fn get_sorts_by<S: Sort>(&self, f: impl Fn(&Arc<S>) -> bool) -> Vec<Arc<S>>

Returns all sorts that satisfy the type and predicate.

Source

pub fn get_arcsort_by(&self, f: impl Fn(&ArcSort) -> bool) -> ArcSort

Returns a sort based on the predicate.

Source

pub fn get_arcsort_for_value_type<T: 'static>(&self) -> ArcSort

Returns the unique sort whose runtime values have Rust type T.

Source

pub fn get_arcsorts_by(&self, f: impl Fn(&ArcSort) -> bool) -> Vec<ArcSort>

Returns all sorts that satisfy the predicate.

Source

pub fn get_sort_by_name(&self, sym: &str) -> Option<&ArcSort>

Returns the sort with the given name if it exists.

Source

pub fn get_overall_run_report(&self) -> &RunReport

Gets the overall run report and returns it.

Source

pub fn value_to_base<T: BaseValue>(&self, x: Value) -> T

Convert from an egglog value to a Rust type.

Source

pub fn base_to_value<T: BaseValue>(&self, x: T) -> Value

Convert from a Rust type to an egglog value.

Source

pub fn value_to_container<T: ContainerValue>( &self, x: Value, ) -> Option<impl Deref<Target = T>>

Convert from an egglog value to a reference of a Rust container type.

Returns None if the value cannot be converted to the requested container type.

Warning: The return type of this function may contain lock guards. Attempts to modify the contents of the containers database may deadlock if the given guard has not been dropped.

Source

pub fn container_to_value<T: ContainerValue>(&mut self, x: T) -> Value

Convert from a Rust container type to an egglog value.

Source

pub fn get_size(&self, func: &str) -> usize

Get the size of a function in the e-graph.

panics if the function does not exist.

Source

pub fn lookup_function(&self, name: &str, key: &[Value]) -> Option<Value>

Lookup a tuple in afunction in the e-graph.

Returns None if the tuple does not exist. panics if the function does not exist.

Source

pub fn get_function(&self, name: &str) -> Option<&Function>

Get a function by name.

Returns None if the function does not exist.

Source

pub fn has_command(&self, name: &str) -> bool

Returns true if a user-defined command with the given name is registered in this e-graph.

Source

pub fn run_user_defined_command( &mut self, name: &str, args: &[Expr], ) -> Result<Vec<CommandOutput>, Error>

Invoke a registered user-defined command by name, passing the given unresolved expression arguments.

This is equivalent to writing (name args...) at the top level, but callable directly from Rust. Returns an error if no command with the given name is registered.

Source

pub fn with_full_state<R>( &mut self, f: impl FnOnce(FullState<'_, '_>) -> R, ) -> R

Run a closure with full read-write access to the database, then flush pending writes.

This is the top-level equivalent of FullPrim::apply, and the closure receives a FullState.

Pending writes staged inside the closure are flushed (and the union-find rebuilt if necessary) before this method returns.

Source

pub fn set_report_level(&mut self, level: ReportLevel)

Source

pub fn dump_debug_info(&self)

A basic method for dumping the state of the database to log::info!.

For large tables, this is unlikely to give particularly useful output.

Source

pub fn get_canonical_value(&self, val: Value, sort: &ArcSort) -> Value

Get the canonical representation for val based on type.

Source

pub fn new_union_action(&self) -> UnionAction

Create a new union action that can be used to union two values.

Trait Implementations§

Source§

impl Clone for EGraph

Source§

fn clone(&self) -> EGraph

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Default for EGraph

Source§

fn default() -> Self

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

Auto Trait Implementations§

§

impl Freeze for EGraph

§

impl !RefUnwindSafe for EGraph

§

impl Send for EGraph

§

impl Sync for EGraph

§

impl Unpin for EGraph

§

impl !UnwindSafe for EGraph

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

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

Source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V