ddl.html


001| '''Data Definition Language (and DDL Viewer).
001| 
001| Parse a DDL file into a data structure which the DDL Viewer can use to display data.
001| 
001| Basic DL (Definition Language) Syntax:
001|     {definition} := {tag} {name} {content} "END" {tag}
001|                  := {tag} {name} {content} "END[ ]*;"
001|                  := {tag} {name} {content} ";"
001| 
001|     {content} := NULL
001|               := {attribute}{content}
001|               := {definition}{content}
001| 
001|     {attribute} := {tag} ":" {name}
001| 
001|     {comment} := "--" {any-text} EOL
001| 
001| The keyword "END" and the symbol ";" are the only defined text. The language is not
001| sensitive to whitespace or indentation. The exception is that comments run to the
001| end of the line. Tags and names are (ATTN: are not? discuss!) case-sensitive. The
001| DDL (Data Definition Language) defines a specific set of tags.
001| 
001| Classes:
001|     ddlObject           - DDL Definition base class.
001|     ddlAttribute        - DDL Attribute class.
001|     ddlDefinition       - DDL Definition class.
001|     ddlFileScanner      - DDL File Scanner class.
001| 
001| Commands:
001|     /d          do_display_data     - compile a DDL file and use to display data
001|     /c          do_compile          - compile and list a DDL file
001|     test        do_test             - (testing)
001| 
001| TODO: Display data!!
001| '''

