horkos 0.2.0

Cloud infrastructure language where insecure code won't compile
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
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
//! Error handling and diagnostics for Horkos.
//!

use crate::ast::Span;
use ariadne::{Color, Label, Report, ReportKind, Source};
use serde::{Deserialize, Serialize};

/// Error codes for all Horkos errors.
///
/// Format: E0XXX where XXX is the error number.
/// Each code has documentation explaining the error.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ErrorCode {
    // Lexer errors (E0001-E0099)
    /// Unexpected character in source
    UnexpectedChar, // E0001
    /// Unterminated string literal
    UnterminatedString, // E0002
    /// Unterminated block comment
    UnterminatedComment, // E0003
    /// Invalid escape sequence
    InvalidEscape, // E0004
    /// Invalid number literal
    InvalidNumber, // E0005

    // Parser errors (E0100-E0199)
    /// Unexpected token
    UnexpectedToken, // E0100
    /// Expected expression
    ExpectedExpression, // E0101
    /// Expected identifier
    ExpectedIdentifier, // E0102
    /// Expected type
    ExpectedType, // E0103
    /// Unclosed delimiter
    UnclosedDelimiter, // E0104

    // Type errors (E0200-E0299)
    /// Type mismatch
    TypeMismatch, // E0200
    /// Undefined variable
    UndefinedVariable, // E0201
    /// Taint violation (Unverified<T> used where T expected)
    TaintViolation, // E0202
    /// Cannot call non-function
    NotCallable, // E0203
    /// Wrong number of arguments
    ArityMismatch, // E0204
    /// Unknown field access
    UnknownField, // E0205
    /// Missing required parameter (conditional requirement)
    MissingRequiredParam, // E0209
    /// Cannot access field on type
    InvalidFieldAccess, // E0206
    /// Operator type error
    InvalidOperator, // E0207
    /// Unknown module
    UnknownModule, // E0208
    /// Compile-time assertion failed
    AssertionFailed, // E0210
    /// Preferred setting overridden in strict mode
    PreferredOverride, // E0211
    /// Security parameter weakened without unsafe
    SecurityViolation, // E0212
    /// Nested unsafe blocks not allowed
    NestedUnsafe, // E0213
    /// Unknown parameter passed to function
    UnknownParameter, // E0214
    /// Shadow banned resource (supported natively)
    ShadowBanned, // E0215

    // Security errors (E0300-E0399)
    /// Tainted value passed to secure context
    TaintedArgument, // E0300
    /// Accessing tainted value outside unsafe
    TaintedAccess, // E0301
    /// Critical port (SSH, RDP, DB) exposed to non-private CIDR
    CriticalPortExposed, // E0302
    /// Port exposed to non-private CIDR
    PortExposed, // E0303

    // Generic
    /// Generic error (fallback)
    Generic, // E9999
}

