aam-rs 2.0.3

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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
//! Task enums and lazy evaluation structures for Command Pattern implementation.
//!
//! This module defines the declarative task types that replace direct AAML mutations.
//! Tasks are generated by Validator, Parser, and other stages, then executed by
//! dedicated executors (ValidateExecutor, ParserExecutor, Executer).

use crate::pipeline::parser::ValueNode;

/// A declarative validation task generated by the Validator.
///
/// Validation tasks represent specific checks that need to be performed on AST nodes.
/// They are generated during the validation phase and executed by `ValidateExecutor`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValidationTask<'a> {
    /// Check if a value matches a registered type's constraints.
    ///
    /// # Fields
    /// - `key`: The configuration key being validated
    /// - `value`: The value to validate
    /// - `type_name`: Name of the type to validate against (e.g., "i32", "string", "vector2")
    /// - `line`: Source line number for diagnostics
    CheckTypeMatch {
        key: std::borrow::Cow<'a, str>,
        value: std::borrow::Cow<'a, str>,
        type_name: std::borrow::Cow<'a, str>,
        line: usize,
    },

    /// Verify that a schema referenced in the configuration is defined.
    ///
    /// # Fields
    /// - `schema_name`: Name of the schema to check
    /// - `line`: Source line number
    VerifySchemaExists {
        schema_name: std::borrow::Cow<'a, str>,
        line: usize,
    },

    /// Verify that a file referenced by an import directive exists.
    ///
    /// # Fields
    /// - `path`: Path to the file
    /// - `line`: Source line number
    VerifyFileExists {
        path: std::borrow::Cow<'a, str>,
        line: usize,
    },

    /// Validate that an assignment complies with a registered schema.
    ///
    /// # Fields
    /// - `schema_name`: Name of the schema to validate against
    /// - `key`: Key being validated
    /// - `value`: Value being validated
    /// - `line`: Source line number
    ValidateAgainstSchema {
        schema_name: std::borrow::Cow<'a, str>,
        key: std::borrow::Cow<'a, str>,
        value: std::borrow::Cow<'a, str>,
        line: usize,
    },

    /// Check that all required fields of a schema are present.
    ///
    /// # Fields
    /// - `schema_name`: Schema name
    /// - `missing_fields`: Required fields not found
    /// - `line`: Source line number
    CheckSchemaCompleteness {
        schema_name: std::borrow::Cow<'a, str>,
        missing_fields: Vec<std::borrow::Cow<'a, str>>,
        line: usize,
    },

    /// Verify no circular references in lookup chains.
    ///
    /// # Fields
    /// - `key`: Key being looked up
    /// - `line`: Source line number
    CheckNoCircularReference {
        key: std::borrow::Cow<'a, str>,
        line: usize,
    },

    /// Verify that an object deriving from schemas implements all required fields.
    ///
    /// # Fields
    /// - `derive_path`: Derivation path (file.aam::Schema1::Schema2)
    /// - `current_key`: The context key doing the derivation
    /// - `line`: Source line number
    CheckDeriveCompleteness {
        derive_path: std::borrow::Cow<'a, str>,
        current_key: std::borrow::Cow<'a, str>,
        line: usize,
    },

    /// Validate an inline list matches expected element types.
    ///
    /// # Fields
    /// - `key`: Configuration key
    /// - `items`: List items as strings
    /// - `element_type`: Expected type of each element
    /// - `line`: Source line number
    ValidateListElements {
        key: std::borrow::Cow<'a, str>,
        items: std::sync::Arc<[ValueNode<'a>]>,
        element_type: std::borrow::Cow<'a, str>,
        line: usize,
    },

    /// Validate an inline object's keys and values.
    ///
    /// # Fields
    /// - `key`: Configuration key
    /// - `pairs`: Key-value pairs in the object
    /// - `line`: Source line number
    ValidateObjectStructure {
        key: std::borrow::Cow<'a, str>,
        pairs: std::sync::Arc<[(std::borrow::Cow<'a, str>, ValueNode<'a>)]>,
        line: usize,
    },
}

