aam-rs 2.0.2

A Rust implementation of the Abstract Alias Mapping (AAM) framework for aliasing and maping aam files.
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
# AAM-RS Architecture Refactoring — From Monolithic to Pipeline

## Overview

The AAM-RS codebase has been refactored from a monolithic `AAML` struct into a clean five-stage pipeline architecture. This document explains the new design, component responsibilities, and how to extend or customize the pipeline.

## Architecture Diagram

```
Text Input
┌───────────────────────────────────────────────────────────────┐
│                          Pipeline                             │
├───────────────────────────────────────────────────────────────┤
│                                                               │
│  Stage 1: Lexer          →  Token Stream (Vec<Token>)       │
│  ├─ Tokenizes raw text                                       │
│  ├─ Preserves line/column info for error diagnostics        │
│  └─ Produces: Vec<Token>                                    │
│                                                               │
│  Stage 2: Parser + ScopeManager  →  AST (Vec<AstNode>)     │
│  ├─ Consumes tokens                                          │
│  ├─ Builds Abstract Syntax Tree                             │
│  ├─ Tracks nesting depth and block context                  │
│  └─ Produces: Vec<AstNode>                                  │
│                                                               │
│  Stage 3: Validator  →  Validation Result                   │
│  ├─ Applies semantic checks                                  │
│  ├─ Validates type and schema constraints                   │
│  └─ Produces: Result<(), AamlError>                         │
│                                                               │
│  Stage 4: Executer  →  PipelineOutput                       │
│  ├─ Executes directives (@import, @schema, @type, @derive) │
│  ├─ Populates final key-value map                           │
│  └─ Produces: PipelineOutput                                │
│                                                               │
└───────────────────────────────────────────────────────────────┘
Final State
├─ Key-Value Map
├─ Schema Definitions
└─ Type Registry


Public API
├─ AAML::parse() — backward-compatible facade
├─ AAML::load() — backward-compatible facade
├─ AAML::find_obj() — query API (unchanged)
├─ AAML::find_deep() — query API (unchanged)
└─ Pipeline::process() — new direct pipeline access
```

## Component Details

### 1. Lexer Stage (`src/pipeline/lexer.rs`)

**Responsibility:** Tokenize raw AAML text into a flat stream of tokens.

**Input:** `&str` (raw file content)  
**Output:** `Result<Vec<Token>, AamlError>`

**Key Types:**
- `Token` — single token with kind, line, column, and text
- `TokenKind` — enum: Identifier, Assign, String, Number, Boolean, LeftBrace, RightBrace, LeftBracket, RightBracket, Comma, At, Newline, Comment
- `Lexer` trait — implement this for custom lexers
- `DefaultLexer` — production implementation

**Features:**
- Character-by-character scanning
- Line/column tracking for precise error diagnostics
- String literal handling (quoted with `"` or `'`)
- Number and boolean literal recognition
- Comment recognition (`#`)
- Directive prefix (`@`) tokenization
- Inline object/list bracket matching

**Example:**
```rust
use aam_rs::pipeline::DefaultLexer;

let lexer = DefaultLexer::new();
let tokens = lexer.tokenize("host = localhost")?;
// tokens: [Identifier("host"), Assign, Identifier("localhost"), Newline]
```

### 2. Parser Stage (`src/pipeline/parser.rs`)

**Responsibility:** Parse tokens into an Abstract Syntax Tree.

**Input:** `Vec<Token>`  
**Output:** `Result<Vec<AstNode>, AamlError>`

**Key Types:**
- `AstNode` — enum representing parsed statements
  - `Assignment { key, value, line }`
  - `Directive { name, args, line }`
  - `InlineObject { pairs, line }`
  - `InlineList { items, line }`
- `Parser` trait — implement for custom parsers
- `DefaultParser` — production implementation

**Features:**
- Token consumption and validation
- Multi-line directive accumulation
- Inline object/list parsing
- Balanced delimiter checking
- Line number preservation

**Example:**
```rust
use aam_rs::pipeline::{DefaultLexer, DefaultParser, Lexer, Parser};

let lexer = DefaultLexer::new();
let tokens = lexer.tokenize("@import base.aam")?;

let parser = DefaultParser::new();
let ast = parser.parse(tokens)?;
// ast: [Directive { name: "import", args: "base.aam", line: 1 }]
```

### 3. ScopeManager (`src/pipeline/scope_manager.rs`)

**Responsibility:** Track syntactic nesting context during parsing.

**Usage:** Used internally by the Parser to manage block nesting state.

