shape

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2026 License: Apache-2.0 Imports: 21 Imported by: 73

Documentation

Overview

Copyright 2010 The Go Authors. All rights reserved. Copyright 2011 The Go Authors. All rights reserved. Adapted from Go 1.25.8 encoding/json.typeFields; see JSON_FIELDS_LICENSE.

Package shape owns structural Go type operations shared by runtime and source consumers. Named identity is resolved through a caller-owned lookup.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Accessor

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

Accessor is an immutable compiled field path with checked runtime access.

func (*Accessor) Equal

func (a *Accessor) Equal(left, right any) (bool, error)

Equal compares optional field values. Two absent paths are equal; an absent path differs from a present nil/zero leaf. Neither input is modified.

func (*Accessor) FieldIndex

func (a *Accessor) FieldIndex() ([]int, error)

FieldIndex returns a detached native struct-field index. Collection-indexed accessors require runtime collection positions and have no single index.

func (*Accessor) Get

func (a *Accessor) Get(target any) (reflect.Value, error)

func (*Accessor) GetAt

func (a *Accessor) GetAt(target any, indexes ...int) (reflect.Value, error)

GetAt returns an addressable source value whenever the supplied source is addressable. Nil ancestors yield an invalid Value without allocating them.

func (*Accessor) GetOptional

func (a *Accessor) GetOptional(target any) (value reflect.Value, present bool, err error)

GetOptional reads a compiled field without allocating nil ancestors. Present is false only for an absent root/ancestor; a nil leaf is a present typed value. Wrong owner types and inaccessible/invalid paths remain errors. Collection element paths requiring indexes must use GetAt instead.

func (*Accessor) Set

func (a *Accessor) Set(target any, value any) error

func (*Accessor) Type

func (a *Accessor) Type() reflect.Type

type CloneOptions

type CloneOptions struct {
	Fields map[reflect.Type][]string
}

CloneOptions limits cloning for exact struct types. Types absent from Fields retain normal CloneValue behavior. A present type with no fields clones as its zero value; omitted fields are neither read nor traversed. Names identify direct exported Go fields, not promoted fields or serialized aliases. All occurrences of a selected type use the same selection, preserving aliases. The caller must not mutate Fields or its slices during CloneValue.

func (*CloneOptions) Select

func (o *CloneOptions) Select(typ reflect.Type, paths ...string) error

Select adds promoted or dot-separated exported field paths using linked shape metadata. Every traversed holder receives a direct selection; no entire embedded struct is copied merely to reach a leaf. Pointer holders are resolved by type only, so selection never dereferences or initializes source values. Private holders and paths through collections are unsupported. Changes are atomic on error. Selections are unioned per exact type across all paths/calls. With no paths, typ receives an empty selection unless it already has one.

type Collection

type Collection[T any] struct{}

Collection normalizes exact typed values without mapping or converting their fields. It is independent of collection identity/association policy.

func (Collection[T]) Pointers

func (Collection[T]) Pointers(value any) ([]*T, error)

Pointers returns rows in source order. It accepts T, pointers to T, and slices/arrays (including named containers) of T or pointers to T. Pointers to collection containers are also accepted. Distinct entity types are rejected. Nil containers return nil; nonnil empty containers return an empty slice. Nil pointer elements retain their ordinal. Slice and pointer-array elements retain their addresses. Scalar values and value arrays require shallow copies for addressability; this operation is not a detached snapshot or identity map.

type CollectionMatchAdapter

type CollectionMatchAdapter[T any, K comparable, S comparable] interface {
	Key(S) (K, bool, error)
	CurrentKey(*T) (K, bool, error)
	Source(S) *T
	Equal(*T, S) (bool, error)
}

CollectionMatchAdapter supplies captured association evidence. Key must use captured identity presence; CurrentKey reads values, never working markers. Equal compares the selected processing baseline, not a previous database row. Adapter methods must not mutate entities or snapshots.

type CollectionMatchInput

type CollectionMatchInput[T any, S comparable] struct {
	Current  []*T
	Original []S
	// ByPointer is trusted capture-time authority from the SAME generation. It
	// may include records outside this local Original sequence (for example a
	// record moved between parent collections). It cannot override a different
	// local snapshot for the same source. Callers must never supply working or
	// foreign-generation snapshots here; this utility cannot establish provenance.
	ByPointer map[*T]S
	// PointerIdentity permits captured source addresses as identity. It must be
	// false for addresses of value-slice slots, which may change meaning on reorder.
	PointerIdentity bool
}

