FluentAI API Reference
Complete reference documentation for the FluentAI standard library and built-in functions.
Core Functions
print(value: any) -> unit
Prints a value to the console without a trailing newline. This function performs an IO effect.
Parameters
-
value
: any
The value to print. Can be any type - it will be converted to a string representation.
Example
// Direct printing
$("Hello, World!").print();
// Printing variables
let name = "Alice";
$(f"Hello, {name}!").print();
// Using with effect handlers
perform IO.print("Processing...");
map
map<T, U>(list: List<T>, f: (T) -> U) -> List<U>
Transforms each element of a list by applying a function, returning a new list with the transformed elements.
Parameters
-
list
: List<T>
The input list to transform.
-
f
: (T) -> U
A function that transforms each element from type T to type U.
Returns
A new list containing the transformed elements.
Example
let numbers = [1, 2, 3, 4, 5];
let doubled = numbers.map(x => x * 2);
// doubled = [2, 4, 6, 8, 10]
let users = [
{name: "Alice", age: 30},
{name: "Bob", age: 25}
];
let names = users.map(user => user.name);
// names = ["Alice", "Bob"]
filter
filter<T>(list: List<T>, predicate: (T) -> bool) -> List<T>
Returns a new list containing only the elements that satisfy the given predicate function.
Parameters
-
list
: List<T>
The input list to filter.
-
predicate
: (T) -> bool
A function that returns true for elements to keep.
Example
let numbers = [1, 2, 3, 4, 5, 6];
let evens = numbers.filter(x => x % 2 == 0);
// evens = [2, 4, 6]
let users = getUserList();
let activeUsers = users
.filter(user => user.active)
.filter(user => user.lastLogin > yesterday);
Type System
Result<T, E>
EnumRepresents the result of an operation that can either succeed with a value of type T or fail with an error of type E.
Variants
| Variant | Description |
|---|---|
Ok(T) |
The operation succeeded with value T |
Err(E) |
The operation failed with error E |
Example
private function divide(a: float, b: float) -> Result {
if (b == 0) {
Err("Division by zero")
} else {
Ok(a / b)
}
}
// Using pattern matching
divide(10, 2).match()
.case(Ok(result), => $(f"Result: {result}").print())
.case(Err(error), => $(f"Error: {error}").print())
.get();
Option<T>
EnumRepresents an optional value that may or may not be present.
Variants
| Variant | Description |
|---|---|
Some(T) |
A value is present |
None |
No value is present |
I/O Operations
IO.read_file
IO.read_file(path: string) -> Result<string, IOError>
Reads the contents of a file as a string. This is an asynchronous operation that performs an IO effect.
Parameters
-
path
: string
The path to the file to read.
Returns
A Result containing either the file contents as a string or an IOError.
Example
// Reading a file with error handling
let contents = perform IO.read_file("config.json");
contents.match()
.case(Ok(data), => parse_json(data))
.case(Err(error), => {
$(f"Failed to read file: {error}").print();
use_default_config()
})
.get();
AI Analysis
FluentAI includes native AI-driven AST analysis capabilities for detecting patterns and optimization opportunities.
analyze_ast
analyze_ast(graph: &Graph) -> Result<AiAnalysisResult, Error>
Performs AI-powered analysis on an AST graph to detect patterns, suggest optimizations, and generate performance insights.
Parameters
-
graph
: &Graph
The AST graph to analyze. Features are extracted directly from nodes without serialization.
Returns
An AiAnalysisResult containing performance score, detected patterns, and optimization suggestions.
Example
use fluentai_ai::analyze_ast;
// Analyze the AST
let analysis = analyze_ast(&ast_graph)?;
// Check performance score
$(f"Performance score: {analysis.performance_score}").print();
// Examine detected patterns
for pattern in analysis.detected_patterns {
$(f"Found pattern: {:?}", pattern.pattern_type).print();
}
AiAnalyzerBuilder
AiAnalyzerBuilder::new() -> Self
Builder pattern for creating custom AI analyzers with specific configuration options.
Builder Methods
| Method | Description |
|---|---|
detect_patterns(bool) |
Enable/disable pattern detection |
detect_optimizations(bool) |
Enable/disable optimization detection |
generate_embeddings(bool) |
Enable/disable node embedding generation |
with_cache(bool) |
Enable/disable result caching |
build() |
Create the configured analyzer |
Example
// Create a custom analyzer
let analyzer = AiAnalyzerBuilder::new()
.detect_patterns(true)
.detect_optimizations(true)
.generate_embeddings(false)
.with_cache(true)
.build();
// Use the analyzer
let result = analyzer.analyze_graph(&ast)?;
// Access embeddings if generated
if let Some(embeddings) = result.node_embeddings {
for (node_id, embedding) in embeddings {
// Use embeddings for similarity analysis
}
}
Pattern Detection
PatternType
EnumRepresents different code patterns that can be detected by the AI analysis system.
Variants
| Pattern | Description |
|---|---|
MapReduce |
Map followed by reduce operations |
FilterMap |
Filter followed by map operations |
RecursiveDescent |
Recursive function patterns |
NestedLoops |
Multiple nested loop structures |
ConditionalChain |
Long if-else chains |
CallbackHell |
Deeply nested callbacks |
DetectedPattern
Information about a detected pattern in the code.
Fields
| Field | Type | Description |
|---|---|---|
pattern_type |
PatternType |
The type of pattern detected |
confidence |
f32 |
Confidence score (0.0 - 1.0) |
node_ids |
Vec<NodeId> |
AST nodes involved in the pattern |
suggestion |
Option<String> |
Optimization suggestion if applicable |
Optimization Hints
OptimizationType
EnumTypes of optimizations that can be suggested by the AI analysis.
Variants
| Optimization | Description |
|---|---|
ConstantFolding |
Evaluate constant expressions at compile time |
CommonSubexpression |
Eliminate duplicate computations |
TailRecursion |
Convert tail recursion to iteration |
DeadCodeElimination |
Remove unreachable code |
LoopFusion |
Combine adjacent loops |
LoopUnrolling |
Unroll small loops for performance |
OptimizationHint
Detailed information about a suggested optimization.
Fields
| Field | Type | Description |
|---|---|---|
optimization_type |
OptimizationType |
Type of optimization |
impact |
f32 |
Estimated performance impact (0.0 - 1.0) |
node_id |
NodeId |
Target node for optimization |
description |
String |
Human-readable description |
Example
// Apply optimization hints
for hint in analysis.optimization_hints {
match hint.optimization_type {
OptimizationType::ConstantFolding => {
// Apply constant folding optimization
optimizer.fold_constants(hint.node_id);
},
OptimizationType::TailRecursion => {
// Convert to iterative form
optimizer.optimize_tail_recursion(hint.node_id);
},
_ => {
// Log other optimizations for manual review
$(f"Suggested: {hint.description}").print();
}
}
}
Metadata Injection
MetadataInjector
MetadataInjector::new(config: InjectorConfig) -> Self
Injects AI analysis results back into the AST metadata for use during compilation.
Configuration
let config = InjectorConfig {
inject_optimizations: true, // Add optimization hints
inject_patterns: true, // Add pattern information
inject_embeddings: false, // Add node embeddings
metadata_prefix: "ai-", // Prefix for metadata tags
};
Methods
| Method | Description |
|---|---|
inject(&self, graph: &mut Graph, analysis: &AiAnalysisResult) |
Inject analysis results into AST metadata |
extract(&self, graph: &Graph) -> Option<AiAnalysisResult> |
Extract previously injected metadata |
Example
// Inject AI metadata into AST
let injector = MetadataInjector::new(InjectorConfig {
inject_optimizations: true,
inject_patterns: true,
inject_embeddings: false,
metadata_prefix: "ai-",
});
// Perform analysis
let analysis = analyze_ast(&graph)?;
// Inject results
injector.inject(&mut graph, &analysis)?;
// Later in compilation pipeline...
// Metadata is available in node.metadata.context_memory
NodeMetadata.feature_vector
NodeMetadata::feature_vector(&self) -> Vec<f32>
Extracts ML-ready features directly from AST node metadata. Available when the ai-analysis feature is enabled.
Feature Components
- Node type encoding
- Purity analysis results
- Type information hash
- Usage statistics
- Performance hints
- Context memory features
Example
// Extract features from AST nodes
#[cfg(feature = "ai-analysis")]
{
let features = node.metadata.feature_vector();
// Features are normalized to [0, 1] range
// Suitable for direct use in ML models
// Use with tensor builder
let tensor = TensorBuilder::new()
.normalize(true)
.build_from_graph(&graph)?;
}
Channels
channel
channel<T>(capacity: int) -> Channel<T>
Creates a new channel for communication between concurrent tasks. Channels are the primary mechanism for safe data sharing in FluentAI.
Parameters
-
capacity
: int
The buffer size of the channel. Use 0 for unbuffered (synchronous) channels.
Channel Methods
| Method | Description |
|---|---|
send(value: T) |
Send a value to the channel |
receive() -> T |
Receive a value from the channel |
try_send(value: T) -> bool |
Try to send without blocking |
try_receive() -> Option<T> |
Try to receive without blocking |
close() |
Close the channel |
Example
// Producer-consumer pattern
let ch = channel(10);
// Producer
spawn {
for i in range(0, 100) {
ch.send(i * i);
}
ch.close();
};
// Consumer
spawn {
for value in ch {
$(f"Received: {value}").print();
}
};