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 (
62 poly_combinator_effect,
63 doc_from_stack_effect,
67 _SYM_NUMS = count().next
68 _COMB_NUMS = count().next
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)
82 As = map(AnyStarJoyType, _R)
83 Ns = map(NumberStarJoyType, _R)
84 Ss = map(StackStarJoyType, _R)
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)
101 def inscribe(function):
102 '''A decorator to inscribe functions into the default dictionary.'''
103 _dictionary[function.name] = function
108 '''Return a dictionary of Joy functions for use with joy().'''
109 return _dictionary.copy()
115 ('bool', ['truthy']),
117 ('floordiv', ['/floor', '//']),
118 ('floor', ['round']),
120 ('mod', ['%', 'rem', 'remainder', 'modulus']),
123 ('getitem', ['pick', 'at']),
128 ('ne', ['<>', '!=']),
134 ('rolldown', ['roll<']),
135 ('rollup', ['roll>']),
141 def add_aliases(D, A):
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.
147 for name, aliases in A:
152 for alias in aliases:
158 Return a dict of named stack effects.
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.
164 # pylint: disable=unused-variable
165 cons = ef(a1, s0)((a1, s0))
166 ccons = compose(cons, cons)
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)
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)
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, ()))
195 first_two = compose(uncons, uncons, pop)
196 fourth = compose(rest, third)
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)
208 product == 1 swap [*] step
209 flatten == [] swap [concat] step
212 enstacken == stack [clear] dip
214 disenstacken == ? [uncons ?] loop pop
215 dinfrirst == dip infra first
216 nullary == [stack] dinfrirst
217 unary == nullary popd
218 binary == nullary [popop] dip
219 ternary == unary [popop] dip
223 size == 0 swap [pop ++] step
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
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
245 # ifte == [nullary] dipd swap branch
246 # genrec == [[genrec] cons cons cons cons] nullary swons concat ifte
248 # Another definition for while. FWIW
249 # while == over [[i] dip nullary] ccons [nullary] dip loop
253 ##second == rest first
254 ##third == rest rest first
256 ##swoncat == swap concat
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
265 ##divisor == popop 2 *
267 ##radical == swap dup * rollup * 4 * - sqrt
270 ##q0 == [[divisor] [minusb] [radical]] pam
271 ##q1 == [[root1] [root2]] pam
272 ##quadratic == [q0] ternary i [q1] ternary
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
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
286 def FunctionWrapper(f):
287 '''Set name attribute.'''
289 raise ValueError('Function %s must have doc string.' % f.__name__)
290 f.name = f.__name__.rstrip('_') # Don't shadow builtins.
294 def SimpleFunctionWrapper(f):
296 Wrap functions that take and return just a stack.
300 @rename_code_object(f.__name__)
301 def inner(stack, expression, dictionary):
302 return f(stack), expression, dictionary
306 def BinaryBuiltinWrapper(f):
308 Wrap functions that take two arguments and return a single result.
312 @rename_code_object(f.__name__)
313 def inner(stack, expression, dictionary):
314 (a, (b, stack)) = stack
316 return (result, stack), expression, dictionary
320 def UnaryBuiltinWrapper(f):
322 Wrap functions that take one argument and return a single result.
326 @rename_code_object(f.__name__)
327 def inner(stack, expression, dictionary):
330 return (result, stack), expression, dictionary
334 class DefinitionWrapper(object):
336 Provide implementation of defined functions, and some helper methods.
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
346 def __call__(self, stack, expression, dictionary):
348 return self._compiled(stack, expression, dictionary) # pylint: disable=E1102
349 expression = list_to_stack(self._body, expression)
350 return stack, expression, dictionary
353 def parse_definition(class_, defi):
355 Given some text describing a Joy function definition parse it and
356 return a DefinitionWrapper.
358 name, proper, body_text = (n.strip() for n in defi.partition('=='))
360 raise ValueError('Definition %r failed' % (defi,))
361 return class_(name, body_text)
364 def add_definitions(class_, defs, dictionary):
366 Scan multi-line string defs for definitions and add them to the
369 for definition in _text_to_defs(defs):
370 class_.add_def(definition, dictionary)
373 def add_def(class_, definition, dictionary, fail_fails=False):
375 Add the definition to the dictionary.
377 F = class_.parse_definition(definition)
379 # print F.name, F._body
380 secs = infer(*F._body)
383 'Failed to infer stack effect of %s == %s',
385 expression_to_string(F.body),
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
395 def _text_to_defs(text):
396 return (line.strip() for line in text.splitlines() if '==' in line)
407 def inscribe_(stack, expression, dictionary):
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:
415 If you want the definition to persist over restarts, enter it into
416 the definitions.txt resource.
418 definition, stack = stack
419 DefinitionWrapper.add_def(definition, dictionary, fail_fails=True)
420 return stack, expression, dictionary
424 @SimpleFunctionWrapper
426 '''Parse the string on the stack to a Joy expression.'''
428 expression = text_to_expression(text)
429 return expression, stack
434 @SimpleFunctionWrapper
439 getitem == drop first
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.
446 -------------------------
450 n, (Q, stack) = stack
451 return pick(Q, n), stack
456 @SimpleFunctionWrapper
463 Expects an integer and a quote on the stack and returns the quote with
464 n items removed off the top.
468 ----------------------
472 n, (Q, stack) = stack
484 @SimpleFunctionWrapper
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.)
493 ----------------------
497 n, (Q, stack) = stack
510 @SimpleFunctionWrapper
513 Use a Boolean value to select one of two items.
517 ----------------------
522 ---------------------
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.)
528 (if_, (then, (else_, stack))) = stack
529 return then if if_ else else_, stack
533 @SimpleFunctionWrapper
536 Use a Boolean value to select one of two items from a sequence.
540 ------------------------
545 -----------------------
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.)
552 (flag, (choices, stack)) = stack
553 (else_, (then, _)) = choices
554 return then if flag else else_, stack
559 @SimpleFunctionWrapper
561 '''Given a list find the maximum.'''
563 return max(iter_stack(tos)), stack
568 @SimpleFunctionWrapper
570 '''Given a list find the minimum.'''
572 return min(iter_stack(tos)), stack
577 @SimpleFunctionWrapper
579 '''Given a quoted sequence of numbers return the sum.
581 sum == 0 swap [+] step
584 return sum(iter_stack(tos)), stack
588 @SimpleFunctionWrapper
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.
596 ------------------------
600 (tos, (second, stack)) = S
601 l = list(iter_stack(second))
603 return list_to_stack(l), stack
607 @SimpleFunctionWrapper
609 '''Given a list remove duplicate items.'''
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
617 @SimpleFunctionWrapper
619 '''Given a list return it sorted.'''
621 return list_to_stack(sorted(iter_stack(tos))), stack
624 _functions['clear'] = s0, s1
626 @SimpleFunctionWrapper
628 '''Clear everything from the stack.
631 clear == stack [pop stack] loop
641 @SimpleFunctionWrapper
644 The unstack operator expects a list on top of the stack and makes that
645 the stack discarding the rest of the stack.
651 @SimpleFunctionWrapper
653 '''Reverse the list on the top of the stack.
656 reverse == [] swap shunt
660 for term in iter_stack(tos):
666 @combinator_effect(_COMB_NUMS(), s7, s6)
667 @SimpleFunctionWrapper
669 '''Concatinate the two lists on the top of the stack.
672 [a b c] [d e f] concat
673 ----------------------------
677 (tos, (second, stack)) = S
678 return concat(second, tos), stack
682 @SimpleFunctionWrapper
684 '''Like concat but reverses the top list into the second.
687 shunt == [swons] step == reverse swap concat
689 [a b c] [d e f] shunt
690 ---------------------------
694 (tos, (second, stack)) = stack
697 second = term, second
702 @SimpleFunctionWrapper
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.
708 (tos, (second, stack)) = S
711 for a, b in zip(iter_stack(tos), iter_stack(second))
713 return list_to_stack(accumulator), stack
717 @SimpleFunctionWrapper
721 return tos + 1, stack
725 @SimpleFunctionWrapper
729 return tos - 1, stack
733 @SimpleFunctionWrapper
744 a, (b, stack) = stack
750 return int(math.floor(n))
752 floor.__doc__ = math.floor.__doc__
756 @SimpleFunctionWrapper
759 divmod(x, y) -> (quotient, remainder)
761 Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
770 Return the square root of the number a.
771 Negative numbers return complex roots.
776 assert a < 0, repr(a)
777 r = math.sqrt(-a) * 1j
783 # if isinstance(text, str):
784 # return run(text, stack)
789 @SimpleFunctionWrapper
791 '''The identity function.'''
796 @SimpleFunctionWrapper
798 '''True if the form on TOS is void otherwise False.'''
800 return _void(form), stack
804 return any(not _void(i) for i in iter_stack(form))
815 def words(stack, expression, dictionary):
816 '''Print all the words in alphabetical order.'''
817 print(' '.join(sorted(dictionary)))
818 return stack, expression, dictionary
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'
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
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
854 # def simple_manual(stack):
856 # Print words and help for each word.
858 # for name, f in sorted(FUNCTIONS.items()):
860 # boxline = '+%s+' % ('-' * (len(name) + 2))
863 # '| %s |' % (name,),
865 # d if d else ' ...',
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]
880 return stack, expression, dictionary
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')
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')
906 @combinator_effect(_COMB_NUMS(), s1)
908 def i(stack, expression, dictionary):
910 The i combinator expects a quoted program on the stack and unpacks it
911 onto the pending expression for evaluation.
920 return stack, concat(quote, expression), dictionary
924 @combinator_effect(_COMB_NUMS(), s1)
926 def x(stack, expression, dictionary):
932 ... [Q] x = ... [Q] dup i
933 ... [Q] x = ... [Q] [Q] i
934 ... [Q] x = ... [Q] Q
938 return stack, concat(quote, expression), dictionary
942 @combinator_effect(_COMB_NUMS(), s7, s6)
944 def b(stack, expression, dictionary):
950 ... [P] [Q] b == ... [P] i [Q] i
951 ... [P] [Q] b == ... P Q
954 q, (p, (stack)) = stack
955 return stack, concat(p, concat(q, expression)), dictionary
959 @combinator_effect(_COMB_NUMS(), a1, s1)
961 def dupdip(stack, expression, dictionary):
965 [F] dupdip == dup [F] dip
975 return stack, concat(F, (a, expression)), dictionary
979 @combinator_effect(_COMB_NUMS(), s7, s6)
981 def infra(stack, expression, dictionary):
983 Accept a quoted program and a list on the stack and run the program
984 with the list as its stack.
987 ... [a b c] [Q] . infra
988 -----------------------------
989 c b a . Q [...] swaack
992 (quote, (aggregate, stack)) = stack
993 return aggregate, concat(quote, (stack, (S_swaack, expression))), dictionary
997 #@combinator_effect(_COMB_NUMS(), s7, s6, s5, s4)
999 def genrec(stack, expression, dictionary):
1001 General Recursion Combinator.
1004 [if] [then] [rec1] [rec2] genrec
1005 ---------------------------------------------------------------------
1006 [if] [then] [rec1 [[if] [then] [rec1] [rec2] genrec] rec2] ifte
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."
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.
1024 For example, given a (general recursive) function 'F':
1027 F == [I] [T] [R1] [R2] genrec
1029 If the [I] if-part fails you must derive R1 and R2 from:
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:
1040 F == [I] [T] [R1] [R2] genrec
1041 == [I] [T] [R1 [F] R2] ifte
1043 Primitive recursive functions are those where R2 == i.
1046 P == [I] [T] [R] primrec
1047 == [I] [T] [R [P] i] ifte
1048 == [I] [T] [R P] ifte
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
1059 @combinator_effect(_COMB_NUMS(), s7, s6)
1061 def map_(S, expression, dictionary):
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.
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)
1071 # return (results, stack), expression, dictionary
1072 (quote, (aggregate, stack)) = S
1074 return (aggregate, stack), expression, dictionary
1076 for term in iter_stack(aggregate):
1078 batch = (s, (quote, (S_infra, (S_first, batch))))
1079 stack = (batch, ((), stack))
1080 return stack, (S_infra, expression), dictionary
1083 #def cleave(S, expression, dictionary):
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).
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
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
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
1110 @poly_combinator_effect(_COMB_NUMS(), [branch_true, branch_false], b1, s7, s6)
1112 def branch(stack, expression, dictionary):
1114 Use a Boolean value to select one of two quoted programs to run.
1118 branch == roll< choice i
1122 False [F] [T] branch
1123 --------------------------
1127 -------------------------
1131 (then, (else_, (flag, stack))) = stack
1132 return stack, concat(then if flag else else_, expression), dictionary
1135 #FUNCTIONS['branch'] = CombinatorJoyType('branch', [branch_true, branch_false], 100)
1140 ##def ifte(stack, expression, dictionary):
1142 ## If-Then-Else Combinator
1145 ## ... [if] [then] [else] ifte
1146 ## ---------------------------------------------------
1147 ## ... [[else] [then]] [...] [if] infra select i
1152 ## ... [if] [then] [else] ifte
1153 ## -------------------------------------------------------
1154 ## ... [else] [then] [...] [if] infra first choice i
1157 ## Has the effect of grabbing a copy of the stack on which to run the
1158 ## if-part using infra.
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
1168 def cond(stack, expression, dictionary):
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.
1176 It works by rewriting into a chain of nested `ifte` expressions, e.g.::
1178 [[[B0] T0] [[B1] T1] [D]] cond
1179 -----------------------------------------
1180 [B0] [T0] [[B1] [T1] [D] ifte] ifte
1183 conditions, stack = stack
1185 expression = _cond(conditions, expression)
1187 # Attempt to preload the args to first ifte.
1188 (P, (T, (E, expression))) = expression
1190 # If, for any reason, the argument to cond should happen to contain
1191 # only the default clause then this optimization will fail.
1194 stack = (E, (T, (P, stack)))
1195 return stack, expression, dictionary
1198 def _cond(conditions, expression):
1199 (clause, rest) = conditions
1200 if not rest: # clause is [D]
1203 return (P, (T, (_cond(rest, ()), (S_ifte, expression))))
1207 @combinator_effect(_COMB_NUMS(), a1, s1)
1209 def dip(stack, expression, dictionary):
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.
1221 (quote, (x, stack)) = stack
1222 expression = (x, expression)
1223 return stack, concat(quote, expression), dictionary
1227 @combinator_effect(_COMB_NUMS(), a2, a1, s1)
1229 def dipd(S, expression, dictionary):
1231 Like dip but expects two items.
1235 ---------------------
1239 (quote, (x, (y, stack))) = S
1240 expression = (y, (x, expression))
1241 return stack, concat(quote, expression), dictionary
1245 @combinator_effect(_COMB_NUMS(), a3, a2, a1, s1)
1247 def dipdd(S, expression, dictionary):
1249 Like dip but expects three items.
1253 -----------------------
1257 (quote, (x, (y, (z, stack)))) = S
1258 expression = (z, (y, (x, expression)))
1259 return stack, concat(quote, expression), dictionary
1263 @combinator_effect(_COMB_NUMS(), a1, s1)
1265 def app1(S, expression, dictionary):
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
1273 -----------------------------------
1274 ... [x ...] [Q] . infra first
1276 (quote, (x, stack)) = S
1277 stack = (quote, ((x, stack), stack))
1278 expression = (S_infra, (S_first, expression))
1279 return stack, expression, dictionary
1283 @combinator_effect(_COMB_NUMS(), a2, a1, s1)
1285 def app2(S, expression, dictionary):
1286 '''Like app1 with two items.
1290 -----------------------------------
1291 ... [y ...] [Q] . infra first
1292 [x ...] [Q] infra first
1295 (quote, (x, (y, stack))) = S
1296 expression = (S_infra, (S_first,
1297 ((x, stack), (quote, (S_infra, (S_first,
1299 stack = (quote, ((y, stack), stack))
1300 return stack, expression, dictionary
1304 @combinator_effect(_COMB_NUMS(), a3, a2, a1, s1)
1306 def app3(S, expression, dictionary):
1307 '''Like app1 with three items.
1310 ... z y x [Q] . app3
1311 -----------------------------------
1312 ... [z ...] [Q] . infra first
1313 [y ...] [Q] infra first
1314 [x ...] [Q] infra first
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
1327 @combinator_effect(_COMB_NUMS(), s7, s6)
1329 def step(S, expression, dictionary):
1331 Run a quoted program on each item in a sequence.
1335 -----------------------
1340 ------------------------
1344 ... [a b c] [Q] . step
1345 ----------------------------------------
1346 ... a . Q [b c] [Q] step
1348 The step combinator executes the quotation on each member of the list
1349 on top of the stack.
1351 (quote, (aggregate, stack)) = S
1353 return stack, expression, dictionary
1354 head, tail = aggregate
1355 stack = quote, (head, stack)
1357 expression = tail, (quote, (S_step, expression))
1358 expression = S_i, expression
1359 return stack, expression, dictionary
1363 @combinator_effect(_COMB_NUMS(), i1, s6)
1365 def times(stack, expression, dictionary):
1367 times == [-- dip] cons [swap] infra [0 >] swap while pop
1371 --------------------- w/ n <= 0
1376 ---------------------------------
1381 --------------------------------- w/ n > 1
1382 ... . Q (n - 1) [Q] times
1385 # times == [-- dip] cons [swap] infra [0 >] swap while pop
1386 (quote, (n, stack)) = stack
1388 return stack, expression, dictionary
1391 expression = n, (quote, (S_times, expression))
1392 expression = concat(quote, expression)
1393 return stack, expression, dictionary
1396 # The current definition above works like this:
1399 # --------------------------------------
1400 # [P] nullary [Q [P] nullary] loop
1402 # while == [pop i not] [popop] [dudipd] primrec
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
1413 #@combinator_effect(_COMB_NUMS(), b1, s6)
1415 def loop(stack, expression, dictionary):
1417 Basic loop combinator.
1421 -----------------------
1425 ------------------------
1429 quote, (flag, stack) = stack
1431 expression = concat(quote, (quote, (S_loop, expression)))
1432 return stack, expression, dictionary
1436 @combinator_effect(_COMB_NUMS(), a1, a2, s6, s7, s8)
1438 def cmp_(stack, expression, dictionary):
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:
1445 ------------------------- a > b
1449 ------------------------- a = b
1453 ------------------------- a < b
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
1461 # FunctionWrapper(cleave),
1462 # FunctionWrapper(while_),
1467 #divmod_ = pm = __(n2, n1), __(n4, n3)
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)),
1476 sec_binary_ints(BinaryBuiltinWrapper(operator.xor)),
1477 sec_binary_ints(BinaryBuiltinWrapper(operator.lshift)),
1478 sec_binary_ints(BinaryBuiltinWrapper(operator.rshift)),
1480 sec_binary_logic(BinaryBuiltinWrapper(operator.and_)),
1481 sec_binary_logic(BinaryBuiltinWrapper(operator.or_)),
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)),
1491 sec_unary_logic(UnaryBuiltinWrapper(bool)),
1492 sec_unary_logic(UnaryBuiltinWrapper(operator.not_)),
1494 sec_unary_math(UnaryBuiltinWrapper(abs)),
1495 sec_unary_math(UnaryBuiltinWrapper(operator.neg)),
1496 sec_unary_math(UnaryBuiltinWrapper(sqrt)),
1498 stack_effect(n1)(i1)(UnaryBuiltinWrapper(floor)),
1501 del F # Otherwise Sphinx autodoc will pick it up.
1504 YIN_STACK_EFFECTS = yin_functions()
1506 # Load the auto-generated primitives into the dictionary.
1507 _functions.update(YIN_STACK_EFFECTS)
1510 # eh = compose(dup, bool)
1511 # sqr = compose(dup, mul)
1512 # of = compose(swap, at)
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))
1521 for name, primitive in getmembers(genlib, isfunction):
1522 inscribe(SimpleFunctionWrapper(primitive))
1525 add_aliases(_dictionary, ALIASES)
1526 add_aliases(_functions, ALIASES)
1527 add_aliases(FUNCTIONS, ALIASES)
1530 DefinitionWrapper.add_definitions(definitions, _dictionary)
1532 #sec_Ns_math(_dictionary['product'])