002| ####################################################################################################
003| from sys import argv, exc_info
004| from traceback import extract_tb
005| from os import path
006| from datetime import datetime
007| from logger import logger,info,debug,trace, LogFilenameTimestamp
008| from goodies import KWARG, typename
009| from files import EOL, datafile, TAB, textfile, linefile
010| ####################################################################################################
011| BasePath = r'C:\CJS\prj\Python\app\langs'
012| DataPath = path.join(BasePath, 'dat')
013| CnfgPath = r'C:\CJS\prj\cjs\ddl'
014| 
015| Log = logger('DDL')
016| 
017| CMND = '/d'
018| ARGS = {
019|     'group': 'G1',
020|     #'savef': '1',
021|     'fname': 'dl_data.ddl',
022|     #'fname': 'dl_test.ddl',
023|     #'fname': 'dl_demo.ddl',
024|     'fpath': BasePath,
025|     #'fpath': DataPath,
026|     #'fpath': CnfgPath,
027|     'dname': 'chessboard.png',
028|     'dpath': r'C:\CJS\prj\Python\app\img',
029| }
030| Out = []
031| 
032| ##------------------------------------------------------------------------------------------------##
033| NumberChars = ['+','-','.']
034| QuoteChars  = ['"', "'"]
035| CommentChar = '-'
036| AttribChar  = ':'
037| EndSymbol   = ';'
038| SpecialQuoteChars = ['<', '>']
039| 
040| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
041| class ddlObject:
042|     '''DDL Definition base class.'''
043| 
044|     def __init__ (self, keyword, name):
045|         self.keyw = keyword
046|         self.name = name
047| 
048|     @property
049|     def keypair (self):
050|         '''Return a (keyw, name) tuple.'''
051|         return (self.keyw, self.name)
052| 
053|     def __call__ (self):
054|         '''Return a (keyw, name) tuple.'''
055|         return self.keypair
056| 
057|     def __str__ (self):
058|         '''String version of (keyw, name) tuple.'''
059|         return '(%s, %s)' % self()
060| 
061|     def __repr__ (self):
062|         '''JSON-like string.'''
063|         t = (typename(self), self.keyw, self.name)
064|         return '{%s:{keyw:%s, name:%s}}' % (typename(self), self.keyw, self.name)
065| 
066| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
067| class ddlAttribute (ddlObject):
068|     '''DDL Attribute class.'''
069| 
070|     def __init__ (self, name, value):
071|         super().__init__(name, value)
072| 
073|     @property
074|     def attrname (self):
075|         '''ATTRNAME is an alias for KEYW.'''
076|         return self.keyw
077| 
078|     @property
079|     def attrvalue (self):
080|         '''ATTRVALUE is an alias for NAME.'''
081|         return self.name
082| 
083|     def __call__ (self, value=None):
084|         '''Return the attribute value.'''
085|         if value is not None:
086|             self.name = value
087|         return self.name
088| 
089|     def __str__ (self):
090|         '''Attribute string "name: value".'''
091|         return '%s=%s' % (self.attrname, self.attrvalue)
092| 
093| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
094| class ddlDefinition (ddlObject):
095|     '''DDL Definition class.'''
096| 
097|     def __init__ (self, keyword, name, content):
098|         super().__init__(keyword, name)
099|         self.content = content
100| 
101|     def __call__ (self, name):
102|         '''Return any content item by name.'''
103|         for obj in self.content:
104|             if isinstance(obj,ddlAttribute):
105|                 if obj.keyw == name:
106|                     return obj
107|             if isinstance(obj,ddlDefinition):
108|                 if obj.name == name:
109|                     return obj
110|         return None
111| 
112|     def __contains__ (self, name):
113|         '''Return true if named content item exists.'''
114|         for obj in self.content:
115|             if isinstance(obj,ddlAttribute):
116|                 if obj.keyw == name:
117|                     return True
118|             if isinstance(obj,ddlDefinition):
119|                 if obj.name == name:
120|                     return True
121|         return False
122| 
123|     def attribute (self, name):
124|         '''Return a content Attribute by name.'''
125|         for obj in self.content:
126|             if isinstance(obj,ddlAttribute) and (obj.keyw == name):
127|                 return obj
128|         return None
129| 
130|     def definition (self, name):
131|         '''Return a content Definition by name.'''
132|         for obj in self.content:
133|             if isinstance(obj,ddlDefinition) and (obj.name == name):
134|                 return obj
135|         return None
136| 
137|     @property
138|     def attributes (self):
139|         '''Return a list of content Attributes.'''
140|         for obj in self.content:
141|             if isinstance(obj,ddlAttribute):
142|                 yield obj
143| 
144|     @property
145|     def definitions (self):
146|         '''Return a list of content Definitions.'''
147|         for obj in self.content:
148|             if isinstance(obj,ddlDefinition):
149|                 yield obj
150| 
151|     def __len__ (self): return len(self.content)
152|     def __iter__ (self): return iter(self.content)
153|     def __getitem__ (self, ix): return self.content[ix]
154|     def __setitem__ (self, ix, val): raise RuntimeError('Definition contents are read-only.')
155|     def __delitem__ (self, ix): raise RuntimeError('Definition contents cannot be deleted.')
156| 
157|     def __str__ (self):
158|         '''String version.'''
159|         t = (self.keyw, self.name, len(list(self.attributes)), len(list(self.definitions)))
160|         return '%s::%s (%d,%d)' % t
161| 
162| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
163| class ddlFileScanner:
164|     '''DDL File Scanner class.'''
165|     def __init__ (self, cfg, bs):
166|         self.cfg = cfg
167|         self.bs = bs
168|         self.address = int(0)
169|         self.vartab = {}
170|         self._config(cfg)
171| 
172|     def __str__ (self):
173|         return '%s @%08x' % (self.cfg.keypair, self.address)
174| 
175|     def _config (self, cfg):
176|         '''Scan the choosen configuration for variables and set their address.'''
177|         self._dispatch(cfg)
178|         for item in cfg.content:
179|             if isinstance(item, ddlDefinition):
180|                 # RECURSE!
181|                 self._config(item)
182| 
183|     def _dispatch (self, obj):
184|         '''Dispatch an object to its handler.'''
185|         Log.debug('Dispatch: %s' % obj)
186|         # Add to variables table...
187|         self.vartab[obj.name] = obj
188|         # Add special attributes...
189|         obj.content.append(ddlAttribute('address', self.address))
190|         obj.content.append(ddlAttribute('value', 0))
191|         # Nothing to process with group or data objects...
192|         if obj.keyw in ['group', 'section']:
193|             return
194|         # Create function name and find function...
195|         name = '_handle_%s' % obj.keyw
196|         if name in type(self).__dict__:
197|             # Call Function...
198|             type(self).__dict__[name](self, obj)
199|         else:
200|             raise RuntimeError('No Object Handler Function: "%s"' % name)
201|         Log.debug()
202| 
203|     def _handle_data (self, obj):
204|         '''Handle DATA object.'''
205|         Log.debug('handler::DATA: %s' % obj.name)
206|         for attr in obj.attributes:
207|             Log.debug('attribute: %s' % attr)
208|             if attr.attrname == 'start':
209|                 try:
210|                     start = int(attr.attrvalue, base=0)
211|                     Log.debug('set address %08x' % start)
212|                     self.address = start
213|                 except:
214|                    continue
215|                    #TODO: Get variable reference value
216|         obj.attribute('address')(self.address)
217| 
218|     def _handle_byte (self, obj):
219|         '''Handle BYTE object.'''
220|         Log.debug('handler::BYTE: %s' % obj.name)
221|         n = 1
222|         for attr in obj.attributes:
223|             Log.debug('attribute: %s' % attr)
224|             if attr.attrname == 'count':
225|                 n = int(attr.attrvalue)
226|         obj.attribute('value')(self.bs[self.address])
227|         self.address += n
228| 
229|     def _handle_int (self, obj):
230|         '''Handle INT object.'''
231|         Log.debug('handler::INT: %s' % obj.name)
232|         size = 4
233|         n = 1
234|         bo = 'LE'
235|         for attr in obj.attributes:
236|             Log.debug('attribute: %s' % attr)
237|             if attr.attrname == 'size':
238|                 size = int(attr.attrvalue) // 8
239|             if attr.attrname == 'count':
240|                 n = int(attr.attrvalue)
241|             if attr.attrname == 'bo':
242|                 bo = attr.attrvalue.upper()
243|         Log.debug('size=%s:%s' % (size, typename(size)))
244|         bixs = list(reversed(range(size)) if bo=='LE' else range(size))
245|         Log.debug(bixs)
246|         bs = [self.bs[self.address+bx] for bx in bixs]
247|         Log.debug(bs)
248|         val = sum([b*pow(256,ix) for ix,b in enumerate(bs)])
249|         obj.attribute('value')(val)
250|         self.address += int(size*n)
251| 
252|     def _handle_float (self, obj):
253|         '''Handle FLOAT object.'''
254|         Log.debug('handler::FLOAT: %s' % obj.name)
255|         size = 64
256|         n = 1
257|         for attr in obj.attributes:
258|             Log.debug('attribute: %s' % attr)
259|             if attr.attrname == 'size':
260|                 size = attr.attrvalue // 8
261|             if attr.attrname == 'count':
262|                 n = int(attr.attrvalue)
263|         self.address += int(size*n)
264| 
265|     def _handle_string (self, obj):
266|         '''Handle STRING object.'''
267|         Log.debug('handler::STRING: %s' % obj.name)
268|         size = 1
269|         n = 1
270|         for attr in obj.attributes:
271|             Log.debug('attribute: %s' % attr)
272|             if attr.attrname == 'size':
273|                 size = attr.attrvalue
274|             if attr.attrname == 'count':
275|                 n = int(attr.attrvalue)
276|         self.address += int(size*n)
277| 
278|     def _handle_span (self, obj):
279|         Log.debug('handler::SPAN: %s' % obj.name)
280|         size = 1
281|         for attr in obj.attributes:
282|             Log.debug('attribute: %s' % attr)
283|             if attr.attrname == 'size':
284|                 size = attr.attrvalue
285|         self.address += int(size)
286| 
287|     def _handle_quote (self, obj):
288|         Log.debug('handler::QUOTE')
289|         for attr in obj.attributes:
290|             Log.debug('attribute: %s' % attr)
291| 
292| 
293| ##================================================================================================##
294| def ddl_tokenize (text):
295|     '''Convert DDL text to a list of tokens.
295| 
295| The token list consists of tuples with the first member identifying the token type.
295| Types: TOK, ATT (attribute), NUM (number), STR (string), QOT (quoted text), END.
295| Strings can begin with single- or double-quotes. They end with the same quote, obviously.
295| Note that strings are not processed, so can't currently contain embedded escaped quotes.
295| Quoted text is tokenized the same. The QOT tokens signal start and end.
295| '''

