language

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 19, 2026 License: MIT Imports: 13 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package language implements the Haskell/ML-style refinement front end. Syntax trees are compiler-owned intermediate data, not runtime payload values.

Index

Examples

Constants

View Source
const DefaultSubstitutionNodes = 1 << 20

Variables

This section is empty.

Functions

func AffectedPaths

func AffectedPaths(predicate *Expr, enclosing string) []string

AffectedPaths returns the statically visible payload paths referenced by one where-clause predicate. It follows only projection chains rooted directly at the clause's `it`; named functions and local aliases are deliberately not expanded. When extraction exceeds its fixed work/output bounds or finds no narrower dependency, the enclosing path remains the conservative answer.

func AppendReleasePolicyFooter

func AppendReleasePolicyFooter(base string, policy *ReleasePolicy) (string, error)

AppendReleasePolicyFooter appends to exact bytes; it never replaces an existing footer or rewrites contract formatting.

func Format

func Format(module *Module) string

Format preserves declaration/equation order and emits a stable source form. Comments/formatting are not retained here; lossless native provenance lives in the native document layer, not this Haskell-like pretty-printer.

func FormatExpression

func FormatExpression(e *Expr) string

FormatExpression produces deterministic, explicitly grouped source. It does not claim equivalence of arbitrarily rewritten predicates or change && into separate where clauses. Source provenance is tracked separately from layout.

func FormatOpenAPI

func FormatOpenAPI(declaration *OpenAPIDeclaration) string

FormatOpenAPI emits a stable complete declaration, not a payload schema. As with Format, its input must be a valid parser/compiler-owned syntax tree.

func FormatPattern

func FormatPattern(p *Pattern) string

func FormatQualifiedType

func FormatQualifiedType(constraints []CapabilityConstraint, signature *Type) string

FormatQualifiedType renders a signature context without changing the type. One constraint uses the compact form; multiple constraints are parenthesized.

func FormatReleasePolicyJSON

func FormatReleasePolicyJSON(policy *ReleasePolicy) ([]byte, error)

FormatReleasePolicyJSON emits stable field order and preserves approval order.

func FormatType

func FormatType(t *Type) string

func ShowDataWithoutValidation

func ShowDataWithoutValidation(data value.Data, limits validation.Limits) (text value.Text, failure error)

ShowDataWithoutValidation displays a structurally representable in-memory payload without asserting its refinements. Invalid bypass-created values may be shown, but validating ReadData never accepts them without checking rules.

Types

type AppliedType

type AppliedType struct {
	Constructor *Type
	Argument    *Type
}

type Apply

type Apply struct {
	Function *Expr
	Argument *Expr
}

type ArrowType

type ArrowType struct {
	Argument *Type
	Result   *Type
}

type Binary

type Binary struct {
	Operator string
	Left     *Expr
	Right    *Expr
}

type BindPattern

type BindPattern struct {
	Name string
}

type BoolLiteral

type BoolLiteral struct {
	Value bool
}

type BreakingFixApproval

type BreakingFixApproval struct {
	ReleaseComparison
	Justification string `json:"justification"`
}

type CapabilityConstraint

type CapabilityConstraint struct {
	Capability string
	Variable   string
	At         Span
}

CapabilityConstraint is an authored type-class requirement on one of a function signature's type variables. The checked snapshot separately exposes the complete explicit plus inferred capability set.

type Case

type Case struct {
	Value *Expr
	Arms  []CaseArm
}

type CaseArm

type CaseArm struct {
	Pattern *Pattern
	Body    *Expr
	At      Span
}

type CheckedModule

type CheckedModule struct {
	Syntax            *Module
	Inferred          map[*Expr]*Type
	FunctionScopes    map[string]map[string]string
	DeclarationScopes map[string]map[string]string
	// FunctionCapabilities contains the effective explicit plus inferred
	// requirements in stable order. Its entries are detached from compiler state.
	FunctionCapabilities map[string][]CapabilityConstraint
}

CheckedModule is a caller-owned code-generation snapshot. Inferred expression keys belong to Syntax's tree; type-variable scopes connect generic declaration parameters to the checker's reified symbols. Mutating any part of the snapshot cannot change the compiled Program or a later snapshot.

