Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/nameparser/_pipeline/_pieces.py: 12%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

652 statements  

1"""Shared piece-level predicates for pipeline stages. 

2 

3How a PIECE reads -- its tokens, plus the tags classify wrote on them 

4and the tags group derived for the piece -- where _vocab answers how a 

5WORD reads from text alone. Both are consulted by more than one 

6stage; the split is by what the question takes, not by 

7which stage happens to ask (mechanisms.md#ONE-PREDICATE-PER-QUESTION). 

8_vocab points here from its own side: "Text-level tests used by more 

9than one stage; piece-level ones live in _pieces, the sibling layer 

10over tokens-plus-tags." own_words (#289/#516) answers over the whole 

11token STREAM rather than one piece -- pieces do not exist yet at the 

12stages that call it -- but the question is still piece-shaped, not 

13word-shaped: it reads token ROLE, which _vocab's text-level tests 

14never take. 

15 

16Before this module those predicates lived in _group, not because 

17grouping owned them but because assign imported group and could not be 

18imported back, so group was the only place both stages could reach. 

19They arrived there that way across three PRs -- #424 brought 

20is_leading_title, leading_titles and trailing_start, #425 the peel 

21(peel_walk, peel_trailing), #429 the no-name-segment test that 

22#430 turned into segment_suffix_reading. 

23is_title_piece and is_suffix_piece are older than any of that: they 

24were group's from its first commit, and travel because the others 

25call them. 

26 

27The import that forced all of it is the one #439 removed: assign no 

28longer names _group at all. What still holds is the rule that replaced 

29it, and tests/v2/test_layering.py is where it is written down -- a 

30piece predicate may not depend on a stage, in either direction. 

31 

32The S2 trailing peel travels as the unit the decisions describe -- 

33peel_walk, peel_trailing and trailing_start together -- though only 

34the first two cross a stage boundary. trailing_titles joins them 

35because it reads what that peel left: the two answer one question 

36between them, where the tail of a name stops being the name -- and 

37tail_reading is that one question, running them against each other to 

38their fixed point for the two stages that must not disagree about the 

39answer. 

40 

41Layering: imports _state and _vocab only; segment, script_segment, 

42classify, group, assign, post_rules and _comma import it (segment, 

43script_segment and classify for the #289/#516 own-words span alone) -- and neither of the two it imports imports it 

44back. 

45 

46Naming follows _vocab's: inside an already-private module the leading 

47underscore marks module-PRIVATE, so the names other stages call are 

48bare and only the internals keep it (_PERIOD_ABBREV here). Getting that 

49backwards -- which this module did until the underscores came off -- 

50costs a reader the one cheap way to tell a shared predicate from a 

51helper. 

52""" 

53from __future__ import annotations 

54 

55import unicodedata 

56from collections.abc import ( 

57 Callable, Container, Iterable, Mapping, Sequence, Set) 

58from typing import NamedTuple 

59 

60from nameparser._pipeline._state import ( 

61 AMBIGUOUS_ACRONYM_TAG, AMBIGUOUS_WORD_TAG, 

62 GENERATION_WORD_TAG, TITLE_CASE_NAME_TAG, GIVEN_ABBREVIATION_TAG, NAME_ROLES, SHAPE_ACRONYM_TAG, SUFFIX_OR_UNREAD, AmbiguityKind, PendingAmbiguity, 

63 CHAIN_TITLE_TAG, DOTTED_TITLE_TAG, PendingReading, 

64 WorkToken, 

65) 

66from nameparser._pipeline._vocab import ( 

67 _CASELESS_LETTERS, _DIGRAPH_INITIALS, _PERIOD_ABBREV, _ROMAN, _SPELLED_INITIAL, 

68 Lean, ambiguous_lean, 

69 in_unabbreviating_script, is_one_case, 

70 is_listed_numeral, is_single_letter_numeral, numeral_leans_to_the_name, 

71 numeral_settled_by_case, reads_as_generation, tag_marker_runs, 

72) 

73 

74 

75# rules/P3: "both questions asked of a name here and in P8 — how 

76# many words it has, and whether it is written in one case — are 

77# asked of the name's OWN words: a maiden marker taken as one, and the 

78# words it takes (M2), are not among them, and neither is a delimited 

79# clause (N1, M1)" (history: decisions/P3) 

80def own_words(tokens: Sequence[WorkToken], comma_offsets: Sequence[int], 

81 markers: frozenset[str], 

82 marker_tags: Mapping[int, str] | None = None, 

83 ) -> tuple[list[str], int]: 

84 """The name's OWN word texts and the index the maiden clause 

85 starts at -- one span for the two stages that ask about it 

86 (#289/#516). 

87 

88 Own words are the role-less tokens before the clause: a delimited 

89 clause's tokens arrive from extract with a role already set, and 

90 everything from a maiden marker on is the clause. Appending a 

91 clause to a name must not change how a word in the name reads. 

92 

93 `marker_tags` is the map `_vocab.tag_marker_runs` already built, 

94 index -> "vocab:maiden-marker"/"...-cont"; a caller that has it 

95 (classify) hands it over and pays no second walk. A caller that 

96 runs BEFORE those tags exist (segment) omits it, and this 

97 function calls `tag_marker_runs` itself to build the SAME map 

98 classify would -- not an approximation of it, which is what a 

99 from-scratch text walk (this module's earlier `first_marker_head`) 

100 could disagree with on a name where a marker's head opens an entry 

101 but no run completes ('z' of 'z domu'): measured, 'ANNA z Nowak, 

102 MD' flipped the recorded one-case verdict under that approximation 

103 (decisions/P3). Sharing the exact function instead makes the 

104 two paths agree by construction, not by corpus luck. 

105 

106 Takes tokens/comma_offsets/markers rather than a whole ParseState: 

107 both call sites have all three already, and passing them lets this 

108 function sit beside the piece predicates rather than in _vocab 

109 (mechanisms.md#ONE-PREDICATE-PER-QUESTION; the 

110 _post_rules.suffix_entries precedent, AGENTS.md's named exception) 

111 -- it answers with the SPAN, where `tag_marker_runs` answers only 

112 which tokens open a run. 

113 

114 `marker_tags`' keys must arrive in index order for the walk below 

115 to find the SMALLEST head in one pass: `tag_marker_runs` walks its 

116 tokens left to right, so the first head it records is already the 

117 smallest, and a caller building its own map must preserve that 

118 order too. 

119 

120 A plain tuple, not a NamedTuple: measured 2026-09-17, wrapping 

121 this in a `NamedTuple` (this module's `Peel` is one) cost the 

122 reference name one more frame (413.00 vs the 412.00 band this 

123 commit must hold) -- a NamedTuple's `__new__` is itself a call, 

124 where a bare tuple literal is not. `Peel` can afford the frame 

125 because assign builds one only where the trailing peel actually 

126 ran; `own_words` returns on every parse. 

127 """ 

128 if marker_tags is None: 

129 marker_tags = tag_marker_runs(tokens, comma_offsets, markers) 

130 clause_at = len(tokens) 

131 for i, tag in marker_tags.items(): 

132 if tag == "vocab:maiden-marker" and tokens[i].role is None: 

133 clause_at = i 

134 break 

135 return ([t.text for t in tokens[:clause_at] if t.role is None], 

136 clause_at) 

137 

138 

139# rules/H3: "successive title words at the start of the part 

140# carrying the given name chain into one title; a title word 

141# elsewhere in the name does not" 

142def is_title_piece(piece: Sequence[int], ptags: Set[str], 

143 tokens: Sequence[WorkToken]) -> bool: 

144 if "title" in ptags: 

145 return True 

146 return len(piece) == 1 and "vocab:title" in tokens[piece[0]].tags 

147 

148 

149# rules/P4: "a particle in the name's leading position chains 

150# nothing" -- WHERE that position is, asked once, by group's chain and 

151# the trailing read's unit count (#624) 

152def chain_lead(pieces: Sequence[Sequence[int]], ptags: Sequence[Set[str]], 

153 tokens: Sequence[WorkToken], n: int) -> int: 

154 """The particle chain's leading position, given `n`, the end of 

155 the leading title run (`leading_titles`): the last title in the run 

156 that is also a particle, else the first piece past the run. A title 

157 is no name word, so the first piece past the run leads; a word in 

158 both vocabularies ('Freiherr', 'St') leads in its stead and puts 

159 the particle behind it inside a name ('Freiherr von Berg', 'St van 

160 Johnson'), and of several such words the last leads, all being 

161 titles ('Freiherr St John Smith' as 'Dr. St John Smith'). No 

162 particle stands between the lead and the run's end, so the chain 

163 opens no unit inside the titles. 

164 

165 The run is read as walked, before H3's give-back: a title the run 

166 hands back to the name because only suffix words follow it is 

167 still a title to the chain, so the particle behind it is the 

168 name's leading piece and chains nothing (P4: 'Dr. Mc Mc' keeps 

169 'Mc' and 'Mc' apart, as before #624). `leading_titles` stops at a 

170 piece that is itself a leading title only where it gave that piece 

171 back, before a suffix piece (the tags it tests inline first), or at 

172 the segment's last piece, which a title may not be unless it is the 

173 whole segment -- the `n + 1 < len(pieces)` test rules that one out. 

174 The same tags go first here, so a name with no suffix behind its 

175 titles pays no frame for the test.""" 

176 if (n + 1 < len(pieces) 

177 and ("suffix" in ptags[n + 1] 

178 or "vocab:suffix" in tokens[pieces[n + 1][0]].tags) 

179 and is_leading_title(pieces[n], ptags[n], tokens)): 

180 n += 1 

181 for k in range(n - 1, -1, -1): 

182 if is_prefix_piece(pieces[k], ptags[k], tokens): 

183 return k 

184 return n 

185 

186 

187# A particle, or a piece a join made one: what group's prefix chain 

188# (at its loop in _group_segment) chains and stops at, what P3's join 

189# derives a prefix from, and what group's rootname count and leading 

190# scan step past. 

191def is_prefix_piece(piece: Sequence[int], ptags: Set[str], 

192 tokens: Sequence[WorkToken]) -> bool: 

193 if "prefix" in ptags: 

194 return True 

195 return len(piece) == 1 and "particle" in tokens[piece[0]].tags 

196 

197 

198# rules/P3: "a recognized connective joins its neighbors into one 

199# name part, connective runs included — except a single-letter 

200# connective in a three-word name, which stays a name word where P13 

201# has not joined it first, and a single-letter connective that reads 

202# as an initial instead (P8), which never joins" (history: 

203# decisions/P3) 

204def is_conj_piece(piece: Sequence[int], ptags: Set[str], 

205 tokens: Sequence[WorkToken]) -> bool: 

206 if "conjunction" in ptags: 

207 return True 

208 return len(piece) == 1 and "conjunction" in tokens[piece[0]].tags 

209 

210 

211def joined_tags(ptags: Sequence[Set[str]], lo: int, hi: int, 

212 add: Set[str] = frozenset(), 

213 drop: Set[str] = frozenset()) -> set[str]: 

214 # the ONE definition of a merged piece's tags: merge_pieces applies 

215 # it, and P5's reserve reads it to model the join it is 

216 # weighing (#425) -- so the view cannot drift from the merge. 

217 # A merged piece inherits every part's tags, so a site whose 

218 # product is not what its parts were drops what no longer 

219 # applies: the particle chain drops `prefix`, the bound join 

220 # `title` (a derived title tag on the pair would have assign 

221 # peel the given name as a leading title). 

222 return (set().union(*ptags[lo:hi]) | add) - drop 

223 

224 

225def merge_pieces(pieces: list[list[int]], ptags: list[set[str]], 

226 lo: int, hi: int, add: Set[str] = frozenset(), 

227 drop: Set[str] = frozenset()) -> None: 

228 # pieces/ptags are parallel arrays; every merge must update 

229 # both in lockstep. 

230 # 

231 # Extend the first piece IN PLACE rather than rebuilding the 

232 # merged list. The obvious spelling -- 

233 # pieces[lo:hi] = [[i for p in pieces[lo:hi] for i in p]] 

234 # -- re-flattens everything accumulated so far on every call, so 

235 # a chain that merges into the same piece n times copies 

236 # 1+2+...+n and the stage goes quadratic in the length of the 

237 # chain. A conjunction run ("and " * n) did exactly that while 

238 # `join_connectives` merged through here: it measured 2.4x-2.9x 

239 # per doubling against the 2.0x every other shape holds. No piece 

240 # list is aliased outside this function (each caller builds every 

241 # piece as a fresh list -- group's [i] -- and reads pieces[k] only 

242 # before a merge), so mutating is safe; verified 

243 # identical token/role/tag/span/ambiguity output over 54,877 

244 # names. 

245 # 

246 # Every call site passes lo < hi, and this REQUIRES it: with 

247 # lo >= hi the slice assignment would insert rather than 

248 # replace, putting a second reference to pieces[lo] into the 

249 # array, and the next merge to touch either index would extend 

250 # the same list twice. The old rebuild-a-fresh-list spelling 

251 # was harmless there. Keep the bound if you add a caller. 

252 # 

253 # The slice assignment itself still shifts every piece behind 

254 # `hi`, C-level work no frame guard counts, so a caller that 

255 # merges once per member of a run whose length grows with the 

256 # input goes quadratic all the same. `join_connectives` and 

257 # group's split-pair merge did, and build their lists in one pass 

258 # instead (decisions/parse-cost, 2026-11-03); the callers left 

259 # merge once per run (the particle chain, the bound join). A 

260 # caller that would merge per member builds its output that way, 

261 # with a row in tests/v2/test_benchmark.py's shift guards. 

262 combined = pieces[lo] 

263 for piece in pieces[lo + 1:hi]: 

264 combined.extend(piece) 

265 pieces[lo:hi] = [combined] 

266 ptags[lo:hi] = [joined_tags(ptags, lo, hi, add, drop)] 

267 

268 

269def join_connectives(pieces: list[list[int]], ptags: list[set[str]], 

270 tokens: Sequence[WorkToken], *, 

271 letter_stays: bool, titles_only: bool, 

272 frozen: Set[int] = frozenset()) -> None: 

273 """rules/P3's connective joins, for both parts that make them: 

274 group's name segments, and the part after a comma, which 

275 `_comma.decide` reads before group joins anything (#617, where the 

276 two had been copies that differed). Contiguous connectives merge 

277 into one first (v1: "of the"); then each connective joins its 

278 neighbours, taking its kind from the one on its left, or from the 

279 one on its right where it opens the part. 

280 

281 `letter_stays` is the single-letter carve-out's answer for this 

282 part, and it reaches a LONE single-letter connective only: one 

283 beside another connective merges into their run first and joins 

284 with it. Group reads it from the name's rootname count; the comma 

285 part, which a title joins and a name word never does, always keeps 

286 the lone letter. `titles_only` is the comma part's: a join is made 

287 only where the neighbour is a title, and makes the joined piece 

288 one ('Mr. and Mrs.') with no prefix kind, nothing in that part 

289 being a particle chain; any other connective there is left a word, 

290 the reading deciding what it is. Otherwise every join is made and 

291 takes the neighbour's title and prefix kinds. `frozen` holds the 

292 TOKEN index of each connective that is to make no join or run of 

293 its own -- group's, the generational ones with no name word on one 

294 side; the comma part's, every generational one -- though a 

295 neighbour's join may still take one in.""" 

296 # contiguous conjunction runs merge first 

297 # 

298 # The first token (`run_pieces[-1][0] in frozen`) and not 

299 # `frozen.isdisjoint(...)`: the piece this loop extends GROWS 

300 # with every merge, so a 

301 # test over its tokens costs 1+2+...+n and the stage goes 

302 # quadratic in the length of a connective run -- measured, 

303 # 'and ' x3200 took 41.8ms against 21.7ms, 6.2x per 4x input 

304 # where the shape reads 4.1x, and tests/v2/test_benchmark.py's 

305 # "and " shape is the guard that caught it. Reading the first 

306 # token alone is exact rather than an approximation: a frozen 

307 # piece is one token and this branch never merges it, and this 

308 # loop finishes before the join below can take one into a 

309 # neighbour's piece, so a piece holding a frozen token here IS 

310 # that token. 

311 # 

312 # Built in one pass, not through `merge_pieces`, whose slice 

313 # assignment would shift the rest of the list once per member 

314 # (its comment). The run being built is `run_pieces[-1]`. 

315 run_pieces: list[list[int]] = [] 

316 run_tags: list[set[str]] = [] 

317 for piece, tags in zip(pieces, ptags): 

318 if (run_pieces 

319 and is_conj_piece(run_pieces[-1], run_tags[-1], tokens) 

320 and is_conj_piece(piece, tags, tokens) 

321 and run_pieces[-1][0] not in frozen 

322 and piece[0] not in frozen): 

323 run_pieces[-1].extend(piece) 

324 run_tags[-1] = joined_tags((run_tags[-1], tags), 0, 2, 

325 add={"conjunction"}) 

326 else: 

327 run_pieces.append(piece) 

328 run_tags.append(tags) 

329 pieces[:] = run_pieces 

330 ptags[:] = run_tags 

331 # each conjunction joins its neighbors, rules/P3: "except a 

332 # single-letter connective in a three-word name, which stays a 

333 # name word" (v1's Google Code issue 11 carve-out, the 

334 # "john e smith" bug). 

335 # 

336 # The joins are written into fresh lists in one pass, for the 

337 # same reason: a run of joins ('Mr. and ' x n) through 

338 # `merge_pieces` would shift the rest of the list once per join. 

339 # A join takes the piece behind it off `out`, so the piece it 

340 # produces is `out[-1]`, the left neighbour of the next piece 

