hxtool.py 7.9 KB

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