apibuild.py 100.3 KB
Newer Older
1
#!/usr/bin/env python2
2 3 4 5 6 7 8 9
#
# This is the API builder, it parses the C sources and build the
# API formal description in XML.
#
# See Copyright for the status of this software.
#
# daniel@veillard.com
#
10 11 12

from __future__ import print_function

13 14 15
import os, sys
import string
import glob
16
import re
17

18 19 20
quiet=True
warnings=0
debug=False
21 22 23 24 25
debugsym=None

#
# C parser analysis code
#
26
included_files = {
27
  "libvirt-common.h": "header with general libvirt API definitions",
28
  "libvirt-domain.h": "header with general libvirt API definitions",
29
  "libvirt-domain-snapshot.h": "header with general libvirt API definitions",
30
  "libvirt-event.h": "header with general libvirt API definitions",
31
  "libvirt-host.h": "header with general libvirt API definitions",
32
  "libvirt-interface.h": "header with general libvirt API definitions",
33
  "libvirt-network.h": "header with general libvirt API definitions",
34
  "libvirt-nodedev.h": "header with general libvirt API definitions",
35
  "libvirt-nwfilter.h": "header with general libvirt API definitions",
36
  "libvirt-secret.h": "header with general libvirt API definitions",
37
  "libvirt-storage.h": "header with general libvirt API definitions",
38
  "libvirt-stream.h": "header with general libvirt API definitions",
39 40
  "virterror.h": "header with error specific API definitions",
  "libvirt.c": "Main interfaces for the libvirt library",
41
  "libvirt-domain.c": "Domain interfaces for the libvirt library",
42
  "libvirt-domain-snapshot.c": "Domain snapshot interfaces for the libvirt library",
43
  "libvirt-host.c": "Host interfaces for the libvirt library",
44
  "libvirt-interface.c": "Interface interfaces for the libvirt library",
45
  "libvirt-network.c": "Network interfaces for the libvirt library",
46
  "libvirt-nodedev.c": "Node device interfaces for the libvirt library",
47
  "libvirt-nwfilter.c": "NWFilter interfaces for the libvirt library",
48
  "libvirt-secret.c": "Secret interfaces for the libvirt library",
49
  "libvirt-storage.c": "Storage interfaces for the libvirt library",
50
  "libvirt-stream.c": "Stream interfaces for the libvirt library",
51
  "virerror.c": "implements error handling and reporting code for libvirt",
52
  "virevent.c": "event loop for monitoring file handles",
53
  "virtypedparam.c": "virTypedParameters APIs",
54 55
}

56 57 58 59 60
qemu_included_files = {
  "libvirt-qemu.h": "header with QEMU specific API definitions",
  "libvirt-qemu.c": "Implementations for the QEMU specific APIs",
}

61 62 63 64 65
lxc_included_files = {
  "libvirt-lxc.h": "header with LXC specific API definitions",
  "libvirt-lxc.c": "Implementations for the LXC specific APIs",
}

66 67 68 69 70
admin_included_files = {
  "libvirt-admin.h": "header with admin specific API definitions",
  "libvirt-admin.c": "Implementations for the admin specific APIs",
}

71 72
ignored_words = {
  "ATTRIBUTE_UNUSED": (0, "macro keyword"),
73
  "ATTRIBUTE_SENTINEL": (0, "macro keyword"),
74
  "VIR_DEPRECATED": (0, "macro keyword"),
75
  "VIR_EXPORT_VAR": (0, "macro keyword"),
76 77 78
  "WINAPI": (0, "Windows keyword"),
  "__declspec": (3, "Windows keyword"),
  "__stdcall": (0, "Windows keyword"),
79 80
}

D
Daniel Veillard 已提交
81
ignored_functions = {
82
  "virConnectSupportsFeature": "private function for remote access",
D
Daniel Veillard 已提交
83 84 85 86 87
  "virDomainMigrateFinish": "private function for migration",
  "virDomainMigrateFinish2": "private function for migration",
  "virDomainMigratePerform": "private function for migration",
  "virDomainMigratePrepare": "private function for migration",
  "virDomainMigratePrepare2": "private function for migration",
C
Chris Lalancette 已提交
88
  "virDomainMigratePrepareTunnel": "private function for tunnelled migration",
89 90 91 92 93 94
  "virDomainMigrateBegin3": "private function for migration",
  "virDomainMigrateFinish3": "private function for migration",
  "virDomainMigratePerform3": "private function for migration",
  "virDomainMigratePrepare3": "private function for migration",
  "virDomainMigrateConfirm3": "private function for migration",
  "virDomainMigratePrepareTunnel3": "private function for tunnelled migration",
95
  "DllMain": "specific function for Win32",
96
  "virTypedParamsValidate": "internal function in virtypedparam.c",
97
  "virTypedParameterValidateSet": "internal function in virtypedparam.c",
98 99
  "virTypedParameterAssign": "internal function in virtypedparam.c",
  "virTypedParameterAssignFromStr": "internal function in virtypedparam.c",
100
  "virTypedParameterToString": "internal function in virtypedparam.c",
101
  "virTypedParamsCheck": "internal function in virtypedparam.c",
102
  "virTypedParamsCopy": "internal function in virtypedparam.c",
103 104 105 106 107 108
  "virDomainMigrateBegin3Params": "private function for migration",
  "virDomainMigrateFinish3Params": "private function for migration",
  "virDomainMigratePerform3Params": "private function for migration",
  "virDomainMigratePrepare3Params": "private function for migration",
  "virDomainMigrateConfirm3Params": "private function for migration",
  "virDomainMigratePrepareTunnel3Params": "private function for tunnelled migration",
J
Jiri Denemark 已提交
109
  "virErrorCopyNew": "private",
D
Daniel Veillard 已提交
110 111
}

112 113 114 115 116 117
ignored_macros = {
  "_virSchedParameter": "backward compatibility macro for virTypedParameter",
  "_virBlkioParameter": "backward compatibility macro for virTypedParameter",
  "_virMemoryParameter": "backward compatibility macro for virTypedParameter",
}

118 119
# macros that should be completely skipped
hidden_macros = {
120 121
  "VIR_DEPRECATED": "internal macro to mark deprecated apis",
  "VIR_EXPORT_VAR": "internal macro to mark exported vars",
122 123
}

124
def escape(raw):
125 126 127 128 129
    raw = raw.replace('&', '&')
    raw = raw.replace('<', '&lt;')
    raw = raw.replace('>', '&gt;')
    raw = raw.replace("'", '&apos;')
    raw = raw.replace('"', '&quot;')
130 131 132 133 134 135
    return raw

def uniq(items):
    d = {}
    for item in items:
        d[item]=1
136
    k = sorted(d.keys())
137
    return k
138 139 140 141 142

class identifier:
    def __init__(self, name, header=None, module=None, type=None, lineno = 0,
                 info=None, extra=None, conditionals = None):
        self.name = name
143 144 145 146 147 148 149
        self.header = header
        self.module = module
        self.type = type
        self.info = info
        self.extra = extra
        self.lineno = lineno
        self.static = 0
150
        if conditionals is None or len(conditionals) == 0:
151 152 153
            self.conditionals = None
        else:
            self.conditionals = conditionals[:]
154
        if self.name == debugsym and not quiet:
155 156
            print("=> define %s : %s" % (debugsym, (module, type, info,
                                         extra, conditionals)))
157 158 159

    def __repr__(self):
        r = "%s %s:" % (self.type, self.name)
160 161
        if self.static:
            r = r + " static"
162
        if self.module is not None:
163
            r = r + " from %s" % (self.module)
164
        if self.info is not None:
165
            r = r + " " + repr(self.info)
166
        if self.extra is not None:
167
            r = r + " " + repr(self.extra)
168
        if self.conditionals is not None:
169
            r = r + " " + repr(self.conditionals)
170
        return r
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187


    def set_header(self, header):
        self.header = header
    def set_module(self, module):
        self.module = module
    def set_type(self, type):
        self.type = type
    def set_info(self, info):
        self.info = info
    def set_extra(self, extra):
        self.extra = extra
    def set_lineno(self, lineno):
        self.lineno = lineno
    def set_static(self, static):
        self.static = static
    def set_conditionals(self, conditionals):
188
        if conditionals is None or len(conditionals) == 0:
189 190 191
            self.conditionals = None
        else:
            self.conditionals = conditionals[:]
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213

    def get_name(self):
        return self.name
    def get_header(self):
        return self.module
    def get_module(self):
        return self.module
    def get_type(self):
        return self.type
    def get_info(self):
        return self.info
    def get_lineno(self):
        return self.lineno
    def get_extra(self):
        return self.extra
    def get_static(self):
        return self.static
    def get_conditionals(self):
        return self.conditionals

    def update(self, header, module, type = None, info = None, extra=None,
               conditionals=None):
214
        if self.name == debugsym and not quiet:
215 216
            print("=> update %s : %s" % (debugsym, (module, type, info,
                                         extra, conditionals)))
217
        if header is not None and self.header is None:
218
            self.set_header(module)
219
        if module is not None and (self.module is None or self.header == self.module):
220
            self.set_module(module)
221
        if type is not None and self.type is None:
222
            self.set_type(type)
223
        if info is not None:
224
            self.set_info(info)
225
        if extra is not None:
226
            self.set_extra(extra)
227
        if conditionals is not None:
228
            self.set_conditionals(conditionals)
229 230 231 232 233 234

class index:
    def __init__(self, name = "noname"):
        self.name = name
        self.identifiers = {}
        self.functions = {}
235 236 237
        self.variables = {}
        self.includes = {}
        self.structs = {}
238
        self.unions = {}
239 240 241 242 243
        self.enums = {}
        self.typedefs = {}
        self.macros = {}
        self.references = {}
        self.info = {}
244

245 246 247
    def warning(self, msg):
        global warnings
        warnings = warnings + 1
248
        print(msg)
249

250 251
    def add_ref(self, name, header, module, static, type, lineno, info=None, extra=None, conditionals = None):
        if name[0:2] == '__':
252
            return None
253 254
        d = None
        try:
255 256 257 258 259
           d = self.identifiers[name]
           d.update(header, module, type, lineno, info, extra, conditionals)
        except:
           d = identifier(name, header, module, type, lineno, info, extra, conditionals)
           self.identifiers[name] = d
260

261
        if d is not None and static == 1:
262
            d.set_static(1)
263

264
        if d is not None and name is not None and type is not None:
265
            self.references[name] = d
266

267
        if name == debugsym and not quiet:
268
            print("New ref: %s" % (d))
269

270
        return d
271 272 273

    def add(self, name, header, module, static, type, lineno, info=None, extra=None, conditionals = None):
        if name[0:2] == '__':
274
            return None
275 276
        d = None
        try:
277 278 279 280 281 282
           d = self.identifiers[name]
           d.update(header, module, type, lineno, info, extra, conditionals)
        except:
           d = identifier(name, header, module, type, lineno, info, extra, conditionals)
           self.identifiers[name] = d

283
        if d is not None and static == 1:
284 285
            d.set_static(1)

286
        if d is not None and name is not None and type is not None:
287 288 289 290 291 292 293 294 295 296
            if type == "function":
                self.functions[name] = d
            elif type == "functype":
                self.functions[name] = d
            elif type == "variable":
                self.variables[name] = d
            elif type == "include":
                self.includes[name] = d
            elif type == "struct":
                self.structs[name] = d
297 298
            elif type == "union":
                self.unions[name] = d
299 300 301 302 303 304 305
            elif type == "enum":
                self.enums[name] = d
            elif type == "typedef":
                self.typedefs[name] = d
            elif type == "macro":
                self.macros[name] = d
            else:
306
                self.warning("Unable to register type ", type)
307

308
        if name == debugsym and not quiet:
309
            print("New symbol: %s" % (d))
310 311

        return d
312 313 314 315 316 317 318

    def merge(self, idx):
        for id in idx.functions.keys():
              #
              # macro might be used to override functions or variables
              # definitions
              #
A
Andrea Bolognani 已提交
319
             if id in self.macros:
320
                 del self.macros[id]
A
Andrea Bolognani 已提交
321
             if id in self.functions:
322 323
                 self.warning("function %s from %s redeclared in %s" % (
                    id, self.functions[id].header, idx.functions[id].header))
324 325 326
             else:
                 self.functions[id] = idx.functions[id]
                 self.identifiers[id] = idx.functions[id]
327 328 329 330 331
        for id in idx.variables.keys():
              #
              # macro might be used to override functions or variables
              # definitions
              #
A
Andrea Bolognani 已提交
332
             if id in self.macros:
333
                 del self.macros[id]
A
Andrea Bolognani 已提交
334
             if id in self.variables:
335 336
                 self.warning("variable %s from %s redeclared in %s" % (
                    id, self.variables[id].header, idx.variables[id].header))
337 338 339
             else:
                 self.variables[id] = idx.variables[id]
                 self.identifiers[id] = idx.variables[id]
340
        for id in idx.structs.keys():
A
Andrea Bolognani 已提交
341
             if id in self.structs:
342 343
                 self.warning("struct %s from %s redeclared in %s" % (
                    id, self.structs[id].header, idx.structs[id].header))
344 345 346
             else:
                 self.structs[id] = idx.structs[id]
                 self.identifiers[id] = idx.structs[id]
347
        for id in idx.unions.keys():
A
Andrea Bolognani 已提交
348
             if id in self.unions:
349 350
                 print("union %s from %s redeclared in %s" % (
                    id, self.unions[id].header, idx.unions[id].header))
351 352 353
             else:
                 self.unions[id] = idx.unions[id]
                 self.identifiers[id] = idx.unions[id]
354
        for id in idx.typedefs.keys():
A
Andrea Bolognani 已提交
355
             if id in self.typedefs:
356 357
                 self.warning("typedef %s from %s redeclared in %s" % (
                    id, self.typedefs[id].header, idx.typedefs[id].header))
358 359 360
             else:
                 self.typedefs[id] = idx.typedefs[id]
                 self.identifiers[id] = idx.typedefs[id]
361 362 363 364 365
        for id in idx.macros.keys():
              #
              # macro might be used to override functions or variables
              # definitions
              #
A
Andrea Bolognani 已提交
366
             if id in self.variables:
367
                 continue
A
Andrea Bolognani 已提交
368
             if id in self.functions:
369
                 continue
A
Andrea Bolognani 已提交
370
             if id in self.enums:
371
                 continue
A
Andrea Bolognani 已提交
372
             if id in self.macros:
373 374
                 self.warning("macro %s from %s redeclared in %s" % (
                    id, self.macros[id].header, idx.macros[id].header))
375 376 377
             else:
                 self.macros[id] = idx.macros[id]
                 self.identifiers[id] = idx.macros[id]
378
        for id in idx.enums.keys():
A
Andrea Bolognani 已提交
379
             if id in self.enums:
380 381
                 self.warning("enum %s from %s redeclared in %s" % (
                    id, self.enums[id].header, idx.enums[id].header))
382 383 384
             else:
                 self.enums[id] = idx.enums[id]
                 self.identifiers[id] = idx.enums[id]
385 386 387

    def merge_public(self, idx):
        for id in idx.functions.keys():
A
Andrea Bolognani 已提交
388
             if id in self.functions:
389 390 391
                 # check that function condition agrees with header
                 if idx.functions[id].conditionals != \
                    self.functions[id].conditionals:
392 393 394 395
                     self.warning("Header condition differs from Function for %s:" \
                                      % id)
                     self.warning("  H: %s" % self.functions[id].conditionals)
                     self.warning("  C: %s" % idx.functions[id].conditionals)
396 397 398
                 up = idx.functions[id]
                 self.functions[id].update(None, up.module, up.type, up.info, up.extra)
         #     else:
399 400
         #         print("Function %s from %s is not declared in headers" % (
         #               id, idx.functions[id].module))
401
         # TODO: do the same for variables.
402 403 404

    def analyze_dict(self, type, dict):
        count = 0
405
        public = 0
406
        for name in dict.keys():
407 408 409 410
            id = dict[name]
            count = count + 1
            if id.static == 0:
                public = public + 1
411
        if count != public:
412
            print("  %d %s , %d public" % (count, type, public))
413
        elif count != 0:
414
            print("  %d public %s" % (count, type))
415 416 417


    def analyze(self):
418 419 420 421 422 423 424
        if not quiet:
            self.analyze_dict("functions", self.functions)
            self.analyze_dict("variables", self.variables)
            self.analyze_dict("structs", self.structs)
            self.analyze_dict("unions", self.unions)
            self.analyze_dict("typedefs", self.typedefs)
            self.analyze_dict("macros", self.macros)
425

426 427 428 429 430
class CLexer:
    """A lexer for the C language, tokenize the input by reading and
       analyzing it line by line"""
    def __init__(self, input):
        self.input = input
431 432 433
        self.tokens = []
        self.line = ""
        self.lineno = 0
434 435 436

    def getline(self):
        line = ''
437 438 439 440 441
        while line == '':
            line = self.input.readline()
            if not line:
                return None
            self.lineno = self.lineno + 1
442 443
            line = line.lstrip()
            line = line.rstrip()
444 445 446 447 448 449
            if line == '':
                continue
            while line[-1] == '\\':
                line = line[:-1]
                n = self.input.readline()
                self.lineno = self.lineno + 1
450 451
                n = n.lstrip()
                n = n.rstrip()
452 453 454 455
                if not n:
                    break
                else:
                    line = line + n
456
        return line
457

458 459 460 461
    def getlineno(self):
        return self.lineno

    def push(self, token):
462
        self.tokens.insert(0, token)
463 464

    def debug(self):
465 466 467
        print("Last token: ", self.last)
        print("Token queue: ", self.tokens)
        print("Line %d end: " % (self.lineno), self.line)
468 469 470

    def token(self):
        while self.tokens == []:
471 472 473 474 475
            if self.line == "":
                line = self.getline()
            else:
                line = self.line
                self.line = ""
476
            if line is None:
477 478 479
                return None

            if line[0] == '#':
480
                self.tokens = list(map((lambda x: ('preproc', x)),
J
John Ferlan 已提交
481
                                       line.split()))
482 483 484 485 486 487 488 489

                # We might have whitespace between the '#' and preproc
                # macro name, so instead of having a single token element
                # of '#define' we might end up with '#' and 'define'. This
                # merges them back together
                if self.tokens[0][1] == "#":
                    self.tokens[0] = ('preproc', self.tokens[0][1] + self.tokens[1][1])
                    self.tokens = self.tokens[:1] + self.tokens[2:]
490
                break
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
            l = len(line)
            if line[0] == '"' or line[0] == "'":
                end = line[0]
                line = line[1:]
                found = 0
                tok = ""
                while found == 0:
                    i = 0
                    l = len(line)
                    while i < l:
                        if line[i] == end:
                            self.line = line[i+1:]
                            line = line[:i]
                            l = i
                            found = 1
                            break
                        if line[i] == '\\':
                            i = i + 1
                        i = i + 1
                    tok = tok + line
                    if found == 0:
                        line = self.getline()
513
                        if line is None:
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
                            return None
                self.last = ('string', tok)
                return self.last

            if l >= 2 and line[0] == '/' and line[1] == '*':
                line = line[2:]
                found = 0
                tok = ""
                while found == 0:
                    i = 0
                    l = len(line)
                    while i < l:
                        if line[i] == '*' and i+1 < l and line[i+1] == '/':
                            self.line = line[i+2:]
                            line = line[:i-1]
                            l = i
                            found = 1
                            break
                        i = i + 1
                    if tok != "":
                        tok = tok + "\n"
                    tok = tok + line
                    if found == 0:
                        line = self.getline()
538
                        if line is None:
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
                            return None
                self.last = ('comment', tok)
                return self.last
            if l >= 2 and line[0] == '/' and line[1] == '/':
                line = line[2:]
                self.last = ('comment', line)
                return self.last
            i = 0
            while i < l:
                if line[i] == '/' and i+1 < l and line[i+1] == '/':
                    self.line = line[i:]
                    line = line[:i]
                    break
                if line[i] == '/' and i+1 < l and line[i+1] == '*':
                    self.line = line[i:]
                    line = line[:i]
                    break
                if line[i] == '"' or line[i] == "'":
                    self.line = line[i:]
                    line = line[:i]
                    break
                i = i + 1
            l = len(line)
            i = 0
            while i < l:
                if line[i] == ' ' or line[i] == '\t':
                    i = i + 1
                    continue
                o = ord(line[i])
                if (o >= 97 and o <= 122) or (o >= 65 and o <= 90) or \
                   (o >= 48 and o <= 57):
                    s = i
                    while i < l:
                        o = ord(line[i])
                        if (o >= 97 and o <= 122) or (o >= 65 and o <= 90) or \
574 575
                           (o >= 48 and o <= 57) or \
                           (" \t(){}:;,+-*/%&!|[]=><".find(line[i]) == -1):
576 577 578 579 580
                            i = i + 1
                        else:
                            break
                    self.tokens.append(('name', line[s:i]))
                    continue
581
                if "(){}:;,[]".find(line[i]) != -1:
582
#                 if line[i] == '(' or line[i] == ')' or line[i] == '{' or \
583 584 585 586 587
#                   line[i] == '}' or line[i] == ':' or line[i] == ';' or \
#                   line[i] == ',' or line[i] == '[' or line[i] == ']':
                    self.tokens.append(('sep', line[i]))
                    i = i + 1
                    continue
588
                if "+-*><=/%&!|.".find(line[i]) != -1:
589
#                 if line[i] == '+' or line[i] == '-' or line[i] == '*' or \
590 591 592 593 594 595 596 597 598 599 600
#                   line[i] == '>' or line[i] == '<' or line[i] == '=' or \
#                   line[i] == '/' or line[i] == '%' or line[i] == '&' or \
#                   line[i] == '!' or line[i] == '|' or line[i] == '.':
                    if line[i] == '.' and  i + 2 < l and \
                       line[i+1] == '.' and line[i+2] == '.':
                        self.tokens.append(('name', '...'))
                        i = i + 3
                        continue

                    j = i + 1
                    if j < l and (
601
                       "+-*><=/%&!|".find(line[j]) != -1):
602 603 604 605 606 607 608 609 610 611 612 613 614 615
#                       line[j] == '+' or line[j] == '-' or line[j] == '*' or \
#                       line[j] == '>' or line[j] == '<' or line[j] == '=' or \
#                       line[j] == '/' or line[j] == '%' or line[j] == '&' or \
#                       line[j] == '!' or line[j] == '|'):
                        self.tokens.append(('op', line[i:j+1]))
                        i = j + 1
                    else:
                        self.tokens.append(('op', line[i]))
                        i = i + 1
                    continue
                s = i
                while i < l:
                    o = ord(line[i])
                    if (o >= 97 and o <= 122) or (o >= 65 and o <= 90) or \
616 617
                       (o >= 48 and o <= 57) or \
                       (" \t(){}:;,+-*/%&!|[]=><".find(line[i]) == -1):
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
#                        line[i] != ' ' and line[i] != '\t' and
#                        line[i] != '(' and line[i] != ')' and
#                        line[i] != '{'  and line[i] != '}' and
#                        line[i] != ':' and line[i] != ';' and
#                        line[i] != ',' and line[i] != '+' and
#                        line[i] != '-' and line[i] != '*' and
#                        line[i] != '/' and line[i] != '%' and
#                        line[i] != '&' and line[i] != '!' and
#                        line[i] != '|' and line[i] != '[' and
#                        line[i] != ']' and line[i] != '=' and
#                        line[i] != '*' and line[i] != '>' and
#                        line[i] != '<'):
                        i = i + 1
                    else:
                        break
                self.tokens.append(('name', line[s:i]))

        tok = self.tokens[0]
        self.tokens = self.tokens[1:]
        self.last = tok
        return tok
639

640 641 642 643
class CParser:
    """The C module parser"""
    def __init__(self, filename, idx = None):
        self.filename = filename
644 645 646 647
        if len(filename) > 2 and filename[-2:] == '.h':
            self.is_header = 1
        else:
            self.is_header = 0
648
        self.input = open(filename)
649
        self.lexer = CLexer(self.input)
650
        if idx is None:
651 652 653 654 655 656 657 658 659 660
            self.index = index()
        else:
            self.index = idx
        self.top_comment = ""
        self.last_comment = ""
        self.comment = None
        self.collect_ref = 0
        self.no_error = 0
        self.conditionals = []
        self.defines = []
661 662 663 664 665 666 667 668 669 670 671 672 673 674

    def collect_references(self):
        self.collect_ref = 1

    def stop_error(self):
        self.no_error = 1

    def start_error(self):
        self.no_error = 0

    def lineno(self):
        return self.lexer.getlineno()

    def index_add(self, name, module, static, type, info=None, extra = None):
675 676 677 678 679 680
        if self.is_header == 1:
            self.index.add(name, module, module, static, type, self.lineno(),
                           info, extra, self.conditionals)
        else:
            self.index.add(name, None, module, static, type, self.lineno(),
                           info, extra, self.conditionals)
681 682 683

    def index_add_ref(self, name, module, static, type, info=None,
                      extra = None):
684 685 686 687 688 689
        if self.is_header == 1:
            self.index.add_ref(name, module, module, static, type,
                               self.lineno(), info, extra, self.conditionals)
        else:
            self.index.add_ref(name, None, module, static, type, self.lineno(),
                               info, extra, self.conditionals)
690 691

    def warning(self, msg):
692 693
        global warnings
        warnings = warnings + 1
694
        if self.no_error:
695
            return
696
        print(msg)
697 698 699

    def error(self, msg, token=-1):
        if self.no_error:
700
            return
701

702
        print("Parse Error: " + msg)
703
        if token != -1:
704
            print("Got token ", token)
705 706
        self.lexer.debug()
        sys.exit(1)
707 708

    def debug(self, msg, token=-1):
709
        print("Debug: " + msg)
710
        if token != -1:
711
            print("Got token ", token)
712
        self.lexer.debug()
713 714

    def parseTopComment(self, comment):
715
        res = {}
716
        lines = comment.split("\n")
717 718
        item = None
        for line in lines:
C
Claudio Bley 已提交
719
            line = line.lstrip().lstrip('*').lstrip()
720 721 722 723 724 725 726

            m = re.match('([_.a-zA-Z0-9]+):(.*)', line)
            if m:
                item = m.group(1)
                line = m.group(2).lstrip()

            if item:
A
Andrea Bolognani 已提交
727
                if item in res:
728 729 730 731
                    res[item] = res[item] + " " + line
                else:
                    res[item] = line
        self.index.info = res
732

733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
    def strip_lead_star(self, line):
        l = len(line)
        i = 0
        while i < l:
            if line[i] == ' ' or line[i] == '\t':
                i += 1
            elif line[i] == '*':
                return line[:i] + line[i + 1:]
            else:
                 return line
        return line

    def cleanupComment(self):
        if type(self.comment) != type(""):
            return
        # remove the leading * on multi-line comments
        lines = self.comment.splitlines(True)
        com = ""
        for line in lines:
            com = com + self.strip_lead_star(line)
        self.comment = com.strip()

755
    def parseComment(self, token):
756
        com = token[1]
757
        if self.top_comment == "":
758
            self.top_comment = com
759
        if self.comment is None or com[0] == '*':
760
            self.comment = com
761
        else:
762
            self.comment = self.comment + com
763
        token = self.lexer.token()
764

765
        if self.comment.find("DOC_DISABLE") != -1:
766
            self.stop_error()
767

768
        if self.comment.find("DOC_ENABLE") != -1:
769
            self.start_error()
770

771
        return token
772 773 774 775 776 777

    #
    # Parse a comment block associate to a typedef
    #
    def parseTypeComment(self, name, quiet = 0):
        if name[0:2] == '__':
778
            quiet = 1
779 780

        args = []
781
        desc = ""
782

783
        if self.comment is None:
784 785 786
            if not quiet:
                self.warning("Missing comment for type %s" % (name))
            return((args, desc))
787
        if self.comment[0] != '*':
788 789 790
            if not quiet:
                self.warning("Missing * in type comment for %s" % (name))
            return((args, desc))
791
        lines = self.comment.split('\n')
792 793 794 795 796 797 798 799 800 801 802 803 804 805 806
        if lines[0] == '*':
            del lines[0]
        if lines[0] != "* %s:" % (name):
            if not quiet:
                self.warning("Misformatted type comment for %s" % (name))
                self.warning("  Expecting '* %s:' got '%s'" % (name, lines[0]))
            return((args, desc))
        del lines[0]
        while len(lines) > 0 and lines[0] == '*':
            del lines[0]
        desc = ""
        while len(lines) > 0:
            l = lines[0]
            while len(l) > 0 and l[0] == '*':
                l = l[1:]
807
            l = l.strip()
808 809 810
            desc = desc + " " + l
            del lines[0]

811
        desc = desc.strip()
812 813 814 815 816 817

        if quiet == 0:
            if desc == "":
                self.warning("Type comment for %s lack description of the macro" % (name))

        return(desc)
818 819 820 821
    #
    # Parse a comment block associate to a macro
    #
    def parseMacroComment(self, name, quiet = 0):
822 823
        global ignored_macros

824
        if name[0:2] == '__':
825
            quiet = 1
A
Andrea Bolognani 已提交
826
        if name in ignored_macros:
827
            quiet = 1
828 829

        args = []
830
        desc = ""
831

832
        if self.comment is None:
833 834 835
            if not quiet:
                self.warning("Missing comment for macro %s" % (name))
            return((args, desc))
836
        if self.comment[0] != '*':
837 838 839
            if not quiet:
                self.warning("Missing * in macro comment for %s" % (name))
            return((args, desc))
840
        lines = self.comment.split('\n')
841 842 843 844 845 846 847 848 849 850 851 852 853
        if lines[0] == '*':
            del lines[0]
        if lines[0] != "* %s:" % (name):
            if not quiet:
                self.warning("Misformatted macro comment for %s" % (name))
                self.warning("  Expecting '* %s:' got '%s'" % (name, lines[0]))
            return((args, desc))
        del lines[0]
        while lines[0] == '*':
            del lines[0]
        while len(lines) > 0 and lines[0][0:3] == '* @':
            l = lines[0][3:]
            try:
854 855 856
                (arg, desc) = l.split(':', 1)
                desc = desc.strip()
                arg = arg.strip()
857
            except:
858 859 860 861 862 863
                if not quiet:
                    self.warning("Misformatted macro comment for %s" % (name))
                    self.warning("  problem with '%s'" % (lines[0]))
                del lines[0]
                continue
            del lines[0]
864
            l = lines[0].strip()
865 866 867
            while len(l) > 2 and l[0:3] != '* @':
                while l[0] == '*':
                    l = l[1:]
868
                desc = desc + ' ' + l.strip()
869 870 871 872
                del lines[0]
                if len(lines) == 0:
                    break
                l = lines[0]
873
            args.append((arg, desc))
874 875 876 877 878 879 880
        while len(lines) > 0 and lines[0] == '*':
            del lines[0]
        desc = ""
        while len(lines) > 0:
            l = lines[0]
            while len(l) > 0 and l[0] == '*':
                l = l[1:]
881
            l = l.strip()
882 883
            desc = desc + " " + l
            del lines[0]
884

885
        desc = desc.strip()
886

887 888 889
        if quiet == 0:
            if desc == "":
                self.warning("Macro comment for %s lack description of the macro" % (name))
890

891
        return((args, desc))
892 893

     #
894
     # Parse a comment block and merge the information found in the
895 896 897 898
     # parameters descriptions, finally returns a block as complete
     # as possible
     #
    def mergeFunctionComment(self, name, description, quiet = 0):
D
Daniel Veillard 已提交
899 900
        global ignored_functions

901
        if name == 'main':
902
            quiet = 1
903
        if name[0:2] == '__':
904
            quiet = 1
A
Andrea Bolognani 已提交
905
        if name in ignored_functions:
D
Daniel Veillard 已提交
906
            quiet = 1
907

908 909 910
        (ret, args) = description
        desc = ""
        retdesc = ""
911

912
        if self.comment is None:
913 914 915
            if not quiet:
                self.warning("Missing comment for function %s" % (name))
            return(((ret[0], retdesc), args, desc))
916
        if self.comment[0] != '*':
917 918 919
            if not quiet:
                self.warning("Missing * in function comment for %s" % (name))
            return(((ret[0], retdesc), args, desc))
920
        lines = self.comment.split('\n')
921 922 923 924 925 926 927 928 929 930 931 932 933 934
        if lines[0] == '*':
            del lines[0]
        if lines[0] != "* %s:" % (name):
            if not quiet:
                self.warning("Misformatted function comment for %s" % (name))
                self.warning("  Expecting '* %s:' got '%s'" % (name, lines[0]))
            return(((ret[0], retdesc), args, desc))
        del lines[0]
        while lines[0] == '*':
            del lines[0]
        nbargs = len(args)
        while len(lines) > 0 and lines[0][0:3] == '* @':
            l = lines[0][3:]
            try:
935 936 937
                (arg, desc) = l.split(':', 1)
                desc = desc.strip()
                arg = arg.strip()
938
            except:
939 940 941 942 943 944
                if not quiet:
                    self.warning("Misformatted function comment for %s" % (name))
                    self.warning("  problem with '%s'" % (lines[0]))
                del lines[0]
                continue
            del lines[0]
945
            l = lines[0].strip()
946 947 948
            while len(l) > 2 and l[0:3] != '* @':
                while l[0] == '*':
                    l = l[1:]
949
                desc = desc + ' ' + l.strip()
950 951 952 953 954 955 956 957
                del lines[0]
                if len(lines) == 0:
                    break
                l = lines[0]
            i = 0
            while i < nbargs:
                if args[i][1] == arg:
                    args[i] = (args[i][0], arg, desc)
958
                    break
959 960 961 962 963 964 965 966 967 968 969 970
                i = i + 1
            if i >= nbargs:
                if not quiet:
                    self.warning("Unable to find arg %s from function comment for %s" % (
                       arg, name))
        while len(lines) > 0 and lines[0] == '*':
            del lines[0]
        desc = None
        while len(lines) > 0:
            l = lines[0]
            i = 0
            # Remove all leading '*', followed by at most one ' ' character
971
            # since we need to preserve correct indentation of code examples
972 973 974 975 976 977
            while i < len(l) and l[i] == '*':
                i = i + 1
            if i > 0:
                if i < len(l) and l[i] == ' ':
                    i = i + 1
                l = l[i:]
978
            if len(l) >= 6 and l[0:7] == "Returns":
979
                try:
980
                    l = l.split(' ', 1)[1]
981 982
                except:
                    l = ""
983
                retdesc = l.strip()
984 985 986 987 988
                del lines[0]
                while len(lines) > 0:
                    l = lines[0]
                    while len(l) > 0 and l[0] == '*':
                        l = l[1:]
989
                    l = l.strip()
990 991 992 993 994 995 996 997 998 999 1000
                    retdesc = retdesc + " " + l
                    del lines[0]
            else:
                if desc is not None:
                    desc = desc + "\n" + l
                else:
                    desc = l
                del lines[0]

        if desc is None:
            desc = ""
1001 1002
        retdesc = retdesc.strip()
        desc = desc.strip()
1003 1004 1005 1006 1007 1008 1009

        if quiet == 0:
             #
             # report missing comments
             #
            i = 0
            while i < nbargs:
1010
                if args[i][2] is None and args[i][0] != "void" and args[i][1] is not None:
1011 1012 1013 1014 1015 1016 1017 1018 1019
                    self.warning("Function comment for %s lacks description of arg %s" % (name, args[i][1]))
                i = i + 1
            if retdesc == "" and ret[0] != "void":
                self.warning("Function comment for %s lacks description of return value" % (name))
            if desc == "":
                self.warning("Function comment for %s lacks description of the function" % (name))


        return(((ret[0], retdesc), args, desc))
1020 1021

    def parsePreproc(self, token):
1022
        if debug:
1023
            print("=> preproc ", token, self.lexer.tokens)
1024
        name = token[1]
1025 1026
        if name == "#include":
            token = self.lexer.token()
1027
            if token is None:
