-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathparse.py
More file actions
4449 lines (4037 loc) · 254 KB
/
parse.py
File metadata and controls
4449 lines (4037 loc) · 254 KB
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 tokenizer import Token
import tokenizer
except ImportError:
from .tokenizer import Token
from . import tokenizer
from typing import List, Tuple, Dict, Callable, Set, ClassVar
from enum import IntEnum
import os, re, eldf
class Error(Exception):
def __init__(self, message, token):
self.message = message
self.pos = token.start
self.end = token.end
class Scope:
parent : 'Scope'
node : 'ASTNode' = None
class Id:
type : str
default_val: str
type_node : 'ASTTypeDefinition' = None
ast_nodes : List['ASTNodeWithChildren']
last_occurrence : 'SymbolNode' = None
def __init__(self, type, default_val = '', ast_node = None):
assert(type is not None)
self.type = type
self.default_val = default_val
self.ast_nodes = []
if ast_node is not None:
self.ast_nodes.append(ast_node)
def init_type_node(self, scope):
if self.type != '':
tid = scope.find(self.type)
if tid is not None and len(tid.ast_nodes) == 1 and type(tid.ast_nodes[0]) == ASTTypeDefinition:
self.type_node = tid.ast_nodes[0]
def serialize_to_dict(self):
ast_nodes = []
for ast_node in self.ast_nodes:
if type(ast_node) in (ASTFunctionDefinition, ASTTypeDefinition):
ast_nodes.append(ast_node.serialize_to_dict())
return {'type': self.type, 'ast_nodes': ast_nodes}
def deserialize_from_dict(self, d):
#self.type = d['type']
for ast_node_dict in d['ast_nodes']:
ast_node = ASTFunctionDefinition() if ast_node_dict['node_type'] == 'function' else ASTTypeDefinition()
ast_node.deserialize_from_dict(ast_node_dict)
self.ast_nodes.append(ast_node)
ids : Dict[str, Id]
is_function : bool
is_lambda = False
def __init__(self, func_args):
self.parent = None
if func_args is not None:
self.is_function = True
self.ids = dict(map(lambda x: (x[0], Scope.Id(x[1], x[2])), func_args))
else:
self.is_function = False
self.ids = {}
self.module_aliases = {}
def init_ids_type_node(self):
for id in self.ids.values():
id.init_type_node(self.parent)
def serialize_to_dict(self):
ids_dict = {}
for name, id in self.ids.items():
ids_dict[name] = id.serialize_to_dict()
return ids_dict
def deserialize_from_dict(self, d):
for name, id_dict in d.items():
id = Scope.Id(id_dict['type'])
id.deserialize_from_dict(id_dict)
self.ids[name] = id
def find_in_current_function(self, name):
s = self
while True:
if name in s.ids:
return s.ids[name]
if s.is_function:
return None
s = s.parent
if s is None:
return None
def find_in_current_type_function(self, name):
s = self
while True:
if name in s.ids:
return True
if s.is_function and type(s.node) == ASTFunctionDefinition and type(s.node.parent) == ASTTypeDefinition:
return False
s = s.parent
if s is None:
return False
def find(self, name):
s = self
while True:
id = s.ids.get(name)
if id is not None:
return id
s = s.parent
if s is None:
return None
def module_alias(self, name):
s = self
while True:
ma = s.module_aliases.get(name)
if ma is not None:
return ma
s = s.parent
if s is None:
return None
def find_and_return_scope(self, name):
s = self
if type(s.node) == ASTTypeDefinition:
id = s.ids.get(name)
if id is not None:
return id, s
while True:
if type(s.node) != ASTTypeDefinition:
id = s.ids.get(name)
if id is not None:
return id, s
s = s.parent
if s is None:
return None, None
def add_function(self, name, ast_node):
if name in self.ids: # V &id = .ids.set_if_not_present(name, .Id(‘’)) // [[[or `put_if_absent` as in Java, or `add_if_absent`]]] note that this is an error: `V id = .ids.set_if_not_present(...)`, but you can do this: `V id = copy(.ids.set_if_not_present(...))`
assert(type(self.ids[name].ast_nodes[0]) == ASTFunctionDefinition) # assert(id.ast_nodes.empty | T(id.ast_nodes[0]) == ASTFunctionDefinition)
self.ids[name].ast_nodes.append(ast_node) # id.ast_nodes [+]= ast_node
else:
self.ids[name] = Scope.Id('', '', ast_node)
def add_name(self, name, ast_node):
if name in self.ids: # I !.ids.set(name, .Id(‘’, ast_node))
if isinstance(ast_node, ASTVariableDeclaration):
t = ast_node.type_token
elif isinstance(ast_node, ASTNodeWithChildren):
t = tokens[ast_node.tokeni + 1]
else:
t = token
raise Error('redefinition of already defined identifier is not allowed', t) # X Error(‘redefinition ...’, ...)
if type(ast_node) == ASTTypeDefinition:
ast_node.type_name = name
self.ids[name] = Scope.Id('', '', ast_node)
scope : Scope
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
int_is_int64 = False
python_division = False
class SymbolNode:
token : Token
symbol : SymbolBase = None
children : List['SymbolNode']# = []
parent : 'SymbolNode' = None
ast_parent : 'ASTNode'
function_call : bool = False
tuple : bool = False
is_list : bool = False
is_dict : bool = False
is_type : bool = False
postfix : bool = False
is_var_decl = False
scope : Scope
token_str_override : str
def __init__(self, token, token_str_override = None, symbol = None):
self.token = token
self.children = []
self.scope = scope
self.token_str_override = token_str_override
self.symbol = symbol
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):
return self.token.start
if self.symbol.id == '(': # )
if self.function_call:
return self.children[0].token.start
else:
return self.token.start
elif self.symbol.id == '[': # ]
if self.is_list or self.is_dict:
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 to_debug_str(self):
if self.token.category in (Token.Category.NAME, Token.Category.NUMERIC_LITERAL):
return self.token_str()
if self.function_call:
res = self.children[0].to_debug_str() + '('
for i in range(1, len(self.children), 2):
res += self.children[i+1].to_debug_str()
if i < len(self.children)-2:
res += ', '
return res + ')'
if len(self.children) == 1:
if self.symbol.id == '(': # )
return '(' + self.children[0].to_debug_str() + ')'
if self.postfix:
return '(' + self.children[0].to_debug_str() + self.symbol.id + ')'
else:
return '(' + self.symbol.id + self.children[0].to_debug_str() + ')'
if len(self.children) == 3: # "with"-expression
assert(self.children[1].token.category == Token.Category.SCOPE_BEGIN)
return self.children[0].to_debug_str() + '. (' + self.children[2].to_debug_str() + ')'
assert(len(self.children) == 2)
return '(' + self.children[0].to_debug_str() + ' ' + self.symbol.id + ' ' + self.children[1].to_debug_str() + ')'
def to_type_str(self):
if self.symbol.id == '[': # ]
if self.is_list:
assert(len(self.children) == 1)
return 'Array[' + self.children[0].to_type_str() + ']'
elif self.is_dict:
assert(len(self.children) == 1 and self.children[0].symbol.id == '=')
return 'Dict[' + self.children[0].children[0].to_type_str() + ', ' \
+ self.children[0].children[1].to_type_str() + ']'
else:
assert(self.is_type)
r = self.children[0].token.value(source) + '['
for i in range(1, len(self.children)):
r += self.children[i].to_type_str()
if i < len(self.children) - 1:
r += ', '
return r + ']'
elif self.symbol.id == '(': # )
if len(self.children) == 1 and self.children[0].symbol.id == '->':
r = 'Callable['
c0 = self.children[0]
if c0.children[0].symbol.id == '(': # )
for child in c0.children[0].children:
r += child.to_type_str() + ', '
else:
r += c0.children[0].to_type_str() + ', '
return r + c0.children[1].to_type_str() + ']'
elif self.function_call:
assert(self.children[0].token_str() in ('T', 'Т', 'type', 'тип'))
return 'TYPE_OF(' + self.children[2].to_str() + ')'
else:
assert(self.tuple)
r = '('
for i in range(len(self.children)):
assert(self.children[i].symbol.id != '->')
r += self.children[i].to_type_str()
if i < len(self.children) - 1:
r += ', '
return r + ')'
elif self.symbol.id == 'T? ':
return self.children[0].to_type_str() + '?'
elif self.symbol.id == ':':
return self.children[0].to_type_str() + ':' + self.children[1].to_type_str()
assert(self.token.category == Token.Category.NAME or (self.token.category == Token.Category.CONSTANT and self.token.value(source) in ('N', 'Н', 'null', 'нуль')))
return self.token_str()
inside_it_lambda: ClassVar = False
def to_str(self):
if not SymbolNode.inside_it_lambda:
found_it = False
def f(sn: SymbolNode):
if sn.function_call:
f(sn.children[0])
return
if (sn.token.category == Token.Category.NAME and sn.token_str() == '(->)') or (sn.token_str() == '->' and len(sn.children) == 0):
nonlocal found_it
found_it = True
else:
for child in sn.children:
if child is not None:
f(child)
f(self)
if found_it:
SymbolNode.inside_it_lambda = True
r = '[](const auto &it){return ' + self.to_str() + ';}'
SymbolNode.inside_it_lambda = False
return r
if self.token.category == Token.Category.NAME:
if self.token_str() in ('L.index', 'Ц.индекс', 'loop.index', 'цикл.индекс'):
parent = self
while parent.parent:
parent = parent.parent
ast_parent = parent.ast_parent
while True:
if type(ast_parent) == ASTLoop:
ast_parent.has_L_index = True
break
ast_parent = ast_parent.parent
return 'Lindex'
if self.token_str() == '(.)':
# if self.parent is not None and self.parent.symbol.id == '=' and self is self.parent.children[1]: # `... = (.)` -> `... = this;`
# return 'this'
return '*this'
if self.token_str() == '(->)':
return 'it'
tid = self.scope.find(self.token_str())
if tid is not None and ((len(tid.ast_nodes) and isinstance(tid.ast_nodes[0], ASTVariableDeclaration) and tid.ast_nodes[0].is_ptr and not tid.ast_nodes[0].nullable) # `animals [+]= animal` -> `animals.append(std::move(animal));`
or (tid.type_node is not None and (tid.type_node.has_virtual_functions or tid.type_node.has_pointers_to_the_same_type))) \
and (self.parent is None or self.parent.symbol.id not in ('.', ':', '!')):
if tid.last_occurrence is None:
last_reference = None
var_name = self.token_str()
def find_last_reference_to_identifier(node):
def f(e : SymbolNode):
if e.token.category == Token.Category.NAME and e.token_str() == var_name and id(e.scope.find(var_name)) == id(tid):
nonlocal last_reference
last_reference = e
for child in e.children:
if child is not None:
f(child)
node.walk_expressions(f)
node.walk_children(find_last_reference_to_identifier)
if tid.type_node is not None:
find_last_reference_to_identifier(self.scope.node)
tid.last_occurrence = last_reference
else:
for index in range(len(tid.ast_nodes[0].parent.children)):
if id(tid.ast_nodes[0].parent.children[index]) == id(tid.ast_nodes[0]):
for index in range(index + 1, len(tid.ast_nodes[0].parent.children)):
find_last_reference_to_identifier(tid.ast_nodes[0].parent.children[index])
tid.last_occurrence = last_reference
break
if id(tid.last_occurrence) == id(self):
return 'std::move(' + self.token_str() + ')'
if tid is not None and len(tid.ast_nodes) and isinstance(tid.ast_nodes[0], ASTVariableDeclaration) and tid.ast_nodes[0].type.endswith('?'):
if self.parent is None or (not (self.parent.symbol.id in ('==', '!=') and self.parent.children[1].token_str() in ('N', 'Н', 'null', 'нуль'))
and not (self.parent.symbol.id == '.')
and not (self.parent.symbol.id == '?')
and not (self.parent.symbol.id == '!' and self.parent.postfix)
and not (self.parent.symbol.id == '=' and self is self.parent.children[0])):
return '*' + self.token_str()
if self.token_str().startswith('@:'):
var_name = self.token_str()[self.token_str().index(':') + 1:]
tid = self.scope.find(var_name)
if tid is not None and len(tid.ast_nodes) and isinstance(tid.ast_nodes[0], ASTVariableDeclaration) and tid.ast_nodes[0].is_static:
return 's_' + var_name
return self.token_str().lstrip('@=').replace(':', '::')
if self.token.category == Token.Category.KEYWORD and self.token_str() in ('L.last_iteration', 'Ц.последняя_итерация', 'loop.last_iteration', 'цикл.последняя_итерация'):
parent = self
while parent.parent:
parent = parent.parent
ast_parent = parent.ast_parent
while True:
if type(ast_parent) == ASTLoop:
ast_parent.has_L_last_iteration = True
break
ast_parent = ast_parent.parent
return '(__begin == __end)'
if self.token.category == Token.Category.NUMERIC_LITERAL:
n = self.token_str()
if n[-1] in 'oв':
return '0' + n[:-1] + 'LL'*int_is_int64
if n[-1] in 'bд':
return '0b' + n[:-1] + 'LL'*int_is_int64
if n[-1] in 'LД':
return n[:-1] + 'LL'
if n[-1] in 'sо':
return n[:-1] + 'f'
if n[4:5] == "'" or n[-3:-2] == "'" or n[-2:-1] == "'" or n[-9:-8] == "'":
nn = ''
for c in n:
nn += {'А':'A','Б':'B','С':'C','Д':'D','Е':'E','Ф':'F'}.get(c, c)
if n[-2:-1] == "'":
nn = nn.replace("'", '')
return '0x' + nn
if '.' in n or 'e' in n:
return n
return n + 'LL'*int_is_int64
if self.token.category == Token.Category.STRING_LITERAL:
s = self.token_str()
indented = False
if s[0] == '|':
indented = True
s = s[1:]
assert(s[0] != '"')
elif s.startswith(r'\/'):
if s[3] != "\n":
raise Error('Zero indented multi-line string literal must start with a new line', Token(self.token.start + 3, self.token.start + 3, Token.Category.STRING_LITERAL))
s = s[2] + s[4:]
assert(s[0] != '"')
if s[0] == '"':
return 'u' + s + '_S'
eat_left = 0
while s[eat_left] == "'":
eat_left += 1
eat_right = 0
while s[-1-eat_right] == "'":
eat_right += 1
s = s[1+eat_left*2:-1-eat_right*2]
if indented:
line_start = source.rfind("\n", 0, self.token.start) + 1
indentation = ''
for i in range(line_start, self.token.start):
indentation += "\t" if source[i] == "\t" else ' '
indentation += ' ' * (2+eat_left*2)
newline_pos = s.find("\n")
if newline_pos != -1:
newline_pos += 1
new_s = s[:newline_pos]
while True:
if s[newline_pos:newline_pos+1] == "\n":
new_s += "\n"
newline_pos += 1
continue
if s[newline_pos:newline_pos+len(indentation)] != indentation:
error_pos = self.token.start + (2+eat_left*2) + newline_pos
raise Error('incorrect indentation of line in indented multi-line string literal', Token(error_pos, error_pos, Token.Category.STRING_LITERAL))
prev_newline_pos = newline_pos
newline_pos = s.find("\n", newline_pos)
if newline_pos == -1:
new_s += s[prev_newline_pos + len(indentation):]
break
newline_pos += 1
new_s += s[prev_newline_pos + len(indentation):newline_pos]
s = new_s
if '\\' in s or "\n" in s:
delimiter = '' # (
while ')' + delimiter + '"' in s:
delimiter += "'"
return 'uR"' + delimiter + '(' + s + ')' + delimiter + '"_S'
return 'u"' + repr(s)[1:-1].replace('"', R'\"').replace(R"\'", "'") + '"_S'
if self.token.category == Token.Category.FSTRING:
nfmtstr = ''
format_args = ''
i = 0
while i < len(self.children):
child = self.children[i]
if child.token.category == Token.Category.STRING_LITERAL:
s = child.token.value(source)
j = 0
while j < len(s):
if s[j] == '#' and (s[j+1:j+2] in ('#', '.', '<') or s[j+1:j+2].isdigit()):
nfmtstr += '##'
elif s[j] == '{':
j += 1
assert(s[j] == '{')
nfmtstr += '{'
elif s[j] == '}':
j += 1
assert(s[j] == '}')
nfmtstr += '}'
else:
nfmtstr += s[j]
j += 1
else:
nfmtstr += '#'
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)#.lstrip(' ')
if fmt[0] == ' ':
p = self.children[i + 1].token.start
raise Error('space format option is not supported [but you can write `f:‘ {c:4}’` instead of `f:‘{c: 5}’`]', Token(p, p, Token.Category.DELIMITER))
if fmt[0] == '<':
nfmtstr += '<'
fmt = fmt[1:]
if '.' in fmt:
if fmt[0] == '0' and fmt[1:2].isdigit(): # zero padding
nfmtstr += '0'
(before_period, after_period) = map(int, ('0' + fmt).split('.')) # `'0' + ` is for e.g. `#.6` (fmt = '.6')
b = before_period
if after_period != 0:
b -= after_period + 1
if b > 1:
nfmtstr += str(b)
nfmtstr += '.' + str(after_period)
else:
nfmtstr += fmt
i += 1
else:
nfmtstr += '.'
if format_args != '':
format_args += ', '
format_args += child.to_str()
i += 1
if source[self.token.start + 2] == '"':
nfmtstr = 'u"' + nfmtstr + '"_S'
elif '\\' in nfmtstr or "\n" in nfmtstr:
delimiter = '' # (
while ')' + delimiter + '"' in nfmtstr:
delimiter += "'"
nfmtstr = 'uR"' + delimiter + '(' + nfmtstr + ')' + delimiter + '"_S'
else:
nfmtstr = 'u"' + repr(nfmtstr)[1:-1].replace('"', R'\"').replace(R"\'", "'") + '"_S'
return nfmtstr + '.format(' + format_args + ')'
if self.token.category == Token.Category.CONSTANT:
return {'N': 'nullptr', 'Н': 'nullptr', 'null': 'nullptr', 'нуль': 'nullptr', '0B': 'false', '0В': 'false', '1B': 'true', '1В': 'true'}[self.token_str()]
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))
def char_or_str(child, is_char):
if is_char:
if child.token_str()[1:-1] == "\\":
return R"u'\\'_C"
return "u'" + child.token_str()[1:-1].replace("'", R"\'") + "'_C"
return child.to_str()
if self.symbol.id == '(': # )
if self.function_call:
func_name = self.children[0].to_str()
f_node = None
if self.children[0].symbol.id == '.':
if len(self.children[0].children) == 1:
in_with = False
n = self
while True:
n = n.parent
if n is None:
break
if len(n.children) == 3 and not n.function_call and n.children[1].token.category == Token.Category.SCOPE_BEGIN:
in_with = True
break
if not in_with:
s = self.scope
while True:
if s.is_function:
if type(s.node) != ASTFunctionDefinition:
assert(s.is_lambda)
raise Error('probably `@` is missing (before this dot)', self.children[0].token)
if type(s.node.parent) == ASTTypeDefinition:
assert(s.node.parent.scope == s.parent)
fid = s.node.parent.find_id_including_base_types(self.children[0].children[0].to_str())
if fid is None:
raise Error('call of undefined method `' + func_name + '`', self.children[0].children[0].token)
if len(fid.ast_nodes) > 1:
raise Error('methods\' overloading is not supported for now', self.children[0].children[0].token)
f_node = fid.ast_nodes[0]
if type(f_node) == ASTTypeDefinition:
if len(f_node.constructors) == 0:
f_node = ASTFunctionDefinition()
else:
if len(f_node.constructors) > 1:
raise Error('constructors\' overloading is not supported for now (see type `' + f_node.type_name + '`)', self.children[0].left_to_right_token())
f_node = f_node.constructors[0]
break
if type(s.node) == ASTWith:
break
s = s.parent
assert(s)
elif func_name.endswith('.map') and self.children[2].token.category == Token.Category.NAME and self.children[2].token_str()[0].isupper():
c2 = self.children[2].to_str()
return func_name + '([](const auto &x){return ' + {'Int':'to_int', 'Int64':'to_int64', 'Long':'to_int64', 'UInt64':'to_uint64', 'ULong':'to_uint64', 'UInt32':'to_uint32', 'Float':'to_float', 'SFloat':'to_float32', 'Float32':'to_float32'}.get(c2, c2) + '(x);})'
elif func_name.endswith('.split'):
if len(self.children) == 5 and self.children[3] is not None and self.children[3].token_str() == "req'":
return func_name + '_req(' + self.children[2].to_str() + ', ' + self.children[4].to_str() + ')'
f_node = type_of(self.children[0])
if f_node is None: # assume this is String method
f_node = builtins_scope.find('String').ast_nodes[0].scope.ids.get('split').ast_nodes[0]
elif func_name.endswith('.read_bytes') and len(self.children) == 3 and self.children[1] is not None and self.children[1].token_str() == "at_most'":
return func_name + '_at_most(' + self.children[2].to_str() + ')'
elif func_name.endswith('.sort_range'):
f_node = type_of(self.children[0])
if f_node is None: # assume this is Array method
f_node = builtins_scope.find('Array').ast_nodes[0].scope.ids.get('sort_range').ast_nodes[0]
elif func_name.endswith('.pop') and len(self.children) == 3 and self.children[2].to_str().startswith('(len)'):
return func_name + '_plus_len(' + self.children[2].to_str()[len('(len)'):] + ')'
elif func_name.endswith(('.count', '.index')) and len(self.children) == 3 and self.children[2].token.category == Token.Category.STRING_LITERAL:
return func_name + '(' + char_or_str(self.children[2], is_char(self.children[2])) + ')'
elif self.children[0].children[1].token.value(source) == 'union':
func_name = self.children[0].children[0].to_str() + '.set_union'
elif func_name.endswith('.to_bytes'):
return 'bytes_from_int(' + self.children[0].children[0].to_str() + ')'
elif func_name.endswith('.bits'):
return 'int_bits(' + self.children[0].children[0].to_str() + ', ' + self.children[2].to_str() + ')'
elif func_name.endswith('.bit'):
return 'bit_ref(' + self.children[0].children[0].to_str() + ', ' + self.children[2].to_str() + ')'
elif func_name.endswith('.as'):
return trans_type(self.children[2].to_type_str(), self.children[2].scope, self.children[2].token) + '(' + self.children[0].children[0].to_str() + ')'
else:
f_node = type_of(self.children[0])
elif func_name == 'Bool':
func_name = 'bool'
elif func_name in ('Int', 'Int64', 'UInt64', 'Int32', 'UInt32', 'Int16', 'UInt16', 'Int8', 'Byte'):
if self.children[1] is not None and self.children[1].token_str() in ("bytes'", "bytes_be'"):
be = '_be' * (self.children[1].token_str() == "bytes_be'")
int_from_bytes = 'int_from_bytes' + be if func_name == 'Int' else 'int_t_from_bytes' + be + '<' + func_name + '>'
if self.children[2].symbol.id == '[' and not self.children[2].is_list and self.children[2].children[1].symbol.id in ('..', '.<', '.+', '<.', '<.<'): # ]
return int_from_bytes + '(' + self.children[2].children[0].to_str() + ', ' + self.children[2].children[1].to_str() + ')'
return int_from_bytes + '(' + self.children[2].to_str() + ')'
func_name = {'Int':'to_int', 'Int64':'to_int64', 'UInt64':'to_uint64', 'Int32':'to_int32', 'UInt32':'to_uint32', 'Int16':'to_int16', 'UInt16':'to_uint16', 'Int8':'to_int8', 'Byte':'Byte'}[func_name]
f_node = builtins_scope.find('Int').ast_nodes[0].constructors[0]
elif func_name in ('Float', 'SFloat', 'Float32', 'Float64'):
func_name = 'to_float' + '32'*(func_name in ('SFloat', 'Float32'))
elif func_name in cpp_vectype_from_11l:
func_name = cpp_vectype_from_11l[func_name]
elif func_name == 'Char' and self.children[2].token.category == Token.Category.STRING_LITERAL:
assert(self.children[1] is None) # [-TODO: write a good error message-]
if not is_char(self.children[2]):
raise Error('Char can be constructed only from single character string literals', self.children[2].token)
return char_or_str(self.children[2], True)
elif func_name == 'Char' and self.children[1] is not None and self.children[1].token_str() == "string'":
return 'Char(' + self.children[2].to_str() + ')'
elif func_name == 'Char' and self.children[1] is not None and self.children[1].token_str() == "digit'":
return 'char_from_digit(' + self.children[2].to_str() + ')'
elif func_name == 'Time' and len(self.children) == 3 and self.children[1] is not None and self.children[1].token_str() == "unix_time'":
return 'timens::from_unix_time(' + self.children[2].to_str() + ')'
elif func_name == 'String' and self.children[2].token.category == Token.Category.STRING_LITERAL:
return self.children[2].to_str()
elif func_name == 'Bytes' and self.children[2].token.category == Token.Category.STRING_LITERAL:
return '"' + self.children[2].token_str()[1:-1] + '"_B'
elif func_name.startswith('Array['): # ]
func_name = 'Array<' + func_name[6:-1] + '>'
elif func_name == 'Array': # `list(range(1,10))` -> `Array(1.<10)` -> `create_array(range_el(1, 10))`
func_name = 'create_array'
elif self.children[0].symbol.id == '[' and (self.children[0].is_list or self.children[0].is_dict): # ] # `[Type]()` -> `Array<Type>()`, `[KeyType = ValueType]()` -> `Dict<KeyType, ValueType>()`
func_name = trans_type(self.children[0].to_type_str(), self.children[0].scope, self.children[0].token)
elif func_name == 'Dict':
func_name = 'create_dict'
elif func_name.startswith('DefaultDict['): # ]
func_name = 'DefaultDict<' + ', '.join(trans_type(c.to_type_str(), c.scope, c.token) for c in self.children[0].children[1:]) + '>'
elif func_name in ('Set', 'Deque'):
func_name = 'create_set' if func_name == 'Set' else 'create_deque'
if self.children[2].is_list:
c = self.children[2].children
res = func_name + ('<' + trans_type(c[0].children[0].token_str(), self.scope, c[0].children[0].token)
+ '>' if len(c) > 1 and c[0].function_call and c[0].children[0].token_str()[0].isupper() else '') + '({'
for i in range(len(c)):
res += c[i].to_str()
if i < len(c)-1:
res += ', '
return res + '})'
elif func_name.startswith(('Set[', 'Deque[')): # ]]
c = self.children[0].children[1]
func_name = func_name[:func_name.find('[')] + '<' + trans_type(c.to_type_str(), c.scope, c.token) + '>' # ]
elif func_name in ('sum', 'all', 'any', 'min', 'max') and self.children[2].function_call and self.children[2].children[0].symbol.id == '.' and self.children[2].children[0].children[1].token_str() == 'map':
assert(len(self.children) == 3)
c2 = self.children[2].children[2].to_str()
if self.children[2].children[2].token.category == Token.Category.NAME and self.children[2].children[2].token_str()[0].isupper():
c2 = '[](const auto &x){return ' + {'Int':'to_int', 'Int64':'to_int64', 'Long':'to_int64', 'UInt64':'to_uint64', 'ULong':'to_uint64', 'UInt32':'to_uint32', 'Float':'to_float', 'SFloat':'to_float32', 'Float32':'to_float32'}.get(c2, c2) + '(x);}'
return func_name + '_map(' + self.children[2].children[0].children[0].to_str() + ', ' + c2 + ')'
elif func_name in ('min', 'max') and len(self.children) == 5 and self.children[3] is not None and self.children[3].token_str() == "key'":
return func_name + '_with_key(' + self.children[2].to_str() + ', ' + self.children[4].to_str() + ')'
elif func_name in ('min', 'max') and len(self.children) == 5 and self.children[3] is not None and self.children[3].token.value(source) == "default'":
return func_name + '_with_default(' + self.children[2].to_str() + ', ' + self.children[4].to_str() + ')'
elif func_name == 'cart_product' and len(self.children) == 5 and self.children[3] is not None and self.children[3].token_str() == "repeat'":
return func_name + '_repeat(' + self.children[2].to_str() + ', ' + self.children[4].to_str() + ')'
elif func_name == 'String' and len(self.children) == 5 and self.children[3] is not None and self.children[3].token_str() == "radix'":
return 'int_to_str_with_radix(' + self.children[2].to_str() + ', ' + self.children[4].to_str() + ')'
elif func_name == 'copy':
s = self.scope
while True:
if s.is_function:
if s.node is not None and type(s.node.parent) == ASTTypeDefinition:
fid = s.parent.ids.get('copy')
if fid is not None:
func_name = '::copy'
break
s = s.parent
if s is None:
break
elif func_name == 'move':
func_name = 'std::move'
elif func_name == '*this':
func_name = '(*this)' # function call has higher precedence than dereference in C++, so `*this(...)` is equivalent to `*(this(...))`
elif func_name == 'term::color':
if self.children[2].token_str() not in {'GRAY', 'BLUE', 'GREEN', 'CYAN', 'RED', 'MAGENTA', 'YELLOW', 'RESET'}:
raise Error('wrong color', self.children[2].left_to_right_token())
return func_name + '(term::Color::' + self.children[2].token_str() + ')'
elif func_name == 'File' and len(self.children) >= 5 and self.children[3] is None:
if self.children[4].token_str() not in {'WRITE', 'APPEND'}:
raise Error('wrong file open mode', self.children[4].left_to_right_token())
args = self.children[2].to_str()
if len(self.children) > 5:
if len(self.children) != 7 or not (self.children[5] is not None and self.children[5].token_str() == "encoding'"):
raise Error('wrong arguments', self.left_to_right_token())
args += ', ' + self.children[6].to_str()
if self.children[4].token_str() == 'APPEND':
args += ', true'
else:
if self.children[4].token_str() == 'APPEND':
args += ', u"utf-8"_S, true'
return 'FileWr(' + args + ')'
elif self.children[0].symbol.id == '[': # ]
pass
elif self.children[0].function_call: # for `enumFromTo(0)(1000)`
pass
else:
if self.children[0].symbol.id == ':':
fid, sc = find_module(self.children[0].children[0].to_str()).scope.find_and_return_scope(self.children[0].children[1].token_str())
elif self.children[0].symbol.id == '.:':
fn_name = self.children[0].children[0].token_str()
fid = None
sc = self.scope
while True:
if type(sc.node) == ASTTypeDefinition:
for child in sc.node.children:
if type(child) == ASTFunctionDefinition and child.is_static and child.function_name == fn_name:
for id_ in sc.ids.values():
if id_.ast_nodes[0] is child:
fid = id_
break
if fid is not None:
break
if fid is not None:
break
sc = sc.parent
if sc is None:
break
else:
fid, sc = self.scope.find_and_return_scope(func_name)
if fid is None:
raise Error('call of undefined function `' + func_name + '`', self.children[0].left_to_right_token())
if len(fid.ast_nodes) > 1:
raise Error('functions\' overloading is not supported for now', self.children[0].left_to_right_token())
if len(fid.ast_nodes) == 0:
if sc.is_function: # for calling of function arguments, e.g. `F amb(comp, ...)...comp(prev, opt)`
f_node = None
else:
raise Error('node of function `' + func_name + '` is not found', self.children[0].left_to_right_token())
else:
f_node = fid.ast_nodes[0]
if type(f_node) == ASTLoop: # for `L(justify) [(s, w) -> ...]...justify(...)`
f_node = None
else:
#assert(type(f_node) in (ASTFunctionDefinition, ASTTypeDefinition) or (type(f_node) in (ASTVariableInitialization, ASTVariableDeclaration) and f_node.function_pointer)
# or (type(f_node) == ASTVariableInitialization and f_node.expression.symbol.id == '->'))
if type(f_node) == ASTTypeDefinition:
if f_node.has_virtual_functions or f_node.has_pointers_to_the_same_type:
func_name = 'std::make_unique<' + func_name + '>'
# elif f_node.has_pointers_to_the_same_type:
# func_name = 'make_SharedPtr<' + func_name + '>'
if len(f_node.constructors) == 0:
f_node = ASTFunctionDefinition()
else:
if len(f_node.constructors) > 1:
raise Error('constructors\' overloading is not supported for now (see type `' + f_node.type_name + '`)', self.children[0].left_to_right_token())
f_node = f_node.constructors[0]
elif type(f_node) == ASTTypeAlias and len(f_node.named_tuple_members) > 0:
f_node = f_node.constructor
last_function_arg = 0
res = func_name + '('
for i in range(1, len(self.children), 2):
make_ref = self.children[i+1].symbol.id in ('&', 'T &') and len(self.children[i+1].children) == 1 and (self.children[i+1].children[0].is_list
or self.children[i+1].children[0].is_dict
or self.children[i+1].children[0].function_call)
if self.children[i] is None:
cstr = self.children[i+1].to_str()
if f_node is not None and type(f_node) == ASTFunctionDefinition:
if last_function_arg >= len(f_node.function_arguments):
raise Error('too many arguments for function `' + func_name + '`', self.children[0].left_to_right_token())
if f_node.first_named_only_argument is not None and last_function_arg >= f_node.first_named_only_argument:
raise Error('argument `' + f_node.function_arguments[last_function_arg].outer_name + '` of function `' + func_name + '` is named-only', self.children[i+1].token)
if f_node.function_arguments[last_function_arg].qualifier == '&' and not (self.children[i+1].symbol.id in ('&', 'T &') and len(self.children[i+1].children) == 1) and self.children[i+1].token_str() not in ('N', 'Н', 'null', 'нуль'):
raise Error('argument `' + f_node.function_arguments[last_function_arg].outer_name + '` of function `' + func_name + '` is in-out, but there is no `&` prefix', self.children[i+1].token)
if f_node.function_arguments[last_function_arg].type_name == 'File?':
tid = self.scope.find(self.children[i+1].token_str())
if tid is None or tid.type != 'File?':
res += '&'
elif f_node.function_arguments[last_function_arg].type_name.endswith('?') and f_node.function_arguments[last_function_arg].type_name.startswith('[') and cstr != 'nullptr': # ] #f_node.function_arguments[last_function_arg].type_name != 'Int?' and not cstr.startswith(('std::make_unique<', 'make_SharedPtr<')):
res += '&'
tid = self.scope.find(cstr)
if tid is not None and tid.default_val == 'nullptr':
res = res[:-1] # res -= '&'
elif f_node.function_arguments[last_function_arg].type_name == 'Char':
if self.children[i+1].token.category == Token.Category.STRING_LITERAL:
assert(cstr.startswith('u"') and cstr.endswith('"_S'))
cstr = "u'" + cstr[2:-3] + "'_C"
res += 'make_ref('*make_ref + cstr + ')'*make_ref
last_function_arg += 1
else:
if f_node is None or type(f_node) != ASTFunctionDefinition:
raise Error('function `' + func_name + '` is not found (you can remove named arguments in function call to suppress this error)', self.children[0].left_to_right_token())
argument_name = self.children[i].token_str()[:-1]
if argument_name == '':
if self.children[i+1].token.category != Token.Category.NAME:
raise Error('variable name expected for implicit named argument', self.children[i+1].token)
argument_name = self.children[i+1].token_str()
while True:
if last_function_arg == len(f_node.function_arguments):
for arg in f_node.function_arguments:
if arg.outer_name == argument_name:
raise Error('please correct order of argument `' + argument_name + '`', self.children[i].token)
raise Error('argument `' + argument_name + '` is not found in function `' + func_name + '`', self.children[i].token)
if f_node.function_arguments[last_function_arg].outer_name == argument_name:
if f_node.function_arguments[last_function_arg].qualifier == '&' and not (self.children[i+1].symbol.id in ('&', 'T &') and len(self.children[i+1].children) == 1) and self.children[i+1].token_str() not in ('N', 'Н', 'null', 'нуль'):
raise Error('argument `' + f_node.function_arguments[last_function_arg].outer_name + '` of function `' + func_name + '` is in-out, but there is no `&` prefix', self.children[i+1].token)
last_function_arg += 1
break
if f_node.function_arguments[last_function_arg].default_value == '':
raise Error('argument `' + f_node.function_arguments[last_function_arg].outer_name + '` of function `' + func_name + '` has no default value, please specify its value here', self.children[i].token)
res += f_node.function_arguments[last_function_arg].default_value + ', '
last_function_arg += 1
if f_node.function_arguments[last_function_arg-1].type_name.endswith('?') and not '->' in f_node.function_arguments[last_function_arg-1].type_name and self.children[i+1].token_str() not in ('N', 'Н', 'null', 'нуль'):
res += '&'
res += 'make_ref('*make_ref + self.children[i+1].to_str() + ')'*make_ref
if i < len(self.children)-2:
res += ', '
if f_node is not None:
if type(f_node) == ASTFunctionDefinition:
while last_function_arg < len(f_node.function_arguments):
if f_node.function_arguments[last_function_arg].default_value == '':
t = self.children[len(self.children)-1].rightmost()
raise Error('missing required argument `'+ f_node.function_arguments[last_function_arg].outer_name + '`', Token(t, t, Token.Category.DELIMITER))
last_function_arg += 1
elif type(f_node) in (ASTTypeEnum, ASTTypeAlias, ASTTypeDefinition):
pass
elif f_node.function_pointer:
if last_function_arg != len(f_node.type_args):
raise Error('wrong number of arguments passed to function pointer', Token(self.children[0].token.end, self.children[0].token.end, Token.Category.DELIMITER))
return res + ')'
elif self.tuple:
res = 'make_tuple('
for i in range(len(self.children)):
res += self.children[i].to_str()
if i < len(self.children)-1:
res += ', '
return res + ')'
elif self.is_var_decl:
assert(self.children[0].symbol.id == '=' and self.children[0].children[0].token.category == Token.Category.NAME)
return self.children[0].children[0].token_str()
else:
assert(len(self.children) == 1)
if self.children[0].symbol.id in ('..', '.<', '.+', '<.', '<.<'): # чтобы вместо `(range_el(0, seq.len()))` было `range_el(0, seq.len())`
return self.children[0].to_str()
return '(' + self.children[0].to_str() + ')'
elif self.symbol.id == '[': # ]
if self.is_list:
if len(self.children) == 0:
raise Error('empty array is not supported', self.left_to_right_token())
type_of_values_is_char = True
for child in self.children:
if not is_char(child):
type_of_values_is_char = False
break
el_type = ''
if len(self.children) > 1 and self.children[0].function_call and self.children[0].children[0].token_str()[0].isupper() and self.children[0].children[0].token_str() not in ('Array', 'Set'):
el_type = trans_type(self.children[0].children[0].token_str(), self.scope, self.children[0].children[0].token)
res = 'create_array'
if self.parent is not None and self.parent.symbol.id == '-':
res += '_fix_len<' + str(len(self.children))
if el_type != '':
res += ', ' + el_type
res += '>'
else:
if el_type != '':
res += '<' + el_type + '>'
res += '({'
for i in range(len(self.children)):
res += char_or_str(self.children[i], type_of_values_is_char)
if i < len(self.children)-1:
res += ', '
return res + '})'
elif self.is_dict:
char_key = True
char_val = True
for child in self.children:
assert(child.symbol.id == '=')
if not is_char(child.children[0]):
char_key = False
if not is_char(child.children[1]):
char_val = False
res = 'create_dict(dict_of'
for child in self.children:
c0 = child.children[0]
if c0.symbol.id == '.' and len(c0.children) == 2 and c0.children[1].token_str().isupper():
c0str = c0.to_str().replace('.', '::') # replace `python_to_11l:tokenizer:Token.Category.NAME` with `python_to_11l::tokenizer::Token::Category::NAME`
else:
c0str = char_or_str(c0, char_key)
res += '(' + c0str + ', ' + char_or_str(child.children[1], char_val) + ')'
return res + ')'
elif self.children[1].token.category == Token.Category.NUMERIC_LITERAL:
return '_get<' + self.children[1].to_str() + '>(' + self.children[0].to_str() + ')' # for support tuples (e.g. `(1, 2)[0]` -> `_get<0>(make_tuple(1, 2))`)
else:
c1 = self.children[1].to_str()
if c1.startswith('(len)'):
return self.children[0].to_str() + '.at_plus_len(' + c1[len('(len)'):] + ')'
return self.children[0].to_str() + '[' + c1 + ']'
elif self.symbol.id == '[%': # ]
return self.children[0].to_str() + '.at_ni(' + self.children[1].to_str() + ')'
elif self.symbol.id == '->' and len(self.children) == 0:
return 'it'
elif self.symbol.id in ('S', 'В', 'switch', 'выбрать'):
char_val = True
for i in range(1, len(self.children), 2):
if not is_char(self.children[i+1]):
char_val = False
res = '[&](const auto &a){return ' # `[&]` is for `cc = {'а':'A','б':'B','с':'C','д':'D','е':'E','ф':'F'}.get(c.lower(), c)` -> `[&](const auto &a){return a == u'а'_C ? u"A"_S : ... : c;}(c.lower())`
was_break = False
for i in range(1, len(self.children), 2):
if self.children[i].token.value(source) in ('E', 'И', 'else', 'иначе'):
res += char_or_str(self.children[i+1], char_val)
was_break = True
break
if self.children[i].symbol.id in ('..', '.<', '.+', '<.', '<.<'):
res += 'in(a, ' + self.children[i].to_str() + ')'
elif self.children[i].symbol.id in ('<', '<=', '>', '>='):
res += 'a ' + self.children[i].symbol.id + ' ' + self.children[i].children[0].to_str()
else:
res += 'a == ' + (char_or_str(self.children[i], is_char(self.children[i]))[:-2] if self.children[i].token.category == Token.Category.STRING_LITERAL else self.children[i].to_str())
res += ' ? ' + char_or_str(self.children[i+1], char_val) + ' : '
# L.was_no_break
# res ‘’= ‘throw KeyError(a)’