day-macros 0.4.6

Compile-time macros for Day.
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
// Copyright © The Daybrite Project
// SPDX-License-Identifier: MPL-2.0

//! `#[derive(Observable)]` and `#[derive(Model)]`: the day-model and day-persistence derives.
//!
//! For `struct Item { id: u32, name: String, … }`, `Observable` generates:
//!
//! - `impl day_model::Identified for Item` from the `#[obs(key)]` field, always explicit, never
//!   inferred: a struct that happens to carry an `id` that is not its key would make inference a
//!   trap, and one attribute line is cheap;
//! - an `ItemFields` trait with one accessor per field, implemented for every
//!   `Source<Item>`, so `store.name()`, `store.elem(id).name()` and `item.address().city()`
//!   all work;
//! - `Item::OBSERVED_FIELDS`, so a test can assert what is observable without reflection.
//!
//! `#[obs(skip)]` leaves a field out entirely: it gets no accessor, path or trigger and, under
//! `Model`, no column. A field the change log cannot name could never mark its row dirty, so
//! persisting it would silently lose edits.
//!
//! `Model` implies `Observable` and adds the schema half (docs/persistence.md): `impl
//! day_persistence::Model` with the table name, column list, row↔struct mappers and the default
//! row. `#[model(id)]` marks the key (it is `#[obs(key)]` too); field options are `column =
//! "…"`, `unique`, `index`, `transient` (observable, never stored), `with = Codec` and `json`;
//! struct options are `table = "…"` and `index("a", "b")` for composites.
//!
//! Field ids come from field names (`day_model::field_id`), so no index can be duplicated by
//! hand. Generated paths say `day_model::…` / `day_persistence::…` unqualified: the crates
//! depend on nothing that could shadow them, and the `day` facade's prelude re-exports both
//! names, so a direct dependency and `use day::prelude::*` both resolve them.
//!
//! Same construction as [`crate::build_path!`], with neither syn nor quote. A derive that needs
//! field names and type tokens never has to understand a type, only re-emit it.

use proc_macro::{Delimiter, TokenStream, TokenTree};

pub(crate) fn observable(input: TokenStream) -> TokenStream {
    finish(expand_observable(input))
}

pub(crate) fn model(input: TokenStream) -> TokenStream {
    finish(expand_model(input))
}

fn finish(result: Result<String, String>) -> TokenStream {
    match result {
        Ok(out) => out
            .parse()
            .unwrap_or_else(|e| panic!("generated code did not parse: {e}")),
        Err(msg) => format!("compile_error!({msg:?});")
            .parse()
            .expect("compile_error! literal always parses"),
    }
}

#[derive(Default)]
struct FieldDef {
    name: String,
    ty: String,
    key: bool,
    skip: bool,
    // The #[model(…)] half; inert under a bare Observable.
    column: Option<String>,
    unique: bool,
    indexed: bool,
    transient: bool,
    with: Option<String>,
    json: bool,
    /// `#[model(relation(…))]`: a `Many<T>` marker field. It gets no column or plain accessor;
    /// the Model derive emits a `RelationRef` accessor and the wiring instead.
    relation: Option<RelationAttr>,
    /// `#[model(link(…))]`: a `Linked<T>` marker field, a relation by value rather than by
    /// key, across databases (docs/persistence.md). It gets no column or accessor; the Model
    /// derive emits the predicate builder and the `LinkDef`.
    link: Option<LinkAttr>,
}

/// The parsed `link(target = T, local = "column", remote = "column")`.
struct LinkAttr {
    target: String,
    local: String,
    remote: String,
}

/// The parsed `relation(target = T, inverse = "…", delete = "…", ordered = "…", join = "…")`.
struct RelationAttr {
    target: String,
    inverse: Option<String>,
    delete: String,
    ordered: Option<String>,
    join: Option<String>,
}

impl FieldDef {
    fn column_name(&self) -> &str {
        self.column.as_deref().unwrap_or(&self.name)
    }
    fn persisted(&self) -> bool {
        !self.skip && !self.transient && self.relation.is_none() && self.link.is_none()
    }
    fn nullable(&self) -> bool {
        self.ty == "Option" || self.ty.starts_with("Option <")
    }
}

struct StructDef {
    name: String,
    table: Option<String>,
    /// `external = "alias"`: the table lives in a database ATTACHed under `alias`, managed by
    /// someone else, so it is read-only and gets neither DDL nor a migration.
    external: Option<String>,
    composites: Vec<Vec<String>>,
    fts: Vec<String>,
    fts_tokenize: Option<String>,
    spatial: Option<(String, String)>,
    fields: Vec<FieldDef>,
}

fn expand_observable(input: TokenStream) -> Result<String, String> {
    let def = parse_struct(input)?;
    let keys: Vec<&FieldDef> = def.fields.iter().filter(|f| f.key).collect();
    if keys.len() > 1 {
        return Err(format!(
            "Observable: `{}` marks more than one field #[obs(key)]",
            def.name
        ));
    }
    Ok(emit_observable(&def))
}

