xref: /openbmc/qemu/scripts/qapi/source.py (revision 69430111)
1#
2# QAPI frontend source file info
3#
4# Copyright (c) 2019 Red Hat Inc.
5#
6# Authors:
7#  Markus Armbruster <armbru@redhat.com>
8#
9# This work is licensed under the terms of the GNU GPL, version 2.
10# See the COPYING file in the top-level directory.
11
12import copy
13import sys
14from typing import List, Optional, TypeVar
15
16
17class QAPISchemaPragma:
18    # Replace with @dataclass in Python 3.7+
19    # pylint: disable=too-few-public-methods
20
21    def __init__(self) -> None:
22        # Are documentation comments required?
23        self.doc_required = False
24        # Whitelist of commands allowed to return a non-dictionary
25        self.returns_whitelist: List[str] = []
26        # Whitelist of entities allowed to violate case conventions
27        self.name_case_whitelist: List[str] = []
28
29
30class QAPISourceInfo:
31    T = TypeVar('T', bound='QAPISourceInfo')
32
33    def __init__(self, fname: str, line: int,
34                 parent: Optional['QAPISourceInfo']):
35        self.fname = fname
36        self.line = line
37        self.parent = parent
38        self.pragma: QAPISchemaPragma = (
39            parent.pragma if parent else QAPISchemaPragma()
40        )
41        self.defn_meta: Optional[str] = None
42        self.defn_name: Optional[str] = None
43
44    def set_defn(self, meta: str, name: str) -> None:
45        self.defn_meta = meta
46        self.defn_name = name
47
48    def next_line(self: T) -> T:
49        info = copy.copy(self)
50        info.line += 1
51        return info
52
53    def loc(self) -> str:
54        if self.fname is None:
55            return sys.argv[0]
56        ret = self.fname
57        if self.line is not None:
58            ret += ':%d' % self.line
59        return ret
60
61    def in_defn(self) -> str:
62        if self.defn_name:
63            return "%s: In %s '%s':\n" % (self.fname,
64                                          self.defn_meta, self.defn_name)
65        return ''
66
67    def include_path(self) -> str:
68        ret = ''
69        parent = self.parent
70        while parent:
71            ret = 'In file included from %s:\n' % parent.loc() + ret
72            parent = parent.parent
73        return ret
74
75    def __str__(self) -> str:
76        return self.include_path() + self.in_defn() + self.loc()
77