341 # read, and `len(out)` is always the index `pieces[k]` would 

342 # stand at had every join so far been made in the list itself. 

343 out: list[list[int]] = [] 

344 out_tags: list[set[str]] = [] 

345 n = len(pieces) 

346 k = 0 

347 while k < n: 

348 piece, tags = pieces[k], ptags[k] 

349 # first token again, exact for the run loop's reason (a 

350 # frozen piece is one token) and for a second: the piece a 

351 # join produces is left on `out`, BEHIND `k`, so no joined 

352 # piece is ever tested here. 

353 if (not is_conj_piece(piece, tags, tokens) 

354 or piece[0] in frozen): 

355 out.append(piece) 

356 out_tags.append(tags) 

357 k += 1 

358 continue 

359 if letter_stays and len(piece) == 1: 

360 text = tokens[piece[0]].text 

361 if not text.isascii(): 

362 # a decomposed 'й' is one letter in two code points 

363 # (#665); compose it, as the lookup does 

364 text = unicodedata.normalize("NFC", text) 

365 if len(text) == 1 and text.isalpha(): 

366 out.append(piece) 

367 out_tags.append(tags) 

368 k += 1 

369 continue 

370 has_left = bool(out) 

371 has_right = k + 1 < n 

372 if has_left: 

373 neighbor, neighbor_tags = out[-1], out_tags[-1] 

374 elif has_right: 

375 neighbor, neighbor_tags = pieces[k + 1], ptags[k + 1] 

376 else: 

377 # a connective alone in its part is its own neighbour, 

378 # so it takes its own kinds 

379 neighbor, neighbor_tags = piece, tags 

380 derived = set() 

381 if is_title_piece(neighbor, neighbor_tags, tokens): 

382 derived.add("title") 

383 elif titles_only: 

384 out.append(piece) 

385 out_tags.append(tags) 

386 k += 1 

387 continue 

388 if (not titles_only 

389 and is_prefix_piece(neighbor, neighbor_tags, tokens)): 

390 derived.add("prefix") 

391 parts = [piece] 

392 part_tags = [tags] 

393 if has_left: 

394 parts.insert(0, out.pop()) 

395 part_tags.insert(0, out_tags.pop()) 

396 if has_right: 

397 parts.append(pieces[k + 1]) 

398 part_tags.append(ptags[k + 1]) 

399 combined = parts[0] 

400 for part in parts[1:]: 

401 combined.extend(part) 

402 out.append(combined) 

403 out_tags.append(joined_tags(part_tags, 0, len(part_tags), 

404 add=derived)) 

405 k += 2 if has_right else 1 

406 pieces[:] = out 

407 ptags[:] = out_tags 

408 

409 

410# _PERIOD_ABBREV: imported from _vocab, not redefined here (#289/#516, 

411# quality-review finding) -- _vocab.name_word_count needed the SAME 

412# shape test is_leading_title asks (_vocab.is_title_shaped), and 

413# layering only allows the move in that direction (_pieces may import 

414# _vocab; _vocab may not import _pieces). tests/v2/test_regex_sync.py 

415# declares `_pieces._PERIOD_ABBREV` as an import of _vocab's, which an 

416# import binds here under the same name. Out of 

417# assign since #424 and in the piece layer since #439: the test is 

418# assign's, and the chain's leading position (`chain_lead`) and the 

419# trailing-run walk must start where assign starts. 

420 

421 

422# rules/H2: "an abbreviation opening the part of the name that 

423# carries the given name — the whole name, or the part after a 

424# family comma — reads as a title even when unlisted" 

425# (history: decisions/H2) 

426def is_leading_title(piece: Sequence[int], ptags: Set[str], 

427 tokens: Sequence[WorkToken]) -> bool: 

428 if is_title_piece(piece, ptags, tokens): 

429 return True 

430 if len(piece) != 1: 

431 return False 

432 text = tokens[piece[0]].text 

433 # INLINED rather than calling _vocab.is_title_shaped, which asks 

434 # the exact same question (#289/#516, quality-review finding: the 

435 # two must not drift, and did once -- name_word_count's own 

436 # vocabulary-only title test read 'Xyz.' as a name word where this 

437 # predicate reads it as a title, and the disagreement flipped a 

438 # comma structure `Dr. Smith, Ed`'s LISTED spelling did not). 

439 # THIS is the one home for the number, `is_title_shaped` pointing 

440 # here rather than restating it: routing this hot path through the 

441 # shared function costs one frame per call (`is_leading_title` 

442 # runs on every leading piece of every parse, unlike 

443 # name_word_count's comma-only path), moving the reference name 

444 # from 412/449 to 417/454 -- five calls on `Dr. Juan de la Vega 

445 # III`, recomputable with `uv run python 

446 # tools/perf/call_count.py`. Kept as two spellings of ONE test 

447 # instead -- if you touch one, touch both, and 

448 # `test_is_title_shaped_and_is_leading_title_agree` (this module's 

449 # own test file) checks it over the union of both predicates' 

450 # example tables rather than leaving it to a sentence. 

451 return (bool(_PERIOD_ABBREV.match(text)) 

452 and (text.isascii() or not (_SPELLED_INITIAL.search(text) 

453 or in_unabbreviating_script(text))) 

454 # rules/H2's transliteration-digraph Except (#1136) -- a 

455 # C-level membership test 

456 and text[:-1].lower() not in _DIGRAPH_INITIALS 

457 # rules/H2's precedence: a given name written short outranks 

458 # the shape ('Chas.', #789) -- classify's tag, a C-level test 

459 and GIVEN_ABBREVIATION_TAG not in tokens[piece[0]].tags) 

460 

461 

462def leading_titles(pieces: Sequence[Sequence[int]], 

463 ptags: Sequence[Set[str]], 

464 tokens: Sequence[WorkToken]) -> int: 

465 """How many leading pieces assign peels as titles: the first 

466 non-title index. A title needs a following piece, unless the whole 

467 segment is one title (v1 parity). And the run gives back its last 

468 piece when that piece is a name candidate: where everything behind 

469 the run is suffix pieces, the run gives back its last piece, when 

470 that piece is one word and is not itself suffix vocabulary 

471 (rules/H3, decisions/H3 -- the block at the floor below 

472 carries the examples of each half, and the ordering its two inline 

473 tag reads were measured on). A dotted run (rules/H10) the run ends 

474 on is given back after the floor. 

475 One definition, read by assign (which sets the roles), by the 

476 chain's trailing-run walk, and by `chain_lead`, which finds the 

477 chain's leading position inside this run for group's chain and the 

478 trailing read alike (P4, #367, #424, #624).""" 

479 n = 0 

480 while n < len(pieces): 

481 if ((n + 1 < len(pieces) or len(pieces) == 1) 

482 and (is_leading_title(pieces[n], ptags[n], tokens) 

483 or (len(pieces[n]) == 1 and DOTTED_TITLE_TAG 

484 in tokens[pieces[n][0]].tags))): 

485 n += 1 

486 continue 

487 break 

488 # rules/H3: "where everything behind the run is post-nominal, 

489 # the run gives its last word back to the name, provided that word 

490 # stands alone and is not itself suffix vocabulary" 

491 # 

492 # ONE WORD, because a joined unit led by a title is a title run and 

493 # handing it back would lose the title: 'Prince of Wales Jr' reads 

494 # title 'Prince of Wales', family 'Jr', not given 'Prince of Wales' 

495 # with no title at all. 

496 # 

497 # The residuals the floor does not reach (a run ending in suffix 

498 # vocabulary, a bare numeral behind the run) are decisions/H3's. 

499 # 

500 # The two inline tag reads are the cheapest NECESSARY condition for 

501 # the piece behind the run to be a suffix piece at all -- 

502 # is_suffix_piece cannot answer yes without one of them -- so the 

503 # ordinary titled name, whose next piece is no kind of suffix, 

504 # leaves this branch without entering a frame (decisions/H3, 

505 # decisions/parse-cost). is_suffix_piece stays the predicate that 

506 # ANSWERS, here and in the walk. 

507 if (n and n < len(pieces) 

508 and ("suffix" in ptags[n] 

509 or "vocab:suffix" in tokens[pieces[n][0]].tags) 

510 and len(pieces[n - 1]) == 1 

511 and not is_suffix_piece(pieces[n - 1], ptags[n - 1], 

512 tokens)): 

513 for k in range(n, len(pieces)): 

514 if not is_suffix_piece(pieces[k], ptags[k], tokens): 

515 break 

516 else: 

517 # nothing behind the run but suffix pieces 

518 n -= 1 

519 # rules/H10: "where a title the run keeps stands behind it, after 

520 # H3's floor has given its word back" -- so a dotted run the run 

521 # ends on is given back too, and so is each dotted run before it, 

522 # while a title before them stays ('U.S. Grant', 'Hon. U.S. Grant'); 

523 # the tag is classify's, on a 

524 # word no other title test takes (decisions/H10, #490) 

525 while (n and len(pieces[n - 1]) == 1 

526 and DOTTED_TITLE_TAG in tokens[pieces[n - 1][0]].tags): 

527 n -= 1 

528 return n 

529 

530 

531def is_suffix_piece(piece: Sequence[int], ptags: Set[str], 

532 tokens: Sequence[WorkToken]) -> bool: 

533 if "suffix" in ptags: 

534 return True 

535 if len(piece) != 1: 

536 return False 

537 tags = tokens[piece[0]].tags 

538 return "vocab:suffix" in tags and "initial" not in tags 

539 

540 

541# rules/S8: "A title word never starts the run, and neither does a 

542# member of the ambiguous class its writing leaves unsettled, a single 

543# letter, a connective" -- what 

544# starts #602's credential run, one predicate for the trailing peel and 

545# the given-part walk (mechanisms.md#ONE-PREDICATE-PER-QUESTION) 

546def starts_a_credential_run(piece: Sequence[int], ptags: Set[str], 

547 tokens: Sequence[WorkToken], 

548 preceding: str | None = None, 

549 one_case: bool | None = None) -> bool: 

550 """Whether one piece starts #602's run: an unambiguous suffix 

551 word of two or more letters, in any script -- a credential acronym, 

552 a generational word or an honorific -- that no other vocabulary 

553 claims as a name. 

554 

555 `is_suffix_piece` already refuses the ambiguous class and an 

556 initial-shaped letter. Refused here: any single letter (a lowercase 

557 `i` or `v` mid-name is an initial or a connective far more often 

558 than a numeral, and carries no `initial` tag), a connective, a 

559 word that is also bound given-name or particle vocabulary (`abd` 

560 heads `Abd Allah`; `vd`, `mc`). No script is refused: an honorific 

561 starts the run as a credential does (#679, decisions/S8), so 

562 `Ана Хорват старији Џонс` reads as `Ana Horvat stariji Jones` does. 

563 

564 The split credential group merges ('Ph. D.', the one piece carrying 

565 the "suffix" piece tag) starts it as its one-token spelling 'PhD' 

566 does: a run that started for one spelling of a word and not the 

567 other is the vocabulary-against-shape split nameparser/AGENTS.md's 

568 spelling sweep names (#603 found it, 'Smith, John Ph. D. Jones' keeping 

569 middle 'Jones' where 'Smith, John PhD Jones' reads suffix 

570 'PhD Jones'). Without a comma `peel_walk` leaves the merged piece 

571 out of the pieces `run_start` walks, so `run_start` asks this of 

572 the piece in front of a kept one itself (#827): 'John Smith Ph. D. 

573 Jones' reads suffix 'Ph. D. Jones' as 'John Smith PhD Jones' reads 

574 'PhD Jones'. 

575 

576 A roman numeral of two or more letters starts it where 

577 `_vocab.reads_as_generation` reads it as the generation, with 

578 `preceding` and `one_case` that predicate's (#784): 'John Smith VI 

579 Jones' as 'John Smith III Jones'. 

580 """ 

581 if "suffix" in ptags or "split" in ptags: 

582 # a split credential alone: a connective join keeps the tag on 

583 # the wider piece ('Ph. D. and Mary'), which starts nothing, as 

584 # 'PhD and Mary' does not 

585 return len(piece) == 2 

586 if len(piece) != 1: 

587 return False 

588 tok = tokens[piece[0]] 

589 if not tok.tags.isdisjoint(_NOT_A_RUN_START): 

590 return False 

591 # rules/S8: "a roman numeral of two or more letters that reads as 

592 # the generation" -- asked of the numeral's predicate, which the 

593 # vocabulary's own numerals answer too 

594 stem = tok.text.rstrip(".") 

595 if len(stem) >= 2 and _ROMAN.match(stem) is not None: 

596 return reads_as_generation(tok.text, tok.tags, preceding, one_case) 

597 # rules/S8: "and so does a listed member of the ambiguous class its 

598 # writing settles as the credential" -- the capitals mark the 

599 # post-nominals as periods do; the particle test above still 

600 # refuses 'DO' 

601 if AMBIGUOUS_ACRONYM_TAG in tok.tags: 

602 return (settled_by_case(tok, one_case) 

603 and sum(map(str.isalpha, tok.text)) >= 2) 

604 if not is_suffix_piece(piece, ptags, tokens): 

605 return False 

606 # C-level, no generator frame per character 

607 letters = "".join(filter(str.isalpha, tok.text.lower())) 

608 return len(letters) >= 2 

609 

610 

611#: tags of suffix words another vocabulary claims as a name word or a 

612#: joiner, which therefore never start #602's run 

613_NOT_A_RUN_START = frozenset({"conjunction", "particle", 

614 "vocab:bound-given"}) 

615 

616 

617def split_credential_report(piece: Sequence[int], 

618 tokens: Sequence[WorkToken], 

619 alternative: PendingReading) -> PendingAmbiguity: 

620 """rules/S12's report on a split credential the count took, one 

621 spelling for the three sites that take one (assign's placement, the 

622 comma's binding, the maiden clause's release). `alternative` is the 

623 words' name reading, whose field each site knows.""" 

624 text = " ".join(tokens[i].text for i in piece) 

625 return PendingAmbiguity( 

626 AmbiguityKind.SUFFIX_OR_NAME, 

627 f"{text!r} is two words whose letters spell a credential, so it " 

628 f"reads as a credential; they may be name words", tuple(piece), 

629 alternative=alternative) 

630 

631 

632def is_lone_never_given_particle(piece: Sequence[int], 

633 tokens: Sequence[WorkToken]) -> bool: 

634 """A piece that is one never-given particle (rules/P1's fold 

635 site). One predicate, asked by the fold in post_rules and by two 

636 sites in assign that predict the fold will take the particle 

637 forward: the given slot, which then leaves no given name in front 

638 of a member (#573), and P6's attachment after a family comma, 

639 which then leaves no given word for the tail to stand behind 

640 (#613) -- copies would drift silently, each site's own tests 

641 still passing (mechanisms.md#ONE-PREDICATE-PER-QUESTION).""" 

642 return (len(piece) == 1 

643 and "particle" in tokens[piece[0]].tags 

644 and "vocab:particle-ambiguous" not in tokens[piece[0]].tags) 

645 

646 

647# rules/P11: "an ambiguous particle written in lower case, in a name of 

648# mixed case, opens the name as a never-given one does" -- the site 

649# test, asked by the fold in post_rules and by assign's report, which 

650# the fold settles (decisions/P11, #670) 

651def is_lowercase_ambiguous_particle(piece: Sequence[int], 

652 tokens: Sequence[WorkToken], 

653 one_case: bool | None) -> bool: 

654 """A piece that is one ambiguous particle written in lower case in 

655 a name of mixed case: rules/P1's fold site under a family-first 

656 order, where the writing settles the particle's fork as a 

657 never-given particle's vocabulary does (#670). `one_case` is 

658 ParseState.one_case; None (nobody asked) settles nothing.""" 

659 return (len(piece) == 1 

660 and "vocab:particle-ambiguous" in tokens[piece[0]].tags 

661 and one_case is False and tokens[piece[0]].text.islower()) 

662 

663 

664def _numeral_behind_the_initial_veto(piece: Sequence[int], 

665 tokens: Sequence[WorkToken]) -> bool: 

666 """Suffix vocabulary that is_suffix_piece refuses because it is 

667 also initial-shaped: a ONE-CHARACTER entry, bare or with a period. 

668 

669 Named for the shape rather than enumerated, because the shape is 

670 what the code tests and the enumeration goes stale -- in the 

671 shipped lexicon it reaches i, v and 2, and NOT x or ix (roman, but 

672 not suffix vocabulary) nor ii/iii/iv (suffix vocabulary, but two 

673 characters, so never initial-shaped and never vetoed in the first 

674 place). A caller adding a one-character suffix in a script that 

675 has initials extends it. 

676 

677 The veto is right where such a word could be a middle initial, and 

678 wrong where it is describing the suffix in front of it, which is 

679 the only place this is asked from. The len(piece) != 1 guard is 

680 defensive: a merged multi-token piece carries "suffix" in ptags, so 

681 is_suffix_piece claims it one branch earlier and no reachable input 

682 arrives here with one. 

683 """ 

684 if len(piece) != 1: 

685 return False 

686 # A one-letter numeral here is the numeral's predicate's yes by 

687 # construction: in a comma part it reads one by the vocabulary, and 

688 # the tag below is that vocabulary (#752), so it is not asked again. 

689 tags = tokens[piece[0]].tags 

690 return "vocab:suffix" in tags and "initial" in tags 

691 

692 

693def _anchors(piece: Sequence[int], tokens: Sequence[WorkToken]) -> bool: 

