run_doxygen.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. # Extension to generate Doxygen XML include files, with IDF config & soc macros included
  2. from __future__ import print_function
  3. from __future__ import unicode_literals
  4. from io import open
  5. import glob
  6. import os
  7. import os.path
  8. import re
  9. import subprocess
  10. from .util import copy_if_modified
  11. ALL_KINDS = [
  12. ("function", "Functions"),
  13. ("union", "Unions"),
  14. ("struct", "Structures"),
  15. ("define", "Macros"),
  16. ("typedef", "Type Definitions"),
  17. ("enum", "Enumerations")
  18. ]
  19. """list of items that will be generated for a single API file
  20. """
  21. def setup(app):
  22. # The idf_build_system extension will emit this event once it
  23. app.connect('idf-info', generate_doxygen)
  24. return {'parallel_read_safe': True, 'parallel_write_safe': True, 'version': '0.1'}
  25. def _parse_defines(header_path, sdk_config_path):
  26. defines = {}
  27. # Note: we run C preprocessor here without any -I arguments (except "sdkconfig.h"), so assumption is
  28. # that these headers are all self-contained and don't include any other headers
  29. # not in the same directory
  30. print("Reading macros from %s..." % (header_path))
  31. processed_output = subprocess.check_output(["xtensa-esp32-elf-gcc", "-I", sdk_config_path,
  32. "-dM", "-E", header_path]).decode()
  33. for line in processed_output.split("\n"):
  34. line = line.strip()
  35. m = re.search("#define ([^ ]+) ?(.*)", line)
  36. if m and not m.group(1).startswith("_"):
  37. defines[m.group(1)] = m.group(2)
  38. return defines
  39. def generate_doxygen(app, project_description):
  40. build_dir = os.path.dirname(app.doctreedir.rstrip(os.sep))
  41. sdk_config_path = os.path.join(project_description["build_dir"], "config")
  42. # Parse kconfig macros to pass into doxygen
  43. #
  44. # TODO: this should use the set of "config which can't be changed" eventually,
  45. # not the header
  46. defines = _parse_defines(os.path.join(project_description["build_dir"],
  47. "config", "sdkconfig.h"), sdk_config_path)
  48. # Add all SOC _caps.h headers to the defines
  49. #
  50. # kind of a hack, be nicer to add a component info dict in project_description.json
  51. soc_path = [p for p in project_description["build_component_paths"] if p.endswith("/soc")][0]
  52. soc_headers = glob.glob(os.path.join(soc_path, "soc", project_description["target"],
  53. "include", "soc", "*_caps.h"))
  54. assert len(soc_headers) > 0
  55. for soc_header in soc_headers:
  56. defines.update(_parse_defines(soc_header, sdk_config_path))
  57. # Call Doxygen to get XML files from the header files
  58. print("Calling Doxygen to generate latest XML files")
  59. doxy_env = os.environ
  60. doxy_env.update({
  61. "ENV_DOXYGEN_DEFINES": " ".join('{}={}'.format(key, value) for key, value in defines.items()),
  62. "IDF_PATH": app.config.idf_path,
  63. "IDF_TARGET": app.config.idf_target,
  64. })
  65. doxyfile = os.path.join(app.config.docs_root, "Doxyfile")
  66. print("Running doxygen with doxyfile {}".format(doxyfile))
  67. # note: run Doxygen in the build directory, so the xml & xml_in files end up in there
  68. subprocess.check_call(["doxygen", doxyfile], env=doxy_env, cwd=build_dir)
  69. # Doxygen has generated XML files in 'xml' directory.
  70. # Copy them to 'xml_in', only touching the files which have changed.
  71. copy_if_modified(os.path.join(build_dir, 'xml/'), os.path.join(build_dir, 'xml_in/'))
  72. # Generate 'api_name.inc' files from the Doxygen XML files
  73. convert_api_xml_to_inc(app, doxyfile)
  74. def convert_api_xml_to_inc(app, doxyfile):
  75. """ Generate header_file.inc files
  76. with API reference made of doxygen directives
  77. for each header file
  78. specified in the 'INPUT' statement of the Doxyfile.
  79. """
  80. build_dir = app.config.build_dir
  81. xml_directory_path = "{}/xml".format(build_dir)
  82. inc_directory_path = "{}/inc".format(build_dir)
  83. if not os.path.isdir(xml_directory_path):
  84. raise RuntimeError("Directory {} does not exist!".format(xml_directory_path))
  85. if not os.path.exists(inc_directory_path):
  86. os.makedirs(inc_directory_path)
  87. header_paths = get_doxyfile_input_paths(app, doxyfile)
  88. print("Generating 'api_name.inc' files with Doxygen directives")
  89. for header_file_path in header_paths:
  90. api_name = get_api_name(header_file_path)
  91. inc_file_path = inc_directory_path + "/" + api_name + ".inc"
  92. rst_output = generate_directives(header_file_path, xml_directory_path)
  93. previous_rst_output = ''
  94. if os.path.isfile(inc_file_path):
  95. with open(inc_file_path, "r", encoding='utf-8') as inc_file_old:
  96. previous_rst_output = inc_file_old.read()
  97. if previous_rst_output != rst_output:
  98. with open(inc_file_path, "w", encoding='utf-8') as inc_file:
  99. inc_file.write(rst_output)
  100. def get_doxyfile_input_paths(app, doxyfile_path):
  101. """Get contents of Doxyfile's INPUT statement.
  102. Returns:
  103. Contents of Doxyfile's INPUT.
  104. """
  105. if not os.path.isfile(doxyfile_path):
  106. raise RuntimeError("Doxyfile '{}' does not exist!".format(doxyfile_path))
  107. print("Getting Doxyfile's INPUT")
  108. with open(doxyfile_path, "r", encoding='utf-8') as input_file:
  109. line = input_file.readline()
  110. # read contents of Doxyfile until 'INPUT' statement
  111. while line:
  112. if line.find("INPUT") == 0:
  113. break
  114. line = input_file.readline()
  115. doxyfile_INPUT = []
  116. line = input_file.readline()
  117. # skip input_file contents until end of 'INPUT' statement
  118. while line:
  119. if line.isspace():
  120. # we have reached the end of 'INPUT' statement
  121. break
  122. # process only lines that are not comments
  123. if line.find("#") == -1:
  124. # extract header file path inside components folder
  125. m = re.search("components/(.*\.h)", line) # noqa: W605 - regular expression
  126. header_file_path = m.group(1)
  127. # Replace env variable used for multi target header
  128. header_file_path = header_file_path.replace("$(IDF_TARGET)", app.config.idf_target)
  129. doxyfile_INPUT.append(header_file_path)
  130. # proceed reading next line
  131. line = input_file.readline()
  132. return doxyfile_INPUT
  133. def get_api_name(header_file_path):
  134. """Get name of API from header file path.
  135. Args:
  136. header_file_path: path to the header file.
  137. Returns:
  138. The name of API.
  139. """
  140. api_name = ""
  141. regex = r".*/(.*)\.h"
  142. m = re.search(regex, header_file_path)
  143. if m:
  144. api_name = m.group(1)
  145. return api_name
  146. def generate_directives(header_file_path, xml_directory_path):
  147. """Generate API reference with Doxygen directives for a header file.
  148. Args:
  149. header_file_path: a path to the header file with API.
  150. Returns:
  151. Doxygen directives for the header file.
  152. """
  153. api_name = get_api_name(header_file_path)
  154. # in XLT file name each "_" in the api name is expanded by Doxygen to "__"
  155. xlt_api_name = api_name.replace("_", "__")
  156. xml_file_path = "%s/%s_8h.xml" % (xml_directory_path, xlt_api_name)
  157. rst_output = ""
  158. rst_output = ".. File automatically generated by 'gen-dxd.py'\n"
  159. rst_output += "\n"
  160. rst_output += get_rst_header("Header File")
  161. rst_output += "* :component_file:`" + header_file_path + "`\n"
  162. rst_output += "\n"
  163. try:
  164. import xml.etree.cElementTree as ET
  165. except ImportError:
  166. import xml.etree.ElementTree as ET
  167. tree = ET.ElementTree(file=xml_file_path)
  168. for kind, label in ALL_KINDS:
  169. rst_output += get_directives(tree, kind)
  170. return rst_output
  171. def get_rst_header(header_name):
  172. """Get rst formatted code with a header.
  173. Args:
  174. header_name: name of header.
  175. Returns:
  176. Formatted rst code with the header.
  177. """
  178. rst_output = ""
  179. rst_output += header_name + "\n"
  180. rst_output += "^" * len(header_name) + "\n"
  181. rst_output += "\n"
  182. return rst_output
  183. def select_unions(innerclass_list):
  184. """Select unions from innerclass list.
  185. Args:
  186. innerclass_list: raw list with unions and structures
  187. extracted from Dogygen's xml file.
  188. Returns:
  189. Doxygen directives with unions selected from the list.
  190. """
  191. rst_output = ""
  192. for line in innerclass_list.splitlines():
  193. # union is denoted by "union" at the beginning of line
  194. if line.find("union") == 0:
  195. union_id, union_name = re.split(r"\t+", line)
  196. rst_output += ".. doxygenunion:: "
  197. rst_output += union_name
  198. rst_output += "\n"
  199. return rst_output
  200. def select_structs(innerclass_list):
  201. """Select structures from innerclass list.
  202. Args:
  203. innerclass_list: raw list with unions and structures
  204. extracted from Dogygen's xml file.
  205. Returns:
  206. Doxygen directives with structures selected from the list.
  207. Note: some structures are excluded as described on code below.
  208. """
  209. rst_output = ""
  210. for line in innerclass_list.splitlines():
  211. # structure is denoted by "struct" at the beginning of line
  212. if line.find("struct") == 0:
  213. # skip structures that are part of union
  214. # they are documented by 'doxygenunion' directive
  215. if line.find("::") > 0:
  216. continue
  217. struct_id, struct_name = re.split(r"\t+", line)
  218. rst_output += ".. doxygenstruct:: "
  219. rst_output += struct_name
  220. rst_output += "\n"
  221. rst_output += " :members:\n"
  222. rst_output += "\n"
  223. return rst_output
  224. def get_directives(tree, kind):
  225. """Get directives for specific 'kind'.
  226. Args:
  227. tree: the ElementTree 'tree' of XML by Doxygen
  228. kind: name of API "kind" to be generated
  229. Returns:
  230. Doxygen directives for selected 'kind'.
  231. Note: the header with "kind" name is included.
  232. """
  233. rst_output = ""
  234. if kind in ["union", "struct"]:
  235. innerclass_list = ""
  236. for elem in tree.iterfind('compounddef/innerclass'):
  237. innerclass_list += elem.attrib["refid"] + "\t" + elem.text + "\n"
  238. if kind == "union":
  239. rst_output += select_unions(innerclass_list)
  240. else:
  241. rst_output += select_structs(innerclass_list)
  242. else:
  243. for elem in tree.iterfind(
  244. 'compounddef/sectiondef/memberdef[@kind="%s"]' % kind):
  245. name = elem.find('name')
  246. rst_output += ".. doxygen%s:: " % kind
  247. rst_output += name.text + "\n"
  248. if rst_output:
  249. all_kinds_dict = dict(ALL_KINDS)
  250. rst_output = get_rst_header(all_kinds_dict[kind]) + rst_output + "\n"
  251. return rst_output