expr

package
v0.4.0-rc.2 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 5 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.

Documentation

Overview

Package expr parses and evaluates a small, deterministic expression language with named variables and game functions, for data-driven conditions, formulas, cheat codes and console commands.

Index

Examples

Constants

View Source
const MaxDepth = 128

MaxDepth is the deepest nesting one expression may hold, bounding recursion in Parse and Eval.

View Source
const MaxNodes = 4096

MaxNodes is the most syntax nodes one expression may hold, so a mod's formula cannot make the game parse or evaluate an unbounded tree.

Variables

View Source
var (
	// ErrUnknownVariable reports a name the Env.Vars does not return.
	ErrUnknownVariable = errors.New("expr: unknown variable")
	// ErrUnknownFunction reports a function the Env.Funcs lacks.
	ErrUnknownFunction = errors.New("expr: unknown function")
	// ErrDivisionByZero reports a division or remainder by zero.
	ErrDivisionByZero = errors.New("expr: division by zero")
	// ErrCostLimit reports an expression longer than MaxNodes or nested deeper than MaxDepth.
	ErrCostLimit = errors.New("expr: expression too large")
)

Functions

func CheckSyntax

func CheckSyntax(src string) error

CheckSyntax validates src's grammar and enforces MaxNodes and MaxDepth without resolving variable or function names or checking types. Callers whose variable types or custom functions are bound later (such as dialogue scripts parsed before a runner is created) use CheckSyntax at load time and ParseVars at evaluation time.

Types

type Env

type Env struct {
	// Vars returns a variable's value. A missing variable makes the evaluation fail with ErrUnknownVariable.
	Vars func(name string) (Value, bool)
	// Funcs are the callable functions; a function the parser knew but this Env lacks fails with ErrUnknownFunction.
	Funcs map[string]Func
}

Env is what an expression evaluates against: the variables it may read and the functions it may call.

type Expr

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

Expr is one parsed and type-checked expression, safe to evaluate concurrently against different Envs.

func Parse

func Parse(src string, names []string, funcs map[string]Func) (*Expr, error)

Parse parses and type-checks src. names are the variables the expression may use, all numbers; funcs are the functions it may call beside the builtins floor, round, abs, min, max and clamp. A syntax or type error is a *ParseError with its column, and an expression over MaxNodes or MaxDepth is ErrCostLimit.

Example
package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/expr"
)

func main() {
	e, err := expr.Parse(`hp < 20 ? "wounded" : "ready"`, []string{"hp"}, nil)
	if err != nil {
		fmt.Println(err)
		return
	}
	text, err := e.String(&expr.Env{Vars: func(string) (expr.Value, bool) { return expr.Number(12), true }})
	fmt.Println(text, err)
}
Output:
wounded <nil>

func ParseVars

func ParseVars(src string, vars map[string]Kind, funcs map[string]Func) (*Expr, error)

ParseVars parses and type-checks src with explicitly typed variables. Each entry in vars maps a variable name (which may include dots, such as "player.hp") to its Kind; funcs are the functions it may call beside the builtins floor, round, abs, min, max and clamp. A syntax or type error is a *ParseError with its column, and an expression over MaxNodes or MaxDepth is ErrCostLimit.

func (*Expr) Bool

func (e *Expr) Bool(env *Env) (bool, error)

Bool evaluates the expression and requires a bool.

func (*Expr) Eval

func (e *Expr) Eval(env *Env) (Value, error)

Eval evaluates the expression against env. A missing variable or function, a division by zero and an error from a called function are returned; a type error cannot happen because Parse checked the types.

func (*Expr) Kind

func (e *Expr) Kind() Kind

Kind returns the type the expression evaluates to.

func (*Expr) NodeCount

func (e *Expr) NodeCount() int

NodeCount returns how many syntax nodes the expression holds.

func (*Expr) Number

func (e *Expr) Number(env *Env) (float64, error)

Number evaluates the expression and requires a number.

func (*Expr) Source

func (e *Expr) Source() string

Source returns the expression source text passed to Parse or ParseVars.

func (*Expr) String

func (e *Expr) String(env *Env) (string, error)

String evaluates the expression and requires a string.

type Func

type Func struct {
	// Params are the parameter kinds, in order.
	Params []Kind
	// Result is the kind Call returns.
	Result Kind
	// Call runs the function; an error stops the evaluation and is returned as is.
	Call func(args []Value) (Value, error)
}

Func is a function an expression may call. The parser checks its arity and parameter kinds, so Call can assume them.

type Kind

type Kind uint8

Kind is the type of a Value, and of a variable, function parameter or result.

const (
	// KindNumber is a float64.
	KindNumber Kind = iota
	// KindBool is true or false.
	KindBool
	// KindString is text.
	KindString
)

func (Kind) String

func (k Kind) String() string

String returns the kind's name.

type ParseError

type ParseError struct {
	// Pos is the 1-based column of the offending token.
	Pos int
	// Msg says what is wrong.
	Msg string
}

ParseError is a syntax or type error with its position in the source.

func (*ParseError) Error

func (e *ParseError) Error() string

Error returns the error with its position.

type Value

type Value struct {
	Kind Kind
	// contains filtered or unexported fields
}

Value is one typed value the language evaluates to.

func Bool

func Bool(v bool) Value

Bool returns a boolean value.

func Number

func Number(v float64) Value

Number returns a numeric value.

func String

func String(v string) Value

String returns a string value.

func (Value) AsBool

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

AsBool returns the boolean v holds, and false for any other kind.

func (Value) AsNumber

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

AsNumber returns the number v holds, and false for any other kind.

func (Value) AsString

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

AsString returns the text v holds, and false for any other kind.

Jump to

Keyboard shortcuts

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