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:
1 parent
5b42e2a3bd
commit
2f44f09b6a
26 files changed
+3418
-70
No files matched your search
+300
@@ -0,0 +1,300 @@
|
||||
//! Using C (and C++) libraries: `import "header.h"`.
|
||||
//! Programs run under the address sanitizer, like the other tests.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
|
||||
use dino::driver;
|
||||
|
||||
/// A fresh folder with the given files in it.
|
||||
fn folder(files: &[(&str, &str)]) -> PathBuf {
|
||||
static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
|
||||
let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let dir = std::env::temp_dir().join(format!("dino-clib-{}-{n}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
for (name, text) in files {
|
||||
std::fs::write(dir.join(name), text).unwrap();
|
||||
}
|
||||
dir
|
||||
}
|
||||
|
||||
/// Compile `main.dino` in a folder with these files and run it; returns what it printed.
|
||||
fn run(files: &[(&str, &str)]) -> String {
|
||||
let dir = folder(files);
|
||||
let c = driver::compile_file(dir.join("main.dino").to_str().unwrap()).unwrap_or_else(|e| panic!("{e}"));
|
||||
let exe = dir.join("prog");
|
||||
let sanitized = driver::build_exe_with(&c, &exe, &["-std=c11", "-fwrapv", "-w", "-fsanitize=address", "-g"]);
|
||||
if let Err(e) = sanitized {
|
||||
assert!(e.contains("asan"), "{e}");
|
||||
driver::build_exe(&c, &exe).unwrap();
|
||||
}
|
||||
let o = Command::new(&exe).env("ASAN_OPTIONS", "detect_leaks=1").output().unwrap();
|
||||
let stderr = String::from_utf8_lossy(&o.stderr).to_string();
|
||||
assert!(!stderr.contains("Sanitizer"), "memory error:\n{stderr}");
|
||||
assert!(o.status.success(), "exit {:?}\n{stderr}", o.status.code());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
String::from_utf8_lossy(&o.stdout).to_string()
|
||||
}
|
||||
|
||||
/// The error message for a program that should not compile.
|
||||
fn error(files: &[(&str, &str)]) -> String {
|
||||
let dir = folder(files);
|
||||
let r = driver::compile_file(dir.join("main.dino").to_str().unwrap());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
match r {
|
||||
Ok(_) => panic!("expected an error"),
|
||||
Err(e) => e,
|
||||
}
|
||||
}
|
||||
|
||||
fn have_pkg(name: &str) -> bool {
|
||||
Command::new("pkg-config").args(["--exists", name]).status().map_or(false, |s| s.success())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_c_library() {
|
||||
let out = run(&[(
|
||||
"main.dino",
|
||||
"import \"math.h\" { cbrt, hypot }\nimport \"string.h\"\nimport \"stdlib.h\"\n\n\
|
||||
func main() {\n print(cbrt(27.0), hypot(3.0, 4.0))\n print(string.strlen(\"héllo\"), stdlib.abs(-4))\n print(stdlib.atoi(\"42abc\") + 1)\n}\n",
|
||||
)]);
|
||||
assert_eq!(out, "3.0 5.0\n6 4\n43\n");
|
||||
}
|
||||
|
||||
const SHAPES_H: &str = r#"
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
typedef struct { double w, h; } Size;
|
||||
typedef struct { Size size; int id; } Box;
|
||||
typedef struct Counter Counter;
|
||||
enum Mode { MODE_A, MODE_B = 10, MODE_C };
|
||||
#define SHAPES_VERSION "1.2"
|
||||
#define MAX_SIDES (4 * 3)
|
||||
#define BIG ((unsigned)1 << 20)
|
||||
#define UNIT_BOX (Box){ { 1.0, 1.0 }, 7 }
|
||||
double area(Size s);
|
||||
void grow(Size *s, double by);
|
||||
Box make_box(int id);
|
||||
int sum(const int *values, int n);
|
||||
void fill(char *buf, int n);
|
||||
int count_chars(const char *text, char c);
|
||||
Counter *counter_new(const char *name);
|
||||
void counter_add(Counter *c, int n);
|
||||
int counter_total(const Counter *c);
|
||||
const char *counter_name(const Counter *c);
|
||||
void counter_free(Counter *c);
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
"#;
|
||||
|
||||
const SHAPES_C: &str = r#"
|
||||
#include "shapes.h"
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
struct Counter { char name[32]; int total; };
|
||||
double area(Size s) { return s.w * s.h; }
|
||||
void grow(Size *s, double by) { s->w *= by; s->h *= by; }
|
||||
Box make_box(int id) { Box b = { { 2.0, 3.0 }, id }; return b; }
|
||||
int sum(const int *values, int n) { int t = 0; for (int i = 0; i < n; i++) t += values[i]; return t; }
|
||||
void fill(char *buf, int n) { for (int i = 0; i < n; i++) buf[i] = 'a' + i; }
|
||||
int count_chars(const char *text, char c) { int k = 0; for (; *text; text++) k += *text == c; return k; }
|
||||
Counter *counter_new(const char *name) { Counter *c = calloc(1, sizeof *c); strncpy(c->name, name, 31); return c; }
|
||||
void counter_add(Counter *c, int n) { c->total += n; }
|
||||
int counter_total(const Counter *c) { return c->total; }
|
||||
const char *counter_name(const Counter *c) { return c->name; }
|
||||
void counter_free(Counter *c) { free(c); }
|
||||
"#;
|
||||
|
||||
const SHAPES_MAIN: &str = r#"import "shapes.h"
|
||||
|
||||
struct Holder {
|
||||
size: shapes.Size
|
||||
func double_it() {
|
||||
shapes.grow(size, 2.0)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
var s = shapes.Size{2.0, 3.0}
|
||||
print(shapes.area(s), shapes.SHAPES_VERSION, shapes.MAX_SIDES, shapes.BIG)
|
||||
shapes.grow(s, 10.0)
|
||||
print(s)
|
||||
var h = Holder{s}
|
||||
h.double_it()
|
||||
print(h.size.w)
|
||||
print(shapes.make_box(5), shapes.UNIT_BOX.id)
|
||||
print(shapes.MODE_A, shapes.MODE_B, shapes.MODE_C)
|
||||
var nums: []i32 = [1, 2, 3, 4]
|
||||
print(shapes.sum(nums, i32(nums.len())))
|
||||
var buf: []u8 = [0, 0, 0]
|
||||
shapes.fill(buf, 3)
|
||||
print(buf)
|
||||
print(shapes.count_chars("banana", 'a'))
|
||||
var c = shapes.counter_new("apples")
|
||||
for i in 1..5 {
|
||||
shapes.counter_add(c, i32(i))
|
||||
}
|
||||
print(shapes.counter_name(c), shapes.counter_total(c), c != nil)
|
||||
shapes.counter_free(c)
|
||||
var none: shapes.Counter
|
||||
print(none == nil)
|
||||
}
|
||||
"#;
|
||||
|
||||
const SHAPES_OUT: &str = "6.0 1.2 12 1048576\nshapes.Size{w: 20.0, h: 30.0}\n40.0\n\
|
||||
shapes.Box{size: shapes.Size{w: 2.0, h: 3.0}, id: 5} 7\n0 10 11\n10\n[97, 98, 99]\n3\napples 10 true\ntrue\n";
|
||||
|
||||
#[test]
|
||||
fn your_own_c_file() {
|
||||
let out = run(&[("shapes.h", SHAPES_H), ("shapes.c", SHAPES_C), ("main.dino", SHAPES_MAIN)]);
|
||||
assert_eq!(out, SHAPES_OUT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn your_own_cpp_file() {
|
||||
if Command::new("c++").arg("--version").output().is_err() {
|
||||
return;
|
||||
}
|
||||
let cpp = r#"
|
||||
#include "shapes.h"
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <numeric>
|
||||
struct Counter { std::string name; std::vector<int> items; };
|
||||
extern "C" {
|
||||
double area(Size s) { return s.w * s.h; }
|
||||
void grow(Size *s, double by) { s->w *= by; s->h *= by; }
|
||||
Box make_box(int id) { return Box{ { 2.0, 3.0 }, id }; }
|
||||
int sum(const int *values, int n) { return std::accumulate(values, values + n, 0); }
|
||||
void fill(char *buf, int n) { for (int i = 0; i < n; i++) buf[i] = 'a' + i; }
|
||||
int count_chars(const char *text, char c) { std::string s(text); int k = 0; for (char x : s) k += x == c; return k; }
|
||||
Counter *counter_new(const char *name) { return new Counter{name, {}}; }
|
||||
void counter_add(Counter *c, int n) { c->items.push_back(n); }
|
||||
int counter_total(const Counter *c) { return std::accumulate(c->items.begin(), c->items.end(), 0); }
|
||||
const char *counter_name(const Counter *c) { return c->name.c_str(); }
|
||||
void counter_free(Counter *c) { delete c; }
|
||||
}
|
||||
"#;
|
||||
let out = run(&[("shapes.h", SHAPES_H), ("shapes.cpp", cpp), ("main.dino", SHAPES_MAIN)]);
|
||||
assert_eq!(out, SHAPES_OUT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picked_names_are_used_bare() {
|
||||
let out = run(&[
|
||||
("shapes.h", SHAPES_H),
|
||||
("shapes.c", SHAPES_C),
|
||||
(
|
||||
"main.dino",
|
||||
"import \"shapes.h\" { Size, area, MAX_SIDES }\n\nfunc main() {\n var s: Size = Size{1.5, 2.0}\n print(area(s), MAX_SIDES)\n}\n",
|
||||
),
|
||||
]);
|
||||
assert_eq!(out, "3.0 12\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zlib_through_pkg_config() {
|
||||
if !have_pkg("zlib") {
|
||||
return;
|
||||
}
|
||||
let out = run(&[(
|
||||
"main.dino",
|
||||
r#"import "zlib.h"
|
||||
|
||||
func main() {
|
||||
var text = "hello hello hello hello hello hello hello"
|
||||
var data: []u8
|
||||
for c in text {
|
||||
data.push(u8(int(c)))
|
||||
}
|
||||
var size = zlib.compressBound(u64(data.len()))
|
||||
var packed: []u8
|
||||
for i in 0..int(size) {
|
||||
packed.push(0)
|
||||
}
|
||||
print(zlib.compress(packed, size, data, u64(data.len())) == zlib.Z_OK, size < u64(data.len()))
|
||||
var back: []u8
|
||||
for i in 0..data.len() {
|
||||
back.push(0)
|
||||
}
|
||||
var n = u64(back.len())
|
||||
print(zlib.uncompress(back, n, packed, size) == zlib.Z_OK, string(back) == string(data), n)
|
||||
print(zlib.gzopen("/no/such/dir/x.gz", "rb") == nil)
|
||||
}
|
||||
"#,
|
||||
)]);
|
||||
assert_eq!(out, "true true\ntrue true 41\ntrue\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sqlite_fills_in_pointer_variables() {
|
||||
if !have_pkg("sqlite3") {
|
||||
return;
|
||||
}
|
||||
let out = run(&[(
|
||||
"main.dino",
|
||||
r#"import "sqlite3.h"
|
||||
|
||||
func main() {
|
||||
var db: sqlite3.sqlite3
|
||||
print(sqlite3.sqlite3_open(":memory:", db) == sqlite3.SQLITE_OK, db != nil)
|
||||
var stmt: sqlite3.sqlite3_stmt
|
||||
sqlite3.sqlite3_prepare_v2(db, "select 6 * 7 union select 1 order by 1", -1, stmt, nil)
|
||||
for sqlite3.sqlite3_step(stmt) == sqlite3.SQLITE_ROW {
|
||||
print(sqlite3.sqlite3_column_int(stmt, 0))
|
||||
}
|
||||
sqlite3.sqlite3_finalize(stmt)
|
||||
print(sqlite3.sqlite3_close(db) == sqlite3.SQLITE_OK)
|
||||
}
|
||||
"#,
|
||||
)]);
|
||||
assert_eq!(out, "true true\n1\n42\ntrue\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raylib_structs_without_a_window() {
|
||||
if !have_pkg("raylib") {
|
||||
return;
|
||||
}
|
||||
let out = run(&[(
|
||||
"main.dino",
|
||||
"import \"raylib.h\"\n\nfunc main() {\n var c = raylib.Fade(raylib.RED, 0.5)\n print(c, raylib.ColorToInt(raylib.Color{0, 0, 0, 255}))\n var p = raylib.Vector2{1.0, 1.0}\n print(raylib.CheckCollisionPointRec(p, raylib.Rectangle{0.0, 0.0, 2.0, 2.0}))\n}\n",
|
||||
)]);
|
||||
assert_eq!(out, "raylib.Color{r: 230, g: 41, b: 55, a: 127} 255\ntrue\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn errors_name_the_problem() {
|
||||
let e = error(&[("main.dino", "import \"no_such_header.h\"\n\nfunc main() {}\n")]);
|
||||
assert!(e.contains("cannot find the C header `no_such_header.h`"), "{e}");
|
||||
|
||||
let e = error(&[("shapes.h", SHAPES_H), ("main.dino", "import \"shapes.h\" { aera }\n\nfunc main() {}\n")]);
|
||||
assert!(e.contains("`shapes.h` has no `aera` (did you mean `area`?)"), "{e}");
|
||||
|
||||
let e = error(&[("main.dino", "import \"stdio.h\"\n\nfunc main() {\n stdio.printf(\"hi\")\n}\n")]);
|
||||
assert!(e.contains("`printf` can't be called from Dino: it takes a variable number of arguments"), "{e}");
|
||||
|
||||
let e = error(&[("shapes.h", SHAPES_H), ("main.dino", "import \"shapes.h\"\n\nfunc main() {\n shapes.grow(shapes.Size{1.0, 1.0}, 2.0)\n}\n")]);
|
||||
assert!(e.contains("`grow` writes into `s`, so it must be a variable"), "{e}");
|
||||
|
||||
let e = error(&[("shapes.h", SHAPES_H), ("main.dino", "import \"shapes.h\"\n\nfunc main() {\n var n = 3\n print(shapes.make_box(n))\n}\n")]);
|
||||
assert!(e.contains("expected `i32`, found `int` (convert it with `i32(...)`)"), "{e}");
|
||||
|
||||
let e = error(&[("shapes.h", SHAPES_H), ("main.dino", "import \"shapes.h\"\n\nfunc main() {\n print(shapes.area())\n}\n")]);
|
||||
assert!(e.contains("`area` takes 1 argument (s: shapes.Size), but 0 were given"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_library_says_how_to_link() {
|
||||
let dir = folder(&[(
|
||||
"main.dino",
|
||||
"import \"math.h\" link \"dino_no_such_lib\"\n\nfunc main() {\n print(math.sqrt(4.0))\n}\n",
|
||||
)]);
|
||||
let c = driver::compile_file(dir.join("main.dino").to_str().unwrap()).unwrap();
|
||||
let e = driver::build_exe(&c, &dir.join("prog")).unwrap_err();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
assert!(e.contains("linking with the C library failed") && e.contains("link \"name\""), "{e}");
|
||||
}
|
||||
@@ -104,3 +104,12 @@ fn doc_examples_are_stable() {
|
||||
}
|
||||
assert!(n > 20, "only {n} doc examples were formattable");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn step_as_a_name_and_c_imports() {
|
||||
let src = "import \"raylib.h\" { Color,RED }\nimport \"zlib.h\" link \"z\"\n\nfunc step(dt: f32) {}\n\nfunc main() {\n step(1.0)\n for i in 0..10 step 2 { print(i) }\n}\n";
|
||||
assert_eq!(
|
||||
fmt(src),
|
||||
"import \"raylib.h\" { Color, RED }\nimport \"zlib.h\" link \"z\"\n\nfunc step(dt: f32) {}\n\nfunc main() {\n step(1.0)\n for i in 0..10 step 2 { print(i) }\n}\n"
|
||||
);
|
||||
}
|
||||
@@ -225,3 +225,33 @@ fn signature_help_marks_the_parameter() {
|
||||
assert_eq!(r.get("activeParameter").and_then(Json::as_i64), Some(1), "{r:?}");
|
||||
assert!(r.to_string().contains("add(a: int, b: int): int"), "{r:?}");
|
||||
}
|
||||
|
||||
// ---------- C headers ----------
|
||||
|
||||
fn with_header(src: &str, method: &str, line: i64, ch: i64) -> Json {
|
||||
let dir = std::env::temp_dir().join(format!("dino-lsp-c-{}-{}", std::process::id(), method.replace('/', "_")));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("geo.h"), "typedef struct { double x, y; } Point;\n#define ORIGIN_NAME \"origin\"\n/* distance */\ndouble dist(Point a, Point b);\nint clamp(int v, int lo, int hi);\n").unwrap();
|
||||
let uri = format!("file://{}/main.dino", dir.display());
|
||||
let mut msgs = vec![request(1, "initialize", Json::obj(vec![])), open(&uri, src), request(2, method, at(&uri, line, ch))];
|
||||
msgs.extend(exit_messages());
|
||||
let (out, _) = talk(msgs);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
out.into_iter().find(|m| m.get("id") == Some(&Json::Num(2.0))).unwrap().get("result").cloned().unwrap_or(Json::Null)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completion_lists_what_a_c_header_has() {
|
||||
let r = with_header("import \"geo.h\"\n\nfunc main() {\n geo.\n}\n", "textDocument/completion", 3, 8).to_string();
|
||||
assert!(r.contains("\"dist\"") && r.contains("\"Point\"") && r.contains("\"ORIGIN_NAME\"") && r.contains("dist(a: geo.Point, b: geo.Point): float"), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hover_and_hints_for_c_functions() {
|
||||
let src = "import \"geo.h\" { clamp }\n\nfunc main() {\n print(clamp(5, 0, \n}\n";
|
||||
let h = with_header(src, "textDocument/hover", 3, 11);
|
||||
let v = h.path(&["contents", "value"]).and_then(Json::as_str).unwrap_or("").to_string();
|
||||
assert!(v.contains("func clamp(v: i32, lo: i32, hi: i32): i32") && v.contains("geo.h"), "{v}");
|
||||
let s = with_header(src, "textDocument/signatureHelp", 3, 22);
|
||||
assert_eq!(s.get("activeParameter").and_then(Json::as_i64), Some(2), "{s:?}");
|
||||
}
|
||||
@@ -2213,6 +2213,17 @@ fn docs_examples_run() {
|
||||
}
|
||||
// the output block, if one follows right away
|
||||
let expected = rest.strip_prefix("\n```text\n").and_then(|r| r.find("```").map(|e| &r[..e]));
|
||||
if code.contains("import \"") {
|
||||
// C libraries: the header may be one written next to the program in the text,
|
||||
// or a library that isn't installed here
|
||||
match driver::compile_to_c(code) {
|
||||
Err(d) if d.msg.contains("cannot find the C header") => continue,
|
||||
Err(d) => panic!("{} failed:\n{code}\n{}", path.display(), d.msg),
|
||||
// without printed output it is a program to look at (a window), not to run
|
||||
Ok(_) if expected.is_none() => continue,
|
||||
Ok(_) => {}
|
||||
}
|
||||
}
|
||||
let o = run_source(code);
|
||||
assert_eq!(o.code, 0, "{} failed:\n{code}\n{}", path.display(), o.stderr);
|
||||
if let Some(want) = expected {
|
||||
|
||||
Reference in new issue
Block a user