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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
use std::fmt;
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;
use crate::ParseErrorKind::InvalidIncludeFile;
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Location {
file: Arc<str>,
line: u32,
}
impl fmt::Display for Location {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}:{}", self.file, self.line)
}
}
impl Location {
pub fn file(&self) -> &str {
&self.file
}
pub fn line(&self) -> u32 {
self.line
}
fn new(file: impl Into<Arc<str>>, line: u32) -> Self {
Self {
file: file.into(),
line,
}
}
#[must_use]
fn map_line(self, op: impl Fn(u32) -> u32) -> Self {
Self {
file: self.file,
line: op(self.line),
}
}
}
#[derive(Debug, PartialEq, Clone)]
#[non_exhaustive]
pub enum Record {
Include { loc: Location, filename: String },
Statement {
loc: Location,
conditions: Vec<Condition>,
error: bool,
sql: String,
expected_count: Option<u64>,
},
Query {
loc: Location,
conditions: Vec<Condition>,
type_string: String,
sort_mode: Option<SortMode>,
label: Option<String>,
sql: String,
expected_results: String,
},
Sleep { loc: Location, duration: Duration },
Subtest { loc: Location, name: String },
Halt { loc: Location },
Control(Control),
}
#[derive(Debug, PartialEq, Clone)]
pub enum Control {
SortMode(SortMode),
BeginInclude(String),
EndInclude(String),
}
#[derive(Debug, PartialEq, Clone)]
pub enum Condition {
OnlyIf { engine_name: String },
SkipIf { engine_name: String },
}
impl Condition {
pub fn should_skip(&self, target_name: &str) -> bool {
match self {
Condition::OnlyIf { engine_name } => engine_name != target_name,
Condition::SkipIf { engine_name } => engine_name == target_name,
}
}
}
#[derive(Debug, PartialEq, Clone)]
pub enum SortMode {
NoSort,
RowSort,
ValueSort,
}
impl SortMode {
pub fn try_from_str(s: &str) -> Result<Self, ParseErrorKind> {
match s {
"nosort" => Ok(Self::NoSort),
"rowsort" => Ok(Self::RowSort),
"valuesort" => Ok(Self::ValueSort),
_ => Err(ParseErrorKind::InvalidSortMode(s.to_string())),
}
}
pub fn as_str(&self) -> &'static str {
match self {
Self::NoSort => "nosort",
Self::RowSort => "rowsort",
Self::ValueSort => "valuesort",
}
}
}
#[derive(thiserror::Error, Debug, PartialEq, Clone)]
#[error("parse error at {loc}: {kind}")]
pub struct ParseError {
kind: ParseErrorKind,
loc: Location,
}
impl ParseError {
pub fn kind(&self) -> ParseErrorKind {
self.kind.clone()
}
pub fn location(&self) -> Location {
self.loc.clone()
}
}
#[derive(thiserror::Error, Debug, PartialEq, Clone)]
pub enum ParseErrorKind {
#[error("unexpected token: {0:?}")]
UnexpectedToken(String),
#[error("unexpected EOF")]
UnexpectedEOF,
#[error("invalid sort mode: {0:?}")]
InvalidSortMode(String),
#[error("invalid line: {0:?}")]
InvalidLine(String),
#[error("invalid type string: {0:?}")]
InvalidType(String),
#[error("invalid number: {0:?}")]
InvalidNumber(String),
#[error("invalid duration: {0:?}")]
InvalidDuration(String),
#[error("invalid control: {0:?}")]
InvalidControl(String),
#[error("invalid include file pattern: {0:?}")]
InvalidIncludeFile(String),
}
impl ParseErrorKind {
fn at(self, loc: Location) -> ParseError {
ParseError { kind: self, loc }
}
}
const DEFAULT_FILENAME: &str = "<entry>";
pub fn parse(script: &str) -> Result<Vec<Record>, ParseError> {
parse_inner(Arc::from(DEFAULT_FILENAME), script)
}
#[allow(clippy::collapsible_match)]
fn parse_inner(filename: Arc<str>, script: &str) -> Result<Vec<Record>, ParseError> {
let mut lines = script.split('\n').enumerate();
let mut records = vec![];
let mut conditions = vec![];
while let Some((num, line)) = lines.next() {
if line.is_empty() || line.starts_with('#') {
continue;
}
let loc = Location::new(filename.clone(), num as u32 + 1);
let tokens: Vec<&str> = line.split_whitespace().collect();
match tokens.as_slice() {
[] => continue,
["include", included] => records.push(Record::Include {
loc,
filename: included.to_string(),
}),
["halt"] => {
records.push(Record::Halt { loc });
break;
}
["subtest", name] => {
records.push(Record::Subtest {
loc,
name: name.to_string(),
});
}
["sleep", dur] => {
records.push(Record::Sleep {
duration: humantime::parse_duration(dur).map_err(|_| {
ParseErrorKind::InvalidDuration(dur.to_string()).at(loc.clone())
})?,
loc,
});
}
["skipif", engine_name] => {
conditions.push(Condition::SkipIf {
engine_name: engine_name.to_string(),
});
}
["onlyif", engine_name] => {
conditions.push(Condition::OnlyIf {
engine_name: engine_name.to_string(),
});
}
["statement", res @ ..] => {
let mut expected_count = None;
let error = match res {
["ok"] => false,
["error"] => true,
["count", count_str] => {
expected_count = Some(count_str.parse::<u64>().map_err(|_| {
ParseErrorKind::InvalidNumber((*count_str).into()).at(loc.clone())
})?);
false
}
_ => return Err(ParseErrorKind::InvalidLine(line.into()).at(loc)),
};
let mut sql = lines
.next()
.ok_or_else(|| {
ParseErrorKind::UnexpectedEOF.at(loc.clone().map_line(|line| line + 1))
})?
.1
.into();
for (_, line) in &mut lines {
if line.is_empty() {
break;
}
sql += "\n";
sql += line;
}
records.push(Record::Statement {
loc,
conditions: std::mem::take(&mut conditions),
error,
sql,
expected_count,
});
}
["query", type_string, res @ ..] => {
let sort_mode = match res.get(0).map(|&s| SortMode::try_from_str(s)).transpose() {
Ok(sm) => sm,
Err(k) => return Err(k.at(loc)),
};
let label = res.get(1).map(|s| s.to_string());
let mut sql = lines
.next()
.ok_or_else(|| {
ParseErrorKind::UnexpectedEOF.at(loc.clone().map_line(|line| line + 1))
})?
.1
.into();
let mut has_result = false;
for (_, line) in &mut lines {
if line.is_empty() {
break;
}
if line == "----" {
has_result = true;
break;
}
sql += "\n";
sql += line;
}
let mut expected_results = String::new();
if has_result {
for (_, line) in &mut lines {
if line.is_empty() {
break;
}
expected_results += line;
expected_results.push('\n');
}
}
records.push(Record::Query {
loc,
conditions: std::mem::take(&mut conditions),
type_string: type_string.to_string(),
sort_mode,
label,
sql,
expected_results,
});
}
["control", res @ ..] => match res {
["sortmode", sort_mode] => match SortMode::try_from_str(sort_mode) {
Ok(sort_mode) => records.push(Record::Control(Control::SortMode(sort_mode))),
Err(k) => return Err(k.at(loc)),
},
_ => return Err(ParseErrorKind::InvalidLine(line.into()).at(loc)),
},
_ => return Err(ParseErrorKind::InvalidLine(line.into()).at(loc)),
}
}
Ok(records)
}
pub fn parse_file(filename: impl AsRef<Path>) -> Result<Vec<Record>, ParseError> {
parse_file_inner(
Arc::from(filename.as_ref().to_str().unwrap()),
filename.as_ref(),
)
}
fn parse_file_inner(filename: Arc<str>, path: &Path) -> Result<Vec<Record>, ParseError> {
let script = std::fs::read_to_string(path).unwrap();
let mut records = vec![];
for rec in parse_inner(filename, &script)? {
if let Record::Include { filename, loc } = rec {
let complete_filename = {
let mut path_buf = path.to_path_buf();
path_buf.pop();
path_buf.push(filename.clone());
path_buf.as_os_str().to_string_lossy().to_string()
};
for included_file in glob::glob(&complete_filename)
.map_err(|e| InvalidIncludeFile(format!("{:?}", e)).at(loc))?
.filter_map(Result::ok)
{
let new_filename_str = included_file.as_os_str().to_string_lossy().to_string();
let new_filename = Arc::from(new_filename_str.clone());
let new_path = included_file.as_path();
records.push(Record::Control(Control::BeginInclude(
new_filename_str.clone(),
)));
records.extend(parse_file_inner(new_filename, new_path)?);
records.push(Record::Control(Control::EndInclude(
new_filename_str.clone(),
)));
}
} else {
records.push(rec);
}
}
Ok(records)
}
#[cfg(test)]
mod tests {
use crate::parse_file;
#[test]
fn test_include_glob() {
let records = parse_file("examples/include_1.slt").unwrap();
assert_eq!(12, records.len());
}
}