loopctl-derive 0.3.0

Derive macro for the loopctl Tool trait
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
//! `#[tool(...)]` attribute parsing for the derive.
//!
//! Parses the container-level attributes (name, description,
//! `read_only`, `concurrency_safe`, `system_prompt`, `handler`,
//! `allow_extra`)
//! and the field-level attributes (`name`, `description`, `skip`,
//! `default`),
//! plus the serde attributes the schema mirrors (`rename`,
//! `rename_all`, `default`). All parsers use syn's nested-meta walker
//! so diagnostics carry the offending attribute's span.

use syn::{Attribute, Expr, Lit, LitStr, Meta};

/// Container-level (`#[tool(...)]` on the struct) attributes.
///
/// Collected from every `#[tool(...)]` attribute on the derived
/// struct; unset members keep their `Default` (absent/false), and the
/// codegen in [`crate::expand`] reads them to decide what the
/// generated `impl Tool` contains.
#[derive(Default)]
pub(crate) struct ContainerAttrs {
    /// Override for the derived tool name.
    ///
    /// When `None`, the codegen falls back to the `snake_cased` struct
    /// identifier (`EchoInput` → `echo_input`). Non-empty and stable
    /// for the session, per the trait's contract.
    pub name: Option<String>,

    /// Override for the description.
    ///
    /// When `None`, the struct's `///` doc comment is used; when
    /// neither is present the derive errors — the trait requires a
    /// non-empty description.
    pub description: Option<String>,

    /// Emit `is_read_only() -> true`.
    ///
    /// The method override is generated only when the flag is set;
    /// otherwise the trait's default (`false`) applies untouched.
    pub read_only: bool,

    /// Emit `is_concurrency_safe() -> true`.
    ///
    /// Same conditional-generation rule as
    /// [`read_only`](Self::read_only): absent means the trait default.
    pub concurrency_safe: bool,

    /// Emit `system_prompt() -> Some(...)`.
    ///
    /// The tool's extra LLM hint, surfaced to the model verbatim.
    /// `None` leaves the trait's default (`None`) in place.
    pub system_prompt: Option<String>,

    /// Name of the handler `call` dispatches to (default: `run`).
    ///
    /// The generated `call` resolves the handler by this name as an
    /// inherent method on the struct; a wrong name surfaces as a
    /// normal "no method named …" compiler error at the call site.
    pub handler: Option<String>,

    /// Omit `additionalProperties: false` from the schema.
    ///
    /// The schema closes the world by default (strict-mode
    /// friendly); tools that accept open-ended input set this to
    /// advertise the absence of the flag instead.
    pub allow_extra: bool,
}

/// Field-level (`#[tool(...)]` on a field) attributes.
///
/// One instance per named field of the derived struct, collected the
/// same way as [`ContainerAttrs`]; the schema generator consults
/// them per field.
#[derive(Default)]
pub(crate) struct FieldAttrs {
    /// JSON property name override.
    ///
    /// Mirrors serde's `#[serde(rename)]` for the schema side only —
    /// the two must agree for deserialization to match the schema.
    pub name: Option<String>,

    /// Property description override.
    ///
    /// Falls back to the field's `///` doc comment; when neither is
    /// present the property simply carries no `description` key.
    pub description: Option<String>,

    /// Exclude the field from the schema and the required array.
    ///
    /// Valid only on fields that deserialize without model input —
    /// `Option<T>` or `#[serde(default)]`; the derive enforces this
    /// with a spanned error.
    pub skip: bool,

    /// Keep the property but omit it from the required array.
    ///
    /// Distinct from [`skip`](Self::skip): the property stays
    /// advertised, the call just succeeds without it. Pairs with
    /// `#[serde(default)]` on the Rust side.
    pub default: bool,
}

const CONTAINER_KEYS: &str =
    "name, description, read_only, concurrency_safe, system_prompt, handler, allow_extra";
const FIELD_KEYS: &str = "name, description, skip, default";

