1"""Stage: assign.
2
3Consumes: pieces + piece_tags (grouped), segments, structure, tokens,
4one_case, and tail_reads -- rules/S2's trailing run as group read it
5once, after P3's joins and before the particle chain (#614), which the
6main segment's placement takes rather than peeling again, save where
7group's joins left no name word in front of it; and interpunct_offsets,
8whose 间隔号 keeps a transcription in its declared order (rules/W4);
9and extracted, whether a set-apart clause stands beside the name
10(N3's single-name rule and the sites that follow it).
11Produces: tokens with roles set on every main-stream token, and the
12folded-middle and attached tags on the particles P6's attachment joins
13to the family after a family comma (#613; the attached tag, 3.0's 4c,
14tells rules/R9 the attachment from O3's fold); and order, the order
15the positional read used, None where none happened (ParseState.order).
16Reads: Policy.name_order (#270), Policy.lone_name_word (rules/O5,
17the field a lone name word takes, #1111), Policy.initials_as_family
18(rules/O4's order report stands down under it, #1254), is_suffix_lenient on the trailing
19piece of a two-part comma name, and Policy.script_orders (#271, which
20overrides it when every name piece is written wholly in one script, or
21in the Han/Hiragana/Katakana repertoire the #272 kana license shares
22across pieces); token/piece tags; Lexicon through tags already
23applied by classify (plus the leading-title period rule), save the
24four suffix sets (suffix_words, suffix_acronyms and their ambiguous
25sets), which the walk over the given part after a family comma reads
26through _vocab.is_suffix_lenient (`_reads_as_a_trailing_suffix`), and
27Lexicon.given_name_titles, which an ambiguity's alternative asks for
28rules/P5's given-name-title licence; and Lexicon.title_phrases, titles
29and titles_ambiguous through _vocab.in_a_title_phrase, for rules/H9's
30TITLE_OR_NAME report on a contested word opening the name.
31
32Implements rules H2, H4, H5, H6, H7, H8, H9, H10, C9, N3, O4, O5, P9,
33S8, S10, S12, W4, and P6 after a family comma,
34of docs/design/rules/,
35each cited at its code below. Ports v1's assignment loops.
36NO_COMMA (per name_order):
37leading title pieces chain while no given-position name has been seen
38(a title needs a following piece, unless the whole name is one title);
39then positional assignment per name_order with the trailing-suffix
40rule: the piece from which everything after is a strict suffix is the
41last name-position piece, the rest are suffixes. Behind that peel a
42trailing run of the title words H5's chain takes
43(`_pieces.trailing_titles`) chains into the title from
44the end, leaving one name piece standing; where the run TAKES
45something the peel was only provisional and runs again over the pieces
46with the titled ones spliced out, the two alternating until the run
47takes nothing, so a trailing title is transparent to the suffix
48reading however many titles are written (_pieces.tail_reading). Where
49the run takes nothing -- almost every name -- the first peel is the
50only one and its answer stands.
51The v1 single-name+nickname rule lives here (decisions/N3): a
52nonempty nickname beside exactly one piece in total puts that piece
53in FAMILY.
54FAMILY_COMMA: segment 0 FAMILY but for a leading run of listed titles
55(rules/H6, #701; v1 kept them in the family) and the post-nominals
56behind its first family piece (SUFFIX, 'Smith Jr., John'). A part after the
57comma that holds no name word, or that a credential opens (#603), is
58not read here: group's head binds its SUFFIX and TITLE roles before
59any join (`_comma.decide`, #613), making the comma a suffix comma
60behind a whole name ('John Smith, Dr.', 'John Smith, PhD Jones') and
61leaving the family comma behind one name word ('Smith, Jr.', 'Smith,
62PhD Jones'), where segment 1 then reaches this stage with no pieces.
63A segment 1 that does reach it gets leading titles, then the same
64trailing title run over the pieces this segment does not read as
65suffixes ('Smith, John Prof.'), then given, then middles with those
66suffix-reading pieces to suffix -- one predicate for both -- and
67#602's run after the given word ('Smith, John PhD Jones'); segments 2+
68are suffixes but for their title words (#603), lenient -- segment
69already flagged the ones that are neither COMMA_STRUCTURE.
70SUFFIX_COMMA: segment 0 as NO_COMMA; segment 1 arrives bound by group,
71and segments 2+ are read as after a family comma.
72Emits PARTICLE_OR_GIVEN when the leading name piece is a lone
73particles_ambiguous token with more pieces following ("Van Johnson",
74and since #367 "Dr. Van Johnson" too, a title no longer displacing the
75particle out of that position) -- whatever role name_order assigns,
76save a lowercase one in a mixed-case name under a family-first order,
77which P1's fold takes (rules/P11, #670) --
78and, since #613, at P6's attachment after a family comma where the run
79holds an ambiguous particle ("Beethoven, Ludwig van").
80Emits SUFFIX_OR_NAME at these sites: the trailing roman numeral, taken
81or declined (since #718 for want of words to spare, since #752 for its
82Title case), a numeral ending the family part before a family comma,
83one of two or more letters ending a given part's walk, a bare I or V
84read as the generation ending that walk behind a name word (since
85#877), each
86ambiguous acronym the trailing peel had to resolve, the bare-suffix
87carve-out where an input that is nothing but post-nominal vocabulary
88gets its first word made into the name (H4's suffix half, #491),
89-- since #289 -- the FAMILY-COMMA path's own read of the first
90post-comma piece as the given name, -- since #531 -- the class member
91ENDING that path's given part, which the first-piece emitter could
92never reach, -- since #602 -- each name word the credential run
93absorbs, in the no-comma name and in the given part after a family
94comma, and -- since #613 -- P6's attachment after a family comma,
95where it declines a post-nominal reading or stands down inside a
96credential run.
97Further emitters of the same kind live in `_comma.py` (called at
98group's head: the comma's own decision, #544's anchored members and
99#603's absorbed words) and `_group.py`; they are not assign's and are
100not counted here. And
101at the one site that places a LONE name word, GIVEN_OR_FAMILY for the
102field the convention picked (O5, #449) and TITLE_OR_NAME for the two
103shapes where the doubt is whether a word is a title instead (H4 and
104H7, #491): the peel leaving one title-vocabulary word standing, and a
105joined unit carrying title vocabulary.
106"""
107from __future__ import annotations
108
109import unicodedata
110
111from collections.abc import Sequence, Set
112from typing import NamedTuple
113
114from nameparser._lexicon import Lexicon, _run_addresses_by_given
115from nameparser._pipeline._vocab import (
116 _ROMAN, effective_script, in_a_title_phrase, in_initialless_script,
117 is_initial_shaped,
118 TITLE_READING, is_listed_numeral, particle_reading,
119 is_suffix_lenient, name_reading, suffix_reading,
120 numeral_leans_to_the_name, numeral_settled_by_case,
121 reads_as_a_reported_numeral, reads_as_generation, resolve_script_set,
122)
123from nameparser._pipeline._pieces import (
124 split_credential_report,
125 anchor_in_reach, credential_at_the_given_slot, given_slot_anchors,
126 _NOT_A_RUN_START, has_name_content, is_lone_never_given_particle,
127 is_lowercase_ambiguous_particle,
128 Peel, TailRead, is_prefix_piece, is_suffix_piece, is_title_piece,
129 leading_titles,
130 particle_tail, listed_lean, peel_walk, settled_by_case,
131 starts_a_credential_run, starts_the_run_here,
132 tail_reading, trailing_titles,
133)
134from nameparser._pipeline._state import (
135 AMBIGUOUS_ACRONYM_TAG, ATTACHED_TAG, DOTTED_TITLE_TAG, NAME_ROLES, TITLE_AMBIGUOUS_TAG, ParseState,
136 Beside, Deferred, PendingAmbiguity, PendingReading, Structure,
137 WorkToken, _AMBIGUOUS_CREDENTIAL_TAGS, _NEVER_FLIPPED, copy_with,
138)
139from nameparser._policy import _EAST_ASIAN_SCRIPTS, _JA_SCRIPTS, Policy, Script
140from nameparser._types import (FOLDED_TAG, SHAPE_ACRONYM_TAG, AmbiguityKind,
141 ReadingKind, ReadingSource, Role)
142
143def _set_roles(tokens: list[WorkToken], piece: tuple[int, ...],
144 role: Role) -> None:
145 for i in piece:
146 tokens[i] = copy_with(tokens[i], role=role)
147
148
149def _name_pieces(state: ParseState, tokens: Sequence[WorkToken],
150 seg_idx: int) -> list[tuple[int, ...]]:
151 """The pieces of segment `seg_idx` the parse read as name words."""
152 return [q for q in state.pieces[seg_idx]
153 if tokens[q[0]].role in NAME_ROLES]
154
155
156def _slot_field(state: ParseState, seg_idx: int, pos: int, count: int,
157 order: tuple[Role, Role, Role] | None) -> Role:
158 """The field position `pos` of `count` name words takes in segment
159 `seg_idx`, every other word read as the parse read it: the family
160 before a family comma, the given part's given or middle name after
161 one, and otherwise the order the main segment's read set.
162
163 `count` is two or more wherever no family comma decides, so rules/O5's
164 lone-word field is never asked here: `as_a_name` counts one more than
165 the name pieces, of which assign always places one (its lone-piece
166 branches index the first, so a parse with none would raise there); a split
167 pair stands behind a name word H4's carve-out keeps; and
168 `_resolve_deferred` counts a chained word one more than its name's,
169 and reads a join that would leave the name one word as no join
170 (rules/P3) before it asks."""
171 if state.structure is Structure.FAMILY_COMMA:
172 return (Role.FAMILY if seg_idx == 0
173 else Role.GIVEN if pos == 0 else Role.MIDDLE)
174 assert order is not None # the main segment's read sets it
175 return _name_positions(order, count)[pos]
176
177
178def _name_alt(token: WorkToken, role: Role,
179 front: Sequence[int] | None, tokens: Sequence[WorkToken],
180 first: bool, licensed: bool) -> PendingReading:
181 """The name reading of a word read as something else, landing in
182 `role` unless the name piece `front` it stands behind would take it
183 in, so that it lands where that piece lands: a particle chain runs
184 to the end of the part's name words (rules/P2), and a lone particle
185 stands unchained only for want of a word behind it, unless it opens
186 the part, where it never chains (rules/P4); and a bound given name
187 opening the part joins the word after it where it is `licensed`, a
188 family comma having fixed the family or a given-name title standing
189 ahead (rules/P5),
190 since the word would otherwise be the family word the join
191 reserves; and a never-given particle opening the part folds it into
192 the family (rules/P1). The front's field is named at
193 assemble, where P6 may since have attached it to the family, which
194 it would not have done with a word behind it (`Beside`)."""
195 alt = name_reading(token, role)
196 if front is None:
197 return alt
198 tags = tokens[front[0]].tags
199 # rules/P1's fold: a never-given particle opening the part takes the
200 # word behind it into the family, whatever the order and the part
201 if first and is_lone_never_given_particle(front, tokens):
202 return copy_with(alt, role=Role.FAMILY)
203 # a piece opening the part with a bound given name is P5's join,
204 # not a chain, though `abu` is a particle too: the word stands apart
205 bound = first and "vocab:bound-given" in tags
206 if ("particle" in tags and (len(front) > 1 or not first) and not bound
207 or licensed and bound and len(front) == 1):
208 # a front P6 has already attached held `role`'s field before it;
209 # `last` names the front's last word, which rules/P10 leaves the
210 # family where it reads the chain's opening phrase as a middle
211 # name (decisions/P10, #704)
212 return copy_with(alt, role=Beside(
213 front[0], role if FOLDED_TAG in tags else tokens[front[0]].role,
214 last=front[-1]))
215 return alt
216
217
218def _absorbed(piece: Sequence[int], tokens: Sequence[WorkToken],
219 alt: PendingReading | None) -> PendingAmbiguity:
220 """rules/S8's report for a name word #602's run absorbs, one
221 spelling for the no-comma and the given-part run. `alt` is its
222 name reading, whose field the caller's positional read knows (None
223 where the caller fills it in once it does)."""
224 text = " ".join(tokens[i].text for i in piece)
225 return PendingAmbiguity(
226 AmbiguityKind.SUFFIX_OR_NAME,
227 f"{text!r} follows a credential, so it reads as part of the "
228 f"suffix run; it may be a name word", tuple(piece),
229 alternative=alt)
230
231
232#: Tags that say the word's own reading was claimed before position
233#: could speak, so O5's convention decided nothing. Built from M4's
234#: `_NEVER_FLIPPED` pair rather than respelling it: the two sets answer
235#: different questions -- may M4 retag the word, and did anything
236#: decide the field -- and share the pair because a bound given name,
237#: or a word written as an initial, answers both. The
238#: third, `particle`, is here alone because a lone particle's reading
239#: is P4's. None is a predicate this emitter owns: they are read off
240#: the tags classify already recorded (mechanisms.md#TWO-LAYER-ASSIGN).
241_WORD_ALREADY_CLAIMED = _NEVER_FLIPPED | frozenset({"particle"})
242
243
244# rules/H2: "an abbreviation opening the part of the name that
245# carries the given name — the whole name, or the part after a
246# family comma — reads as a title even when unlisted" -- the count is
247# _pieces.leading_titles since #424 (the chain's leading position is
248# read off the same run, _pieces.chain_lead, #624); the roles are set
249# here.
250def _peel_leading_titles(pieces: tuple[tuple[int, ...], ...],
251 ptags: tuple[frozenset[str], ...],
252 tokens: list[WorkToken],
253 ambiguities: list[PendingAmbiguity] | None,
254 lexicon: Lexicon) -> int:
255 """Assign TITLE to the leading title pieces and return the first
256 non-title index. `ambiguities` is None where a family comma has
257 already marked the part as the given name, so no fork is left to
258 report."""
259 n = leading_titles(pieces, ptags, tokens)
260 for k in range(n):
261 _set_roles(tokens, pieces[k], Role.TITLE)
262 # rules/H9: "read as a name word where it is the first name word
263 # after any titles" -- the peel stops at it because classify read it
264 # out of the title, so it is the first piece the peel leaves
265 # ('Dean Smith', 'Mr Dean Smith'); and rules/H9: "a word no listed
266 # phrase holds is a title only behind a style or a modifier, or
267 # before `of`", so standing alone it reports nothing ('Grace Smith')
268 if (ambiguities is not None and n < len(pieces) and len(pieces[n]) == 1
269 and TITLE_AMBIGUOUS_TAG in tokens[pieces[n][0]].tags
270 and "vocab:title" not in tokens[pieces[n][0]].tags
271 and in_a_title_phrase(tokens[pieces[n][0]].text, lexicon)):
272 i = pieces[n][0]
273 ambiguities.append(PendingAmbiguity(
274 AmbiguityKind.TITLE_OR_NAME,
275 f"{tokens[i].text!r} is a title that may also be a given name, "
276 f"and stands in no title phrase; read as ", (i,),
277 field_tail=" rather than a title", alternative=TITLE_READING))
278 return n
279
280
281class EffectiveOrder(NamedTuple):
282 """What _effective_order made of a name's scripts. `order` is the
283 order the positional read uses; `by_script` says an East Asian
284 script's script_orders entry RESOLVED it, which is not the same as
285 `order` happening to
286 equal the declared name_order -- under a declared family-first
287 order a Han name's W4 entry and the declaration agree, and only
288 this flag distinguishes the script rule DECIDING the reading from
289 the caller's declaration standing unopposed. O5's convention
290 report reads it (#449). Set only for an East Asian script's entry:
291 Han, Hangul and kana, whose own convention settles the order (W4)
292 and so a lone word's field (O5's W4 Except), and a caller's own
293 katakana entry, which asserts the Japanese convention (#594): a Cyrillic entry, a pack's declared order
294 (locales.MN, #1237), orders a longer name and leaves a lone word to
295 O5's convention."""
296
297 order: tuple[Role, Role, Role]
298 by_script: bool
299
300
301# rules/W4: "a name written wholly in one East Asian script, or in
302# the kana-licensed Japanese repertoire, reads family-first whatever
303# order the caller declared; a wholly-katakana name keeps the declared
304# order; and a name written wholly in a script a chosen locale pack
305# gives an order reads by that order" -- both clauses: the entry
306# answers for any script, its by_script only for an East Asian one
307# (history: decisions/W4)
308def _effective_order(policy: Policy,
309 pieces: Sequence[tuple[int, ...]],
310 name_pieces: Sequence[int],
311 tokens: list[WorkToken],
312 *, dot_divided: bool) -> EffectiveOrder:
313 """script_orders resolution (#271): when every name piece is
314 written wholly in ONE script that has an entry, that script's
315 order governs the positional read; anything else -- Latin, mixed
316 scripts, no entry -- falls back to name_order. A 间隔号-divided
317 name (`dot_divided`, #298) suppresses the whole lookup first: the
318 dot marks a transcription -- playing the role pure katakana plays
319 in the kana license, orthography naming the convention -- so the
320 license yields to name_order. Piece-level, after
321 title/suffix peeling: 'Dr. 毛泽东' is a wholly-Han NAME under a
322 Latin title. Kana-licensed tokens (高橋みなみ, #272) resolve to
323 HIRAGANA the same way a wholly-Han or wholly-Hangul token resolves
324 to its own script -- and so does a kana-licensed NAME split across
325 separately single-script PIECES ('高橋 みなみ', Han piece plus
326 Hiragana piece): resolve_script_set generalizes the license from
327 one token's characters to the whole found-script set below, which
328 is why Han+Hangul ('毛 김') still declines even though both
329 individually read family-first -- the license is specific to the
330 Han/Hiragana/Katakana repertoire, not "the entries happen to
331 agree".
332
333 Naming note, since the two are easy to conflate: THIS function
334 resolves the ORDER for a whole name; `_vocab.effective_script`
335 resolves the SCRIPT for a single token. This function calls that
336 one per token below.
337
338 Takes the segment's pieces and WHICH of them the name kept, the
339 shape every piece-layer predicate takes: a caller holding those
340 indices had to build a second list of the same pieces to hand
341 over otherwise, which on 3.11 is a comprehension frame on every
342 parse (decisions/parse-cost).
343
344 Returns an EffectiveOrder: the order triple, and `by_script` set only on
345 the one path where an entry answered for an East Asian script (a
346 Cyrillic entry answers the order with `by_script` False, see
347 EffectiveOrder). Every fallback below is a
348 script rule DECLINING, and reports it as such.
349 """
350 declared = EffectiveOrder(policy.name_order, by_script=False)
351 # #298 transcription marker -- see the docstring; codepoint-scoped
352 # (only U+00B7 records; decisions/T3)
353 if dot_divided:
354 return declared
355 if not policy.script_orders:
356 return declared
357 # Collect every token's script rather than comparing pairwise as
358 # tokens are seen: the kana license needs the WHOLE set (a Han
359 # piece and a Hiragana piece only license together, never one at a
360 # time), so resolution is deferred to resolve_script_set below.
361 found: set[Script] = set()
362 for piece_idx in name_pieces:
363 for i in pieces[piece_idx]:
364 script = effective_script(tokens[i].text)
365 if script is None:
366 # Latin, mixed, or a script with no entry: never a key
367 return declared
368 if script not in _JA_SCRIPTS:
369 # A script outside the kana license resolves alone to
370 # itself or, beside any other, to None, so one with no
371 # entry decides the declared order now; this spares a
372 # Cyrillic name the rest of its words' classifying
373 # under a policy with no Cyrillic entry.
374 for keyed, _order in policy.script_orders:
375 if keyed is script:
376 break
377 else:
378 return declared
379 found.add(script)
380 resolved = resolve_script_set(found)
381 if resolved is None:
382 # e.g. Han+Hangul: two scripts, neither the kana license's
383 # Han/Hiragana/Katakana repertoire -- no single tradition
384 return declared
385 for script, order in policy.script_orders:
386 if script is resolved:
387 return EffectiveOrder(
388 order, by_script=resolved in _EAST_ASIAN_SCRIPTS)
389 # the resolved script has no entry: the declaration stands, and
390 # nothing about the writing system decided the reading
391 return declared
392
393
394# rules/O4: "words no vocabulary has claimed read by position. In
395# the default given-first order the first name word is the given name,
396# the last is the family name, and everything between is middle names"
397def _name_positions(order: tuple[Role, Role, Role],
398 count: int) -> list[Role]:
399 """Roles for `count` name pieces (titles/suffixes already peeled),
400 per name_order. GIVEN_FIRST: given, middles..., family.
401 FAMILY_FIRST: family, given, middles... FAMILY_FIRST_GIVEN_LAST:
402 family, middles..., given. One piece takes order[0], which
403 `_assign_main`, placing a lone name word, overrides with rules/O5's
404 field (every other caller lays out two or more, or slices the first
405 slot off); two pieces take order[0] and the other primary."""
406 first, second = order[0], order[1]
407 if count == 1:
408 return [first]
409 if first is Role.GIVEN: # GIVEN_FIRST
410 return ([Role.GIVEN] + [Role.MIDDLE] * (count - 2)
411 + [Role.FAMILY])
412 if second is Role.GIVEN: # FAMILY_FIRST
413 return ([Role.FAMILY, Role.GIVEN]
414 + [Role.MIDDLE] * (count - 2))
415 return ([Role.FAMILY] + [Role.MIDDLE] * (count - 2) # F_F_GIVEN_LAST
416 + [Role.GIVEN])
417
418
419def _placed(read: TailRead, rest: list[int],
420 pieces: tuple[tuple[int, ...], ...],
421 ) -> tuple[list[int], tuple[int, ...], Peel]:
422 """`tail_reading`'s three answers, taken off the run group read at
423 its head (#614) rather than read again over the joined pieces: the
424 walk with the name pieces first and the run's suffixes after them,
425 the pieces the H5 chain took, and the read's peel with `names` and
426 `run_titles` renumbered onto these pieces. Group split the run off
427 before its joins and put it back after them unchanged, so each of
428 its pieces is whole here and a membership test on its first token
429 places it."""
430 names: list[int] = []
431 suffixes: list[int] = []
432 titled: list[int] = []
433 run_titles: list[int] = []
434 for k in rest:
435 first = pieces[k][0]
436 if first not in read.tail:
437 names.append(k)
438 elif first in read.titles:
439 titled.append(k)
440 else:
441 suffixes.append(k)
442 if first in read.run_titles:
443 run_titles.append(k)
444 peel = read.peel
445 count = len(names)
446 names.extend(suffixes)
447 # built, not `_replace`d: that is two frames on every read
448 return names, tuple(titled), Peel(
449 count, peel.numerals, peel.picks, peel.anchors, tuple(run_titles),
450 peel.absorbed, peel.declined)
451
452
453def _assign_main(seg_idx: int, state: ParseState,
454 tokens: list[WorkToken],
455 ambiguities: list[PendingAmbiguity],
456 ) -> tuple[Role, Role, Role] | None:
457 """Returns the order the positional read used, for ParseState.order
458 -- None on every path that returns before resolving one."""
459 pieces = state.pieces[seg_idx]
460 ptags = state.piece_tags[seg_idx]
461 n = _peel_leading_titles(pieces, ptags, tokens, ambiguities,
462 state.lexicon)
463 if n == len(pieces):
464 return None
465 # group-flagged suffix pieces (the ph-d merge) are suffixes at ANY
466 # position -- v1's fix_phd extracted the credential from the string
467 # before parsing, so position never mattered (PR review I3).
468 # Walked rather than collected first: the list was never read
469 # again, and on 3.11 a comprehension is a frame of its own, which
470 # is one frame back against the one the H5 reading below costs. A
471 # 3.11 FACT and not a portable one: PEP 709 inlines comprehensions
472 # from 3.12, where this tree's reference parse costs 395 written
473 # either way (measured 2026-09-09, against 416 and 417 on 3.11).
474 # 3.11 is the interpreter the band is quoted for, so 3.11 is what
475 # the shape is chosen on (decisions/parse-cost).
476 for k in range(n, len(pieces)):
477 if "suffix" in ptags[k]:
478 _set_roles(tokens, pieces[k], Role.SUFFIX)
479 rest = peel_walk(n, ptags)
480 if not rest:
481 return None
482 # rules/N3: "a name that is only a nickname and one name word
483 # reads that word as the family name" (history: decisions/N3)
484 # -- v1's p_len == 1 counted
485 # the WHOLE segment before any title peeling -- 'Xyz. (Bud) Smith'
486 # has two pieces, so the title peel wins and this rule declines;
487 # H1 then names Smith the family (rules/N3's title bullet)
488 # A suffix makes two pieces as a title does: that shape is N3's
489 # suffix clause, at O5's site below.
490 # The nickname scan sits LAST in the test: it is a generator, which
491 # every interpreter resumes once per token (seven call events on
492 # the reference name), and only a one-piece segment ever reads its
493 # answer. Hoisting it to the top of the read, where it once stood,
494 # is what put 3.12-3.15 one call over the band (decisions/parse-cost).
495 # Behind `state.extracted`, as at N3's suffix clause below: a
496 # nickname is a clause extract set aside.
497 if (len(pieces) == 1 and len(rest) == 1 and state.extracted
498 and any(t.role is Role.NICKNAME for t in tokens)):
499 _set_roles(tokens, pieces[rest[0]], Role.FAMILY)
500 return None
501 # rules/S2's trailing peel and rules/H5's title chain, read
502 # together to their fixed point by _pieces.tail_reading -- one
503 # function since the /simplify round, shared with the bound-given
504 # reserve (P5), which must count the name words this leaves.
505 #
506 # rules/H5: "successive single words that wear the abbreviation
507 # shape and are title vocabulary chain into the title from the end,
508 # leaving one name word standing" -- the titles are set BEFORE
509 # _name_positions, so the shortened list is what the positional
510 # read and the script test both see (a trailing Latin title must
511 # not make a wholly-CJK name look mixed-script, the same reason the
512 # leading peel runs first). Read ahead of the bare-suffix carve-out
513 # because with no name piece left there is nothing for the chain to
514 # read: its floor keeps 0 pieces of an empty list, so the branch
515 # below is reached exactly as before.
516 #
517 # Every bare ambiguous acronym the FINAL peel had to resolve is one
518 # coin-flip each, in either direction, so the report collects
519 # rather than overwrites. Deferred to after assignment because what
520 # a pick is declined as depends on the role it took, and which role
521 # "not peeled" means depends on name_order; the field itself is
522 # worded by assemble (#626). (The roman-numeral fork's TAKEN branch
523 # needs no such deferral and is reported here; its declined branch
524 # is a pick, #718, and is reported with the others.)
525 #
526 # Read once in group, after P3's connective joins and ahead of the
527 # particle chain, on a main segment of three or more pieces whose
528 # run is one block at its end (#614): the run is placed off that
529 # reading. Where the read left name pieces and
530 # group's joins then left none past the leading titles -- a join
531 # that made the name a title ('Freiherr von Berg Dr. and Ed.
532 # Prof.') -- the reading is taken here over what stands, as it was
533 # taken everywhere before #614, so the name keeps a word. The same
534 # procedure and not always the same answer: the run group read
535 # split off was kept out of group's joins, so what stands differs
536 # from what stood before #614 (that name read family 'von Berg Dr.
537 # and Ed. Prof.' then).
538 read = (state.tail_reads[seg_idx]
539 if seg_idx < len(state.tail_reads) else None)
540 if read is not None:
541 placed = _placed(read, rest, pieces)
542 if read.peel.names and not placed[2].names:
543 read = None
544 else:
545 rest, titled_tail, peeled = placed
546 if read is None:
547 rest, titled_tail, peeled = tail_reading(rest, pieces, ptags, tokens,
548 state.one_case)
549 for piece_idx in titled_tail:
550 _set_roles(tokens, pieces[piece_idx], Role.TITLE)
551 # rules/S8: "except a title word, which reads as a title" -- the
552 # credential run (#602) is placed here, so a name word it absorbed
553 # is reported here too
554 for piece_idx in peeled.run_titles:
555 _set_roles(tokens, pieces[piece_idx], Role.TITLE)
556 # the name reading of a word the run or the numeral fork took lands
557 # where one more name word after the name's would: its field is
558 # filled in below, once the positional read has an order
559 trailing_alts = len(ambiguities)
560 for piece in peeled.absorbed:
561 ambiguities.append(_absorbed(piece, tokens, None))
562 for numeral in peeled.numerals:
563 # a single letter is a name part unless it happens to be a
564 # roman numeral -- and V/X/I are ordinary middle initials, so
565 # taking it as a suffix is a call, not a fact; a numeral read
566 # by its shape alone is in no wordlist, and may be a name word
567 text = tokens[numeral[0]].text
568 ambiguities.append(PendingAmbiguity(
569 AmbiguityKind.SUFFIX_OR_NAME,
570 f"{text!r} is a roman numeral, so it reads as a "
571 f"generational suffix; "
572 + ("any other single letter there would be a middle initial"
573 if len(text.rstrip(".")) == 1
574 else "it may be a name word"),
575 numeral))
576 name_pieces, suffix_pieces = rest[:peeled.names], rest[peeled.names:]
577 if peeled.run_titles:
578 suffix_pieces = [q for q in suffix_pieces
579 if q not in peeled.run_titles]
580 if peeled.names == 0:
581 # everything suffix-shaped after titles: first one is the name
582 name_pieces, suffix_pieces = suffix_pieces[:1], suffix_pieces[1:]
583 # AFTER the whole tail reading, and load-bearing: the script test
584 # sees the NAME pieces only, so a Latin title or suffix ('Dr. 毛
585 # 泽东', '毛 泽东, PhD') cannot make a wholly-CJK name look
586 # mixed-script.
587 resolved = _effective_order(state.policy, pieces, name_pieces, tokens,
588 dot_divided=bool(state.interpunct_offsets))
589 order = resolved.order
590 # rules/O5: "a name of one name word that nothing else has
591 # decided reads that word as the field the caller's lone-word
592 # setting names" -- `Policy.lone_name_word`, a convention, not a
593 # determination: O4 has no positions to compare at one word, so
594 # this line is where the library picks one of two equally
595 # consistent readings and picks it the same way every time. A
596 # script that settles the order decides a lone word's field too
597 # (O5's W4 Except). The rules that DO decide such a name (H1, M4
598 # and N3's suffix clause; N3's bare shape returns before reaching
599 # here) run after this and retag (decisions/O5, #1111).
600 lone_field = (order[0] if resolved.by_script
601 else state.policy.lone_name_word)
602 roles = ([lone_field] if len(name_pieces) == 1
603 else _name_positions(order, len(name_pieces)))
604 for pos, piece_idx in enumerate(name_pieces):
605 _set_roles(tokens, pieces[piece_idx], roles[pos])
606 for piece_idx in suffix_pieces:
607 _set_roles(tokens, pieces[piece_idx], Role.SUFFIX)
608
609 # rules/O4: "a name word followed by nothing but initials reports
610 # the order" -- the positional read takes the word as the given
611 # name, where a byline writes its family name first (`Armitage J
612 # O`); declared nowhere, so the default given-first order picked it
613 # (decisions/O4, #1254). Bare capitals (`Armitage JO`) are no
614 # initials here: they are written as a short surname is (`Zhi LI`).
615 # Inline and nested so a plain name exits at its second piece
616 # (the parse-cost band, decisions/parse-cost). No test of the comma
617 # or the segment is needed: assign calls this for segment 0 under
618 # no comma or a suffix comma alone. Nor of a script's order: one
619 # needs the name written wholly in Han, Hangul or kana, which hold
620 # no initial (rules/T5) for the walk below to find (#1348 review).
621 order_report: PendingAmbiguity | None = None
622 if (len(name_pieces) >= 2 and order[0] is Role.GIVEN
623 and not state.policy.initials_as_family):
624 first = pieces[name_pieces[0]]
625 # a particle in front is PARTICLE_OR_GIVEN's fork, reported
626 # there; an initial in front is refused below by its one letter
627 initialed = (len(first) == 1
628 and "particle" not in tokens[first[0]].tags)
629 for k in name_pieces[1:]:
630 if not initialed:
631 break
632 piece = pieces[k]
633 letters = tokens[piece[0]]
634 # chunks of the composed spelling, as classify measures a
635 # letter (`composed_len`): a decomposed `É.S.` is one run;
636 # the shape tag is given only to letters (period_joined_vocab's
637 # alphabetic gate), so a chunk's length is the whole test
638 initialed = len(piece) == 1 and (
639 "initial" in letters.tags
640 or SHAPE_ACRONYM_TAG in letters.tags
641 and all(len(chunk) == 1
642 for chunk in unicodedata.normalize(
643 "NFC", letters.text).rstrip(".").split(".")))
644 text = unicodedata.normalize("NFC", tokens[first[0]].text)
645 # the word in front is a name word a byline could write first:
646 # no run of initials itself (rules/T7's `J.A.`), and in a script
647 # that writes initials, as no byline in Han or Hangul does
648 if (initialed and any(c.isalpha() for c in text)
649 and not all(len(chunk) == 1
650 for chunk in text.rstrip(".").split("."))
651 and not in_initialless_script(text)):
652 order_report = PendingAmbiguity(
653 AmbiguityKind.ORDER,
654 f"{tokens[first[0]].text!r} is the only name word before "
655 f"initials, which a byline writes after the family name "
656 f"and a South Asian name writes as the family; read as ",
657 tuple(first),
658 # rules/A1: "the order (O4), whose other reading lays out
659 # the whole name rather than moving one word" -- so the
660 # report names none and says it in words (decisions/O4)
661 field_tail=(" by the given-first order; read family "
662 "first (name_order=FAMILY_FIRST), the word in "
663 "front is the family name and the letters "
664 "the given and middle initials"))
665
666 def as_a_name(i: int) -> PendingReading:
667 # every other word read as the parse reads it -- the carve-out's
668 # name word too -- the name word the reading declines would be
669 # the last of one more than the name's; asked per report, so a
670 # name that makes no report here pays nothing
671 front = (pieces[name_pieces[-1]] if name_pieces
672 and i not in pieces[name_pieces[-1]] else None)
673 # rules/P5's other licence, a given-name title ahead, asked of
674 # the leading run through the predicate group's join asks, so
675 # the two cannot disagree about what one run asserts; asked
676 # only where the bound branch could take it, so a report per
677 # word of a long run never walks the name (the scaling test)
678 licensed = (front is not None and len(name_pieces) == 1
679 and "vocab:bound-given" in tokens[front[0]].tags
680 and _run_addresses_by_given(
681 (tokens[j].text for k in range(name_pieces[0])
682 for j in pieces[k]),
683 state.lexicon._sets.given_name_titles))
684 return _name_alt(tokens[i],
685 _slot_field(state, seg_idx, len(name_pieces),
686 len(name_pieces) + 1, order),
687 front, tokens, len(name_pieces) == 1, licensed)
688
689 for r in range(trailing_alts, len(ambiguities)):
690 report = ambiguities[r]
691 ambiguities[r] = copy_with(
692 report, alternative=as_a_name(report.indices[0]))
693 # rules/S8: "nor, in a name written wholly in one case, does a
694 # credential that is also a given name written short" -- the run
695 # declined where nothing in the writing settles it, so the reading
696 # not taken is the credential's run (decisions/S8, #1394). Each such
697 # word stands before any run `run_start` starts, the walk returning
698 # the first, so it is in the name core and holds a name role
699 for i in peeled.declined:
700 ambiguities.append(PendingAmbiguity(
701 AmbiguityKind.SUFFIX_OR_NAME,
702 f"{tokens[i].text!r} is a credential and a given name "
703 f"written short, in a name written in one case; read as ",
704 (i,), field_tail=" rather than the credential",
705 alternative=suffix_reading(tokens[i])))
706 # after the trailing reports are given their name reading, which
707 # the order report has none of
708 if order_report is not None:
709 ambiguities.append(order_report)
710 # Both emitters below turn on the PEEL's count, so neither can
711 # reach a name that kept two name pieces, and the two scans are
712 # nested under the count rather than run beside it: they cost the
713 # call budget on every parse otherwise (decisions/parse-cost).
714 if peeled.names <= 1:
715 head = pieces[name_pieces[0]]
716 # Both conventions here turn on a lone name word, so both
717 # report at the site that places one
718 # (mechanisms.md#AMBIGUITY-AT-THE-DECISION-SITE), and one
719 # predicate carries what says nothing else decided the FIELD:
720 # a title (segment 0's own peel, or one a family comma left in
721 # the next segment -- either is a Role.TITLE by now, and
722 # either makes the reading H1's), a maiden name (M4's), or a
723 # script order convention. `resolved.by_script` rather than a
724 # comparison against name_order: a declared family-first order
725 # agreeing with a Han name's entry is agreement, not
726 # authorship, and for a lone CJK honorific ('さん', '씨') it
727 # scopes W2's reading out rather than excusing it (#271/#308).
728 titled = any(t.role is Role.TITLE for t in tokens)
729 field_undecided = (
730 not resolved.by_script and not titled
731 and not any(t.role is Role.MAIDEN for t in tokens))
732 # rules/H4: "an input whose every word is post-nominal
733 # vocabulary reads its first word as a name and reports
734 # `suffix-or-name`" (history: decisions/H4) -- only the
735 # word made into a name reports, and no name piece survived
736 # the peel, so the carve-out above made the first post-nominal
737 # the name. Its field is worded by assemble from the final role
738 # (`PendingAmbiguity.field_tail`, #626).
739 if peeled.names == 0 and field_undecided:
740 text = " ".join(tokens[i].text for i in head)
741 ambiguities.append(PendingAmbiguity(
742 AmbiguityKind.SUFFIX_OR_NAME,
743 f"{text!r} is post-nominal vocabulary with no name word "
744 f"beside it; read as ", tuple(head),
745 field_tail=" rather than a post-nominal, nothing else "
746 "being left to be the name",
747 alternative=suffix_reading(tokens[head[0]])))
748 # One name piece off the peel: the convention placed a lone
749 # name word. A suffix beside it is not a decision -- 'Smith
750 # Jr.' IS this convention -- and the count comes off the peel
751 # rather than off name_pieces, which is what keeps the carve-out
752 # above out of these branches. Title vocabulary in the unit makes
753 # the doubt H4's or H7's (is the WORD a title), anything else
754 # O5's (which FIELD it took, or N3's where a nickname decides
755 # it), so only the second reads `field_undecided`: a title or a
756 # maiden name beside a lone title word is placed by H1 or M4
757 # whatever N3 does here, and a script order never reaches this
758 # branch (#1169).
759 if peeled.names == 1 and not resolved.by_script:
760 # rules/H4: "an input whose only remaining name word
761 # after the title peel is itself title vocabulary reads
762 # that word as the name by convention and reports
763 # `title-or-name`" (history: decisions/H4), and
764 # rules/H7: "one name UNIT of more than one word carrying
765 # title vocabulary reports `title-or-name`" (history:
766 # decisions/H7, decisions/H4 #518) -- one branch, its detail
767 # naming a field only in H7's shape ('John of Bishop',
768 # 'Attorney General of Minnesota'), where the unit is more
769 # than the title word.
770 # A LONE title word never reaches here ('Dr.', 'Prince of
771 # Wales'): the leading-title peel took the whole name.
772 if any("vocab:title" in tokens[i].tags for i in head):
773 text = " ".join(tokens[i].text for i in head)
774 lone = len(head) == 1
775 # rules/N3: "a name that is only a nickname and one name
776 # word reads that word as the family name, whatever
777 # suffix stands beside them" -- a title word left as
778 # that word too, its doubt (is it a title) still H4's
779 # report; the scan behind `state.extracted`, as at N3's
780 # other sites (decisions/N3, #1169)
781 # The word's own reading, as O5's clause below asks it:
782 # a title-particle ('St', 'Graf') or an initial keeps
783 # the reading it has, as N3's Except has it
784 if (lone and state.extracted
785 and tokens[head[0]].tags.isdisjoint(
786 _WORD_ALREADY_CLAIMED)
787 and any(t.role is Role.NICKNAME for t in tokens)):
788 _set_roles(tokens, head, Role.FAMILY)
789 ambiguities.append(PendingAmbiguity(
790 AmbiguityKind.TITLE_OR_NAME,
791 f"{text!r} is title vocabulary and the only name word "
792 f"the title peel left standing; read as the name by "
793 f"convention rather than as more title"
794 if lone else
795 f"{text!r} is the only name unit and joins title "
796 f"vocabulary to a name word; read as ",
797 tuple(head),
798 field_tail=None if lone else " by convention",
799 alternative=TITLE_READING))
800 # rules/O5: "a name of one name word that nothing else has
801 # decided reads that word as the field the caller's lone-word
802 # setting names" -- the report for that reading (history:
803 # decisions/O5, #449, #1111). Past
804 # `field_undecided`, two clauses of O5's own: the word's
805 # own reading may have claimed it, and A2's content test
806 # -- a piece with no alphanumeric character is no name
807 # word, so parse("(") keeps its unbalanced-delimiter
808 # report and gains nothing here.
809 elif (field_undecided
810 and all(tokens[i].tags.isdisjoint(_WORD_ALREADY_CLAIMED)
811 for i in head)
812 and any(c.isalnum() for i in head
813 for c in tokens[i].text)):
814 # rules/N3: "a name that is only a nickname and one name
815 # word reads that word as the family name, whatever
816 # suffix stands beside them" -- the suffixed shape the
817 # early count above declines, decided here, where the
818 # peel has set the suffix aside and O5's clauses have
819 # said nothing else decided the word (decisions/N3,
820 # #815). The early count's scan, behind
821 # `state.extracted` as at N3's bare site above (a
822 # nickname is only ever a clause extract), so a name
823 # with no clause pays no frame for it.
824 if state.extracted and any(t.role is Role.NICKNAME
825 for t in tokens):
826 _set_roles(tokens, head, Role.FAMILY)
827 else:
828 text = " ".join(tokens[i].text for i in head)
829 ambiguities.append(PendingAmbiguity(
830 AmbiguityKind.GIVEN_OR_FAMILY,
831 f"{text!r} is the only name word and nothing else "
832 f"decides it; read as ", tuple(head),
833 field_tail=" by convention, the field "
834 "Policy.lone_name_word names",
835 # the other primary field, named from the final
836 # role by assemble
837 alternative=PendingReading(ReadingKind.NAME,
838 ReadingSource.POSITION,
839 Deferred.OTHER_PRIMARY)))
840 # rules/S10: "a one-letter numeral before a credential is the
841 # family name, and the reading is reported" -- the part's last name
842 # word with nothing but the trailing run behind it (#721, Derek:
843 # 'John Smith V PhD' keeps family 'V' and reports, as 'john i, phd'
844 # does). Decided here, where the trailing read has said what that
845 # run is
846 # `_ROMAN` first, C-level, so an ordinary name word pays no frame
847 if (len(name_pieces) >= 2
848 and len(last := pieces[name_pieces[-1]]) == 1
849 and _ROMAN.match((word := tokens[last[0]].text).rstrip("."))
850 is not None
851 # the trailing run, or the Ph./D. pair, which the walk
852 # leaves out, behind it
853 and (suffix_pieces or titled_tail
854 or name_pieces[-1] + 1 < len(pieces)
855 and "suffix" in ptags[name_pieces[-1] + 1])
856 and tuple(last) not in peeled.picks
857 and reads_as_a_reported_numeral(
858 word, tokens[last[0]].tags,
859 tokens[pieces[name_pieces[-2]][0]].text, state.one_case)):
860 ambiguities.append(PendingAmbiguity(
861 AmbiguityKind.SUFFIX_OR_NAME,
862 f"{word!r} is a roman numeral, but a post-nominal or title "
863 f"follows it; read as ", tuple(last),
864 field_tail=" rather than a generational suffix",
865 alternative=suffix_reading(tokens[last[0]])))
866 for piece in peeled.picks:
867 # every pick is in rest, so the loops above just gave it a
868 # role; whether it was read as a suffix or a name settles what
869 # it was declined as, and which field assemble names (#626)
870 token = tokens[piece[0]]
871 assert token.role is not None
872 # rules/S10: "either reading is reported" -- the numeral fork's
873 # declined pick (#718), which carries neither credential tag
874 # (the acronym fork's picks carry one) and is never a suffix
875 if token.tags.isdisjoint(_AMBIGUOUS_CREDENTIAL_TAGS):
876 # a pick a credential run in front then took is the run's
877 # absorbed name word (rules/S8); otherwise it is declined
878 # for want of words to spare (one letter) or for its Title
879 # case (two or more, rules/S10's lean)
880 if token.role is Role.SUFFIX:
881 ambiguities.append(_absorbed(piece, tokens,
882 as_a_name(piece[0])))
883 continue
884 why = ("is a roman numeral, but the name has no other word "
885 "to spare for it" if len(token.text.rstrip(".")) == 1
886 else "is a roman numeral written in Title case, which "
887 "leans to the name")
888 ambiguities.append(PendingAmbiguity(
889 AmbiguityKind.SUFFIX_OR_NAME,
890 f"{token.text!r} {why}; read as ", piece,
891 field_tail=" rather than a generational suffix",
892 alternative=suffix_reading(token)))
893 continue
894 declined = ("a name part" if token.role is Role.SUFFIX
895 else "a post-nominal")
896 # rules/S9: "An unlisted word joins the ambiguous class (S4) by
897 # SHAPE" (and rules/S3); such a word is in no
898 # wordlist and may be written with its periods, so the listed
899 # member's wording would misdescribe it on both counts (#563)
900 what = ("is shaped like a post-nominal but listed in no "
901 "vocabulary, so it may be an ordinary name"
902 if SHAPE_ACRONYM_TAG in token.tags
903 else "written without periods is both a post-nominal "
904 "and an ordinary name")
905 ambiguities.append(PendingAmbiguity(
906 AmbiguityKind.SUFFIX_OR_NAME,
907 f"{token.text!r} {what}; read as ", piece,
908 field_tail=f" rather than {declined}",
909 alternative=(as_a_name(piece[0])
910 if token.role is Role.SUFFIX
911 else suffix_reading(token))))
912 # leading ambiguous particle read as a name (#121 surfaced)
913 if name_pieces:
914 head = pieces[name_pieces[0]]
915 # rules/P11: "an ambiguous particle written in lower case, in a
916 # name of mixed case, opens the name as a never-given one does"
917 # -- and "nothing is reported" there, the writing having settled
918 # the fork (decisions/P11, #670)
919 if (len(head) == 1 and len(name_pieces) > 1
920 and "vocab:particle-ambiguous" in tokens[head[0]].tags
921 and not (order is not None and order[0] is Role.FAMILY
922 and is_lowercase_ambiguous_particle(
923 head, tokens, state.one_case))):
924 # the field is assemble's to word from the final role
925 # (`PendingAmbiguity.field_tail`, #626), never assumed given:
926 # `order` above is _effective_order's answer, not
927 # necessarily name_order's, and a later rule may still move
928 # the word ('Van Ivan Petrovich' under the East Slavic rule
929 # rotates 'Van' into the family)
930 ambiguities.append(PendingAmbiguity(
931 AmbiguityKind.PARTICLE_OR_GIVEN,
932 f"leading {tokens[head[0]].text!r} may be a family-name "
933 f"particle; read as ", tuple(head), field_tail="",
934 alternative=particle_reading(tokens[head[0]].tags)))
935 return order
936
937
938def _names_before(fam_pieces: Sequence[Sequence[int]],
939 tokens: Sequence[WorkToken], lead: int, k: int) -> int:
940 """How many name words stand in front of the numeral at
941 `fam_pieces[k]`, the title run's `lead` pieces left out: the pieces
942 that are not wholly linking words (`_is_linking_word`)."""
943 # rules/S10: "a particle or a connective is no name word there,
944 # wherever it stands in the part" -- the count of the family part's
945 # numeral site; a chain or join holding a name word is one piece and
946 # counts (decisions/P9 (#1080), decisions/S10 (#1093))
947 return sum(1 for j in range(lead, k)
948 if not all(_is_linking_word(tokens[t].tags, j == k - 1)
949 for t in fam_pieces[j]))
950
951
952def _is_linking_word(tags: Set[str], beside: bool) -> bool:
953 """Whether a word of the family part is a linking word, which the
954 numeral's count leaves out: a particle, or a connective, save one
955 that is also suffix vocabulary standing `beside` the numeral."""
956 # rules/S10: "A connective that is also suffix vocabulary, as the
957 # generational 'i' is, stays in the count where P13 has not linked
958 # the letter" -- the exception's half of this predicate
959 # (decisions/P13 (#1097))
960 return "particle" in tags or ("conjunction" in tags and not (
961 beside and "vocab:suffix" in tags))
962
963
964def _family_part_numeral(word: WorkToken, preceding: str, names: int,
965 one_case: bool | None) -> Role | None:
966 """The role of a roman numeral ending the family part before a
967 family comma, behind `names` name words of that part (`_names_before`,
968 which leaves its linking words out), as the comma-less name reads one
969 ending it (rules/S10), or None where the numeral's
970 predicate reads no numeral there (an initial in front, a letter with
971 its period): the suffix where it reads as the generation, a
972 one-letter numeral needing two name words in front of it, save one
973 its written case settles (T4), and the family name where that count
974 fails or its Title case leans to the name."""
975 if reads_as_generation(word.text, word.tags, preceding, one_case):
976 if (names < 2 and len(word.text) == 1
977 and not numeral_settled_by_case(word.text, one_case)):
978 return Role.FAMILY
979 return Role.SUFFIX
980 if numeral_leans_to_the_name(word.text, word.tags, preceding, one_case):
981 return Role.FAMILY
982 return None
983
984
985def _reads_as_a_trailing_suffix(piece: Sequence[int],
986 prev_piece: Sequence[int],
987 prev_ptags: Set[str],
988 tokens: Sequence[WorkToken],
989 lexicon: Lexicon,
990 one_case: bool | None) -> bool:
991 """The lenient tail test for a trailing one-token piece after a
992 family comma, and #432's carve-out from it.
993
994 A word that could be a middle initial, written with the period that
995 marks an abbreviation, is name material -- so 'Smith, John V.' is
996 middle 'V.' where 'Smith, John V' stays suffix 'V' (v1 parity,
997 #144). Only behind a NAME word: behind a suffix the credential run
998 owns it, and 'Smith, John PhD I.' keeps suffix 'PhD I.'.
999
1000 The period is the whole carve-out. is_initial_shaped would be
1001 redundant beside it: the caller only consults this where
1002 is_suffix_piece said no, and a lenient single token it refuses is
1003 one carrying the `initial` tag, so the shape is already implied.
1004
1005 reads_as_generation is asked with no word in front (`preceding`
1006 None): its initial-in-front refusal is a no-comma rule and the
1007 opposite of this path's v1 parity -- 'Chang, Andy C I' is first
1008 Andy, middle C, suffix I, and asking it with the word in front
1009 made the numeral a middle. The #401/#421 entry
1010 under decisions/P5 records the same fork declining to transfer
1011 to this walk under LENIENT.
1012 """
1013 # rules/C9: "behind a name word it is the generation only when
1014 # written bare, a period marking it the abbreviation of a name and
1015 # so a middle initial"
1016 tok = tokens[piece[0]]
1017 text = tok.text
1018 if text.endswith(".") and not is_suffix_piece(
1019 prev_piece, prev_ptags, tokens):
1020 return False
1021 # the numeral's predicate, which in this slot reads a bare
1022 # one-letter numeral by the vocabulary ('Smith, John X' keeps
1023 # middle 'X'); `_ROMAN` first, C-level
1024 if len(text) == 1 and _ROMAN.match(text) is not None:
1025 return reads_as_generation(text, tok.tags, None, one_case)
1026 return is_suffix_lenient(text, lexicon)
1027
1028
1029def _inside_a_credential_run(seg: Sequence[Sequence[int]],
1030 tokens: list[WorkToken], given_at: int,
1031 k: int, end: int,
1032 ambiguities: list[PendingAmbiguity]) -> bool:
1033 """rules/P9 (P6's third exception) for the run `seg[k:end]`: a
1034 run assign read as post-nominals, with a credential read in
1035 front of it and another behind, stands INSIDE the credential run
1036 assign read whole rather than ending the name, so it keeps that
1037 reading -- 'DOE, JANE PHD VD MA' reads suffix 'PHD VD MA' where the
1038 attachment had pulled VD out of the middle of it (#573). Behind as
1039 well as in front: with nothing behind it the word ends the name,
1040 and 'Doe, Jane PhD vd' keeps family 'vd Doe'. A title between it
1041 and the post-nominal in front is transparent, as it is to every
1042 trailing reading (H5): 'DOE, JANE PHD PROF. VD MA' reads as 'DOE,
1043 JANE PHD VD MA' does. The run is never empty: the caller asks
1044 only where `k < end`, and over an empty range the test below would
1045 pass vacuously and report a fork on the word behind (#613's
1046 review, ', Jane PhD do MA'). (Behind it no title is skipped: a title
1047 there leaves the word a name in assign, so nothing reaches here.)
1048
1049 The test is the ROLES assign gave, not S7's company query: the
1050 question is whether assign read the run whole, and a member in
1051 front that the writing or a count made the credential ('DOE, JANE
1052 MA VD PHD') says so as plainly as a degree does. So does a
1053 generation, in front or behind ('Berg, Jan PhD vd Jr.'): the
1054 tussenvoegsel P6 is about stands right behind the given name, and
1055 a post-nominal between them says this word is not one. The run's own
1056 role is what keeps a plain particle out ('Doe, Jane PhD de PhD',
1057 whose 'de' is a name word, not a post-nominal), and the given
1058 name in front is what keeps 'Doe, Jane vd PhD' attaching.
1059 Reported as S4's credential fork, at the site that declines the
1060 attachment."""
1061 def suffix_read(q: int) -> bool:
1062 return all(tokens[i].role is Role.SUFFIX for i in seg[q])
1063
1064 def is_title(q: int) -> bool:
1065 return all(tokens[i].role is Role.TITLE for i in seg[q])
1066
1067 if not all(suffix_read(q) for q in range(k, end)):
1068 return False
1069 front = k - 1
1070 while front > given_at and is_title(front):
1071 front -= 1
1072 if (front <= given_at or end == len(seg)
1073 or not suffix_read(front) or not suffix_read(end)):
1074 return False
1075 run = seg[k]
1076 text = " ".join(tokens[i].text for i in run)
1077 ambiguities.append(PendingAmbiguity(
1078 AmbiguityKind.SUFFIX_OR_NAME,
1079 f"{text!r} written without periods is both a post-nominal and a "
1080 f"family-name particle; between credentials after a family "
1081 f"comma it reads as a post-nominal",
1082 tuple(run), alternative=particle_reading(tokens[run[0]].tags)))
1083 return True
1084
1085
1086def _attach_particle_tail(pieces: Sequence[Sequence[int]],
1087 tokens: list[WorkToken], given_at: int,
1088 k: int, end: int,
1089 ambiguities: list[PendingAmbiguity]) -> None:
1090 """rules/P6's attachment after a family comma: the particle run
1091 `pieces[k:end]` ending the given part joins the family the comma
1092 named and is written before it -- the Dutch alphabetized listing,
1093 "Beethoven, Ludwig van" being how "Ludwig van Beethoven" is filed.
1094 The caller has found the run (`particle_tail`) and checked that a
1095 given word stands ahead of it and that P1's fold will not take the
1096 part; this declines only where the run stands inside a credential
1097 run the walk read whole (`_inside_a_credential_run`, the third
1098 exception).
1099
1100 Keyed on the tokens' VOCABULARY, not their roles, which is what
1101 gives the attachment its stated precedence over S2: `vd`, `mc` and
1102 `do` are the three words in both vocabularies; the walk reads a
1103 trailing `vd` or `mc` as a post-nominal, so those two need the
1104 override, and `do` is in the AMBIGUOUS acronym half, which already
1105 leaves it a name word, so it attaches by the plain rule. After a
1106 family comma the tussenvoegsel is the commoner reading.
1107
1108 The words-to-spare guard is a piece test, not a count: every
1109 trailing piece that is wholly particles attaches, and the run must
1110 leave a GIVEN word ahead of it, so "Nguyen, Van" keeps its only
1111 given word. Only the DEGENERATE Vietnamese listing is protected by
1112 that -- "Nguyen, Thi Van" has a given word to spare, so `Van`
1113 attaches and the given name is lost. rules/P6 records why that
1114 is accepted.
1115
1116 mechanisms.md#FOLDED_TAG does the rest: tokens never move, so the
1117 family view reads the tag and renders these before the base.
1118
1119 Decided in assign since #613, in the pass that read the given
1120 part; until then post_rules took it a stage later, and assign held
1121 the tail back from #602's run by predicting it."""
1122 if _inside_a_credential_run(pieces, tokens, given_at, k, end,
1123 ambiguities):
1124 return
1125 run = [i for piece in pieces[k:end] for i in piece]
1126 # mechanisms.md#AMBIGUITY-AT-THE-DECISION-SITE: "Emit at
1127 # the site that takes the branch, not where an ambiguous
1128 # tag sits" -- this attachment is where the fork is
1129 # decided, so the report is raised here, at the attachment,
1130 # rather than by the given-part walk's own emitters, which
1131 # read the run before the attachment decides it (#405).
1132 #
1133 # Two arms, keyed on what the attachment OVERRODE rather
1134 # than on what the words are, so each names a branch the
1135 # parse actually weighed. `declined_suffix` reads the role
1136 # the walk gave the run, which is why both lists are built
1137 # BEFORE the re-roling loop below overwrites it.
1138 #
1139 # ORDERED, not asserted disjoint. The two cannot both hold
1140 # under the shipped vocabulary -- `vd` and `mc` are the
1141 # only words in both the particle and the unambiguous
1142 # suffix vocabularies, and neither is ambiguous particle
1143 # vocabulary -- but a caller's Lexicon may put one word in
1144 # both, and rules/A1 says parsing never fails on any
1145 # input, so this decides instead of raising. (Measured: an
1146 # assert here DID fire on `Berg, Jan zz` under a Lexicon
1147 # adding `zz` to particles_ambiguous and suffix_acronyms.)
1148 # The suffix arm wins because it names the reading the
1149 # parse actually took: assign had read the word as a
1150 # post-nominal, so the name-word reading was never on the
1151 # table for the attachment to decline.
1152 #
1153 # Both details name the ATTACHMENT and stop there. What
1154 # P6 decides is that the run joins the family the comma
1155 # named instead of standing on its own; how the joined
1156 # words then READ is R2's call, taken by the UNJOINED_TAG
1157 # loop at the end of post_rules. The two can disagree:
1158 # `de la, Jan van` attaches `van` and leaves an
1159 # all-particle family, which R2 marks, so every other view
1160 # -- `family_base`, the initials, case repair -- reads
1161 # those words as ordinary name words ('Jan Van De La'
1162 # forced). A detail promising "read as the family's
1163 # particle" would contradict all three.
1164 ambiguous = [i for i in run
1165 if "vocab:particle-ambiguous" in tokens[i].tags]
1166 declined_suffix = [i for i in run
1167 if tokens[i].role is Role.SUFFIX]
1168 text = " ".join(tokens[i].text for i in run)
1169 if declined_suffix:
1170 ambiguities.append(PendingAmbiguity(
1171 AmbiguityKind.SUFFIX_OR_NAME,
1172 f"{text!r} written without periods is both a "
1173 f"post-nominal and a family-name particle; after a "
1174 f"family comma it joins the family the comma named "
1175 f"rather than standing as a post-nominal",
1176 tuple(run), alternative=suffix_reading(tokens[run[0]])))
1177 elif ambiguous:
1178 word = tokens[ambiguous[0]].text
1179 walked = tokens[run[0]].role
1180 assert walked is not None # the given part's walk roled the run
1181 ambiguities.append(PendingAmbiguity(
1182 AmbiguityKind.PARTICLE_OR_GIVEN,
1183 f"{word!r} is both a family-name particle and an "
1184 f"ordinary given name; after a family comma "
1185 f"{text!r} joins the family the comma named "
1186 f"rather than standing as a name word of its own",
1187 tuple(run),
1188 # where the given part's walk placed it, before this moves
1189 # it: a name word, or a title the walk read off its period
1190 # ('Doe, Jane nee Smith St.'); a name word is taken in by
1191 # the piece in front where that piece would take it
1192 alternative=(TITLE_READING if tokens[run[0]].role is Role.TITLE
1193 else _name_alt(
1194 tokens[ambiguous[0]],
1195 walked,
1196 pieces[k - 1] if k - 1 >= given_at
1197 and tokens[pieces[k - 1][0]].role in NAME_ROLES
1198 else None,
1199 tokens, k - 1 == given_at, True))))
1200 for i in run:
1201 tokens[i] = copy_with(
1202 tokens[i], role=Role.FAMILY,
1203 tags=tokens[i].tags | {FOLDED_TAG, ATTACHED_TAG})
1204
1205
1206def _split_name_alt(state: ParseState, tokens: Sequence[WorkToken],
1207 seg_idx: int, piece: Sequence[int],
1208 order: tuple[Role, Role, Role] | None) -> PendingReading:
1209 """The name reading of a split credential assign placed, every
1210 other word read as the parse read it: the family before a family
1211 comma, the given part's given or middle name after one, and
1212 otherwise the last of the part's name words -- or wherever the name
1213 piece in front of it would take it in (`_name_alt`)."""
1214 names = [q for q in _name_pieces(state, tokens, seg_idx)
1215 if q[0] < piece[0]]
1216 role = _slot_field(state, seg_idx, len(names), len(names) + 1, order)
1217 return _name_alt(tokens[piece[0]], role, names[-1] if names else None,
1218 tokens, len(names) == 1,
1219 state.structure is Structure.FAMILY_COMMA)
1220
1221
1222def _resolve_deferred(state: ParseState, tokens: Sequence[WorkToken],
1223 ambiguities: list[PendingAmbiguity],
1224 order: tuple[Role, Role, Role] | None) -> None:
1225 """Name the field of each alternative classify or group deferred,
1226 from the positions just read: a connective's join takes in the name
1227 word on each side, so where those stand in two pieces the joined
1228 unit takes the place of the first, and where both are inside the
1229 letter's own piece, or the join would leave the name one word, the
1230 letter keeps its own field (named at assemble); a chained particle
1231 stands as a name word of its own in front of its piece, one more
1232 unit. Every other word keeps its reading, so the field is
1233 the one the positional read gives that place: the family before a
1234 family comma, the given part's given or middle name after one, and
1235 the declared order's otherwise. A referent outside every name
1236 position is left deferred, and surfaces as no alternative."""
1237 for r, report in enumerate(ambiguities):
1238 alt = report.alternative
1239 if (alt is None or alt.role not in (Deferred.JOINED,
1240 Deferred.UNCHAINED)
1241 or not report.indices):
1242 continue
1243 i = report.indices[0]
1244 for seg_idx in range(len(state.pieces)):
1245 names = _name_pieces(state, tokens, seg_idx)
1246 at = next((k for k, q in enumerate(names) if i in q), None)
1247 if at is not None:
1248 break
1249 else:
1250 continue
1251 if alt.role is Deferred.UNCHAINED:
1252 pos, count = at, len(names) + 1
1253 else:
1254 # the join takes in the name word on each side: a word of
1255 # the connective's own piece, or the piece beside it. One
1256 # inside its piece joins nothing the piece did not hold, so
1257 # it lands where its piece lands; one opening or ending the
1258 # name has no word to join on that side, and no field
1259 piece = names[at]
1260 k = piece.index(i)
1261 first = at - 1 if k == 0 else at
1262 last = at + 1 if k == len(piece) - 1 else at
1263 if first < 0 or last >= len(names):
1264 continue
1265 pos, count = first, len(names) - (last - first)
1266 # rules/P3: "a single-letter connective in a three-word name"
1267 # stays a name word, so a join that would leave the name one
1268 # word is no join, and the letter keeps its own field; a
1269 # family comma's surname is a word of the name the given
1270 # part's count does not see
1271 if first == last or (
1272 count == 1
1273 and state.structure is not Structure.FAMILY_COMMA):
1274 ambiguities[r] = copy_with(report, alternative=copy_with(
1275 alt, role=Beside(i)))
1276 continue
1277 ambiguities[r] = copy_with(report, alternative=copy_with(
1278 alt, role=_slot_field(state, seg_idx, pos, count, order)))
1279
1280
1281def assign(state: ParseState) -> ParseState:
1282 tokens = list(state.tokens)
1283 ambiguities = list(state.ambiguities)
1284 if not state.segments:
1285 return state
1286 order: tuple[Role, Role, Role] | None = None
1287 if state.structure is Structure.NO_COMMA:
1288 order = _assign_main(0, state, tokens, ambiguities)
1289 tail = len(state.segments)
1290 elif state.structure is Structure.SUFFIX_COMMA:
1291 order = _assign_main(0, state, tokens, ambiguities)
1292 tail = 1
1293 else: # FAMILY_COMMA
1294 # PARTICLE_OR_GIVEN is deliberately not emitted on the
1295 # wholly-family read: after a comma that fixed the family, a
1296 # leading given-position particle is not meaningfully
1297 # ambiguous, and script_orders is not consulted for the parallel
1298 # reason. Scoped, not silent: the comma fixed WHICH PIECE is the
1299 # family and said nothing about a particle trailing the given
1300 # name, so P6's attachment after the given-part walk below
1301 # decides that fork and reports it there, at the site that
1302 # takes the branch (#405). Behind a whole name, a comma followed
1303 # by no name word is not this path since #613: `_comma.decide`
1304 # makes it the suffix comma, read positionally by the branch
1305 # above, which emits and consults both as the comma-less name
1306 # does -- and group's chain emitter with them, the comma being
1307 # decided before the chain runs. Behind one name word it is
1308 # this path, with segment 1 already bound ('Smith, Jr.').
1309 # v1: "lastname part may have suffixes in it" -- the first
1310 # piece is always the family even if suffix-shaped; any later
1311 # strict-suffix piece goes to SUFFIX per piece ('Smith Jr.,
1312 # John' -> family=Smith, suffix=Jr.)
1313 fam_pieces = state.pieces[0]
1314 fam_tags = state.piece_tags[0]
1315 # The part after the comma reaches here as the given part, or
1316 # bound and with no pieces left: group's `_comma.decide` binds a
1317 # postnominal one before any join (#613, rules/C7), so this
1318 # path is the listing form's, and the positional read #296 gave
1319 # a comma followed by no name word behind two name words is
1320 # decide's suffix comma now, read by the NO_COMMA branch above.
1321 # rules/C11's report, scoped to the ambiguous credential
1322 # class: this is the given-name half of the comma's OWN
1323 # decision (listing or credential run), where the writing left
1324 # the fork open. `_comma.decide` reports the credential half,
1325 # where it binds the part, and P6's attachment fork reports
1326 # from `_attach_particle_tail` above ("Berg, Jan vd") -- a
1327 # different fork. Each half is reported where its branch is
1328 # taken, so this DECISION is never reported twice; a second ambiguous
1329 # token elsewhere in the name is a second fork and reports on
1330 # its own (#289, mechanisms.md#AMBIGUITY-AT-THE-DECISION-SITE).
1331 #
1332 # The report tracks the FORK BEING CONSULTED, not the lean --
1333 # exactly as the trailing slot has always done (`Jack MA`
1334 # reported before #289 too, even where the pick was declined
1335 # for want of words to spare). So membership alone gates it:
1336 # a caseless script or an all-lower spelling still called this
1337 # fork and read it positionally.
1338 #
1339 # The gate reads EITHER tag (`_AMBIGUOUS_CREDENTIAL_TAGS`, the
1340 # same pair `_group`'s chain emitter asks), and the shape one
1341 # is what reaches a by-shape member -- under EITHER 2.4
1342 # switch, the dotted and the caps alike, since classify writes
1343 # it from both branches. It reaches one with the dotted switch
1344 # OFF as well: classify writes the shape tag whether or not
1345 # the switch admits the token to the class, which is what lets
1346 # a declined fork be REPORTED without being taken ('Smith,
1347 # A.B.' under `unlisted_dotted_suffixes=False` reports and
1348 # keeps its given). An earlier wording said the class reaches
1349 # a by-shape member "once `Policy.unlisted_dotted_suffixes`
1350 # admits it", which is true of the CLASS and false of this
1351 # report.
1352 #
1353 # Read off the FIRST post-comma piece only -- on this path it
1354 # is the given name, `_comma.decide` having read the part and
1355 # found a name word in it, and it is the one piece the lean
1356 # can reach at one word before the comma. So `"Smith, MA PhD"` reports ONCE, for 'MA' alone:
1357 # 'PhD' is settled vocabulary and carries neither tag, and
1358 # even a second CLASS member there would not be read here
1359 # (test_assign.py asserts the count).
1360 #
1361 # The #531 emitter at the far end of this branch counts
1362 # differently, and the difference is the slot rather than a
1363 # second policy: it reports once per member of the trailing
1364 # run it reads, so 'Doe, John MA JD' reports TWICE, matching
1365 # the comma-less 'John Smith MA JD'. A member the writing
1366 # keeps as a name stops that run, which is why
1367 # 'Doe, John MA Ma' reports once and for 'Ma' alone -- 'MA'
1368 # then has a name word behind it and is never asked
1369 # (rules/S5).
1370 if state.pieces[1] and len(state.pieces[1][0]) == 1:
1371 i = state.pieces[1][0][0]
1372 if not tokens[i].tags.isdisjoint(_AMBIGUOUS_CREDENTIAL_TAGS):
1373 # the field is assemble's to word: with nothing before
1374 # the comma and a title after the word, H1 moves it to
1375 # the family (', Ma Dr.', #626's review)
1376 ambiguities.append(PendingAmbiguity(
1377 AmbiguityKind.SUFFIX_OR_NAME,
1378 f"{tokens[i].text!r} after the comma is also an "
1379 f"ordinary name word; read as ", (i,), field_tail="",
1380 # the comma's other branch: the part a credential run
1381 alternative=suffix_reading(tokens[i])))
1382 # Segment 1 is read before segment 0's family pass. It
1383 # consumes piece tags and text only -- nothing segment 0's
1384 # read writes. (A title standing after the comma behind a whole
1385 # name, 'John V, Dr.', is bound at group's head since #613 and
1386 # never reaches this path.)
1387 if len(state.segments) > 1:
1388 pieces = state.pieces[1]
1389 ptags = state.piece_tags[1]
1390 # Both are the walk's, filled once the title run is found.
1391 titled_idx: frozenset[int] = frozenset()
1392 walkable: frozenset[int] = frozenset()
1393 #: Where the trailing suffix run starts, for the #531
1394 #: report below: `trailing_floor`'s answer, read once on
1395 #: the first member the loop meets and -1 until then (no
1396 #: piece index can be negative, and the loop's own floor is
1397 #: n + 1). Once is enough for the same reason one number is
1398 #: enough inside that walk: the question is MONOTONE, the
1399 #: loop below ascends, and a later member can only ask for
1400 #: LESS of the walk than the first one did.
1401 run_floor = -1
1402
1403 def previous_kept(m: int, titled: frozenset[int]) -> int:
1404 """The piece before `m` that the H5 chain did NOT
1405 take. Both readings this segment needs are that one:
1406 the piece the lenient tail test measures against, and
1407 -- asked of one past the end -- where the segment's
1408 name ENDS, since a title the chain took is not where a
1409 name ends (#144). One walk for both, so 'as if the
1410 titled pieces were absent' cannot come to mean two
1411 things.
1412
1413 DEFENSIVE, and measured inert: over 191,146 generated
1414 inputs the skip fired on 153 of the 140,227 walks the
1415 lenient test's `prev` asked for, and deleting it
1416 changed no parse among them (2026-09-09, on the shape
1417 this replaced, where the name's END walked past the
1418 same pieces in a copy of this loop). Kept because "as
1419 if the titled pieces were absent" is the rule the
1420 predicate below implements, and a caller's vocabulary
1421 reaches shapes the sweep's word list does not -- an
1422 inert branch is cheaper than a rule with a hole in it.
1423 """
1424 m -= 1
1425 while m in titled:
1426 m -= 1
1427 return m
1428
1429 #: State of the #531 walk below, per `titled` value: how
1430 #: far down the trailing suffix run has been walked, and
1431 #: whether that walk has SETTLED (it stopped on a piece
1432 #: that refuses, so no lower piece can end the given part
1433 #: either and the refusal is never re-asked).
1434 #:
1435 #: The key carries `titled` for the same reason the
1436 #: predicate takes it as a parameter: the two passes ask
1437 #: about the same pieces with different ones spliced out.
1438 #: It CANNOT go stale. Everything the recorded verdict
1439 #: rests on is tags and text -- `is_suffix_piece` reads
1440 #: ptags and token tags, `_reads_as_a_trailing_suffix`
1441 #: reads text plus `is_suffix_piece`, `listed_lean` reads
1442 #: tags, text and `state.one_case` -- and none of them
1443 #: reads `.role`, verified by reading all three
1444 #: (2026-09-19). The one thing this segment's code rewrites
1445 #: between the two passes is the role, through `_set_roles`,
1446 #: which is a `copy_with(role=...)` and leaves
1447 #: text and tags identical.
1448 floors: dict[frozenset[int], tuple[int, bool]] = {}
1449 #: #544's anchors, per `titled` value like `floors` and for
1450 #: the same reason: `given_slot_anchors` over the pieces the
1451 #: chain kept, computed once, the first time a member's own
1452 #: writing declines, so a run of members is read in one
1453 #: forward pass rather than one look-behind per member.
1454 anchor_memo: dict[frozenset[int], list[bool]] = {}
1455
1456 def anchored(m: int, titled: frozenset[int]) -> bool:
1457 memo = anchor_memo.get(titled)
1458 if memo is None:
1459 # nothing in front the pass could read as an
1460 # anchor: the ordinary 'Smith, John Ma' stops here.
1461 # Asked only before the pass exists -- once it
1462 # does it answers in one lookup, where the reach
1463 # test walks back through the run
1464 if not anchor_in_reach(range(m - 1, -1, -1), pieces,
1465 ptags, tokens, titled):
1466 return False
1467 # from past the leading title run, which `n` already
1468 # counts: this closure is reached only from the walk
1469 # below `_peel_leading_titles` sets it on
1470 memo = given_slot_anchors(pieces, ptags, tokens, n,
1471 skip=titled)
1472 anchor_memo[titled] = memo
1473 return memo[m]
1474
1475 def trailing_floor(m: int, titled: frozenset[int]) -> int:
1476 """Where the trailing suffix run starts, walked as far
1477 down as `m` needs it: `m >= trailing_floor(m, titled)`
1478 is exactly "every kept piece behind `m` reads as a
1479 suffix", which is what ENDING the given part means
1480 (rules/S5, #531).
1481
1482 ONE walk per `titled` value, shared by the predicate
1483 below and by that rule's report at the foot of this
1484 segment, and the reason both are LINEAR in the run's
1485 length. The question is MONOTONE -- a piece ends the
1486 given part whenever the piece behind it does -- so a
1487 single descent answers for every member, each piece
1488 read at most once. Asked member by member instead, the
1489 reading is recursive (a member ends the given part iff
1490 everything kept behind it reads as a suffix, and a
1491 piece behind it is a member asking the same of its own
1492 tail): a walk per member, which cost O(run**2) with the
1493 per-member memo this replaced and 2**run without one.
1494 Measured on `'Doe, John ' + 'MA '*k`, k doubling from
1495 200: 2.1/4.1/8.3/17.1ms here, against 8.6/31.4/120/463
1496 with the memo and 1.5/3.2/7.2/17.3 at cc78c960, where
1497 no such walk existed at all (2026-09-19).
1498
1499 `low` descends only to `m`, so what comes back is a
1500 floor FOR `m` rather than the run's own first piece
1501 whenever the run reaches past it; that is all either
1502 caller asks, and stopping there is what keeps the
1503 member's own frame count where it was. `final` carries
1504 the other half: a piece that refuses settles the floor
1505 for everything in front of it.
1506
1507 Re-entrant by construction, and it has to be: the
1508 descent asks the predicate below about a piece that is
1509 itself often a member, which asks this back. `floors`
1510 names the piece under test BEFORE that call, so the
1511 re-entrant reading is "this piece ends the given part",
1512 which is what the descent has just established of it.
1513 """
1514 entry = floors.get(titled)
1515 if entry is None:
1516 # previous_kept() of one past the end, spelled out
1517 # here rather than called: the frame budget again,
1518 # this walk being asked of every family-comma name
1519 # with a member in the given part, and the skip is
1520 # two lines. Keep the two in step.
1521 low = len(pieces) - 1
1522 while low in titled:
1523 low -= 1
1524 entry = (low, False)
1525 floors[titled] = entry
1526 low, final = entry
1527 while not final and low > m:
1528 if reads_as_a_suffix(low, titled):
1529 low -= 1
1530 while low in titled:
1531 low -= 1
1532 else:
1533 final = True
1534 floors[titled] = (low, final)
1535 return low
1536
1537 #: where the particle run opening the given part ends,
1538 #: per `titled` value -- `attaches_the_lead`'s one walk
1539 lead_run_ends: dict[frozenset[int], int] = {}
1540
1541 def attaches_the_lead(m: int, titled: frozenset[int]) -> bool:
1542 """Is piece `m` the name word a never-given particle
1543 opening the given part attaches to? post_rules' P1
1544 fold takes such a particle forward into the family and
1545 needs a name word for it to attach to, so the given
1546 name the #531 slot below counts on is not there, and
1547 the first word past the particle run is the surname it
1548 heads rather than a word to spare ('SMITH, VD MA'
1549 reads as 'Smith, vd Ma' does, #573). Only where the
1550 member's writing says nothing: capitals in a mixed-case
1551 name still make it the credential ('Smith, de MA'
1552 keeps suffix 'MA'), as they do with no words to spare
1553 anywhere (rules/S5). Asked only of a class member
1554 the slot would otherwise take."""
1555 if not is_lone_never_given_particle(pieces[n], tokens):
1556 return False
1557 if listed_lean(tokens[pieces[m][0]],
1558 state.one_case) == "credential":
1559 return False
1560 # The member is the particle run's word when it is the
1561 # first kept piece past that run. Where the run ends is
1562 # one answer per `titled` value, walked once and kept,
1563 # so a run of members costs one walk rather than one
1564 # each (the second review measured the per-member scan
1565 # quadratic on 'SMITH, VD ' + 'DE '*k + 'MA '*k). Every
1566 # token, not the piece's tags: a chain of particles
1567 # ('DE LA') is one piece whose tags say nothing of it
1568 # ('SMITH, VD DE LA MA').
1569 run_end = lead_run_ends.get(titled)
1570 if run_end is None:
1571 run_end = n + 1
1572 while run_end < len(pieces) and (
1573 run_end in titled
1574 or all("particle" in tokens[i].tags
1575 for i in pieces[run_end])):
1576 run_end += 1
1577 lead_run_ends[titled] = run_end
1578 return m <= run_end
1579
1580 def reads_as_a_suffix(m: int, titled: frozenset[int]) -> bool:
1581 """Does this segment's walk read piece `m` as a suffix?
1582
1583 Asked twice, and by one predicate rather than by two
1584 conditions written to match
1585 (mechanisms.md#ONE-PREDICATE-PER-QUESTION): once to
1586 find the pieces the H5 title chain must not reach
1587 past, and once by the walk order below, which is the
1588 site that places them.
1589
1590 `titled` is a PARAMETER because the two passes hand it
1591 different values -- an empty set on the first, the
1592 chain's own pieces on the second, which is what makes
1593 that second reading the one 'as if the titled pieces
1594 were absent'.
1595 A closure over the caller's local said the same thing,
1596 but only by WHEN it was rebound.
1597 """
1598 if is_suffix_piece(pieces[m], ptags[m], tokens):
1599 return True
1600 # rules/S10: "A numeral of two or more letters reads as
1601 # the generation" in the given part, which asks no
1602 # initial in front -- 'Smith, John VI' as 'Smith, John
1603 # III' (#752); `_ROMAN` first, C-level
1604 if (len(pieces[m]) == 1
1605 and len(stem := (tok := tokens[pieces[m][0]]).text
1606 .rstrip(".")) >= 2
1607 and _ROMAN.match(stem) is not None):
1608 return reads_as_generation(tok.text, tok.tags, None,
1609 state.one_case)
1610 # rules/S5: "a word that ENDS that part reads as the credential
1611 # unless its WRITING says otherwise" -- the given part's
1612 # trailing slot (#531).
1613 # INLINE, and that is the frame budget talking rather
1614 # than taste: the candidates pass asks this closure once
1615 # per piece of every family-comma segment, so a helper
1616 # call would cost a frame on every non-member piece and
1617 # a generator expression would cost its own on 3.11.
1618 # Membership is therefore a bare `in` on tags already
1619 # in hand, after a `len` -- 'Doe, John Q.' and
1620 # 'Smith, John V' measure +0 with this shape and +1
1621 # with a helper (2026-09-18).
1622 #
1623 # That "once per piece" is the NON-MEMBER cost, and
1624 # only it. A member is asked a second time by
1625 # trailing_floor()'s descent above, and twice is the
1626 # whole of it: the descent takes each piece once and
1627 # the candidates pass asks each piece once, which is what
1628 # makes the run linear. What the slot costs, measured
1629 # against cc78c960: 'Smith, John', 'Doe, John Q.',
1630 # 'Smith, John V', 'Smith, MA' and 'Berg, Jan vd' are
1631 # all +0 frames, while 'Doe, John MA' is +6 and 'Doe,
1632 # John MA PhD' +23 -- the member's descent, its lean,
1633 # and the report below (2026-09-19).
1634 #
1635 # The comma has already named the family and the first
1636 # piece after it is the given name, so the words to
1637 # spare S4's count asks about are there by
1638 # construction and the count says nothing at this
1639 # slot. What is left is the writing, which is the same
1640 # evidence the comma-less spelling of the same name
1641 # reads. #144's two-segment restriction below is NOT
1642 # inherited: it exists because a trailing 'V' before a
1643 # third comma part is likely a middle initial, and a
1644 # class member is not initial-shaped while a
1645 # credential list behind it makes the credential
1646 # reading likelier rather than less.
1647 piece = pieces[m]
1648 # rules/S12: a split credential reads "as a member of the
1649 # ambiguous class", here read as the class is with no
1650 # writing to lean on and in silence, as group merges it
1651 # only behind the given word
1652 if len(piece) == 2 and "split" in ptags[m]:
1653 return (m >= trailing_floor(m, titled)
1654 and not attaches_the_lead(m, titled))
1655 if len(piece) == 1:
1656 tok = tokens[piece[0]]
1657 if AMBIGUOUS_ACRONYM_TAG in tok.tags:
1658 # 'ending the given part' reaches past the
1659 # credentials behind it and past a trailing
1660 # title, which trailing_floor() skips the way
1661 # previous_kept() does -- so 'Doe, John MA
1662 # Prof.' and 'Doe, John Prof. MA' land on one
1663 # answer without a second notion of trailing.
1664 # A name word behind the member ends the
1665 # reach, and the member is an ordinary middle
1666 # name read in silence.
1667 if (m >= trailing_floor(m, titled)
1668 and not attaches_the_lead(m, titled)):
1669 # A member that is ALSO particle
1670 # vocabulary reads as the credential only
1671 # on a POSITIVE credential lean: P6's
1672 # attachment outranks this reading in
1673 # every other spelling, and 'Doe, John do'
1674 # leans nothing, so the positional reading
1675 # would take it -- the wrong answer there,
1676 # not merely a stray report
1677 # (decisions/S5, 2026-09-18).
1678 #
1679 # A FUNCTION since #533 rather than a
1680 # condition written here (mechanisms.md
1681 # #ONE-PREDICATE-PER-QUESTION). The call
1682 # costs one frame PER MEMBER asked at this
1683 # slot, not one per name: against
1684 # 2f57ff21, 'Doe, John MA' is 310 -> 311
1685 # and 'Doe, John MA Ma MA', which asks
1686 # four times, 439 -> 443, while a name
1687 # with no member here never reaches it
1688 # ('Smith, John' 206, 'MA JD' 185, both
1689 # unchanged). Measured 2026-09-19 per
1690 # `Parser.parse`; Derek took that trade
1691 # deliberately.
1692 # #544: an unambiguous credential in front
1693 # of it in the same run anchors it -- asked
1694 # through a thunk, so only a member the
1695 # writing declines pays for the pass
1696 if credential_at_the_given_slot(
1697 tok, state.one_case,
1698 lambda: anchored(m, titled)):
1699 return True
1700 prev = previous_kept(m, titled)
1701 # trailing piece of a two-part name is unambiguously
1702 # positioned: v1 accepts the lenient test there
1703 # ('Smith, John V' -> suffix='V', #144); with a third
1704 # comma part the trailing token is more likely a middle
1705 # initial, so strict only
1706 return (m == previous_kept(len(pieces), titled)
1707 and len(state.segments) == 2
1708 and len(pieces[m]) == 1
1709 and _reads_as_a_trailing_suffix(
1710 pieces[m], pieces[prev], ptags[prev],
1711 tokens, state.lexicon, state.one_case))
1712
1713 # rules/C1: "anything else after the comma means the
1714 # listing form" -- and this walk reads it. A segment of no
1715 # name word never reaches here: it is `_comma.decide`'s, read piece by piece and bound at
1716 # group's head (#613, rules/C8), the suffix verdict
1717 # before the title reading of the same word (#296, #325).
1718 # A name word in the segment makes it v1's walk ('Smith,
1719 # John Jr.').
1720 # rules/H9: "no comma has marked the given name" -- here the
1721 # family comma has, so the peel reports nothing
1722 n = _peel_leading_titles(pieces, ptags, tokens, None,
1723 state.lexicon)
1724 # rules/H5: "the title is TRANSPARENT to the suffix
1725 # reading: where two or more name words stand, what
1726 # stands once the chain is taken reads exactly as it
1727 # would read written without the title, plus the title"
1728 # -- the trailing title run, on this walk
1729 # too. A name word in segment 1 is what keeps
1730 # `_comma.decide` from reading the segment as the
1731 # postnominal part, so 'Smith, John Prof.' had no route
1732 # to title at all and read middle 'Prof.' at every
1733 # baseline; the 'Smith, Dr.' family of rows are decide's
1734 # doing, a different mechanism.
1735 #
1736 # The candidates are the pieces this walk would NOT
1737 # read as a suffix, which is this path's answer to the
1738 # peel the no-comma path runs first -- 'Smith, John
1739 # Prof. Jr.' must reach `Prof.` past the postnominal
1740 # behind it, and 'Smith, John Prof. V' past the
1741 # numeral the lenient tail test claims (#144), which
1742 # is why the filter is the walk's own predicate and
1743 # not the strict suffix test alone. Piece `n` is
1744 # always the given below, whatever that predicate
1745 # would say of it, so it is always a candidate. That
1746 # `k == n` is LOAD-BEARING, not defensive: it is what
1747 # the walk's floor stands on when the given piece
1748 # itself reads as a suffix, and dropping it leaves
1749 # 'Smith, II Mr. V' a middle 'Mr.' where the title is
1750 # (24 inputs of that shape move, of 191,146 generated,
1751 # measured 2026-09-09).
1752 #
1753 # `candidates` is the ORDER, which `trailing_titles` and
1754 # its slice read; everything after asks MEMBERSHIP,
1755 # once per piece, and a list or tuple answers that by
1756 # scanning, so the walk was quadratic in the part's
1757 # length (#553). Hence the two sets. A tuple keying
1758 # `floors` or `anchor_memo` above would also re-hash
1759 # its whole length at every lookup, where a frozenset
1760 # caches its hash.
1761 candidates = [k for k in range(n, len(pieces))
1762 if k == n
1763 or not reads_as_a_suffix(k, frozenset())]
1764 # rules/H8: "the word joins the title field, and the given
1765 # part reads as it would without it" -- a bare salutation
1766 # chains here as a period-marked title does
1767 kept = trailing_titles(candidates, pieces, ptags, tokens,
1768 salutations=True)
1769 walkable = frozenset(candidates)
1770 titled_idx = frozenset(candidates[kept:])
1771 for k in titled_idx:
1772 _set_roles(tokens, pieces[k], Role.TITLE)
1773 # v1 walk order: the first non-title piece is ALWAYS the
1774 # given, before any suffix check -- 'Smith, V. Jones' keeps
1775 # first='V.'. Two 2.x deviations are `_comma.decide`'s
1776 # reading now (#613), so the walk here never meets
1777 # either: a last piece
1778 # that is unambiguously suffix-shaped is a suffix, where v1
1779 # made it the given ('Smith, Dr. Jr.';
1780 # classified fix(comma-family)), a segment whose only
1781 # non-title piece is a suffix piece holding no name word;
1782 # and a credential opening the segment makes it the
1783 # postnominal part whatever follows ('Hardman, RN - CRNA'
1784 # kept first='RN' until #603).
1785 if n < len(pieces):
1786 _set_roles(tokens, pieces[n], Role.GIVEN)
1787 # The chain's floor leaves a name piece standing, so the
1788 # given above is never one of the pieces it took. What the
1789 # chain DOES move is where this segment's name ends, which
1790 # the lenient tail test turns on (#144) -- so where it took
1791 # something the question is re-asked with the pieces it
1792 # left. Where it took nothing, `walkable` already IS this
1793 # predicate's answer for every piece: the first pass's own
1794 # memo, not a second spelling of the question, and it
1795 # cannot have gone stale because nothing the chain does
1796 # moved the end of the name.
1797 # rules/S8: "or after the given word in the part after a
1798 # family comma" -- the given part's own credential run
1799 # (#602), the comma having fixed the family. The tag tests are inline ahead of the
1800 # predicate, as in `_pieces.credential_run`, so a name word
1801 # pays no frame: this loop runs on every family-comma name.
1802 sticky_from = len(pieces)
1803 for m in range(n + 1, len(pieces)):
1804 tags = tokens[pieces[m][0]].tags
1805 if (m not in titled_idx
1806 and ("suffix" in ptags[m] or "split" in ptags[m]
1807 or (("vocab:suffix" in tags
1808 or AMBIGUOUS_ACRONYM_TAG in tags
1809 or _ROMAN.match(tokens[pieces[m][0]].text
1810 .rstrip(".")) is not None)
1811 and tags.isdisjoint(_NOT_A_RUN_START)))
1812 and starts_a_credential_run(pieces[m], ptags[m],
1813 tokens, None,
1814 state.one_case)):
1815 sticky_from = m
1816 break
1817 # rules/P6: "a particle ending the name attaches to that
1818 # family name" -- decided here, in the pass that reads the
1819 # given part, rather than predicted for post_rules to take
1820 # a stage later (#613). The tail is `pieces[k6:end6]`, found
1821 # by `particle_tail` ONCE, at the moment the walk reaches
1822 # #602's run (or, with no run, once the walk has placed
1823 # every piece): the pieces in front of the run hold the roles
1824 # this walk gave them and the run's own words hold none
1825 # yet, which is the state in which the walk's answer equals
1826 # the one it would give over the finished roles -- the run
1827 # reads every word it keeps as a suffix or a title, neither
1828 # a name role, and a class member in it as the credential,
1829 # where the walk's #531 stop wants it. The tail's words are
1830 # left to the walk, not the run: absorbing them reported a
1831 # suffix reading the attachment then overrode ('Smith, John
1832 # PhD de', 'Smith, John PhD de Jr.'). A particle the walk
1833 # does not end on -- one with a credential behind it and
1834 # another particle past that, 'Smith, John PhD de PhD van'
1835 # -- stays in the run, as does a lone member of the
1836 # ambiguous credential class (`do`), which the run reads as
1837 # the credential.
1838 k6 = end6 = len(pieces)
1839
1840 def as_a_middle(m: int, token: WorkToken) -> PendingReading:
1841 # the name reading of a word the walk read as a suffix:
1842 # a middle name, taken in by the name word in front, or
1843 # the family where P1's fold opens the part
1844 front = pieces[m - 1]
1845 # P1's fold after a family comma takes the rest of the
1846 # part into the family whatever the order, so a word past
1847 # the opening particle's own piece lands there; the word
1848 # directly behind it is `_name_alt`'s, which takes it into
1849 # that piece; decisions/C9 (#877)
1850 if n < m - 1 and is_lone_never_given_particle(pieces[n],
1851 tokens):
1852 return name_reading(token, Role.FAMILY)
1853 return _name_alt(
1854 token, Role.MIDDLE,
1855 front if tokens[front[0]].role in NAME_ROLES else None,
1856 tokens, m - 1 == n, True)
1857
1858 for m in range(n + 1, len(pieces)):
1859 if m == sticky_from:
1860 k6, end6 = particle_tail(pieces, tokens)
1861 if m in titled_idx:
1862 continue
1863 suffix_here = (reads_as_a_suffix(m, titled_idx)
1864 if titled_idx else m not in walkable)
1865 # rules/S10: "A numeral read by its shape alone reports
1866 # too" -- one of two or more letters the walk reads as
1867 # the generation; `_ROMAN` first, C-level
1868 if (suffix_here and len(pieces[m]) == 1
1869 and len(stem := (tok := tokens[pieces[m][0]]).text
1870 .rstrip(".")) >= 2
1871 and _ROMAN.match(stem) is not None
1872 and not is_listed_numeral(tok.text, tok.tags)
1873 and not numeral_settled_by_case(tok.text,
1874 state.one_case)):
1875 ambiguities.append(PendingAmbiguity(
1876 AmbiguityKind.SUFFIX_OR_NAME,
1877 f"{tok.text!r} is a roman numeral, so it reads as "
1878 f"a generational suffix; it may be a name word",
1879 (pieces[m][0],),
1880 # a name word the walk keeps past the given
1881 # name is a middle one
1882 alternative=as_a_middle(m, tok)))
1883 # rules/C9: "a lone letter ending the given part ahead of
1884 # a further comma is the middle initial, whatever stands
1885 # before it" -- the further comma has named the suffix,
1886 # so the credential run in front stops short of it
1887 # (#819); `len` first, C-level
1888 if (m > sticky_from and len(state.segments) > 2
1889 and len(pieces[m]) == 1
1890 and len(tokens[pieces[m][0]].text.rstrip(".")) == 1
1891 and m == previous_kept(len(pieces), titled_idx)
1892 and is_initial_shaped(
1893 tokens[pieces[m][0]].text.upper())):
1894 _set_roles(tokens, pieces[m], Role.MIDDLE)
1895 continue
1896 # rules/C9: "The bare letter read as the generation behind
1897 # a name word is reported" -- the shape a middle initial
1898 # is written in, as S10 reports it with no comma;
1899 # decisions/C9 (#877); `len` first, C-level
1900 if (len(pieces[m]) == 1
1901 and len((tok := tokens[pieces[m][0]]).text) == 1
1902 and (m >= sticky_from and not k6 <= m < end6
1903 or m < sticky_from and suffix_here)
1904 and _ROMAN.match(tok.text) is not None
1905 and tokens[pieces[m - 1][0]].role in NAME_ROLES
1906 # a particle in front may take the letter into
1907 # its chain or stand alone, the field the name
1908 # reading names depending on which; decisions/C9
1909 # (#877)
1910 and not is_prefix_piece(pieces[m - 1], ptags[m - 1],
1911 tokens)
1912 and not numeral_settled_by_case(tok.text,
1913 state.one_case)):
1914 ambiguities.append(PendingAmbiguity(
1915 AmbiguityKind.SUFFIX_OR_NAME,
1916 f"{tok.text!r} is a roman numeral, so it reads as a "
1917 f"generational suffix; any other single letter "
1918 f"there would be a middle initial",
1919 (pieces[m][0],), alternative=as_a_middle(m, tok)))
1920 if m >= sticky_from and not k6 <= m < end6:
1921 # inside the run: a title word reads as a title,
1922 # every other word as a suffix, and a word the walk
1923 # would have kept as a name is reported, here where
1924 # the run absorbs it
1925 if (m > sticky_from
1926 and not is_suffix_piece(pieces[m], ptags[m],
1927 tokens)
1928 and is_title_piece(pieces[m], ptags[m],
1929 tokens)):
1930 _set_roles(tokens, pieces[m], Role.TITLE)
1931 continue
1932 piece = pieces[m]
1933 if (len(piece) == 1
1934 and not tokens[piece[0]].tags.isdisjoint(
1935 _AMBIGUOUS_CREDENTIAL_TAGS)):
1936 # a class member inside the run is still the
1937 # fork #531's report names, now read as the
1938 # credential, as #544's anchor reads one --
1939 # unless its capitals settled it (rules/S6)
1940 if not settled_by_case(tokens[piece[0]],
1941 state.one_case):
1942 ambiguities.append(PendingAmbiguity(
1943 AmbiguityKind.SUFFIX_OR_NAME,
1944 f"{tokens[piece[0]].text!r} ending the given "
1945 f"part is also an ordinary name word; read "
1946 f"as a credential", (piece[0],),
1947 alternative=as_a_middle(
1948 m, tokens[piece[0]])))
1949 # the run's own first word is the credential that
1950 # starts it, a split one ('Pharm D') included
1951 elif (not suffix_here and m != sticky_from
1952 and has_name_content(piece, tokens)):
1953 ambiguities.append(
1954 _absorbed(piece, tokens,
1955 as_a_middle(m, tokens[piece[0]])))
1956 _set_roles(tokens, piece, Role.SUFFIX)
1957 continue
1958 _set_roles(tokens, pieces[m],
1959 Role.SUFFIX if suffix_here else Role.MIDDLE)
1960 # #531's report, one of this module's SUFFIX_OR_NAME
1961 # sites (the header lists them). The gate reads EITHER tag, as the
1962 # first-post-comma emitter's does: classify writes the
1963 # shape tag whether or not the dotted switch admits
1964 # the token, which is what lets a declined fork be
1965 # reported without being taken.
1966 #
1967 # The report tracks the FORK CONSULTED, not the lean
1968 # (#289's rule), so a member the writing kept as a
1969 # name reports too -- 'Doe, John Ma' stays a middle
1970 # name and says so. It reports only in the TRAILING
1971 # RUN: with a name word behind it no fork was
1972 # consulted, and AGENTS.md's "a kind is worth adding
1973 # only if a reader would hesitate too" is why that
1974 # must stay silent rather than why it happens to (the
1975 # sentence is the 2.0-conventions section's, not
1976 # rules/A1's, which this cited until 2026-09-19).
1977 #
1978 # The `do` carve-out is a REPORT carve-out on top of
1979 # the reading one above: a particle-tagged member this
1980 # walk did not itself take is P6's fork, and P6
1981 # reports it in its own kind, which is
1982 # mechanisms.md#AMBIGUITY-AT-THE-DECISION-SITE read
1983 # strictly. Without it 'Doe, John do' reported both
1984 # kinds.
1985 piece = pieces[m]
1986 if (len(piece) == 1
1987 and not tokens[piece[0]].tags.isdisjoint(
1988 _AMBIGUOUS_CREDENTIAL_TAGS)
1989 and (suffix_here
1990 or "particle" not in tokens[piece[0]].tags)
1991 # rules/S6: "a clash settled by the writing is
1992 # not reported"
1993 and not (suffix_here and settled_by_case(
1994 tokens[piece[0]], state.one_case))):
1995 # The SAME floor the predicate measures members
1996 # against, so this report has no walk of its own to
1997 # regress: it had one, and on a run the predicate's
1998 # memo had already made quadratic the report was
1999 # CUBIC, because its per-member walk re-scanned
2000 # `walkable` -- a list -- at every step. Measured
2001 # then on `'Doe, ' + 'John '*r + 'MA '*r`, r
2002 # doubling from 100: 5.8/28/175/1229ms, 4.9x then
2003 # 6.2x then 7.0x per doubling and heading for the
2004 # 8x a cubic gives, against 1.8/3.7/8.0ms here
2005 # (2026-09-19). Nothing guarded it: the scan was a
2006 # C-level `in` over a list and emitted no frame, so
2007 # the frame-ratio test in tests/v2/test_benchmark.py
2008 # was structurally blind to it, and the clock-based
2009 # shapes beside it repeat ONE unit where this cost
2010 # needs a name holding two runs (`_PREFIXED_SHAPES`
2011 # adds a prefix but still repeats one run, so it
2012 # does not reach this either). What keeps it gone
2013 # is the structure: one walk, read by both callers,
2014 # so a second would have to be written on purpose.
2015 #
2016 # Read once for the whole loop, `run_floor` being
2017 # where the FIRST member's walk stopped and the
2018 # floor for every later member too: if the walk
2019 # reached that member, nothing behind it refuses
2020 # and no later member can be refused either; if it
2021 # stopped short, it stopped at the LAST piece that
2022 # refuses, which is exactly what a later member's
2023 # own walk would have found (2026-09-19).
2024 if run_floor < 0:
2025 run_floor = trailing_floor(m, titled_idx)
2026 if m >= run_floor:
2027 i2 = piece[0]
2028 ambiguities.append(PendingAmbiguity(
2029 AmbiguityKind.SUFFIX_OR_NAME,
2030 f"{tokens[i2].text!r} ending the given "
2031 f"part is also an ordinary name word; "
2032 f"read as "
2033 f"{'a credential' if suffix_here else 'a name'}",
2034 (i2,),
2035 alternative=(
2036 as_a_middle(m, tokens[i2])
2037 if suffix_here
2038 else suffix_reading(tokens[i2]))))
2039 if sticky_from == len(pieces):
2040 k6, end6 = particle_tail(pieces, tokens)
2041 # Behind every family comma, one with nothing before it
2042 # too, which then makes the particle the whole family
2043 # (', Dr. Jones vd'; decisions/C15, #892). GIVEN ahead of
2044 # the tail -- rules/P6: "at least one given word must
2045 # remain" -- the given is piece `n`, so a tail starting
2046 # there leaves none ('Nguyen, Van').
2047 # And not where a never-given particle opens the part: P1's
2048 # fold takes every given and middle word into the family in
2049 # post_rules, so no given word remains for this one either
2050 # ('Smith, de Mesnil van' keeps 'van' where the fold puts
2051 # it, not hoisted in front of 'Smith', the 2026-08-18
2052 # defect); with no name word behind it to fold, the tail
2053 # stays the suffix, behind an empty head as behind its twin
2054 # (', de PhD vd' as 'Smith, de PhD vd', #892).
2055 if (n < k6 < end6
2056 and not is_lone_never_given_particle(pieces[n],
2057 tokens)):
2058 _attach_particle_tail(pieces, tokens, n, k6, end6,
2059 ambiguities)
2060 # rules/H6: "A run of title words opening the part before a
2061 # family comma is the title" -- by vocabulary only, never H2's
2062 # shape, leaving one piece for the family, and stopping at a
2063 # word that is a particle too, or where everything behind it is
2064 # post-nominal, which leaves no family word to address -- H3's
2065 # concern, by a stricter test than H3's one-word give-back, so
2066 # this is not `leading_titles`. A dual is a title wherever a name
2067 # word follows it. `is_title_piece` is H5's vocabulary read, so
2068 # the two slots that refuse the shape agree on what a title word
2069 # is, save H5's written-short clause, which this slot does not
2070 # read (decisions/H6, decisions/H9 (#999)).
2071 #
2072 # rules/H10: "where a title the run keeps stands behind it" --
2073 # a dotted run counts as a title word here as in the leading
2074 # run, and one the run ends on is given back, so the roles are
2075 # set once the run is known (decisions/H10 (#490)).
2076 lead = 0
2077 floor = len(fam_pieces)
2078 # the length test and the tag test first, both C-level: a part
2079 # no title opens ('Smith, John', 'Smith Jones, John') pays no
2080 # frame. "title" and "vocab:title" are the two arms
2081 # `is_title_piece` answers yes from, so for a listed title the
2082 # predicate stays the one that answers; a lone piece carrying
2083 # classify's DOTTED_TITLE_TAG is taken on the tag alone
2084 # (rules/H10) and given back below unless a title the run keeps
2085 # stands behind it
2086 tags0 = tokens[fam_pieces[0][0]].tags if fam_pieces else frozenset()
2087 if (floor > 1
2088 and ("title" in fam_tags[0] or "vocab:title" in tags0
2089 or DOTTED_TITLE_TAG in tags0)
2090 and ((len(fam_pieces[0]) == 1 and DOTTED_TITLE_TAG in tags0)
2091 or is_title_piece(fam_pieces[0], fam_tags[0], tokens))):
2092 # where the trailing post-nominal run starts: walked once,
2093 # and only for a part a title opens
2094 while floor > 1 and is_suffix_piece(fam_pieces[floor - 1],
2095 fam_tags[floor - 1],
2096 tokens):
2097 floor -= 1
2098 # the first piece is a title or a dotted run, asked above; a
2099 # dotted run the run ends on is given back after the walk
2100 while (lead + 1 < floor
2101 and (lead == 0 or is_title_piece(
2102 fam_pieces[lead], fam_tags[lead], tokens)
2103 or (len(fam_pieces[lead]) == 1 and DOTTED_TITLE_TAG
2104 in tokens[fam_pieces[lead][0]].tags))
2105 and "particle" not in tokens[fam_pieces[lead][0]].tags):
2106 lead += 1
2107 while (lead and len(fam_pieces[lead - 1]) == 1
2108 and DOTTED_TITLE_TAG
2109 in tokens[fam_pieces[lead - 1][0]].tags):
2110 lead -= 1
2111 for k in range(lead):
2112 _set_roles(tokens, fam_pieces[k], Role.TITLE)
2113 # rules/P9: "a particle that is also suffix vocabulary heads
2114 # the name word behind it" -- with a name piece behind it in
2115 # this part (vd, mc), it heads that name, as P2's join does,
2116 # and is not peeled from between two family words
2117 # (#573: 'SMITH VD MA, JOHN', where the uniform case left the
2118 # chain stopped before VD; 'SMITH VD JR, JOHN', a suffix word
2119 # behind it, keeps suffix 'VD JR'). Read here because only
2120 # this family pass needs it: a comma followed by no name
2121 # word behind a whole name is group's suffix comma since #613,
2122 # and the NO_COMMA read takes segment 0, trailing run and all
2123 # ('Berg de MA, Prof.'). The first piece the title run leaves
2124 # is the family's first and is family whatever it is, as piece
2125 # 0 is with no title ('Dr. PhD Smith, John' as 'PhD Smith, John').
2126 # A piece at or past the floor is already known to be a suffix
2127 # with nothing but suffixes behind it, so it is not asked again.
2128
2129 # Whether a particle read as family stands in front of the
2130 # piece the loop is at, and whether the piece right in front was
2131 # read as family, for P2's arm below.
2132 chained = False
2133 family_before = False
2134 for k in range(lead, len(fam_pieces)):
2135 piece = fam_pieces[k]
2136 if k >= floor:
2137 _set_roles(tokens, piece, Role.SUFFIX)
2138 # rules/C1: "a numeral ending the family part is read as the
2139 # comma-less name reads it" -- the numeral's predicate, a
2140 # one-letter numeral with two name words in front of it
2141 # (rules/S10; name words only, `_names_before`), so 'John
2142 # Smith V, M.J.' keeps suffix 'V' as 'John Smith III, M.J.'
2143 # keeps 'III' (#774). `_ROMAN`
2144 # first, C-level, so a family word pays no frame
2145 elif (k > lead and len(piece) == 1
2146 and _ROMAN.match(
2147 (word := tokens[piece[0]]).text.rstrip("."))
2148 is not None
2149 and all(is_suffix_piece(fam_pieces[j], fam_tags[j],
2150 tokens)
2151 for j in range(k + 1, len(fam_pieces)))
2152 and (numeral := _family_part_numeral(
2153 word, tokens[fam_pieces[k - 1][0]].text,
2154 _names_before(fam_pieces, tokens, lead, k),
2155 state.one_case)) is not None):
2156 _set_roles(tokens, piece, numeral)
2157 # reported where taken: a name word here is the family
2158 # name the comma has just named, which nobody misreads
2159 if (numeral is Role.SUFFIX
2160 and not is_listed_numeral(word.text, word.tags)
2161 and not numeral_settled_by_case(word.text,
2162 state.one_case)):
2163 ambiguities.append(PendingAmbiguity(
2164 AmbiguityKind.SUFFIX_OR_NAME,
2165 f"{word.text!r} ending the family part is a roman "
2166 f"numeral, so it reads as a generational suffix; "
2167 f"it may be a name word", tuple(piece),
2168 alternative=name_reading(word, Role.FAMILY)))
2169 elif (k > lead and is_suffix_piece(piece, fam_tags[k], tokens)
2170 and not (k + 1 < len(fam_pieces)
2171 and "particle" in tokens[piece[0]].tags
2172 and not is_suffix_piece(
2173 fam_pieces[k + 1], fam_tags[k + 1],
2174 tokens))
2175 # rules/P2: "before a family comma the part keeps
2176 # either in the family behind a particle, as the
2177 # chain does" -- a suffix word S8 starts no run at
2178 # or declines for its writing, anything but
2179 # suffixes behind it ('bin Abd Rahman, Ahmad',
2180 # 'bin Md Rahman, Ahmad'); a particle that is suffix
2181 # vocabulary too is P9's (decisions/P2, #1177)
2182 and not (chained and family_before
2183 and "particle" not in tokens[piece[0]].tags
2184 and not all(
2185 is_suffix_piece(fam_pieces[j], fam_tags[j],
2186 tokens)
2187 for j in range(k + 1, len(fam_pieces)))
2188 and not starts_the_run_here(
2189 k, fam_pieces, fam_tags, tokens,
2190 state.one_case, False))):
2191 _set_roles(tokens, piece, Role.SUFFIX)
2192 else:
2193 _set_roles(tokens, piece, Role.FAMILY)
2194 # the tag tests are is_prefix_piece's own arms, inline
2195 # so a family word pays no frame
2196 chained = chained or ("prefix" in fam_tags[k]
2197 or len(piece) == 1
2198 and "particle"
2199 in tokens[piece[0]].tags)
2200 family_before = tokens[piece[0]].role is Role.FAMILY
2201 tail = 2
2202 # rules/C2: segments past the structure's name segments are
2203 # consumed as suffixes, except "a word of the title vocabulary there
2204 # that is not also suffix vocabulary is a title" (#603) -- a part
2205 # past the second comma holds no name word, so the surnames H5
2206 # keeps a bare trailing title word from misreading are not there to
2207 # protect ('Eric H. Holder, Jr., Attorney General'). A
2208 # piece holding a suffix word stays the postnominal the slot makes
2209 # it, a dual alone as after a family comma (C8) and a dual group's
2210 # connective join took into a title ('PhD - and MD') alike.
2211 for seg_idx in range(tail, len(state.segments)):
2212 for piece, ptags_ in zip(state.pieces[seg_idx],
2213 state.piece_tags[seg_idx]):
2214 # the tag tests inline ahead of the predicate: every tail
2215 # past the name segments runs this ('John Smith, Jr., PhD'),
2216 # the part after a suffix comma being bound by group, and the call
2217 # would be its frame. Both arms are needed -- a connective
2218 # join tags a piece a title though its first token is none
2219 # ('and Secretary of State')
2220 _set_roles(tokens, piece,
2221 Role.TITLE
2222 if (("title" in ptags_
2223 or "vocab:title" in tokens[piece[0]].tags)
2224 and is_title_piece(piece, ptags_, tokens)
2225 and not any("vocab:suffix" in tokens[i].tags
2226 for i in piece))
2227 else Role.SUFFIX)
2228 # rules/S12: "where the count takes the pair, the reading is reported" -- at
2229 # the end of a name, at the end of the given part, as a run start,
2230 # here where its roles are final (the part a comma's decision binds reports in `_comma`, a
2231 # pair a maiden clause releases in group). A loop over the piece
2232 # tags, so a name with no pair pays no frame for it.
2233 for seg_idx in range(min(tail, len(state.segments))):
2234 for piece, ptags_ in zip(state.pieces[seg_idx],
2235 state.piece_tags[seg_idx]):
2236 if ("split" in ptags_ and len(piece) == 2
2237 and tokens[piece[0]].role is Role.SUFFIX
2238 and tokens[piece[1]].role is Role.SUFFIX):
2239 ambiguities.append(split_credential_report(
2240 piece, tokens, _split_name_alt(state, tokens, seg_idx,
2241 piece, order)))
2242 # the reports earlier stages left a field for: only a name that
2243 # has one pays the walk
2244 if state.ambiguities:
2245 _resolve_deferred(state, tokens, ambiguities, order)
2246 return copy_with(state, tokens=tuple(tokens),
2247 order=order,
2248 ambiguities=tuple(ambiguities))