OILS / mycpp / translate.py View on Github | oils.pub

226 lines, 138 significant
1#!/usr/bin/env python3
2from __future__ import print_function
3"""
4translate.py - Hook up all the stages
5"""
6
7import os
8import sys
9import tempfile
10import time
11
12# Our code
13#from _devbuild.gen.mycpp_asdl import mtype
14
15from mycpp import const_pass
16from mycpp import cppgen_pass
17from mycpp import control_flow_pass
18from mycpp import conversion_pass
19from mycpp import pass_state
20from mycpp.util import log
21from mycpp import visitor
22
23from typing import (Dict, List, Tuple, Any, TextIO, TYPE_CHECKING)
24
25if TYPE_CHECKING:
26 from mypy.nodes import FuncDef, MypyFile, Expression
27 from mypy.types import Type
28
29
30class Timer:
31 """
32 Example timings:
33
34 So loading it takes 13.4 seconds, and the rest only takes 2 seconds. If we
35 combine const pass and forward decl pass, that's only a couple hundred
36 milliseconds. So might as well keep them separate.
37
38 [0.1] mycpp: LOADING asdl/format.py ...
39 [13.7] mycpp pass: CONVERT
40 [13.8] mycpp pass: CONST
41 [14.0] mycpp pass: DECL
42 [14.4] mycpp pass: CONTROL FLOW
43 [15.0] mycpp pass: DATAFLOW
44 [15.0] mycpp pass: IMPL
45 [15.5] mycpp DONE
46 """
47
48 def __init__(self, start_time: float):
49 self.start_time = start_time
50
51 def Section(self, msg: str, *args: Any) -> None:
52 elapsed = time.time() - self.start_time
53
54 if args:
55 msg = msg % args
56
57 #log('\t[%.1f] %s', elapsed, msg)
58 log('\t%s', msg)
59
60
61def Run(timer: Timer,
62 f: TextIO,
63 header_f: TextIO,
64 types: Dict['Expression', 'Type'],
65 to_header: List[str],
66 to_compile: List[Tuple[str, 'MypyFile']],
67 preamble_path: str = '',
68 stack_roots_warn: bool = False,
69 minimize_stack_roots: bool = False) -> int:
70
71 #_ = mtype
72 #if 0:
73 # log('m %r' % mtype)
74 # log('m %r' % mtype.Callable)
75
76 f.write("""\
77// BEGIN mycpp output
78""")
79 if preamble_path:
80 f.write('#include "%s"\n' % preamble_path)
81
82 # Which functions are C++ 'virtual'?
83 virtual = pass_state.Virtual()
84
85 all_member_vars: cppgen_pass.AllMemberVars = {}
86 all_local_vars: cppgen_pass.AllLocalVars = {}
87 dot_exprs: Dict[str, conversion_pass.DotExprs] = {}
88 yield_out_params: Dict[FuncDef, Tuple[str, str]] = {}
89 dunder_exit_special: Dict[FuncDef, bool] = {}
90
91 # [PASS] namespace foo { class Spam; class Eggs; }
92 timer.Section('mycpp pass: CONVERT')
93
94 for name, module in to_compile:
95 forward_decls: List[str] = [] # unused
96 module_dot_exprs: conversion_pass.DotExprs = {}
97 p_convert = conversion_pass.Pass(
98 types,
99 virtual, # output
100 forward_decls, # TODO: write output of forward_decls
101 all_member_vars, # output
102 all_local_vars, # output
103 module_dot_exprs, # output
104 yield_out_params, # output
105 dunder_exit_special, # output
106 )
107 # forward declarations may go to header
108 p_convert.SetOutputFile(header_f if name in to_header else f)
109 p_convert.visit_mypy_file(module)
110 MaybeExitWithErrors(p_convert)
111
112 dot_exprs[module.path] = module_dot_exprs
113
114 if 0:
115 for node in dunder_exit_special:
116 log(' *** ctx_EXIT %s', node.name)
117
118 # After seeing class and method names in the first pass, figure out which
119 # ones are virtual. We use this info in the second pass.
120 virtual.Calculate()
121 if 0:
122 log('virtuals %s', virtual.virtuals)
123 log('has_vtable %s', virtual.has_vtable)
124
125 # [PASS]
126 timer.Section('mycpp pass: CONTROL FLOW')
127
128 cflow_graphs = {} # fully qualified function name -> control flow graph
129 for name, module in to_compile:
130 p_cflow = control_flow_pass.Build(types, virtual, all_local_vars,
131 dot_exprs[module.path])
132 p_cflow.visit_mypy_file(module)
133 cflow_graphs.update(p_cflow.cflow_graphs)
134 MaybeExitWithErrors(p_cflow)
135
136 # [PASS] Conditionally run Souffle
137 stack_roots = None
138 if minimize_stack_roots:
139 timer.Section('mycpp pass: SOUFFLE data flow')
140
141 # souffle_dir contains two subdirectories.
142 # facts: TSV files for the souffle inputs generated by mycpp
143 # outputs: TSV files for the solver's output relations
144 souffle_dir = os.getenv('MYCPP_SOUFFLE_DIR', None)
145 if souffle_dir is None:
146 tmp_dir = tempfile.TemporaryDirectory()
147 souffle_dir = tmp_dir.name
148 stack_roots = pass_state.ComputeMinimalStackRoots(
149 cflow_graphs, souffle_dir=souffle_dir)
150 else:
151 timer.Section('mycpp: dumping control flow graph to _tmp/mycpp-facts')
152
153 pass_state.DumpControlFlowGraphs(cflow_graphs)
154
155 # [PASS]
156 timer.Section('mycpp pass: CONST')
157
158 global_strings = const_pass.GlobalStrings()
159 p_const = const_pass.Collect(types, global_strings)
160
161 for name, module in to_compile:
162 p_const.visit_mypy_file(module)
163 MaybeExitWithErrors(p_const)
164
165 global_strings.ComputeStableVarNames()
166 # Emit GLOBAL_STR(), never to header
167 global_strings.WriteConstants(f)
168
169 # [PASS] C++ declarations like:
170 # class Foo { void method(); }; class Bar { void method(); };
171 timer.Section('mycpp pass: DECL')
172
173 for name, module in to_compile:
174 p_decl = cppgen_pass.Decl(
175 types,
176 global_strings, # input
177 yield_out_params,
178 dunder_exit_special,
179 virtual=virtual, # input
180 all_member_vars=all_member_vars, # input
181 )
182 # prototypes may go to a header
183 p_decl.SetOutputFile(header_f if name in to_header else f)
184 p_decl.visit_mypy_file(module)
185 MaybeExitWithErrors(p_decl)
186
187 if 0:
188 log('\tall_member_vars')
189 from pprint import pformat
190 print(pformat(all_member_vars), file=sys.stderr)
191
192 timer.Section('mycpp pass: IMPL')
193
194 # [PASS] the definitions / implementations:
195 # void Foo:method() { ... }
196 # void Bar:method() { ... }
197 for name, module in to_compile:
198 p_impl = cppgen_pass.Impl(
199 types,
200 global_strings,
201 yield_out_params,
202 dunder_exit_special,
203 local_vars=all_local_vars,
204 all_member_vars=all_member_vars,
205 dot_exprs=dot_exprs[module.path],
206 stack_roots=stack_roots,
207 stack_roots_warn=stack_roots_warn,
208 )
209 p_impl.SetOutputFile(f) # doesn't go to header
210 p_impl.visit_mypy_file(module)
211 MaybeExitWithErrors(p_impl)
212
213 timer.Section('mycpp DONE')
214 return 0 # success
215
216
217def MaybeExitWithErrors(p: visitor.SimpleVisitor) -> None:
218 # Check for errors we collected
219 num_errors = len(p.errors_keep_going)
220 if num_errors != 0:
221 log('')
222 log('%s: %d translation errors (after type checking)', sys.argv[0],
223 num_errors)
224
225 # A little hack to tell the test-invalid-examples harness how many errors we had
226 sys.exit(min(num_errors, 255))