/// Parse the container-level `#[tool(...)]` attributes.
///
/// Walks every `tool` attribute on the struct with syn's nested-meta
/// parser, so diagnostics carry the offending attribute's span. Later
/// attributes win for repeated keys.
///
/// # Errors
///
/// Returns a spanned error for malformed or unknown attributes.
pub(crate) fn parse_container(attrs: &[Attribute]) -> syn::Result<ContainerAttrs> {
    let mut out = ContainerAttrs::default();
    for attr in attrs.iter().filter(|a| a.path().is_ident("tool")) {
        attr.parse_nested_meta(|meta| {
            if meta.path.is_ident("name") {
                out.name = Some(string_value(&meta)?);
            } else if meta.path.is_ident("description") {
                out.description = Some(string_value(&meta)?);
            } else if meta.path.is_ident("system_prompt") {
                out.system_prompt = Some(string_value(&meta)?);
            } else if meta.path.is_ident("handler") {
                out.handler = Some(string_value(&meta)?);
            } else if meta.path.is_ident("read_only") {
                out.read_only = true;
            } else if meta.path.is_ident("concurrency_safe") {
                out.concurrency_safe = true;
            } else if meta.path.is_ident("allow_extra") {
                out.allow_extra = true;
            } else {
                return Err(meta.error(format!(
                    "unknown `tool` attribute; expected one of: {CONTAINER_KEYS}"
                )));
            }
            Ok(())
        })?;
    }
    Ok(out)
}

/// Parse the field-level `#[tool(...)]` attributes.
///
/// Same nested-meta walk as
/// [`parse_container`](fn@parse_container), over one field's
/// attributes.
///
/// # Errors
///
/// Returns a spanned error for malformed or unknown attributes.
pub(crate) fn parse_field(attrs: &[Attribute]) -> syn::Result<FieldAttrs> {
    let mut out = FieldAttrs::default();
    for attr in attrs.iter().filter(|a| a.path().is_ident("tool")) {
        attr.parse_nested_meta(|meta| {
            if meta.path.is_ident("name") {
                out.name = Some(string_value(&meta)?);
            } else if meta.path.is_ident("description") {
                out.description = Some(string_value(&meta)?);
            } else if meta.path.is_ident("skip") {
                out.skip = true;
            } else if meta.path.is_ident("default") {
                out.default = true;
            } else {
                return Err(meta.error(format!(
                    "unknown `tool` attribute; expected one of: {FIELD_KEYS}"
                )));
            }
            Ok(())
        })?;
    }
    Ok(out)
}

/// Read a `key = "value"` string from a nested meta item.
///
/// Used by both parsers for every value-shaped attribute; rejects
/// non-string-literal values with the value's span.
///
/// # Errors
///
/// Returns a spanned error when the value is not a string literal.
fn string_value(meta: &syn::meta::ParseNestedMeta<'_>) -> syn::Result<String> {
    let value = meta.value()?;
    let lit: LitStr = value.parse()?;
    Ok(lit.value())
}

/// The `///` doc comment text of an item, joined across lines, if any.
///
/// Each line is trimmed and the lines are joined with single spaces,
/// so a multi-line `///` paragraph reads as one sentence chain in the
/// generated description.
pub(crate) fn doc_string(attrs: &[Attribute]) -> Option<String> {
    let mut lines = Vec::new();
    for attr in attrs.iter().filter(|a| a.path().is_ident("doc")) {
        if let Meta::NameValue(nv) = &attr.meta
            && let Expr::Lit(expr) = &nv.value
            && let Lit::Str(s) = &expr.lit
        {
            lines.push(s.value().trim().to_string());
        }
    }
    if lines.is_empty() {
        None
    } else {
        Some(lines.join(" "))
    }
}

/// Whether the field carries a `#[serde(default)]`-shaped attribute.
///
/// The schema-side condition for `#[tool(skip)]` validity and for
/// omitting a field from `required`: a field the runtime accepts
/// without is not truly required. Matches the `default` key whether
/// it is a bare flag or `default = "path"`.
pub(crate) fn has_serde_default(attrs: &[Attribute]) -> bool {
    let mut found = false;
    for attr in attrs.iter().filter(|a| a.path().is_ident("serde")) {
        let _ = attr.parse_nested_meta(|meta| {
            if meta.path.is_ident("default") {
                found = true;
            }
            Ok(())
        });
    }
    found
}

