Exemple #1
0
def gen_vhdl_axi(in_filename, out_filename):

    if out_filename[-4:] != ".vhd":
        raise ValueError("output filename is expected to have .vhd extension")

    rdlc = RDLCompiler()
    rdlc.compile_file(in_filename)
    root = rdlc.elaborate()

    walker = RDLWalker(unroll=True)
    listener = HectareListener()
    walker.walk(root, listener)
    print("Parsing finished.")

    vhdl_gen = HectareVhdlGen(listener.addrmaps[0], input_filename=in_filename)
    s_pkg = vhdl_gen.generate_package()
    s_vhdl = vhdl_gen.generate_string()

    print("Generating {0} ...".format(out_filename))
    out_file = open(out_filename, "w")
    out_file.write(s_vhdl)
    out_file.close()

    if s_pkg is not None:
        pkg_filename = out_filename.replace(".vhd", "_pkg.vhd")
        print("Generating {0} ...".format(pkg_filename))
        out_file = open(pkg_filename, "w")
        out_file.write(s_pkg)
        out_file.close()
Exemple #2
0
 def compile(self, files, top_name, inst_name=None, parameters=None):
     this_dir = os.path.dirname(os.path.realpath(__file__))
     rdlc = RDLCompiler(message_printer=TestPrinter(),
                        warning_flags=self.compiler_warning_flags,
                        error_flags=self.compiler_error_flags)
     for file in files:
         rdlc.compile_file(os.path.join(this_dir, file))
     return rdlc.elaborate(top_name, inst_name, parameters)
    def compile(self, files, top_name=None):
        rdlc = RDLCompiler(message_printer=TestPrinter())
        ipxact = IPXACTImporter(rdlc)

        for file in files:
            if file.endswith(".rdl"):
                rdlc.compile_file(file)
            elif file.endswith(".xml"):
                ipxact.import_file(file)
        return rdlc.elaborate(top_name)
Exemple #4
0
    def compile(self):
        # Create an instance of the compiler
        rdlc = RDLCompiler()

        # Compile all the files provided
        for input_file in self.input_files:
            rdlc.compile_file(input_file)

        # Elaborate the design
        root = rdlc.elaborate()

        # Traverse the register model!
        walker = RDLWalker(unroll=True)
        listener = MyModelPrintingListener()
        walker.walk(root, listener)
Exemple #5
0
 def test_illegal_type_name_import_raises_error(self):
     rdlc = RDLCompiler()
     i = TypeNameErrorTestcaseImporter(rdlc)
     with self.assertRaisesRegex(
             ValueError,
             "Type name has invalid characters: 'illegal.type.name'"):
         i.import_file("asdf")
Exemple #6
0
 def test_illegal_inst_name_import_raises_error(self):
     rdlc = RDLCompiler()
     i = InstNameErrorTestcaseImporter(rdlc)
     with self.assertRaisesRegex(
             ValueError,
             "Instance name has invalid characters: 'reg1.some_signal'"):
         i.import_file("asdf")
Exemple #7
0
    def main(self, options: 'argparse.Namespace') -> None:
        rdlc = RDLCompiler()
        process_input.process_input(rdlc, self.importers, options.input_files,
                                    options)

        for name, comp_def in rdlc.root.comp_defs.items():
            if isinstance(comp_def, Addrmap):
                print(name)
Exemple #8
0
    def test_list_udps(self):
        this_dir = os.path.dirname(os.path.realpath(__file__))
        rdlc = RDLCompiler()
        rdlc.define_udp("int_udp", int, default=123)
        rdlc.compile_file(os.path.join(this_dir, "rdl_src/udp_15.2.2_ex1.rdl"))
        rdlc.elaborate("foo")

        self.assertEqual(sorted(rdlc.list_udps()), [
            'a_map_p',
            'int_udp',
            'some_bool_p',
            'some_num_p',
            'some_ref_p',
        ])