type CollectionMatchResult

type CollectionMatchResult[S comparable] struct {
	// Original is aligned with Current; S's zero value represents a nil item.
	Original []S
	// Changed reports membership/order/nil changes, not changed business values.
	Changed bool
}

type CollectionMatcher

type CollectionMatcher[T any, K comparable, S comparable] struct {
	Adapter CollectionMatchAdapter[T, K, S]
}

CollectionMatcher associates an initialized graph with captured processing snapshots. It does not match sparse requests to database rows or apply marks. Replaced pointers and relocated value records require both captured supplied identity and equal baseline evidence. Unknown/ambiguous records fail closed. Each nonzero snapshot may occur once per collection, even without an assigned key. Sharing it across independent collections or self-reference edges is valid.

func (CollectionMatcher[T, K, S]) Match

func (m CollectionMatcher[T, K, S]) Match(input CollectionMatchInput[T, S]) (CollectionMatchResult[S], error)

type Contract

type Contract struct{ Packages Packages }

func (Contract) Equivalent

func (c Contract) Equivalent(left, right string) (bool, error)

func (Contract) ValidateLinked

func (c Contract) ValidateLinked(expression string, typeOf reflect.Type) error

type Field

type Field struct {
	Name, TypeExpr      string
	ReflectedType       reflect.Type
	Tag                 reflect.StructTag
	Index               []int
	Anonymous, Exported bool
	PkgPath             string
	// contains filtered or unexported fields
}

func (Field) BuiltinType

func (f Field) BuiltinType() (string, bool)

func (Field) CanonicalType

func (f Field) CanonicalType() (string, error)

CanonicalType returns the complete field type expression under its actual declaring package/import authority. Promoted synthetic fields retain that authority, detached from later descriptor mutations. TypeExpr is unchanged.

func (Field) StructField

func (f Field) StructField() reflect.StructField

type FieldValue

type FieldValue struct {
	Accessor *Accessor
	Value    any
}

FieldValue associates a compiled field accessor with an assignable value. Values are not cloned; callers choose their own ownership/detachment policy.

type JSONField

type JSONField struct {
	Field                                       Field
	Name                                        string
	Quoted, OmitEmpty, OmitZero, OptionalHolder bool
}

JSONField is one selected encoding/json v1 field. Selection follows JSON dominance, not Go selector visibility. Field retains the exact source type. OptionalHolder means an anonymous pointer ancestor may omit the field.

func (JSONField) MayOmit

func (f JSONField) MayOmit() bool

MayOmit reports the standard encoder's omission policy. In particular, omitempty does not omit structs or nonzero-length fixed arrays. IsZero methods under omitzero remain author-controlled and therefore may omit a field.

type Lookup

type Lookup func(string) (*x.Type, error)

type Method

type Method struct {
	Name       string
	Parameters []string
	Results    []string
	Variadic   bool
}

Method is a receiver-free exported method signature. Types use full package identities and parameter names are intentionally not part of the contract.

type Packages

type Packages struct {
	Default string
	Imports map[string]string
}

type Reference

type Reference struct {
	Qualifier, Name, BaseName string
	Arguments                 []string
	Wrappers                  []Wrapper
}

func (Reference) Exported

func (r Reference) Exported() bool

func (Reference) QualifiedName

func (r Reference) QualifiedName() string

type Resolution

type Resolution struct {
	Identity   string
	Descriptor *x.Type
}

type Resolver

type Resolver struct {
	Lookup    Lookup
	Imports   map[string]string
	Package   string
	Rewriter  func(string) (string, error)
	Qualifier func(packagePath, suggested string) string
}

func (Resolver) Canonical

func (r Resolver) Canonical(source any) (string, error)

func (Resolver) CanonicalReference

func (r Resolver) CanonicalReference(source string) (string, string, error)

func (Resolver) Expression

func (r Resolver) Expression(typeOf reflect.Type) (string, error)

func (Resolver) Generic

func (r Resolver) Generic(source string) (Reference, error)

func (Resolver) Named

func (r Resolver) Named(source string) (string, error)

func (Resolver) Qualifiers

func (r Resolver) Qualifiers(source string) ([]string, error)

func (Resolver) Reference

func (r Resolver) Reference(source string) (Reference, error)

func (Resolver) References

func (r Resolver) References(source string) ([]string, error)

References returns canonical named type references in a type expression, including generic arguments, container elements and structural fields.

