Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add option to preserve comments when parsing templates #2037

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ Unreleased
- Use modern packaging metadata with ``pyproject.toml`` instead of ``setup.cfg``.
:pr:`1793`
- Use ``flit_core`` instead of ``setuptools`` as build backend.
- Preserve comments in ASTs when parsing templates with ``Environment.parse``. :pr:`2037`


Version 3.1.5
Expand Down
16 changes: 5 additions & 11 deletions src/jinja2/lexer.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,17 +146,7 @@
f"({'|'.join(re.escape(x) for x in sorted(operators, key=lambda x: -len(x)))})"
)

ignored_tokens = frozenset(
[
TOKEN_COMMENT_BEGIN,
TOKEN_COMMENT,
TOKEN_COMMENT_END,
TOKEN_WHITESPACE,
TOKEN_LINECOMMENT_BEGIN,
TOKEN_LINECOMMENT_END,
TOKEN_LINECOMMENT,
]
)
ignored_tokens = frozenset([TOKEN_WHITESPACE])
ignore_if_empty = frozenset(
[TOKEN_WHITESPACE, TOKEN_DATA, TOKEN_COMMENT, TOKEN_LINECOMMENT]
)
Expand Down Expand Up @@ -631,6 +621,10 @@ def wrap(
token = TOKEN_BLOCK_BEGIN
elif token == TOKEN_LINESTATEMENT_END:
token = TOKEN_BLOCK_END
elif token == TOKEN_LINECOMMENT_BEGIN:
token = TOKEN_COMMENT_BEGIN
elif token == TOKEN_LINECOMMENT_END:
token = TOKEN_COMMENT_END
Comment on lines +624 to +627
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

note: Possible (small?) performance hit. Not sure how to avoid it.

# we are not interested in those tokens in the parser
elif token in (TOKEN_RAW_BEGIN, TOKEN_RAW_END):
continue
Expand Down
7 changes: 7 additions & 0 deletions src/jinja2/nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -715,6 +715,13 @@ def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
return self.expr2.as_const(eval_ctx)


class Comment(Stmt):
"""A template comment."""
Copy link
Contributor Author

@pawamoy pawamoy Oct 10, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Could maybe add .. versionadded:: 3.2, is that a valid directive?


fields = ("data",)
data: str


def args_as_const(
node: t.Union["_FilterTestCommon", "Call"], eval_ctx: t.Optional[EvalContext]
) -> t.Tuple[t.List[t.Any], t.Dict[t.Any, t.Any]]:
Expand Down
16 changes: 12 additions & 4 deletions src/jinja2/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -315,10 +315,13 @@ def parse_block(self) -> nodes.Block:
# with whitespace data
if node.required:
for body_node in node.body:
if not isinstance(body_node, nodes.Output) or any(
not isinstance(output_node, nodes.TemplateData)
or not output_node.data.isspace()
for output_node in body_node.nodes
if not isinstance(body_node, (nodes.Output, nodes.Comment)) or (
isinstance(body_node, nodes.Output)
Comment on lines +318 to +319
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

note: This was needed to fix the logic and two failing tests:

FAILED tests/test_inheritance.py::TestInheritance::test_level1_required - jinja2.exceptions.TemplateSyntaxError: Required blocks can only contain comments or whitespace
FAILED tests/test_inheritance.py::TestInheritance::test_invalid_required - jinja2.exceptions.TemplateSyntaxError: Required blocks can only contain comments or whitespace

and any(
not isinstance(output_node, nodes.TemplateData)
or not output_node.data.isspace()
for output_node in body_node.nodes
)
):
self.fail("Required blocks can only contain comments or whitespace")

Expand Down Expand Up @@ -1025,6 +1028,11 @@ def flush_data() -> None:
else:
body.append(rv)
self.stream.expect("block_end")
elif token.type == "comment_begin":
pawamoy marked this conversation as resolved.
Show resolved Hide resolved
flush_data()
next(self.stream)
body.append(nodes.Comment(next(self.stream).value))
self.stream.expect("comment_end")
else:
raise AssertionError("internal parsing error")

Expand Down
13 changes: 13 additions & 0 deletions tests/test_lexnparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,19 @@ def assert_error(code, expected):
)
assert_error("{% unknown_tag %}", "Encountered unknown tag 'unknown_tag'.")

def test_comment_preservation(self, env):
ast = env.parse("{# foo #}{{ bar }}")
assert len(ast.body) == 2
assert isinstance(ast.body[0], nodes.Comment)
assert ast.body[0].data == " foo "

def test_line_comment_preservation(self, env):
env = Environment(line_comment_prefix="#")
ast = env.parse("# foo\n{{ bar }}")
assert len(ast.body) == 2
assert isinstance(ast.body[0], nodes.Comment)
assert ast.body[0].data == " foo"


class TestSyntax:
def test_call(self, env):
Expand Down