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

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

651 statements  

1"""Stage: post_rules. 

2 

3Consumes: tokens (roles assigned), plus pieces and structure -- the 

4particle fold reads the opening piece of segment 0, or of segment 1 

5under a family comma (#359). structure was always read here, for the 

6rotation gate. Also comma_offsets and dropped, which R1's entry pass 

7below reads to find the separators the writer typed (#436/#437), and 

8extracted, one_case and original, which S1's set-apart pass reads, 

9settling S13's members with its own (#810, #792), original also read 

10by R1's entry pass for a comma a set-apart clause kept; and order, 

11the order assign read the name under, which H1, P1's fold, P6's 

12attachment, P10, O1, O2, O6, O7 and W5's surname pair key on rather than 

13Policy.name_order (#395). 

14Produces: tokens with roles adjusted by the post rules (among them the 

15TITLE and SUFFIX roles of a set-apart clause's words, rules/S1, each 

16word's comma trimmed off its text and span, and the 

17SUFFIX role of a delimited member its writing settles after the name, 

18rules/S13, with the SUFFIX_OR_NICKNAME report on any other member left 

19a nickname), the stable 

20"joined" tag on a post-nominal continuing the entry before it, the 

21folded-middle tag on the words O3 folds and P6's no-comma attachment 

22joins to the family, with the attached tag on the latter (rules/R9 

23tells the two apart by it), the second-surname tag on each word of the 

24family's second unit where O6 reads two (rules/R10), the first-surname 

25tag on each word of the first unit, written by O6 where it reads two 

26and by O3 on the family it folds into otherwise (rules/R11), both unit 

27tags where it reads a Han surname pair (rules/W5, #845), with a 

28SEGMENTATION report where that pair was written undivided, and the ambiguity P6's attachment reports at the end of a name read 

29family-first (#467) -- after a family comma, that attachment is 

30assign's since #613, and behind an empty part before the comma too 

31since #892. 

32Reads: Policy.patronymic_rules, Policy.initials_as_family, 

33Policy.capitals_as_family (O9, which reads Lexicon.conjunctions for 

34a run and, for its peel, Lexicon.suffix_acronyms and suffix_words), 

35Policy.two_family_names, 

36Policy.two_given_names, Policy.name_order (O6 and O7 stand down where 

37the script's order differs from the declared one, and O6 reads 

38Policy.script_orders for the part before a family comma, through 

39`_assign._effective_order`), 

40Policy.middle_as_family, 

41Policy.extra_suffix_delimiters (R1's entry pass, for the delimiter 

42cores group drops); Lexicon.given_name_titles, Lexicon.given_names 

43(O6's veto), Lexicon.bound_long_names_only (P12's split of a pair 

44in a name of fewer than four name words, #1464), 

45Lexicon.saint_particles (P10's saint clause; P10 runs under every 

46policy and reads Policy.patronymic_rules for its Turkic guard), and 

47Lexicon.suffix_acronyms_ambiguous (a dotted member in a clause, which 

48carries no tag there, S13, through `_vocab.dotted_member`), and for S1's set-apart clause 

49Lexicon.suffix_words directly and, through `_vocab.set_apart_kind` and 

50`set_apart`, Lexicon.suffix_words_ambiguous, suffix_acronyms, titles, 

51title_modifiers, title_styles, after_given_titles and honorific_tails 

52(through `_vocab.period_joined_credential`), with generation_words 

53and honorific_words, the suffix words that do not settle a member 

54(`_vocab.settles_a_member`). 

55 

56Implements rules S1, S13, H1, M4, P1, P6 (its no-comma site), P10, P11, 

57P12's two splits, O1, O2, O6, O7, O8, O9, O3, R1, R10, R11 and W5's 

58surname pair of docs/design/rules/; each is cited at its code below, and 

59H1/P1/O1/O2's history lives in docs/design/decisions/. 

60`suffix_entries` is the R1 entry pass as a state-in/state-out 

61function, for Parser.revise to run over a forced-role sub-parse 

62(#511); `post_rules` runs the same worker last. 

63""" 

64from __future__ import annotations 

65 

66import bisect 

67import dataclasses 

68import re 

69from collections.abc import Sequence 

70 

71from nameparser._lexicon import Lexicon, _normalize, _run_addresses_by_given 

72from nameparser._pipeline._assign import ( 

73 _effective_order, _name_alt, _name_pieces, _name_positions, 

74) 

75from nameparser._pipeline._pieces import ( 

76 is_lone_never_given_particle, is_lowercase_ambiguous_particle, 

77 settled_by_case, 

78) 

79from nameparser._pipeline._state import ( 

80 AMBIGUOUS_ACRONYM_TAG, ATTACHED_TAG, CAPITALS_FAMILY_TAG, COMMA_CHARS, 

81 COMMA_STRIP, NAME_ROLES, 

82 PATRONYMIC_TAG, 

83 BOUND_PHRASE_TAG, BOUND_SECOND_TAG, PARTICLE_GIVEN_TAG, PAST_REACH_TAG, SHARED_NAME_TAG, 

84 FIRST_SURNAME_TAG, SECOND_SURNAME_TAG, SURNAME_PAIR_TAG, 

85 ParseState, PendingAmbiguity, PendingReading, Structure, 

86 WorkToken, _NEVER_FLIPPED, comma_bucket, copy_with, reported_suffix_fork, 

87) 

88from nameparser._pipeline._vocab import ( 

89 _HYPHENS, _LETTER, SetApartKind, delimiter_cores, dotted_member, 

90 ROMAN, east_slavic_rotates, has_patronymic_ending, is_capitals_word, 

91 is_initial, is_listed_given_name, 

92 is_patronymic_marker, joined_member, member_word, period_member, 

93 reads_as_initials, 

94 set_apart, set_apart_kind, settles_a_member, suffix_reading, 

95 unit_ends, 

96) 

97from nameparser._policy import PatronymicRule 

98from nameparser._types import ( 

99 FOLDED_TAG, UNJOINED_CONJUNCTION_TAG, UNJOINED_TAG, AmbiguityKind, Role, 

100 Span, 

101) 

102 

103 

104#: The roles that are transparent to a run of post-nominals (R1's 

105#: entry pass below). These three roles render into fields other than 

106#: the name and the suffix, so a run of 

107#: post-nominals is not parted by them -- 'Smith, MD Dr. PhD', 

108#: 'Smith, MD "Doc" PhD' and 'Smith, MD (nee Jones) PhD' are each one 

109#: entry. GIVEN/MIDDLE/FAMILY are name words and part it. 

110_RENDERS_ELSEWHERE = frozenset({Role.TITLE, Role.NICKNAME, Role.MAIDEN}) 

111 

112 

113def _rotations_apply(state: ParseState) -> bool: 

114 # Both patronymic rotations RESTORE the given-first reading a 

115 # family-first listing hides, so rules/O1's scope clause holds 

116 # them to the default order: a caller who declared family-first has 

117 # already said what the rotation would infer, and position decides 

118 # (decisions/O1, the 2026-09-07 entry on #384). `state.order`, 

119 # not policy.name_order, for the reason the P1 fold gives -- a 

120 # script_orders entry can override the policy, and the roles the 

121 # rotations read are the ones assign actually made. None means 

122 # assign positioned nothing: a family comma (which the NO_COMMA 

123 # test already excludes) or an early return with no name piece to 

124 # position, so there is no declaration to defer to and the 

125 # rotation's own shape test decides. 

126 return state.structure is Structure.NO_COMMA and ( 

127 state.order is None or state.order[0] is Role.GIVEN) 

128 

129 

130def _mark_suffix_entries(tokens: list[WorkToken], state: ParseState) -> None: 

131 # In place over the caller's token list, as every other post rule 

132 # writes; suffix_entries() below is the state wrapper, and 

133 # decisions/R1 (#511) records why the pass has two spellings. 

134 # Reads dropped, comma_offsets and the policy off `state`, which 

135 # post_rules does not change, so the un-rebuilt state is current. 

136 # 

137 # rules/R1: "a run of post-nominals written with spaces renders 

138 # with spaces, and one written with commas keeps them" 

139 # 

140 # Two consecutive SUFFIX tokens are one entry iff they share a 

141 # comma bucket and nothing between them parts the run: a name word 

142 # or a dropped delimiter core parts it; a token whose role is in 

143 # _RENDERS_ELSEWHERE, or a dropped token that is not a core (the 

144 # marker of a bracketed maiden clause, 'Smith, MD (nee Jones) 

145 # PhD'), does not. comma_bucket and delimiter_cores 

146 # are segment's and group's own answers, called rather than copied 

147 # (mechanisms.md#ONE-PREDICATE-PER-QUESTION). decisions/R1 

148 # (#436/#437). 

149 # 

150 # After assign, because it keys on Role.SUFFIX; last in post_rules, 

151 # after S13's pass, the one rule here that writes SUFFIX (#810), and 

152 # by convention otherwise, since no other writes SUFFIX or a 

153 # _RENDERS_ELSEWHERE role. Recorded as a tag because a span-less 

154 # token (unpickled, or built by replace()) leaves the render 

155 # nothing to scan (mechanisms.md#MARK-DONT-STRIP). Every WorkToken 

156 # has a span, so `span.start` is read unguarded, and the 

157 # `i not in dropped` filter is belt-and-braces: a dropped token 

158 # never holds SUFFIX, and the filter keeps `suffixes` and the 

159 # `parted` scan agreeing on what a dropped index is. 

160 dropped = set(state.dropped) 

161 # a plain loop and an early return, where a comprehension and the 

162 # cores ahead of the count cost frames on every parse, and most 

163 # names hold fewer than two suffixes (decisions/parse-cost, #1170) 

164 suffixes: list[int] = [] 

165 for i, tok in enumerate(tokens): 

166 if tok.role is Role.SUFFIX and i not in dropped: 

167 suffixes.append(i) 

168 if len(suffixes) < 2: 

169 return 

170 cores = delimiter_cores(state.policy.extra_suffix_delimiters) 

171 for previous, current in zip(suffixes, suffixes[1:]): 

172 same_part = (comma_bucket(tokens[previous].span.start, 

173 state.comma_offsets) 

174 == comma_bucket(tokens[current].span.start, 

175 state.comma_offsets)) 

176 parted = any( 

177 tokens[between].text in cores if between in dropped 

178 else tokens[between].role not in _RENDERS_ELSEWHERE 

179 for between in range(previous + 1, current)) or ( 

180 # rules/S1: "parts its words as a comma between them would" 

181 # -- a comma a set-apart clause kept on a word, which no 

182 # comma bucket holds and S1's pass trimmed off the word; 

183 # decisions/S1 (#792) 

184 state.original[tokens[previous].span.end: 

185 tokens[previous].span.end + 1] in COMMA_CHARS 

186 or state.original[tokens[previous].span.end: 

187 tokens[current].span.start].replace(" ", "") 

188 in COMMA_CHARS) 

189 if same_part and not parted: 

190 tokens[current] = copy_with( 

191 tokens[current], tags=tokens[current].tags | {"joined"}) 

192 

193 

194def suffix_entries(state: ParseState) -> ParseState: 

195 """rules/R1's entry pass over a whole state, wrapping 

196 _mark_suffix_entries: tag a SUFFIX token "joined" when it 

197 continues the entry of the SUFFIX token before it. post_rules runs 

198 the worker last, over the roles assign settled; this wrapper exists 

199 for Parser.revise (#511), which runs it over a SUB-PARSE of a field 

200 value whose every non-dropped token it has forced to the named 

201 role, so a suffix value derives its entries from its own commas by 

202 the rule a whole name uses. The pass ADDS the tag and never removes 

203 one; a caller forcing roles keeps what the sub-parse marked, a 

204 within-piece mark being role-blind (decisions/R1, the #436 

205 DECLINED list) and every between-piece mark on a suffix value 

206 being one this pass sets again. Reads comma_offsets, dropped and 

207 Policy.extra_suffix_delimiters; writes the "joined" tag and 

208 nothing else.""" 

209 tokens = list(state.tokens) 

210 _mark_suffix_entries(tokens, state) 

211 return copy_with(state, tokens=tuple(tokens)) 

212 

213 

214#: Each role `_positions` lists, by its place in the answer. 

215_POSITION_SLOT: dict[Role | None, int] = { 

216 Role.TITLE: 0, Role.GIVEN: 1, Role.MIDDLE: 2, Role.FAMILY: 3} 

217 