func (Resolver) Resolve

func (r Resolver) Resolve(source string) (*Resolution, error)

func (Resolver) Rewrite

func (r Resolver) Rewrite(source string) (string, error)

type Runtime

type Runtime struct {
	Imports map[string]string
	Lookup  func(string) (reflect.Type, error)
}

func (Runtime) AssignFields

func (Runtime) AssignFields(target any, fields ...FieldValue) error

AssignFields validates every write before publishing any of them. Existing pointer holders retain their identities; only missing holders are allocated. The caller must exclusively own target during assignment. Overlapping field paths are rejected rather than making their order part of the contract.

func (Runtime) CloneValue

func (Runtime) CloneValue(value any, options ...CloneOptions) (any, error)

CloneValue detaches a value's mutable graph without changing its concrete type. Pointer/map cycles and shared references are retained. Slices preserve length/capacity and clone the full backing capacity, including hidden values. Identical slice starts/types/capacities may share their cloned backing store. Other overlapping allocations (including interior pointers and offset slice aliases) are rejected rather than silently changing graph relationships. Functions, channels, unsafe pointers, synchronization state and unexported mutable internals are unsupported. time.Time is a known immutable exception. On error no result is published and the source is never mutated. The caller must prevent concurrent mutation of the source during the call. An optional CloneOptions selects exported fields of exact struct types; omitted fields are left zero and are not traversed, including service fields.

func (Runtime) Indirect

func (Runtime) Indirect(t reflect.Type) reflect.Type

func (Runtime) IsNil

func (Runtime) IsNil(value any) bool

IsNil reports nil interface values and typed nil values of every nil-capable Go kind. It does not dereference or invoke the supplied value.

func (Runtime) Pointer

func (Runtime) Pointer(t reflect.Type) reflect.Type

func (Runtime) Struct

func (r Runtime) Struct(fields []RuntimeField) (result reflect.Type, err error)

func (Runtime) Synthetic

func (Runtime) Synthetic(packagePath, name string, typeOf reflect.Type) (*x.Type, error)

func (Runtime) Type

func (r Runtime) Type(source string) (result reflect.Type, err error)

func (Runtime) WithZeroFields

func (r Runtime) WithZeroFields(source any, paths ...string) (any, error)

WithZeroFields returns the same runtime type with selected canonical field paths zeroed. Root and modified struct/pointer branches are copied; untouched branches remain shared. No mutation reaches the supplied value.

type RuntimeField

type RuntimeField struct {
	Name, TypeExpr string
	Type           reflect.Type
	Tag            reflect.StructTag
	Anonymous      bool
	PkgPath        string
}

type Source

type Source struct {
	Package string
	Imports map[string]SourceImport
	Fields  []SourceField
}

type SourceField

type SourceField struct {
	Owner         string
	Names         []string
	TypeExpr, Tag string
}

type SourceFieldEdits

type SourceFieldEdits struct {
	Types  []SourceFieldTypeUpdate
	Tags   []SourceFieldTagUpdate
	Remove []SourceFieldRemoval
}

SourceFieldEdits authorizes exact type changes and exact guarded removals. Empty edits retain AppendStructFields behavior.

type SourceFieldRemoval

type SourceFieldRemoval struct {
	Owner, Field, TypeExpr, Tag string
}

SourceFieldRemoval identifies one previously owned direct field. TypeExpr is its canonical package-qualified type, and Tag is its prior unquoted Go tag. Removal fails if the existing field has changed or remains in generated source.

type SourceFieldTagUpdate

type SourceFieldTagUpdate struct{ Owner, Field, Previous, Tag string }

SourceFieldTagUpdate authorizes one exact tag transition from a previously emitted tag. Customized tags fail closed; the field and surrounding bytes stay in place. Previous and Tag are unquoted Go struct tag values.

type SourceFieldTypeUpdate

type SourceFieldTypeUpdate struct {
	Owner, Field, TypeExpr string
}

SourceFieldTypeUpdate authorizes only the named, direct struct field's exact generated type. TypeExpr uses the generated source's import context. Existing tags remain destination-owned, including when the type is already identical.

type SourceImport

type SourceImport struct {
	Path, Alias string
	Explicit    bool
}

type SourceKind

type SourceKind string
const (
	SourceUnknown SourceKind = ""
	SourceShape   SourceKind = "shape"
	SourceProgram SourceKind = "program"
)

type SourceParser

type SourceParser struct{}

