OSDN Git Service

Minor cleanup.
[joypy/Thun.git] / joy / library.py
1 # -*- coding: utf-8 -*-
2 #
3 #    Copyright © 2014-2020 Simon Forman
4 #
5 #    This file is part of Thun
6 #
7 #    Thun is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU General Public License as published by
9 #    the Free Software Foundation, either version 3 of the License, or
10 #    (at your option) any later version.
11 #
12 #    Thun is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU General Public License for more details.
16 #
17 #    You should have received a copy of the GNU General Public License
18 #    along with Thun.  If not see <http://www.gnu.org/licenses/>. 
19 #
20 '''
21 This module contains the Joy function infrastructure and a library of
22 functions.  Its main export is a Python function initialize() that
23 returns a dictionary of Joy functions suitable for use with the joy()
24 function.
25 '''
26 from builtins import map, object, range, zip
27
28 from inspect import getdoc
29 from functools import wraps
30 from itertools import count
31 from inspect import getmembers, isfunction
32 import operator, math
33
34 from .parser import text_to_expression, Symbol
35 from .utils import generated_library as genlib
36 from .utils.stack import (
37         concat,
38         expression_to_string,
39         iter_stack,
40         list_to_stack,
41         pick,
42         )
43
44
45 HELP_TEMPLATE = '''\
46
47 ==== Help on %s ====
48
49 %s
50
51 ---- end (%s)
52 '''
53
54
55 # This is the main dict we're building.
56 _dictionary = {}
57
58
59 def inscribe(function):
60         '''A decorator to inscribe functions into the default dictionary.'''
61         _dictionary[function.name] = function
62         return function
63
64
65 def initialize():
66         '''Return a dictionary of Joy functions for use with joy().'''
67         return _dictionary.copy()
68
69
70 ALIASES = (
71         ('add', ['+']),
72         ('and', ['&']),
73         ('bool', ['truthy']),
74         ('mul', ['*']),
75         ('floordiv', ['/floor', '//']),
76         ('floor', ['round']),
77         ('truediv', ['/', 'div']),
78         ('mod', ['%', 'rem', 'remainder', 'modulus']),
79         ('eq', ['=']),
80         ('ge', ['>=']),
81         ('getitem', ['pick', 'at']),
82         ('gt', ['>']),
83         ('le', ['<=']),
84         ('lshift', ['<<']),
85         ('lt', ['<']),
86         ('ne', ['<>', '!=']),
87         ('rshift', ['>>']),
88         ('sub', ['-']),
89         ('xor', ['^']),
90         ('succ', ['++']),
91         ('pred', ['--']),
92         ('rolldown', ['roll<']),
93         ('rollup', ['roll>']),
94         ('eh', ['?']),
95         ('id', [u'•']),
96         )
97
98
99 def add_aliases(D, A):
100         '''
101         Given a dict and a iterable of (name, [alias, ...]) pairs, create
102         additional entries in the dict mapping each alias to the named function
103         if it's in the dict.  Aliases for functions not in the dict are ignored.
104         '''
105         for name, aliases in A:
106                 try:
107                         F = D[name]
108                 except KeyError:
109                         continue
110                 for alias in aliases:
111                         D[alias] = F
112
113
114 definitions = ('''\
115 ? dup truthy
116 *fraction [uncons] dip uncons [swap] dip concat [*] infra [*] dip cons
117 *fraction0 concat [[swap] dip * [*] dip] infra
118 anamorphism [pop []] swap [dip swons] genrec
119 average [sum 1.0 *] [size] cleave /
120 binary nullary [popop] dip
121 cleave fork [popd] dip
122 codireco cons dip rest cons
123 dinfrirst dip infra first
124 unstack ? [uncons ?] loop pop
125 down_to_zero [0 >] [dup --] while
126 dupdipd dup dipd
127 enstacken stack [clear] dip
128 flatten [] swap [concat] step
129 fork [i] app2
130 gcd 1 [tuck modulus dup 0 >] loop pop
131 ifte [nullary not] dipd branch
132 ii [dip] dupdip i
133 least_fraction dup [gcd] infra [div] concat map
134 make_generator [codireco] ccons
135 nullary [stack] dinfrirst
136 of swap at
137 pam [i] map
138 tailrec [i] genrec
139 product 1 swap [*] step
140 quoted [unit] dip
141 range [0 <=] [1 - dup] anamorphism
142 range_to_zero unit [down_to_zero] infra
143 run [] swap infra
144 size 0 swap [pop ++] step
145 sqr dup mul
146 step_zero 0 roll> step
147 swoncat swap concat
148 tailrec [i] genrec
149 ternary unary [popop] dip
150 unary nullary popd
151 unquoted [i] dip
152 while swap [nullary] cons dup dipd concat loop
153 '''
154 #
155 #
156 # ifte == [nullary] dipd swap branch
157 # genrec == [[genrec] cons cons cons cons] nullary swons concat ifte
158
159 # Another definition for while. FWIW
160 # while == over [[i] dip nullary] ccons [nullary] dip loop
161
162 ##ccons == cons cons
163 ##unit == [] cons
164 ##second == rest first
165 ##third == rest rest first
166 ##swons == swap cons
167
168 ##Zipper
169 ##z-down == [] swap uncons swap
170 ##z-up == swons swap shunt
171 ##z-right == [swons] cons dip uncons swap
172 ##z-left == swons [uncons swap] dip swap
173
174 ##Quadratic Formula
175 ##divisor == popop 2 *
176 ##minusb == pop neg
177 ##radical == swap dup * rollup * 4 * - sqrt
178 ##root1 == + swap /
179 ##root2 == - swap /
180 ##q0 == [[divisor] [minusb] [radical]] pam
181 ##q1 == [[root1] [root2]] pam
182 ##quadratic == [q0] ternary i [q1] ternary
183
184 # Project Euler
185 ##'''\
186 ##PE1.1 == + dup [+] dip
187 ##PE1.2 == dup [3 & PE1.1] dip 2 >>
188 ##PE1.3 == 14811 swap [PE1.2] times pop
189 ##PE1 == 0 0 66 [7 PE1.3] times 4 PE1.3 pop
190 ##'''
191 #PE1.2 == [PE1.1] step
192 #PE1 == 0 0 66 [[3 2 1 3 1 2 3] PE1.2] times [3 2 1 3] PE1.2 pop
193 )
194
195
196 def FunctionWrapper(f):
197         '''Set name attribute.'''
198         if not f.__doc__:
199                 raise ValueError('Function %s must have doc string.' % f.__name__)
200         f.name = f.__name__.rstrip('_')  # Don't shadow builtins.
201         return f
202
203
204 def SimpleFunctionWrapper(f):
205         '''
206         Wrap functions that take and return just a stack.
207         '''
208         @FunctionWrapper
209         @wraps(f)
210         def inner(stack, expression, dictionary):
211                 return f(stack), expression, dictionary
212         return inner
213
214
215 def BinaryBuiltinWrapper(f):
216         '''
217         Wrap functions that take two arguments and return a single result.
218         '''
219         @FunctionWrapper
220         @wraps(f)
221         def inner(stack, expression, dictionary):
222                 (a, (b, stack)) = stack
223                 result = f(b, a)
224                 return (result, stack), expression, dictionary
225         return inner
226
227
228 def UnaryBuiltinWrapper(f):
229         '''
230         Wrap functions that take one argument and return a single result.
231         '''
232         @FunctionWrapper
233         @wraps(f)
234         def inner(stack, expression, dictionary):
235                 (a, stack) = stack
236                 result = f(a)
237                 return (result, stack), expression, dictionary
238         return inner
239
240
241 class DefinitionWrapper(object):
242         '''
243         Provide implementation of defined functions, and some helper methods.
244         '''
245
246         def __init__(self, name, body_text, doc=None):
247                 self.name = self.__name__ = name
248                 self.body = text_to_expression(body_text)
249                 self._body = tuple(iter_stack(self.body))
250                 self.__doc__ = doc or body_text
251                 self._compiled = None
252
253         def __call__(self, stack, expression, dictionary):
254                 if self._compiled:
255                         return self._compiled(stack, expression, dictionary)  # pylint: disable=E1102
256                 expression = list_to_stack(self._body, expression)
257                 return stack, expression, dictionary
258
259         @classmethod
260         def parse_definition(class_, defi):
261                 '''
262                 Given some text describing a Joy function definition parse it and
263                 return a DefinitionWrapper.
264                 '''
265                 return class_(*(n.strip() for n in defi.split(None, 1)))
266
267         @classmethod
268         def add_definitions(class_, defs, dictionary):
269                 '''
270                 Scan multi-line string defs for definitions and add them to the
271                 dictionary.
272                 '''
273                 for definition in _text_to_defs(defs):
274                         class_.add_def(definition, dictionary)
275
276         @classmethod
277         def add_def(class_, definition, dictionary, fail_fails=False):
278                 '''
279                 Add the definition to the dictionary.
280                 '''
281                 F = class_.parse_definition(definition)
282                 dictionary[F.name] = F
283
284         @classmethod
285         def load_definitions(class_, filename, dictionary):
286                 with open(filename) as f:
287                         lines = [line for line in f if '==' in line]
288                 for line in lines:
289                         class_.add_def(line, dictionary)
290
291
292 def _text_to_defs(text):
293         return (
294                 line.strip()
295                 for line in text.splitlines()
296                 if not line.startswith('#')
297                 )
298
299
300 #
301 # Functions
302 #
303
304
305 @inscribe
306 @FunctionWrapper
307 def inscribe_(stack, expression, dictionary):
308         '''
309         Create a new Joy function definition in the Joy dictionary.  A
310         definition is given as a string with a name followed by a double
311         equal sign then one or more Joy functions, the body. for example:
312
313                         sqr == dup mul
314
315         If you want the definition to persist over restarts, enter it into
316         the definitions.txt resource.
317         '''
318         definition, stack = stack
319         DefinitionWrapper.add_def(definition, dictionary, fail_fails=True)
320         return stack, expression, dictionary
321
322
323 @inscribe
324 @SimpleFunctionWrapper
325 def parse(stack):
326         '''Parse the string on the stack to a Joy expression.'''
327         text, stack = stack
328         expression = text_to_expression(text)
329         return expression, stack
330
331
332 # @inscribe
333 # @SimpleFunctionWrapper
334 # def infer_(stack):
335 #       '''Attempt to infer the stack effect of a Joy expression.'''
336 #       E, stack = stack
337 #       effects = infer_expression(E)
338 #       e = list_to_stack([(fi, (fo, ())) for fi, fo in effects])
339 #       return e, stack
340
341
342 @inscribe
343 @SimpleFunctionWrapper
344 def getitem(stack):
345         '''
346         ::
347
348                 getitem == drop first
349
350         Expects an integer and a quote on the stack and returns the item at the
351         nth position in the quote counting from 0.
352         ::
353
354                          [a b c d] 0 getitem
355                 -------------------------
356                                                                 a
357
358         '''
359         n, (Q, stack) = stack
360         return pick(Q, n), stack
361
362
363 @inscribe
364 @SimpleFunctionWrapper
365 def drop(stack):
366         '''
367         ::
368
369                 drop == [rest] times
370
371         Expects an integer and a quote on the stack and returns the quote with
372         n items removed off the top.
373         ::
374
375                          [a b c d] 2 drop
376                 ----------------------
377                                          [c d]
378
379         '''
380         n, (Q, stack) = stack
381         while n > 0:
382                 try:
383                         _, Q = Q
384                 except ValueError:
385                         raise IndexError
386                 n -= 1
387         return Q, stack
388
389
390 @inscribe
391 @SimpleFunctionWrapper
392 def take(stack):
393         '''
394         Expects an integer and a quote on the stack and returns the quote with
395         just the top n items in reverse order (because that's easier and you can
396         use reverse if needed.)
397         ::
398
399                          [a b c d] 2 take
400                 ----------------------
401                                          [b a]
402
403         '''
404         n, (Q, stack) = stack
405         x = ()
406         while n > 0:
407                 try:
408                         item, Q = Q
409                 except ValueError:
410                         raise IndexError
411                 x = item, x
412                 n -= 1
413         return x, stack
414
415
416 @inscribe
417 @SimpleFunctionWrapper
418 def choice(stack):
419         '''
420         Use a Boolean value to select one of two items.
421         ::
422
423                                 A B False choice
424                  ----------------------
425                                                          A
426
427
428                                 A B True choice
429                  ---------------------
430                                                          B
431
432         Currently Python semantics are used to evaluate the "truthiness" of the
433         Boolean value (so empty string, zero, etc. are counted as false, etc.)
434         '''
435         (if_, (then, (else_, stack))) = stack
436         return then if if_ else else_, stack
437
438
439 @inscribe
440 @SimpleFunctionWrapper
441 def select(stack):
442         '''
443         Use a Boolean value to select one of two items from a sequence.
444         ::
445
446                                 [A B] False select
447                  ------------------------
448                                                                 A
449
450
451                                 [A B] True select
452                  -----------------------
453                                                          B
454
455         The sequence can contain more than two items but not fewer.
456         Currently Python semantics are used to evaluate the "truthiness" of the
457         Boolean value (so empty string, zero, etc. are counted as false, etc.)
458         '''
459         (flag, (choices, stack)) = stack
460         (else_, (then, _)) = choices
461         return then if flag else else_, stack
462
463
464 @inscribe
465 @SimpleFunctionWrapper
466 def max_(S):
467         '''Given a list find the maximum.'''
468         tos, stack = S
469         return max(iter_stack(tos)), stack
470
471
472 @inscribe
473 @SimpleFunctionWrapper
474 def min_(S):
475         '''Given a list find the minimum.'''
476         tos, stack = S
477         return min(iter_stack(tos)), stack
478
479
480 @inscribe
481 @SimpleFunctionWrapper
482 def sum_(S):
483         '''Given a quoted sequence of numbers return the sum.
484
485         sum == 0 swap [+] step
486         '''
487         tos, stack = S
488         return sum(iter_stack(tos)), stack
489
490
491 @inscribe
492 @SimpleFunctionWrapper
493 def remove(S):
494         '''
495         Expects an item on the stack and a quote under it and removes that item
496         from the the quote.  The item is only removed once.
497         ::
498
499                          [1 2 3 1] 1 remove
500                 ------------------------
501                                                 [2 3 1]
502
503         '''
504         (tos, (second, stack)) = S
505         l = list(iter_stack(second))
506         l.remove(tos)
507         return list_to_stack(l), stack
508
509
510 @inscribe
511 @SimpleFunctionWrapper
512 def unique(S):
513         '''Given a list remove duplicate items.'''
514         tos, stack = S
515         I = list(iter_stack(tos))
516         return list_to_stack(sorted(set(I), key=I.index)), stack
517
518
519 @inscribe
520 @SimpleFunctionWrapper
521 def sort_(S):
522         '''Given a list return it sorted.'''
523         tos, stack = S
524         return list_to_stack(sorted(iter_stack(tos))), stack
525
526
527 @inscribe
528 @SimpleFunctionWrapper
529 def clear(stack):
530         '''Clear everything from the stack.
531         ::
532
533                 clear == stack [pop stack] loop
534
535                          ... clear
536                 ---------------
537
538         '''
539         return ()
540
541
542 @inscribe
543 @SimpleFunctionWrapper
544 def disenstacken(stack):
545         '''
546         The disenstacken operator expects a list on top of the stack and makes that
547         the stack discarding the rest of the stack.
548         '''
549         return stack[0]
550
551
552 @inscribe
553 @SimpleFunctionWrapper
554 def reverse(S):
555         '''Reverse the list on the top of the stack.
556         ::
557
558                 reverse == [] swap shunt
559         '''
560         (tos, stack) = S
561         res = ()
562         for term in iter_stack(tos):
563                 res = term, res
564         return res, stack
565
566
567 @inscribe
568 @SimpleFunctionWrapper
569 def concat_(S):
570         '''Concatinate the two lists on the top of the stack.
571         ::
572
573                          [a b c] [d e f] concat
574                 ----------------------------
575                                          [a b c d e f]
576
577         '''
578         (tos, (second, stack)) = S
579         return concat(second, tos), stack
580
581
582 @inscribe
583 @SimpleFunctionWrapper
584 def shunt(stack):
585         '''Like concat but reverses the top list into the second.
586         ::
587
588                 shunt == [swons] step == reverse swap concat
589
590                          [a b c] [d e f] shunt
591                 ---------------------------
592                                  [f e d a b c] 
593
594         '''
595         (tos, (second, stack)) = stack
596         while tos:
597                 term, tos = tos
598                 second = term, second
599         return second, stack
600
601
602 @inscribe
603 @SimpleFunctionWrapper
604 def zip_(S):
605         '''
606         Replace the two lists on the top of the stack with a list of the pairs
607         from each list.  The smallest list sets the length of the result list.
608         '''
609         (tos, (second, stack)) = S
610         accumulator = [
611                 (a, (b, ()))
612                 for a, b in zip(iter_stack(tos), iter_stack(second))
613                 ]
614         return list_to_stack(accumulator), stack
615
616
617 @inscribe
618 @SimpleFunctionWrapper
619 def succ(S):
620         '''Increment TOS.'''
621         (tos, stack) = S
622         return tos + 1, stack
623
624
625 @inscribe
626 @SimpleFunctionWrapper
627 def pred(S):
628         '''Decrement TOS.'''
629         (tos, stack) = S
630         return tos - 1, stack
631
632
633 @inscribe
634 @SimpleFunctionWrapper
635 def pm(stack):
636         '''
637         Plus or minus
638         ::
639
640                          a b pm
641                 -------------
642                          a+b a-b
643
644         '''
645         a, (b, stack) = stack
646         p, m, = b + a, b - a
647         return m, (p, stack)
648
649
650 def floor(n):
651         return int(math.floor(n))
652
653 floor.__doc__ = math.floor.__doc__
654
655
656 @inscribe
657 @SimpleFunctionWrapper
658 def divmod_(S):
659         '''
660         divmod(x, y) -> (quotient, remainder)
661
662         Return the tuple (x//y, x%y).  Invariant: div*y + mod == x.
663         '''
664         a, (b, stack) = S
665         d, m = divmod(a, b)
666         return d, (m, stack)
667
668
669 def sqrt(a):
670         '''
671         Return the square root of the number a.
672         Negative numbers return complex roots.
673         '''
674         try:
675                 r = math.sqrt(a)
676         except ValueError:
677                 assert a < 0, repr(a)
678                 r = math.sqrt(-a) * 1j
679         return r
680
681
682 #def execute(S):
683 #  (text, stack) = S
684 #  if isinstance(text, str):
685 #    return run(text, stack)
686 #  return stack
687
688
689 @inscribe
690 @SimpleFunctionWrapper
691 def id_(stack):
692         '''The identity function.'''
693         return stack
694
695
696 @inscribe
697 @SimpleFunctionWrapper
698 def void(stack):
699         '''True if the form on TOS is void otherwise False.'''
700         form, stack = stack
701         return _void(form), stack
702
703
704 def _void(form):
705         return any(not _void(i) for i in iter_stack(form))
706
707
708
709 ##  transpose
710 ##  sign
711 ##  take
712
713
714 @inscribe
715 @FunctionWrapper
716 def words(stack, expression, dictionary):
717         '''Print all the words in alphabetical order.'''
718         print(' '.join(sorted(dictionary)))
719         return stack, expression, dictionary
720
721
722 @inscribe
723 @FunctionWrapper
724 def sharing(stack, expression, dictionary):
725         '''Print redistribution information.'''
726         print("You may convey verbatim copies of the Program's source code as"
727         ' you receive it, in any medium, provided that you conspicuously'
728         ' and appropriately publish on each copy an appropriate copyright'
729         ' notice; keep intact all notices stating that this License and'
730         ' any non-permissive terms added in accord with section 7 apply'
731         ' to the code; keep intact all notices of the absence of any'
732         ' warranty; and give all recipients a copy of this License along'
733         ' with the Program.'
734         ' You should have received a copy of the GNU General Public License'
735         ' along with Thun.  If not see <http://www.gnu.org/licenses/>.')
736         return stack, expression, dictionary
737
738
739 @inscribe
740 @FunctionWrapper
741 def warranty(stack, expression, dictionary):
742         '''Print warranty information.'''
743         print('THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY'
744         ' APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE'
745         ' COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM'
746         ' "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR'
747         ' IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES'
748         ' OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE'
749         ' ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS'
750         ' WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE'
751         ' COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.')
752         return stack, expression, dictionary
753
754
755 # def simple_manual(stack):
756 #   '''
757 #   Print words and help for each word.
758 #   '''
759 #   for name, f in sorted(FUNCTIONS.items()):
760 #     d = getdoc(f)
761 #     boxline = '+%s+' % ('-' * (len(name) + 2))
762 #     print('\n'.join((
763 #       boxline,
764 #       '| %s |' % (name,),
765 #       boxline,
766 #       d if d else '   ...',
767 #       '',
768 #       '--' * 40,
769 #       '',
770 #       )))
771 #   return stack
772
773
774 @inscribe
775 @FunctionWrapper
776 def help_(S, expression, dictionary):
777         '''Accepts a quoted symbol on the top of the stack and prints its docs.'''
778         ((symbol, _), stack) = S
779         word = dictionary[symbol]
780         print(HELP_TEMPLATE % (symbol, getdoc(word), symbol))
781         return stack, expression, dictionary
782
783
784 #
785 # § Combinators
786 #
787
788
789 # Several combinators depend on other words in their definitions,
790 # we use symbols to prevent hard-coding these, so in theory, you
791 # could change the word in the dictionary to use different semantics.
792 S_choice = Symbol('choice')
793 S_first = Symbol('first')
794 S_genrec = Symbol('genrec')
795 S_getitem = Symbol('getitem')
796 S_i = Symbol('i')
797 S_ifte = Symbol('ifte')
798 S_infra = Symbol('infra')
799 S_loop = Symbol('loop')
800 S_pop = Symbol('pop')
801 S_primrec = Symbol('primrec')
802 S_step = Symbol('step')
803 S_swaack = Symbol('swaack')
804 S_times = Symbol('times')
805
806
807 @inscribe
808 @FunctionWrapper
809 def i(stack, expression, dictionary):
810         '''
811         The i combinator expects a quoted program on the stack and unpacks it
812         onto the pending expression for evaluation.
813         ::
814
815                          [Q] i
816                 -----------
817                                 Q
818
819         '''
820         quote, stack = stack
821         return stack, concat(quote, expression), dictionary
822
823
824 @inscribe
825 @FunctionWrapper
826 def x(stack, expression, dictionary):
827         '''
828         ::
829
830                 x == dup i
831
832                 ... [Q] x = ... [Q] dup i
833                 ... [Q] x = ... [Q] [Q] i
834                 ... [Q] x = ... [Q]  Q
835
836         '''
837         quote, _ = stack
838         return stack, concat(quote, expression), dictionary
839
840
841 @inscribe
842 @FunctionWrapper
843 def b(stack, expression, dictionary):
844         '''
845         ::
846
847                 b == [i] dip i
848
849                 ... [P] [Q] b == ... [P] i [Q] i
850                 ... [P] [Q] b == ... P Q
851
852         '''
853         q, (p, (stack)) = stack
854         return stack, concat(p, concat(q, expression)), dictionary
855
856
857 @inscribe
858 @FunctionWrapper
859 def dupdip(stack, expression, dictionary):
860         '''
861         ::
862
863                 [F] dupdip == dup [F] dip
864
865                 ... a [F] dupdip
866                 ... a dup [F] dip
867                 ... a a   [F] dip
868                 ... a F a
869
870         '''
871         F, stack = stack
872         a = stack[0]
873         return stack, concat(F, (a,  expression)), dictionary
874
875
876 @inscribe
877 @FunctionWrapper
878 def infra(stack, expression, dictionary):
879         '''
880         Accept a quoted program and a list on the stack and run the program
881         with the list as its stack.  Does not affect the rest of the stack.
882         ::
883
884                          ... [a b c] [Q] . infra
885                 -----------------------------
886                          c b a . Q [...] swaack
887
888         '''
889         (quote, (aggregate, stack)) = stack
890         return aggregate, concat(quote, (stack, (S_swaack, expression))), dictionary
891
892
893 @inscribe
894 @FunctionWrapper
895 def genrec(stack, expression, dictionary):
896         '''
897         General Recursion Combinator.
898         ::
899
900                                   [if] [then] [rec1] [rec2] genrec
901             ---------------------------------------------------------------------
902                [if] [then] [rec1 [[if] [then] [rec1] [rec2] genrec] rec2] ifte
903
904         From "Recursion Theory and Joy" (j05cmp.html) by Manfred von Thun:
905         "The genrec combinator takes four program parameters in addition to
906         whatever data parameters it needs. Fourth from the top is an if-part,
907         followed by a then-part. If the if-part yields true, then the then-part
908         is executed and the combinator terminates. The other two parameters are
909         the rec1-part and the rec2-part. If the if-part yields false, the
910         rec1-part is executed. Following that the four program parameters and
911         the combinator are again pushed onto the stack bundled up in a quoted
912         form. Then the rec2-part is executed, where it will find the bundled
913         form. Typically it will then execute the bundled form, either with i or
914         with app2, or some other combinator."
915
916         The way to design one of these is to fix your base case [then] and the
917         test [if], and then treat rec1 and rec2 as an else-part "sandwiching"
918         a quotation of the whole function.
919
920         For example, given a (general recursive) function 'F':
921         ::
922
923                         F == [I] [T] [R1] [R2] genrec
924
925         If the [I] if-part fails you must derive R1 and R2 from:
926         ::
927
928                         ... R1 [F] R2
929
930         Just set the stack arguments in front, and figure out what R1 and R2
931         have to do to apply the quoted [F] in the proper way.  In effect, the
932         genrec combinator turns into an ifte combinator with a quoted copy of
933         the original definition in the else-part:
934         ::
935
936                         F == [I] [T] [R1]   [R2] genrec
937                           == [I] [T] [R1 [F] R2] ifte
938
939         Primitive recursive functions are those where R2 == i.
940         ::
941
942                         P == [I] [T] [R] tailrec
943                           == [I] [T] [R [P] i] ifte
944                           == [I] [T] [R P] ifte
945
946         '''
947         (rec2, (rec1, stack)) = stack
948         (then, (if_, _)) = stack
949         F = (if_, (then, (rec1, (rec2, (S_genrec, ())))))
950         else_ = concat(rec1, (F, rec2))
951         return (else_, stack), (S_ifte, expression), dictionary
952
953
954 @inscribe
955 @FunctionWrapper
956 def map_(S, expression, dictionary):
957         '''
958         Run the quoted program on TOS on the items in the list under it, push a
959         new list with the results in place of the program and original list.
960         '''
961         # (quote, (aggregate, stack)) = S
962         # results = list_to_stack([
963         # joy((term, stack), quote, dictionary)[0][0]
964         # for term in iter_stack(aggregate)
965         # ])
966         # return (results, stack), expression, dictionary
967         (quote, (aggregate, stack)) = S
968         if not aggregate:
969                 return (aggregate, stack), expression, dictionary
970         batch = ()
971         for term in iter_stack(aggregate):
972                 s = term, stack
973                 batch = (s, (quote, (S_infra, (S_first, batch))))
974         stack = (batch, ((), stack))
975         return stack, (S_infra, expression), dictionary
976
977
978 @inscribe
979 @FunctionWrapper
980 def primrec(stack, expression, dictionary):
981         '''
982         From the "Overview of the language JOY":
983
984         > The primrec combinator expects two quoted programs in addition to a
985         data parameter. For an integer data parameter it works like this: If
986         the data parameter is zero, then the first quotation has to produce
987         the value to be returned. If the data parameter is positive then the
988         second has to combine the data parameter with the result of applying
989         the function to its predecessor.
990
991         5  [1]  [*]  primrec
992
993         > Then primrec tests whether the top element on the stack (initially
994         the 5) is equal to zero. If it is, it pops it off and executes one of
995         the quotations, the [1] which leaves 1 on the stack as the result.
996         Otherwise it pushes a decremented copy of the top element and
997         recurses. On the way back from the recursion it uses the other
998         quotation, [*], to multiply what is now a factorial on top of the
999         stack by the second element on the stack.
1000
1001                 n [Base] [Recur] primrec
1002
1003            0 [Base] [Recur] primrec
1004         ------------------------------
1005               Base
1006
1007            n [Base] [Recur] primrec
1008         ------------------------------------------ n > 0
1009            n (n-1) [Base] [Recur] primrec Recur
1010
1011         '''
1012         recur, (base, (n, stack)) = stack
1013         if n <= 0:
1014                 expression = concat(base, expression)
1015         else:
1016                 expression = S_primrec, concat(recur, expression)
1017                 stack = recur, (base, (n - 1, (n, stack)))
1018         return stack, expression, dictionary
1019
1020
1021 #def cleave(S, expression, dictionary):
1022 #  '''
1023 #  The cleave combinator expects two quotations, and below that an item X.
1024 #  It first executes [P], with X on top, and saves the top result element.
1025 #  Then it executes [Q], again with X, and saves the top result.
1026 #  Finally it restores the stack to what it was below X and pushes the two
1027 #  results P(X) and Q(X).
1028 #  '''
1029 #  (Q, (P, (x, stack))) = S
1030 #  p = joy((x, stack), P, dictionary)[0][0]
1031 #  q = joy((x, stack), Q, dictionary)[0][0]
1032 #  return (q, (p, stack)), expression, dictionary
1033
1034
1035 @inscribe
1036 @FunctionWrapper
1037 def branch(stack, expression, dictionary):
1038         '''
1039         Use a Boolean value to select one of two quoted programs to run.
1040
1041         ::
1042
1043                         branch == roll< choice i
1044
1045         ::
1046
1047                                 False [F] [T] branch
1048                  --------------------------
1049                                                          F
1050
1051                                 True [F] [T] branch
1052                  -------------------------
1053                                                                         T
1054
1055         '''
1056         (then, (else_, (flag, stack))) = stack
1057         return stack, concat(then if flag else else_, expression), dictionary
1058
1059
1060 ##@inscribe
1061 ##@FunctionWrapper
1062 ##def ifte(stack, expression, dictionary):
1063 ##  '''
1064 ##  If-Then-Else Combinator
1065 ##  ::
1066 ##
1067 ##                  ... [if] [then] [else] ifte
1068 ##       ---------------------------------------------------
1069 ##          ... [[else] [then]] [...] [if] infra select i
1070 ##
1071 ##
1072 ##
1073 ##
1074 ##                ... [if] [then] [else] ifte
1075 ##       -------------------------------------------------------
1076 ##          ... [else] [then] [...] [if] infra first choice i
1077 ##
1078 ##
1079 ##  Has the effect of grabbing a copy of the stack on which to run the
1080 ##  if-part using infra.
1081 ##  '''
1082 ##  (else_, (then, (if_, stack))) = stack
1083 ##  expression = (S_infra, (S_first, (S_choice, (S_i, expression))))
1084 ##  stack = (if_, (stack, (then, (else_, stack))))
1085 ##  return stack, expression, dictionary
1086
1087
1088 @inscribe
1089 @FunctionWrapper
1090 def cond(stack, expression, dictionary):
1091         '''
1092         This combinator works like a case statement.  It expects a single quote
1093         on the stack that must contain zero or more condition quotes and a 
1094         default quote.  Each condition clause should contain a quoted predicate
1095         followed by the function expression to run if that predicate returns
1096         true.  If no predicates return true the default function runs.
1097
1098         It works by rewriting into a chain of nested `ifte` expressions, e.g.::
1099
1100                                                 [[[B0] T0] [[B1] T1] [D]] cond
1101                         -----------------------------------------
1102                                  [B0] [T0] [[B1] [T1] [D] ifte] ifte
1103
1104         '''
1105         conditions, stack = stack
1106         if conditions:
1107                 expression = _cond(conditions, expression)
1108                 try:
1109                         # Attempt to preload the args to first ifte.
1110                         (P, (T, (E, expression))) = expression
1111                 except ValueError:
1112                         # If, for any reason, the argument to cond should happen to contain
1113                         # only the default clause then this optimization will fail.
1114                         pass
1115                 else:
1116                         stack = (E, (T, (P, stack)))
1117         return stack, expression, dictionary
1118
1119
1120 def _cond(conditions, expression):
1121         (clause, rest) = conditions
1122         if not rest:  # clause is [D]
1123                 return clause
1124         P, T = clause
1125         return (P, (T, (_cond(rest, ()), (S_ifte, expression))))
1126
1127
1128 @inscribe
1129 @FunctionWrapper
1130 def dip(stack, expression, dictionary):
1131         '''
1132         The dip combinator expects a quoted program on the stack and below it
1133         some item, it hoists the item into the expression and runs the program
1134         on the rest of the stack.
1135         ::
1136
1137                          ... x [Q] dip
1138                 -------------------
1139                                  ... Q x
1140
1141         '''
1142         (quote, (x, stack)) = stack
1143         expression = (x, expression)
1144         return stack, concat(quote, expression), dictionary
1145
1146
1147 @inscribe
1148 @FunctionWrapper
1149 def dipd(S, expression, dictionary):
1150         '''
1151         Like dip but expects two items.
1152         ::
1153
1154                          ... y x [Q] dip
1155                 ---------------------
1156                                  ... Q y x
1157
1158         '''
1159         (quote, (x, (y, stack))) = S
1160         expression = (y, (x, expression))
1161         return stack, concat(quote, expression), dictionary
1162
1163
1164 @inscribe
1165 @FunctionWrapper
1166 def dipdd(S, expression, dictionary):
1167         '''
1168         Like dip but expects three items.
1169         ::
1170
1171                          ... z y x [Q] dip
1172                 -----------------------
1173                                  ... Q z y x
1174
1175         '''
1176         (quote, (x, (y, (z, stack)))) = S
1177         expression = (z, (y, (x, expression)))
1178         return stack, concat(quote, expression), dictionary
1179
1180
1181 @inscribe
1182 @FunctionWrapper
1183 def app1(S, expression, dictionary):
1184         '''
1185         Given a quoted program on TOS and anything as the second stack item run
1186         the program and replace the two args with the first result of the
1187         program.
1188         ::
1189
1190                                                         ... x [Q] . app1
1191                  -----------------------------------
1192                                 ... [x ...] [Q] . infra first
1193         '''
1194         (quote, (x, stack)) = S
1195         stack = (quote, ((x, stack), stack))
1196         expression = (S_infra, (S_first, expression))
1197         return stack, expression, dictionary
1198
1199
1200 @inscribe
1201 @FunctionWrapper
1202 def app2(S, expression, dictionary):
1203         '''Like app1 with two items.
1204         ::
1205
1206                                                 ... y x [Q] . app2
1207                  -----------------------------------
1208                                 ... [y ...] [Q] . infra first
1209                                                 [x ...] [Q]   infra first
1210
1211         '''
1212         (quote, (x, (y, stack))) = S
1213         expression = (S_infra, (S_first,
1214                 ((x, stack), (quote, (S_infra, (S_first,
1215                         expression))))))
1216         stack = (quote, ((y, stack), stack))
1217         return stack, expression, dictionary
1218
1219
1220 @inscribe
1221 @FunctionWrapper
1222 def app3(S, expression, dictionary):
1223         '''Like app1 with three items.
1224         ::
1225
1226                                                 ... z y x [Q] . app3
1227                  -----------------------------------
1228                                 ... [z ...] [Q] . infra first
1229                                                 [y ...] [Q]   infra first
1230                                                 [x ...] [Q]   infra first
1231
1232         '''
1233         (quote, (x, (y, (z, stack)))) = S
1234         expression = (S_infra, (S_first,
1235                 ((y, stack), (quote, (S_infra, (S_first,
1236                 ((x, stack), (quote, (S_infra, (S_first,
1237                         expression))))))))))
1238         stack = (quote, ((z, stack), stack))
1239         return stack, expression, dictionary
1240
1241
1242 @inscribe
1243 @FunctionWrapper
1244 def step(S, expression, dictionary):
1245         '''
1246         Run a quoted program on each item in a sequence.
1247         ::
1248
1249                                         ... [] [Q] . step
1250                          -----------------------
1251                                                                  ... .
1252
1253
1254                                  ... [a] [Q] . step
1255                         ------------------------
1256                                                          ... a . Q
1257
1258
1259                          ... [a b c] [Q] . step
1260                 ----------------------------------------
1261                                                                  ... a . Q [b c] [Q] step
1262
1263         The step combinator executes the quotation on each member of the list
1264         on top of the stack.
1265         '''
1266         (quote, (aggregate, stack)) = S
1267         if not aggregate:
1268                 return stack, expression, dictionary
1269         head, tail = aggregate
1270         stack = quote, (head, stack)
1271         if tail:
1272                 expression = tail, (quote, (S_step, expression))
1273         expression = S_i, expression
1274         return stack, expression, dictionary
1275
1276
1277 @inscribe
1278 @FunctionWrapper
1279 def times(stack, expression, dictionary):
1280         '''
1281         times == [-- dip] cons [swap] infra [0 >] swap while pop
1282         ::
1283
1284                          ... n [Q] . times
1285                 ---------------------  w/ n <= 0
1286                                                  ... .
1287
1288
1289                          ... 1 [Q] . times
1290                 ---------------------------------
1291                                                  ... . Q
1292
1293
1294                          ... n [Q] . times
1295                 ---------------------------------  w/ n > 1
1296                                                  ... . Q (n - 1) [Q] times
1297
1298         '''
1299         # times == [-- dip] cons [swap] infra [0 >] swap while pop
1300         (quote, (n, stack)) = stack
1301         if n <= 0:
1302                 return stack, expression, dictionary
1303         n -= 1
1304         if n:
1305                 expression = n, (quote, (S_times, expression))
1306         expression = concat(quote, expression)
1307         return stack, expression, dictionary
1308
1309
1310 # The current definition above works like this:
1311
1312 #             [P] [Q] while
1313 # --------------------------------------
1314 #    [P] nullary [Q [P] nullary] loop
1315
1316 #   while == [pop i not] [popop] [dudipd] tailrec
1317
1318 #def while_(S, expression, dictionary):
1319 #  '''[if] [body] while'''
1320 #  (body, (if_, stack)) = S
1321 #  while joy(stack, if_, dictionary)[0][0]:
1322 #    stack = joy(stack, body, dictionary)[0]
1323 #  return stack, expression, dictionary
1324
1325
1326 @inscribe
1327 @FunctionWrapper
1328 def loop(stack, expression, dictionary):
1329         '''
1330         Basic loop combinator.
1331         ::
1332
1333                          ... True [Q] loop
1334                 -----------------------
1335                                         ... Q [Q] loop
1336
1337                          ... False [Q] loop
1338                 ------------------------
1339                                                         ...
1340
1341         '''
1342         quote, (flag, stack) = stack
1343         if flag:
1344                 expression = concat(quote, (quote, (S_loop, expression)))
1345         return stack, expression, dictionary
1346
1347
1348 @inscribe
1349 @FunctionWrapper
1350 def cmp_(stack, expression, dictionary):
1351         '''
1352         cmp takes two values and three quoted programs on the stack and runs
1353         one of the three depending on the results of comparing the two values:
1354         ::
1355
1356                                          a b [G] [E] [L] cmp
1357                                 ------------------------- a > b
1358                                                                 G
1359
1360                                          a b [G] [E] [L] cmp
1361                                 ------------------------- a = b
1362                                                                                 E
1363
1364                                          a b [G] [E] [L] cmp
1365                                 ------------------------- a < b
1366                                                                                                 L
1367         '''
1368         L, (E, (G, (b, (a, stack)))) = stack
1369         expression = concat(G if a > b else L if a < b else E, expression)
1370         return stack, expression, dictionary
1371
1372
1373 #  FunctionWrapper(cleave),
1374 #  FunctionWrapper(while_),
1375
1376
1377 for F in (
1378
1379         #divmod_ = pm = __(n2, n1), __(n4, n3)
1380
1381         BinaryBuiltinWrapper(operator.eq),
1382         BinaryBuiltinWrapper(operator.ge),
1383         BinaryBuiltinWrapper(operator.gt),
1384         BinaryBuiltinWrapper(operator.le),
1385         BinaryBuiltinWrapper(operator.lt),
1386         BinaryBuiltinWrapper(operator.ne),
1387
1388         BinaryBuiltinWrapper(operator.xor),
1389         BinaryBuiltinWrapper(operator.lshift),
1390         BinaryBuiltinWrapper(operator.rshift),
1391
1392         BinaryBuiltinWrapper(operator.and_),
1393         BinaryBuiltinWrapper(operator.or_),
1394
1395         BinaryBuiltinWrapper(operator.add),
1396         BinaryBuiltinWrapper(operator.floordiv),
1397         BinaryBuiltinWrapper(operator.mod),
1398         BinaryBuiltinWrapper(operator.mul),
1399         BinaryBuiltinWrapper(operator.pow),
1400         BinaryBuiltinWrapper(operator.sub),
1401         BinaryBuiltinWrapper(operator.truediv),
1402
1403         UnaryBuiltinWrapper(bool),
1404         UnaryBuiltinWrapper(operator.not_),
1405
1406         UnaryBuiltinWrapper(abs),
1407         UnaryBuiltinWrapper(operator.neg),
1408         UnaryBuiltinWrapper(sqrt),
1409
1410         UnaryBuiltinWrapper(floor),
1411         ):
1412         inscribe(F)
1413 del F  # Otherwise Sphinx autodoc will pick it up.
1414
1415
1416 for name, primitive in getmembers(genlib, isfunction):
1417         inscribe(SimpleFunctionWrapper(primitive))
1418
1419
1420 add_aliases(_dictionary, ALIASES)
1421
1422
1423 DefinitionWrapper.add_definitions(definitions, _dictionary)