218 

219def _positions(tokens: list[WorkToken], 

220 ) -> tuple[list[int], list[int], list[int], list[int]]: 

221 """The positions of the TITLE, GIVEN, MIDDLE and FAMILY tokens, in 

222 that order, each list ascending: the four roles post_rules' rules 

223 read as position lists, in one walk however many of them the caller 

224 wants.""" 

225 # one plain loop, where a comprehension per role cost a frame of its 

226 # own on 3.11 beside the call's, and post_rules asks for the lists on 

227 # every parse (the parse-cost band, decisions/parse-cost, #1089) 

228 lists: tuple[list[int], list[int], list[int], list[int]] = ( 

229 [], [], [], []) 

230 for i, token in enumerate(tokens): 

231 slot = _POSITION_SLOT.get(token.role) 

232 if slot is not None: 

233 lists[slot].append(i) 

234 return lists 

235 

236 

237def _leading_name_piece(state: ParseState, 

238 tokens: list[WorkToken]) -> tuple[int, ...]: 

239 """The piece that OPENS the name, whatever role name_order gave it: 

240 the first piece holding a GIVEN, MIDDLE or FAMILY token, in the 

241 segment the positional read governs. Every piece holding none of 

242 those is walked past -- title and suffix pieces, but NICKNAME and 

243 MAIDEN as well, and anything assign left unroled -- and any number 

244 of them, not only a single leading title. The segment is 0, except 

245 under a family comma that fixed the surname, where the name 

246 continues in segment 1 -- assign records no order there. A family 

247 comma followed by no name word fixed nothing, and assign reads 

248 segment 0 positionally and records the order (#296's bundle), so 

249 the name is segment 0 again. Empty on either of two exits: that 

250 segment does not exist, or none of its pieces holds a name 

251 token.""" 

252 seg = (1 if state.structure is Structure.FAMILY_COMMA 

253 and state.order is None else 0) 

254 if seg >= len(state.pieces): 

255 return () 

256 # nested loops, where an any() generator cost frames on every parse 

257 # (decisions/parse-cost, #1170) 

258 for piece in state.pieces[seg]: 

259 for i in piece: 

260 if tokens[i].role in NAME_ROLES: 

261 return piece 

262 return () 

263 

264 

265def _retag(tokens: list[WorkToken], i: int, role: Role) -> None: 

266 tokens[i] = copy_with(tokens[i], role=role) 

267 

268 

269def _split_a_lone_backward_pair(state: ParseState, tokens: list[WorkToken], 

270 ambiguities: list[PendingAmbiguity]) -> bool: 

271 """A pair P12 joined from its second word that holds every name word 

272 the parse read is split back, in place: its first word takes the 

273 order's first position and its second the order's other name role, 

274 as P5's reserve leaves a bound word's pair of two name words, and 

275 the one-word report assign made of it is withdrawn. True where it 

276 split one.""" 

277 # the caller has found the two name words adjacent, the first 

278 # carrying the pair's tag 

279 first = next(i for i, t in enumerate(tokens) 

280 if t.role in (Role.GIVEN, Role.MIDDLE, Role.FAMILY)) 

281 second = first + 1 

282 # rules/P5's two exceptions to its reserve, read alike: after a 

283 # family comma the family is fixed and the pair is the given name, 

284 # and a given-name title asserts that a given name follows 

285 if (state.structure is Structure.FAMILY_COMMA and state.comma_offsets 

286 and tokens[first].span.start > state.comma_offsets[0]): 

287 return False 

288 titles = [i for i, t in enumerate(tokens[:first]) if t.role is Role.TITLE] 

289 if titles and _run_addresses_by_given( 

290 (tokens[i].text for i in _addressing_run(titles, first)), 

291 state.lexicon._sets.given_name_titles): 

292 return False 

293 order = state.order or state.policy.name_order 

294 other = order[2] if order[1] is Role.MIDDLE else order[1] 

295 tokens[first] = copy_with( 

296 tokens[first], role=order[0], 

297 tags=tokens[first].tags - {BOUND_PHRASE_TAG, BOUND_SECOND_TAG}) 

298 _retag(tokens, second, other) 

299 ambiguities[:] = [a for a in ambiguities 

300 if not (a.kind is AmbiguityKind.GIVEN_OR_FAMILY 

301 and {first, second} & set(a.indices))] 

302 # a report on a later word named the field it would take beside ONE 

303 # name unit; beside two, under a family-first order with the given 

304 # name second, that word would be the third, the middle (assemble 

305 # folds it into the family under middle_as_family); a word after a 

306 # comma names the given name for the comma's other reading, which 

307 # no count of units moves 

308 if order[0] is Role.FAMILY and order[1] is Role.GIVEN: 

309 comma = state.comma_offsets[0] if state.comma_offsets else None 

310 for k, a in enumerate(ambiguities): 

311 alt = a.alternative 

312 if (alt is not None and alt.role is Role.GIVEN and a.indices 

313 and min(a.indices) > second 

314 and (comma is None 

315 or tokens[max(a.indices)].span.start < comma)): 

316 ambiguities[k] = dataclasses.replace( 

317 a, alternative=dataclasses.replace(alt, role=Role.MIDDLE)) 

318 return True 

319 

320#: A letter, a decomposed accent's base included: a word holding none, 

321#: a lone mark, is no name word to the count rules/P12 makes. 

322_HAS_LETTER = re.compile(_LETTER) 

323 

324 

325def _cut_pair(state: ParseState, head: int) -> ParseState: 

326 """`state` with the piece holding the pair at `head` cut in two 

327 before its second word, its piece tags given to both halves, for 

328 the readers of pieces after the pair is split (rules/O9's layout, 

329 P1's opening piece). Group builds the pieces and their tags in step, 

330 segment by segment.""" 

331 segs: list[tuple[tuple[int, ...], ...]] = [] 

332 tag_segs: list[tuple[frozenset[str], ...]] = [] 

333 for seg, ptags in zip(state.pieces, state.piece_tags): 

334 out: list[tuple[int, ...]] = [] 

335 out_tags: list[frozenset[str]] = [] 

336 for piece, tag in zip(seg, ptags): 

337 if head in piece and head + 1 in piece: 

338 cut = piece.index(head + 1) 

339 out += [piece[:cut], piece[cut:]] 

340 out_tags += [tag, tag] 

341 else: 

342 out.append(piece) 

343 out_tags.append(tag) 

344 segs.append(tuple(out)) 

345 tag_segs.append(tuple(out_tags)) 

346 return copy_with(state, pieces=tuple(segs), piece_tags=tuple(tag_segs)) 

347 

348 

349def _split_a_short_open_pair(state: ParseState, tokens: list[WorkToken], 

350 head: int) -> tuple[bool, ParseState]: 

351 """A pair P12 joined behind a bound word written `long_names_only`, 

352 in a name of fewer than four name words, is split back, in place, to 

353 the reading the name has without the join, and the state handed 

354 back holds the pieces that reading has, the pair two of them. A 

355 pair opening the name's pieces is P5's, which group leaves without 

356 the pair's tag, so it is never split here. Behind a family comma no 

357 role moves: the part before it is the family whole, and in the part 

358 after it the pair stands behind the given name, among the middle 

359 names. Elsewhere the pieces are laid out by the order again. The 

360 pair's tag goes in every case; True where a role moved too.""" 

361 tokens[head] = copy_with(tokens[head], 

362 tags=tokens[head].tags - {BOUND_PHRASE_TAG}) 

363 state = _cut_pair(state, head) 

364 if state.structure is Structure.FAMILY_COMMA: 

365 return False, state 

366 units = _name_pieces(state, tokens, 0) 

367 order = state.order or state.policy.name_order 

368 moved = False 

369 for unit, role in zip(units, _name_positions(order, len(units))): 

370 for i in unit: 

371 if tokens[i].role in NAME_ROLES and tokens[i].role is not role: 

372 _retag(tokens, i, role) 

373 moved = True 

374 return moved, state 

375 

376 

377# rules/P2: "a particle joins the words after it into one name 

378# part, the join running until the next particle starts a group of 

379# its own, a trailing suffix begins" 

380# rules/P3: "the joined part is ONE name word wherever another 

381# rule counts them" 

382# rules/P5: "a recognized bound given-name word joins the word 

383# after it into one given name" 

384def _units(tokens: list[WorkToken], idx: list[int]) -> list[list[int]]: 

385 """`idx` split into the units other rules COUNT: one name word 

386 each, except where another rule has already made several words one 

387 name. Three do -- a particle and the words it chains, a 

388 conjunction-joined run, and a bound given-name word with the word 

389 it completes -- so `van der Berg` and `abdul Rahman` are each one 

390 unit and the fold cannot leave half of either behind. 

391 

392 Read off the TAGS rather than the pieces, for two different 

393 reasons. A conjunction join grouping DID build and the prefix 

394 chain then swallowed: "de la Vega y Santos Juan" reaches this as 

395 [de][la Vega y Santos Juan], the ambiguous particle having chained 

396 forward over the join, so the join's own boundary is gone. (The 

397 leading particle keeps its piece -- it has to, or the fold's 

398 lone-piece site test would not fire at all.) The bound-given join grouping 

399 never built at all: P5 joins only where the bound word is the 

400 first non-title piece, save a listed two-word given name P12 

401 joins past the first name word (#694) and a pair P12 joins from 

402 its listed second word (#1072), and at a fold site the first piece 

403 is the particle -- "ibn Awf abdul Rahman" reaches here as four 

404 separate pieces. The tag is the only witness in both cases. 

405 

406 The particle chain is what keeps this partition agreeing with the 

407 one `assign` reads off pieces: strip the folded run and `assign` 

408 gives the same tail one role, so the fold must not hand its words 

409 out separately.""" 

410 units: list[list[int]] = [] 

411 i = 0 

412 for end in unit_ends([tokens[k].tags for k in idx]): 

413 units.append(list(idx[i:end])) 

414 i = end 

415 return units 

416 

417 

418def _fold_reach(tokens: list[WorkToken], name_idx: list[int]) -> int: 

419 """How many of `name_idx` the fold takes: the particle run, plus 

420 the one name word it attaches to -- one UNIT, so a conjunction 

421 join goes whole ("de la Vega y Santos Juan" keeps Vega y Santos 

422 together). All of them when the name is nothing but particles.""" 

423 i = 0 

424 while i < len(name_idx) and "particle" in tokens[name_idx[i]].tags: 

425 i += 1 

426 if i == len(name_idx): 

427 return i 

428 return i + len(_units(tokens, name_idx[i:])[0]) 

429 

430 

431def _family_word_count(tokens: list[WorkToken], family: list[int], 

432 hyphen_joins: bool = False) -> int: 

433 """The family's name words as rules/O6 counts them: a particle run 

434 counts with the word it attaches to, a connective counts as 

435 nothing and a hyphen joins words without making them one, so "de 

436 la Vega" is one word and "Ortega y Gasset" and "García-López" two. 

437 A family of nothing but particles counts each of them, R2 reading 

438 them as ordinary name words. `hyphen_joins` counts a hyphenated word 

439 as one, as the word O6 takes is counted (#959). A bound word counts 

440 with the word that completes it, the pair P12 joins being one name 

441 ('عبد الله', #694).""" 

442 # rules/P12: "the two words are one name unit, past the first name word" 

443 # -- so the pair's first word counts with the word after it 

444 words = sum(1 if hyphen_joins 

445 else len([part for part in _HYPHENS.split(tokens[i].text) 

446 if part]) 

447 for i in family 

448 if "particle" not in tokens[i].tags 

449 and "conjunction" not in tokens[i].tags 

450 and BOUND_PHRASE_TAG not in tokens[i].tags) 

451 return words or len(family) 

452 

453 

454def _hyphenated_given(text: str, lexicon: Lexicon) -> bool: 

455 """A hyphenated word that writes given names, which the taken word's 

456 count (a hyphenated word counting as one) would otherwise let through 

457 (#959): every part of it a listed given name or an initial 

458 ("María-José" under the Spanish list, "M.-J.", "M.-José").""" 

459 parts = [part for part in _HYPHENS.split(text) if part] 

460 return len(parts) > 1 and all(is_initial(part) or is_listed_given_name(part, lexicon) 

461 for part in parts) 

462 

463 

464#: The kinds of report that ask which field a word takes; where the 

465#: capitals settle the field (rules/O9) the fork is not open. 

