diff options
Diffstat (limited to 'codegen/header.py')
-rw-r--r-- | codegen/header.py | 54 |
1 files changed, 54 insertions, 0 deletions
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) |