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]
14macro_rules! error {
16 ($($arg:tt)*) => (
17 std::io::Error::new(std::io::ErrorKind::Other, format!($($arg)*))
18 )
19}
20
21pub trait ErrorExt<T> {
23 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
39pub(crate) trait PreprocessParseErrorExt<T> {
41 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 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
80pub(crate) trait ConfigParseErrorExt<T> {
82 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
113fn source_location(info: &PreprocessInfo, line: usize) -> Result<(String, u32), Error> {
117 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
131pub(crate) fn located_error(
134 info: &PreprocessInfo,
135 input: &str,
136 offset: usize,
137 message: &Error,
138) -> Error {
139 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 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 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 c.escape_unicode().to_string()
171 } else {
172 printable(&c.to_string())
173 }
174 },
175 );
176 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
197fn printable_line(text: &str) -> String {
199 text.split('\t')
200 .map(printable)
201 .collect::<Vec<_>>()
202 .join("\t")
203}
204
205#[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}