466_SETTLED_BY_CAPITALS = frozenset({ 

467 AmbiguityKind.SUFFIX_OR_NAME, AmbiguityKind.TITLE_OR_NAME, 

468 AmbiguityKind.PARTICLE_OR_GIVEN, AmbiguityKind.GIVEN_OR_FAMILY, 

469 AmbiguityKind.ORDER}) 

470#: The kinds of them that ask where the family is, which the capitals 

471#: answer for every word of the name: the order a name is read in 

472#: among them, the capitals having named its family wherever it stands. 

473_SETTLED_EVERYWHERE = frozenset({ 

474 AmbiguityKind.PARTICLE_OR_GIVEN, AmbiguityKind.GIVEN_OR_FAMILY, 

475 AmbiguityKind.ORDER}) 

476 

477#: The roles of the words rules/O9 reads: the name words, and the 

478#: titles and suffixes a word in capitals may have been read as. 

479_CAPITALS_READS = frozenset({ 

480 Role.TITLE, Role.GIVEN, Role.MIDDLE, Role.FAMILY, Role.SUFFIX}) 

481 

482 

483def _listed_suffix(text: str, lexicon: Lexicon) -> bool: 

484 """A credential or generation the vocabulary lists, or a roman 

485 numeral, which rules/O9 peels off the end of a run of capitals. 

486 Asked only of a capitals word, which holds no full stop.""" 

487 # the ambiguous halves are subsets of these two 

488 n = _normalize(text) 

489 sets = lexicon._sets 

490 return (n in sets.suffix_acronyms or n in sets.suffix_words 

491 or _is_numeral(text)) 

492 

493 

494def _is_numeral(text: str) -> bool: 

495 # rules/O9: "a lone roman numeral of two or more letters stays the 

496 # suffix" -- asked only of a capitals word, which has two or more 

497 # letters and no full stop 

498 return ROMAN.match(text) is not None 

499 

500 

501def _is_conjunction(token: WorkToken, conjunctions: frozenset[str]) -> bool: 

502 """A conjunction as rules/O9 reads one. A listed conjunction of one 

503 letter in a name in mixed case is tagged an initial (rules/P8), but 

504 beside a capitals word it is the connective a double surname writes 

505 (`LOPEZ Y GARCIA`), written bare: a letter with its full stop is an 

506 initial (`Y.`).""" 

507 return ("conjunction" in token.tags 

508 or token.text.isalpha() 

509 and _normalize(token.text) in conjunctions) 

510 

511 

512def _capitals_runs(tokens: list[WorkToken], seq: list[int], 

513 caps: dict[int, bool], 

514 conjunctions: frozenset[str]) -> list[list[int]]: 

515 """The runs of capitals among the words SEQ, in text order, each 

516 joined across particles and conjunctions, trimmed of a conjunction 

517 at either end, and extended back over the lowercase particles 

518 written right before it (rules/O9).""" 

519 def conjunction(j: int) -> bool: 

520 return _is_conjunction(tokens[j], conjunctions) 

521 

522 def joiner(j: int) -> bool: 

523 return not caps[j] and ("particle" in tokens[j].tags 

524 or conjunction(j)) 

525 

526 runs: list[list[int]] = [] 

527 n = 0 

528 while n < len(seq): 

529 if not caps[seq[n]]: 

530 n += 1 

531 continue 

532 begin = n 

533 run = [seq[n]] 

534 n += 1 

535 while n < len(seq): 

536 if caps[seq[n]]: 

537 run.append(seq[n]) 

538 n += 1 

539 continue 

540 m = n 

541 while m < len(seq) and joiner(seq[m]): 

542 m += 1 

543 if m == n or m == len(seq) or not caps[seq[m]]: 

544 break 

545 run.extend(seq[n:m]) 

546 n = m 

547 # rules/O9: "a run neither opens nor ends in a conjunction" -- a 

548 # conjunction written in capitals joins two words or none 

549 while run and conjunction(run[-1]): 

550 run.pop() 

551 # a run left empty is dropped below with the runs of particles 

552 head = 0 

553 while head < len(run) and conjunction(run[head]): 

554 head += 1 

555 run = run[head:] 

556 begin += head 

557 # rules/O9: "a lowercase particle written right before the run 

558 # joins it" 

559 start = begin 

560 # joining across particles above has taken any particle standing 

561 # between two runs, so the walk never reaches the run before 

562 while (start > 0 

563 and "particle" in tokens[seq[start - 1]].tags 

564 and tokens[seq[start - 1]].text.islower()): 

565 start -= 1 

566 runs.append(seq[start:begin] + run) 

567 return runs 

568 

569 

570def _family_in_capitals(state: ParseState, tokens: list[WorkToken], 

571 ambiguities: list[PendingAmbiguity]) -> bool: 

572 """rules/O9, under Policy.capitals_as_family: the run of capitals 

573 is the family name and the other words keep their written order. 

574 True where it laid the name out.""" 

575 # rules/O9: "the switch reads only the part before the first comma" 

576 # -- a family comma has decided the family already 

577 if state.structure is Structure.FAMILY_COMMA: 

578 return False 

579 offsets = state.comma_offsets 

580 seq = [i for i, t in enumerate(tokens) 

581 if t.role in _CAPITALS_READS 

582 and (not offsets or comma_bucket(t.span.start, offsets) == 0)] 

583 caps = {i: is_capitals_word(tokens[i].text) for i in seq} 

584 conjunctions = state.lexicon._sets.conjunctions 

585 

586 def name_word(j: int) -> bool: 

587 # a capitals word that may be the family: no particle, numeral 

588 # or conjunction, which no run keeps by itself 

589 return (caps[j] and "particle" not in tokens[j].tags 

590 and not _is_numeral(tokens[j].text) 

591 and not _is_conjunction(tokens[j], conjunctions)) 

592 

593 rules = state.policy.patronymic_rules 

594 if rules: 

595 markers = {i for i in seq if caps[i] and ( 

596 PatronymicRule.TURKIC in rules 

597 and is_patronymic_marker(tokens[i].text) 

598 or PatronymicRule.EAST_SLAVIC in rules 

599 and has_patronymic_ending(tokens[i].text))} 

600 # rules/O9: "a word the patronymic rule in force reads as its 

601 # marker is no capitals word where another capitals word is 

602 # left to be the family" -- the switch never moves a marker into 

603 # the family (`ALIYEV Ilham Heydar OGLU`), and a surname spelled 

604 # like one stays the family where nothing else can be 

605 # (`ABRAMOVICH Roman`) 

606 if markers and any(name_word(j) for j in seq if j not in markers): 

607 for i in markers: 

608 caps[i] = False 

609 

610 def lowercase_joiner(j: int) -> bool: 

611 return tokens[j].text.islower() and ( 

612 "particle" in tokens[j].tags or "conjunction" in tokens[j].tags) 

613 

614 # rules/O9: "a listed credential or numeral ending the name peels 

615 # off before a run is chosen, wherever a capitals word that is no 

616 # particle is left" -- walked from the end over the suffix slot, 

617 # past a suffix written otherwise (`Marie DUPONT Jr. MBA`), so a 

618 # credential cut off from the family by a name word comes off too 

619 # (`DUPONT Marie MBA`); a joining word ends the slot (`Joan MAS i 

620 # MBA`), and so does a word in capitals the vocabulary does not list 

621 names_left = sum(1 for j in seq if name_word(j)) 

622 peeled: list[int] = [] 

623 peeled_set: set[int] = set() 

624 for j in reversed(seq): 

625 if caps[j]: 

626 if (not _listed_suffix(tokens[j].text, state.lexicon) 

627 or names_left - name_word(j) == 0): 

628 break 

629 names_left -= name_word(j) 

630 peeled.append(j) 

631 peeled_set.add(j) 

632 elif tokens[j].role is not Role.SUFFIX or lowercase_joiner(j): 

633 break 

634 rest = [j for j in seq if j not in peeled_set] if peeled else seq 

635 runs = [run for run in _capitals_runs(tokens, rest, caps, 

636 conjunctions) 

637 # rules/O9: "a run of particles alone is no run, nor is a 

638 # lone roman numeral" 

639 if any(name_word(j) for j in run)] 

640 if not runs: 

641 return False 

642 # rules/O9: "where a name word divides two runs, the last is the 

643 # family" 

644 run = runs[-1] 

645 # a joining word the peel left behind the family joins nothing; it 

646 # goes back among the other words (`Marie DUPONT y MBA`) 

647 returned = ({j for j in rest if j > run[-1] and lowercase_joiner(j)} 

648 if peeled else set()) 

649 in_runs = {j for other in runs for j in other} 

650 # rules/O9: "a word other than a title, a particle, a conjunction or 

651 # a suffix holds a lowercase letter" -- the name is in mixed case, 

652 # read over the words no run took: a particle or conjunction counts 

653 # where it is written as a name is, with a capital (`MORRISON Van`), 

654 # and a run joining it leaves it no evidence (`JAN Van DER BERG`) 

655 for i in seq: 

656 t = tokens[i] 

657 if (t.role in NAME_ROLES and not caps[i] and i not in in_runs 

658 and any(ch.islower() for ch in t.text) 

659 and not (t.text.islower() and ("particle" in t.tags 

660 or "conjunction" in t.tags))): 

661 break 

662 else: 

663 return False 

664 family = set(run) 

665 placed = family | set(peeled) 

666 piece_of: dict[int, int] = {} 

667 if state.pieces: 

668 for k, piece in enumerate(state.pieces[0]): 

669 for i in piece: 

670 piece_of[i] = k 

671 others = [i for i in seq if i not in placed 

672 and (tokens[i].role in NAME_ROLES or i in returned)] 

673 # rules/O9: "a lowercase particle opening a unit stays with the word 

674 # after it" -- group leaves a particle opening the name a piece of 

675 # its own for P1's fold (`de Mesnil`), which this layout would part 

676 for n in range(len(others) - 2, -1, -1): 

677 i = others[n] 

678 if "particle" in tokens[i].tags and tokens[i].text.islower(): 

679 piece_of[i] = piece_of.get(others[n + 1], -1 - others[n + 1]) 

680 # P6's attachment marks, which the layout here undoes 

681 clear = frozenset({FOLDED_TAG, ATTACHED_TAG}) 

682 # rules/O9: "the first unit holding a word that may be a given name 

683 # is the given name" -- a conjunction or particle written in 

684 # lowercase is a joining word, and a unit of nothing else is a 

685 # middle name (a particle with a word after it shares its unit, 

686 # above); one written with a capital, as a name is, is read as one 

687 given = next((piece_of.get(i, -1 - i) for i in others 

688 if not (tokens[i].text.islower() 

689 and ("conjunction" in tokens[i].tags 

690 or "particle" in tokens[i].tags))), 

691 piece_of.get(others[0], -1 - others[0]) if others else None) 

692 for i in others: 

693 role = Role.GIVEN if piece_of.get(i, -1 - i) == given else Role.MIDDLE 

694 tokens[i] = copy_with(tokens[i], role=role, 

695 tags=tokens[i].tags - clear) 

696 for i in run: 

697 # every word of the run, a particle in it included, whose 

698 # reading assemble names by its particle kind first 

699 tokens[i] = copy_with(tokens[i], role=Role.FAMILY, 

700 tags=tokens[i].tags - clear 

701 | {CAPITALS_FAMILY_TAG}) 

702 for i in peeled: 

703 tokens[i] = copy_with(tokens[i], role=Role.SUFFIX, 

704 tags=tokens[i].tags - clear) 

705 # rules/O9: "the capitals settle the field" -- a report asking which 

706 # field a word of the run takes names no open fork; nor does one 

707 # asking whether a lone word is the given or the family name, or 

708 # whether a particle opens the family, the capitals having named the 

709 # family, nor an order report, whose other reading lays the family 

710 # out by position; a title or suffix fork on any other word stays, the 

711 # capitals deciding nothing about it under any order 

712 ambiguities[:] = [a for a in ambiguities 

713 if not (a.kind in _SETTLED_BY_CAPITALS 

714 and (a.kind in _SETTLED_EVERYWHERE 

715 or placed.intersection(a.indices)))] 

716 return True 

717 

718 

719def _take_trailing_initials(tokens: list[WorkToken]) -> None: 

720 # rules/O8: "the letters ending the name are its family name" -- 

721 # under the given-first order, with no family comma, the middle 

722 # initials standing right before a family name written as one 

723 # initial join it. In place, as every post rule writes; text order 

