alef_core/ir.rs
1use serde::{Deserialize, Serialize};
2
3/// Indicates the core Rust type wraps the resolved type in a smart pointer or cow.
4/// Used by codegen to generate correct From/Into conversions.
5#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
6pub enum CoreWrapper {
7 #[default]
8 None,
9 /// `Cow<'static, str>` — binding uses String, core needs `.into()`
10 Cow,
11 /// `Arc<T>` — binding unwraps, core wraps with `Arc::new()`
12 Arc,
13 /// `bytes::Bytes` — binding uses `Vec<u8>`, core needs `Bytes::from()`
14 Bytes,
15 /// `Arc<Mutex<T>>` — binding wraps with `Arc::new(Mutex::new())`, methods call `.lock()`
16 ArcMutex,
17}
18
19/// Typed default value for a field, enabling backends to emit language-native defaults.
20#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
21pub enum DefaultValue {
22 BoolLiteral(bool),
23 StringLiteral(String),
24 IntLiteral(i64),
25 FloatLiteral(f64),
26 EnumVariant(String),
27 /// Empty collection or Default::default()
28 Empty,
29 /// None / null
30 None,
31}
32
33/// Complete API surface extracted from a Rust crate's public interface.
34#[derive(Debug, Clone, Default, Serialize, Deserialize)]
35pub struct ApiSurface {
36 pub crate_name: String,
37 pub version: String,
38 pub types: Vec<TypeDef>,
39 pub functions: Vec<FunctionDef>,
40 pub enums: Vec<EnumDef>,
41 pub errors: Vec<ErrorDef>,
42 /// Type names → fully qualified rust_paths for types that were extracted but
43 /// then excluded from the public binding surface. Preserved so trait_bridge
44 /// codegen can still reference them by qualified path when they appear in
45 /// trait method signatures (e.g. `Renderer::render(&InternalDocument)`).
46 #[serde(default)]
47 pub excluded_type_paths: std::collections::HashMap<String, String>,
48}
49
50/// A public struct exposed to bindings.
51#[derive(Debug, Clone, Serialize, Deserialize)]
52pub struct TypeDef {
53 pub name: String,
54 pub rust_path: String,
55 /// Original rust_path before path mapping rewrites. Used for From impl
56 /// targets to avoid orphan rule violations when core_import is a re-export facade.
57 #[serde(default)]
58 pub original_rust_path: String,
59 pub fields: Vec<FieldDef>,
60 pub methods: Vec<MethodDef>,
61 pub is_opaque: bool,
62 pub is_clone: bool,
63 /// True if the type derives `Copy` (or is bitwise-copyable).
64 /// Used by FFI codegen to avoid emitting `.clone()` (which trips clippy::clone_on_copy).
65 #[serde(default)]
66 pub is_copy: bool,
67 pub doc: String,
68 #[serde(default)]
69 pub cfg: Option<String>,
70 /// True if this type was extracted from a trait definition.
71 /// Trait types need `dyn` keyword when used as opaque inner types.
72 #[serde(default)]
73 pub is_trait: bool,
74 /// True if the type implements Default (via derive or manual impl).
75 /// Used by backends like NAPI to make all fields optional with defaults.
76 #[serde(default)]
77 pub has_default: bool,
78 /// True if some fields were stripped due to `#[cfg]` conditions.
79 /// When true, struct literal initializers need `..Default::default()` to fill
80 /// the missing fields that may exist when the core crate is compiled with features.
81 #[serde(default)]
82 pub has_stripped_cfg_fields: bool,
83 /// True if this type appears as a function return type.
84 /// Used to select output DTO style (e.g., TypedDict for Python return types).
85 #[serde(default)]
86 pub is_return_type: bool,
87 /// Serde `rename_all` strategy for this type (e.g., `"camelCase"`, `"snake_case"`).
88 /// Used by Go/Java/C# backends to emit correct JSON tags matching Rust serde config.
89 #[serde(default)]
90 pub serde_rename_all: Option<String>,
91 /// True if the type derives `serde::Serialize` and `serde::Deserialize`.
92 /// Used by FFI backend to gate `from_json`/`to_json` generation — types
93 /// without serde derives cannot be (de)serialized.
94 #[serde(default)]
95 pub has_serde: bool,
96 /// Super-traits of this trait (e.g., `["Plugin"]` for `OcrBackend: Plugin`).
97 /// Only populated when `is_trait` is true. Used by trait bridge codegen
98 /// to determine which super-trait impls to generate.
99 #[serde(default)]
100 pub super_traits: Vec<String>,
101}
102
103/// A field on a public struct.
104#[derive(Debug, Clone, Serialize, Deserialize)]
105pub struct FieldDef {
106 pub name: String,
107 pub ty: TypeRef,
108 pub optional: bool,
109 pub default: Option<String>,
110 pub doc: String,
111 /// True if this field's type was sanitized (e.g., Duration→u64, trait object→String).
112 /// Fields marked sanitized cannot participate in auto-generated From/Into conversions.
113 #[serde(default)]
114 pub sanitized: bool,
115 /// True if the core field type is `Box<T>` (or `Option<Box<T>>`).
116 /// Used by FFI backends to insert proper deref when cloning field values.
117 #[serde(default)]
118 pub is_boxed: bool,
119 /// Fully qualified Rust path for the field's type (e.g. `my_crate::types::OutputFormat`).
120 /// Used by backends to disambiguate types with the same short name.
121 #[serde(default)]
122 pub type_rust_path: Option<String>,
123 /// `#[cfg(...)]` condition string on this field, if any.
124 /// Used by backends to conditionally include fields in struct literals.
125 #[serde(default)]
126 pub cfg: Option<String>,
127 /// Typed default value for language-native default emission.
128 #[serde(default)]
129 pub typed_default: Option<DefaultValue>,
130 /// Core wrapper on this field (Cow, Arc, Bytes). Affects From/Into codegen.
131 #[serde(default)]
132 pub core_wrapper: CoreWrapper,
133 /// Core wrapper on Vec inner elements (e.g., `Vec<Arc<T>>`).
134 #[serde(default)]
135 pub vec_inner_core_wrapper: CoreWrapper,
136 /// Full Rust path of the newtype wrapper that was resolved away for this field,
137 /// e.g. `"my_crate::NodeIndex"` when `NodeIndex(u32)` was resolved to `u32`.
138 /// When set, binding→core codegen must wrap values into the newtype
139 /// (e.g. `my_crate::NodeIndex(val.field)`) and core→binding codegen must unwrap (`.0`).
140 #[serde(default)]
141 pub newtype_wrapper: Option<String>,
142 /// Explicit `#[serde(rename = "...")]` on this field, if any. Preserved so binding
143 /// structs that mirror the core struct can serialize/deserialize using the same wire
144 /// names (e.g. core `tool_type` with `#[serde(rename = "type")]` round-trips as `"type"`).
145 #[serde(default)]
146 pub serde_rename: Option<String>,
147 /// True when the field carries `#[serde(flatten)]`. Backends use this to emit
148 /// language-native flatten support: Jackson `@JsonAnyGetter`/`@JsonAnySetter`
149 /// in Java, `[JsonExtensionData]` in C# — both keyed `Map<String, Object>` /
150 /// `Dictionary<string, JsonElement>` so unknown sibling fields land under the
151 /// flattened bag instead of being rejected.
152 #[serde(default)]
153 pub serde_flatten: bool,
154}
155
156/// A method on a public struct.
157#[derive(Debug, Clone, Serialize, Deserialize)]
158pub struct MethodDef {
159 pub name: String,
160 pub params: Vec<ParamDef>,
161 pub return_type: TypeRef,
162 pub is_async: bool,
163 pub is_static: bool,
164 pub error_type: Option<String>,
165 pub doc: String,
166 pub receiver: Option<ReceiverKind>,
167 /// True if any param or return type was sanitized during unknown type resolution.
168 /// Methods with sanitized signatures cannot be auto-delegated.
169 #[serde(default)]
170 pub sanitized: bool,
171 /// Fully qualified trait path if this method comes from a trait impl
172 /// (e.g. "liter_llm::LlmClient"). None for inherent methods.
173 #[serde(default)]
174 pub trait_source: Option<String>,
175 /// True if the core function returns a reference (`&T`, `Option<&T>`, etc.).
176 /// Used by code generators to insert `.clone()` before type conversion.
177 #[serde(default)]
178 pub returns_ref: bool,
179 /// True if the core function returns `Cow<'_, T>` where T is a named type (not str/bytes).
180 /// Used by code generators to emit `.into_owned()` before type conversion.
181 #[serde(default)]
182 pub returns_cow: bool,
183 /// Full Rust path of the newtype wrapper that was resolved away for the return type,
184 /// e.g. `"my_crate::NodeIndex"` when the return type `NodeIndex(u32)` was resolved to `u32`.
185 /// When set, codegen must unwrap the returned newtype value (e.g. `result.0`) before returning.
186 #[serde(default)]
187 pub return_newtype_wrapper: Option<String>,
188 /// True if this method has a default implementation in the trait definition.
189 /// Methods with defaults can be optionally implemented by the foreign object
190 /// in trait bridge codegen.
191 #[serde(default)]
192 pub has_default_impl: bool,
193}
194
195/// How `self` is received.
196#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
197pub enum ReceiverKind {
198 Ref,
199 RefMut,
200 Owned,
201}
202
203/// A free function exposed to bindings.
204#[derive(Debug, Clone, Serialize, Deserialize)]
205pub struct FunctionDef {
206 pub name: String,
207 pub rust_path: String,
208 #[serde(default)]
209 pub original_rust_path: String,
210 pub params: Vec<ParamDef>,
211 pub return_type: TypeRef,
212 pub is_async: bool,
213 pub error_type: Option<String>,
214 pub doc: String,
215 #[serde(default)]
216 pub cfg: Option<String>,
217 /// True if any param or return type was sanitized during unknown type resolution.
218 #[serde(default)]
219 pub sanitized: bool,
220 /// True if the return type was sanitized (Named replaced with String). When true,
221 /// the binding-side return type is wider than the actual core return — codegen must
222 /// JSON-serialize the core value rather than treating it as the binding type.
223 #[serde(default)]
224 pub return_sanitized: bool,
225 /// True if the core function returns a reference (`&T`, `Option<&T>`, etc.).
226 /// Used by code generators to insert `.clone()` before type conversion.
227 #[serde(default)]
228 pub returns_ref: bool,
229 /// True if the core function returns `Cow<'_, T>` where T is a named type (not str/bytes).
230 /// Used by code generators to emit `.into_owned()` before type conversion.
231 #[serde(default)]
232 pub returns_cow: bool,
233 /// Full Rust path of the newtype wrapper that was resolved away for the return type.
234 /// When set, codegen must unwrap the returned newtype value (e.g. `result.0`).
235 #[serde(default)]
236 pub return_newtype_wrapper: Option<String>,
237}
238
239/// A function/method parameter.
240#[derive(Debug, Clone, Serialize, Deserialize)]
241pub struct ParamDef {
242 pub name: String,
243 pub ty: TypeRef,
244 pub optional: bool,
245 pub default: Option<String>,
246 /// True if this param's type was sanitized during unknown type resolution.
247 #[serde(default)]
248 pub sanitized: bool,
249 /// Typed default value for language-native default emission.
250 #[serde(default)]
251 pub typed_default: Option<DefaultValue>,
252 /// True if the original Rust parameter was a reference (`&T`).
253 /// Used by codegen to generate owned intermediates and pass refs.
254 #[serde(default)]
255 pub is_ref: bool,
256 /// True if the original Rust parameter was a mutable reference (`&mut T`).
257 /// Used by codegen to generate `&mut` refs when calling core functions.
258 #[serde(default)]
259 pub is_mut: bool,
260 /// Full Rust path of the newtype wrapper that was resolved away for this param,
261 /// e.g. `"my_crate::NodeIndex"` when `NodeIndex(u32)` was resolved to `u32`.
262 /// When set, codegen must wrap the raw value back into the newtype when calling core:
263 /// `my_crate::NodeIndex(param)` instead of just `param`.
264 #[serde(default)]
265 pub newtype_wrapper: Option<String>,
266 /// Original Rust type before sanitization, stored when param.sanitized=true.
267 /// Allows codegen to reconstruct proper deserialization logic.
268 /// E.g. `"Vec<(PathBuf, Option<FileExtractionConfig>)>"` when sanitized to `Vec<String>`.
269 #[serde(default)]
270 pub original_type: Option<String>,
271}
272
273/// A public enum.
274#[derive(Debug, Clone, Serialize, Deserialize)]
275pub struct EnumDef {
276 pub name: String,
277 pub rust_path: String,
278 #[serde(default)]
279 pub original_rust_path: String,
280 pub variants: Vec<EnumVariant>,
281 pub doc: String,
282 #[serde(default)]
283 pub cfg: Option<String>,
284 /// True if the enum derives `Copy`. Only unit-variant enums can derive Copy.
285 /// Used by FFI codegen to avoid emitting `.clone()` (which trips clippy::clone_on_copy).
286 #[serde(default)]
287 pub is_copy: bool,
288 /// True if the enum derives both `serde::Serialize` and `serde::Deserialize`.
289 /// Used by host-language emission (e.g. Swift `Codable`) to gate JSON-bridge conformance.
290 #[serde(default)]
291 pub has_serde: bool,
292 /// Serde tag property name for internally tagged enums (from `#[serde(tag = "...")]`)
293 #[serde(default, skip_serializing_if = "Option::is_none")]
294 pub serde_tag: Option<String>,
295 /// True when the enum has `#[serde(untagged)]`.
296 /// Absence of `serde_tag` does NOT imply untagged — it means externally-tagged (the serde
297 /// default). Only set this when the attribute is explicitly present on the Rust type.
298 #[serde(default)]
299 pub serde_untagged: bool,
300 /// Serde rename strategy for enum variants (from `#[serde(rename_all = "...")]`)
301 #[serde(default, skip_serializing_if = "Option::is_none")]
302 pub serde_rename_all: Option<String>,
303}
304
305/// An enum variant.
306#[derive(Debug, Clone, Serialize, Deserialize)]
307pub struct EnumVariant {
308 pub name: String,
309 pub fields: Vec<FieldDef>,
310 pub doc: String,
311 /// True if this variant has `#[default]` attribute (used by `#[derive(Default)]`).
312 #[serde(default)]
313 pub is_default: bool,
314 /// Explicit serde rename for this variant (from `#[serde(rename = "...")]`).
315 #[serde(default, skip_serializing_if = "Option::is_none")]
316 pub serde_rename: Option<String>,
317 /// True if this is a tuple variant (unnamed fields like `Variant(T1, T2)`).
318 /// False for struct variants with named fields or unit variants.
319 #[serde(default)]
320 pub is_tuple: bool,
321}
322
323/// An error type (enum used in Result<T, E>).
324#[derive(Debug, Clone, Serialize, Deserialize)]
325pub struct ErrorDef {
326 pub name: String,
327 pub rust_path: String,
328 #[serde(default)]
329 pub original_rust_path: String,
330 pub variants: Vec<ErrorVariant>,
331 pub doc: String,
332}
333
334/// An error variant.
335#[derive(Debug, Clone, Serialize, Deserialize)]
336pub struct ErrorVariant {
337 pub name: String,
338 /// The `#[error("...")]` message template string, e.g. `"I/O error: {0}"`.
339 pub message_template: Option<String>,
340 /// Fields on this variant (struct or tuple fields).
341 #[serde(default)]
342 pub fields: Vec<FieldDef>,
343 /// True if any field has `#[source]` or `#[from]`.
344 #[serde(default)]
345 pub has_source: bool,
346 /// True if any field has `#[from]` (auto From conversion).
347 #[serde(default)]
348 pub has_from: bool,
349 /// True if this is a unit variant (no fields).
350 #[serde(default)]
351 pub is_unit: bool,
352 pub doc: String,
353}
354
355/// Reference to a type, with enough info for codegen.
356#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
357pub enum TypeRef {
358 Primitive(PrimitiveType),
359 String,
360 /// Rust `char` — single Unicode character. Binding layer represents as single-char string.
361 Char,
362 Bytes,
363 Optional(Box<TypeRef>),
364 Vec(Box<TypeRef>),
365 Map(Box<TypeRef>, Box<TypeRef>),
366 Named(String),
367 Path,
368 Unit,
369 Json,
370 Duration,
371}
372
373impl TypeRef {
374 /// Returns true if this type reference contains `Named(name)` at any depth.
375 pub fn references_named(&self, name: &str) -> bool {
376 match self {
377 Self::Named(n) => n == name,
378 Self::Optional(inner) | Self::Vec(inner) => inner.references_named(name),
379 Self::Map(k, v) => k.references_named(name) || v.references_named(name),
380 _ => false,
381 }
382 }
383}
384
385/// Rust primitive types.
386#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
387pub enum PrimitiveType {
388 Bool,
389 U8,
390 U16,
391 U32,
392 U64,
393 I8,
394 I16,
395 I32,
396 I64,
397 F32,
398 F64,
399 Usize,
400 Isize,
401}