Source

sphinx-contrib / phpdomain / sphinxcontrib / phpdomain.py

  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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
# -*- coding: utf-8 -*-
"""
    sphinx.domains.php
    ~~~~~~~~~~~~~~~~~~~

    The PHP domain. Based off of the rubydomain by SHIBUKAWA Yoshiki

    :copyright: Copyright 2011 by Mark Story
    :license: BSD, see LICENSE for details.
"""

import re

from docutils import nodes
from docutils.parsers.rst import directives

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



php_sig_re = re.compile(
    r'''^ ([\w.]*\:\:)?          # class name(s)
          (\$?\w+)  \s*          # thing name
          (?: \((.*)\)           # optional: arguments
          (?:\s* -> \s* (.*))?   # return annotation
          )? $                   # and nothing more
          ''', re.VERBOSE)


php_paramlist_re = re.compile(r'([\[\],])')  # split at '[', ']' and ','

NS = '\\'

separators = {
  'method': '::',
  'function': NS,
  'class': NS,
  'namespace': NS,
  'global': '',
  'const': '::',
  'attr': '::$',
  'exception': '',
  'staticmethod': '::',
  'interface': NS,
  'trait': NS
}

php_separator = re.compile(r"(\w+)?(?:[:]{2})?")


def php_rsplit(fullname):
    items = [item for item in php_separator.findall(fullname)]
    return ''.join(items[:-2]), ''.join(items[1:-1])


