Skip to content

Commit

Permalink
refactor(analysis): rewrite substitute_unbound to use the new pattern…
Browse files Browse the repository at this point in the history
… system
  • Loading branch information
kszucs authored and cpcloud committed Aug 7, 2023
1 parent 4daf2df commit 885d2ff
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 10 deletions.
2 changes: 2 additions & 0 deletions ibis/common/graph.py
Expand Up @@ -209,6 +209,8 @@ def fn(node, _, **kwargs):
# kwargs to the pattern rather than the original one node object, this way
# we can match on already replaced nodes
if (result := pat.match(node, ctx)) is NoMatch:
# TODO(kszucs): annotable instances should use node.__recreate__()
# for quick reconstruction
return node.__class__(**kwargs)
else:
return result
Expand Down
2 changes: 2 additions & 0 deletions ibis/common/patterns.py
Expand Up @@ -1591,6 +1591,8 @@ def pattern(obj: AnyType) -> Pattern:
return _any
elif isinstance(obj, Pattern):
return obj
elif isinstance(obj, Variable):
return Capture(obj)
elif isinstance(obj, Mapping):
return PatternMapping(obj)
elif isinstance(obj, type):
Expand Down
10 changes: 10 additions & 0 deletions ibis/common/tests/test_patterns.py
Expand Up @@ -156,6 +156,16 @@ def test_variable():
assert p.make(context) == 10


def test_pattern_factory_wraps_variable_with_capture():
v = Variable("other")
p = pattern(v)
assert p == Capture(v, Any())

ctx = {}
assert p.match(10, ctx) == 10
assert ctx == {v: 10}


def test_capture():
ctx = {}

Expand Down
17 changes: 7 additions & 10 deletions ibis/expr/analysis.py
Expand Up @@ -14,11 +14,14 @@
from ibis import util
from ibis.common.annotations import ValidationError
from ibis.common.exceptions import IbisTypeError, IntegrityError
from ibis.common.patterns import Call, Object
from ibis.common.patterns import Call, Object, Variable

p = Object.namespace(ops)
c = Call.namespace(ops)

x = Variable("x")
y = Variable("y")

# ---------------------------------------------------------------------
# Some expression metaprogramming / graph transformations to support
# compilation later
Expand Down Expand Up @@ -167,15 +170,9 @@ def fn(node):

def substitute_unbound(node):
"""Rewrite `node` by replacing table expressions with an equivalent unbound table."""
assert isinstance(node, ops.Node), type(node)

def fn(node, _, **kwargs):
if isinstance(node, ops.DatabaseTable):
return ops.UnboundTable(name=node.name, schema=node.schema)
else:
return node.__class__(**kwargs)

return node.map(fn)[node]
return node.replace(
p.DatabaseTable(name=x, schema=y) >> c.UnboundTable(name=x, schema=y)
)


def get_mutation_exprs(exprs: list[ir.Expr], table: ir.Table) -> list[ir.Expr | None]:
Expand Down

0 comments on commit 885d2ff

Please sign in to comment.