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
#[cfg(debug_assertions)]
use std::backtrace::Backtrace;

use std::{borrow::Cow, cmp::Ordering};

use annotate_snippets::snippet::AnnotationType;
use debris_common::{CompileContext, Ident, Span, SpecialIdent};
use itertools::Itertools;

use super::{
    snippet::AnnotationOwned,
    utils::{display_expected_of_all, display_expected_of_any},
    AsAnnotationSnippet, SliceOwned, SnippetOwned, SourceAnnotationOwned,
};

/// A generic error which gets thrown when compiling
///
/// Contains a more specific [`LangErrorKind`]
#[derive(Debug)]
pub struct LangError {
    /// The specific error
    pub kind: LangErrorKind,
    pub span: Span,
    /// In debug mode stores the backtrace to provide additional
    /// debugging help
    #[cfg(debug_assertions)]
    backtrace: Backtrace,
}

impl LangError {
    #[cfg(not(debug_assertions))]
    pub fn new(kind: LangErrorKind, span: Span) -> Self {
        LangError { kind, span }
    }

    #[cfg(debug_assertions)]
    #[track_caller]
    pub fn new(kind: LangErrorKind, span: Span) -> Self {
        LangError {
            kind,
            span,
            backtrace: Backtrace::force_capture(),
        }
    }
}

