rototo 0.1.0-alpha.6

Control plane for runtime configuration of your application.
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
use std::fmt;

use serde::{Serialize, Serializer};

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum DiagnosticEntity {
    Package,
    Qualifier,
    Variable,
    Catalog,
    CatalogEntry,
    EvaluationContext,
    EvaluationContextSample,
    Value,
    Rule,
}

#[derive(Debug, Clone, Copy)]
pub struct RuleMeta {
    pub rule: &'static str,
    pub severity: Severity,
    pub entity: DiagnosticEntity,
    pub title: &'static str,
    pub help: &'static str,
}

macro_rules! rototo_rule_severity {
    () => {
        Severity::Error
    };
    ($severity:ident) => {
        Severity::$severity
    };
}

macro_rules! rototo_rules {
    ($($variant:ident => {
        id: $id:literal,
        entity: $entity:ident,
        title: $title:literal,
        help: $help:literal $(,
        severity: $severity:ident)? $(,)?
    }),+ $(,)?) => {
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
        pub enum RototoRuleId {
            $($variant),+
        }

        impl RototoRuleId {
            pub const ALL: &'static [Self] = &[
                $(Self::$variant),+
            ];

            pub fn iter() -> impl Iterator<Item = Self> {
                Self::ALL
                    .iter()
                    .copied()
                    .filter(|rule| !rule.is_retired())
            }

            pub fn is_retired(self) -> bool {
                matches!(
                    self,
                    Self::PackageContextSchemaRef
                        | Self::PackageContextSchemaAttribute
                        | Self::PackageContextSchemaReservedField
                        | Self::PackageContextSchemaMissing
                        | Self::QualifierPredicateMissing
                        | Self::QualifierPredicateShape
                        | Self::QualifierPredicateUnknownOp
                        | Self::QualifierPredicateUnknownQualifier
                        | Self::QualifierPredicateBucket
                        | Self::QualifierPredicateValue
                        | Self::QualifierPredicateContextTypeMismatch
                        | Self::QualifierPredicateDuplicate
                        | Self::CatalogSchemaVersion
                        | Self::CatalogSchemaRef
                )
            }

            pub fn meta(self) -> RuleMeta {
                match self {
                    $(Self::$variant => RuleMeta {
                        rule: concat!("rototo/", $id),
                        severity: rototo_rule_severity!($($severity)?),
                        entity: DiagnosticEntity::$entity,
                        title: $title,
                        help: $help,
                    }),+
                }
            }
        }
    };
}

