gen

package
v1.1.5 Latest Latest
Warning

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

Go to latest
Published: Jul 23, 2026 License: MIT Imports: 26 Imported by: 0

Documentation

Overview

Package gen implements code generation from TL schema.

Index

Constants

View Source
const LayerPolicyVersion = 1

Variables

This section is empty.

Functions

func Funcs

func Funcs() template.FuncMap

Funcs returns functions which used in templates.

func MarshalLayerPolicyAudit

func MarshalLayerPolicyAudit(document LayerPolicyAuditDocument) ([]byte, error)

MarshalLayerPolicyAudit renders a deterministic retained/stale/new report.

func MarshalLayerPolicyDocument

func MarshalLayerPolicyDocument(document LayerPolicyDocument) ([]byte, error)

MarshalLayerPolicyDocument renders a deterministic strict policy document.

func MarshalLayerPolicyTemplate

func MarshalLayerPolicyTemplate(report LayerObligationReport) ([]byte, error)

MarshalLayerPolicyTemplate renders a stable, reviewable JSON policy skeleton. Feeding an unedited skeleton back into gotdgen fails closed because every action is empty.

func Template

func Template() *template.Template

Template parses and returns vendored code generation templates.

Types

type FileSystem

type FileSystem interface {
	WriteFile(baseName string, source []byte) error
}

FileSystem represents a directory of generated package.

type GenerateFlags

type GenerateFlags struct {
	// Client enables client generation.
	Client bool
	// Registry enables type ID registry generation.
	Registry bool
	// Server enables experimental server generation.
	Server bool
	// Handlers enables update handler generation.
	Handlers bool
	// UpdatesClassifier enables updates classifier generation.
	UpdatesClassifier bool
	// GetSet enables getters and setters generation.
	GetSet bool
	// Mapping enables mapping helpers generation.
	Mapping bool
	// Slices enables slice helpers generation.
	Slices bool
	// TDLibJSON enables TDLib API JSON encoders and decoders generation.
	TDLibJSON bool
}

GenerateFlags is flags for optional generation.

func (*GenerateFlags) RegisterFlags

func (s *GenerateFlags) RegisterFlags(set *flag.FlagSet)

RegisterFlags registers GenerateFlags fields in given flag set.

type Generator

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

Generator generates go types from tl.Schema.

func NewGenerator

func NewGenerator(s *tl.Schema, genOpt GeneratorOptions) (*Generator, error)

NewGenerator initializes and returns new Generator from tl.Schema.

func NewSchemaSetGenerator

func NewSchemaSetGenerator(s *SchemaSet, genOpt GeneratorOptions) (*Generator, error)

NewSchemaSetGenerator initializes a Generator from a normalized collection of layer schemas. The canonical profile drives the existing public Go bindings; all profiles remain attached to the Generator for layer-aware backends. This keeps parsing, semantic identity and wire variants in one IR instead of rebuilding them in a companion generator.

func (*Generator) LayerConversionPlan

func (g *Generator) LayerConversionPlan() *LayerConversionPlan

LayerConversionPlan returns the single policy-applied conversion plan, or nil for a legacy single-schema Generator. Callers must treat it as immutable.

func (*Generator) LayerObligations

func (g *Generator) LayerObligations(policy LayerObligationPolicy) (LayerObligationReport, error)

LayerObligations analyzes the normalized SchemaSet attached to Generator.

func (*Generator) MarshalLayerExecutionAudit added in v1.1.0

func (g *Generator) MarshalLayerExecutionAudit() ([]byte, error)

MarshalLayerExecutionAudit returns deterministic review evidence for the sparse plan selection. The complete schema remains generation-only; this document contains identities and route decisions, never runtime TypeRefs.

func (*Generator) SchemaSet

func (g *Generator) SchemaSet() *SchemaSet

SchemaSet returns the normalized multi-schema input, or nil when Generator was created through the legacy single-schema entry point.

func (*Generator) WriteSource

func (g *Generator) WriteSource(fs FileSystem, pkgName string, t *template.Template) error

WriteSource writes generated definitions to fs.

