|
7 | 7 | from __future__ import annotations |
8 | 8 |
|
9 | 9 | from dataclasses import dataclass, field |
10 | | -from functools import cached_property |
| 10 | +from functools import cache, cached_property |
11 | 11 | from itertools import chain, repeat |
12 | 12 | from typing import ( |
13 | 13 | TYPE_CHECKING, |
|
25 | 25 | from uuid import UUID |
26 | 26 | from weakref import WeakValueDictionary |
27 | 27 |
|
| 28 | +from egglog import bindings |
| 29 | + |
28 | 30 | from .bindings import Value |
29 | 31 |
|
30 | 32 | if TYPE_CHECKING: |
|
54 | 56 | "DefaultRewriteDecl", |
55 | 57 | "DelayedDeclarations", |
56 | 58 | "DummyDecl", |
| 59 | + "EGraphDecl", |
57 | 60 | "EqDecl", |
58 | 61 | "ExprActionDecl", |
59 | 62 | "ExprDecl", |
@@ -349,6 +352,175 @@ class CombinedRulesetDecl: |
349 | 352 | rulesets: tuple[Ident, ...] |
350 | 353 |
|
351 | 354 |
|
| 355 | +T_expr_decl = TypeVar("T_expr_decl", bound="ExprDecl") |
| 356 | + |
| 357 | + |
| 358 | +@dataclass(frozen=True) |
| 359 | +class EGraphDecl: |
| 360 | + """ |
| 361 | + State of an e-graph, which when re-added to a new e-graph will reconstruct the same e-graph, given the same Declarations. |
| 362 | +
|
| 363 | + All the expressions in here may reference values which appear in the `e_classes` mapping. |
| 364 | + """ |
| 365 | + |
| 366 | + # Mapping from top level let binding names to their types and expressions |
| 367 | + let_bindings: dict[str, TypedExprDecl] = field(default_factory=dict) |
| 368 | + # Mapping from egglog values representing e-classes to all the expressions in that e-class |
| 369 | + e_classes: dict[bindings.Value, tuple[JustTypeRef, tuple[CallDecl, ...]]] = field(default_factory=dict) |
| 370 | + # Mapping from function calls to the values they are set to |
| 371 | + sets: dict[CallDecl, TypedExprDecl] = field(default_factory=dict) |
| 372 | + # Top-level expr actions such as relation facts. |
| 373 | + expr_actions: tuple[TypedExprDecl, ...] = field(default=()) |
| 374 | + # Mapping from function calls to the set costs. |
| 375 | + costs: dict[CallDecl, tuple[JustTypeRef, int]] = field(default_factory=dict) |
| 376 | + # Set of values which are subsumed |
| 377 | + subsumed: tuple[tuple[JustTypeRef, CallDecl], ...] = field(default=()) |
| 378 | + |
| 379 | + def __hash__(self) -> int: |
| 380 | + return hash(( |
| 381 | + type(self), |
| 382 | + tuple(self.let_bindings.items()), |
| 383 | + tuple((value, tp, exprs) for value, (tp, exprs) in self.e_classes.items()), |
| 384 | + tuple(self.sets.items()), |
| 385 | + self.expr_actions, |
| 386 | + tuple(self.costs.items()), |
| 387 | + self.subsumed, |
| 388 | + )) |
| 389 | + |
| 390 | + @cached_property |
| 391 | + def to_actions(self) -> list[ActionDecl]: # noqa: C901 |
| 392 | + """ |
| 393 | + Converts this egraph decl to a list of actions that can be executed to reconstruct the egraph. |
| 394 | +
|
| 395 | + Converts all e-classes to grounded terms + unions. |
| 396 | +
|
| 397 | + Currently does not support cycles or empty e-classes. |
| 398 | + """ |
| 399 | + # First fill up the e_class_grounded_term for all e_classes |
| 400 | + # by iteratively adding grounded terms for e-classes which have a grounded term until no more progress can be made. |
| 401 | + |
| 402 | + # mapping from e-class to a grounded term in that e-class |
| 403 | + e_class_grounded_term: dict[Value, CallDecl] = {} |
| 404 | + |
| 405 | + def is_grounded(expr: ExprDecl) -> bool: |
| 406 | + """ |
| 407 | + Checks if the given expression is grounded, meaning any values recursively in it have grounded terms in their e-classes. |
| 408 | + """ |
| 409 | + match expr: |
| 410 | + case LetRefDecl(name): |
| 411 | + raise ValueError(f"Cannot have unexpanded let bindings in egraph decl: {name}") |
| 412 | + case UnboundVarDecl(_): |
| 413 | + msg = "Cannot have unbound variables in egraph decl" |
| 414 | + raise ValueError(msg) |
| 415 | + case CallDecl(_, args, _): |
| 416 | + return all(is_grounded(a.expr) for a in args) |
| 417 | + case LitDecl(_) | PyObjectDecl(_): |
| 418 | + return True |
| 419 | + case PartialCallDecl(call): |
| 420 | + return is_grounded(call) |
| 421 | + case DummyDecl(): |
| 422 | + msg = "Cannot have dummy decls in egraph decl" |
| 423 | + raise ValueError(msg) |
| 424 | + case ValueDecl(value): |
| 425 | + return value in e_class_grounded_term |
| 426 | + case GetCostDecl(): |
| 427 | + msg = "Cannot have GetCostDecl in egraph decl" |
| 428 | + raise ValueError(msg) |
| 429 | + case _: |
| 430 | + assert_never(expr) |
| 431 | + |
| 432 | + made_progress = True |
| 433 | + while made_progress: |
| 434 | + made_progress = False |
| 435 | + for e_class, (_, exprs) in self.e_classes.items(): |
| 436 | + if e_class in e_class_grounded_term: |
| 437 | + continue |
| 438 | + for expr in exprs: |
| 439 | + if is_grounded(expr): |
| 440 | + e_class_grounded_term[e_class] = expr |
| 441 | + made_progress = True |
| 442 | + break |
| 443 | + |
| 444 | + # call declarations already emitted as part of other actions. |
| 445 | + emitted_call_decls = set[CallDecl]() |
| 446 | + |
| 447 | + @cache |
| 448 | + def to_grounded(expr: ExprDecl) -> ExprDecl: |
| 449 | + """ |
| 450 | + Converts the given expression to a grounded term, by replacing any values in it with their grounded terms. |
| 451 | + """ |
| 452 | + match expr: |
| 453 | + case LetRefDecl(name): |
| 454 | + raise ValueError(f"Cannot have unexpanded let bindings in egraph decl: {name}") |
| 455 | + case UnboundVarDecl(_): |
| 456 | + msg = "Cannot have unbound variables in egraph decl" |
| 457 | + raise ValueError(msg) |
| 458 | + case CallDecl(callable, args, bound_tp_params): |
| 459 | + emitted_call_decls.add(expr) |
| 460 | + new_args = tuple(TypedExprDecl(a.tp, to_grounded(a.expr)) for a in args) |
| 461 | + return CallDecl(callable, new_args, bound_tp_params) |
| 462 | + case LitDecl(_) | PyObjectDecl(_): |
| 463 | + return expr |
| 464 | + case PartialCallDecl(call): |
| 465 | + return PartialCallDecl(cast("CallDecl", to_grounded(call))) |
| 466 | + case DummyDecl(): |
| 467 | + msg = "Cannot have dummy decls in egraph decl" |
| 468 | + raise ValueError(msg) |
| 469 | + case ValueDecl(value): |
| 470 | + if value not in e_class_grounded_term: |
| 471 | + raise ValueError(f"Value {value} does not have a grounded term in egraph decl") |
| 472 | + return to_grounded(e_class_grounded_term[value]) |
| 473 | + case GetCostDecl(): |
| 474 | + msg = "Cannot have GetCostDecl in egraph decl" |
| 475 | + raise ValueError(msg) |
| 476 | + case _: |
| 477 | + assert_never(expr) |
| 478 | + |
| 479 | + # calls that are in e-classes with only one value, so wouldn't be added as a union and might need |
| 480 | + # to be added as a single expr action if they don't show up anywhere else |
| 481 | + single_e_class_calls: list[tuple[JustTypeRef, CallDecl]] = [] |
| 482 | + |
| 483 | + # Now add all e-classes as actions. |
| 484 | + actions: list[ActionDecl] = [] |
| 485 | + for e_class, (tp, exprs) in self.e_classes.items(): |
| 486 | + chosen_term = e_class_grounded_term[e_class] |
| 487 | + if len(exprs) == 1: |
| 488 | + single_e_class_calls.append((tp, chosen_term)) |
| 489 | + continue |
| 490 | + |
| 491 | + grounded_chosen_term = to_grounded(chosen_term) |
| 492 | + for expr in exprs: |
| 493 | + if expr == chosen_term: |
| 494 | + continue |
| 495 | + actions.append(UnionDecl(tp, grounded_chosen_term, to_grounded(expr))) |
| 496 | + actions.extend( |
| 497 | + LetDecl(name, TypedExprDecl(typed_expr.tp, to_grounded(typed_expr.expr))) |
| 498 | + for name, typed_expr in self.let_bindings.items() |
| 499 | + ) |
| 500 | + actions.extend( |
| 501 | + SetDecl(set_expr.tp, cast("CallDecl", to_grounded(call)), to_grounded(set_expr.expr)) |
| 502 | + for call, set_expr in self.sets.items() |
| 503 | + ) |
| 504 | + actions.extend( |
| 505 | + ExprActionDecl(TypedExprDecl(typed_expr.tp, to_grounded(typed_expr.expr))) |
| 506 | + for typed_expr in self.expr_actions |
| 507 | + ) |
| 508 | + actions.extend( |
| 509 | + SetCostDecl(tp, cast("CallDecl", to_grounded(call)), LitDecl(cost)) |
| 510 | + for call, (tp, cost) in self.costs.items() |
| 511 | + ) |
| 512 | + actions.extend(ChangeDecl(tp, cast("CallDecl", to_grounded(call)), "subsume") for tp, call in self.subsumed) |
| 513 | + |
| 514 | + # Now add any remaining call s that weren't part of any other actions |
| 515 | + actions.extend( |
| 516 | + ExprActionDecl(TypedExprDecl(tp, to_grounded(expr))) |
| 517 | + for (tp, expr) in single_e_class_calls |
| 518 | + if expr not in emitted_call_decls |
| 519 | + ) |
| 520 | + |
| 521 | + return actions |
| 522 | + |
| 523 | + |
352 | 524 | # Have two different types of type refs, one that can include vars recursively and one that cannot. |
353 | 525 | # We only use the one with vars for classmethods and methods, and the other one for egg references as |
354 | 526 | # well as runtime values. |
|
0 commit comments