fn expand_model(input: TokenStream) -> Result<String, String> {
    let def = parse_struct(input)?;
    let keys: Vec<&FieldDef> = def.fields.iter().filter(|f| f.key).collect();
    let key = match keys.as_slice() {
        [k] => *k,
        [] => {
            return Err(format!(
                "Model: `{}` needs exactly one field marked #[model(id)]",
                def.name
            ));
        }
        _ => {
            return Err(format!(
                "Model: `{}` marks more than one field as the id",
                def.name
            ));
        }
    };
    if key.transient || key.skip {
        return Err(format!(
            "Model: `{}`'s id field cannot be transient or skipped",
            def.name
        ));
    }
    if key.with.is_some() || key.json {
        // The key's stored form must match its `Key` form: the fold's WHERE parameters and
        // external-merge decoding both derive it from the key kind, not from a codec.
        return Err(format!(
            "Model: `{}`'s id field takes no codec — integer, Uuid and String keys store \
             in their canonical forms",
            def.name
        ));
    }

    let mut out = emit_observable(&def);
    out.push_str(&emit_model(&def, key)?);
    Ok(out)
}

// ---------------------------------------------------------------------------
// Emission
// ---------------------------------------------------------------------------

fn emit_observable(def: &StructDef) -> String {
    let name = &def.name;
    // Relation marker fields observe through their RelationRef accessor (Model-emitted), not
    // a plain Field: a `Many` holds nothing a Field could usefully bind.
    let observed: Vec<&FieldDef> = def
        .fields
        .iter()
        .filter(|f| !f.skip && f.relation.is_none() && f.link.is_none())
        .collect();
    let mut out = String::new();

    // The key, if one was marked. Without one the struct still observes; putting it in a
    // `Keyed` collection is then a compile error naming `Identified` and this attribute.
    if let Some(k) = def.fields.iter().find(|f| f.key) {
        // `AsKey` picks the key's form by the field type (integers pass through as their own
        // handle, `Uuid` and `String` intern), so the derive never interprets the type.
        out.push_str(&format!(
            "impl day_model::Identified for {name} {{\n\
             \x20   fn key(&self) -> day_model::Key {{ day_model::AsKey::as_key(&self.{}) }}\n\
             }}\n",
            k.name
        ));
    }

    // One accessor per observed field, for every Source of this type.
    let trait_name = format!("{name}Fields");
    out.push_str(&format!(
        "#[allow(non_camel_case_types)]\npub trait {trait_name}: day_model::Source<{name}> + Sized {{\n"
    ));
    for f in &observed {
        out.push_str(&format!(
            "    fn {}(self) -> day_model::Field<Self, {name}, {}> {{\n\
             \x20       day_model::project(self, \"{}\", |s| &s.{}, |s| &mut s.{})\n\
             \x20   }}\n",
            f.name, f.ty, f.name, f.name, f.name
        ));
    }
    out.push_str("}\n");
    out.push_str(&format!(
        "impl<S: day_model::Source<{name}>> {trait_name} for S {{}}\n"
    ));

    // The `ApplyField` impl: the typed path an undo stack replays through and, since
    // `read_field`, the one label-addressed writes capture priors through and relation wiring
    // reads foreign keys through. One match arm per observed field, downcasting to the field's
    // type.
    out.push_str(&format!(
        "impl day_model::ApplyField for {name} {{\n\
         \x20   fn apply_field(&mut self, label: &str, value: &dyn ::core::any::Any) -> bool {{\n\
         \x20       match label {{\n{}\
         \x20           _ => false,\n\
         \x20       }}\n\
         \x20   }}\n\
         \x20   fn read_field(&self, label: &str) -> \
         Option<::std::rc::Rc<dyn ::core::any::Any>> {{\n\
         \x20       match label {{\n{}\
         \x20           _ => None,\n\
         \x20       }}\n\
         \x20   }}\n\
         }}\n",
        observed
            .iter()
            .map(|f| format!(
                "            \"{}\" => match value.downcast_ref::<{}>() {{\n\
                 \x20               Some(v) => {{\n\
                 \x20                   self.{} = v.clone();\n\
                 \x20                   true\n\
                 \x20               }}\n\
                 \x20               None => false,\n\
                 \x20           }},\n",
                f.name, f.ty, f.name
            ))
            .collect::<String>(),
        observed
            .iter()
            .map(|f| format!(
                "            \"{}\" => Some(::std::rc::Rc::new(self.{}.clone())),\n",
                f.name, f.name
            ))
            .collect::<String>()
    ));

    // A names list, so a test can assert what is observable without reflection.
    out.push_str(&format!(
        "impl {name} {{\n    pub const OBSERVED_FIELDS: &'static [&'static str] = &[{}];\n}}\n",
        observed
            .iter()
            .map(|f| format!("\"{}\"", f.name))
            .collect::<Vec<_>>()
            .join(", ")
    ));
    out
}

