curry_lang.html


001| """Curry Language.
001| 
001| A simple language implementation that uses currying so that all functions take only one
001| parameter. For instance, rather than a function ADD(a,b), we have ADD(a)(b). The function
001| itself takes a single argument (the first parameter of the ADD operation), and it *returns*
001| an anonymous function that also takes only one parameter (the second parameter of the ADD).
001| 
001| The format of the language is that operators (functions) have names that end with a colon,
001| so the ADD operation above would be written:
001| 
001|     add:a b
001| 
001| The compiler generates a simple linear list of tokens that the language engine executes.
001| The language engine iterates over that list executing the tokens.
001| 
001| Commands:
001|     text        do_run_source_text          Compile and Execute a string of source code.
001|     file        do_run_source_file          Compile and Execute a source code file.
001|     listf       do_function_list            List the language functions.
001|     test        do_test                     (for testing)
001| 
001| """

002| ####################################################################################################
003| from sys import argv, exc_info
004| from traceback import extract_tb
005| from os import path
006| from datetime import date, time, datetime, timedelta
007| from math import ceil,floor, radians,degrees,sin,cos,tan,atan2, sqrt,log10, pi
008| from logger import logger,info,debug,trace, LogFilenameTimestamp
009| from lexer import Datum
010| from goodies import KWARG
011| ####################################################################################################
012| BasePath = r'C:\CJS\prj\Python\app\langs'
013| Log = logger('CurryLang')
014| 
015| CMND = 'text'
016| ARGS = {
017|     'fname': 'curry.in',
018|     'fpath': BasePath,
019|     'src': 'set:a 2.71828 set:b 3.14159 prn:add:a b',
020| }
021| 
022| SrcText1 = '''\
022| set:e 2.718281828
022| set:end exec
022| set:tag $here
022| set:list-1 [answer = e ; ]
022| set:list-2 [end tag]
022| set:list-3 add:list-1 list-2
022| prn:join:[items-in-list= len:list-3]
022| prn:join:list-3
022| sum:add:[1 2 3][4 5 6]
022| '''

023| SrcText2 = '''\
023| prn:date:-1
023| set:a [1 2 3]
023| set:b str:a
023| prn:[a b]
023| prnw:a prnw:b
023| prnl:a prnl:b
023| end
023| '''

024| SrcText3 = '''\
024| set:exit 1
024| set:n 1.45
024| prnl:[n rdn:n round:n rup:n]
024| prnl: sqrt: pow:10 [1 2 3 4 5 6 7 8 9]
024| exit
024| '''

025| SrcText4 = '''\
025| set:a [0 1 0 1 0]
025| prn:a
025| '''

