Skip to content
Myr

Add support for explicit callers

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

This adds support for a never intended Jinja2 feature which however worked in limited support before due to a bug with the identifier scoping. A quick github code search indicates that developers commonly did this to set the default caller to none. This fixes #642

authored by Armin Ronacher · committed by Armin Ronacher · parent e302252 · Browse files · 4 files+68 added−7 removed
This commit

State

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

Diff stats

4 files+68 added−7 removed

  • tests:+21 added−1 removed
  • other:+47 added−6 removed

4 files+68 added−7 removed

modified:jinja2/compiler.py+25 added-4 removed
501 unmodified lines
502 frame = frame.inner()503 frame.symbols.analyze_node(node)504 macro_ref = MacroRef(node)505506 explicit_caller = None507 skip_special_params = set()508 args = []507 for arg in node.args:509 for idx, arg in enumerate(node.args):510 if arg.name == 'caller':511 explicit_caller = idx512 if arg.name in ('kwargs', 'varargs'):513 skip_special_params.add(arg.name)514 args.append(frame.symbols.ref(arg.name))515516 undeclared = find_undeclared(node.body, ('caller', 'kwargs', 'varargs'))517518 if 'caller' in undeclared:519 # In older Jinja2 versions there was a bug that allowed caller520 # to retain the special behavior even if it was mentioned in521 # the argument list. However thankfully this was only really522 # working if it was the last argument. So we are explicitly523 # checking this now and error out if it is anywhere else in524 # the argument list.525 if explicit_caller is not None:526 try:527 node.defaults[explicit_caller - len(node.args)]528 except IndexError:529 self.fail('When defining macros or call blocks the '530 'special "caller" argument must be omitted '531 'or be given a default.', node.lineno)532 else:512 args.append(frame.symbols.declare_parameter('caller'))533 args.append(frame.symbols.declare_parameter('caller'))534 macro_ref.accesses_caller = True514 if 'kwargs' in undeclared:535 if 'kwargs' in undeclared and not 'kwargs' in skip_special_params:536 args.append(frame.symbols.declare_parameter('kwargs'))537 macro_ref.accesses_kwargs = True517 if 'varargs' in undeclared:538 if 'varargs' in undeclared and not 'varargs' in skip_special_params:539 args.append(frame.symbols.declare_parameter('varargs'))540 macro_ref.accesses_varargs = True541542 # macros are delayed, they never require output checks
1098 unmodified lines
modified:jinja2/runtime.py+15 added-1 removed
413 unmodified lines
414 self.arguments = arguments415 self.catch_kwargs = catch_kwargs416 self.catch_varargs = catch_varargs417 self.caller = caller418 self.explicit_caller = 'caller' in arguments419 if default_autoescape is None:420 default_autoescape = environment.autoescape421 self._default_autoescape = default_autoescape422
26 unmodified lines
449 # try to consume the positional arguments450 arguments = list(args[:self._argument_count])451 off = len(arguments)452453 # For information why this is necessary refer to the handling454 # of caller in the `macro_body` handler in the compiler.455 found_caller = False456457 # if the number of arguments consumed is not the number of458 # arguments expected we start filling in keyword arguments459 # and defaults.460 if off != self._argument_count:
1 unmodified line
462 try:463 value = kwargs.pop(name)464 except KeyError:465 value = missing466 if name == 'caller':467 found_caller = True468 arguments.append(value)469 else:470 found_caller = self.explicit_caller471472 # it's important that the order of these arguments does not change473 # if not also changed in the compiler's `function_scoping` method.474 # the order is caller, keyword arguments, positional arguments!466 if self.caller:475 if self.caller and not found_caller:476 caller = kwargs.pop('caller', None)477 if caller is None:478 caller = self._environment.undefined('No caller defined',479 name='caller')480 arguments.append(caller)481482 if self.catch_kwargs:483 arguments.append(kwargs)484 elif kwargs:485 if 'caller' in kwargs:486 raise TypeError('macro %r was invoked with two values for '487 'the special caller argument. This is '488 'most likely a bug.' % self.name)489 raise TypeError('macro %r takes no keyword argument %r' %490 (self.name, next(iter(kwargs))))491 if self.catch_varargs:492 arguments.append(args[self._argument_count:])
239 unmodified lines
modified:tests/test_regression.py+21 added-1 removed
10 unmodified lines
11import sys12import pytest1314from jinja2 import Template, Environment, DictLoader, TemplateSyntaxError, \15 TemplateNotFound, PrefixLoader15 TemplateAssertionError, TemplateNotFound, PrefixLoader16from jinja2._compat import text_type171819@pytest.mark.regression
401 unmodified lines
421 assert t.render(x={'y': [0, 1, 2]}) == '0|01|12|2'422423 t = env.from_string('{% for x in x.y recursive %}{{ x }}{% endfor %}')424 assert t.render(x={'y': [0, 1, 2]}) == '012'425426 def test_double_caller(self, env):427 t = env.from_string('{% macro x(caller=none) %}[{% if caller %}'428 '{{ caller() }}{% endif %}]{% endmacro %}'429 '{{ x() }}{% call x() %}aha!{% endcall %}')430 assert t.render() == '[][aha!]'431432 def test_double_caller_no_default(self, env):433 with pytest.raises(TemplateAssertionError) as exc_info:434 env.from_string('{% macro x(caller) %}[{% if caller %}'435 '{{ caller() }}{% endif %}]{% endmacro %}')436 assert exc_info.match(r'"caller" argument must be omitted or '437 r'be given a default')438439 t = env.from_string('{% macro x(caller=none) %}[{% if caller %}'440 '{{ caller() }}{% endif %}]{% endmacro %}')441 with pytest.raises(TypeError) as exc_info:442 t.module.x(None, caller=lambda: 42)443 assert exc_info.match(r'\'x\' was invoked with two values for the '444 r'special caller argument')
modified:CHANGES+7 added-1 removed
1Jinja2 Changelog2================34Version 2.9.14Version 2.9.25-------------6(bugfix release, release date undecided)78- Fixed a regression that caused for loops to not be able to use the same9 variable for the target as well as source iterator. (#640)10- Add support for a previously unknown behavior of macros. It used to be11 possible in some circumstances to explicitly provide a caller argument12 to macros. While badly buggy and unintended it turns out that this is a13 common case that gets copy pasted around. To not completely break backwards14 compatibility with the most common cases it's now possible to provide an15 explicit keyword argument for caller if it's given an explicit default.1617Version 2.9.118-------------19(bugfix release, released on January 7th 2017)
433 unmodified lines