Skip to main content

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