1 # -*- coding: utf-8 -*-
3 # Copyright © 2014-2020 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 pkg_resources import resource_stream
27 from io import TextIOWrapper
28 from inspect import getdoc, getmembers, isfunction
29 from functools import wraps
30 from itertools import count
33 from . import __name__ as _joy_package_name
34 from .parser import text_to_expression, Symbol
35 from .utils import generated_library as genlib
36 from .utils.errors import (
41 from .utils.stack import (
50 def default_defs(dictionary):
51 def_stream = TextIOWrapper(
52 resource_stream(_joy_package_name, 'defs.txt'),
55 Def.load_definitions(def_stream, dictionary)
68 # This is the main dict we're building.
72 def inscribe(function, d=_dictionary):
73 '''A decorator to inscribe functions into the default dictionary.'''
74 d[function.name] = function
79 '''Return a dictionary of Joy functions for use with joy().'''
80 return _dictionary.copy()
88 ('floordiv', ['/floor', '//', '/', 'div']),
89 ('mod', ['%', 'rem', 'remainder', 'modulus']),
92 ('getitem', ['pick', 'at']),
103 ('rolldown', ['roll<']),
104 ('rollup', ['roll>']),
110 def add_aliases(D, A):
112 Given a dict and a iterable of (name, [alias, ...]) pairs, create
113 additional entries in the dict mapping each alias to the named function
114 if it's in the dict. Aliases for functions not in the dict are ignored.
116 for name, aliases in A:
121 for alias in aliases:
125 def FunctionWrapper(f):
126 '''Set name attribute.'''
128 raise ValueError('Function %s must have doc string.' % f.__name__)
129 f.name = f.__name__.rstrip('_') # Don't shadow builtins.
133 def SimpleFunctionWrapper(f):
135 Wrap functions that take and return just a stack.
139 def inner(stack, expression, dictionary):
140 return f(stack), expression, dictionary
144 def BinaryBuiltinWrapper(f):
146 Wrap functions that take two arguments and return a single result.
150 def inner(stack, expression, dictionary):
152 (a, (b, stack)) = stack
154 raise StackUnderflowError('Not enough values on stack.')
155 # Boolean predicates like "or" fail here. :(
156 ## if ( not isinstance(a, int)
157 ## or not isinstance(b, int)
158 ## or isinstance(a, bool) # Because bools are ints in Python.
159 ## or isinstance(b, bool)
161 ## raise NotAnIntError
163 return (result, stack), expression, dictionary
167 def UnaryBuiltinWrapper(f):
169 Wrap functions that take one argument and return a single result.
173 def inner(stack, expression, dictionary):
176 return (result, stack), expression, dictionary
182 Definitions created by inscribe.
185 def __init__(self, name, body):
188 self._body = tuple(iter_stack(body))
189 self.__doc__ = expression_to_string(body)
190 self._compiled = None
192 def __call__(self, stack, expression, dictionary):
194 return self._compiled(stack, expression, dictionary) # pylint: disable=E1102
195 expression = list_to_stack(self._body, expression)
196 return stack, expression, dictionary
199 def load_definitions(class_, stream, dictionary):
201 if line.lstrip().startswith('#'):
203 name, body = text_to_expression(line)
204 ## if name not in dictionary:
205 ## inscribe(class_(name, body), dictionary)
206 inscribe(class_(name, body), dictionary)
216 def inscribe_(stack, expression, dictionary):
218 Create a new Joy function definition in the Joy dictionary. A
219 definition is given as a quote with a name followed by a Joy
220 expression. for example:
222 [sqr dup mul] inscribe
225 (name, body), stack = stack
226 inscribe(Def(name, body), dictionary)
227 return stack, expression, dictionary
231 @SimpleFunctionWrapper
233 '''Parse the string on the stack to a Joy expression.'''
235 expression = text_to_expression(text)
236 return expression, stack
240 # @SimpleFunctionWrapper
242 # '''Attempt to infer the stack effect of a Joy expression.'''
244 # effects = infer_expression(E)
245 # e = list_to_stack([(fi, (fo, ())) for fi, fo in effects])
250 @SimpleFunctionWrapper
255 getitem == drop first
257 Expects an integer and a quote on the stack and returns the item at the
258 nth position in the quote counting from 0.
262 -------------------------
266 n, (Q, stack) = stack
267 return pick(Q, n), stack
271 @SimpleFunctionWrapper
278 Expects an integer and a quote on the stack and returns the quote with
279 n items removed off the top.
283 ----------------------
287 n, (Q, stack) = stack
298 @SimpleFunctionWrapper
301 Expects an integer and a quote on the stack and returns the quote with
302 just the top n items in reverse order (because that's easier and you can
303 use reverse if needed.)
307 ----------------------
311 n, (Q, stack) = stack
325 def gcd2(stack, expression, dictionary):
326 '''Compiled GCD function.'''
327 (v1, (v2, stack)) = stack
332 (v1, (v2, stack)) = (v3, (v1, stack))
333 return (v2, stack), expression, dictionary
337 @SimpleFunctionWrapper
340 Use a Boolean value to select one of two items.
344 ----------------------
349 ---------------------
352 Currently Python semantics are used to evaluate the "truthiness" of the
353 Boolean value (so empty string, zero, etc. are counted as false, etc.)
355 (if_, (then, (else_, stack))) = stack
356 return then if if_ else else_, stack
360 @SimpleFunctionWrapper
363 Use a Boolean value to select one of two items from a sequence.
367 ------------------------
372 -----------------------
375 The sequence can contain more than two items but not fewer.
376 Currently Python semantics are used to evaluate the "truthiness" of the
377 Boolean value (so empty string, zero, etc. are counted as false, etc.)
379 (flag, (choices, stack)) = stack
380 (else_, (then, _)) = choices
381 return then if flag else else_, stack
385 @SimpleFunctionWrapper
387 '''Given a list find the maximum.'''
389 return max(iter_stack(tos)), stack
393 @SimpleFunctionWrapper
395 '''Given a list find the minimum.'''
397 return min(iter_stack(tos)), stack
401 @SimpleFunctionWrapper
404 Given a quoted sequence of numbers return the sum.
407 sum == 0 swap [+] step
411 return sum(iter_stack(tos)), stack
415 @SimpleFunctionWrapper
418 Expects an item on the stack and a quote under it and removes that item
419 from the the quote. The item is only removed once.
423 ------------------------
427 (tos, (second, stack)) = S
428 l = list(iter_stack(second))
430 return list_to_stack(l), stack
434 @SimpleFunctionWrapper
436 '''Given a list remove duplicate items.'''
438 I = list(iter_stack(tos))
439 return list_to_stack(sorted(set(I), key=I.index)), stack
443 @SimpleFunctionWrapper
445 '''Given a list return it sorted.'''
447 return list_to_stack(sorted(iter_stack(tos))), stack
451 @SimpleFunctionWrapper
453 '''Clear everything from the stack.
456 clear == stack [pop stack] loop
466 @SimpleFunctionWrapper
467 def disenstacken(stack):
469 The disenstacken operator expects a list on top of the stack and makes that
470 the stack discarding the rest of the stack.
476 @SimpleFunctionWrapper
479 Reverse the list on the top of the stack.
482 reverse == [] swap shunt
486 for term in iter_stack(tos):
492 @SimpleFunctionWrapper
495 Concatinate the two lists on the top of the stack.
498 [a b c] [d e f] concat
499 ----------------------------
503 (tos, (second, stack)) = S
504 return concat(second, tos), stack
508 @SimpleFunctionWrapper
511 Like concat but reverses the top list into the second.
514 shunt == [swons] step == reverse swap concat
516 [a b c] [d e f] shunt
517 ---------------------------
521 (tos, (second, stack)) = stack
524 second = term, second
529 @SimpleFunctionWrapper
532 Replace the two lists on the top of the stack with a list of the pairs
533 from each list. The smallest list sets the length of the result list.
535 (tos, (second, stack)) = S
538 for a, b in zip(iter_stack(tos), iter_stack(second))
540 return list_to_stack(accumulator), stack
544 @SimpleFunctionWrapper
548 return tos + 1, stack
552 @SimpleFunctionWrapper
556 return tos - 1, stack
560 @SimpleFunctionWrapper
571 a, (b, stack) = stack
577 return int(math.floor(n))
579 floor.__doc__ = math.floor.__doc__
583 @SimpleFunctionWrapper
586 divmod(x, y) -> (quotient, remainder)
588 Return the tuple (x//y, x%y). Invariant: q * y + r == x.
597 Return the square root of the number a.
598 Negative numbers return complex roots.
603 assert a < 0, repr(a)
604 r = math.sqrt(-a) * 1j
610 # if isinstance(text, str):
611 # return run(text, stack)
616 @SimpleFunctionWrapper
618 '''The identity function.'''
623 @SimpleFunctionWrapper
625 '''True if the form on TOS is void otherwise False.'''
627 return _void(form), stack
631 return any(not _void(i) for i in iter_stack(form))
642 def words(stack, expression, dictionary):
643 '''Print all the words in alphabetical order.'''
644 print(' '.join(sorted(dictionary)))
645 return stack, expression, dictionary
650 def sharing(stack, expression, dictionary):
651 '''Print redistribution information.'''
652 print("You may convey verbatim copies of the Program's source code as"
653 ' you receive it, in any medium, provided that you conspicuously'
654 ' and appropriately publish on each copy an appropriate copyright'
655 ' notice; keep intact all notices stating that this License and'
656 ' any non-permissive terms added in accord with section 7 apply'
657 ' to the code; keep intact all notices of the absence of any'
658 ' warranty; and give all recipients a copy of this License along'
660 ' You should have received a copy of the GNU General Public License'
661 ' along with Thun. If not see <http://www.gnu.org/licenses/>.')
662 return stack, expression, dictionary
667 def warranty(stack, expression, dictionary):
668 '''Print warranty information.'''
669 print('THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY'
670 ' APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE'
671 ' COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM'
672 ' "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR'
673 ' IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES'
674 ' OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE'
675 ' ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS'
676 ' WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE'
677 ' COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.')
678 return stack, expression, dictionary
681 # def simple_manual(stack):
683 # Print words and help for each word.
685 # for name, f in sorted(FUNCTIONS.items()):
687 # boxline = '+%s+' % ('-' * (len(name) + 2))
690 # '| %s |' % (name,),
692 # d if d else ' ...',
702 def help_(S, expression, dictionary):
703 '''Accepts a quoted symbol on the top of the stack and prints its docs.'''
704 ((symbol, _), stack) = S
705 word = dictionary[symbol]
706 print(HELP_TEMPLATE % (symbol, getdoc(word), symbol))
707 return stack, expression, dictionary
715 # Several combinators depend on other words in their definitions,
716 # we use symbols to prevent hard-coding these, so in theory, you
717 # could change the word in the dictionary to use different semantics.
718 S_choice = Symbol('choice')
719 S_first = Symbol('first')
720 S_genrec = Symbol('genrec')
721 S_getitem = Symbol('getitem')
723 S_ifte = Symbol('ifte')
724 S_infra = Symbol('infra')
725 S_loop = Symbol('loop')
726 S_pop = Symbol('pop')
727 S_primrec = Symbol('primrec')
728 S_step = Symbol('step')
729 S_swaack = Symbol('swaack')
730 S_times = Symbol('times')
735 def i(stack, expression, dictionary):
737 The i combinator expects a quoted program on the stack and unpacks it
738 onto the pending expression for evaluation.
749 raise StackUnderflowError('Not enough values on stack.')
750 return stack, concat(quote, expression), dictionary
755 def x(stack, expression, dictionary):
761 ... [Q] x = ... [Q] dup i
762 ... [Q] x = ... [Q] [Q] i
763 ... [Q] x = ... [Q] Q
767 return stack, concat(quote, expression), dictionary
772 def b(stack, expression, dictionary):
778 ... [P] [Q] b == ... [P] i [Q] i
779 ... [P] [Q] b == ... P Q
782 q, (p, (stack)) = stack
783 return stack, concat(p, concat(q, expression)), dictionary
788 def ii(stack, expression, dictionary):
797 quote, (a, stack) = stack
798 expression = concat(quote, (a, concat(quote, expression)))
799 return stack, expression, dictionary
804 def dupdip(stack, expression, dictionary):
808 [F] dupdip == dup [F] dip
818 return stack, concat(F, (a, expression)), dictionary
823 def infra(stack, expression, dictionary):
825 Accept a quoted program and a list on the stack and run the program
826 with the list as its stack. Does not affect the rest of the stack.
829 ... [a b c] [Q] . infra
830 -----------------------------
831 c b a . Q [...] swaack
834 (quote, (aggregate, stack)) = stack
835 return aggregate, concat(quote, (stack, (S_swaack, expression))), dictionary
840 def genrec(stack, expression, dictionary):
842 General Recursion Combinator.
845 [if] [then] [rec1] [rec2] genrec
846 ---------------------------------------------------------------------
847 [if] [then] [rec1 [[if] [then] [rec1] [rec2] genrec] rec2] ifte
849 From "Recursion Theory and Joy" (j05cmp.html) by Manfred von Thun:
850 "The genrec combinator takes four program parameters in addition to
851 whatever data parameters it needs. Fourth from the top is an if-part,
852 followed by a then-part. If the if-part yields true, then the then-part
853 is executed and the combinator terminates. The other two parameters are
854 the rec1-part and the rec2-part. If the if-part yields false, the
855 rec1-part is executed. Following that the four program parameters and
856 the combinator are again pushed onto the stack bundled up in a quoted
857 form. Then the rec2-part is executed, where it will find the bundled
858 form. Typically it will then execute the bundled form, either with i or
859 with app2, or some other combinator."
861 The way to design one of these is to fix your base case [then] and the
862 test [if], and then treat rec1 and rec2 as an else-part "sandwiching"
863 a quotation of the whole function.
865 For example, given a (general recursive) function 'F':
868 F == [I] [T] [R1] [R2] genrec
870 If the [I] if-part fails you must derive R1 and R2 from:
875 Just set the stack arguments in front, and figure out what R1 and R2
876 have to do to apply the quoted [F] in the proper way. In effect, the
877 genrec combinator turns into an ifte combinator with a quoted copy of
878 the original definition in the else-part:
881 F == [I] [T] [R1] [R2] genrec
882 == [I] [T] [R1 [F] R2] ifte
884 Primitive recursive functions are those where R2 == i.
887 P == [I] [T] [R] tailrec
888 == [I] [T] [R [P] i] ifte
889 == [I] [T] [R P] ifte
892 (rec2, (rec1, stack)) = stack
893 (then, (if_, _)) = stack
894 F = (if_, (then, (rec1, (rec2, (S_genrec, ())))))
895 else_ = concat(rec1, (F, rec2))
896 return (else_, stack), (S_ifte, expression), dictionary
901 def map_(S, expression, dictionary):
903 Run the quoted program on TOS on the items in the list under it, push a
904 new list with the results in place of the program and original list.
906 # (quote, (aggregate, stack)) = S
907 # results = list_to_stack([
908 # joy((term, stack), quote, dictionary)[0][0]
909 # for term in iter_stack(aggregate)
911 # return (results, stack), expression, dictionary
912 (quote, (aggregate, stack)) = S
914 return (aggregate, stack), expression, dictionary
916 for term in iter_stack(aggregate):
918 batch = (s, (quote, (S_infra, (S_first, batch))))
919 stack = (batch, ((), stack))
920 return stack, (S_infra, expression), dictionary
925 def primrec(stack, expression, dictionary):
927 From the "Overview of the language JOY":
929 > The primrec combinator expects two quoted programs in addition to a
930 data parameter. For an integer data parameter it works like this: If
931 the data parameter is zero, then the first quotation has to produce
932 the value to be returned. If the data parameter is positive then the
933 second has to combine the data parameter with the result of applying
934 the function to its predecessor.::
938 > Then primrec tests whether the top element on the stack (initially
939 the 5) is equal to zero. If it is, it pops it off and executes one of
940 the quotations, the [1] which leaves 1 on the stack as the result.
941 Otherwise it pushes a decremented copy of the top element and
942 recurses. On the way back from the recursion it uses the other
943 quotation, [*], to multiply what is now a factorial on top of the
944 stack by the second element on the stack.::
946 n [Base] [Recur] primrec
948 0 [Base] [Recur] primrec
949 ------------------------------
952 n [Base] [Recur] primrec
953 ------------------------------------------ n > 0
954 n (n-1) [Base] [Recur] primrec Recur
957 recur, (base, (n, stack)) = stack
959 expression = concat(base, expression)
961 expression = S_primrec, concat(recur, expression)
962 stack = recur, (base, (n - 1, (n, stack)))
963 return stack, expression, dictionary
966 #def cleave(S, expression, dictionary):
968 # The cleave combinator expects two quotations, and below that an item X.
969 # It first executes [P], with X on top, and saves the top result element.
970 # Then it executes [Q], again with X, and saves the top result.
971 # Finally it restores the stack to what it was below X and pushes the two
972 # results P(X) and Q(X).
974 # (Q, (P, (x, stack))) = S
975 # p = joy((x, stack), P, dictionary)[0][0]
976 # q = joy((x, stack), Q, dictionary)[0][0]
977 # return (q, (p, stack)), expression, dictionary
982 def branch(stack, expression, dictionary):
984 Use a Boolean value to select one of two quoted programs to run.
988 branch == roll< choice i
993 --------------------------
997 -------------------------
1001 (then, (else_, (flag, stack))) = stack
1002 return stack, concat(then if flag else else_, expression), dictionary
1007 ##def ifte(stack, expression, dictionary):
1009 ## If-Then-Else Combinator
1012 ## ... [if] [then] [else] ifte
1013 ## ---------------------------------------------------
1014 ## ... [[else] [then]] [...] [if] infra select i
1019 ## ... [if] [then] [else] ifte
1020 ## -------------------------------------------------------
1021 ## ... [else] [then] [...] [if] infra first choice i
1024 ## Has the effect of grabbing a copy of the stack on which to run the
1025 ## if-part using infra.
1027 ## (else_, (then, (if_, stack))) = stack
1028 ## expression = (S_infra, (S_first, (S_choice, (S_i, expression))))
1029 ## stack = (if_, (stack, (then, (else_, stack))))
1030 ## return stack, expression, dictionary
1035 def cond(stack, expression, dictionary):
1037 This combinator works like a case statement. It expects a single quote
1038 on the stack that must contain zero or more condition quotes and a
1039 default quote. Each condition clause should contain a quoted predicate
1040 followed by the function expression to run if that predicate returns
1041 true. If no predicates return true the default function runs.
1043 It works by rewriting into a chain of nested `ifte` expressions, e.g.::
1045 [[[B0] T0] [[B1] T1] [D]] cond
1046 -----------------------------------------
1047 [B0] [T0] [[B1] [T1] [D] ifte] ifte
1050 conditions, stack = stack
1052 expression = _cond(conditions, expression)
1054 # Attempt to preload the args to first ifte.
1055 (P, (T, (E, expression))) = expression
1057 # If, for any reason, the argument to cond should happen to contain
1058 # only the default clause then this optimization will fail.
1061 stack = (E, (T, (P, stack)))
1062 return stack, expression, dictionary
1065 def _cond(conditions, expression):
1066 (clause, rest) = conditions
1067 if not rest: # clause is [D]
1070 return (P, (T, (_cond(rest, ()), (S_ifte, expression))))
1075 def dip(stack, expression, dictionary):
1077 The dip combinator expects a quoted program on the stack and below it
1078 some item, it hoists the item into the expression and runs the program
1079 on the rest of the stack.
1088 (quote, (x, stack)) = stack
1090 raise StackUnderflowError('Not enough values on stack.')
1091 expression = (x, expression)
1092 return stack, concat(quote, expression), dictionary
1097 def dipd(S, expression, dictionary):
1099 Like dip but expects two items.
1103 ---------------------
1107 (quote, (x, (y, stack))) = S
1108 expression = (y, (x, expression))
1109 return stack, concat(quote, expression), dictionary
1114 def dipdd(S, expression, dictionary):
1116 Like dip but expects three items.
1120 -----------------------
1124 (quote, (x, (y, (z, stack)))) = S
1125 expression = (z, (y, (x, expression)))
1126 return stack, concat(quote, expression), dictionary
1131 def app1(S, expression, dictionary):
1133 Given a quoted program on TOS and anything as the second stack item run
1134 the program and replace the two args with the first result of the
1139 -----------------------------------
1140 ... [x ...] [Q] . infra first
1143 (quote, (x, stack)) = S
1144 stack = (quote, ((x, stack), stack))
1145 expression = (S_infra, (S_first, expression))
1146 return stack, expression, dictionary
1151 def app2(S, expression, dictionary):
1152 '''Like app1 with two items.
1156 -----------------------------------
1157 ... [y ...] [Q] . infra first
1158 [x ...] [Q] infra first
1161 (quote, (x, (y, stack))) = S
1162 expression = (S_infra, (S_first,
1163 ((x, stack), (quote, (S_infra, (S_first,
1165 stack = (quote, ((y, stack), stack))
1166 return stack, expression, dictionary
1171 def app3(S, expression, dictionary):
1172 '''Like app1 with three items.
1175 ... z y x [Q] . app3
1176 -----------------------------------
1177 ... [z ...] [Q] . infra first
1178 [y ...] [Q] infra first
1179 [x ...] [Q] infra first
1182 (quote, (x, (y, (z, stack)))) = S
1183 expression = (S_infra, (S_first,
1184 ((y, stack), (quote, (S_infra, (S_first,
1185 ((x, stack), (quote, (S_infra, (S_first,
1186 expression))))))))))
1187 stack = (quote, ((z, stack), stack))
1188 return stack, expression, dictionary
1193 def step(S, expression, dictionary):
1195 Run a quoted program on each item in a sequence.
1199 -----------------------
1204 ------------------------
1208 ... [a b c] [Q] . step
1209 ----------------------------------------
1210 ... a . Q [b c] [Q] step
1212 The step combinator executes the quotation on each member of the list
1213 on top of the stack.
1215 (quote, (aggregate, stack)) = S
1217 return stack, expression, dictionary
1218 head, tail = aggregate
1219 stack = quote, (head, stack)
1221 expression = tail, (quote, (S_step, expression))
1222 expression = S_i, expression
1223 return stack, expression, dictionary
1228 def times(stack, expression, dictionary):
1230 times == [-- dip] cons [swap] infra [0 >] swap while pop
1234 --------------------- w/ n <= 0
1239 -----------------------
1244 ------------------------------------- w/ n > 1
1245 ... . Q (n - 1) [Q] times
1248 # times == [-- dip] cons [swap] infra [0 >] swap while pop
1249 (quote, (n, stack)) = stack
1251 return stack, expression, dictionary
1254 expression = n, (quote, (S_times, expression))
1255 expression = concat(quote, expression)
1256 return stack, expression, dictionary
1259 # The current definition above works like this:
1262 # --------------------------------------
1263 # [P] nullary [Q [P] nullary] loop
1265 # while == [pop i not] [popop] [dudipd] tailrec
1267 #def while_(S, expression, dictionary):
1268 # '''[if] [body] while'''
1269 # (body, (if_, stack)) = S
1270 # while joy(stack, if_, dictionary)[0][0]:
1271 # stack = joy(stack, body, dictionary)[0]
1272 # return stack, expression, dictionary
1277 def loop(stack, expression, dictionary):
1279 Basic loop combinator.
1283 -----------------------
1287 ------------------------
1292 quote, stack = stack
1294 raise StackUnderflowError('Not enough values on stack.')
1295 if not isinstance(quote, tuple):
1296 raise NotAListError('Loop body not a list.')
1298 (flag, stack) = stack
1300 raise StackUnderflowError('Not enough values on stack.')
1302 expression = concat(quote, (quote, (S_loop, expression)))
1303 return stack, expression, dictionary
1308 def cmp_(stack, expression, dictionary):
1310 cmp takes two values and three quoted programs on the stack and runs
1311 one of the three depending on the results of comparing the two values:
1315 ------------------------- a > b
1319 ------------------------- a = b
1323 ------------------------- a < b
1326 L, (E, (G, (b, (a, stack)))) = stack
1327 expression = concat(G if a > b else L if a < b else E, expression)
1328 return stack, expression, dictionary
1331 # FunctionWrapper(cleave),
1332 # FunctionWrapper(while_),
1337 #divmod_ = pm = __(n2, n1), __(n4, n3)
1339 BinaryBuiltinWrapper(operator.eq),
1340 BinaryBuiltinWrapper(operator.ge),
1341 BinaryBuiltinWrapper(operator.gt),
1342 BinaryBuiltinWrapper(operator.le),
1343 BinaryBuiltinWrapper(operator.lt),
1344 BinaryBuiltinWrapper(operator.ne),
1346 BinaryBuiltinWrapper(operator.xor),
1347 BinaryBuiltinWrapper(operator.lshift),
1348 BinaryBuiltinWrapper(operator.rshift),
1350 BinaryBuiltinWrapper(operator.and_),
1351 BinaryBuiltinWrapper(operator.or_),
1353 BinaryBuiltinWrapper(operator.add),
1354 BinaryBuiltinWrapper(operator.floordiv),
1355 BinaryBuiltinWrapper(operator.mod),
1356 BinaryBuiltinWrapper(operator.mul),
1357 BinaryBuiltinWrapper(operator.pow),
1358 BinaryBuiltinWrapper(operator.sub),
1359 ## BinaryBuiltinWrapper(operator.truediv),
1361 UnaryBuiltinWrapper(bool),
1362 UnaryBuiltinWrapper(operator.not_),
1364 UnaryBuiltinWrapper(abs),
1365 UnaryBuiltinWrapper(operator.neg),
1366 UnaryBuiltinWrapper(sqrt),
1368 UnaryBuiltinWrapper(floor),
1369 UnaryBuiltinWrapper(round),
1372 del F # Otherwise Sphinx autodoc will pick it up.
1375 for name, primitive in getmembers(genlib, isfunction):
1376 inscribe(SimpleFunctionWrapper(primitive))
1379 add_aliases(_dictionary, ALIASES)