Debian Codegraph @

rpython/rtyper/annlowlevel.py

raw symbols SCIP
1 """
2 The code needed to flow and annotate low-level helpers -- the ll_*() functions
3 """
4
5 from rpython.tool.sourcetools import valid_identifier
6 from rpython.annotator import model as annmodel
7 from rpython.annotator.policy import AnnotatorPolicy
8 from rpython.annotator.signature import Sig
9 from rpython.annotator.specialize import flatten_star_args
10 from rpython.rtyper.llannotation import (
11 SomePtr, annotation_to_lltype, lltype_to_annotation)
12 from rpython.rtyper.normalizecalls import perform_normalizations
13 from rpython.rtyper.lltypesystem import lltype, llmemory
14 from rpython.flowspace.model import Constant
15 from rpython.rlib.objectmodel import specialize
16 from rpython.rtyper import extregistry
17 from rpython.rtyper.rmodel import warning
18
19
20 class KeyComp(object):
21 def __init__(self, val):
22 self.val = val
23 def __eq__(self, other):
24 return self.__class__ is other.__class__ and self.val == other.val
25 def __ne__(self, other):
26 return not (self == other)
27 def __hash__(self):
28 return hash(self.val)
29 def __str__(self):
30 val = self.val
31 if isinstance(val, lltype.LowLevelType):
32 return val._short_name() + 'LlT'
33 s = getattr(val, '__name__', None)
34 if s is None:
35 compact = getattr(val, 'compact_repr', None)
36 if compact is None:
37 s = repr(val)
38 else:
39 s = compact()
40 return s + 'Const'
41 __repr__ = __str__
42
43 class LowLevelAnnotatorPolicy(AnnotatorPolicy):
44 def __init__(self, rtyper=None):
45 self.rtyper = rtyper
46
47 @staticmethod
48 def lowlevelspecialize(funcdesc, args_s, key_for_args):
49 args_s, key1, builder = flatten_star_args(funcdesc, args_s)
50 key = []
51 new_args_s = []
52 for i, s_obj in enumerate(args_s):
53 if i in key_for_args:
54 key.append(key_for_args[i])
55 new_args_s.append(s_obj)
56 elif isinstance(s_obj, annmodel.SomePBC):
57 assert s_obj.is_constant(), "ambiguous low-level helper specialization"
58 key.append(KeyComp(s_obj.const))
59 new_args_s.append(s_obj)
60 elif isinstance(s_obj, annmodel.SomeNone):
61 key.append(KeyComp(None))
62 new_args_s.append(s_obj)
63 else:
64 new_args_s.append(annmodel.not_const(s_obj))
65 try:
66 key.append(annotation_to_lltype(s_obj))
67 except ValueError:
68 # passing non-low-level types to a ll_* function is allowed
69 # for module/ll_*
70 key.append(s_obj.__class__)
71 key = (tuple(key),)
72 if key1 is not None:
73 key += (key1,)
74 flowgraph = funcdesc.cachedgraph(key, builder=builder)
75 args_s[:] = new_args_s
76 return flowgraph
77
78 @staticmethod
79 def default_specialize(funcdesc, args_s):
80 return LowLevelAnnotatorPolicy.lowlevelspecialize(funcdesc, args_s, {})
81
82 specialize__ll = default_specialize
83
84 @staticmethod
85 def specialize__ll_and_arg(funcdesc, args_s, *argindices):
86 keys = {}
87 for i in argindices:
88 keys[i] = args_s[i].const
89 return LowLevelAnnotatorPolicy.lowlevelspecialize(funcdesc, args_s,
90 keys)
91
92 def annotate_lowlevel_helper(annotator, ll_function, args_s, policy=None):
93 if policy is None:
94 policy = LowLevelAnnotatorPolicy()
95 return annotator.annotate_helper(ll_function, args_s, policy)
96
97 # ___________________________________________________________________
98 # Mix-level helpers: combining RPython and ll-level
99
100 class MixLevelAnnotatorPolicy(LowLevelAnnotatorPolicy):
101
102 def __init__(self, annhelper):
103 self.rtyper = annhelper.rtyper
104
105 def default_specialize(self, funcdesc, args_s):
106 name = funcdesc.name
107 if name.startswith('ll_') or name.startswith('_ll_'): # xxx can we do better?
108 return super(MixLevelAnnotatorPolicy, self).default_specialize(
109 funcdesc, args_s)
110 else:
111 return AnnotatorPolicy.default_specialize(funcdesc, args_s)
112
113 def specialize__arglltype(self, funcdesc, args_s, i):
114 key = self.rtyper.getrepr(args_s[i]).lowleveltype
115 alt_name = funcdesc.name+"__for_%sLlT" % key._short_name()
116 return funcdesc.cachedgraph(key, alt_name=valid_identifier(alt_name))
117
118 def specialize__genconst(self, funcdesc, args_s, i):
119 # XXX this is specific to the JIT
120 TYPE = annotation_to_lltype(args_s[i], 'genconst')
121 args_s[i] = lltype_to_annotation(TYPE)
122 alt_name = funcdesc.name + "__%s" % (TYPE._short_name(),)
123 return funcdesc.cachedgraph(TYPE, alt_name=valid_identifier(alt_name))
124
125
126 class MixLevelHelperAnnotator(object):
127
128 def __init__(self, rtyper):
129 self.rtyper = rtyper
130 self.policy = MixLevelAnnotatorPolicy(self)
131 self.pending = [] # list of (ll_function, graph, args_s, s_result)
132 self.delayedreprs = set()
133 self.delayedconsts = []
134 self.delayedfuncs = []
135 self.newgraphs = set()
136
137 def getgraph(self, ll_function, args_s, s_result):
138 # get the graph of the mix-level helper ll_function and prepare it for
139 # being annotated. Annotation and RTyping should be done in a single shot
140 # at the end with finish().
141 ann = self.rtyper.annotator
142 with ann.using_policy(self.policy):
143 graph, args_s = ann.get_call_parameters(ll_function, args_s)
144 for v_arg, s_arg in zip(graph.getargs(), args_s):
145 ann.setbinding(v_arg, s_arg)
146 ann.setbinding(graph.getreturnvar(), s_result)
147 #self.rtyper.annotator.annotated[graph.returnblock] = graph
148 self.pending.append((ll_function, graph, args_s, s_result))
149 return graph
150
151 def delayedfunction(self, ll_function, args_s, s_result, needtype=False):
152 # get a delayed pointer to the low-level function, annotated as
153 # specified. The pointer is only valid after finish() was called.
154 graph = self.getgraph(ll_function, args_s, s_result)
155 if needtype:
156 ARGS = [self.getdelayedrepr(s_arg, False).lowleveltype
157 for s_arg in args_s]
158 RESULT = self.getdelayedrepr(s_result, False).lowleveltype
159 FUNCTYPE = lltype.FuncType(ARGS, RESULT)
160 else:
161 FUNCTYPE = None
162 return self.graph2delayed(graph, FUNCTYPE)
163
164 def constfunc(self, ll_function, args_s, s_result):
165 p = self.delayedfunction(ll_function, args_s, s_result)
166 return Constant(p, lltype.typeOf(p))
167
168 def graph2delayed(self, graph, FUNCTYPE=None):
169 if FUNCTYPE is None:
170 FUNCTYPE = lltype.ForwardReference()
171 # obscure hack: embed the name of the function in the string, so
172 # that the genc database can get it even before the delayedptr
173 # is really computed
174 name = "delayed!%s" % (graph.name,)
175 delayedptr = lltype._ptr(lltype.Ptr(FUNCTYPE), name, solid=True)
176 self.delayedfuncs.append((delayedptr, graph))
177 return delayedptr
178
179 def graph2const(self, graph):
180 p = self.graph2delayed(graph)
181 return Constant(p, lltype.typeOf(p))
182
183 def getdelayedrepr(self, s_value, check_never_seen=True):
184 """Like rtyper.getrepr(), but the resulting repr will not be setup() at
185 all before finish() is called.
186 """
187 r = self.rtyper.getrepr(s_value)
188 if check_never_seen:
189 r.set_setup_delayed(True)
190 delayed = True
191 else:
192 delayed = r.set_setup_maybe_delayed()
193 if delayed:
194 self.delayedreprs.add(r)
195 return r
196
197 def s_r_instanceof(self, cls, can_be_None=True, check_never_seen=True):
198 classdesc = self.rtyper.annotator.bookkeeper.getdesc(cls)
199 classdef = classdesc.getuniqueclassdef()
200 s_instance = annmodel.SomeInstance(classdef, can_be_None)
201 r_instance = self.getdelayedrepr(s_instance, check_never_seen)
202 return s_instance, r_instance
203
204 def delayedconst(self, repr, obj):
205 if repr.is_setup_delayed():
206 # record the existence of this 'obj' for the bookkeeper - e.g.
207 # if 'obj' is an instance, this will populate the classdef with
208 # the prebuilt attribute values of the instance
209 bk = self.rtyper.annotator.bookkeeper
210 bk.immutablevalue(obj)
211 delayedptr = lltype._ptr(repr.lowleveltype, "delayed!")
212 self.delayedconsts.append((delayedptr, repr, obj))
213 return delayedptr
214 else:
215 return repr.convert_const(obj)
216
217 def finish(self):
218 self.finish_annotate()
219 self.finish_rtype()
220
221 def finish_annotate(self):
222 # push all the graphs into the annotator's pending blocks dict at once
223 rtyper = self.rtyper
224 ann = rtyper.annotator
225 bk = ann.bookkeeper
226 translator = ann.translator
227 original_graph_count = len(translator.graphs)
228 with ann.using_policy(self.policy):
229 for ll_function, graph, args_s, s_result in self.pending:
230 # mark the return block as already annotated, because the return var
231 # annotation was forced in getgraph() above. This prevents temporary
232 # less general values reaching the return block from crashing the
233 # annotator (on the assert-that-new-binding-is-not-less-general).
234 ann.annotated[graph.returnblock] = graph
235 s_function = bk.immutablevalue(ll_function)
236 bk.emulate_pbc_call(graph, s_function, args_s)
237 self.newgraphs.add(graph)
238 ann.complete_helpers()
239 for ll_function, graph, args_s, s_result in self.pending:
240 s_real_result = ann.binding(graph.getreturnvar())
241 if s_real_result != s_result:
242 raise Exception("wrong annotation for the result of %r:\n"
243 "originally specified: %r\n"
244 " found by annotating: %r" %
245 (graph, s_result, s_real_result))
246 del self.pending[:]
247 for graph in translator.graphs[original_graph_count:]:
248 self.newgraphs.add(graph)
249
250 def finish_rtype(self):
251 rtyper = self.rtyper
252 translator = rtyper.annotator.translator
253 original_graph_count = len(translator.graphs)
254 perform_normalizations(rtyper.annotator)
255 for r in self.delayedreprs:
256 r.set_setup_delayed(False)
257 rtyper.call_all_setups()
258 for p, repr, obj in self.delayedconsts:
259 p._become(repr.convert_const(obj))
260 rtyper.call_all_setups()
261 for p, graph in self.delayedfuncs:
262 self.newgraphs.add(graph)
263 real_p = rtyper.getcallable(graph)
264 REAL = lltype.typeOf(real_p).TO
265 FUNCTYPE = lltype.typeOf(p).TO
266 if isinstance(FUNCTYPE, lltype.ForwardReference):
267 FUNCTYPE.become(REAL)
268 assert FUNCTYPE == REAL
269 p._become(real_p)
270 rtyper.specialize_more_blocks()
271 self.delayedreprs.clear()
272 del self.delayedconsts[:]
273 del self.delayedfuncs[:]
274 for graph in translator.graphs[original_graph_count:]:
275 self.newgraphs.add(graph)
276
277 def backend_optimize(self, **flags):
278 # only optimize the newly created graphs
279 from rpython.translator.backendopt.all import backend_optimizations
280 translator = self.rtyper.annotator.translator
281 newgraphs = list(self.newgraphs)
282 backend_optimizations(translator, newgraphs, secondary=True,
283 inline_graph_from_anywhere=True, **flags)
284 self.newgraphs.clear()
285
286 # ____________________________________________________________
287
288 class PseudoHighLevelCallable(object):
289 """A gateway to a low-level function pointer. To high-level RPython
290 code it looks like a normal function, taking high-level arguments
291 and returning a high-level result.
292 """
293 def __init__(self, llfnptr, args_s, s_result):
294 self.llfnptr = llfnptr
295 self.args_s = args_s
296 self.s_result = s_result
297
298 def __call__(self, *args):
299 raise Exception("PseudoHighLevelCallable objects are not really "
300 "callable directly")
301
302 class PseudoHighLevelCallableEntry(extregistry.ExtRegistryEntry):
303 _type_ = PseudoHighLevelCallable
304
305 def compute_result_annotation(self, *args_s):
306 return self.instance.s_result
307
308 def specialize_call(self, hop):
309 args_r = [hop.rtyper.getrepr(s) for s in self.instance.args_s]
310 r_res = hop.rtyper.getrepr(self.instance.s_result)
311 vlist = hop.inputargs(*args_r)
312 p = self.instance.llfnptr
313 TYPE = lltype.typeOf(p)
314 c_func = Constant(p, TYPE)
315 FUNCTYPE = TYPE.TO
316 for r_arg, ARGTYPE in zip(args_r, FUNCTYPE.ARGS):
317 assert r_arg.lowleveltype == ARGTYPE
318 assert r_res.lowleveltype == FUNCTYPE.RESULT
319 hop.exception_is_here()
320 return hop.genop('direct_call', [c_func] + vlist, resulttype = r_res)
321
322 # ____________________________________________________________
323
324
325 def llhelper(F, f):
326 """Gives a low-level function pointer of type F which, when called,
327 invokes the RPython function f().
328 """
329 # Example - the following code can be either run or translated:
330 #
331 # def my_rpython_code():
332 # g = llhelper(F, my_other_rpython_function)
333 # assert typeOf(g) == F
334 # ...
335 # g()
336 #
337 # however the following doesn't translate (xxx could be fixed with hacks):
338 #
339 # prebuilt_g = llhelper(F, f)
340 # def my_rpython_code():
341 # prebuilt_g()
342
343 # the next line is the implementation for the purpose of direct running
344 return lltype.functionptr(F.TO, f.__name__, _callable=f)
345
346 def llhelper_args(f, ARGS, RESULT):
347 return llhelper(lltype.Ptr(lltype.FuncType(ARGS, RESULT)), f)
348
349 class LLHelperEntry(extregistry.ExtRegistryEntry):
350 _about_ = llhelper
351
352 def compute_result_annotation(self, s_F, s_callable):
353 from rpython.annotator.description import FunctionDesc
354 assert s_F.is_constant()
355 assert isinstance(s_callable, annmodel.SomePBC)
356 F = s_F.const
357 FUNC = F.TO
358 args_s = [lltype_to_annotation(T) for T in FUNC.ARGS]
359 for desc in s_callable.descriptions:
360 assert isinstance(desc, FunctionDesc)
361 assert desc.pyobj is not None
362 if s_callable.is_constant():
363 assert s_callable.const is desc.pyobj
364 key = (llhelper, desc.pyobj)
365 s_res = self.bookkeeper.emulate_pbc_call(key, s_callable, args_s)
366 assert lltype_to_annotation(FUNC.RESULT).contains(s_res)
367 return SomePtr(F)
368
369 def specialize_call(self, hop):
370 hop.exception_cannot_occur()
371 if hop.args_s[1].is_constant():
372 return hop.args_r[1].get_unique_llfn()
373 else:
374 F = hop.args_s[0].const
375 assert hop.args_r[1].lowleveltype == F
376 return hop.inputarg(hop.args_r[1], 1)
377
378 # ____________________________________________________________
379
380 def make_string_entries(strtype):
381 assert strtype in (str, unicode)
382
383 def hlstr(ll_s):
384 if not ll_s:
385 return None
386 if hasattr(ll_s, 'chars'):
387 if strtype is str:
388 return ''.join(ll_s.chars)
389 else:
390 return u''.join(ll_s.chars)
391 else:
392 return ll_s._str
393
394 class HLStrEntry(extregistry.ExtRegistryEntry):
395 _about_ = hlstr
396
397 def compute_result_annotation(self, s_ll_str):
398 if strtype is str:
399 return annmodel.SomeString(can_be_None=True)
400 else:
401 return annmodel.SomeUnicodeString(can_be_None=True)
402
403 def specialize_call(self, hop):
404 hop.exception_cannot_occur()
405 assert hop.args_r[0].lowleveltype == hop.r_result.lowleveltype
406 v_ll_str, = hop.inputargs(*hop.args_r)
407 return hop.genop('same_as', [v_ll_str],
408 resulttype = hop.r_result.lowleveltype)
409
410 def llstr(s):
411 from rpython.rtyper.lltypesystem.rstr import mallocstr, mallocunicode
412 from rpython.rtyper.lltypesystem.rstr import STR, UNICODE
413 if strtype is str:
414 if s is None:
415 return lltype.nullptr(STR)
416 ll_s = mallocstr(len(s))
417 else:
418 if s is None:
419 return lltype.nullptr(UNICODE)
420 ll_s = mallocunicode(len(s))
421 for i, c in enumerate(s):
422 ll_s.chars[i] = c
423 return ll_s
424
425 class LLStrEntry(extregistry.ExtRegistryEntry):
426 _about_ = llstr
427
428 def compute_result_annotation(self, s_str):
429 from rpython.rtyper.lltypesystem.rstr import STR, UNICODE
430 if strtype is str:
431 return lltype_to_annotation(lltype.Ptr(STR))
432 else:
433 return lltype_to_annotation(lltype.Ptr(UNICODE))
434
435 def specialize_call(self, hop):
436 from rpython.rtyper.lltypesystem.rstr import (string_repr,
437 unicode_repr)
438 hop.exception_cannot_occur()
439 if strtype is str:
440 v_ll_str = hop.inputarg(string_repr, 0)
441 else:
442 v_ll_str = hop.inputarg(unicode_repr, 0)
443 return hop.genop('same_as', [v_ll_str],
444 resulttype = hop.r_result.lowleveltype)
445
446 return hlstr, llstr
447
448 hlstr, llstr = make_string_entries(str)
449 hlunicode, llunicode = make_string_entries(unicode)
450
451 # ____________________________________________________________
452
453 def cast_object_to_ptr(PTR, object):
454 """NOT_RPYTHON: hack. The object may be disguised as a PTR now.
455 Limited to casting a given object to a single type.
456 """
457 if hasattr(object, '_freeze_'):
458 warning("Trying to cast a frozen object to pointer")
459 if isinstance(PTR, lltype.Ptr):
460 TO = PTR.TO
461 else:
462 TO = PTR
463 if not hasattr(object, '_carry_around_for_tests'):
464 if object is None:
465 return lltype.nullptr(PTR.TO)
466 assert not hasattr(object, '_TYPE')
467 object._carry_around_for_tests = True
468 object._TYPE = TO
469 else:
470 assert object._TYPE == TO
471 #
472 if isinstance(PTR, lltype.Ptr):
473 return lltype._ptr(PTR, object, True)
474 else:
475 raise NotImplementedError("cast_object_to_ptr(%r, ...)" % PTR)
476
477 @specialize.argtype(0)
478 def cast_instance_to_base_ptr(instance):
479 from rpython.rtyper.rclass import OBJECTPTR
480 return cast_object_to_ptr(OBJECTPTR, instance)
481
482 @specialize.argtype(0)
483 def cast_instance_to_gcref(instance):
484 return lltype.cast_opaque_ptr(llmemory.GCREF,
485 cast_instance_to_base_ptr(instance))
486
487 @specialize.argtype(0)
488 def cast_nongc_instance_to_base_ptr(instance):
489 from rpython.rtyper.rclass import NONGCOBJECTPTR
490 return cast_object_to_ptr(NONGCOBJECTPTR, instance)
491
492 @specialize.argtype(0)
493 def cast_nongc_instance_to_adr(instance):
494 return llmemory.cast_ptr_to_adr(cast_nongc_instance_to_base_ptr(instance))
495
496 class CastObjectToPtrEntry(extregistry.ExtRegistryEntry):
497 _about_ = cast_object_to_ptr
498
499 def compute_result_annotation(self, s_PTR, s_object):
500 assert s_PTR.is_constant()
501 if isinstance(s_PTR.const, lltype.Ptr):
502 return SomePtr(s_PTR.const)
503 else:
504 assert False
505
506 def specialize_call(self, hop):
507 from rpython.rtyper.rnone import NoneRepr
508 PTR = hop.r_result.lowleveltype
509 if isinstance(PTR, lltype.Ptr):
510 T = lltype.Ptr
511 opname = 'cast_pointer'
512 null = lltype.nullptr(PTR.TO)
513 else:
514 assert False
515
516 hop.exception_cannot_occur()
517 if isinstance(hop.args_r[1], NoneRepr):
518 return hop.inputconst(PTR, null)
519 v_arg = hop.inputarg(hop.args_r[1], arg=1)
520 assert isinstance(v_arg.concretetype, T)
521 return hop.genop(opname, [v_arg], resulttype = PTR)
522
523
524 # ____________________________________________________________
525
526 def cast_base_ptr_to_instance(Class, ptr):
527 """NOT_RPYTHON: hack. Reverse the hacking done in cast_object_to_ptr()."""
528 if isinstance(lltype.typeOf(ptr), lltype.Ptr):
529 ptr = ptr._as_obj()
530 if ptr is None:
531 return None
532 if not isinstance(ptr, Class):
533 raise NotImplementedError("cast_base_ptr_to_instance: casting %r to %r"
534 % (ptr, Class))
535 return ptr
536
537 cast_base_ptr_to_nongc_instance = cast_base_ptr_to_instance
538
539 @specialize.arg(0)
540 def cast_gcref_to_instance(Class, ptr):
541 """Reverse the hacking done in cast_instance_to_gcref()."""
542 from rpython.rtyper.rclass import OBJECTPTR
543 ptr = lltype.cast_opaque_ptr(OBJECTPTR, ptr)
544 return cast_base_ptr_to_instance(Class, ptr)
545
546 @specialize.arg(0)
547 def cast_adr_to_nongc_instance(Class, ptr):
548 from rpython.rtyper.rclass import NONGCOBJECTPTR
549 ptr = llmemory.cast_adr_to_ptr(ptr, NONGCOBJECTPTR)
550 return cast_base_ptr_to_nongc_instance(Class, ptr)
551
552 class CastBasePtrToInstanceEntry(extregistry.ExtRegistryEntry):
553 _about_ = cast_base_ptr_to_instance
554
555 def compute_result_annotation(self, s_Class, s_ptr):
556 assert s_Class.is_constant()
557 classdef = self.bookkeeper.getuniqueclassdef(s_Class.const)
558 return annmodel.SomeInstance(classdef, can_be_None=True)
559
560 def specialize_call(self, hop):
561 v_arg = hop.inputarg(hop.args_r[1], arg=1)
562 if isinstance(v_arg.concretetype, lltype.Ptr):
563 opname = 'cast_pointer'
564 else:
565 assert False
566 hop.exception_cannot_occur()
567 return hop.genop(opname, [v_arg],
568 resulttype = hop.r_result.lowleveltype)
569
570 # ____________________________________________________________
571
572
573 def placeholder_sigarg(s):
574 if s == "self":
575 def expand(s_self, *args_s):
576 assert isinstance(s_self, SomePtr)
577 return s_self
578 elif s == "SELF":
579 raise NotImplementedError
580 else:
581 assert s.islower()
582 def expand(s_self, *args_s):
583 assert isinstance(s_self, SomePtr)
584 return getattr(s_self.ll_ptrtype.TO, s.upper())
585 return expand
586
587 def typemeth_placeholder_sigarg(s):
588 if s == "SELF":
589 def expand(s_TYPE, *args_s):
590 assert isinstance(s_TYPE, annmodel.SomePBC)
591 assert s_TYPE.is_constant()
592 return s_TYPE
593 elif s == "self":
594 def expand(s_TYPE, *args_s):
595 assert isinstance(s_TYPE, annmodel.SomePBC)
596 assert s_TYPE.is_constant()
597 return lltype.Ptr(s_TYPE.const)
598 else:
599 assert s.islower()
600 def expand(s_TYPE, *args_s):
601 assert isinstance(s_TYPE, annmodel.SomePBC)
602 assert s_TYPE.is_constant()
603 return getattr(s_TYPE.const, s.upper())
604 return expand
605
606
607 class ADTInterface(object):
608
609 def __init__(self, base, sigtemplates):
610 self.sigtemplates = sigtemplates
611 self.base = base
612 sigs = {}
613 if base is not None:
614 sigs.update(base.sigs)
615 for name, template in sigtemplates.items():
616 args, result = template
617 if args[0] == "self":
618 make_expand = placeholder_sigarg
619 elif args[0] == "SELF":
620 make_expand = typemeth_placeholder_sigarg
621 else:
622 assert False, ("ADTInterface signature should start with"
623 " 'SELF' or 'self'")
624 sigargs = []
625 for arg in args:
626 if isinstance(arg, str):
627 arg = make_expand(arg)
628 sigargs.append(arg)
629 sigs[name] = Sig(*sigargs)
630 self.sigs = sigs
631
632 def __call__(self, adtmeths):
633 for name, sig in self.sigs.items():
634 meth = adtmeths[name]
635 prevsig = getattr(meth, '_annenforceargs_', None)
636 if prevsig:
637 assert prevsig is sig
638 else:
639 meth._annenforceargs_ = sig
640 return adtmeths
641
642 # ____________________________________________________________
643
644 class cachedtype(type):
645 """Metaclass for classes that should only have one instance per
646 tuple of arguments given to the constructor."""
647
648 def __init__(selfcls, name, bases, dict):
649 super(cachedtype, selfcls).__init__(name, bases, dict)
650 selfcls._instancecache = {}
651
652 def __call__(selfcls, *args):
653 d = selfcls._instancecache
654 try:
655 return d[args]
656 except KeyError:
657 instance = d[args] = selfcls.__new__(selfcls, *args)
658 try:
659 instance.__init__(*args)
660 except:
661 # If __init__ fails, remove the 'instance' from d.
662 # That's a "best effort" attempt, it's not really enough
663 # in theory because some other place might have grabbed
664 # a reference to the same broken 'instance' in the meantime
665 del d[args]
666 raise
667 return instance