Coverage for hdl_registers/register_python_generator.py: 100%

22 statements  

« prev     ^ index     » next       coverage.py v6.4.4, created at 2022-09-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/tsfpga/hdl_registers 

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

9 

10import pickle 

11 

12from tsfpga.system_utils import create_file 

13 

14from .register_code_generator import RegisterCodeGenerator 

15 

16 

17class RegisterPythonGenerator(RegisterCodeGenerator): 

18 """ 

19 Generate a Python class with register definitions. 

20 """ 

21 

22 def __init__(self, module_name, generated_info): 

23 """ 

24 Arguments: 

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

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

27 """ 

28 self.module_name = module_name 

29 self.generated_info = generated_info 

30 self._class_name = self._to_pascal_case(module_name) 

31 

32 def create_class(self, register_list, output_folder): 

33 """ 

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

35 that recreates it. 

36 

37 Arguments: 

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

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

40 """ 

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

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

43 

44 py_code = f'''\ 

45{self._file_header} 

46import pickle 

47from pathlib import Path 

48 

49THIS_DIR = Path(__file__).parent 

50 

51 

52class {self._class_name}: 

53 

54 """ 

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

56 """ 

57 

58 def __new__(cls): 

59 """ 

60 Recreate the RegisterList object from binary pickle. 

61 """ 

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

63 return pickle.load(file_handle) 

64 

65 

66def get_register_list(): 

67 """ 

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

69 Recreated from a python pickle file. 

70 """ 

71 return {self._class_name}() 

72''' 

73 create_file(py_file, py_code) 

74 

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

76 pickle.dump(register_list, file_handle) 

77 

78 @property 

79 def _file_header(self): 

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

81 

82 @staticmethod 

83 def _comment(comment, indentation=0): 

84 indent = " " * indentation 

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