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
use std::{fmt, sync::Arc};
use serde::{Deserialize, Serialize};
use crate::{formatting::source_lines, lexer::loc_to_pos};
#[derive(Clone)]
pub struct Context {
pub source: Arc<Source>,
pub left: usize,
pub right: usize,
}
impl fmt::Display for Context {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.source_position())?;
let lines = source_lines(&self.source, self.left, 0).replace('\n', "\n\t");
writeln!(f, ":\n\t{}", lines)?;
Ok(())
}
}
impl Context {
pub(crate) fn new(source: Arc<Source>, left: usize, right: usize) -> Self {
Self {
source,
left,
right,
}
}
pub(crate) fn source_position(&self) -> String {
let mut f = String::new();
let (row, column) = loc_to_pos(&self.source.src, self.left);
f += &format!(" at line {}, column {}", row + 1, column + 1);
if let Some(ref filename) = self.source.filename {
f += &format!(" of file {}", filename);
}
f
}
}
#[derive(Clone)]
pub enum SourceInfo {
Parser(Context),
TemporaryVariable,
Ffi,
Test,
}
impl fmt::Debug for SourceInfo {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Parser(_) => f.write_str("SourceInfo::Parser"),
Self::TemporaryVariable => f.write_str("SourceInfo::TemporaryVariable"),
Self::Ffi => f.write_str("SourceInfo::Ffi"),
Self::Test => f.write_str("SourceInfo::Test"),
}
}
}
impl SourceInfo {
pub fn ffi() -> Self {
Self::Ffi
}
pub(crate) fn parser(source: Arc<Source>, left: usize, right: usize) -> Self {
Self::Parser(Context::new(source, left, right))
}
}
#[derive(PartialEq, Serialize, Deserialize)]
pub struct Source {
pub filename: Option<String>,
pub src: String,
}
impl Source {
pub fn new<T: AsRef<str>>(src: T) -> Self {
Self {
filename: None,
src: src.as_ref().into(),
}
}
pub fn new_with_name<T: AsRef<str>, U: AsRef<str>>(filename: T, src: U) -> Self {
Self {
filename: Some(filename.as_ref().into()),
src: src.as_ref().into(),
}
}
}