impl<'a> ValidationTask<'a> {
    /// Returns the line number associated with this task for error reporting.
    pub fn line(&self) -> usize {
        match self {
            ValidationTask::CheckTypeMatch { line, .. } => *line,
            ValidationTask::VerifySchemaExists { line, .. } => *line,
            ValidationTask::VerifyFileExists { line, .. } => *line,
            ValidationTask::ValidateAgainstSchema { line, .. } => *line,
            ValidationTask::CheckSchemaCompleteness { line, .. } => *line,
            ValidationTask::CheckDeriveCompleteness { line, .. } => *line,
            ValidationTask::CheckNoCircularReference { line, .. } => *line,
            ValidationTask::ValidateListElements { line, .. } => *line,
            ValidationTask::ValidateObjectStructure { line, .. } => *line,
        }
    }

    /// Returns a human-readable description of this task.
    pub fn description(&self) -> String {
        match self {
            ValidationTask::CheckTypeMatch { type_name, .. } => {
                format!("Check type match against '{}'", type_name)
            }
            ValidationTask::VerifySchemaExists { schema_name, .. } => {
                format!("Verify schema '{}' exists", schema_name)
            }
            ValidationTask::VerifyFileExists { path, .. } => {
                format!("Verify file '{}' exists", path)
            }
            ValidationTask::ValidateAgainstSchema { schema_name, .. } => {
                format!("Validate against schema '{}'", schema_name)
            }
            ValidationTask::CheckSchemaCompleteness { schema_name, .. } => {
                format!("Check completeness of schema '{}'", schema_name)
            }
            ValidationTask::CheckDeriveCompleteness { derive_path, .. } => {
                format!("Check derive completeness for '{}'", derive_path)
            }
            ValidationTask::CheckNoCircularReference { .. } => {
                "Check for circular references".to_string()
            }
            ValidationTask::ValidateListElements { element_type, .. } => {
                format!("Validate list elements are type '{}'", element_type)
            }
            ValidationTask::ValidateObjectStructure { .. } => {
                "Validate inline object structure".to_string()
            }
        }
    }
}

/// A declarative parsing task generated by the Parser.
///
/// Parse tasks represent operations that need to be performed on parsed modules,
/// variables, and scopes. They enable deferred processing and analysis.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ParseTask<'a> {
    /// Resolve a module reference in a scope.
    ///
    /// # Fields
    /// - `module_name`: Name of the module to resolve
    /// - `scope`: Current scope path
    /// - `line`: Source line number
    ResolveModuleReference {
        module_name: std::borrow::Cow<'a, str>,
        scope: std::borrow::Cow<'a, str>,
        line: usize,
    },

    /// Resolve an imported file and apply its types and schemas to the context.
    ///
    /// # Fields
    /// - `derive_path`: Raw derive path (e.g. file.aam::SchemaName)
    /// - `line`: Source line number
    ResolveDeriveImport {
        derive_path: std::borrow::Cow<'a, str>,
        line: usize,
    },

    /// Process variable assignments in a scope.
    ///
    /// # Fields
    /// - `variable_name`: Name of the variable
    /// - `value`: Variable value
    /// - `scope`: Scope path
    /// - `line`: Source line number
    ProcessVariable {
        variable_name: std::borrow::Cow<'a, str>,
        value: std::borrow::Cow<'a, str>,
        scope: std::borrow::Cow<'a, str>,
        line: usize,
    },

    /// Manage scope lifecycle (entry/exit).
    ///
    /// # Fields
    /// - `scope`: Scope path
    /// - `is_entry`: true for scope entry, false for exit
    /// - `line`: Source line number
    ManageScope {
        scope: std::borrow::Cow<'a, str>,
        is_entry: bool,
        line: usize,
    },

    /// Execute a directive (e.g., @import, @derive).
    ///
    /// # Fields
    /// - `directive_name`: Name of the directive
    /// - `arguments`: Directive arguments
    /// - `line`: Source line number
    ExecuteDirective {
        directive_name: std::borrow::Cow<'a, str>,
        arguments: std::borrow::Cow<'a, str>,
        line: usize,
    },

    /// Register a type definition from @type directive.
    ///
    /// # Fields
    /// - `type_name`: Name of the type being registered
    /// - `type_spec`: Type specification
    /// - `line`: Source line number
    RegisterType {
        type_name: std::borrow::Cow<'a, str>,
        type_spec: std::borrow::Cow<'a, str>,
        line: usize,
    },

    /// Register a schema definition from @schema directive.
    ///
    /// # Fields
    /// - `schema_name`: Name of the schema
    /// - `fields`: Field definitions
    /// - `line`: Source line number
    RegisterSchema {
        schema_name: std::borrow::Cow<'a, str>,
        fields: std::borrow::Cow<'a, str>,
        line: usize,
    },
}

