Add C and C++ library support

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>
This commit is contained in:
Your NameandClaude Opus 5.5 committed 2026-11-08 12:55:41 +01:00
1 parent 5b42e2a3bd
commit 2f44f09b6a
26 files changed
+3418 -70

No files matched your search

+104 -17
View File
@@ -5,13 +5,40 @@ use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::{SystemTime, UNIX_EPOCH};
use crate::ast::{Item, Program};
use crate::error::{Diag, PResult};
use crate::{check, codegen_c, loader, parser};
use crate::{cheader, check, codegen_c, loader, parser};
/// Dino source -> C source, for a program in a single file.
/// Read the C headers imported by the program. `dir` is the folder of the main file.
pub fn load_c_headers(main: &Program, modules: &[(String, Program)], dir: &Path) -> PResult<Vec<cheader::Lib>> {
let mut libs: Vec<cheader::Lib> = Vec::new();
let all = std::iter::once(("", main)).chain(modules.iter().map(|(k, p)| (k.as_str(), p)));
for (key, p) in all {
// `import a.b` lives in a/b.dino: its headers are found next to it
let mut here = dir.to_path_buf();
let parts: Vec<&str> = key.split('.').collect();
for part in &parts[..parts.len().saturating_sub(1)] {
here.push(part);
}
for item in &p.items {
let Item::Import(i) = item else { continue };
if !i.c || libs.iter().any(|l| l.header == i.path) {
continue;
}
let lib = cheader::load(&i.path, &here, i.link.as_deref())
.map_err(|m| Diag::new(m, i.span).in_module(key))?;
libs.push(lib);
}
}
Ok(libs)
}
/// Dino source -> C source, for a program in a single file. C headers it imports are looked
/// for in the current folder and the system's.
pub fn compile_to_c(src: &str) -> PResult<String> {
let ast = parser::parse(src)?;
let hir = check::check(&ast)?;
let libs = load_c_headers(&ast, &[], Path::new("."))?;
let hir = check::check_project_c(&ast, &[], libs)?;
Ok(codegen_c::generate(&hir))
}
@@ -40,7 +67,9 @@ pub fn compile_project(
let loaded = loaded.map_err(&render)?;
let modules: Vec<(String, crate::ast::Program)> =
loaded.modules.into_iter().map(|m| (m.key, m.program)).collect();
let hir = check::check_project(&loaded.main, &modules).map_err(&render)?;
let dir = Path::new(main_path).parent().map(Path::to_path_buf).unwrap_or_default();
let libs = load_c_headers(&loaded.main, &modules, &dir).map_err(&render)?;
let hir = check::check_project_c(&loaded.main, &modules, libs).map_err(&render)?;
Ok(codegen_c::generate(&hir))
}
@@ -73,24 +102,80 @@ pub fn build_exe(c_code: &str, out: &Path) -> Result<(), String> {
}
/// Like `build_exe`, with explicit compiler flags (used by tests to turn on strict warnings).
/// The generated code says which C libraries it needs in `// dino-...:` lines at the top.
pub fn build_exe_with(c_code: &str, out: &Path, flags: &[&str]) -> Result<(), String> {
let (mut cflags, mut libs, mut sources) = (Vec::new(), Vec::new(), Vec::new());
for line in c_code.lines().take_while(|l| l.starts_with("// dino-")) {
let (kind, value) = line["// dino-".len()..].split_once(": ").unwrap_or(("", ""));
match kind {
"cflag" => cflags.push(value.to_string()),
"lib" => libs.push(value.to_string()),
"source" => sources.push(PathBuf::from(value)),
_ => {}
}
}
let uses_c = c_code.contains("\n#include \"");
// C headers often use GNU extensions
let flags: Vec<&str> = flags.iter().map(|f| if uses_c && *f == "-std=c11" { "-std=gnu11" } else { *f }).collect();
let cc = cheader::cc();
// C++ files are compiled on their own, then linked in with the C++ library
let mut objects: Vec<PathBuf> = Vec::new();
let mut c_sources: Vec<PathBuf> = Vec::new();
let cleanup = |objects: &[PathBuf]| {
for o in objects {
let _ = std::fs::remove_file(o);
}
};
for src in &sources {
let ext = src.extension().and_then(|e| e.to_str()).unwrap_or("");
if ext == "c" {
c_sources.push(src.clone());
continue;
}
let obj = unique_name("cpp", ".o");
let cxx = std::env::var("CXX").unwrap_or_else(|_| "c++".to_string());
let r = Command::new(&cxx).args(["-c", "-O2", "-w"]).args(&cflags).arg(src).arg("-o").arg(&obj).output();
match r {
Err(e) => {
cleanup(&objects);
return Err(format!("cannot run the C++ compiler `{cxx}` for {}: {e}", src.display()));
}
Ok(o) if !o.status.success() => {
cleanup(&objects);
return Err(format!("{} does not compile:\n{}", src.display(), String::from_utf8_lossy(&o.stderr)));
}
Ok(_) => objects.push(obj),
}
}
let c_file = unique_name("prog", ".c");
std::fs::write(&c_file, c_code).map_err(|e| format!("cannot write {}: {e}", c_file.display()))?;
let cc = std::env::var("CC").unwrap_or_else(|_| "cc".to_string());
let result = Command::new(&cc)
.args(flags)
.arg("-o")
.arg(out)
.arg(&c_file)
.arg("-lm") // the math functions
.output();
let mut cmd = Command::new(&cc);
cmd.args(&flags).args(&cflags).arg("-o").arg(out).arg(&c_file);
for s in &c_sources {
// the user's own C file: warnings are theirs to see, but not ours to fail on
cmd.arg(s);
}
cmd.args(&objects).args(&libs).arg("-lm"); // the math functions
if !objects.is_empty() {
cmd.arg("-lstdc++");
}
let result = cmd.output();
let _ = std::fs::remove_file(&c_file);
cleanup(&objects);
match result {
Err(e) => Err(format!("cannot run the C compiler `{cc}`: {e}\nInstall one (gcc or clang) or set $CC.")),
Ok(o) if !o.status.success() => Err(format!(
"the C compiler rejected the generated code (this is a bug in Dino):\n{}",
String::from_utf8_lossy(&o.stderr)
)),
Ok(o) if !o.status.success() => {
let err = String::from_utf8_lossy(&o.stderr);
if err.contains("undefined reference") || err.contains("cannot find -l") || err.contains("Undefined symbols") || err.contains("ld returned") {
Err(format!(
"linking with the C library failed:\n{err}\nIf a function is missing, name its library in the import: `import \"header.h\" link \"name\"` (for libname.so)."
))
} else if uses_c {
Err(format!("the C compiler rejected the program:\n{err}"))
} else {
Err(format!("the C compiler rejected the generated code (this is a bug in Dino):\n{err}"))
}
}
Ok(_) => Ok(()),
}
}
@@ -100,11 +185,13 @@ pub fn build_exe_with(c_code: &str, out: &Path, flags: &[&str]) -> Result<(), St
/// The error's `file` says which module it is in (`None`: the main file).
pub fn diagnose(
main_src: &str,
dir: &Path,
mut read: impl FnMut(&str) -> Option<(String, String)>,
) -> Result<(), Diag> {
let loaded = loader::load(main_src, &mut |key| read(key))?;
let modules: Vec<(String, crate::ast::Program)> =
loaded.modules.into_iter().map(|m| (m.key, m.program)).collect();
check::check_project(&loaded.main, &modules)?;
let libs = load_c_headers(&loaded.main, &modules, dir)?;
check::check_project_c(&loaded.main, &modules, libs)?;
Ok(())
}