Skip to content

Commit 6d4eb2b

Browse files
authored
Fix Union JSON serialization (#1936)
This doesn't allow JSON deserialization (for that, some rust/runtime work has to happen) but it does fix serialization to at least work one way. <!-- ELLIPSIS_HIDDEN --> ---- > [!IMPORTANT] > Add JSON serialization support for union types in Go, with `MarshalJSON` methods and a test file, but deserialization is not implemented. > > - **Serialization**: > - Add `MarshalJSON` method to union types in `types-unions.go.j2` and `unions.go` for JSON serialization. > - `UnmarshalJSON` method added but returns "not implemented" error. > - **Testing**: > - Add `json_test.go` to test JSON serialization round-trip. > - Includes a commented-out test case for `Union__float__bool` indicating incomplete functionality. > > <sup>This description was created by </sup>[<img alt="Ellipsis" src="https://img.shields.io/badge/Ellipsis-blue?color=175173">](https://www.ellipsis.dev?ref=BoundaryML%2Fbaml&utm_source=github&utm_medium=referral)<sup> for c216146. You can [customize](https://app.ellipsis.dev/BoundaryML/settings/summaries) this summary. It will automatically update as commits are pushed.</sup> <!-- ELLIPSIS_HIDDEN -->
1 parent b037124 commit 6d4eb2b

3 files changed

Lines changed: 606 additions & 1 deletion

File tree

engine/language_client_codegen/src/go/templates/types-unions.go.j2

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
package types
22

33
import (
4+
"encoding/json"
45
"fmt"
56

6-
flatbuffers "github.com/google/flatbuffers/go"
7+
flatbuffers "github.com/google/flatbuffers/go"
78
baml "github.com/boundaryml/baml/engine/language_client_go/pkg"
89
"github.com/boundaryml/baml/engine/language_client_go/pkg/cffi"
910
)
@@ -47,6 +48,21 @@ func (u {{ union.name }}) BamlTypeName() string {
4748
return "{{ union.name }}"
4849
}
4950

51+
func (u {{ union.name }}) MarshalJSON() ([]byte, error) {
52+
switch u.variant {
53+
{% for variant in union.variants %}
54+
case "{{ variant.0 }}":
55+
return json.Marshal(u.variant_{{ variant.0 }})
56+
{% endfor %}
57+
}
58+
59+
return nil, fmt.Errorf("invalid union variant: %s", u.variant)
60+
}
61+
62+
func (u *{{ union.name }}) UnmarshalJSON(data []byte) error {
63+
return fmt.Errorf("not implemented")
64+
}
65+
5066
{% for variant in union.variants %}
5167
func (u *{{ union.name }}) Set{{ variant.0|exported_name }}(v {{ variant.1.name }}) {
5268
u.variant = "{{ variant.0 }}"

0 commit comments

Comments
 (0)