pub mod ast;
pub mod lex;
pub mod lower;
pub mod parse;
use std::path::{Path, PathBuf};
#[derive(Default, Clone, Debug)]
pub struct Options {
pub include_dirs: Vec<PathBuf>,
pub defines: Vec<(String, String)>,
}
pub fn parse_files(paths: &[PathBuf], opts: &Options) -> Result<ast::Program, String> {
let mut prog = ast::Program::new();
let mut externs = parse::Externs::default();
for path in paths {
let mut pp = lex::Preprocessor::new(opts.include_dirs.clone(), &opts.defines).map_err(|e| fmt_err(&[], &e))?;
let base = prog.files.len() as u16;
let toks = pp.preprocess_file(path).map_err(|e| fmt_err(&pp.files, &e))?;
let files: Vec<PathBuf> = pp.files.clone();
let toks = toks
.into_iter()
.map(|mut t| {
t.loc.file += base;
t
})
.collect();
prog.files.extend(files.iter().map(|f| f.display().to_string()));
parse::parse_unit(&mut prog, &mut externs, toks).map_err(|mut e| {
e.loc.file -= base;
fmt_err(&files, &e)
})?;
}
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)
}