type CheckedPayloadType

type CheckedPayloadType struct {
	Module CheckedModule
	Type   *Type
}

CheckedPayloadType is a caller-owned generation snapshot. Type and all module expression pointers belong to Module's inferred-type map. Mutating a snapshot cannot change the handle, its Program, or a later snapshot.

type CompatibilityApproval

type CompatibilityApproval struct {
	ReleaseComparison
	Reason string `json:"reason"`
}

type Conditional

type Conditional struct {
	Condition *Expr
	Then      *Expr
	Else      *Expr
}

type ConsPattern

type ConsPattern struct {
	Head *Pattern
	Tail *Pattern
}

type ConstructorPattern

type ConstructorPattern struct {
	Name      string
	Arguments []*Pattern
}

type Equation

type Equation struct {
	Patterns []*Pattern
	Body     *Expr
	At       Span
}

type Error

type Error struct {
	Code    string
	At      Span
	Message string
}

func (*Error) Error

func (e *Error) Error() string

type Expr

type Expr struct {
	Form ExprForm
	At   Span
}

func ParseExpression

func ParseExpression(source string) (expression *Expr, failure error)

type ExprForm

type ExprForm interface {
	// contains filtered or unexported methods
}

type Field

type Field struct {
	Name string
	Type *Type
	At   Span
}

type FieldValue

type FieldValue struct {
	Name  string
	Value *Expr
	At    Span
}

type FloatConversion

type FloatConversion struct {
	Mode string
	Type string
}

FloatConversion identifies the explicit finite IEEE conversion built-ins. Exact conversion and rounding are distinct language operations.

func FixedFloatConversion

func FixedFloatConversion(name string) (FloatConversion, bool)

type Function

type Function struct {
	Name        string
	Constraints []CapabilityConstraint
	Signature   *Type
	Equations   []Equation
	At          Span
}

type Import

type Import struct {
	Path string
	At   Span
}

type ImportError

type ImportError struct {
	Code     string
	SourceID string
	Message  string
	Cause    error
}

ImportError attributes original parse/import errors to their source file. Errors from flattened cross-module type checking identify the owning file, but their span belongs to the canonical flattened source, not original bytes.

func (*ImportError) Error

func (e *ImportError) Error() string

func (*ImportError) Unwrap

func (e *ImportError) Unwrap() error

type IntegerConversion

type IntegerConversion struct {
	Mode   string
	Type   string
	Bits   uint
	Signed bool
}

IntegerConversion identifies the explicit fixed-width built-in families. User-defined functions still take precedence over built-in names.

func FixedIntegerConversion

func FixedIntegerConversion(name string) (IntegerConversion, bool)

type Let

type Let struct {
	Name       string
	Annotation *Type
	Value      *Expr
	Body       *Expr
}

type ListLiteral

type ListLiteral struct {
	Elements []*Expr
}

type ListPattern

type ListPattern struct {
	Elements []*Pattern
}

type ListType

type ListType struct {
	Element *Type
}

type LiteralPattern

type LiteralPattern struct {
	Value *Expr
}

type MapLiteral

type MapLiteral struct {
	Entries []MapValue
}

type MapValue

type MapValue struct {
	Key   string
	Value *Expr
	At    Span
}

MapValue retains the original quoted token. Map identity uses the decoded UTF-16 key, so alternate escape spellings cannot create distinct entries.

type Module

type Module struct {
	Source        string
	Package       string
	Imports       []Import
	Limits        SchemaLimits
	ReleasePolicy *ReleasePolicy
	OpenAPI       *OpenAPIDeclaration
	Types         []TypeDecl
	Functions     []Function
	// contains filtered or unexported fields
}

func Parse

func Parse(source string) (module *Module, failure error)

Parse parses declarations without executing predicates or loading imports. Import resolution and type checking are separate compilation phases.

type NamedType

type NamedType struct {
	Name string
}

type NumberLiteral

type NumberLiteral struct {
	Text string
}

type OpenAPIBodyDeclaration

type OpenAPIBodyDeclaration struct {
	MediaType string
	FieldPath []string
	Required  *bool
	At        Span
}

type OpenAPIDeclaration

