oxblade 0.1.0

Blade templates for Laravel for Rust: Blade's markup and directives, Laravel's helpers, Rust's expressions. Community package, not affiliated with Laravel.
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
use std::{
    any::{Any, TypeId},
    cell::{OnceCell, RefCell},
    collections::HashMap,
    rc::Rc,
    sync::Arc,
};

use serde::{Serialize, de::DeserializeOwned};

use crate::{
    attributes::AttributeBag,
    error::{Error, ErrorKind, Result},
    library::fault,
    shape::{Direction, Shape, TypeDesc, TypeRegistry},
    value::{Arg, Object, Value, ValueMap},
};

use super::{decode, snake_case};

type Constructor =
    for<'a> fn(ValueMap<'a>, &ComponentServices) -> Result<Option<Box<dyn ComponentInstance>>>;

/// Constructor and view name for a registered class component.
#[derive(Clone, Copy)]
pub struct ComponentRegistration {
    /// Tag name without the `x-` prefix.
    pub name: &'static str,
    #[doc(hidden)]
    pub fields: fn(&mut TypeRegistry) -> TypeDesc,
    #[doc(hidden)]
    pub construct: Constructor,
}

#[derive(Clone)]
pub(crate) struct RegisteredComponent {
    pub(crate) registration: ComponentRegistration,
    schema: Arc<ComponentSchema>,
}

struct ComponentSchema {
    types: TypeRegistry,
    shape: TypeDesc,
}

impl RegisteredComponent {
    pub(crate) fn new(registration: ComponentRegistration) -> Self {
        let mut types = TypeRegistry::default();
        let shape = (registration.fields)(&mut types);
        Self {
            registration,
            schema: Arc::new(ComponentSchema { types, shape }),
        }
    }
}

inventory::collect!(ComponentRegistration);

/// Iterates over class components linked into the application.
pub fn components() -> impl Iterator<Item = ComponentRegistration> {
    inventory::iter::<ComponentRegistration>
        .into_iter()
        .copied()
}

/// Already-built services made available to Rust component constructors.
#[derive(Default)]
pub struct ComponentServices(HashMap<TypeId, Arc<dyn Any + Send + Sync>>);

impl ComponentServices {
    pub(crate) fn insert<T: Send + Sync + 'static>(&mut self, service: T) {
        self.0.insert(TypeId::of::<T>(), Arc::new(service));
    }

    /// Clones a value registered under its concrete Rust type.
    pub fn get<T: Clone + Send + Sync + 'static>(&self) -> Result<T> {
        self.0
            .get(&TypeId::of::<T>())
            .and_then(|value| value.downcast_ref::<T>())
            .cloned()
            .ok_or_else(|| {
                fault(format!(
                    "no component service registered for `{}`",
                    std::any::type_name::<T>()
                ))
            })
    }
}

/// Data available after the caller's slots have rendered.
pub struct ComponentContext<'cx, 'a> {
    attributes: &'cx AttributeBag,
    data: &'cx ValueMap<'a>,
    services: &'cx ComponentServices,
}

impl<'cx, 'a> ComponentContext<'cx, 'a> {
    pub(super) fn new(
        attributes: &'cx AttributeBag,
        data: &'cx ValueMap<'a>,
        services: &'cx ComponentServices,
    ) -> Self {
        Self {
            attributes,
            data,
            services,
        }
    }

    /// Extra attributes from the component tag.
    pub fn attributes(&self) -> &AttributeBag {
        self.attributes
    }

    /// Props, exposed methods, slots and attributes available to the view.
    pub fn data(&self) -> &ValueMap<'a> {
        self.data
    }

    /// Clones an already-built service registered under its type.
    pub fn service<T: Clone + Send + Sync + 'static>(&self) -> Result<T> {
        self.services.get()
    }

    /// Reads the rendered default and named slots.
    pub fn slots(&self) -> Slots<'cx, 'a> {
        Slots(self.data)
    }
}