func (*Generator) WriteTLProfileSource added in v1.1.0

func (g *Generator) WriteTLProfileSource(fs FileSystem, pkgName string, t *template.Template) error

WriteTLProfileSource writes the public multi-layer sidecar. Canonical Go bindings remain owned by WriteSource; this target contains only exact profile metadata and, as later stages are enabled, sparse execution plans.

type GeneratorOptions

type GeneratorOptions struct {
	// DocBaseURL is a documentation base URL.
	// If DocBaseURL is set, Generator will embed documentation references to generated code.
	//
	// If base is https://core.telegram.org, documentation content will be also
	// embedded.
	DocBaseURL string
	// DocLineLimit sets GoDoc comment line length limit.
	DocLineLimit int
	// LayerPolicy resolves exact non-mechanical decisions for SchemaSet code
	// generation. It is ignored by the legacy single-schema entry point.
	LayerPolicy LayerObligationPolicy
	GenerateFlags
}

GeneratorOptions is a Generator options structure.

func (*GeneratorOptions) RegisterFlags

func (s *GeneratorOptions) RegisterFlags(set *flag.FlagSet)

RegisterFlags registers GeneratorOptions fields in given flag set.

type LayerAvailability

type LayerAvailability uint8

LayerAvailability is the exact relationship between the canonical schema and one concrete wire profile. Availability is intentionally independent from body and RPC result conversion.

const (
	LayerAvailabilityPresent LayerAvailability = iota
	LayerAvailabilityCanonicalOnly
	LayerAvailabilityProfileOnly
	LayerAvailabilityAbsent
)

func (LayerAvailability) String

func (a LayerAvailability) String() string

type LayerConversionPlan

type LayerConversionPlan struct {
	CanonicalLayer int
	Profiles       []LayerProfileConversion
	Report         LayerObligationReport
}

LayerConversionPlan is the single conversion analysis shared by obligation reporting, static codecs, metadata, and RPC result descriptors.

func AnalyzeLayerConversions

func AnalyzeLayerConversions(schemaSet *SchemaSet, policy LayerObligationPolicy) (*LayerConversionPlan, error)

AnalyzeLayerConversions builds and applies policy to the single normalized conversion model. No generated backend is involved in this phase.

func (*LayerConversionPlan) Profile

func (p *LayerConversionPlan) Profile(layer int) *LayerProfileConversion

Profile returns the exact profile plan. Layers are never clamped.

type LayerFamilyConversion

type LayerFamilyConversion struct {
	Key           semantic.SemanticKey
	Canonical     *semantic.ProfileVariant
	Profile       *semantic.ProfileVariant
	Availability  LayerAvailability
	BodyChanged   bool
	ResultChanged bool
	Fields        []LayerFieldMapping
	Obligations   []LayerObligation
}

LayerFamilyConversion is the single semantic conversion decision for one family in one exact profile. Emitters project this model; they must not independently re-classify fields, availability, or result types.

func (LayerFamilyConversion) BodyObligations

func (f LayerFamilyConversion) BodyObligations() []LayerObligation

BodyObligations returns decisions which affect request/constructor bodies.

func (LayerFamilyConversion) FieldProjectionObligations

func (f LayerFamilyConversion) FieldProjectionObligations() []LayerObligation

FieldProjectionObligations returns canonical fields which the exact target profile cannot carry. Generated encoders evaluate these policies only when the corresponding runtime field is present.

func (LayerFamilyConversion) ProjectionObligations

func (f LayerFamilyConversion) ProjectionObligations() []LayerObligation

ProjectionObligations returns the projection decision for a constructor which is absent from the target profile. Update projections take precedence because every canonical-only update also carries the generic new-only obligation. Policy may override the mechanical new-only drop with an explicit projection, rejection, or unavailable decision.

func (LayerFamilyConversion) ResultObligations

func (f LayerFamilyConversion) ResultObligations() []LayerObligation

ResultObligations returns decisions for a method's complete result TypeRef.

type LayerFieldMapping

type LayerFieldMapping struct {
	CanonicalOrdinal int
	ProfileOrdinal   int
	CanonicalName    string
	ProfileName      string
}

