Something went wrong. Try again.
A polyglot incremental mutation tester
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538use std::fs;use std::path::{Path, PathBuf};
use arborium::Highlighter;use comrak::{Options, markdown_to_html};use serde::Deserialize;
const DOCS_DIR: &str = "docs";const OUT_DIR: &str = "target/bough-docs-site";
#[derive(Deserialize, Default)]struct Frontmatter { #[serde(default)] title: Option<String>, #[serde(default)] idx: Option<i64>,}
#[derive(Debug)]struct TocEntry { title: String, href: String, children: Vec<TocEntry>,}
struct Page { title: String, slug: String, body_html: String,}
fn parse_md(content: &str) -> (Frontmatter, String) { match markdown_frontmatter::parse::<Frontmatter>(content) { Ok((fm, body)) => (fm, body.to_owned()), Err(_) => (Frontmatter::default(), content.to_owned()), }}
fn build_toc(dir: &Path, docs_dir: &Path) -> Vec<TocEntry> { let Ok(entries) = fs::read_dir(dir) else { return Vec::new(); };
let mut items: Vec<(i64, TocEntry)> = Vec::new();
let mut dir_entries: Vec<_> = entries.flatten().collect(); dir_entries.sort_by_key(|e| e.file_name());
for entry in dir_entries { let path = entry.path();
if path.is_dir() { let index_path = path.join("index.md"); let (fm, _) = if index_path.exists() { let content = fs::read_to_string(&index_path).expect("failed to read index.md"); parse_md(&content) } else { (Frontmatter::default(), String::new()) };
let title = fm.title.unwrap_or_else(|| { path.file_name() .unwrap_or_default() .to_string_lossy() .into_owned() }); let idx = fm.idx.unwrap_or(i64::MAX);
let rel = path.strip_prefix(docs_dir).unwrap(); let href = format!("/{}/", rel.to_string_lossy()); let children = build_toc(&path, docs_dir);
items.push(( idx, TocEntry { title, href, children, }, )); } else if path.extension().is_some_and(|e| e == "md") { let stem = path.file_stem().unwrap_or_default(); if stem == "index" { continue; }
let content = fs::read_to_string(&path).expect("failed to read md file"); let (fm, _) = parse_md(&content);
let title = fm .title .unwrap_or_else(|| stem.to_string_lossy().into_owned()); let idx = fm.idx.unwrap_or(i64::MAX);
let rel = path.strip_prefix(docs_dir).unwrap().with_extension(""); let href = format!("/{}/", rel.to_string_lossy());
items.push(( idx, TocEntry { title, href, children: Vec::new(), }, )); } }
items.sort_by_key(|(idx, _)| *idx); items.into_iter().map(|(_, entry)| entry).collect()}
fn highlight_code_blocks(html: &str, hl: &mut Highlighter) -> String { let mut out = String::with_capacity(html.len()); let mut rest = html;
while let Some(pre_start) = rest.find("<pre><code class=\"language-") { out.push_str(&rest[..pre_start]); rest = &rest[pre_start..];
let Some(lang_start) = rest.find("language-") else { out.push_str(rest); return out; }; let after_prefix = &rest[lang_start + 9..]; let Some(lang_end) = after_prefix.find('"') else { out.push_str(rest); return out; }; let lang = &after_prefix[..lang_end];
let Some(code_start) = rest .find('>') .and_then(|i| rest[i + 1..].find('>').map(|j| i + 1 + j + 1)) else { out.push_str(rest); return out; }; let code_body = &rest[code_start..]; let Some(code_end) = code_body.find("</code></pre>") else { out.push_str(rest); return out; };
let raw_code = &code_body[..code_end]; let decoded = raw_code .replace("&", "&") .replace("<", "<") .replace(">", ">") .replace(""", "\"") .replace("'", "'");
match hl.highlight(lang, &decoded) { Ok(highlighted) => { out.push_str("<pre><code>"); out.push_str(&highlighted); out.push_str("</code></pre>"); } Err(_) => { out.push_str(&rest[..code_start + code_end + 13]); } }
rest = &code_body[code_end + 13..]; }
out.push_str(rest); out}
fn render_toc_entries(entries: &[TocEntry], current_slug: &str) -> String { if entries.is_empty() { return String::new(); }
let mut out = String::from("<ol>"); for entry in entries { let entry_slug = entry.href.trim_matches('/'); let id = entry_slug.replace('/', "-"); let is_match = entry_slug == current_slug || (!entry_slug.is_empty() && current_slug.starts_with(entry_slug) && current_slug[entry_slug.len()..].starts_with('/')); let class = if is_match { " class=\"active\"" } else { "" }; out.push_str(&format!( "<li id=\"toc-{id}\"{class}><a href=\"{}\">{}</a>", entry.href, entry.title )); if !entry.children.is_empty() { out.push_str(&render_toc_entries(&entry.children, current_slug)); } out.push_str("</li>"); } out.push_str("</ol>"); out}
fn render_page(page: &Page, toc_html: &str) -> String { format!( r#"<!DOCTYPE html><html lang="en"> <head> <link href="https://codeenplace.dev/fonts.css" rel="stylesheet" /> <link href="https://codeenplace.dev/base.css" rel="stylesheet" /> <link href="/layout.css" rel="stylesheet" /> <link href="https://codeenplace.dev/light.color.css" rel="stylesheet" media="(prefers-color-scheme:light)" /> <link href="https://codeenplace.dev/dark.color.css" rel="stylesheet" media="(prefers-color-scheme:dark)" /> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>{title}</title> <style> pre code {{ display: block; padding: 1rem; overflow-x: auto; border-radius: 4px; background: var(--col-bright-bg); color: var(--col-fg); }} a-k, a-kc, a-kd, a-ke, a-kf, a-ki, a-km, a-ko, a-kp, a-kr, a-kt, a-ky {{ color: var(--col-red); }} a-f, a-fb, a-fc, a-fd, a-fm {{ color: var(--col-blue); }} a-s, a-sc, a-se, a-sp, a-ss, a-st {{ color: var(--col-green); }} a-co, a-cn {{ color: var(--col-yellow); }} a-c, a-cb, a-cd, a-ch, a-cs {{ color: var(--col-bright-white); font-style: italic; }} a-o {{ color: var(--col-orange); }} a-t, a-tb, a-td, a-te, a-tf, a-tg, a-tl, a-tq, a-tr, a-tt, a-tu, a-tx {{ color: var(--col-cyan); }} a-at {{ color: var(--col-purple); }} a-v, a-vb, a-vm, a-vp {{ color: var(--col-fg); }} a-n {{ color: var(--col-yellow); }} a-l, a-m {{ color: var(--col-yellow); }} a-p, a-pb, a-pd, a-pp, a-pr, a-ps {{ color: var(--col-bright-fg); }} a-in, a-ex {{ color: var(--col-bright-red); }} a-em {{ font-weight: bold; }} a-dr, a-rp, a-rx {{ color: var(--col-orange); }} #toc .active > a {{ color: var(--col-purple); }} </style> </head>
<body> <nav id="toc"><ol><li><a href="/">Bough</a><ol><li><a href="https://github.com/CodeEnPlace/bough">GitHub</a></li></ol></li></ol>{toc}</nav> <main> <h1>{title}</h1> {body} </main> <script> (function() {{ var prefetched = {{}}; function prefetch(url) {{ if (prefetched[url] || url === location.pathname) return; prefetched[url] = true; var l = document.createElement("link"); l.rel = "prefetch"; l.href = url; document.head.appendChild(l); }} document.addEventListener("pointerenter", function(e) {{ var a = e.target.closest("a[href^='/']"); if (a) prefetch(a.getAttribute("href")); }}, true); document.addEventListener("focusin", function(e) {{ var a = e.target.closest("a[href^='/']"); if (a) prefetch(a.getAttribute("href")); }}); }})(); </script> </body></html>"#, title = page.title, body = page.body_html, toc = toc_html, )}
fn collect_md_files(dir: &Path) -> Vec<PathBuf> { let mut files = Vec::new(); let Ok(entries) = fs::read_dir(dir) else { return files; }; for entry in entries.flatten() { let path = entry.path(); if path.is_dir() { files.extend(collect_md_files(&path)); } else if path.extension().is_some_and(|e| e == "md") { files.push(path); } } files.sort(); files}
const EXAMPLES_DIR: &str = "docs/mutations";
#[derive(Deserialize)]struct ExamplesFile { mutation: Vec<MutationExample>,}
#[derive(Deserialize)]struct MutationExample { kind: String, snippet: String,}
fn make_mutation_reference(lang: &bough_core::LanguageId) -> String { use std::collections::BTreeMap; use std::fmt::Write;
let ext = lang.file_extension(); let examples_path = Path::new(EXAMPLES_DIR).join(format!("{}.examples.toml", lang.slug())); let toml_content = fs::read_to_string(&examples_path).unwrap_or_else(|e| { panic!( "failed to read examples file {}: {e}", examples_path.display() ) }); let examples_file: ExamplesFile = toml::from_str(&toml_content).unwrap_or_else(|e| { panic!( "failed to parse examples file {}: {e}", examples_path.display() ) });
// Build kind key → snippet map, checking for duplicates let mut snippets: BTreeMap<String, String> = BTreeMap::new(); for example in &examples_file.mutation { if snippets.contains_key(&example.kind) { panic!( "{}: duplicate example for kind '{}'", examples_path.display(), example.kind ); } // Validate the kind key is recognised if bough_core::MutantKind::from_key(&example.kind).is_none() { panic!( "{}: unknown mutation kind '{}'", examples_path.display(), example.kind ); } snippets.insert(example.kind.clone(), example.snippet.clone()); }
// Check for extraneous keys (kinds the language doesn't support) for key in snippets.keys() { let kind = bough_core::MutantKind::from_key(key).unwrap(); let subs = lang.substitutions(&kind); if subs.is_empty() { panic!( "{}: example for kind '{}' but language {} doesn't support it (empty substitutions)", examples_path.display(), key, lang.display_name() ); } }
let mut out = format!("+++\ntitle = \"{}\"\n+++\n\n", lang.display_name());
for kind in bough_core::MutantKind::all_variants() { let subs = lang.substitutions(&kind); if subs.is_empty() { continue; }
let key = kind.to_key(); let snippet = snippets.get(&key).unwrap_or_else(|| { panic!( "{}: missing example for supported kind '{}'", examples_path.display(), key ) });
// Parse the snippet in-memory to find mutants of this kind let source_mutants = bough_core::find_mutants_in_source(*lang, snippet.as_bytes()); let matching: Vec<_> = source_mutants.iter().filter(|m| m.kind == kind).collect();
if matching.is_empty() { panic!( "{}: snippet for kind '{}' doesn't contain any mutants of that kind when parsed", examples_path.display(), key ); }
let _ = writeln!(out, "## {}\n", kind.heading()); let _ = writeln!(out, "### Before\n\n```{ext}\n{}\n```\n", snippet.trim_end()); let _ = writeln!(out, "### After\n");
for mutant in &matching { let span_start = mutant.subst_span.start().byte(); let span_end = mutant.subst_span.end().byte(); for sub in &subs { let mutated = format!("{}{}{}", &snippet[..span_start], sub, &snippet[span_end..],); let _ = writeln!(out, "```{ext}\n{}\n```\n", mutated.trim_end()); } } }
out}
pub fn build() { let docs_dir = Path::new(DOCS_DIR); let out_dir = Path::new(OUT_DIR);
if out_dir.exists() { fs::remove_dir_all(out_dir).expect("failed to clean output dir"); } fs::create_dir_all(out_dir).expect("failed to create output dir");
fs::write(out_dir.join("layout.css"), include_str!("layout.css")) .expect("failed to write layout.css");
let generated_dir = Path::new("target/bough-docs-generated"); if generated_dir.exists() { fs::remove_dir_all(generated_dir).expect("failed to clean generated dir"); } let reference_dir = generated_dir.join("config"); fs::create_dir_all(&reference_dir).expect("failed to create generated config dir"); let reference_md = format!( "+++\ntitle = \"Configuration Reference\"\n+++\n\n{}", crate::facet_reference::make_facet_reference::<bough_cli::config::Config>() ); fs::write(reference_dir.join("reference.md"), reference_md) .expect("failed to write config reference");
let mutations_dir = generated_dir.join("mutations"); fs::create_dir_all(&mutations_dir).expect("failed to create generated mutations dir"); for lang in bough_core::LanguageId::ALL { let md = make_mutation_reference(lang); fs::write(mutations_dir.join(format!("{}.md", lang.slug())), md) .expect("failed to write mutation reference"); }
let mut md_files = collect_md_files(docs_dir); md_files.extend(collect_md_files(generated_dir)); if md_files.is_empty() { eprintln!("no markdown files found in {}", docs_dir.display()); return; }
let mut toc = build_toc(docs_dir, docs_dir); for gen_entry in build_toc(generated_dir, generated_dir) { if let Some(existing) = toc.iter_mut().find(|e| e.href == gen_entry.href) { existing.children.extend(gen_entry.children); } else { toc.push(gen_entry); } } let mut hl = Highlighter::new();
let mut opts = Options::default(); opts.extension.table = true; opts.extension.strikethrough = true; opts.extension.autolink = true; opts.render.unsafe_ = true;
let pages: Vec<Page> = md_files .iter() .map(|path| { let content = fs::read_to_string(path).expect("failed to read md file"); let (fm, body) = parse_md(&content);
let title = fm.title.unwrap_or_else(|| { path.file_stem() .unwrap_or_default() .to_string_lossy() .into_owned() });
let rel = path .strip_prefix(docs_dir) .or_else(|_| path.strip_prefix(generated_dir)) .unwrap(); let slug = if rel.file_stem().is_some_and(|s| s == "index") { rel.parent() .map(|p| p.to_string_lossy().into_owned()) .unwrap_or_default() } else { rel.with_extension("").to_string_lossy().into_owned() };
let body_html = markdown_to_html(&body, &opts); let body_html = highlight_code_blocks(&body_html, &mut hl);
Page { title, slug, body_html, } }) .collect();
for page in &pages { let toc_html = render_toc_entries(&toc, &page.slug);
let out_path = if page.slug.is_empty() { out_dir.join("index.html") } else { let dir = out_dir.join(&page.slug); fs::create_dir_all(&dir).expect("failed to create page dir"); dir.join("index.html") };
let html = render_page(page, &toc_html); fs::write(&out_path, html).expect("failed to write html"); eprintln!(" wrote {}", out_path.display()); }
eprintln!("built {} pages into {}", pages.len(), out_dir.display());}
#[cfg(test)]mod tests { use super::*;
/// Validates that every language has a complete, well-formed examples TOML file. /// /// This test calls `make_mutation_reference` for each language, which: /// - Loads and parses the TOML file /// - Checks for duplicate keys /// - Checks for unknown or unsupported mutation kinds /// - Verifies every supported kind has an example /// - Parses each snippet and verifies it contains mutants of the expected kind #[test] fn all_example_files_are_valid() { // Tests run from crate dir; examples are relative to workspace root let workspace_root = Path::new(env!("CARGO_MANIFEST_DIR")).join("..").join(".."); std::env::set_current_dir(&workspace_root).expect("failed to cd to workspace root");
for lang in bough_core::LanguageId::ALL { let md = make_mutation_reference(lang); // Sanity: output should contain at least one heading assert!( md.contains("## "), "{}: generated markdown has no headings", lang.display_name() ); } }}