694 """Whether a suffix piece may ANCHOR an ambiguous member behind it 

695 (#544): not a connective, not a particle, and not a single-letter 

696 roman numeral. 

697 

698 A connective anchors nothing because between two name words it is 

699 a link -- the generational 'i' is also Catalan's 'i' (rules/P3) 

700 -- and 'Jane Doe nee Puig i Ma' must keep its clause. A particle 

701 anchors nothing for the same reason from the other side: it joins 

702 the name word behind it (rules/P2), so a word that is both 

703 particle and suffix vocabulary ('vd', 'mc') standing in front of 

704 a member is the head of a family name, not a credential list -- 

705 'Smith vd Ma, John' keeps family 'Smith vd Ma' and 'Jan vd Ma' 

706 family 'vd Ma'. A particle MEMBER is still anchored by a 

707 credential in front of it ('doe, jane v phd do'); the exclusion is 

708 of the anchor only. A single-letter roman numeral, in any case 

709 ('V', 'v', 'I.'), anchors nothing for its SHAPE: one letter is 

710 the shape a middle initial is written in ('V' can be one), and S3 

711 retired single-character vocabulary matches for the same reason. 

712 Not because a numeral is no credential -- a multi-letter suffix 

713 word ('III', 'Jr') anchors like any other suffix piece 

714 (`is_single_letter_numeral`). A title/suffix DUAL ('ms', 'vc', 

715 'sr') does anchor, except in the given part's 

716 leading title run, where it stands in title position ('Smith, Ms 

717 Ma' is Ms. Ma Smith); that exclusion is the callers', which start 

718 their walks past the leading title run or, in 

719 `segment_suffix_reading`, read no anchor at all in a part whose 

720 leading title run holds one. 

721 

722 Asked only of a piece `is_suffix_piece` accepted, and only once a 

723 member's own writing has declined, so an ordinary name never pays 

724 for it.""" 

725 if len(piece) != 1: 

726 return True 

727 tok = tokens[piece[0]] 

728 return ("conjunction" not in tok.tags 

729 and "particle" not in tok.tags 

730 and not is_single_letter_numeral(tok.text)) 

731 

732 

733# rules/S7: "Only a credential in FRONT speaks; one behind the 

734# member says nothing about it." #544: an ambiguous member standing 

735# BEHIND an unambiguous credential in one run is described by that 

736# credential's company, not by its own writing -- 'PhD MEng' is a list of degrees whatever case 'MEng' 

737# is written in. ONE forward pass per question, so a run of members 

738# is read in linear time: a look-behind per member is quadratic in 

739# the run, which test_benchmark's frame-ratio guard is built to catch. 

740def credential_anchors(order: Sequence[int], 

741 pieces: Sequence[Sequence[int]], 

742 ptags: Sequence[Set[str]], 

743 tokens: Sequence[WorkToken], 

744 first_kept: bool = True) -> list[bool]: 

745 """For each position of `order` (piece indices in text order), 

746 whether a lone listed member standing there is ANCHORED: the 

747 contiguous run of pieces in FRONT of it that are suffix pieces or 

748 lone ambiguous members ends in -- counting back past the members -- 

749 a suffix piece that may anchor (`_anchors`). Any other piece ends 

750 the run. The anchor is in front only: 'Wang Ma PhD' leaves 'Ma' 

751 unanchored. 

752 

753 The caller decides where the walk starts, and starts it past the 

754 leading title run, where a title/suffix dual reads as a title 

755 ('Smith, VC MA Ma' keeps its middle name). Where `order` holds the 

756 name part, its own leading position is the name the reserve keeps 

757 -- `rest[0]` at the no-comma peel, the given part's own first 

758 piece at the given-slot call sites -- so ITS writing never anchors 

759 what stands behind it, whatever vocabulary it carries: 'PhD Ma' 

760 keeps the count's reading, family 'Ma', rather than reading as a 

761 credential list headed by the given name itself. `first_kept` 

762 False is the one caller with no reserve, `segment_suffix_reading`, 

763 asking whether a comma part is a credential run at all: there the 

764 first piece is a run member like any other ('Smith, PhD MEng').""" 

765 out: list[bool] = [] 

766 anchor = False 

767 for pos, idx in enumerate(order): 

768 out.append(anchor) 

769 if pos == 0 and first_kept: 

770 continue 

771 piece = pieces[idx] 

772 if is_suffix_piece(piece, ptags[idx], tokens): 

773 # a suffix piece that may not anchor still ENDS the run it 

774 # would have anchored: 'PhD v Ma' is not a credential list 

775 # through the numeral 

776 anchor = _anchors(piece, tokens) 

777 elif not (len(piece) == 1 

778 and AMBIGUOUS_ACRONYM_TAG in tokens[piece[0]].tags): 

779 anchor = False 

780 return out 

781 

782 

783def given_slot_anchors(pieces: Sequence[Sequence[int]], 

784 ptags: Sequence[Set[str]], 

785 tokens: Sequence[WorkToken], 

786 start: int, end: int | None = None, 

787 skip: Container[int] = ()) -> list[bool]: 

788 """`credential_anchors` for the given part's slot, indexed by PIECE 

789 rather than by position: the pass over `start` to `end`, `skip` 

790 spliced out, and False before `start`, from `end` on and at every 

791 skipped piece. `start` is where the leading title run ends, so a 

792 title/suffix dual standing in it anchors nothing ('Smith, VC MA 

793 Ma'), and the piece at `start` is the given name the reserve keeps. 

794 The one home of that query for assign's given slot.""" 

795 stop = len(pieces) if end is None else end 

796 order: Sequence[int] = range(start, stop) 

797 if skip: 

798 order = [q for q in order if q not in skip] 

799 out = [False] * len(pieces) 

800 for q, anchored in zip(order, credential_anchors(order, pieces, ptags, 

801 tokens)): 

802 out[q] = anchored 

803 return out 

804 

805 

806def anchor_in_reach(back: Iterable[int], 

807 pieces: Sequence[Sequence[int]], 

808 ptags: Sequence[Set[str]], 

809 tokens: Sequence[WorkToken], 

810 skip: Container[int] = ()) -> bool: 

811 """False where `credential_anchors` must answer False for the 

812 member standing just behind `back` -- the piece indices in front 

813 of it, nearest first, `skip` spliced out: past the lone members 

814 in front, the first other piece is no suffix piece, or there is 

815 none. True means only "ask the pass". 

816 

817 Exact in that direction because the test is weaker than the 

818 pass's: a suffix piece carries "suffix" in its ptags or is one 

819 token carrying "vocab:suffix" (`is_suffix_piece`), so a piece 

820 failing both can neither anchor nor carry a run on. Read from tags 

821 alone, with no frame per piece, so the ordinary name ending in a 

822 Title-case member ('John Smith Ma', 'Doe, John Q. Ma') spends one 

823 frame here rather than the pass's one per piece. Callers pass the 

824 positions the pass itself would read or a superset reaching 

825 further back: the walk meets any anchor the pass would find before 

826 it reaches past the pass's start, so reaching further can cost a 

827 pass that finds nothing and never a reading.""" 

828 for q in back: 

829 if q in skip: 

830 continue 

831 piece = pieces[q] 

832 if "suffix" in ptags[q]: 

833 return True 

834 if len(piece) != 1: 

835 return False 

836 tags = tokens[piece[0]].tags 

837 if "vocab:suffix" in tags: 

838 return True 

839 if AMBIGUOUS_ACRONYM_TAG not in tags: 

840 return False 

841 return False 

842 

843 

844def segment_suffix_reading(pieces: Sequence[Sequence[int]], 

845 ptags: Sequence[Set[str]], 

846 tokens: Sequence[WorkToken], 

847 lenient: bool, 

848 one_case: bool | None, 

849 anchored: list[int] | None = None, 

850 absorbed: list[int] | None = None, 

851 licensed: Container[int] = (), 

852 head_named: bool = True, # rules/S11 

853 runs: Container[int] = (), # rules/C16 

854 ) -> tuple[bool, ...] | None: 

855 """How each piece of a no-name segment reads: True a suffix, False 

856 a title. None when the segment holds a name word and so is not a 

857 credential run at all. 

858 

859 `one_case` admits #289's credential lean: an ALL-CAPS member of 

860 the ambiguous set inside a mixed-case name is a credential in this 

861 slot even with one word before the comma, because the writing is 

862 evidence the count does not have ('Smith, MA' -> family 'Smith', 

863 suffix 'MA'). Only the LEAN reaches here on its own: a token 

864 admitted to the class by SHAPE takes the count instead, which 

865 `_comma.decide` takes and hands in as `licensed`, below ('Smith, 

866 XYZ' -> given 'XYZ', one name word being no count). 

867 

868 A listed member ANCHORED by an unambiguous credential in front of 

869 it in the same run reads as a credential too, whatever its writing 

870 (#544, `credential_anchors`): 'Smith, PhD MEng' is family 'Smith' 

871 with two degrees. A title/suffix dual standing in the part's 

872 LEADING TITLE RUN -- every piece ahead of it a title or another 

873 such dual -- is a title there, and in a part that holds one this 

874 reading anchors nothing at all, not by the dual and not by a 

875 later credential: the dual makes the next name-position word the 

876 given name, and reading the part wholly as credentials would 

877 stack the anchor's guess on the dual's ('Smith, Ms Ma', 'Smith, 

878 Ms VC Ma' and 'Smith, VC PhD Ma' keep a given name, 'Smith, 

879 Prof. VC Ma' too). The walk then reads the part, and its given 

880 slot's company starts past that given name ('Smith, VC PhD Jr 

881 Ma' reads suffix 'Jr Ma'). A plain title ahead of the credential 

882 does not stop this reading ('Smith, Dr. PhD LAc' reads title 

883 'Dr.', suffix 'PhD LAc'). 

884 

885 `anchored`, when the caller passes a list, receives the index of 

886 every piece the anchor read as a credential after its own writing 

887 declined -- the picks the caller reports, since this decides them 

888 (mechanisms.md#AMBIGUITY-AT-THE-DECISION-SITE). A member whose own 

889 capitals lean credential is not among them. Meaningful only when 

890 the answer is not None: a segment the walk abandons part-way may 

891 have appended to it first. 

892 

893 ONE reader since #613: `_comma.decide`, which reads the part once 

894 at group's head and binds the roles this returns, so the decision 

895 that the part holds no name word and the roles its words get 

896 cannot disagree. Until then it answered for two readers in 

897 _assign.py, the no-name gate and the router, and #429 shipped the 

898 inverse of its own fix by deriving that agreement twice 

899 (mechanisms.md#ONE-PREDICATE-PER-QUESTION); it answered for a 

900 third until #436, group's one-entry join. 

901 

902 `licensed` holds the pieces rules/C4's count has licensed as 

903 credentials -- ambiguous-class words in a credential run behind 

904 two name words -- and each reads as a suffix whatever its writing 

905 or company. 

906 

907 `runs` holds a run of initials spelling a listed credential that 

908 stands behind one word (rules/C16, #1238), passed only there: 

909 reached while the part is still in its leading run of titles, it 

910 makes the part the given part and the answer None. 

911 

912 The initial veto (`_vocab.is_initial`) keeps a roman numeral out 

913 of a suffix reading, which is right after a NAME word (rules/C9's 

914 one-character suffix word, read by what stands before it): 'Smith, John V.' is a 

915 middle initial (#432). After a SUFFIX word the numeral is 

916 describing that suffix -- 'PSM I' is Professional Scrum Master 

917 level I -- so the run continues through it, period included, an 

918 initial there being no shape anyone writes (#430). A title resets 

919 that: what follows a bare title is not continuing a credential. 

920 

921 A part OPENED by a credential is the postnominal part however it 

922 goes on (#603, rules/C13): where an unambiguous suffix word that 

923 starts #602's run (`starts_a_credential_run`) is the first suffix 

924 word of the part, with only titles in front of it (a title/suffix 

925 dual among them ends the chance: a credential behind one opens 

926 nothing), every later 

927 word is read as #602's run reads the given part -- a title word as 

928 a title, anything else as a suffix -- so 'John Smith, PhD Jones' 

929 and 'Smith, PhD Jones' read suffix 'PhD Jones'. A word of the 

930 title vocabulary as well opens nothing (#603, Derek): in front of 

931 a given name it is the listing form's title ('Smith, Ms Jane'), 

932 and no count of the words before the comma can tell a two-word 

933 surname from a given name and a family name, so none decides it. 

934 `absorbed`, when passed, receives the index 

935 of every piece the opened part takes that would otherwise have 

936 made this None -- the caller reports them, as #602's run reports 

937 the name words it takes. 

938 

939 None covers both ways a segment can fail to be a run: a name word 

940 anywhere in it (in a part no credential opened), and no pieces at 

941 all ('Doe,, Jr.', which holds no 

942 title to read by). 

943 

944 `lenient` is Policy.lenient_comma_suffixes, and only the numeral 

945 continuation consults it. A part after the comma that is nothing 

946 but suffix words, rules/C14: "stops being a credential run at such a word" 

947 -- such a word being a suffix word written as an initial. Under 

948 strict the numeral gets no suffix reading behind a suffix word, so 

949 a part no credential opened is no run and the reading is None 

950 ('Smith, VC I'); a part a credential opened (C13) still takes the 

951 word in through `opened` below and hands it to `absorbed` 

952 ('Smith, PSM I.'), which implements 

953 rules/C14's Except bullet "A credential opening the part". The walk reads the token's `initial` 

954 tag, so a one-case lowercase letter is vetoed as its capital is 

955 (rules/T4). Reading no policy here silently overrode the one knob a 

956 caller sets to prevent exactly this (#430). History: 

957 decisions/C14 (#761), decisions/C13 (#603). 

958 

959 The FAMILY_COMMA rule that segment 0 is the family name rests 

960 on the writer having said where the family name ends. A comma 

961 followed by no name word said no such thing -- 'John Smith, Dr.' is 

962 'Dr. John Smith' with the honorific moved -- so the pre-comma name 

963 keeps its positional read instead of being merged (through 

964 `_comma.decide`'s suffix comma, behind a whole name). Uses the same 

965 is_leading_title predicate the peel does, period-abbreviation 

966 inference included, so the two cannot disagree about what a title 

967 is; a mixed run like 'Smith, Dr. Jr.' is a title and a postnominal, 

968 each read where it stands, never a title run 'Dr. Jr.'. 

969 """ 

970 if not pieces: 

971 return None 

972 out: list[bool] = [] 

973 # #544: `credential_anchors` over the whole part, computed the 

974 # first time a member's writing declines with a suffix piece in 

975 # reach in front of it (`anchor_in_reach`, asked only while the 

976 # pass does not exist yet). A member opening the part has nothing 

977 # in front and asks neither ('Smith, Ed', 'Smith, Ma John'); a 

978 # name word in front returns None before the member is reached; 

979 # and a title in front ends the reach test, so 'Smith, Dr. Ma' 

980 # pays that one test and no pass. 

981 anchors: list[bool] | None = None 

982 # Whether every piece so far stands in the part's leading title 

983 # run (titles, and title/suffix duals), and whether a dual has 

984 # stood there: once one has, nothing in the part anchors. Tracked 

985 # here rather than read off `leading_titles`, whose period-shape 

986 # inference counts a suffix like 'Esq.' into the run ('Smith, Esq. 

987 # VC Ma' keeps its anchored 'Ma' only by this walk's reading). 

988 leading = True 

989 dual_led = False 

990 # #603: the first suffix word of the leading run, which may open 

991 # the part unless a dual stood ahead of it; asked whether it does 

992 # only once a piece reaches the title and name branches below, so a 

993 # part of nothing but suffix words ('Smith, Jr.', 'Smith, PhD MA') 

994 # never pays for the question 

995 opener: tuple[Sequence[int], Set[str]] | None = None 

996 opened = False 

997 for piece, tags in zip(pieces, ptags): 

998 # the verdict just recorded IS "stands behind a suffix" -- keeping 

999 # a separate flag meant maintaining that equality by hand at three 

1000 # sites, and a fourth branch that appended without assigning would 

1001 # have diverged silently 

1002 after_suffix = bool(out) and out[-1] 

1003 # rules/C16: "behind one word, initials run together are the 

1004 # given name whatever they spell" -- `runs`, which the 

1005 # caller passes only there; a suffix word in front of the run 

1006 # makes it the credential run, titles and duals leave it a name 

1007 # (decisions/C16 (#1238)) 

1008 if leading and piece[0] in runs: 

1009 return None 

1010 if is_suffix_piece(piece, tags, tokens): 

1011 if (leading and len(piece) == 1 

1012 and "vocab:title" in tokens[piece[0]].tags): 

1013 dual_led = True 

1014 else: 

1015 if leading and not dual_led: 

1016 opener = (piece, tags) 

1017 leading = False 

1018 out.append(True) 

1019 continue 

1020 member = (len(piece) == 1 

1021 and AMBIGUOUS_ACRONYM_TAG in tokens[piece[0]].tags) 

1022 # rules/S11: "The floor holds first" -- at the first slot after 

1023 # a comma a generation word's writing adds nothing to the count 

1024 # C4 reads first, `head_named` being that count's two name 

1025 # words before the comma (', Dr. fils' and 'Sir Alexandre, fils' 

1026 # keep a family word) 

1027 if member and listed_lean(tokens[piece[0]], one_case) \ 

1028 == "credential" and ( 

1029 head_named 

1030 or AMBIGUOUS_WORD_TAG not in tokens[piece[0]].tags): 

1031 leading = False 

1032 out.append(True) 

1033 continue 

1034 # A word rules/C4's count licenses as a credential: the 

1035 # caller (`_comma.decide`) counted two name words before the 

1036 # comma and found the part a credential run, which settles the 

1037 # ambiguous word here before S7's anchors are asked (#613) 

