1 # -*- coding: utf-8 -*-
3 # Copyright © 2014, 2015, 2017, 2018 Simon Forman
5 # This file is part of Thun
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.
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.
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/>.
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()
26 from logging import getLogger
28 _log = getLogger(__name__)
29 _log.info('Loading library.')
31 from inspect import getdoc
32 from functools import wraps
33 from itertools import count
34 from inspect import getmembers, isfunction
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
41 from .utils import generated_library as genlib
42 from .utils.types import (
64 poly_combinator_effect,
65 doc_from_stack_effect,
69 _SYM_NUMS = count().next
70 _COMB_NUMS = count().next
74 A = a0, a1, a2, a3, a4, a5, a6, a7, a8, a9 = map(AnyJoyType, _R)
75 B = b0, b1, b2, b3, b4, b5, b6, b7, b8, b9 = map(BooleanJoyType, _R)
76 N = n0, n1, n2, n3, n4, n5, n6, n7, n8, n9 = map(NumberJoyType, _R)
77 S = s0, s1, s2, s3, s4, s5, s6, s7, s8, s9 = map(StackJoyType, _R)
78 F = f0, f1, f2, f3, f4, f5, f6, f7, f8, f9 = map(FloatJoyType, _R)
79 I = i0, i1, i2, i3, i4, i5, i6, i7, i8, i9 = map(IntJoyType, _R)
80 T = t0, t1, t2, t3, t4, t5, t6, t7, t8, t9 = map(TextJoyType, _R)
84 As = map(AnyStarJoyType, _R)
85 Ns = map(NumberStarJoyType, _R)
86 Ss = map(StackStarJoyType, _R)
89 sec0 = stack_effect(t1)()
90 sec1 = stack_effect(s0, i1)(s1)
91 sec2 = stack_effect(s0, i1)(a1)
92 sec_binary_cmp = stack_effect(n1, n2)(b1)
93 sec_binary_ints = stack_effect(i1, i2)(i3)
94 sec_binary_logic = stack_effect(b1, b2)(b3)
95 sec_binary_math = stack_effect(n1, n2)(n3)
96 sec_unary_logic = stack_effect(a1)(b1)
97 sec_unary_math = stack_effect(n1)(n2)
98 sec_Ns_math = stack_effect((Ns[1], s1),)(n0)
103 def inscribe(function):
104 '''A decorator to inscribe functions into the default dictionary.'''
105 _dictionary[function.name] = function
110 '''Return a dictionary of Joy functions for use with joy().'''
111 return _dictionary.copy()
117 ('bool', ['truthy']),
119 ('floordiv', ['/floor', '//']),
120 ('floor', ['round']),
122 ('mod', ['%', 'rem', 'remainder', 'modulus']),
125 ('getitem', ['pick', 'at']),
130 ('ne', ['<>', '!=']),
136 ('rolldown', ['roll<']),
137 ('rollup', ['roll>']),
143 def add_aliases(D, A):
145 Given a dict and a iterable of (name, [alias, ...]) pairs, create
146 additional entries in the dict mapping each alias to the named function
147 if it's in the dict. Aliases for functions not in the dict are ignored.
149 for name, aliases in A:
154 for alias in aliases:
160 Return a dict of named stack effects.
162 "Yin" functions are those that only rearrange items in stacks and
163 can be defined completely by their stack effects. This means they
164 can be auto-compiled.
166 # pylint: disable=unused-variable
167 cons = ef(a1, s0)((a1, s0))
168 ccons = compose(cons, cons)
170 dupd = ef(a2, a1)(a2, a2, a1)
171 dupdd = ef(a3, a2, a1)(a3, a3, a2, a1)
172 first = ef((a1, s1),)(a1,)
173 over = ef(a2, a1)(a2, a1, a2)
175 popd = ef(a2, a1,)(a1)
176 popdd = ef(a3, a2, a1,)(a2, a1,)
177 popop = ef(a2, a1,)()
178 popopd = ef(a3, a2, a1,)(a1)
179 popopdd = ef(a4, a3, a2, a1,)(a2, a1)
180 rest = ef((a1, s0),)(s0,)
181 rolldown = ef(a1, a2, a3)(a2, a3, a1)
182 rollup = ef(a1, a2, a3)(a3, a1, a2)
183 rrest = compose(rest, rest)
184 second = compose(rest, first)
186 swaack = (s1, s0), (s0, s1)
187 swap = ef(a1, a2)(a2, a1)
188 swons = compose(swap, cons)
189 third = compose(rest, second)
190 tuck = ef(a2, a1)(a1, a2, a1)
191 uncons = ef((a1, s0),)(a1, s0)
192 unswons = compose(uncons, swap)
193 stuncons = compose(stack, uncons)
194 stununcons = compose(stack, uncons, uncons)
195 unit = ef(a1)((a1, ()))
197 first_two = compose(uncons, uncons, pop)
198 fourth = compose(rest, third)
200 _Tree_add_Ee = compose(pop, swap, rolldown, rrest, ccons)
201 _Tree_get_E = compose(popop, second)
202 _Tree_delete_clear_stuff = compose(rollup, popop, rest)
203 _Tree_delete_R0 = compose(over, first, swap, dup)
210 product == 1 swap [*] step
211 flatten == [] swap [concat] step
214 enstacken == stack [clear] dip
216 disenstacken == ? [uncons ?] loop pop
217 dinfrirst == dip infra first
218 nullary == [stack] dinfrirst
219 unary == nullary popd
220 binary == nullary [popop] dip
221 ternary == unary [popop] dip
225 size == 0 swap [pop ++] step
227 cleave == fork [popd] dip
228 average == [sum 1.0 *] [size] cleave /
229 gcd == 1 [tuck modulus dup 0 >] loop pop
230 least_fraction == dup [gcd] infra [div] concat map
231 *fraction == [uncons] dip uncons [swap] dip concat [*] infra [*] dip cons
232 *fraction0 == concat [[swap] dip * [*] dip] infra
233 down_to_zero == [0 >] [dup --] while
234 range_to_zero == unit [down_to_zero] infra
235 anamorphism == [pop []] swap [dip swons] genrec
236 range == [0 <=] [1 - dup] anamorphism
237 while == swap [nullary] cons dup dipd concat loop
239 primrec == [i] genrec
240 step_zero == 0 roll> step
241 codireco == cons dip rest cons
242 make_generator == [codireco] ccons
243 ifte == [nullary not] dipd branch
247 # ifte == [nullary] dipd swap branch
248 # genrec == [[genrec] cons cons cons cons] nullary swons concat ifte
250 # Another definition for while. FWIW
251 # while == over [[i] dip nullary] ccons [nullary] dip loop
255 ##second == rest first
256 ##third == rest rest first
258 ##swoncat == swap concat
261 ##z-down == [] swap uncons swap
262 ##z-up == swons swap shunt
263 ##z-right == [swons] cons dip uncons swap
264 ##z-left == swons [uncons swap] dip swap
267 ##divisor == popop 2 *
269 ##radical == swap dup * rollup * 4 * - sqrt
272 ##q0 == [[divisor] [minusb] [radical]] pam
273 ##q1 == [[root1] [root2]] pam
274 ##quadratic == [q0] ternary i [q1] ternary
278 ##PE1.1 == + dup [+] dip
279 ##PE1.2 == dup [3 & PE1.1] dip 2 >>
280 ##PE1.3 == 14811 swap [PE1.2] times pop
281 ##PE1 == 0 0 66 [7 PE1.3] times 4 PE1.3 pop
283 #PE1.2 == [PE1.1] step
284 #PE1 == 0 0 66 [[3 2 1 3 1 2 3] PE1.2] times [3 2 1 3] PE1.2 pop
288 def FunctionWrapper(f):
289 '''Set name attribute.'''
291 raise ValueError('Function %s must have doc string.' % f.__name__)
292 f.name = f.__name__.rstrip('_') # Don't shadow builtins.
296 def SimpleFunctionWrapper(f):
298 Wrap functions that take and return just a stack.
302 @rename_code_object(f.__name__)
303 def inner(stack, expression, dictionary):
304 return f(stack), expression, dictionary
308 def BinaryBuiltinWrapper(f):
310 Wrap functions that take two arguments and return a single result.
314 @rename_code_object(f.__name__)
315 def inner(stack, expression, dictionary):
316 (a, (b, stack)) = stack
318 return (result, stack), expression, dictionary
322 def UnaryBuiltinWrapper(f):
324 Wrap functions that take one argument and return a single result.
328 @rename_code_object(f.__name__)
329 def inner(stack, expression, dictionary):
332 return (result, stack), expression, dictionary
336 class DefinitionWrapper(object):
338 Provide implementation of defined functions, and some helper methods.
341 def __init__(self, name, body_text, doc=None):
342 self.name = self.__name__ = name
343 self.body = text_to_expression(body_text)
344 self._body = tuple(iter_stack(self.body))
345 self.__doc__ = doc or body_text
346 self._compiled = None
348 def __call__(self, stack, expression, dictionary):
350 return self._compiled(stack, expression, dictionary) # pylint: disable=E1102
351 expression = list_to_stack(self._body, expression)
352 return stack, expression, dictionary
355 def parse_definition(class_, defi):
357 Given some text describing a Joy function definition parse it and
358 return a DefinitionWrapper.
360 name, proper, body_text = (n.strip() for n in defi.partition('=='))
362 raise ValueError('Definition %r failed' % (defi,))
363 return class_(name, body_text)
366 def add_definitions(class_, defs, dictionary):
368 Scan multi-line string defs for definitions and add them to the
371 for definition in _text_to_defs(defs):
372 class_.add_def(definition, dictionary)
375 def add_def(class_, definition, dictionary, fail_fails=False):
377 Add the definition to the dictionary.
379 F = class_.parse_definition(definition)
380 _log.info('Adding definition %s := %s', F.name, expression_to_string(F.body))
381 dictionary[F.name] = F
384 def _text_to_defs(text):
385 return (line.strip() for line in text.splitlines() if '==' in line)
396 def inscribe_(stack, expression, dictionary):
398 Create a new Joy function definition in the Joy dictionary. A
399 definition is given as a string with a name followed by a double
400 equal sign then one or more Joy functions, the body. for example:
404 If you want the definition to persist over restarts, enter it into
405 the definitions.txt resource.
407 definition, stack = stack
408 DefinitionWrapper.add_def(definition, dictionary, fail_fails=True)
409 return stack, expression, dictionary
413 @SimpleFunctionWrapper
415 '''Parse the string on the stack to a Joy expression.'''
417 expression = text_to_expression(text)
418 return expression, stack
423 @SimpleFunctionWrapper
428 getitem == drop first
430 Expects an integer and a quote on the stack and returns the item at the
431 nth position in the quote counting from 0.
435 -------------------------
439 n, (Q, stack) = stack
440 return pick(Q, n), stack
445 @SimpleFunctionWrapper
452 Expects an integer and a quote on the stack and returns the quote with
453 n items removed off the top.
457 ----------------------
461 n, (Q, stack) = stack
473 @SimpleFunctionWrapper
476 Expects an integer and a quote on the stack and returns the quote with
477 just the top n items in reverse order (because that's easier and you can
478 use reverse if needed.)
482 ----------------------
486 n, (Q, stack) = stack
499 @SimpleFunctionWrapper
502 Use a Boolean value to select one of two items.
506 ----------------------
511 ---------------------
514 Currently Python semantics are used to evaluate the "truthiness" of the
515 Boolean value (so empty string, zero, etc. are counted as false, etc.)
517 (if_, (then, (else_, stack))) = stack
518 return then if if_ else else_, stack
522 @SimpleFunctionWrapper
525 Use a Boolean value to select one of two items from a sequence.
529 ------------------------
534 -----------------------
537 The sequence can contain more than two items but not fewer.
538 Currently Python semantics are used to evaluate the "truthiness" of the
539 Boolean value (so empty string, zero, etc. are counted as false, etc.)
541 (flag, (choices, stack)) = stack
542 (else_, (then, _)) = choices
543 return then if flag else else_, stack
548 @SimpleFunctionWrapper
550 '''Given a list find the maximum.'''
552 return max(iter_stack(tos)), stack
557 @SimpleFunctionWrapper
559 '''Given a list find the minimum.'''
561 return min(iter_stack(tos)), stack
566 @SimpleFunctionWrapper
568 '''Given a quoted sequence of numbers return the sum.
570 sum == 0 swap [+] step
573 return sum(iter_stack(tos)), stack
577 @SimpleFunctionWrapper
580 Expects an item on the stack and a quote under it and removes that item
581 from the the quote. The item is only removed once.
585 ------------------------
589 (tos, (second, stack)) = S
590 l = list(iter_stack(second))
592 return list_to_stack(l), stack
596 @SimpleFunctionWrapper
598 '''Given a list remove duplicate items.'''
600 I = list(iter_stack(tos))
601 list_to_stack(sorted(set(I), key=I.index))
602 return list_to_stack(sorted(set(I), key=I.index)), stack
606 @SimpleFunctionWrapper
608 '''Given a list return it sorted.'''
610 return list_to_stack(sorted(iter_stack(tos))), stack
613 _functions['clear'] = s0, s1
615 @SimpleFunctionWrapper
617 '''Clear everything from the stack.
620 clear == stack [pop stack] loop
630 @SimpleFunctionWrapper
633 The unstack operator expects a list on top of the stack and makes that
634 the stack discarding the rest of the stack.
640 @SimpleFunctionWrapper
642 '''Reverse the list on the top of the stack.
645 reverse == [] swap shunt
649 for term in iter_stack(tos):
655 @combinator_effect(_COMB_NUMS(), s7, s6)
656 @SimpleFunctionWrapper
658 '''Concatinate the two lists on the top of the stack.
661 [a b c] [d e f] concat
662 ----------------------------
666 (tos, (second, stack)) = S
667 return concat(second, tos), stack
671 @SimpleFunctionWrapper
673 '''Like concat but reverses the top list into the second.
676 shunt == [swons] step == reverse swap concat
678 [a b c] [d e f] shunt
679 ---------------------------
683 (tos, (second, stack)) = stack
686 second = term, second
691 @SimpleFunctionWrapper
694 Replace the two lists on the top of the stack with a list of the pairs
695 from each list. The smallest list sets the length of the result list.
697 (tos, (second, stack)) = S
700 for a, b in zip(iter_stack(tos), iter_stack(second))
702 return list_to_stack(accumulator), stack
706 @SimpleFunctionWrapper
710 return tos + 1, stack
714 @SimpleFunctionWrapper
718 return tos - 1, stack
722 @SimpleFunctionWrapper
733 a, (b, stack) = stack
739 return int(math.floor(n))
741 floor.__doc__ = math.floor.__doc__
745 @SimpleFunctionWrapper
748 divmod(x, y) -> (quotient, remainder)
750 Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
759 Return the square root of the number a.
760 Negative numbers return complex roots.
765 assert a < 0, repr(a)
766 r = math.sqrt(-a) * 1j
772 # if isinstance(text, str):
773 # return run(text, stack)
778 @SimpleFunctionWrapper
780 '''The identity function.'''
785 @SimpleFunctionWrapper
787 '''True if the form on TOS is void otherwise False.'''
789 return _void(form), stack
793 return any(not _void(i) for i in iter_stack(form))
804 def words(stack, expression, dictionary):
805 '''Print all the words in alphabetical order.'''
806 print(' '.join(sorted(dictionary)))
807 return stack, expression, dictionary
812 def sharing(stack, expression, dictionary):
813 '''Print redistribution information.'''
814 print("You may convey verbatim copies of the Program's source code as"
815 ' you receive it, in any medium, provided that you conspicuously'
816 ' and appropriately publish on each copy an appropriate copyright'
817 ' notice; keep intact all notices stating that this License and'
818 ' any non-permissive terms added in accord with section 7 apply'
819 ' to the code; keep intact all notices of the absence of any'
820 ' warranty; and give all recipients a copy of this License along'
822 ' You should have received a copy of the GNU General Public License'
823 ' along with Thun. If not see <http://www.gnu.org/licenses/>.')
824 return stack, expression, dictionary
829 def warranty(stack, expression, dictionary):
830 '''Print warranty information.'''
831 print('THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY'
832 ' APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE'
833 ' COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM'
834 ' "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR'
835 ' IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES'
836 ' OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE'
837 ' ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS'
838 ' WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE'
839 ' COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.')
840 return stack, expression, dictionary
843 # def simple_manual(stack):
845 # Print words and help for each word.
847 # for name, f in sorted(FUNCTIONS.items()):
849 # boxline = '+%s+' % ('-' * (len(name) + 2))
852 # '| %s |' % (name,),
854 # d if d else ' ...',
864 def help_(S, expression, dictionary):
865 '''Accepts a quoted symbol on the top of the stack and prints its docs.'''
866 ((symbol, _), stack) = S
867 word = dictionary[symbol]
869 return stack, expression, dictionary
877 # Several combinators depend on other words in their definitions,
878 # we use symbols to prevent hard-coding these, so in theory, you
879 # could change the word in the dictionary to use different semantics.
880 S_choice = Symbol('choice')
881 S_first = Symbol('first')
882 S_getitem = Symbol('getitem')
883 S_genrec = Symbol('genrec')
884 S_loop = Symbol('loop')
886 S_ifte = Symbol('ifte')
887 S_infra = Symbol('infra')
888 S_step = Symbol('step')
889 S_times = Symbol('times')
890 S_swaack = Symbol('swaack')
891 S_truthy = Symbol('truthy')
895 @combinator_effect(_COMB_NUMS(), s1)
897 def i(stack, expression, dictionary):
899 The i combinator expects a quoted program on the stack and unpacks it
900 onto the pending expression for evaluation.
909 return stack, concat(quote, expression), dictionary
913 @combinator_effect(_COMB_NUMS(), s1)
915 def x(stack, expression, dictionary):
921 ... [Q] x = ... [Q] dup i
922 ... [Q] x = ... [Q] [Q] i
923 ... [Q] x = ... [Q] Q
927 return stack, concat(quote, expression), dictionary
931 @combinator_effect(_COMB_NUMS(), s7, s6)
933 def b(stack, expression, dictionary):
939 ... [P] [Q] b == ... [P] i [Q] i
940 ... [P] [Q] b == ... P Q
943 q, (p, (stack)) = stack
944 return stack, concat(p, concat(q, expression)), dictionary
948 @combinator_effect(_COMB_NUMS(), a1, s1)
950 def dupdip(stack, expression, dictionary):
954 [F] dupdip == dup [F] dip
964 return stack, concat(F, (a, expression)), dictionary
968 @combinator_effect(_COMB_NUMS(), s7, s6)
970 def infra(stack, expression, dictionary):
972 Accept a quoted program and a list on the stack and run the program
973 with the list as its stack.
976 ... [a b c] [Q] . infra
977 -----------------------------
978 c b a . Q [...] swaack
981 (quote, (aggregate, stack)) = stack
982 return aggregate, concat(quote, (stack, (S_swaack, expression))), dictionary
986 #@combinator_effect(_COMB_NUMS(), s7, s6, s5, s4)
988 def genrec(stack, expression, dictionary):
990 General Recursion Combinator.
993 [if] [then] [rec1] [rec2] genrec
994 ---------------------------------------------------------------------
995 [if] [then] [rec1 [[if] [then] [rec1] [rec2] genrec] rec2] ifte
997 From "Recursion Theory and Joy" (j05cmp.html) by Manfred von Thun:
998 "The genrec combinator takes four program parameters in addition to
999 whatever data parameters it needs. Fourth from the top is an if-part,
1000 followed by a then-part. If the if-part yields true, then the then-part
1001 is executed and the combinator terminates. The other two parameters are
1002 the rec1-part and the rec2-part. If the if-part yields false, the
1003 rec1-part is executed. Following that the four program parameters and
1004 the combinator are again pushed onto the stack bundled up in a quoted
1005 form. Then the rec2-part is executed, where it will find the bundled
1006 form. Typically it will then execute the bundled form, either with i or
1007 with app2, or some other combinator."
1009 The way to design one of these is to fix your base case [then] and the
1010 test [if], and then treat rec1 and rec2 as an else-part "sandwiching"
1011 a quotation of the whole function.
1013 For example, given a (general recursive) function 'F':
1016 F == [I] [T] [R1] [R2] genrec
1018 If the [I] if-part fails you must derive R1 and R2 from:
1023 Just set the stack arguments in front, and figure out what R1 and R2
1024 have to do to apply the quoted [F] in the proper way. In effect, the
1025 genrec combinator turns into an ifte combinator with a quoted copy of
1026 the original definition in the else-part:
1029 F == [I] [T] [R1] [R2] genrec
1030 == [I] [T] [R1 [F] R2] ifte
1032 Primitive recursive functions are those where R2 == i.
1035 P == [I] [T] [R] primrec
1036 == [I] [T] [R [P] i] ifte
1037 == [I] [T] [R P] ifte
1040 (rec2, (rec1, stack)) = stack
1041 (then, (if_, _)) = stack
1042 F = (if_, (then, (rec1, (rec2, (S_genrec, ())))))
1043 else_ = concat(rec1, (F, rec2))
1044 return (else_, stack), (S_ifte, expression), dictionary
1048 @combinator_effect(_COMB_NUMS(), s7, s6)
1050 def map_(S, expression, dictionary):
1052 Run the quoted program on TOS on the items in the list under it, push a
1053 new list with the results (in place of the program and original list.
1055 # (quote, (aggregate, stack)) = S
1056 # results = list_to_stack([
1057 # joy((term, stack), quote, dictionary)[0][0]
1058 # for term in iter_stack(aggregate)
1060 # return (results, stack), expression, dictionary
1061 (quote, (aggregate, stack)) = S
1063 return (aggregate, stack), expression, dictionary
1065 for term in iter_stack(aggregate):
1067 batch = (s, (quote, (S_infra, (S_first, batch))))
1068 stack = (batch, ((), stack))
1069 return stack, (S_infra, expression), dictionary
1072 #def cleave(S, expression, dictionary):
1074 # The cleave combinator expects two quotations, and below that an item X.
1075 # It first executes [P], with X on top, and saves the top result element.
1076 # Then it executes [Q], again with X, and saves the top result.
1077 # Finally it restores the stack to what it was below X and pushes the two
1078 # results P(X) and Q(X).
1080 # (Q, (P, (x, stack))) = S
1081 # p = joy((x, stack), P, dictionary)[0][0]
1082 # q = joy((x, stack), Q, dictionary)[0][0]
1083 # return (q, (p, stack)), expression, dictionary
1086 def branch_true(stack, expression, dictionary):
1087 # pylint: disable=unused-variable
1088 (then, (else_, (flag, stack))) = stack
1089 return stack, concat(then, expression), dictionary
1092 def branch_false(stack, expression, dictionary):
1093 # pylint: disable=unused-variable
1094 (then, (else_, (flag, stack))) = stack
1095 return stack, concat(else_, expression), dictionary
1099 @poly_combinator_effect(_COMB_NUMS(), [branch_true, branch_false], b1, s7, s6)
1101 def branch(stack, expression, dictionary):
1103 Use a Boolean value to select one of two quoted programs to run.
1107 branch == roll< choice i
1111 False [F] [T] branch
1112 --------------------------
1116 -------------------------
1120 (then, (else_, (flag, stack))) = stack
1121 return stack, concat(then if flag else else_, expression), dictionary
1124 #FUNCTIONS['branch'] = CombinatorJoyType('branch', [branch_true, branch_false], 100)
1129 ##def ifte(stack, expression, dictionary):
1131 ## If-Then-Else Combinator
1134 ## ... [if] [then] [else] ifte
1135 ## ---------------------------------------------------
1136 ## ... [[else] [then]] [...] [if] infra select i
1141 ## ... [if] [then] [else] ifte
1142 ## -------------------------------------------------------
1143 ## ... [else] [then] [...] [if] infra first choice i
1146 ## Has the effect of grabbing a copy of the stack on which to run the
1147 ## if-part using infra.
1149 ## (else_, (then, (if_, stack))) = stack
1150 ## expression = (S_infra, (S_first, (S_choice, (S_i, expression))))
1151 ## stack = (if_, (stack, (then, (else_, stack))))
1152 ## return stack, expression, dictionary
1157 def cond(stack, expression, dictionary):
1159 This combinator works like a case statement. It expects a single quote
1160 on the stack that must contain zero or more condition quotes and a
1161 default quote. Each condition clause should contain a quoted predicate
1162 followed by the function expression to run if that predicate returns
1163 true. If no predicates return true the default function runs.
1165 It works by rewriting into a chain of nested `ifte` expressions, e.g.::
1167 [[[B0] T0] [[B1] T1] [D]] cond
1168 -----------------------------------------
1169 [B0] [T0] [[B1] [T1] [D] ifte] ifte
1172 conditions, stack = stack
1174 expression = _cond(conditions, expression)
1176 # Attempt to preload the args to first ifte.
1177 (P, (T, (E, expression))) = expression
1179 # If, for any reason, the argument to cond should happen to contain
1180 # only the default clause then this optimization will fail.
1183 stack = (E, (T, (P, stack)))
1184 return stack, expression, dictionary
1187 def _cond(conditions, expression):
1188 (clause, rest) = conditions
1189 if not rest: # clause is [D]
1192 return (P, (T, (_cond(rest, ()), (S_ifte, expression))))
1196 @combinator_effect(_COMB_NUMS(), a1, s1)
1198 def dip(stack, expression, dictionary):
1200 The dip combinator expects a quoted program on the stack and below it
1201 some item, it hoists the item into the expression and runs the program
1202 on the rest of the stack.
1210 (quote, (x, stack)) = stack
1211 expression = (x, expression)
1212 return stack, concat(quote, expression), dictionary
1216 @combinator_effect(_COMB_NUMS(), a2, a1, s1)
1218 def dipd(S, expression, dictionary):
1220 Like dip but expects two items.
1224 ---------------------
1228 (quote, (x, (y, stack))) = S
1229 expression = (y, (x, expression))
1230 return stack, concat(quote, expression), dictionary
1234 @combinator_effect(_COMB_NUMS(), a3, a2, a1, s1)
1236 def dipdd(S, expression, dictionary):
1238 Like dip but expects three items.
1242 -----------------------
1246 (quote, (x, (y, (z, stack)))) = S
1247 expression = (z, (y, (x, expression)))
1248 return stack, concat(quote, expression), dictionary
1252 @combinator_effect(_COMB_NUMS(), a1, s1)
1254 def app1(S, expression, dictionary):
1256 Given a quoted program on TOS and anything as the second stack item run
1257 the program and replace the two args with the first result of the
1262 -----------------------------------
1263 ... [x ...] [Q] . infra first
1265 (quote, (x, stack)) = S
1266 stack = (quote, ((x, stack), stack))
1267 expression = (S_infra, (S_first, expression))
1268 return stack, expression, dictionary
1272 @combinator_effect(_COMB_NUMS(), a2, a1, s1)
1274 def app2(S, expression, dictionary):
1275 '''Like app1 with two items.
1279 -----------------------------------
1280 ... [y ...] [Q] . infra first
1281 [x ...] [Q] infra first
1284 (quote, (x, (y, stack))) = S
1285 expression = (S_infra, (S_first,
1286 ((x, stack), (quote, (S_infra, (S_first,
1288 stack = (quote, ((y, stack), stack))
1289 return stack, expression, dictionary
1293 @combinator_effect(_COMB_NUMS(), a3, a2, a1, s1)
1295 def app3(S, expression, dictionary):
1296 '''Like app1 with three items.
1299 ... z y x [Q] . app3
1300 -----------------------------------
1301 ... [z ...] [Q] . infra first
1302 [y ...] [Q] infra first
1303 [x ...] [Q] infra first
1306 (quote, (x, (y, (z, stack)))) = S
1307 expression = (S_infra, (S_first,
1308 ((y, stack), (quote, (S_infra, (S_first,
1309 ((x, stack), (quote, (S_infra, (S_first,
1310 expression))))))))))
1311 stack = (quote, ((z, stack), stack))
1312 return stack, expression, dictionary
1316 @combinator_effect(_COMB_NUMS(), s7, s6)
1318 def step(S, expression, dictionary):
1320 Run a quoted program on each item in a sequence.
1324 -----------------------
1329 ------------------------
1333 ... [a b c] [Q] . step
1334 ----------------------------------------
1335 ... a . Q [b c] [Q] step
1337 The step combinator executes the quotation on each member of the list
1338 on top of the stack.
1340 (quote, (aggregate, stack)) = S
1342 return stack, expression, dictionary
1343 head, tail = aggregate
1344 stack = quote, (head, stack)
1346 expression = tail, (quote, (S_step, expression))
1347 expression = S_i, expression
1348 return stack, expression, dictionary
1352 @combinator_effect(_COMB_NUMS(), i1, s6)
1354 def times(stack, expression, dictionary):
1356 times == [-- dip] cons [swap] infra [0 >] swap while pop
1360 --------------------- w/ n <= 0
1365 ---------------------------------
1370 --------------------------------- w/ n > 1
1371 ... . Q (n - 1) [Q] times
1374 # times == [-- dip] cons [swap] infra [0 >] swap while pop
1375 (quote, (n, stack)) = stack
1377 return stack, expression, dictionary
1380 expression = n, (quote, (S_times, expression))
1381 expression = concat(quote, expression)
1382 return stack, expression, dictionary
1385 # The current definition above works like this:
1388 # --------------------------------------
1389 # [P] nullary [Q [P] nullary] loop
1391 # while == [pop i not] [popop] [dudipd] primrec
1393 #def while_(S, expression, dictionary):
1394 # '''[if] [body] while'''
1395 # (body, (if_, stack)) = S
1396 # while joy(stack, if_, dictionary)[0][0]:
1397 # stack = joy(stack, body, dictionary)[0]
1398 # return stack, expression, dictionary
1402 #@combinator_effect(_COMB_NUMS(), b1, s6)
1404 def loop(stack, expression, dictionary):
1406 Basic loop combinator.
1410 -----------------------
1414 ------------------------
1418 quote, (flag, stack) = stack
1420 expression = concat(quote, (quote, (S_loop, expression)))
1421 return stack, expression, dictionary
1425 @combinator_effect(_COMB_NUMS(), a1, a2, s6, s7, s8)
1427 def cmp_(stack, expression, dictionary):
1429 cmp takes two values and three quoted programs on the stack and runs
1430 one of the three depending on the results of comparing the two values:
1434 ------------------------- a > b
1438 ------------------------- a = b
1442 ------------------------- a < b
1445 L, (E, (G, (b, (a, stack)))) = stack
1446 expression = concat(G if a > b else L if a < b else E, expression)
1447 return stack, expression, dictionary
1450 # FunctionWrapper(cleave),
1451 # FunctionWrapper(while_),
1456 #divmod_ = pm = __(n2, n1), __(n4, n3)
1458 sec_binary_cmp(BinaryBuiltinWrapper(operator.eq)),
1459 sec_binary_cmp(BinaryBuiltinWrapper(operator.ge)),
1460 sec_binary_cmp(BinaryBuiltinWrapper(operator.gt)),
1461 sec_binary_cmp(BinaryBuiltinWrapper(operator.le)),
1462 sec_binary_cmp(BinaryBuiltinWrapper(operator.lt)),
1463 sec_binary_cmp(BinaryBuiltinWrapper(operator.ne)),
1465 sec_binary_ints(BinaryBuiltinWrapper(operator.xor)),
1466 sec_binary_ints(BinaryBuiltinWrapper(operator.lshift)),
1467 sec_binary_ints(BinaryBuiltinWrapper(operator.rshift)),
1469 sec_binary_logic(BinaryBuiltinWrapper(operator.and_)),
1470 sec_binary_logic(BinaryBuiltinWrapper(operator.or_)),
1472 sec_binary_math(BinaryBuiltinWrapper(operator.add)),
1473 sec_binary_math(BinaryBuiltinWrapper(operator.floordiv)),
1474 sec_binary_math(BinaryBuiltinWrapper(operator.mod)),
1475 sec_binary_math(BinaryBuiltinWrapper(operator.mul)),
1476 sec_binary_math(BinaryBuiltinWrapper(operator.pow)),
1477 sec_binary_math(BinaryBuiltinWrapper(operator.sub)),
1478 sec_binary_math(BinaryBuiltinWrapper(operator.truediv)),
1480 sec_unary_logic(UnaryBuiltinWrapper(bool)),
1481 sec_unary_logic(UnaryBuiltinWrapper(operator.not_)),
1483 sec_unary_math(UnaryBuiltinWrapper(abs)),
1484 sec_unary_math(UnaryBuiltinWrapper(operator.neg)),
1485 sec_unary_math(UnaryBuiltinWrapper(sqrt)),
1487 stack_effect(n1)(i1)(UnaryBuiltinWrapper(floor)),
1490 del F # Otherwise Sphinx autodoc will pick it up.
1493 YIN_STACK_EFFECTS = yin_functions()
1495 # Load the auto-generated primitives into the dictionary.
1496 _functions.update(YIN_STACK_EFFECTS)
1499 # eh = compose(dup, bool)
1500 # sqr = compose(dup, mul)
1501 # of = compose(swap, at)
1503 # ''' in dict(compose=compose), _functions
1504 for name in sorted(_functions):
1505 sec = _functions[name]
1506 F = FUNCTIONS[name] = SymbolJoyType(name, [sec], _SYM_NUMS())
1507 if name in YIN_STACK_EFFECTS:
1508 _log.info('Setting stack effect for Yin function %s := %s', F.name, doc_from_stack_effect(*sec))
1510 for name, primitive in getmembers(genlib, isfunction):
1511 inscribe(SimpleFunctionWrapper(primitive))
1514 add_aliases(_dictionary, ALIASES)
1515 add_aliases(_functions, ALIASES)
1516 add_aliases(FUNCTIONS, ALIASES)
1519 DefinitionWrapper.add_definitions(definitions, _dictionary)
1522 EXPECTATIONS = dict(
1523 ifte=(s7, (s6, (s5, s4))),
1537 C = _dictionary[name]
1538 expect = EXPECTATIONS.get(name)
1540 sec = doc_from_stack_effect(expect)
1541 _log.info('Setting stack EXPECT for combinator %s := %s', C.name, sec)
1543 _log.info('combinator %s', C.name)
1544 FUNCTIONS[name] = CombinatorJoyType(name, [C], _COMB_NUMS(), expect)
1548 of quoted enstacken ?
1549 unary binary ternary
1552 of_ = _dictionary[name]
1553 secs = infer_expression(of_.body)
1554 assert len(secs) == 1, repr(secs)
1556 'Setting stack effect for definition %s := %s',
1558 doc_from_stack_effect(*secs[0]),
1560 FUNCTIONS[name] = SymbolJoyType(name, infer_expression(of_.body), _SYM_NUMS())
1563 #sec_Ns_math(_dictionary['product'])
1565 ## product == 1 swap [*] step
1566 ## flatten == [] swap [concat] step
1567 ## disenstacken == ? [uncons ?] loop pop
1569 ## size == 0 swap [pop ++] step
1571 ## cleave == fork [popd] dip
1572 ## average == [sum 1.0 *] [size] cleave /
1573 ## gcd == 1 [tuck modulus dup 0 >] loop pop
1574 ## least_fraction == dup [gcd] infra [div] concat map
1575 ## *fraction == [uncons] dip uncons [swap] dip concat [*] infra [*] dip cons
1576 ## *fraction0 == concat [[swap] dip * [*] dip] infra
1577 ## down_to_zero == [0 >] [dup --] while
1578 ## range_to_zero == unit [down_to_zero] infra
1579 ## anamorphism == [pop []] swap [dip swons] genrec
1580 ## range == [0 <=] [1 - dup] anamorphism
1581 ## while == swap [nullary] cons dup dipd concat loop
1582 ## dupdipd == dup dipd
1583 ## primrec == [i] genrec
1584 ## step_zero == 0 roll> step
1585 ## codireco == cons dip rest cons
1586 ## make_generator == [codireco] ccons
1587 ## ifte == [nullary not] dipd branch