const HEADER: &str = "#![allow(unused)]\n";
pub struct Program {
pub source: String,
pub offset: usize,
}
pub fn visible(code: &str) -> String {
let shown: Vec<&str> = code
.lines()
.map(|line| match line.trim_start() {
"#" => "",
hidden if hidden.starts_with("# ") => &hidden[2..],
escaped if escaped.starts_with("##") => &escaped[1..],
_ => line,
})
.collect();
shown.join("\n")
}
fn has_main(file: &syn::File) -> bool {
file.items.iter().any(|item| matches!(item, syn::Item::Fn(f) if f.sig.ident == "main"))
}
pub fn program(code: &str) -> Program {
let code = visible(code);
if syn::parse_file(&code).is_ok_and(|file| has_main(&file)) {
return Program { source: format!("{HEADER}{code}\n"), offset: 1 };
}
Program { source: format!("{HEADER}fn main() {{\n{code}\n}}\n"), offset: 2 }
}
pub fn parsed(code: &str) -> Option<syn::File> {
syn::parse_file(&program(code).source).ok()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_snippet_is_the_body_of_main() {
let read = program("use std::fmt;\nassert!(true);");
assert_eq!(read.source, "#![allow(unused)]\nfn main() {\nuse std::fmt;\nassert!(true);\n}\n");
assert_eq!(read.offset, 2);
}
#[test]
fn a_block_with_a_main_is_a_whole_program() {
let read = program("fn helper() {}\nfn main() {\n helper();\n}");
assert_eq!(read.source, "#![allow(unused)]\nfn helper() {}\nfn main() {\n helper();\n}\n");
assert_eq!(read.offset, 1);
}
#[test]
fn hidden_lines_are_part_of_the_program_and_keep_their_place() {
assert_eq!(
visible("# use a::b;\n#\nlet x = 1;\n## not hidden\n#[derive(Debug)]"),
"use a::b;\n\nlet x = 1;\n# not hidden\n#[derive(Debug)]"
);
assert!(parsed("# use std::fmt;\nlet x = 1;").is_some());
assert!(parsed("let x = = 1;").is_none());
}
}