/// Access to rendered component slots by name.
pub struct Slots<'cx, 'a>(&'cx ValueMap<'a>);

impl Slots<'_, '_> {
    /// Returns the rendered slot HTML, or an empty string if it was omitted.
    pub fn text(&self, name: &str) -> String {
        self.0
            .get(snake_case(name).as_ref())
            .and_then(|value| value.display().ok())
            .unwrap_or_default()
    }
}

/// Bounded buffer for direct-render components.
pub struct Output {
    text: String,
    limit: usize,
    overflow: bool,
}

impl Output {
    pub(super) fn new(limit: usize) -> Self {
        Self {
            text: String::new(),
            limit,
            overflow: false,
        }
    }

    /// Writes HTML already known to be safe.
    pub fn raw(&mut self, html: &str) -> Result<()> {
        if html.len() > self.limit - self.text.len() {
            self.overflow = true;
            return Err(Self::limit_error());
        }
        self.text.push_str(html);
        Ok(())
    }

    /// Escapes and writes a string.
    pub fn escaped(&mut self, text: &str) -> Result<()> {
        self.raw(&crate::encode::e(text))
    }

    pub(super) fn finish(self) -> Result<String> {
        if self.overflow {
            Err(Self::limit_error())
        } else {
            Ok(self.text)
        }
    }

    fn limit_error() -> Error {
        Error::new(ErrorKind::Limit, "render output limit exceeded", None)
    }
}

/// How a class component produces its HTML.
pub enum ComponentRender {
    /// A named view rendered with the component data.
    View(String),
    /// Blade source compiled and rendered with the component data.
    Template(&'static str),
    /// The output was written directly to the buffer.
    Direct,
}

/// Implementation hooks generated by `#[component]`.
///
/// Component instances and returned view data or method results must be safe to
/// drop even after a serialization error. Projection bounds Serde traversal.
/// Any work performed by application code itself must also use bounded stack space.
#[doc(hidden)]
pub trait ClassComponent: DeserializeOwned + Shape + 'static {
    fn inject(&mut self, _services: &ComponentServices) -> Result<()> {
        Ok(())
    }
    fn enabled(&self) -> bool {
        true
    }
    fn with_attributes(&mut self, _attributes: &mut AttributeBag) -> Result<()> {
        Ok(())
    }
    fn fields<'a>(&self) -> Result<ValueMap<'a>>;
    fn methods() -> &'static [&'static str] {
        &[]
    }
    fn call<'a>(&self, name: &str, _args: &[Value<'a>]) -> Result<Value<'a>> {
        Err(fault(format!("unknown component method `{name}`")))
    }
    fn view_data<'a>(&self, _cx: &ComponentContext<'_, '_>) -> Result<ValueMap<'a>> {
        Ok(ValueMap::new())
    }
    fn render(&self, cx: &ComponentContext<'_, '_>, out: &mut Output) -> Result<ComponentRender>;
}

/// Erased class component instance used by the renderer.
#[doc(hidden)]
pub trait ComponentInstance {
    fn receiver<'a>(&self, fields: ValueMap<'a>) -> Value<'a>
    where
        Self: 'a;
    fn data<'a>(&self) -> Result<ValueMap<'a>>
    where
        Self: 'a;
    fn with_attributes(&mut self, attributes: &mut AttributeBag) -> Result<()>;
    fn view_data<'a>(&self, cx: &ComponentContext<'_, '_>) -> Result<ValueMap<'a>>
    where
        Self: 'a;
    fn render(&self, cx: &ComponentContext<'_, '_>, out: &mut Output) -> Result<ComponentRender>;
}

/// Deserializes constructor props, injects registered services and checks visibility.
#[doc(hidden)]
pub fn construct<T: ClassComponent>(
    input: ValueMap<'_>,
    services: &ComponentServices,
) -> Result<Option<Box<dyn ComponentInstance>>> {
    let mut instance: T = decode::from_value(&Value::Map(input))?;
    instance.inject(services)?;
    Ok(instance
        .enabled()
        .then(|| Box::new(Instance(Rc::new(instance))) as Box<_>))
}