**Key Types:**
- `ScopeManager` — manages nesting depth and accumulated content
- `BlockType` — enum: None, Object, List, DirectiveBlock

**Features:**
- Tracks brace/bracket nesting depth
- Accumulates multi-line directive content
- Detects balanced block completeness
- Provides block context for semantic analysis

**Example:**
```rust
use aam_rs::pipeline::scope_manager::{ScopeManager, BlockType};

let mut scope = ScopeManager::new();
scope.enter_block(BlockType::Object);
assert_eq!(scope.nesting_depth(), 1);
scope.exit_block().unwrap();
assert_eq!(scope.nesting_depth(), 0);
```

### 4. Validator Stage (`src/pipeline/validator.rs`)

**Responsibility:** Perform semantic validation on the AST.

**Input:** `&[AstNode]`  
**Output:** `Result<(), AamlError>`

**Key Types:**
- `Validator` trait — implement for custom validators
- `DefaultValidator` — production implementation

**Checks Performed:**
- Non-empty keys in assignments
- Non-empty directive names
- Balanced braces and brackets in values
- Basic syntactic correctness

**Note:** Schema/type validation happens in the Executer after directives are processed, since schemas and types are defined via `@schema` and `@type` directives.

**Example:**
```rust
use aam_rs::pipeline::{DefaultLexer, DefaultParser, DefaultValidator, Lexer, Parser, Validator};

let lexer = DefaultLexer::new();
let tokens = lexer.tokenize("key = value")?;
let parser = DefaultParser::new();
let ast = parser.parse(tokens)?;

let validator = DefaultValidator::new();
validator.validate(&ast)?;  // Returns Ok(()) if valid
```

### 5. Executer Stage (`src/pipeline/executer.rs`)

**Responsibility:** Execute directives and populate the final runtime state.

**Input:** `Vec<AstNode>`  
**Output:** `Result<PipelineOutput, AamlError>`

**Key Types:**
- `Executer` trait — implement for custom executers
- `DefaultExecuter` — production implementation
- `ExecutionDescriptor` — metadata about what was executed
- `PipelineOutput` — final state (map, schemas, types)

**Workflow:**
1. Create an `AAML` instance with default command handlers
2. Iterate through AST nodes in order
3. For assignments: store in the key-value map
4. For directives: find and execute registered command handler
5. Return `PipelineOutput` with final state

**Example:**
```rust
use aam_rs::pipeline::{DefaultExecuter, Executer, AstNode};

let ast = vec![
    AstNode::Assignment { key: "a".to_string(), value: "b".to_string(), line: 1 },
];

let executer = DefaultExecuter::new();
let output = executer.execute(ast)?;
assert!(output.map.contains_key("a"));
```

### 6. Pipeline Orchestrator (`src/pipeline/mod.rs`)

**Responsibility:** Coordinate all five stages and provide the unified entry point.

**Key Types:**
- `Pipeline` — orchestrator
- `PipelineOutput` — final result

**Main Method:**
```rust
pub fn process(&self, content: &str) -> Result<PipelineOutput, AamlError>
```

**Example:**
```rust
use aam_rs::pipeline::Pipeline;

let pipeline = Pipeline::new();
let output = pipeline.process("host = localhost\nport = 8080")?;

println!("Keys: {:?}", output.map.keys().collect::<Vec<_>>());
// Keys: ["host", "port"]
```

## Backward Compatibility

The existing `AAML` public API remains unchanged and is now a **thin facade** over the pipeline:

```rust
use aam_rs::aaml::AAML;

// Old API still works exactly the same
let cfg = AAML::parse("host = localhost")?;
let value = cfg.find_obj("host")?;
```

**Implementation:**
- `AAML::parse()` and `AAML::load()` internally use `Pipeline::process()`
- `AAML::find_obj()` and `AAML::find_deep()` query the finalized map (unchanged)
- All existing directives and commands work identically
- All v1 syntax remains supported

## Error Handling

Each pipeline stage can produce specialized errors:

**Lexer Errors:**
- `AamlError::LexError` — invalid character or unclosed delimiter

**Parser Errors:**
- `AamlError::ParseError` — malformed syntax, missing operators, unbalanced braces

**Validator Errors:**
- `AamlError::ParseError` — semantic violations (empty keys, unbalanced delimiters)

**Executer Errors:**
- `AamlError::DirectiveError` — unknown or malformed directive
- `AamlError::SchemaValidationError` — schema constraint violated
- `AamlError::InvalidType` — type validation failed

**Line Number Tracking:**
Each error carries the source line number for precise diagnostics.

## Extending the Pipeline

### Custom Lexer

Implement the `Lexer` trait:

