expr

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: AGPL-3.0 Imports: 26 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 expr compiles and runs github.com/expr-lang/expr expressions, with SQL-style aliases for its operators.

Language

The language is expr's, with these aliases added:

env = "prod" AND region IN ["eu", "us"]
NOT (service.name CONTAINS "test") OR host REGEXP "^web-"

AND, OR, NOT, IN and CONTAINS are expr's and, or, not, in and contains, REGEXP and regexp are matches, and = is ==. Every expr operator and builtin works too. The aliases are all upper case or all lower case, so "And" is an error, and NOT binds tighter than =, so NOT (a = b) needs its parentheses. Text in quotes and member names, as in attributes.regexp, are never respelled, and neither is the = of let x = 1.

Untyped, TypedDynamic and TypedStatic

An Env says when names get their types. Untyped never types them. TypedDynamic types them when the program runs, from the variables it runs with. TypedStatic types them when the program compiles, from variables declared as a struct. When the types fit, as in value = "92", all three give the same result. They differ in which names exist, when a type error shows and how a missing value reads. With the variables {"value": "92"}, declared for TypedStatic as struct{ Value string `expr:"value"` }:

expression           Untyped                  TypedDynamic                TypedStatic
value > 80           run error: string > int  type error: string and int  compile error: string and int
cluster.name = "c1"  run error: no cluster    false                       compile error: unknown name
plan                 false                    error: the result is nil    compile error: unknown name

An Untyped program is compiled once and knows no types until it runs, so a mistake shows as CodeRunFailed, a.b fails when a is missing, and a nil result is false.

A TypedDynamic program is typed against the top-level types of the variables it runs with, compiled once for each set of those types, so a mistake shows as CodeTypeInvalid when it runs. Member access is nil-safe: a.b is nil when a is missing or isn't a map. A nil result is an error. Nest turns flat dotted keys into the nested maps a TypedDynamic program reads.

A TypedStatic program is compiled once against the declared variables, so an unknown name, a misspelled field or a wrong type is a compile error. A missing key of a map or any value, such as a field of parsed JSON, is nil. A nil result is an error.

Limits

Env.LimitNesting, Env.LimitPattern, Env.LimitNodes and Env.LimitMemory bound what a program can cost: how deep list functions nest, how long a REGEXP pattern is, how many nodes the program has and how much it allocates in a run. Each limit is unset by default.

Schema, references and values

Env.Schema describes an Env's names for a client, such as an editor that checks expressions as they are typed or a docs page: the declared vars of a TypedStatic Env, as expr's docgen describes them, and the limits programs compile with.

Program.References lists the variables an expression reads, as paths such as tls.version. Program.ReferenceValues runs each of them with a set of variables and returns their values as text, to show what an expression saw when it didn't match.

Patches

Env.Patch adds a caller's own rewrite of the syntax tree, such as reading body.x from a parsed copy of the body. A patch is a github.com/expr-lang/expr/ast.Visitor, and the patches the package applies itself are in github.com/SigNoz/baseplate.go/expr/patcher.

Usage

Compile once and run as often as needed; a Program is safe for concurrent use:

program, err := expr.Compile(`env = "prod" AND region IN ["eu"]`, expr.TypedDynamic())
if err != nil {
	return err
}

env, _ := expr.Nest(flat)
matched, err := program.Bool(env)

Compile is for expressions whose result is a bool, and CompileValue for any value.

Errors

Every error is a github.com/SigNoz/baseplate.go/errors.TypeInvalidInput error with one of the package's codes, such as CodeSyntaxInvalid or CodeTypeInvalid, and a one-line message. An error at a place in the expression wraps an *PositionError with its offsets, line and column in the text as written:

if position, ok := errors.AsType[*expr.PositionError](err); ok {
	fmt.Println(position.Line, position.Column)
}

The error's text ends with the line and a caret under the error, as expr prints it.

Example
package main

import (
	"fmt"

	"github.com/SigNoz/baseplate.go/expr"
)