struct Instance<T>(Rc<T>);

impl<T: ClassComponent> ComponentInstance for Instance<T> {
    fn receiver<'a>(&self, fields: ValueMap<'a>) -> Value<'a>
    where
        Self: 'a,
    {
        Value::object(Receiver {
            instance: Rc::clone(&self.0),
            fields,
        })
    }

    fn data<'a>(&self) -> Result<ValueMap<'a>>
    where
        Self: 'a,
    {
        let mut fields = self.0.fields()?;
        for &name in T::methods() {
            fields.insert(
                name.into(),
                Value::object(Exposed(Rc::clone(&self.0), name)),
            );
        }
        Ok(fields)
    }

    fn with_attributes(&mut self, attributes: &mut AttributeBag) -> Result<()> {
        Rc::get_mut(&mut self.0)
            .ok_or_else(|| fault("component already shared"))?
            .with_attributes(attributes)
    }

    fn view_data<'a>(&self, cx: &ComponentContext<'_, '_>) -> Result<ValueMap<'a>>
    where
        Self: 'a,
    {
        self.0.view_data(cx)
    }

    fn render(&self, cx: &ComponentContext<'_, '_>, out: &mut Output) -> Result<ComponentRender> {
        self.0.render(cx, out)
    }
}

struct Receiver<'a, T> {
    instance: Rc<T>,
    fields: ValueMap<'a>,
}

impl<T> std::fmt::Debug for Receiver<'_, T> {
    fn fmt(&self, out: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        out.write_str(std::any::type_name::<T>())
    }
}

impl<'a, T: ClassComponent> Object<'a> for Receiver<'a, T> {
    fn type_name(&self) -> &'static str {
        std::any::type_name::<T>()
    }

    fn field(&self, name: &str) -> Option<Value<'a>> {
        self.fields.get(name).cloned()
    }

    fn method(&self, name: &str, args: Vec<Arg<'a, '_>>) -> Option<Result<Value<'a>>> {
        T::methods().contains(&name).then(|| {
            let args = args
                .into_iter()
                .map(|arg| match arg {
                    Arg::Value(value) => Ok(value),
                    Arg::Closure(_) => Err(fault("component methods require value arguments")),
                })
                .collect::<Result<Vec<_>>>()?;
            self.instance.call(name, &args)
        })
    }
}

