-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate.py
executable file
·697 lines (570 loc) · 19.3 KB
/
generate.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
#!/usr/bin/env python3
import sys
import yaml
import re
import os
from typing import Dict, List, Optional, Tuple
FileName = str
decl_dict = {
"BOOL": "bool @NAME@",
"CHAR": "char @NAME@",
"INT8": "int8_t @NAME@",
"INT16": "int16_t @NAME@",
"INT32": "int32_t @NAME@",
"INT64": "int64_t @NAME@",
"INTPTR": "intptr_t @NAME@",
"UINT8": "uint8_t @NAME@",
"UINT16": "uint16_t @NAME@",
"UINT32": "uint32_t @NAME@",
"UINT64": "uint64_t @NAME@",
"UINTPTR": "uintptr_t @NAME@",
"FLOAT": "float @NAME@",
"DOUBLE": "double @NAME@",
"CHAR_ARRAY": "char @NAME@[]",
}
test_assign_dict = {
"CHAR_ARRAY": """\
{ /* TOP_C: #include <string.h> */
const char @NAME@_orig[] = @VALUE@;
strncpy(@NAME@, @NAME@_orig, sizeof(@NAME@));
}
""",
}
testing_reset_toggles_decl = f"""\
/** @brief Reset toggles to the initialization values.
*
* Call this function in the setup of a test suite to start every
* test with consistent values.
*
* This function is available only when testing is enabled (when
* `TESTING` is defined as 1).
*/
void testing_reset_toggles(void);
"""
def printerr(*args, **kwargs):
print(*args, **kwargs, file=sys.stderr)
def is_empty(s):
return s is None
def read_yaml_file(yaml_input: FileName) -> Tuple[List[str], List[str]]:
"""Read from YAML file, return tuple with header and data."""
with open(yaml_input) as yaml_file:
data = yaml.load(
yaml_file,
Loader=yaml.BaseLoader, # SafeLoader
)
if data is None:
return []
return list(data)
def read_defaults(yaml_input: FileName) -> Dict[str, Dict[str, str]]:
"""Read default values from YAML file, return dict with name and data."""
# Read from YAML file
data = read_yaml_file(yaml_input)
necessary = {"NAME", "DEFAULT", "TYPE", "DECL", "BRIEF"}
optional = {"DESCRIPTION", "H", "C", "TEST_ASSIGN"}
all_known = {*necessary, *optional}
# Insert data in the dict
defaults = {}
for x in data:
# Assert necessary fields are present
for field in necessary:
assert field in x, f"Field '{field}' is missing on data {x}"
# Add missing optional fields
for field in optional:
if field not in x:
x[field] = None
# Warn any unknown fields
for y in x:
if y not in all_known:
printerr(f"Warning: unknown field '{y}' in data {x}")
# Assert option is not repeated
name = x["NAME"]
assert name not in defaults, f"Option '{name}' is duplicated on {x}"
defaults[name] = x
return defaults
def read_char_ids(
yaml_input: FileName,
defaults: Dict[str, Dict[str, str]] = {},
) -> Dict[str, Dict[str, str]]:
"""
Read characterizations from YAML file, return dict with char_id and data.
"""
# Read from YAML file
data = read_yaml_file(yaml_input)
necessary = {"CHAR_ID", "BRIEF"}
optional = {"DESCRIPTION", "BASED_ON"}
all_known = {*necessary, *optional, *defaults.keys()}
# Insert data in the dict
char_ids = {}
for x in data:
# Assert necessary fields are present
for field in necessary:
assert field in x, f"Field '{field}' is missing on data {x}"
# Add missing optional fields
for field in optional:
if field not in x:
x[field] = None
# Warn any unknown fields
for y in x:
if y not in all_known:
printerr(f"Warning: unknown field '{y}' in data {x}")
# Assert char ID is not repeated
name = x["CHAR_ID"]
assert name not in char_ids, f"Char ID '{name}' is duplicated on {x}"
# Process char ID based on other char ID
based_on = x["BASED_ON"]
if based_on is None:
xx = x
else:
if isinstance(based_on, str):
based_on = [based_on]
elif isinstance(based_on, list):
pass
else:
assert False, f"BASED_ON must be a string or list of strings"
xx = {}
for base in based_on:
assert isinstance(
base, str
), f"BASED_ON must be a string or list of strings"
assert base in char_ids, (
f"Char ID '{base}' is not defined."
f" Available: {list(char_ids.keys())}."
)
xx.update(char_ids[base])
xx.update(x)
char_ids[name] = xx
return char_ids
def write_characterization_header(
defaults: Dict[str, Dict[str, str]],
char_ids: Dict[str, Dict[str, str]],
code_output: FileName = "include/toggle.h",
):
####################################################################
# Code begin
code_begin = """\
#ifndef TOGGLE_H
#define TOGGLE_H
#ifdef __cplusplus
extern "C"
{
#endif
/** @file toggle.h
* @brief Toggle definitions.
*
* This file validates the macro CHAR_ID and includes the corresponding
* Toggle header.
*
* In the list of CHAR_IDS, always add to the end of the list and
* increment NUM_CHAR_IDS.
*
* Numbering starts with 1 because the compiler would treat an undefined
* CHAR_ID as 0.
*/
#include <stdbool.h>
#include <stdint.h>
#ifdef DOXYGEN
/** @brief Characterization ID (int).
*
* Define the device characterization: the options and features enabled.
*
* The characterization ID should be defined when calling CMake (ex:
* `cmake -D CHAR_ID=...`) or when calling the compiler (ex:
* `gcc -D CHAR_ID=...`).
*/
#define CHAR_ID CHAR_ID_TEST
#endif
#ifndef CHAR_ID
#define CHAR_ID CHAR_ID_TEST
#warning "CHAR_ID is not defined. Using default."
#endif
"""
####################################################################
# Code end
code_end = """\
#ifdef __cplusplus
}
#endif
#endif /* TOGGLE_H */
"""
####################################################################
# Options documentation and default values
code_option_doc = """\
/* Options documentation. */
#ifdef DOXYGEN
"""
for name, data in defaults.items():
code_option_doc += f"""\
{apply_indent(format_brief_descr_comment(data['BRIEF'], data['DESCRIPTION']), indent=4)}
{apply_indent(format_h_declaration(data), indent=4)}
"""
code_option_doc += apply_indent(testing_reset_toggles_decl, indent=4)
code_option_doc += """
#endif /* DOXYGEN */
"""
####################################################################
# Characterization IDs
code_char_ids = """\
/* List of CHAR_IDs. */
"""
num = -1 # Set variable for empty char_ids
for num, items in enumerate(char_ids.items()):
char_id, data = items
code_char_ids += (
f"#define {char_id} {num+1} /**< @brief {data['BRIEF']} */\n"
)
code_char_ids += f"""
#define NUM_CHAR_IDS {num+1} /**< @brief Number of char IDs. */
/* Validate CHAR_ID range. */
#if (CHAR_ID < 1 || CHAR_ID > NUM_CHAR_IDS)
#error "Macro CHAR_ID is not in the valid range."
#endif
"""
####################################################################
# Characterization inclusions
code_char_includes = """\
/* Include the characterization. */
#ifdef DOXYGEN
/* Nothing to include for Doxygen. */
"""
for char_id in char_ids:
code_char_includes += (
f"#elif (CHAR_ID == {char_id})\n"
f' #include "characterizations/{char_id.lower()}.h"\n'
)
code_char_includes += f"#endif\n\n"
####################################################################
# Fit everything together and write
code = (
code_begin
+ code_option_doc
+ code_char_ids
+ code_char_includes
+ code_end
)
code = clean_code(code)
create_directory(code_output)
with open(code_output, "w") as fp:
fp.write(code)
def create_directory(filename: FileName):
directory = re.sub(r"/[^/]*$", r"", filename)
os.makedirs(directory, exist_ok=True)
def format_brief_descr_comment(
brief: str, descr: str, mid_comment: bool = False
) -> str:
comment = "" if mid_comment else "/** "
if is_empty(descr):
comment += f"@brief {brief}"
comment += "" if mid_comment else " */"
else:
comment += f"@brief {brief}" + format_comment("\n" + descr)
comment += "" if mid_comment else f"\n */"
return comment
def apply_indent(code: str, indent: int) -> str:
indent = " " * indent
return indent + ("\n" + indent).join(code.split("\n"))
def write_characterization_source(
defaults: Dict[str, Dict[str, str]],
char_ids: Dict[str, Dict[str, str]],
code_output: FileName = "src/toggle.c",
):
####################################################################
# Code begin
code_begin = """\
#include "toggle.h"
"""
####################################################################
# Code end
code_end = ""
####################################################################
# Characterization inclusions
code_char_includes = """\
#ifdef DOXYGEN
/* Nothing to include for Doxygen. */
"""
for char_id in char_ids:
code_char_includes += (
f"#elif (CHAR_ID == {char_id})\n"
f' #include "characterizations/{char_id.lower()}.c"\n'
)
code_char_includes += f"#endif\n"
####################################################################
# Fit everything together and write
code = code_begin + code_char_includes + code_end
code = clean_code(code)
create_directory(code_output)
with open(code_output, "w") as fp:
fp.write(code)
def write_char_id_source(
defaults: Dict[str, Dict[str, str]],
char_id: Dict[str, Dict[str, str]],
):
file_name = char_id["CHAR_ID"].lower() + ".c"
code_output = f"src/characterizations/{file_name}"
####################################################################
# Code begin
code_begin = ""
####################################################################
# Code end
code_end = ""
####################################################################
# Options value
code_option = ""
for name, data in defaults.items():
code_option += f"""\
{format_c_definition(data, char_id)}
"""
####################################################################
# Testing functions
if is_testing(char_id):
code_option += """
void testing_reset_toggles(void)
{
"""
for name, data in defaults.items():
code_option += f"""\
{apply_indent(format_c_assignment(data, char_id), indent=4)}
"""
code_option += "}\n"
####################################################################
# Necessary headers
necessary_headers = ""
found_headers = re.findall(
r"TOP_C: (.*?)(?:\s*\*\/)?$", code_option, re.MULTILINE
)
found_headers = list(set(found_headers))
necessary_headers += "\n".join(found_headers)
necessary_headers += "\n"
####################################################################
# Fit everything together and write
code = code_begin + necessary_headers + code_option + code_end
code = clean_code(code)
create_directory(code_output)
with open(code_output, "w") as fp:
fp.write(code)
def write_char_id_header(
defaults: Dict[str, Dict[str, str]],
char_id: Dict[str, Dict[str, str]],
):
file_name = char_id["CHAR_ID"].lower() + ".h"
header_guard = "CHARACTERIZATIONS_" + char_id["CHAR_ID"].upper() + "_H"
code_output = f"include/characterizations/{file_name}"
####################################################################
# Code begin
code_begin = f"""\
#ifndef {header_guard}
#define {header_guard}
/** @file {file_name}
* {format_brief_descr_comment(
char_id['BRIEF'], char_id["DESCRIPTION"], mid_comment=True
)}
*/
"""
####################################################################
# Code end
code_end = f"""
#endif /* {header_guard} */
"""
####################################################################
# Options value
code_option = ""
for name, data in defaults.items():
code_option += f"""\
{format_brief_descr_comment(data['BRIEF'], data['DESCRIPTION'])}
{format_h_declaration(data, char_id)}
"""
####################################################################
# Testing functions
if is_testing(char_id):
code_option += apply_indent(testing_reset_toggles_decl, indent=0)
####################################################################
# Fit everything together and write
code = code_begin + code_option + code_end
code = clean_code(code)
create_directory(code_output)
with open(code_output, "w") as fp:
fp.write(code)
def format_comment(comment: str, *, indent: int = 0) -> str:
comment = comment.rstrip()
lines = ["", *comment.split("\n")]
comment = f"\n{' ' * indent} * ".join(lines)
return comment
def format_h_declaration(
defaults: Dict[str, str], char_id: Optional[Dict[str, str]] = None
) -> str:
code = defaults["H"]
return format_ch_def_decl(code, defaults, char_id, format="decl")
def format_c_definition(
defaults: Dict[str, str], char_id: Optional[Dict[str, str]] = None
) -> str:
code = defaults["C"]
return format_ch_def_decl(code, defaults, char_id, format="def")
def format_c_assignment(
defaults: Dict[str, str], char_id: Optional[Dict[str, str]] = None
) -> str:
code = defaults["TEST_ASSIGN"]
return format_ch_def_decl(code, defaults, char_id, format="assign")
def is_testing(char_id: Optional[Dict[str, str]] = None) -> bool:
if char_id is None or "TESTING" not in char_id or char_id["TESTING"] == "":
testing = False
else:
testing = bool(int(char_id["TESTING"]))
return testing
def get_value(
name: str,
defaults: Dict[str, str],
char_id: Optional[Dict[str, str]] = None,
) -> str:
# Get value from characterization or defaults
if char_id is None or name not in char_id or char_id[name] == "":
value = defaults["DEFAULT"]
else:
value = char_id[name]
return value
def error_if_value_option_is_set_on_characterization_file(
name: str,
defaults: Dict[str, str],
char_id: Dict[str, str],
) -> str:
# Error if a "VALUE option" is being set on the characterization.
if char_id is None:
pass
elif defaults["TYPE"].startswith("VALUE") and name in char_id:
assert name not in char_id, (
f"{name} is declared with TYPE = VALUE and cannot be "
"redefined in the characterization. "
f"Remove {name} from the file yaml/char_ids.yaml."
)
def format_ch_def_decl(
code: str,
defaults: Dict[str, str],
char_id: Dict[str, str],
*,
format: str,
):
typ = defaults["TYPE"]
decl = defaults["DECL"]
name = defaults["NAME"]
value = get_value(name, defaults, char_id)
testing = is_testing(char_id)
testing_changes = False
error_if_value_option_is_set_on_characterization_file(
name, defaults, char_id
)
# No custom code. Generate default.
# TYPE and DECL
if typ == "VALUE":
testing_changes = False
elif typ == "OPTION":
testing_changes = True
else:
raise NotImplementedError(
f'TYPE = "{typ}" is not implemented. ' 'Valid: ["VALUE", "OPTION"].'
)
# DECL part 1
if decl == "MACRO":
# MACRO (without type) cannot be tested
testing_changes = False
elif decl == "CUSTOM":
# CUSTOM cannot be tested
testing_changes = False
if is_empty(code):
# Make sure it is at lease an empty string
code = ""
# DECL part 2
if decl == "MACRO":
# MACRO (without type) cannot be tested
base = "MACRO"
decl = "MACRO"
elif decl == "CUSTOM":
# CUSTOM cannot be tested
# Nothing to do for custom
return code
elif (
decl.startswith("MACRO_")
or decl.startswith("CONST_")
or decl.startswith("VAR_")
):
# MACRO_*, CONST_* or VAR_*
base, orig_decl = decl.split("_", 1)
if orig_decl in decl_dict:
decl = decl_dict[orig_decl]
else:
raise NotImplementedError(
f'DECL = "{decl}" is not implemented. '
'Valid: ["*_UINT8", etc].'
)
if orig_decl in test_assign_dict:
test_assign = test_assign_dict[orig_decl]
else:
test_assign = "@NAME@ = @VALUE@;"
else:
raise NotImplementedError(
f'DECL = "{decl}" is not implemented. '
'Valid: ["MACRO_*", "CONST_*", "VAR_*"].'
)
# Changes when testing
if base == "MACRO":
if testing and testing_changes:
# When testing and not a value, a macro is transformed
# in a non-const variable
if format == "decl":
code = f"extern {decl};"
elif format == "def":
code = f"{decl} = @VALUE@;"
elif format == "assign":
code = test_assign
else:
if format == "decl":
code = f"#define @NAME@ @VALUE@"
elif format == "def":
code = ""
elif format == "assign":
code = ""
elif base == "CONST":
if format == "decl":
code = f"extern @CONST@ {decl};"
elif format == "def":
code = f"@CONST@ {decl} = @VALUE@;"
elif testing and testing_changes:
# When testing and not a value, a const is transformed
# in a non-const variable
if format == "assign":
code = test_assign
elif base == "VAR":
if format == "decl":
code = f"extern {decl};"
elif format == "def":
code = f"{decl} = @VALUE@;"
elif format == "assign":
code = test_assign
# Update values on the code
code = code.replace("@NAME@", name)
code = code.replace("@VALUE@", value)
const = "" if testing and testing_changes else "const"
if const == "":
code = code.replace("@CONST@ ", const)
code = code.replace(" @CONST@", const)
else:
code = code.replace("@CONST@", const)
return code
def clean_code(code: str) -> str:
# One LF at the end of the file
code = code.strip() + "\n"
# Remove trailing whitespace
code = re.sub(r"[ \t]+$", r"", code, flags=re.MULTILINE)
# One new line before and after braces
code = re.sub(r"\n\n+}", r"\n}", code)
code = re.sub(r"{\n\n+", r"{\n", code)
# No multiple new lines
code = re.sub(r"\n\n\n+", r"\n\n", code)
return code
def main():
defaults = read_defaults("yaml/defaults.yaml")
char_ids = read_char_ids("yaml/char_ids.yaml", defaults=defaults)
write_characterization_header(defaults, char_ids)
write_characterization_source(defaults, char_ids)
for name, char_id in char_ids.items():
write_char_id_header(defaults, char_id)
write_char_id_source(defaults, char_id)
if __name__ == "__main__":
main()