class PhpObject(ObjectDescription):
    """
    Description of a general PHP object.
    """
    option_spec = {
        'noindex': directives.flag,
        'module': directives.unchanged,
    }

    doc_field_types = [
        TypedField('parameter', label=l_('Parameters'),
                   names=('param', 'parameter', 'arg', 'argument'),
                   typerolename='obj', typenames=('paramtype', 'type')),
        TypedField('variable', label=l_('Variables'), rolename='obj',
                   names=('var', 'ivar', 'cvar'),
                   typerolename='obj', typenames=('vartype',)),
        GroupedField('exceptions', label=l_('Throws'), rolename='exc',
                     names=('throws', 'throw', 'exception', 'except'),
                     can_collapse=True),
        Field('returnvalue', label=l_('Returns'), has_arg=False,
              names=('returns', 'return')),
        Field('returntype', label=l_('Return type'), has_arg=False,
              names=('rtype', 'returntype')),
    ]

    def get_signature_prefix(self, sig):
        """
        May return a prefix to put before the object name in the signature.
        """
        return ''

    def needs_arglist(self):
        """
        May return true if an empty argument list is to be generated even if
        the document contains none.
        """
        return False

    def handle_signature(self, sig, signode):
        """
        Transform a PHP signature into RST nodes.
        Returns (fully qualified name of the thing, classname if any).

        If inside a class, the current class name is handled intelligently:
        * it is stripped from the displayed name if present
        * it is added to the full name (return value) if not present
        """
        m = php_sig_re.match(sig)
        if m is None:
            raise ValueError

        name_prefix, name, arglist, retann = m.groups()

        if not name_prefix:
            name_prefix = ""

        # determine module and class name (if applicable), as well as full name
        modname = self.options.get(
            'namespace', self.env.temp_data.get('php:namespace'))

        classname = self.env.temp_data.get('php:class')
        separator = separators[self.objtype]

        if self.objtype == 'global' or self.objtype == 'function':
            add_module = False
            modname = None
            classname = None
            fullname = name
        else:
            add_module = True
            # name_prefix and a non-static method, means the classname was 
            # repeated. Trim off the <class>::
            if name_prefix and self.objtype != 'staticmethod':
                if name_prefix.startswith(classname):
                    name_prefix = name_prefix[len(classname):].rstrip('::')
                classname = classname.rstrip('::')
                fullname = name_prefix + classname + separator + name
            elif name_prefix:
                classname = classname.rstrip('::')
                fullname = name_prefix + name

            # Currently in a class, but not creating another class,
            elif classname and not self.objtype in ['class', 'exception', 'interface', 'trait']:
                if not self.env.temp_data['php:in_class']:
                    name_prefix = classname + separator

                fullname = classname + separator + name
            else:
                classname = ''
                fullname = name

        signode['namespace'] = modname
        signode['class'] = self.class_name = classname
        signode['fullname'] = fullname

        sig_prefix = self.get_signature_prefix(sig)

        if sig_prefix:
            signode += addnodes.desc_annotation(sig_prefix, sig_prefix)

        if name_prefix:
            if modname and not self.env.temp_data['php:in_class']:
                name_prefix = modname + NS + name_prefix
            signode += addnodes.desc_addname(name_prefix, name_prefix)

        elif add_module and self.env.config.add_module_names:
            if self.objtype == 'global':
                nodetext = ''
                signode += addnodes.desc_addname(nodetext, nodetext)
            else:
                modname = self.options.get(
                    'namespace', self.env.temp_data.get('php:namespace'))

                if modname and not self.env.temp_data.get('php:in_class', False):
                    nodetext = modname + NS
                    signode += addnodes.desc_addname(nodetext, nodetext)

        signode += addnodes.desc_name(name, name)
        if not arglist:
            if self.needs_arglist():
                # for callables, add an empty parameter list
                signode += addnodes.desc_parameterlist()
            if retann:
                signode += addnodes.desc_returns(retann, retann)
            return fullname, name_prefix

        signode += addnodes.desc_parameterlist()

        stack = [signode[-1]]
        for token in php_paramlist_re.split(arglist):
            if token == '[':
                opt = addnodes.desc_optional()
                stack[-1] += opt
                stack.append(opt)
            elif token == ']':
                try:
                    stack.pop()
                except IndexError:
                    raise ValueError
            elif not token or token == ',' or token.isspace():
                pass
            else:
                token = token.strip()
                stack[-1] += addnodes.desc_parameter(token, token)
        if len(stack) != 1:
            raise ValueError
        if retann:
            signode += addnodes.desc_returns(retann, retann)
        return fullname, name_prefix

    def get_index_text(self, modname, name):
        """
        Return the text for the index entry of the object.
        """
        raise NotImplementedError('must be implemented in subclasses')

    def _is_class_member(self):
        return self.objtype.startswith('method') or self.objtype.startswith('attr')

    def add_target_and_index(self, name_cls, sig, signode):
        if self.objtype == 'global':
            modname = ''
        else:
            modname = self.options.get(
                'namespace', self.env.temp_data.get('php:namespace'))
        separator = separators[self.objtype]
        if self._is_class_member():
            if signode['class']:
                prefix = modname and modname + NS or ''
            else:
                prefix = modname and modname + NS or ''
        else:
            prefix = modname and modname + NS or ''
        fullname = prefix + name_cls[0]

        # note target
        if fullname not in self.state.document.ids:
            signode['names'].append(fullname)
            signode['ids'].append(fullname)
            signode['first'] = (not self.names)
            self.state.document.note_explicit_target(signode)
            objects = self.env.domaindata['php']['objects']
            if fullname in objects:
                self.env.warn(
                    self.env.docname,
                    'duplicate object description of %s, ' % fullname +
                    'other instance in ' +
                    self.env.doc2path(objects[fullname][0]),
                    self.lineno)
            objects[fullname] = (self.env.docname, self.objtype)

        indextext = self.get_index_text(modname, name_cls)
        if indextext:
            self.indexnode['entries'].append(('single', indextext,
                                              fullname, fullname))



class PhpGloballevel(PhpObject):
    """
    Description of an object on global level (global variables).
    """

    def get_index_text(self, modname, name_cls):
        if self.objtype == 'global':
            return _('%s (global variable)') % name_cls[0]
        else:
            return ''

