doc.py 8.4 KB
Newer Older
M
Marc-André Lureau 已提交
1 2 3 4 5 6
#!/usr/bin/env python
# QAPI texi generator
#
# This work is licensed under the terms of the GNU LGPL, version 2+.
# See the COPYING file in the top-level directory.
"""This script produces the documentation of a qapi schema in texinfo format"""
7

8
from __future__ import print_function
M
Marc-André Lureau 已提交
9
import re
10
import qapi.common
M
Marc-André Lureau 已提交
11

12
MSG_FMT = """
M
Marc-André Lureau 已提交
13 14 15 16 17 18 19
@deftypefn {type} {{}} {name}

{body}
@end deftypefn

""".format

20
TYPE_FMT = """
M
Marc-André Lureau 已提交
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
@deftp {{{type}}} {name}

{body}
@end deftp

""".format

EXAMPLE_FMT = """@example
{code}
@end example
""".format


def subst_strong(doc):
    """Replaces *foo* by @strong{foo}"""
36
    return re.sub(r'\*([^*\n]+)\*', r'@strong{\1}', doc)
M
Marc-André Lureau 已提交
37 38 39 40


def subst_emph(doc):
    """Replaces _foo_ by @emph{foo}"""
41
    return re.sub(r'\b_([^_\n]+)_\b', r'@emph{\1}', doc)
M
Marc-André Lureau 已提交
42 43 44 45 46 47 48 49 50


def subst_vars(doc):
    """Replaces @var by @code{var}"""
    return re.sub(r'@([\w-]+)', r'@code{\1}', doc)


def subst_braces(doc):
    """Replaces {} with @{ @}"""
51
    return doc.replace('{', '@{').replace('}', '@}')
M
Marc-André Lureau 已提交
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74


def texi_example(doc):
    """Format @example"""
    # TODO: Neglects to escape @ characters.
    # We should probably escape them in subst_braces(), and rename the
    # function to subst_special() or subs_texi_special().  If we do that, we
    # need to delay it until after subst_vars() in texi_format().
    doc = subst_braces(doc).strip('\n')
    return EXAMPLE_FMT(code=doc)


def texi_format(doc):
    """
    Format documentation

    Lines starting with:
    - |: generates an @example
    - =: generates @section
    - ==: generates @subsection
    - 1. or 1): generates an @enumerate @item
    - */-: generates an @itemize list
    """
75
    ret = ''
M
Marc-André Lureau 已提交
76 77 78 79
    doc = subst_braces(doc)
    doc = subst_vars(doc)
    doc = subst_emph(doc)
    doc = subst_strong(doc)
80
    inlist = ''
M
Marc-André Lureau 已提交
81 82
    lastempty = False
    for line in doc.split('\n'):
83
        empty = line == ''
M
Marc-André Lureau 已提交
84 85 86 87 88 89 90 91

        # FIXME: Doing this in a single if / elif chain is
        # problematic.  For instance, a line without markup terminates
        # a list if it follows a blank line (reaches the final elif),
        # but a line with some *other* markup, such as a = title
        # doesn't.
        #
        # Make sure to update section "Documentation markup" in
92
        # docs/devel/qapi-code-gen.txt when fixing this.
93
        if line.startswith('| '):
M
Marc-André Lureau 已提交
94
            line = EXAMPLE_FMT(code=line[2:])
95 96 97 98
        elif line.startswith('= '):
            line = '@section ' + line[2:]
        elif line.startswith('== '):
            line = '@subsection ' + line[3:]
M
Marc-André Lureau 已提交
99 100
        elif re.match(r'^([0-9]*\.) ', line):
            if not inlist:
101
                ret += '@enumerate\n'
102
                inlist = 'enumerate'
103
            ret += '@item\n'
104
            line = line[line.find(' ')+1:]
M
Marc-André Lureau 已提交
105 106
        elif re.match(r'^[*-] ', line):
            if not inlist:
107 108
                ret += '@itemize %s\n' % {'*': '@bullet',
                                          '-': '@minus'}[line[0]]
109
                inlist = 'itemize'
110
            ret += '@item\n'
M
Marc-André Lureau 已提交
111 112
            line = line[2:]
        elif lastempty and inlist:
113
            ret += '@end %s\n\n' % inlist
114
            inlist = ''
M
Marc-André Lureau 已提交
115 116

        lastempty = empty
117
        ret += line + '\n'
M
Marc-André Lureau 已提交
118 119

    if inlist:
120 121
        ret += '@end %s\n\n' % inlist
    return ret
M
Marc-André Lureau 已提交
122 123


124 125
def texi_body(doc):
    """Format the main documentation body"""
126
    return texi_format(doc.body.text)
127 128 129 130


def texi_enum_value(value):
    """Format a table of members item for an enumeration value"""
131
    return '@item @code{%s}\n' % value.name
132 133


134
def texi_member(member, suffix=''):
135
    """Format a table of members item for an object type member"""
136
    typ = member.type.doc_type()
137 138 139
    membertype = ': ' + typ if typ else ''
    return '@item @code{%s%s}%s%s\n' % (
        member.name, membertype,
140 141
        ' (optional)' if member.optional else '',
        suffix)
