cdomain.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. # -*- coding: utf-8; mode: python -*-
  2. # pylint: disable=W0141,C0113,C0103,C0325
  3. u"""
  4. cdomain
  5. ~~~~~~~
  6. Replacement for the sphinx c-domain.
  7. :copyright: Copyright (C) 2016 Markus Heiser
  8. :license: GPL Version 2, June 1991 see Linux/COPYING for details.
  9. List of customizations:
  10. * Moved the *duplicate C object description* warnings for function
  11. declarations in the nitpicky mode. See Sphinx documentation for
  12. the config values for ``nitpick`` and ``nitpick_ignore``.
  13. * Add option 'name' to the "c:function:" directive. With option 'name' the
  14. ref-name of a function can be modified. E.g.::
  15. .. c:function:: int ioctl( int fd, int request )
  16. :name: VIDIOC_LOG_STATUS
  17. The func-name (e.g. ioctl) remains in the output but the ref-name changed
  18. from 'ioctl' to 'VIDIOC_LOG_STATUS'. The function is referenced by::
  19. * :c:func:`VIDIOC_LOG_STATUS` or
  20. * :any:`VIDIOC_LOG_STATUS` (``:any:`` needs sphinx 1.3)
  21. * Handle signatures of function-like macros well. Don't try to deduce
  22. arguments types of function-like macros.
  23. """
  24. from docutils import nodes
  25. from docutils.parsers.rst import directives
  26. import sphinx
  27. from sphinx import addnodes
  28. from sphinx.domains.c import c_funcptr_sig_re, c_sig_re
  29. from sphinx.domains.c import CObject as Base_CObject
  30. from sphinx.domains.c import CDomain as Base_CDomain
  31. from itertools import chain
  32. import re
  33. __version__ = '1.1'
  34. # Get Sphinx version
  35. major, minor, patch = sphinx.version_info[:3]
  36. # Namespace to be prepended to the full name
  37. namespace = None
  38. #
  39. # Handle trivial newer c domain tags that are part of Sphinx 3.1 c domain tags
  40. # - Store the namespace if ".. c:namespace::" tag is found
  41. #
  42. RE_namespace = re.compile(r'^\s*..\s*c:namespace::\s*(\S+)\s*$')
  43. def markup_namespace(match):
  44. global namespace
  45. namespace = match.group(1)
  46. return ""
  47. #
  48. # Handle c:macro for function-style declaration
  49. #
  50. RE_macro = re.compile(r'^\s*..\s*c:macro::\s*(\S+)\s+(\S.*)\s*$')
  51. def markup_macro(match):
  52. return ".. c:function:: " + match.group(1) + ' ' + match.group(2)
  53. #
  54. # Handle newer c domain tags that are evaluated as .. c:type: for
  55. # backward-compatibility with Sphinx < 3.0
  56. #
  57. RE_ctype = re.compile(r'^\s*..\s*c:(struct|union|enum|enumerator|alias)::\s*(.*)$')
  58. def markup_ctype(match):
  59. return ".. c:type:: " + match.group(2)
  60. #
  61. # Handle newer c domain tags that are evaluated as :c:type: for
  62. # backward-compatibility with Sphinx < 3.0
  63. #
  64. RE_ctype_refs = re.compile(r':c:(var|struct|union|enum|enumerator)::`([^\`]+)`')
  65. def markup_ctype_refs(match):
  66. return ":c:type:`" + match.group(2) + '`'
  67. #
  68. # Simply convert :c:expr: and :c:texpr: into a literal block.
  69. #
  70. RE_expr = re.compile(r':c:(expr|texpr):`([^\`]+)`')
  71. def markup_c_expr(match):
  72. return '\ ``' + match.group(2) + '``\ '
  73. #
  74. # Parse Sphinx 3.x C markups, replacing them by backward-compatible ones
  75. #
  76. def c_markups(app, docname, source):
  77. result = ""
  78. markup_func = {
  79. RE_namespace: markup_namespace,
  80. RE_expr: markup_c_expr,
  81. RE_macro: markup_macro,
  82. RE_ctype: markup_ctype,
  83. RE_ctype_refs: markup_ctype_refs,
  84. }
  85. lines = iter(source[0].splitlines(True))
  86. for n in lines:
  87. match_iterators = [regex.finditer(n) for regex in markup_func]
  88. matches = sorted(chain(*match_iterators), key=lambda m: m.start())
  89. for m in matches:
  90. n = n[:m.start()] + markup_func[m.re](m) + n[m.end():]
  91. result = result + n
  92. source[0] = result
  93. #
  94. # Now implements support for the cdomain namespacing logic
  95. #
  96. def setup(app):
  97. # Handle easy Sphinx 3.1+ simple new tags: :c:expr and .. c:namespace::
  98. app.connect('source-read', c_markups)
  99. if (major == 1 and minor < 8):
  100. app.override_domain(CDomain)
  101. else:
  102. app.add_domain(CDomain, override=True)
  103. return dict(
  104. version = __version__,
  105. parallel_read_safe = True,
  106. parallel_write_safe = True
  107. )
  108. class CObject(Base_CObject):
  109. """
  110. Description of a C language object.
  111. """
  112. option_spec = {
  113. "name" : directives.unchanged
  114. }
  115. def handle_func_like_macro(self, sig, signode):
  116. u"""Handles signatures of function-like macros.
  117. If the objtype is 'function' and the the signature ``sig`` is a
  118. function-like macro, the name of the macro is returned. Otherwise
  119. ``False`` is returned. """
  120. global namespace
  121. if not self.objtype == 'function':
  122. return False
  123. m = c_funcptr_sig_re.match(sig)
  124. if m is None:
  125. m = c_sig_re.match(sig)
  126. if m is None:
  127. raise ValueError('no match')
  128. rettype, fullname, arglist, _const = m.groups()
  129. arglist = arglist.strip()
  130. if rettype or not arglist:
  131. return False
  132. arglist = arglist.replace('`', '').replace('\\ ', '') # remove markup
  133. arglist = [a.strip() for a in arglist.split(",")]
  134. # has the first argument a type?
  135. if len(arglist[0].split(" ")) > 1:
  136. return False
  137. # This is a function-like macro, it's arguments are typeless!
  138. signode += addnodes.desc_name(fullname, fullname)
  139. paramlist = addnodes.desc_parameterlist()
  140. signode += paramlist
  141. for argname in arglist:
  142. param = addnodes.desc_parameter('', '', noemph=True)
  143. # separate by non-breaking space in the output
  144. param += nodes.emphasis(argname, argname)
  145. paramlist += param
  146. if namespace:
  147. fullname = namespace + "." + fullname
  148. return fullname
  149. def handle_signature(self, sig, signode):
  150. """Transform a C signature into RST nodes."""
  151. global namespace
  152. fullname = self.handle_func_like_macro(sig, signode)
  153. if not fullname:
  154. fullname = super(CObject, self).handle_signature(sig, signode)
  155. if "name" in self.options:
  156. if self.objtype == 'function':
  157. fullname = self.options["name"]
  158. else:
  159. # FIXME: handle :name: value of other declaration types?
  160. pass
  161. else:
  162. if namespace:
  163. fullname = namespace + "." + fullname
  164. return fullname
  165. def add_target_and_index(self, name, sig, signode):
  166. # for C API items we add a prefix since names are usually not qualified
  167. # by a module name and so easily clash with e.g. section titles
  168. targetname = 'c.' + name
  169. if targetname not in self.state.document.ids:
  170. signode['names'].append(targetname)
  171. signode['ids'].append(targetname)
  172. signode['first'] = (not self.names)
  173. self.state.document.note_explicit_target(signode)
  174. inv = self.env.domaindata['c']['objects']
  175. if (name in inv and self.env.config.nitpicky):
  176. if self.objtype == 'function':
  177. if ('c:func', name) not in self.env.config.nitpick_ignore:
  178. self.state_machine.reporter.warning(
  179. 'duplicate C object description of %s, ' % name +
  180. 'other instance in ' + self.env.doc2path(inv[name][0]),
  181. line=self.lineno)
  182. inv[name] = (self.env.docname, self.objtype)
  183. indextext = self.get_index_text(name)
  184. if indextext:
  185. if major == 1 and minor < 4:
  186. # indexnode's tuple changed in 1.4
  187. # https://github.com/sphinx-doc/sphinx/commit/e6a5a3a92e938fcd75866b4227db9e0524d58f7c
  188. self.indexnode['entries'].append(
  189. ('single', indextext, targetname, ''))
  190. else:
  191. self.indexnode['entries'].append(
  192. ('single', indextext, targetname, '', None))
  193. class CDomain(Base_CDomain):
  194. """C language domain."""
  195. name = 'c'
  196. label = 'C'
  197. directives = {
  198. 'function': CObject,
  199. 'member': CObject,
  200. 'macro': CObject,
  201. 'type': CObject,
  202. 'var': CObject,
  203. }