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

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