-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathspan.rs
More file actions
65 lines (53 loc) · 1.49 KB
/
Copy pathspan.rs
File metadata and controls
65 lines (53 loc) · 1.49 KB
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
use crate::parser::file_cache::file_cache;
use ariadne::{Label, Report, ReportKind};
use std::fmt::Display;
use std::ops::Range;
use std::path::Path;
#[derive(Clone, Debug)]
pub struct Span<'a>(&'a Path, Range<usize>, &'a str);
impl<'a> Span<'a> {
pub fn empty() -> Self {
Span(&Path::new(""), 0..0, "")
}
}
/// Converts a pest Span to an ariadne Span.
pub fn to_span<'a>(file: &'a Path, span: pest::Span<'a>) -> Span<'a> {
Span(file, span.start()..span.end(), span.as_str())
}
impl<'a> ariadne::Span for Span<'a> {
type SourceId = Path;
fn source(&self) -> &Self::SourceId {
self.0
}
fn start(&self) -> usize {
self.1.start
}
fn end(&self) -> usize {
self.1.end
}
}
impl<'a> Display for Span<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", self.2)
}
}
pub fn print_with_span<'a>(span: Option<Span<'a>>, msg: &str) {
let Some(span) = span else {
eprintln!("{msg}");
return;
};
Report::build(ReportKind::Error, span.clone())
.with_message(msg)
.with_label(Label::new(span).with_message("The error occurred here"))
.finish()
.eprint(file_cache())
.unwrap();
}
/// Prints a message alongside the given span.
/// Pass the span as an option.
macro_rules! eprintln_span {
($span:expr, $($arg:tt)*) => {
$crate::parser::span::print_with_span($span, &format!($($arg)*));
};
}
pub(crate) use eprintln_span;