|
| 1 | +# |
| 2 | +# Copyright (C) 2025 HDLtools Project |
| 3 | +# |
| 4 | +# SPDX-License-Identifier: GPL-3.0-or-later |
| 5 | +# |
| 6 | + |
| 7 | +""" |
| 8 | +Module for detecting hardware description languages (HDL). |
| 9 | +
|
| 10 | +This module provides the `HdlDetect` class, which can detect whether a given |
| 11 | +code is written in VHDL, Verilog, or SystemVerilog. It uses specific keywords |
| 12 | +and patterns to identify the language based on the code provided. |
| 13 | +""" |
| 14 | + |
| 15 | +import argparse |
| 16 | +import re |
| 17 | + |
| 18 | + |
| 19 | +class HdlDetect: |
| 20 | + """ |
| 21 | + Class to detect hardware description language (HDL) from a given code. |
| 22 | + """ |
| 23 | + |
| 24 | + def __init__(self, code=''): |
| 25 | + self.lang = None |
| 26 | + self.detect(code) |
| 27 | + |
| 28 | + def detect(self, code): |
| 29 | + """Detect the HDL from the provided code.""" |
| 30 | + self.code = code |
| 31 | + self.lang = None |
| 32 | + |
| 33 | + if 'entity' in self.code and 'module' not in self.code: |
| 34 | + self.lang = 'vhdl' |
| 35 | + elif 'entity' not in self.code and 'module' in self.code: |
| 36 | + self.lang = 'vlog' |
| 37 | + keywords = r'\blogic\b|\balways_ff\b|\balways_comb\b' |
| 38 | + if re.search(keywords, self.code): |
| 39 | + self.lang = 'slog' |
| 40 | + |
| 41 | + def is_vhdl(self): |
| 42 | + """Returns True if the code is VHDL.""" |
| 43 | + return self.lang == 'vhdl' |
| 44 | + |
| 45 | + def is_vlog(self): |
| 46 | + """Returns True if the code is Verilog.""" |
| 47 | + return self.lang == 'vlog' |
| 48 | + |
| 49 | + def is_slog(self): |
| 50 | + """Returns True if the code is SystemVerilog.""" |
| 51 | + return self.lang == 'slog' |
| 52 | + |
| 53 | + def is_xlog(self): |
| 54 | + """Returns True if the code is Verilog or SystemVerilog.""" |
| 55 | + return self.lang in ('vlog', 'slog') |
| 56 | + |
| 57 | + def get_lang(self): |
| 58 | + """Returns the detected language.""" |
| 59 | + return self.lang |
| 60 | + |
| 61 | + def __str__(self): |
| 62 | + return self.lang |
| 63 | + |
| 64 | + |
| 65 | +if __name__ == "__main__": |
| 66 | + parser = argparse.ArgumentParser() |
| 67 | + parser.add_argument('hdlfile') |
| 68 | + args = parser.parse_args() |
| 69 | + with open(args.hdlfile, 'r', encoding='utf-8') as fobj: |
| 70 | + text = fobj.read() |
| 71 | + obj = HdlDetect(text) |
| 72 | + print(obj.get_lang()) |
0 commit comments