Skip to content

Commit

Permalink
Copy changes from parser.py to parser_libcst.py.
Browse files Browse the repository at this point in the history
  • Loading branch information
rchen152 committed Jul 18, 2022
1 parent b2fdcd2 commit 5b045e8
Showing 1 changed file with 30 additions and 2 deletions.
32 changes: 30 additions & 2 deletions pytype/directors/parser_libcst.py
Expand Up @@ -25,6 +25,9 @@ class LineRange:
start_line: int
end_line: int

def __contains__(self, line):
return self.start_line <= line <= self.end_line


@dataclasses.dataclass(frozen=True)
class Call(LineRange):
Expand Down Expand Up @@ -53,6 +56,31 @@ class _VariableAnnotation(LineRange):
annotation: str


class BlockReturns:
"""Tracks return statements in with/try blocks."""

def __init__(self):
self._block_ranges = []
self._returns = []
self._block_returns = {}

def add_return(self, pos):
self._returns.append(pos.start.line)

def all_returns(self):
return set(self._returns)

def __iter__(self):
return iter(self._block_returns.items())

def __repr__(self):
return f"""
Blocks: {self._block_ranges}
Returns: {self._returns}
{self._block_returns}
"""


class _ParseVisitor(libcst.CSTVisitor):
"""Visitor for parsing a source tree.
Expand Down Expand Up @@ -80,8 +108,8 @@ def __init__(self):
self.variable_annotations = []
self.decorators = []
self.defs_start = None
self.returns = set()
self.function_ranges = {}
self.block_returns = BlockReturns()

def _get_containing_groups(self, start_line, end_line=None):
"""Get _StructuredComment groups that fully contain the given line range."""
Expand Down Expand Up @@ -240,7 +268,7 @@ def visit_AnnAssign(self, node):
_VariableAnnotation(pos.start.line, pos.end.line, annotation))

def visit_Return(self, node):
self.returns.add(self._get_position(node).start.line)
self.block_returns.add_return(self._get_position(node))

def _visit_decorators(self, node):
if not node.decorators:
Expand Down

0 comments on commit 5b045e8

Please sign in to comment.