1use core::convert::Infallible;
2use core::fmt;
3
4#[cfg(feature = "std")]
5use std::io;
6#[cfg(feature = "std")]
7use std::path::PathBuf;
8
9use crate as rune;
10use crate::alloc::prelude::*;
11use crate::alloc::{self, Box, String, Vec};
12use crate::ast;
13use crate::ast::unescape;
14use crate::ast::{Span, Spanned};
15use crate::compile::ir;
16use crate::compile::{HasSpan, Location, MetaInfo, Visibility};
17use crate::hash::TooManyParameters;
18use crate::indexing::items::{GuardMismatch, MissingLastId};
19use crate::macros::{SyntheticId, SyntheticKind};
20use crate::parse::{Expectation, IntoExpectation, LexerMode};
21use crate::runtime::debug::DebugSignature;
22use crate::runtime::unit::EncodeError;
23use crate::runtime::{
24 AccessError, AnyObjError, ExpectedType, RuntimeError, TypeInfo, TypeOf, VmError,
25};
26#[cfg(feature = "std")]
27use crate::source;
28use crate::{Hash, Item, ItemBuf, SourceId};
29
30#[derive(Debug)]
32pub struct Error {
33 span: Span,
35 kind: rust_alloc::boxed::Box<ErrorKind>,
38}
39
40impl Error {
41 pub(crate) fn new<S, K>(span: S, kind: K) -> Self
43 where
44 S: Spanned,
45 ErrorKind: From<K>,
46 {
47 Self {
48 span: span.span(),
49 kind: rust_alloc::boxed::Box::new(ErrorKind::from(kind)),
50 }
51 }
52
53 pub fn msg<S, M>(span: S, message: M) -> Self
55 where
56 S: Spanned,
57 M: fmt::Display + fmt::Debug + Send + Sync + 'static,
58 {
59 Self {
60 span: span.span(),
61 kind: rust_alloc::boxed::Box::new(ErrorKind::msg(message)),
62 }
63 }
64
65 #[cfg(feature = "emit")]
67 pub(crate) fn kind(&self) -> &ErrorKind {
68 &self.kind
69 }
70
71 #[cfg(test)]
73 pub(crate) fn into_kind(self) -> ErrorKind {
74 *self.kind
75 }
76}
77
78impl Spanned for Error {
79 #[inline]
80 fn span(&self) -> Span {
81 self.span
82 }
83}
84
85impl core::error::Error for Error {
86 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
87 self.kind.source()
88 }
89}
90
91impl fmt::Display for Error {
92 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93 fmt::Display::fmt(&self.kind, f)
94 }
95}
96
97impl From<Infallible> for Error {
98 #[inline]
99 fn from(value: Infallible) -> Self {
100 match value {}
101 }
102}
103
104impl<S, E> From<HasSpan<S, E>> for Error
105where
106 S: Spanned,
107 ErrorKind: From<E>,
108{
109 fn from(spanned: HasSpan<S, E>) -> Self {
110 Self::new(spanned.span(), spanned.into_inner())
111 }
112}
113
114impl From<TooManyParameters> for ErrorKind {
115 #[inline]
116 fn from(error: TooManyParameters) -> Self {
117 ErrorKind::TooManyParameters(error)
118 }
119}
120
121impl From<fmt::Error> for ErrorKind {
122 #[inline]
123 fn from(fmt::Error: fmt::Error) -> Self {
124 ErrorKind::FormatError
125 }
126}
127
128impl From<syntree::Error<alloc::Error>> for ErrorKind {
129 #[inline]
130 fn from(error: syntree::Error<alloc::Error>) -> Self {
131 ErrorKind::Syntree(error)
132 }
133}
134
135#[cfg(feature = "std")]
136impl From<io::Error> for ErrorKind {
137 #[inline]
138 fn from(error: io::Error) -> Self {
139 Self::from(anyhow::Error::from(error))
140 }
141}
142
143impl From<ir::scopes::MissingLocal> for ErrorKind {
144 #[inline]
145 fn from(error: ir::scopes::MissingLocal) -> Self {
146 ErrorKind::MissingLocal { name: error.0 }
147 }
148}
149
150#[cfg(feature = "anyhow")]
151impl From<anyhow::Error> for ErrorKind {
152 #[inline]
153 fn from(error: anyhow::Error) -> Self {
154 ErrorKind::Custom { error }
155 }
156}
157
158impl From<&'static str> for ErrorKind {
159 #[inline]
160 fn from(value: &'static str) -> Self {
161 ErrorKind::msg(value)
162 }
163}
164
165impl<T> From<Box<T>> for ErrorKind
167where
168 ErrorKind: From<T>,
169{
170 #[inline]
171 fn from(kind: Box<T>) -> Self {
172 ErrorKind::from(Box::into_inner(kind))
173 }
174}
175
176impl<T> From<rust_alloc::boxed::Box<T>> for ErrorKind
178where
179 ErrorKind: From<T>,
180{
181 #[inline]
182 fn from(kind: rust_alloc::boxed::Box<T>) -> Self {
183 ErrorKind::from(*kind)
184 }
185}
186
187impl From<ExpectedType> for ErrorKind {
188 #[inline]
189 fn from(error: ExpectedType) -> Self {
190 ErrorKind::ExpectedType {
191 actual: error.actual,
192 expected: error.expected,
193 }
194 }
195}
196
197impl From<alloc::Error> for rust_alloc::boxed::Box<ErrorKind> {
198 #[inline]
199 fn from(error: alloc::Error) -> Self {
200 rust_alloc::boxed::Box::new(ErrorKind::from(error))
201 }
202}
203
204impl Error {
205 pub fn expected_meta<S>(spanned: S, meta: MetaInfo, expected: &'static str) -> Self
207 where
208 S: Spanned,
209 {
210 Self::new(spanned, ErrorKind::ExpectedMeta { meta, expected })
211 }
212
213 pub(crate) fn expected<A, E>(actual: A, expected: E) -> Self
215 where
216 A: IntoExpectation + Spanned,
217 E: IntoExpectation,
218 {
219 Self::new(
220 actual.span(),
221 ErrorKind::Expected {
222 actual: actual.into_expectation(),
223 expected: expected.into_expectation(),
224 },
225 )
226 }
227
228 pub(crate) fn unsupported<T, E>(actual: T, what: E) -> Self
230 where
231 T: Spanned,
232 E: IntoExpectation,
233 {
234 Self::new(
235 actual.span(),
236 ErrorKind::Unsupported {
237 what: what.into_expectation(),
238 },
239 )
240 }
241
242 pub(crate) fn expected_type<E>(spanned: impl Spanned, actual: TypeInfo) -> Self
244 where
245 E: TypeOf,
246 {
247 Self::new(
248 spanned,
249 IrErrorKind::Expected {
250 expected: TypeInfo::from(E::STATIC_TYPE_INFO),
251 actual,
252 },
253 )
254 }
255}
256
257#[derive(Debug)]
259#[non_exhaustive]
260pub(crate) enum ErrorKind {
261 #[cfg(feature = "anyhow")]
262 Custom {
263 error: anyhow::Error,
264 },
265 #[cfg(not(feature = "anyhow"))]
266 Custom {
267 error: String,
268 },
269 AllocError {
270 error: alloc::Error,
271 },
272 IrError(IrErrorKind),
273 MetaError(MetaError),
274 AccessError(AccessError),
275 VmError(VmError),
276 EncodeError(EncodeError),
277 MissingLastId(MissingLastId),
278 GuardMismatch(GuardMismatch),
279 MissingScope(MissingScope),
280 PopError(PopError),
281 UnescapeError(unescape::ErrorKind),
282 Syntree(syntree::Error<alloc::Error>),
283 TooManyParameters(TooManyParameters),
284 FormatError,
285 #[cfg(feature = "std")]
286 SourceError {
287 path: PathBuf,
288 error: source::FromPathError,
289 },
290 ExpectedType {
291 actual: TypeInfo,
292 expected: TypeInfo,
293 },
294 Expected {
295 actual: Expectation,
296 expected: Expectation,
297 },
298 Unsupported {
299 what: Expectation,
300 },
301 #[cfg(feature = "std")]
302 ModNotFound {
303 path: PathBuf,
304 },
305 ModAlreadyLoaded {
306 item: ItemBuf,
307 #[cfg(feature = "emit")]
308 existing: (SourceId, Span),
309 },
310 MissingMacro {
311 item: ItemBuf,
312 },
313 MissingSelf,
314 MissingLocal {
315 name: Box<str>,
316 },
317 MissingItem {
318 item: ItemBuf,
319 },
320 MissingItemHash {
321 hash: Hash,
322 },
323 MissingItemParameters {
324 item: ItemBuf,
325 parameters: [Option<Hash>; 2],
326 },
327 UnsupportedGlobal,
328 UnsupportedModuleSource,
329 #[cfg(feature = "std")]
330 UnsupportedModuleRoot {
331 root: PathBuf,
332 },
333 #[cfg(feature = "std")]
334 UnsupportedModuleItem {
335 item: ItemBuf,
336 },
337 UnsupportedSelf,
338 UnsupportedUnaryOp {
339 op: ast::UnOp,
340 },
341 UnsupportedBinaryOp {
342 op: ast::BinOp,
343 },
344 UnsupportedLitObject {
345 meta: MetaInfo,
346 },
347 LitObjectMissingField {
348 field: Box<str>,
349 item: ItemBuf,
350 },
351 LitObjectNotField {
352 field: Box<str>,
353 item: ItemBuf,
354 },
355 UnsupportedAssignExpr,
356 UnsupportedBinaryExpr,
357 UnsupportedRef,
358 BadArgumentCount {
359 expected: usize,
360 actual: usize,
361 },
362 UnsupportedPatternExpr,
363 UnsupportedBinding,
364 DuplicateObjectKey {
365 #[cfg(feature = "emit")]
366 existing: Span,
367 #[cfg(feature = "emit")]
368 object: Span,
369 },
370 InstanceFunctionOutsideImpl,
371 UnsupportedTupleIndex {
372 number: ast::Number,
373 },
374 BreakUnsupported,
375 BreakUnsupportedValue,
376 ContinueUnsupported,
377 ContinueUnsupportedBlock,
378 SelectMultipleDefaults,
379 ExpectedBlockSemiColon {
380 #[cfg(feature = "emit")]
381 followed_span: Span,
382 },
383 FnConstAsyncConflict,
384 BlockConstAsyncConflict,
385 ClosureKind,
386 UnsupportedSelfType,
387 UnsupportedSuper,
388 UnsupportedSuperInSelfType,
389 UnsupportedAfterGeneric,
390 IllegalUseSegment,
391 UseAliasNotSupported,
392 FunctionConflict {
393 existing: DebugSignature,
394 },
395 FunctionReExportConflict {
396 hash: Hash,
397 },
398 ConstantConflict {
399 hash: Hash,
400 },
401 StaticStringMissing {
402 hash: Hash,
403 slot: usize,
404 },
405 StaticBytesMissing {
406 hash: Hash,
407 slot: usize,
408 },
409 StaticStringHashConflict {
410 hash: Hash,
411 current: String,
412 existing: String,
413 },
414 StaticBytesHashConflict {
415 hash: Hash,
416 current: Vec<u8>,
417 existing: Vec<u8>,
418 },
419 StaticObjectKeysMissing {
420 hash: Hash,
421 slot: usize,
422 },
423 StaticObjectKeysHashConflict {
424 hash: Hash,
425 current: Box<[String]>,
426 existing: Box<[String]>,
427 },
428 ConflictingLabels {
429 #[cfg_attr(not(feature = "emit"), allow(unused))]
430 existing: Span,
431 },
432 DuplicateSelectDefault {
433 #[cfg_attr(not(feature = "emit"), allow(unused))]
434 existing: Span,
435 },
436 MissingLabel {
437 label: Box<str>,
438 },
439 ExpectedLeadingPathSegment,
440 UnsupportedVisibility,
441 ExpectedMeta {
442 expected: &'static str,
443 meta: MetaInfo,
444 },
445 NoSuchBuiltInMacro {
446 name: Box<str>,
447 },
448 VariableMoved {
449 #[cfg(feature = "emit")]
450 moved_at: Span,
451 },
452 UnsupportedGenerics,
453 NestedTest {
454 #[cfg(feature = "emit")]
455 nested_span: Span,
456 },
457 NestedBench {
458 #[cfg(feature = "emit")]
459 nested_span: Span,
460 },
461 MissingFunctionHash {
462 hash: Hash,
463 },
464 FunctionConflictHash {
465 hash: Hash,
466 },
467 PatternMissingFields {
468 item: ItemBuf,
469 #[cfg(feature = "emit")]
470 fields: Box<[Box<str>]>,
471 },
472 MissingLabelLocation {
473 name: &'static str,
474 index: usize,
475 },
476 MaxMacroRecursion {
477 depth: usize,
478 max: usize,
479 },
480 YieldInConst,
481 AwaitInConst,
482 AwaitOutsideAsync,
483 ExpectedEof {
484 actual: ast::Kind,
485 },
486 UnexpectedEof,
487 BadLexerMode {
488 actual: LexerMode,
489 expected: LexerMode,
490 },
491 ExpectedEscape,
492 UnterminatedStrLit,
493 UnterminatedByteStrLit,
494 UnterminatedCharLit,
495 UnterminatedByteLit,
496 ExpectedCharClose,
497 ExpectedCharOrLabel,
498 ExpectedByteClose,
499 UnexpectedChar {
500 c: char,
501 },
502 PrecedenceGroupRequired,
503 BadSignedOutOfBounds {
504 size: ast::NumberSize,
505 },
506 BadUnsignedOutOfBounds {
507 size: ast::NumberSize,
508 },
509 BadFieldAccess,
510 ExpectedMacroCloseDelimiter {
511 expected: ast::Kind,
512 actual: ast::Kind,
513 },
514 MultipleMatchingAttributes {
515 name: &'static str,
516 },
517 MissingSourceId {
518 source_id: SourceId,
519 },
520 ExpectedMultilineCommentTerm,
521 BadSlice,
522 BadSyntheticId {
523 kind: SyntheticKind,
524 id: SyntheticId,
525 },
526 BadCharLiteral,
527 BadByteLiteral,
528 BadNumberLiteral,
529 AmbiguousItem {
530 item: ItemBuf,
531 #[cfg(feature = "emit")]
532 locations: Vec<(Location, ItemBuf)>,
533 },
534 AmbiguousContextItem {
535 item: ItemBuf,
536 #[cfg(feature = "emit")]
537 infos: Box<[MetaInfo]>,
538 },
539 NotVisible {
540 #[cfg(feature = "emit")]
541 chain: Vec<Location>,
542 #[cfg(feature = "emit")]
543 location: Location,
544 visibility: Visibility,
545 item: ItemBuf,
546 from: ItemBuf,
547 },
548 NotVisibleMod {
549 #[cfg(feature = "emit")]
550 chain: Vec<Location>,
551 #[cfg(feature = "emit")]
552 location: Location,
553 visibility: Visibility,
554 item: ItemBuf,
555 from: ItemBuf,
556 },
557 MissingMod {
558 item: ItemBuf,
559 },
560 ImportCycle {
561 #[cfg(feature = "emit")]
562 path: Vec<ImportStep>,
563 },
564 ImportRecursionLimit {
565 count: usize,
566 #[allow(unused)]
567 path: Vec<ImportStep>,
568 },
569 LastUseComponent,
570 RttiConflict {
571 hash: Hash,
572 },
573 TypeRttiConflict {
574 hash: Hash,
575 },
576 ArenaWriteSliceOutOfBounds {
577 index: usize,
578 },
579 ArenaAllocError {
580 requested: usize,
581 },
582 UnsupportedPatternRest,
583 UnsupportedMut,
584 UnsupportedSuffix,
585 ClosureInConst,
586 AsyncBlockInConst,
587 #[cfg(feature = "fmt")]
588 BadSpan {
589 len: usize,
590 },
591 UnexpectedEndOfSyntax {
592 inside: Expectation,
593 },
594 UnexpectedEndOfSyntaxWith {
595 inside: Expectation,
596 expected: Expectation,
597 },
598 ExpectedSyntaxEnd {
599 inside: Expectation,
600 actual: Expectation,
601 },
602 #[cfg(feature = "fmt")]
603 BadIndent {
604 level: isize,
605 indent: usize,
606 },
607 ExpectedSyntax {
608 expected: Expectation,
609 actual: Expectation,
610 },
611 ExpectedSyntaxIn {
612 inside: Expectation,
613 expected: Expectation,
614 actual: Expectation,
615 },
616 ExpectedOne {
617 inside: Expectation,
618 expected: Expectation,
619 },
620 ExpectedAtMostOne {
621 inside: Expectation,
622 expected: Expectation,
623 count: usize,
624 },
625 ExpectedAtLeastOne {
626 inside: Expectation,
627 expected: Expectation,
628 },
629 #[cfg(feature = "fmt")]
630 UnsupportedDelimiter {
631 expectation: Expectation,
632 },
633}
634
635impl ErrorKind {
636 #[inline]
637 #[cfg(feature = "anyhow")]
638 pub(crate) fn msg<M>(message: M) -> Self
639 where
640 M: fmt::Display + fmt::Debug + Send + Sync + 'static,
641 {
642 Self::Custom {
643 error: anyhow::Error::msg(message),
644 }
645 }
646
647 #[inline]
648 #[cfg(not(feature = "anyhow"))]
649 pub(crate) fn msg<M>(message: M) -> Self
650 where
651 M: fmt::Display + fmt::Debug + Send + Sync + 'static,
652 {
653 match crate::alloc::fmt::try_format(format_args!("{message}")) {
654 Ok(string) => Self::Custom { error: string },
655 Err(error) => Self::AllocError { error },
656 }
657 }
658}
659
660impl core::error::Error for ErrorKind {
661 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
662 match self {
663 #[cfg(feature = "anyhow")]
664 ErrorKind::Custom { error } => Some(error.as_ref()),
665 ErrorKind::IrError(source) => Some(source),
666 ErrorKind::MetaError(source) => Some(source),
667 ErrorKind::AccessError(source) => Some(source),
668 ErrorKind::VmError(source) => Some(source),
669 ErrorKind::EncodeError(source) => Some(source),
670 ErrorKind::MissingLastId(source) => Some(source),
671 ErrorKind::GuardMismatch(source) => Some(source),
672 ErrorKind::MissingScope(source) => Some(source),
673 ErrorKind::PopError(source) => Some(source),
674 ErrorKind::UnescapeError(source) => Some(source),
675 #[cfg(feature = "std")]
676 ErrorKind::SourceError { error, .. } => Some(error),
677 _ => None,
678 }
679 }
680}
681
682impl fmt::Display for ErrorKind {
683 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
684 match self {
685 ErrorKind::Custom { error } => {
686 error.fmt(f)?;
687 }
688 ErrorKind::AllocError { error } => {
689 error.fmt(f)?;
690 }
691 ErrorKind::IrError(error) => {
692 error.fmt(f)?;
693 }
694 ErrorKind::MetaError(error) => {
695 error.fmt(f)?;
696 }
697 ErrorKind::AccessError(error) => {
698 error.fmt(f)?;
699 }
700 ErrorKind::VmError(error) => {
701 error.fmt(f)?;
702 }
703 ErrorKind::EncodeError(error) => {
704 error.fmt(f)?;
705 }
706 ErrorKind::MissingLastId(error) => {
707 error.fmt(f)?;
708 }
709 ErrorKind::GuardMismatch(error) => {
710 error.fmt(f)?;
711 }
712 ErrorKind::MissingScope(error) => {
713 error.fmt(f)?;
714 }
715 ErrorKind::PopError(error) => {
716 error.fmt(f)?;
717 }
718 ErrorKind::UnescapeError(error) => {
719 error.fmt(f)?;
720 }
721 ErrorKind::Syntree(error) => {
722 error.fmt(f)?;
723 }
724 ErrorKind::TooManyParameters(error) => {
725 error.fmt(f)?;
726 }
727 ErrorKind::FormatError => {
728 write!(f, "Formatting error")?;
729 }
730 #[cfg(feature = "std")]
731 ErrorKind::SourceError { path, error } => {
732 write!(
733 f,
734 "Failed to load source at `{path}`: {error}",
735 path = path.display(),
736 )?;
737 }
738 ErrorKind::ExpectedType { actual, expected } => {
739 write!(f, "Expected type `{expected}` but found `{actual}`")?;
740 }
741 ErrorKind::Expected { actual, expected } => {
742 write!(f, "Expected {expected} but got {actual}")?;
743 }
744 ErrorKind::Unsupported { what } => {
745 write!(f, "Unsupported {what}")?;
746 }
747 #[cfg(feature = "std")]
748 ErrorKind::ModNotFound { path } => {
749 write!(
750 f,
751 "File not found, expected a module file like `{path}.rn`",
752 path = path.display()
753 )?;
754 }
755 ErrorKind::ModAlreadyLoaded { item, .. } => {
756 write!(f, "Module `{item}` has already been loaded")?;
757 }
758 ErrorKind::MissingMacro { item } => {
759 write!(f, "Missing macro {item}")?;
760 }
761 ErrorKind::MissingSelf => write!(f, "No `self` in current context")?,
762 ErrorKind::MissingLocal { name } => {
763 write!(f, "No local variable `{name}`")?;
764 }
765 ErrorKind::MissingItem { item } => {
766 write!(f, "Missing item {item}")?;
767 }
768 ErrorKind::MissingItemHash { hash } => {
769 write!(
770 f,
771 "Tried to insert meta with hash `{hash}` which does not have an item",
772 )?;
773 }
774 ErrorKind::MissingItemParameters { item, parameters } => {
775 write!(f, "Missing item {}", ParameterizedItem(item, parameters))?;
776 }
777 ErrorKind::UnsupportedGlobal => {
778 write!(f, "Unsupported crate prefix `::`")?;
779 }
780 ErrorKind::UnsupportedModuleSource => {
781 write!(
782 f,
783 "Cannot load modules using a source without an associated URL"
784 )?;
785 }
786 #[cfg(feature = "std")]
787 ErrorKind::UnsupportedModuleRoot { root } => {
788 write!(
789 f,
790 "Cannot load modules relative to `{root}`",
791 root = root.display()
792 )?;
793 }
794 #[cfg(feature = "std")]
795 ErrorKind::UnsupportedModuleItem { item } => {
796 write!(f, "Cannot load module for `{item}`")?;
797 }
798 ErrorKind::UnsupportedSelf => {
799 write!(f, "Keyword `self` not supported here")?;
800 }
801 ErrorKind::UnsupportedUnaryOp { op } => {
802 write!(f, "Unsupported unary operator `{op}`")?;
803 }
804 ErrorKind::UnsupportedBinaryOp { op } => {
805 write!(f, "Unsupported binary operator `{op}`")?;
806 }
807 ErrorKind::UnsupportedLitObject { meta } => {
808 write!(f, "Item `{meta}` is not an object")?;
809 }
810 ErrorKind::LitObjectMissingField { field, item } => {
811 write!(f, "Missing field `{field}` in declaration of `{item}`")?;
812 }
813 ErrorKind::LitObjectNotField { field, item } => {
814 write!(f, "Field `{field}` is not a field in `{item}`")?;
815 }
816 ErrorKind::UnsupportedAssignExpr => {
817 write!(f, "Cannot assign to expression")?;
818 }
819 ErrorKind::UnsupportedBinaryExpr => {
820 write!(f, "Unsupported binary expression")?;
821 }
822 ErrorKind::UnsupportedRef => {
823 write!(f, "Cannot take reference of expression")?;
824 }
825 ErrorKind::BadArgumentCount { expected, actual } => {
826 write!(f, "Wrong number of arguments {actual}, expected {expected}",)?;
827 }
828 ErrorKind::UnsupportedPatternExpr => {
829 write!(f, "This kind of expression is not supported as a pattern")?;
830 }
831 ErrorKind::UnsupportedBinding => {
832 write!(f, "Not a valid binding")?;
833 }
834 ErrorKind::DuplicateObjectKey { .. } => {
835 write!(f, "Duplicate key in literal object")?;
836 }
837 ErrorKind::InstanceFunctionOutsideImpl => {
838 write!(f, "Instance function declared outside of `impl` block")?;
839 }
840 ErrorKind::UnsupportedTupleIndex { number } => {
841 write!(f, "Unsupported tuple index `{number}`")?;
842 }
843 ErrorKind::BreakUnsupported => {
844 write!(f, "Break outside of loop")?;
845 }
846 ErrorKind::BreakUnsupportedValue => {
847 write!(
848 f,
849 "Can only break with a value inside `loop` or breakable block"
850 )?;
851 }
852 ErrorKind::ContinueUnsupported => {
853 write!(f, "Continue outside of loop")?;
854 }
855 ErrorKind::ContinueUnsupportedBlock => {
856 write!(f, "Labeled blocks cannot be `continue`'d")?;
857 }
858 ErrorKind::SelectMultipleDefaults => {
859 write!(f, "Multiple `default` branches in select")?;
860 }
861 ErrorKind::ExpectedBlockSemiColon { .. } => {
862 write!(f, "Expected expression to be terminated by a semicolon `;`")?;
863 }
864 ErrorKind::FnConstAsyncConflict => {
865 write!(
866 f,
867 "An `fn` can't both be `async` and `const` at the same time"
868 )?;
869 }
870 ErrorKind::BlockConstAsyncConflict => {
871 write!(
872 f,
873 "A block can't both be `async` and `const` at the same time"
874 )?;
875 }
876 ErrorKind::ClosureKind => {
877 write!(f, "Unsupported closure kind")?;
878 }
879 ErrorKind::UnsupportedSelfType => {
880 write!(
881 f,
882 "Keyword `Self` is only supported inside of `impl` blocks"
883 )?;
884 }
885 ErrorKind::UnsupportedSuper => {
886 write!(
887 f,
888 "Keyword `super` is not supported at the root module level"
889 )?;
890 }
891 ErrorKind::UnsupportedSuperInSelfType => {
892 write!(
893 f,
894 "Keyword `super` can't be used in paths starting with `Self`"
895 )?;
896 }
897 ErrorKind::UnsupportedAfterGeneric => {
898 write!(
899 f,
900 "This kind of path component cannot follow a generic argument"
901 )?;
902 }
903 ErrorKind::IllegalUseSegment => {
904 write!(
905 f,
906 "Another segment can't follow wildcard `*` or group imports"
907 )?;
908 }
909 ErrorKind::UseAliasNotSupported => {
910 write!(
911 f,
912 "Use aliasing is not supported for wildcard `*` or group imports"
913 )?;
914 }
915 ErrorKind::FunctionConflict { existing } => {
916 write!(
917 f,
918 "Conflicting function signature already exists `{existing}`",
919 )?;
920 }
921 ErrorKind::FunctionReExportConflict { hash } => {
922 write!(f, "Conflicting function hash already exists `{hash}`")?;
923 }
924 ErrorKind::ConstantConflict { hash } => {
925 write!(f, "Conflicting constant for hash `{hash}`")?;
926 }
927 ErrorKind::StaticStringMissing { hash, slot } => {
928 write!(
929 f,
930 "Missing static string for hash `{hash}` and slot `{slot}`",
931 )?;
932 }
933 ErrorKind::StaticBytesMissing { hash, slot } => {
934 write!(
935 f,
936 "Missing static byte string for hash `{hash}` and slot `{slot}`",
937 )?;
938 }
939 ErrorKind::StaticStringHashConflict {
940 hash,
941 current,
942 existing,
943 } => {
944 write!(f,"Conflicting static string for hash `{hash}` between `{existing:?}` and `{current:?}`")?;
945 }
946 ErrorKind::StaticBytesHashConflict {
947 hash,
948 current,
949 existing,
950 } => {
951 write!(f,"Conflicting static string for hash `{hash}` between `{existing:?}` and `{current:?}`")?;
952 }
953 ErrorKind::StaticObjectKeysMissing { hash, slot } => {
954 write!(
955 f,
956 "Missing static object keys for hash `{hash}` and slot `{slot}`",
957 )?;
958 }
959 ErrorKind::StaticObjectKeysHashConflict {
960 hash,
961 current,
962 existing,
963 } => {
964 write!(f,"Conflicting static object keys for hash `{hash}` between `{existing:?}` and `{current:?}`")?;
965 }
966 ErrorKind::ConflictingLabels { .. } => {
967 write!(f, "Multiple labels provided")?;
968 }
969 ErrorKind::DuplicateSelectDefault { .. } => {
970 write!(f, "Multiple default select branches")?;
971 }
972 ErrorKind::MissingLabel { label } => {
973 write!(f, "Missing label '{label}")?;
974 }
975 ErrorKind::ExpectedLeadingPathSegment => {
976 write!(f, "Segment is only supported in the first position")?;
977 }
978 ErrorKind::UnsupportedVisibility => {
979 write!(f, "Visibility modifier not supported")?;
980 }
981 ErrorKind::ExpectedMeta { expected, meta } => {
982 write!(f, "Expected {expected} but got `{meta}`")?;
983 }
984 ErrorKind::NoSuchBuiltInMacro { name } => {
985 write!(f, "No such built-in macro `{name}`")?;
986 }
987 ErrorKind::VariableMoved { .. } => {
988 write!(f, "Variable moved")?;
989 }
990 ErrorKind::UnsupportedGenerics => {
991 write!(f, "Unsupported generic argument")?;
992 }
993 ErrorKind::NestedTest { .. } => {
994 write!(f, "Attribute `#[test]` is not supported on nested items")?;
995 }
996 ErrorKind::NestedBench { .. } => {
997 write!(f, "Attribute `#[bench]` is not supported on nested items")?;
998 }
999 ErrorKind::MissingFunctionHash { hash } => {
1000 write!(f, "Missing function with hash `{hash}`")?;
1001 }
1002 ErrorKind::FunctionConflictHash { hash } => {
1003 write!(f, "Conflicting function already exists `{hash}`")?;
1004 }
1005 ErrorKind::PatternMissingFields { item, .. } => {
1006 write!(f, "Non-exhaustive pattern for `{item}`")?;
1007 }
1008 ErrorKind::MissingLabelLocation { name, index } => {
1009 write!(
1010 f,
1011 "Use of label `{name}_{index}` which has no code location",
1012 )?;
1013 }
1014 ErrorKind::MaxMacroRecursion { depth, max } => {
1015 write!(
1016 f,
1017 "Reached macro recursion limit at {depth}, limit is {max}",
1018 )?;
1019 }
1020 ErrorKind::YieldInConst => {
1021 write!(f, "Expression `yield` inside of constant function")?;
1022 }
1023 ErrorKind::AwaitInConst => {
1024 write!(f, "Expression `.await` inside of constant context")?;
1025 }
1026 ErrorKind::AwaitOutsideAsync => {
1027 write!(f, "Expression `.await` outside of async function or block")?;
1028 }
1029 ErrorKind::ExpectedEof { actual } => {
1030 write!(f, "Expected end of file, but got {actual}")?;
1031 }
1032 ErrorKind::UnexpectedEof => {
1033 write!(f, "Unexpected end of file")?;
1034 }
1035 ErrorKind::BadLexerMode { actual, expected } => {
1036 write!(f, "Bad lexer mode `{actual}`, expected `{expected}`")?;
1037 }
1038 ErrorKind::ExpectedEscape => {
1039 write!(f, "Expected escape sequence")?;
1040 }
1041 ErrorKind::UnterminatedStrLit => {
1042 write!(f, "Unterminated string literal")?;
1043 }
1044 ErrorKind::UnterminatedByteStrLit => {
1045 write!(f, "Unterminated byte string literal")?;
1046 }
1047 ErrorKind::UnterminatedCharLit => {
1048 write!(f, "Unterminated character literal")?;
1049 }
1050 ErrorKind::UnterminatedByteLit => {
1051 write!(f, "Unterminated byte literal")?;
1052 }
1053 ErrorKind::ExpectedCharClose => {
1054 write!(f, "Expected character literal to be closed")?;
1055 }
1056 ErrorKind::ExpectedCharOrLabel => {
1057 write!(f, "Expected label or character")?;
1058 }
1059 ErrorKind::ExpectedByteClose => {
1060 write!(f, "Expected byte literal to be closed")?;
1061 }
1062 ErrorKind::UnexpectedChar { c } => {
1063 write!(f, "Unexpected character `{c}`")?;
1064 }
1065 ErrorKind::PrecedenceGroupRequired => {
1066 write!(f, "Group required in expression to determine precedence")?;
1067 }
1068 ErrorKind::BadSignedOutOfBounds { size } => {
1069 write!(
1070 f,
1071 "Number literal out of bounds `{}` to `{}`",
1072 size.signed_min(),
1073 size.signed_max(),
1074 )?;
1075 }
1076 ErrorKind::BadUnsignedOutOfBounds { size } => {
1077 write!(
1078 f,
1079 "Number literal out of bounds `{}` to `{}`",
1080 size.unsigned_min(),
1081 size.unsigned_max(),
1082 )?;
1083 }
1084 ErrorKind::BadFieldAccess => {
1085 write!(f, "Unsupported field access")?;
1086 }
1087 ErrorKind::ExpectedMacroCloseDelimiter { expected, actual } => {
1088 write!(f, "Expected close delimiter {expected}, but got {actual}")?;
1089 }
1090 ErrorKind::MultipleMatchingAttributes { name } => {
1091 write!(f, "Can only specify one attribute named `{name}`")?;
1092 }
1093 ErrorKind::MissingSourceId { source_id } => {
1094 write!(f, "Missing source id `{source_id}`")?;
1095 }
1096 ErrorKind::ExpectedMultilineCommentTerm => {
1097 write!(f, "Expected multiline comment to be terminated with a `*/`")?;
1098 }
1099 ErrorKind::BadSlice => {
1100 write!(f, "Tried to read bad slice from source")?;
1101 }
1102 ErrorKind::BadSyntheticId { kind, id } => {
1103 write!(
1104 f,
1105 "Tried to get bad synthetic identifier `{id}` for `{kind}`",
1106 )?;
1107 }
1108 ErrorKind::BadCharLiteral => {
1109 write!(f, "Bad character literal")?;
1110 }
1111 ErrorKind::BadByteLiteral => {
1112 write!(f, "Bad byte literal")?;
1113 }
1114 ErrorKind::BadNumberLiteral => {
1115 write!(f, "Number literal not valid")?;
1116 }
1117 ErrorKind::AmbiguousItem { item, .. } => {
1118 write!(f, "Item `{item}` can refer to multiple things")?;
1119 }
1120 ErrorKind::AmbiguousContextItem { item, .. } => {
1121 write!(
1122 f,
1123 "Item `{item}` can refer to multiple things from the context"
1124 )?;
1125 }
1126 ErrorKind::NotVisible {
1127 visibility,
1128 item,
1129 from,
1130 ..
1131 } => {
1132 write!(f,"Item `{item}` with visibility `{visibility}`, is not accessible from module `{from}`")?;
1133 }
1134 ErrorKind::NotVisibleMod {
1135 visibility,
1136 item,
1137 from,
1138 ..
1139 } => {
1140 write!(f,"Module `{item}` with {visibility} visibility, is not accessible from module `{from}`")?;
1141 }
1142 ErrorKind::MissingMod { item } => {
1143 write!(f, "Missing query meta for module {item}")?;
1144 }
1145 ErrorKind::ImportCycle { .. } => {
1146 write!(f, "Cycle in import")?;
1147 }
1148 ErrorKind::ImportRecursionLimit { count, .. } => {
1149 write!(f, "Import recursion limit reached ({count})")?;
1150 }
1151 ErrorKind::LastUseComponent => {
1152 write!(f, "Missing last use component")?;
1153 }
1154 ErrorKind::RttiConflict { hash } => {
1155 write!(f,"Tried to insert variant runtime type information, but conflicted with hash `{hash}`")?;
1156 }
1157 ErrorKind::TypeRttiConflict { hash } => {
1158 write!(
1159 f,
1160 "Tried to insert runtime type information, but conflicted with hash `{hash}`"
1161 )?;
1162 }
1163 ErrorKind::ArenaWriteSliceOutOfBounds { index } => {
1164 write!(f, "Writing arena slice out of bounds for index {index}")?;
1165 }
1166 ErrorKind::ArenaAllocError { requested } => {
1167 write!(f, "Allocation error for {requested} bytes")?;
1168 }
1169 ErrorKind::UnsupportedPatternRest => {
1170 write!(f, "Pattern `..` is not supported in this location")?;
1171 }
1172 ErrorKind::UnsupportedMut => {
1173 write!(
1174 f,
1175 "The `mut` modifier is not supported in Rune, everything is mutable by default"
1176 )?;
1177 }
1178 ErrorKind::UnsupportedSuffix => {
1179 write!(
1180 f,
1181 "Unsupported suffix, expected one of `u8`, `i64`, `u64`, or `f64`"
1182 )?;
1183 }
1184 ErrorKind::ClosureInConst => {
1185 write!(f, "Closures are not supported in constant contexts")?;
1186 }
1187 ErrorKind::AsyncBlockInConst => {
1188 write!(f, "Async blocks are not supported in constant contexts")?;
1189 }
1190 #[cfg(feature = "fmt")]
1191 ErrorKind::BadSpan { len } => {
1192 write!(f, "Span is outside of source 0-{len}")?;
1193 }
1194 ErrorKind::UnexpectedEndOfSyntax { inside } => {
1195 write!(f, "Unexpected end of syntax while parsing {inside}")?;
1196 }
1197 ErrorKind::UnexpectedEndOfSyntaxWith { inside, expected } => {
1198 write!(
1199 f,
1200 "Expected {expected} but got end of syntax while parsing {inside}"
1201 )?;
1202 }
1203 ErrorKind::ExpectedSyntaxEnd { inside, actual } => {
1204 write!(
1205 f,
1206 "Expected end of syntax but got {actual} while parsing {inside}"
1207 )?;
1208 }
1209 #[cfg(feature = "fmt")]
1210 ErrorKind::BadIndent { level, indent } => {
1211 write!(f, "Got bad indent {level} with existing {indent}")?;
1212 }
1213 ErrorKind::ExpectedSyntax { expected, actual } => {
1214 write!(f, "Expected {expected} but got {actual}")?;
1215 }
1216 ErrorKind::ExpectedSyntaxIn {
1217 inside,
1218 expected,
1219 actual,
1220 } => {
1221 write!(
1222 f,
1223 "Expected {expected} but got {actual} while parsing {inside}"
1224 )?;
1225 }
1226 ErrorKind::ExpectedOne { inside, expected } => {
1227 write!(f, "Expected {expected} while parsing {inside}")?;
1228 }
1229 ErrorKind::ExpectedAtMostOne {
1230 inside,
1231 expected,
1232 count,
1233 } => {
1234 write!(
1235 f,
1236 "Expected one {expected} but got {count} of them while parsing {inside}"
1237 )?;
1238 }
1239 ErrorKind::ExpectedAtLeastOne { inside, expected } => {
1240 write!(f, "Expected one {expected} while parsing {inside}")?;
1241 }
1242 #[cfg(feature = "fmt")]
1243 ErrorKind::UnsupportedDelimiter { expectation } => {
1244 write!(f, "Unsupported delimiter {expectation}")?;
1245 }
1246 }
1247
1248 Ok(())
1249 }
1250}
1251
1252struct ParameterizedItem<'a>(&'a Item, &'a [Option<Hash>; 2]);
1253
1254impl fmt::Display for ParameterizedItem<'_> {
1255 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1256 let mut it = self.0.iter();
1257
1258 let (Some(item), Some(ty)) = (it.next_back(), it.next_back()) else {
1259 return self.0.fmt(f);
1260 };
1261
1262 let mut first = false;
1263
1264 for c in it {
1265 if first {
1266 write!(f, "::{c}")?;
1267 } else {
1268 write!(f, "{c}")?;
1269 }
1270
1271 first = true;
1272 }
1273
1274 let [ty_param, item_param] = self.1;
1275
1276 if let Some(ty_param) = ty_param {
1277 write!(f, "::{ty}<{ty_param}>")?;
1278 } else {
1279 write!(f, "::{ty}")?;
1280 }
1281
1282 if let Some(item_param) = item_param {
1283 write!(f, "::{item}<{item_param}>")?;
1284 } else {
1285 write!(f, "::{item}")?;
1286 }
1287
1288 Ok(())
1289 }
1290}
1291
1292impl From<alloc::Error> for Error {
1293 #[inline]
1294 fn from(error: alloc::Error) -> Self {
1295 Error::new(Span::empty(), ErrorKind::AllocError { error })
1296 }
1297}
1298
1299impl From<alloc::Error> for ErrorKind {
1300 #[inline]
1301 fn from(error: alloc::Error) -> Self {
1302 ErrorKind::AllocError { error }
1303 }
1304}
1305
1306impl From<alloc::alloc::AllocError> for Error {
1307 #[inline]
1308 fn from(error: alloc::alloc::AllocError) -> Self {
1309 Self::from(alloc::Error::from(error))
1310 }
1311}
1312
1313impl From<alloc::alloc::AllocError> for ErrorKind {
1314 #[inline]
1315 fn from(error: alloc::alloc::AllocError) -> Self {
1316 Self::from(alloc::Error::from(error))
1317 }
1318}
1319
1320impl From<IrErrorKind> for ErrorKind {
1321 #[inline]
1322 fn from(error: IrErrorKind) -> Self {
1323 ErrorKind::IrError(error)
1324 }
1325}
1326
1327impl From<MetaError> for ErrorKind {
1328 #[inline]
1329 fn from(error: MetaError) -> Self {
1330 ErrorKind::MetaError(error)
1331 }
1332}
1333
1334impl From<AccessError> for ErrorKind {
1335 #[inline]
1336 fn from(error: AccessError) -> Self {
1337 ErrorKind::AccessError(error)
1338 }
1339}
1340
1341impl From<VmError> for ErrorKind {
1342 #[inline]
1343 fn from(error: VmError) -> Self {
1344 ErrorKind::VmError(error)
1345 }
1346}
1347
1348impl From<RuntimeError> for ErrorKind {
1349 #[inline]
1350 fn from(error: RuntimeError) -> Self {
1351 ErrorKind::VmError(VmError::new(error.into_vm_error_kind()))
1352 }
1353}
1354
1355impl From<AnyObjError> for ErrorKind {
1356 #[inline]
1357 fn from(error: AnyObjError) -> Self {
1358 Self::from(RuntimeError::from(error))
1359 }
1360}
1361
1362impl From<EncodeError> for ErrorKind {
1363 #[inline]
1364 fn from(error: EncodeError) -> Self {
1365 ErrorKind::EncodeError(error)
1366 }
1367}
1368
1369impl From<MissingLastId> for ErrorKind {
1370 #[inline]
1371 fn from(error: MissingLastId) -> Self {
1372 ErrorKind::MissingLastId(error)
1373 }
1374}
1375
1376impl From<GuardMismatch> for ErrorKind {
1377 #[inline]
1378 fn from(error: GuardMismatch) -> Self {
1379 ErrorKind::GuardMismatch(error)
1380 }
1381}
1382
1383impl From<MissingScope> for ErrorKind {
1384 #[inline]
1385 fn from(error: MissingScope) -> Self {
1386 ErrorKind::MissingScope(error)
1387 }
1388}
1389
1390impl From<PopError> for ErrorKind {
1391 #[inline]
1392 fn from(error: PopError) -> Self {
1393 ErrorKind::PopError(error)
1394 }
1395}
1396
1397impl From<unescape::ErrorKind> for ErrorKind {
1398 #[inline]
1399 fn from(source: unescape::ErrorKind) -> Self {
1400 ErrorKind::UnescapeError(source)
1401 }
1402}
1403
1404#[derive(Debug)]
1406#[non_exhaustive]
1407pub(crate) enum IrErrorKind {
1408 NotConst,
1411 ConstCycle,
1413 UnsupportedMeta {
1415 meta: MetaInfo,
1417 },
1418 Expected {
1420 expected: TypeInfo,
1422 actual: TypeInfo,
1424 },
1425 BudgetExceeded,
1427 MissingIndex {
1429 index: usize,
1431 },
1432 MissingField {
1434 field: Box<str>,
1436 },
1437 BreakOutsideOfLoop,
1439 ArgumentCountMismatch {
1440 actual: usize,
1441 expected: usize,
1442 },
1443}
1444
1445impl core::error::Error for IrErrorKind {}
1446
1447impl fmt::Display for IrErrorKind {
1448 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1449 match self {
1450 IrErrorKind::NotConst => {
1451 write!(f, "Expected a constant expression")?;
1452 }
1453 IrErrorKind::ConstCycle => {
1454 write!(f, "Constant cycle detected")?;
1455 }
1456 IrErrorKind::UnsupportedMeta { meta } => {
1457 write!(f, "Item `{meta}` is not supported here",)?
1458 }
1459 IrErrorKind::Expected { expected, actual } => {
1460 write!(f, "Expected a value of type {expected} but got {actual}",)?
1461 }
1462 IrErrorKind::BudgetExceeded => {
1463 write!(f, "Evaluation budget exceeded")?;
1464 }
1465 IrErrorKind::MissingIndex { index } => {
1466 write!(f, "Missing index {index}")?;
1467 }
1468 IrErrorKind::MissingField { field } => {
1469 write!(f, "Missing field `{field}`")?;
1470 }
1471 IrErrorKind::BreakOutsideOfLoop => {
1472 write!(f, "Break outside of supported loop")?;
1473 }
1474 IrErrorKind::ArgumentCountMismatch { actual, expected } => {
1475 write!(
1476 f,
1477 "Argument count mismatch, got {actual} but expected {expected}",
1478 )?;
1479 }
1480 }
1481
1482 Ok(())
1483 }
1484}
1485
1486#[derive(Debug, TryClone)]
1490#[non_exhaustive]
1491pub struct ImportStep {
1492 pub location: Location,
1494 pub item: ItemBuf,
1496}
1497
1498#[derive(Debug)]
1500pub struct MetaError {
1501 kind: rust_alloc::boxed::Box<MetaErrorKind>,
1502}
1503
1504impl MetaError {
1505 pub(crate) fn new<E>(kind: E) -> Self
1507 where
1508 MetaErrorKind: From<E>,
1509 {
1510 Self {
1511 kind: rust_alloc::boxed::Box::new(kind.into()),
1512 }
1513 }
1514}
1515
1516impl From<alloc::Error> for MetaError {
1517 #[inline]
1518 fn from(error: alloc::Error) -> Self {
1519 Self::new(MetaErrorKind::AllocError { error })
1520 }
1521}
1522
1523impl From<alloc::alloc::AllocError> for MetaError {
1524 #[inline]
1525 fn from(error: alloc::alloc::AllocError) -> Self {
1526 Self::from(alloc::Error::from(error))
1527 }
1528}
1529
1530#[derive(Debug)]
1531pub(crate) enum MetaErrorKind {
1533 AllocError {
1534 error: alloc::Error,
1535 },
1536 MetaConflict {
1537 current: MetaInfo,
1539 existing: MetaInfo,
1541 parameters: Hash,
1543 },
1544}
1545
1546impl fmt::Display for MetaError {
1547 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1548 match &*self.kind {
1549 MetaErrorKind::AllocError { error } => error.fmt(f),
1550 MetaErrorKind::MetaConflict {
1551 current,
1552 existing,
1553 parameters,
1554 } => {
1555 write!(f, "Can't insert item `{current}` ({parameters}) because conflicting meta `{existing}` already exists")
1556 }
1557 }
1558 }
1559}
1560
1561impl core::error::Error for MetaError {}
1562
1563#[derive(Debug)]
1564pub(crate) struct MissingScope(pub(crate) usize);
1565
1566impl fmt::Display for MissingScope {
1567 #[inline]
1568 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1569 write!(f, "Missing scope with id {}", self.0)
1570 }
1571}
1572
1573impl core::error::Error for MissingScope {}
1574
1575#[derive(Debug)]
1576pub(crate) enum PopError {
1577 MissingScope(usize),
1578 MissingParentScope(usize),
1579}
1580
1581impl fmt::Display for PopError {
1582 #[inline]
1583 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1584 match self {
1585 PopError::MissingScope(id) => write!(f, "Missing scope with id {id}"),
1586 PopError::MissingParentScope(id) => write!(f, "Missing parent scope with id {id}"),
1587 }
1588 }
1589}
1590
1591impl core::error::Error for PopError {}