1028 1029 1030 1031 1032 1033 1034 1035
                return None
            if token[0] == 'preproc':
                self.index_add(token[1], self.filename, not self.is_header,
                                "include")
                return self.lexer.token()
            return token
        if name == "#define":
            token = self.lexer.token()
1036
            if token is None:
1037 1038 1039 1040 1041 1042
                return None
            if token[0] == 'preproc':
                 # TODO macros with arguments
                name = token[1]
                lst = []
                token = self.lexer.token()
1043
                while token is not None and token[0] == 'preproc' and \
1044 1045 1046
                      token[1][0] != '#':
                    lst.append(token[1])
                    token = self.lexer.token()
1047
                try:
1048
                    name = name.split('(') [0]
1049 1050
                except:
                    pass
1051 1052 1053 1054 1055

                # skip hidden macros
                if name in hidden_macros:
                    return token

1056 1057 1058 1059
                strValue = None
                if len(lst) == 1 and lst[0][0] == '"' and lst[0][-1] == '"':
                    strValue = lst[0][1:-1]
                (args, desc) = self.parseMacroComment(name, not self.is_header)
1060
                self.index_add(name, self.filename, not self.is_header,
1061
                               "macro", (args, desc, strValue))
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
                return token

        #
        # Processing of conditionals modified by Bill 1/1/05
        #
        # We process conditionals (i.e. tokens from #ifdef, #ifndef,
        # #if, #else and #endif) for headers and mainline code,
        # store the ones from the header in libxml2-api.xml, and later
        # (in the routine merge_public) verify that the two (header and
        # mainline code) agree.
        #
        # There is a small problem with processing the headers. Some of
        # the variables are not concerned with enabling / disabling of
        # library functions (e.g. '__XML_PARSER_H__'), and we don't want
        # them to be included in libxml2-api.xml, or involved in
        # the check between the header and the mainline code.  To
        # accomplish this, we ignore any conditional which doesn't include
        # the string 'ENABLED'
        #
        if name == "#ifdef":
            apstr = self.lexer.tokens[0][1]
            try:
                self.defines.append(apstr)
1085
                if apstr.find('ENABLED') != -1:
1086 1087 1088 1089 1090 1091 1092
                    self.conditionals.append("defined(%s)" % apstr)
            except:
                pass
        elif name == "#ifndef":
            apstr = self.lexer.tokens[0][1]
            try:
                self.defines.append(apstr)
1093
                if apstr.find('ENABLED') != -1:
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
                    self.conditionals.append("!defined(%s)" % apstr)
            except:
                pass
        elif name == "#if":
            apstr = ""
            for tok in self.lexer.tokens:
                if apstr != "":
                    apstr = apstr + " "
                apstr = apstr + tok[1]
            try:
                self.defines.append(apstr)
1105
                if apstr.find('ENABLED') != -1:
1106 1107 1108 1109 1110
                    self.conditionals.append(apstr)
            except:
                pass
        elif name == "#else":
            if self.conditionals != [] and \
1111
               self.defines[-1].find('ENABLED') != -1:
1112 1113 1114
                self.conditionals[-1] = "!(%s)" % self.conditionals[-1]
        elif name == "#endif":
            if self.conditionals != [] and \
1115
               self.defines[-1].find('ENABLED') != -1:
1116 1117 1118
                self.conditionals = self.conditionals[:-1]
            self.defines = self.defines[:-1]
        token = self.lexer.token()
1119
        while token is not None and token[0] == 'preproc' and \
1120 1121 1122
            token[1][0] != '#':
            token = self.lexer.token()
        return token
1123 1124 1125 1126 1127 1128

     #
     # token acquisition on top of the lexer, it handle internally
     # preprocessor and comments since they are logically not part of
     # the program structure.
     #
1129 1130 1131
    def push(self, tok):
        self.lexer.push(tok)

1132 1133 1134 1135
    def token(self):
        global ignored_words

        token = self.lexer.token()
1136
        while token is not None:
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
            if token[0] == 'comment':
                token = self.parseComment(token)
                continue
            elif token[0] == 'preproc':
                token = self.parsePreproc(token)
                continue
            elif token[0] == "name" and token[1] == "__const":
                token = ("name", "const")
                return token
            elif token[0] == "name" and token[1] == "__attribute":
                token = self.lexer.token()
1148
                while token is not None and token[1] != ";":
1149 1150
                    token = self.lexer.token()
                return token
A
Andrea Bolognani 已提交
1151
            elif token[0] == "name" and token[1] in ignored_words:
1152 1153 1154 1155 1156 1157 1158 1159 1160
                (n, info) = ignored_words[token[1]]
                i = 0
                while i < n:
                    token = self.lexer.token()
                    i = i + 1
                token = self.lexer.token()
                continue
            else:
                if debug:
1161
                    print("=> ", token)
1162 1163
                return token
        return None
1164 1165 1166 1167 1168

     #
     # Parse a typedef, it records the type and its name.
     #
    def parseTypedef(self, token):
1169
        if token is None:
1170 1171
            return None
        token = self.parseType(token)
1172
        if token is None:
1173 1174 1175 1176 1177
            self.error("parsing typedef")
            return None
        base_type = self.type
        type = base_type
         #self.debug("end typedef type", token)
1178
        while token is not None:
1179 1180 1181
            if token[0] == "name":
                name = token[1]
                signature = self.signature
1182
                if signature is not None:
1183
                    type = type.split('(')[0]
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
                    d = self.mergeFunctionComment(name,
                            ((type, None), signature), 1)
                    self.index_add(name, self.filename, not self.is_header,
                                    "functype", d)
                else:
                    if base_type == "struct":
                        self.index_add(name, self.filename, not self.is_header,
                                        "struct", type)
                        base_type = "struct " + name
                    else:
                        # TODO report missing or misformatted comments
                        info = self.parseTypeComment(name, 1)
                        self.index_add(name, self.filename, not self.is_header,
                                    "typedef", type, info)
                token = self.token()
            else:
                self.error("parsing typedef: expecting a name")
                return token
             #self.debug("end typedef", token)
1203
            if token is not None and token[0] == 'sep' and token[1] == ',':
1204 1205
                type = base_type
                token = self.token()
1206
                while token is not None and token[0] == "op":
1207 1208
                    type = type + token[1]
                    token = self.token()
1209
            elif token is not None and token[0] == 'sep' and token[1] == ';':
1210
                break
1211
            elif token is not None and token[0] == 'name':
1212
                type = base_type
1213
                continue
1214 1215 1216 1217 1218
            else:
                self.error("parsing typedef: expecting ';'", token)
                return token
        token = self.token()
        return token
1219

1220 1221 1222 1223 1224
     #
     # Parse a C code block, used for functions it parse till
     # the balancing } included
     #
    def parseBlock(self, token):
1225
        while token is not None:
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
            if token[0] == "sep" and token[1] == "{":
                token = self.token()
                token = self.parseBlock(token)
            elif token[0] == "sep" and token[1] == "}":
                self.comment = None
                token = self.token()
                return token
            else:
                if self.collect_ref == 1:
                    oldtok = token
                    token = self.token()
                    if oldtok[0] == "name" and oldtok[1][0:3] == "vir":
                        if token[0] == "sep" and token[1] == "(":
                            self.index_add_ref(oldtok[1], self.filename,
                                                0, "function")
                            token = self.token()
                        elif token[0] == "name":
                            token = self.token()
                            if token[0] == "sep" and (token[1] == ";" or
                               token[1] == "," or token[1] == "="):
                                self.index_add_ref(oldtok[1], self.filename,
                                                    0, "type")
                    elif oldtok[0] == "name" and oldtok[1][0:4] == "XEN_":
                        self.index_add_ref(oldtok[1], self.filename,
                                            0, "typedef")
                    elif oldtok[0] == "name" and oldtok[1][0:7] == "LIBXEN_":
                        self.index_add_ref(oldtok[1], self.filename,
                                            0, "typedef")

                else:
                    token = self.token()
        return token
1258 1259 1260 1261 1262 1263

     #
     # Parse a C struct definition till the balancing }
     #
    def parseStruct(self, token):
        fields = []
1264
         #self.debug("start parseStruct", token)
1265
        while token is not None:
1266 1267 1268 1269 1270 1271
            if token[0] == "sep" and token[1] == "{":
                token = self.token()
                token = self.parseTypeBlock(token)
            elif token[0] == "sep" and token[1] == "}":
                self.struct_fields = fields
                 #self.debug("end parseStruct", token)
1272
                 #print(fields)
1273 1274 1275 1276 1277 1278 1279
                token = self.token()
                return token
            else:
                base_type = self.type
                 #self.debug("before parseType", token)
                token = self.parseType(token)
                 #self.debug("after parseType", token)
1280
                if token is not None and token[0] == "name":
1281 1282 1283 1284 1285
                    fname = token[1]
                    token = self.token()
                    if token[0] == "sep" and token[1] == ";":
                        self.comment = None
                        token = self.token()
1286 1287 1288 1289 1290 1291 1292
                        self.cleanupComment()
                        if self.type == "union":
                            fields.append((self.type, fname, self.comment,
                                           self.union_fields))
                            self.union_fields = []
                        else:
                            fields.append((self.type, fname, self.comment))
1293 1294 1295
                        self.comment = None
                    else:
                        self.error("parseStruct: expecting ;", token)
1296
                elif token is not None and token[0] == "sep" and token[1] == "{":
1297 1298
                    token = self.token()
                    token = self.parseTypeBlock(token)
1299
                    if token is not None and token[0] == "name":
1300
                        token = self.token()
1301
                    if token is not None and token[0] == "sep" and token[1] == ";":
1302 1303 1304 1305 1306 1307
                        token = self.token()
                    else:
                        self.error("parseStruct: expecting ;", token)
                else:
                    self.error("parseStruct: name", token)
                    token = self.token()
1308
                self.type = base_type
1309
        self.struct_fields = fields
1310
         #self.debug("end parseStruct", token)
1311
         #print(fields)
1312
        return token
1313

1314 1315 1316 1317 1318 1319
     #
     # Parse a C union definition till the balancing }
     #
    def parseUnion(self, token):
        fields = []
        # self.debug("start parseUnion", token)
1320
        while token is not None:
1321 1322 1323 1324 1325 1326
            if token[0] == "sep" and token[1] == "{":
                token = self.token()
                token = self.parseTypeBlock(token)
            elif token[0] == "sep" and token[1] == "}":
                self.union_fields = fields
                # self.debug("end parseUnion", token)
1327
                # print(fields)
1328 1329 1330 1331 1332 1333 1334
                token = self.token()
                return token
            else:
                base_type = self.type
                # self.debug("before parseType", token)
                token = self.parseType(token)
                # self.debug("after parseType", token)
1335
                if token is not None and token[0] == "name":
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
                    fname = token[1]
                    token = self.token()
                    if token[0] == "sep" and token[1] == ";":
                        self.comment = None
                        token = self.token()
                        self.cleanupComment()
                        fields.append((self.type, fname, self.comment))
                        self.comment = None
                    else:
                        self.error("parseUnion: expecting ;", token)
1346
                elif token is not None and token[0] == "sep" and token[1] == "{":
1347 1348
                    token = self.token()
                    token = self.parseTypeBlock(token)
1349
                    if token is not None and token[0] == "name":
1350
                        token = self.token()
1351
                    if token is not None and token[0] == "sep" and token[1] == ";":
1352 1353 1354 1355 1356 1357
                        token = self.token()
                    else:
                        self.error("parseUnion: expecting ;", token)
                else:
                    self.error("parseUnion: name", token)
                    token = self.token()
1358
                self.type = base_type
1359 1360
        self.union_fields = fields
        # self.debug("end parseUnion", token)
1361
        # print(fields)
1362 1363
        return token

1364 1365 1366 1367 1368
     #
     # Parse a C enum block, parse till the balancing }
     #
    def parseEnumBlock(self, token):
        self.enums = []
1369 1370
        name = None
        comment = ""
E
Eric Blake 已提交
1371
        value = "-1"
1372
        commentsBeforeVal = self.comment is not None
1373
        while token is not None:
1374 1375 1376 1377
            if token[0] == "sep" and token[1] == "{":
                token = self.token()
                token = self.parseTypeBlock(token)
            elif token[0] == "sep" and token[1] == "}":