/// Specifies a specific error reason
#[derive(Debug, Eq, PartialEq, Clone)]
pub enum LangErrorKind {
    UnexpectedProperty {
        property: String,
        value_class: String,
    },
    TupleMismatch {
        lhs_count: usize,
        rhs_count: usize,
    },
    IndexOutOfBounds {
        index: i32,
        max: usize,
    },
    ImmutableProperty,
    UnexpectedType {
        expected: Vec<String>,
        got: String,
        declared: Option<Span>,
    },
    UnexpectedStructInitializer {
        ident: Ident,
        strukt: Ident,
        available: Vec<Ident>,
    },
    MissingStructInitializer {
        strukt: Ident,
        missing: Vec<Ident>,
    },
    UnexpectedOverload {
        parameters: Vec<String>,
        expected: Vec<Vec<String>>,
        function_definition_span: Option<Span>,
    },
    MissingVariable {
        var_name: Ident,
        similar: Vec<String>,
        notes: Vec<String>,
    },
    NonComptimeVariable {
        var_name: String,
        class: String,
    },
    UnexpectedOperator {
        operator: SpecialIdent,
        lhs: String,
        rhs: String,
    },
    MissingModule {
        path: String,
        error: std::io::ErrorKind,
    },
    CircularImport {
        module: String,
    },
    InvalidControlFlow {
        control_flow: String,
        requires: ControlFlowRequires,
    },
    UnreachableCode,
    NotYetImplemented {
        msg: String,
    },
    ComptimeUpdate,
    ComptimeCall,
    InvalidComptimeBranch,
    ContinueWithValue,
    InvalidExternItemPath {
        path: String,
        error: String,
    },
    FunctionAlreadyExported,
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum ControlFlowRequires {
    Function,
    Loop,
}

impl<'a> AsAnnotationSnippet<'a> for LangError {
    #[allow(unused_mut)]
    fn as_annotation_snippet(&self, ctx: &'a CompileContext) -> SnippetOwned<'a> {
        let LangErrorSnippet { slices, mut footer } = self.kind.get_snippet(self.span, ctx);

        #[cfg(debug_assertions)]
        footer.push(AnnotationOwned {
            annotation_type: AnnotationType::Info,
            id: None,
            label: Some(Cow::Owned(format!("Backtrace:\n{}", self.backtrace))),
        });

        SnippetOwned {
            annotation_type: AnnotationType::Error,
            id: Some("Lang".into()),
            title: self.kind.to_string().into(),
            slices,
            footer,
        }
    }
}

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

impl std::fmt::Display for LangErrorKind {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            LangErrorKind::UnexpectedProperty {
                property,
                value_class: _,
            } => {
                write!(f, "'{property}' does not exist on this value")
            }
            LangErrorKind::TupleMismatch {
                lhs_count,
                rhs_count,
            } => write!(
                f,
                "Expected a tuple with {lhs_count} elements, but got {rhs_count}"
            ),
            LangErrorKind::IndexOutOfBounds { index, max } => {
                if *index > 0 {
                    write!(f, "Index {index} is out of bounds (max: {max})")
                } else {
                    write!(f, "Index must be greater than 0 (got: {index})")
                }
            }
            LangErrorKind::ImmutableProperty => write!(f, "Cannot change immutable value"),
            LangErrorKind::UnexpectedType {
                expected: _,
                got,
                declared: _,
            } => write!(f, "Received unexpected type {got}"),
            LangErrorKind::UnexpectedStructInitializer {
                ident,
                strukt,
                available: _,
            } => write!(f, "Unexpected member {ident} of {strukt}"),
            LangErrorKind::MissingStructInitializer {
                strukt: _,
                missing: _,
            } => {
                write!(f, "Incomplete struct instantiation")
            }
            LangErrorKind::UnexpectedOverload {
                parameters,
                expected: _,
                function_definition_span: _,
            } => write!(
                f,
                "No overload was found for parameters ({})",
                parameters.iter().join(", ")
            ),
            LangErrorKind::MissingVariable {
                var_name,
                similar: _,
                notes: _,
            } => write!(f, "Variable '{var_name}' does not exist"),
            LangErrorKind::NonComptimeVariable { var_name, class: _ } => write!(
                f,
                "Cannot assign non-comptime value to const variable '{var_name}'"
            ),
            LangErrorKind::UnexpectedOperator { operator, lhs, rhs } => write!(
                f,
                "Operator {operator} is not defined between type {lhs} and {rhs}"
            ),
            LangErrorKind::MissingModule { path, error: _ } => {
                write!(f, "Cannot find module at {path}")
            }
            LangErrorKind::CircularImport { module } => {
                write!(f, "Cannot import '{module}' multiple times")
            }
            LangErrorKind::InvalidControlFlow {
                control_flow,
                requires: _,
            } => write!(f, "Invalid control flow statement: {control_flow}"),
            LangErrorKind::UnreachableCode {} => write!(f, "This code will never be executed"),
            LangErrorKind::NotYetImplemented { msg } => {
                write!(f, "This feature is not yet implemented: {msg}")
            }
            LangErrorKind::ComptimeUpdate => {
                write!(
                    f,
                    "Cannot update this variable at runtime, only at compile time"
                )
            }
            LangErrorKind::ComptimeCall => write!(
                f,
                "Cannot call comptime function in a a non-comptime context"
            ),
            LangErrorKind::InvalidComptimeBranch => {
                write!(f, "Cannot evaluate this condition at compile time")
            }
            LangErrorKind::ContinueWithValue => {
                write!(f, "Cannot continue with a value")
            }
            LangErrorKind::InvalidExternItemPath { .. } => {
                write!(f, "Invalid extern item path")
            }
            LangErrorKind::FunctionAlreadyExported => {
                write!(f, "This function is already exported")
            }
        }
    }
}

struct LangErrorSnippet<'a> {
    slices: Vec<SliceOwned<'a>>,
    footer: Vec<AnnotationOwned<'a>>,
}

