Help us shape the future of Go! Take the 2026 Go Developer Survey

hff

package module
v0.0.0-...-0734ea7 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2026 License: Apache-2.0 Imports: 7 Imported by: 0

README

HFF

Human-Friendly Filter

Write intuitively. Read clearly.

Documentation Go Reference Go version

Website · Tutorials · Guides · Cookbook · Backends · Reference · Specification · Design Records

HFF is a small, type-safe filter language for people querying your service. Combine conditions, search nested data, and filter collections in expressions you can read at a glance. Choose the features your service exposes, with one language designed for local evaluation and translation to backends such as SQL.

name="Alice" age>=18
labels.app="api" labels.env="production"
status>=500 latency_ms>1000
status="open" priority:in("high","urgent")
assignee!.email~"@example\\.com$"
items:any(item=>item.price*item.quantity>=100)

Why HFF

  • Built for Humans. Write compact conditions with familiar comparisons, spaces for AND, and methods for common filtering tasks. The syntax prioritizes how people read and write queries.
  • Portable Across Backends. Use the same syntax and semantics for local evaluation and translation to SQL or other processing systems. Backend adapters map the language to each target without changing the query grammar.
  • Lightweight and Flexible. Keep the runtime small and portable. Extend typed methods and backend adapters to fit different environments and service requirements.
  • Pure and Type-Safe. Check variables and operations against a schema before evaluation. Filters have no side effects, and null-safe rules handle missing values without exception-handling expressions.
  • Configurable Capabilities. Choose the operators and methods your service supports. The syntax stays fixed; unavailable features are rejected during compilation.
  • Ready to Use. Supply a schema and capability set to a configurable engine. Typed Go parsing generated by PEGO, compilation, and execution form an integrated filter interface for your service.

HFF is deliberately a filter language, not a complete programming language. Queries must depend on service data: age+10<20 is a filter, while 1+1, 10<20, and 10<age are rejected.

AIP-160 filtering addresses human-written service filters. HFF aims to cover needs beyond that model, including arithmetic, list indexing, and receiver methods. HFF uses AND-before-OR precedence, unlike AIP-160's OR-before-AND rule.

CEL is a portable, safe expression language for embedding in applications. HFF places its emphasis on quickly written filter queries, service-specific capability selection, and translation to arbitrary backends alongside its own runtime.

Syntax and parser

HFF syntax is defined in PEGO, with a typed Go parser generated from the grammar. The syntax-only parser is currently internal to this module; applications do not yet have a public parse-only API. The same grammar is used for every capability configuration. PEGO is a development-time parser generator, not a requirement to compile grammars at runtime.

Specification

This repository provides immutable values, schemas, capabilities, validated input, common query compilation, core local evaluation, scalar/string methods, and list/object methods and collection callbacks. Base64 and JSON conversion methods and local extension evaluators are also available. The SQL backend builds parameterized PostgreSQL predicates for documented scalar, schema-typed JSON/JSONB, and native composite profiles, and supports typed SQL method translators. Full JSONB type fidelity, broader structure and relation mapping, and additional dialects remain in progress. Start with the tutorials for a staged local-service example. Use the guides for feature behavior, the cookbook for practical filter recipes, backend documentation for local and PostgreSQL support, and the reference for exact method and Go API lookups.

Read the language specification, beginning with syntax, types and schemas, and evaluation. The normative method catalog defines the configurable library; the reference index provides a receiver-family lookup. Capabilities describe integration requirements.

Design records explain the rationale for individual language features.

License

Apache License 2.0.

Documentation

Overview

Package hff defines the values and contracts shared by Human-Friendly Filter compilers, local evaluators, and backend translators.

Applications usually configure an engine with a schema and capabilities, compile a query into a Program, then pass that Program to a backend Build function. Compilation produces a reusable, immutable typed plan; it does not construct an evaluator or execute a database query. This separation lets a service select local matching, SQL translation, or another backend without paying for an unused execution path.

Values represent explicit HFF data. Use Int and Float to retain numeric subtypes, Null for an explicit null, and Object/List for owned collections. The zero Value is invalid. A missing object key differs from a present key containing Null; Lookup's boolean result exposes that distinction. Value accessors return an ok flag instead of coercing an incompatible type.

Types describe the input contract. The schema package provides field helpers for assembling structs, lists, maps, unions, optional fields, and nullable fields. ValidateInput creates an Input whose exact schema can be reused by multiple filters; this is separate from compiling a query against that schema.

Program and Node expose the read-only typed IR for backend authors. Programs are created by engine compilation, not by manually assembling nodes. An IR retains null tests, guards, method resolution, callback bindings, and source spans so a backend can preserve HFF semantics or reject unsupported operations.

Errors report configuration, compilation, input, and execution failures. Ordinary null results are data and do not become execution errors. Profiles describe backend support and guarantees; they do not grant capability policy or prove that a caller-owned database satisfies a declared storage contract.

Index

Examples

Constants

