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
"""Resolve the PDF's citation hyperlinks to reference-list anchors.

The PDF carries real link annotations, which poppler exposes, but an
internal one resolves only to a *page* ("spans.html#27"), not to an entry.
Pages 26-29 are the bibliography, so such a link means "one of the entries
on page 27".  The visible citation text ("Biere et al. 1999") names which,
so resolution is: parse the reference list into a (surname, year) index,
read the same key off the citation, and check the entry really does sit on
the page the annotation points at.

Ambiguity is real: alloytools.org has 2023, 2023a, 2023b and 2023c.  The
year suffix disambiguates those, and anything still unresolved is left as
plain text and reported, never guessed.
"""

import html as htmllib
import re

# "et al.", "and", initials and particles must not be mistaken for surnames.
PARTICLES = {"de", "du", "van", "von", "der", "den", "la", "le", "di", "da"}


def surname(name):
    """Reduce an author string to the key surname, lowercased.

    "Nipkow et al." -> "nipkow";  "de Moura and Bjorner" -> "de moura";
    "du Boulay et al." -> "du boulay";  "alloytools.org" -> "alloytools.org".
    """
    n = htmllib.unescape(name).strip()
    n = re.sub(r"\s*\bet\s+al\.?", "", n)
    n = n.split(" and ")[0]
    n = n.split(";")[0]
    n = n.strip().strip(",.")
    if not n:
        return ""
    words = n.split()
    if not words:
        return ""
    # keep a leading particle with the surname ("de Moura", "du Boulay")
    if len(words) >= 2 and words[-2].lower() in PARTICLES:
        return " ".join(words[-2:]).lower()
    return words[-1].lower()


def all_surnames(text):
    """Every author surname in a reference entry, lowercased."""
    t = htmllib.unescape(re.sub(r"<[^>]+>", "", text)).strip()
    m = re.match(r"(.*?)\.\s*\d{4}[a-z]?\.", t, re.S)
    if not m:
        return []
    out = []
    for part in re.split(r",| and ", m.group(1)):
        part = part.strip().strip(",.")
        if not part or len(part.split()) < 2:
            continue
        words = part.split()
        if words[-2].lower() in PARTICLES:
            out.append(" ".join(words[-2:]).lower())
        else:
            out.append(words[-1].lower())
    return out


def parse_reference(text):
    """Return (surname_key, year) for a reference-list entry."""
    t = htmllib.unescape(re.sub(r"<[^>]+>", "", text)).strip()
    m = re.match(r"(.*?)\.\s*(\d{4}[a-z]?)\.", t, re.S)
    if not m:
        return None
    authors, year = m.group(1), m.group(2)
    # entries list every author; only the first surname is used as the key,
    # matching how citations are abbreviated to "First et al."
    first = re.split(r",| and ", authors)[0]
    # "Nelson, Tim" style never occurs here, but a single-token corporate
    # author (alloytools.org) must survive intact
    key = surname(first) if " " in first.strip() else \
        first.strip().strip(",.").lower()
    return (key, year)


def key_variants(name):
    """Candidate surname keys for a citation's author string.

    Compound surnames ("Tunnell Wilson") cannot be told from
    given-name+surname by shape alone, so offer both the last word and the
    last two words and let the reference list decide which exists.
    """
    n = htmllib.unescape(name).strip()
    n = re.sub(r"\s*\bet\s+al\.?", "", n)
    n = n.split(" and ")[0].split(";")[0].strip().strip(",.")
    words = n.split()
    out = []
    if not words:
        return out
    out.append(words[-1].lower())
    if len(words) >= 2:
        out.append(" ".join(words[-2:]).lower())
    if len(words) >= 3:
        out.append(" ".join(words[-3:]).lower())
    return out


class Index:
    def __init__(self, entries):
        """entries: list of (anchor_id, page, html_text)."""
        self.by_key = {}
        self.by_key_nosuffix = {}
        # Any author's surname, not just the first.  A citation broken
        # across a line ("following Dolev / and Yao [1983]") leaves only a
        # co-author next to the year, so this is the fallback that resolves
        # it.  Used only when it is unambiguous.
        self.by_any = {}
        for rid, page, text in entries:
            parsed = parse_reference(text)
            if not parsed:
                continue
            key, year = parsed
            self.by_key[(key, year)] = (rid, page)
            self.by_key_nosuffix.setdefault((key, year[:4]), []).append(
                (rid, page, year))
            for sur in all_surnames(text):
                self.by_any.setdefault((sur, year), []).append((rid, page))

    def lookup(self, name, year, target_page=None):
        """Resolve a citation; return an anchor id or None.

        `target_page` is the page the PDF's own link annotation points at,
        used only to confirm a match, never to guess one.  A citation that
        cannot be resolved confidently returns None and is left as plain
        text by the caller.
        """
        # Prefer the longest surname variant that the bibliography knows,
        # so "Tunnell Wilson" wins over "Wilson" when both are plausible.
        for key in sorted(key_variants(name), key=len, reverse=True):
            hit = self.by_key.get((key, year))
            if hit:
                if target_page is None or hit[1] == target_page:
                    return hit[0]
                return None      # index and PDF disagree; trust neither
        for key in sorted(key_variants(name), key=len, reverse=True):
            cands = self.by_key_nosuffix.get((key, year[:4]), [])
            if target_page is not None:
                cands = [c for c in cands if c[1] == target_page]
            if len(cands) == 1:
                return cands[0][0]
        # last resort: match on any author, which recovers citations whose
        # first author was left on the previous line
        for key in sorted(key_variants(name), key=len, reverse=True):
            cands = self.by_any.get((key, year), [])
            if target_page is not None:
                cands = [c for c in cands if c[1] == target_page]
            if len({c[0] for c in cands}) == 1:
                return cands[0][0]
        return None