rev: release-0.15 scopes/doc/scopesdomain.py -rw-r--r-- 11.3 KiB View raw Log this file
e53de6d7cb89 — Leonard Ritter * win32 build fix 1 year, 5 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
# -*- coding: utf-8 -*-

import re
import string

from docutils import nodes

from sphinx import addnodes
from sphinx.roles import XRefRole
from sphinx.locale import l_, _
from sphinx.domains import Domain, ObjType
from sphinx.directives import ObjectDescription
from sphinx.util.nodes import make_refnode
from sphinx.util.docfields import Field, TypedField

import scopesparser as parser

domain_name = 'scopes'
ref_prefix = 'scopes.'
xref_prefix = 'scopes:'

# RE to split at word boundaries
wsplit_re = re.compile(r'(\W+)')

# REs for C signatures
c_sig_re = re.compile(
    r'''^([^(]*?)          # return type
        ([\w:.]+)  \s*     # thing name (colon allowed for C++)
        (?: \((.*)\) )?    # optionally arguments
        (\s+const)? $      # const specifier
    ''', re.VERBOSE)
c_funcptr_sig_re = re.compile(
    r'''^([^(]+?)          # return type
        (\( [^()]+ \)) \s* # name in parentheses
        \( (.*) \)         # arguments
        (\s+const)? $      # const specifier
    ''', re.VERBOSE)
c_funcptr_arg_sig_re = re.compile(
    r'''^\s*([^(,]+?)      # return type
        \( ([^()]+) \) \s* # name in parentheses
        \( (.*) \)         # arguments
        (\s+const)?        # const specifier
        \s*(?=$|,)         # end with comma or end of string
    ''', re.VERBOSE)
c_funcptr_name_re = re.compile(r'^\(\s*\*\s*(.*?)\s*\)$')

class ScopesObject(ObjectDescription):
    """
    Description of a Scopes language object.
    """

    doc_field_types = [
        TypedField('parameter', label=l_('Parameters'),
                   names=('param', 'parameter', 'arg', 'argument'),
                   typerolename='type', typenames=('type',)),
        Field('returnvalue', label=l_('Returns'), has_arg=False,
              names=('returns', 'return')),
        Field('returntype', label=l_('Return type'), has_arg=False,
              names=('rtype',)),
        Field('prec', label=l_('Precedence'), has_arg=False,
              names=('prec',)),
        Field('assoc', label=l_('Associativity'), has_arg=False,
              names=('assoc',)),
    ]

    # These Scopes types aren't described anywhere, so don't try to create
    # a cross-reference to them
    stopwords = set((
        # 'const', 'void', 'char', 'wchar_t', 'int', 'short',
        # 'long', 'float', 'double', 'unsigned', 'signed', 'FILE',
        # 'clock_t', 'time_t', 'ptrdiff_t', 'size_t', 'ssize_t',
        # 'struct', '_Bool',
    ))

    def handle_signature(self, sig, signode):
        """Transform a Scopes declaration into RST nodes."""
        # first try the function pointer signature regex, it's more specific
        expr = parser.compile(sig, "<signature>").strip()

        def parse_arg(plist, e):
            type_ = parser.ast_type(e)
            if type_ == "list":
                head = e and e[0]
                mode = None
                if head == "?":
                    paramlist = addnodes.desc_optional()
                    paramlist.child_text_separator = ' '
                    for arg in e[1:]:
                        parse_arg(paramlist, arg)
                    plist += paramlist
                elif head == "<splice>":
                    for arg in e[1:]:
                        parse_arg(plist, arg)
                elif head == "|":
                    for i,arg in enumerate(e[1:]):
                        if i > 0:
                            plist += addnodes.desc_parameter("|", " | ", noemph=True)
                        parse_arg(plist, arg)
                else:
                    paramlist = addnodes.desc_parameterlist()
                    paramlist.child_text_separator = ' '
                    for arg in e:
                        parse_arg(paramlist, arg)
                    plist += paramlist
            elif type_ == "symbol":
                if e.startswith('_:'):
                    e = e[2:]
                    plist += addnodes.desc_name(e, ' ' + e + ' ')
                else:
                    plist += addnodes.desc_parameter(e, ' ' + e + ' ')
            else:
                e = repr(e)
                plist += addnodes.desc_parameter(e, e)

        locname = self.objtype

        signode += addnodes.desc_annotation(self.objtype, locname)

        if self.objtype in ('infix-macro',):
            paramlist = addnodes.desc_parameterlist()
            paramlist.child_text_separator = ' '
            name = expr[1]
            parse_arg(paramlist, expr[0])
            paramlist += addnodes.desc_name(name, ' ' + name)
            parse_arg(paramlist, expr[2])
            signode += paramlist
        elif self.objtype in ('symbol-prefix',):
            name = expr[0]
            rest = expr[1]
            signode += addnodes.desc_name(name, name)
            paramlist = addnodes.desc_parameter(rest, rest)
            signode += paramlist
        elif self.objtype in ('define','type'):
            name = expr
            paramlist = addnodes.desc_name(name, name)
            signode += paramlist
        elif self.objtype in ('sugar',):
            paramlist = addnodes.desc_parameterlist()
            paramlist.child_text_separator = ' '
            name = expr[0]
            signode += addnodes.desc_name(name, '')
            paramlist += addnodes.desc_name(name, name + ' ')
            for i,arg in enumerate(expr[1:]):
                parse_arg(paramlist, arg)
            signode += paramlist
        else:
            paramlist = addnodes.desc_parameterlist()
            paramlist.child_text_separator = ' '
            name = expr[0]
            signode += addnodes.desc_name(name, name + ' ')
            for i,arg in enumerate(expr[1:]):
                parse_arg(paramlist, arg)
            signode += paramlist

        return name, self.objtype

    def get_index_text(self, name):
        return '%s (%s)' % name

    def add_target_and_index(self, name, sig, signode):
        #print("add_target_and_index",name,sig,signode)
        # for Scopes items we add a prefix since names are usually not qualified
        # by a module name and so easily clash with e.g. section titles
        #name, objtype = name
        keyname = name[1] + '.' + name[0]
        targetname = ref_prefix + keyname
        if targetname not in self.state.document.ids:
            signode['names'].append(targetname)
            signode['ids'].append(targetname)
            signode['first'] = (not self.names)
            self.state.document.note_explicit_target(signode)
            inv = self.env.domaindata[domain_name]['objects']
            if keyname in inv:
                self.state_machine.reporter.warning(
                    'duplicate Scopes object description of %s, ' % keyname +
                    'other instance in ' + self.env.doc2path(inv[keyname][0]),
                    line=self.lineno)
            inv[keyname] = (self.env.docname, self.objtype)

        indextext = self.get_index_text(name)
        if indextext:
            self.indexnode['entries'].append(('single', indextext,
                                              targetname, ''))

    def before_content(self):
        #print("before_content")
        self.typename_set = False
        if self.name == 'c:type':
            if self.names:
                self.env.ref_context['c:type'] = self.names[0]
                self.typename_set = True

    def after_content(self):
        #print("after_content")
        if self.typename_set:
            self.env.ref_context.pop('c:type', None)

class ScopesXRefRole(XRefRole):
    def process_link(self, env, refnode, has_explicit_title, title, target):
        #print("process_link",env,refnode,has_explicit_title,title,target)
        return title, target

class ScopesDomain(Domain):
    """Scopes language domain."""
    name = domain_name
    label = 'Scopes'
    object_types = {
        'builtin': ObjType(l_('builtin'), 'builtin'),
        'sugar':    ObjType(l_('sugar'),    'sugar'),
        'spice':    ObjType(l_('spice'),    'spice'),
        'infix-macro':    ObjType(l_('infix-macro'), 'infix-macro'),
        'symbol-prefix':    ObjType(l_('symbol-prefix'), 'symbol-prefix'),
        'fn': ObjType(l_('fn'), 'fn'),
        'inline': ObjType(l_('inline'), 'inline'),
        'compiledfn': ObjType(l_('compiledfn'), 'compiledfn'),
        'define': ObjType(l_('define'), 'define'),
        'type': ObjType(l_('type'), 'type'),
        'type-factory': ObjType(l_('type-factory'), 'type-factory'),
    }

    directives = {
        'builtin': ScopesObject,
        'sugar': ScopesObject,
        'spice': ScopesObject,
        'infix-macro': ScopesObject,
        'symbol-prefix': ScopesObject,
        'fn': ScopesObject,
        'inline': ScopesObject,
        'compiledfn': ScopesObject,
        'define': ScopesObject,
        'type': ScopesObject,
        'type-factory': ScopesObject,
    }
    roles = {
        'fn' :  ScopesXRefRole(),
        'inline' :  ScopesXRefRole(),
        'compiledfn' :  ScopesXRefRole(),
        'builtin' :  ScopesXRefRole(),
        'sugar' :  ScopesXRefRole(),
        'spice' :  ScopesXRefRole(),
        'infix-macro' :  ScopesXRefRole(),
        'symbol-prefix':    ScopesXRefRole(),
        'define':    ScopesXRefRole(),
        'obj':    ScopesXRefRole(),
        'type':    ScopesXRefRole(),
        'type-factory':    ScopesXRefRole(),
    }

    #role_map = {
    #    'func' : 'fn',
    #}

    search_roles = [
        'define',
        'sugar',
        'spice',
        'infix-macro',
        'fn',
        'inline',
        'builtin',
        'type',
        'type-factory',
    ]

    initial_data = {
        'objects': {},  # fullname -> docname, objtype
    }

    def clear_doc(self, docname):
        for fullname, (fn, _) in list(self.data['objects'].items()):
            if fn == docname:
                del self.data['objects'][fullname]

    def merge_domaindata(self, docnames, otherdata):
        # XXX check duplicates
        for fullname, (fn, objtype) in otherdata['objects'].items():
            if fn in docnames:
                self.data['objects'][fullname] = (fn, objtype)

    def resolve_xref(self, env, fromdocname, builder,
                     typ, target, node, contnode):
        if typ == 'obj':
            result = self.resolve_any_xref(env, fromdocname, builder, target, node, contnode)
            if result:
                return result[0][1]
        else:
            typ = self.role_map.get(typ, typ)
            target = typ + '.' + target
            if target not in self.data['objects']:
                return None
            obj = self.data['objects'][target]
            return make_refnode(builder, fromdocname, obj[0], ref_prefix + target,
                                contnode, target)

    def resolve_any_xref(self, env, fromdocname, builder, anytarget,
                         node, contnode):
        result = []
        for role in self.search_roles:
            target = role + '.' + anytarget
            if target not in self.data['objects']:
                continue
            obj = self.data['objects'][target]
            result.append(
                (xref_prefix + self.role_for_objtype(obj[1]),
                     make_refnode(builder, fromdocname, obj[0], ref_prefix + target,
                                  contnode, target)))
        return result

    def get_objects(self):
        for refname, (docname, type) in list(self.data['objects'].items()):
            yield (refname, refname, type, docname, ref_prefix + refname, 1)

def setup(app):
    app.add_domain(ScopesDomain)