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}
16
17/// Typed default value for a field, enabling backends to emit language-native defaults.
18#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
19pub enum DefaultValue {
20    BoolLiteral(bool),
21    StringLiteral(String),
22    IntLiteral(i64),
23    FloatLiteral(f64),
24    EnumVariant(String),
25    /// Empty collection or Default::default()
26    Empty,
27    /// None / null
28    None,
29}
30
31/// Complete API surface extracted from a Rust crate's public interface.
32#[derive(Debug, Clone, Serialize, Deserialize)]
33pub struct ApiSurface {
34    pub crate_name: String,
35    pub version: String,
36    pub types: Vec<TypeDef>,
37    pub functions: Vec<FunctionDef>,
38    pub enums: Vec<EnumDef>,
39    pub errors: Vec<ErrorDef>,
40}
41
42/// A public struct exposed to bindings.
43#[derive(Debug, Clone, Serialize, Deserialize)]
44pub struct TypeDef {
45    pub name: String,
46    pub rust_path: String,
47    pub fields: Vec<FieldDef>,
48    pub methods: Vec<MethodDef>,
49    pub is_opaque: bool,
50    pub is_clone: bool,
51    pub doc: String,
52    #[serde(default)]
53    pub cfg: Option<String>,
54    /// True if this type was extracted from a trait definition.
55    /// Trait types need `dyn` keyword when used as opaque inner types.
56    #[serde(default)]
57    pub is_trait: bool,
58    /// True if the type implements Default (via derive or manual impl).
59    /// Used by backends like NAPI to make all fields optional with defaults.
60    #[serde(default)]
61    pub has_default: bool,
62    /// True if some fields were stripped due to `#[cfg]` conditions.
63    /// When true, struct literal initializers need `..Default::default()` to fill
64    /// the missing fields that may exist when the core crate is compiled with features.
65    #[serde(default)]
66    pub has_stripped_cfg_fields: bool,
67    /// True if this type appears as a function return type.
68    /// Used to select output DTO style (e.g., TypedDict for Python return types).
69    #[serde(default)]
70    pub is_return_type: bool,
71    /// Serde `rename_all` strategy for this type (e.g., `"camelCase"`, `"snake_case"`).
72    /// Used by Go/Java/C# backends to emit correct JSON tags matching Rust serde config.
73    #[serde(default)]
74    pub serde_rename_all: Option<String>,
75}
76
77/// A field on a public struct.
78#[derive(Debug, Clone, Serialize, Deserialize)]
79pub struct FieldDef {
80    pub name: String,
81    pub ty: TypeRef,
82    pub optional: bool,
83    pub default: Option<String>,
84    pub doc: String,
85    /// True if this field's type was sanitized (e.g., Duration→u64, trait object→String).
86    /// Fields marked sanitized cannot participate in auto-generated From/Into conversions.
87    #[serde(default)]
88    pub sanitized: bool,
89    /// True if the core field type is `Box<T>` (or `Option<Box<T>>`).
90    /// Used by FFI backends to insert proper deref when cloning field values.
91    #[serde(default)]
92    pub is_boxed: bool,
93    /// Fully qualified Rust path for the field's type (e.g. `my_crate::types::OutputFormat`).
94    /// Used by backends to disambiguate types with the same short name.
95    #[serde(default)]
96    pub type_rust_path: Option<String>,
97    /// `#[cfg(...)]` condition string on this field, if any.
98    /// Used by backends to conditionally include fields in struct literals.
99    #[serde(default)]
100    pub cfg: Option<String>,
101    /// Typed default value for language-native default emission.
102    #[serde(default)]
103    pub typed_default: Option<DefaultValue>,
104    /// Core wrapper on this field (Cow, Arc, Bytes). Affects From/Into codegen.
105    #[serde(default)]
106    pub core_wrapper: CoreWrapper,
107    /// Core wrapper on Vec inner elements (e.g., `Vec<Arc<T>>`).
108    #[serde(default)]
109    pub vec_inner_core_wrapper: CoreWrapper,
110    /// Full Rust path of the newtype wrapper that was resolved away for this field,
111    /// e.g. `"my_crate::NodeIndex"` when `NodeIndex(u32)` was resolved to `u32`.
112    /// When set, binding→core codegen must wrap values into the newtype
113    /// (e.g. `my_crate::NodeIndex(val.field)`) and core→binding codegen must unwrap (`.0`).
114    #[serde(default)]
115    pub newtype_wrapper: Option<String>,
116}
117
118/// A method on a public struct.
119#[derive(Debug, Clone, Serialize, Deserialize)]
120pub struct MethodDef {
121    pub name: String,
122    pub params: Vec<ParamDef>,
123    pub return_type: TypeRef,
124    pub is_async: bool,
125    pub is_static: bool,
126    pub error_type: Option<String>,
127    pub doc: String,
128    pub receiver: Option<ReceiverKind>,
129    /// True if any param or return type was sanitized during unknown type resolution.
130    /// Methods with sanitized signatures cannot be auto-delegated.
131    #[serde(default)]
132    pub sanitized: bool,
133    /// Fully qualified trait path if this method comes from a trait impl
134    /// (e.g. "liter_llm::LlmClient"). None for inherent methods.
135    #[serde(default)]
136    pub trait_source: Option<String>,
137    /// True if the core function returns a reference (`&T`, `Option<&T>`, etc.).
138    /// Used by code generators to insert `.clone()` before type conversion.
139    #[serde(default)]
140    pub returns_ref: bool,
141    /// True if the core function returns `Cow<'_, T>` where T is a named type (not str/bytes).
142    /// Used by code generators to emit `.into_owned()` before type conversion.
143    #[serde(default)]
144    pub returns_cow: bool,
145    /// Full Rust path of the newtype wrapper that was resolved away for the return type,
146    /// e.g. `"my_crate::NodeIndex"` when the return type `NodeIndex(u32)` was resolved to `u32`.
147    /// When set, codegen must unwrap the returned newtype value (e.g. `result.0`) before returning.
148    #[serde(default)]
149    pub return_newtype_wrapper: Option<String>,
150}
151
152/// How `self` is received.
153#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
154pub enum ReceiverKind {
155    Ref,
156    RefMut,
157    Owned,
158}
159
160/// A free function exposed to bindings.
161#[derive(Debug, Clone, Serialize, Deserialize)]
162pub struct FunctionDef {
163    pub name: String,
164    pub rust_path: String,
165    pub params: Vec<ParamDef>,
166    pub return_type: TypeRef,
167    pub is_async: bool,
168    pub error_type: Option<String>,
169    pub doc: String,
170    #[serde(default)]
171    pub cfg: Option<String>,
172    /// True if any param or return type was sanitized during unknown type resolution.
173    #[serde(default)]
174    pub sanitized: bool,
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    /// Full Rust path of the newtype wrapper that was resolved away for the return type.
180    /// When set, codegen must unwrap the returned newtype value (e.g. `result.0`).
181    #[serde(default)]
182    pub return_newtype_wrapper: Option<String>,
183}
184
185/// A function/method parameter.
186#[derive(Debug, Clone, Serialize, Deserialize)]
187pub struct ParamDef {
188    pub name: String,
189    pub ty: TypeRef,
190    pub optional: bool,
191    pub default: Option<String>,
192    /// True if this param's type was sanitized during unknown type resolution.
193    #[serde(default)]
194    pub sanitized: bool,
195    /// Typed default value for language-native default emission.
196    #[serde(default)]
197    pub typed_default: Option<DefaultValue>,
198    /// True if the original Rust parameter was a reference (`&T`).
199    /// Used by codegen to generate owned intermediates and pass refs.
200    #[serde(default)]
201    pub is_ref: bool,
202    /// Full Rust path of the newtype wrapper that was resolved away for this param,
203    /// e.g. `"my_crate::NodeIndex"` when `NodeIndex(u32)` was resolved to `u32`.
204    /// When set, codegen must wrap the raw value back into the newtype when calling core:
205    /// `my_crate::NodeIndex(param)` instead of just `param`.
206    #[serde(default)]
207    pub newtype_wrapper: Option<String>,
208}
209
210/// A public enum.
211#[derive(Debug, Clone, Serialize, Deserialize)]
212pub struct EnumDef {
213    pub name: String,
214    pub rust_path: String,
215    pub variants: Vec<EnumVariant>,
216    pub doc: String,
217    #[serde(default)]
218    pub cfg: Option<String>,
219    /// Serde tag property name for internally tagged enums (from `#[serde(tag = "...")]`)
220    #[serde(default, skip_serializing_if = "Option::is_none")]
221    pub serde_tag: Option<String>,
222    /// Serde rename strategy for enum variants (from `#[serde(rename_all = "...")]`)
223    #[serde(default, skip_serializing_if = "Option::is_none")]
224    pub serde_rename_all: Option<String>,
225}
226
227/// An enum variant.
228#[derive(Debug, Clone, Serialize, Deserialize)]
229pub struct EnumVariant {
230    pub name: String,
231    pub fields: Vec<FieldDef>,
232    pub doc: String,
233    /// True if this variant has `#[default]` attribute (used by `#[derive(Default)]`).
234    #[serde(default)]
235    pub is_default: bool,
236    /// Explicit serde rename for this variant (from `#[serde(rename = "...")]`).
237    #[serde(default, skip_serializing_if = "Option::is_none")]
238    pub serde_rename: Option<String>,
239}
240
241/// An error type (enum used in Result<T, E>).
242#[derive(Debug, Clone, Serialize, Deserialize)]
243pub struct ErrorDef {
244    pub name: String,
245    pub rust_path: String,
246    pub variants: Vec<ErrorVariant>,
247    pub doc: String,
248}
249
250/// An error variant.
251#[derive(Debug, Clone, Serialize, Deserialize)]
252pub struct ErrorVariant {
253    pub name: String,
254    /// The `#[error("...")]` message template string, e.g. `"I/O error: {0}"`.
255    pub message_template: Option<String>,
256    /// Fields on this variant (struct or tuple fields).
257    #[serde(default)]
258    pub fields: Vec<FieldDef>,
259    /// True if any field has `#[source]` or `#[from]`.
260    #[serde(default)]
261    pub has_source: bool,
262    /// True if any field has `#[from]` (auto From conversion).
263    #[serde(default)]
264    pub has_from: bool,
265    /// True if this is a unit variant (no fields).
266    #[serde(default)]
267    pub is_unit: bool,
268    pub doc: String,
269}
270
271/// Reference to a type, with enough info for codegen.
272#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
273pub enum TypeRef {
274    Primitive(PrimitiveType),
275    String,
276    /// Rust `char` — single Unicode character. Binding layer represents as single-char string.
277    Char,
278    Bytes,
279    Optional(Box<TypeRef>),
280    Vec(Box<TypeRef>),
281    Map(Box<TypeRef>, Box<TypeRef>),
282    Named(String),
283    Path,
284    Unit,
285    Json,
286    Duration,
287}
288
289/// Rust primitive types.
290#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
291pub enum PrimitiveType {
292    Bool,
293    U8,
294    U16,
295    U32,
296    U64,
297    I8,
298    I16,
299    I32,
300    I64,
301    F32,
302    F64,
303    Usize,
304    Isize,
305}