facet-reflect 0.44.4

Build and manipulate values of arbitrary Facet types at runtime while respecting invariants - safe runtime reflection
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
use super::*;
use crate::HasFields;
#[cfg(feature = "std")]
use core::cell::RefCell;
use hashbrown::{HashMap, HashSet};

#[cfg(feature = "std")]
thread_local! {
    static INVARIANT_SUBTREE_CACHE: RefCell<HashMap<facet_core::ConstTypeId, bool>> =
        RefCell::new(HashMap::new());
}

fn shape_subtree_has_invariants(
    shape: &'static Shape,
    cache: &mut HashMap<facet_core::ConstTypeId, Option<bool>>,
) -> bool {
    #[cfg(feature = "std")]
    if let Some(cached) = INVARIANT_SUBTREE_CACHE.with(|memo| memo.borrow().get(&shape.id).copied())
    {
        return cached;
    }

    if let Some(cached) = cache.get(&shape.id) {
        // `None` means we're currently evaluating this shape in a recursive cycle.
        // Returning false here breaks recursion; direct invariants are checked before descent.
        return cached.unwrap_or(false);
    }

    cache.insert(shape.id, None);

    let has_invariants = if shape.vtable.has_invariants() {
        true
    } else {
        match shape.ty {
            Type::User(UserType::Struct(struct_ty)) => struct_ty
                .fields
                .iter()
                .any(|field| shape_subtree_has_invariants(field.shape.get(), cache)),
            Type::User(UserType::Enum(enum_ty)) => enum_ty.variants.iter().any(|variant| {
                variant
                    .data
                    .fields
                    .iter()
                    .any(|field| shape_subtree_has_invariants(field.shape.get(), cache))
            }),
            _ => match shape.def {
                Def::List(list) => shape_subtree_has_invariants(list.t(), cache),
                Def::Array(array) => shape_subtree_has_invariants(array.t(), cache),
                Def::Slice(slice) => shape_subtree_has_invariants(slice.t(), cache),
                Def::Map(map) => {
                    shape_subtree_has_invariants(map.k(), cache)
                        || shape_subtree_has_invariants(map.v(), cache)
                }
                Def::Set(set) => shape_subtree_has_invariants(set.t(), cache),
                Def::Option(opt) => shape_subtree_has_invariants(opt.t(), cache),
                Def::Result(result) => {
                    shape_subtree_has_invariants(result.t(), cache)
                        || shape_subtree_has_invariants(result.e(), cache)
                }
                Def::Pointer(ptr) => ptr
                    .pointee()
                    .is_some_and(|pointee| shape_subtree_has_invariants(pointee, cache)),
                _ => false,
            },
        }
    };

    #[cfg(feature = "std")]
    INVARIANT_SUBTREE_CACHE.with(|memo| {
        memo.borrow_mut().insert(shape.id, has_invariants);
    });
    cache.insert(shape.id, Some(has_invariants));
    has_invariants
}

