-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathts2pythonParser.py
More file actions
executable file
·1895 lines (1690 loc) · 89.6 KB
/
ts2pythonParser.py
File metadata and controls
executable file
·1895 lines (1690 loc) · 89.6 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
#!/usr/bin/env python3
"""ts2python.py - compiles Typescript dataclasses to Python
TypedDicts <https://www.python.org/dev/peps/pep-0589/>
Copyright 2021 by Eckhart Arnold (arnold@badw.de)
Bavarian Academy of Sciences and Humanities (badw.de)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
"""
#######################################################################
#
# SYMBOLS SECTION - Can be edited. Changes will be preserved.
#
#######################################################################
import datetime
import keyword
from functools import partial, lru_cache
import os
import sys
from typing import Tuple, List, Union, Any, Callable, Set, Dict, Sequence, \
Optional
try:
scriptpath = os.path.abspath(os.path.dirname(__file__))
except NameError:
scriptpath = ''
if scriptpath not in sys.path:
sys.path.append(scriptpath)
from DHParser.compile import Compiler, compile_source, Junction, full_compile
from DHParser.configuration import set_config_value, get_config_value, get_config_values, \
access_presets, finalize_presets, set_preset_value, get_preset_value, NEVER_MATCH_PATTERN, \
get_config_values, read_local_config,ALLOWED_PRESET_VALUES, dump_config_data
from DHParser import dsl
from DHParser.dsl import recompile_grammar, never_cancel
from DHParser.ebnf import grammar_changed
from DHParser.error import ErrorCode, Error, canonical_error_strings, has_errors, NOTICE, \
WARNING, ERROR, FATAL
from DHParser.log import start_logging, suspend_logging, resume_logging
from DHParser.nodetree import Node, WHITESPACE_PTYPE, TOKEN_PTYPE, RootNode, Path, pick_from_path, \
node_names
from DHParser.parse import Grammar, PreprocessorToken, Whitespace, Drop, AnyChar, Parser, \
Lookbehind, Lookahead, Alternative, Pop, Text, Synonym, Counted, Interleave, INFINITE, ERR, \
Option, NegativeLookbehind, OneOrMore, RegExp, Retrieve, Series, Capture, TreeReduction, \
ZeroOrMore, Forward, NegativeLookahead, Required, CombinedParser, Custom, mixin_comment, \
last_value, matching_bracket, optional_last_value, SmartRE, RX_NEVER_MATCH
from DHParser.pipeline import create_parser_junction, create_preprocess_junction, \
create_junction, PseudoJunction, full_pipeline, end_points, PipelineResult
from DHParser.preprocess import nil_preprocessor, PreprocessorFunc, PreprocessorResult, \
gen_find_include_func, preprocess_includes, make_preprocessor, chain_preprocessors
from DHParser.stringview import StringView
from DHParser.toolkit import re, is_filename, load_if_file, cpu_count, \
ThreadLocalSingletonFactory, expand_table, md5, as_list, static
from DHParser.trace import set_tracer, resume_notices_on, trace_history
from DHParser.transform import is_empty, remove_if, TransformationDict, TransformerFunc, \
transformation_factory, remove_children_if, move_fringes, normalize_whitespace, \
is_anonymous, name_matches, reduce_single_child, replace_by_single_child, replace_or_reduce, \
remove_whitespace, replace_by_children, remove_empty, remove_tokens, flatten, all_of, \
any_of, transformer, merge_adjacent, collapse, collapse_children_if, transform_result, \
remove_children, remove_content, remove_brackets, change_name, remove_anonymous_tokens, \
keep_children, is_one_of, not_one_of, content_matches, apply_if, peek, \
remove_anonymous_empty, keep_nodes, traverse_locally, strip, lstrip, rstrip, \
replace_content_with, forbid, assert_content, remove_infix_operator, add_error, error_on, \
left_associative, lean_left, node_maker, has_descendant, neg, has_ancestor, insert, \
positions_of, replace_child_names, add_attributes, delimit_children, merge_connected, \
has_attr, has_parent, has_children, has_child, apply_unless, apply_ifelse, traverse, \
TransformerCallable
from DHParser import parse as parse_namespace__
version = "0.8.2"
#######################################################################
#
# PREPROCESSOR SECTION - Can be edited. Changes will be preserved.
#
#######################################################################
# To capture includes, replace the NEVER_MATCH_PATTERN
# by a pattern with group "name" here, e.g. r'\input{(?P<name>.*)}'
RE_INCLUDE = NEVER_MATCH_PATTERN
RE_COMMENT = '(?:\\/\\/.*)|(?:\\/\\*(?:.|\\n)*?\\*\\/)'
def ts2pythonTokenizer(original_text) -> Tuple[str, List[Error]]:
# Here, a function body can be filled in that adds preprocessor tokens
# to the source code and returns the modified source.
return original_text, []
# def preprocessor_factory() -> PreprocessorFunc:
# # below, the second parameter must always be the same as ts2pythonGrammar.COMMENT__!
# find_next_include = gen_find_include_func(RE_INCLUDE, '(?:\\/\\/.*)|(?:\\/\\*(?:.|\\n)*?\\*\\/)')
# include_prep = partial(preprocess_includes, find_next_include=find_next_include)
# tokenizing_prep = make_preprocessor(ts2pythonTokenizer)
# return chain_preprocessors(include_prep, tokenizing_prep)
#
#
# get_preprocessor = ThreadLocalSingletonFactory(preprocessor_factory)
preprocessing: PseudoJunction = create_preprocess_junction(
ts2pythonTokenizer, RE_INCLUDE, RE_COMMENT)
#######################################################################
#
# PARSER SECTION - Don't edit! CHANGES WILL BE OVERWRITTEN!
#
#######################################################################
class ts2pythonGrammar(Grammar):
r"""Parser for a ts2python document.
Instantiate this class and then call the instance with the
source code as argument in order to use the parser, e.g.:
parser = ts2python()
syntax_tree = parser(source_code)
"""
arg_list = Forward()
declaration = Forward()
declarations_block = Forward()
document = Forward()
function = Forward()
generic_type = Forward()
literal = Forward()
type = Forward()
types = Forward()
source_hash__ = "95673a7df727cc16cf2fc10e84222160"
early_tree_reduction__ = CombinedParser.MERGE_TREETOPS
disposable__ = re.compile('(?:FRAC$|EXP$|EOF$|_top_level_literal$|INT$|_reserved$|NEG$|_part$|_top_level_assignment$|_quoted_identifier$|_keyword$|DOT$|_namespace$|_array_ellipsis$)')
static_analysis_pending__ = [] # type: List[bool]
parser_initialization__ = ["upon instantiation"]
COMMENT__ = r'(?://.*)\n?|(?:/\*(?:.|\n)*?\*/) *\n?'
comment_rx__ = re.compile(COMMENT__)
WHITESPACE__ = r'\s*'
WSP_RE__ = mixin_comment(whitespace=WHITESPACE__, comment=COMMENT__)
wsp__ = Whitespace(WSP_RE__)
dwsp__ = Drop(Whitespace(WSP_RE__, keep_comments=True))
EOF = Drop(SmartRE(f'(?!.)', '!/./'))
EXP = Option(SmartRE(f'(?P<:Text>E|e)(?:(?P<:Text>\\+|\\-)?)([0-9]+)', '`E`|`e` [`+`|`-`] /[0-9]+/'))
DOT = Text(".")
FRAC = Option(Series(DOT, RegExp('[0-9]+')))
NEG = Text("-")
INT = Series(Option(NEG), SmartRE(f'([1-9][0-9]+|[0-9])', '/[1-9][0-9]+/|/[0-9]/'))
_reserved = Drop(SmartRE(f'(?P<:Text>true|false)', '`true`|`false`'))
_part = RegExp('(?!\\d)\\w+')
identifier = Series(NegativeLookahead(_reserved), _part, dwsp__)
name = Series(NegativeLookahead(_reserved), _part, ZeroOrMore(Series(Text("."), _part)), dwsp__)
_quoted_identifier = Alternative(identifier, Series(Series(Drop(Text('"')), dwsp__), identifier, Series(Drop(Text('"')), dwsp__), mandatory=2), Series(Series(Drop(Text("\'")), dwsp__), identifier, Series(Drop(Text("\'")), dwsp__), mandatory=2))
variable = Synonym(name)
basic_type = SmartRE(f'(?P<:Text>object|array|string|number|boolean|null|integer|uinteger|decimal|unknown|any|void)(?P<comment__>{WSP_RE__})', '`object`|`array`|`string`|`number`|`boolean`|`null`|`integer`|`uinteger`|`decimal`|`unknown`|`any`|`void` ~')
key = Alternative(identifier, Series(Series(Drop(Text('"')), dwsp__), identifier, Series(Drop(Text('"')), dwsp__)))
association = Series(key, Series(Drop(Text(":")), dwsp__), literal, mandatory=1)
object = Series(Series(Drop(Text("{")), dwsp__), Option(Series(association, ZeroOrMore(Series(Series(Drop(Text(",")), dwsp__), association)))), Option(Series(Drop(Text(",")), dwsp__)), Series(Drop(Text("}")), dwsp__))
array = Series(Series(Drop(Text("[")), dwsp__), Option(Series(literal, ZeroOrMore(Series(Series(Drop(Text(",")), dwsp__), literal)))), Series(Drop(Text("]")), dwsp__))
string = SmartRE(f'("[^"\\n]*")(?P<comment__>{WSP_RE__})|(\'[^\'\\n]*\')(?P<comment__>{WSP_RE__})', '/"[^"\\n]*"/ ~|/\'[^\'\\n]*\'/ ~')
boolean = SmartRE(f'(?P<:Text>true|false)(?P<comment__>{WSP_RE__})', '`true`|`false` ~')
number = Series(INT, FRAC, EXP, dwsp__)
integer = Series(INT, SmartRE(f'(?![.Ee])', '!/[.Ee]/'), dwsp__)
type_name = Synonym(name)
_top_level_literal = Drop(Synonym(literal))
_array_ellipsis = Drop(Series(literal, ZeroOrMore(Series(Series(Drop(Text(",")), dwsp__), literal))))
assignment = Series(variable, Series(Drop(Text("=")), dwsp__), Alternative(literal, variable), Option(Series(Drop(Text(";")), dwsp__)))
_top_level_assignment = Drop(Synonym(assignment))
const = Series(Option(Series(Drop(Text("export")), dwsp__)), Series(Drop(Text("const")), dwsp__), declaration, Option(Series(Series(Drop(Text("=")), dwsp__), Alternative(literal, identifier))), Option(Series(Drop(Text(";")), dwsp__)), mandatory=2)
item = Series(_quoted_identifier, Option(Series(Series(Drop(Text("=")), dwsp__), literal)))
enum = Series(Option(Series(Drop(Text("export")), dwsp__)), Series(Drop(Text("enum")), dwsp__), identifier, Series(Drop(Text("{")), dwsp__), item, ZeroOrMore(Series(Series(Drop(Text(",")), dwsp__), item)), Option(Series(Drop(Text(",")), dwsp__)), Series(Drop(Text("}")), dwsp__), mandatory=3)
keyof = Series(Text("keyof"), dwsp__)
optional = Series(Text("?"), dwsp__)
readonly = Series(Text("readonly"), dwsp__)
func_type = Series(Option(Series(Drop(Text("new")), dwsp__)), Series(Drop(Text("(")), dwsp__), Option(arg_list), Series(Drop(Text(")")), dwsp__), Series(Drop(Text("=>")), dwsp__), types)
extends = Series(SmartRE(f'(?:extends)(?P<comment__>{WSP_RE__})|(?:implements)(?P<comment__>{WSP_RE__})', '"extends"|"implements"'), Alternative(generic_type, type_name), ZeroOrMore(Series(Series(Drop(Text(",")), dwsp__), Alternative(generic_type, type_name))))
index_signature = Series(Option(readonly), Series(Drop(Text("[")), dwsp__), identifier, Alternative(Series(Drop(Text(":")), dwsp__), Series(Option(Series(Drop(Text("in")), dwsp__)), keyof), Series(Drop(Text("in")), dwsp__)), type, Series(Drop(Text("]")), dwsp__), Option(optional))
map_signature = Series(index_signature, Series(Drop(Text(":")), dwsp__), types)
mapped_type = Series(Series(Drop(Text("{")), dwsp__), map_signature, Option(Series(Drop(Text(";")), dwsp__)), Series(Drop(Text("}")), dwsp__))
extends_type = Series(Series(Drop(Text("extends")), dwsp__), Option(keyof), Alternative(basic_type, type_name, mapped_type))
declarations_tuple = Series(Series(Drop(Text("[")), dwsp__), declaration, ZeroOrMore(Series(Series(Drop(Text(",")), dwsp__), declaration)), Series(Drop(Text("]")), dwsp__))
type_tuple = Series(Series(Drop(Text("[")), dwsp__), types, ZeroOrMore(Series(Series(Drop(Text(",")), dwsp__), types)), Series(Drop(Text("]")), dwsp__))
indexed_type = Series(type_name, Series(Drop(Text("[")), dwsp__), Alternative(type_name, literal), Series(Drop(Text("]")), dwsp__))
array_type = Alternative(basic_type, generic_type, type_name, Series(Series(Drop(Text("(")), dwsp__), types, Series(Drop(Text(")")), dwsp__)), type_tuple, declarations_block)
array_types = Synonym(array_type)
array_of = Series(array_types, Series(Drop(Text("[]")), dwsp__))
equals_type = Series(Series(Drop(Text("=")), dwsp__), Alternative(basic_type, type_name))
parameter_type = Series(Option(readonly), Alternative(array_of, basic_type, generic_type, indexed_type, Series(type_name, Option(extends_type), Option(equals_type)), declarations_block, type_tuple, declarations_tuple))
parameter_types = Series(Option(Series(Drop(Text("|")), dwsp__)), parameter_type, ZeroOrMore(Series(Series(Drop(Text("|")), dwsp__), parameter_type)))
type_parameters = Series(Series(Drop(Text("<")), dwsp__), parameter_types, ZeroOrMore(Series(Series(Drop(Text(",")), dwsp__), parameter_types)), Series(Drop(Text(">")), dwsp__), mandatory=1)
type_alias = Series(Option(Series(Drop(Text("export")), dwsp__)), Series(Drop(Text("type")), dwsp__), identifier, Option(type_parameters), Series(Drop(Text("=")), dwsp__), types, Option(Series(Drop(Text(";")), dwsp__)), mandatory=2)
alias = Synonym(identifier)
wildcard = Series(Series(Drop(Text("*")), dwsp__), Series(Drop(Text("as")), dwsp__), alias)
intersection = Series(type, OneOrMore(Series(Series(Drop(Text("&")), dwsp__), type, mandatory=1)))
symbol = Series(Option(Series(Drop(Text("type")), dwsp__)), identifier, Option(Series(Series(Drop(Text("as")), dwsp__), alias)))
interface = Series(Option(Series(Drop(Text("export")), dwsp__)), Option(Series(Drop(Text("declare")), dwsp__)), SmartRE(f'(?:interface)(?P<comment__>{WSP_RE__})|(?:class)(?P<comment__>{WSP_RE__})', '"interface"|"class"'), identifier, Option(type_parameters), Option(extends), declarations_block, Option(Series(Drop(Text(";")), dwsp__)), mandatory=3)
namespace = Series(Option(Series(Drop(Text("export")), dwsp__)), Series(Drop(Text("namespace")), dwsp__), identifier, Series(Drop(Text("{")), dwsp__), ZeroOrMore(Alternative(interface, type_alias, enum, const, Series(declaration, Option(Series(Drop(Text(";")), dwsp__))), Series(function, Option(Series(Drop(Text(";")), dwsp__))))), Series(Drop(Text("}")), dwsp__), mandatory=2)
static = Series(Text("static"), dwsp__)
virtual_enum = Series(Option(Series(Drop(Text("export")), dwsp__)), Series(Drop(Text("namespace")), dwsp__), identifier, Series(Drop(Text("{")), dwsp__), ZeroOrMore(Alternative(interface, type_alias, enum, const, Series(declaration, Option(Series(Drop(Text(";")), dwsp__))))), Series(Drop(Text("}")), dwsp__))
qualifiers = Interleave(readonly, static, Series(Drop(Text('public')), dwsp__), Series(Drop(Text('protected')), dwsp__), Series(Drop(Text('private')), dwsp__), repetitions=[(0, 1), (0, 1), (0, 1), (0, 1), (0, 1)])
_keyword = Drop(SmartRE(f'(?P<:Text>readonly|function|const|public|private|protected)(?!\\w)', '`readonly`|`function`|`const`|`public`|`private`|`protected` !/\\w/'))
special = Series(Series(Drop(Text("[")), dwsp__), name, Series(Drop(Text("]")), dwsp__), Series(Drop(Text("(")), dwsp__), Option(arg_list), Series(Drop(Text(")")), dwsp__), Option(Series(Series(Drop(Text(":")), dwsp__), types, mandatory=1)), mandatory=4)
argument = Series(identifier, Option(optional), Option(Series(Series(Drop(Text(":")), dwsp__), types, mandatory=1)))
arg_tail = Series(Series(Drop(Text("...")), dwsp__), identifier, Option(Series(Series(Drop(Text(":")), dwsp__), Alternative(array_of, generic_type), mandatory=1)))
symList = Series(Series(Drop(Text("{")), dwsp__), symbol, ZeroOrMore(Series(Series(Drop(Text(",")), dwsp__), symbol)), Series(Drop(Text("}")), dwsp__))
importList = Series(Alternative(symList, identifier), ZeroOrMore(Series(Series(Drop(Text(",")), dwsp__), Alternative(symList, identifier))))
Import = Series(Series(Drop(Text("import")), dwsp__), Option(Series(Alternative(wildcard, importList), Series(Drop(Text("from")), dwsp__))), string)
module = Series(Series(Drop(Text("declare")), dwsp__), Series(Drop(Text("module")), dwsp__), _quoted_identifier, Series(Drop(Text("{")), dwsp__), document, Series(Drop(Text("}")), dwsp__))
_namespace = Alternative(virtual_enum, namespace)
literal.set(Alternative(integer, number, boolean, string, array, object))
generic_type.set(Series(type_name, type_parameters))
type.set(Series(Option(readonly), Alternative(array_of, basic_type, generic_type, indexed_type, Series(type_name, NegativeLookahead(Text("("))), Series(Series(Drop(Text("(")), dwsp__), types, Series(Drop(Text(")")), dwsp__)), mapped_type, declarations_block, type_tuple, declarations_tuple, literal, func_type)))
types.set(Series(Option(Series(Drop(Text("|")), dwsp__)), Alternative(intersection, type), ZeroOrMore(Series(Series(Drop(Text("|")), dwsp__), Alternative(intersection, type)))))
arg_list.set(Series(Alternative(Series(argument, ZeroOrMore(Series(Series(Drop(Text(",")), dwsp__), argument)), Option(Series(Series(Drop(Text(",")), dwsp__), arg_tail))), arg_tail), Option(Series(Drop(Text(",")), dwsp__))))
function.set(Alternative(Series(Option(Series(Option(Series(Drop(Text("export")), dwsp__)), qualifiers, Option(Series(Drop(Text("function")), dwsp__)), NegativeLookahead(_keyword), identifier, Option(optional), Option(type_parameters))), Series(Drop(Text("(")), dwsp__), Option(arg_list), Series(Drop(Text(")")), dwsp__), Option(Series(Series(Drop(Text(":")), dwsp__), types, mandatory=1)), mandatory=2), special))
declaration.set(Series(Option(Series(Drop(Text("export")), dwsp__)), qualifiers, Option(SmartRE(f'(?:let)(?P<comment__>{WSP_RE__})|(?:var)(?P<comment__>{WSP_RE__})', '"let"|"var"')), NegativeLookahead(_keyword), identifier, Option(optional), NegativeLookahead(Text("(")), Option(Series(Series(Drop(Text(":")), dwsp__), types, mandatory=1))))
declarations_block.set(Series(Series(Drop(Text("{")), dwsp__), Option(Series(Alternative(function, declaration), ZeroOrMore(Series(Option(SmartRE(f'(?:;)(?P<comment__>{WSP_RE__})|(?:,)(?P<comment__>{WSP_RE__})', '";"|","')), Alternative(function, declaration))), Option(SmartRE(f'(?:;)(?P<comment__>{WSP_RE__})|(?:,)(?P<comment__>{WSP_RE__})', '";"|","')))), Option(Series(map_signature, Option(SmartRE(f'(?:;)(?P<comment__>{WSP_RE__})|(?:,)(?P<comment__>{WSP_RE__})', '";"|","')))), Series(Drop(Text("}")), dwsp__)))
document.set(Series(dwsp__, ZeroOrMore(Alternative(interface, type_alias, _namespace, enum, const, module, _top_level_assignment, _array_ellipsis, _top_level_literal, Series(Import, Option(Series(Drop(Text(";")), dwsp__))), Series(function, Option(Series(Drop(Text(";")), dwsp__))), Series(declaration, Option(Series(Drop(Text(";")), dwsp__)))))))
root = Series(document, EOF)
resume_rules__ = {'interface': [re.compile(r'(?=export|$)')],
'type_alias': [re.compile(r'(?=export|$)')],
'enum': [re.compile(r'(?=export|$)')],
'const': [re.compile(r'(?=export|$)')],
'declaration': [re.compile(r'(?=export|$)')],
'_top_level_assignment': [re.compile(r'(?=export|$)')],
'_top_level_literal': [re.compile(r'(?=export|$)')],
'module': [re.compile(r'(?=export|$)')]}
root__ = root
parsing: PseudoJunction = create_parser_junction(ts2pythonGrammar)
get_grammar = parsing.factory # for backwards compatibility, only
try:
assert RE_INCLUDE == NEVER_MATCH_PATTERN or \
RE_COMMENT in (ts2pythonGrammar.COMMENT__, NEVER_MATCH_PATTERN), \
"Please adjust the pre-processor-variable RE_COMMENT in file ts2pythonParser.py so that " \
"it either is the NEVER_MATCH_PATTERN or has the same value as the COMMENT__-attribute " \
"of the grammar class ts2pythonGrammar! " \
'Currently, RE_COMMENT reads "%s" while COMMENT__ is "%s". ' \
% (RE_COMMENT, ts2pythonGrammar.COMMENT__) + \
"\n\nIf RE_COMMENT == NEVER_MATCH_PATTERN then includes will deliberately be " \
"processed, otherwise RE_COMMENT==ts2pythonGrammar.COMMENT__ allows the " \
"preprocessor to ignore comments."
except (AttributeError, NameError):
pass
#######################################################################
#
# AST SECTION - Can be edited. Changes will be preserved.
#
#######################################################################
SPECIAL_FUNCTIONS = {"Symbol.iterator": "__iter__"}
def convert_special_function(p: Path):
node = p[-1]
assert node.name == "special"
identifier = node['name']
identifier.name = "identifier"
identifier.result = SPECIAL_FUNCTIONS.get(identifier.content, "__unknown__")
def add_flags(p: Path):
p[0].attr['keep_comments'] = get_config_value('ts2python.KeepMultilineComments', False)
def clear_flags(p: Path):
p[0].attr = dict()
ts2python_AST_transformation_table = {
# AST Transformations for the ts2python-grammar
# "<": flatten,
"<<<": add_flags,
":Text": change_name('TEXT'),
"comment__": remove_if(lambda p: p[-1].content.rfind('\n') < 0 \
or not p[0].get_attr('keep_comments', True)),
"special": [apply_if(add_error("Unknown special function"),
lambda p: p[-1]['name'].content not in SPECIAL_FUNCTIONS),
convert_special_function],
"function": apply_if(reduce_single_child, has_child('special')),
"alias": reduce_single_child,
"document, root": [], # declarations_block? # ensures that the transfomations under "*" are not applied, here!
"*": move_fringes(lambda p: p[-1].name == "comment__", side="right"),
">>>": clear_flags
}
def ts2pythonTransformer() -> TransformerCallable:
"""Creates a transformation function that does not share state with other
threads or processes."""
return static(partial(transformer,
transformation_table=ts2python_AST_transformation_table.copy(),
src_stage='CST', dst_stage='AST'))
ASTTransformation: Junction = Junction(
'CST', ThreadLocalSingletonFactory(ts2pythonTransformer), 'AST')
#######################################################################
#
# COMPILER SECTION - Can be edited. Changes will be preserved.
#
#######################################################################
def dump_configuration() -> str:
return f"""[ts2python]
RenderAnonymous = {get_config_value('ts2python.RenderAnonymous', 'local')}
UseEnum = {get_config_value('ts2python.UseEnum', True)}
UsePostponedEvaluation = {get_config_value('ts2python.UsePostponedEvaluation', True)}
UseTypeUnion = {get_config_value('ts2python.UseTypeUnion', False)}
UseExplicitTypeAlias = {get_config_value('ts2python.UseExplicitTypeAlias', False)}
UseTypeParameters = {get_config_value('ts2python.UseTypeParameters', False)}
UseLiteralType = {get_config_value('ts2python.UseLiteralType', False)}
UseVariadicGenerics = {get_config_value('ts2python.UseVariadicGenerics', False)}
UseNotRequired = {get_config_value('ts2python.UseNotRequired', False)}
AllowReadOnly = {get_config_value('ts2python.AllowReadOnly', False)}
AssumeDeferredEvaluation = {get_config_value('ts2python.AssumeDeferredEvaluation', False)}
KeepMultilineComments = {get_config_value('ts2python.KeepMultilineComments', False)}"""
def required_python_version(ts2python_cfg: Dict[str, bool],
purpose: str = "compatibility") -> Tuple[int, int]:
assert purpose in ("compatibility", "features")
min_version = (3, 7)
if ts2python_cfg.get('ts2python.UseLiteralType', False):
min_version = (3, 8)
if ts2python_cfg.get('ts2python.UseTypeUnion', False):
min_version = (3, 10)
elif ts2python_cfg.get('ts2python.UseExplicitTypeAlias', False):
min_version = (3, 10)
if ts2python_cfg.get('ts2python.UseVariadicGenerics', False):
min_version = (3, 11)
elif ts2python_cfg.get('ts2python.UseNotRequired', False) \
and purpose == "features":
min_version = (3, 11)
if ts2python_cfg.get('ts2python.UseTypeParameters', False):
min_version = (3, 12)
if ts2python_cfg.get('ts2python.AllowReadOnly', False) \
and purpose == "features":
min_version = (3, 13)
if ts2python_cfg.get('ts2python.AssumeDeferredEvaluation', False):
min_version = (3, 14)
# Neither UseReadOnly nor UseNotRequired place any demand on the
# Python version, because:
# ReadOnly can be defined as Union for Python-version < 3.13
# NotRequired can be defined as Optional for Python-version < 3.11
return min_version
def set_compatibility_level(version_info: Tuple[int, ...] = (3, 7),
config_or_preset: str = "preset"):
if config_or_preset == "preset":
set_value = set_preset_value
else:
assert config_or_preset == "config"
set_value = set_config_value
if not version_info >= (3, 7):
print('Compatibility version must be >= 3.7')
sys.exit(1)
if version_info >= (3, 8):
set_value('ts2python.UseLiteralType', True, allow_new_key=True)
if version_info >= (3, 10):
set_value('ts2python.UseTypeUnion', True, allow_new_key=True)
if version_info < (3, 12):
set_value('ts2python.UseExplicitTypeAlias', True, allow_new_key=True)
if version_info >= (3, 11):
set_value('ts2python.UseNotRequired', True, allow_new_key=True)
set_value('ts2python.UseVariadicGenerics', True, allow_new_key=True)
if version_info >= (3, 12):
set_value('ts2python.UseTypeParameters', True, allow_new_key=True)
if version_info >= (3, 13):
set_value('ts2python.AllowReadOnly', True, allow_new_key=True)
if version_info >= (3, 14):
set_value('ts2python.AssumeDeferredEvaluation', True, allow_new_key=True)
set_value('ts2python.UsePostponedEvaluation', False, allow_new_key=True)
def source_hash(source_text: str) -> str:
try:
with open(__file__, 'r', encoding='utf-8') as f:
script = f.read()
except (FileNotFoundError, IOError):
script = "source of ts2pythonParser.py not found!?"
return md5(source_text, script, dump_configuration())
GENERAL_IMPORTS = """
import sys
from enum import Enum, IntEnum"""
TYPE_IMPORTS_37 = """from typing import Union, Optional, Any, Generic, TypeVar, Callable, List, \\
Iterable, Iterator, Tuple, Dict, Awaitable
"""
TYPE_IMPORTS_311 = """from typing import Union, Optional, Any, Generic, TypeVar, Callable, List, \\
Iterable, Iterator, Tuple, Dict, TypedDict, NotRequired, Literal, TypeAlias, \\
Awaitable, Self
try:
from typing import ReadOnly
except ImportError:
ReadOnly = Union
"""
TYPE_IMPORTS_313 = """from typing import Union, Optional, Any, Generic, TypeVar, Callable, List, \\
Iterable, Iterator, Tuple, Dict, TypedDict, NotRequired, Literal, ReadOnly, Awaitable
"""
TYPEDDICT_IMPORTS_37 = """
try:
from ts2python.typeddict_shim import TypedDict, GenericTypedDict, NotRequired, Literal, \\
ReadOnly, TypeAlias
# Override typing.TypedDict for Runtime-Validation
except ImportError:
print("Module ts2python.typeddict_shim not found. Only coarse-grained "
"runtime type-validation of TypedDicts possible")
try:
from typing import TypedDict, Literal
except ImportError:
try:
from ts2python.typing_extensions import TypedDict, Literal
except ImportError:
print(f'Please install the "typing_extensions" module via the shell '
f'command "# pip install typing_extensions" before running '
f'{__file__} with Python-versions <= 3.8!')
try:
from typing_extensions import NotRequired, ReadOnly, TypeAlias
except ImportError:
NotRequired = Optional
ReadOnly = Union
TypeAlias = Any
GenericMeta = type
class _GenericTypedDictMeta(GenericMeta):
def __new__(cls, name, bases, ns, total=True):
return type.__new__(_GenericTypedDictMeta, name, (dict,), ns)
__call__ = dict
GenericTypedDict = _GenericTypedDictMeta('TypedDict', (dict,), {})
GenericTypedDict.__module__ = __name__"""
TYPE_IMPORTS_MAPPING = {(3, 13): [TYPE_IMPORTS_313],
(3, 11): [TYPE_IMPORTS_311],
(3, 9): [TYPE_IMPORTS_37, TYPEDDICT_IMPORTS_37],
(3, 7): [TYPE_IMPORTS_37, TYPEDDICT_IMPORTS_37]}
FUNCTOOLS_IMPORTS = """
try:
from ts2python.singledispatch_shim import singledispatch, singledispatchmethod
except ImportError:
print("ts2python.singledispatch_shim not found! @singledispatch-annotation"
" imported from functools may cause NameErrors on forward-referenced"
" types.")
try:
from functools import singledispatch, singledispatchmethod
except ImportError:
print(f"functools.singledispatchmethod does not exist in Python Version "
f"{sys.version}. This module may therefore fail to run if "
f"singledispatchmethod is needed, anywhere!")
"""
PROMISE_LIKE_CLASS_312 = """class PromiseLike[T]:
def then(self, onfullfilled: Optional[Callable], onrejected: Optional[Callable]) -> Self:
pass
"""
PROMISE_LIKE_CLASS_37 = """PromiseLike = Iterable # Admittedly, a very poor hack"""
def to_typename(varname: str) -> str:
# assert varname[-1:] != '_' or keyword.iskeyword(varname[:-1]), varname # and varname[0].islower()
return varname[0].upper() + varname[1:] + '_'
def to_varname(typename: str) -> str:
assert typename[0].isupper() or typename[-1:] == '_', typename
return typename[0].lower() + (typename[1:-1] if typename[-1:] == '_' else typename[1:])
def to_dict(declarations: str) -> str:
r"""Converts a sequence of declarations to a dictionary.
Example::
>>> decls = "name: str\nversion: int"
>>> print(to_dict(decls))
{"name": str, "version": int}
"""
entries = declarations.split('\n')
for i in range(len(entries)):
k = entries[i].find(":")
assert k >= 0
entries[i] = f'"{entries[i][:k]}"{entries[i][k:]}'
return "".join(["{", ", ".join(entries), "}"])
def is_qualified(name: str) -> bool:
"""Returns True if the given type-name is qualified, e.g.::
>>> is_qualified("T")
False
>>> is_qualified("ReadOnly[T]")
True
"""
return name[-1:] == ']'
def strip_qualifier(qualified_name: str) -> str:
"""Removes qualifiers from type names, e.g.::
>>> qualified_name = "ReadOnly[T]"
>>> strip_qualifier(qualified_name)
'T'
"""
while True:
a = qualified_name.find('[')
b = qualified_name.rfind(']')
if a >= 0:
assert b >= 0, f"unmatched brackets in {qualified_name}"
qualified_name = qualified_name[a + 1:b]
else:
assert b < 0, f"unmatched brackets in {qualified_name}"
return qualified_name
def strip_type_parameters(objname: str) -> str:
"""Removes Type-Parameters from object name, e.g.::
>>> strip_type_parameters("Mapping_0[K, V]")
'Mapping_0'
>>> strip_type_parameters("Mapping_0[K[X, Y], V]")
'Mapping_0'
>>> strip_type_parameters("Mapping_0[K, V[T[A, B]]]")
'Mapping_0'
"""
if objname[-1:] == ']':
b = len(objname) - 1
a = b
while b >= a:
a = objname.rfind('[', 0, a)
b = objname.rfind(']', 0, b)
return objname[:a]
return objname
NOT_YET_IMPLEMENTED_WARNING = ErrorCode(310)
UNSUPPORTED_WARNING = ErrorCode(320)
TYPE_NAME_SUBSTITUTION = {
'object': 'Dict',
'array': 'List',
'string': 'str',
'number': 'float',
'decimal': 'float',
'integer': 'int',
'uinteger': 'int',
'boolean': 'bool',
'null': 'None',
'undefined': 'None',
'unknown': 'Any',
'any': 'Any',
'void': 'None',
'PromiseLike': 'PromiseLike',
'IterableIterator': 'Iterator',
'Array': 'List',
'Record': 'Dict',
'ReadonlyArray': 'List',
'Uint32Array': 'List[int]',
'Error': 'Exception',
'RegExp': 'str' }
class ts2pythonCompiler(Compiler):
"""Compiler for the abstract-syntax-tree of a ts2python source file.
"""
def reset(self):
super().reset()
self.additional_imports = ''
self.require_singledispatch = False
self.base_class_name = "TypedDict"
self.render_anonymous = get_config_value('ts2python.RenderAnonymous', 'local')
if self.render_anonymous not in ('type', 'functional', 'local', 'toplevel'):
raise ValueError(
f'Illegal value "{self.render_anonymous}" for '
f'ts2python.RenderAnonymous. Must be one of "type", '
f'"functional", "local", "toplevel".')
ts2python_cfg = get_config_values('ts2python.*')
self.use_enums = ts2python_cfg.get('ts2python.UseEnum', True)
self.use_postponed_evaluation = ts2python_cfg.get('ts2python.UsePostponedEvaluation', False)
self.use_type_union = ts2python_cfg.get('ts2python.UseTypeUnion', False)
self.use_explicit_type_alias = ts2python_cfg.get('ts2python.UseExplicitTypeAlias', False)
self.use_type_parameters = ts2python_cfg.get('ts2python.UseTypeParameters', False)
if self.use_type_parameters:
self.use_explicit_type_alias = False
self.use_literal_type = ts2python_cfg.get('ts2python.UseLiteralType', False)
self.use_variadic_generics = ts2python_cfg.get('ts2python.UseVariadicGenerics', False)
self.use_not_required = ts2python_cfg.get('ts2python.UseNotRequired', False)
self.allow_read_only = ts2python_cfg.get('ts2python.AllowReadOnly', False)
self.assume_deferred_evaluation = ts2python_cfg.get('ts2python.AssumeDeferredEvaluation', False)
self.keep_comments = ts2python_cfg.get('ts2python.KeepMultilineComments', False)
self.compatibility_level = required_python_version(ts2python_cfg, "compatibility")
self.feature_level = required_python_version(ts2python_cfg, "features")
if self.use_type_parameters and not self.use_variadic_generics:
raise ValueError(
'Configuration flag UseTypeParameters can only be set to True '
'if UseVariadicGenerics is also set to True!')
self.overloaded_type_names: Set[str] = set()
self.known_types: List[Dict[str, str]] = [
{'Union': 'Union', 'List': 'List', 'Tuple': 'Tuple', 'Optional': 'Optional',
'Dict': 'Dict', 'Set': 'Set', 'Any': 'Any', 'Generic': 'Generic',
'Coroutine': 'Coroutine', 'list': 'list', 'tuple': 'tuple', 'dict': 'dict',
'set': 'set', 'frozenset': 'frozenset', 'int': 'int', 'float': 'float',
'str': 'str', 'None': 'None'}]
self.local_classes: List[List[str]] = [[]]
self.base_classes: Dict[str, List[str]] = {}
self.typed_dicts: Set[str] = {'TypedDict'} # names of classes that are TypedDicts
# self.default_values: Dict = {}
# self.referred_objects: Dict = {}
self.basic_type_aliases: Set[str] = set()
self.obj_name: List[str] = ['TOPLEVEL_']
self.scope_type: List[str] = ['']
self.optional_keys: List[List[str]] = [[]]
self.func_name: str = '' # name of the current functions header or ''
self.func_type_parameters: str = '' # type parameters of the current function header, if any
self.strip_type_from_const = False
def compile(self, node) -> str:
result = super().compile(node)
if isinstance(result, str):
return result
raise TypeError(f"Compilation of {node.name} yielded a result of "
f"type {str(type(result))} and not str as expected!")
def is_toplevel(self) -> bool:
return self.obj_name == ['TOPLEVEL_']
def get_known_type(self, typename: str, value: str = "") -> str:
i = typename.find('[')
if i >= 0: typename = typename[:i] # for example, reduces List[str] to List
for type_dict in self.known_types:
if typename in type_dict:
return type_dict[typename]
return value
def add_to_known_types(self, node, typename: str, kind: str):
if typename in self.known_types[-1] and not is_qualified(kind):
self.tree.new_error(
node, f'{node.name} {typename} has already been defined earlier as '
f'{self.known_types[-1][typename]}!', WARNING)
self.known_types[-1][typename] = kind
def prepare(self, root: Node) -> None:
type_aliases = {nd['identifier'].content for nd in root.select_children('type_alias')}
namespaces = {nd['identifier'].content for nd in root.select_children('namespace')}
self.overloaded_type_names = type_aliases & namespaces
self.tree.stage = 'py'
return None
def finalize(self, python_code: Any) -> Any:
chksum = f'source_hash__ = "{source_hash(self.tree.source)}"'
if self.tree.name == 'root':
for py_version, type_imports in TYPE_IMPORTS_MAPPING.items():
if self.compatibility_level >= py_version:
break
else:
raise ValueError(f'Illegal minimal Python version {self.compatibility_level}')
c_major, c_minor = self.compatibility_level
# f_major, f_minor = self.feature_level
code_blocks = [f'# Generated by ts2python version {version} '
f'on {datetime.datetime.now()}\n# compatibility level: '
f'Python {c_major}.{c_minor} and above\n',
# f'# feature level: Python {f_major}.{f_minor}\n',
'from __future__ import annotations' if
self.use_postponed_evaluation else '',
GENERAL_IMPORTS] \
+ type_imports \
+ ([FUNCTOOLS_IMPORTS] if self.require_singledispatch else []) \
+ [self.additional_imports, chksum, '\n##### BEGIN OF ts2python generated code\n']
else:
code_blocks = []
code_blocks.append(python_code)
if self.tree.name == 'root':
code_blocks.append('\n##### END OF ts2python generated code\n')
cooked = '\n\n'.join(code_blocks)
cooked = re.sub(' +(?=\n)', '', cooked)
return re.sub(r'\n\n\n+', '\n\n\n', cooked)
def on_EMPTY__(self, node) -> str:
return ''
def on_ZOMBIE__(self, node) -> str:
self.tree.new_error(node,
"Malformed syntax-tree! Possibly caused by a parsing error.")
return ""
# raise ValueError('Malformed syntax-tree!')
def on_comment__(self, node) -> str:
assert node.content.rfind("\n") >= 0 # inline comments should have been removed
if self.keep_comments:
comment = node.content
multiline = True if re.match(' *\n', comment) else False
comment = comment.strip()
comment = re.sub(r'/\*+\s*|\s*\*/|//[ \t]*', '', comment)
comment = re.sub(r'(?:\n|^)[ \t]*\* ?', '\n', comment).lstrip()
comment = comment.replace("'", chr(0x2bc)) # circumvent possible source of errors in compile_type_expression()!
lines = comment.split('\n')
for i in range(len(lines)):
line = lines[i].strip()
lines[i] = "# " + line if line else ''
comment = '\n'.join(lines)
return f"\n{comment}" if multiline else comment
return ""
def on_root(self, node) -> str:
roots = [child for child in node.children if child.name != 'comment__']
assert len(roots) == 1, node.as_sxpr()
return self.compile(roots[0])
def on_document(self, node) -> str:
if 'module' in node and isinstance(node['module'], Sequence) > 1:
self.tree.new_error(
node, 'Transpiling more than a single ambient module '
'is not yet implemented! Only the first ambient module will '
'be transpiled for now.', NOT_YET_IMPLEMENTED_WARNING)
return self.compile(node['module'][0]['document'])
self.mark_overloaded_functions(node)
return '\n\n'.join(self.compile(child) for child in node.children
if child.name != 'declaration')
def on_module(self, node) -> str:
name = self.compile(node['identifier'])
return self.compile(node['document'])
def on_Import(self, node) -> str:
return "" # For now, ignore imports
def on_symbol(self, node) -> str:
return "" # For the time being
def render_class_header(self, name: str,
base_classes: str,
force_base_class: str = '',
generic_types: str = '') -> str:
assert name
optional_key_list = self.optional_keys[-1]
base_class_name = (force_base_class or self.base_class_name).strip()
tps = generic_types if self.use_type_parameters else ''
if base_class_name == 'TypedDict':
total = not bool(optional_key_list) or self.use_not_required
if base_classes:
td_name = 'TypedDict' if (self.use_variadic_generics or
base_classes.find('Generic[') < 0) \
else 'GenericTypedDict'
if self.use_not_required or total:
return f"class {name}{tps}({base_classes}, {td_name}):\n"
else:
return f"class {name}{tps}({base_classes}, "\
f"{td_name}, total={total}):\n"
else:
tps = generic_types if self.use_type_parameters else ''
if self.use_not_required or total:
return f"class {name}{tps}(TypedDict):\n"
else:
return f"class {name}{tps}(TypedDict, total={total}):\n"
else:
if base_classes:
if base_class_name:
return f"class {name}{tps}({base_classes}, {base_class_name}):\n"
else:
return f"class {name}{tps}({base_classes}):\n"
else:
if base_class_name:
return f"class {name}{tps}({base_class_name}):\n"
else:
return f"class {name}{tps}:\n"
def render_local_classes(self) -> str:
self.func_name = ''
classes = self.local_classes[-1]
return '\n'.join(lc for lc in classes) + '\n' if classes else ''
def process_type_parameters(self, node: Node) -> Tuple[str, str]:
tps = ''
preface = ''
try:
tp = self.compile(node['type_parameters'])
tpl_qualified = [p.replace("'", "") for p in tp.split(', ')] # may contain "ReadOnly[...]"
tpl = [strip_qualifier(p) for p in tpl_qualified]
tps = '[' + ', '.join(p for p in tpl) + ']'
if self.use_type_parameters:
preface = ''
else:
preface = ''.join(f"{p} = TypeVar('{p}')\n"
for p in tpl if not self.get_known_type(p))
for q, p in zip(tpl_qualified, tpl):
self.add_to_known_types(node, p, q if is_qualified(q) else '[]')
except KeyError:
pass
return tps, preface
def on_interface(self, node) -> str:
name = self.compile(node['identifier'])
self.obj_name.append(name)
self.scope_type.append('interface')
self.local_classes.append([])
self.optional_keys.append([])
if self.use_type_parameters: self.known_types.append(dict())
tps, preface = self.process_type_parameters(node)
preface += '\n'
preface += node.get_attr('preface', '')
if not self.use_type_parameters: self.known_types.append(dict())
base_class_list = []
try:
base_class_list = self.bases(node['extends'])
base_classes = ', '.join(base_class_list) # self.compile(node['extends'])
if self.local_classes[-1]:
preface += self.render_local_classes() + '\n'
self.local_classes[-1] = []
if tps and not self.use_variadic_generics:
base_classes += f", Generic{tps}"
except KeyError:
base_classes = f"Generic{tps}" \
if (tps and not self.use_type_parameters
and (not self.use_variadic_generics
or 'function' in node['declarations_block']))\
else ''
if any(bc not in self.typed_dicts for bc in base_class_list):
force_base_class = ' '
elif 'function' in node['declarations_block']:
force_base_class = ' ' # do not derive from TypeDict
else:
force_base_class = ''
self.typed_dicts.add(name)
decls_block = node['declarations_block']
save_render_anonymous = self.render_anonymous
if force_base_class:
self.render_anonymous = "local"
decls_block.attr['no_typed_dict'] = True
decls = self.compile(decls_block)
interface = self.render_class_header(name, base_classes, force_base_class, tps)
self.base_classes[name] = base_class_list
if self.base_class_name == "TypedDict" and self.render_anonymous == "toplevel":
interface = self.render_local_classes() + '\n' + interface
else:
interface += (' ' + self.render_local_classes().replace('\n', '\n ')).rstrip(' ')
self.render_anonymous = save_render_anonymous
self.optional_keys.pop()
self.local_classes.pop()
self.known_types.pop()
self.add_to_known_types(node, name, 'interface')
self.scope_type.pop()
self.obj_name.pop()
return preface + interface + ' ' + decls.replace('\n', '\n ')
# def on_type_parameter(self, node) -> str: # OBSOLETE, see on_type_parameters()
# return self.compile(node['identifier'])
@lru_cache(maxsize=4)
def bases(self, node) -> List[str]:
assert node.name == 'extends'
bases = [self.compile(nd) for nd in node.children]
return [TYPE_NAME_SUBSTITUTION.get(bc, bc) for bc in bases]
def on_extends(self, node) -> str:
return ', '.join(self.bases(node))
def on_type_alias(self, node) -> str:
alias = self.compile(node['identifier'])
if all(typ[0].name in ('basic_type', 'literal')
for typ in node.select('type')):
self.basic_type_aliases.add(alias)
self.obj_name.append(alias)
if alias not in self.overloaded_type_names:
if self.use_type_parameters: self.known_types.append(dict())
tps, preface = self.process_type_parameters(node)
if not self.use_type_parameters:
if self.use_explicit_type_alias:
tps = ": TypeAlias"
else:
tps = ''
if self.known_types[-1].get(alias, '') \
in ('namespace', 'enum', 'virtual_enum'):
preface = ('# commented out, because there is already an '
'enumeration with the same name\n# ' + preface)
else:
self.add_to_known_types(node, alias, 'type_alias')
self.local_classes.append([])
self.optional_keys.append([])
types = self.compile(node['types'])
preface += self.render_local_classes()
self.optional_keys.pop()
self.local_classes.pop()
if self.use_type_parameters: self.known_types.pop()
code = preface + ("type " if self.use_type_parameters else "") \
+ f"{alias}{tps} = {types}"
# there follows a hack to avoid failure on type unions of
# stringified type aliases and real types
if not self.use_type_parameters \
and types[-1:] == "'" and alias in self.known_types[-1]:
del self.known_types[-1][alias]
else:
code = ''
if node[-1].name == 'comment__':
code += '\n\n' + self.compile(node[-1])
self.obj_name.pop()
return code
def mark_overloaded_functions(self, scope: Node):
is_interface = self.scope_type[-1] in ('interface', 'namespace')
first_use: Dict[str, Node] = dict()
try:
for func_decl in as_list(scope['function']):
name = func_decl['identifier'].content
if keyword.iskeyword(name):
name += '_'
if name in first_use:
first_use[name].attr['decorator'] = \
'@singledispatchmethod' if is_interface \
else '@singledispatch'
func_decl.attr['decorator'] = f'@{name}.register'
self.require_singledispatch = True
else:
first_use[name] = func_decl
except KeyError:
pass # no functions in declarations block
def on_declarations_tuple(self, node) -> str:
return self.on_declarations_block(node)
def on_declarations_block(self, node) -> str:
self.mark_overloaded_functions(node)
# declarations = '\n'.join(self.compile(nd) for nd in node
# if nd.name in ('declaration', 'function'))
if node.get_attr('no_typed_dict', False):
for nd in node.children:
if 'optional' in nd:
nd.attr['force_optional'] = True
raw_decls = [self.compile(nd) for nd in node
if nd.name in ('declaration', 'function', 'comment__')]
declarations = '\n'.join(d for d in raw_decls if d)
if all(decl.lstrip()[0:1] in ('#', '') for decl in raw_decls):
return "pass"
return declarations or "pass"
def on_declaration(self, node) -> str:
identifier = self.compile(node['identifier'])
self.obj_name.append(to_typename(identifier))
T = self.compile_type_expression(node, node['types']) \
if 'types' in node else 'Any'
typename = self.obj_name.pop()
if T[0:5] == 'class':
self.local_classes[-1].append(T)
T = typename # substitute typename for type
if 'optional' in node:
self.optional_keys[-1].append(identifier)
T = f"Optional[{T}]" if node.get_attr('force_optional', False) \
else f"NotRequired[{T}]"
if self.is_toplevel() and bool(self.local_classes[-1]):
preface = self.render_local_classes()
self.local_classes.pop()
self.optional_keys.pop()
return preface + f"{identifier}: {T}"
return f"{identifier}: {T}"
def on_function(self, node) -> str:
is_constructor = False
if 'identifier' in node:
name = self.compile(node["identifier"])
self.func_name = name
if name == 'constructor' and self.scope_type[-1] == 'interface':
name = self.obj_name[-1] + 'Constructor'
is_constructor = True
else: # anonymous function
name = "__call__"
if self.use_type_parameters: self.known_types.append(dict())
tps, preface = self.process_type_parameters(node)
if preface and not self.is_toplevel():
self.local_classes[-1].insert(0, preface)
preface = ''
if not self.use_type_parameters: tps = ''
self.func_type_parameters = tps
try:
arguments = self.compile(node['arg_list'])
if self.scope_type[-1] == 'interface':
arguments = 'self, ' + arguments
except KeyError:
arguments = 'self' if self.scope_type[-1] == 'interface' else ''