1"""Stage: group.
2
3Consumes: tokens (classified), segments, structure, one_case, extracted
4(the role + inner span per delimited region, for the #329 pass below,
5which drops a maiden clause's marker and, since #1164, an alias marker
6opening a nickname clause; post_rules reads it too, for S13); and, through
7`_comma.decide`, comma_offsets (the own-words span of the name's case
8contrast) and dropped, which decide extends.
9Produces: structure -- its head decides a comma form once the words
10are tagged (rules/C1, #613, `_comma.decide`), binding the SUFFIX and
11TITLE roles of a postnominal part after the comma, emptying its
12segment and dropping its delimiter cores before any join, plus the SUFFIX_OR_NAME
13ambiguities that decision reports, those the particle chain and a
14maiden or alias clause report on a trailing member they take into the name
15(an ambiguous acronym, or since #718 a declined numeral), the
16PARTICLE_OR_GIVEN report the particle chain makes where it chains an
17ambiguous particle with nothing but leading titles in front of it
18(`St van Johnson`, `Freiherr von der Berg`; `Vincent van Gogh` and
19`Dr. Van Johnson` report nothing here), and the
20caps shape's acronym tags on
21a bound all-caps word (#564); pieces + piece_tags per segment
22(runs of token indices -- tokens are NEVER joined into strings: the
23anti-#100 invariant); maiden tail tokens get role=MAIDEN and an
24alias's words role=NICKNAME (rules/N4, #1164), and the trailing run a
25take gives up gets its SUFFIX and TITLE roles here (#601), so no join
26can reach it; marker tokens of both kinds land in dropped;
27and tail_reads, rules/S2's trailing run of each main segment read
28ONCE, after P3's connective joins and before the particle chain and
29the bound-given join, and split off so neither reaches it (#614),
30which assign places and reports rather than peeling again; and,
31last in each part, P12's join past the start of a listed pair, or of a
32`completes_any` bound word and the plain word after it (#1464), and of a
33pair read from its listed second word at the start too (#1072), the
34classify tag left only on the first word of a pair it joined (#694).
35Reads: token tags (from classify), Lexicon.given_name_titles (the
36P5 licence, #369), Policy.name_order (rules/P13's joins at the end
37of a name read given-first, #1098) and Policy.extra_suffix_delimiters, whose
38delimiter-core tokens part a tail segment as a comma would and are
39dropped (v1 suffix_delimiter parity, #549), as the built-in cores'
40are (rules/C10, #889); and, through
41`_comma.decide`, what that module's own header lists
42(Policy.lenient_comma_suffixes and Policy.unlisted_caps_suffixes among
43them). The v1
44"derived titles/prefixes" registration becomes piece_tags entries --
45per-parse state that dissolves with the state (v1 kept per-parse sets
46for the same reason).
47
48Implements rules P2, P3, P4, P12, P13, M2, N4 and C10 (a delimiter core
49parting a tail segment), S2's trailing read (#614), C1's
50decision through _comma, and
51the
52group half of M1 (#329: the marker dropped inside EXTRACTED maiden
53content, which M2's pieces walk cannot reach because extract's
54content never enters pieces); each is cited at its code below. Also
55implements rule P5 (cited below at the bound-given join) and ports
56the "Ph. D."-split merge (v1 fix_phd; decisions/phd-merge).
57
58The piece-level predicates moved to _pieces in #439 -- the S2
59trailing peel, the leading-title and title-piece tests, the
60suffix-piece test, the no-name-segment test. Most are shared with
61assign; trailing_start is group's alone and travelled because the
62shared ones call it (is_title_piece was too, until #602 and #603 gave
63assign calls of its own). They had collected here
64by import direction rather than by topic (assign imported group and
65could not be imported back), which is the accumulation
66mechanisms.md#ONE-PREDICATE-PER-QUESTION describes; group imports them
67back like any other caller, and still does the work H3 and S2 describe
68with them. is_prefix_piece and is_conj_piece followed in #617, with
69the merge and rules/P3's connective joins (join_connectives), when
70the comma decision's own copy of those joins was folded into them.
71What remains defined here is group's own: the piece predicates
72_is_rootname, _is_maiden_marker_piece, _bounds_the_title_run,
73_is_lone_letter and _is_name_word, beside the helpers of its joins and
74its marker takes, `_closing_run_start` among them
75(maiden and alias, rules/M2 and N4).
76"""
77from __future__ import annotations
78
79import bisect
80import operator
81from collections.abc import Iterable, Sequence, Set
82from enum import IntEnum
83from typing import assert_never
84
85from nameparser._lexicon import _run_addresses_by_given
86from nameparser._pipeline._pieces import (
87 split_credential_report,
88 Peel, TailRead, chain_lead, chain_run_end, is_conj_piece, is_leading_title, is_prefix_piece,
89 is_suffix_piece, is_title_piece, is_trailing_title_word,
90 join_connectives, joined_tags,
91 leading_titles, merge_particle_runs, merge_pieces, peel_walk,
92 read_trailing_run, settled_by_case, tail_reading, trailing_candidates,
93 trailing_run_start, trailing_start,
94 trailing_start_past_titles,
95)
96from nameparser._pipeline._state import (
97 ALIAS_MARKER_TAG, AMBIGUOUS_ACRONYM_TAG, BOUND_PHRASE_TAG, DOTTED_TITLE_TAG, PATRONYMIC_TAG, BOUND_SECOND_TAG, SPLIT_CREDENTIAL_TAG,
98 SPLIT_MEMBER_TAG, TRAILING_TITLE_TAG, ParseState,
99 Deferred, PendingAmbiguity, Structure, WorkToken,
100 _AMBIGUOUS_CREDENTIAL_TAGS, copy_with,
101)
102import nameparser._pipeline._comma as _comma
103from nameparser._pipeline._vocab import (
104 ROMAN, comma_follows_marker, delimiter_cores, ends_in_a_generation,
105 composed, name_reading, numeral_settled_by_case,
106 reads_as_a_reported_numeral, suffix_reading,
107)
108from nameparser._types import AmbiguityKind, Role
109
110# the split credential is `_vocab.split_pair`, which classify asks of
111# every adjacent pair and writes on the pair's first word, and which
112# is_wholly_suffix asks to merge the same Ph./D. pair, as
113# `_comma._pieces` reads the tag -- so that predicate's callers read
114# what this stage merges: `_comma.decide`'s reading of the part after
115# the comma, segment's C2 flag on a tail part, and script_segment's
116# decline of a wholly-suffix post-comma run, all of which see the
117# merged reading
118
119Piece = list[int]
120_SPAN_START = operator.attrgetter("span.start")
121_MARKER_TAGS = frozenset({ALIAS_MARKER_TAG, "vocab:maiden-marker"})
122#: rules/N4's boundaries inside a part: a patronymic particle (`bin`,
123#: `a/l`), or another marker of either kind
124_ALIAS_ENDS = _MARKER_TAGS | {PATRONYMIC_TAG}
125#: What the marker passes took out of a segment: the markers' TOKEN
126#: indices (a maiden marker's more than one where the entry is a
127#: phrase, 'z domu'; every alias marker's, rules/N4), and every other
128#: piece they took with the role that piece takes -- the maiden name's
129#: Role.MAIDEN, an alias's Role.NICKNAME, and the trailing run's SUFFIX
130#: or TITLE (#601). `_apply_take` builds it, take by take.
131ClauseTake = tuple[Piece, list[tuple[Piece, Role]]]
132#: What `_clause_take` answers with (through `_maiden_take` and
133#: `_alias_takes`), one index space further out: PIECE indices into its
134#: own `pieces` argument. `_apply_take` resolves them to the token
135#: indices ClauseTake declares, which is the only
136#: reason the two are different types rather than one name used twice.
137ClauseIndices = tuple[list[int], list[tuple[int, Role]]]
138
139
140class ClauseSite(IntEnum):
141 """Where a maiden clause stands, which decides whether a marker
142 counts there at all and which rule reads the end of the part
143 (rules/M2, #601).
144
145 A maiden marker counts only in the part holding the family name, so
146 GIVEN_SLOT and TAIL are statements, not defaults: a maiden marker
147 there is an ordinary word; an alias marker (rules/N4) counts in
148 GIVEN_SLOT too, and in no TAIL. FAMILY_PART is the part before a
149 family comma, where a marker counts but no trailing rule reads the
150 words after the clause.
151
152 A CLOSED set: `_clause_take` dispatches on it exhaustively, ONCE
153 (`typing.assert_never`), for both markers. group() is the one place (structure,
154 segment index) is mapped onto it, and tests/v2/pipeline/
155 test_group.py's `test_the_site_is_pinned_to_the_structure_it_is_
156 read_from` pins that mapping -- by watching the call, not by
157 restating it -- along with this enum's size.
158 """
159
160 FAMILY_PART = 0 # FAMILY_COMMA segment 0: a marker counts, nothing trails
161 TRAILING = 1 # NO_COMMA, SUFFIX_COMMA segment 0: S2 peel + H5 chain
162 GIVEN_SLOT = 2 # FAMILY_COMMA segment 1: a maiden marker is a word; an alias marker counts
163 TAIL = 3 # every tail segment: a marker is an ordinary word
164
165
166class BoundJoin(IntEnum):
167 """v1 _join_bound_first_name's reserve_last, as the three states it
168 actually has. IntEnum: the value IS the number of name pieces
169 assign's peel must leave in the JOINED view for the join to stand
170 (#425), so the >= comparison below reads unchanged. Post-comma the
171 reserve runs no peel -- the pair alone is that one piece; the
172 decline reads H5's trailing run only where a title word follows
173 the bound word (#637) -- and DISABLED
174 is a mode, never compared: as a threshold 0 would join everything,
175 which is why the block is entered on identity first."""
176
177 DISABLED = 0 # the FAMILY_COMMA family segment (v1 never joined it)
178 LENIENT = 1 # FAMILY_COMMA's post-comma segment (reserve_last=False)
179 STRICT = 2 # main segments (reserve_last=True: keep a family piece)
180
181
182# rules/M2: "A marker that counts takes the words after it as the
183# maiden name, and is itself dropped" -- where a marker counts, and up
184# to what, are `_maiden_take`'s (history: decisions/M2)
185#
186# A marker piece is a LONE marker -- M2's When ("a recognized maiden
187# marker stands as a word in a name"). The consumer runs before every join but the Ph. D. merge
188# (see _group_segment), so a marker inside a wider piece is one the
189# consumer left there: declined ("Jane van der Berg née" reads family
190# 'van der Berg née'), or never examined (a leading marker, or a second
191# marker behind the span it took). Matching inside joined pieces would
192# re-read those.
193#
194# With the pass ahead of the joins no default-vocabulary input reaches
195# the lone-piece half through the one caller left that sees joined
196# pieces (P5's marker decline, on `fk + 1`): a marker-headed wider
197# piece needs a connective right after a declined marker, and a
198# connective after a marker is a word the consumer takes. Measured at
199# #420's review --
200# dropping `len(piece) == 1` leaves the suite and a 337k-name sweep
201# identical -- so it stays as the rule's definition, not as a guard a
202# pin holds.
203def _is_maiden_marker_piece(piece: Sequence[int],
204 tokens: Sequence[WorkToken]) -> bool:
205 return (len(piece) == 1
206 and "vocab:maiden-marker" in tokens[piece[0]].tags)
207
208
209# mechanisms.md#ONE-PREDICATE-PER-QUESTION: "where the reader comes
210# AFTER the decider, record the answer on the state instead" -- which is
211# what the marker tags are. classify owns the phrase lookahead; group,
212# running later, reads what it wrote.
213def marker_run_length(following: Iterable[Set[str]]) -> int:
214 """How many tokens a marker run spans, given the tag sets of what
215 FOLLOWS its head, in order: 1 plus the leading continuations.
216
217 One walk for both places group asks -- over pieces below and over
218 token indices in the clause drop at the end of this module, 700
219 lines apart and differing only in index space. `following` is
220 consumed lazily and only until the run ends, so a caller passes a
221 generator over the rest of its sequence rather than materializing
222 one."""
223 run = 1
224 for tags in following:
225 if "vocab:maiden-marker-cont" not in tags:
226 break
227 run += 1
228 return run
229
230
231def _marker_run_pieces(pieces: Sequence[Sequence[int]],
232 tokens: Sequence[WorkToken], m: int) -> int:
233 """How many pieces the marker run at pieces[m] spans: 1
234 for a single-word marker, more for a phrase entry ('z domu').
235
236 classify already decided where the run ends and recorded it on the
237 tokens -- "vocab:maiden-marker" on the head,
238 "vocab:maiden-marker-cont" on the rest.
239
240 Each continuation is the NEXT piece, and
241 that holds because classify REFUSES to tag a run whose tokens are
242 not structurally contiguous. It is not a property of this walk, and
243 the reasons a token can be absent between two pieces are wider
244 than they look. No join has run yet, so a piece is one token. A
245 tail segment is cut at its delimiter cores and grouped part by
246 part (#549), and a core between two marker words would be a token
247 between them, which classify would not have tagged as a run. And
248 `pieces` comes from a SEGMENT, or a part of one, and segment keeps
249 only the tokens no stage has given a role, bucketed by the commas
250 before them -- so a run half inside a bracketed clause, or split across a
251 structure comma, is one no segment holds whole. Walking cont tags
252 without classify's refusal read a proper PREFIX of the phrase as
253 the whole marker, and 'Anna z (domu) Nowak' lost its given name to
254 a bare preposition. Any future stage that removes a token from a
255 segment owes this the same refusal.
256
257 What classify guarantees is exactly the main stream's half of that
258 and no more: a run of ROLE-LESS tokens stays inside one segment. It
259 can also tag a run across two adjacent clauses of the same role,
260 which this walk never sees because a role-bearing token is in no
261 segment at all -- see _vocab.tag_marker_runs, which states the limit.
262 """
263 return marker_run_length(
264 tokens[pieces[k][0]].tags for k in range(m + 1, len(pieces)))
265
266
267def _maiden_take(pieces: Sequence[Sequence[int]],
268 ptags: Sequence[Set[str]],
269 tokens: Sequence[WorkToken],
270 one_case: bool | None,
271 site: ClauseSite,
272 ambiguities: list[PendingAmbiguity],
273 ) -> ClauseIndices | None:
274 """The PIECE indices the marker pass removes, split the way
275 ClauseIndices declares them: the marker's pieces (one, or several
276 for a phrase entry like 'z domu'), then the maiden name's and the
277 trailing run's, each with the role it takes. None where the marker is
278 an ordinary word. Piece indices into `pieces`, not the TOKEN
279 indices `_group_segment` builds out of them.
280
281 Three questions, in order (rules/M2, #601), answered by
282 `_clause_take`, which rules/N4's alias take shares:
283
284 * WHERE A MARKER COUNTS. Only in the part holding the family name
285 -- never in the given part after a family comma, never in a tail
286 part -- and only with a name word straight before it: not a word
287 of the leading title run (H3's give-back included, so 'Lord
288 Chancellor née Jones' counts; a lone title is a title), not a
289 suffix word unless it opens the name (S2), not a connective. A
290 particle counts: with nothing after it to attach to it is no
291 particle there ('Mai Le née Nguyen').
292 * WHAT IT TAKES. Every word after it up to the trailing run the
293 name reads as if the clause were not written, and always the
294 first word after it. The run is read over the VIEW -- the head
295 plus the vocabulary-shaped tail, and anything from the first
296 credential that starts a run (S8, #602) -- by `tail_reading`, so
297 the count of words to spare is the clause-free name's. Before a
298 family comma no trailing rule reads the part, and the family
299 part takes a suffix word from anywhere in it: the clause stops
300 at the first one and hands the rest back unbound.
301 * THE RUN IS BOUND. Where a trailing rule reads the part, the take
302 consumes the run and returns the role the reading gave each
303 piece, so no join below this pass can reach into it.
304
305 Computed before any join (the Ph. D. merge aside), as the marker
306 pass always has been (#420): the joins see a name without the
307 clause in it.
308 """
309 if site is ClauseSite.GIVEN_SLOT or site is ClauseSite.TAIL:
310 return None
311 m = next((v for v in range(1, len(pieces))
312 if _is_maiden_marker_piece(pieces[v], tokens)), None)
313 if m is None:
314 return None
315 # the marker may be a phrase, in which case it is several pieces
316 lo = m + _marker_run_pieces(pieces, tokens, m)
317 return _clause_take(pieces, ptags, tokens, one_case, site, ambiguities,
318 m, lo, len(pieces), Role.MAIDEN)
319
320
321#: How a take's reports name the clause and its marker, per role
322_MAIDEN_WORDS = ("maiden name", "maiden marker")
323_ALIAS_WORDS = ("nickname", "alias marker")
324
325
326def _clause_take(pieces: Sequence[Sequence[int]],
327 ptags: Sequence[Set[str]],
328 tokens: Sequence[WorkToken],
329 one_case: bool | None,
330 site: ClauseSite,
331 ambiguities: list[PendingAmbiguity],
332 m: int, lo: int, stop: int, role: Role,
333 skip: Set[int] = frozenset(),
334 run_ended: bool = False,
335 ) -> ClauseIndices | None:
336 """What the marker at pieces[m] takes, its own words being
337 pieces[m:lo]: the maiden take's three questions (see `_maiden_take`)
338 asked for either marker. `stop` is where a boundary ends the clause
339 before the end of the part (rules/N4's patronymic word or another
340 marker), and is `len(pieces)` where none does; `role` is the role
341 the clause's words take; `skip` holds the piece indices an earlier
342 take in the same part has already taken, which the clause-free
343 reading of the trailing run does not count. `run_ended` says the
344 leading title run ends before pieces[m - 1], because an earlier
345 take, or a refused marker the run stops at, stands before it: the
346 word before the marker is past the run, the suffix-word test
347 applying to it and S2's opening-suffix allowance not. None where the
348 marker is an ordinary word.
349 """
350 if site is ClauseSite.TAIL:
351 return None
352 if lo >= stop:
353 return None
354 before = m - 1
355 # where the run is known to end earlier, no title run can reach the
356 # word before the marker: asking `leading_titles` of a slice per
357 # marker made a part of n markers quadratic (the `alias_markers` row
358 # and `test_a_refused_alias_take_asks_the_title_run_once` in
359 # tests/v2/test_benchmark.py)
360 lead = (0 if run_ended
361 else 1 if m == 1 and is_title_piece(pieces[0], ptags[0], tokens)
362 else leading_titles(pieces[:m], ptags[:m], tokens))
363 if (before < lead
364 or (before > lead
365 and is_suffix_piece(pieces[before], ptags[before], tokens))
366 or is_conj_piece(pieces[before], ptags[before], tokens)):
367 return None
368 # a suffix word straight after the marker: nothing was announced
369 if is_suffix_piece(pieces[lo], ptags[lo], tokens):
370 return None
371 # no trailing rule reads the end of the clause: before a family
372 # comma, or where a boundary ends the clause inside the part. A
373 # suffix word ends it there and hands the rest back unbound. In the
374 # given part after a family comma (an alias only, rules/N4) so does
375 # any word that part's own reading may take out of the name -- a
376 # title, a member of the ambiguous class -- which is handed back for
377 # that reading to decide
378 if (site is ClauseSite.FAMILY_PART or site is ClauseSite.GIVEN_SLOT
379 or stop < len(pieces)):
380 end = stop
381 # where the given part's closing run of titles and post-nominals
382 # starts, found once on the first title this loop meets
383 closing: int | None = None
384 for j in range(lo + 1, stop):
385 if "suffix" in ptags[j] or is_suffix_piece(pieces[j], ptags[j],
386 tokens):
387 end = j
388 break
389 if site is not ClauseSite.GIVEN_SLOT:
390 continue
391 if is_title_piece(pieces[j], ptags[j], tokens):
392 if closing is None:
393 closing = _closing_run_start(pieces, ptags, tokens)
394 if j + 1 >= closing:
395 end = j
396 break
397 elif len(pieces[j]) == 1 and not tokens[pieces[j][0]].tags \
398 .isdisjoint(_AMBIGUOUS_CREDENTIAL_TAGS):
399 end = j
400 break
401 return list(range(m, lo)), [(j, role) for j in range(lo, end)]
402 if site is not ClauseSite.TRAILING:
403 assert_never(site)
404 words = _MAIDEN_WORDS if role is Role.MAIDEN else _ALIAS_WORDS
405 c = trailing_candidates(lo, pieces, ptags, tokens)
406 end = len(pieces)
407 released: list[tuple[int, Role]] = []
408 # the view's picks, for the kept member below (#718)
409 picked: tuple[tuple[int, ...], ...] = ()
410 # nothing behind the clause that a trailing rule could take: the
411 # view would be the head alone, and the whole rest is the clause
412 if c < len(pieces):
413 left = (list(range(m)) if not skip
414 else [i for i in range(m) if i not in skip]) + list(
415 range(c, len(pieces)))
416 # where the clause stood in the view: the words before it, less
417 # an earlier take's
418 vm = len(left) - (len(pieces) - c)
419 view = [pieces[i] for i in left]
420 vtags = [ptags[i] for i in left]
421 vrest, vchained, vpeel = tail_reading(
422 peel_walk(leading_titles(view, vtags, tokens), vtags),
423 view, vtags, tokens, one_case)
424 picked = vpeel.picks
425 titles = set(vchained) | set(vpeel.run_titles)
426 in_run = titles | set(vrest[vpeel.names:]) | {
427 q for q in range(vm, len(view)) if "suffix" in vtags[q]}
428 e = len(view)
429 while e - 1 >= vm and (e - 1) in in_run:
430 e -= 1
431 end = c + (e - vm)
432 released = [(j, Role.TITLE if vm + (j - c) in titles
433 else Role.SUFFIX) for j in range(end, len(pieces))]
434 # rules/S12: "where the count takes the pair, the reading is reported" --
435 # the clause-free reading took it, and the take binds it here
436 for j, kind in released:
437 if "split" in ptags[j] and kind is Role.SUFFIX:
438 ambiguities.append(
439 split_credential_report(
440 pieces[j], tokens,
441 name_reading(tokens[pieces[j][0]], role)))
442 # mechanisms.md#AMBIGUITY-AT-THE-DECISION-SITE: "Emit at the
443 # site that takes the branch, not where an ambiguous tag sits"
444 # -- the take consumed the run, so the forks the reading called
445 # on it are reported here, where assign will never see them
446 consumed = {i for j in range(end, len(pieces)) for i in pieces[j]}
447 for piece in (*vpeel.picks, *vpeel.absorbed,
448 *vpeel.numerals):
449 if piece[0] in consumed:
450 ambiguities.append(PendingAmbiguity(
451 AmbiguityKind.SUFFIX_OR_NAME,
452 f"{tokens[piece[0]].text!r} after the {words[0]} "
453 f"reads as a suffix; it may be a name word",
454 tuple(piece),
455 # a name word there ends the clause
456 alternative=name_reading(tokens[piece[0]],
457 role)))
458 # ...and the member the clause KEEPS as its last word: the reading
459 # left it a name word, which is a fork too
460 last = pieces[end - 1]
461 word = tokens[last[0]]
462 # a one-word member: a split credential the clause keeps is one the
463 # count declined, which reports nothing (rules/S12), and its first
464 # word is not the clause's last
465 if len(last) == 1 and not word.tags.isdisjoint(_AMBIGUOUS_CREDENTIAL_TAGS):
466 ambiguities.append(PendingAmbiguity(
467 AmbiguityKind.SUFFIX_OR_NAME,
468 f"{word.text!r} ending the {words[0]} is also a "
469 f"post-nominal; the {words[1]}'s clause keeps it rather "
470 f"than reading it as one", tuple(last),
471 alternative=suffix_reading(word)))
472 elif tuple(last) in picked:
473 # rules/S10: "either reading is reported" -- a numeral the read
474 # declined, for want of words to spare or for its Title case,
475 # which the clause keeps
476 why = ("but the name has no other word to spare for it"
477 if len(word.text.rstrip(".")) == 1
478 else "but written in Title case it leans to the name")
479 ambiguities.append(PendingAmbiguity(
480 AmbiguityKind.SUFFIX_OR_NAME,
481 f"{word.text!r} ending the {words[0]} is a roman numeral, "
482 f"{why}; the {words[1]}'s clause keeps it rather than "
483 f"reading it as a generational suffix", tuple(last),
484 alternative=suffix_reading(word)))
485 elif (released and len(last) == 1 and end - 2 >= lo
486 and reads_as_a_reported_numeral(
487 word.text, word.tags, tokens[pieces[end - 2][0]].text,
488 one_case)):
489 # rules/S10: "a one-letter numeral before a credential is the
490 # family name, and the reading is reported" -- the clause's
491 # twin of assign's report (#721's review): the clause keeps the
492 # numeral its released post-nominal stands behind
493 ambiguities.append(PendingAmbiguity(
494 AmbiguityKind.SUFFIX_OR_NAME,
495 f"{word.text!r} ending the {words[0]} is a roman numeral, "
496 f"but a post-nominal follows it; the {words[1]}'s clause "
497 f"keeps it rather than reading it as a generational suffix",
498 tuple(last), alternative=suffix_reading(word)))
499 return (list(range(m, lo)),
500 [(j, role) for j in range(lo, end)] + released)
501
502
503def _closing_run_start(pieces: Sequence[Sequence[int]],
504 ptags: Sequence[Set[str]],
505 tokens: Sequence[WorkToken]) -> int:
506 """Where the given part's closing run starts: the first piece from
507 which, to the part's end, every piece is a title, a post-nominal or
508 a member of the ambiguous credential class, and `len(pieces)` where
509 the last piece is none of them. A title inside the part is assign's
510 walk's name word, and only a title in this run opens the part's
511 trailing run of titles and post-nominals (a trailing title, H8's
512 salutation), so an alias in the given part after a family comma
513 stops before it (rules/N4). Found once, walking back from the end,
514 so a run of titles after an alias costs a linear walk. A lone roman
515 numeral is no member: it is shaped like an initial, which the alias
516 takes, and a report naming its initial reading would name a field
517 the alias denies it (`test_cases`' alternative check)."""
518 k = len(pieces)
519 while k > 0 and (is_title_piece(pieces[k - 1], ptags[k - 1], tokens)
520 or "suffix" in ptags[k - 1]
521 or is_suffix_piece(pieces[k - 1], ptags[k - 1], tokens)
522 or not tokens[pieces[k - 1][0]].tags.isdisjoint(
523 _AMBIGUOUS_CREDENTIAL_TAGS)):
524 k -= 1
525 return k
526
527
528def _bounds_the_title_run(piece: Sequence[int], ptags: Set[str],
529 tokens: Sequence[WorkToken]) -> bool:
530 """Whether `_pieces.leading_titles` stops at this one-word piece, so
531 the run ends before it: the run's own test, a leading title (H2's
532 shape included) or a dotted title, negated. Its give-back only
533 shortens the run, so where this holds the run ends at or before the
534 piece."""
535 return not (is_leading_title(piece, ptags, tokens)
536 or DOTTED_TITLE_TAG in tokens[piece[0]].tags)
537
538
539# rules/N4: "a marker that counts takes the words after it as the
540# nickname, and is itself dropped" (history: decisions/N4, #1164)
541def _alias_takes(pieces: Sequence[Sequence[int]],
542 ptags: Sequence[Set[str]],
543 tokens: Sequence[WorkToken],
544 one_case: bool | None,
545 site: ClauseSite,
546 ambiguities: list[PendingAmbiguity],
547 ) -> ClauseIndices | None:
548 """Every alias marker's take in the part, left to right, as one
549 ClauseIndices: the markers' pieces, then each alias's pieces with
550 Role.NICKNAME (and, where the last alias ends the name, the
551 trailing run's with the role the clause-free reading gives it).
552
553 One pass over the part rather than a take and a deletion per
554 marker, so a part holding many markers costs no more than a linear
555 walk. A marker counts where M2's marker does, in any part that may
556 hold a name word (the given part after a family comma included,
557 but no tail part), and its alias runs to the first boundary
558 (`_ALIAS_ENDS`) or, with none, as far as M2's clause would.
559 """
560 n = len(pieces)
561 # a tail part is refused in `_clause_take`
562 if n < 3:
563 return None
564 markers: list[int] = []
565 taken: list[tuple[int, Role]] = []
566 skip: set[int] = set()
567 # the first refused alias marker the leading title run stops at: the
568 # run ends before it, as it ends before a take
569 refused: int | None = None
570 m = 1
571 while m < n - 1:
572 # inline: asked per piece of a part holding a marker
573 piece = pieces[m]
574 if len(piece) != 1 or ALIAS_MARKER_TAG not in tokens[piece[0]].tags:
575 m += 1
576 continue
577 # a marker of either kind left a word is no name word for this
578 # one to stand behind ('Osman @ @ Jaki', 'Smith née @ JJ')
579 behind = pieces[m - 1]
580 if len(behind) == 1 and not tokens[behind[0]].tags.isdisjoint(
581 _MARKER_TAGS):
582 if refused is None and _bounds_the_title_run(piece, ptags[m],
583 tokens):
584 refused = m
585 m += 1
586 continue
587 # the first boundary (`_ALIAS_ENDS`); a plain loop, no frame
588 stop = n
589 for j in range(m + 1, n):
590 p = pieces[j]
591 if len(p) == 1 and not tokens[p[0]].tags.isdisjoint(_ALIAS_ENDS):
592 stop = j
593 break
594 # an alias a maiden marker ends in the part holding the family
595 # name reads its end as the name with no clause written does
596 # (rules/M2's "as if the clause were not written"): over the
597 # words before that marker, which end the name there
598 # -- where M2 takes that marker: a name word before it (no
599 # suffix word, no connective) and a word after it that is no
600 # suffix word, M2's head rule
601 end_of_name = n
602 if (stop < n and site is ClauseSite.TRAILING
603 and "vocab:maiden-marker" in tokens[pieces[stop][0]].tags):
604 after = stop + _marker_run_pieces(pieces, tokens, stop)
605 last = stop - 1
606 if (after < n
607 and not is_suffix_piece(pieces[after], ptags[after],
608 tokens)
609 and "suffix" not in ptags[last]
610 and not is_suffix_piece(pieces[last], ptags[last],
611 tokens)
612 and not is_conj_piece(pieces[last], ptags[last],
613 tokens)):
614 end_of_name = stop
615 # a maiden clause before the marker is no word of the name the
616 # alias's trailing run is read against, as the maiden take reads
617 # without the alias (rules/N4's Precedence); a plain loop, no
618 # frame
619 view_skip: Set[int] = skip
620 if stop == end_of_name and site is ClauseSite.TRAILING:
621 for k in range(1, m):
622 if "vocab:maiden-marker" in tokens[pieces[k][0]].tags:
623 # only a clause M2's take would take: ask it, over
624 # the words before the alias, its reports discarded
625 before = _maiden_take(pieces[:m], ptags[:m], tokens,
626 one_case, site, [])
627 if before is not None:
628 view_skip = skip | set(before[0]) | {
629 j for j, _ in before[1]}
630 break
631 take = _clause_take(
632 pieces if end_of_name == n else pieces[:end_of_name],
633 ptags if end_of_name == n else ptags[:end_of_name],
634 tokens, one_case, site, ambiguities, m, m + 1, stop,
635 Role.NICKNAME, view_skip,
636 bool(markers) or (refused is not None and refused < m - 1))
637 if take is None:
638 if refused is None and _bounds_the_title_run(piece, ptags[m],
639 tokens):
640 refused = m
641 m += 1
642 continue
643 markers.extend(take[0])
644 taken.extend(take[1])
645 skip.update(take[0])
646 skip.update(j for j, _ in take[1])
647 m = stop
648 return (markers, taken) if markers else None
649
650
651def _apply_take(take: ClauseIndices, pieces: list[Piece],
652 ptags: list[set[str]],
653 taken: ClauseTake | None = None) -> ClauseTake:
654 """Remove a take's pieces from the segment, adding their tokens to
655 what the marker passes took so far: the markers' tokens, and each
656 other piece with its role. One rebuild rather than a deletion per
657 piece, so a part holding many markers stays linear."""
658 marker_ks, removed = take
659 if taken is None:
660 taken = ([], [])
661 # plain loops, no frame
662 gone = set(marker_ks)
663 for k in marker_ks:
664 taken[0].extend(pieces[k])
665 for k, role in removed:
666 taken[1].append((pieces[k], role))
667 gone.add(k)
668 kept: list[Piece] = []
669 kept_tags: list[set[str]] = []
670 for k in range(len(pieces)):
671 if k not in gone:
672 kept.append(pieces[k])
673 kept_tags.append(ptags[k])
674 pieces[:] = kept
675 ptags[:] = kept_tags
676 return taken
677
678
679#: What `_between_name_words` reads instead of walking: two arrays over
680#: the segment's pieces, giving for each index the nearest piece on
681#: its left and on its right that is NOT a connective -- `-1` and
682#: `len(pieces)` where the run reaches the end. Built by
683#: `_run_neighbours`, and an ALIAS rather than a NamedTuple because a
684#: NamedTuple's __new__ is a frame of its own (decisions/parse-cost).
685_Beside = tuple[list[int], list[int]]
686
687
688def _run_neighbours(pieces: Sequence[Sequence[int]],
689 ptags: Sequence[Set[str]],
690 tokens: Sequence[WorkToken]) -> _Beside:
691 """The nearest piece that is not a connective, on each side of
692 every index.
693
694 EVERY MEMBER OF ONE RUN HAS THE SAME ANSWER, which is the whole
695 of the fix: `_between_name_words` used to walk the run itself, so a
696 name holding a run of n connectives walked it n times and the
697 stage went quadratic in the run's length -- measured 2026-09-20,
698 `"Josep " + "i " * n + "Rovira"` grew 3.8x per doubling against
699 the 2.0x every other shape holds, 59ms at n=800. Two linear
700 passes answer the same question once for the whole segment.
701 `tests/v2/test_benchmark.py`'s `link_run` shape is the guard.
702
703 `is_conj_piece` is asked ONCE per piece, into a list the second
704 pass then reads: asking it in both passes would double the calls,
705 and it is the only per-piece call this builder makes. Recorded in
706 the FIRST pass rather than by a comprehension of its own -- which
707 is a code object on 3.11 and a bytecode saving here rather than a
708 frame one, measured: the profile hook emits no call event for it.
709
710 WHAT IT COSTS A SHORT NAME, because answering for the whole
711 segment is not free where the walk would have stopped at once:
712 this call, plus `is_conj_piece` for the pieces the walk never
713 reached. Re-measured 2026-09-21 on py3.11 against b9ed1429, the
714 whole pair through `tests/v2/test_benchmark.py`'s own
715 `_frames_for` shape -- `Josep Carod i Rovira` 311 -> 313 frames
716 (one call and two more `is_conj_piece` over its four pieces,
717 less the frame the fold below saved) and `Jane Doe nee Puig i
718 Soler` 315 -> 319. An O(1) rise per link-bearing name against an
719 unbounded saving: the same name with a run of 64 links goes
720 6,741 -> 2,587. (The pair first written here read 304 -> 307 and
721 307 -> 312, with 6,741 -> 2,652 for the run of 64. Re-measured
722 2026-09-22 on py3.11, WHICH OF THOSE REPRODUCE is: the two
723 short-name pairs, neither of them; the run-of-64 pair, its left
724 half only -- b9ed1429 reads 6,741 exactly, while 6048eb5d, the
725 tree the 2,652 was taken on, reads 2,651 here. So the interpreter
726 splice ran through a single arrow, which is what the table
727 `tools/perf/call_count.py`'s own docstring warns about. Every
728 figure above is one interpreter, stated.)
729 `tools/perf/call_count.py` is unmoved (parse=406.00,
730 facade=443.00) -- its reference name carries no link -- and so are
731 `John Smith`, `Smith, John`, `Juan Garcia y Lopez` and `Jane Doe
732 nee Smith`, none of which reaches this at all.
733
734 Called only where a generational connective was found in the
735 segment (the `frozen` loop), so no ordinary name pays for it at
736 all.
737
738 Dropping either pass's `not` fails
739 test_a_connective_piece_counts_toward_the_carve_outs_total
740 (mutation-checked 2026-09-20; how the two arrays are READ is
741 checked in `_between_name_words`, which reads them).
742 """
743 n = len(pieces)
744 left = [-1] * n
745 right = [n] * n
746 conj = [False] * n
747 prev = -1
748 for k in range(n):
749 left[k] = prev
750 is_conj = is_conj_piece(pieces[k], ptags[k], tokens)
751 conj[k] = is_conj
752 if not is_conj:
753 prev = k
754 nxt = n
755 for k in range(n - 1, -1, -1):
756 right[k] = nxt
757 if not conj[k]:
758 nxt = k
759 return left, right
760
761
762def _is_rootname(piece: Sequence[int], ptags: Set[str],
763 tokens: Sequence[WorkToken]) -> bool:
764 if len(piece) == 1 and "initial" in tokens[piece[0]].tags:
765 return False
766 # rules/P3: "A connective counts as a name word wherever this
767 # rule counts them, whatever else the vocabulary says the word is"
768 # (#397). The order against the `initial` refusal above decides
769 # nothing, and what makes that safe lives in classify rather than
770 # here: for a single letter it writes `initial` or `conjunction`
771 # and never both, so a one-case `I`/`i` arrives with no conjunction
772 # tag whichever test runs first -- measured, hoisting this arm
773 # above the refusal moves no field, report or initial on any
774 # corpus name under three name orders, and no test. INLINE rather
775 # than a call to is_conj_piece: this runs once per piece of every
776 # name (frame budget).
777 if ("conjunction" in ptags
778 or (len(piece) == 1 and "conjunction" in tokens[piece[0]].tags)):
779 return True
780 return not (is_title_piece(piece, ptags, tokens)
781 or is_prefix_piece(piece, ptags, tokens)
782 or is_suffix_piece(piece, ptags, tokens))
783
784
785def _is_lone_letter(piece: Sequence[int], tokens: Sequence[WorkToken],
786 one_case: bool | None) -> bool:
787 """A piece of one word that is one letter, with or without its
788 period: the letter P13 links. Not a connective, the word P13 asks
789 about, nor a lowercase letter in a name of mixed case, which S10
790 reads as the generation by its writing."""
791 if len(piece) != 1 or "conjunction" in tokens[piece[0]].tags:
792 return False
793 letter = composed(tokens[piece[0]].text.rstrip("."))
794 return (len(letter) == 1 and letter.isalpha()
795 and not numeral_settled_by_case(letter, one_case))
796
797
798def _is_name_word(piece: Sequence[int], ptags: Set[str],
799 tokens: Sequence[WorkToken]) -> bool:
800 return not (is_conj_piece(piece, ptags, tokens)
801 or is_title_piece(piece, ptags, tokens)
802 or is_suffix_piece(piece, ptags, tokens))
803
804
805def _link_the_last_letter(pieces: list[list[int]], ptags: list[set[str]],
806 tokens: Sequence[WorkToken],
807 one_case: bool | None, keep_a_name: bool) -> None:
808 """P13's two joins at the end of the part holding the family name,
809 made ahead of P3's carve-out. `keep_a_name` marks the whole name's
810 part, where a piece past the title run must stand in front of the
811 join, so the name keeps a word for its given name. The connective
812 is looked for before the title run is counted, so a part with no
813 connective where P13 looks pays only the walk back from the end,
814 not leading_titles' count."""
815 # rules/P13: "A single-letter connective in front of a lone letter
816 # ending the name words joins it to the word before" and "A
817 # connective with nothing to link joins the word before it alone"
818 # -- both joins, made ahead of P3's carve-out (decisions/P13
819 # (#1097, #1098))
820 e = len(pieces) - 1
821 lone = False
822 while e >= 0:
823 piece = pieces[e]
824 if _is_lone_letter(piece, tokens, one_case):
825 lone = True
826 break
827 # rules/P13: "with nothing behind it but suffixes or a
828 # trailing title H5 reads" -- H5's own word test, asked rather
829 # than copied, so the walk steps over every title the chain
830 # takes (decisions/P13, #1168)
831 if not (is_trailing_title_word(piece, tokens)
832 or is_suffix_piece(piece, ptags[e], tokens)
833 or (e > 0 and len(piece) == 1
834 # reads_as_generation's own first test, asked at C
835 # level as _comma._whole_name and _group_segment's
836 # P3 numeral count ask it, so a word that is no
837 # numeral pays no frame for the call
838 and ROMAN.match(tokens[piece[0]].text.rstrip("."))
839 is not None
840 and ends_in_a_generation(
841 [tokens[pieces[e - 1][-1]].text,
842 tokens[piece[0]].text], one_case))):
843 break
844 e -= 1
845 if e < 1:
846 return
847 # the connective: in front of the lone letter, or the word the walk
848 # stopped at
849 at = e - 1 if lone else e
850 if (at < 1 or len(pieces[at]) != 1
851 or "conjunction" not in tokens[pieces[at][0]].tags):
852 return
853 word = tokens[pieces[at][0]]
854 text = composed(word.text)
855 if lone:
856 if not (len(text) == 1 and text.isalpha()):
857 return
858 elif not (text.isalpha()
859 and not (one_case and len(text) == 1
860 and text.lower() != text.upper())
861 and "vocab:suffix" not in word.tags
862 and not (len(text) > 1 and e + 1 < len(pieces)
863 and is_trailing_title_word(pieces[e + 1], tokens))):
864 return
865 if (at - 1 >= leading_titles(pieces, ptags, tokens) + keep_a_name
866 and _is_name_word(pieces[at - 1], ptags[at - 1], tokens)):
867 merge_pieces(pieces, ptags, at - 1, e + 1)
868
869
870# rules/P3: "a word the rest of the parse reads as a name word
871# rather than as a generation, a credential or an honorific, looked
872# for past any run of connectives standing between. A connective with
873# nothing to its right is connecting nothing, and a word of that
874# vocabulary ending a name, or standing before the credential a name
875# ends with, is the generation it also spells" (#397) -- the WHOLE
876# clause, its second sentence included, because that sentence is what
877# this predicate answering `False` means. Reading it as a generation
878# is the CALLER's half: `_group_segment`'s `frozen` set is where a
879# connective this refuses is placed as the generation.
880# `Sequence[Sequence[int]]` rather than `Sequence[Piece]`: this reads a
881# piece and never edits one (widened when the maiden walk was a
882# second caller, before #601).
883def _between_name_words(k: int, lo: int, hi: int,
884 pieces: Sequence[Sequence[int]],
885 ptags: Sequence[Set[str]],
886 tokens: Sequence[WorkToken],
887 beside: _Beside) -> bool:
888 """Whether such a word stands on EACH side of the connective piece
889 at `k`.
890
891 Both sides in one call because neither caller ever wants one: a
892 connective is placed to join only where a name word stands on both
893 sides of it, so the two answers were always ANDed at the call site
894 and the left one short-circuits the right either way. One frame per
895 generational connective rather than two, which is the whole of the
896 saving -- the left arm below is the old left call and the right arm
897 the old right one, unchanged (#397 follow-up).
898
899 `lo` and `hi` bound the name's own words: assign peels the pieces
900 below `lo` as its leading titles and those from `hi` up as its
901 trailing suffix run, so a piece outside that span is a credential
902 or an honorific however it is spelled, and the numeral or bare
903 acronym the peel takes ('i V', 'i MA') is inside `hi` by
904 construction rather than by a second reading of the vocabulary
905 (mechanisms.md#ONE-PREDICATE-PER-QUESTION).
906
907 Inside the span the suffix and title tests still run, because
908 neither bound reaches a credential or an honorific standing in
909 the MIDDLE of a name ('Josep Jr. i Rovira', 'Josep Dr. i
910 Rovira'): the peel walks from the end and stops at the first name
911 word, the title run from the front.
912
913 The answer steps over connectives because a RUN of them joins as
914 one ('Carod i y Rovira'), so the word this rule is about is the
915 first one past the run -- and where the run runs out ('Juan i e')
916 there is no name word on that side at all. `beside` is where that
917 stepping already happened:
918 `_run_neighbours` walked every run once for the whole segment, so
919 this reads an index rather than walking to it. A SENTINEL OUT OF
920 RANGE is how "the run ran out" arrives --
921 -1 on the left, `len(pieces)` on the right -- and each bound test
922 below turns it into False, exactly as the walk did when it ran
923 here and stopped at the same place. `lo` is never negative and
924 `hi` never past `len(pieces)`, so neither sentinel can pass the
925 bound, and the piece tests are never asked about an index that is
926 not one.
927
928 Mutation-checked 2026-09-21, every arm of both sides by a NAMED
929 test. Reading the LEFT array for the right arm too fails
930 test_a_connective_with_nothing_to_its_right_does_not_join;
931 the RIGHT array for the left arm too fails
932 test_a_leading_title_on_the_left_is_no_name_word.
933 The bounds, WIDENED to the whole segment rather than dropped --
934 dropping the right one indexes past the pieces on the sentinel and
935 raises instead of failing a test -- fail
936 test_the_marker_is_not_the_name_word_on_the_links_left (left) and
937 test_the_right_hand_test_reads_the_peel_not_the_suffix_piece
938 (right). Either piece test on the LEFT fails
939 test_a_credential_or_honorific_mid_name_is_no_name_word_either;
940 either on the RIGHT fails
941 test_a_credential_or_honorific_mid_name_on_the_right_too, which is
942 the row the fold asked for: while this was two per-side calls a
943 mutation hit both sides at once and the left-hand rows covered for
944 the right-hand ones, whose own rows stand at the END of the name
945 where `hi` refuses them first. SWAPPING the two arrays outright is
946 an EQUIVALENT mutant and no test fails: the two arms are ANDed, so
947 which array answers which side is not a question the conjunction
948 can see.
949 """
950 left = beside[0][k]
951 if not (lo <= left < hi
952 and not is_suffix_piece(pieces[left], ptags[left], tokens)
953 and not is_title_piece(pieces[left], ptags[left], tokens)):
954 return False
955 right = beside[1][k]
956 return (lo <= right < hi
957 and not is_suffix_piece(pieces[right], ptags[right], tokens)
958 and not is_title_piece(pieces[right], ptags[right], tokens))
959
960
961# rules/S12: "where the count declines it, the pair is the two words
962# it is written as" -- after the trailing read, which is where the
963# count is asked in a main segment
964def _settle_splits(pieces: list[Piece], ptags: list[set[str]]) -> None:
965 """Split every merged split credential left in `pieces` back into
966 its two words, in place: a pair the trailing read declined reads
967 as it reads unmerged. One a connective join took into a wider piece
968 keeps the join and loses the tag (the only shape that reaches it
969 is a pair beside a connective, 'Pharm D and')."""
970 k = 0
971 while k < len(pieces):
972 if "split" in ptags[k]:
973 if len(pieces[k]) == 2 and ptags[k] == {"split"}:
974 a, b = pieces[k]
975 pieces[k:k + 1] = [[a], [b]]
976 ptags[k:k + 1] = [set(), set()]
977 k += 2
978 continue
979 ptags[k] = ptags[k] - {"split"}
980 k += 1
981
982
983# rules/P12: "the two words are one name unit, past the first name word"
984# -- past the piece P5's leading join reads, which this leaves as it
985# was, its reserve included, save a pair read from its second word,
986# which joins there too; classify's tag says the word and the token
987# after it are a listed phrase, a `completes_any` bound word before a
988# plain word, or a plain word before a listed second word (history:
989# decisions/P12, #694, #1464, #1072)
990def _join_bound_phrases(pieces: list[Piece], ptags: list[set[str]],
991 tokens: Sequence[WorkToken],
992 joined_heads: set[int]) -> None:
993 # built in one pass: a merge per pair would shift every piece
994 # behind it, a quadratic in a run of pairs (merge_pieces' note)
995 k = leading_titles(pieces, ptags, tokens)
996 # P5's first word, save a pair joined from its second word, which
997 # joins there too (#1072)
998 if not (k < len(pieces) and BOUND_SECOND_TAG in tokens[pieces[k][0]].tags):
999 k += 1
1000 out, out_tags = pieces[:k], ptags[:k]
1001 n = len(pieces)
1002 joined = False
1003 while k < n:
1004 word = pieces[k]
1005 if (k + 1 < n and len(word) == 1 and not ptags[k]
1006 and BOUND_PHRASE_TAG in tokens[word[0]].tags
1007 and pieces[k + 1] == [word[0] + 1] and not ptags[k + 1]):
1008 joined_heads.add(word[0])
1009 word.extend(pieces[k + 1])
1010 out.append(word)
1011 out_tags.append(set())
1012 joined = True
1013 k += 2
1014 continue
1015 out.append(word)
1016 out_tags.append(ptags[k])
1017 k += 1
1018 if joined:
1019 pieces[:] = out
1020 ptags[:] = out_tags
1021
1022
1023def _group_segment(seg: tuple[int, ...], additional: int,
1024 tokens: Sequence[WorkToken],
1025 bound_join: BoundJoin = BoundJoin.STRICT,
1026 ambiguities: list[PendingAmbiguity] | None = None,
1027 given_name_titles: Set[str] = frozenset(),
1028 opens_the_name: bool = False,
1029 *,
1030 one_case: bool | None,
1031 site: ClauseSite,
1032 reads: list[TailRead | None] | None = None,
1033 phrase_heads: set[int] | None = None,
1034 given_first: bool,
1035 ) -> tuple[list[Piece], list[set[str]], ClauseTake | None]:
1036 pieces: list[Piece] = [[i] for i in seg]
1037 ptags: list[set[str]] = [set() for _ in seg]
1038 # Out-parameter, same shape as _assign_main: forks are reported
1039 # where they are decided. A caller that passes None (or a throwaway
1040 # list) suppresses reporting -- see group() for when that applies.
1041 if ambiguities is None:
1042 ambiguities = []
1043 # The maiden take reports on this same channel: it reports only at
1044 # the TRAILING site, which group() never suppresses.
1045
1046 # ph-d merge first: "Ph." "D." adjacent -> one suffix piece,
1047 # where the lexicon lists `phd` as unambiguous suffix vocabulary
1048 # (#1000)
1049 # (decisions/phd-merge; v1 fix_phd did this by regex on the
1050 # raw string)
1051 # A suffix never BEGINS a name: position outranks the vocabulary
1052 # match (#371). This merge is what makes a leading "Ph." "D." a
1053 # credential at all -- every other suffix-shaped word standing
1054 # first already falls out as a title (H2's abbreviation clause, or
1055 # TITLES membership) or as a name word, so the pair is the only
1056 # shape that reaches the defect, and it reached it by emptying the
1057 # family: "Ph. D. Van Johnson" read given 'Van Johnson' with no
1058 # surname at all.
1059 #
1060 # WHERE THE INPUT BEGINS, and that is v1's own boundary rather
1061 # than a new one: fix_phd was a regex requiring a preceding space
1062 # (`\s(ph\.?\s+d\.?)`), so it could never fire at the head of the
1063 # string and fired everywhere else -- mid-name as readily as
1064 # trailing. Three tests, because "the head" has three meanings
1065 # here and only one of them is v1's:
1066 # `k == 0` the first PIECE, which is not the first word --
1067 # extract_delimited removes a bracketed or quoted
1068 # clause before segment runs, so `"Bob" Ph. D. John
1069 # Smith` reaches this with the pair at k == 0 and a
1070 # word standing before it in the input. v1 merges
1071 # there; declining broke parity on 112 measured
1072 # names, every one opening with a quote or bracket.
1073 # `a[0] == 0` the first TOKEN, which is v1's boundary.
1074 # seg_idx 0 and not after a family comma: a credential run
1075 # legitimately opens segment 1 ("Smith, Ph. D.
1076 # Jr.", C8's credential run in the listing form), and segment 0 before a
1077 # comma is the family the comma named, where v1
1078 # merges too ("Ph. D., John" reads last 'Ph. D.').
1079 #
1080 # A leading TITLE is therefore NOT stepped over, unlike the #367
1081 # scan below, and the two disagree on purpose: that scan asks
1082 # where the NAME begins, this asks where the STRING does. `Sir
1083 # Ph. D. Van Johnson` keeps suffix 'Ph. D.' with an empty family,
1084 # which is #371's symptom surviving one word to the left -- 1.4.0
1085 # parity, stated as a boundary in rules/S2 rather than fixed
1086 # here, because "the first piece of the name" cannot be computed
1087 # before this merge: `is_leading_title` is true of `Ph.` itself,
1088 # so the scan would step over the very piece being judged.
1089 #
1090 # Every other split credential ('Pharm. D.', `_vocab.split_pair`'s
1091 # "split" answer) merges under the same head test as a member of
1092 # the ambiguous class, where a rule reads such a member: in a main
1093 # segment, where S2's read below decides it by the count, kept
1094 # whole where the read takes it and split back into its two words
1095 # where it does not (`_settle_splits`), so a declined pair reads
1096 # exactly as the two words read; and in the given part after a
1097 # family comma behind the given word, where S5's walk reads it,
1098 # merged ahead of the joins so the particle chain stops in front of
1099 # it and P5's bound join declines it as it declines a suffix word,
1100 # and a pair declined there is middle-name text whole or split.
1101 # (A connective beside a pair keeps it from merging at all, in
1102 # classify.)
1103 # Not in the part before a family comma, which reads no member as
1104 # a suffix ('Smith MA, John'). Classify tagged each pair's first
1105 # word, so the test here is a tag.
1106 #
1107 # Written into fresh lists in one pass, `pos` being the index the
1108 # piece stands at once the merges before it are made: a merge in
1109 # place shifts the rest of the list (`merge_pieces`' comment), and
1110 # a run of pairs would shift it once per pair. A merged pair is
1111 # never a member of another, so the scan moves past both words.
1112 splits = False
1113 given_from: int | None = None
1114 out: list[Piece] = []
1115 out_tags: list[set[str]] = []
1116 n = len(pieces)
1117 k = 0
1118 while k < n:
1119 a = pieces[k]
1120 add: str | None = None
1121 if k + 1 < n:
1122 b = pieces[k + 1]
1123 tags = tokens[a[0]].tags
1124 pos = len(out)
1125 if (len(a) == 1 and len(b) == 1
1126 and not (opens_the_name and pos == 0 and a[0] == 0)):
1127 if SPLIT_CREDENTIAL_TAG in tags:
1128 add = "suffix"
1129 elif SPLIT_MEMBER_TAG in tags:
1130 if site is ClauseSite.TRAILING:
1131 add = "split"
1132 splits = True
1133 elif site is ClauseSite.GIVEN_SLOT:
1134 if given_from is None:
1135 given_from = leading_titles(
1136 out + pieces[k:], out_tags + ptags[k:],
1137 tokens)
1138 if pos > given_from:
1139 add = "split"
1140 if add is None:
1141 out.append(a)
1142 out_tags.append(ptags[k])
1143 k += 1
1144 continue
1145 a.extend(pieces[k + 1])
1146 out.append(a)
1147 out_tags.append(joined_tags(ptags, k, k + 2, add={add}))
1148 k += 2
1149 pieces[:] = out
1150 ptags[:] = out_tags
1151
1152 # rules/M2: "A marker that counts takes the words after it as
1153 # the maiden name, and is itself dropped" (history:
1154 # decisions/M2) -- the marker pass (#274), and it runs
1155 # BEFORE every join below. Each join rule asks a question about the
1156 # name -- how many words it has (P3's carve-out, P5's reserve),
1157 # what the word after a particle or a bound word is -- and the
1158 # marker and the maiden name are not part of that name: they leave.
1159 # Asked while they were still pieces, the count answered for a name
1160 # that would not exist ('juan y garcia nee jones' counted five, 'y'
1161 # joined, and the family was empty once the clause left: #418), and
1162 # a join could absorb the marker before the pass looked for a lone
1163 # one ('Jane van der Berg née y Jones' kept the marker in the
1164 # family: #412). Removing the pieces first makes both impossible by
1165 # construction, with no stop on the chain (#399, #417) and no
1166 # exclusion in the reserve (#411) left to keep in step.
1167 #
1168 # The tokens are not touched here: this function reads them and
1169 # returns what it took, and group() records the drop and the roles.
1170 taken: ClauseTake | None = None
1171 # rules/N4's alias markers first: an alias stops at a maiden marker,
1172 # and the maiden take is then asked of what is left, so either may
1173 # follow the other (decisions/N4). A plain loop, no frame, so a name
1174 # with no marker pays no call (decisions/parse-cost)
1175 for piece in pieces:
1176 if len(piece) == 1 and ALIAS_MARKER_TAG in tokens[piece[0]].tags:
1177 take = _alias_takes(pieces, ptags, tokens, one_case, site,
1178 ambiguities)
1179 if take is not None:
1180 taken = _apply_take(take, pieces, ptags)
1181 break
1182 take = _maiden_take(pieces, ptags, tokens, one_case,
1183 site, ambiguities)
1184 if take is not None:
1185 taken = _apply_take(take, pieces, ptags, taken)
1186
1187 # S2's trailing run, read once below once the connectives have
1188 # joined (#614)
1189 read: TailRead | None = None
1190 tail_pieces: list[Piece] = []
1191 tail_ptags: list[set[str]] = []
1192 # too few pieces for the read: a split credential has no words to
1193 # spare (rules/S4)
1194 if splits and len(pieces) + additional < 3:
1195 _settle_splits(pieces, ptags)
1196 if len(pieces) + additional >= 3:
1197 # the part holding the family name -- the end of the name
1198 # only under a given-first order -- and only where a one-word
1199 # connective stands: a plain loop, no frame, for a name with none
1200 if ((site is ClauseSite.TRAILING and given_first)
1201 or site is ClauseSite.FAMILY_PART):
1202 for piece in pieces:
1203 if (len(piece) == 1
1204 and "conjunction" in tokens[piece[0]].tags):
1205 _link_the_last_letter(
1206 pieces, ptags, tokens, one_case,
1207 keep_a_name=site is ClauseSite.TRAILING)
1208 break
1209 # rules/P3: "A connective that is also generational
1210 # vocabulary joins only where a name word stands on each side
1211 # of it" (#397). `frozen` holds the TOKEN index of every such
1212 # connective missing a name word on one side: it is the
1213 # generation it also spells, so no join of its own reaches it,
1214 # it may not merge into a run, and it does not count toward
1215 # the carve-out total. A token index because the joins below
1216 # move piece indices. A neighbour's join can still absorb it:
1217 # `join_connectives`' neighbour-join loop skips a frozen piece
1218 # only as the join's subject.
1219 #
1220 # Asked here, of the pieces as classify left them and of the
1221 # neighbours' class, because after a merge the absorbed suffix
1222 # IS the word on the right. No length test: the clause names a
1223 # class, not a spelling, while the three-word carve-out below
1224 # stays single-letter because its own sentence says so. Only a
1225 # connective of the suffix vocabulary reaches the body, so a
1226 # name with none pays no call for this test. decisions/P3.
1227 frozen: set[int] = set()
1228 # whether any connective is left free to join: a segment with
1229 # none skips the rootname count and the shared loop, both of
1230 # which then do nothing (0 of 3,153 such calls changed a piece
1231 # over the corpora and case table, #617's /simplify), as
1232 # `_comma._reading_pieces` skips it for the part after a comma
1233 free = False
1234 lo = hi = -1
1235 beside: _Beside = ([], [])
1236 for k, piece in enumerate(pieces):
1237 tok = tokens[piece[0]]
1238 if len(piece) != 1 or "conjunction" not in tok.tags:
1239 continue
1240 if "vocab:suffix" not in tok.tags:
1241 free = True
1242 continue
1243 # The bounds and the run memo, computed once per segment
1244 # and only where such a connective was found, so the cost
1245 # is the link's own and no ordinary name pays any of it.
1246 if hi < 0:
1247 lo = leading_titles(pieces, ptags, tokens)
1248 # H5's reading and not the peel over the pieces as
1249 # WRITTEN: a title standing behind the suffix run
1250 # hides it from `trailing_start`, which then answers
1251 # `len(pieces)` and hands this loop a credential as
1252 # the name word on the link's right. 'John Quincy
1253 # Adams i MA Prof.' joined to family 'Adams i MA' with
1254 # no report at all, where 'John Quincy Adams i MA' --
1255 # the same name, one title shorter -- reads family
1256 # 'Adams', suffix 'i MA' and reports the acronym
1257 # (#397 second review).
1258 hi = trailing_start_past_titles(lo, pieces, ptags,
1259 tokens,
1260 one_case=one_case)
1261 # ONE ANSWER PER RUN: every member of a contiguous run
1262 # of connectives has the same nearest name word on
1263 # each side, and asking per member walked the run once
1264 # per member -- quadratic in its length, 3.8x per
1265 # doubling measured at `b9ed1429`.
1266 beside = _run_neighbours(pieces, ptags, tokens)
1267 if _between_name_words(k, lo, hi, pieces, ptags, tokens,
1268 beside):
1269 free = True
1270 else:
1271 frozen.add(piece[0])
1272 if free:
1273 total = sum(_is_rootname(p, t, tokens)
1274 for p, t in zip(pieces, ptags)
1275 if p[0] not in frozen) + additional
1276 # rules/P3: "a numeral ending the name, or standing before
1277 # the listed suffix words a name ends with, that the trailing fork
1278 # reads as the generation is no word of the three, as a
1279 # listed one is not" -- the C3 count's question, asked by
1280 # its predicate; decisions/C3 (#893). The suffix words are
1281 # stepped over by their tag and the shape tested by a
1282 # C-level match, so a name ending in a word pays no frame;
1283 # the walk stops short of every listed suffix word, a listed
1284 # numeral included, so `last` is never one
1285 e = len(pieces) - 1
1286 while (e > 0 and len(pieces[e]) == 1
1287 and "vocab:suffix" in tokens[pieces[e][0]].tags):
1288 e -= 1
1289 last = tokens[pieces[e][0]]
1290 if (e > 0 and len(pieces[e]) == 1
1291 and ROMAN.match(last.text.rstrip(".")) is not None
1292 and pieces[e][0] not in frozen
1293 and ends_in_a_generation(
1294 [tokens[pieces[e - 1][-1]].text, last.text],
1295 one_case)):
1296 total -= 1
1297 # The threshold of P3's carve-out ("except a single-letter
1298 # connective in a three-word name, which stays a name word")
1299 # reads the ROOTNAME count, and since #397 a connective counts
1300 # ITSELF toward that count WHERE IT IS JOINING, so a connective
1301 # that is also suffix vocabulary no longer raises the bar for
1302 # its own join and no longer lowers it for an unrelated one
1303 # ("Carod y Rovira i" counted the trailing generation and let
1304 # the `y` join).
1305 join_connectives(pieces, ptags, tokens, letter_stays=total < 4,
1306 titles_only=False, frozen=frozen)
1307 # rules/S2's trailing run is read ONCE, here -- after P3's
1308 # connective joins, which do not depend on it and make the
1309 # units it counts, and before the particle chain and the
1310 # bound-given join, which do -- and bound (#614): the run is
1311 # split off, the chain and the join group the name in front of
1312 # it, and assign places the run off this reading. Group had
1313 # asked the peel before and after those joins -- the chain's
1314 # stop and its re-ask after its own merges, the reserve's two
1315 # views -- because they change the pieces the count reads; the
1316 # read counts the units the chain will build instead
1317 # (_pieces.read_trailing_run), so there is nothing to re-ask,
1318 # and no join takes a word the run took ('John van der Berg
1319 # Prof.' keeps its title). The main segments only (no comma,
1320 # or the part before a suffix comma); a family comma's parts, a
1321 # part past a comma and a segment of fewer than three pieces --
1322 # which no join reaches anyway -- read as before, and so does a
1323 # run holding a name piece (_pieces.read_trailing_run).
1324 # The particles straight behind each other are merged first,
1325 # into the one piece the chain would open its run with, so the
1326 # read counts and absorbs the run as that piece (#625);
1327 # `premerged` keeps which runs the merge made, for the chain's
1328 # report below.
1329 premerged: Set[int] = frozenset()
1330 if site is ClauseSite.TRAILING:
1331 n = leading_titles(pieces, ptags, tokens)
1332 premerged, lead = merge_particle_runs(pieces, ptags, tokens, n)
1333 found = read_trailing_run(pieces, ptags, tokens, one_case, n,
1334 lead)
1335 if found is not None:
1336 read, start = found
1337 tail_pieces, tail_ptags = pieces[start:], ptags[start:]
1338 del pieces[start:]
1339 del ptags[start:]
1340 # the read has decided every split credential: one it took
1341 # left with the run, and one still here is two name words
1342 if splits:
1343 _settle_splits(pieces, ptags)
1344 # rules/S2: "a trailing word of the suffix vocabulary reads as a
1345 # suffix" -- on a main segment the run read above decides it
1346 # and is split off already; elsewhere the chain stops where
1347 # assign's peel begins (`trailing_run_start`, trailing titles
1348 # included, in the given part after a family comma; else
1349 # `trailing_start`; the H5 paragraph below explains the
1350 # titles). decisions/P2 (#424).
1351 # rules/P2: "a particle joins the words after it into one name
1352 # part, the join running until the next particle starts a group of
1353 # its own, a trailing suffix begins" -- and on to the maiden marker
1354 # (M2) or the name's end; the final group reads as the family name,
1355 # earlier groups by position. (history: decisions/P2)
1356 # rules/P4: "a particle in the name's leading position chains
1357 # nothing: the words stay separate" (history: decisions/P2)
1358 #
1359 # "Leading" is the first piece of the NAME, past assign's own
1360 # title run (`leading_titles`), unless a word in that run is
1361 # also a particle: then the last such word leads in the run's
1362 # place (`chain_lead`, decisions/P2 (#624)). Computed once,
1363 # before the loop: every merge below starts past this index, so
1364 # none can move it. Suffix pieces are deliberately not skipped
1365 # when finding the leading piece (decisions/P2). A maiden
1366 # marker still here is one the consumer declined, an ordinary
1367 # word to the chain. decisions/M2 (#417).
1368 name_start = leading_titles(pieces, ptags, tokens)
1369 leading = chain_lead(pieces, ptags, tokens, name_start)
1370 # rules/P2: "a trailing suffix begins" -- where it begins
1371 # is read by assign's peel over the pieces as they stand
1372 # (#424), once per segment and kept as a length from the end,
1373 # which the chain's merges ahead of it do not move -- except
1374 # where a particle that is suffix vocabulary too (vd, mc, do)
1375 # starts the run: the prefix run below takes it as a particle,
1376 # as P6 reads it after a comma, and 'John van Mc' keeps family
1377 # 'van Mc' (every baseline's reading). A suffix WORD stops the
1378 # chain where S8 would start its run at it, a word S8 starts no
1379 # run at ('bin Abd Rahman') or declines for its writing with a
1380 # name word behind it ('binti Md Salleh') being the chain's
1381 # (#1177), and the trailing
1382 # run -- the numeral, or the bare acronym with words to spare
1383 # -- stops it where the suffix-piece test alone did not ('John
1384 # van der Berg V' read family 'van der Berg V'). The chain
1385 # takes both forks, and where no run was read ahead of it it
1386 # asks again after its merges whether the acronym still has
1387 # the pieces the fork counted (below).
1388 # the run read above is already split off (#614), so the chain
1389 # stops at the end of what is left.
1390 # rules/H5: "the title is TRANSPARENT to the suffix reading"
1391 # -- in the given part after a family comma too, where assign's
1392 # walk reads the trailing title run, so the chain stops before
1393 # the run of suffixes and titles `tail_reading` takes there
1394 # rather than before the suffixes alone, and does not carry a
1395 # trailing title into the particle's name ('Smith, John van der
1396 # Berg Prof.' reads title 'Prof.' as 'Smith, John Prof.' does,
1397 # #623). The bound matters only where a particle stands past the
1398 # chain's lead, so it is not asked otherwise: the chain then
1399 # merges nothing (the test is `is_prefix_piece`'s, inline).
1400 # rules/C2: "a part past the second comma holds no name word"
1401 # -- assign reads such a part wholly as suffixes and its title
1402 # words as titles, so the chain builds no name unit there and is
1403 # not run, and a title word behind a particle run stays a word
1404 # C2 can read ('John Smith, Jr., van der Berg Prof.', #636). The
1405 # part after a suffix comma reaches no chain either: `_comma.
1406 # decide` binds it and empties its segment before any join
1407 # (#613).
1408 chains = False
1409 if read is None and site is not ClauseSite.TAIL:
1410 for k in range(leading + 1, len(pieces)):
1411 if ("prefix" in ptags[k]
1412 or len(pieces[k]) == 1
1413 and "particle" in tokens[pieces[k][0]].tags):
1414 chains = True
1415 break
1416 given_slot = site is ClauseSite.GIVEN_SLOT
1417 tail = (0 if not chains
1418 else len(pieces) - (
1419 trailing_run_start(name_start, pieces, ptags, tokens,
1420 one_case) if given_slot
1421 else trailing_start(name_start, pieces, ptags, tokens,
1422 one_case=one_case)))
1423 # the members the chain reports below, which the read's picks
1424 # then give up (#614)
1425 took: set[tuple[int, ...]] = set()
1426
1427 def chain(tail: int) -> None:
1428 # `pieces[:titled]` are known to be leading titles. A merge
1429 # from k to j changes only indices from k on, and k only
1430 # grows, so a piece behind k is final and its answer can
1431 # be kept: the
1432 # cursor makes the all-titles-ahead test below one walk per
1433 # chain rather than one per chain site (#559).
1434 titled = 0
1435 k = 0
1436 while k < len(pieces):
1437 if k <= leading or not is_prefix_piece(pieces[k],
1438 ptags[k], tokens):
1439 k += 1
1440 continue
1441 j = chain_run_end(k, pieces, ptags, tokens,
1442 len(pieces) - tail, one_case,
1443 given_slot)
1444 # The other half of PARTICLE_OR_GIVEN. _assign reports the
1445 # fork when an ambiguous particle stays a lone leading piece
1446 # ("Van Johnson" -> given under the default order, family
1447 # under FAMILY_FIRST); the chain here takes the opposite
1448 # branch when the particle is not the name's leading piece.
1449 # A fork whose two sides are decided in different stages
1450 # needs an emitter in each.
1451 #
1452 # Narrow, and #367 is why. `titled == k` says every
1453 # piece ahead of this one is a title, and the loop
1454 # skipped every piece up to `leading`, so `leading` is
1455 # STRICTLY before k -- one of those titles, and, being
1456 # before the title run's end, a prefix as well
1457 # (`chain_lead`): a word in both vocabularies (`st`,
1458 # `freiherr` and the rank particles by default, or any overlap a caller
1459 # configures). A plain title alone can no longer put a
1460 # particle off the name's leading piece; it is stepped
1461 # over and _assign reports the fork instead.
1462 #
1463 # What that leaves is wider than one shape: any number of
1464 # plain title pieces, then a piece in BOTH vocabularies,
1465 # then any number of further titles, then the ambiguous
1466 # particle whose chain claims something. "Freiherr von
1467 # Richthofen" is the canonical spelling and the one
1468 # tests/v2/cases.py and tests/v2/test_parser.py lead with,
1469 # but "St Van Johnson", "Do St Johnson" (the chained
1470 # particle itself in both vocabularies) and "Dr. Do van
1471 # Johnson" (a plain title AHEAD of the both-vocabulary
1472 # word) all reach here too. What none of them can do is
1473 # dispense with the both-vocabulary WORD. The conjunction
1474 # merge is the only other way a piece acquires `title` or
1475 # `prefix`, and it cannot manufacture the pair: it derives
1476 # from ONE neighbor, which is the left one whenever there
1477 # is a left one, and its right operands are always fresh
1478 # pieces (the loop runs left to right, so nothing to the
1479 # right has been merged yet). Both tags therefore have to
1480 # come from the piece it extends, which bottoms out at a
1481 # lone token in both vocabularies.
1482 #
1483 # j > k + 1 is what makes this a DECISION rather than a
1484 # shape: when the chain stops at the next piece (the
1485 # trailing run, a suffix word S8 would start its run
1486 # at, or a suffix-vocabulary particle's stop) the inner
1487 # scan never advances, the merge from k to k+1 folds a
1488 # piece into itself, and the particle stays a lone
1489 # leading piece -- nothing
1490 # was chained, and _assign reports that case instead.
1491 # Without this the two emitters both fire on the same token.
1492 # A run merged ahead of the read (`premerged`, #625) has
1493 # claimed the particles behind it already, so its chain
1494 # is a decision though `j == k + 1` ('Freiherr von der').
1495 # (Tag test first: it is a set lookup and almost no name
1496 # has an ambiguous particle, while is_leading_title is a
1497 # call per piece.)
1498 if ((j > k + 1 or pieces[k][0] in premerged)
1499 and "vocab:particle-ambiguous"
1500 in tokens[pieces[k][0]].tags):
1501 while titled < k and is_leading_title(
1502 pieces[titled], ptags[titled], tokens):
1503 titled += 1
1504 if titled == k:
1505 i = pieces[k][0]
1506 ambiguities.append(PendingAmbiguity(
1507 AmbiguityKind.PARTICLE_OR_GIVEN,
1508 f"{tokens[i].text!r} was chained onto the "
1509 f"following name piece; it is also a given "
1510 f"name in other names",
1511 (i,),
1512 # where it would stand unchained is
1513 # assign's to name
1514 alternative=name_reading(tokens[i],
1515 Deferred.UNCHAINED)))
1516 # rules/S4: "A BARE ambiguous acronym is consumed
1517 # only when the name has words to spare — as the second
1518 # of two words it stays the family name — and at the
1519 # slots that report, either reading carries the
1520 # ambiguity flag"
1521 #
1522 # The chain's half of SUFFIX_OR_NAME: once the chain
1523 # takes the acronym, the lone piece assign reports on
1524 # is gone, so the fork reports here
1525 # (mechanisms.md#AMBIGUITY-AT-THE-DECISION-SITE). It is
1526 # the DECLINED reading: the scan stops at
1527 # `len(pieces) - tail`, before every piece the peel
1528 # took, and a re-peel truncates the first pass's
1529 # appends with the pieces. `j > k + 1` is its floor
1530 # too, and `not is_prefix_piece(last, ...)` leaves a
1531 # word in both vocabularies ending a PARTICLE run to
1532 # P6's fork; it costs a frame, so it is tested last. A
1533 # member S2's read picked is reported here and leaves
1534 # the read's picks. decisions/S6 (#289), decisions/S2
1535 # (#614).
1536 last = pieces[j - 1]
1537 # A numeral S2's read declined (rules/S10, #718) is not
1538 # reported here: it stays one of the read's picks, and
1539 # assign words it from the role it ends in ('Freiherr
1540 # von Richthofen V', 'a family name'), the chain taking
1541 # nothing the read had not already given up
1542 if (j > k + 1 and len(last) == 1
1543 and not tokens[last[0]].tags.isdisjoint(
1544 _AMBIGUOUS_CREDENTIAL_TAGS)
1545 and not is_prefix_piece(last, ptags[j - 1],
1546 tokens)):
1547 ambiguities.append(PendingAmbiguity(
1548 AmbiguityKind.SUFFIX_OR_NAME,
1549 f"{tokens[last[0]].text!r} is both a post-nominal "
1550 f"and an ordinary name; the particle chain took "
1551 f"it into the name rather than reading it as a "
1552 f"post-nominal",
1553 tuple(last),
1554 alternative=suffix_reading(tokens[last[0]])))
1555 took.add(tuple(last))
1556 merge_pieces(pieces, ptags, k, j, drop={"prefix"})
1557 k += 1
1558
1559 # Where the run was read above (#614) it is split off and
1560 # `tail` is 0, so none of what follows runs, as it does not
1561 # where no particle stands past the lead (#623); it is the path
1562 # for the segments that read no run above -- a family comma's
1563 # two name parts and a run with a name piece inside it (a part past the
1564 # second comma makes no chain, #636) -- and the given part
1565 # reaches it still
1566 # ('Smith, Freiherr van Berg X.Y.Z.', the row that holds it).
1567 #
1568 # The peel was read over the pieces as they stand, and the
1569 # chain's own merges can change what it counts: behind a word
1570 # in both the title and particle vocabularies the scan above
1571 # stops where assign's title peel does not (P4, #367), so the
1572 # chain takes the name's first word, and the acronym the fork
1573 # counted with three pieces meets assign with two -- 'Freiherr
1574 # von Berg Ma' read given 'von Berg', family 'Ma' (1.4.0's
1575 # reading; the reviews found it behind the claim that the
1576 # merges leave the count alone). So the peel is asked again
1577 # over the pieces the chain leaves, and where it no longer
1578 # takes what the chain stopped before, the chain runs again
1579 # without that stop: what assign will not peel is a name word,
1580 # and the chain takes it. The numeral cannot flip (a chain
1581 # group is never initial-shaped), so the second run is the
1582 # acronym's alone, and rare; the snapshot is one copy per
1583 # segment with a trailing run, linear like the rest.
1584 if tail:
1585 kept = ([list(q) for q in pieces], [set(t) for t in ptags],
1586 len(ambiguities))
1587 chain(tail)
1588 start = leading_titles(pieces, ptags, tokens)
1589 left = len(pieces) - (
1590 trailing_run_start(start, pieces, ptags, tokens, one_case)
1591 if given_slot
1592 else trailing_start(start, pieces, ptags, tokens,
1593 one_case=one_case))
1594 if left < tail:
1595 pieces[:], ptags[:] = kept[0], kept[1]
1596 del ambiguities[kept[2]:]
1597 chain(left)
1598 elif site is not ClauseSite.TAIL:
1599 chain(0)
1600 if read is not None and took:
1601 # built, not `_replace`d: two frames a call
1602 peel = read.peel
1603 read = TailRead(read.tail, read.titles, read.run_titles, Peel(
1604 peel.names, peel.numerals,
1605 tuple([p for p in peel.picks if p not in took]),
1606 peel.anchors, peel.run_titles, peel.absorbed,
1607 peel.declined))
1608 # rules/P5: "a recognized bound given-name word joins the
1609 # word after it into one given name" (history: decisions/P5)
1610 # -- bound given names: the first non-title piece joins the next
1611 # ONCE (pairwise, v1 parity: 'Salem, Abdul Rahman Ahmed' keeps
1612 # Ahmed a middle name). BoundJoin encodes v1's reserve_last.
1613 # "the first non-title piece" by assign's count (#424): group's
1614 # title test does not see H2's unlisted abbreviations, and
1615 # 'Xyz. abdul John Smith' joined nothing where 'Dr. abdul John
1616 # Smith' read given 'abdul John'.
1617 fk = leading_titles(pieces, ptags, tokens)
1618 if (bound_join is not BoundJoin.DISABLED
1619 and fk + 1 < len(pieces)
1620 and len(pieces[fk]) == 1
1621 and "vocab:bound-given" in tokens[pieces[fk][0]].tags):
1622 # P5 joins the bound word to "the word after it", and a
1623 # marker is not a name word -- it is the announcement that
1624 # another name follows. The only marker left by now is one
1625 # the consumer declined (nothing after it, or nothing but
1626 # a suffix), and the join must still not take it: 'Berg,
1627 # abdul nee PhD' read given 'abdul nee', and 'Berg, abdul
1628 # nee' clears the LENIENT reserve the same way. Measured
1629 # rather than assumed -- dropping this undid #411 on
1630 # exactly that row. Nor is a suffix piece (#421) --
1631 # rules/P5: "nor a word of the unambiguous suffix
1632 # vocabulary (S2), wherever position will then place it"
1633 # -- and declining it is also what keeps merge_pieces' tag
1634 # union from making the joined piece a suffix piece.
1635 # rules/P5: "nor a title word a trailing rule reads as a
1636 # title" -- after a family comma one H5's trailing run takes
1637 # from the given part, read as the comma-less name reads it,
1638 # plus the bare salutations H8 adds after a family comma
1639 # (`salutations=True`),
1640 # which the LENIENT join reads no peel for and so asks here,
1641 # only where a title word or one written short follows ('Berg, abdul Prof.',
1642 # #637; where the given part's own walk then reads the words
1643 # behind it otherwise, the title stays a name word, which
1644 # rules/P5 accepts); in a part past the second
1645 # comma any title word, which C2 reads as a title ('John
1646 # Smith, Jr., abdul Dr. Smith', #640). A title word standing
1647 # in the name is a name word and joins ('abdul Sir Smith
1648 # Berg', 'Berg, abdul Prof. Ali').
1649 # A credential split across a space (rules/S12) is declined
1650 # as its one-word spelling is: merged in the given part
1651 # before this join, so the particle chain stops in front of
1652 # it too ('Rahman, Abdul MB ChB', 'Smith, John van Pharm D')
1653 # After a family comma a member its capitals settle as the
1654 # credential (rules/S6) is declined as a suffix word is: the
1655 # join would read it as the given name's second word, where
1656 # the given part's trailing slot or the run S8 starts takes
1657 # it ('Smith, Abdul MA'); with no comma nothing would, and
1658 # the join stands ('Abdul MA Smith')
1659 nxt, nxt_tags = pieces[fk + 1], ptags[fk + 1]
1660 if (_is_maiden_marker_piece(nxt, tokens)
1661 or is_suffix_piece(nxt, nxt_tags, tokens)
1662 or "split" in nxt_tags
1663 or (bound_join is BoundJoin.LENIENT and len(nxt) == 1
1664 and AMBIGUOUS_ACRONYM_TAG in tokens[nxt[0]].tags
1665 and settled_by_case(tokens[nxt[0]], one_case))
1666 or ((site is ClauseSite.TAIL
1667 or bound_join is BoundJoin.LENIENT)
1668 and (is_title_piece(nxt, nxt_tags, tokens)
1669 # after a family comma only: a title
1670 # written short that may be a given name,
1671 # which H5's run takes with its period
1672 # (#999), the tail_reading test deciding;
1673 # past a second comma C2 reads only a
1674 # listed title
1675 or (site is not ClauseSite.TAIL
1676 and len(nxt) == 1
1677 and TRAILING_TITLE_TAG
1678 in tokens[nxt[0]].tags))
1679 and (site is ClauseSite.TAIL
1680 or fk + 1 in tail_reading(
1681 peel_walk(fk, ptags), pieces, ptags,
1682 tokens, one_case,
1683 salutations=True)[1]))):
1684 pass
1685 elif bound_join is BoundJoin.LENIENT:
1686 # post-comma the family is fixed and the pair is the
1687 # given whatever follows, so no peel is read
1688 # (decisions/P5, #423), save the title test above
1689 merge_pieces(pieces, ptags, fk, fk + 2, drop={"title"})
1690 else:
1691 # rules/P5: "the trailing suffix run (S2) and the
1692 # trailing title run (H5), each read over what the other
1693 # leaves until neither takes anything more, are read
1694 # once, before the join is tried, and the name words they
1695 # leave are the words to spare" (history: decisions/P5).
1696 # That reading is the one above, after P3's joins and
1697 # before the chain (#614): the run is
1698 # split off, every piece left is a name piece, and the
1699 # join leaves one fewer. Nor can the join move a suffix
1700 # -- rules/P5: "a word the run left as a name word
1701 # stays one, whatever the join makes of the word in
1702 # front of it" -- since nothing in group reads the run
1703 # again after it.
1704 #
1705 # Where the run was not read above (a run with a name
1706 # piece inside it, _pieces.read_trailing_run), the
1707 # reserve still reads both views, as it did everywhere
1708 # before #614: the join tried on the pieces as it would
1709 # leave them, the reading assign runs over each (the
1710 # ONE function, _pieces.tail_reading), the suffixes
1711 # compared as the peeled pieces themselves -- 'abdul
1712 # Smith V' peels the V unjoined and nothing joined (no
1713 # word to spare there, rules/S10), 'abdul Smith Ma'
1714 # peels the acronym unjoined and keeps it joined.
1715 if read is not None:
1716 same_suffixes = True
1717 chained = False
1718 names_after = len(peel_walk(fk, ptags)) - 1
1719 else:
1720 rest, chain_took, before = tail_reading(
1721 peel_walk(fk, ptags), pieces, ptags, tokens,
1722 one_case)
1723 view, view_tags = list(pieces), list(ptags)
1724 view[fk:fk + 2] = [pieces[fk] + pieces[fk + 1]]
1725 view_tags[fk:fk + 2] = [joined_tags(ptags, fk, fk + 2,
1726 drop={"title"})]
1727 view_rest, _, after = tail_reading(
1728 peel_walk(fk, view_tags), view, view_tags, tokens,
1729 one_case)
1730 same_suffixes = (
1731 [tuple(view[j]) for j in view_rest[after.names:]]
1732 == [tuple(pieces[j]) for j in rest[before.names:]])
1733 chained = fk + 1 in chain_took
1734 names_after = after.names
1735 # rules/P5: "a trailing roman numeral the run takes
1736 # (S10), or a bare acronym it takes, or a trailing title
1737 # word the run takes, is no word to spare" -- and the join joins
1738 # two NAME words, so a piece the chain takes is no more
1739 # joinable than a marker or a suffix piece is: 'Sir
1740 # abdul Prof.' reads title 'Sir Prof.', given 'abdul'.
1741 # Read off the UNJOINED view, the one that still has
1742 # the title as a piece of its own -- the join would
1743 # swallow it, and a swallowed title is a title the
1744 # joined view can no longer see. The suffix comparison
1745 # alone said this while the counts were subtractions,
1746 # by leaving the chained piece in the tail it compared;
1747 # under the shared reading the chain takes it out of
1748 # both views, so the rule is asked as the rule.
1749 # A given-name title ahead of the bound word asserts
1750 # that a given name follows -- the assertion H1 reads
1751 # when it keeps "Sir John" a given name -- so behind
1752 # one there is no family to spare (#369). Asked of the
1753 # title run through the ONE predicate post_rules asks
1754 # for H1, so the two rules cannot disagree about what
1755 # one run asserts; what it reads is the whole run's key
1756 # or that key's LAST word (#489). And it is the same
1757 # RUN on both sides: `range(fk)` is the pieces AHEAD of
1758 # the bound word, and H1 asks its own question of the
1759 # leading run too (_post_rules._addressing_run). They
1760 # did disagree for one commit -- H1 keyed every TITLE
1761 # token, so the trailing title in 'Sir abdul rahman
1762 # Prof.' joined this run and flipped the join's own
1763 # premise, handing the licensed pair to the family.
1764 # Reading the leading run at both sites is what makes
1765 # that unreachable rather than merely unlikely: a
1766 # trailing title is behind the word, and neither site
1767 # can see it. What H2's unlisted abbreviations do
1768 # inside such a run is the predicate's own business,
1769 # and its docstring is where they are worked through.
1770 # The licence lifts the reserve for two name
1771 # WORDS: the piece the join would take must be one word
1772 # -- a particle chain is the family name P2 built ('Sir
1773 # abdul van der Berg' keeps family 'van der Berg').
1774 licensed = (fk > 0 and len(pieces[fk + 1]) == 1
1775 and _run_addresses_by_given(
1776 (tokens[i].text
1777 for k in range(fk)
1778 for i in pieces[k]),
1779 given_name_titles))
1780 reserve = BoundJoin.LENIENT if licensed else BoundJoin.STRICT
1781 if (not chained and same_suffixes
1782 and names_after >= reserve):
1783 # the pair is a given name whatever tag the word
1784 # carried (rules/P5); joined_tags says why the
1785 # title tag is dropped. Pinned in test_group.py.
1786 merge_pieces(pieces, ptags, fk, fk + 2, drop={"title"})
1787 # `phrase_heads` is passed only for a part holding a tagged word
1788 if (phrase_heads is not None and bound_join is not BoundJoin.DISABLED
1789 and site is not ClauseSite.TAIL):
1790 _join_bound_phrases(pieces, ptags, tokens, phrase_heads)
1791 if reads is not None:
1792 reads.append(read)
1793 pieces.extend(tail_pieces)
1794 ptags.extend(tail_ptags)
1795 return pieces, ptags, taken
1796
1797
1798def group(state: ParseState) -> ParseState:
1799 # rules/C1's decision, read once now that classify has tagged
1800 # the words and before any join below can reach the part after the
1801 # comma (#613); a postnominal part comes back bound, its segment
1802 # emptied (a name with no comma asks nothing)
1803 if state.structure is Structure.FAMILY_COMMA:
1804 state = _comma.decide(state)
1805 tokens = list(state.tokens)
1806 dropped = list(state.dropped)
1807 ambiguities = list(state.ambiguities)
1808 all_pieces: list[tuple[tuple[int, ...], ...]] = []
1809 all_ptags: list[tuple[frozenset[str], ...]] = []
1810 all_reads: list[TailRead | None] = []
1811 # v1 parity: additional_parts_count=1 applies only to FAMILY_COMMA
1812 # parts; the SUFFIX_COMMA pre-comma segment gets 0.
1813 additional = 1 if state.structure is Structure.FAMILY_COMMA else 0
1814 # v1 expand_suffix_delimiter parity (#206): tail segments (wholly
1815 # consumed as suffixes by assign) are cut at their delimiter-core
1816 # tokens, which land in `dropped` as the maiden marker does; the
1817 # built-in cores, which no v1 release read, cut them too (#889)
1818 cores = delimiter_cores(state.policy.extra_suffix_delimiters)
1819 # identity tests, not a dict keyed by the enum: Enum.__hash__ is a
1820 # Python method, a frame per key on every parse
1821 family_comma = state.structure is Structure.FAMILY_COMMA
1822 tail_start = (2 if family_comma
1823 else 1 if state.structure is Structure.SUFFIX_COMMA
1824 else None)
1825 for seg_idx, seg in enumerate(state.segments):
1826 if family_comma:
1827 bound_join = (BoundJoin.LENIENT if seg_idx == 1
1828 else BoundJoin.DISABLED)
1829 else:
1830 bound_join = BoundJoin.STRICT
1831 # Suppressed after a family comma for the same reason _assign
1832 # suppresses it there: the family name is already fixed, so
1833 # there is no fork left to report. A tail segment needs no
1834 # suppression: group makes no particle chain there (#636) and
1835 # takes no maiden clause (rules/M2, #601), so nothing in group
1836 # reports in one. rules/C2: "a part the parse consumes wholly
1837 # as suffixes raises no report that a word of it was read as a
1838 # name"
1839 tail = tail_start is not None and seg_idx >= tail_start
1840 # #601: where a maiden clause would stand, off the three facts
1841 # already in hand here -- which decides whether a marker counts
1842 # at all and which rule reads the end of the part.
1843 if tail:
1844 site = ClauseSite.TAIL
1845 elif family_comma:
1846 site = (ClauseSite.GIVEN_SLOT if seg_idx == 1
1847 else ClauseSite.FAMILY_PART)
1848 else:
1849 site = ClauseSite.TRAILING
1850 # rules/C10: "a suffix delimiter parts the suffix words on each
1851 # side of it as a comma would" (#549): the segment is
1852 # grouped as the parts between its cores, each read exactly as
1853 # the comma twin's own segment would be, and the cores are
1854 # dropped (v1 expand_suffix_delimiter parity, #206), where
1855 # post_rules' entry pass reads them back as entry boundaries.
1856 # No join or link search reaches across a core, because none
1857 # of them ever sees one, and a maiden marker in a tail part is
1858 # an ordinary word (#601). A one-token segment that
1859 # is its core keeps it (v1 expand() splits within a part, never
1860 # erases a lone part); a segment of several cores and nothing
1861 # else drops them all, as the #206 drop did.
1862 # Accumulated in a list and frozen once per part: a tuple
1863 # extended per token is quadratic in the part's length, C-level
1864 # work no frame guard sees (#553's class; review of #549).
1865 # Measured 2026-10-03, py3.11, 'Smith, John, ' + 'PhD ' * n +
1866 # '- MD' under a ' - ' delimiter: 4.7x for n 4,000 -> 16,000 as
1867 # written, the default policy's own 4.5x, where the tuple read
1868 # 8.0x. No clock guard: _PREFIXED_SHAPES parses with the default
1869 # policy and _POLICY_SHAPES repeats a unit with no prefix, and a
1870 # tail needs both, so a row would mean a table of its own.
1871 parts: list[tuple[int, ...]] = [seg]
1872 if tail and cores and len(seg) > 1:
1873 parts = []
1874 current: list[int] = []
1875 for i in seg:
1876 if tokens[i].text in cores:
1877 dropped.append(i)
1878 if current:
1879 parts.append(tuple(current))
1880 current = []
1881 else:
1882 current.append(i)
1883 if current:
1884 parts.append(tuple(current))
1885 pieces = []
1886 ptags = []
1887 seg_reads: list[TailRead | None] = []
1888 for part in parts:
1889 # a plain loop, no frame: a name with no tagged pair pays
1890 # nothing (rules/P12)
1891 heads: set[int] | None = None
1892 for i in part:
1893 if BOUND_PHRASE_TAG in tokens[i].tags:
1894 heads = set()
1895 break
1896 part_pieces, part_ptags, taken = _group_segment(
1897 part, additional, tokens, bound_join,
1898 None if family_comma else ambiguities,
1899 state.lexicon._sets.given_name_titles,
1900 opens_the_name=(seg_idx == 0 and not family_comma),
1901 one_case=state.one_case,
1902 site=site, reads=seg_reads, phrase_heads=heads,
1903 given_first=state.policy.name_order[0] is Role.GIVEN)
1904 if heads is not None:
1905 # the tag stays only on a pair P12 joined, which O6
1906 # counts as one word; P5's pair at the start, and a
1907 # pair a chain or a comma kept apart, count as two
1908 for i in part:
1909 if BOUND_PHRASE_TAG in tokens[i].tags and i not in heads:
1910 # BOUND_SECOND_TAG stays, as `vocab:bound-given`
1911 # does: the unit readers count the pair by it
1912 # where no join was made, before a family comma
1913 # (#1072)
1914 tokens[i] = copy_with(
1915 tokens[i], tags=tokens[i].tags - {BOUND_PHRASE_TAG})
1916 pieces.extend(part_pieces)
1917 ptags.extend(part_ptags)
1918 # the marker is dropped and the maiden name's tokens become
1919 # MAIDEN (#274); which pieces those are was settled in
1920 # _group_segment, before the joins
1921 if taken is not None:
1922 marker_piece, removed_pieces = taken
1923 dropped.extend(marker_piece)
1924 # the maiden name, and the trailing run the take
1925 # consumed with the roles the clause-free name's
1926 # reading gave it (#601)
1927 for piece, role in removed_pieces:
1928 for i in piece:
1929 tokens[i] = copy_with(tokens[i], role=role)
1930 # Group used to decide the suffix ENTRY, marking a continuation
1931 # token "joined" between pieces off segment SHAPE -- `tail` by
1932 # index, ORed since #429 with segment_suffix_reading's
1933 # per-piece content verdict, gated per piece and sticky across
1934 # an interleaved title. post_rules derives that from the
1935 # commas the writer typed instead (#436/#437, rules/R1),
1936 # which is what the input answers directly. The stickiness
1937 # survives by construction rather than by code:
1938 # 'Smith, MD Dr. PhD' has no comma between MD and PhD and a
1939 # title between them renders elsewhere, so they join, while
1940 # 'Smith Jr., Mr. Jr.' has the writer's own comma and they do
1941 # not.
1942 # continuation tokens of a suffix-merged piece (the ph-d merge)
1943 # carry the stable "joined" tag: the suffix string view joins
1944 # SUFFIX tokens with ", ", and the tag lets it heal the split
1945 for piece, piece_tags_ in zip(pieces, ptags):
1946 if "suffix" in piece_tags_ and len(piece) > 1:
1947 for i in piece[1:]:
1948 tokens[i] = copy_with(
1949 tokens[i], tags=tokens[i].tags | {"joined"})
1950 # map over the type, not a generator: the conversion runs in C,
1951 # where a generator cost a frame per piece
1952 all_pieces.append(tuple(map(tuple, pieces)))
1953 all_ptags.append(tuple(map(frozenset, ptags)))
1954 all_reads.append(seg_reads[0] if len(seg_reads) == 1 else None)
1955 # rules/M1: "a leading recognized marker is dropped where the
1956 # clause holds a word past it" and "a clause of nothing but its
1957 # marker keeps its words" — Then's marker drop and the Then bullet
1958 # on a marker-only clause, for a marker inside EXTRACTED maiden
1959 # content (decisions/M1, #329). Classify tags
1960 # such a marker like any other token -- what the #274 rule above
1961 # lacks is not the TAG but the token: extract claims a delimited
1962 # clause and tokenize gives its tokens Role.MAIDEN up front, so
1963 # segment (main stream = role is None) leaves them out of every
1964 # segment, they never enter `pieces`, and a rule that walks pieces
1965 # cannot reach them.
1966 #
1967 # Scoped to the CLAUSE, via state.extracted (one role + inner span
1968 # per delimited region), rather than to a maiden token's
1969 # neighbours. Both reasons are load-bearing:
1970 # * Role.MAIDEN is not proof of extraction -- the #274 rule above
1971 # sets it too, on the bare form, earlier in this same function.
1972 # A neighbour test would fire there and eat the 'Nee' out of
1973 # "Jane Smith nee Nee Jones". Keying on extracted spans puts
1974 # the bare path out of reach by construction.
1975 # * Separate clauses are separate content. In "(Nee) (Jones)" the
1976 # two land as one contiguous run of maiden tokens, so only the
1977 # clause bound keeps the lone "(Nee)" intact.
1978 # Drop the clause's LEADING MARKER only when the clause holds a
1979 # word past it: `Nee` is a real surname (Irish Ni/Nee, and a
1980 # Chinese romanization), so a one-token "(Nee)" is a maiden name,
1981 # not a marker. The marker and no more, whatever the clause holds
1982 # past it: cases.py's maiden_marker_delimited_three_token_clause is
1983 # the row that bounds this in both directions, every other
1984 # delimited row having a two-token clause where the two readings
1985 # agree. The marker is one token for a word entry and the whole run
1986 # for a phrase one ('z domu'), which is why the loop below counts
1987 # continuation tags rather than assuming one.
1988 # Spans index the original string by the anti-#100
1989 # invariant, and script_segment only ever splits a token into
1990 # sub-slices, so containment stays exact.
1991 #
1992 # Bisect rather than scan the token list per clause: that is
1993 # quadratic in the number of delimited pairs (decisions/parse-cost,
1994 # 2026-08-02 #329, holds the measurement). Same idiom, and the same
1995 # reason, as _extract._overlaps and _tokenize's origin resolution.
1996 # test_benchmark's maiden_pairs shape is the guard.
1997 # rules/N4: "the marker dropped as M3 drops it" -- a nickname
1998 # clause opening with an alias marker, by the same walk (decisions/N4 (#1164)).
1999 # A plain loop over a map of a C getter, no frame: a name with no
2000 # clause pays nothing, and one with a clause no frame for the starts
2001 starts = list(map(_SPAN_START, tokens)) if state.extracted else []
2002 for role, clause in state.extracted:
2003 # extract gives a clause one of the two roles
2004 tag = ("vocab:maiden-marker" if role is Role.MAIDEN
2005 else ALIAS_MARKER_TAG)
2006 # first token starting at or after the clause opens; tokens
2007 # are span-sorted and group never reorders or resizes them
2008 first = bisect.bisect_left(starts, clause.start)
2009 if first >= len(tokens) or tag not in tokens[first].tags:
2010 continue
2011 # How many tokens the marker is: one, or the whole run of a
2012 # phrase entry, as classify recorded it. Same walk the
2013 # piece test above makes, in token-index space. An alias
2014 # marker is one word, and no token carries its continuation.
2015 run = marker_run_length(
2016 tokens[k].tags for k in range(first + 1, len(tokens)))
2017 # Testing the end of the token AFTER the run proves the run
2018 # AND that token are all inside: tokens do not overlap and
2019 # are index-ordered, so every earlier one ends no later,
2020 # and bisect already put first.start at or after
2021 # clause.start. That is also the "more than the marker"
2022 # test, since the tokens inside a clause are contiguous in
2023 # index order -- a clause holding nothing but its marker
2024 # keeps its words, exactly as a one-token "(Nee)" does.
2025 # rules/M3: "a marker followed by a comma is no marker"
2026 # -- asked of the same word extract's M3 test asks it of
2027 if (first + run < len(tokens)
2028 and tokens[first + run].span.end <= clause.end
2029 and not comma_follows_marker(tokens[first + run].text)):
2030 dropped.extend(range(first, first + run))
2031 return copy_with(
2032 state, tokens=tuple(tokens), pieces=tuple(all_pieces),
2033 piece_tags=tuple(all_ptags), dropped=tuple(dropped),
2034 tail_reads=tuple(all_reads), ambiguities=tuple(ambiguities))