func (SourceParser) AppendStructFields

func (SourceParser) AppendStructFields(existing, generated []byte) ([]byte, error)

AppendStructFields updates a generated shape without replacing existing declarations. Existing bytes, field order, tags and comments remain owned by the destination; incompatible definitions require an explicit migration.

func (SourceParser) Classify

func (SourceParser) Classify(source []byte) (SourceKind, error)

Classify distinguishes type declarations (including their methods) from implementation files. Mixed shape and package-level execution declarations remain unknown so callers cannot delete possible user-owned type content.

func (SourceParser) EditStructFields

func (SourceParser) EditStructFields(existing, generated []byte, edits SourceFieldEdits) ([]byte, error)

EditStructFields preserves unrelated destination bytes while applying exact field authority. Removed fields' comments remain destination-owned. It never deletes whole types, methods, or unlisted fields.

func (SourceParser) Parse

func (p SourceParser) Parse(source []byte) (*Source, error)

Parse projects Go source bytes without requiring a filesystem artifact.

func (SourceParser) ParseFile

func (p SourceParser) ParseFile(filename string) (*Source, error)

func (SourceParser) UpdateStructFields

func (SourceParser) UpdateStructFields(existing, generated []byte, updates []SourceFieldTypeUpdate) ([]byte, error)

UpdateStructFields appends fields and applies exact, opt-in field type changes. Unlisted fields retain AppendStructFields conflict protection. It preserves destination bytes outside changed type expressions and necessary import edits; it does not replace declarations, tags, comments, methods or field order.

type Type

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

func Linked

func Linked(typeOf reflect.Type) *Type

func New

func New(descriptor *x.Type, lookup Lookup) *Type

func (*Type) Accessor

func (t *Type) Accessor(path string) (*Accessor, error)

func (*Type) BaseDescriptor

func (t *Type) BaseDescriptor() *x.Type

func (*Type) Descriptor

func (t *Type) Descriptor() *x.Type

func (*Type) Fields

func (t *Type) Fields() ([]Field, error)

func (*Type) FieldsAt

func (t *Type) FieldsAt(fieldPath string) ([]Field, error)

func (*Type) FirstStructField

func (t *Type) FirstStructField(names ...string) (reflect.StructField, bool)

func (*Type) Implements

func (t *Type) Implements(contract reflect.Type, pointer bool) (bool, error)

Implements checks the requested value/pointer method set against a runtime interface contract. Linked receivers use Go's exact implementation test; synthetic receivers use the canonical exported method-set owner.

func (*Type) IndexedAccessor

func (t *Type) IndexedAccessor(path string) (*Accessor, error)

IndexedAccessor compiles a field path that can cross slice/array elements. Each collection crossed before the next field consumes one GetAt index; remaining indexes address elements of the final field.

func (*Type) IsStruct

func (t *Type) IsStruct() (bool, error)

IsStruct reports the actual named value's structural kind. Unlike Fields it does not unwrap collections into their element rows.

func (*Type) JSONFields

func (t *Type) JSONFields() ([]JSONField, error)

JSONFields enumerates linked standard-library JSON fields in encoding order. It does not inspect values, invoke custom code, or construct runtime types.

func (*Type) Methods

func (t *Type) Methods(pointer bool) ([]Method, error)

Methods returns the exported method signatures available to the requested receiver. A pointer receiver includes value-receiver methods. Returned slices do not alias the descriptor. Synthetic declarations must carry method metadata.

func (*Type) NamedDescriptor

func (t *Type) NamedDescriptor() *x.Type

func (*Type) References

func (t *Type) References() ([]string, error)

References enumerates direct structural dependencies of a descriptor through the same import authority as field/type resolution. Methods are linked with their owning compiled type and do not create structural catalog entries.

func (*Type) ResolveField

func (t *Type) ResolveField(path string) (*Resolution, error)

ResolveField resolves an exported path using native visible-field selection. Identity is the complete canonical field type. Descriptor follows Resolver's named-type lookup contract and may be nil for builtin/unregistered types.

func (*Type) StructField

func (t *Type) StructField(fieldPath string) (reflect.StructField, error)

type Wrapper

type Wrapper struct {
	Kind   WrapperKind
	Length string
}

type WrapperKind

type WrapperKind string
const (
	WrapperPointer WrapperKind = "pointer"
	WrapperSlice   WrapperKind = "slice"
	WrapperArray   WrapperKind = "array"
)

Jump to

Keyboard shortcuts

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