summaryrefslogtreecommitdiffstats
path: root/awlsim.py
blob: 2a11758b2113a5836223e28d0c395749c7d6f929 (plain)
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
# -*- coding: utf-8 -*-
#
# AWL simulator
# Copyright 2012 Michael Buesch <m@bues.ch>
#
# Licensed under the terms of the GNU General Public License version 2.
#

import sys
import time

from awlparser import *
from awldatatypes import *
from awlinstructions import *
from awloperators import *
from awlinsntrans import *
from awloptrans import *
from awlblocks import *
from awldatablocks import *
from awlstatusword import *
from awllabels import *
from awltimers import *
from awlcounters import *
from util import *
from lfsr import *


VERSION_MAJOR = 0
VERSION_MINOR = 6


class FlagByte(GenericByte):
	"Flag byte"

	def __init__(self):
		GenericByte.__init__(self)

class InputByte(GenericByte):
	"PAE byte"

	def __init__(self):
		GenericByte.__init__(self)

class OutputByte(GenericByte):
	"PAA byte"

	def __init__(self):
		GenericByte.__init__(self)

class LocalByte(GenericByte):
	"L byte"

	def __init__(self):
		GenericByte.__init__(self)

class Accu(GenericDWord):
	"Accumulator register"

	def __init__(self):
		GenericDWord.__init__(self)

class Adressregister(GenericDWord):
	"Address register"

	def __init__(self):
		GenericDWord.__init__(self)

class ParenStackElem(object):
	"Parenthesis stack element"

	def __init__(self, insnType, statusWord):
		self.insnType = insnType
		self.NER = statusWord.NER
		self.VKE = statusWord.VKE
		self.OR = statusWord.OR

	def __repr__(self):
		return '(insn="%s" VKE=%s OR=%d)' %\
			(AwlInsn.type2name[self.insnType],
			 self.VKE, self.OR)

class ObjectCache(object):
	def __init__(self, createCallback):
		self.__createCallback = createCallback
		self.reset()

	def get(self, callbackData=None):
		try:
			return self.__cache.pop()
		except IndexError as e:
			return self.__createCallback(callbackData)

	def put(self, obj):
		self.__cache.append(obj)

	def reset(self):
		self.__cache = []

class CallStackElem(object):
	"Call stack element"

	localdataCache = ObjectCache(lambda cpu:
		[ LocalByte()
		  for _ in range(cpu.specs.getNrLocalbytes()) ]
	)

	@classmethod
	def resetCache(cls):
		cls.localdataCache.reset()

	def __init__(self, cpu, block, db):
		self.cpu = cpu
		self.status = S7StatusWord()
		self.parenStack = []
		self.ip = 0
		self.localdata = self.localdataCache.get(cpu)
		assert(len(self.localdata) == cpu.specs.getNrLocalbytes())
		self.block = block
		self.db = db

	@property
	def insns(self):
		return self.block.insns

	@property
	def labels(self):
		return self.block.labels

	def destroy(self):
		# Only put it back into the cache, if the size didn't change.
		if len(self.localdata) == self.cpu.specs.getNrLocalbytes():
			self.localdataCache.put(self.localdata)
		self.localdata = None

	def __repr__(self):
		return str(self.block)

class McrStackElem(object):
	"MCR stack element"

	def __init__(self, statusWord):
		self.VKE = statusWord.VKE

	def __bool__(self):
		return bool(self.VKE)

	__nonzero__ = __bool__

