aam-rs 2.1.0

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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
//! Error types for the AAML parser and validation pipeline with beautiful colored output.

use colored::Colorize;
use std::cell::RefCell;
use std::fmt;
use std::io;

#[derive(Debug, Clone)]
pub(crate) struct ErrorRenderContext {
    path: String,
    source: String,
}

thread_local! {
    static ERROR_RENDER_CONTEXT: RefCell<ErrorRenderContext> = RefCell::new(ErrorRenderContext {
        path: "<raw_string>".to_string(),
        source: String::new(),
    });
}

pub(crate) struct ErrorRenderContextGuard {
    previous: ErrorRenderContext,
}

impl Drop for ErrorRenderContextGuard {
    fn drop(&mut self) {
        let previous = self.previous.clone();
        ERROR_RENDER_CONTEXT.with(|ctx| {
            *ctx.borrow_mut() = previous;
        });
    }
}

pub fn set_error_render_context(path: impl Into<String>, source: impl Into<String>) {
    let path = path.into();
    let source = source.into();
    ERROR_RENDER_CONTEXT.with(|ctx| {
        let mut ctx_mut = ctx.borrow_mut();
        ctx_mut.path = path;
        ctx_mut.source = source;
    });
}

pub(crate) fn push_error_render_context(
    path: impl Into<String>,
    source: impl Into<String>,
) -> ErrorRenderContextGuard {
    let previous = get_error_render_context();
    set_error_render_context(path, source);
    ErrorRenderContextGuard { previous }
}

fn get_error_render_context() -> ErrorRenderContext {
    ERROR_RENDER_CONTEXT.with(|ctx| ctx.borrow().clone())
}

fn source_line(source: &str, line: usize) -> Option<&str> {
    if line == 0 {
        return None;
    }
    source.lines().nth(line - 1)
}

fn type_alias_line_info(source: &str, alias_name: &str) -> Option<(usize, String, usize)> {
    for (idx, raw) in source.lines().enumerate() {
        let line_num = idx + 1;
        let trimmed = raw.trim_start();
        if !trimmed.starts_with("@type") {
            continue;
        }

        let rest = trimmed.trim_start_matches("@type").trim_start();
        let Some((lhs, _rhs)) = rest.split_once('=') else {
            continue;
        };
        if lhs.trim() != alias_name {
            continue;
        }

        let col = raw.find(alias_name).map(|p| p + 1).unwrap_or(1);
        return Some((line_num, raw.to_string(), col));
    }
    None
}

/// Error diagnostics with "What", "Why", and "Fix" guidance (inspired by Cargo).
#[derive(Debug, Clone)]
pub struct ErrorDiagnostics {
    /// What went wrong (short title).
    pub what: String,
    /// Why it happened (detailed explanation).
    pub why: String,
    /// How to fix it (suggested resolution).
    pub fix: String,
}

impl ErrorDiagnostics {
    /// Create new diagnostics.
    pub fn new(what: impl Into<String>, why: impl Into<String>, fix: impl Into<String>) -> Self {
        Self {
            what: what.into(),
            why: why.into(),
            fix: fix.into(),
        }
    }

    /// Pretty-print with colors (like Cargo).
    pub fn pretty_print(&self) -> String {
        format!(
            "{}\n{}\n\n{}\n{}\n\n{}\n{}\n",
            "error".red().bold(),
            format!("  {}", self.what).red(),
            "why".cyan().bold(),
            format!("  {}", self.why).cyan(),
            "fix".green().bold(),
            format!("  {}", self.fix).green(),
        )
    }
}

/// All errors that can be produced while parsing or validating an AAML document.
#[derive(Debug)]
pub enum AamlError {
    /// An I/O error occurred while reading a file.
    IoError {
        details: String,
        diagnostics: Option<ErrorDiagnostics>,
    },

    /// A line could not be parsed as a valid AAML statement.
    ParseError {
        /// 1-based line number in the source file.
        line: usize,
        /// Raw content of the offending line.
        content: String,
        /// Human-readable explanation of why parsing failed.
        details: String,
        /// Diagnostic guidance.
        diagnostics: Option<ErrorDiagnostics>,
    },

