Skip to content

HMath.Expression

Module index · Numerical conventions

Description

A pure, bounded real expression language shared with HMath.Symbolic.

Grammar: let name = expression in expression; left-associative + - * /; right-associative ^; unary + - binds below powers (-2^2 = -(2^2)). Calls use commas; literals are integers, exact decimal/scientific notation, or numerator//denominator. Constants are pi, e and tau. Identifiers contain letters, digits and underscores and start with a letter or underscore.

Values select exact Rational or finite Double arithmetic. Exact mode rejects transcendental functions and irrational square roots rather than rounding them. There is no IO, reflection, dynamically supplied Haskell function or code execution. The registry maps allowed names to a closed set of builtins. Let is strict and lexically scoped. Expression identity ignores source locations, otherwise it is structural; algebraic equality is a separate symbolic operation.

Limits cover input characters, AST/payload units, recursion, arithmetic steps and integer bits. They are conservative work/allocation limits, not operating-system byte or wall-clock quotas. Intermediate rational sizes are checked before large arithmetic. Compilation/CSE and cache insertion use the same bounded validator. Compiler traversal and evaluation have separate fresh budgets; cache hits still revalidate limits, registry and bindings when evaluated. Only trusted callers should construct an AST directly; validation rejects malformed names and shapes.

On this page

API Purpose
SourcePos Zero-based offset and one-based linecolumn.
SourcePos Declaration and type contract below.
sourceOffset Zero-based source character offset; generated nodes use zero.
sourceLine One-based source line, or zero for generated unknown positions.
sourceColumn One-based source column, or zero for generated unknown positions.
unknownPosition Source position sentinel (offset,line,column)=(0,0,0), used by programmatically constructed nodes rather than parsed source positions.
Expr Positioned expression syntax tree.
Expr Declaration and type contract below.
expressionPosition Source location carried by this Expr for positioned errors.
expressionNode Literalvariableoperatorcalllet structure of this expression.
ExprNode Expression syntax: exact literal,named variableconstant,unarybinary operation,registered call,or lexically scoped let binding.
Literal Declaration and type contract below.
Variable Declaration and type contract below.
Constant Declaration and type contract below.
Unary Declaration and type contract below.
Binary Declaration and type contract below.
Call Declaration and type contract below.
Let Declaration and type contract below.
UnaryOp Unary expression operator; Negate changes the operand sign.
Negate Declaration and type contract below.
BinaryOp Arithmetic expression operator: addition,subtraction,multiplication,division,or exponentiation.
Add Declaration and type contract below.
Subtract Declaration and type contract below.
Multiply Declaration and type contract below.
Divide Declaration and type contract below.
Power Declaration and type contract below.
NamedConstant Symbolic pi,Euler number e,or tau=2*pi.
Pi Declaration and type contract below.
Euler Declaration and type contract below.
Tau Declaration and type contract below.
literal Construct an exact Rational literal Expr at unknownPosition.
variable Construct a named variable Expr at unknownPosition; lookup and limit validation occur during checked processing.
constant Construct a PiEulerTau named-constant Expr at unknownPosition, without numeric evaluation.
unary Given UnaryOp then child Expr, construct an unevaluated unary node at unknownPosition.
binary Given BinaryOp,left Expr,right Expr, construct an unevaluated binary node at unknownPosition.
call Given function name then argument Expr list, construct a call node at unknownPosition.
letIn Given binding name,value Expr,body Expr, construct a lexically scoped let node at unknownPosition.
Limits Explicit resource budgets checked before parsing,evaluation,serialization,and cache growth; start from defaultLimits.
Limits Declaration and type contract below.
maximumSteps Maximum checked evaluation/rewrite instruction steps.
maximumDepth Maximum permitted parser/expression recursion depth.
maximumNodes Maximum expression or compiled-node storage budget.
maximumInputChars Maximum accepted input/serialized text characters.
maximumIntegerBits Maximum exact-integer bit length in checked arithmetic.
maximumCacheEntries Maximum retained compiled-expression cache entries; zero disables retention.
defaultLimits Default expression budgets: 100000 steps, depth 128, 20000 nodes, 100000 input characters, 1024 integer bits and 64 cache entries.
ExprError Structured expression failure with category,source position,and human-readable detail.
ExprError Declaration and type contract below.
errorKind Structured syntax,name,domain,type,nonfinite,unsupported,or resource-error category.
errorPosition Source position attached to the failed operation.
errorMessage Human-readable detail for this expression failure.
ErrorKind Expression error category distinguishing syntaxnametypedomainnonfinite failures from bounded-resource exhaustion and unsupported operations.
SyntaxError Declaration and type contract below.
UnknownName Declaration and type contract below.
TypeMismatch Declaration and type contract below.
DomainFailure Declaration and type contract below.
NonFinite Declaration and type contract below.
StepLimit Declaration and type contract below.
DepthLimit Declaration and type contract below.
MemoryLimit Declaration and type contract below.
InvalidLimits Declaration and type contract below.
Unsupported Declaration and type contract below.
validateLimits Return Right () if all resource budgets fit implementation bounds: steps 1..10000000, depth 1..256, nodes 1..100000, input chars 1..1000000, integer bits 2..8192, cache entries 0..1024.
validateExpression Validate size before traversing arbitrary user-created trees further.
parseExpression Parse with positions and a bounded lexer.
prettyExpression Fully parenthesized, deterministic grammar output.
freeVariables Return sorted distinct variable names free in an Expr, respecting lexical let bindings.
Precision Expression numeric mode: ExactRational retains exact supported rational arithmetic; Float64 uses checked binary64 evaluation.
ExactRational Declaration and type contract below.
Float64 Declaration and type contract below.
Value Evaluation result tagged ExactValue Rational or FloatValue Double.
ExactValue Declaration and type contract below.
FloatValue Declaration and type contract below.
Bindings Map from variable names to tagged expression Values.
Builtin Finite whitelist of supported scalar operations; Registry maps valid names/aliases to these selectors, never arbitrary host code.
Sin Declaration and type contract below.
Cos Declaration and type contract below.
Tan Declaration and type contract below.
Exp Declaration and type contract below.
Log Declaration and type contract below.
Sqrt Declaration and type contract below.
Abs Declaration and type contract below.
Signum Declaration and type contract below.
Floor Declaration and type contract below.
Ceiling Declaration and type contract below.
Min Declaration and type contract below.
Max Declaration and type contract below.
Asin Declaration and type contract below.
Acos Declaration and type contract below.
Atan Declaration and type contract below.
Sinh Declaration and type contract below.
Cosh Declaration and type contract below.
Tanh Declaration and type contract below.
Registry Immutable safe builtin-name registry, initialized with emptyRegistry or defaultRegistry and extended with registerFunction.
defaultRegistry Registry of supported safe scalar builtins (trigonometric/hyperbolic functions, explogsqrt, abssignum, rounding and minmax).
emptyRegistry Construct a registry containing no builtins; callers may add permitted names with registerFunction.
registerFunction Given valid identifier name,Builtin selector,then registry, insert or replace an alias.
allowedFunctions Sorted function and alias names accepted by a registry; no evaluation occurs.
typeCheckExpression Static scalarprecisionname/arity checking.
evaluateExpression Direct left-to-right evaluation.
evaluateText Given limits,precision,registry,bindings,then source text, parse and evaluate under the checked expression budgets.
Compiled Opaque validated expression DAG with common-subexpression sharing and source locations.
compileExpression Compile to a hash-consed DAG.
compiledNodeCount Number of unique DAG instructions after common-subexpression sharing.
evaluateCompiled DAG evaluation memoizes successful nodes only; errors keep the first left-to-right source location.
optimizeExpression Conservative constant folding of literal arithmetic only.
ExpressionCache Immutable FIFO cache.
emptyExpressionCache Construct an empty immutable compiled-expression cache. cachedExpression returns an updated cache explicitly.
cachedExpression Given limits,source text,then cache, return (compiled expression,updated cache), reusing a matching entry when permitted.
cacheSize Return number of retained compiled-source entries; does not compile or evaluate anything.
formatScientific Scientific notation with 0..30 fractional digits, for finite values.
formatRadix Integer radix 2..36; fractional values and nonfinite Double are rejected.
serializeExpression Given limits then Expr, validate its structure and produce versioned safe textual encoding, retaining expression structure.
deserializeExpression Given limits then encoded text, parse the supported serialization and revalidate its structure.
expressionHash Stable FNV-1a over canonical serialization Unicode code points (not UTF-8 bytes).

Documentation

SourcePos

data SourcePos Source #

Zero-based offset and one-based linecolumn. Generated expressions use 00/0.

Constructors

SourcePos 

Fields

  • sourceOffset :: Int

    Zero-based source character offset; generated nodes use zero.

  • sourceLine :: Int

    One-based source line, or zero for generated unknown positions.

  • sourceColumn :: Int

    One-based source column, or zero for generated unknown positions.

Instances

Instances details
Show SourcePos Source # 
Instance details

Defined in HMath.Expression

Eq SourcePos Source # 
Instance details

Defined in HMath.Expression

