| 1 |
from __future__ import print_function |
| 2 |
|
| 3 |
from rpython.annotator import model as annmodel, description |
| 4 |
from rpython.flowspace.argument import Signature |
| 5 |
from rpython.flowspace.model import (Variable, Constant, Block, Link, |
| 6 |
checkgraph, FunctionGraph, SpaceOperation) |
| 7 |
from rpython.rlib.objectmodel import ComputedIntSymbolic |
| 8 |
from rpython.rtyper.error import TyperError |
| 9 |
from rpython.rtyper.rmodel import getgcflavor |
| 10 |
from rpython.tool.sourcetools import valid_identifier |
| 11 |
from rpython.annotator.classdesc import ClassDesc |
| 12 |
|
| 13 |
|
| 14 |
def normalize_call_familes(annotator): |
| 15 |
for callfamily in annotator.bookkeeper.pbc_maximal_call_families.infos(): |
| 16 |
if not callfamily.modified: |
| 17 |
assert callfamily.normalized |
| 18 |
continue |
| 19 |
normalize_calltable(annotator, callfamily) |
| 20 |
callfamily.normalized = True |
| 21 |
callfamily.modified = False |
| 22 |
|
| 23 |
def normalize_calltable(annotator, callfamily): |
| 24 |
"""Try to normalize all rows of a table.""" |
| 25 |
nshapes = len(callfamily.calltables) |
| 26 |
for shape, table in callfamily.calltables.items(): |
| 27 |
for row in table: |
| 28 |
did_something = normalize_calltable_row_signature(annotator, shape, |
| 29 |
row) |
| 30 |
if did_something: |
| 31 |
assert not callfamily.normalized, "change in call family normalisation" |
| 32 |
if nshapes != 1: |
| 33 |
raise_call_table_too_complex_error(callfamily, annotator) |
| 34 |
while True: |
| 35 |
progress = False |
| 36 |
for shape, table in callfamily.calltables.items(): |
| 37 |
for row in table: |
| 38 |
progress |= normalize_calltable_row_annotation(annotator, |
| 39 |
row.values()) |
| 40 |
if not progress: |
| 41 |
return |
| 42 |
assert not callfamily.normalized, "change in call family normalisation" |
| 43 |
|
| 44 |
def raise_call_table_too_complex_error(callfamily, annotator): |
| 45 |
msg = [] |
| 46 |
items = callfamily.calltables.items() |
| 47 |
for i, (shape1, table1) in enumerate(items): |
| 48 |
for shape2, table2 in items[i + 1:]: |
| 49 |
if shape1 == shape2: |
| 50 |
continue |
| 51 |
row1 = table1[0] |
| 52 |
row2 = table2[0] |
| 53 |
problematic_function_graphs = set(row1.values()).union(set(row2.values())) |
| 54 |
pfg = [str(graph) for graph in problematic_function_graphs] |
| 55 |
pfg.sort() |
| 56 |
msg.append("the following functions:") |
| 57 |
msg.append(" %s" % ("\n ".join(pfg), )) |
| 58 |
msg.append("are called with inconsistent numbers of arguments") |
| 59 |
msg.append("(and/or the argument names are different, which is" |
| 60 |
" not supported in this case)") |
| 61 |
if shape1[0] != shape2[0]: |
| 62 |
msg.append("sometimes with %s arguments, sometimes with %s" % (shape1[0], shape2[0])) |
| 63 |
else: |
| 64 |
pass |
| 65 |
callers = [] |
| 66 |
msg.append("the callers of these functions are:") |
| 67 |
for tag, (caller, callee) in annotator.translator.callgraph.iteritems(): |
| 68 |
if callee not in problematic_function_graphs: |
| 69 |
continue |
| 70 |
if str(caller) in callers: |
| 71 |
continue |
| 72 |
callers.append(str(caller)) |
| 73 |
callers.sort() |
| 74 |
for caller in callers: |
| 75 |
msg.append(" %s" % (caller, )) |
| 76 |
raise TyperError("\n".join(msg)) |
| 77 |
|
| 78 |
def normalize_calltable_row_signature(annotator, shape, row): |
| 79 |
graphs = row.values() |
| 80 |
assert graphs, "no graph??" |
| 81 |
sig0 = graphs[0].signature |
| 82 |
defaults0 = graphs[0].defaults |
| 83 |
for graph in graphs[1:]: |
| 84 |
if graph.signature != sig0: |
| 85 |
break |
| 86 |
if graph.defaults != defaults0: |
| 87 |
break |
| 88 |
else: |
| 89 |
return False |
| 90 |
|
| 91 |
shape_cnt, shape_keys, shape_star = shape |
| 92 |
assert not shape_star, "should have been removed at this stage" |
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
call_nbargs = shape_cnt + len(shape_keys) |
| 97 |
|
| 98 |
did_something = False |
| 99 |
|
| 100 |
for graph in graphs: |
| 101 |
argnames, varargname, kwargname = graph.signature |
| 102 |
assert not varargname, "XXX not implemented" |
| 103 |
assert not kwargname, "XXX not implemented" |
| 104 |
inputargs_s = [annotator.binding(v) for v in graph.getargs()] |
| 105 |
argorder = range(shape_cnt) |
| 106 |
for key in shape_keys: |
| 107 |
i = list(argnames).index(key) |
| 108 |
assert i not in argorder |
| 109 |
argorder.append(i) |
| 110 |
need_reordering = (argorder != range(call_nbargs)) |
| 111 |
if need_reordering or len(graph.getargs()) != call_nbargs: |
| 112 |
oldblock = graph.startblock |
| 113 |
inlist = [] |
| 114 |
defaults = graph.defaults or () |
| 115 |
num_nondefaults = len(inputargs_s) - len(defaults) |
| 116 |
defaults = [description.NODEFAULT] * num_nondefaults + list(defaults) |
| 117 |
newdefaults = [] |
| 118 |
for j in argorder: |
| 119 |
v = Variable(graph.getargs()[j]) |
| 120 |
annotator.setbinding(v, inputargs_s[j]) |
| 121 |
inlist.append(v) |
| 122 |
newdefaults.append(defaults[j]) |
| 123 |
newblock = Block(inlist) |
| 124 |
|
| 125 |
|
| 126 |
outlist = inlist[:shape_cnt] |
| 127 |
|
| 128 |
for j in range(shape_cnt, len(inputargs_s)): |
| 129 |
try: |
| 130 |
i = argorder.index(j) |
| 131 |
v = inlist[i] |
| 132 |
except ValueError: |
| 133 |
default = defaults[j] |
| 134 |
if default is description.NODEFAULT: |
| 135 |
raise TyperError( |
| 136 |
"call pattern has %d positional arguments, " |
| 137 |
"but %r takes at least %d arguments" % ( |
| 138 |
shape_cnt, graph.name, num_nondefaults)) |
| 139 |
v = Constant(default) |
| 140 |
outlist.append(v) |
| 141 |
newblock.closeblock(Link(outlist, oldblock)) |
| 142 |
graph.startblock = newblock |
| 143 |
for i in range(len(newdefaults)-1,-1,-1): |
| 144 |
if newdefaults[i] is description.NODEFAULT: |
| 145 |
newdefaults = newdefaults[i:] |
| 146 |
break |
| 147 |
graph.defaults = tuple(newdefaults) |
| 148 |
graph.signature = Signature([argnames[j] for j in argorder], |
| 149 |
None, None) |
| 150 |
|
| 151 |
checkgraph(graph) |
| 152 |
annotator.annotated[newblock] = annotator.annotated[oldblock] |
| 153 |
did_something = True |
| 154 |
return did_something |
| 155 |
|
| 156 |
def normalize_calltable_row_annotation(annotator, graphs): |
| 157 |
if len(graphs) <= 1: |
| 158 |
return False |
| 159 |
graph_bindings = {} |
| 160 |
for graph in graphs: |
| 161 |
graph_bindings[graph] = [annotator.binding(v) |
| 162 |
for v in graph.getargs()] |
| 163 |
iterbindings = graph_bindings.itervalues() |
| 164 |
nbargs = len(iterbindings.next()) |
| 165 |
for binding in iterbindings: |
| 166 |
assert len(binding) == nbargs |
| 167 |
|
| 168 |
generalizedargs = [] |
| 169 |
for i in range(nbargs): |
| 170 |
args_s = [] |
| 171 |
for graph, bindings in graph_bindings.items(): |
| 172 |
args_s.append(bindings[i]) |
| 173 |
s_value = annmodel.unionof(*args_s) |
| 174 |
generalizedargs.append(s_value) |
| 175 |
result_s = [annotator.binding(graph.getreturnvar()) |
| 176 |
for graph in graph_bindings] |
| 177 |
generalizedresult = annmodel.unionof(*result_s) |
| 178 |
|
| 179 |
conversion = False |
| 180 |
for graph in graphs: |
| 181 |
bindings = graph_bindings[graph] |
| 182 |
need_conversion = (generalizedargs != bindings) |
| 183 |
if need_conversion: |
| 184 |
conversion = True |
| 185 |
oldblock = graph.startblock |
| 186 |
inlist = [] |
| 187 |
for j, s_value in enumerate(generalizedargs): |
| 188 |
v = Variable(graph.getargs()[j]) |
| 189 |
annotator.setbinding(v, s_value) |
| 190 |
inlist.append(v) |
| 191 |
newblock = Block(inlist) |
| 192 |
|
| 193 |
outlist = inlist[:] |
| 194 |
newblock.closeblock(Link(outlist, oldblock)) |
| 195 |
graph.startblock = newblock |
| 196 |
|
| 197 |
checkgraph(graph) |
| 198 |
annotator.annotated[newblock] = annotator.annotated[oldblock] |
| 199 |
|
| 200 |
if annotator.binding(graph.getreturnvar()) != generalizedresult: |
| 201 |
conversion = True |
| 202 |
annotator.setbinding(graph.getreturnvar(), generalizedresult) |
| 203 |
|
| 204 |
return conversion |
| 205 |
|
| 206 |
|
| 207 |
|
| 208 |
def merge_classpbc_getattr_into_classdef(annotator): |
| 209 |
|
| 210 |
|
| 211 |
|
| 212 |
|
| 213 |
all_families = annotator.bookkeeper.classpbc_attr_families |
| 214 |
for attrname, access_sets in all_families.items(): |
| 215 |
for access_set in access_sets.infos(): |
| 216 |
descs = access_set.descs |
| 217 |
if len(descs) <= 1: |
| 218 |
continue |
| 219 |
if not isinstance(descs.iterkeys().next(), ClassDesc): |
| 220 |
continue |
| 221 |
classdefs = [desc.getuniqueclassdef() for desc in descs] |
| 222 |
commonbase = classdefs[0] |
| 223 |
for cdef in classdefs[1:]: |
| 224 |
commonbase = commonbase.commonbase(cdef) |
| 225 |
if commonbase is None: |
| 226 |
raise TyperError("reading attribute %r: no common base " |
| 227 |
"class for %r" % (attrname, descs.keys())) |
| 228 |
extra_access_sets = commonbase.extra_access_sets |
| 229 |
if commonbase.repr is not None: |
| 230 |
assert access_set in extra_access_sets |
| 231 |
continue |
| 232 |
access_set.commonbase = commonbase |
| 233 |
if access_set not in extra_access_sets: |
| 234 |
counter = len(extra_access_sets) |
| 235 |
extra_access_sets[access_set] = attrname, counter |
| 236 |
|
| 237 |
|
| 238 |
|
| 239 |
def create_class_constructors(annotator): |
| 240 |
bk = annotator.bookkeeper |
| 241 |
call_families = bk.pbc_maximal_call_families |
| 242 |
|
| 243 |
for family in call_families.infos(): |
| 244 |
if len(family.descs) <= 1: |
| 245 |
continue |
| 246 |
descs = family.descs.keys() |
| 247 |
if not isinstance(descs[0], ClassDesc): |
| 248 |
continue |
| 249 |
|
| 250 |
|
| 251 |
change = descs[0].mergeattrfamilies(descs[1:], '__init__') |
| 252 |
if hasattr(descs[0].getuniqueclassdef(), 'my_instantiate_graph'): |
| 253 |
assert not change, "after the fact change to a family of classes" |
| 254 |
continue |
| 255 |
|
| 256 |
attrfamily = descs[0].getattrfamily('__init__') |
| 257 |
inits_s = [desc.s_read_attribute('__init__') for desc in descs] |
| 258 |
s_value = annmodel.unionof(attrfamily.s_value, *inits_s) |
| 259 |
attrfamily.s_value = s_value |
| 260 |
|
| 261 |
for desc in descs: |
| 262 |
bk.needs_generic_instantiate[desc.getuniqueclassdef()] = True |
| 263 |
|
| 264 |
|
| 265 |
|
| 266 |
def create_instantiate_functions(annotator): |
| 267 |
|
| 268 |
|
| 269 |
needs_generic_instantiate = annotator.bookkeeper.needs_generic_instantiate |
| 270 |
|
| 271 |
for classdef in needs_generic_instantiate: |
| 272 |
assert getgcflavor(classdef) == 'gc' |
| 273 |
create_instantiate_function(annotator, classdef) |
| 274 |
|
| 275 |
def create_instantiate_function(annotator, classdef): |
| 276 |
|
| 277 |
|
| 278 |
|
| 279 |
|
| 280 |
|
| 281 |
if hasattr(classdef, 'my_instantiate_graph'): |
| 282 |
return |
| 283 |
v = Variable() |
| 284 |
block = Block([]) |
| 285 |
block.operations.append(SpaceOperation('instantiate1', [], v)) |
| 286 |
name = valid_identifier('instantiate_' + classdef.name) |
| 287 |
graph = FunctionGraph(name, block) |
| 288 |
block.closeblock(Link([v], graph.returnblock)) |
| 289 |
annotator.setbinding(v, annmodel.SomeInstance(classdef)) |
| 290 |
annotator.annotated[block] = graph |
| 291 |
|
| 292 |
generalizedresult = annmodel.SomeInstance(classdef=None) |
| 293 |
annotator.setbinding(graph.getreturnvar(), generalizedresult) |
| 294 |
classdef.my_instantiate_graph = graph |
| 295 |
annotator.translator.graphs.append(graph) |
| 296 |
|
| 297 |
|
| 298 |
|
| 299 |
class TooLateForNewSubclass(Exception): |
| 300 |
pass |
| 301 |
|
| 302 |
class TotalOrderSymbolic(ComputedIntSymbolic): |
| 303 |
|
| 304 |
def __init__(self, orderwitness, peers): |
| 305 |
self.orderwitness = orderwitness |
| 306 |
self.peers = peers |
| 307 |
self.value = None |
| 308 |
self._with_subclasses = None |
| 309 |
peers.append(self) |
| 310 |
|
| 311 |
def __cmp__(self, other): |
| 312 |
if not isinstance(other, TotalOrderSymbolic): |
| 313 |
return cmp(self.compute_fn(), other) |
| 314 |
else: |
| 315 |
return cmp(self.orderwitness, other.orderwitness) |
| 316 |
|
| 317 |
|
| 318 |
|
| 319 |
def __sub__(self, other): |
| 320 |
return self.compute_fn() - other |
| 321 |
|
| 322 |
def __rsub__(self, other): |
| 323 |
return other - self.compute_fn() |
| 324 |
|
| 325 |
def check_any_subclass_in_peer_list(self, i): |
| 326 |
|
| 327 |
|
| 328 |
assert self.peers[i] is self |
| 329 |
return self.peers[i + 1].orderwitness != self.orderwitness + [MAX] |
| 330 |
|
| 331 |
def number_with_subclasses(self): |
| 332 |
|
| 333 |
|
| 334 |
|
| 335 |
|
| 336 |
if self._with_subclasses is None: |
| 337 |
self.peers.sort() |
| 338 |
i = self.peers.index(self) |
| 339 |
self._with_subclasses = self.check_any_subclass_in_peer_list(i) |
| 340 |
return self._with_subclasses |
| 341 |
|
| 342 |
def compute_fn(self): |
| 343 |
if self.value is None: |
| 344 |
self.peers.sort() |
| 345 |
for i, peer in enumerate(self.peers): |
| 346 |
assert peer.value is None or peer.value == i |
| 347 |
peer.value = i |
| 348 |
|
| 349 |
if peer._with_subclasses is False: |
| 350 |
if peer.check_any_subclass_in_peer_list(i): |
| 351 |
raise TooLateForNewSubclass |
| 352 |
|
| 353 |
assert self.value is not None |
| 354 |
return self.value |
| 355 |
|
| 356 |
def dump(self, annotator): |
| 357 |
self.peers.sort() |
| 358 |
mapping = {} |
| 359 |
for classdef in annotator.bookkeeper.classdefs: |
| 360 |
if hasattr(classdef, '_unique_cdef_id'): |
| 361 |
mapping[classdef._unique_cdef_id] = classdef |
| 362 |
for peer in self.peers: |
| 363 |
if peer is self: |
| 364 |
print('==>', end=" ") |
| 365 |
else: |
| 366 |
print(' ', end=" ") |
| 367 |
print('value %4s --' % (peer.value,), peer.orderwitness, end=" ") |
| 368 |
if peer.orderwitness[-1] in mapping: |
| 369 |
print(mapping[peer.orderwitness[-1]]) |
| 370 |
else: |
| 371 |
print() |
| 372 |
|
| 373 |
def assign_inheritance_ids(annotator): |
| 374 |
|
| 375 |
|
| 376 |
|
| 377 |
|
| 378 |
|
| 379 |
bk = annotator.bookkeeper |
| 380 |
try: |
| 381 |
lst = bk._inheritance_id_symbolics |
| 382 |
except AttributeError: |
| 383 |
lst = bk._inheritance_id_symbolics = [] |
| 384 |
for classdef in annotator.bookkeeper.classdefs: |
| 385 |
if not hasattr(classdef, 'minid'): |
| 386 |
witness = [get_unique_cdef_id(cdef) for cdef in classdef.getmro()] |
| 387 |
witness.reverse() |
| 388 |
classdef.minid = TotalOrderSymbolic(witness, lst) |
| 389 |
classdef.maxid = TotalOrderSymbolic(witness + [MAX], lst) |
| 390 |
|
| 391 |
MAX = 1E100 |
| 392 |
_cdef_id_counter = 0 |
| 393 |
def get_unique_cdef_id(cdef): |
| 394 |
global _cdef_id_counter |
| 395 |
try: |
| 396 |
return cdef._unique_cdef_id |
| 397 |
except AttributeError: |
| 398 |
cdef._unique_cdef_id = _cdef_id_counter |
| 399 |
_cdef_id_counter += 1 |
| 400 |
return cdef._unique_cdef_id |
| 401 |
|
| 402 |
|
| 403 |
|
| 404 |
def perform_normalizations(annotator): |
| 405 |
create_class_constructors(annotator) |
| 406 |
annotator.frozen += 1 |
| 407 |
try: |
| 408 |
normalize_call_familes(annotator) |
| 409 |
merge_classpbc_getattr_into_classdef(annotator) |
| 410 |
assign_inheritance_ids(annotator) |
| 411 |
finally: |
| 412 |
annotator.frozen -= 1 |
| 413 |
create_instantiate_functions(annotator) |