wain_syntax_text/
source.rs1use std::fmt;
2use wain_ast::source::Source;
3
4pub fn describe_position(f: &mut fmt::Formatter<'_>, source: &str, start: usize) -> fmt::Result {
5 if start == source.len() {
6 write!(f, " caused at byte offset {} (end of input)", start)
7 } else {
8 let source = &source[start..];
9 let end = source.find(['\n', '\r'].as_ref()).unwrap_or(source.len());
10 write!(
11 f,
12 " caused at byte offset {}\n\n ... {}\n ^\n starts from here",
13 start,
14 &source[..end],
15 )
16 }
17}
18
19#[derive(Clone)]
20pub struct TextSource<'source>(pub(crate) &'source str);
21
22impl<'s> Source for TextSource<'s> {
23 type Raw = &'s str;
24
25 fn describe(&self, f: &mut fmt::Formatter<'_>, offset: usize) -> fmt::Result {
26 describe_position(f, self.0, offset)
27 }
28
29 fn raw(&self) -> Self::Raw {
30 self.0
31 }
32}