gen_esp_err_to_name.py 15 KB

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