    /// A key or type name was not found in the registry or map.
    NotFound {
        key: String,
        context: String,
        diagnostics: Option<ErrorDiagnostics>,
    },

    /// A value does not satisfy a basic type constraint (not schema-specific).
    InvalidValue {
        details: String,
        expected: String,
        diagnostics: Option<ErrorDiagnostics>,
    },

    /// A value failed validation against a registered or built-in type.
    InvalidType {
        /// Name of the type that rejected the value.
        type_name: String,
        /// Details from the type validator.
        details: String,
        /// What was provided.
        provided: String,
        /// Diagnostic guidance.
        diagnostics: Option<ErrorDiagnostics>,
    },

    /// A directive (`@import`, `@derive`, …) encountered an error in its arguments.
    DirectiveError {
        directive: String,
        message: String,
        diagnostics: Option<ErrorDiagnostics>,
    },

    /// A schema constraint was violated during parsing or explicit validation.
    SchemaValidationError {
        /// Name of the schema that declared the field.
        schema: String,
        /// Name of the field that failed validation.
        field: String,
        /// Declared type of the field.
        type_name: String,
        /// Human-readable description of the failure.
        details: String,
        /// Diagnostic guidance.
        diagnostics: Option<ErrorDiagnostics>,
    },

    /// Missing required field in schema.
    MissingRequiredField {
        schema: String,
        field: String,
        field_type: String,
        diagnostics: Option<ErrorDiagnostics>,
    },

    /// Circular dependency detected.
    CircularDependency {
        path: String,
        diagnostics: Option<ErrorDiagnostics>,
    },

    /// Type registration conflict.
    TypeRegistrationConflict {
        type_name: String,
        existing: String,
        new: String,
        diagnostics: Option<ErrorDiagnostics>,
    },

    /// Nesting depth exceeded (possible infinite loop).
    NestingDepthExceeded {
        depth: usize,
        context: String,
        diagnostics: Option<ErrorDiagnostics>,
    },

    /// Malformed inline object or array literal.
    MalformedLiteral {
        literal_type: String,
        content: String,
        diagnostics: Option<ErrorDiagnostics>,
    },

    /// Directive syntax is incorrect.
    DirectiveSyntaxError {
        directive: String,
        provided_syntax: String,
        expected_syntax: String,
        diagnostics: Option<ErrorDiagnostics>,
    },

    /// Type conversion failed.
    TypeConversionError {
        from_type: String,
        to_type: String,
        value: String,
        diagnostics: Option<ErrorDiagnostics>,
    },

    /// Lexical analysis error (invalid character or token).
    LexError {
        /// Line number where the error occurred
        line: usize,
        /// Column number where the error occurred
        column: usize,
        /// The invalid character
        character: String,
        /// Diagnostic guidance
        diagnostics: Option<ErrorDiagnostics>,
    },
}

/// Backward-compatible alias used by some bindings.
pub type AamError = AamlError;

