Skip to content
Myr

refactor visit_Output

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* `finalize` is generated once and cached for all nodes. * Extract common behavior for native env. Removed the compiler behavior where groups of nodes would generate a format string. Instead, individual nodes are always yielded. This made rendering 30% faster in the examples, and simplifies the code. It also removes the issue where Python would report either the first or last line of the multi-line format expression, messing up the traceback line number mapping.

authored by David Lord · committed by David Lord · parent 5d33f67 · 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

5 files+181 added−290 removed

modified:jinja2/compiler.py+138 added-114 removed
6 unmodified lines
78 :copyright: (c) 2017 by the Jinja Team.9 :license: BSD, see LICENSE for more details.10"""11from collections import namedtuple12from itertools import chain12from copy import deepcopy13from keyword import iskeyword as is_python_keyword14from functools import update_wrapper15from jinja2 import nodes16from jinja2.nodes import EvalContext
1203 unmodified lines
1220 def visit_ExprStmt(self, node, frame):1221 self.newline(node)1222 self.visit(node.node, frame)12231224 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 = None12301230 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.12341235 Returns a ``namedtuple`` with the following attributes:12361237 ``const``1238 A function to finalize constant data at compile time.12391240 ``src``1241 Source code to output around nodes to be evaluated at1242 runtime.1243 """1244 if self._finalize is not None:1245 return self._finalize12461247 finalize = default = self._default_finalize1248 src = None12491250 if self.environment.finalize:1251 src = "environment.finalize("1252 env_finalize = self.environment.finalize1236 finalize_src = "environment.finalize("12531254 def finalize(value):1239 return text_type(env_finalize(value))1255 return default(env_finalize(value))12561257 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, "12651266 def finalize(value):1251 return text_type(env_finalize(self.environment, value))1267 return default(env_finalize(self.environment, value))12681253 # 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._finalize12711272 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))12781279 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.12821283 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)12881289 if frame.eval_ctx.autoescape:1290 const = escape(const)12911292 # Template data doesn't go through finalize.1293 if isinstance(node, nodes.TemplateData):1294 return text_type(const)12951296 return finalize.const(const)12971298 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(")13081309 if finalize.src is not None:1310 self.write(finalize.src)13111312 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(")")13171318 if finalize.src is not None:1319 self.write(")")13201321 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 return13271328 self.writeline("if parent_template is None:")1329 self.indent()1258 outdent_later = True13301260 # try to evaluate as many chunks as possible into a static1261 # string at compile time.1331 finalize = self._make_finalize()1332 body = []13331334 # 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()13481273 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 continue13561278 # 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)12841285 # 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 continue12951357 if body and isinstance(body[-1], list):1358 body[-1].append(const)1359 else:1360 body.append([const])13611301 # 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)13671368 self.indent()13691370 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)13741375 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 '))')13841342 # 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)13891390 if frame.buffer is not None:1391 self.write(",")13921393 if frame.buffer is not None:1394 self.outdent()1371 self.writeline(')')1395 self.writeline(")" if len(body) == 1 else "))")13961373 if outdent_later:1397 if frame.require_output_check:1398 self.outdent()13991400 def visit_Assign(self, node, frame):1401 self.push_assign_tracking()
368 unmodified lines
modified:jinja2/nativetypes.py+21 added-153 removed
4 unmodified lines
5from jinja2 import nodes6from jinja2._compat import text_type7from jinja2.compiler import CodeGenerator, has_safe_repr8from jinja2.environment import Environment, Template9from jinja2.utils import concat, escape91011def native_concat(nodes, preserve_quotes=True):12 """Return a native Python type from the list of compiled nodes. If
34 unmodified lines
47 return literal484950class 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 """5556 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 value5963 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))6268 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)6580 # 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()6883 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 const7188 # Try to evaluate as many chunks as possible into a static string at89 # compile time.90 body = []72 return finalize.const(const)7392 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)7797 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(")")81104 # 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)82113 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 continue119120 if body and isinstance(body[-1], list):121 body[-1].append(const)122 else:123 body.append([const])124125 # 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)133134 self.indent()135136 for item in body:137 if isinstance(item, list):138 val = repr(native_concat(item))139140 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)149150 close = 0151152 if finalize is not None:153 self.write('environment.finalize(')154155 if finalize_context:156 self.write('context, ')157158 close += 1159160 self.visit(item, frame)161162 if close > 0:163 self.write(')' * close)164165 if frame.buffer is not None:166 self.write(',')167168 if frame.buffer is not None:169 # close the open parentheses170 self.outdent()171 self.writeline(len(body) == 1 and ')' or '))')172173 # otherwise we create a format string as this is faster in that case174 else:175 format = []176 arguments = []177178 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)184185 self.writeline('yield ')186 self.write(repr(concat(format)) + ' % (')187 self.indent()188189 for argument in arguments:190 self.newline(argument)191 close = 0192193 if finalize is not None:194 self.write('environment.finalize(')195196 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, ')202203 close += 1204205 self.visit(argument, frame)206 self.write(')' * close + ', ')207208 self.outdent()209 self.writeline(')')210211 if outdent_later:212 self.outdent()21321483class NativeEnvironment(Environment):84 """An environment that renders templates to native Python types."""8586 code_generator_class = NativeCodeGenerator
24 unmodified lines
modified:jinja2/runtime.py+1 added-1 removed
503 unmodified lines
504505 def __iter__(self):506 return self507508 @internalcode508 def __next__(self):509 if self._after is not missing:510 rv = self._after511 self._after = missing
4 unmodified lines
516 self._before = self._current517 self._current = rv518 return rv, self519520 @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 lines
modified:tests/test_api.py+15 added-15 removed
9 unmodified lines
10"""11import os12import tempfile13import shutil14from io import StringIO1516import pytest17from jinja2 import Environment, Undefined, ChainableUndefined, \18 DebugUndefined, StrictUndefined, UndefinedError, meta, \
187 unmodified lines
206207@pytest.mark.api208@pytest.mark.streaming209class TestStreaming(object):209210 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>"218219 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>'228229 def test_streaming_behavior(self, env):230 tmpl = env.from_string("")231 stream = tmpl.stream()
184 unmodified lines
modified:tests/test_async.py+6 added-7 removed
100 unmodified lines
101 assert rv == ['1', '2', '3']102103104def 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"111112113@pytest.fixture114def test_env_async():
387 unmodified lines