func main() {
	program, err := expr.Compile(`env = "prod" AND service.name IN ["api", "web"]`, expr.TypedDynamic())
	if err != nil {
		panic(err)
	}

	env, _ := expr.Nest(map[string]string{"env": "prod", "service.name": "api"})

	matched, err := program.Bool(env)
	if err != nil {
		panic(err)
	}

	_, _ = fmt.Println(matched)
}
Output:
true

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	CodeSyntaxInvalid   = errors.MustNewCode("syntax_invalid")
	CodeTypeInvalid     = errors.MustNewCode("type_invalid")
	CodeResultNotBool   = errors.MustNewCode("result_not_bool")
	CodeNodesExceeded   = errors.MustNewCode("nodes_exceeded")
	CodeRunFailed       = errors.MustNewCode("run_failed")
	CodeNestingTooDeep  = errors.MustNewCode("nesting_too_deep")
	CodePatternInvalid  = errors.MustNewCode("pattern_invalid")
	CodeMemoryExceeded  = errors.MustNewCode("memory_exceeded")
	CodeVarsInvalid     = errors.MustNewCode("vars_invalid")
	CodeNameUnknown     = errors.MustNewCode("name_unknown")
	CodeFunctionUnknown = errors.MustNewCode("function_unknown")
)

The codes of the errors Compile, CompileValue, Program.Bool and Program.Run return.

Functions

func Nest

func Nest[K ~string, V ~string](flat map[K]V) (map[string]any, bool)

Nest returns a flat map with dotted keys as nested maps, the variables a TypedDynamic program reads: "k8s.pod.name" becomes k8s.pod.name. Keys and their dotted segments are trimmed of spaces.

When a dotted key and a plain key collide, such as "foo" and "foo.bar", the nested map wins and the second return value is true. The same holds for a deeper dotted key over a shallower one. Which of two keys that are equal after trimming wins is unspecified.

Example
package main

import (
	"fmt"

	"github.com/SigNoz/baseplate.go/expr"
)

func main() {
	env, conflict := expr.Nest(map[string]string{"k8s.pod.name": "api-7f9c", "k8s.namespace": "alpha"})
	_, _ = fmt.Println(env, conflict)

	_, conflict = expr.Nest(map[string]string{"host": "web-1", "host.name": "web-1.internal"})
	_, _ = fmt.Println(conflict)
}
Output:
map[k8s:map[namespace:alpha pod:map[name:api-7f9c]]] false
true

Types

type Env

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

Env is how an expression's names are typed, the patches its programs apply and the limits they keep to. The zero Env is Untyped.

func TypedDynamic

func TypedDynamic() Env

TypedDynamic returns an Env that types a program when it runs, against each set of variables it runs with, such as the nested maps Nest returns. Any name is allowed, and member access is nil-safe, as patcher.NilSafe makes it. A program is typed against the top-level types of each set of variables and compiled once for each set of those types. A nil or non-bool result of a [Compile]d program is an error.

With the variables {"value": "92"}:

value > 80           type error (CodeTypeInvalid): string and int
cluster.name = "c1"  false
plan                 error (CodeResultNotBool): the result is nil
Example
package main

import (
	"fmt"

	"github.com/SigNoz/baseplate.go/expr"
)

func main() {
	program, err := expr.Compile(`cluster.name = "alpha"`, expr.TypedDynamic())
	if err != nil {
		panic(err)
	}

	for _, flat := range []map[string]string{
		{"cluster.name": "alpha"},
		{"cluster": "alpha"},
		{"env": "prod"},
	} {
		env, _ := expr.Nest(flat)

		matched, err := program.Bool(env)
		_, _ = fmt.Println(matched, err)
	}
}
Output:
true <nil>
false <nil>
false <nil>

func TypedStatic

func TypedStatic(vars any) Env