struct Exposed<T>(Rc<T>, &'static str);

impl<T> std::fmt::Debug for Exposed<T> {
    fn fmt(&self, out: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        out.write_str(self.1)
    }
}

impl<'a, T: ClassComponent> Object<'a> for Exposed<T> {
    fn type_name(&self) -> &'static str {
        "component method"
    }

    fn call(&self, args: &[Value<'a>]) -> Option<Result<Value<'a>>> {
        Some(self.0.call(self.1, args))
    }
}

/// Converts a Rust return value to an engine value.
///
/// An owned result must be safe to drop even when serialization rejects it.
#[doc(hidden)]
pub fn serialize_value<'a>(value: impl Serialize) -> Result<Value<'a>> {
    decode::serialize_value(value)
}

/// Converts a Rust view model to its named fields.
#[doc(hidden)]
pub fn serialize_fields<'a>(value: impl Serialize) -> Result<ValueMap<'a>> {
    let Value::Map(fields) = serialize_value(value)? else {
        return Err(fault(
            "component view() must return a model with named fields",
        ));
    };
    Ok(fields)
}

/// Deserializes a value argument for a component or receiver method.
#[doc(hidden)]
pub fn argument<T: DeserializeOwned>(value: &Value<'_>) -> Result<T> {
    decode::from_value(value)
}

/// Accepts HTML returned directly or through a closure over render data.
#[doc(hidden)]
pub trait RenderOutput<'a, Kind> {
    fn write(self, data: &ValueMap<'a>, out: &mut Output) -> Result<()>;
}

impl<'a> RenderOutput<'a, ()> for String {
    fn write(self, _data: &ValueMap<'a>, out: &mut Output) -> Result<()> {
        out.raw(&self)
    }
}

impl<'a> RenderOutput<'a, ()> for &str {
    fn write(self, _data: &ValueMap<'a>, out: &mut Output) -> Result<()> {
        out.raw(self)
    }
}

impl<'a> RenderOutput<'a, ()> for crate::shape::Html {
    fn write(self, _data: &ValueMap<'a>, out: &mut Output) -> Result<()> {
        out.raw(self.as_str())
    }
}

impl<'a, T: RenderOutput<'a, ()>> RenderOutput<'a, ()> for Result<T> {
    fn write(self, data: &ValueMap<'a>, out: &mut Output) -> Result<()> {
        self?.write(data, out)
    }
}

impl<'a, F, T> RenderOutput<'a, (T,)> for F
where
    F: FnOnce(&ValueMap<'a>) -> T,
    T: RenderOutput<'a, ()>,
{
    fn write(self, data: &ValueMap<'a>, out: &mut Output) -> Result<()> {
        self(data).write(data, out)
    }
}

/// Writes the result of a class component's render hook.
#[doc(hidden)]
pub fn render_output<'a, Kind>(
    value: impl RenderOutput<'a, Kind>,
    data: &ValueMap<'a>,
    out: &mut Output,
) -> Result<ComponentRender> {
    value.write(data, out)?;
    Ok(ComponentRender::Direct)
}

/// Description and runtime dispatcher for a registered receiver type.
#[derive(Clone, Copy)]
pub struct MethodRegistration {
    /// Qualified receiver type.
    pub type_name: fn() -> &'static str,
    /// Names this receiver supports.
    pub names: &'static [&'static str],
    #[doc(hidden)]
    pub invoke: for<'a> fn(&MethodCache<'a>, &Value<'a>, &str, &[Value<'a>]) -> Result<Value<'a>>,
    #[doc(hidden)]
    pub wrap: for<'a> fn(Value<'a>) -> Result<Value<'a>>,
}

inventory::collect!(MethodRegistration);

/// Iterates over method registrations linked into the application.
pub fn methods() -> impl Iterator<Item = MethodRegistration> {
    inventory::iter::<MethodRegistration>.into_iter().copied()
}

/// Per-render cache for immutable, borrowed JSON receivers.
#[doc(hidden)]
#[derive(Default)]
pub struct MethodCache<'a>(
    RefCell<HashMap<(TypeId, *const serde_json::Value), CachedReceiver<'a>>>,
);

struct CachedReceiver<'a> {
    _source: &'a serde_json::Value,
    receiver: Rc<dyn Any>,
}

impl<'a> MethodCache<'a> {
    fn receiver<T: DeserializeOwned + 'static>(&self, value: &Value<'a>) -> Result<Rc<T>> {
        let Value::Json(value) = value else {
            return decode::from_value(value).map(Rc::new);
        };
        let key = (TypeId::of::<T>(), std::ptr::from_ref(*value));
        if let Some(entry) = self.0.borrow().get(&key) {
            return entry
                .receiver
                .clone()
                .downcast()
                .map_err(|_| fault("incompatible cached method receiver"));
        }
        let receiver = Rc::new(decode::from_value::<T>(&Value::Json(value))?);
        self.0.borrow_mut().insert(
            key,
            CachedReceiver {
                _source: value,
                receiver: receiver.clone(),
            },
        );
        Ok(receiver)
    }
}

/// Receiver adapter implemented by `#[methods]`.
#[doc(hidden)]
pub trait MethodReceiver: DeserializeOwned + 'static {
    const METHODS: &'static [&'static str];
    fn invoke<'a>(&self, name: &str, args: &[Value<'a>]) -> Result<Value<'a>>;
}