Ord SourcePos Source # 
Instance details

Defined in HMath.Expression

unknownPosition

unknownPosition :: SourcePos Source #

Source position sentinel (offset,line,column)=(0,0,0), used by programmatically constructed nodes rather than parsed source positions.

Expr

data Expr Source #

Positioned expression syntax tree. Smart builders use unknownPosition; parsed nodes retain source locations. Validation/evaluation returns structured ExprError rather than executing host code.

Constructors

Expr 

Fields

Instances

Instances details
Show Expr Source # 
Instance details

Defined in HMath.Expression

Methods

showsPrec :: Int -> Expr -> ShowS #

show :: Expr -> String #

showList :: [Expr] -> ShowS #

Eq Expr Source # 
Instance details

Defined in HMath.Expression

Methods

(==) :: Expr -> Expr -> Bool #

(/=) :: Expr -> Expr -> Bool #

Ord Expr Source # 
Instance details

Defined in HMath.Expression

Methods

compare :: Expr -> Expr -> Ordering #

(<) :: Expr -> Expr -> Bool #

(<=) :: Expr -> Expr -> Bool #

(>) :: Expr -> Expr -> Bool #

(>=) :: Expr -> Expr -> Bool #

max :: Expr -> Expr -> Expr #

min :: Expr -> Expr -> Expr #

ExprNode

data ExprNode Source #

Expression syntax: exact literal,named variableconstant,unarybinary operation,registered call,or lexically scoped let binding.

Instances

Instances details
Show ExprNode Source # 
Instance details

Defined in HMath.Expression

Eq ExprNode Source # 
Instance details

Defined in HMath.Expression

Ord ExprNode Source # 
Instance details

Defined in HMath.Expression

UnaryOp

data UnaryOp Source #

Unary expression operator; Negate changes the operand sign.

Constructors

Negate 

Instances

Instances details
Show UnaryOp Source # 
Instance details

Defined in HMath.Expression

Eq UnaryOp Source # 
Instance details

Defined in HMath.Expression

Methods

(==) :: UnaryOp -> UnaryOp -> Bool #

(/=) :: UnaryOp -> UnaryOp -> Bool #

Ord UnaryOp Source # 
Instance details

Defined in HMath.Expression

BinaryOp

data BinaryOp Source #

Arithmetic expression operator: addition,subtraction,multiplication,division,or exponentiation. Evaluation enforces the selected numeric/domain limits.

Constructors

Add 
Subtract 
Multiply 
Divide 
Power 

Instances

Instances details
Show BinaryOp Source # 
Instance details

Defined in HMath.Expression

Eq BinaryOp Source # 
Instance details

Defined in HMath.Expression

Ord BinaryOp Source # 
Instance details

Defined in HMath.Expression

NamedConstant

data NamedConstant Source #

Symbolic pi,Euler number e,or tau=2*pi. Precision mode determines how a constant is evaluated.

Constructors

Pi 
Euler 
Tau 

literal

literal :: Rational -> Expr Source #

Construct an exact Rational literal Expr at unknownPosition. This builder does not validate resource limits; evaluation/serialization performs checked validation.

variable

variable :: String -> Expr Source #

Construct a named variable Expr at unknownPosition; lookup and limit validation occur during checked processing.

constant

constant :: NamedConstant -> Expr Source #

Construct a PiEulerTau named-constant Expr at unknownPosition, without numeric evaluation.

unary

unary :: UnaryOp -> Expr -> Expr Source #

Given UnaryOp then child Expr, construct an unevaluated unary node at unknownPosition.

binary

binary :: BinaryOp -> Expr -> Expr -> Expr Source #

Given BinaryOp,left Expr,right Expr, construct an unevaluated binary node at unknownPosition. Domain and resource checks occur when evaluated.

call

call :: String -> [Expr] -> Expr Source #

Given function name then argument Expr list, construct a call node at unknownPosition. Evaluation resolves the supplied registry; construction does not execute a function.

letIn

letIn :: String -> Expr -> Expr -> Expr Source #

Given binding name,value Expr,body Expr, construct a lexically scoped let node at unknownPosition. The binding applies in the body, not its own value expression.

Limits

data Limits Source #

Explicit resource budgets checked before parsing,evaluation,serialization,and cache growth; start from defaultLimits.

Constructors

Limits 

Fields

Instances

Instances details
Show Limits Source # 
Instance details

Defined in HMath.Expression

Eq Limits Source # 
Instance details

Defined in HMath.Expression

Methods

(==) :: Limits -> Limits -> Bool #

(/=) :: Limits -> Limits -> Bool #

defaultLimits