296|     def istoken (ch):
297|         if ch.isidentifier(): return True
298|         if ch.isdecimal(): return True
299|         if ch in NumberChars: return True
300|         if ch == AttribChar: return True
301|         return False
302| 
303|     def get_token (cs):
304|         '''Read chars until a break.'''
305|         tok = []
306|         while 0 < len(cs):
307|             # End of token if space...
308|             if cs[-1].isspace():
309|                 break
310|             # End of token if non name or number char...
311|             if not istoken(cs[-1]):
312|                 break
313|             # Some special handling for attributes...
314|             if cs[-1] == AttribChar:
315|                 cs.pop()
316|                 s = ''.join(tok)
317|                 Log.trace('attribute: %s' % s)
318|                 return ('ATT', s)
319|             # Otherwise add character to token...
320|             ch = cs.pop()
321|             tok.append(ch)
322| 
323|         s = ''.join(tok)
324|         # Detect numbers...
325|         if '^' in s:
326|             s = s.replace('^','e')
327|         try:
328|             n = float(s)
329|             return ('NUM', n)
330|         except:
331|             pass
332|         # Detect END keyword...
333|         if s.upper() == 'END':
334|             s = s.upper()
335|         Log.trace('token: %s' % s)
336|         return ('TOK', s)
337| 
338|     # Convert text into a list of tokens...
339|     tokens = []
340|     chars = list(reversed(text))
341|     while 0 < len(chars):
342| 
343|         # Skip spaces...
344|         if chars[-1].isspace():
345|             chars.pop()
346|             continue
347| 
348|         # Skip comments...
349|         if (chars[-1] == CommentChar) and (chars[-2] == CommentChar):
350|             while (0 < len(chars)) and (chars[-1] != EOL):
351|                 chars.pop()
352|             if (0 < len(chars)) and (chars[-1] == EOL):
353|                 chars.pop()
354|             continue
355| 
356|         # The semi-colon is syntax sugar for "END <name>"...
357|         if chars[-1] == EndSymbol:
358|             tokens.append(('END', chars.pop()))
359|             continue
360| 
361|         # Detect <<< and >>> quoting...
362|         if chars[-1] in SpecialQuoteChars:
363|             if chars[-1] == chars[-2] == chars[-3]:
364|                 chars.pop()
365|                 chars.pop()
366|                 tokens.append(('QOT', chars.pop()))
367|                 continue
368| 
369|         # Detect " and ' strings...
370|         if chars[-1] in QuoteChars:
371|             qc = chars.pop()
372|             buf = []
373|             while (0 < len(chars)) and (chars[-1] != qc):
374|                 buf.append(chars.pop())
375|             if (0 < len(chars)) and (chars[-1] != qc):
376|                 raise RuntimeError('String without closing quote!')
377|             else:
378|                 chars.pop()
379|             tokens.append(('STR', ''.join(buf)))
380|             continue
381| 
382|         # Else, must be a name or number...
383|         tok = get_token(chars)
384|         if tok:
385|             tokens.append(tok)
386| 
387|     # Return the list of tokens...
388|     return tokens
389| 
390| ##================================================================================================##
391| def ddl_parse (tokens, name='New'):
392|     '''Parse a list of DDL tokens into a DDL data structure.
392| 
392| Convert the tokens list from ddl_tokenize to a list of DDL objects.
392| Returns the top-level DDL definition.
392| 
392| '''

