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

223 lines, 135 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 stack_roots_warn: bool = False,
68 minimize_stack_roots: bool = False) -> int:
69
70 #_ = mtype
71 #if 0:
72 # log('m %r' % mtype)
73 # log('m %r' % mtype.Callable)
74
75 f.write("""\
76// BEGIN mycpp output
77""")
78
79 # Which functions are C++ 'virtual'?
80 virtual = pass_state.Virtual()
81
82 all_member_vars: cppgen_pass.AllMemberVars = {}
83 all_local_vars: cppgen_pass.AllLocalVars = {}
84 dot_exprs: Dict[str, conversion_pass.DotExprs] = {}
85 yield_out_params: Dict[FuncDef, Tuple[str, str]] = {}
86 dunder_exit_special: Dict[FuncDef, bool] = {}
87
88 # [PASS] namespace foo { class Spam; class Eggs; }
89 timer.Section('mycpp pass: CONVERT')
90
91 for name, module in to_compile:
92 forward_decls: List[str] = [] # unused
93 module_dot_exprs: conversion_pass.DotExprs = {}
94 p_convert = conversion_pass.Pass(
95 types,
96 virtual, # output
97 forward_decls, # TODO: write output of forward_decls
98 all_member_vars, # output
99 all_local_vars, # output
100 module_dot_exprs, # output
101 yield_out_params, # output
102 dunder_exit_special, # output
103 )
104 # forward declarations may go to header
105 p_convert.SetOutputFile(header_f if name in to_header else f)
106 p_convert.visit_mypy_file(module)
107 MaybeExitWithErrors(p_convert)
108
109 dot_exprs[module.path] = module_dot_exprs
110
111 if 0:
112 for node in dunder_exit_special:
113 log(' *** ctx_EXIT %s', node.name)
114
115 # After seeing class and method names in the first pass, figure out which
116 # ones are virtual. We use this info in the second pass.
117 virtual.Calculate()
118 if 0:
119 log('virtuals %s', virtual.virtuals)
120 log('has_vtable %s', virtual.has_vtable)
121
122 # [PASS]
123 timer.Section('mycpp pass: CONTROL FLOW')
124
125 cflow_graphs = {} # fully qualified function name -> control flow graph
126 for name, module in to_compile:
127 p_cflow = control_flow_pass.Build(types, virtual, all_local_vars,
128 dot_exprs[module.path])
129 p_cflow.visit_mypy_file(module)
130 cflow_graphs.update(p_cflow.cflow_graphs)
131 MaybeExitWithErrors(p_cflow)
132
133 # [PASS] Conditionally run Souffle
134 stack_roots = None
135 if minimize_stack_roots:
136 timer.Section('mycpp pass: SOUFFLE data flow')
137
138 # souffle_dir contains two subdirectories.
139 # facts: TSV files for the souffle inputs generated by mycpp
140 # outputs: TSV files for the solver's output relations
141 souffle_dir = os.getenv('MYCPP_SOUFFLE_DIR', None)
142 if souffle_dir is None:
143 tmp_dir = tempfile.TemporaryDirectory()
144 souffle_dir = tmp_dir.name
145 stack_roots = pass_state.ComputeMinimalStackRoots(
146 cflow_graphs, souffle_dir=souffle_dir)
147 else:
148 timer.Section('mycpp: dumping control flow graph to _tmp/mycpp-facts')
149
150 pass_state.DumpControlFlowGraphs(cflow_graphs)
151
152 # [PASS]
153 timer.Section('mycpp pass: CONST')
154
155 global_strings = const_pass.GlobalStrings()
156 p_const = const_pass.Collect(types, global_strings)
157
158 for name, module in to_compile:
159 p_const.visit_mypy_file(module)
160 MaybeExitWithErrors(p_const)
161
162 global_strings.ComputeStableVarNames()
163 # Emit GLOBAL_STR(), never to header
164 global_strings.WriteConstants(f)
165
166 # [PASS] C++ declarations like:
167 # class Foo { void method(); }; class Bar { void method(); };
168 timer.Section('mycpp pass: DECL')
169
170 for name, module in to_compile:
171 p_decl = cppgen_pass.Decl(
172 types,
173 global_strings, # input
174 yield_out_params,
175 dunder_exit_special,
176 virtual=virtual, # input
177 all_member_vars=all_member_vars, # input
178 )
179 # prototypes may go to a header
180 p_decl.SetOutputFile(header_f if name in to_header else f)
181 p_decl.visit_mypy_file(module)
182 MaybeExitWithErrors(p_decl)
183
184 if 0:
185 log('\tall_member_vars')
186 from pprint import pformat
187 print(pformat(all_member_vars), file=sys.stderr)
188
189 timer.Section('mycpp pass: IMPL')
190
191 # [PASS] the definitions / implementations:
192 # void Foo:method() { ... }
193 # void Bar:method() { ... }
194 for name, module in to_compile:
195 p_impl = cppgen_pass.Impl(
196 types,
197 global_strings,
198 yield_out_params,
199 dunder_exit_special,
200 local_vars=all_local_vars,
201 all_member_vars=all_member_vars,
202 dot_exprs=dot_exprs[module.path],
203 stack_roots=stack_roots,
204 stack_roots_warn=stack_roots_warn,
205 )
206 p_impl.SetOutputFile(f) # doesn't go to header
207 p_impl.visit_mypy_file(module)
208 MaybeExitWithErrors(p_impl)
209
210 timer.Section('mycpp DONE')
211 return 0 # success
212
213
214def MaybeExitWithErrors(p: visitor.SimpleVisitor) -> None:
215 # Check for errors we collected
216 num_errors = len(p.errors_keep_going)
217 if num_errors != 0:
218 log('')
219 log('%s: %d translation errors (after type checking)', sys.argv[0],
220 num_errors)
221
222 # A little hack to tell the test-invalid-examples harness how many errors we had
223 sys.exit(min(num_errors, 255))