eval

package
v1.3.1 Latest Latest
Warning

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

Go to latest
Published: Mar 9, 2026 License: MIT Imports: 7 Imported by: 1

Documentation

Overview

Package eval provides the FHIRPath expression evaluator.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Add

func Add(left, right types.Value) (types.Value, error)

Add performs addition on two values.

func And

func And(left, right types.Collection) types.Collection

And performs logical AND with three-valued logic.

func Compare

func Compare(left, right types.Value) (int, error)

Compare compares two values and returns -1, 0, or 1.

func Concatenate

func Concatenate(left, right types.Collection) types.Collection

Concatenate performs string concatenation (& operator). Unlike +, & treats empty as empty string.

func Contains

func Contains(left, right types.Collection) types.Collection

Contains checks if left collection contains right.

func Divide

func Divide(left, right types.Value) (types.Value, error)

Divide performs division on two values.

func Equal

func Equal(left, right types.Collection) types.Collection

Equal returns true if left = right.

func Equivalent

func Equivalent(left, right types.Collection) types.Collection

Equivalent returns true if left ~ right.

func GreaterOrEqual

func GreaterOrEqual(left, right types.Value) (types.Collection, error)

GreaterOrEqual returns true if left >= right.

func GreaterThan

func GreaterThan(left, right types.Value) (types.Collection, error)

GreaterThan returns true if left > right.

func Implies

func Implies(left, right types.Collection) types.Collection

Implies performs logical implication.

func In

func In(left, right types.Collection) types.Collection

In checks if left is in right collection.

func IntegerDivide

func IntegerDivide(left, right types.Value) (types.Value, error)

IntegerDivide performs integer division (div operator).

func IsDomainResource

func IsDomainResource(resourceType string) bool

IsDomainResource returns true if the given resource type inherits from DomainResource. Bundle, Binary, and Parameters inherit directly from Resource, not DomainResource.

func IsSubtypeOf

func IsSubtypeOf(actualType, baseType string) bool

IsSubtypeOf checks if actualType is a subtype of (or equal to) baseType. This handles the FHIR type hierarchy:

Resource
  └── DomainResource
        ├── Patient
        ├── Observation
        └── ... (most resources)
  └── Bundle, Binary, Parameters (directly inherit from Resource)

func IsSubtypeOfWithModel added in v1.2.0

func IsSubtypeOfWithModel(actualType, baseType string, model Model) bool

IsSubtypeOfWithModel checks subtype relationship using the model if available, falling back to the built-in heuristic when model is nil. When a model is present, it is authoritative — the heuristic fallback is skipped.

func LessOrEqual

func LessOrEqual(left, right types.Value) (types.Collection, error)

LessOrEqual returns true if left <= right.

func LessThan

func LessThan(left, right types.Value) (types.Collection, error)

LessThan returns true if left < right.

func Modulo

func Modulo(left, right types.Value) (types.Value, error)

Modulo performs modulo operation (mod operator).

func Multiply

func Multiply(left, right types.Value) (types.Value, error)

Multiply performs multiplication on two values.

func Negate

func Negate(value types.Value) (types.Value, error)

Negate negates a numeric value.

func Not

func Not(value types.Collection) types.Collection

Not performs logical NOT.

func NotEqual

func NotEqual(left, right types.Collection) types.Collection

NotEqual returns true if left != right.

func NotEquivalent

func NotEquivalent(left, right types.Collection) types.Collection

NotEquivalent returns true if left !~ right.

func Or

func Or(left, right types.Collection) types.Collection

Or performs logical OR with three-valued logic.

func Subtract

func Subtract(left, right types.Value) (types.Value, error)

Subtract performs subtraction on two values.

func TypeMatches

func TypeMatches(actualType, typeName string) bool

TypeMatches checks if actualType matches the requested typeName. Handles case-insensitive comparison and FHIR type aliases. This function is exported for use by the is() function implementation.

func TypeMatchesWithModel added in v1.2.0

func TypeMatchesWithModel(actualType, typeName string, model Model) bool

TypeMatchesWithModel checks type matching using the model if available, falling back to the built-in TypeMatches when model is nil. When a model is present, it is authoritative for type hierarchy — only spec-stable FHIRPath type mappings are applied, version-specific heuristics are skipped.