393|     toks = list(reversed(tokens))
394| 
395|     def dl_content ():
396|         content = []
397|         while (0 < len(toks)):
398|             # End of content...
399|             if toks[-1][0] == 'END':
400|                 Log.trace('Content ended with ; token.')
401|                 break
402|             if (toks[-1][0] == 'TOK') and (toks[-1][1] == 'END'):
403|                 Log.trace('Content ended with END token.')
404|                 break
405|             # Process attributes...
406|             if toks[-1][0] == 'ATT':
407|                 obj = dl_attribute()
408|                 content.append(obj)
409|                 continue
410|             # Process sub-definitions...
411|             if toks[-1][0] == 'TOK':
412|                 obj = dl_definition()
413|                 content.append(obj)
414|                 continue
415|             # Oops!
416|             raise SyntaxError('Unexpected token: (%s,%s)' % toks[-1])
417|         # Return the list of attributes and definitions...
418|         return content
419| 
420|     def dl_definition ():
421|         keyw = toks.pop()       # definition keyword
422|         name = toks.pop()       # definition name
423|         Log.debug('DEF: %s %s' % (keyw,name))
424|         content = dl_content()
425|         # End of definition...
426|         match toks[-1][0]:
427|             case 'TOK':
428|                 end = toks.pop()
429|                 if end[1] != 'END':
430|                     raise SyntaxError('Expected END keyword!')
431|                 tag = toks.pop()
432|                 if not ((tag[0]=='END') or ((tag[0]=='TOK') and (tag[1]==keyw[1]))):
433|                     raise SyntaxError('Expected matching keyword after END! [%s:%s]' % (keyw,tag))
434|             case 'END':
435|                 toks.pop()
436|             case _:
437|                 raise SyntaxError('Unexpected token: (%s,%s)' % toks[-1])
438|         # Return definition...
439|         return ddlDefinition(keyw[1], name[1], content)
440| 
441|     def dl_attribute ():
442|         name = toks.pop()       # attribute name
443|         value = toks.pop()      # attribute value
444|         Log.debug('ATT: %s %s' % (name,value))
445|         buf = []
446|         if value[0] == 'QOT':
447|             if value[1] != '<':
448|                 raise SyntaxError('Expected <<< for quoted text.')
449|             while 0 < len(toks):
450|                 tok = toks.pop()
451|                 if tok[0] == 'QOT':
452|                     if tok[1] != '>':
453|                         raise SyntaxError('Expected >>> for quoted text.')
454|                     break
455|                 buf.append(tok)
456|             # Return attribute...
457|             return (name[1], buf)
458|         # Return attribute...
459|         return ddlAttribute(name[1], value[1])
460| 
461|     return dl_definition()
462| 
463| ##================================================================================================##
464| def config_dump (cfg, depth=0):
465|     '''Dump configuration to the log.'''
466|     Log.info('[%02d]DEF: %s %s (items: %d)' % (depth, cfg.keyw, cfg.name, len(cfg.content)))
467| 
468|     for item in cfg.content:
469|         # Attributes...
470|         if isinstance(item, ddlAttribute):
471|             Log.info('[%02d]Attribute: %s=%s' % (depth, item.attrname, item.attrvalue))
472|             continue
473| 
474|         # Definitions...
475|         if isinstance(item, ddlDefinition):
476|             # RECURSE!
477|             config_dump(item, depth=depth+1)
478|             continue
479| 
480|         # Oops!
481|         raise RuntimeError('Not an Attribute or Definition!')
482| 
483|     # Exit definition...
484|     Log.info('[%02d]end %s' % (depth,cfg.keyw))
485| 
486| ##================================================================================================##
487| def config_listing (cfg, output, depth=0, sep='| '):
488|     '''Write configuration to file (with pretty printing).'''
489|     output.append('%s%s %s (items: %d)' % (sep*depth, cfg.keyw, cfg.name, len(cfg.content)))
490| 
491|     for item in cfg.content:
492|         # Attributes...
493|         if isinstance(item, ddlAttribute):
494|             output.append('%s> %s: %s' % (sep*depth, item.attrname, item.attrvalue))
495|             continue
496| 
497|         # Definitions...
498|         if isinstance(item, ddlDefinition):
499|             # RECURSE!
500|             config_listing(item, output, depth=depth+1)
501|             continue
502| 
503|         # Oops!
504|         raise RuntimeError('Not an Attribute or Definition!')
505| 
506|     # Exit definition...
507|     output.append('%send %s' % (sep*depth,cfg.keyw))
508|     if 0 < depth:
509|         output.append('%s%s' % (sep*(depth-1),sep[0]))
510|     else:
511|         output.append('')
512| 
513| ##================================================================================================##
514| def config_groups (cfg, depth=0):
515|     '''Find the data definition groups in the configuration.'''
516|     if cfg.keyw == 'group':
517|         return {cfg.name: cfg.content}
518|     groups = {}
519| 
520|     for item in cfg.definitions:
521|         if item.keyw == 'group':
522|             groups[item.name] = item
523|             continue
524|         # RECURSE!
525|         gs = config_groups(item, depth=depth+1)
526|         for nm in gs:
527|             groups[nm] = gs[nm]
528| 
529|     # Return the groups...
530|     return groups
531| 
532| 
533| ##================================================================================================##
534| def do_display_data (**kwargs):
535|     """CMND: Compile a DDL file and use it to display a data file."""
536|     fpath = KWARG('fpath', BasePath, str, kwargs)
537|     fname = KWARG('fname', 'test.ddl', str, kwargs)
538|     dpath = KWARG('dpath', BasePath, str, kwargs)
539|     dname = KWARG('dname', 'image.png', str, kwargs)
540|     gname = KWARG('group', '*', str, kwargs)
541|     savef = KWARG('savef', 0, int, kwargs)
542|     Log.info('display-data:: %s' % str(list(kwargs.keys())))
543|     Log.debug('fpath="%s"' % fpath)
544|     Log.debug('fname="%s"' % fname)
545|     Log.debug('dpath="%s"' % dpath)
546|     Log.debug('dname="%s"' % dname)
547|     Log.debug('group="%s"' % gname)
548|     Log.debug('save-list-file=%d' % savef)
549|     Log.info()
550|     srcfile = path.join(fpath,fname) if fpath else fname
551|     datfile = path.join(dpath,dname) if dpath else dname
552|     lstfile = '%s.list' % path.splitext(srcfile)[0]
553| 
554|     # Load the DDL file...
555|     fsrc = textfile(srcfile)
556|     fsrc.load()
557|     Log.info()
558| 
559|     # Tokenize the text...
560|     tokens = ddl_tokenize(fsrc.data)
561| 
562|     # Create the DDL configuration...
563|     config = ddl_parse(tokens, name=fname)
564|     # Find the data groups...
565|     grps = config_groups(config)
566|     Log.info()
567| 
568|     # Write the listing to file...
569|     if savef:
570|         flst = linefile(lstfile)
571|         config_listing(config, flst.data)
572|         flst.save()
573|         Log.info()
574| 
575|     # Get the data group to use...
576|     if gname not in grps:
577|         raise RuntimeError('Group "%s" not found.' % gname)
578|     grp = grps[gname]
579|     Out.append(grp)
580|     Log.info('Found Group "%s"' % grp.name)
581|     Log.info()
582| 
583|     # SCAN...
584|     fdat = datafile(datfile)
585|     fdat.load()
586| 
587|     scanner = ddlFileScanner(grp, fdat.data)
588|     Out.append(scanner)
589|     Log.info()
590|     Log.info('final-address: %08x' % scanner.address)
591|     Log.info()
592| 
593|     Log.info('VARIABLES:')
594|     for vn,v in scanner.vartab.items():
595|         addr = v.attribute('address').attrvalue if 'address' in v else 0
596|         valu = v.attribute('value').attrvalue if 'value' in v else 0
597|         labl = v.attribute('label').attrvalue if 'label' in v else ''
598|         Log.info('[%08x] %s:%s = %s "%s"' % (addr, vn, v.keyw, valu, labl))
599|         #Log.info('%s: %s' % (vn,v.content))
600|     Log.info()
601| 
602|     Log.info()
603|     return 'Done'
604| 
605| ##================================================================================================##
606| def do_compile (**kwargs):
607|     """CMND: Compile a DDL file."""
608|     fpath = KWARG('fpath', BasePath, str, kwargs)
609|     fname = KWARG('fname', 'source.ddl', str, kwargs)
610|     Log.info('compile:: %s' % str(list(kwargs.keys())))
611|     Log.debug('fpath="%s"' % fpath)
612|     Log.debug('fname="%s"' % fname)
613|     Log.info()
614|     srcfile = path.join(fpath,fname) if fpath else fname
615|     lstfile = '%s.list' % path.splitext(srcfile)[0]
616| 
617|     # Load the DDL file...
618|     fo = textfile(srcfile)
619|     fo.load()
620| 
621|     # List the DDL file...
622|     Log.debug()
623|     Log.debug('DDL FILE:')
624|     for line in fo.data.splitlines():
625|         Log.debug(line)
626|     Log.debug()
627| 
628|     # Tokenize the text...
629|     Log.debug('TOKENIZE DDL TEXT:')
630|     tokens = ddl_tokenize(fo.data)
631|     Out.append(tokens)
632| 
633|     # List the token list...
634|     Log.debug()
635|     Log.debug('DDL TOKENS:')
636|     for tok in tokens:
637|         Log.debug(tok)
638|     Log.debug()
639| 
640|     # Create the DDL configuration...
641|     Log.debug('PARSE DDL TOKENS:')
642|     config = ddl_parse(tokens, name=fname)
643|     Out.append(config)
644| 
645|     # List the configuration...
646|     Log.debug()
647|     Log.debug('DDL CONFIG:')
648|     config_dump(config)
649| 
650|     # Write the listing to file...
651|     fo = linefile(lstfile)
652|     config_listing(config, fo.data)
653|     fo.save()
654| 
655|     Log.info()
656|     return 'Done'
657| 
658| ##================================================================================================##
659| def do_test (**kwargs):
660|     """CMND: Test."""
661|     fpath = KWARG('fpath', BasePath, str, kwargs)
662|     fname = KWARG('fname', 'test.ddl', str, kwargs)
663|     Log.info('test:: %s' % str(list(kwargs.keys())))
664|     Log.debug('fpath="%s"' % fpath)
665|     Log.debug('fname="%s"' % fname)
666|     Log.info()
667|     Log.info()
668|     return 'Done'
669| ####################################################################################################
670| def dispatch (cmd, **kwargs):
671|     """Dispatch to a module function based on CMD."""
672|     Log.info('CMD: %s' % cmd)
673|     for kw in kwargs:
674|         Log.debug('argument[%s]: %s' % (kw,kwargs[kw]))
675|     Log.info()
676|     if cmd == '/d': return do_display_data(**kwargs)
677|     if cmd == '/c': return do_compile(**kwargs)
678|     if cmd == 'test': return do_test(**kwargs)
679|     return 'Nothing to do!'
680| ####################################################################################################
681| if __name__ == '__main__':
682|     print('autorun: %s' % argv[0])
683|     #Log.start(path.join(BasePath,LogFilenameTimestamp('ddl_%s.log')))
684|     Log.start(path.join(BasePath,'ddl.log'))
685|     Log.level(trace())
686|     Log.info(argv[0])
687|     Log.info()
688|     cmd = argv[1] if 1 < len(argv) else CMND
689|     kwargs = ARGS
690|     for a in argv[2:]:
691|         nv = a.split('=', 2)
692|         kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
693|         Log.debug('%s: "%s"' % (nv[0], kwargs[nv[0]]))
694|     try:
695|         print('CMD: %s' % cmd)
696|         print()
697|         obj = dispatch(cmd, **kwargs)
698|         print()
699|         print(obj)
700|         Log.info()
701|         Log.info(obj)
702|     except:
703|         etype, evalue, tb = exc_info()
704|         ts = extract_tb(tb)
705|         Log.error()
706|         Log.error('%s: %s' % (etype.__name__,str(evalue)))
707|         Log.error()
708|         for t in ts[-5:]:
709|             Log.error('[%d] %s (%s)' % (t[1], t[2], t[0]))
710|             Log.error(' %s' % t[3])
711|             Log.error()
712|         raise
713|     finally:
714|         Log.end()
715| ####################################################################################################
716| '''eof'''
717|