mod common;
use std::io::Read;
use std::path::{Path, PathBuf};
use serde_json::{Map, Value as JsonValue};
use tabnas::Value;
const STDINT_TYPEDEFS: &[&str] = &[
"int8_t",
"int16_t",
"int32_t",
"int64_t",
"uint8_t",
"uint16_t",
"uint32_t",
"uint64_t",
"size_t",
"ssize_t",
"ptrdiff_t",
"intptr_t",
"uintptr_t",
"wchar_t",
"wint_t",
"time_t",
"clock_t",
"off_t",
"FILE",
"va_list",
];
const SCALAR_KEYS: &[&str] = &[
"declKind",
"declaredName",
"callee",
"isMacro",
"op",
"jumpKind",
"labelKind",
"labelName",
"qualifiers",
"literalKind",
"value",
"name",
"memberName",
"associationKind",
"tagName",
"attributeForm",
"attributeName",
"attributePrefix",
"directive",
"macroName",
"macroKind",
"macroParams",
"macroVariadic",
"includeForm",
"headerKind",
"headerName",
"branchKind",
];
fn is_trivia(tname: &str) -> bool {
matches!(
tname,
"TRIVIA_LINE_COMMENT" | "TRIVIA_BLOCK_COMMENT" | "TRIVIA_LINE_CONT"
)
}
fn to_fixture(node: &Value) -> Option<JsonValue> {
let entries = match object_of(node) {
Some(entries) => entries,
None => {
return match node {
Value::Array(_) | Value::ListRef(_) => Some(JsonValue::Object(Map::new())),
_ => None,
};
}
};
if string_at(&entries, "kind").as_deref() == Some("token") {
let tname = string_at(&entries, "tname").unwrap_or_default();
if is_trivia(&tname) {
return None;
}
let mut token = Map::new();
token.insert("k".to_string(), JsonValue::String("tok".to_string()));
token.insert("t".to_string(), JsonValue::String(tname));
token.insert(
"s".to_string(),
JsonValue::String(string_at(&entries, "src").unwrap_or_default()),
);
return Some(JsonValue::Object(token));
}
let mut out = Map::new();
if let Some(kind) = string_at(&entries, "kind") {
out.insert("k".to_string(), JsonValue::String(kind));
}
for key in SCALAR_KEYS {
let Some(value) = entries.get(*key) else {
continue;
};
match value {
Value::Undefined | Value::Null => continue,
Value::Object(_) | Value::MapRef(_) => continue,
Value::Array(_) | Value::ListRef(_) => {
let items = list_of(value);
if items.iter().any(|item| {
matches!(
item,
Value::Object(_) | Value::MapRef(_) | Value::Array(_) | Value::ListRef(_)
) || matches!(item, Value::Null)
}) {
continue;
}
out.insert(
(*key).to_string(),
JsonValue::Array(items.iter().map(json_scalar).collect()),
);
}
scalar => {
out.insert((*key).to_string(), json_scalar(scalar));
}
}
}
if let Some(children) = entries.get("children") {
let children = list_of(children);
if !children.is_empty() {
let kept: Vec<JsonValue> = children.iter().filter_map(to_fixture).collect();
if !kept.is_empty() {
out.insert("children".to_string(), JsonValue::Array(kept));
}
}
}
Some(JsonValue::Object(out))
}
fn json_scalar(value: &Value) -> JsonValue {
match value {
Value::Number(number) if number.fract() == 0.0 && number.abs() < 9e15 => {
JsonValue::from(*number as i64)
}
other => other.to_json(),
}
}
fn object_of(value: &Value) -> Option<indexmap::IndexMap<String, Value>> {
match value {
Value::Object(entries) => Some((**entries).clone()),
Value::MapRef(map) => Some(map.value.clone()),
_ => None,
}
}
fn list_of(value: &Value) -> Vec<Value> {
match value {
Value::Array(items) => items.to_vec(),
Value::ListRef(list) => list.value.to_vec(),
_ => Vec::new(),
}
}
fn string_at(entries: &indexmap::IndexMap<String, Value>, key: &str) -> Option<String> {
match entries.get(key) {
Some(Value::String(text)) => Some(text.clone()),
_ => None,
}
}
fn corpus_dir() -> PathBuf {
repo_root().join("ts/test/csmith-corpus")
}
fn fixtures_dir() -> PathBuf {
repo_root().join("ts/test/csmith-fixtures")
}
fn repo_root() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.parent()
.expect("rs/ has a parent")
.to_path_buf()
}
fn normalise_eol(text: &str) -> String {
text.replace("\r\n", "\n").replace('\r', "\n")
}
fn gunzip(path: &Path) -> std::io::Result<Vec<u8>> {
let file = std::fs::File::open(path)?;
let mut out = Vec::new();
flate2::read::GzDecoder::new(file).read_to_end(&mut out)?;
Ok(out)
}
fn first_text_diff(got: &str, want: &str) -> String {
let at = got
.bytes()
.zip(want.bytes())
.position(|(left, right)| left != right)
.unwrap_or_else(|| got.len().min(want.len()));
let from = at.saturating_sub(60);
let window = |text: &str| {
let mut start = from.min(text.len());
while start > 0 && !text.is_char_boundary(start) {
start -= 1;
}
let mut end = (at + 60).min(text.len());
while end > start && !text.is_char_boundary(end) {
end -= 1;
}
text[start..end].to_string()
};
format!(
"at byte {at} of {} (fixture has {}):\n got: ...{}...\n want: ...{}...",
got.len(),
want.len(),
window(got),
window(want)
)
}
#[test]
fn csmith_corpus_matches_the_golden_fixtures() {
let corpus = corpus_dir();
let mut seeds: Vec<PathBuf> = match std::fs::read_dir(&corpus) {
Ok(entries) => entries
.filter_map(|entry| entry.ok().map(|entry| entry.path()))
.filter(|path| {
path.extension().is_some_and(|ext| ext == "c")
&& path
.file_name()
.is_some_and(|name| name.to_string_lossy().starts_with("seed-"))
})
.collect(),
Err(error) => panic!("the Csmith corpus is not readable at {corpus:?}: {error}"),
};
seeds.sort();
assert!(
!seeds.is_empty(),
"the Csmith corpus at {corpus:?} is empty, so nothing was graded"
);
let parser = tabnas_c::make_with(&tabnas_c::COptions::new().with_extended(true));
let mut meta = tabnas_c::CMeta::new();
for name in STDINT_TYPEDEFS {
meta.symbols.bind_typedef(name);
}
let mut passed = 0usize;
let mut failures: Vec<String> = Vec::new();
for path in &seeds {
let name = path.file_stem().unwrap().to_string_lossy().to_string();
let source = normalise_eol(&std::fs::read_to_string(path).expect("a seed is readable"));
let value = match tabnas_c::parse_with_meta(&parser, &source, &meta) {
Ok(value) => value,
Err(error) => {
failures.push(format!("{name}: parse failed with {}", error.code));
continue;
}
};
if object_of(&value)
.and_then(|entries| string_at(&entries, "kind"))
.as_deref()
!= Some("translation_unit")
{
failures.push(format!("{name}: the root is not a translation_unit"));
continue;
}
let unknown = object_of(&value)
.and_then(|entries| entries.get("children").map(list_of))
.unwrap_or_default()
.iter()
.filter(|child| {
object_of(child)
.and_then(|entries| string_at(&entries, "declKind"))
.as_deref()
== Some("unknown")
})
.count();
if unknown > 0 {
failures.push(format!(
"{name}: {unknown} external declaration(s) came back with declKind unknown"
));
continue;
}
let problems = common::tree_problems(&value);
if !problems.is_empty() {
failures.push(format!("{name}: {problems:?}"));
continue;
}
let fixture = fixtures_dir().join(format!("{name}.json.gz"));
let raw = match gunzip(&fixture) {
Ok(raw) => raw,
Err(error) => {
failures.push(format!("{name}: fixture unreadable: {error}"));
continue;
}
};
let want = String::from_utf8_lossy(&raw).to_string();
let got =
serde_json::to_string(&to_fixture(&value).expect("a translation unit serializes"))
.expect("the fixture shape serializes")
+ "\n";
if got == want {
passed += 1;
continue;
}
failures.push(format!("{name}: differs {}", first_text_diff(&got, &want)));
}
assert!(
failures.is_empty(),
"{passed} of {} Csmith fixtures match; these differ:\n{}",
seeds.len(),
failures
.iter()
.take(8)
.cloned()
.collect::<Vec<_>>()
.join("\n")
);
assert_eq!(passed, seeds.len(), "not every seed was graded");
}