-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathcodegen.py
More file actions
2351 lines (1881 loc) · 98.6 KB
/
Copy pathcodegen.py
File metadata and controls
2351 lines (1881 loc) · 98.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/python3
from __future__ import annotations
import argparse
import hashlib
import os
import subprocess
import sys
import time
import uuid
from collections.abc import Callable, Iterable, Mapping
from dataclasses import astuple, dataclass, is_dataclass
from typing import Any, TypeAlias, TypedDict, cast
GeneratedFileMap = dict[str, list[str]]
CommentLines: TypeAlias = list[str]
TagContext: TypeAlias = bool | int | str | list[str] | None
EXPORT_TARGETS = ('Server', 'Client', 'Mapper', 'Common')
REGISTRATION_TARGETS = ('Server', 'Client', 'Mapper')
CLIENT_ENTITY_TARGETS = ('Client', 'Mapper')
@dataclass(slots=True)
class TagMetaRecord:
abs_path: str
line_index: int
tag_info: str | None
tag_context: TagContext
comment: CommentLines
@dataclass(slots=True)
class MethodArg:
arg_type: str
name: str
nullable: bool = False
default_value: str | None = None
@dataclass(slots=True)
class RefTypeField:
field_type: str
name: str
comment: CommentLines
@dataclass(slots=True)
class RefTypeMethod:
name: str
ret: str
args: list[MethodArg]
comment: CommentLines
@dataclass(slots=True)
class SettingsEntry:
kind: str
value_type: str
name: str
init_values: list[str]
comment: CommentLines
@dataclass(slots=True)
class EnumKeyValue:
key: str
value: str | None
comment: CommentLines
@dataclass(slots=True)
class EntityInfo:
server: str
client: str
is_global: bool
has_protos: bool
has_statics: bool
has_abstract: bool
has_time_events: bool
exported: bool
comment: CommentLines
@dataclass(slots=True)
class MethodRegistrationInfo:
function_name: str
engine_entity_type_extern: str
return_type: str
@dataclass(slots=True)
class ExportEnumTag:
group_name: str
underlying_type: str
key_values: list[EnumKeyValue]
flags: list[str]
comment: CommentLines
@dataclass(slots=True)
class ExportValueTypeTag:
name: str
native_type: str
flags: list[str]
comment: CommentLines
@dataclass(slots=True)
class ExportPropertyTag:
entity: str
access: str
property_type: str
name: str
flags: list[str]
comment: CommentLines
@dataclass(slots=True)
class ExportMethodTag:
target: str
entity: str
name: str
ret: str
args: list[MethodArg]
flags: list[str]
comment: CommentLines
ret_nullable: bool = False
@dataclass(slots=True)
class ExportEventTag:
target: str
entity: str
name: str
args: list[MethodArg]
flags: list[str]
comment: CommentLines
@dataclass(slots=True)
class ExportRefTypeTag:
target: str
name: str
fields: list[RefTypeField]
methods: list[RefTypeMethod]
flags: list[str]
comment: CommentLines
@dataclass(slots=True)
class ExportEntityTag:
name: str
server_class_name: str
client_class_name: str
flags: list[str]
comment: CommentLines
@dataclass(slots=True)
class ExportSettingsTag:
group_name: str
target: str
settings: list[SettingsEntry]
flags: list[str]
comment: CommentLines
@dataclass(slots=True)
class EngineHookTag:
name: str
flags: list[str]
comment: CommentLines
@dataclass(slots=True)
class MigrationRuleTag:
args: list[str]
comment: CommentLines
@dataclass(slots=True)
class CodeGenTag:
template_type: str
abs_path: str
entry: str
line_index: int
tag_context: TagContext
flags: list[str]
comment: CommentLines
class CodeGenTagStore(TypedDict):
ExportEnum: list[ExportEnumTag]
ExportValueType: list[ExportValueTypeTag]
ExportProperty: list[ExportPropertyTag]
ExportMethod: list[ExportMethodTag]
ExportEvent: list[ExportEventTag]
ExportRefType: list[ExportRefTypeTag]
ExportEntity: list[ExportEntityTag]
ExportSettings: list[ExportSettingsTag]
EngineHook: list[EngineHookTag]
MigrationRule: list[MigrationRuleTag]
CodeGen: list[CodeGenTag]
class TagMetaStore(TypedDict):
ExportEnum: list[TagMetaRecord]
ExportValueType: list[TagMetaRecord]
ExportProperty: list[TagMetaRecord]
ExportMethod: list[TagMetaRecord]
ExportEvent: list[TagMetaRecord]
ExportRefType: list[TagMetaRecord]
ExportEntity: list[TagMetaRecord]
ExportSettings: list[TagMetaRecord]
EngineHook: list[TagMetaRecord]
MigrationRule: list[TagMetaRecord]
CodeGen: list[TagMetaRecord]
def create_codegen_tag_store() -> CodeGenTagStore:
return {
'ExportEnum': [],
'ExportValueType': [],
'ExportProperty': [],
'ExportMethod': [],
'ExportEvent': [],
'ExportRefType': [],
'ExportEntity': [],
'ExportSettings': [],
'EngineHook': [],
'MigrationRule': [],
'CodeGen': [],
}
def create_tag_meta_store() -> TagMetaStore:
return {
'ExportEnum': [],
'ExportValueType': [],
'ExportProperty': [],
'ExportMethod': [],
'ExportEvent': [],
'ExportRefType': [],
'ExportEntity': [],
'ExportSettings': [],
'EngineHook': [],
'MigrationRule': [],
'CodeGen': [],
}
def create_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description='FOnline code generator', fromfile_prefix_chars='@')
parser.add_argument('-maincfg', dest='maincfg', required=True, help='main config file')
parser.add_argument('-buildhash', dest='buildhash', required=True, help='build hash')
parser.add_argument('-devname', dest='devname', required=True, help='dev game name')
parser.add_argument('-nicename', dest='nicename', required=True, help='nice game name')
parser.add_argument('-embedded', dest='embedded', required=True, help='embedded buffer capacity')
parser.add_argument('-internalcfg', dest='internalcfg', required=True, help='internal config buffer capacity')
parser.add_argument('-meta', dest='meta', required=True, action='append', help='path to script api metadata (///@ tags)')
parser.add_argument('-commonheader', dest='commonheader', action='append', default=[], help='path to common header file')
parser.add_argument('-genoutput', dest='genoutput', required=True, help='generated code output dir')
parser.add_argument('-verbose', dest='verbose', action='store_true', help='verbose mode')
return parser
args = argparse.Namespace()
start_time = 0.0
def log(*parts: object) -> None:
print('[CodeGen]', *parts)
def get_guid(name: str) -> str:
return '{' + str(uuid.uuid3(uuid.NAMESPACE_OID, name)).upper() + '}'
def int_to_4_bytes(value: int) -> int:
return value & 0xffffffff
def get_hash(input_text: str, seed: int = 0) -> str:
input_bytes = input_text.encode()
m = 0x5bd1e995
r = 24
length = len(input_bytes)
h = seed ^ length
round_index = 0
while length >= (round_index * 4) + 4:
k = input_bytes[round_index * 4]
k |= input_bytes[(round_index * 4) + 1] << 8
k |= input_bytes[(round_index * 4) + 2] << 16
k |= input_bytes[(round_index * 4) + 3] << 24
k = int_to_4_bytes(k)
k = int_to_4_bytes(k * m)
k ^= k >> r
k = int_to_4_bytes(k * m)
h = int_to_4_bytes(h * m)
h ^= k
round_index += 1
length_diff = length - (round_index * 4)
if length_diff == 1:
h ^= input_bytes[-1]
h = int_to_4_bytes(h * m)
elif length_diff == 2:
h ^= int_to_4_bytes(input_bytes[-1] << 8)
h ^= input_bytes[-2]
h = int_to_4_bytes(h * m)
elif length_diff == 3:
h ^= int_to_4_bytes(input_bytes[-1] << 16)
h ^= int_to_4_bytes(input_bytes[-2] << 8)
h ^= input_bytes[-3]
h = int_to_4_bytes(h * m)
h ^= h >> 13
h = int_to_4_bytes(h * m)
h ^= h >> 15
assert h <= 0xffffffff
if h & 0x80000000 == 0:
return str(h)
else:
return str(-((h ^ 0xFFFFFFFF) + 1))
assert get_hash('abcd') == '646393889'
assert get_hash('abcde') == '1594468574'
assert get_hash('abcdef') == '1271458169'
assert get_hash('abcdefg') == '-106836237'
# Generated file list
generated_file_list = ['EmbeddedResources-Include.h',
'InternalConfig-Include.h',
'Version-Include.h',
'GenericCode-Common.cpp',
'MetadataRegistration-Server.cpp',
'MetadataRegistration-Client.cpp',
'MetadataRegistration-Mapper.cpp',
'MetadataRegistration-ServerStub.cpp',
'MetadataRegistration-ClientStub.cpp',
'MetadataRegistration-MapperStub.cpp']
# Parse meta information
codegen_tags: CodeGenTagStore = create_codegen_tag_store()
def verbose_print(*parts: object) -> None:
if args.verbose:
log(*parts)
errors: list[tuple[object, ...]] = []
def show_error(*messages: object) -> None:
global errors
errors.append(messages)
log(str(messages[0]))
for message_part in messages[1:]:
log('-', str(message_part))
def write_error_stub(output_dir: str, error_lines: list[str], file_name: str) -> None:
with open(output_dir.rstrip('/') + '/' + file_name, 'w', encoding='utf-8') as file:
file.write('\n'.join(error_lines))
def check_errors() -> None:
if errors:
try:
error_lines = []
error_lines.append('')
error_lines.append('#error Code generation failed')
error_lines.append('')
error_lines.append('// Stub generated due to code generation error')
error_lines.append('//')
for messages in errors:
error_lines.append('// ' + str(messages[0]))
for message_part in messages:
error_lines.append('// - ' + str(message_part))
error_lines.append('//')
for file_name in generated_file_list:
write_error_stub(args.genoutput, error_lines, file_name)
except Exception as ex:
show_error('Can\'t write stubs', ex)
for error_entry in errors[0]:
if isinstance(error_entry, BaseException):
log('Most recent exception:')
raise error_entry
sys.exit(1)
def run_codegen_step(action: Callable[[], None], error_message: str) -> None:
try:
action()
except Exception as ex:
show_error(error_message, ex)
check_errors()
# Parse tags
tag_metas: TagMetaStore = create_tag_meta_store()
def find_comment_start(line: str) -> int:
for start_pos, char in enumerate(line):
if char != ' ' and char != '\t':
return start_pos
return -1
def collect_stripped_block(lines: list[str], start_index: int, end_marker: str, trim_left: bool = False) -> list[str] | None:
for index in range(start_index, len(lines)):
candidate = lines[index].lstrip() if trim_left else lines[index]
if candidate.startswith(end_marker):
return [line.strip() for line in lines[start_index:index] if line.strip()]
return None
def find_enclosing_class_name(lines: list[str], line_index: int) -> str | None:
for index in range(line_index, 0, -1):
if lines[index].startswith('class '):
return lines[index][6:lines[index].find(' ', 6)]
return None
def find_enclosing_property_entity(lines: list[str], line_index: int) -> str | None:
for index in range(line_index, 0, -1):
if lines[index].startswith('class '):
property_pos = lines[index].find('Properties')
assert property_pos != -1
return lines[index][6:property_pos]
return None
def find_following_declaration(lines: list[str], line_index: int) -> str | None:
for index in range(line_index + 1, len(lines)):
declaration = lines[index].strip()
if not declaration or declaration.startswith('//'):
continue
return declaration
return None
def infer_declared_type_name(declaration: str) -> str:
if declaration.startswith('struct ') or declaration.startswith('class '):
return declaration.split()[1]
if declaration.startswith('using '):
separator = declaration.find('=')
assert separator != -1, 'Invalid using declaration'
return declaration[len('using '):separator].strip()
assert False, 'Unable to infer type name from declaration'
def resolve_export_tag_context(tag_name: str, lines: list[str], line_index: int) -> TagContext:
if tag_name == 'ExportEnum':
return collect_stripped_block(lines, line_index + 1, '};', trim_left=True)
if tag_name == 'ExportValueType':
return find_following_declaration(lines, line_index)
if tag_name == 'ExportProperty':
property_entity = find_enclosing_property_entity(lines, line_index)
assert property_entity is not None
return property_entity + ' ' + lines[line_index + 1].strip()
if tag_name == 'ExportMethod':
return lines[line_index + 1].strip()
if tag_name == 'ExportEvent':
class_name = find_enclosing_class_name(lines, line_index)
assert class_name is not None
return class_name + ' ' + lines[line_index + 1].strip()
if tag_name == 'ExportRefType':
return collect_stripped_block(lines, line_index + 1, '};')
if tag_name == 'ExportEntity':
return True
if tag_name == 'ExportSettings':
return collect_stripped_block(lines, line_index + 1, 'SETTING_GROUP_END')
assert False, 'Invalid export tag context ' + tag_name
def resolve_tag_context(tag_name: str, lines: list[str], line_index: int, tag_pos: int) -> TagContext:
if tag_name.startswith('Export'):
return resolve_export_tag_context(tag_name, lines, line_index)
if tag_name == 'EngineHook':
return lines[line_index + 1].strip()
if tag_name == 'CodeGen':
return tag_pos
return None
def parse_meta_file(abs_path: str) -> None:
try:
with open(abs_path, 'r', encoding='utf-8-sig') as f:
lines = f.readlines()
except Exception as ex:
show_error('Can\'t read file', abs_path, ex)
return
last_comment: CommentLines = []
for line_index in range(len(lines)):
line = lines[line_index]
line_len = len(line)
if line_len < 5:
continue
try:
tag_pos = find_comment_start(line)
if tag_pos == -1 or line_len - tag_pos <= 2 or line[tag_pos] != '/' or line[tag_pos + 1] != '/':
last_comment = []
continue
if line_len - tag_pos >= 4 and line[tag_pos + 2] == '/' and line[tag_pos + 3] == '@':
tag_str = line[tag_pos + 4:].strip()
comment_pos = tag_str.find('//')
if comment_pos != -1:
last_comment = [tag_str[comment_pos + 2:].strip()]
tag_str = tag_str[:comment_pos].rstrip()
comment = last_comment if last_comment else []
tag_split = tag_str.split(' ', 1)
tag_name = tag_split[0]
if tag_name not in tag_metas:
show_error('Invalid tag ' + tag_name, abs_path + ' (' + str(line_index + 1) + ')', line.strip())
continue
tag_info = tag_split[1] if len(tag_split) > 1 else None
tag_context = resolve_tag_context(tag_name, lines, line_index, tag_pos)
tag_metas[tag_name].append(TagMetaRecord(abs_path, line_index, tag_info, tag_context, comment))
last_comment = []
elif line_len - tag_pos >= 3 and line[tag_pos + 2] != '/':
last_comment.append(line[tag_pos + 2:].strip())
else:
last_comment = []
except Exception as ex:
show_error('Invalid tag format', abs_path + ' (' + str(line_index + 1) + ')', line.strip(), ex)
# Meta files from build system
meta_files_registry = []
def collect_meta_files() -> list[str]:
meta_files: list[str] = []
for path in args.meta:
abs_path = os.path.abspath(path)
if abs_path not in meta_files and 'GeneratedSource' not in abs_path:
assert os.path.isfile(abs_path), 'Invalid meta file path ' + path
meta_files.append(abs_path)
meta_files.sort()
return meta_files
def parse_meta_files() -> None:
for abs_path in collect_meta_files():
parse_meta_file(abs_path)
check_errors()
ref_types: set[str] = set()
engine_enums: set[str] = set()
custom_types: set[str] = set()
custom_types_native_map: dict[str, str] = {}
game_entities: list[str] = []
game_entities_info: dict[str, EntityInfo] = {}
entity_relatives: set[str] = set()
generic_funcdefs: set[str] = set()
symbol_tokens = set('`~!@#$%^&*()+-=|\\/.,\';][]}{:><"')
def flush_token(result: list[str], current_token: str) -> str:
if current_token.strip():
result.append(current_token.strip())
return ''
def tokenize(text: str | None, anySymbols: list[int] | None = None) -> list[str]:
if anySymbols is None:
anySymbols = []
if text is None:
return []
text = text.strip()
result: list[str] = []
current_token = ''
for ch in text:
if ch in symbol_tokens:
if len(result) in anySymbols:
current_token += ch
continue
current_token = flush_token(result, current_token)
current_token = ch
current_token = flush_token(result, current_token)
elif ch in ' \t':
current_token = flush_token(result, current_token)
else:
current_token += ch
current_token = flush_token(result, current_token)
return result
def normalize_hash_text(text: str) -> str:
return text.replace('\r', '').replace('\n', '').replace('\t', '').replace(' ', '')
def require_list_context(tag_context: TagContext, tag_name: str) -> list[str]:
assert isinstance(tag_context, list), 'Invalid context type for ' + tag_name
return tag_context
def require_str_context(tag_context: TagContext, tag_name: str) -> str:
assert isinstance(tag_context, str), 'Invalid context type for ' + tag_name
return tag_context
def require_int_context(tag_context: TagContext, tag_name: str) -> int:
assert isinstance(tag_context, int), 'Invalid context type for ' + tag_name
return tag_context
def require_enum_value_text(key_value: EnumKeyValue) -> str:
assert key_value.value is not None, 'Enum value is not resolved for ' + key_value.key
return key_value.value
def get_context_preview(tag_context: TagContext) -> str:
if isinstance(tag_context, list):
return tag_context[0] if tag_context else '(empty)'
if isinstance(tag_context, str):
return tag_context
return '(empty)'
def hash_recursive(hasher: Any, data: Any) -> None:
if isinstance(data, Mapping):
for key in sorted(data.keys()):
hasher.update(normalize_hash_text(str(key)).encode('utf-8'))
hash_recursive(hasher, data[key])
elif is_dataclass(data):
hash_recursive(hasher, astuple(cast(Any, data)))
elif isinstance(data, Iterable) and not isinstance(data, str):
for index, item in enumerate(data):
hasher.update(normalize_hash_text(str(index)).encode('utf-8'))
hash_recursive(hasher, item)
else:
hasher.update(normalize_hash_text(str(data)).encode('utf-8'))
compatibility_hasher = hashlib.new('sha256')
def iter_cpp_top_level(text: str) -> Iterable[tuple[int, str, bool]]:
angle_depth = 0
paren_depth = 0
brace_depth = 0
bracket_depth = 0
quote: str | None = None
escaped = False
for index, char in enumerate(text):
top_level = angle_depth == 0 and paren_depth == 0 and brace_depth == 0 and bracket_depth == 0 and quote is None
yield index, char, top_level
if quote is not None:
if escaped:
escaped = False
elif char == '\\':
escaped = True
elif char == quote:
quote = None
continue
if char in ('"', "'"):
quote = char
elif char == '<':
angle_depth += 1
elif char == '>' and angle_depth > 0:
angle_depth -= 1
elif char == '(':
paren_depth += 1
elif char == ')' and paren_depth > 0:
paren_depth -= 1
elif char == '{':
brace_depth += 1
elif char == '}' and brace_depth > 0:
brace_depth -= 1
elif char == '[':
bracket_depth += 1
elif char == ']' and bracket_depth > 0:
bracket_depth -= 1
def find_cpp_top_level_char(text: str, target: str) -> int:
for index, char, top_level in iter_cpp_top_level(text):
if char == target and top_level:
return index
return -1
def find_matching_cpp_paren(text: str, open_pos: int) -> int:
assert 0 <= open_pos < len(text) and text[open_pos] == '(', 'Invalid opening paren position'
depth = 0
quote: str | None = None
escaped = False
for index in range(open_pos, len(text)):
char = text[index]
if quote is not None:
if escaped:
escaped = False
elif char == '\\':
escaped = True
elif char == quote:
quote = None
continue
if char in ('"', "'"):
quote = char
elif char == '(':
depth += 1
elif char == ')':
depth -= 1
if depth == 0:
return index
assert False, 'Unmatched opening paren'
def split_engine_args(function_args_text: str) -> list[str]:
result: list[str] = []
current_start = 0
for index, char, top_level in iter_cpp_top_level(function_args_text):
if char == ',' and top_level:
current = function_args_text[current_start:index].strip()
if current:
result.append(current)
current_start = index + 1
current = function_args_text[current_start:].strip()
if current:
result.append(current)
return result
def normalize_default_arg_value(default_value: str, arg_type: str) -> str:
default_value = default_value.strip()
if default_value in ('nullptr', 'NULL'):
return 'null'
default_type_ctors = {
'any': ['any_t'],
'hstring': ['hstring'],
'ucolor': ['ucolor'],
'ipos': ['ipos32'],
'isize': ['isize32'],
'fpos': ['fpos32'],
'fsize': ['fsize32'],
}
if arg_type in default_type_ctors:
if default_value == '{}':
return arg_type + '()'
for default_type_ctor in default_type_ctors[arg_type]:
if default_value in (default_type_ctor + ' {}', default_type_ctor + '{}', default_type_ctor + '()'):
return arg_type + '()'
ctor_prefix = default_type_ctor + ' {'
if default_value.startswith(ctor_prefix) and default_value.endswith('}'):
return arg_type + '(' + default_value[len(ctor_prefix):-1].strip() + ')'
ctor_prefix = default_type_ctor + '('
if default_value.startswith(ctor_prefix) and default_value.endswith(')'):
return arg_type + '(' + default_value[len(ctor_prefix):-1].strip() + ')'
return default_value
def parse_export_property_definition(tag_context: str, export_flags: list[str], valid_types: set[str]) -> tuple[str, str, str, str, list[str]]:
entity = tag_context[:tag_context.find(' ')]
access = export_flags[0]
assert access in ['Common', 'Server', 'Client'], 'Invalid export property target ' + access
property_flags = export_flags[1:]
tokens = [token.strip() for token in tag_context[tag_context.find('(') + 1:tag_context.find(')')].split(',')]
assert len(tokens) == 2
property_type = engine_type_to_meta_type(tokens[0], valid_types)
assert 'uint64' not in property_type, 'Type uint64 is not supported by properties'
property_name = tokens[1]
property_flags.append('CoreProperty')
return entity, access, property_type, property_name, property_flags
def resolve_property_targets(entity: str, property_flags: list[str], game_entities: list[str]) -> list[str]:
if entity == 'Entity':
property_flags.append('SharedProperty')
return game_entities
assert entity in game_entities, 'Invalid entity ' + entity
return [entity]
def parse_method_args(args_text: str, valid_types: set[str], skip_first_arg: bool = False) -> list[MethodArg]:
result_args: list[MethodArg] = []
raw_args = split_engine_args(args_text)
has_default_arg = False
for arg in raw_args[1:] if skip_first_arg else raw_args:
arg = arg.strip()
raw_default_value = None
default_separator = find_cpp_top_level_char(arg, '=')
if default_separator != -1:
raw_default_value = arg[default_separator + 1:]
assert raw_default_value.strip(), 'Default argument value is empty: ' + arg
arg = arg[:default_separator].rstrip()
has_default_arg = True
else:
assert not has_default_arg, 'Default argument is followed by non-default argument: ' + arg
nullable = False
if arg.startswith('FO_NULLABLE'):
nullable = True
arg = arg[len('FO_NULLABLE'):].lstrip()
separator = arg.rfind(' ')
assert separator != -1, 'Invalid argument declaration: ' + arg
arg_type = engine_type_to_meta_type(arg[:separator].rstrip(), valid_types)
default_value = normalize_default_arg_value(raw_default_value, arg_type) if raw_default_value is not None else None
arg_name = arg[separator + 1:]
assert arg_name, 'Argument name is empty: ' + arg
result_args.append(MethodArg(arg_type, arg_name, nullable=nullable, default_value=default_value))
return result_args
def parse_export_method_signature(tag_context: str, valid_types: set[str], game_entities: list[str]) -> tuple[str, str, str, str, list[MethodArg], bool]:
line_tokens = tokenize(tag_context)
brace_open_pos = tag_context.find('(')
brace_close_pos = find_matching_cpp_paren(tag_context, brace_open_pos)
function_args = tag_context[brace_open_pos + 1:brace_close_pos]
function_token_index = find_token_index(line_tokens, '(')
assert function_token_index > 1, tag_context
function_name = line_tokens[function_token_index - 1]
return_tokens = line_tokens[1:function_token_index - 1]
ret_nullable = False
if return_tokens and return_tokens[0] == 'FO_NULLABLE':
ret_nullable = True
return_tokens = return_tokens[1:]
ret = engine_type_to_meta_type(''.join(return_tokens), valid_types)
function_tokens = function_name.split('_', 2)
assert len(function_tokens) == 3, function_name
target = function_tokens[0].strip()
assert target in EXPORT_TARGETS, target
entity = function_tokens[1]
assert entity in game_entities + ['Entity'], entity
name = function_tokens[2]
return target, entity, name, ret, parse_method_args(function_args, valid_types, skip_first_arg=True), ret_nullable
def resolve_event_target(tag_context: str, game_entities_info: Mapping[str, EntityInfo]) -> tuple[str, str]:
class_name = tag_context[:tag_context.find(' ')].strip()
for entity_name, entity_info in game_entities_info.items():
if class_name == entity_info.server or class_name == entity_info.client:
return ('Server' if class_name == entity_info.server else 'Client'), entity_name
if class_name == 'MapperEngine':
return 'Mapper', 'Game'
assert False, class_name
def parse_export_event_signature(tag_context: str, valid_types: set[str]) -> tuple[str, list[MethodArg]]:
brace_open_pos = tag_context.find('(')
brace_close_pos = tag_context.rfind(')')
first_comma_pos = tag_context.find(',', brace_open_pos)
event_name = tag_context[brace_open_pos + 1:first_comma_pos if first_comma_pos != -1 else brace_close_pos].strip()
event_args: list[MethodArg] = []
if first_comma_pos != -1:
args_text = tag_context[first_comma_pos + 1:brace_close_pos].strip()
if args_text:
for arg in split_engine_args(args_text):
arg = arg.strip()
separator = arg.find('/')
type_part = arg[:separator - 1].rstrip()
nullable = False
if type_part.startswith('FO_NULLABLE'):
nullable = True
type_part = type_part[len('FO_NULLABLE'):].lstrip()
arg_type = engine_type_to_meta_type(type_part, valid_types)
arg_name = arg[separator + 2:-2]
event_args.append(MethodArg(arg_type, arg_name, nullable=nullable))
return event_name, event_args
def parse_settings_group_name(first_line: str) -> str:
assert first_line.startswith('SETTING_GROUP'), 'Invalid start macro'
group_name = first_line[first_line.find('(') + 1:first_line.find(',')]
assert group_name.endswith('Settings'), 'Invalid group ending ' + group_name
return group_name[:-len('Settings')]
def parse_settings_entry(line: str, valid_types: set[str]) -> SettingsEntry:
setting_comment = [line[line.find('//') + 2:].strip()] if line.find('//') != -1 else []
setting_type = line[:line.find('(')]
assert setting_type in ['FIXED_SETTING', 'VARIABLE_SETTING'], 'Invalid setting type ' + setting_type
setting_args = [token.strip().strip('"') for token in line[line.find('(') + 1:line.find(')')].split(',')]
assert len(setting_args) >= 3, 'Invalid setting args count'
return SettingsEntry(
'fix' if setting_type == 'FIXED_SETTING' else 'var',
engine_type_to_meta_type(setting_args[0], valid_types),
setting_args[1] + '.' + setting_args[2],
setting_args[3:],
setting_comment,
)
def parse_settings_entries(tag_context: list[str], valid_types: set[str], hasher: Any) -> list[SettingsEntry]:
settings: list[SettingsEntry] = []
for line in tag_context[1:]:
settings.append(parse_settings_entry(line, valid_types))
hash_recursive(hasher, (settings[-1].kind, settings[-1].value_type, settings[-1].name, settings[-1].init_values))
return settings
def parse_enum_key_values(enum_lines: list[str]) -> list[EnumKeyValue]:
key_values: list[EnumKeyValue] = []
assert enum_lines[1].startswith('{')
for raw_line in enum_lines[2:]:
comment_position = raw_line.find('//')
line = raw_line[:comment_position].rstrip() if comment_position != -1 else raw_line
separator = line.find('=')
if separator == -1:
next_value = str(int(require_enum_value_text(key_values[-1]), 0) + 1) if key_values else '0'
key_values.append(EnumKeyValue(line.rstrip(','), next_value, []))
else:
key_values.append(EnumKeyValue(line[:separator].rstrip(), line[separator + 1:].lstrip().rstrip(','), []))
return key_values
def find_token_index(tokens: list[str], value: str, start: int = 0) -> int:
try:
return tokens.index(value, start)
except ValueError:
return -1
def find_first_token_index(tokens: list[str], values: set[str], start: int = 0) -> int:
for index in range(start, len(tokens)):
if tokens[index] in values:
return index
return -1
def skip_leading_attributes(tokens: list[str], start: int = 0) -> int:
index = start
while index + 1 < len(tokens) and tokens[index] == '[' and tokens[index + 1] == '[':
index += 2
while index + 1 < len(tokens) and not (tokens[index] == ']' and tokens[index + 1] == ']'):
index += 1
assert index + 1 < len(tokens), 'Unterminated attribute specifier'
index += 2
return index
def parse_exported_ref_type_method(stripped_line: str, line_tokens: list[str], function_token_index: int, valid_types: set[str]) -> RefTypeMethod:
decl_begin = skip_leading_attributes(line_tokens)
assert function_token_index - 1 >= decl_begin, 'Invalid function definition'
decl_tokens = line_tokens[decl_begin:function_token_index - 1]
assert decl_tokens, 'Invalid function declaration'
function_begin = stripped_line.index('(')
function_end = find_matching_cpp_paren(stripped_line, function_begin)
assert function_begin != -1 and function_end != -1 and function_begin < function_end, 'Invalid function definition'
if decl_tokens[-1] == 'auto':
trailing_tokens = tokenize(stripped_line[function_end + 1:])
arrow_index = find_token_index(trailing_tokens, '-')
assert arrow_index != -1 and arrow_index + 1 < len(trailing_tokens), 'Invalid trailing return declaration'
assert trailing_tokens[arrow_index + 1] == '>'
declaration_end = find_first_token_index(trailing_tokens, {'{', ';'}, arrow_index + 2)
assert declaration_end != -1, 'Invalid trailing return declaration'
return_type = ''.join(trailing_tokens[arrow_index + 2:declaration_end])
else:
return_type = ''.join(decl_tokens)
function_args = stripped_line[function_begin + 1:function_end]
result_args = parse_method_args(function_args, valid_types)
return RefTypeMethod(line_tokens[function_token_index - 1], engine_type_to_meta_type(return_type, valid_types), result_args, [])