1use serde::{Deserialize, Serialize};
10
11pub const MAX_EXAMPLES: usize = 5;
13
14#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
16#[serde(rename_all = "snake_case")]
17pub enum Severity {
18 Info,
20 Warning,
22}
23
24impl Severity {
25 #[must_use]
27 pub const fn as_str(self) -> &'static str {
28 match self {
29 Self::Info => "info",
30 Self::Warning => "warning",
31 }
32 }
33}
34
35macro_rules! codes {
36 ($($(#[$doc:meta])* $variant:ident = $name:literal, $severity:ident;)+) => {
37 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
40 pub enum Code {
41 $($(#[$doc])* $variant,)+
42 }
43
44 impl Code {
45 pub const ALL: &'static [Code] = &[$(Code::$variant,)+];
47
48 #[must_use]
50 pub const fn as_str(self) -> &'static str {
51 match self {
52 $(Code::$variant => $name,)+
53 }
54 }
55
56 #[must_use]
58 pub const fn severity(self) -> Severity {
59 match self {
60 $(Code::$variant => Severity::$severity,)+
61 }
62 }
63 }
64 };
65}
66
67codes! {
68 LowercaseFolded = "lowercase_folded", Info;
70 TUFolded = "t_u_folded", Info;
72 AlphabetContradiction = "alphabet_contradiction", Warning;
74 InteriorWhitespace = "interior_whitespace", Warning;
76 UnknownCharactersExcluded = "unknown_characters_excluded", Warning;
78 HeaderFieldCountMismatch = "header_field_count_mismatch", Warning;
80 HeaderUtf8Replaced = "header_utf8_replaced", Warning;
82 HeaderValuesCleaned = "header_values_cleaned", Info;
85 NearDuplicateValues = "near_duplicate_values", Warning;
87 MissingLikeValues = "missing_like_values", Warning;
89 IdentifierLikeField = "identifier_like_field", Warning;
91 ThresholdExceedsSequenceCount = "threshold_exceeds_sequence_count", Warning;
94 NoEligiblePositions = "no_eligible_positions", Warning;
96 BelowMinCoverage = "below_min_coverage", Warning;
98 HcsLowSupportRegions = "hcs_low_support_regions", Warning;
100 FlagHasNoEffect = "flag_has_no_effect", Warning;
102}
103
104impl Serialize for Code {
105 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
106 s.serialize_str(self.as_str())
107 }
108}
109
110#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
115pub struct Diagnostic {
116 pub code: String,
118 pub severity: Severity,
120 pub message: String,
122 pub count: u64,
124 pub examples: Vec<String>,
126 pub hint: Option<String>,
128}
129
130impl Diagnostic {
131 #[must_use]
133 pub fn new(code: Code, message: impl Into<String>, tally: Tally) -> Self {
134 Self {
135 code: code.as_str().to_owned(),
136 severity: code.severity(),
137 message: message.into(),
138 count: tally.count,
139 examples: tally.examples,
140 hint: None,
141 }
142 }
143
144 #[must_use]
146 pub fn with_hint(mut self, hint: impl Into<String>) -> Self {
147 self.hint = Some(hint.into());
148 self
149 }
150
151 #[must_use]
153 pub fn known_code(&self) -> Option<Code> {
154 Code::ALL.iter().copied().find(|c| c.as_str() == self.code)
155 }
156}
157
158pub(crate) use crate::human::plural;
159
160pub(crate) const fn agree(n: u64, one: &'static str, many: &'static str) -> &'static str {
162 if n == 1 { one } else { many }
163}
164
165pub fn sort(diagnostics: &mut [Diagnostic]) {
168 diagnostics.sort_by_key(|d| d.known_code().map_or(usize::MAX, |c| c as usize));
169}
170
171#[derive(Clone, Debug, Default, PartialEq, Eq)]
173pub struct Tally {
174 pub count: u64,
176 pub examples: Vec<String>,
178}
179
180impl Tally {
181 #[must_use]
183 pub const fn count_only(count: u64) -> Self {
184 Self {
185 count,
186 examples: Vec::new(),
187 }
188 }
189
190 pub fn add(&mut self, n: u64, example: impl FnOnce() -> String) {
193 if n == 0 {
194 return;
195 }
196 self.count = self.count.saturating_add(n);
197 if self.examples.len() < MAX_EXAMPLES {
198 self.examples.push(example());
199 }
200 }
201
202 pub fn merge(&mut self, later: Self) {
204 self.count = self.count.saturating_add(later.count);
205 let room = MAX_EXAMPLES.saturating_sub(self.examples.len());
206 self.examples.extend(later.examples.into_iter().take(room));
207 }
208
209 #[must_use]
211 pub const fn is_empty(&self) -> bool {
212 self.count == 0
213 }
214}
215
216#[cfg(test)]
217mod tests {
218 use super::*;
219
220 #[test]
221 fn codes_are_unique_snake_case() {
222 let mut names: Vec<_> = Code::ALL.iter().map(|c| c.as_str()).collect();
223 assert!(names.iter().all(|n| {
224 n.bytes()
225 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
226 }));
227 let n = names.len();
228 names.sort_unstable();
229 names.dedup();
230 assert_eq!(names.len(), n);
231 for (i, c) in Code::ALL.iter().enumerate() {
232 assert_eq!(*c as usize, i, "ALL must list codes in declaration order");
233 }
234 }
235
236 #[test]
237 fn tally_keeps_first_examples_in_order() {
238 let mut a = Tally::default();
239 for i in 0..3 {
240 a.add(1, || format!("a{i}"));
241 }
242 let mut b = Tally::default();
243 for i in 0..4 {
244 b.add(2, || format!("b{i}"));
245 }
246 b.add(0, || unreachable!("zero-count adds are ignored"));
247 a.merge(b);
248 assert_eq!(a.count, 11);
249 assert_eq!(a.examples, ["a0", "a1", "a2", "b0", "b1"]);
250 let mut calls = 0;
251 a.add(1, || {
252 calls += 1;
253 String::new()
254 });
255 assert_eq!(calls, 0, "examples are not built once the list is full");
256 }
257
258 #[test]
259 fn diagnostics_serialise_and_sort() {
260 let mut t = Tally::default();
261 t.add(2, || "record 1".into());
262 let d = Diagnostic::new(Code::InteriorWhitespace, "2 records", t).with_hint("h");
263 let json = serde_json::to_string(&d).unwrap();
264 assert_eq!(
265 json,
266 r#"{"code":"interior_whitespace","severity":"warning","message":"2 records","count":2,"examples":["record 1"],"hint":"h"}"#
267 );
268 let back: Diagnostic = serde_json::from_str(&json).unwrap();
269 assert_eq!(back, d);
270 let mut v = vec![
271 Diagnostic::new(Code::FlagHasNoEffect, "z", Tally::default()),
272 Diagnostic {
273 code: "from_the_future".into(),
274 ..d.clone()
275 },
276 Diagnostic::new(Code::LowercaseFolded, "a", Tally::default()),
277 d,
278 ];
279 sort(&mut v);
280 let order: Vec<_> = v.iter().map(|d| d.code.as_str()).collect();
281 assert_eq!(
282 order,
283 [
284 "lowercase_folded",
285 "interior_whitespace",
286 "flag_has_no_effect",
287 "from_the_future"
288 ]
289 );
290 assert_eq!(
291 serde_json::to_string(&Code::TUFolded).unwrap(),
292 r#""t_u_folded""#
293 );
294 }
295}