impl ErrorCode {
    /// Get the numeric code string (e.g., "E0201")
    pub fn code(&self) -> &'static str {
        match self {
            // Lexer
            ErrorCode::UnexpectedChar => "E0001",
            ErrorCode::UnterminatedString => "E0002",
            ErrorCode::UnterminatedComment => "E0003",
            ErrorCode::InvalidEscape => "E0004",
            ErrorCode::InvalidNumber => "E0005",
            // Parser
            ErrorCode::UnexpectedToken => "E0100",
            ErrorCode::ExpectedExpression => "E0101",
            ErrorCode::ExpectedIdentifier => "E0102",
            ErrorCode::ExpectedType => "E0103",
            ErrorCode::UnclosedDelimiter => "E0104",
            // Type
            ErrorCode::TypeMismatch => "E0200",
            ErrorCode::UndefinedVariable => "E0201",
            ErrorCode::TaintViolation => "E0202",
            ErrorCode::NotCallable => "E0203",
            ErrorCode::ArityMismatch => "E0204",
            ErrorCode::UnknownField => "E0205",
            ErrorCode::InvalidFieldAccess => "E0206",
            ErrorCode::InvalidOperator => "E0207",
            ErrorCode::UnknownModule => "E0208",
            ErrorCode::MissingRequiredParam => "E0209",
            ErrorCode::AssertionFailed => "E0210",
            ErrorCode::PreferredOverride => "E0211",
            ErrorCode::SecurityViolation => "E0212",
            ErrorCode::NestedUnsafe => "E0213",
            ErrorCode::UnknownParameter => "E0214",
            ErrorCode::ShadowBanned => "E0215",
            // Security
            ErrorCode::TaintedArgument => "E0300",
            ErrorCode::TaintedAccess => "E0301",
            ErrorCode::CriticalPortExposed => "E0302",
            ErrorCode::PortExposed => "E0303",
            // Generic
            ErrorCode::Generic => "E9999",
        }
    }

    /// Get the error title (short description)
    pub fn title(&self) -> &'static str {
        match self {
            // Lexer
            ErrorCode::UnexpectedChar => "unexpected character",
            ErrorCode::UnterminatedString => "unterminated string literal",
            ErrorCode::UnterminatedComment => "unterminated block comment",
            ErrorCode::InvalidEscape => "invalid escape sequence",
            ErrorCode::InvalidNumber => "invalid number",
            // Parser
            ErrorCode::UnexpectedToken => "unexpected token",
            ErrorCode::ExpectedExpression => "expected expression",
            ErrorCode::ExpectedIdentifier => "expected identifier",
            ErrorCode::ExpectedType => "expected type",
            ErrorCode::UnclosedDelimiter => "unclosed delimiter",
            // Type
            ErrorCode::TypeMismatch => "type mismatch",
            ErrorCode::UndefinedVariable => "undefined variable",
            ErrorCode::TaintViolation => "taint violation",
            ErrorCode::NotCallable => "cannot call non-function",
            ErrorCode::ArityMismatch => "wrong number of arguments",
            ErrorCode::UnknownField => "unknown field",
            ErrorCode::InvalidFieldAccess => "invalid field access",
            ErrorCode::InvalidOperator => "invalid operator for types",
            ErrorCode::UnknownModule => "unknown module",
            ErrorCode::MissingRequiredParam => "missing required parameter",
            ErrorCode::AssertionFailed => "assertion failed",
            ErrorCode::PreferredOverride => "preferred setting overridden",
            ErrorCode::SecurityViolation => "security parameter requires unsafe",
            ErrorCode::NestedUnsafe => "nested unsafe blocks not allowed",
            ErrorCode::UnknownParameter => "unknown parameter",
            ErrorCode::ShadowBanned => "shadow banned resource",
            // Security
            ErrorCode::TaintedArgument => "tainted value in secure context",
            ErrorCode::TaintedAccess => "accessing tainted value outside unsafe",
            ErrorCode::CriticalPortExposed => "critical port exposed to internet",
            ErrorCode::PortExposed => "port exposed to internet",
            // Generic
            ErrorCode::Generic => "error",
        }
    }

    /// Get an explanation note for this error type
    pub fn explanation(&self) -> Option<&'static str> {
        match self {
            ErrorCode::TaintViolation | ErrorCode::TaintedArgument | ErrorCode::TaintedAccess => {
                Some("Unverified<T> wraps imported infrastructure that hasn't been security-audited. \
                      Use unsafe(\"reason\") { ... } to explicitly acknowledge the risk.")
            }
            ErrorCode::UndefinedVariable => {
                Some("Variables must be declared with 'val' before use.")
            }
            ErrorCode::ArityMismatch => {
                Some("Functions must be called with the correct number of arguments.")
            }
            _ => None,
        }
    }
}

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

/// A diagnostic message (error, warning, or info).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Diagnostic {
    pub kind: DiagnosticKind,
    pub code: ErrorCode,
    pub message: String,
    pub span: Option<Span>,
    pub filename: Option<String>,
    pub labels: Vec<DiagnosticLabel>,
    pub notes: Vec<String>,
    pub help: Option<String>,
    pub suggestion: Option<Suggestion>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum DiagnosticKind {
    Error,
    Warning,
    Info,
}

/// A label pointing to a span in the source code.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiagnosticLabel {
    pub span: Span,
    pub message: String,
    pub is_primary: bool,
}

impl DiagnosticLabel {
    /// Create a primary label (the main error location)
    pub fn primary(span: Span, message: impl Into<String>) -> Self {
        Self {
            span,
            message: message.into(),
            is_primary: true,
        }
    }

