diff --git a/src/testcrush/grammars/transformers.py b/src/testcrush/grammars/transformers.py index 0456030..efc8402 100755 --- a/src/testcrush/grammars/transformers.py +++ b/src/testcrush/grammars/transformers.py @@ -2,8 +2,9 @@ # SPDX-License-Identifier: MIT import lark +import pathlib -from typing import Literal, Any, Iterable +from typing import Literal, Any, Iterable, Union from testcrush.zoix import Fault from testcrush.utils import get_logger @@ -312,3 +313,27 @@ def reg_and_mem(self, *reg_val_pairs: str) -> str: """ reg_and_mem = f"\"{', '.join([ str(pair).strip() for pair in reg_val_pairs])}\"" return reg_and_mem + + +class TraceTransformerFactory: + """ + Factory pattern for trace transformers and the corresponding grammars. + + To be used as ``transformer, grammar = TraceTransformerFactory("ProcessorString")`` + """ + _current_directory = pathlib.Path(__file__).parent + _transformers = { + "CV32E40P": (TraceTransformerCV32E40P, _current_directory / "trace_cv32e40p.lark") + } + + def __call__(self, processor_type: str) -> Union[tuple[TraceTransformerCV32E40P, str]]: + + transformer, grammar = self._transformers.get(processor_type, (None, None)) + + if not transformer: + raise KeyError(f"Transformer for {processor_type} not found") + + with open(grammar) as src: + lark_grammar = src.read() + + return transformer(), lark_grammar diff --git a/src/unit_tests/test_transformers.py b/src/unit_tests/test_transformers.py index 61a281c..239174a 100644 --- a/src/unit_tests/test_transformers.py +++ b/src/unit_tests/test_transformers.py @@ -20,7 +20,7 @@ class FaultListTransformerTest(unittest.TestCase): grammar = open("../testcrush/grammars/fault_list.lark").read() - maxDiff = None + def get_parser(self): return lark.Lark(grammar=self.grammar, start="start", parser="lalr", transformer=transformers.FaultListTransformer()) @@ -148,11 +148,11 @@ def test_small_delay_defects_fault_list(self): class TraceTransformerCV32E40PTest(unittest.TestCase): - grammar = open("../testcrush/grammars/trace_cv32e40p.lark").read() - def get_parser(self): - return lark.Lark(grammar=self.grammar, start="start", parser="lalr", transformer=transformers.TraceTransformerCV32E40P()) + factory = transformers.TraceTransformerFactory() + transformer, grammar = factory("CV32E40P") + return lark.Lark(grammar=grammar, start="start", parser="lalr", transformer=transformer) def test_doc_example(self):