aboutsummaryrefslogtreecommitdiff
path: root/_ext/crowbar_domain.py
blob: 673f75682953fa6722fa7941d845f3b7211e14b7 (plain)
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
from collections import defaultdict
import re

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

from sphinx import addnodes
from sphinx.directives import ObjectDescription
from sphinx.domains import Domain
from sphinx.domains import Index
from sphinx.roles import XRefRole
from sphinx.util import logging
from sphinx.util.nodes import make_refnode

logger = logging.getLogger(__name__)

peg_token = re.compile(r"\s+|\+|\*|\?|\(|\)|'[^']+'|[\w\-]+")
def tokenize_peg(peg_def):
    for token in peg_token.finditer(peg_def):
        yield token[0]

class ElementDirective(ObjectDescription):
    has_content = True
    required_arguments = 1
    option_spec = {
        'contains': directives.unchanged_required,
    }

    def handle_signature(self, sig, signode):
        element, defs = sig.split(' <- ')
        peg_rule = nodes.literal()
        signode += peg_rule
        peg_rule += addnodes.desc_name(text=element)
        peg_rule += nodes.Text(' ')
        peg_rule += addnodes.desc_sig_operator(text='<-')
        defs = defs.split(' / ')
        for d in defs:
            if peg_rule.children[-1].astext() != '<-':
                peg_rule += [nodes.Text(' '), addnodes.desc_sig_operator(text='/')]
            peg_rule += nodes.Text(' ')
            for token in tokenize_peg(d):
                if re.fullmatch(r"[a-z][\w\-]+", token):
                    refattrs = dict(refdomain='std', refexplicit=False, reftarget=token.replace('-', ' '), reftype='term', refwarn=True)
                    reference = addnodes.pending_xref('', nodes.literal(text=token, classes=['xref', 'std', 'std-term']), **refattrs)
                    peg_rule += addnodes.desc_sig_name('', '', reference)
                elif re.fullmatch(r'[A-Z]\w+', token):
                    refattrs = dict(refdomain='crowbar', refexplicit=False, reftarget=token, reftype='ref', refwarn=True)
                    reference = addnodes.pending_xref('', nodes.literal(text=token, classes=['xref', 'crowbar', 'crowbar-ref']), **refattrs)
                    peg_rule += addnodes.desc_sig_name('', '', reference)
                elif len(token.strip()) == 0 or (token.startswith("'") and token.endswith("'")):
                    peg_rule += nodes.literal(text=token)
                else:
                    peg_rule += addnodes.desc_sig_operator('', '', nodes.literal(text=token))
        return element

    def add_target_and_index(self, name, sig, signode):
        signode['ids'].append('element' + '-' + name)
        if 'noindex' not in self.options:
            crowbar = self.env.get_domain('crowbar')
            crowbar.add_element(name)


class ElementIndex(Index):
    name = 'element'
    localname = 'Element Index'
    shortname = 'Element'

    def generate(self, docnames=None):
        content = defaultdict(list)

        # sort the list of elements in alphabetical order
        elements = self.domain.get_elements()
        elements = sorted(elements, key=lambda recipe: recipe[0])

        # generate the expected output, shown below, from the above using the
        # first letter of the recipe as a key to group thing
        #
        # name, subtype, docname, anchor, extra, qualifier, description
        for name, dispname, typ, docname, anchor, _ in elements:
            content[dispname[0].lower()].append(
                (dispname, 0, docname, anchor, docname, '', typ))

        # convert the dict to the sorted list of tuples expected
        content = sorted(content.items())

        return content, True


class CrowbarDomain(Domain):
    name = 'crowbar'
    label = 'Crowbar'
    roles = {
        'ref': XRefRole(warn_dangling=True),
    }
    directives = {
        'element': ElementDirective,
    }
    indices = {
        ElementIndex,
    }
    initial_data = {
        'elements': [],
    }

    def get_full_qualified_name(self, node):
        return '{}.{}'.format('element', node.arguments[0])

    def get_elements(self):
        for obj in self.data['elements']:
            yield(obj)

    def get_objects(self):
        yield from self.get_elements()

    def resolve_xref(self, env, fromdocname, builder, typ, target, node,
                     contnode):
        match = [(docname, anchor)
                 for name, sig, typ, docname, anchor, prio
                 in self.get_objects() if sig == target]

        if len(match) > 0:
            todocname = match[0][0]
            targ = match[0][1]

            return make_refnode(builder, fromdocname, todocname, targ,
                                contnode, targ)
        else:
            return None

    def add_keyword(self, signature):
        """Add a new keyword to the domain."""
        name = '{}.{}'.format('keyword', signature)
        anchor = 'keyword-{}'.format(signature)

        # name, dispname, type, docname, anchor, priority
        self.data['keywords'].append(
            (name, signature, 'Keyword', self.env.docname, anchor, 0))

    def add_element(self, signature):
        """Add a new element to the domain."""
        name = '{}.{}'.format('element', signature)
        anchor = 'element-{}'.format(signature)

        # name, dispname, type, docname, anchor, priority
        self.data['elements'].append(
            (name, signature, 'Element', self.env.docname, anchor, 0))


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

    return {
        'version': '0.1',
        'parallel_read_safe': True,
        'parallel_write_safe': True,
    }