aboutsummaryrefslogtreecommitdiffstats
path: root/awlsim/common/exceptions.py
blob: d814fb5c0e65aefc1b72ff02f8fc6e8023951b0a (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
# -*- coding: utf-8 -*-
#
# AWL simulator - Exceptions
#
# Copyright 2012-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.common.enumeration import *

import binascii


__all__ = [
	"AwlSimError",
	"AwlParserError",
	"AwlSimBug",
	"FrozenAwlSimError",
	"MaintenanceRequest",
	"ExitCodes",
	"suppressAllExc",
]


class AwlSimError(Exception):
	"""Main AwlSim exception.
	"""

	EXC_TYPE = "AwlSimError"

	def __init__(self, message, cpu=None,
		     rawInsn=None, insn=None, lineNr=None,
		     sourceId=None, sourceName=None):
		super(AwlSimError, self).__init__(self, message)
		self.message = message
		self.cpu = cpu
		self.rawInsn = rawInsn
		self.failingInsnStr = None
		self.insn = insn
		self.lineNr = lineNr
		self.sourceId = sourceId
		self.sourceName = sourceName
		self.seenByUser = False

	def setCpu(self, cpu):
		self.cpu = cpu

	def getCpu(self):
		return self.cpu

	def setRawInsn(self, rawInsn):
		self.rawInsn = rawInsn

	def getRawInsn(self):
		if self.rawInsn:
			return self.rawInsn
		insn = self.getInsn()
		if insn:
			rawInsn = insn.getRawInsn()
			if rawInsn:
				return rawInsn
		return None

	def setInsn(self, insn):
		self.insn = insn

	def getInsn(self):
		if self.insn:
			return self.insn
		cpu = self.getCpu()
		if cpu:
			curInsn = cpu.getCurrentInsn()
			if curInsn:
				return curInsn
		return None

	def setSourceId(self, sourceId):
		self.sourceId = sourceId

	def getSourceId(self):
		if self.sourceId is not None:
			return self.sourceId
		rawInsn = self.getRawInsn()
		if rawInsn:
			sourceId = rawInsn.getSourceId()
			if sourceId:
				return sourceId
		insn = self.getInsn()
		if insn:
			sourceId = insn.getSourceId()
			if sourceId:
				return sourceId
		cpu = self.getCpu()
		if cpu:
			curInsn = cpu.getCurrentInsn()
			if curInsn:
				sourceId = curInsn.getSourceId()
				if sourceId:
					return sourceId
		return None

	def setSourceName(self, sourceName):
		self.sourceName = sourceName

	def getSourceName(self):
		return self.sourceName

	def setLineNr(self, lineNr):
		self.lineNr = lineNr

	# Try to get the AWL-code line number where the
	# exception occurred. Returns None on failure.
	def getLineNr(self):
		if self.lineNr is not None:
			return self.lineNr
		rawInsn = self.getRawInsn()
		if rawInsn:
			lineNr = rawInsn.getLineNr()
			if lineNr is not None:
				return lineNr
		insn = self.getInsn()
		if insn:
			lineNr = insn.getLineNr()
			if lineNr is not None:
				return lineNr
		cpu = self.getCpu()
		if cpu:
			curInsn = cpu.getCurrentInsn()
			if curInsn:
				lineNr = curInsn.getLineNr()
				if lineNr is not None:
					return lineNr
		return None

	def getLineNrStr(self, errorStr="<unknown>"):
		lineNr = self.getLineNr()
		if lineNr is not None:
			return "%d" % lineNr
		return errorStr

	def setFailingInsnStr(self, string):
		self.failingInsnStr = string

	def getFailingInsnStr(self, errorStr=""):
		if self.failingInsnStr is not None:
			return self.failingInsnStr
		rawInsn = self.getRawInsn()
		if rawInsn:
			return str(rawInsn)
		insn = self.getInsn()
		if insn:
			return str(insn)
		cpu = self.getCpu()
		if cpu:
			curInsn = cpu.getCurrentInsn()
			if curInsn:
				return str(curInsn)
		return errorStr

	def doGetReport(self, title, verbose=True):
		ret = [ "%s:\n\n" % title ]

		# Format the source file name.
		sourceName = self.getSourceName()
		sourceId = self.getSourceId()
		fileStr = ""
		if sourceName or sourceId:
			fileStr = "\n  in source"
		if sourceName:
			fileStr += " '%s'" % sourceName
		if sourceId:
			identHashHex = binascii.hexlify(sourceId)
			identHashStr = identHashHex.decode("UTF-8", "ignore")
			fileStr += "\n  with source hash '%s...'" % identHashStr[:10]

		# Format the line string.
		lineStr = ""
		lineNr = self.getLineNr()
		if lineNr is not None:
			lineStr = "\n  at line %d" % lineNr

		# Append file and line information to report.
		if fileStr or lineStr:
			ret.append("Error%s%s:\n\n" % (fileStr, lineStr))

		# Append instruction information to report.
		insnStr = self.getFailingInsnStr()
		if insnStr:
			ret.append("  %s\n" % insnStr)

		# Append the actual error message to the report.
		ret.append("\n  %s\n" % self.message)

		# Append a CPU dump, if verbose.
		if verbose:
			cpu = self.getCpu()
			if cpu:
				ret.append("\n%s\n" % str(cpu))

		return "".join(ret)

	def getReport(self, verbose=True):
		return self.doGetReport("Awlsim error", verbose)

	def getSeenByUser(self):
		return self.seenByUser

	def setSeenByUser(self, seen=True):
		self.seenByUser = seen

	def __repr__(self):
		return self.getReport()

	__str__ = __repr__

class AwlParserError(AwlSimError):
	"""Parser specific exception.
	"""

	EXC_TYPE = "AwlParserError"

	def __init__(self, message, lineNr=None):
		AwlSimError.__init__(self,
				     message = message,
				     lineNr = lineNr)

	def getReport(self, verbose=True):
		return self.doGetReport("AWL parser error", verbose)

class AwlSimBug(AwlSimError): #@nocov
	"""AwlSim bug exception.
	This will be raised in situations that represent an actual code bug.
	"""

	EXC_TYPE = "AwlSimBug"

	def __init__(self, message, *args, **kwargs):
		message = "AWLSIM BUG: %s\n"\
			"This bug should be reported to the awlsim developers." %\
			str(message)
		AwlSimError.__init__(self, message, *args, **kwargs)

class FrozenAwlSimError(AwlSimError):
	"""A frozen AwlSim exception.
	The report will be frozen and not be generated from scratch.
	"""

	EXC_TYPE = "FrozenAwlSimError"

	def __init__(self, excType, errorText, verboseErrorText=None):
		AwlSimError.__init__(self, message = errorText)
		self.EXC_TYPE = excType
		self.verboseErrorText = verboseErrorText or errorText

	def getReport(self, verbose=True):
		if verbose:
			return self.verboseErrorText
		return self.message

class MaintenanceRequest(Exception):
	EnumGen.start
	# Soft-reboot request, handled by the simulator core.
	# On soft-reboot, the upstart-OBs are executed.
	# Memory is not cleared.
	TYPE_SOFTREBOOT		= EnumGen.item
	# Regular-shutdown request, handled by toplevel simulator.
	# This exception is handed up to the toplevel loop.
	TYPE_SHUTDOWN		= EnumGen.item
	# CPU-STOP request, handled by toplevel simulator.
	# This exception is handed up to the toplevel loop.
	TYPE_STOP		= EnumGen.item
	# CPU-STOP due to runtime timeout.
	# This exception is handed up to the toplevel loop.
	TYPE_RTTIMEOUT		= EnumGen.item
	EnumGen.end

	def __init__(self, requestType, message=""):
		super(MaintenanceRequest, self).__init__(self, message)
		self.requestType = requestType
		self.message = message

	def __repr__(self):
		return self.message

class ExitCodes(object):
	"""Awlsim program exit codes."""

	EnumGen.start
	# Success.
	EXIT_OK			= EnumGen.itemAt(0)
	# Command line option error.
	EXIT_ERR_CMDLINE	= EnumGen.itemAt(10)
	# Python interpreter error.
	EXIT_ERR_INTERP		= EnumGen.itemAt(20)
	# AwlSimError.
	EXIT_ERR_SIM		= EnumGen.itemAt(30)
	# I/O error.
	EXIT_ERR_IO		= EnumGen.itemAt(40)
	# Other error.
	EXIT_ERR_OTHER		= EnumGen.itemAt(100)
	EnumGen.end

class __suppressAllExc(object):
	"""Context manager to suppress almost all exceptions.
	Only really fatal coding exceptions will be re-raised.
	The usage is similar to that of contextlib.suppress().
	"""

	import re as _re

	def __enter__(self):
		pass

	def __exit__(self, exctype, excinst, exctb): #@nocov
		if exctype is None:
			return False # no exception
		if issubclass(exctype, (SyntaxError, NameError, AttributeError)):
			return False # raise fatal exception
		if issubclass(exctype, ValueError):
			re, text = self._re, str(excinst)
			if re.match(r'.*takes exactly \d+ argument \(\d+ given\).*', text) or\
			   re.match(r'.*missing \d+ required positional argument.*', text) or\
			   re.match(r'.*takes \d+ positional argument but \d+ were given.*', text):
				return False # raise fatal exception
		return True # suppress exception
suppressAllExc = __suppressAllExc()
bues.ch cgit interface