Exemple #9
0
class RDL(object):
    def __init__(self):
        self.files = []  #the RDL File
        self.rdlc = RDLCompiler()  #for compiler the file
        self.root = ""  #the file has been elaborate
        self.listener = GetRegListener()  #using self listener

    #read rdl file
    @DEBUG()
    def read_rdl(self, files=[]):
        INFO("read_rdl: " + "Reading SystemRDL Files")
        try:
            #compile all the files provided
            for input_file in files:
                self.rdlc.compile_file(input_file)
            self.root = self.rdlc.elaborate(
            )  #get the root of  Tree in the RDL
        except RDLCompileError:
            sys.exit(1)
        self.files = files
        walker = RDLWalker(unroll=True)
        walker.walk(self.root, self.listener)
        self.listener.do_stats()  #to process the information of SystemRDL file

    #gen the uvm file according the SystemRDL file has been elaborate
    @DEBUG()
    def gen_uvmral(self, outdir="", outfile=""):
        INFO("gen_uvmral: " + "Generate UVM-RAL File")
        exporter = uvmGenExporter()
        exporter.export(self.root, outdir, outfile)

    #gen the ip-xact file according the SystemRDL file has been elaborate
    @DEBUG()
    def gen_ipxact(self, outdir="", outfile=""):
        INFO("gen_ipxact: " + "Generate IP-XACT File")
        exporter = IPXACTExporter()
        exporter.export(self.root, outdir, outfile)

    def display_rdl(self):
        print(self.files)
        print(self.listener.reg_name)
        print(self.listener.reg_width)
        print(self.listener.reg_type)
        print(self.listener.reg_addr)
Exemple #10
0
    def main(self, options: 'argparse.Namespace') -> None:
        rdlc = RDLCompiler()

        parameters = process_input.parse_parameters(rdlc, options.parameters)

        process_input.process_input(rdlc, self.importers, options.input_files,
                                    options)

        top = process_input.elaborate(rdlc, parameters, options)

        # Run exporter
        self.do_export(top, options)
Exemple #11
0
def process_input(rdlc: RDLCompiler, importers: 'List[Importer]', input_files: List[str], options: 'argparse.Namespace') -> None:
    for file in input_files:
        if not os.path.exists(file):
            rdlc.msg.fatal(f"Input file does not exist: {file}")

        ext = os.path.splitext(file)[1].strip(".")
        if ext == "rdl":
            # Is SystemRDL file
            rdlc.compile_file(
                file,
                incl_search_paths=options.incdirs,
            )
        else:
            # Is foreign input file.

            # Search which importer to use by extension first
            importer_candidates = [] # type: List[Importer]
            for importer in importers:
                if ext in importer.file_extensions:
                    importer_candidates.append(importer)

            # Do 2nd pass if needed
            importer = None
            if len(importer_candidates) == 1:
                importer = importer_candidates[0]
            elif len(importer_candidates) > 1:
                # ambiguous which importer to use
                # Do 2nd pass compatibility check
                for importer_candidate in importer_candidates:
                    if importer_candidate.is_compatible(file):
                        importer = importer_candidate
                        break

            if not importer:
                rdlc.msg.fatal(
                    "Unknown file type. Could not find any importers capable of reading this file.",
                    FileSourceRef(file)
                )

            importer.do_import(rdlc, options, file)
Exemple #12
0
    def eval_RDL_expr(self, expr_text):
        input_stream = InputStream(expr_text)

        rdlc = RDLCompiler(message_printer=TestPrinter())

        tree = sa_systemrdl.parse(input_stream, "expr",
                                  RdlSaErrorListener(rdlc.msg))

        visitor = ExprVisitor(rdlc)
        result = visitor.visit(tree)

        pred_type = result.predict_type()
        return pred_type, result.get_value()
Exemple #13
0
def elaborate(rdlc: RDLCompiler, parameters: Dict[str, Any], options: 'argparse.Namespace') -> AddrmapNode:
    try:
        root = rdlc.elaborate(
            top_def_name=options.top_def_name,
            inst_name=options.inst_name,
            parameters=parameters
        )
    except (ValueError, TypeError) as e:
        # Parameter issues raise ValueError or TypeError
        # TODO: Fix exception types once they become specialized in the compiler
        rdlc.msg.fatal(e.args[0])

    return root.top