View Source
const (
	// ConfigurationError indicates invalid host configuration or API arguments.
	ConfigurationError = core.ConfigurationError
	// SyntaxError indicates a malformed HFF query.
	SyntaxError = core.SyntaxError
	// TypeError indicates a query value or operation violates the schema types.
	TypeError = core.TypeError
	// CapabilityError indicates the query requires a denied or missing permission.
	CapabilityError = core.CapabilityError
	// BackendError indicates a backend cannot implement a valid compiled program.
	BackendError = core.BackendError
	// InputError indicates a record is invalid or incompatible with its schema.
	InputError = core.InputError
	// LimitError indicates a configured finite resource limit was exceeded.
	LimitError = core.LimitError
	// CancelledError indicates a context cancellation or deadline.
	CancelledError = core.CancelledError
)
View Source
const (
	// PropagateNull skips the extension invocation when the receiver or any
	// evaluated argument is null, returning null. This is the zero/default policy.
	PropagateNull = core.PropagateNull
	// InvokeNull permits dispatch for null receivers or arguments only when the
	// corresponding declared type admits NullType. It does not turn no-value into
	// a Value or invoke the callback for no-value.
	InvokeNull = core.InvokeNull
)
View Source
const (
	InvalidNode   = plan.InvalidNode
	MatchAllNode  = plan.MatchAllNode
	LiteralNode   = plan.LiteralNode
	VariableNode  = plan.VariableNode
	ParameterNode = plan.ParameterNode
	FieldNode     = plan.FieldNode
	IndexNode     = plan.IndexNode
	GuardNode     = plan.GuardNode
	NullTestNode  = plan.NullTestNode
	BinaryNode    = plan.BinaryNode
	NegateNode    = plan.NegateNode
	BoolNode      = plan.BoolNode
	AndNode       = plan.AndNode
	OrNode        = plan.OrNode
	NotNode       = plan.NotNode
	ListNode      = plan.ListNode
	ObjectNode    = plan.ObjectNode
	CallNode      = plan.CallNode
	CallbackNode  = plan.CallbackNode
	TypeGuardNode = plan.TypeGuardNode
	Equal         = plan.Equal
	NotEqual      = plan.NotEqual
	Less          = plan.Less
	LessEqual     = plan.LessEqual
	Greater       = plan.Greater
	GreaterEqual  = plan.GreaterEqual
	Match         = plan.Match
	NotMatch      = plan.NotMatch
	Add           = plan.Add
	Subtract      = plan.Subtract
	Multiply      = plan.Multiply
	Divide        = plan.Divide
	Remainder     = plan.Remainder
)

Node and operator constants are stable IR discriminants. Append new values; do not renumber or reuse existing values.

