Instagram / LibCST

A concrete syntax tree parser and serializer library for Python that preserves many aspects of Python's abstract syntax tree
https://libcst.readthedocs.io/
Other
1.56k stars 192 forks source link

Issue with `whitespace_after_*` not fixable #1118

Open AryazE opened 8 months ago

AryazE commented 8 months ago

I have to transform (using a libcst.CSTTransformer) some 3rd party code, which might contain statements like assert("foo") == "foo". Although this is a valid python code, I get the error libcst._nodes.base.CSTValidationError: Must have at least one space after 'assert'. I cannot fix this in the leave_Assert hook, as it is called after validation, and I cannot fix it in the visit_Assert hook, as the object node is frozen. Currently, the only option I can think of is to do a regex search and replace before LibCST to add the missing whitespace and then feed it to my transformer. Is there any easier way to do this, preferably within LibCST?

kiri11 commented 3 months ago

Seems like duplicate of https://github.com/Instagram/LibCST/issues/1095 UPDATE: Okay, maybe it's not the same, just similar. Here is assert, and there is while. UPDATE2: I was wrong, this is not an issue with the validator, I was just trying to add a node without parentheses.

kiri11 commented 3 months ago

@AryazE I had a similar issue. However, the LibCST validator is working correctly here by preventing me from generating incorrect code.

I fixed my code and might help you if you share what are you trying to do. I guess you did the same mistake by adding a new node without parentheses. LibCST does not automatically add whitespace or parentheses for you.

Here is what I did: just copied the parentheses from the node I was trying to replace:

return new_node.with_changes(
    lpar=updated_node.lpar,
    rpar=updated_node.rpar
)