-
Notifications
You must be signed in to change notification settings - Fork 45
/
renderer.py
415 lines (365 loc) · 15.3 KB
/
renderer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
# Copyright 2024 The Penzai Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Renderer objects and handler definitions."""
from __future__ import annotations
import contextlib
import dataclasses
import functools
import traceback
import typing
from typing import Any, Callable, Iterable
import warnings
from penzai.treescope.foldable_representation import basic_parts
from penzai.treescope.foldable_representation import common_styles
from penzai.treescope.foldable_representation import foldable_impl
from penzai.treescope.foldable_representation import layout_algorithms
from penzai.treescope.foldable_representation import part_interface
class TreescopeSubtreeRenderer(typing.Protocol):
"""Protocol for a (recursive) subtree renderer.
Implementations of this protocol render full subtrees to HTML tags. Handlers
take one of these as an argument and use it to render their children.
"""
def __call__(
self,
node: Any,
path: tuple[Any, ...] | None = None,
) -> part_interface.RenderableAndLineAnnotations:
"""Signature for a (recursive) subtree renderer.
Args:
node: The node to render.
path: Optionally, a path to this node. Handlers should pass the JAX
keypath to each of their pytree node children. They can also pass
keypaths to non-pytree-node children if desired.
Returns:
A representation of the object as a renderable tree part in the
intermediate representation.
"""
...
class TreescopeNodeHandler(typing.Protocol):
"""Protocol for a rendering handler for a particular node type.
Rendering handlers run in order (from most specific to least specific),
until one of them is able to handle the given node. Handlers should return
NotImplemented for types of node that they are unable to handle.
"""
def __call__(
self,
node: Any,
path: tuple[Any, ...] | None,
subtree_renderer: TreescopeSubtreeRenderer,
) -> (
part_interface.RenderableTreePart
| part_interface.RenderableAndLineAnnotations
| type(NotImplemented)
):
"""Signature for a rendering handler for a particular node type.
Args:
node: The node to render.
path: Optionally, a path to this node. This will be the JAX keypath to the
node if the node is part of a JAX PyTree. It may also be provided for
nodes outside of the PyTree, in a format similar to that used by JAX
keypaths. Handlers are encouraged to use this to build their rendering,
and to pass an extended version when rendering their children using
``subtree_renderer``.
subtree_renderer: A recursive renderer for subtrees of this node. This
should be used to render the children of this node into HTML tags to
include in the rendering of this node. Should only be called on nodes
that are children of `node`, to avoid an infinite loop.
Returns:
A representation of the object as a tree part, or NotImplemented
if this handler doesn't support rendering this object (indicating that
we should try the next handler). Tree parts may have optional end-of-line
annotations.
"""
class TreescopeCustomWrapperHook(typing.Protocol):
"""Protocol for a custom wrapper hook.
Custom wrapper hooks are more powerful versions of node handlers. They run
on every node, and are given control over how that node is rendered. In
particular, they can modify the arguments that are passed to subsequent
wrappers and ordinary handlers by calling ``node_renderer`` with modified
values, and can also insert additional HTML tags around the rendered result.
Generally, custom wrapper hooks should call ``node_renderer`` exactly once
with the same ``node`` argument and the same ``path``.
"""
def __call__(
self,
node: Any,
path: tuple[Any, ...] | None,
node_renderer: TreescopeSubtreeRenderer,
) -> (
part_interface.RenderableTreePart
| part_interface.RenderableAndLineAnnotations
| type(NotImplemented)
):
"""Signature for a custom wrapper hook.
Args:
node: The node that we are rendering.
path: Optionally, a path to this node as a string; see
`TreescopeNodeHandler`.
node_renderer: The inner renderer for this node. This can be used to
render `node` itself according to the ordinary logic. Usually the
wrapper hook should call `node_renderer` once with `node`, possibly
customizing its arguments, and then postprocess the return value.
Returns:
A modified rendering of the object, or NotImplemented if this
hook does not want to modify this rendering at all. (Returning
NotImplemented)
"""
...
@dataclasses.dataclass
class TreescopeRenderer:
"""A renderer object with a configurable set of handlers.
Attributes:
handlers: List of handlers, ordered from most specific to least specific.
Handlers will be tried in order until one returns something other than
NotImplemented.
wrapper_hooks: List of wrapper hooks, ordered from outermost to innermost.
All wrapper hooks will run in order on every node.
context_builders: List of functions that build rendering context managers.
Each of these context managers will be entered before rendering the tree,
and will be exited after converting the returned tags to an HTML string.
The main use for this is to set up shared state needed by the handlers or
wrapper hooks (e.g. using a `penzai.ContextualValue`). Context builders
can also return None instead of a context manager, if they just need to do
processing at the start of rendering and don't need to clean up.
"""
handlers: list[TreescopeNodeHandler]
wrapper_hooks: list[TreescopeCustomWrapperHook]
context_builders: list[
Callable[[], contextlib.AbstractContextManager[Any] | None]
]
def extended_with(
self,
*,
handlers: Iterable[TreescopeNodeHandler] = (),
wrapper_hooks: Iterable[TreescopeCustomWrapperHook] = (),
context_builders: Iterable[
Callable[[], contextlib.AbstractContextManager[Any] | None]
] = (),
) -> TreescopeRenderer:
"""Extends a renderer with additional steps, returning a new renderer.
Args:
handlers: New handlers to insert. These will be inserted at the beginning
of the handler list, to allow them to override existing handlers.
wrapper_hooks: New wrapper hooks. These will be inserted before the
existing wrapper hooks, to allow them to override existing hooks.
context_builders: New context builders. These will be inserted after the
existing context builders.
Returns:
A copy of this renderer extended with the new parts.
"""
return TreescopeRenderer(
handlers=list(handlers) + self.handlers,
wrapper_hooks=list(wrapper_hooks) + self.wrapper_hooks,
context_builders=self.context_builders + list(context_builders),
)
def _render_subtree(
self,
ignore_exceptions: bool,
rendering_stack: list[Any],
already_executed_wrapper_count: int,
node: Any,
path: tuple[Any, ...] | None = None,
) -> part_interface.RenderableAndLineAnnotations:
"""Renders a specific subtree using the renderer.
Args:
ignore_exceptions: Whether to catch and ignore errors in handlers or
postprocessors.
rendering_stack: A list of the ancestors of this node, used to check for
and break cyclic references.
already_executed_wrapper_count: The number of wrappers we have already
called for this node.
node: See `TreescopeSubtreeRenderer.__call__`.
path: See `TreescopeSubtreeRenderer.__call__`.
Returns:
A renderable representation of the object.
"""
while already_executed_wrapper_count < len(self.wrapper_hooks):
# We have hooks we haven't processed. Defer to the hook.
# We pass a reference to this method back to the wrapper to allow it to
# resume execution at the next wrapper.
hook = self.wrapper_hooks[already_executed_wrapper_count]
render_without_this_hook = functools.partial(
self._render_subtree,
ignore_exceptions,
rendering_stack,
already_executed_wrapper_count + 1,
)
try:
postprocessed_result = hook(
node=node, path=path, node_renderer=render_without_this_hook
)
if postprocessed_result is NotImplemented:
# Skip this hook and defer to the next one (or to a handler)
already_executed_wrapper_count += 1
continue
elif isinstance(
postprocessed_result, part_interface.RenderableAndLineAnnotations
):
return postprocessed_result
elif isinstance(
postprocessed_result, part_interface.RenderableTreePart
):
return part_interface.RenderableAndLineAnnotations(
renderable=postprocessed_result
)
else:
raise ValueError(
f"Wrapper hook {hook} returned a value of an unexpected type:"
f" {postprocessed_result}"
)
except Exception: # pylint: disable=broad-exception-caught
if ignore_exceptions:
warnings.warn(
f"Ignoring error inside wrapper hook {hook}"
f":\n{traceback.format_exc(limit=10)}"
)
already_executed_wrapper_count += 1
continue
else:
raise
# If we get here, all of the wrappers have already processed this object.
# Use object identity to track cyclic objects.
node_id = id(node)
if node_id in rendering_stack:
# Cycle! This object contains itself.
return part_interface.RenderableAndLineAnnotations(
renderable=common_styles.ErrorColor(
basic_parts.Text(
f"<cyclic reference to {type(node).__name__} at"
f" 0x{node_id:x}>"
)
)
)
else:
# Track cyclic references. We use `try: ... finally: ...` to ensure we
# clean up after ourselves even if we return a value early. (There's also
# separate internal try/catch logic for error handling.)
rendering_stack.append(node_id)
try:
# Give each of our handlers a chance to render this node.
# We pass this method as the renderer for any children of the node, and
# reenable all of the wrapper hooks.
rec = functools.partial(
self._render_subtree, ignore_exceptions, rendering_stack, 0
)
for handler in self.handlers:
try:
maybe_result = handler(node=node, path=path, subtree_renderer=rec)
if maybe_result is NotImplemented:
# Try the next handler.
continue
elif isinstance(
maybe_result, part_interface.RenderableAndLineAnnotations
):
# Found a result!
return maybe_result
elif isinstance(maybe_result, part_interface.RenderableTreePart):
# Wrap it with empty annotations.
return part_interface.RenderableAndLineAnnotations(
renderable=maybe_result
)
else:
raise ValueError(
f"Handler {handler} returned a value of an unexpected type:"
f" {maybe_result}"
)
except Exception: # pylint: disable=broad-exception-caught
if ignore_exceptions:
warnings.warn(
"Ignoring error while formatting value of type"
f" {type(node)} with"
f" {handler}:\n{traceback.format_exc(limit=10)}"
)
continue
else:
raise
# If we get here, it means no handler was found.
if ignore_exceptions:
warnings.warn(
f"No handler registered for a node of type {type(node)}."
)
# Fall back to a basic `repr` so that we still render something even
# without a handler for it.
return part_interface.RenderableAndLineAnnotations(
renderable=common_styles.AbbreviationColor(
basic_parts.Text(repr(node))
)
)
else:
raise ValueError(
f"No handler registered for a node of type {type(node)}."
)
finally:
# Remove it from the rendering stack.
popped_val = rendering_stack.pop()
assert popped_val == node_id
def to_foldable_representation(
self,
value: Any,
ignore_exceptions: bool = False,
root_keypath: tuple[Any, ...] | None = (),
) -> part_interface.RenderableAndLineAnnotations:
"""Renders an object to the foldable intermediate representation.
Args:
value: Value to render.
ignore_exceptions: Whether to catch errors during rendering of subtrees
and show a fallback for those subtrees, instead of failing the entire
renderer. Best used in contexts where `to_foldable_representation` is
not being called directly by the user, e.g. when registering this as a
default pretty-printer.
root_keypath: Keypath to the value being rendered. Can be None to disable
all keypaths during rendering.
Returns:
Renderable representation of the object.
"""
with contextlib.ExitStack() as stack:
# Set up any scoped state contexts that handlers need.
for context_builder in self.context_builders:
new_context = context_builder()
if new_context is not None:
stack.enter_context(new_context)
# Build the foldable HTML tag recursively.
return self._render_subtree(
ignore_exceptions=ignore_exceptions,
rendering_stack=[],
already_executed_wrapper_count=0,
node=value,
path=root_keypath,
)
def to_text(self, value: Any, roundtrip_mode: bool = False) -> str:
"""Convenience method to render an object to text.
Args:
value: Value to render.
roundtrip_mode: Whether to render in roundtrip mode.
Returns:
A text representation of the object.
"""
foldable_ir = basic_parts.build_full_line_with_annotations(
self.to_foldable_representation(value)
)
layout_algorithms.expand_for_balanced_layout(foldable_ir)
return foldable_impl.render_to_text_as_root(foldable_ir, roundtrip_mode)
def to_html(self, value: Any, roundtrip_mode: bool = False) -> str:
"""Convenience method to render an object to HTML.
Args:
value: Value to render.
roundtrip_mode: Whether to render in roundtrip mode.
Returns:
HTML source code for the foldable representation of the object.
"""
foldable_ir = basic_parts.build_full_line_with_annotations(
self.to_foldable_representation(value)
)
layout_algorithms.expand_for_balanced_layout(foldable_ir)
return foldable_impl.render_to_html_as_root(foldable_ir, roundtrip_mode)