|
| 1 | +# |
| 2 | +# Copyright (C) 2025 HDLtools Project |
| 3 | +# |
| 4 | +# SPDX-License-Identifier: GPL-3.0-or-later |
| 5 | +# |
| 6 | + |
| 7 | +""" |
| 8 | +This module defines the HDLController class that orchestrates the entire flow |
| 9 | +from reading and sanitizing HDL code, parsing modules, and generating output |
| 10 | +HDL code using Jinja2 templates. |
| 11 | +""" |
| 12 | + |
| 13 | +import sys |
| 14 | + |
| 15 | +from hdltools.hdl_reader import HDLReader |
| 16 | +from hdltools.mod_parser import ModParser |
| 17 | +from hdltools.hdl_writer import HDLWriter |
| 18 | + |
| 19 | + |
| 20 | +class HDLController: |
| 21 | + """A central controller to orchestrate the HDL processing tasks.""" |
| 22 | + |
| 23 | + def __init__(self, template): |
| 24 | + self.reader = HDLReader() |
| 25 | + self.parser = ModParser() |
| 26 | + self.writer = HDLWriter() |
| 27 | + self.template = template |
| 28 | + |
| 29 | + def generate(self, filepath, top=None, suffix=None): |
| 30 | + """Generates HDL code from the input file.""" |
| 31 | + |
| 32 | + try: |
| 33 | + self.reader.read_file(filepath) |
| 34 | + except (OSError, UnicodeDecodeError): |
| 35 | + self._error(f'file not found ({filepath})') |
| 36 | + |
| 37 | + raw_code = self.reader.get_code() |
| 38 | + self.parser.set_code(raw_code) |
| 39 | + self.parser.parse() |
| 40 | + |
| 41 | + modules = self.parser.get_names() |
| 42 | + if not modules: |
| 43 | + self._error('module not found') |
| 44 | + if top and top not in modules: |
| 45 | + self._error(f'top not found ({top})') |
| 46 | + if not top: |
| 47 | + top = modules[0] |
| 48 | + |
| 49 | + context = self.parser.get_module(top) |
| 50 | + context['name'] = top |
| 51 | + context['suffix'] = suffix |
| 52 | + self.writer.render(self.template, context) |
| 53 | + |
| 54 | + return self.writer.get_code() |
| 55 | + |
| 56 | + def write(self, filepath): |
| 57 | + """Writes the generated HDL code.""" |
| 58 | + if not filepath: |
| 59 | + print(self.writer.get_code()) |
| 60 | + else: |
| 61 | + self.writer.write_file(filepath) |
| 62 | + |
| 63 | + @staticmethod |
| 64 | + def _error(message, ecode=1): |
| 65 | + print(f'ERROR: {message}') |
| 66 | + sys.exit(ecode) |
0 commit comments