gen_esp_err_to_name.py 15 KB

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