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
use std::fmt::{Debug, Display, Write};
use crate::objects::Value;
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Location {
pub lineno: u32,
pub column: u32,
pub offset: u32,
}
impl Debug for Location {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}:{}({})", self.lineno, self.column, self.offset)
}
}
impl Display for Location {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Debug::fmt(self, f)
}
}
pub fn escape_str(value: &str, ascii_only: bool) -> String {
let mut ans = String::new();
for c in value.chars() {
match c {
'\0' => ans.push_str("\\0"),
'\t' => ans.push_str("\\t"),
'\r' => ans.push_str("\\r"),
'\n' => ans.push_str("\\n"),
'\\' => ans.push_str("\\\\"),
'"' => ans.push_str("\\\""),
'\'' => ans.push_str("\\\'"),
'\x20'..='\x7e' if ascii_only => ans.push(c),
_ if ascii_only => ans.push_str(&c.escape_default().to_string()),
_ => ans.push(c),
}
}
ans
}
pub(crate) trait Join<Item: Display>: Iterator<Item = Item> {
fn join(&mut self, sep: &str) -> String {
if let Some(first) = self.next() {
let (lb, _) = self.size_hint();
let mut result = String::with_capacity(sep.len() * lb);
write!(&mut result, "{}", first).unwrap();
self.for_each(|i| {
result.push_str(sep);
write!(&mut result, "{}", i).unwrap();
});
result
} else {
String::new()
}
}
}
impl<T: ?Sized, Item: Display> Join<Item> for T where T: Iterator<Item = Item> {}
#[derive(Clone)]
pub(crate) struct ValueDebug<'a>(pub &'a Value);
impl Debug for ValueDebug<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
#[derive(Clone)]
pub(crate) struct ValueVecDebug<'a>(pub &'a Vec<Value>);
impl Debug for ValueVecDebug<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_list()
.entries(self.0.iter().map(ValueDebug))
.finish()
}
}