LayerFieldMapping joins a target profile field with its canonical field. A -1 ordinal is an explicitly absent side, never an inferred alias.

type LayerObligation

type LayerObligation struct {
	Key       LayerObligationKey
	Kind      LayerObligationKind
	Layer     int
	Direction LayerObligationDirection

	Semantic      semantic.SemanticKey
	OtherSemantic semantic.SemanticKey
	WireID        uint32
	OtherWireID   uint32
	Field         string
	OtherField    string
	FlagWord      string
	FlagBit       uint8
	Fields        []string
	SourceType    string
	TargetType    string
	SourceShape   semantic.ShapeDigest
	TargetShape   semantic.ShapeDigest

	// Resolution is copied from an exact matching policy entry. A zero Action
	// means the obligation is unresolved.
	Resolution LayerObligationResolution
}

LayerObligation describes one explicit compatibility decision.

type LayerObligationDirection

type LayerObligationDirection string

LayerObligationDirection identifies the conversion path requiring policy.

const (
	LayerDirectionCanonicalToProfile LayerObligationDirection = "canonical-to-profile"
	LayerDirectionProfileToCanonical LayerObligationDirection = "profile-to-canonical"
	LayerDirectionBoth               LayerObligationDirection = "both"
	LayerDirectionProfile            LayerObligationDirection = "profile"
)

type LayerObligationKey

type LayerObligationKey string

LayerObligationKey is copied verbatim into policy. It is a domain-separated digest of all machine-relevant coordinates, not of diagnostic prose.

type LayerObligationKind

type LayerObligationKind string

LayerObligationKind is one non-mechanical cross-layer decision exposed by schema generation. Values are stable policy identifiers.

const (
	LayerObligationAlias            LayerObligationKind = "alias"
	LayerObligationRequired         LayerObligationKind = "required"
	LayerObligationIncompatible     LayerObligationKind = "incompatible"
	LayerObligationResult           LayerObligationKind = "result"
	LayerObligationOldOnly          LayerObligationKind = "old-only"
	LayerObligationNewOnly          LayerObligationKind = "new-only"
	LayerObligationAtomicFlagGroup  LayerObligationKind = "atomic-flag-group"
	LayerObligationUpdateProjection LayerObligationKind = "update-projection"
	LayerObligationFieldProjection  LayerObligationKind = "field-projection"
	LayerObligationFieldReplacement LayerObligationKind = "field-replacement"
	LayerObligationDiscard          LayerObligationKind = "discard"
	LayerObligationPrivate          LayerObligationKind = "private"
)

type LayerObligationPolicy

type LayerObligationPolicy struct {
	Entries []LayerObligationPolicyEntry
}

LayerObligationPolicy is deliberately a slice: duplicate keys are rejected instead of being silently overwritten by a map literal or decoder.

func LoadLayerPolicy

func LoadLayerPolicy(path string) (LayerObligationPolicy, error)

LoadLayerPolicy reads a policy document from path.

func ReadLayerPolicy

func ReadLayerPolicy(r io.Reader) (LayerObligationPolicy, error)

ReadLayerPolicy decodes one strict JSON policy document.

type LayerObligationPolicyEntry

type LayerObligationPolicyEntry struct {
	Key        LayerObligationKey        `json:"key"`
	Resolution LayerObligationResolution `json:"resolution"`
}

LayerObligationPolicyEntry resolves exactly one generated key.

type LayerObligationReport

type LayerObligationReport struct {
	Obligations []LayerObligation
}

LayerObligationReport is deterministic for a SchemaSet and policy.

func AnalyzeLayerObligations

func AnalyzeLayerObligations(schemaSet *SchemaSet, policy LayerObligationPolicy) (LayerObligationReport, error)

AnalyzeLayerObligations discovers non-mechanical compatibility decisions and applies policy by exact generated key. Unknown policy keys are stale errors.

func (LayerObligationReport) Unresolved

func (r LayerObligationReport) Unresolved() []LayerObligation

Unresolved returns a detached list of obligations with no policy decision.

type LayerObligationResolution

