|
1
|
|
|
import keyword |
|
2
|
|
|
|
|
3
|
|
|
DISCARD = object() |
|
4
|
|
|
|
|
5
|
|
|
|
|
6
|
|
|
class Pattern(tuple): |
|
7
|
|
|
"""A matcher that binds a value to a name.""" |
|
8
|
|
|
|
|
9
|
|
|
__slots__ = () |
|
10
|
|
|
|
|
11
|
|
|
def __new__(cls, name: str): |
|
12
|
|
|
if name == "_": |
|
13
|
|
|
return DISCARD |
|
14
|
|
|
if not name.isidentifier(): |
|
15
|
|
|
raise ValueError |
|
16
|
|
|
if keyword.iskeyword(name): |
|
17
|
|
|
raise ValueError |
|
18
|
|
|
return super().__new__(cls, (name,)) |
|
19
|
|
|
|
|
20
|
|
|
@property |
|
21
|
|
|
def name(self): |
|
22
|
|
|
"""Return the name of the matcher.""" |
|
23
|
|
|
return tuple.__getitem__(self, 0) |
|
24
|
|
|
|
|
25
|
|
|
def __getitem__(self, other): |
|
26
|
|
|
return AsPattern(self, other) |
|
27
|
|
|
|
|
28
|
|
|
|
|
29
|
|
|
class AsPattern(tuple): |
|
30
|
|
|
"""A matcher that contains further bindings.""" |
|
31
|
|
|
|
|
32
|
|
|
__slots__ = () |
|
33
|
|
|
|
|
34
|
|
|
def __new__(cls, matcher: Pattern, match): |
|
35
|
|
|
if match is DISCARD: |
|
36
|
|
|
return matcher |
|
37
|
|
|
return super().__new__(cls, (matcher, match)) |
|
38
|
|
|
|
|
39
|
|
|
@property |
|
40
|
|
|
def matcher(self): |
|
41
|
|
|
"""Return the left-hand-side of the as-match.""" |
|
42
|
|
|
return self[0] |
|
43
|
|
|
|
|
44
|
|
|
@property |
|
45
|
|
|
def match(self): |
|
46
|
|
|
"""Return the right-hand-side of the as-match.""" |
|
47
|
|
|
return self[1] |
|
48
|
|
|
|
|
49
|
|
|
|
|
50
|
|
|
class AttrPattern(tuple): |
|
51
|
|
|
|
|
52
|
|
|
__slots__ = () |
|
53
|
|
|
|
|
54
|
|
|
def __new__(*args, **kwargs): |
|
55
|
|
|
cls, *args = args |
|
56
|
|
|
if args: |
|
57
|
|
|
raise ValueError(args) |
|
58
|
|
|
return super(AttrPattern, cls).__new__(cls, (tuple(kwargs.items()),)) |
|
59
|
|
|
|
|
60
|
|
|
@property |
|
61
|
|
|
def match_dict(self): |
|
62
|
|
|
return self[0] |
|
63
|
|
|
|
|
64
|
|
|
|
|
65
|
|
|
class DictPattern(tuple): |
|
66
|
|
|
|
|
67
|
|
|
__slots__ = () |
|
68
|
|
|
|
|
69
|
|
|
def __new__(cls, match_dict, *, exhaustive=False): |
|
70
|
|
|
return super(DictPattern, cls).__new__(cls, (tuple(match_dict.items()), exhaustive)) |
|
71
|
|
|
|
|
72
|
|
|
@property |
|
73
|
|
|
def match_dict(self): |
|
74
|
|
|
return self[0] |
|
75
|
|
|
|
|
76
|
|
|
@property |
|
77
|
|
|
def exhaustive(self): |
|
78
|
|
|
return self[1] |
|
79
|
|
|
|