gpui-form-derive 0.7.0

Macro crate for gpui-form
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
use component_shape_codegen::doc_description;
use darling::{Error as DarlingError, FromField};
use gpui_form_codegen::components::ShapeOptions;
use proc_macro2::Span;
use strum::IntoStaticStr;
use syn::{parse::Parser as _, punctuated::Punctuated};

use crate::derives::gpui_form::attrs::{
    EmptyForm, GpuiFormFieldOption, McpToolOptions, NoInventory,
};
use crate::derives::gpui_form::ir::{
    DefaultExpr, FieldAttrContext, FieldContext, FieldMetadata, RenderedFieldIntent,
    RenderedValueIntent, Spanned,
};
use crate::derives::gpui_form::validation::KorumaField;

#[derive(Debug)]
pub struct ComponentField {
    pub context: FieldContext,
    attr: FieldAttr,
    metadata: FieldMetadata,
}

#[derive(Debug)]
struct ComponentFieldOptions {
    component: ShapeOptions,
    rendered: Box<RenderedFieldIntent>,
    context: FieldAttrContext,
}

#[derive(Debug)]
enum FieldAttr {
    Component(Box<ComponentFieldOptions>),
    Hidden {
        rendered: Box<RenderedFieldIntent>,
        context: FieldAttrContext,
    },
    Skipped,
}

impl FieldAttr {
    const fn option_key(&self) -> FieldOptionKey {
        match self {
            Self::Component(_) => FieldOptionKey::Component,
            Self::Hidden { .. } => FieldOptionKey::Hidden,
            Self::Skipped => FieldOptionKey::Skip,
        }
    }
}

#[derive(Debug)]
struct ParsedComponentField {
    context: FieldContext,
    attr: Option<FieldAttr>,
    metadata: FieldMetadata,
    explicit_description: bool,
}

#[derive(Clone, Copy, Debug, Eq, IntoStaticStr, PartialEq)]
#[strum(serialize_all = "snake_case", const_into_str)]
enum FieldOptionKey {
    Component,
    Hidden,
    Skip,
}

impl FieldOptionKey {
    const fn label(self) -> &'static str {
        self.into_str()
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum FieldOptionConflict {
    Duplicate(FieldOptionKey),
    Intent {
        first: FieldOptionKey,
        second: FieldOptionKey,
    },
    SkipWith(FieldOptionKey),
}

fn field_option_conflict(
    existing: FieldOptionKey,
    incoming: FieldOptionKey,
) -> Option<FieldOptionConflict> {
    if existing == incoming {
        return Some(FieldOptionConflict::Duplicate(incoming));
    }

    match (existing, incoming) {
        (FieldOptionKey::Skip, other) | (other, FieldOptionKey::Skip) => {
            Some(FieldOptionConflict::SkipWith(other))
        },
        (FieldOptionKey::Component, FieldOptionKey::Hidden)
        | (FieldOptionKey::Hidden, FieldOptionKey::Component) => {
            Some(FieldOptionConflict::Intent {
                first: existing,
                second: incoming,
            })
        },
        _ => None,
    }
}

pub struct SkippedField;

pub struct RenderedField<'a> {
    pub value: &'a RenderedValueIntent,
    pub default: Option<&'a Spanned<DefaultExpr>>,
    pub context: &'a FieldAttrContext,
}

pub struct ComponentRenderedField<'a> {
    pub rendered: RenderedField<'a>,
    pub component: &'a ShapeOptions,
}

pub enum ComponentFieldIntent<'a> {
    Skipped(SkippedField),
    Hidden(RenderedField<'a>),
    Component(ComponentRenderedField<'a>),
}

impl ComponentField {
    pub fn metadata(&self) -> &FieldMetadata {
        &self.metadata
    }

    pub fn intent(&self) -> ComponentFieldIntent<'_> {
        match &self.attr {
            FieldAttr::Component(component) => {
                ComponentFieldIntent::Component(ComponentRenderedField {
                    rendered: RenderedField {
                        value: &component.rendered.value,
                        default: component.rendered.default.as_ref(),
                        context: &component.context,
                    },
                    component: &component.component,
                })
            },
            FieldAttr::Hidden { rendered, context } => {
                ComponentFieldIntent::Hidden(RenderedField {
                    value: &rendered.value,
                    default: rendered.default.as_ref(),
                    context,
                })
            },
            FieldAttr::Skipped => ComponentFieldIntent::Skipped(SkippedField),
        }
    }

    pub fn rendered(&self) -> Option<RenderedField<'_>> {
        match self.intent() {
            ComponentFieldIntent::Skipped(_) => None,
            ComponentFieldIntent::Hidden(rendered) => Some(rendered),
            ComponentFieldIntent::Component(component) => Some(component.rendered),
        }
    }

    pub fn component(&self) -> Option<ComponentRenderedField<'_>> {
        match self.intent() {
            ComponentFieldIntent::Component(component) => Some(component),
            ComponentFieldIntent::Skipped(_) | ComponentFieldIntent::Hidden(_) => None,
        }
    }
}