type LayerObligationResolution struct {
	Action LayerResolutionAction `json:"action"`
	Hook   string                `json:"hook,omitempty"`
	Target string                `json:"target,omitempty"`
	Note   string                `json:"note,omitempty"`
}

LayerObligationResolution is the machine-checked action for one exact key. Hook is required for generated adapter/project/alias calls. Note is human context only and never resolves an obligation by itself.

type LayerPolicyAuditDocument

type LayerPolicyAuditDocument struct {
	Version  int                          `json:"version"`
	Retained []LayerObligationPolicyEntry `json:"retained"`
	Stale    []LayerObligationPolicyEntry `json:"stale"`
	New      []LayerObligationPolicyEntry `json:"new"`
}

LayerPolicyAuditDocument is the fail-safe migration view produced when a schema import changes obligation keys. Retained entries still match an exact generated obligation, stale entries are never copied to the merged policy, and New contains unresolved, deliberately unapproved skeleton entries.

func AuditLayerPolicy

AuditLayerPolicy partitions an existing strict policy without treating stale keys as approval. It still validates duplicates and every retained action.

func (LayerPolicyAuditDocument) MergedPolicy

MergedPolicy drops stale entries, retains only exact reviewed decisions, and appends the unresolved skeleton. The result intentionally fails normal generation until every new action has been reviewed.

type LayerPolicyDocument

type LayerPolicyDocument struct {
	Version int                          `json:"version"`
	Entries []LayerObligationPolicyEntry `json:"entries"`
}

LayerPolicyDocument is the strict, versioned on-disk policy consumed by gotdgen. Exact obligation keys already contain both source and target shape digests, so unchanged entries remain valid when a newer Layer is appended.

func BuildLayerPolicyTemplate

func BuildLayerPolicyTemplate(report LayerObligationReport) LayerPolicyDocument

BuildLayerPolicyTemplate returns a deterministic document containing only unresolved non-mechanical decisions. Empty actions are intentional: the document is a review artifact and cannot accidentally approve a behavior.

type LayerProfileConversion

type LayerProfileConversion struct {
	Layer       int
	Families    []LayerFamilyConversion
	Obligations []LayerObligation
}

LayerProfileConversion contains deterministic family plans for one profile.

func (*LayerProfileConversion) Family

Family returns the category-qualified family plan, if present.

type LayerResolutionAction

type LayerResolutionAction string

LayerResolutionAction is a generated behavior, not free-form approval text.

const (
	LayerResolveUnavailable     LayerResolutionAction = "unavailable"
	LayerResolveReject          LayerResolutionAction = "reject"
	LayerResolveRejectIfPresent LayerResolutionAction = "reject-if-present"
	LayerResolveDrop            LayerResolutionAction = "drop"
	LayerResolveAlias           LayerResolutionAction = "alias"
	LayerResolveDefault         LayerResolutionAction = "default"
	LayerResolveAdapter         LayerResolutionAction = "adapter"
	LayerResolveProject         LayerResolutionAction = "project"
	LayerResolveAllow           LayerResolutionAction = "allow"
)

type SchemaProfile

type SchemaProfile = semantic.SchemaModel

SchemaProfile is one parsed and validated TL schema at an exact API layer.

type SchemaSet

type SchemaSet = semantic.Universe

SchemaSet is the normalized collection of all supported TL schema profiles. It is the single cross-backend IR consumed by both the canonical Go binding backend and the layer-aware static wire backend.

func NewSchemaSet

func NewSchemaSet(canonicalLayer int, profiles ...*SchemaProfile) (*SchemaSet, error)

NewSchemaSet validates and joins profiles around one canonical layer.

type SchemaSource

type SchemaSource = semantic.SourceRef

SchemaSource identifies the immutable input used to build a profile.

Directories

Path Synopsis
Package td contains generated code from example schema and is used for codegen testing.
Package td contains generated code from example schema and is used for codegen testing.
Package semantic builds a layer-aware, Go-backend-independent model of TL schemas.
Package semantic builds a layer-aware, Go-backend-independent model of TL schemas.

Jump to

Keyboard shortcuts

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