1038 if piece[0] in licensed and (len(piece) == 1 or "split" in tags): 

1039 leading = False 

1040 out.append(True) 

1041 continue 

1042 if (member and not dual_led 

1043 and SHAPE_ACRONYM_TAG not in tokens[piece[0]].tags): 

1044 if anchors is None and out and anchor_in_reach( 

1045 range(len(out) - 1, -1, -1), pieces, ptags, tokens): 

1046 anchors = credential_anchors(range(len(pieces)), pieces, 

1047 ptags, tokens, first_kept=False) 

1048 if anchors is not None and anchors[len(out)]: 

1049 leading = False 

1050 if anchored is not None: 

1051 anchored.append(len(out)) 

1052 out.append(True) 

1053 continue 

1054 if (lenient and after_suffix 

1055 and _numeral_behind_the_initial_veto(piece, tokens)): 

1056 leading = False 

1057 out.append(True) 

1058 continue 

1059 if opener is not None: 

1060 # asked once: cleared, as it is set at most once 

1061 opened = starts_a_credential_run(opener[0], opener[1], tokens) 

1062 opener = None 

1063 if opened: 

1064 # #602's run: a title word reads as a title, anything else 

1065 # as a suffix -- vocabulary only, as in the given part 

1066 if is_title_piece(piece, tags, tokens): 

1067 out.append(False) 

1068 else: 

1069 if absorbed is not None: 

1070 absorbed.append(len(out)) 

1071 out.append(True) 

1072 elif is_leading_title(piece, tags, tokens): 

1073 out.append(False) 

1074 else: 

1075 return None 

1076 return tuple(out) 

1077 

1078 

1079class Peel(NamedTuple): 

1080 """What assign's trailing peel made of a walk. `names` is a count 

1081 of positions in the caller's `rest`: rest[:names] are the name 

1082 pieces and rest[names:] the suffixes. The other two are pieces -- 

1083 token-index tuples, as PendingAmbiguity wants them -- and each is 

1084 one token long: `numerals` are the pieces the roman-numeral fork 

1085 took as a call, each reported, in peel order (none for a numeral 

1086 its lower case settled or the vocabulary lists in two or more 

1087 letters, which is taken unrecorded; a one-letter one is always the 

1088 walk's last piece, one of two or more letters anywhere in its 

1089 trailing run, #752), 

1090 `picks` the bare ambiguous acronyms the peel had to resolve, in 

1091 peel order, either way (the last may sit at rest[names - 1]), and 

1092 a numeral the fork declined, a one-letter one for want of words to 

1093 spare (#718), always the walk's last piece, or one of two or more 

1094 letters for its Title case (#752), anywhere in the trailing run, 

1095 and a name unless a credential run in front of it takes it. 

1096 `anchors` is `peel_trailing`'s working state for `tail_reading` 

1097 alone -- the walk's `credential_anchors` pass over `rest` where a 

1098 member needed one, handed to the next pass of the fixed point 

1099 (`peel_trailing`'s `start`). No caller reads it, and the Peel 

1100 `tail_reading` returns carries None.""" 

1101 

1102 names: int 

1103 numerals: tuple[tuple[int, ...], ...] 

1104 picks: tuple[tuple[int, ...], ...] 

1105 anchors: list[bool] | None 

1106 #: #602 (`credential_run`): the pieces in rest[names:] that are 

1107 #: title words inside the credential run, and the name pieces the 

1108 #: run absorbed, which assign reports 

1109 run_titles: tuple[int, ...] = () 

1110 absorbed: tuple[tuple[int, ...], ...] = () 

1111 #: rules/S8 (#1394): the token indices of the given names written 

1112 #: short whose run a name word behind them declined in a name of one 

1113 #: case (`run_start`'s `declined`), which assign reports 

1114 declined: tuple[int, ...] = () 

1115 

1116 

1117# rules/S2: "a trailing word of the suffix vocabulary reads as a 

1118# suffix — generational forms and credential acronyms alike" -- and 

1119# rules/S3: "an ambiguous acronym written with its periods, one after 

1120# each letter or one after each of two or more letter chunks, counts 

1121# unambiguously; a single trailing period is the abbreviation shape 

1122# any word can wear and does not" -- and rules/S4: "a BARE ambiguous acronym is consumed only when 

1123# the name has words to spare" 

1124# (v1's are_suffixes tail rule, with the roman-numeral special) 

1125def peel_walk(start: int, ptags: Sequence[Set[str]]) -> list[int]: 

1126 """The indices peel_trailing walks: `start` to the segment's end, 

1127 minus the group-flagged credential pieces (the Ph. D. merge), 

1128 which assign reads as suffixes at any position. Built here and nowhere 

1129 else, so the walk's input cannot drift between assign and the 

1130 group sites that read it: the numeral fork is a last-piece 

1131 test that reads the piece before as rest[k - 2], which holds only 

1132 over this list.""" 

1133 return [j for j in range(start, len(ptags)) 

1134 if "suffix" not in ptags[j]] 

1135 

1136 

1137def trailing_start(start: int, pieces: Sequence[Sequence[int]], 

1138 ptags: Sequence[Set[str]], tokens: Sequence[WorkToken], 

1139 *, one_case: bool | None) -> int: 

1140 """Where assign's trailing suffix run begins, read over the pieces 

1141 as they stand from `start`: the index of the first piece the S2 

1142 peel takes, or len(pieces) when it takes none (#424). What P2's 

1143 chain stops before where S2's run was not read once ahead of it 

1144 (#614: the part before a family comma, a part past the second 

1145 comma, a run holding a name piece; the given part after a family 

1146 comma stops at `trailing_run_start` since #623), and 

1147 what M2's walk stops before where no trailing rule reads the 

1148 clause -- each had asked "is this a 

1149 suffix?" with the suffix-piece test, which vetoes a bare 'V' as 

1150 an initial (the #401 question), and so took a trailing numeral, 

1151 or a bare acronym with words to spare, into the family or the 

1152 maiden name. 

1153 

1154 Both forks, always, and #602's credential run on top 

1155 (`credential_run`), so P2's chain stops where the run starts. 

1156 Readers that also need H5's title chain read the same pieces 

1157 through `tail_reading`, which runs this pair's peel and the chain 

1158 to a fixed point -- the maiden take among them (#601). So this 

1159 function's answer is the whole answer only where no trailing 

1160 title chain also reads the pieces.""" 

1161 rest = peel_walk(start, ptags) 

1162 names = run_start(rest, peel_trailing(rest, pieces, ptags, tokens, 

1163 one_case).names, 

1164 pieces, ptags, tokens, one_case=one_case) 

1165 return rest[names] if names < len(rest) else len(pieces) 

1166 

1167 

1168# #289/#516: the "listed member, not by-shape" test both 

1169# peel_trailing and segment_suffix_reading ask before reading the 

1170# lean -- shared here so the two cannot drift on what counts 

1171# (quality-review finding: it was spelled twice, once per site, 

1172# before this). Those two test "vocab:suffix-ambiguous" in tags 

1173# INLINE, before calling this, rather than leaving that cheap check to 

1174# this function's own body: measured, a caller whose `elif` reaches 

1175# this on every piece (segment_suffix_reading's does, one per 

1176# family-comma segment 1, member or not) pays one frame for the call 

1177# regardless of what is inside it, and the inline pre-check is what 

1178# keeps a non-member piece ("Smith, John"'s "John") from ever making 

1179# the call at all. 

1180# 

1181# A further caller since #533 -- credential_at_the_given_slot just 

1182# below -- deliberately does NOT pre-check: it owns #531's reading 

1183# and leaves membership to its own callers (its docstring says so), 

1184# and the frame argument holds transitively because its caller asks 

1185# inline -- `AMBIGUOUS_ACRONYM_TAG in tok.tags` after a 

1186# `len(piece) == 1` at assign's given-part trailing slot. So no 

1187# non-member piece reaches this function down that route either. 

1188def listed_lean(token: WorkToken, one_case: bool | None) -> Lean | None: 

1189 """`ambiguous_lean` for a LISTED bare-ambiguous token, or None if 

1190 the token is not tagged a listed member, is admitted by SHAPE 

1191 instead (`SHAPE_ACRONYM_TAG`, a switch's doing, not the writing's), 

1192 or there is no case fact to ask at all.""" 

1193 if (one_case is None or AMBIGUOUS_ACRONYM_TAG not in token.tags 

1194 or SHAPE_ACRONYM_TAG in token.tags): 

1195 return None 

1196 # rules/S11: "Any other's writing never speaks, and the count decides 

1197 # alone" -- only a word written `title_case_is_name` (`fils`, `kc`) 

1198 # takes the suffix word's cue; an agnomen and `junior` take none 

1199 # (decisions/S11, #1039) 

1200 if AMBIGUOUS_WORD_TAG in token.tags: 

1201 return ambiguous_lean(token.text, one_case, 

1202 "word" if TITLE_CASE_NAME_TAG in token.tags 

1203 else "none") 

1204 return ambiguous_lean(token.text, one_case) 

1205 

1206 

1207# rules/S6: "a clash settled by the writing is not reported" -- the 

1208# gate's form step for a listed acronym, asked where a reading is 

1209# chosen, so the word keeps its tags and with them its other readings 

1210# (history: decisions/S6 (#785)) 

1211def settled_by_case(token: WorkToken, one_case: bool | None) -> bool: 

1212 """Whether the writing settles a LISTED ambiguous acronym as the 

1213 credential: written in capitals in a name of mixed case 

1214 (`listed_lean`). Only the clash between the credential and the 

1215 name reading is settled; the word stays a member of the class, so 

1216 a particle reading ('DO') or the place a maiden clause gives its 

1217 first word still answers as before. A suffix word that is also a 

1218 name ('fils') is S11's and is not asked here.""" 

1219 return (AMBIGUOUS_WORD_TAG not in token.tags 

1220 and listed_lean(token, one_case) == "credential") 

1221 

1222 

1223def credential_at_the_given_slot( 

1224 token: WorkToken, one_case: bool | None, 

1225 anchored: Callable[[], bool] | None = None) -> bool: 

1226 """#531's reading of a class MEMBER ending the given part after a 

1227 family comma: the credential unless the writing says otherwise. 

1228 The caller decides membership and that the piece ends that part. 

1229 

1230 The words to spare are there by construction at that slot, so the 

1231 count says nothing and only the lean does; a member that is also 

1232 particle vocabulary reads as the credential on a POSITIVE lean 

1233 alone, P6's attachment keeping every other spelling. 

1234 

1235 Or where the member is ANCHORED (#544): an unambiguous credential 

1236 in front of it in the same run (`credential_anchors`) makes it the 

1237 credential whatever its writing says, a particle member included 

1238 -- a degree in front outranks P6's attachment, as the capitals do 

1239 ('doe, jane v phd do' reads suffix 'phd do'). Only the caller 

1240 knows the run, so it computes the anchor; `anchored` is a THUNK, 

1241 asked last, so a member the writing already settles never pays 

1242 for the walk. 

1243 

1244 Called from assign's walk over the given part, as one function 

1245 rather than a condition written at the site 

1246 (mechanisms.md#ONE-PREDICATE-PER-QUESTION). It is a text-and-tags 

1247 question, which is what puts it in this module rather than beside 

1248 any caller. 

1249 

1250 The membership half of that contract is CHECKED rather than 

1251 trusted, because getting it wrong is silent: all three of 

1252 `listed_lean`'s None reasons fall through to the `particle` test 

1253 below, so a non-member handed in by mistake is answered True -- 

1254 "read it as the credential" -- for a word the class never admitted. 

1255 An assert rather than a raise or a branch: it enters no Python 

1256 frame (measured -- 'Doe, John MA' stays at 311), it states the 

1257 contract where a reader of the function body meets it, and under 

1258 -O it is exactly the code that was here before. 

1259 """ 

1260 assert AMBIGUOUS_ACRONYM_TAG in token.tags, ( 

1261 f"credential_at_the_given_slot is #531's reading of a LISTED " 

1262 f"class member; {token.text!r} carries {sorted(token.tags)} " 

1263 f"and is not one. The caller decides membership -- test " 

1264 f"AMBIGUOUS_ACRONYM_TAG before calling") 

1265 lean = listed_lean(token, one_case) 

1266 if lean == "credential" or (lean is None 

1267 and "particle" not in token.tags): 

1268 return True 

1269 return anchored is not None and anchored() 

1270 

1271 

1272#: `_chain_units`' marks: a piece opening a name unit, and a name word 

1273#: the chain joins to the run in front of it 

1274OPENS, JOINED = 1, 0 

1275 

1276 

1277def second_unit(rest: Sequence[int], units: Sequence[int]) -> int: 

1278 """The position in `rest` of the piece opening its second name 

1279 unit, `len(rest)` where there is none: `rest[:m]` holds two units 

1280 exactly when this is below `m`. The first piece always counts as 

1281 a unit's, being where the name the walk reads starts.""" 

1282 for i in range(1, len(rest)): 

1283 if units[rest[i]] == OPENS: 

1284 return i 

1285 return len(rest) 

1286 

1287 

1288def _kept_in_front(rest: Sequence[int], front: int, 

1289 pieces: Sequence[Sequence[int]], 

1290 ptags: Sequence[Set[str]], 

1291 tokens: Sequence[WorkToken], 

1292 one_case: bool | None) -> int: 

1293 """The position in `rest` of the last word the trailing walk keeps 

1294 at or before `front`, which stands in front of a generation word 

1295 that is also a name, so that word's count looks past what the walk 

1296 takes there (rules/S11, #890); -1 where it keeps none. Taken by 

1297 itself: a suffix piece, a numeral of two or more letters read as the 

1298 generation ('Pedro VI Filho'), a member of the ambiguous class its 

1299 writing makes a suffix ('Pedro MA Filho'). Taken when carried: a 

1300 bare member of the class behind any of those, the members between 

1301 passing the run on, as rules/S7's company reads it ('Pedro Junior 

1302 Ma Filho'). One pass, so a carried run costs a step a member.""" 

1303 members: int | None = None # where an uncarried run of members began 

1304 j = front 

1305 while j >= 0: 

1306 piece = pieces[rest[j]] 

1307 if is_suffix_piece(piece, ptags[rest[j]], tokens): 

1308 members = None # a carrier: the run behind it is taken 

1309 j -= 1 

1310 continue 

1311 if len(piece) != 1: 

1312 break 

1313 tok = tokens[piece[0]] 

1314 stem = tok.text.rstrip(".") 

1315 if ((len(stem) > 1 and _ROMAN.match(stem) is not None 

1316 and reads_as_generation( 

1317 tok.text, tok.tags, 

1318 tokens[pieces[rest[j - 1]][0]].text if j >= 1 else None, 

1319 one_case)) 

1320 or (AMBIGUOUS_ACRONYM_TAG in tok.tags 

1321 and listed_lean(tok, one_case) == "credential")): 

1322 members = None 

1323 j -= 1 

1324 continue 

1325 # a bare member that leans nowhere is taken only if something in 

1326 # front carries the run; an agnomen carries nothing and is kept 

1327 if (AMBIGUOUS_ACRONYM_TAG not in tok.tags 

1328 or AMBIGUOUS_WORD_TAG in tok.tags): 

1329 break 

1330 if members is None: 

1331 members = j 

1332 j -= 1 

1333 return j if members is None else members 

1334 

1335 

1336def peel_trailing(rest: Sequence[int], pieces: Sequence[Sequence[int]], 

1337 ptags: Sequence[Set[str]], 

1338 tokens: Sequence[WorkToken], 

1339 one_case: bool | None, 

1340 start: int | None = None, 

1341 anchors: list[bool] | None = None, 

1342 units: Sequence[int] | None = None, 

1343 second: int = 1, 

1344 count_numeral: bool = True) -> Peel: 

1345 """The S2 trailing peel over `rest`, a peel_walk list. In the 

1346 piece layer rather than in assign because group's bound-given 

1347 reserve asks the same question of the view the join would leave 

1348 (#425): one walk, so the reserve and the assignment cannot drift. Pure -- the ambiguities are 

1349 returned for assign to report, in the order it always reported 

1350 them. 

1351 

1352 `one_case` is ParseState.one_case, the recorded fact: None means 

1353 nobody asked, which is every caller that has no state to ask with, 

1354 and reads as "no lean" -- rules/S4's count alone, the behavior 

1355 of every release before this one. 

1356 

1357 `start` and `anchors` resume a walk rather than begin one: the 

1358 walk picks up at `rest[start - 1]`, as though the pieces from 

1359 `start` on were already peeled, with `anchors` the pass an earlier 

1360 walk built (or None). Only `tail_reading` passes them, and its 

1361 docstring states when that answers what a fresh walk would. The 

1362 returned picks and numerals are the resumed walk's own; a 

1363 one-letter numeral is never read, `start` standing short of the 

1364 walk's last piece. 

1365 

1366 `second` is where the second name unit opens in `rest` 

1367 (`second_unit`), the caller's to find once; positions are units 

1368 where `units` is None, and it is 1. 

1369 

1370 `units`, where given, marks each piece by the unit the chain will 

1371 put it in (`_chain_units`, #620): the words to spare are counted in 

1372 units, so a particle chain counts as the one name word P2 makes of 

1373 it, and a word the chain joins to a run without the reading 

1374 weighing it is a name word the walk stops at. The numeral fork still reads the piece in front of the 

1375 numeral as written: an initial there keeps it a name word whatever 

1376 unit the initial is in ('John van der J. V', rules/P2). 

1377 

1378 `count_numeral` False takes a one-letter numeral without asking 

1379 for words to spare: the given part after a family comma is read 

1380 without the count, and its chain bound must not ask it (#718). 

1381 Every numeral is weighed by `_vocab.reads_as_generation`, the one 

1382 predicate every numeral rule asks (#752). 

1383 """ 