type OpenAPIDeclaration struct {
	Version    string
	Title      string
	APIVersion string
	Operations []OpenAPIOperationDeclaration
	At         Span
}

OpenAPIDeclaration defines a complete API in the same source as its checked request/response types. It is not a payload root or an executable predicate.

type OpenAPIHeaderDeclaration

type OpenAPIHeaderDeclaration struct {
	Name      string
	FieldPath []string
	Required  *bool
	At        Span
}

type OpenAPIOperationDeclaration

type OpenAPIOperationDeclaration struct {
	OperationID string
	Method      string
	Path        string
	Request     OpenAPIRequestDeclaration
	Responses   []OpenAPIResponseDeclaration
	At          Span
}

type OpenAPIParameterDeclaration

type OpenAPIParameterDeclaration struct {
	In        string
	Name      string
	FieldPath []string
	// Nil infers native presence from the checked field type. A nonnil value
	// is an explicit required/optional assertion, not permission to drop data.
	Required *bool
	At       Span
}

type OpenAPIRequestDeclaration

type OpenAPIRequestDeclaration struct {
	TypeName   string
	Parameters []OpenAPIParameterDeclaration
	Body       *OpenAPIBodyDeclaration
	At         Span
}

type OpenAPIResponseDeclaration

type OpenAPIResponseDeclaration struct {
	Status      string
	TypeName    string
	Description string
	Headers     []OpenAPIHeaderDeclaration
	Body        *OpenAPIBodyDeclaration
	ContextType string
	At          Span
}

type Pattern

type Pattern struct {
	Form PatternForm
	At   Span
}

type PatternForm

type PatternForm interface {
	// contains filtered or unexported methods
}

type PayloadType

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

PayloadType is an immutable, closed type checked in one Program's environment. It can instantiate generic declarations, compose records/collections and add arbitrary statically checked refinements. Creating a handle executes no rules. Its zero value is invalid; use Program.PayloadType to obtain a checked handle.

func (*PayloadType) CheckedSyntax

func (t *PayloadType) CheckedSyntax() CheckedPayloadType

func (*PayloadType) Formatted

func (t *PayloadType) Formatted() string

func (*PayloadType) ReadData

func (t *PayloadType) ReadData(text value.Text, caller validation.Limits) (value.Data, validation.Report)

func (*PayloadType) ReadDataWithoutRefinements

func (t *PayloadType) ReadDataWithoutRefinements(text value.Text, caller validation.Limits) (value.Data, validation.Report)

ReadDataWithoutRefinements is the explicit structural-only text boundary for this closed type, including generic and inline-refined targets. It never runs a where clause and never bypasses shape, representation or resource checks.

func (*PayloadType) Source

func (t *PayloadType) Source() string

func (*PayloadType) Syntax

func (t *PayloadType) Syntax() *Type

func (*PayloadType) ValidateData

func (t *PayloadType) ValidateData(data value.Data, caller validation.Limits) validation.Report

func (*PayloadType) ValidateDataWithoutRefinements

func (t *PayloadType) ValidateDataWithoutRefinements(data value.Data, caller validation.Limits) validation.Report

type Position

type Position struct {
	Offset int
	Line   int
	Column int
}

type Program

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

Program owns a parsed and statically checked module. It exposes no mutable compiler state. Imported modules must be resolved before using Compile; the standalone entry point refuses unresolved imports instead of ignoring them.

func Compile

func Compile(source string) (program *Program, failure error)

Compile performs static checks before a Program can be evaluated or emitted.

func (*Program) CheckedSyntax

func (p *Program) CheckedSyntax() CheckedModule

func (*Program) Formatted

func (p *Program) Formatted() string

func (*Program) OpenAPI

func (p *Program) OpenAPI() *OpenAPIDeclaration

OpenAPI returns a detached source declaration. Native assembly separately validates protocol, field binding, and wire-representation semantics.

func (*Program) PayloadType

func (p *Program) PayloadType(source string) (target *PayloadType, failure error)

func (*Program) ReadData

func (p *Program) ReadData(root string, text value.Text, caller validation.Limits) (data value.Data, report validation.Report)

ReadData is the validating canonical-text boundary for a named root. It never evaluates source text. An invalid or indeterminate result exposes no candidate value; callers must check the report before using the returned Data.

