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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
use colored::Colorize;
use std::{
fmt::{Debug, Display},
ops::{Deref, DerefMut},
path::Path,
sync::{
atomic::{AtomicUsize, Ordering},
Arc,
},
};
use dashmap::DashMap;
use internment::Intern;
use once_cell::sync::Lazy;
use std::path::PathBuf;
pub type CtxResult<T> = Result<T, CtxErr>;
pub trait ToCtxErr {
type Okay;
fn err_ctx(self, loc: Option<CtxLocation>) -> Result<Self::Okay, CtxErr>;
}
impl<T, E: Into<anyhow::Error>> ToCtxErr for Result<T, E> {
type Okay = T;
fn err_ctx(self, loc: Option<CtxLocation>) -> Result<Self::Okay, CtxErr> {
self.map_err(|e| Ctx {
inner: Arc::new(e.into()),
context: loc,
})
}
}
pub type CtxErr = Ctx<anyhow::Error>;
pub trait ToCtx: Sized {
fn with_ctx(self, loc: impl Into<Option<CtxLocation>>) -> Ctx<Self> {
Ctx {
inner: Arc::new(self),
context: loc.into(),
}
}
}
impl<T: Sized> ToCtx for T {}
#[derive(PartialEq, Eq, PartialOrd, Ord)]
pub struct Ctx<T> {
inner: Arc<T>,
context: Option<CtxLocation>,
}
impl<T> Clone for Ctx<T> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
context: self.context,
}
}
}
impl<T: Debug> Debug for Ctx<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.inner.fmt(f)
}
}
impl<T> Ctx<T> {
pub fn ctx(&self) -> Option<CtxLocation> {
self.context
}
}
impl<T> Deref for Ctx<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.inner.deref()
}
}
impl<T: Clone> DerefMut for Ctx<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
Arc::make_mut(&mut self.inner)
}
}
impl<T> From<T> for Ctx<T> {
fn from(val: T) -> Self {
Ctx {
inner: val.into(),
context: None,
}
}
}
impl<T: Display> Ctx<T> {
pub fn pretty_print(&self, source_lookup: impl Fn(ModuleId) -> Option<String>) -> String {
let error_location: String;
let mut detailed_line: Option<String> = None;
if let Some(ctx) = self.ctx() {
if let Some(source_full_string) = source_lookup(ctx.source) {
let mut char_counter = 0;
let mut errloc = ctx.source.to_string();
for (lineno, line) in source_full_string.split('\n').enumerate() {
let line_len = line.len() + 1;
if char_counter + line.len() > ctx.start_offset {
let line_offset = ctx.start_offset - char_counter;
errloc = format!("{}:{}", ctx.source, lineno + 1);
detailed_line = Some(format!("{}\n{}", line, {
let mut toret = String::new();
for _ in 0..line_offset {
toret.push(' ');
}
toret.push_str(&format!("{}", "^".bright_green().bold()));
for _ in
1..(ctx.end_offset - ctx.start_offset).min(line.len() - line_offset)
{
toret.push_str(&format!("{}", "~".bright_green().bold()));
}
toret
}));
break;
}
char_counter += line_len
}
error_location = errloc;
} else {
error_location = ctx.source.to_string();
}
} else {
error_location = "(unknown location)".to_string();
}
let err_str = format!(
"{}: {} {}",
error_location.bold(),
"error:".bold().red(),
self.inner.to_string().bold()
);
if let Some(line) = detailed_line {
let lines = line.lines().collect::<Vec<&str>>().join("\n\t");
format!("{}\n\t{}", err_str, lines)
} else {
err_str
}
}
}
impl<T: Display> Display for Ctx<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(
&self.pretty_print(|mid| std::fs::read_to_string(&mid.to_string()).ok()),
f,
)
}
}
#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug)]
pub struct CtxLocation {
pub source: ModuleId,
pub start_offset: usize,
pub end_offset: usize,
}
#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Hash)]
pub struct ModuleId {
absolute_path: Intern<String>,
}
impl Display for ModuleId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(&self.absolute_path, f)
}
}
impl ModuleId {
pub fn new(path: &Path) -> Self {
let canon = path.to_string_lossy().into_owned();
ModuleId {
absolute_path: Intern::new(canon),
}
}
pub fn from_path(path: &Path) -> Self {
let canon = path.to_string_lossy().into_owned();
ModuleId {
absolute_path: Intern::new(canon),
}
}
pub fn relative(self, frag: &str) -> Self {
let mut path = Path::new(self.absolute_path.as_str()).to_owned();
path.pop();
path.push(frag);
let new = path.to_string_lossy().into_owned();
ModuleId {
absolute_path: Intern::new(new),
}
}
pub fn load_file(self) -> std::io::Result<String> {
std::fs::read_to_string(self.absolute_path.as_str())
}
pub fn uniqid(self) -> usize {
static CACHE: Lazy<DashMap<ModuleId, usize>> = Lazy::new(DashMap::new);
static GCOUNTER: AtomicUsize = AtomicUsize::new(0);
*CACHE
.entry(self)
.or_insert_with(|| GCOUNTER.fetch_add(1, Ordering::Relaxed))
}
}
#[derive(Clone)]
pub struct ProjectRoot(pub PathBuf);
impl ProjectRoot {
pub fn module_from_root(self, path: &Path) -> ModuleId {
ModuleId::new(&self.0.join(path))
}
}