1use std::{fmt, ops::BitAnd, str::FromStr};
6
7mod table;
8
9#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
11pub enum Edition {
12 Msc1991,
13 Msc2000,
14 Msc2010,
15 Msc2020,
16}
17
18impl Edition {
19 pub const ALL: [Edition; 4] = [
20 Edition::Msc1991,
21 Edition::Msc2000,
22 Edition::Msc2010,
23 Edition::Msc2020,
24 ];
25
26 pub const fn year(self) -> u16 {
27 match self {
28 Edition::Msc1991 => 1991,
29 Edition::Msc2000 => 2000,
30 Edition::Msc2010 => 2010,
31 Edition::Msc2020 => 2020,
32 }
33 }
34
35 pub fn from_year(year: u16) -> Option<Self> { Self::ALL.into_iter().find(|e| e.year() == year) }
36
37 pub fn current_at(year: u16) -> Self {
39 Self::ALL
40 .into_iter()
41 .rev()
42 .find(|e| e.year() <= year)
43 .unwrap_or(Edition::Msc1991)
44 }
45
46 pub fn named_in(text: &str) -> Option<Self> {
48 text
49 .split(|c: char| !c.is_ascii_digit())
50 .filter(|digits| digits.len() == 4)
51 .find_map(|digits| Self::from_year(digits.parse().ok()?))
52 }
53
54 const fn bit(self) -> u8 { 1 << self as u8 }
55}
56
57impl fmt::Display for Edition {
58 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.year()) }
59}
60
61#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
63pub struct Editions(u8);
64
65impl Editions {
66 pub const ALL: Editions = Editions(0b1111);
67 pub const NONE: Editions = Editions(0);
68
69 pub fn contains(self, edition: Edition) -> bool { self.0 & edition.bit() != 0 }
70
71 pub fn is_empty(self) -> bool { self.0 == 0 }
72
73 pub fn single(self) -> Option<Edition> {
74 let mut all = self.iter();
75 all.next().filter(|_| all.next().is_none())
76 }
77
78 pub fn iter(self) -> impl Iterator<Item = Edition> {
79 Edition::ALL.into_iter().filter(move |e| self.contains(*e))
80 }
81}
82
83impl BitAnd for Editions {
84 type Output = Editions;
85
86 fn bitand(self, other: Editions) -> Editions { Editions(self.0 & other.0) }
87}
88
89impl FromIterator<Edition> for Editions {
90 fn from_iter<I: IntoIterator<Item = Edition>>(editions: I) -> Self {
91 Editions(editions.into_iter().fold(0, |bits, e| bits | e.bit()))
92 }
93}
94
95impl fmt::Display for Editions {
96 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97 if self.is_empty() {
98 return f.write_str("none");
99 }
100 let years: Vec<String> = self.iter().map(|e| e.to_string()).collect();
101 f.write_str(&years.join("/"))
102 }
103}
104
105#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
107pub struct Code {
108 class: u8,
109 sub: u8,
110 leaf: u8,
111}
112
113const LEAF_XX: u8 = 100;
114
115impl Code {
116 pub fn editions(self) -> Editions {
118 let class = usize::from(self.class);
119 let Some(&[start, end]) = table::CLASS_START.get(class..class + 2) else {
120 return Editions::NONE;
121 };
122 let entries = &table::ENTRIES[usize::from(start)..usize::from(end)];
123 entries
124 .binary_search_by_key(&self.key(), |entry| entry >> 4)
125 .map_or(Editions::NONE, |i| Editions((entries[i] & 0xf) as u8))
126 }
127
128 fn key(self) -> u16 {
130 let sub = if self.sub == b'-' {
131 0
132 } else {
133 self.sub - b'A' + 1
134 };
135 u16::from(sub) * 101 + u16::from(self.leaf)
136 }
137
138 fn parse(text: &[u8]) -> Option<Self> {
139 let &[c1, c2, sub, l1, l2] = text else {
140 return None;
141 };
142 let digits = |a: u8, b: u8| {
143 (a.is_ascii_digit() && b.is_ascii_digit()).then(|| (a - b'0') * 10 + (b - b'0'))
144 };
145 let sub = sub.to_ascii_uppercase();
146 let leaf = if l1.eq_ignore_ascii_case(&b'x') && l2.eq_ignore_ascii_case(&b'x') {
147 LEAF_XX
148 } else {
149 digits(l1, l2)?
150 };
151 (sub == b'-' || sub.is_ascii_uppercase()).then_some(Code {
152 class: digits(c1, c2)?,
153 sub,
154 leaf,
155 })
156 }
157}
158
159impl FromStr for Code {
160 type Err = ();
161
162 fn from_str(text: &str) -> Result<Self, ()> { Code::parse(text.as_bytes()).ok_or(()) }
164}
165
166impl fmt::Display for Code {
167 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168 write!(f, "{:02}{}", self.class, self.sub as char)?;
169 match (self.leaf, self.sub) {
170 (LEAF_XX, b'-') => f.write_str("XX"),
171 (LEAF_XX, _) => f.write_str("xx"),
172 (leaf, _) => write!(f, "{leaf:02}"),
173 }
174 }
175}
176
177pub fn codes(text: &str) -> impl Iterator<Item = Code> + '_ {
180 let bytes = text.as_bytes();
181 let word = |i: usize| {
182 bytes
183 .get(i)
184 .is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'-')
185 };
186 (0..bytes.len().saturating_sub(4))
187 .filter(move |&i| (i == 0 || !word(i - 1)) && !word(i + 5))
188 .filter_map(move |i| Code::parse(&bytes[i..i + 5]))
189}
190
191#[derive(Clone, Copy, Debug, PartialEq, Eq)]
193pub struct Evidence {
194 pub print: Edition,
196 pub declared: Option<Edition>,
198 pub label: Option<Edition>,
200 pub year: Option<u16>,
202}
203
204impl Evidence {
205 pub fn dated(&self) -> Option<u16> { self.year.filter(|y| *y >= Edition::Msc1991.year()) }
208}
209
210#[derive(Clone, Copy, Debug, PartialEq, Eq)]
212pub enum Reason {
213 Declared,
214 AuthorLabel,
215 UniqueFit,
216 ClassPrint,
217 Era,
218 Nearest,
219 Oldest,
220}
221
222#[derive(Clone, Debug, PartialEq, Eq)]
223pub struct Inference {
224 pub edition: Edition,
225 pub reason: Reason,
226 pub fits: Editions,
228 pub unknown: Vec<Code>,
230}
231
232pub fn infer(codes: impl IntoIterator<Item = Code>, evidence: &Evidence) -> Inference {
236 let (mut fits, mut known, mut unknown) = (Editions::ALL, false, Vec::new());
237 for code in codes {
238 match code.editions() {
239 editions if editions.is_empty() => {
240 if !unknown.contains(&code) {
241 unknown.push(code);
242 }
243 },
244 editions => (fits, known) = (fits & editions, true),
245 }
246 }
247 let fitting = |e: Option<Edition>| e.filter(|e| known && fits.contains(*e));
248 let era = evidence.dated().map(Edition::current_at);
249 let (edition, reason) = if let Some(e) = fitting(evidence.declared) {
250 (e, Reason::Declared)
251 } else if let Some(e) = fitting(evidence.label) {
252 (e, Reason::AuthorLabel)
253 } else if let Some(e) = fits.single().filter(|_| known) {
254 (e, Reason::UniqueFit)
255 } else if !known || fits.is_empty() || fits.contains(evidence.print) {
256 (evidence.print, Reason::ClassPrint)
257 } else if let Some(era) = era.filter(|era| fits.contains(*era)) {
258 (era, Reason::Era)
259 } else if let Some(era) = era {
260 let distance = |e: &Edition| ((*e as i8 - era as i8).abs(), *e);
261 (
262 fits.iter().min_by_key(distance).unwrap_or(evidence.print),
263 Reason::Nearest,
264 )
265 } else {
266 (fits.iter().next().unwrap_or(evidence.print), Reason::Oldest)
267 };
268 Inference {
269 edition,
270 reason,
271 fits: if known { fits } else { Editions::ALL },
272 unknown,
273 }
274}
275
276impl Inference {
277 pub fn correction(&self, evidence: &Evidence) -> Option<Edition> {
279 (self.edition != evidence.print).then_some(self.edition)
280 }
281
282 pub fn notes(&self, evidence: &Evidence) -> Vec<(&'static str, String)> {
284 let mut notes = Vec::new();
285 let year = evidence.dated().unwrap_or_default();
286 let why = match self.reason {
287 Reason::Declared => Some("the edition the call names".to_string()),
288 Reason::AuthorLabel => Some("the edition of the author's own label".to_string()),
289 Reason::UniqueFit => Some("the only edition the codes are in".to_string()),
290 Reason::Era => Some(format!("the edition current in the document's year {year}")),
291 Reason::Nearest => Some(format!(
292 "the codes' edition nearest the document's year {year}"
293 )),
294 Reason::Oldest => Some("the codes' oldest edition, the source undated".to_string()),
295 Reason::ClassPrint => None,
297 };
298 if let (Some(edition), Some(why)) = (self.correction(evidence), why) {
299 let text = format!(
300 "MSC {} (the class's print) -> {edition}: {why} (codes fit {})",
301 evidence.print, self.fits
302 );
303 notes.push(("msc_edition", text));
304 }
305 for code in &self.unknown {
306 notes.push((
307 "msc_unknown_code",
308 format!("MSC code {code} is in no edition (1991, 2000, 2010, 2020)"),
309 ));
310 }
311 notes
312 }
313}
314
315#[cfg(test)]
316mod tests {
317 use super::*;
318
319 fn code(text: &str) -> Code { text.parse().unwrap() }
320
321 #[test]
322 fn code_shapes() {
323 for (text, canonical) in [
324 ("35Q55", "35Q55"),
325 ("35q55", "35Q55"),
326 ("35-02", "35-02"),
327 ("35Qxx", "35Qxx"),
328 ("35QXX", "35Qxx"),
329 ("35-XX", "35-XX"),
330 ("35-xx", "35-XX"),
331 ] {
332 assert_eq!(code(text).to_string(), canonical, "{text}");
333 }
334 for bad in [
335 "35Q5", "35Q555", "3AQ55", "35Q5x", "35.55", "35QX5", "", "35Q55 ",
336 ] {
337 assert!(bad.parse::<Code>().is_err(), "{bad}");
338 }
339 }
340
341 #[test]
342 fn codes_are_scanned_words() {
343 let found: Vec<String> =
344 codes(r"\textbf{Primary} 35Q55; Secondary 35-XX, 11Fxx \sep 05C10.(2010-05-11) x35Q55 35Q55x 9.F.4.1")
345 .map(|c| c.to_string())
346 .collect();
347 assert_eq!(found, ["35Q55", "35-XX", "11Fxx", "05C10"]);
348 assert_eq!(codes("D.3.1, F.4.1, Theory of computation").count(), 0);
349 }
350
351 #[test]
352 fn editions_set() {
353 let set: Editions = [Edition::Msc2010, Edition::Msc2020].into_iter().collect();
354 assert!(set.contains(Edition::Msc2010) && !set.contains(Edition::Msc2000));
355 assert_eq!(set.single(), None);
356 assert_eq!(
357 (set & [Edition::Msc2020].into_iter().collect()).single(),
358 Some(Edition::Msc2020)
359 );
360 assert!((set & Editions::NONE).is_empty());
361 assert_eq!(set.to_string(), "2010/2020");
362 assert_eq!(Editions::NONE.to_string(), "none");
363 assert_eq!(Edition::current_at(1985), Edition::Msc1991);
364 assert_eq!(Edition::current_at(2009), Edition::Msc2000);
365 assert_eq!(Edition::current_at(2026), Edition::Msc2020);
366 assert_eq!(
367 Edition::named_in(r"\textup {2010} Mathematics Subject Classification"),
368 Some(Edition::Msc2010)
369 );
370 assert_eq!(
371 Edition::named_in("MSC2000 (revised 2010)"),
372 Some(Edition::Msc2000)
373 );
374 assert_eq!(Edition::named_in("12010 or 2011"), None);
375 }
376
377 #[test]
378 fn table_lookup_and_invariants() {
379 let starts = &table::CLASS_START;
380 assert!(
381 starts.windows(2).all(|w| w[0] <= w[1]),
382 "CLASS_START is monotone"
383 );
384 assert_eq!(usize::from(starts[starts.len() - 1]), table::ENTRIES.len());
385 for class in starts.windows(2) {
386 let entries = &table::ENTRIES[usize::from(class[0])..usize::from(class[1])];
387 assert!(
388 entries.windows(2).all(|w| w[0] >> 4 < w[1] >> 4),
389 "each class's keys strictly sorted"
390 );
391 assert!(
392 entries.iter().all(|e| e & 0xf != 0),
393 "every code is in an edition"
394 );
395 }
396 let years = |c: &str| code(c).editions().to_string();
397 assert_eq!(years("16R10"), "1991/2000/2010/2020");
398 assert_eq!(years("57K12"), "2020");
399 assert_eq!(years("58G25"), "1991");
400 assert_eq!(years("15A33"), "1991/2000");
401 assert_eq!(years("20E45"), "2000/2010/2020");
402 assert_eq!(years("53D05"), "2000/2010/2020");
403 assert_eq!(years("00-XX"), "1991/2000/2010/2020");
404 assert_eq!(years("35Qxx"), "1991/2000/2010/2020");
405 assert_eq!(years("99A99"), "none");
406 assert_eq!(years("35Q00"), "none");
407 }
408
409 #[test]
411 fn table_edition_totals() {
412 let totals = Edition::ALL.map(|e| {
413 table::ENTRIES
414 .iter()
415 .filter(|entry| Editions((*entry & 0xf) as u8).contains(e))
416 .count()
417 });
418 assert_eq!(totals, [4811, 5531, 6198, 6603]);
419 }
420
421 fn evidence(
422 print: u16,
423 declared: Option<u16>,
424 label: Option<u16>,
425 year: Option<u16>,
426 ) -> Evidence {
427 let e = |y: u16| Edition::from_year(y).unwrap();
428 Evidence {
429 print: e(print),
430 declared: declared.map(e),
431 label: label.map(e),
432 year,
433 }
434 }
435
436 fn stamp(list: &str, ev: Evidence) -> (u16, Reason) {
437 let inference = infer(codes(list), &ev);
438 (inference.edition.year(), inference.reason)
439 }
440
441 #[test]
443 fn infer_cases() {
444 use Reason::*;
445 assert_eq!(
447 stamp("35Q55, 35A01", evidence(2010, Some(2010), None, Some(2012))),
448 (2010, Declared)
449 );
450 assert_eq!(
452 stamp(
453 "16R10; 17A70, 16R30",
454 evidence(2020, None, Some(2010), Some(2015))
455 ),
456 (2010, AuthorLabel)
457 );
458 assert_eq!(
460 stamp("57K12", evidence(2010, Some(2010), None, Some(2021))),
461 (2020, UniqueFit)
462 );
463 assert_eq!(
464 stamp(
465 "15A33, 20G40, 20E45",
466 evidence(2020, None, None, Some(2009))
467 ),
468 (2000, UniqueFit)
469 );
470 assert_eq!(
471 stamp(
472 "58G25, 58G30, 53C20; 35P15",
473 evidence(2020, None, None, Some(1996))
474 ),
475 (1991, UniqueFit)
476 );
477 assert_eq!(
479 stamp("41A25, 94A12", evidence(2020, None, None, Some(2021))),
480 (2020, ClassPrint)
481 );
482 assert_eq!(
483 stamp(
484 "60E07, 60F15, 91E40",
485 evidence(2020, None, None, Some(2002))
486 ),
487 (2020, ClassPrint)
488 );
489 assert_eq!(
491 stamp(
492 "35Q55, 35A01, 35B40",
493 evidence(2000, Some(2000), None, Some(2012))
494 ),
495 (2010, Era)
496 );
497 assert_eq!(
499 stamp(
500 "18E30, 14F05; 14M15, 18A05",
501 evidence(2020, Some(2020), None, Some(2022))
502 ),
503 (2010, Nearest)
504 );
505 for year in [None, Some(1980)] {
508 assert_eq!(
509 stamp("35Q55, 35B51", evidence(2000, Some(2000), None, year)),
510 (2010, Oldest)
511 );
512 assert_eq!(
513 stamp(
514 "18E30, 14F05; 14M15",
515 evidence(2020, Some(2020), None, year)
516 ),
517 (1991, Oldest)
518 );
519 }
520 assert_eq!(
522 stamp("35Q55, 35B51", evidence(2000, Some(2000), None, Some(2022))),
523 (2020, Era)
524 );
525 assert_eq!(
527 stamp(
528 "53D05; 53C55; 58F06",
529 evidence(2000, Some(2000), None, Some(2010))
530 ),
531 (2000, ClassPrint)
532 );
533 let ev = evidence(2020, None, None, Some(2021));
535 let inference = infer(codes("99A99, 41A25, 99a99"), &ev);
536 assert_eq!(
537 (inference.edition, inference.reason),
538 (Edition::Msc2020, ClassPrint)
539 );
540 assert_eq!(inference.notes(&ev), [(
541 "msc_unknown_code",
542 "MSC code 99A99 is in no edition (1991, 2000, 2010, 2020)".to_string()
543 )]);
544 assert_eq!(
546 stamp("99A99", evidence(2020, None, Some(2010), Some(2015))),
547 (2020, ClassPrint)
548 );
549 }
550
551 #[test]
552 fn notes_name_the_correction() {
553 let ev = evidence(2020, None, Some(2010), Some(2015));
554 let inference = infer(codes("16R10"), &ev);
555 assert_eq!(inference.notes(&ev), [(
556 "msc_edition",
557 "MSC 2020 (the class's print) -> 2010: the edition of the author's own label (codes fit \
558 1991/2000/2010/2020)"
559 .to_string()
560 )]);
561 let ev = evidence(2020, None, None, Some(2021));
562 assert!(
563 infer(codes("57K12"), &ev).notes(&ev).is_empty(),
564 "no Info when the print stands"
565 );
566 }
567
568 #[test]
573 #[ignore = "regenerates the table from downloaded sources"]
574 fn regenerate_table() {
575 use std::{collections::BTreeMap, fmt::Write, fs, path::Path, process::Command};
576 let dir = std::env::var("MSC_SOURCES").expect("MSC_SOURCES names the source directory");
577 let dir = Path::new(&dir);
578 let whole_line =
579 |text: &str| -> Vec<Code> { text.lines().filter_map(|l| l.trim().parse().ok()).collect() };
580 let pdf = |name: &str| {
581 let out = Command::new("pdftotext")
582 .arg(dir.join(name))
583 .arg("-")
584 .output()
585 .expect("pdftotext");
586 whole_line(&String::from_utf8_lossy(&out.stdout))
587 };
588 let csv = fs::read(dir.join("MSC_2020.csv")).unwrap();
589 let csv = String::from_utf8_lossy(&csv);
590 let c2020: Vec<Code> = csv
591 .lines()
592 .skip(1)
593 .filter_map(|l| l.split('\t').next()?.trim_matches('"').parse().ok())
594 .collect();
595 let mut c1991 = Vec::new();
597 for page in fs::read_dir(dir.join("hw1991")).unwrap() {
598 let path = page.unwrap().path();
599 if path.extension().is_none_or(|x| x != "html") {
600 continue;
601 }
602 let html = String::from_utf8_lossy(&fs::read(&path).unwrap()).into_owned();
603 for entry in html.split("<LI>").skip(1).chain(html.split("<H3>").skip(1)) {
604 let mut rest = entry.trim_start();
605 if rest.starts_with("<A ") {
606 rest = rest.split_once('>').map_or("", |(_, r)| r.trim_start());
607 }
608 c1991.extend(rest.get(..5).and_then(|c| c.parse::<Code>().ok()));
609 }
610 }
611 let sources = [
612 (Edition::Msc1991, c1991, 4811),
613 (Edition::Msc2000, pdf("classifications2000.pdf"), 5531),
614 (Edition::Msc2010, pdf("classifications2010.pdf"), 6198),
615 (Edition::Msc2020, c2020, 6603),
616 ];
617 let mut table: BTreeMap<Code, u8> = BTreeMap::new();
618 for (edition, codes, published) in sources {
619 let before = table.values().filter(|m| *m & edition.bit() != 0).count();
620 for code in codes {
621 *table.entry(code).or_default() |= edition.bit();
622 }
623 let count = table.values().filter(|m| *m & edition.bit() != 0).count() - before;
624 assert_eq!(
625 count, published,
626 "MSC{edition}: the published number of codes"
627 );
628 }
629 let mut starts = vec![0u16; 99];
630 for code in table.keys() {
631 for start in &mut starts[usize::from(code.class) + 1..] {
632 *start += 1;
633 }
634 }
635 let entries: Vec<u16> = table
636 .iter()
637 .map(|(c, mask)| (c.key() << 4) | u16::from(*mask))
638 .collect();
639 let hex = |values: &[u16]| {
640 values
641 .chunks(16)
642 .map(|line| {
643 line
644 .iter()
645 .map(|v| format!("0x{v:04x},"))
646 .collect::<Vec<_>>()
647 .join(" ")
648 })
649 .map(|line| format!(" {line}\n"))
650 .collect::<String>()
651 };
652 let mut out = String::new();
653 write!(
654 out,
655 "// @generated by `util::msc::tests::regenerate_table` from background/msc/ (fetched 2026-11-26); do not edit.
656//
657// Derived facts: the MSC codes (identifiers only, no descriptions) of each edition, as a set of editions per code.
658// MSC2020 (msc2020.org/MSC_2020.csv) (c) zbMATH Open and AMS Mathematical Reviews, published under CC BY-NC-SA 4.0;
659// MSC2010 and MSC2000 from AMS's published lists (mathscinet.ams.org/msc/pdfs/classifications{{2010,2000}}.pdf);
660// MSC1991 from the Heriot-Watt hypertext copy (www.macs.hw.ac.uk/~chris/mr-html.tar.Z).
661// Regenerate: MSC_SOURCES=$PWD/background/msc \\
662// cargo test -p latexml_core --lib util::msc::tests::regenerate_table -- --ignored
663//
664// ENTRIES holds one entry per code, by class (CLASS_START[class]..CLASS_START[class + 1]), sorted:
665// `(sub_index * 101 + leaf_index) << 4 | editions`, sub_index 0 for `-` then A-Z 1-26, leaf_index 100 for `xx`,
666// editions bit 0 = 1991, 1 = 2000, 2 = 2010, 3 = 2020.
667
668#[rustfmt::skip]
669pub(super) static CLASS_START: [u16; 99] = [
670{}];
671
672#[rustfmt::skip]
673pub(super) static ENTRIES: [u16; {}] = [
674{}];
675",
676 hex(&starts),
677 entries.len(),
678 hex(&entries)
679 )
680 .unwrap();
681 fs::write(
682 Path::new(env!("CARGO_MANIFEST_DIR")).join("src/util/msc/table.rs"),
683 out,
684 )
685 .unwrap();
686 }
687}