//! Read-only view of the program tables emitted by `baml_cranelift` //! (`baml_export_table` and `baml_export_ext`), plus small helpers over //! `TypeObject`s and the `describe` JSON. //! //! Function id = position in the export table's function list. Type id = //! position in this program's type list: first the types the export table //! lists (the root package), then every other class or enum reachable from an //! exported signature, in a fixed walk order. Both are stable for one build. use std::{ collections::{HashMap, HashSet}, sync::atomic::{AtomicUsize, Ordering}, }; use bex2_heap_types::{ exports::{ EXPORT_EXT_VERSION, EXPORT_FLAG_MAY_WAIT, EXPORT_FLAG_METHOD, ExportExt, ExportTable, ExportedFunc, ExportedParam, FnSig, TYPE_PARAM_MARK_NESTED, TYPE_PARAM_MARK_NONE, }, object::{ ClassObject, EnumVariantObject, FieldDesc, TYPE_FLAG_ERASED, TYPE_FLAG_LITERAL_BIGINT, TypeKind, TypeObject, }, }; use serde_json::{Value as Json, json}; /// One entry of the type list. pub struct TypeEntry { /// Class or enum object; null for an interface. pub class: *const ClassObject, pub ty: *const TypeObject, pub name: &'static str, pub qualified: String, } /// Facts about one exported function beyond the export table. #[derive(Default)] pub struct FuncInfo { pub qualified: String, pub throws: *const TypeObject, pub self_class: *const ClassObject, pub type_params: u32, pub may_wait: bool, pub is_method: bool, /// Per parameter: `TYPE_PARAM_MARK_NONE`, `TYPE_PARAM_MARK_NESTED`, or the /// index of the type parameter that is the parameter's whole type. pub param_marks: Vec, pub return_mark: u32, /// Hash of each parameter's exact declared type (0 when unknown). pub param_hashes: Vec, /// Hash of each parameter's default expression (0 without one; empty /// when no parameter has a default). pub param_defaults: Vec, pub return_hash: u64, /// Declared signature of each function-typed parameter. pub param_sigs: Vec>, pub return_sig: Option<&'static FnSig>, } /// Qualified name of the class whose instances hold a host value. pub const HOST_VALUE_CLASS: &str = "baml.host.Value"; /// Qualified name of the class a host error becomes. pub const HOST_CALLABLE_CLASS: &str = "baml.errors.HostCallable"; /// Qualified name of the panic a host reply the library cannot accept becomes. pub const CONTRACT_VIOLATION_CLASS: &str = "baml.panics.HostContractViolation"; /// Addresses of this program's `baml.host.Value` and `baml.errors.HostCallable` /// class objects (0 when the program has none). Static `.rodata` of the one /// program linked into this copy of the library, so the same at every init; /// set by [`Program::new`] and read by the free helpers below, which have no /// `Program` at hand. static HOST_VALUE: AtomicUsize = AtomicUsize::new(0); static HOST_CALLABLE: AtomicUsize = AtomicUsize::new(0); /// Whether `class` is `baml.host.Value`: its instances hold a host value (a /// token the host chose) in their `@@rust_type` slot, and cross as tag 17 /// and the token, never as a handle or fields. pub fn is_host_value_class(class: *const ClassObject) -> bool { !class.is_null() && class as usize == HOST_VALUE.load(Ordering::Relaxed) } /// Whether `class` is `baml.errors.HostCallable`, the one class with a /// private field (`_handle`, a host value) that is not opaque. pub fn is_host_callable_class(class: *const ClassObject) -> bool { !class.is_null() && class as usize == HOST_CALLABLE.load(Ordering::Relaxed) } /// Static tables of one compiled program. pub struct Program { pub funcs: &'static [ExportedFunc], pub infos: Vec, pub types: Vec, /// `ClassObject` address (class or enum) → type id. class_ids: HashMap, /// `ClassObject` address → qualified name, for every emitted class and enum. qualified: HashMap, /// The class hook that can wait and so marks every function as able to /// wait (named in refusals), if any. pub wait_hook: Option<&'static str>, /// Trampoline address → (arity, `CALLABLE_FLAG_*`), for every function value. callables: HashMap, /// `baml.host.Value`, `baml.errors.HostCallable` and /// `baml.panics.HostContractViolation`, when the program has them. pub host_value: *const ClassObject, pub host_callable: *const ClassObject, pub contract_violation: *const ClassObject, } // SAFETY: every pointer here targets immutable static `.rodata` of the program. unsafe impl Send for Program {} // SAFETY: as above; the program is never mutated after construction. unsafe impl Sync for Program {} /// Returns `&[T]` for a `(ptr, len)` pair from a static table. /// /// # Safety /// `ptr` must point to `len` valid `T`s that live for the whole program. unsafe fn static_slice(ptr: *const T, len: usize) -> &'static [T] { if ptr.is_null() || len == 0 { &[] } else { // SAFETY: the caller guarantees `len` valid, immutable, 'static elements. unsafe { std::slice::from_raw_parts(ptr, len) } } } /// Reads a static UTF-8 string from a table (empty when null or invalid). /// /// # Safety /// `(ptr, len)` must describe static bytes. pub unsafe fn static_str(ptr: *const u8, len: usize) -> &'static str { // SAFETY: forwarded caller contract. let bytes = unsafe { static_slice(ptr, len) }; std::str::from_utf8(bytes).unwrap_or("") } impl Program { /// # Safety /// `table` (and `ext` when present) must be valid tables emitted by /// `baml_cranelift`, living for the rest of the process. pub unsafe fn new(table: &'static ExportTable, ext: Option<&'static ExportExt>) -> Self { // SAFETY: the export table's arrays are static `.rodata` emitted with these lengths. let funcs = unsafe { static_slice(table.funcs_ptr, table.func_count) }; // SAFETY: as above. let listed = unsafe { static_slice(table.types_ptr, table.type_count) }; let ext = ext.filter(|e| e.version == EXPORT_EXT_VERSION); let mut qualified = HashMap::new(); let mut callables = HashMap::new(); let mut infos: Vec = Vec::with_capacity(funcs.len()); if let Some(e) = ext { // SAFETY: static arrays emitted with these lengths. for c in unsafe { static_slice(e.classes_ptr, e.class_count) } { // SAFETY: static name bytes. qualified.insert(c.class as usize, unsafe { static_str(c.name_ptr, c.name_len) }); } // SAFETY: static array emitted with this length. for c in unsafe { static_slice(e.callables_ptr, e.callable_count) } { callables.insert(c.fn_ptr as usize, (c.arity, c.flags)); } // SAFETY: as above. let fext = unsafe { static_slice(e.funcs_ptr, e.func_count) }; for (fx, f) in fext.iter().zip(funcs) { // SAFETY: static array with `param_count` marks when non-null. let param_marks = unsafe { static_slice(fx.param_marks_ptr, f.param_count) }.to_vec(); // SAFETY: static arrays with `param_count` entries when non-null. let param_hashes = unsafe { static_slice(fx.param_type_hashes_ptr, f.param_count) }.to_vec(); // SAFETY: as above. let param_defaults = unsafe { static_slice(fx.param_default_digests_ptr, f.param_count) }.to_vec(); // SAFETY: as above; each non-null entry is a static `FnSig`. let param_sigs = unsafe { static_slice(fx.param_sigs_ptr, f.param_count) } .iter() .map(|&p| (!p.is_null()).then(|| unsafe { &*p })) .collect(); infos.push(FuncInfo { param_hashes, param_defaults, return_hash: fx.return_type_hash, param_sigs, // SAFETY: a static `FnSig` when non-null. return_sig: (!fx.return_sig.is_null()).then(|| unsafe { &*fx.return_sig }), param_marks, return_mark: fx.return_mark, // SAFETY: static name bytes. qualified: unsafe { static_str(fx.qualified_name_ptr, fx.qualified_name_len) } .to_string(), throws: fx.throws_ty, self_class: fx.self_class, type_params: fx.type_param_count, may_wait: fx.flags & EXPORT_FLAG_MAY_WAIT != 0, is_method: fx.flags & EXPORT_FLAG_METHOD != 0, }); } } while infos.len() < funcs.len() { let f = &funcs[infos.len()]; infos.push(FuncInfo { // SAFETY: static name bytes. qualified: unsafe { static_str(f.name_ptr, f.name_len) }.to_string(), // Without the extension table, assume the worst. may_wait: true, return_mark: TYPE_PARAM_MARK_NONE, ..FuncInfo::default() }); } let class_named = |want: &str| { qualified .iter() .find(|(_, q)| **q == want) .map_or(std::ptr::null(), |(c, _)| *c as *const ClassObject) }; let host_value = class_named(HOST_VALUE_CLASS); let host_callable = class_named(HOST_CALLABLE_CLASS); let contract_violation = class_named(CONTRACT_VIOLATION_CLASS); HOST_VALUE.store(host_value as usize, Ordering::Relaxed); HOST_CALLABLE.store(host_callable as usize, Ordering::Relaxed); let wait_hook = ext .filter(|e| !e.wait_hook_ptr.is_null()) // SAFETY: static name bytes. .map(|e| unsafe { static_str(e.wait_hook_ptr, e.wait_hook_len) }); let mut prog = Self { funcs, infos, types: Vec::new(), class_ids: HashMap::new(), qualified, wait_hook, callables, host_value, host_callable, contract_violation, }; for t in listed { if t.ty.is_null() { continue; } // SAFETY: static type object and name. let (class, name) = unsafe { ((*t.ty).class, static_str(t.name_ptr, t.name_len)) }; prog.push_type(class, t.ty, name); } // Every other class or enum an exported signature can carry. let mut seen = HashSet::new(); let mut roots: Vec<*const TypeObject> = Vec::new(); for (f, info) in funcs.iter().zip(&prog.infos) { roots.extend(Self::params(f).iter().map(|p| p.ty)); roots.push(f.return_ty); roots.push(info.throws); } for ty in roots { prog.discover(ty, &mut seen); } prog } fn push_type(&mut self, class: *const ClassObject, ty: *const TypeObject, name: &'static str) { if !class.is_null() && self.class_ids.contains_key(&(class as usize)) { return; } let id = u32::try_from(self.types.len()).unwrap_or(u32::MAX); if !class.is_null() { self.class_ids.insert(class as usize, id); } let qualified = if class.is_null() { name.to_string() } else { self.qualified_name(class) }; self.types.push(TypeEntry { class, ty, name, qualified, }); } /// Walks a type and lists every class and enum it names. fn discover(&mut self, ty: *const TypeObject, seen: &mut HashSet) { let mut stack = vec![ty]; while let Some(ty) = stack.pop() { if ty.is_null() || !seen.insert(ty as usize) { continue; } // SAFETY: static type object. let t = unsafe { &*ty }; stack.extend(type_args(t).iter().copied()); if matches!(t.kind, TypeKind::Class | TypeKind::Enum) && !t.class.is_null() { // SAFETY: static class object and name. let cls = unsafe { &*t.class }; let name = unsafe { static_str(cls.name_ptr, cls.name_len) }; self.push_type(t.class, ty, name); if t.kind == TypeKind::Class && !is_opaque_class(cls) { stack.extend(class_fields(cls).iter().map(|fd| fd.ty)); } } } } pub fn func(&self, id: u32) -> Option<&'static ExportedFunc> { self.funcs.get(id as usize) } pub fn info(&self, id: u32) -> &FuncInfo { &self.infos[id as usize] } pub fn params(f: &'static ExportedFunc) -> &'static [ExportedParam] { // SAFETY: the parameter array is static `.rodata` emitted with `param_count` entries. unsafe { static_slice(f.params_ptr, f.param_count) } } /// Arity and `CALLABLE_FLAG_*` of the trampoline a function value points at. pub fn callable(&self, fn_ptr: *const u8) -> Option<(u32, u32)> { self.callables.get(&(fn_ptr as usize)).copied() } /// Type id of a listed class or enum. pub fn type_id_of(&self, class: *const ClassObject) -> Option { self.class_ids.get(&(class as usize)).copied() } /// Class (or enum) object of a listed type id. pub fn class_of(&self, id: u32) -> Option<*const ClassObject> { let t = self.types.get(id as usize)?; (!t.class.is_null()).then_some(t.class) } /// The class or enum with qualified name `name`, when the program emits it. pub fn class_named(&self, name: &str) -> Option<*const ClassObject> { self.qualified .iter() .find(|(_, q)| **q == name) .map(|(c, _)| *c as *const ClassObject) } /// `package.namespace.Name` (just `namespace.Name` for the program's own types). pub fn qualified_name(&self, class: *const ClassObject) -> String { match self.qualified.get(&(class as usize)) { Some(q) => (*q).to_string(), None => class_name(class), } } /// The `describe` document: every exported function and type, as JSON. pub fn describe(&self) -> Json { let funcs: Vec = self .funcs .iter() .zip(&self.infos) .enumerate() .map(|(id, (f, info))| { let params: Vec = Self::params(f) .iter() .enumerate() .map(|(i, p)| { let mark = info .param_marks .get(i) .copied() .unwrap_or(TYPE_PARAM_MARK_NONE); let sig = info.param_sigs.get(i).copied().flatten(); let mut j = json!({ // SAFETY: parameter names are static strings. "name": unsafe { static_str(p.name_ptr, p.name_len) }, "type": self.describe_whole_type(p.ty, sig), "has_default": p.has_default != 0, }); // Which default: a digest of its expression (the value // itself is computed by compiled code when omitted). if let Some(&d) = info.param_defaults.get(i) && d != 0 { j["default_digest"] = Json::from(format!("{d:016x}")); } add_type_param_mark(&mut j, mark); j }) .collect(); let method_of = if info.is_method { self.type_id_of(info.self_class) .map_or(Json::Null, Json::from) } else { Json::Null }; let mut j = json!({ "id": id, // SAFETY: function names and docs are static strings. "name": unsafe { static_str(f.name_ptr, f.name_len) }, "qualified_name": info.qualified, "doc": unsafe { static_str(f.doc_ptr, f.doc_len) }, "params": params, "returns": self.describe_whole_type(f.return_ty, info.return_sig), "throws": self.describe_type(info.throws, 0), "type_params": info.type_params, "method_of": method_of, "may_wait": info.may_wait, }); // `"returns_type_param"` / `"returns_generic"`, like the parameters' marks. let mut marks = json!({}); add_type_param_mark(&mut marks, info.return_mark); if let Some(i) = marks.get("type_param") { j["returns_type_param"] = i.clone(); } j["returns_generic"] = Json::Bool(marks.get("generic").is_some()); j }) .collect(); let types: Vec = self .types .iter() .enumerate() .map(|(id, t)| self.describe_type_def(id, t)) .collect(); json!({ "format": 5, "functions": funcs, "types": types, }) } fn describe_type_def(&self, id: usize, t: &TypeEntry) -> Json { let (name, qualified) = (t.name, t.qualified.as_str()); if t.ty.is_null() { return json!({ "id": id, "name": name, "qualified_name": qualified, "kind": "unknown" }); } // SAFETY: `t.ty` is a static `TypeObject`. let ty = unsafe { &*t.ty }; match ty.kind { TypeKind::Class if !ty.class.is_null() => { if is_host_value_class(ty.class) { return json!({ "id": id, "name": name, "qualified_name": qualified, "kind": "host_value" }); } // SAFETY: `ty.class` is a static `ClassObject`. let class = unsafe { &*ty.class }; if is_opaque_class(class) { return json!({ "id": id, "name": name, "qualified_name": qualified, "kind": "opaque" }); } let fields: Vec = class_fields(class) .iter() .map(|fd| { json!({ // SAFETY: field names are static strings. "name": unsafe { static_str(fd.name_ptr, fd.name_len) }, "type": self.describe_type(fd.ty, 0), }) }) .collect(); // A generic class is listed (its instances reach a host through // `unknown`), but a host cannot send one back. json!({ "id": id, "name": name, "qualified_name": qualified, "kind": "class", "type_params": class.generic_count, "fields": fields }) } TypeKind::Enum if !ty.class.is_null() => { // SAFETY: `ty.class` is a static enum `ClassObject`. let variants: Vec = enum_variants(unsafe { &*ty.class }) .iter() .map(|&v| { if v.is_null() { Json::Null } else { // SAFETY: variant objects and their names are static. Json::from(unsafe { static_str((*v).name_ptr, (*v).name_len) }) } }) .collect(); json!({ "id": id, "name": name, "qualified_name": qualified, "kind": "enum", "variants": variants }) } TypeKind::Interface => { json!({ "id": id, "name": name, "qualified_name": qualified, "kind": "interface" }) } _ => json!({ "id": id, "name": name, "qualified_name": qualified, "kind": "unknown" }), } } /// The type of a whole parameter or result: a function type with its /// signature, `{"kind": "function", "params": [...], "returns": T, /// "throws": T, "exact": bool}` ("exact": every type in it can be /// checked, so host functions and handles are accepted there). fn describe_whole_type(&self, ty: *const TypeObject, sig: Option<&FnSig>) -> Json { let Some(sig) = sig else { return self.describe_type(ty, 0); }; let params: Vec = sig_params(sig) .iter() .map(|&p| self.describe_type(p, 1)) .collect(); json!({ "kind": "function", "params": params, "returns": self.describe_type(sig.ret, 1), "throws": self.describe_type(sig.throws, 1), "exact": sig.checked == 1, }) } /// A type as a JSON tree: `{"kind": "int"}`, `{"kind": "list", "of": ...}`, /// `{"kind": "class", "id": 3, "name": "Person"}`, ... pub fn describe_type(&self, ty: *const TypeObject, depth: usize) -> Json { if ty.is_null() || depth > 64 { return json!({ "kind": "unknown" }); } // SAFETY: every type pointer in the tables is a static `TypeObject`. let t = unsafe { &*ty }; let args = type_args(t); let arg = |i: usize| -> Json { args.get(i).map_or(json!({ "kind": "unknown" }), |&a| { self.describe_type(a, depth + 1) }) }; match t.kind { TypeKind::Null => json!({ "kind": "null" }), TypeKind::Bool => json!({ "kind": "bool" }), TypeKind::Int => json!({ "kind": "int" }), TypeKind::Float => json!({ "kind": "float" }), TypeKind::String => json!({ "kind": "string" }), TypeKind::Bytes => json!({ "kind": "bytes" }), TypeKind::Bigint => match bigint_literal(t) { // The value as a decimal string: JSON numbers cannot hold every bigint. Some(v) => json!({ "kind": "literal", "value": v, "bigint": true }), None => json!({ "kind": "bigint" }), }, TypeKind::Class if is_host_value_class(t.class) => json!({ "kind": "host_value" }), TypeKind::Class | TypeKind::Enum => { let kind = if t.kind == TypeKind::Class { "class" } else { "enum" }; let name = if t.class.is_null() { "" } else { // SAFETY: static class object and name. unsafe { static_str((*t.class).name_ptr, (*t.class).name_len) } }; json!({ "kind": kind, "id": self.type_id_of(t.class), "name": name }) } TypeKind::Interface => { let name = if t.interface.is_null() { "" } else { // SAFETY: static interface object and name. unsafe { static_str((*t.interface).name_ptr, (*t.interface).name_len) } }; json!({ "kind": "interface", "name": name }) } TypeKind::Array => json!({ "kind": "list", "of": arg(0) }), TypeKind::Map => json!({ "kind": "map", "key": arg(0), "value": arg(1) }), TypeKind::Optional | TypeKind::Union => { // The flat view (see `flatten`): what the bytes follow. let flat = flatten(t); let one = |m: *const TypeObject| self.describe_type(m, depth + 1); let core = match flat.members.as_slice() { [] => return json!({ "kind": "null" }), [m] => one(*m), ms => { json!({ "kind": "union", "members": ms.iter().map(|&m| one(m)).collect::>() }) } }; if flat.nullable { json!({ "kind": "optional", "of": core }) } else { core } } TypeKind::Tuple => { let items: Vec = (0..args.len()).map(arg).collect(); json!({ "kind": "tuple", "items": items }) } TypeKind::LiteralInt => { json!({ "kind": "literal", "value": (t.literal_payload as u64).cast_signed() }) } TypeKind::LiteralBool => json!({ "kind": "literal", "value": t.literal_payload != 0 }), TypeKind::LiteralFloat => { json!({ "kind": "literal", "value": f64::from_bits(t.literal_payload as u64) }) } TypeKind::LiteralString => { // SAFETY: literal strings are static bytes (`payload` = ptr, `tag` = len). let s = unsafe { static_str(t.literal_payload as *const u8, t.literal_tag) }; json!({ "kind": "literal", "value": s }) } TypeKind::Function => json!({ "kind": "function" }), TypeKind::Future => json!({ "kind": "future" }), TypeKind::Unknown if is_erased(t) => json!({ "kind": "erased" }), TypeKind::Unknown => json!({ "kind": "unknown" }), TypeKind::Never => json!({ "kind": "never" }), TypeKind::Type => json!({ "kind": "type" }), } } } /// Adds `"type_param": i` (the type is exactly type parameter `i`, sent and /// returned in the self-describing form) or `"generic": true` (the type /// mentions a type parameter inside, which then is `unknown`) to `j`. fn add_type_param_mark(j: &mut Json, mark: u32) { if mark == TYPE_PARAM_MARK_NESTED { j["generic"] = Json::Bool(true); } else if mark != TYPE_PARAM_MARK_NONE { j["type_param"] = Json::from(mark); j["generic"] = Json::Bool(true); } } /// Stable digest of everything a host relies on: the `describe` document /// without its doc comments (ids, names, types, field order, defaults, flags). pub fn interface_digest(describe: &Json) -> [u8; 32] { use sha2::{Digest, Sha256}; fn strip(v: &Json) -> Json { match v { Json::Object(m) => Json::Object( m.iter() .filter(|(k, _)| k.as_str() != "doc") .map(|(k, v)| (k.clone(), strip(v))) .collect(), ), Json::Array(a) => Json::Array(a.iter().map(strip).collect()), other => other.clone(), } } let canonical = serde_json::to_vec(&strip(describe)).unwrap_or_default(); Sha256::digest(&canonical).into() } /// The parameter types of a signature (an entry is null when it has no object). pub fn sig_params(sig: &FnSig) -> &'static [*const TypeObject] { // SAFETY: a static array with `param_count` entries when non-null. unsafe { static_slice(sig.params_ptr, sig.param_count) } } /// The flat view of an optional or union type, the one `describe`, the /// encoder and the decoder all follow: members collected depth first in /// declaration order (a union member contributes its members; an optional /// member contributes null and then its inner type), null taken out, and /// duplicates dropped keeping the first. `nullable` when null was anywhere: /// then the value has one presence byte, and the members follow it. pub struct Flat { pub nullable: bool, pub members: Members, } /// The members of a [`Flat`] view: up to four inline (every call decodes and /// encodes optionals and small unions through this, so it must not /// allocate), more on the heap. pub struct Members { len: usize, inline: [*const TypeObject; 4], more: Vec<*const TypeObject>, } impl Members { const fn new() -> Self { Self { len: 0, inline: [std::ptr::null(); 4], more: Vec::new(), } } fn push(&mut self, t: *const TypeObject) { if self.len < self.inline.len() { self.inline[self.len] = t; } else { if self.more.is_empty() { self.more.extend_from_slice(&self.inline); } self.more.push(t); } self.len += 1; } pub fn as_slice(&self) -> &[*const TypeObject] { if self.len <= self.inline.len() { &self.inline[..self.len] } else { &self.more } } } impl std::ops::Deref for Members { type Target = [*const TypeObject]; fn deref(&self) -> &Self::Target { self.as_slice() } } /// See [`Flat`]. Type objects are interned per type, so a type repeated /// through nesting or an alias is the same pointer. Any other type is its /// own one-member view. /// /// The compiler already emits optional and union type objects in this form /// (`normalize_union_keys` in `baml_cranelift`): a union's members are never /// null, optional or union, and an optional holds one member or one such /// union. Then the flat view is the type object's own members, which `checks` /// builds assert. The walk stays as a guard for a library packed by a /// compiler that left an optional union nested inside a union. pub fn flatten(t: &TypeObject) -> Flat { fn walk(ty: *const TypeObject, flat: &mut Flat, depth: usize) { // SAFETY: a non-null type pointer is a static type object. let kind = (!ty.is_null()).then(|| unsafe { (*ty).kind }); match kind { Some(TypeKind::Null) => flat.nullable = true, Some(TypeKind::Optional | TypeKind::Union) if depth < 64 => { // SAFETY: as above. let t = unsafe { &*ty }; if t.kind == TypeKind::Optional { flat.nullable = true; } for &m in type_args(t) { walk(m, flat, depth + 1); } } _ => { if !flat.members.iter().any(|&m| std::ptr::eq(m, ty)) { flat.members.push(ty); } } } } let mut flat = Flat { nullable: false, members: Members::new(), }; // The common case, `T?` of a plain type, without the walk. if t.kind == TypeKind::Optional && let [inner] = type_args(t) && !inner.is_null() // SAFETY: a non-null type pointer is a static type object. && !matches!( unsafe { (**inner).kind }, TypeKind::Null | TypeKind::Optional | TypeKind::Union ) { flat.nullable = true; flat.members.push(*inner); return flat; } walk(t, &mut flat, 0); #[cfg(feature = "checks")] assert_already_flat(t, &flat); flat } /// `checks` builds: the compiler emitted `t` flat, so [`flatten`] returned /// exactly its own members (a union's members; an optional's inner type, or /// that inner union's members) and found null only in an optional. #[cfg(feature = "checks")] fn assert_already_flat(t: &TypeObject, flat: &Flat) { let own: &[*const TypeObject] = match t.kind { TypeKind::Union => type_args(t), TypeKind::Optional => match type_args(t) { &[inner] if !inner.is_null() => { // SAFETY: a non-null type pointer is a static type object. let inner = unsafe { &*inner }; if inner.kind == TypeKind::Union { type_args(inner) } else { type_args(t) } } args => args, }, _ => return, }; assert!( flat.nullable == (t.kind == TypeKind::Optional) && flat.members.as_slice() == own, "the compiler emitted a {:?} type object that is not flat", t.kind ); } /// Type arguments of a type object (`list` element, `map` key and value, tuple /// items, union members, `optional` inner). pub fn type_args(t: &TypeObject) -> &'static [*const TypeObject] { // SAFETY: type argument arrays are static `.rodata` with `args_len` entries. unsafe { static_slice(t.args_ptr, t.args_len) } } /// Declared fields of a class (empty for `@@rust_type` classes). pub fn class_fields(class: &ClassObject) -> &'static [FieldDesc] { // SAFETY: the field array is static `.rodata` with `field_count` entries when non-null. unsafe { static_slice(class.fields_ptr, class.field_count as usize) } } /// Variants of an enum class. pub fn enum_variants(class: &ClassObject) -> &'static [*const EnumVariantObject] { // SAFETY: the variant array is static `.rodata` with `variant_count` entries. unsafe { static_slice(class.variants_ptr, class.variant_count) } } /// Whether the compiler emitted `unknown` in place of a declared type it /// erases (a type parameter, a recursive alias, ...). No host value is /// accepted there: compiled code still assumes the declared type. pub fn is_erased(t: &TypeObject) -> bool { t.flags & TYPE_FLAG_ERASED != 0 } /// The value of a bigint literal type (`5n`), in decimal, or `None` for any /// other type (the plain `bigint` type included). pub fn bigint_literal(t: &TypeObject) -> Option<&'static str> { (t.kind == TypeKind::Bigint && t.flags & TYPE_FLAG_LITERAL_BIGINT != 0) // SAFETY: the compiler stores the decimal digits as static bytes. .then(|| unsafe { static_str(t.literal_payload as *const u8, t.literal_tag) }) } /// Whether the bigint (sign, little-endian 64-bit limbs) is the value of the /// bigint literal `lit` (decimal digits, `-` when negative). Compares lengths /// and limbs, never the decimal text: a host can send a bigint of millions of /// limbs, and converting it is quadratic. The literal (at most 128 bits) is /// parsed into limbs; a longer value is refused by its length alone. pub fn bigint_is_literal(lit: &str, negative: bool, limbs: &[u64]) -> bool { let (lit_neg, digits) = match lit.strip_prefix('-') { Some(d) => (true, d), None => (false, lit), }; let mut want: Vec = Vec::new(); for b in digits.bytes() { if !b.is_ascii_digit() { return false; } let mut carry = u128::from(b - b'0'); for limb in &mut want { let cur = u128::from(*limb) * 10 + carry; *limb = cur as u64; carry = cur >> 64; } if carry != 0 { want.push(carry as u64); } } let mut n = limbs.len(); // Trim high zero limbs; a value longer than the literal stops here. while n > want.len() && limbs[n - 1] == 0 { n -= 1; } let have = &limbs[..n]; if have.len() != want.len() || have != want.as_slice() { return false; } // Zero has no sign. want.is_empty() || negative == lit_neg } /// A bigint (sign, little-endian 64-bit limbs) in decimal, as the compiler /// writes bigint literals (`-` when negative; zero is `0`). #[cfg(test)] pub fn bigint_decimal(negative: bool, limbs: &[u64]) -> String { // Repeated division by 10^19, the largest power of ten in a `u64`. const CHUNK: u64 = 10_000_000_000_000_000_000; let mut mag: Vec = limbs.to_vec(); while mag.last() == Some(&0) { mag.pop(); } if mag.is_empty() { return "0".to_string(); } let mut chunks = Vec::new(); while !mag.is_empty() { let mut rem: u128 = 0; for limb in mag.iter_mut().rev() { let cur = (rem << 64) | u128::from(*limb); *limb = u64::try_from(cur / u128::from(CHUNK)).unwrap_or(u64::MAX); rem = cur % u128::from(CHUNK); } chunks.push(u64::try_from(rem).unwrap_or(0)); while mag.last() == Some(&0) { mag.pop(); } } let mut out = String::new(); if negative { out.push('-'); } out.push_str(&chunks.pop().unwrap_or(0).to_string()); for c in chunks.iter().rev() { use std::fmt::Write as _; let _ = write!(out, "{c:019}"); } out } /// A class whose values cannot be copied field by field, so they cross as /// handles: /// - its instances hold a Rust object (files, sockets, cancel tokens): the /// class has slots but no declared fields (`@@rust_type`); /// - or it has a private field (a name starting with `_`), which the host must /// not read or set (`baml.time.Duration` keeps `_nanoseconds`). /// /// Two exceptions: `baml.host.Value` (a `@@rust_type` class whose slot holds /// a host value: tag 17 and its token, see [`is_host_value_class`]) and /// `baml.errors.HostCallable` (its private `_handle` is such a host value, so /// the host can read every field: it crosses as a class). pub fn is_opaque_class(class: &ClassObject) -> bool { if class.is_enum != 0 || is_host_value_class(std::ptr::from_ref(class)) || is_host_callable_class(std::ptr::from_ref(class)) { return false; } if class.field_count > 0 && class.fields_ptr.is_null() { return true; } class_fields(class).iter().any(|fd| { // SAFETY: static field name. unsafe { static_str(fd.name_ptr, fd.name_len) }.starts_with('_') }) } /// Display name of a class, `package.Name` when the package is known (used /// when the extension table has no qualified name for it). pub fn class_name(class: *const ClassObject) -> String { if class.is_null() { return "".to_string(); } // SAFETY: class objects and their strings are static `.rodata`. let (name, pkg) = unsafe { ( static_str((*class).name_ptr, (*class).name_len), static_str((*class).package_ptr, (*class).package_len), ) }; if pkg.is_empty() || pkg == "user" { name.to_string() } else { format!("{pkg}.{name}") } } #[cfg(test)] mod tests { use super::{bigint_decimal, bigint_is_literal}; #[test] fn bigint_is_literal_compares_limbs() { assert!(bigint_is_literal("5", false, &[5])); assert!(bigint_is_literal("5", false, &[5, 0, 0])); assert!(!bigint_is_literal("5", true, &[5])); assert!(bigint_is_literal("-5", true, &[5])); assert!(bigint_is_literal("0", true, &[])); assert!(bigint_is_literal("0", false, &[0, 0])); assert!(!bigint_is_literal("5", false, &[5, 1])); assert!(bigint_is_literal("18446744073709551616", false, &[0, 1])); assert!(bigint_is_literal( "340282366920938463463374607431768211455", false, &[u64::MAX, u64::MAX] )); assert!(!bigint_is_literal("5", false, &vec![0x5a5a; 1 << 20])); } #[test] fn bigint_decimal_matches_the_compiler() { assert_eq!(bigint_decimal(false, &[]), "0"); assert_eq!(bigint_decimal(true, &[0, 0]), "0"); assert_eq!(bigint_decimal(false, &[5]), "5"); assert_eq!(bigint_decimal(true, &[5]), "-5"); assert_eq!(bigint_decimal(false, &[0, 1]), "18446744073709551616"); assert_eq!( bigint_decimal(false, &[10_000_000_000_000_000_000]), "10000000000000000000" ); assert_eq!( bigint_decimal(false, &[u64::MAX, u64::MAX]), "340282366920938463463374607431768211455" ); } }