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

Names in subscript expressions have the wrong expression context #318

Closed
zsol opened this issue Jun 18, 2020 · 4 comments · Fixed by #319
Closed

Names in subscript expressions have the wrong expression context #318

zsol opened this issue Jun 18, 2020 · 4 comments · Fixed by #319
Assignees
Labels
bug Something isn't working

Comments

@zsol
Copy link
Member

zsol commented Jun 18, 2020

I stumbled on this by running RemoveImportsVisitor on a large codebase and saw that
RemoveImportsVisitor incorrectly removes imports corresponding to some symbols used in assignments.

Example repro:

from a import b
b[0] = False
@zsol zsol added the bug Something isn't working label Jun 18, 2020
@zsol zsol self-assigned this Jun 18, 2020
@zsol
Copy link
Member Author

zsol commented Jun 18, 2020

Looks like this is because in the above example, b[0] is used in ExpressionContext.STORE, so it's recorded as an assignment in ScopeProvider. Technically, b is not being assigned to, so that's incorrect. Consider also

from a import identity
x = [1]
identity(x)[0] = 2

Currently ExpressionContextProvider returns LOAD for the name identity. That's the source of this bug.

I think ExpressionContextProvider should only return STORE for Name nodes inside a Subscript expression. @jimmylai any thoughts on this?

@zsol
Copy link
Member Author

zsol commented Jun 18, 2020

To clarify, this line tests a buggy behavior, it should verify that a has a LOAD context:
https://github.com/Instagram/LibCST/blob/master/libcst/metadata/tests/test_expression_context_provider.py#L151

@zsol
Copy link
Member Author

zsol commented Jun 18, 2020

Looks like the ast module already does this:

>>> import ast
>>> m = ast.parse("from a import b; b[0] = False")
>>> m.body[1].targets[0].value.ctx
<_ast.Load object at 0x7f25ce22a3d0>

zsol added a commit to zsol/LibCST that referenced this issue Jun 18, 2020
@zsol zsol changed the title RemoveImportsVisitor incorrectly removes symbols used in assignments Names in subscript expressions have the wrong expression context Jun 18, 2020
@jimmylai
Copy link
Contributor

Great finding! I didn't carefully make it right for subscript name when building ExpressionContext . Thanks for reporting this and fix it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants