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

367 lines, 199 significant
1"""
2conversion_pass.py - forward declarations, and virtuals
3"""
4import mypy
5
6from mypy.nodes import (Expression, NameExpr, MemberExpr, TupleExpr, CallExpr,
7 FuncDef, Argument)
8from mypy.types import Type, Instance, TupleType, NoneType
9
10from mycpp import util
11from mycpp.util import log, SplitPyName
12from mycpp import pass_state
13from mycpp import visitor
14from mycpp import cppgen_pass
15
16from typing import Dict, List, Tuple, Optional, TYPE_CHECKING
17
18if TYPE_CHECKING:
19 #from mycpp import cppgen_pass
20 pass
21
22_ = log
23
24DotExprs = Dict[MemberExpr, pass_state.member_t]
25
26
27class MyTypeInfo:
28 """Like mypy.nodes.TypeInfo"""
29
30 def __init__(self, fullname: str) -> None:
31 self.fullname = fullname
32
33
34class Primitive(Instance):
35
36 def __init__(self, name: str, args: List[Type] = None) -> None:
37 self.type = MyTypeInfo(name) # type: ignore
38 self.args = args if args is not None else []
39
40
41MYCPP_INT = Primitive('builtins.int')
42
43
44class Pass(visitor.SimpleVisitor):
45
46 def __init__(
47 self,
48 types: Dict[Expression, Type],
49 virtual: pass_state.Virtual,
50 forward_decls: List[str],
51 all_member_vars: 'cppgen_pass.AllMemberVars',
52 all_local_vars: 'cppgen_pass.AllLocalVars',
53 module_dot_exprs: DotExprs,
54 yield_out_params: Dict[FuncDef, Tuple[str, str]], # output
55 ) -> None:
56 visitor.SimpleVisitor.__init__(self)
57
58 # Input
59 self.types = types
60
61 # These are all outputs we compute
62 self.virtual = virtual
63 self.forward_decls = forward_decls
64 self.all_member_vars = all_member_vars
65 self.all_local_vars = all_local_vars
66 self.module_dot_exprs = module_dot_exprs
67 # Used to add another param to definition, and
68 # yield x --> YIELD->append(x)
69 self.yield_out_params = yield_out_params
70
71 # Internal state
72 self.current_member_vars: Dict[str, 'cppgen_pass.MemberVar'] = {}
73 self.current_local_vars: List[Tuple[str, Type]] = []
74
75 # Where do we need to update current_local_vars?
76 #
77 # x = 42 # oils_visit_assignment_stmt
78 # a, b = foo
79
80 # x = [y for y in other] # oils_visit_assign_to_listcomp_:
81 #
82 # Special case for enumerate:
83 # for i, x in enumerate(other):
84 #
85 # def f(p, q): # params are locals, _WriteFuncParams
86 # # but only if update_locals
87
88 self.imported_names = set() # MemberExpr -> module::Foo() or self->foo
89 # HACK for conditional import inside mylib.PYTHON
90 # in core/shell.py
91 self.imported_names.add('help_meta')
92
93 def visit_import(self, o: 'mypy.nodes.Import') -> None:
94 for name, as_name in o.ids:
95 if as_name is not None:
96 # import time as time_
97 self.imported_names.add(as_name)
98 else:
99 # import libc
100 self.imported_names.add(name)
101
102 def visit_import_from(self, o: 'mypy.nodes.ImportFrom') -> None:
103 """
104 Write C++ namespace aliases and 'using' for imports.
105 We need them in the 'decl' phase for default arguments like
106 runtime_asdl::scope_e -> scope_e
107 """
108 # For MemberExpr . -> module::func() or this->field. Also needed in
109 # the decl phase for default arg values.
110 for name, alias in o.names:
111 if alias:
112 self.imported_names.add(alias)
113 else:
114 self.imported_names.add(name)
115
116 def oils_visit_member_expr(self, o: 'mypy.nodes.MemberExpr') -> None:
117 # Why is self.types[o] missing some types? e.g. hnode.Record() call in
118 # asdl/runtime.py, failing with KeyError NameExpr
119 lhs_type = self.types.get(o.expr) # type: Optional[Type]
120
121 is_small_str = False
122 if util.SMALL_STR:
123 if util.IsStr(lhs_type):
124 is_small_str = True
125
126 # This is an approximate hack that assumes that locals don't shadow
127 # imported names. Might be a problem with names like 'word'?
128 if is_small_str:
129 # mystr.upper()
130 dot = pass_state.StackObjectMember(
131 o.expr, lhs_type, o.name) # type: pass_state.member_t
132
133 elif o.name in ('CreateNull', 'Take'):
134 # heuristic for MyType::CreateNull()
135 # MyType::Take(other)
136 type_name = self.types[o].ret_type.type.fullname
137 dot = pass_state.StaticClassMember(type_name, o.name)
138 elif (isinstance(o.expr, NameExpr) and
139 o.expr.name in self.imported_names):
140 # heuristic for state::Mem()
141 module_path = SplitPyName(o.expr.fullname or o.expr.name)
142 dot = pass_state.ModuleMember(module_path, o.name)
143 else:
144 # mylist->append(42)
145 dot = pass_state.HeapObjectMember(o.expr, lhs_type, o.name)
146
147 self.module_dot_exprs[o] = dot
148
149 self.accept(o.expr)
150
151 def oils_visit_mypy_file(self, o: 'mypy.nodes.MypyFile') -> None:
152 mod_parts = o.fullname.split('.')
153 comment = 'forward declare'
154
155 self.write('namespace %s { // %s\n', mod_parts[-1], comment)
156
157 # Do default traversal
158 self.indent += 1
159 super().oils_visit_mypy_file(o)
160 self.indent -= 1
161
162 self.write('}\n')
163 self.write('\n')
164
165 def oils_visit_class_def(
166 self, o: 'mypy.nodes.ClassDef',
167 base_class_sym: Optional[util.SymbolPath]) -> None:
168 self.write_ind('class %s;\n', o.name)
169 if base_class_sym:
170 self.virtual.OnSubclass(base_class_sym, self.current_class_name)
171
172 # Do default traversal of methods, associating member vars with the
173 # ClassDef node
174 self.current_member_vars = {}
175 super().oils_visit_class_def(o, base_class_sym)
176 self.all_member_vars[o] = self.current_member_vars
177
178 def _ValidateDefaultArg(self, arg: Argument) -> None:
179 t = self.types[arg.initializer]
180
181 valid = False
182 if isinstance(t, NoneType):
183 valid = True
184 if isinstance(t, Instance):
185 # Allowing strings since they're immutable, e.g.
186 # prefix='' seems OK
187 if t.type.fullname in ('builtins.bool', 'builtins.int',
188 'builtins.float', 'builtins.str'):
189 valid = True
190
191 # ASDL enums lex_mode_t, scope_t, ...
192 if t.type.fullname.endswith('_t'):
193 valid = True
194
195 # Hack for loc__Missing. Should detect the general case.
196 if t.type.fullname.endswith('loc__Missing'):
197 valid = True
198
199 if not valid:
200 self.report_error(
201 arg,
202 'Invalid default arg %r of type %s (not None, bool, int, float, ASDL enum)'
203 % (arg.initializer, t))
204
205 def _ValidateDefaultArgs(self, func_def: FuncDef) -> None:
206 arguments = func_def.arguments
207
208 num_defaults = 0
209 for arg in arguments:
210 if arg.initializer:
211 self._ValidateDefaultArg(arg)
212 num_defaults += 1
213
214 if num_defaults > 1:
215 # Report on first arg
216 self.report_error(
217 arg, '%s has %d default arguments. Only 1 is allowed' %
218 (func_def.name, num_defaults))
219 return
220
221 def oils_visit_func_def(self, o: 'mypy.nodes.FuncDef') -> None:
222 self._ValidateDefaultArgs(o)
223
224 self.virtual.OnMethod(self.current_class_name, o.name)
225
226 self.current_local_vars = []
227
228 # Add params as local vars, but only if we're NOT in a constructor.
229 # This is borrowed from cppgen_pass -
230 # _ConstructorImpl has update_locals=False, likewise for decl
231 # Is this just a convention?
232 # Counterexample: what if locals are used in __init__ after allocation?
233 # Are we assuming we never do mylib.MaybeCollect() inside a
234 # constructor? We can check that too.
235
236 if self.current_method_name != '__init__':
237 # Add function params as locals, to be rooted
238 arg_types = o.type.arg_types
239 arg_names = [arg.variable.name for arg in o.arguments]
240 for name, typ in zip(arg_names, arg_types):
241 if name == 'self':
242 continue
243 self.current_local_vars.append((name, typ))
244
245 # Traverse to collect member variables
246 super().oils_visit_func_def(o)
247 self.all_local_vars[o] = self.current_local_vars
248
249 # Is this function is a generator? Then associate the node with an
250 # accumulator param (name and type).
251 # This is info is consumed by both the Decl and Impl passes
252 _, _, c_iter_list_type = cppgen_pass.GetCReturnType(o.type.ret_type)
253 if c_iter_list_type is not None:
254 self.yield_out_params[o] = ('YIELD', c_iter_list_type)
255
256 def oils_visit_assign_to_listcomp(self, lval: NameExpr,
257 left_expr: Expression,
258 index_expr: Expression, seq: Expression,
259 cond: Expression) -> None:
260 # We need to consider 'result' a local var:
261 # result = [x for x in other]
262
263 # what about yield accumulator, like
264 # it_g = g(n)
265 self.current_local_vars.append((lval.name, self.types[lval]))
266
267 super().oils_visit_assign_to_listcomp(lval, left_expr, index_expr, seq,
268 cond)
269
270 def _MaybeAddMember(self, lval: MemberExpr) -> None:
271 assert not self.at_global_scope, "Members shouldn't be assigned at the top level"
272
273 # Collect statements that look like self.foo = 1
274 # Only do this in __init__ so that a derived class mutating a field
275 # from the base class doesn't cause duplicate C++ fields. (C++
276 # allows two fields of the same name!)
277 #
278 # HACK for WordParser: also include Reset(). We could change them
279 # all up front but I kinda like this.
280 if self.current_method_name not in ('__init__', 'Reset'):
281 return
282
283 if isinstance(lval.expr, NameExpr) and lval.expr.name == 'self':
284 #log(' lval.name %s', lval.name)
285 lval_type = self.types[lval]
286 c_type = cppgen_pass.GetCType(lval_type)
287 is_managed = cppgen_pass.CTypeIsManaged(c_type)
288 self.current_member_vars[lval.name] = (lval_type, c_type,
289 is_managed)
290
291 def oils_visit_assignment_stmt(self, o: 'mypy.nodes.AssignmentStmt',
292 lval: Expression, rval: Expression) -> None:
293
294 if isinstance(lval, MemberExpr):
295 self._MaybeAddMember(lval)
296
297 # Handle:
298 # x = y
299 # These two are special cases in cppgen_pass, but not here
300 # x = NewDict()
301 # x = cast(T, y)
302 #
303 # Note: this has duplicates: the 'done' set in visit_block() handles
304 # it. Could make it a Dict.
305 if isinstance(lval, NameExpr):
306 rval_type = self.types[rval]
307
308 # Two pieces of logic adapted from cppgen_pass: is_iterator and is_cast.
309 # Can we simplify them?
310
311 is_iterator = (isinstance(rval_type, Instance) and
312 rval_type.type.fullname == 'typing.Iterator')
313
314 # Downcasted vars are BLOCK-scoped, not FUNCTION-scoped, so they
315 # don't become local vars. They are also ALIASED, so they don't
316 # need to be rooted.
317 is_downcast_and_shadow = False
318 if (isinstance(rval, CallExpr) and
319 isinstance(rval.callee, NameExpr) and
320 rval.callee.name == 'cast'):
321 to_cast = rval.args[1]
322 if (isinstance(to_cast, NameExpr) and
323 to_cast.name.startswith('UP_')):
324 is_downcast_and_shadow = True
325
326 if (not self.at_global_scope and not is_iterator and
327 not is_downcast_and_shadow):
328 self.current_local_vars.append((lval.name, self.types[lval]))
329
330 # Handle local vars, like _write_tuple_unpacking
331
332 # This handles:
333 # a, b = func_that_returns_tuple()
334 if isinstance(lval, TupleExpr):
335 rval_type = self.types[rval]
336 assert isinstance(rval_type, TupleType), rval_type
337
338 for i, (lval_item,
339 item_type) in enumerate(zip(lval.items, rval_type.items)):
340 #self.log('*** %s :: %s', lval_item, item_type)
341 if isinstance(lval_item, NameExpr):
342 if util.SkipAssignment(lval_item.name):
343 continue
344 self.current_local_vars.append((lval_item.name, item_type))
345
346 # self.a, self.b = foo()
347 if isinstance(lval_item, MemberExpr):
348 self._MaybeAddMember(lval_item)
349
350 super().oils_visit_assignment_stmt(o, lval, rval)
351
352 def oils_visit_for_stmt(self, o: 'mypy.nodes.ForStmt',
353 func_name: Optional[str]) -> None:
354 # TODO: this variable should be BLOCK scoped, not function scoped, like
355 # the tuple variables for i, x
356 index0_name: Optional[str] = None
357 if func_name == 'enumerate':
358 assert isinstance(o.index, TupleExpr), o.index
359 index0 = o.index.items[0]
360 assert isinstance(index0, NameExpr), index0
361 index0_name = index0.name # generate int i = 0; ; ++i
362
363 if index0_name:
364 # can't initialize two things in a for loop, so do it on a separate line
365 self.current_local_vars.append((index0_name, MYCPP_INT))
366
367 super().oils_visit_for_stmt(o, func_name)