rws-macros 17.31.0

Procedural macros for rust-web-server (route attributes)
Documentation
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
//! Procedural macro attributes for [rust-web-server](https://crates.io/crates/rust-web-server).
//!
//! Import via the main crate with `features = ["macros"]`:
//!
//! ```toml
//! [dependencies]
//! rust-web-server = { version = "18", features = ["macros"] }
//! ```
//!
//! # Attributes
//!
//! | Attribute | Equivalent |
//! |-----------|------------|
//! | `#[route(GET, "/path")]` | generic; any method |
//! | `#[get("/path")]` | shorthand for GET |
//! | `#[post("/path")]` | shorthand for POST |
//! | `#[put("/path")]` | shorthand for PUT |
//! | `#[patch("/path")]` | shorthand for PATCH |
//! | `#[delete("/path")]` | shorthand for DELETE |
//!
//! On a classic handler — `fn(&Request, &PathParams, &ConnectionInfo[, &S])`
//! — the attributes add a `Route: METHOD /path` doc comment and leave the
//! function unchanged; register it with `routes!` or `.get()`, `.post()`, etc.
//!
//! On any other function (18.28.0) the arguments are extractors
//! (`Path<T>`, `Query<T>`, `Json<T>`, `Form<T>`, `State<S>`, `&S`, `Body`,
//! `BodyText`, `RequestHeaders`, `&Request`, `&ConnectionInfo`, any
//! `FromRequest` type) and the return type anything `IntoResponse`: the
//! function becomes a unit struct implementing
//! `rust_web_server::handler::{Handler, AsyncHandler, RouteSpec}`, registered
//! with `.route(handler)`, and the function itself stays callable as
//! `handler::call(…)`. The route's parameters are checked against the
//! `Path` argument at compile time. See `rust_web_server::handler`.
//!
//! ```ignore
//! #[get("/posts/{id}")]
//! fn show_post(Path(id): Path<u64>, State(db): State<Db>) -> Result<Json<Post>, AppError> { … }
//!
//! let app = App::with_state(db).route(show_post);
//! ```
//!
//! ## `#[derive(FromPath)]`
//!
//! A struct with one `FromStr` field per route parameter, named after it,
//! for `Path<T>`.
//!
//! ## `#[derive(Config)]`
//!
//! Generates `fn load() -> Result<Self, String>` that reads environment variables
//! and parses them into the annotated field types. See `rust_web_server::config_binding`.
//!
//! ## `#[derive(Factory)]` (17.30.0)
//!
//! Beside `#[derive(Model)]`: `T::factory()` for tests, building instances
//! with default field values. See `rust_web_server::test_client::factory`.

use proc_macro::TokenStream;
use quote::quote;
use syn::{
    parse::{Parse, ParseStream},
    parse_macro_input, Data, DeriveInput, Fields, Ident, ItemFn, Lit, LitInt, LitStr, Token,
};

mod handler;

// ── Shared helper ─────────────────────────────────────────────────────────────

fn annotate(method: &str, path: LitStr, func: ItemFn) -> TokenStream {
    handler::expand(method, path, func).into()
}

// ── #[route(METHOD, "/path")] ─────────────────────────────────────────────────

struct RouteArgs {
    method: Ident,
    path: LitStr,
}

impl Parse for RouteArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let method: Ident = input.parse()?;
        input.parse::<Token![,]>()?;
        let path: LitStr = input.parse()?;
        Ok(RouteArgs { method, path })
    }
}

/// Annotate a handler function with its HTTP method and path.
///
/// On a classic handler (`&Request, &PathParams, &ConnectionInfo[, state]`)
/// it adds a `Route: METHOD /path` doc comment and otherwise leaves the
/// function unchanged; register it with `routes!` or `.get()`. On a typed
/// handler (extractor arguments) it generates the adapter — see the crate
/// docs and `rust_web_server::handler`.
///
/// # Example
///
/// ```ignore
/// use rust_web_server::route;
/// use rust_web_server::request::Request;
/// use rust_web_server::router::PathParams;
/// use rust_web_server::server::ConnectionInfo;
/// use rust_web_server::response::Response;
/// use std::sync::Arc;
///
/// struct Db;
///
/// #[route(GET, "/users/:id")]
/// fn get_user(
///     req: &Request,
///     params: &PathParams,
///     conn: &ConnectionInfo,
///     state: &Arc<Db>,
/// ) -> Response {
///     let id = params.get("id").unwrap_or("0");
///     Response::new()
/// }
/// ```
#[proc_macro_attribute]
pub fn route(args: TokenStream, input: TokenStream) -> TokenStream {
    let RouteArgs { method, path } = parse_macro_input!(args as RouteArgs);
    let func = parse_macro_input!(input as ItemFn);
    annotate(&method.to_string(), path, func)
}

// ── #[get("/path")], #[post("/path")], … ─────────────────────────────────────

/// Shorthand for `#[route(GET, "/path")]`.
///
/// # Example
///
/// ```ignore
/// use rust_web_server::get;
/// # use rust_web_server::request::Request;
/// # use rust_web_server::router::PathParams;
/// # use rust_web_server::server::ConnectionInfo;
/// # use rust_web_server::response::Response;
///
/// #[get("/healthz")]
/// fn health(_: &Request, _: &PathParams, _: &ConnectionInfo) -> Response {
///     Response::new()
/// }
/// ```
#[proc_macro_attribute]
pub fn get(args: TokenStream, input: TokenStream) -> TokenStream {
    let path = parse_macro_input!(args as LitStr);
    let func = parse_macro_input!(input as ItemFn);
    annotate("GET", path, func)
}

/// Shorthand for `#[route(POST, "/path")]`.
#[proc_macro_attribute]
pub fn post(args: TokenStream, input: TokenStream) -> TokenStream {
    let path = parse_macro_input!(args as LitStr);
    let func = parse_macro_input!(input as ItemFn);
    annotate("POST", path, func)
}

/// Shorthand for `#[route(PUT, "/path")]`.
#[proc_macro_attribute]
pub fn put(args: TokenStream, input: TokenStream) -> TokenStream {
    let path = parse_macro_input!(args as LitStr);
    let func = parse_macro_input!(input as ItemFn);
    annotate("PUT", path, func)
}

