Expand description
§FHIRPath Expression Engine
This crate provides a complete implementation of the FHIRPath 3.0.0 specification for evaluating FHIRPath expressions against FHIR resources. FHIRPath is a path-based navigation and extraction language designed specifically for FHIR resources, enabling powerful queries and data manipulation operations.
§Overview
FHIRPath is a declarative language that allows you to:
- Navigate FHIR resources using path expressions (e.g.,
Patient.name.family) - Filter collections with boolean predicates (e.g.,
telecom.where(system = 'email')) - Transform data using built-in functions (e.g.,
name.given.first()) - Perform calculations with mathematical operations (e.g.,
birthDate.today() - birthDate) - Access extensions in FHIR resources (e.g.,
Patient.extension('http://example.org/birthPlace')) - Work with types using type checking and conversion (e.g.,
value.is(Quantity))
§Key Features
§Core Functionality
- Parser: Complete FHIRPath syntax support including literals, operators, and function calls
- Evaluator: Fast evaluation engine with proper type handling and error reporting
- Type System: Support for both FHIR and System namespaces with automatic type inference
- Extension Support: Native handling of FHIR extensions and choice elements
§Language Support
- Collections: Comprehensive collection operations (where, select, all, exists, etc.)
- Mathematics: Arithmetic operations with proper decimal precision handling
- String Operations: Text manipulation and pattern matching functions
- Date/Time: Temporal operations with timezone and precision support
- Type Operations: Dynamic type checking with
is,as, andofTypeoperators - Variables: Support for external variables and built-in constants
§FHIR Integration
- Multi-version Support: Works with FHIR R4, R4B, R5, and R6 via feature flags
- Resource Navigation: Smart navigation of FHIR choice elements (e.g.,
value[x]) - Extension Access: Built-in
extension()function for FHIR extension handling - Type Hierarchy: Understanding of FHIR resource and data type relationships
§Architecture
The crate is organized into several key components:
- Public API (
lib.rs): Simple interface withevaluate_expressionfunction - Parser (
parser.rs): Converts FHIRPath text into an Abstract Syntax Tree (AST) - Evaluator (
evaluator.rs): Executes the AST against FHIR resources - Function Modules: Specialized implementations for FHIRPath functions
- Type System: FHIR type hierarchy and namespace management
- Support Types: Integration with the
fhirpath_supportcrate for results
§Usage Examples
§Basic Navigation
use helios_fhirpath::{evaluate_expression, EvaluationContext};
// Navigate to family name
let result = evaluate_expression("Patient.name.family", &context)?;
// Result: Collection containing family names
// Get first given name
let result = evaluate_expression("Patient.name.given.first()", &context)?;
// Result: First given name as string
// Check if patient is active
let result = evaluate_expression("Patient.active", &context)?;
// Result: Boolean value§Collection Operations
// Filter email addresses
let result = evaluate_expression(
"Patient.telecom.where(system = 'email')",
&context
)?;
// Check if any email exists
let result = evaluate_expression(
"Patient.telecom.where(system = 'email').exists()",
&context
)?;
// Count phone numbers
let result = evaluate_expression(
"Patient.telecom.where(system = 'phone').count()",
&context
)?;§Type Operations
// Check if observation value is a Quantity
let result = evaluate_expression(
"Observation.value.is(Quantity)",
&context
)?;
// Cast value to Quantity and get unit
let result = evaluate_expression(
"Observation.value.as(Quantity).unit",
&context
)?;
// Get type information
let result = evaluate_expression(
"Observation.value.type().name",
&context
)?;§Extension Access
// Create context with patient data
let mut context = EvaluationContext::new(vec![]);
// Access FHIR extension by URL
let result = evaluate_expression(
"Patient.extension('http://hl7.org/fhir/StructureDefinition/patient-birthPlace')",
&context
)?;
// Extension with variable
context.set_variable_result("birthPlaceUrl", EvaluationResult::string(
"http://hl7.org/fhir/StructureDefinition/patient-birthPlace".to_string()
));
let result = evaluate_expression(
"Patient.extension(%birthPlaceUrl).value",
&context
)?;§Mathematical Operations
// Basic arithmetic
let result = evaluate_expression("1 + 2 * 3", &context)?; // Result: 7
// Decimal operations
let result = evaluate_expression("10.5 / 2.1", &context)?;
// Age calculation (if Patient.birthDate exists)
let result = evaluate_expression(
"today() - Patient.birthDate",
&context
)?;§Variables and Constants
let mut context = EvaluationContext::new(vec![]);
// Set custom variables
context.set_variable_result("threshold", EvaluationResult::decimal(rust_decimal::Decimal::new(5, 0)));
context.set_variable_result("unitSystem", EvaluationResult::string("metric".to_string()));
// Use variables in expressions
let result = evaluate_expression("value > %threshold", &context)?;
// Built-in constants are automatically available
let result = evaluate_expression("system = %ucum", &context)?; // %ucum = 'http://unitsofmeasure.org'§Error Handling
The evaluate_expression function returns detailed error messages for both parsing and evaluation failures:
// Syntax error
match evaluate_expression("Patient.name.", &context) {
Err(err) => println!("Parse error: {}", err),
Ok(_) => {}
}
// Runtime error
match evaluate_expression("Patient.nonExistentField", &context) {
Err(err) => println!("Evaluation error: {}", err),
Ok(_) => {}
}§Performance Considerations
- Parsing: Expression parsing is relatively expensive; consider caching parsed expressions for repeated use
- Evaluation: Evaluation performance depends on resource size and expression complexity
- Memory: Large collections in FHIR resources may consume significant memory during evaluation
§Specification Compliance
This implementation aims for full compliance with FHIRPath 3.0.0. Current implementation status includes:
- ✅ Core Language: Literals, operators, path navigation
- ✅ Collection Functions: where, select, first, last, tail, etc.
- ✅ Boolean Logic: and, or, not, implies, xor
- ✅ Type Operations: is, as, ofType with FHIR type system
- ✅ String Functions: matches, contains, startsWith, etc.
- ✅ Math Functions: abs, ceiling, floor, round, sqrt, etc.
- ✅ Date Functions: today, now, date/time arithmetic
- ✅ Extension Functions: FHIR extension access
- ✅ Variables: External variables and built-in constants
- 🟡 Advanced Features: Some STU (Standard for Trial Use) functions
See the FHIRPath README for detailed implementation status.
§FHIR Version Support
This crate supports multiple FHIR versions through Cargo feature flags:
[dependencies]
fhirpath = { version = "0.1", features = ["R4"] } # FHIR R4 support
fhirpath = { version = "0.1", features = ["R5"] } # FHIR R5 support
fhirpath = { version = "0.1", features = ["R4", "R5"] } # Multiple versionsAvailable features:
R4: FHIR 4.0.1 (normative)R4B: FHIR 4.3.0 (ballot)R5: FHIR 5.0.0 (ballot)R6: FHIR 6.0.0 (draft)
Re-exports§
pub use evaluator::EvaluationContext;
Modules§
- cli
- FHIRPath CLI Tool
- debug_
trace - Debug trace support for step-by-step FHIRPath evaluation tracing.
- error
- Error types for FHIRPath CLI and server operations
- evaluator
- FHIRPath Expression Evaluator
- handlers
- Request handlers for the FHIRPath server
- models
- Data models for FHIRPath server request and response handling
- parse_
debug - Parse debug tree generation for FHIRPath expressions
- parser
- FHIRPath Expression Parser
- server
- FHIRPath Server Implementation
- type_
inference - Type inference for FHIRPath expressions
- ucum
- UCUM integration module for FHIRPath
Enums§
Functions§
- evaluate_
expression - Evaluates a FHIRPath expression against a given context.
- parse_
expression - Parse a FHIRPath expression source string into a typed
parser::ExpressionAST.