TypedStatic returns an Env that types a program when it compiles, against vars: a struct, whose fields are named by their expr tag or else their Go name, or a map of typed zero values. Only the names vars declares exist, so an unknown name, a wrong type or a misspelled field is a compile error. An unknown var or field is CodeNameUnknown, and an unknown function is CodeFunctionUnknown. Member access is nil-safe on map and any values, as patcher.NilSafeTyped makes it, and checked on struct fields. A nil or non-bool result of a [Compile]d program is an error. Run the program with a value of the same type as vars.

The name of every var and field must be one identifier other than an alias such as AND, and a var's name must not be a builtin function, true, false, nil or $env. Compile returns a github.com/SigNoz/baseplate.go/errors.TypeInvalidInput error with CodeVarsInvalid when vars breaks these rules, or isn't a struct or a map[string]any.

With vars of type struct{ Value string `expr:"value"` }:

value > 80           compile error (CodeTypeInvalid): string and int
cluster.name = "c1"  compile error (CodeNameUnknown): unknown name
plan                 compile error (CodeNameUnknown): unknown name
Example
package main

import (
	"fmt"
	"time"

	"github.com/SigNoz/baseplate.go/errors"
	"github.com/SigNoz/baseplate.go/expr"
)

func main() {
	type tls struct {
		Version string `expr:"version"`
	}

	type check struct {
		StatusCode   int           `expr:"status_code"`
		ResponseTime time.Duration `expr:"response_time"`
		JSON         any           `expr:"json"`
		TLS          tls           `expr:"tls"`
	}

	env := expr.TypedStatic(check{}).LimitNesting(1).LimitPattern(256)

	_, err := expr.Compile(`tls.vrsion = "1.3"`, env)
	_, _ = fmt.Println(errors.CodeOf(err), errors.MessageOf(err))

	program, err := expr.Compile(`status_code = 200 AND response_time < duration("1s") AND json.missing = nil`, env)
	if err != nil {
		panic(err)
	}

	passed, err := program.Bool(check{
		StatusCode:   200,
		ResponseTime: 120 * time.Millisecond,
		JSON:         map[string]any{"state": "ok"},
	})
	_, _ = fmt.Println(passed, err)
}
Output:
name_unknown type expr_test.tls has no field vrsion
true <nil>

func Untyped

func Untyped() Env

Untyped returns an Env in which any name is allowed and nothing is typed until the program runs. Member access isn't nil-safe: a.b fails when a is missing. A [Compile]d program returns false for a nil result.

With the variables {"value": "92"}:

value > 80           run error (CodeRunFailed): string > int
cluster.name = "c1"  run error (CodeRunFailed): cannot fetch name
plan                 false
Example
package main

import (
	"fmt"

	"github.com/SigNoz/baseplate.go/expr"
)

func main() {
	program, err := expr.Compile(`attributes["level"] = "error" AND body CONTAINS "timeout"`, expr.Untyped())
	if err != nil {
		panic(err)
	}

	matched, err := program.Bool(map[string]any{
		"attributes": map[string]any{"level": "error"},
		"body":       "upstream timeout after 30s",
	})
	_, _ = fmt.Println(matched, err)

	missing, err := program.Bool(map[string]any{"attributes": map[string]any{}})
	_, _ = fmt.Println(missing, err)
}
Output:
true <nil>
false <nil>

func (Env) LimitMemory

func (e Env) LimitMemory(n uint) Env

LimitMemory returns a copy of e whose programs allocate at most n units of expr's memory budget in a run. Zero, the default, keeps expr's own budget. Program.Run and Program.Bool return a github.com/SigNoz/baseplate.go/errors.TypeInvalidInput error with CodeMemoryExceeded for a run over it.

func (Env) LimitNesting

func (e Env) LimitNesting(n uint) Env

LimitNesting returns a copy of e whose programs reject a list function, such as all or filter, nested more than n deep in another's predicate, so a program's run time stays linear in the size of its input. Zero, the default, sets no limit. Compile returns a github.com/SigNoz/baseplate.go/errors.TypeInvalidInput error with CodeNestingTooDeep for a program over it.

