Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

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

3# 

4# This file is part of the tsfpga project. 

5# https://tsfpga.com 

6# https://gitlab.com/tsfpga/tsfpga 

7# -------------------------------------------------------------------------------------------------- 

8 

9import pickle 

10 

11from tsfpga.system_utils import create_file 

12from .register_code_generator import RegisterCodeGenerator 

13 

14 

15class RegisterPythonGenerator(RegisterCodeGenerator): 

16 """ 

17 Generate a Python class with register definitions. 

18 """ 

19 

20 def __init__(self, module_name, generated_info): 

21 """ 

22 Arguments: 

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

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

25 """ 

26 self.module_name = module_name 

27 self.generated_info = generated_info 

28 self._class_name = self._to_pascal_case(module_name) 

29 

30 def create_class(self, register_list, output_folder): 

31 """ 

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

33 that recreates it. 

34 

35 Arguments: 

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

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

38 """ 

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

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

41 

42 py_code = f"""\ 

43{self._file_header} 

44import pickle 

45from pathlib import Path 

46 

47THIS_DIR = Path(__file__).parent 

48 

49 

50class {self._class_name}: 

51 

52 def __new__(cls): 

53 # Recreate the RegisterList object from binary pickle. 

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

55 return pickle.load(file_handle) 

56""" 

57 create_file(py_file, py_code) 

58 

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

60 pickle.dump(register_list, file_handle) 

61 

62 @property 

63 def _file_header(self): 

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

65 

66 @staticmethod 

67 def _comment(comment, indentation=0): 

68 indent = " " * indentation 

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