tilo-resource-macros 0.5.2

Procedural macros for tilo-resource.
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
//! `#[derive(Effect)]`: a typed effect vocabulary from an enum.

use proc_macro2::TokenStream as Tokens;
use quote::{format_ident, quote};
use syn::spanned::Spanned;
use syn::{Data, DeriveInput, Fields};

use crate::{doc_lines, humanize, krate, snake_case};

/// A field's `#[param(…)]`: its description, after `secret,` when the
/// argument is a secret (an invite, a password) the host keeps out of logs,
/// history and confirmations, and then `choices = EXPR` when the values it
/// takes are a fixed list (any expression yielding strings, such as a
/// constant table), or `labelled_choices = EXPR` when each says how a person
/// reads it (`(value, label)` pairs). `place,` marks a place inside the resource
/// (`at: Option<Place>`): the effect acts there instead of at the invoker's
/// caret; `place = "field"` names the collection whose items it takes.
/// `decimal,` marks an identity the record or the surface names: it travels
/// as canonical decimal text, since a salted id outgrows what a JSON number
/// carries exactly, and any other text is refused when the effect is read.
#[derive(Default)]
struct Param {
    /// What the argument is beyond a value, by its leading flag.
    flag: Flag,
    /// The collection whose items the place names (`place = "blocks"`).
    place_in: Option<String>,
    description: Option<String>,
    /// The parameter's description as a key of the vocabulary's catalogue
    /// (`label = "app-param-name"`), read in the person's language where the
    /// action is published.
    label: Option<String>,
    choices: Option<syn::Expr>,
    /// Whether `choices` pairs each value with how a person reads it.
    labelled: bool,
    /// The argument's name where it differs from the field's (`name =
    /// "pageSize"`): a contract its callers already speak.
    name: Option<String>,
    /// `resource = "kind"`: a person picks an existing resource of that kind,
    /// the argument naming it (`ParamType::Resource`).
    resource: Option<String>,
}

/// A parameter's leading flag.
#[derive(Default, Clone, Copy, PartialEq, Eq)]
enum Flag {
    #[default]
    None,
    /// A secret the host keeps out of logs, history and confirmations.
    Secret,
    /// Content another action produced, carried as its hash; on a
    /// `Vec<String>`, a list of content, each item its hash.
    Content,
    /// A place inside the resource.
    Place,
    /// A documented struct whose fields are the effect's arguments (the
    /// effect's only field).
    Flatten,
    /// An identity, as canonical decimal text: anything else names no id.
    Identity,
}

impl syn::parse::Parse for Param {
    fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
        let mut param = Self::default();
        if input.peek(syn::Ident) && !input.peek2(syn::Token![=]) {
            let flag: syn::Ident = input.parse()?;
            if flag == "flatten" {
                param.flag = Flag::Flatten;
            } else if flag == "secret" {
                param.flag = Flag::Secret;
            } else if flag == "place" {
                param.flag = Flag::Place;
            } else if flag == "content" {
                param.flag = Flag::Content;
            } else if flag == "decimal" {
                param.flag = Flag::Identity;
            } else {
                return Err(syn::Error::new(
                    flag.span(),
                    "expected `secret`, `content`, `place`, `decimal` or `flatten`",
                ));
            }
            if input.is_empty() {
                return Ok(param);
            }
            input.parse::<syn::Token![,]>()?;
        }
        if input.peek(syn::LitStr) {
            param.description = Some(input.parse::<syn::LitStr>()?.value());
            if input.is_empty() {
                return Ok(param);
            }
            input.parse::<syn::Token![,]>()?;
        }
        while !input.is_empty() {
            if input.peek(syn::LitStr) {
                let text = input.parse::<syn::LitStr>()?;
                if param.description.replace(text.value()).is_some() {
                    return Err(syn::Error::new(text.span(), "one parameter description"));
                }
                if input.is_empty() {
                    break;
                }
                input.parse::<syn::Token![,]>()?;
                continue;
            }
            let key: syn::Ident = input.parse()?;
            input.parse::<syn::Token![=]>()?;
            if key == "place" {
                param.flag = Flag::Place;
                param.place_in = Some(input.parse::<syn::LitStr>()?.value());
            } else if key == "name" {
                param.name = Some(input.parse::<syn::LitStr>()?.value());
            } else if key == "label" {
                param.label = Some(input.parse::<syn::LitStr>()?.value());
            } else if key == "choices" || key == "labelled_choices" {
                param.labelled = key == "labelled_choices";
                param.choices = Some(input.parse()?);
            } else if key == "resource" {
                param.resource = Some(input.parse::<syn::LitStr>()?.value());
            } else {
                return Err(syn::Error::new(
                    key.span(),
                    "expected `choices = ...`, `labelled_choices = ...`, `place = \"field\"`, `resource = \"kind\"`, \
                     `name = \"argument\"` or `label = \"key\"`",
                ));
            }
            if !input.is_empty() {
                input.parse::<syn::Token![,]>()?;
            }
        }
        Ok(param)
    }
}

/// The compile error for a parameter whose Rust type describes no JSON schema:
/// what the type is, and the way out.
fn described_type_messages(param: &str) -> (String, &'static str) {
    (
        format!(
            "the effect parameter `{param}` describes no JSON schema: its type `{{Self}}` has none"
        ),
        "derive `JsonSchema` for `{Self}`",
    )
}

/// The `#[effect(...)]` options of the enum itself: the operation type its
/// effects are routed as, and the app whose `ActionKey`s they are published
/// under.
struct EnumOptions {
    operation: String,
    /// The app its typed references name their effects by.
    app: Option<String>,
    /// The directory of the catalogue its labels are keys of (`catalogue =
    /// "tests/locales"`), relative to the crate: `locales` by default.
    catalogue: Option<String>,
}

fn enum_options(input: &DeriveInput) -> syn::Result<EnumOptions> {
    let mut operation = None;
    let mut app = None;
    let mut catalogue = None;
    for attr in input
        .attrs
        .iter()
        .filter(|attr| attr.path().is_ident("effect"))
    {
        attr.parse_nested_meta(|meta| {
            if meta.path.is_ident("operation") {
                operation = Some(meta.value()?.parse::<syn::LitStr>()?.value());
                Ok(())
            } else if meta.path.is_ident("app") {
                app = Some(meta.value()?.parse::<syn::LitStr>()?.value());
                Ok(())
            } else if meta.path.is_ident("catalogue") {
                catalogue = Some(meta.value()?.parse::<syn::LitStr>()?.value());
                Ok(())
            } else {
                Err(meta.error(
                    "expected `operation = \"...\"`, `app = \"...\"` or `catalogue = \"dir\"`",
                ))
            }
        })?;
    }
    let operation = operation.ok_or_else(|| {
        syn::Error::new(
            input.ident.span(),
            "name the effects' operation type: `#[effect(operation = \"app.effects\")]`",
        )
    })?;
    Ok(EnumOptions {
        operation,
        app,
        catalogue,
    })
}

#[derive(Default)]
#[allow(
    clippy::struct_excessive_bools,
    reason = "one flag per option the attribute spells out"
)]
struct VariantOptions {
    label: Option<String>,
    /// `keywords = "…"`: the other words people use for the effect.
    keywords: Vec<String>,
    /// `icon = "…"`: the effect's own picture, by its Lucide name.
    icon: Option<String>,
    view: bool,
    row: bool,
    idempotent: bool,
    job: bool,
    cancellable: bool,
    returns: bool,
    /// `returns = Type`: the type of the value it answers with
    /// ([`JsonSchema`](tilo_resource::JsonSchema)), from which its return
    /// schema and its kind are published.
    returns_type: Option<syn::Path>,
    content: bool,
    destructive: bool,
    privileged: bool,
    sensitive: bool,
    /// `own_device`: the effect's whole scope is the invoking person's own
    /// device, touching nothing shared and no one else.
    own_device: bool,
    /// `attended`: the effect needs its person attending (a chooser, a
    /// credential, something only they may see): anyone acting for them is
    /// always asked first.
    attended: bool,
    /// `screen`: the effect only changes what is on the screen it is invoked
    /// on (a form it opens, a panel or a place it shows). It reads and answers
    /// nothing, only the person at that screen invokes it, and no agent is
    /// listed it.
    screen: bool,
    risk: Option<syn::Path>,
    /// `phrase = "path"`: the `fn(&Self) -> String` naming what one bound
    /// invocation loses, which its caller types to confirm it.
    phrase: Option<syn::Path>,
    /// `audience = "agents"` or `"people"`: who listings offer it to.
    audience: Option<syn::Ident>,
    untrusted: bool,
    /// `opens_path` declares the effect opens the file its `path` names;
    /// `opens_path = "csv,tsv"` limits it to those extensions.
    opens_path: Option<Vec<String>>,
    presence: bool,
    edit: bool,
    /// `document`: published as a document operation the app's own registry
    /// applies to the record it holds, as the history verbs are, rather than
    /// an effect its surface answers.
    document: bool,
    /// `prompted`: offered in the palette with its first parameter's prompt
    /// even where every parameter may be left out, as a named verb whose
    /// optional argument a person still says (how many steps to undo).
    prompted: bool,
    member: bool,
    kind: Option<String>,
    /// The entities whose ids the effect's first field is bound to: a
    /// collection's items (`item = field`) or a declared row type's rows
    /// (`on = RowType`). One variant may be offered on several of them (a
    /// queue and a recent video offer `play` alike), each binding its own
    /// row.
    targets: Vec<Target>,
    /// `offload(cpu_ms = N, memory_mb = N, output_mb = N, gpu)`: what a
    /// content transform needs of a device, so the system may dispatch it to
    /// the invoker's best-placed one.
    offload: Option<OffloadOption>,
    /// `host_render`: a host answers it in a render service of its own,
    /// never in the record's confined app worker.
    host_render: bool,
    /// `tag = <expr>`, repeatable: further contract tags, each a
    /// `&'static str` constant.
    tags: Vec<syn::Expr>,
    /// `outside_with = "param"`: a read that reaches outside the record only
    /// when that parameter is given.
    outside_with: Option<String>,
}

/// What an effect is offered on, as the variant declares it.
enum Target {
    /// The collection field whose items offer it.
    Field(String),
    /// The [`RowType`](tilo_resource::words::RowType) whose rows offer it.
    Row(syn::Path),
}

/// An effect's `offload(...)` option, as written.
struct OffloadOption {
    gpu: bool,
    cpu_ms: u64,
    memory_mb: u64,
    output_mb: u64,
}

/// Parse `offload(cpu_ms = N, memory_mb = N, output_mb = N, gpu)`; every key
/// but `gpu` is required.
fn offload_option(meta: &syn::meta::ParseNestedMeta<'_>) -> syn::Result<OffloadOption> {
    let mut gpu = false;
    let mut cpu_ms = None;
    let mut memory_mb = None;
    let mut output_mb = None;
    let number = |inner: &syn::meta::ParseNestedMeta<'_>| -> syn::Result<u64> {
        inner.value()?.parse::<syn::LitInt>()?.base10_parse()
    };
    meta.parse_nested_meta(|inner| {
        if inner.path.is_ident("gpu") {
            gpu = true;
        } else if inner.path.is_ident("cpu_ms") {
            cpu_ms = Some(number(&inner)?);
        } else if inner.path.is_ident("memory_mb") {
            memory_mb = Some(number(&inner)?);
        } else if inner.path.is_ident("output_mb") {
            output_mb = Some(number(&inner)?);
        } else {
            return Err(inner.error("expected `cpu_ms`, `memory_mb`, `output_mb` or `gpu`"));
        }
        Ok(())
    })?;
    let missing = |key: &str| meta.error(format!("`offload(...)` needs `{key} = ...`"));
    Ok(OffloadOption {
        gpu,
        cpu_ms: cpu_ms.ok_or_else(|| missing("cpu_ms"))?,
        memory_mb: memory_mb.ok_or_else(|| missing("memory_mb"))?,
        output_mb: output_mb.ok_or_else(|| missing("output_mb"))?,
    })
}

fn variant_options(attrs: &[syn::Attribute]) -> syn::Result<VariantOptions> {
    let mut options = VariantOptions::default();
    for attr in attrs.iter().filter(|attr| attr.path().is_ident("effect")) {
        attr.parse_nested_meta(|meta| {
            if meta.path.is_ident("label") {
                options.label = Some(meta.value()?.parse::<syn::LitStr>()?.value());
            } else if meta.path.is_ident("keywords") {
                options.keywords =
                    crate::keyword_list(&meta.value()?.parse::<syn::LitStr>()?)?;
            } else if meta.path.is_ident("icon") {
                options.icon = Some(crate::icon_name(&meta.value()?.parse::<syn::LitStr>()?)?);
            } else if meta.path.is_ident("kind") {
                options.kind = Some(meta.value()?.parse::<syn::LitStr>()?.value());
            } else if meta.path.is_ident("view") {
                options.view = true;
            } else if meta.path.is_ident("document") {
                options.document = true;
            } else if meta.path.is_ident("prompted") {
                options.prompted = true;
            } else if meta.path.is_ident("row") {
                options.row = true;
            } else if meta.path.is_ident("idempotent") {
                options.idempotent = true;
            } else if meta.path.is_ident("job") {
                options.job = true;
            } else if meta.path.is_ident("cancellable") {
                options.cancellable = true;
            } else if meta.path.is_ident("returns") {
                options.returns = true;
                if meta.input.peek(syn::Token![=]) {
                    options.returns_type = Some(meta.value()?.parse::<syn::Path>()?);
                }
            } else if meta.path.is_ident("content") {
                options.content = true;
            } else if meta.path.is_ident("destructive") {
                options.destructive = true;
            } else if meta.path.is_ident("privileged") {
                options.privileged = true;
            } else if meta.path.is_ident("sensitive") {
                options.sensitive = true;
            } else if meta.path.is_ident("own_device") {
                options.own_device = true;
            } else if meta.path.is_ident("attended") {
                options.attended = true;
            } else if meta.path.is_ident("screen") {
                options.screen = true;
            } else if meta.path.is_ident("risk") {
                options.risk = Some(meta.value()?.parse::<syn::LitStr>()?.parse::<syn::Path>()?);
            } else if meta.path.is_ident("phrase") {
                options.phrase =
                    Some(meta.value()?.parse::<syn::LitStr>()?.parse::<syn::Path>()?);
            } else if meta.path.is_ident("audience") {
                options.audience = Some(crate::audience_option(&meta)?);
            } else if meta.path.is_ident("untrusted") {
                options.untrusted = true;
            } else if meta.path.is_ident("opens_path") {
                options.opens_path = Some(if meta.input.peek(syn::Token![=]) {
                    meta.value()?
                        .parse::<syn::LitStr>()?
                        .value()
                        .split(',')
                        .map(|extension| extension.trim().to_ascii_lowercase())
                        .filter(|extension| !extension.is_empty())
                        .collect()
                } else {
                    Vec::new()
                });
            } else if meta.path.is_ident("presence") {
                options.presence = true;
            } else if meta.path.is_ident("edit") {
                options.edit = true;
            } else if meta.path.is_ident("member") {
                options.member = true;
            } else if meta.path.is_ident("item") {
                options.targets.push(Target::Field(
                    meta.value()?.parse::<syn::Ident>()?.to_string(),
                ));
            } else if meta.path.is_ident("on") {
                options
                    .targets
                    .push(Target::Row(meta.value()?.parse::<syn::Path>()?));
            } else if meta.path.is_ident("offload") {
                options.offload = Some(offload_option(&meta)?);
            } else if meta.path.is_ident("host_render") {
                options.host_render = true;
            } else if meta.path.is_ident("tag") {
                options.tags.push(meta.value()?.parse::<syn::Expr>()?);
            } else if meta.path.is_ident("outside_with") {
                options.outside_with = Some(meta.value()?.parse::<syn::LitStr>()?.value());
            } else {
                return Err(meta.error(
                    "expected `label`, `keywords`, `icon`, `view`, `document`, `prompted`, `row`, `job`, `cancellable`, `returns` (`returns = Type` for the value's type), `content`, \
                     `destructive`, `privileged`, `sensitive`, `idempotent`, \
                     `own_device`, `attended`, `screen`, `risk`, `phrase`, `audience`, `untrusted`, `opens_path`, `presence`, `edit`, `member`, \
                     `item = field`, `on = RowType`, `offload(...)`, `host_render`, `tag = ...`, `outside_with` or `kind`",
                ));
            }
            Ok(())
        })?;
    }
    Ok(options)
}

#[allow(
    clippy::too_many_lines,
    reason = "one linear expansion per variant reads better than helpers threading token lists"
)]
pub(crate) fn derive(input: &DeriveInput) -> syn::Result<Tokens> {
    let krate = krate();
    let name = &input.ident;
    let Data::Enum(data) = &input.data else {
        return Err(syn::Error::new(
            input.span(),
            "`Effect` is derived for an enum: one variant per effect",
        ));
    };
    if !input.generics.params.is_empty() {
        return Err(syn::Error::new(
            input.generics.span(),
            "an effect vocabulary has no generic parameters",
        ));
    }
    if data.variants.is_empty() {
        return Err(syn::Error::new(
            input.span(),
            "an effect vocabulary names at least one effect",
        ));
    }
    let EnumOptions {
        operation,
        app,
        catalogue,
    } = enum_options(input)?;
    let catalogue =
        crate::words::Catalogue::read(catalogue.as_deref().unwrap_or(crate::words::LOCALES));
    let any_arguments = data
        .variants
        .iter()
        .any(|variant| !matches!(variant.fields, Fields::Unit));

    let mut decls = Vec::new();
    let mut ids = Vec::new();
    let mut encodes = Vec::new();
    let mut decodes = Vec::new();
    let mut consts = Vec::new();
    let mut phrases = Vec::new();
    for variant in &data.variants {
        let options = variant_options(&variant.attrs)?;
        let ident = &variant.ident;
        let id = snake_case(&ident.to_string()).replace('_', "-");
        let docs = doc_lines(&variant.attrs);
        let written = docs
            .first()
            .map(|line| line.trim_end_matches('.').to_owned())
            .filter(|line| !line.is_empty())
            .unwrap_or_else(|| humanize(&snake_case(&ident.to_string())));
        let (label_word, label) = catalogue.declared(
            &krate,
            variant.span(),
            options.label.as_deref(),
            &crate::words::key(&operation, &id),
            &written,
        )?;
        // A bound invocation keeps the phrase its caller types, wherever the
        // effect is offered: the declaration decodes the arguments it is
        // bound with and names what it loses.
        let phrase = if options.phrase.is_some() {
            quote! {
                ::core::option::Option::Some((|arguments: &#krate::__private::serde_json::Map<
                    ::std::string::String,
                    #krate::__private::serde_json::Value,
                >| {
                    <Self as #krate::Effect>::decode(#id, arguments)
                        .ok()
                        .and_then(|effect| <Self as #krate::Effect>::confirmation_phrase(&effect))
                }) as #krate::effect::PhraseOf)
            }
        } else {
            quote!(::core::option::Option::None)
        };
        let description = docs
            .iter()
            .filter(|line| !line.is_empty())
            .cloned()
            .collect::<Vec<_>>()
            .join(" ");
        if options.view
            && (options.job
                || options.cancellable
                || options.destructive
                || options.privileged
                || options.sensitive)
        {
            return Err(syn::Error::new(
                variant.span(),
                "a `view` effect only changes what its caller sees: it answers at once and \
                 asks no confirmation (drop `job`, `cancellable`, `destructive`, `privileged` and `sensitive`)",
            ));
        }
        if options.screen
            && (options.kind.is_some()
                || options.view
                || options.edit
                || options.returns
                || options.content
                || options.job
                || options.cancellable
                || options.own_device
                || options.attended)
        {
            return Err(syn::Error::new(
                variant.span(),
                "a `screen` effect only changes the screen it is invoked on: it reads and \
                 answers nothing (drop `kind`, `view`, `edit`, `returns`, `content`, `job`, \
                 `cancellable`, `own_device` and `attended`)",
            ));
        }
        if options.document && (options.view || options.edit || options.screen) {
            return Err(syn::Error::new(
                variant.span(),
                "a `document` effect is an operation of the record's own document, not a \
                 view of its caller: drop `view`, `edit` and `screen`",
            ));
        }
        let action_kind = match options.kind.as_deref() {
            // An edit at the invoker's caret is an undoable change of the
            // record, whatever else it is.
            None if options.edit => quote!(Undoable),
            None if options.screen => quote!(Read),
            None if options.view => quote!(Read),
            Some("outside") => quote!(Outside),
            Some("read") => quote!(Read),
            Some("undoable") => quote!(Undoable),
            None => {
                return Err(syn::Error::new(
                    variant.span(),
                    "an effect states what it is where it is declared: write `kind = \
                     \"outside\"` for a change checked against the caller's grants, \
                     `kind = \"read\"` for a read or `kind = \"undoable\"` for an undoable \
                     change (`view` implies `read` and `edit` implies `undoable`)",
                ));
            }
            Some(other) => {
                return Err(syn::Error::new(
                    variant.span(),
                    format!("unknown kind `{other}`: `read`, `undoable` or `outside`"),
                ));
            }
        };

        let mut fields = Vec::new();
        match &variant.fields {
            Fields::Unit => {}
            Fields::Named(named) => {
                for field in &named.named {
                    let field_ident = field.ident.clone().ok_or_else(|| {
                        syn::Error::new(field.span(), "named field without a name")
                    })?;
                    let mut param = Param::default();
                    for attr in field
                        .attrs
                        .iter()
                        .filter(|attr| attr.path().is_ident("param"))
                    {
                        param = attr.parse_args::<Param>()?;
                    }
                    fields.push((field_ident, field.ty.clone(), param));
                }
            }
            Fields::Unnamed(_) => {
                return Err(syn::Error::new(
                    variant.span(),
                    "an effect's arguments are named fields: `Save { draft: String }`",
                ));
            }
        }

        let flattened = fields
            .iter()
            .any(|(_, _, described)| described.flag == Flag::Flatten);
        if flattened && fields.len() != 1 {
            return Err(syn::Error::new(
                variant.span(),
                "a `#[param(flatten)]` is the effect's only field: its fields are the arguments",
            ));
        }
        for (field, _, described) in &fields {
            if described.resource.is_some() && described.flag != Flag::None {
                return Err(syn::Error::new(
                    field.span(),
                    "`resource = \"kind\"` names one existing resource a person picks: it goes \
                     with no `secret`, `content`, `place`, `decimal` or `flatten`",
                ));
            }
        }
        let params = fields.iter().map(|(field, ty, described)| {
            if described.flag == Flag::Flatten {
                return Ok(quote!(#krate::__private::flat_params(
                    &<#ty as #krate::JsonSchema>::json_schema()
                )));
            }
            let param = described.name.clone().unwrap_or_else(|| field.to_string());
            let description = if let Some(key) = &described.label {
                let (word, _) = catalogue.declared(
                    &krate,
                    field.span(),
                    Some(key),
                    &crate::words::key(&operation, &id),
                    &humanize(&param),
                )?;
                quote!(#word.read())
            } else {
                let description = described
                    .description
                    .clone()
                    .unwrap_or_else(|| humanize(&param));
                quote!(#description)
            };
            let (known, optional) = crate::known_param_type(ty);
            let param_ty = if described.resource.is_some() {
                quote!(#krate::__private::ParamType::Resource)
            } else if described.flag == Flag::Secret {
                quote!(#krate::__private::ParamType::Secret)
            } else if let Some(known) = known {
                known
            } else {
                quote!(#krate::__private::param_type_of(
                    &<T as #krate::JsonSchema>::json_schema()
                ))
            };
            let (message, label) = described_type_messages(&param);
            // The value a wrapper carries must describe itself too: checked
            // here so the refusal names the parameter and that value rather
            // than only the wrapper's bound.
            let value = crate::parameter_value_type(ty);
            let checked_value = (value != ty).then(|| {
                quote!(
                    #[diagnostic::on_unimplemented(message = #message, label = #label)]
                    trait DescribedValue_: #krate::JsonSchema {}
                    impl<T: #krate::JsonSchema + ?Sized> DescribedValue_ for T {}
                    fn __effect_value<T: DescribedValue_ + ?Sized>() {}
                )
            });
            let check_value = (value != ty).then(|| quote!(__effect_value::<#value>();));
            // The one mapping from a declared type to its parameter, shared
            // with a verb's. The type is a parameter of the checker so a type
            // with no schema fails once, at the field, in these words.
            let declared = quote!({
                #[diagnostic::on_unimplemented(message = #message, label = #label)]
                trait Described_: #krate::JsonSchema {}
                impl<T: #krate::JsonSchema + ?Sized> Described_ for T {}
                fn __effect_param<T: Described_ + ?Sized>() -> #krate::__private::ActionParam {
                    #krate::__private::declared_param(
                        #param,
                        #param_ty,
                        #description,
                        <T as #krate::JsonSchema>::json_schema,
                        #optional,
                        #krate::__private::PlaceIn::Nowhere,
                        ::core::option::Option::None,
                    )
                }
                #checked_value
                #check_value
                __effect_param::<#ty>()
            });
            let declared = match &described.choices {
                Some(choices) if described.labelled => {
                    quote!(#declared.with_labelled_choices(#choices))
                }
                Some(choices) => quote!(#declared.with_choices(#choices)),
                None => declared,
            };
            let declared = if described.flag == Flag::Content {
                // A list of content (`Vec<String>`) names each item's hash.
                let list = crate::last_ident(ty).is_some_and(|(name, _)| name == "Vec");
                if list {
                    quote!(#declared.as_content_list())
                } else {
                    quote!(#declared.as_content())
                }
            } else {
                declared
            };
            let declared = match (&described.place_in, described.flag == Flag::Place) {
                (Some(field), _) => quote!(#declared.as_place_in(#field)),
                (None, true) => quote!(#declared.as_place()),
                (None, false) => declared,
            };
            let declared = match &described.resource {
                Some(kind) => quote!(#declared.of_resource_kind(#kind)),
                None => declared,
            };
            Ok(quote!(::std::vec![#declared]))
        });
        let answers = if options.job || options.cancellable {
            let cancellable = options.cancellable;
            let returns = options.returns;
            quote!(#krate::effect::Answers::Later { cancellable: #cancellable, returns: #returns })
        } else if options.content {
            quote!(#krate::effect::Answers::Content)
        } else if options.returns {
            quote!(#krate::effect::Answers::Value)
        } else {
            quote!(#krate::effect::Answers::Nothing)
        };
        let result = if let Some(ty) = &options.returns_type {
            quote!(::core::option::Option::Some(#krate::effect::EffectResult {
                schema: <#ty as #krate::JsonSchema>::json_schema,
                ty: ::core::option::Option::Some(<#ty as #krate::JsonSchema>::field_type),
            }))
        } else {
            quote!(::core::option::Option::None)
        };
        let risk = match (options.destructive, options.privileged, options.sensitive) {
            (true, false, false) => quote!(Destructive),
            (false, true, false) => quote!(Privileged),
            (false, false, true) => quote!(Sensitive),
            (false, false, false) if options.view => quote!(None),
            (false, false, false) => quote!(Low),
            _ => {
                return Err(syn::Error::new(
                    variant.span(),
                    "an effect is one of `destructive`, `privileged` or `sensitive`",
                ));
            }
        };
        let idempotent = options.idempotent;
        let own_device = options.own_device;
        let attended = options.attended;
        let risk_of = if let Some(classify) = &options.risk {
            quote! {
                ::std::option::Option::Some(
                    (|args: &#krate::__private::ActionArgs| -> #krate::__private::RiskLevel {
                        match <Self as #krate::Effect>::decode(#id, &args.to_json()) {
                            ::std::result::Result::Ok(effect) => #classify(&effect),
                            ::std::result::Result::Err(_) => #krate::__private::RiskLevel::Destructive,
                        }
                    }) as fn(&#krate::__private::ActionArgs) -> #krate::__private::RiskLevel,
                )
            }
        } else {
            quote!(::std::option::Option::None)
        };
        if let Some(phrase) = &options.phrase {
            if !options.destructive || (options.targets.is_empty() && !options.row) {
                return Err(syn::Error::new(
                    phrase.span(),
                    "a typed phrase names what one invocation loses: declare the effect \
                     `destructive` and offered only bound to what it erases (`row`, `on = Row` \
                     or `item = field`)",
                ));
            }
            let pattern = if matches!(variant.fields, Fields::Unit) {
                quote!(Self::#ident)
            } else {
                quote!(Self::#ident { .. })
            };
            phrases.push(quote!(#pattern => ::core::option::Option::Some(#phrase(self)),));
        }
        let row = options.row;
        let audience = options
            .audience
            .clone()
            .unwrap_or_else(|| syn::Ident::new("Everyone", variant.span()));
        let untrusted = options.untrusted;
        let opens = options.opens_path.as_ref().map_or_else(
            || quote!(::core::option::Option::None),
            |extensions| quote!(::core::option::Option::Some(&[#(#extensions),*])),
        );
        if options.presence && !options.view && !options.edit {
            return Err(syn::Error::new(
                variant.span(),
                "`presence` declares a view of the invoking presence: add `view`",
            ));
        }
        let presence = options.presence;
        let edits = options.edit;
        let prompted = options.prompted;
        let member = options.member;
        // An effect with arguments binds its first to the entity it is offered
        // on. One without (showing a set of remotes) is offered on every entity
        // of the type as it is: the entity changes nothing about it.
        let items = if options.targets.is_empty() {
            quote!(&[])
        } else {
            let targets = options.targets.iter().map(|target| match target {
                Target::Field(field) => quote!(#krate::effect::EffectTarget::Field(#field)),
                Target::Row(path) => quote! {
                    #krate::effect::EffectTarget::Row(
                        <#path as #krate::words::RowType>::KIND,
                    )
                },
            });
            quote!(&[#(#targets),*])
        };
        // A row id is not always the text the effect acts on: offered on a
        // row, the first parameter reads the id as its own type (`u64` counts,
        // an identity parses), and a row whose id is not one is refused.
        let row_id = if options
            .targets
            .iter()
            .any(|target| matches!(target, Target::Row(_)))
        {
            fields.first().map_or_else(
                || quote!(::core::option::Option::None),
                |(_, ty, _)| {
                    quote! {
                        ::core::option::Option::Some((|id: &str| {
                            // The field's own serde type reads the id: a
                            // string as it is, a number from its decimal text.
                            #krate::__private::serde_json::from_value::<#ty>(
                                #krate::__private::serde_json::Value::String(id.to_owned()),
                            )
                            .or_else(|_| #krate::__private::serde_json::from_str::<#ty>(id))
                            .ok()
                            .and_then(|value| #krate::__private::serde_json::to_value(value).ok())
                            .ok_or_else(|| format!("`{id}` is not one this effect acts on"))
                        }) as #krate::effect::RowIdOf)
                    }
                },
            )
        } else {
            quote!(::core::option::Option::None)
        };
        let reads = match options.kind.as_deref() {
            Some(kind) => kind == "read",
            None => options.view && !options.edit,
        };
        let offload = match &options.offload {
            None => quote!(::core::option::Option::None),
            Some(_) if !reads || !options.content => {
                return Err(syn::Error::new(
                    variant.span(),
                    "an `offload` effect is a content transform any device may run: declare it \
                     `content` and `kind = \"read\"`",
                ));
            }
            Some(OffloadOption {
                gpu,
                cpu_ms,
                memory_mb,
                output_mb,
            }) => {
                let mib = |megabytes: u64| megabytes.saturating_mul(1024 * 1024);
                let (memory_bytes, output_bytes) = (mib(*memory_mb), mib(*output_mb));
                quote!(::core::option::Option::Some(#krate::effect::EffectOffload {
                    gpu: #gpu,
                    cpu_time_ms: #cpu_ms,
                    memory_bytes: #memory_bytes,
                    output_bytes: #output_bytes,
                }))
            }
        };
        let kind = if options.document {
            quote!(Document)
        } else if options.view || options.edit {
            quote!(View)
        } else {
            quote!(Effect)
        };
        // Each one a constant, as the row it lands in is.
        let host_render = options
            .host_render
            .then(|| quote!(#krate::__private::HOST_RENDER_TAG))
            .into_iter();
        // A screen effect offered on rows or items shows the one it names.
        let place = (options.screen && !options.targets.is_empty() && !fields.is_empty())
            .then(|| quote!(#krate::__private::SCREEN_PLACE_TAG));
        let screen = options
            .screen
            .then(|| quote!(#krate::__private::SCREEN_TAG))
            .into_iter()
            .chain(place);
        let declared = &options.tags;
        let tags = quote!(&[#(#host_render,)* #(#screen,)* #(#declared),*]);
        let outside_with = match &options.outside_with {
            None => quote!(::core::option::Option::None),
            Some(_) if !reads => {
                return Err(syn::Error::new(
                    variant.span(),
                    "`outside_with` names what makes a read reach outside: declare it \
                     `kind = \"read\"`",
                ));
            }
            Some(param) => quote!(::core::option::Option::Some(#param)),
        };
        let params: Vec<Tokens> = params.collect::<syn::Result<Vec<_>>>()?;
        // Each parameter's surface type, when its Rust type describes one: a record or enum its
        // wire type (an object) says nothing of.
        let typed: Vec<Tokens> = fields
            .iter()
            .filter(|(_, _, described)| {
                described.flag != Flag::Flatten && described.flag != Flag::Secret
            })
            .map(|(field, ty, described)| {
                let param = described.name.clone().unwrap_or_else(|| field.to_string());
                if let Some(kind) = &described.resource {
                    return quote! {{
                        types.push((
                            #param,
                            (|_: &mut #krate::TypeSet| {
                                #krate::FieldType::Resource(::std::string::String::from(#kind))
                            }) as #krate::surface::FieldTypeOf,
                        ));
                    }};
                }
                let (message, label) = described_type_messages(&param);
                quote! {{
                    #[diagnostic::on_unimplemented(message = #message, label = #label)]
                    trait Described_: #krate::JsonSchema {}
                    impl<T: #krate::JsonSchema + ?Sized> Described_ for T {}
                    fn __effect_field_type<T: Described_ + ?Sized>()
                        -> #krate::surface::FieldTypeOf
                    {
                        <T as #krate::JsonSchema>::field_type
                    }
                    types.push((#param, __effect_field_type::<#ty>()));
                }}
            })
            .collect();
        let param_types_fn = if typed.is_empty() {
            quote!(#krate::effect::no_param_types)
        } else {
            quote!(|| {
                let mut types: ::std::vec::Vec<(&'static str, #krate::surface::FieldTypeOf)> =
                    ::std::vec::Vec::new();
                #(#typed)*
                types
            })
        };
        let keywords = &options.keywords;
        let icon = crate::optional_str(options.icon.as_deref());
        let params_fn = if params.is_empty() {
            quote!(#krate::effect::no_params)
        } else {
            quote!(|| {
                let mut params: ::std::vec::Vec<#krate::__private::ActionParam> =
                    ::std::vec::Vec::new();
                #(params.extend(#params);)*
                params
            })
        };
        decls.push(quote! {
            #krate::effect::EffectRow {
                id: #id,
                label: #label_word,
                keywords: &[#(#keywords),*],
                icon: #icon,
                description: #description,
                params: #params_fn,
                param_types: #param_types_fn,
                result: #result,
                kind: #krate::__private::OperationKind::#kind,
                prompted: #prompted,
                row: #row,
                answers: #answers,
                risk: #krate::__private::RiskLevel::#risk,
                idempotent: #idempotent,
                action_kind: #krate::__private::ActionKind::#action_kind,
                own_device: #own_device,
                attended: #attended,
                risk_of: #risk_of,
                audience: #krate::__private::Audience::#audience,
                untrusted: #untrusted,
                opens: #opens,
                presence: #presence,
                edits: #edits,
                member: #member,
                items: #items,
                row_id: #row_id,
                phrase: #phrase,
                offload: #offload,
                tags: #tags,
                outside_with: #outside_with,
            }
        });

        let field_idents: Vec<_> = fields.iter().map(|(field, _, _)| field.clone()).collect();
        let field_names: Vec<String> = fields
            .iter()
            .map(|(field, _, described)| {
                described.name.clone().unwrap_or_else(|| field.to_string())
            })
            .collect();
        let field_decodes: Vec<Tokens> = fields
            .iter()
            .map(|(field, ty, described)| {
                let name = described.name.clone().unwrap_or_else(|| field.to_string());
                let decode = if described.flag == Flag::Identity {
                    match identity_field(ty) {
                        Some(IdentityForm::Optional) => {
                            quote!(#krate::effect::optional_identity_argument(arguments, #name)?)
                        }
                        Some(IdentityForm::Text) => {
                            quote!(#krate::effect::identity_argument(arguments, #name)?)
                        }
                        None => {
                            return Err(syn::Error::new(
                                field.span(),
                                "`decimal` is for an identity carried as text: `String` or \
                                 `Option<String>`",
                            ));
                        }
                    }
                } else {
                    quote!(#krate::effect::argument(arguments, #name)?)
                };
                Ok(decode)
            })
            .collect::<syn::Result<Vec<Tokens>>>()?;
        let pattern = if matches!(variant.fields, Fields::Unit) {
            quote!(Self::#ident)
        } else {
            quote!(Self::#ident { #(#field_idents,)* })
        };
        let ignore = if matches!(variant.fields, Fields::Unit) {
            quote!(Self::#ident)
        } else {
            quote!(Self::#ident { .. })
        };
        ids.push(quote!(#ignore => #id,));
        let (encode, build) = if let Some(field) = field_idents.first().filter(|_| flattened) {
            (
                quote! {
                    if let ::core::result::Result::Ok(#krate::__private::serde_json::Value::Object(fields)) =
                        #krate::__private::serde_json::to_value(#field)
                    {
                        // An absent option is left out, as an argument not given.
                        arguments.extend(fields.into_iter().filter(|(_, value)| !value.is_null()));
                    }
                },
                quote!(Self::#ident {
                    #field: #krate::effect::flattened_argument(
                        arguments,
                        ::core::stringify!(#field),
                    )?,
                }),
            )
        } else if matches!(variant.fields, Fields::Unit) {
            (quote!(), quote!(Self::#ident))
        } else {
            (
                quote!(#(#krate::effect::put(&mut arguments, #field_names, #field_idents);)*),
                quote!(Self::#ident { #(#field_idents: #field_decodes,)* }),
            )
        };
        encodes.push(quote! {
            #pattern => {
                #encode
            }
        });
        decodes.push(quote!(#id => ::core::result::Result::Ok(#build),));

        let const_ident = format_ident!("{}", snake_case(&ident.to_string()).to_uppercase());
        let tys: Vec<&syn::Type> = fields.iter().map(|(_, ty, _)| ty).collect();
        let input_ty = match tys.as_slice() {
            [] => quote!(()),
            [single] => quote!(#single),
            many => quote!((#(#many,)*)),
        };
        let const_doc = format!("Bind a control to the `{id}` effect: {label}.");
        consts.push(quote! {
            #[doc = #const_doc]
            pub const #const_ident: #krate::ActionRef<#name, #input_ty> =
                #krate::ActionRef::new(
                    #id,
                    &[#(#field_names),*],
                    #krate::ResourceKind::of_effect::<#name>(
                        #operation,
                        <#name as #krate::Effect>::LABEL,
                        <#name as #krate::Effect>::APP_ID,
                    ),
                );
        });
    }

    let arguments_binding = if any_arguments {
        quote!(arguments)
    } else {
        quote!(_arguments)
    };
    let app_id = app
        .as_ref()
        .map_or_else(|| quote!(#krate::kind::DEFAULT_APP), |app| quote!(#app));
    let row_count = decls.len();
    let rows = decls.into_iter().map(|row| name_self(row, name));
    let phrase = (!phrases.is_empty()).then(|| {
        quote! {
            fn confirmation_phrase(&self) -> ::core::option::Option<::std::string::String> {
                #[allow(unreachable_patterns, reason = "the other effects are confirmed without typing")]
                match self {
                    #(#phrases)*
                    _ => ::core::option::Option::None,
                }
            }
        }
    });
    catalogue.missing()?;
    Ok(quote! {
        impl #krate::Effect for #name {
            const OPERATION: &'static str = #operation;

            const APP_ID: &'static str = #app_id;

            fn declarations() -> ::std::vec::Vec<#krate::effect::EffectDecl> {
                #krate::effect::EffectDecl::of_rows(Self::__effect_rows())
            }

            fn declaration(id: &str) -> ::core::option::Option<#krate::effect::EffectDecl> {
                #krate::effect::EffectDecl::find_row(Self::__effect_rows(), id)
            }

            fn id(&self) -> &'static str {
                match self {
                    #(#ids)*
                }
            }

            fn rows() -> ::std::vec::Vec<#krate::effect::EffectRow> {
                <[_]>::to_vec(Self::__effect_rows())
            }

            #phrase

            #[allow(unused_mut, reason = "a unit effect has no arguments to insert")]
            fn arguments(&self) -> #krate::__private::serde_json::Map<::std::string::String, #krate::__private::serde_json::Value> {
                let mut arguments = #krate::__private::serde_json::Map::new();
                match self {
                    #(#encodes)*
                }
                arguments
            }

            fn decode(
                id: &str,
                #arguments_binding: &#krate::__private::serde_json::Map<::std::string::String, #krate::__private::serde_json::Value>,
            ) -> ::core::result::Result<Self, #krate::effect::EffectDecodeError> {
                match id {
                    #(#decodes)*
                    other => ::core::result::Result::Err(
                        #krate::effect::EffectDecodeError::Unknown(::std::string::ToString::to_string(other)),
                    ),
                }
            }
        }

        #[allow(dead_code, reason = "a control binds the effects it offers, not necessarily all")]
        impl #name {
            #(#consts)*

            /// Every effect's declaration, read by one function for every
            /// vocabulary. A `static` rather than a `const`, so the table has
            /// one address and is never built at a use site: a large app's
            /// rows outgrow what may sit on the stack.
            #[doc(hidden)]
            pub fn __effect_rows() -> &'static [#krate::effect::EffectRow] {
                static ROWS: [#krate::effect::EffectRow; #row_count] = [#(#rows),*];
                &ROWS
            }
        }
    })
}

/// The rows live in a `static` inside a function, which cannot see the
/// impl's `Self`: every `Self` in a row (the derive's own or one an app wrote
/// in an attribute expression) names the enum instead. The derive rejects
/// generic enums, so the bare name is the whole type.
fn name_self(tokens: Tokens, name: &syn::Ident) -> Tokens {
    use proc_macro2::{Group, TokenTree};
    tokens
        .into_iter()
        .map(|tree| match tree {
            TokenTree::Ident(ident) if ident == "Self" => {
                TokenTree::Ident(syn::Ident::new(&name.to_string(), ident.span()))
            }
            TokenTree::Group(group) => {
                let mut renamed = Group::new(group.delimiter(), name_self(group.stream(), name));
                renamed.set_span(group.span());
                TokenTree::Group(renamed)
            }
            other => other,
        })
        .collect()
}

/// How a `#[param(decimal)]` field carries its identity.
enum IdentityForm {
    /// `String`: the effect always names one.
    Text,
    /// `Option<String>`: the effect may name none.
    Optional,
}

/// How a `#[param(decimal)]` field carries its identity, when it is declared
/// the way a decimal id is: as `String` or `Option<String>` text.
fn identity_field(ty: &syn::Type) -> Option<IdentityForm> {
    match crate::last_ident(ty) {
        Some((name, None)) if name == "String" => Some(IdentityForm::Text),
        Some((name, Some(inner))) if name == "Option" => match crate::last_ident(inner) {
            Some((inner, None)) if inner == "String" => Some(IdentityForm::Optional),
            _ => None,
        },
        _ => None,
    }
}

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

    /// The error an effect vocabulary written as `source` does not build with.
    fn error(source: &str) -> String {
        let input: syn::DeriveInput = syn::parse_str(source).expect("an effect vocabulary");
        derive(&input)
            .expect_err("the vocabulary is refused")
            .to_string()
    }

    #[test]
    fn an_effect_without_a_kind_is_told_what_to_write() {
        let error = error(
            r#"
            #[effect(operation = "example.effects")]
            enum ExampleEffect {
                /// Keep the draft.
                Save,
            }
            "#,
        );
        assert!(error.contains("`kind = \"outside\"`"), "{error}");
        assert!(error.contains("`kind = \"read\"`"), "{error}");
        assert!(error.contains("`kind = \"undoable\"`"), "{error}");
    }

    #[test]
    fn a_view_effect_needs_no_kind_declaration() {
        let input: syn::DeriveInput = syn::parse_str(
            r#"
            #[effect(operation = "example.effects")]
            enum ExampleEffect {
                /// Show the draft.
                #[effect(view)]
                Show { draft: String },
            }
            "#,
        )
        .expect("an effect vocabulary");
        // The crate has no catalogue, so the label is what is missing: the
        // derive got past the variant's kind.
        let error = derive(&input)
            .expect_err("the label is missing")
            .to_string();
        assert!(error.contains("en-US.ftl"), "{error}");
        assert!(!error.contains("states what it is"), "{error}");
    }
}