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