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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
use std::{
    error::Error,
    fmt::{self, Display},
    io,
    string::FromUtf8Error,
    sync::Arc,
};

use codemap::{Span, SpanLoc};

pub type SassResult<T> = Result<T, Box<SassError>>;

/// `SassError`s can be either a structured error specific to `grass` or an
/// `io::Error`.
///
/// In the former case, the best way to interact with the error is to simply print
/// it to the user. The `Display` implementation of this kind of error mirrors
/// that of the errors `dart-sass` emits, e.g.
///```scss
/// Error: $number: foo is not a number.
///     |
/// 308 |     color: unit(foo);
///     |                 ^^^
///     |
/// ./input.scss:308:17
///```
///
#[derive(Debug, Clone)]
pub struct SassError {
    kind: SassErrorKind,
}

impl SassError {
    #[must_use]
    pub fn kind(self) -> PublicSassErrorKind {
        match self.kind {
            SassErrorKind::ParseError {
                message,
                loc,
                unicode,
            } => PublicSassErrorKind::ParseError {
                message,
                loc,
                unicode,
            },
            SassErrorKind::FromUtf8Error(s) => PublicSassErrorKind::FromUtf8Error(s),
            SassErrorKind::IoError(io) => PublicSassErrorKind::IoError(io),
            SassErrorKind::Raw(..) => unreachable!("raw errors should not be accessible by users"),
        }
    }

    pub(crate) fn raw(self) -> (String, Span) {
        match self.kind {
            SassErrorKind::Raw(string, span) => (string, span),
            e => unreachable!("unable to get raw of {:?}", e),
        }
    }

    pub(crate) const fn from_loc(message: String, loc: SpanLoc, unicode: bool) -> Self {
        SassError {
            kind: SassErrorKind::ParseError {
                message,
                loc,
                unicode,
            },
        }
    }
}

#[non_exhaustive]
#[derive(Debug, Clone)]
pub enum PublicSassErrorKind {
    ParseError {
        /// The message related to this parse error.
        ///
        /// Error messages should only be used to assist in debugging for the
        /// end user. They may change significantly between bugfix versions and
        /// should not be relied on to remain stable.
        ///
        /// Error messages do not contain the `Error: ` prefix or pretty-printed
        /// span and context information as is shown in the `Display` implementation.
        message: String,
        loc: SpanLoc,

        /// Whether or not the user allows unicode characters to be emitted in
        /// error messages.
        ///
        /// This is configurable with [`crate::Options::unicode_error_messages`]
        unicode: bool,
    },

    /// Sass was unable to find the entry-point file.
    ///
    /// Files that cannot be found using `@import`, `@use`, and `@forward` will
    /// emit [`Self::ParseError`]s
    IoError(Arc<io::Error>),

    /// The entry-point file or an imported file was not valid UTF-8.
    FromUtf8Error(String),
}

#[derive(Debug, Clone)]
enum SassErrorKind {
    /// A raw error with no additional metadata
    /// It contains only a `String` message and
    /// a span
    Raw(String, Span),
    ParseError {
        message: String,
        loc: SpanLoc,
        unicode: bool,
    },
    // we put `IoError`s in an `Arc` to allow them to be cloneable
    IoError(Arc<io::Error>),
    FromUtf8Error(String),
}

impl Display for SassError {
    // TODO: trim whitespace from start of line shown in error
    // TODO: color errors
    // TODO: integrate with codemap-diagnostics
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let (message, loc, unicode) = match &self.kind {
            SassErrorKind::ParseError {
                message,
                loc,
                unicode,
            } => (message, loc, *unicode),
            SassErrorKind::FromUtf8Error(..) => return writeln!(f, "Error: Invalid UTF-8."),
            SassErrorKind::IoError(s) => return writeln!(f, "Error: {}", s),
            SassErrorKind::Raw(..) => unreachable!(),
        };

        let first_bar = if unicode { '╷' } else { ',' };
        let second_bar = if unicode { '│' } else { '|' };
        let third_bar = if unicode { '│' } else { '|' };
        let fourth_bar = if unicode { '╵' } else { '\'' };

        let line = loc.begin.line + 1;
        let col = loc.begin.column + 1;
        writeln!(f, "Error: {}", message)?;
        let padding = vec![' '; format!("{}", line).len() + 1]
            .iter()
            .collect::<String>();
        writeln!(f, "{}{}", padding, first_bar)?;
        writeln!(
            f,
            "{} {} {}",
            line,
            second_bar,
            loc.file.source_line(loc.begin.line)
        )?;
        writeln!(
            f,
            "{}{} {}{}",
            padding,
            third_bar,
            vec![' '; loc.begin.column].iter().collect::<String>(),
            vec!['^'; loc.end.column.max(loc.begin.column) - loc.begin.column.min(loc.end.column)]
                .iter()
                .collect::<String>()
        )?;
        writeln!(f, "{}{}", padding, fourth_bar)?;

        if unicode {
            writeln!(f, "./{}:{}:{}", loc.file.name(), line, col)?;
        } else {
            writeln!(f, "  {} {}:{}  root stylesheet", loc.file.name(), line, col)?;
        }
        Ok(())
    }
}

impl From<io::Error> for Box<SassError> {
    #[inline]
    fn from(error: io::Error) -> Box<SassError> {
        Box::new(SassError {
            kind: SassErrorKind::IoError(Arc::new(error)),
        })
    }
}

impl From<FromUtf8Error> for Box<SassError> {
    #[inline]
    fn from(error: FromUtf8Error) -> Box<SassError> {
        Box::new(SassError {
            kind: SassErrorKind::FromUtf8Error(format!(
                "Invalid UTF-8 character \"\\x{:X?}\"",
                error.as_bytes()[0]
            )),
        })
    }
}

impl From<(&str, Span)> for Box<SassError> {
    #[inline]
    fn from(error: (&str, Span)) -> Box<SassError> {
        Box::new(SassError {
            kind: SassErrorKind::Raw(error.0.to_owned(), error.1),
        })
    }
}

impl From<(String, Span)> for Box<SassError> {
    #[inline]
    fn from(error: (String, Span)) -> Box<SassError> {
        Box::new(SassError {
            kind: SassErrorKind::Raw(error.0, error.1),
        })
    }
}

impl Error for SassError {
    #[inline]
    fn description(&self) -> &'static str {
        "Sass parsing error"
    }
}