defaultLimits :: Limits Source #

Default expression budgets: 100000 steps, depth 128, 20000 nodes, 100000 input characters, 1024 integer bits and 64 cache entries. Use record updates; validateLimits checks hard implementation bounds.

ExprError

data ExprError Source #

Structured expression failure with category,source position,and human-readable detail.

Constructors

ExprError 

Fields

Instances

Instances details
Show ExprError Source # 
Instance details

Defined in HMath.Expression

Eq ExprError Source # 
Instance details

Defined in HMath.Expression

ErrorKind

data ErrorKind Source #

Expression error category distinguishing syntaxnametypedomainnonfinite failures from bounded-resource exhaustion and unsupported operations.

Instances

Instances details
Show ErrorKind Source # 
Instance details

Defined in HMath.Expression

Eq ErrorKind Source # 
Instance details

Defined in HMath.Expression

Ord ErrorKind Source # 
Instance details

Defined in HMath.Expression

validateLimits

validateLimits :: Limits -> Either ExprError () Source #

Return Right () if all resource budgets fit implementation bounds: steps 1..10000000, depth 1..256, nodes 1..100000, input chars 1..1000000, integer bits 2..8192, cache entries 0..1024. Otherwise return ExprError InvalidLimits.

validateExpression

validateExpression :: Limits -> Expr -> Either ExprError () Source #

Validate size before traversing arbitrary user-created trees further.

parseExpression

parseExpression :: Limits -> String -> Either ExprError Expr Source #

Parse with positions and a bounded lexer. Parentheses, calls, unary chains and right-associative powers all count toward parser recursion.

prettyExpression

prettyExpression :: Expr -> String Source #

Fully parenthesized, deterministic grammar output. Signed literal folding during parsing is intentional; serialization additionally preserves raw nodes.

freeVariables

freeVariables :: Expr -> [String] Source #

Return sorted distinct variable names free in an Expr, respecting lexical let bindings. No evaluation or name lookup occurs.

Precision

data Precision Source #

Expression numeric mode: ExactRational retains exact supported rational arithmetic; Float64 uses checked binary64 evaluation. Unsupported exact transcendental operations return structured errors.

Constructors

ExactRational 
Float64 

Instances

Instances details
Show Precision Source # 
Instance details

Defined in HMath.Expression

Eq Precision Source # 
Instance details

Defined in HMath.Expression

Ord Precision Source # 
Instance details

Defined in HMath.Expression

Value

data Value Source #

Evaluation result tagged ExactValue Rational or FloatValue Double. The selected Precision controls permitted operations and conversions.

Instances

Instances details
Show Value Source # 
Instance details

Defined in HMath.Expression

Methods

showsPrec :: Int -> Value -> ShowS #

show :: Value -> String #

showList :: [Value] -> ShowS #

Eq Value Source # 
Instance details

Defined in HMath.Expression

Methods

(==) :: Value -> Value -> Bool #

(/=) :: Value -> Value -> Bool #

Bindings

type Bindings = Map String Value Source #

Map from variable names to tagged expression Values. Lexical let bindings extend the environment inside their body.

Builtin

data Builtin Source #

Finite whitelist of supported scalar operations; Registry maps valid names/aliases to these selectors, never arbitrary host code.

Constructors

Sin 
Cos 
Tan 
Exp 
Log 
Sqrt 
Abs 
Signum 
Floor 
Ceiling 
Min 
Max 
Asin 
Acos 
Atan 
Sinh 
Cosh 
Tanh 

Instances

Instances details
Bounded Builtin Source # 
Instance details

Defined in HMath.Expression

Enum Builtin Source # 
Instance details

Defined in HMath.Expression

Show Builtin Source # 
Instance details

Defined in HMath.Expression

Eq Builtin Source # 
Instance details

Defined in HMath.Expression

Methods

(==) :: Builtin -> Builtin -> Bool #

(/=) :: Builtin -> Builtin -> Bool #

Ord Builtin Source # 
Instance details

Defined in HMath.Expression

Registry

data Registry Source #

Immutable safe builtin-name registry, initialized with emptyRegistry or defaultRegistry and extended with registerFunction.

Instances

Instances details
Show Registry Source # 
Instance details

Defined in HMath.Expression

Eq Registry Source # 
Instance details

Defined in HMath.Expression

defaultRegistry

defaultRegistry :: Registry Source #

Registry of supported safe scalar builtins (trigonometric/hyperbolic functions, explogsqrt, abssignum, rounding and minmax). Evaluation dispatches known Builtin values, never arbitrary source code.

emptyRegistry

emptyRegistry :: Registry Source #

