From a68c720755bd61b3a2011313de4396ccc88393fb Mon Sep 17 00:00:00 2001 From: Your Name Date: Sun, 8 Nov 2026 14:08:46 +0100 Subject: [PATCH] Let a Rex file wrap a C header with the same name Structs from C headers get their own table names, so raylib.rex can wrap "raylib.h" and still have its own Color. Ignore Opcode's .opcode file. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 1 + src/check.rs | 16 +++++++++++----- src/codegen_c.rs | 4 ++-- src/types.rs | 10 +++++++++- tests/clib.rs | 13 +++++++++++++ 5 files changed, 36 insertions(+), 8 deletions(-) diff --git a/.gitignore b/.gitignore index 2f7896d..3bcabfc 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ target/ +.opcode diff --git a/src/check.rs b/src/check.rs index b9f373d..1edeb94 100644 --- a/src/check.rs +++ b/src/check.rs @@ -1111,12 +1111,12 @@ impl Checker { fn global_key(&self, e: &Expr) -> Option { match &e.kind { ExprKind::Ident(n) => match self.c_item(n) { - Some(i) => Some(format!("{}.{n}", self.clibs[i].prefix)), + Some(i) => Some(c_key(&self.clibs[i].prefix, n)), None => Some(self.q(n)), }, ExprKind::Field { expr, name } => match self.alias_target(expr)? { Target::User(p) => Some(format!("{p}.{name}")), - Target::C(i) => Some(format!("{}.{name}", self.clibs[*i].prefix)), + Target::C(i) => Some(c_key(&self.clibs[*i].prefix, name)), _ => None, }, _ => None, @@ -1173,7 +1173,7 @@ impl Checker { CTy::Str => Ty::Str, CTy::Handle(n) if n == "pointer" => Ty::CPtr("pointer"), CTy::Handle(n) => Ty::CPtr(Box::leak(format!("{}.{n}", self.clibs[lib].prefix).into_boxed_str())), - CTy::Struct(n) => Ty::Struct(self.structs.get(&format!("{}.{n}", self.clibs[lib].prefix))?.name), + CTy::Struct(n) => Ty::Struct(self.structs.get(&c_key(&self.clibs[lib].prefix, n))?.name), CTy::Ptr { .. } | CTy::Unsupported(_) => return None, }) } @@ -1183,13 +1183,13 @@ impl Checker { for li in 0..self.clibs.len() { let prefix = self.clibs[li].prefix.clone(); for s in self.clibs[li].structs.clone() { - let key = format!("{prefix}.{}", s.name); + let key = c_key(&prefix, &s.name); let name: &'static str = Box::leak(key.clone().into_boxed_str()); self.structs.insert(key.clone(), StructInfo { name, fields: Vec::new(), methods: HashMap::new(), span: Span::default() }); self.c_structs.insert(key, s.c.clone()); } for s in self.clibs[li].structs.clone() { - let key = format!("{prefix}.{}", s.name); + let key = c_key(&prefix, &s.name); let fields: Vec<(String, Ty)> = s.fields.iter().map(|(n, t)| (n.clone(), self.c_type(li, t).unwrap_or(Ty::CPtr("pointer")))).collect(); self.structs.get_mut(&key).unwrap().fields = fields; @@ -4168,6 +4168,12 @@ fn check_mutating_calls(funcs: &[HFunc]) -> PResult<()> { Ok(()) } +/// The table name of a struct from a C header. It is marked so a file of the user's with the +/// same name as the header (a `raylib.rex` wrapping "raylib.h") can have types with the same names. +fn c_key(prefix: &str, name: &str) -> String { + format!("{}{prefix}.{name}", crate::types::C_MARK) +} + /// The name in `names` closest to `name`, if one is close enough to be a likely typo. fn similar<'a>(name: &str, names: &[&'a str]) -> Option<&'a str> { fn dist(a: &str, b: &str) -> usize { diff --git a/src/codegen_c.rs b/src/codegen_c.rs index 67dad14..cf9edd4 100644 --- a/src/codegen_c.rs +++ b/src/codegen_c.rs @@ -916,11 +916,11 @@ impl Gen { let c = c_struct(&s.name); let mut parts: Vec = Vec::new(); for (i, (name, ty)) in s.fields.iter().enumerate() { - let head = format!("{}{}: ", if i == 0 { format!("{}{{", s.name) } else { ", ".to_string() }, name); + let head = format!("{}{}: ", if i == 0 { format!("{}{{", crate::types::shown(&s.name)) } else { ", ".to_string() }, name); parts.push(str_lit(&head)); parts.push(to_str(*ty, &format!("v.{}", field_name(name)))); } - parts.push(str_lit(&if s.fields.is_empty() { format!("{}{{}}", s.name) } else { "}".to_string() })); + parts.push(str_lit(&if s.fields.is_empty() { format!("{}{{}}", crate::types::shown(&s.name)) } else { "}".to_string() })); self.out.push_str(&format!("static dstr {c}_str({c} v) {{\n")); self.out.push_str(&format!(" dstr parts[] = {{{}}};\n", parts.join(", "))); self.out.push_str(&format!( diff --git a/src/types.rs b/src/types.rs index 6518626..348de8c 100644 --- a/src/types.rs +++ b/src/types.rs @@ -1,5 +1,13 @@ use std::fmt; +/// Starts the table names of structs that come from C headers (see `check::c_key`). +pub const C_MARK: &str = "C:"; + +/// A type name as people should see it. +pub fn shown(name: &str) -> &str { + name.strip_prefix(C_MARK).unwrap_or(name) +} + /// The sized number types. (`i64` is the same type as `int`, and `f64` as `float`.) #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Num { @@ -171,7 +179,7 @@ impl fmt::Display for Ty { Ty::Bool => f.write_str("bool"), Ty::Char => f.write_str("char"), Ty::Str => f.write_str("string"), - Ty::Struct(name) | Ty::Enum(name) => f.write_str(name), + Ty::Struct(name) | Ty::Enum(name) => f.write_str(shown(name)), Ty::List(elem) => write!(f, "[]{elem}"), Ty::Map(k, v) => write!(f, "map[{k}, {v}]"), Ty::Num(n) => f.write_str(n.name()), diff --git a/tests/clib.rs b/tests/clib.rs index c35a29a..139a84a 100644 --- a/tests/clib.rs +++ b/tests/clib.rs @@ -298,3 +298,16 @@ fn a_missing_library_says_how_to_link() { let _ = std::fs::remove_dir_all(&dir); assert!(e.contains("linking with the C library failed") && e.contains("link \"name\""), "{e}"); } + +#[test] +fn a_wrapper_file_can_have_the_headers_name() { + // shapes.rex wraps shapes.h and has its own `Size` + let wrapper = "import \"shapes.h\"\n\npub struct Size {\n pub w, h: int\n}\n\npub func area(s: Size): float {\n return shapes.area(shapes.Size{float(s.w), float(s.h)})\n}\n"; + let out = run(&[ + ("shapes.h", SHAPES_H), + ("shapes.c", SHAPES_C), + ("shapes.rex", wrapper), + ("main.rex", "import shapes\n\nfunc main() {\n var s = shapes.Size{2, 3}\n print(s, shapes.area(s))\n}\n"), + ]); + assert_eq!(out, "shapes.Size{w: 2, h: 3} 6.0\n"); +}