lpl3e.html
001| '''\
001| LPL-3. Little Programming Language #3 - Runtime Engine.
001|
001| Developer@Sonnack.com
001| August 2017
001| '''
002|
003| from __future__ import print_function
004| from sys import argv
005| from os import environ
006| from math import sqrt
007| from random import random
008| from datetime import datetime
009| from logger import logger
010|
011| BasePath = r'C:\CJS\prj\Python\app\langs'
012| Log = logger('LPL-3E')
013|
014|
015|
016| class LPL3 (object):
017| NULL = 'nul'
018| LST = 'list'
019| LBL = 'label'
020| VAR = 'var'
021| REF = 'ref'
022| SET = 'set'
023| IF = 'if'
024| WHILE = 'while'
025| UNTIL = 'until'
026| FOR = 'for'
027| SELECT = 'select'
028| CASE = 'case'
029| NEXT = 'next'
030| BREAK = 'break'
031| RETURN = 'return'
032| EXIT = 'exit'
033| PRINT = 'print'
034| FUNC = 'function'
035| PROG = 'program'
036| CODE = '%import:'
037| GLOBALS = 'globals'
038|
039| KeyWords = [LST,LBL,VAR,REF,SET,IF,WHILE,UNTIL,FOR,SELECT,CASE,NEXT,BREAK,RETURN,EXIT,PRINT,FUNC,PROG,CODE,NULL]
040| DataTypes = [VAR,'array','bool','int','float','string','date','byte','char','long','double']
041| ReservedWords = [GLOBALS]+KeyWords+DataTypes
042|
043|
044|
045| def ext_function_random (namtab):
046| t = (LPL3.VAR, ['float'], [random()])
047| namtab['out'] = t
048| Log.debug('random.random: out=%s' % str(t))
049| return t
050|
051|
052| ExternalFunctions = {
053| 'random.random':ext_function_random,
054| }
055|
056|
057| def function_random (args):
058| if len(args):
059| raise RuntimeError('(random) takes no arguments: "%s"' % str(args))
060| return (LPL3.VAR, ['float'], [random()])
061|
062| InternalFunctions = {
063| 'random':function_random,
064| }
065|
066|
067| def function_math_sqrt (arg):
068| if arg[0] != LPL3.VAR:
069| raise RuntimeError('Invalid object for (sqrt): "%s"' % str(arg))
070| if arg[1][0] not in ['int','float']:
071| raise RuntimeError('Invalid argument type for (sqrt): "%s"' % str(arg))
072| n = float(arg[2][0])
073| return (LPL3.VAR, ['float'], [sqrt(n)])
074|
075|
076| def lpl_3_execute_item (namtab, obj, label=None, args=[]):
077| '''Execute Item. (Such as found on a list or in a value. Return value depends on object)'''
078| Log.trace('ITEM: nt=%s' % str(list(namtab.keys())))
079| if not isinstance(obj,tuple):
080| raise RuntimeError('Invalid Node; Not a tuple: %s' % str(obj))
081|
082|
083| if len(obj) == 0:
084| Log.debug('ITEM: <<NULL>>')
085| return None
086|
087| obj_type = obj[0]
088| Log.debug('ITEM: type=%s' % str(obj_type))
089|
090| if obj_type == LPL3.NULL:
091| Log.debug('ITEM: <<NOP>>')
092| return ()
093|
094| if obj_type == LPL3.LST:
095| return obj
096|
097| if obj_type == LPL3.LBL:
098| name = obj[1]
099| namtab[name] = obj[2]
100| return lpl_3_execute_item(namtab, obj[2], label=name)
101|
102| if obj_type == LPL3.VAR:
103| return lpl_3_execute_var(namtab, obj)
104|
105| if obj_type == LPL3.REF:
106| name = obj[1]
107| tail = [lpl_3_execute_item(namtab,a) for a in obj[2:]]
108| rtn_obj = lpl_3_execute_reference(namtab, obj)
109| return lpl_3_execute_item(namtab, rtn_obj, label=name, args=tail)
110|
111| if obj_type == LPL3.SET:
112| return lpl_3_execute_set(namtab, obj)
113|
114| if obj_type == LPL3.IF:
115| return lpl_3_execute_ifelse(namtab, obj)
116|
117| if obj_type == LPL3.WHILE:
118| return lpl_3_execute_while(namtab, obj)
119|
120| if obj_type == LPL3.UNTIL:
121| return lpl_3_execute_until(namtab, obj)
122|
123| if obj_type == LPL3.FOR:
124| return lpl_3_execute_forloop(namtab, obj)
125|
126| if obj_type == LPL3.SELECT:
127| return lpl_3_execute_select(namtab, obj)
128|
129| if obj_type == LPL3.PRINT:
130| return lpl_3_execute_print(namtab, obj)
131|
132| if obj_type == LPL3.FUNC:
133| symtab = {'ins':args, 'out':()}
134| symtab['function-name'] = label if label else '<function>'
135| symtab['caller'] = namtab['function-name']
136| symtab[LPL3.GLOBALS] = namtab[LPL3.GLOBALS]
137| return lpl_3_execute_function(symtab, obj)
138|
139| if obj_type.startswith(LPL3.CODE):
140| ext_name = obj_type[len(LPL3.CODE):]
141| ext_func = ExternalFunctions[ext_name]
142| Log.trace('ExternalName: "%s"' % ext_name)
143| return ext_func(namtab)
144|
145| if obj_type in InternalFunctions:
146| int_func = InternalFunctions[obj_type]
147| return int_func(obj[1:])
148|
149| obj = lpl_3_execute_object(namtab, obj_type, obj[1:])
150| if obj:
151| return obj
152|
153| raise RuntimeError('Invalid Node; Not executible: %s' % str(obj))
154|
155|
156| def lpl_3_execute_object (namtab, op_name, op_args):
157| '''Execute Operator. (Includes invoking functions! Return value is result of function.)'''
158| Log.info('OBJ: name=%s' % op_name)
159| Log.trace('OBJ: args=%s' % str(op_args))
160| Log.trace('OBJ: nt=%s' % str(list(namtab.keys())))
161|
162|
163| if 0 < len(op_args):
164| arg0 = lpl_3_execute_item(namtab, op_args[0])
165| Log.debug('OBJ: [%s]arg0=%s' % (op_name, str(arg0)))
166| if op_name == 'int':
167| return (LPL3.VAR, ['int'], [int(arg0[2][0])])
168| if op_name == 'float':
169| return (LPL3.VAR, ['float'], [float(arg0[2][0])])
170|
171| if op_name == 'neg': return (LPL3.VAR, arg0[1], [ -(arg0[2][0])])
172| if op_name == 'inv': return (LPL3.VAR, arg0[1], [ ~(arg0[2][0])])
173| if op_name == 'abs': return (LPL3.VAR, arg0[1], [abs(arg0[2][0])])
174| if op_name == 'not': return (LPL3.VAR, arg0[1], [not(arg0[2][0])])
175| if op_name == 'sqrt': return function_math_sqrt(arg0)
176|
177|
178| if 1 < len(op_args):
179| arg1 = lpl_3_execute_item(namtab, op_args[1])
180| Log.debug('OBJ: [%s]arg1=%s' % (op_name, str(arg1)))
181| if op_name == 'lt': return (LPL3.VAR, ['bool'], [((arg0[2][0]) > (arg1[2][0]))])
182| if op_name == 'elt': return (LPL3.VAR, ['bool'], [((arg0[2][0]) >= (arg1[2][0]))])
183| if op_name == 'eq': return (LPL3.VAR, ['bool'], [((arg0[2][0]) == (arg1[2][0]))])
184| if op_name == 'ne': return (LPL3.VAR, ['bool'], [((arg0[2][0]) != (arg1[2][0]))])
185| if op_name == 'egt': return (LPL3.VAR, ['bool'], [((arg0[2][0]) <= (arg1[2][0]))])
186| if op_name == 'gt': return (LPL3.VAR, ['bool'], [((arg0[2][0]) < (arg1[2][0]))])
187| if op_name == 'and': return (LPL3.VAR, ['bool'], [((arg0[2][0]) and (arg1[2][0]))])
188| if op_name == 'or': return (LPL3.VAR, ['bool'], [((arg0[2][0]) or (arg1[2][0]))])
189| if op_name == 'xor': return (LPL3.VAR, ['bool'], [((arg0[2][0]) ^ (arg1[2][0]))])
190|
191| if op_name in ['+','add']: return (LPL3.VAR, arg0[1], [((arg0[2][0]) + (arg1[2][0]))])
192| if op_name in ['-','sub']: return (LPL3.VAR, arg0[1], [((arg0[2][0]) - (arg1[2][0]))])
193| if op_name in ['*','mul']: return (LPL3.VAR, arg0[1], [((arg0[2][0]) * (arg1[2][0]))])
194| if op_name in ['/','div']: return (LPL3.VAR, arg0[1], [((arg0[2][0]) / (arg1[2][0]))])
195| if op_name in ['%','mod']: return (LPL3.VAR, arg0[1], [((arg0[2][0]) % (arg1[2][0]))])
196| if op_name == ['^','pow']: return (LPL3.VAR, arg0[1], [((arg0[2][0]) ** (arg1[2][0]))])
197|
198|
199| if 2 < len(op_args):
200| pass
201|
202|
203|
204|
205|
206| if op_name in namtab:
207| ftn = namtab[op_name]
208| return lpl_3_execute_function_call(namtab, ftn, op_name, op_args)
209|
210|
211| if op_name in namtab[LPL3.GLOBALS]:
212| ftn = namtab[LPL3.GLOBALS][op_name]
213| return lpl_3_execute_function_call(namtab, ftn, op_name, op_args)
214|
215| raise RuntimeError('Unknown operator: "%s"' % op_name)
216|
217|
218| def lpl_3_object_value (namtab, obj):
219| var = lpl_3_execute_item(namtab, obj)
220| if var[0] != LPL3.VAR:
221| raise RuntimeError('Invalid value: %s' % str(var))
222| dtype = var[1]
223| value = var[2][0]
224| if 'array' in dtype:
225| return len(value)
226| return value
227|
228|
229| def lpl_3_execute_var (namtab, obj):
230| dtype = obj[1]
231| value = obj[2][0]
232|
233| if 'array' in dtype:
234|
235| Log.info('ARRAY: len=%d type=%s' % (len(obj[2]),obj[1]))
236| return obj
237|
238|
239| if not value:
240| if len(dtype) == 0:
241| obj[2][:] = [None]
242| elif dtype[0] == 'bool':
243| obj[2][:] = [bool()]
244| elif dtype[0] == 'int':
245| obj[2][:] = [int()]
246| elif dtype[0] == 'float':
247| obj[2][:] = [float()]
248| elif dtype[0] == 'string':
249| obj[2][:] = [str()]
250| elif dtype[0] == 'date':
251| obj[2][:] = [datetime.now()]
252| else:
253|
254| if isinstance(value,tuple):
255| init_value = lpl_3_execute_item(namtab, value)
256| if init_value and (init_value[0] != LPL3.VAR):
257| raise RuntimeError('Invalid initialization object: %s' % str(obj))
258| obj[2][:] = [init_value[2][0]]
259|
260| Log.info('VAR: "%s" type=%s' % (obj[2][0],obj[1]))
261| return obj
262|
263|
264| def lpl_3_execute_reference (namtab, obj):
265| '''Execute Reference. Return value is referred-to object.'''
266| name = obj[1]
267| Log.debug('REF: name=%s' % name)
268| if name in namtab:
269| return namtab[name]
270| g = namtab[LPL3.GLOBALS]
271| if name in g:
272| return g[name]
273| raise RuntimeError('No such object: "%s"' % name)
274|
275|
276| def lpl_3_execute_set (namtab, obj):
277| '''Set a target var's value to another var's value.'''
278| if len(obj) != 3:
279| raise RuntimeError('Illegal (set: a b) object: %s' % str(obj))
280| arg0 = lpl_3_execute_item(namtab, obj[1])
281| arg1 = lpl_3_execute_item(namtab, obj[2])
282| if arg0[0] != LPL3.VAR:
283| raise RuntimeError('Can only (set:) a var: %s' % str(obj))
284| if arg1[0] != LPL3.VAR:
285| raise RuntimeError('Need a value for (set:): %s' % str(obj))
286| arg0[2][:] = arg1[2]
287| Log.info('SET: %s' % str(arg0))
288| return arg0
289|
290|
291| def lpl_3_execute_print (namtab, obj):
292| '''Print a list of objects.'''
293| items_printed = 0
294| for sub_obj in obj[1:]:
295| t = lpl_3_execute_item(namtab, sub_obj)
296| Log.info('PRINT: %s' % str(t))
297| items_printed += 1
298| if len(t) == 0:
299| print('<<NULL>>')
300| continue
301| if t[0] == LPL3.VAR:
302| print(str(t[2]))
303| continue
304| t = lpl_3_execute_item(namtab, t)
305| print(str(t))
306| return (LPL3.VAR, ['int'], [items_printed])
307|
308|
309| def lpl_3_execute_ifelse (namtab, obj_if):
310| test = lpl_3_object_value(namtab, obj_if[1])
311| Log.debug('IF-ELSE: test=%s' % str(test))
312|
313| do_list = obj_if[2] if test else obj_if[3]
314| for sub_obj in do_list[1:]:
315| lpl_3_execute_item(namtab, sub_obj)
316| return obj_if
317|
318|
319| def lpl_3_execute_while (namtab, obj_while):
320|
321| value = lpl_3_object_value(namtab,obj_while[1])
322| while value:
323| for sub_obj in obj_while[2]:
324| obj = lpl_3_execute_item(namtab, sub_obj)
325| if 0 < len(obj):
326| obj_type = obj[0]
327| if obj_type == LPL3.BREAK:
328| break
329| if obj_type == LPL3.NEXT:
330| continue
331|
332| value = lpl_3_object_value(namtab,obj_while[1])
333| return ()
334|
335|
336| def lpl_3_execute_until (namtab, obj_until):
337|
338| value = lpl_3_object_value(namtab,obj_until[1])
339| while not value:
340| for sub_obj in obj_until[2]:
341| obj = lpl_3_execute_item(namtab, sub_obj)
342| if 0 < len(obj):
343| obj_type = obj[0]
344| if obj_type == LPL3.BREAK:
345| break
346| if obj_type == LPL3.NEXT:
347| continue
348|
349| value = lpl_3_object_value(namtab,obj_until[1])
350| return ()
351|
352|
353| def lpl_3_execute_forloop (namtab, obj_for):
354|
355| return ()
356|
357|
358| def lpl_3_execute_select (namtab, obj_sel):
359|
360| return ()
361|
362|
363| def lpl_3_execute_function_call (namtab, obj, name='<function>', args=[]):
364| '''Call function.'''
365| Log.debug('CALL: %s' % name)
366| if obj[0] != LPL3.FUNC:
367| raise RuntimeError('Not a function (%s): %s' % (name,str(obj)))
368|
369| ins = [lpl_3_execute_item(namtab,a) for a in args]
370| symtab = {'function-name':name, 'ins':ins, 'out':()}
371| symtab['caller'] = namtab['function-name']
372| symtab[LPL3.GLOBALS] = namtab[LPL3.GLOBALS]
373| return lpl_3_execute_function(symtab, obj)
374|
375|
376| def lpl_3_execute_function (namtab, obj):
377| '''Execute Function. namtab={ins:[(value,type),..], out:obj} (Return value "out" in namtab.)'''
378| ftn_name = namtab['function-name'] if 'function-name' in namtab else '<function>'
379| rtn_name = namtab['caller'] if 'caller' in namtab else '<unknown>'
380| Log.info('FUNC: name=%s' % ftn_name)
381| Log.debug('FUNC: caller=%s' % rtn_name)
382| Log.trace('FUNC: ins=%s' % str(namtab['ins']))
383| Log.trace('FUNC: nt=%s' % str(list(namtab.keys())))
384|
385| symtab = {'function-name':ftn_name, 'caller':rtn_name}
386| symtab[LPL3.GLOBALS] = namtab[LPL3.GLOBALS]
387|
388|
389| for ix,sub_obj in enumerate(obj[1]):
390| Log.trace('FUNC: in[%d]=%s' % (ix,sub_obj))
391|
392|
393|
394|
395| k = '$%d' % (ix+1)
396| sub_type = sub_obj[0]
397| if sub_type == LPL3.VAR:
398| symtab[k] = sub_obj
399| continue
400| if sub_type == LPL3.LBL:
401| name = sub_obj[1]
402| content = sub_obj[2]
403| if content[0] != LPL3.VAR:
404| raise RuntimeError('Illegal function input; must be a var: %s' % str(content))
405| symtab[k] = content
406| symtab[name] = content
407|
408|
409| for ix,sub_obj in enumerate(obj[2]):
410| Log.trace('FUNC: out[%d]=%s' % (ix,sub_obj))
411|
412|
413| if 0 < ix:
414| raise RuntimeError('Illegal function output; only one allowed! %s' % str(obj[2]))
415| sub_type = sub_obj[0]
416| if sub_type in [LPL3.VAR, LPL3.REF, LPL3.LST, LPL3.FUNC]:
417| symtab['out'] = sub_obj
418| continue
419| if sub_type == LPL3.LBL:
420| name = sub_obj[1]
421| content = sub_obj[2]
422| if content[0] != LPL3.VAR:
423| raise RuntimeError('Illegal function output; must be a var: %s' % str(content))
424| symtab['out'] = content
425| symtab[name] = content
426|
427|
428| for ix,arg in enumerate(namtab['ins']):
429|
430| inp = lpl_3_execute_item(namtab, arg)
431| Log.trace('FUNC: bind[%d]=%s' % (ix,inp))
432| k = '$%d' % (ix+1)
433| if k not in symtab:
434| symtab[k] = inp
435| continue
436| var = symtab[k]
437| if var[1] != inp[1]:
438| raise RuntimeError('Input argument[%d]; wrong type: %s' % (ix,str(inp)))
439| var[2][:] = inp[2]
440|
441|
442| for sub_obj in obj[3]:
443| lpl_3_execute_item(symtab, sub_obj)
444|
445| if 'out' in symtab:
446| namtab['out'] = symtab['out']
447| Log.info('FUNC/EXIT[%s]: out=%s' % (ftn_name,str(namtab['out'])))
448| return namtab['out']
449|
450|
451| def lpl_3_execute_program (namtab, obj):
452| '''Execute Program. (Return value is result of "main" function.)'''
453| Log.trace('PROG: nt=%s' % str(list(namtab.keys())))
454|
455|
456| for ix,sub_obj in enumerate(obj[1:]):
457| Log.debug('PROG: item[%d]=%s' % (ix,str(sub_obj)))
458| if sub_obj[0] == LPL3.LBL:
459| namtab[LPL3.GLOBALS][sub_obj[1]] = sub_obj[2]
460|
461|
462| ftn_name = namtab['execute'] if 'execute' in namtab else 'main'
463| if ftn_name in namtab[LPL3.GLOBALS]:
464| ftn = namtab[LPL3.GLOBALS][ftn_name]
465| if ftn[0] != LPL3.FUNC:
466| raise RuntimeError('Illegal (%s); not a function: %s' % (ftn_name,str(ftn)))
467|
468| Log.debug('PROG: execute=%s;%s' % (ftn_name,str(ftn[1:3])))
469|
470| prog_args = (LPL3.VAR,['string','array'], argv)
471| prog_envs = (LPL3.VAR,['string','array'], environ.items())
472|
473| namtab['function-name'] = ftn_name
474| namtab['caller'] = namtab['program-name']
475| namtab['ins'] = [prog_args, prog_envs]
476| namtab['out'] = ()
477|
478| return lpl_3_execute_function(namtab, ftn)
479|
480|
481| return (LPL3.VAR, ['string'], ['No (main) function found in program!'])
482|
483|
484| def lpl_3_execute (namtab, obj, label=None):
485| '''Execute an object - presumably a Program. (Return value depends on object.)'''
486| Log.trace('EXEC: nt=%s' % str(list(namtab.keys())))
487| if not isinstance(obj,tuple):
488| raise RuntimeError('Invalid Node; Not a tuple: %s' % str(obj))
489|
490|
491| if len(obj) == 0:
492| Log.debug('EXEC: <<NULL>>')
493| return
494|
495| obj_type = obj[0]
496| Log.debug('EXEC: type=%s' % obj_type)
497|
498| if obj_type == LPL3.LBL:
499| name = obj[1]
500| namtab[LPL3.GLOBALS][name] = obj[2]
501| lpl_3_execute(namtab, obj[2], label=name)
502| return
503|
504| if obj_type == LPL3.PROG:
505| namtab['program-name'] = label if label else '<program>'
506| Log.info()
507| Log.info('Program: %s' % namtab['program-name'])
508| Log.info()
509| obj = lpl_3_execute_program(namtab, obj)
510| Log.info()
511| Log.info('OUT: %s' % str(obj))
512| Log.info()
513| return
514|
515| if obj_type == LPL3.FUNC:
516| namtab['function-name'] = label if label else '<function>'
517| namtab['caller'] = '<program>'
518| namtab['ins'] = []
519| namtab['out'] = ()
520| Log.info()
521| Log.info('Function: %s' % namtab['function-name'])
522| Log.info()
523| obj = lpl_3_execute_function(namtab, obj)
524| Log.info()
525| Log.info('OUT: %s' % str(obj))
526| Log.info()
527| return
528|
529| if obj_type == LPL3.NULL:
530| Log.info('EXEC: <<NOP>>')
531| return
532|
533| raise RuntimeError('Invalid Node; Not executible: %s' % str(obj))
534|
535|
536|
537| '''eof'''
538|