724 # already renders them first, so no tag is needed. History: 

725 # decisions/O8 (#1254). 

726 # A family comma and a family-first order need no test of their 

727 # own: each puts the family first in text order, so no middle stands 

728 # right before it for the run below to take (#1347 review). 

729 _, given, middle, family = _positions(tokens) 

730 if (len(family) != 1 or not middle 

731 or "initial" not in tokens[family[0]].tags): 

732 return 

733 run: list[int] = [] 

734 i = family[0] - 1 

735 while (i >= 0 and tokens[i].role is Role.MIDDLE 

736 and "initial" in tokens[i].tags): 

737 run.append(i) 

738 i -= 1 

739 if not run: 

740 return 

741 # rules/O8: "a name written as nothing but letters keeps its first 

742 # letter as the given name" -- a non-initial name word must stand 

743 # before the run 

744 if not any("initial" not in tokens[j].tags 

745 for j in given + middle if j < run[-1]): 

746 return 

747 for j in run: 

748 tokens[j] = copy_with(tokens[j], role=Role.FAMILY) 

749 

750 

751def _take_second_family_name(state: ParseState, tokens: list[WorkToken], 

752 capitals: bool) -> None: 

753 # rules/O6: "the family name takes the name word beside it, so 

754 # the last two name words are the family" -- the first two under 

755 # a family-first order. In place, as every post rule writes. 

756 # History: decisions/O6 (#754). 

757 _, given, middle, family = _positions(tokens) 

758 turkic = PatronymicRule.TURKIC in state.policy.patronymic_rules 

759 # rules/O6: "a family comma decides by itself" -- the family is the 

760 # part before it, divided where it holds two units (decisions/O6, 

761 # #1456) 

762 if state.structure is Structure.FAMILY_COMMA: 

763 if len(family) > 1: 

764 _divide_comma_family(state, tokens, family, turkic) 

765 return 

766 # An order a name's script set (W4) other than the declared one is 

767 # not the caller's declaration, and no script it keys writes two 

768 # family names as separate words. Where the two agree nothing here 

769 # tells them apart, and the rule reads the name (rules/O6 Accepted). 

770 if (not family or state.order is None 

771 or state.order != state.policy.name_order): 

772 return 

773 # rules/O6: "a family that already holds two words keeps what it 

774 # has", and so does one the capitals named (O9): nothing is taken, 

775 # and the family is divided where it holds two units (decisions/O6, 

776 # #1479) 

777 if capitals or _family_word_count(tokens, family) != 1: 

778 _divide_family(tokens, family, turkic) 

779 return 

780 others = sorted(given + middle) 

781 # The rest in the units assign read them as, so a particle chain 

782 # (P2) or a bound given-name pair (P5) moves whole or not at all. 

783 units = _units(tokens, others) 

784 # rules/O6: "a particle chain after the family is cut where P1's 

785 # family-first fold cuts its own run" -- under a family-first order, 

786 # the given name the order declares after the chain left to the 

787 # order (decisions/O6, #1024); under the default order the chain 

788 # ends the name and stays whole 

789 if state.order[0] is not Role.GIVEN and units: 

790 cut = _fold_reach(tokens, units[0]) 

791 if cut < len(units[0]): 

792 units[:1] = [units[0][:cut], *_units(tokens, units[0][cut:])] 

793 if len(units) < 2: 

794 return 

795 take = units[-1] if state.order[0] is Role.GIVEN else units[0] 

796 # What is taken must be ONE name word, so a bound given-name pair 

797 # (P5) stays put; rules/O6: "A hyphenated word counts as one when it 

798 # is the word taken" (decisions/O6, #959), where the family's own 

799 # hyphen counts two; and a word a family name could be: not an 

800 # initial, which writes a given name (one written alone; "J.R." is 

801 # taken), nor a lone dash or other mark with no letter in it. 

802 if _family_word_count(tokens, take, hyphen_joins=True) != 1: 

803 return 

804 if len(take) == 1 and "initial" in tokens[take[0]].tags: 

805 return 

806 if not any(ch.isalpha() for i in take for ch in tokens[i].text): 

807 return 

808 # rules/O6: "a listed given name stays where it is" -- the caller's 

809 # Lexicon.given_names (empty by default; a pack turning O6 on may 

810 # carry one) names a word only a given name is, under either order, 

811 # and a hyphenated word writing given names stays too. Only a unit 

812 # of one token is asked: a word behind a particle ("de Miguel") is a 

813 # unit of two, a surname taken as before (decisions/O6 (#959)). 

814 if len(take) == 1 and ( 

815 is_listed_given_name(tokens[take[0]].text, state.lexicon) 

816 or _hyphenated_given(tokens[take[0]].text, state.lexicon)): 

817 return 

818 # rules/O6: "a name a community gives every member is no family 

819 # name of two" -- Kaur and Singh, on either side of the join, tagged 

820 # at classify from Lexicon.shared_names (decisions/O6, #704) 

821 if any(SHARED_NAME_TAG in tokens[i].tags for i in take + family): 

822 return 

823 # rules/O6: "a given name a particle completes stays where it is" -- 

824 # given-first, the unit taken being the one beside a given name of 

825 # one word, a particle run and a word classify tags from 

826 # Lexicon.particle_given_names, in the shape rules/P10 reads; under a 

827 # family-first order the unit after the family completes no given 

828 # name (decisions/O6, #704) 

829 if (state.order[0] is Role.GIVEN and len(units) == 2 

830 and _one_given_word(tokens, units[0]) 

831 and all(tokens[i].role is Role.GIVEN for i in units[0]) 

832 and _completes_a_given_name(tokens, take, state.lexicon)): 

833 return 

834 if state.order[0] is Role.GIVEN: 

835 # given, middles..., family: the middle unit standing right 

836 # before the family joins it, and text order already renders 

837 # it first, so no role around it moves. A rotation that left 

838 # the name in another shape fails this test. 

839 if take[-1] > family[0] or any( 

840 tokens[i].role is not Role.MIDDLE for i in take): 

841 return 

842 else: 

843 # family first: the unit after the family joins it, and what is 

844 # left is a shorter name of the same order, laid out as the P1 

845 # fold above lays its remainder -- one family already placed. A 

846 # particle P6 attached at the far end is family already and 

847 # keeps its place. 

848 if family[0] > take[0]: 

849 return 

850 _lay_out_after_family(tokens, units, state.order) 

851 # the unit taken joins the family, which is then divided, or moves 

852 # in unmarked where the division declines 

853 if not _divide_family(tokens, sorted(take + family), turkic): 

854 for i in take: 

855 _retag(tokens, i, Role.FAMILY) 

856 

857 

858def _lay_out_after_family(tokens: list[WorkToken], units: list[list[int]], 

859 order: tuple[Role, Role, Role]) -> None: 

860 """The family-first layout O6 and W5's pair share, in place: the 

861 units after `units[0]`, the unit joining the family, are laid out as 

862 a shorter name of the same order, one family already placed. The 

863 caller moves `units[0]` into the family itself: W5 marks it the 

864 second unit, and O6 marks it through `_divide_family`, or moves it 

865 unmarked where that declines.""" 

866 for unit, role in zip(units[1:], _name_positions( 

867 order, len(units))[1:]): 

868 for i in unit: 

869 _retag(tokens, i, role) 

870 

871 

872def _divide_family(tokens: list[WorkToken], family: list[int], 

873 turkic: bool) -> bool: 

874 """rules/O6: "a family is divided by its own words" -- in place, 

875 however it was read: the one place O6 divides a family, after its 

876 take, for a family it takes nothing into (one already holding two 

877 words, a particle chain or the family a P10 phrase leaves, and one 

878 O9's capitals named) and for the part before a family comma 

879 (decisions/O6, #1456, #1479). 

880 

881 The units are P1's fold units over the family's words in written 

882 order (`unit_ends(chain=False)`): a particle run and the ONE name 

883 word it attaches to, a connective join, a bound given-name pair, or 

884 a plain word. Exactly two, each one word as the word O6 takes is 

885 counted, are marked; a family of one unit or of three or more is 

886 left whole, and so is one holding a connective (decisions/R10) or a 

887 name a community gives every member, and so is a family ending in a 

888 standalone patronymic marker under the Turkic rule (`turkic`): the 

889 father's name and the marker, which O2 reads as one family and R9 

890 as the patronymic. The shape tests O6 asks of 

891 the word it takes (an initial, a mark with no letter) are not asked 

892 here: a family already read is divided as written ('Gallegos G.'). 

893 A particle P6 attached to the family it ends is set aside and goes 

894 with the first unit, the family it was attached to. 

895 

896 True where it marked two units, each word then FAMILY. Plain loops 

897 throughout, since every parse of a family under the switch pays for 

898 this; no frame band guards the switch's path (`_CALL_BASELINE` 

899 measures the default), so its cost is counted in decisions/O6.""" 

900 if len(family) < 2: 

901 return False 

902 words: list[int] = [] 

903 tags: list[frozenset[str]] = [] 

904 attached: list[int] = [] 

905 for i in family: 

906 tag = tokens[i].tags 

907 if "conjunction" in tag or SHARED_NAME_TAG in tag: 

908 return False 

909 if ATTACHED_TAG in tag: 

910 attached.append(i) 

911 else: 

912 words.append(i) 

913 tags.append(tag) 

914 ends = unit_ends(tags, chain=False) 

915 if len(ends) != 2 or (turkic and is_patronymic_marker( 

916 tokens[words[-1]].text)): 

917 return False 

918 first, second = words[:ends[0]], words[ends[0]:] 

919 # each unit one name word: a particle run counts with the word it 

920 # attaches to, a bound given-name word with the word it completes 

921 # whether or not it is also a particle ('abdul Rahman', 'Abu Bakr', 

922 # and P12's phrase, whose bound word is one too, read by this test 

923 # rather than the phrase tag group keeps only where it joined the 

924 # pair, so not before a comma), and a unit of particles alone counts 

925 # each of them, as `_family_word_count` counts a family; and a first 

926 # unit of particles alone is no first surname (`bin` where a suffix 

927 # word behind it stops the particle run, 'bin Abd Rahman') 

928 for unit in (first, second): 

929 named = 0 

930 bare = True 

931 completes = False # the word before is a bound given-name word 

932 for i in unit: 

933 tag = tokens[i].tags 

934 if "particle" not in tag: 

935 bare = False 

936 if not completes: 

937 named += 1 

938 # the word before is a bound given-name word, or the first 

939 # word of a pair joined from its second (#1072) 

940 completes = ("vocab:bound-given" in tag 

941 or BOUND_SECOND_TAG in tag) 

942 if named > 1 or bare and (len(unit) > 1 or unit is first): 

943 return False 

944 _mark_surname(tokens, sorted(first + attached), FIRST_SURNAME_TAG) 

945 _mark_surname(tokens, second, SECOND_SURNAME_TAG) 

946 return True 

947 

948 

949def _divide_comma_family(state: ParseState, tokens: list[WorkToken], 

950 family: list[int], turkic: bool) -> None: 

951 """rules/O6: "the part before it is the whole family, divided" -- 

952 where nothing after the comma joined it: the family is that part's 

953 words alone, none taken in from after the comma (P1's fold, P6's 

954 attachment), and the part's script sets no order other than the 

955 declared one (W4), as the comma-less name is left alone there 

956 (decisions/O6, #1456).""" 

957 # the family's words in written order, so its last word is the one 

958 # a word joined from after the comma would be 

959 if tokens[family[-1]].span.start > state.comma_offsets[0]: 

960 return 

961 # every script an order can be keyed to (Script: Han, Hangul, kana, 

962 # Cyrillic) is written from U+0400 up, so a word below it, accented 

963 # Latin included, is in none (W4); a C-level test, no frame 

964 if max(tokens[family[0]].text) >= "\u0400" and _effective_order( 

965 state.policy, [tuple(family)], [0], tokens, 

966 dot_divided=bool(state.interpunct_offsets) 

967 ).order != state.policy.name_order: 

968 return 

969 _divide_family(tokens, family, turkic) 

970 

971 

972def _read_surname_pair(state: ParseState, 

973 tokens: list[WorkToken]) -> PendingAmbiguity | None: 

