Skip to contentSkip to conversation

kconfig cleanups and mypy annotations

PATCH In review Paolo Bonzini 4 participants 19 messages Apr 30 – May 1 RISC-V

lore
Share & tools
lore
#0 lore raw

cover kconfig cleanups and mypy annotations

Modernize the code a bit and fix some issues that were found while adding mypy annotations to minikconf.

While this stops short of adding flake8 and pylint, it already improves the style and fixes a bug (see patches 1-2).

Paolo Bonzini (13):
kconfig: remove duplicate declaration of CONFIG_CXL
kconfig: remove duplicate declaration of CONFIG_MIPS_BOSTON_AIA
minikconf: run through isort
minikconf: small cleanups and dead code removal
minikconf: move command-line assignment out of the parser
minikconf: fix type mismatch in do_declaration
minikconf: simplify self.tok
minikconf: modernize handling of include chain
minikconf: use .items()
minikconf: pull main program into a function
minikconf: remove unnecessary semicolons
minikconf: replace else with early return and avoid unnecessary else
minikconf: add mypy annotations

 hw/Kconfig              |   1 -
 hw/cxl/Kconfig          |   3 -
 hw/misc/Kconfig         |   8 -
 hw/riscv/Kconfig        |   4 +
 python/tests/linters.py |   6 +
 scripts/minikconf.py    | 465 +++++++++++++++++++++-------------------
 6 files changed, 254 insertions(+), 233 deletions(-)
 delete mode 100644 hw/cxl/Kconfig
Signature · 1 line
2.54.0
#1 lore raw

PATCH 1/13 kconfig: remove duplicate declaration of CONFIG_CXL

---
 hw/Kconfig     | 1 -
 hw/cxl/Kconfig | 3 ---
 2 files changed, 4 deletions(-)
 delete mode 100644 hw/cxl/Kconfig
hw/Kconfig +0 -1
index b3ed092f7a8..c109f5537b2 100644
@@ -6,7 +6,6 @@ source audio/Kconfig
 source block/Kconfig
 source char/Kconfig
 source core/Kconfig
-source cxl/Kconfig
 source display/Kconfig
 source dma/Kconfig
 source fsi/Kconfig
hw/cxl/Kconfig deleted +0 -3
deleted file mode 100644
index 8e67519b161..00000000000
@@ -1,3 +0,0 @@
-config CXL
-    bool
-    default y if PCI_EXPRESS
Signature · 1 line
2.54.0
#2 lore raw

PATCH 2/13 kconfig: remove duplicate declaration of CONFIG_MIPS_BOSTON_AIA

In reply to Paolo Bonzini
---
 hw/misc/Kconfig  | 8 --------
 hw/riscv/Kconfig | 4 ++++
 2 files changed, 4 insertions(+), 8 deletions(-)
hw/misc/Kconfig +0 -8
index f4d49248c08..99bdf09219a 100644
@@ -135,14 +135,6 @@ config RISCV_MIPS_CPC
 config RISCV_MIPS_CPS
     bool
 
-config MIPS_BOSTON_AIA
-    bool
-    default y
-    depends on RISCV64
-    select RISCV_MIPS_CMGCR
-    select RISCV_MIPS_CPC
-    select RISCV_MIPS_CPS
-
 config MPS2_FPGAIO
     bool
     select LED
hw/riscv/Kconfig +4 -0
index 0222c93f878..2518b04175f 100644
@@ -132,5 +132,9 @@ config XIANGSHAN_KUNMINGHU
 config MIPS_BOSTON_AIA
     bool
     default y
+    depends on RISCV64
     select PCI_EXPRESS
     select PCI_EXPRESS_XILINX
+    select RISCV_MIPS_CMGCR
+    select RISCV_MIPS_CPC
+    select RISCV_MIPS_CPS
Signature · 1 line
2.54.0
Reviewed-by on v1 2/13
#3 lore raw

Re: [PATCH 02/13] kconfig: remove duplicate declaration of CONFIG_MIPS_BOSTON_AIA

Quoted 12 lines · Paolo Bonzini
---
  hw/misc/Kconfig  | 8 --------
  hw/riscv/Kconfig | 4 ++++
  2 files changed, 4 insertions(+), 8 deletions(-)
hw/riscv/Kconfig +0 -0
index 0222c93f878..2518b04175f 100644

hw/riscv/Kconfig config XIANGSHAN_KUNMINGHU · line 134

Quoted 3 lines
hw/riscv/Kconfig +0 -0
@@ -132,5 +132,9 @@ config XIANGSHAN_KUNMINGHU
  config MIPS_BOSTON_AIA
      bool
      default y

Pre-existing but 'default y' unlikely needed.

Quoted 6 lines
hw/riscv/Kconfig +4 -0
+    depends on RISCV64
      select PCI_EXPRESS
      select PCI_EXPRESS_XILINX
+    select RISCV_MIPS_CMGCR
+    select RISCV_MIPS_CPC
+    select RISCV_MIPS_CPS
Reviewed-by on v1 2/13
#4 lore raw

Re: [PATCH 02/13] kconfig: remove duplicate declaration of CONFIG_MIPS_BOSTON_AIA

In reply to Paolo Bonzini
Quoted 2 lines · Paolo Bonzini

Alistair

Quoted 42 lines
---
 hw/misc/Kconfig  | 8 --------
 hw/riscv/Kconfig | 4 ++++
 2 files changed, 4 insertions(+), 8 deletions(-)
hw/misc/Kconfig +0 -8
index f4d49248c08..99bdf09219a 100644
@@ -135,14 +135,6 @@ config RISCV_MIPS_CPC
 config RISCV_MIPS_CPS
     bool
 
-config MIPS_BOSTON_AIA
-    bool
-    default y
-    depends on RISCV64
-    select RISCV_MIPS_CMGCR
-    select RISCV_MIPS_CPC
-    select RISCV_MIPS_CPS
-
 config MPS2_FPGAIO
     bool
     select LED
hw/riscv/Kconfig +4 -1
index 0222c93f878..2518b04175f 100644
@@ -132,5 +132,9 @@ config XIANGSHAN_KUNMINGHU
 config MIPS_BOSTON_AIA
     bool
     default y
+    depends on RISCV64
     select PCI_EXPRESS
     select PCI_EXPRESS_XILINX
+    select RISCV_MIPS_CMGCR
+    select RISCV_MIPS_CPC
+    select RISCV_MIPS_CPS
--

2.54.0

#5 lore raw

PATCH 3/13 minikconf: run through isort

In reply to Paolo Bonzini
---
 python/tests/linters.py | 3 +++
 scripts/minikconf.py    | 4 ++--
 2 files changed, 5 insertions(+), 2 deletions(-)
python/tests/linters.py +3 -0
index 9696c0b71b8..4ce4e8a9805 100644
@@ -25,6 +25,9 @@ def test_flake8_qapi(self):
             ]
         )
 
+    def test_isort_minikconf(self):
+        check_call([sys.executable, "-m", "isort", "-c", "../scripts/minikconf.py"])
+
     def test_isort_pkg(self):
         check_call([sys.executable, "-m", "isort", "-c", "qemu/"])
 
scripts/minikconf.py +2 -2
index 4de5aeed11a..24389763db0 100644
@@ -12,9 +12,9 @@
 # the top-level directory.
 
 import os
-import sys
-import re
 import random
+import re
+import sys
 
 __all__ = [ 'KconfigDataError', 'KconfigParserError',
             'KconfigData', 'KconfigParser' ,
Signature · 1 line
2.54.0
#6 lore raw

PATCH 4/13 minikconf: small cleanups and dead code removal

In reply to Paolo Bonzini
---
 scripts/minikconf.py | 21 ++++++++++-----------
 1 file changed, 10 insertions(+), 11 deletions(-)
scripts/minikconf.py +10 -11
index 24389763db0..08df8d5dabb 100644
@@ -108,7 +108,7 @@ def __str__(self):
             return self.name
 
         def has_value(self):
-            return not (self.value is None)
+            return self.value is not None
         def set_value(self, val, clause):
             self.clauses_for_var.append(clause)
             if self.has_value() and self.value != val:
@@ -158,7 +158,7 @@ def __init__(self, dest, value, cond=None):
             KconfigData.Clause.__init__(self, dest)
             self.value = value
             self.cond = cond
-            if not (self.cond is None):
+            if self.cond is not None:
                 self.cond.add_edges_to(self.dest)
         def __str__(self):
             value = 'y' if self.value else 'n'
@@ -212,7 +212,7 @@ def __init__(self, value_mangler=defconfig):
     def check_undefined(self):
         undef = False
         for i in self.referenced_vars:
-            if not (i in self.defined_vars):
+            if i not in self.defined_vars:
                 print("undefined symbol %s" % (i), file=sys.stderr)
                 undef = True
         return undef
@@ -220,7 +220,6 @@ def check_undefined(self):
     def compute_config(self):
         if self.check_undefined():
             raise KconfigDataError("there were undefined symbols")
-            return None
 
         debug_print("Input:")
         for clause in self.clauses:
@@ -270,7 +269,7 @@ def do_declaration(self, var):
 
     # var is a string with the variable's name.
     def do_var(self, var):
-        if (var in self.referenced_vars):
+        if var in self.referenced_vars:
             return self.referenced_vars[var]
 
         var_obj = self.referenced_vars[var] = KconfigData.Var(var)
@@ -339,9 +338,9 @@ def __str__(self):
 class KconfigParser:
 
     @classmethod
-    def parse(self, fp, mode=None):
+    def parse(cls, fp, mode=None):
         data = KconfigData(mode or defconfig)
-        parser = KconfigParser(data)
+        parser = cls(data)
         parser.parse_file(fp)
         return data
 
@@ -352,9 +351,10 @@ def parse_file(self, fp):
         self.abs_fname = os.path.abspath(fp.name)
         self.fname = fp.name
         self.data.previously_included.append(self.abs_fname)
-        self.src = fp.read()
-        if self.src == '' or self.src[-1] != '\n':
-            self.src += '\n'
+        src = fp.read()
+        if src == '' or src[-1] != '\n':
+            src += '\n'
+        self.src = src
         self.cursor = 0
         self.line = 1
         self.line_pos = 0
@@ -534,7 +534,6 @@ def parse_property(self, var):
     # properties: properties property
     #       | /* empty */
     def parse_properties(self, var):
-        had_default = False
         while self.tok == TOK_DEFAULT or self.tok == TOK_DEPENDS or \
               self.tok == TOK_SELECT or self.tok == TOK_BOOL or \
               self.tok == TOK_IMPLY:
Signature · 1 line
2.54.0
#7 lore raw

PATCH 5/13 minikconf: move command-line assignment out of the parser

In reply to Paolo Bonzini

KconfigParser.do_assignment() only exists to handle CONFIG_FOO=y/n arguments from the command line; it is never invoked while parsing a Kconfig source file. Because main() called it on a parser that had never been through parse_file(), a failing CONFIG_ check would raise a KconfigParserError whose __init__ and location() touch fields of "self" that do not exist yet. The regex in main() currently shields this, but it is fragile.

Move the prefix-stripping assignment to KconfigData as do_cmdline_assignment(), simplify KconfigParser.parse() to accept an existing KconfigData, and call it from main() so the parser is only used for actual file parsing.

---
 scripts/minikconf.py | 27 +++++++++------------------
 1 file changed, 9 insertions(+), 18 deletions(-)
scripts/minikconf.py +9 -18
index 08df8d5dabb..668de577d09 100644
@@ -278,6 +278,10 @@ def do_var(self, var):
     def do_assignment(self, var, val):
         self.clauses.append(KconfigData.AssignmentClause(var, val))
 
+    def do_cmdline_assignment(self, var, val):
+        assert var.startswith("CONFIG_")
+        self.do_assignment(self.do_var(var[7:]), val)
+
     def do_default(self, var, val, cond=None):
         val = self.value_mangler(val)
         self.clauses.append(KconfigData.DefaultClause(var, val, cond))
@@ -338,11 +342,8 @@ def __str__(self):
 class KconfigParser:
 
     @classmethod
-    def parse(cls, fp, mode=None):
-        data = KconfigData(mode or defconfig)
-        parser = cls(data)
-        parser.parse_file(fp)
-        return data
+    def parse(cls, fp, data):
+        cls(data).parse_file(fp)
 
     def __init__(self, data):
         self.data = data
@@ -361,14 +362,6 @@ def parse_file(self, fp):
         self.get_token()
         self.parse_config()
 
-    def do_assignment(self, var, val):
-        if not var.startswith("CONFIG_"):
-            raise KconfigParserError(
-                self, "assigned variable should start with CONFIG_"
-            )
-        var = self.data.do_var(var[7:])
-        self.data.do_assignment(var, val)
-
     # file management -----
 
     def error_path(self):
@@ -688,18 +681,16 @@ def scan_token(self):
         sys.exit(1)
 
     data = KconfigData(mode)
-    parser = KconfigParser(data)
     external_vars = set()
     for arg in argv[3:]:
         m = re.match(r'^(CONFIG_[A-Z0-9_]+)=([yn]?)$', arg)
         if m is not None:
             name, value = m.groups()
-            parser.do_assignment(name, value == 'y')
+            data.do_cmdline_assignment(name, value == 'y')
             external_vars.add(name[7:])
         else:
-            fp = open(arg, 'rt', encoding='utf-8')
-            parser.parse_file(fp)
-            fp.close()
+            with open(arg, 'rt', encoding='utf-8') as fp:
+                KconfigParser.parse(fp, data)
 
     config = data.compute_config()
     for key in sorted(config.keys()):
Signature · 1 line
2.54.0
#8 lore raw

PATCH 6/13 minikconf: fix type mismatch in do_declaration

In reply to Paolo Bonzini

The set stores strings, not Vars. Because of this the duplicate definition check did not work.

---
 scripts/minikconf.py | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
scripts/minikconf.py +2 -2
index 668de577d09..2656d364920 100644
@@ -262,8 +262,8 @@ def visit_fn(var):
     # semantic actions -------------
 
     def do_declaration(self, var):
-        if (var in self.defined_vars):
-            raise KconfigDataError('variable "' + var + '" defined twice')
+        if var.name in self.defined_vars:
+            raise KconfigDataError('variable "%s" defined twice' % var.name)
 
         self.defined_vars.add(var.name)
 
Signature · 1 line
2.54.0
#9 lore raw

PATCH 7/13 minikconf: simplify self.tok

In reply to Paolo Bonzini

Do not ever store a string in self.tok, only a finished token.

---
 scripts/minikconf.py | 59 ++++++++++++++++++++++----------------------
 1 file changed, 30 insertions(+), 29 deletions(-)
scripts/minikconf.py +30 -29
index 2656d364920..3d63cc6b21f 100644
@@ -330,9 +330,9 @@ def do_imply(self, var, symbol, cond=None):
 class KconfigParserError(Exception):
     def __init__(self, parser, msg, tok=None):
         self.loc = parser.location()
-        tok = tok or parser.tok
+        tok = tok if tok is not None else parser.tok
         if tok != TOK_NONE:
-            location = TOKENS.get(tok, None) or ('"%s"' % tok)
+            location = TOKENS[tok] if isinstance(tok, int) else '"%s"' % tok
             msg = '%s before %s' % (msg, location)
         self.msg = msg
 
@@ -573,13 +573,14 @@ def parse_config(self):
 
     def get_token(self):
         while True:
-            self.tok = self.src[self.cursor]
+            ch = self.src[self.cursor]
             self.pos = self.cursor
             self.cursor += 1
 
             self.val = None
-            self.tok = self.scan_token()
-            if self.tok is not None:
+            tok = self.scan_token(ch)
+            if tok is not None:
+                self.tok = tok
                 return
 
     def check_keyword(self, rest):
@@ -591,46 +592,46 @@ def check_keyword(self, rest):
         self.cursor += length
         return True
 
-    def scan_token(self):
-        if self.tok == '#':
+    def scan_token(self, ch):
+        if ch == '#':
             self.cursor = self.src.find('\n', self.cursor)
             return None
-        elif self.tok == '=':
+        elif ch == '=':
             return TOK_EQUAL
-        elif self.tok == '(':
+        elif ch == '(':
             return TOK_LPAREN
-        elif self.tok == ')':
+        elif ch == ')':
             return TOK_RPAREN
-        elif self.tok == '&' and self.src[self.pos+1] == '&':
+        elif ch == '&' and self.src[self.pos+1] == '&':
             self.cursor += 1
             return TOK_AND
-        elif self.tok == '|' and self.src[self.pos+1] == '|':
+        elif ch == '|' and self.src[self.pos+1] == '|':
             self.cursor += 1
             return TOK_OR
-        elif self.tok == '!':
+        elif ch == '!':
             return TOK_NOT
-        elif self.tok == 'd' and self.check_keyword("epends"):
+        elif ch == 'd' and self.check_keyword("epends"):
             return TOK_DEPENDS
-        elif self.tok == 'o' and self.check_keyword("n"):
+        elif ch == 'o' and self.check_keyword("n"):
             return TOK_ON
-        elif self.tok == 's' and self.check_keyword("elect"):
+        elif ch == 's' and self.check_keyword("elect"):
             return TOK_SELECT
-        elif self.tok == 'i' and self.check_keyword("mply"):
+        elif ch == 'i' and self.check_keyword("mply"):
             return TOK_IMPLY
-        elif self.tok == 'c' and self.check_keyword("onfig"):
+        elif ch == 'c' and self.check_keyword("onfig"):
             return TOK_CONFIG
-        elif self.tok == 'd' and self.check_keyword("efault"):
+        elif ch == 'd' and self.check_keyword("efault"):
             return TOK_DEFAULT
-        elif self.tok == 'b' and self.check_keyword("ool"):
+        elif ch == 'b' and self.check_keyword("ool"):
             return TOK_BOOL
-        elif self.tok == 'i' and self.check_keyword("f"):
+        elif ch == 'i' and self.check_keyword("f"):
             return TOK_IF
-        elif self.tok == 'y' and self.check_keyword(""):
+        elif ch == 'y' and self.check_keyword(""):
             return TOK_Y
-        elif self.tok == 'n' and self.check_keyword(""):
+        elif ch == 'n' and self.check_keyword(""):
             return TOK_N
-        elif (self.tok == 's' and self.check_keyword("ource")) or \
-              self.tok == 'i' and self.check_keyword("nclude"):
+        elif (ch == 's' and self.check_keyword("ource")) or \
+              ch == 'i' and self.check_keyword("nclude"):
             # source FILENAME
             # include FILENAME
             while self.src[self.cursor].isspace():
@@ -639,19 +640,19 @@ def scan_token(self):
             self.cursor = self.src.find('\n', self.cursor)
             self.val = self.src[start:self.cursor]
             return TOK_SOURCE
-        elif self.tok.isalnum():
+        elif ch.isalnum():
             # identifier
             while self.src[self.cursor].isalnum() or self.src[self.cursor] == '_':
                 self.cursor += 1
             self.val = self.src[self.pos:self.cursor]
             return TOK_ID
-        elif self.tok == '\n':
+        elif ch == '\n':
             if self.cursor == len(self.src):
                 return TOK_EOF
             self.line += 1
             self.line_pos = self.cursor
-        elif not self.tok.isspace():
-            raise KconfigParserError(self, 'invalid input')
+        elif not ch.isspace():
+            raise KconfigParserError(self, 'invalid input', ch)
 
         return None
 
Signature · 1 line
2.54.0
#10 lore raw

PATCH 8/13 minikconf: modernize handling of include chain

In reply to Paolo Bonzini

Use a dataclass, and store it in the parser to avoid having to save and restore it.

---
 scripts/minikconf.py | 66 +++++++++++++++++++++++++-------------------
 1 file changed, 37 insertions(+), 29 deletions(-)
scripts/minikconf.py +37 -29
index 3d63cc6b21f..07a5152ef54 100644
@@ -15,11 +15,30 @@
 import random
 import re
 import sys
+from dataclasses import dataclass
 
 __all__ = [ 'KconfigDataError', 'KconfigParserError',
             'KconfigData', 'KconfigParser' ,
             'defconfig', 'allyesconfig', 'allnoconfig', 'randconfig' ]
 
+@dataclass
+class IncludeInfo:
+    file: str
+    line: int
+    parent: IncludeInfo | None
+
+    def __iter__(self):
+        inf = self
+        while inf is not None:
+            yield "%s:%d" % (inf.file, inf.line)
+            inf = inf.parent
+
+    def error_path(self):
+        res = ""
+        for loc in self:
+            res = "In file included from %s:\n" % loc + res
+        return res
+
 def debug_print(*args):
     #print('# ' + (' '.join(str(x) for x in args)))
     pass
@@ -202,7 +221,6 @@ def process(self):
     def __init__(self, value_mangler=defconfig):
         self.value_mangler = value_mangler
         self.previously_included = []
-        self.incl_info = None
         self.defined_vars = set()
         self.referenced_vars = dict()
         self.clauses = list()
@@ -342,13 +360,12 @@ def __str__(self):
 class KconfigParser:
 
     @classmethod
-    def parse(cls, fp, data):
-        cls(data).parse_file(fp)
+    def parse(cls, fp, data, incl_info=None):
+        cls(fp, data, incl_info).parse_config()
 
-    def __init__(self, data):
+    def __init__(self, fp, data, incl_info):
         self.data = data
-
-    def parse_file(self, fp):
+        self.incl_info = incl_info
         self.abs_fname = os.path.abspath(fp.name)
         self.fname = fp.name
         self.data.previously_included.append(self.abs_fname)
@@ -360,19 +377,9 @@ def parse_file(self, fp):
         self.line = 1
         self.line_pos = 0
         self.get_token()
-        self.parse_config()
 
     # file management -----
 
-    def error_path(self):
-        inf = self.data.incl_info
-        res = ""
-        while inf:
-            res = ("In file included from %s:%d:\n" % (inf['file'],
-                                                       inf['line'])) + res
-            inf = inf['parent']
-        return res
-
     def location(self):
         col = 1
         for ch in self.src[self.line_pos:self.pos]:
@@ -380,33 +387,34 @@ def location(self):
                 col += 8 - ((col - 1) % 8)
             else:
                 col += 1
-        return '%s%s:%d:%d' %(self.error_path(), self.fname, self.line, col)
+        inf = self.incl_info
+        incl_chain = inf.error_path() if inf is not None else ""
+        return '%s%s:%d:%d' % (incl_chain, self.fname, self.line, col)
 
     def do_include(self, include):
         incl_abs_fname = os.path.join(os.path.dirname(self.abs_fname),
                                       include)
         # catch inclusion cycle
-        inf = self.data.incl_info
+        inf = self.incl_info
         while inf:
-            if incl_abs_fname == os.path.abspath(inf['file']):
+            if incl_abs_fname == os.path.abspath(inf.file):
                 raise KconfigParserError(self, "Inclusion loop for %s"
                                     % include)
-            inf = inf['parent']
+            inf = inf.parent
 
         # skip multiple include of the same file
         if incl_abs_fname in self.data.previously_included:
             return
         try:
-            fp = open(incl_abs_fname, 'rt', encoding='utf-8')
-        except IOError as e:
-            raise KconfigParserError(self,
-                                '%s: %s' % (e.strerror, include))
+            try:
+                fp = open(incl_abs_fname, 'rt', encoding='utf-8')
+            except IOError as e:
+                raise KconfigParserError(self, '%s: %s' % (e.strerror, include))
 
-        inf = self.data.incl_info
-        self.data.incl_info = { 'file': self.fname, 'line': self.line,
-                'parent': inf }
-        KconfigParser(self.data).parse_file(fp)
-        self.data.incl_info = inf
+            inner = IncludeInfo(file=self.fname, line=self.line, parent=self.incl_info)
+            type(self).parse(fp, self.data, inner)
+        finally:
+            fp.close()
 
     # recursive descent parser -----
 
Signature · 1 line
2.54.0
#11 lore raw

Re: [PATCH 08/13] minikconf: modernize handling of include chain

Quoted 9 lines · Paolo Bonzini
scripts/minikconf.py +1 -0
index 3d63cc6b21f..07a5152ef54 100644
@@ -15,11 +15,30 @@
 import random
 import re
 import sys
+from dataclasses import dataclass

scripts/minikconf.py line 28

Quoted 10 lines
scripts/minikconf.py +5 -0
 
 __all__ = [ 'KconfigDataError', 'KconfigParserError',
             'KconfigData', 'KconfigParser' ,
             'defconfig', 'allyesconfig', 'allnoconfig', 'randconfig' ]
 
+@dataclass
+class IncludeInfo:
+    file: str
+    line: int
+    parent: IncludeInfo | None

Add from __future__ import annotations with this patch or add the annotations with patch 13?

Signature · 1 line
Marc-André Lureau <[email protected]>
#12 lore raw

Re: [PATCH 08/13] minikconf: modernize handling of include chain

Quoted 16 lines · On Thu, Apr 30, 2026 at 12:35 PM <[email protected]> wrote:
Quoted 14 lines · Paolo Bonzini
scripts/minikconf.py +1 -0
index 3d63cc6b21f..07a5152ef54 100644
@@ -15,11 +15,30 @@
 import random
 import re
 import sys
+from dataclasses import dataclass
 
 __all__ = [ 'KconfigDataError', 'KconfigParserError',
             'KconfigData', 'KconfigParser' ,
             'defconfig', 'allyesconfig', 'allnoconfig', 'randconfig' ]
 
Quoted 7 lines

scripts/minikconf.py line 28

Quoted 5 lines
scripts/minikconf.py +5 -0
+@dataclass
+class IncludeInfo:
+    file: str
+    line: int
+    parent: IncludeInfo | None

Add from __future__ import annotations with this patch or add the annotations with patch 13?

Yes, I will move them.

Paolo

#13 lore raw

PATCH 9/13 minikconf: use .items()

In reply to Paolo Bonzini
---
 scripts/minikconf.py | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
scripts/minikconf.py +2 -2
index 07a5152ef54..0806a92c14d 100644
@@ -244,8 +244,8 @@ def compute_config(self):
             debug_print(clause)
 
         debug_print("\nDependency graph:")
-        for i in self.referenced_vars:
-            debug_print(i, "->", [str(x) for x in self.referenced_vars[i].outgoing])
+        for source, edges in self.referenced_vars.items():
+            debug_print(source, "->", [str(x) for x in edges.outgoing])
 
         # The reverse of the depth-first order is the topological sort
         dfo = dict()
Signature · 1 line
2.54.0
#14 lore raw

PATCH 10/13 minikconf: pull main program into a function

In reply to Paolo Bonzini

Avoid pulluting the global namespace.

---
 scripts/minikconf.py | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
scripts/minikconf.py +4 -1
index 0806a92c14d..e14b80e3ae7 100644
@@ -664,7 +664,7 @@ def scan_token(self, ch):
 
         return None
 
-if __name__ == '__main__':
+def main():
     argv = sys.argv
     mode = defconfig
     if len(sys.argv) > 1:
@@ -710,3 +710,6 @@ def scan_token(self, ch):
     for fname in data.previously_included:
         print ('%s: %s' % (argv[1], fname), file=deps)
     deps.close()
+
+if __name__ == '__main__':
+    main()
Signature · 1 line
2.54.0
#15 lore raw

PATCH 11/13 minikconf: remove unnecessary semicolons

In reply to Paolo Bonzini
---
 scripts/minikconf.py | 38 +++++++++++++++++++-------------------
 1 file changed, 19 insertions(+), 19 deletions(-)
scripts/minikconf.py +19 -19
index e14b80e3ae7..5fb42c8f760 100644
@@ -325,25 +325,25 @@ def do_imply(self, var, symbol, cond=None):
 # tokens table
 TOKENS = {}
 TOK_NONE = -1
-TOK_LPAREN = 0;   TOKENS[TOK_LPAREN] = '"("';
-TOK_RPAREN = 1;   TOKENS[TOK_RPAREN] = '")"';
-TOK_EQUAL = 2;    TOKENS[TOK_EQUAL] = '"="';
-TOK_AND = 3;      TOKENS[TOK_AND] = '"&&"';
-TOK_OR = 4;       TOKENS[TOK_OR] = '"||"';
-TOK_NOT = 5;      TOKENS[TOK_NOT] = '"!"';
-TOK_DEPENDS = 6;  TOKENS[TOK_DEPENDS] = '"depends"';
-TOK_ON = 7;       TOKENS[TOK_ON] = '"on"';
-TOK_SELECT = 8;   TOKENS[TOK_SELECT] = '"select"';
-TOK_IMPLY = 9;    TOKENS[TOK_IMPLY] = '"imply"';
-TOK_CONFIG = 10;  TOKENS[TOK_CONFIG] = '"config"';
-TOK_DEFAULT = 11; TOKENS[TOK_DEFAULT] = '"default"';
-TOK_Y = 12;       TOKENS[TOK_Y] = '"y"';
-TOK_N = 13;       TOKENS[TOK_N] = '"n"';
-TOK_SOURCE = 14;  TOKENS[TOK_SOURCE] = '"source"';
-TOK_BOOL = 15;    TOKENS[TOK_BOOL] = '"bool"';
-TOK_IF = 16;      TOKENS[TOK_IF] = '"if"';
-TOK_ID = 17;      TOKENS[TOK_ID] = 'identifier';
-TOK_EOF = 18;     TOKENS[TOK_EOF] = 'end of file';
+TOK_LPAREN = 0;   TOKENS[TOK_LPAREN] = '"("'
+TOK_RPAREN = 1;   TOKENS[TOK_RPAREN] = '")"'
+TOK_EQUAL = 2;    TOKENS[TOK_EQUAL] = '"="'
+TOK_AND = 3;      TOKENS[TOK_AND] = '"&&"'
+TOK_OR = 4;       TOKENS[TOK_OR] = '"||"'
+TOK_NOT = 5;      TOKENS[TOK_NOT] = '"!"'
+TOK_DEPENDS = 6;  TOKENS[TOK_DEPENDS] = '"depends"'
+TOK_ON = 7;       TOKENS[TOK_ON] = '"on"'
+TOK_SELECT = 8;   TOKENS[TOK_SELECT] = '"select"'
+TOK_IMPLY = 9;    TOKENS[TOK_IMPLY] = '"imply"'
+TOK_CONFIG = 10;  TOKENS[TOK_CONFIG] = '"config"'
+TOK_DEFAULT = 11; TOKENS[TOK_DEFAULT] = '"default"'
+TOK_Y = 12;       TOKENS[TOK_Y] = '"y"'
+TOK_N = 13;       TOKENS[TOK_N] = '"n"'
+TOK_SOURCE = 14;  TOKENS[TOK_SOURCE] = '"source"'
+TOK_BOOL = 15;    TOKENS[TOK_BOOL] = '"bool"'
+TOK_IF = 16;      TOKENS[TOK_IF] = '"if"'
+TOK_ID = 17;      TOKENS[TOK_ID] = 'identifier'
+TOK_EOF = 18;     TOKENS[TOK_EOF] = 'end of file'
 
 class KconfigParserError(Exception):
     def __init__(self, parser, msg, tok=None):
Signature · 1 line
2.54.0
#16 lore raw

PATCH 12/13 minikconf: replace else with early return and avoid unnecessary else

In reply to Paolo Bonzini
---
 scripts/minikconf.py | 79 ++++++++++++++++++++++----------------------
 1 file changed, 40 insertions(+), 39 deletions(-)
scripts/minikconf.py +40 -39
index 5fb42c8f760..7a2fe865484 100644
@@ -430,24 +430,24 @@ def parse_y_or_n(self):
 
     # var: ID
     def parse_var(self):
-        if self.tok == TOK_ID:
-            val = self.val
-            self.get_token()
-            return self.data.do_var(val)
-        else:
+        if self.tok != TOK_ID:
             raise KconfigParserError(self, 'Expected identifier')
+        val = self.val
+        assert val is not None
+        self.get_token()
+        return self.data.do_var(val)
 
     # assignment_var: ID (starting with "CONFIG_")
     def parse_assignment_var(self):
-        if self.tok == TOK_ID:
-            val = self.val
-            if not val.startswith("CONFIG_"):
-                raise KconfigParserError(self,
-                           'Expected identifier starting with "CONFIG_"', TOK_NONE)
-            self.get_token()
-            return self.data.do_var(val[7:])
-        else:
+        if self.tok != TOK_ID:
             raise KconfigParserError(self, 'Expected identifier')
+        val = self.val
+        assert val is not None
+        if not val.startswith("CONFIG_"):
+            raise KconfigParserError(self,
+                       'Expected identifier starting with "CONFIG_"', TOK_NONE)
+        self.get_token()
+        return self.data.do_var(val[7:])
 
     # assignment: var EQUAL y_or_n
     def parse_assignment(self):
@@ -495,11 +495,10 @@ def parse_expr(self):
     # condition: IF expr
     #       | empty
     def parse_condition(self):
-        if self.tok == TOK_IF:
-            self.get_token()
-            return self.parse_expr()
-        else:
+        if self.tok != TOK_IF:
             return None
+        self.get_token()
+        return self.parse_expr()
 
     # property: DEFAULT y_or_n condition
     #       | DEPENDS ON expr
@@ -604,41 +603,41 @@ def scan_token(self, ch):
         if ch == '#':
             self.cursor = self.src.find('\n', self.cursor)
             return None
-        elif ch == '=':
+        if ch == '=':
             return TOK_EQUAL
-        elif ch == '(':
+        if ch == '(':
             return TOK_LPAREN
-        elif ch == ')':
+        if ch == ')':
             return TOK_RPAREN
-        elif ch == '&' and self.src[self.pos+1] == '&':
+        if ch == '&' and self.src[self.pos+1] == '&':
             self.cursor += 1
             return TOK_AND
-        elif ch == '|' and self.src[self.pos+1] == '|':
+        if ch == '|' and self.src[self.pos+1] == '|':
             self.cursor += 1
             return TOK_OR
-        elif ch == '!':
+        if ch == '!':
             return TOK_NOT
-        elif ch == 'd' and self.check_keyword("epends"):
+        if ch == 'd' and self.check_keyword("epends"):
             return TOK_DEPENDS
-        elif ch == 'o' and self.check_keyword("n"):
+        if ch == 'o' and self.check_keyword("n"):
             return TOK_ON
-        elif ch == 's' and self.check_keyword("elect"):
+        if ch == 's' and self.check_keyword("elect"):
             return TOK_SELECT
-        elif ch == 'i' and self.check_keyword("mply"):
+        if ch == 'i' and self.check_keyword("mply"):
             return TOK_IMPLY
-        elif ch == 'c' and self.check_keyword("onfig"):
+        if ch == 'c' and self.check_keyword("onfig"):
             return TOK_CONFIG
-        elif ch == 'd' and self.check_keyword("efault"):
+        if ch == 'd' and self.check_keyword("efault"):
             return TOK_DEFAULT
-        elif ch == 'b' and self.check_keyword("ool"):
+        if ch == 'b' and self.check_keyword("ool"):
             return TOK_BOOL
-        elif ch == 'i' and self.check_keyword("f"):
+        if ch == 'i' and self.check_keyword("f"):
             return TOK_IF
-        elif ch == 'y' and self.check_keyword(""):
+        if ch == 'y' and self.check_keyword(""):
             return TOK_Y
-        elif ch == 'n' and self.check_keyword(""):
+        if ch == 'n' and self.check_keyword(""):
             return TOK_N
-        elif (ch == 's' and self.check_keyword("ource")) or \
+        if (ch == 's' and self.check_keyword("ource")) or \
               ch == 'i' and self.check_keyword("nclude"):
             # source FILENAME
             # include FILENAME
@@ -648,21 +647,23 @@ def scan_token(self, ch):
             self.cursor = self.src.find('\n', self.cursor)
             self.val = self.src[start:self.cursor]
             return TOK_SOURCE
-        elif ch.isalnum():
+        if ch.isalnum():
             # identifier
             while self.src[self.cursor].isalnum() or self.src[self.cursor] == '_':
                 self.cursor += 1
             self.val = self.src[self.pos:self.cursor]
             return TOK_ID
-        elif ch == '\n':
+        if ch == '\n':
             if self.cursor == len(self.src):
                 return TOK_EOF
             self.line += 1
             self.line_pos = self.cursor
-        elif not ch.isspace():
-            raise KconfigParserError(self, 'invalid input', ch)
+            return None
+        if ch.isspace():
+            return None
+
+        raise KconfigParserError(self, 'invalid input', ch)
 
-        return None
 
 def main():
     argv = sys.argv
Signature · 1 line
2.54.0
#17 lore raw

PATCH 13/13 minikconf: add mypy annotations

In reply to Paolo Bonzini
---
 python/tests/linters.py |   3 +
 scripts/minikconf.py    | 222 ++++++++++++++++++++++------------------
 2 files changed, 124 insertions(+), 101 deletions(-)
python/tests/linters.py +3 -0
index 4ce4e8a9805..82b88aebb20 100644
@@ -65,6 +65,9 @@ def test_isort_qapi_sphinx(self):
             ]
         )
 
+    def test_mypy_minikconf(self):
+        check_call([sys.executable, "-m", "mypy", "../scripts/minikconf.py"])
+
     def test_mypy_pkg(self):
         check_call([sys.executable, "-m", "mypy", "-p", "qemu"])
 
scripts/minikconf.py +121 -101

576 lines not on this page · raw message

Signature · 1 line
2.54.0
Reviewed-by on the v1 series
#18 lore raw
In reply to Paolo Bonzini
Quoted 9 lines · Paolo Bonzini

kconfig cleanups and mypy annotations

Modernize the code a bit and fix some issues that were found while adding mypy annotations to minikconf.

While this stops short of adding flake8 and pylint, it already improves the style and fixes a bug (see patches 1-2).

[...]

Signature · 1 line
Marc-André Lureau <[email protected]>