gen_esp_err_to_name.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. #!/usr/bin/env python
  2. #
  3. # SPDX-FileCopyrightText: 2018-2022 Espressif Systems (Shanghai) CO LTD
  4. # SPDX-License-Identifier: Apache-2.0
  5. import argparse
  6. import collections
  7. import fnmatch
  8. import functools
  9. import os
  10. import re
  11. import textwrap
  12. from io import open
  13. from typing import Any, List, Optional, TextIO
  14. # list files here which should not be parsed
  15. ignore_files: list = list()
  16. # add directories here which should not be parsed, this is a tuple since it will be used with *.startswith()
  17. ignore_dirs = (os.path.join('examples'),
  18. os.path.join('components', 'cmock', 'CMock', 'test'),
  19. os.path.join('components', 'spi_flash', 'sim'))
  20. # macros from here have higher priorities in case of collisions
  21. priority_headers = [os.path.join('components', 'esp_common', 'include', 'esp_err.h')]
  22. # The following headers won't be included. This is useful if they are permanently included from esp_err_to_name.c.in.
  23. dont_include = [os.path.join('soc', 'soc.h'),
  24. os.path.join('esp_err.h')]
  25. err_dict = collections.defaultdict(list) # identified errors are stored here; mapped by the error code
  26. rev_err_dict = dict() # map of error string to error code
  27. unproc_list = list() # errors with unknown codes which depend on other errors
  28. class ErrItem(object):
  29. """
  30. Contains information about the error:
  31. - name - error string
  32. - file - relative path inside the IDF project to the file which defines this error
  33. - include_as - (optional) overwrites the include determined from file
  34. - comment - (optional) comment for the error
  35. - rel_str - (optional) error string which is a base for the error
  36. - rel_off - (optional) offset in relation to the base error
  37. """
  38. def __init__(self, name: str, file: str, include_as: Optional[Any]=None, comment: str='', rel_str: str='', rel_off: int=0) -> None:
  39. self.name = name
  40. self.file = file
  41. self.include_as = include_as
  42. self.comment = comment
  43. self.rel_str = rel_str
  44. self.rel_off = rel_off
  45. def __str__(self) -> str:
  46. ret = self.name + ' from ' + self.file
  47. if (self.rel_str != ''):
  48. ret += ' is (' + self.rel_str + ' + ' + str(self.rel_off) + ')'
  49. if self.comment != '':
  50. ret += ' // ' + self.comment
  51. return ret
  52. def __cmp__(self, other) -> int:
  53. if self.file in priority_headers and other.file not in priority_headers:
  54. return -1
  55. elif self.file not in priority_headers and other.file in priority_headers:
  56. return 1
  57. base = '_BASE'
  58. if self.file == other.file:
  59. if self.name.endswith(base) and not other.name.endswith(base):
  60. return 1
  61. elif not self.name.endswith(base) and other.name.endswith(base):
  62. return -1
  63. self_key = self.file + self.name
  64. other_key = other.file + other.name
  65. if self_key < other_key:
  66. return -1
  67. elif self_key > other_key:
  68. return 1
  69. else:
  70. return 0
  71. class InputError(RuntimeError):
  72. """
  73. Represents and error on the input
  74. """
  75. def __init__(self, p: str, e: str) -> None:
  76. super(InputError, self).__init__(p + ': ' + e)
  77. def process(line: str, idf_path: str, include_as: Any) -> None:
  78. """
  79. Process a line of text from file idf_path (relative to IDF project).
  80. Fills the global list unproc_list and dictionaries err_dict, rev_err_dict
  81. """
  82. if idf_path.endswith('.c'):
  83. # We would not try to include a C file
  84. raise InputError(idf_path, 'This line should be in a header file: %s' % line)
  85. words = re.split(r' +', line, 2)
  86. # words[1] is the error name
  87. # words[2] is the rest of the line (value, base + value, comment)
  88. if len(words) < 3:
  89. raise InputError(idf_path, 'Error at line %s' % line)
  90. line = ''
  91. todo_str = words[2]
  92. comment = ''
  93. # identify possible comment
  94. m = re.search(r'/\*!<(.+?(?=\*/))', todo_str)
  95. if m:
  96. comment = m.group(1).strip()
  97. todo_str = todo_str[:m.start()].strip() # keep just the part before the comment
  98. # identify possible parentheses ()
  99. m = re.search(r'\((.+)\)', todo_str)
  100. if m:
  101. todo_str = m.group(1) # keep what is inside the parentheses
  102. # identify BASE error code, e.g. from the form BASE + 0x01
  103. m = re.search(r'\s*(\w+)\s*\+(.+)', todo_str)
  104. if m:
  105. related = m.group(1) # BASE
  106. todo_str = m.group(2) # keep and process only what is after "BASE +"
  107. # try to match a hexadecimal number
  108. m = re.search(r'0x([0-9A-Fa-f]+)', todo_str)
  109. if m:
  110. num = int(m.group(1), 16)
  111. else:
  112. # Try to match a decimal number. Negative value is possible for some numbers, e.g. ESP_FAIL
  113. m = re.search(r'(-?[0-9]+)', todo_str)
  114. if m:
  115. num = int(m.group(1), 10)
  116. elif re.match(r'\w+', todo_str):
  117. # It is possible that there is no number, e.g. #define ERROR BASE
  118. related = todo_str # BASE error
  119. num = 0 # (BASE + 0)
  120. else:
  121. raise InputError(idf_path, 'Cannot parse line %s' % line)
  122. try:
  123. related
  124. except NameError:
  125. # The value of the error is known at this moment because it do not depends on some other BASE error code
  126. err_dict[num].append(ErrItem(words[1], idf_path, include_as, comment))
  127. rev_err_dict[words[1]] = num
  128. else:
  129. # Store the information available now and compute the error code later
  130. unproc_list.append(ErrItem(words[1], idf_path, include_as, comment, related, num))
  131. def process_remaining_errors() -> None:
  132. """
  133. Create errors which could not be processed before because the error code
  134. for the BASE error code wasn't known.
  135. This works for sure only if there is no multiple-time dependency, e.g.:
  136. #define BASE1 0
  137. #define BASE2 (BASE1 + 10)
  138. #define ERROR (BASE2 + 10) - ERROR will be processed successfully only if it processed later than BASE2
  139. """
  140. for item in unproc_list:
  141. if item.rel_str in rev_err_dict:
  142. base_num = rev_err_dict[item.rel_str]
  143. num = base_num + item.rel_off
  144. err_dict[num].append(ErrItem(item.name, item.file, item.include_as, item.comment))
  145. rev_err_dict[item.name] = num
  146. else:
  147. print(item.rel_str + ' referenced by ' + item.name + ' in ' + item.file + ' is unknown')
  148. del unproc_list[:]
  149. def path_to_include(path: str) -> str:
  150. """
  151. Process the path (relative to the IDF project) in a form which can be used
  152. to include in a C file. Using just the filename does not work all the
  153. time because some files are deeper in the tree. This approach tries to
  154. find an 'include' parent directory an include its subdirectories, e.g.
  155. "components/XY/include/esp32/file.h" will be transported into "esp32/file.h"
  156. So this solution works only works when the subdirectory or subdirectories
  157. are inside the "include" directory. Other special cases need to be handled
  158. here when the compiler gives an unknown header file error message.
  159. """
  160. spl_path = path.split(os.sep)
  161. try:
  162. i = spl_path.index('include')
  163. except ValueError:
  164. # no include in the path -> use just the filename
  165. return os.path.basename(path)
  166. else:
  167. return os.sep.join(spl_path[i + 1:]) # subdirectories and filename in "include"
  168. def print_warning(error_list: List, error_code: int) -> None:
  169. """
  170. Print warning about errors with the same error code
  171. """
  172. print('[WARNING] The following errors have the same code (%d):' % error_code)
  173. for e in error_list:
  174. print(' ' + str(e))
  175. def max_string_width() -> int:
  176. max = 0
  177. for k in err_dict:
  178. for e in err_dict[k]:
  179. x = len(e.name)
  180. if x > max:
  181. max = x
  182. return max
  183. def generate_c_output(fin: TextIO, fout: TextIO) -> None:
  184. """
  185. Writes the output to fout based on th error dictionary err_dict and
  186. template file fin.
  187. """
  188. # make includes unique by using a set
  189. includes = set()
  190. for k in err_dict:
  191. for e in err_dict[k]:
  192. if e.include_as:
  193. includes.add(e.include_as)
  194. else:
  195. includes.add(path_to_include(e.file))
  196. # The order in a set in non-deterministic therefore it could happen that the
  197. # include order will be different in other machines and false difference
  198. # in the output file could be reported. In order to avoid this, the items
  199. # are sorted in a list.
  200. include_list = list(includes)
  201. include_list.sort()
  202. max_width = max_string_width() + 17 + 1 # length of " ERR_TBL_IT()," with spaces is 17
  203. max_decdig = max(len(str(k)) for k in err_dict)
  204. for line in fin:
  205. if re.match(r'@COMMENT@', line):
  206. fout.write('//Do not edit this file because it is autogenerated by ' + os.path.basename(__file__) + '\n')
  207. elif re.match(r'@HEADERS@', line):
  208. for i in include_list:
  209. if i not in dont_include:
  210. fout.write("#if __has_include(\"" + i + "\")\n#include \"" + i + "\"\n#endif\n")
  211. elif re.match(r'@ERROR_ITEMS@', line):
  212. last_file = ''
  213. for k in sorted(err_dict.keys()):
  214. if len(err_dict[k]) > 1:
  215. err_dict[k].sort(key=functools.cmp_to_key(ErrItem.__cmp__))
  216. print_warning(err_dict[k], k)
  217. for e in err_dict[k]:
  218. if e.file != last_file:
  219. last_file = e.file
  220. fout.write(' // %s\n' % last_file)
  221. table_line = (' ERR_TBL_IT(' + e.name + '), ').ljust(max_width) + '/* ' + str(k).rjust(max_decdig)
  222. fout.write('# ifdef %s\n' % e.name)
  223. fout.write(table_line)
  224. hexnum_length = 0
  225. if k > 0: # negative number and zero should be only ESP_FAIL and ESP_OK
  226. hexnum = ' 0x%x' % k
  227. hexnum_length = len(hexnum)
  228. fout.write(hexnum)
  229. if e.comment != '':
  230. if len(e.comment) < 50:
  231. fout.write(' %s' % e.comment)
  232. else:
  233. indent = ' ' * (len(table_line) + hexnum_length + 1)
  234. w = textwrap.wrap(e.comment, width=120, initial_indent=indent, subsequent_indent=indent)
  235. # this couldn't be done with initial_indent because there is no initial_width option
  236. fout.write(' %s' % w[0].strip())
  237. for i in range(1, len(w)):
  238. fout.write('\n%s' % w[i])
  239. fout.write(' */\n# endif\n')
  240. else:
  241. fout.write(line)
  242. def generate_rst_output(fout: TextIO) -> None:
  243. for k in sorted(err_dict.keys()):
  244. v = err_dict[k][0]
  245. fout.write(':c:macro:`{}` '.format(v.name))
  246. if k > 0:
  247. fout.write('**(0x{:x})**'.format(k))
  248. else:
  249. fout.write('({:d})'.format(k))
  250. if len(v.comment) > 0:
  251. fout.write(': {}'.format(v.comment))
  252. fout.write('\n\n')
  253. def main() -> None:
  254. if 'IDF_PATH' in os.environ:
  255. idf_path = os.environ['IDF_PATH']
  256. else:
  257. idf_path = os.path.realpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
  258. parser = argparse.ArgumentParser(description='ESP32 esp_err_to_name lookup generator for esp_err_t')
  259. parser.add_argument('--c_input', help='Path to the esp_err_to_name.c.in template input.',
  260. default=idf_path + '/components/esp_common/src/esp_err_to_name.c.in')
  261. parser.add_argument('--c_output', help='Path to the esp_err_to_name.c output.', default=idf_path + '/components/esp_common/src/esp_err_to_name.c')
  262. parser.add_argument('--rst_output', help='Generate .rst output and save it into this file')
  263. args = parser.parse_args()
  264. include_as_pattern = re.compile(r'\s*//\s*{}: [^"]* "([^"]+)"'.format(os.path.basename(__file__)))
  265. define_pattern = re.compile(r'\s*#define\s+(ESP_ERR_|ESP_OK|ESP_FAIL)')
  266. for root, dirnames, filenames in os.walk(idf_path):
  267. for filename in fnmatch.filter(filenames, '*.[ch]'):
  268. full_path = os.path.join(root, filename)
  269. path_in_idf = os.path.relpath(full_path, idf_path)
  270. if path_in_idf in ignore_files or path_in_idf.startswith(ignore_dirs):
  271. continue
  272. with open(full_path, encoding='utf-8') as f:
  273. try:
  274. include_as = None
  275. for line in f:
  276. line = line.strip()
  277. m = include_as_pattern.search(line)
  278. if m:
  279. include_as = m.group(1)
  280. # match also ESP_OK and ESP_FAIL because some of ESP_ERRs are referencing them
  281. elif define_pattern.match(line):
  282. try:
  283. process(line, path_in_idf, include_as)
  284. except InputError as e:
  285. print(e)
  286. except UnicodeDecodeError:
  287. raise ValueError('The encoding of {} is not Unicode.'.format(path_in_idf))
  288. process_remaining_errors()
  289. if args.rst_output is not None:
  290. with open(args.rst_output, 'w', encoding='utf-8') as fout:
  291. generate_rst_output(fout)
  292. else:
  293. with open(args.c_input, 'r', encoding='utf-8') as fin, open(args.c_output, 'w', encoding='utf-8') as fout:
  294. generate_c_output(fin, fout)
  295. if __name__ == '__main__':
  296. main()