lpl6.html
001| """LPL-6. Curry Language with cmd: format commands.
001|
001| Functions:
001| Variables ~dict:
001| Functions ~dict:
001|
001| Classes:
001| variable ~Statement Token Base Class: Variable
001| argument ~Statement Token Class: Argument
001| function ~Statement Token Class: Function
001|
001| Functions:
001| send_to_output ~
001| process_statements ~Process compiled statement list.
001| compile_source ~Compile source code text and return compiled statements.
001| compile_and_run ~Entry point for compiling and executing source code.
001|
001| """
002|
003| from sys import stdin, stdout, stderr
004| from os import environ
005| from datetime import date, datetime, timedelta
006| from math import radians,degrees,sin,cos,tan,atan2, sqrt,log10, pi
007| from math import ceil, floor
008| from logger import logger
009| from goodies import typename
010|
011| Log = logger('LPL-6')
012|
013|
014|
015|
016|
017|
018|
019| class Datum (object):
020| '''Datum class.
020|
020| Given a string value, convert to a binary value if possible.
020| Given a numeric value, set type and make a string copy.
020|
020| Attributes:
020| string_value
020| binary_value
020| datum_type
020|
020| Methods:
020|
020| '''
021| STRING = 'string'
022| BOOL = 'boolean'
023| FLOAT = 'float'
024| INT = 'int'
025| DATE = 'date'
026| COMPLEX = 'complex'
027|
028| TimeFmt = '%Y-%m-%d %H:%M:%S'
029|
030| DateFormats = ['%m-%d-%Y','%m-%d-%y', '%m/%d/%Y','%m/%d/%y', '%Y-%m-%d','%Y/%m/%d']
031|
032| def __init__ (self, value):
033| '''Create a new Datum instance.'''
034| Log.trace(f'Datum({value!s})')
035|
036| def _initialize_attributes (s, n, t):
037| self.string_value = s
038| self.binary_value = n
039| self.datum_type = t
040|
041|
042| if isinstance(value, str):
043|
044| def convert_string_to_numeric (s):
045|
046| if s in ['TRUE','ON','YES']:
047| _initialize_attributes(s, True, Datum.BOOL)
048| return True
049|
050|
051| if s in ['FALSE','OFF','NO']:
052| _initialize_attributes(s, False, Datum.BOOL)
053| return True
054|
055|
056| try:
057| int_value = int(s, base=0)
058| _initialize_attributes(s, int_value, Datum.INT)
059| return True
060| except:
061| pass
062|
063|
064| try:
065| float_value = float(s)
066| _initialize_attributes(s, float_value, Datum.FLOAT)
067| return True
068| except:
069| pass
070|
071|
072| for fmt in Datum.DateFormats:
073| try:
074| datetime_value = datetime.strptime(s, fmt)
075| _initialize_attributes(s, datetime_value, Datum.DATE)
076| return True
077| except:
078| pass
079|
080|
081| return False
082|
083| success = convert_string_to_numeric(value)
084| if not success:
085| _initialize_attributes(value, None, Datum.STRING)
086|
087|
088| elif isinstance(value, complex):
089| _initialize_attributes(str(value), value, Datum.COMPLEX)
090|
091|
092| if isinstance(value, bool):
093| _initialize_attributes(str(value), value, Datum.BOOL)
094|
095|
096| elif isinstance(value, float):
097| _initialize_attributes(str(value), value, Datum.FLOAT)
098|
099|
100| elif isinstance(value, int):
101| _initialize_attributes(str(value), value, Datum.INT)
102|
103|
104| elif isinstance(value, datetime):
105| _initialize_attributes(value.strftime(TimeFmt), value, Datum.DATETIME)
106|
107| @property
108| def strval (self): return self.string_value
109|
110| @property
111| def binval (self): return self.binary_value
112|
113| @property
114| def dtype (self): return self.datum_type
115|
116| def __eq__ (self, other): return (self.strval == other.strval)
117| def __lt__ (self, other): return (self.strval < other.strval)
118| def __gt__ (self, other): return not ((self == other) or (self < other))
119| def __le__ (self, other): return not (other < self)
120| def __ge__ (self, other): return not (self < other)
121| def __ne__ (self, other): return not (self == other)
122|
123| def __bool__ (self):
124| '''Datum is True if string has length or number is non-zero.'''
125| return True if self.binval else False
126|
127| def __int__ (self):
128| '''Return integer if possible.'''
129| if self.dtype == Datum.INT:
130| return self.binval
131| if self.dtype == Datum.FLOAT:
132| return int(self.binval)
133| if self.dtype == Datum.DATE:
134| return self.binval.toordinal()
135| raise ValueError('Datum is not a number!')
136|
137| def __float__ (self):
138| '''Return float if possible.'''
139| if self.dtype == Datum.FLOAT:
140| return self.binval
141| if self.dtype == Datum.INT:
142| return float(self.binval)
143| if self.dtype == Datum.DATE:
144| return self.binval.timestamp()
145| raise ValueError('Datum is not a number!')
146|
147| def __str__ (self):
148| '''String version (includes type).'''
149| return f'{self.strval} ({self.dtype})'
150|
151| def __repr__ (self):
152| return f'<{typename(self)} ({self.strval}) @{id(self):08X}>'
153|
154|
155| class variable:
156| '''Statement Token Base Class: Variable'''
157|
158| def __init__ (self, name):
159| self.name = name
160|
161| def __call__ (self):
162| return self.name
163|
164| def __str__ (self):
165| return self.name
166|
167| def __repr__ (self):
168| return f'<{typename(self)} ({self.name}) @{id(self):08X}>'
169|
170|
171| class argument (variable):
172| '''Statement Token Class: Argument'''
173|
174| def __init__ (self, value):
175| super().__init__(str(value))
176| self.value = value
177|
178| def __call__ (self):
179| return self.value
180|
181| def __repr__ (self):
182| return f'<{typename(self)} ({self.value}) @{id(self):08X}>'
183|
184|
185| class function (variable):
186| '''Statement Token Class: Function'''
187|
188| def __init__ (self, name, function):
189| super().__init__(name)
190| self.function = function
191|
192| def __call__ (self, arg):
193| return self.function(arg)
194|
195| def __str__ (self):
196| return f'{self.name}()'
197|
198| def __repr__ (self):
199| return f'<{typename(self)} "{self.name}" @{id(self):08X}>'
200|
201|
202| Variables = {}
203|
204|
205|
206|
207| def fPrint (a):
208| print('Output: %s' % str(a))
209| retv = len(a) if isinstance(a,list) else 1
210| return argument(retv)
211|
212| def fPrintLines (a):
213| print('Output:')
214| if isinstance(a,list):
215| for line in a:
216| print('> %s' % str(line))
217| return argument(len(a))
218| print('Output: %s' % str(a))
219| return argument(1)
220|
221| def fPrintWords (a):
222| if isinstance(a,list):
223| out = ' '.join([str(word) for word in a])
224| print('Output: %s' % out)
225| return argument(len(a))
226| print('Output: %s' % str(a))
227| return argument(1)
228|
229|
230|
231|
232| def fInt (a):
233| if isinstance(a,list):
234| retv = [int(_a) for _a in a]
235| return argument(retv)
236| return argument(int(a))
237|
238| def fFloat (a):
239| if isinstance(a,list):
240| retv = [float(_a) for _a in a]
241| return argument(retv)
242| return argument(float(a))
243|
244| def fStr (a):
245| if isinstance(a,list):
246| retv = [str(_a) for _a in a]
247| return argument(retv)
248| return argument(str(a))
249|
250| def fDate (a):
251|
252| td = timedelta(int(a))
253| if isinstance(a, list):
254| retv = [date.today()+td for _a in a]
255| return argument(retv)
256| return argument(date.today()+td)
257|
258| def fRound (a):
259| if isinstance(a,list):
260| retv = [round(_a) for _a in a]
261| return argument(retv)
262| return argument(round(a))
263|
264| def fCeiling (a):
265| if isinstance(a,list):
266| retv = [ceil(_a) for _a in a]
267| return argument(retv)
268| return argument(ceil(a))
269|
270| def fFloor (a):
271| if isinstance(a,list):
272| retv = [floor(_a) for _a in a]
273| return argument(retv)
274| return argument(floor(a))
275|
276| def fNeg (a):
277| if isinstance(a,list):
278| retv = [-_a for _a in a]
279| return argument(retv)
280| return argument(-a)
281|
282| def fAbs (a):
283| if isinstance(a,list):
284| retv = [abs(_a) for _a in a]
285| return argument(retv)
286| return argument(abs(a))
287|
288| def fInv (a):
289| if isinstance(a,list):
290| retv = [1.0/_a for _a in a]
291| return argument(retv)
292| return argument(1.0/a)
293|
294| def fSqr (a):
295| if isinstance(a,list):
296| retv = [_a*_a for _a in a]
297| return argument(retv)
298| return argument(a*a)
299|
300| def fSqrt (a):
301| if isinstance(a, list):
302| retv = [sqrt(_a) for _a in a]
303| return argument(retv)
304| return argument(sqrt(a))
305|
306| def fLog (a):
307| if isinstance(a, list):
308| retv = [log10(_a) for _a in a]
309| return argument(retv)
310| return argument(log10(a))
311|
312| def fDeg (a):
313| if isinstance(a, list):
314| retv = [degrees(_a) for _a in a]
315| return argument(retv)
316| return argument(degrees(a))
317|
318| def fRad (a):
319| if isinstance(a, list):
320| retv = [radians(_a) for _a in a]
321| return argument(retv)
322| return argument(radians(a))
323|
324| def fSin (a):
325| if isinstance(a, list):
326| retv = [sin(radians(_a)) for _a in a]
327| return argument(retv)
328| return argument(sin(radians(a)))
329|
330| def fCos (a):
331| if isinstance(a, list):
332| retv = [cos(radians(_a)) for _a in a]
333| return argument(retv)
334| return argument(cos(radians(a)))
335|
336| def fTan (a):
337| if isinstance(a, list):
338| retv = [tan(radians(_a)) for _a in a]
339| return argument(retv)
340| return argument(tan(radians(a)))
341|
342|
343|
344| def fLen (a):
345| if isinstance(a, list):
346| return argument(len(a))
347| return argument(-1)
348|
349| def fSum (a):
350| if isinstance(a, list):
351| return argument(sum(a))
352| return argument(a)
353|
354| def fJoin (a):
355| if isinstance(a, list):
356| s = ''.join([str(x) for x in a])
357| return argument(s)
358| raise NotImplementedError('Join Error: Not a List.')
359|
360|
361|
362| def fSet (a):
363|
364| def f (b):
365|
366| Variables[a] = b
367| return argument(b)
368| return function(f'_set:{a}', f)
369|
370| def fComplex (a):
371| if isinstance(a,list):
372| raise NotImplementedError('Sorry: No list function for making complex numbers.')
373| def f (b):
374| if isinstance(a,list):
375| raise NotImplementedError('Sorry: No list function for making complex numbers.')
376| return argument(complex(a,b))
377| return function('_complex', f)
378|
379| def fAdd (a):
380|
381| def f (b):
382|
383| if isinstance(a,list) and isinstance(b,list):
384| return argument(a+b)
385| if isinstance(a,list):
386| retv = [x+b for x in a]
387| return argument(retv)
388| if isinstance(b,list):
389| retv = [a+x for x in b]
390| return argument(retv)
391| return argument(a+b)
392| return function('_add', f)
393|
394| def fSub (a):
395|
396| def f (b):
397|
398| if isinstance(a,list) and isinstance(b,list):
399| raise NotImplementedError('Sorry: [list]-[list] not implemented.')
400| if isinstance(a,list):
401| retv = [x-b for x in a]
402| return argument(retv)
403| if isinstance(b,list):
404| retv = [a-x for x in b]
405| return argument(retv)
406| return argument(a-b)
407| return function('_sub', f)
408|
409| def fMul (a):
410|
411| def f (b):
412|
413| if isinstance(a,list) and isinstance(b,list):
414| raise NotImplementedError('Sorry: [list]*[list] not implemented.')
415| if isinstance(a,list):
416| retv = [x*b for x in a]
417| return argument(retv)
418| if isinstance(b,list):
419| retv = [a*x for x in b]
420| return argument(retv)
421| return argument(a*b)
422| return function('_mul', f)
423|
424| def fDiv (a):
425|
426| def f (b):
427|
428| if isinstance(a,list) and isinstance(b,list):
429| raise NotImplementedError('Sorry: [list]/[list] not implemented.')
430| if isinstance(a,list):
431| retv = [x/b for x in a]
432| return argument(retv)
433| if isinstance(b,list):
434| retv = [a/x for x in b]
435| return argument(retv)
436| return argument(a/b)
437| return function('_div', f)
438|
439| def fPow (a):
440|
441| def f (b):
442|
443| if isinstance(a,list) and isinstance(b,list):
444| raise NotImplementedError('Sorry: [list]**[list] not implemented.')
445| if isinstance(a,list):
446| retv = [pow(x,b) for x in a]
447| return argument(retv)
448| if isinstance(b,list):
449| retv = [pow(a,x) for x in b]
450| return argument(retv)
451| return argument(a**b)
452| return function('_pow', f)
453|
454| def fAtan2 (a):
455|
456| def f (b):
457|
458| return argument(degrees(atan2(a,b)))
459| return function('_atan2', f)
460|
461| def fList (a):
462|
463| buf = [a]
464| def f (b):
465|
466| if b == ']':
467| return argument(buf)
468| buf.append(b)
469|
470| return function('_lst', f)
471| return function('_lst', f)
472|
473|
474| Functions = {
475| 'prn':fPrint, 'prnl':fPrintLines, 'prnw':fPrintWords,
476| 'set':fSet,
477| 'int':fInt, 'float':fFloat, 'complex':fComplex, 'str':fStr,
478| 'round':fRound, 'rup':fCeiling, 'rdn':fFloor,
479| 'neg':fNeg, 'abs':fAbs, 'inv':fInv, 'sqr':fSqr, 'sqrt':fSqrt, 'log':fLog,
480| 'add':fAdd, 'sub':fSub, 'mul':fMul, 'div':fDiv, 'pow':fPow,
481| 'deg':fDeg, 'rad':fRad, 'sin':fSin, 'cos':fCos, 'tan':fTan, 'atan2':fAtan2,
482| 'date':fDate,
483| '[':fList, 'len':fLen, 'sum':fSum, 'join':fJoin,
484| }
485|
486|
487|
488|
489|
490| def send_to_output (txt='', verbose=False):
491| '''Send text to Log and optionally to stdout.'''
492| if verbose:
493| print(txt)
494| Log.info(txt)
495|
496|
497| def process_statements (stmts, verbose=False):
498| '''Process compiled statement list.'''
499| Log.info(f'Process-Statements({len(stmts)} nodes)')
500| Log.info()
501| Stack = []
502|
503| def pretty_print (node):
504| '''Pretty printer for nodes.'''
505|
506| if isinstance(node, function):
507| return f'{node} {node!r} {id(node.function):08x}>'
508|
509| if isinstance(node, argument):
510| return f'{node} {node!r}'
511|
512| if isinstance(node, variable):
513| name = str(node)
514| valu = Variables[name] if name in Variables else None
515| return f'{name} = {valu}'
516|
517| return '###ERR###'
518|
519| def process_node (node):
520| '''Recursive node processor.'''
521| Log.trace(f'processNode({pretty_print(node)})')
522|
523|
524| if isinstance(node, function):
525| Stack.append(node)
526| return node
527|
528|
529|
530| if isinstance(node, variable):
531| name = str(node)
532| if name in Variables:
533| valu = Variables[name]
534| node = argument(valu)
535| Log.trace(f'VAR {name} = {valu}')
536| else:
537| Log.trace(f'ARG {name}')
538|
539|
540|
541| if len(Stack) == 0:
542| return node
543|
544|
545| f = Stack.pop()
546| retval = f(node())
547|
548| Log.trace(f'node=>{retval} ({typename(retval)})')
549|
550|
551| return process_node(retval)
552|
553| raise RuntimeError(f'Unknown Node Type: {typename(node)}')
554|
555|
556| Variables.clear()
557| a = argument(None)
558|
559| results = [a]
560| for stmt in stmts:
561| a = process_node(stmt)
562| Log.debug(f'RETV: {pretty_print(a)}')
563| results.insert(0,a)
564|
565| return results
566|
567|
568| def compile_source (source_text, verbose=False):
569| '''Compile source code text and return compiled statements.'''
570| Log.info(f'Compile-Source({len(source_text)} chars)')
571| Log.info()
572| Log.trace(source_text.replace('\n',' '))
573| Log.trace()
574|
575|
576|
577| def character_handler (ch):
578| if ch == ':': return ': '
579| if ch == '[': return ' [ '
580| if ch == ']': return ' ] '
581| return ch
582|
583| t = [character_handler(ch) for ch in source_text]
584| s = ''.join(t)
585|
586|
587| toks = s.split()
588|
589|
590| stmts = []
591| for tok in toks:
592| Log.trace(f'token={tok}')
593|
594|
595| if tok.endswith(':'):
596| name = tok[0:-1]
597| fctn = Functions[name]
598| item = function(name, fctn)
599| stmts.append(item)
600|
601|
602| elif tok == '[':
603| fctn = Functions[tok]
604| item = function('list', fctn)
605| stmts.append(item)
606|
607|
608| else:
609|
610| val = Datum(tok)
611| if val.dtype==Datum.STRING:
612| item = variable(val.strval)
613| else:
614| item = argument(val.binval)
615| stmts.append(item)
616| Log.trace()
617|
618|
619| send_to_output('Statements:', verbose=verbose)
620| for stmt in stmts:
621| send_to_output(repr(stmt), verbose=verbose)
622| send_to_output(verbose=verbose)
623|
624|
625| return stmts
626|
627|
628| def compile_and_run (source_text, verbose=False):
629| '''Entry point for compiling and executing source code.'''
630| Log.info(f'Compile-and-Run({len(source_text)} chars)')
631| Log.info()
632|
633|
634| stmts = compile_source(source_text, verbose=verbose)
635|
636|
637| retval = process_statements(stmts, verbose=verbose)
638| send_to_output(f'Return: {retval} ({typename(retval)})', verbose=verbose)
639| send_to_output(verbose=verbose)
640|
641| send_to_output('Variables:', verbose=verbose)
642| for name,valu in sorted(Variables.items(), key=lambda x:str(x[0])):
643| send_to_output(f'{name}: {valu}', verbose=verbose)
644| send_to_output(verbose=verbose)
645|
646| return retval
647|
648|
649|
650|
651| if __name__ == '__main__':
652| src = 'set:a 2.71812 set:b mul:2 3.14159 set:c 1.618033 mul: div:a b c'
653| out = compile_and_run(src)
654| print(f'Source: {src}')
655| print(f'Answer: {out[0]}')
656| print()
657| for ix,node in enumerate(out, start=1):
658| print(f'{ix:2}: {node}')
659| print()
660|
661| '''eof'''
662|