class PhpNamespacelevel(PhpObject):
    """
    Description of an object on namespace level (functions, constants).
    """

    def needs_arglist(self):
        return self.objtype == 'function'

    def get_signature_prefix(self, sig):
        """
        Adds class prefix for constants created inside classes
        """
        if self.objtype == 'const':
            return _('constant ')
        if self.class_name and self.class_name != '':
            return self.class_name + '::'

    def get_index_text(self, modname, name_cls):
        if self.objtype == 'function':
            if not modname:
                return _('%s() (global function)') % name_cls[0]
            return _('%s() (function in %s)') % (name_cls[0], modname)
        elif self.objtype == 'const' and self.class_name != '':
            return _('%s (class constant)') % (name_cls[0])
        elif self.objtype == 'const':
            if not modname:
                return _('%s (global constant)') % (name_cls[0])
            return _('%s (constant in %s)') % (name_cls[0], modname)
        else:
            return ''


class PhpClasslike(PhpObject):
    """
    Description of a class-like object
    (classes, exceptions, interfaces, traits).
    """

    def get_signature_prefix(self, sig):
        return self.objtype + ' '

    def get_index_text(self, modname, name_cls):
        if self.objtype == 'class':
            if not modname:
                return _('%s (class)') % name_cls[0]
            return _('%s (class in %s)') % (name_cls[0], modname)
        elif self.objtype == 'interface':
            if not modname:
                return _('%s (interface)') % name_cls[0]
            return _('%s (interface in %s)') % (name_cls[0], modname)
        elif self.objtype == 'trait':
            if not modname:
                return _('%s (trait)') % name_cls[0]
            return _('%s (trait in %s)') % (name_cls[0], modname)
        elif self.objtype == 'exception':
            return name_cls[0]
        else:
            return ''

    def after_content(self):
        self.env.temp_data['php:in_class'] = False

    def before_content(self):
        self.env.temp_data['php:in_class'] = True
        if self.names:
            self.env.temp_data['php:class'] = self.names[0][0]

class PhpClassmember(PhpObject):
    """
    Description of a class member (methods, attributes).
    """

    def get_signature_prefix(self, sig):
        if self.objtype == 'attr':
            return _('property ')
        if self.objtype == 'staticmethod':
            return _('static ')
        return ''

    def needs_arglist(self):
        return self.objtype == 'method'

    def get_index_text(self, modname, name_cls):
        name, cls = name_cls
        add_modules = self.env.config.add_module_names

        if self.objtype.endswith('method') or self.objtype == 'attr':
            try:
                clsname, propname = php_rsplit(name)
            except ValueError:
                propname = name
                clsname = None

        if self.objtype.endswith('method'):
            if modname and clsname is None:
                return _('%s() (in namespace %s)') % (name, modname)
            elif modname and add_modules:
                return _('%s() (%s\\%s method)') % (propname, modname, clsname)
            else:
                return _('%s() (%s method)') % (propname, clsname)
        elif self.objtype == 'attr':
            if modname and clsname is None:
                return _('%s (in namespace %s)') % (name, modname)
            elif modname and add_modules:
                return _('%s (%s\\%s property)') % (propname, modname, clsname)
            else:
                return _('%s (%s property)') % (propname, clsname)
        else:
            return ''

class PhpNamespace(Directive):
    """
    Directive to start a new PHP namespace, which are similar to modules.
    """
    has_content = False
    required_arguments = 1
    optional_arguments = 0
    final_argument_whitespace = False
    option_spec = {
        'synopsis': lambda x: x,
        'noindex': directives.flag,
        'deprecated': directives.flag,
    }

    def run(self):
        env = self.state.document.settings.env
        modname = self.arguments[0].strip()
        noindex = 'noindex' in self.options
        env.temp_data['php:namespace'] = modname
        env.temp_data['php:class'] = None
        env.domaindata['php']['namespaces'][modname] = (
            env.docname, self.options.get('synopsis', ''),
            'deprecated' in self.options)

        targetnode = nodes.target('', '', ids=['namespace-' + modname], ismod=True)
        self.state.document.note_explicit_target(targetnode)
        ret = [targetnode]

        # the synopsis isn't printed; in fact, it is only used in the
        # modindex currently
        if not noindex:
            indextext = _('%s (namespace)') % modname
            inode = addnodes.index(entries=[('single', indextext,
                                             'namespace-' + modname, modname)])
            ret.append(inode)
        return ret


