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#![feature(let_chains)]
use std::collections::BTreeSet;
use std::io::{BufRead, Write};
use std::path::{Path, PathBuf};
use anyhow::{bail, Context};
use clap::{Parser, Subcommand};
use confique::{toml::FormatOptions, Config as ConfigParser};
use indicatif::{ProgressBar, ProgressIterator, ProgressStyle};
use tracing::*;
mod logging;
const TARGET: &str = env!("TARGET");
#[derive(Debug, Parser)]
#[command(version, about, long_about = None)]
pub(crate) struct Cli {
#[command(subcommand)]
pub(crate) command: Command,
}
#[derive(Debug, Subcommand)]
pub(crate) enum Command {
/// Generate a default config file at `$CWD/migration_config.toml`.
GenerateConfig,
/// Using the collected directives from `rustc` repo generated by the collection tool,
/// replace all `//` directives with `//@` directives.
Migrate {
/// Path to the `rustc` repo to operate the tool on. Note that this tool consumes output
/// generated by a test directive collection script beforehand.
#[clap(value_name = "PATH_TO_RUSTC")]
path_to_rustc: PathBuf,
},
/// From the collected directives from `rustc` repo generated by the collection tool, output
/// a Rust array consisting of directive names (does not include revisions or values or
/// comments).
CollectDirectiveNames {
/// Path to the `rustc` repo to operate the tool on. Note that this tool consumes output
/// generated by a test directive collection script beforehand.
#[clap(value_name = "PATH_TO_RUSTC")]
path_to_rustc: PathBuf,
},
}
#[derive(Debug, Default, ConfigParser)]
pub(crate) struct Config {
/// Manually specify directives. This is mostly used to override some special tests that are
/// not properly handled by the collection script.
#[config(default = [])]
pub(crate) manual_directives: Vec<String>,
}
fn main() -> anyhow::Result<()> {
logging::setup_logging();
let config_path = PathBuf::from("migration_config.toml");
if !config_path.exists() {
info!("migration_config.toml does not exist, default values will be used");
}
let config = Config::from_file(&config_path).unwrap_or_default();
debug!(?config);
let cli = Cli::parse();
debug!(?cli);
match &cli.command {
Command::GenerateConfig => {
if !config_path.exists() {
let template = confique::toml::template::<Config>(FormatOptions::default());
std::fs::write(&config_path, template)?;
} else {
error!("migration_config.toml already exists");
eprintln!("migration_config.toml already exists, no config will be generated");
bail!("migration_config.toml already exists!");
}
}
Command::Migrate { path_to_rustc } => {
let mut collected_directives = collect_directives(path_to_rustc.as_path())?;
collected_directives.extend(config.manual_directives);
migrate_compiletest_tests(path_to_rustc.as_path(), &collected_directives)?;
migrate_coverage_maps(path_to_rustc.as_path(), &collected_directives)?;
}
Command::CollectDirectiveNames { path_to_rustc } => {
let mut collected_directives = collect_directives(path_to_rustc.as_path())?;
collected_directives.extend(config.manual_directives);
let directive_names = extract_directive_names(&collected_directives)?;
println!("{:?}", directive_names.iter().collect::<Vec<_>>());
}
}
Ok(())
}
fn collect_directives(path_to_rustc: &Path) -> anyhow::Result<BTreeSet<String>> {
debug!(?path_to_rustc);
assert!(path_to_rustc.exists(), "$PATH_TO_RUSTC_REPO does not exist");
let mut collected_directives_path = PathBuf::new();
collected_directives_path.push(&path_to_rustc);
collected_directives_path.push("build");
collected_directives_path.push(TARGET);
collected_directives_path.push("test");
collected_directives_path.push("__directive_lines");
debug!(directives_path = ?collected_directives_path.with_extension("txt"));
let collected_directives =
std::fs::read_to_string(collected_directives_path.with_extension("txt"))
.context("failed to read collected directives")?;
let mut collected_directives = collected_directives
.lines()
.map(ToOwned::to_owned)
.collect::<BTreeSet<String>>();
collected_directives.retain(|directive| {
!directive.trim().is_empty() // skip empty directives
&& directive.trim() != "//" // skip empty comment
&& !directive.trim().starts_with('#') // skip makefile directives
&& directive.split_once("//").map(|(_, post)| {
!post.trim().starts_with("ignore-tidy")
}).unwrap_or(true)
});
info!(
"there are {} collected directives",
collected_directives.len()
);
Ok(collected_directives)
}
fn migrate_compiletest_tests(
path_to_rustc: &Path,
collected_directives: &BTreeSet<String>,
) -> anyhow::Result<()> {
// Collect paths of compiletest test files
let walker = walkdir::WalkDir::new(path_to_rustc.join("tests"))
.sort_by_file_name()
.into_iter()
.filter_map(Result::ok)
.filter(|e| {
!e.file_type().is_dir()
&& e.path()
.extension()
.map(|s| s == "rs" || s == "fixed")
.unwrap_or(false)
// We already migrated ui test suite tests
&& !e.path().starts_with(path_to_rustc.join("tests").join("ui"))
})
.map(|e| e.into_path());
let test_file_paths = walker.collect::<BTreeSet<_>>();
info!("there are {} compiletest test files", test_file_paths.len());
let pb = ProgressBar::new(test_file_paths.len() as u64);
pb.set_style(
ProgressStyle::with_template(
"migrating compiletest tests: {spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] ({pos}/{len}, ETA {eta})",
)
.unwrap(),
);
for path in test_file_paths.iter().progress_with(pb) {
// - Read the contents of the compiletest test file
// - Open a named temporary file
// - Process each line of the compiletest test:
// - If line starts with "//", try to match it with one of the collected directives.
// If a match is found, replace "//" with "//@" and append line to temp file.
// - Otherwise, append line verbatim to temp file.
// - Replace original compiletest test with temp file.
let compiletest_test_file = std::fs::File::open(&path)?;
let mut reader = std::io::BufReader::new(compiletest_test_file);
let mut tmp_file = tempfile::NamedTempFile::new()?;
let mut line_buf = String::new();
'line: loop {
line_buf.clear();
let bytes_read = reader.read_line(&mut line_buf)?;
if bytes_read == 0 {
break;
}
if line_buf.trim_start().starts_with("//") {
let (before, after) = line_buf.split_once("//").unwrap();
if !after.starts_with('@') {
for directive in collected_directives.iter() {
if line_buf.replace("\r", "").replace("\n", "") == *directive {
write!(tmp_file, "{}//@{}", before, after)?;
continue 'line;
}
}
}
// No matched directive, very unlikely a directive and instead just a comment
write!(tmp_file, "{}", line_buf)?;
} else {
write!(tmp_file, "{}", line_buf)?;
}
}
let tmp_path = tmp_file.into_temp_path();
tmp_path.persist(path)?;
}
Ok(())
}
fn migrate_coverage_maps(
path_to_rustc: &Path,
collected_directives: &BTreeSet<String>,
) -> anyhow::Result<()> {
// Collect paths of compiletest coverage maps
let walker = walkdir::WalkDir::new(path_to_rustc.join("tests"))
.sort_by_file_name()
.into_iter()
.filter_map(Result::ok)
.filter(|e| {
!e.file_type().is_dir()
&& e.path()
.extension()
.map(|s| s == "coverage")
.unwrap_or(false)
// Only search in tests/{coverage,coverage-run-rustdoc}
&& (e.path().starts_with(path_to_rustc.join("tests").join("coverage")) ||
e.path().starts_with(path_to_rustc.join("tests").join("coverage-run-rustdoc")))
})
.map(|e| e.into_path());
let coverage_map_paths = walker.collect::<BTreeSet<_>>();
info!(
"there are {} compiletest coverage files",
coverage_map_paths.len()
);
let pb = ProgressBar::new(coverage_map_paths.len() as u64);
pb.set_style(
ProgressStyle::with_template(
"migrating compiletest coverage files: {spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] ({pos}/{len}, ETA {eta})",
)
.unwrap(),
);
for path in coverage_map_paths.iter().progress_with(pb) {
// - Read the contents of the compiletest test file
// - Open a named temporary file
// - Process each line of the compiletest test:
// - If line starts with "//", try to match it with one of the collected directives.
// If a match is found, replace "//" with "//@" and append line to temp file.
// - Otherwise, append line verbatim to temp file.
// - Replace original compiletest test with temp file.
let compiletest_coverage_file = std::fs::File::open(&path)?;
let mut reader = std::io::BufReader::new(compiletest_coverage_file);
let mut tmp_file = tempfile::NamedTempFile::new()?;
let mut line_buf = String::new();
'line: loop {
line_buf.clear();
let bytes_read = reader.read_line(&mut line_buf)?;
if bytes_read == 0 {
break;
}
if line_buf.starts_with(" LL| |")
&& let Some((pre, post)) = line_buf.split_once(" LL| |")
{
if !pre.is_empty() {
error!(path = %path.display(), ?line_buf, "pre not empty: `{}`", pre);
bail!("wtf?");
}
if let Some((inner_pre, inner_post)) = post.split_once("//") {
if !inner_post.starts_with('@') {
for directive in collected_directives.iter() {
if post.replace("\r", "").replace("\n", "") == *directive {
write!(
tmp_file,
"{} LL| |{}//@{}",
pre, inner_pre, inner_post
)?;
continue 'line;
}
}
}
}
// No matched directive, very unlikely a directive and instead just a comment
write!(tmp_file, "{}", line_buf)?;
} else {
write!(tmp_file, "{}", line_buf)?;
}
}
let tmp_path = tmp_file.into_temp_path();
tmp_path.persist(path)?;
}
Ok(())
}
fn extract_directive_names(
collected_directives: &BTreeSet<String>,
) -> anyhow::Result<BTreeSet<String>> {
let mut ret = BTreeSet::new();
for raw_directive in collected_directives {
// Directives can take the forms:
// 1. `// name` or with value or with comments:
// - `// name: <rest>`
// - `// name <rest>`
// 2. `//[rev] name` or with value or with commments:
// - `//[rev] name: ...`
// - `//[rev] name ...`
// There may be arbitrary whitespace between `//`, `[rev]` and `name`.
// First, let's get rid of the `//`.
let Some((leading, rest)) = raw_directive.split_once("//") else {
bail!("failed to split `{}`", raw_directive);
};
assert!(
leading.trim().is_empty(),
"expected directive to be leading in the line, there's a bug in the collection script"
);
let rest = rest.trim_start();
let rest = rest.trim_start_matches('@');
// Next, let's get rid of revisions.
let mut rest = if let Some(lbracket_pos) = rest.find('[')
&& rest.starts_with('[')
{
let Some(rbracket_pos) = rest.find(']') else {
error!(
?raw_directive,
?lbracket_pos,
"weird directive: `{:?}`",
rest
);
panic!("directive found with unpaired [] delimiters");
};
if lbracket_pos > rbracket_pos {
error!(
?raw_directive,
?lbracket_pos,
?rbracket_pos,
"weird directive: `{:?}`",
rest
);
}
assert!(lbracket_pos <= rbracket_pos);
let rest = &rest[(rbracket_pos + 1)..];
rest.trim_start()
} else {
rest.trim_start()
};
// Special case: one of the test files has some weird syntax like
// `// [rev]: directive-name`...
if rest.starts_with(':') {
// ... so skip that pesky colon.
rest = &rest[1..];
rest = rest.trim_start();
}
// Now, let's extract the directive name.
let directive_name = if let Some((directive_name, _)) = rest.split_once([':', ' ']) {
directive_name.trim()
} else {
let directive_name = rest;
assert!(!directive_name.trim().contains([' ']));
directive_name.trim()
};
ret.insert(directive_name.to_owned());
}
Ok(ret)
}