Skip to main content

facet_path/
lib.rs

1//! TeamDman-maintained fork of [facet-path](https://github.com/facet-rs/facet/tree/65bae5c31a7ce401bc44630fb96250ea884cfd3e/facet-path), published as
2//! [teamy-facet-path](https://crates.io/crates/teamy-facet-path).
3//! This fork uses its own Facet crate identities; use matching Teamy packages.
4//! Upstream MIT OR Apache-2.0 licensing and attribution are retained.
5//! See the [release notes](https://github.com/TeamDman/facet/blob/teamy-main/TEAMY_RELEASE.md).
6//!
7#![warn(missing_docs)]
8#![cfg_attr(not(feature = "std"), no_std)]
9//!
10//! [![crates.io](https://img.shields.io/crates/v/teamy-facet-path.svg)](https://crates.io/crates/teamy-facet-path)
11//! [![documentation](https://docs.rs/teamy-facet-path/badge.svg)](https://docs.rs/teamy-facet-path)
12//! [![MIT/Apache-2.0 licensed](https://img.shields.io/crates/l/teamy-facet-path.svg)](./LICENSE-MIT)
13//! [![Discord](https://img.shields.io/discord/1379550208551026748?logo=discord&label=discord)](https://discord.gg/JhD7CwCJ8F)
14//!
15//!
16//! Path tracking for navigating Facet type structures.
17//!
18//! This crate provides lightweight path tracking that records navigation steps through a Facet type hierarchy. When an error occurs during serialization or deserialization, the path can be used to produce helpful error messages showing exactly where in the data structure the problem occurred.
19//!
20//! ## Features
21//!
22//! - Lightweight `PathStep` enum that stores indices, not strings
23//! - Reconstruct human-readable paths by replaying steps against a `Shape`
24//! - Optional `pretty` feature for rich error rendering with `facet-pretty`
25//!
26//! ## Usage
27//!
28//! ```rust
29//! use facet::Facet;
30//! use facet_path::{Path, PathStep};
31//!
32//! #[derive(Facet)]
33//! struct Outer {
34//!     items: Vec<Inner>,
35//! }
36//!
37//! #[derive(Facet)]
38//! struct Inner {
39//!     name: String,
40//!     value: u32,
41//! }
42//!
43//! // Build a path during traversal
44//! let mut path = Path::new(<Outer as Facet>::SHAPE);
45//! path.push(PathStep::Field(0));      // "items"
46//! path.push(PathStep::Index(2));       // [2]
47//! path.push(PathStep::Field(0));      // "name"
48//!
49//! // Format the path as a human-readable string
50//! let formatted = path.format();
51//! assert_eq!(formatted, "items[2].name");
52//! ```
53//!
54//! ## Feature Flags
55//!
56//! - `std` (default): Enables standard library support
57//! - `alloc`: Enables heap allocation without full std
58//! - `pretty`: Enables rich error rendering with `facet-pretty`
59//!
60//!
61//!
62#![doc = include_str!("../readme-footer.md")]
63
64extern crate alloc;
65
66use alloc::string::String;
67use alloc::vec::Vec;
68use core::fmt::Write;
69
70use facet_core::{Def, Field, Shape, Type, UserType};
71
72pub mod access;
73pub use access::PathAccessError;
74
75pub mod walk;
76pub use walk::{ShapeVisitor, VisitDecision, WalkStatus, walk_shape};
77
78/// A single step in a path through a type structure.
79///
80/// Each step records an index that can be used to navigate
81/// back through a [`Shape`] to reconstruct field names and types.
82#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
83#[non_exhaustive]
84pub enum PathStep {
85    /// Navigate to a struct field by index
86    Field(u32),
87    /// Navigate to a list/array element by index
88    Index(u32),
89    /// Navigate to an enum variant by index
90    Variant(u32),
91    /// Navigate into a map key at a specific entry index.
92    /// The entry index distinguishes paths for different map keys' inner frames.
93    MapKey(u32),
94    /// Navigate into a map value at a specific entry index.
95    /// The entry index distinguishes paths for different map values' inner frames.
96    MapValue(u32),
97    /// Navigate into `Some` of an Option
98    OptionSome,
99    /// Navigate through a pointer/reference
100    Deref,
101    /// Navigate into a transparent inner type (e.g., `NonZero<T>` -> T)
102    Inner,
103    /// Navigate into a proxy type (e.g., `Inner` with `#[facet(proxy = InnerProxy)]`)
104    ///
105    /// This step distinguishes a proxy frame from its parent in the deferred
106    /// processing path, so both can be stored without path collisions.
107    Proxy,
108}
109
110/// A path through a type structure, recorded as a series of steps.
111///
112/// This is a lightweight representation that only stores indices.
113/// The actual field names and type information can be reconstructed
114/// by replaying these steps against the original [`Shape`].
115#[derive(Debug, Clone)]
116pub struct Path {
117    /// The root [`Shape`] from which this path originates.
118    pub shape: &'static Shape,
119
120    /// The sequence of [`PathStep`]s representing navigation through the type structure.
121    pub steps: Vec<PathStep>,
122}
123
124impl PartialEq for Path {
125    fn eq(&self, other: &Self) -> bool {
126        // Compare shapes by pointer address (they're static references)
127        core::ptr::eq(self.shape, other.shape) && self.steps == other.steps
128    }
129}
130
131impl Eq for Path {}
132
133impl PartialOrd for Path {
134    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
135        Some(self.cmp(other))
136    }
137}
138
139impl Ord for Path {
140    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
141        // Compare shapes by pointer address first, then by steps
142        let shape_cmp =
143            (self.shape as *const Shape as usize).cmp(&(other.shape as *const Shape as usize));
144        if shape_cmp != core::cmp::Ordering::Equal {
145            return shape_cmp;
146        }
147        self.steps.cmp(&other.steps)
148    }
149}
150
151impl core::hash::Hash for Path {
152    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
153        // Hash the shape pointer address
154        (self.shape as *const Shape as usize).hash(state);
155        self.steps.hash(state);
156    }
157}
158
159impl Path {
160    /// Create a new empty path.
161    pub const fn new(shape: &'static Shape) -> Self {
162        Self {
163            shape,
164            steps: Vec::new(),
165        }
166    }
167
168    /// Create a path with pre-allocated capacity.
169    pub fn with_capacity(shape: &'static Shape, capacity: usize) -> Self {
170        Self {
171            shape,
172            steps: Vec::with_capacity(capacity),
173        }
174    }
175
176    /// Push a step onto the path.
177    pub fn push(&mut self, step: PathStep) {
178        self.steps.push(step);
179    }
180
181    /// Pop the last step from the path.
182    pub fn pop(&mut self) -> Option<PathStep> {
183        self.steps.pop()
184    }
185
186    /// Get the steps in this path.
187    pub fn steps(&self) -> &[PathStep] {
188        &self.steps
189    }
190
191    /// Get the length of this path.
192    pub const fn len(&self) -> usize {
193        self.steps.len()
194    }
195
196    /// Check if this path is empty.
197    pub const fn is_empty(&self) -> bool {
198        self.steps.is_empty()
199    }
200
201    /// Format this path as a human-readable string using the stored root shape.
202    ///
203    /// Returns a path like `outer.inner.items[3].name`.
204    pub fn format(&self) -> String {
205        self.format_with_shape(self.shape)
206    }
207
208    /// Format this path as a human-readable string by walking the given shape.
209    ///
210    /// Returns a path like `outer.inner.items[3].name`.
211    pub fn format_with_shape(&self, shape: &'static Shape) -> String {
212        let mut result = String::new();
213        let mut current_shape = shape;
214        let mut current_variant_idx: Option<usize> = None;
215
216        for step in &self.steps {
217            match step {
218                PathStep::Field(idx) => {
219                    let idx = *idx as usize;
220                    if let Some(field_name) =
221                        get_field_name_with_variant(current_shape, idx, current_variant_idx)
222                    {
223                        if !result.is_empty() {
224                            result.push('.');
225                        }
226                        result.push_str(field_name);
227                    }
228                    if let Some(field_shape) =
229                        get_field_shape_with_variant(current_shape, idx, current_variant_idx)
230                    {
231                        current_shape = field_shape;
232                    }
233                    current_variant_idx = None;
234                }
235                PathStep::Index(idx) => {
236                    write!(result, "[{}]", idx).unwrap();
237                    if let Some(elem_shape) = get_element_shape(current_shape) {
238                        current_shape = elem_shape;
239                    }
240                    current_variant_idx = None;
241                }
242                PathStep::Variant(idx) => {
243                    let idx = *idx as usize;
244                    if let Some(variant_name) = get_variant_name(current_shape, idx) {
245                        result.push_str("::");
246                        result.push_str(variant_name);
247                    }
248                    // Don't advance current_shape — the next Field step will
249                    // use the variant index to look up fields within the enum.
250                    current_variant_idx = Some(idx);
251                }
252                PathStep::MapKey(idx) => {
253                    write!(result, "[key#{}]", idx).unwrap();
254                    if let Some(key_shape) = get_map_key_shape(current_shape) {
255                        current_shape = key_shape;
256                    }
257                    current_variant_idx = None;
258                }
259                PathStep::MapValue(idx) => {
260                    write!(result, "[value#{}]", idx).unwrap();
261                    if let Some(value_shape) = get_map_value_shape(current_shape) {
262                        current_shape = value_shape;
263                    }
264                    current_variant_idx = None;
265                }
266                PathStep::OptionSome => {
267                    result.push_str("::Some");
268                    if let Some(inner_shape) = get_option_inner_shape(current_shape) {
269                        current_shape = inner_shape;
270                    }
271                    current_variant_idx = None;
272                }
273                PathStep::Deref => {
274                    if let Some(inner_shape) = get_pointer_inner_shape(current_shape) {
275                        current_shape = inner_shape;
276                    }
277                    current_variant_idx = None;
278                }
279                PathStep::Inner => {
280                    if let Some(inner_shape) = get_inner_shape(current_shape) {
281                        current_shape = inner_shape;
282                    }
283                    current_variant_idx = None;
284                }
285                PathStep::Proxy => {
286                    if let Some(proxy_def) = current_shape.effective_proxy(None) {
287                        current_shape = proxy_def.shape;
288                    }
289                    current_variant_idx = None;
290                }
291            }
292        }
293
294        if result.is_empty() {
295            result.push_str("<root>");
296        }
297
298        result
299    }
300
301    /// Resolve the field at the end of this path, if the path ends at a struct field.
302    ///
303    /// This navigates through the given shape following each step in the path,
304    /// and returns the [`Field`] if the final step is a `PathStep::Field`.
305    ///
306    /// This is useful for accessing field metadata like attributes when handling
307    /// errors that occur at a specific field location.
308    ///
309    /// # Returns
310    ///
311    /// - `Some(&Field)` if the path ends at a struct field
312    /// - `None` if the path is empty, doesn't end at a field, or navigation fails
313    pub fn resolve_leaf_field(&self, shape: &'static Shape) -> Option<&'static Field> {
314        if self.steps.is_empty() {
315            return None;
316        }
317
318        let mut current_shape = shape;
319        let mut current_variant_idx: Option<usize> = None;
320
321        // Navigate through all steps except the last one
322        for step in &self.steps[..self.steps.len() - 1] {
323            match step {
324                PathStep::Field(idx) => {
325                    let idx = *idx as usize;
326                    current_shape =
327                        get_field_shape_with_variant(current_shape, idx, current_variant_idx)?;
328                    current_variant_idx = None;
329                }
330                PathStep::Index(_) => {
331                    current_shape = get_element_shape(current_shape)?;
332                    current_variant_idx = None;
333                }
334                PathStep::Variant(idx) => {
335                    // Remember the variant for the next field lookup
336                    current_variant_idx = Some(*idx as usize);
337                }
338                PathStep::MapKey(_) => {
339                    current_shape = get_map_key_shape(current_shape)?;
340                    current_variant_idx = None;
341                }
342                PathStep::MapValue(_) => {
343                    current_shape = get_map_value_shape(current_shape)?;
344                    current_variant_idx = None;
345                }
346                PathStep::OptionSome => {
347                    current_shape = get_option_inner_shape(current_shape)?;
348                    current_variant_idx = None;
349                }
350                PathStep::Deref => {
351                    current_shape = get_pointer_inner_shape(current_shape)?;
352                    current_variant_idx = None;
353                }
354                PathStep::Inner => {
355                    current_shape = get_inner_shape(current_shape)?;
356                    current_variant_idx = None;
357                }
358                PathStep::Proxy => {
359                    let proxy_def = current_shape.effective_proxy(None)?;
360                    current_shape = proxy_def.shape;
361                    current_variant_idx = None;
362                }
363            }
364        }
365
366        // Check if the last step is a field
367        if let Some(PathStep::Field(idx)) = self.steps.last() {
368            let idx = *idx as usize;
369            return get_field_with_variant(current_shape, idx, current_variant_idx);
370        }
371
372        None
373    }
374}
375
376impl core::fmt::Display for Path {
377    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
378        f.write_str(&self.format())
379    }
380}
381
382/// Get the field at the given index, handling both structs and enum variants.
383fn get_field_with_variant(
384    shape: &Shape,
385    idx: usize,
386    variant_idx: Option<usize>,
387) -> Option<&'static Field> {
388    match shape.ty {
389        Type::User(UserType::Struct(sd)) => sd.fields.get(idx),
390        Type::User(UserType::Enum(ed)) => {
391            let variant_idx = variant_idx?;
392            let variant = ed.variants.get(variant_idx)?;
393            variant.data.fields.get(idx)
394        }
395        _ => None,
396    }
397}
398
399/// Get the shape of a field at the given index, handling both structs and enum variants.
400fn get_field_shape_with_variant(
401    shape: &Shape,
402    idx: usize,
403    variant_idx: Option<usize>,
404) -> Option<&'static Shape> {
405    get_field_with_variant(shape, idx, variant_idx).map(|f| f.shape())
406}
407
408/// Get the name of a field at the given index, handling both structs and enum variants.
409fn get_field_name_with_variant(
410    shape: &Shape,
411    idx: usize,
412    variant_idx: Option<usize>,
413) -> Option<&'static str> {
414    get_field_with_variant(shape, idx, variant_idx).map(|f| f.name)
415}
416
417/// Get the element shape for a list/array.
418const fn get_element_shape(shape: &Shape) -> Option<&'static Shape> {
419    match shape.def {
420        Def::List(ld) => Some(ld.t()),
421        Def::Array(ad) => Some(ad.t()),
422        Def::Slice(sd) => Some(sd.t()),
423        _ => None,
424    }
425}
426
427/// Get the name of a variant at the given index.
428fn get_variant_name(shape: &Shape, idx: usize) -> Option<&'static str> {
429    match shape.ty {
430        Type::User(UserType::Enum(ed)) => ed.variants.get(idx).map(|v| v.name),
431        _ => None,
432    }
433}
434
435/// Get the key shape for a map.
436const fn get_map_key_shape(shape: &Shape) -> Option<&'static Shape> {
437    match shape.def {
438        Def::Map(md) => Some(md.k()),
439        _ => None,
440    }
441}
442
443/// Get the value shape for a map.
444const fn get_map_value_shape(shape: &Shape) -> Option<&'static Shape> {
445    match shape.def {
446        Def::Map(md) => Some(md.v()),
447        _ => None,
448    }
449}
450
451/// Get the inner shape for an Option.
452const fn get_option_inner_shape(shape: &Shape) -> Option<&'static Shape> {
453    match shape.def {
454        Def::Option(od) => Some(od.t()),
455        _ => None,
456    }
457}
458
459/// Get the inner shape for a pointer.
460const fn get_pointer_inner_shape(shape: &Shape) -> Option<&'static Shape> {
461    match shape.def {
462        Def::Pointer(pd) => pd.pointee(),
463        _ => None,
464    }
465}
466
467/// Get the inner shape for a transparent type (e.g., `NonZero<T>`).
468const fn get_inner_shape(shape: &Shape) -> Option<&'static Shape> {
469    shape.inner
470}
471
472#[cfg(test)]
473mod tests {
474    use super::*;
475
476    #[test]
477    fn test_path_step_size() {
478        // PathStep should be 8 bytes (discriminant + u32, aligned)
479        assert_eq!(core::mem::size_of::<PathStep>(), 8);
480    }
481}