Exemple #14
0
def gen_c_header(in_filename, out_filename):

    if out_filename[-2:] != ".h":
        raise ValueError("output filename is expected to have .h extension")

    rdlc = RDLCompiler()
    rdlc.compile_file(in_filename)
    root = rdlc.elaborate()

    walker = RDLWalker(unroll=True)
    listener = HectareListener()
    walker.walk(root, listener)
    print("Parsing finished.")

    c_header_gen = HectareCHeaderGen(listener.addrmaps[0],
                                     input_filename=in_filename)
    s_header = c_header_gen.generate_string()

    print("Generating {0} ...".format(out_filename))
    out_file = open(out_filename, "w")
    out_file.write(s_header)
    out_file.close()
    def eval_RDL_expr(self, expr_text):
        input_stream = InputStream(expr_text)
        lexer = SystemRDLLexer(input_stream)
        token_stream = CommonTokenStream(lexer)
        parser = SystemRDLParser(token_stream)
        tree = parser.expr()

        rdlc = RDLCompiler(message_printer=TestPrinter())

        visitor = ExprVisitor(rdlc)
        result = visitor.visit(tree)

        pred_type = result.predict_type()
        return pred_type, result.get_value()
Exemple #16
0
def main():
    if len(sys.argv) < 3:
        raise Exception('Usage: generate_test_case.py <tc_name> <rdl_file>')

    testcase_name = sys.argv[1]
    rdl_file = sys.argv[2]
    output_dir = os.path.dirname(rdl_file)

    rdlc = RDLCompiler()
    rdlc.compile_file(rdl_file)
    root = rdlc.elaborate().top

    UVMGenerator(output_dir, False,
                 True).export_reg_models(root, testcase_name)

    UVMGenerator(output_dir, True, True).export_reg_models(root, testcase_name)

    UVMGenerator(output_dir, True,
                 False).export_reg_models(root, testcase_name)

    # Generate test logic
    UVMGenerator(output_dir, True,
                 True).generate_test_logic(root, testcase_name)
    def test_importer(self):
        rdlc = RDLCompiler()

        i = MyImporter(rdlc)
        i.import_file("asdf")
        root = rdlc.elaborate()

        nodes = []
        for node in root.descendants():
            if isinstance(node, FieldNode):
                attr = (node.low, node.high)
            elif isinstance(node, AddressableNode):
                attr = node.raw_absolute_address
            nodes.append(
                (node.get_path(), type(node).__name__, node.type_name, attr))

        expected_nodes = [
            ('top', 'AddrmapNode', 'top', 0),
            ('top.sub', 'AddrmapNode', None, 0x100),
            ('top.sub.subsub', 'RegfileNode', "my_rf", 0x100),
            ('top.sub.subsub.reg1', 'RegNode', None, 0x100),
            ('top.sub.subsub.reg1.f1', 'FieldNode', 'my_field_t', (0, 7)),
            ('top.sub.subsub.reg1.f3', 'FieldNode', None, (8, 15)),
            ('top.sub.subsub.reg1.f2', 'FieldNode', 'my_field_t', (16, 23)),
            ('top.sub.subsub.r2', 'RegNode', "my_reg_t", 0x110),
            ('top.sub.subsub.r2.f1', 'FieldNode', 'my_field_t', (0, 7)),
            ('top.sub.subsub.r2.f2', 'FieldNode', 'my_field_t', (8, 15)),
            ('top.sub.subsub.r2.f3', 'FieldNode', 'my_field_t', (16, 23)),
            ('top.sub.subsub.r3', 'RegNode', "my_reg_t", 0x120),
            ('top.sub.subsub.r3.f1', 'FieldNode', 'my_field_t', (0, 7)),
            ('top.sub.subsub.r3.f2', 'FieldNode', 'my_field_t', (8, 15)),
            ('top.sub.subsub.r3.f3', 'FieldNode', 'my_field_t', (16, 23)),
            ('top.my_mem[]', 'MemNode', None, 0x400),
            ('top.my_mem2[]', 'MemNode', 'my_mem_t', 0x800),
        ]

        self.assertEqual(nodes, expected_nodes)