026| 
027| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
028| class variable (object):
029|     """Statement Token Base Class: Variable"""
030|     def __init__ (self, name):
031|         self.n = name
032|     def __call__ (self):
033|         return self.n
034|     def __str__ (self):
035|         return self.n
036|     def __repr__ (self):
037|         return 'variable: "%s"' % self.n
038| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
039| class argument (variable):
040|     """Statement Token Class: Argument"""
041|     def __init__ (self, value):
042|         super().__init__(str(value))
043|         self.v = value
044|     def __call__ (self):
045|         return self.v
046|     def __repr__ (self):
047|         return 'argument: %s' % self.v
048| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
049| class function (variable):
050|     """Statement Token Class: Function"""
051|     def __init__ (self, name, function):
052|         super().__init__(name)
053|         self.f = function
054|     def __call__ (self, arg):
055|         return self.f(arg)
056|     def __str__ (self):
057|         return '%s()' % self.n
058|     def __repr__ (self):
059|         return 'function: %s() %s@%08X' % (self.n, self.f.__name__, id(self.f))
060| 
061| ##------------------------------------------------------------------------------------------------##
062| Variables = {}
063| 
064| ##================================================================================================##
065| ## Output Functions (unary)...
066| ##================================================================================================##
067| def fPrint (a):
068|     print('Output: %s' % str(a))
069|     retv = len(a) if isinstance(a,list) else 1
070|     return argument(retv)
071| ##================================================================================================##
072| def fPrintLines (a):
073|     print('Output:')
074|     if isinstance(a,list):
075|         for line in a:
076|             print('> %s' % str(line))
077|         return argument(len(a))
078|     print('Output: %s' % str(a))
079|     return argument(1)
080| ##================================================================================================##
081| def fPrintWords (a):
082|     if isinstance(a,list):
083|         out = ' '.join([str(word) for word in a])
084|         print('Output: %s' % out)
085|         return argument(len(a))
086|     print('Output: %s' % str(a))
087|     return argument(1)
088| 
089| ##================================================================================================##
090| ## Unary Functions...
091| ##================================================================================================##
092| def fInt (a):
093|     if isinstance(a,list):
094|         retv = [int(_a) for _a in a]
095|         return argument(retv)
096|     return argument(int(a))
097| ##================================================================================================##
098| def fFloat (a):
099|     if isinstance(a,list):
100|         retv = [float(_a) for _a in a]
101|         return argument(retv)
102|     return argument(float(a))
103| ##================================================================================================##
104| def fStr (a):
105|     if isinstance(a,list):
106|         retv = [str(_a) for _a in a]
107|         return argument(retv)
108|     return argument(str(a))
109| ##================================================================================================##
110| def fDate (a):
111|     #print('fDate(%s:%s)' % (a,type(a).__name__))
112|     td = timedelta(int(a))
113|     if isinstance(a, list):
114|         retv = [date.today()+td for _a in a]
115|         return argument(retv)
116|     return argument(date.today()+td)
117| ##================================================================================================##
118| def fRound (a):
119|     if isinstance(a,list):
120|         retv = [round(_a) for _a in a]
121|         return argument(retv)
122|     return argument(round(a))
123| ##================================================================================================##
124| def fCeiling (a):
125|     if isinstance(a,list):
126|         retv = [ceil(_a) for _a in a]
127|         return argument(retv)
128|     return argument(ceil(a))
129| ##================================================================================================##
130| def fFloor (a):
131|     if isinstance(a,list):
132|         retv = [floor(_a) for _a in a]
133|         return argument(retv)
134|     return argument(floor(a))
135| ##================================================================================================##
136| def fNeg (a):
137|     if isinstance(a,list):
138|         retv = [-_a for _a in a]
139|         return argument(retv)
140|     return argument(-a)
141| ##================================================================================================##
142| def fAbs (a):
143|     if isinstance(a,list):
144|         retv = [abs(_a) for _a in a]
145|         return argument(retv)
146|     return argument(abs(a))
147| ##================================================================================================##
148| def fInv (a):
149|     if isinstance(a,list):
150|         retv = [1.0/_a for _a in a]
151|         return argument(retv)
152|     return argument(1.0/a)
153| ##================================================================================================##
154| def fSqr (a):
155|     if isinstance(a,list):
156|         retv = [_a*_a for _a in a]
157|         return argument(retv)
158|     return argument(a*a)
159| ##================================================================================================##
160| def fSqrt (a):
161|     if isinstance(a, list):
162|         retv = [sqrt(_a) for _a in a]
163|         return argument(retv)
164|     return argument(sqrt(a))
165| ##================================================================================================##
166| def fLog (a):
167|     if isinstance(a, list):
168|         retv = [log10(_a) for _a in a]
169|         return argument(retv)
170|     return argument(log10(a))
171| ##================================================================================================##
172| def fDeg (a):
173|     if isinstance(a, list):
174|         retv = [degrees(_a) for _a in a]
175|         return argument(retv)
176|     return argument(degrees(a))
177| ##================================================================================================##
178| def fRad (a):
179|     if isinstance(a, list):
180|         retv = [radians(_a) for _a in a]
181|         return argument(retv)
182|     return argument(radians(a))
183| ##================================================================================================##
184| def fSin (a):
185|     if isinstance(a, list):
186|         retv = [sin(radians(_a)) for _a in a]
187|         return argument(retv)
188|     return argument(sin(radians(a)))
189| ##================================================================================================##
190| def fCos (a):
191|     if isinstance(a, list):
192|         retv = [cos(radians(_a)) for _a in a]
193|         return argument(retv)
194|     return argument(cos(radians(a)))
195| ##================================================================================================##
196| def fTan (a):
197|     if isinstance(a, list):
198|         retv = [tan(radians(_a)) for _a in a]
199|         return argument(retv)
200|     return argument(tan(radians(a)))
201| ##================================================================================================##
202| ## List Functions...
203| ##================================================================================================##
204| def fLen (a):
205|     if isinstance(a, list):
206|         return argument(len(a))
207|     return argument(-1)
208| ##================================================================================================##
209| def fSum (a):
210|     if isinstance(a, list):
211|         return argument(sum(a))
212|     return argument(a)
213| ##================================================================================================##
214| def fJoin (a):
215|     if isinstance(a, list):
216|         s = ''.join([str(x) for x in a])
217|         return argument(s)
218|     raise NotImplementedError('Join Error: Not a List.')
219| ##================================================================================================##
220| ## Binary Functions...
221| ##================================================================================================##
222| def fSet (a):
223|     #print('fSet-0(%s:%s)' % (a,type(a).__name__))
224|     def f (b):
225|         #print('fSet-1(%s:%s)' % (b,type(b).__name__))
226|         Variables[a] = b
227|         return argument(b)
228|     return function(('_set:%s' % a), f)
229| ##================================================================================================##
230| def fComplex (a):
231|     if isinstance(a,list):
232|         raise NotImplementedError('Sorry: No list function for making complex numbers.')
233|     def f (b):
234|         if isinstance(a,list):
235|             raise NotImplementedError('Sorry: No list function for making complex numbers.')
236|         return argument(complex(a,b))
237|     return function('_complex', f)
238| ##================================================================================================##
239| def fAdd (a):
240|     #print('fAdd-0(%s:%s)' % (a,type(a).__name__))
241|     def f (b):
242|         #print('fAdd-1(%s:%s)' % (b,type(b).__name__))
243|         if isinstance(a,list) and isinstance(b,list):
244|             return argument(a+b)
245|         if isinstance(a,list):
246|             retv = [x+b for x in a]
247|             return argument(retv)
248|         if isinstance(b,list):
249|             retv = [a+x for x in b]
250|             return argument(retv)
251|         return argument(a+b)
252|     return function('_add', f)
253| ##================================================================================================##
254| def fSub (a):
255|     #print('fSub-0(%s:%s)' % (a,type(a).__name__))
256|     def f (b):
257|         #print('fSub-1(%s:%s)' % (b,type(b).__name__))
258|         if isinstance(a,list) and isinstance(b,list):
259|             raise NotImplementedError('Sorry: [list]-[list] not implemented.')
260|         if isinstance(a,list):
261|             retv = [x-b for x in a]
262|             return argument(retv)
263|         if isinstance(b,list):
264|             retv = [a-x for x in b]
265|             return argument(retv)
266|         return argument(a-b)
267|     return function('_sub', f)
268| ##================================================================================================##
269| def fMul (a):
270|     #print('fMul-0(%s:%s)' % (a,type(a).__name__))
271|     def f (b):
272|         #print('fMul-1(%s:%s)' % (b,type(b).__name__))
273|         if isinstance(a,list) and isinstance(b,list):
274|             raise NotImplementedError('Sorry: [list]*[list] not implemented.')
275|         if isinstance(a,list):
276|             retv = [x*b for x in a]
277|             return argument(retv)
278|         if isinstance(b,list):
279|             retv = [a*x for x in b]
280|             return argument(retv)
281|         return argument(a*b)
282|     return function('_mul', f)
283| ##================================================================================================##
284| def fDiv (a):
285|     #print('fDiv-0(%s:%s)' % (a,type(a).__name__))
286|     def f (b):
287|         #print('fDiv-1(%s:%s)' % (b,type(b).__name__))
288|         if isinstance(a,list) and isinstance(b,list):
289|             raise NotImplementedError('Sorry: [list]/[list] not implemented.')
290|         if isinstance(a,list):
291|             retv = [x/b for x in a]
292|             return argument(retv)
293|         if isinstance(b,list):
294|             retv = [a/x for x in b]
295|             return argument(retv)
296|         return argument(a/b)
297|     return function('_div', f)
298| ##================================================================================================##
299| def fPow (a):
300|     #print('fPow-0(%s:%s)' % (a,type(a).__name__))
301|     def f (b):
302|         #print('fPow-1(%s:%s)' % (b,type(b).__name__))
303|         if isinstance(a,list) and isinstance(b,list):
304|             raise NotImplementedError('Sorry: [list]**[list] not implemented.')
305|         if isinstance(a,list):
306|             retv = [pow(x,b) for x in a]
307|             return argument(retv)
308|         if isinstance(b,list):
309|             retv = [pow(a,x) for x in b]
310|             return argument(retv)
311|         return argument(a**b)
312|     return function('_pow', f)
313| ##================================================================================================##
314| def fAtan2 (a):
315|     #print('fAtan2-0(%s:%s)' % (a,type(a).__name__))
316|     def f (b):
317|         #print('fAtan2-1(%s:%s)' % (b,type(b).__name__))
318|         return argument(degrees(atan2(a,b)))
319|     return function('_atan2', f)
320| ##================================================================================================##
321| def fList (a):
322|     #print('fList-0(%s:%s)' % (a,type(a).__name__))
323|     buf = [a]
324|     def f (b):
325|         #print('fList-%d(%s:%s)' % (len(buf),b,type(b).__name__))
326|         if b == ']':
327|             return argument(buf)
328|         buf.append(b)
329|         #print('fList-0: buf=%s' % str(buf))
330|         return function('_lst', f)
331|     return function('_lst', f)
332| 
333| ##------------------------------------------------------------------------------------------------##
334| ##TODO: and,or,xor, eq,ne,lt,elt,egt,gt, ...?
335| ##ATTN: random, today, date
336| Functions = {
337|     'prn':fPrint, 'prnl':fPrintLines, 'prnw':fPrintWords,
338|     'set':fSet,
339|     'int':fInt, 'float':fFloat, 'complex':fComplex, 'str':fStr,
340|     'round':fRound, 'rup':fCeiling, 'rdn':fFloor,
341|     'neg':fNeg, 'abs':fAbs, 'inv':fInv, 'sqr':fSqr, 'sqrt':fSqrt, 'log':fLog,
342|     'add':fAdd, 'sub':fSub, 'mul':fMul, 'div':fDiv, 'pow':fPow,
343|     'deg':fDeg, 'rad':fRad, 'sin':fSin, 'cos':fCos, 'tan':fTan, 'atan2':fAtan2,
344|     'date':fDate,
345|     '[':fList, 'len':fLen, 'sum':fSum, 'join':fJoin,
346| }
347| 
348| ##================================================================================================##
349| def process_statements (stmts):
350|     """Process compiled statement list."""
351|     print("PROCESS STATEMENTS")
352|     Stack = []
353| 
354|     # Recursive node processor...
355|     def process_node (n):
356|         # If node is a function, just push it on the stack...
357|         if isinstance(n, function):
358|             Stack.append(n)
359|             return n
360|         # If node is a variable, get its value...
361|         if isinstance(n, variable):
362|             name = str(n)
363|             if name in Variables:
364|                 valu = Variables[name]
365|                 n = argument(valu)
366|             # Node is an argument (or unassigned variable), so apply it
367|             # to a function (unless there aren't any; then we're done)...
368|             if len(Stack) == 0:
369|                 return n
370|             # EXECUTE FUNCTION!
371|             f = Stack.pop()
372|             retval = f(n())
373|             #print('returns: %s (%s)' % (retval, type(retval).__name__))
374|             # And recurse on the result...
375|             return process_node(retval)
376|         raise RuntimeError('Unknown Node Type: "%s"' % type(n).__name__)
377| 
378|     # Execute the nodes of the statement...
379|     Variables.clear()
380|     a = argument(None)
381|     for stmt in stmts:
382|         a = process_node(stmt)
383|     return a
384| 
385| ##================================================================================================##
386| def compile_source (source_text, show_statements=False):
387|     """Compile source code text and return compiled statements."""
388|     print("COMPILE SOURCE")
389|     print(source_text)
390|     print()
391| 
392|     def character_handler (ch):
393|         if ch == ':': return ': '
394|         if ch == '[': return ' [ '
395|         if ch == ']': return ' ] '
396|         return ch
397| 
398|     # First, break apart tokens that follow a ':' with no space...
399|     t = [character_handler(ch) for ch in source_text]
400|     s = ''.join(t)
401|     # And then just tokenize based on spaces...
402|     toks = s.split()
403| 
404|     # For each token...
405|     stmts = []
406|     for tok in toks:
407|         # If it's a function, create a Function...
408|         if tok.endswith(':'):
409|             name = tok[0:-1]                # strip the colon
410|             fctn = Functions[name]          # find the function
411|             item = function(name, fctn)     # create a new node
412|             stmts.append(item)              # add it to stmts
413|         elif tok == '[':
414|             fctn = Functions[tok]
415|             item = function('list', fctn)
416|             stmts.append(item)
417|         # Otherwise just create an Argument...
418|         else:
419|             val = Datum(tok)
420|             obj = variable(tok) if val.t==Datum.STRING else argument(val())
421|             stmts.append(obj)
422|     # List the statements to the log...
423|     if show_statements:
424|         print('Compiled Statements:')
425|         for stmt in stmts:
426|             print(repr(stmt))
427|         print()
428|     # Return the list of statements...
429|     return stmts
430| 
431| ##================================================================================================##
432| def compile_and_run (source_text, show_statements=False):
433|     """Entry point for compiling and executing source code."""
434|     # Compile...
435|     stmts = compile_source(source_text, show_statements=show_statements)
436|     # Execute...
437|     retval = process_statements(stmts)
438|     print()
439|     print('Return: %s (%s)' % (retval, type(retval).__name__))
440|     print()
441|     print('Variables:')
442|     for name,valu in sorted(Variables.items(), key=lambda x:str(x[0])):
443|         print('%s: %s' % (name,valu))
444|     print()
445|     return retval
446| 
447| 
448| ##================================================================================================##
449| def do_run_source_text (**kwargs):
450|     """CMND: Compile and Execute a string of source code."""
451|     src = KWARG('src', '', str, kwargs)
452|     show_stmts = KWARG('v1', '0', str, kwargs)
453|     Log.info('RUN-TEXT:: %s' % str(list(kwargs.keys())))
454|     Log.debug('src="%s"' % src)
455|     Log.debug('show_statements=%s' % ('Yes' if src else 'No'))
456|     Log.info()
457|     retv = compile_and_run(src, show_statements=show_stmts)
458|     Log.info()
459|     return 'Done'
460| ##================================================================================================##
461| def do_run_source_file (**kwargs):
462|     """CMND: Compile and Execute a source code file."""
463|     fpath = KWARG('fpath', BasePath, str, kwargs)
464|     fname = KWARG('fname', 'curry.in', str, kwargs)
465|     show_stmts = KWARG('v1', '0', str, kwargs)
466|     Log.info('RUN-FILE:: %s' % str(list(kwargs.keys())))
467|     Log.debug('fpath="%s"' % fpath)
468|     Log.debug('fname="%s"' % fname)
469|     Log.info()
470|     retv = compile_and_run(source_text, show_statements=show_stmts)
471|     Log.info()
472|     return 'Done'
473| 
474| ##================================================================================================##
475| def do_function_list (**kwargs):
476|     """List the functions."""
477|     for op in sorted(Functions.keys()):
478|         fctn = Functions[op]
479|         print('%s: %s' % (op, fctn.__name__))
480|     return 'Done'
481| 
482| ##================================================================================================##
483| def do_test (**kwargs):
484|     """Do a test."""
485|     fpath = KWARG('fpath', BasePath, str, kwargs)
486|     fname = KWARG('fname', 'test.out', str, kwargs)
487|     Log.info('test:: %s' % str(list(kwargs.keys())))
488|     Log.debug('fpath="%s"' % fpath)
489|     Log.debug('fname="%s"' % fname)
490|     Log.info()
491|     Log.info()
492|     return 'Done'
493| ####################################################################################################
494| def dispatch (cmd, **kwargs):
495|     """Dispatch to a module function based on CMD."""
496|     Log.info('CMD: %s' % cmd)
497|     for kw in kwargs:
498|         Log.debug('argument[%s]: %s' % (kw,kwargs[kw]))
499|     Log.info()
500|     if cmd == 'text': return do_run_source_text(**kwargs)
501|     if cmd == 'file': return do_run_source_file(**kwargs)
502|     if cmd == 'listf': return do_function_list(**kwargs)
503|     if cmd == 'test': return do_test(**kwargs)
504|     return 'Nothing to do!'
505| ####################################################################################################
506| if __name__ == '__main__':
507|     print('autorun: %s' % argv[0])
508|     #Log.start(path.join(BasePath,LogFilenameTimestamp('currylang_%s.log')))
509|     Log.start(path.join(BasePath,'currylang.log'))
510|     Log.level(trace())
511|     Log.info(argv[0])
512|     Log.info()
513|     cmd = argv[1] if 1 < len(argv) else CMND
514|     kwargs = ARGS
515|     for a in argv[2:]:
516|         nv = a.split('=', 1)
517|         kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
518|         Log.debug('%s: "%s"' % (nv[0], kwargs[nv[0]]))
519|     try:
520|         obj = dispatch(cmd, **kwargs)
521|         print()
522|         print(obj)
523|         Log.info()
524|         Log.info(obj)
525|     except:
526|         etype, evalue, tb = exc_info()
527|         ts = extract_tb(tb)
528|         Log.error()
529|         Log.error('%s: %s' % (etype.__name__,str(evalue)))
530|         Log.error()
531|         for t in ts[-5:]:
532|             Log.error('[%d] %s (%s)' % (t[1], t[2], t[0]))
533|             Log.error(' %s' % t[3])
534|             Log.error()
535|         raise
536|     finally:
537|         Log.end()
538| ####################################################################################################
539| """eof"""
540|