Skip to main content

dayzmake_core/
error.rs

1#![macro_use]
2
3use std::cmp::min;
4use std::fmt::Display;
5use std::io::Error;
6use std::path::Path;
7
8use peg::error::ParseError;
9use peg::str::LineCol;
10
11use crate::preprocess::PreprocessInfo;
12
13#[macro_export]
14/// Creates an `std::io::Error` with `ErrorKind::Other` from a formatted message.
15macro_rules! error {
16    ($($arg:tt)*) => (
17        std::io::Error::new(std::io::ErrorKind::Other, format!($($arg)*))
18    )
19}
20
21/// Extensions on `Result<T, std::io::Error>` for error context.
22pub trait ErrorExt<T> {
23    /// Prepends `msg` to the error message, keeping the original text.
24    ///
25    /// # Errors
26    ///
27    /// Returns the original error with `msg` prepended to its message.
28    fn prepend_error<M: AsRef<[u8]> + Display>(self, msg: M) -> Result<T, Error>;
29}
30impl<T> ErrorExt<T> for Result<T, Error> {
31    fn prepend_error<M: AsRef<[u8]> + Display>(self, msg: M) -> Result<T, Error> {
32        match self {
33            Ok(t) => Ok(t),
34            Err(e) => Err(error!("{}\n{}", msg, e)),
35        }
36    }
37}
38
39/// Formats parse errors from the preprocessor with file/line context.
40pub(crate) trait PreprocessParseErrorExt<T> {
41    /// Formats a preprocess parse error, showing the offending input line.
42    ///
43    /// # Errors
44    ///
45    /// Returns the formatted error, or the original `Ok` value.
46    fn format_error(self, origin: Option<&Path>, input: &str) -> Result<T, Error>;
47}
48impl<T> PreprocessParseErrorExt<T> for Result<T, ParseError<LineCol>> {
49    fn format_error(self, origin: Option<&Path>, input: &str) -> Result<T, Error> {
50        match self {
51            Ok(t) => Ok(t),
52            Err(pe) => {
53                let line_index = pe
54                    .location
55                    .line
56                    .checked_sub(1)
57                    .ok_or_else(|| error!("invalid line number {}", pe.location.line))?;
58                // Reported 1-based, like config errors; `line_index` is only for the lookup.
59                let line_origin = u32::try_from(pe.location.line)
60                    .map_err(|_| error!("invalid line number {}", pe.location.line))?;
61                let file_origin = match origin {
62                    Some(path) => format!("{}:", printable(&path.display().to_string())),
63                    None => String::new(),
64                };
65
66                let line = input.lines().nth(line_index).unwrap_or("");
67
68                Err(format_parse_error(
69                    line,
70                    &file_origin,
71                    line_origin,
72                    pe.location.column,
73                    &pe.expected,
74                ))
75            }
76        }
77    }
78}
79
80/// Formats parse errors from the config parser with file/line context.
81pub(crate) trait ConfigParseErrorExt<T> {
82    /// Formats a config parse error, showing the offending input line.
83    ///
84    /// # Errors
85    ///
86    /// Returns the formatted error, or an error if the error location is out of range.
87    fn format_error(self, info: &PreprocessInfo, input: &str) -> Result<T, Error>;
88}
89impl<T> ConfigParseErrorExt<T> for Result<T, ParseError<LineCol>> {
90    fn format_error(self, info: &PreprocessInfo, input: &str) -> Result<T, Error> {
91        match self {
92            Ok(t) => Ok(t),
93            Err(pe) => {
94                let (file_origin, line_origin) = source_location(info, pe.location.line)?;
95
96                let line = input
97                    .lines()
98                    .nth(pe.location.line.saturating_sub(1))
99                    .unwrap_or("");
100
101                Err(format_parse_error(
102                    line,
103                    &file_origin,
104                    line_origin,
105                    pe.location.column,
106                    &pe.expected,
107                ))
108            }
109        }
110    }
111}
112
113/// The file prefix (`file:` or empty) and the original line number of line `line` (1-based) of the
114/// preprocessed input; the one place that maps a preprocessed line to its source, shared by every
115/// config error that has a location.
116fn source_location(info: &PreprocessInfo, line: usize) -> Result<(String, u32), Error> {
117    // line_origins holds one entry per preprocessed line and is empty for an input without lines,
118    // so the lookup can fail (handled below); otherwise its length is an upper bound for the
119    // parser's 1-based line numbers.
120    let idx = min(line, info.line_origins.len()).saturating_sub(1);
121    let Some((line_origin, file)) = info.line_origins.get(idx) else {
122        return Err(error!("Parse error location out of range: line {line}"));
123    };
124    let file_origin = match file {
125        Some(path) => format!("{}:", printable(&path.display().to_string())),
126        None => String::new(),
127    };
128    Ok((file_origin, *line_origin))
129}
130
131/// Gives `message` the `In line <file>:<line>:` context of a parse error, for an error found at byte
132/// `offset` of the preprocessed `input` (an error raised from a grammar action, not by the parser).
133pub(crate) fn located_error(
134    info: &PreprocessInfo,
135    input: &str,
136    offset: usize,
137    message: &Error,
138) -> Error {
139    // `\n` counts the same for LF and CRLF line ends
140    let line = input
141        .get(..offset)
142        .map_or(0, |head| head.matches('\n').count())
143        + 1;
144    match source_location(info, line) {
145        Ok((file, line_number)) => Error::new(
146            message.kind(),
147            format!("In line {file}{line_number}:\n\n  {message}"),
148        ),
149        // no line origin to map to: the message is still more useful without a location than lost
150        Err(_) => Error::new(message.kind(), message.to_string()),
151    }
152}
153
154fn format_parse_error(
155    line: &str,
156    file: &str,
157    line_number: u32,
158    column_number: usize,
159    expected: &impl Display,
160) -> Error {
161    let trimmed = line.trim_start();
162    // The parser's column counts characters, so every width here is in characters too.
163    let stripped = line.chars().count() - trimmed.chars().count();
164    let column = column_number.saturating_sub(1);
165    let offending = line.chars().nth(column).map_or_else(
166        || "\\n".to_string(),
167        |c| {
168            if c.is_whitespace() && !c.is_ascii() {
169                // An invisible token (NBSP, ideographic space) is shown escaped.
170                c.escape_unicode().to_string()
171            } else {
172                printable(&c.to_string())
173            }
174        },
175    );
176    // Control characters are escaped for display, so the caret pads by the displayed width.
177    let padding = printable_line(
178        &trimmed
179            .chars()
180            .take(column.saturating_sub(stripped))
181            .collect::<String>(),
182    )
183    .chars()
184    .count();
185
186    error!(
187        "In line {}{}:\n\n  {}\n  {}^\n\nUnexpected token \"{}\", expected: {}",
188        file,
189        line_number,
190        printable_line(trimmed),
191        " ".repeat(padding),
192        offending,
193        expected
194    )
195}
196
197/// Like [`printable`], but tabs pass through, as they always did in the displayed parse-error line.
198fn printable_line(text: &str) -> String {
199    text.split('\t')
200        .map(printable)
201        .collect::<Vec<_>>()
202        .join("\t")
203}
204
205/// Makes text from an untrusted file safe to print: control characters (escape sequences, line
206/// breaks, bell) are written as `\n`, `\u{1b}` and so on, so they cannot drive the terminal.
207#[must_use]
208pub fn printable(text: &str) -> String {
209    text.chars()
210        .flat_map(|c| {
211            if c.is_control() {
212                c.escape_default().collect::<Vec<char>>()
213            } else {
214                vec![c]
215            }
216        })
217        .collect()
218}