Exemple #18
0
def parse_parameters(rdlc: RDLCompiler, parameter_options: List[str]) -> Dict[str, Any]:
    parameters = {}
    for raw_param in parameter_options:
        m = re.fullmatch(r"(\w+)=(.+)", raw_param)
        if not m:
            rdlc.msg.fatal(f"Invalid parameter argument: {raw_param}")

        p_name = m.group(1)
        try:
            p_value = rdlc.eval(m.group(2))
        except ValueError:
            rdlc.msg.fatal(f"Unable to parse value '{m.group(2)}' for parameter '{p_name}'")
        parameters[p_name] = p_value

    return parameters
Exemple #19
0
    def test_builtin_udp(self):
        this_dir = os.path.dirname(os.path.realpath(__file__))
        rdlc = RDLCompiler()
        rdlc.define_udp("int_udp", int, default=123)
        rdlc.compile_file(os.path.join(this_dir, "rdl_src/udp_builtin.rdl"))
        root = rdlc.elaborate("top")

        top = root.find_by_path("top")
        reg1 = root.find_by_path("top.reg1")
        field1 = root.find_by_path("top.reg1.field1")

        self.assertIs(top.get_property('int_udp'), 43)
        self.assertIs(reg1.get_property('int_udp'), 42)
        self.assertIs(field1.get_property('int_udp'), 123)
Exemple #20
0
def gen_rdl_header(top_name, rdl_file, output_folder):
    # Generate HTML and addressmap header
    rdlc = RDLCompiler()
    try:
        rdlc.compile_file(rdl_file)
        # Elaborate the design
        root = rdlc.elaborate()
    except RDLCompileError:
        # A compilation error occurred. Exit with error code
        sys.exit(1)
    root = rdlc.elaborate()
    exporter = HTMLExporter()
    exporter.export(root, os.path.join(output_folder, f"{top_name}_html"))
    rdl_json = convert_addrmap(rdlc, root.top)
    convert_to_json(rdl_json, os.path.join(output_folder, f"{top_name}.json"))
    convert_to_header(rdl_json, os.path.join(output_folder, top_name))
Exemple #21
0
    def test_elab_override_via_eval(self):
        rdlc = RDLCompiler()
        root = self.compile(
            ["rdl_testcases/parameters.rdl"],
            "elab_params",
            parameters={
                "STR": rdlc.eval('"python!"'),
                "INT": rdlc.eval('5'),
                "INTARR": rdlc.eval("'{6,7}"),
                "ONWR": rdlc.eval('woclr'),
                "BOOL": rdlc.eval('100/2 - 50')
            })

        f1 = root.find_by_path("elab_params.r1.f")
        f2 = root.find_by_path("elab_params.r2.f")
        f3 = root.find_by_path("elab_params.r3.f")

        self.assertEqual(f1.width, 5)
        self.assertEqual(f2.width, 6)
        self.assertEqual(f3.width, 7)
        self.assertEqual(f1.get_property("onwrite"), rdlt.OnWriteType.woclr)
        self.assertEqual(f2.get_property("donttest"), False)
        self.assertEqual(f3.get_property("name"), "python!")
Exemple #22
0
from systemrdl.node import RootNode, Node, RegNode, AddrmapNode, RegfileNode
from systemrdl.node import FieldNode, MemNode, AddressableNode
from peakrdl.pdf import PDFExporter

# Ignore this. Only needed for this example
this_dir = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.join(this_dir, "../input_files"))

input_dir = this_dir + "/input_files/"
output_dir = this_dir + "/output_files/"

# Get the input .rdl file from the command line
input_files = sys.argv[1:]

## Compile and elaborate the input .rdl file
rdlc = RDLCompiler()

## List for storing the elaborated ouput of each .rdl file
rdlc_elab_list = []

## Compile and store the elaborated object
try:
    for input_file in input_files:
        input_file = input_dir + input_file
        rdlc.compile_file(input_file)
        rdlc_elab_list.append(rdlc.elaborate())

