summaryrefslogtreecommitdiffstats
path: root/awlsim/fupcompiler/elembool.py
blob: d1edc2153f7aefb09c0202c036cd50222cb07724 (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
# -*- coding: utf-8 -*-
#
# AWL simulator - FUP compiler - Boolean element
#
# Copyright 2016-2018 Michael Buesch <m@bues.ch>
#
# 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 2 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, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#

from __future__ import division, absolute_import, print_function, unicode_literals
#from awlsim.common.cython_support cimport * #@cy
from awlsim.common.compat import *

from awlsim.fupcompiler.elem import *
from awlsim.fupcompiler.elemoper import *

from awlsim.core.operators import * #+cimport
from awlsim.core.operatortypes import * #+cimport

from awlsim.core.instructions.all_insns import * #+cimport


class FupCompiler_ElemBool(FupCompiler_Elem):
	"""FUP compiler - Boolean element.
	"""

	ELEM_NAME = "BOOL"

	EnumGen.start
	SUBTYPE_AND		= EnumGen.item
	SUBTYPE_OR		= EnumGen.item
	SUBTYPE_XOR		= EnumGen.item
	SUBTYPE_S		= EnumGen.item
	SUBTYPE_R		= EnumGen.item
	SUBTYPE_SR		= EnumGen.item
	SUBTYPE_RS		= EnumGen.item
	SUBTYPE_FP		= EnumGen.item
	SUBTYPE_FN		= EnumGen.item
	EnumGen.end

	str2subtype = {
		"and"		: SUBTYPE_AND,
		"or"		: SUBTYPE_OR,
		"xor"		: SUBTYPE_XOR,
		"s"		: SUBTYPE_S,
		"r"		: SUBTYPE_R,
		"sr"		: SUBTYPE_SR,
		"rs"		: SUBTYPE_RS,
		"fp"		: SUBTYPE_FP,
		"fn"		: SUBTYPE_FN,
	}

	@classmethod
	def parse(cls, grid, x, y, subType, content):
		try:
			subType = cls.str2subtype[subType]
			type2class = {
				cls.SUBTYPE_AND		: FupCompiler_ElemBoolAnd,
				cls.SUBTYPE_OR		: FupCompiler_ElemBoolOr,
				cls.SUBTYPE_XOR		: FupCompiler_ElemBoolXor,
				cls.SUBTYPE_S		: FupCompiler_ElemBoolS,
				cls.SUBTYPE_R		: FupCompiler_ElemBoolR,
				cls.SUBTYPE_SR		: FupCompiler_ElemBoolSR,
				cls.SUBTYPE_RS		: FupCompiler_ElemBoolRS,
				cls.SUBTYPE_FP		: FupCompiler_ElemBoolFP,
				cls.SUBTYPE_FN		: FupCompiler_ElemBoolFN,
			}
			elemClass = None
			with contextlib.suppress(KeyError):
				elemClass = type2class[subType]
			if elemClass:
				return elemClass(grid=grid,
						 x=x, y=y,
						 content=content)
		except KeyError:
			pass
		return None

	def __init__(self, grid, x, y, subType, content, **kwargs):
		FupCompiler_Elem.__init__(self, grid=grid, x=x, y=y,
					  elemType=FupCompiler_Elem.TYPE_BOOLEAN,
					  subType=subType, content=content,
					  **kwargs)

	def _getBodyOper(self):
		"""Get the body operand.
		"""
		if len(self.subElems) != 1:
			raise FupElemError("Invalid body operator in '%s'" % (
				str(self)),
				self)
		subElem = getany(self.subElems)
		if not subElem.isType(FupCompiler_Elem.TYPE_OPERAND,
				      FupCompiler_ElemOper.SUBTYPE_EMBEDDED):
			raise FupElemError("Body operator element '%s' "
				"is of invalid type." % (
				str(subElem)),
				self)
		return subElem

	def getOutConn(self):
		outConnections = list(self.outConnections)
		if len(outConnections) != 1:
			raise FupElemError("Boolean elements only support one output.", self)
		return outConnections[0]

	def _doCompileBool(self, insnClass):
		if not self.enabled:
			return []
		insns = []
		# Walk down each input connection of this element.
		nrConn = 0
		for conn in sorted(self.inConnections, key=lambda c: c.pos):
			if not conn.isConnected:
				continue
			# For each element that is connected to this element's
			# input connection via its output connection.
			otherConn = conn.getConnectedConn(getOutput=True)
			otherElem = otherConn.elem
			if otherElem.isType(self.TYPE_OPERAND,
					    FupCompiler_ElemOper.SUBTYPE_LOAD):
				# The other element is a LOAD operand.
				# Compile the boolean (load) instruction.
				# This generates:  U #oper , O #oper or something similar.
				insns.extend(otherConn.compileConn(
						targetInsnClass=insnClass,
						inverted=conn.inverted))
			elif otherElem.isType(self.TYPE_BOOLEAN):
				# The other element we get the signal from
				# is a boolean element. Compile this to get its
				# resulting VKE.
				insns.extend(otherElem.__compileToVKE(insnClass=insnClass,
								    inverted=conn.inverted))
			else:
				insnBranchClass = self.compiler.branchInsnClass[insnClass]
				insns.append(self.newInsn(insnBranchClass, parentFupConn=conn))
				insns.extend(otherConn.compileConn(targetInsnClass=insnClass,
								   inverted=conn.inverted))
				insns.append(self.newInsn(AwlInsn_BEND, parentFupConn=conn))
			nrConn += 1
		if nrConn < 1:
			raise FupElemError("The boolean element '%s' has no "
				"enabled connected inputs. At least one active input has to be "
				"connected to a boolean element." % (
				str(self)),
				self)
		outConn = self.getOutConn()
		if outConn.inverted:
			insns.append(self.newInsn(AwlInsn_NOT, parentFupConn=outConn))
		return insns

	def __compileToVKE(self, insnClass, inverted=False):
		"""Compile this boolean operation in a way that after the last
		instruction returned by this method the result of this element
		resides in the VKE.
		insnClass => The AwlInsn class used to load to VKE.
		Returns a list of AwlInsn instances.
		"""
		insns = []
		outConn = self.getOutConn()
		if self.needCompile:
			insnBranchClass = self.compiler.branchInsnClass[insnClass]
			if inverted:
				insnBranchClass = self.compiler.invertedInsnClass[insnBranchClass]
			insns.append(self.newInsn(insnBranchClass, parentFupConn=outConn))
			insns.extend(self.compile())
			# Store result to a TEMP variable, if required.
			if len(tuple(outConn.getConnectedConns(getInputs=True))) > 1:
				insns.extend(self._storeToTemp("BOOL", AwlInsn_ASSIGN,
							       { outConn,
							         self.MAIN_RESULT }))
			insns.append(self.newInsn(AwlInsn_BEND, parentFupConn=outConn))
		else:
			# Get the stored result from TEMP.
			if inverted:
				insnClass = self.compiler.invertedInsnClass[insnClass]
			insns.extend(self._loadFromTemp(insnClass, conn=outConn))
		return insns

	def compileConn(self, conn, desiredTarget, inverted=False):
		if not self.enabled:
			return []
		self._compileConn_checkTarget(conn, desiredTarget, inverted,
					      targetExpectVKE=True,
					      allowInversion=True)
		insnClass = FupCompiler_Conn.targetToInsnClass(desiredTarget,
							       toLoad=conn.dirOut,
							       inverted=inverted)
		return self.__compileToVKE(insnClass)

class FupCompiler_ElemBoolAnd(FupCompiler_ElemBool):
	"""FUP compiler - Boolean AND element.
	"""

	ELEM_NAME = "AND"

	def __init__(self, grid, x, y, content, **kwargs):
		FupCompiler_ElemBool.__init__(self, grid=grid, x=x, y=y,
					      subType=FupCompiler_ElemBool.SUBTYPE_AND,
					      content=content,
					      **kwargs)

	def _doCompile(self):
		return self._doCompileBool(AwlInsn_U)

	def connIsOptional(self, conn):
		if not self.enabled:
			return True
		if conn.dirIn:
			# All inputs are optional.
			# But at least one must be specified. That is checked in _doCompileBool().
			return True
		return False

class FupCompiler_ElemBoolOr(FupCompiler_ElemBool):
	"""FUP compiler - Boolean OR element.
	"""

	ELEM_NAME = "OR"

	def __init__(self, grid, x, y, content, **kwargs):
		FupCompiler_ElemBool.__init__(self, grid=grid, x=x, y=y,
					      subType=FupCompiler_ElemBool.SUBTYPE_OR,
					      content=content,
					      **kwargs)

	def _doCompile(self):
		return self._doCompileBool(AwlInsn_O)

	def connIsOptional(self, conn):
		if not self.enabled:
			return True
		if conn.dirIn:
			# All inputs are optional.
			# But at least one must be specified. That is checked in _doCompileBool().
			return True
		return False

class FupCompiler_ElemBoolXor(FupCompiler_ElemBool):
	"""FUP compiler - Boolean XOR element.
	"""

	ELEM_NAME = "XOR"

	def __init__(self, grid, x, y, content, **kwargs):
		FupCompiler_ElemBool.__init__(self, grid=grid, x=x, y=y,
					      subType=FupCompiler_ElemBool.SUBTYPE_XOR,
					      content=content,
					      **kwargs)

	def _doCompile(self):
		return self._doCompileBool(AwlInsn_X)

	def connIsOptional(self, conn):
		if not self.enabled:
			return True
		if conn.dirIn:
			# All inputs are optional.
			# But at least one must be specified. That is checked in _doCompileBool().
			return True
		return False

class FupCompiler_ElemBoolSR(FupCompiler_ElemBool):
	"""FUP compiler - Boolean SR element.
	"""

	ELEM_NAME	= "SR"
	SUBTYPE		= FupCompiler_ElemBool.SUBTYPE_SR
	HAVE_S		= True
	HAVE_R		= True
	HIGH_PRIO_R	= True

	def __init__(self, grid, x, y, content, **kwargs):
		FupCompiler_ElemBool.__init__(self, grid=grid, x=x, y=y,
					      subType=self.SUBTYPE,
					      content=content,
					      **kwargs)

	def __compileSR(self, bodyOper, connName, insnClass):
		conn = self.getUniqueConnByText(connName, searchInputs=True)
		if not conn or not conn.isConnected:
			return []
		otherConn = conn.getConnectedConn(getOutput=True)
		insns = otherConn.compileConn(targetInsnClass=AwlInsn_U,
					      inverted=conn.inverted)
		insns.extend(bodyOper.compileAs(insnClass))
		return insns

	def __compileS(self, bodyOper):
		if not self.HAVE_S:
			return []
		return self.__compileSR(bodyOper, "S", AwlInsn_S)

	def __compileR(self, bodyOper):
		if not self.HAVE_R:
			return []
		return self.__compileSR(bodyOper, "R", AwlInsn_R)

	@property
	def isCompileEntryPoint(self):
		if not self.enabled:
			return False
		# We are a compilation entry, if Q is not connected.
		conn = self.getUniqueConnByText("Q", searchOutputs=True)
		if not conn or not conn.isConnected:
			return True
		return False

	def _doCompile(self):
		if not self.enabled:
			return []
		insns = []

		bodyOper = self._getBodyOper()

		# Compile S and R inputs
		if self.HIGH_PRIO_R:
			insns.extend(self.__compileS(bodyOper))
			insns.extend(self.__compileR(bodyOper))
		else:
			insns.extend(self.__compileR(bodyOper))
			insns.extend(self.__compileS(bodyOper))

		# Compile Q output
		conn_Q = self.getUniqueConnByText("Q", searchOutputs=True)
		if conn_Q and conn_Q.isConnected:
			insns.extend(bodyOper.compileAs(AwlInsn_UN if conn_Q.inverted
							else AwlInsn_U))

		return insns

	def connIsOptional(self, conn):
		# R, S and Q are optional.
		return True

class FupCompiler_ElemBoolRS(FupCompiler_ElemBoolSR):
	"""FUP compiler - Boolean RS element.
	"""

	ELEM_NAME	= "RS"
	SUBTYPE		= FupCompiler_ElemBool.SUBTYPE_RS
	HAVE_S		= True
	HAVE_R		= True
	HIGH_PRIO_R	= False

class FupCompiler_ElemBoolS(FupCompiler_ElemBoolSR):
	"""FUP compiler - Boolean S element.
	"""

	ELEM_NAME	= "S"
	SUBTYPE		= FupCompiler_ElemBool.SUBTYPE_S
	HAVE_S		= True
	HAVE_R		= False
	HIGH_PRIO_R	= False

	def _doCompile(self):
		if not self.enabled:
			return []
		# Enforce connection names.
		# They might not be present in the project file.
		if len(list(self.inConnections)) == 1:
			getany(self.inConnections).text = self.ELEM_NAME
		if len(list(self.outConnections)) == 1:
			getany(self.outConnections).text = "Q"

		# Run the SR compiler
		return FupCompiler_ElemBoolSR._doCompile(self)

class FupCompiler_ElemBoolR(FupCompiler_ElemBoolS):
	"""FUP compiler - Boolean R element.
	"""

	ELEM_NAME	= "R"
	SUBTYPE		= FupCompiler_ElemBool.SUBTYPE_R
	HAVE_S		= False
	HAVE_R		= True
	HIGH_PRIO_R	= True

class FupCompiler_ElemBoolFP(FupCompiler_ElemBool):
	"""FUP compiler - Boolean FP element.
	"""

	ELEM_NAME	= "FP"
	SUBTYPE		= FupCompiler_ElemBool.SUBTYPE_FP
	POSITIVE	= True

	def __init__(self, grid, x, y, content, **kwargs):
		FupCompiler_ElemBool.__init__(self, grid=grid, x=x, y=y,
					      subType=self.SUBTYPE,
					      content=content,
					      **kwargs)

	def _doCompile(self):
		if not self.enabled:
			return []
		insns = []

		bodyOper = self._getBodyOper()

		inConns = list(self.inConnections)
		if len(inConns) != 1:
			raise FupElemError("Invalid number of input connections",
				self)
		inConn = inConns[0]

		outConns = list(self.outConnections)
		if len(outConns) != 1:
			raise FupElemError("Invalid number of output connections",
				self)
		outConn = outConns[0]

		otherConn = inConn.getConnectedConn(getOutput=True)
		insns.extend(otherConn.compileConn(targetInsnClass=AwlInsn_U,
						   inverted=inConn.inverted))
		insns.extend(bodyOper.compileAs(AwlInsn_FP if self.POSITIVE
						else AwlInsn_FN))
		if outConn.inverted:
			insns.append(self.newInsn(AwlInsn_NOT, parentFupConn=outConn))

		return insns

class FupCompiler_ElemBoolFN(FupCompiler_ElemBoolFP):
	"""FUP compiler - Boolean FN element.
	"""

	ELEM_NAME	= "FN"
	SUBTYPE		= FupCompiler_ElemBool.SUBTYPE_FN
	POSITIVE	= False
bues.ch cgit interface