func Union

func Union(left, right types.Collection) types.Collection

Union returns the union of two collections.

func Xor

func Xor(left, right types.Collection) types.Collection

Xor performs logical XOR.

Types

type Context

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

Context holds the evaluation state.

func NewContext

func NewContext(resource []byte) *Context

NewContext creates a new evaluation context. Automatically sets %resource, %rootResource, and %context to the root resource for FHIR constraint evaluation. Per FHIRPath spec:

  • %resource: the root resource being evaluated
  • %rootResource: the root resource in the evaluation context (differs from %resource for contained/Bundle resources)
  • %context: the original node passed to the evaluation engine (same as %resource for top-level evaluation)

func (*Context) CheckCancellation

func (c *Context) CheckCancellation() error

CheckCancellation checks if the context has been canceled.

func (*Context) CheckCollectionSize

func (c *Context) CheckCollectionSize(col types.Collection) error

CheckCollectionSize validates that a collection doesn't exceed the maximum size. Returns an error if the collection is too large.

func (*Context) Context

func (c *Context) Context() context.Context

Context returns the Go context.

func (*Context) EnforceCollectionLimit

func (c *Context) EnforceCollectionLimit(col types.Collection) (types.Collection, bool)

EnforceCollectionLimit truncates a collection if it exceeds the maximum size. Returns the (possibly truncated) collection and whether truncation occurred.

func (*Context) GetLimit

func (c *Context) GetLimit(name string) int

GetLimit gets a limit value.

func (*Context) GetModel added in v1.2.0

func (c *Context) GetModel() Model

GetModel returns the FHIR model, or nil if not set.

func (*Context) GetProfileValidator

func (c *Context) GetProfileValidator() ProfileValidator

GetProfileValidator returns the profile validator.

func (*Context) GetResolver

func (c *Context) GetResolver() Resolver

GetResolver returns the reference resolver.

func (*Context) GetTerminologyService

func (c *Context) GetTerminologyService() TerminologyService

GetTerminologyService returns the terminology service.

func (*Context) GetVariable

func (c *Context) GetVariable(name string) (types.Collection, bool)

GetVariable gets an external variable.

func (*Context) Path added in v1.2.0

func (c *Context) Path() string

Path returns the current FHIR navigation path.

func (*Context) Root

func (c *Context) Root() types.Collection

Root returns the root collection.

func (*Context) SetContext

func (c *Context) SetContext(ctx context.Context)

SetContext sets the Go context for cancellation.

func (*Context) SetLimit

func (c *Context) SetLimit(name string, value int)

SetLimit sets a limit value (e.g., maxDepth, maxCollectionSize).

func (*Context) SetModel added in v1.2.0

func (c *Context) SetModel(m Model)

SetModel sets the FHIR model for version-specific type resolution.

func (*Context) SetPath added in v1.2.0

func (c *Context) SetPath(path string)

SetPath sets the current FHIR navigation path.

func (*Context) SetProfileValidator

func (c *Context) SetProfileValidator(pv ProfileValidator)

SetProfileValidator sets the profile validator for conformsTo validation.

func (*Context) SetResolver

func (c *Context) SetResolver(r Resolver)

SetResolver sets the reference resolver.

func (*Context) SetTerminologyService

func (c *Context) SetTerminologyService(ts TerminologyService)

SetTerminologyService sets the terminology service for memberOf validation.

func (*Context) SetVariable

func (c *Context) SetVariable(name string, value types.Collection)

SetVariable sets an external variable.

func (*Context) This

func (c *Context) This() types.Collection

This returns the current $this value.

func (*Context) WithIndex

func (c *Context) WithIndex(index int) *Context

WithIndex returns a new context with the given $index value.

func (*Context) WithThis

func (c *Context) WithThis(this types.Collection) *Context

WithThis returns a new context with the given $this value.

type ErrorType

type ErrorType int

ErrorType represents the category of evaluation error.