/// Dispatches through a deserialized and cached receiver.
#[doc(hidden)]
pub fn call_method<'a, T: MethodReceiver>(
    cache: &MethodCache<'a>,
    value: &Value<'a>,
    name: &str,
    args: &[Value<'a>],
) -> Result<Value<'a>> {
    cache.receiver::<T>(value)?.invoke(name, args)
}

/// Associates an engine value with a known receiver type.
#[doc(hidden)]
pub fn wrap_method_receiver<'a, T: MethodReceiver>(value: Value<'a>) -> Result<Value<'a>> {
    Ok(Value::object(Typed::<T> {
        value,
        receiver: OnceCell::new(),
    }))
}

struct Typed<'a, T> {
    value: Value<'a>,
    receiver: OnceCell<Result<T>>,
}

impl<T> std::fmt::Debug for Typed<'_, T> {
    fn fmt(&self, out: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.value.fmt(out)
    }
}

impl<'a, T: MethodReceiver> Object<'a> for Typed<'a, T> {
    fn type_name(&self) -> &'static str {
        std::any::type_name::<T>()
    }
    fn field(&self, name: &str) -> Option<Value<'a>> {
        self.value.field(name)
    }
    fn method(&self, name: &str, args: Vec<Arg<'a, '_>>) -> Option<Result<Value<'a>>> {
        if !T::METHODS.contains(&name) {
            return None;
        }
        let args = args
            .into_iter()
            .map(|arg| match arg {
                Arg::Value(value) => Ok(value),
                Arg::Closure(_) => Err(fault("registered methods require value arguments")),
            })
            .collect::<Result<Vec<_>>>();
        Some(args.and_then(|args| {
            let receiver = self
                .receiver
                .get_or_init(|| decode::from_value(&self.value));
            receiver.as_ref().map_err(Clone::clone)?.invoke(name, &args)
        }))
    }
    fn display(&self) -> Result<String> {
        self.value.display()
    }
    fn entries(&self, limit: usize) -> Result<Vec<(Value<'a>, Value<'a>)>> {
        self.value.entries(limit)
    }
    fn json_kind(&self) -> crate::encode::JsonKind<'_> {
        crate::encode::JsonValue::json_kind(&self.value)
    }
}

impl<'a> super::Markup<'a> {
    pub(super) fn take_props(&mut self, class: &RegisteredComponent) -> ValueMap<'a> {
        let mut output = ValueMap::new();
        self.take_shape_props(&mut output, &class.schema.shape, &class.schema.types, 0);
        output
    }

    fn take_shape_props(
        &mut self,
        output: &mut ValueMap<'a>,
        shape: &TypeDesc,
        registry: &TypeRegistry,
        depth: usize,
    ) {
        if depth >= 64 {
            return;
        }
        match shape {
            TypeDesc::Ref(name) => {
                if let Some(ty) = registry.get(name, Direction::Deserialize) {
                    self.take_shape_props(output, &ty.ty, registry, depth + 1);
                }
            }
            TypeDesc::Struct(fields) => {
                for field in fields {
                    if field.flatten {
                        self.take_shape_props(output, &field.ty, registry, depth + 1);
                        continue;
                    }
                    let matched = self.supplied.keys().find(|supplied| {
                        std::iter::once(field.name)
                            .chain(field.aliases.iter().copied())
                            .any(|candidate| snake_case(candidate) == snake_case(supplied))
                    });
                    if let Some(name) = matched.cloned() {
                        self.bag.offset_unset(&name);
                        if let Some(value) = self.supplied.get(&name) {
                            let value = if self.literals.contains(&name) {
                                decode::coerce_shape(value.clone(), &field.ty)
                            } else {
                                value.clone()
                            };
                            output.insert(field.name.into(), value);
                        }
                    }
                }
            }
            TypeDesc::Option(ty) | TypeDesc::Display { ty, .. } => {
                self.take_shape_props(output, ty, registry, depth + 1);
            }
            _ => {}
        }
    }
}

