OSDN Git Service

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