974 """rules/W5: "the two surnames are the family, in two units" -- the 

975 second, which script_segment tagged, joins the family assign placed 

976 before it, and what is left is laid out by the order as O6's 

977 family-first branch lays out its own (decisions/W5, #845). In place. 

978 

979 script_segment divides the pair only where the name is read 

980 family-first, so assign placed the first surname as the family and 

981 the second as the first word after it; the checks below keep the 

982 tag inert anywhere else all the same. 

983 

984 The report is made here, where the pair is read, and only for a 

985 name written undivided: there W1's longest listed surname first 

986 reads the given name from the second surname on, and that is the 

987 reading not taken, while a writer's space after the pair has 

988 already said where the given name starts.""" 

989 if state.order is None or state.order[0] is Role.GIVEN: 

990 return None 

991 _, given, middle, family = _positions(tokens) 

992 units = _units(tokens, sorted(given + middle)) 

993 if (len(family) != 1 or not units or len(units[0]) != 1 

994 or units[0][0] != family[0] + 1 

995 or SURNAME_PAIR_TAG not in tokens[units[0][0]].tags): 

996 return None 

997 first, second = family[0], units[0][0] 

998 _lay_out_after_family(tokens, units, state.order) 

999 _mark_surname(tokens, family, FIRST_SURNAME_TAG) 

1000 _mark_surname(tokens, units[0], SECOND_SURNAME_TAG) 

1001 after = second + 1 

1002 if (after == len(tokens) or tokens[after].span is None 

1003 or tokens[after].span.start != tokens[second].span.end): 

1004 return None 

1005 word = (tokens[first].text + tokens[second].text 

1006 + tokens[after].text) 

1007 return PendingAmbiguity( 

1008 AmbiguityKind.SEGMENTATION, 

1009 f"{word!r} splits as {tokens[first].text!r} + " 

1010 f"{tokens[second].text!r} + {tokens[after].text!r} on two " 

1011 f"surnames; {tokens[first].text!r} + " 

1012 f"{tokens[second].text + tokens[after].text!r} also reads", 

1013 (first, second, after)) 

1014 

1015 

1016def _one_given_word(tokens: list[WorkToken], given: list[int]) -> bool: 

1017 """Whether the given name is ONE word, as rules/O7 and P10 count it: O6's 

1018 count, save that a bound given-name pair (P5) is two words though 

1019 its bound word is also a particle the count passes over ('Abu 

1020 Bakr').""" 

1021 return (_family_word_count(tokens, given) == 1 

1022 and not (len(given) > 1 

1023 and "vocab:bound-given" in tokens[given[0]].tags)) 

1024 

1025 

1026def _completes_a_given_name(tokens: list[WorkToken], unit: list[int], 

1027 lexicon: Lexicon) -> bool: 

1028 """Whether `unit` is a particle run and ONE word written 

1029 `after_particle` ('del Carmen'), the second of a compound given name 

1030 as rules/P10 reads one; a run holding a saint particle ('Santa 

1031 María') opens a surname instead.""" 

1032 n = 0 

1033 while n < len(unit) and "particle" in tokens[unit[n]].tags: 

1034 if _normalize(tokens[unit[n]].text) in lexicon._sets.saint_particles: 

1035 return False 

1036 n += 1 

1037 return (0 < n == len(unit) - 1 

1038 and PARTICLE_GIVEN_TAG in tokens[unit[-1]].tags) 

1039 

1040 

1041def _given_phrase_middle(state: ParseState, 

1042 tokens: list[WorkToken]) -> None: 

1043 # rules/P10: "the particle run and that word are a middle name" -- 

1044 # behind a lone given name of one word, read given-first with no 

1045 # family comma, the family's opening particle run and the one word 

1046 # after it, read off the tag classify gives a word of 

1047 # Lexicon.particle_given_names, where a name word is left for the 

1048 # family (decisions/P10, #704). In place, as every post rule writes. 

1049 # A family comma reads the phrase as a middle already, and a 

1050 # family-first order puts no family behind the given name. 

1051 # Called only for a name holding a marked word (post_rules' loop). 

1052 if (state.structure is Structure.FAMILY_COMMA or state.order is None 

1053 or state.order[0] is not Role.GIVEN): 

1054 return 

1055 _, given, middle, family = _positions(tokens) 

1056 # a given name no patronymic, shared name or mark, of one word, with 

1057 # no middle between it and the family 

1058 if (not given or not family or middle 

1059 or family[0] < given[-1] 

1060 or not _one_given_word(tokens, given) 

1061 or any(PATRONYMIC_TAG in tokens[i].tags 

1062 or SHARED_NAME_TAG in tokens[i].tags for i in given) 

1063 or not any(ch.isalpha() for i in given for ch in tokens[i].text)): 

1064 return 

1065 cut = _fold_reach(tokens, family) 

1066 if cut >= len(family) or not _completes_a_given_name( 

1067 tokens, family[:cut], state.lexicon): 

1068 return 

1069 # a name word left for the family: one with a letter that is no 

1070 # connective standing alone ('María del Carmen y') 

1071 if not any(any(ch.isalpha() for ch in tokens[i].text) 

1072 and "conjunction" not in tokens[i].tags 

1073 for i in family[cut:]): 

1074 return 

1075 # and no Turkic marker behind the phrase, whose father's name it 

1076 # would be 

1077 if (PatronymicRule.TURKIC in state.policy.patronymic_rules 

1078 and is_patronymic_marker(tokens[family[cut]].text)): 

1079 return 

1080 for i in family[:cut]: 

1081 _retag(tokens, i, Role.MIDDLE) 

1082 

1083 

1084def _take_second_given_name(state: ParseState, 

1085 tokens: list[WorkToken]) -> None: 

1086 # rules/O7: "the given name takes the middle unit beside it" -- 

1087 # O6's mirror, read after O6 has taken its word and before O3 

1088 # folds what is left. In place, as every post rule writes. 

1089 # History: decisions/O7 (#704). 

1090 # A family comma leaves the given part laid out given-first; without 

1091 # one, an order the script set (W4) is not the caller's, as for O6. 

1092 if state.structure is Structure.FAMILY_COMMA: 

1093 given_first = True 

1094 elif state.order is None or state.order != state.policy.name_order: 

1095 return 

1096 else: 

1097 given_first = state.order.index(Role.GIVEN) < state.order.index( 

1098 Role.MIDDLE) 

1099 _, given, middle, _ = _positions(tokens) 

1100 # a given name already holding two words keeps what it has: a 

1101 # hyphenated one, or a bound given-name pair (P5), counted as O6 

1102 # counts the family 

1103 if not given or not middle or not _one_given_word(tokens, given): 

1104 return 

1105 # the unit beside the given name: the positions lay a given-first 

1106 # part out given, middles..., and FAMILY_FIRST_GIVEN_LAST's 

1107 # middles..., given, so it is the first middle unit or the last 

1108 units = _units(tokens, middle) 

1109 take = units[0] if given_first else units[-1] 

1110 # ONE name word, counted as O6 counts one, with a letter in it; an 

1111 # initial is taken, since it writes a given name. A given name with 

1112 # no letter in it is a mark or a number, nothing to complete. 

1113 if (_family_word_count(tokens, take) != 1 

1114 or not any(ch.isalpha() for i in take for ch in tokens[i].text) 

1115 or not any(ch.isalpha() for i in given for ch in tokens[i].text)): 

1116 return 

1117 # a patronymic is no given name, on either side of the join: a 

1118 # patronymic particle's run, its reading decided at classify (R9's 

1119 # vocabulary arm), whether it is the unit taken or the given name 

1120 # itself; a word an ending rule a policy turns on reads as one; and 

1121 # a Turkic marker's father 

1122 if any(PATRONYMIC_TAG in tokens[i].tags for i in take + given): 

1123 return 

1124 # rules/O7: "a name a community gives every member is no given 

1125 # name" -- Kaur and Singh, on either side of the join, tagged at 

1126 # classify from Lexicon.shared_names (decisions/O7, #704) 

1127 if any(SHARED_NAME_TAG in tokens[i].tags for i in take + given): 

1128 return 

1129 rules = state.policy.patronymic_rules 

1130 if rules: 

1131 slavic = PatronymicRule.EAST_SLAVIC in rules 

1132 turkic = PatronymicRule.TURKIC in rules 

1133 after = take[-1] + 1 

1134 if any(slavic and has_patronymic_ending(tokens[i].text) 

1135 or turkic and is_patronymic_marker(tokens[i].text) 

1136 for i in take) or ( 

1137 turkic and after < len(tokens) 

1138 and is_patronymic_marker(tokens[after].text)): 

1139 return 

1140 for i in take: 

1141 _retag(tokens, i, Role.GIVEN) 

1142 

1143 

1144# rules/R10: "the family's second name unit, the one written second, 

1145# makes the second-surname view" -- whichever of the two units O6 

1146# divides the family into, a word taken or not, or W5's pair 

1147# (decisions/R10, #754); and rules/R11: "the family's first name unit, 

1148# the one written first, makes the first-surname view" -- the other one, 

1149# marked in the same place (decisions/R11, #1022). It moves a unit into 

1150# the family as it marks it, one copy per word (frame budget). 

1151def _mark_surname(tokens: list[WorkToken], unit: list[int], 

1152 tag: str) -> None: 

1153 for i in unit: 

1154 tokens[i] = copy_with(tokens[i], role=Role.FAMILY, 

1155 tags=tokens[i].tags | {tag}) 

1156 

1157 

1158def _addressing_run(titles: list[int], name_word: int) -> list[int]: 

1159 """The title run H1 asks about: the LEADING one where one stands, 

1160 else the whole (trailing) run -- rules/H1 -- the run standing 

1161 BEFORE the one name word being the run that addresses, and a run 

1162 standing behind it deciding that word's field only when none 

1163 stands before. 

1164 

1165 Every title token is in the TITLE role by the time this runs, both 

1166 ends of `Sir John Prof.` among them, so `titles` is not a run -- 

1167 keeping the two ends apart is what makes a trailing title 

1168 TRANSPARENT (rules/H5): `Sir John Prof.` is `Sir John` plus a 

1169 title, and reading both ends as one run keyed 'sir prof' made 

1170 adding the title flip the name word's field (#489, #316). 

1171 

1172 The split is at the NAME WORD, not at the first token of another 

1173 role, and the difference is a nickname or a maiden name written 

1174 among the titles. H1's own rationale says what stands beside the 

1175 name word "does not make the name any longer, so it does not 

1176 decide this reading", and that has to hold for WHICH run 

1177 addresses as well as for how many words the name has: `Dr. 

1178 'Smitty' Sir John` is one run written around a nickname and reads 

1179 given 'John' as `Dr. Sir John` does, while `'Smitty' Dr. Jones 

1180 Sir.` keeps family 'Jones' as `Dr. Jones Sir.` does. Splitting on 

1181 the first non-title token got both wrong (measured 2026-09-09). 

1182 

1183 Called only from inside H1's guard, after the role counts have 

1184 short-circuited, so a name with both a given and a family never 

1185 builds this list; `name_word` is the first GIVEN, or the first 

1186 FAMILY in the direction #720 added. The given guard has proved it 

1187 is the only name word there is; the family guard proves only that 

1188 no given or middle stands beside it, which is where a comma or 

1189 O5's convention set to the family leaves one name word.""" 

1190 return [i for i in titles if i < name_word] or titles 

1191 

1192 

1193def _family_settled(state: ParseState, tokens: list[WorkToken], 

1194 families: list[int]) -> bool: 

1195 """Whether something other than O5's convention placed this lone family 

1196 word, so H1's family -> given direction leaves it (#720). After a 

1197 comma a particle in it is settled -- rules/C3's "the comma settles 

1198 P1's fork for a leading particle that could be a given name" 

1199 ('van Gogh, Sir'); without one, P1's fold below takes a never-given 

1200 particle opening the name with a word behind it ('Sir de Mesnil'), 

1201 or under a family-first order a piece `_family_first_lead_folds` 

1202 names ('Sir van Berg', rules/P11), asked by the fold's own 

1203 predicates on the same piece. An ambiguous particle 

1204 nothing settled, or a bare one with nothing to fold, is a 

1205 word O5's convention placed, which reaches here only with 

1206 `Policy.lone_name_word` set to family ('Sir Van', 'Sir Abu Bakar', 

1207 'Sir de', and 'Sir von und zu' under the default order, whose 

1208 never-given 'zu' does not open it).""" 

1209 if state.structure is Structure.FAMILY_COMMA: 

1210 return any("particle" in tokens[i].tags for i in families) 

1211 if len(families) < 2: 

1212 return False 

