Instagram / Instagram/LibCST

[BUG] Generated Code not equivalent to AST

Open
#341 11 comments 0 reactions 0 assignees View on GitHub
Dominant language
Python
Stars
1.9k
Forks
229
PR merge metrics
No merged PRs in 30d

Description

When doing replacements in a node, it's easy to end up with a tree, which won't get correctly converted to source code. The issue is that `libcst` is not adding the necessary parentheses.

For example, the code below
```py
import libcst.matchers as m
import libcst

module = libcst.parse_module('x * y')

matcher = m.Name(value='x')
new_module = m.replace(module, matcher, libcst.parse_expression("1 + 2"))
print(new_module.code)
```

will output
```py
1 + 2 * y
```

whereas the expected code is:

```py
(1 + 2) * y
```

I think it's reasonable to expect that a `module` is equivalent to `parse_module(module.code)`.

Contributor guide

Open the contributing guide

Research direction

Start with the parse_module and m.replace entry points using the provided x * y example, then trace how the replacement expression is rendered into source. Done means replacing x with 1 + 2 produces (1 + 2) * y, and reparsing generated module.code preserves the intended tree.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.