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
use gpui_form_codegen::components::{
    ComponentFieldIr, ComponentShapeStoragePolicy, ResolvedComponentShape,
};
use koruma_derive_core::{FieldInfo as KorumaFieldInfo, ParsedValidatorUse};
use proc_macro2::Span;
use syn::{Expr, Ident, Path, Type};

#[derive(Clone, Debug)]
pub struct Spanned<T> {
    pub value: T,
    pub span: Span,
}

impl<T> Spanned<T> {
    pub fn new<S: syn::spanned::Spanned>(value: T, span: &S) -> Self {
        Self {
            value,
            span: span.span(),
        }
    }
}

#[derive(Clone, Debug)]
pub struct FieldAttrContext {
    pub attr_span: Span,
    pub option_span: Span,
}

impl FieldAttrContext {
    pub fn new(attr_span: Span, option_span: Span) -> Self {
        Self {
            attr_span,
            option_span,
        }
    }
}

#[derive(Clone, Debug)]
pub struct DeriveContext {
    pub original_ident: Ident,
    pub paths: gpui_form_codegen::CratePaths,
}

impl DeriveContext {
    pub fn new(original_ident: Ident, paths: gpui_form_codegen::CratePaths) -> Self {
        Self {
            original_ident,
            paths,
        }
    }
}

#[derive(Clone, Debug)]
pub struct FieldContext {
    pub field_ident: Ident,
    pub field_ty: Type,
    pub field_span: Span,
}

impl FieldContext {
    pub fn new(field_ident: Ident, field_ty: Type, field_span: Span) -> Self {
        Self {
            field_ident,
            field_ty,
            field_span,
        }
    }
}

#[derive(Clone, Debug, Default)]
pub struct FieldMetadata {
    pub label: Option<String>,
    pub description: Option<String>,
    pub examples: Vec<String>,
}

#[derive(Clone, Debug)]
pub struct TypeOverride(pub Type);

#[derive(Clone, Debug)]
pub struct DefaultExpr(pub Expr);

#[derive(Clone, Debug)]
pub struct ConvertedValueIntent {
    pub form_type: Spanned<TypeOverride>,
    pub from_source: Spanned<Expr>,
    pub into_source: Spanned<Expr>,
    pub into_source_is_fallible: bool,
}

#[derive(Clone, Debug)]
pub enum RenderedValueIntent {
    Identity,
    Converted(Box<ConvertedValueIntent>),
    KorumaNewtype { span: Span },
}

impl RenderedValueIntent {
    pub fn source_to_form(&self) -> Option<&Spanned<Expr>> {
        match self {
            Self::Identity => None,
            Self::Converted(converted) => Some(&converted.from_source),
            Self::KorumaNewtype { .. } => None,
        }
    }

    pub fn form_to_source(&self) -> Option<&Spanned<Expr>> {
        match self {
            Self::Identity => None,
            Self::Converted(converted) => Some(&converted.into_source),
            Self::KorumaNewtype { .. } => None,
        }
    }

    pub fn form_to_source_is_fallible(&self) -> bool {
        match self {
            Self::Identity | Self::KorumaNewtype { .. } => false,
            Self::Converted(converted) => converted.into_source_is_fallible,
        }
    }
}

#[derive(Clone, Debug)]
pub struct RenderedFieldIntent {
    pub value: RenderedValueIntent,
    pub default: Option<Spanned<DefaultExpr>>,
}

impl Default for RenderedFieldIntent {
    fn default() -> Self {
        Self {
            value: RenderedValueIntent::Identity,
            default: None,
        }
    }
}

/// Value-holder storage selected during derive planning.
#[derive(Clone, Debug)]
pub enum HolderStoragePlan {
    OriginallyOptional,
    Direct,
    ShapePolicy { shape: Path },
}

impl HolderStoragePlan {
    pub fn from_non_component_field(was_optional: bool) -> Self {
        if was_optional {
            Self::OriginallyOptional
        } else {
            Self::Direct
        }
    }

    pub fn from_component_shape_storage_policy(
        was_optional: bool,
        storage_policy: ComponentShapeStoragePolicy,
    ) -> Self {
        if was_optional {
            Self::OriginallyOptional
        } else {
            Self::ShapePolicy {
                shape: storage_policy.shape().clone(),
            }
        }
    }

    pub fn shape_policy(&self) -> Option<&Path> {
        match self {
            Self::ShapePolicy { shape } => Some(shape),
            Self::OriginallyOptional | Self::Direct => None,
        }
    }

    pub fn is_shape_policy(&self) -> bool {
        self.shape_policy().is_some()
    }
}

#[derive(Clone, Debug)]
pub enum ValidationRule {
    Validator(String),
    Required,
    Newtype,
    Nested,
}

impl ValidationRule {
    pub fn is_required(&self) -> bool {
        matches!(self, Self::Required)
    }
}

#[derive(Clone, Debug, Default)]
pub struct ValidationMetadata {
    rules: Vec<ValidationRule>,
}

impl ValidationMetadata {
    pub fn push(&mut self, rule: ValidationRule) {
        self.rules.push(rule);
    }

    pub fn has_required(&self) -> bool {
        self.rules.iter().any(ValidationRule::is_required)
    }

    pub fn iter(&self) -> impl Iterator<Item = &ValidationRule> {
        self.rules.iter()
    }
}

#[derive(Clone, Debug, Default)]
pub struct KorumaValidationInfo {
    pub field_validators: Vec<ParsedValidatorUse>,
    pub element_validators: Vec<ParsedValidatorUse>,
    pub is_newtype: bool,
    pub is_nested: bool,
}

