711c9650788a03e2b22a8528694014ff7006ad3f
[soc.git] / src / soc / decoder / isa / caller.py
1 """core of the python-based POWER9 simulator
2
3 this is part of a cycle-accurate POWER9 simulator. its primary purpose is
4 not speed, it is for both learning and educational purposes, as well as
5 a method of verifying the HDL.
6
7 related bugs:
8
9 * https://bugs.libre-soc.org/show_bug.cgi?id=424
10 """
11
12 from functools import wraps
13 from soc.decoder.orderedset import OrderedSet
14 from soc.decoder.selectable_int import (FieldSelectableInt, SelectableInt,
15 selectconcat)
16 from soc.decoder.power_enums import (spr_dict, spr_byname, XER_bits,
17 insns, InternalOp)
18 from soc.decoder.helpers import exts, trunc_div, trunc_rem
19 from soc.consts import PI, MSR
20
21 from collections import namedtuple
22 import math
23 import sys
24
25 instruction_info = namedtuple('instruction_info',
26 'func read_regs uninit_regs write_regs ' + \
27 'special_regs op_fields form asmregs')
28
29 special_sprs = {
30 'LR': 8,
31 'CTR': 9,
32 'TAR': 815,
33 'XER': 1,
34 'VRSAVE': 256}
35
36
37 def swap_order(x, nbytes):
38 x = x.to_bytes(nbytes, byteorder='little')
39 x = int.from_bytes(x, byteorder='big', signed=False)
40 return x
41
42
43 def create_args(reglist, extra=None):
44 args = OrderedSet()
45 for reg in reglist:
46 args.add(reg)
47 args = list(args)
48 if extra:
49 args = [extra] + args
50 return args
51
52
53 class Mem:
54
55 def __init__(self, row_bytes=8, initial_mem=None):
56 self.mem = {}
57 self.bytes_per_word = row_bytes
58 self.word_log2 = math.ceil(math.log2(row_bytes))
59 print ("Sim-Mem", initial_mem, self.bytes_per_word, self.word_log2)
60 if not initial_mem:
61 return
62
63 # different types of memory data structures recognised (for convenience)
64 if isinstance(initial_mem, list):
65 initial_mem = (0, initial_mem)
66 if isinstance(initial_mem, tuple):
67 startaddr, mem = initial_mem
68 initial_mem = {}
69 for i, val in enumerate(mem):
70 initial_mem[startaddr + row_bytes*i] = (val, row_bytes)
71
72 for addr, (val, width) in initial_mem.items():
73 #val = swap_order(val, width)
74 self.st(addr, val, width, swap=False)
75
76 def _get_shifter_mask(self, wid, remainder):
77 shifter = ((self.bytes_per_word - wid) - remainder) * \
78 8 # bits per byte
79 # XXX https://bugs.libre-soc.org/show_bug.cgi?id=377
80 # BE/LE mode?
81 shifter = remainder * 8
82 mask = (1 << (wid * 8)) - 1
83 print ("width,rem,shift,mask", wid, remainder, hex(shifter), hex(mask))
84 return shifter, mask
85
86 # TODO: Implement ld/st of lesser width
87 def ld(self, address, width=8, swap=True, check_in_mem=False):
88 print("ld from addr 0x{:x} width {:d}".format(address, width))
89 remainder = address & (self.bytes_per_word - 1)
90 address = address >> self.word_log2
91 assert remainder & (width - 1) == 0, "Unaligned access unsupported!"
92 if address in self.mem:
93 val = self.mem[address]
94 elif check_in_mem:
95 return None
96 else:
97 val = 0
98 print("mem @ 0x{:x} rem {:d} : 0x{:x}".format(address, remainder, val))
99
100 if width != self.bytes_per_word:
101 shifter, mask = self._get_shifter_mask(width, remainder)
102 print ("masking", hex(val), hex(mask<<shifter), shifter)
103 val = val & (mask << shifter)
104 val >>= shifter
105 if swap:
106 val = swap_order(val, width)
107 print("Read 0x{:x} from addr 0x{:x}".format(val, address))
108 return val
109
110 def st(self, addr, v, width=8, swap=True):
111 staddr = addr
112 remainder = addr & (self.bytes_per_word - 1)
113 addr = addr >> self.word_log2
114 print("Writing 0x{:x} to ST 0x{:x} memaddr 0x{:x}/{:x}".format(v,
115 staddr, addr, remainder, swap))
116 assert remainder & (width - 1) == 0, "Unaligned access unsupported!"
117 if swap:
118 v = swap_order(v, width)
119 if width != self.bytes_per_word:
120 if addr in self.mem:
121 val = self.mem[addr]
122 else:
123 val = 0
124 shifter, mask = self._get_shifter_mask(width, remainder)
125 val &= ~(mask << shifter)
126 val |= v << shifter
127 self.mem[addr] = val
128 else:
129 self.mem[addr] = v
130 print("mem @ 0x{:x}: 0x{:x}".format(addr, self.mem[addr]))
131
132 def __call__(self, addr, sz):
133 val = self.ld(addr.value, sz)
134 print ("memread", addr, sz, val)
135 return SelectableInt(val, sz*8)
136
137 def memassign(self, addr, sz, val):
138 print ("memassign", addr, sz, val)
139 self.st(addr.value, val.value, sz)
140
141
142 class GPR(dict):
143 def __init__(self, decoder, regfile):
144 dict.__init__(self)
145 self.sd = decoder
146 for i in range(32):
147 self[i] = SelectableInt(regfile[i], 64)
148
149 def __call__(self, ridx):
150 return self[ridx]
151
152 def set_form(self, form):
153 self.form = form
154
155 def getz(self, rnum):
156 #rnum = rnum.value # only SelectableInt allowed
157 print("GPR getzero", rnum)
158 if rnum == 0:
159 return SelectableInt(0, 64)
160 return self[rnum]
161
162 def _get_regnum(self, attr):
163 getform = self.sd.sigforms[self.form]
164 rnum = getattr(getform, attr)
165 return rnum
166
167 def ___getitem__(self, attr):
168 print("GPR getitem", attr)
169 rnum = self._get_regnum(attr)
170 return self.regfile[rnum]
171
172 def dump(self):
173 for i in range(0, len(self), 8):
174 s = []
175 for j in range(8):
176 s.append("%08x" % self[i+j].value)
177 s = ' '.join(s)
178 print("reg", "%2d" % i, s)
179
180 class PC:
181 def __init__(self, pc_init=0):
182 self.CIA = SelectableInt(pc_init, 64)
183 self.NIA = self.CIA + SelectableInt(4, 64)
184
185 def update(self, namespace):
186 self.CIA = namespace['NIA'].narrow(64)
187 self.NIA = self.CIA + SelectableInt(4, 64)
188 namespace['CIA'] = self.CIA
189 namespace['NIA'] = self.NIA
190
191
192 class SPR(dict):
193 def __init__(self, dec2, initial_sprs={}):
194 self.sd = dec2
195 dict.__init__(self)
196 for key, v in initial_sprs.items():
197 if isinstance(key, SelectableInt):
198 key = key.value
199 key = special_sprs.get(key, key)
200 if isinstance(key, int):
201 info = spr_dict[key]
202 else:
203 info = spr_byname[key]
204 if not isinstance(v, SelectableInt):
205 v = SelectableInt(v, info.length)
206 self[key] = v
207
208 def __getitem__(self, key):
209 print ("get spr", key)
210 print ("dict", self.items())
211 # if key in special_sprs get the special spr, otherwise return key
212 if isinstance(key, SelectableInt):
213 key = key.value
214 if isinstance(key, int):
215 key = spr_dict[key].SPR
216 key = special_sprs.get(key, key)
217 if key in self:
218 res = dict.__getitem__(self, key)
219 else:
220 if isinstance(key, int):
221 info = spr_dict[key]
222 else:
223 info = spr_byname[key]
224 dict.__setitem__(self, key, SelectableInt(0, info.length))
225 res = dict.__getitem__(self, key)
226 print ("spr returning", key, res)
227 return res
228
229 def __setitem__(self, key, value):
230 if isinstance(key, SelectableInt):
231 key = key.value
232 if isinstance(key, int):
233 key = spr_dict[key].SPR
234 print ("spr key", key)
235 key = special_sprs.get(key, key)
236 print ("setting spr", key, value)
237 dict.__setitem__(self, key, value)
238
239 def __call__(self, ridx):
240 return self[ridx]
241
242
243 class ISACaller:
244 # decoder2 - an instance of power_decoder2
245 # regfile - a list of initial values for the registers
246 # initial_{etc} - initial values for SPRs, Condition Register, Mem, MSR
247 # respect_pc - tracks the program counter. requires initial_insns
248 def __init__(self, decoder2, regfile, initial_sprs=None, initial_cr=0,
249 initial_mem=None, initial_msr=0,
250 initial_insns=None, respect_pc=False,
251 disassembly=None,
252 initial_pc=0,
253 bigendian=True):
254
255 self.bigendian = bigendian
256 self.halted = False
257 self.respect_pc = respect_pc
258 if initial_sprs is None:
259 initial_sprs = {}
260 if initial_mem is None:
261 initial_mem = {}
262 if initial_insns is None:
263 initial_insns = {}
264 assert self.respect_pc == False, "instructions required to honor pc"
265
266 print ("ISACaller insns", respect_pc, initial_insns, disassembly)
267
268 # "fake program counter" mode (for unit testing)
269 self.fake_pc = 0
270 disasm_start = 0
271 if not respect_pc:
272 if isinstance(initial_mem, tuple):
273 self.fake_pc = initial_mem[0]
274 disasm_start = self.fake_pc
275 else:
276 disasm_start = initial_pc
277
278 # disassembly: we need this for now (not given from the decoder)
279 self.disassembly = {}
280 if disassembly:
281 for i, code in enumerate(disassembly):
282 self.disassembly[i*4 + disasm_start] = code
283
284 # set up registers, instruction memory, data memory, PC, SPRs, MSR
285 self.gpr = GPR(decoder2, regfile)
286 self.mem = Mem(row_bytes=8, initial_mem=initial_mem)
287 self.imem = Mem(row_bytes=4, initial_mem=initial_insns)
288 self.pc = PC()
289 self.spr = SPR(decoder2, initial_sprs)
290 self.msr = SelectableInt(initial_msr, 64) # underlying reg
291
292 # TODO, needed here:
293 # FPR (same as GPR except for FP nums)
294 # 4.2.2 p124 FPSCR (definitely "separate" - not in SPR)
295 # note that mffs, mcrfs, mtfsf "manage" this FPSCR
296 # 2.3.1 CR (and sub-fields CR0..CR6 - CR0 SO comes from XER.SO)
297 # note that mfocrf, mfcr, mtcr, mtocrf, mcrxrx "manage" CRs
298 # -- Done
299 # 2.3.2 LR (actually SPR #8) -- Done
300 # 2.3.3 CTR (actually SPR #9) -- Done
301 # 2.3.4 TAR (actually SPR #815)
302 # 3.2.2 p45 XER (actually SPR #1) -- Done
303 # 3.2.3 p46 p232 VRSAVE (actually SPR #256)
304
305 # create CR then allow portions of it to be "selectable" (below)
306 self._cr = SelectableInt(initial_cr, 64) # underlying reg
307 self.cr = FieldSelectableInt(self._cr, list(range(32,64)))
308
309 # "undefined", just set to variable-bit-width int (use exts "max")
310 self.undefined = SelectableInt(0, 256) # TODO, not hard-code 256!
311
312 self.namespace = {}
313 self.namespace.update(self.spr)
314 self.namespace.update({'GPR': self.gpr,
315 'MEM': self.mem,
316 'SPR': self.spr,
317 'memassign': self.memassign,
318 'NIA': self.pc.NIA,
319 'CIA': self.pc.CIA,
320 'CR': self.cr,
321 'MSR': self.msr,
322 'undefined': self.undefined,
323 'mode_is_64bit': True,
324 'SO': XER_bits['SO']
325 })
326
327 # update pc to requested start point
328 self.set_pc(initial_pc)
329
330 # field-selectable versions of Condition Register TODO check bitranges?
331 self.crl = []
332 for i in range(8):
333 bits = tuple(range(i*4, (i+1)*4))# errr... maybe?
334 _cr = FieldSelectableInt(self.cr, bits)
335 self.crl.append(_cr)
336 self.namespace["CR%d" % i] = _cr
337
338 self.decoder = decoder2.dec
339 self.dec2 = decoder2
340
341 def TRAP(self, trap_addr=0x700, trap_bit=PI.TRAP):
342 print ("TRAP:", hex(trap_addr))
343 # store CIA(+4?) in SRR0, set NIA to 0x700
344 # store MSR in SRR1, set MSR to um errr something, have to check spec
345 self.spr['SRR0'] = self.pc.CIA
346 self.spr['SRR1'] = self.namespace['MSR']
347 self.trap_nia = SelectableInt(trap_addr, 64)
348 self.namespace['MSR'][63-trap_bit] = 1
349
350 def memassign(self, ea, sz, val):
351 self.mem.memassign(ea, sz, val)
352
353 def prep_namespace(self, formname, op_fields):
354 # TODO: get field names from form in decoder*1* (not decoder2)
355 # decoder2 is hand-created, and decoder1.sigform is auto-generated
356 # from spec
357 # then "yield" fields only from op_fields rather than hard-coded
358 # list, here.
359 fields = self.decoder.sigforms[formname]
360 for name in op_fields:
361 if name == 'spr':
362 sig = getattr(fields, name.upper())
363 else:
364 sig = getattr(fields, name)
365 val = yield sig
366 if name in ['BF', 'BFA']:
367 self.namespace[name] = val
368 else:
369 self.namespace[name] = SelectableInt(val, sig.width)
370
371 self.namespace['XER'] = self.spr['XER']
372 self.namespace['CA'] = self.spr['XER'][XER_bits['CA']].value
373 self.namespace['CA32'] = self.spr['XER'][XER_bits['CA32']].value
374
375 def handle_carry_(self, inputs, outputs, already_done):
376 inv_a = yield self.dec2.e.do.invert_a
377 if inv_a:
378 inputs[0] = ~inputs[0]
379
380 imm_ok = yield self.dec2.e.do.imm_data.ok
381 if imm_ok:
382 imm = yield self.dec2.e.do.imm_data.data
383 inputs.append(SelectableInt(imm, 64))
384 assert len(outputs) >= 1
385 print ("outputs", repr(outputs))
386 if isinstance(outputs, list) or isinstance(outputs, tuple):
387 output = outputs[0]
388 else:
389 output = outputs
390 gts = []
391 for x in inputs:
392 print ("gt input", x, output)
393 gt = (x > output)
394 gts.append(gt)
395 print(gts)
396 cy = 1 if any(gts) else 0
397 if not (1 & already_done):
398 self.spr['XER'][XER_bits['CA']] = cy
399
400 print ("inputs", inputs)
401 # 32 bit carry
402 gts = []
403 for x in inputs:
404 print ("input", x, output)
405 gt = (x[32:64] > output[32:64]) == SelectableInt(1, 1)
406 gts.append(gt)
407 cy32 = 1 if any(gts) else 0
408 if not (2 & already_done):
409 self.spr['XER'][XER_bits['CA32']] = cy32
410
411 def handle_overflow(self, inputs, outputs, div_overflow):
412 inv_a = yield self.dec2.e.do.invert_a
413 if inv_a:
414 inputs[0] = ~inputs[0]
415
416 imm_ok = yield self.dec2.e.do.imm_data.ok
417 if imm_ok:
418 imm = yield self.dec2.e.do.imm_data.data
419 inputs.append(SelectableInt(imm, 64))
420 assert len(outputs) >= 1
421 print ("handle_overflow", inputs, outputs, div_overflow)
422 if len(inputs) < 2 and div_overflow is None:
423 return
424
425 # div overflow is different: it's returned by the pseudo-code
426 # because it's more complex than can be done by analysing the output
427 if div_overflow is not None:
428 ov, ov32 = div_overflow, div_overflow
429 # arithmetic overflow can be done by analysing the input and output
430 elif len(inputs) >= 2:
431 output = outputs[0]
432
433 # OV (64-bit)
434 input_sgn = [exts(x.value, x.bits) < 0 for x in inputs]
435 output_sgn = exts(output.value, output.bits) < 0
436 ov = 1 if input_sgn[0] == input_sgn[1] and \
437 output_sgn != input_sgn[0] else 0
438
439 # OV (32-bit)
440 input32_sgn = [exts(x.value, 32) < 0 for x in inputs]
441 output32_sgn = exts(output.value, 32) < 0
442 ov32 = 1 if input32_sgn[0] == input32_sgn[1] and \
443 output32_sgn != input32_sgn[0] else 0
444
445 self.spr['XER'][XER_bits['OV']] = ov
446 self.spr['XER'][XER_bits['OV32']] = ov32
447 so = self.spr['XER'][XER_bits['SO']]
448 so = so | ov
449 self.spr['XER'][XER_bits['SO']] = so
450
451 def handle_comparison(self, outputs):
452 out = outputs[0]
453 print ("handle_comparison", out.bits, hex(out.value))
454 # TODO - XXX *processor* in 32-bit mode
455 # https://bugs.libre-soc.org/show_bug.cgi?id=424
456 #if is_32bit:
457 # o32 = exts(out.value, 32)
458 # print ("handle_comparison exts 32 bit", hex(o32))
459 out = exts(out.value, out.bits)
460 print ("handle_comparison exts", hex(out))
461 zero = SelectableInt(out == 0, 1)
462 positive = SelectableInt(out > 0, 1)
463 negative = SelectableInt(out < 0, 1)
464 SO = self.spr['XER'][XER_bits['SO']]
465 print ("handle_comparison SO", SO)
466 cr_field = selectconcat(negative, positive, zero, SO)
467 self.crl[0].eq(cr_field)
468
469 def set_pc(self, pc_val):
470 self.namespace['NIA'] = SelectableInt(pc_val, 64)
471 self.pc.update(self.namespace)
472
473 def setup_one(self):
474 """set up one instruction
475 """
476 if self.respect_pc:
477 pc = self.pc.CIA.value
478 else:
479 pc = self.fake_pc
480 self._pc = pc
481 ins = self.imem.ld(pc, 4, False, True)
482 if ins is None:
483 raise KeyError("no instruction at 0x%x" % pc)
484 print("setup: 0x%x 0x%x %s" % (pc, ins & 0xffffffff, bin(ins)))
485 print ("CIA NIA", self.respect_pc, self.pc.CIA.value, self.pc.NIA.value)
486
487 yield self.dec2.dec.raw_opcode_in.eq(ins & 0xffffffff)
488 yield self.dec2.dec.bigendian.eq(self.bigendian)
489
490 def execute_one(self):
491 """execute one instruction
492 """
493 # get the disassembly code for this instruction
494 code = self.disassembly[self._pc]
495 print("sim-execute", hex(self._pc), code)
496 opname = code.split(' ')[0]
497 yield from self.call(opname)
498
499 if not self.respect_pc:
500 self.fake_pc += 4
501 print ("execute one, CIA NIA", self.pc.CIA.value, self.pc.NIA.value)
502
503 def get_assembly_name(self):
504 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
505 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
506 asmcode = yield self.dec2.dec.op.asmcode
507 print ("get assembly name asmcode", asmcode)
508 asmop = insns.get(asmcode, None)
509
510 # sigh reconstruct the assembly instruction name
511 ov_en = yield self.dec2.e.do.oe.oe
512 ov_ok = yield self.dec2.e.do.oe.ok
513 if ov_en & ov_ok:
514 asmop += "."
515 lk = yield self.dec2.e.do.lk
516 if lk:
517 asmop += "l"
518 int_op = yield self.dec2.dec.op.internal_op
519 print ("int_op", int_op)
520 if int_op in [InternalOp.OP_B.value, InternalOp.OP_BC.value]:
521 AA = yield self.dec2.dec.fields.FormI.AA[0:-1]
522 print ("AA", AA)
523 if AA:
524 asmop += "a"
525 if int_op == InternalOp.OP_MFCR.value:
526 dec_insn = yield self.dec2.e.do.insn
527 if dec_insn & (1<<20) != 0: # sigh
528 asmop = 'mfocrf'
529 else:
530 asmop = 'mfcr'
531 # XXX TODO: for whatever weird reason this doesn't work
532 # https://bugs.libre-soc.org/show_bug.cgi?id=390
533 if int_op == InternalOp.OP_MTCRF.value:
534 dec_insn = yield self.dec2.e.do.insn
535 if dec_insn & (1<<20) != 0: # sigh
536 asmop = 'mtocrf'
537 else:
538 asmop = 'mtcrf'
539 return asmop
540
541 def call(self, name):
542 name = name.strip() # remove spaces if not already done so
543 if self.halted:
544 print ("halted - not executing", name)
545 return
546
547 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
548 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
549 asmop = yield from self.get_assembly_name()
550 print ("call", name, asmop)
551
552 # check halted condition
553 if name == 'attn':
554 self.halted = True
555 return
556
557 # check illegal instruction
558 illegal = False
559 if name not in ['mtcrf', 'mtocrf']:
560 illegal = name != asmop
561
562 if illegal:
563 print ("name %s != %s - calling ILLEGAL trap" % (name, asmop))
564 self.TRAP(0x700, PI.ILLEG)
565 self.namespace['NIA'] = self.trap_nia
566 self.pc.update(self.namespace)
567 return
568
569 info = self.instrs[name]
570 yield from self.prep_namespace(info.form, info.op_fields)
571
572 # preserve order of register names
573 input_names = create_args(list(info.read_regs) +
574 list(info.uninit_regs))
575 print(input_names)
576
577 # main registers (RT, RA ...)
578 inputs = []
579 for name in input_names:
580 regnum = yield getattr(self.decoder, name)
581 regname = "_" + name
582 self.namespace[regname] = regnum
583 print('reading reg %d' % regnum)
584 inputs.append(self.gpr(regnum))
585
586 # "special" registers
587 for special in info.special_regs:
588 if special in special_sprs:
589 inputs.append(self.spr[special])
590 else:
591 inputs.append(self.namespace[special])
592
593 # clear trap (trap) NIA
594 self.trap_nia = None
595
596 print(inputs)
597 results = info.func(self, *inputs)
598 print(results)
599
600 # "inject" decorator takes namespace from function locals: we need to
601 # overwrite NIA being overwritten (sigh)
602 if self.trap_nia is not None:
603 self.namespace['NIA'] = self.trap_nia
604
605 print ("after func", self.namespace['CIA'], self.namespace['NIA'])
606
607 # detect if CA/CA32 already in outputs (sra*, basically)
608 already_done = 0
609 if info.write_regs:
610 output_names = create_args(info.write_regs)
611 for name in output_names:
612 if name == 'CA':
613 already_done |= 1
614 if name == 'CA32':
615 already_done |= 2
616
617 print ("carry already done?", bin(already_done))
618 carry_en = yield self.dec2.e.do.output_carry
619 if carry_en:
620 yield from self.handle_carry_(inputs, results, already_done)
621
622 # detect if overflow was in return result
623 overflow = None
624 if info.write_regs:
625 for name, output in zip(output_names, results):
626 if name == 'overflow':
627 overflow = output
628
629 ov_en = yield self.dec2.e.do.oe.oe
630 ov_ok = yield self.dec2.e.do.oe.ok
631 print ("internal overflow", overflow)
632 if ov_en & ov_ok:
633 yield from self.handle_overflow(inputs, results, overflow)
634
635 rc_en = yield self.dec2.e.do.rc.data
636 if rc_en:
637 self.handle_comparison(results)
638
639 # any modified return results?
640 if info.write_regs:
641 for name, output in zip(output_names, results):
642 if name == 'overflow': # ignore, done already (above)
643 continue
644 if isinstance(output, int):
645 output = SelectableInt(output, 256)
646 if name in ['CA', 'CA32']:
647 if carry_en:
648 print ("writing %s to XER" % name, output)
649 self.spr['XER'][XER_bits[name]] = output.value
650 else:
651 print ("NOT writing %s to XER" % name, output)
652 elif name in info.special_regs:
653 print('writing special %s' % name, output, special_sprs)
654 if name in special_sprs:
655 self.spr[name] = output
656 else:
657 self.namespace[name].eq(output)
658 if name == 'MSR':
659 print ('msr written', hex(self.msr.value))
660 else:
661 regnum = yield getattr(self.decoder, name)
662 print('writing reg %d %s' % (regnum, str(output)))
663 if output.bits > 64:
664 output = SelectableInt(output.value, 64)
665 self.gpr[regnum] = output
666
667 print ("end of call", self.namespace['CIA'], self.namespace['NIA'])
668 # UPDATE program counter
669 self.pc.update(self.namespace)
670
671
672 def inject():
673 """Decorator factory.
674
675 this decorator will "inject" variables into the function's namespace,
676 from the *dictionary* in self.namespace. it therefore becomes possible
677 to make it look like a whole stack of variables which would otherwise
678 need "self." inserted in front of them (*and* for those variables to be
679 added to the instance) "appear" in the function.
680
681 "self.namespace['SI']" for example becomes accessible as just "SI" but
682 *only* inside the function, when decorated.
683 """
684 def variable_injector(func):
685 @wraps(func)
686 def decorator(*args, **kwargs):
687 try:
688 func_globals = func.__globals__ # Python 2.6+
689 except AttributeError:
690 func_globals = func.func_globals # Earlier versions.
691
692 context = args[0].namespace # variables to be injected
693 saved_values = func_globals.copy() # Shallow copy of dict.
694 func_globals.update(context)
695 result = func(*args, **kwargs)
696 print ("globals after", func_globals['CIA'], func_globals['NIA'])
697 print ("args[0]", args[0].namespace['CIA'],
698 args[0].namespace['NIA'])
699 args[0].namespace = func_globals
700 #exec (func.__code__, func_globals)
701
702 #finally:
703 # func_globals = saved_values # Undo changes.
704
705 return result
706
707 return decorator
708
709 return variable_injector
710