OSDN Git Service

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