-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathparsegen.py
More file actions
executable file
·1410 lines (1189 loc) · 42.1 KB
/
Copy pathparsegen.py
File metadata and controls
executable file
·1410 lines (1189 loc) · 42.1 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
import sys
import os
import re
import subprocess
import tempfile
import zlib
from enum import Enum
from typing import List, Set, Dict, Optional, TextIO, Tuple
from dataclasses import dataclass
LINE_LENGTH = 262144
gcc = "gcc"
cflags = ""
family_name = "cfg"
class CType(Enum):
NT = 0
UC = 1
US = 2
UD = 3
SC = 4
SS = 5
SD = 6
@dataclass
class TypeInfo:
space: str
underscore: str
format_char: str
signed: bool
TYPE_INFO = {
CType.NT: TypeInfo("", "", "", False),
CType.UC: TypeInfo("unsigned char", "unsigned_char", "u", False),
CType.US: TypeInfo("unsigned short", "unsigned_short", "u", False),
CType.UD: TypeInfo("unsigned int", "unsigned_int", "u", False),
CType.SC: TypeInfo("signed char", "signed_char", "d", True),
CType.SS: TypeInfo("short", "short", "d", True),
CType.SD: TypeInfo("int", "int", "d", True)
}
class StorageFormat(Enum):
NONE = 0
SINGLE = 1
QUOTED = 2
MULT = 3
MULT_PACKED = 4
PTR = 5
@dataclass
class ConfigDataElement:
name: str = ""
format: StorageFormat = StorageFormat.NONE
type: CType = CType.NT
length: int = 0
dependancy: str = ""
comment: str = ""
class ConfigData:
def __init__(self):
self.data_array: List[ConfigDataElement] = []
self.duplicate_names: Set[str] = set()
def duplicate_name(self, name: str) -> bool:
if name in self.duplicate_names:
print(f"Duplicate definition of \"{name}\" found on line {current_location.line_number}.", file=sys.stderr)
return True
self.duplicate_names.add(name)
return False
def add_comment(self, comment: str):
self.data_array.append(ConfigDataElement(comment=comment))
def add_var_single(self, name: str, type_val, dependancy: str, comment: str = ""):
if not self.duplicate_name(name):
if isinstance(type_val, str):
type_val = get_c_type(type_val)
self.data_array.append(ConfigDataElement(name, StorageFormat.SINGLE, type_val, 0, dependancy, comment))
def add_var_quoted(self, name: str, dependancy: str, comment: str = ""):
if not self.duplicate_name(name):
self.data_array.append(ConfigDataElement(name, StorageFormat.QUOTED, CType.NT, 0, dependancy, comment))
def add_var_mult(self, name: str, type_val, length: int, dependancy: str, comment: str = ""):
if not self.duplicate_name(name):
if isinstance(type_val, str):
type_val = get_c_type(type_val)
self.data_array.append(ConfigDataElement(name, StorageFormat.MULT, type_val, length, dependancy, comment))
def add_var_packed(self, name: str, length: int, dependancy: str, comment: str = ""):
if not self.duplicate_name(name):
self.data_array.append(ConfigDataElement(name, StorageFormat.MULT_PACKED, CType.NT, length, dependancy, comment))
def add_var_ptr(self, name: str, type_val, length: int, dependancy: str, comment: str = ""):
if not self.duplicate_name(name):
if isinstance(type_val, str):
type_val = get_c_type(type_val)
self.data_array.append(ConfigDataElement(name, StorageFormat.PTR, type_val, length, dependancy, comment))
def ctype_mult_used(self, type_val: CType) -> bool:
return any(elem.format == StorageFormat.MULT and elem.type == type_val for elem in self.data_array)
def ctype_ptr_used(self, type_val: CType) -> bool:
return any(elem.format == StorageFormat.PTR and elem.type == type_val for elem in self.data_array)
def packed_used(self) -> bool:
return any(elem.format == StorageFormat.MULT_PACKED for elem in self.data_array)
def quoted_used(self) -> bool:
return any(elem.format == StorageFormat.QUOTED for elem in self.data_array)
def unsigned_used(self) -> bool:
return any(not TYPE_INFO[elem.type].signed for elem in self.data_array)
class LocationTracker:
def __init__(self):
self.line_number = 0
self.column_number = 0
def error(self, msg: str):
print(f"Error: parse problem occured at {self.line_number}:{self.column_number}. {msg}.", file=sys.stderr)
defines: Set[str] = set()
dependancies: Set[str] = set()
ifs: List[bool] = []
memsets: List[str] = []
config_data = ConfigData()
current_location = LocationTracker()
def get_c_type(type_str: str) -> CType:
for ctype, info in TYPE_INFO.items():
if info.space == type_str:
return ctype
print(f"Invalid C type \"{type_str}\" when parsing line {current_location.line_number}.", file=sys.stderr)
return CType.NT
def find_next_match(s: str, match_char: str) -> int:
pos = -1
i = 0
while i < len(s):
if s[i] == match_char:
pos = i
break
if s[i] == '\\' and i + 1 < len(s):
i += 1
i += 1
return pos
def find_chr(s: str, match_char: str) -> int:
pos = -1
i = 0
while i < len(s):
if s[i] == match_char:
pos = i
break
if s[i] in ['"', "'"]:
match_pos = find_next_match(s[i+1:], s[i])
if match_pos >= 0:
i += match_pos + 1
i += 1
return pos
def asm2c_hex_convert(s: str) -> str:
s = re.sub(r'\$([0-9A-Fa-f]+)', r'0x\1', s)
s = re.sub(r'([0-9][0-9A-Fa-f]*)[hH]', r'0x\1', s)
return s
def c_hex_convert(s: str) -> str:
def hex_to_dec(match):
hex_val = match.group(1)
return str(int(hex_val, 16))
return re.sub(r'0x([0-9A-Fa-f]+)', hex_to_dec, s)
def enhanced_atoi(s: str) -> int:
try:
s = asm2c_hex_convert(s)
s = c_hex_convert(s)
return int(eval(s))
except:
current_location.error("Invalid number expression")
return 0
def safe_atoi(s: str) -> int:
if not s:
s = "X"
test_s = s[1:] if s.startswith('-') else s
if not test_s.isdigit():
current_location.error("Not a number")
return 0
return int(s)
def all_spaces(s: str) -> bool:
return s.strip() == ""
def encode_string(s: str, quotes: bool = True) -> str:
result = ""
if quotes:
result += '"'
for char in s:
if char in ['\\', '"', "'", '\n', '\t']:
result += '\\'
result += char
if quotes:
result += '"'
return result
def all_true(lst: List[bool]) -> bool:
return all(lst) if lst else True
def get_token(line: str, delimiters: str) -> List[str]:
tokens = []
current_token = ""
in_quote = False
quote_char = None
i = 0
while i < len(line):
char = line[i]
if not in_quote and char in delimiters:
if current_token:
tokens.append(current_token)
current_token = ""
elif char in ['"', "'"]:
if not in_quote:
in_quote = True
quote_char = char
elif char == quote_char:
in_quote = False
quote_char = None
current_token += char
else:
current_token += char
i += 1
if current_token:
tokens.append(current_token)
return tokens
def convert_asm_type(type_str: str, unsigned_var: bool = True) -> Optional[str]:
type_map = {
"dd": "unsigned int",
"dw": "unsigned short",
"db": "unsigned char",
"sd": "int",
"sw": "short",
"sb": "signed char"
}
var_type = type_map.get(type_str.lower())
if not var_type:
current_location.error("Not a valid type")
return None
if var_type.startswith("unsigned ") and not unsigned_var:
var_type = var_type[9:]
return var_type
class CodeGenerator:
def __init__(self, c_stream: TextIO, cheader_file: str = ""):
self.c_stream = c_stream
self.cheader_file = cheader_file
def write_includes(self):
self.c_stream.write("""/*
Config file handler generated by Nach's Config file handler creator.
*/
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
""")
if "PSR_COMPRESSED" in defines:
self.c_stream.write("#include <zlib.h>\n")
if self.cheader_file:
self.c_stream.write(f'#include "{self.cheader_file}"\n')
self.c_stream.write(f"""
#define LINE_LENGTH {LINE_LENGTH}
static char line[LINE_LENGTH];
""")
def write_string_functions(self):
if config_data.quoted_used() or config_data.packed_used():
self.c_stream.write("""
static char *encode_string(const char *str)
{
size_t i = 0;
line[i++] = '\\"';
while (*str)
{
if ((*str == '\\\\') ||
(*str == '\\"') ||
(*str == '\\'') ||
(*str == '\\n') ||
(*str == '\\t'))
{
line[i++] = '\\\\';
}
line[i++] = *str++;
}
line[i++] = '\\"';
line[i] = 0;
return(line);
}
static char *decode_string(char *str)
{
size_t str_len = strlen(str), i = 0;
char *dest = str;
if ((str_len > 1) && (*str == '\\"') && (str[str_len-1] == '\\"'))
{
memmove(str, str+1, str_len-2);
str[str_len-2] = 0;
while (*str)
{
if (*str == '\\\\')
{
str++;
}
dest[i++] = *str++;
}
}
dest[i] = 0;
return(dest);
}
""")
def write_utility_functions(self):
self.c_stream.write("""
static char *find_next_match(char *str, char match_char)
{
char *pos = 0;
while (*str)
{
if (*str == match_char)
{
pos = str;
break;
}
if (*str == '\\\\')
{
if (str[1])
{
str++;
}
else
{
break;
}
}
str++;
}
return(pos);
}
static char *find_str(char *str, char *match_str)
{
char *pos = 0;
while (*str)
{
if (strchr(match_str, *str))
{
pos = str;
break;
}
if ((*str == '\\"') || (*str == '\\''))
{
char *match_pos = 0;
if ((match_pos = find_next_match(str+1, *str)))
{
str = match_pos;
}
}
str++;
}
return(pos);
}
""")
if config_data.unsigned_used():
self.c_stream.write("""
static int atoui(const char *nptr)
{
return(strtoul(nptr, 0, 10));
}
""")
def write_dependancies(self):
self.c_stream.write("\n")
for dep in dependancies:
self.c_stream.write(f"extern unsigned char {dep};\n")
def write_init_function(self):
self.c_stream.write(f"""
static unsigned char psr_init_done = 0;
static void init_{family_name}_vars()
{{
if (!psr_init_done)
{{
psr_init_done = 1;
""")
for memset in memsets:
self.c_stream.write(f" {memset}\n")
self.c_stream.write(" }\n}\n")
def write_array_function(self, ctype: CType, operation: str):
if not (config_data.ctype_mult_used(ctype) or config_data.ctype_ptr_used(ctype)):
return
info = TYPE_INFO[ctype]
if operation == "write":
self.c_stream.write(f"""
static void write_{info.underscore}_array(int (*outf)(void *, const char *, ...), void *fp, const char *var_name, {info.space} *var, size_t size, const char *comment)
{{
size_t i;
outf(fp, "%s=%{info.format_char}", var_name, (int)*var);
for (i = 1; i < size; i++)
{{
outf(fp, ",%{info.format_char}", (int)(var[i]));
}}
if (comment)
{{
outf(fp, " ;%s", comment);
}}
outf(fp, "\\n");
}}
""")
elif operation == "read":
atoi_func = "atoi" if info.signed else "atoui"
self.c_stream.write(f"""
static void read_{info.underscore}_array(char *line, {info.space} *var, size_t size)
{{
size_t i;
char *token;
*var = ({info.space}){atoi_func}(strtok(line, ", \\t\\r\\n"));
for (i = 1; (i < size) && (token = strtok(0, ", \\t\\r\\n")); i++)
{{
var[i] = ({info.space}){atoi_func}(token);
}}
}}
""")
def write_packed_functions(self):
if not config_data.packed_used():
return
# Write functions
self.c_stream.write("""
static char *base94_encode(size_t size)
{
unsigned int i;
static char buffer[] = { 0, 0, 0, 0, 0, 0};
for (i = 0; i < 5; i++)
{
buffer[i] = ' ' + (char)(size % 94);
size /= 94;
}
return(buffer);
}
static char *char_array_pack(const char *str, size_t len)
{
char packed[LINE_LENGTH];
char *p = packed;
while (len)
{
if (*str)
{
size_t length = strlen(str);
strcpy(p, encode_string(str));
str += length;
len -= length;
p += strlen(p);
}
else
{
size_t i = 0;
while (len && !*str)
{
i++;
str++;
len--;
}
sprintf(p, "0%s", encode_string(base94_encode(i)));
p += strlen(p);
}
*p++ = '\\\\';
}
p[-1] = 0;
strcpy(line, packed);
return(line);
}
static size_t base94_decode(const char *buffer)
{
size_t size = 0;
int i;
for (i = 4; i >= 0; i--)
{
size *= 94;
size += (size_t)(buffer[i]-' ');
}
return(size);
}
static char *get_token(char *str, char *delim)
{
static char *pos = 0;
char *token = 0;
if (str) //Start a new string?
{
pos = str;
}
if (pos)
{
//Skip delimiters
while (*pos && strchr(delim, *pos))
{
pos++;
}
if (*pos)
{
token = pos;
//Skip non-delimiters
while (*pos && !strchr(delim, *pos))
{
//Skip quoted characters
if ((*pos == '\\"') || (*pos == '\\''))
{
char *match_pos = 0;
if ((match_pos = find_next_match(pos+1, *pos)))
{
pos = match_pos;
}
}
pos++;
}
if (*pos)
{
*pos++ = '\\0';
}
}
}
return(token);
}
static char *char_array_unpack(char *str)
{
char packed[LINE_LENGTH];
char *p = packed, *token;
size_t len = 0;
memset(packed, 0, sizeof(packed));
for (token = get_token(str, "\\\\"); token; token = get_token(0, "\\\\"))
{
if (*token == '0')
{
size_t i = base94_decode(decode_string(token+1));
len += i;
if (len > sizeof(packed)) { break; }
memset(p, 0, i);
p += i;
}
else
{
char *decoded = decode_string(token);
size_t decoded_length = strlen(decoded);
len += decoded_length;
if (len > sizeof(packed))
{
memcpy(p, decoded, sizeof(packed)-(len-decoded_length));
break;
}
memcpy(p, decoded, decoded_length);
p += decoded_length;
}
}
memcpy(line, packed, sizeof(packed));
return(line);
}
""")
def write_io_functions(self, operation: str):
if operation == "write":
self.write_write_functions()
elif operation == "read":
self.write_read_functions()
def write_write_functions(self):
self.write_packed_functions()
for ctype in [CType.UC, CType.US, CType.UD, CType.SC, CType.SS, CType.SD]:
self.write_array_function(ctype, "write")
self.c_stream.write(f"""
static void write_{family_name}_vars_internal(void *fp, int (*outf)(void *, const char *, ...))
{{
""")
for elem in config_data.data_array:
self._write_element(elem)
if "PSR_HASH" in defines:
hash_output = "\\n\\n\\n;Do not modify the following, for internal use only.\\n"
self.c_stream.write(f' outf(fp, "{hash_output}");\n')
self.c_stream.write(f' outf(fp, "PSR_HASH=%u\\n", PSR_HASH);\n')
self.c_stream.write(f"""}}
unsigned char write_{family_name}_vars(const char *file)
{{
FILE *fp = 0;
""")
if "PSR_EXTERN" not in defines:
self.c_stream.write(f" init_{family_name}_vars();\n\n")
self._write_file_io("write", "w", "fprintf")
if "PSR_COMPRESSED" in defines:
self._write_compressed_io("write")
if "PSR_MEMCPY" in defines:
self._write_memcpy_functions()
def write_read_functions(self):
for ctype in [CType.UC, CType.US, CType.UD, CType.SC, CType.SS, CType.SD]:
self.write_array_function(ctype, "read")
self.c_stream.write(f"""
static void read_{family_name}_vars_internal(void *fp, char *(*fin)(char *, int, void *), int (*fend)(void *))
{{
while (!fend(fp))
{{
char *p, *var, *value;
fin(line, LINE_LENGTH, fp);
if ((p = find_str(line, ";"))) {{ *p = 0; }}
if ((p = strchr(line, '=')))
{{
*p = 0;
var = line;
value = p+1;
while (isspace(*var)) {{ var++; }}
while (isspace(*value)) {{ value++; }}
if ((p = find_str(var, " \\t\\r\\n"))) {{ *p = 0; }}
if ((p = find_str(value, " \\t\\r\\n"))) {{ *p = 0; }}
if (!*var || !*value) {{ continue; }}
""")
if dependancies:
self._write_dependancy_checks()
self.c_stream.write(""" }
else
{
continue;
}
""")
for elem in config_data.data_array:
self._read_element(elem)
if "PSR_HASH" in defines:
self._write_hash_check()
self.c_stream.write(" }\n")
if "PSR_HASH" in defines:
self._write_hash_validation()
self.c_stream.write(f"""}}
unsigned char read_{family_name}_vars(const char *file)
{{
FILE *fp = 0;
""")
if "PSR_EXTERN" not in defines:
self.c_stream.write(f" init_{family_name}_vars();\n\n")
self._write_file_io("read", "r", "fgets", "feof")
if "PSR_COMPRESSED" in defines:
self._write_compressed_io("read")
def _write_element(self, elem: ConfigDataElement):
dependancy_prefix = dependancy_suffix = ""
if elem.dependancy:
dependancy_prefix = f"if ({elem.dependancy[:-1]}) {{ "
dependancy_suffix = " }"
if elem.format == StorageFormat.NONE:
if elem.comment:
self.c_stream.write(f' outf(fp, ";%s\\n", {encode_string(elem.comment)});\n')
else:
self.c_stream.write(' outf(fp, "\\n");\n')
elif elem.format in [StorageFormat.MULT, StorageFormat.PTR]:
info = TYPE_INFO[elem.type]
comment_str = encode_string(elem.comment) if elem.comment else "0"
self.c_stream.write(f' {dependancy_prefix}write_{info.underscore}_array(outf, fp, "{elem.dependancy}{elem.name}", {elem.name}, {elem.length}, {comment_str});{dependancy_suffix}\n')
else:
config_comment = f" ;{encode_string(elem.comment, False)}" if elem.comment else ""
self.c_stream.write(f' {dependancy_prefix}outf(fp, "{elem.dependancy}{elem.name}=')
if elem.format == StorageFormat.SINGLE:
info = TYPE_INFO[elem.type]
self.c_stream.write(f'%{info.format_char}{config_comment}\\n", {elem.name}')
elif elem.format == StorageFormat.QUOTED:
self.c_stream.write(f'%s{config_comment}\\n", encode_string({elem.name})')
elif elem.format == StorageFormat.MULT_PACKED:
self.c_stream.write(f'%s{config_comment}\\n", char_array_pack((char *){elem.name}, {elem.length})')
self.c_stream.write(f');{dependancy_suffix}\n')
def _read_element(self, elem: ConfigDataElement):
if elem.format == StorageFormat.NONE:
return
self.c_stream.write(f' if (!strcmp(var, "{elem.dependancy}{elem.name}")) {{ ')
if elem.format == StorageFormat.SINGLE:
info = TYPE_INFO[elem.type]
atoi_func = "atoi" if info.signed else "atoui"
self.c_stream.write(f'{elem.name} = ({info.space}){atoi_func}(value);')
elif elem.format in [StorageFormat.MULT, StorageFormat.PTR]:
info = TYPE_INFO[elem.type]
self.c_stream.write(f'read_{info.underscore}_array(value, {elem.name}, {elem.length});')
elif elem.format == StorageFormat.QUOTED:
self.c_stream.write(f'*{elem.name} = 0; strncat({elem.name}, decode_string(value), sizeof({elem.name})-1);')
elif elem.format == StorageFormat.MULT_PACKED:
self.c_stream.write(f'memcpy({elem.name}, char_array_unpack(value), {elem.length});')
self.c_stream.write(' continue; }\n')
def _write_dependancy_checks(self):
# Extract search and replace patterns for f-string
search_pattern = " \\t\\r\\n"
backslash_t_r_n = " \\t\\r\\n"
self.c_stream.write(f""" if ((p = strchr(var, ':')))
{{
if (!strlen(p+1)) {{ continue; }}
""")
deps = list(dependancies)
self.c_stream.write(f' if (!strncmp(var, "{deps[0]}:", (p-var)+1)) {{ if (!{deps[0]}) {{ continue; }} }}\n')
for dep in deps[1:]:
self.c_stream.write(f' else if (!strncmp(var, "{dep}:", (p-var)+1)) {{ if (!{dep}) {{ continue; }} }}\n')
self.c_stream.write(""" else { continue; }
}
""")
def _write_hash_check(self):
self.c_stream.write(""" if (!strcmp(var, "PSR_HASH"))
{
if ((unsigned int)atoui(value) == PSR_HASH)
{
psr_init_done = 2;
continue;
}
break;
}
""")
def _write_hash_validation(self):
self.c_stream.write(f""" if (psr_init_done == 2)
{{
psr_init_done = 1;
}}
else
{{
psr_init_done = 0;
init_{family_name}_vars();
}}
""")
def _write_file_io(self, operation: str, mode: str, func: str, end_func: str = None):
self.c_stream.write(f""" if ((fp = fopen(file, "{mode}")))
{{
{operation}_{family_name}_vars_internal(fp, (""")
if operation == "write":
self.c_stream.write(f"int (*)(void *, const char *, ...)){func}")
else:
self.c_stream.write(f"char *(*)(char *, int, void *)){func}, (int (*)(void *)){end_func}")
self.c_stream.write(""");
fclose(fp);
""")
if "PSR_NOUPDATE" not in defines and operation == "read":
self.c_stream.write(f" write_{family_name}_vars(file);\n")
self.c_stream.write(""" return(1);
}
""")
if "PSR_NOUPDATE" not in defines and operation == "read":
self.c_stream.write(f" write_{family_name}_vars(file);\n")
self.c_stream.write(" return(0);\n}\n")
def _write_compressed_io(self, operation: str):
gzgets_fix = ""
if operation == "read":
gzgets_fix = "static char *gzgets_fix(char *buf, int len, void *file)\n{\n return(gzgets(file, buf, len));\n}\n"
self.c_stream.write(f"""
{gzgets_fix}unsigned char {operation}_{family_name}_vars_compressed(const char *file)
{{
gzFile gzfp;
""")
if "PSR_EXTERN" not in defines:
self.c_stream.write(f" init_{family_name}_vars();\n\n")
mode = "rb" if operation == "read" else "wb9"
func = "gzgets_fix, gzeof" if operation == "read" else "gzprintf"
self.c_stream.write(f""" if ((gzfp = gzopen(file, "{mode}")))
{{
{operation}_{family_name}_vars_internal(gzfp, {func});
gzclose(gzfp);
""")
if "PSR_NOUPDATE" not in defines and operation == "read":
self.c_stream.write(f" write_{family_name}_vars_compressed(file);\n")
self.c_stream.write(""" return(1);
}
""")
if "PSR_NOUPDATE" not in defines and operation == "read":
self.c_stream.write(f" write_{family_name}_vars_compressed(file);\n")
self.c_stream.write(" return(0);\n}\n")
def _write_memcpy_functions(self):
self.c_stream.write(f"""
static unsigned int {family_name}_vars_memory(unsigned char *buffer, void *(*cpy)(void *, void *, size_t))
{{
unsigned char *p = buffer;
""")
for elem in config_data.data_array:
dependancy_prefix = dependancy_suffix = ""
if elem.dependancy:
dependancy_prefix = f"if ({elem.dependancy[:-1]}) {{ "
dependancy_suffix = " }"
if elem.format == StorageFormat.PTR:
info = TYPE_INFO[elem.type]
self.c_stream.write(f' {dependancy_prefix}cpy(p, {elem.name}, sizeof({info.space})*{elem.length}); p += sizeof({info.space})*{elem.length};{dependancy_suffix}\n')
elif elem.format != StorageFormat.NONE:
prefix = "&" if elem.format == StorageFormat.SINGLE else ""
self.c_stream.write(f' {dependancy_prefix}cpy(p, {prefix}{elem.name}, sizeof({elem.name})); p += sizeof({elem.name});{dependancy_suffix}\n')
self.c_stream.write(f""" return(p-buffer);
}}
static void *cpynull(void *l, void *r, size_t len){{ return(0); }}
unsigned int size_{family_name}_vars_memory()
{{
return({family_name}_vars_memory(0, cpynull));
}}
void write_{family_name}_vars_memory(unsigned char *buffer)
{{
{family_name}_vars_memory(buffer, (void *(*)(void *, void *, size_t))memcpy);
}}
static void *cpyright(void *src, void *dest, size_t len)
{{
memcpy(dest, src, len);
return(0);
}}
void read_{family_name}_vars_memory(unsigned char *buffer)
{{
{family_name}_vars_memory(buffer, cpyright);
}}
""")
def output_cheader_start(cheader_stream: TextIO):
cheader_stream.write(f"""/*
Config file handler header generated by Nach's Config file handler creator.
*/
#ifdef __cplusplus
extern "C" {{
#endif
unsigned char read_{family_name}_vars(const char *);
unsigned char write_{family_name}_vars(const char *);
""")
if "PSR_COMPRESSED" in defines:
cheader_stream.write(f"""unsigned char read_{family_name}_vars_compressed(const char *);
unsigned char write_{family_name}_vars_compressed(const char *);
""")
if "PSR_MEMCPY" in defines:
cheader_stream.write(f"""void read_{family_name}_vars_memory(unsigned char *);
void write_{family_name}_vars_memory(unsigned char *);
unsigned int size_{family_name}_vars_memory();
""")
cheader_stream.write("\n")
def output_cheader_end(cheader_stream: TextIO):
cheader_stream.write("""
#ifdef __cplusplus
}
#endif
""")
def handle_directive(instruction: str, label: Optional[str]):
global ifs
if instruction.lower() == "define":
if label:
defines.add(label)
else:
current_location.error("Could not get define label")
elif instruction.lower() == "undef":
if label:
defines.discard(label)
else:
current_location.error("Could not get undefine label")
elif instruction.lower() == "ifdef":
if label:
ifs.append(label in defines)
else:
current_location.error("Could not get ifdef label")
elif instruction.lower() == "ifndef":
if label:
ifs.append(label not in defines)
else:
current_location.error("Could not get ifndef label")
elif instruction.lower() == "else":
if label:
current_location.error("Processor directive else does not accept labels")
else:
if not ifs:
current_location.error("Processor directive else without ifdef")
else:
process = not ifs.pop()
ifs.append(process)
elif instruction.lower() in ["elifdef", "elseifdef"]:
if label:
if ifs and ifs[-1]:
ifs.pop()
ifs.append(False)
elif label in defines:
ifs.pop()
ifs.append(True)
else:
current_location.error("Could not get elseifdef label")
elif instruction.lower() == "endif":
if label:
current_location.error("Processor directive endif does not accept labels")
else:
if not ifs:
current_location.error("Processor directive endif without ifdef")
else:
ifs.pop()
else:
current_location.error("Unknown processor directive")
def get_comment(line: str, comment_separator: str) -> Tuple[str, Optional[str]]:
pos = find_chr(line, comment_separator)
if pos >= 0:
comment = line[pos+1:].strip()
if comment and comment[-1].isspace():
comment = comment.rstrip()
line = line[:pos]
return line, comment
return line, None
def output_header_conditional(hvars_lines: List[str], instruction: str, label: Optional[str]):