1 # SPDX-License-Identifier: GPL-2.0
2 # Copyright 2019 Jonathan Corbet <corbet@lwn.net>
4 # Apply kernel-specific tweaks after the initial document processing
7 from docutils import nodes
8 from sphinx import addnodes
9 from sphinx.environment import NoUri
13 # Regex nastiness. Of course.
14 # Try to identify "function()" that's not already marked up some
15 # other way. Sphinx doesn't like a lot of stuff right after a
16 # :c:func: block (i.e. ":c:func:`mmap()`s" flakes out), so the last
17 # bit tries to restrict matches to things that won't create trouble.
19 RE_function = re.compile(r'([\w_][\w\d_]+\(\))')
22 # Many places in the docs refer to common system calls. It is
23 # pointless to try to cross-reference them and, as has been known
24 # to happen, somebody defining a function by these names can lead
25 # to the creation of incorrect and confusing cross references. So
26 # just don't even try with these names.
28 Skipfuncs = [ 'open', 'close', 'read', 'write', 'fcntl', 'mmap',
29 'select', 'poll', 'fork', 'execve', 'clone', 'ioctl',
33 # Find all occurrences of function() and try to replace them with
34 # appropriate cross references.
36 def markup_funcs(docname, app, node):
37 cdom = app.env.domains['c']
41 for m in RE_function.finditer(t):
43 # Include any text prior to function() as a normal text node.
46 repl.append(nodes.Text(t[done:m.start()]))
48 # Go through the dance of getting an xref out of the C domain
50 target = m.group(1)[:-2]
51 target_text = nodes.Text(target + '()')
53 if target not in Skipfuncs:
54 lit_text = nodes.literal(classes=['xref', 'c', 'c-func'])
55 lit_text += target_text
56 pxref = addnodes.pending_xref('', refdomain = 'c',
58 reftarget = target, modname = None,
61 # XXX The Latex builder will throw NoUri exceptions here,
62 # work around that by ignoring them.
65 xref = cdom.resolve_xref(app.env, docname, app.builder,
66 'function', target, pxref, lit_text)
70 # Toss the xref into the list if we got it; otherwise just put
76 repl.append(target_text)
79 repl.append(nodes.Text(t[done:]))
82 def auto_markup(app, doctree, name):
84 # This loop could eventually be improved on. Someday maybe we
85 # want a proper tree traversal with a lot of awareness of which
86 # kinds of nodes to prune. But this works well for now.
88 # The nodes.literal test catches ``literal text``, its purpose is to
89 # avoid adding cross-references to functions that have been explicitly
90 # marked with cc:func:.
92 for para in doctree.traverse(nodes.paragraph):
93 for node in para.traverse(nodes.Text):
94 if not isinstance(node.parent, nodes.literal):
95 node.parent.replace(node, markup_funcs(name, app, node))
98 app.connect('doctree-resolved', auto_markup)
100 'parallel_read_safe': True,
101 'parallel_write_safe': True,