Skip to content

Commit 48ae978

Browse files
Michael0x2agvanrossum
authored andcommitted
Create a custom version of fastparse.py for Python 2 (#2102)
* Add a modified version of fastparse for Python 2.7 This commit adds a modified version of the fastparse module that works specifically on a Python 2 AST. This allows us to skip the step of first having to convert a Python 2 AST into a Python 3 AST, which helps boost performance on large codebases. * Make mypy start using fastparse 2 when applicable This commit adjusts parse.py and fastparse.py slightly so that they defer to fastparse2.py as necessary when encountering Python 2 code. * Fix bugs with new Python 2 AST converter This commit fixes a few bugs leftover from the conversion process, which were mainly remnants of WIP items I forgot to fix.
1 parent fa18e08 commit 48ae978

File tree

3 files changed

+877
-14
lines changed

3 files changed

+877
-14
lines changed

mypy/fastparse.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,7 @@
2525
from mypy.errors import Errors
2626

2727
try:
28-
from typed_ast import ast27
2928
from typed_ast import ast35
30-
from typed_ast import conversions
3129
except ImportError:
3230
if sys.version_info.minor > 2:
3331
print('You must install the typed_ast package before you can run mypy'
@@ -59,11 +57,8 @@ def parse(source: Union[str, bytes], fnam: str = None, errors: Errors = None,
5957
"""
6058
is_stub_file = bool(fnam) and fnam.endswith('.pyi')
6159
try:
62-
if pyversion[0] >= 3 or is_stub_file:
63-
ast = ast35.parse(source, fnam, 'exec')
64-
else:
65-
ast2 = ast27.parse(source, fnam, 'exec')
66-
ast = conversions.py2to3(ast2)
60+
assert pyversion[0] >= 3 or is_stub_file
61+
ast = ast35.parse(source, fnam, 'exec')
6762

6863
tree = ASTConverter(pyversion=pyversion,
6964
is_stub=is_stub_file,
@@ -802,6 +797,12 @@ class TypeConverter(ast35.NodeTransformer):
802797
def __init__(self, line: int = -1) -> None:
803798
self.line = line
804799

800+
def visit_raw_str(self, s: str) -> Type:
801+
# An escape hatch that allows the AST walker in fastparse2 to
802+
# directly hook into the Python 3.5 type converter in some cases
803+
# without needing to create an intermediary `ast35.Str` object.
804+
return parse_type_comment(s.strip(), line=self.line)
805+
805806
def generic_visit(self, node: ast35.AST) -> None:
806807
raise TypeCommentParseError(TYPE_COMMENT_AST_ERROR, self.line)
807808

0 commit comments

Comments
 (0)