const (
	// ErrParse indicates a parsing error.
	ErrParse ErrorType = iota
	// ErrType indicates a type mismatch error.
	ErrType
	// ErrSingletonExpected indicates multiple values where one was expected.
	ErrSingletonExpected
	// ErrFunctionNotFound indicates an unknown function.
	ErrFunctionNotFound
	// ErrInvalidArguments indicates invalid function arguments.
	ErrInvalidArguments
	// ErrDivisionByZero indicates division by zero.
	ErrDivisionByZero
	// ErrInvalidPath indicates an invalid path expression.
	ErrInvalidPath
	// ErrTimeout indicates evaluation timeout.
	ErrTimeout
	// ErrInvalidOperation indicates an unsupported operation.
	ErrInvalidOperation
	// ErrInvalidExpression indicates an invalid expression.
	ErrInvalidExpression
)

func (ErrorType) String

func (t ErrorType) String() string

String returns the string representation of the error type.

type EvalError

type EvalError struct {
	Type       ErrorType
	Message    string
	Path       string   // Expression path where error occurred
	Position   Position // Position in source expression
	Underlying error    // Original error if wrapping
}

EvalError represents an error that occurred during evaluation.

func DivisionByZeroError

func DivisionByZeroError() *EvalError

DivisionByZeroError creates a division by zero error.

func FunctionNotFoundError

func FunctionNotFoundError(name string) *EvalError

FunctionNotFoundError creates a function not found error.

func InvalidArgumentsError

func InvalidArgumentsError(funcName string, expected, actual int) *EvalError

InvalidArgumentsError creates an invalid arguments error.

func InvalidOperationError

func InvalidOperationError(op, leftType, rightType string) *EvalError

InvalidOperationError creates an invalid operation error.

func InvalidPathError

func InvalidPathError(path string) *EvalError

InvalidPathError creates an invalid path error.

func NewEvalError

func NewEvalError(errType ErrorType, format string, args ...interface{}) *EvalError

NewEvalError creates a new evaluation error. Supports format strings like fmt.Sprintf.

func ParseError

func ParseError(message string) *EvalError

ParseError creates a parsing error.

func SingletonError

func SingletonError(count int) *EvalError

SingletonError creates a singleton expected error.

func TypeError

func TypeError(expected, actual, operation string) *EvalError

TypeError creates a type mismatch error.

func (*EvalError) Error

func (e *EvalError) Error() string

Error implements the error interface.

func (*EvalError) Unwrap

func (e *EvalError) Unwrap() error

Unwrap returns the underlying error.

func (*EvalError) WithPath

func (e *EvalError) WithPath(path string) *EvalError

WithPath adds path information to the error.

func (*EvalError) WithPosition

func (e *EvalError) WithPosition(line, column int) *EvalError

WithPosition adds position information to the error.

func (*EvalError) WithUnderlying

func (e *EvalError) WithUnderlying(err error) *EvalError

WithUnderlying adds an underlying error.

type Evaluator

type Evaluator struct {
	grammar.BasefhirpathVisitor
	// contains filtered or unexported fields
}

Evaluator evaluates FHIRPath expressions using the visitor pattern.

func NewEvaluator

func NewEvaluator(ctx *Context, funcs FuncRegistry) *Evaluator

NewEvaluator creates a new evaluator with the given context and function registry.

func (*Evaluator) Evaluate

func (e *Evaluator) Evaluate(tree antlr.ParseTree) (types.Collection, error)

Evaluate evaluates a parse tree and returns the result.

func (*Evaluator) Visit

func (e *Evaluator) Visit(tree antlr.ParseTree) interface{}

Visit dispatches to the appropriate visitor method.

func (*Evaluator) VisitAdditiveExpression

func (e *Evaluator) VisitAdditiveExpression(ctx *grammar.AdditiveExpressionContext) interface{}

VisitAdditiveExpression visits expr + expr, expr - expr, expr & expr.

func (*Evaluator) VisitAndExpression

func (e *Evaluator) VisitAndExpression(ctx *grammar.AndExpressionContext) interface{}

VisitAndExpression visits expr and expr.

func (*Evaluator) VisitBooleanLiteral

func (e *Evaluator) VisitBooleanLiteral(ctx *grammar.BooleanLiteralContext) interface{}

VisitBooleanLiteral visits a boolean literal.

func (*Evaluator) VisitDateLiteral

func (e *Evaluator) VisitDateLiteral(ctx *grammar.DateLiteralContext) interface{}

