All of lore.kernel.org
 help / color / mirror / Atom feed
From: Victor Toso <victortoso@redhat.com>
To: qemu-devel@nongnu.org
Cc: John Snow <jsnow@redhat.com>, Eric Blake <eblake@redhat.com>,
	Markus Armbruster <armbru@redhat.com>
Subject: [RFC PATCH v1 6/8] qapi: golang: Generate qapi's command types in Go
Date: Sat,  2 Apr 2022 00:41:02 +0200	[thread overview]
Message-ID: <20220401224104.145961-7-victortoso@redhat.com> (raw)
In-Reply-To: <20220401224104.145961-1-victortoso@redhat.com>

This patch handles QAPI command types and generates data structures in
Go that decodes from QMP JSON Object to Go data structure and vice
versa.

At the time of this writing, it generates 210 structures
(208 commands)

This is very similar to previous commit, that handles QAPI union types
in Go.

Each QAPI command will generate a Go struct with the suffix 'Command'.
Its fields, if any, are the mandatory or optional arguments defined in
the QAPI command.

Simlar to Event, this patch adds two structures to handle QAPI
specification for command types: 'Command' and 'CommandBase'.

'CommandBase' contains @Id and @Name. 'Command' extends 'CommandBase'
with an @Arg field of type 'Any'.

The 'Command' type implements the Unmarshaler to decode QMP JSON
Object into the correct Golang (command) struct.

Marshal example:
```go
	cmdArg := SetPasswordCommand{}
	cmdArg.Protocol = DisplayProtocolVnc
	cmdArg.Password = "secret"
	cmd := Command{}
	cmd.Name = "set_password"
	cmd.Arg = cmdArg

	b, _ := json.Marshal(&cmd)
	// string(b) == `{"execute":"set_password","arguments":{"protocol":"vnc","password":"secret"}}`
```

Unmarshal example:
```go
	qmpCommand := `
{
	"execute": "set_password",
	"arguments":{
		"protocol": "vnc",
		"password": "secret"
	}
}`
	cmd := Command{}
	_ = json.Unmarshal([]byte(qmpCommand), &cmd)
	// cmd.Name == "set_password"
	// cmd1.Arg.(SetPasswordCommand).Protocol == DisplayProtocolVnc
```

Signed-off-by: Victor Toso <victortoso@redhat.com>
---
 scripts/qapi/golang.py | 49 ++++++++++++++++++++++++++++++++++++++----
 1 file changed, 45 insertions(+), 4 deletions(-)

diff --git a/scripts/qapi/golang.py b/scripts/qapi/golang.py
index 3bb66d07c7..0b9c19babb 100644
--- a/scripts/qapi/golang.py
+++ b/scripts/qapi/golang.py
@@ -31,10 +31,11 @@ class QAPISchemaGenGolangVisitor(QAPISchemaVisitor):
 
     def __init__(self, prefix: str):
         super().__init__()
-        self.target = {name: "" for name in ["alternate", "enum", "event", "helper", "struct", "union"]}
+        self.target = {name: "" for name in ["alternate", "command", "enum", "event", "helper", "struct", "union"]}
         self.objects_seen = {}
         self.schema = None
         self.events = {}
+        self.commands = {}
         self._docmap = {}
         self.golang_package_name = "qapi"
 
@@ -76,6 +77,19 @@ def visit_end(self):
 '''
         self.target["event"] += generate_marshal_methods('Event', self.events)
 
+        self.target["command"] += '''
+type CommandBase struct {
+    Id   string `json:"id,omitempty"`
+    Name string `json:"execute"`
+}
+
+type Command struct {
+    CommandBase
+    Arg Any    `json:"arguments,omitempty"`
+}
+'''
+        self.target["command"] += generate_marshal_methods('Command', self.commands)
+
         self.target["helper"] += '''
 // Creates a decoder that errors on unknown Fields
 // Returns true if successfully decoded @from string @into type
@@ -295,7 +309,29 @@ def visit_command(self,
                       allow_oob: bool,
                       allow_preconfig: bool,
                       coroutine: bool) -> None:
-        pass
+        assert name == info.defn_name
+        type_name = qapi_to_go_type_name(name, info.defn_meta)
+        self.commands[name] = type_name
+
+        doc = self._docmap.get(name, None)
+        self_contained = True if not arg_type or not arg_type.name.startswith("q_obj") else False
+        content = ""
+        if boxed or self_contained:
+            args = "" if not arg_type else "\n" + arg_type.name
+            doc_struct, _ = qapi_to_golang_struct_docs(doc)
+            content = generate_struct_type(type_name, args, doc_struct)
+        else:
+            assert isinstance(arg_type, QAPISchemaObjectType)
+            content = qapi_to_golang_struct(name,
+                                            doc,
+                                            arg_type.info,
+                                            arg_type.ifcond,
+                                            arg_type.features,
+                                            arg_type.base,
+                                            arg_type.members,
+                                            arg_type.variants)
+
+        self.target["command"] += content
 
     def visit_event(self, name, info, ifcond, features, arg_type, boxed):
         assert name == info.defn_name
