Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions benchmarks/go/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,8 @@ type SampleV2 struct {
// Player enum type
type Player int32

func (Player) ForyEnumMarker() {}

const (
PlayerJava Player = 0
PlayerFlash Player = 1
Expand All @@ -112,6 +114,8 @@ const (
// Size enum type
type Size int32

func (Size) ForyEnumMarker() {}

const (
SizeSmall Size = 0
SizeLarge Size = 1
Expand Down
15 changes: 15 additions & 0 deletions compiler/fory_compiler/generators/go.py
Original file line number Diff line number Diff line change
Expand Up @@ -492,6 +492,8 @@ def generate_enum(
const_name = f"{type_name}{self.to_pascal_case(stripped_name)}"
lines.append(f"\t{const_name} {type_name} = {value.value}")
lines.append(")")
lines.append("")
lines.append(f"func ({type_name}) ForyEnumMarker() {{}}")

return lines

Expand Down Expand Up @@ -617,6 +619,19 @@ def generate_union(

lines.append(f"func (u {type_name}) ForyUnionMarker() {{}}")
lines.append("")
cases = []
for field in union.fields:
type_expr = self.get_union_case_reflect_type_expr(field, parent_stack)
type_id_expr = self.get_union_case_type_id_expr(field, parent_stack)
spec_expr = self.get_union_case_type_spec_expr(field, parent_stack)
spec_field = f", Spec: {spec_expr}" if spec_expr is not None else ""
cases.append(
f"fory.UnionCase{{ID: {field.number}, Type: {type_expr}, TypeID: {type_id_expr}{spec_field}}}"
)
lines.append(f"func (u {type_name}) ForyUnionCases() []fory.UnionCase {{")
lines.append(f"\treturn []fory.UnionCase{{{', '.join(cases)}}}")
lines.append("}")
lines.append("")
lines.append(
f"func (u {type_name}) ForyUnionGet() (uint32, any) {{ return uint32(u.case_), u.value }}"
)
Expand Down
3 changes: 3 additions & 0 deletions compiler/fory_compiler/tests/test_fory_2_0_codegen.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,9 @@ def test_go_generator_uses_fory_2_0_type_ids():
assert "fory.NAMED_ENUM" in content
assert "fory.TYPED_STRUCT" in content
assert "fory.NAMED_STRUCT" in content
assert "func (Color) ForyEnumMarker() {}" in content
assert "func (NamedColor) ForyEnumMarker() {}" in content
assert "func (u DemoUnion) ForyUnionCases() []fory.UnionCase {" in content


def test_dart_generator_uses_fory_2_0_enum_type_id():
Expand Down
21 changes: 19 additions & 2 deletions go/fory/enum.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,16 @@
package fory

import (
"math"
"reflect"
)

// EnumMarker marks Go numeric enum types so unregistered enums serialize as Fory ENUM
// ordinals rather than ordinary named integer types.
type EnumMarker interface {
ForyEnumMarker()
}

// enumSerializer serializes Go enum types (which are typically int-based types)
// For xlang serialization, enums are written as VarUint32Small7 of their ordinal value
type enumSerializer struct {
Expand All @@ -33,9 +40,19 @@ func (s *enumSerializer) WriteData(ctx *WriteContext, value reflect.Value) {
var ordinal uint32
switch value.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
ordinal = uint32(value.Int())
v := value.Int()
if v < 0 || v > math.MaxUint32 {
ctx.SetError(SerializationErrorf("enum value %d out of uint32 ordinal range", v))
return
}
ordinal = uint32(v)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
ordinal = uint32(value.Uint())
v := value.Uint()
if v > math.MaxUint32 {
ctx.SetError(SerializationErrorf("enum value %d out of uint32 ordinal range", v))
return
}
ordinal = uint32(v)
default:
ctx.SetError(SerializationErrorf("enum serializer: unsupported kind %v", value.Kind()))
return
Expand Down
18 changes: 12 additions & 6 deletions go/fory/field_info.go
Original file line number Diff line number Diff line change
Expand Up @@ -487,9 +487,11 @@ func isInternalTypeWithoutTypeMeta(t reflect.Type) bool {
}

var (
unionMarkerType = reflect.TypeOf((*UnionMarker)(nil)).Elem()
unionGetterType = reflect.TypeOf((*UnionGetter)(nil)).Elem()
unionSetterType = reflect.TypeOf((*UnionSetter)(nil)).Elem()
enumMarkerType = reflect.TypeOf((*EnumMarker)(nil)).Elem()
unionMarkerType = reflect.TypeOf((*UnionMarker)(nil)).Elem()
unionGetterType = reflect.TypeOf((*UnionGetter)(nil)).Elem()
unionSetterType = reflect.TypeOf((*UnionSetter)(nil)).Elem()
unionDescriptorType = reflect.TypeOf((*UnionDescriptor)(nil)).Elem()
)

// isUnionType checks if a type implements the union accessors.
Expand Down Expand Up @@ -997,13 +999,17 @@ func isBuiltinPrimitiveElem(t reflect.Type) bool {
return t.PkgPath() == "" || t == float16Type || t == bfloat16Type
}

// isUnregisteredEnumType reports whether t is a user-defined named integer type
// (the idiomatic Go enum representation) that is not a built-in numeric alias.
// isUnregisteredEnumType reports whether t is a user-defined numeric type explicitly marked
// as a Fory enum via EnumMarker. Ordinary named integer types such as `type Balance int64`
// are not enums and preserve their underlying scalar integer encoding and full value range.
func isUnregisteredEnumType(t reflect.Type) bool {
if t == nil || t.PkgPath() == "" || t == durationType || t == float16Type || t == bfloat16Type {
return false
}
return isNumericKind(t.Kind())
if !isNumericKind(t.Kind()) {
return false
}
return t.Implements(enumMarkerType) || reflect.PtrTo(t).Implements(enumMarkerType)
}

// typeIdFromKind derives a TypeId from a reflect.Type's kind
Expand Down
3 changes: 3 additions & 0 deletions go/fory/field_spec.go
Original file line number Diff line number Diff line change
Expand Up @@ -919,6 +919,9 @@ func inferPackedElementTypeSpec(goType reflect.Type) (*TypeSpec, bool) {
if goType == durationType {
return NewSimpleTypeSpec(DURATION), true
}
if !isBuiltinPrimitiveElem(goType) {
return nil, false
}
switch goType.Kind() {
case reflect.Bool:
return NewSimpleTypeSpec(BOOL), true
Expand Down
146 changes: 146 additions & 0 deletions go/fory/fory_2_0_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,25 @@ type f20NestedLeaf struct {

type f20Role int32

func (f20Role) ForyEnumMarker() {}

const (
f20RoleUser f20Role = iota
f20RoleAdmin
)

type f20Balance int64
type f20Counter uint64

type f20NamedIntAndEnum struct {
PosBalance f20Balance
NegBalance f20Balance
BigCounter f20Counter
Role f20Role
BalanceList []f20Balance
RoleList []f20Role
}

type f20NestedContainer struct {
Leaf f20NestedLeaf
LeafPtr *f20NestedLeaf
Expand Down Expand Up @@ -124,6 +138,26 @@ func (u *f20UnionCase) ForyUnionSet(caseID uint32, value any) {
u.value = value
}

type f20UnboundUnion struct {
caseID uint32
value any
}

func (f20UnboundUnion) ForyUnionMarker() {}
func (u f20UnboundUnion) ForyUnionGet() (uint32, any) {
return u.caseID, u.value
}
func (u *f20UnboundUnion) ForyUnionSet(caseID uint32, value any) {
u.caseID = caseID
u.value = value
}
func (f20UnboundUnion) ForyUnionCases() []UnionCase {
return []UnionCase{
{ID: 0, Type: reflect.TypeOf(int32(0)), TypeID: VARINT32},
{ID: 1, Type: reflect.TypeOf(f20NestedLeaf{}), TypeID: COMPATIBLE_STRUCT},
}
}

func TestFory20RootHeaderVersionAndValidation(t *testing.T) {
fx := New(WithXlang(true), WithCompatible(false))
dataX, err := fx.Serialize(int32(42))
Expand Down Expand Up @@ -491,3 +525,115 @@ func TestFory20UnboundMetaBackRefDistinctTargetsAfterL0Hit(t *testing.T) {
require.Equal(t, f20Point2D{X: 10, Y: 20}, out.P)
require.Equal(t, f20Vector2D{X: 30, Y: 40}, out.V)
}

func TestFory20NamedIntegersPreserveRangeAlongsideUnregisteredEnum(t *testing.T) {
for _, compatible := range []bool{true, false} {
writer := New(WithXlang(true), WithCompatible(compatible))
reader := New(WithXlang(true), WithCompatible(compatible))

orig := f20NamedIntAndEnum{
PosBalance: f20Balance(1 << 40),
NegBalance: f20Balance(-1),
BigCounter: f20Counter((uint64(1) << 50) + 12345),
Role: f20RoleAdmin,
BalanceList: []f20Balance{f20Balance(-(1 << 45)), f20Balance(-1), f20Balance(1 << 42)},
RoleList: []f20Role{f20RoleUser, f20RoleAdmin},
}
data, err := writer.Serialize(&orig)
require.NoError(t, err)

var out f20NamedIntAndEnum
require.NoError(t, reader.Deserialize(bytes.Clone(data), &out))
require.Equal(t, orig, out)

// Verify root round-trips and wire type IDs distinguish named integers from marked enums.
bal := f20Balance(1 << 40)
balBytes, err := writer.Serialize(bal)
require.NoError(t, err)
require.Equal(t, uint8(VARINT64), balBytes[2])
var balOut f20Balance
require.NoError(t, reader.Deserialize(bytes.Clone(balBytes), &balOut))
require.Equal(t, bal, balOut)

negBal := f20Balance(-1)
negBytes, err := writer.Serialize(negBal)
require.NoError(t, err)
var negOut f20Balance
require.NoError(t, reader.Deserialize(bytes.Clone(negBytes), &negOut))
require.Equal(t, negBal, negOut)

roleBytes, err := writer.Serialize(f20RoleAdmin)
require.NoError(t, err)
require.Equal(t, uint8(ENUM), roleBytes[2])
var roleOut f20Role
require.NoError(t, reader.Deserialize(bytes.Clone(roleBytes), &roleOut))
require.Equal(t, f20RoleAdmin, roleOut)

// Marked enum with out-of-range ordinal must return a controlled serialization error.
invalidRole := f20Role(-1)
_, err = writer.Serialize(invalidRole)
require.Error(t, err)
}
}

func TestFory20UnboundUnionRoundTrip(t *testing.T) {
for _, compatible := range []bool{true, false} {
writer := New(WithXlang(true), WithCompatible(compatible))
reader := New(WithXlang(true), WithCompatible(compatible))

primOrig := f20UnboundUnion{caseID: 0, value: int32(-123456)}
primBytes, err := writer.Serialize(&primOrig)
require.NoError(t, err)
// Byte 0: root header, Byte 1: ref flag, Byte 2: wire type id (UNION)
require.Equal(t, uint8(UNION), primBytes[2])

var primOut f20UnboundUnion
require.NoError(t, reader.Deserialize(bytes.Clone(primBytes), &primOut))
require.Equal(t, primOrig, primOut)

structOrig := f20UnboundUnion{
caseID: 1,
value: f20NestedLeaf{Label: "unbound-union-leaf", Score: 99},
}
structBytes, err := writer.Serialize(&structOrig)
require.NoError(t, err)
require.Equal(t, uint8(UNION), structBytes[2])

var structOut f20UnboundUnion
require.NoError(t, reader.Deserialize(bytes.Clone(structBytes), &structOut))
require.Equal(t, structOrig, structOut)

// Dynamic any read must reject an UNBOUND UNION with no registered identity.
var dynOut any
require.Error(t, reader.Deserialize(bytes.Clone(structBytes), &dynOut))

// Struct holding an unregistered union field must also round-trip cleanly.
type unionHolder struct {
Tag string
Value f20UnboundUnion
}
holderOrig := unionHolder{Tag: "holder", Value: structOrig}
holderBytes, err := writer.Serialize(&holderOrig)
require.NoError(t, err)
var holderOut unionHolder
require.NoError(t, reader.Deserialize(bytes.Clone(holderBytes), &holderOut))
require.Equal(t, holderOrig, holderOut)
}

// Asymmetric: registered union writer -> unregistered UnionDescriptor reader.
regWriter := New(WithXlang(true), WithCompatible(true))
require.NoError(t, regWriter.RegisterUnion(
f20UnboundUnion{},
812,
NewUnionSerializer(f20UnboundUnion{}.ForyUnionCases()...),
))
unregReader := New(WithXlang(true), WithCompatible(true))
asymOrig := f20UnboundUnion{caseID: 1, value: f20NestedLeaf{Label: "asym-union", Score: 55}}
asymBytes, err := regWriter.Serialize(&asymOrig)
require.NoError(t, err)
require.Equal(t, uint8(TYPED_UNION), asymBytes[2])

var asymOut f20UnboundUnion
require.NoError(t, unregReader.Deserialize(bytes.Clone(asymBytes), &asymOut))
require.Equal(t, asymOrig, asymOut)
}
4 changes: 4 additions & 0 deletions go/fory/tests/xlang/xlang_test_main.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,8 @@ func assertEqualFloat64(expected, actual float64, name string) {

type Color int32

func (Color) ForyEnumMarker() {}

const (
GREEN Color = 0
RED Color = 1
Expand Down Expand Up @@ -264,6 +266,8 @@ type TwoStringFieldStruct struct {
// Enum field structs for testing
type TestEnum int32

func (TestEnum) ForyEnumMarker() {}

const (
VALUE_A TestEnum = 0
VALUE_B TestEnum = 1
Expand Down
3 changes: 3 additions & 0 deletions go/fory/type_def.go
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,9 @@ func (td *TypeDef) buildTypeInfoForTarget(resolver *TypeResolver, targetType ref
localInfo.Serializer != nil && isUnionTypeId(TypeId(localInfo.TypeID)) {
return localInfo, nil
}
if localInfo, unionErr := resolver.getOrCreateLocalUnionTypeInfo(targetType); unionErr == nil && localInfo != nil {
return localInfo, nil
}
}
return nil, DeserializationErrorf("wire type NAMED_UNION cannot be materialized as %v", targetType)
default:
Expand Down
Loading
Loading