/// Shorthand for `#[route(PATCH, "/path")]`.
#[proc_macro_attribute]
pub fn patch(args: TokenStream, input: TokenStream) -> TokenStream {
    let path = parse_macro_input!(args as LitStr);
    let func = parse_macro_input!(input as ItemFn);
    annotate("PATCH", path, func)
}

/// Shorthand for `#[route(DELETE, "/path")]`.
#[proc_macro_attribute]
pub fn delete(args: TokenStream, input: TokenStream) -> TokenStream {
    let path = parse_macro_input!(args as LitStr);
    let func = parse_macro_input!(input as ItemFn);
    annotate("DELETE", path, func)
}

// ── #[derive(FromPath)] ───────────────────────────────────────────────────────

/// Derive `rust_web_server::handler::FromPath` for a struct with named
/// fields: one route parameter per field, by name, each parsed with
/// `FromStr`. A typed handler's route must have exactly these parameters
/// (checked at compile time).
///
/// ```ignore
/// #[derive(rust_web_server::FromPath)]
/// struct PostKey { id: u64, slug: String }
///
/// #[get("/posts/{id}/{slug}")]
/// fn post(Path(key): Path<PostKey>) -> String { format!("{} {}", key.id, key.slug) }
/// ```
#[proc_macro_derive(FromPath)]
pub fn derive_from_path(input: TokenStream) -> TokenStream {
    let ast = parse_macro_input!(input as DeriveInput);
    handler::derive_from_path(ast)
        .unwrap_or_else(|e| e.to_compile_error())
        .into()
}

// ── #[derive(FromRequest)] ────────────────────────────────────────────────────

/// Derive `FromRequest` for a named-field struct.
///
/// Each field must implement `FromRequest`. Fields are extracted in declaration
/// order; the first failure short-circuits and returns that error response.
///
/// # Example
///
/// ```ignore
/// use rust_web_server::extract::{BodyText, Query};
///
/// #[derive(rust_web_server::FromRequest)]
/// struct Payload {
///     body: BodyText,
///     params: Query,
/// }
/// ```
#[proc_macro_derive(FromRequest)]
pub fn derive_from_request(input: TokenStream) -> TokenStream {
    let ast = parse_macro_input!(input as DeriveInput);
    impl_from_request(ast)
        .unwrap_or_else(|e| e.to_compile_error())
        .into()
}

// ── #[derive(Validate)] ───────────────────────────────────────────────────────

/// Derive `Validate` for a named-field struct.
///
/// Annotate fields with `#[validate(...)]` rules. All failures are collected
/// before returning, so the caller sees every invalid field in one response.
///
/// # Supported validators
///
/// | Syntax | Checks |
/// |--------|--------|
/// | `length(min = N)` | `field.chars().count() >= N` |
/// | `length(max = N)` | `field.chars().count() <= N` |
/// | `length(min = N, max = N)` | both bounds |
/// | `range(min = N)` | `field as f64 >= N` |
/// | `range(max = N)` | `field as f64 <= N` |
/// | `range(min = N, max = N)` | both bounds |
/// | `email` | local part, `@`, domain with `.` |
/// | `required` | `!field.is_empty()` |
/// | `url` | starts with `http://` or `https://` |
///
/// # Example
///
/// ```ignore
/// #[derive(rust_web_server::Validate)]
/// struct CreateUser {
///     #[validate(length(min = 1, max = 50))]
///     name: String,
///     #[validate(email)]
///     email: String,
///     #[validate(range(min = 0, max = 150))]
///     age: u8,
/// }
/// ```
#[proc_macro_derive(Validate, attributes(validate))]
pub fn derive_validate(input: TokenStream) -> TokenStream {
    let ast = parse_macro_input!(input as DeriveInput);
    impl_validate(ast)
        .unwrap_or_else(|e| e.to_compile_error())
        .into()
}

fn impl_validate(input: DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
    let span = input.ident.span();
    let name = &input.ident;

    let fields = match &input.data {
        Data::Struct(s) => match &s.fields {
            Fields::Named(f) => &f.named,
            _ => {
                return Err(syn::Error::new(
                    span,
                    "#[derive(Validate)] only supports structs with named fields",
                ))
            }
        },
        _ => {
            return Err(syn::Error::new(
                span,
                "#[derive(Validate)] can only be derived on structs",
            ))
        }
    };

    let mut all_checks: Vec<proc_macro2::TokenStream> = Vec::new();

    for field in fields {
        let field_ident = field.ident.as_ref().unwrap();
        let field_name = field_ident.to_string();
        for attr in &field.attrs {
            if attr.path().is_ident("validate") {
                let checks = generate_field_checks(attr, field_ident, &field_name)?;
                all_checks.extend(checks);
            }
        }
    }

    Ok(quote! {
        const _: () = {
            use ::rust_web_server as _rws;
            impl _rws::validate::Validate for #name {
                fn validate(&self) -> ::core::result::Result<(), _rws::validate::ValidationErrors> {
                    let mut __errors = _rws::validate::ValidationErrors::new();
                    #(#all_checks)*
                    if __errors.is_empty() {
                        ::core::result::Result::Ok(())
                    } else {
                        ::core::result::Result::Err(__errors)
                    }
                }
            }
        };
    })
}