    /// Create a secondary label (additional context)
    pub fn secondary(span: Span, message: impl Into<String>) -> Self {
        Self {
            span,
            message: message.into(),
            is_primary: false,
        }
    }
}

/// A suggested fix for an error.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Suggestion {
    pub span: Span,
    pub replacement: String,
    pub message: String,
}

impl Diagnostic {
    // === Constructors ===

    /// Create an error with just a message (no location)
    pub fn error(message: impl Into<String>) -> Self {
        Self {
            kind: DiagnosticKind::Error,
            code: ErrorCode::Generic,
            message: message.into(),
            span: None,
            filename: None,
            labels: Vec::new(),
            notes: Vec::new(),
            help: None,
            suggestion: None,
        }
    }

    /// Create an error at a specific location (legacy compatibility)
    pub fn error_at(message: impl Into<String>, span: Span, filename: impl Into<String>) -> Self {
        Self {
            kind: DiagnosticKind::Error,
            code: ErrorCode::Generic,
            message: message.into(),
            span: Some(span),
            filename: Some(filename.into()),
            labels: vec![DiagnosticLabel {
                span,
                message: String::new(),
                is_primary: true,
            }],
            notes: Vec::new(),
            help: None,
            suggestion: None,
        }
    }

    /// Create a warning
    pub fn warning(message: impl Into<String>) -> Self {
        Self {
            kind: DiagnosticKind::Warning,
            code: ErrorCode::Generic,
            message: message.into(),
            span: None,
            filename: None,
            labels: Vec::new(),
            notes: Vec::new(),
            help: None,
            suggestion: None,
        }
    }

    /// Create a warning at a specific location
    pub fn warning_at(message: impl Into<String>, span: Span, filename: impl Into<String>) -> Self {
        Self {
            kind: DiagnosticKind::Warning,
            code: ErrorCode::Generic,
            message: message.into(),
            span: Some(span),
            filename: Some(filename.into()),
            labels: vec![DiagnosticLabel {
                span,
                message: String::new(),
                is_primary: true,
            }],
            notes: Vec::new(),
            help: None,
            suggestion: None,
        }
    }

    // === Builder Methods ===

    /// Set the error code
    pub fn with_code(mut self, code: ErrorCode) -> Self {
        self.code = code;
        // Add automatic explanation note if available
        if let Some(explanation) = code.explanation() {
            if !self.notes.iter().any(|n| n == explanation) {
                self.notes.push(explanation.to_string());
            }
        }
        self
    }

    /// Add a primary label at the error span
    pub fn with_primary_label(mut self, message: impl Into<String>) -> Self {
        if let Some(span) = self.span {
            // Replace existing primary label or add new one
            self.labels.retain(|l| !l.is_primary);
            self.labels.push(DiagnosticLabel::primary(span, message));
        }
        self
    }

    /// Add a secondary label
    pub fn with_label(mut self, span: Span, message: impl Into<String>) -> Self {
        self.labels.push(DiagnosticLabel::secondary(span, message));
        self
    }

    /// Add a note (explanatory text)
    pub fn with_note(mut self, note: impl Into<String>) -> Self {
        self.notes.push(note.into());
        self
    }

    /// Add a help message
    pub fn with_help(mut self, help: impl Into<String>) -> Self {
        self.help = Some(help.into());
        self
    }

    /// Add a suggestion for fixing the error
    pub fn with_suggestion(
        mut self,
        span: Span,
        replacement: impl Into<String>,
        message: impl Into<String>,
    ) -> Self {
        self.suggestion = Some(Suggestion {
            span,
            replacement: replacement.into(),
            message: message.into(),
        });
        self
    }

    // === Rendering ===

