Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/blob/main/crates/aien-abi-conformance/src/rust.rs # 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 Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / crates / aien-abi-conformance / src / rust.rs` 283 lines ยท 10062 bytes Raw Blame History 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 //! Rust side: declaration macros that record what they declare, and the manifest renderer. 17 18 use crate::manifest::{canon_sig, make_sig}; 19 20 /// Kind of a field's element type, as the C probe names it. 21 pub trait CKind { 22 const KIND: &'static str; 23 const COUNT: usize = 1; 24 } 25 26 macro_rules! ckind { 27 ($($t:ty => $k:literal),*) => { $(impl CKind for $t { const KIND: &'static str = $k; })* }; 28 } 29 ckind!(bool => "bool", i8 => "i8", u8 => "u8", i16 => "i16", u16 => "u16", i32 => "i32", 30 u32 => "u32", i64 => "i64", u64 => "u64", f32 => "f32", f64 => "f64"); 31 #[cfg(target_pointer_width = "64")] 32 ckind!(usize => "u64", isize => "i64"); 33 34 impl CKind for [T; N] { 35 const KIND: &'static str = T::KIND; 36 const COUNT: usize = N; 37 } 38 39 /// One field as recorded by [`abi_struct!`]. 40 #[derive(Debug, Clone, PartialEq, Eq)] 41 pub struct Field { 42 pub name: &'static str, 43 pub offset: usize, 44 pub size: usize, 45 pub kind: &'static str, 46 pub count: usize, 47 } 48 49 impl Field { 50 /// `ty` is the declared type's tokens: a `c_char` element is reported as `c_char` 51 /// (the C probe's name for plain `char`), whatever its signedness on this target. 52 pub fn of(name: &'static str, offset: usize, ty: &'static str) -> Field { 53 let kind = if ty.contains("c_char") { 54 "c_char" 55 } else { 56 T::KIND 57 }; 58 Field { 59 name, 60 offset, 61 size: std::mem::size_of::(), 62 kind, 63 count: T::COUNT, 64 } 65 } 66 } 67 68 /// A `#[repr(C)]` struct declared through [`abi_struct!`]. 69 pub trait AbiStruct: Sized { 70 const NAME: &'static str; 71 fn fields() -> Vec; 72 fn manifest_lines() -> Vec { 73 let mut v = vec![format!( 74 "struct {} {} {}", 75 Self::NAME, 76 std::mem::size_of::(), 77 std::mem::align_of::() 78 )]; 79 for f in Self::fields() { 80 v.push(format!( 81 "field {} {} {} {} {} {}", 82 Self::NAME, 83 f.name, 84 f.offset, 85 f.size, 86 f.kind, 87 f.count 88 )); 89 } 90 v 91 } 92 } 93 94 /// A recorded extern or callback signature: (name, return type tokens, parameter type tokens). 95 pub type FnSig = (&'static str, &'static str, &'static [&'static str]); 96 97 /// Everything one boundary's Rust mirror declares. 98 #[derive(Default)] 99 pub struct RustAbi { 100 pub structs: Vec>, 101 pub consts: Vec<(&'static str, i128)>, 102 pub fnptrs: Vec, 103 pub fns: Vec, 104 } 105 106 impl RustAbi { 107 pub fn with_struct(mut self) -> Self { 108 self.structs.push(T::manifest_lines()); 109 self 110 } 111 pub fn with_consts(mut self, c: &[(&'static str, i128)]) -> Self { 112 self.consts.extend_from_slice(c); 113 self 114 } 115 pub fn with_fnptrs(mut self, f: &[FnSig]) -> Self { 116 self.fnptrs.extend_from_slice(f); 117 self 118 } 119 pub fn with_fns(mut self, f: &[FnSig]) -> Self { 120 self.fns.extend_from_slice(f); 121 self 122 } 123 } 124 125 fn sig_text(ret: &str, params: &[&str]) -> String { 126 let s = make_sig(params, ret); 127 canon_sig(&s).unwrap_or(s) 128 } 129 130 /// The Rust mirror rendered as manifest fact lines, in the same order as 131 /// [`crate::Manifest::fact_lines`] renders a file (structs with their fields, constants, 132 /// callbacks, functions). 133 pub fn rust_manifest(abi: &RustAbi) -> Vec { 134 let mut v: Vec = abi.structs.iter().flatten().cloned().collect(); 135 for (n, val) in &abi.consts { 136 v.push(format!("const {n} {val}")); 137 } 138 for (n, r, p) in &abi.fnptrs { 139 v.push(format!("fnptr {n} {}", sig_text(r, p))); 140 } 141 for (n, r, p) in &abi.fns { 142 v.push(format!("fn {n} {}", sig_text(r, p))); 143 } 144 v 145 } 146 147 /// Declare a `#[repr(C)]` struct and record its fields in declaration order 148 /// (implements [`AbiStruct`]). Attributes and doc comments pass through unchanged. 149 #[macro_export] 150 macro_rules! abi_struct { 151 ($(#[$m:meta])* $vis:vis struct $name:ident { 152 $($(#[$fm:meta])* $fvis:vis $f:ident : $t:ty),* $(,)? 153 }) => { 154 $(#[$m])* $vis struct $name { $($(#[$fm])* $fvis $f : $t),* } 155 impl $crate::AbiStruct for $name { 156 const NAME: &'static str = stringify!($name); 157 fn fields() -> ::std::vec::Vec<$crate::Field> { 158 ::std::vec![$($crate::Field::of::<$t>( 159 stringify!($f), ::core::mem::offset_of!($name, $f), stringify!($t))),*] 160 } 161 } 162 }; 163 } 164 165 /// Declare an `extern "C"` block (attributes on the block, such as a `cfg`, apply to it as 166 /// usual) and a `pub const $table: &[FnSig]` naming every function's types. The table exists 167 /// in stub builds too, so the signatures are checked even where nothing links. 168 #[macro_export] 169 macro_rules! abi_externs { 170 ($table:ident; $(#[$bm:meta])* extern "C" { 171 $( $(#[$m:meta])* pub fn $name:ident ( $($p:ident : $t:ty),* $(,)? ) $(-> $r:ty)? ; )* 172 }) => { 173 $(#[$bm])* extern "C" { $( $(#[$m])* pub fn $name($($p: $t),*) $(-> $r)?; )* } 174 pub const $table: &[$crate::FnSig] = 175 &[$( (stringify!($name), stringify!($($r)?), &[$(stringify!($t)),*]) ),*]; 176 }; 177 } 178 179 /// Declare `unsafe extern "C" fn` callback types and a table of their signatures. 180 #[macro_export] 181 macro_rules! abi_fnptr { 182 ($table:ident; $( $(#[$m:meta])* pub type $name:ident = 183 unsafe extern "C" fn( $($p:ident : $t:ty),* $(,)? ) $(-> $r:ty)? ; )*) => { 184 $( $(#[$m])* pub type $name = unsafe extern "C" fn($($p: $t),*) $(-> $r)?; )* 185 pub const $table: &[$crate::FnSig] = 186 &[$( (stringify!($name), stringify!($($r)?), &[$(stringify!($t)),*]) ),*]; 187 }; 188 } 189 190 /// Declare integer constants mirrored from C and a table of their values. 191 #[macro_export] 192 macro_rules! abi_consts { 193 ($table:ident; $( $(#[$m:meta])* pub const $name:ident : $t:ty = $v:expr ; )*) => { 194 $( $(#[$m])* pub const $name: $t = $v; )* 195 pub const $table: &[(&str, i128)] = &[$( (stringify!($name), $name as i128) ),*]; 196 }; 197 } 198 199 /// Compare a Rust mirror with its checked-in manifest file. With `AIEN_ABI_BLESS=1` the file's 200 /// fact lines are rewritten from the Rust side instead (its `abi`/`header` lines and comments 201 /// are kept); the C side then has to agree in `build.rs` before anything links. 202 pub fn assert_manifest(abi: &RustAbi, path: &std::path::Path) { 203 let text = std::fs::read_to_string(path) 204 .unwrap_or_else(|e| panic!("cannot read {}: {e}", path.display())); 205 let rust = rust_manifest(abi); 206 if std::env::var("AIEN_ABI_BLESS").as_deref() == Ok("1") { 207 let mut out: Vec = text 208 .lines() 209 .take_while(|l| { 210 let t = l.trim_start(); 211 t.is_empty() 212 || t.starts_with('#') 213 || t.starts_with("abi ") 214 || t.starts_with("header ") 215 }) 216 .map(str::to_string) 217 .collect(); 218 out.extend(rust.iter().cloned()); 219 std::fs::write(path, out.join("\n") + "\n").expect("write manifest"); 220 return; 221 } 222 let m = crate::Manifest::parse(&text).unwrap_or_else(|e| panic!("{}: {e}", path.display())); 223 let file = m.fact_lines(); 224 if file != rust { 225 let only_rust: Vec<&String> = rust.iter().filter(|l| !file.contains(l)).collect(); 226 let only_file: Vec<&String> = file.iter().filter(|l| !rust.contains(l)).collect(); 227 panic!( 228 "Rust FFI declarations differ from {}\n Rust only: {only_rust:#?}\n manifest only: {only_file:#?}\n (order differs if both are empty). \ 229 An intended ABI change updates the manifest (AIEN_ABI_BLESS=1) and the omega pin together.", 230 path.display() 231 ); 232 } 233 } 234 235 #[cfg(test)] 236 mod tests { 237 use super::*; 238 use std::os::raw::{c_char, c_int, c_void}; 239 240 crate::abi_struct! { 241 #[repr(C)] 242 #[derive(Clone, Copy)] 243 pub struct Demo { 244 /// doc on a field 245 pub a: u8, 246 pub name: [c_char; 4], 247 pub b: u64, 248 pub flag: bool, 249 pub n: usize, 250 } 251 } 252 crate::abi_fnptr! { CB; #[allow(dead_code)] pub type Cb = unsafe extern "C" fn(ctx: *mut c_void, x: u64) -> c_int; } 253 crate::abi_externs! { FNS; #[cfg(any())] extern "C" { 254 /// doc 255 pub fn demo_open(p: *const c_char, cb: Option, out: *mut *mut Demo) -> c_int; 256 pub fn demo_close(); 257 } } 258 crate::abi_consts! { K; pub const DEMO_E: c_int = -3; pub const DEMO_V: u32 = 2; } 259 260 #[test] 261 fn macros_record_layout_and_signatures() { 262 let abi = RustAbi::default() 263 .with_struct::() 264 .with_consts(K) 265 .with_fnptrs(CB) 266 .with_fns(FNS); 267 let got = rust_manifest(&abi); 268 let want = [ 269 "struct Demo 32 8", 270 "field Demo a 0 1 u8 1", 271 "field Demo name 1 4 c_char 4", 272 "field Demo b 8 8 u64 1", 273 "field Demo flag 16 1 bool 1", 274 "field Demo n 24 8 u64 1", 275 "const DEMO_E -3", 276 "const DEMO_V 2", 277 "fnptr Cb fn(*mut c_void, u64) -> i32", 278 "fn demo_open fn(*const c_char, Cb, *mut *mut Demo) -> i32", 279 "fn demo_close fn() -> ()", 280 ]; 281 assert_eq!(got, want); 282 } 283 }