aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / crates / aien-abi-conformance / src / header.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! Just enough C header reading for omega's plain ABI headers: comments and preprocessor |
| 17 | //! lines removed, then top-level declarations split on `;`. It reads |
| 18 | //! `typedef struct [Tag] { ... } Name;` (field names in order), prototypes and |
| 19 | //! `typedef R (*Name)(...);` callback types. Types come back in canonical Rust spelling. |
| 20 | |
| 21 | use crate::manifest::{make_sig, split_top}; |
| 22 | use std::collections::BTreeMap; |
| 23 | |
| 24 | #[derive(Debug, Default)] |
| 25 | pub struct Header { |
| 26 | /// struct typedef name -> field names in declaration order |
| 27 | pub structs: BTreeMap<String, Vec<String>>, |
| 28 | /// function name -> canonical signature |
| 29 | pub fns: BTreeMap<String, String>, |
| 30 | /// callback typedef name -> canonical signature |
| 31 | pub fnptrs: BTreeMap<String, String>, |
| 32 | } |
| 33 | |
| 34 | /// Remove comments, string-free preprocessor lines (with `\` continuations) and |
| 35 | /// `extern "C" {` / `}` wrappers. |
| 36 | pub fn strip(src: &str) -> String { |
| 37 | let mut out = String::with_capacity(src.len()); |
| 38 | let b = src.as_bytes(); |
| 39 | let mut i = 0; |
| 40 | while i < b.len() { |
| 41 | if b[i] == b'/' && i + 1 < b.len() && b[i + 1] == b'*' { |
| 42 | i += 2; |
| 43 | while i + 1 < b.len() && !(b[i] == b'*' && b[i + 1] == b'/') { |
| 44 | i += 1; |
| 45 | } |
| 46 | i += 2; |
| 47 | out.push(' '); |
| 48 | } else if b[i] == b'/' && i + 1 < b.len() && b[i + 1] == b'/' { |
| 49 | while i < b.len() && b[i] != b'\n' { |
| 50 | i += 1; |
| 51 | } |
| 52 | } else { |
| 53 | out.push(b[i] as char); |
| 54 | i += 1; |
| 55 | } |
| 56 | } |
| 57 | let mut kept = String::new(); |
| 58 | let mut cont = false; |
| 59 | for line in out.lines() { |
| 60 | let t = line.trim(); |
| 61 | if cont || t.starts_with('#') { |
| 62 | cont = t.ends_with('\\'); |
| 63 | continue; |
| 64 | } |
| 65 | kept.push_str(line); |
| 66 | kept.push('\n'); |
| 67 | } |
| 68 | kept.replace("extern \"C\" {", " ") |
| 69 | } |
| 70 | |
| 71 | /// Split at top-level `;` (braces tracked) into whitespace-normalised statements. |
| 72 | fn statements(src: &str) -> Vec<String> { |
| 73 | let mut v = Vec::new(); |
| 74 | let mut depth = 0i32; |
| 75 | let mut cur = String::new(); |
| 76 | for c in src.chars() { |
| 77 | match c { |
| 78 | '{' => depth += 1, |
| 79 | '}' => { |
| 80 | depth -= 1; |
| 81 | if depth < 0 { |
| 82 | // the closing brace of an extern "C" block |
| 83 | depth = 0; |
| 84 | continue; |
| 85 | } |
| 86 | } |
| 87 | ';' if depth == 0 => { |
| 88 | let s = cur.split_whitespace().collect::<Vec<_>>().join(" "); |
| 89 | if !s.is_empty() { |
| 90 | v.push(s); |
| 91 | } |
| 92 | cur.clear(); |
| 93 | continue; |
| 94 | } |
| 95 | _ => {} |
| 96 | } |
| 97 | cur.push(c); |
| 98 | } |
| 99 | v |
| 100 | } |
| 101 | |
| 102 | fn tokens(s: &str) -> Vec<String> { |
| 103 | let mut t = Vec::new(); |
| 104 | let mut cur = String::new(); |
| 105 | for c in s.chars() { |
| 106 | if c.is_alphanumeric() || c == '_' { |
| 107 | cur.push(c); |
| 108 | } else { |
| 109 | if !cur.is_empty() { |
| 110 | t.push(std::mem::take(&mut cur)); |
| 111 | } |
| 112 | if !c.is_whitespace() { |
| 113 | t.push(c.to_string()); |
| 114 | } |
| 115 | } |
| 116 | } |
| 117 | if !cur.is_empty() { |
| 118 | t.push(cur); |
| 119 | } |
| 120 | t |
| 121 | } |
| 122 | |
| 123 | const BUILTIN: &[&str] = &[ |
| 124 | "void", "char", "short", "int", "long", "float", "double", "signed", "unsigned", "_Bool", |
| 125 | "bool", |
| 126 | ]; |
| 127 | |
| 128 | /// One C declaration (parameter, field or return type) -> (canonical Rust type, name). |
| 129 | pub fn c_decl(decl: &str) -> (String, Option<String>) { |
| 130 | let toks = tokens(decl); |
| 131 | let mut base_const = false; |
| 132 | let mut words: Vec<String> = Vec::new(); |
| 133 | let mut i = 0; |
| 134 | while i < toks.len() && toks[i] != "*" && toks[i] != "[" { |
| 135 | match toks[i].as_str() { |
| 136 | "const" => base_const = true, |
| 137 | "volatile" | "struct" | "enum" | "restrict" | "__restrict" => {} |
| 138 | w => words.push(w.to_string()), |
| 139 | } |
| 140 | i += 1; |
| 141 | } |
| 142 | // Pointer levels: each `*` may be followed by `const` (the pointer itself, ABI-irrelevant). |
| 143 | let mut stars = 0; |
| 144 | let mut name = None; |
| 145 | while i < toks.len() { |
| 146 | match toks[i].as_str() { |
| 147 | "*" => stars += 1, |
| 148 | "const" | "restrict" | "__restrict" => {} |
| 149 | "[" => { |
| 150 | // array parameter: decays to a pointer |
| 151 | stars += 1; |
| 152 | while i < toks.len() && toks[i] != "]" { |
| 153 | i += 1; |
| 154 | } |
| 155 | } |
| 156 | w if w.chars().all(|c| c.is_alphanumeric() || c == '_') => name = Some(w.to_string()), |
| 157 | _ => {} |
| 158 | } |
| 159 | i += 1; |
| 160 | } |
| 161 | let builtin: Vec<&str> = words |
| 162 | .iter() |
| 163 | .map(String::as_str) |
| 164 | .filter(|w| BUILTIN.contains(w)) |
| 165 | .collect(); |
| 166 | let (base, rest_name) = if builtin.is_empty() { |
| 167 | ( |
| 168 | words.first().cloned().unwrap_or_default(), |
| 169 | words.get(1).cloned(), |
| 170 | ) |
| 171 | } else { |
| 172 | let others: Vec<&String> = words |
| 173 | .iter() |
| 174 | .filter(|w| !BUILTIN.contains(&w.as_str())) |
| 175 | .collect(); |
| 176 | (builtin.join(" "), others.first().map(|s| s.to_string())) |
| 177 | }; |
| 178 | let name = name.or(rest_name); |
| 179 | let rust_base = match base.as_str() { |
| 180 | "int" | "signed" | "signed int" | "int32_t" => "i32", |
| 181 | "unsigned" | "unsigned int" | "uint32_t" => "u32", |
| 182 | "long" | "long int" | "long long" | "int64_t" => "i64", |
| 183 | "unsigned long" | "unsigned long long" | "uint64_t" => "u64", |
| 184 | "short" | "int16_t" => "i16", |
| 185 | "unsigned short" | "uint16_t" => "u16", |
| 186 | "signed char" | "int8_t" => "i8", |
| 187 | "unsigned char" | "uint8_t" => "u8", |
| 188 | "char" => "c_char", |
| 189 | "size_t" => "usize", |
| 190 | "ssize_t" | "ptrdiff_t" => "isize", |
| 191 | "float" => "f32", |
| 192 | "double" => "f64", |
| 193 | "bool" | "_Bool" => "bool", |
| 194 | "void" if stars > 0 => "c_void", |
| 195 | "void" => "()", |
| 196 | other => other, |
| 197 | } |
| 198 | .to_string(); |
| 199 | let mut ty = String::new(); |
| 200 | for level in 0..stars { |
| 201 | // The innermost pointer points at the (possibly const) base; outer ones point at |
| 202 | // pointers whose own constness the C declaration placed after their `*`. |
| 203 | let innermost = level == stars - 1; |
| 204 | ty.push_str(if innermost && base_const { |
| 205 | "*const " |
| 206 | } else { |
| 207 | "*mut " |
| 208 | }); |
| 209 | } |
| 210 | ty.push_str(&rust_base); |
| 211 | (ty, name) |
| 212 | } |
| 213 | |
| 214 | fn params(list: &str) -> Vec<String> { |
| 215 | let l = list.trim(); |
| 216 | if l.is_empty() || l == "void" { |
| 217 | return Vec::new(); |
| 218 | } |
| 219 | split_top(l).iter().map(|p| c_decl(p).0).collect() |
| 220 | } |
| 221 | |
| 222 | /// Parse the declarations of one header. |
| 223 | pub fn parse(src: &str) -> Header { |
| 224 | let mut h = Header::default(); |
| 225 | for st in statements(&strip(src)) { |
| 226 | if let Some(rest) = st.strip_prefix("typedef ") { |
| 227 | if rest.starts_with("struct") && rest.contains('{') { |
| 228 | let (Some(open), Some(close)) = (rest.find('{'), rest.rfind('}')) else { |
| 229 | continue; |
| 230 | }; |
| 231 | let name = rest[close + 1..].trim().to_string(); |
| 232 | let mut fields = Vec::new(); |
| 233 | for decl in rest[open + 1..close].split(';') { |
| 234 | let d = decl.trim(); |
| 235 | if d.is_empty() { |
| 236 | continue; |
| 237 | } |
| 238 | let parts = split_top(d); |
| 239 | // first declarator carries the base type; the rest are bare declarators |
| 240 | if let Some((_, Some(n))) = parts.first().map(|p| c_decl(p)) { |
| 241 | fields.push(n); |
| 242 | } |
| 243 | for p in parts.iter().skip(1) { |
| 244 | let t = tokens(p); |
| 245 | if let Some(n) = t |
| 246 | .iter() |
| 247 | .find(|w| w.chars().all(|c| c.is_alphanumeric() || c == '_')) |
| 248 | { |
| 249 | fields.push(n.clone()); |
| 250 | } |
| 251 | } |
| 252 | } |
| 253 | h.structs.insert(name, fields); |
| 254 | } else if let Some(p) = rest.find("(*") { |
| 255 | // typedef R (*Name)(params) |
| 256 | let ret = c_decl(&rest[..p]).0; |
| 257 | let after = &rest[p + 2..]; |
| 258 | let Some(close) = after.find(')') else { |
| 259 | continue; |
| 260 | }; |
| 261 | let name = after[..close].trim().to_string(); |
| 262 | let plist = after[close + 1..].trim(); |
| 263 | if let Some(inner) = plist.strip_prefix('(').and_then(|s| s.strip_suffix(')')) { |
| 264 | h.fnptrs.insert(name, make_sig(¶ms(inner), &ret)); |
| 265 | } |
| 266 | } |
| 267 | continue; |
| 268 | } |
| 269 | // prototype: R name(params) |
| 270 | let Some(open) = st.find('(') else { continue }; |
| 271 | if !st.ends_with(')') || st.contains('{') || st.contains('=') { |
| 272 | continue; |
| 273 | } |
| 274 | let (ret, name) = c_decl(&st[..open]); |
| 275 | let Some(name) = name else { continue }; |
| 276 | let inner = &st[open + 1..st.len() - 1]; |
| 277 | h.fns.insert(name, make_sig(¶ms(inner), &ret)); |
| 278 | } |
| 279 | h |
| 280 | } |
| 281 | |
| 282 | #[cfg(test)] |
| 283 | mod tests { |
| 284 | use super::*; |
| 285 | |
| 286 | #[test] |
| 287 | fn declarations() { |
| 288 | assert_eq!(c_decl("const char *dir").0, "*const c_char"); |
| 289 | assert_eq!(c_decl("RxcHost **out").0, "*mut *mut RxcHost"); |
| 290 | assert_eq!(c_decl("const uint64_t links[4]").0, "*const u64"); |
| 291 | assert_eq!(c_decl("uint32_t out[4]").0, "*mut u32"); |
| 292 | assert_eq!(c_decl("size_t").0, "usize"); |
| 293 | assert_eq!(c_decl("unsigned int x").0, "u32"); |
| 294 | assert_eq!(c_decl("const OmegaGpuTensor *t").0, "*const OmegaGpuTensor"); |
| 295 | assert_eq!(c_decl("void").0, "()"); |
| 296 | assert_eq!(c_decl("int").1, None); |
| 297 | assert_eq!(c_decl("uint32_t m").1.as_deref(), Some("m")); |
| 298 | } |
| 299 | |
| 300 | #[test] |
| 301 | fn header_parts() { |
| 302 | let src = r#" |
| 303 | /* comment with ; inside */ |
| 304 | #ifndef X |
| 305 | #define X 1u /* abi */ |
| 306 | #define LONG(a) \ |
| 307 | ((a) + 1) |
| 308 | #ifdef __cplusplus |
| 309 | extern "C" { |
| 310 | #endif |
| 311 | typedef struct Foo Foo; |
| 312 | typedef int (*CbFn)(void *ctx, uint64_t task, uint64_t *result); |
| 313 | typedef struct { |
| 314 | uint32_t a, b; // two |
| 315 | char name[64]; |
| 316 | bool ok; |
| 317 | } Info; |
| 318 | int open_it(const char *dir, uint32_t n, Foo **out, Info *info); |
| 319 | void close_it(Foo *h); |
| 320 | uint32_t layout(uint32_t out[4]); |
| 321 | int set_cb(Foo *h, CbFn fn, void *ctx); |
| 322 | const char *rc_name(int rc); |
| 323 | #ifdef __cplusplus |
| 324 | } |
| 325 | #endif |
| 326 | #endif |
| 327 | "#; |
| 328 | let h = parse(src); |
| 329 | assert_eq!(h.structs["Info"], ["a", "b", "name", "ok"]); |
| 330 | assert_eq!( |
| 331 | h.fns["open_it"], |
| 332 | "fn(*const c_char, u32, *mut *mut Foo, *mut Info) -> i32" |
| 333 | ); |
| 334 | assert_eq!(h.fns["close_it"], "fn(*mut Foo) -> ()"); |
| 335 | assert_eq!(h.fns["layout"], "fn(*mut u32) -> u32"); |
| 336 | assert_eq!(h.fns["set_cb"], "fn(*mut Foo, CbFn, *mut c_void) -> i32"); |
| 337 | assert_eq!(h.fns["rc_name"], "fn(i32) -> *const c_char"); |
| 338 | assert_eq!(h.fnptrs["CbFn"], "fn(*mut c_void, u64, *mut u64) -> i32"); |
| 339 | } |
| 340 | } |