bool_m.html
001| '''BOOL Macro Compiler.
001|
001| This file implements a BOOL/M compiler that reads source files and generates BOOL run-time objects.
001|
001| classes:
001| BoolMacroParser (Properties)
001| BoolMacroBuilder (object)
001|
001| Function (object)
001|
001| BoolObject (object) - BOOL build object base class
001| BoolListObject (BoolObject) - List object
001| BoolMessageObject (BoolObject) - Message object
001| BoolInstanceObject (BoolObject) - Instance object
001| BoolReferenceObject (BoolObject) - Reference object
001| BoolActionObject (BoolObject) - Action object
001| BoolActorObject (BoolObject) - Actor object
001| BoolModelObject (BoolObject) - Model object
001|
001| functions:
001| dump_action(action, log=Log)
001| dump_model(model, log=Log)
001|
001| Developer@Sonnack.com
001| February 2014
001| '''
002|
003| from sys import stdout, stderr, argv
004| from os import path
005| from datetime import datetime
006| from logger import logger, info, debug, trace
007| from lexer import SourceFile, Lexer
008| from goodies import reduce
009| from bool_obj import *
010|
011| Log = logger('BOOL/M')
012|
013|
014| class Function (object):
015| '''.'''
016| def argslist (self):
017| return reduce(lambda acc,x: acc+(',' if len(acc) else '')+str(x), self.args, '')
018|
019| def __call__ (self):
020| return (self.name, self.args)
021|
022| def __cmp__ (self, other):
023| return cmp(self.name, other.name) or cmp(self.args, other.args)
024|
025| def __str__ (self):
026| s = '%s(%s)'
027| t = (self.name, self.argslist())
028| return s % t
029|
030| def __repr__ (self):
031| '''JSON-Like String.'''
032| s = '{Function:{name:"%s", args:"%s", id:%s}}'
033| t = (self.name, self.argslist(), hex(id(self)))
034| return s % t
035|
036| def __init__ (self, name, args=[]):
037| self.name = name
038| self.args = args
039|
040|
041|
042|
043| class BoolMacroParser (object):
044| '''Parser for BOOL-M (Hand-Compiled Macro) Source Code.'''
045| Log = logger('Parser')
046|
047| def _get_tok (self):
048| '''Get Token wedge to allow logging of each Token.'''
049| tok = self.lex.get_token()
050| self.curr_line = tok[4]
051| self.curr_char = tok[5]
052| self.Log.trace("token: '%s'" % str(tok))
053| return tok
054|
055| def _unget_tok (self, tok):
056| '''Unget Character.'''
057| self.lex.unget_token(tok)
058|
059| def _parse_file (self):
060| '''Parse File. The Big Kahuna. Call this to kick off a parse.'''
061| tok = self._get_tok()
062| while tok:
063|
064| if tok[0] == Lexer.NewlineToken:
065| tok = self._get_tok()
066| continue
067|
068| if tok[0] not in [Lexer.NameToken, Lexer.StringToken]:
069| raise SyntaxError('Expected an Object Name. [%s]' % str(tok))
070| obj_name = tok[1]
071|
072| tok = self._get_tok()
073| if (tok[0] != Lexer.SymbolToken) or (tok[1] != ':'):
074| raise SyntaxError('Expected a colon after the name! [%s]' % str(tok))
075|
076| tok = self._get_tok()
077| if tok[0] not in [Lexer.NameToken, Lexer.StringToken]:
078| raise SyntaxError('Expected a Command. [%s]' % str(tok))
079| obj_command = tok[1]
080|
081| items = self._get_item_list()
082|
083| attributes = self._get_attr_list()
084|
085| t = (obj_name, obj_command, items, attributes, self.curr_line, self.curr_char)
086| self.aout.append(t)
087|
088| tok = self._get_tok()
089|
090|
091| def _get_item_list (self):
092| '''Get a comma-delimited item list of zero or more items.'''
093| self.Log.trace("_get_item_list:")
094| items = []
095| tok = self._get_tok()
096| while tok:
097| if tok[0] == Lexer.NewlineToken:
098| self._unget_tok(tok)
099| break
100|
101| item = self._get_name_value_or_func(tok)
102|
103| tok = self._get_tok()
104| if tok[1] == '=':
105| self._last_item = item
106| break
107| items.append(item)
108| if tok[1] == ',':
109| tok = self._get_tok()
110| continue
111|
112| return items
113|
114| def _get_attr_list (self):
115| '''Get a comma-delimited attribute (name=value) list of zero or more attributes.'''
116| self.Log.trace("_get_attr_list:")
117| attributes = {}
118|
119| if self._last_item:
120| attr_nam = self._last_item
121|
122| attr_val = self._get_name_value_or_func(self._get_tok())
123|
124| attributes[attr_nam] = attr_val
125| self._last_item = None
126|
127| tok = self._get_tok()
128| while tok[0] != Lexer.NewlineToken:
129|
130| if tok[1] == ',':
131| tok = self._get_tok()
132| continue
133| if tok[0] not in [Lexer.NameToken, Lexer.StringToken]:
134| raise SyntaxError('Expected an Attribute Name. [%s]' % str(tok))
135| attr_nam = tok[1]
136|
137| tok = self._get_tok()
138| if (tok[0] != Lexer.SymbolToken) or (tok[1] != '='):
139| raise SyntaxError('Expected an equals sign after the name! [%s]' % str(tok))
140|
141| attr_val = self._get_name_value_or_func(self._get_tok())
142|
143| attributes[attr_nam] = attr_val
144|
145| tok = self._get_tok()
146|
147| return attributes
148|
149| def _get_name_value_or_func (self, tok):
150| '''Resolve a single Token's type (literal, name, function) and return it.'''
151| self.Log.trace("_get_name_value_or_func: '%s'" % str(tok))
152|
153| if tok[0] == Lexer.NewlineToken:
154| raise SyntaxError(('Unexpected end of line!'))
155|
156| if tok[0] in [Lexer.BooleanToken, Lexer.NumberToken, Lexer.StringToken, Lexer.DateToken]:
157| return tok[2]
158| if tok[0] != Lexer.NameToken:
159| raise SyntaxError('Expected an Item Name. [%s]' % str(tok))
160| item_name = tok[1]
161|
162| tok = self._get_tok()
163| if tok[1] != '(':
164|
165| self._unget_tok(tok)
166| return item_name
167|
168| args = []
169| tok = self._get_tok()
170| while tok[1] != ')':
171| if tok[0] == Lexer.NewlineToken:
172| raise SyntaxError('Expected a Value. [%s]' % str(tok))
173|
174| if tok[0] in [Lexer.BooleanToken, Lexer.NumberToken, Lexer.DateToken]:
175| arg = tok[2]
176| else:
177| arg = tok[1]
178|
179| args.append(arg)
180|
181| tok = self._get_tok()
182| if tok[1] not in [',', ')']:
183| raise SyntaxError('Bad Function Argument List. [%s]' % str(tok))
184| if tok[1] == ',':
185| tok = self._get_tok()
186|
187| return Function(item_name, args)
188|
189| def __getitem__ (self, ix):
190| '''Return a given output item.'''
191| return self.aout[ix]
192|
193| def __iter__ (self):
194| '''Iterating a Parser iterates its output.'''
195| return iter(self.aout)
196|
197| def __cmp__ (self, other):
198| '''Compare Parsers by comparing their outputs.'''
199| return cmp(self.aout, other.aout)
200|
201| def __bool__ (self):
202| '''Parser is "true" when it has some output.'''
203| return (0 < len(self))
204|
205| def __len__ (self):
206| return len(self.aout)
207|
208| def __str__ (self):
209| '''String version.'''
210| return str(self.src)
211|
212| def __repr__ (self):
213| '''JSON-ish version.'''
214| s = '{BoolMacroParser:{len:%d, lex:%s, id:%s}}'
215| t = (len(self), repr(self.lex), hex(id(self)))
216| return s % t
217|
218| def __init__ (self, filename):
219| '''Create a new BOOL-M Parser instance.'''
220| self.aout = []
221| self.curr_char = 0
222| self.curr_line = 0
223| self.src = SourceFile(filename)
224| self.lex = Lexer(self.src)
225| if '$' in self.lex.sym_chars:
226| self.lex.sym_chars.remove('$')
227| self._last_item = None
228|
229| self.Log.trace('Parser: BEGIN')
230| try:
231| self._parse_file()
232| except IndexError:
233| o1 = 'Parser: EOF'
234| self.Log.trace(o1)
235| print(o1, file=stdout)
236| except SyntaxError as e:
237| e1 = Properties.E1
238| e2 = Properties.E2 % str(e)
239| e3 = Properties.E3 % self.src.filename
240| e4 = Properties.E4 % (self.src.lines, self.src.cp, self.src.chars)
241| self.Log.error(e1)
242| self.Log.error(e2)
243| self.Log.error(e3)
244| self.Log.error(e4)
245| print(e1, file=stderr)
246| print(e2, file=stderr)
247| print(e3, file=stderr)
248| print(e4, file=stderr)
249| Log.trace('Parser: END')
250|
251|
252|
253|
254|
255| class BoolObject (object):
256| '''Bool Object base class.'''
257|
258| def getObject (self):
259| return BoolTuple(self.metatype, self.properties)
260|
261| def __str__ (self):
262| s = '{%s id=%s}'
263| t = (self.metatype, hex(id(self)))
264| return s % t
265|
266| def __init__ (self, metatype, properties=None):
267| self.metatype = metatype
268| self.properties = properties if properties else []
269|
270|
271| class BoolListObject (BoolObject):
272| '''Bool List Object class.'''
273|
274| def getObject (self):
275| list_items = (['?']+self.items) if self.has_gate else self.items
276| if self.has_gate:
277| self.properties.insert(0, ('tag','gated'))
278| return BoolList(len(self.items), list_items, self.properties)
279|
280| def set_list_gate (self, obj):
281| self.has_gate = True
282| self.add_to_items(obj)
283|
284| def add_to_items (self, obj):
285| self.items.append(obj)
286|
287| def __len__ (self):
288| return len(self.items)
289|
290| def __str__ (self):
291| s = '{%s len=%d gated=%s}'
292| t = (self.metatype, self.items, self.has_gate)
293| return s % t
294|
295| def __init__ (self, items=None, properties=None):
296| super(BoolListObject,self).__init__(BoolDefs.LST, properties)
297| self.items = items if items else []
298| self.has_gate = False
299|
300|
301| class BoolMessageObject (BoolObject):
302| '''Bool Message Object class.'''
303|
304| def getObject (self):
305| return BoolMessage(self.name, self.target, self.params, self.properties)
306|
307| def set_target (self, obj):
308| self.target = obj
309|
310| def add_to_params (self, obj):
311| self.params.append(obj)
312|
313| def __str__ (self):
314| p = reduce(lambda acc,s: acc+str(s), self.params, '')
315| s = '{%s "%s" target=%s params=%s}'
316| t = (self.metatype, self.name, self.target, p)
317| return s % t
318|
319| def __init__ (self, name, target=None, params=None, properties=None):
320| super(BoolMessageObject,self).__init__(BoolDefs.MSG, properties)
321| self.name = name
322| self.target = target
323| self.params = params if params else []
324|
325|
326| class BoolInstanceObject (BoolObject):
327| '''Bool Instance Object class.'''
328|
329| def getObject (self):
330| self.properties.insert(0, ('name',self.name))
331| return BoolInstance(self.model, self.ds, self.inits, self.properties)
332|
333| def set_initlist (self, obj):
334| self.inits = obj
335|
336| def __str__ (self):
337| s = '{%s "%s" model=%s ds=%s init=%s}'
338| t = (self.metatype, self.name, self.model, self.ds, str(self.inits))
339| return s % t
340|
341| def __init__ (self, name, model, ds, inits=None, properties=None):
342| super(BoolInstanceObject,self).__init__(BoolDefs.OBJ, properties)
343| self.name = name
344| self.model = model
345| self.ds = ds
346| self.inits = inits
347|
348|
349| class BoolReferenceObject (BoolObject):
350| '''Bool Reference Object class.'''
351|
352| def getObject (self):
353| self.properties.insert(0, ('name',self.name))
354| return BoolReference(self.model, self.ds, self.properties)
355|
356| def __str__ (self):
357| s = '{%s "%s" model=%s ds=%s}'
358| t = (self.metatype, self.name, self.model, self.ds)
359| return s % t
360|
361| def __init__ (self, name, model, ds, properties=None):
362| super(BoolReferenceObject,self).__init__(BoolDefs.REF, properties)
363| self.name = name
364| self.model = model
365| self.ds = ds
366|
367|
368| class BoolActionObject (BoolObject):
369| '''Bool Action Object class.'''
370|
371| def getObject (self):
372| return BoolAction(self.name, self.initlist, self.exitlist, self.clauses, self.codeblock, self.datablock, self.nametable, self.properties)
373|
374| def add_to_initlist (self, obj):
375| self.initlist.append(obj)
376|
377| def add_to_exitlist (self, obj):
378| self.exitlist.append(obj)
379|
380| def add_to_clauses (self, name, tags=None):
381| clause = [name, 0, None]
382| if tags:
383| clause.extend(tags)
384| self.clauses.append(clause)
385|
386| def add_to_codeblock (self, obj):
387| addr = BoolAddress(self.name, len(self.codeblock))
388| self.codeblock.append(obj)
389| return addr
390|
391| def add_to_datablock (self, datum):
392| ds = len(self.datablock)
393| self.datablock.append(datum)
394| return ds
395|
396| def add_to_nametable (self, name, model, addr):
397| self.nametable[name] = (model, (self.name, addr))
398|
399| def __str__ (self):
400| s = '{%s "%s" init=%d exit=%d clauses=%d cs=%d ds=%d}'
401| t = (self.metatype, self.name, len(self.initlist), len(self.exitlist), len(self.clauses), len(self.codeblock), len(self.datablock))
402| return s % t
403|
404| def __init__ (self, name, properties=None):
405| super(BoolActionObject,self).__init__(BoolDefs.ACT, properties)
406| self.name = name
407| self.initlist = []
408| self.exitlist = []
409| self.clauses = []
410| self.codeblock = []
411| self.datablock = []
412| self.nametable = {}
413|
414|
415| class BoolActorObject (BoolObject):
416| '''Bool Actor Object class.'''
417|
418| def getObject (self):
419| return BoolActor(self.name, self.params, self.properties)
420|
421| def add_to_params (self, obj):
422| self.params.append(obj)
423|
424| def __str__ (self):
425| s = '{%s "%s" params=%d}'
426| t = (self.metatype, self.name, len(self.params))
427| return s % t
428|
429| def __init__ (self, name, params=None, properties=None):
430| super(BoolActorObject,self).__init__(BoolDefs.TOR, properties)
431| self.name = name
432| self.params = params if params else [[name]]
433|
434|
435| class BoolModelObject (BoolObject):
436| '''Bool Model Object class.'''
437|
438| def getObject (self):
439| return BoolModel(self.name, self.template, self.actions, self.nametable, self.properties)
440|
441| def add_to_template (self, obj):
442| self.template.append(obj)
443|
444| def add_to_actions (self, obj):
445| addr = len(self.actions)
446| self.actions.append(obj)
447| self.add_to_nametable(obj.name, obj.metatype, addr)
448|
449| def add_to_nametable (self, name, model, addr):
450| self.nametable[name] = (model, (self.name, addr))
451|
452| def __str__ (self):
453| s = '{%s "%s" template=%d actions=%d}'
454| t = (self.metatype, self.name, len(self.template), len(self.actions))
455| return s % t
456|
457| def __init__ (self, name, properties=None):
458| super(BoolModelObject,self).__init__(BoolDefs.MOD, properties)
459| self.name = name
460| self.template = []
461| self.actions = []
462| self.nametable = {}
463|
464|
465|
466|
467|
468| class BoolMacroBuilder (object):
469| '''Build BOOL Python (Level 3) from BOOLM macro language.
469| PARSER:
469| START - initialize all Builder objects
469| END - end of Builder code
469| NameSpace:
469| INSERT - create new entry, fail if exists
469| Action:
469| CREATE - begin a new Action
469| NAMETABLE - insert new name:address, fail if exists
469| INITLIST - insert new address, fail if exists
469| EXITLIST - insert new address, fail if exists
469| CLAUSE - create new clause entry, fail if exists
469| PARAM - bump clause parameters counter
469| EXECLIST - attach execute list to clause
469| EMIT - emit current Action object
469| Actor:
469| CREATE - begin new Actor object
469| PARAM - append to current Actor Clause
469| CLAUSE - start a new Actor Clause
469| EMIT - emit current Actor object
469| Label:
469| CREATE - create new Label object
469| List:
469| CREATE - begin new List object
469| GATE - set current List Gate Object
469| APPEND - append to current List object
469| EMIT - emit current List object
469| Message:
469| CREATE - begin new Message object
469| TARGET - set current Message Target
469| PARAM - append to current Message Params
469| EMIT - emit current Message object
469| Object:
469| CREATE - begin new Object object
469| INITLIST - set current Object Initlist
469| EMIT - emit current Object object
469| Reference:
469| CREATE - begin new Reference object
469| EMIT - emit current List object
469| '''
470| LST = 'LST'
471| MSG = 'MSG'
472| OBJ = 'OBJ'
473| REF = 'REF'
474| ACT = 'ACT'
475| TOR = 'TOR'
476| MOD = 'MOD'
477|
478| E_BUILD_1 = "Builder: ERROR *** Oh, No!! There's an Error! ***"
479| E_BUILD_2 = "Err: %s"
480| E_BUILD_3 = "File: %s"
481| E_BUILD_4 = "Line: %d, Char: %d"
482| E_UNKNOWN = 'Unknown Agent Command: "%s"'
483| E_BLD_EMP = 'Build stack is empty.'
484| E_BLD_OBJ = 'Build Stack has wrong object type. Expected: %s; Got: %s'
485| E_CLAUSE = 'Current Actor Clause not a match for parameter. Expected: %s, Got:%s'
486| E_NOCLAUSE = 'No such Action Clause: "%s"'
487| E_UNKFUNCT = 'Unknown Function: "%s"'
488|
489| Log = logger('Builder')
490|
491| def build (self, parser):
492| '''Build!'''
493| self.parser = parser
494|
495| for tok in self.parser:
496| self.Log.trace('Token: %s' % str(tok))
497|
498| agent_name = tok[0]
499| command = tok[1].upper()
500| if agent_name not in self.agents:
501| raise NameError('No such Agent: "%s"' % agent_name)
502| agent = self.agents[agent_name]
503| if not agent:
504| self.Log.error('No Agent Function for "%s"' % agent_name)
505| continue
506| try:
507| agent(command, tok[2], tok[3])
508| except Exception as e:
509| e1 = BoolMacroBuilder.E_BUILD_1
510| e2 = BoolMacroBuilder.E_BUILD_2 % str(e)
511| e3 = BoolMacroBuilder.E_BUILD_3 % self.parser.src.filename
512| e4 = BoolMacroBuilder.E_BUILD_4 % (tok[4], tok[5])
513| self.Log.error(e1)
514| self.Log.error(e2)
515| self.Log.error(e3)
516| self.Log.error(e4)
517| print(e1, file=stderr)
518| print(e2, file=stderr)
519| print(e3, file=stderr)
520| print(e4, file=stderr)
521| print(file=stderr)
522| raise
523|
524| def agent_Parser (self, command, args, params):
525| '''END, RESET, START.'''
526| self.Log.trace('Parser: %s' % command)
527|
528| def agent_NameSpace (self, command, args, params):
529| '''INSERT.'''
530| self.Log.trace('NameSpace: %s' % command)
531| if command == 'INSERT':
532| obj_addr = self.expand_value(args[2])
533| self.m.act_global.add_name_to_nametable(args[0], args[1], obj_addr)
534| return
535|
536| raise RuntimeError(self.E_UNKNOWN % command)
537|
538| def agent_Model (self, command, args, params):
539| '''Model Object builder.'''
540| self.Log.trace('Model: %s %s %s' % (command, str(args), str(params)))
541| if command == 'CREATE':
542| self.curr_model = BoolModelObject(args[0])
543| return
544|
545| if not self.curr_model:
546| raise RuntimeError(self.E_BLD_EMP)
547| if command == 'TEMPLATE':
548| obj_addr = self.expand_value(args[0])
549| self.curr_model.add_to_template(obj_addr)
550| return
551| if command == 'ACTION':
552| obj_name = args[0]
553|
554|
555|
556| return
557| if command == 'NAMETABLE':
558| obj_addr = self.expand_value(args[2])
559| self.curr_model.add_to_nametable(args[0], args[1], obj_addr)
560| return
561| if command == 'EMIT':
562| mod = self.curr_model.getObject()
563| self.curr_model = None
564| self.last_address = self.m.act_global.add_object_to_codeblock(mod)
565| self.m.models[mod.name] = self.last_address
566| return
567|
568| raise RuntimeError(self.E_UNKNOWN % command)
569|
570| def agent_Action (self, command, args, params):
571| '''CREATE,...EMIT.'''
572| self.Log.trace('Action: %s %s %s' % (command, str(args), str(params)))
573|
574| if command == 'CREATE':
575| self.curr_action = BoolActionObject(args[0])
576| return
577|
578| if not self.curr_action:
579| raise RuntimeError(self.E_BLD_EMP)
580| if command == 'INITLIST':
581| obj_addr = self.expand_value(args[0])
582| self.curr_action.add_to_initlist(obj_addr)
583| return
584| if command == 'EXITLIST':
585| obj_addr = self.expand_value(args[0])
586| self.curr_action.add_to_exitlist(obj_addr)
587| return
588| if command == 'CLAUSE':
589| tags = None
590| if 'flags' in params:
591| flags = params['flags'].split('/')
592| tags = [('tag',s) for s in flags]
593| self.curr_action.add_to_clauses(args[0], tags)
594| return
595| if command == 'PARAM':
596| obj_name = args[0]
597| for clause in self.curr_action.clauses:
598| if clause[0] == obj_name:
599| clause[1] += 1
600| return
601| raise RuntimeError(self.E_NOCLAUSE % obj_name)
602| if command == 'EXECLIST':
603| obj_name = args[0]
604| obj_addr = self.expand_value(args[1])
605| for clause in self.curr_action.clauses:
606| if clause[0] == obj_name:
607| clause[2] = obj_addr
608| return
609| raise RuntimeError(self.E_NOCLAUSE % obj_name)
610| if command == 'NAMETABLE':
611| obj_addr = self.expand_value(args[2])
612| self.curr_action.add_to_nametable(args[0], args[1], obj_addr)
613| return
614| if command == 'EMIT':
615| act = self.curr_action.getObject()
616| self.curr_action = None
617|
618| if self.curr_model:
619|
620| self.curr_model.add_to_actions(act)
621| return
622|
623| self.last_address = self.m.act_global.add_object_to_codeblock(act)
624| self.m.actions[act.name] = self.last_address
625| return
626|
627| raise RuntimeError(self.E_UNKNOWN % command)
628|
629| def agent_Actor (self, command, args, params):
630| '''CREATE,PARAM,CLAUSE,EMIT.'''
631| self.Log.trace('Actor: %s %s %s' % (command, str(args), str(params)))
632| if command == 'CREATE':
633| name = args[0]
634|
635| obj = BoolActorObject(name)
636| self.build_stack.append(obj)
637| return
638| if command == 'PARAM':
639| obj = self.get_build_object(self.TOR)
640| clause = obj.params.pop()
641| if clause[0] != params['clause']:
642| raise RuntimeError(self.E_CLAUSE % (params['clause'], clause[0]))
643| addr = self.expand_value(args[0])
644| clause.append(addr)
645| obj.params.append(clause)
646| return
647| if command == 'CLAUSE':
648| addr = self.expand_value(args[0])
649| clause = [addr]
650| obj = self.get_build_object(self.TOR)
651| obj.params.append(clause)
652| return
653| if command == 'EMIT':
654| self.emit_build_object(self.TOR)
655| return
656|
657| raise RuntimeError(self.E_UNKNOWN % command)
658|
659| def agent_List (self, command, args, params):
660| '''CREATE,GATE,APPEND,EMIT.'''
661| self.Log.trace('List: %s %s %s' % (command, str(args), str(params)))
662| if command == 'CREATE':
663|
664| obj = BoolListObject()
665| self.build_stack.append(obj)
666| return
667| if command == 'GATE':
668| addr = self.expand_value(args[0])
669| obj = self.get_build_object(self.LST)
670| obj.set_list_gate(addr)
671| return
672| if command == 'APPEND':
673| addr = self.expand_value(args[0])
674| obj = self.get_build_object(self.LST)
675| obj.add_to_items(addr)
676| return
677| if command == 'EMIT':
678| self.emit_build_object(self.LST)
679| return
680|
681| raise RuntimeError(self.E_UNKNOWN % command)
682|
683| def agent_Message (self, command, args, params):
684| '''CREATE,TARGET,PARAM,EMIT.'''
685| self.Log.trace('Message: %s %s %s' % (command, str(args), str(params)))
686| if command == 'CREATE':
687|
688| obj = BoolMessageObject(args[0])
689| self.build_stack.append(obj)
690| return
691| if command == 'TARGET':
692| addr = self.expand_value(args[0])
693| obj = self.get_build_object(self.MSG)
694| obj.set_target(addr)
695| return
696| if command == 'PARAM':
697| addr = self.expand_value(args[0])
698| obj = self.get_build_object(self.MSG)
699| obj.add_to_params(addr)
700| return
701| if command == 'EMIT':
702| self.emit_build_object(self.MSG)
703| return
704|
705| raise RuntimeError(self.E_UNKNOWN % command)
706|
707| def agent_Object (self, command, args, params):
708| '''CREATE,INITLIST,EMIT.'''
709| self.Log.trace('Instance: %s %s %s' % (command, str(args), str(params)))
710| if command == 'CREATE':
711| if self.curr_action:
712| ds = self.curr_action.add_to_datablock(None)
713| else:
714| ds = self.m.act_global.allocate_data_slot(None)
715|
716| obj = BoolInstanceObject(args[0], args[1], ds)
717| self.build_stack.append(obj)
718| return
719| if command == 'INITLIST':
720| addr = self.expand_value(args[0])
721| obj = self.get_build_object(self.OBJ)
722| obj.set_initlist(addr)
723| return
724| if command == 'EMIT':
725| self.emit_build_object(self.OBJ)
726| return
727|
728| raise RuntimeError(self.E_UNKNOWN % command)
729|
730| def agent_Reference (self, command, args, params):
731| '''CREATE,EMIT.'''
732| self.Log.trace('Reference: %s %s %s' % (command, str(args), str(params)))
733| if command == 'CREATE':
734| ds = self.curr_action.add_to_datablock(None)
735|
736| obj = BoolReferenceObject(args[0], args[1], ds)
737| self.build_stack.append(obj)
738| return
739| if command == 'EMIT':
740| self.emit_build_object(self.REF)
741| return
742|
743| raise RuntimeError(self.E_UNKNOWN % command)
744|
745| def agent_Label (self, command, args, params):
746| '''CREATE.'''
747| self.Log.trace('Label: %s %s %s' % (command, str(args), str(params)))
748| return
749|
750| def expand_value (self, value):
751| '''Resolve Functions from plain names.'''
752| if isinstance(value, Function):
753| return self.expand_Function(value)
754| return value
755|
756| def expand_Function (self, funct):
757| '''Implement various Functions.'''
758|
759|
760|
761| if funct.name == 'lastaddr':
762| return self.last_address
763| if funct.name == 'self':
764| return ('special','self')
765|
766| if funct.name == 'constant':
767| nbr = funct.args[0]
768| nbr_name = str(nbr)
769| if nbr_name in self.m.constants:
770| return self.m.constants[nbr_name]
771| if isinstance(nbr, bool):
772| return self.m.add_constant_instance(nbr_name, 'bool', nbr)
773| if isinstance(nbr, int) or isinstance(nbr, int):
774| return self.m.add_constant_instance(nbr_name, 'int', int(nbr))
775| if isinstance(nbr, float):
776| return self.m.add_constant_instance(nbr_name, 'float', nbr)
777| raise TypeError('Unknown constant data type: "%s"' % nbr_name)
778|
779| if funct.name == 'constant$':
780| s = funct.args[0]
781| s_key = self.m.get_string_key(s)
782| if s_key in self.m.constants:
783| return self.m.constants[s_key]
784| return self.m.add_constant_string_instance(s_key, s)
785|
786| if funct.name == 'nametable':
787| nam = funct.args[0]
788|
789| if self.curr_model:
790| if nam in self.curr_model.nametable:
791| return self.curr_model.nametable[nam][1]
792|
793| if self.curr_action:
794| if nam in self.curr_action.nametable:
795| return self.curr_action.nametable[nam][1]
796|
797| if nam in self.m.act_global.nametable:
798| return self.m.act_global.nametable[nam][1]
799|
800| if nam in self.m.act_system.nametable:
801| return self.m.act_system.nametable[nam][1]
802| raise SyntaxError('Unknown Name: "%s"' % nam)
803| raise RuntimeError(self.E_UNKFUNCT % funct.name)
804|
805| def get_object_by_address (self, address):
806| '''Return an object given its address.'''
807| if address.ns == 'system':
808| return self.m.act_system.codeblock[address.value]
809| if address.ns == 'global':
810| return self.m.act_global.codeblock[address.value]
811| if self.curr_action and (address.ns == 'local'):
812| return self.curr_action.codeblock[address.value]
813| return None
814|
815| def get_build_object (self, meta):
816| '''Get a (type-checked) reference to top object on Build Stack.'''
817| build_obj = self.build_stack[len(self.build_stack)-1]
818| if build_obj.metatype != meta:
819| raise RuntimeError(self.E_BLD_OBJ % (meta, build_obj.metatype))
820| return build_obj
821|
822| def emit_build_object (self, meta):
823| '''Type-check the given object and append it to the outout.'''
824| build_obj = self.build_stack.pop()
825| if build_obj.metatype != meta:
826| raise RuntimeError(self.E_BLD_OBJ % (meta, build_obj.metatype))
827| obj = build_obj.getObject()
828|
829| if self.curr_action:
830|
831| self.last_address = self.curr_action.add_to_codeblock(obj)
832|
833| elif self.curr_model:
834|
835| self.last_address = self.curr_model.add_to_template(obj)
836|
837| else:
838| self.last_address = self.m.act_global.add_object_to_codeblock(obj)
839| self.Log.trace('+%s =%s' % (self.last_address, str(obj)))
840|
841| def __contains__ (self, key):
842| '''Is an object in the @system or @global Actions?'''
843| if key in self.m.act_global.nametable:
844| return True
845| if key in self.m.act_system.nametable:
846| return True
847| return False
848|
849| def __getitem__ (self, key):
850| '''Find an object in the @system or @global Actions.'''
851| if key in self.m.act_global.nametable:
852| return self.m.act_global.nametable[key][1]
853|
854| if key in self.m.act_system.nametable:
855| return self.m.act_system.nametable[key][1]
856| return None
857|
858| def __len__ (self):
859| return len(self.m.act_system.nametable) + len(self.m.act_global.nametable)
860|
861| def __str__ (self):
862| '''String version is a list of NameSpace keys.'''
863| a1 = ['s:%s' % k for k in list(self.m.act_system.nametable.keys())]
864| a2 = ['g:%s' % k for k in list(self.m.act_global.nametable.keys())]
865| return reduce(lambda acc,k: acc+(',' if len(acc) else '')+k, sorted(a1+a2, key=lambda k:k[2:].lower()), '')
866|
867| def __repr__ (self):
868| '''JSON-ish version.'''
869| s = '{BoolMacroBuilder:{system:%d, global:%d, constants:%d, id:%s}}'
870| t = (len(self.m.act_system.codeblock), len(self.m.act_global.codeblock), len(list(self.m.constants.keys())), hex(id(self)))
871| return s % t
872|
873| def __init__ (self):
874| '''Create a new BOOL-M Builder instance.'''
875| self.build_stack = []
876| self.last_address = ('global',0)
877| self.curr_action = None
878| self.curr_model = None
879| self.agents = {}
880| self.agents['Action'] = self.agent_Action
881| self.agents['Actor'] = self.agent_Actor
882| self.agents['Label'] = self.agent_Label
883| self.agents['List'] = self.agent_List
884| self.agents['Message'] = self.agent_Message
885| self.agents['Model'] = self.agent_Model
886| self.agents['Object'] = self.agent_Object
887| self.agents['Reference'] = self.agent_Reference
888| self.agents['NameSpace'] = self.agent_NameSpace
889| self.agents['PARSER'] = self.agent_Parser
890|
891| self.m = BoolModule('boolm')
892|
893| def dump (self):
894| '''Dump a Build object to the Log.'''
895|
896| self.Log.info('[Models]')
897| for n in sorted(self.m.models):
898| self.Log.info('. %s=%s' % (n, str(self.m.models[n])))
899| self.Log.info()
900|
901| self.Log.info('[Actions]')
902| for n in sorted(self.m.actions):
903| self.Log.info('. %s=%s' % (n, str(self.m.actions[n])))
904| self.Log.info()
905|
906| self.Log.info('[Constants]')
907| for n in sorted(self.m.constants):
908| self.Log.info('. %s=%s' % (n, str(self.m.constants[n])))
909| self.Log.info()
910|
911| self.Log.info('[TextSpace]')
912| for ix,s in enumerate(self.m.textspc):
913| self.Log.info('. [%04d]: "%s"' % (ix,s))
914| self.Log.info()
915|
916| dump_action(self.m.act_system, self.Log)
917| dump_action(self.m.act_global, self.Log)
918|
919|
920|
921| def dump_action (act, log=Log):
922| '''Dump an Action tuple to the Log.'''
923|
924| log.info('@@%s' % act.name)
925|
926| log.info('name-table:')
927| for n in sorted(act.nametable.keys()):
928| log.info('> %s=%s' % (n, str(act.nametable[n])))
929|
930| log.info('init-list:')
931| for x in act.initlist:
932| log.info('> %s' % str(x))
933|
934| log.info('exit-list:')
935| for x in act.exitlist:
936| log.info('> %s' % str(x))
937|
938| log.info('clauses:')
939| for x in act.clauses:
940| log.info('> %s' % str(x))
941|
942| log.info('code-block:')
943| for ix,x in enumerate(act.codeblock):
944| log.info('> [%04d] %s' % (ix,str(x)))
945|
946| log.info('data-slots:')
947| for ix,cell in enumerate(act.dataslots):
948| log.info('DS[%04d] %s' % (ix, cell))
949| log.info()
950|
951|
952| def dump_model (mod, log=Log, dump_actions=False):
953| '''Dump an Model tuple to the Log.'''
954|
955| log.info('**%s' % mod.name)
956|
957| log.info('name-table:')
958| for n in sorted(mod.nametable.keys()):
959| log.info('> %s=%s' % (n, str(mod.nametable[n])))
960|
961| log.info('template:')
962| for x in mod.template:
963| log.info('> %s' % str(x))
964|
965| log.info('action-list:')
966| for x in mod.actions:
967| log.info('> %s' % str(x))
968| if dump_actions:
969| dump_action(x)
970| log.info()
971|
972|
973|
974|
975| def main (command, args=[]):
976| '''Package Main.'''
977| print('command',command)
978|
979| if command == 'parse':
980| builder = BoolMacroBuilder()
981|
982| for fn in args:
983| Log.info('FILE: %s' % fn)
984| parser = BoolMacroParser(fn)
985| Log.debug('Parser Tokens: %d' % len(parser))
986| builder.build(parser)
987| Log.info()
988| builder.dump()
989|
990| for act_name in sorted(builder.m.actions):
991| if act_name in ['global', 'system']:
992| continue
993| act_addr = builder.m.actions[act_name]
994| if act_addr.ns == 'system':
995| continue
996| Log.info('%s: %s' % (act_name, act_addr))
997| act = builder.get_object_by_address(act_addr)
998| if act:
999| dump_action(act)
1000|
1001| for mod_name in sorted(builder.m.models):
1002| mod_addr = builder.m.models[mod_name]
1003| if mod_addr.ns == 'system':
1004| continue
1005| Log.info('%s: %s' % (mod_name, mod_addr))
1006| mod = builder.get_object_by_address(mod_addr)
1007| if mod:
1008| dump_model(mod)
1009|
1010| return builder
1011|
1012| if (command == '') or (command == 'main'):
1013| return [ 'Usage:'
1014| , "main('parse',args): Parse files in args; return Builder."
1015| , "main(''): Usage Message; return this List."
1016| ]
1017|
1018| return (command, args)
1019|
1020|
1021| if __name__ == '__main__':
1022| print('autorun:',argv[0])
1023| Log.start('bool_m.log')
1024| Log.level(info())
1025| cmnd = argv[1] if 1 < len(argv) else ''
1026| args = argv[2:] if 2 < len(argv) else []
1027| try:
1028| obj = main(cmnd, args)
1029| print('DONE',type(obj))
1030| Log.info('~~~ ')
1031| Log.info(type(obj))
1032| except Exception as e:
1033| Log.error(e)
1034| finally:
1035| Log.end()
1036|
1037|
1038| '''eof'''
1039|