Skip to main content

taba/
typescript.rs

1//! What serde_json writes and reads, as TypeScript sees it.
2//!
3//! [`Output`] is what TypeScript receives, and [`Input`] is what it may send. Each impl holds a
4//! [`Shape`] as const data. A derived type is one [`Named`] that other shapes refer to.
5//! Only the derives and the impls here build shapes, so they're hidden.
6//!
7//! 64-bit integers have no impl, because a JavaScript number can't hold one exactly. They're fine
8//! as map keys, which travel as strings.
9//!
10//! A [`RawValue`] fails every read inside an untagged or internally tagged enum, or a flattened
11//! field, though its declaration accepts any JSON. Use [`Value`] there.
12//!
13//! [`RawValue`]: ::serde_json::value::RawValue
14//! [`Value`]: ::serde_json::Value
15
16use alloc::{
17    boxed::Box,
18    collections::{BTreeMap, BTreeSet},
19    format,
20    string::String,
21    vec::Vec,
22};
23use core::{fmt::Debug, hash::Hash, marker::PhantomData, panic::Location};
24
25#[doc(hidden)]
26pub mod __private {
27    pub use super::{
28        Direction, Input, Named, Object, Output, Parameter, Placeholder, Property, Request, Rest,
29        Shape,
30    };
31}
32
33/// One JSON shape.
34#[derive(Debug)]
35pub enum Shape {
36    /// `boolean`.
37    Boolean,
38
39    /// `number`.
40    Number,
41
42    /// `string`.
43    String,
44
45    /// `null`.
46    Null,
47
48    /// No value.
49    Never,
50
51    /// A string literal type.
52    Literal(&'static str),
53
54    /// A homogeneous array.
55    Array(&'static Shape),
56
57    /// A fixed-length array.
58    Tuple(&'static [Shape]),
59
60    /// An object with any string keys.
61    Record(&'static Shape),
62
63    /// An object with fixed keys.
64    Object(&'static Object),
65
66    /// Any one of these.
67    Union(&'static [Shape]),
68
69    /// One of its [`Named`]'s parameters, by position.
70    Parameter(usize),
71
72    /// A named type, declared once, with its arguments.
73    ///
74    /// A `fn` because references can form cycles, and a const like `__SHAPE` can't hold one.
75    Reference(fn() -> &'static Named, &'static [Shape]),
76}
77
78/// An object's keys.
79#[derive(Debug)]
80pub struct Object {
81    /// Its keys, in [`serde`]'s order.
82    pub properties: &'static [Property],
83
84    /// Its other keys.
85    pub rest: Rest,
86}
87
88/// What [`serde`] does with an [`Object`]'s other keys.
89#[derive(Debug)]
90pub enum Rest {
91    /// Ignores them.
92    Ignored,
93
94    /// Rejects them, under `deny_unknown_fields`.
95    Rejected,
96
97    /// They're the keys of these parts.
98    ///
99    /// A part is a `#[serde(flatten)]` field, or an internally tagged newtype variant's value. A
100    /// `null` adds none, which is what a flattened `None` writes.
101    Parts(&'static [Shape]),
102}
103
104/// One key of an [`Object`].
105#[derive(Debug)]
106pub struct Property {
107    /// The field's `#[doc]` values, like [`Named::docs`].
108    pub docs: &'static [&'static str],
109
110    /// The key, as [`serde`] names it.
111    pub key: &'static str,
112
113    /// The field's name in the Rust source, or its variant's or struct's for a key serde adds.
114    pub location: &'static Location<'static>,
115
116    /// Whether the key may be missing.
117    pub optional: bool,
118
119    /// The value's shape.
120    pub shape: Shape,
121}
122
123/// A type the derives describe, where it's defined.
124#[derive(Debug)]
125pub struct Named {
126    /// Its `#[doc]` values, as written.
127    ///
128    /// Each `///` line is one value, still led by the space after the slashes.
129    pub docs: &'static [&'static str],
130
131    /// Which derive built it.
132    pub direction: Direction,
133
134    /// Its name in the Rust source, or `None` for a type taba describes itself.
135    pub location: Option<&'static Location<'static>>,
136
137    /// Its module, from [`module_path!`].
138    pub module_path: &'static str,
139
140    /// Its Rust name.
141    pub name: &'static str,
142
143    /// The type parameters its TypeScript declaration takes, in order.
144    pub parameters: &'static [&'static str],
145
146    /// Its shape, with a [`Shape::Parameter`] where each type parameter goes.
147    pub shape: Shape,
148}
149
150impl Named {
151    /// Its path, crate first, which TypeScript calls a procedure by.
152    pub fn path(&self) -> String {
153        format!("{}::{}", self.module_path, self.name)
154    }
155
156    /// The crate it's defined in.
157    pub fn crate_(&self) -> &'static str {
158        self.module_path.split_once("::").map_or(self.module_path, |(crate_, _)| crate_)
159    }
160}
161
162/// Which derive built a [`Named`].
163#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
164pub enum Direction {
165    /// [`Output`]'s.
166    Output,
167
168    /// [`Input`]'s.
169    Input,
170}
171
172/// What serde_json writes for `Self`.
173#[diagnostic::on_unimplemented(
174    note = "derive `Output` alongside `Serialize`",
175    note = "a type from another crate takes `#[taba(with = \"...\")]` on its field",
176    note = "a 64-bit integer has no exact JavaScript number"
177)]
178pub trait Output {
179    #[doc(hidden)]
180    const __SHAPE: Shape;
181
182    /// Its shape inside an internally tagged newtype variant.
183    #[doc(hidden)]
184    const __TAGGED: Shape = Self::__SHAPE;
185}
186
187/// What serde_json reads as `Self`.
188#[diagnostic::on_unimplemented(
189    note = "derive `Input` alongside `Deserialize`",
190    note = "a type from another crate takes `#[taba(with = \"...\")]` on its field",
191    note = "a 64-bit integer has no exact JavaScript number"
192)]
193pub trait Input {
194    /// Whether a struct field of this type may be missing when read.
195    #[doc(hidden)]
196    const __OPTIONAL: bool = false;
197
198    #[doc(hidden)]
199    const __SHAPE: Shape;
200
201    /// Its shape inside an internally tagged newtype variant.
202    #[doc(hidden)]
203    const __TAGGED: Shape = Self::__SHAPE;
204}
205
206/// An [`Input`] that isn't generic in TypeScript.
207#[diagnostic::on_unimplemented(
208    message = "`{Self}` can't be a procedure",
209    label = "a procedure derives `Input` and isn't generic",
210    note = "to call one instantiation of a generic type, wrap it in a struct of its own"
211)]
212pub trait Request {
213    /// Its declaration.
214    fn named() -> &'static Named;
215}
216
217macro_rules! both {
218    ($shape:expr, $($ty:ty),+) => {$(
219        impl Output for $ty {
220            const __SHAPE: Shape = $shape;
221        }
222
223        impl Input for $ty {
224            const __SHAPE: Shape = $shape;
225        }
226    )+};
227}
228
229both!(Shape::Boolean, bool);
230both!(Shape::Number, u8, u16, u32, i8, i16, i32);
231both!(Shape::String, String, char);
232both!(Shape::Null, ());
233
234macro_rules! float {
235    ($($ty:ty),+) => {$(
236        /// Nullable because JSON doesn't represent `NaN` or infinity.
237        impl Output for $ty {
238            const __SHAPE: Shape = Shape::Union(&[Shape::Number, Shape::Null]);
239        }
240
241        impl Input for $ty {
242            const __SHAPE: Shape = Shape::Number;
243        }
244    )+};
245}
246
247float!(f32, f64);
248
249impl<T: ?Sized> Output for PhantomData<T> {
250    const __SHAPE: Shape = Shape::Null;
251}
252
253impl<T: ?Sized> Input for PhantomData<T> {
254    const __SHAPE: Shape = Shape::Null;
255}
256
257impl Output for str {
258    const __SHAPE: Shape = Shape::String;
259}
260
261impl<T: Output + ?Sized> Output for &T {
262    const __SHAPE: Shape = T::__SHAPE;
263}
264
265impl<T: Output + ?Sized> Output for Box<T> {
266    const __SHAPE: Shape = T::__SHAPE;
267}
268
269impl<T: Input> Input for Box<T> {
270    const __OPTIONAL: bool = T::__OPTIONAL;
271    const __SHAPE: Shape = T::__SHAPE;
272
273    // `T::__TAGGED` would cycle on recursive types
274    const __TAGGED: Shape = T::__SHAPE;
275}
276
277impl<T: Output> Output for Option<T> {
278    const __SHAPE: Shape = Shape::Union(&[T::__SHAPE, Shape::Null]);
279
280    // serde can't write one beside a tag
281    const __TAGGED: Shape = Shape::Never;
282}
283
284impl<T: Input> Input for Option<T> {
285    const __OPTIONAL: bool = true;
286    const __SHAPE: Shape = Shape::Union(&[T::__SHAPE, Shape::Null]);
287
288    // serde never reads one beside a tag as `None`
289    const __TAGGED: Shape = T::__TAGGED;
290}
291
292impl<T: Output> Output for [T] {
293    const __SHAPE: Shape = Shape::Array(&T::__SHAPE);
294}
295
296macro_rules! generic {
297    ($shape:expr, $($ty:ident),+) => {$(
298        impl<T: Output> Output for $ty<T> {
299            const __SHAPE: Shape = $shape;
300        }
301
302        impl<T: Input> Input for $ty<T> {
303            const __SHAPE: Shape = $shape;
304        }
305    )+};
306}
307
308generic!(Shape::Array(&T::__SHAPE), Vec, BTreeSet);
309
310impl<T: Output, const N: usize> Output for [T; N] {
311    const __SHAPE: Shape = Shape::Tuple(&[T::__SHAPE; N]);
312}
313
314impl<T: Input, const N: usize> Input for [T; N] {
315    const __SHAPE: Shape = Shape::Tuple(&[T::__SHAPE; N]);
316}
317
318macro_rules! tuples {
319    () => {};
320    ($first:ident $(, $rest:ident)*) => {
321        impl<$first: Output $(, $rest: Output)*> Output for ($first, $($rest),*) {
322            const __SHAPE: Shape = Shape::Tuple(&[$first::__SHAPE $(, $rest::__SHAPE)*]);
323        }
324
325        impl<$first: Input $(, $rest: Input)*> Input for ($first, $($rest),*) {
326            const __SHAPE: Shape = Shape::Tuple(&[$first::__SHAPE $(, $rest::__SHAPE)*]);
327        }
328
329        tuples!($($rest),*);
330    };
331}
332
333tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P); // 16
334
335/// A map key [`serde_json`](::serde_json) writes as a string.
336///
337/// Integer keys are exact as digit strings, including 64 and 128 bit.
338#[diagnostic::on_unimplemented(note = "a key is a string, `char`, `bool` or integer")]
339pub trait Key {}
340
341macro_rules! key {
342    ($($ty:ty),+) => {$(impl Key for $ty {})+};
343}
344
345key!(String, char, bool);
346key!(u8, u16, u32, u64, u128, usize);
347key!(i8, i16, i32, i64, i128, isize);
348
349impl<K: Key, V: Output> Output for BTreeMap<K, V> {
350    const __SHAPE: Shape = Shape::Record(&V::__SHAPE);
351}
352
353impl<K: Key, V: Input> Input for BTreeMap<K, V> {
354    const __SHAPE: Shape = Shape::Record(&V::__SHAPE);
355}
356
357/// A placeholder for the `N`th of a [`Named`]'s parameters.
358#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
359pub struct Parameter<const N: usize>;
360
361impl<const N: usize> Output for Parameter<N> {
362    const __SHAPE: Shape = Shape::Parameter(N);
363}
364
365impl<const N: usize> Input for Parameter<N> {
366    const __SHAPE: Shape = Shape::Parameter(N);
367}
368
369impl<const N: usize> Key for Parameter<N> {}
370
371/// Everything a [`Parameter`] implements.
372///
373/// A field type can ask only these of a type parameter.
374pub trait Placeholder: Output + Input + Key + Copy + Debug + Default + Hash + Ord {}
375
376impl<const N: usize> Placeholder for Parameter<N> {}
377
378mod serde_json {
379    use ::serde_json::{Map, Number, Value, value::RawValue};
380
381    use super::*;
382
383    both!(Shape::Number, Number);
384
385    macro_rules! value {
386        ($trait:ident) => {
387            impl $trait for Value {
388                const __SHAPE: Shape = Shape::Reference(
389                    || &Named {
390                        docs: &[],
391                        direction: Direction::$trait,
392                        location: None,
393                        module_path: "serde_json::value",
394                        name: "Value",
395                        parameters: &[],
396                        shape: Shape::Union(&[
397                            Shape::Null,
398                            Shape::Boolean,
399                            Shape::Number,
400                            Shape::String,
401                            Shape::Array(&<Value as $trait>::__SHAPE),
402                            Shape::Record(&<Value as $trait>::__SHAPE),
403                        ]),
404                    },
405                    &[],
406                );
407            }
408
409            impl $trait for Map<String, Value> {
410                const __SHAPE: Shape = Shape::Record(&<Value as $trait>::__SHAPE);
411            }
412        };
413    }
414
415    value!(Output);
416    value!(Input);
417
418    impl Output for RawValue {
419        const __SHAPE: Shape = <Value as Output>::__SHAPE;
420    }
421
422    impl Input for Box<RawValue> {
423        const __SHAPE: Shape = <Value as Input>::__SHAPE;
424    }
425
426    impl Input for &RawValue {
427        const __SHAPE: Shape = <Value as Input>::__SHAPE;
428    }
429}
430
431#[cfg(feature = "std")]
432mod std {
433    use std::collections::{HashMap, HashSet};
434
435    use super::{Input, Key, Output, Shape};
436
437    impl<T: Output, S> Output for HashSet<T, S> {
438        const __SHAPE: Shape = Shape::Array(&T::__SHAPE);
439    }
440
441    impl<T: Input, S> Input for HashSet<T, S> {
442        const __SHAPE: Shape = Shape::Array(&T::__SHAPE);
443    }
444
445    impl<K: Key, V: Output, S> Output for HashMap<K, V, S> {
446        const __SHAPE: Shape = Shape::Record(&V::__SHAPE);
447    }
448
449    impl<K: Key, V: Input, S> Input for HashMap<K, V, S> {
450        const __SHAPE: Shape = Shape::Record(&V::__SHAPE);
451    }
452}