Merge pull request #1109 from pallets/visit-output-refactor
Before adoption: this commit came in with the history the project adopted, so no landing records it.
refactor visit_Output
authored by David Lord · committed by GitHub · parents 5d33f67, 3487c8e · Browse files · 5 files·+181 added−290 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+181 added−290 removed
- tests:+21 added−22 removed
- other:+160 added−268 removed
Provenance
- Commit
6c1a62f- Tree
27ef51b- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
5d33f67- Parent 2
3487c8e
5 files changed+181 added−290 removed
modified:jinja2/compiler.py+138 added-114 removed
6 unmodified lines7 8 :copyright: (c) 2017 by the Jinja Team.9 :license: BSD, see LICENSE for more details.10 """11+from collections import namedtuple12 from itertools import chain12-from copy import deepcopy13 from keyword import iskeyword as is_python_keyword14 from functools import update_wrapper15 from jinja2 import nodes16 from jinja2.nodes import EvalContext1203 unmodified lines1220 def visit_ExprStmt(self, node, frame):1221 self.newline(node)1222 self.visit(node.node, frame)1223 1224- def visit_Output(self, node, frame):1225- # if we have a known extends statement, we don't output anything1226- # if we are in a require_output_check section1227- if self.has_known_extends and frame.require_output_check:1228- return1224+ _FinalizeInfo = namedtuple("_FinalizeInfo", ("const", "src"))1225+ #: The default finalize function if the environment isn't configured1226+ #: with one. Or if the environment has one, this is called on that1227+ #: function's output for constants.1228+ _default_finalize = text_type1229+ _finalize = None1230 1230- finalize = text_type1231- finalize_src = None1232- allow_constant_finalize = True1231+ def _make_finalize(self):1232+ """Build the finalize function to be used on constants and at1233+ runtime. Cached so it's only created once for all output nodes.1234 1235+ Returns a ``namedtuple`` with the following attributes:1236+1237+ ``const``1238+ A function to finalize constant data at compile time.1239+1240+ ``src``1241+ Source code to output around nodes to be evaluated at1242+ runtime.1243+ """1244+ if self._finalize is not None:1245+ return self._finalize1246+1247+ finalize = default = self._default_finalize1248+ src = None1249+1250 if self.environment.finalize:1251+ src = "environment.finalize("1252 env_finalize = self.environment.finalize1236- finalize_src = "environment.finalize("1253 1254 def finalize(value):1239- return text_type(env_finalize(value))1255+ return default(env_finalize(value))1256 1257 if getattr(env_finalize, "contextfunction", False):1242- finalize_src += "context, "1243- allow_constant_finalize = False1258+ src += "context, "1259+ finalize = None1260 elif getattr(env_finalize, "evalcontextfunction", False):1245- finalize_src += "context.eval_ctx, "1246- allow_constant_finalize = False1261+ src += "context.eval_ctx, "1262+ finalize = None1263 elif getattr(env_finalize, "environmentfunction", False):1248- finalize_src += "environment, "1264+ src += "environment, "1265 1266 def finalize(value):1251- return text_type(env_finalize(self.environment, value))1267+ return default(env_finalize(self.environment, value))1268 1253- # if we are inside a frame that requires output checking, we do so1254- outdent_later = False1269+ self._finalize = self._FinalizeInfo(finalize, src)1270+ return self._finalize1271+1272+ def _output_const_repr(self, group):1273+ """Given a group of constant values converted from ``Output``1274+ child nodes, produce a string to write to the template module1275+ source.1276+ """1277+ return repr(concat(group))1278+1279+ def _output_child_to_const(self, node, frame, finalize):1280+ """Try to optimize a child of an ``Output`` node by trying to1281+ convert it to constant, finalized data at compile time.1282+1283+ If :exc:`Impossible` is raised, the node is not constant and1284+ will be evaluated at runtime. Any other exception will also be1285+ evaluated at runtime for easier debugging.1286+ """1287+ const = node.as_const(frame.eval_ctx)1288+1289+ if frame.eval_ctx.autoescape:1290+ const = escape(const)1291+1292+ # Template data doesn't go through finalize.1293+ if isinstance(node, nodes.TemplateData):1294+ return text_type(const)1295+1296+ return finalize.const(const)1297+1298+ def _output_child_pre(self, node, frame, finalize):1299+ """Output extra source code before visiting a child of an1300+ ``Output`` node.1301+ """1302+ if frame.eval_ctx.volatile:1303+ self.write("(escape if context.eval_ctx.autoescape else to_string)(")1304+ elif frame.eval_ctx.autoescape:1305+ self.write("escape(")1306+ else:1307+ self.write("to_string(")1308+1309+ if finalize.src is not None:1310+ self.write(finalize.src)1311+1312+ def _output_child_post(self, node, frame, finalize):1313+ """Output extra source code after visiting a child of an1314+ ``Output`` node.1315+ """1316+ self.write(")")1317+1318+ if finalize.src is not None:1319+ self.write(")")1320+1321+ def visit_Output(self, node, frame):1322+ # If an extends is active, don't render outside a block.1323 if frame.require_output_check:1256- self.writeline('if parent_template is None:')1324+ # A top-level extends is known to exist at compile time.1325+ if self.has_known_extends:1326+ return1327+1328+ self.writeline("if parent_template is None:")1329 self.indent()1258- outdent_later = True1330 1260- # try to evaluate as many chunks as possible into a static1261- # string at compile time.1331+ finalize = self._make_finalize()1332 body = []1333+1334+ # Evaluate constants at compile time if possible. Each item in1335+ # body will be either a list of static data or a node to be1336+ # evaluated at runtime.1337 for child in node.nodes:1338 try:1265- # If the finalize function needs context, and this isn't1266- # template data, evaluate the node at render.1339 if not (1268- allow_constant_finalize1340+ # If the finalize function requires runtime context,1341+ # constants can't be evaluated at compile time.1342+ finalize.const1343+ # Unless it's basic template data that won't be1344+ # finalized anyway.1345 or isinstance(child, nodes.TemplateData)1346 ):1347 raise nodes.Impossible()1348 1273- const = child.as_const(frame.eval_ctx)1274- except nodes.Impossible:1349+ const = self._output_child_to_const(child, frame, finalize)1350+ except (nodes.Impossible, Exception):1351+ # The node was not constant and needs to be evaluated at1352+ # runtime. Or another error was raised, which is easier1353+ # to debug at runtime.1354 body.append(child)1355 continue1356 1278- # the frame can't be volatile here, becaus otherwise the1279- # as_const() function would raise an Impossible exception1280- # at that point.1281- try:1282- if frame.eval_ctx.autoescape:1283- const = escape(const)1284-1285- # Only call finalize on expressions, not template data.1286- if isinstance(child, nodes.TemplateData):1287- const = text_type(const)1288- else:1289- const = finalize(const)1290- except Exception:1291- # if something goes wrong here we evaluate the node1292- # at runtime for easier debugging1293- body.append(child)1294- continue1295-1357 if body and isinstance(body[-1], list):1358 body[-1].append(const)1359 else:1360 body.append([const])1361 1301- # if we have less than 3 nodes or a buffer we yield or extend/append1302- if len(body) < 3 or frame.buffer is not None:1303- if frame.buffer is not None:1304- # for one item we append, for more we extend1305- if len(body) == 1:1306- self.writeline('%s.append(' % frame.buffer)1362+ if frame.buffer is not None:1363+ if len(body) == 1:1364+ self.writeline("%s.append(" % frame.buffer)1365+ else:1366+ self.writeline("%s.extend((" % frame.buffer)1367+1368+ self.indent()1369+1370+ for item in body:1371+ if isinstance(item, list):1372+ # A group of constant data to join and output.1373+ val = self._output_const_repr(item)1374+1375+ if frame.buffer is None:1376+ self.writeline("yield " + val)1377 else:1308- self.writeline('%s.extend((' % frame.buffer)1309- self.indent()1310- for item in body:1311- if isinstance(item, list):1312- val = repr(concat(item))1313- if frame.buffer is None:1314- self.writeline('yield ' + val)1315- else:1316- self.writeline(val + ',')1378+ self.writeline(val + ",")1379+ else:1380+ if frame.buffer is None:1381+ self.writeline("yield ", item)1382 else:1318- if frame.buffer is None:1319- self.writeline('yield ', item)1320- else:1321- self.newline(item)1383+ self.newline(item)1322- close = 11323- if frame.eval_ctx.volatile:1324- self.write('(escape if context.eval_ctx.autoescape'1325- ' else to_string)(')1326- elif frame.eval_ctx.autoescape:1327- self.write('escape(')1328- else:1329- self.write('to_string(')1330- if self.environment.finalize is not None:1331- self.write(finalize_src)1332- close += 11333- self.visit(item, frame)1334- self.write(')' * close)1335- if frame.buffer is not None:1336- self.write(',')1337- if frame.buffer is not None:1338- # close the open parentheses1339- self.outdent()1340- self.writeline(len(body) == 1 and ')' or '))')1384 1342- # otherwise we create a format string as this is faster in that case1343- else:1344- format = []1345- arguments = []1346- for item in body:1347- if isinstance(item, list):1348- format.append(concat(item).replace('%', '%%'))1349- else:1350- format.append('%s')1351- arguments.append(item)1352- self.writeline('yield ')1353- self.write(repr(concat(format)) + ' % (')1354- self.indent()1355- for argument in arguments:1356- self.newline(argument)1357- close = 01358- if frame.eval_ctx.volatile:1359- self.write('(escape if context.eval_ctx.autoescape else'1360- ' to_string)(')1361- close += 11362- elif frame.eval_ctx.autoescape:1363- self.write('escape(')1364- close += 11365- if self.environment.finalize is not None:1366- self.write(finalize_src)1367- close += 11368- self.visit(argument, frame)1369- self.write(')' * close + ', ')1385+ # A node to be evaluated at runtime.1386+ self._output_child_pre(item, frame, finalize)1387+ self.visit(item, frame)1388+ self._output_child_post(item, frame, finalize)1389+1390+ if frame.buffer is not None:1391+ self.write(",")1392+1393+ if frame.buffer is not None:1394 self.outdent()1371- self.writeline(')')1395+ self.writeline(")" if len(body) == 1 else "))")1396 1373- if outdent_later:1397+ if frame.require_output_check:1398 self.outdent()1399 1400 def visit_Assign(self, node, frame):1401 self.push_assign_tracking()368 unmodified linesmodified:jinja2/nativetypes.py+21 added-153 removed
4 unmodified lines5 from jinja2 import nodes6 from jinja2._compat import text_type7 from jinja2.compiler import CodeGenerator, has_safe_repr8 from jinja2.environment import Environment, Template9-from jinja2.utils import concat, escape9 10 11 def native_concat(nodes, preserve_quotes=True):12 """Return a native Python type from the list of compiled nodes. If34 unmodified lines47 return literal48 49 50 class NativeCodeGenerator(CodeGenerator):52- """A code generator which avoids injecting ``to_string()`` calls around the53- internal code Jinja uses to render templates.51+ """A code generator which renders Python types by not adding52+ ``to_string()`` around output nodes, and using :func:`native_concat`53+ to convert complex strings back to Python types if possible.54 """55 56- def visit_Output(self, node, frame):57- """Same as :meth:`CodeGenerator.visit_Output`, but do not call58- ``to_string`` on output nodes in generated code.59- """60- if self.has_known_extends and frame.require_output_check:61- return56+ @staticmethod57+ def _default_finalize(value):58+ return value59 63- finalize = self.environment.finalize64- finalize_context = getattr(finalize, 'contextfunction', False)65- finalize_eval = getattr(finalize, 'evalcontextfunction', False)66- finalize_env = getattr(finalize, 'environmentfunction', False)60+ def _output_const_repr(self, group):61+ return repr(native_concat(group))62 68- if finalize is not None:69- if finalize_context or finalize_eval:70- const_finalize = None71- elif finalize_env:72- def const_finalize(x):73- return finalize(self.environment, x)74- else:75- const_finalize = finalize76- else:77- def const_finalize(x):78- return x63+ def _output_child_to_const(self, node, frame, finalize):64+ const = node.as_const(frame.eval_ctx)65 80- # If we are inside a frame that requires output checking, we do so.81- outdent_later = False66+ if not has_safe_repr(const):67+ raise nodes.Impossible()68 83- if frame.require_output_check:84- self.writeline('if parent_template is None:')85- self.indent()86- outdent_later = True69+ if isinstance(node, nodes.TemplateData):70+ return const71 88- # Try to evaluate as many chunks as possible into a static string at89- # compile time.90- body = []72+ return finalize.const(const)73 92- for child in node.nodes:93- try:94- if const_finalize is None:95- raise nodes.Impossible()74+ def _output_child_pre(self, node, frame, finalize):75+ if finalize.src is not None:76+ self.write(finalize.src)77 97- const = child.as_const(frame.eval_ctx)98- if not has_safe_repr(const):99- raise nodes.Impossible()100- except nodes.Impossible:101- body.append(child)102- continue78+ def _output_child_post(self, node, frame, finalize):79+ if finalize.src is not None:80+ self.write(")")81 104- # the frame can't be volatile here, because otherwise the as_const105- # function would raise an Impossible exception at that point106- try:107- if frame.eval_ctx.autoescape:108- if hasattr(const, '__html__'):109- const = const.__html__()110- else:111- const = escape(const)82 113- const = const_finalize(const)114- except Exception:115- # if something goes wrong here we evaluate the node at runtime116- # for easier debugging117- body.append(child)118- continue119-120- if body and isinstance(body[-1], list):121- body[-1].append(const)122- else:123- body.append([const])124-125- # if we have less than 3 nodes or a buffer we yield or extend/append126- if len(body) < 3 or frame.buffer is not None:127- if frame.buffer is not None:128- # for one item we append, for more we extend129- if len(body) == 1:130- self.writeline('%s.append(' % frame.buffer)131- else:132- self.writeline('%s.extend((' % frame.buffer)133-134- self.indent()135-136- for item in body:137- if isinstance(item, list):138- val = repr(native_concat(item))139-140- if frame.buffer is None:141- self.writeline('yield ' + val)142- else:143- self.writeline(val + ',')144- else:145- if frame.buffer is None:146- self.writeline('yield ', item)147- else:148- self.newline(item)149-150- close = 0151-152- if finalize is not None:153- self.write('environment.finalize(')154-155- if finalize_context:156- self.write('context, ')157-158- close += 1159-160- self.visit(item, frame)161-162- if close > 0:163- self.write(')' * close)164-165- if frame.buffer is not None:166- self.write(',')167-168- if frame.buffer is not None:169- # close the open parentheses170- self.outdent()171- self.writeline(len(body) == 1 and ')' or '))')172-173- # otherwise we create a format string as this is faster in that case174- else:175- format = []176- arguments = []177-178- for item in body:179- if isinstance(item, list):180- format.append(native_concat(item).replace('%', '%%'))181- else:182- format.append('%s')183- arguments.append(item)184-185- self.writeline('yield ')186- self.write(repr(concat(format)) + ' % (')187- self.indent()188-189- for argument in arguments:190- self.newline(argument)191- close = 0192-193- if finalize is not None:194- self.write('environment.finalize(')195-196- if finalize_context:197- self.write('context, ')198- elif finalize_eval:199- self.write('context.eval_ctx, ')200- elif finalize_env:201- self.write('environment, ')202-203- close += 1204-205- self.visit(argument, frame)206- self.write(')' * close + ', ')207-208- self.outdent()209- self.writeline(')')210-211- if outdent_later:212- self.outdent()213-214-83 class NativeEnvironment(Environment):84 """An environment that renders templates to native Python types."""85 86 code_generator_class = NativeCodeGenerator24 unmodified linesmodified:jinja2/runtime.py+1 added-1 removed
503 unmodified lines504 505 def __iter__(self):506 return self507 508- @internalcode508 def __next__(self):509 if self._after is not missing:510 rv = self._after511 self._after = missing4 unmodified lines516 self._before = self._current517 self._current = rv518 return rv, self519 520+ @internalcode521 def __call__(self, iterable):522 """When iterating over nested data, render the body of the loop523 recursively with the given inner iterable data.524 375 unmodified linesmodified:tests/test_api.py+15 added-15 removed
9 unmodified lines10 """11 import os12 import tempfile13 import shutil14+from io import StringIO15 16 import pytest17 from jinja2 import Environment, Undefined, ChainableUndefined, \18 DebugUndefined, StrictUndefined, UndefinedError, meta, \187 unmodified lines206 207 @pytest.mark.api208 @pytest.mark.streaming209 class TestStreaming(object):209-210 def test_basic_streaming(self, env):211- tmpl = env.from_string("<ul>{% for item in seq %}<li>{{ loop.index "212- "}} - {{ item }}</li>{%- endfor %}</ul>")213- stream = tmpl.stream(seq=list(range(4)))214- assert next(stream) == '<ul>'215- assert next(stream) == '<li>1 - 0</li>'216- assert next(stream) == '<li>2 - 1</li>'217- assert next(stream) == '<li>3 - 2</li>'218- assert next(stream) == '<li>4 - 3</li>'219- assert next(stream) == '</ul>'211+ t = env.from_string(212+ "<ul>{% for item in seq %}<li>{{ loop.index }} - {{ item }}</li>"213+ "{%- endfor %}</ul>"214+ )215+ stream = t.stream(seq=list(range(3)))216+ assert next(stream) == "<ul>"217+ assert "".join(stream) == "<li>1 - 0</li><li>2 - 1</li><li>3 - 2</li></ul>"218 219 def test_buffered_streaming(self, env):222- tmpl = env.from_string("<ul>{% for item in seq %}<li>{{ loop.index "223- "}} - {{ item }}</li>{%- endfor %}</ul>")224- stream = tmpl.stream(seq=list(range(4)))220+ tmpl = env.from_string(221+ "<ul>{% for item in seq %}<li>{{ loop.index }} - {{ item }}</li>"222+ "{%- endfor %}</ul>"223+ )224+ stream = tmpl.stream(seq=list(range(3)))225 stream.enable_buffering(size=3)226- assert next(stream) == u'<ul><li>1 - 0</li><li>2 - 1</li>'227- assert next(stream) == u'<li>3 - 2</li><li>4 - 3</li></ul>'226+ assert next(stream) == u'<ul><li>1'227+ assert next(stream) == u' - 0</li>'228 229 def test_streaming_behavior(self, env):230 tmpl = env.from_string("")231 stream = tmpl.stream()184 unmodified linesmodified:tests/test_async.py+6 added-7 removed
100 unmodified lines101 assert rv == ['1', '2', '3']102 103 104 def test_async_iteration_in_templates_extended():105- t = Template('{% for x in rng %}{{ loop.index0 }}/{{ x }}{% endfor %}',106- enable_async=True)107- async def async_iterator():108- for item in [1, 2, 3]:109- yield item110- rv = list(t.generate(rng=async_iterator()))111- assert rv == ['0/1', '1/2', '2/3']105+ t = Template(106+ "{% for x in rng %}{{ loop.index0 }}/{{ x }}{% endfor %}", enable_async=True107+ )108+ stream = t.generate(rng=auto_aiter(range(1, 4)))109+ assert next(stream) == "0"110+ assert "".join(stream) == "/11/22/3"111 112 113 @pytest.fixture114 def test_env_async():387 unmodified lines