/// The schema half. Every generated expression goes through `day_persistence::` paths and the
/// field's type: the derive never guesses a SQL type, it asks `ColumnValue::SQL_TYPE` (or
/// the named codec's) at compile time.
fn emit_model(def: &StructDef, key: &FieldDef) -> Result<String, String> {
    let name = &def.name;
    let bare_table = def.table.clone().unwrap_or_else(|| snake_case(name));
    // An external table is addressed through its database alias everywhere SQL names it
    // (the fault SELECT, predicates, the FTS shadow `alias.table_fts`), which is what one
    // qualified `TABLE` constant gives every existing code path at once.
    let table = match &def.external {
        Some(alias) => format!("{alias}.{bare_table}"),
        None => bare_table,
    };
    let persisted: Vec<&FieldDef> = def.fields.iter().filter(|f| f.persisted()).collect();
    for f in def.fields.iter().filter(|f| f.link.is_some()) {
        let l = f.link.as_ref().expect("filtered");
        if !persisted.iter().any(|p| p.column_name() == l.local) {
            return Err(format!(
                "Model: link(…) on `{}` names local = {:?}, which is not a persisted column of `{name}`",
                f.name, l.local
            ));
        }
    }

    let mut columns = String::new();
    for f in &persisted {
        let sql = sql_type_expr(f);
        columns.push_str(&format!(
            "        day_persistence::ColumnDef {{ name: \"{}\", field: \"{}\", sql: {sql}, \
             not_null: {}, unique: {}, indexed: {} }},\n",
            f.column_name(),
            f.name,
            !f.nullable(),
            f.unique,
            f.indexed,
        ));
    }

    // fts()/spatial() name COLUMNS; a typo would silently index nothing, so check now.
    let column_names: Vec<&str> = persisted.iter().map(|f| f.column_name()).collect();
    for c in &def.fts {
        if !column_names.contains(&c.as_str()) {
            return Err(format!(
                "Model: fts(…) names `{c}`, which is not a persisted column of `{name}`"
            ));
        }
    }
    if let Some((lat, lon)) = &def.spatial {
        for c in [lat, lon] {
            if !column_names.contains(&c.as_str()) {
                return Err(format!(
                    "Model: spatial(…) names `{c}`, which is not a persisted column of `{name}`"
                ));
            }
        }
    }

    let composites = def
        .composites
        .iter()
        .map(|cols| {
            format!(
                "&[{}]",
                cols.iter()
                    .map(|c| format!("\"{c}\""))
                    .collect::<Vec<_>>()
                    .join(", ")
            )
        })
        .collect::<Vec<_>>()
        .join(", ");

    let mut to_row = String::new();
    for f in &persisted {
        to_row.push_str(&format!("            {},\n", encode_expr(f)));
    }

    let mut from_row = String::new();
    for f in &def.fields {
        if let Some(i) = persisted.iter().position(|p| p.name == f.name) {
            from_row.push_str(&format!("            {}: {},\n", f.name, decode_expr(f, i)));
        } else {
            from_row.push_str(&format!(
                "            {}: ::core::default::Default::default(),\n",
                f.name
            ));
        }
    }

    // Typed column refs: `Trip::name()` in a predicate, beside `trip.name()` the binding.
    // Inherent fns without a receiver never collide with the Fields trait's methods (which
    // take self): method-call syntax finds the trait, path syntax finds these.
    let mut cols = String::new();
    for f in &persisted {
        let encode = match codec(f) {
            Some(codec) => format!(
                "<{codec} as day_persistence::ValueCodec<{}>>::to_sqlite_value",
                f.ty
            ),
            None => format!("day_persistence::encode_column::<{}>", f.ty),
        };
        cols.push_str(&format!(
            "    pub fn {}() -> day_persistence::Col<{}> {{\n\
             \x20       day_persistence::Col::new(\"{}\", \"{}\", \"{table}\", {encode})\n\
             \x20   }}\n",
            f.name,
            f.ty,
            f.column_name(),
            f.name,
        ));
    }
    // The static relation reference, for predicates. The instance accessor of the same name
    // lives on the Relations trait and takes `self`, so path syntax finds this one and
    // method-call syntax finds that one, the rule `Trip::name()` already relies on.
    for f in def.fields.iter().filter(|f| f.relation.is_some()) {
        let r = f.relation.as_ref().expect("filtered");
        cols.push_str(&format!(
            "    pub fn {}() -> day_persistence::RelationCol<{name}, {}> {{\n\
             \x20       day_persistence::RelationCol::new(\"{}\", \"{table}\", \
             <{} as day_persistence::Model>::TABLE)\n\
             \x20   }}\n",
            f.name, r.target, f.name, r.target,
        ));
    }
    // A link's predicate builder is a plain RelationCol: the container resolves the
    // (owner, field) pair to the link's join condition at compile time, so `any`/`none`/
    // `is_empty`/`count_ge` read exactly as they do across a keyed relation.
    for f in def.fields.iter().filter(|f| f.link.is_some()) {
        let l = f.link.as_ref().expect("filtered");
        cols.push_str(&format!(
            "    pub fn {}() -> day_persistence::RelationCol<{name}, {}> {{\n\
             \x20       day_persistence::RelationCol::new(\"{}\", \"{table}\", \
             <{} as day_persistence::Model>::TABLE)\n\
             \x20   }}\n",
            f.name, l.target, f.name, l.target,
        ));
    }
    if !def.fts.is_empty() {
        cols.push_str(&format!(
            "    pub fn fts() -> day_persistence::FtsRef {{\n\
             \x20       day_persistence::FtsRef {{ columns: <{name} as day_persistence::Model>::FTS_COLUMNS }}\n\
             \x20   }}\n"
        ));
    }
    if let Some((lat, lon)) = &def.spatial {
        cols.push_str(&format!(
            "    pub fn geo() -> day_persistence::GeoRef {{\n\
             \x20       day_persistence::GeoRef {{ lat: \"{lat}\", lon: \"{lon}\" }}\n\
             \x20   }}\n"
        ));
    }
    let col_impl = format!("#[allow(dead_code)]\nimpl {name} {{\n{cols}}}\n");

    // Relations: the const table, the wiring, and the RelationRef accessor trait.
    let rels: Vec<(&FieldDef, &RelationAttr)> = def
        .fields
        .iter()
        .filter_map(|f| f.relation.as_ref().map(|r| (f, r)))
        .collect();
    let delete_expr = |d: &str| match d {
        "cascade" => "day_persistence::DeleteRule::Cascade",
        "deny" => "day_persistence::DeleteRule::Deny",
        _ => "day_persistence::DeleteRule::Nullify",
    };
    let opt_str = |o: &Option<String>| match o {
        Some(s) => format!("Some(\"{s}\")"),
        None => "None".into(),
    };
    let relations_const = if rels.is_empty() {
        String::new()
    } else {
        format!(
            "    const RELATIONS: &'static [day_persistence::RelationDef] = &[\n{}    ];\n",
            rels.iter()
                .map(|(f, r)| format!(
                    "        day_persistence::RelationDef {{ field: \"{}\", target_table: \
                     <{} as day_persistence::Model>::TABLE, inverse: \"{}\", delete: {}, \
                     ordered: {}, join: {} }},\n",
                    f.name,
                    r.target,
                    r.inverse.as_deref().unwrap_or(""),
                    delete_expr(&r.delete),
                    opt_str(&r.ordered),
                    opt_str(&r.join),
                ))
                .collect::<String>()
        )
    };
    let wire_fn = if rels.is_empty() {
        String::new()
    } else {
        format!(
            "    fn wire(reg: &mut day_persistence::Registrar<'_>) {{\n{}    }}\n",
            rels.iter()
                .map(|(f, r)| match (&r.join, &r.inverse) {
                    (Some(join), _) => format!(
                        "        day_persistence::wire_join::<Self, {}>(reg, \"{}\", \
                         \"{join}\", {}, {});\n",
                        r.target,
                        f.name,
                        opt_str(&r.ordered),
                        delete_expr(&r.delete),
                    ),
                    (None, Some(inverse)) => format!(
                        "        day_persistence::wire_to_many::<Self, {}>(reg, \"{}\", \
                         \"{inverse}\", {}, {});\n",
                        r.target,
                        f.name,
                        delete_expr(&r.delete),
                        opt_str(&r.ordered),
                    ),
                    (None, None) => String::new(), // refused at parse time
                })
                .collect::<String>()
        )
    };
    let rel_trait = if rels.is_empty() {
        String::new()
    } else {
        format!(
            "#[allow(non_camel_case_types)]\n\
             pub trait {name}Relations: day_model::Source<{name}> + Sized {{\n{}}}\n\
             impl<S: day_model::Source<{name}>> {name}Relations for S {{}}\n",
            rels.iter()
                .map(|(f, r)| format!(
                    "    fn {}(self) -> day_persistence::RelationRef<Self, {name}, {}> {{\n\
                     \x20       day_persistence::RelationRef::new(day_model::project(\
                     self, \"{}\", |s| &s.{}, |s| &mut s.{}))\n\
                     \x20   }}\n",
                    f.name, r.target, f.name, f.name, f.name
                ))
                .collect::<String>()
        )
    };

    let fts_const = if def.fts.is_empty() {
        String::new()
    } else {
        let tokenize = match &def.fts_tokenize {
            Some(t) => format!(
                "    const FTS_TOKENIZE: Option<&'static str> = Some(\"{}\");\n",
                t.replace('\\', "\\\\").replace('"', "\\\"")
            ),
            None => String::new(),
        };
        format!(
            "    const FTS_COLUMNS: &'static [&'static str] = &[{}];\n{tokenize}",
            def.fts
                .iter()
                .map(|c| format!("\"{c}\""))
                .collect::<Vec<_>>()
                .join(", ")
        )
    };
    let links: Vec<(&FieldDef, &LinkAttr)> = def
        .fields
        .iter()
        .filter_map(|f| f.link.as_ref().map(|l| (f, l)))
        .collect();
    let links_const = if links.is_empty() {
        String::new()
    } else {
        format!(
            "    const LINKS: &'static [day_persistence::LinkDef] = &[\n{}    ];\n",
            links
                .iter()
                .map(|(f, l)| format!(
                    "        day_persistence::LinkDef {{ field: \"{}\", local: \"{}\", \
                     target_table: <{} as day_persistence::Model>::TABLE, remote: \"{}\" }},\n",
                    f.name, l.local, l.target, l.remote
                ))
                .collect::<String>()
        )
    };
    let external_const = if def.external.is_some() {
        "    const EXTERNAL: bool = true;\n".to_string()
    } else {
        String::new()
    };
    let spatial_const = match &def.spatial {
        None => String::new(),
        Some((lat, lon)) => format!(
            "    const SPATIAL: Option<day_persistence::SpatialCols> = \
             Some(day_persistence::SpatialCols {{ lat: \"{lat}\", lon: \"{lon}\" }});\n"
        ),
    };

    let key_sql = sql_type_expr(key);
    Ok(col_impl
        + &rel_trait
        + &format!(
            "impl day_persistence::Model for {name} {{\n\
         \x20   const TABLE: &'static str = \"{table}\";\n\
         \x20   const KEY: &'static str = \"{key_col}\";\n\
         \x20   const KEY_SQL: day_persistence::SqlType = {key_sql};\n\
         \x20   const COLUMNS: &'static [day_persistence::ColumnDef] = &[\n{columns}    ];\n\
         \x20   const COMPOSITE_INDEXES: &'static [&'static [&'static str]] = &[{composites}];\n\
         {fts_const}{spatial_const}{relations_const}{links_const}{external_const}\
         \x20   fn to_row(&self) -> Vec<day_persistence::Value> {{\n\
         \x20       vec![\n{to_row}        ]\n\
         \x20   }}\n\
         \x20   fn from_row(row: &dyn day_persistence::Row) -> \
         Result<Self, day_persistence::DbError> {{\n\
         \x20       Ok(Self {{\n{from_row}        }})\n\
         \x20   }}\n\
         \x20   fn default_row() -> Vec<day_persistence::Value> {{\n\
         \x20       day_persistence::Model::to_row(&<Self as ::core::default::Default>::default())\n\
         \x20   }}\n\
         {wire_fn}\
         }}\n",
            key_col = key.column_name(),
        ))
}