class PhpXRefRole(XRefRole):
    """
    Provides cross reference links for PHP objects
    """
    def process_link(self, env, refnode, has_explicit_title, title, target):
        if not has_explicit_title:
            if title.startswith("::"):
                title = title[2:]
            target = target.lstrip('~') # only has a meaning for the title
            # if the first character is a tilde, don't display the module/class
            # parts of the contents
            if title[0:1] == '~':
                m = re.search(r"(?:\\|[:]{2})(.*)\Z", title)
                if m:
                    title = m.group(1)

        if not title.startswith("$"):
            refnode['php:namespace'] = env.temp_data.get('php:namespace')
            refnode['php:class'] = env.temp_data.get('php:class')

        return title, target

class PhpNamespaceIndex(Index):
    """
    Index subclass to provide the Php module index.
    """

    name = 'modindex'
    localname = l_('PHP Namespace Index')
    shortname = l_('namespaces')

    def generate(self, docnames=None):
        content = {}
        # list of prefixes to ignore
        ignores = self.domain.env.config['modindex_common_prefix']
        ignores = sorted(ignores, key=len, reverse=True)
        # list of all modules, sorted by module name
        modules = sorted(self.domain.data['namespaces'].iteritems(),
                         key=lambda x: x[0].lower())
        # sort out collapsable modules
        prev_modname = ''
        num_toplevels = 0
        for modname, (docname, synopsis, deprecated) in modules:
            if docnames and docname not in docnames:
                continue

            for ignore in ignores:
                if modname.startswith(ignore):
                    modname = modname[len(ignore):]
                    stripped = ignore
                    break
            else:
                stripped = ''

            # we stripped the whole module name?
            if not modname:
                modname, stripped = stripped, ''

            entries = content.setdefault(modname[0].lower(), [])

            package = modname.split(NS)[0]
            if package != modname:
                # it's a submodule
                if prev_modname == package:
                    # first submodule - make parent a group head
                    entries[-1][1] = 1
                elif not prev_modname.startswith(package):
                    # submodule without parent in list, add dummy entry
                    entries.append([stripped + package, 1, '', '', '', '', ''])
                subtype = 2
            else:
                num_toplevels += 1
                subtype = 0

            qualifier = deprecated and _('Deprecated') or ''
            entries.append([stripped + modname, subtype, docname,
                            'namespace-' + stripped + modname, '',
                            qualifier, synopsis])
            prev_modname = modname

        # apply heuristics when to collapse modindex at page load:
        # only collapse if number of toplevel modules is larger than
        # number of submodules
        collapse = len(modules) - num_toplevels < num_toplevels

        # sort by first letter
        content = sorted(content.iteritems())

        return content, collapse