1378
                if name is not None:
1379
                    self.cleanupComment()
1380
                    if self.comment is not None:
1381 1382 1383 1384 1385 1386
                        comment = self.comment
                        self.comment = None
                    self.enums.append((name, value, comment))
                token = self.token()
                return token
            elif token[0] == "name":
J
Jiri Denemark 已提交
1387 1388 1389
                self.cleanupComment()
                if name is not None:
                    if self.comment is not None:
1390
                        comment = self.comment.strip()
J
Jiri Denemark 已提交
1391 1392 1393 1394 1395 1396 1397 1398 1399
                        self.comment = None
                    self.enums.append((name, value, comment))
                name = token[1]
                comment = ""
                token = self.token()
                if token[0] == "op" and token[1][0] == "=":
                    value = ""
                    if len(token[1]) > 1:
                        value = token[1][1:]
1400
                    token = self.token()
J
Jiri Denemark 已提交
1401 1402
                    while token[0] != "sep" or (token[1] != ',' and
                          token[1] != '}'):
1403
                        # We might be dealing with '1U << 12' here
1404
                        value = value + re.sub("^(\d+)U$","\\1", token[1])
1405
                        token = self.token()
J
Jiri Denemark 已提交
1406 1407 1408 1409 1410 1411 1412
                else:
                    try:
                        value = "%d" % (int(value) + 1)
                    except:
                        self.warning("Failed to compute value of enum %s" % (name))
                        value=""
                if token[0] == "sep" and token[1] == ",":
1413 1414 1415 1416
                    if commentsBeforeVal:
                        self.cleanupComment()
                        self.enums.append((name, value, self.comment))
                        name = comment = self.comment = None
J
Jiri Denemark 已提交
1417
                    token = self.token()
1418 1419 1420
            else:
                token = self.token()
        return token
1421

1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510
    def parseVirEnumDecl(self, token):
        if token[0] != "name":
            self.error("parsing VIR_ENUM_DECL: expecting name", token)

        token = self.token()

        if token[0] != "sep":
            self.error("parsing VIR_ENUM_DECL: expecting ')'", token)

        if token[1] != ')':
            self.error("parsing VIR_ENUM_DECL: expecting ')'", token)

        token = self.token()
        if token[0] == "sep" and token[1] == ';':
            token = self.token()

        return token

    def parseVirEnumImpl(self, token):
        # First the type name
        if token[0] != "name":
            self.error("parsing VIR_ENUM_IMPL: expecting name", token)

        token = self.token()

        if token[0] != "sep":
            self.error("parsing VIR_ENUM_IMPL: expecting ','", token)

        if token[1] != ',':
            self.error("parsing VIR_ENUM_IMPL: expecting ','", token)
        token = self.token()

        # Now the sentinel name
        if token[0] != "name":
            self.error("parsing VIR_ENUM_IMPL: expecting name", token)

        token = self.token()

        if token[0] != "sep":
            self.error("parsing VIR_ENUM_IMPL: expecting ','", token)

        if token[1] != ',':
            self.error("parsing VIR_ENUM_IMPL: expecting ','", token)

        token = self.token()

        # Now a list of strings (optional comments)
        while token is not None:
            isGettext = False
            # First a string, optionally with N_(...)
            if token[0] == 'name':
                if token[1] != 'N_':
                    self.error("parsing VIR_ENUM_IMPL: expecting 'N_'", token)
                token = self.token()
                if token[0] != "sep" or token[1] != '(':
                    self.error("parsing VIR_ENUM_IMPL: expecting '('", token)
                token = self.token()
                isGettext = True

                if token[0] != "string":
                    self.error("parsing VIR_ENUM_IMPL: expecting a string", token)
                token = self.token()
            elif token[0] == "string":
                token = self.token()
            else:
                self.error("parsing VIR_ENUM_IMPL: expecting a string", token)

            # Then a separator
            if token[0] == "sep":
                if isGettext and token[1] == ')':
                    token = self.token()

                if token[1] == ',':
                    token = self.token()

                if token[1] == ')':
                    token = self.token()
                    break

            # Then an optional comment
            if token[0] == "comment":
                token = self.token()


        if token[0] == "sep" and token[1] == ';':
            token = self.token()

        return token

1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
    def parseVirLogInit(self, token):
        if token[0] != "string":
            self.error("parsing VIR_LOG_INIT: expecting string", token)

        token = self.token()

        if token[0] != "sep":
            self.error("parsing VIR_LOG_INIT: expecting ')'", token)

        if token[1] != ')':
            self.error("parsing VIR_LOG_INIT: expecting ')'", token)

        token = self.token()
        if token[0] == "sep" and token[1] == ';':
            token = self.token()

        return token

1529
     #
1530
     # Parse a C definition block, used for structs or unions it parse till
1531 1532 1533
     # the balancing }
     #
    def parseTypeBlock(self, token):
1534
        while token is not None:
1535 1536 1537 1538 1539 1540 1541 1542 1543
            if token[0] == "sep" and token[1] == "{":
                token = self.token()
                token = self.parseTypeBlock(token)
            elif token[0] == "sep" and token[1] == "}":
                token = self.token()
                return token
            else:
                token = self.token()
        return token
1544 1545 1546 1547 1548 1549 1550 1551

     #
     # Parse a type: the fact that the type name can either occur after
     #    the definition or within the definition makes it a little harder
     #    if inside, the name token is pushed back before returning
     #
    def parseType(self, token):
        self.type = ""
1552
        self.struct_fields = []
1553
        self.union_fields = []
1554
        self.signature = None
1555
        if token is None:
1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566
            return token

        while token[0] == "name" and (
              token[1] == "const" or \
              token[1] == "unsigned" or \
              token[1] == "signed"):
            if self.type == "":
                self.type = token[1]
            else:
                self.type = self.type + " " + token[1]
            token = self.token()
1567

1568
        if token[0] == "name" and token[1] == "long":
1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582
            if self.type == "":
                self.type = token[1]
            else:
                self.type = self.type + " " + token[1]

            # some read ahead for long long
            oldtmp = token
            token = self.token()
            if token[0] == "name" and token[1] == "long":
                self.type = self.type + " " + token[1]
            else:
                self.push(token)
                token = oldtmp

1583 1584
            oldtmp = token
            token = self.token()
1585
            if token[0] == "name" and token[1] == "int":
1586 1587 1588 1589
                self.type = self.type + " " + token[1]
            else:
                self.push(token)
                token = oldtmp
1590 1591

        elif token[0] == "name" and token[1] == "short":
1592 1593 1594 1595
            if self.type == "":
                self.type = token[1]
            else:
                self.type = self.type + " " + token[1]
1596

1597
        elif token[0] == "name" and token[1] == "struct":
1598 1599 1600 1601 1602 1603 1604 1605 1606
            if self.type == "":
                self.type = token[1]
            else:
                self.type = self.type + " " + token[1]
            token = self.token()
            nametok = None
            if token[0] == "name":
                nametok = token
                token = self.token()
1607
            if token is not None and token[0] == "sep" and token[1] == "{":
1608 1609
                token = self.token()
                token = self.parseStruct(token)
1610
            elif token is not None and token[0] == "op" and token[1] == "*":
1611 1612
                self.type = self.type + " " + nametok[1] + " *"
                token = self.token()
1613
                while token is not None and token[0] == "op" and token[1] == "*":
1614 1615 1616 1617 1618 1619 1620 1621
                    self.type = self.type + " *"
                    token = self.token()
                if token[0] == "name":
                    nametok = token
                    token = self.token()
                else:
                    self.error("struct : expecting name", token)
                    return token
1622
            elif token is not None and token[0] == "name" and nametok is not None:
1623 1624 1625
                self.type = self.type + " " + nametok[1]
                return token

1626
            if nametok is not None:
1627 1628 1629
                self.lexer.push(token)
                token = nametok
            return token
1630

1631 1632 1633 1634 1635 1636 1637 1638 1639 1640
        elif token[0] == "name" and token[1] == "union":
            if self.type == "":
                self.type = token[1]
            else:
                self.type = self.type + " " + token[1]
            token = self.token()
            nametok = None
            if token[0] == "name":
                nametok = token
                token = self.token()
1641
            if token is not None and token[0] == "sep" and token[1] == "{":
1642 1643
                token = self.token()
                token = self.parseUnion(token)
1644
            elif token is not None and token[0] == "name" and nametok is not None:
1645 1646 1647
                self.type = self.type + " " + nametok[1]
                return token

1648
            if nametok is not None:
1649 1650 1651 1652
                self.lexer.push(token)
                token = nametok
            return token

1653
        elif token[0] == "name" and token[1] == "enum":
1654 1655 1656 1657 1658 1659
            if self.type == "":
                self.type = token[1]
            else:
                self.type = self.type + " " + token[1]
            self.enums = []
            token = self.token()
1660
            if token is not None and token[0] == "sep" and token[1] == "{":
1661 1662
                # drop comments before the enum block
                self.comment = None
1663 1664 1665 1666 1667
                token = self.token()
                token = self.parseEnumBlock(token)
            else:
                self.error("parsing enum: expecting '{'", token)
            enum_type = None
1668
            if token is not None and token[0] != "name":
1669 1670 1671 1672 1673 1674 1675 1676 1677
                self.lexer.push(token)
                token = ("name", "enum")
            else:
                enum_type = token[1]
            for enum in self.enums:
                self.index_add(enum[0], self.filename,
                               not self.is_header, "enum",
                               (enum[1], enum[2], enum_type))
            return token
1678 1679
        elif token[0] == "name" and token[1] == "VIR_ENUM_DECL":
            token = self.token()
1680
            if token is not None and token[0] == "sep" and token[1] == "(":
1681 1682 1683 1684
                token = self.token()
                token = self.parseVirEnumDecl(token)
            else:
                self.error("parsing VIR_ENUM_DECL: expecting '('", token)
1685
            if token is not None:
1686 1687 1688 1689 1690 1691
                self.lexer.push(token)
                token = ("name", "virenumdecl")
            return token

        elif token[0] == "name" and token[1] == "VIR_ENUM_IMPL":
            token = self.token()
1692
            if token is not None and token[0] == "sep" and token[1] == "(":
1693 1694 1695 1696
                token = self.token()
                token = self.parseVirEnumImpl(token)
            else:
                self.error("parsing VIR_ENUM_IMPL: expecting '('", token)
1697
            if token is not None:
1698 1699 1700
                self.lexer.push(token)
                token = ("name", "virenumimpl")
            return token
1701

1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713
        elif token[0] == "name" and token[1] == "VIR_LOG_INIT":
            token = self.token()
            if token is not None and token[0] == "sep" and token[1] == "(":
                token = self.token()
                token = self.parseVirLogInit(token)
            else:
                self.error("parsing VIR_LOG_INIT: expecting '('", token)
            if token is not None:
                self.lexer.push(token)
                token = ("name", "virloginit")
            return token

1714 1715 1716 1717 1718 1719 1720 1721 1722 1723
        elif token[0] == "name":
            if self.type == "":
                self.type = token[1]
            else:
                self.type = self.type + " " + token[1]
        else:
            self.error("parsing type %s: expecting a name" % (self.type),
                       token)
            return token
        token = self.token()
1724
        while token is not None and (token[0] == "op" or
1725 1726 1727
              token[0] == "name" and token[1] == "const"):
            self.type = self.type + " " + token[1]
            token = self.token()
1728 1729

         #
1730 1731
         # if there is a parenthesis here, this means a function type
         #
1732
        if token is not None and token[0] == "sep" and token[1] == '(':
1733 1734
            self.type = self.type + token[1]
            token = self.token()
1735
            while token is not None and token[0] == "op" and token[1] == '*':
1736 1737
                self.type = self.type + token[1]
                token = self.token()
1738
            if token is None or token[0] != "name" :
1739
                self.error("parsing function type, name expected", token)
1740 1741 1742 1743
                return token
            self.type = self.type + token[1]
            nametok = token
            token = self.token()
1744
            if token is not None and token[0] == "sep" and token[1] == ')':
1745 1746
                self.type = self.type + token[1]
                token = self.token()
1747
                if token is not None and token[0] == "sep" and token[1] == '(':
1748
                    token = self.token()
