1 # -*- coding: utf-8 -*-
3 # Copyright © 2016 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 Pretty printing support, e.g.::
23 Joy? [23 18 * 99 +] trace
35 On each line the stack is printed with the top to the left, then a
36 bullet symbol,``•``, to represent the current locus of processing, then
37 the pending expression to the right.
39 # (Kinda clunky and hacky. This should be swapped out in favor of much
41 from traceback import print_exc
42 from .stack import expression_to_string, stack_to_string
44 from ..library import FunctionWrapper
48 def trace(stack, expression, dictionary):
49 '''Evaluate a Joy expression on a stack and print a trace.
51 This function is just like the `i` combinator but it also prints a
52 trace of the evaluation
54 :param stack stack: The stack.
55 :param stack expression: The expression to evaluate.
56 :param dict dictionary: A ``dict`` mapping names to Joy functions.
57 :rtype: (stack, (), dictionary)
63 s, _, d = joy(stack, quote, dictionary, tp.viewer)
70 return s, expression, d
73 class TracePrinter(object):
75 This is what does the formatting. You instantiate it and pass the ``viewer()``
76 method to the :py:func:`joy.joy.joy` function, then print it to see the
83 def viewer(self, stack, expression):
85 Record the current stack and expression in the TracePrinter's history.
86 Pass this method as the ``viewer`` argument to the :py:func:`joy.joy.joy` function.
88 :param stack quote: A stack.
89 :param stack expression: A stack.
91 self.history.append((stack, expression))
94 return '\n'.join(self.go())
98 Return a list of strings, one for each entry in the history, prefixed
99 with enough spaces to align all the interpreter dots.
101 This method is called internally by the ``__str__()`` method.
107 for stack, expression in self.history:
108 stack = stack_to_string(stack)
109 expression = expression_to_string(expression)
111 if n > max_stack_length:
113 lines.append((n, '%s • %s' % (stack, expression)))
114 for i in range(len(lines)): # Prefix spaces to line up '•'s.
115 length, line = lines[i]
116 lines[i] = (' ' * (max_stack_length - length) + line)
124 print('Exception while printing viewer.')