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
//! # Structural Typing for Rust
//!
//! Structural typing separates schemas (what fields can exist) from selections (what fields must be
//! present). Optionality is context-dependent—a name is always a string, but different contexts may
//! or may not require it. Instead of creating separate types for each context (`CreateUser`,
//! `UpdateUser`, `DBUser`...) or using `Option<T>` everywhere, define your schema once and use
//! generic trait bounds for context-specific requirements—all verified at compile time.
//!
//! This design is inspired by Rich Hickey's [`Maybe Not`](https://www.youtube.com/watch?v=YR5WdGrpoug)
//! talk, which articulates the principle of separating attribute definitions from their use in aggregates,
//! along with ideas from TypeScript's structural types and RDF's independent attributes.
//!
//! ## Installation
//!
//! ```toml
//! [dependencies]
//! structural-typing = "0.1.9"
//! derive-where = "1.6" # For deriving traits on structural types
//! ```
//!
//! ## Usage
//!
//! ### Define the schema
//!
//! ```ignore
//! use structural_typing::structural;
//!
//! #[structural]
//! struct User {
//! id: u32,
//! name: String,
//! email: String,
//! }
//! ```
//!
//! The `#[structural]` macro generates a module named `user` containing a `Fields` trait with
//! associated types for each field. This enables compile-time tracking of which fields are present.
//!
//! ### Generic functions with field requirements
//!
//! Functions can require specific fields through trait bounds using the generated `Fields` trait.
//! The `Presence` type can be `Present` (`T`), `Optional` (`Option<T>`), or `Absent` (`PhantomData<T>`):
//!
//! ```ignore
//! # use structural_typing::{structural, presence::Present};
//! #
//! # #[structural]
//! # struct User {
//! # id: u32,
//! # name: String,
//! # email: String,
//! # }
//! #
//! // Requires both id and name
//! fn display_user<F: user::Fields<id = Present, name = Present>>(user: &User<F>) {
//! println!("User #{}: {}", user.id, user.name);
//! }
//! ```
//!
//! Relaxing requirements is backward compatible. Existing callers with id and name continue to work
//! if we remove the `name` requirement—unlike changing a function parameter from `T` to `Option<T>`,
//! which breaks all existing call sites.
//!
//! ```ignore
//! # use structural_typing::{structural, presence::Present, access::Access};
//! #
//! # #[structural]
//! # struct User {
//! # id: u32,
//! # name: String,
//! # email: String,
//! # }
//! #
//! // Requires only id; adapts behavior based on whether name is present
//! fn display_user<F: user::Fields<id = Present>>(user: &User<F>) {
//! if let Some(name) = user.name.get() {
//! println!("User #{}: {}", user.id, name);
//! } else {
//! println!("User #{}", user.id);
//! }
//! }
//! ```
//!
//! ### Build instances incrementally
//!
//! The builder API infers field presence from the value type:
//!
//! ```ignore
//! # use structural_typing::{structural, presence::Present, access::Access};
//! #
//! # #[structural]
//! # struct User {
//! # id: u32,
//! # name: String,
//! # email: String,
//! # }
//! #
//! # fn display_user<F: user::Fields<id = Present>>(user: &User<F>) {
//! # if let Some(name) = user.name.get() {
//! # println!("User #{}: {}", user.id, name);
//! # } else {
//! # println!("User #{}", user.id);
//! # }
//! # }
//! #
//! let bob = user::empty().id(123);
//! display_user(&bob);
//!
//! let bob = bob.name("Bob".to_owned());
//! ```
//!
//! ### Serde integration
//!
//! Enable the `serde` feature to use structural types with serde.
//!
//! The `select!` macro creates concrete types, useful for serialization boundaries:
//!
//! ```ignore
//! use serde::{Deserialize, Serialize};
//!
//! #[structural]
//! #[derive(Serialize, Deserialize)]
//! struct User {
//! id: u32,
//! name: String,
//! email: String,
//! }
//!
//! fn insert_user<F: user::Fields<email = Present>>(
//! user: User<F>
//! ) -> User<select!(user: id, ..F)> {
//! // Insert to database, get generated ID
//! user.id(42)
//! }
//!
//! let json = r#"{"name": "Alice", "email": "alice@example.com"}"#;
//! // name optional, email present, id absent
//! let req: User<select!(user: name?, email)> = serde_json::from_str(json)?;
//!
//! let response = insert_user(req);
//! let json = serde_json::to_string(&response)?;
//! // => {"id":42, "name": "Alice", "email": "alice@example.com"}
//! ```
//!
//! ### Extract and merge
//!
//! ```ignore
//! # use structural_typing::{structural, select};
//! #
//! # #[structural]
//! # struct User {
//! # id: u32,
//! # name: String,
//! # email: String,
//! # }
//! #
//! # let alice = user::empty()
//! # .id(42)
//! # .name("Alice".to_owned())
//! # .email("alice@example.com".to_owned());
//! #
//! let (credentials, id_only) = alice.extract::<select!(user: name, email)>();
//! assert_eq!(credentials.name, "Alice");
//! assert_eq!(id_only.id, 42);
//!
//! let alice = credentials.merge(id_only);
//! // Merged values override existing values
//! let overridden = alice.merge(user::empty().id(21));
//! assert_eq!(overridden.name, "Alice");
//! assert_eq!(overridden.id, 21);
//! ```
//!
//! ### Nested schemas
//!
//! Schemas can contain other structural types:
//!
//! ```ignore
//! use structural_typing::{structural, presence::Present};
//!
//! #[structural]
//! struct Address {
//! street: String,
//! city: String,
//! zip: String,
//! }
//!
//! #[structural]
//! struct User<A: address::Fields> {
//! id: u32,
//! name: String,
//! address: Address<A>,
//! }
//!
//! // Require specific nested fields
//! fn ship<A, F>(user: User<A, F>)
//! where
//! A: address::Fields<street = Present, city = Present>,
//! F: user::Fields<id = Present, address = Present>
//! {
//! println!("Shipping to {} at: {}, {}",
//! user.id, user.address.street, user.address.city);
//! }
//! ```
//!
//! #### Nested setters
//!
//! Use `#[nested(...)]` to generate convenient setters for nested struct fields:
//!
//! ```ignore
//! use structural_typing::{structural, select};
//!
//! #[structural]
//! struct User<A: address::Fields = select!(address: all-)> {
//! id: u32,
//! name: String,
//! #[nested(address: street, city, zip)]
//! address: Address<A>,
//! }
//!
//! // Setters are generated with field_nested_field naming
//! let user = user::empty()
//! .id(1)
//! .name("Alice".to_owned())
//! .address(address::empty())
//! .address_city("Seattle".to_owned())
//! .address_street("Main St".to_owned());
//!
//! assert_eq!(user.address.city, "Seattle");
//! assert_eq!(user.address.street, "Main St");
//! ```
//!
//! Nested setters work by extracting the nested field, updating it, and merging back—preserving all
//! other fields' presence states. This makes them compatible with `extract()` and other structural operations.
//!
//! **Limitations**:
//! - `#[nested]` requires the parent struct to have at least 2 fields because the
//! implementation uses the spread operator, which needs other fields to preserve. Single-field parent
//! structs will produce a compile error.
//! - Merge operations between instances with different nested field presence states are not supported.
//! The nested struct's generic parameter must match for merge to work.
//!
//! See the [examples](https://github.com/Crazytieguy/structural-typing-rs/tree/master/examples)
//! directory for more comprehensive usage.
//!
//! ## Design
//!
//! The `#[structural]` macro generates a module containing a `Fields` trait with associated types
//! for each field. Field presence is tracked through type-level markers (`Present`, `Optional`,
//! `Absent`) that implement the `Presence` trait. Functions express requirements through trait bounds,
//! and the builder API uses type inference to determine field states.
//!
//! This approach enables:
//! - **Compile-time verification**: All field requirements checked during compilation
//! - **Zero runtime overhead**: No dynamic checks or boxing
//! - **API evolution**: Relaxing requirements is backward compatible
//! - **Flexible composition**: Merge, extract, and transform with compile-time guarantees
/// Runtime field access trait for checking presence and getting values.
/// Traits for splitting structs into selected fields and remainder.
/// Type-level presence markers and traits for field state tracking.
/// Serde integration helpers.
pub use structural;
/// Construct a `FieldSet` by selecting fields from a module.
///
/// # Presence States
///
/// | Suffix | Presence | Field Type |
/// |--------|----------|------------|
/// | (none) | Present | `T` |
/// | `?` | Optional | `Option<T>` |
/// | `-` | Absent | `PhantomData<T>` |
///
/// Access is always `user.field`. In generic code use `.get()` from the `Access` trait.
///
/// # Syntax Reference
///
/// | Pattern | Description |
/// |---------|-------------|
/// | `select!(mod: field)` | field is Present (required) |
/// | `select!(mod: field?)` | field is Optional |
/// | `select!(mod: field-)` | field is Absent |
/// | `select!(mod: field<P>)` | field has custom presence type P |
/// | `select!(mod: all)` | all fields Present |
/// | `select!(mod: all?)` | all fields Optional |
/// | `select!(mod: all-)` | all fields Absent |
/// | `select!(mod: f1, f2?)` | multiple fields (f1=Present, f2=Optional) |
/// | `select!(mod: f, ..F)` | spread: f=Present, rest inherited from F |
/// | `select!(mod: f?, ..F)` | spread: f=Optional, rest inherited from F |
/// | `select!(mod: f, all-)` | f=Present, all others Absent |
///
/// # Examples
///
/// ```ignore
/// // Concrete types for API boundaries
/// type Create = select!(user: name, email); // Both required
/// type Update = select!(user: name?, email?); // Both optional
///
/// // Generic: add id field to any existing fields
/// type WithId<F: user::Fields> = select!(user: id, ..F);
///
/// // Function using concrete type
/// fn create(user: User<Create>) -> User<WithId<Create>> { ... }
/// ```