fn generate_field_checks(
    attr: &syn::Attribute,
    field_ident: &syn::Ident,
    field_name: &str,
) -> syn::Result<Vec<proc_macro2::TokenStream>> {
    let mut checks: Vec<proc_macro2::TokenStream> = Vec::new();

    attr.parse_nested_meta(|meta| {
        if meta.path.is_ident("email") {
            let msg = format!("{field_name} must be a valid email address");
            checks.push(quote! {
                if !_rws::validate::is_email(&self.#field_ident) {
                    __errors.add(#field_name, #msg);
                }
            });
        } else if meta.path.is_ident("required") {
            let msg = format!("{field_name} must not be empty");
            checks.push(quote! {
                if self.#field_ident.is_empty() {
                    __errors.add(#field_name, #msg);
                }
            });
        } else if meta.path.is_ident("url") {
            let msg = format!("{field_name} must be a valid URL (http:// or https://)");
            checks.push(quote! {
                if !_rws::validate::is_url(&self.#field_ident) {
                    __errors.add(#field_name, #msg);
                }
            });
        } else if meta.path.is_ident("length") {
            let mut min: Option<u64> = None;
            let mut max: Option<u64> = None;
            meta.parse_nested_meta(|inner| {
                if inner.path.is_ident("min") {
                    let lit: LitInt = inner.value()?.parse()?;
                    min = Some(lit.base10_parse()?);
                } else if inner.path.is_ident("max") {
                    let lit: LitInt = inner.value()?.parse()?;
                    max = Some(lit.base10_parse()?);
                } else {
                    return Err(inner.error("expected `min` or `max`"));
                }
                Ok(())
            })?;

            let mut len_checks: Vec<proc_macro2::TokenStream> = Vec::new();
            if let Some(n) = min {
                let msg = format!("{field_name} must be at least {n} character(s) long");
                let n_lit = proc_macro2::Literal::usize_suffixed(n as usize);
                len_checks.push(quote! {
                    if __len < #n_lit { __errors.add(#field_name, #msg); }
                });
            }
            if let Some(n) = max {
                let msg = format!("{field_name} must be at most {n} character(s) long");
                let n_lit = proc_macro2::Literal::usize_suffixed(n as usize);
                len_checks.push(quote! {
                    if __len > #n_lit { __errors.add(#field_name, #msg); }
                });
            }
            checks.push(quote! {
                {
                    let __len = self.#field_ident.chars().count();
                    #(#len_checks)*
                }
            });
        } else if meta.path.is_ident("range") {
            let mut min: Option<f64> = None;
            let mut max: Option<f64> = None;
            meta.parse_nested_meta(|inner| {
                if inner.path.is_ident("min") {
                    min = Some(lit_to_f64(&inner.value()?.parse::<Lit>()?)?);
                } else if inner.path.is_ident("max") {
                    max = Some(lit_to_f64(&inner.value()?.parse::<Lit>()?)?);
                } else {
                    return Err(inner.error("expected `min` or `max`"));
                }
                Ok(())
            })?;

            let mut rng_checks: Vec<proc_macro2::TokenStream> = Vec::new();
            if let Some(n) = min {
                let msg = format!("{field_name} must be at least {n}");
                let n_lit = proc_macro2::Literal::f64_suffixed(n);
                rng_checks.push(quote! {
                    if __val < #n_lit { __errors.add(#field_name, #msg); }
                });
            }
            if let Some(n) = max {
                let msg = format!("{field_name} must be at most {n}");
                let n_lit = proc_macro2::Literal::f64_suffixed(n);
                rng_checks.push(quote! {
                    if __val > #n_lit { __errors.add(#field_name, #msg); }
                });
            }
            checks.push(quote! {
                {
                    let __val = self.#field_ident as f64;
                    #(#rng_checks)*
                }
            });
        } else {
            return Err(meta.error(
                "unknown validator; expected: email, required, url, length, range",
            ));
        }
        Ok(())
    })?;

    Ok(checks)
}

fn lit_to_f64(lit: &Lit) -> syn::Result<f64> {
    match lit {
        Lit::Float(f) => Ok(f.base10_parse()?),
        Lit::Int(i) => Ok(i.base10_parse::<i64>()? as f64),
        _ => Err(syn::Error::new_spanned(lit, "expected a numeric literal")),
    }
}

fn impl_from_request(input: DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
    let span = input.ident.span();
    let name = &input.ident;

    let fields = match &input.data {
        Data::Struct(s) => match &s.fields {
            Fields::Named(f) => &f.named,
            _ => {
                return Err(syn::Error::new(
                    span,
                    "#[derive(FromRequest)] only supports structs with named fields",
                ))
            }
        },
        _ => {
            return Err(syn::Error::new(
                span,
                "#[derive(FromRequest)] can only be derived on structs",
            ))
        }
    };

    let extractions = fields.iter().map(|f| {
        let ident = f.ident.as_ref().unwrap();
        let ty = &f.ty;
        quote! {
            let #ident = <#ty as _rws::extract::FromRequest>::from_request(__req)?;
        }
    });

    let field_names = fields.iter().map(|f| f.ident.as_ref().unwrap());

    Ok(quote! {
        const _: () = {
            use ::rust_web_server as _rws;
            impl _rws::extract::FromRequest for #name {
                fn from_request(__req: &_rws::request::Request) -> ::core::result::Result<Self, _rws::response::Response> {
                    #(#extractions)*
                    ::core::result::Result::Ok(#name { #(#field_names),* })
                }
            }
        };
    })
}

// ── #[derive(Config)] ─────────────────────────────────────────────────────────

/// Derive `load() -> Result<Self, String>` for a configuration struct.
///
/// Each field is bound to an environment variable. The env var name is derived
/// from the field name (uppercased) plus an optional struct-level prefix.
///
/// # Struct-level attribute
///
/// ```text
/// #[config(prefix = "APP_")]
/// ```
///
/// When set, every field's env var key is `prefix + key`.
///
/// # Field-level attribute
///
/// ```text
/// #[config(env = "PORT", default = "8080")]
/// ```
///
/// | Option | Meaning |
/// |--------|---------|
/// | `env = "KEY"` | explicit env var name (prefix is still prepended) |
/// | `default = "v"` | fallback when the env var is absent |
///
/// If `env` is omitted the field name is uppercased and used as the key.
/// Wrapping the field type in `Option<T>` makes it optional (returns `None` when absent).
///
/// # Example
///
/// ```ignore
/// #[derive(rust_web_server::Config)]
/// #[config(prefix = "APP_")]
/// struct AppConfig {
///     #[config(env = "PORT", default = "8080")]
///     port: u16,
///     #[config(env = "DATABASE_URL")]
///     database_url: String,
///     #[config(env = "DEBUG")]
///     debug: Option<bool>,
/// }
///
/// let cfg = AppConfig::load().unwrap();
/// ```
#[proc_macro_derive(Config, attributes(config))]
pub fn derive_config(input: TokenStream) -> TokenStream {
    let ast = parse_macro_input!(input as DeriveInput);
    impl_config(ast)
        .unwrap_or_else(|e| e.to_compile_error())
        .into()
}

fn impl_config(input: DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
    let span = input.ident.span();
    let name = &input.ident;

    // Parse optional struct-level prefix: #[config(prefix = "...")]
    let prefix = parse_config_prefix(&input.attrs)?;

    let fields = match &input.data {
        Data::Struct(s) => match &s.fields {
            Fields::Named(f) => &f.named,
            _ => {
                return Err(syn::Error::new(
                    span,
                    "#[derive(Config)] only supports structs with named fields",
                ))
            }
        },
        _ => {
            return Err(syn::Error::new(
                span,
                "#[derive(Config)] can only be derived on structs",
            ))
        }
    };

    let mut field_loads: Vec<proc_macro2::TokenStream> = Vec::new();
    let mut field_names: Vec<&syn::Ident> = Vec::new();

    for field in fields {
        let ident = field.ident.as_ref().unwrap();
        field_names.push(ident);

        // Parse field-level #[config(env = "...", default = "...")]
        let (env_key, default) = parse_field_config(&field.attrs, ident, &prefix)?;

        let is_option = is_option_type(&field.ty);

        let load_expr = if is_option {
            quote! {
                _rws::config_binding::load_optional(&#env_key)?
            }
        } else if let Some(default_str) = default {
            quote! {
                _rws::config_binding::load_with_default(&#env_key, #default_str)?
            }
        } else {
            quote! {
                _rws::config_binding::load_required(&#env_key)?
            }
        };

        field_loads.push(quote! {
            let #ident = #load_expr;
        });
    }

    Ok(quote! {
        impl #name {
            /// Load configuration from environment variables.
            pub fn load() -> ::core::result::Result<Self, ::std::string::String> {
                use ::rust_web_server as _rws;
                #(#field_loads)*
                ::core::result::Result::Ok(#name {
                    #(#field_names),*
                })
            }
        }
    })
}

/// Return `(env_key_expr, Option<default_str>)` for a field.
/// `env_key_expr` is a `proc_macro2::TokenStream` that evaluates to a `String`.
fn parse_field_config(
    attrs: &[syn::Attribute],
    ident: &syn::Ident,
    prefix: &str,
) -> syn::Result<(proc_macro2::TokenStream, Option<LitStr>)> {
    let mut env_name: Option<String> = None;
    let mut default: Option<LitStr> = None;

    for attr in attrs {
        if !attr.path().is_ident("config") {
            continue;
        }
        attr.parse_nested_meta(|meta| {
            if meta.path.is_ident("env") {
                let lit: LitStr = meta.value()?.parse()?;
                env_name = Some(lit.value());
            } else if meta.path.is_ident("default") {
                default = Some(meta.value()?.parse()?);
            } else {
                return Err(meta.error("unknown config key; expected `env` or `default`"));
            }
            Ok(())
        })?;
    }

    let key = format!(
        "{}{}",
        prefix,
        env_name.unwrap_or_else(|| ident.to_string().to_uppercase())
    );

    Ok((quote! { #key }, default))
}

/// Parse `#[config(prefix = "...")]` from struct attributes, returning the prefix string.
fn parse_config_prefix(attrs: &[syn::Attribute]) -> syn::Result<String> {
    let mut prefix = String::new();
    for attr in attrs {
        if !attr.path().is_ident("config") {
            continue;
        }
        attr.parse_nested_meta(|meta| {
            if meta.path.is_ident("prefix") {
                let lit: LitStr = meta.value()?.parse()?;
                prefix = lit.value();
            } else {
                return Err(meta.error("unknown struct config key; expected `prefix`"));
            }
            Ok(())
        })?;
    }
    Ok(prefix)
}

/// Return true if `ty` is `Option<_>`.
fn is_option_type(ty: &syn::Type) -> bool {
    if let syn::Type::Path(tp) = ty {
        if let Some(seg) = tp.path.segments.last() {
            return seg.ident == "Option";
        }
    }
    false
}

// ── #[derive(Model)] ──────────────────────────────────────────────────────────

/// Derive `rust_web_server::model::Model` for a struct.
///
/// # Struct attributes
///
/// | Attribute | Meaning |
/// |---|---|
/// | `#[table(name = "tbl")]` | Override table name (default: struct name lowercased) |
/// | `#[timestamps]` | `save` sets the `created_at` and `updated_at` fields' columns (17.31.0) |
/// | `#[soft_delete]` | `delete` sets the `deleted_at` field's column (an `Option`); queries skip such rows (17.31.0) |
///
/// # Field attributes
///
/// | Attribute | Meaning |
/// |---|---|
/// | `#[primary_key]` | Mark as primary key (`i64`, `i32`, `String` or `Uuid`) |
/// | `#[primary_key(auto_increment)]` | Auto-increment primary key |
/// | `#[column(name = "col")]` | Override column name |
/// | `#[column(unique)]` | Mark column unique (informational) |
/// | `#[version]` | Optimistic-locking version (an integer), checked and incremented by `save` (17.31.0) |
/// | `#[ignore]` | Exclude from DB mapping |
///
/// `T::repository(&pool)` is keyed by `i64` for an integer primary key of
/// any width (as before 17.31.0) and by the field's type otherwise
/// (`String`, `Uuid`).
///
/// # Example
///
/// ```ignore
/// #[derive(rust_web_server::Model, Debug, Clone)]
/// #[table(name = "users")]
/// pub struct User {
///     #[primary_key(auto_increment)]
///     pub id: i64,
///     #[column(name = "first_name")]
///     pub name: String,
///     pub email: String,
///     #[ignore]
///     pub display_label: String,
/// }
///
/// // Conventions the repository maintains (17.31.0):
/// #[derive(rust_web_server::Model, Debug, Clone)]
/// #[table(name = "posts")]
/// #[timestamps]
/// #[soft_delete]
/// pub struct Post {
///     #[primary_key]
///     pub id: rust_web_server::model::Uuid, // Uuid::NIL → save picks a v7
///     pub title: String,
///     #[version]
///     pub lock_version: i64,
///     pub created_at: rust_web_server::model::Timestamp,
///     pub updated_at: rust_web_server::model::Timestamp,
///     pub deleted_at: Option<rust_web_server::model::Timestamp>,
/// }
/// ```
#[proc_macro_derive(Model, attributes(table, column, primary_key, timestamps, soft_delete, version))]
pub fn derive_model(input: TokenStream) -> TokenStream {
    let ast = parse_macro_input!(input as DeriveInput);
    impl_model(ast)
        .unwrap_or_else(|e| e.to_compile_error())
        .into()
}

fn impl_model(input: DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
    let span = input.ident.span();
    let struct_name = &input.ident;

    // ── Determine table name ──────────────────────────────────────────────────
    let table_name = parse_table_name(&input.attrs, struct_name)?;

    let fields = match &input.data {
        Data::Struct(s) => match &s.fields {
            Fields::Named(f) => &f.named,
            _ => {
                return Err(syn::Error::new(
                    span,
                    "#[derive(Model)] only supports structs with named fields",
                ))
            }
        },
        _ => {
            return Err(syn::Error::new(
                span,
                "#[derive(Model)] can only be derived on structs",
            ))
        }
    };

    // ── Parse field metadata ──────────────────────────────────────────────────
    struct FieldMeta {
        field_ident: syn::Ident,
        col_name: String,
        #[allow(dead_code)]
        is_pk: bool,
        is_auto_increment: bool,
        is_ignored: bool,
        is_version: bool,
        ty: syn::Type,
    }

    let mut pk_field: Option<FieldMeta> = None;
    let mut regular_fields: Vec<FieldMeta> = Vec::new();

    for field in fields {
        let ident = field.ident.as_ref().unwrap().clone();
        let mut col_name = ident.to_string();
        let mut is_pk = false;
        let mut is_auto_increment = false;
        let mut is_ignored = false;
        let mut is_version = false;

        for attr in &field.attrs {
            if attr.path().is_ident("ignore") {
                is_ignored = true;
            } else if attr.path().is_ident("version") {
                is_version = true;
            } else if attr.path().is_ident("primary_key") {
                is_pk = true;
                // Check for (auto_increment)
                let _ = attr.parse_nested_meta(|meta| {
                    if meta.path.is_ident("auto_increment") {
                        is_auto_increment = true;
                    }
                    Ok(())
                });
            } else if attr.path().is_ident("column") {
                let _ = attr.parse_nested_meta(|meta| {
                    if meta.path.is_ident("name") {
                        let lit: LitStr = meta.value()?.parse()?;
                        col_name = lit.value();
                    }
                    // unique / nullable are informational — ignore
                    Ok(())
                });
            }
        }

        let meta = FieldMeta {
            field_ident: ident,
            col_name,
            is_pk,
            is_auto_increment,
            is_ignored,
            is_version,
            ty: field.ty.clone(),
        };

        if is_version && (is_pk || is_ignored) {
            return Err(syn::Error::new_spanned(field, "#[version] goes on a mapped integer field, not the #[primary_key] or an #[ignore]d one"));
        }
        if is_pk {
            pk_field = Some(meta);
        } else {
            regular_fields.push(meta);
        }
    }

    let pk = pk_field.ok_or_else(|| {
        syn::Error::new(span, "#[derive(Model)] requires exactly one #[primary_key] field")
    })?;

    // ── Conventions: #[timestamps], #[soft_delete], #[version] ───────────────
    let has_struct_attr = |name: &str| input.attrs.iter().any(|a| a.path().is_ident(name));
    let column_of = |field: &str, attr: &str, must_be_option: bool| -> syn::Result<String> {
        let found = regular_fields.iter().find(|f| f.field_ident == field && !f.is_ignored).ok_or_else(|| {
            syn::Error::new(span, format!("#[{attr}] needs a mapped field named `{field}` (e.g. `{field}: {}`)", if must_be_option { "Option<Timestamp>" } else { "Timestamp" }))
        })?;
        if must_be_option && !is_option_type(&found.ty) {
            return Err(syn::Error::new_spanned(&found.ty, format!("#[{attr}]: `{field}` must be an Option (NULL means not deleted), e.g. Option<Timestamp>")));
        }
        Ok(found.col_name.clone())
    };
    // Only the conventions in use become methods: a model without them
    // expands exactly as before 17.31.0, so it still compiles against a
    // rust-web-server whose `Model` trait predates them.
    let opt = |name: &str, c: Option<String>| -> proc_macro2::TokenStream {
        let name = syn::Ident::new(name, proc_macro2::Span::call_site());
        match c {
            Some(c) => quote! {
                fn #name() -> ::core::option::Option<&'static str> {
                    ::core::option::Option::Some(#c)
                }
            },
            None => quote! {},
        }
    };
    let (created_at, updated_at) = if has_struct_attr("timestamps") {
        (Some(column_of("created_at", "timestamps", false)?), Some(column_of("updated_at", "timestamps", false)?))
    } else {
        (None, None)
    };
    let deleted_at = if has_struct_attr("soft_delete") { Some(column_of("deleted_at", "soft_delete", true)?) } else { None };
    let versions: Vec<&FieldMeta> = regular_fields.iter().filter(|f| f.is_version).collect();
    if versions.len() > 1 {
        return Err(syn::Error::new(span, "#[derive(Model)] takes at most one #[version] field"));
    }
    let version = versions.first().map(|f| f.col_name.clone());
    let (created_at, updated_at, deleted_at, version) = (
        opt("created_at_column", created_at),
        opt("updated_at_column", updated_at),
        opt("soft_delete_column", deleted_at),
        opt("version_column", version),
    );

    // `repository()`'s key: i64 for any integer key (as before), else the
    // key's own type.
    let pk_ty = &pk.ty;
    let is_integer = matches!(pk_ty, syn::Type::Path(tp) if tp.qself.is_none() && tp.path.segments.len() == 1
        && ["i8", "i16", "i32", "i64", "isize", "u8", "u16", "u32", "u64", "usize"].iter().any(|t| tp.path.segments[0].ident == t));
    let repo_key = if is_integer { quote! { i64 } } else { quote! { #pk_ty } };

    // ── column_names (all mapped fields, including PK) ────────────────────────
    let mut all_col_names: Vec<String> = Vec::new();
    all_col_names.push(pk.col_name.clone());
    for f in regular_fields.iter().filter(|f| !f.is_ignored) {
        all_col_names.push(f.col_name.clone());
    }

    let pk_col_name = pk.col_name.clone();
    let pk_field_ident = &pk.field_ident;
    let auto_inc = pk.is_auto_increment;

    // ── from_row body ─────────────────────────────────────────────────────────
    let pk_from_row = {
        let col = &pk.col_name;
        let fident = &pk.field_ident;
        quote! { #fident: row.get(#col)? }
    };

    let regular_from_row: Vec<proc_macro2::TokenStream> = fields
        .iter()
        .filter(|f| {
            let ident_str = f.ident.as_ref().unwrap().to_string();
            // Skip the PK field (handled separately) and ignored fields.
            let is_pk_field = ident_str == pk_field_ident.to_string();
            !is_pk_field
        })
        .map(|f| {
            let fident = f.ident.as_ref().unwrap();
            // Check if ignored
            let is_ignored = f.attrs.iter().any(|a| a.path().is_ident("ignore"));
            if is_ignored {
                quote! { #fident: ::core::default::Default::default() }
            } else {
                // Determine column name override
                let mut col = fident.to_string();
                for attr in &f.attrs {
                    if attr.path().is_ident("column") {
                        let _ = attr.parse_nested_meta(|meta| {
                            if meta.path.is_ident("name") {
                                if let Ok(lit) = meta.value()?.parse::<LitStr>() {
                                    col = lit.value();
                                }
                            }
                            Ok(())
                        });
                    }
                }
                quote! { #fident: row.get(#col)? }
            }
        })
        .collect();

    // ── to_values body ────────────────────────────────────────────────────────
    let pk_to_values = {
        let col = &pk.col_name;
        quote! {
            (#col, ::rust_web_server::model::ToColumn::to_column(&self.#pk_field_ident))
        }
    };

    let regular_to_values: Vec<proc_macro2::TokenStream> = fields
        .iter()
        .filter(|f| {
            let ident_str = f.ident.as_ref().unwrap().to_string();
            let is_pk_field = ident_str == pk_field_ident.to_string();
            let is_ignored = f.attrs.iter().any(|a| a.path().is_ident("ignore"));
            !is_pk_field && !is_ignored
        })
        .map(|f| {
            let fident = f.ident.as_ref().unwrap();
            let mut col = fident.to_string();
            for attr in &f.attrs {
                if attr.path().is_ident("column") {
                    let _ = attr.parse_nested_meta(|meta| {
                        if meta.path.is_ident("name") {
                            if let Ok(lit) = meta.value()?.parse::<LitStr>() {
                                col = lit.value();
                            }
                        }
                        Ok(())
                    });
                }
            }
            quote! {
                (#col, ::rust_web_server::model::ToColumn::to_column(&self.#fident))
            }
        })
        .collect();

    // ── Generate impl ─────────────────────────────────────────────────────────
    Ok(quote! {
        impl ::rust_web_server::model::Model for #struct_name {
            fn table_name() -> &'static str {
                #table_name
            }

            fn column_names() -> &'static [&'static str] {
                &[#(#all_col_names),*]
            }

            fn primary_key_name() -> &'static str {
                #pk_col_name
            }

            fn primary_key_value(&self) -> ::rust_web_server::model::Value {
                ::rust_web_server::model::ToColumn::to_column(&self.#pk_field_ident)
            }

            fn primary_key_auto_increment() -> bool {
                #auto_inc
            }

            fn from_row(row: &::rust_web_server::model::ModelRow) -> ::core::result::Result<Self, ::rust_web_server::model::DbError> {
                ::core::result::Result::Ok(#struct_name {
                    #pk_from_row,
                    #(#regular_from_row),*
                })
            }

            fn to_values(&self) -> ::std::vec::Vec<(&'static str, ::rust_web_server::model::Value)> {
                vec![
                    #pk_to_values,
                    #(#regular_to_values),*
                ]
            }

            #created_at
            #updated_at
            #deleted_at
            #version
        }

        impl #struct_name {
            /// Create a `ModelRepository` tied to the given pool.
            pub fn repository(pool: &::rust_web_server::model::DbPool) -> ::rust_web_server::model::ModelRepository<#struct_name, #repo_key> {
                ::rust_web_server::model::ModelRepository::new(pool)
            }

            /// Create a `QueryBuilder` tied to the given pool.
            pub fn query(pool: &::rust_web_server::model::DbPool) -> ::rust_web_server::model::QueryBuilder<#struct_name> {
                ::rust_web_server::model::QueryBuilder::new(pool)
            }
        }
    })
}

fn parse_table_name(
    attrs: &[syn::Attribute],
    struct_name: &syn::Ident,
) -> syn::Result<String> {
    for attr in attrs {
        if attr.path().is_ident("table") {
            let mut name: Option<String> = None;
            attr.parse_nested_meta(|meta| {
                if meta.path.is_ident("name") {
                    let lit: LitStr = meta.value()?.parse()?;
                    name = Some(lit.value());
                }
                Ok(())
            })?;
            if let Some(n) = name {
                return Ok(n);
            }
        }
    }
    // Default: lowercased struct name.
    Ok(struct_name.to_string().to_lowercase())
}

// ── #[derive(Factory)] ────────────────────────────────────────────────────────

/// Derive `rust_web_server::test_client::factory::Factory` for a
/// `#[derive(Model)]` struct, and an inherent `T::factory()` returning a
/// `ModelFactory<T>` for tests (17.30.0).
///
/// Each field gets its type's `FactoryValue` default (numbers `0`, `bool`
/// `false`, `Option` `None`, a `String` the field's name plus a sequence
/// number), or `Default::default()` for a type without one and for
/// `#[ignore]` fields. The `#[primary_key]` is `0` when it's
/// `auto_increment`, else the sequence number. It reads the same attributes
/// as `#[derive(Model)]` and declares none of its own.
///
/// ```ignore
/// #[derive(rust_web_server::Model, rust_web_server::Factory, Debug, Clone)]
/// #[table(name = "users")]
/// pub struct User {
///     #[primary_key(auto_increment)]
///     pub id: i64,
///     pub name: String,
/// }
///
/// let user = User::factory().with(|u| u.name = "Ann".into()).create(&pool).await?;
/// ```
#[proc_macro_derive(Factory)]
pub fn derive_factory(input: TokenStream) -> TokenStream {
    let ast = parse_macro_input!(input as DeriveInput);
    impl_factory(ast)
        .unwrap_or_else(|e| e.to_compile_error())
        .into()
}

fn impl_factory(input: DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
    let span = input.ident.span();
    let struct_name = &input.ident;
    if !input.generics.params.is_empty() {
        return Err(syn::Error::new(span, "#[derive(Factory)] doesn't support generic structs"));
    }
    let fields = match &input.data {
        Data::Struct(s) => match &s.fields {
            Fields::Named(f) => &f.named,
            _ => return Err(syn::Error::new(span, "#[derive(Factory)] only supports structs with named fields")),
        },
        _ => return Err(syn::Error::new(span, "#[derive(Factory)] can only be derived on structs")),
    };

    let mut has_pk = false;
    let mut inits: Vec<proc_macro2::TokenStream> = Vec::new();
    for field in fields {
        let ident = field.ident.as_ref().unwrap();
        let ty = &field.ty;
        let name = ident.to_string();
        let name = name.strip_prefix("r#").unwrap_or(&name).to_string();
        let mut is_pk = false;
        let mut auto_increment = false;
        let mut ignored = false;
        for attr in &field.attrs {
            if attr.path().is_ident("ignore") {
                ignored = true;
            } else if attr.path().is_ident("primary_key") {
                is_pk = true;
                let _ = attr.parse_nested_meta(|meta| {
                    if meta.path.is_ident("auto_increment") {
                        auto_increment = true;
                    }
                    Ok(())
                });
            }
        }
        has_pk |= is_pk;
        let probe = quote! { (&&__Probe::<#ty>(::core::marker::PhantomData)) };
        inits.push(if ignored {
            quote! { #ident: ::core::default::Default::default() }
        } else if is_pk && !auto_increment {
            quote! { #ident: #probe.make_key(#name, __seq) }
        } else {
            quote! { #ident: #probe.make(#name, __seq) }
        });
    }
    if !has_pk {
        return Err(syn::Error::new(span, "#[derive(Factory)] needs the #[primary_key] field of #[derive(Model)]"));
    }

    Ok(quote! {
        impl ::rust_web_server::test_client::factory::Factory for #struct_name {
            fn factory_default(__seq: u64) -> Self {
                #[allow(unused_imports)]
                use ::rust_web_server::test_client::factory::__private::{
                    Probe as __Probe, ViaDefault as _, ViaValue as _,
                };
                #struct_name {
                    #(#inits),*
                }
            }
        }

        impl #struct_name {
            /// A factory building this model with default values, for tests.
            pub fn factory() -> ::rust_web_server::test_client::factory::ModelFactory<#struct_name> {
                ::rust_web_server::test_client::factory::ModelFactory::new()
            }
        }
    })
}

// ── #[derive(JsonSchema)] ─────────────────────────────────────────────────────

/// Derive `rust_web_server::schema::JsonSchema` for a struct with named
/// fields or an enum of unit variants.
///
/// The schema follows the type's serde attributes, so it describes the JSON
/// `serde_json` reads and writes: container `rename_all` and `default`;
/// field `rename`, `default`, `skip`/`skip_serializing`/`skip_deserializing`
/// (left out) and `skip_serializing_if` (not required); variant `rename`.
/// Attributes that change the JSON's shape — `flatten`, `tag`, `content`,
/// `untagged`, `transparent`, `with`/`serialize_with`/`deserialize_with`,
/// separate serialize/deserialize renames — are a compile error rather than a
/// schema that doesn't match. `Option` fields are not required. Doc comments
/// become `description`s.
///
/// ```ignore
/// #[derive(serde::Serialize, serde::Deserialize, rust_web_server::JsonSchema)]
/// #[serde(rename_all = "camelCase")]
/// struct Item {
///     /// Stock keeping unit.
///     sku: String,
///     in_stock: u32,
///     note: Option<String>,
/// }
/// ```
#[proc_macro_derive(JsonSchema, attributes(serde))]
pub fn derive_json_schema(input: TokenStream) -> TokenStream {
    let ast = parse_macro_input!(input as DeriveInput);
    impl_json_schema(ast)
        .unwrap_or_else(|e| e.to_compile_error())
        .into()
}

fn impl_json_schema(input: DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
    let name = &input.ident;
    let container = SerdeAttrs::parse(&input.attrs)?;
    let description = doc_comment(&input.attrs);
    let body = match &input.data {
        Data::Struct(s) => {
            let Fields::Named(fields) = &s.fields else {
                return Err(syn::Error::new_spanned(
                    name,
                    "#[derive(JsonSchema)] supports structs with named fields and enums of unit variants",
                ));
            };
            let mut properties = Vec::new();
            for field in &fields.named {
                let attrs = SerdeAttrs::parse(&field.attrs)?;
                if attrs.skip {
                    continue;
                }
                let ident = field.ident.as_ref().expect("named field");
                let json_name = attrs.rename.clone().unwrap_or_else(|| {
                    rename_with(ident.to_string().trim_start_matches("r#"), container.rename_all.as_deref(), false)
                });
                let ty = &field.ty;
                let field_doc = doc_comment(&field.attrs);
                let may_be_absent = attrs.default || container.default || attrs.skip_serializing_if;
                properties.push(quote! {
                    __schema.property(
                        #json_name,
                        &_rws::schema::nested::<#ty>(),
                        #field_doc,
                        !#may_be_absent && !<#ty as _rws::schema::JsonSchema>::is_optional(),
                    );
                });
            }
            quote! {
                let mut __schema = _rws::schema::ObjectSchema::new(#description);
                #(#properties)*
                __schema.finish()
            }
        }
        Data::Enum(e) => {
            let mut values = Vec::new();
            for variant in &e.variants {
                if !matches!(variant.fields, Fields::Unit) {
                    return Err(syn::Error::new_spanned(
                        variant,
                        "#[derive(JsonSchema)] supports only unit enum variants",
                    ));
                }
                let attrs = SerdeAttrs::parse(&variant.attrs)?;
                if attrs.skip {
                    continue;
                }
                values.push(attrs.rename.unwrap_or_else(|| {
                    rename_with(&variant.ident.to_string(), container.rename_all.as_deref(), true)
                }));
            }
            quote! { _rws::schema::string_enum(#description, &[#(#values),*]) }
        }
        Data::Union(_) => {
            return Err(syn::Error::new_spanned(name, "#[derive(JsonSchema)] does not support unions"));
        }
    };

    let mut generics = input.generics.clone();
    for param in generics.type_params_mut() {
        param.bounds.push(syn::parse_quote!(::rust_web_server::schema::JsonSchema));
    }
    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
    Ok(quote! {
        const _: () = {
            use ::rust_web_server as _rws;
            impl #impl_generics _rws::schema::JsonSchema for #name #ty_generics #where_clause {
                fn json_schema() -> ::std::string::String {
                    #body
                }
            }
        };
    })
}

/// The `#[serde(...)]` attributes `#[derive(JsonSchema)]` understands.
#[derive(Default)]
struct SerdeAttrs {
    rename: Option<String>,
    rename_all: Option<String>,
    default: bool,
    skip: bool,
    skip_serializing_if: bool,
}

impl SerdeAttrs {
    fn parse(attrs: &[syn::Attribute]) -> syn::Result<Self> {
        let mut out = SerdeAttrs::default();
        for attr in attrs.iter().filter(|a| a.path().is_ident("serde")) {
            attr.parse_nested_meta(|meta| {
                let key = meta.path.get_ident().map(|i| i.to_string()).unwrap_or_default();
                match key.as_str() {
                    "rename" | "rename_all" => {
                        if !meta.input.peek(Token![=]) {
                            return Err(meta.error(format!(
                                "#[derive(JsonSchema)] needs one `{key}` for both directions (one schema describes input and output)"
                            )));
                        }
                        let value = meta.value()?.parse::<LitStr>()?.value();
                        if key == "rename" {
                            out.rename = Some(value);
                        } else {
                            if rename_with("a_b", Some(&value), false).is_empty() {
                                return Err(meta.error(format!("unknown rename_all rule \"{value}\"")));
                            }
                            out.rename_all = Some(value);
                        }
                    }
                    "default" => {
                        out.default = true;
                        if meta.input.peek(Token![=]) {
                            meta.value()?.parse::<LitStr>()?;
                        }
                    }
                    "skip" | "skip_serializing" | "skip_deserializing" => out.skip = true,
                    "skip_serializing_if" => {
                        out.skip_serializing_if = true;
                        meta.value()?.parse::<LitStr>()?;
                    }
                    "flatten" | "tag" | "content" | "untagged" | "transparent" | "with" | "serialize_with"
                    | "deserialize_with" | "remote" | "from" | "try_from" | "into" | "getter" => {
                        return Err(meta.error(format!(
                            "#[derive(JsonSchema)] does not support #[serde({key})]: the schema would not match the JSON"
                        )));
                    }
                    _ => {
                        // Attributes that don't change the JSON's shape
                        // (alias, deny_unknown_fields, bound, crate, borrow,
                        // expecting, ...): skip their value, if any.
                        if meta.input.peek(Token![=]) {
                            meta.value()?.parse::<proc_macro2::TokenStream>()?;
                        } else if meta.input.peek(syn::token::Paren) {
                            meta.parse_nested_meta(|nested| {
                                if nested.input.peek(Token![=]) {
                                    nested.value()?.parse::<proc_macro2::TokenTree>()?;
                                }
                                Ok(())
                            })?;
                        }
                    }
                }
                Ok(())
            })?;
        }
        Ok(out)
    }
}

/// `name` renamed by serde's `rename_all` `rule` (`variant`: `name` is a
/// PascalCase enum variant rather than a snake_case field). Empty for an
/// unknown rule.
fn rename_with(name: &str, rule: Option<&str>, variant: bool) -> String {
    let Some(rule) = rule else { return name.to_string() };
    // Split into lower-case words.
    let words: Vec<String> = if variant {
        let mut words = Vec::new();
        let mut current = String::new();
        for c in name.chars() {
            if c.is_uppercase() && !current.is_empty() {
                words.push(std::mem::take(&mut current));
            }
            current.extend(c.to_lowercase());
        }
        if !current.is_empty() {
            words.push(current);
        }
        words
    } else {
        name.split('_').map(str::to_string).collect()
    };
    let capitalize = |w: &String| {
        let mut chars = w.chars();
        chars.next().map(|c| c.to_uppercase().chain(chars).collect::<String>()).unwrap_or_default()
    };
    match rule {
        "lowercase" => words.concat(),
        "UPPERCASE" => words.concat().to_uppercase(),
        "PascalCase" => words.iter().map(capitalize).collect(),
        "camelCase" => {
            let pascal: String = words.iter().map(capitalize).collect();
            let mut chars = pascal.chars();
            chars.next().map(|c| c.to_lowercase().chain(chars).collect()).unwrap_or_default()
        }
        "snake_case" => words.join("_"),
        "SCREAMING_SNAKE_CASE" => words.join("_").to_uppercase(),
        "kebab-case" => words.join("-"),
        "SCREAMING-KEBAB-CASE" => words.join("-").to_uppercase(),
        _ => String::new(),
    }
}

/// The item's `///` doc comment, lines joined with spaces.
fn doc_comment(attrs: &[syn::Attribute]) -> String {
    let mut lines = Vec::new();
    for attr in attrs.iter().filter(|a| a.path().is_ident("doc")) {
        if let syn::Meta::NameValue(nv) = &attr.meta {
            if let syn::Expr::Lit(syn::ExprLit { lit: Lit::Str(s), .. }) = &nv.value {
                let line = s.value().trim().to_string();
                if !line.is_empty() {
                    lines.push(line);
                }
            }
        }
    }
    lines.join(" ")
}

#[cfg(test)]
mod tests {
    use super::rename_with;

    #[test]
    fn rename_all_rules_match_serde() {
        let field = |rule| rename_with("line_item_id", Some(rule), false);
        assert_eq!("lineitemid", field("lowercase"));
        assert_eq!("LINEITEMID", field("UPPERCASE"));
        assert_eq!("LineItemId", field("PascalCase"));
        assert_eq!("lineItemId", field("camelCase"));
        assert_eq!("line_item_id", field("snake_case"));
        assert_eq!("LINE_ITEM_ID", field("SCREAMING_SNAKE_CASE"));
        assert_eq!("line-item-id", field("kebab-case"));
        assert_eq!("LINE-ITEM-ID", field("SCREAMING-KEBAB-CASE"));
        let variant = |rule| rename_with("BackOrdered", Some(rule), true);
        assert_eq!("backordered", variant("lowercase"));
        assert_eq!("backOrdered", variant("camelCase"));
        assert_eq!("back_ordered", variant("snake_case"));
        assert_eq!("BACK-ORDERED", variant("SCREAMING-KEBAB-CASE"));
        assert_eq!("BackOrdered", variant("PascalCase"));
        assert_eq!("as_is", rename_with("as_is", None, false));
        assert_eq!("", rename_with("a_b", Some("Train-Case"), false));
    }
}