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

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