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
//! Type descriptions for checking view data and component props.
mod builtins;
mod registration;
pub use oxblade_macros::{Shape, Shared, View};
pub use registration::{
Shared, SharedRegistration, View, ViewModel, ViewRegistration, shared_models, view, view_models,
};
use std::collections::{BTreeMap, BTreeSet};
/// The direction in which Serde processes a type.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum Direction {
/// Data supplied to the template by a view model.
Serialize,
/// Data accepted by a component prop.
Deserialize,
}
/// A position in the Rust source that declares a type, field or variant.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SourceLocation {
/// The compiler's source file path.
pub file: &'static str,
/// The one-based line number.
pub line: u32,
/// The one-based column number.
pub column: u32,
}
/// A type as seen at the template boundary.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum TypeDesc {
/// A JSON null.
Null,
/// A boolean.
Bool,
/// An integer.
Int,
/// A floating-point number.
Float,
/// A UTF-8 string.
String,
/// A printable prop accepting strings, integers, floats and null.
Text,
/// A string carrying trusted markup provenance when produced by the view serializer.
Html,
/// A date or time represented as text at the JSON boundary.
Date,
/// A specific string value such as a Serde discriminator.
Literal(&'static str),
/// A value that can also be null.
Option(Box<TypeDesc>),
/// A homogeneous array.
List {
/// Type of each element.
element: Box<TypeDesc>,
/// The exact length of a fixed array, if known.
length: Option<usize>,
},
/// A positional sequence, in wire order.
Tuple(Vec<TupleElement>),
/// An ordered map. JSON encodes supported non-string keys as object member names.
Map {
/// Logical type of each key.
key: Box<TypeDesc>,
/// Type of each value.
value: Box<TypeDesc>,
},
/// Named fields in declaration order, including flattened members.
Struct(Vec<FieldDesc>),
/// A Serde enum with its tag strategy and ordered variants.
Enum(EnumDesc),
/// Alternative representations of a single type. An empty union has no valid values.
Union(Vec<TypeDesc>),
/// An unchecked value.
Any,
/// A named type in the registry for the current direction.
Ref(&'static str),
/// A type with a named template display handler.
Display {
/// Registered handler name.
name: &'static str,
/// Underlying wire representation.
ty: Box<TypeDesc>,
},
}
/// How a named field can occur at the wire boundary.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Presence {
/// The key may be omitted. The type still describes a value when the key is present.
Absent,
/// The key is required and its value is optional.
Nullable,
/// The key is required.
Required,
}
/// A named field in a struct or enum payload.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FieldDesc {
/// Primary wire name in this direction.
pub name: &'static str,
/// Additional accepted input names. Empty for output.
pub aliases: Vec<&'static str>,
/// Whether a key may be missing or its value may be null.
pub presence: Presence,
/// Whether this type contributes keys to the enclosing object instead of using its own key.
pub flatten: bool,
/// Value type, or the source of keys if flattened.
pub ty: TypeDesc,
/// Where the field was declared.
pub source: SourceLocation,
}
/// A position in a tuple or tuple variant.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TupleElement {
/// The type at this position.
pub ty: TypeDesc,
/// Whether Serde can omit this output position or default a missing input position.
pub omittable: bool,
}
/// How Serde distinguishes variants on the wire.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum EnumTag {
/// A unit variant is a string. On input it may also be an object with a null payload.
/// Other variants use an object with the variant name as its key.
External,
/// A discriminator is inserted into the variant object.
Internal {
/// Name of the discriminator field.
tag: &'static str,
},
/// A discriminator and optional payload are stored in separate object fields.
Adjacent {
/// Name of the discriminator field.
tag: &'static str,
/// Name of the payload field.
content: &'static str,
},
/// Only the variant payload appears on the wire.
Untagged,
}
/// A Serde enum's representation in one direction.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct EnumDesc {
/// Default tagging strategy.
pub tag: EnumTag,
/// Variants in declaration order, including the first-match order for untagged input.
pub variants: Vec<VariantDesc>,
}
/// One Serde enum variant.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct VariantDesc {
/// Wire name or discriminator value.
pub name: &'static str,
/// Additional accepted variant names. Empty for output.
pub aliases: Vec<&'static str>,
/// Whether this variant omits the enclosing enum's tag even in a tagged enum.
pub untagged: bool,
/// Variant content. `None` means a unit variant.
pub payload: Option<TypeDesc>,
/// Whether a non-unit adjacent variant can deserialize with its content field omitted.
pub payload_omittable: bool,
/// Where the variant was declared.
pub source: SourceLocation,
}
/// A registered definition for a named type in one direction.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct NamedType {
/// The Rust name as written, without module or generic arguments.
pub name: &'static str,
/// Where the type was declared.
pub source: SourceLocation,
/// Definition referenced by a `TypeDesc::Ref`.
pub ty: TypeDesc,
}
/// Definitions encountered while walking shapes. Recursive references use Rust's qualified type names.
#[derive(Default, Debug)]
pub struct TypeRegistry {
definitions: BTreeMap<Direction, BTreeMap<&'static str, NamedType>>,
pending: BTreeSet<(&'static str, Direction)>,
}
impl TypeRegistry {
/// Looks up a reference in the direction in which it was produced.
pub fn get(&self, id: &str, direction: Direction) -> Option<&NamedType> {
self.definitions.get(&direction)?.get(id)
}
/// Lists definitions, including distinct instantiations of generic types.
pub fn iter(&self) -> impl Iterator<Item = (&'static str, Direction, &NamedType)> {
self.definitions.iter().flat_map(|(&direction, types)| {
types.iter().map(move |(&id, named)| (id, direction, named))
})
}
/// Loads the linked nongeneric types, even when they are not yet reached by a view or prop.
pub fn register_linked(&mut self, direction: Direction) {
for entry in inventory::iter::<__private::ShapeRegistration> {
(entry.describe)(self, direction);
}
}
/// Defines a named shape once per direction and returns its reference, even during recursion.
pub fn define<T: ?Sized>(
&mut self,
direction: Direction,
name: &'static str,
source: SourceLocation,
describe: impl FnOnce(&mut Self) -> TypeDesc,
) -> TypeDesc {
let id = std::any::type_name::<T>();
let key = (id, direction);
if self.get(id, direction).is_none() && self.pending.insert(key) {
let ty = describe(self);
self.pending.remove(&key);
self.definitions
.entry(direction)
.or_default()
.insert(id, NamedType { name, source, ty });
}
TypeDesc::Ref(id)
}
}
/// Describes the values Serde writes for templates and accepts for component props.
#[diagnostic::on_unimplemented(
message = "`{Self}` has no oxblade Shape",
note = "For unordered HashMap or HashSet values, use IndexMap, BTreeMap, or an ordered sequence for deterministic output"
)]
pub trait Shape {
/// Describes this type, registering any named types it references.
fn describe(registry: &mut TypeRegistry, direction: Direction) -> TypeDesc;
/// Describes values serialized into a view.
fn serialize_shape(registry: &mut TypeRegistry) -> TypeDesc {
Self::describe(registry, Direction::Serialize)
}
/// Describes values accepted by a component prop.
fn deserialize_shape(registry: &mut TypeRegistry) -> TypeDesc {
Self::describe(registry, Direction::Deserialize)
}
}
/// Printable component prop data.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
pub enum Text {
/// Plain text.
String(String),
/// A signed integer.
Int(i64),
/// An unsigned integer outside the signed range.
Unsigned(u64),
/// A floating-point number.
Float(f64),
/// A null value that prints nothing.
Empty,
}
impl std::fmt::Display for Text {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::String(value) => value.fmt(formatter),
Self::Int(value) => value.fmt(formatter),
Self::Unsigned(value) => value.fmt(formatter),
Self::Float(value) => value.fmt(formatter),
Self::Empty => Ok(()),
}
}
}
/// Explicitly trusted HTML from application code. Serializes as a string and cannot be deserialized.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Html(String);
impl Html {
/// Serde newtype marker that the engine's view serializer can observe for provenance.
pub const SERDE_NAME: &str = "__oxblade_html";
/// Marks an already safe string as trusted. The caller must escape any untrusted fragments first.
pub fn new(html: impl Into<String>) -> Self {
Self(html.into())
}
/// Returns the trusted markup.
pub fn as_str(&self) -> &str {
&self.0
}
}
impl serde::Serialize for Html {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_newtype_struct(Self::SERDE_NAME, &self.0)
}
}
/// Implementation details used by the derive macros.
#[doc(hidden)]
pub mod __private {
use super::{Direction, SourceLocation, TypeDesc, TypeRegistry};
/// Re-export for macro consumers.
pub use inventory::submit;
/// An inventory entry for a named type.
pub struct ShapeRegistration {
/// Function that inserts the named definition.
pub describe: fn(&mut TypeRegistry, Direction) -> TypeDesc,
}
inventory::collect!(ShapeRegistration);
/// Encloses a descriptor in a display annotation when one is present.
pub fn display(ty: TypeDesc, name: &'static str) -> TypeDesc {
TypeDesc::Display {
name,
ty: Box::new(ty),
}
}
/// Whether a value's outer representation is optional.
pub fn is_option(ty: &TypeDesc) -> bool {
match ty {
TypeDesc::Display { ty, .. } => is_option(ty),
TypeDesc::Option(_) => true,
_ => false,
}
}
/// Whether an optional wire value is known, including through newtype definitions.
pub fn is_nullable(ty: &TypeDesc, registry: &TypeRegistry, direction: Direction) -> bool {
let mut ty = ty;
let mut visited = None;
loop {
match ty {
TypeDesc::Ref(name) => {
if !visited
.get_or_insert_with(std::collections::BTreeSet::new)
.insert(*name)
{
return false;
}
let Some(named) = registry.get(name, direction) else {
return false;
};
ty = &named.ty;
}
TypeDesc::Display { ty: inner, .. } => ty = inner,
_ => return is_option(ty),
}
}
}
/// Source location of the invocation.
pub const fn source(file: &'static str, line: u32, column: u32) -> SourceLocation {
SourceLocation { file, line, column }
}
}