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
#!/usr/bin/env python3
"""Check every citation anchor names the entry it links to, and vice versa.

The converter resolves citations by matching text against the bibliography,
so checking it the same way would only confirm it agrees with itself.  This
instead reads the *rendered* HTML: for each anchor, does the surname and
year visible in the link text actually appear in the entry it points at?
That catches a citation silently attached to the wrong entry, which is the
failure mode a word-multiset diff cannot see.
"""
import html as htmllib
import re
import sys

path = sys.argv[1] if len(sys.argv) > 1 else "paper.html"
doc = open(path, encoding="utf-8").read()

refs_at = doc.index('<section class="references"')
body, refs = doc[:refs_at], doc[refs_at:]


def plain(s):
    return htmllib.unescape(re.sub(r"<[^>]+>", "", s))


entries = {}
for m in re.finditer(r'<li id="(ref\d+)">(.*?)</li>', refs, re.S):
    entries[m.group(1)] = plain(m.group(2))

bad = 0
n = 0
for m in re.finditer(
        r'<a href="#(ref\d+)" id="cite\d+"[^>]*>(.*?)</a>', body, re.S):
    rid, text = m.group(1), plain(m.group(2))
    n += 1
    entry = entries.get(rid)
    if entry is None:
        print(f"DANGLING {rid}: {text!r}")
        bad += 1
        continue
    # the entry's own authors-and-year prefix, e.g.
    # "Danny Dolev and Andrew Chi-Chih Yao. 1983."
    head = entry.split(".", 1)[0]
    ymatch = re.search(r"\b(\d{4})[a-z]?\.", entry)
    eyear = ymatch.group(1) if ymatch else None

    year = re.search(r"\b((?:19|20)\d\d)", text)
    if year:
        if eyear and year.group(1) != eyear:
            print(f"YEAR  {rid}: cite {text!r} vs entry {entry[:70]!r}")
            bad += 1
            continue
    words = [w for w in re.findall(r"[A-Za-z][\w’'\u00C0-\u024F-]+", text)
             if w.lower() not in ("et", "al", "and")]
    if words:
        # every surname in the citation must occur in the entry's authors
        missing = [w for w in words if w.lower() not in entry.lower()]
        if missing:
            print(f"NAME  {rid}: cite {text!r} missing {missing} "
                  f"in {head[:70]!r}")
            bad += 1

print(f"checked {n} citation anchors, {bad} bad")

# Every entry that the body cites must carry a back-reference, and every
# back-reference must point at a citation that exists.
cids = set(re.findall(r'id="(cite\d+)"', body))
for m in re.finditer(r'<li id="(ref\d+)">(.*?)</li>', refs, re.S):
    for target in re.findall(r'href="#(cite\d+)"', m.group(2)):
        if target not in cids:
            print(f"BACKREF {m.group(1)} -> #{target} does not exist")
            bad += 1

sys.exit(1 if bad else 0)