-
-
Notifications
You must be signed in to change notification settings - Fork 145
/
cppgen_pass.py
2797 lines (2233 loc) · 89.9 KB
/
cppgen_pass.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
cppgen.py - AST pass to that prints C++ code
"""
import io
import json # for "C escaping"
import os
import sys
from typing import overload, Union, Optional, Any, Dict
from mypy.visitor import ExpressionVisitor, StatementVisitor
from mypy.types import (
Type, AnyType, NoneTyp, TupleType, Instance, Overloaded, CallableType,
UnionType, UninhabitedType, PartialType, TypeAliasType)
from mypy.nodes import (
Expression, Statement, Block, NameExpr, IndexExpr, MemberExpr, TupleExpr,
ExpressionStmt, AssignmentStmt, IfStmt, StrExpr, SliceExpr, FuncDef,
UnaryExpr, ComparisonExpr, CallExpr, IntExpr, ListExpr, DictExpr,
ListComprehension)
from mycpp import format_strings
from mycpp.crash import catch_errors
from mycpp.util import log
from typing import Tuple
T = None
class UnsupportedException(Exception):
pass
def _SkipAssignment(var_name):
"""Skip _ = log and unused = log"""
return var_name == '_' or var_name.startswith('unused')
def _GetCTypeForCast(type_expr):
if isinstance(type_expr, MemberExpr):
subtype_name = '%s::%s' % (type_expr.expr.name, type_expr.name)
elif isinstance(type_expr, IndexExpr):
# List[word_t] would be a problem.
# But worked around it in osh/word_parse.py
#subtype_name = 'List<word_t>'
raise AssertionError()
else:
subtype_name = type_expr.name
# Hack for now
if subtype_name != 'int':
subtype_name += '*'
return subtype_name
def _GetCastKind(module_path, subtype_name):
cast_kind = 'static_cast'
# Hack for the CastDummy in expr_to_ast.py
if 'expr_to_ast.py' in module_path:
for name in (
'sh_array_literal', 'command_sub', 'braced_var_sub',
'double_quoted', 'single_quoted',
# Another kind of hack, not because of CastDummy
'place_expr_t',
):
if name in subtype_name:
cast_kind = 'reinterpret_cast'
break
return cast_kind
def _GetContainsFunc(t):
contains_func = None
if isinstance(t, Instance):
type_name = t.type.fullname
if type_name == 'builtins.list':
contains_func = 'list_contains'
elif type_name == 'builtins.str':
contains_func = 'str_contains'
elif type_name == 'builtins.dict':
contains_func = 'dict_contains'
elif isinstance(t, UnionType):
# Special case for Optional[T] == Union[T, None]
if len(t.items) != 2:
raise NotImplementedError('Expected Optional, got %s' % t)
if not isinstance(t.items[1], NoneTyp):
raise NotImplementedError('Expected Optional, got %s' % t)
contains_func = _GetContainsFunc(t.items[0])
return contains_func # None checked later
def IsStr(t):
"""Helper to check if a type is a string."""
return isinstance(t, Instance) and t.type.fullname == 'builtins.str'
def _CheckConditionType(t):
"""
strings, lists, and dicts shouldn't be used in boolean contexts, because that
doesn't translate to C++.
"""
if isinstance(t, Instance):
type_name = t.type.fullname
if type_name == 'builtins.str':
return False
elif type_name == 'builtins.list':
return False
elif type_name == 'builtins.dict':
return False
elif isinstance(t, UnionType):
if (len(t.items) == 2 and
IsStr(t.items[0]) and isinstance(t.items[1], NoneTyp)):
return False # Optional[str]
return True
def CTypeIsManaged(c_type):
# type: (str) -> bool
"""For rooting and field masks."""
assert c_type != 'void'
# int, double, bool, scope_t enums, etc. are not managed
return c_type.endswith('*')
def get_c_type(t, param=False, local=False):
is_pointer = False
if isinstance(t, NoneTyp): # e.g. a function that doesn't return anything
return 'void'
elif isinstance(t, AnyType):
# Note: this usually results in another compile-time error. We should get
# rid of the 'Any' types.
c_type = 'void'
is_pointer = True
elif isinstance(t, PartialType):
# Note: bin/oil.py has some of these? Not sure why.
c_type = 'void'
is_pointer = True
# TODO: It seems better not to check for string equality, but that's what
# mypyc/genops.py does?
elif isinstance(t, Instance):
type_name = t.type.fullname
if type_name == 'builtins.int':
c_type = 'int'
elif type_name == 'builtins.float':
c_type = 'double'
elif type_name == 'builtins.bool':
c_type = 'bool'
elif type_name == 'builtins.str':
c_type = 'Str'
is_pointer = True
elif type_name == 'builtins.list':
assert len(t.args) == 1, t.args
type_param = t.args[0]
inner_c_type = get_c_type(type_param)
c_type = 'List<%s>' % inner_c_type
is_pointer = True
elif type_name == 'builtins.dict':
params = []
for type_param in t.args:
params.append(get_c_type(type_param))
c_type = 'Dict<%s>' % ', '.join(params)
is_pointer = True
elif type_name == 'typing.IO':
c_type = 'void'
is_pointer = True
else:
# note: fullname => 'parse.Lexer'; name => 'Lexer'
base_class_names = [b.type.fullname for b in t.type.bases]
#log('** base_class_names %s', base_class_names)
# Check base class for pybase.SimpleObj so we can output
# expr_asdl::tok_t instead of expr_asdl::tok_t*. That is a enum, while
# expr_t is a "regular base class".
# NOTE: Could we avoid the typedef? If it's SimpleObj, just generate
# tok_e instead?
if 'asdl.pybase.SimpleObj' not in base_class_names:
is_pointer = True
parts = t.type.fullname.split('.')
c_type = '%s::%s' % (parts[-2], parts[-1])
elif isinstance(t, UninhabitedType):
# UninhabitedType has a NoReturn flag
c_type = 'void'
elif isinstance(t, TupleType):
inner_c_types = []
for inner_type in t.items:
inner_c_types.append(get_c_type(inner_type))
c_type = 'Tuple%d<%s>' % (len(t.items), ', '.join(inner_c_types))
is_pointer = True
elif isinstance(t, UnionType):
# Special case for Optional[T] == Union[T, None]
if len(t.items) != 2:
raise NotImplementedError('Expected Optional, got %s' % t)
if not isinstance(t.items[1], NoneTyp):
raise NotImplementedError('Expected Optional, got %s' % t)
c_type = get_c_type(t.items[0])
elif isinstance(t, CallableType):
# Function types are expanded
# Callable[[Parser, Token, int], arith_expr_t] =>
# arith_expr_t* (*f)(Parser*, Token*, int) nud;
ret_type = get_c_type(t.ret_type)
arg_types = [get_c_type(typ) for typ in t.arg_types]
c_type = '%s (*f)(%s)' % (ret_type, ', '.join(arg_types))
elif isinstance(t, TypeAliasType):
if 0:
log('***')
log('%s', t)
log('%s', dir(t))
log('%s', t.alias)
log('%s', dir(t.alias))
log('%s', t.alias.target)
log('***')
return get_c_type(t.alias.target)
else:
raise NotImplementedError('MyPy type: %s %s' % (type(t), t))
if is_pointer:
if param or local:
c_type = 'Local<%s>' % c_type
else:
c_type += '*'
return c_type
def get_c_return_type(t) -> Tuple[str, bool]:
"""
Returns a C string, and whether the tuple-by-value optimization was applied
"""
c_ret_type = get_c_type(t)
# Optimization: Return tupels BY VALUE
if isinstance(t, TupleType):
assert c_ret_type.endswith('*')
return c_ret_type[:-1], True
else:
return c_ret_type, False
def PythonStringLiteral(s: str) -> str:
"""
Returns a properly quoted string.
"""
# MyPy does bad escaping. Decode and push through json to get something
# workable in C++.
return json.dumps(format_strings.DecodeMyPyString(s))
class Generate(ExpressionVisitor[T], StatementVisitor[None]):
def __init__(self, types: Dict[Expression, Type], const_lookup, f,
virtual=None, local_vars=None, fmt_ids=None,
field_gc=None,
decl=False, forward_decl=False, ret_val_rooting=False):
self.types = types
self.const_lookup = const_lookup
self.f = f
self.virtual = virtual
# local_vars: FuncDef node -> list of type, var
# This is different from member_vars because we collect it in the 'decl'
# phase. But then write it in the definition phase.
self.local_vars = local_vars
self.fmt_ids = fmt_ids
self.field_gc = field_gc
self.fmt_funcs = io.StringIO()
self.decl = decl
self.forward_decl = forward_decl
self.ret_val_rooting = ret_val_rooting
self.unique_id = 0
self.indent = 0
self.local_var_list = [] # Collected at assignment
self.prepend_to_block = None # For writing vars after {
self.current_func_node = None
# This is cleared when we start visiting a class. Then we visit all the
# methods, and accumulate the types of everything that looks like
# self.foo = 1. Then we write C++ class member declarations at the end
# of the class.
# This is all in the 'decl' phase.
self.member_vars = {} # type: Dict[str, Type]
self.current_class_name = None # for prototypes
self.current_method_name = None
self.imported_names = set() # For module::Foo() vs. self.foo
def log(self, msg, *args):
ind_str = self.indent * ' '
log(ind_str + msg, *args)
def write(self, msg, *args):
if self.decl or self.forward_decl:
return
if args:
msg = msg % args
self.f.write(msg)
# Write respecting indent
def write_ind(self, msg, *args):
if self.decl or self.forward_decl:
return
ind_str = self.indent * ' '
if args:
msg = msg % args
self.f.write(ind_str + msg)
# A little hack to reuse this pass for declarations too
def decl_write(self, msg, *args):
# TODO:
# self.header_f ?
# Just one file for all exported?
if args:
msg = msg % args
self.f.write(msg)
def decl_write_ind(self, msg, *args):
ind_str = self.indent * ' '
if args:
msg = msg % args
self.f.write(ind_str + msg)
#
# COPIED from IRBuilder
#
@overload
def accept(self, node: Expression) -> T: ...
@overload
def accept(self, node: Statement) -> None: ...
def accept(self, node: Union[Statement, Expression]) -> Optional[T]:
with catch_errors(self.module_path, node.line):
if isinstance(node, Expression):
try:
res = node.accept(self)
#res = self.coerce(res, self.node_type(node), node.line)
# If we hit an error during compilation, we want to
# keep trying, so we can produce more error
# messages. Generate a temp of the right type to keep
# from causing more downstream trouble.
except UnsupportedException:
res = self.alloc_temp(self.node_type(node))
return res
else:
try:
node.accept(self)
except UnsupportedException:
pass
return None
# Not in superclasses:
def visit_mypy_file(self, o: 'mypy.nodes.MypyFile') -> T:
# Skip some stdlib stuff. A lot of it is brought in by 'import
# typing'.
if o.fullname in (
'__future__', 'sys', 'types', 'typing', 'abc', '_ast', 'ast',
'_weakrefset', 'collections', 'cStringIO', 're', 'builtins'):
# These module are special; their contents are currently all
# built-in primitives.
return
#self.log('')
#self.log('mypyfile %s', o.fullname)
mod_parts = o.fullname.split('.')
if self.forward_decl:
comment = 'forward declare'
elif self.decl:
comment = 'declare'
else:
comment = 'define'
self.decl_write_ind('namespace %s { // %s\n', mod_parts[-1], comment)
self.decl_write('\n')
self.module_path = o.path
if self.forward_decl:
self.indent += 1
#self.log('defs %s', o.defs)
for node in o.defs:
# skip module docstring
if (isinstance(node, ExpressionStmt) and
isinstance(node.expr, StrExpr)):
continue
self.accept(node)
# Write fmtX() functions inside the namespace.
if self.decl:
self.decl_write('\n')
self.decl_write(self.fmt_funcs.getvalue())
self.fmt_funcs = io.StringIO() # clear it for the next file
if self.forward_decl:
self.indent -= 1
self.decl_write('\n')
self.decl_write_ind(
'} // %s namespace %s\n', comment, mod_parts[-1])
self.decl_write('\n')
# NOTE: Copied ExpressionVisitor and StatementVisitor nodes below!
# LITERALS
def visit_int_expr(self, o: 'mypy.nodes.IntExpr') -> T:
self.write(str(o.value))
def visit_str_expr(self, o: 'mypy.nodes.StrExpr') -> T:
self.write(self.const_lookup[o])
def visit_bytes_expr(self, o: 'mypy.nodes.BytesExpr') -> T:
pass
def visit_unicode_expr(self, o: 'mypy.nodes.UnicodeExpr') -> T:
pass
def visit_float_expr(self, o: 'mypy.nodes.FloatExpr') -> T:
# e.g. for arg.t > 0.0
self.write(str(o.value))
def visit_complex_expr(self, o: 'mypy.nodes.ComplexExpr') -> T:
pass
# Expressions
def visit_ellipsis(self, o: 'mypy.nodes.EllipsisExpr') -> T:
pass
def visit_star_expr(self, o: 'mypy.nodes.StarExpr') -> T:
pass
def visit_name_expr(self, o: 'mypy.nodes.NameExpr') -> T:
if o.name == 'None':
self.write('nullptr')
return
if o.name == 'True':
self.write('true')
return
if o.name == 'False':
self.write('false')
return
if o.name == 'self':
self.write('this')
return
self.write(o.name)
def visit_member_expr(self, o: 'mypy.nodes.MemberExpr') -> T:
t = self.types[o]
if o.expr:
#log('member o = %s', o)
# This is an approximate hack that assumes that locals don't shadow
# imported names. Might be a problem with names like 'word'?
if (isinstance(o.expr, NameExpr) and (
o.expr.name in self.imported_names or
o.expr.name in ('mylib', 'libc', 'posix', 'fcntl_',
'time_', 'termios', 'signal_') or
o.name == '__init__'
)):
op = '::'
else:
op = '->' # Everything is a pointer
self.accept(o.expr)
self.write(op)
if o.name == 'errno':
# Avoid conflict with errno macro
# e->errno turns into e->errno_
self.write('errno_')
else:
self.write('%s', o.name)
def visit_yield_from_expr(self, o: 'mypy.nodes.YieldFromExpr') -> T:
pass
def visit_yield_expr(self, o: 'mypy.nodes.YieldExpr') -> T:
pass
def _WriteArgList(self, o):
self.write('(')
# So we can get better AssertionError messages in Python
if o.callee.name != 'AssertionError':
for i, arg in enumerate(o.args):
if i != 0:
self.write(', ')
self.accept(arg)
self.write(')')
def _IsInstantiation(self, o):
callee_name = o.callee.name
callee_type = self.types[o.callee]
# e.g. int() takes str, float, etc. It doesn't matter for translation.
if isinstance(callee_type, Overloaded):
if 0:
for item in callee_type.items():
self.log('item: %s', item)
if isinstance(callee_type, CallableType):
# If the function name is the same as the return type, then add
# 'Alloc<>'. f = Foo() => f = Alloc<Foo>().
ret_type = callee_type.ret_type
# str(i) doesn't need new. For now it's a free function.
# TODO: rename int_to_str? or Str::from_int()?
if (callee_name not in ('str', 'bool', 'float') and
isinstance(ret_type, Instance)):
ret_type_name = ret_type.type.name
# HACK: Const is the callee; expr__Const is the return type
if (ret_type_name == callee_name or
ret_type_name.endswith('__' + callee_name)):
return True
return False
def visit_call_expr(self, o: 'mypy.nodes.CallExpr') -> T:
if o.callee.name == 'isinstance':
assert len(o.args) == 2, args
obj = o.args[0]
typ = o.args[1]
if 0:
log('obj %s', obj)
log('typ %s', typ)
self.accept(obj)
self.write('->tag_() == ')
assert isinstance(typ, NameExpr), typ
# source__CFlag -> source_e::CFlag
tag = typ.name.replace('__', '_e::')
self.write(tag)
return
# return cast(sh_array_literal, tok)
# -> return static_cast<sh_array_literal*>(tok)
# TODO: Consolidate this with AssignmentExpr logic.
if o.callee.name == 'cast':
call = o
type_expr = call.args[0]
subtype_name = _GetCTypeForCast(type_expr)
cast_kind = _GetCastKind(self.module_path, subtype_name)
self.write('%s<%s>(', cast_kind, subtype_name)
self.accept(call.args[1]) # variable being casted
self.write(')')
return
# Translate printf-style vargs for some functions, e.g.
#
# p_die('foo %s', x, token=t)
# =>
# p_die(fmt1(x), t)
#
# And then we need 3 or 4 version of p_die()? For the rest of the
# tokens.
# Others:
# - debug_f.log()?
# Maybe I should rename them all printf()
# or fprintf()? Except p_die() has extra args
if o.callee.name == 'log' or o.callee.name == 'stderr_line':
args = o.args
if len(args) == 1: # log(CONST)
self.write('println_stderr(')
self.accept(args[0])
self.write(')')
return
rest = args[1:]
quoted_fmt = PythonStringLiteral(args[0].value)
# DEFINITION PASS: Write the call
self.write('println_stderr(StrFormat(%s, ' % quoted_fmt)
for i, arg in enumerate(rest):
if i != 0:
self.write(', ')
self.accept(arg)
self.write('))')
return
# TODO: Consolidate X_die() and log()? It has an extra arg though.
if o.callee.name in ('p_die', 'e_die', 'e_strict', 'e_usage'):
args = o.args
if len(args) == 1: # log(CONST)
self.write('%s(' % o.callee.name)
self.accept(args[0])
self.write(')')
return
has_keyword_arg = o.arg_names[-1] is not None
if has_keyword_arg:
rest = args[1:-1]
else:
rest = args[1:]
# If there are no arguments, it must look like
# Same with
# e_die('constant string')
if not rest:
pass
self.write('%s(StrFormat(' % o.callee.name)
if isinstance(args[0], StrExpr):
self.write(PythonStringLiteral(args[0].value))
else:
self.accept(args[0])
# Should p_die() be in mylib?
# DEFINITION PASS: Write the call
for i, arg in enumerate(rest):
self.write(', ')
self.accept(arg)
if has_keyword_arg:
self.write('), ')
self.accept(args[-1])
else:
self.write(')')
self.write(')')
return
callee_name = o.callee.name
if self._IsInstantiation(o):
self.write('Alloc<')
self.accept(o.callee)
self.write('>')
self._WriteArgList(o)
return
# Namespace.
if callee_name == 'int': # int('foo') in Python conflicts with keyword
self.write('to_int')
elif callee_name == 'float':
self.write('to_float')
elif callee_name == 'bool':
self.write('to_bool')
else:
self.accept(o.callee) # could be f() or obj.method()
self._WriteArgList(o)
# TODO: look at keyword arguments!
#self.log(' arg_kinds %s', o.arg_kinds)
#self.log(' arg_names %s', o.arg_names)
def visit_op_expr(self, o: 'mypy.nodes.OpExpr') -> T:
c_op = o.op
# a + b when a and b are strings. (Can't use operator overloading
# because they're pointers.)
left_type = self.types[o.left]
right_type = self.types[o.right]
# NOTE: Need get_c_type to handle Optional[Str*] in ASDL schemas.
# Could tighten it up later.
left_ctype = get_c_type(left_type)
right_ctype = get_c_type(right_type)
#if c_op == '+':
if 0:
self.log('*** %r', c_op)
self.log('%s', o.left)
self.log('%s', o.right)
#self.log('t0 %r', t0.type.fullname)
#self.log('t1 %r', t1.type.fullname)
self.log('left_ctype %r', left_ctype)
self.log('right_ctype %r', right_ctype)
self.log('')
if left_ctype == right_ctype == 'Str*' and c_op == '+':
self.write('str_concat(')
self.accept(o.left)
self.write(', ')
self.accept(o.right)
self.write(')')
return
if left_ctype == 'Str*' and right_ctype == 'int' and c_op == '*':
self.write('str_repeat(')
self.accept(o.left)
self.write(', ')
self.accept(o.right)
self.write(')')
return
# [None] * 3 => list_repeat(None, 3)
if left_ctype.startswith('List<') and right_ctype == 'int' and c_op == '*':
self.write('list_repeat(')
self.accept(o.left.items[0])
self.write(', ')
self.accept(o.right)
self.write(')')
return
# RHS can be primitive or tuple
if left_ctype == 'Str*' and c_op == '%':
self.write('StrFormat(')
if isinstance(o.left, StrExpr):
self.write(PythonStringLiteral(o.left.value))
else:
self.accept(o.left)
#log('right_type %s', right_type)
if isinstance(right_type, Instance):
fmt_types = [right_type]
elif isinstance(right_type, TupleType):
fmt_types = right_type.items
# Handle Optional[str]
elif (isinstance(right_type, UnionType) and
len(right_type.items) == 2 and
isinstance(right_type.items[1], NoneTyp)):
fmt_types = [right_type.items[0]]
else:
raise AssertionError(right_type)
# In the definition pass, write the call site.
if isinstance(right_type, TupleType):
for i, item in enumerate(o.right.items):
self.write(', ')
self.accept(item)
else: # '[%s]' % x
self.write(', ')
self.accept(o.right)
self.write(')')
return
# These parens are sometimes extra, but sometimes required. Example:
#
# if ((a and (false or true))) { # right
# vs.
# if (a and false or true)) { # wrong
self.write('(')
self.accept(o.left)
self.write(' %s ', c_op)
self.accept(o.right)
self.write(')')
def visit_comparison_expr(self, o: 'mypy.nodes.ComparisonExpr') -> T:
# Make sure it's binary
assert len(o.operators) == 1, o.operators
assert len(o.operands) == 2, o.operands
operator = o.operators[0]
left = o.operands[0]
right = o.operands[1]
# Assume is and is not are for None / nullptr comparison.
if operator == 'is': # foo is None => foo == nullptr
self.accept(o.operands[0])
self.write(' == ')
self.accept(o.operands[1])
return
if operator == 'is not': # foo is not None => foo != nullptr
self.accept(o.operands[0])
self.write(' != ')
self.accept(o.operands[1])
return
# TODO: Change Optional[T] to T for our purposes?
t0 = self.types[left]
t1 = self.types[right]
# 0: not a special case
# 1: str
# 2: Optional[str] which is Union[str, None]
left_type = 0 # not a special case
right_type = 0 # not a special case
if IsStr(t0):
left_type = 1
elif (isinstance(t0, UnionType) and len(t0.items) == 2 and
IsStr(t0.items[0]) and isinstance(t0.items[1], NoneTyp)):
left_type = 2
if IsStr(t1):
right_type = 1
elif (isinstance(t1, UnionType) and len(t1.items) == 2 and
IsStr(t1.items[0]) and isinstance(t1.items[1], NoneTyp)):
right_type = 2
#self.log('left_type %s right_type %s', left_type, right_type)
if left_type > 0 and right_type > 0 and operator in ('==', '!='):
if operator == '!=':
self.write('!(')
# NOTE: This could also be str_equals(left, right)? Does it make a
# difference?
if left_type > 1 or right_type > 1:
self.write('maybe_str_equals(')
else:
self.write('str_equals(')
self.accept(left)
self.write(', ')
self.accept(right)
self.write(')')
if operator == '!=':
self.write(')')
return
# Note: we could get rid of this altogether and rely on C++ function
# overloading. But somehow I like it more explicit, closer to C (even
# though we use templates).
contains_func = _GetContainsFunc(t1)
if operator == 'in':
if isinstance(right, TupleExpr):
left_type = self.types[left]
equals_func = None
if IsStr(left_type):
equals_func = 'str_equals'
elif (isinstance(left_type, UnionType) and len(left_type.items) == 2 and
IsStr(left_type.items[0]) and isinstance(left_type.items[1], NoneTyp)):
equals_func = 'maybe_str_equals'
# x in (1, 2, 3) => (x == 1 || x == 2 || x == 3)
self.write('(')
for i, item in enumerate(right.items):
if i != 0:
self.write(' || ')
if equals_func:
self.write('%s(' % equals_func)
self.accept(left)
self.write(', ')
self.accept(item)
self.write(')')
else:
self.accept(left)
self.write(' == ')
self.accept(item)
self.write(')')
return
assert contains_func, "RHS of 'in' has type %r" % t1
# x in mylist => list_contains(mylist, x)
self.write('%s(', contains_func)
self.accept(right)
self.write(', ')
self.accept(left)
self.write(')')
return
if operator == 'not in':
if isinstance(right, TupleExpr):
# x not in (1, 2, 3) => (x != 1 && x != 2 && x != 3)
self.write('(')
for i, item in enumerate(right.items):
if i != 0:
self.write(' && ')
self.accept(left)
self.write(' != ')
self.accept(item)
self.write(')')
return
assert contains_func, t1
# x not in mylist => !list_contains(mylist, x)
self.write('!%s(', contains_func)
self.accept(right)
self.write(', ')
self.accept(left)
self.write(')')
return
# Default case
self.accept(o.operands[0])
self.write(' %s ', o.operators[0])
self.accept(o.operands[1])
def visit_cast_expr(self, o: 'mypy.nodes.CastExpr') -> T:
pass
def visit_reveal_expr(self, o: 'mypy.nodes.RevealExpr') -> T:
pass
def visit_super_expr(self, o: 'mypy.nodes.SuperExpr') -> T:
pass
def visit_assignment_expr(self, o: 'mypy.nodes.AssignmentExpr') -> T:
pass
def visit_unary_expr(self, o: 'mypy.nodes.UnaryExpr') -> T:
# e.g. a[-1] or 'not x'
if o.op == 'not':
op_str = '!'
else:
op_str = o.op
self.write(op_str)
self.accept(o.expr)
def _WriteListElements(self, o, sep=', '):
# sep may be 'COMMA' for a macro
self.write('{')
for i, item in enumerate(o.items):
if i != 0:
self.write(sep)
self.accept(item)
self.write('}')
def visit_list_expr(self, o: 'mypy.nodes.ListExpr') -> T:
list_type = self.types[o]
#self.log('**** list_type = %s', list_type)
c_type = get_c_type(list_type)
item_type = list_type.args[0] # int for List[int]
item_c_type = get_c_type(item_type)
assert c_type.endswith('*'), c_type
c_type = c_type[:-1] # HACK TO CLEAN UP
if len(o.items) == 0:
self.write('Alloc<%s>()' % c_type)
else:
self.write('NewList<%s>(std::initializer_list<%s>' %
(item_c_type, item_c_type))
self._WriteListElements(o)
self.write(')')
def _WriteDictElements(self, o, key_type, val_type):
# Ran into a limit of C++ type inference. Somehow you need
# std::initializer_list{} here, not just {}
self.write('std::initializer_list<%s>{' % get_c_type(key_type))
for i, item in enumerate(o.items):
pass
self.write('}, ')
self.write('std::initializer_list<%s>{' % get_c_type(val_type))
# TODO: values