except RDLCompileError:
    sys.exit(1)

## Generate the PDF output files
def compile_rdl(infile, incl_search_paths=None, top=None):
    '''compile the rdl'''
    rdlc = RDLCompiler()
    rdlc.compile_file(infile, incl_search_paths=incl_search_paths)
    return rdlc.elaborate(top_def_name=top).top
################################################################################
parser = argparse.ArgumentParser(description='dfdfdfd.')

#parser.add_argument('infile', nargs='?', type=argparse.FileType('r') )
parser.add_argument('rdl', type=str, help='SystemRDL source file')
parser.add_argument('chip', type=str, help='Chip model name')

#parser.add_argument('--', type=int,   help='Full (default) or Half duplex mode',               required=False)
#parser.add_argument('--mc21', type=int,   help='To remove',               required=False)
#parser.add_argument('--servercamera', type=int, help='Camera number',               required=False)

args = parser.parse_args()

#print(args)

rdlc = RDLCompiler()

try:
    rdlc.compile_file(args.rdl)

    root = rdlc.elaborate(args.chip)
except RDLCompileError:
    sys.exit(1)

#sys.exit(10)

walker = RDLWalker(unroll=True)
golistener = RdlToGoCodeListener()
walker.walk(root, golistener)

print("//THIS FILE WAS AUTO GENERATED. PLEASE DO NOT EDIT")
import os

# Ignore this. Only needed for this example
this_dir = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.join(this_dir, "../"))


from systemrdl import RDLCompiler, RDLListener, RDLWalker, RDLCompileError
from systemrdl.node import FieldNode, RegNode, AddrmapNode, SignalNode
from ralbot.uvmgen import uvmGenExporter

# Collect input files from the command line arguments
input_files = sys.argv[1:]

# Create an instance of the compiler
rdlc = RDLCompiler()

try:
    # Compile all the files provided
    for input_file in input_files:
        rdlc.compile_file(input_file)
    
    # Elaborate the design
    root = rdlc.elaborate()
except RDLCompileError:
    # A compilation error occurred. Exit with error code
    sys.exit(1)


file = "test.svh"
exporter = uvmGenExporter()
from systemrdl import RDLCompiler, RDLCompileError
from ralbot.html import HTMLExporter

#===============================================================================
#input_file = sys.argv[1]
#output_dir = sys.argv[1]

output_dir = "./output"

#print(output_dir)

top = ['hi3516av200', 'hi3519v101']
#top = ['hi3519v101'] # top level address maps

roots = []
rdlc = RDLCompiler()
rdlc.compile_file('hi3516av200.rdl')
#rdlc.compile_file('hi3516cv300_family.rdl')

for addrspace in top:
    root = rdlc.elaborate(addrspace)
    roots.append(root.top)
htmlexporter = HTMLExporter()
htmlexporter.export(roots, output_dir)

#rdlc = RDLCompiler()

#try:
#for input_file in input_files:
#    rdlc.compile_file(input_file)
#    root = rdlc.elaborate()
Exemple #27
0
#!/usr/bin/env python3

import sys
import os

from systemrdl import RDLCompiler
from peakrdl.uvm import UVMExporter

rdl_file = sys.argv[1]
sv_file = sys.argv[2]

rdlc = RDLCompiler()
rdlc.compile_file(rdl_file)
root = rdlc.elaborate().top

UVMExporter().export(
    root,
    sv_file,
    use_uvm_factory=False,
    reuse_class_definitions=True,
    export_as_package=True,
)
Exemple #28
0
 def __init__(self):
     self.files = []  #the RDL File
     self.rdlc = RDLCompiler()  #for compiler the file
     self.root = ""  #the file has been elaborate
     self.listener = GetRegListener()  #using self listener
 def compile(self, files, top_name):
     this_dir = os.path.dirname(os.path.realpath(__file__))
     rdlc = RDLCompiler(message_printer=TestPrinter())
     for file in files:
         rdlc.compile_file(os.path.join(this_dir, file))
     return rdlc.elaborate(top_name)