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