class PhpDomain(Domain):
    """PHP language domain."""
    name = 'php'
    label = 'PHP'
    object_types = {
        'function': ObjType(l_('function'), 'func', 'obj'),
        'global': ObjType(l_('global variable'), 'global', 'obj'),
        'const': ObjType(l_('const'), 'const', 'obj'),
        'method': ObjType(l_('method'), 'meth', 'obj'),
        'class': ObjType(l_('class'), 'class', 'obj'),
        'attr': ObjType(l_('attribute'), 'attr', 'obj'),
        'exception': ObjType(l_('exception'), 'exc', 'obj'),
        'namespace': ObjType(l_('namespace'), 'ns', 'obj'),
        'interface': ObjType(l_('interface'), 'interface', 'obj'),
        'trait': ObjType(l_('trait'), 'trait', 'obj'),
    }

    directives = {
        'function': PhpNamespacelevel,
        'global': PhpGloballevel,
        'const': PhpNamespacelevel,
        'class': PhpClasslike,
        'method': PhpClassmember,
        'staticmethod': PhpClassmember,
        'attr': PhpClassmember,
        'exception': PhpClasslike,
        'interface': PhpClasslike,
        'trait': PhpClasslike,
        'namespace': PhpNamespace,
    }

    roles = {
        'func': PhpXRefRole(fix_parens=False),
        'global': PhpXRefRole(),
        'class': PhpXRefRole(),
        'exc': PhpXRefRole(),
        'meth': PhpXRefRole(fix_parens=False),
        'attr': PhpXRefRole(),
        'const': PhpXRefRole(),
        'ns': PhpXRefRole(),
        'obj': PhpXRefRole(),
        'interface': PhpXRefRole(),
        'trait': PhpXRefRole(),
    }

    initial_data = {
        'objects': {},  # fullname -> docname, objtype
        'namespaces': {},  # namespace -> docname, synopsis
    }
    indices = [
        PhpNamespaceIndex,
    ]

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

    def resolve_xref(self, env, fromdocname, builder,
                     typ, target, node, contnode):
        if (typ == 'ns' or
            typ == 'obj' and target in self.data['namespaces']):
            docname, synopsis, deprecated = \
                self.data['namespaces'].get(target, ('','','', ''))
            if not docname:
                return None
            else:
                title = '%s%s' % (synopsis,
                                    (deprecated and ' (deprecated)' or ''))
                return make_refnode(builder, fromdocname, docname,
                                    'namespace-' + target, contnode, title)
        else:
            modname = node.get('php:namespace')
            clsname = node.get('php:class')
            searchorder = node.hasattr('refspecific') and 1 or 0
            name, obj = self.find_obj(env, modname, clsname,
                                      target, typ, searchorder)
            if not obj:
                return None
            else:
                return make_refnode(builder, fromdocname, obj[0], name,
                                    contnode, name)

    def find_obj(self, env, modname, classname, name, type, searchorder=0):
        """
        Find a PHP object for "name", perhaps using the given namespace and/or
        classname.
        """
        # skip parens
        if name[-2:] == '()':
            name = name[:-2]

        if not name:
            return None, None

        objects = self.data['objects']

        newname = None
        if searchorder == 1:
            if modname and classname and \
                     modname + NS + classname + '::' + name in objects:
                newname = modname + NS + classname + '::' + name
            elif modname and modname + NS + name in objects:
                newname = modname + NS + name
            elif modname and modname + NS + name in objects:
                newname = modname + NS + name
            elif classname and classname + '::' + name in objects:
                newname = classname + '.' + name
            elif classname and classname + '::$' + name in objects:
                newname = classname + '::$' + name
            elif name in objects:
                newname = name
        else:
            if name in objects:
                newname = name
            elif classname and classname + '::' + name in objects:
                newname = classname + '::' + name
            elif classname and classname + '::$' + name in objects:
                newname = classname + '::$' + name
            elif modname and modname + NS + name in objects:
                newname = modname + NS + name
            elif modname and classname and \
                     modname + NS + classname + '::' + name in objects:
                newname = modname + NS + classname + '::' + name
            elif modname and classname and \
                     modname + NS + classname + '::$' + name in objects:
                newname = modname + NS + classname + '::$' + name
            # special case: object methods
            elif type in ('func', 'meth') and '::' not in name and \
                 'object::' + name in objects:
                newname = 'object::' + name
        if newname is None:
            return None, None
        return newname, objects[newname]

    def get_objects(self):
        for ns, info in self.data['namespaces'].iteritems():
            yield (ns, ns, 'namespace', info[0], 'namespace-' + ns, 0)
        for refname, (docname, type) in self.data['objects'].iteritems():
            yield (refname, refname, type, docname, refname, 1)


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