nyar_error/runtime/
mod.rs

1use diagnostic::{ReportKind, SourceSpan};
2use std::{
3    fmt::{Display, Formatter},
4    panic::Location,
5};
6
7use crate::{Diagnostic, NyarError, NyarErrorKind, SyntaxError};
8
9mod for_serde;
10#[cfg(feature = "wasmtime")]
11mod for_wasm;
12
13#[cfg(feature = "walkdir")]
14mod for_walkdir;
15
16#[derive(Clone, Debug, Eq, PartialEq)]
17pub struct RuntimeError {
18    message: String,
19}
20
21impl From<RuntimeError> for NyarError {
22    fn from(value: RuntimeError) -> Self {
23        NyarErrorKind::Runtime(value).as_error(ReportKind::Error)
24    }
25}
26
27impl From<()> for NyarError {
28    #[track_caller]
29    fn from(_: ()) -> Self {
30        let caller = Location::caller();
31        RuntimeError { message: caller.to_string() }.into()
32    }
33}
34
35impl From<std::io::Error> for NyarError {
36    fn from(value: std::io::Error) -> Self {
37        RuntimeError { message: value.to_string() }.into()
38    }
39}
40
41impl Display for RuntimeError {
42    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
43        f.write_str(&self.message)
44    }
45}
46
47impl RuntimeError {
48    pub fn new(message: impl Display) -> Self {
49        Self { message: message.to_string() }
50    }
51    pub fn as_report(&self, kind: ReportKind) -> Diagnostic {
52        let mut report = Diagnostic::new(kind);
53        report.set_message(self.to_string());
54        report.finish()
55    }
56}
57
58impl NyarError {
59    pub fn syntax_error(message: impl Into<String>, position: SourceSpan) -> Self {
60        let this = SyntaxError { info: message.into(), hint: "".to_string(), span: position };
61        NyarErrorKind::Parsing(this).as_error(ReportKind::Error)
62    }
63
64    pub fn runtime_error(message: impl Into<String>) -> Self {
65        let this = RuntimeError { message: message.into() };
66        NyarErrorKind::Runtime(this).as_error(ReportKind::Error)
67    }
68
69    pub fn custom<S: ToString>(message: S) -> Self {
70        let this = message.to_string();
71        NyarErrorKind::Custom(this).as_error(ReportKind::Error)
72    }
73}