1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
//! This module implements `TemporalError`.

use core::fmt;

use icu_calendar::CalendarError;

/// `TemporalError`'s error type.
#[derive(Debug, Default, Clone, Copy)]
pub enum ErrorKind {
    /// Error.
    #[default]
    Generic,
    /// TypeError
    Type,
    /// RangeError
    Range,
    /// SyntaxError
    Syntax,
}

impl fmt::Display for ErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Generic => "Error",
            Self::Type => "TypeError",
            Self::Range => "RangeError",
            Self::Syntax => "SyntaxError",
        }
        .fmt(f)
    }
}

/// The error type for `boa_temporal`.
#[derive(Debug, Clone)]
pub struct TemporalError {
    kind: ErrorKind,
    msg: Box<str>,
}

impl TemporalError {
    fn new(kind: ErrorKind) -> Self {
        Self {
            kind,
            msg: Box::default(),
        }
    }

    /// Create a generic error
    #[must_use]
    pub fn general<S>(msg: S) -> Self
    where
        S: Into<Box<str>>,
    {
        Self::new(ErrorKind::Generic).with_message(msg)
    }

    /// Create a range error.
    #[must_use]
    pub fn range() -> Self {
        Self::new(ErrorKind::Range)
    }

    /// Create a type error.
    #[must_use]
    pub fn r#type() -> Self {
        Self::new(ErrorKind::Type)
    }

    /// Create a syntax error.
    #[must_use]
    pub fn syntax() -> Self {
        Self::new(ErrorKind::Syntax)
    }

    /// Create an abrupt end error.
    #[must_use]
    pub fn abrupt_end() -> Self {
        Self::syntax().with_message("Abrupt end to parsing target.")
    }

    /// Add a message to the error.
    #[must_use]
    pub fn with_message<S>(mut self, msg: S) -> Self
    where
        S: Into<Box<str>>,
    {
        self.msg = msg.into();
        self
    }

    /// Returns this error's kind.
    #[must_use]
    pub fn kind(&self) -> ErrorKind {
        self.kind
    }

    /// Returns the error message.
    #[must_use]
    pub fn message(&self) -> &str {
        &self.msg
    }
}

impl fmt::Display for TemporalError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.kind)?;

        let msg = self.msg.trim();
        if !msg.is_empty() {
            write!(f, ": {msg}")?;
        }

        Ok(())
    }
}

impl From<CalendarError> for TemporalError {
    fn from(value: CalendarError) -> Self {
        TemporalError::general(value.to_string())
    }
}