    /// Print this diagnostic to stderr using ariadne.
    pub fn print(&self, source: &str) {
        let filename = self.filename.as_deref().unwrap_or("<unknown>");

        let report_kind = match self.kind {
            DiagnosticKind::Error => ReportKind::Custom("error", Color::Red),
            DiagnosticKind::Warning => ReportKind::Custom("warning", Color::Yellow),
            DiagnosticKind::Info => ReportKind::Custom("info", Color::Blue),
        };

        // Format message with error code
        let message = if self.code != ErrorCode::Generic {
            format!("[{}]: {}", self.code.code(), self.message)
        } else {
            self.message.clone()
        };

        // Use the primary label's span for the report offset, or 0 if no labels
        let offset = self
            .labels
            .iter()
            .find(|l| l.is_primary)
            .map(|l| l.span.start as usize)
            .unwrap_or(0);

        let mut builder = Report::build(report_kind, filename, offset).with_message(&message);

        // Add labels
        for label in &self.labels {
            let color = if label.is_primary {
                match self.kind {
                    DiagnosticKind::Error => Color::Red,
                    DiagnosticKind::Warning => Color::Yellow,
                    DiagnosticKind::Info => Color::Blue,
                }
            } else {
                Color::Cyan
            };

            let mut ariadne_label = Label::new((filename, label.span.to_range())).with_color(color);

            if !label.message.is_empty() {
                ariadne_label = ariadne_label.with_message(&label.message);
            }

            builder = builder.with_label(ariadne_label);
        }

        // Add notes
        for note in &self.notes {
            builder = builder.with_note(note);
        }

        // Add help
        if let Some(help) = &self.help {
            builder = builder.with_help(help);
        }

        builder
            .finish()
            .print((filename, Source::from(source)))
            .unwrap();

        // Print suggestion separately if present
        if let Some(suggestion) = &self.suggestion {
            eprintln!("  suggestion: {}", suggestion.message);
            eprintln!("             {}", suggestion.replacement);
        }
    }

    /// Render to string (for testing)
    pub fn to_string_simple(&self) -> String {
        let code = if self.code != ErrorCode::Generic {
            format!("[{}] ", self.code.code())
        } else {
            String::new()
        };
        format!(
            "{}{}: {}",
            match self.kind {
                DiagnosticKind::Error => "error",
                DiagnosticKind::Warning => "warning",
                DiagnosticKind::Info => "info",
            },
            code,
            self.message
        )
    }
}

/// Print multiple diagnostics.
pub fn print_diagnostics(diagnostics: &[Diagnostic], source: &str) {
    for diagnostic in diagnostics {
        diagnostic.print(source);
    }
}

// === Diagnostic Builders for Common Errors ===

/// Builder for common error patterns.
pub struct DiagnosticBuilder;

impl DiagnosticBuilder {
    // === Type Errors ===

    /// Type mismatch error with detailed context
    pub fn type_mismatch(expected: &str, found: &str, span: Span, filename: &str) -> Diagnostic {
        // Special case for Tags
        if expected == "Tags" {
            return Diagnostic::error_at("tag values must be strings".to_string(), span, filename)
                .with_code(ErrorCode::TypeMismatch)
                .with_primary_label("contains non-string value")
                .with_help("AWS tags require all values to be strings, e.g. { count: \"42\" }");
        }

        Diagnostic::error_at(
            format!("expected `{}`, found `{}`", expected, found),
            span,
            filename,
        )
        .with_code(ErrorCode::TypeMismatch)
        .with_primary_label(format!("expected `{}`", expected))
    }

    /// Undefined variable with optional "did you mean" suggestion
    pub fn undefined_variable(
        name: &str,
        span: Span,
        filename: &str,
        similar: Option<&str>,
    ) -> Diagnostic {
        let mut diag = Diagnostic::error_at(
            format!("cannot find variable `{}` in this scope", name),
            span,
            filename,
        )
        .with_code(ErrorCode::UndefinedVariable)
        .with_primary_label("not found in this scope");

        if let Some(similar_name) = similar {
            diag = diag.with_help(format!("did you mean `{}`?", similar_name));
        }

        diag
    }

    /// Taint violation: using Unverified<T> where T is expected
    pub fn taint_violation(
        tainted_type: &str,
        expected_type: &str,
        span: Span,
        filename: &str,
    ) -> Diagnostic {
        Diagnostic::error_at(
            format!(
                "cannot use `{}` where `{}` is expected",
                tainted_type, expected_type
            ),
            span,
            filename,
        )
        .with_code(ErrorCode::TaintViolation)
        .with_primary_label(format!("this has type `{}`", tainted_type))
        .with_help("wrap the operation in an unsafe block:\n\n    unsafe(\"TICKET-XXX: reason\") {\n        // your code here\n    }")
    }

