xref: /linux/Documentation/sphinx/automarkup.py (revision 22c55fb9eb92395d999b8404d73e58540d11bdd8)
1# SPDX-License-Identifier: GPL-2.0
2# Copyright 2019 Jonathan Corbet <corbet@lwn.net>
3#
4# Apply kernel-specific tweaks after the initial document processing
5# has been done.
6#
7from docutils import nodes
8import sphinx
9from sphinx import addnodes
10from sphinx.errors import NoUri
11import re
12from itertools import chain
13
14from kernel_abi import get_kernel_abi
15
16#
17# Regex nastiness.  Of course.
18# Try to identify "function()" that's not already marked up some
19# other way.  Sphinx doesn't like a lot of stuff right after a
20# :c:func: block (i.e. ":c:func:`mmap()`s" flakes out), so the last
21# bit tries to restrict matches to things that won't create trouble.
22#
23RE_function = re.compile(r'\b(([a-zA-Z_]\w+)\(\))', flags=re.ASCII)
24
25#
26# Sphinx 3 uses a different C role for each one of struct, union, enum and
27# typedef
28#
29RE_struct = re.compile(r'\b(struct)\s+([a-zA-Z_]\w+)', flags=re.ASCII)
30RE_union = re.compile(r'\b(union)\s+([a-zA-Z_]\w+)', flags=re.ASCII)
31RE_enum = re.compile(r'\b(enum)\s+([a-zA-Z_]\w+)', flags=re.ASCII)
32RE_typedef = re.compile(r'\b(typedef)\s+([a-zA-Z_]\w+)', flags=re.ASCII)
33
34#
35# Detects a reference to a documentation page of the form Documentation/... with
36# an optional extension
37#
38RE_doc = re.compile(r'(\bDocumentation/)?((\.\./)*[\w\-/]+)\.(rst|txt)')
39RE_abi_file = re.compile(r'(\bDocumentation/ABI/[\w\-/]+)')
40RE_abi_symbol = re.compile(r'(\b/(sys|config|proc)/[\w\-/]+)')
41
42RE_namespace = re.compile(r'^\s*..\s*c:namespace::\s*(\S+)\s*$')
43
44#
45# Reserved C words that we should skip when cross-referencing
46#
47Skipnames = [ 'for', 'if', 'register', 'sizeof', 'struct', 'unsigned' ]
48
49
50#
51# Many places in the docs refer to common system calls.  It is
52# pointless to try to cross-reference them and, as has been known
53# to happen, somebody defining a function by these names can lead
54# to the creation of incorrect and confusing cross references.  So
55# just don't even try with these names.
56#
57Skipfuncs = [ 'open', 'close', 'read', 'write', 'fcntl', 'mmap',
58              'select', 'poll', 'fork', 'execve', 'clone', 'ioctl',
59              'socket' ]
60
61c_namespace = ''
62
63#
64# Detect references to commits.
65#
66RE_git = re.compile(r'commit\s+(?P<rev>[0-9a-f]{12,40})(?:\s+\(".*?"\))?',
67    flags=re.IGNORECASE | re.DOTALL)
68
69def markup_refs(docname, app, node):
70    t = node.astext()
71    done = 0
72    repl = [ ]
73    #
74    # Associate each regex with the function that will markup its matches
75    #
76
77    markup_func = {RE_doc: markup_doc_ref,
78                           RE_abi_file: markup_abi_file_ref,
79                           RE_abi_symbol: markup_abi_ref,
80                           RE_function: markup_func_ref_sphinx3,
81                           RE_struct: markup_c_ref,
82                           RE_union: markup_c_ref,
83                           RE_enum: markup_c_ref,
84                           RE_typedef: markup_c_ref,
85                           RE_git: markup_git}
86
87    match_iterators = [regex.finditer(t) for regex in markup_func]
88    #
89    # Sort all references by the starting position in text
90    #
91    sorted_matches = sorted(chain(*match_iterators), key=lambda m: m.start())
92    for m in sorted_matches:
93        #
94        # Include any text prior to match as a normal text node.
95        #
96        if m.start() > done:
97            repl.append(nodes.Text(t[done:m.start()]))
98
99        #
100        # Call the function associated with the regex that matched this text and
101        # append its return to the text
102        #
103        repl.append(markup_func[m.re](docname, app, m))
104
105        done = m.end()
106    if done < len(t):
107        repl.append(nodes.Text(t[done:]))
108    return repl
109
110#
111# Keep track of cross-reference lookups that failed so we don't have to
112# do them again.
113#
114failed_lookups = { }
115def failure_seen(target):
116    return (target) in failed_lookups
117def note_failure(target):
118    failed_lookups[target] = True
119
120#
121# In sphinx3 we can cross-reference to C macro and function, each one with its
122# own C role, but both match the same regex, so we try both.
123#
124def markup_func_ref_sphinx3(docname, app, match):
125    base_target = match.group(2)
126    target_text = nodes.Text(match.group(0))
127    possible_targets = [base_target]
128    # Check if this document has a namespace, and if so, try
129    # cross-referencing inside it first.
130    if c_namespace:
131        possible_targets.insert(0, c_namespace + "." + base_target)
132
133    if base_target not in Skipnames:
134        for target in possible_targets:
135            if (target not in Skipfuncs) and not failure_seen(target):
136                lit_text = nodes.literal(classes=['xref', 'c', 'c-func'])
137                lit_text += target_text
138                xref = add_and_resolve_xref(app, docname, 'c', 'function',
139                                            target, contnode=lit_text)
140                if xref:
141                    return xref
142                note_failure(target)
143
144    return target_text
145
146def markup_c_ref(docname, app, match):
147    class_str = {RE_struct: 'c-struct',
148                 RE_union: 'c-union',
149                 RE_enum: 'c-enum',
150                 RE_typedef: 'c-type',
151                 }
152    reftype_str = {RE_struct: 'struct',
153                   RE_union: 'union',
154                   RE_enum: 'enum',
155                   RE_typedef: 'type',
156                   }
157
158    base_target = match.group(2)
159    target_text = nodes.Text(match.group(0))
160    possible_targets = [base_target]
161    # Check if this document has a namespace, and if so, try
162    # cross-referencing inside it first.
163    if c_namespace:
164        possible_targets.insert(0, c_namespace + "." + base_target)
165
166    if base_target not in Skipnames:
167        for target in possible_targets:
168            if not (match.re == RE_function and target in Skipfuncs):
169                lit_text = nodes.literal(classes=['xref', 'c', class_str[match.re]])
170                lit_text += target_text
171                xref = add_and_resolve_xref(app, docname, 'c',
172                                            reftype_str[match.re], target,
173                                            contnode=lit_text)
174                if xref:
175                    return xref
176
177    return target_text
178
179#
180# Try to replace a documentation reference of the form Documentation/... with a
181# cross reference to that page
182#
183def markup_doc_ref(docname, app, match):
184    absolute = match.group(1)
185    target = match.group(2)
186    if absolute:
187       target = "/" + target
188
189    xref = add_and_resolve_xref(app, docname, 'std', 'doc', target)
190    if xref:
191        return xref
192    else:
193        return nodes.Text(match.group(0))
194
195#
196# Try to replace a documentation reference for ABI symbols and files
197# with a cross reference to that page
198#
199def markup_abi_ref(docname, app, match, warning=False):
200    kernel_abi = get_kernel_abi()
201
202    fname = match.group(1)
203    target = kernel_abi.xref(fname)
204
205    # Kernel ABI doesn't describe such file or symbol
206    if not target:
207        if warning:
208            kernel_abi.log.warning("%s not found", fname)
209        return nodes.Text(match.group(0))
210
211    xref = add_and_resolve_xref(app, docname, 'std', 'ref', target)
212    if xref:
213        return xref
214    else:
215        return nodes.Text(match.group(0))
216
217def add_and_resolve_xref(app, docname, domain, reftype, target, contnode=None):
218    #
219    # Go through the dance of getting an xref out of the corresponding domain
220    #
221    dom_obj = app.env.domains[domain]
222    pxref = addnodes.pending_xref('', refdomain = domain, reftype = reftype,
223                                  reftarget = target, modname = None,
224                                  classname = None, refexplicit = False)
225
226    #
227    # XXX The Latex builder will throw NoUri exceptions here,
228    # work around that by ignoring them.
229    #
230    try:
231        xref = dom_obj.resolve_xref(app.env, docname, app.builder, reftype,
232                                    target, pxref, contnode)
233    except NoUri:
234        xref = None
235
236    if xref:
237        return xref
238    #
239    # We didn't find the xref; if a container node was supplied,
240    # mark it as a broken xref
241    #
242    if contnode:
243        contnode['classes'].append("broken_xref")
244    return contnode
245
246#
247# Variant of markup_abi_ref() that warns whan a reference is not found
248#
249def markup_abi_file_ref(docname, app, match):
250    return markup_abi_ref(docname, app, match, warning=True)
251
252
253def get_c_namespace(app, docname):
254    source = app.env.doc2path(docname)
255    with open(source) as f:
256        for l in f:
257            match = RE_namespace.search(l)
258            if match:
259                return match.group(1)
260    return ''
261
262def markup_git(docname, app, match):
263    # While we could probably assume that we are running in a git
264    # repository, we can't know for sure, so let's just mechanically
265    # turn them into git.kernel.org links without checking their
266    # validity. (Maybe we can do something in the future to warn about
267    # these references if this is explicitly requested.)
268    text = match.group(0)
269    rev = match.group('rev')
270    return nodes.reference('', nodes.Text(text),
271        refuri=f'https://git.kernel.org/torvalds/c/{rev}')
272
273def auto_markup(app, doctree, name):
274    global c_namespace
275    c_namespace = get_c_namespace(app, name)
276    def text_but_not_a_reference(node):
277        # The nodes.literal test catches ``literal text``, its purpose is to
278        # avoid adding cross-references to functions that have been explicitly
279        # marked with cc:func:.
280        if not isinstance(node, nodes.Text) or isinstance(node.parent, nodes.literal):
281            return False
282
283        child_of_reference = False
284        parent = node.parent
285        while parent:
286            if isinstance(parent, nodes.Referential):
287                child_of_reference = True
288                break
289            parent = parent.parent
290        return not child_of_reference
291
292    #
293    # This loop could eventually be improved on.  Someday maybe we
294    # want a proper tree traversal with a lot of awareness of which
295    # kinds of nodes to prune.  But this works well for now.
296    #
297    for para in doctree.traverse(nodes.paragraph):
298        for node in para.traverse(condition=text_but_not_a_reference):
299            node.parent.replace(node, markup_refs(name, app, node))
300
301def setup(app):
302    app.connect('doctree-resolved', auto_markup)
303    return {
304        'parallel_read_safe': True,
305        'parallel_write_safe': True,
306        }
307