impl LangErrorKind {
    fn get_snippet<'a>(&self, span: Span, ctx: &'a CompileContext) -> LangErrorSnippet<'a> {
        let code = ctx.input_files.get_span_code(span);
        let origin = code.get_code().path.as_deref();
        let source = code.get_code().source.as_ref();
        let range = code.get_relative_span(span).unwrap();

        match self {
            LangErrorKind::UnexpectedProperty { value_class, property } => {
                LangErrorSnippet {
                    slices: vec![SliceOwned {
                        origin,
                        source,
                        annotations: vec![SourceAnnotationOwned {
                            annotation_type: AnnotationType::Error,
                            label: format!("{value_class} has no property '{property}'"),
                            range,
                        }],
                    }],
                    footer: vec![],
                }
            }
            LangErrorKind::TupleMismatch {lhs_count,rhs_count} => {
                let message = match lhs_count.cmp(rhs_count) {
                    Ordering::Greater => "Not enough values to unpack",
                    Ordering::Less => "Too many values to unpack",
                    Ordering::Equal => unreachable!()
                };
                LangErrorSnippet {
                    slices: vec![SliceOwned {
                        origin ,
                        source,
                        annotations: vec![SourceAnnotationOwned {
                            annotation_type: AnnotationType::Error,
                            label: format!("{message}: expected {lhs_count} but got {rhs_count}"),
                            range,
                        }]
                    }],
                    footer: vec![]
                }
            }
            LangErrorKind::IndexOutOfBounds{..} => LangErrorSnippet {
                slices: vec![SliceOwned {
                    origin ,
                    source,
                    annotations: vec![SourceAnnotationOwned {
                        annotation_type: AnnotationType::Error,
                        label: "Invalid access here".into(),
                        range,
                    }]
                }],
                footer: vec![]
            },
            LangErrorKind::ImmutableProperty => LangErrorSnippet {
                slices: vec![SliceOwned {
                    origin ,
                    source,
                    annotations: vec![SourceAnnotationOwned {
                        annotation_type: AnnotationType::Error,
                        label: "Comptime properties are immutable".into(),
                        range,
                    }]
                }],
                footer: vec![]
            },
            LangErrorKind::UnexpectedType { expected, got, declared } => {
                let expected_msg = display_expected_of_any(expected);
                let mut snippet = LangErrorSnippet {
                    slices: vec![SliceOwned {
                        origin,
                        source,
                        annotations: vec![SourceAnnotationOwned {
                            annotation_type: AnnotationType::Error,
                            label: format!("{expected_msg}, but got {got}"),
                            range,
                        }],
                    }],
                    footer: vec![],
                };

                if let Some(declared) = declared {
                    if let Some(declared) = code.get_relative_span(*declared) {
                        snippet.slices[0].annotations.push(SourceAnnotationOwned {
                            annotation_type: AnnotationType::Info,
                            label: "Type declared here".to_string(),
                            range: declared
                        });
                    }
                }

                snippet
            },
            LangErrorKind::UnexpectedStructInitializer { ident, strukt:_, available } => LangErrorSnippet {
                slices: vec![SliceOwned {
                    origin,
                    source,
                    annotations: vec![SourceAnnotationOwned {
                        annotation_type: AnnotationType::Error,
                        label: format!("Unexpected member: {ident}"),
                        range,
                    }],
                }],
                footer: vec![AnnotationOwned {
                    annotation_type: AnnotationType::Help,
                    id: None,
                    label: Some(Cow::Owned(display_expected_of_any(available)))
                }],
            },
            LangErrorKind::MissingStructInitializer { missing, strukt } => LangErrorSnippet {
                slices: vec![SliceOwned {
                    origin,
                    source,
                    annotations: vec![SourceAnnotationOwned {
                        annotation_type: AnnotationType::Error,
                        label: format!("Incomplete struct initialization of {strukt}"),
                        range,
                    }],
                }],
                footer: vec![AnnotationOwned {
                    annotation_type: AnnotationType::Help,
                    id: None,
                    label: Some(Cow::Owned(display_expected_of_all(missing)))
                }],
            },
            LangErrorKind::UnexpectedOverload { parameters, expected, function_definition_span} => {
                let parameters_string = format!("({})", parameters.iter().map(String::clone).join(", "));
                let mut possible_overloads = expected.iter().map(|params| {
                    if params.is_empty() {
                        "no parameters".to_string()
                    } else {
                        params.iter().map(String::clone).join(", ")
                    }
                });
                let message = if expected.len() == 1 {
                    format!("Called with {} but expected ({})", parameters_string, possible_overloads.next().unwrap())
                } else {
                    format!("Expected one of:\n  * {}",  possible_overloads.join("\n  * "))
                };

                let mut annotations =  vec![SourceAnnotationOwned {
                    annotation_type: AnnotationType::Error,
                    label: "No valid overload for this function call exists".to_string(),
                    range,
                }];

                if let Some(span) = function_definition_span {
                    let local_span = code.get_relative_span(*span);
                    if let Some(span) = local_span {
                        annotations.push(SourceAnnotationOwned {
                            annotation_type: AnnotationType::Info,
                            label: "Function defined here".to_string(),
                            range: span,
                        });
                    }
                }

                LangErrorSnippet {
                    slices: vec![SliceOwned {
                        source,
                        origin,
                        annotations,
                    }],
                    footer: vec![AnnotationOwned {
                        annotation_type: AnnotationType::Note,
                        id: None,
                        label: Some(message.into())
                    }],
                }
            }
            LangErrorKind::MissingVariable { similar, var_name, notes } => {
                let mut notes = notes.iter().map(|note| AnnotationOwned {
                    id: None,
                    annotation_type: AnnotationType::Note,
                    label: Some(note.clone().into())
                }).collect_vec();

                let footer = match similar.as_slice() {
                    [] => None,
                    [one] => Some(format!("Did you mean: '{one}'?").into()),
                    multiple => {
                        Some(format!("Similar names exist: {}", multiple.join(", ")).into())
                    }
                };

                notes.push(AnnotationOwned {
                    id: None,
                    annotation_type: AnnotationType::Help,
                    label: footer,
                });

                LangErrorSnippet {
                    slices: vec![SliceOwned {
                        origin,
                        source,
                        annotations: vec![SourceAnnotationOwned {
                            annotation_type: AnnotationType::Error,
                            label: format!("Variable {var_name} not found in this scope"),
                            range,
                        }],
                    }],
                    footer: notes,
                }
            }
            LangErrorKind::NonComptimeVariable {
                class, var_name,
            } => LangErrorSnippet {
                slices: vec![SliceOwned {
                    origin,
                    source,
                    annotations: vec![SourceAnnotationOwned {
                        annotation_type: AnnotationType::Error,
                        label: format!("Cannot assign non-comptime value to '{var_name}'"),
                        range,
                    }],
                }],
                footer: vec![AnnotationOwned {
                    id: None,
                    annotation_type: AnnotationType::Note,
                    label: Some(format!("The value of type {class} cannot be known at compile time").into())
                }],
            },
            LangErrorKind::UnexpectedOperator {
                lhs,
                rhs: _,
                operator,
            } => LangErrorSnippet {
                slices: vec![SliceOwned {
                    origin,
                    source,
                    annotations: vec![SourceAnnotationOwned {
                        annotation_type: AnnotationType::Error,
                        label: format!("{lhs} does not implement operator {operator}"),
                        range,
                    }],
                }],
                footer: vec![],
            },
            LangErrorKind::MissingModule {
                path: _,
                error,
            } => LangErrorSnippet {
                slices: vec![SliceOwned {
                    origin,
                    source,
                    annotations: vec![SourceAnnotationOwned {
                        annotation_type: AnnotationType::Error,
                        label: match error {
                            std::io::ErrorKind::NotFound => "Cannot find this module".to_string(),
                            std::io::ErrorKind::PermissionDenied => "Cannot access this module because the permission was denied".to_string(),
                            other => format!("Error reading this module: {other:?}")
                        },
                        range,
                    }],
                }],
                footer: vec![],
            },
            LangErrorKind::CircularImport {
                module: _
            } => LangErrorSnippet {
                slices: vec![SliceOwned {
                    origin,
                    source,
                    annotations: vec![SourceAnnotationOwned {
                        annotation_type: AnnotationType::Error,
                        label: "Trying to import this module multiple times".to_string(),
                        range,
                    }],
                }],
                footer: vec![],
            },
            LangErrorKind::InvalidControlFlow { control_flow, requires } => {
                let message = match requires {
                    ControlFlowRequires::Function => "only valid in a function",
                    ControlFlowRequires::Loop => "only valid in a loop",
                };
                LangErrorSnippet {
                slices: vec![SliceOwned {
                    origin,
                    source,
                    annotations: vec![SourceAnnotationOwned {
                        annotation_type: AnnotationType::Error,
                        label: format!("{control_flow} is {message}"),
                        range,
                    }],
                }],
                footer: vec![],
            }},
            LangErrorKind::UnreachableCode => LangErrorSnippet {
                slices: vec![SliceOwned {
                    origin,
                    source,
                    annotations: vec![
                    SourceAnnotationOwned {
                        annotation_type: AnnotationType::Error,
                        label: "This code cannot be reached".to_string(),
                        range,
                    }
                    ],
                }],
                footer: vec![],
            },
            LangErrorKind::NotYetImplemented { msg: _ } => LangErrorSnippet {
                slices: vec![SliceOwned {
                    origin,
                    source,
                    annotations: vec![SourceAnnotationOwned {
                        annotation_type: AnnotationType::Error,
                        label: "This feature is not yet implemented!".to_string(),
                        range,
                    }],
                }],
                footer: vec![AnnotationOwned {
                    id: None,
                    annotation_type: AnnotationType::Note,
                    label: Some("If you think this is a bug, please submit an issue at the github repository.".into())
                }],
            },
            LangErrorKind::ComptimeUpdate => LangErrorSnippet {
                slices: vec![SliceOwned {
                    origin,
                    source,
                    annotations: vec![SourceAnnotationOwned {
                        annotation_type: AnnotationType::Error,
                        label: "Cannot perform runtime updates for this value".to_string(),
                        range,
                    }]
                }],
                footer: vec![]
            },
            LangErrorKind::ComptimeCall => LangErrorSnippet {
                slices: vec![SliceOwned {
                    origin,
                    source,
                    annotations: vec![SourceAnnotationOwned {
                        annotation_type: AnnotationType::Error,
                        label: "Cannot perform comptime calls in this context".to_string(),
                        range,
                    }]
                }],
                footer: vec![]
            },
            LangErrorKind::InvalidComptimeBranch => LangErrorSnippet {
                slices: vec![SliceOwned {
                    origin,
                    source,
                    annotations: vec![SourceAnnotationOwned {
                        annotation_type: AnnotationType::Error,
                        label: "Cannot know the value of this condition at compile time".to_string(),
                        range,
                    }]
                }],
                footer: vec![AnnotationOwned {
                    id: None,
                    annotation_type: AnnotationType::Help,
                    label: Some("Try removing the comptime keyword".into())
                }]
            },
            LangErrorKind::ContinueWithValue => LangErrorSnippet {
                slices: vec![SliceOwned {
                    origin,
                    source,
                    annotations: vec![SourceAnnotationOwned {
                        annotation_type: AnnotationType::Error,
                        label: String::new(),
                        range,
                    }]
                }],
                footer: vec![]
            },
            LangErrorKind::InvalidExternItemPath{ error, .. } => LangErrorSnippet {
                slices: vec![SliceOwned {
                    origin,
                    source,
                    annotations: vec![SourceAnnotationOwned {
                        annotation_type: AnnotationType::Error,
                        label: error.into(),
                        range,
                    }]
                }],
                footer: vec![]
            },
            LangErrorKind::FunctionAlreadyExported => LangErrorSnippet {
                slices: vec![SliceOwned {
                    origin,
                    source,
                    annotations: vec![SourceAnnotationOwned {
                        annotation_type: AnnotationType::Error,
                        label: "Cannot export a function multiple times".into(),
                        range,
                    }]
                }],
                footer: vec![]
            }
        }
    }
}