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