1213 lead = _leading_name_piece(state, tokens) 

1214 return (is_lone_never_given_particle(lead, tokens) 

1215 or state.order is not None and state.order[0] is Role.FAMILY 

1216 and _family_first_lead_folds(state, tokens, lead)) 

1217 

1218 

1219def _family_first_lead_folds(state: ParseState, tokens: list[WorkToken], 

1220 lead: Sequence[int], 

1221 reach: int | None = None) -> bool: 

1222 """Whether rules/P1's fold takes `lead`, the piece opening the 

1223 name, beside the lone never-given particle it takes under every 

1224 order (asked inline by each caller first, sparing every parse a 

1225 frame), and asked only under a family-first order: two more -- a lone ambiguous particle written 

1226 in lower case in a name of mixed case (rules/P11, #670), and a 

1227 particle chain a title-particle in front lets P2 build (rules/P4's 

1228 Except, #828), cut after its particles and one name unit unless a 

1229 suffix-or-name report names a word past that reach ('St de Mesnil 

1230 Jean V'). A chain the reach already covers is left whole ('St Sir de 

1231 Mesnil', 'St abu Bakar'). `reach` is `_fold_reach` over `lead` 

1232 where the caller has it already.""" 

1233 # rules/P1: "a particle chain behind a title-particle is cut as the 

1234 # run is" -- the chain clause; and rules/P11: "an ambiguous particle 

1235 # written in lower case, in a name of mixed case, opens the name as 

1236 # a never-given one does" -- the writing clause (decisions/P1 and 

1237 # decisions/P11, #828, #670) 

1238 if is_lowercase_ambiguous_particle(lead, tokens, state.one_case): 

1239 return True 

1240 if len(lead) < 2 or "particle" not in tokens[lead[0]].tags: 

1241 return False 

1242 if reach is None: 

1243 reach = _fold_reach(tokens, list(lead)) 

1244 # a word past the reach a suffix-or-name report names was read 

1245 # against the whole chain ('St de Mesnil Jean V', whose numeral had 

1246 # no word to spare): the cut would strand it, so the chain stands 

1247 return reach < len(lead) and not reported_suffix_fork( 

1248 state.ambiguities, lead[reach:]) 

1249 

1250 

1251# rules/S1: "it is no nickname and no maiden name, and the words around 

1252# it read as they would beside a nickname" -- the clause's words 

1253# take their roles here, once the name's words are placed: extract has 

1254# already lifted a clause wholly of unambiguous non-name words out of 

1255# the name, and a member of the ambiguous class joins one only after 

1256# the name (rules/S13), and only where its writing or another word of 

1257# its clause settles it; decisions/S1 (#792, #1138) 

1258def _set_apart_clauses(state: ParseState, 

1259 tokens: list[WorkToken]) -> None: 

1260 """Give each word of a delimited clause wholly of non-name words 

1261 the role its vocabulary gives it: a title a title, a credential or 

1262 generation the suffix, and a word that is both a title in front of 

1263 the name's first word or in a name with no word of its own, and the 

1264 suffix anywhere else. A clause extract set apart may still be 

1265 declined here, keeping its pair's reading: titles alone behind a 

1266 word read as a suffix, a credential written as initials before a 

1267 name word of its comma part, a member of the ambiguous class not 

1268 after the name, or one neither its writing nor a credential of its 

1269 clause settles.""" 

1270 first_name = last_name = -1 

1271 for i, t in enumerate(tokens): 

1272 if t.role in NAME_ROLES: 

1273 last_name = i 

1274 if first_name < 0: 

1275 first_name = i 

1276 starts = [t.span.start for t in tokens] 

1277 lex = state.lexicon 

1278 # whether a name word stands after each token in its comma part, 

1279 # built once on first need, so a name of many clauses stays linear 

1280 ahead: list[bool] | None = None 

1281 for _, clause in state.extracted: 

1282 lo = bisect.bisect_left(starts, clause.start) 

1283 hi = bisect.bisect_left(starts, clause.end) 

1284 words = state.original[clause.start:clause.end].split() 

1285 # every word one token of the clause, as extract read them 

1286 if not words or hi - lo != len(words) or any( 

1287 tokens[i].role not in (Role.NICKNAME, Role.MAIDEN) 

1288 for i in range(lo, hi)): 

1289 continue 

1290 kinds: list[SetApartKind] = [] 

1291 member = False 

1292 unsettled = settled = False 

1293 # the clause's credential words, asked `settles_a_member` only 

1294 # where an unsettled member needs one 

1295 others: list[str] = [] 

1296 for i in range(lo, hi): 

1297 token = tokens[i] 

1298 kind = set_apart_kind(token.text, lex) 

1299 # a member its periods settle, or a joined word whose own 

1300 # chunks settle its member, settles the others, as does a 

1301 # credential that is no name (`settles_a_member`); one its 

1302 # capitals settle does not, so the clause reads as its 

1303 # joined spelling, whose chunks are never read by case 

1304 # (#1138) 

1305 if kind == "member": 

1306 kind, member, settled = "suffix", True, True 

1307 elif kind is None and AMBIGUOUS_ACRONYM_TAG in token.tags \ 

1308 and settled_by_case(token, state.one_case): 

1309 kind, member = "suffix", True 

1310 elif kind is None and member_word(token.text, lex): 

1311 kind, member, unsettled = "suffix", True, True 

1312 elif kind is None: 

1313 break 

1314 else: 

1315 others.append(token.text) 

1316 kinds.append(kind) 

1317 else: 

1318 # rules/S1: "a member its writing leaves unsettled is one 

1319 # too where a credential of the same clause settles it" -- 

1320 # a credential that is no name, or a member its periods 

1321 # settle (decisions/S1, #1138); asked only of a clause 

1322 # holding such a member, so one with none pays nothing 

1323 if unsettled and not settled: 

1324 for text in others: 

1325 if settles_a_member(text, lex): 

1326 break 

1327 else: 

1328 continue 

1329 # a member is settled after the name only (rules/S13), and 

1330 # a credential written as initials before a name word of its 

1331 # comma part stays the nickname 

1332 if member and not 0 <= last_name < lo: 

1333 continue 

1334 # a name word after the clause in its comma part stands 

1335 # behind the last name word, so a clause after the name skips 

1336 # the walk; a title is never initials, asked inline 

1337 if last_name >= hi and any( 

1338 kind != "title" 

1339 and reads_as_initials(w, kind, state.one_case, lex) 

1340 for w, kind in zip(words, kinds)): 

1341 if ahead is None: 

1342 ahead = _name_ahead(state, tokens) 

1343 if ahead[hi - 1]: 

1344 continue 

1345 # the token in front of the clause 

1346 if not set_apart(words, kinds, lo > 0 

1347 and tokens[lo - 1].role is Role.SUFFIX, lex): 

1348 continue 

1349 for i, kind in zip(range(lo, hi), kinds): 

1350 title = kind == "title" or ( 

1351 kind == "dual" and (first_name < 0 or i < first_name)) 

1352 # a comma the clause kept on its word (rules/N1) is no 

1353 # part of a title or a suffix: the word's span is 

1354 # trimmed, so its text stays the original slice, and 

1355 # R1's entry pass reads the comma left between two 

1356 # suffix words 

1357 token = tokens[i] 

1358 text = token.text.strip(COMMA_STRIP) 

1359 start = token.span.start + token.text.index(text) 

1360 tokens[i] = copy_with( 

1361 token, role=Role.TITLE if title else Role.SUFFIX, 

1362 text=text, span=Span(start, start + len(text))) 

1363 

1364 

1365def _name_ahead(state: ParseState, tokens: list[WorkToken]) -> list[bool]: 

1366 """For each token, whether a name word stands after it before the 

1367 next comma: one walk from the end, each comma part's answer reset 

1368 where the part changes.""" 

1369 ahead = [False] * len(tokens) 

1370 seen = False 

1371 part = None 

1372 for i in range(len(tokens) - 1, -1, -1): 

1373 here = comma_bucket(tokens[i].span.start, state.comma_offsets) 

1374 if here != part: 

1375 part, seen = here, False 

1376 ahead[i] = seen 

1377 if tokens[i].role in NAME_ROLES: 

1378 seen = True 

1379 return ahead 

1380 

1381 

1382# rules/S13: "where the member's writing settles it as the credential, 

1383# the way the rules that read the writing say a credential is written, 

1384# it is no nickname but the suffix" -- the settling itself is 

1385# `_set_apart_clauses`', which reads a lone member whose writing 

1386# settles it after the name as a clause of one non-name word; what is 

1387# left here is the report on a member it left the nickname 

1388# (decisions/S13 (#810), decisions/S1 (#792)) 

1389def _report_delimited_members(tokens: list[WorkToken], lexicon: Lexicon, 

1390 ambiguities: list[PendingAmbiguity]) -> None: 

1391 """Report the fork on every member of the ambiguous class left a 

1392 nickname: `_set_apart_clauses`, run first, has made each member its 

1393 writing settles after the name the suffix, so a member still a 

1394 nickname is one it did not settle, a dotted member or a joined word 

1395 holding a member ('MA/PhD') inside the name included. Reported 

1396 here, where the clause is decided, rather than in extract, which 

1397 has no token index to point at. A dotted or joined member carries 

1398 no tag in a clause (classify tags a shape only outside one), so 

1399 each is found by its text, by `dotted_member` or `joined_member` as 

1400 the settling finds it, whatever else the vocabulary reads it as.""" 

1401 for i, token in enumerate(tokens): 

1402 if token.role is not Role.NICKNAME: 

1403 continue 

1404 # the period and the joiners asked first, at C level, so a 

1405 # nickname written with neither pays no frame 

1406 if (AMBIGUOUS_ACRONYM_TAG in token.tags 

1407 or "." in token.text and ( 

1408 dotted_member(token.text, lexicon) 

1409 or period_member(token.text, lexicon)) 

1410 or ("/" in token.text or "-" in token.text) 

1411 and joined_member(token.text, lexicon)): 

1412 ambiguities.append(PendingAmbiguity( 

1413 AmbiguityKind.SUFFIX_OR_NICKNAME, 

1414 f"delimited {token.text!r} is also a post-nominal; read " 

1415 f"as a nickname rather than a suffix", 

1416 (i,), alternative=suffix_reading(token))) 

1417 

1418 

1419def _unattached(state: ParseState, tokens: list[WorkToken], 

1420 word: WorkToken, start: int) -> PendingReading: 

1421 """The name reading of the particle run P6 attaches at the end of 

1422 a name read family-first, which starts at token `start`: the field 

1423 the positional read gave it, or the field of the name piece in 

1424 front where that piece would take a name word in (`_name_alt`).""" 

1425 role = tokens[start].role 

1426 assert role is not None # assign roled every name word 

1427 # the run ends a name read family-first, so a name word stands in 

1428 # front of it 

1429 front, first = next( 

1430 ((piece, k == 0) for seg_idx in range(len(state.pieces)) 

1431 for k, piece in enumerate(_name_pieces(state, tokens, seg_idx)) 

1432 if start - 1 in piece), (None, False)) 

1433 return _name_alt(word, role, front, tokens, first, False) 

1434 

1435 

1436def post_rules(state: ParseState) -> ParseState: 

1437 # rules/P12's split hands its readers the pieces cut, and the stage 

1438 # hands on group's, pieces being no field it writes 

1439 grouped = (state.pieces, state.piece_tags) 

1440 tokens = list(state.tokens) 

1441 ambiguities = list(state.ambiguities) 

1442 if state.extracted: 

1443 _set_apart_clauses(state, tokens) 

1444 _report_delimited_members(tokens, state.lexicon, ambiguities) 

1445 titles, givens, middles, families = _positions(tokens) 

1446 # rules/P12: "A pair read from its second word needs a third name 

1447 # word" -- asked of the parse, once roles are settled, so the 

1448 # trailing run's reading is the one counted (decisions/P12, #1072) 

1449 # the tag test inline, in C, so that a name of two words with no 

1450 # such pair pays no frame for it 

1451 names = givens + middles + families 

1452 if (len(names) == 2 and max(names) == min(names) + 1 

1453 and BOUND_SECOND_TAG in tokens[min(names)].tags 

1454 and _split_a_lone_backward_pair(state, tokens, ambiguities)): 

1455 titles, givens, middles, families = _positions(tokens) 

1456 # rules/P12: "the pair is joined only in a name the parse reads as 

1457 # four name words or more" -- the `long_names_only` Except, counted 

