Files
rexlang/tests/clib.rs
T
Your NameandClaude Opus 5.5 7cf9727bcd Rename the language from Dino to Rex
Files use .rex, the command is rex, and the crate, runtime prefixes,
docs, editor files and examples all use the new name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 13:51:23 +01:00

301 lines
11 KiB
Rust

//! 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 rex::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!("rex-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.rex` 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.rex").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.rex").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.rex",
"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.rex", 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.rex", 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.rex",
"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.rex",
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.rex",
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.rex",
"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.rex", "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.rex", "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.rex", "import \"stdio.h\"\n\nfunc main() {\n stdio.printf(\"hi\")\n}\n")]);
assert!(e.contains("`printf` can't be called from Rex: it takes a variable number of arguments"), "{e}");
let e = error(&[("shapes.h", SHAPES_H), ("main.rex", "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.rex", "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.rex", "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.rex",
"import \"math.h\" link \"rex_no_such_lib\"\n\nfunc main() {\n print(math.sqrt(4.0))\n}\n",
)]);
let c = driver::compile_file(dir.join("main.rex").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}");
}