@@ -391,7 +427,7 @@ def generate_marshal_methods_enum(members: List[QAPISchemaEnumMember]) -> str:
 }}
 '''
 
-# Marshal methods for Event and Union types
+# Marshal methods for Event, Commad and Union types
 def generate_marshal_methods(type: str,
                              type_dict: Dict[str, str],
                              discriminator: str = "",
@@ -404,6 +440,11 @@ def generate_marshal_methods(type: str,
         discriminator = "base.Name"
         struct_field = "Arg"
         json_field = "data"
+    elif type == "Command":
+        base = type + "Base"
+        discriminator = "base.Name"
+        struct_field = "Arg"
+        json_field = "arguments"
     else:
         assert base != ""
         discriminator = "base." + discriminator
@@ -636,7 +677,7 @@ def qapi_to_go_type_name(name: str, meta: str) -> str:
     name = words[0].title() if words[0].islower() or words[0].isupper() else words[0]
     name += ''.join(word.title() for word in words[1:])
 
-    if meta == "event":
+    if meta == "event" or meta == "command":
         name = name[:-3] if name.endswith("Arg") else name
         name += meta.title()
 
-- 
2.35.1



  parent reply	other threads:[~2022-04-01 22:48 UTC|newest]

Thread overview: 71+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2022-04-01 22:40 [RFC PATCH v1 0/8] qapi: add generator for Golang interface Victor Toso
2022-04-01 22:40 ` [RFC PATCH v1 1/8] qapi: golang: Generate qapi's enum types in Go Victor Toso
2022-05-10 10:06   ` Daniel P. Berrangé
2022-05-10 11:15     ` Victor Toso
2022-05-10 11:19       ` Daniel P. Berrangé
2022-05-10 11:28         ` Victor Toso
2022-05-10 11:39           ` Daniel P. Berrangé
2022-04-01 22:40 ` [RFC PATCH v1 2/8] qapi: golang: Generate qapi's alternate " Victor Toso
2022-05-10 10:10   ` Daniel P. Berrangé
2022-05-10 11:21     ` Victor Toso
2022-05-10 11:28       ` Daniel P. Berrangé
2022-04-01 22:40 ` [RFC PATCH v1 3/8] qapi: golang: Generate qapi's struct " Victor Toso
2022-04-01 22:41 ` [RFC PATCH v1 4/8] qapi: golang: Generate qapi's union " Victor Toso
2022-05-10 10:26   ` Daniel P. Berrangé
2022-05-10 11:32     ` Victor Toso
2022-05-10 11:42       ` Daniel P. Berrangé
2022-04-01 22:41 ` [RFC PATCH v1 5/8] qapi: golang: Generate qapi's event " Victor Toso
2022-05-10 10:42   ` Daniel P. Berrangé
2022-05-10 11:38     ` Victor Toso
2022-04-01 22:41 ` Victor Toso [this message]
2022-04-01 22:41 ` [RFC PATCH v1 7/8] qapi: golang: Add CommandResult type to Go Victor Toso
2022-04-01 22:41 ` [RFC PATCH v1 8/8] qapi: golang: document skip function visit_array_types Victor Toso
2022-04-19 18:12 ` [RFC PATCH v1 0/8] qapi: add generator for Golang interface Andrea Bolognani
2022-04-19 18:42   ` Andrea Bolognani
2022-04-28 13:50   ` Markus Armbruster
2022-04-29 13:15     ` Andrea Bolognani
2022-05-02  7:21       ` Markus Armbruster
2022-05-02  9:04         ` Andrea Bolognani
2022-05-02 11:46           ` Markus Armbruster
2022-05-02 14:01             ` Andrea Bolognani
2022-05-03  7:57               ` Markus Armbruster
2022-05-03  9:40                 ` Andrea Bolognani
2022-05-03 11:04                   ` Kevin Wolf
2022-05-10  9:55                   ` Daniel P. Berrangé
2022-05-11  6:15                   ` Markus Armbruster
2022-05-09 18:53               ` Victor Toso
2022-05-10  8:06                 ` Markus Armbruster
2022-05-10 11:48                   ` Victor Toso
2022-05-10  9:52               ` Daniel P. Berrangé
2022-05-10 15:25                 ` Andrea Bolognani
2022-05-11 13:45                 ` Markus Armbruster
2022-05-09 10:21   ` Victor Toso
2022-05-10 17:37     ` Andrea Bolognani
2022-05-10 18:02       ` Daniel P. Berrangé
2022-04-26 11:14 ` Markus Armbruster
2022-05-09 10:52   ` Victor Toso
2022-05-10  8:53   ` Daniel P. Berrangé
2022-05-10  9:06     ` Victor Toso
2022-05-10  9:17       ` Daniel P. Berrangé
2022-05-10  9:32         ` Daniel P. Berrangé
2022-05-10 10:50           ` Victor Toso
2022-05-10 10:57             ` Daniel P. Berrangé
2022-05-10 12:02     ` Markus Armbruster
2022-05-10 12:34       ` Daniel P. Berrangé
2022-05-10 12:51         ` Daniel P. Berrangé
2022-05-11 14:17           ` Markus Armbruster
2022-05-11 14:41             ` Daniel P. Berrangé
2022-05-11 15:38           ` Andrea Bolognani
2022-05-11 15:50             ` Daniel P. Berrangé
2022-05-11 16:22               ` Andrea Bolognani
2022-05-11 16:32                 ` Daniel P. Berrangé
2022-05-18  8:10               ` Victor Toso
2022-05-18  8:51                 ` Daniel P. Berrangé
2022-05-18  9:01                   ` Victor Toso
2022-05-11 14:17         ` Markus Armbruster
2022-05-18  8:55           ` Victor Toso
2022-05-18 12:30             ` Markus Armbruster
2022-05-25 13:49               ` Andrea Bolognani
2022-05-25 14:10                 ` Markus Armbruster
2022-06-01 13:53                 ` Victor Toso
2022-05-10 10:47 ` Daniel P. Berrangé

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20220401224104.145961-7-victortoso@redhat.com \
    --to=victortoso@redhat.com \
    --cc=armbru@redhat.com \
    --cc=eblake@redhat.com \
    --cc=jsnow@redhat.com \
    --cc=qemu-devel@nongnu.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.