-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathparse.py
3894 lines (3531 loc) · 217 KB
/
parse.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
try:
from python_to_11l.tokenizer import Token
import python_to_11l.tokenizer as tokenizer
except ImportError:
from tokenizer import Token
import tokenizer
from typing import List, Tuple, Dict, Callable
from enum import IntEnum
import os, re, eldf
class Scope:
parent : 'Scope'
class Var:
type : str
node : 'ASTNode'
def __init__(self, type, node):
assert(type is not None)
self.type = type
self.node = node
def serialize_to_dict(self):
node = None
if type(self.node) == ASTFunctionDefinition:
node = self.node.serialize_to_dict()
return {'type': self.type, 'node': node}
def deserialize_from_dict(self, d):
if d['node'] is not None:
self.node = ASTFunctionDefinition()
self.node.deserialize_from_dict(d['node'])
vars : Dict[str, Var]
nonlocals_copy : set
nonlocals : set
globals : set
is_function : bool
is_lambda_or_for = False
is_class = False
def __init__(self, func_args):
self.parent = None
if func_args is not None:
self.is_function = True
self.vars = dict(map(lambda x: (x[0], Scope.Var(x[1], None)), func_args))
else:
self.is_function = False
self.vars = {}
self.nonlocals_copy = set()
self.nonlocals = set()
self.globals = set()
def serialize_to_dict(self, imported_modules):
ids_dict = {'Imported modules': imported_modules}
for name, id in self.vars.items():
if name not in python_types_to_11l and not id.type.startswith('('): # )
ids_dict[name] = id.serialize_to_dict()
return ids_dict
def deserialize_from_dict(self, d):
for name, id_dict in d.items():
if name != 'Imported modules':
id = Scope.Var(id_dict['type'], None)
id.deserialize_from_dict(id_dict)
self.vars[name] = id
def add_var(self, name, error_if_already_defined = False, type = '', err_token = None, node = None):
s = self
while True:
if name in s.nonlocals_copy or name in s.nonlocals or name in s.globals:
return False
if s.is_function:
break
s = s.parent
if s is None:
break
if not (name in self.vars):
s = self
while True:
if name in s.vars:
return False
if s.is_function or s.is_class:
break
s = s.parent
if s is None:
break
self.vars[name] = Scope.Var(type, node)
return True
elif error_if_already_defined:
if name in ('move', 'ref') and self.parent is None:
return False
raise Error('redefinition of already defined variable/function is not allowed', err_token if err_token is not None else token)
if self.vars[name].type == '(Function)':
raise Error('redefinition of built-in function is not allowed', err_token if err_token is not None else token)
return False
def find_and_get_prefix(self, name, token):
if name == 'self':
return ''
if name == 'sum':
return ''
s = self
while True:
if name in s.nonlocals_copy:
return '@='
if name in s.nonlocals:
return '@'
if name in s.globals:
return ':'
if s.is_function and not s.is_lambda_or_for:
break
s = s.parent
if s is None:
break
capture_level = 0
s = self
while True:
if name in s.vars:
if s.parent is None: # variable is declared in the global scope
if s.vars[name].type == '(Module)':
return ':::'
return ':' if capture_level > 0 else ''
else:
return capture_level*'@'
if s.is_function:
capture_level += 1
s = s.parent
if s is None:
if name in ('id', 'next'):
return ''
raise Error('undefined identifier', token)
def find(self, name):
s = self
while True:
id = s.vars.get(name)
if id is not None:
return id
s = s.parent
if s is None:
return None
def var_type(self, name):
id = self.find(name)
return id.type if id is not None else None
scope : Scope
class Module:
scope : Scope
def __init__(self, scope):
self.scope = scope
modules : Dict[str, Module] = {}
class SymbolBase:
id : str
lbp : int
nud_bp : int
led_bp : int
nud : Callable[['SymbolNode'], 'SymbolNode']
led : Callable[['SymbolNode', 'SymbolNode'], 'SymbolNode']
def set_nud_bp(self, nud_bp, nud):
self.nud_bp = nud_bp
self.nud = nud
def set_led_bp(self, led_bp, led):
self.led_bp = led_bp
self.led = led
def __init__(self):
def nud(s): raise Error('unknown unary operator', s.token)
self.nud = nud
def led(s, l): raise Error('unknown binary operator', s.token)
self.led = led
class SymbolNode:
token : Token
symbol : SymbolBase = None
children : List['SymbolNode']# = []
parent : 'SymbolNode' = None
ast_parent : 'ASTNode'
function_call = False
iterable_unpacking = False
tuple = False
is_list = False
is_set = False
def is_dict(self): return self.symbol.id == '{' and not self.is_set # }
slicing = False
is_not = False
has_format_specifiers = False
skip_find_and_get_prefix = False
scope_prefix : str = ''
scope : Scope
token_str_override : str
def __init__(self, token, token_str_override = None):
self.token = token
self.children = []
self.scope = scope
self.token_str_override = token_str_override
def var_type(self):
if self.is_parentheses():
return self.children[0].var_type()
if self.symbol.id == '*' and self.children[0].var_type() == 'List':
return 'List'
if self.symbol.id == '+' and len(self.children) == 2 and (self.children[0].var_type() == 'List' or self.children[1].var_type() == 'List'):
return 'List'
if self.is_list:
return 'List'
#if self.symbol.id == '[' and not self.is_list and self.children[0].var_type() == 'str': # ]
if self.symbol.id == '[' and self.children[0].var_type() in ('str', 'List[str]'): # ]
return 'str'
if self.slicing and self.children[0].var_type() == 'List':
return 'List'
if self.symbol.id == '*' and (self.children[0].var_type() == 'str' or self.children[1].var_type() == 'str'):
return 'str'
if self.symbol.id == '%' and self.children[0].var_type() == 'str':
return 'str'
if self.symbol.id == '+' and len(self.children) == 2 and (self.children[0].var_type() == 'str' or self.children[1].var_type() == 'str'):
return 'str'
if self.token.category in (Token.Category.STRING_LITERAL, Token.Category.FSTRING):
return 'str'
if self.symbol.id == '.':
if self.children[0].token_str() == 'os' and self.children[1].token_str() == 'pathsep':
return 'str'
return None
if self.symbol.id == 'if':
t0 = self.children[0].var_type()
if t0 is not None:
return t0
return self.children[2].var_type()
if self.function_call:
if self.children[0].token_str() in ('str', 'chr') \
or (self.children[0].symbol.id == '.' and self.children[0].children[1].token_str() == 'rstrip'): # for `annotated += indent + (...).rstrip(' ') + "\n"`
return 'str'
if self.children[0].token_str() == 'list':
return 'List'
id = self.scope.find(self.children[0].token_str())
if id is not None:
if isinstance(id.node, ASTTypeHint) and id.node.type == 'Callable' and id.node.type_args[-1] == 'str':
return 'str'
if isinstance(id.node, ASTFunctionDefinition) and id.node.function_return_type in ('str', 'Char'):
return 'str'
if self.token.category == Token.Category.NAME:
return self.scope.var_type(self.token_str())
return None
def append_child(self, child):
child.parent = self
self.children.append(child)
def leftmost(self):
if self.token.category in (Token.Category.NUMERIC_LITERAL, Token.Category.STRING_LITERAL, Token.Category.NAME, Token.Category.CONSTANT) or self.symbol.id == 'lambda':
return self.token.start
if self.symbol.id == '(': # )
if self.function_call:
return self.children[0].token.start #self.children[0].leftmost()
else:
return self.token.start
elif self.symbol.id == '[': # ]
if self.is_list:
return self.token.start
else:
return self.children[0].token.start
if len(self.children) in (2, 3):
return self.children[0].leftmost()
return self.token.start
def rightmost(self):
if self.token.category in (Token.Category.NUMERIC_LITERAL, Token.Category.STRING_LITERAL, Token.Category.NAME, Token.Category.CONSTANT):
return self.token.end
if self.symbol.id in '([{': # }])
if len(self.children) == 0:
return self.token.end + 1
return (self.children[-1] or self.children[-2]).rightmost() + 1
return self.children[-1].rightmost()
def left_to_right_token(self):
return Token(self.leftmost(), self.rightmost(), Token.Category.NAME)
def token_str(self):
return self.token.value(source) if not self.token_str_override else self.token_str_override
def is_parentheses(self):
return self.symbol.id == '(' and not self.tuple and not self.function_call # )
def str_format(self):
fmtstr = self.children[0].children[0].to_str()
nfmtstr = ''
format_args = ''
field_index = 0
i = 0
while i < len(fmtstr):
if fmtstr[i] == '#' and (fmtstr[i+1:i+2] in ('#', '{', '.', '<') or fmtstr[i+1:i+2].isdigit()): # }
nfmtstr += '##'
i += 1
continue
if fmtstr[i] == '{':
nfmtstr += '#'
i += 1
field_name = ''
while fmtstr[i] not in ('}', ':'):
field_name += fmtstr[i]
i += 1
if field_name == '':
field_name = str(field_index)
field_index += 1
if format_args != '':
format_args += ', '
if field_name.isdigit():
format_arg = self.children[1 + int(field_name)*2].to_str()
else:
for j in range(1, len(self.children), 2): # `i` can not be used here :():
if self.children[j+1] is not None:
if self.children[j].token_str() == field_name:
format_arg = self.children[j+1].to_str()
break
else:
raise Error('argument `' + field_name + '` is not found', self.left_to_right_token())
if fmtstr[i] == ':':
before_period = 0
after_period = 6
was_dot = False
i += 1
if fmtstr[i:i+1] == '<':
nfmtstr += '<'
i += 1
elif fmtstr[i:i+1] == '>':
i += 1
if fmtstr[i:i+1] == '0' and fmtstr[i+1:i+2].isdigit(): # zero padding
nfmtstr += '0'
i += 1
while i < len(fmtstr) and fmtstr[i].isdigit():
before_period = before_period*10 + ord(fmtstr[i]) - ord('0')
i += 1
if fmtstr[i:i+1] == '.':
was_dot = True
i += 1
after_period = 0
while i < len(fmtstr) and fmtstr[i].isdigit():
after_period = after_period*10 + ord(fmtstr[i]) - ord('0')
i += 1
if fmtstr[i:i+1] == 'f':
if before_period != 0:
b = before_period
if after_period != 0:
b -= after_period + 1
if b > 1:
nfmtstr += str(b)
nfmtstr += '.' + str(after_period)
i += 1
else:
if was_dot:
tpos = self.children[0].children[0].token.start + i
raise Error("floating point numbers without 'f' in format specifier are not supported", Token(tpos, tpos, Token.Category.STRING_LITERAL))
if before_period != 0:
nfmtstr += str(before_period)
else:
nfmtstr += '.'
if fmtstr[i:i+1] == 'X':
format_arg = 'hex(' + format_arg + ')'
i += 1 # {{
if fmtstr[i] != '}':
tpos = self.children[0].children[0].token.start + i
raise Error('expected `}`', Token(tpos, tpos, Token.Category.STRING_LITERAL))
else:
nfmtstr += '.'
format_args += format_arg
i += 1
continue
nfmtstr += fmtstr[i]
i += 1
return nfmtstr + '.format(' + format_args + ')'
def struct_unpack(self):
assert(self.children[1].token.category == Token.Category.STRING_LITERAL)
big_endian = False
format = self.children[1].token_str()[1:-1]
if format.startswith(('<', '>')):
if format[0] == '>':
big_endian = True
format = format[1:]
assert(len(format) == 1)
(ty, sz) = {'i':('Int32', 4), 'I':('UInt32', 4), 'h':('Int16', 2), 'H':('UInt16', 2), 'b':('Int8', 1), 'B':('Byte', 1)}[format]
res = 'Int(' + ty + '(bytes' + '_be'*big_endian + "' " + self.children[3].to_str()
if self.children[0].children[1].token_str() == 'unpack_from':
res += '[' + self.children[5].to_str() + ' .+ ' + str(sz) + ']'
return res + '))'
def to_str(self, indent = 0):
# r = ''
# prev_token_end = self.children[0].token.start
# for c in self.children:
# r += source[prev_token_end:c.token.start]
# if c.token.value(source) != 'self': # hack for a while
# r += c.token.value(source)
# prev_token_end = c.token.end
# return r
if self.token.category == Token.Category.NAME:
if self.scope_prefix == ':' and ((self.parent and self.parent.function_call and self is self.parent.children[0]) or (self.token_str()[0].isupper() and self.token_str() != self.token_str().upper()) or self.token_str() in python_types_to_11l): # global functions and types do not require prefix `:` because global functions and types are ok, but global variables are not so good and they should be marked with `:`
return self.token_str()
if self.token_str() == 'self' and (self.parent is None or (self.parent.symbol.id != '.' and self.parent.symbol.id != 'lambda')):
parent = self
while parent.parent is not None:
parent = parent.parent
ast_parent = parent.ast_parent
while ast_parent is not None:
if isinstance(ast_parent, ASTFunctionDefinition):
if len(ast_parent.function_arguments) and ast_parent.function_arguments[0][0] == 'self' and isinstance(ast_parent.parent, ASTClassDefinition):
return '(.)'
break
ast_parent = ast_parent.parent
return self.scope_prefix + self.token_str()
if self.token.category == Token.Category.NUMERIC_LITERAL:
n = self.token.value(source)
i = 0
# if n[0] in '-+':
# sign = n[0]
# i = 1
# else:
# sign = ''
sign = ''
is_hex = n[i:i+1] == '0' and n[i+1:i+2] in ('x', 'X')
is_oct = n[i:i+1] == '0' and n[i+1:i+2] in ('o', 'O')
is_bin = n[i:i+1] == '0' and n[i+1:i+2] in ('b', 'B')
if is_hex or is_oct or is_bin:
i += 2
if is_hex:
n = n[i:].replace('_', '').upper()
if len(n) <= 2: # ultrashort hexadecimal number
n = '0'*(2-len(n)) + n
return n[:1] + "'" + n[1:]
elif len(n) <= 4: # short hexadecimal number
n = '0'*(4-len(n)) + n
return n[:2] + "'" + n[2:]
else:
number_with_separators = ''
j = len(n)
while j > 4:
number_with_separators = "'" + n[j-4:j] + number_with_separators
j -= 4
return sign + '0'*(4-j) + n[0:j] + number_with_separators
if n[-1] in 'jJ':
n = n[:-1] + 'i'
return sign + n[i:].replace('_', "'") + ('o' if is_oct else 'b' if is_bin else '')
if self.token.category == Token.Category.STRING_LITERAL:
def balance_pq_string(s):
min_nesting_level = 0
nesting_level = 0
for ch in s:
if ch == "‘":
nesting_level += 1
elif ch == "’":
nesting_level -= 1
min_nesting_level = min(min_nesting_level, nesting_level)
nesting_level -= min_nesting_level
return "'"*-min_nesting_level + "‘"*-min_nesting_level + "‘" + s + "’" + "’"*nesting_level + "'"*nesting_level
s = self.token.value(source)
if s[0] in 'rR':
l = 3 if s[1:4] in ('"""', "'''") else 1
return balance_pq_string(s[1+l:-l])
elif s[0] in 'bB':
if len(s) == 4 or (len(s) == 5 and s[2] == "\\"):
return s[1:] + '.code'
elif '\\' in s:
return 'Bytes("' + s[2:-1] + '")'
else:
return 'Bytes(‘' + s[2:-1] + '’)'
else:
l = 3 if s[0:3] in ('"""', "'''") else 1
if l == 3 and s[3:5] == "\\\n" and not '\\' in s[4:]:
return r'\/‘' + s[4:-3] + '’'
if '\\' in s or ('‘' in s and not '’' in s) or (not '‘' in s and '’' in s):
if s == R'"\\"' or s == R"'\\'":
return R'‘\’'
s = s.replace("\n", "\\n\\\n").replace("\\\\n\\\n", "\\\n")
if s[0] == '"':
return s if l == 1 else '"' + s[3:-3].replace('"', R'\"') + '"'
else:
return '"' + s[l:-l].replace('"', R'\"').replace(R"\'", "'") + '"'
else:
return balance_pq_string(s[l:-l])
if self.token.category == Token.Category.FSTRING:
r = ''
if self.has_format_specifiers:
i = 0
while i < len(self.children):
child = self.children[i]
if child.token.category == Token.Category.STRING_LITERAL:
r += child.token.value(source)
else:
fmt = ''
fmtf = ''
if i + 1 < len(self.children) and self.children[i + 1].token.category == Token.Category.STATEMENT_SEPARATOR:
fmt = ':' + self.children[i + 1].token.value(source).replace('>', '')
if '.' in fmt:
if fmt[-1] != 'f':
raise Error("floating point numbers without 'f' in format specifier are not supported", self.children[i + 1].token)
fmt = fmt[:-1]
elif fmt[-1] == 'f':
fmt = fmt[:-1] + '.6'
elif fmt[-1] == ',':
fmt = fmt[:-1]
fmtf = 'commatize'
elif fmt[-1] == 'g':
fmt = fmt[:-1]
fmtf = 'gconvfmt'
i += 1
if fmtf != '':
r += '{' + fmtf + '(' + child.to_str() + ')' + ('' if fmt == ':' else fmt) + '}'
else:
r += '{' + child.to_str() + fmt + '}'
i += 1
for child in self.children:
if child.token.category == Token.Category.STRING_LITERAL:
if '\\' in child.token.value(source):
r = 'f:"' + r + '"'
break
else:
r = 'f:‘' + r + '’'
else:
prev_is_str = False
for child in self.children:
if child.token.category == Token.Category.STRING_LITERAL:
assert(not prev_is_str)
prev_is_str = True
s = child.token.value(source).replace('{{', '{').replace('}}', '}')
if '\\' in s:
r += '"' + s + '"'
else:
r += '‘' + s + '’'
else:
if not prev_is_str and len(r) != 0:
r += '‘’'
prev_is_str = False
if child.token.category == Token.Category.NAME or child.symbol.id in ('[', '('): # )]
r += child.to_str()
else:
r += '(' + child.to_str() + ')'
if self.parent is not None and self.parent.symbol.id == '.':
r = '(' + r + ')'
return r
if self.token.category == Token.Category.CONSTANT:
return {'None': 'N', 'False': '0B', 'True': '1B'}[self.token.value(source)]
def range_need_space(child1, child2):
return not((child1 is None or child1.token.category in (Token.Category.NUMERIC_LITERAL, Token.Category.STRING_LITERAL))
and (child2 is None or child2.token.category in (Token.Category.NUMERIC_LITERAL, Token.Category.STRING_LITERAL)))
if self.symbol.id == '(': # )
if self.function_call:
if self.children[0].symbol.id == '.':
c01 = self.children[0].children[1].token_str()
if self.children[0].children[0].symbol.id == '{' and c01 == 'get': # } # replace `{'and':'&', 'or':'|', 'in':'C'}.get(self.symbol.id, 'symbol-' + self.symbol.id)` with `(S .symbol.id {‘and’ {‘&’}; ‘or’ {‘|’}; ‘in’ {‘C’} E ‘symbol-’(.symbol.id)})`
parenthesis = ('(', ')') if self.parent is not None else ('', '')
return parenthesis[0] + self.children[0].to_str() + parenthesis[1]
if c01 == 'join' and not (self.children[0].children[0].symbol.id == '.' and self.children[0].children[0].children[0].token_str() == 'os'): # replace `', '.join(arr)` with `arr.join(‘, ’)`
assert(len(self.children) == 3)
if self.children[0].children[0].token.category.STRING_LITERAL and self.children[0].children[0].token.value(source) in ('""', "''") and self.children[1].function_call and self.children[1].children[0].token_str() == 'sorted': # `''.join(sorted(s))` -> `sorted(s)`
if not (self.children[1].children[1].function_call and self.children[1].children[1].children[0].token_str() == 'list'): # left `''.join(sorted(list(...)))` as is
#return 'sorted(' + self.children[1].children[1].to_str() + ')' # this code works correctly for one argument only (i.e. it does not support multiple arguments)
return self.children[1].to_str()
return (self.children[1].to_str() if self.children[1].token.category == Token.Category.NAME or self.children[1].symbol.id == 'for' or self.children[1].function_call else '(' + self.children[1].to_str() + ')') + '.join(' + (self.children[0].children[0].children[0].to_str() if self.children[0].children[0].is_parentheses() else self.children[0].children[0].to_str()) + ')'
if c01 == 'split' and len(self.children) == 5 and not (self.children[0].children[0].token_str() == 're'): # split() second argument [limit] in 11l is similar to JavaScript, Ruby and PHP, but not Python
if self.children[4] is None:
maxsplit = self.children[3].to_str()
else:
assert(self.children[3].token_str() == 'maxsplit')
maxsplit = self.children[4].to_str()
return self.children[0].to_str() + '(' + self.children[1].to_str() + ', ' + maxsplit + ' + 1)'
if c01 == 'split' and len(self.children) == 1:
return self.children[0].to_str() + '_py()' # + '((‘ ’, "\\t", "\\r", "\\n"), group_delimiters\' 1B)'
if c01 == 'is_integer' and len(self.children) == 1: # `x.is_integer()` -> `fract(x) == 0`
return 'fract(' + self.children[0].children[0].to_str() + ') == 0'
if c01 == 'bit_length' and len(self.children) == 1: # `x.bit_length()` -> `bits:length(x)`
return 'bits:length(' + self.children[0].children[0].to_str() + ')'
if (c01 == 'count' and len(self.children) == 3 and self.children[1].token.category == Token.Category.STRING_LITERAL # `bin(x).count('1')` -> `bits:popcount(x)`
and self.children[1].token_str()[1:-1] == '1' and self.children[0].children[0].function_call and self.children[0].children[0].children[0].token_str() == 'bin'):
return 'bits:popcount(' + self.children[0].children[0].children[1].to_str() + ')'
if c01 == 'to_bytes': # `i.to_bytes(length, byteorder)` -> `UIntXX(i).to_bytes()`
assert(len(self.children) == 5)
if not (self.children[3].token.category == Token.Category.STRING_LITERAL and self.children[3].token_str()[1:-1] == 'little' if self.children[4] is None else
self.children[4].token.category == Token.Category.STRING_LITERAL and self.children[4].token_str()[1:-1] == 'little' and self.children[3].token_str() == 'byteorder'):
raise Error("only 'little' byteorder supported so far", self.children[3].token)
return 'UInt' + str(int(self.children[1].to_str()) * 8) + '(' + self.children[0].children[0].to_str() + ').to_bytes()'
if c01 == 'hex': # `b.hex()` -> `b.hex().lowercase()`
return self.children[0].to_str() + '().lowercase()'
if c01 == 'pop' and len(self.children) == 3 and self.children[1].to_str()[0] == '-':
return self.children[0].to_str() + '((len)' + self.children[1].to_str() + ')'
repl = {'startswith':'starts_with', 'endswith':'ends_with', 'find':'findi', 'rfind':'rfindi',
'lower':'lowercase', 'islower':'is_lowercase', 'upper':'uppercase', 'isupper':'is_uppercase', 'isdigit':'is_digit', 'isalpha':'is_alpha',
'timestamp':'unix_time', 'lstrip':'ltrim', 'rstrip':'rtrim', 'strip':'trim', 'writerow':'write_row', 'isatty':'is_associated_with_console',
'appendleft':'append_left', 'extendleft':'extend_left', 'popleft':'pop_left', 'issubset':'is_subset', 'isdisjoint':'is_disjoint', 'setdefault':'set_default'}.get(c01, '')
if repl != '': # replace `startswith` with `starts_with`, `endswith` with `ends_with`, etc.
c00 = self.children[0].children[0].to_str()
if repl == 'uppercase' and c00.endswith('[2..]') and self.children[0].children[0].children[0].symbol.id == '(' and self.children[0].children[0].children[0].children[0].token_str() == 'hex': # ) # `hex(x)[2:].upper()` -> `hex(x)`
return 'hex(' + self.children[0].children[0].children[0].children[1].to_str() + ')'
#assert(len(self.children) == 3)
res = c00 + '.' + repl + '('
def is_char(child):
ts = child.token_str()
return child.token.category == Token.Category.STRING_LITERAL and (len(ts) == 3 or (ts[:2] == '"\\' and len(ts) == 4))
if repl.endswith('trim') and len(self.children) == 1: # `strip()` -> `trim((‘ ’, "\t", "\r", "\n"))`
res += '(‘ ’, "\\t", "\\r", "\\n")'
elif repl.endswith('trim') and not is_char(self.children[1]): # `"...".strip("\t ")` -> `"...".trim([Char]("\t "))`
assert(len(self.children) == 3)
res += '[Char](' + self.children[1].to_str() + ')'
else:
for i in range(1, len(self.children), 2):
assert(self.children[i+1] is None)
res += self.children[i].to_str()
if i < len(self.children)-2:
res += ', '
return res + ')'
if self.children[0].children[0].function_call and \
self.children[0].children[0].children[0].token_str() == 'open' and \
len(self.children[0].children[0].children) == 5 and \
self.children[0].children[0].children[4] is None and \
self.children[0].children[0].children[3].token_str() in ("'rb'", '"rb"') and \
c01 == 'read': # transform `open(fname, 'rb').read()` into `File(fname).read_bytes()`
assert(self.children[0].children[0].children[2] is None)
return 'File(' + self.children[0].children[0].children[1].to_str() + ').read_bytes()'
if self.children[0].children[0].function_call and \
self.children[0].children[0].children[0].token_str() == 'open' and \
len(self.children[0].children[0].children) == 5 and \
self.children[0].children[0].children[4] is None and \
self.children[0].children[0].children[3].token_str() in ("'wb'", '"wb"') and \
c01 == 'write': # transform `open(fname, 'wb').write(bytes)` into `File(fname, WRITE).write_bytes(bytes)`
assert(self.children[0].children[0].children[2] is None)
return 'File(' + self.children[0].children[0].children[1].to_str() + ', WRITE).write_bytes(' + self.children[1].to_str() + ')'
if c01 in ('read', 'write'): # `bmp = open('1.bmp', 'rb'); t = bmp.read(2)` -> `... bmp.read_bytes(at_most' 2)`
method_name = "read_bytes(at_most' " if c01 == 'read' else 'write_bytes('
if self.children[0].children[0].token.category == Token.Category.NAME:
tid = self.scope.find(self.children[0].children[0].token_str())
if tid.type in ('BinaryIO', 'BinaryOutput') or \
(type(tid.node) == ASTExprAssignment and tid.node.expression.function_call and
tid.node.expression.children[0].token_str() == 'open' and
len(tid.node.expression.children) == 5 and
tid.node.expression.children[4] is None and
tid.node.expression.children[3].token_str()[-2]) == 'b':
return self.children[0].children[0].token_str() + '.' + method_name + self.children[1].to_str() + ')'
elif self.children[0].children[0].symbol.id == '.' and self.children[0].children[0].children[0].token_str() == 'self': # `out : BinaryIO...self.out.write(...)` -> `....out.write_bytes(...)`
tid = self.scope.find(self.children[0].children[0].children[1].token_str())
if tid.type in ('BinaryIO', 'BinaryOutput'):
return self.children[0].children[0].to_str() + '.' + method_name + self.children[1].to_str() + ')'
if c01 == 'seek' and len(self.children) == 5 and ((self.children[3].symbol.id == '.' and self.children[3].children[0].token_str() == 'os') or self.children[3].token_str() in ('1', '2')):
if self.children[3].symbol.id == '.':
c3c1 = self.children[3].children[1].token_str()
assert(c3c1 in ('SEEK_CUR', 'SEEK_END'))
cur = c3c1 == 'SEEK_CUR'
else:
cur = self.children[3].token_str() == '1'
c1s = self.children[1].to_str()
return self.children[0].children[0].to_str() + '. .seek(.' + ('tell()' if cur else 'get_file_size()') + (' + ' + c1s)*(c1s != '0') + ')'
if c01 == 'total_seconds': # `delta.total_seconds()` -> `delta.seconds`
assert(len(self.children) == 1)
return self.children[0].children[0].to_str() + '.seconds'
if c01 == 'conjugate' and len(self.children) == 1: # `c.conjugate()` -> `conjugate(c)`
return 'conjugate(' + self.children[0].children[0].to_str() + ')'
if c01 == 'readlines': # `f.readlines()` -> `f.read_lines(1B)`
assert(len(self.children) == 1)
return self.children[0].children[0].to_str() + ".read_lines(1B)"
if c01 == 'readline': # `f.readline()` -> `f.read_line(1B)`
assert(len(self.children) == 1)
return self.children[0].children[0].to_str() + ".read_line(1B)"
c00 = self.children[0].children[0].token_str()
if c00 == 're' and c01 != 'compile' and self.children[0].children[0].scope_prefix == ':::': # `re.search('pattern', 'string')` -> `re:‘pattern’.search(‘string’)`
c1_in_braces_if_needed = self.children[1].to_str()
if self.children[1].token.category != Token.Category.STRING_LITERAL:
c1_in_braces_if_needed = '(' + c1_in_braces_if_needed + ')'
if c01 == 'split': # `re.split('pattern', 'string')` -> `‘string’.split(re:‘pattern’)`
return self.children[3].to_str() + '.split(re:' + c1_in_braces_if_needed + ')'
if c01 == 'sub': # `re.sub('pattern', 'repl', 'string')` -> `‘string’.replace(re:‘pattern’, ‘repl’)`
return self.children[5].to_str() + '.replace(re:' + c1_in_braces_if_needed + ', ' + re.sub(R'\\(\d{1,2})', R'$\1', self.children[3].to_str()) + ')'
if c01 == 'match':
assert c1_in_braces_if_needed[0] != '(', 'only string literal patterns supported in `match()` for a while' # )
if c1_in_braces_if_needed[-2] == '$': # `re.match('pattern$', 'string')` -> `re:‘pattern’.match(‘string’)`
return 're:' + c1_in_braces_if_needed[:-2] + c1_in_braces_if_needed[-1] + '.match(' + self.children[3].to_str() + ')'
else: # `re.match('pattern', 'string')` -> `re:‘^pattern’.search(‘string’)`
return 're:' + c1_in_braces_if_needed[0] + '^' + c1_in_braces_if_needed[1:] + '.search(' + self.children[3].to_str() + ')'
return 're:' + c1_in_braces_if_needed + '.' + {'fullmatch': 'match', 'findall': 'find_strings', 'finditer': 'find_matches'}.get(c01, c01) + '(' + self.children[3].to_str() + ')'
if c00 == 'collections' and c01 == 'defaultdict': # `collections.defaultdict(ValueType) # KeyType` -> `DefaultDict[KeyType, ValueType]()`
assert(len(self.children) == 3)
if source[self.children[1].token.end + 2 : self.children[1].token.end + 3] != '#':
raise Error('to use `defaultdict` the type of dict keys must be specified in the comment', self.children[0].children[1].token)
sl = slice(self.children[1].token.end + 3, source.find("\n", self.children[1].token.end + 3))
return 'DefaultDict[' + trans_type(source[sl].lstrip(' '), self.scope, Token(sl.start, sl.stop, Token.Category.NAME)) + ', ' \
+ trans_type(self.children[1].token_str(), self.scope, self.children[1].token) + ']()'
if c00 == 'collections' and c01 == 'deque': # `collections.deque() # ValueType` -> `Deque[ValueType]()`
if len(self.children) == 3:
return 'Deque(' + self.children[1].to_str() + ')'
assert(len(self.children) == 1)
if source[self.token.end + 2 : self.token.end + 3] != '#':
raise Error('to use `deque` the type of deque values must be specified in the comment', self.children[0].children[1].token)
sl = slice(self.token.end + 3, source.find("\n", self.token.end + 3))
return 'Deque[' + trans_type(source[sl].lstrip(' '), self.scope, Token(sl.start, sl.stop, Token.Category.NAME)) + ']()'
if c00 == 'collections' and c01 == 'Counter':
if len(self.children) != 3:
raise Error('`Counter` constructor requires one argument, please use `defaultdict(int)` here', self.children[0].children[1].token)
return 'Counter(' + self.children[1].to_str() + ')'
if (c00 == 'int' or c00.startswith(('Int', 'UInt'))) and c01 == 'from_bytes':
assert(len(self.children) == 5)
byteorder = self.children[3 if self.children[4] is None else 4].token_str()[1:-1]
if byteorder not in ('little', 'big'):
raise Error("only 'little' and 'big' byteorders are supported", self.children[3].token)
return ('Int' if c00 == 'int' else c00) + '(bytes' + '_be' * (byteorder == 'big') + "' " + self.children[1].to_str() + ')'
if c00 == 'random' and c01 == 'shuffle':
return 'random:shuffle(&' + self.children[1].to_str() + ')'
if c00 == 'random' and c01 in ('randint', 'uniform'):
return 'random:(' + self.children[1].to_str() + ' .. ' + self.children[3].to_str() + ')'
if c00 == 'random' and c01 == 'randrange':
return 'random:(' + self.children[1].to_str() + (' .< ' + self.children[3].to_str() if len(self.children) == 5 else '') + ')'
if c00 == 'heapq':
res = 'minheap:' + {'heappush':'push', 'heappop':'pop', 'heapify':'heapify'}[c01] + '(&'
for i in range(1, len(self.children), 2):
assert(self.children[i+1] is None)
res += self.children[i].to_str()
if i < len(self.children)-2:
res += ', '
return res + ')'
if c00 == 'bisect':
res = 'bisect:' + {'bisect':'right', 'bisect_right':'right', 'bisect_left':'left'}[c01] + '('
for i in range(1, len(self.children), 2):
assert(self.children[i+1] is None)
res += self.children[i].to_str()
if i < len(self.children)-2:
res += ', '
return res + ')'
if c00 == 'itertools' and c01 == 'count': # `itertools.count(1)` -> `1..`
if len(self.children) < 3:
raise Error('please specify `start` argument', Token(self.token.start, self.token.end + 1, Token.Category.NAME))
r = self.children[1].to_str() + '..'
if len(self.children) == 5: # `itertools.count(1, 2)` -> `(1..).step(2)`
return '(' + r + ').step(' + self.children[3].to_str() + ')'
else:
return r
if c00 == '.' and c01 == 'fromtimestamp' and len(self.children[0].children[0].children) == 2 \
and self.children[0].children[0].children[0].token_str() == self.children[0].children[0].children[1].token_str() == 'datetime': # `datetime.datetime.fromtimestamp(s)` -> `Time(unix_time' s)`
return "Time(unix_time' " + self.children[1].to_str() + ')'
if c00 == 'array':
assert(c01 == 'array' and len(self.children) == 5 and self.children[1].token.category == Token.Category.STRING_LITERAL)
ty = {'b':'Int8', 'B':'Byte', 'h':'Int16', 'H':'UInt16', 'l':'Int32', 'L':'UInt32', 'q':'Int64', 'Q':'UInt64', 'f':'Float32'}[self.children[1].token_str()[1:-1]]
if self.children[3].is_parentheses() and self.children[3].children[0].symbol.id == 'for': # `array.array("H", (0 for _ in range(n + 1)))` -> `[UInt16(0)] * (n + 1)`
s = self.children[3].children[0]
if s.children[1].to_str() != '_':
raise Error('loop variable must be `_`', s.children[1].token)
c21 = s.children[2].children[1]
return '[' + ty + '(' + s.children[0].to_str() + ')] * ' + (c21.to_str() if c21.token.category in (Token.Category.NUMERIC_LITERAL, Token.Category.NAME) or c21.symbol.id == '(' else '(' + c21.to_str() + ')') # )
elif self.children[3].is_list: # `array.array("L", [0, 1])` -> `[UInt32(0), 1]`
s = self.children[3]
res = '['
for i in range(len(s.children)):
if i == 0:
res += ty + '(' + s.children[i].to_str() + ')'
else:
res += s.children[i].to_str()
if i < len(s.children)-1:
res += ', '
return res + ']'
elif self.children[3].function_call and self.children[3].children[0].token_str() == 'range': # `array.array("L", range(n + 1))` -> `Array(UInt32(0) .< UInt32(n + 1))`
return 'Array(' + ty + '(0) .< ' + ty + '(' + self.children[3].children[1].to_str() + '))'
elif self.children[3].function_call and self.children[3].children[0].to_str() == 'itertools:repeat':# `array.array("L", itertools.repeat(0, n + 1))` -> `[UInt32(0)] * (n + 1)`
c33 = self.children[3].children[3]
return '[' + ty + '(' + self.children[3].children[1].to_str() + ')] * ' + (c33.to_str() if c33.token.category in (Token.Category.NUMERIC_LITERAL, Token.Category.NAME) or c33.symbol.id == '(' else '(' + c33.to_str() + ')') # )
if self.children[0].children[0].token.category == Token.Category.STRING_LITERAL and c01 == 'format':
return self.str_format()
func_name = self.children[0].to_str()
if func_name == 'str':
func_name = 'String'
elif func_name == 'Char' and self.children[1].token.category != Token.Category.STRING_LITERAL:
if not (self.children[1].function_call and self.children[1].children[0].token_str() in ('str', 'int')):
raise Error('ambiguous Char constructor: write `Char(str(' + self.children[1].left_to_right_token().value(source) + '))` or ' +
'`Char(int(' + self.children[1].left_to_right_token().value(source) + '))`', self.left_to_right_token())
return 'Char(' + ('string' if self.children[1].children[0].token_str() == 'str' else 'digit') + "' " + self.children[1].children[1].to_str() + ')'
elif func_name == 'bool':
func_name = 'Bool'
elif func_name in ('int', 'Int64', 'BigInt'):
if func_name == 'int':
func_name = 'Int'
if len(self.children) == 5:
if self.children[3+1] is None:
radix = self.children[3].to_str()
else:
assert(self.children[3].token_str() == 'base')
radix = self.children[3+1].to_str()
return func_name + '(' + self.children[1].to_str() + ", radix' " + radix + ')'
elif func_name == 'float':
if len(self.children) == 3 and self.children[1].token.category == Token.Category.STRING_LITERAL and self.children[1].token_str()[1:-1].lower() in ('infinity', 'inf'):
return 'Float.infinity'
func_name = 'Float'
elif func_name == 'complex':
func_name = 'Complex'
elif func_name == 'bytearray':
func_name = '[Byte]'
elif func_name == 'bytes':
if self.children[1].token.category == Token.Category.STRING_LITERAL:
s = self.children[1].token.value(source)
assert(s[0] in 'bB')
if '\\' in s:
return 'Bytes("' + s[2:-1] + '")'
else:
return 'Bytes(‘' + s[2:-1] + '’)'
return self.children[1].to_str()
elif func_name == 'list': # `list(map(...))` -> `map(...)`
if len(self.children) == 1:
return '[]'
if len(self.children) == 3 and self.children[1].symbol.id == '(' and self.children[1].children[0].token_str() == 'range': # ) # `list(range(...))` -> `Array(...)`
parens = True#len(self.children[1].children) == 7 # if true, then this is a range with step
return 'Array' + '('*parens + self.children[1].to_str() + ')'*parens
assert(len(self.children) == 3)
if self.children[1].symbol.id == '(' and self.children[1].children[0].token_str() in ('map', 'product', 'zip'): # )
return self.children[1].to_str()
else:
return 'Array(' + self.children[1].to_str() + ')'
elif func_name == 'tuple': # `tuple(sorted(...))` -> `tuple_sorted(...)`
assert(len(self.children) == 3)
if self.children[1].function_call and self.children[1].children[0].token_str() == 'sorted':
return 'tuple_' + self.children[1].to_str()
elif func_name == 'MutTuple':
func_name = ''
elif func_name == 'PseudoTuple':
func_name = 'Array'
elif func_name == 'dict':
if len(self.children) == 1:
inside_list_comprehension = self.parent is not None and self.parent.symbol.id == 'for' and self.parent.parent.is_list and self.parent.parent.parent is None
if inside_list_comprehension and type(self.parent.parent.ast_parent) == ASTAssignmentWithTypeHint:
ty = self.parent.parent.ast_parent.trans_type_with_args()
assert(ty.startswith('[')) # ]
return ty[1:-1] + '()'
if inside_list_comprehension and type(self.parent.parent.ast_parent) == ASTExprAssignment and \
self.parent.parent.ast_parent.dest_expression.symbol.id == '.' and \
self.parent.parent.ast_parent.dest_expression.children[0].token_str() == 'self':
m = self.parent.parent.ast_parent.parent.parent.find_member_including_base_classes(self.parent.parent.ast_parent.dest_expression.children[1].token_str())
assert(m is not None)
ty = m.trans_type_with_args()
assert(ty.startswith('[')) # ]
return ty[1:-1] + '()'
if self.parent is not None or type(self.ast_parent) not in (ASTAssignmentWithTypeHint, ASTReturn):
raise Error('empty dict is not supported here' + ' (please specify type of the whole expression)' * inside_list_comprehension, self.left_to_right_token())
func_name = 'Dict'
elif func_name == 'set': # `set() # KeyType` -> `Set[KeyType]()`
if len(self.children) == 3:
if self.children[1].token.category == Token.Category.STRING_LITERAL:
return 'Set(Array(' + self.children[1].to_str() + '))'
return 'Set(' + self.children[1].to_str() + ')'
assert(len(self.children) == 1)
if source[self.token.end + 2 : self.token.end + 3] != '#':
# if self.parent is None and type(self.ast_parent) == ASTExprAssignment \
# and self.ast_parent.dest_expression.symbol.id == '.' \
# and self.ast_parent.dest_expression.children[0].token_str() == 'self' \
# and type(self.ast_parent.parent) == ASTFunctionDefinition \
# and self.ast_parent.parent.function_name == '__init__':
# return 'Set()'
raise Error('to use `set` the type of set keys must be specified in the comment', self.children[0].token)
sl = slice(self.token.end + 3, source.find("\n", self.token.end + 3))
return 'Set[' + trans_type(source[sl].lstrip(' '), self.scope, Token(sl.start, sl.stop, Token.Category.NAME)) + ']()'
elif func_name == 'open':
mode = '‘r’'
for i in range(1, len(self.children), 2):
if self.children[i+1] is None:
if i == 3:
mode = self.children[i].to_str()
else:
arg_name = self.children[i].to_str()
if arg_name == 'mode':
mode = self.children[i+1].to_str()
elif arg_name == 'newline':
if mode not in ('‘w’', '"w"', '‘a’', '"a"'):
raise Error("`newline` argument is only supported in 'w' and 'a' modes", self.children[i].token)
if self.children[i+1].to_str() not in ('"\\n"', '‘’'):
raise Error('the only allowed values for `newline` argument are "\\n" and \'\'', self.children[i+1].token)
self.children.pop(i+1)
self.children.pop(i)
break
res = 'File('
for i in range(1, len(self.children), 2):
if self.children[i+1] is None:
if i == 3:
if mode[1] == 'r':
continue
if mode[1] == 'w':
res += 'WRITE'
elif mode[1] == 'a':
res += 'APPEND'
else:
raise Error("wrong file open mode", self.children[i].token)
else:
res += self.children[i].to_str()
else:
res += self.children[i].to_str() + "' "
res += self.children[i+1].to_str()
res += ', '
return res[:-2] + ')'
elif func_name == 'product_of_a_seq':
func_name = 'product'
elif func_name == 'product':
func_name = 'cart_product'
elif func_name == 'deepcopy':
func_name = 'copy'
elif func_name == 'hexu':
func_name = 'hex'
elif func_name == 'hex':
assert(len(self.children) == 3)
return '(‘0x’hex(' + self.children[1].to_str() + ').lowercase())'
elif func_name == 'oct':
assert(len(self.children) == 3)
return '(‘0o’String(' + self.children[1].to_str() + ", radix' 8))"
elif func_name == 'rotl32':
func_name = 'rotl'
elif func_name == 'rotr32':
func_name = 'rotr'
elif func_name == 'popcount':
func_name = 'bits:popcount'
elif func_name == 'quit':
func_name = 'exit'
elif func_name == 'print' and self.iterable_unpacking:
func_name = 'print_elements'
if func_name == 'len': # replace `len(container)` with `container.len`
assert(len(self.children) == 3)
if isinstance(self.ast_parent, (ASTIf, ASTWhile)) if self.parent is None else (self.parent.symbol.id == 'if' and self is self.parent.children[1]): # `if len(arr)` -> `I !arr.empty`
return '!' + self.children[1].to_str() + '.empty'
if len(self.children[1].children) == 2 and self.children[1].symbol.id not in ('.', '['): # ]
return '(' + self.children[1].to_str() + ')' + '.len'
return self.children[1].to_str() + '.len'
elif func_name == 'ord': # replace `ord(ch)` with `ch.code`
assert(len(self.children) == 3)
return self.children[1].to_str() + '.code'
elif func_name == 'chr': # replace `chr(code)` with `Char(code' code)`
assert(len(self.children) == 3)
return "Char(code' " + self.children[1].to_str() + ')'
elif func_name == 'int_to_str_with_radix': # replace `int_to_str_with_radix(i, base)` with `String(i, radix' base)`
assert(len(self.children) == 5)
return 'String(' + self.children[1].to_str() + ", radix' " + self.children[3].to_str() + ')'
elif func_name == 'isinstance': # replace `isinstance(obj, type)` with `T(obj) >= type`
assert(len(self.children) == 5)
return 'T(' + self.children[1].to_str() + ') >= ' + self.children[3].to_str()
elif func_name in ('map', 'filter'): # replace `map(function, iterable)` with `iterable.map(function)`
assert(len(self.children) == 5)
b = len(self.children[3].children) > 1 and self.children[3].symbol.id not in ('(', '[') # ])
c1 = self.children[1].to_str()
return '('*b + self.children[3].to_str() + ')'*b + '.' + func_name + '(' + {'int':'Int', 'float':'Float', 'str':'String'}.get(c1, c1) + ')'
elif func_name == 'reduce':
if len(self.children) == 5: # replace `reduce(function, iterable)` with `iterable.reduce(function)`
return self.children[3].to_str() + '.reduce(' + self.children[1].to_str() + ')'
else: # replace `reduce(function, iterable, initial)` with `iterable.reduce(initial, function)`
assert(len(self.children) == 7)
return self.children[3].to_str() + '.reduce(' + self.children[5].to_str() + ', ' + self.children[1].to_str() + ')'
elif func_name == 'super': # replace `super()` with `T.base`
assert(len(self.children) == 1)
return 'T.base'
elif func_name in ('next_permutation', 'is_sorted'): # `next_permutation(arr)` -> `arr.next_permutation()`
assert(len(self.children) == 3)
return self.children[1].to_str() + '.' + func_name + '()'
elif func_name in ('nidiv', 'nmod'): # `nidiv(a, b)` -> `a -I/ b` and `nmod(a, b)` -> `a -% b`
assert(len(self.children) == 5)
p = self.children[1].token.category == Token.Category.OPERATOR_OR_DELIMITER and self.children[1].symbol.lbp < symbol_table['//'].lbp
p2 = self.children[3].token.category == Token.Category.OPERATOR_OR_DELIMITER and self.children[3].symbol.lbp <= symbol_table['//'].lbp
return p * '(' + self.children[1].to_str() + ')' * p + (' -I/ ' if func_name == 'nidiv' else ' -% ') + p2 * '(' + self.children[3].to_str() + ')' * p2
elif func_name == 'range':
assert(3 <= len(self.children) <= 7)
parenthesis = ('(', ')') if self.parent is not None and (self.parent.symbol.id == 'for' or (self.parent.function_call and self.parent.children[0].token_str() in ('map', 'filter', 'reduce'))) else ('', '')
if len(self.children) == 3: # replace `range(e)` with `(0 .< e)`
space = ' ' * range_need_space(self.children[1], None)