OILS / pea / parse.py View on Github | oils.pub

45 lines, 24 significant
1import ast
2from ast import AST, stmt
3import os
4
5from pea.header import TypeSyntaxError, Program, PyFile
6
7
8def ParseFuncType(st: stmt) -> AST:
9 # 2024-12: causes an error with the latest MyPy, 1.13.0
10 # works with Soil CI MyPy, 1.10.0
11 #assert st.type_comment, st
12
13 # Caller checks this. Is there a better way?
14 assert hasattr(st, 'type_comment'), st
15
16 try:
17 # This parses with the func_type production in the grammar
18 return ast.parse(st.type_comment, mode='func_type')
19 except SyntaxError:
20 raise TypeSyntaxError(st.lineno, st.type_comment)
21
22
23def ParseFiles(files: list[str], prog: Program) -> bool:
24
25 for filename in files:
26 with open(filename) as f:
27 contents = f.read()
28
29 try:
30 # Python 3.8+ supports type_comments=True
31 module = ast.parse(contents, filename=filename, type_comments=True)
32 except SyntaxError as e:
33 # This raises an exception for some reason
34 #e.print_file_and_line()
35 print('Error parsing %s: %s' % (filename, e))
36 return False
37
38 tmp = os.path.basename(filename)
39 namespace, _ = os.path.splitext(tmp)
40
41 prog.py_files.append(PyFile(filename, namespace, module))
42
43 prog.stats['num_files'] += 1
44
45 return True