qapi2texi.py 8.6 KB
Newer Older
M
Marc-André Lureau 已提交
1 2 3 4 5 6 7 8 9 10 11
#!/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"""
import re
import sys

import qapi

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

{body}

@end deftypefn

""".format

21
TYPE_FMT = """
M
Marc-André Lureau 已提交
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
@deftp {{{type}}} {name}

{body}

@end deftp

""".format

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


def subst_strong(doc):
    """Replaces *foo* by @strong{foo}"""
    return re.sub(r'\*([^*\n]+)\*', r'@emph{\1}', doc)


def subst_emph(doc):
    """Replaces _foo_ by @emph{foo}"""
    return re.sub(r'\b_([^_\n]+)_\b', r' @emph{\1} ', doc)


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


def subst_braces(doc):
    """Replaces {} with @{ @}"""
53
    return doc.replace('{', '@{').replace('}', '@}')
M
Marc-André Lureau 已提交
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


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
    """
    lines = []
    doc = subst_braces(doc)
    doc = subst_vars(doc)
    doc = subst_emph(doc)
    doc = subst_strong(doc)
82
    inlist = ''
M
Marc-André Lureau 已提交
83 84
    lastempty = False
    for line in doc.split('\n'):
85
        empty = line == ''
M
Marc-André Lureau 已提交
86 87 88 89 90 91 92 93 94

        # 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
        # docs/qapi-code-gen.txt when fixing this.
95
        if line.startswith('| '):
M
Marc-André Lureau 已提交
96
            line = EXAMPLE_FMT(code=line[2:])
97 98 99 100
        elif line.startswith('= '):
            line = '@section ' + line[2:]
        elif line.startswith('== '):
            line = '@subsection ' + line[3:]
M
Marc-André Lureau 已提交
101 102
        elif re.match(r'^([0-9]*\.) ', line):
            if not inlist:
103 104 105 106
                lines.append('@enumerate')
                inlist = 'enumerate'
            line = line[line.find(' ')+1:]
            lines.append('@item')
M
Marc-André Lureau 已提交
107 108
        elif re.match(r'^[*-] ', line):
            if not inlist:
109 110 111 112
                lines.append('@itemize %s' % {'*': '@bullet',
                                              '-': '@minus'}[line[0]])
                inlist = 'itemize'
            lines.append('@item')
M
Marc-André Lureau 已提交
113 114
            line = line[2:]
        elif lastempty and inlist:
115 116
            lines.append('@end %s\n' % inlist)
            inlist = ''
M
Marc-André Lureau 已提交
117 118 119 120 121

        lastempty = empty
        lines.append(line)

    if inlist:
122 123
        lines.append('@end %s\n' % inlist)
    return '\n'.join(lines)
M
Marc-André Lureau 已提交
124 125


126 127 128 129 130 131 132
def texi_body(doc):
    """Format the main documentation body"""
    return texi_format(str(doc.body)) + '\n'


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


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

M
Marc-André Lureau 已提交
146

147
def texi_members(doc, what, base, variants, member_func):
148 149 150
    """Format the table of members"""
    items = ''
    for section in doc.args.itervalues():
151 152 153 154
        if section.content:
            desc = str(section)
        else:
            desc = 'Not documented'
155
        items += member_func(section.member) + texi_format(desc) + '\n'
156 157
    if base:
        items += '@item The members of @code{%s}\n' % base.doc_type()
158 159 160 161 162 163 164 165 166 167 168
    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)
169 170
    if not items:
        return ''
171
    return '\n@b{%s:}\n@table @asis\n%s@end table\n' % (what, items)
172 173 174 175 176


def texi_sections(doc):
    """Format additional sections following arguments"""
    body = ''
M
Marc-André Lureau 已提交
177 178 179
    for section in doc.sections:
        name, doc = (section.name, str(section))
        func = texi_format
180
        if name.startswith('Example'):
M
Marc-André Lureau 已提交
181 182 183
            func = texi_example

        if name:
184
            # prefer @b over @strong, so txt doesn't translate it to *Foo:*
185
            body += '\n\n@b{%s:}\n' % name
186 187

        body += func(doc)
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 198 199 200 201 202 203 204 205 206 207 208 209 210 211
            + texi_sections(doc))


class QAPISchemaGenDocVisitor(qapi.QAPISchemaVisitor):
    def __init__(self):
        self.out = None
        self.cur_doc = None

    def visit_begin(self, schema):
        self.out = ''

    def visit_enum_type(self, name, info, values, prefix):
        doc = self.cur_doc
        if self.out:
            self.out += '\n'
        self.out += TYPE_FMT(type='Enum',
                             name=doc.symbol,
212
                             body=texi_entity(doc, 'Values',
213
                                              member_func=texi_enum_value))
214 215 216 217 218 219 220 221 222

    def visit_object_type(self, name, info, base, members, variants):
        doc = self.cur_doc
        if not variants:
            typ = 'Struct'
        elif variants._tag_name:        # TODO unclean member access
            typ = 'Flat Union'
        else:
            typ = 'Simple Union'
223 224
        if base and base.is_implicit():
            base = None
225 226 227 228
        if self.out:
            self.out += '\n'
        self.out += TYPE_FMT(type=typ,
                             name=doc.symbol,
229
                             body=texi_entity(doc, 'Members', base, variants))
230 231 232 233 234 235 236

    def visit_alternate_type(self, name, info, variants):
        doc = self.cur_doc
        if self.out:
            self.out += '\n'
        self.out += TYPE_FMT(type='Alternate',
                             name=doc.symbol,
237
                             body=texi_entity(doc, 'Members'))
238 239 240 241 242 243

    def visit_command(self, name, info, arg_type, ret_type,
                      gen, success_response, boxed):
        doc = self.cur_doc
        if self.out:
            self.out += '\n'
244 245 246 247 248 249
        if boxed:
            body = texi_body(doc)
            body += '\n@b{Arguments:} the members of @code{%s}' % arg_type.name
            body += texi_sections(doc)
        else:
            body = texi_entity(doc, 'Arguments')
250 251
        self.out += MSG_FMT(type='Command',
                            name=doc.symbol,
252
                            body=body)
253 254 255 256 257 258 259

    def visit_event(self, name, info, arg_type, boxed):
        doc = self.cur_doc
        if self.out:
            self.out += '\n'
        self.out += MSG_FMT(type='Event',
                            name=doc.symbol,
260
                            body=texi_entity(doc, 'Arguments'))
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283

    def symbol(self, doc, entity):
        self.cur_doc = doc
        entity.visit(self)
        self.cur_doc = None

    def freeform(self, doc):
        assert not doc.args
        if self.out:
            self.out += '\n'
        self.out += texi_body(doc) + texi_sections(doc)


def texi_schema(schema):
    """Convert QAPI schema documentation to Texinfo"""
    gen = QAPISchemaGenDocVisitor()
    gen.visit_begin(schema)
    for doc in schema.docs:
        if doc.symbol:
            gen.symbol(doc, schema.lookup_entity(doc.symbol))
        else:
            gen.freeform(doc)
    return gen.out
M
Marc-André Lureau 已提交
284 285 286 287 288 289 290 291 292


def main(argv):
    """Takes schema argument, prints result to stdout"""
    if len(argv) != 2:
        print >>sys.stderr, "%s: need exactly 1 argument: SCHEMA" % argv[0]
        sys.exit(1)

    schema = qapi.QAPISchema(argv[1])
293 294 295
    if not qapi.doc_required:
        print >>sys.stderr, ("%s: need pragma 'doc-required' "
                             "to generate documentation" % argv[0])
296
    print texi_schema(schema)
M
Marc-André Lureau 已提交
297 298


299
if __name__ == '__main__':
M
Marc-André Lureau 已提交
300
    main(sys.argv)