Skip to content

Python: Parenthesize template results based on surrounding context#6827

Merged
knutwannheden merged 4 commits intomainfrom
python-template-parenthesize-fix
Feb 26, 2026
Merged

Python: Parenthesize template results based on surrounding context#6827
knutwannheden merged 4 commits intomainfrom
python-template-parenthesize-fix

Conversation

@knutwannheden
Copy link
Copy Markdown
Contributor

Summary

  • Adds maybe_parenthesize() to wrap template results in J.Parentheses when their operator precedence is lower than the surrounding AST context (e.g., or template result placed inside a not parent)
  • Restructures Template.apply() into three explicit phases: placeholder substitution → precedence-based parenthesization → coordinate application
  • Mirrors Java's ParenthesizeVisitor.maybeParenthesize called from JavaTemplate.doApply()

Test plan

  • 6 new unit/integration tests in TestMaybeParenthesize covering binary-in-binary, unary-under-not, no-parens-needed, non-expression passthrough, and full Template.apply() integration
  • Existing 31 template tests continue to pass

Template.apply() now checks whether the returned expression needs
parentheses when placed in the surrounding AST context, mirroring
JavaTemplate.doApply()'s call to ParenthesizeVisitor.maybeParenthesize.

Restructures Template.apply() into three phases:
1. Placeholder substitution
2. Precedence-based parenthesization (new)
3. Coordinate application (prefix, statement wrapping, formatting)
Remove dead `coordinates` and `cursor` params from `apply_substitutions`,
extend `_get_precedence` to handle `not` unary (precedence 3), fix test
calling renamed `apply_coordinates`, and add clarifying docstring for the
outer/inner parenthesization boundary.
…ture

Remove stale `cursor=None` kwarg from test calls after the parameter
was removed from TemplateEngine.apply_substitutions in 7ca8044.
@knutwannheden knutwannheden merged commit 886de26 into main Feb 26, 2026
1 check passed
@knutwannheden knutwannheden deleted the python-template-parenthesize-fix branch February 26, 2026 13:54
@github-project-automation github-project-automation Bot moved this from In Progress to Done in OpenRewrite Feb 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Archived in project

Development

Successfully merging this pull request may close these issues.

1 participant