bhc-diagnostics 0.2.9

Error reporting and diagnostics for BHC
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
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
//! Error code explanations.
//!
//! This module provides detailed explanations for error codes, accessible
//! via the `--explain` flag (e.g., `bhc --explain E0001`).
//!
//! ## Error Code Conventions
//!
//! - `E0xxx`: Type errors
//! - `E00xx`: Basic type mismatches (E0001-E0019)
//! - `E002x`: Shape/dimension errors (E0020-E0039)
//! - `E003x`: Tensor operation errors (E0030-E0039)
//! - `E004x`: Pattern matching errors (E0040-E0049)
//! - `E005x`: Module/import errors (E0050-E0059)
//! - `W0xxx`: Warnings
//! - `W001x`: Unused bindings (W0010-W0019)
//! - `W002x`: Deprecated features (W0020-W0029)
//!
//! ## M10 Phase 4: Contextual Help
//!
//! Each error explanation includes:
//! - Documentation links to relevant sections
//! - Related error codes for similar issues
//! - Common mistake patterns with fixes

use std::collections::HashMap;
use std::sync::LazyLock;

/// An error code explanation.
#[derive(Clone, Debug)]
pub struct ErrorExplanation {
    /// The error code.
    pub code: &'static str,
    /// A brief title for the error.
    pub title: &'static str,
    /// A detailed explanation.
    pub explanation: &'static str,
    /// Example code that triggers this error.
    pub example: Option<&'static str>,
    /// Example of the correct code.
    pub correct_example: Option<&'static str>,
    /// Link to related documentation.
    pub doc_link: Option<&'static str>,
    /// Related error codes that might be relevant.
    pub related_codes: &'static [&'static str],
    /// Common mistake patterns that lead to this error.
    pub common_mistakes: &'static [CommonMistake],
}

/// A common mistake pattern with its fix.
#[derive(Clone, Debug)]
pub struct CommonMistake {
    /// Description of the mistake pattern.
    pub pattern: &'static str,
    /// Suggested fix for this mistake.
    pub fix: &'static str,
}