class S7CPUSpecs(object):
	"STEP 7 CPU Specifications"

	def __init__(self, cpu):
		self.cpu = None
		self.setNrAccus(2)
		self.setNrTimers(2048)
		self.setNrCounters(2048)
		self.setNrFlags(8192)
		self.setNrInputs(8192)
		self.setNrOutputs(8192)
		self.setNrLocalbytes(1024)
		self.cpu = cpu

	def setNrAccus(self, count):
		if count not in (2, 4):
			raise AwlSimError("Invalid number of accus")
		self.nrAccus = count
		if self.cpu:
			self.cpu.reallocate()

	def getNrAccus(self):
		return self.nrAccus

	def setNrTimers(self, count):
		self.nrTimers = count
		if self.cpu:
			self.cpu.reallocate()

	def getNrTimers(self):
		return self.nrTimers

	def setNrCounters(self, count):
		self.nrCounters = count
		if self.cpu:
			self.cpu.reallocate()

	def getNrCounters(self):
		return self.nrCounters

	def setNrFlags(self, count):
		self.nrFlags = count
		if self.cpu:
			self.cpu.reallocate()

	def getNrFlags(self):
		return self.nrFlags

	def setNrInputs(self, count):
		self.nrInputs = count
		if self.cpu:
			self.cpu.reallocate()

	def getNrInputs(self):
		return self.nrInputs

	def setNrOutputs(self, count):
		self.nrOutputs = count
		if self.cpu:
			self.cpu.reallocate()

	def getNrOutputs(self):
		return self.nrOutputs

	def setNrLocalbytes(self, count):
		self.nrLocalbytes = count
		if self.cpu:
			self.cpu.reallocate()

	def getNrLocalbytes(self):
		return self.nrLocalbytes

