1#!/usr/bin/env python3
2#
3# Copyright (c) 2023 Bjarki Arge Andreasen
4#
5# SPDX-License-Identifier: Apache-2.0
6"""
7Script to generate iterable sections from JSON encoded dictionary containing lists of items.
8"""
9
10import argparse
11import json
12
13
14def get_tagged_items(filepath: str, tag: str) -> list:
15    with open(filepath) as fp:
16        return json.load(fp)[tag]
17
18
19def gen_ld(filepath: str, items: list, alignment: int):
20    with open(filepath, "w") as fp:
21        for item in items:
22            fp.write(f"ITERABLE_SECTION_ROM({item}, {alignment})\n")
23
24
25def gen_cmake(filepath: str, items: list, alignment: int):
26    with open(filepath, "w") as fp:
27        for item in items:
28            fp.write(
29                f'list(APPEND sections "{{NAME\\;{item}_area\\;'
30                + 'GROUP\\;RODATA_REGION\\;'
31                + f'SUBALIGN\\;{alignment}\\;'
32                + 'NOINPUT\\;TRUE}")\n'
33            )
34            fp.write(
35                f'list(APPEND section_settings "{{SECTION\\;{item}_area\\;'
36                + 'SORT\\;NAME\\;'
37                + 'KEEP\\;TRUE\\;'
38                + f'INPUT\\;._{item}.static.*\\;'
39                + f'SYMBOLS\\;_{item}_list_start\\;_{item}_list_end}}")\n'
40            )
41        fp.write('set(DEVICE_API_SECTIONS         "${sections}" CACHE INTERNAL "")\n')
42        fp.write('set(DEVICE_API_SECTION_SETTINGS "${section_settings}" CACHE INTERNAL "")\n')
43
44
45def parse_args() -> argparse.Namespace:
46    parser = argparse.ArgumentParser(
47        description=__doc__,
48        formatter_class=argparse.RawDescriptionHelpFormatter,
49        allow_abbrev=False,
50    )
51
52    parser.add_argument("-i", "--input", required=True, help="Path to input list of tags")
53    parser.add_argument("-a", "--alignment", required=True, help="Iterable section alignment")
54    parser.add_argument("-t", "--tag", required=True, help="Tag to generate iterable sections for")
55    parser.add_argument("-l", "--ld-output", required=True, help="Path to output linker file")
56    parser.add_argument(
57        "-c", "--cmake-output", required=True, help="Path to CMake linker script inclusion file"
58    )
59
60    return parser.parse_args()
61
62
63def main():
64    args = parse_args()
65
66    items = get_tagged_items(args.input, args.tag)
67
68    gen_ld(args.ld_output, items, args.alignment)
69    gen_cmake(args.cmake_output, items, args.alignment)
70
71
72if __name__ == "__main__":
73    main()
74