impl From<&KorumaFieldInfo> for KorumaValidationInfo {
    fn from(info: &KorumaFieldInfo) -> Self {
        Self {
            field_validators: info.field_validators().to_vec(),
            element_validators: info.element_validators().to_vec(),
            is_newtype: info.is_newtype(),
            is_nested: info.is_nested(),
        }
    }
}

#[derive(Clone, Debug)]
pub struct HolderFieldIr {
    pub field_name: Ident,
    #[allow(dead_code)]
    pub original_type: Type,
    #[allow(dead_code)]
    pub source_value_type: Type,
    pub form_type: Type,
    pub was_optional: bool,
    pub storage: HolderStoragePlan,
    pub validation: KorumaValidationInfo,
    pub validation_metadata: ValidationMetadata,
    pub metadata: FieldMetadata,
    pub default_expr: Option<Expr>,
    pub default_span: Option<Span>,
    pub value_mapping: RenderedValueIntent,
    pub context: FieldAttrContext,
}

impl HolderFieldIr {
    pub fn field_name(&self) -> &Ident {
        &self.field_name
    }

    pub fn original_type(&self) -> &Type {
        &self.original_type
    }

    pub fn form_type(&self) -> &Type {
        &self.form_type
    }

    pub fn storage(&self) -> &HolderStoragePlan {
        &self.storage
    }

    pub fn validation(&self) -> &KorumaValidationInfo {
        &self.validation
    }

    pub fn default_expr(&self) -> Option<&Expr> {
        self.default_expr.as_ref()
    }

    pub fn default_expr_span(&self) -> Span {
        self.default_span.unwrap_or(self.context.attr_span)
    }

    pub fn source_to_form_expr(&self) -> Option<&Expr> {
        self.value_mapping
            .source_to_form()
            .map(|from_source| &from_source.value)
    }

    pub fn source_to_form_span(&self) -> Span {
        self.value_mapping
            .source_to_form()
            .map(|from_source| from_source.span)
            .unwrap_or(self.context.option_span)
    }

    pub fn form_to_source_expr(&self) -> Option<&Expr> {
        self.value_mapping
            .form_to_source()
            .map(|into_source| &into_source.value)
    }

    pub fn form_to_source_span(&self) -> Span {
        self.value_mapping
            .form_to_source()
            .map(|into_source| into_source.span)
            .unwrap_or(self.context.option_span)
    }

    pub fn form_to_source_is_fallible(&self) -> bool {
        self.value_mapping.form_to_source_is_fallible()
    }

    /// Returns true if this rendered field needs the `RequiredValidation`
    /// koruma validator.
    pub fn needs_required_validation(&self) -> bool {
        matches!(self.storage, HolderStoragePlan::ShapePolicy { .. })
            && !self.was_optional
            && !self.validation.is_nested
    }
}

#[derive(Clone, Debug)]
pub struct SkippedFieldPlan {
    pub field_name: Ident,
    pub original_type: Type,
}

#[derive(Clone, Debug)]
pub struct HiddenFieldPlan {
    pub shared: HolderFieldIr,
}

#[derive(Clone, Debug)]
pub struct ComponentFieldPlan {
    pub shared: HolderFieldIr,
    pub component: ComponentFieldIr,
}

/// Precomputed field facts shared by expansion, inventory, and value holders.
#[derive(Clone, Debug)]
pub enum FieldPlan {
    Skipped(Box<SkippedFieldPlan>),
    Hidden(Box<HiddenFieldPlan>),
    Component(Box<ComponentFieldPlan>),
}

impl FieldPlan {
    pub fn skipped(field_name: Ident, original_type: Type) -> Self {
        Self::Skipped(Box::new(SkippedFieldPlan {
            field_name,
            original_type,
        }))
    }

    pub fn hidden(shared: HolderFieldIr) -> Self {
        Self::Hidden(Box::new(HiddenFieldPlan { shared }))
    }

    pub fn component_field(shared: HolderFieldIr, component: ComponentFieldIr) -> Self {
        Self::Component(Box::new(ComponentFieldPlan { shared, component }))
    }

    pub fn shared(&self) -> Option<&HolderFieldIr> {
        match self {
            Self::Skipped(_) => None,
            Self::Hidden(plan) => Some(&plan.shared),
            Self::Component(plan) => Some(&plan.shared),
        }
    }

    pub fn is_skipped(&self) -> bool {
        matches!(self, Self::Skipped(_))
    }

    pub fn field_name(&self) -> &Ident {
        match self {
            Self::Skipped(plan) => &plan.field_name,
            Self::Hidden(plan) => &plan.shared.field_name,
            Self::Component(plan) => &plan.shared.field_name,
        }
    }

    pub fn component(&self) -> Option<&ResolvedComponentShape> {
        match self {
            Self::Component(plan) => Some(&plan.component.shape),
            Self::Skipped(_) | Self::Hidden(_) => None,
        }
    }

    pub fn component_plan(&self) -> Option<&ComponentFieldPlan> {
        match self {
            Self::Component(plan) => Some(plan.as_ref()),
            Self::Skipped(_) | Self::Hidden(_) => None,
        }
    }

    /// Returns true if this field needs the `RequiredValidation` koruma validator.
    /// This applies to fields that:
    /// - Can be missing in the form holder
    /// - Must be present in the source struct
    /// - Are not nested structs (nested fields have their own validation)
    pub fn needs_required_validation(&self) -> bool {
        let Some(shared) = self.shared() else {
            return false;
        };

        matches!(shared.storage, HolderStoragePlan::ShapePolicy { .. })
            && !shared.was_optional
            && !shared.validation.is_nested
    }
}