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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
|
use std::env;
use std::ffi::OsString;
use std::fs::{read_to_string, File};
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use walkdir::WalkDir;
use abnf_to_pest::render_rules_to_pest;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum FileType {
/// Dhall source file
Text,
/// Dhall binary file
Binary,
/// Text file with expected text output
UI,
}
impl FileType {
fn to_ext(self) -> &'static str {
match self {
FileType::Text => "dhall",
FileType::Binary => "dhallb",
FileType::UI => "txt",
}
}
fn constructor(self) -> &'static str {
match self {
FileType::Text => "TestFile::Source",
FileType::Binary => "TestFile::Binary",
FileType::UI => "TestFile::UI",
}
}
fn construct(self, path: &str) -> String {
// e.g. with
// path = "tests/foor/barA"
// returns something like:
// TestFile::Source("tests/foor/barA.dhall")
format!(r#"{}("{}.{}")"#, self.constructor(), path, self.to_ext())
}
}
fn dhall_files_in_dir<'a>(
dir: &'a Path,
take_ab_suffix: bool,
filetype: FileType,
) -> impl Iterator<Item = (String, String)> + 'a {
WalkDir::new(dir)
.into_iter()
.filter_map(|e| e.ok())
.filter_map(move |path| {
let path = path.path().strip_prefix(dir).unwrap();
let ext = path.extension()?;
if ext != &OsString::from(filetype.to_ext()) {
return None;
}
let path = path.to_string_lossy();
let path = &path[..path.len() - 1 - ext.len()];
let path = if take_ab_suffix && &path[path.len() - 1..] != "A" {
return None;
} else if take_ab_suffix {
path[..path.len() - 1].to_owned()
} else {
path.to_owned()
};
// Transform path into a valid Rust identifier
let name = path.replace("/", "_").replace("-", "_");
Some((name, path))
})
}
struct TestFeature {
/// Name of the module, used in the output of `cargo test`
module_name: &'static str,
/// Directory containing the tests files, relative to the base tests directory
directory: &'static str,
/// Relevant variant of `dhall::tests::Test`
variant: &'static str,
/// Given a file name, whether to exclude it
path_filter: Box<dyn FnMut(&str) -> bool>,
/// Type of the input file
input_type: FileType,
/// Type of the output file, if any
output_type: Option<FileType>,
}
fn make_test_module(
w: &mut impl Write, // Where to output the generated code
base_paths: &[&Path],
mut feature: TestFeature,
) -> std::io::Result<()> {
writeln!(w, "mod {} {{", feature.module_name)?;
let take_ab_suffix = feature.output_type.is_some()
&& feature.output_type != Some(FileType::UI);
for base_path in base_paths {
let tests_dir = base_path.join(feature.directory);
for (name, path) in
dhall_files_in_dir(&tests_dir, take_ab_suffix, feature.input_type)
{
if (feature.path_filter)(&path) {
continue;
}
let path = tests_dir.join(path);
let path = path.to_string_lossy();
let test = match feature.output_type {
None => {
let input = feature.input_type.construct(&path);
format!("{}({})", feature.variant, input)
}
Some(output_type @ FileType::UI) => {
let input = feature.input_type.construct(&path);
// All ui outputs are in the local `tests/` directory.
let output_file = PathBuf::from("tests/").join(
PathBuf::from(path.as_ref())
.strip_prefix(base_path)
.unwrap(),
);
let output =
output_type.construct(&output_file.to_str().unwrap());
format!("{}({}, {})", feature.variant, input, output)
}
Some(output_type) => {
let input =
feature.input_type.construct(&format!("{}A", path));
let output = output_type.construct(&format!("{}B", path));
format!("{}({}, {})", feature.variant, input, output)
}
};
writeln!(w, "make_spec_test!({}, {});", test, name)?;
}
}
writeln!(w, "}}")?;
Ok(())
}
fn generate_tests() -> std::io::Result<()> {
// Tries to detect when the submodule gets updated.
// To force regeneration of the test list, just `touch dhall-lang/.git`
println!("cargo:rerun-if-changed=../dhall-lang/.git");
println!(
"cargo:rerun-if-changed=../.git/modules/dhall-lang/refs/heads/master"
);
let out_dir = env::var("OUT_DIR").unwrap();
let parser_tests_path = Path::new(&out_dir).join("spec_tests.rs");
let spec_tests_dirs =
vec![Path::new("../dhall-lang/tests/"), Path::new("tests/")];
let tests = vec![
TestFeature {
module_name: "parser_success",
directory: "parser/success/",
variant: "ParserSuccess",
path_filter: Box::new(|path: &str| {
false
// Too slow in debug mode
|| path == "largeExpression"
// Pretty sure the test is incorrect
|| path == "unit/import/urls/quotedPathFakeUrlEncode"
// TODO: RFC3986 URLs
|| path == "unit/import/urls/emptyPath0"
|| path == "unit/import/urls/emptyPath1"
|| path == "unit/import/urls/emptyPathSegment"
|| path == "usingToMap"
}),
input_type: FileType::Text,
output_type: Some(FileType::Binary),
},
TestFeature {
module_name: "parser_failure",
directory: "parser/failure/",
variant: "ParserFailure",
path_filter: Box::new(|_path: &str| false),
input_type: FileType::Text,
output_type: Some(FileType::UI),
},
TestFeature {
module_name: "printer",
directory: "parser/success/",
variant: "Printer",
path_filter: Box::new(|path: &str| {
false
// Too slow in debug mode
|| path == "largeExpression"
// TODO: RFC3986 URLs
|| path == "unit/import/urls/emptyPath0"
|| path == "unit/import/urls/emptyPath1"
|| path == "unit/import/urls/emptyPathSegment"
|| path == "usingToMap"
}),
input_type: FileType::Text,
output_type: Some(FileType::Binary),
},
TestFeature {
module_name: "binary_encoding",
directory: "parser/success/",
variant: "BinaryEncoding",
path_filter: Box::new(|path: &str| {
false
// Too slow in debug mode
|| path == "largeExpression"
// Pretty sure the test is incorrect
|| path == "unit/import/urls/quotedPathFakeUrlEncode"
// See https://github.com/pyfisch/cbor/issues/109
|| path == "double"
|| path == "unit/DoubleLitExponentNoDot"
|| path == "unit/DoubleLitSecretelyInt"
// TODO: RFC3986 URLs
|| path == "unit/import/urls/emptyPath0"
|| path == "unit/import/urls/emptyPath1"
|| path == "unit/import/urls/emptyPathSegment"
|| path == "usingToMap"
}),
input_type: FileType::Text,
output_type: Some(FileType::Binary),
},
TestFeature {
module_name: "binary_decoding_success",
directory: "binary-decode/success/",
variant: "BinaryDecodingSuccess",
path_filter: Box::new(|path: &str| {
false
// We don't support bignums
|| path == "unit/IntegerBigNegative"
|| path == "unit/IntegerBigPositive"
|| path == "unit/NaturalBig"
}),
input_type: FileType::Binary,
output_type: Some(FileType::Text),
},
TestFeature {
module_name: "binary_decoding_failure",
directory: "binary-decode/failure/",
variant: "BinaryDecodingFailure",
path_filter: Box::new(|_path: &str| false),
input_type: FileType::Binary,
output_type: Some(FileType::UI),
},
TestFeature {
module_name: "import_success",
directory: "import/success/",
variant: "ImportSuccess",
path_filter: Box::new(|path: &str| {
false
|| path == "alternativeEnvNatural"
|| path == "alternativeEnvSimple"
|| path == "alternativeHashMismatch"
|| path == "asLocation"
|| path == "asText"
|| path == "customHeaders"
|| path == "hashFromCache"
|| path == "headerForwarding"
|| path == "noHeaderForwarding"
}),
input_type: FileType::Text,
output_type: Some(FileType::Text),
},
TestFeature {
module_name: "import_failure",
directory: "import/failure/",
variant: "ImportFailure",
path_filter: Box::new(|path: &str| {
false
|| path == "alternativeEnv"
|| path == "alternativeEnvMissing"
|| path == "hashMismatch"
|| path == "missing"
|| path == "referentiallyInsane"
|| path == "customHeadersUsingBoundVariable"
}),
input_type: FileType::Text,
output_type: Some(FileType::UI),
},
TestFeature {
module_name: "beta_normalize",
directory: "normalization/success/",
variant: "Normalization",
path_filter: Box::new(|path: &str| {
// We don't support bignums
path == "simple/integerToDouble"
// Too slow
|| path == "remoteSystems"
// TODO: projection by expression
|| path == "unit/RecordProjectionByTypeEmpty"
|| path == "unit/RecordProjectionByTypeNonEmpty"
|| path == "unit/RecordProjectionByTypeNormalizeProjection"
|| path == "unit/RecordProjectionByTypeWithinFieldSelection"
|| path == "unit/RecursiveRecordMergeWithinFieldSelection1"
|| path == "unit/NestedRecordProjectionByType"
// TODO: fix Double/show
|| path == "prelude/JSON/number/1"
// TODO: doesn't typecheck
|| path == "unit/RightBiasedRecordMergeWithinRecordProjection"
|| path == "unit/Sort"
// // TODO: Further record simplifications
|| path == "simplifications/rightBiasedMergeWithinRecordProjectionWithinFieldSelection0"
|| path == "simplifications/rightBiasedMergeWithinRecordProjectionWithinFieldSelection1"
|| path == "simplifications/rightBiasedMergeWithinRecursiveRecordMergeWithinFieldselection"
|| path == "simplifications/issue661"
|| path == "unit/RecordProjectionWithinFieldSelection"
|| path == "unit/RecursiveRecordMergeWithinFieldSelection0"
|| path == "unit/RecursiveRecordMergeWithinFieldSelection2"
|| path == "unit/RecursiveRecordMergeWithinFieldSelection3"
}),
input_type: FileType::Text,
output_type: Some(FileType::Text),
},
TestFeature {
module_name: "alpha_normalize",
directory: "alpha-normalization/success/",
variant: "AlphaNormalization",
path_filter: Box::new(|path: &str| {
// This test doesn't typecheck
path == "unit/FunctionNestedBindingXXFree"
}),
input_type: FileType::Text,
output_type: Some(FileType::Text),
},
TestFeature {
module_name: "type_inference_success",
directory: "type-inference/success/",
variant: "TypeInferenceSuccess",
path_filter: Box::new(|path: &str| {
false
// Too slow
|| path == "prelude"
}),
input_type: FileType::Text,
output_type: Some(FileType::Text),
},
TestFeature {
module_name: "type_inference_failure",
directory: "type-inference/failure/",
variant: "TypeInferenceFailure",
path_filter: Box::new(|path: &str| {
false
// TODO: enable free variable checking
|| path == "unit/MergeHandlerFreeVar"
}),
input_type: FileType::Text,
output_type: Some(FileType::UI),
},
];
let mut file = File::create(parser_tests_path)?;
for test in tests {
make_test_module(&mut file, &spec_tests_dirs, test)?;
}
Ok(())
}
fn convert_abnf_to_pest() -> std::io::Result<()> {
let out_dir = env::var("OUT_DIR").unwrap();
let abnf_path = "src/syntax/text/dhall.abnf";
let visibility_path = "src/syntax/text/dhall.pest.visibility";
let grammar_path = Path::new(&out_dir).join("dhall.pest");
println!("cargo:rerun-if-changed={}", abnf_path);
println!("cargo:rerun-if-changed={}", visibility_path);
let mut data = read_to_string(abnf_path)?;
data.push('\n');
let data = data.replace('∀', ""); // TODO: waiting for abnf 0.6.1
let mut rules = abnf_to_pest::parse_abnf(&data)?;
for line in BufReader::new(File::open(visibility_path)?).lines() {
let line = line?;
if line.len() >= 2 && &line[0..2] == "# " {
rules.get_mut(&line[2..]).map(|x| x.silent = true);
}
}
let mut file = File::create(grammar_path)?;
writeln!(&mut file, "// AUTO-GENERATED FILE. See build.rs.")?;
// TODO: this is a cheat; properly support RFC3986 URLs instead
rules.remove("url_path");
writeln!(&mut file, "url_path = _{{ path }}")?;
// Work around some greediness issue in the grammar.
rules.remove("missing");
writeln!(
&mut file,
r#"missing = {{ "missing" ~ !simple_label_next_char }}"#
)?;
// Prefer my nice error message to illegible parse errors.
rules.remove("unicode_escape");
rules.remove("unbraced_escape");
rules.remove("braced_escape");
rules.remove("braced_codepoint");
rules.remove("unicode_suffix");
writeln!(
&mut file,
r#"unicode_escape = _{{ HEXDIG{{4}} | "{{" ~ HEXDIG+ ~ "}}" }}"#
)?;
rules.remove("simple_label");
writeln!(
&mut file,
"simple_label = {{
keyword ~ simple_label_next_char+
| !keyword ~ simple_label_first_char ~ simple_label_next_char*
}}"
)?;
rules.remove("nonreserved_label");
writeln!(
&mut file,
"nonreserved_label = _{{
!(builtin ~ !simple_label_next_char) ~ label
}}"
)?;
// Setup grammar for precedence climbing
rules.remove("operator_expression");
writeln!(&mut file, r##"
import_alt = {{ "?" ~ whsp1 }}
bool_or = {{ "||" }}
natural_plus = {{ "+" ~ whsp1 }}
text_append = {{ "++" }}
list_append = {{ "#" }}
bool_and = {{ "&&" }}
natural_times = {{ "*" }}
bool_eq = {{ "==" }}
bool_ne = {{ "!=" }}
operator = _{{
equivalent |
bool_ne |
bool_eq |
natural_times |
combine_types |
prefer |
combine |
bool_and |
list_append |
text_append |
natural_plus |
bool_or |
import_alt
}}
operator_expression = {{ application_expression ~ (whsp ~ operator ~ whsp ~ application_expression)* }}
"##)?;
writeln!(
&mut file,
"final_expression = ${{ SOI ~ complete_expression ~ EOI }}"
)?;
writeln!(&mut file)?;
writeln!(&mut file, "{}", render_rules_to_pest(rules).pretty(80))?;
Ok(())
}
// Generate pest parser manually becaue otherwise we'd need to modify something outside of
// OUT_DIR and that's forbidden by docs.rs.
fn generate_pest_parser() -> std::io::Result<()> {
let out_dir = env::var("OUT_DIR").unwrap();
let grammar_path = Path::new(&out_dir).join("dhall.pest");
let grammar_path = grammar_path.to_str();
let output_path = Path::new(&out_dir).join("dhall_parser.rs");
let pest = quote::quote!(
#[grammar = #grammar_path]
struct DhallParser;
);
let derived = pest_generator::derive_parser(pest, false);
let file_contents = quote::quote!(
struct DhallParser;
#derived
);
let mut file = File::create(output_path)?;
writeln!(file, "{}", file_contents)
}
fn main() -> std::io::Result<()> {
convert_abnf_to_pest()?;
generate_pest_parser()?;
generate_tests()?;
Ok(())
}
|