gomap

package
v0.0.12 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 12, 2025 License: Apache-2.0 Imports: 13 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ExtractGoType

func ExtractGoType(def *ir.Node, s *schema.Schema, registry *schema.SchemaRegistry) (reflect.Type, error)

ExtractGoType extracts Go type information from a schema definition node. It resolves .[name] references, handles !or [null, T] patterns for nullable types, parameterized types like .array(string), and constructs a reflect.Type that represents the Go type.

Examples:

  • "string" → reflect.TypeOf("")
  • ".[int]" → resolves to int definition, returns reflect.TypeOf(0)
  • "!or [null, string]" → returns reflect.PtrTo(reflect.TypeOf(""))
  • ".array(string)" → returns reflect.SliceOf(reflect.TypeOf("")) ([]string)
  • ".array(.array(string))" → returns [][]string
  • ".sparsearray(string)" → returns map[uint32]string

The function recursively resolves references and builds up complex types, including nested parameterized types.

func FromString added in v0.0.9

func FromString[T any](s string, v *T, opts ...UnmapOption) (*T, error)

func FromTony added in v0.0.6

func FromTony(data []byte, v interface{}, opts ...UnmapOption) error

FromTony unmarshals Tony-formatted bytes to a Go value. It first unmarshals the bytes to an IR node (using parseOpts from opts), then converts the IR node to the value (using FromTonyIR with opts).

func FromTonyIR added in v0.0.6

func FromTonyIR(node *ir.Node, v interface{}, opts ...UnmapOption) error

FromTonyIR converts a Tony IR node to a Go value. v must be a pointer to the target type. It automatically uses a FromTonyIR() method if available (user-implemented or generated), otherwise falls back to reflection-based conversion.

func GetDefaultRegistries

func GetDefaultRegistries() (*schema.SchemaRegistry, *schema.ContextRegistry)

GetDefaultRegistries returns the current default registries.

func IsNullable

func IsNullable(def *ir.Node, s *schema.Schema, registry *schema.SchemaRegistry) bool

IsNullable checks if a definition allows null (via !or with null). It returns true if the definition is a !or pattern that includes null as one of its options.

Examples:

  • !or [null, string] → true
  • !or [string] → false
  • string → false
  • .[nullable-string] → recursively checks the referenced definition

The function checks for null in three forms:

  • ir.NullType node type
  • Tag == "null"
  • StringType with String == "null"

func ParseStructTag

func ParseStructTag(tag string) (map[string]string, error)

ParseStructTag parses a struct tag string and returns a map of key-value pairs. Handles comma-separated values: `tony:"key1=value1,key2=value2,flag"` Supports quoted values with spaces: `tony:"key='value with spaces'"`

func SetDefaultRegistries

func SetDefaultRegistries(schemaReg *schema.SchemaRegistry, ctxReg *schema.ContextRegistry)

SetDefaultRegistries sets the default registries used when nil is passed to NewMapper. This allows global configuration of schema registries.

func ToEncodeOptions added in v0.0.7

func ToEncodeOptions(opts ...MapOption) []encode.EncodeOption

ToEncodeOptions extracts EncodeOptions from a slice of MapOptions.

func ToParseOptions added in v0.0.7

func ToParseOptions(opts ...UnmapOption) []parse.ParseOption

ToParseOptions extracts ParseOptions from a slice of UnmapOptions.

func ToString added in v0.0.9

func ToString[T any](v *T, opts ...MapOption) (string, error)

func ToTony added in v0.0.6

func ToTony(v interface{}, opts ...MapOption) ([]byte, error)

ToTony converts a Go value to Tony-formatted bytes. It first converts the value to an IR node (using ToTonyIR with mapOpts), then marshals the IR to bytes (using encOpts from mapOpts).

func ToTonyIR added in v0.0.6

func ToTonyIR(v interface{}, opts ...MapOption) (*ir.Node, error)

ToTonyIR converts a Go value to a Tony IR node. It automatically uses a ToTonyIR() method if available (user-implemented or generated), otherwise falls back to reflection-based conversion.

Types

type FieldInfo