View Source
const (
	// InvalidType is the zero and invalid descriptor kind.
	InvalidType = core.InvalidType
	// NullType is the explicit null value type.
	NullType = core.NullType
	// BoolType is the Boolean value type.
	BoolType = core.BoolType
	// IntType is the signed int64 value type.
	IntType = core.IntType
	// FloatType is the finite float64 value type.
	FloatType = core.FloatType
	// StringType is the UTF-8 string value type.
	StringType = core.StringType
	// BytesType is the byte-sequence value type.
	BytesType = core.BytesType
	// ListType is an ordered sequence with one declared element type.
	ListType = core.ListType
	// StructType is a fixed-key object with declared fields.
	StructType = core.StructType
	// MapType is an object whose keys share one declared value type.
	MapType = core.MapType
	// TimestampType is an instant with nanosecond precision.
	TimestampType = core.TimestampType
	// DurationType is a signed duration with nanosecond precision.
	DurationType = core.DurationType
	// AnyType accepts any valid HFF value.
	AnyType = core.AnyType
	// NeverType has no values and is used for compiler analysis.
	NeverType = core.NeverType
	// UnionType accepts a value belonging to any listed member type.
	UnionType = core.UnionType
	// FunctionType describes callback functions in compiled plans.
	FunctionType = core.FunctionType
)
View Source
const (
	// InvalidKind is the invalid zero Value representation.
	InvalidKind = core.InvalidKind
	// NullKind is explicit HFF null.
	NullKind = core.NullKind
	// BoolKind is a Boolean value.
	BoolKind = core.BoolKind
	// IntKind is a signed int64 value.
	IntKind = core.IntKind
	// FloatKind is a finite float64 value.
	FloatKind = core.FloatKind
	// StringKind is a valid UTF-8 string value.
	StringKind = core.StringKind
	// BytesKind is a byte sequence.
	BytesKind = core.BytesKind
	// ListKind is an ordered list of HFF values.
	ListKind = core.ListKind
	// ObjectKind is a string-keyed object of HFF values.
	ObjectKind = core.ObjectKind
	// TimestampKind is a timestamp value.
	TimestampKind = core.TimestampKind
	// DurationKind is a duration value.
	DurationKind = core.DurationKind
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Binding

type Binding plan.Binding

Binding describes a lexically scoped callback parameter or capture. A nested callback may capture an outer binding; names can be shadowed, so use ID for identity within the Program.

func (Binding) ID

func (b Binding) ID() BindingID

ID returns the binding identity, scoped to one Program. Do not persist it as a cross-program identifier; an invalid zero Binding has ID zero.

func (Binding) Name

func (b Binding) Name() string

Name returns the callback parameter or capture name, or an empty string for an invalid zero Binding.

func (Binding) Type

func (b Binding) Type() Type

Type returns the binding's resolved type descriptor. Invalid bindings return the invalid zero Type.

type BindingID

type BindingID = plan.BindingID

BindingID identifies a callback parameter or capture within one Program. IDs are lexical plan-local handles and cannot be compared across Programs.

type CompatibilityVersion

type CompatibilityVersion struct{ Component, Version string }

CompatibilityVersion names a known implementation or caller-supplied data version. A missing component is unknown; a backend must not infer a database version it cannot inspect.

type Diagnostics

type Diagnostics = core.Diagnostics

Diagnostics groups independent source errors. Use errors.As for individual *Error values and Errors to obtain a defensive copy of the members.

type Error

type Error = core.Error

Error is the typed failure returned by the API. Inspect Code rather than parsing Message text. Path identifies an input location; Span, Line, and Column identify query source when available. Span is a half-open byte range; Line and Column are one-based, with columns counted in Unicode code points. Cause supports errors.Is.

type ErrorCode

type ErrorCode = core.ErrorCode

ErrorCode classifies a configuration, syntax, type, capability, backend, input, limit, or cancellation failure. A completed false match is not an error.

type FeatureSupport

type FeatureSupport struct {
	// ID is the capability or feature identifier being described.
	ID capabilities.ID
	// Level is the support status; an omitted entry remains unknown.
	Level SupportLevel
	// Conditions explains requirements when Level is Conditional.
	Conditions string
}

FeatureSupport records the backend's status for one capability ID. This is not permission to compile that feature; the engine's capabilities policy is configured separately.

type Field

type Field struct {
	// Name is the exact HFF object key.
	Name string
	// Type is the required value type when the field is present.
	Type Type
	// Optional permits the key to be absent; it does not permit explicit null.
	Optional bool
}

Field describes one exact object key in a struct type. Optional marks the field as absence-capable without adding NullType. Add NullType to Type to permit a present null value; input validation also accepts absence for a nullable field. The flag and value type remain distinct parts of the schema.

type GuaranteeID

type GuaranteeID string

GuaranteeID names one affirmative backend guarantee. Absence means only that the profile does not assert the guarantee; it does not claim the opposite.

const (
	// InputValidationGuarantee means the backend validates host input records.
	InputValidationGuarantee GuaranteeID = "input-validation"
	// EvaluationOrderGuarantee means evaluation follows HFF's left-to-right order.
	EvaluationOrderGuarantee GuaranteeID = "left-to-right-evaluation"
	// CancellationGuarantee means the backend honors cancellation at documented checkpoints.
	CancellationGuarantee GuaranteeID = "context-cancellation"
	// StepBudgetGuarantee means the backend enforces its runtime step ceiling.
	StepBudgetGuarantee GuaranteeID = "step-budget"
	// GeneratedValuesGuarantee means the backend enforces its generated-value ceiling.
	GeneratedValuesGuarantee GuaranteeID = "generated-values-budget"
	// JSONDepthGuarantee means the backend enforces its JSON depth ceiling.
	JSONDepthGuarantee GuaranteeID = "json-depth-budget"
)

type Input

type Input core.Input

Input is an immutable record validated against one exact schema. Its zero value is invalid; use ValidateInput or the engine package's Validate method to construct it. Backends can reuse it with MatchInput when schemas match.

func ValidateInput

func ValidateInput(ctx context.Context, schema Type, value Value, config ValidationConfig) (Input, error)

ValidateInput checks the complete value for valid HFF representations, input budgets, and compatibility with schema. It returns no partial Input on error; cancellation, limit failures, and configuration errors remain typed errors. A nil context or invalid schema is a configuration error. Zero input limits select finite defaults; set config.Unlimited to disable input depth/value ceilings explicitly. This check visits the whole record, even if a later filter reads only a few fields.

Example
package main

import (
	"context"
	"fmt"

	"github.com/ornew/hff"
	"github.com/ornew/hff/schema"
)

func main() {
	typ := schema.Struct(schema.Int("age"))
	record := hff.Object(map[string]hff.Value{"age": hff.Int(25)})
	input, err := hff.ValidateInput(context.Background(), typ, record, hff.ValidationConfig{})
	if err != nil {
		panic(err)
	}
	fmt.Println("same schema:", input.Compatible(typ))
	fmt.Println("different numeric type:", input.Compatible(schema.Struct(schema.Float("age"))))
}
Output:
same schema: true
different numeric type: false

func (Input) Compatible

func (i Input) Compatible(t Type) bool

Compatible reports whether i is valid and was validated against a schema structurally equal to t. It does not widen unions, infer compatibility, or convert values; invalid zero inputs and schemas return false.

func (Input) Schema

func (i Input) Schema() Type

Schema returns the exact schema contract used to validate this input. On an invalid zero Input it returns the invalid zero Type.

func (Input) Value

func (i Input) Value() Value

Value returns the immutable value held by a validated input. On an invalid zero Input it returns the invalid zero Value.

type Kind

type Kind = core.Kind

Kind identifies a value's exact representation. InvalidKind is not null: use Null to create explicit HFF null, and use input validation to reject an invalid zero Value.

type Limits

type Limits = core.Limits

Limits contains per-stage resource ceilings; it does not itself disable limits or configure every stage at once. APIs apply only their relevant fields. Compile fields are MaxQueryBytes (source bytes), MaxSyntaxDepth, MaxCallbackDepth, and MaxCompileSteps. Input fields are MaxInputDepth and MaxInputValues. Runtime fields are MaxSteps, MaxGeneratedValues, and MaxJSONDepth. Zero fields resolve to finite values returned by DefaultLimits; negative fields are invalid. For example, ValidateInput reads MaxInputDepth and MaxInputValues, while local evaluation reads runtime fields. Use an explicit unlimited option where an API provides one; leaving fields at zero selects defaults rather than unlimited work.

func DefaultLimits

func DefaultLimits() Limits

DefaultLimits returns HFF's current finite values for all limit fields. An API may use only the fields belonging to its stage; consult that API's configuration documentation before changing them.

type Method

type Method plan.Method

Method lists the applicable signatures of a resolved method call. It is IR metadata, not a callable extension implementation.

func (Method) Name

func (m Method) Name() string

Name returns the resolved method call name, or an empty string when m is an invalid zero Method.

func (Method) Signatures

func (m Method) Signatures() []Signature

Signatures returns a defensive copy of the signatures that compile-time resolution found applicable to this call. The result describes dispatch choices; it does not contain backend function pointers. An invalid zero Method returns an empty slice.

type MethodConfig

type MethodConfig struct {
	// ID is the stable extension identity suffix, for example "service.lookup.v1".
	// Capabilities.Method(ID) creates its permission ID; keep ID stable across
	// engine and backend configuration.
	ID string
	// Name is the ASCII method identifier used in query calls. Receiver types may
	// distinguish overloads, but declarations must not create ambiguous overloads.
	Name string
	// Receiver is the type accepted by the implementation. Calls with an
	// incompatible receiver fail during compilation rather than being coerced.
	Receiver Type
	// Parameters are required positional argument types, in query argument
	// order. Values are type-checked; this declaration performs no conversion.
	Parameters []Type
	// Optional are trailing positional argument types; callers cannot skip them.
	Optional []Type
	// Variadic is the repeated trailing type, or the zero Type when absent.
	Variadic Type
	// Result is the declared result type. An ordinary Null result
	// is also always allowed as a data failure, regardless of this type.
	Result Type
	// NullPolicy controls invocation when receiver or arguments are null. The
	// zero value, PropagateNull, skips invocation and returns null.
	NullPolicy NullPolicy
	// BaseCost is the positive local step charge applied before each call.
	BaseCost int
}

MethodConfig declares one extension signature shared by engine compilation and backend registration. Parameters are required positional arguments, followed by trailing Optional arguments and then repeated Variadic arguments. Optional positions cannot be skipped to reach Variadic. A zero Variadic means no repeated argument. BaseCost must be positive and is charged for each local callback invocation; backends validate implementation registration separately.

type MethodDeclaration

type MethodDeclaration core.MethodDeclaration

MethodDeclaration is the immutable, backend-independent extension signature. Its zero value is invalid. Install declarations in engine configuration to type-check calls and select their capabilities; register matching executable implementations separately with a backend Build configuration.

func NewMethodDeclaration

func NewMethodDeclaration(c MethodConfig) (MethodDeclaration, error)

NewMethodDeclaration validates and copies a method signature declaration. Invalid types, IDs, names, parameter ordering, null policy, or costs return a ConfigurationError. The returned declaration does not register an implementation or grant its capability.

func (MethodDeclaration) BaseCost

func (d MethodDeclaration) BaseCost() int

BaseCost returns the positive per-invocation local step charge, or zero for an invalid declaration.

func (MethodDeclaration) Equal

func (d MethodDeclaration) Equal(other MethodDeclaration) bool

Equal reports whether two valid declarations have identical IDs, types, argument positions, null policy, and base cost. It is useful when Build verifies that a registered implementation still matches the engine's declaration; invalid zero declarations compare false.

func (MethodDeclaration) ID

func (d MethodDeclaration) ID() string

ID returns the stable extension ID used for capability checks and dispatch, or an empty string for an invalid zero declaration.

func (MethodDeclaration) MaxArgs

func (d MethodDeclaration) MaxArgs() int

MaxArgs returns the maximum positional argument count, or -1 when Variadic makes the signature unbounded. An invalid declaration returns its zero value.

func (MethodDeclaration) MinArgs

func (d MethodDeclaration) MinArgs() int

MinArgs returns the minimum positional argument count, including all required parameters but not optional or variadic arguments. An invalid declaration returns zero.

func (MethodDeclaration) Name

func (d MethodDeclaration) Name() string

Name returns the HFF call name, without its type-family prefix, or an empty string for an invalid zero declaration.

func (MethodDeclaration) NullPolicy

func (d MethodDeclaration) NullPolicy() NullPolicy

NullPolicy returns the configured null dispatch policy. An invalid zero declaration reports PropagateNull, the zero/default policy.

func (MethodDeclaration) Optional

func (d MethodDeclaration) Optional() []Type

Optional returns a defensive copy of trailing optional parameter types. These positions are positional and cannot be omitted while supplying a later variadic argument.

func (MethodDeclaration) Parameter

func (d MethodDeclaration) Parameter(i int) (Type, bool)

Parameter returns the type accepted at zero-based argument position i, including optional and repeated variadic positions. The bool is false for a negative index, an out-of-range position, or an invalid declaration.

func (MethodDeclaration) Parameters

func (d MethodDeclaration) Parameters() []Type

Parameters returns a defensive copy of required positional parameter types.

func (MethodDeclaration) Receiver

func (d MethodDeclaration) Receiver() Type

Receiver returns the immutable receiver type descriptor by value. The zero declaration returns an invalid Type.

func (MethodDeclaration) Result

func (d MethodDeclaration) Result() Type

Result returns the successful result type descriptor. Null remains an allowed callback result even when this type is non-nullable.

func (MethodDeclaration) Valid

func (d MethodDeclaration) Valid() bool

Valid reports whether d is a successfully constructed declaration rather than its zero value.

func (MethodDeclaration) Variadic

func (d MethodDeclaration) Variadic() Type

Variadic returns the repeated trailing parameter type, or an invalid Type.

type Node

type Node plan.Node

Node is an opaque immutable semantic node. Its zero value is invalid. Children are in source evaluation order. Child and payload accessors return false for invalid indices, invalid nodes, or inapplicable payloads; returned slices are copies. Use Kind before reading kind-specific payloads.

func (Node) Binding

func (n Node) Binding() (Binding, bool)

Binding returns the referenced lexical binding and true for a ParameterNode or a VariableNode that names a callback binding. Input-root paths and other node kinds return false.

func (Node) Captures

func (n Node) Captures() ([]Binding, bool)

Captures returns callback captures as a defensive copy and true only for CallbackNode. Captures refer to lexical bindings outside that callback.

func (Node) Child

func (n Node) Child(i int) (Node, bool)

Child returns child i and false when i is outside the child range.

func (Node) ChildCount

func (n Node) ChildCount() int

ChildCount returns the number of children in source evaluation order. An invalid node has no children and returns zero.

func (Node) Constraint

func (n Node) Constraint() (Type, bool)

Constraint returns the declared runtime type test and true only for TypeGuardNode. The node's resolved Type may be narrower when the input schema already provides more information.

func (Node) Field

func (n Node) Field() (string, bool)

Field returns the immediate literal field name and true only when n is a FieldNode. Empty names and names containing dots are returned unchanged.

func (Node) Keys

func (n Node) Keys() ([]string, bool)

Keys returns a copy of the object-entry keys aligned by index with ObjectNode children. It returns true for an object literal, including one with no entries, and false for other kinds or an invalid node.

func (Node) Kind

func (n Node) Kind() NodeKind

Kind returns the semantic operation represented by n, or InvalidNode for an invalid zero Node.

func (Node) Literal

func (n Node) Literal() (Value, bool)

Literal returns an explicit literal payload, including an explicit Null, and true only for LiteralNode. It returns an invalid zero Value and false for other node kinds or an invalid node.

func (Node) MayNoValue

func (n Node) MayNoValue() bool

MayNoValue reports whether n can produce the internal no-value state, such as when a postfix guard finds a missing or mismatched path. No-value is not an HFF Value and propagates through evaluation. An invalid Node reports false.

func (Node) Method

func (n Node) Method() (Method, bool)

Method returns the resolved method payload and true only for CallNode.

func (Node) Operator

func (n Node) Operator() (Operator, bool)

Operator returns the operation payload for binary and null-test nodes. The bool is false for other node kinds or an invalid node.

func (Node) Parameters

func (n Node) Parameters() ([]Binding, bool)

Parameters returns callback parameters as a defensive copy and true only for CallbackNode. The bool distinguishes an empty parameter list from an inapplicable accessor.

func (Node) Path

func (n Node) Path() ([]string, bool)

Path returns a copy of the static path from the Program's input root when n is a variable or field chain rooted there. Callback-local variables, dynamic indexing, and other node kinds have no such path and return false. Empty literal path components are preserved. A path with no components is not returned as a payload.

func (Node) Span

func (n Node) Span() Span

Span returns n's half-open UTF-8 byte range in Program.Source. An invalid Node returns the zero Span.

func (Node) Type

func (n Node) Type() Type

Type returns the statically resolved result type of n. A runtime type guard can narrow it relative to the original schema; an invalid Node returns the invalid zero Type.

func (Node) Valid

func (n Node) Valid() bool

Valid reports whether n is a compiler-created node rather than its zero value.

type NodeKind

type NodeKind = plan.NodeKind

NodeKind identifies a semantic operation in the typed IR, independent from parser productions. Use it to select the applicable Node payload accessor.

type NullPolicy

type NullPolicy = core.NullPolicy

NullPolicy controls whether an extension callback runs when its receiver or an argument evaluates to explicit null. No-value always propagates without invoking an extension.

type Operator

type Operator = plan.Operator

Operator identifies arithmetic, comparison, and explicit null-test operations. It is meaningful only for node kinds that carry an operator.

type Path

type Path = core.Path

Path is a sequence of literal field or index labels. Components are not split on dots; for example, []string{"service.name"} is one field.

type Profile

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

Profile is an immutable snapshot of known backend facts and effective configuration. Inspect it for compatibility reporting; Build remains authoritative for a specific program, mapping, and configuration. A zero Profile is invalid.

func NewProfile

func NewProfile(config ProfileConfig) (Profile, error)

NewProfile validates and snapshots a profile. It rejects an empty backend name, invalid or duplicate entries, invalid declarations, and negative limits with a ConfigurationError. Slice and limit-pointer changes made by the caller after construction do not affect the Profile. For example, omit a feature to leave it unknown rather than claiming support:

profile, err := hff.NewProfile(hff.ProfileConfig{
    Backend: "local",
    Features: []hff.FeatureSupport{{ID: capabilities.Access, Level: hff.Supported}},
})
if err != nil { return err }
if access, ok := profile.Feature(capabilities.Access); ok { _ = access.Level }

func (Profile) Backend

func (p Profile) Backend() string

Backend returns the declared backend name, or an empty string for an invalid zero Profile.

func (Profile) Capabilities

func (p Profile) Capabilities() capabilities.Set

Capabilities returns the declared service policy. Its zero value is unspecified and does not mean all capabilities are allowed; use capabilities.Set.Specified to distinguish it from an explicit empty policy.

func (Profile) CompileLimits

func (p Profile) CompileLimits() (Limits, bool)

CompileLimits reports query-byte, syntax-depth, callback-depth, and compilation-work ceilings. The bool is false when no stage limits were declared; a true result with zero applicable fields means explicitly unbounded. Other stage fields are not applicable.

func (Profile) Details

func (p Profile) Details() []ProfileDetail

Details returns a defensive copy of backend-specific descriptive values. Details have no built-in interpretation and grant no capability.

func (Profile) Feature

func (p Profile) Feature(id capabilities.ID) (FeatureSupport, bool)

Feature looks up a declared feature. The bool is false when the ID has no entry, which means support is unknown. When true, inspect Level and, for Conditional, Conditions; the result does not replace Build validation.

func (Profile) Features

func (p Profile) Features() []FeatureSupport

Features returns a defensive copy of declared feature statuses. Omitted feature IDs remain unknown; changing the returned slice cannot change p.

func (Profile) Guarantees

func (p Profile) Guarantees() []GuaranteeID

Guarantees returns a defensive copy of affirmative guarantees. An absent ID is not an assertion that the backend violates it.

func (Profile) HasGuarantee

func (p Profile) HasGuarantee(id GuaranteeID) bool

HasGuarantee reports whether this profile explicitly declares the affirmative guarantee. False means no guarantee is asserted, not necessarily that the backend lacks the behavior.

func (Profile) InputLimits

func (p Profile) InputLimits() (Limits, bool)

InputLimits reports input depth and value-count ceilings. The bool is false when no limits were declared; a true result with zero applicable fields means explicitly unbounded.

func (Profile) Methods

func (p Profile) Methods() []MethodDeclaration

Methods returns a defensive copy of configured immutable extension declarations. Their presence does not enable those methods in the service's capability set or prove that a particular Build registered an implementation.

func (Profile) RuntimeLimits

func (p Profile) RuntimeLimits() (Limits, bool)

RuntimeLimits reports evaluation-step, generated-value, and JSON-depth ceilings. The bool is false when no limits were declared; a true result with zero applicable fields means explicitly unbounded.

func (Profile) Valid

func (p Profile) Valid() bool

Valid reports whether p contains a profile created successfully by NewProfile; the zero Profile is invalid.

func (Profile) Version

func (p Profile) Version(component string) (string, bool)

Version returns a known component version and true when component was declared. A false result means unknown; versions are not guessed from a backend or database connection.

func (Profile) Versions

func (p Profile) Versions() []CompatibilityVersion

Versions returns a defensive copy of known version components. Missing components remain unknown; values are never inferred from a backend.

type ProfileConfig

type ProfileConfig struct {
	// Backend is a stable backend name, such as "local" or "postgresql".
	Backend string
	// Features lists known feature statuses; omitted IDs remain unknown.
	Features []FeatureSupport
	// Versions lists only known implementation or explicitly supplied data versions.
	Versions []CompatibilityVersion
	// Guarantees lists affirmative guarantees, not missing behavior.
	Guarantees []GuaranteeID
	// Details contains backend-specific descriptive values.
	Details []ProfileDetail
	// Methods contains extension declarations; it does not enable permissions.
	Methods []MethodDeclaration
	// Capabilities is the effective service policy; its zero value is unknown.
	Capabilities capabilities.Set
	// Nil limits mean unknown or outside this backend's responsibility. Non-nil
	// limits describe resolved ceilings; zero applicable fields mean explicitly
	// unbounded. Fields belonging to a different stage are not applicable.
	CompileLimits *Limits
	InputLimits   *Limits
	RuntimeLimits *Limits
}

ProfileConfig declares backend facts known to the caller or implementation. NewProfile validates and snapshots slices and limit pointers. Nil stage-limit pointers mean unknown or outside the backend's responsibility; non-nil zero fields mean explicitly unbounded for that stage. Capabilities is a separate explicit service policy, not a backend support report.

type ProfileDetail

type ProfileDetail struct{ Name, Value string }

ProfileDetail holds backend-specific descriptive information. It grants no capabilities and is not a configuration option or execution guarantee.

type Program

type Program plan.Program

Program holds the immutable typed plan and the schema, capability policy, method declarations, and resolved limits used to compile it. Compilation creates Programs; backends consume them without mutation. Its zero value is invalid.

func (Program) Capabilities

func (p Program) Capabilities() capabilities.Set

Capabilities returns the explicit capability policy used to compile p. This is the compile-time permission set, not a backend support profile. An invalid zero Program returns the unspecified zero Set.

func (Program) Limits

func (p Program) Limits() Limits

Limits returns the resolved limit values used to compile p. Inspect the compile-stage fields rather than interpreting zero as unlimited; zero fields were resolved from defaults unless UnlimitedLimits reports true. The zero Program returns the zero Limits value.

func (Program) Root

func (p Program) Root() Node

Root returns the root of the typed plan, or an invalid Node for an invalid zero Program.

func (Program) Schema

func (p Program) Schema() Type

Schema returns the exact immutable input schema used at compilation. The zero Program returns an invalid Type.

func (Program) Source

func (p Program) Source() string

Source returns the original query text used to compile p, preserving source spelling for diagnostics and inspection. The zero Program returns an empty string.

func (Program) UnlimitedLimits

func (p Program) UnlimitedLimits() bool

UnlimitedLimits reports whether compilation was explicitly configured without finite limits. It concerns compilation only, not input validation or backend runtime limits.

func (Program) Valid

func (p Program) Valid() bool

Valid reports whether p is a compiler-created typed program rather than the invalid zero Program.

type Signature

type Signature plan.Signature

Signature is one resolved method declaration applicable at a call site. A call may contain several non-ambiguous signatures for overload resolution.

func (Signature) Declaration

func (s Signature) Declaration() (MethodDeclaration, bool)

Declaration returns the immutable extension declaration for an extension signature. The bool is false for built-in signatures or an invalid signature; a false result does not indicate a missing backend implementation.

func (Signature) ID

func (s Signature) ID() string

ID returns the stable method signature identity, or an empty string for an invalid signature.

func (Signature) Parameters

func (s Signature) Parameters() []Type

Parameters returns a defensive copy of the ordered declared parameter types: required parameters, optional parameters, then the repeated type if variadic. Optional positions are positional, and the final parameter is repeated only when Variadic reports true. An invalid signature returns nil.

func (Signature) Receiver

func (s Signature) Receiver() Type

Receiver returns the signature's receiver type descriptor, or an invalid zero Type for an invalid signature.

func (Signature) Result

func (s Signature) Result() Type

Result returns the signature's declared result type. Extension callbacks may also return ordinary null as a data failure. An invalid signature returns the invalid zero Type.

func (Signature) Variadic

func (s Signature) Variadic() bool

Variadic reports whether the signature repeats its final parameter type. An invalid signature reports false.

type Span

type Span = core.Span

Span is a half-open range [Start, End) of UTF-8 byte offsets in the original query, not rune indexes. Source diagnostics report one-based lines and columns counted in Unicode code points. A zero Span is an empty range at byte offset zero; use the containing query to interpret it.

type SupportLevel

type SupportLevel uint8

SupportLevel describes backend support separately from service permission. An absent feature entry is unknown, not unsupported or supported. Even a Supported entry is descriptive; Build remains authoritative for a concrete program and configuration.

const (
	// UnknownSupport means the profile makes no claim about the feature. Profiles
	// express this by omitting the feature entry; NewProfile rejects an explicit
	// UnknownSupport entry.
	UnknownSupport SupportLevel = iota
	// Supported means the backend declares support, subject to Build validation.
	Supported
	// Conditional means support requires a non-empty Conditions explanation.
	Conditional
	// Unsupported means this backend profile declares the feature unavailable.
	Unsupported
)

type Type

type Type core.Type

Type is an immutable description of values accepted by a schema or produced by a compiled expression. Its zero value is invalid; construct descriptors with PrimitiveType or the composite constructors, then call Check before using one as a host input schema. Function types are compiler metadata and are rejected by Check.

func NewListType

func NewListType(element Type) Type

NewListType constructs an ordered list type whose elements must match element. Check the resulting descriptor before using it as an input schema.

func NewMapType

func NewMapType(element Type) Type

NewMapType constructs an object type whose values must all match element. Map keys are strings. Check the resulting descriptor before using it as an input schema.

func NewStructType

func NewStructType(fields ...Field) Type

NewStructType constructs a fixed-key object type from fields. Field order is canonicalized, but names and descriptors are not repaired: Check reports invalid UTF-8 or duplicate names, invalid types, and unsupported function types. Empty field names are allowed. Optional records key-absence permission independently of the value type. A nullable field can use Type: NewUnionType(PrimitiveType(StringType), PrimitiveType(NullType)); input validation accepts its absence as a normal null-safe case even when Optional is false. Optional still does not add NullType to Type.

func NewUnionType

func NewUnionType(members ...Type) Type

NewUnionType constructs a normalized union from member descriptors. Nested unions are flattened, duplicate members are removed, and members are sorted canonically. No members produces NeverType; one member returns that member directly. Include NullType to allow explicit null; this does not make a struct field optional.

func PrimitiveType

func PrimitiveType(k TypeKind) Type

PrimitiveType constructs a primitive descriptor, including AnyType, NullType, and NeverType. Invalid or composite kinds produce the invalid zero Type. AnyType accepts any valid HFF value; NeverType accepts no values and is mainly useful in compiler analysis. Use the composite constructors for list, map, struct, and union descriptors.

func (Type) Check

func (t Type) Check() error

Check recursively validates a host-schema descriptor. It rejects invalid and function types, duplicate struct keys, and nesting beyond the supported schema depth. Engine input schemas additionally require a struct or map root.

func (Type) Element

func (t Type) Element() Type

Element returns the declared element type for a list or map. It returns an invalid zero Type for other kinds or an invalid receiver.

func (Type) Equal

func (t Type) Equal(other Type) bool

Equal reports structural equality, including field names, optionality, and nested member types. It does not infer compatibility or perform coercion.

func (Type) Fields

func (t Type) Fields() []Field

Fields returns a defensive copy of a struct's fields. It returns nil for non-struct or invalid types; changing the returned slice does not change t.

func (Type) Key

func (t Type) Key() string

Key returns the stable canonical structural key for descriptor comparison and caches. It is not a display format or serialization contract.

func (Type) Kind

func (t Type) Kind() TypeKind

Kind returns the descriptor kind; an invalid zero Type reports InvalidType.

func (Type) Members

func (t Type) Members() []Type

Members returns a defensive copy of union members, or nil when t is not a union. A normalized union has at least two members; singleton unions have already collapsed to their member type.

func (Type) Parameters

func (t Type) Parameters() []Type

Parameters returns a defensive copy of function parameter types, or nil for a non-function type. Function types are compiler metadata, not host schema types accepted by Check.

func (Type) Result

func (t Type) Result() Type

Result returns a function's result type, or an invalid zero Type for other kinds or an invalid receiver.

type TypeKind

type TypeKind = core.TypeKind

TypeKind identifies a schema or compiler type category. FunctionType and NeverType are primarily used in compiled plans, not host input schemas.

type ValidationConfig

type ValidationConfig = core.ValidationConfig

ValidationConfig selects host-input depth and value-count limits. Zero fields use finite defaults; Unlimited explicitly removes those two ceilings. Compile and runtime fields in Limits do not affect ValidateInput.

type Value

type Value core.Value

Value owns immutable data. Its zero value is invalid; it is neither missing nor null. Use Null for explicit null, and use Object lookup to distinguish a missing key from a key holding Null.

func Bool

func Bool(v bool) Value

Bool constructs a Boolean HFF value. The payload is stored exactly; HFF truthiness is defined by evaluation, not by this constructor.

func Bytes

func Bytes(v []byte) Value

Bytes copies v into an immutable byte value. Later changes to v do not change the Value; AsBytes returns another copy.

func Duration

func Duration(v time.Duration) Value

Duration constructs a nanosecond-precision duration value.

func Float

func Float(v float64) Value

Float constructs a float64 HFF value. Non-finite values are rejected by input validation rather than converted to null.

func Int

func Int(v int64) Value

Int constructs an int64 HFF value without conversion to or from float64.

func List

func List(values ...Value) Value

List copies values into an immutable ordered list. The empty call creates an empty list, not null. Backends such as local Match validate it against the Program schema; ValidateInput can create a reusable checked input explicitly.

func Null

func Null() Value

Null constructs the explicit HFF null value.

func Object

func Object(values map[string]Value) Value

Object copies values into an immutable object. A nil or empty map creates an empty object, not null. A missing key differs from a key explicitly mapped to Null(); use Lookup's bool result to tell them apart.

func String

func String(v string) Value

String constructs an HFF string without normalization or numeric parsing. Input validation rejects strings that are not valid UTF-8.

func Timestamp

func Timestamp(v time.Time) Value

Timestamp constructs a timestamp normalized to UTC. It represents an instant; the input time's location and monotonic clock reading are not part of the HFF value.

func (Value) AsBool

func (v Value) AsBool() (bool, bool)

AsBool returns the Boolean payload and true only for BoolKind. The bool in the second result reports the kind match, not the payload's truth value.

func (Value) AsBytes

func (v Value) AsBytes() ([]byte, bool)

AsBytes returns a defensive copy and true only for BytesKind. Mutating the returned bytes cannot change v.

func (Value) AsDuration

func (v Value) AsDuration() (time.Duration, bool)

AsDuration returns the nanosecond-precision duration and true only for DurationKind.

func (Value) AsFloat

func (v Value) AsFloat() (float64, bool)

AsFloat returns the float64 payload and true only for FloatKind. Input validation rejects NaN and infinities; this accessor does not coerce IntKind.

func (Value) AsInt

func (v Value) AsInt() (int64, bool)

AsInt returns the int64 payload and true only for IntKind. It does not convert FloatKind values.

func (Value) AsList

func (v Value) AsList() ([]Value, bool)

AsList returns a defensive copy of the ordered elements and true only for ListKind. A valid empty list returns a non-nil empty slice and true; false means the receiver is not a list, not that the list is empty.

Example
package main

import (
	"fmt"

	"github.com/ornew/hff"
)

func main() {
	list := hff.List(hff.String("admin"), hff.String("viewer"))
	items, ok := list.AsList()
	if !ok {
		panic("expected a list")
	}
	// The returned slice is a copy; changing it does not mutate the HFF list.
	items[0] = hff.String("changed")
	original, _ := list.AsList()
	first, _ := original[0].AsString()
	fmt.Println(first)
}
Output:
admin

func (Value) AsObject

func (v Value) AsObject() (map[string]Value, bool)

AsObject returns a defensive copy of the entries and true only for ObjectKind. A valid empty object returns a non-nil empty map and true; false means the receiver is not an object.

func (Value) AsString

func (v Value) AsString() (string, bool)

AsString returns the string payload and true only for StringKind. The bool reports the kind match; it is not a success flag for string contents.

func (Value) AsTimestamp

func (v Value) AsTimestamp() (time.Time, bool)

AsTimestamp returns the UTC-normalized instant and true only for TimestampKind.

func (Value) Kind

func (v Value) Kind() Kind

Kind returns the exact representation kind. The zero Value reports InvalidKind; explicit null reports NullKind.

func (Value) Lookup

func (v Value) Lookup(key string) (Value, bool)

Lookup returns an object field and whether the key exists. A present Null() value returns (Null(), true); a missing key or non-object receiver returns (zero Value, false). The zero Value in the latter case is invalid, not null.

Example
package main

import (
	"fmt"

	"github.com/ornew/hff"
)

func main() {
	record := hff.Object(map[string]hff.Value{"nickname": hff.Null(), "active": hff.Bool(false)})
	_, missing := record.Lookup("missing")
	nickname, present := record.Lookup("nickname")
	active, _ := record.Lookup("active")
	flag, typed := active.AsBool()
	fmt.Println("missing key exists:", missing)
	fmt.Println("nickname exists and is null:", present && nickname.Kind() == hff.NullKind)
	fmt.Println("active Boolean:", flag, typed)
}
Output:
missing key exists: false
nickname exists and is null: true
active Boolean: false true

Directories

Path Synopsis
adapters
govalue
Package govalue adapts Go records to HFF while keeping reflection out of the compiler and backend contracts.
Package govalue adapts Go records to HFF while keeping reflection out of the compiler and backend contracts.
backends
local
Package local builds an in-process evaluator for an already compiled HFF Program.
Package local builds an in-process evaluator for an already compiled HFF Program.
sql
Package sql translates compiled HFF Programs into parameterized PostgreSQL predicates.
Package sql translates compiled HFF Programs into parameterized PostgreSQL predicates.
Package capabilities defines which HFF features a service permits at compile time.
Package capabilities defines which HFF features a service permits at compile time.
Package config encodes and decodes versioned HFF engine and PostgreSQL binding configurations as JSON.
Package config encodes and decodes versioned HFF engine and PostgreSQL binding configurations as JSON.
Package engine configures HFF compilation and validates host records.
Package engine configures HFF compilation and validates host records.
examples
base64 command
base64-raw command
Command base64-raw demonstrates strict unpadded standard base64 locally and builds the equivalent PostgreSQL predicate without opening a connection.
Command base64-raw demonstrates strict unpadded standard base64 locally and builds the equivalent PostgreSQL predicate without opening a connection.
callbacks command
collections command
compilation command
Compile a query into a reusable, typed plan without building an evaluator.
Compile a query into a reusable, typed plan without building an evaluator.
configuration command
Command configuration demonstrates engine construction and record validation.
Command configuration demonstrates engine construction and record validation.
extensions command
go-binding command
go-values command
json command
local command
parsing command
Command parsing demonstrates syntax-only parsing from inside the HFF module.
Command parsing demonstrates syntax-only parsing from inside the HFF module.
profiles command
scalar-methods command
sql-bytes command
Command sql-bytes builds a PostgreSQL predicate over bytes and base64 text.
Command sql-bytes builds a PostgreSQL predicate over bytes and base64 text.
sql-composite command
sql-durations command
Command sql-durations builds a PostgreSQL filter over duration text.
Command sql-durations builds a PostgreSQL filter over duration text.
sql-extensions command
sql-json command
sql-json-bytes command
Command sql-json-bytes builds a predicate over schema-known JSON Bytes.
Command sql-json-bytes builds a predicate over schema-known JSON Bytes.
sql-json-comparison command
Command sql-json-comparison builds a parameterized filter comparing expected and actual values inside one JSONB document.
Command sql-json-comparison builds a parameterized filter comparing expected and actual values inside one JSONB document.
sql-json-container-unions command
Command sql-json-container-unions filters a JSONB duration-or-list column.
Command sql-json-container-unions filters a JSONB duration-or-list column.
sql-json-items command
Command sql-json-items filters named binary attachments in a JSONB object.
Command sql-json-items filters named binary attachments in a JSONB object.
sql-json-unions command
sql-label-search command
Command sql-label-search builds one query for labels stored as either a single string or a list of strings.
Command sql-label-search builds one query for labels stored as either a single string or a list of strings.
sql-predicate command
Build a parameterized PostgreSQL predicate without executing database I/O.
Build a parameterized PostgreSQL predicate without executing database I/O.
sql-relations command
sql-stored-durations command
Command sql-stored-durations builds a PostgreSQL filter over a bigint column.
Command sql-stored-durations builds a PostgreSQL filter over a bigint column.
sql-timestamps command
Command sql-timestamps builds a PostgreSQL filter over a nanosecond-precise Timestamp.
Command sql-timestamps builds a PostgreSQL filter over a nanosecond-precise Timestamp.
temporal command
hack
observe-relation-average command
Command observe-relation-average prints SQL shapes for a fixed relation AVG workload.
Command observe-relation-average prints SQL shapes for a fixed relation AVG workload.
observe-sort-key command
Command observe-sort-key prints SQL shapes for dynamic numeric sorting.
Command observe-sort-key prints SQL shapes for dynamic numeric sorting.
observe-structural-distinct command
Command observe-structural-distinct prints SQL shapes for stable structural deduplication.
Command observe-structural-distinct prints SQL shapes for stable structural deduplication.
internal
compiler
Package compiler performs common semantic checking before backend construction.
Package compiler performs common semantic checking before backend construction.
conformance
Package conformance holds shared language examples for parser, compiler, and backend tests.
Package conformance holds shared language examples for parser, compiler, and backend tests.
core
Package core owns HFF's immutable value and type representations.
Package core owns HFF's immutable value and type representations.
govalue
Package govalue contains the reflection conversion shared by Go adapters.
Package govalue contains the reflection conversion shared by Go adapters.
plan
Package plan owns immutable typed plans.
Package plan owns immutable typed plans.
syntax
Package syntax implements HFF's fixed grammar using a PEGO-generated typed parser.
Package syntax implements HFF's fixed grammar using a PEGO-generated typed parser.
The playground bridge is private to the documentation site, not a JavaScript SDK.
The playground bridge is private to the documentation site, not a JavaScript SDK.
Package schema builds immutable HFF input type descriptors with field helpers.
Package schema builds immutable HFF input type descriptors with field helpers.

Jump to

Keyboard shortcuts

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