1458 # here once roles are settled, so a word the trailing run or a title 

1459 # phrase takes counts as the parse reads it (decisions/P12 (#1464, 

1460 # #1531)); the tag tests inline, in C, so that a name with no such 

1461 # pair pays no frame for it 

1462 else: 

1463 for i in names: 

1464 if (BOUND_PHRASE_TAG in tokens[i].tags 

1465 and BOUND_SECOND_TAG not in tokens[i].tags): 

1466 # name words hold a letter: a lone mark assign placed 

1467 # is none; a plain loop, where a generator cost a frame 

1468 # per word 

1469 letters = 0 

1470 for k in names: 

1471 if _HAS_LETTER.search(tokens[k].text): 

1472 letters += 1 

1473 if (letters < 4 and _normalize(tokens[i].text) 

1474 in state.lexicon._sets.bound_long_names_only): 

1475 moved, state = _split_a_short_open_pair( 

1476 state, tokens, i) 

1477 if moved: 

1478 titles, givens, middles, families = _positions( 

1479 tokens) 

1480 break 

1481 

1482 # rules/H1: "a title followed by exactly one name word makes 

1483 # that word the family name, whatever suffix, nickname or maiden 

1484 # name stands beside it, unless the title is a given-name title, 

1485 # which keeps it the given name; a run of several titles addresses 

1486 # as its last title does" -- counting suffix, nickname and maiden 

1487 # as further name words is what emptied the family (#410) 

1488 # (known gap: the guard tests which roles are unoccupied, it does 

1489 # not count units -- decisions/H1) (v1 handle_firstnames) 

1490 # 

1491 # rules/H1: "a run of several titles addresses as its last 

1492 # title does, and where a run stands BEFORE the one name word it 

1493 # is the run that addresses, a run standing behind it deciding 

1494 # that word's field only when none stands before" -- #489. WHICH 

1495 # run that is, and why the two ends of a name are not one, are 

1496 # _addressing_run's; its docstring carries the history. 

1497 if (titles and givens and not middles and not families 

1498 and not _run_addresses_by_given( 

1499 (tokens[i].text 

1500 for i in _addressing_run(titles, givens[0])), 

1501 state.lexicon._sets.given_name_titles)): 

1502 for i in givens: 

1503 _retag(tokens, i, Role.FAMILY) 

1504 # every rule below reads these lists; recompute after any 

1505 # retag so no guard can inspect a name that has already 

1506 # moved -- a stale index list is the bug shape #359 fixed 

1507 _, givens, middles, families = _positions(tokens) 

1508 # rules/H1: "a comma with no given name after it does not decide 

1509 # the field, nor does O5's convention" -- the other direction, for 

1510 # the shapes assign reads as the family before H1 can see them 

1511 # (#720): a family comma with no name word after it and one before 

1512 # it, and the one name word O5's convention read as the family 

1513 # (`Policy.lone_name_word` set to family). The comma named no given 

1514 # part, and the convention places a word nothing else decided, so 

1515 # the title decides as it does in 'Sir John' ('John III, Sir' reads 

1516 # as 'Sir John III'), unless 

1517 # something else settled the word (_family_settled). 

1518 elif (titles and families and not givens and not middles 

1519 and not _family_settled(state, tokens, families) 

1520 and _run_addresses_by_given( 

1521 (tokens[i].text 

1522 for i in _addressing_run(titles, families[0])), 

1523 state.lexicon._sets.given_name_titles)): 

1524 for i in families: 

1525 _retag(tokens, i, Role.GIVEN) 

1526 # recomputed for H1's reason, stated above 

1527 _, givens, _, families = _positions(tokens) 

1528 

1529 # rules/M4: "a maiden name standing beside exactly one name 

1530 # word makes that word the family name, whatever suffix or 

1531 # nickname stands beside it" (#445) -- the MAIDEN role, not a 

1532 # marker: M1's configured pair produces one with no marker 

1533 # anywhere ("Smith (Jones)" under maiden_delimiters), and the 

1534 # rationale carries over unchanged, so the rule is keyed on the 

1535 # maiden name as the statement is. 

1536 # 

1537 # H1's sibling, and placed under it so the interaction the rule 

1538 # states is decidable by reading: where H1 fired, `givens` is 

1539 # empty here and this cannot fire; where H1 declined because the 

1540 # title addresses by given name, `titles` is what keeps this rule 

1541 # off the same word. A titled name is H1's at both outcomes. 

1542 # 

1543 # Sibling EXCEPT in what it counts, and that is a known gap 

1544 # rather than a boundary: this guard counts GIVEN tokens where 

1545 # H1 counts nothing (it tests which roles are unoccupied), so a 

1546 # name word another rule joined counts as several here and the 

1547 # rule declines -- `Dr. Mary and Jane` reads family, while 

1548 # `Mary and Jane née Jones` keeps given 'Mary and Jane'. 

1549 # rules/P3 says a joined part is one name word wherever 

1550 # another rule counts them, so the two disagree; widening moves 

1551 # no corpus name and is not this change's to make 

1552 # (decisions/M4). 

1553 # rules/M4: "a bound given name keeps the reading O5's convention 

1554 # gives it, and so does a word read as an initial" 

1555 # -- read off the tags classify already recorded rather than a 

1556 # predicate of this rule's own, because this rule changes what 

1557 # POSITION decided and must not reach what a word IS 

1558 # (mechanisms.md#TWO-LAYER-ASSIGN). 

1559 if (not titles and len(givens) == 1 and not middles and not families 

1560 and any(t.role is Role.MAIDEN for t in tokens) 

1561 and not (_NEVER_FLIPPED & tokens[givens[0]].tags)): 

1562 _retag(tokens, givens[0], Role.FAMILY) 

1563 # recomputed for H1's reason, stated at H1: a stale index list 

1564 # is the bug shape #359 fixed 

1565 _, givens, middles, families = _positions(tokens) 

1566 

1567 # rules/P1: "the particle run and the name words it takes are 

1568 # family, under every name order" -- its Then clause, for a 

1569 # never-given particle opening the name and, under a family-first 

1570 # order, the two pieces `_family_first_lead_folds` adds; how many words the run 

1571 # takes is set by the order or a family comma, in P1's bullets and 

1572 # below (v1 handle_non_first_name_prefix; decisions/P1) 

1573 # How far the fold reaches depends on the order the name was READ 

1574 # under (#395; decisions/P1, 2026-08-17): declaring a 

1575 # family-first order asserts that what follows the family is not 

1576 # more surname, which is the very question of where the run stops. 

1577 # Under that declaration the run takes its own particles and ONE 

1578 # name word; under the default order it keeps taking the rest of 

1579 # the name, nothing having marked where the surname ends. Note what 

1580 # actually holds the family-comma shape back, since it is NOT 

1581 # that test -- "Smith, de Mesnil Jean" DOES fire the leading site, 

1582 # segment 1 opening with the particle. It keeps the old reach 

1583 # because assign records no order after a family comma, the comma 

1584 # having already fixed the surname, so `order is None` here. 

1585 # Anything that later gives that path an order turns the 

1586 # narrowing on for it. 

1587 # ONE site, the opening piece. A particle standing in the GIVEN 

1588 # position was a second site until #467, and it was the parser 

1589 # overriding a declaration rather than reading one: under a 

1590 # family-first order that slot holds what the caller SAID is the 

1591 # given name, and the never-given vocabulary supplies a default 

1592 # where position leaves the question open, not a veto over an 

1593 # answer position already gave. So "Menil de" under either 

1594 # family-first order reports given "de" -- P6 takes the trailing 

1595 # particle only where it landed in a MIDDLE, which means nothing. 

1596 # Code-local: a lone PIECE is the test (`_family_first_lead_folds` names the two 

1597 # pieces a family-first order adds), so a particle group already 

1598 # chained forward is not a lone particle elsewhere, and rule H1 

1599 # above cannot be what produces the fold's family reading -- its 

1600 # given -> family branch is gated on `not families`, and its family 

1601 # -> given branch leaves the word this fold takes, asking the same 

1602 # predicate (_family_settled). 

1603 lead = _leading_name_piece(state, tokens) 

1604 family_first = state.order is not None and state.order[0] is Role.FAMILY 

1605 reach = None 

1606 if (family_first and len(lead) > 1 

1607 and "particle" in tokens[lead[0]].tags): 

1608 # the words past the fold's reach, marked for assemble's 

1609 # alternatives whether or not the fold cuts there (#828) 

1610 reach = _fold_reach(tokens, list(lead)) 

1611 for i in lead[reach:]: 

1612 tokens[i] = copy_with(tokens[i], 

1613 tags=tokens[i].tags | {PAST_REACH_TAG}) 

1614 lead_fires = (is_lone_never_given_particle(lead, tokens) 

1615 or family_first 

1616 and _family_first_lead_folds(state, tokens, lead, reach)) 

1617 if len(givens) + len(middles) + len(families) > 1 and lead_fires: 

1618 order = state.order 

1619 if order is not None and order[0] is Role.FAMILY: 

1620 # `state.order`, not policy.name_order: a script_orders 

1621 # entry can put the family first under a given-first 

1622 # policy, and the roles below have to match the read 

1623 # assign actually made. 

1624 name_idx = sorted(givens + middles + families) 

1625 cut = _fold_reach(tokens, name_idx) 

1626 for i in name_idx[:cut]: 

1627 _retag(tokens, i, Role.FAMILY) 

1628 # What is left is a shorter name of the same order: one 

1629 # family already placed, so drop that slot and lay the 

1630 # rest out as _name_positions would for n + 1 pieces. 

1631 rest = _units(tokens, name_idx[cut:]) 

1632 for unit, role in zip(rest, _name_positions( 

1633 order, len(rest) + 1)[1:]): 

1634 for i in unit: 

1635 _retag(tokens, i, role) 

1636 else: 

1637 for i in givens + middles: 

1638 _retag(tokens, i, Role.FAMILY) 

1639 # downstream rules key on the role counts: recompute 

1640 _, givens, middles, families = _positions(tokens) 

1641 

1642 # v1 gates both rotations on `not self._had_comma`; the 

1643 # middle_as_family fold below runs comma or not (v1 order: 

1644 # patronymics first, then handle_middle_name_as_last) 

1645 rules = state.policy.patronymic_rules 

1646 # gated on the rules, which a default parse leaves empty, so it 

1647 # asks nothing (decisions/parse-cost, #1170) 

1648 rotations_apply = bool(rules) and _rotations_apply(state) 

1649 # rules/O1: "a name of exactly three name words — titles, 

1650 # suffixes and nicknames aside — whose last name word carries a 

1651 # patronymic ending and whose middle name word does not reads as 

1652 # family-first" (history: decisions/O1) 

1653 if rotations_apply and PatronymicRule.EAST_SLAVIC in rules and \ 

1654 len(givens) == 1 and len(middles) == 1 and len(families) == 1: 

1655 tail = tokens[families[0]].text 

1656 mid = tokens[middles[0]].text 

1657 # rules/O1: "T5 wins, and T4 in a name written wholly in one 

1658 # case" -- an initial first or in the middle keeps the order, 

1659 # read off classify's tag, which carries both rules' reading 

1660 # (so a one-case name's two spellings read alike, a letter P8 

1661 # reads as a connective rotating in either; decisions/O1, 

1662 # #1185, #1217) 

1663 if (east_slavic_rotates(mid, tail) 

1664 and "initial" not in tokens[givens[0]].tags 

1665 and "initial" not in tokens[middles[0]].tags): 

1666 g, m, f = givens[0], middles[0], families[0] 

1667 _retag(tokens, m, Role.GIVEN) 

1668 _retag(tokens, f, Role.MIDDLE) 

1669 _retag(tokens, g, Role.FAMILY) 

1670 # recomputed for H1's reason, stated at H1: a stale index 

1671 # list is the bug shape #359 fixed 

1672 _, givens, middles, families = _positions(tokens) 

1673 # rules/O2: "a name of exactly four name words — titles, 

1674 # suffixes and nicknames aside — ending in a standalone 

1675 # patronymic marker reads family-first: the first name word is 

1676 # the family name" (history: decisions/O2) 

1677 if rotations_apply and PatronymicRule.TURKIC in rules and \ 

1678 len(givens) == 1 and len(middles) == 2 and len(families) == 1: 

1679 tail = tokens[families[0]].text 

1680 if is_patronymic_marker(tail): 

