pub enum Reference {
One(Arc<str>),
Two(Arc<str>, Arc<str>),
Three(Arc<str>, Arc<str>, Arc<str>),
Four(Arc<str>, Arc<str>, Arc<str>, Arc<str>),
}Expand description
Reference to an identifier or chained scope segments.
Used by expression parsing and evaluation to locate values in the context and to map references to workflow/workspace paths.
PartialEq<String> only matches Reference::One against an identical
string; multi-part references never compare equal to String.
Variants§
One(Arc<str>)
A single identifier reference
Two(Arc<str>, Arc<str>)
A two-part chained property reference
Three(Arc<str>, Arc<str>, Arc<str>)
A three-part chained property reference
Four(Arc<str>, Arc<str>, Arc<str>, Arc<str>)
A four-part chained property reference
Implementations§
Source§impl Reference
impl Reference
Sourcepub fn new(identifier: Arc<str>) -> Arc<Self>
pub fn new(identifier: Arc<str>) -> Arc<Self>
§Creates a new single-part reference from an identifier.
§title: New
Creates a new single-part reference from an identifier.
This function constructs a Reference::One variant wrapped in an Arc, providing
a simple way to create basic references for single identifiers. This is the most
common way to create references for individual workflow nodes, cells, or variables.
§Arguments
identifier- AnArc<str>containing the identifier name. The identifier must be a valid AIMX identifier (starting with a letter or underscore, followed by letters, digits, or underscores).
§Returns
Returns an Arc<Reference> containing a Reference::One variant with the
provided identifier. The reference is wrapped in an Arc for efficient sharing
and cloning throughout the system.
§Errors
This function does not return errors. However, invalid identifiers may cause issues when the reference is used in parsing or evaluation contexts.
§Behavior
Internally, new() performs the following operations:
- Reference Construction: Creates a
Reference::Onevariant with the provided identifier - Arc Wrapping: Wraps the reference in an
Arcfor shared ownership - Memory Allocation: Allocates the reference on the heap for efficient sharing
§Usage
The new() function is commonly used to create simple references for various purposes:
use aimx::Reference;
use std::sync::Arc;
// Create a simple reference to a workflow node
let node_reference = Reference::new(Arc::from("my_workflow"));
// Create a reference to a cell identifier
let cell_reference = Reference::new(Arc::from("cell_name"));
// Create a reference for evaluation context
let context_reference = Reference::new(Arc::from("variable_name"));§See Also
Reference::parse()- Parse complex reference chains from strings- [
Reference::child()] - Create multi-part references by appending to existing ones - [
Reference::normalize()] - Combine references within a scope Reference::identifier()- Extract the identifier from a reference
§Performance Considerations
- Efficient Cloning: Since the return value is wrapped in
Arc, cloning is very efficient - Memory Sharing: Multiple references to the same identifier share the same underlying data
- Minimal Allocation: Only allocates memory for the
Referencestruct itself - No Validation: Does not validate identifier syntax, leaving that to parsing contexts
§Identifier Validation
While new() accepts any Arc<str>, identifiers should follow AIMX naming conventions:
- Must start with a letter or underscore
- Can contain letters, digits, and underscores
- Should not be reserved words (like
_which is reserved for workspace root) - Common patterns include:
foo,bar,baz- General identifiers_local- Local or temporary referencescamelCase,snake_case- Variable namingUPPER_CASE- Constants or special values
Sourcepub fn workspace() -> Arc<Self>
pub fn workspace() -> Arc<Self>
§Returns the global singleton reference to the workspace root identifier (_).
§title: Workspace
Returns the global singleton reference to the workspace root identifier (_).
This function provides access to the shared workspace root reference, which serves as the foundation for navigating the entire AIMX workspace hierarchy. The workspace root acts as the entry point for tree traversal and workflow discovery operations.
§Returns
Returns an Arc<Reference> pointing to the workspace root identifier (_).
This reference is shared across all API instances and maintains thread-safe
access to the global workspace context using OnceCell for lazy initialization.
§Behavior
Internally, workspace() performs the following operations:
- Uses a static
OnceCell<Arc<Reference>>to ensure the reference is created only once - Creates a new single-part reference with the identifier
"_" - Returns a clone of the cached reference for thread-safe sharing
This implementation ensures that:
- The workspace root reference is consistent across the entire application
- Multiple calls to
workspace()return equivalent references - Thread-safe access is maintained through
ArcandOnceCell
§Usage Pattern
The workspace root reference is typically used as the starting point for workspace operations:
use aimx::{Aim, Reference};
use aimx::expressions::ExpressionLike;
// Get the workspace root reference
let workspace_root = Reference::workspace();
// Use it with API functions
let catalog = Aim::catalog(workspace_root).unwrap();
for node in catalog {
println!("Node: {}", node.to_formula());
}§Integration with API
The workspace root reference is used internally by several API functions for workspace-level operations. See the Aim API documentation for functions that operate on the workspace root.
§See Also
- [
Reference::child()] - Create child references for navigation Reference::new()- Create custom referencesAimAPI documentation - For workspace operations using this reference
Sourcepub fn inference() -> Arc<Self>
pub fn inference() -> Arc<Self>
§Returns the global singleton reference to the inference context identifier (inference).
§title: Inference
Returns the global singleton reference to the inference context identifier (inference).
This function provides access to the shared inference context reference, which serves as the foundation for accessing inference-related data and metadata within AIMX workflows. The inference context acts as a namespace for inference-specific variables, prompts, responses, and configuration data.
§Returns
Returns an Arc<Reference> pointing to the inference context identifier (inference).
This reference is shared across all API instances and maintains thread-safe
access to the global inference context using OnceCell for lazy initialization.
§Behavior
Internally, inference() performs the following operations:
- Uses a static
OnceCell<Arc<Reference>>to ensure the reference is created only once - Creates a new single-part reference with the identifier
"inference" - Returns a clone of the cached reference for thread-safe sharing
This implementation ensures that:
- The inference context reference is consistent across the entire application
- Multiple calls to
inference()return equivalent references - Thread-safe access is maintained through
ArcandOnceCell
§Usage Pattern
The inference context reference is typically used to access inference-specific data within workflows:
use aimx::Reference;
// Get the inference context reference
let inference_context = Reference::inference();
// Use it to resolve inference-related variables
// For example, in expression evaluation:
// $inference.prompt, $inference.response, $inference.model§Integration with API
The inference context reference is used internally by the AIMX engine to:
- Provide access to inference prompts and responses during workflow execution
- Store inference model configuration and metadata
- Enable expressions within workflows to reference inference state
- Support conditional logic based on inference results
§See Also
Reference::workspace()- Get the workspace root referenceReference::context()- Get the evaluation context referenceReference::new()- Create custom referencesContextLike::inference_call()- Execute inference within a workflow context
§Inference Context Variables
When used as a prefix in expressions, the inference context provides access to:
$inference.prompt- The generated prompt sent to the inference provider$inference.response- The response received from the inference provider$inference.model- The model identifier being used for inference$inference.status- The current status of the inference operation$inference.tool- Tool-specific inference data when using tool calls$inference.workflow- The workflow being executed during inference
These variables are automatically populated during inference operations and can be used in subsequent workflow rules for conditional logic, result processing, and workflow orchestration.
Sourcepub fn context() -> Arc<Self>
pub fn context() -> Arc<Self>
§Returns the global singleton reference to the evaluation context identifier (context).
§title: Context
Returns the global singleton reference to the evaluation context identifier (context).
This function provides access to the shared evaluation context reference, which serves as the foundation for managing workflow instance lifecycle and exclusive write access within AIMX workflows. The context acts as a registry for active workflow instances that are currently being modified.
§Returns
Returns an Arc<Reference> pointing to the evaluation context identifier (context).
This reference is shared across all API instances and maintains thread-safe
access to the global context using OnceCell for lazy initialization.
§Behavior
Internally, context() performs the following operations:
- Uses a static
OnceCell<Arc<Reference>>to ensure the reference is created only once - Creates a new single-part reference with the identifier
"context" - Returns a clone of the cached reference for thread-safe sharing
This implementation ensures that:
- The context reference is consistent across the entire application
- Multiple calls to
context()return equivalent references - Thread-safe access is maintained through
ArcandOnceCell
§Usage Pattern
The context reference is primarily used internally by the AIMX API for workflow instance management:
use aimx::Reference;
// Get the context reference (typically used internally)
let context_ref = Reference::context();
// Use it to manage workflow instances
// For example, in the acquire/release cycle:
// Aim::acquire(workflow_reference) -> handle
// ... perform modifications ...
// Aim::release(handle)§Integration with API
The context reference is used internally by several API functions for workflow instance management:
crate::api::Aim::acquire()- Registers a workflow instance for exclusive write accesscrate::api::Aim::release()- Deregisters a workflow instance and finalizes changescrate::values::Instance::locate()- Retrieves the context lock for a specific instance handle
When used as a workflow node, the context provides access to:
- Active workflow instance handles
- Instance lifecycle management
- MVCC (Multi-Version Concurrency Control) coordination
§Context Workflow Operations
The context workflow maintains a registry of active instances:
- Instance Registration: When
Aim::acquire()is called, a new entry is added to the context workflow with the instance handle as the identifier - Instance Management: The context tracks which workflows are currently being modified
- Instance Cleanup: When
Aim::release()is called, the instance entry is removed from the context workflow
§Thread Safety
The context reference and its underlying workflow are designed for concurrent access:
- Multiple threads can safely call
Reference::context() - The context workflow uses internal locking mechanisms for thread-safe instance management
- Instance handles provide isolated access to individual workflow modifications
§See Also
Reference::workspace()- Get the workspace root referenceReference::inference()- Get the inference context referenceReference::new()- Create custom referencescrate::api::Aim::acquire()- Acquire exclusive workflow accesscrate::api::Aim::release()- Release workflow accesscrate::values::Instance- Workflow instance management
§Error Handling
The context() function itself cannot fail as it only returns a cached reference. However, operations that use the context reference may fail:
- Instance acquisition may fail if a workflow is already in use
- Instance operations require valid handles obtained through
Aim::acquire() - Context workflow operations are subject to standard AIMX error handling
Sourcepub fn status() -> Arc<Self>
pub fn status() -> Arc<Self>
§Returns the global singleton reference to the task status identifier (status).
§title: Status
Returns the global singleton reference to the task status identifier (status).
This function provides access to the shared task status reference, which serves as a special context identifier for accessing task status information in agentic workflows. The status reference is used internally by the AIMX engine to manage task state and workflow progress tracking.
§Returns
Returns an Arc<Reference> pointing to the task status identifier (status).
This reference is shared across all API instances and maintains thread-safe
access to the global status context using OnceCell for lazy initialization.
§Behavior
Internally, status() performs the following operations:
- Uses a static
OnceCell<Arc<Reference>>to ensure the reference is created only once - Creates a new single-part reference with the identifier
"status" - Returns a clone of the cached reference for thread-safe sharing
This implementation ensures that:
- The status reference is consistent across the entire application
- Multiple calls to
status()return equivalent references - Thread-safe access is maintained through
ArcandOnceCell
§Usage Pattern
The status reference is typically used internally by the AIMX engine for task management operations:
use aimx::{Reference, expressions::ExpressionLike};
use std::sync::Arc;
// Get the status reference
let status_ref = Reference::status();
// Use it in expressions or context operations
let formula = status_ref.to_formula();
println!("Status reference formula: {}", formula);§Integration with Task System
The status reference is primarily used by the task management system for:
- Accessing task status information during workflow evaluation
- Providing context for task status operations in expressions
- Supporting task status tracking in agentic workflows
See the task function module for related task management functionality.
§See Also
Reference::workspace()- Workspace root referenceReference::inference()- Inference context referenceReference::context()- Evaluation context referencecrate::values::Value- Runtime value representation
Sourcepub fn tool() -> Arc<Self>
pub fn tool() -> Arc<Self>
§Returns the global singleton reference to the tool identifier (tool).
§title: Tool
Returns the global singleton reference to the tool identifier (tool).
This function provides access to the shared tool reference, which serves as a standard location within the AIMX workspace hierarchy for tool-related configurations and operations. The tool node acts as a registry for tool definitions, configurations, and metadata that can be referenced throughout the workflow system.
§Returns
Returns an Arc<Reference> pointing to the tool identifier (tool).
This reference is shared across all API instances and maintains thread-safe
access to the global tool context using OnceCell for lazy initialization.
§Behavior
Internally, tool() performs the following operations:
- Uses a static
OnceCell<Arc<Reference>>to ensure the reference is created only once - Creates a new single-part reference with the identifier
"tool" - Returns a clone of the cached reference for thread-safe sharing
This implementation ensures that:
- The tool reference is consistent across the entire application
- Multiple calls to
tool()return equivalent references - Thread-safe access is maintained through
ArcandOnceCell
§Usage Pattern
The tool reference is primarily used internally by the AIMX API during workspace initialization and for tool-related operations:
use aimx::Reference;
// Get the tool reference (typically used internally)
let tool_ref = Reference::tool();
// Use it to create or reference tool configurations
// For example, in workflow initialization:
// workflow.add_node(Arc::from("tool"), Node::default())?;§Integration with API
The tool reference is used internally by several API functions during workspace creation:
crate::aim::Workspace::create()- Creates a default tool node during workspace initializationcrate::values::Node- The tool node usesPattern::Evaluatefor standard evaluation workflows
When used as a workflow node, the tool provides a standardized location for:
- Tool Configurations: Store tool-specific settings and parameters
- Tool Metadata: Maintain information about available tools and their capabilities
- Tool References: Provide a consistent way to reference tools across workflows
- Tool State Management: Track tool usage and state across different workflow executions
§Default Tool Node
During workspace creation, the tool reference is automatically initialized with:
- Identifier:
"tool" - Pattern:
Pattern::Evaluate(standard evaluation workflow) - Inference: Default inference configuration with no specific model
This creates a foundation for tool-related operations that can be extended as needed by applications.
§Thread Safety
The tool reference and its underlying workflow are designed for concurrent access:
- Multiple threads can safely call
Reference::tool() - The tool workflow uses internal locking mechanisms for thread-safe operations
- Tool configurations can be safely accessed and modified through the standard AIMX workflow APIs
§See Also
Reference::workspace()- Get the workspace root referenceReference::context()- Get the evaluation context referenceReference::inference()- Get the inference context referenceReference::new()- Create custom referencescrate::values::Node- Workflow node managementcrate::inference::Pattern- Inference pattern definitions
§Error Handling
The tool() function itself cannot fail as it only returns a cached reference. However, operations that use the tool reference may fail:
- Tool node operations require the workspace to be properly initialized
- Tool workflow operations are subject to standard AIMX error handling
- Tool-specific errors will be reported through the standard workflow evaluation system
Sourcepub fn workflow() -> Arc<Self>
pub fn workflow() -> Arc<Self>
§Returns the global singleton reference to the workflow identifier (workflow).
§title: Workflow
Returns the global singleton reference to the workflow identifier (workflow).
This reference is used internally by the AIMX system to identify and access workflow-related functionality. It is part of the foundational system nodes that are automatically created when initializing a new workspace, alongside context, inference, status, and tool references. The workflow reference provides access to the core workflow management operations within the workspace.
§Returns
Returns a Arc<Reference> containing a singleton reference to the string "workflow".
§Side Effects
None. This function only returns a reference to a pre-initialized global singleton.
§Usage Pattern
The workflow() function is primarily used internally by the AIMX system for:
- Creating the default workflow structure during workspace initialization
- Accessing the workflow management subsystem
- Internal system operations that require workflow context
For most users, direct usage of this function is not necessary as the workflow functionality is accessed through higher-level API functions.
use aimx::Reference;
// Get the workflow reference (primarily for internal use)
let workflow_ref = Reference::workflow();
assert_eq!(workflow_ref.to_string(), "workflow");§See Also
Reference::workspace()- Reference to the workspace rootReference::context()- Reference to the evaluation contextReference::inference()- Reference to the inference contextReference::status()- Reference to the task statusReference::tool()- Reference to the tool identifier
Sourcepub fn parse(input: &str) -> Result<Arc<Self>>
pub fn parse(input: &str) -> Result<Arc<Self>>
§Parses a reference string into a Reference instance.
§title: Parse
Parses a reference string into a Reference instance.
This function converts a string representation of an AIMX reference into a structured Reference enum variant. References can be simple identifiers or chained property access patterns using dot notation. The parser supports up to four segments and handles function call detection to distinguish between references and method calls.
§Arguments
input- A string slice containing the reference to parse. Can be:- A simple identifier (e.g.,
"foo") - A chained reference with dot notation (e.g.,
"foo.bar.baz") - References with optional whitespace around dots (e.g.,
"foo . bar")
- A simple identifier (e.g.,
§Returns
Returns a Result<Arc<Reference>> containing:
Ok(Arc<Reference>)- A successfully parsed reference wrapped in anArcErr(anyhow::Error)- An error if the input is invalid
§Errors
Returns an error if:
- The input is an invalid reference (e.g., bare underscore
"_") - The input contains invalid identifier syntax
- The input starts with a known function name followed by parentheses (treated as function calls, not references)
§Behavior
Internally, parse() performs the following operations:
- Input Validation: Checks if the input is a valid reference string
- Function Registry Access: Acquires a read lock on the global
FunctionRegistryto distinguish between references and function calls - Identifier Parsing: Parses the first identifier using
parse_identifier() - Reference Chain Parsing: Optionally parses additional segments separated by dots
- Function Call Detection: Checks if segments are followed by parentheses to avoid misinterpreting function calls as references
- Reference Construction: Builds the appropriate
Referencevariant (One,Two,Three, orFour) - Arc Wrapping: Wraps the result in an
Arcfor efficient sharing
The parser supports references with up to four segments:
Reference::One- Single identifier (e.g.,"foo")Reference::Two- Two-part chain (e.g.,"foo.bar")Reference::Three- Three-part chain (e.g.,"foo.bar.baz")Reference::Four- Four-part chain (e.g.,"foo.bar.baz.qux")
§Side Effects
- Acquires a read lock on the global
FunctionRegistry - May consume partial input if the reference is followed by additional content
- Creates new
Arc<Reference>instances for memory management
§Usage Patterns
§Basic Reference Parsing
use aimx::Reference;
use std::sync::Arc;
// Parse a simple identifier
let simple_ref = Reference::parse("my_variable").unwrap();
assert_eq!(simple_ref.to_string(), "my_variable");
// Parse a chained reference
let chained_ref = Reference::parse("object.property").unwrap();
assert_eq!(chained_ref.to_string(), "object.property");
// Parse a deeply nested reference
let nested_ref = Reference::parse("workflow.step.data.value").unwrap();
assert_eq!(nested_ref.to_string(), "workflow.step.data.value");§Error Handling
use aimx::Reference;
// Handle invalid references
match Reference::parse("_") {
Ok(reference) => println!("Parsed: {}", reference),
Err(error) => println!("Parse error: {}", error),
}
// Handle function calls (which are not references)
match Reference::parse("sin(x)") {
Ok(reference) => println!("Parsed as reference: {}", reference),
Err(error) => println!("Correctly rejected as function call: {}", error),
}§Integration with Evaluation Context
use aimx::{Reference, Aim};
use std::sync::Arc;
// Parse a reference for later evaluation
let reference = Reference::parse("user.profile.name").unwrap();
// Acquire workflow context for evaluation
let handle = Aim::acquire(reference.clone()).unwrap();
// ... perform operations with the handle
Aim::release(&handle).unwrap();§See Also
Reference::new()- Create simple single-part references- [
Reference::child()] - Build multi-part references programmatically - [
Reference::normalize()] - Combine references within a scope Reference::identifier()- Extract the final identifier from a referenceparse_reference()- Lower-level parsing function with nom integration
§Identifier Syntax Rules
References must follow AIMX identifier rules:
- Must start with a letter or underscore
- Can contain letters, digits, and underscores after the first character
- Dot notation separates chained property access
- Whitespace is allowed around dots but not within identifiers
- Reserved identifiers like
_(workspace root) cannot be used as standalone references
§Function Call Detection
The parser integrates with the FunctionRegistry to distinguish between:
- References:
object.method(parsed as reference toobjectwith propertymethod) - Function calls:
object.method()(parsed as reference toobject+ separate function call)
When a segment is followed by ( and exists in the function registry, the parser “rolls back” to treat only the preceding segments as the reference.
§Performance Considerations
- Function Registry Lock: Acquires a read lock on the global function registry
- Arc Allocation: Creates
Arcinstances for shared ownership - String Parsing: Uses efficient nom parser combinators
- Minimal Copying: References use
Arc<str>to avoid unnecessary string copying
§Error Messages
The parser provides descriptive error messages:
"Invalid reference ~<input>"for general parsing failures- Context about why certain inputs are rejected (e.g., function calls vs references)
- Line and position information when integrated with larger parsing contexts
Sourcepub fn handle(&self) -> Arc<str>
pub fn handle(&self) -> Arc<str>
§Converts a reference into a handle string by joining parts with underscores.
§title: Handle
Converts a reference into a handle string by joining parts with underscores.
This function transforms a Reference (which uses dot notation for chaining) into
a handle string that uses underscore notation. This is primarily used for creating
unique identifiers for workflow instances in the context workflow, where dot notation
could conflict with property access syntax.
§Arguments
This function takes no arguments. It operates on self, the Reference instance.
§Returns
Returns an Arc<str> containing the handle string representation of the reference.
Each part of the reference is joined with underscores (_) instead of dots (.).
§Behavior
Internally, handle() performs the following operations:
- Create Writer: Initializes a
Writerusing theformulizer()mode for proper escaping - Process Reference Parts: Matches against the reference variant and writes each part:
Reference::One(one)→ writesoneReference::Two(one, two)→ writesone_twoReference::Three(one, two, three)→ writesone_two_threeReference::Four(one, two, three, four)→ writesone_two_three_four
- Join with Underscores: Inserts underscore characters between each part
- Finish and Wrap: Completes the writer and wraps the result in
Arc<str>
§Usage Pattern
The handle() function is primarily used in the high-level API for workflow instance management:
use aimx::{Aim, Reference};
use std::sync::Arc;
// Create a reference to a workflow
let locator = Reference::parse("my_workflow.sub_workflow").unwrap();
// Convert to handle for use in context workflow
let handle: Arc<str> = locator.handle();
// The handle will be "my_workflow_sub_workflow" instead of "my_workflow.sub_workflow"
assert_eq!(&*handle, "my_workflow_sub_workflow");This pattern is used internally by the Aim::acquire() function to create unique
identifiers for workflow instances that won’t conflict with dot notation used for
property access in expressions.
§Examples
use aimx::Reference;
use std::sync::Arc;
// Single part reference
let single = Reference::new(Arc::from("workflow"));
assert_eq!(&*single.handle(), "workflow");
// Two part reference
let two_part = Reference::Two(Arc::from("parent"), Arc::from("child"));
assert_eq!(&*two_part.handle(), "parent_child");
// Three part reference
let three_part = Reference::Three(
Arc::from("workspace"),
Arc::from("workflow"),
Arc::from("step")
);
assert_eq!(&*three_part.handle(), "workspace_workflow_step");
// Four part reference
let four_part = Reference::Four(
Arc::from("root"),
Arc::from("parent"),
Arc::from("child"),
Arc::from("leaf")
);
assert_eq!(&*four_part.handle(), "root_parent_child_leaf");§See Also
Reference::print()- Writes reference using dot notation to a writerReference::to_formula()- Returns formula string representation with dot notationReference::identifier()- Extracts the final identifier from a referenceAim::acquire()- Uses handle() internally for workflow instance management
§Naming Convention
The handle format uses underscores to ensure compatibility with various contexts:
- Avoids Dot Conflicts: Prevents conflicts with property access syntax (
obj.property) - File System Safe: Underscores are safer for file names and identifiers
- URL Safe: Handles can be used in URLs and other contexts where dots might be problematic
- Consistent Formatting: Provides a predictable, flat identifier format
§Performance Considerations
- Writer Reuse: Uses the
formulizer()writer which includes proper escaping - Arc Wrapping: Returns
Arc<str>for efficient sharing and cloning - Single Allocation: Creates the string in one operation without intermediate allocations
- No Validation: Does not validate the reference parts, assuming they are already valid
§Use Cases
The handle format is particularly useful for:
- Workflow Instance Keys: Creating unique keys in the context workflow
- File Names: Generating file names that don’t contain dots
- Database Keys: Creating database keys that avoid dot notation
- API Identifiers: Generating API identifiers that work in various contexts
- Serialization: Creating flat identifiers for serialization formats
Sourcepub fn identifier(&self) -> Arc<str>
pub fn identifier(&self) -> Arc<str>
§Returns the identifier of the terminal segment in a reference chain.
§title: Identifier
Returns the identifier of the terminal segment in a reference chain.
For single-part references, this returns the identifier itself. For multi-part references, this returns the identifier of the final segment in the chain (the rightmost identifier).
§Returns
Returns an Arc<str> containing the terminal identifier.
§Behavior
The identifier() method extracts the terminal identifier from a reference regardless of its chain length:
- For
Reference::One(id)→ returnsid - For
Reference::Two(_, id)→ returnsid - For
Reference::Three(_, _, id)→ returnsid - For
Reference::Four(_, _, _, id)→ returnsid
This method is commonly used to extract the local name component from a fully-qualified reference, particularly when working with cell identifiers in workflow contexts.
§Usage Pattern
use aimx::Reference;
use std::sync::Arc;
// Parse a multi-part reference
let reference = Reference::parse("workflow.node.cell").unwrap();
println!("Full reference: {}", reference);
println!("Terminal identifier: {}", reference.identifier());
// For single-part references
let simple_ref = Reference::new(Arc::from("simple"));
assert_eq!(simple_ref.identifier(), Arc::from("simple"));§See Also
- [
Reference::parent()] - Gets the parent reference (all but the terminal segment) - [
Reference::child()] - Appends a new terminal identifier to create a child reference Reference::new()- Creates a new single-part reference
pub fn depth(&self) -> usize
pub fn is_level_below(&self, reference: &Reference) -> bool
pub fn contains_root(&self) -> bool
pub fn to_path(&self) -> PathBuf
Sourcepub fn rename_child(&self, identifier: Arc<str>) -> Reference
pub fn rename_child(&self, identifier: Arc<str>) -> Reference
§Creates a new Reference instance with the same structure but a different terminal identifier.
§title: Reference rename
This method creates a new Reference instance with the same structure as the original but with a different terminal identifier. It preserves all parent segments of chained references while replacing only the final segment.
§Arguments
identifier- AArc<str>containing the new terminal identifier for the reference.
§Returns
Returns a Reference instance with the same structure as self but with the terminal identifier replaced by the provided identifier.
§Behavior
Internally, rename() performs the following operations based on the reference type:
- For
Reference::One- Creates a new single-part reference with the provided identifier - For
Reference::Two- Creates a new two-part reference preserving the first part and using the new identifier as the second part - For
Reference::Three- Creates a new three-part reference preserving the first two parts and using the new identifier as the third part - For
Reference::Four- Creates a new four-part reference preserving the first three parts and using the new identifier as the fourth part
§Side Effects
This method is a pure function that creates a new Reference instance without modifying the original. No external state is changed.
§Examples
use aimx::{Reference, expressions::ExpressionLike};
use std::sync::Arc;
// Rename a single-part reference
let original = Reference::new(Arc::from("old_name"));
let renamed = original.rename_child(Arc::from("new_name"));
assert_eq!(renamed.to_formula(), "new_name");
// Rename a multi-part reference
let chained = Reference::parse("parent.child").unwrap();
let renamed_chained = chained.rename_child(Arc::from("new_child"));
assert_eq!(renamed_chained.to_formula(), "parent.new_child");
// Rename a deeply nested reference
let deep = Reference::parse("a.b.c").unwrap();
let renamed_deep = deep.rename_child(Arc::from("d"));
assert_eq!(renamed_deep.to_formula(), "a.b.d");§See Also
Reference::new()- Create a new single-part reference- [
Reference::parent()] - Get the parent reference (all parts except terminal) - [
Reference::child()] - Add a child segment to a reference Reference::identifier()- Get the terminal identifier of a reference
Sourcepub fn get_parent(&self) -> Result<Reference>
pub fn get_parent(&self) -> Result<Reference>
§Returns the parent reference by removing the terminal segment from a multi-part reference chain.
§title: Parent
This function returns the parent reference by removing the terminal segment from a multi-part reference chain. It provides a way to navigate up the reference hierarchy.
§Arguments
self- A borrowed reference instance that may contain one to four segments
§Returns
Returns a Result<Reference> containing:
Ok(Reference)- The parent reference with one fewer segmentErr(anyhow::Error)- An error if the reference has no parent (single-segment references)
§Errors
Returns an error if:
- The reference is a single-segment reference (
Reference::One) which has no parent
§Behavior
Internally, parent() performs the following operations:
- Matches on the reference variant to determine the number of segments
- For single-segment references (
Reference::One), returns an error - For multi-segment references, creates a new reference with all segments except the last one:
Reference::Two(one, two)→Reference::One(one)Reference::Three(one, two, three)→Reference::Two(one, two)Reference::Four(one, two, three, four)→Reference::Three(one, two, three)
§Usage Pattern
use aimx::{reference::Reference, expressions::ExpressionLike};
use std::sync::Arc;
// Parse a multi-part reference
let reference = Reference::parse("foo.bar.baz").unwrap();
// Get the parent reference
let parent = reference.get_parent().unwrap();
assert_eq!(parent.to_formula(), "foo.bar");
// Get the grandparent reference
let grandparent = parent.get_parent().unwrap();
assert_eq!(grandparent.to_formula(), "foo");
// Attempting to get parent of single reference fails
let single = Reference::new(Arc::from("single"));
assert!(single.get_parent().is_err());§See Also
child()- Creates a child reference by appending a segmentnormalize()- Combines references within a scopeReference- Reference type documentation
Sourcepub fn add_child(&self, identifier: Arc<str>) -> Result<Reference>
pub fn add_child(&self, identifier: Arc<str>) -> Result<Reference>
§Creates a new Reference by appending an identifier to extend the reference chain.
§title: Child
This function creates a new Reference by appending an identifier to an existing reference, extending the reference chain by one level. This is used to build hierarchical references in AIMX expressions and workflow navigation.
§Arguments
identifier- AArc<str>containing the identifier to append to the reference chain. This becomes the new terminal segment of the reference.
§Returns
Returns a Result<Reference> containing:
Ok(Reference)- A newReferenceinstance with the identifier appended as the terminal segmentErr(anyhow::Error)- An error if the reference chain would exceed the maximum of four segments
§Errors
Returns an error if:
- The current reference already has four segments (maximum depth reached)
- The identifier would create an invalid reference chain
§Behavior
Internally, child() performs the following operations:
- Examines the current reference structure (One, Two, Three, or Four segments)
- Creates a new
Referencewith one additional segment by appending the provided identifier - Returns the new reference chain
- If the current reference already has four segments, returns an error
The function supports building reference chains up to four levels deep:
One→TwoTwo→ThreeThree→FourFour→ Error (maximum depth exceeded)
§Side Effects
- None. This is a pure function that creates a new
Referencewithout modifying the original.
§Usage Pattern
use aimx::{Reference, expressions::ExpressionLike};
use std::sync::Arc;
// Create a base reference
let base_ref = Reference::new(Arc::from("workspace"));
// Extend the reference chain
let child_ref = base_ref.add_child(Arc::from("project")).unwrap();
let grandchild_ref = child_ref.add_child(Arc::from("module")).unwrap();
// Use in expressions or API calls
println!("Base: {}", base_ref.to_formula()); // "workspace"
println!("Child: {}", child_ref.to_formula()); // "workspace.project"
println!("Grandchild: {}", grandchild_ref.to_formula()); // "workspace.project.module"§See Also
Reference::parent()- Get the parent reference by removing the terminal segmentReference::normalize()- Combine two references within a scopeReference::identifier()- Get the terminal identifier of a reference chain
Sourcepub fn combine_and_normalize(&self, reference: &Reference) -> Result<Reference>
pub fn combine_and_normalize(&self, reference: &Reference) -> Result<Reference>
§Combines a scope reference with another reference to create a normalized, fully-qualified reference.
§title: Normalize
This function combines a scope reference with another reference to create a normalized, fully-qualified reference. It’s used during workflow evaluation to resolve relative references within a specific scope context.
§Arguments
reference- A reference to be normalized within the current scope. This can be a single identifier or a multi-part reference chain.
§Returns
Returns a Reference containing the combined reference that merges the current scope with the provided reference. The resulting reference maintains the hierarchical structure of both components.
§Errors
Returns an error if:
- The combined reference would exceed the maximum chain length of 4 segments
- The operation would create an invalid reference structure
§Behavior
Internally, normalize() performs the following operations:
- Determines the current scope reference structure (One, Two, Three, or Four segments)
- Analyzes the reference to be normalized
- Combines the scope with the reference according to these rules:
- One-segment scope + One-segment reference → Two-segment result
- One-segment scope + Two-segment reference → Three-segment result
- One-segment scope + Three-segment reference → Four-segment result
- Two-segment scope + One-segment reference → Three-segment result
- Two-segment scope + Two-segment reference → Four-segment result
- Three-segment scope + One-segment reference → Four-segment result
- Validates that the result doesn’t exceed the four-segment limit
- Returns the combined reference or an error if the limit would be exceeded
§Side Effects
This function has no side effects. It is a pure function that only computes a new reference value.
§Usage Pattern
use aimx::reference::Reference;
use std::sync::Arc;
// Create a scope reference
let scope = Reference::new(Arc::from("workflow"));
// Create a local reference to normalize
let local = Reference::new(Arc::from("variable"));
// Normalize the local reference within the scope
let normalized = scope.combine_and_normalize(&local).unwrap();
assert_eq!(normalized.to_string(), "workflow.variable");
// Works with multi-part references too
let multi_part = Reference::Two(Arc::from("module"), Arc::from("function"));
let fully_qualified = scope.combine_and_normalize(&multi_part).unwrap();
assert_eq!(fully_qualified.to_string(), "workflow.module.function");§See Also
Reference::child()- Appends a single identifier to a referenceReference::parent()- Gets the parent reference by removing the terminal segmentReference::handle()- Converts a reference to a handle string
Sourcepub fn print(&self, writer: &mut Writer)
pub fn print(&self, writer: &mut Writer)
§Serializes a reference into a writer using dot notation.
§title: Print
This method serializes a Reference into a Writer by writing its identifier segments joined with dots.
§Arguments
writer- A mutable reference toWriterwhere the reference will be written as a dot-separated identifier chain.
§Returns
Returns no value (()). The method modifies the Writer in place.
§Behavior
The print() method writes the reference’s identifier segments to the provided Writer using dot notation to separate chained segments:
- Single-part references (
Reference::One) - writes just the identifier - Two-part references (
Reference::Two) - writesidentifier1.identifier2 - Three-part references (
Reference::Three) - writesidentifier1.identifier2.identifier3 - Four-part references (
Reference::Four) - writesidentifier1.identifier2.identifier3.identifier4
The method uses Writer::write_str() to write each identifier segment and Writer::write_char() to write the separating dots.
§Side Effects
- Modifies the internal buffer of the provided
Writer - No other side effects
§Usage Pattern
The print() method is typically called through the WriterLike trait implementation or when constructing formula strings:
use aimx::{Reference, aim::Writer};
use std::sync::Arc;
// Create a multi-part reference
let reference = Reference::Three(
"object".into(),
"property".into(),
"method".into(),
);
// Print to a writer for formula generation
let mut writer = Writer::formulizer();
reference.print(&mut writer);
let formula = writer.finish();
assert_eq!(formula, "object.property.method");§See Also
Reference::to_formula()- Returns a formula string representationReference::handle()- Returns an underscore-separated handle stringWriterLike- Trait providing writing capabilitiesWriter- Buffered writer for AIM/AIMX serialization
Trait Implementations§
Source§impl ExpressionLike for Reference
impl ExpressionLike for Reference
Source§fn evaluate(&self, context: &mut dyn ContextLike) -> Result<Arc<Value>>
fn evaluate(&self, context: &mut dyn ContextLike) -> Result<Arc<Value>>
Evaluate this reference by looking up its value in the context.
This returns Result<Value> so that resolution failures can unwind
to the owning rule. At the rule/expression level, these errors are
converted into Value::Errata for consistent propagation.
If get_referenced returns a Value::Errata, it is passed through
unchanged, allowing error values to propagate naturally through
expressions that reference them.
Source§fn to_formula(&self) -> String
fn to_formula(&self) -> String
Return the formula-string representation (round-trippable by the parser).
Source§impl WriterLike for Reference
impl WriterLike for Reference
Source§fn to_stringized(&self) -> String
fn to_stringized(&self) -> String
Source§fn to_sanitized(&self) -> String
fn to_sanitized(&self) -> String
Source§fn to_expressionized(&self) -> String
fn to_expressionized(&self) -> String
impl Eq for Reference
impl StructuralPartialEq for Reference
Auto Trait Implementations§
impl Freeze for Reference
impl RefUnwindSafe for Reference
impl Send for Reference
impl Sync for Reference
impl Unpin for Reference
impl UnwindSafe for Reference
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
key and return true if they are equal.§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
§impl<T> PolicyExt for Twhere
T: ?Sized,
impl<T> PolicyExt for Twhere
T: ?Sized,
§impl<T> ToStringFallible for Twhere
T: Display,
impl<T> ToStringFallible for Twhere
T: Display,
§fn try_to_string(&self) -> Result<String, TryReserveError>
fn try_to_string(&self) -> Result<String, TryReserveError>
ToString::to_string, but without panic on OOM.