142

M
Marc-André Lureau 已提交
143

144
def texi_members(doc, what, base, variants, member_func):
145 146
    """Format the table of members"""
    items = ''
147
    for section in doc.args.values():
148
        # TODO Drop fallbacks when undocumented members are outlawed
149 150
        if section.text:
            desc = texi_format(section.text)
151 152 153
        elif (variants and variants.tag_member == section.member
              and not section.member.type.doc_type()):
            values = section.member.type.member_names()
154 155
            members_text = ', '.join(['@t{"%s"}' % v for v in values])
            desc = 'One of ' + members_text + '\n'
156
        else:
157 158
            desc = 'Not documented\n'
        items += member_func(section.member) + desc
159 160
    if base:
        items += '@item The members of @code{%s}\n' % base.doc_type()
161 162 163 164 165 166 167 168 169 170 171
    if variants:
        for v in variants.variants:
            when = ' when @code{%s} is @t{"%s"}' % (
                variants.tag_member.name, v.name)
            if v.type.is_implicit():
                assert not v.type.base and not v.type.variants
                for m in v.type.local_members:
                    items += member_func(m, when)
            else:
                items += '@item The members of @code{%s}%s\n' % (
                    v.type.doc_type(), when)
172 173
    if not items:
        return ''
174
    return '\n@b{%s:}\n@table @asis\n%s@end table\n' % (what, items)
175 176 177 178 179


def texi_sections(doc):
    """Format additional sections following arguments"""
    body = ''
M
Marc-André Lureau 已提交
180
    for section in doc.sections:
181
        if section.name:
182
            # prefer @b over @strong, so txt doesn't translate it to *Foo:*
183
            body += '\n@b{%s:}\n' % section.name
184
        if section.name and section.name.startswith('Example'):
185
            body += texi_example(section.text)
186
        else:
187
            body += texi_format(section.text)
M
Marc-André Lureau 已提交
188 189 190
    return body


191 192
def texi_entity(doc, what, base=None, variants=None,
                member_func=texi_member):
193
    return (texi_body(doc)
194
            + texi_members(doc, what, base, variants, member_func)
195 196 197
            + texi_sections(doc))


198
class QAPISchemaGenDocVisitor(qapi.common.QAPISchemaVisitor):
199 200 201
    def __init__(self, prefix):
        self._prefix = prefix
        self._gen = qapi.common.QAPIGenDoc()
202 203
        self.cur_doc = None

204 205
    def write(self, output_dir):
        self._gen.write(output_dir, self._prefix + 'qapi-doc.texi')
206 207 208

    def visit_enum_type(self, name, info, values, prefix):
        doc = self.cur_doc
209 210 211 212
        self._gen.add(TYPE_FMT(type='Enum',
                               name=doc.symbol,
                               body=texi_entity(doc, 'Values',
                                                member_func=texi_enum_value)))
213 214 215

    def visit_object_type(self, name, info, base, members, variants):
        doc = self.cur_doc
216 217
        if base and base.is_implicit():
            base = None
218 219 220 221
        self._gen.add(TYPE_FMT(type='Object',
                               name=doc.symbol,
                               body=texi_entity(doc, 'Members',
                                                base, variants)))
222 223 224

    def visit_alternate_type(self, name, info, variants):
        doc = self.cur_doc
225 226 227
        self._gen.add(TYPE_FMT(type='Alternate',
                               name=doc.symbol,
                               body=texi_entity(doc, 'Members')))
228 229 230 231

    def visit_command(self, name, info, arg_type, ret_type,
                      gen, success_response, boxed):
        doc = self.cur_doc
232 233
        if boxed:
            body = texi_body(doc)
234 235
            body += ('\n@b{Arguments:} the members of @code{%s}\n'
                     % arg_type.name)
236 237 238
            body += texi_sections(doc)
        else:
            body = texi_entity(doc, 'Arguments')
239 240 241
        self._gen.add(MSG_FMT(type='Command',
                              name=doc.symbol,
                              body=body))
242 243 244

    def visit_event(self, name, info, arg_type, boxed):
        doc = self.cur_doc
245 246 247
        self._gen.add(MSG_FMT(type='Event',
                              name=doc.symbol,
                              body=texi_entity(doc, 'Arguments')))
248 249

    def symbol(self, doc, entity):
250 251
        if self._gen._body:
            self._gen.add('\n')
252 253 254 255 256 257
        self.cur_doc = doc
        entity.visit(self)
        self.cur_doc = None

    def freeform(self, doc):
        assert not doc.args
258 259 260
        if self._gen._body:
            self._gen.add('\n')
        self._gen.add(texi_body(doc) + texi_sections(doc))
261 262


263 264 265 266 267
def gen_doc(schema, output_dir, prefix):
    if not qapi.common.doc_required:
        return
    vis = QAPISchemaGenDocVisitor(prefix)
    vis.visit_begin(schema)
268 269
    for doc in schema.docs:
        if doc.symbol:
270
            vis.symbol(doc, schema.lookup_entity(doc.symbol))
271
        else:
272 273
            vis.freeform(doc)
    vis.write(output_dir)