elo-rust 0.4.1

Rust code generation target for ELO validation language
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
# ELO Rust Code Generation Target

A production-grade Rust code generation target for the ELO validation language. Converts ELO validation expressions into zero-cost Rust validators with <1ยตs execution time.

[![CI][ci-badge]][ci-link]
[![Crates.io][crates-badge]][crates-link]
[![Docs.rs][docs-badge]][docs-link]
[![License][license-badge]][license-link]
[![Security Audit][security-badge]][security-link]
[![Code Coverage][coverage-badge]][coverage-link]

[ci-badge]: https://github.com/evoludigit/elo-rust/workflows/CI/badge.svg
[ci-link]: https://github.com/evoludigit/elo-rust/actions/workflows/ci.yml
[crates-badge]: https://img.shields.io/crates/v/elo-rust.svg
[crates-link]: https://crates.io/crates/elo-rust
[docs-badge]: https://docs.rs/elo-rust/badge.svg
[docs-link]: https://docs.rs/elo-rust
[license-badge]: https://img.shields.io/crates/l/elo-rust.svg
[license-link]: #license
[security-badge]: https://img.shields.io/badge/security-audited-green.svg
[security-link]: ./FINAL_SECURITY_REPORT.md
[coverage-badge]: https://img.shields.io/badge/coverage-65%25%2B-brightgreen.svg
[coverage-link]: #testing

## Features

โœจ **High Performance**
- Generated validators execute in <1ยตs
- Zero-copy design with minimal allocations
- Compile-time optimization via Rust compiler

๐ŸŽฏ **Comprehensive Validation**
- String operations: regex matching, contains, length, case conversion, trim, starts_with, ends_with
- Date/time functions: today(), now(), age(), days_since(), date parsing
- Array operations: contains, any, all, length, is_empty
- Type checking: is_null, is_some for Option types

๐Ÿ› ๏ธ **Developer Friendly**
- Simple validator macro: `#[elo_validator(elo = "expression")]`
- CLI tool for code generation: `elo compile --expression "age >= 18"`
- Framework integration examples (Actix-web, Axum)
- Comprehensive error reporting

## Quick Start

### Using the Validator Macro

```rust
use elo_rust::elo_validator;

#[elo_validator(elo = r#"
  email matches "^[a-z]+@example\.com$" &&
  age >= 18 &&
  verified == true
"#)]
pub struct UserValidator;

let user = User { age: 25, email: "john@example.com".to_string(), verified: true };
match UserValidator::validate(&user) {
    Ok(()) => println!("โœ… Valid user"),
    Err(e) => println!("โŒ Error: {}", e),
}
```

### Using the CLI

```bash
# Parse and validate ELO expression
elo compile --expression "age >= 18 && verified == true"

# Parse from file
elo validate --input rules.elo

# Compile with output
elo compile --input rules.elo --output validator.rs
```

### As a Library

```rust
use elo_rust::parser::Parser;
use elo_rust::codegen::RustCodeGenerator;

// Parse ELO expression
let parser = Parser::new("age >= 18");
let ast = parser.parse()?;

// Generate Rust code
let gen = RustCodeGenerator::new();
let code = gen.generate_validator("validate_age", &ast, "User")?;
```

### In Actix-web (With ELO Validator)

```rust
use actix_web::{post, web, App, HttpServer};
use elo_rust::elo_validator;
use serde::{Deserialize, Serialize};

#[derive(Deserialize, Clone)]
struct CreateUserRequest {
    username: String,
    email: String,
    age: i32,
}

#[derive(Serialize)]
struct ValidationError {
    field: String,
    message: String,
}

#[elo_validator(elo = r#"
  email matches "^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,}$" &&
  username.length() >= 3 && username.length() <= 20 &&
  age >= 18 && age <= 120
"#)]
struct UserValidator;

#[post("/users")]
async fn create_user(req: web::Json<CreateUserRequest>) -> HttpResponse {
    match UserValidator::validate(&req) {
        Ok(()) => HttpResponse::Created().json(serde_json::json!({
            "message": "User created successfully"
        })),
        Err(errors) => HttpResponse::BadRequest().json(serde_json::json!({
            "errors": errors
        })),
    }
}
```

## Supported Functions & Operators

### String Functions (8)
- `matches(pattern)` - Regex pattern matching
- `contains(substring)` - Substring search
- `length()` - String length
- `uppercase()` - Convert to uppercase
- `lowercase()` - Convert to lowercase
- `trim()` - Remove whitespace
- `starts_with(prefix)` - Prefix check
- `ends_with(suffix)` - Suffix check