/// The `#[serde(rename = "…")]` value on a field, if any.
///
/// The schema mirrors serde's rename for deserialization consistency —
/// a mismatch between the schema's property name and the key serde
/// looks for would make the schema lie about what the model should
/// send.
pub(crate) fn serde_rename(attrs: &[Attribute]) -> Option<String> {
    let mut plain = None;
    let mut deserialize = None;
    for attr in attrs.iter().filter(|a| a.path().is_ident("serde")) {
        let Ok(list) = attr
            .parse_args_with(syn::punctuated::Punctuated::<Meta, syn::Token![,]>::parse_terminated)
        else {
            continue;
        };
        for meta in &list {
            match meta {
                Meta::NameValue(nv) if nv.path.is_ident("rename") => {
                    if let Expr::Lit(expr) = &nv.value
                        && let Lit::Str(lit) = &expr.lit
                    {
                        plain = Some(lit.value());
                    }
                }
                Meta::List(ml) if ml.path.is_ident("rename") => {
                    let Ok(inner) = syn::parse::Parser::parse2(
                        &syn::punctuated::Punctuated::<Meta, syn::Token![,]>::parse_terminated,
                        ml.tokens.clone(),
                    ) else {
                        continue;
                    };
                    for meta in &inner {
                        if let Meta::NameValue(nv) = meta
                            && nv.path.is_ident("deserialize")
                            && let Expr::Lit(expr) = &nv.value
                            && let Lit::Str(lit) = &expr.lit
                        {
                            deserialize = Some(lit.value());
                        }
                    }
                }
                _ => {}
            }
        }
    }
    deserialize.or(plain)
}

/// The `#[serde(rename_all = "…")]` strategy on the struct, if any.
///
/// Applied to each field's Rust name to derive its JSON property name,
/// exactly as serde deserializes it.
pub(crate) fn serde_rename_all(attrs: &[Attribute]) -> Option<RenameAll> {
    let mut out = None;
    for attr in attrs.iter().filter(|a| a.path().is_ident("serde")) {
        let _ = attr.parse_nested_meta(|meta| {
            if meta.path.is_ident("rename_all")
                && let Ok(lit) = meta.value()?.parse::<LitStr>()
            {
                out = RenameAll::from_str(&lit.value());
            }
            Ok(())
        });
    }
    out
}

/// The `#[serde(rename_all = "…")]` casing strategies.
#[derive(Debug, Clone, Copy)]
pub(crate) enum RenameAll {
    /// The `lowercase` strategy — field names as-is but all lowercase.
    Lower,
    /// The `UPPERCASE` strategy — field names uppercased.
    Upper,
    /// The `PascalCase` strategy — each word capitalized, no separators.
    Pascal,
    /// The `camelCase` strategy — first word lowercase, rest capitalized.
    Camel,
    /// The `snake_case` strategy — underscore-separated lowercase words.
    Snake,
    /// The `SCREAMING_SNAKE_CASE` strategy — underscore-separated uppercase.
    ScreamingSnake,
    /// The `kebab-case` strategy — hyphen-separated lowercase words.
    Kebab,
    /// The `SCREAMING-KEBAB-CASE` strategy — hyphen-separated uppercase.
    ScreamingKebab,
}

impl RenameAll {
    /// Parse the serde casing name into the strategy.
    ///
    /// Returns `None` for unrecognized names (serde itself errors in
    /// that case; the derive then ignores the attribute).
    pub(crate) fn from_str(s: &str) -> Option<Self> {
        match s {
            "lowercase" => Some(Self::Lower),
            "UPPERCASE" => Some(Self::Upper),
            "PascalCase" => Some(Self::Pascal),
            "camelCase" => Some(Self::Camel),
            "snake_case" => Some(Self::Snake),
            "SCREAMING_SNAKE_CASE" => Some(Self::ScreamingSnake),
            "kebab-case" => Some(Self::Kebab),
            "SCREAMING_KEBAB_CASE" => Some(Self::ScreamingKebab),
            _ => None,
        }
    }