Example
package main

import (
	"fmt"
	"goforge.dev/refine/language"
	"goforge.dev/refine/validation"
	"goforge.dev/refine/value"
)

func main() {
	program, err := language.Compile("type Positive = Int where it > 0")
	if err != nil {
		panic(err)
	}
	input, err := value.TextFromUTF8("21")
	if err != nil {
		panic(err)
	}
	payload, report := program.ReadData("Positive", input, validation.Limits{})
	fmt.Println(validation.StateName(report.State()))
	if validation.StateName(report.State()) != "valid" {
		return
	}
	shown, err := language.ShowDataWithoutValidation(payload, validation.Limits{})
	if err != nil {
		panic(err)
	}
	text, err := shown.UTF8()
	if err != nil {
		panic(err)
	}
	fmt.Println(text)
}
Output:
valid
21

func (*Program) ReadDataWithoutRefinements

func (p *Program) ReadDataWithoutRefinements(root string, text value.Text, caller validation.Limits) (value.Data, validation.Report)

ReadDataWithoutRefinements explicitly bypasses where clauses, not structural validation. It uses the same non-executing text grammar, typed representation, exact numeric/timestamp checks and resource limits as ReadData. An invalid or indeterminate structural result exposes no candidate. A successful result is not evidence that the refinements hold; call ValidateData to establish that.

func (*Program) ReleasePolicy

func (p *Program) ReleasePolicy() *ReleasePolicy

ReleasePolicy returns detached entry-file metadata, not imported approvals.

func (*Program) SchemaLimits

func (p *Program) SchemaLimits() validation.Limits

func (*Program) Source

func (p *Program) Source() string

func (*Program) Summary

func (p *Program) Summary() string

func (*Program) Syntax

func (p *Program) Syntax() *Module

func (*Program) ValidateData

func (p *Program) ValidateData(root string, data value.Data, caller validation.Limits) validation.Report

ValidateData checks a named, non-parameterized root declaration against an immutable language payload. Parameterized types may occur inside that root. This is not JSON/Avro decoding: Maybe/Nullable/data alternatives use Data's explicit constructors. No native wire representation is guessed here. Unsupported execution features produce Indeterminate, never silent success. Program and Data are immutable; each call owns its meters and diagnostics.

Example
package main

import (
	"fmt"
	"goforge.dev/refine/language"
	"goforge.dev/refine/validation"
	"goforge.dev/refine/value"
)

func main() {
	program, err := language.Compile(`
type Person = { age :: Int where it >= 0 }
type Child = Person
  where it.age < 18
    @code "person.child_age"
    @message "Age must be less than 18"
`)
	if err != nil {
		panic(err)
	}
	payload, err := value.Record([]value.DataField{{Name: "age", Value: value.OfNumber(value.Integer(21))}})
	if err != nil {
		panic(err)
	}
	report := program.ValidateData("Child", payload, validation.Limits{})
	fmt.Println(validation.StateName(report.State()))
	for _, diagnostic := range report.Diagnostics() {
		fmt.Println(diagnostic.Code + ": " + diagnostic.Message)
	}
}
Output:
invalid
person.child_age: Age must be less than 18

func (*Program) ValidateDataWithoutRefinements

func (p *Program) ValidateDataWithoutRefinements(root string, data value.Data, caller validation.Limits) validation.Report

ValidateDataWithoutRefinements is the explicit structural-only bypass used by generated model factories. It still checks declared shapes, fixed-width representability, timestamps and resource limits; it never changes the input.

type Project

type Project struct {
	Record *Expr
	Field  string
}

type RecordLiteral

type RecordLiteral struct {
	Fields []FieldValue
}

type RecordType

type RecordType struct {
	Fields []Field
}

type RefinedType

type RefinedType struct {
	Base  *Type
	Rules []Where
}

type ReleaseComparison

type ReleaseComparison struct {
	Baseline       string `json:"baseline"`
	BaselineSHA256 string `json:"baselineSha256"`
	SnapshotSHA256 string `json:"snapshotSha256"`
	Direction      string `json:"direction"`
}