### DateTime Functions (5)
- `today()` - Current date
- `now()` - Current UTC timestamp
- `age(birthdate)` - Age calculation from birthdate
- `days_since(date)` - Days elapsed
- `date("YYYY-MM-DD")` - Parse ISO 8601 date

### Temporal Keywords (16)
`NOW`, `TODAY`, `TOMORROW`, `YESTERDAY`, `EPOCH`,
`UTC`, `START_OF_DAY`, `END_OF_DAY`, `START_OF_WEEK`,
`END_OF_WEEK`, `START_OF_MONTH`, `END_OF_MONTH`,
`START_OF_YEAR`, `END_OF_YEAR`, `MIDNIGHT`, `NOON`

### Array Functions (5)
- `contains(value)` - Element search
- `any(predicate)` - Existence check with closure
- `all(predicate)` - Universal check with closure
- `length()` - Array size
- `is_empty()` - Empty check

### Type Functions (2)
- `is_null()` - Option null check
- `is_some()` - Option some check

### Operators
**Arithmetic**: `+`, `-`, `*`, `/`, `%`
**Comparison**: `==`, `!=`, `<`, `<=`, `>`, `>=`
**Logical**: `&&`, `||`, `!`

## Expression Examples

### Simple Validation
```elo
age >= 18
```

### Email & Username Validation
```elo
email matches "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$" &&
username |> length() >= 3 && username |> length() <= 20
```

### Temporal Validation (New in 0.4.0)
```elo
created_at >= TODAY &&
expires_at > NOW &&
updated_at < END_OF_DAY
```

### Conditional Validation with Let Bindings
```elo
let username_len = username |> length() in
let email_valid = email matches "^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,}$" in
username_len >= 3 && username_len <= 20 && email_valid
```

### User Account Validation with Guard
```elo
guard age >= 18 && verified in
email matches "^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,}$" &&
username |> length() >= 3
```

### Permission Checking
```elo
(roles |> contains("admin") || roles |> contains("moderator")) &&
verified == true &&
active == true
```

### Order Validation with Aggregation
```elo
items |> length() > 0 &&
items |> all(quantity > 0 && price > 0) &&
total > 0
```

### Conditional Pricing with If Expression
```elo
if verified then price * 0.9 else price
```

### Complex Policy Logic
```elo
let is_admin = roles |> contains("admin") in
let account_age = days_since(created_at) in
if is_admin then
  account_age > 0
else
  account_age > 30 && verified && payment_verified
```

## API Documentation

### RustCodeGenerator

Main code generator for transforming ELO expressions to Rust code.

```rust
pub struct RustCodeGenerator {
    // Type context for resolving custom types
}

impl RustCodeGenerator {
    pub fn new() -> Self
    pub fn with_context(type_context: TypeContext) -> Self
    pub fn generate_function_signature(
        &self,
        name: &str,
        input_type: &str,
    ) -> Result<TokenStream, String>

    pub fn generate_literal_integer(&self, value: i64) -> Result<TokenStream, String>
    pub fn generate_literal_string(&self, value: &str) -> Result<TokenStream, String>
    pub fn generate_literal_bool(&self, value: bool) -> Result<TokenStream, String>

    pub fn generate_field_access(
        &self,
        receiver: &str,
        field: &str,
    ) -> Result<TokenStream, String>

    pub fn generate_validator(
        &self,
        name: &str,
        elo_expr: &str,
        input_type: &str,
    ) -> Result<TokenStream, String>
}
```

### OperatorGenerator

Generates code for binary and unary operations.

```rust
pub struct OperatorGenerator;

impl OperatorGenerator {
    pub fn new() -> Self
    pub fn binary(
        &self,
        op: BinaryOp,
        left: TokenStream,
        right: TokenStream,
    ) -> TokenStream
    pub fn unary(
        &self,
        op: UnaryOp,
        operand: TokenStream,
    ) -> TokenStream
}
```

### FunctionGenerator

Generates code for standard library functions.

```rust
pub struct FunctionGenerator;

impl FunctionGenerator {
    pub fn new() -> Self
    pub fn string_function(
        &self,
        name: &str,
        args: Vec<TokenStream>,
    ) -> TokenStream
    pub fn datetime_function(
        &self,
        name: &str,
        args: Vec<TokenStream>,
    ) -> TokenStream
    pub fn array_function(
        &self,
        name: &str,
        args: Vec<TokenStream>,
    ) -> TokenStream
}
```