impl<'a> ParseTask<'a> {
    /// Returns the line number associated with this task.
    pub fn line(&self) -> usize {
        match self {
            ParseTask::ResolveModuleReference { line, .. } => *line,
            ParseTask::ResolveDeriveImport { line, .. } => *line,
            ParseTask::ProcessVariable { line, .. } => *line,
            ParseTask::ManageScope { line, .. } => *line,
            ParseTask::ExecuteDirective { line, .. } => *line,
            ParseTask::RegisterType { line, .. } => *line,
            ParseTask::RegisterSchema { line, .. } => *line,
        }
    }

    /// Returns a human-readable description.
    pub fn description(&self) -> String {
        match self {
            ParseTask::ResolveModuleReference { module_name, .. } => {
                format!("Resolve module reference '{}'", module_name)
            }
            ParseTask::ResolveDeriveImport { derive_path, .. } => {
                format!("Resolve derive import '{}'", derive_path)
            }
            ParseTask::ProcessVariable { variable_name, .. } => {
                format!("Process variable '{}'", variable_name)
            }
            ParseTask::ManageScope {
                scope, is_entry, ..
            } => {
                let action = if *is_entry { "Enter" } else { "Exit" };
                format!("{} scope '{}'", action, scope)
            }
            ParseTask::ExecuteDirective { directive_name, .. } => {
                format!("Execute directive '@{}'", directive_name)
            }
            ParseTask::RegisterType { type_name, .. } => {
                format!("Register type '{}'", type_name)
            }
            ParseTask::RegisterSchema { schema_name, .. } => {
                format!("Register schema '{}'", schema_name)
            }
        }
    }

    /// Performs checks that do not require mutable execution context.
    pub fn validate_stateless(&self) -> Result<(), TaskError> {
        if let ParseTask::ExecuteDirective {
            directive_name,
            line,
            ..
        } = self
            && !matches!(directive_name.as_ref(), "import" | "derive")
        {
            return Err(TaskError {
                line: *line,
                message: format!("Unknown directive: @{}", directive_name),
                task_description: self.description(),
                aaml_error: None,
            });
        }

        Ok(())
    }
}

/// A declarative execution task for the final execution phase.
///
/// Execution tasks represent the final operations to be performed to materialize
/// the configuration, independent of AAML struct manipulation.
#[derive(Debug, Clone)]
pub enum ExecutionTask<'a> {
    /// Set a configuration value in the output.
    ///
    /// # Fields
    /// - `key`: Configuration key
    /// - `value`: Value to set
    /// - `line`: Source line number
    SetValue {
        key: std::borrow::Cow<'a, str>,
        value: std::borrow::Cow<'a, str>,
        line: usize,
    },

    /// Merge a value with an existing one (+=).
    ///
    /// # Fields
    /// - `key`: Key to merge
    /// - `value`: Value to merge in
    /// - `line`: Source line number
    MergeValue {
        key: std::borrow::Cow<'a, str>,
        value: std::borrow::Cow<'a, str>,
        line: usize,
    },

    /// Apply schema validation to a subtree.
    ///
    /// # Fields
    /// - `schema_name`: Schema to apply
    /// - `root_keys`: Keys that are part of this schema
    /// - `line`: Source line number
    ApplySchema {
        schema_name: std::borrow::Cow<'a, str>,
        root_keys: Vec<std::borrow::Cow<'a, str>>,
        line: usize,
    },

    /// Execute inheritance from a parent configuration.
    ///
    /// # Fields
    /// - `parent_key`: Parent configuration key
    /// - `child_key`: Child configuration key
    /// - `line`: Source line number
    ExecuteInheritance {
        derive_path: std::borrow::Cow<'a, str>,
        child_key: std::borrow::Cow<'a, str>,
        line: usize,
    },

    /// Import configuration from an external file.
    ///
    /// # Fields
    /// - `file_path`: Path to import
    /// - `merge_strategy`: How to merge ("override" or "merge")
    /// - `line`: Source line number
    ImportFile {
        file_path: std::borrow::Cow<'a, str>,
        merge_strategy: std::borrow::Cow<'a, str>,
        line: usize,
    },

    /// Resolve a reference to another key.
    ///
    /// # Fields
    /// - `source_key`: Key containing the reference
    /// - `target_key`: Key being referenced
    /// - `line`: Source line number
    ResolveReference {
        source_key: std::borrow::Cow<'a, str>,
        target_key: std::borrow::Cow<'a, str>,
        line: usize,
    },
}

