import "zlib.h" reads the header (cc -E + a small C declaration parser), links via pkg-config or link "name", and builds .c/.cpp files next to the program. C structs become Dino structs, pointers become pointer types (nil = NULL), T* parameters take variables or lists. Adds dino header, editor completion/hover for C names, docs chapter 13, a raylib example, and tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
232 lines
8.8 KiB
Rust
232 lines
8.8 KiB
Rust
use std::path::PathBuf;
|
|
use std::{env, fs, process};
|
|
|
|
use dino::{driver, fmt, lexer, lsp, parser};
|
|
|
|
fn usage() -> ! {
|
|
eprintln!("Dino compiler (work in progress)\n");
|
|
eprintln!("usage:");
|
|
eprintln!(" dino run <file.dino> [args...] compile and run (args go to the program)");
|
|
eprintln!(" dino build <file.dino> [-o out] compile to an executable");
|
|
eprintln!(" dino emit-c <file.dino> print the generated C code");
|
|
eprintln!(" dino check <file.dino> check for errors without building");
|
|
eprintln!(" dino fmt [--check] <file|dir>.. format code in place (--check only reports; `-` = stdin to stdout)");
|
|
eprintln!(" dino lsp run the language server (for editors)");
|
|
eprintln!(" dino header <file.h> [name] show what Dino can use from a C header");
|
|
eprintln!(" dino parse <file.dino> print the syntax tree");
|
|
eprintln!(" dino tokens <file.dino> print the tokens");
|
|
process::exit(2);
|
|
}
|
|
|
|
fn die(msg: &str) -> ! {
|
|
eprintln!("{msg}");
|
|
process::exit(1);
|
|
}
|
|
|
|
/// All `.dino` files at `path` (a file, or a folder searched recursively).
|
|
fn dino_files(path: &std::path::Path, out: &mut Vec<PathBuf>) {
|
|
if path.is_dir() {
|
|
let mut entries: Vec<PathBuf> = fs::read_dir(path).map(|r| r.filter_map(|e| e.ok().map(|e| e.path())).collect()).unwrap_or_default();
|
|
entries.sort();
|
|
for e in entries {
|
|
dino_files(&e, out);
|
|
}
|
|
} else if path.extension().map_or(false, |e| e == "dino") || path.is_file() && out.is_empty() && path.extension().is_none() {
|
|
out.push(path.to_path_buf());
|
|
}
|
|
}
|
|
|
|
/// `dino header zlib.h [name] [--link z]`: what Dino code can use from a C header.
|
|
fn run_header(args: &[String]) -> ! {
|
|
let mut header: Option<&str> = None;
|
|
let mut filter: Option<&str> = None;
|
|
let mut link: Option<&str> = None;
|
|
let mut it = args.iter();
|
|
while let Some(a) = it.next() {
|
|
match a.as_str() {
|
|
"--link" => link = it.next().map(String::as_str),
|
|
_ if header.is_none() => header = Some(a),
|
|
_ => filter = Some(a),
|
|
}
|
|
}
|
|
let Some(header) = header else { usage() };
|
|
let dir = env::current_dir().unwrap_or_default();
|
|
let lib = dino::cheader::load(header, &dir, link).unwrap_or_else(|e| die(&format!("error: {e}")));
|
|
let shown = |n: &str| filter.map_or(true, |f| n.to_lowercase().contains(&f.to_lowercase()));
|
|
let mut text = format!("import \"{header}\" // use the names below as {}.name\n", lib.prefix);
|
|
if !lib.libs.is_empty() || !lib.cflags.is_empty() {
|
|
text.push_str(&format!("// builds with: {}\n", lib.cflags.iter().chain(&lib.libs).cloned().collect::<Vec<_>>().join(" ")));
|
|
}
|
|
let mut section = |title: &str, lines: Vec<String>| {
|
|
if !lines.is_empty() {
|
|
text.push_str(&format!("\n// {title}\n"));
|
|
for l in lines {
|
|
text.push_str(&l);
|
|
text.push('\n');
|
|
}
|
|
}
|
|
};
|
|
section("types", lib.structs.iter().filter(|s| shown(&s.name)).map(|s| lib.describe(&s.name).unwrap()).collect());
|
|
section(
|
|
"pointer types (pass them around, compare them with nil)",
|
|
lib.handles.iter().filter(|h| shown(h)).map(|h| format!("{}.{h}", lib.prefix)).collect(),
|
|
);
|
|
section(
|
|
"functions",
|
|
lib.funcs.iter().filter(|f| f.problem.is_none() && shown(&f.name)).map(|f| format!("func {}", lib.signature(f))).collect(),
|
|
);
|
|
section("constants", lib.consts.iter().filter(|c| shown(&c.name)).map(|c| lib.describe(&c.name).unwrap()).collect());
|
|
section(
|
|
"functions Dino can't call yet",
|
|
lib.funcs
|
|
.iter()
|
|
.filter(|f| shown(&f.name))
|
|
.filter_map(|f| f.problem.as_ref().map(|p| format!("{}: it {p}", f.name)))
|
|
.collect(),
|
|
);
|
|
// a closed pipe (`| head`) is not an error
|
|
let _ = std::io::Write::write_all(&mut std::io::stdout(), text.as_bytes());
|
|
process::exit(0);
|
|
}
|
|
|
|
/// `dino fmt [--check] files-or-folders...`
|
|
fn run_fmt(args: &[String]) -> ! {
|
|
// `dino fmt -`: text in on stdin, tidy text out on stdout (for editors)
|
|
if args.len() == 1 && args[0] == "-" {
|
|
let mut src = String::new();
|
|
if std::io::Read::read_to_string(&mut std::io::stdin(), &mut src).is_err() {
|
|
die("error: cannot read the input");
|
|
}
|
|
match fmt::format(&src) {
|
|
Ok(out) => {
|
|
print!("{out}");
|
|
process::exit(0);
|
|
}
|
|
Err(d) => die(&d.render("<stdin>", &src)),
|
|
}
|
|
}
|
|
let check = args.iter().any(|a| a == "--check");
|
|
let paths: Vec<&String> = args.iter().filter(|a| *a != "--check").collect();
|
|
if paths.is_empty() {
|
|
usage();
|
|
}
|
|
let mut files = Vec::new();
|
|
for p in paths {
|
|
let before = files.len();
|
|
let path = PathBuf::from(p);
|
|
if path.is_file() {
|
|
files.push(path);
|
|
} else {
|
|
dino_files(&path, &mut files);
|
|
if files.len() == before {
|
|
die(&format!("error: no .dino files found at {p}"));
|
|
}
|
|
}
|
|
}
|
|
let mut problems = 0;
|
|
let mut changed = 0;
|
|
for file in &files {
|
|
let shown = file.display().to_string();
|
|
let src = fs::read_to_string(file).unwrap_or_else(|e| die(&format!("error: cannot read {shown}: {e}")));
|
|
match fmt::format(&src) {
|
|
Err(d) => {
|
|
eprintln!("{}", d.render(&shown, &src));
|
|
problems += 1;
|
|
}
|
|
Ok(out) if out == src => {}
|
|
Ok(out) => {
|
|
changed += 1;
|
|
if check {
|
|
println!("{shown} needs formatting");
|
|
} else if let Err(e) = fs::write(file, out) {
|
|
die(&format!("error: cannot write {shown}: {e}"));
|
|
} else {
|
|
println!("formatted {shown}");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if problems > 0 || (check && changed > 0) {
|
|
process::exit(1);
|
|
}
|
|
process::exit(0);
|
|
}
|
|
|
|
fn main() {
|
|
let args: Vec<String> = env::args().skip(1).collect();
|
|
if args.first().map(String::as_str) == Some("lsp") {
|
|
let stdin = std::io::stdin();
|
|
process::exit(lsp::run(stdin.lock(), std::io::stdout()));
|
|
}
|
|
if args.first().map(String::as_str) == Some("fmt") {
|
|
run_fmt(&args[1..]);
|
|
}
|
|
if args.first().map(String::as_str) == Some("header") {
|
|
run_header(&args[1..]);
|
|
}
|
|
if args.len() < 2 {
|
|
usage();
|
|
}
|
|
let cmd = args[0].as_str();
|
|
let path = &args[1];
|
|
let mut out: Option<PathBuf> = None;
|
|
// `dino run file.dino a b c` hands `a b c` to the program; `build` takes `-o`
|
|
let mut program_args: Vec<String> = Vec::new();
|
|
let mut rest = args[2..].iter();
|
|
while let Some(a) = rest.next() {
|
|
match a.as_str() {
|
|
"-o" if cmd == "build" => out = Some(PathBuf::from(rest.next().unwrap_or_else(|| usage()))),
|
|
_ if cmd == "run" => program_args.push(a.clone()),
|
|
_ => usage(),
|
|
}
|
|
}
|
|
|
|
let src = fs::read_to_string(path).unwrap_or_else(|e| die(&format!("error: cannot read {path}: {e}")));
|
|
let fail = |d: dino::error::Diag| -> ! { die(&d.render(path, &src)) };
|
|
|
|
match cmd {
|
|
"tokens" => match lexer::lex(&src) {
|
|
Ok(toks) => {
|
|
for t in toks {
|
|
println!("{:>4}:{:<3} {:?}", t.span.line, t.span.col, t.tok);
|
|
}
|
|
}
|
|
Err(d) => fail(d),
|
|
},
|
|
"parse" => match parser::parse(&src) {
|
|
Ok(p) => println!("{:#?}", p),
|
|
Err(d) => fail(d),
|
|
},
|
|
"check" => match driver::compile_file(path) {
|
|
Ok(_) => println!("{path}: ok"),
|
|
Err(e) => die(&e),
|
|
},
|
|
"emit-c" => match driver::compile_file(path) {
|
|
Ok(c) => print!("{c}"),
|
|
Err(e) => die(&e),
|
|
},
|
|
"build" => {
|
|
let c = driver::compile_file(path).unwrap_or_else(|e| die(&e));
|
|
let default = PathBuf::from(path).with_extension("");
|
|
let out = out.unwrap_or(default);
|
|
if let Err(e) = driver::build_exe(&c, &out) {
|
|
die(&format!("error: {e}"));
|
|
}
|
|
}
|
|
"run" => {
|
|
let c = driver::compile_file(path).unwrap_or_else(|e| die(&e));
|
|
let exe = driver::temp_exe();
|
|
if let Err(e) = driver::build_exe(&c, &exe) {
|
|
die(&format!("error: {e}"));
|
|
}
|
|
let status = process::Command::new(&exe).args(&program_args).status();
|
|
let _ = fs::remove_file(&exe);
|
|
match status {
|
|
Ok(s) => process::exit(s.code().unwrap_or(1)),
|
|
Err(e) => die(&format!("error: cannot run the program: {e}")),
|
|
}
|
|
}
|
|
_ => usage(),
|
|
}
|
|
}
|