1749 1750 1751
                    type = self.type
                    token = self.parseSignature(token)
                    self.type = type
1752
                else:
1753
                    self.error("parsing function type, '(' expected", token)
1754 1755
                    return token
            else:
1756
                self.error("parsing function type, ')' expected", token)
1757 1758 1759 1760 1761 1762 1763 1764
                return token
            self.lexer.push(token)
            token = nametok
            return token

         #
         # do some lookahead for arrays
         #
1765
        if token is not None and token[0] == "name":
1766 1767
            nametok = token
            token = self.token()
1768
            if token is not None and token[0] == "sep" and token[1] == '[':
1769
                self.type = self.type + " " + nametok[1]
1770
                while token is not None and token[0] == "sep" and token[1] == '[':
1771 1772
                    self.type = self.type + token[1]
                    token = self.token()
1773
                    while token is not None and token[0] != 'sep' and \
1774 1775 1776
                          token[1] != ']' and token[1] != ';':
                        self.type = self.type + token[1]
                        token = self.token()
1777
                if token is not None and token[0] == 'sep' and token[1] == ']':
1778 1779 1780
                    self.type = self.type + token[1]
                    token = self.token()
                else:
1781
                    self.error("parsing array type, ']' expected", token)
1782
                    return token
1783
            elif token is not None and token[0] == "sep" and token[1] == ':':
1784 1785 1786 1787 1788 1789 1790
                 # remove :12 in case it's a limited int size
                token = self.token()
                token = self.token()
            self.lexer.push(token)
            token = nametok

        return token
1791 1792 1793 1794 1795 1796

     #
     # Parse a signature: '(' has been parsed and we scan the type definition
     #    up to the ')' included
    def parseSignature(self, token):
        signature = []
1797
        if token is not None and token[0] == "sep" and token[1] == ')':
1798 1799 1800
            self.signature = []
            token = self.token()
            return token
1801
        while token is not None:
1802
            token = self.parseType(token)
1803
            if token is not None and token[0] == "name":
1804 1805
                signature.append((self.type, token[1], None))
                token = self.token()
1806
            elif token is not None and token[0] == "sep" and token[1] == ',':
1807 1808
                token = self.token()
                continue
1809
            elif token is not None and token[0] == "sep" and token[1] == ')':
1810 1811 1812 1813 1814
                 # only the type was provided
                if self.type == "...":
                    signature.append((self.type, "...", None))
                else:
                    signature.append((self.type, None, None))
1815
            if token is not None and token[0] == "sep":
1816 1817 1818 1819 1820 1821 1822 1823
                if token[1] == ',':
                    token = self.token()
                    continue
                elif token[1] == ')':
                    token = self.token()
                    break
        self.signature = signature
        return token
1824

1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856
    # this dict contains the functions that are allowed to use [unsigned]
    # long for legacy reasons in their signature and return type. this list is
    # fixed. new procedures and public APIs have to use [unsigned] long long
    long_legacy_functions = \
      { "virGetVersion"                  : (False, ("libVer", "typeVer")),
        "virConnectGetLibVersion"        : (False, ("libVer")),
        "virConnectGetVersion"           : (False, ("hvVer")),
        "virDomainGetMaxMemory"          : (True,  ()),
        "virDomainMigrate"               : (False, ("flags", "bandwidth")),
        "virDomainMigrate2"              : (False, ("flags", "bandwidth")),
        "virDomainMigrateBegin3"         : (False, ("flags", "bandwidth")),
        "virDomainMigrateConfirm3"       : (False, ("flags", "bandwidth")),
        "virDomainMigrateDirect"         : (False, ("flags", "bandwidth")),
        "virDomainMigrateFinish"         : (False, ("flags")),
        "virDomainMigrateFinish2"        : (False, ("flags")),
        "virDomainMigrateFinish3"        : (False, ("flags")),
        "virDomainMigratePeer2Peer"      : (False, ("flags", "bandwidth")),
        "virDomainMigratePerform"        : (False, ("flags", "bandwidth")),
        "virDomainMigratePerform3"       : (False, ("flags", "bandwidth")),
        "virDomainMigratePrepare"        : (False, ("flags", "bandwidth")),
        "virDomainMigratePrepare2"       : (False, ("flags", "bandwidth")),
        "virDomainMigratePrepare3"       : (False, ("flags", "bandwidth")),
        "virDomainMigratePrepareTunnel"  : (False, ("flags", "bandwidth")),
        "virDomainMigratePrepareTunnel3" : (False, ("flags", "bandwidth")),
        "virDomainMigrateToURI"          : (False, ("flags", "bandwidth")),
        "virDomainMigrateToURI2"         : (False, ("flags", "bandwidth")),
        "virDomainMigrateVersion1"       : (False, ("flags", "bandwidth")),
        "virDomainMigrateVersion2"       : (False, ("flags", "bandwidth")),
        "virDomainMigrateVersion3"       : (False, ("flags", "bandwidth")),
        "virDomainMigrateSetMaxSpeed"    : (False, ("bandwidth")),
        "virDomainSetMaxMemory"          : (False, ("memory")),
        "virDomainSetMemory"             : (False, ("memory")),
1857
        "virDomainSetMemoryFlags"        : (False, ("memory")),
E
Eric Blake 已提交
1858
        "virDomainBlockCommit"           : (False, ("bandwidth")),
1859
        "virDomainBlockJobSetSpeed"      : (False, ("bandwidth")),
1860
        "virDomainBlockPull"             : (False, ("bandwidth")),
1861
        "virDomainBlockRebase"           : (False, ("bandwidth")),
1862
        "virDomainMigrateGetMaxSpeed"    : (False, ("bandwidth")) }
1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887

    def checkLongLegacyFunction(self, name, return_type, signature):
        if "long" in return_type and "long long" not in return_type:
            try:
                if not CParser.long_legacy_functions[name][0]:
                    raise Exception()
            except:
                self.error(("function '%s' is not allowed to return long, "
                            "use long long instead") % (name))

        for param in signature:
            if "long" in param[0] and "long long" not in param[0]:
                try:
                    if param[1] not in CParser.long_legacy_functions[name][1]:
                        raise Exception()
                except:
                    self.error(("function '%s' is not allowed to take long "
                                "parameter '%s', use long long instead")
                               % (name, param[1]))

    # this dict contains the structs that are allowed to use [unsigned]
    # long for legacy reasons. this list is fixed. new structs have to use
    # [unsigned] long long
    long_legacy_struct_fields = \
      { "_virDomainInfo"                 : ("maxMem", "memory"),
1888 1889
        "_virNodeInfo"                   : ("memory"),
        "_virDomainBlockJobInfo"         : ("bandwidth") }
1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901

    def checkLongLegacyStruct(self, name, fields):
        for field in fields:
            if "long" in field[0] and "long long" not in field[0]:
                try:
                    if field[1] not in CParser.long_legacy_struct_fields[name]:
                        raise Exception()
                except:
                    self.error(("struct '%s' is not allowed to contain long "
                                "field '%s', use long long instead") \
                               % (name, field[1]))

1902 1903 1904 1905 1906 1907 1908
     #
     # Parse a global definition, be it a type, variable or function
     # the extern "C" blocks are a bit nasty and require it to recurse.
     #
    def parseGlobal(self, token):
        static = 0
        if token[1] == 'extern':
1909
            token = self.token()
1910
            if token is None:
1911 1912 1913 1914
                return token
            if token[0] == 'string':
                if token[1] == 'C':
                    token = self.token()
1915
                    if token is None:
1916 1917 1918
                        return token
                    if token[0] == 'sep' and token[1] == "{":
                        token = self.token()
1919
#                        print('Entering extern "C line ', self.lineno())
1920
                        while token is not None and (token[0] != 'sep' or
1921 1922 1923 1924 1925 1926 1927 1928
                              token[1] != "}"):
                            if token[0] == 'name':
                                token = self.parseGlobal(token)
                            else:
                                self.error(
                                 "token %s %s unexpected at the top level" % (
                                        token[0], token[1]))
                                token = self.parseGlobal(token)
1929
#                        print('Exiting extern "C" line', self.lineno())
1930 1931 1932 1933 1934 1935 1936
                        token = self.token()
                        return token
                else:
                    return token
        elif token[1] == 'static':
            static = 1
            token = self.token()
1937
            if token is None or  token[0] != 'name':
1938 1939 1940 1941 1942 1943 1944 1945
                return token

        if token[1] == 'typedef':
            token = self.token()
            return self.parseTypedef(token)
        else:
            token = self.parseType(token)
            type_orig = self.type
1946
        if token is None or token[0] != "name":
1947 1948 1949 1950
            return token
        type = type_orig
        self.name = token[1]
        token = self.token()
1951
        while token is not None and (token[0] == "sep" or token[0] == "op"):
1952 1953 1954 1955
            if token[0] == "sep":
                if token[1] == "[":
                    type = type + token[1]
                    token = self.token()
1956
                    while token is not None and (token[0] != "sep" or \
1957 1958 1959 1960
                          token[1] != ";"):
                        type = type + token[1]
                        token = self.token()

1961
            if token is not None and token[0] == "op" and token[1] == "=":
1962 1963 1964 1965 1966 1967 1968 1969 1970
                 #
                 # Skip the initialization of the variable
                 #
                token = self.token()
                if token[0] == 'sep' and token[1] == '{':
                    token = self.token()
                    token = self.parseBlock(token)
                else:
                    self.comment = None
1971
                    while token is not None and (token[0] != "sep" or \
1972 1973 1974
                          (token[1] != ';' and token[1] != ',')):
                            token = self.token()
                self.comment = None
1975
                if token is None or token[0] != "sep" or (token[1] != ';' and
1976 1977 1978
                   token[1] != ','):
                    self.error("missing ';' or ',' after value")

1979
            if token is not None and token[0] == "sep":
1980 1981 1982 1983
                if token[1] == ";":
                    self.comment = None
                    token = self.token()
                    if type == "struct":
1984
                        self.checkLongLegacyStruct(self.name, self.struct_fields)
1985 1986 1987 1988 1989 1990 1991 1992 1993
                        self.index_add(self.name, self.filename,
                             not self.is_header, "struct", self.struct_fields)
                    else:
                        self.index_add(self.name, self.filename,
                             not self.is_header, "variable", type)
                    break
                elif token[1] == "(":
                    token = self.token()
                    token = self.parseSignature(token)
1994
                    if token is None:
1995 1996
                        return None
                    if token[0] == "sep" and token[1] == ";":
1997
                        self.checkLongLegacyFunction(self.name, type, self.signature)
1998 1999 2000 2001 2002 2003
                        d = self.mergeFunctionComment(self.name,
                                ((type, None), self.signature), 1)
                        self.index_add(self.name, self.filename, static,
                                        "function", d)
                        token = self.token()
                    elif token[0] == "sep" and token[1] == "{":
2004
                        self.checkLongLegacyFunction(self.name, type, self.signature)
2005 2006 2007 2008 2009
                        d = self.mergeFunctionComment(self.name,
                                ((type, None), self.signature), static)
                        self.index_add(self.name, self.filename, static,
                                        "function", d)
                        token = self.token()
2010
                        token = self.parseBlock(token)
2011 2012 2013 2014 2015 2016
                elif token[1] == ',':
                    self.comment = None
                    self.index_add(self.name, self.filename, static,
                                    "variable", type)
                    type = type_orig
                    token = self.token()
2017
                    while token is not None and token[0] == "sep":
2018 2019
                        type = type + token[1]
                        token = self.token()
2020
                    if token is not None and token[0] == "name":
2021 2022 2023 2024 2025 2026
                        self.name = token[1]
                        token = self.token()
                else:
                    break

        return token
2027 2028

    def parse(self):
2029
        if not quiet:
2030
            print("Parsing %s" % (self.filename))
2031
        token = self.token()
2032
        while token is not None:
2033
            if token[0] == 'name':
2034
                token = self.parseGlobal(token)
2035
            else:
2036 2037 2038 2039 2040
                self.error("token %s %s unexpected at the top level" % (
                       token[0], token[1]))
                token = self.parseGlobal(token)
                return
        self.parseTopComment(self.top_comment)
2041
        return self.index
2042

2043 2044 2045

