jqlite

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: MIT Imports: 20 Imported by: 0 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.

README

jqlite for Go

The Go port of jqlite, the profile of the jq 1.8 language, carried over file by file from the .NET reference (dotnet/JQLite/Core, see docs/porting.md). Standard library only; Go 1.26.

Module github.com/devlooped/jqlite/go: the package jqlite at the module root is the host boundary, the engine is in internal/.

Use

import "github.com/devlooped/jqlite/go"

expression, err := jqlite.Parse(`.items[] | select(.price > $min) | {name, price}`)
if err != nil {
	return err // a *jqlite.ParseError, with Line and Column
}

input, _ := jqlite.ParseJSON(`{"items":[{"name":"a","price":5},{"name":"b","price":15}]}`)
min := map[string]jqlite.Value{"min": jqlite.Number(10)}

// All the results at once…
results, err := expression.Evaluate(input, min) // err: *jqlite.Error, *jqlite.HaltError
for _, r := range results {
	fmt.Println(jqlite.ToJSON(r)) // {"name":"b","price":15}
}

// …or as they come: break stops the evaluation.
for r, err := range expression.Results(input, min) {
	if err != nil {
		return err
	}
	fmt.Println(jqlite.ToJSON(r))
}
  • Parse(expression), ParseWithResolver(expression, resolver), ParseWithOptions(expression, options) give an *Expression: parsed and bound once, immutable, safe to evaluate from many goroutines at once. MustParse panics on an error. Evaluate(expression, input, variables) parses and evaluates.
  • Expression.Evaluate gives all results; EvaluateFunc pushes each result to a callback that gives false to stop; Results is an iter.Seq2[Value, error] for range; Lines evaluates each value of a JSON Lines stream alone.
  • Host variables: map[string]Value, names without $ ("root" is $root), validated before evaluation (*VariableError; ENV is not allowed).
  • Options: Resolver (modules: FileResolver, FSResolver over an fs.FS such as an embed.FS), Environment ($ENV as NAME=value entries in order; nil is the process environment), Now and Location (now and the local zone of localtime, strflocaltime, %z, %Z), MaxDepth (0 is 1000), Debug and Stderr handlers. The zero Options are the defaults.
  • Errors are host errors only here: *ParseError (Line, Column, Module), *Error (the error Value), *HaltError (Value, ExitCode); halt ends normally.
  • Values: Go has no ordered JSON value, so Value is the engine's own (immutable, keys in insertion order), with ParseJSON/ToJSON (canonical text, §5.1), FromAny/ToAny (map[string]any has no order: FromAny sorts its keys, ToAny loses the order), and Null, Bool, Number, String, NewArray, NewObject. Strings are UTF-8; ill-formed input becomes U+FFFD (§4.1).

Build, test, benchmark

cd go
go generate ./...   # copies spec/prelude.jq next to internal/binding/prelude.go for //go:embed
go build ./...
go vet ./...
gofmt -l .          # prints nothing
go test ./...

go test ./... runs:

  • the corpus of spec/tests/ (read from there, not copied) twice: through the public API (conformance_test.go, TestCorpusCase) and through the core with every prelude builtin bound to its definition (TestCorpusCaseWithoutNativeOverrides), with localtime.test at UTC+02:00 and modules.test over spec/tests/modules/;
  • the unit tests of every layer, ported from dotnet/Tests/Core/: values, lexer, parser, parser and resolver limits, the corpus parsed and bound, the resolver (bound programs printed as hops and slots, single functions), the catalogue against §9 of the spec, modules, the interpreter, native _modify/_assign against the prelude, the native table, the depth limit and the stack (internal/runtime/stack_guard_test.go, below);
  • the regex engine (internal/builtins/regex_engine_test.go): random patterns against a plain backtracking matcher of the same programs, patterns and inputs that need linear time, the memory of a search, the largest patterns within the limits of spec §11 (the translator checks them, the engine refuses nothing);
  • the host boundary: options, errors, streaming, variables, values, depth on a fresh goroutine, one expression from 32 goroutines at once, and the portability rules of AGENTS.md on the core (portability_test.go: the core imports only math, strings, unicode/utf8 and slices, every other package by file with its reason; no recover, goroutines or channels but in runtime/stack_guard.go; panic only for the programming errors it lists).