1384 picks: list[tuple[int, ...]] = [] 

1385 numerals: list[tuple[int, ...]] = [] 

1386 # where the second name unit opens in `rest`, found once a member 

1387 # asks; positions are units where `units` is None 

1388 k = len(rest) if start is None else start 

1389 while k > 0: 

1390 piece = pieces[rest[k - 1]] 

1391 # a word the chain joins to a run, and the reading does not 

1392 # weigh, is a name word 

1393 if units is not None and units[rest[k - 1]] != OPENS: 

1394 break 

1395 if is_suffix_piece(piece, ptags[rest[k - 1]], tokens): 

1396 k -= 1 

1397 continue 

1398 # rules/S10: "the numeral reads as the generation" -- every 

1399 # numeral the suffix test above refused, the listed ones it took 

1400 # being the predicate's yes too. One of two or more letters is 

1401 # read anywhere in the trailing run ('John Smith VI MD' as 'John 

1402 # Smith III MD', #784); one of one letter only where it ends the 

1403 # walk, since with a credential behind it it is the name word 

1404 # S10's Accepted clause keeps (#721). `_ROMAN` on the stem first, 

1405 # C-level, so a name word pays no frame. A one-letter numeral 

1406 # "needs words to spare, as a bare ambiguous acronym does" -- 

1407 # the acronym fork's own count, below, so 'John V' keeps family 

1408 # 'V' (#718). Declined, it is a pick, since "either reading is 

1409 # reported", and no branch below can take a numeral 

1410 if (k >= 2 and len(piece) == 1 

1411 and _ROMAN.match(text := tokens[piece[0]].text.rstrip(".")) 

1412 is not None and text 

1413 and (len(text) > 1 

1414 or k == len(rest) 

1415 # the walk leaves out the Ph./D. pair, which is the 

1416 # credential behind the numeral all the same 

1417 and not (rest[k - 1] + 1 < len(ptags) 

1418 and "suffix" in ptags[rest[k - 1] + 1]))): 

1419 tok = tokens[piece[0]] 

1420 if reads_as_generation(tok.text, tok.tags, 

1421 tokens[pieces[rest[k - 2]][0]].text, 

1422 one_case): 

1423 # rules/S10: "a numeral written in lower case in a name 

1424 # of mixed case is the generation and reports nothing" 

1425 # -- decided here once: taken as any suffix word is, and 

1426 # not recorded as the fork's call, so no reporter meets 

1427 # it 

1428 if numeral_settled_by_case(tok.text, one_case): 

1429 k -= 1 

1430 continue 

1431 if (len(text) > 1 or not count_numeral 

1432 or k - 2 >= second): 

1433 numerals.append(tuple(piece)) 

1434 k -= 1 

1435 continue 

1436 picks.append(tuple(piece)) 

1437 break 

1438 # rules/S10: "a Title-case numeral in a name of mixed case 

1439 # leans to the name" -- weighed and declined, so reported 

1440 if numeral_leans_to_the_name( 

1441 tok.text, tok.tags, 

1442 tokens[pieces[rest[k - 2]][0]].text, one_case): 

1443 picks.append(tuple(piece)) 

1444 break 

1445 # A bare ambiguous acronym ("MA", not "M.A.") is a credential 

1446 # only when peeling it still leaves a given AND a family name. 

1447 # With two pieces, "one of them is a credential" is the less 

1448 # likely reading, so it stays the family name -- "Jack MA" is a 

1449 # person, "John Smith MA" is a person with a degree. This is 

1450 # v1's reserve_last narrowed to the ambiguous set: 2.0 

1451 # deliberately peels UNambiguous suffixes even when nothing is 

1452 # left ("Smith PhD" -> suffix, a classified fix), because there 

1453 # the vocabulary is not in doubt. 

1454 bare_ambiguous = (len(piece) == 1 

1455 and AMBIGUOUS_ACRONYM_TAG in tokens[piece[0]].tags) 

1456 # rules/S12: a split credential reads "as a member of the 

1457 # ambiguous class" -- read by the count alone, its writing carrying no 

1458 # case to lean on, and in silence: its other reading is two 

1459 # name words, which the count already refuses it behind one 

1460 if len(piece) == 2 and "split" in ptags[rest[k - 1]]: 

1461 if k >= 2 and k - 2 >= second: 

1462 k -= 1 

1463 continue 

1464 break 

1465 # #516, switch off: the writing still makes this token 

1466 # credential-SHAPED, and the parser is choosing the name 

1467 # reading over that one -- the fork the caller asked to be 

1468 # told about. Reported here, unconsumed, rather than folded 

1469 # into `bare_ambiguous` above: with the switch off the token 

1470 # never carries "vocab:suffix-ambiguous" (classify's own 

1471 # gate), so `bare_ambiguous` is already False and this is the 

1472 # ONLY place the report can be recorded. Switch ON, the token 

1473 # carries BOTH tags, so `not bare_ambiguous` is what stands 

1474 # this branch down and lets the consuming branch below take 

1475 # it; the two are not exclusive. 

1476 if (not bare_ambiguous and k >= 2 and len(piece) == 1 

1477 and SHAPE_ACRONYM_TAG in tokens[piece[0]].tags): 

1478 picks.append(tuple(piece)) 

1479 break 

1480 # #289: written case is evidence the count does not have, and 

1481 # it overrides the count in BOTH directions -- an all-caps 

1482 # member of a mixed-case name is taken with nothing to spare 

1483 # ("Jack MA"), a Title-case one is declined with plenty 

1484 # ("John Smith Ma"). The lean is the LISTED set's alone: a 

1485 # token admitted to this class by SHAPE carries no writing 

1486 # convention to read, so it takes the count (decisions/S6). 

1487 # 

1488 # k < 2 means it is the only piece left, which is not the fork 

1489 # this reports -- and not a floor the lean moves: the walk 

1490 # starts after the leading title run, so one piece behind a 

1491 # title ("Mr MA") is exactly this case and must stay a name. 

1492 # The lean is computed only past this floor -- membership, 

1493 # then the floor, then the count-or-lean, in that order, with 

1494 # nothing computed a step earlier could discard. 

1495 if bare_ambiguous and k >= 2: 

1496 # rules/S6: "a clash settled by the writing is not 

1497 # reported" -- taken as any suffix word is, and no pick 

1498 if settled_by_case(tokens[piece[0]], one_case): 

1499 k -= 1 

1500 continue 

1501 picks.append(tuple(piece)) 

1502 lean = listed_lean(tokens[piece[0]], one_case) 

1503 # peeling still leaves given + family, or the writing says 

1504 # to peel anyway 

1505 # rules/S11: "only where the name has words to spare" -- a 

1506 # generation word counts the NAME words in front of it, so 

1507 # what the walk takes there ('Pedro Junior Filho', 'Pedro VI 

1508 # Filho', 'Pedro Junior Ma Filho') is not counted as the word 

1509 # spared and then peeled as well (#890). One scan to the 

1510 # last word the walk keeps, so a run costs a step a word 

1511 front = k - 2 

1512 if AMBIGUOUS_WORD_TAG in tokens[piece[0]].tags: 

1513 front = _kept_in_front(rest, front, pieces, ptags, tokens, 

1514 one_case) 

1515 # rules/S11: "the floor holds first" -- a generation word's 

1516 # case may settle it as the suffix only where the name keeps 

1517 # a family word ('Pedro Jnr fils' keeps family 'fils', 

1518 # Derek, #890); an acronym's capitals take it with none 

1519 gated = AMBIGUOUS_WORD_TAG in tokens[piece[0]].tags 

1520 if (lean == "credential" and (not gated or front >= second) 

1521 or (lean is None and front >= second)): 

1522 k -= 1 

1523 continue 

1524 # #544: or an unambiguous credential stands IN FRONT of it 

1525 # in the same run -- 'John Smith PhD MEng' is a list of 

1526 # degrees, not a family name 'MEng'. Computed once per 

1527 # walk, and only when a member has declined and a suffix 

1528 # piece is in reach, so an ordinary name never pays for 

1529 # it. Still a pick: the fork is reported as a counted 

1530 # member's is. 

1531 # 

1532 # `rest[k - 2:0:-1]` is what stands in front of the member 

1533 # down to, not including, `rest[0]`, the name the reserve 

1534 # keeps, which never anchors (`credential_anchors`). So a 

1535 # member at k == 2 finds nothing in reach. A by-shape member 

1536 # (a lean of None) gets here at k == 2, or, counted in the 

1537 # chain's units (#620), behind a run the chain joins into 

1538 # one word ('Freiherr von Berg G.J.', at k == 3), where 

1539 # what it finds in reach is that run's words. 

1540 # The pass, once built, answers first: asked of every 

1541 # member, the reach test would walk back through the run 

1542 # each time, one look-behind per member. 

1543 # A generation word that is also a name has no company to 

1544 # keep (rules/S7's credentials): a suffix word in front of 

1545 # it is no evidence, its count above having looked past it 

1546 if AMBIGUOUS_WORD_TAG in tokens[piece[0]].tags: 

1547 break 

1548 if anchors is None and anchor_in_reach( 

1549 rest[k - 2:0:-1], pieces, ptags, tokens): 

1550 anchors = credential_anchors(rest, pieces, ptags, tokens) 

1551 if anchors is not None and anchors[k - 1]: 

1552 k -= 1 

1553 continue 

1554 break 

1555 return Peel(k, tuple(numerals), tuple(picks), anchors) 

1556 

1557 

1558def behind_the_merged_credential(rest: Sequence[int], p: int, 

1559 ptags: Sequence[Set[str]]) -> bool: 

1560 """Whether the Ph./D. pair stands right in front of `rest[p]`, 

1561 left out of the walk (`peel_walk`) though it is a credential there 

1562 all the same -- the test `run_start` asks inline, its hot loop 

1563 paying no frame for it (#827).""" 

1564 return (p > 0 and rest[p] - rest[p - 1] == 2 

1565 and "suffix" in ptags[rest[p] - 1]) 

1566 

1567 

1568def _name_word_behind(credential: WorkToken, piece: Sequence[int], 

1569 ptags: Set[str], tokens: Sequence[WorkToken], 

1570 one_case: bool | None, 

1571 lower_is_name: bool = False) -> bool: 

1572 """Whether the piece behind `credential` (a member its capitals 

1573 settle, a credential acronym written in Title case, or a given name 

1574 written short in a name of one case) reads as a word of the 

1575 name rather than a further credential, asked of its 

1576 first word, since group has merged particle runs and connective 

1577 joins by then ('de la Vega', 'Ortega y Gasset'): a particle, a word 

1578 of a script with no case, or a cased word not written in lower case 

1579 (Title case or capitals, title vocabulary included), that is no 

1580 suffix word and no member its own capitals settle. A credential 

1581 merged across a space ('Pharm D', 'Ph. D.') is no name word, nor is 

1582 a roman numeral S10 reads as the generation, listed or not 

1583 ('MD VI Jones'). Asked only through `declined_by_the_name_behind`, 

1584 of a settled member, a credential acronym written in Title case 

1585 (`acronym_in_title_case`) or a given name written short in a name 

1586 of one case (`short_given_name_in_one_case`); for the last alone 

1587 (`lower_is_name`) a word in lower case is a name word as one in 

1588 capitals is, lower case being the name's own writing there.""" 

1589 if "suffix" in ptags or "split" in ptags: 

1590 return False 

1591 tok = tokens[piece[0]] 

1592 if "particle" in tok.tags: 

1593 return True 

1594 # a word of a script with no case for the contrast is no word in 

1595 # lower case (_policy._SCRIPT_PROPERTIES, #1222), save behind a 

1596 # given name written short in a name of one case (#1394) 

1597 if (not lower_is_name 

1598 and tok.text.translate(_CASELESS_LETTERS).islower()): 

1599 return False 

1600 # a numeral S10 reads as the generation is the credential's 

1601 # company, no name word, asked of S10's predicate as 

1602 # `generation_word_before_a_name` asks it (decisions/S8, #1394) 

1603 text = tok.text.rstrip(".") 

1604 if (_ROMAN.match(text) is not None 

1605 and reads_as_generation(tok.text, tok.tags, credential.text, 

1606 one_case)): 

1607 return False 

1608 return ("vocab:suffix" not in tok.tags 

1609 and SHAPE_ACRONYM_TAG not in tok.tags 

1610 and not (AMBIGUOUS_ACRONYM_TAG in tok.tags 

1611 and settled_by_case(tok, one_case))) 

1612 

1613 

1614# rules/S8: "nor does a credential acronym written in Title case" -- 

1615# the clause this implements (decisions/S8, #1019) 

1616def acronym_in_title_case(token: WorkToken) -> bool: 

1617 """Whether an unambiguous credential ACRONYM is written as a name 

1618 word is: one run of letters, a trailing period allowed, its first 

1619 letter a capital and every later one lower case ('Md', 'Phd', 

1620 'Md.'), where a credential's writing has capitals after the first 

1621 letter ('MD', 'PhD') or periods or joiners inside it ('M.D.', 

1622 'M.d.', 'Pa-c'). The case mask is not consulted, so 'Bt', 'Kt' and 

1623 'Knt', whose own masks are Title case, read as names here too. A 

1624 suffix WORD (a generation, honorific or other word written out: 

1625 'Jr', 'Esq', 'III', 'Старший') has no capitals of its own for Title 

1626 case to drop, so its case says nothing and it is not asked. Not 

1627 `_vocab.written_as_a_name`, #564's wider case contrast, which 

1628 admits 'McDonald'. Only `run_start` asks it, where a name word 

1629 stands behind the acronym.""" 

1630 if "vocab:suffix" not in token.tags or "vocab:suffix-word" in token.tags: 

1631 return False 

1632 stem = token.text.rstrip(".") 

1633 return (len(stem) >= 2 and stem.isalpha() and stem[0].isupper() 

1634 and stem[1:].islower()) 

1635 

1636 

1637# rules/S8: "nor does a generation word written out" -- the clause 

1638# this implements (decisions/S8) 

1639def generation_word_before_a_name(token: WorkToken, 

1640 piece: Sequence[int], ptags: Set[str], 

1641 tokens: Sequence[WorkToken], 

1642 one_case: bool | None) -> bool: 

1643 """Whether a generation WORD ('Junior', 'Jr', 'Snr', 'mlađi') has 

1644 behind it, in `piece`, a word of the name, asked of the piece's 

1645 first word as `_name_word_behind` asks it: a word that is no suffix 

1646 word, no numeral S10 reads as the generation, no initial, no connective, no title word 

1647 (the run reads that as a title: 'Eric H. Holder Jr. Attorney 

1648 General') and no maiden marker, so no particle that is also title 

1649 or suffix vocabulary ('St.', 'Mc'), and is a particle or is written 

1650 in a name of one case or, 

1651 in a name of mixed case, in Title case or a script with no case -- 

1652 capitals there are a credential's writing as likely as a name's 

1653 ('de Planta jr. CF'), and lower case is no name word's. A credential 

1654 merged across a space is no name word. The numerals are S10's, read 

1655 by their own predicate, and stay out. Asked only through 

1656 `declined_by_the_name_behind`.""" 

1657 if (GENERATION_WORD_TAG not in token.tags 

1658 or _ROMAN.match(token.text.rstrip(".")) is not None 

1659 or "suffix" in ptags or "split" in ptags): 

1660 return False 

1661 tags = tokens[piece[0]].tags 

1662 text = tokens[piece[0]].text 

1663 if (not tags.isdisjoint(_NOT_A_NAME_BEHIND) 

1664 # a numeral S10 reads by its shape carries no suffix tag 

1665 # ('JOHN SMITH JUNIOR VI JONES'); asked of S10's predicate, 

1666 # so a Title-case 'Vi' leaning to the name stays one 

1667 or (_ROMAN.match(text.rstrip(".")) is not None 

1668 and reads_as_generation(text, tags, token.text, 

1669 one_case))): 

1670 return False 

1671 if "particle" in tags: 

1672 return True 

1673 # a script with no case for the contrast writes neither case 

1674 # (_policy._SCRIPT_PROPERTIES, #1222) 

1675 cased = text.translate(_CASELESS_LETTERS) 

1676 return bool(one_case) or not (cased.islower() or cased.isupper()) 

1677 

1678 

1679#: what a word behind a generation word is that is no word of the name 

1680_NOT_A_NAME_BEHIND = frozenset({"vocab:suffix", SHAPE_ACRONYM_TAG, 

1681 "initial", "conjunction", "vocab:title", 

1682 "vocab:maiden-marker"}) 

1683 

1684 

1685# rules/S8: "nor, in a name written wholly in one case, does a 

1686# credential that is also a given name written short" -- the clause 

1687# this implements (decisions/S8, #1394) 

1688def short_given_name_in_one_case(token: WorkToken, behind_at: int, 

1689 tokens: Sequence[WorkToken]) -> bool: 