class docBuilder:
    """A documentation builder"""
J
Jiri Denemark 已提交
2046
    def __init__(self, name, path='.', directories=['.'], includes=[]):
2047
        self.name = name
J
Jiri Denemark 已提交
2048
        self.path = path
2049
        self.directories = directories
2050
        if name == "libvirt":
2051
            self.includes = includes + list(included_files.keys())
2052
        elif name == "libvirt-qemu":
2053
            self.includes = includes + list(qemu_included_files.keys())
2054
        elif name == "libvirt-lxc":
2055
            self.includes = includes + list(lxc_included_files.keys())
2056
        elif name == "libvirt-admin":
2057
            self.includes = includes + list(admin_included_files.keys())
2058 2059 2060
        self.modules = {}
        self.headers = {}
        self.idx = index()
2061
        self.xref = {}
2062 2063
        self.index = {}
        self.basename = name
2064
        self.errors = 0
2065

2066 2067 2068
    def warning(self, msg):
        global warnings
        warnings = warnings + 1
2069
        print(msg)
2070

2071 2072
    def error(self, msg):
        self.errors += 1
2073
        print("Error:", msg, file=sys.stderr)
2074

2075
    def indexString(self, id, str):
2076
        if str is None:
2077
            return
2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093
        str = str.replace("'", ' ')
        str = str.replace('"', ' ')
        str = str.replace("/", ' ')
        str = str.replace('*', ' ')
        str = str.replace("[", ' ')
        str = str.replace("]", ' ')
        str = str.replace("(", ' ')
        str = str.replace(")", ' ')
        str = str.replace("<", ' ')
        str = str.replace('>', ' ')
        str = str.replace("&", ' ')
        str = str.replace('#', ' ')
        str = str.replace(",", ' ')
        str = str.replace('.', ' ')
        str = str.replace(';', ' ')
        tokens = str.split()
2094 2095 2096
        for token in tokens:
            try:
                c = token[0]
2097
                if string.letters.find(c) < 0:
2098 2099 2100 2101 2102 2103 2104 2105
                    pass
                elif len(token) < 3:
                    pass
                else:
                    lower = string.lower(token)
                    # TODO: generalize this a bit
                    if lower == 'and' or lower == 'the':
                        pass
A
Andrea Bolognani 已提交
2106
                    elif token in self.xref:
2107 2108 2109 2110 2111
                        self.xref[token].append(id)
                    else:
                        self.xref[token] = [id]
            except:
                pass
2112 2113

    def analyze(self):
2114
        if not quiet:
2115
            print("Project %s : %d headers, %d modules" % (self.name, len(self.headers.keys()), len(self.modules.keys())))
2116
        self.idx.analyze()
2117 2118

    def scanHeaders(self):
2119 2120 2121
        for header in self.headers.keys():
            parser = CParser(header)
            idx = parser.parse()
2122
            self.headers[header] = idx
2123
            self.idx.merge(idx)
2124 2125

    def scanModules(self):
2126 2127 2128 2129 2130 2131
        for module in self.modules.keys():
            parser = CParser(module)
            idx = parser.parse()
            # idx.analyze()
            self.modules[module] = idx
            self.idx.merge_public(idx)
2132 2133 2134

    def scan(self):
        for directory in self.directories:
2135 2136 2137 2138
            files = glob.glob(directory + "/*.c")
            for file in files:
                skip = 1
                for incl in self.includes:
2139
                    if file.find(incl) != -1:
2140
                        skip = 0
2141 2142
                        break
                if skip == 0:
2143
                    self.modules[file] = None
2144 2145 2146 2147
            files = glob.glob(directory + "/*.h")
            for file in files:
                skip = 1
                for incl in self.includes:
2148
                    if file.find(incl) != -1:
2149
                        skip = 0
2150 2151
                        break
                if skip == 0:
2152
                    self.headers[file] = None
2153 2154
        self.scanHeaders()
        self.scanModules()
2155

2156 2157
    def modulename_file(self, file):
        module = os.path.basename(file)
2158 2159 2160 2161 2162
        if module[-2:] == '.h':
            module = module[:-2]
        elif module[-2:] == '.c':
            module = module[:-2]
        return module
2163 2164 2165 2166

    def serialize_enum(self, output, name):
        id = self.idx.enums[name]
        output.write("    <enum name='%s' file='%s'" % (name,
2167
                     self.modulename_file(id.header)))
2168
        if id.info is not None:
2169
            info = id.info
2170
            if info[0] is not None and info[0] != '':
2171 2172 2173 2174
                try:
                    val = eval(info[0])
                except:
                    val = info[0]
2175
                output.write(" value='%s'" % (val))
2176
            if info[2] is not None and info[2] != '':
2177
                output.write(" type='%s'" % info[2])
2178
            if info[1] is not None and info[1] != '':
2179
                output.write(" info='%s'" % escape(info[1]))
2180 2181 2182 2183
        output.write("/>\n")

    def serialize_macro(self, output, name):
        id = self.idx.macros[name]
2184
        output.write("    <macro name='%s' file='%s'" % (name,
2185
                     self.modulename_file(id.header)))
2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207
        if id.info is None:
            args = []
            desc = None
            strValue = None
        else:
            (args, desc, strValue) = id.info

        if strValue is not None:
            output.write(" string='%s'" % strValue)
        output.write(">\n")

        if desc is not None and desc != "":
            output.write("      <info><![CDATA[%s]]></info>\n" % (desc))
            self.indexString(name, desc)
        for arg in args:
            (name, desc) = arg
            if desc is not None and desc != "":
                output.write("      <arg name='%s' info='%s'/>\n" % (
                             name, escape(desc)))
                self.indexString(name, desc)
            else:
                output.write("      <arg name='%s'/>\n" % (name))
2208 2209
        output.write("    </macro>\n")

2210 2211 2212 2213 2214
    def serialize_union(self, output, field, desc):
        output.write("      <field name='%s' type='union' info='%s'>\n" % (field[1] , desc))
        output.write("        <union>\n")
        for f in field[3]:
            desc = f[2]
2215
            if desc is None:
2216 2217 2218 2219 2220 2221 2222 2223
                desc = ''
            else:
                desc = escape(desc)
            output.write("          <field name='%s' type='%s' info='%s'/>\n" % (f[1] , f[0], desc))

        output.write("        </union>\n")
        output.write("      </field>\n")

2224 2225
    def serialize_typedef(self, output, name):
        id = self.idx.typedefs[name]
2226 2227 2228 2229
        if id.info[0:7] == 'struct ':
            output.write("    <struct name='%s' file='%s' type='%s'" % (
                     name, self.modulename_file(id.header), id.info))
            name = id.info[7:]
A
Andrea Bolognani 已提交
2230
            if name in self.idx.structs and ( \
2231 2232
               type(self.idx.structs[name].info) == type(()) or
                type(self.idx.structs[name].info) == type([])):
2233
                output.write(">\n")
2234 2235 2236 2237
                try:
                    for field in self.idx.structs[name].info:
                        desc = field[2]
                        self.indexString(name, desc)
2238
                        if desc is None:
2239 2240 2241
                            desc = ''
                        else:
                            desc = escape(desc)
2242 2243 2244 2245
                        if field[0] == "union":
                            self.serialize_union(output, field, desc)
                        else:
                            output.write("      <field name='%s' type='%s' info='%s'/>\n" % (field[1] , field[0], desc))
2246
                except:
2247
                    self.warning("Failed to serialize struct %s" % (name))
2248 2249
                output.write("    </struct>\n")
            else:
2250
                output.write("/>\n")
2251 2252 2253
        else :
            output.write("    <typedef name='%s' file='%s' type='%s'" % (
                         name, self.modulename_file(id.header), id.info))
2254
            try:
2255
                desc = id.extra
2256
                if desc is not None and desc != "":
2257 2258 2259 2260 2261 2262
                    output.write(">\n      <info><![CDATA[%s]]></info>\n" % (desc))
                    output.write("    </typedef>\n")
                else:
                    output.write("/>\n")
            except:
                output.write("/>\n")
2263 2264 2265

    def serialize_variable(self, output, name):
        id = self.idx.variables[name]
2266
        if id.info is not None:
2267 2268 2269 2270 2271
            output.write("    <variable name='%s' file='%s' type='%s'/>\n" % (
                    name, self.modulename_file(id.header), id.info))
        else:
            output.write("    <variable name='%s' file='%s'/>\n" % (
                    name, self.modulename_file(id.header)))
2272

2273 2274
    def serialize_function(self, output, name):
        id = self.idx.functions[name]
2275
        if name == debugsym and not quiet:
2276
            print("=>", id)
2277

2278
        # NB: this is consumed by a regex in 'getAPIFilenames' in hvsupport.pl
2279
        output.write("    <%s name='%s' file='%s' module='%s'>\n" % (id.type,
2280 2281 2282 2283 2284
                     name, self.modulename_file(id.header),
                     self.modulename_file(id.module)))
        #
        # Processing of conditionals modified by Bill 1/1/05
        #
2285
        if id.conditionals is not None:
2286 2287 2288 2289 2290
            apstr = ""
            for cond in id.conditionals:
                if apstr != "":
                    apstr = apstr + " &amp;&amp; "
                apstr = apstr + cond
2291
            output.write("      <cond>%s</cond>\n"% (apstr))
2292 2293 2294 2295
        try:
            (ret, params, desc) = id.info
            output.write("      <info><![CDATA[%s]]></info>\n" % (desc))
            self.indexString(name, desc)
2296
            if ret[0] is not None:
2297 2298
                if ret[0] == "void":
                    output.write("      <return type='void'/>\n")
A
Andrea Bolognani 已提交
2299
                elif (ret[1] is None or ret[1] == '') and name not in ignored_functions:
2300
                    self.error("Missing documentation for return of function `%s'" % name)
2301 2302 2303 2304 2305 2306 2307
                else:
                    output.write("      <return type='%s' info='%s'/>\n" % (
                             ret[0], escape(ret[1])))
                    self.indexString(name, ret[1])
            for param in params:
                if param[0] == 'void':
                    continue
2308
                if (param[2] is None or param[2] == ''):
A
Andrea Bolognani 已提交
2309
                    if name in ignored_functions:
2310 2311 2312
                        output.write("      <arg name='%s' type='%s' info=''/>\n" % (param[1], param[0]))
                    else:
                        self.error("Missing documentation for arg `%s' of function `%s'" % (param[1], name))
2313 2314 2315 2316
                else:
                    output.write("      <arg name='%s' type='%s' info='%s'/>\n" % (param[1], param[0], escape(param[2])))
                    self.indexString(name, param[2])
        except:
2317
            print("Exception:", sys.exc_info()[1], file=sys.stderr)
2318
            self.warning("Failed to save function %s info: %s" % (name, repr(id.info)))
2319 2320 2321 2322
        output.write("    </%s>\n" % (id.type))

    def serialize_exports(self, output, file):
        module = self.modulename_file(file)
2323 2324
        output.write("    <file name='%s'>\n" % (module))
        dict = self.headers[file]
2325
        if dict.info is not None:
2326 2327 2328 2329 2330 2331 2332
            for data in ('Summary', 'Description', 'Author'):
                try:
                    output.write("     <%s>%s</%s>\n" % (
                                 string.lower(data),
                                 escape(dict.info[data]),
                                 string.lower(data)))
                except:
2333
                    self.warning("Header %s lacks a %s description" % (module, data))
A
Andrea Bolognani 已提交
2334
            if 'Description' in dict.info:
2335
                desc = dict.info['Description']
2336
                if desc.find("DEPRECATED") != -1:
2337
                    output.write("     <deprecated/>\n")
2338

2339
        ids = sorted(dict.macros.keys())
2340 2341
        for id in uniq(ids):
            # Macros are sometime used to masquerade other types.
A
Andrea Bolognani 已提交
2342
            if id in dict.functions:
2343
                continue
A
Andrea Bolognani 已提交
2344
            if id in dict.variables:
2345
                continue
A
Andrea Bolognani 已提交
2346
            if id in dict.typedefs:
2347
                continue
A
Andrea Bolognani 已提交
2348
            if id in dict.structs:
2349
                continue
A
Andrea Bolognani 已提交
2350
            if id in dict.unions:
