Skip to main content

oraclemcp_driver_cx_derive/
lib.rs

1//! Procedural macros for the `oraclemcp-driver-cx` driver.
2//!
3//! This crate hosts the `#[derive(FromRow)]` macro. It is an implementation
4//! detail of the `oraclemcp-driver-cx` crate: end users never depend on it
5//! directly. The driver crate re-exports the derive (gated behind its default-on `derive`
6//! feature) alongside the `FromRow` trait the generated code implements, so the
7//! single import
8//!
9//! ```ignore
10//! use oraclemcp_driver_cx::FromRow;
11//! ```
12//!
13//! brings both the trait and the derive into scope.
14//!
15//! # What the derive generates
16//!
17//! For a struct
18//!
19//! ```ignore
20//! #[derive(FromRow)]
21//! struct Emp { id: i64, name: String, hired: Option<chrono::NaiveDate> }
22//! ```
23//!
24//! the macro emits an `impl oraclemcp_driver_cx::FromRow for Emp`, whose
25//! `from_row` pulls
26//! each field out of the row **by column name** through the existing typed
27//! accessor (`TypedRow::get_by_name`), which itself goes through the real
28//! `FromSql` conversion. There is no stringly-typed shortcut: an `i64` field is
29//! genuinely converted from the Oracle `NUMBER`, an `Option<T>` field accepts a
30//! SQL `NULL`, and a `chrono::NaiveDate` field is decoded from a `DATE`.
31//!
32//! # Supported shapes and attributes
33//!
34//! * Named-field structs — each field maps to a column named after the field.
35//! * Tuple structs — each field maps to a column **by position** (index 0, 1, …).
36//! * `#[driver_cx(rename_all = "UPPERCASE" | "lowercase" | "snake_case" |
37//!   "SCREAMING_SNAKE_CASE" | "camelCase" | "PascalCase")]` on the struct
38//!   renames every field's column (column resolution is case-insensitive, so
39//!   `UPPERCASE`/`lowercase` are cosmetic, but the others change word casing).
40//! * `#[driver_cx(column = "…")]` on a field overrides that one column name.
41//! * `#[driver_cx(rename = "…")]` is an accepted alias for `column = "…"`.
42//!
43//! Enums, unions, and unit/zero-field structs produce a clear `compile_error!`.
44
45use proc_macro::TokenStream;
46use proc_macro2::TokenStream as TokenStream2;
47use quote::quote;
48use syn::{parse_macro_input, spanned::Spanned, Data, DeriveInput, Fields, LitStr, Meta, Token};
49
50/// Derive an `oraclemcp_driver_cx::FromRow` implementation that maps a query row into the
51/// annotated struct, with compile-time-checked field types.
52///
53/// See the [crate-level documentation](crate) for the supported shapes and the
54/// `#[driver_cx(...)]` attributes.
55#[proc_macro_derive(FromRow, attributes(driver_cx))]
56pub fn derive_from_row(input: TokenStream) -> TokenStream {
57    let input = parse_macro_input!(input as DeriveInput);
58    expand(input)
59        .unwrap_or_else(syn::Error::into_compile_error)
60        .into()
61}
62
63/// One of the case-conversion strategies accepted by `rename_all`.
64#[derive(Clone, Copy)]
65enum RenameAll {
66    Upper,
67    Lower,
68    Snake,
69    ScreamingSnake,
70    Camel,
71    Pascal,
72}
73
74impl RenameAll {
75    fn parse(value: &LitStr) -> syn::Result<Self> {
76        Ok(match value.value().as_str() {
77            "UPPERCASE" => RenameAll::Upper,
78            "lowercase" => RenameAll::Lower,
79            "snake_case" => RenameAll::Snake,
80            "SCREAMING_SNAKE_CASE" => RenameAll::ScreamingSnake,
81            "camelCase" => RenameAll::Camel,
82            "PascalCase" => RenameAll::Pascal,
83            other => {
84                return Err(syn::Error::new(
85                    value.span(),
86                    format!(
87                        "unknown rename_all rule {other:?}; expected one of \
88                         \"UPPERCASE\", \"lowercase\", \"snake_case\", \
89                         \"SCREAMING_SNAKE_CASE\", \"camelCase\", \"PascalCase\""
90                    ),
91                ));
92            }
93        })
94    }
95
96    fn apply(self, field: &str) -> String {
97        match self {
98            RenameAll::Upper => field.to_uppercase(),
99            RenameAll::Lower => field.to_lowercase(),
100            RenameAll::Snake => to_snake(field),
101            RenameAll::ScreamingSnake => to_snake(field).to_uppercase(),
102            RenameAll::Camel => to_camel(field, false),
103            RenameAll::Pascal => to_camel(field, true),
104        }
105    }
106}
107
108/// Convert an identifier (`fooBar`, `FooBar`, `foo_bar`) to `foo_bar`.
109fn to_snake(field: &str) -> String {
110    let mut out = String::with_capacity(field.len() + 4);
111    let mut prev_lower_or_digit = false;
112    for ch in field.chars() {
113        if ch.is_uppercase() {
114            if prev_lower_or_digit {
115                out.push('_');
116            }
117            for lower in ch.to_lowercase() {
118                out.push(lower);
119            }
120            prev_lower_or_digit = false;
121        } else {
122            out.push(ch);
123            prev_lower_or_digit = ch.is_lowercase() || ch.is_ascii_digit();
124        }
125    }
126    out
127}
128
129/// Convert an identifier to camelCase (`pascal = false`) or PascalCase
130/// (`pascal = true`), treating `_` as a word boundary.
131fn to_camel(field: &str, pascal: bool) -> String {
132    let mut out = String::with_capacity(field.len());
133    let mut upper_next = pascal;
134    for ch in field.chars() {
135        if ch == '_' {
136            upper_next = true;
137            continue;
138        }
139        if upper_next {
140            for upper in ch.to_uppercase() {
141                out.push(upper);
142            }
143            upper_next = false;
144        } else {
145            out.push(ch);
146        }
147    }
148    out
149}
150
151/// Container-level options parsed from `#[driver_cx(...)]` on the struct.
152#[derive(Default)]
153struct ContainerOpts {
154    rename_all: Option<RenameAll>,
155}
156
157/// Field-level options parsed from `#[driver_cx(...)]` on a field.
158#[derive(Default)]
159struct FieldOpts {
160    column: Option<String>,
161}
162
163/// Parse every `#[driver_cx(...)]` attribute on a struct into container options.
164fn parse_container_opts(input: &DeriveInput) -> syn::Result<ContainerOpts> {
165    let mut opts = ContainerOpts::default();
166    for attr in &input.attrs {
167        if !attr.path().is_ident("driver_cx") {
168            continue;
169        }
170        let metas =
171            attr.parse_args_with(syn::punctuated::Punctuated::<Meta, Token![,]>::parse_terminated)?;
172        for meta in metas {
173            match &meta {
174                Meta::NameValue(nv) if nv.path.is_ident("rename_all") => {
175                    let lit = expect_str_lit(&nv.value)?;
176                    opts.rename_all = Some(RenameAll::parse(&lit)?);
177                }
178                _ => {
179                    return Err(syn::Error::new(
180                        meta.span(),
181                        "unsupported #[driver_cx(...)] container option; \
182                         expected `rename_all = \"...\"`",
183                    ));
184                }
185            }
186        }
187    }
188    Ok(opts)
189}
190
191/// Parse every `#[driver_cx(...)]` attribute on a field into field options.
192fn parse_field_opts(attrs: &[syn::Attribute]) -> syn::Result<FieldOpts> {
193    let mut opts = FieldOpts::default();
194    for attr in attrs {
195        if !attr.path().is_ident("driver_cx") {
196            continue;
197        }
198        let metas =
199            attr.parse_args_with(syn::punctuated::Punctuated::<Meta, Token![,]>::parse_terminated)?;
200        for meta in metas {
201            match &meta {
202                Meta::NameValue(nv) if nv.path.is_ident("column") || nv.path.is_ident("rename") => {
203                    let lit = expect_str_lit(&nv.value)?;
204                    opts.column = Some(lit.value());
205                }
206                _ => {
207                    return Err(syn::Error::new(
208                        meta.span(),
209                        "unsupported #[driver_cx(...)] field option; \
210                         expected `column = \"...\"` or `rename = \"...\"`",
211                    ));
212                }
213            }
214        }
215    }
216    Ok(opts)
217}
218
219/// If `ty` is syntactically `Option<Inner>` (in any of the spellings
220/// `Option<T>`, `std::option::Option<T>`, `core::option::Option<T>`), return
221/// `Some(Inner)`. This drives the choice between the NULL-rejecting accessor and
222/// the NULL-tolerant one in the generated code: an `Option<T>` field accepts a
223/// SQL `NULL` (mapping to `None`), a bare `T` field does not.
224fn option_inner(ty: &syn::Type) -> Option<&syn::Type> {
225    let syn::Type::Path(type_path) = ty else {
226        return None;
227    };
228    if type_path.qself.is_some() {
229        return None;
230    }
231    let segments = &type_path.path.segments;
232    // Accept `Option`, `option::Option`, `std::option::Option`, etc. — the last
233    // segment must be `Option` and the leading segments (if any) must be the
234    // `std`/`core` option path.
235    let last = segments.last()?;
236    if last.ident != "Option" {
237        return None;
238    }
239    let ok_prefix = match segments.len() {
240        1 => true,
241        n => {
242            let lead: Vec<String> = segments
243                .iter()
244                .take(n - 1)
245                .map(|s| s.ident.to_string())
246                .collect();
247            let lead: Vec<&str> = lead.iter().map(String::as_str).collect();
248            matches!(
249                lead.as_slice(),
250                ["option"] | ["std", "option"] | ["core", "option"]
251            )
252        }
253    };
254    if !ok_prefix {
255        return None;
256    }
257    let syn::PathArguments::AngleBracketed(args) = &last.arguments else {
258        return None;
259    };
260    args.args.iter().find_map(|arg| match arg {
261        syn::GenericArgument::Type(inner) => Some(inner),
262        _ => None,
263    })
264}
265
266/// Require an expression to be a string literal, returning it.
267fn expect_str_lit(expr: &syn::Expr) -> syn::Result<LitStr> {
268    if let syn::Expr::Lit(syn::ExprLit {
269        lit: syn::Lit::Str(s),
270        ..
271    }) = expr
272    {
273        Ok(s.clone())
274    } else {
275        Err(syn::Error::new(expr.span(), "expected a string literal"))
276    }
277}
278
279fn expand(input: DeriveInput) -> syn::Result<TokenStream2> {
280    let data = match &input.data {
281        Data::Struct(data) => data,
282        Data::Enum(e) => {
283            return Err(syn::Error::new(
284                e.enum_token.span(),
285                "#[derive(FromRow)] cannot be applied to enums: a query row maps \
286                 to a fixed set of columns, which an enum's variants do not model",
287            ));
288        }
289        Data::Union(u) => {
290            return Err(syn::Error::new(
291                u.union_token.span(),
292                "#[derive(FromRow)] cannot be applied to unions",
293            ));
294        }
295    };
296
297    let container = parse_container_opts(&input)?;
298    let name = &input.ident;
299    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
300
301    let body = match &data.fields {
302        Fields::Named(named) => named_body(named, &container)?,
303        Fields::Unnamed(unnamed) => unnamed_body(unnamed)?,
304        Fields::Unit => {
305            return Err(syn::Error::new(
306                input.ident.span(),
307                "#[derive(FromRow)] needs at least one field to map; a unit struct \
308                 maps no columns",
309            ));
310        }
311    };
312
313    Ok(quote! {
314        #[automatically_derived]
315        impl #impl_generics ::oraclemcp_driver_cx::FromRow for #name #ty_generics #where_clause {
316            fn from_row(
317                row: &::oraclemcp_driver_cx::TypedRow<'_>,
318            ) -> ::core::result::Result<Self, ::oraclemcp_driver_cx::ConversionError> {
319                ::core::result::Result::Ok(#name #body)
320            }
321        }
322    })
323}
324
325/// Build the `{ field: ..., ... }` construction for a named-field struct.
326fn named_body(named: &syn::FieldsNamed, container: &ContainerOpts) -> syn::Result<TokenStream2> {
327    if named.named.is_empty() {
328        return Err(syn::Error::new(
329            named.span(),
330            "#[derive(FromRow)] needs at least one field to map",
331        ));
332    }
333    let mut inits = Vec::with_capacity(named.named.len());
334    for field in &named.named {
335        let ident = field
336            .ident
337            .as_ref()
338            .ok_or_else(|| syn::Error::new(field.span(), "named field without an identifier"))?;
339        let ty = &field.ty;
340        let opts = parse_field_opts(&field.attrs)?;
341        let column = match opts.column {
342            Some(explicit) => explicit,
343            None => {
344                let base = ident.to_string();
345                let base = base.strip_prefix("r#").unwrap_or(&base);
346                match container.rename_all {
347                    Some(rule) => rule.apply(base),
348                    None => base.to_string(),
349                }
350            }
351        };
352        let access = match option_inner(ty) {
353            // Option<Inner>: NULL -> None. Call the NULL-tolerant accessor with
354            // the *inner* type so it returns Option<Inner> == the field type.
355            Some(inner) => quote! { row.try_get_by_name_opt::<#inner>(#column)? },
356            // Bare T: NULL is an error.
357            None => quote! { row.try_get_by_name::<#ty>(#column)? },
358        };
359        inits.push(quote! { #ident: #access });
360    }
361    Ok(quote! { { #(#inits),* } })
362}
363
364/// Build the `( ..., ... )` construction for a tuple struct, mapping by position.
365fn unnamed_body(unnamed: &syn::FieldsUnnamed) -> syn::Result<TokenStream2> {
366    if unnamed.unnamed.is_empty() {
367        return Err(syn::Error::new(
368            unnamed.span(),
369            "#[derive(FromRow)] needs at least one field to map",
370        ));
371    }
372    let mut inits = Vec::with_capacity(unnamed.unnamed.len());
373    for (index, field) in unnamed.unnamed.iter().enumerate() {
374        // Reject field-level attributes that only make sense on named fields.
375        let opts = parse_field_opts(&field.attrs)?;
376        if opts.column.is_some() {
377            return Err(syn::Error::new(
378                field.span(),
379                "#[driver_cx(column = ...)] is not supported on a tuple struct field; \
380                 tuple-struct fields map to columns by position",
381            ));
382        }
383        let ty = &field.ty;
384        let access = match option_inner(ty) {
385            Some(inner) => quote! { row.try_get_opt::<#inner>(#index)? },
386            None => quote! { row.try_get::<#ty>(#index)? },
387        };
388        inits.push(access);
389    }
390    // Trailing comma so a single-field tuple struct constructs as a tuple
391    // (`Foo(x,)`) rather than a parenthesized expression (`Foo(x)`).
392    Ok(quote! { ( #(#inits,)* ) })
393}