pub mod ast;
pub mod borrow;
pub mod callers;
pub mod exec;
pub mod lex;
pub mod lower;
pub mod parse;
pub mod target;
use std::path::{Path, PathBuf};
#[derive(Default, Clone, Debug)]
pub struct Options {
pub include_dirs: Vec<PathBuf>,
pub defines: Vec<(String, String)>,
pub undefines: Vec<String>,
pub forced_includes: Vec<PathBuf>,
pub short_enums: Option<bool>,
pub target: target::Target,
}
impl Options {
pub fn for_image(image: &crate::image::Image) -> Options {
Options {
short_enums: image.short_enums,
target: target::Target::for_image(image),
..Default::default()
}
}
}
pub fn parse_files(paths: &[PathBuf], opts: &Options) -> Result<ast::Program, String> {
parse_units(paths, opts).map_err(|(_, e)| e)
}
pub fn parse_files_lenient(
paths: &[PathBuf],
opts: &Options,
) -> Result<(ast::Program, Vec<(PathBuf, String)>), String> {
let mut paths = paths.to_vec();
let mut skipped = Vec::new();
loop {
match parse_units(&paths, opts) {
Ok(prog) => return Ok((prog, skipped)),
Err((Some(i), e)) => skipped.push((paths.remove(i), e)),
Err((None, e)) => return Err(e),
}
}
}
fn parse_units(paths: &[PathBuf], opts: &Options) -> Result<ast::Program, (Option<usize>, String)> {
let mut prog = ast::Program::new();
prog.int_enums = opts.short_enums == Some(false);
let mut externs = parse::Externs::default();
let target = opts.target.predefines();
let defs: Vec<(String, Option<String>)> = opts
.defines
.iter()
.map(|(k, v)| (k.clone(), Some(v.clone())))
.chain(opts.undefines.iter().map(|k| (k.clone(), None)))
.collect();
type Pre = Result<(Vec<lex::Token>, Vec<PathBuf>), (Option<usize>, String)>;
let preprocess = |index: usize| -> Pre {
let mut pp =
lex::Preprocessor::new(opts.include_dirs.clone(), &target, &defs).map_err(|e| (None, fmt_err(&[], &e)))?;
let toks = pp
.preprocess_file(&paths[index], &opts.forced_includes)
.map_err(|e| (Some(index), fmt_err(&pp.files, &e)))?;
Ok((toks, pp.files.clone()))
};
let workers = std::thread::available_parallelism()
.map_or(1, |n| n.get())
.min(8)
.min(paths.len().max(1));
let next = std::sync::atomic::AtomicUsize::new(0);
let done: Vec<std::sync::Mutex<Option<Pre>>> = paths.iter().map(|_| std::sync::Mutex::new(None)).collect();
std::thread::scope(|scope| {
for _ in 0..workers {
scope.spawn(|| {
loop {
let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
if i >= paths.len() {
break;
}
*done[i].lock().unwrap() = Some(preprocess(i));
}
});
}
});
let mut file_ids: std::collections::HashMap<String, u16> = std::collections::HashMap::new();
for (index, path) in paths.iter().enumerate() {
let at = Some(index);
let (toks, files) = done[index]
.lock()
.unwrap()
.take()
.expect("every unit was preprocessed")?;
let mut ids: Vec<u16> = Vec::with_capacity(files.len());
for f in &files {
let name = f.display().to_string();
let id = match file_ids.get(&name) {
Some(id) => *id,
None => {
let id = u16::try_from(prog.files.len())
.ok()
.filter(|id| *id < u16::MAX)
.ok_or_else(|| (None, "more than 65534 source files (headers included)".to_string()))?;
prog.files.push(name.clone());
file_ids.insert(name, id);
id
}
};
ids.push(id);
}
let toks = toks
.into_iter()
.map(|mut t| {
t.loc.file = ids[t.loc.file as usize];
t
})
.collect();
parse::parse_unit(&mut prog, &mut externs, toks).map_err(|mut e| {
e.loc.file = ids.iter().position(|i| *i == e.loc.file).unwrap_or(0) as u16;
(at, fmt_err(&files, &e))
})?;
let unit = prog.units.len() as u16;
prog.units.push(path.display().to_string());
prog.func_unit.resize(prog.funcs.len(), unit);
prog.global_unit.resize(prog.globals.len(), unit);
}
Ok(prog)
}
fn fmt_err(files: &[PathBuf], e: &lex::CError) -> String {
let f = files
.get(e.loc.file as usize)
.map(|p| p.display().to_string())
.unwrap_or_else(|| "<input>".into());
format!("{f}:{}: {}", e.loc.line, e.msg)
}
pub fn collect_sources(root: &Path) -> std::io::Result<Vec<PathBuf>> {
let mut out = Vec::new();
if root.is_file() {
out.push(root.to_path_buf());
return Ok(out);
}
let mut stack = vec![root.to_path_buf()];
while let Some(dir) = stack.pop() {
for ent in std::fs::read_dir(&dir)? {
let p = ent?.path();
if p.is_dir() {
stack.push(p);
} else if p.extension().is_some_and(|e| e == "c") {
out.push(p);
}
}
}
out.sort();
Ok(out)
}