func (Env) LimitNodes

func (e Env) LimitNodes(n uint) Env

LimitNodes returns a copy of e whose programs have at most n nodes. Zero, the default, keeps expr's own limit. Compile returns a github.com/SigNoz/baseplate.go/errors.TypeInvalidInput error with CodeNodesExceeded for a program over it.

func (Env) LimitPattern

func (e Env) LimitPattern(n uint) Env

LimitPattern returns a copy of e whose programs require the pattern of every REGEXP (or matches) to be a string literal of at most n characters, so patterns compile once. Expr itself rejects an invalid literal pattern, with CodeTypeInvalid. Zero, the default, sets no limit. Compile returns a github.com/SigNoz/baseplate.go/errors.TypeInvalidInput error with CodePatternInvalid for a pattern that breaks it.

func (Env) Patch

func (e Env) Patch(v ast.Visitor) Env

Patch returns a copy of e whose programs apply v when they compile. A patch rewrites the syntax tree in place, as those in github.com/SigNoz/baseplate.go/expr/patcher do. Patches run in the order they were added, and before the nil-safe patch of a TypedDynamic program, so they see member access as written.

An Untyped program runs each patch once, in Compile. A TypedDynamic program runs it again for each new set of top-level variable types, from whichever goroutine runs the program, so a patch that keeps state sees every tree it rewrites and must be safe for concurrent use. Since a patch can make the program read any name, a TypedDynamic program with patches compiles again when the type of any of its variables changes, not only of the names it was written with.

Example
package main

import (
	"fmt"

	"github.com/expr-lang/expr/ast"

	"github.com/SigNoz/baseplate.go/expr"
)

// tBodyField reads a member of body from a parsed copy of it, body_map.
type tBodyField struct{}

func (tBodyField) Visit(node *ast.Node) {
	member, ok := (*node).(*ast.MemberNode)
	if !ok {
		return
	}

	if root, ok := member.Node.(*ast.IdentifierNode); ok && root.Value == "body" {
		root.Value = "body_map"
	}
}

func main() {
	program, err := expr.Compile(`body.level = "error"`, expr.Untyped().Patch(tBodyField{}))
	if err != nil {
		panic(err)
	}

	matched, err := program.Bool(map[string]any{
		"body":     `{"level": "error"}`,
		"body_map": map[string]any{"level": "error"},
	})
	_, _ = fmt.Println(matched, err)
}
Output:
true <nil>

func (Env) Schema

func (e Env) Schema() (Schema, error)

Schema returns the schema of e's programs. It returns the errors TypedStatic reports for vars that break its rules.

type Limits

type Limits struct {
	Nesting uint `json:"nesting,omitempty"`
	Pattern uint `json:"pattern,omitempty"`
	Nodes   uint `json:"nodes,omitempty"`
}

Limits are the limits a program is compiled with. Zero is unset. The memory limit is left out, as it only applies when a program runs.

type PositionError

type PositionError struct {
	From   int `json:"from"`   // Offset of the first code point, from 0.
	To     int `json:"to"`     // Offset after the last code point.
	Line   int `json:"line"`   // From 1.
	Column int `json:"column"` // From 1, in code points.
	// contains filtered or unexported fields
}

PositionError is where in an expression's source an error is. It is the cause of every error with a position that Compile, CompileValue, Program.Bool and Program.Run return; the type, code and message are on the github.com/SigNoz/baseplate.go/errors error that wraps it. Get it with github.com/SigNoz/baseplate.go/errors.AsType.

func (*PositionError) Error

func (e *PositionError) Error() string

Error returns the line and column, followed by the source line with a caret under the error.

type Program

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

Program is a compiled expression. It is safe for concurrent use.

func Compile

func Compile(src string, env Env) (*Program, error)

Compile compiles an expression whose result is a bool.

It returns a github.com/SigNoz/baseplate.go/errors.TypeInvalidInput error with CodeSyntaxInvalid when src doesn't parse, CodeNodesExceeded when it has too many nodes, CodeTypeInvalid for a type error and CodeResultNotBool when its result is known not to be a bool. An error at a place in src wraps a *PositionError.