impl<'a> ExecutionTask<'a> {
    /// Returns the line number associated with this task.
    pub fn line(&self) -> usize {
        match self {
            ExecutionTask::SetValue { line, .. } => *line,
            ExecutionTask::MergeValue { line, .. } => *line,
            ExecutionTask::ApplySchema { line, .. } => *line,
            ExecutionTask::ExecuteInheritance { line, .. } => *line,
            ExecutionTask::ImportFile { line, .. } => *line,
            ExecutionTask::ResolveReference { line, .. } => *line,
        }
    }

    /// Returns a human-readable description.
    pub fn description(&self) -> String {
        match self {
            ExecutionTask::SetValue { key, .. } => format!("Set value for key '{}'", key),
            ExecutionTask::MergeValue { key, .. } => format!("Merge value for key '{}'", key),
            ExecutionTask::ApplySchema { schema_name, .. } => {
                format!("Apply schema '{}'", schema_name)
            }
            ExecutionTask::ExecuteInheritance {
                derive_path,
                child_key,
                ..
            } => {
                format!("Execute inheritance: '{}' <- '{}'", child_key, derive_path)
            }
            ExecutionTask::ImportFile { file_path, .. } => {
                format!("Import file '{}'", file_path)
            }
            ExecutionTask::ResolveReference {
                source_key,
                target_key,
                ..
            } => {
                format!("Resolve reference: '{}' -> '{}'", source_key, target_key)
            }
        }
    }
}

/// Result of executing a batch of tasks, with error aggregation support for LSP.
#[derive(Debug, Clone)]
pub struct TaskExecutionResult {
    /// Whether all tasks executed successfully
    pub success: bool,

    /// Collected errors with line/context information
    pub errors: Vec<TaskError>,

    /// Execution statistics
    pub stats: ExecutionStats,
}

/// A single task execution error with full diagnostic context.
#[derive(Debug, Clone)]
pub struct TaskError {
    /// Associated task line number
    pub line: usize,

    /// Error message
    pub message: String,

    /// Task description for context
    pub task_description: String,

    /// AAML error details
    pub aaml_error: Option<String>,
}

/// Execution statistics for performance monitoring.
#[derive(Debug, Clone, Default)]
pub struct ExecutionStats {
    /// Total tasks executed
    pub total_tasks: usize,

    /// Successfully executed tasks
    pub successful_tasks: usize,

    /// Failed tasks
    pub failed_tasks: usize,

    /// Time spent in validation phase (milliseconds)
    pub validation_ms: u64,

    /// Time spent in parsing phase (milliseconds)
    pub parsing_ms: u64,

    /// Time spent in execution phase (milliseconds)
    pub execution_ms: u64,
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::borrow::Cow;

    #[test]
    fn test_validation_task_line_numbers() {
        let task = ValidationTask::CheckTypeMatch {
            key: Cow::from("foo".to_string()),
            value: Cow::from("bar"),
            type_name: Cow::from("string".to_string()),
            line: 42,
        };
        assert_eq!(task.line(), 42);
    }

    #[test]
    fn test_parse_task_description() {
        let task = ParseTask::ExecuteDirective {
            directive_name: Cow::from("import"),
            arguments: Cow::from("base.aam"),
            line: 10,
        };
        assert_eq!(task.description(), "Execute directive '@import'");
    }

    #[test]
    fn test_execution_task_inheritance() {
        let task = ExecutionTask::ExecuteInheritance {
            derive_path: Cow::from("base.aam::Parent"),
            child_key: Cow::from("child"),
            line: 5,
        };
        assert_eq!(
            task.description(),
            "Execute inheritance: 'child' <- 'base.aam::Parent'"
        );
    }
}