fn sql_type_expr(f: &FieldDef) -> String {
    match codec(f) {
        Some(codec) => format!(
            "<{codec} as day_persistence::ValueCodec<{}>>::SQL_TYPE",
            f.ty
        ),
        None => format!("<{} as day_persistence::ColumnValue>::SQL_TYPE", f.ty),
    }
}

fn encode_expr(f: &FieldDef) -> String {
    match codec(f) {
        Some(codec) => format!(
            "<{codec} as day_persistence::ValueCodec<{}>>::to_sqlite_value(&self.{})",
            f.ty, f.name
        ),
        None => format!(
            "day_persistence::ColumnValue::to_sqlite_value(&self.{})",
            f.name
        ),
    }
}

/// A stored NULL decodes as the field's `Default`, which is what makes an added column's old
/// rows readable before their backfill, matching the model's deleted-row semantics.
fn decode_expr(f: &FieldDef, i: usize) -> String {
    let read = format!("day_persistence::Row::get(row, {i}usize)");
    match codec(f) {
        Some(codec) => format!(
            "match {read} {{\n\
             \x20               day_persistence::Value::Null => ::core::default::Default::default(),\n\
             \x20               v => <{codec} as day_persistence::ValueCodec<{}>>::from_sqlite_value(v)?,\n\
             \x20           }}",
            f.ty
        ),
        None => format!(
            "match {read} {{\n\
             \x20               day_persistence::Value::Null => ::core::default::Default::default(),\n\
             \x20               v => <{} as day_persistence::ColumnValue>::from_sqlite_value(v)?,\n\
             \x20           }}",
            f.ty
        ),
    }
}