    /// Tainted argument passed to secure function
    pub fn tainted_argument(
        param_name: &str,
        tainted_type: &str,
        expected_type: &str,
        span: Span,
        filename: &str,
    ) -> Diagnostic {
        Diagnostic::error_at(
            format!(
                "cannot pass tainted value to parameter `{}`",
                param_name
            ),
            span,
            filename,
        )
        .with_code(ErrorCode::TaintedArgument)
        .with_primary_label(format!("this has type `{}`", tainted_type))
        .with_note(format!("parameter `{}` expects `{}`, but got `{}`", param_name, expected_type, tainted_type))
        .with_help("wrap in unsafe block to acknowledge the risk:\n\n    unsafe(\"TICKET-XXX: verified secure\") {\n        // function call here\n    }")
    }

    /// Accessing tainted value outside unsafe block
    pub fn tainted_access(field: &str, base_type: &str, span: Span, filename: &str) -> Diagnostic {
        Diagnostic::error_at(
            format!("cannot access `{}` on tainted value outside unsafe block", field),
            span,
            filename,
        )
        .with_code(ErrorCode::TaintedAccess)
        .with_primary_label(format!("`{}` is tainted (type: `{}`)", field, base_type))
        .with_help("use unsafe block to access tainted values:\n\n    unsafe(\"TICKET-XXX: reason\") {\n        legacy.bucket\n    }")
    }

    /// Wrong number of arguments
    pub fn arity_mismatch(expected: usize, found: usize, span: Span, filename: &str) -> Diagnostic {
        let plural_expected = if expected == 1 {
            "argument"
        } else {
            "arguments"
        };
        let plural_found = if found == 1 { "was" } else { "were" };

        Diagnostic::error_at(
            format!(
                "function expects {} {}, but {} {} supplied",
                expected, plural_expected, found, plural_found
            ),
            span,
            filename,
        )
        .with_code(ErrorCode::ArityMismatch)
        .with_primary_label(format!("expected {} {}", expected, plural_expected))
    }

    /// Cannot call non-function type
    pub fn not_callable(typ: &str, span: Span, filename: &str) -> Diagnostic {
        Diagnostic::error_at(
            format!("cannot call value of type `{}`", typ),
            span,
            filename,
        )
        .with_code(ErrorCode::NotCallable)
        .with_primary_label("not a function")
        .with_note("only functions can be called with ()")
    }

    /// Unknown field access
    pub fn unknown_field(field: &str, base_type: &str, span: Span, filename: &str) -> Diagnostic {
        Diagnostic::error_at(
            format!("no field `{}` on type `{}`", field, base_type),
            span,
            filename,
        )
        .with_code(ErrorCode::UnknownField)
        .with_primary_label(format!("`{}` has no field `{}`", base_type, field))
    }

    /// Invalid operator for types
    pub fn invalid_operator(
        op: &str,
        left_type: &str,
        right_type: &str,
        span: Span,
        filename: &str,
    ) -> Diagnostic {
        Diagnostic::error_at(
            format!(
                "cannot apply `{}` to `{}` and `{}`",
                op, left_type, right_type
            ),
            span,
            filename,
        )
        .with_code(ErrorCode::InvalidOperator)
        .with_primary_label(format!("operator `{}` not valid for these types", op))
    }

    // === Lexer Errors ===

    /// Unexpected character
    pub fn unexpected_char(ch: char, span: Span, filename: &str) -> Diagnostic {
        Diagnostic::error_at(format!("unexpected character `{}`", ch), span, filename)
            .with_code(ErrorCode::UnexpectedChar)
            .with_primary_label("unexpected here")
    }

    /// Unterminated string
    pub fn unterminated_string(span: Span, filename: &str) -> Diagnostic {
        Diagnostic::error_at("unterminated string literal", span, filename)
            .with_code(ErrorCode::UnterminatedString)
            .with_primary_label("string starts here but never ends")
            .with_help("add a closing `\"` to terminate the string")
    }

    // === Parser Errors ===

    /// Unexpected token
    pub fn unexpected_token(expected: &str, found: &str, span: Span, filename: &str) -> Diagnostic {
        Diagnostic::error_at(
            format!("expected {}, found {}", expected, found),
            span,
            filename,
        )
        .with_code(ErrorCode::UnexpectedToken)
        .with_primary_label(format!("expected {}", expected))
    }