1690 """Whether `token`, carrying classify's GIVEN_ABBREVIATION_TAG (a 

1691 given name written short: 'MD', 'md', 'MD.'; the caller asks that it 

1692 would start the run, so it is a credential too), stands in a name 

1693 written wholly in one case, where its case is the name's and says 

1694 nothing, with `tokens[behind_at]`, the first word of the piece 

1695 behind it, holding a letter of a script with case (_policy._SCRIPT_PROPERTIES, 

1696 #1222) and being no maiden marker. The caller has asked, inline 

1697 ahead of the call so a credential that is no such word pays no 

1698 frame, that `token` carries the tag and that `one_case` holds. The 

1699 case asked is rules/S6's: 

1700 `one_case`, the name's own words, for one of them, so appending a 

1701 clause changes nothing about it; for a word of a maiden clause or 

1702 of brackets, the WHOLE name's, which `one_case` does not cover, so a 

1703 word of a mixed-case clause is not read as one of a name of one 

1704 case ('JOHN SMITH née Ann Lee MD Jones'). A word is the clause's 

1705 where it already holds a role (extract's brackets) or a maiden 

1706 marker stands before it. A word of no cased script 

1707 behind it ('محمد علي MD حسن') keeps the run: the capitals of a Latin 

1708 'MD' before it are the writer's choice of the credential's 

1709 spelling, not the case the words around it share. A maiden marker 

1710 behind it opens a clause (M2), no name word. The rest of the 

1711 name-word test is `_name_word_behind`'s, the caller's.""" 

1712 behind = tokens[behind_at] 

1713 cased = behind.text.translate(_CASELESS_LETTERS) 

1714 if (cased.upper() == cased.lower() 

1715 or "vocab:maiden-marker" in behind.tags): 

1716 return False 

1717 # rules/S6: "The case asked of a word in a maiden clause or between 

1718 # brackets is the whole name's" 

1719 if token.role is None and not any( 

1720 "vocab:maiden-marker" in t.tags for t in tokens[:behind_at]): 

1721 return True 

1722 return is_one_case([t.text for t in tokens]) 

1723 

1724 

1725# rules/S8: "not where a name word stands behind it" -- the four 

1726# writings that decline the run there, one predicate for `run_start`, 

1727# P2's chain stop (`starts_the_run_here`) and the family part's suffix 

1728# pass in assign, which borrows it under rules/P2 before a family comma, 

1729# where S8's declines do not apply (decisions/P2, #1177) 

1730def declined_by_the_name_behind(token: WorkToken, piece: Sequence[int], 

1731 ptags: Set[str], 

1732 tokens: Sequence[WorkToken], 

1733 one_case: bool | None) -> bool: 

1734 """Whether a word that would start #602's run declines it because 

1735 of the word behind it, `piece`: a member its capitals settle, a 

1736 credential acronym written in Title case, or a given name written 

1737 short in a name of one case (`short_given_name_in_one_case`), with a 

1738 word of the name behind it (`_name_word_behind`), or a generation 

1739 word written out 

1740 before a name (`generation_word_before_a_name`). The caller asks 

1741 whether the word starts a run at all.""" 

1742 # rules/S8: "nor, in a name written wholly in one case, does a 

1743 # credential that is also a given name written short" -- the tag 

1744 # tested inline, so a credential that is no such word pays no frame 

1745 short = (bool(one_case) and GIVEN_ABBREVIATION_TAG in token.tags 

1746 and short_given_name_in_one_case(token, piece[0], tokens)) 

1747 return ((short 

1748 or AMBIGUOUS_ACRONYM_TAG in token.tags 

1749 and settled_by_case(token, one_case) 

1750 # rules/S8: "nor does a credential acronym written in 

1751 # Title case" -- the writing of a name word 

1752 or acronym_in_title_case(token)) 

1753 and _name_word_behind(token, piece, ptags, tokens, one_case, 

1754 short) 

1755 # rules/S8: "nor does a generation word written out" -- a 

1756 # filer's middle-name box, the family name behind it 

1757 or generation_word_before_a_name(token, piece, ptags, tokens, 

1758 one_case)) 

1759 

1760 

1761def _declined_here(token: WorkToken, i: int, piece: Sequence[int], 

1762 ptags: Set[str], tokens: Sequence[WorkToken], 

1763 one_case: bool | None, 

1764 declined: list[int] | None) -> bool: 

1765 """`declined_by_the_name_behind` for `run_start`, recording in 

1766 `declined`, where the caller keeps one, the index `i` of a given 

1767 name written short whose run its own writing declined, the one 

1768 decline whose writing settles nothing (rules/S8's one-case clause, 

1769 #1394): assign reports it.""" 

1770 if not declined_by_the_name_behind(token, piece, ptags, tokens, 

1771 one_case): 

1772 return False 

1773 if (declined is not None and one_case 

1774 and GIVEN_ABBREVIATION_TAG in token.tags 

1775 and short_given_name_in_one_case(token, piece[0], tokens)): 

1776 declined.append(i) 

1777 return True 

1778 

1779 

1780# rules/S8: "A credential after the name core starts a run to the 

1781# end of its part" -- applied to a finished peel (#602), so every 

1782# reader of the trailing run (assign, P5's reserve, the maiden take) 

1783# sees one answer; P2's chain stop also asks the run's start word by 

1784# word (`starts_the_run_here`), the count of name words aside. 

1785def run_start(rest: Sequence[int], names: int, 

1786 pieces: Sequence[Sequence[int]], 

1787 ptags: Sequence[Set[str]], 

1788 tokens: Sequence[WorkToken], 

1789 units: Sequence[int] | None = None, 

1790 one_case: bool | None = None, 

1791 initials_cue: bool = True, 

1792 declined: list[int] | None = None) -> int: 

1793 """Where #602's run starts in `rest[:names]`: the position of the 

1794 first credential that starts one (`starts_a_credential_run`) with 

1795 two name pieces in front of it, or `names` where none does -- with 

1796 no comma the family has to exist first. A lone particle does not 

1797 count toward the two, 'de Mesnil' being one surname, unless the 

1798 run starts right behind it (#627). The position 

1799 alone, for readers that need only where the name ends 

1800 (`trailing_start`); `credential_run` builds the rest of the answer. 

1801 

1802 The tag tests are INLINE ahead of the predicate, so a name word -- 

1803 every piece of an ordinary name -- and a connective or particle 

1804 never pay the predicate's frame: this runs on every parse, once 

1805 per piece, and a clause holding a run of links ('Puig i i i ... 

1806 Soler') otherwise paid two frames per link (decisions/parse-cost). 

1807 The predicate repeats the refusal; the inline copy is only the 

1808 cheap half of the same question. Under three names no run can 

1809 start, two core pieces having to stand in front of it. 

1810 

1811 `units` (`_chain_units`, #620) counts over pieces the chain has not 

1812 joined yet: a word the chain will join to the run in front of it 

1813 is no name word of its own, and a particle opening such a run is 

1814 the one the run makes ('der la', merged into one piece ahead of 

1815 the read, one surname).""" 

1816 if names < 3: 

1817 return names 

1818 core = 0 

1819 lone = False 

1820 for p in range(names): 

1821 q = rest[p] 

1822 tags = tokens[pieces[q][0]].tags 

1823 if core + lone >= 2: 

1824 # the Ph./D. pair standing in front of this piece starts the 

1825 # run there, though the walk leaves it out (#827): 'John 

1826 # Smith Ph. D. Jones' as 'John Smith PhD Jones' 

1827 # (`behind_the_merged_credential`, inline) 

1828 if (q - rest[p - 1] == 2 and "suffix" in ptags[q - 1] 

1829 and starts_a_credential_run(pieces[q - 1], ptags[q - 1], 

1830 tokens)): 

1831 return p 

1832 if (("vocab:suffix" in tags or "split" in ptags[q] 

1833 or AMBIGUOUS_ACRONYM_TAG in tags 

1834 or _ROMAN.match(tokens[pieces[q][0]].text.rstrip(".")) 

1835 is not None) 

1836 and tags.isdisjoint(_NOT_A_RUN_START) 

1837 # p >= 2 here: two name words stand in front 

1838 and starts_a_credential_run( 

1839 pieces[q], ptags[q], tokens, 

1840 tokens[pieces[rest[p - 1]][0]].text, one_case) 

1841 # rules/S8: "not where a name word stands behind it" 

1842 # -- a settled member followed by one is the 

1843 # writer's initials as likely as a credential 

1844 and not (initials_cue and p + 1 < len(rest) 

1845 # the Ph./D. pair behind it is a credential 

1846 # the walk leaves out (#827) 

1847 and not behind_the_merged_credential( 

1848 rest, p + 1, ptags) 

1849 and _declined_here( 

1850 tokens[pieces[q][0]], pieces[q][0], 

1851 pieces[rest[p + 1]], ptags[rest[p + 1]], 

1852 tokens, one_case, declined))): 

1853 return p 

1854 # a lone particle is not yet a name: 'de Mesnil' is one surname 

1855 # -- unless it opens a chain run, which is then the surname 

1856 # (with no `units` every piece opens its own), or the run 

1857 # starts right behind it, leaving it nothing to join: then it 

1858 # counts as a name word of its own, as 'van der' and 'von und 

1859 # zu' do (#627, 'John von PhD Jones') 

1860 if units is None or units[q] == OPENS: 

1861 lone = (len(pieces[q]) == 1 and "particle" in tags 

1862 and (units is None or q + 1 == len(units) 

1863 or units[q + 1] == OPENS)) 

1864 core += not lone 

1865 return names 

1866 

1867 

1868# rules/P6: "a particle ending the name attaches to that family 

1869# name" -- WHICH particles, asked once, by assign's given-part walk, 

1870# which both leaves them out of #602's run and attaches them (#613; 

1871# #610 had first made the run and post_rules' attachment one walk) 

1872def particle_tail(seg: Sequence[Sequence[int]], 

1873 tokens: Sequence[WorkToken]) -> tuple[int, int]: 

1874 """`seg[lo:hi]`, the run of wholly-particle pieces P6 attaches: back 

1875 from the end past pieces that hold no name word and are not 

1876 themselves particles -- a post-nominal is written BEHIND the 

1877 particle in this listing -- then back over particle pieces, 

1878 stopping at a lone member of the ambiguous credential class read as 

1879 the credential (#531: the capitals or a degree made it one, so it 

1880 is not the tussenvoegsel). 

1881 

1882 The class-member stop keys on the VOCABULARY tag and not on the 

1883 suffix role alone, which is what gives P6's attachment precedence 

1884 over S2: `vd` and `mc` are unambiguous suffix vocabulary, also 

1885 particles, also suffix-roled, and the tag is what keeps them inside 

1886 the run, while the role alone would have stood the attachment down 

1887 for #531's member too ('Doe, John DO' read family 'DO Doe' with the 

1888 condition absent, verified when #531 landed). A trailing piece that 

1889 IS particle vocabulary ends the first walk rather than being looked 

1890 past, since `vd` arrives suffix-roled and is the run. 

1891 

1892 Read off ROLES, asked at the moment assign's walk reaches #602's 

1893 run (or, with no run, once the walk has placed every piece): every 

1894 word in front of the run holds the role the walk gave it, and the 

1895 run's words hold none yet -- no name role, and a class member not 

1896 yet read as anything, the run being what will read it as the 

1897 credential. That is why the answer equals the one this would give 

1898 over the finished roles, which is what the attachment needs. 

1899 `lo == hi` where there is no such run. 

1900 

1901 The single-token tests are inline (the common piece is one token), 

1902 so the walk pays no frame per piece; it runs on every family-comma 

1903 parse.""" 

1904 hi = len(seg) 

1905 while hi > 0: 

1906 piece = seg[hi - 1] 

1907 if (all("particle" in tokens[i].tags for i in piece) 

1908 if len(piece) > 1 else 

1909 "particle" in tokens[piece[0]].tags): 

1910 break 

1911 if (any(tokens[i].role in NAME_ROLES for i in piece) 

1912 if len(piece) > 1 else 

1913 tokens[piece[0]].role in NAME_ROLES): 

1914 break 

1915 hi -= 1 

1916 lo = hi 

1917 while lo > 0: 

1918 piece = seg[lo - 1] 

1919 if len(piece) == 1: 

1920 tok = tokens[piece[0]] 

1921 if "particle" not in tok.tags or ( 

1922 AMBIGUOUS_ACRONYM_TAG in tok.tags 

1923 and tok.role in SUFFIX_OR_UNREAD): 

1924 break 

1925 elif not all("particle" in tokens[i].tags for i in piece): 

1926 break 

1927 lo -= 1 

1928 return lo, hi 

1929 

1930 

1931 

1932def has_name_content(piece: Sequence[int], 

1933 tokens: Sequence[WorkToken]) -> bool: 

1934 """Whether a piece holds a letter or digit: a piece with none is 

1935 no name word (rules/A2), so a run that takes it in absorbs no 

1936 name and reports nothing. C-level, no frame per character.""" 

1937 return any(map(str.isalnum, "".join([tokens[i].text for i in piece]))) 

1938 

1939 

1940def credential_run(rest: Sequence[int], peel: Peel, p: int, 

1941 pieces: Sequence[Sequence[int]], 

1942 ptags: Sequence[Set[str]], 

1943 tokens: Sequence[WorkToken], 

1944 one_case: bool | None = None) -> Peel: 

1945 """`peel` with its name count cut back to `p`, where #602's run 

1946 starts (`run_start`, which the caller asks first so that a name 

1947 with no run pays one frame, not two). 

1948 

1949 Every word from the credential on is then in the suffix run, 

1950 except a title word, which is recorded in `run_titles` for assign 

1951 to read as a title; a name word the run absorbs is recorded in 

1952 `absorbed` for assign to report -- not a word with no letter or 

1953 digit in it, and not a member the peel already reported as a pick. 

1954 One pass, the suffix test first: a credential, the common word in 

1955 a run, leaves both lists without the title test's frame.""" 

1956 run_titles: list[int] = [] 

1957 absorbed: list[tuple[int, ...]] = [] 

1958 # a numeral starting the run is read as the generation, which a 

1959 # shape alone makes a call, reported as the peel's are (rules/S10) 

1960 numerals = peel.numerals 

1961 # where the Ph./D. pair the walk leaves out starts the run 

1962 # (`run_start`), rest[p] is the first word behind it, read like the 

1963 # rest; else rest[p] is the credential 

1964 first = p if behind_the_merged_credential(rest, p, ptags) else p + 1 

1965 start = pieces[rest[p]] 

1966 if (first > p and len(start) == 1 and _ROMAN.match( 

1967 (tok := tokens[start[0]]).text.rstrip(".")) is not None 

1968 and not is_listed_numeral(tok.text, tok.tags) 

1969 and not numeral_settled_by_case(tok.text, one_case)): 

1970 numerals = (tuple(start), *numerals) 

1971 for q in rest[first:peel.names]: 

1972 if is_suffix_piece(pieces[q], ptags[q], tokens): 

1973 continue 

1974 if is_title_piece(pieces[q], ptags[q], tokens): 

1975 run_titles.append(q) 

1976 continue 

1977 piece = tuple(pieces[q]) 

1978 if piece not in peel.picks and has_name_content(piece, tokens): 

1979 absorbed.append(piece) 

1980 return Peel(p, numerals, peel.picks, peel.anchors, 

1981 tuple(run_titles), tuple(absorbed)) 

1982 

1983 

1984# rules/H5: "only a word the vocabulary knows as a title is one, 

1985# and a bare title word is a name word" 

1986# -- the trailing run's own predicate. NOT is_leading_title: 

1987# that predicate carries H2's unlisted-abbreviation inference, which is 

1988# the LEADING slot's shape rule and has no trailing counterpart, so 

1989# with it 'John Smith Xyz.' would lose its family name to a title 

1990# (decisions/H5). Classify's CHAIN_TITLE_TAG reads a word's title 

1991# vocabulary through the same "vocab:title" tag is_title_piece reads, 

1992# so the leading and trailing runs cannot disagree about what a title 

1993# WORD is while disagreeing, deliberately, about what a title SHAPE is 

1994# -- save the word H5's written-short clause adds, classify's 

1995# TRAILING_TITLE_TAG, which no leading read admits (#999). 

1996def trailing_titles(rest: Sequence[int], pieces: Sequence[Sequence[int]], 

1997 ptags: Sequence[Set[str]], 

1998 tokens: Sequence[WorkToken], 

1999 end: int | None = None, 

2000 salutations: bool = False) -> int: 

2001 """How many pieces of `rest` the trailing title chain LEAVES 

2002 standing: `rest[:kept]` are the name pieces and `rest[kept:]` the 

2003 title words the chain took (wearing the abbreviation shape, a title 

2004 listed whole with a period inside it, or under `salutations` a bare 

2005 salutation), in piece order. Counted 

2006 the way `peel_trailing` counts, so the two answers compose without 

2007 arithmetic at the call site. `rest` is the caller's NAME pieces: 

2008 on the no-comma path what the S2 peel left, after a family comma 

2009 the segment's pieces that the segment's own suffix reading does 

2010 not claim, and in `tail_reading` the leftovers of whichever peel 

2011 is current. `end`, where given, reads `rest[:end]` without the 

2012 copy, for `tail_reading`'s passes. `salutations` is the given 

2013 part after a family comma asking, where a bare salutation the 

2014 vocabulary marks `after_given` chains as well (rules/H8). 

2015 Floor: the first position of `rest` is never taken, so one name 

2016 piece stands and a name is never all title. An empty 

2017 `rest` returns 0, which is what leaves assign's bare-suffix 

2018 carve-out reached exactly as before. 

2019 

2020 ONE WORD per piece, the same gate the leading peel's give-back 

2021 uses: a joined unit is not the shape this reads, and the tokens of 

2022 one are not each a title word. 

2023 

2024 Every parse with a name word to place enters this frame -- assign 

2025 asks the question here rather than answering a cheaper version of 

2026 it inline (mechanisms.md#ONE-PREDICATE-PER-QUESTION) -- so what it 

2027 costs an ordinary name is one frame and one tag test. The 

2028 exceptions return before it: a segment that is all title, and a 

2029 comma part read wholly as a credential run, have no name piece to 

2030 hand this (52 of the 1289 corpus parses, measured 2026-09-09 -- 

2031 'Coach', 'Lord of the Universe', 'Smith, Jr.', 'MD, PHD'). 

2032 The word test is classify's CHAIN_TITLE_TAG, a set membership test 

2033 (a C call, no Python frame), so the ordinary parse pays one tag 

2034 test and stops (decisions/parse-cost, #1171). 

2035 """ 