2351
                continue
A
Andrea Bolognani 已提交
2352
            if id in dict.enums:
2353 2354
                continue
            output.write("     <exports symbol='%s' type='macro'/>\n" % (id))
2355
        ids = sorted(dict.enums.keys())
2356 2357
        for id in uniq(ids):
            output.write("     <exports symbol='%s' type='enum'/>\n" % (id))
2358
        ids = sorted(dict.typedefs.keys())
2359 2360
        for id in uniq(ids):
            output.write("     <exports symbol='%s' type='typedef'/>\n" % (id))
2361
        ids = sorted(dict.structs.keys())
2362 2363
        for id in uniq(ids):
            output.write("     <exports symbol='%s' type='struct'/>\n" % (id))
2364
        ids = sorted(dict.variables.keys())
2365 2366
        for id in uniq(ids):
            output.write("     <exports symbol='%s' type='variable'/>\n" % (id))
2367
        ids = sorted(dict.functions.keys())
2368 2369 2370
        for id in uniq(ids):
            output.write("     <exports symbol='%s' type='function'/>\n" % (id))
        output.write("    </file>\n")
2371 2372

    def serialize_xrefs_files(self, output):
2373
        headers = sorted(self.headers.keys())
2374
        for file in headers:
2375 2376 2377
            module = self.modulename_file(file)
            output.write("    <file name='%s'>\n" % (module))
            dict = self.headers[file]
2378 2379 2380 2381 2382 2383
            ids = uniq(list(dict.functions.keys()) + \
                       list(dict.variables.keys()) + \
                       list(dict.macros.keys()) + \
                       list(dict.typedefs.keys()) + \
                       list(dict.structs.keys()) + \
                       list(dict.enums.keys()))
2384 2385 2386 2387
            ids.sort()
            for id in ids:
                output.write("      <ref name='%s'/>\n" % (id))
            output.write("    </file>\n")
2388 2389 2390 2391
        pass

    def serialize_xrefs_functions(self, output):
        funcs = {}
2392 2393 2394 2395 2396 2397 2398
        for name in self.idx.functions.keys():
            id = self.idx.functions[name]
            try:
                (ret, params, desc) = id.info
                for param in params:
                    if param[0] == 'void':
                        continue
A
Andrea Bolognani 已提交
2399
                    if param[0] in funcs:
2400 2401 2402 2403 2404
                        funcs[param[0]].append(name)
                    else:
                        funcs[param[0]] = [name]
            except:
                pass
2405
        typ = sorted(funcs.keys())
2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418
        for type in typ:
            if type == '' or type == 'void' or type == "int" or \
               type == "char *" or type == "const char *" :
                continue
            output.write("    <type name='%s'>\n" % (type))
            ids = funcs[type]
            ids.sort()
            pid = ''    # not sure why we have dups, but get rid of them!
            for id in ids:
                if id != pid:
                    output.write("      <ref name='%s'/>\n" % (id))
                    pid = id
            output.write("    </type>\n")
2419 2420 2421

    def serialize_xrefs_constructors(self, output):
        funcs = {}
2422 2423 2424 2425 2426 2427
        for name in self.idx.functions.keys():
            id = self.idx.functions[name]
            try:
                (ret, params, desc) = id.info
                if ret[0] == "void":
                    continue
A
Andrea Bolognani 已提交
2428
                if ret[0] in funcs:
2429 2430 2431 2432 2433
                    funcs[ret[0]].append(name)
                else:
                    funcs[ret[0]] = [name]
            except:
                pass
2434
        typ = sorted(funcs.keys())
2435 2436 2437 2438 2439
        for type in typ:
            if type == '' or type == 'void' or type == "int" or \
               type == "char *" or type == "const char *" :
                continue
            output.write("    <type name='%s'>\n" % (type))
2440
            ids = sorted(funcs[type])
2441 2442 2443
            for id in ids:
                output.write("      <ref name='%s'/>\n" % (id))
            output.write("    </type>\n")
2444 2445

    def serialize_xrefs_alpha(self, output):
2446
        letter = None
2447
        ids = sorted(self.idx.identifiers.keys())
2448 2449
        for id in ids:
            if id[0] != letter:
2450
                if letter is not None:
2451 2452 2453 2454
                    output.write("    </letter>\n")
                letter = id[0]
                output.write("    <letter name='%s'>\n" % (letter))
            output.write("      <ref name='%s'/>\n" % (id))
2455
        if letter is not None:
2456
            output.write("    </letter>\n")
2457 2458

    def serialize_xrefs_references(self, output):
2459
        typ = sorted(self.idx.identifiers.keys())
2460 2461 2462 2463 2464 2465 2466
        for id in typ:
            idf = self.idx.identifiers[id]
            module = idf.header
            output.write("    <reference name='%s' href='%s'/>\n" % (id,
                         'html/' + self.basename + '-' +
                         self.modulename_file(module) + '.html#' +
                         id))
2467 2468 2469

    def serialize_xrefs_index(self, output):
        index = self.xref
2470
        typ = sorted(index.keys())
2471 2472 2473 2474 2475 2476 2477 2478
        letter = None
        count = 0
        chunk = 0
        chunks = []
        for id in typ:
            if len(index[id]) > 30:
                continue
            if id[0] != letter:
2479 2480
                if letter is None or count > 200:
                    if letter is not None:
2481 2482 2483 2484 2485 2486 2487
                        output.write("      </letter>\n")
                        output.write("    </chunk>\n")
                        count = 0
                        chunks.append(["chunk%s" % (chunk -1), first_letter, letter])
                    output.write("    <chunk name='chunk%s'>\n" % (chunk))
                    first_letter = id[0]
                    chunk = chunk + 1
2488
                elif letter is not None:
2489 2490 2491 2492
                    output.write("      </letter>\n")
                letter = id[0]
                output.write("      <letter name='%s'>\n" % (letter))
            output.write("        <word name='%s'>\n" % (id))
2493
            tokens = index[id]
2494 2495 2496 2497 2498 2499 2500 2501 2502
            tokens.sort()
            tok = None
            for token in tokens:
                if tok == token:
                    continue
                tok = token
                output.write("          <ref name='%s'/>\n" % (token))
                count = count + 1
            output.write("        </word>\n")
2503
        if letter is not None:
2504 2505 2506 2507 2508 2509 2510 2511 2512
            output.write("      </letter>\n")
            output.write("    </chunk>\n")
            if count != 0:
                chunks.append(["chunk%s" % (chunk -1), first_letter, letter])
            output.write("    <chunks>\n")
            for ch in chunks:
                output.write("      <chunk name='%s' start='%s' end='%s'/>\n" % (
                             ch[0], ch[1], ch[2]))
            output.write("    </chunks>\n")
2513 2514

    def serialize_xrefs(self, output):
2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532
        output.write("  <references>\n")
        self.serialize_xrefs_references(output)
        output.write("  </references>\n")
        output.write("  <alpha>\n")
        self.serialize_xrefs_alpha(output)
        output.write("  </alpha>\n")
        output.write("  <constructors>\n")
        self.serialize_xrefs_constructors(output)
        output.write("  </constructors>\n")
        output.write("  <functions>\n")
        self.serialize_xrefs_functions(output)
        output.write("  </functions>\n")
        output.write("  <files>\n")
        self.serialize_xrefs_files(output)
        output.write("  </files>\n")
        output.write("  <index>\n")
        self.serialize_xrefs_index(output)
        output.write("  </index>\n")
2533 2534

    def serialize(self):
J
Jiri Denemark 已提交
2535
        filename = "%s/%s-api.xml" % (self.path, self.name)
2536
        if not quiet:
2537
            print("Saving XML description %s" % (filename))
2538 2539 2540 2541
        output = open(filename, "w")
        output.write('<?xml version="1.0" encoding="ISO-8859-1"?>\n')
        output.write("<api name='%s'>\n" % self.name)
        output.write("  <files>\n")
2542
        headers = sorted(self.headers.keys())
2543 2544 2545 2546
        for file in headers:
            self.serialize_exports(output, file)
        output.write("  </files>\n")
        output.write("  <symbols>\n")
2547
        macros = sorted(self.idx.macros.keys())
2548 2549
        for macro in macros:
            self.serialize_macro(output, macro)
2550
        enums = sorted(self.idx.enums.keys())
2551 2552
        for enum in enums:
            self.serialize_enum(output, enum)
2553
        typedefs = sorted(self.idx.typedefs.keys())
2554 2555
        for typedef in typedefs:
            self.serialize_typedef(output, typedef)
2556
        variables = sorted(self.idx.variables.keys())
2557 2558
        for variable in variables:
            self.serialize_variable(output, variable)
2559
        functions = sorted(self.idx.functions.keys())
2560 2561 2562 2563 2564 2565
        for function in functions:
            self.serialize_function(output, function)
        output.write("  </symbols>\n")
        output.write("</api>\n")
        output.close()

2566
        if self.errors > 0:
2567
            print("apibuild.py: %d error(s) encountered during generation" % self.errors, file=sys.stderr)
2568 2569
            sys.exit(3)

J
Jiri Denemark 已提交
2570
        filename = "%s/%s-refs.xml" % (self.path, self.name)
2571
        if not quiet:
2572
            print("Saving XML Cross References %s" % (filename))
2573 2574 2575 2576 2577 2578 2579 2580
        output = open(filename, "w")
        output.write('<?xml version="1.0" encoding="ISO-8859-1"?>\n')
        output.write("<apirefs name='%s'>\n" % self.name)
        self.serialize_xrefs(output)
        output.write("</apirefs>\n")
        output.close()


A
Andrea Bolognani 已提交
2581 2582 2583 2584
class app:
    def warning(self, msg):
        global warnings
        warnings = warnings + 1
2585
        print(msg)
A
Andrea Bolognani 已提交
2586 2587 2588

    def rebuild(self, name):
        if name not in ["libvirt", "libvirt-qemu", "libvirt-lxc", "libvirt-admin"]:
A
Andrea Bolognani 已提交
2589
            self.warning("rebuild() failed, unknown module %s" % name)
A
Andrea Bolognani 已提交
2590 2591 2592 2593 2594 2595 2596 2597
            return None
        builder = None
        srcdir = os.path.abspath((os.environ["srcdir"]))
        builddir = os.path.abspath((os.environ["builddir"]))
        if srcdir == builddir:
            builddir = None
        if glob.glob(srcdir + "/../src/libvirt.c") != [] :
            if not quiet:
2598
                print("Rebuilding API description for %s" % name)
A
Andrea Bolognani 已提交
2599 2600 2601
            dirs = [srcdir + "/../src",
                    srcdir + "/../src/util",
                    srcdir + "/../include/libvirt"]
2602 2603
            if (builddir and
                not os.path.exists(srcdir + "/../include/libvirt/libvirt-common.h")):
A
Andrea Bolognani 已提交
2604 2605 2606 2607
                dirs.append(builddir + "/../include/libvirt")
            builder = docBuilder(name, srcdir, dirs, [])
        elif glob.glob("src/libvirt.c") != [] :
            if not quiet:
2608
                print("Rebuilding API description for %s" % name)
A
Andrea Bolognani 已提交
2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626
            builder = docBuilder(name, srcdir,
                                 ["src", "src/util", "include/libvirt"],
                                 [])
        else:
            self.warning("rebuild() failed, unable to guess the module")
            return None
        builder.scan()
        builder.analyze()
        builder.serialize()
        return builder

    #
    # for debugging the parser
    #
    def parse(self, filename):
        parser = CParser(filename)
        idx = parser.parse()
        return idx
2627 2628 2629


if __name__ == "__main__":
A
Andrea Bolognani 已提交
2630
    app = app()
2631 2632
    if len(sys.argv) > 1:
        debug = 1
A
Andrea Bolognani 已提交
2633
        app.parse(sys.argv[1])
2634
    else:
A
Andrea Bolognani 已提交
2635 2636 2637 2638
        app.rebuild("libvirt")
        app.rebuild("libvirt-qemu")
        app.rebuild("libvirt-lxc")
        app.rebuild("libvirt-admin")
2639 2640 2641 2642
    if warnings > 0:
        sys.exit(2)
    else:
        sys.exit(0)