    // === Assertion Errors ===

    /// Compile-time assertion failed
    pub fn assertion_failed(message: &str, span: Span, filename: &str) -> Diagnostic {
        Diagnostic::error_at(format!("assertion failed: {}", message), span, filename)
            .with_code(ErrorCode::AssertionFailed)
            .with_primary_label("assertion evaluated to false")
    }
}

// === Utility Functions ===

/// Calculate Levenshtein distance between two strings (for "did you mean" suggestions)
#[allow(clippy::needless_range_loop)]
pub fn levenshtein_distance(a: &str, b: &str) -> usize {
    let a_len = a.chars().count();
    let b_len = b.chars().count();

    if a_len == 0 {
        return b_len;
    }
    if b_len == 0 {
        return a_len;
    }

    let mut matrix = vec![vec![0usize; b_len + 1]; a_len + 1];

    for i in 0..=a_len {
        matrix[i][0] = i;
    }
    for j in 0..=b_len {
        matrix[0][j] = j;
    }

    for (i, a_char) in a.chars().enumerate() {
        for (j, b_char) in b.chars().enumerate() {
            let cost = if a_char == b_char { 0 } else { 1 };
            matrix[i + 1][j + 1] = (matrix[i][j + 1] + 1)
                .min(matrix[i + 1][j] + 1)
                .min(matrix[i][j] + cost);
        }
    }

    matrix[a_len][b_len]
}

/// Find the most similar string from a list (for "did you mean" suggestions)
pub fn find_similar<'a>(
    target: &str,
    candidates: &[&'a str],
    max_distance: usize,
) -> Option<&'a str> {
    candidates
        .iter()
        .map(|&c| (c, levenshtein_distance(target, c)))
        .filter(|(_, d)| *d <= max_distance && *d > 0)
        .min_by_key(|(_, d)| *d)
        .map(|(c, _)| c)
}

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

    #[test]
    fn test_error_codes() {
        assert_eq!(ErrorCode::TypeMismatch.code(), "E0200");
        assert_eq!(ErrorCode::UndefinedVariable.code(), "E0201");
        assert_eq!(ErrorCode::TaintViolation.code(), "E0202");
    }

    #[test]
    fn test_diagnostic_with_code() {
        let span = Span::new(0, 10, 1, 1);
        let diag = Diagnostic::error_at("test", span, "test.hk").with_code(ErrorCode::TypeMismatch);

        assert_eq!(diag.code, ErrorCode::TypeMismatch);
        assert!(diag.to_string_simple().contains("E0200"));
    }

    #[test]
    fn test_diagnostic_builder() {
        let span = Span::new(0, 10, 1, 1);
        let diag = DiagnosticBuilder::type_mismatch("String", "Number", span, "test.hk");

        assert_eq!(diag.code, ErrorCode::TypeMismatch);
        assert!(diag.message.contains("String"));
        assert!(diag.message.contains("Number"));
    }

    #[test]
    fn test_levenshtein_distance() {
        assert_eq!(levenshtein_distance("bucket", "bucekt"), 2);
        assert_eq!(levenshtein_distance("hello", "hello"), 0);
        assert_eq!(levenshtein_distance("abc", "xyz"), 3);
    }

    #[test]
    fn test_find_similar() {
        let candidates = vec!["bucket", "vpc", "subnet", "security"];

        assert_eq!(find_similar("bucekt", &candidates, 3), Some("bucket"));
        assert_eq!(find_similar("vps", &candidates, 2), Some("vpc"));
        assert_eq!(find_similar("xyz", &candidates, 2), None);
    }

    #[test]
    fn test_diagnostic_with_notes() {
        let span = Span::new(0, 10, 1, 1);
        let diag = Diagnostic::error_at("test", span, "test.hk")
            .with_note("this is a note")
            .with_note("another note");

        assert_eq!(diag.notes.len(), 2);
    }

    #[test]
    fn test_undefined_variable_with_suggestion() {
        let span = Span::new(0, 10, 1, 1);
        let diag = DiagnosticBuilder::undefined_variable("bucekt", span, "test.hk", Some("bucket"));

        assert!(diag.help.as_ref().unwrap().contains("bucket"));
    }
}