2036 k = len(rest) if end is None else end 

2037 while k > 1: 

2038 idx = rest[k - 1] 

2039 piece = pieces[idx] 

2040 # classify's CHAIN_TITLE_TAG is the word test, a C-level read 

2041 # (#1171); no #323 veto on the shape there, unlike 

2042 # is_leading_title's: the shape is ANDed with a vocabulary 

2043 # read, so the word is listed, and a listed CJK title wearing a 

2044 # stop should read as a title 

2045 if len(piece) == 1 and ( 

2046 CHAIN_TITLE_TAG in tokens[piece[0]].tags 

2047 # rules/H8: "the given part after it ends in a word whose 

2048 # title reading is a salutation" -- the salutation chains 

2049 # as a period-marked title does ("It reads as the 

2050 # period-marked spelling reads"); a tag test, so a name 

2051 # word pays no frame 

2052 or (salutations and "vocab:after-given-title" 

2053 in tokens[piece[0]].tags)): 

2054 k -= 1 

2055 continue 

2056 break 

2057 return k 

2058 

2059 

2060# rules/H5: "successive single words that wear the abbreviation 

2061# shape and are title vocabulary chain into the title from the end", 

2062# and "a title the vocabulary lists whole with a period inside it 

2063# chains without a final one" -- one word's half of that, for a caller 

2064# asking it of a piece the chain did not walk to: the maiden take, 

2065# choosing the words the clause-free view is read over (#601), and 

2066# P13's walk back to a connective ending the name words (#1168). 

2067# Both read classify's CHAIN_TITLE_TAG, the one statement of the word 

2068# test (#1171); `trailing_titles` reads it inline, for the frame budget 

2069# its docstring states, and adds its `salutations` arm, which no 

2070# caller of this one asks. 

2071def is_trailing_title_word(piece: Sequence[int], 

2072 tokens: Sequence[WorkToken]) -> bool: 

2073 """Whether one piece is a word H5's trailing chain takes: a lone 

2074 token wearing the abbreviation shape that the title vocabulary 

2075 lists, or that classify marks as a title written short that may 

2076 be a given name (TRAILING_TITLE_TAG), or a title the vocabulary 

2077 lists whole with a period inside it, which classify marks 

2078 (JOINED_TITLE_TAG) and which needs no final period -- the words 

2079 classify marks CHAIN_TITLE_TAG. Position is the caller's question 

2080 -- this answers only what the word is.""" 

2081 return len(piece) == 1 and CHAIN_TITLE_TAG in tokens[piece[0]].tags 

2082 

2083 

2084#: lone-word tags `trailing_candidates` admits on: the ambiguous class, 

2085#: listed or by shape, and any suffix word -- an initial-shaped one 

2086#: included, which `is_suffix_piece` vetoes and the numeral fork reads 

2087_TRAILING_WORD_TAGS = frozenset({AMBIGUOUS_ACRONYM_TAG, SHAPE_ACRONYM_TAG, 

2088 "vocab:suffix"}) 

2089 

2090 

2091# rules/M2: "It takes them up to the trailing run of post-nominals 

2092# and titles that the end of the name reads as if the clause were not 

2093# written" -- which words of a clause might be in that run, written 

2094# beside the peel and the chain whose admissions it has to cover (#610) 

2095def trailing_candidates(lo: int, pieces: Sequence[Sequence[int]], 

2096 ptags: Sequence[Set[str]], 

2097 tokens: Sequence[WorkToken]) -> int: 

2098 """The first of the pieces after `lo` that `tail_reading` might read 

2099 into the trailing run: `pieces[c:]`, a SUPERSET of what it takes, 

2100 for the maiden take to build its clause-free view over and let 

2101 `tail_reading` decide. `pieces[lo]` itself is never a candidate. 

2102 

2103 Back from the end over every piece the peel or the chain admits on 

2104 its own terms -- a suffix piece, a member of the ambiguous class, 

2105 an initial-shaped suffix word, a period-marked title word or a 

2106 title listed whole with a period inside it -- and 

2107 over a roman numeral the numeral's predicate admits, asked with no 

2108 case so it stays a superset: one of two or more letters wherever it 

2109 stands, the peel reading it anywhere in the run (#752), and one of 

2110 one letter where nothing stands behind it but such title words and 

2111 group-flagged suffix pieces: the chain takes the titles first and 

2112 the walk never holds the flagged pieces ('Ph. D.'), so either way 

2113 that numeral is the walk's last piece and the fork reads it. Then 

2114 back to the first 

2115 credential that starts #602's run, whose words the run takes 

2116 whatever they are. A BARE title word is no candidate: H5's chain 

2117 does not take one, and in the view it would only inflate the count 

2118 of words to spare. 

2119 

2120 The superset is pinned by tests/v2/pipeline/test_pieces.py over a 

2121 generated grid against `tail_reading` itself, so a new admission 

2122 in the peel or the chain fails there until this covers it.""" 

2123 c = len(pieces) 

2124 titles_behind = True 

2125 while c - 1 > lo: 

2126 k = c - 1 

2127 piece = pieces[k] 

2128 title = is_trailing_title_word(piece, tokens) 

2129 if not (title or "suffix" in ptags[k] or "split" in ptags[k] 

2130 or is_suffix_piece(piece, ptags[k], tokens) 

2131 or (len(piece) == 1 and ( 

2132 not tokens[piece[0]].tags.isdisjoint(_TRAILING_WORD_TAGS) 

2133 or ((titles_behind 

2134 or len(tokens[piece[0]].text.rstrip(".")) > 1) 

2135 and reads_as_generation( 

2136 tokens[piece[0]].text, tokens[piece[0]].tags, 

2137 tokens[pieces[k - 1][0]].text, None))))): 

2138 break 

2139 # a group-flagged suffix piece is outside the peel's walk 

2140 # altogether (`peel_walk` drops it), so it is behind the 

2141 # numeral the way a chained title is 

2142 titles_behind = titles_behind and (title or "suffix" in ptags[k]) 

2143 c = k 

2144 # the tag test is the predicate's own necessary half, inline so a 

2145 # name word pays no frame 

2146 return next((j for j in range(lo + 1, c) 

2147 if ("suffix" in ptags[j] or "split" in ptags[j] 

2148 or "vocab:suffix" in tokens[pieces[j][0]].tags 

2149 or _ROMAN.match(tokens[pieces[j][0]].text.rstrip(".")) 

2150 is not None) 

2151 and starts_a_credential_run( 

2152 pieces[j], ptags[j], tokens, 

2153 tokens[pieces[j - 1][0]].text) 

2154 # a member its capitals settle, asked with the case as 

2155 # mixed so the superset holds whatever the name's case 

2156 or AMBIGUOUS_ACRONYM_TAG in tokens[pieces[j][0]].tags 

2157 and starts_a_credential_run(pieces[j], ptags[j], tokens, 

2158 None, False)), 

2159 c) 

2160 

2161 

2162# rules/H5: "the title is TRANSPARENT to the suffix reading: where 

2163# two or more name words stand, what stands once the chain is taken 

2164# reads exactly as it would read written without the title, plus the 

2165# title" 

2166def tail_reading(rest: list[int], pieces: Sequence[Sequence[int]], 

2167 ptags: Sequence[Set[str]], 

2168 tokens: Sequence[WorkToken], 

2169 one_case: bool | None, 

2170 units: Sequence[int] | None = None, 

2171 count_numeral: bool = True, 

2172 salutations: bool = False, 

2173 initials_cue: bool = True, 

2174 ) -> tuple[list[int], tuple[int, ...], Peel]: 

2175 """The S2 peel and the H5 chain read together to a FIXED POINT: 

2176 peel, chain, splice the chained pieces out, peel again over what 

2177 is left -- the name pieces the chain kept, then the pieces the 

2178 peel had taken, in original order -- until the chain takes 

2179 nothing. Where it takes nothing on the first pass, which is almost 

2180 every name, that first peel is the answer and the loop costs one 

2181 comparison. 

2182 

2183 Returns the walk with the chained pieces spliced out, the pieces 

2184 the chain took, and the FINAL peel -- whose numeral fork and 

2185 ambiguous picks are the ones assign reports. The walk is 

2186 partitioned by that peel exactly as a caller partitions its own: 

2187 `rest[:peel.names]` the name pieces, `rest[peel.names:]` the 

2188 suffixes. A bare tuple rather than a named one because a 

2189 NamedTuple's __new__ is a frame of its own on every parse 

2190 (decisions/parse-cost), and `_group_segment` returns its three 

2191 the same way. 

2192 

2193 Transparency is what the fixed point buys: 'X Prof. Y' reads 

2194 exactly as 'X Y' reads plus the title, however many titles are 

2195 written and wherever the peel then stops. Iterating ONCE reads a 

2196 second title only half way -- 'John Prof. MA Prof.' un-peeled the 

2197 acronym and re-exposed the first title, reading family 'Prof.' 

2198 with suffix 'MA' where 'John Prof. MA' read family 'MA' (written 

2199 in one case today: since #289 capitals in a mixed-case name take 

2200 the acronym whatever the count, so 'john prof. ma prof.' and 

2201 'john prof. ma' are the pair that still reads family 'ma'). 

2202 

2203 One function for assign's placement, group's bound-given reserve 

2204 (P5), which must count the name words assign will leave, and the 

2205 maiden take (rules/M2), which must end the clause where the 

2206 reading of the name will begin -- and since #614, for a main 

2207 segment, the one read group takes between P3's joins and the 

2208 particle chain (`read_trailing_run`), which assign and the reserve 

2209 take their answer from instead. Deriving that agreement twice is what left the two 

2210 disagreeing at S4's bare-ambiguous reserve: 'abdul rahman MA' 

2211 declined the join and 'abdul rahman MA Prof.' took it 

2212 (mechanisms.md#ONE-PREDICATE-PER-QUESTION). 

2213 

2214 `rest` is a peel_walk list and is not mutated -- the splice 

2215 rebinds this local -- so a caller's own reference still names the 

2216 walk it built. Every caller reads the one returned here instead, 

2217 which is the one the final peel partitions. 

2218 

2219 The chain's floor is `trailing_titles`' own, one name piece left 

2220 standing. 

2221 

2222 #602's credential run is applied to the final peel on the way out 

2223 (`credential_run`), so every reader sees the run where it starts. 

2224 

2225 Linear in the walk (#558). Re-peeling the whole walk every pass 

2226 re-read each suffix the passes before had already peeled, so a 

2227 name ending 'MA Prof. MA Prof. ...' cost the square of its tail. 

2228 A pass instead RESUMES the walk where the splice left it, over 

2229 `rest` as written: the pieces in front of the splice are the ones 

2230 a fresh walk would meet, and `credential_anchors` reads each 

2231 position off the pieces in front of it, so the carried pass 

2232 answers for them too. What a fresh walk reads differently is the 

2233 position COUNT of the pieces it already peeled, which the splice 

2234 lowers, and two tests of the walk read it. The acronym fork's 

2235 words to spare: a member whose count falls below three can 

2236 decline where it was taken -- 'john prof. ma ma prof.' is exactly 

2237 that, keeping family 'ma' only because the second pass walks 

2238 afresh -- so a pass resumes only with two or more pieces in front 

2239 of the splice, every peeled piece then counting three or more. 

2240 And the numeral fork, which reads the walk's last piece against 

2241 the one before it: a pass resumes only with two or more peeled 

2242 pieces behind the splice, so that pair is the one the first walk 

2243 read. Elsewhere -- a splice near the front of the walk, or before 

2244 two pieces have been peeled -- the pass walks afresh over the 

2245 spliced pieces. The fuzz that checked this against the 

2246 re-peeling loop, the three conditions each shown load-bearing by 

2247 a weakened copy failing it, is recorded on the PR closing #558. 

2248 `count_numeral` is `peel_trailing`'s, passed to every pass, and 

2249 `salutations` is `trailing_titles`', passed to every chain. 

2250 The splice itself is never materialized in between: the runs are 

2251 collected back to front and joined once. 

2252 """ 

2253 # where the second name unit opens, found once for the read: a 

2254 # pass keeps `rest[:hi]`, so it holds while it stands in front of 

2255 # the splice, and each pass rescanning for it from the front cost 

2256 # the square of a run behind a long joined surname (#620's 

2257 # /simplify, 'Freiherr von Berg Berg ... MA Dr. MA Dr. ...') 

2258 second = 1 if units is None else second_unit(rest, units) 

2259 peeled = peel_trailing(rest, pieces, ptags, tokens, one_case, 

2260 units=units, second=second, 

2261 count_numeral=count_numeral) 

2262 kept = trailing_titles(rest, pieces, ptags, tokens, 

2263 end=peeled.names, salutations=salutations) 

2264 declined: list[int] = [] 

2265 if kept == peeled.names: 

2266 p = run_start(rest, peeled.names, pieces, ptags, tokens, units, 

2267 one_case, initials_cue, declined) 

2268 peeled = (peeled if p == peeled.names else credential_run( 

2269 rest, peeled, p, pieces, ptags, tokens, one_case)) 

2270 return rest, (), (peeled._replace(declined=tuple(declined)) 

2271 if declined else peeled) 

2272 # `rest[:hi]` stands as written; `behind` holds the peeled runs 

2273 # the splices left after it, and `titled` the chained ones, each 

2274 # back to front -- a pass's run goes in FRONT of what the pass 

2275 # before it took 

2276 hi = len(rest) 

2277 behind: list[list[int]] = [] 

2278 behind_count = 0 

2279 titled: list[list[int]] = [] 

2280 picks = list(peeled.picks) 

2281 numerals = list(peeled.numerals) 

2282 while kept < peeled.names: 

2283 names = peeled.names 

2284 titled.append(rest[kept:names]) 

2285 behind.append(rest[names:hi]) 

2286 behind_count += hi - names 

2287 # the walk stopped AT the chain's last title, and a fresh walk 

2288 # will not meet that piece: drop the pick it made there 

2289 if picks and picks[-1] == tuple(pieces[rest[names - 1]]): 

2290 picks.pop() 

2291 hi = kept 

2292 # Counted in units (#620) the position test still answers: a 

2293 # splice lowers a count only by taking out titles that open 

2294 # units of their own, and with fewer than two units in front of 

2295 # it every piece there is in the first piece's chain run, which 

2296 # the titles behind it join -- they count nothing, so nothing 

2297 # the walk peeled loses a word to spare (fuzzed over 372,330 

2298 # names against a units test here: no difference) 

2299 if kept >= 2 and behind_count >= 2: 

2300 peeled = peel_trailing(rest, pieces, ptags, tokens, one_case, 

2301 start=hi, anchors=peeled.anchors, 

2302 units=units, second=second, 

2303 count_numeral=count_numeral) 

2304 picks.extend(peeled.picks) 

2305 numerals.extend(peeled.numerals) 

2306 else: 

2307 rest = rest[:hi] + [j for run in reversed(behind) for j in run] 

2308 if units is not None and second >= hi: 

2309 second = second_unit(rest, units) 

2310 hi = len(rest) 

2311 behind, behind_count = [], 0 

2312 peeled = peel_trailing(rest, pieces, ptags, tokens, one_case, 

2313 units=units, second=second, 

2314 count_numeral=count_numeral) 

2315 picks = list(peeled.picks) 

2316 numerals = list(peeled.numerals) 

2317 kept = trailing_titles(rest, pieces, ptags, tokens, 

2318 end=peeled.names, salutations=salutations) 

2319 if behind: 

2320 rest = rest[:hi] + [j for run in reversed(behind) for j in run] 

2321 final = Peel(peeled.names, tuple(numerals), tuple(picks), None) 

2322 p = run_start(rest, final.names, pieces, ptags, tokens, units, 

2323 one_case, initials_cue, declined) 

2324 final = (final if p == final.names else credential_run( 

2325 rest, final, p, pieces, ptags, tokens, one_case)) 

2326 return (rest, tuple(j for run in reversed(titled) for j in run), 

2327 final._replace(declined=tuple(declined)) if declined 

2328 else final) 

2329 

2330 

2331class TailRead(NamedTuple): 

2332 """S2's trailing run as group reads it ONCE, after P3's connective 

2333 joins and before the particle chain and the bound-given join 

2334 (#614), handed to assign so neither join can move it and assign 

2335 reads no second time -- save where group's joins left no name word 

2336 in front of the run, and assign reads the name again so it keeps 

2337 one ('Prince of Wales Jr'). Token indices rather than piece 

2338 indices, since group's joins renumber the pieces in front of the 

2339 run: `tail` holds every token the run took, `titles` those the H5 

2340 chain took and `run_titles` the title words inside #602's run (both 

2341 inside `tail`), and `peel` the final peel, whose numeral fork, bare 

2342 ambiguous picks and absorbed name words are what assign reports; 

2343 its `names` counts the name pieces as the read left them.""" 

2344 

2345 tail: frozenset[int] 

2346 titles: frozenset[int] 

2347 run_titles: frozenset[int] 

2348 peel: Peel 

2349 

2350 

2351# rules/P2: "A particle joins the words after it into one name part, 

2352# the join running until the next particle starts a group of its own" 

2353# -- how far, asked by the chain and by S2's read alike (#620), so the 

2354# units the read counts are the ones the chain then builds 

