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

417 lines, 237 significant
1"""
2conversion_pass.py - forward declarations, and virtuals
3"""
4import mypy
5
6from mypy.nodes import (Expression, NameExpr, MemberExpr, TupleExpr, CallExpr,
7 ClassDef, FuncDef, Argument)
8from mypy.types import Type, Instance, TupleType, NoneType, PartialType
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.TypedVisitor):
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 dunder_exit_special: Dict[ClassDef, bool],
56 ) -> None:
57 visitor.TypedVisitor.__init__(self, types)
58
59 # These are all outputs we compute
60 self.virtual = virtual
61 self.forward_decls = forward_decls
62 self.all_member_vars = all_member_vars
63 self.all_local_vars = all_local_vars
64 self.module_dot_exprs = module_dot_exprs
65 # Used to add another param to definition, and
66 # yield x --> YIELD->append(x)
67 self.yield_out_params = yield_out_params
68 self.dunder_exit_special = dunder_exit_special
69
70 # Internal state
71 self.inside_dunder_exit = None # type: Optional[ClassDef]
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 # asdl/runtime.py is missing types, so call GetTypeOptional
118 lhs_type = self._GetTypeOptional(o.expr) # type: Optional[Type]
119
120 is_small_str = False
121 if util.SMALL_STR:
122 if util.IsStr(lhs_type):
123 is_small_str = True
124
125 # This is an approximate hack that assumes that locals don't shadow
126 # imported names. Might be a problem with names like 'word'?
127 if is_small_str:
128 # mystr.upper()
129 dot = pass_state.StackObjectMember(
130 o.expr, lhs_type, o.name) # type: pass_state.member_t
131
132 elif o.name in ('CreateNull', 'Take'):
133 # heuristic for MyType::CreateNull()
134 # MyType::Take(other)
135 type_name = self.types[o].ret_type.type.fullname
136 dot = pass_state.StaticClassMember(type_name, o.name)
137 elif (isinstance(o.expr, NameExpr) and
138 o.expr.name in self.imported_names):
139 # heuristic for state::Mem()
140 module_path = SplitPyName(o.expr.fullname or o.expr.name)
141 dot = pass_state.ModuleMember(module_path, o.name)
142 else:
143 # mylist->append(42)
144 dot = pass_state.HeapObjectMember(o.expr, lhs_type, o.name)
145
146 self.module_dot_exprs[o] = dot
147
148 self.accept(o.expr)
149
150 def oils_visit_mypy_file(self, o: 'mypy.nodes.MypyFile') -> None:
151 mod_parts = o.fullname.split('.')
152 comment = 'forward declare'
153
154 self.write('namespace %s { // %s\n', mod_parts[-1], comment)
155
156 # Do default traversal
157 self.indent += 1
158 super().oils_visit_mypy_file(o)
159 self.indent -= 1
160
161 self.write('}\n')
162 self.write('\n')
163
164 def oils_visit_class_def(
165 self, o: 'mypy.nodes.ClassDef',
166 base_class_sym: Optional[util.SymbolPath],
167 current_class_name: 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, 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, current_class_name)
176 self.all_member_vars[o] = self.current_member_vars
177
178 def _ValidateDefaultArg(self, arg: Argument) -> None:
179 t = self._GetType(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',
222 current_class_name: Optional[util.SymbolPath],
223 current_method_name: Optional[str]) -> None:
224 self._ValidateDefaultArgs(o)
225
226 self.virtual.OnMethod(current_class_name, o.name)
227
228 self.current_local_vars = []
229
230 # Add params as local vars, but only if we're NOT in a constructor.
231 # This is borrowed from cppgen_pass -
232 # _ConstructorImpl has update_locals=False, likewise for decl
233 # Is this just a convention?
234 # Counterexample: what if locals are used in __init__ after allocation?
235 # Are we assuming we never do mylib.MaybeCollect() inside a
236 # constructor? We can check that too.
237
238 if current_method_name != '__init__':
239 # Add function params as locals, to be rooted
240 arg_types = o.type.arg_types
241 arg_names = [arg.variable.name for arg in o.arguments]
242 for name, typ in zip(arg_names, arg_types):
243 if name == 'self':
244 continue
245 self.current_local_vars.append((name, typ))
246
247 # Traverse to collect member variables
248 super().oils_visit_func_def(o, current_class_name, current_method_name)
249 self.all_local_vars[o] = self.current_local_vars
250
251 # Is this function is a generator? Then associate the node with an
252 # accumulator param (name and type).
253 # This is info is consumed by both the Decl and Impl passes
254 _, _, c_iter_list_type = cppgen_pass.GetCReturnType(o.type.ret_type)
255 if c_iter_list_type is not None:
256 self.yield_out_params[o] = ('YIELD', c_iter_list_type)
257
258 def oils_visit_dunder_exit(self, o: ClassDef, stmt: FuncDef,
259 base_class_sym: util.SymbolPath) -> None:
260 self.inside_dunder_exit = o
261 super().oils_visit_dunder_exit(o, stmt, base_class_sym)
262 self.inside_dunder_exit = None
263
264 def visit_return_stmt(self, o: 'mypy.nodes.ReturnStmt') -> None:
265 # Mark special destructors
266 if self.inside_dunder_exit:
267 self.dunder_exit_special[self.inside_dunder_exit] = True
268 super().visit_return_stmt(o)
269
270 def visit_raise_stmt(self, o: 'mypy.nodes.RaiseStmt') -> None:
271 if self.inside_dunder_exit:
272 # Note: this doesn't check function calls that raise, but it's
273 # better than nothing
274 self.report_error(
275 o, "raise not allowed within __exit__ (C++ doesn't allow it)")
276 return
277 super().visit_raise_stmt(o)
278
279 def oils_visit_assign_to_listcomp(self, lval: NameExpr,
280 left_expr: Expression,
281 index_expr: Expression, seq: Expression,
282 cond: Expression) -> None:
283 # We need to consider 'result' a local var:
284 # result = [x for x in other]
285
286 # what about yield accumulator, like
287 # it_g = g(n)
288 self.current_local_vars.append((lval.name, self._GetType(lval)))
289
290 super().oils_visit_assign_to_listcomp(lval, left_expr, index_expr, seq,
291 cond)
292
293 def _MaybeAddMember(self, lval: MemberExpr,
294 current_method_name: Optional[str],
295 at_global_scope: bool) -> None:
296 assert not at_global_scope, "Members shouldn't be assigned at the top level"
297
298 # Collect statements that look like self.foo = 1
299 # Only do this in __init__ so that a derived class mutating a field
300 # from the base class doesn't cause duplicate C++ fields. (C++
301 # allows two fields of the same name!)
302 #
303 # HACK for WordParser: also include Reset(). We could change them
304 # all up front but I kinda like this.
305 if current_method_name not in ('__init__', 'Reset'):
306 return
307
308 if isinstance(lval.expr, NameExpr) and lval.expr.name == 'self':
309 #log(' lval.name %s', lval.name)
310 lval_type = self._GetType(lval)
311 c_type = cppgen_pass.GetCType(lval_type)
312 is_managed = cppgen_pass.CTypeIsManaged(c_type)
313 self.current_member_vars[lval.name] = (lval_type, c_type,
314 is_managed)
315
316 def oils_visit_assignment_stmt(self, o: 'mypy.nodes.AssignmentStmt',
317 lval: Expression, rval: Expression,
318 current_method_name: Optional[str],
319 at_global_scope: bool) -> None:
320
321 if isinstance(lval, MemberExpr):
322 self._MaybeAddMember(lval, current_method_name, at_global_scope)
323
324 # TupleExpr will not be in self.types
325 t = self._GetTypeOptional(lval) # type: Optional[Type]
326 if isinstance(t, PartialType):
327 self.report_error(
328 o,
329 "Mismatched types: trying to assign expression of type '%s' to "
330 "a PartialType variable '%s' (was likely assigned None before).\n"
331 "Tip: If your type translates to a heap-allocated type (e.g. str "
332 "or class), you can annotate it with '# type: Optional[T]'. "
333 "If your type is allocated on the stack (int), then you can use "
334 "-1 or similar as an in-band null value" %
335 (t.var.type.type.name, t.var.name))
336 return
337
338 # Handle:
339 # x = y
340 # These two are special cases in cppgen_pass, but not here
341 # x = NewDict()
342 # x = cast(T, y)
343 #
344 # Note: this has duplicates: the 'done' set in visit_block() handles
345 # it. Could make it a Dict.
346 if isinstance(lval, NameExpr):
347 rval_type = self._GetType(rval)
348
349 # Two pieces of logic adapted from cppgen_pass: is_iterator and is_cast.
350 # Can we simplify them?
351
352 is_iterator = (isinstance(rval_type, Instance) and
353 rval_type.type.fullname == 'typing.Iterator')
354
355 # Downcasted vars are BLOCK-scoped, not FUNCTION-scoped, so they
356 # don't become local vars. They are also ALIASED, so they don't
357 # need to be rooted.
358 is_downcast_and_shadow = False
359 if (isinstance(rval, CallExpr) and
360 isinstance(rval.callee, NameExpr) and
361 rval.callee.name == 'cast'):
362 to_cast = rval.args[1]
363 if (isinstance(to_cast, NameExpr) and
364 to_cast.name.startswith('UP_')):
365 is_downcast_and_shadow = True
366
367 if (not at_global_scope and not is_iterator and
368 not is_downcast_and_shadow):
369 self.current_local_vars.append((lval.name, self._GetType(lval)))
370
371 # Handle local vars, like _write_tuple_unpacking
372
373 # This handles:
374 # a, b = func_that_returns_tuple()
375 if isinstance(lval, TupleExpr):
376 if isinstance(rval, TupleExpr):
377 self.report_error(
378 o, "mycpp currently does not handle code like "
379 "'a, b = x, y'. You can move each assignment to its own line "
380 "or return (x, y) from a function instead.")
381 return
382
383 rval_type = self._GetType(rval)
384 assert isinstance(rval_type, TupleType), rval_type
385
386 for i, (lval_item,
387 item_type) in enumerate(zip(lval.items, rval_type.items)):
388 #self.log('*** %s :: %s', lval_item, item_type)
389 if isinstance(lval_item, NameExpr):
390 if util.SkipAssignment(lval_item.name):
391 continue
392 self.current_local_vars.append((lval_item.name, item_type))
393
394 # self.a, self.b = foo()
395 if isinstance(lval_item, MemberExpr):
396 self._MaybeAddMember(lval_item, current_method_name,
397 at_global_scope)
398
399 super().oils_visit_assignment_stmt(o, lval, rval, current_method_name,
400 at_global_scope)
401
402 def oils_visit_for_stmt(self, o: 'mypy.nodes.ForStmt',
403 func_name: Optional[str]) -> None:
404 # TODO: this variable should be BLOCK scoped, not function scoped, like
405 # the tuple variables for i, x
406 index0_name: Optional[str] = None
407 if func_name == 'enumerate':
408 assert isinstance(o.index, TupleExpr), o.index
409 index0 = o.index.items[0]
410 assert isinstance(index0, NameExpr), index0
411 index0_name = index0.name # generate int i = 0; ; ++i
412
413 if index0_name:
414 # can't initialize two things in a for loop, so do it on a separate line
415 self.current_local_vars.append((index0_name, MYCPP_INT))
416
417 super().oils_visit_for_stmt(o, func_name)