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
use crate::ast;
use crate::token::Kind;
use runestick::{Item, Meta, Span};
use std::fmt;
use std::io;
use thiserror::Error;

/// A compile result.
pub type CompileResult<T, E = CompileError> = std::result::Result<T, E>;

/// Result alias used by this frontend.
pub type Result<T, E = Error> = std::result::Result<T, E>;

/// Error capable of collecting all error types emitted by this crate.
#[derive(Debug, Error)]
pub enum Error {
    /// Source parse error.
    #[error("parse error")]
    ParseError(#[from] ParseError),
    /// Compiler error.
    #[error("compile error")]
    CompileError(#[from] CompileError),
    /// Configuration error.
    #[error("configuration error")]
    ConfigurationError(#[from] ConfigurationError),
    /// I/O error.
    #[error("I/O error")]
    Io(#[from] io::Error),
    /// Formatting error.
    #[error("formatting error")]
    Fmt(#[from] fmt::Error),
    /// Errors raised by the virtual machine.
    #[error("virtual machine error")]
    VmError(#[from] runestick::VmError),
    /// Errors raised when setting up context.
    #[error("context error")]
    ContextError(#[from] runestick::ContextError),
}

#[derive(Debug, Clone, Error)]
pub enum ConfigurationError {
    /// Tried to configure the compiler with an unsupported optimzation option.
    #[error("unsupported optimization option `{option}`")]
    UnsupportedOptimizationOption {
        /// The unsupported option.
        option: String,
    },
}

/// Error when parsing.
#[derive(Debug, Clone, Copy, Error)]
pub enum ParseError {
    /// Error raised when we encounter end-of-file but we didn't expect it.
    #[error("unexpected end-of-file")]
    UnexpectedEof {
        /// Span that caused the error.
        span: Span,
    },
    /// Error raised when we expect and end-of-file but it didn't happen.
    #[error("expected end of file, but encountered `{actual}`")]
    ExpectedEof {
        /// Span that caused the error.
        span: Span,
        /// Kind of the token encountered instead of end-of-file.
        actual: Kind,
    },
    /// Expected use import but found something else.
    #[error("expected import component but found `{actual}`")]
    ExpectedDeclUseImportComponent {
        /// The span of the component.
        span: Span,
        /// The actual token kind.
        actual: Kind,
    },
    /// Error encountered when we see a string escape sequence without a
    /// character being escaped.
    #[error("expected escape")]
    ExpectedStringEscape {
        /// Span that caused the error.
        span: Span,
    },
    /// Expected a string close but didn't see it.
    #[error("unterminated string literal")]
    UnterminatedStrLit {
        /// Span that caused the error.
        span: Span,
    },
    /// Encountered an unterminated character literal.
    #[error("unterminated character literal")]
    UnterminatedCharLit {
        /// The span of the unterminated literal.
        span: Span,
    },
    /// Encountered an unterminated byte literal.
    #[error("unterminated byte literal")]
    UnterminatedByteLit {
        /// The span of the unterminated literal.
        span: Span,
    },
    /// Expected a character to be closed.
    #[error("expected character literal to be closed")]
    ExpectedCharClose {
        /// Span that caused the error.
        span: Span,
    },
    /// Expected a byte to be closed.
    #[error("expected byte literal to be closed")]
    ExpectedByteClose {
        /// Span that caused the error.
        span: Span,
    },
    /// Expected a string template to be closed, but it wasn't.
    #[error("expected string template to be closed")]
    ExpectedTemplateClose {
        /// Span that caused the error.
        span: Span,
    },
    /// Error encountered when we see a character escape sequence without a
    /// character being escaped.
    #[error("expected character character")]
    ExpectedCharEscape {
        /// Span that caused the error.
        span: Span,
    },
    /// Encountered an unexpected token.
    #[error("token mismatch, expected `{expected}` but was `{actual}`")]
    TokenMismatch {
        /// Span that caused the error.
        span: Span,
        /// The kind of the expected token we saw.
        expected: Kind,
        /// The kind of the actual token we saw.
        actual: Kind,
    },
    /// Expected a pattern but got something else.
    #[error("expected start of pattern but got `{actual}`")]
    ExpectedPatError {
        /// Span that caused the error.
        span: Span,
        /// The kind of the actual token we saw.
        actual: Kind,
    },
    /// Expected an expression but got something else.
    #[error("expected start of expression but got `{actual}`")]
    ExpectedExpr {
        /// Span that caused the error.
        span: Span,
        /// The kind of the actual token we saw.
        actual: Kind,
    },
    /// Expected an enum variant but got something else.
    #[error("expected enum variant but got `{actual}`")]
    ExpectedEnumVariant {
        /// Span that caused the error.
        span: Span,
        /// The kind of the actual token we saw.
        actual: Kind,
    },
    /// When we expect to see a loop (typically after a label).
    #[error("expected loop but got `{actual}")]
    ExpectedLoop {
        /// Span that caused the error.
        span: Span,
        /// The kind of the actual token we saw.
        actual: Kind,
    },
    /// Expected a block expression but got something else.
    #[error("expected block expression but got `{actual}`")]
    ExpectedBlockExpr {
        /// Span that caused the error.
        span: Span,
        /// The kind of the actual token we saw.
        actual: Kind,
    },
    /// Encountered an unexpected character.
    #[error("unexpected character `{c}`")]
    UnexpectedChar {
        /// Span that caused the error.
        span: Span,
        /// Character encountered.
        c: char,
    },
    /// Expected a number, but got something else.
    #[error("expected number but got `{actual}`")]
    ExpectedNumber {
        /// Span that caused the error.
        span: Span,
        /// The kind of the actual token we saw.
        actual: Kind,
    },
    /// Expected a byte, but got something else.
    #[error("expected byte but got `{actual}`")]
    ExpectedByte {
        /// Span that caused the error.
        span: Span,
        /// The kind of the actual token we saw.
        actual: Kind,
    },
    /// Expected a char, but got something else.
    #[error("expected char but got `{actual}`")]
    ExpectedChar {
        /// Span that caused the error.
        span: Span,
        /// The kind of the actual token we saw.
        actual: Kind,
    },
    /// Expected a string, but got something else.
    #[error("expected string but got `{actual}`")]
    ExpectedString {
        /// Span that caused the error.
        span: Span,
        /// The actual token kind which was not a string.
        actual: Kind,
    },
    /// Expected an operator but got something else.
    #[error("expected operator (`+`, `-`, `/`, `*`) but got `{actual}`")]
    ExpectedOperator {
        /// The location of the unexpected operator.
        span: Span,
        /// The actual token that was encountered instead of an operator.
        actual: Kind,
    },
    /// Expected a boolean literal.
    #[error("expected `true` or `false` but got `{actual}`")]
    ExpectedBool {
        /// The location of the unexpected token.
        span: Span,
        /// The actual token that was encountered.
        actual: Kind,
    },
    /// Expected a valid object key.
    #[error("expected an object key (string or identifier) but got `{actual}`")]
    ExpectedLitObjectKey {
        /// The location of the unexpected token.
        span: Span,
        /// The actual token that was encountered.
        actual: Kind,
    },
    /// Expected a unary operator.
    #[error("expected unary operator (`!`) but got `{actual}`")]
    ExpectedUnaryOperator {
        /// The span that caused the error.
        span: Span,
        /// The actual token.
        actual: Kind,
    },
    /// Expression group required to break precedence.
    #[error("group required in expression to determine precedence")]
    PrecedenceGroupRequired {
        /// Span that caused the error.
        span: Span,
    },
    /// Attempt to read a slice which doesn't exist.
    #[error("tried to read bad slice from source `{span}`")]
    BadSlice {
        /// The slice we tried to read.
        span: Span,
    },
    /// Encountered a bad string escape sequence.
    #[error("bad escape sequence")]
    BadEscapeSequence {
        /// Span of the illegal escape sequence.
        span: Span,
    },
    /// Tried to resolve an illegal number literal.
    #[error("number literal not valid")]
    BadNumberLiteral {
        /// Span of the illegal number literal.
        span: Span,
    },
    /// Number out of bounds.
    #[error("number literal out of bounds `-9223372036854775808` to `9223372036854775807`")]
    BadNumberOutOfBounds {
        /// Span of the illegal number literal.
        span: Span,
    },
    /// A bad character literal.
    #[error("bad character literal")]
    BadCharLiteral {
        /// Span containing the bad character literal.
        span: Span,
    },
    /// A bad byte literal.
    #[error("bad byte literal")]
    BadByteLiteral {
        /// Span containing the bad byte literal.
        span: Span,
    },
    /// We tried to parse a unicode escape in a byte sequence.
    #[error("unicode escapes are not supported as a byte or byte string")]
    UnicodeEscapeNotSupported {
        /// Where the bad escape is.
        span: Span,
    },
    /// Error when we encounter a bad unicode escape.
    #[error("bad unicode escape")]
    BadUnicodeEscape {
        /// Where the bad escape is.
        span: Span,
    },
    /// Error when we encounter a bad byte escape in bounds.
    #[error(
        "this form of character escape may only be used with characters in the range [\\x00-\\x7f]"
    )]
    UnsupportedUnicodeByteEscape {
        /// Where the bad escape is.
        span: Span,
    },
    /// Error when we encounter a bad byte escape in bounds.
    #[error(
        "this form of byte escape may only be used with characters in the range [\\x00-\\xff]"
    )]
    UnsupportedByteEscape {
        /// Where the bad escape is.
        span: Span,
    },
    /// Error when we encounter a bad byte escape.
    #[error("bad byte escape")]
    BadByteEscape {
        /// Where the bad escape is.
        span: Span,
    },
    /// When we encounter an invalid template literal.
    #[error("invalid template literal")]
    InvalidTemplateLiteral {
        /// The span where the error occured.
        span: Span,
    },
    /// When we encounter an unescaped closing brace `}`.
    #[error("closing braces must be escaped inside of templates with `\\}}`")]
    UnexpectedCloseBrace {
        /// Where the brace was encountered.
        span: Span,
    },
    /// When we encounter an expression that cannot be used in a chained manner.
    #[error("unsupported field access")]
    UnsupportedFieldAccess {
        /// Span of the expression that can't be used in a chain.
        span: Span,
    },
    /// Trying to use a token that is not supported as a function argument.
    #[error("not supported as a function or closure argument")]
    ExpectedFunctionArgument {
        /// Where the argument is.
        span: Span,
    },
}

impl ParseError {
    /// Get the span for the parse error.
    pub fn span(&self) -> Span {
        match *self {
            Self::UnexpectedEof { span, .. } => span,
            Self::ExpectedEof { span, .. } => span,
            Self::ExpectedStringEscape { span, .. } => span,
            Self::UnterminatedStrLit { span, .. } => span,
            Self::UnterminatedCharLit { span, .. } => span,
            Self::UnterminatedByteLit { span, .. } => span,
            Self::ExpectedCharEscape { span, .. } => span,
            Self::ExpectedCharClose { span, .. } => span,
            Self::ExpectedByteClose { span, .. } => span,
            Self::ExpectedTemplateClose { span, .. } => span,
            Self::TokenMismatch { span, .. } => span,
            Self::ExpectedPatError { span, .. } => span,
            Self::ExpectedExpr { span, .. } => span,
            Self::ExpectedEnumVariant { span, .. } => span,
            Self::ExpectedLoop { span, .. } => span,
            Self::ExpectedBlockExpr { span, .. } => span,
            Self::UnexpectedChar { span, .. } => span,
            Self::ExpectedNumber { span, .. } => span,
            Self::ExpectedByte { span, .. } => span,
            Self::ExpectedChar { span, .. } => span,
            Self::ExpectedString { span, .. } => span,
            Self::ExpectedOperator { span, .. } => span,
            Self::ExpectedBool { span, .. } => span,
            Self::ExpectedLitObjectKey { span, .. } => span,
            Self::ExpectedUnaryOperator { span, .. } => span,
            Self::PrecedenceGroupRequired { span, .. } => span,
            Self::BadSlice { span, .. } => span,
            Self::BadEscapeSequence { span, .. } => span,
            Self::BadNumberLiteral { span, .. } => span,
            Self::BadNumberOutOfBounds { span, .. } => span,
            Self::BadCharLiteral { span, .. } => span,
            Self::BadByteLiteral { span, .. } => span,
            Self::UnicodeEscapeNotSupported { span, .. } => span,
            Self::BadUnicodeEscape { span, .. } => span,
            Self::UnsupportedUnicodeByteEscape { span, .. } => span,
            Self::UnsupportedByteEscape { span, .. } => span,
            Self::BadByteEscape { span, .. } => span,
            Self::InvalidTemplateLiteral { span, .. } => span,
            Self::UnexpectedCloseBrace { span, .. } => span,
            Self::UnsupportedFieldAccess { span, .. } => span,
            Self::ExpectedFunctionArgument { span, .. } => span,
            Self::ExpectedDeclUseImportComponent { span, .. } => span,
        }
    }
}

/// Error when encoding AST.
#[derive(Debug, Error)]
pub enum CompileError {
    /// An internal encoder invariant was broken.
    #[error("internal compiler error: {msg}")]
    Internal {
        /// The message of the variant.
        msg: &'static str,
        /// Where the invariant was broken.
        span: Span,
    },
    /// Unit error from runestick encoding.
    #[error("unit construction error: {error}")]
    UnitError {
        /// Source error.
        #[from]
        error: runestick::UnitError,
    },
    /// Error for resolving values from source files.
    #[error("{error}")]
    ParseError {
        /// Source error.
        #[from]
        error: ParseError,
    },
    /// Error when trying to index a duplicate item.
    #[error("found conflicting item `{existing}`")]
    ItemConflict {
        /// Where the conflicting item was found.
        span: Span,
        /// The name of the conflicting item.
        existing: Item,
    },
    /// Error for variable conflicts.
    #[error("variable `{name}` conflicts")]
    VariableConflict {
        /// Span where the error occured.
        span: Span,
        /// Name of the conflicting variable.
        name: String,
        /// The span where the variable was already present.
        existing_span: Span,
    },
    /// Error for missing local variables.
    #[error("missing variable `{name}`")]
    MissingLocal {
        /// Span where the error occured.
        span: Span,
        /// Name of the missing variable.
        name: String,
    },
    /// Error for missing types.
    #[error("no type matching `{item}`")]
    MissingType {
        /// Span where the error occured.
        span: Span,
        /// Name of the missing type.
        item: Item,
    },
    /// Tried to use a module that was missing.
    #[error("missing module `{item}`")]
    MissingModule {
        /// The span of the missing module.
        span: Span,
        /// The name of the missing module.
        item: Item,
    },
    /// A specific label is missing.
    #[error("label not found in scope")]
    MissingLabel {
        /// The span of the missing label.
        span: Span,
    },
    /// Unsupported wildcard component in use.
    #[error("wildcard support not supported in this position")]
    UnsupportedWildcard {
        /// Where the wildcard import is.
        span: Span,
    },
    /// Tried to declare an instance function on a type for which it is not
    /// supported.
    #[error("cannot declare instance functions for type `{meta}`")]
    UnsupportedInstanceFunction {
        /// The span where we tried to declare an instance function.
        span: Span,
        /// The meta we tried to declare an instance function for.
        meta: Meta,
    },
    /// Tried to treat something as a value which is not supported.
    #[error("`{meta}` cannot be used as a value")]
    UnsupportedValue {
        /// The span of the error.
        span: Span,
        /// The meta we tried to treat as a value.
        meta: Meta,
    },
    /// Tried to treat something as a type which is not supported.
    #[error("`{meta}` cannot be used as a type")]
    UnsupportedType {
        /// The span of the error.
        span: Span,
        /// The meta we tried to treat as a type.
        meta: Meta,
    },
    /// Argument in unsupported position.
    #[error("argument not supported here")]
    UnsupportedArgument {
        /// Where it occured.
        span: Span,
    },
    /// `self` occured in an unsupported position.
    #[error("`self` not supported here")]
    UnsupportedSelf {
        /// Where it occured.
        span: Span,
    },
    /// Encountered a unary operator we can't encode.
    #[error("unsupported unary operator `{op}`")]
    UnsupportedUnaryOp {
        /// The span of the illegal operator use.
        span: Span,
        /// The operator.
        op: ast::UnaryOp,
    },
    /// Encountered a binary operator we can't encode.
    #[error("unsupported binary operator `{op}`")]
    UnsupportedBinaryOp {
        /// The span of the illegal call.
        span: Span,
        /// The operator.
        op: ast::BinOp,
    },
    /// Cannot crate object literal of the given type.
    #[error("type `{item}` is not an object")]
    UnsupportedLitObject {
        /// The span of the unsupported object.
        span: Span,
        /// The path to the unsupported object.
        item: Item,
    },
    /// Key is not present in the given type literal.
    #[error("missing field `{field}` in declaration of `{item}`")]
    LitObjectMissingField {
        /// The span of the unsupported object.
        span: Span,
        /// They key that didn't exist.
        field: String,
        /// The related item.
        item: Item,
    },
    /// Key is not present in the given type literal.
    #[error("`{field}` is not a field in `{item}`")]
    LitObjectNotField {
        /// The span of the unsupported object.
        span: Span,
        /// They key that is not a field.
        field: String,
        /// The related item.
        item: Item,
    },
    /// When we encounter an expression that cannot be assigned to.
    #[error("cannot assign to expression")]
    UnsupportedAssignExpr {
        /// The thing being assigned to.
        span: Span,
    },
    /// Unsupported assignment operator.
    #[error("unsupported operator `{op}` in assignment")]
    UnsupportedAssignBinOp {
        /// The assign expression.
        span: Span,
        /// The unsupported operator.
        op: ast::BinOp,
    },
    /// When we encounter an expression that doesn't have a stack location and
    /// can't be referenced.
    #[error("cannot take reference of expression")]
    UnsupportedRef {
        /// The thing we are taking the reference of.
        span: Span,
    },
    /// Await has been used in a position where it's not supported.
    #[error("`await` expression is not supported in this location")]
    UnsupportedAwait {
        /// The location of the await.
        span: Span,
    },
    /// Using a pattern that is not supported in a select.
    #[error("unsupported select pattern")]
    UnsupportedSelectPattern {
        /// The span of the pattern.
        span: Span,
    },
    /// Unsupported field access.
    #[error("unsupported field access")]
    UnsupportedFieldAccess {
        /// The field access expression.
        span: Span,
    },
    /// A meta item that is not supported in the given pattern position.
    #[error("wrong number of arguments, expected `{expected}` but got `{actual}`")]
    UnsupportedArgumentCount {
        /// The span which the error occured.
        span: Span,
        /// The meta item we tried to use as a pattern.
        meta: Meta,
        /// The expected number of arguments.
        expected: usize,
        /// The actual number of arguments.
        actual: usize,
    },
    /// A meta item that is not supported in the given pattern position.
    #[error("`{meta}` is not supported in a pattern like this")]
    UnsupportedMetaPattern {
        /// The meta item we tried to use as a pattern.
        meta: Meta,
        /// The span which the error occured.
        span: Span,
    },
    /// A meta item that is not supported in the given closure position.
    #[error("`{meta}` is not supported as a closure")]
    UnsupportedMetaClosure {
        /// The meta item we tried to use as a pattern.
        meta: Meta,
        /// The span which the error occured.
        span: Span,
    },
    /// The pattern is not supported.
    #[error("item is not supported in a pattern")]
    UnsupportedPattern {
        /// Span where the error occured.
        span: Span,
    },
    /// The pattern is not supported as a binding.
    #[error("not a valid binding")]
    UnsupportedBinding {
        /// Span where the error occured.
        span: Span,
    },
    /// Error raised when trying to use a break outside of a loop.
    #[error("break expressions cannot be used as a value")]
    BreakOutsideOfLoop {
        /// The span of the illegal break.
        span: Span,
    },
    /// An error raised when attempting to return locally created references
    /// from a function.
    #[error("cannot return locally created references")]
    ReturnLocalReferences {
        /// The span which we try to return from.
        block: Span,
        /// The span at which we tried to return.
        span: Span,
        /// The references we tried to return.
        references_at: Vec<Span>,
    },
    /// Attempting to use a float in a match pattern.
    #[error("floating point numbers cannot be used in patterns")]
    MatchFloatInPattern {
        /// Where the float was used.
        span: Span,
    },
    /// Attempting to create an object with a duplicate object key.
    #[error("duplicate key in literal object")]
    DuplicateObjectKey {
        /// Where the key was re-defined.
        span: Span,
        /// Where the object key exists previously.
        existing: Span,
        /// The object being defined.
        object: Span,
    },
    /// Attempt to call something that is not a function.
    #[error("`{item}` is not a function")]
    MissingFunction {
        /// The span of the unsupported function call.
        span: Span,
        /// The item we're trying to call.
        item: Item,
    },
    /// Attempt to yield outside of a function or a closure.
    #[error("`yield` must be used in function or closure")]
    YieldOutsideFunction {
        /// The span of the unsupported yield.
        span: Span,
    },
    /// Attempt to declare a function which takes `self` outside of an `impl`
    /// block.
    #[error("instance function declared outside of `impl` block")]
    InstanceFunctionOutsideImpl {
        /// Where the function is declared.
        span: Span,
    },
    /// Attempt to declare an async function with `yield`.
    #[error("async generators are not supported")]
    UnsupportedAsyncGenerator {
        /// The span of the async generator.
        span: Span,
    },
    /// Import doesn't exist.
    #[error("import `{item}` (imported in prelude) does not exist")]
    MissingPreludeModule {
        /// The item that didn't exist.
        item: Item,
    },
}

impl CompileError {
    /// Construct an internal error.
    ///
    /// This should be used for programming invariants of the encoder which are
    /// broken for some reason.
    pub fn internal(msg: &'static str, span: Span) -> Self {
        Self::Internal { msg, span }
    }
}

impl CompileError {
    /// Get the span for the error.
    pub fn span(&self) -> Span {
        match *self {
            Self::UnitError { .. } => Span::default(),
            Self::Internal { span, .. } => span,
            Self::ParseError { error, .. } => error.span(),
            Self::ItemConflict { span, .. } => span,
            Self::VariableConflict { span, .. } => span,
            Self::MissingLocal { span, .. } => span,
            Self::MissingType { span, .. } => span,
            Self::MissingModule { span, .. } => span,
            Self::MissingLabel { span, .. } => span,
            Self::UnsupportedWildcard { span, .. } => span,
            Self::UnsupportedRef { span, .. } => span,
            Self::UnsupportedAwait { span, .. } => span,
            Self::UnsupportedInstanceFunction { span, .. } => span,
            Self::UnsupportedValue { span, .. } => span,
            Self::UnsupportedType { span, .. } => span,
            Self::UnsupportedArgument { span, .. } => span,
            Self::UnsupportedSelf { span, .. } => span,
            Self::UnsupportedUnaryOp { span, .. } => span,
            Self::UnsupportedBinaryOp { span, .. } => span,
            Self::UnsupportedLitObject { span, .. } => span,
            Self::UnsupportedAssignExpr { span, .. } => span,
            Self::UnsupportedAssignBinOp { span, .. } => span,
            Self::UnsupportedSelectPattern { span, .. } => span,
            Self::UnsupportedFieldAccess { span, .. } => span,
            Self::UnsupportedArgumentCount { span, .. } => span,
            Self::UnsupportedMetaPattern { span, .. } => span,
            Self::UnsupportedMetaClosure { span, .. } => span,
            Self::UnsupportedPattern { span, .. } => span,
            Self::UnsupportedBinding { span, .. } => span,
            Self::BreakOutsideOfLoop { span, .. } => span,
            Self::ReturnLocalReferences { span, .. } => span,
            Self::MatchFloatInPattern { span, .. } => span,
            Self::DuplicateObjectKey { span, .. } => span,
            Self::LitObjectMissingField { span, .. } => span,
            Self::LitObjectNotField { span, .. } => span,
            Self::MissingFunction { span, .. } => span,
            Self::YieldOutsideFunction { span, .. } => span,
            Self::InstanceFunctionOutsideImpl { span, .. } => span,
            Self::UnsupportedAsyncGenerator { span, .. } => span,
            Self::MissingPreludeModule { .. } => Span::empty(),
        }
    }
}