internal/corpus (the reader of the .test files and the structural comparison of spec §14) and internal/corpus/modules (the module sources of the tests, over a directory or a map) are test support, not part of the engine: they use the host's file system and regexp freely.

Recursion and the stack

MaxDepth is the only recursion limit a program meets (spec §11): up to it, an evaluation never fails because of the Go stack. A goroutine's stack grows, but only to runtime/debug.SetMaxStack (1 GB on 64-bit systems), and going past it is a fatal error that no recover catches. One call level takes about 1.6 KB of stack for a single call (EvalOne) and 2.5 KB for a call that is not single (Eval through callbacks), measured at 50,000 levels (TestTheStackOfACallLevel); a recursive call written inside a deeply nested body costs that nesting at every level, so no fixed MaxDepth would be safe for every program. So the interpreter does what the reference does with threads (runtime/stack_guard.go): it counts the Eval and EvalOne frames active on the current goroutine, and at 10,000 the step continues on a new goroutine while the current one waits (a panic of the step, such as one of the host's callback, comes back to the caller's goroutine). Each goroutine's stack stays at a few MB whatever MaxDepth is; what remains is memory: about 1.6 to 2.5 KB per call level in all, 160–250 MB at MaxDepth 100,000. The tests run every recursion of the reference's StackGuardTests at MaxDepth 1,000, 5,000 and 20,000, each with the default hop and with a hop every 50 frames, a recursion 1,000 calls deep through 900 levels of nesting (900,000 frames), and 100,000 levels (TestAHundredThousandLevels, 0.2 s), the largest tested.

TestTheEmbeddedPreludeIsTheSpecs fails when internal/binding/prelude.jq differs from spec/prelude.jq: run go generate ./... again. The race detector (go test -race ./...) needs cgo and a C compiler.

The benchmark runner of bench/README.md is cmd/bench, on the core engine:

go build -o bin/jqlite-bench.exe ./cmd/bench
bin/jqlite-bench.exe <program.jq> <input.json> <take> <warmup-ms> <measure-ms> <output-file>
pwsh ../bench/run.ps1 -Impl dotnet,go

Differences from the reference's structure

Each file of dotnet/JQLite/Core is a file of the same name in snake case, in the package of its layer (Values/ValueOps.cs is internal/values/value_ops.go), with the same type and function names. Where Go asks for something else:

