wit/bindgen,cm: marshal & unmarshal for record types#225
wit/bindgen,cm: marshal & unmarshal for record types#225lxfontes wants to merge 1 commit intobytecodealliance:mainfrom
Conversation
Signed-off-by: Lucas Fontes <lucas@cosmonic.com>
|
Amazing. This looks great so far. Thanks! |
| var b strings.Builder | ||
| b.WriteString("struct {\n") | ||
| stringio.Write(&b, "_ ", file.Import(g.opts.cmPackage), ".HostLayout") | ||
| stringio.Write(&b, "_ ", file.Import(g.opts.cmPackage), ".HostLayout", "`json:\"-\"`") |
There was a problem hiding this comment.
Don't forget the space before the backtick, or just have a single string with HostLayout and the tag.
| stringio.Write(&b, "return ", stringsName, "[v.Tag()]\n") | ||
| b.WriteString("}\n\n") | ||
|
|
||
| file.Import("encoding/json") |
There was a problem hiding this comment.
Make sure to capture the name of the import. It might not be json.
| file.Import("encoding/json") | ||
| b.WriteString(formatDocComments("MarshalJSON implements [json.Marshaler].", true)) | ||
| stringio.Write(&b, "func (v ", goName, ") MarshalJSON() ([]byte, error) {\n") | ||
| stringio.Write(&b, "ret := make(map[string]any)\n") |
There was a problem hiding this comment.
I think there might be a better way to do this.
Possibly by putting MarshalJSON and UnmarshalJSON in package cm, and generate only the minimal mapping from case name to case type.
| list[T] | ||
| } | ||
|
|
||
| func (l List[T]) MarshalJSON() ([]byte, error) { |
There was a problem hiding this comment.
These methods should be on the inner list[T] struct.
| } | ||
|
|
||
| // MarshalJSON implements the json.Marshaler interface for [Option]. | ||
| func (o Option[T]) MarshalJSON() ([]byte, error) { |
There was a problem hiding this comment.
These methods should be on the inner struct.
|
|
||
| // UnmarshalJSON unmarshals the Option from JSON. | ||
| func (o *Option[T]) UnmarshalJSON(buf []byte) error { | ||
| if len(buf) == 0 { |
There was a problem hiding this comment.
This should also check if buf == null.
There was a problem hiding this comment.
👍 the null story here is interesting. will push it up as part of the breaking this PR into many
|
going to close this PR and move over to #239 |
Adds
jsonstruct tags to Records, based on wit names.Also adds
MarshalJSON&UnmarshalJSONto:Example, encoding a complex record type:
and filling it up:
Without this Pull Request:
With this Pull Request:
Tuple handling
Tuples are encoded as json arrays with explicit
nulls.Variant handling
Variants are encoded as json dictionaries, so they can carry the variant data.
Option handling
Options rely on explicit
nullfor the "None" case.If this direction seems reasonable I will add:
cm.Result