1681 g, m1, m2, f = givens[0], middles[0], middles[1], families[0] 

1682 _retag(tokens, m1, Role.GIVEN) 

1683 _retag(tokens, m2, Role.MIDDLE) 

1684 _retag(tokens, f, Role.MIDDLE) 

1685 _retag(tokens, g, Role.FAMILY) 

1686 # recomputed for H1's reason, stated at H1: a stale index 

1687 # list is the bug shape #359 fixed 

1688 _, givens, middles, families = _positions(tokens) 

1689 # rules/O2: "a name of exactly three name words ending in a 

1690 # standalone patronymic marker reads the father's name and the 

1691 # marker together as the family name" -- the middle word joins the 

1692 # marker in the family (history: decisions/O2, #1187) 

1693 elif rotations_apply and PatronymicRule.TURKIC in rules and \ 

1694 len(givens) == 1 and len(middles) == 1 and len(families) == 1: 

1695 # the marker must be the LAST name word: O1 above may have 

1696 # rotated the first word into the family (`Уулу Аскар Бакытович` 

1697 # with both rules on) 

1698 if (givens[0] < middles[0] < families[0] 

1699 and is_patronymic_marker(tokens[families[0]].text)): 

1700 _retag(tokens, middles[0], Role.FAMILY) 

1701 _, givens, middles, families = _positions(tokens) 

1702 # rules/P6: "a particle ending the name attaches to that family 

1703 # name and is written before it" -- the no-comma site, where a 

1704 # declared family-first order names the family as a comma does. 

1705 # Keyed on the slot, not the vocabulary: a MIDDLE is the one slot 

1706 # meaning nothing here, and dropping a particle from it moves no 

1707 # other role, so no re-layout is needed; the run must also end the 

1708 # name (below). And rules/P6: "Without 

1709 # a comma, the family must hold a base of its own" -- R2's 

1710 # invariant, not a ban on a second particle ("de Mesnil Jan de" 

1711 # gives 'de de Mesnil') (decisions/P6 (#466, #467)) 

1712 # every retagging block above recomputes the lists, so they are 

1713 # current here (a stale index list is the bug shape #359 fixed) 

1714 names = givens + middles + families 

1715 if middles and families and state.order is not None: 

1716 run: list[int] = [] 

1717 i = len(middles) 

1718 while i and "particle" in tokens[middles[i - 1]].tags: 

1719 i -= 1 

1720 run.append(middles[i]) 

1721 # ENDING the name is the rule's own word, and it is the whole 

1722 # test: the trailing MIDDLE is not always the trailing NAME 

1723 # word. Under FAMILY_FIRST_GIVEN_LAST the given name stands 

1724 # behind the middles, and under the default order the family 

1725 # does, so in both a middle that ends the name is impossible 

1726 # and this declines without asking which order was declared. 

1727 # Only FAMILY_FIRST can put a name's last word in a middle. 

1728 # 

1729 # A draft tested the SLOT alone and fired on 52 default-order 

1730 # names, where a conjunction stops a particle's forward chain 

1731 # and leaves it standing in a middle ("Maria Luisa y de la 

1732 # Cruz"), and on 366 FAMILY_FIRST_GIVEN_LAST middles with the 

1733 # given name still behind them. A later draft tested the order 

1734 # as well; measured over 542,592 generated parses, that second 

1735 # test never decides anything this one has not already decided, 

1736 # so it is not here. 

1737 trailing = bool(run) and max(run) == max(names) 

1738 if trailing and any("particle" not in tokens[j].tags 

1739 for j in families): 

1740 # mechanisms.md#AMBIGUITY-AT-THE-DECISION-SITE: "Emit at 

1741 # the site that takes the branch, not where an ambiguous 

1742 # tag sits". decisions/P6 (#405) settled that this 

1743 # attachment reports the fork it decides, and the state it 

1744 # fixed is the one this site would otherwise recreate -- 

1745 # `Beethoven, Ludwig van` reporting while `Beethoven Ludwig 

1746 # van` under FAMILY_FIRST decides the identical fork in 

1747 # silence. ONE arm here where the comma path has two: the 

1748 # suffix reading stands without a comma, so no post-nominal 

1749 # reading is ever overridden for this site to report. 

1750 ambiguous = [j for j in run 

1751 if "vocab:particle-ambiguous" in tokens[j].tags] 

1752 if ambiguous: 

1753 word = tokens[ambiguous[0]].text 

1754 text = " ".join(tokens[j].text for j in sorted(run)) 

1755 ambiguities.append(PendingAmbiguity( 

1756 AmbiguityKind.PARTICLE_OR_GIVEN, 

1757 f"{word!r} is both a family-name particle and an " 

1758 f"ordinary given name; ending a name read " 

1759 f"family-first, {text!r} joins the family that " 

1760 f"order named rather than standing as a name word " 

1761 f"of its own", 

1762 tuple(sorted(run)), 

1763 # the field the positional read gave it, which this 

1764 # attachment moves, unless the piece in front would 

1765 # take a name word in 

1766 alternative=_unattached(state, tokens, 

1767 tokens[ambiguous[0]], 

1768 min(run)))) 

1769 for j in run: 

1770 tokens[j] = copy_with( 

1771 tokens[j], role=Role.FAMILY, 

1772 tags=tokens[j].tags | {FOLDED_TAG, ATTACHED_TAG}) 

1773 # recomputed for H1's reason, stated at H1: a stale index 

1774 # list is the bug shape #359 fixed 

1775 _, givens, middles, families = _positions(tokens) 

1776 

1777 # every parse asks these, so a name holding no marked word pays one 

1778 # plain loop and no call (the parse-cost band, decisions/parse-cost); 

1779 # P10 runs first, and adds no surname pair's tag 

1780 phrase = pair = False 

1781 for token in tokens: 

1782 if PARTICLE_GIVEN_TAG in token.tags: 

1783 phrase = True 

1784 if SURNAME_PAIR_TAG in token.tags: 

1785 pair = True 

1786 if phrase: 

1787 _given_phrase_middle(state, tokens) 

1788 if pair and (report := _read_surname_pair(state, tokens)) is not None: 

1789 ambiguities.append(report) 

1790 # rules/O9 lays out a name it reads after the rules above, so their 

1791 # moves never undo it, and before O6, which stands down where the 

1792 # capitals named the family; O7 and O3 still read the words left. 

1793 # O8 needs no test: the family it reads is one initial, and a 

1794 # family the capitals named is a word of two letters or more 

1795 capitals = (state.policy.capitals_as_family 

1796 and _family_in_capitals(state, tokens, ambiguities)) 

1797 if state.policy.initials_as_family: 

1798 _take_trailing_initials(tokens) 

1799 if state.policy.two_family_names: 

1800 _take_second_family_name(state, tokens, capitals) 

1801 if state.policy.two_given_names: 

1802 _take_second_given_name(state, tokens) 

1803 

1804 # rules/O3: "every middle word joins the family name and is 

1805 # rendered before it" (v1 handle_middle_name_as_last). v1 

1806 # PREPENDED middle_list to last_list; mechanisms.md#FOLDED_TAG: 

1807 # "tokens never move: a rule that needs different rendering order 

1808 # tags the token, and the rendering views consult the tag" 

1809 # 

1810 # The lists walked again, for this fold and R2 below: P10, W5's 

1811 # pair, O6 and O7 above retag without updating them. 

1812 _, givens, middles, families = _positions(tokens) 

1813 if state.policy.middle_as_family: 

1814 # rules/R11: "middle words folded into the family belong to 

1815 # neither unit" -- where O6 marked no units the family before the 

1816 # fold is the first, marked here so the views can leave the 

1817 # folded words out; only a fold that moves a word pays for it 

1818 # (decisions/R11, #1022). A family O6 split carries its marks 

1819 # already; a loop, not a generator, which costs a frame 

1820 if middles: 

1821 for i in families: 

1822 if FIRST_SURNAME_TAG in tokens[i].tags: 

1823 break 

1824 else: 

1825 _mark_surname(tokens, families, FIRST_SURNAME_TAG) 

1826 for i in middles: 

1827 tokens[i] = copy_with( 

1828 tokens[i], role=Role.FAMILY, 

1829 tags=tokens[i].tags | {FOLDED_TAG}) 

1830 # the lists as a walk would now find them, for R2 

1831 families = sorted(families + middles) 

1832 middles = [] 

1833 # rules/R2: "a name part whose every word is particle 

1834 # vocabulary is a part where none of them is doing a particle's 

1835 # work — nothing joins them to a name — so they read as ordinary 

1836 # name words" 

1837 # 

1838 # Last of the rules that MOVE a token, because every rule above 

1839 # can still move one between parts: 

1840 # P1's fold, P6's attachment and O3's fold all rewrite roles, and 

1841 # this reads the roles they settle on. 

1842 # 

1843 # Marked, not untagged: `particle` is stable API and says the word 

1844 # IS particle vocabulary wherever it lands, which stays true. 

1845 # 

1846 # All three roles for uniformity with the rule, not because all 

1847 # three are observable: no view filters tags on GIVEN (initials 

1848 # exempt that role outright), so restricting this loop to MIDDLE 

1849 # and FAMILY moves 0 of 4,506 parses. The GIVEN arm is marked so a 

1850 # future view reading the mark gets a consistent answer. 

1851 # 

1852 # rules/R3: "A part holding nothing else is a part where it is 

1853 # joining nothing, and there it initials like any other name word" 

1854 # -- #461's mark, decided HERE for the same reason R2's is: the 

1855 # question is about the PART, and a view that re-derives a 

1856 # part-level fact is how initials() and family_base came apart. 

1857 # 

1858 # ONE walk decides both marks -- a plain loop, not two generator 

1859 # expressions: this runs per role on every parse and a genexp 

1860 # costs a frame of its own (frame budget). An EMPTY role needs no 

1861 # `continue` ahead of the walk, which is inert on one: measured 

1862 # 2026-09-20, py3.11, one survived the whole suite and moved 

1863 # neither frame count (parse=406.00 facade=443.00 either way). 

1864 # `bool(part)` says the same thing about the R2 arm as 

1865 # `_types._remarked`'s twin of this walk does. 

1866 # 

1867 # rules/R2: "A connective that is not also particle vocabulary, 

1868 # standing between two words of the part, is set aside when the 

1869 # part is asked whether every word is particle vocabulary" -- 

1870 # `between` is the part's own first and last word excluded, and a 

1871 # set-aside connective is left unmarked, so it stays in the base, 

1872 # initials nothing and keeps its case (decisions/R2, #939). A set, 

1873 # since the marking loop asks it per word: a list made a part 

1874 # alternating particle and connective quadratic (test_benchmark's 

1875 # `connective_between_particles` row). 

1876 for part in (givens, middles, families): 

1877 all_particle = bool(part) 

1878 conj: list[int] = [] 

1879 between: set[int] = set() 

1880 others = 0 

1881 last = len(part) - 1 

1882 for n, i in enumerate(part): 

1883 tags = tokens[i].tags 

1884 is_conj = "conjunction" in tags 

1885 if is_conj: 

1886 conj.append(i) 

1887 if "particle" not in tags: 

1888 if is_conj and 0 < n < last: 

1889 between.add(i) 

1890 continue 

1891 all_particle = False 

1892 if not is_conj: 

1893 others += 1 

1894 if all_particle: 

1895 for i in part: 

1896 if i not in between: 

1897 tokens[i] = copy_with( 

1898 tokens[i], tags=tokens[i].tags | {UNJOINED_TAG}) 

1899 elif conj and not others: 

1900 # #461: nothing here for the connective to join. The `elif` 

1901 # is deliberate -- where the part is all-particle R2's mark 

1902 # already readmits every word but a connective it set aside, 

1903 # a word that is BOTH particle and connective included 

1904 # (never set aside, being a particle), which is what keeps 

1905 # a caller's `add("y", kind="particle")` readings unchanged; 

1906 # and it keeps this mark off a connective R2 set aside, which 

1907 # joins the particles around it and initials nothing. 

1908 for i in conj: 

1909 tokens[i] = copy_with( 

1910 tokens[i], 

1911 tags=tokens[i].tags | {UNJOINED_CONJUNCTION_TAG}) 

1912 _mark_suffix_entries(tokens, state) 

1913 return copy_with(state, tokens=tuple(tokens), 

1914 ambiguities=tuple(ambiguities), 

1915 pieces=grouped[0], piece_tags=grouped[1])