Coverage for hdl_registers/generator/c/header.py: 98%

108 statements  

« prev     ^ index     » next       coverage.py v7.6.10, created at 2025-01-28 20:51 +0000

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

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

3# 

4# This file is part of the hdl-registers project, an HDL register generator fast enough to run 

5# in real time. 

6# https://hdl-registers.com 

7# https://github.com/hdl-registers/hdl-registers 

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

9 

10# Standard libraries 

11from pathlib import Path 

12from typing import TYPE_CHECKING, Any, Optional 

13 

14# First party libraries 

15from hdl_registers.constant.bit_vector_constant import UnsignedVectorConstant 

16from hdl_registers.constant.boolean_constant import BooleanConstant 

17from hdl_registers.constant.float_constant import FloatConstant 

18from hdl_registers.constant.integer_constant import IntegerConstant 

19from hdl_registers.constant.string_constant import StringConstant 

20from hdl_registers.field.enumeration import Enumeration 

21from hdl_registers.generator.register_code_generator import RegisterCodeGenerator 

22from hdl_registers.register import Register 

23from hdl_registers.register_list import RegisterList 

24 

25if TYPE_CHECKING: 

26 # First party libraries 

27 from hdl_registers.register_array import RegisterArray 

28 

29# There is no unit test of this class that checks the generated code. It is instead functionally 

30# tested in the file 'test_compiled_c_code.py'. That test generates C code from an example 

31# register set, compiles it and performs some run-time assertions in a C program. 

32# That test is considered more meaningful and exhaustive than a unit test would be. 

33 

34 

35class CHeaderGenerator(RegisterCodeGenerator): 

36 """ 

37 Generate a C header. 

38 See the :ref:`generator_c` article for usage details. 

39 

40 The header will contain: 

41 

42 * Constant values for all :ref:`register constants <constant_overview>`. 

43 

44 * Enumeration types for all :ref:`field_enumeration`. 

45 

46 * A ``struct`` type with all registers as members, which can be memory mapped directly. 

47 

48 * For each register, ``#define`` constants with the index and address of the register. 

49 

50 * For each field in each register, ``#define`` constants with the bit shift, bit mask and 

51 inverse bit mask of the field. 

52 """ 

53 

54 __version__ = "1.0.0" 

55 

56 SHORT_DESCRIPTION = "C header" 

57 

58 COMMENT_START = "//" 

59 

60 # The most commonly used indentation. 

61 # For code at the top level. 

62 DEFAULT_INDENTATION_LEVEL = 0 

63 

64 @property 

65 def output_file(self) -> Path: 

66 """ 

67 Result will be placed in this file. 

68 """ 

69 return self.output_folder / self._file_name 

70 

71 def __init__( 

72 self, register_list: RegisterList, output_folder: Path, file_name: Optional[str] = None 

73 ): 

74 """ 

75 For argument description, please see the super class. 

76 

77 Arguments: 

78 file_name: Optionally specify an explicit result file name. 

79 If not specified, the name will be derived from the name of the register list. 

80 """ 

81 super().__init__(register_list=register_list, output_folder=output_folder) 

82 

83 self._file_name = f"{self.name}_regs.h" if file_name is None else file_name 

84 

85 def get_code(self, **kwargs: Any) -> str: 

86 """ 

87 Get a complete C header with all constants and all registers. 

88 """ 

89 define_name = f"{self.name.upper()}_REGS_H" 

90 

91 c_code = f"""\ 

92#ifndef {define_name} 

93#define {define_name} 

94 

95{self._constants()} 

96{self._number_of_registers()} 

97{self._register_struct()} 

98{self._register_defines()}\ 

99#endif {self.comment(define_name)}""" 

100 

101 return c_code 

102 

103 def _register_struct(self) -> str: 

104 array_structs = "" 

105 

106 register_struct_type = f"{self.name}_regs_t" 

107 

108 register_struct = self.comment("Type for this register list.") 

109 register_struct += f"typedef struct {register_struct_type}\n" 

110 register_struct += "{\n" 

111 

112 for register_object in self.iterate_register_objects(): 

113 if isinstance(register_object, Register): 

114 register_struct += self.comment(f'Mode "{register_object.mode.name}".', indent=2) 

115 register_struct += f" uint32_t {register_object.name};\n" 

116 

117 else: 

118 array_struct_type = f"{self.name}_{register_object.name}_t" 

119 

120 array_structs += self.comment( 

121 f"Type for the '{register_object.name}' register array." 

122 ) 

123 array_structs += f"typedef struct {array_struct_type}\n" 

124 array_structs += "{\n" 

125 for register in register_object.registers: 

126 array_structs += self.comment(f"Mode '{register.mode.name}'.", indent=2) 

127 array_structs += f" uint32_t {register.name};\n" 

128 array_structs += f"} {array_struct_type};\n\n" 

129 

130 register_struct += ( 

131 f" {array_struct_type} {register_object.name}[{register_object.length}];\n" 

132 ) 

133 

134 register_struct += f"} {register_struct_type};\n" 

135 

136 return array_structs + register_struct 

137 

138 def _number_of_registers(self) -> str: 

