From fbe4a5eeab2107dfe03fc097bc1f9627b222adbd Mon Sep 17 00:00:00 2001 From: aqua Date: Sun, 22 Oct 2023 18:42:58 +0300 Subject: Initial commit --- codegen/header.py | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 codegen/header.py (limited to 'codegen/header.py') diff --git a/codegen/header.py b/codegen/header.py new file mode 100644 index 0000000..2ffbf6b --- /dev/null +++ b/codegen/header.py @@ -0,0 +1,54 @@ +""" Header serializer """ +__license__ = 'GPL-3.0-only' + +import re +import sys +from pathlib import Path +from .cgen import as_str + +class Header: + """ Python representation of a header """ + def __init__(self, name: str): + self.name = name + self.file = None + self.variables = [] + self.functions = [] + self.structs = [] + + def __enter__(self): + if self.name is None: + self.file = sys.stdout + else: + self.file = open(self.name, mode='w', encoding='utf-8') + return self + + def __exit__(self, exc_type, exc_value, traceback): + if self.file != sys.stdout: + self.file.close() + + def header_guard(self, mock=False): + """ Generate header guard from name """ + name = Path(self.name).stem + guard = '_'.join(re.findall('.[^A-Z]*', name)) + guard = guard.upper().replace('.', '_') + if mock: + return f'MOCK_{guard}_HH' + return f'{guard}_H' + + def _print(self, items): + for item in items: + print(as_str(item), file=self.file) + if len(items) > 0: + print('', file=self.file) + + def print_c_header(self): + """ Print C header """ + header_guard = self.header_guard() + print(f'#ifndef {header_guard}', file=self.file) + print(f'#define {header_guard}\n', file=self.file) + + self._print(self.structs) + self._print(self.variables) + self._print(self.functions) + + print(f'#endif // {header_guard}', file=self.file) -- cgit v1.2.1