Skip to content

Commit 270afec

Browse files
goodmamiJukkaL
authored andcommitted
Fix 7807 (#7820)
Commit a8c7947 removed the old parser after the new one had taken over, but the ability to use `mypy.parse` as a script for dumping parse trees was also removed, perhaps by accident. This commit adds that functionality back as a script under `misc/`. This is work towards #7807. What remains is editing the wiki accordingly.
1 parent 7e7b1e4 commit 270afec

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

misc/dump-ast.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
#!/usr/bin/env python
2+
3+
"""
4+
Parse source files and print the abstract syntax trees.
5+
"""
6+
7+
from typing import Tuple
8+
import sys
9+
import argparse
10+
11+
from mypy.errors import CompileError
12+
from mypy.options import Options
13+
from mypy import defaults
14+
from mypy.parse import parse
15+
16+
17+
def dump(fname: str,
18+
python_version: Tuple[int, int],
19+
quiet: bool = False) -> None:
20+
options = Options()
21+
options.python_version = python_version
22+
with open(fname, 'rb') as f:
23+
s = f.read()
24+
tree = parse(s, fname, None, errors=None, options=options)
25+
if not quiet:
26+
print(tree)
27+
28+
29+
def main() -> None:
30+
# Parse a file and dump the AST (or display errors).
31+
parser = argparse.ArgumentParser(
32+
description="Parse source files and print the abstract syntax tree (AST).",
33+
)
34+
parser.add_argument('--py2', action='store_true', help='parse FILEs as Python 2')
35+
parser.add_argument('--quiet', action='store_true', help='do not print AST')
36+
parser.add_argument('FILE', nargs='*', help='files to parse')
37+
args = parser.parse_args()
38+
39+
if args.py2:
40+
pyversion = defaults.PYTHON2_VERSION
41+
else:
42+
pyversion = defaults.PYTHON3_VERSION
43+
44+
status = 0
45+
for fname in args.FILE:
46+
try:
47+
dump(fname, pyversion, args.quiet)
48+
except CompileError as e:
49+
for msg in e.messages:
50+
sys.stderr.write('%s\n' % msg)
51+
status = 1
52+
sys.exit(status)
53+
54+
55+
if __name__ == '__main__':
56+
main()

0 commit comments

Comments
 (0)