make-stmconst.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. """
  2. This script reads in the given CMSIS device include file (eg stm32f405xx.h),
  3. extracts relevant peripheral constants, and creates qstrs, mpz's and constants
  4. for the stm module.
  5. """
  6. from __future__ import print_function
  7. import argparse
  8. import re
  9. # Python 2/3 compatibility
  10. import platform
  11. if platform.python_version_tuple()[0] == '2':
  12. def convert_bytes_to_str(b):
  13. return b
  14. elif platform.python_version_tuple()[0] == '3':
  15. def convert_bytes_to_str(b):
  16. try:
  17. return str(b, 'utf8')
  18. except ValueError:
  19. # some files have invalid utf8 bytes, so filter them out
  20. return ''.join(chr(l) for l in b if l <= 126)
  21. # end compatibility code
  22. # given a list of (name,regex) pairs, find the first one that matches the given line
  23. def re_match_first(regexs, line):
  24. for name, regex in regexs:
  25. match = re.match(regex, line)
  26. if match:
  27. return name, match
  28. return None, None
  29. class LexerError(Exception):
  30. def __init__(self, line):
  31. self.line = line
  32. class Lexer:
  33. re_io_reg = r'__IO uint(?P<bits>8|16|32)_t +(?P<reg>[A-Z0-9]+)'
  34. re_comment = r'(?P<comment>[A-Za-z0-9 \-/_()&]+)'
  35. re_addr_offset = r'Address offset: (?P<offset>0x[0-9A-Z]{2,3})'
  36. regexs = (
  37. ('#define hex', re.compile(r'#define +(?P<id>[A-Z0-9_]+) +(?:\(\(uint32_t\))?(?P<hex>0x[0-9A-F]+)U?(?:\))?($| +/\*)')),
  38. ('#define X', re.compile(r'#define +(?P<id>[A-Z0-9_]+) +(?P<id2>[A-Z0-9_]+)($| +/\*)')),
  39. ('#define X+hex', re.compile(r'#define +(?P<id>[A-Za-z0-9_]+) +\((?P<id2>[A-Z0-9_]+) \+ (?P<hex>0x[0-9A-F]+)U?\)($| +/\*)')),
  40. ('#define typedef', re.compile(r'#define +(?P<id>[A-Z0-9_]+(ext)?) +\(\([A-Za-z0-9_]+_TypeDef \*\) (?P<id2>[A-Za-z0-9_]+)\)($| +/\*)')),
  41. ('typedef struct', re.compile(r'typedef struct$')),
  42. ('{', re.compile(r'{$')),
  43. ('}', re.compile(r'}$')),
  44. ('} TypeDef', re.compile(r'} *(?P<id>[A-Z][A-Za-z0-9_]+)_(?P<global>([A-Za-z0-9_]+)?)TypeDef;$')),
  45. ('IO reg', re.compile(re_io_reg + r'; +/\*!< ' + re_comment + r', +' + re_addr_offset + r' *\*/')),
  46. ('IO reg array', re.compile(re_io_reg + r'\[(?P<array>[2-8])\]; +/\*!< ' + re_comment + r', +' + re_addr_offset + r'-(0x[0-9A-Z]{2,3}) *\*/')),
  47. )
  48. def __init__(self, filename):
  49. self.file = open(filename, 'rb')
  50. self.line_number = 0
  51. def next_match(self, strictly_next=False):
  52. while True:
  53. line = self.file.readline()
  54. line = convert_bytes_to_str(line)
  55. self.line_number += 1
  56. if len(line) == 0:
  57. return ('EOF', None)
  58. match = re_match_first(Lexer.regexs, line.strip())
  59. if strictly_next or match[0] is not None:
  60. return match
  61. def must_match(self, kind):
  62. match = self.next_match(strictly_next=True)
  63. if match[0] != kind:
  64. raise LexerError(self.line_number)
  65. return match
  66. def parse_file(filename):
  67. lexer = Lexer(filename)
  68. reg_defs = {}
  69. consts = {}
  70. periphs = []
  71. while True:
  72. m = lexer.next_match()
  73. if m[0] == 'EOF':
  74. break
  75. elif m[0] == '#define hex':
  76. d = m[1].groupdict()
  77. consts[d['id']] = int(d['hex'], base=16)
  78. elif m[0] == '#define X':
  79. d = m[1].groupdict()
  80. if d['id2'] in consts:
  81. consts[d['id']] = consts[d['id2']]
  82. elif m[0] == '#define X+hex':
  83. d = m[1].groupdict()
  84. if d['id2'] in consts:
  85. consts[d['id']] = consts[d['id2']] + int(d['hex'], base=16)
  86. elif m[0] == '#define typedef':
  87. d = m[1].groupdict()
  88. if d['id2'] in consts:
  89. periphs.append((d['id'], consts[d['id2']]))
  90. elif m[0] == 'typedef struct':
  91. lexer.must_match('{')
  92. m = lexer.next_match()
  93. regs = []
  94. while m[0] in ('IO reg', 'IO reg array'):
  95. d = m[1].groupdict()
  96. reg = d['reg']
  97. offset = int(d['offset'], base=16)
  98. bits = int(d['bits'])
  99. comment = d['comment']
  100. if m[0] == 'IO reg':
  101. regs.append((reg, offset, bits, comment))
  102. else:
  103. for i in range(int(d['array'])):
  104. regs.append((reg + str(i), offset + i * bits // 8, bits, comment))
  105. m = lexer.next_match()
  106. if m[0] == '}':
  107. pass
  108. elif m[0] == '} TypeDef':
  109. reg_defs[m[1].groupdict()['id']] = regs
  110. else:
  111. raise LexerError(lexer.line_number)
  112. return periphs, reg_defs
  113. def print_int_obj(val, needed_mpzs):
  114. if -0x40000000 <= val < 0x40000000:
  115. print('MP_ROM_INT(%#x)' % val, end='')
  116. else:
  117. print('MP_ROM_PTR(&mpz_%08x)' % val, end='')
  118. needed_mpzs.add(val)
  119. def print_periph(periph_name, periph_val, needed_qstrs, needed_mpzs):
  120. qstr = periph_name.upper()
  121. print('{ MP_ROM_QSTR(MP_QSTR_%s), ' % qstr, end='')
  122. print_int_obj(periph_val, needed_mpzs)
  123. print(' },')
  124. needed_qstrs.add(qstr)
  125. def print_regs(reg_name, reg_defs, needed_qstrs, needed_mpzs):
  126. reg_name = reg_name.upper()
  127. for r in reg_defs:
  128. qstr = reg_name + '_' + r[0]
  129. print('{ MP_ROM_QSTR(MP_QSTR_%s), ' % qstr, end='')
  130. print_int_obj(r[1], needed_mpzs)
  131. print(' }, // %s-bits, %s' % (r[2], r[3]))
  132. needed_qstrs.add(qstr)
  133. # This version of print regs groups registers together into submodules (eg GPIO submodule).
  134. # This makes the qstrs shorter, and makes the list of constants more manageable (since
  135. # they are not all in one big module) but it is then harder to compile the constants, and
  136. # is more cumbersome to access.
  137. # As such, we don't use this version.
  138. # And for the number of constants we have, this function seems to use about the same amount
  139. # of ROM as print_regs.
  140. def print_regs_as_submodules(reg_name, reg_defs, modules, needed_qstrs):
  141. mod_name_lower = reg_name.lower() + '_'
  142. mod_name_upper = mod_name_lower.upper()
  143. modules.append((mod_name_lower, mod_name_upper))
  144. print("""
  145. STATIC const mp_rom_map_elem_t stm_%s_globals_table[] = {
  146. { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_%s) },
  147. """ % (mod_name_lower, mod_name_upper))
  148. needed_qstrs.add(mod_name_upper)
  149. for r in reg_defs:
  150. print(' { MP_ROM_QSTR(MP_QSTR_%s), MP_ROM_INT(%#x) }, // %s-bits, %s' % (r[0], r[1], r[2], r[3]))
  151. needed_qstrs.add(r[0])
  152. print("""};
  153. STATIC MP_DEFINE_CONST_DICT(stm_%s_globals, stm_%s_globals_table);
  154. const mp_obj_module_t stm_%s_obj = {
  155. .base = { &mp_type_module },
  156. .name = MP_QSTR_%s,
  157. .globals = (mp_obj_dict_t*)&stm_%s_globals,
  158. };
  159. """ % (mod_name_lower, mod_name_lower, mod_name_lower, mod_name_upper, mod_name_lower))
  160. def main():
  161. cmd_parser = argparse.ArgumentParser(description='Extract ST constants from a C header file.')
  162. cmd_parser.add_argument('file', nargs=1, help='input file')
  163. cmd_parser.add_argument('-q', '--qstr', dest='qstr_filename', default='build/stmconst_qstr.h',
  164. help='Specified the name of the generated qstr header file')
  165. cmd_parser.add_argument('--mpz', dest='mpz_filename', default='build/stmconst_mpz.h',
  166. help='the destination file of the generated mpz header')
  167. args = cmd_parser.parse_args()
  168. periphs, reg_defs = parse_file(args.file[0])
  169. # add legacy GPIO constants that were removed when upgrading CMSIS
  170. if 'GPIO' in reg_defs and 'stm32f4' in args.file[0]:
  171. reg_defs['GPIO'].append(['BSRRL', 0x18, 16, 'legacy register'])
  172. reg_defs['GPIO'].append(['BSRRH', 0x1a, 16, 'legacy register'])
  173. modules = []
  174. needed_qstrs = set()
  175. needed_mpzs = set()
  176. print("// Automatically generated from %s by make-stmconst.py" % args.file[0])
  177. print("")
  178. for periph_name, periph_val in periphs:
  179. print_periph(periph_name, periph_val, needed_qstrs, needed_mpzs)
  180. for reg in (
  181. 'ADC',
  182. #'ADC_Common',
  183. #'CAN_TxMailBox',
  184. #'CAN_FIFOMailBox',
  185. #'CAN_FilterRegister',
  186. #'CAN',
  187. 'CRC',
  188. 'DAC',
  189. 'DBGMCU',
  190. 'DMA_Stream',
  191. 'DMA',
  192. 'EXTI',
  193. 'FLASH',
  194. 'GPIO',
  195. 'SYSCFG',
  196. 'I2C',
  197. 'IWDG',
  198. 'PWR',
  199. 'RCC',
  200. 'RTC',
  201. #'SDIO',
  202. 'SPI',
  203. 'TIM',
  204. 'USART',
  205. 'WWDG',
  206. 'RNG',
  207. ):
  208. if reg in reg_defs:
  209. print_regs(reg, reg_defs[reg], needed_qstrs, needed_mpzs)
  210. #print_regs_as_submodules(reg, reg_defs[reg], modules, needed_qstrs)
  211. #print("#define MOD_STM_CONST_MODULES \\")
  212. #for mod_lower, mod_upper in modules:
  213. # print(" { MP_ROM_QSTR(MP_QSTR_%s), MP_ROM_PTR(&stm_%s_obj) }, \\" % (mod_upper, mod_lower))
  214. print("")
  215. with open(args.qstr_filename, 'wt') as qstr_file:
  216. print('#if MICROPY_PY_STM', file=qstr_file)
  217. for qstr in sorted(needed_qstrs):
  218. print('Q({})'.format(qstr), file=qstr_file)
  219. print('#endif // MICROPY_PY_STM', file=qstr_file)
  220. with open(args.mpz_filename, 'wt') as mpz_file:
  221. for mpz in sorted(needed_mpzs):
  222. assert 0 <= mpz <= 0xffffffff
  223. print('STATIC const mp_obj_int_t mpz_%08x = {{&mp_type_int}, '
  224. '{.neg=0, .fixed_dig=1, .alloc=2, .len=2, ' '.dig=(uint16_t*)(const uint16_t[]){%#x, %#x}}};'
  225. % (mpz, mpz & 0xffff, (mpz >> 16) & 0xffff), file=mpz_file)
  226. if __name__ == "__main__":
  227. main()