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
#![allow(clippy::result_unit_err)]
use std::{cell::RefCell, collections::HashMap};
use regex::Regex;
use thiserror::Error;
const PARSE_DEBUG: bool = true;
#[derive(Debug, Copy, Clone, Hash, PartialEq)]
pub struct FileLocation {
pub line_number: usize,
pub position: usize,
pub index: usize,
}
impl FileLocation {
pub fn start() -> Self {
Self {
line_number: 1,
position: 0,
index: 0,
}
}
pub fn advanced_by(mut self, text: &str) -> Self {
let lines = text.chars().filter(|c| *c == '\n').count();
self.line_number += lines;
self.index += text.len();
if lines > 0 {
let last_newline = text.rfind('\n').unwrap();
self.position = text.len() - last_newline;
} else {
self.position += text.len();
}
self
}
}
impl std::fmt::Display for FileLocation {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "line {}:{}", self.line_number, self.position)
}
}
#[derive(Debug, Clone, Hash, PartialEq)]
pub struct TextLit<'a> {
pub text: &'a str,
pub location: FileLocation,
}
impl<'a> TextLit<'a> {
pub fn new(text: &'a str, location: FileLocation) -> Self {
Self { text, location }
}
}
#[derive(Error, Debug, Clone)]
pub struct ParseError {
pub message: &'static str,
pub at: FileLocation,
pub child_errors: Vec<ParseError>,
}
impl ParseError {
pub fn new(message: &'static str, at: FileLocation) -> Self {
Self {
message,
at,
child_errors: Vec::new(),
}
}
pub fn with_child(message: &'static str, at: FileLocation, child: ParseError) -> Self {
if child.child_errors.len() == 1 {
Self {
message,
at,
child_errors: child.child_errors,
}
} else {
Self {
message,
at,
child_errors: vec![child],
}
}
}
pub fn with_children(
message: &'static str,
at: FileLocation,
children: Vec<ParseError>,
) -> Self {
Self {
message,
at,
child_errors: children,
}
}
}
impl std::fmt::Display for ParseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "{}", ParseErrorFmtDepth(self, 0))?;
Ok(())
}
}
struct ParseErrorFmtDepth<'a>(&'a ParseError, usize);
impl std::fmt::Display for ParseErrorFmtDepth<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let err = self.0;
let depth = self.1;
for _ in 0..depth {
write!(f, " ")?;
}
writeln!(f, "{} at {}", err.message, err.at)?;
for child in &err.child_errors {
write!(f, "{}", ParseErrorFmtDepth(child, depth + 1))?;
}
Ok(())
}
}
#[derive(Debug, Clone, Copy)]
pub struct StringParser<'a> {
pub text: &'a str,
pub pos: FileLocation,
}
impl<'a> StringParser<'a> {
pub fn new(input: &'a str) -> Self {
Self {
text: input,
pos: FileLocation::start(),
}
}
pub fn split_at(&self, pos: usize) -> (TextLit<'a>, Self) {
let (left, right) = self.text.split_at(pos);
let forked = Self {
text: right,
pos: self.pos.advanced_by(left),
};
let left = TextLit::new(left, self.pos);
(left, forked)
}
pub fn is_empty(&self) -> bool {
self.text.is_empty()
}
}
thread_local! {
pub static REGEXES: RefCell<HashMap<String,Regex>> = RefCell::new(HashMap::new());
}
pub fn parse_string_lit<'a>(
input: StringParser<'a>,
lit: &'static str,
) -> Result<(TextLit<'a>, StringParser<'a>), ()> {
if input.text.starts_with(lit) {
if PARSE_DEBUG {
println!("Matched string literal: {:?} at {}", lit, input.pos);
}
Ok(input.split_at(lit.len()))
} else {
if PARSE_DEBUG {
println!("Failed to match string literal: {:?} at {}", lit, input.pos);
}
Err(())
}
}
pub fn get_regex(regex: &str) -> Regex {
REGEXES.with(|regexes| {
let mut regexes = regexes.borrow_mut();
if let Some(regex) = regexes.get(regex) {
regex.clone()
} else {
let new_regex = Regex::new(&format!("^{}", regex)).unwrap();
regexes.insert(regex.to_string(), new_regex.clone());
new_regex
}
})
}
pub fn parse_string_regex<'a>(
input: StringParser<'a>,
regex_str: &'static str,
) -> Result<(TextLit<'a>, StringParser<'a>), ()> {
let regex = get_regex(regex_str);
if let Some(captures) = regex.find_at(input.text, 0) {
if PARSE_DEBUG {
println!("Matched regex: {:?} at {}", regex_str, input.pos);
}
let capture = captures;
Ok(input.split_at(capture.end()))
} else {
if PARSE_DEBUG {
println!("Failed to match regex: {:?} at {}", regex_str, input.pos);
}
Err(())
}
}