Commit | Line | Data |
---|---|---|
e8a122ff | 1 | class 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 | ||
50 | class usymbol(symbol): | |
6d98d3d8 | 51 | __slots__ = ["name"] |
e8a122ff | 52 | ns = "" |
6d98d3d8 | 53 | |
e8a122ff FT |
54 | def __init__(self, name): |
55 | self.name = name | |
56 | ||
e8a122ff | 57 | class 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 |
65 | class 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 | ||
ef6415d5 FT |
71 | @classmethod |
72 | def make(cls, *args, typename=None, **kwargs): | |
73 | self = cls(*args, **kwargs) | |
74 | self.typename = typename | |
75 | return self | |
76 | ||
e8a122ff FT |
77 | class obj(object): |
78 | def __getitem__(self, key): | |
79 | return self.__dict__[key] | |
80 | def __setitem__(self, key, val): | |
81 | self.__dict__[key] = val | |
82 | def __delitem__(self, key): | |
83 | del self.__dict__[key] | |
6d98d3d8 FT |
84 | def __getattr__(self, name): |
85 | try: | |
86 | return self.__dict__[symbol.get("", name)] | |
87 | except KeyError: | |
88 | raise AttributeError(name) from None |