    /// Apply the strategy to a field name.
    ///
    /// The input is the Rust field identifier; the output is the JSON
    /// property name serde will look for during deserialization.
    pub(crate) fn apply(self, name: &str) -> String {
        match self {
            Self::Lower => name.to_lowercase(),
            Self::Upper => name.to_uppercase(),
            Self::Pascal => to_pascal_case(name),
            Self::Camel => {
                let pascal = to_pascal_case(name);
                let mut chars = pascal.chars();
                match chars.next() {
                    Some(first) => first.to_lowercase().collect::<String>() + chars.as_str(),
                    None => String::new(),
                }
            }
            Self::Snake => serde_snake_case(name),
            Self::ScreamingSnake => serde_snake_case(name).to_uppercase(),
            Self::Kebab => serde_snake_case(name).replace('_', "-"),
            Self::ScreamingKebab => serde_snake_case(name).replace('_', "-").to_uppercase(),
        }
    }
}

/// `PascalCase` from a `snake_case` or `camelCase` input.
///
/// Splits on underscores, capitalizes each word's first letter, and
/// joins without separators. Empty segments (from leading/trailing
/// underscores) are dropped.
fn to_pascal_case(name: &str) -> String {
    name.split('_')
        .filter(|s| !s.is_empty())
        .map(|word| {
            let mut chars = word.chars();
            match chars.next() {
                Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
                None => String::new(),
            }
        })
        .collect()
}

/// `snake_case` matching serde's field-rename behavior.
///
/// An underscore is inserted before an uppercase character only when
/// the previous character is lowercase or a digit — consecutive
/// uppercase (an acronym like `ID` in `userID`) stays together:
/// `userID` becomes `user_id`, not `user_i_d`.
fn serde_snake_case(name: &str) -> String {
    let chars: Vec<char> = name.chars().collect();
    let mut out = String::new();
    for (i, &ch) in chars.iter().enumerate() {
        if ch.is_uppercase() {
            let prev_lower = i > 0
                && chars
                    .get(i.wrapping_sub(1))
                    .is_some_and(|c| c.is_lowercase() || c.is_numeric());
            let next_lower = chars
                .get(i.wrapping_add(1))
                .is_some_and(|c| c.is_lowercase());
            // Insert before an uppercase that starts a word —
            // after lowercase/digit, or at an acronym-to-word boundary.
            if prev_lower || (i > 0 && next_lower) {
                out.push('_');
            }
            out.extend(ch.to_lowercase());
        } else {
            out.push(ch);
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn rename_all_covers_the_full_serde_strategy_set() {
        let cases: Vec<(&str, &str, &str)> = vec![
            ("lowercase", "FileName", "filename"),
            ("UPPERCASE", "FileName", "FILENAME"),
            ("PascalCase", "file_name", "FileName"),
            ("camelCase", "file_name", "fileName"),
            ("snake_case", "FileName", "file_name"),
            ("SCREAMING_SNAKE_CASE", "FileName", "FILE_NAME"),
            ("kebab-case", "file_name", "file-name"),
            ("SCREAMING_KEBAB_CASE", "file_name", "FILE-NAME"),
        ];
        for (name, input, expected) in cases {
            let strategy =
                RenameAll::from_str(name).unwrap_or_else(|| panic!("unknown strategy: {name}"));
            assert_eq!(
                strategy.apply(input),
                expected,
                "strategy {name:?} on {input:?}"
            );
        }
    }

    #[test]
    fn snake_case_preserves_consecutive_uppercase() {
        assert_eq!(
            RenameAll::from_str("snake_case").unwrap().apply("userID"),
            "user_id"
        );
        assert_eq!(
            RenameAll::from_str("snake_case")
                .unwrap()
                .apply("parseHTTPResponse"),
            "parse_http_response"
        );
        assert_eq!(
            RenameAll::from_str("snake_case").unwrap().apply("htmlID"),
            "html_id"
        );
    }

    #[test]
    fn serde_rename_deserialize_form_is_preferred() {
        use syn::parse_quote;
        let attr: Attribute = parse_quote! {
            #[serde(rename(deserialize = "from_wire", serialize = "to_wire"))]
        };
        assert_eq!(
            serde_rename(&[attr]),
            Some("from_wire".to_string()),
            "the deserialize half wins over the serialize half"
        );
        let attr: Attribute = parse_quote! {
            #[serde(rename = "simple")]
        };
        assert_eq!(serde_rename(&[attr]), Some("simple".to_string()));
    }

    #[test]
    fn rename_all_from_str_rejects_unknown_names() {
        assert!(RenameAll::from_str("NonsenseCase").is_none());
        assert!(RenameAll::from_str("").is_none());
    }
}