rototo_rules! {
    PackageNotFound => {
        id: "package-not-found",
        entity: Package,
        title: "Package was not found",
        help: "Pass a path to an existing rototo package directory.",
    },
    PackageManifestMissing => {
        id: "package-manifest-missing",
        entity: Package,
        title: "Package manifest is missing",
        help: "Create rototo-package.toml at the package root.",
    },
    PackageManifestParseFailed => {
        id: "package-manifest-parse-failed",
        entity: Package,
        title: "Package manifest could not be parsed",
        help: "Fix the TOML syntax in rototo-package.toml.",
    },
    PackageManifestSchemaFailed => {
        id: "package-manifest-schema-failed",
        entity: Package,
        title: "Package manifest does not match schema",
        help: "Declare schema_version = 1 and optional extends in rototo-package.toml.",
    },
    TraceWhenMissing => {
        id: "trace-when-missing",
        entity: Package,
        title: "Trace policy is missing when",
        help: "Each [[trace]] policy must declare when = \"<expression>\".",
    },
    TraceWhenShape => {
        id: "trace-when-shape",
        entity: Package,
        title: "Trace policy when expression is invalid",
        help: "A [[trace]] when must be a string holding a valid boolean expression.",
    },
    TraceWhenInvalidReference => {
        id: "trace-when-invalid-reference",
        entity: Package,
        title: "Trace policy when references an unknown identifier",
        help: "Trace when reads context.<path>, env.qualifier[\"<id>\"], env.now, and env.resolving.variable / env.resolving.qualifier.",
    },
    PackageContextSchemaRef => {
        id: "package-context-schema-ref",
        entity: Package,
        title: "Evaluation context schema is invalid",
        help: "Retired. Use evaluation-contexts/<id>.schema.json for evaluation context validation.",
    },
    PackageContextSchemaAttribute => {
        id: "package-context-schema-attribute",
        entity: Package,
        title: "Qualifier context attribute is not declared by the evaluation context schema",
        help: "Declare the context path in the package context schema or update the qualifier.",
    },
    PackageContextSchemaReservedField => {
        id: "package-context-schema-reserved-field",
        entity: Package,
        title: "Evaluation context schema declares a reserved field",
        help: "Rename the evaluation context field; qualifier is reserved for qualifier.<id> predicate references.",
    },
    PackageContextSchemaMissing => {
        id: "package-context-schema-missing",
        entity: Package,
        title: "Evaluation context schema is missing",
        help: "Retired. Add evaluation-contexts/<id>.schema.json for evaluation context validation.",
        severity: Warning,
    },
    EvaluationContextSchemaInvalid => {
        id: "evaluation-context-schema-invalid",
        entity: EvaluationContext,
        title: "Evaluation context schema is invalid",
        help: "Fix the evaluation-contexts/<id>.schema.json file so it parses and compiles as JSON Schema.",
    },
    EvaluationContextReservedField => {
        id: "evaluation-context-reserved-field",
        entity: EvaluationContext,
        title: "Evaluation context schema declares a reserved field",
        help: "Rename the evaluation context field; qualifier is reserved for qualifier.<id> predicate references.",
    },
    EvaluationContextSampleSchemaMismatch => {
        id: "evaluation-context-sample-schema-mismatch",
        entity: EvaluationContextSample,
        title: "Evaluation context sample does not match its schema",
        help: "Update the evaluation context sample so it validates against the owning evaluation context schema.",
    },
    EvaluationContextSampleShape => {
        id: "evaluation-context-sample-shape",
        entity: EvaluationContextSample,
        title: "Evaluation context sample is invalid",
        help: "Evaluation context samples must parse as JSON objects.",
    },
    QualifierParseFailed => {
        id: "qualifier-parse-failed",
        entity: Qualifier,
        title: "Qualifier TOML file could not be parsed",
        help: "Fix the TOML syntax so rototo can parse the qualifier file.",
    },
    QualifierSchemaVersion => {
        id: "qualifier-schema-version",
        entity: Qualifier,
        title: "Qualifier schema version is missing or unsupported",
        help: "Declare schema_version = 1 in the qualifier file.",
    },
    QualifierWhenMissing => {
        id: "qualifier-when-missing",
        entity: Qualifier,
        title: "Qualifier condition is missing",
        help: "Add an expression with when = \"...\".",
    },
    QualifierWhenShape => {
        id: "qualifier-when-shape",
        entity: Qualifier,
        title: "Qualifier condition is invalid",
        help: "Use when = \"...\" with a valid expression.",
    },
    QualifierWhenUnknownQualifier => {
        id: "qualifier-when-unknown-qualifier",
        entity: Qualifier,
        title: "Qualifier condition references an unknown qualifier",
        help: "Create the referenced qualifier or update the qualifier reference in the when expression.",
    },
    QualifierWhenUndeclaredContextPath => {
        id: "qualifier-when-undeclared-context-path",
        entity: Qualifier,
        title: "Qualifier when expression references an undeclared context path",
        help: "Declare the attribute in an evaluation context schema under evaluation-contexts/<id>.schema.json, or fix the path in the when expression.",
    },
    QualifierWhenInvalidReference => {
        id: "qualifier-when-invalid-reference",
        entity: Qualifier,
        title: "Qualifier when expression references an identifier rototo does not provide",
        help: "Expressions read context.<path>, env.qualifier[\"<id>\"], and env.now. Reference qualifiers as env.qualifier[\"<id>\"].",
    },
    QualifierWhenContextPathTypeMismatch => {
        id: "qualifier-when-context-path-type-mismatch",
        entity: Qualifier,
        title: "Qualifier when expression uses a context path with the wrong type",
        help: "Declare the context attribute with a type that matches how the when expression uses it, or change the comparison to match the declared type.",
    },
    QualifierPredicateMissing => {
        id: "qualifier-predicate-missing",
        entity: Qualifier,
        title: "Qualifier predicate is missing",
        help: "Retired. Use when = \"...\" with a valid expression.",
    },
    QualifierPredicateShape => {
        id: "qualifier-predicate-shape",
        entity: Qualifier,
        title: "Qualifier predicate has the wrong shape",
        help: "Retired. Use when = \"...\" with a valid expression.",
    },
    QualifierPredicateUnknownOp => {
        id: "qualifier-predicate-unknown-op",
        entity: Qualifier,
        title: "Qualifier predicate uses an unknown operator",
        help: "Use a supported predicate operator such as eq, in, gte, prefix, regex, semver, time_between, exists, between, contains_any, cidr, or bucket.",
    },
    QualifierPredicateUnknownQualifier => {
        id: "qualifier-predicate-unknown-qualifier",
        entity: Qualifier,
        title: "Qualifier predicate references an unknown qualifier",
        help: "Create the referenced qualifier or update the qualifier.<id> reference.",
    },
    QualifierPredicateBucket => {
        id: "qualifier-predicate-bucket",
        entity: Qualifier,
        title: "Bucket predicate is invalid",
        help: "Bucket predicates need salt and range = [start, end] with 0 <= start < end <= 10000.",
    },
    QualifierPredicateValue => {
        id: "qualifier-predicate-value",
        entity: Qualifier,
        title: "Qualifier predicate value is invalid",
        help: "Add a value with the shape required by the predicate operator.",
    },
    QualifierPredicateContextTypeMismatch => {
        id: "qualifier-predicate-context-type-mismatch",
        entity: Qualifier,
        title: "Qualifier predicate does not match the evaluation context schema type",
        help: "Update the predicate operator or value so it matches the context schema field type.",
    },
    QualifierNoCompatibleEvaluationContext => {
        id: "qualifier-no-compatible-evaluation-context",
        entity: Qualifier,
        title: "Qualifier has no compatible evaluation context",
        help: "Add an evaluation context schema under evaluation-contexts/<id>.schema.json that declares the qualifier's context attributes, or update the qualifier predicates.",
    },
    QualifierPredicateDuplicate => {
        id: "qualifier-predicate-duplicate",
        entity: Qualifier,
        title: "Qualifier predicate is duplicated",
        help: "Remove duplicate predicates that do not change qualifier behavior.",
        severity: Warning,
    },
    QualifierCycle => {
        id: "qualifier-cycle",
        entity: Qualifier,
        title: "Qualifier references form a cycle",
        help: "Remove the qualifier reference cycle so qualifier evaluation can terminate.",
    },
    QualifierUnreferenced => {
        id: "qualifier-unreferenced",
        entity: Qualifier,
        title: "Qualifier is not referenced",
        help: "Reference the qualifier from another qualifier or variable rule, or remove it.",
        severity: Warning,
    },
    QualifierUnreachable => {
        id: "qualifier-unreachable",
        entity: Qualifier,
        title: "Qualifier cannot affect resolution",
        help: "Reference the qualifier from a reachable variable rule path, or remove it.",
        severity: Warning,
    },
    VariableParseFailed => {
        id: "variable-parse-failed",
        entity: Variable,
        title: "Variable TOML file could not be parsed",
        help: "Fix the TOML syntax so rototo can parse the variable file.",
    },
    VariableSchemaVersion => {
        id: "variable-schema-version",
        entity: Variable,
        title: "Variable schema version is missing or unsupported",
        help: "Declare schema_version = 1 in the variable file.",
    },
    VariableTypeSource => {
        id: "variable-type-source",
        entity: Variable,
        title: "Variable type source is invalid",
        help: "Declare type as a primitive type or catalog:<catalog-id>.",
    },
    VariableUnknownType => {
        id: "variable-unknown-type",
        entity: Variable,
        title: "Variable type is unknown",
        help: "Use one of bool, int, number, string, list, or catalog:<catalog-id>.",
    },
    VariableUnknownCatalog => {
        id: "variable-unknown-catalog",
        entity: Variable,
        title: "Variable references an unknown catalog",
        help: "Create the referenced catalog or update the catalog type.",
    },
    VariableValuesDisallowed => {
        id: "variable-values-disallowed",
        entity: Variable,
        title: "Variable values are not allowed",
        help: "Remove [values] and put literal values directly under [resolve].",
    },
    VariableUnknownValue => {
        id: "variable-unknown-value",
        entity: Variable,
        title: "Variable references an unknown catalog value",
        help: "Create the referenced catalog value or update the reference.",
    },
    VariableValueTypeMismatch => {
        id: "variable-value-type-mismatch",
        entity: Variable,
        title: "Variable value does not match type",
        help: "Update the value so it matches the declared primitive type.",
    },
    CatalogParseFailed => {
        id: "catalog-parse-failed",
        entity: Catalog,
        title: "Catalog schema file could not be parsed",
        help: "Fix the JSON syntax so rototo can parse the catalog schema file.",
    },
    CatalogEntryParseFailed => {
        id: "catalog-entry-parse-failed",
        entity: CatalogEntry,
        title: "Catalog value TOML file could not be parsed",
        help: "Fix the TOML syntax so rototo can parse the catalog value file.",
    },
    CatalogSchemaVersion => {
        id: "catalog-schema-version",
        entity: Catalog,
        title: "Catalog schema version is missing or unsupported",
        help: "Declare schema_version = 1 in the catalog file.",
    },
    CatalogSchemaRef => {
        id: "catalog-schema-ref",
        entity: Catalog,
        title: "Catalog schema reference is invalid",
        help: "Point schema to a readable valid JSON Schema file.",
    },
    CatalogSchemaInvalid => {
        id: "catalog-schema-invalid",
        entity: Catalog,
        title: "Catalog schema is invalid",
        help: "Update catalogs/<id>.schema.json so it is a valid JSON Schema.",
    },
    CatalogEntrySchemaMismatch => {
        id: "catalog-entry-schema-mismatch",
        entity: CatalogEntry,
        title: "Catalog value does not match schema",
        help: "Update the catalog value so it matches the catalog JSON Schema.",
    },
    CatalogEntryUnknownReference => {
        id: "catalog-entry-unknown-reference",
        entity: CatalogEntry,
        title: "Catalog value references an invalid catalog entry",
        help: "Create the referenced catalog entry, fix the pointer, or update the x-rototo-catalog-ref field.",
    },
    VariableResolveMissingDefault => {
        id: "variable-resolve-missing-default",
        entity: Variable,
        title: "Variable resolve default is missing",
        help: "Add [resolve].default with a value reference.",
    },
    VariableResolveShape => {
        id: "variable-resolve-shape",
        entity: Variable,
        title: "Variable resolve block is invalid",
        help: "Resolve blocks must be tables with default and optional rule references.",
    },
    VariableRuleShape => {
        id: "variable-rule-shape",
        entity: Variable,
        title: "Variable rule is invalid",
        help: "Rules must be tables with qualifier and value references.",
    },
    VariableRuleUnknownQualifier => {
        id: "variable-rule-unknown-qualifier",
        entity: Variable,
        title: "Variable rule references an unknown qualifier",
        help: "Create the referenced qualifier or update the rule.",
    },
    VariableRuleUndeclaredContextPath => {
        id: "variable-rule-undeclared-context-path",
        entity: Rule,
        title: "Variable rule references an undeclared context path",
        help: "Declare the attribute in an evaluation context schema under evaluation-contexts/<id>.schema.json, or fix the path in the rule when/query expression.",
    },
    VariableRuleInvalidReference => {
        id: "variable-rule-invalid-reference",
        entity: Rule,
        title: "Variable rule references an identifier rototo does not provide",
        help: "Expressions read context.<path>, entry.<path> (in queries), env.qualifier[\"<id>\"], and env.now. Reference qualifiers as env.qualifier[\"<id>\"].",
    },
    VariableRuleContextPathTypeMismatch => {
        id: "variable-rule-context-path-type-mismatch",
        entity: Rule,
        title: "Variable rule uses a context path with the wrong type",
        help: "Declare the context attribute with a type that matches how the rule uses it, or change the comparison to match the declared type.",
    },
    VariableRuleShadowed => {
        id: "variable-rule-shadowed",
        entity: Rule,
        title: "Variable rule is shadowed",
        help: "Remove the later duplicate qualifier rule or reorder the resolve rules.",
        severity: Warning,
    },
    VariableRuleSelectsDefaultValue => {
        id: "variable-rule-selects-default-value",
        entity: Rule,
        title: "Variable rule selects the default value",
        help: "Remove the rule or update it to select a value that differs from the resolve default.",
        severity: Warning,
    },
    VariableEvaluationContextConflict => {
        id: "variable-evaluation-context-conflict",
        entity: Variable,
        title: "Variable rules require incompatible evaluation contexts",
        help: "Use rule conditions that share at least one compatible evaluation context, or split the behavior into separate variables.",
    },
    EvaluationContextParseFailed => {
        id: "evaluation-context-parse-failed",
        entity: EvaluationContext,
        title: "Evaluation context schema JSON file could not be parsed",
        help: "Fix the JSON syntax so rototo can parse the evaluation context schema file.",
    },
    EvaluationContextSampleParseFailed => {
        id: "evaluation-context-sample-parse-failed",
        entity: EvaluationContextSample,
        title: "Evaluation context sample JSON file could not be parsed",
        help: "Fix the JSON syntax so rototo can parse the evaluation context sample file.",
    },
    CustomLintFailed => {
        id: "custom-lint-failed",
        entity: Package,
        title: "Custom lint execution failed",
        help: "Update the Lua lint file or target data so custom lint can run.",
    },
    CustomLintRegistrationInvalid => {
        id: "custom-lint-registration-invalid",
        entity: Package,
        title: "Custom lint registration is invalid",
        help: "Register custom lint with an allowed stage, entity, field, rule metadata, and handler.",
    },
    CustomLintRuleConflict => {
        id: "custom-lint-rule-conflict",
        entity: Package,
        title: "Custom lint rule metadata conflicts",
        help: "Use identical title and help text for repeated custom rule declarations.",
    },
    CustomLintFileUnregistered => {
        id: "custom-lint-file-unregistered",
        entity: Package,
        title: "Custom lint file registers no handlers",
        help: "Register at least one handler from the Lua file or remove the file.",
        severity: Warning,
    },
    CustomLintRegistrationDuplicate => {
        id: "custom-lint-registration-duplicate",
        entity: Package,
        title: "Custom lint registration is duplicated",
        help: "Remove duplicate custom lint registrations so handlers run once per target.",
        severity: Warning,
    },
    SchemaUiUnknownWidget => {
        id: "schema-ui-unknown-widget",
        entity: Catalog,
        title: "UI widget hint names an unknown widget",
        help: "Use a widget from the x-rototo-ui vocabulary: color, slider, textarea.",
        severity: Warning,
    },
    SchemaUiWidgetTypeMismatch => {
        id: "schema-ui-widget-type-mismatch",
        entity: Catalog,
        title: "UI widget hint does not fit the property type",
        help: "Pick a widget that supports the property's declared type, or change the type.",
        severity: Warning,
    },
    SchemaUiWidgetParams => {
        id: "schema-ui-widget-params",
        entity: Catalog,
        title: "UI widget hint parameters are invalid",
        help: "Fix the x-rototo-ui object: declare a widget string, use only the widget's parameters, and give sliders bounds.",
        severity: Warning,
    },
}

