Skip to content

Commit

Permalink
Fix Literal parse error in RemoveImportsVisitor (#1130)
Browse files Browse the repository at this point in the history
  • Loading branch information
camillol authored May 3, 2024
1 parent 0713a35 commit 82f804a
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
11 changes: 10 additions & 1 deletion libcst/codemod/visitors/_gather_string_annotation_names.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ def visit_Annotation(self, node: cst.Annotation) -> bool:
def leave_Annotation(self, original_node: cst.Annotation) -> None:
self._annotation_stack.pop()

def visit_Subscript(self, node: cst.Subscript) -> bool:
qnames = self.get_metadata(QualifiedNameProvider, node)
# A Literal["foo"] should not be interpreted as a use of the symbol "foo".
return not any(qn.name == "typing.Literal" for qn in qnames)

def visit_Call(self, node: cst.Call) -> bool:
qnames = self.get_metadata(QualifiedNameProvider, node)
if any(qn.name in self._typing_functions for qn in qnames):
Expand Down Expand Up @@ -71,7 +76,11 @@ def handle_any_string(
value = node.evaluated_value
if value is None:
return
mod = cst.parse_module(value)
try:
mod = cst.parse_module(value)
except cst.ParserSyntaxError:
# Not all strings inside a type annotation are meant to be valid Python code.
return
extracted_nodes = m.extractall(
mod,
m.Name(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,14 @@ def test_dotted_names(self) -> None:
visitor.names,
{"api", "api.http_exceptions", "api.http_exceptions.HttpException"},
)

def test_literals(self) -> None:
visitor = self.gather_names(
"""
from typing import Literal
a: Literal["in"]
b: list[Literal["1x"]]
c: Literal["Any"]
"""
)
self.assertEqual(visitor.names, set())

0 comments on commit 82f804a

Please sign in to comment.