Example (Error)
package main

import (
	"fmt"

	"github.com/SigNoz/baseplate.go/errors"
	"github.com/SigNoz/baseplate.go/expr"
)

func main() {
	_, err := expr.Compile(`env = "prod" AND "5" > 3`, expr.TypedDynamic())
	if err != nil {
		_, _ = fmt.Println(errors.CodeOf(err))
		_, _ = fmt.Println(errors.MessageOf(err))
	}

	program, err := expr.Compile(`env = "prod" AND`, expr.Untyped())
	_, _ = fmt.Println(program == nil, errors.CodeOf(err))

	if position, ok := errors.AsType[*expr.PositionError](err); ok {
		_, _ = fmt.Println(position.Line, position.Column)
	}

	_, _ = fmt.Println(err)
}
Output:
type_invalid
invalid operation: > (mismatched types string and int)
true syntax_invalid
1 16
unexpected token EOF: (1:16)
 | env = "prod" AND
 | ...............^

func CompileValue

func CompileValue(src string, env Env) (*Program, error)

CompileValue compiles an expression whose result can be any value. It returns the errors Compile does, except CodeResultNotBool.

Example
package main

import (
	"fmt"

	"github.com/SigNoz/baseplate.go/expr"
)

func main() {
	program, err := expr.CompileValue(`lower(attributes["level"]) + "-" + string(severity_number)`, expr.Untyped())
	if err != nil {
		panic(err)
	}

	value, err := program.Run(map[string]any{
		"attributes":      map[string]any{"level": "ERROR"},
		"severity_number": 17,
	})
	_, _ = fmt.Println(value, err)
}
Output:
error-17 <nil>

func (*Program) Bool

func (p *Program) Bool(vars any) (bool, error)

Bool runs the program with vars and returns its bool result. A TypedDynamic program takes a map[string]any, such as one from Nest.

It returns a github.com/SigNoz/baseplate.go/errors.TypeInvalidInput error with CodeRunFailed when the run fails and CodeResultNotBool when the result isn't a bool. A TypedDynamic program can also return the errors of Compile, since it is typed against vars.

func (*Program) ReferenceValues

func (p *Program) ReferenceValues(vars any) map[string]string

ReferenceValues runs each of Program.References with vars and returns its value as text, at most 256 characters, to show what an expression saw. Strings are as they are, nil is "nil", lists, maps and structs are JSON, or their type when JSON can't encode them, as with a map that holds itself, and other values are formatted as Go formats them. A reference that fails to compile or run is left out.

func (*Program) References

func (p *Program) References() []string

References returns the variables the expression reads, sorted, as paths such as tls.version or headers["content-type"]. A key that is a plain name is written with a dot, so headers["server"] gives headers.server. A path stops where the expression stops naming members by string, so json.items[0].ok gives json.items. A read through $env gives the variable's path, so $env.status_code gives status_code.

func (*Program) Run

func (p *Program) Run(vars any) (any, error)

Run runs the program with vars and returns its result. It returns the errors Program.Bool does, except CodeResultNotBool.

func (*Program) Source

func (p *Program) Source() string

Source returns the expression as it was written.

type Schema

type Schema struct {
	Vars   *docgen.Context `json:"vars,omitempty"` // Nil unless the Env is TypedStatic; the others allow any name.
	Limits Limits          `json:"limits"`
}

Schema is what an Env's programs can read, for a client such as an editor or a docs page: the declared vars of a TypedStatic Env, as expr's docgen describes them, and the limits programs compile with.

Directories

Path Synopsis
Package patcher holds the syntax tree patches github.com/SigNoz/baseplate.go/expr applies when it compiles an expression.
Package patcher holds the syntax tree patches github.com/SigNoz/baseplate.go/expr applies when it compiles an expression.

Jump to

Keyboard shortcuts

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