Coverage for hdl_registers/register_python_generator.py: 100%

22 statements  

« prev     ^ index     » next       coverage.py v6.5.0, created at 2023-01-29 22:03 +0000

1# -------------------------------------------------------------------------------------------------- 

2# Copyright (c) Lukas Vik. All rights reserved. 

3# 

4# This file is part of the hdl_registers project, a HDL register generator fast enough to be run 

5# in real time. 

6# https://hdl-registers.com 

7# https://gitlab.com/hdl_registers/hdl_registers 

8# -------------------------------------------------------------------------------------------------- 

9 

10# Standard libraries 

11import pickle 

12 

13# Third party libraries 

14from tsfpga.system_utils import create_file 

15 

16# Local folder libraries 

17from .register_code_generator import RegisterCodeGenerator 

18 

19 

20class RegisterPythonGenerator(RegisterCodeGenerator): 

21 """ 

22 Generate a Python class with register definitions. 

23 """ 

24 

25 def __init__(self, module_name, generated_info): 

26 """ 

27 Arguments: 

28 module_name (str): The name of the register map. 

29 generated_info (list(str)): Will be placed in the file headers. 

30 """ 

31 self.module_name = module_name 

32 self.generated_info = generated_info 

33 self._class_name = self._to_pascal_case(module_name) 

34 

35 def create_class(self, register_list, output_folder): 

36 """ 

37 Save register list object to binary file (pickle) and create a python class 

38 that recreates it. 

39 

40 Arguments: 

41 register_list (RegisterList): This register list object will be saved. 

42 output_folder (pathlib.Path): The pickle and python files will be saved here. 

43 """ 

44 pickle_file = output_folder / f"{self.module_name}.pickle" 

45 py_file = output_folder / f"{self.module_name}.py" 

46 

47 py_code = f'''\ 

48{self._file_header} 

49import pickle 

50from pathlib import Path 

51 

52THIS_DIR = Path(__file__).parent 

53 

54 

55class {self._class_name}: 

56 

57 """ 

58 Instantiate this class to get the RegisterList object for the {self.module_name} module. 

59 """ 

60 

61 def __new__(cls): 

62 """ 

63 Recreate the RegisterList object from binary pickle. 

64 """ 

65 with (THIS_DIR / "{pickle_file.name}").open("rb") as file_handle: 

66 return pickle.load(file_handle) 

67 

68 

69def get_register_list(): 

70 """ 

71 Return a RegisterList object with the registers/constants from the {self.module_name} module. 

72 Recreated from a python pickle file. 

73 """ 

74 return {self._class_name}() 

75''' 

76 create_file(py_file, py_code) 

77 

78 with pickle_file.open("wb") as file_handle: 

79 pickle.dump(register_list, file_handle) 

80 

81 @property 

82 def _file_header(self): 

83 return "".join([self._comment(header_line) for header_line in self.generated_info]) 

84 

85 @staticmethod 

86 def _comment(comment, indentation=0): 

87 indent = " " * indentation 

88 return f"{indent}# {comment}\n"