Where Difference Why
everywhere A static class is a package variable of an empty struct type: ValueOps.Compare(a, b), Errors.CannotIndex(t, k), CodePoints.Length(s) calls read as in C#, and the functions of CodePoints and ValueOps (both have Compare) do not collide in one package
everywhere TryX(…, out result, out error) is TryX(…) (result, err Value, ok bool); out parameters are results; optional strings are a flag (HasFormat, HasAlias, HasVariable) or "" (no module, the main program as from) Go has no out and no nullable strings
binding/natives.go The native catalogue (Builtins/Natives.cs) is in the binding package Go forbids import cycles: the resolver binds to the catalogue, and the builtins import the binding and runtime packages
runtime/native_table.go, builtins/register.go The table and the two native types are in the runtime package; builtins fills them in its init (the static constructor of NativeTable), and registers Formats.TryApply too, which the interpreter calls for @name and templates the same import cycle (guide §1.1)
runtime/stack_guard.go HasStack counts the Eval/EvalOne frames of the current goroutine (10,000) instead of probing the stack; OnFreshStack runs the step on a new goroutine Go cannot ask how much stack is left; see Recursion and the stack
values/code_points.go Hex and Decimal write numbers for messages the core uses no fmt or strconv beyond value_text.go
values/ Strings are UTF-8: CodePoints.Compare is a byte comparison, Advance maps code points to bytes, Utf8Length is gone; FromString replaces each maximal ill-formed subpart with U+FFFD (Utf8.DecodeReplacing) Go strings are bytes; Go's own decoders replace per byte or per run (guide §3.2)
values/value_text.go The reader combines \u surrogate pairs itself and sanitizes ill-formed UTF-8; reader error columns count code points the reference reads UTF-16 text and lets FromString fix lone surrogates; the two counts differ only for characters above U+FFFF
values/jq_value.go Value is a struct of a kind, a float64 and an any (32 bytes, not 16) guide §2.1
values/jq_object.go, values/jq_string.go SortedKeys and the text of a grown string are cached in an atomic.Pointer the reference's benign race is a data race in Go's memory model
syntax/parser.go Partial nodes of parsePipe, if and reduce/foreach get their hole filled in place Go has no with copies; a node is not changed after parsing
syntax/lexer.go The source is sanitized first (ill-formed UTF-8 to U+FFFD) as the reference's lone surrogates
binding/prelude.go //go:embed prelude.jq, a copy made by go generate (copy_prelude.go) embed sees only files of the package's directory
builtins/regex_*.go The engine reads UTF-8 and its positions are byte offsets, which RegexNatives converts to code points; a match that starts with a fixed code point skips ahead with strings.Index on its UTF-8 bytes, whatever the code point; RegexSyntax.Op is RegexOp (OpChar…); the program cache counts its entries in an atomic.Int64 Go strings are bytes (guide §3.3); sync.Map has no count
builtins/math_extra.go Each product that is added is converted with float64(…); the polynomials go through a horner helper Go may fuse x*y + z (it does on arm64); an explicit conversion rounds first
builtins/assign_natives.go A draft keeps its children in attachment order the reference walks dictionaries; Go map order is random
builtins/strftime.go Formatting appends to a []byte the reference upper-cases a StringBuilder in place
tests OnSmallStack cases run on a new goroutine; the "ab" * 1e9 case is "ab" * 1.1e9; allocation bounds are doubled goroutine stacks start small and grow; Go strings reach the spec's 2^31 − 1 bytes, where .NET's string limit stops sooner; values are twice as large
host Options with Now/Location instead of TimeProvider, Environment as NAME=value entries, FSResolver instead of JqResourceResolver, Results/Lines as iter.Seq2 instead of IAsyncEnumerable the idioms of Go

Not ported: the .NET-only tests of JsonElement conversion, IObservable and the async JSON Lines helpers (JqObservableTests, JqJsonlStreamingTests); their Go counterparts are the tests of value.go, Results and Lines.

Documentation

Overview

Package jqlite is the Go port of jqlite, the profile of the jq language specified in spec/jqlite.md: parse a program once into an Expression, evaluate it many times, from many goroutines. This package is the host boundary; the engine is in internal/.

Index

Constants

View Source
const (
	KindNull   = values.KindNull
	KindFalse  = values.KindFalse
	KindTrue   = values.KindTrue
	KindNumber = values.KindNumber
	KindString = values.KindString
	KindArray  = values.KindArray
	KindObject = values.KindObject
)

The kinds of values.

Variables

View Source
var (
	Null  = values.Null
	False = values.False
	True  = values.True
)

Null, False and True are the three constant values.

Functions

func EvaluateLines

func EvaluateLines(expression string, r io.Reader, variables map[string]Value) iter.Seq2[Value, error]

EvaluateLines parses expression with the default options and evaluates it on each value of a JSON Lines stream, as Expression.Lines; a parse error is the first and only element.

func ToAny

func ToAny(v Value) any

ToAny converts a value to Go's any: nil, bool, float64, string, []any and map[string]any (Go maps have no order: an object's key order is lost; ToJSON keeps it). NaN and ±Infinity stay float64 as they are.

func ToJSON

func ToJSON(v Value) string

ToJSON gives the canonical text of a value (spec §5.1): compact, NaN as null, ±Infinity as ±1.7976931348623157e+308, numbers in their shortest form.

