use std::env;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use raf_source::{LoadError, LoadErrorKind, MemoryTree, RelPath, Workspace};
const SELECTOR: &str = "RAF_SOURCE_CHILD";
const MARK: &str = "RAF_CHILD ";
const REFUSED: i32 = 3;
const OVERFLOW_MESSAGE: &str = "has overflowed its stack";
const FAILED: i32 = 4;
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Outcome {
Refused { file: String, budget: String },
Index(Vec<String>),
Aborted { detail: String },
Failed { message: String },
}
pub(crate) fn symbols(workspace: &Workspace) -> Vec<String> {
workspace
.items()
.filter_map(|item| item.path.strip_prefix("demo::"))
.filter(|name| !name.contains("::"))
.map(str::to_owned)
.collect()
}
fn library(file: &RelPath, text: String) -> MemoryTree {
let manifest = format!(
"[package]\nname = \"demo\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[lib]\npath = \"{file}\"\n"
);
[
("Cargo.toml".to_owned(), manifest),
(file.to_string(), text),
]
.into_iter()
.collect()
}
pub(crate) fn selector() -> Option<String> {
env::var_os(SELECTOR).map(|selector| selector.to_string_lossy().into_owned())
}
pub(crate) fn run_child_if_requested(text_of: impl FnOnce(&str) -> String) {
run_child_if_requested_with(text_of, |_, _| {});
}
pub(crate) fn run_child_if_requested_with(
text_of: impl FnOnce(&str) -> String,
compare: impl FnOnce(&MemoryTree, &Result<Workspace, LoadError>),
) {
let Some(selector) = selector() else {
return;
};
let (name, text) = (selector.clone(), text_of(&selector));
let file = RelPath::new(&format!("{name}.rs")).expect("the selector is a plain name");
let tree = library(&file, text);
let loaded = Workspace::load(&tree, &["."]);
compare(&tree, &loaded);
let code = match loaded {
Ok(workspace) => {
println!("{MARK}index {}", symbols(&workspace).join(","));
0
}
Err(error) => {
if let LoadErrorKind::Budget { budget, .. } = &error.kind {
println!("{MARK}refused {} {budget}", error.file);
REFUSED
} else {
println!("{MARK}failed {error}");
FAILED
}
}
};
std::process::exit(code);
}
pub(crate) fn run_child(test: &str, selector: &str) -> Outcome {
let executable: PathBuf = env::current_exe().expect("the test binary has a path");
let output = Command::new(executable)
.args(["--exact", test, "--nocapture", "--test-threads=1"])
.env(SELECTOR, selector)
.env_remove("RUST_MIN_STACK")
.stdin(Stdio::null())
.output()
.expect("start the child");
let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
classify(
output.status.code(),
died_by_signal(output.status),
&stdout,
&stderr,
)
}
#[cfg(unix)]
fn died_by_signal(status: std::process::ExitStatus) -> bool {
use std::os::unix::process::ExitStatusExt as _;
status.signal().is_some()
}
#[cfg(not(unix))]
fn died_by_signal(_status: std::process::ExitStatus) -> bool {
false
}
const WINDOWS_STACK_OVERFLOW: i32 = 0xC000_00FD_u32.cast_signed();
pub(crate) fn classify(code: Option<i32>, signaled: bool, stdout: &str, stderr: &str) -> Outcome {
let line = stdout
.lines()
.find_map(|line| line.split_once(MARK))
.map(|(_, rest)| rest.to_owned());
match (code, line) {
(Some(0), Some(line)) => match line.strip_prefix("index ") {
Some(list) => Outcome::Index(if list.is_empty() {
Vec::new()
} else {
list.split(',').map(str::to_owned).collect()
}),
None => Outcome::Failed {
message: format!("exit 0 with a line that is not an index: {line}"),
},
},
(Some(REFUSED), Some(line)) => match line.strip_prefix("refused ") {
Some(rest) => match rest.split_once(' ') {
Some((file, budget)) => Outcome::Refused {
file: file.to_owned(),
budget: budget.to_owned(),
},
None => Outcome::Failed {
message: format!("a refusal without a budget: {rest}"),
},
},
None => Outcome::Failed {
message: format!("exit {REFUSED} with a line that is not a refusal: {line}"),
},
},
(Some(FAILED), Some(line)) => Outcome::Failed { message: line },
(code, line) => {
let overflow = stderr.contains(OVERFLOW_MESSAGE);
if line.is_none() && (signaled || overflow || code == Some(WINDOWS_STACK_OVERFLOW)) {
Outcome::Aborted {
detail: format!("status {code:?}; stderr tail: {}", tail(stderr)),
}
} else {
Outcome::Failed {
message: format!(
"status {code:?} is not an abort; result line {line:?}; stderr tail: {}",
tail(stderr)
),
}
}
}
}
}
fn tail(text: &str) -> String {
const KEEP: usize = 4000;
let start = text.char_indices().rev().nth(KEEP).map_or(0, |(at, _)| at);
text[start..].to_owned()
}
pub(crate) fn problem(outcome: &Outcome, file: &str, expected: &[&str]) -> Option<String> {
match outcome {
Outcome::Refused {
file: named,
budget,
} => {
if named != file {
Some(format!("refusal names {named:?}, not {file:?}"))
} else if budget.is_empty() {
Some("refusal does not name a budget".to_owned())
} else {
None
}
}
Outcome::Index(found) => {
if found
.iter()
.map(String::as_str)
.eq(expected.iter().copied())
{
None
} else {
Some(format!(
"exit 0 with the index {found:?}, expected {expected:?}"
))
}
}
Outcome::Aborted { detail } => Some(format!("the parse aborted: {detail}")),
Outcome::Failed { message } => Some(format!("failed outside the two outcomes: {message}")),
}
}