-
Notifications
You must be signed in to change notification settings - Fork 0
/
referencing.py
336 lines (215 loc) · 8.65 KB
/
referencing.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
#!/usr/bin/env python
"""
Reference abstractions.
Copyright (C) 2016, 2017 Paul Boddie <paul@boddie.org.uk>
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 3 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <http://www.gnu.org/licenses/>.
"""
class Reference:
"A reference abstraction."
def __init__(self, kind, origin=None, name=None):
"""
Initialise a reference using 'kind' to indicate the kind of object,
'origin' to indicate the actual origin of a referenced object, and a
'name' indicating an alias for the object in the program structure.
"""
if isinstance(kind, Reference):
raise ValueError, (kind, origin)
self.kind = kind
self.origin = origin
self.name = name
def __repr__(self):
return "Reference(%r, %r, %r)" % (self.kind, self.origin, self.name)
def __str__(self):
"""
Serialise the reference as '<var>' or a description incorporating the
kind and origin.
"""
if self.kind == "<var>":
alias = self.name and ";%s" % self.name or ""
return "%s%s" % (self.kind, alias)
else:
alias = self.name and self.name != self.origin and ";%s" % self.name or ""
return "%s:%s%s" % (self.kind, self.origin, alias)
def __hash__(self):
"Hash instances using the kind and origin only."
return hash((self.kind, self.get_origin()))
def __cmp__(self, other):
"Compare with 'other' using the kind and origin only."
if isinstance(other, Reference):
return cmp((self.kind, self.get_origin()), (other.kind, other.get_origin()))
else:
return cmp(str(self), other)
def get_name(self):
"Return the name used for this reference."
return self.name
def get_origin(self):
"Return the origin of the reference."
return self.kind != "<var>" and self.origin or None
def get_kind(self):
"Return the kind of object referenced."
return self.kind
def has_kind(self, kinds):
"""
Return whether the reference describes an object from the given 'kinds',
where such kinds may be "<class>", "<function>", "<instance>",
"<module>" or "<var>". Unresolved references may also have kinds of
"<depends>" and "<invoke>".
"""
if not isinstance(kinds, (list, tuple)):
kinds = [kinds]
return self.get_kind() in kinds
def get_path(self):
"Return the attribute names comprising the path to the origin."
return self.get_origin().split(".")
def unresolved(self):
"Return whether this reference is unresolved."
return self.has_kind(["<depends>", "<invoke>", "<var>"])
def static(self):
"Return this reference if it refers to a static object, None otherwise."
return self.has_kind(["<class>", "<function>", "<module>"]) and self or None
def final(self):
"Return a reference to either a static object or None."
static = self.static()
return static and static.origin or None
def instance_of(self, alias=None):
"""
Return a reference to an instance of the referenced class, indicating an
'alias' for the instance if specified.
"""
return self.has_kind("<class>") and Reference("<instance>", self.origin, alias) or None
def as_var(self):
"""
Return a variable version of this reference. Any origin information is
discarded since variable references are deliberately ambiguous.
"""
return Reference("<var>", None, self.name)
def copy(self):
"Copy this reference."
return Reference(self.get_kind(), self.get_origin(), self.get_name())
def alias(self, name):
"Alias this reference employing 'name'."
return Reference(self.get_kind(), self.get_origin(), name)
def unaliased(self):
"Return this reference without any alias."
return Reference(self.get_kind(), self.get_origin())
def mutate(self, ref):
"Mutate this reference to have the same details as 'ref'."
self.kind = ref.kind
self.origin = ref.origin
self.name = ref.name
def parent(self):
"Return the parent of this reference's origin."
if not self.get_origin():
return None
return self.get_origin().rsplit(".", 1)[0]
def name_parent(self):
"Return the parent of this reference's aliased name."
if not self.get_name():
return None
return self.get_name().rsplit(".", 1)[0]
def leaf(self):
"Return the leafname of the reference's origin."
if not self.get_origin():
return None
return self.get_origin().rsplit(".", 1)[-1]
def ancestors(self):
"""
Return ancestors of this reference's origin in order of decreasing
depth.
"""
origin = self.get_origin()
if not origin:
return None
parts = origin.split(".")
ancestors = []
for i in range(len(parts) - 1, 0, -1):
ancestors.append(".".join(parts[:i]))
return ancestors
def is_constant_alias(self):
"Return whether this reference is an alias for a constant."
name = self.get_name()
return name and name.rsplit(".")[-1].startswith("$c")
def is_predefined_value(self):
"Return whether this reference identifies a predefined value."
# NOTE: Details of built-in types employed.
return self.get_origin() in ("__builtins__.none.NoneType", "__builtins__.boolean.boolean")
def get_types(self):
"Return class, instance-only and module types for this reference."
class_types = self.has_kind("<class>") and [self.get_origin()] or []
instance_types = []
module_types = self.has_kind("<module>") and [self.get_origin()] or []
return class_types, instance_types, module_types
def decode_reference(s, name=None):
"Decode 's', making a reference."
if isinstance(s, Reference):
return s.alias(name)
# Null value.
elif not s:
return Reference("<var>", None, name)
# Kind and origin.
elif ":" in s:
kind, origin = s.split(":")
if ";" in origin:
origin, name = origin.split(";")
return Reference(kind, origin, name)
# Kind and name.
elif ";" in s:
kind, name = s.split(";")
return Reference(kind, None, name)
# Kind-only, origin is indicated name.
elif s[0] == "<":
return Reference(s, name, name)
# Module-only.
else:
return Reference("<module>", s, name)
# Type/reference collection functions.
def is_single_class_type(all_types):
"""
Return whether 'all_types' is a mixture of class and instance kinds for
a single class type.
"""
kinds = set()
types = set()
for type in all_types:
kinds.add(type.get_kind())
types.add(type.get_origin())
return len(types) == 1 and kinds == set(["<class>", "<instance>"])
def combine_types(class_types, instance_types, module_types):
"""
Combine 'class_types', 'instance_types', 'module_types' into a single
list of references.
"""
all_types = []
for kind, l in [("<class>", class_types), ("<instance>", instance_types), ("<module>", module_types)]:
for t in l:
all_types.append(Reference(kind, t))
return all_types
def separate_types(refs):
"""
Separate 'refs' into type-specific lists, returning a tuple containing
lists of class types, instance types, module types, function types and
unknown "var" types.
"""
class_types = []
instance_types = []
module_types = []
function_types = []
var_types = []
for kind, l in [
("<class>", class_types), ("<instance>", instance_types), ("<module>", module_types),
("<function>", function_types), ("<var>", var_types)
]:
for ref in refs:
if ref.get_kind() == kind:
l.append(ref.get_origin())
return class_types, instance_types, module_types, function_types, var_types
# vim: tabstop=4 expandtab shiftwidth=4