data: Replace usymbol/string equivalence with obj __getattr__ implementation.
[coe.git] / coe / data.py
CommitLineData
e8a122ff 1class symbol(object):
6d98d3d8 2 __slots__ = []
e8a122ff
FT
3 isafe = set("abcdefghijklmnopqrstuvwxyz" +
4 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
5 "$%^&*_=/.")
6 qsafe = isafe | set("0123456789-+")
7
8 def __eq__(s, o):
9 if not isinstance(o, symbol):
10 return False
11 return (s.name == o.name) and (s.ns == o.ns)
12
13 def __hash__(self):
14 return (hash(self.ns) * 31) + hash(self.name)
15
16 def __lt__(s, o):
17 ns, nm = ("", o) if isinstance(o, str) else (s.ns, s.name)
18 return s.ns < ns or s.name < nm
19 def __gt__(s, o):
20 ns, nm = ("", o) if isinstance(o, str) else (s.ns, s.name)
21 return s.ns > ns or s.name > nm
22
23 @staticmethod
24 def quote(st):
25 ret = ""
26 q = False
27 cset = symbol.isafe
28 for c in st:
29 if c not in cset:
30 q = True
31 ret += "\\" + c
32 else:
33 ret += c
34 cset = symbol.qsafe
35 if q:
36 ret = "|" + ret + "|"
37 return ret
38
39 @staticmethod
40 def get(ns, name):
41 if ns == "":
42 return usymbol(name)
43 return nssymbol(ns, name)
44
45 def __repr__(self):
46 if self.ns == "":
47 return self.quote(self.name)
48 return "%s:%s" % (self.quote(self.ns), self.quote(self.name))
49
50class usymbol(symbol):
6d98d3d8 51 __slots__ = ["name"]
e8a122ff 52 ns = ""
6d98d3d8 53
e8a122ff
FT
54 def __init__(self, name):
55 self.name = name
56
e8a122ff 57class nssymbol(symbol):
6d98d3d8
FT
58 __slots__ = ["ns", "name"]
59
e8a122ff
FT
60 def __init__(self, ns, name, *args, **kw):
61 super().__init__(*args, **kw)
62 self.name = name
63 self.ns = ns
64
8dc0c47a
FT
65class namedtype(type):
66 def __new__(cls, *args, typename=None, **kwargs):
67 self = super().__new__(cls, *args, **kwargs)
68 self.typename = typename
69 return self
70
e8a122ff
FT
71class obj(object):
72 def __getitem__(self, key):
73 return self.__dict__[key]
74 def __setitem__(self, key, val):
75 self.__dict__[key] = val
76 def __delitem__(self, key):
77 del self.__dict__[key]
6d98d3d8
FT
78 def __getattr__(self, name):
79 try:
80 return self.__dict__[symbol.get("", name)]
81 except KeyError:
82 raise AttributeError(name) from None