fn validate_invariants_recursive<'mem, 'facet>(
    value: Peek<'mem, 'facet>,
    visited: &mut HashSet<crate::ValueId>,
    shape_cache: &mut HashMap<facet_core::ConstTypeId, Option<bool>>,
) -> Result<(), (&'static Shape, String)> {
    if !shape_subtree_has_invariants(value.shape(), shape_cache) {
        return Ok(());
    }

    let id = value.id();
    if !visited.insert(id) {
        return Ok(());
    }

    if let Some(result) = unsafe { value.shape().call_invariants(value.data()) }
        && let Err(message) = result
    {
        return Err((value.shape(), message));
    }

    match value.shape().ty {
        Type::User(UserType::Struct(_)) => {
            if let Ok(peek_struct) = value.into_struct() {
                for (field, child) in peek_struct.fields() {
                    if shape_subtree_has_invariants(field.shape.get(), shape_cache) {
                        validate_invariants_recursive(child, visited, shape_cache)?;
                    }
                }
            }
        }
        Type::User(UserType::Enum(_)) => {
            if let Ok(peek_enum) = value.into_enum() {
                for (field, child) in peek_enum.fields() {
                    if shape_subtree_has_invariants(field.shape.get(), shape_cache) {
                        validate_invariants_recursive(child, visited, shape_cache)?;
                    }
                }
            }
        }
        _ => match value.shape().def {
            Def::List(_) | Def::Array(_) | Def::Slice(_) => {
                if let Ok(list_like) = value.into_list_like()
                    && shape_subtree_has_invariants(list_like.def.t(), shape_cache)
                {
                    for elem in list_like.iter() {
                        validate_invariants_recursive(elem, visited, shape_cache)?;
                    }
                }
            }
            Def::Map(_) => {
                if let Ok(map) = value.into_map() {
                    let def = map.def();
                    let key_has_invariants = shape_subtree_has_invariants(def.k(), shape_cache);
                    let value_has_invariants = shape_subtree_has_invariants(def.v(), shape_cache);
                    if key_has_invariants || value_has_invariants {
                        for (key, val) in map.iter() {
                            if key_has_invariants {
                                validate_invariants_recursive(key, visited, shape_cache)?;
                            }
                            if value_has_invariants {
                                validate_invariants_recursive(val, visited, shape_cache)?;
                            }
                        }
                    }
                }
            }
            Def::Set(_) => {
                if let Ok(set) = value.into_set()
                    && shape_subtree_has_invariants(set.def().t(), shape_cache)
                {
                    for elem in set.iter() {
                        validate_invariants_recursive(elem, visited, shape_cache)?;
                    }
                }
            }
            Def::Option(_) => {
                if let Ok(opt) = value.into_option()
                    && let Some(inner) = opt.value()
                    && shape_subtree_has_invariants(inner.shape(), shape_cache)
                {
                    validate_invariants_recursive(inner, visited, shape_cache)?;
                }
            }
            Def::Result(_) => {
                if let Ok(result) = value.into_result() {
                    if let Some(ok) = result.ok() {
                        validate_invariants_recursive(ok, visited, shape_cache)?;
                    }
                    if let Some(err) = result.err() {
                        validate_invariants_recursive(err, visited, shape_cache)?;
                    }
                }
            }
            Def::Pointer(_) => {
                if let Ok(ptr) = value.into_pointer()
                    && let Some(inner) = ptr.borrow_inner()
                    && shape_subtree_has_invariants(inner.shape(), shape_cache)
                {
                    validate_invariants_recursive(inner, visited, shape_cache)?;
                }
            }
            _ => {}
        },
    }

    Ok(())
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// Build
////////////////////////////////////////////////////////////////////////////////////////////////////
impl<'facet, const BORROW: bool> Partial<'facet, BORROW> {
    /// Builds the value, consuming the Partial.
    pub fn build(mut self) -> Result<HeapValue<'facet, BORROW>, ReflectError> {
        use crate::typeplan::TypePlanNodeKind;

        if self.frames().len() != 1 {
            return Err(self.err(ReflectErrorKind::InvariantViolation {
                invariant: "Partial::build() expects a single frame — call end() until that's the case",
            }));
        }

        // Try the optimized path using precomputed FieldInitPlan (includes validators)
        // Extract frame info first (borrows only self.mode)
        let frame_info = self.mode.stack().last().map(|frame| {
            let variant_idx = match &frame.tracker {
                Tracker::Enum { variant_idx, .. } => Some(*variant_idx),
                _ => None,
            };
            (frame.type_plan, variant_idx)
        });

        // Look up plans from the type plan node - need to resolve NodeId to get the actual node
        let plans_info = frame_info.and_then(|(type_plan_id, variant_idx)| {
            let type_plan = self.root_plan.node(type_plan_id);
            match &type_plan.kind {
                TypePlanNodeKind::Struct(struct_plan) => Some(struct_plan.fields),
                TypePlanNodeKind::Enum(enum_plan) => {
                    let variants = self.root_plan.variants(enum_plan.variants);
                    variant_idx.and_then(|idx| variants.get(idx).map(|v| v.fields))
                }
                _ => None,
            }
        });

        if let Some(plans_range) = plans_info {
            // Resolve the SliceRange to an actual slice
            let plans = self.root_plan.fields(plans_range);
            // Now mutably borrow mode.stack to get the frame
            // (root_plan borrow of `plans` is still active but that's fine -
            // mode and root_plan are separate fields)
            let frame = self.mode.stack_mut().last_mut().unwrap();
            crate::trace!(
                "build(): Using optimized fill_and_require_fields for {}, tracker={:?}",
                frame.allocated.shape(),
                frame.tracker.kind()
            );
            frame
                .fill_and_require_fields(plans, plans.len(), &self.root_plan)
                .map_err(|e| self.err(e))?;
        } else {
            // Fall back to the old path if optimized path wasn't available
            let frame = self.frames_mut().last_mut().unwrap();
            crate::trace!(
                "build(): calling fill_defaults for {}, tracker={:?}, is_init={}",
                frame.allocated.shape(),
                frame.tracker.kind(),
                frame.is_init
            );
            if let Err(e) = frame.fill_defaults() {
                return Err(self.err(e));
            }
            crate::trace!(
                "build(): after fill_defaults, tracker={:?}, is_init={}",
                frame.tracker.kind(),
                frame.is_init
            );

            let frame = self.frames_mut().last_mut().unwrap();
            crate::trace!(
                "build(): calling require_full_initialization, tracker={:?}",
                frame.tracker.kind()
            );
            let result = frame.require_full_initialization();
            crate::trace!(
                "build(): require_full_initialization result: {:?}",
                result.is_ok()
            );
            result.map_err(|e| self.err(e))?
        }

        let frame = self.frames_mut().pop().unwrap();

        // Validate invariants on the full value tree (root + nested values).
        // Safety: the value is fully initialized at this point.
        let value_ptr = unsafe { frame.data.assume_init().as_const() };
        let root = unsafe { Peek::unchecked_new(value_ptr, frame.allocated.shape()) };
        let mut visited = HashSet::new();
        let mut shape_cache = HashMap::new();
        if let Err((shape, message)) =
            validate_invariants_recursive(root, &mut visited, &mut shape_cache)
        {
            // Put the frame back so Drop can handle cleanup properly
            self.frames_mut().push(frame);
            return Err(self.err(ReflectErrorKind::UserInvariantFailed { message, shape }));
        }

        // Mark as built to prevent Drop from cleaning up the value
        self.state = PartialState::Built;

        match frame
            .allocated
            .shape()
            .layout
            .sized_layout()
            .map_err(|_layout_err| {
                self.err(ReflectErrorKind::Unsized {
                    shape: frame.allocated.shape(),
                    operation: "build (final check for sized layout)",
                })
            }) {
            Ok(layout) => {
                // Determine if we should deallocate based on ownership
                let should_dealloc = frame.ownership.needs_dealloc();

                Ok(HeapValue {
                    guard: Some(Guard {
                        ptr: unsafe { NonNull::new_unchecked(frame.data.as_mut_byte_ptr()) },
                        layout,
                        should_dealloc,
                    }),
                    shape: frame.allocated.shape(),
                    phantom: PhantomData,
                })
            }
            Err(e) => {
                // Put the frame back for proper cleanup
                self.frames_mut().push(frame);
                Err(e)
            }
        }
    }

    /// Finishes deserialization in-place, validating the value without moving it.
    ///
    /// This is intended for use with [`from_raw`](Self::from_raw) where the value
    /// is deserialized into caller-provided memory (e.g., a `MaybeUninit<T>` on the stack).
    ///
    /// On success, the caller can safely assume the memory contains a fully initialized,
    /// valid value and call `MaybeUninit::assume_init()`.
    ///
    /// On failure, any partially initialized data is cleaned up (dropped), and the
    /// memory should be considered uninitialized.
    ///
    /// # Panics
    ///
    /// Panics if called with more than one frame on the stack (i.e., if you haven't
    /// called `end()` enough times to return to the root level).
    ///
    /// # Example
    ///
    /// ```ignore
    /// use std::mem::MaybeUninit;
    /// use facet_core::{Facet, PtrUninit};
    /// use facet_reflect::Partial;
    ///
    /// let mut slot = MaybeUninit::<MyStruct>::uninit();
    /// let ptr = PtrUninit::new(slot.as_mut_ptr().cast());
    ///
    /// let partial = unsafe { Partial::from_raw_with_shape(ptr, MyStruct::SHAPE)? };
    /// // ... deserialize into partial ...
    /// partial.finish_in_place()?;
    ///
    /// // Now safe to assume initialized
    /// let value = unsafe { slot.assume_init() };
    /// ```
    pub fn finish_in_place(mut self) -> Result<(), ReflectError> {
        use crate::typeplan::TypePlanNodeKind;

        if self.frames().len() != 1 {
            return Err(self.err(ReflectErrorKind::InvariantViolation {
                invariant: "Partial::finish_in_place() expects a single frame — call end() until that's the case",
            }));
        }

        // Try the optimized path using precomputed FieldInitPlan (includes validators)
        // Extract frame info first (borrows only self.mode)
        let frame_info = self.mode.stack().last().map(|frame| {
            let variant_idx = match &frame.tracker {
                Tracker::Enum { variant_idx, .. } => Some(*variant_idx),
                _ => None,
            };
            (frame.type_plan, variant_idx)
        });

        // Look up plans from the type plan node - need to resolve NodeId to get the actual node
        let plans_info = frame_info.and_then(|(type_plan_id, variant_idx)| {
            let type_plan = self.root_plan.node(type_plan_id);
            match &type_plan.kind {
                TypePlanNodeKind::Struct(struct_plan) => Some(struct_plan.fields),
                TypePlanNodeKind::Enum(enum_plan) => {
                    let variants = self.root_plan.variants(enum_plan.variants);
                    variant_idx.and_then(|idx| variants.get(idx).map(|v| v.fields))
                }
                _ => None,
            }
        });

        if let Some(plans_range) = plans_info {
            // Resolve the SliceRange to an actual slice
            let plans = self.root_plan.fields(plans_range);
            // Now mutably borrow mode.stack to get the frame
            // (root_plan borrow of `plans` is still active but that's fine -
            // mode and root_plan are separate fields)
            let frame = self.mode.stack_mut().last_mut().unwrap();
            crate::trace!(
                "finish_in_place(): Using optimized fill_and_require_fields for {}, tracker={:?}",
                frame.allocated.shape(),
                frame.tracker.kind()
            );
            frame
                .fill_and_require_fields(plans, plans.len(), &self.root_plan)
                .map_err(|e| self.err(e))?;
        } else {
            // Fall back to the old path if optimized path wasn't available
            let frame = self.frames_mut().last_mut().unwrap();
            crate::trace!(
                "finish_in_place(): calling fill_defaults for {}, tracker={:?}, is_init={}",
                frame.allocated.shape(),
                frame.tracker.kind(),
                frame.is_init
            );
            if let Err(e) = frame.fill_defaults() {
                return Err(self.err(e));
            }
            crate::trace!(
                "finish_in_place(): after fill_defaults, tracker={:?}, is_init={}",
                frame.tracker.kind(),
                frame.is_init
            );

            let frame = self.frames_mut().last_mut().unwrap();
            crate::trace!(
                "finish_in_place(): calling require_full_initialization, tracker={:?}",
                frame.tracker.kind()
            );
            let result = frame.require_full_initialization();
            crate::trace!(
                "finish_in_place(): require_full_initialization result: {:?}",
                result.is_ok()
            );
            result.map_err(|e| self.err(e))?
        }

        let frame = self.frames_mut().pop().unwrap();

        // Validate invariants on the full value tree (root + nested values).
        // Safety: the value is fully initialized at this point.
        let value_ptr = unsafe { frame.data.assume_init().as_const() };
        let root = unsafe { Peek::unchecked_new(value_ptr, frame.allocated.shape()) };
        let mut visited = HashSet::new();
        let mut shape_cache = HashMap::new();
        if let Err((shape, message)) =
            validate_invariants_recursive(root, &mut visited, &mut shape_cache)
        {
            // Put the frame back so Drop can handle cleanup properly
            self.frames_mut().push(frame);
            return Err(self.err(ReflectErrorKind::UserInvariantFailed { message, shape }));
        }

        // Mark as built to prevent Drop from cleaning up the now-valid value.
        // The caller owns the memory and will handle the value from here.
        self.state = PartialState::Built;

        // Frame is dropped here without deallocation (External ownership doesn't dealloc)
        Ok(())
    }
}