Skip to content

Commit

Permalink
Implemented factory pattern for trace transformers
Browse files Browse the repository at this point in the history
  • Loading branch information
NikosDelijohn committed Oct 10, 2024
1 parent f5c1245 commit b3ca434
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 deletions.
27 changes: 26 additions & 1 deletion src/testcrush/grammars/transformers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
8 changes: 4 additions & 4 deletions src/unit_tests/test_transformers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down Expand Up @@ -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):

Expand Down

0 comments on commit b3ca434

Please sign in to comment.