class S7CPU(object):
	"STEP 7 CPU"

	def __init__(self, sim):
		self.sim = sim
		self.simplePRNG = Simple_PRNG()
		self.specs = S7CPUSpecs(self)
		self.setCycleTimeLimit(5.0)
		self.setCycleExitCallback(None)
		self.setBlockExitCallback(None)
		self.setPostInsnCallback(None)
		self.reset()
		self.__extendedInsnsEnabled = False

	def getSimplePRNG(self):
		return self.simplePRNG

	def enableExtendedInsns(self, en=True):
		self.__extendedInsnsEnabled = en

	def setCycleTimeLimit(self, newLimit):
		self.cycleTimeLimit = float(newLimit)

	def __translateInsn(self, rawInsn, ip):
		ex = None
		try:
			insn = AwlInsnTranslator.fromRawInsn(rawInsn,
				self.__extendedInsnsEnabled)
			insn.setCpu(self)
			insn.setIP(ip)
		except AwlSimError as e:
			ex = e
		if ex:
			raise AwlSimError("%s\nline %d: %s" %\
				(str(rawInsn), rawInsn.getLineNr(),
				 str(ex)))
		return insn

	def __translateInsns(self, rawInsns):
		insns = []
		for ip, rawInsn in enumerate(rawInsns):
			insns.append(self.__translateInsn(rawInsn, ip))
		return insns

	def __translateDB(self, db, rawDB):
		pass#TODO

	def load(self, parseTree):
		# Translate instructions
		self.reset()
		for obNumber in parseTree.obs.keys():
			insns = self.__translateInsns(parseTree.obs[obNumber].insns)
			self.obs[obNumber] = OB(insns, obNumber)
		for fbNumber in parseTree.fbs.keys():
			insns = self.__translateInsns(parseTree.fbs[fbNumber].insns)
			self.fbs[fbNumber] = FB(insns, fbNumber)
		for fcNumber in parseTree.fcs.keys():
			insns = self.__translateInsns(parseTree.fcs[fcNumber].insns)
			self.fcs[fcNumber] = FC(insns, fcNumber)
		for dbNumber in parseTree.dbs.keys():
			db = DB(dbNumber)
			self.__translateDB(db, parseTree.dbs[dbNumber])
			self.dbs[dbNumber] = db
		try:
			self.obs[1]
		except KeyError:
			raise AwlSimError("No OB1 defined")

	def reallocate(self, force=False):
		if force or (self.specs.getNrAccus() == 4) != self.is4accu:
			self.accu1, self.accu2 = Accu(), Accu()
			if self.specs.getNrAccus() == 2:
				self.accu3, self.accu4 = None, None
			elif self.specs.getNrAccus() == 4:
				self.accu3, self.accu4 = Accu(), Accu()
			else:
				assert(0)
		if force or self.specs.getNrTimers() != len(self.timers):
			self.timers = [ Timer(self, i)
					for i in range(self.specs.getNrTimers()) ]
		if force or self.specs.getNrCounters() != len(self.counters):
			self.counters = [ Counter(self, i)
					  for i in range(self.specs.getNrCounters()) ]
		if force or self.specs.getNrFlags() != len(self.flags):
			self.flags = [ FlagByte()
				       for _ in range(self.specs.getNrFlags()) ]
		if force or self.specs.getNrInputs() != len(self.inputs):
			self.inputs = [ InputByte()
					for _ in range(self.specs.getNrInputs()) ]
		if force or self.specs.getNrOutputs() != len(self.outputs):
			self.outputs = [ OutputByte()
					 for _ in range(self.specs.getNrOutputs()) ]
		CallStackElem.resetCache()

	def reset(self):
		self.dbs = {
			# User DBs
		}
		self.obs = {
			# OBs
		}
		self.fcs = {
			# User FCs
		}
		self.fbs = {
			# User FBs
		}
		self.reallocate(force=True)
		self.ar1 = Adressregister()
		self.ar2 = Adressregister()
		self.globDB = None
		self.callStack = [ ]
		self.setMcrActive(False)
		self.mcrStack = [ ]

		self.relativeJump = 1

		# Stats
		self.cycleCount = 0
		self.insnCount = 0
		self.insnCountMod = self.simplePRNG.getBits(7) + 1
		self.runtimeSec = 0.0
		self.insnPerSecond = 0.0
		self.avgInsnPerCycle = 0.0
		self.cycleStartTime = 0.0
		self.maxCycleTime = 0.0
		self.avgCycleTime = 0.0

		self.updateTimestamp()

	def setCycleExitCallback(self, cb, data=None):
		if not cb:
			cb = lambda x: None
		self.cbCycleExit = cb
		self.cbCycleExitData = data

	def setBlockExitCallback(self, cb, data=None):
		if not cb:
			cb = lambda x: None
		self.cbBlockExit = cb
		self.cbBlockExitData = data

	def setPostInsnCallback(self, cb, data=None):
		if not cb:
			cb = lambda x: None
		self.cbPostInsn = cb
		self.cbPostInsnData = data

	@property
	def is4accu(self):
		return self.accu4 is not None

	# Get the active status word
	@property
	def status(self):
		return self.callStack[-1].status

	# Get the active parenthesis stack
	@property
	def parenStack(self):
		return self.callStack[-1].parenStack

	def __runTimeCheck(self):
		if self.now - self.cycleStartTime <= self.cycleTimeLimit:
			return
		raise AwlSimError("Cycle time exceed %.3f seconds" %\
				  self.cycleTimeLimit)

	# Run one cycle of the user program
	def runCycle(self):
		self.__startCycleTimeMeasurement()
		# Initialize CPU state
		self.callStack = [ CallStackElem(self, self.obs[1], None) ]
		# Run the user program cycle
		while self.callStack:
			cse = self.callStack[-1]
			while cse.ip < len(cse.insns):
				insn = cse.insns[cse.ip]
				self.relativeJump = 1
				insn.run()
				self.cbPostInsn(self.cbPostInsnData)
				cse.ip += self.relativeJump
				cse = self.callStack[-1]
				self.insnCount += 1
				if self.insnCount % self.insnCountMod == 0:
					self.updateTimestamp()
					self.__runTimeCheck()
					self.insnCountMod = self.simplePRNG.getBits(7) + 1
			self.cbBlockExit(self.cbBlockExitData)
			self.callStack.pop().destroy()
		self.cbCycleExit(self.cbCycleExitData)
		self.cycleCount += 1
		self.__endCycleTimeMeasurement()

	def inCycle(self):
		# Return true, if we are in runCycle().
		return bool(self.callStack)

	def __startCycleTimeMeasurement(self):
		self.updateTimestamp()
		self.cycleStartTime = self.now

	def __endCycleTimeMeasurement(self):
		self.updateTimestamp()
		elapsedTime = self.now - self.cycleStartTime
		self.runtimeSec += elapsedTime
		if self.cycleCount >= 50:
			self.runtimeSec = max(self.runtimeSec, 0.00001)
			self.insnPerSecond = self.insnCount / self.runtimeSec
			self.avgInsnPerCycle = self.insnCount / self.cycleCount
			self.cycleCount, self.insnCount, self.runtimeSec =\
				0, 0, 0.0
		self.maxCycleTime = max(self.maxCycleTime, elapsedTime)
		self.avgCycleTime = (self.avgCycleTime + elapsedTime) / 2

	def getCurrentIP(self):
		try:
			return self.callStack[-1].ip
		except IndexError as e:
			return None

	def getCurrentInsn(self):
		try:
			return self.callStack[-1].insns[self.getCurrentIP()]
		except IndexError as e:
			return None

	def labelIdxToRelJump(self, labelIndex):
		cse = self.callStack[-1]
		label = cse.labels[labelIndex]
		referencedInsn = label.getInsn()
		referencedIp = referencedInsn.getIP()
		assert(referencedIp < len(cse.insns))
		return referencedIp - cse.ip

	def jumpToLabel(self, labelIndex):
		self.relativeJump = self.labelIdxToRelJump(labelIndex)

	def jumpRelative(self, insnOffset):
		self.relativeJump = insnOffset

	def run_CALL(self, blockOper, dbOper=None):
		if blockOper.type == AwlOperator.BLKREF_FC:
			if dbOper:
				raise AwlSimError("FC call must not "
					"have DB operand")
			try:
				fc = self.fcs[blockOper.offset]
			except KeyError as e:
				raise AwlSimError("Called FC not found")
			cse = CallStackElem(self, fc, self.callStack[-1].db)
		elif blockOper.type == AwlOperator.BLKREF_FB:
			if not dbOper or dbOper.type != AwlOperator.BLKREF_DB:
				raise AwlSimError("FB call must have "
					"DB operand")
			try:
				fb = self.fbs[blockOper.offset]
			except KeyError as e:
				raise AwlSimError("Called FB not found")
			try:
				db = self.dbs[dbOper.offset]
			except KeyError as e:
				raise AwlSimError("DB used in FB call not found")
			cse = CallStackElem(self, fb, db)
		elif blockOper.type == AwlOperand.BLKREF_SFC:
			#TODO
			raise AwlSimError("SFC calls not implemented, yet")
		elif blockOper.type == AwlOperand.BLKREF_SFB:
			#TODO
			raise AwlSimError("SFB calls not implemented, yet")
		else:
			raise AwlSimError("Invalid CALL operand")
		self.callStack.append(cse)

	def run_BE(self):
		s = self.status
		s.OS, s.OR, s.STA, s.NER = 0, 0, 1, 0
		# Jump beyond end of block
		cse = self.callStack[-1]
		self.relativeJump = len(cse.insns) - cse.ip

	def run_AUF(self, dbOper):
		try:
			db = self.dbs[dbOper.offset]
		except KeyError:
			raise AwlSimError("Datablock %i does not exist" %\
					  dbOper.offset)
		if dbOper.type == AwlOperator.BLKREF_DB:
			self.globDB = db
		elif dbOper.type == AwlOperator.BLKREF_DI:
			self.callStack[-1].db = db
		else:
			raise AwlSimError("Invalid DB reference in AUF")

	def run_TDB(self):
		cse = self.callStack[-1]
		# Swap global and instance DB
		cse.db, self.globDB = self.globDB, cse.db

	def updateTimestamp(self):
		self.now = time.time()

	def getStatusWord(self):
		return self.status

	def getAccu(self, index):
		if index < 1 or index > self.specs.getNrAccus():
			raise AwlSimError("Invalid ACCU offset")
		return (self.accu1, self.accu2,
			self.accu3, self.accu4)[index - 1]

	def getAR(self, index):
		if index < 1 or index > 2:
			raise AwlSimError("Invalid AR offset")
		return (self.ar1, self.ar2)[index - 1]

	def getTimer(self, index):
		try:
			return self.timers[index]
		except IndexError as e:
			raise AwlSimError("Fetched invalid timer %d" % index)

	def getCounter(self, index):
		try:
			return self.counters[index]
		except IndexError as e:
			raise AwlSimError("Fetched invalid counter %d" % index)

	def getSpecs(self):
		return self.specs

	def setMcrActive(self, active):
		self.mcrActive = active

	def mcrIsOn(self):
		if not self.mcrActive:
			return True
		if all(self.mcrStack):
			return True
		return False

	def mcrStackAppend(self, statusWord):
		self.mcrStack.append(McrStackElem(statusWord))
		if len(self.mcrStack) > 8:
			raise AwlSimError("MCR stack overflow")

	def mcrStackPop(self):
		try:
			return self.mcrStack.pop()
		except IndexError:
			raise AwlSimError("MCR stack underflow")

	def parenStackAppend(self, insnType, statusWord):
		self.parenStack.append(ParenStackElem(insnType, statusWord))
		if len(self.parenStack) > 7:
			raise AwlSimError("Parenthesis stack overflow")

	def fetch(self, operator):
		try:
			fetchMethod = self.fetchTypeMethods[operator.type]
		except KeyError:
			raise AwlSimError("Invalid fetch request")
		return fetchMethod(self, operator)

	def fetchIMM(self, operator):
		return operator.immediate

	def fetchIMM_REAL(self, operator):
		return operator.immediate

	def fetchIMM_S5T(self, operator):
		return operator.immediate

	def fetchSTW(self, operator):
		if operator.width == 1:
			return self.status.getByBitNumber(operator.bitOffset)
		elif operator.width == 16:
			return self.status.getWord()
		else:
			assert(0)

	def fetchSTW_Z(self, operator):
		return (~self.status.A0 & ~self.status.A1) & 1

	def fetchSTW_NZ(self, operator):
		return self.status.A0 | self.status.A1

	def fetchSTW_POS(self, operator):
		return (~self.status.A0 & self.status.A1) & 1

	def fetchSTW_NEG(self, operator):
		return (self.status.A0 & ~self.status.A1) & 1

	def fetchSTW_POSZ(self, operator):
		return ~self.status.A0 & 1

	def fetchSTW_NEGZ(self, operator):
		return ~self.status.A1 & 1

	def fetchSTW_UO(self, operator):
		return self.status.A0 & self.status.A1

	def __fetchFromByteArray(self, array, operator):
		width, byteOff, bitOff =\
			operator.width, operator.offset, operator.bitOffset
		try:
			if width == 1:
				return array[byteOff].getBit(bitOff)
			elif width == 8:
				assert(bitOff == 0)
				return array[byteOff].get()
			elif width == 16:
				assert(bitOff == 0)
				return (array[byteOff].get() << 8) |\
				       array[byteOff + 1].get()
			elif width == 32:
				assert(bitOff == 0)
				return (array[byteOff].get() << 24) |\
				       (array[byteOff + 1].get() << 16) |\
				       (array[byteOff + 2].get() << 8) |\
				       array[byteOff + 3].get()
		except IndexError as e:
			raise AwlSimError("fetch: Offset out of range")
		assert(0)

	def fetchE(self, operator):
		return self.__fetchFromByteArray(self.inputs, operator)

	def fetchA(self, operator):
		return self.__fetchFromByteArray(self.outputs, operator)

	def fetchM(self, operator):
		return self.__fetchFromByteArray(self.flags, operator)

	def fetchL(self, operator):
		return self.__fetchFromByteArray(self.callStack[-1].localdata,
						 operator)

	def fetchDB(self, operator):
		if not self.globDB:
			raise AwlSimError("Fetch from global DB, "
				"but no DB is opened")
		return self.globDB.fetch(operator)

	def fetchDI(self, operator):
		cse = self.callStack[-1]
		if not cse.db:
			raise AwlSimError("Fetch from instance DI, "
				"but no DI is opened")
		return cse.db.fetch(operator)

	def fetchPA(self, operator):
		pass#TODO
		return 0

	def fetchPE(self, operator):
		pass#TODO
		return 0

	def fetchT(self, operator):
		timer = self.getTimer(operator.offset)
		if operator.insn.type == AwlInsn.TYPE_L:
			return timer.getTimevalBin()
		elif operator.insn.type == AwlInsn.TYPE_LC:
			return timer.getTimevalS5T()
		return timer.get()

	def fetchZ(self, operator):
		counter = self.getCounter(operator.offset)
		if operator.insn.type == AwlInsn.TYPE_L:
			return counter.getValueBin()
		elif operator.insn.type == AwlInsn.TYPE_LC:
			return counter.getValueBCD()
		return counter.get()

	def fetchVirtACCU(self, operator):
		return self.getAccu(operator.offset).get()

	def fetchVirtAR(self, operator):
		return self.getAR(operator.offset).get()

	fetchTypeMethods = {
		AwlOperator.IMM			: fetchIMM,
		AwlOperator.IMM_REAL		: fetchIMM_REAL,
		AwlOperator.IMM_S5T		: fetchIMM_S5T,
		AwlOperator.MEM_E		: fetchE,
		AwlOperator.MEM_A		: fetchA,
		AwlOperator.MEM_M		: fetchM,
		AwlOperator.MEM_L		: fetchL,
		AwlOperator.MEM_DB		: fetchDB,
		AwlOperator.MEM_DI		: fetchDI,
		AwlOperator.MEM_T		: fetchT,
		AwlOperator.MEM_Z		: fetchZ,
		AwlOperator.MEM_PA		: fetchPA,
		AwlOperator.MEM_PE		: fetchPE,
		AwlOperator.MEM_STW		: fetchSTW,
		AwlOperator.MEM_STW_Z		: fetchSTW_Z,
		AwlOperator.MEM_STW_NZ		: fetchSTW_NZ,
		AwlOperator.MEM_STW_POS		: fetchSTW_POS,
		AwlOperator.MEM_STW_NEG		: fetchSTW_NEG,
		AwlOperator.MEM_STW_POSZ	: fetchSTW_POSZ,
		AwlOperator.MEM_STW_NEGZ	: fetchSTW_NEGZ,
		AwlOperator.MEM_STW_UO		: fetchSTW_UO,
		AwlOperator.VIRT_ACCU		: fetchVirtACCU,
		AwlOperator.VIRT_AR		: fetchVirtAR,
	}

	def store(self, operator, value):
		try:
			storeMethod = self.storeTypeMethods[operator.type]
		except KeyError:
			raise AwlSimError("Invalid store request")
		storeMethod(self, operator, value)

	def __storeToByteArray(self, array, operator, value):
		width, byteOff, bitOff =\
			operator.width, operator.offset, operator.bitOffset
		try:
			if width == 1:
				array[byteOff].setBitValue(bitOff, value)
			elif width == 8:
				assert(bitOff == 0)
				array[byteOff].set(value)
			elif width == 16:
				assert(bitOff == 0)
				array[byteOff].set(value >> 8)
				array[byteOff + 1].set(value)
			elif width == 32:
				assert(bitOff == 0)
				array[byteOff].set(value >> 24)
				array[byteOff + 1].set(value >> 16)
				array[byteOff + 2].set(value >> 8)
				array[byteOff + 3].set(value)
			else:
				assert(0)
		except IndexError as e:
			raise AwlSimError("fetch: Offset out of range")

	def storeE(self, operator, value):
		if self.inCycle():
			raise AwlSimError("Can't store to E")
		self.__storeToByteArray(self.inputs, operator, value)

	def storeA(self, operator, value):
		self.__storeToByteArray(self.outputs, operator, value)

	def storeM(self, operator, value):
		self.__storeToByteArray(self.flags, operator, value)

	def storeL(self, operator, value):
		self.__storeToByteArray(self.callStack[-1].localdata,
					operator, value)

	def storeDB(self, operator, value):
		if not self.globDB:
			raise AwlSimError("Store to global DB, "
				"but no DB is opened")
		self.globDB.store(operator, value)

	def storeDI(self, operator, value):
		cse = self.callStack[-1]
		if not cse.db:
			raise AwlSimError("Store to instance DI, "
				"but no DI is opened")
		cse.db.store(operator, value)

	def storePA(self, operator, value):
		pass #TODO

	def storePE(self, operator, value):
		pass #TODO

	def storeSTW(self, operator, value):
		if operator.width == 1:
			raise AwlSimError("Cannot store to individual STW bits")
		elif operator.width == 16:
			self.status.setWord(value)
		else:
			assert(0)

	storeTypeMethods = {
		AwlOperator.MEM_E		: storeE,
		AwlOperator.MEM_A		: storeA,
		AwlOperator.MEM_M		: storeM,
		AwlOperator.MEM_L		: storeL,
		AwlOperator.MEM_DB		: storeDB,
		AwlOperator.MEM_DI		: storeDI,
		AwlOperator.MEM_PA		: storePA,
		AwlOperator.MEM_PE		: storePE,
		AwlOperator.MEM_STW		: storeSTW,
	}

	def __dumpMem(self, prefix, memArray, maxLen):
		ret, line, first, count, i = [], [], True, 0, 0
		while i < maxLen:
			line.append(memArray[i].toHex())
			count += 1
			if count >= 16:
				if not first:
					prefix = ' ' * len(prefix)
				first = False
				ret.append(prefix + ' '.join(line))
				line, count = [], 0
			i += 1
		assert(count == 0)
		return '\n'.join(ret)

	def __repr__(self):
		if not self.callStack:
			return ""
		ret = [ "S7-CPU dump:" ]
		ret.append(" status:  " + str(self.status))
		if self.is4accu:
			accus = [ accu.toHex()
				  for accu in (self.accu1, self.accu2,
				  	       self.accu3, self.accu4) ]
		else:
			accus = [ accu.toHex()
				  for accu in (self.accu1, self.accu2) ]
		ret.append("   ACCU:  " + "  ".join(accus))
		ret.append("     AR:  " + self.ar1.toHex() + "  " +\
					  self.ar2.toHex())
		ret.append(self.__dumpMem("      M:  ",
					  self.flags,
					  min(64, self.specs.getNrFlags())))
		ret.append(self.__dumpMem("    PAE:  ",
					  self.inputs,
					  min(64, self.specs.getNrInputs())))
		ret.append(self.__dumpMem("    PAA:  ",
					  self.outputs,
					  min(64, self.specs.getNrOutputs())))
		pstack = str(self.parenStack) if self.parenStack else "Empty"
		ret.append(" PStack:  " + pstack)
		ret.append(" GlobDB:  %s" % str(self.globDB))
		if self.callStack:
			elems = [ str(cse) for cse in self.callStack ]
			elems = " => ".join(elems)
			ret.append(" CStack:  depth:%d  stack: %s" %\
				   (len(self.callStack), elems))
			cse = self.callStack[-1]
			ret.append(self.__dumpMem("      L:  ",
						  cse.localdata,
						  min(16, self.specs.getNrLocalbytes())))
			ret.append(" InstDB:  %s" % str(cse.db))
		else:
			ret.append(" CStack:  Empty")
		ret.append("  insn.:  IP:%s    %s" %\
			   (str(self.getCurrentIP()),
			    str(self.getCurrentInsn())))
		ret.append("  speed:  %d insn/s  %.01f insn/cy  "
			   "ctAvg:%.04fs  "
			   "ctMax:%.04fs" %\
			   (int(round(self.insnPerSecond)),
			    self.avgInsnPerCycle,
			    self.avgCycleTime,
			    self.maxCycleTime))
		return '\n'.join(ret)

class AwlSim(object):
	def __init__(self):
		self.cpu = S7CPU(self)

	def load(self, parseTree):
		self.cpu.load(parseTree)

	def getCPU(self):
		return self.cpu

	def runCycle(self):
		ex = None
		try:
			self.cpu.runCycle()
		except AwlSimError as e:
			ex = e
		if ex:
			raise AwlSimError("ERROR at AWL line %d: %s\n\n%s" %\
				(self.cpu.getCurrentInsn().getLineNr(),
				 str(ex), str(self.cpu)))

	def __repr__(self):
		return str(self.cpu)
bues.ch cgit interface