/// Registry of all error code explanations.
static ERROR_REGISTRY: LazyLock<HashMap<&'static str, ErrorExplanation>> = LazyLock::new(|| {
    let mut map = HashMap::new();

    // === Type Errors (E0001-E0019) ===

    map.insert(
        "E0001",
        ErrorExplanation {
            code: "E0001",
            title: "Type mismatch",
            explanation: r#"
This error occurs when the type checker expects one type but finds another.

Type mismatches commonly occur when:
- A function is called with an argument of the wrong type
- A variable is used in a context that requires a different type
- A return value doesn't match the function's declared return type

The compiler shows the expected type and the actual type found. Check that
your types align, or add explicit type conversions where needed.
"#,
            example: Some(
                r#"
foo :: Int -> Int
foo x = "hello"  -- Error: expected Int, found String
"#,
            ),
            correct_example: Some(
                r#"
foo :: Int -> Int
foo x = x + 1
"#,
            ),
            doc_link: Some("https://bhc.dev/docs/type-system"),
            related_codes: &["E0007", "E0009"],
            common_mistakes: &[
                CommonMistake {
                    pattern: "Returning wrong type from function",
                    fix: "Check the function's type signature matches the return expression",
                },
                CommonMistake {
                    pattern: "Passing string literal where number expected",
                    fix: "Use numeric literals (42) not strings (\"42\")",
                },
            ],
        },
    );

    map.insert(
        "E0002",
        ErrorExplanation {
            code: "E0002",
            title: "Infinite type (occurs check)",
            explanation: r#"
This error occurs when type inference would create an infinite type,
typically when a value is used in a way that would require it to contain
itself.

This is detected by the "occurs check" during unification. If a type
variable would need to be unified with a type containing that same
variable, it would create an infinite loop in the type.

Common causes:
- Recursive data without proper type annotations
- Accidentally creating circular references in types
"#,
            example: Some(
                r#"
-- This creates an infinite type: a = [a]
foo x = [x, foo x]
"#,
            ),
            correct_example: Some(
                r#"
-- Use a recursive data type instead
data Tree a = Leaf a | Node [Tree a]

foo :: a -> Tree a
foo x = Node [Leaf x, foo x]
"#,
            ),
            doc_link: Some("https://bhc.dev/docs/type-inference"),
            related_codes: &["E0001", "E0022"],
            common_mistakes: &[CommonMistake {
                pattern: "Building a list containing the result of a recursive call",
                fix: "Use a proper recursive data type instead of lists",
            }],
        },
    );

    map.insert(
        "E0003",
        ErrorExplanation {
            code: "E0003",
            title: "Unbound variable",
            explanation: r#"
This error occurs when you use a variable name that hasn't been defined
in the current scope.

Common causes:
- Typo in the variable name
- Using a variable before it's defined
- Variable defined in a different scope (e.g., inside a let or lambda)
- Forgot to import a module

The compiler will suggest similar names if it finds a likely typo.
"#,
            example: Some(
                r#"
foo = x + 1  -- Error: x is not defined
"#,
            ),
            correct_example: Some(
                r#"
foo x = x + 1  -- x is now a parameter
"#,
            ),
            doc_link: Some("https://bhc.dev/docs/scoping"),
            related_codes: &["E0004"],
            common_mistakes: &[
                CommonMistake {
                    pattern: "Typo in variable name (e.g., 'lenght' instead of 'length')",
                    fix: "Check the 'did you mean?' suggestion in the error message",
                },
                CommonMistake {
                    pattern: "Using a variable from an inner scope",
                    fix: "Pass the variable as a parameter or define it in the current scope",
                },
                CommonMistake {
                    pattern: "Forgot to import a module",
                    fix: "Add an import statement for the missing module",
                },
            ],
        },
    );

    map.insert(
        "E0004",
        ErrorExplanation {
            code: "E0004",
            title: "Unbound constructor",
            explanation: r#"
This error occurs when you use a data constructor that hasn't been defined
or imported.

Data constructors in Haskell/BHC must:
- Start with an uppercase letter (e.g., Just, Nothing, True)
- Be defined in a data/newtype declaration
- Be imported if defined in another module

Common causes:
- Typo in the constructor name
- Forgot to import the data type
- Constructor is not exported from its module
"#,
            example: Some(
                r#"
foo = Jus 42  -- Error: typo, should be Just
"#,
            ),
            correct_example: Some(
                r#"
foo = Just 42  -- Correct constructor name
"#,
            ),
            doc_link: Some("https://bhc.dev/docs/data-types"),
            related_codes: &["E0003", "E0005"],
            common_mistakes: &[
                CommonMistake {
                    pattern: "Typo in constructor name",
                    fix: "Check the 'did you mean?' suggestion",
                },
                CommonMistake {
                    pattern: "Constructor not exported",
                    fix: "Import the module with explicit constructor list",
                },
            ],
        },
    );

    map.insert(
        "E0005",
        ErrorExplanation {
            code: "E0005",
            title: "Pattern arity mismatch",
            explanation: r#"
This error occurs when a pattern has a different number of arguments than
the data constructor expects.

Each data constructor has a fixed number of fields. When pattern matching,
you must provide exactly that many pattern variables.
"#,
            example: Some(
                r#"
data Point = Point Int Int

foo (Point x) = x  -- Error: Point has 2 fields, but pattern has 1
"#,
            ),
            correct_example: Some(
                r#"
data Point = Point Int Int

foo (Point x y) = x + y  -- Correct: matches both fields
-- Or use a wildcard:
foo (Point x _) = x      -- Ignore second field
"#,
            ),
            doc_link: Some("https://bhc.dev/docs/pattern-matching"),
            related_codes: &["E0004", "E0008"],
            common_mistakes: &[CommonMistake {
                pattern: "Missing pattern variables",
                fix: "Use wildcards (_) for fields you don't need",
            }],
        },
    );

    map.insert(
        "E0006",
        ErrorExplanation {
            code: "E0006",
            title: "Ambiguous type variable",
            explanation: r#"
This error occurs when the compiler cannot determine a concrete type for
a type variable. The type is ambiguous because there's not enough
information to resolve it.

This often happens with:
- Numeric literals that could be Int, Float, etc.
- Polymorphic functions where the result type isn't constrained
- Show/Read without a concrete type context

Solution: Add a type annotation to specify the intended type.
"#,
            example: Some(
                r#"
foo = show (read "42")  -- Error: ambiguous type for read
"#,
            ),
            correct_example: Some(
                r#"
foo = show (read "42" :: Int)  -- Explicit type annotation
"#,
            ),
            doc_link: Some("https://bhc.dev/docs/type-inference"),
            related_codes: &["E0001"],
            common_mistakes: &[
                CommonMistake {
                    pattern: "Using read without type annotation",
                    fix: "Add :: Type after the expression",
                },
                CommonMistake {
                    pattern: "Numeric literal in polymorphic context",
                    fix: "Add type annotation like (42 :: Int)",
                },
            ],
        },
    );

    map.insert(
        "E0007",
        ErrorExplanation {
            code: "E0007",
            title: "Kind mismatch",
            explanation: r#"
This error occurs when a type is used with the wrong kind.

Kinds classify types:
- `*` (or `Type`): Concrete types like Int, Bool, [Char]
- `* -> *`: Type constructors like Maybe, [], IO
- `* -> * -> *`: Two-parameter type constructors like Either, (,)

Kind errors often occur when:
- Applying a concrete type as if it were a type constructor
- Forgetting to apply a type constructor to its argument
"#,
            example: Some(
                r#"
foo :: Int Maybe  -- Error: Int has kind *, not * -> *
"#,
            ),
            correct_example: Some(
                r#"
foo :: Maybe Int  -- Correct: Maybe :: * -> *, Int :: *
"#,
            ),
            doc_link: Some("https://bhc.dev/docs/kinds"),
            related_codes: &["E0001"],
            common_mistakes: &[CommonMistake {
                pattern: "Type arguments in wrong order",
                fix: "Put type constructor before its argument",
            }],
        },
    );

    map.insert(
        "E0008",
        ErrorExplanation {
            code: "E0008",
            title: "Function arity mismatch",
            explanation: r#"
This error occurs when a function is called with the wrong number of
arguments.

While Haskell/BHC supports partial application (providing fewer arguments
than expected), this error is raised when you provide MORE arguments than
the function accepts.

The error message shows which arguments are extra.
"#,
            example: Some(
                r#"
add :: Int -> Int -> Int
add x y = x + y

result = add 1 2 3  -- Error: add takes 2 arguments, got 3
"#,
            ),
            correct_example: Some(
                r#"
add :: Int -> Int -> Int
add x y = x + y

result = add 1 2  -- Correct: 2 arguments
"#,
            ),
            doc_link: Some("https://bhc.dev/docs/functions"),
            related_codes: &["E0005", "E0009"],
            common_mistakes: &[CommonMistake {
                pattern: "Passing extra arguments",
                fix: "Check the function's type signature for argument count",
            }],
        },
    );

    map.insert(
        "E0009",
        ErrorExplanation {
            code: "E0009",
            title: "Not a function",
            explanation: r#"
This error occurs when you try to apply something that isn't a function
as if it were one.

In Haskell/BHC, function application is denoted by juxtaposition:
  f x    -- Apply f to x

If `f` is not a function type (doesn't have the form `a -> b`), you'll
get this error.
"#,
            example: Some(
                r#"
x = 42
result = x 10  -- Error: 42 is Int, not a function
"#,
            ),
            correct_example: Some(
                r#"
f x = x + 1
result = f 10  -- Correct: f is a function
"#,
            ),
            doc_link: Some("https://bhc.dev/docs/functions"),
            related_codes: &["E0001", "E0008"],
            common_mistakes: &[
                CommonMistake {
                    pattern: "Applying a non-function value",
                    fix: "Check if you meant to call a different function",
                },
                CommonMistake {
                    pattern: "Missing operator between values",
                    fix: "Add the operator like + or * between values",
                },
            ],
        },
    );

    // === Shape Errors (E0020-E0029) ===

    map.insert(
        "E0020",
        ErrorExplanation {
            code: "E0020",
            title: "Dimension mismatch",
            explanation: r#"
This error occurs when tensor dimensions don't match as required by an
operation.

For example, matrix multiplication requires the inner dimensions to match:
  matmul :: Tensor '[m, k] a -> Tensor '[k, n] a -> Tensor '[m, n] a

The 'k' dimension (columns of first matrix, rows of second) must be equal.

Common causes:
- Matrices with incompatible shapes for multiplication
- Elementwise operations on tensors of different shapes
- Incorrect reshape operations
"#,
            example: Some(
                r#"
-- Shapes: [3, 5] × [7, 4] - inner dimensions 5 ≠ 7
result = matmul a b  -- Error: dimension mismatch
"#,
            ),
            correct_example: Some(
                r#"
-- Shapes: [3, 5] × [5, 4] - inner dimensions match
result = matmul a b  -- OK: produces [3, 4]
"#,
            ),
            doc_link: Some("https://bhc.dev/docs/tensors/shapes"),
            related_codes: &["E0023", "E0030", "E0031"],
            common_mistakes: &[
                CommonMistake {
                    pattern: "Matrices in wrong order for matmul",
                    fix: "Try swapping the arguments or transpose one matrix",
                },
                CommonMistake {
                    pattern: "Wrong reshape dimensions",
                    fix: "Check that total elements match before and after reshape",
                },
            ],
        },
    );

    map.insert(
        "E0023",
        ErrorExplanation {
            code: "E0023",
            title: "Shape rank mismatch",
            explanation: r#"
This error occurs when a tensor has a different number of dimensions
(rank) than expected.

For example:
- A function expecting a matrix (rank 2) receives a vector (rank 1)
- A function expecting a vector (rank 1) receives a scalar (rank 0)

Check that your tensors have the correct number of dimensions.
"#,
            example: Some(
                r#"
-- matmul expects rank-2 tensors (matrices)
a :: Tensor '[10] Float      -- rank 1 (vector)
b :: Tensor '[10, 5] Float   -- rank 2 (matrix)
result = matmul a b  -- Error: rank mismatch
"#,
            ),
            correct_example: Some(
                r#"
-- Both operands are rank-2
a :: Tensor '[1, 10] Float   -- rank 2 (row vector as matrix)
b :: Tensor '[10, 5] Float   -- rank 2 (matrix)
result = matmul a b  -- OK: produces [1, 5]
"#,
            ),
            doc_link: Some("https://bhc.dev/docs/tensors/ranks"),
            related_codes: &["E0020", "E0030"],
            common_mistakes: &[
                CommonMistake {
                    pattern: "Vector where matrix expected",
                    fix: "Use reshape to add dimension: '[n] -> '[1, n] or '[n, 1]",
                },
                CommonMistake {
                    pattern: "Wrong tensor dimension count",
                    fix: "Use unsqueeze/squeeze to add/remove dimensions",
                },
            ],
        },
    );

    // === Tensor Operation Errors (E0030-E0039) ===

    map.insert(
        "E0030",
        ErrorExplanation {
            code: "E0030",
            title: "Matrix multiplication dimension mismatch",
            explanation: r#"
This error occurs specifically during matrix multiplication when the inner
dimensions don't match.

Matrix multiplication has the signature:
  matmul :: Tensor '[m, k] a -> Tensor '[k, n] a -> Tensor '[m, n] a

The second dimension of the first matrix (k, the number of columns) must
equal the first dimension of the second matrix (k, the number of rows).

Visual representation:
  [m × k] @ [k × n] = [m × n]
       └───┴──── these must match

Common fixes:
- Transpose one of the matrices
- Swap the order of arguments
- Reshape to get compatible dimensions
"#,
            example: Some(
                r#"
weights :: Tensor '[768, 512] Float
input   :: Tensor '[1024, 768] Float
-- Error: matmul expects inner dims to match
-- weights has 512 cols, input has 1024 rows
result = matmul weights input
"#,
            ),
            correct_example: Some(
                r#"
weights :: Tensor '[768, 512] Float
input   :: Tensor '[768, 1024] Float
-- 768 == 768, so inner dimensions match
result = matmul (transpose weights) input  -- [512, 1024]

-- Or swap the order:
result = matmul input weights  -- Depends on what you want
"#,
            ),
            doc_link: Some("https://bhc.dev/docs/tensors/matmul"),
            related_codes: &["E0020", "E0023", "E0038"],
            common_mistakes: &[
                CommonMistake {
                    pattern: "Arguments in wrong order",
                    fix: "Try matmul b a instead of matmul a b",
                },
                CommonMistake {
                    pattern: "Forgot to transpose",
                    fix: "Use transpose on one of the matrices",
                },
                CommonMistake {
                    pattern: "Shapes are reversed from numpy/pytorch convention",
                    fix: "BHC uses [rows, cols] ordering consistently",
                },
            ],
        },
    );

    map.insert(
        "E0031",
        ErrorExplanation {
            code: "E0031",
            title: "Broadcast incompatible shapes",
            explanation: r#"
This error occurs when two tensors have shapes that cannot be broadcast
together according to NumPy-style broadcasting rules.

Broadcasting rules:
1. Shapes are compared element-wise from the trailing dimensions
2. Dimensions are compatible if they are equal or one of them is 1
3. Missing dimensions are treated as 1

For example:
  [3, 4] and [4] -> OK (becomes [3, 4])
  [3, 4] and [1, 4] -> OK (becomes [3, 4])
  [3, 4] and [2, 4] -> Error! (3 ≠ 2 and neither is 1)
"#,
            example: Some(
                r#"
a :: Tensor '[3, 4] Float
b :: Tensor '[2, 4] Float
result = a + b  -- Error: cannot broadcast [3,4] with [2,4]
"#,
            ),
            correct_example: Some(
                r#"
a :: Tensor '[3, 4] Float
b :: Tensor '[1, 4] Float
result = a + b  -- OK: b broadcasts to [3, 4]
"#,
            ),
            doc_link: Some("https://bhc.dev/docs/tensors/broadcasting"),
            related_codes: &["E0020", "E0023"],
            common_mistakes: &[
                CommonMistake {
                    pattern: "Non-1 dimensions that don't match",
                    fix: "Use reshape to make one dimension 1 for broadcasting",
                },
                CommonMistake {
                    pattern: "Broadcasting where elementwise was intended",
                    fix: "Ensure shapes match exactly or use explicit broadcast",
                },
            ],
        },
    );

    map.insert(
        "E0037",
        ErrorExplanation {
            code: "E0037",
            title: "Dynamic tensor conversion failed",
            explanation: r#"
This error occurs when attempting to convert a DynTensor to a statically-
shaped tensor with fromDynamic, but the runtime shape doesn't match.

DynTensor is an existentially-quantified wrapper that hides the shape:
  data DynTensor a where
    MkDynTensor :: Tensor shape a -> DynTensor a

When using fromDynamic, you must handle the case where the shapes don't
match:
  fromDynamic :: ShapeWitness shape -> DynTensor a -> Maybe (Tensor shape a)

Always pattern match on the Maybe result to handle both cases.
"#,
            example: Some(
                r#"
processTensor :: DynTensor Float -> Tensor '[256, 256] Float
processTensor dyn = fromJust (fromDynamic witness dyn)
-- Error if runtime shape isn't [256, 256]!
"#,
            ),
            correct_example: Some(
                r#"
processTensor :: DynTensor Float -> Maybe (Tensor '[256, 256] Float)
processTensor dyn = case fromDynamic witness dyn of
    Just tensor -> Just (processStatic tensor)
    Nothing     -> Nothing  -- Handle shape mismatch
"#,
            ),
            doc_link: Some("https://bhc.dev/docs/tensors/dynamic"),
            related_codes: &["E0020", "E0023"],
            common_mistakes: &[
                CommonMistake {
                    pattern: "Using fromJust with fromDynamic",
                    fix: "Always pattern match on Maybe result",
                },
                CommonMistake {
                    pattern: "Not validating runtime shapes",
                    fix: "Check shape at boundaries using fromDynamic safely",
                },
            ],
        },
    );

    // === Warnings (W0xxx) ===

    map.insert(
        "W0001",
        ErrorExplanation {
            code: "W0001",
            title: "Unused variable",
            explanation: r#"
This warning indicates that a variable is defined but never used.

While this doesn't prevent compilation, unused variables often indicate:
- Incomplete code (forgot to use the variable)
- Dead code that can be removed
- A typo in the variable name

To suppress this warning for intentionally unused variables, prefix the
name with an underscore: `_unused`.
"#,
            example: Some(
                r#"
foo x y = x + 1  -- Warning: y is unused
"#,
            ),
            correct_example: Some(
                r#"
foo x _y = x + 1  -- No warning: _y is intentionally unused
-- Or actually use y:
foo x y = x + y
"#,
            ),
            doc_link: Some("https://bhc.dev/docs/warnings"),
            related_codes: &[],
            common_mistakes: &[
                CommonMistake {
                    pattern: "Forgot to use variable in computation",
                    fix: "Use the variable or prefix with _ if intentionally unused",
                },
                CommonMistake {
                    pattern: "Typo in variable name causing apparent unused var",
                    fix: "Check for similar names used elsewhere",
                },
            ],
        },
    );

    map
});