## Project Statistics

- **Total Tests**: 786 (100% passing)
- **Code Coverage**: 70%+ of codebase
- **Production Code**: 4,600+ lines
- **Standard Library Functions**: 20+ implemented
- **Temporal Functions**: 16 keywords supported
- **Code Generation**: Full AST visitor pattern with optimization
- **Performance**: <5ยตs full compilation, <1ยตs execution
- **Security**: Enterprise-grade hardening with comprehensive validation

## Testing

Run the full test suite:
```bash
cargo test
```

Run specific test category:
```bash
cargo test string_functions
cargo test datetime_functions
cargo test array_functions
cargo test macro_usage
```

Run examples:
```bash
cargo run --example actix_validator --features serde-support
cargo run --example axum_validator --features serde-support
```

## Building

```bash
# Debug build
cargo build

# Release build with optimizations
cargo build --release

# CLI tool
cargo build --bin elo

# Documentation
cargo doc --no-deps --open
```

## Architecture

```
src/
โ”œโ”€โ”€ lib.rs                    # Public API
โ”œโ”€โ”€ parser/
โ”‚   โ”œโ”€โ”€ mod.rs              # Recursive descent parser
โ”‚   โ”œโ”€โ”€ lexer.rs            # Tokenization
โ”‚   โ””โ”€โ”€ error.rs            # Parse errors with source context
โ”œโ”€โ”€ ast/
โ”‚   โ”œโ”€โ”€ mod.rs              # AST definitions
โ”‚   โ””โ”€โ”€ visitor.rs          # Visitor pattern for traversal
โ”œโ”€โ”€ codegen/
โ”‚   โ”œโ”€โ”€ mod.rs              # Main RustCodeGenerator
โ”‚   โ”œโ”€โ”€ ast_to_code.rs      # AST visitor to TokenStream
โ”‚   โ”œโ”€โ”€ operators.rs        # Binary/unary operators
โ”‚   โ”œโ”€โ”€ functions.rs        # String/date/array functions
โ”‚   โ”œโ”€โ”€ temporal.rs         # Temporal type operations
โ”‚   โ”œโ”€โ”€ type_inference.rs   # Type inference engine
โ”‚   โ”œโ”€โ”€ optimization.rs     # Constant folding optimizer
โ”‚   โ”œโ”€โ”€ types.rs            # Type system & context
โ”‚   โ””โ”€โ”€ errors.rs           # Code generation errors
โ”œโ”€โ”€ runtime/
โ”‚   โ”œโ”€โ”€ mod.rs              # ValidationError types
โ”‚   โ”œโ”€โ”€ value.rs            # EloValue enum for runtime types
โ”‚   โ””โ”€โ”€ temporal.rs         # Temporal value operations
โ”œโ”€โ”€ security.rs             # Input validation & security
โ””โ”€โ”€ bin/
    โ””โ”€โ”€ elo.rs              # CLI tool

tests/
โ”œโ”€โ”€ error_handling.rs       # 26 error tests
โ”œโ”€โ”€ temporal_integration.rs # 14 temporal tests
โ”œโ”€โ”€ parsing.rs              # 9 benchmark tests
โ””โ”€โ”€ ... (19 other test modules, 700+ tests total)

benches/
โ””โ”€โ”€ parsing.rs              # Performance benchmarks

examples/
โ”œโ”€โ”€ simple_validator.rs     # Basic example
โ”œโ”€โ”€ actix_validator.rs      # Actix integration
โ””โ”€โ”€ axum_validator.rs       # Axum integration
```

## Performance

Generated validators are designed for minimal overhead:

- **Code Generation**: <100ms per expression
- **Validator Execution**: <1ยตs per check
- **Memory Overhead**: Minimal allocations
- **Binary Size**: ~50 lines typical validator code

## License

MIT

## Contributing

Contributions are welcome! Please ensure:
- All tests pass: `cargo test`
- Code passes clippy: `cargo clippy --all-targets -- -D warnings`
- Code is formatted: `cargo fmt`

## Support

For issues, questions, or contributions, please visit:
https://github.com/enspirit/elo

---

**Version**: 0.4.1
**Status**: โœ… Production Ready
**Last Updated**: February 8, 2026
**Architecture**: โœ… Complete (8 phases)
**Tests**: โœ… 786 passing (100%)
**Coverage**: โœ… 70%+
**Benchmarks**: โœ… <5ยตs compilation, <1ยตs execution