Add support for namespaces in tuple parsing (#1664)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by GitHub · parents 1d55cdd, b8f4831 · Browse files · 5 files·+64 added−26 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+64 added−26 removed
- tests:+8 added−0 removed
- other:+56 added−26 removed
Provenance
- Commit
fbc3a69- Tree
7e160ca- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
1d55cdd- Parent 2
b8f4831
5 files changed+64 added−26 removed
modified:docs/templates.rst+3 added
1676 unmodified lines1677 Found item having something: {{ ns.found }}1678 1679 .. versionadded:: 2.101680 1681+ .. versionchanged:: 3.21682+ Namespace attributes can be assigned to in multiple assignment.1683 1684+1685 Extensions1686 ----------1687 1688 .. py:currentmodule:: jinja2277 unmodified linesmodified:src/jinja2/compiler.py+27 added-10 removed
1579 unmodified lines1580 self.outdent()1581 1582 def visit_Assign(self, node: nodes.Assign, frame: Frame) -> None:1583 self.push_assign_tracking()1584+1585+ # ``a.b`` is allowed for assignment, and is parsed as an NSRef. However,1586+ # it is only valid if it references a Namespace object. Emit a check for1587+ # that for each ref here, before assignment code is emitted. This can't1588+ # be done in visit_NSRef as the ref could be in the middle of a tuple.1589+ seen_refs: t.Set[str] = set()1590+1591+ for nsref in node.find_all(nodes.NSRef):1592+ if nsref.name in seen_refs:1593+ # Only emit the check for each reference once, in case the same1594+ # ref is used multiple times in a tuple, `ns.a, ns.b = c, d`.1595+ continue1596+1597+ seen_refs.add(nsref.name)1598+ ref = frame.symbols.ref(nsref.name)1599+ self.writeline(f"if not isinstance({ref}, Namespace):")1600+ self.indent()1601+ self.writeline(1602+ "raise TemplateRuntimeError"1603+ '("cannot assign attribute on non-namespace object")'1604+ )1605+ self.outdent()1606+1607 self.newline(node)1608 self.visit(node.target, frame)1609 self.write(" = ")1610 self.visit(node.node, frame)48 unmodified lines1659 1660 self.write(ref)1661 1662 def visit_NSRef(self, node: nodes.NSRef, frame: Frame) -> None:1640- # NSRefs can only be used to store values; since they use the normal1641- # `foo.bar` notation they will be parsed as a normal attribute access1642- # when used anywhere but in a `set` context1663+ # NSRef is a dotted assignment target a.b=c, but uses a[b]=c internally.1664+ # visit_Assign emits code to validate that each ref is to a Namespace1665+ # object only. That can't be emitted here as the ref could be in the1666+ # middle of a tuple assignment.1667 ref = frame.symbols.ref(node.name)1644- self.writeline(f"if not isinstance({ref}, Namespace):")1645- self.indent()1646- self.writeline(1647- "raise TemplateRuntimeError"1648- '("cannot assign attribute on non-namespace object")'1649- )1650- self.outdent()1668 self.writeline(f"{ref}[{node.attr!r}]")1669 1670 def visit_Const(self, node: nodes.Const, frame: Frame) -> None:1671 val = node.as_const(frame.eval_ctx)327 unmodified linesmodified:src/jinja2/parser.py+24 added-16 removed
485 unmodified lines486 `with_namespace` is enabled, a namespace assignment may be parsed.487 """488 target: nodes.Expr489 490- if with_namespace and self.stream.look().type == "dot":490+ if name_only:491 token = self.stream.expect("name")492- next(self.stream) # dot493- attr = self.stream.expect("name")494- target = nodes.NSRef(token.value, attr.value, lineno=token.lineno)495- elif name_only:496- token = self.stream.expect("name")492 target = nodes.Name(token.value, "store", lineno=token.lineno)493 else:494 if with_tuple:495 target = self.parse_tuple(501- simplified=True, extra_end_rules=extra_end_rules496+ simplified=True,497+ extra_end_rules=extra_end_rules,498+ with_namespace=with_namespace,499 )500 else:504- target = self.parse_primary()501+ target = self.parse_primary(with_namespace=with_namespace)502 503 target.set_ctx("store")504 505 if not target.can_assign():133 unmodified lines639 if with_filter:640 node = self.parse_filter_expr(node)641 return node642 646- def parse_primary(self) -> nodes.Expr:643+ def parse_primary(self, with_namespace: bool = False) -> nodes.Expr:644+ """Parse a name or literal value. If ``with_namespace`` is enabled, also645+ parse namespace attr refs, for use in assignments."""646 token = self.stream.current647 node: nodes.Expr648 if token.type == "name":649+ next(self.stream)650 if token.value in ("true", "false", "True", "False"):651 node = nodes.Const(token.value in ("true", "True"), lineno=token.lineno)652 elif token.value in ("none", "None"):653 node = nodes.Const(None, lineno=token.lineno)654+ elif with_namespace and self.stream.current.type == "dot":655+ # If namespace attributes are allowed at this point, and the next656+ # token is a dot, produce a namespace reference.657+ next(self.stream)658+ attr = self.stream.expect("name")659+ node = nodes.NSRef(token.value, attr.value, lineno=token.lineno)660 else:661 node = nodes.Name(token.value, "load", lineno=token.lineno)656- next(self.stream)662 elif token.type == "string":663 next(self.stream)664 buf = [token.value]665 lineno = token.lineno21 unmodified lines687 simplified: bool = False,688 with_condexpr: bool = True,689 extra_end_rules: t.Optional[t.Tuple[str, ...]] = None,690 explicit_parentheses: bool = False,691+ with_namespace: bool = False,692 ) -> t.Union[nodes.Tuple, nodes.Expr]:693 """Works like `parse_expression` but if multiple expressions are694 delimited by a comma a :class:`~jinja2.nodes.Tuple` node is created.695 This method could also return a regular expression instead of a tuple696 if no commas where found.697 698 The default parsing mode is a full tuple. If `simplified` is `True`693- only names and literals are parsed. The `no_condexpr` parameter is694- forwarded to :meth:`parse_expression`.699+ only names and literals are parsed; ``with_namespace`` allows namespace700+ attr refs as well. The `no_condexpr` parameter is forwarded to701+ :meth:`parse_expression`.702 703 Because tuples do not require delimiters and may end in a bogus comma704 an extra hint is needed that marks the end of a tuple. For example705 for loops support tuples between `for` and `in`. In that case the4 unmodified lines710 tuple is a valid expression or not.711 """712 lineno = self.stream.current.lineno713 if simplified:707- parse = self.parse_primary708- elif with_condexpr:709- parse = self.parse_expression714+715+ def parse() -> nodes.Expr:716+ return self.parse_primary(with_namespace=with_namespace)717+718 else:719 720 def parse() -> nodes.Expr:713- return self.parse_expression(with_condexpr=False)721+ return self.parse_expression(with_condexpr=with_condexpr)722 723 args: t.List[nodes.Expr] = []724 is_tuple = False725 324 unmodified linesmodified:tests/test_core_tags.py+8 added
536 unmodified lines537 "{{ ns.a }}|{{ ns.b }}"538 )539 assert tmpl.render() == "13|37"540 541+ def test_namespace_set_tuple(self, env_trim):542+ tmpl = env_trim.from_string(543+ "{% set ns = namespace(a=12, b=36) %}"544+ "{% set ns.a, ns.b = ns.a + 1, ns.b + 1 %}"545+ "{{ ns.a }}|{{ ns.b }}"546+ )547+ assert tmpl.render() == "13|37"548+549 def test_block_escaping_filtered(self):550 env = Environment(autoescape=True)551 tmpl = env.from_string(552 "{% set foo | trim %}<em>{{ test }}</em> {% endset %}foo: {{ foo }}"51 unmodified linesmodified:CHANGES.rst+2 added
41 unmodified lines42 - Improve annotations for methods returning copies. :pr:`1880`43 - ``urlize`` does not add ``mailto:`` to values like `@a@b`. :pr:`1870`44 - Tests decorated with `@pass_context`` can be used with the ``|select``45 filter. :issue:`1624`46+- Using ``set`` for multiple assignment (``a, b = 1, 2``) does not fail when the47+ target is a namespace attribute. :issue:`1413`48 49 50 Version 3.1.451 -------------994 unmodified lines