Construct a registry containing no builtins; callers may add permitted names with registerFunction.

registerFunction

registerFunction :: String -> Builtin -> Registry -> Either ExprError Registry Source #

Given valid identifier name,Builtin selector,then registry, insert or replace an alias. Reject invalid names (including length>1024) or more than 256 distinct entries with structured ExprError.

allowedFunctions

allowedFunctions :: Registry -> [String] Source #

Sorted function and alias names accepted by a registry; no evaluation occurs.

typeCheckExpression

typeCheckExpression :: Limits -> Precision -> Registry -> Bindings -> Expr -> Either ExprError Precision Source #

Static scalarprecisionname/arity checking. Domains and integer-valued variable exponents are checked during evaluation, since they depend on values. Let-bound names are typed lexically without evaluating their initializers.

evaluateExpression

evaluateExpression :: Limits -> Precision -> Registry -> Bindings -> Expr -> Either ExprError Value Source #

Direct left-to-right evaluation. Unused let bindings are still evaluated; unreferenced external bindings are not inspected or copied.

evaluateText

evaluateText :: Limits -> Precision -> Registry -> Bindings -> String -> Either ExprError Value Source #

Given limits,precision,registry,bindings,then source text, parse and evaluate under the checked expression budgets. Return exact Rational or Float64 Value according to mode; syntaxnamedomain/resource failures return positioned ExprError.

Compiled

data Compiled Source #

Opaque validated expression DAG with common-subexpression sharing and source locations. Use compileExpression/evaluateCompiled.

Instances

Instances details
Show Compiled Source # 
Instance details

Defined in HMath.Expression

Eq Compiled Source # 
Instance details

Defined in HMath.Expression

compileExpression

compileExpression :: Limits -> Expr -> Either ExprError Compiled Source #

Compile to a hash-consed DAG. Strict lets are retained, including unused bindings. CSE changes work requirements, but preserves numeric/domain errors.

compiledNodeCount

compiledNodeCount :: Compiled -> Int Source #

Number of unique DAG instructions after common-subexpression sharing.

evaluateCompiled

evaluateCompiled :: Limits -> Precision -> Registry -> Bindings -> Compiled -> Either ExprError Value Source #

DAG evaluation memoizes successful nodes only; errors keep the first left-to-right source location. Registry checks occur even on compiled calls.

optimizeExpression

optimizeExpression :: Limits -> Precision -> Expr -> Either ExprError Expr Source #

Conservative constant folding of literal arithmetic only. Calls, division by zero and failing/oversized operations remain intact, preserving failures and registry restrictions. Floating mode does not reassociate operations.

ExpressionCache

data ExpressionCache Source #

Immutable FIFO cache. Its entries contain syntax only, never environments or results. Keys include exact source; eviction occurs at the caller's limit.

Instances

Instances details
Show ExpressionCache Source # 
Instance details

Defined in HMath.Expression

Eq ExpressionCache Source # 
Instance details

Defined in HMath.Expression

emptyExpressionCache

emptyExpressionCache :: ExpressionCache Source #

Construct an empty immutable compiled-expression cache. cachedExpression returns an updated cache explicitly.

cachedExpression

cachedExpression :: Limits -> String -> ExpressionCache -> Either ExprError (Compiled, ExpressionCache) Source #

Given limits,source text,then cache, return (compiled expression,updated cache), reusing a matching entry when permitted. Enforce entry and aggregate source/instruction budgets; parsecompileresource failures return ExprError.

cacheSize

cacheSize :: ExpressionCache -> Int Source #

Return number of retained compiled-source entries; does not compile or evaluate anything.

formatScientific

formatScientific :: Int -> Value -> Either ExprError String Source #

Scientific notation with 0..30 fractional digits, for finite values.

formatRadix

formatRadix :: Int -> Value -> Either ExprError String Source #

Integer radix 2..36; fractional values and nonfinite Double are rejected.

serializeExpression

serializeExpression :: Limits -> Expr -> Either ExprError String Source #

Given limits then Expr, validate its structure and produce versioned safe textual encoding, retaining expression structure. Exceeded character/structure limits return ExprError.

deserializeExpression

deserializeExpression :: Limits -> String -> Either ExprError Expr Source #

Given limits then encoded text, parse the supported serialization and revalidate its structure. Malformed/unsupported nodes or exceeded limits return ExprError; no host code evaluation is used.

expressionHash

expressionHash :: Limits -> Expr -> Either ExprError Word64 Source #

Stable FNV-1a over canonical serialization Unicode code points (not UTF-8 bytes). This is an identity hash, never a cryptographic authenticator.