```rust
use aam_rs::pipeline::{Lexer, Token};
use crate::error::AamlError;

struct MyCustomLexer;

impl Lexer for MyCustomLexer {
    fn tokenize(&self, content: &str) -> Result<Vec<Token>, AamlError> {
        // Your tokenization logic
        todo!()
    }
}
```

### Custom Parser

Implement the `Parser` trait:

```rust
use aam_rs::pipeline::{Parser, Token, AstNode};
use crate::error::AamlError;

struct MyCustomParser;

impl Parser for MyCustomParser {
    fn parse(&self, tokens: Vec<Token>) -> Result<Vec<AstNode>, AamlError> {
        // Your parsing logic
        todo!()
    }
}
```

### Custom Validator

Implement the `Validator` trait:

```rust
use aam_rs::pipeline::{Validator, AstNode};
use crate::error::AamlError;

struct MyCustomValidator;

impl Validator for MyCustomValidator {
    fn validate(&self, ast: &[AstNode]) -> Result<(), AamlError> {
        // Your validation logic
        todo!()
    }
}
```

### Custom Executer

Implement the `Executer` trait:

```rust
use aam_rs::pipeline::{Executer, AstNode, PipelineOutput};
use crate::error::AamlError;

struct MyCustomExecuter;

impl Executer for MyCustomExecuter {
    fn execute(&self, ast: Vec<AstNode>) -> Result<PipelineOutput, AamlError> {
        // Your execution logic
        todo!()
    }
}
```

### Using Custom Stages

The `Pipeline` struct currently uses `Box<dyn Trait>` for dependency injection. To use custom implementations, you would need to make `Pipeline::new()` flexible or create new orchestrator methods. For now, you can instantiate stages independently:

```rust
let lexer = MyCustomLexer;
let tokens = lexer.tokenize(content)?;

let parser = MyCustomParser;
let ast = parser.parse(tokens)?;

let validator = MyCustomValidator;
validator.validate(&ast)?;

let executer = MyCustomExecuter;
let output = executer.execute(ast)?;
```

## Testing

Each stage has independent unit tests:

```bash
# Run all pipeline tests
cargo test pipeline::

# Run specific stage tests
cargo test pipeline::lexer::
cargo test pipeline::parser::
cargo test pipeline::scope_manager::
cargo test pipeline::validator::
cargo test pipeline::executer::
```

Integration tests verify end-to-end behavior:

```bash
# Run all integration tests (existing v1 tests still pass)
cargo test --test '*'
```

## Performance Considerations

The pipeline adds a small overhead by introducing an intermediate AST representation:

- **Lexer:** O(n) single pass
- **Parser:** O(n) token consumption
- **Validator:** O(n) AST traversal
- **Executer:** O(n) AST traversal + directive execution

**Total:** O(n) overall, comparable to the original monolithic approach.

For large files, the AST is memory-efficient (enum variants are small). Stress tests with the `standard_stress.rs` example verify acceptable performance.

## Migration Guide (For Contributors)

If you're updating existing code:

1. **Parsing logic:** Move to `lexer.rs` (tokenization) or `parser.rs` (AST building)
2. **Validation logic:** Move to `validator.rs` (semantic checks)
3. **Directive execution:** Move to `executer.rs` (command handlers in `src/commands/`)
4. **Query API:** Keep in `src/aaml/lookup.rs` (unchanged)
5. **Type registration:** Remains in `src/aaml/types_registry.rs` (unchanged)

## FAQ

**Q: Is the old monolithic approach still available?**
A: No, internally everything uses the pipeline. But the public `AAML` API remains unchanged, so user code is unaffected.

**Q: Can I mix custom and default stages?**
A: Yes, you can instantiate individual stages and chain them manually. See "Using Custom Stages" above.

**Q: Where are the command handlers (@import, @schema, etc.) implemented?**
A: In `src/commands/` (unchanged from v1). They're registered in `AAML::register_default_commands()` and invoked by the Executer.

**Q: How do I add a new builtin type?**
A: Implement the `Type` trait in `src/types/` and register it in `resolve_builtin()` (unchanged from v1).

**Q: Why separate Parser and ScopeManager?**
A: `ScopeManager` is a helper for tracking syntactic nesting. It could be internal to the Parser, but separating it allows for clearer testing and potential reuse.

## Related Files

- **Pipeline module:** `src/pipeline/`
- **AAML facade:** `src/aaml/mod.rs`
- **Error types:** `src/error.rs`
- **Commands:** `src/commands/`
- **Types:** `src/types/`
- **Integration tests:** `tests/`