ReleaseComparison identifies one exact, directional release comparison. It is metadata, never a predicate or a source of runtime authority.

type ReleasePolicy

type ReleasePolicy struct {
	Version       int                     `json:"version"`
	Overrides     []CompatibilityApproval `json:"overrides,omitempty"`
	BreakingFixes []BreakingFixApproval   `json:"breakingFixes,omitempty"`
}

func ParseReleasePolicyJSON

func ParseReleasePolicyJSON(input []byte) (*ReleasePolicy, error)

ParseReleasePolicyJSON rejects duplicate/unknown keys, noncanonical identities, null containers and unbounded metadata. It does not approve a comparison; the release planner must bind every record to its actual comparison identity.

func SplitReleasePolicyFooter

func SplitReleasePolicyFooter(source string) (base string, policy *ReleasePolicy, present bool, failure error)

SplitReleasePolicyFooter masks only the owned suffix, not contract bytes. Malformed or misplaced real annotations fail rather than becoming authority.

type SchemaLimits

type SchemaLimits struct {
	Total  uint64
	Clause uint64
	At     Span
}

SchemaLimits are the contract-authored total validation budget and the default budget for a where clause. Zero is the immutable unspecified value; runtimes substitute the documented defaults.

type SourceBundle

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

func CompileSources

func CompileSources(entry string, sources map[string]string) (*SourceBundle, error)

CompileSources resolves Haskell-like imports exclusively from supplied source strings. It performs no I/O. IDs are canonical relative slash-separated paths; an import is relative to its importing file and must remain within that root. Shared dependencies are included once, in deterministic dependency-first order. Cycles and ambiguous cross-module declaration names reject explicitly. Packages are output namespaces, not automatic symbol qualification: the entry namespace controls the flattened program and each original namespace is kept.

func (*SourceBundle) Entry

func (b *SourceBundle) Entry() string

func (*SourceBundle) Files

func (b *SourceBundle) Files() []SourceFile

func (*SourceBundle) Program

func (b *SourceBundle) Program() *Program

func (*SourceBundle) ReleasePolicy

func (b *SourceBundle) ReleasePolicy() *ReleasePolicy

func (*SourceBundle) Sources

func (b *SourceBundle) Sources() map[string]string

type SourceFile

type SourceFile struct {
	ID        string
	Source    string
	Digest    string
	Namespace string
	Imports   []string
}

SourceFile retains the original import source, not only its flattened form. Imports contains resolved source IDs in declaration order.

type Span

type Span struct {
	Start Position
	End   Position
}

type TextLiteral

type TextLiteral struct {
	Quoted string
}

type Type

type Type struct {
	Form TypeForm
	At   Span
}

func ParseTypeExpression

func ParseTypeExpression(source string) (typ *Type, failure error)

ParseTypeExpression parses one type, not declarations or executable input. It applies the same lexical, parser and syntax-tree resource limits as Parse.

func SubstituteType

func SubstituteType(t *Type, bindings map[string]*Type) (*Type, error)

SubstituteType performs capture-free simultaneous replacement of named type parameters. Replacement trees are caller-owned checked ASTs and are returned as-is: they are never recursively rebound through the same substitution. Unchanged Where expressions and source spans are retained by shallow copy.

func SubstituteTypeBounded

func SubstituteTypeBounded(t *Type, bindings map[string]*Type, maxNodes int) (*Type, error)

SubstituteTypeBounded applies the same operation with an explicit visited-node bound. Checked language types already obey the parser's depth bound; this additional bound makes the helper safe for manually assembled pathological ASTs.

type TypeDecl

type TypeDecl struct {
	Name       string
	Parameters []string
	Body       *Type
	Variants   []Variant
	At         Span
}

type TypeForm

type TypeForm interface {
	// contains filtered or unexported methods
}

type Unary

type Unary struct {
	Operator string
	Operand  *Expr
}

type Variable

type Variable struct {
	Name string
}

type Variant

type Variant struct {
	Name      string
	Arguments []*Type
	At        Span
}

type Where

type Where struct {
	Predicate *Expr
	Code      string
	Message   *Expr
	Steps     uint64
	At        Span
}

type WildPattern

type WildPattern struct{}

Jump to

Keyboard shortcuts

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