VisitDateLiteral visits a date literal.

func (*Evaluator) VisitDateTimeLiteral

func (e *Evaluator) VisitDateTimeLiteral(ctx *grammar.DateTimeLiteralContext) interface{}

VisitDateTimeLiteral visits a datetime literal.

func (*Evaluator) VisitEntireExpression

func (e *Evaluator) VisitEntireExpression(ctx *grammar.EntireExpressionContext) interface{}

VisitEntireExpression visits the root expression.

func (*Evaluator) VisitEqualityExpression

func (e *Evaluator) VisitEqualityExpression(ctx *grammar.EqualityExpressionContext) interface{}

VisitEqualityExpression visits equality expressions.

func (*Evaluator) VisitExternalConstant

func (e *Evaluator) VisitExternalConstant(ctx *grammar.ExternalConstantContext) interface{}

VisitExternalConstant visits an external constant (%name).

func (*Evaluator) VisitExternalConstantTerm

func (e *Evaluator) VisitExternalConstantTerm(ctx *grammar.ExternalConstantTermContext) interface{}

VisitExternalConstantTerm visits an external constant.

func (*Evaluator) VisitFunctionInvocation

func (e *Evaluator) VisitFunctionInvocation(ctx *grammar.FunctionInvocationContext) interface{}

VisitFunctionInvocation visits a function call.

func (*Evaluator) VisitImpliesExpression

func (e *Evaluator) VisitImpliesExpression(ctx *grammar.ImpliesExpressionContext) interface{}

VisitImpliesExpression visits expr implies expr.

func (*Evaluator) VisitIndexInvocation

func (e *Evaluator) VisitIndexInvocation(ctx *grammar.IndexInvocationContext) interface{}

VisitIndexInvocation visits $index.

func (*Evaluator) VisitIndexerExpression

func (e *Evaluator) VisitIndexerExpression(ctx *grammar.IndexerExpressionContext) interface{}

VisitIndexerExpression visits expr[index].

func (*Evaluator) VisitInequalityExpression

func (e *Evaluator) VisitInequalityExpression(ctx *grammar.InequalityExpressionContext) interface{}

VisitInequalityExpression visits comparison expressions.

func (*Evaluator) VisitInvocationExpression

func (e *Evaluator) VisitInvocationExpression(ctx *grammar.InvocationExpressionContext) interface{}

VisitInvocationExpression visits expr.invocation.

func (*Evaluator) VisitInvocationTerm

func (e *Evaluator) VisitInvocationTerm(ctx *grammar.InvocationTermContext) interface{}

VisitInvocationTerm visits an invocation term.

func (*Evaluator) VisitLiteralTerm

func (e *Evaluator) VisitLiteralTerm(ctx *grammar.LiteralTermContext) interface{}

VisitLiteralTerm visits a literal term.

func (*Evaluator) VisitMemberInvocation

func (e *Evaluator) VisitMemberInvocation(ctx *grammar.MemberInvocationContext) interface{}

VisitMemberInvocation visits a member access.

func (*Evaluator) VisitMembershipExpression

func (e *Evaluator) VisitMembershipExpression(ctx *grammar.MembershipExpressionContext) interface{}

VisitMembershipExpression visits 'in' and 'contains' expressions.

func (*Evaluator) VisitMultiplicativeExpression

func (e *Evaluator) VisitMultiplicativeExpression(ctx *grammar.MultiplicativeExpressionContext) interface{}

VisitMultiplicativeExpression visits expr * expr, expr / expr, etc.

func (*Evaluator) VisitNullLiteral

func (e *Evaluator) VisitNullLiteral(ctx *grammar.NullLiteralContext) interface{}

VisitNullLiteral visits a null literal {}.

func (*Evaluator) VisitNumberLiteral

func (e *Evaluator) VisitNumberLiteral(ctx *grammar.NumberLiteralContext) interface{}

VisitNumberLiteral visits a number literal.

func (*Evaluator) VisitOrExpression

func (e *Evaluator) VisitOrExpression(ctx *grammar.OrExpressionContext) interface{}

VisitOrExpression visits expr or expr, expr xor expr.

func (*Evaluator) VisitParenthesizedTerm

