Reference

Enum Reference 

Source
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

Source

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 - An Arc<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:

  1. Reference Construction: Creates a Reference::One variant with the provided identifier
  2. Arc Wrapping: Wraps the reference in an Arc for shared ownership
  3. 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 Reference struct 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 references
    • camelCase, snake_case - Variable naming
    • UPPER_CASE - Constants or special values
Source

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:

  1. Uses a static OnceCell<Arc<Reference>> to ensure the reference is created only once
  2. Creates a new single-part reference with the identifier "_"
  3. 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 Arc and OnceCell
§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 references
  • Aim API documentation - For workspace operations using this reference
Source

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:

  1. Uses a static OnceCell<Arc<Reference>> to ensure the reference is created only once
  2. Creates a new single-part reference with the identifier "inference"
  3. 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 Arc and OnceCell
§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
§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.

Source

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:

  1. Uses a static OnceCell<Arc<Reference>> to ensure the reference is created only once
  2. Creates a new single-part reference with the identifier "context"
  3. 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 Arc and OnceCell
§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:

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:

  1. Instance Registration: When Aim::acquire() is called, a new entry is added to the context workflow with the instance handle as the identifier
  2. Instance Management: The context tracks which workflows are currently being modified
  3. 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
§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
Source

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:

  1. Uses a static OnceCell<Arc<Reference>> to ensure the reference is created only once
  2. Creates a new single-part reference with the identifier "status"
  3. 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 Arc and OnceCell
§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
Source

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:

  1. Uses a static OnceCell<Arc<Reference>> to ensure the reference is created only once
  2. Creates a new single-part reference with the identifier "tool"
  3. 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 Arc and OnceCell
§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:

When used as a workflow node, the tool provides a standardized location for:

  1. Tool Configurations: Store tool-specific settings and parameters
  2. Tool Metadata: Maintain information about available tools and their capabilities
  3. Tool References: Provide a consistent way to reference tools across workflows
  4. 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
§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
Source

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
Source

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")
§Returns

Returns a Result<Arc<Reference>> containing:

  • Ok(Arc<Reference>) - A successfully parsed reference wrapped in an Arc
  • Err(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:

  1. Input Validation: Checks if the input is a valid reference string
  2. Function Registry Access: Acquires a read lock on the global FunctionRegistry to distinguish between references and function calls
  3. Identifier Parsing: Parses the first identifier using parse_identifier()
  4. Reference Chain Parsing: Optionally parses additional segments separated by dots
  5. Function Call Detection: Checks if segments are followed by parentheses to avoid misinterpreting function calls as references
  6. Reference Construction: Builds the appropriate Reference variant (One, Two, Three, or Four)
  7. Arc Wrapping: Wraps the result in an Arc for 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 reference
  • parse_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 to object with property method)
  • Function calls: object.method() (parsed as reference to object + 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 Arc instances 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
Source

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:

  1. Create Writer: Initializes a Writer using the formulizer() mode for proper escaping
  2. Process Reference Parts: Matches against the reference variant and writes each part:
    • Reference::One(one) → writes one
    • Reference::Two(one, two) → writes one_two
    • Reference::Three(one, two, three) → writes one_two_three
    • Reference::Four(one, two, three, four) → writes one_two_three_four
  3. Join with Underscores: Inserts underscore characters between each part
  4. 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
§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
Source

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) → returns id
  • For Reference::Two(_, id) → returns id
  • For Reference::Three(_, _, id) → returns id
  • For Reference::Four(_, _, _, id) → returns id

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
Source

pub fn base(&self) -> Arc<str>

Returns the base in a reference chain.

Source

pub fn depth(&self) -> usize

Source

pub fn is_level_below(&self, reference: &Reference) -> bool

Source

pub fn contains_root(&self) -> bool

Source

pub fn to_path(&self) -> PathBuf

Source

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 - A Arc<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:

  1. For Reference::One - Creates a new single-part reference with the provided identifier
  2. For Reference::Two - Creates a new two-part reference preserving the first part and using the new identifier as the second part
  3. For Reference::Three - Creates a new three-part reference preserving the first two parts and using the new identifier as the third part
  4. 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
Source

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 segment
  • Err(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:

  1. Matches on the reference variant to determine the number of segments
  2. For single-segment references (Reference::One), returns an error
  3. 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 segment
  • normalize() - Combines references within a scope
  • Reference - Reference type documentation
Source

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 - A Arc<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 new Reference instance with the identifier appended as the terminal segment
  • Err(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:

  1. Examines the current reference structure (One, Two, Three, or Four segments)
  2. Creates a new Reference with one additional segment by appending the provided identifier
  3. Returns the new reference chain
  4. If the current reference already has four segments, returns an error

The function supports building reference chains up to four levels deep:

  • OneTwo
  • TwoThree
  • ThreeFour
  • Four → Error (maximum depth exceeded)
§Side Effects
  • None. This is a pure function that creates a new Reference without 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
Source

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:

  1. Determines the current scope reference structure (One, Two, Three, or Four segments)
  2. Analyzes the reference to be normalized
  3. 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
  4. Validates that the result doesn’t exceed the four-segment limit
  5. 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
Source

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 to Writer where 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:

  1. Single-part references (Reference::One) - writes just the identifier
  2. Two-part references (Reference::Two) - writes identifier1.identifier2
  3. Three-part references (Reference::Three) - writes identifier1.identifier2.identifier3
  4. Four-part references (Reference::Four) - writes identifier1.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

Trait Implementations§

Source§

impl Clone for Reference

Source§

fn clone(&self) -> Reference

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Reference

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Reference

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl ExpressionLike for Reference

Source§

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

Return the formula-string representation (round-trippable by the parser).

Source§

impl Hash for Reference

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq<Reference> for Workflow

Source§

fn eq(&self, other: &Reference) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialEq<Reference> for str

Source§

fn eq(&self, other: &Reference) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialEq<Workflow> for Reference

Source§

fn eq(&self, other: &Workflow) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialEq<str> for Reference

Source§

fn eq(&self, other: &str) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialEq for Reference

Source§

fn eq(&self, other: &Reference) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl WriterLike for Reference

Source§

fn write(&self, writer: &mut Writer)

Serialize this expression with the given Writer.
Source§

fn to_stringized(&self) -> String

Return a string representation (raw unsafe output).
Source§

fn to_sanitized(&self) -> String

Return a sanitized string representation (escaped for safe output).
Source§

fn to_expressionized(&self) -> String

Return a sanitized string representation (escaped for safe output).
Source§

impl Eq for Reference

Source§

impl StructuralPartialEq for Reference

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> PolicyExt for T
where T: ?Sized,

§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] only if self and other return Action::Follow. Read more
§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] if either self or other returns Action::Follow. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
§

impl<T> ToStringFallible for T
where T: Display,

§

fn try_to_string(&self) -> Result<String, TryReserveError>

ToString::to_string, but without panic on OOM.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

impl<T> ErasedDestructor for T
where T: 'static,