type FieldInfo struct {
	// Name is the struct field name
	Name string

	// SchemaFieldName is the field name in the schema (may differ from struct field name)
	SchemaFieldName string

	// Type is the Go type of the field
	Type reflect.Type

	// Optional indicates if the field is optional (nullable or can be empty)
	Optional bool

	// Omit indicates if the field should be omitted from marshaling/unmarshaling
	Omit bool

	// Required indicates if the field is required (overrides type-based inference)
	Required bool

	// CommentFieldName is the name of a struct field (type []string) to populate with comment data
	CommentFieldName string

	// LineCommentFieldName is the name of a struct field (type []string) to populate with line comment data
	LineCommentFieldName string

	// ImplementsTextMarshaler indicates if the field type implements encoding.TextMarshaler
	ImplementsTextMarshaler bool

	// ImplementsTextUnmarshaler indicates if the field type implements encoding.TextUnmarshaler
	ImplementsTextUnmarshaler bool
}

FieldInfo holds field metadata extracted from struct tags

func GetStructFields

func GetStructFields(typ reflect.Type, s *schema.Schema, mode string, allowExtra bool, registry *schema.SchemaRegistry) ([]*FieldInfo, error)

GetStructFields extracts field information from a struct type. The behavior depends on the mode:

  • "schema" mode: Schema is source of truth, match struct fields to schema fields
  • "schemagen" mode: Struct is source of truth, extract field info from struct

registry can be nil for single-schema cases, but is required for cross-schema references.

type MapOption added in v0.0.7

type MapOption func(*mapConfig)

MapOption is an option for controlling the mapping process from Go to Tony IR.

func Depth added in v0.0.10

func Depth(n int) MapOption

Depth sets the indentation depth for encoding.

func EncodeBrackets added in v0.0.10

func EncodeBrackets(v bool) MapOption

EncodeBrackets controls whether brackets are used in the encoded output.

func EncodeColors added in v0.0.10

func EncodeColors(c *encode.Colors) MapOption

EncodeColors sets the color scheme for encoded output.

func EncodeComments added in v0.0.10

func EncodeComments(v bool) MapOption

EncodeComments controls whether comments are included in the encoded output.

func EncodeFormat added in v0.0.10

func EncodeFormat(f format.Format) MapOption

EncodeFormat sets the output format (Tony, YAML, or JSON).

func EncodeWire added in v0.0.9

func EncodeWire(v bool) MapOption

func InjectRaw added in v0.0.10

func InjectRaw(v bool) MapOption

InjectRaw controls whether raw values are injected in the encoded output.

type Mapper

type Mapper struct {
	// contains filtered or unexported fields
}

Mapper provides schema-aware marshaling and unmarshaling. It holds optional schema and context registries for resolving schema references. If registries are nil, the default registries are used (set via SetDefaultRegistries).

func DefaultMapper

func DefaultMapper() *Mapper

DefaultMapper returns a Mapper using the default registries. This is a convenience function equivalent to NewMapper(nil, nil).

func NewMapper

func NewMapper(schemaReg *schema.SchemaRegistry, ctxReg *schema.ContextRegistry) *Mapper

NewMapper creates a new Mapper with the given registries. If either registry is nil, the corresponding default registry is used. If no default registries are set, schema resolution will be disabled for that registry.

func (*Mapper) ContextRegistry

func (m *Mapper) ContextRegistry() *schema.ContextRegistry

ContextRegistry returns the context registry being used by this mapper.

func (*Mapper) FromTonyIR added in v0.0.6

func (m *Mapper) FromTonyIR(node *ir.Node, v interface{}, opts ...UnmapOption) error

FromTonyIR converts a Tony IR node to a Go value using schema-aware unmarshaling. v must be a pointer to the target type. It automatically uses a FromTony() method if available (user-implemented or generated), otherwise falls back to schema-aware or reflection-based conversion.

func (*Mapper) SchemaRegistry

func (m *Mapper) SchemaRegistry() *schema.SchemaRegistry

SchemaRegistry returns the schema registry being used by this mapper.

func (*Mapper) ToTonyIR added in v0.0.6

