Skip to main content

facet_core/
lib.rs

1//! TeamDman-maintained fork of [facet-core](https://github.com/facet-rs/facet/tree/65bae5c31a7ce401bc44630fb96250ea884cfd3e/facet-core), published as
2//! [teamy-facet-core](https://crates.io/crates/teamy-facet-core).
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#![cfg_attr(not(feature = "std"), no_std)]
8// Enable portable_simd when available (detected via autocfg in build.rs)
9#![cfg_attr(has_portable_simd, feature(portable_simd))]
10#![warn(missing_docs)]
11#![warn(clippy::std_instead_of_core)]
12#![warn(clippy::std_instead_of_alloc)]
13// Allow uncommon unicode in the 𝟋 prelude module
14#![allow(uncommon_codepoints)]
15//!
16//! [![crates.io](https://img.shields.io/crates/v/teamy-facet-core.svg)](https://crates.io/crates/teamy-facet-core)
17//! [![documentation](https://docs.rs/teamy-facet-core/badge.svg)](https://docs.rs/teamy-facet-core)
18//! [![MIT/Apache-2.0 licensed](https://img.shields.io/crates/l/teamy-facet-core.svg)](./LICENSE-MIT)
19//! [![Discord](https://img.shields.io/discord/1379550208551026748?logo=discord&label=discord)](https://discord.gg/JhD7CwCJ8F)
20//!
21//! Defines the `Facet` trait and implements it for a lot (a LOT) of builtin types.
22//!
23//! This crate is foundational to facet's reflection capabilities, providing the type system that enables runtime type manipulation.
24//!
25#![doc = include_str!("../readme-footer.md")]
26
27extern crate alloc;
28
29// Core type definitions (merged from facet-core-types)
30mod types;
31pub use types::*;
32
33// Write trait for serializers
34mod write;
35pub use write::Write;
36
37#[cfg(feature = "taxon")]
38pub mod taxon_bridge;
39
40// Implementations of the Shape trait
41mod impls;
42#[cfg(feature = "semver")]
43pub use semver;
44
45/// Allows querying the [`Shape`] of a type, which in turn lets us inspect any fields, build a value of
46/// this type progressively, etc.
47///
48/// The `'facet` lifetime allows `Facet` to be derived for types that borrow from something else.
49///
50/// # Safety
51///
52/// If you implement this wrong, all the safe abstractions in `facet-reflect`,
53/// all the serializers, deserializers, the entire ecosystem is unsafe.
54///
55/// You're responsible for describing the type layout properly, and annotating all the invariants.
56pub unsafe trait Facet<'facet>: 'facet {
57    /// The shape of this type, including: whether it's a Struct, an Enum, something else?
58    ///
59    /// All its fields, with their names, types, attributes, doc comments, etc.
60    /// VTables for list operations, set operations, map operations, option operations,
61    /// and implementations for Display, Debug, etc.—marker traits like Send, Sync, Copy, Eq,
62    /// and probably other things I'm forgetting.
63    const SHAPE: &'static Shape;
64}
65
66/// Returns the shape of a type as a function pointer.
67///
68/// This is a helper for lazy shape initialization in field definitions.
69/// Using a function pointer instead of a direct reference moves const
70/// evaluation from compile time to runtime, improving compile times.
71///
72/// # Example
73///
74/// ```ignore
75/// use facet_core::{FieldBuilder, shape_of};
76///
77/// // In field definitions:
78/// FieldBuilder::new("my_field", shape_of::<i32>, 0)
79/// ```
80#[inline]
81pub const fn shape_of<'a, T: Facet<'a>>() -> &'static Shape {
82    T::SHAPE
83}
84
85/// Ultra-compact prelude for derive macro codegen (the "digamma" prelude).
86///
87/// All exports are prefixed with `𝟋` to avoid collisions after `use ::facet::𝟋::*;`
88///
89/// The `𝟋` character (U+1D4CB, Mathematical Script Small F, "digamma") was chosen because:
90/// - It's a valid Rust identifier (XID_Start)
91/// - It's visually distinctive ("this is internal macro stuff")
92/// - It won't collide with any user-defined names
93#[doc(hidden)]
94#[allow(nonstandard_style)]
95pub mod 𝟋 {
96    // === Type aliases ===
97    pub use crate::Attr as 𝟋Attr;
98    pub use crate::Def as 𝟋Def;
99    pub use crate::DefaultSource as 𝟋DS;
100    pub use crate::EnumRepr as 𝟋ERpr;
101    pub use crate::EnumType as 𝟋ETy;
102    pub use crate::EnumTypeBuilder as 𝟋ETyB;
103    pub use crate::Facet as 𝟋Fct;
104    pub use crate::Field as 𝟋Fld;
105    pub use crate::FieldBuilder as 𝟋FldB;
106    pub use crate::FieldFlags as 𝟋FF;
107    pub use crate::HashProxy as 𝟋HP;
108    pub use crate::MarkerTraits as 𝟋Mt;
109    pub use crate::Repr as 𝟋Repr;
110    pub use crate::Shape as 𝟋Shp;
111    pub use crate::ShapeBuilder as 𝟋ShpB;
112    pub use crate::ShapeFlags as 𝟋ShpF;
113    pub use crate::ShapeRef as 𝟋ShpR;
114    pub use crate::StructKind as 𝟋Sk;
115    pub use crate::StructType as 𝟋STy;
116    pub use crate::StructTypeBuilder as 𝟋STyB;
117    pub use crate::Type as 𝟋Ty;
118    pub use crate::UserType as 𝟋UTy;
119    pub use crate::VTableDirect as 𝟋VtD;
120    pub use crate::VTableErased as 𝟋VtE;
121    pub use crate::Variance as 𝟋Vnc;
122    pub use crate::VarianceDesc as 𝟋VncD;
123    pub use crate::Variant as 𝟋Var;
124    pub use crate::VariantBuilder as 𝟋VarB;
125    pub use ::core::option::Option::None as 𝟋None;
126    pub use ::core::option::Option::Some as 𝟋Some;
127    pub use ::core::result::Result::Err as 𝟋Err;
128    pub use ::core::result::Result::Ok as 𝟋Ok;
129
130    // === Core utility re-exports ===
131    pub use ::core::mem::forget as 𝟋forget;
132    pub use ::core::mem::transmute as 𝟋transmute;
133    pub use ::core::ptr::drop_in_place as 𝟋drop_in_place;
134
135    /// Helper to get shape of a type as a function - monomorphized per type
136    pub use crate::shape_of as 𝟋shp;
137
138    // === Declaration ID ===
139    pub use crate::DeclId as 𝟋DId;
140    pub use crate::decl_id_hash as 𝟋dih;
141
142    // === Constants ===
143    /// Empty attributes slice
144    pub const 𝟋NOAT: &[crate::FieldAttribute] = &[];
145    /// Empty doc slice
146    pub const 𝟋NODOC: &[&str] = &[];
147    /// Empty flags
148    pub const 𝟋NOFL: crate::FieldFlags = crate::FieldFlags::empty();
149    /// Computed variance (for non-opaque types) - bivariant base with field walking fallback
150    pub const 𝟋CV: crate::VarianceDesc = crate::VarianceDesc::BIVARIANT;
151
152    // === Type Aliases ===
153    /// PhantomData type for shadow structs, invariant with respect to lifetime `'a`.
154    pub type 𝟋Ph<'a> = ::core::marker::PhantomData<*mut &'a ()>;
155
156    /// String type for proxy conversion errors (requires alloc feature).
157    #[cfg(feature = "alloc")]
158    pub type 𝟋Str = ::alloc::string::String;
159
160    /// Fallback when alloc is not available - proxy requires alloc at runtime,
161    /// but we need a type for compilation in no_std contexts.
162    #[cfg(not(feature = "alloc"))]
163    pub type 𝟋Str = &'static str;
164
165    /// Result type alias for macro-generated code.
166    pub type 𝟋Result<T, E> = ::core::result::Result<T, E>;
167
168    // === Helper functions ===
169    /// Returns `drop_in_place::<T>` as a function pointer for vtable construction.
170    pub const fn 𝟋drop_for<T>() -> unsafe fn(*mut T) {
171        ::core::ptr::drop_in_place::<T>
172    }
173
174    /// Returns a default_in_place function pointer for TypeOpsDirect.
175    /// # Safety
176    /// The pointer must point to uninitialized memory of sufficient size and alignment for T.
177    pub const fn 𝟋default_for<T: Default>() -> unsafe fn(*mut T) {
178        unsafe fn default_in_place<T: Default>(ptr: *mut T) {
179            unsafe { ptr.write(T::default()) };
180        }
181        default_in_place::<T>
182    }
183
184    /// Returns a clone_into function pointer for TypeOpsDirect.
185    /// # Safety
186    /// - `src` must point to a valid, initialized value of type T
187    /// - `dst` must point to uninitialized memory of sufficient size and alignment for T
188    pub const fn 𝟋clone_for<T: Clone>() -> unsafe fn(*const T, *mut T) {
189        unsafe fn clone_into<T: Clone>(src: *const T, dst: *mut T) {
190            unsafe { dst.write((*src).clone()) };
191        }
192        clone_into::<T>
193    }
194
195    /// Returns a parse function pointer for VTableDirect.
196    /// # Safety
197    /// The pointer must point to uninitialized memory of sufficient size and alignment for T.
198    pub const fn 𝟋parse_for<T: ::core::str::FromStr>()
199    -> unsafe fn(&str, *mut T) -> ::core::result::Result<(), crate::ParseError> {
200        unsafe fn parse<T: ::core::str::FromStr>(
201            s: &str,
202            dst: *mut T,
203        ) -> ::core::result::Result<(), crate::ParseError> {
204            match <T as ::core::str::FromStr>::from_str(s) {
205                Ok(value) => {
206                    unsafe { dst.write(value) };
207                    Ok(())
208                }
209                Err(_) => Err(crate::ParseError::from_str("parse error")),
210            }
211        }
212        parse::<T>
213    }
214
215    // === TypeOpsIndirect helpers ===
216    // These take OxPtrMut/OxPtrConst and work with wide pointers
217
218    /// Returns a drop_in_place function pointer for TypeOpsIndirect.
219    pub const fn 𝟋indirect_drop_for<T>() -> unsafe fn(crate::OxPtrMut) {
220        unsafe fn drop_in_place<T>(ox: crate::OxPtrMut) {
221            unsafe { ::core::ptr::drop_in_place(ox.ptr().as_ptr::<T>() as *mut T) };
222        }
223        drop_in_place::<T>
224    }
225
226    /// Returns a default_in_place function pointer for TypeOpsIndirect.
227    pub const fn 𝟋indirect_default_for<T: Default>() -> unsafe fn(crate::OxPtrUninit) -> bool {
228        unsafe fn default_in_place<T: Default>(ox: crate::OxPtrUninit) -> bool {
229            unsafe { ox.put(T::default()) };
230            true
231        }
232        default_in_place::<T>
233    }
234
235    /// Returns a clone_into function pointer for TypeOpsIndirect.
236    pub const fn 𝟋indirect_clone_for<T: Clone>() -> unsafe fn(crate::OxPtrConst, crate::OxPtrMut) {
237        unsafe fn clone_into<T: Clone>(src: crate::OxPtrConst, dst: crate::OxPtrMut) {
238            let src_val = unsafe { &*(src.ptr().as_byte_ptr() as *const T) };
239            unsafe { dst.ptr().as_uninit().put(src_val.clone()) };
240        }
241        clone_into::<T>
242    }
243
244    // === Specialization ===
245    pub use crate::types::specialization::impls;
246    pub use crate::types::specialization::{
247        Spez, SpezCloneIntoNo, SpezCloneIntoYes, SpezDebugNo, SpezDebugYes, SpezDefaultInPlaceNo,
248        SpezDefaultInPlaceYes, SpezDisplayNo, SpezDisplayYes, SpezEmpty, SpezHashNo, SpezHashYes,
249        SpezOrdNo, SpezOrdYes, SpezParseNo, SpezParseYes, SpezPartialEqNo, SpezPartialEqYes,
250        SpezPartialOrdNo, SpezPartialOrdYes,
251    };
252}