pub(crate) fn annotate_methods<'a>(
    data: &mut ValueMap<'a>,
    shape: &TypeDesc,
    types: &TypeRegistry,
    registrations: &[MethodRegistration],
) -> Result<()> {
    let dispatch = MethodShapes {
        types,
        registrations,
    };
    dispatch.fields(data, shape, 0)
}

struct MethodShapes<'a> {
    types: &'a TypeRegistry,
    registrations: &'a [MethodRegistration],
}

impl MethodShapes<'_> {
    fn fields(&self, data: &mut ValueMap<'_>, shape: &TypeDesc, depth: usize) -> Result<()> {
        if depth >= 64 {
            return Ok(());
        }
        match shape {
            TypeDesc::Ref(name) => {
                if let Some(ty) = self.types.get(name, Direction::Serialize) {
                    self.fields(data, &ty.ty, depth + 1)?;
                }
            }
            TypeDesc::Struct(fields) => {
                for field in fields {
                    if field.flatten {
                        self.fields(data, &field.ty, depth + 1)?;
                    } else if let Some(value) = data.get_mut(field.name) {
                        *value = self.value(
                            std::mem::replace(value, Value::Null),
                            &field.ty,
                            depth + 1,
                        )?;
                    }
                }
            }
            TypeDesc::Display { ty, .. } | TypeDesc::Option(ty) => {
                self.fields(data, ty, depth + 1)?
            }
            _ => {}
        }
        Ok(())
    }

    fn value<'v>(&self, value: Value<'v>, ty: &TypeDesc, depth: usize) -> Result<Value<'v>> {
        if depth >= 64 || value.is_null() || matches!(value, Value::Object(_)) {
            return Ok(value);
        }
        Ok(match ty {
            TypeDesc::Ref(name) => {
                if let Some(method) = self
                    .registrations
                    .iter()
                    .find(|method| (method.type_name)() == *name)
                {
                    return (method.wrap)(value);
                }
                if let Some(ty) = self.types.get(name, Direction::Serialize) {
                    return self.value(value, &ty.ty, depth + 1);
                }
                value
            }
            TypeDesc::Option(ty) | TypeDesc::Display { ty, .. } => {
                self.value(value, ty, depth + 1)?
            }
            TypeDesc::List { element, .. } => match value {
                Value::List(items) => Value::List(
                    items
                        .into_iter()
                        .map(|value| self.value(value, element, depth + 1))
                        .collect::<Result<_>>()?,
                ),
                Value::Json(serde_json::Value::Array(items)) => Value::List(
                    items
                        .iter()
                        .map(|value| self.value(Value::Json(value), element, depth + 1))
                        .collect::<Result<_>>()?,
                ),
                value => value,
            },
            TypeDesc::Tuple(types) => match value {
                Value::List(items) => Value::List(
                    items
                        .into_iter()
                        .enumerate()
                        .map(|(index, value)| match types.get(index) {
                            Some(ty) => self.value(value, &ty.ty, depth + 1),
                            None => Ok(value),
                        })
                        .collect::<Result<_>>()?,
                ),
                value => value,
            },
            TypeDesc::Struct(_) => match value {
                Value::Map(mut fields) => {
                    self.fields(&mut fields, ty, depth + 1)?;
                    Value::Map(fields)
                }
                Value::Json(serde_json::Value::Object(fields)) => {
                    let mut fields = fields
                        .iter()
                        .map(|(name, value)| (name.clone(), Value::Json(value)))
                        .collect();
                    self.fields(&mut fields, ty, depth + 1)?;
                    Value::Map(fields)
                }
                value => value,
            },
            TypeDesc::Map { value: ty, .. } => match value {
                Value::Map(fields) => Value::Map(
                    fields
                        .into_iter()
                        .map(|(name, value)| Ok((name, self.value(value, ty, depth + 1)?)))
                        .collect::<Result<_>>()?,
                ),
                value => value,
            },
            _ => value,
        })
    }
}