139 # It is possible that we have constants but no registers 

140 num_regs = 0 

141 if self.register_list.register_objects: 

142 num_regs = self.register_list.register_objects[-1].index + 1 

143 

144 c_code = self.comment("Number of registers within this register list.") 

145 c_code += f"#define {self.name.upper()}_NUM_REGS ({num_regs}u)\n" 

146 

147 return c_code 

148 

149 def _register_defines(self) -> str: 

150 c_code = "" 

151 for register, register_array in self.iterate_registers(): 

152 c_code += self._addr_define(register, register_array) 

153 c_code += self._field_definitions(register, register_array) 

154 c_code += "\n" 

155 

156 return c_code 

157 

158 def _addr_define(self, register: Register, register_array: Optional["RegisterArray"]) -> str: 

159 name = self.qualified_register_name( 

160 register=register, register_array=register_array 

161 ).upper() 

162 

163 register_description = self.register_description( 

164 register=register, register_array=register_array 

165 ) 

166 

167 register_array_comment = ( 

168 f" (array_index < {register_array.length})" if register_array else "" 

169 ) 

170 comment = [ 

171 f"Address of the {register_description}{register_array_comment}.", 

172 f"Mode '{register.mode.name}'.", 

173 ] 

174 c_code = self.comment_block(comment) 

175 

176 if register_array: 

177 c_code += ( 

178 f"#define {name}_INDEX(array_index) ({register_array.base_index}u + " 

179 f"(array_index) * {len(register_array.registers)}u + {register.index}u)\n" 

180 ) 

181 c_code += f"#define {name}_ADDR(array_index) (4u * {name}_INDEX(array_index))\n" 

182 else: 

183 c_code += f"#define {name}_INDEX ({register.index}u)\n" 

184 c_code += f"#define {name}_ADDR (4u * {name}_INDEX)\n" 

185 

186 return c_code 

187 

188 def _field_definitions( 

189 self, register: Register, register_array: Optional["RegisterArray"] 

190 ) -> str: 

191 c_code = "" 

192 for field in register.fields: 

193 field_description = self.field_description( 

194 register=register, register_array=register_array, field=field 

195 ) 

196 c_code += self.comment(f"Attributes for the {field_description}.") 

197 

198 name = self.qualified_field_name( 

199 register=register, field=field, register_array=register_array 

200 ).upper() 

201 c_code += f"#define {name}_SHIFT ({field.base_index}u)\n" 

202 c_code += f'#define {name}_MASK (0b{"1" * field.width}u << {field.base_index}u)\n' 

203 c_code += f"#define {name}_MASK_INVERSE (~{name}_MASK)\n" 

204 

205 if isinstance(field, Enumeration): 

206 # Enums in C export their enumerators to the surrounding scope, causing huge risk of 

207 # name clashes. 

208 # Hence we give the enumerators long names qualified with the register name, etc. 

209 name_value_pairs = [ 

210 f"{name}_{element.name.upper()} = {element.value}," 

211 for element in field.elements 

212 ] 

213 separator = "\n " 

214 

215 c_code += f"""\ 

216enum {self.to_pascal_case(name)} 

217{ 

218 {separator.join(name_value_pairs)} 

219} ; 

220""" 

221 

222 return c_code 

223 

224 def _constants(self) -> str: 

225 c_code = "" 

226 

227 def define(name: str, value: str) -> str: 

228 return f"#define {name} ({value})\n" 

229 

230 for constant in self.iterate_constants(): 

231 c_code += self.comment(f"Value of register constant '{constant.name}'.") 

232 

233 constant_name = f"{self.name.upper()}_{constant.name.upper()}" 

234 

235 if isinstance(constant, BooleanConstant): 

236 c_code += define(constant_name, str(constant.value).lower()) 

237 elif isinstance(constant, IntegerConstant): 

238 # No suffix -> "int", i.e. signed integer of at least 32 bits. 

239 c_code += define(constant_name, str(constant.value)) 

240 elif isinstance(constant, FloatConstant): 

241 # No suffix -> "double" (https://stackoverflow.com/questions/13276862). 

242 # Matches the VHDL type which is at least 64 bits (IEEE 1076-2008, 5.2.5.1). 

243 # Note that casting a Python float to string guarantees full precision in the 

244 # resulting string: https://stackoverflow.com/a/60026172 

245 c_code += define(constant_name, str(constant.value)) 

246 elif isinstance(constant, StringConstant): 

247 # C string literal: Raw value enclosed in double quotation marks. 

248 # Without "static", we get a linker warning about multiple definitions 

249 # despite the multiple-include guard. 

250 # See here https://stackoverflow.com/a/9196883 for some other information. 

251 c_code += f'static char *{constant_name} = "{constant.value}";\n' 

252 elif isinstance(constant, UnsignedVectorConstant): 

253 # "unsigned" and "long" as suffix. 

254 # Makes it possible to use large numbers for e.g. base addresses. 

255 c_code += define( 

256 constant_name, f"{constant.prefix}{constant.value_without_separator}UL" 

257 ) 

258 else: 

259 raise ValueError(f"Got unexpected constant type. {constant}") 

260 

261 return c_code