hxtool.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. # coding=utf-8
  2. #
  3. # QEMU hxtool .hx file parsing extension
  4. #
  5. # Copyright (c) 2020 Linaro
  6. #
  7. # This work is licensed under the terms of the GNU GPLv2 or later.
  8. # See the COPYING file in the top-level directory.
  9. """hxtool is a Sphinx extension that implements the hxtool-doc directive"""
  10. # The purpose of this extension is to read fragments of rST
  11. # from .hx files, and insert them all into the current document.
  12. # The rST fragments are delimited by SRST/ERST lines.
  13. # The conf.py file must set the hxtool_srctree config value to
  14. # the root of the QEMU source tree.
  15. # Each hxtool-doc:: directive takes one argument which is the
  16. # path of the .hx file to process, relative to the source tree.
  17. import os
  18. import re
  19. from enum import Enum
  20. from docutils import nodes
  21. from docutils.statemachine import ViewList
  22. from docutils.parsers.rst import directives, Directive
  23. from sphinx.errors import ExtensionError
  24. from sphinx.util.nodes import nested_parse_with_titles
  25. import sphinx
  26. # Sphinx up to 1.6 uses AutodocReporter; 1.7 and later
  27. # use switch_source_input. Check borrowed from kerneldoc.py.
  28. Use_SSI = sphinx.__version__[:3] >= '1.7'
  29. if Use_SSI:
  30. from sphinx.util.docutils import switch_source_input
  31. else:
  32. from sphinx.ext.autodoc import AutodocReporter
  33. __version__ = '1.0'
  34. # We parse hx files with a state machine which may be in one of two
  35. # states: reading the C code fragment, or inside a rST fragment.
  36. class HxState(Enum):
  37. CTEXT = 1
  38. RST = 2
  39. def serror(file, lnum, errtext):
  40. """Raise an exception giving a user-friendly syntax error message"""
  41. raise ExtensionError('%s line %d: syntax error: %s' % (file, lnum, errtext))
  42. def parse_directive(line):
  43. """Return first word of line, if any"""
  44. return re.split(r'\W', line)[0]
  45. def parse_defheading(file, lnum, line):
  46. """Handle a DEFHEADING directive"""
  47. # The input should be "DEFHEADING(some string)", though note that
  48. # the 'some string' could be the empty string. If the string is
  49. # empty we ignore the directive -- these are used only to add
  50. # blank lines in the plain-text content of the --help output.
  51. #
  52. # Return the heading text. We strip out any trailing ':' for
  53. # consistency with other headings in the rST documentation.
  54. match = re.match(r'DEFHEADING\((.*?):?\)', line)
  55. if match is None:
  56. serror(file, lnum, "Invalid DEFHEADING line")
  57. return match.group(1)
  58. def parse_archheading(file, lnum, line):
  59. """Handle an ARCHHEADING directive"""
  60. # The input should be "ARCHHEADING(some string, other arg)",
  61. # though note that the 'some string' could be the empty string.
  62. # As with DEFHEADING, empty string ARCHHEADINGs will be ignored.
  63. #
  64. # Return the heading text. We strip out any trailing ':' for
  65. # consistency with other headings in the rST documentation.
  66. match = re.match(r'ARCHHEADING\((.*?):?,.*\)', line)
  67. if match is None:
  68. serror(file, lnum, "Invalid ARCHHEADING line")
  69. return match.group(1)
  70. def parse_srst(file, lnum, line):
  71. """Handle an SRST directive"""
  72. # The input should be either "SRST", or "SRST(label)".
  73. match = re.match(r'SRST(\((.*?)\))?', line)
  74. if match is None:
  75. serror(file, lnum, "Invalid SRST line")
  76. return match.group(2)
  77. class HxtoolDocDirective(Directive):
  78. """Extract rST fragments from the specified .hx file"""
  79. required_argument = 1
  80. optional_arguments = 1
  81. option_spec = {
  82. 'hxfile': directives.unchanged_required
  83. }
  84. has_content = False
  85. def run(self):
  86. env = self.state.document.settings.env
  87. hxfile = env.config.hxtool_srctree + '/' + self.arguments[0]
  88. # Tell sphinx of the dependency
  89. env.note_dependency(os.path.abspath(hxfile))
  90. state = HxState.CTEXT
  91. # We build up lines of rST in this ViewList, which we will
  92. # later put into a 'section' node.
  93. rstlist = ViewList()
  94. current_node = None
  95. node_list = []
  96. with open(hxfile) as f:
  97. lines = (l.rstrip() for l in f)
  98. for lnum, line in enumerate(lines, 1):
  99. directive = parse_directive(line)
  100. if directive == 'HXCOMM':
  101. pass
  102. elif directive == 'SRST':
  103. if state == HxState.RST:
  104. serror(hxfile, lnum, 'expected ERST, found SRST')
  105. else:
  106. state = HxState.RST
  107. label = parse_srst(hxfile, lnum, line)
  108. if label:
  109. rstlist.append("", hxfile, lnum - 1)
  110. # Build label as _DOCNAME-HXNAME-LABEL
  111. hx = os.path.splitext(os.path.basename(hxfile))[0]
  112. refline = ".. _" + env.docname + "-" + hx + \
  113. "-" + label + ":"
  114. rstlist.append(refline, hxfile, lnum - 1)
  115. elif directive == 'ERST':
  116. if state == HxState.CTEXT:
  117. serror(hxfile, lnum, 'expected SRST, found ERST')
  118. else:
  119. state = HxState.CTEXT
  120. elif directive == 'DEFHEADING' or directive == 'ARCHHEADING':
  121. if directive == 'DEFHEADING':
  122. heading = parse_defheading(hxfile, lnum, line)
  123. else:
  124. heading = parse_archheading(hxfile, lnum, line)
  125. if heading == "":
  126. continue
  127. # Put the accumulated rST into the previous node,
  128. # and then start a fresh section with this heading.
  129. if len(rstlist) > 0:
  130. if current_node is None:
  131. # We had some rST fragments before the first
  132. # DEFHEADING. We don't have a section to put
  133. # these in, so rather than magicing up a section,
  134. # make it a syntax error.
  135. serror(hxfile, lnum,
  136. 'first DEFHEADING must precede all rST text')
  137. self.do_parse(rstlist, current_node)
  138. rstlist = ViewList()
  139. if current_node is not None:
  140. node_list.append(current_node)
  141. section_id = 'hxtool-%d' % env.new_serialno('hxtool')
  142. current_node = nodes.section(ids=[section_id])
  143. current_node += nodes.title(heading, heading)
  144. else:
  145. # Not a directive: put in output if we are in rST fragment
  146. if state == HxState.RST:
  147. # Sphinx counts its lines from 0
  148. rstlist.append(line, hxfile, lnum - 1)
  149. if current_node is None:
  150. # We don't have multiple sections, so just parse the rst
  151. # fragments into a dummy node so we can return the children.
  152. current_node = nodes.section()
  153. self.do_parse(rstlist, current_node)
  154. return current_node.children
  155. else:
  156. # Put the remaining accumulated rST into the last section, and
  157. # return all the sections.
  158. if len(rstlist) > 0:
  159. self.do_parse(rstlist, current_node)
  160. node_list.append(current_node)
  161. return node_list
  162. # This is from kerneldoc.py -- it works around an API change in
  163. # Sphinx between 1.6 and 1.7. Unlike kerneldoc.py, we use
  164. # sphinx.util.nodes.nested_parse_with_titles() rather than the
  165. # plain self.state.nested_parse(), and so we can drop the saving
  166. # of title_styles and section_level that kerneldoc.py does,
  167. # because nested_parse_with_titles() does that for us.
  168. def do_parse(self, result, node):
  169. if Use_SSI:
  170. with switch_source_input(self.state, result):
  171. nested_parse_with_titles(self.state, result, node)
  172. else:
  173. save = self.state.memo.reporter
  174. self.state.memo.reporter = AutodocReporter(result, self.state.memo.reporter)
  175. try:
  176. nested_parse_with_titles(self.state, result, node)
  177. finally:
  178. self.state.memo.reporter = save
  179. def setup(app):
  180. """ Register hxtool-doc directive with Sphinx"""
  181. app.add_config_value('hxtool_srctree', None, 'env')
  182. app.add_directive('hxtool-doc', HxtoolDocDirective)
  183. return dict(
  184. version = __version__,
  185. parallel_read_safe = True,
  186. parallel_write_safe = True
  187. )