impl AamlError {
    fn code(&self) -> &'static str {
        match self {
            AamlError::CircularDependency { .. } => "E001",
            AamlError::ParseError { .. } => "E002",
            AamlError::InvalidType { .. } => "E003",
            AamlError::SchemaValidationError { .. } => "E004",
            AamlError::MissingRequiredField { .. } => "E005",
            AamlError::NotFound { .. } => "E006",
            AamlError::DirectiveError { .. } => "E007",
            AamlError::DirectiveSyntaxError { .. } => "E008",
            AamlError::MalformedLiteral { .. } => "E009",
            AamlError::TypeRegistrationConflict { .. } => "E010",
            AamlError::TypeConversionError { .. } => "E011",
            AamlError::InvalidValue { .. } => "E012",
            AamlError::NestingDepthExceeded { .. } => "E013",
            AamlError::LexError { .. } => "E014",
            AamlError::IoError { .. } => "E015",
        }
    }

    fn title(&self) -> &'static str {
        match self {
            AamlError::CircularDependency { .. } => "cyclic dependency detected",
            AamlError::ParseError { .. } => "parse error",
            AamlError::InvalidType { .. } => "type validation failed",
            AamlError::SchemaValidationError { .. } => "schema validation failed",
            AamlError::MissingRequiredField { .. } => "missing required field",
            AamlError::NotFound { .. } => "entry not found",
            AamlError::DirectiveError { .. } => "directive execution failed",
            AamlError::DirectiveSyntaxError { .. } => "directive syntax error",
            AamlError::MalformedLiteral { .. } => "malformed literal",
            AamlError::TypeRegistrationConflict { .. } => "type registration conflict",
            AamlError::TypeConversionError { .. } => "type conversion failed",
            AamlError::InvalidValue { .. } => "invalid value",
            AamlError::NestingDepthExceeded { .. } => "nesting depth exceeded",
            AamlError::LexError { .. } => "lexical analysis failed",
            AamlError::IoError { .. } => "I/O operation failed",
        }
    }

    fn default_help(&self) -> &'static str {
        match self {
            AamlError::CircularDependency { .. } => {
                "types in AAM must be acyclic. Consider using a primitive type or breaking the loop."
            }
            AamlError::ParseError { .. } => {
                "check assignment/directive syntax near the highlighted line."
            }
            AamlError::InvalidType { .. } => {
                "ensure the value matches the declared type or update the type declaration."
            }
            AamlError::SchemaValidationError { .. } | AamlError::MissingRequiredField { .. } => {
                "fill required fields and ensure each field value matches its declared type."
            }
            AamlError::NotFound { .. } => {
                "verify the referenced key/type/schema exists and is in scope."
            }
            AamlError::DirectiveError { .. } | AamlError::DirectiveSyntaxError { .. } => {
                "check directive name and argument format."
            }
            AamlError::MalformedLiteral { .. } => {
                "ensure object/list literals are balanced and well-formed."
            }
            AamlError::TypeRegistrationConflict { .. } => {
                "rename the type or remove duplicate @type declarations."
            }
            AamlError::TypeConversionError { .. } => {
                "provide a value that can be converted to the requested type."
            }
            AamlError::InvalidValue { .. } => "provide a value in the expected format.",
            AamlError::NestingDepthExceeded { .. } => {
                "reduce recursion depth or split nested data."
            }
            AamlError::LexError { .. } => "remove or replace unsupported characters.",
            AamlError::IoError { .. } => "check file path and permissions.",
        }
    }

    fn render_compiler_style(&self) -> String {
        let ctx = get_error_render_context();
        let mut out = String::new();
        out.push_str(&format!(
            "{}[{}]: {}\n",
            "error".red().bold(),
            self.code().red().bold(),
            self.title().bold()
        ));

        match self {
            AamlError::CircularDependency { path, .. } => {
                let nodes: Vec<String> = path
                    .split("->")
                    .map(str::trim)
                    .filter(|s| !s.is_empty())
                    .map(ToString::to_string)
                    .collect();
                let cycle_start = nodes
                    .first()
                    .cloned()
                    .unwrap_or_else(|| "unknown".to_string());
                let chain = if nodes.is_empty() {
                    path.to_string()
                } else {
                    nodes.join(" -> ")
                };

                let first_alias = nodes.first().cloned().unwrap_or_else(|| "?".to_string());
                let first_loc = type_alias_line_info(&ctx.source, &first_alias);

                if let Some((line, _, col)) = first_loc {
                    out.push_str(&format!(
                        " {} {}:{}:{}\n",
                        "-->".blue().bold(),
                        ctx.path,
                        line,
                        col
                    ));
                } else {
                    out.push_str(&format!(" {} {}:?:?\n", "-->".blue().bold(), ctx.path));
                }
                out.push_str(&format!(" {}\n", "|".blue().bold()));

                for (idx, alias) in nodes.iter().enumerate() {
                    if let Some((line, src, col)) = type_alias_line_info(&ctx.source, alias) {
                        out.push_str(&format!(
                            " {} {} {}\n",
                            line.to_string().blue().bold(),
                            "|".blue().bold(),
                            src
                        ));
                        let marker = if idx == 0 {
                            "cycle starts here"
                        } else if idx == nodes.len().saturating_sub(1) {
                            "cycle closes here"
                        } else {
                            "part of cycle"
                        };
                        out.push_str(&format!(
                            " {} {}{} {}\n",
                            "|".blue().bold(),
                            " ".repeat(col.saturating_sub(1)),
                            "^".red().bold(),
                            marker
                        ));
                    }
                }

                out.push_str(&format!(" {}\n", "|".blue().bold()));
                out.push_str(&format!(
                    " {} {} {}\n",
                    "=".blue().bold(),
                    "cycle:".bold(),
                    chain
                ));
                out.push_str(&format!(
                    " {} returns to '{}'\n",
                    "=".blue().bold(),
                    cycle_start
                ));
            }
            AamlError::ParseError {
                line,
                content,
                details,
                ..
            } => {
                out.push_str(&format!(
                    " {} {}:{}:{}\n",
                    "-->".blue().bold(),
                    ctx.path,
                    line,
                    1
                ));
                out.push_str(&format!(" {}\n", "|".blue().bold()));
                let display_line = source_line(&ctx.source, *line).unwrap_or(content.as_str());
                let caret_col = display_line
                    .find(content.trim())
                    .map(|v| v + 1)
                    .unwrap_or(1);
                out.push_str(&format!(
                    " {} {} {}\n",
                    line.to_string().blue().bold(),
                    "|".blue().bold(),
                    display_line
                ));
                out.push_str(&format!(
                    " {} {} {}\n",
                    "|".blue().bold(),
                    "^".red().bold(),
                    details
                ));
                out.push_str(&format!(
                    " {} {}{}\n",
                    "|".blue().bold(),
                    " ".repeat(caret_col.saturating_sub(1)),
                    "^-- here".red().bold()
                ));
            }
            AamlError::LexError {
                line,
                column,
                character,
                ..
            } => {
                out.push_str(&format!(
                    " {} {}:{}:{}\n",
                    "-->".blue().bold(),
                    ctx.path,
                    line,
                    column
                ));
                if let Some(src) = source_line(&ctx.source, *line) {
                    out.push_str(&format!(
                        " {} {} {}\n",
                        line.to_string().blue().bold(),
                        "|".blue().bold(),
                        src
                    ));
                    out.push_str(&format!(
                        " {} {}{} invalid character '{}'\n",
                        "|".blue().bold(),
                        " ".repeat(column.saturating_sub(1)),
                        "^--".red().bold(),
                        character
                    ));
                } else {
                    out.push_str(&format!(
                        " {} invalid character '{}'\n",
                        "|".blue().bold(),
                        character
                    ));
                }
            }
            _ => {
                out.push_str(&format!(" {} {}:?:?\n", "-->".blue().bold(), ctx.path));
                out.push_str(&format!(
                    " {} {}\n",
                    "|".blue().bold(),
                    self.short_message()
                ));
            }
        }

        if let Some(diag) = self.diagnostics() {
            out.push_str(&format!(" {}\n", "|".blue().bold()));
            out.push_str(&format!(" {} {}\n", "help:".green().bold(), diag.fix));
        } else {
            out.push_str(&format!(" {}\n", "|".blue().bold()));
            out.push_str(&format!(
                " {} {}\n",
                "help:".green().bold(),
                self.default_help()
            ));
        }

        out
    }

    /// Get the primary error message (short form).
    pub fn short_message(&self) -> String {
        match self {
            AamlError::IoError { details, .. } => format!("IO error: {}", details),
            AamlError::ParseError {
                line,
                content,
                details,
                ..
            } => {
                format!("Parse error at line {}: {} ({})", line, content, details)
            }
            AamlError::NotFound { key, context, .. } => {
                format!("Key '{}' not found ({})", key, context)
            }
            AamlError::InvalidValue {
                details, expected, ..
            } => {
                format!("Invalid value: {} (expected: {})", details, expected)
            }
            AamlError::InvalidType {
                type_name,
                provided,
                details,
                ..
            } => {
                format!(
                    "Invalid type '{}': {} (got: {})",
                    type_name, details, provided
                )
            }
            AamlError::DirectiveError {
                directive, message, ..
            } => {
                format!("Directive '@{}' error: {}", directive, message)
            }
            AamlError::SchemaValidationError {
                schema,
                field,
                type_name,
                details,
                ..
            } => {
                format!(
                    "Schema '{}' field '{}' ({}): {}",
                    schema, field, type_name, details
                )
            }
            AamlError::MissingRequiredField {
                schema,
                field,
                field_type,
                ..
            } => {
                format!(
                    "Missing required field '{}' in schema '{}' (type: {})",
                    field, schema, field_type
                )
            }
            AamlError::CircularDependency { path, .. } => {
                format!("Circular dependency detected: {}", path)
            }
            AamlError::TypeRegistrationConflict {
                type_name,
                existing,
                new,
                ..
            } => {
                format!(
                    "Type '{}' already defined as '{}', cannot redefine as '{}'",
                    type_name, existing, new
                )
            }
            AamlError::NestingDepthExceeded { depth, context, .. } => {
                format!("Nesting depth exceeded ({}): {}", depth, context)
            }
            AamlError::MalformedLiteral {
                literal_type,
                content,
                ..
            } => {
                format!("Malformed {} literal: {}", literal_type, content)
            }
            AamlError::DirectiveSyntaxError {
                directive,
                provided_syntax,
                expected_syntax,
                ..
            } => {
                format!(
                    "Directive '@{}' syntax error: got '{}', expected '{}'",
                    directive, provided_syntax, expected_syntax
                )
            }
            AamlError::TypeConversionError {
                from_type,
                to_type,
                value,
                ..
            } => {
                format!(
                    "Cannot convert '{}' from {} to {}",
                    value, from_type, to_type
                )
            }
            AamlError::LexError {
                line,
                column,
                character,
                ..
            } => {
                format!(
                    "Lexical error at {}:{}: invalid character '{}'",
                    line, column, character
                )
            }
        }
    }

    /// Get the detailed diagnostics if available.
    pub fn diagnostics(&self) -> Option<&ErrorDiagnostics> {
        match self {
            AamlError::IoError { diagnostics, .. } => diagnostics.as_ref(),
            AamlError::ParseError { diagnostics, .. } => diagnostics.as_ref(),
            AamlError::NotFound { diagnostics, .. } => diagnostics.as_ref(),
            AamlError::InvalidValue { diagnostics, .. } => diagnostics.as_ref(),
            AamlError::InvalidType { diagnostics, .. } => diagnostics.as_ref(),
            AamlError::DirectiveError { diagnostics, .. } => diagnostics.as_ref(),
            AamlError::SchemaValidationError { diagnostics, .. } => diagnostics.as_ref(),
            AamlError::MissingRequiredField { diagnostics, .. } => diagnostics.as_ref(),
            AamlError::CircularDependency { diagnostics, .. } => diagnostics.as_ref(),
            AamlError::TypeRegistrationConflict { diagnostics, .. } => diagnostics.as_ref(),
            AamlError::NestingDepthExceeded { diagnostics, .. } => diagnostics.as_ref(),
            AamlError::MalformedLiteral { diagnostics, .. } => diagnostics.as_ref(),
            AamlError::DirectiveSyntaxError { diagnostics, .. } => diagnostics.as_ref(),
            AamlError::TypeConversionError { diagnostics, .. } => diagnostics.as_ref(),
            AamlError::LexError { diagnostics, .. } => diagnostics.as_ref(),
        }
    }
}

impl fmt::Display for AamlError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.render_compiler_style())
    }
}

impl std::error::Error for AamlError {}

impl From<io::Error> for AamlError {
    fn from(err: io::Error) -> Self {
        let details = err.to_string();
        let diagnostics = Some(ErrorDiagnostics::new(
            "I/O operation failed",
            format!("Could not read or write file: {}", details),
            "Check file permissions and ensure the path exists",
        ));
        AamlError::IoError {
            details,
            diagnostics,
        }
    }
}