2355def chain_run_end(k: int, pieces: Sequence[Sequence[int]], 

2356 ptags: Sequence[Set[str]], 

2357 tokens: Sequence[WorkToken], end: int, 

2358 one_case: bool | None = None, 

2359 given_slot: bool = False) -> int: 

2360 """Where the chain run opened by the particle `pieces[k]` ends: past 

2361 the particles straight behind it, then past the name words up to 

2362 `end`, a suffix piece S8 would start its run at, a member its 

2363 capitals settle as the credential in the given part after a family 

2364 comma, or the next particle. `pieces[k:j]` is the one name unit P2 

2365 makes of them; `j == k + 1` where it makes none. `one_case` is 

2366 ParseState's. 

2367 

2368 A suffix piece stops it only where `starts_the_run_here` says S8 

2369 would start its run there, so a suffix word S8 starts no run at 

2370 ('Abd') or declines for its writing with a name word behind it 

2371 ('Md', 'Jr.') is the chain's (rules/P2, #1177), save the second in 

2372 the given part after a family comma (`given_slot`), where S8's run 

2373 starts behind the given word whatever stands behind it; and a 

2374 particle that is suffix vocabulary too opens no chain over a suffix 

2375 word right behind it. 

2376 

2377 Only the given part after a family comma stops at a settled member: 

2378 there the member starts S8's run behind the given word whatever 

2379 stands in front, so the chain leaves it to the run. Elsewhere the 

2380 trailing read's `end` stops the chain at a member the read takes, 

2381 and a stop at one it declines would strand it as a name word between 

2382 the particle run and the words behind it (#785's review). 

2383 

2384 The particle test is `is_prefix_piece`'s definition written inline: 

2385 the walk runs per piece of every chained name (AGENTS.md's frame 

2386 budget, question 1), and so is the member tag ahead of the 

2387 settled test.""" 

2388 count = len(pieces) 

2389 j = k + 1 

2390 while j < count and ("prefix" in ptags[j] 

2391 or len(pieces[j]) == 1 

2392 and "particle" in tokens[pieces[j][0]].tags): 

2393 j += 1 

2394 settled_case = one_case if given_slot else None 

2395 while (j < end and "prefix" not in ptags[j] 

2396 and not (len(pieces[j]) == 1 

2397 and "particle" in tokens[pieces[j][0]].tags) 

2398 # rules/P2: "a trailing suffix begins" -- at a suffix word 

2399 # S8 would start its run at; one it declines, a name word 

2400 # behind it, is the chain's (decisions/P2, #1177) 

2401 and not (is_suffix_piece(pieces[j], ptags[j], tokens) 

2402 # rules/P2: "a particle that is suffix vocabulary 

2403 # too opens no chain over a suffix word right behind 

2404 # it" -- P9's reading before a comma, kept wherever 

2405 # the chain runs (decisions/P2, #1177) 

2406 and (j == k + 1 and len(pieces[k]) == 1 

2407 and "vocab:suffix" in tokens[pieces[k][0]].tags 

2408 or starts_the_run_here(j, pieces, ptags, tokens, 

2409 one_case, given_slot))) 

2410 # rules/S6: "a clash settled by the writing is not reported" 

2411 # -- and the chain does not take the settled credential in 

2412 and not (len(pieces[j]) == 1 

2413 and AMBIGUOUS_ACRONYM_TAG in tokens[pieces[j][0]].tags 

2414 and settled_by_case(tokens[pieces[j][0]], 

2415 settled_case))): 

2416 j += 1 

2417 return j 

2418 

2419 

2420def starts_the_run_here(j: int, pieces: Sequence[Sequence[int]], 

2421 ptags: Sequence[Set[str]], 

2422 tokens: Sequence[WorkToken], 

2423 one_case: bool | None, 

2424 given_slot: bool) -> bool: 

2425 """Whether the suffix piece `pieces[j]` would start #602's run 

2426 where it stands, as `run_start` asks it, the count of name words in 

2427 front aside: it starts one (`starts_a_credential_run`) and, outside 

2428 the given part after a family comma, the word behind it, if any, 

2429 does not decline it (`declined_by_the_name_behind`). A word written 

2430 as a name ('Md', 'Abd', 'Jr.' before a name) is no stop for P2's 

2431 chain there, and none for assign's family-part pass behind a 

2432 particle, the two callers.""" 

2433 if not starts_a_credential_run(pieces[j], ptags[j], tokens, 

2434 tokens[pieces[j - 1][0]].text, 

2435 one_case): 

2436 return False 

2437 if given_slot or j + 1 == len(pieces) or len(pieces[j]) != 1: 

2438 return True 

2439 return not declined_by_the_name_behind( 

2440 tokens[pieces[j][0]], pieces[j + 1], ptags[j + 1], tokens, one_case) 

2441 

2442 

2443# rules/P2: "A particle joins the words after it into one name part" 

2444# -- the particles straight behind it first, merged ahead of S2's read 

2445# so the read counts and absorbs the run as the one piece the chain 

2446# makes of it (#625) 

2447def merge_particle_runs(pieces: list[list[int]], ptags: list[set[str]], 

2448 tokens: Sequence[WorkToken], 

2449 n: int) -> tuple[set[int], int | None]: 

2450 """Merge each run of two or more adjacent particles past the 

2451 chain's leading position into one piece, the one `chain_run_end` 

2452 would open its run with ('van der', 'van mc'). The merged piece is 

2453 a particle still (`prefix`), and no title: a P3 join can carry the 

2454 tag in from a word in both vocabularies ('St und Do'), and the 

2455 merged run would then read as a leading title. 

2456 

2457 `n` is the end of the leading title run (`leading_titles`), read 

2458 before anything merges. Returns the first token of each merged 

2459 piece -- the chain's PARTICLE_OR_GIVEN report keys on a run that 

2460 claimed something past its particle, which a merged run has though 

2461 `chain_run_end` then claims nothing more -- and the leading 

2462 position (`chain_lead`) where it asked it, else None. 

2463 

2464 The particle test is `is_prefix_piece`'s definition written 

2465 inline, and the leading position is asked only where two particles 

2466 stand together past the first piece (AGENTS.md's frame budget, 

2467 question 1).""" 

2468 prefix: list[bool] = [] 

2469 for k in range(len(pieces)): 

2470 prefix.append("prefix" in ptags[k] 

2471 or len(pieces[k]) == 1 

2472 and "particle" in tokens[pieces[k][0]].tags) 

2473 merged: set[int] = set() 

2474 k = 1 

2475 while k + 1 < len(prefix) and not (prefix[k] and prefix[k + 1]): 

2476 k += 1 

2477 if k + 1 >= len(prefix): 

2478 return merged, None 

2479 lead = chain_lead(pieces, ptags, tokens, n) 

2480 k = lead + 1 

2481 while k < len(prefix): 

2482 if prefix[k]: 

2483 q = k + 1 

2484 while q < len(prefix) and prefix[q]: 

2485 q += 1 

2486 if q > k + 1: 

2487 merged.add(pieces[k][0]) 

2488 merge_pieces(pieces, ptags, k, q, add={"prefix"}, 

2489 drop={"title"}) 

2490 del prefix[k + 1:q] 

2491 k += 1 

2492 return merged, lead 

2493 

2494 

2495def _chain_units(pieces: Sequence[Sequence[int]], 

2496 ptags: Sequence[Set[str]], 

2497 tokens: Sequence[WorkToken], 

2498 n: int, lead: int | None = None, 

2499 one_case: bool | None = None) -> list[int] | None: 

2500 """The name units P2's chain will make of `pieces`, as a mark per 

2501 piece -- OPENS where a piece opens a unit, and JOINED where the 

2502 chain will join a name word to the run in front of it and the 

2503 reading does not weigh the word (`_weighed`, which keeps a word of 

2504 its own what a position always counted as one). The particles 

2505 straight behind each other are one piece already 

2506 (`merge_particle_runs`, #625), so a particle run is one unit and a 

2507 dual inside it ('van mc', 'von vd') no word the read can take. 

2508 `n` is the end of the leading title run, and the chain starts past 

2509 its leading position (`chain_lead`, the one answer group's chain 

2510 takes too, #624; `lead` where the caller has asked it already), 

2511 which opens no unit inside the titles: the name starts at `n`. 

2512 

2513 Nothing else is merged: the read counts with the flags and reads 

2514 every other piece as written, so no word it weighs is hidden 

2515 inside a unit 

2516 (#620; the merged copy #614 read through hid a title inside a 

2517 credential run and a shape-only numeral, and its indices drifted 

2518 from the pieces'). None where no particle stands past the first 

2519 piece, every piece then its own unit.""" 

2520 count = len(pieces) 

2521 prefix = [("prefix" in ptags[k] 

2522 or len(pieces[k]) == 1 

2523 and "particle" in tokens[pieces[k][0]].tags) 

2524 for k in range(count)] 

2525 if not any(prefix[1:]): 

2526 return None 

2527 units = [OPENS] * count 

2528 k = (chain_lead(pieces, ptags, tokens, n) if lead is None 

2529 else lead) + 1 

2530 while k < count: 

2531 if prefix[k]: 

2532 j = chain_run_end(k, pieces, ptags, tokens, count, one_case) 

2533 q = k + 1 

2534 # a split credential is weighed as the class it is a 

2535 # member of (rules/S12); a suffix word with an unweighed 

2536 # word behind it inside the chain's run is one the chain 

2537 # took because S8 starts no run there or declines one, so 

2538 # the peel cannot reach it and it is no word of its own 

2539 # (rules/P2, decisions/P2 (#1177)) 

2540 while (q < j and "split" not in ptags[q] 

2541 and (not _weighed(pieces[q], tokens) 

2542 or q + 1 < j 

2543 and not _weighed(pieces[q + 1], tokens) 

2544 and is_suffix_piece(pieces[q], ptags[q], tokens))): 

2545 units[q] = JOINED 

2546 q += 1 

2547 k = j 

2548 continue 

2549 k += 1 

2550 return units 

2551 

2552 

2553def _weighed(piece: Sequence[int], tokens: Sequence[WorkToken]) -> bool: 

2554 """Whether a word the chain will join is one the trailing reading 

2555 WEIGHS, and so counts as a word of its own, as a position always 

2556 counted it: a suffix word of either kind, the ambiguous class, a 

2557 word in it by shape, an initial, a roman numeral by shape, or a 

2558 period-marked title word. A word the chain joins and the reading 

2559 weighs is a word the reading may yet take ('Freiherr von Berg MA 

2560 X.Y.Z.' keeps suffix 'MA X.Y.Z.'), so it ends the plain run the 

2561 count folds into the particle (#620's review); a title written 

2562 short that may be a given name is one too, H5's chain taking it 

2563 as it takes a listed title (#999), and so is a title listed whole 

2564 with a period inside it, which the chain takes without a final one 

2565 (#1104). A connective join is one name word, P3's own count. The 

2566 tests are inline: this asks once per word behind a particle run.""" 

2567 if len(piece) > 1: 

2568 return False 

2569 tok = tokens[piece[0]] 

2570 return (not tok.tags.isdisjoint(_WEIGHED_TAGS) 

2571 or _ROMAN.match(stem := tok.text.rstrip(".")) is not None 

2572 and stem != "") 

2573 

2574 

2575#: the tags any one of which makes `_weighed` True for a one-word 

2576#: piece: the trailing reading's lone-word tags, an initial, and a word 

2577#: H5's chain takes (#999, #1104, #1171) 

2578_WEIGHED_TAGS = _TRAILING_WORD_TAGS | {"initial", CHAIN_TITLE_TAG} 

2579 

2580 

2581def read_trailing_run(pieces: Sequence[Sequence[int]], 

2582 ptags: Sequence[Set[str]], 

2583 tokens: Sequence[WorkToken], 

2584 one_case: bool | None, n: int, 

2585 lead: int | None = None, 

2586 ) -> tuple[TailRead, int] | None: 

2587 """`tail_reading` read once over a segment's pieces as group holds 

2588 them after rules/P3's connective joins and before the particle 

2589 chain (#614), counting name words by the units the chain will make 

2590 (`_chain_units`, #620): a `TailRead`, and the index in `pieces` of 

2591 the first piece of the run, which runs to the end. None where there 

2592 is nothing to read (no name piece past the leading titles), and 

2593 where the run is not one block at the end of `pieces`: a title the 

2594 H5 chain takes standing in front of a name word the peel declined 

2595 ('John Dr. G.J.'), the one shape whose run holds a name piece -- 

2596 there group joins as before #614 and assign reads for itself. A 

2597 segment the read takes nothing from reads as a run of no pieces, at 

2598 the end. 

2599 

2600 `n` is the end of the leading title run (`leading_titles`) and 

2601 `lead` the chain's leading position where the caller has asked it, 

2602 both read before `merge_particle_runs` merged the pieces: the merge 

2603 starts past the lead and drops the title tag, so it moves the lead 

2604 never, and the title run only where H3 had given a title back 

2605 before a run of particles that are suffix vocabulary, which the 

2606 read takes as written: 'Dr. mc Jr mc mc' reads family 'mc', suffix 

2607 'Jr mc mc', where the run read after the merge would leave 'mc Jr 

2608 mc mc' in the family.""" 

2609 if n == len(pieces): 

2610 return None 

2611 units = _chain_units(pieces, ptags, tokens, n, lead, one_case) 

2612 rest, titled, peel = tail_reading(peel_walk(n, ptags), pieces, ptags, 

2613 tokens, one_case, units) 

2614 tail: set[int] = set() 

2615 for k in rest[peel.names:]: 

2616 tail.update(pieces[k]) 

2617 titles: set[int] = set() 

2618 for k in titled: 

2619 titles.update(pieces[k]) 

2620 tail |= titles 

2621 run_titles: set[int] = set() 

2622 for k in peel.run_titles: 

2623 run_titles.update(pieces[k]) 

2624 start = len(pieces) 

2625 for k, piece in enumerate(pieces): 

2626 if piece[0] in tail: 

2627 start = k 

2628 break 

2629 for k in range(start, len(pieces)): 

2630 if pieces[k][0] not in tail and "suffix" not in ptags[k]: 

2631 return None 

2632 return TailRead(frozenset(tail), frozenset(titles), 

2633 frozenset(run_titles), peel), start 

2634 

2635 

2636def trailing_run_start(start: int, pieces: Sequence[Sequence[int]], 

2637 ptags: Sequence[Set[str]], 

2638 tokens: Sequence[WorkToken], 

2639 one_case: bool | None) -> int: 

2640 """Where the run `tail_reading` takes over `pieces[start:]` begins, 

2641 its trailing titles included: the first index of a piece the peel 

2642 or the H5 chain took, `len(pieces)` where they take none. The 

2643 bound for a reading that takes the trailing titles as well as the 

2644 suffixes, as assign's walk does in the given part after a family 

2645 comma (#623), where `trailing_start` sees only the suffixes and 

2646 `trailing_start_past_titles` leaves the titles inside the bound. 

2647 The chain takes a bare salutation too, as that walk does (rules/H8).""" 

2648 # rules/S4: "the given part's trailing slot after a family comma is 

2649 # read without it (S5)" -- the numeral half of the count, which 

2650 # assign's walk there never asks either, so the chain this bounds 

2651 # stops where that walk will read the suffix (#718's review); the 

2652 # acronym half is still counted here, as before #718 

2653 rest, titled, peel = tail_reading(peel_walk(start, ptags), pieces, 

2654 ptags, tokens, one_case, 

2655 count_numeral=False, salutations=True, 

2656 initials_cue=False) 

2657 first = len(pieces) 

2658 for k in rest[peel.names:]: 

2659 first = min(first, k) 

2660 for k in titled: 

2661 first = min(first, k) 

2662 return first 

2663 

2664 

2665# rules/H5: "the title is TRANSPARENT to the suffix reading: where 

2666# two or more name words stand, what stands once the chain is taken 

2667# reads exactly as it would read written without the title, plus the 

2668# title" 

2669def trailing_start_past_titles(start: int, 

2670 pieces: Sequence[Sequence[int]], 

2671 ptags: Sequence[Set[str]], 

2672 tokens: Sequence[WorkToken], 

2673 *, one_case: bool | None) -> int: 

2674 """`trailing_start` read through H5's chain: where assign's 

2675 trailing suffix run begins once a trailing TITLE has stopped 

2676 hiding it. 

2677 

2678 `trailing_start` reads the pieces as WRITTEN, so a title standing 

2679 behind the suffix run makes the peel take nothing and the answer 

2680 is `len(pieces)` -- the reading assign itself has not had since 

2681 H5, because assign runs the peel and the chain to their fixed 

2682 point instead (`tail_reading`). A caller using that answer as the 

2683 right bound of the NAME is told a credential is a name word: 

2684 'John Quincy Adams i MA Prof.' read family 'Adams i MA' where 

2685 'John Quincy Adams i MA' reads family 'Adams' and suffix 'i MA' 

2686 (#397 second review). Every caller that bounds the name wants 

2687 this one; `trailing_start` stays for the callers that count a 

2688 trailing run of the pieces as they stand. 

2689 

2690 The returned index bounds the name from the right, and the 

2691 trailing titles the chain spliced out are not under it: they end 

2692 the segment, so they stand at or past the first suffix piece 

2693 whenever there is one. Where the peel takes nothing even past the 

2694 chain this returns `len(pieces)` as `trailing_start` does, and a 

2695 trailing title is then inside the bound and refused by the title 

2696 test the callers already run beside it. 

2697 """ 

2698 rest, _titled, peeled = tail_reading(peel_walk(start, ptags), 

2699 pieces, ptags, tokens, one_case) 

2700 return rest[peeled.names] if peeled.names < len(rest) else len(pieces)