impl Serialize for RototoRuleId {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(self.meta().rule)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct CustomRuleId(String);

impl CustomRuleId {
    pub fn parse(rule: impl AsRef<str>) -> std::result::Result<Self, CustomRuleIdError> {
        let rule = rule.as_ref();
        let Some((authority, id)) = rule.split_once('/') else {
            return Err(CustomRuleIdError::new(
                "custom rule id must use <authority>/<rule-id>",
            ));
        };
        if id.contains('/') {
            return Err(CustomRuleIdError::new(
                "custom rule id must contain exactly one slash",
            ));
        }
        if authority == "rototo" {
            return Err(CustomRuleIdError::new(
                "rototo is reserved for built-in diagnostic rules",
            ));
        }
        if !valid_rule_segment(authority) || !valid_rule_segment(id) {
            return Err(CustomRuleIdError::new(
                "rule id segments must use lowercase ASCII letters, digits, and hyphen",
            ));
        }
        Ok(Self(rule.to_owned()))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for CustomRuleId {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl Serialize for CustomRuleId {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

#[derive(Debug, Clone)]
pub struct CustomRuleIdError {
    message: String,
}

impl CustomRuleIdError {
    fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
        }
    }
}

impl fmt::Display for CustomRuleIdError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.message)
    }
}

impl std::error::Error for CustomRuleIdError {}

fn valid_rule_segment(segment: &str) -> bool {
    !segment.is_empty()
        && segment
            .bytes()
            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CustomRuleDefinition {
    pub rule: CustomRuleId,
    pub severity: Severity,
    pub title: String,
    pub help: String,
}

impl CustomRuleDefinition {
    pub fn new(rule: CustomRuleId, title: impl Into<String>, help: impl Into<String>) -> Self {
        Self::with_severity(rule, Severity::Error, title, help)
    }

    pub fn with_severity(
        rule: CustomRuleId,
        severity: Severity,
        title: impl Into<String>,
        help: impl Into<String>,
    ) -> Self {
        Self {
            rule,
            severity,
            title: title.into(),
            help: help.into(),
        }
    }

    pub fn same_metadata(&self, other: &Self) -> bool {
        self.severity == other.severity && self.title == other.title && self.help == other.help
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum DiagnosticRule {
    Rototo(RototoRuleId),
    Custom(CustomRuleId),
}

impl DiagnosticRule {
    pub fn as_string(&self) -> String {
        match self {
            Self::Rototo(rule) => rule.meta().rule.to_owned(),
            Self::Custom(rule) => rule.as_str().to_owned(),
        }
    }
}

impl Serialize for DiagnosticRule {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            Self::Rototo(rule) => rule.serialize(serializer),
            Self::Custom(rule) => rule.serialize(serializer),
        }
    }
}

#[derive(Debug, Serialize)]
pub struct DiagnosticCatalogEntry {
    pub rule: String,
    pub severity: Severity,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub entity: Option<DiagnosticEntity>,
    pub title: String,
    pub help: String,
}

impl DiagnosticCatalogEntry {
    pub fn from_rototo(rule: RototoRuleId) -> Self {
        let meta = rule.meta();
        Self {
            rule: meta.rule.to_owned(),
            severity: meta.severity,
            entity: Some(meta.entity),
            title: meta.title.to_owned(),
            help: meta.help.to_owned(),
        }
    }

    pub fn from_custom(definition: &CustomRuleDefinition) -> Self {
        Self {
            rule: definition.rule.as_str().to_owned(),
            severity: definition.severity,
            entity: None,
            title: definition.title.clone(),
            help: definition.help.clone(),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[serde(transparent)]
pub struct DocId(pub u32);

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum LintStage {
    Discover,
    Parse,
    Project,
    Register,
    Reference,
    Value,
    Graph,
    Policy,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum SemanticEntity {
    Package,
    Manifest,
    Qualifier {
        id: String,
    },
    Predicate {
        qualifier: String,
        index: usize,
    },
    Variable {
        id: String,
    },
    Catalog {
        id: String,
    },
    CatalogEntry {
        catalog: String,
        key: String,
    },
    EvaluationContext {
        id: String,
    },
    EvaluationContextSample {
        evaluation_context: String,
        key: String,
    },
    Value {
        variable: String,
        key: String,
    },
    Rule {
        variable: String,
        index: usize,
    },
    CustomLint {
        path: String,
    },
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum SemanticField {
    PackageExtends,
    SchemaVersion,
    Description,
    QualifierWhen,
    QualifierPredicates,
    PredicateAttribute,
    PredicateOp,
    PredicateNot,
    PredicateValue,
    PredicateSalt,
    PredicateRange,
    VariableType,
    VariableSchema,
    VariableValues,
    VariableResolve,
    VariableResolveDefault,
    VariableRuleWhen,
    VariableRuleQuery,
    VariableRuleValue,
    Value,
    ValueJsonPath { path: Vec<String> },
    SchemaJson,
    SchemaJsonPath { path: Vec<String> },
    EvaluationContextSample,
    CatalogEntry,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize)]
pub struct SemanticTarget {
    pub entity: SemanticEntity,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub field: Option<SemanticField>,
}

impl SemanticTarget {
    pub fn entity(entity: SemanticEntity) -> Self {
        Self {
            entity,
            field: None,
        }
    }

    pub fn field(entity: SemanticEntity, field: SemanticField) -> Self {
        Self {
            entity,
            field: Some(field),
        }
    }
}

impl From<SemanticEntity> for SemanticTarget {
    fn from(entity: SemanticEntity) -> Self {
        Self::entity(entity)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct SourcePosition {
    pub line: usize,
    pub character: usize,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct SourceRange {
    pub start: SourcePosition,
    pub end: SourcePosition,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct TextRange {
    pub(crate) start: usize,
    pub(crate) end: usize,
}

impl TextRange {
    pub(crate) fn new(start: usize, end: usize) -> Self {
        Self { start, end }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct SourceSpan {
    pub(crate) doc: DocId,
    pub(crate) range: TextRange,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiagnosticLocationKind {
    Span,
    Document,
    PackageRoot,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct DiagnosticLocation {
    #[serde(skip)]
    pub kind: DiagnosticLocationKind,
    #[serde(skip)]
    pub doc: Option<DocId>,
    #[serde(skip)]
    pub(crate) span: Option<SourceSpan>,
    pub path: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub range: Option<SourceRange>,
}

impl DiagnosticLocation {
    pub fn span(doc: DocId, path: impl Into<String>, range: SourceRange) -> Self {
        Self {
            kind: DiagnosticLocationKind::Span,
            doc: Some(doc),
            span: None,
            path: path.into(),
            range: Some(range),
        }
    }

    pub(crate) fn source_span(
        doc: DocId,
        path: impl Into<String>,
        text_range: TextRange,
        rendered_range: SourceRange,
    ) -> Self {
        Self {
            kind: DiagnosticLocationKind::Span,
            doc: Some(doc),
            span: Some(SourceSpan {
                doc,
                range: text_range,
            }),
            path: path.into(),
            range: Some(rendered_range),
        }
    }

    pub fn document(doc: DocId, path: impl Into<String>) -> Self {
        Self {
            kind: DiagnosticLocationKind::Document,
            doc: Some(doc),
            span: None,
            path: path.into(),
            range: None,
        }
    }

    pub fn package_root(path: impl Into<String>) -> Self {
        Self {
            kind: DiagnosticLocationKind::PackageRoot,
            doc: None,
            span: None,
            path: path.into(),
            range: None,
        }
    }

    pub fn doc(&self) -> Option<DocId> {
        self.doc
    }

    pub(crate) fn byte_start(&self) -> Option<usize> {
        self.span.map(|span| span.range.start)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct RelatedLocation {
    pub location: DiagnosticLocation,
    pub message: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct LintDiagnostic {
    pub rule: DiagnosticRule,
    pub severity: Severity,
    pub stage: LintStage,
    pub target: SemanticTarget,
    pub message: String,
    pub help: String,
    #[serde(rename = "location")]
    pub primary: DiagnosticLocation,
    pub related: Vec<RelatedLocation>,
}

impl LintDiagnostic {
    pub fn rototo(
        rule: RototoRuleId,
        stage: LintStage,
        target: impl Into<SemanticTarget>,
        primary: DiagnosticLocation,
        message: impl Into<String>,
    ) -> Self {
        let meta = rule.meta();
        Self {
            rule: DiagnosticRule::Rototo(rule),
            severity: meta.severity,
            stage,
            target: target.into(),
            message: message.into(),
            help: meta.help.to_owned(),
            primary,
            related: Vec::new(),
        }
    }

    pub fn custom(
        definition: &CustomRuleDefinition,
        stage: LintStage,
        target: impl Into<SemanticTarget>,
        primary: DiagnosticLocation,
        message: impl Into<String>,
    ) -> Self {
        Self {
            rule: DiagnosticRule::Custom(definition.rule.clone()),
            severity: definition.severity,
            stage,
            target: target.into(),
            message: message.into(),
            help: definition.help.clone(),
            primary,
            related: Vec::new(),
        }
    }
}

#[derive(Debug, Serialize)]
pub struct Diagnostic {
    pub rule: DiagnosticRule,
    pub severity: Severity,
    pub path: String,
    pub message: String,
    pub help: String,
}

impl Diagnostic {
    pub fn rototo(rule: RototoRuleId, path: impl Into<String>, message: impl Into<String>) -> Self {
        let meta = rule.meta();
        Self {
            rule: DiagnosticRule::Rototo(rule),
            severity: meta.severity,
            path: path.into(),
            message: message.into(),
            help: meta.help.to_owned(),
        }
    }

    pub fn custom(
        definition: &CustomRuleDefinition,
        path: impl Into<String>,
        message: impl Into<String>,
    ) -> Self {
        Self {
            rule: DiagnosticRule::Custom(definition.rule.clone()),
            severity: definition.severity,
            path: path.into(),
            message: message.into(),
            help: definition.help.clone(),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
    Error,
    Warning,
}

impl Severity {
    pub fn parse(value: &str) -> Option<Self> {
        match value {
            "error" => Some(Self::Error),
            "warning" => Some(Self::Warning),
            _ => None,
        }
    }
}