/// Look up an error explanation by code.
#[must_use]
pub fn get_explanation(code: &str) -> Option<&'static ErrorExplanation> {
    ERROR_REGISTRY.get(code)
}

/// Get all registered error codes.
#[must_use]
pub fn all_error_codes() -> Vec<&'static str> {
    let mut codes: Vec<_> = ERROR_REGISTRY.keys().copied().collect();
    codes.sort();
    codes
}

/// Format an error explanation for display.
#[must_use]
pub fn format_explanation(explanation: &ErrorExplanation) -> String {
    let mut output = String::new();

    output.push_str(&format!(
        "# {} - {}\n\n",
        explanation.code, explanation.title
    ));
    output.push_str(explanation.explanation.trim());
    output.push_str("\n\n");

    if let Some(example) = explanation.example {
        output.push_str("## Example of erroneous code:\n");
        output.push_str("```haskell");
        output.push_str(example);
        output.push_str("```\n\n");
    }

    if let Some(correct) = explanation.correct_example {
        output.push_str("## Corrected code:\n");
        output.push_str("```haskell");
        output.push_str(correct);
        output.push_str("```\n\n");
    }

    // M10 Phase 4: Common mistakes
    if !explanation.common_mistakes.is_empty() {
        output.push_str("## Common Mistakes\n\n");
        for mistake in explanation.common_mistakes {
            output.push_str(&format!("**{}**\n", mistake.pattern));
            output.push_str(&format!("  Fix: {}\n\n", mistake.fix));
        }
    }

    // M10 Phase 4: Related error codes
    if !explanation.related_codes.is_empty() {
        output.push_str("## Related\n\n");
        output.push_str("See also: ");
        let codes: Vec<String> = explanation
            .related_codes
            .iter()
            .map(|c| format!("`{}`", c))
            .collect();
        output.push_str(&codes.join(", "));
        output.push_str("\n\n");
    }

    // M10 Phase 4: Documentation link
    if let Some(doc_link) = explanation.doc_link {
        output.push_str("## Documentation\n\n");
        output.push_str(&format!("For more information, see: {}\n", doc_link));
    }

    output
}

/// Print an error explanation to stdout.
pub fn print_explanation(code: &str) {
    match get_explanation(code) {
        Some(explanation) => {
            println!("{}", format_explanation(explanation));
        }
        None => {
            println!("Error code `{code}` not found.");
            println!("\nAvailable error codes:");
            for code in all_error_codes() {
                if let Some(exp) = get_explanation(code) {
                    println!("  {}: {}", code, exp.title);
                }
            }
        }
    }
}

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

    #[test]
    fn test_get_explanation() {
        let exp = get_explanation("E0001").unwrap();
        assert_eq!(exp.code, "E0001");
        assert_eq!(exp.title, "Type mismatch");
    }

    #[test]
    fn test_unknown_code() {
        assert!(get_explanation("E9999").is_none());
    }

    #[test]
    fn test_all_error_codes() {
        let codes = all_error_codes();
        assert!(!codes.is_empty());
        assert!(codes.contains(&"E0001"));
    }

    #[test]
    fn test_format_explanation() {
        let exp = get_explanation("E0001").unwrap();
        let formatted = format_explanation(exp);
        assert!(formatted.contains("E0001"));
        assert!(formatted.contains("Type mismatch"));
    }
}