lpl3.html


001| '''\
001| LPL-3. Little Programming Language #3.
001| 
001|     <list-items>  :=  <NULL> | <list-item> | <list-item> <list-items>
001|     <list-item>  :=  <value> | <list>
001|     <list>  :=  ( <keyword> <list-items> )
001|     <expr>  :=  <value> | (<oper> <list-items> ) | <list> {{if <list> has a value}}
001|     <value>  :=  <name> | <number> | <string> | <date>
001|     <keyword>  :=  <NULL>=list:|label:|var:|ref:|function:|<oper>|if:|while:|until:|for:|match:|cases:
001| 
001|     (list: <list-items> )
001|     (label: <name> <list> )
001|     (ref: <name> )
001|     (function: (ins: <var-list> ) (out: <var> ) (list: <list-items ) )
001|     (<oper> <list-items> )
001|     (var<opts>: <initial-value> )
001|     (set: <var> <expr> )
001|     (if: <expr> (then: <list-items> ) (else: <list-items> ) )
001|     (while: <expr> (list: <list-items> ) )
001|     (until: <expr> (list: <list-items> ) )
001|     (for: <var> (in: <list-items> ) (list: <list-items> ) )
001|     (for: <var> (step: <from> <to> <step> ) (list: <list-items> ) )
001|     (match: <expr> (case: <expr> (list: <list-items> )) (else: <list-items> ) )
001|     (cases: (case: <expr> (list: <list-items> )) (else: <list-items> ) )
001| 
001|     [1] list: keyword is always optional; lack of keyword or operator defaults to list:
001| 
001| commands:
001|     main            - Main function (normal use)
001|     test            - Test function (development)
001| 
001| usage:
001|     module.dispatch({command}, args={arguments})    -- calling module from code
001| 
001|     $PYTHON module_name {command} {arguments}       -- executing module externally
001| 
001| Developer@Sonnack.com
001| April 2016
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
008| from lpl3e import lpl_3_execute, LPL3, BasePath
009| from lpl3d import lpl_3_dump_obj
010| from lpl3c import lpl_3_compile_file
011| ####################################################################################################
012| Log = logger('LPL-3')
013| 
014| extern = lambda s: ('%s%s' % (LPL3.CODE,s),)
015| 
016| ##------------------------------------------------------------------------------------------------##
017| EG =(LPL3.LBL,'lpl-3.1', (LPL3.PROG,
018|     (LPL3.LBL,'main', (LPL3.FUNC,
019|         (   (LPL3.LBL,'argv', (LPL3.VAR,['string','array'],[])),
020|             (LPL3.LBL,'env', (LPL3.VAR,['string','array'],[])),
021|         ),
022|         (   (LPL3.VAR,['int'],[int(-1)]),
023|         ),
024|         (   (LPL3.REF,'sysinit'),
025|             (LPL3.LBL,'dt', (LPL3.VAR,['date'],[(LPL3.REF,'now')])),
026|             (LPL3.REF,'demo', (LPL3.REF,'dt'), (LPL3.REF,'random')),
027|             (LPL3.SET, (LPL3.REF,'out'), (LPL3.VAR,['int'],[1])),
028|         ),
029|     )),
030|     (LPL3.LBL,'demo', (LPL3.FUNC,
031|         (),
032|         (   (LPL3.VAR,['int'],[int(-1)]),
033|         ),
034|         (   (LPL3.LBL,'aa', (LPL3.VAR,['float'],[float(12.3)])),
035|             (LPL3.LBL,'bb', (LPL3.VAR,['float'],[float(6.9)])),
036|             (LPL3.LBL,'cc', (LPL3.VAR,['float'],[float(0)])),
037|             (LPL3.SET, (LPL3.REF,'cc'), ('distance', (LPL3.REF,'aa'),(LPL3.REF,'bb'))),
038|             (LPL3.SET, (LPL3.REF,'out'), ('int', (LPL3.REF,'cc'))),
039|             (LPL3.PRINT, (LPL3.REF,'$1'),(LPL3.REF,'$2')),
040|             (LPL3.PRINT, (LPL3.REF,'aa'),(LPL3.REF,'bb'),(LPL3.REF,'cc'),(LPL3.REF,'out')),
041|         ),
042|     )),
043|     (LPL3.LBL,'distance', (LPL3.FUNC,
044|         (   (LPL3.LBL,'a', (LPL3.VAR,['float'],[float(0)])),
045|             (LPL3.LBL,'b', (LPL3.VAR,['float'],[float(0)])),
046|         ),
047|         (   (LPL3.LBL,'h', (LPL3.VAR,['float'],[float(0)])),
048|         ),
049|         (   (LPL3.SET, (LPL3.REF,'h'), ('sqrt', ('add', ('mul',(LPL3.REF,'a'),(LPL3.REF,'a')), ('mul',(LPL3.REF,'b'),(LPL3.REF,'b'))))),
050|             (LPL3.PRINT, (LPL3.REF,'a'),(LPL3.REF,'b'),(LPL3.REF,'h')),
051|         ),
052|     )),
053|     (LPL3.LBL,'sqrt', (LPL3.FUNC, [(LPL3.VAR,['float'],[float(0)])], [(LPL3.VAR,['float'],[float(0)])], [extern('math.sqrt')])),
054|     (LPL3.LBL,'random', (LPL3.FUNC, [], [(LPL3.VAR,['float'],[float(0)])], [extern('random.random')])),
055|     (LPL3.LBL,'now', (LPL3.FUNC, (),((LPL3.VAR,['date'],[datetime.now()]),), [])),
056|     (LPL3.LBL,'sysinit', (LPL3.FUNC, (),(), [])),
057| ))
058| 
059| ##================================================================================================##
060| ## LPL-3
061| ##================================================================================================##
062| def lpl_3 (objs, nt={LPL3.GLOBALS:{}}):
063|     Log.info('LPL-3::START')
064|     lpl_3_execute(nt, objs)
065|     Log.info('LPL-3::END')
066|     Log.info()
067|     Log.info('Global Name Table:')
068|     for n in nt:
069|         Log.info('%s: %s' % (n, nt[n]))
070|     Log.info()
071| 
072| 
073| ##================================================================================================##
074| def do_demo2 (*args):
075|     Log.info('demo2:: %s' % str(args))
076|     Log.info('LPL-3::DUMP')
077|     Log.flush()
078|     lpl_3_dump_obj(EG, fp=Log.fp)
079|     Log.flush()
080|     Log.info()
081| ##================================================================================================##
082| def do_demo1 (*args):
083|     Log.info('demo1:: %s' % str(args))
084|     Log.flush()
085|     lpl_3_dump_obj(EG, fp=Log.fp)
086|     Log.flush()
087|     nt = {'execute':'main', LPL3.GLOBALS:{}, 'log':True, 'debug':False}
088|     lpl_3(EG, nt)
089|     return 'Done'
090| ##================================================================================================##
091| def do_test (*args):
092|     Log.info('test:: %s' % str(args))
093|     srcname = args[0] if 0 < len(args) else path.join(BasePath,'lpl3.in')
094|     outname = args[1] if 1 < len(args) else path.join(BasePath,'lpl3.out')
095|     # Compile...
096|     obj = lpl_3_compile_file(srcname)
097|     # List...
098|     fp = open(outname, mode='w', encoding='utf-8')
099|     try: lpl_3_dump_obj(obj, fp=fp)
100|     except: raise
101|     finally: fp.close()
102|     # Execute...
103|     nt = {'execute':'main', LPL3.GLOBALS:{}, 'log':True, 'debug':True}
104|     lpl_3(obj, nt)
105|     return 'Done'
106| ##================================================================================================##
107| def do_main (*args):
108|     Log.info('main:: %s' % str(args))
109|     srcname = args[0]
110|     outname = args[1] if 1 < len(args) else path.join(BasePath,'lpl3.out')
111|     exename = args[2] if 2 < len(args) else 'main'
112|     # Compile...
113|     obj = lpl_3_compile_file(srcname)
114|     # List...
115|     fp = open(outname, mode='w', encoding='utf-8')
116|     try: lpl_3_dump_obj(obj, fp=fp)
117|     except: raise
118|     finally: fp.close()
119|     # Execute...
120|     nt = {'execute':exename, LPL3.GLOBALS:{}, 'log':False, 'debug':False}
121|     lpl_3(obj, nt)
122|     return 'Done'
123| ####################################################################################################
124| def dispatch (cmd, *args):
125|     Log.info('command: %s' % cmd)
126|     Log.info('arguments: %d' % len(args))
127|     if cmd == 'main': return do_main(*args)
128|     if cmd == 'test': return do_test(*args)
129|     if cmd == 'demo1': return do_demo1(*args)
130|     if cmd == 'demo2': return do_demo2(*args)
131|     return 'Nothing to do!'
132| ####################################################################################################
133| if __name__ == '__main__':
134|     print('autorun: %s' % argv[0])
135|     Log.start(path.join(BasePath,'lpl3.log'))
136|     Log.level(info())
137|     Log.info(argv[0])
138|     Log.info()
139|     cmd = argv[1] if 1 < len(argv) else ''
140|     etc = argv[2:] if 2 < len(argv) else []
141|     try:
142|         print('CMD: %s' % cmd)
143|         print()
144|         obj = dispatch(cmd, *etc)
145|         print()
146|         print(obj)
147|         Log.info()
148|         Log.info(obj)
149|     except SyntaxError as e:
150|         _,_,tb = exc_info()
151|         ts = extract_tb(tb)
152|         Log.error()
153|         Log.error('SyntaxError:\n%s' % e)
154|         Log.error('%s' % e.text.split('\n')[e.lineno-1])
155|         Log.error('%s^' % ((e.offset-1) * ' '))
156|         Log.error()
157|         for t in ts[-3:]:
158|             Log.error('%d: %s (%s)\n> %s\n' % (t[1],t[2],t[0],t[3]))
159|             Log.error()
160|         raise
161|     except:
162|         etype, evalue, tb = exc_info()
163|         ts = extract_tb(tb)
164|         Log.error()
165|         Log.error('%s: %s' % (etype.__name__,str(evalue)))
166|         Log.error()
167|         for t in ts:
168|             Log.error('[%d] %s (%s)' % (t[1], t[2], path.basename(t[0])))
169|             Log.error(' %s' % t[3])
170|             Log.error()
171|         raise
172|     finally:
173|         Log.end()
174| ####################################################################################################
175| '''eof'''
176|