Skip to content

Commit

Permalink
Fix for not parsing subscripts such as cast()["from"]
Browse files Browse the repository at this point in the history
  • Loading branch information
Kronuz committed Dec 8, 2020
1 parent 8eee3cc commit fd444fe
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 5 deletions.
11 changes: 6 additions & 5 deletions libcst/metadata/scope_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -825,11 +825,12 @@ def _handle_string_annotation(
return False

def visit_Subscript(self, node: cst.Subscript) -> Optional[bool]:
qnames = {qn.name for qn in self.scope.get_qualified_names_for(node.value)}
if any(qn.startswith(("typing.", "typing_extensions.")) for qn in qnames):
self.__in_type_hint.add(node)
if "typing.Literal" in qnames or "typing_extensions.Literal" in qnames:
self.__in_ignored_subscript.add(node)
if isinstance(node.value, cst.Name):
qnames = {qn.name for qn in self.scope.get_qualified_names_for(node.value)}
if any(qn.startswith(("typing.", "typing_extensions.")) for qn in qnames):
self.__in_type_hint.add(node)
if "typing.Literal" in qnames or "typing_extensions.Literal" in qnames:
self.__in_ignored_subscript.add(node)
return True

def leave_Subscript(self, original_node: cst.Subscript) -> None:
Expand Down
57 changes: 57 additions & 0 deletions libcst/metadata/tests/test_scope_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -1567,3 +1567,60 @@ def f(a):
self.assertEqual(list(a_param_refs)[0].node, comp.for_in.iter)
self.assertEqual(len(a_comp_assignment.references), 1)
self.assertEqual(list(a_comp_assignment.references)[0].node, comp.elt)

def test_cast(self) -> None:
with self.assertRaises(cst.ParserSyntaxError):
m, scopes = get_scope_metadata_provider(
"""
from typing import TypeVar
TypeVar("Name", "3rr0r")
"""
)

try:
m, scopes = get_scope_metadata_provider(
"""
from typing import TypeVar
TypeVar("3rr0r", "int")
"""
)
except cst.ParserSyntaxError:
self.fail(
"First string argument of NewType and TypeVar should not be parsed"
)

with self.assertRaises(cst.ParserSyntaxError):
m, scopes = get_scope_metadata_provider(
"""
from typing import Dict
Dict["str", "3rr0r"]
"""
)

try:
m, scopes = get_scope_metadata_provider(
"""
from typing import Dict, cast
cast(Dict[str, str], {})["3rr0r"]
"""
)
except cst.ParserSyntaxError:
self.fail("Subscript of function calls should not be parsed")

try:
m, scopes = get_scope_metadata_provider(
"""
from typing import cast
cast(str, "3rr0r")
"""
)
except cst.ParserSyntaxError:
self.fail("String arguments of cast should not be parsed")

with self.assertRaises(cst.ParserSyntaxError):
m, scopes = get_scope_metadata_provider(
"""
from typing import cast
cast("3rr0r", "")
"""
)

0 comments on commit fd444fe

Please sign in to comment.