Types

type Array

type Array = values.Array

Array is the array of a Value (Count, At); Object is its object (Count, KeyAt, ValueAt, TryGetValue, in insertion order).

type Error

type Error struct {
	Message string
	Value   Value
}

Error is an error that reached the top of an expression: Value is the error value (what error(v) raised, or the message string of a builtin's error). The Message is the value itself when it is a string, else its JSON text followed by " (not a string)" (spec §10.1).

func (*Error) Error

func (e *Error) Error() string

type Expression

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

Expression is a jq expression parsed and bound once by Parse, to evaluate on any number of inputs. It is immutable and safe to evaluate concurrently from many goroutines, each evaluation with its own input and variables.

func MustParse

func MustParse(expression string) *Expression

MustParse is Parse for expressions known to be valid: it panics on an error.

func Parse

func Parse(expression string) (*Expression, error)

Parse parses and binds expression with the default options (no modules). An empty expression is `.`. The error is a *ParseError.

func ParseWithOptions

func ParseWithOptions(expression string, options Options) (*Expression, error)

ParseWithOptions parses and binds expression, loading its modules through the options' resolver, into an expression to evaluate any number of times, concurrently if need be. The error is a *ParseError.

func ParseWithResolver

func ParseWithResolver(expression string, resolver Resolver) (*Expression, error)

ParseWithResolver parses and binds expression, loading its modules through resolver, with the default options otherwise.

func (*Expression) Evaluate

func (e *Expression) Evaluate(input Value, variables map[string]Value) ([]Value, error)

Evaluate evaluates the expression on input and gives all its results. variables are the host variables, by name without '$' ("root" is $root): each name a jq identifier, ENV excluded (a *VariableError). A variable the expression uses but the host does not give is the runtime error "$name is not defined"; a binding in the expression shadows a host variable. When an error reaches the top of the expression (an *Error, or a *HaltError for halt_error), the results are nil.

func (*Expression) EvaluateFunc

func (e *Expression) EvaluateFunc(input Value, variables map[string]Value, onResult func(Value) bool) error

EvaluateFunc evaluates the expression on input, giving each result to onResult as soon as it is produced; onResult gives false to stop the evaluation (stopping is not an error). An error that reaches the top of the expression comes after the results produced before it.

func (*Expression) Lines

func (e *Expression) Lines(r io.Reader, variables map[string]Value) iter.Seq2[Value, error]

Lines evaluates the expression on each value of a JSON Lines stream in turn (one JSON value per line, blank lines skipped), yielding the results of each; the results of one input are computed before they are yielded. Each value is evaluated alone (spec §12): halt ends only the evaluation of its value. A line that is not JSON, an error that reaches the top of the expression or an error of the reader is yielded with Null and ends the sequence; breaking out of the loop stops reading.

func (*Expression) Results

func (e *Expression) Results(input Value, variables map[string]Value) iter.Seq2[Value, error]

Results evaluates the expression on input as a sequence for range: each result with a nil error, then, if an error reaches the top of the expression, Null with that error. Breaking out of the loop stops the evaluation.

type FSResolver

type FSResolver struct {
	FS   fs.FS
	Root string
}

FSResolver is a Resolver over an fs.FS (an embed.FS, for modules built into the program): a path is relative to the directory of the importing module, or to Root for the expression itself, and gets the extension .jq or .json when it has none. The canonical path is the path in the file system.

func (*FSResolver) CanonicalPath

func (r *FSResolver) CanonicalPath(p string, kind ModuleKind, _ *Value, fromPath string) (string, error)

func (*FSResolver) Open

func (r *FSResolver) Open(canonicalPath string) (io.ReadCloser, error)

type FileResolver

type FileResolver struct {
	BaseDirectory string
}

FileResolver is a Resolver over the file system: a path is relative to the directory of the importing module, or to BaseDirectory for the expression itself, and gets the extension .jq (code) or .json (data) when it has none. The canonical path is the absolute file path.

func NewFileResolver

func NewFileResolver(baseDirectory string) *FileResolver

NewFileResolver gives a resolver whose expressions' own directives are relative to baseDirectory.

func (*FileResolver) CanonicalPath

func (r *FileResolver) CanonicalPath(p string, kind ModuleKind, _ *Value, fromPath string) (string, error)

func (*FileResolver) Open

func (r *FileResolver) Open(canonicalPath string) (io.ReadCloser, error)

type HaltError

type HaltError struct {
	Message  string
	Value    Value
	ExitCode int
}

HaltError is halt_error ending an evaluation: Value is the value it was given and ExitCode its code. (halt ends an evaluation normally, without an error.)

func (*HaltError) Error

func (e *HaltError) Error() string

type Kind

type Kind = values.Kind

Kind is the kind of a Value, in jq's sort order.

type Member

type Member struct {
	Key   string
	Value Value
}

Member is a key and its value, for NewObject.

type ModuleKind

type ModuleKind int

ModuleKind tells whether an import asks for a code module (.jq) or a data module (import "p" as $name;, JSON values).

const (
	ModuleCode ModuleKind = iota
	ModuleData
)

The kinds of modules.

type Object

type Object = values.Object

Array is the array of a Value (Count, At); Object is its object (Count, KeyAt, ValueAt, TryGetValue, in insertion order).

type Options

type Options struct {
	// Resolver resolves import and include directives and modulemeta; without one, no module exists.
	Resolver Resolver

	// Environment is the variables of $ENV and env, as "NAME=value" entries in this order (the form
	// of os.Environ). When nil (the default), the process environment, read when an evaluation first
	// uses $ENV; an empty, non-nil slice is an empty $ENV.
	Environment []string

	// Now is the source of now; nil is time.Now.
	Now func() time.Time

	// Location is the local time zone of localtime, strflocaltime, %z and %Z; nil is time.Local. A
	// zone's name (time.Time.Zone) is the abbreviation of %Z; an empty name prints the offset.
	Location *time.Location

	// MaxDepth is the maximum number of calls of jq-defined functions active at once (spec §11);
	// beyond it, the catchable error "Maximum call depth exceeded". Deeper recursion never exhausts
	// the host stack. 0 is the default, 1000.
	MaxDepth int

	// Debug receives the value of each debug (its input) and each message of debug(msgs), as is.
	// Without one, the values are dropped.
	Debug func(Value)

	// Stderr receives the input of each stderr, as is. Without one, the values are dropped.
	Stderr func(Value)
}

Options is what an expression takes from its host besides the input and the variables: modules, $ENV, the clock and zone, the depth limit and the handlers of debug and stderr. Options are read when the expression is parsed and apply to every evaluation of it; the zero Options are the defaults.

type ParseError

type ParseError struct {
	// Message is the error with where it is: "<message> at [<module>, ]line L, column C".
	Message string
	// Line and Column are 1-based, in the expression or in the module Module (when not empty);
	// columns count code points.
	Line   int
	Column int
	Module string
}

ParseError is a syntax or binding error, given by Parse before any evaluation: an unknown function, label or module, a cycle of imports.

func (*ParseError) Error

func (e *ParseError) Error() string

type Resolver

type Resolver interface {
	// CanonicalPath gives the canonical path of the module path of the given kind, imported with
	// metadata (the directive's metadata object, or nil) from the module at fromPath (a canonical
	// path, or "" for the expression itself); "" when there is no such module. The same canonical
	// path means the same module.
	CanonicalPath(path string, kind ModuleKind, metadata *Value, fromPath string) (string, error)

	// Open opens the module at a canonical path that CanonicalPath gave.
	Open(canonicalPath string) (io.ReadCloser, error)
}

Resolver finds the modules of import and include directives and of modulemeta: maps a path, as written, to a canonical path (the module's identity), then opens it. A module is read once per canonical path while an expression is parsed. modulemeta calls the resolver while expressions are evaluated, possibly from several goroutines at once: implementations must allow that.

type Value

type Value = values.Value

Value is a jqlite value: null, false, true, a number (float64), a string, an array or an object whose keys keep their insertion order. Values are immutable and safe to share between goroutines. The zero Value is null.

Go has no standard ordered JSON value, so the host boundary exposes the engine's own value type, with conversions from and to JSON text (ParseJSON, ToJSON) and from and to Go's any (FromAny, ToAny).

func Bool

func Bool(b bool) Value

Bool gives true or false.

func Evaluate

func Evaluate(expression string, input Value, variables map[string]Value) ([]Value, error)

Evaluate parses expression with the default options and evaluates it on input, giving all its results.

func FromAny

func FromAny(v any) (Value, error)

FromAny converts a Go value: nil, bool, the integer and floating-point types, string, json.Number, a Value, []any (and any slice), map[string]any (and any map with string keys, keys sorted, since Go maps have no order). Anything else is an error.

func NewArray

func NewArray(items ...Value) Value

NewArray gives an array of the items.

func NewObject

func NewObject(members ...Member) Value

NewObject gives an object of the members, in their order; a repeated key keeps its first position and its last value.

func Number

func Number(n float64) Value

Number gives a number value.

func ParseJSON

func ParseJSON(text string) (Value, error)

ParseJSON reads exactly one JSON value (spec §5.3: NaN, Infinity and their relatives are read too, lone surrogate escapes become U+FFFD). The error's message is jq's, as fromjson gives it.

func String

func String(s string) Value

String gives a string value; each ill-formed UTF-8 sequence becomes U+FFFD (spec §4.1).

type VariableError

type VariableError struct {
	Name string
}

VariableError is a host variable name that is not valid (spec §12): not a jq identifier, or ENV.

func (*VariableError) Error

func (e *VariableError) Error() string

Directories

Path Synopsis
cmd
bench command
Command bench is the runner of the cross-language benchmark (bench/README.md): the same command line, the same three measurements and the same line of output in every port.
Command bench is the runner of the cross-language benchmark (bench/README.md): the same command line, the same three measurements and the same line of output in every port.
internal
binding
Package binding resolves the names of a parsed program (spec §7) into the bound program the interpreter evaluates, loads modules (§9.11) and holds the prelude and the native catalogue.
Package binding resolves the names of a parsed program (spec §7) into the bound program the interpreter evaluates, loads modules (§9.11) and holds the prelude and the native catalogue.
builtins
Package builtins implements the natives of spec §9 and registers them into runtime.NativeTable when it is initialized.
Package builtins implements the natives of spec §9 and registers them into runtime.NativeTable when it is initialized.
corpus
Package corpus reads the conformance corpus of spec/tests (format in spec/tests/README.md) for the tests of every layer.
Package corpus reads the conformance corpus of spec/tests (format in spec/tests/README.md) for the tests of every layer.
corpus/modules
Package modules holds the module sources of the tests: a directory with the path rule of spec/tests/README.md, and a map of texts.
Package modules holds the module sources of the tests: a directory with the path rule of spec/tests/README.md, and a map of texts.
runtime
Package runtime is the push-based interpreter of a bound program (spec §6 to §8), its environments, paths, signals, the host interface (evaluation.go) and the native table.
Package runtime is the push-based interpreter of a bound program (spec §6 to §8), its environments, paths, signals, the host interface (evaluation.go) and the native table.
syntax
Package syntax holds the lexer, the AST and the parser of jqlite (spec §2, §3).
Package syntax holds the lexer, the AST and the parser of jqlite (spec §2, §3).
values
Package values holds the jqlite value, its arrays and objects, and the operations on values: equality, ordering, arithmetic (value_ops.go), the JSON writer and reader (value_text.go) and every run-time message (errors.go).
Package values holds the jqlite value, its arrays and objects, and the operations on values: equality, ordering, arithmetic (value_ops.go), the JSON writer and reader (value_text.go) and every run-time message (errors.go).

Jump to

Keyboard shortcuts

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