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 __future__ import print_function
42 from builtins import object
43 from traceback import print_exc
44 from .stack import expression_to_string, stack_to_string
46 from ..library import inscribe, FunctionWrapper
51 def trace(stack, expression, dictionary):
52 '''Evaluate a Joy expression on a stack and print a trace.
54 This function is just like the `i` combinator but it also prints a
55 trace of the evaluation
57 :param stack stack: The stack.
58 :param stack expression: The expression to evaluate.
59 :param dict dictionary: A ``dict`` mapping names to Joy functions.
60 :rtype: (stack, (), dictionary)
66 s, _, d = joy(stack, quote, dictionary, tp.viewer)
73 return s, expression, d
76 class TracePrinter(object):
78 This is what does the formatting. You instantiate it and pass the ``viewer()``
79 method to the :py:func:`joy.joy.joy` function, then print it to see the
86 def viewer(self, stack, expression):
88 Record the current stack and expression in the TracePrinter's history.
89 Pass this method as the ``viewer`` argument to the :py:func:`joy.joy.joy` function.
91 :param stack quote: A stack.
92 :param stack expression: A stack.
94 self.history.append((stack, expression))
97 return '\n'.join(self.go())
101 Return a list of strings, one for each entry in the history, prefixed
102 with enough spaces to align all the interpreter dots.
104 This method is called internally by the ``__str__()`` method.
110 for stack, expression in self.history:
111 stack = stack_to_string(stack)
112 expression = expression_to_string(expression)
114 if n > max_stack_length:
116 lines.append((n, '%s • %s' % (stack, expression)))
117 return [ # Prefix spaces to line up '•'s.
118 (' ' * (max_stack_length - length) + line)
119 for length, line in lines
127 print('Exception while printing viewer.')