impl FromField for ComponentField {
    fn from_field(field: &syn::Field) -> darling::Result<Self> {
        let ident = field.ident.clone().ok_or_else(|| {
            DarlingError::custom("GpuiForm only supports named struct fields").with_span(field)
        })?;
        let mut parsed = ParsedComponentField {
            context: FieldContext::new(ident, field.ty.clone(), syn::spanned::Spanned::span(field)),
            attr: None,
            metadata: FieldMetadata {
                label: None,
                description: doc_description(&field.attrs),
                examples: Vec::new(),
            },
            explicit_description: false,
        };
        let mut errors = DarlingError::accumulator();
        let mut had_attribute_errors = false;

        for attr in &field.attrs {
            if !attr.path().is_ident("gpui_form") {
                continue;
            }

            let list = match attr.meta.require_list().map_err(|_| {
                DarlingError::custom(
                    "`gpui_form` field attribute must be a list, for example \
                     `#[gpui_form(component(my::Shape))]`",
                )
                .with_span(attr)
            }) {
                Ok(list) => list,
                Err(error) => {
                    errors.push(error);
                    had_attribute_errors = true;
                    continue;
                },
            };

            let items = match Punctuated::<GpuiFormFieldOption, syn::Token![,]>::parse_terminated
                .parse2(list.tokens.clone())
                .map_err(DarlingError::from)
            {
                Ok(items) => items,
                Err(error) => {
                    errors.push(error);
                    had_attribute_errors = true;
                    continue;
                },
            };

            let attr_span = syn::spanned::Spanned::span(attr);
            for item in items {
                if errors
                    .handle(parse_gpui_form_item(&mut parsed, item, attr_span))
                    .is_none()
                {
                    had_attribute_errors = true;
                }
            }
        }

        let attr = if !had_attribute_errors {
            match validate_field_intent(&parsed) {
                Ok(()) => parsed.attr,
                Err(error) => {
                    errors.push(error);
                    None
                },
            }
        } else {
            parsed.attr
        };

        match attr {
            Some(attr) => errors.finish_with(ComponentField {
                context: parsed.context,
                attr,
                metadata: parsed.metadata,
            }),
            None => errors.finish_with(ComponentField {
                context: parsed.context,
                attr: FieldAttr::Skipped,
                metadata: parsed.metadata,
            }),
        }
    }
}

fn parse_gpui_form_item(
    field: &mut ParsedComponentField,
    item: GpuiFormFieldOption,
    attr_span: Span,
) -> darling::Result<()> {
    match item {
        GpuiFormFieldOption::Label { span, value } => {
            assign_field_metadata_once("label", &mut field.metadata.label, value, span)
        },
        GpuiFormFieldOption::Description { span, value } => {
            if field.explicit_description {
                return Err(DarlingError::from(syn::Error::new(
                    span,
                    "duplicate gpui_form field metadata `description`",
                )));
            }
            field.metadata.description = Some(value);
            field.explicit_description = true;
            Ok(())
        },
        GpuiFormFieldOption::Example { value, .. } => {
            field.metadata.examples.push(value);
            Ok(())
        },
        GpuiFormFieldOption::Skip { span } => set_attr(field, FieldAttr::Skipped, span),
        GpuiFormFieldOption::Hidden { span, options } => {
            let context = FieldAttrContext::new(attr_span, span);
            set_attr(
                field,
                FieldAttr::Hidden {
                    rendered: options,
                    context,
                },
                span,
            )
        },
        GpuiFormFieldOption::Component {
            span,
            shape,
            options,
        } => {
            let context = FieldAttrContext::new(attr_span, span);
            let component =
                ShapeOptions::from_constructor_expr_with_span(*shape, context.option_span)
                    .map_err(DarlingError::from)?;
            set_attr(
                field,
                FieldAttr::Component(Box::new(ComponentFieldOptions {
                    component,
                    rendered: options,
                    context,
                })),
                span,
            )
        },
    }
}

