1"""The reading index, and the compiler that folds readings into sets.
2
3The default vocabulary is written per word in nameparser/vocab/*.toml,
4each word listing its READINGS (what it can be read as, keyed by kind)
5in the file of the language whose names it occurs in
6(decisions/vocabulary-model). tools/vocab/build.py checks the files and
7writes two modules from them, each generated and committed:
8
9* nameparser/config/_index.py, the READING INDEX: for each word, one
10 row per reading, ``(tag, kind, properties)``, the tag being its file's
11 BCP 47 tag and the properties the ones the compiler reads. It is what
12 a set has forgotten, which file each word came from.
13* nameparser/config/_compiled.py, the sets the parser reads, which is
14 :func:`compile_readings` run over the index.
15
16This module is the compiler both the build and a choice of languages
17(phase 3b, :func:`choose`) run, so there is one implementation of what a reading
18compiles to; tests/v2/test_reading_index.py holds that compiling the
19index reproduces _compiled.py exactly. It is also the one way to read
20the index at run time (:func:`readings_of`, :func:`index`), and the
21reader every parse calls for ``Reading.languages``
22(:func:`languages_of`), so the first parse in a process loads it.
23
24It imports nothing internal at module level, and the index only inside
25:func:`index`: the build loads this file by path, as it loads
26_lexicon.py, so that a generated module left broken cannot stop the
27tool that rewrites it.
28"""
29from __future__ import annotations
30
31import functools
32import unicodedata
33from collections.abc import Iterable, Mapping
34from dataclasses import dataclass
35from types import MappingProxyType
36from typing import Any, TypedDict
37
38#: kind -> category. The category decides which compiled field a reading
39#: feeds. For title, suffix, particle and conjunction, the category's own
40#: name is also a kind (`title = {}`: a title not yet classified), so
41#: classifying a word later moves no set. bound_given's one kind shares
42#: its category's name, and so does bound_second's, the word a bound
43#: pair writes second and joins from (rules/P12, #1072); the relation (birth_marker, alias_marker) and name (given,
44#: family) categories have no generic kind. Kind
45#: names are unique across categories; a fine kind arrives with its
46#: category's classification, in a core PR, as one row here. The
47#: familiar category's one kind, `familiar` (a short given name standing
48#: for longer ones, `max` of `maximilian`), compiles into FAMILIAR alone,
49#: which only the name match reads: no parse reads it (decisions/
50#: name-matching, 2026-11-08 FAMILIAR FORMS). The spelling category's
51#: one kind, `spelling` (a given name written another way, by choice or
52#: by a romanization, `olha` of `olga`), compiles into
53#: ALTERNATE_SPELLINGS alone, which only the name match reads, as the
54#: opt-in `alternate-spelling`: unlike a `given` reading's `same_as`, it
55#: puts no word in GIVEN_NAME_ABBREVIATIONS and gives the word no name
56#: reading, so no parse reads it either (decisions/name-matching,
57#: 2026-11-12 ALTERNATE SPELLINGS ARE OPT-IN).
58CATEGORY: dict[str, str] = {
59 "title": "title",
60 "salutation": "title",
61 "style": "title",
62 "academic": "title",
63 "religious": "title",
64 "nobility": "title",
65 "military": "title",
66 "office": "title",
67 "occupation": "title",
68 "kinship": "title",
69 "modifier": "title",
70 "suffix": "suffix",
71 "generation": "suffix",
72 "agnomen": "suffix",
73 "credential": "suffix",
74 "honorific": "suffix",
75 "professional_honorific": "suffix",
76 "status": "suffix",
77 "courtesy": "suffix",
78 "particle": "particle",
79 "preposition": "particle",
80 "article": "particle",
81 "patronymic": "particle",
82 "teknonymic": "particle",
83 "clan": "particle",
84 "rank": "particle",
85 "saint": "particle",
86 "alias": "particle",
87 "conjunction": "conjunction",
88 "bound_given": "bound_given",
89 "bound_second": "bound_second",
90 "birth_marker": "relation",
91 "alias_marker": "relation",
92 "given": "name",
93 "family": "name",
94 "familiar": "familiar",
95 "spelling": "spelling",
96}
97
98#: The categories a choice neither prefers nor drops by (`choose`): a
99#: name reading keeps a gate on and settles nothing, and a familiar or a
100#: spelling reading moves no parse at all, so none competes with another
101#: file's reading of the word.
102UNPREFERRED = frozenset({"name", "familiar", "spelling"})
103#: Each category only the name match reads, with the list property its
104#: reading names its pairs by: the longer names a familiar form stands
105#: for, the names a spelling is another spelling of.
106MATCHING_LISTS: Mapping[str, str] = MappingProxyType({
107 "familiar": "short_for", "spelling": "spelling_of"})
108#: The categories only the name match reads: a file of these alone
109#: changes nothing a plain choice of it could (tags).
110MATCHING_ONLY = frozenset(MATCHING_LISTS)
111
112#: Behavioral properties per category: each compiles into a field, and
113#: its allowed values are exactly what today's pipeline does. A name
114#: reading's are `default` (phase 3a), `cased`, the word's case mask
115#: (the shipped ones on `family` readings, #1014), `shared`, which
116#: rules/P10, O6 and O7 read, and `after_particle`, which P10 and O6 read
117#: (#704): its other keys are evidence. A particle reading's
118#: `capital_opening` is rules/R12's: the particle takes a capital where
119#: it opens the family name, the Armenian `Ter` and `Der`.
120BEHAVIORAL: dict[str, frozenset[str]] = {
121 "title": frozenset({"abbreviation", "addresses", "after_given",
122 "attached", "attaches", "cased", "default",
123 "dotted"}),
124 "suffix": frozenset({"acronym", "attached", "cased", "default",
125 "title_case_is_name"}),
126 "particle": frozenset({"capital_opening", "cased", "default"}),
127 "conjunction": frozenset({"may_be_initial", "cased", "default"}),
128 "bound_given": frozenset({"completed_by", "completes_any", "cased",
129 "default", "long_names_only"}),
130 "bound_second": frozenset({"completes", "cased", "default"}),
131 "relation": frozenset({"cased", "default"}),
132 "name": frozenset({"after_particle", "cased", "default", "shared"}),
133 "familiar": frozenset({"default"}),
134 "spelling": frozenset({"default"}),
135}
136
137#: The suffix word kinds a name reading gates (rules/S11): the third
138#: derived marker reads these, and a name reading beside another word
139#: kind marks nothing, no gate reading that clash yet. A credential is
140#: here for one written as a word (`acronym = false`), `kc`, `pc` and
141#: `dl`, whose dotted spellings must stay the paired initials (#965); a
142#: credential acronym's clash is the second marker's.
143GATED_WORDS = frozenset({"generation", "agnomen", "credential"})
144
145#: The suffix word kinds rules/R8's `honorifics` view holds: a form of
146#: address written after the name (`さん`, `님`, `先生`), which CLDR
147#: files as a title; an office written there (`議員`) is a credential
148#: (#326).
149HONORIFIC_KINDS = frozenset({"honorific", "professional_honorific"})
150
151#: The particle kinds written with a capital, a saint's name (`St Clair`,
152#: `San Martín`) and a German rank inside the surname (`Freiherr von
153#: Richthofen`): rules/R4's case repair does not lowercase them (#1069).
154CAPITALIZED_PARTICLE_KINDS = frozenset({"saint", "rank"})
155
156
157#: The group a reading's `same_as` is read in, by the reading's
158#: category, a name reading's being its kind (`given`, `family`): the
159#: roles of a name each read one group (decisions/name-matching,
160#: 2026-11-08), so a given name's listed spelling is not a surname's
161#: (`ma`, María written short, beside the surname Ma). A bound given
162#: name stands in the given name and a particle in the surname, so
163#: theirs are read there; a conjunction's and a birth marker's stand in
164#: no role a match compares, and compile to no group.
165SAME_AS_GROUPS: Mapping[str, str] = MappingProxyType({
166 "given": "given",
167 "bound_given": "given",
168 "family": "family",
169 "particle": "family",
170 "title": "title",
171 "suffix": "suffix",
172})
173
174
175def same_as_group(kind: str) -> str | None:
176 """The `SAME_AS` group a `kind` reading's `same_as` compiles into,
177 or None where it compiles into none."""
178 category = CATEGORY[kind]
179 return SAME_AS_GROUPS.get(kind if category == "name" else category)
180
181
182def same_as_of(props: Mapping[str, Any]) -> tuple[str, ...]:
183 """The words a reading's `same_as` names, in the order written: a
184 text names one, a list several (`md` written short for `muhammad`,
185 `mohammad`, `mohammed` and `mohamed`, #1383), and none is ()."""
186 value = props.get("same_as")
187 if value is None:
188 return ()
189 if isinstance(value, str):
190 return (value,)
191 return tuple(value)
192
193
194def indexed(kind: str) -> frozenset[str]:
195 """The properties of a `kind` reading the index keeps: its
196 category's behavioral ones, and on every kind but `familiar`
197 `same_as`, the word a spelling stands for, which compiles into
198 SAME_AS (in the group of `same_as_group`) and on a `given` reading
199 also into GIVEN_NAME_ABBREVIATIONS (#789); on a `familiar` reading
200 `short_for`, the longer given names the word stands for, which
201 compiles into FAMILIAR; on a `spelling` reading `spelling_of`, the
202 given names the word is another spelling of, which compiles into
203 ALTERNATE_SPELLINGS. Everything else a reading carries is
204 evidence, compiled to nothing."""
205 category = CATEGORY[kind]
206 return BEHAVIORAL[category] | {MATCHING_LISTS.get(category, "same_as")}
207
208
209class ReadingProperties:
210 """The unwritten values of the properties whose default is not
211 false, defined once for every reading type that has a `kind` and
212 `props`: the build's Reading, which holds a reading as its file
213 wrote it, and :class:`IndexReading`, which holds it as the index
214 does."""
215
216 __slots__ = ()
217 text: str
218 kind: str
219 props: Mapping[str, Any]
220
221 @property
222 def category(self) -> str:
223 return CATEGORY[self.kind]
224
225 @property
226 def marks_a_clash(self) -> bool:
227 """A name reading that marks a clash with a reading beside it
228 (the derived markers, the build's check 11): every name reading
229 but a `given` one carrying `same_as`, a name written short, which
230 the parse reads through rules/H2's yielding at the head of a name
231 and the match through its listed spellings, never through the
232 words-to-spare count a clash gates (`md`, Muhammad written short
233 and the medical degree, #1383)."""
234 return self.category == "name" and not (
235 self.kind == "given" and "same_as" in self.props)
236
237 @property
238 def acronym(self) -> bool:
239 """Matched with its periods removed: unwritten, true only for a
240 credential."""
241 return bool(self.props.get("acronym", self.kind == "credential"))
242
243 @property
244 def on_by_default(self) -> bool:
245 """Compiled into the default vocabulary: unwritten, true. A
246 reading written `default = false` is recorded and checked as a
247 reading but compiles to nothing, a name reading included (3a),
248 for a pack to turn on in phase 3 (decisions/vocabulary-model)."""
249 return self.props.get("default", True) is not False
250
251 def flag(self, prop: str) -> bool:
252 """A `may_be_*` flag, `after_given`, `abbreviation`,
253 `title_case_is_name`, `shared`, `after_particle`,
254 `capital_opening`, `dotted`, `completes_any` or
255 `long_names_only`: unwritten, false."""
256 return bool(self.props.get(prop, False))
257
258 @property
259 def addresses(self) -> object:
260 """Which name a title addresses: unwritten, the family name. An
261 object, not a str, because the build reads it before its check
262 3 has refused a value that is not one of the allowed strings."""
263 return self.props.get("addresses", "family")
264
265
266@dataclass(frozen=True, slots=True)
267class IndexReading(ReadingProperties):
268 """One row of the reading index.
269
270 ``text`` is the word, normalized as the vocabulary stores it;
271 ``tag`` the BCP 47 tag of the file holding the reading (``"en"``,
272 ``"pt-BR"``, ``"mul"``, ``"und"``); ``kind`` its vocabulary kind,
273 a key of :data:`CATEGORY` (``"credential"``, ``"preposition"``,
274 ``"given"``), finer than :class:`nameparser.ReadingKind`;
275 ``props`` the properties :func:`indexed` keeps, as written, read
276 through the accessors above for their unwritten values. A word in
277 several files has a row per file, and a reading written
278 ``default = false`` has its row too, with
279 ``on_by_default`` false.
280
281 A lookup result, not a value to keep: its ``props`` is a read-only
282 view, so an IndexReading neither hashes nor pickles. What a parse
283 keeps of it is its tag, in ``Reading.languages``
284 (:func:`languages_of`)."""
285
286 text: str
287 tag: str
288 kind: str
289 props: Mapping[str, Any]
290
291
292#: A row as nameparser/config/_index.py writes it, under its word:
293#: (tag, kind, properties), the properties as sorted (key, value) pairs,
294#: a list value as a sorted tuple and the `attached` table as its side,
295#: so the whole index is one constant.
296Row = tuple[str, str, tuple[tuple[str, Any], ...]]
297#: The index as written: (text, rows) per word, sorted by text, its
298#: rows by tag and then kind.
299Index = tuple[tuple[str, tuple[Row, ...]], ...]
300
301
302def to_row(r: IndexReading) -> Row:
303 """`r` as the index writes it under its word."""
304 pairs = []
305 for key in sorted(r.props):
306 value = r.props[key]
307 if key == "attached":
308 value = value["side"] if isinstance(value, Mapping) else value
309 elif isinstance(value, (list, tuple, set, frozenset)):
310 value = tuple(sorted(value))
311 pairs.append((key, value))
312 return (r.tag, r.kind, tuple(pairs))
313
314
315def from_row(text: str, row: Row) -> IndexReading:
316 tag, kind, pairs = row
317 return IndexReading(text, tag, kind, MappingProxyType(dict(pairs)))
318
319
320@functools.cache
321def _by_text() -> Mapping[str, tuple[Row, ...]]:
322 # the index is written grouped by word, so this is one dict() call
323 # in C, and an IndexReading is built only for a word looked up:
324 # building all of them costs more than importing the index
325 # (decisions/vocabulary-model, 2026-10-29 3a)
326 from nameparser.config._index import READINGS
327 return MappingProxyType(dict(READINGS))
328
329
330@functools.cache
331def index() -> tuple[IndexReading, ...]:
332 """Every row of the shipped reading index, in its order (by text,
333 then tag, then kind), for a compile over the whole pool. Built on
334 first call and kept: the index describes the shipped files, which
335 do not change in a process."""
336 return tuple(from_row(text, row)
337 for text, rows in _by_text().items() for row in rows)
338
339
340def readings_of(text: str) -> tuple[IndexReading, ...]:
341 """Every reading the shipped files hold for `text`, on by default
342 or not, one per file and kind, in index order; empty for a word no
343 file holds.
344
345 `text` is looked up as the vocabulary stores it (lowercase, NFC,
346 edge periods removed; _lexicon._normalize), and a phrase whole
347 (``"z domu"``). A reading the parse took from a caller's own
348 vocabulary, from a shape or from position has no row here, which is
349 what an empty ``Reading.languages`` says; the parse reads the tags
350 through :func:`languages_of`, which builds no IndexReading."""
351 return tuple(from_row(text, row) for row in _by_text().get(text, ()))
352
353
354#: The tags no choice names: mul.toml's readings are every language's
355#: and und.toml's no known language's, so neither is a language to
356#: choose. A plain choice never removes a reading of either (choose); a
357#: strict one, which drops every file not chosen, keeps mul.toml's all
358#: the same, as it keeps native-script words' readings, and drops
359#: und.toml's (:func:`strict_pool`; decisions/vocabulary-model,
360#: 2026-11-02 #1005).
361UNCHOOSABLE = frozenset({"mul", "und"})
362
363
364@functools.cache
365def tags() -> frozenset[str]:
366 """The tags of the shipped files that hold a reading a choice can
367 change: any but a familiar or a spelling one (MATCHING_ONLY). A
368 plain choice never drops one of those, which no parse reads, so a
369 file holding only those would change nothing as a plain choice, and
370 is refused as one holding no reading (decisions/name-matching,
371 2026-11-08 FAMILIAR FORMS; hu.toml and zu.toml had that shape on
372 2026-11-20)."""
373 return frozenset(row[0] for rows in _by_text().values() for row in rows
374 if CATEGORY[row[1]] not in MATCHING_ONLY)
375
376
377@functools.cache
378def files() -> frozenset[str]:
379 """The tags of every shipped vocabulary file, one holding no
380 reading (only exclusions) included: :func:`tags` and the files a
381 strict choice may name, which a plain one may not."""
382 from nameparser.config._index import FILES
383 return frozenset(FILES)
384
385
386def selected(languages: Iterable[str], *,
387 strict: bool = False) -> frozenset[str]:
388 """The file tags a choice of `languages` selects: each chosen tag's
389 own and its ancestors', never its descendants' (``pt-BR`` selects
390 ``pt-BR`` and ``pt``; ``pt`` only ``pt``), matched without regard to
391 case, as BCP 47 tags are. No macrolanguage table is read: ``ms``
392 does not select ``id``.
393
394 A plain choice selects among the files that hold a reading, since a
395 file holding none would change nothing; a `strict` one among every
396 file, since it drops whatever is not chosen and so is never inert
397 (``hu``, whose file holds only exclusions).
398
399 Raises ValueError for ``mul`` or ``und``, and for a tag that selects
400 no file at all, naming the tags that do."""
401 held = (files() if strict else tags()) - UNCHOOSABLE
402 by_fold = {t.casefold(): t for t in held}
403 out: set[str] = set()
404 for tag in languages:
405 if tag.casefold() in UNCHOOSABLE:
406 raise ValueError(
407 f"{tag!r} is not a language to choose: mul.toml's readings "
408 f"are every language's and und.toml's no known language's; "
409 f"every choice, plain or strict, keeps mul.toml's, a plain "
410 f"one keeps und.toml's too and a strict one drops "
411 f"und.toml's. Drop it")
412 ancestors = _ancestors(tag)
413 found = {by_fold[a] for a in ancestors if a in by_fold}
414 if not found:
415 empty = sorted(t for t in files() - tags() - UNCHOOSABLE
416 if t.casefold() in ancestors)
417 if empty:
418 raise ValueError(
419 f"{empty[0]}.toml holds no reading a parse reads yet, "
420 f"so a plain choice of {tag!r} would change nothing; a "
421 f"strict one (strict=True) accepts it")
422 raise ValueError(
423 f"no vocabulary file holds the language {tag!r} or one it "
424 f"belongs to; the languages that have one: "
425 f"{', '.join(sorted(by_fold.values()))}")
426 out |= found
427 return frozenset(out)
428
429
430def _ancestors(tag: str) -> list[str]:
431 """`tag` and the tags it belongs to, casefolded, longest first."""
432 parts = tag.split("-")
433 return ["-".join(parts[:i]).casefold() for i in range(len(parts), 0, -1)]
434
435
436def choose(readings: Iterable[IndexReading],
437 chosen: frozenset[str]) -> list[IndexReading]:
438 """The readings a choice of the file tags `chosen` compiles, each
439 as :func:`compile_readings` is to read it (decisions/vocabulary-model,
440 2026-10-27 #753, items 2 and 7):
441
442 * **turning on**: a chosen file's ``default = false`` readings join
443 the readings on by default;
444 * **prefer**: on a word where a chosen file holds a vocabulary
445 reading (any category but a name), the other files' vocabulary
446 readings leave, save mul.toml's, which are every language's, and
447 und.toml's, whose language is not known to be another's. Name
448 readings never leave and never settle anything (decision 15):
449 they keep the gate on; nor do familiar or spelling readings,
450 which no parse reads (:data:`UNPREFERRED`);
451 * **the shape clash**: a chosen file's conjunction reading drops
452 ``may_be_initial``, the clash it records being with the initial
453 the letter spells, a shape reading, which a preference outranks
454 (decision 20).
455
456 With nothing chosen this is the readings on by default, unchanged,
457 so the default is the compile of an empty choice."""
458 if not chosen:
459 return [r for r in readings if r.on_by_default]
460 live = [(r, CATEGORY[r.kind] not in UNPREFERRED) for r in readings
461 if r.on_by_default or r.tag in chosen]
462 preferred = {r.text for r, competes in live
463 if competes and r.tag in chosen}
464 out = []
465 for r, competes in live:
466 if (competes and r.text in preferred
467 and r.tag not in chosen and r.tag not in UNCHOOSABLE):
468 continue
469 if r.tag in chosen and ("default" in r.props
470 or (r.category == "conjunction"
471 and "may_be_initial" in r.props)):
472 props = {k: v for k, v in r.props.items()
473 if k not in ("default", "may_be_initial")}
474 r = IndexReading(r.text, r.tag, r.kind, MappingProxyType(props))
475 out.append(r)
476 return out
477
478
479def is_native_script(text: str) -> bool:
480 """Whether a strict choice keeps `text` whatever its file: it holds
481 a letter and no Latin letter (the CJK honorifics, the Cyrillic and
482 Devanagari titles), so it selects itself by script, which is read
483 from the word as the parse always reads it. A word with no letter
484 (``&``, ``2``) is not native-script."""
485 letters = [c for c in text if c.isalpha()]
486 return bool(letters) and not any(
487 "LATIN" in unicodedata.name(c, "") for c in letters)
488
489
490def strict_pool(chosen: frozenset[str]) -> list[IndexReading]:
491 """The readings a strict choice of the file tags `chosen` compiles
492 from, before :func:`choose`: the chosen files' and mul.toml's
493 readings and every reading of a native-script word
494 (:func:`is_native_script`) whatever file holds it, name readings
495 included; no other file's, und.toml's among them
496 (file-strict; decisions/vocabulary-model, 2026-10-30, and
497 2026-11-02 #1005 for mul.toml)."""
498 return strict_kept(index(), chosen)
499
500
501def strict_kept(readings: Iterable[IndexReading],
502 chosen: frozenset[str]) -> list[IndexReading]:
503 """The readings of `readings` a strict choice of the file tags
504 `chosen` keeps: the chosen files', mul.toml's, which are every
505 language's, and native-script ones."""
506 return [r for r in readings
507 if r.tag in chosen or r.tag == "mul" or is_native_script(r.text)]
508
509
510def chosen_readings(readings: Iterable[IndexReading], chosen: frozenset[str],
511 strict: bool) -> list[IndexReading]:
512 """`readings` under the choice of the file tags `chosen`: under
513 `strict` only the chosen files', mul.toml's and native-script ones (as
514 :func:`strict_pool` keeps them), then :func:`choose`. What
515 :func:`compile_choice` compiles, and what a `Lexicon` under a
516 choice reads a word's readings by."""
517 return choose(strict_kept(readings, chosen) if strict else readings,
518 chosen)
519
520
521@functools.cache
522def compile_choice(chosen: frozenset[str], strict: bool = False) -> Compiled:
523 """The constants the shipped index compiles to under a choice of
524 the file tags `chosen` (:func:`selected`'s result), kept per choice:
525 a compile costs milliseconds, paid once per choice and only by a
526 caller who makes one. An empty plain choice compiles the default; a
527 `strict` one compiles from :func:`strict_pool` alone."""
528 return compile_readings(chosen_readings(index(), chosen, strict))
529
530
531def strict_ungated(chosen: frozenset[str]) -> frozenset[str]:
532 """The words a strict choice of the file tags `chosen` ungates: a
533 chosen file or mul.toml holds the word's vocabulary reading and
534 only a dropped file the name reading gating it, so under strict a possibly-given
535 particle is never-given, a title only inside a phrase is a title,
536 and a suffix gated by the count is not. Compared with the PLAIN
537 choice of the same tags, never with the default's markers, which
538 miss a reading the choice turns on (decisions/vocabulary-model,
539 2026-10-30 #753, file-strict)."""
540 plain, strict = compile_choice(chosen), compile_choice(chosen, True)
541 out = ((plain["PARTICLES"] - plain["NON_GIVEN_NAME_PARTICLES"])
542 & strict["NON_GIVEN_NAME_PARTICLES"])
543 out |= plain["TITLES_AMBIGUOUS"] & strict["TITLES"]
544 out |= plain["SUFFIX_ACRONYMS_AMBIGUOUS"] & (
545 strict["SUFFIX_ACRONYMS"] - strict["SUFFIX_ACRONYMS_AMBIGUOUS"])
546 out |= plain["SUFFIX_WORDS_AMBIGUOUS"] & (
547 strict["SUFFIX_WORDS"] - strict["SUFFIX_WORDS_AMBIGUOUS"])
548 return frozenset(out)
549
550
551def changed_words(chosen: frozenset[str]) -> frozenset[str]:
552 """The words whose compiled readings the choice `chosen` changes:
553 every entry that joins or leaves a constant, a title phrase's two
554 words among them, and every word whose case mask changes. This is a
555 vocabulary choice's deviation surface, derived from the index rather
556 than declared by hand (the RFC's "Measuring a pack"): a name holding
557 none of these words parses under the choice as under the default."""
558 if not chosen:
559 return frozenset()
560 default, choice = compile_choice(frozenset()), compile_choice(chosen)
561 words: set[str] = set()
562 for key in default:
563 if key in ("SAME_AS", "SAME_AS_NAMED", "FAMILIAR",
564 "ALTERNATE_SPELLINGS"):
565 # a word's listed spelling moves no word between sets, so it
566 # changes no parse: a choice's `sr` of `senhor`, not `señor`,
567 # and whether the match reads the link written bare; nor does
568 # a familiar form, which only the match reads
569 continue
570 a: Any = default[key] # type: ignore[literal-required]
571 b: Any = choice[key] # type: ignore[literal-required]
572 if isinstance(a, dict):
573 words |= {k for k in a.keys() | b.keys() if a.get(k) != b.get(k)}
574 else:
575 words |= a ^ b
576 return frozenset(w for entry in words for w in (entry, *entry.split()))
577
578
579def languages_of(text: str, kinds: frozenset[str]) -> tuple[str, ...]:
580 """The tags of the files holding a reading of `text`, on by
581 default, of one of `kinds` (keys of :data:`CATEGORY`), each once,
582 in index order; empty for a word no file holds as one of them.
583 `text` is normalized as :func:`readings_of` takes it. What
584 ``Reading.languages`` holds under the default lexicon, which reads
585 it through ``Lexicon._files`` (decisions/vocabulary-model,
586 2026-10-29; 2026-11-02, 4i-d); its first call in a process loads
587 the index."""
588 out: list[str] = []
589 for tag, kind, pairs in _by_text().get(text, ()):
590 if (kind in kinds and tag not in out
591 and ("default", False) not in pairs):
592 out.append(tag)
593 return tuple(out)
594
595
596def suffix_kind_of(text: str) -> str | None:
597 """The kind of `text`'s suffix reading (a key of :data:`CATEGORY`
598 whose category is ``suffix``), on by default or not; None for a
599 word no file holds as a suffix. A word has one suffix kind in every
600 file (the build's check 4), so the first row says it. `text` is
601 normalized as :func:`readings_of` takes it. The shipped files'
602 answer only: since 3.0's 4i-b the parse reads a suffix word's kind
603 from its own `Lexicon`, which compiles it (GENERATION_WORDS,
604 CREDENTIAL_WORDS, HONORIFIC_WORDS), and this agrees with the default's."""
605 for _tag, kind, _pairs in _by_text().get(text, ()):
606 if CATEGORY[kind] == "suffix":
607 return kind
608 return None
609
610
611def holds_kind(text: str, kind: str) -> bool:
612 """Whether a file holds `text` in a reading of `kind` (a key of
613 :data:`CATEGORY`), on by default or not. `text` is normalized as
614 :func:`readings_of` takes it. The shipped files' answer only: since
615 3.0's 4i-b the parse reads a particle's patronymic kind from its
616 own `Lexicon` (PATRONYMIC_PARTICLES)."""
617 return any(k == kind for _tag, k, _pairs in _by_text().get(text, ()))
618
619
620def _sorted_lists(lists: Mapping[str, Iterable[str]]
621 ) -> dict[str, tuple[str, ...]]:
622 """Each word's names as a sorted tuple, the words sorted, as the
623 compiled module writes a map of word lists."""
624 return {w: tuple(sorted(names)) for w, names in sorted(lists.items())}
625
626
627class CompileError(ValueError):
628 """The readings cannot compile: a fact about the data, which the
629 build reports as a vocabulary error (exit 2) where any other
630 exception from the compiler is an internal one (exit 3)."""
631
632
633class Compiled(TypedDict):
634 """What :func:`compile_readings` returns: one key per constant, in
635 the order nameparser/config/_compiled.py defines them, typed as it
636 declares them."""
637 GIVEN_NAME_TITLES: frozenset[str]
638 TITLES: frozenset[str]
639 AFTER_GIVEN_TITLES: frozenset[str]
640 TITLES_AMBIGUOUS: frozenset[str]
641 TITLE_MODIFIERS: frozenset[str]
642 TITLE_STYLES: frozenset[str]
643 TITLE_PHRASES: frozenset[str]
644 NON_GIVEN_NAME_PARTICLES: frozenset[str]
645 PARTICLES: frozenset[str]
646 CONJUNCTIONS: frozenset[str]
647 CONJUNCTIONS_AMBIGUOUS: frozenset[str]
648 BOUND_GIVEN_NAMES: frozenset[str]
649 GIVEN_NAME_ABBREVIATIONS: frozenset[str]
650 MAIDEN_MARKERS: frozenset[str]
651 ALIAS_MARKERS: frozenset[str]
652 SUFFIX_WORDS: frozenset[str]
653 GLUED_HONORIFICS: frozenset[str]
654 SUFFIX_WORDS_AMBIGUOUS: frozenset[str]
655 AGNOMENS: frozenset[str]
656 SUFFIX_ACRONYMS_AMBIGUOUS: frozenset[str]
657 SUFFIX_ACRONYMS: frozenset[str]
658 CAPITALIZATION_EXCEPTIONS: dict[str, str]
659 GENERATION_WORDS: frozenset[str]
660 CREDENTIAL_WORDS: frozenset[str]
661 HONORIFIC_WORDS: frozenset[str]
662 PATRONYMIC_PARTICLES: frozenset[str]
663 TITLE_ABBREVIATIONS: frozenset[str]
664 TITLE_CASE_NAME_WORDS: frozenset[str]
665 SHARED_NAMES: frozenset[str]
666 PARTICLE_GIVEN_NAMES: frozenset[str]
667 SAINT_PARTICLES: frozenset[str]
668 CAPITALIZED_PARTICLES: frozenset[str]
669 CAPITAL_OPENING_PARTICLES: frozenset[str]
670 DOTTED_TITLES: frozenset[str]
671 GLUED_TITLES: frozenset[str]
672 BOUND_PHRASES: frozenset[str]
673 BOUND_COMPLETES_ANY: frozenset[str]
674 BOUND_LONG_NAMES_ONLY: frozenset[str]
675 BOUND_SECONDS: frozenset[str]
676 BOUND_SECOND_PHRASES: frozenset[str]
677 BOUND_SECONDS_LISTED: frozenset[str]
678 SAME_AS: dict[str, dict[str, tuple[str, ...]]]
679 SAME_AS_NAMED: dict[str, frozenset[str]]
680 FAMILIAR: dict[str, tuple[str, ...]]
681 ALTERNATE_SPELLINGS: dict[str, tuple[str, ...]]
682
683
684def compile_readings(readings: Iterable[ReadingProperties]) -> Compiled:
685 """Fold the readings on by default into the default vocabulary's
686 constants. The readings are taken as already checked (the build's
687 checks run before it calls this); each needs ``text``, ``kind``
688 and ``props``.
689
690 Raises :class:`CompileError` on a post-nominal that is both an
691 acronym and a word, a backstop the build's checks 4 and 5 always
692 reach first. Any other exception is a bug in this function."""
693 on = [r for r in readings if r.on_by_default]
694 # the derived markers (the build's check 11): a clash with a name is
695 # a word's name reading beside the reading it clashes with, and a
696 # name reading written `default = false` marks nothing in the
697 # default, as it compiles to nothing (3a)
698 # a `given` reading carrying `same_as`, a name written short, marks
699 # none (`ReadingProperties.marks_a_clash`, #1383)
700 named = {r.text for r in on if r.marks_a_clash}
701 given = {r.text for r in on if r.kind == "given"}
702 titles: set[str] = set()
703 given_titles: set[str] = set()
704 after_given: set[str] = set()
705 written_short: set[str] = set()
706 title_kinds: dict[str, set[str]] = {}
707 attaches: dict[str, set[str]] = {}
708 particles: set[str] = set()
709 never_given: set[str] = set()
710 conjunctions: set[str] = set()
711 initial_conjunctions: set[str] = set()
712 bound: set[str] = set()
713 markers: set[str] = set()
714 alias_markers: set[str] = set()
715 words: set[str] = set()
716 glued: set[str] = set()
717 ambiguous_words: set[str] = set()
718 agnomens: set[str] = set()
719 ambiguous: set[str] = set()
720 acronyms: set[str] = set()
721 generations: set[str] = set()
722 credential_words: set[str] = set()
723 honorific_words: set[str] = set()
724 patronymics: set[str] = set()
725 saints: set[str] = set()
726 capitalized: set[str] = set()
727 capital_opening: set[str] = set()
728 dotted: set[str] = set()
729 glued_titles: set[str] = set()
730 title_case_names: set[str] = set()
731 shared: set[str] = set()
732 after_particle: set[str] = set()
733 bound_phrases: set[str] = set()
734 completes_any: set[str] = set()
735 long_names_only: set[str] = set()
736 seconds: set[str] = set()
737 second_phrases: set[str] = set()
738 open_seconds: set[str] = set()
739 cased: dict[str, str] = {}
740 same_as: dict[str, dict[str, set[str]]] = {
741 g: {} for g in SAME_AS_GROUPS.values()}
742 # per name kind, the words a reading of it writes short (`same_as`)
743 # and the words it names with none: a name of its own
744 short_names: dict[str, set[str]] = {}
745 own_names: dict[str, set[str]] = {}
746 # per matching-only category, a word -> the given names its pairs
747 # name, every file's: a familiar form -> the longer names it stands
748 # for, a spelling -> the names it is another spelling of
749 pairs: dict[str, dict[str, set[str]]] = {c: {} for c in MATCHING_LISTS}
750 for r in on:
751 t, p, category = r.text, r.props, CATEGORY[r.kind]
752 if category in MATCHING_LISTS:
753 pairs[category].setdefault(t, set()).update(
754 p.get(MATCHING_LISTS[category], ()))
755 continue
756 if "same_as" in p and (group := same_as_group(r.kind)) is not None:
757 same_as[group].setdefault(t, set()).update(same_as_of(p))
758 if "cased" in p:
759 cased[t] = p["cased"]
760 if category == "name":
761 into = short_names if "same_as" in p else own_names
762 into.setdefault(r.kind, set()).add(t)
763 if r.flag("shared"):
764 shared.add(t)
765 if r.kind == "given" and r.flag("after_particle"):
766 after_particle.add(t)
767 elif category == "title":
768 titles.add(t)
769 if r.addresses == "given":
770 given_titles.add(t)
771 if r.flag("after_given"):
772 after_given.add(t)
773 if r.flag("dotted"):
774 dotted.add(t)
775 if "attached" in p:
776 # a title reading's side is "before", the build's check
777 glued_titles.add(t)
778 if r.flag("abbreviation"):
779 written_short.add(t)
780 title_kinds.setdefault(t, set()).add(r.kind)
781 attaches.setdefault(t, set()).update(p.get("attaches", ()))
782 elif category == "suffix":
783 if r.acronym:
784 acronyms.add(t)
785 if t in named:
786 ambiguous.add(t)
787 else:
788 words.add(t)
789 if "attached" in p:
790 glued.add(t)
791 if t in named and r.kind in GATED_WORDS:
792 ambiguous_words.add(t)
793 if r.flag("title_case_is_name"):
794 title_case_names.add(t)
795 if r.kind == "agnomen":
796 agnomens.add(t)
797 elif r.kind == "generation":
798 generations.add(t)
799 elif r.kind == "credential":
800 credential_words.add(t)
801 elif r.kind in HONORIFIC_KINDS:
802 honorific_words.add(t)
803 elif category == "particle":
804 particles.add(t)
805 if r.kind == "patronymic":
806 patronymics.add(t)
807 elif r.kind == "saint":
808 saints.add(t)
809 if r.kind in CAPITALIZED_PARTICLE_KINDS:
810 capitalized.add(t)
811 if r.flag("capital_opening"):
812 capital_opening.add(t)
813 if t not in given:
814 never_given.add(t)
815 elif category == "conjunction":
816 conjunctions.add(t)
817 if r.flag("may_be_initial"):
818 initial_conjunctions.add(t)
819 elif category == "bound_given":
820 bound.add(t)
821 bound_phrases.update(f"{t} {w}"
822 for w in p.get("completed_by", ()))
823 if r.flag("completes_any"):
824 completes_any.add(t)
825 if r.flag("long_names_only"):
826 long_names_only.add(t)
827 elif category == "bound_second":
828 seconds.add(t)
829 if p.get("completes"):
830 second_phrases.update(f"{w} {t}" for w in p["completes"])
831 else:
832 open_seconds.add(t)
833 elif category == "relation":
834 # a birth marker routes what follows it to the maiden name
835 # (rules/M2), an alias marker to the nickname (rules/N4)
836 (markers if r.kind == "birth_marker" else alias_markers).add(t)
837 contested = titles & given - particles
838 out = Compiled(
839 GIVEN_NAME_TITLES=frozenset(given_titles),
840 # a title that may be a given name compiles into TITLES_AMBIGUOUS
841 # INSTEAD: a word in TITLES is a title wherever it stands, which
842 # is what a caller listing one there has always asked for
843 TITLES=frozenset(titles - contested),
844 AFTER_GIVEN_TITLES=frozenset(after_given),
845 # the fourth derived marker (check 11): a title that may be a
846 # given name, a title only inside a title phrase (rules/H9), and
847 # so not in TITLES above. A
848 # title that is also a particle ('st', 'freiherr') is left to the
849 # particle rules, which weigh its given reading at the front
850 # already (rules/P4)
851 TITLES_AMBIGUOUS=frozenset(contested),
852 # a word every title reading of which is a modifier: a title only
853 # with a head title behind it in its run (decision 10, rules/H9)
854 TITLE_MODIFIERS=frozenset(
855 t for t, ks in title_kinds.items() if ks == {"modifier"}),
856 TITLE_STYLES=frozenset(
857 t for t, ks in title_kinds.items() if "style" in ks),
858 # `attaches` resolved to the two-word phrases it licenses, the
859 # word before and each title word of a kind it names
860 TITLE_PHRASES=frozenset(
861 f"{t} {h}" for t, kinds in attaches.items() if kinds
862 for h, hk in title_kinds.items()
863 if h != t and (hk & kinds or h in kinds)),
864 NON_GIVEN_NAME_PARTICLES=frozenset(never_given),
865 PARTICLES=frozenset(particles),
866 CONJUNCTIONS=frozenset(conjunctions),
867 CONJUNCTIONS_AMBIGUOUS=frozenset(initial_conjunctions),
868 BOUND_GIVEN_NAMES=frozenset(bound),
869 # a given name written short (`chas`, Filipino `ma`): opening the
870 # given part period-marked, it is the given name, which outranks
871 # rules/H2's shape (#789)
872 GIVEN_NAME_ABBREVIATIONS=frozenset(short_names.get("given", ())),
873 MAIDEN_MARKERS=frozenset(markers),
874 ALIAS_MARKERS=frozenset(alias_markers),
875 SUFFIX_WORDS=frozenset(words),
876 GLUED_HONORIFICS=frozenset(glued),
877 SUFFIX_WORDS_AMBIGUOUS=frozenset(ambiguous_words),
878 AGNOMENS=frozenset(agnomens),
879 SUFFIX_ACRONYMS_AMBIGUOUS=frozenset(ambiguous),
880 SUFFIX_ACRONYMS=frozenset(acronyms),
881 CAPITALIZATION_EXCEPTIONS=dict(sorted(cased.items())),
882 # the kinds the compiled sets above do not record, which the
883 # generation, credentials, honorifics and patronymic views read (rules/R8,
884 # rules/R9): a suffix WORD's kind, `jr` and `esq` both being in
885 # SUFFIX_WORDS, and a particle's. Internal, re-exported by no
886 # config module (#754, 4i-b)
887 GENERATION_WORDS=frozenset(generations),
888 CREDENTIAL_WORDS=frozenset(credential_words),
889 HONORIFIC_WORDS=frozenset(honorific_words),
890 PATRONYMIC_PARTICLES=frozenset(patronymics),
891 # the title readings written short (`abbreviation`), which H5's
892 # trailing chain takes where the word may also be a given name
893 # (#999); internal, like the kind sets above
894 TITLE_ABBREVIATIONS=frozenset(written_short),
895 # the suffix words whose Title case is their writing as a name
896 # (`fils`, `kc`): of a word gated by a name reading, the one
897 # kind whose writing leans (rules/S6, S11, #1039)
898 TITLE_CASE_NAME_WORDS=frozenset(title_case_names),
899 # the names a community gives every member (Sikh `kaur`,
900 # `singh`), no personal or family name of the bearer's own,
901 # which the two-name switches neither move nor complete
902 # (rules/O6, O7, #704); internal, like the kind sets above
903 SHARED_NAMES=frozenset(shared),
904 # the given names written behind a particle as the second of a
905 # compound given name (`del Carmen`, `de los Ángeles`), which
906 # rules/P10 reads as a middle name behind a one-word given name
907 # (#704)
908 PARTICLE_GIVEN_NAMES=frozenset(after_particle),
909 # the particles naming a saint (`san`, `santa`, `st`), which
910 # open a place name or a surname (`Santa María`), never a given
911 # name's second, so a given name phrase holds none (#704)
912 SAINT_PARTICLES=frozenset(saints),
913 # the particles of the kinds written with a capital (`St`,
914 # `San`, `Freiherr`, `Graf`), which case repair does not
915 # lowercase, rules/R4 (#1069)
916 CAPITALIZED_PARTICLES=frozenset(capitalized),
917 # the particles written `capital_opening` (`ter`, `der`), which
918 # case repair writes with a capital where no particle stands
919 # before one in the family name, nor, where it opens the family
920 # name, written right before it in any role, rules/R12
921 CAPITAL_OPENING_PARTICLES=frozenset(capital_opening),
922 # the titles written `dotted` (`us`, `uk`, `pd`), which a run of
923 # single letters joined by full stops spells at the head of a
924 # name where a title the run keeps stands behind it, rules/H10
925 DOTTED_TITLES=frozenset(dotted),
926 # the titles written `attached` (side "before"), which
927 # rules/W6's front peel splits off the start of the name's first
928 # word they are glued to (`นายสมชาย`, #317)
929 # a title that may be a given name is a title only in a phrase
930 # (rules/H9), so none is split off a glued word: the given name
931 # it opens would be cut and no title read (#317)
932 GLUED_TITLES=frozenset(glued_titles - contested),
933 # `completed_by` resolved to the two-word given names it lists,
934 # the bound word and each word that completes it ('عبد الله'),
935 # which rules/P12 joins wherever they stand (#694)
936 BOUND_PHRASES=frozenset(bound_phrases),
937 # the bound given names written `completes_any`, which rules/P12
938 # joins with any plain name word after them past the first name
939 # word, and of those the ones written `long_names_only`, joined
940 # only in a name of four words or more (#1464)
941 BOUND_COMPLETES_ANY=frozenset(completes_any),
942 BOUND_LONG_NAMES_ONLY=frozenset(long_names_only),
943 # the bound_second readings, the word a bound pair writes second
944 # and joins from, and the pairs those written `completes` list
945 # ('ذو الغنى'), the only ones such a word joins: one with no
946 # `completes` joins behind any plain word, at the first name
947 # word too (rules/P12, #1072)
948 BOUND_SECONDS=frozenset(seconds),
949 BOUND_SECOND_PHRASES=frozenset(second_phrases),
950 # the words every reading of which lists `completes`: those join
951 # behind their listed words alone, where one reading listing none
952 # joins behind any plain word
953 BOUND_SECONDS_LISTED=frozenset(seconds - open_seconds),
954 # every reading's `same_as` in the group of its kind: the words
955 # it is a listed spelling of (`wm` of `william` among given
956 # names, `junior` of `jr` among suffixes, `sr` of both `señor`
957 # and `senhor` among titles), which no set above records
958 SAME_AS={g: {w: tuple(sorted(heads))
959 for w, heads in sorted(same_as[g].items())}
960 for g in sorted(same_as)},
961 # the derived marker of a listed spelling: a word whose name
962 # reading carries a `same_as` beside a reading of the same kind
963 # with none, a name written short that is a name of its own too
964 # (`jo`, José written short and the given name Jo), whose links
965 # the name match reads only where the word is written with its
966 # period (decisions/name-matching, 2026-11-08 #1006 follow-up).
967 # A bound given name's or a particle's `same_as` is a spelling
968 # written without one (`ابو` of `أبو`), and marks nothing
969 SAME_AS_NAMED={g: frozenset(
970 w for k, short in short_names.items()
971 if same_as_group(k) == g
972 for w in short & own_names.get(k, set()))
973 for g in sorted(same_as)},
974 # a familiar form and the longer given names it stands for, one
975 # way (`max` of `maxim` and `maximilian`, which do not stand for
976 # each other), every file's together: read by the name match's
977 # opt-in `familiar-form` alone, never by a parse
978 # (decisions/name-matching, 2026-11-08 FAMILIAR FORMS)
979 FAMILIAR=_sorted_lists(pairs["familiar"]),
980 # a given name and the given names it is another spelling of,
981 # one way, every file's together: read by the name match's
982 # opt-in `alternate-spelling` alone, never by a parse
983 # (decisions/name-matching, 2026-11-12 ALTERNATE SPELLINGS ARE
984 # OPT-IN)
985 ALTERNATE_SPELLINGS=_sorted_lists(pairs["spelling"]),
986 )
987 # One form per post-nominal: the word test strips only edge periods
988 # and the acronym test strips all of them, so a word in both is
989 # matched twice by two rules, and which one fired is unreadable from
990 # outside. The sharper stake is the ambiguous set's: suffix_as_written
991 # ORs the two branches, so an ambiguous acronym that were also a word
992 # would be claimed through the word and bypass the period gate the
993 # marking exists to impose. The single overlap was 'esq', dropped
994 # 2026-09-08 (decisions/suffix-acronym-collisions). Lexicon guards
995 # only that ambiguous half (its gate-bypass raise), so a caller may
996 # still put an unambiguous word in both. In the TOML the overlap is
997 # unreachable -- the build's check 4 refuses two suffix kinds on one
998 # word, check 5 one kind with `acronym` differing between files, and
999 # check 2 a word twice in one file -- so this is a backstop kept
1000 # because it costs one set intersection, not a check any input
1001 # reaches today.
1002 both = out["SUFFIX_ACRONYMS"] & out["SUFFIX_WORDS"]
1003 if both:
1004 raise CompileError(f"{sorted(both)}: a post-nominal is an acronym or a "
1005 f"word, never both (check `acronym` in every file)")
1006 return out