Don't add unnecessary parentheses during inline variable extraction#3935
Don't add unnecessary parentheses during inline variable extraction#3935ak4-sh wants to merge 4 commits into
Conversation
- Following nodes get parantheses: BinOp, BoolOp, Compare, UnaryOp, IfExp, Lambda, NamedExpr, GeneratorExp, Tuple, Await, Yield, YieldFrom - Constant AST nodes get parantheses if they're being inlined into an attr acces node Remove debug comments and avoid creating replacement clones Replacement text is being freshly generated per reference hence clone not needed Rename test Move always_needs_parens out of loop
There was a problem hiding this comment.
Thanks for the fix, @ak4-sh !
One tiny optional follow-up (not blocking): NumberLiteral also matches floats/complex, but only integer literals have the 42. ambiguity
4.2.foo and 4j.foo are already valid Python, so they'll get a harmless-but-redundant (...). If you want to be minimal you could narrow that check to integer literals, but the current behavior is perfectly safe. Thanks again!
|
@NathanTempest has imported this pull request. If you are a Meta employee, you can view this in D110088158. |
kinto0
left a comment
There was a problem hiding this comment.
Review automatically exported from Phabricator review in Meta.
ndmitchell
left a comment
There was a problem hiding this comment.
Review automatically exported from Phabricator review in Meta.
|
Thanks for the comment @NathanTempest! I've updated the match condition, do let me know if it looks okay |
NathanTempest
left a comment
There was a problem hiding this comment.
Good work! The Number::Int narrowing is exactly right, floats/complex no longer get redundant parens while decimal ints (42.bit_length()) are still handled. One small convention nit: we keep imports at the top rather than inline-qualified paths, so use ruff_python_ast::Number; + Number::Int(_) (matches how alt/expr.rs does it). Optionally, a quick negative test that 4.2.foo stays unparenthesized would lock in the new behavior. Thanks for iterating on this!
|
@NathanTempest Made the updates, sorry about this! |
Summary
Fix inline variable refactoring to only add parentheses when they are needed for the expression being inlined and the context where it is inserted.
value = 42; value.bit_length()becomes(42).bit_length().Fixes #3882
Test Plan
Added LSP code action tests for: