1use std::fmt;
10
11macro_rules! rule_ids {
12 ($($variant:ident => $id:literal,)+) => {
13 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
15 pub enum RuleId {
16 $(
17 #[doc = $id]
18 $variant,
19 )+
20 }
21
22 impl RuleId {
23 pub const ALL: &'static [Self] = &[$(Self::$variant),+];
25
26 #[must_use]
28 pub const fn as_str(self) -> &'static str {
29 match self {
30 $(Self::$variant => $id),+
31 }
32 }
33
34 #[must_use]
36 pub fn parse(id: &str) -> Option<Self> {
37 match id {
38 $($id => Some(Self::$variant),)+
39 _ => None,
40 }
41 }
42 }
43
44 impl serde::Serialize for RuleId {
45 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
46 serializer.serialize_str(self.as_str())
47 }
48 }
49
50 impl<'de> serde::Deserialize<'de> for RuleId {
51 fn deserialize<D: serde::Deserializer<'de>>(
52 deserializer: D,
53 ) -> Result<Self, D::Error> {
54 let id = <std::borrow::Cow<'_, str> as serde::Deserialize>::deserialize(
55 deserializer,
56 )?;
57 Self::parse(&id).ok_or_else(|| {
58 serde::de::Error::custom(format!("no spec defines the rule {id}"))
59 })
60 }
61 }
62 };
63}
64
65rule_ids! {
66 FragmentNamesTheVenueForm => "acquisition:a-fragment-names-the-venue-form",
67 CleanRemovesOnlyANamedLeftover => "acquisition:clean-removes-only-a-named-leftover",
68 EveryPairCarriesAVerdict => "acquisition:every-pair-carries-a-verdict",
69 OneTargetRunsOneMechanism => "acquisition:one-target-runs-one-mechanism",
70 StatusReportsAndNeverJudges => "acquisition:status-reports-and-never-judges",
71 TheOperatorCallerReportsEveryOutcome => "acquisition:the-operator-caller-reports-every-outcome",
72 ThePinMovesInOneTransaction => "acquisition:the-pin-moves-in-one-transaction",
73 TheShellEntryCallerIsRateLimitedAndSilent => "acquisition:the-shell-entry-caller-is-rate-limited-and-silent",
74 TheSyncLeavesADiffNobodyCommitted => "acquisition:the-sync-leaves-a-diff-nobody-committed",
75 TheToolServesAndDoesNotEdit => "acquisition:the-tool-serves-and-does-not-edit",
76 RecordedDimensionOnlyShrinks => "budget-debt:a-recorded-dimension-only-shrinks",
77 DebtIsCreatedByAnExplicitAct => "budget-debt:debt-is-created-by-an-explicit-act",
78 CellCarriesOneReference => "comparison-docs:a-cell-carries-one-reference",
79 ComparisonCarriesALegend => "comparison-docs:a-comparison-carries-a-legend",
80 VerdictCarriesItsWord => "comparison-docs:a-verdict-carries-its-word",
81 EveryTableIsDated => "comparison-docs:every-table-is-dated",
82 TablePipesAreEscaped => "comparison-docs:table-pipes-are-escaped",
83 CitationResolvesToARule => "decision-records:a-citation-resolves-to-a-rule",
84 BodyStaysWithinWordCap => "decision-records:body-stays-within-350-words",
85 FilenameCarriesNoDigit => "decision-records:filename-carries-no-digit",
86 MergedRecordIsPermanent => "decision-records:merged-record-is-permanent",
87 RecordIsNotRevised => "decision-records:record-is-not-revised",
88 DeclaredLocationIsNamedByItsVariable => "distribution:a-declared-location-is-named-by-its-variable",
89 LandingClassifiesItsTargetFirst => "distribution:a-landing-classifies-its-target-first",
90 SeededRuleRunsNoCanonCommand => "distribution:a-seeded-rule-runs-no-canon-command",
91 SkillChecksItsHostBeforeItPlans => "distribution:a-skill-checks-its-host-before-it-plans",
92 SkillHasOneOwner => "distribution:a-skill-has-one-owner",
93 SkillInstallRestoresOnFailure => "distribution:a-skill-install-restores-on-failure",
94 SkillObeysThePortableFormat => "distribution:a-skill-obeys-the-portable-format",
95 SkillPlansBeforeItActs => "distribution:a-skill-plans-before-it-acts",
96 InstallSweepsWhatThePayloadDropped => "distribution:an-install-sweeps-what-the-payload-dropped",
97 InitializationPreservesProjectContent => "distribution:initialization-preserves-project-content",
98 InstancesOperateOffline => "distribution:instances-operate-offline",
99 ManifestIdentifiesEveryOwnedFile => "distribution:manifest-identifies-every-owned-file",
100 DeclarationIsSeededOnceAndThenOwned => "distribution:the-declaration-is-seeded-once-and-then-owned",
101 SkillPackageIsSelfContained => "distribution:a-skill-package-is-self-contained",
102 SkillInstallPreviewsBeforeWriting => "distribution:skill-install-previews-before-writing",
103 SkillUninstallRemovesOnlyWhatItWrote => "distribution:skill-uninstall-removes-only-what-it-wrote",
104 SkillsArePartOfThePayload => "distribution:skills-are-part-of-the-payload",
105 TheDoctorAnswersForTheInstalledSkills => "distribution:the-doctor-answers-for-the-installed-skills",
106 ThePayloadNamesNoOtherProject => "distribution:the-payload-names-no-other-project",
107 ThePayloadRootsAreDeclaredOnce => "distribution:the-payload-roots-are-declared-once",
108 UpgradeConflictsAreAtomic => "distribution:upgrade-conflicts-are-atomic",
109 UserScopeFilesStayUnrecorded => "distribution:user-scope-files-stay-unrecorded",
110 UserScopeReceiptIsRequiredState => "distribution:a-user-scope-receipt-is-required-state",
111 MachineScopeRecipeDropsASessionVariable => "release:a-machine-scope-recipe-drops-a-session-variable",
112 PlanIsStoredAndAppliedByItsId => "reconcile:a-plan-is-stored-and-applied-by-its-id",
113 ApplyRefusesAPlanWhoseInputsMoved => "reconcile:an-apply-refuses-a-plan-whose-inputs-moved",
114 OneWriterHoldsATarget => "reconcile:one-writer-holds-a-target",
115 PlanWritesNothing => "reconcile:a-plan-writes-nothing",
116 DecisionPrecedesWhatDependsOnIt => "reconcile:a-decision-precedes-what-depends-on-it",
117 FindingIsSomethingTheProgramProved => "reconcile:a-finding-is-something-the-program-proved",
118 WriteIntoAdoptedStateIsAnOperatorAct => "reconcile:a-write-into-adopted-state-is-an-operator-act",
119 IncrementalScopeLeavesNoStructuralFinding => "reconcile:an-incremental-scope-leaves-no-structural-finding",
120 OnePlanIsTheInputToEveryWrite => "reconcile:one-plan-is-the-input-to-every-write",
121 ReadinessIsTheWorstPrecondition => "reconcile:readiness-is-the-worst-precondition",
122 FingerprintCoversWhatTheApplyWouldDo => "reconcile:the-fingerprint-covers-what-the-apply-would-do",
123 PlannerIsDeterministic => "reconcile:the-planner-is-deterministic",
124 TargetDecidesItsClassification => "reconcile:the-target-decides-its-classification",
125 ReleaseIsReadThroughOneSeam => "bundle:a-release-is-read-through-one-seam",
126 ReleaseDeclaresWhatItLands => "bundle:a-release-declares-what-it-lands",
127 ProtocolVersionIsARangeTheEngineDeclares => "bundle:the-protocol-version-is-a-range-the-engine-declares",
128 PreSchemaReleaseIsCatalogedOrUnavailable => "bundle:a-pre-schema-release-is-cataloged-or-unavailable",
129 FetchedArchiveIsVerifiedBeforeItIsRead => "bundle:a-fetched-archive-is-verified-before-it-is-read",
130 ResolutionHappensOnceAndWritesOnlyTheCache => "bundle:resolution-happens-once-and-writes-only-the-cache",
131 RunThatDidNotFinishIsRolledBack => "reconcile:a-run-that-did-not-finish-is-rolled-back",
132 ApplyProvesEveryPostconditionItReports => "reconcile:an-apply-proves-every-postcondition-it-reports",
133 DestinationIsContainedBeforeItIsWritten => "reconcile:a-destination-is-contained-before-it-is-written",
134 PlanIdIsAFingerprintAndNeverAPath => "reconcile:a-plan-id-is-a-fingerprint-and-never-a-path",
135 ApplyResolvesNothing => "reconcile:an-apply-resolves-nothing",
136 TargetRecordsTheReleaseItHolds => "reconcile:a-target-records-the-release-it-holds",
137 ReleaseDeclaresWhatItAsksOfItsOperator => "reconcile:a-release-declares-what-it-asks-of-its-operator",
138 BinaryBuildsForEveryDeclaredTarget => "release:the-binary-builds-for-every-declared-target",
139 OneCatalogDescribesEveryServedDocument => "docs-discovery:one-catalog-describes-every-served-document",
140 InstanceIsRoutedToTheIndex => "docs-discovery:an-instance-is-routed-to-the-index",
141 AuthorInstructionsStayWithinBudget => "docs-format:author-instructions-stay-within-budget",
142 ChapterStaysWithinLineCap => "docs-format:chapter-stays-within-200-lines",
143 DocumentStatesThePresent => "docs-format:document-states-the-present",
144 DocumentUsesStructuralMarkdownOnly => "docs-format:document-uses-structural-markdown-only",
145 EveryBudgetCarriesAGate => "docs-format:every-budget-carries-a-gate",
146 FenceDeclaresALanguage => "docs-format:fence-declares-a-language",
147 ProseStaysUnwrapped => "docs-format:prose-stays-unwrapped",
148 DocumentCarriesNoPersonalPath => "docs-foundations:a-document-carries-no-personal-path",
149 DocumentDirectoryExplainsItself => "docs-foundations:a-document-directory-explains-itself",
150 DocumentOwnsWhatItGoverns => "docs-foundations:a-document-owns-what-it-governs",
151 KindPrefixCarriesASlug => "docs-foundations:a-kind-prefix-carries-a-slug",
152 ArtifactFilenamesCarryAKindPrefix => "docs-foundations:artifact-filenames-carry-a-kind-prefix",
153 CompanionArtifactsShareTheSpecName => "docs-foundations:companion-artifacts-share-the-spec-name",
154 SpecStatesThePresent => "docs-foundations:spec-states-the-present",
155 SpecWinsOverRecord => "docs-foundations:spec-wins-over-record",
156 SpecsAreCentralized => "docs-foundations:specs-are-centralized",
157 ProhibitionsAreCapped => "docs-specs:prohibitions-are-capped",
158 RequirementCarriesAVerification => "docs-specs:requirement-carries-a-verification",
159 RequirementCarriesFiveParts => "docs-specs:requirement-carries-five-parts",
160 RuleIdIsUniqueAndSlugged => "docs-specs:rule-id-is-unique-and-slugged",
161 RuleIdOutlivesItsSentence => "docs-specs:rule-id-outlives-its-sentence",
162 SpecStaysWithinLineCap => "docs-specs:spec-stays-within-300-lines",
163 StatementUsesAnEarsPattern => "docs-specs:statement-uses-an-ears-pattern",
164 UnenforcedRulesAreDeclared => "docs-specs:unenforced-rules-are-declared",
165 VerificationNamesALiveHook => "docs-specs:verification-names-a-live-hook",
166 DivergentResultNamesItsDestination => "guides:a-divergent-result-names-its-destination",
167 ManualStepEnumeratesItsInteraction => "guides:a-manual-step-enumerates-its-interaction",
168 StepFollowsItsProducers => "guides:a-step-follows-its-producers",
169 StepIsOneImperativeAction => "guides:a-step-is-one-imperative-action",
170 ExternalFactIsVerifiedUpstream => "guides:an-external-fact-is-verified-upstream",
171 CitationsLiveInTheReferenceZone => "guides:citations-live-in-the-reference-zone",
172 EveryStepCarriesItsCheck => "guides:every-step-carries-its-check",
173 PreconditionsOpenAndVerificationCloses => "guides:preconditions-open-and-verification-closes",
174 TheManifestStaysReadable => "instance:the-manifest-stays-readable",
175 AgentsBlockStaysManaged => "instance:the-agents-block-stays-managed",
176 TrackingRegistryStaysValid => "instance:the-tracking-registry-stays-valid",
177 ProjectDeclaresWhatItsGatesJudge => "instance:the-project-declares-what-its-gates-judge",
178 ManagedBlockAgreesWithTheDeclaration => "instance:the-managed-block-agrees-with-the-declaration",
179 BugzillaReportBodyFitsReportWidth => "known-issues:a-bugzilla-report-body-fits-in-79-columns",
180 FiledRecordCarriesItsReport => "known-issues:a-filed-record-carries-its-report",
181 RecordCarriesItsRetirementCondition => "known-issues:a-record-carries-its-retirement-condition",
182 RecordCarriesOneFilingState => "known-issues:a-record-carries-one-filing-state",
183 RecordCarriesOneState => "known-issues:a-record-carries-one-state",
184 RecordRecordsItsLastCheck => "known-issues:a-record-records-its-last-check",
185 RecordWalksTheMechanism => "known-issues:a-record-walks-the-mechanism",
186 CaseIdIsASlug => "known-issues:case-id-is-a-slug",
187 CanonGateIsNotDelivered => "release:a-canon-gate-is-not-delivered",
188 DeliveredGateReadsWhatTheConventionOwns => "release:a-delivered-gate-reads-what-the-convention-owns",
189 ReleasedVersionIsNotReAuthored => "release:a-released-version-is-not-re-authored",
190 TagDerivesFromTheVersionFile => "release:a-tag-derives-from-the-version-file",
191 EveryReleaseDeclaresWhatItAsks => "release:every-release-declares-what-it-asks",
192 LicenseDeclaresBothHalves => "release:license-declares-both-halves",
193 CanonRecordDescribesItsTree => "release:the-canon-record-describes-its-tree",
194 RkPinHasTwoFactsAndOneMover => "release:the-rk-pin-has-two-facts-and-one-mover",
195 DeliveredGateSetIsDeclaredOnce => "release:the-delivered-gate-set-is-declared-once",
196 ThirdPartyNoticesTravelWithThePayload => "release:third-party-notices-travel-with-the-payload",
197 VersionsAreSemanticAndAligned => "release:versions-are-semantic-and-aligned",
198 CommentCitesTheRule => "spec-to-code:a-comment-cites-the-rule",
199 CommentNamesNoRecord => "spec-to-code:a-comment-names-no-record",
200 GateMessageCitesTheRule => "spec-to-code:a-gate-message-cites-the-rule",
201 SpecMayLeadItsCode => "spec-to-code:a-spec-may-lead-its-code",
202 SuppressionNamesItsCase => "spec-to-code:a-suppression-names-its-case",
203 DeclaredDependentExists => "tracking:a-declared-dependent-exists",
204 PerishableSourceIsRegistered => "tracking:a-perishable-source-is-registered",
205 EntryDeclaresHowToRevalidate => "tracking:an-entry-declares-how-to-revalidate",
206 OverdueEntryBlocks => "tracking:an-overdue-entry-blocks",
207 UpstreamCheckDoesNotEditTheTree => "tracking:an-upstream-check-does-not-edit-the-tree",
208 UpstreamDerivationPinsARevision => "tracking:an-upstream-derivation-pins-a-revision",
209 RegistryHasOneReadableShape => "tracking:the-registry-has-one-readable-shape",
210 ExistingDocumentConvertsWhenEdited => "writing-style:an-existing-document-converts-when-edited",
211 NoDeliveredGateJudgesProse => "writing-style:no-delivered-gate-judges-prose",
212 SourcesNameTheRevisionRead => "writing-style:sources-name-the-revision-read",
213 DocumentationBlockRoutesToTheStyle => "writing-style:the-documentation-block-routes-to-the-style",
214 StyleLivesInOneDocument => "writing-style:the-style-lives-in-one-document",
215 NoneImposesNoObligation => "writing-policy:none-imposes-no-obligation",
216 ProjectSelectsOneSource => "writing-policy:the-project-selects-one-source",
217}
218
219impl fmt::Display for RuleId {
220 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
221 f.write_str(self.as_str())
222 }
223}
224
225#[cfg(test)]
226mod tests {
227 use super::*;
228
229 #[test]
230 fn slugs_are_well_formed_and_unique() {
231 let mut seen = std::collections::BTreeSet::new();
232 for rule in RuleId::ALL {
233 let id = rule.as_str();
234 let (domain, name) = id.split_once(':').unwrap();
235 let assert_slug = |part: &str| {
236 assert!(!part.is_empty(), "{id} has an empty half");
237 assert!(
238 part.bytes()
239 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-'),
240 "{id} is not a slug pair"
241 );
242 };
243 assert_slug(domain);
244 assert_slug(name);
245 assert!(seen.insert(id), "{id} is duplicated");
246 }
247 }
248
249 #[test]
250 fn display_renders_the_slug_pair() {
251 assert_eq!(
252 RuleId::ChapterStaysWithinLineCap.to_string(),
253 "docs-format:chapter-stays-within-200-lines"
254 );
255 }
256}