fn codec(f: &FieldDef) -> Option<String> {
    if let Some(with) = &f.with {
        Some(with.clone())
    } else if f.json {
        Some("day_persistence::Json".into())
    } else {
        None
    }
}

fn snake_case(name: &str) -> String {
    let mut out = String::with_capacity(name.len() + 4);
    for (i, ch) in name.chars().enumerate() {
        if ch.is_uppercase() {
            if i > 0 {
                out.push('_');
            }
            out.extend(ch.to_lowercase());
        } else {
            out.push(ch);
        }
    }
    out
}

// ---------------------------------------------------------------------------
// Parsing
// ---------------------------------------------------------------------------

/// The whole derive input: struct-level `#[model(…)]` options, the name, and the fields.
fn parse_struct(input: TokenStream) -> Result<StructDef, String> {
    let tokens: Vec<TokenTree> = input.into_iter().collect();

    let mut table = None;
    let mut external = None;
    let mut composites = Vec::new();
    let mut fts = Vec::new();
    let mut fts_tokenize = None;
    let mut spatial = None;
    let mut i = 0;
    while i < tokens.len() {
        match &tokens[i] {
            TokenTree::Ident(id) if id.to_string() == "struct" => break,
            TokenTree::Punct(p) if p.as_char() == '#' => {
                if let Some(TokenTree::Group(g)) = tokens.get(i + 1) {
                    if let Some(items) = attr_items(g, "model") {
                        parse_struct_options(
                            items,
                            &mut table,
                            &mut external,
                            &mut composites,
                            &mut fts,
                            &mut fts_tokenize,
                            &mut spatial,
                        )?;
                    }
                    i += 2;
                    continue;
                }
                return Err("malformed attribute on the struct".into());
            }
            _ => i += 1,
        }
    }
    if i >= tokens.len() {
        return Err("the derive expects a struct".into());
    }
    let name = match tokens.get(i + 1) {
        Some(TokenTree::Ident(id)) => id.to_string(),
        _ => return Err("the derive expects a named struct".into()),
    };
    let body = match tokens.get(i + 2) {
        Some(TokenTree::Group(g)) if g.delimiter() == Delimiter::Brace => g.stream(),
        Some(TokenTree::Punct(p)) if p.as_char() == '<' => {
            return Err("the derive does not support generic structs yet".into());
        }
        _ => return Err("the derive expects a struct with named fields".into()),
    };

    Ok(StructDef {
        name,
        table,
        external,
        composites,
        fts,
        fts_tokenize,
        spatial,
        fields: parse_fields(body)?,
    })
}

/// If the bracket group is `name(…)`, return the paren group's items split on top-level commas.
fn attr_items(bracket: &proc_macro::Group, name: &str) -> Option<Vec<Vec<TokenTree>>> {
    let inner: Vec<TokenTree> = bracket.stream().into_iter().collect();
    match (inner.first(), inner.get(1)) {
        (Some(TokenTree::Ident(id)), Some(TokenTree::Group(g)))
            if id.to_string() == name && g.delimiter() == Delimiter::Parenthesis =>
        {
            let mut items = vec![Vec::new()];
            for tt in g.stream() {
                match &tt {
                    TokenTree::Punct(p) if p.as_char() == ',' => items.push(Vec::new()),
                    _ => items.last_mut().expect("never empty").push(tt),
                }
            }
            items.retain(|item| !item.is_empty());
            Some(items)
        }
        _ => None,
    }
}

fn parse_struct_options(
    items: Vec<Vec<TokenTree>>,
    table: &mut Option<String>,
    external: &mut Option<String>,
    composites: &mut Vec<Vec<String>>,
    fts: &mut Vec<String>,
    fts_tokenize: &mut Option<String>,
    spatial: &mut Option<(String, String)>,
) -> Result<(), String> {
    for item in items {
        match item.as_slice() {
            [TokenTree::Ident(id), TokenTree::Group(g)]
                if id.to_string() == "fts" && g.delimiter() == Delimiter::Parenthesis =>
            {
                // Column literals, plus an optional `tokenize = "…"` naming the FTS5
                // tokenizer (e.g. "unicode61 remove_diacritics 2").
                let mut fts_items = vec![Vec::new()];
                for tt in g.stream() {
                    match &tt {
                        TokenTree::Punct(p) if p.as_char() == ',' => fts_items.push(Vec::new()),
                        _ => fts_items.last_mut().expect("never empty").push(tt.clone()),
                    }
                }
                for item in fts_items.into_iter().filter(|i| !i.is_empty()) {
                    match item.as_slice() {
                        [TokenTree::Literal(lit)] => fts.push(string_literal(lit)?),
                        [
                            TokenTree::Ident(k),
                            TokenTree::Punct(eq),
                            TokenTree::Literal(lit),
                        ] if k.to_string() == "tokenize" && eq.as_char() == '=' => {
                            *fts_tokenize = Some(string_literal(lit)?);
                        }
                        other => {
                            return Err(format!(
                                "fts(…) expects column string literals and an optional \
                                 tokenize = \"…\", found `{}`",
                                tokens_text(other)
                            ));
                        }
                    }
                }
            }
            [TokenTree::Ident(id), TokenTree::Group(g)]
                if id.to_string() == "spatial" && g.delimiter() == Delimiter::Parenthesis =>
            {
                let mut lat = None;
                let mut lon = None;
                let inner: Vec<TokenTree> = g.stream().into_iter().collect();
                let mut j = 0;
                while j + 2 < inner.len() + 1 {
                    match (&inner.get(j), &inner.get(j + 1), &inner.get(j + 2)) {
                        (
                            Some(TokenTree::Ident(k)),
                            Some(TokenTree::Punct(eq)),
                            Some(TokenTree::Literal(lit)),
                        ) if eq.as_char() == '=' => {
                            match k.to_string().as_str() {
                                "lat" => lat = Some(string_literal(lit)?),
                                "lon" => lon = Some(string_literal(lit)?),
                                other => {
                                    return Err(format!(
                                        "spatial(…) takes lat = \"…\" and lon = \"…\", found `{other}`"
                                    ));
                                }
                            }
                            j += 3;
                            if matches!(inner.get(j), Some(TokenTree::Punct(p)) if p.as_char() == ',')
                            {
                                j += 1;
                            }
                        }
                        _ => return Err("spatial(…) takes lat = \"…\" and lon = \"…\"".into()),
                    }
                }
                match (lat, lon) {
                    (Some(lat), Some(lon)) => *spatial = Some((lat, lon)),
                    _ => return Err("spatial(…) needs BOTH lat = \"…\" and lon = \"…\"".into()),
                }
            }
            [
                TokenTree::Ident(id),
                TokenTree::Punct(eq),
                TokenTree::Literal(lit),
            ] if id.to_string() == "table" && eq.as_char() == '=' => {
                *table = Some(string_literal(lit)?);
            }
            [
                TokenTree::Ident(id),
                TokenTree::Punct(eq),
                TokenTree::Literal(lit),
            ] if id.to_string() == "external" && eq.as_char() == '=' => {
                let alias = string_literal(lit)?;
                if alias.is_empty() || !alias.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
                {
                    return Err(format!(
                        "external = {alias:?} must be a plain SQL schema name (letters, digits, `_`)"
                    ));
                }
                *external = Some(alias);
            }
            [TokenTree::Ident(id), TokenTree::Group(g)]
                if id.to_string() == "index" && g.delimiter() == Delimiter::Parenthesis =>
            {
                let mut cols = Vec::new();
                for tt in g.stream() {
                    match &tt {
                        TokenTree::Literal(lit) => cols.push(string_literal(lit)?),
                        TokenTree::Punct(p) if p.as_char() == ',' => {}
                        other => {
                            return Err(format!(
                                "index(…) expects string literals, found `{other}`"
                            ));
                        }
                    }
                }
                composites.push(cols);
            }
            other => {
                return Err(format!(
                    "unknown #[model] option on the struct: `{}` (supported: table = \"…\", external = \"alias\", index(\"a\", \"b\"), fts(\"a\", \"b\"), spatial(lat = \"…\", lon = \"…\"))",
                    tokens_text(other)
                ));
            }
        }
    }
    Ok(())
}

fn parse_field_options(items: Vec<Vec<TokenTree>>, f: &mut FieldDef) -> Result<(), String> {
    for item in items {
        match item.as_slice() {
            [TokenTree::Ident(id)] => match id.to_string().as_str() {
                "id" => f.key = true,
                "unique" => f.unique = true,
                "index" => f.indexed = true,
                "transient" => f.transient = true,
                "json" => f.json = true,
                other => {
                    return Err(format!(
                        "unknown #[model] option on field `{}`: `{other}` (supported: id, unique, index, transient, json, column = \"…\", with = Codec)",
                        f.name
                    ));
                }
            },
            [
                TokenTree::Ident(id),
                TokenTree::Punct(eq),
                TokenTree::Literal(lit),
            ] if id.to_string() == "column" && eq.as_char() == '=' => {
                f.column = Some(string_literal(lit)?);
            }
            [TokenTree::Ident(id), TokenTree::Punct(eq), rest @ ..]
                if id.to_string() == "with" && eq.as_char() == '=' && !rest.is_empty() =>
            {
                f.with = Some(tokens_text(rest));
            }
            [TokenTree::Ident(id), TokenTree::Group(g)]
                if id.to_string() == "relation" && g.delimiter() == Delimiter::Parenthesis =>
            {
                f.relation = Some(parse_relation(g, &f.name)?);
            }
            [TokenTree::Ident(id), TokenTree::Group(g)]
                if id.to_string() == "link" && g.delimiter() == Delimiter::Parenthesis =>
            {
                f.link = Some(parse_link(g, &f.name)?);
            }
            other => {
                return Err(format!(
                    "unknown #[model] option on field `{}`: `{}`",
                    f.name,
                    tokens_text(other)
                ));
            }
        }
    }
    Ok(())
}

/// `relation(target = Type, inverse = "field", delete = "…", ordered = "field", join = "table")`.
fn parse_relation(g: &proc_macro::Group, field: &str) -> Result<RelationAttr, String> {
    let mut items = vec![Vec::new()];
    for tt in g.stream() {
        match &tt {
            TokenTree::Punct(p) if p.as_char() == ',' => items.push(Vec::new()),
            _ => items.last_mut().expect("never empty").push(tt),
        }
    }
    items.retain(|i| !i.is_empty());

    let (mut target, mut inverse, mut delete, mut ordered, mut join) =
        (None, None, None, None, None);
    for item in items {
        match item.as_slice() {
            [TokenTree::Ident(k), TokenTree::Punct(eq), rest @ ..]
                if eq.as_char() == '=' && !rest.is_empty() =>
            {
                match k.to_string().as_str() {
                    "target" => target = Some(tokens_text(rest)),
                    "inverse" => inverse = Some(literal_str(rest, field)?),
                    "delete" => delete = Some(literal_str(rest, field)?),
                    "ordered" => ordered = Some(literal_str(rest, field)?),
                    "join" => join = Some(literal_str(rest, field)?),
                    other => {
                        return Err(format!(
                            "relation(…) on `{field}`: unknown option `{other}` (supported: \
                             target = Type, inverse = \"field\", delete = \"…\", \
                             ordered = \"field\", join = \"table\")"
                        ));
                    }
                }
            }
            // Bare `ordered`, the join form: the position lives on the membership row, so
            // there is no child field to name (one child can sit at different positions
            // under different parents).
            [TokenTree::Ident(k)] if k.to_string() == "ordered" => {
                ordered = Some("position".into());
            }
            other => {
                return Err(format!(
                    "relation(…) on `{field}`: expected `name = …`, found `{}`",
                    tokens_text(other)
                ));
            }
        }
    }
    let Some(target) = target else {
        return Err(format!("relation(…) on `{field}` needs target = Type"));
    };
    let delete = delete.unwrap_or_else(|| "nullify".into());
    if !["nullify", "cascade", "deny"].contains(&delete.as_str()) {
        return Err(format!(
            "relation(…) on `{field}`: delete = {delete:?} — nullify, cascade, or deny"
        ));
    }
    if inverse.is_none() && join.is_none() {
        return Err(format!(
            "relation(…) on `{field}` needs inverse = \"field\" (the target's One<…> field) \
             — or join = \"table\" for a many-to-many"
        ));
    }
    Ok(RelationAttr {
        target,
        inverse,
        delete,
        ordered,
        join,
    })
}

/// `link(target = Type, local = "column", remote = "column")` is a relation matched by value:
/// rows of `Type` whose `remote` column equals this row's `local` column. No foreign key and
/// no wiring, which is what lets it cross into an `external` table SQLite cannot constrain.
fn parse_link(g: &proc_macro::Group, field: &str) -> Result<LinkAttr, String> {
    let mut items = vec![Vec::new()];
    for tt in g.stream() {
        match &tt {
            TokenTree::Punct(p) if p.as_char() == ',' => items.push(Vec::new()),
            _ => items.last_mut().expect("never empty").push(tt),
        }
    }
    items.retain(|i| !i.is_empty());
    let (mut target, mut local, mut remote) = (None, None, None);
    for item in items {
        match item.as_slice() {
            [TokenTree::Ident(k), TokenTree::Punct(eq), rest @ ..]
                if eq.as_char() == '=' && !rest.is_empty() =>
            {
                match k.to_string().as_str() {
                    "target" => target = Some(tokens_text(rest)),
                    "local" => local = Some(literal_str(rest, field)?),
                    "remote" => remote = Some(literal_str(rest, field)?),
                    other => {
                        return Err(format!(
                            "link(…) on `{field}`: unknown option `{other}` (supported: \
                             target = Type, local = \"column\", remote = \"column\")"
                        ));
                    }
                }
            }
            other => {
                return Err(format!(
                    "link(…) on `{field}`: expected `name = …`, found `{}`",
                    tokens_text(other)
                ));
            }
        }
    }
    match (target, local, remote) {
        (Some(target), Some(local), Some(remote)) => Ok(LinkAttr {
            target,
            local,
            remote,
        }),
        _ => Err(format!(
            "link(…) on `{field}` needs target = Type, local = \"column\", and remote = \"column\""
        )),
    }
}

fn literal_str(rest: &[TokenTree], field: &str) -> Result<String, String> {
    match rest {
        [TokenTree::Literal(l)] => string_literal(l),
        other => Err(format!(
            "relation(…) on `{field}`: expected a string literal, found `{}`",
            tokens_text(other)
        )),
    }
}

fn string_literal(lit: &proc_macro::Literal) -> Result<String, String> {
    let s = lit.to_string();
    if s.len() >= 2 && s.starts_with('"') && s.ends_with('"') {
        Ok(s[1..s.len() - 1].to_string())
    } else {
        Err(format!("expected a string literal, found `{s}`"))
    }
}

fn tokens_text(tokens: &[TokenTree]) -> String {
    tokens
        .iter()
        .map(|t| t.to_string())
        .collect::<Vec<_>>()
        .join(" ")
}

/// Split the brace body on top-level commas and read `#[obs|model(...)] vis name : Type` out of
/// each. "Top-level" means outside `<…>` too, so a `HashMap<u64, usize>` field stays one chunk;
/// brackets and parens are already single `Group` tokens, but angles arrive as bare puncts.
fn parse_fields(body: TokenStream) -> Result<Vec<FieldDef>, String> {
    let mut fields = Vec::new();
    let mut chunk: Vec<TokenTree> = Vec::new();
    let mut angle_depth = 0i32;
    let mut prev_dash = false;

    for tt in body {
        match &tt {
            TokenTree::Punct(p) if p.as_char() == '<' => {
                angle_depth += 1;
                chunk.push(tt);
            }
            // `->` in a fn-pointer type must not close an angle bracket.
            TokenTree::Punct(p) if p.as_char() == '>' && !prev_dash => {
                angle_depth = (angle_depth - 1).max(0);
                chunk.push(tt);
            }
            TokenTree::Punct(p) if p.as_char() == ',' && angle_depth == 0 => {
                if !chunk.is_empty() {
                    fields.push(parse_one(&chunk)?);
                    chunk.clear();
                }
            }
            _ => chunk.push(tt),
        }
        prev_dash = matches!(
            chunk.last(),
            Some(TokenTree::Punct(p)) if p.as_char() == '-'
        );
    }
    if !chunk.is_empty() {
        fields.push(parse_one(&chunk)?);
    }
    Ok(fields)
}

fn parse_one(chunk: &[TokenTree]) -> Result<FieldDef, String> {
    let mut i = 0;
    let mut f = FieldDef::default();
    let mut deferred: Vec<Vec<Vec<TokenTree>>> = Vec::new();

    // Attributes and doc comments. `#[model(…)]` items need the field name for their errors,
    // so they are parsed after it is known.
    while i < chunk.len() {
        match &chunk[i] {
            TokenTree::Punct(p) if p.as_char() == '#' => {
                if let Some(TokenTree::Group(g)) = chunk.get(i + 1) {
                    if let Some(items) = attr_items(g, "obs") {
                        for item in items {
                            match item.as_slice() {
                                [TokenTree::Ident(id)] if id.to_string() == "key" => f.key = true,
                                [TokenTree::Ident(id)] if id.to_string() == "skip" => {
                                    f.skip = true;
                                }
                                other => {
                                    return Err(format!(
                                        "unknown #[obs] option: `{}` (supported: key, skip)",
                                        tokens_text(other)
                                    ));
                                }
                            }
                        }
                    } else if let Some(items) = attr_items(g, "model") {
                        deferred.push(items);
                    }
                    i += 2;
                    continue;
                }
                return Err("malformed attribute on a field".into());
            }
            _ => break,
        }
    }

    // Visibility.
    if let Some(TokenTree::Ident(id)) = chunk.get(i)
        && id.to_string() == "pub"
    {
        i += 1;
        if let Some(TokenTree::Group(g)) = chunk.get(i)
            && g.delimiter() == Delimiter::Parenthesis
        {
            i += 1;
        }
    }

    f.name = match chunk.get(i) {
        Some(TokenTree::Ident(id)) => id.to_string(),
        _ => return Err("expected a field name".into()),
    };
    i += 1;
    match chunk.get(i) {
        Some(TokenTree::Punct(p)) if p.as_char() == ':' => i += 1,
        _ => return Err(format!("expected `:` after field `{}`", f.name)),
    }

    // The type is whatever is left, re-emitted verbatim, never interpreted.
    f.ty = tokens_text(&chunk[i..]);
    if f.ty.is_empty() {
        return Err(format!("field `{}` has no type", f.name));
    }

    for items in deferred {
        parse_field_options(items, &mut f)?;
    }
    Ok(f)
}