Skip to content

Commit 34eb0fa

Browse files
committed
pattern composition
1 parent 1c4ff4e commit 34eb0fa

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

mellea/stdlib/pattern.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,22 @@
44
from string import Template
55
from pydantic import BaseModel, create_model
66

7+
8+
def supercede(cls1: type, cls2: type) -> type:
9+
"""
10+
Return the more specific class if one is a subclass of the other.
11+
Raise ValueError if neither is a subclass of the other.
12+
"""
13+
if issubclass(cls1, cls2) and cls1 is not cls2:
14+
return cls1
15+
elif issubclass(cls2, cls1) and cls1 is not cls2:
16+
return cls2
17+
elif cls1 is cls2:
18+
return cls1
19+
else:
20+
raise ValueError(f"{cls1.__name__} and {cls2.__name__} are unrelated.")
21+
22+
723
class Pattern:
824

925
def __init__(self, pattern:str, **types:type[Any]):
@@ -48,6 +64,21 @@ def format(self) -> str:
4864
)
4965

5066

67+
def __and__(self, other) -> 'Pattern':
68+
# WIP. not a final state.
69+
# We should actually keep the original Pattern instance, rather than immediately merging them,
70+
# because we must perform query optimization later.
71+
72+
types = self.types.copy()
73+
for v in other.types.keys():
74+
if v in types:
75+
types[v] = supersede(other.types[v], types[v])
76+
77+
return Pattern(
78+
self.pattern.template + " " + other.pattern.template,
79+
**types)
80+
81+
5182
if __name__ == "__main__":
5283

5384
from mellea import start_session, SimpleContext

0 commit comments

Comments
 (0)