func (m *Mapper) ToTonyIR(v interface{}, opts ...MapOption) (*ir.Node, error)

ToTonyIR converts a Go value to a Tony IR node using schema-aware marshaling. It automatically uses a ToTony() method if available (user-implemented or generated), otherwise falls back to schema-aware or reflection-based conversion.

type MarshalError

type MarshalError struct {
	FieldPath string // Field path (e.g., "person.address.street")
	Message   string
	Err       error
}

MarshalError represents an error during marshaling

func (*MarshalError) Error

func (e *MarshalError) Error() string

func (*MarshalError) Unwrap

func (e *MarshalError) Unwrap() error

type SchemaError

type SchemaError struct {
	SchemaName string
	Message    string
	Err        error
}

SchemaError represents an error during schema resolution

func (*SchemaError) Error

func (e *SchemaError) Error() string

func (*SchemaError) Unwrap

func (e *SchemaError) Unwrap() error

type StructSchema

type StructSchema struct {
	// Mode is either "schema" (usage mode) or "schemagen" (definition mode)
	Mode string

	// SchemaName is the schema name/URI from the tag
	SchemaName string

	// Context is the schema context URI (e.g., "tony-format/context")
	// If empty, defaults to "tony-format/context"
	Context string

	// AllowExtra allows struct to have extra fields not in schema (default: false, strict)
	AllowExtra bool

	// CommentFieldName is the name of a struct field (type []string) to populate with comment data
	CommentFieldName string

	// LineCommentFieldName is the name of a struct field (type []string) to populate with line comment data
	LineCommentFieldName string

	// TagFieldName is the name of a struct field (type string) to populate with the IR node's tag
	TagFieldName string
}

StructSchema holds schema reference and mode information extracted from struct tags

func GetStructSchema

func GetStructSchema(typ reflect.Type) (*StructSchema, error)

GetStructSchema extracts schema information from a struct type. It looks for an anonymous field with a `tony:"schema=..."` or `tony:"schemagen=..."` tag.

Schema tags are only checked on direct anonymous fields of the struct, not recursively into embedded structs. If a struct embeds another struct that has a schema tag, only the outer struct's schema tag is used.

Example:

type A struct {
    schemaTag `tony:"schema=person"`
    Name string
}
type B struct {
    schemaTag `tony:"schema=company"`  // This tag is used for B
    A                                  // A's schema tag is ignored
    CompanyName string
}

type TypeError

type TypeError struct {
	FieldPath string
	Expected  string
	Actual    string
	Message   string
}

TypeError represents a type mismatch error

func (*TypeError) Error

func (e *TypeError) Error() string

type UnmapOption added in v0.0.7

type UnmapOption func(*unmapConfig)

UnmapOption is an option for controlling the unmapping process from Tony IR to Go.

func NoBrackets added in v0.0.10

func NoBrackets() UnmapOption

NoBrackets disables bracket parsing.

func ParseComments added in v0.0.10

func ParseComments(v bool) UnmapOption

ParseComments controls whether comments are parsed from the input.

func ParseFormat added in v0.0.10

func ParseFormat(f format.Format) UnmapOption

ParseFormat sets the input format for parsing (Tony, YAML, or JSON).

func ParseJSON added in v0.0.10

func ParseJSON() UnmapOption

ParseJSON sets the input format to JSON.

func ParsePositions added in v0.0.10

func ParsePositions(m map[*ir.Node]*token.Pos) UnmapOption

ParsePositions enables position tracking during parsing. The provided map will be populated with node-to-position mappings.

func ParseTony added in v0.0.10

func ParseTony() UnmapOption

ParseTony sets the input format to Tony.

func ParseYAML added in v0.0.10

func ParseYAML() UnmapOption

ParseYAML sets the input format to YAML.

type UnmarshalError

type UnmarshalError struct {
	FieldPath string // Field path (e.g., "person.address.street")
	Message   string
	Err       error
}

UnmarshalError represents an error during unmarshaling

func (*UnmarshalError) Error

func (e *UnmarshalError) Error() string

func (*UnmarshalError) Unwrap

func (e *UnmarshalError) Unwrap() error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL