[PATCH v3 14/19] scripts/qapi: allow passing multiple segments to mcgen

Paolo Bonzini <[email protected]> Tue, 26 May 2026 19:56:13 +0200
Newsgroups org.nongnu.qemu-rust,org.nongnu.qemu-devel
Message-ID <[email protected]>
Make mcgen more flexible to allow for easier removal of empty lines.
For example, in Rust you can have #[cfg(X)] lines that would often
be empty; let mcgen remove the whole segment or at least the empty
spaces and lines at the end of it.

Separate invocations of mcgen still preserve the empty lines
between them.

Signed-off-by: Paolo Bonzini <[email protected]>
---
 scripts/qapi/common.py | 22 ++++++++++++++++++----
 1 file changed, 18 insertions(+), 4 deletions(-)

diff --git a/scripts/qapi/common.py b/scripts/qapi/common.py
index c75396a01b5..44229c2e366 100644
--- a/scripts/qapi/common.py
+++ b/scripts/qapi/common.py
@@ -172,10 +172,24 @@ def cgen(code: str, **kwds: object) -> str:
     return re.sub(re.escape(EATSPACE) + r' *', '', raw)
 
 
-def mcgen(code: str, **kwds: object) -> str:
-    if code[0] == '\n':
-        code = code[1:]
-    return cgen(code, **kwds)
+def mcgen(*code: str, **kwds: object) -> str:
+    '''
+    Generate ``code`` with ``kwds`` interpolated.  Separate
+    positional arguments represent separate segments that could
+    expand to empty strings; empty segments are omitted and no
+    blank lines are introduced at their boundaries.
+    '''
+    last = len(code) - 1
+    result = []
+    for i, s in enumerate(code):
+        if s.startswith('\n'):
+            s = s[1:]
+        if i != last:
+            s = s.rstrip()
+        s = cgen(s, **kwds)
+        if s:
+            result.append(s)
+    return '\n'.join(result)
 
 
 def c_fname(filename: str) -> str:
-- 
2.54.0