func (e *Evaluator) VisitParenthesizedTerm(ctx *grammar.ParenthesizedTermContext) interface{}

VisitParenthesizedTerm visits a parenthesized expression.

func (*Evaluator) VisitPolarityExpression

func (e *Evaluator) VisitPolarityExpression(ctx *grammar.PolarityExpressionContext) interface{}

VisitPolarityExpression visits +expr or -expr.

func (*Evaluator) VisitQuantityLiteral

func (e *Evaluator) VisitQuantityLiteral(ctx *grammar.QuantityLiteralContext) interface{}

VisitQuantityLiteral visits a quantity literal.

func (*Evaluator) VisitStringLiteral

func (e *Evaluator) VisitStringLiteral(ctx *grammar.StringLiteralContext) interface{}

VisitStringLiteral visits a string literal.

func (*Evaluator) VisitTermExpression

func (e *Evaluator) VisitTermExpression(ctx *grammar.TermExpressionContext) interface{}

VisitTermExpression visits a term expression.

func (*Evaluator) VisitThisInvocation

func (e *Evaluator) VisitThisInvocation(ctx *grammar.ThisInvocationContext) interface{}

VisitThisInvocation visits $this.

func (*Evaluator) VisitTimeLiteral

func (e *Evaluator) VisitTimeLiteral(ctx *grammar.TimeLiteralContext) interface{}

VisitTimeLiteral visits a time literal.

func (*Evaluator) VisitTotalInvocation

func (e *Evaluator) VisitTotalInvocation(ctx *grammar.TotalInvocationContext) interface{}

VisitTotalInvocation visits $total.

func (*Evaluator) VisitTypeExpression

func (e *Evaluator) VisitTypeExpression(ctx *grammar.TypeExpressionContext) interface{}

VisitTypeExpression visits 'is' and 'as' expressions.

func (*Evaluator) VisitUnionExpression

func (e *Evaluator) VisitUnionExpression(ctx *grammar.UnionExpressionContext) interface{}

VisitUnionExpression visits expr | expr.

type FuncDef

type FuncDef struct {
	Name     string
	MinArgs  int
	MaxArgs  int
	Fn       FuncImpl
	TypeArgs []int // Indices of arguments that are type specifiers (extracted as strings, not evaluated as expressions)
}

FuncDef defines a FHIRPath function.

type FuncImpl

type FuncImpl func(ctx *Context, input types.Collection, args []interface{}) (types.Collection, error)

FuncImpl is the signature for function implementations.

type FuncRegistry

type FuncRegistry interface {
	Get(name string) (FuncDef, bool)
}

FuncRegistry is an interface for function lookup.

type Model added in v1.2.0

type Model interface {
	ChoiceTypes(path string) []string
	TypeOf(path string) string
	ReferenceTargets(path string) []string
	ParentType(typeName string) string
	IsSubtype(child, parent string) bool
	ResolvePath(path string) string
	IsResource(typeName string) bool
}

Model provides FHIR version-specific type and path metadata. When set on a Context, the evaluator uses it for precise polymorphic field resolution, type hierarchy checking, and path-based type inference. When nil, the evaluator falls back to built-in heuristics.

type Position

type Position struct {
	Line   int
	Column int
}

Position represents a location in the source expression.

type ProfileValidator

type ProfileValidator interface {
	// ConformsTo checks if a resource conforms to the specified profile.
	// Returns true if the resource conforms, false otherwise.
	ConformsTo(ctx context.Context, resource []byte, profileURL string) (bool, error)
}

ProfileValidator handles profile conformance validation.

type Resolver

type Resolver interface {
	Resolve(ctx context.Context, reference string) ([]byte, error)
}

Resolver handles FHIR reference resolution.

type TerminologyService

type TerminologyService interface {
	// MemberOf checks if a code/Coding/CodeableConcept is in the specified ValueSet.
	// Returns true if the code is in the ValueSet, false otherwise.
	// Returns error if the ValueSet cannot be resolved or validation fails.
	MemberOf(ctx context.Context, code interface{}, valueSetURL string) (bool, error)
}

TerminologyService handles terminology operations like ValueSet membership.

Jump to

Keyboard shortcuts

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