fn assign_field_metadata_once(
    label: &str,
    slot: &mut Option<String>,
    value: String,
    span: Span,
) -> darling::Result<()> {
    if slot.is_some() {
        return Err(DarlingError::from(syn::Error::new(
            span,
            format!("duplicate gpui_form field metadata `{label}`"),
        )));
    }
    *slot = Some(value);
    Ok(())
}

fn set_attr(
    field: &mut ParsedComponentField,
    incoming_attr: FieldAttr,
    span: Span,
) -> darling::Result<()> {
    let incoming = incoming_attr.option_key();
    if let Some(existing) = field.attr.as_ref().map(FieldAttr::option_key)
        && let Some(conflict) = field_option_conflict(existing, incoming)
    {
        return Err(DarlingError::from(syn::Error::new(
            span,
            field_conflict_message(conflict),
        )));
    }

    field.attr = Some(incoming_attr);
    Ok(())
}

fn field_conflict_message(conflict: FieldOptionConflict) -> String {
    match conflict {
        FieldOptionConflict::Duplicate(key) => {
            let key = key.label();
            format!(
                "duplicate `{key}` option in `gpui_form` field attribute; remove the duplicate `{key}` entry"
            )
        },
        FieldOptionConflict::Intent { first, second } => {
            let first = first.label();
            let second = second.label();
            format!(
                "`{first}` cannot be combined with `{second}` in a `gpui_form` field attribute; \
                 choose exactly one of component, hidden, or skip"
            )
        },
        FieldOptionConflict::SkipWith(option) => {
            let option = option.label();
            format!(
                "`skip` cannot be combined with `{option}` in a `gpui_form` field attribute; \
                 remove `skip` or remove the `{option}` option"
            )
        },
    }
}

fn validate_field_intent(field: &ParsedComponentField) -> darling::Result<()> {
    if field.attr.is_none() {
        return Err(DarlingError::from(syn::Error::new(
            field.context.field_span,
            format!(
                "field `{}` must choose a gpui_form field intent; add `component(...)`, `hidden`, or `skip`",
                field.context.field_ident
            ),
        )));
    };

    Ok(())
}

#[derive(Debug, darling::FromDeriveInput)]
#[darling(attributes(gpui_form), supports(struct_named, struct_unit))]
pub struct ComponentStruct {
    pub data: darling::ast::Data<(), ComponentField>,
    #[darling(default)]
    pub empty: Option<EmptyForm>,
    #[darling(default)]
    pub no_inventory: Option<NoInventory>,
    #[darling(default)]
    pub koruma: Option<KorumaField>,
    #[darling(default)]
    pub mcp: Option<McpToolOptions>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use quote::ToTokens as _;

    #[test]
    fn parsed_component_field_uses_typed_converted_value_intent() {
        let field: syn::Field = syn::parse_quote! {
            #[gpui_form(component(
                crate::Input,
                value(
                    type = String,
                    from_source = to_form,
                    into_source = to_source,
                )
            ))]
            value: u64
        };

        let parsed = ComponentField::from_field(&field).expect("field should parse");
        let ComponentFieldIntent::Component(component) = parsed.intent() else {
            panic!("expected component field intent");
        };
        let RenderedValueIntent::Converted(converted) = component.rendered.value else {
            panic!("expected converted value intent");
        };

        assert_eq!(
            converted.form_type.value.0.to_token_stream().to_string(),
            "String"
        );
        assert_eq!(
            converted.from_source.value.to_token_stream().to_string(),
            "to_form"
        );
        assert_eq!(
            converted.into_source.value.to_token_stream().to_string(),
            "to_source"
        );
    }

    #[test]
    fn parsed_value_intent_rejects_incomplete_conversion_pair() {
        let field: syn::Field = syn::parse_quote! {
            #[gpui_form(component(
                crate::Input,
                value(type = String, from_source = to_form)
            ))]
            value: u64
        };

        let error = ComponentField::from_field(&field).expect_err("field should fail");

        assert!(
            error.to_string().contains(
                "requires an explicit `into_source = ...` or `try_into_source = ...` conversion"
            ),
            "unexpected error: {error}"
        );
    }
}