1"""Stage: script_segment (#271, #272, #308, #312).
2
3Consumes: tokens, segments, structure, interpunct_offsets, segmenter,
4one_case where segment recorded it, and comma_offsets, for the
5own-words span `_one_case` asks the fact over where segment did not
6(#613; the answer is not recorded, classify recording its own), and
7original, for the peel's ASCII bail.
8Produces: tokens, first with the slash after a listed title opening
9the name or the given part after a family comma cut off and the slash's token
10dropped (rules/T9), then by four independent splits into sub-slices -- a
11word of the part before any comma glued to the next at its full stop
12divided there (rules/T8), with a SUFFIX_OR_NAME report where an
13initial is cut from the word ending the name, a listed title peeled
14off the START of the name's first word or the given part's (rules/W6), a
15listed honorific peeled off the END of the name's last
16non-post-nominal token, in whichever of the name's runs that falls
17(the tail token also carries this module's _PEELED_TAG), and the
18first activated-script token of the name segment split into n+1
19(into its two surnames and, undivided, the given name behind them,
20where a Han surname pair stands there, the second surname carrying
21SURNAME_PAIR_TAG for post_rules, rules/W5) -- segments (index runs remapped past the insertions and T9's removal), ambiguities
22(indices likewise remapped, plus a SEGMENTATION report when more than
23one split was vocabulary-supported, or when a segmenter's answer
24scored under the confidence floor).
25Reads: Lexicon.titles, suffix_acronyms, suffix_words and
26saint_particles (T9's title before the slash) and titles,
27title_modifiers, suffix_words and suffix_acronyms with their ambiguous
28sets (T9's name after it), the vocabulary `_vocab.glued_cuts` reads for T8 (Lexicon.titles,
29titles_ambiguous, title_modifiers, title_styles, saint_particles,
30given_name_abbreviations, suffix_acronyms and its ambiguous set,
31suffix_words and its ambiguous set, credential_words, and
32period_joined_vocab's), and Lexicon.suffix_words, suffix_acronyms,
33titles, titles_ambiguous, title_modifiers, title_styles, conjunctions
34and maiden_markers DIRECTLY (the end-of-name report's and the glued
35saint word's tests), Policy.segment_scripts, Lexicon.surnames, Policy.script_orders
36and Policy.name_order (the order W5's pair needs, rules/W4),
37Lexicon.honorific_tails (the tail peel's words), Lexicon.glued_titles,
38title_modifiers and titles (the front peel's words, the modifiers it
39peels only with a title behind them, and the titles a site steps past
40and never cuts),
41ParseState.segmenter, Lexicon.maiden_markers
42DIRECTLY (the own-words span `_one_case` takes, _pieces.own_words),
43everything classify and `_comma.decide` read, through
44`_postnominal_behind_a_whole_name` (the comma's own decision, asked of
45a classified copy of the state, #613), and Lexicon suffix
46vocabulary through TWO predicates, which are NOT one another's
47singular and plural. _vocab.is_suffix_strict asks whether a single
48token is a post-nominal, initial veto included (the peel's scan-back
49and the surname site). _vocab.is_wholly_suffix asks C1's suffix
50test of a whole RUN -- the one `_comma.decide` and segment's C2 flag
51ask -- through the POLICY-selected
52token test plus period_joined_vocab, delimiter handling and the
53Ph./D. merge -- so the run predicate says yes both to tokens the
54token predicate VETOES ("V.", "V", "I") and to tokens it never sees
55as suffixes at all ("Msc.Ed.", "J.씨", which reach it through
56period_joined_vocab). The initial-shaped words are the class #319 was
57ABOUT, not the whole of the disagreement, and the extra routes listed
58above are where the rest of it comes from;
59test_is_wholly_suffix_is_not_the_plural_of_is_post_nominal pins the
60"V." half. The run predicate is how the peel declines a run that is
61not name text (#319), but only where the name's own run offers a
62site, since a glued honorific is itself part of what makes a run read
63as suffix-shaped; it owns two further Policy fields
64(lenient_comma_suffixes picks the strict or lenient token test -- it
65flips "田中さん, V." -- and extra_suffix_delimiters both counts a bare
66delimiter-core token as a suffix and splits a token on a core, the
67split being the half that flips "田中さん, Jr./V." under {"/"} and the
68bare core the half that flips "田中さん, /").
69
70Implements rules T9 (a slash for a title's full stop), T8 (a word glued at its full stop), W1 (the
71vocabulary/segmenter division), W2 (the glued-honorific peel), W6 (the
72glued-title peel), W3 (the
73writer's divisions are respected) and W5's division (a Han surname
74pair) of docs/design/rules/, cited at their code below; the decision
75chain (#308, #312, #319, the vetting bars, the measured
76spaced-honorific trade) is decisions/W1, #W2 and #W3, and T8's
77decisions/T8, and T9's decisions/T9. Every split makes sub-slices of one token, rewriting nothing, and
78T9's drop removes a token whole -- spans still index the original
79exactly, so the anti-#100 invariant holds by construction. The script splits also match on the token's CORE, its
80text.rstrip(FULL_STOPS) (#323) -- rstrip and never strip, because
81both offsets are measured from the text's START, so the core has to
82stay a prefix of the text for the offset the match yields to land
83where the match did. The peel runs before the script splits, so suffix classification
84can claim the tail and the surname match or segmenter consult sees
85the name rather than name-plus-honorific; its ASCII bail sits above
86every script split, T8's division alone running ahead of it, since
87it divides glued words in any cased script, ASCII ones included, so
88a caller-added LATIN tail
89fires only on a name carrying at least one non-ASCII character (see
90the bail's own comment, and honorific_tails' field note).
91"""
92from __future__ import annotations
93
94import functools
95import unicodedata
96from collections.abc import Callable, Sequence
97
98from nameparser._lexicon import FULL_STOPS, Lexicon, _normalize
99import nameparser._pipeline._comma as _comma
100from nameparser._pipeline._classify import classify
101from nameparser._pipeline._state import (
102 SURNAME_PAIR_TAG, ParseState, PendingAmbiguity, PendingReading,
103 Structure, WorkToken, copy_with,
104)
105from nameparser._pipeline._vocab import (
106 GLUED_SHAPE, dotted_title_end, effective_script, is_name_word,
107 glued_cuts, glued_saint_cut, title_prefixes,
108 is_initial_chunk, is_one_case,
109 period_joined_vocab,
110 is_suffix_strict, is_wholly_suffix, resolve_script_set,
111)
112from nameparser._pipeline._pieces import own_words
113from nameparser._policy import _EAST_ASIAN_SCRIPTS, Script
114from nameparser._types import (
115 AmbiguityKind, ReadingKind, ReadingSource, Role, Segmentation, Span,
116)
117
118#: Marks the tail token the peel below MANUFACTURED, so the segmenter's
119#: neighbour test can tell it from a token somebody wrote. Namespaced,
120#: therefore unstable provenance rather than API (_types.STABLE_TAGS is
121#: the whole stable set, and FOLDED_TAG is the precedent for a
122#: structural marker carrying this prefix); it is vocabulary-derived
123#: besides, since honorific_tails is what licensed the split. Emitter
124#: and reader are both in this module, so unlike FOLDED_TAG it needs no
125#: home in _types.
126_PEELED_TAG = "vocab:peeled-honorific"
127
128#: Segmenter answers scoring below this attach a SEGMENTATION report
129#: (amendment 2026-07-29 section 3): a statistical division carries one
130#: and a rule-based division, scored 1.0, none. The measurement that kept
131#: 0.9: decisions/W1 (#272). Not configurable.
132_SEGMENTER_CONFIDENCE_FLOOR = 0.9
133
134
135def _remap(run: tuple[int, ...], split_at: int,
136 added: int) -> tuple[int, ...]:
137 """One segment run after token `split_at` split into `added` + 1
138 pieces: the extra pieces join the run immediately after it, and
139 every later index shifts by as many."""
140 out: list[int] = []
141 for j in run:
142 if j == split_at:
143 out.extend(range(split_at, split_at + added + 1))
144 else:
145 out.append(j + added if j > split_at else j)
146 return tuple(out)
147
148
149def _pieces(text: str, splits: tuple[int, ...]) -> tuple[str, ...]:
150 """`text` cut at every offset in `splits`: n offsets, n+1 pieces."""
151 cuts = (0, *splits, len(text))
152 return tuple(text[a:b] for a, b in zip(cuts, cuts[1:]))
153
154
155def _split(state: ParseState, i: int, splits: tuple[int, ...],
156 detail: str | None, tail_tag: str | None = None) -> ParseState:
157 """Cut token `i` at every offset in `splits`, recording `detail` as
158 a SEGMENTATION report when there is one, and adding `tail_tag` to
159 the LAST piece when there is one of those.
160
161 The offsets arrive non-empty, ascending and interior whatever chose
162 them. From a segmenter: non-empty is the caller's own check,
163 strictly ascending with each >= 1 is Segmentation.__post_init__'s,
164 and the last offset is < len(text) -- checked by the caller. From
165 the vocabulary: the single offset is >= 1 and < len(text) by the
166 range(cap, 0, -1) construction and its len-1 cap. From T8's
167 division: `_vocab.glued_cuts` appends each offset after a matched
168 stop, so each is >= 2, ascending, and < len(text), a name following.
169 From T9's division: (slash,), (slash, slash + 1) or (1,), each
170 interior, a title before the slash and a slash or a name after it.
171
172 The ONE split path: the vocabulary hit is the single-offset case,
173 and the segmenter's answer and T8's division the general one, so
174 none can drift from the others' index arithmetic. `tail_tag` is part of keeping it
175 one path: the piece is tagged HERE, where it is built, rather than
176 by the caller, which would have to re-derive where its own tail
177 landed after handing the index arithmetic off. Only the peel passes
178 one, and the piece it wants is the last by construction -- the
179 honorific it cut off the end; the surname path passes nothing and
180 the default leaves it exactly as it was."""
181 token = state.tokens[i]
182 base = token.span.start
183 parts: list[WorkToken] = []
184 start = 0
185 for piece in _pieces(token.text, splits):
186 end = start + len(piece)
187 parts.append(copy_with(
188 token, text=piece, span=Span(base + start, base + end)))
189 start = end
190 if tail_tag is not None:
191 parts[-1] = copy_with(
192 parts[-1], tags=parts[-1].tags | {tail_tag})
193 added = len(splits)
194 tokens = state.tokens[:i] + tuple(parts) + state.tokens[i + 1:]
195 # Every index the earlier stages recorded is now stale past the
196 # split point: the segment runs group's own iteration rests on, and
197 # the ambiguities from extract_delimited (resolved to indices by
198 # tokenize) and segment. An ambiguity ON the split token keeps
199 # pointing at the head.
200 segments = tuple(_remap(run, i, added) for run in state.segments)
201 ambiguities = tuple(
202 copy_with(a, indices=tuple(
203 j + added if j > i else j for j in a.indices))
204 for a in state.ambiguities)
205 if detail is not None:
206 ambiguities += (PendingAmbiguity(
207 AmbiguityKind.SEGMENTATION, detail,
208 tuple(range(i, i + added + 1))),)
209 return copy_with(state, tokens=tokens, segments=segments,
210 ambiguities=ambiguities)
211
212
213@functools.lru_cache(maxsize=16)
214def _longest_entry(entries: frozenset[str]) -> int:
215 """The longest entry in a vocabulary, cached per-vocabulary rather
216 than recomputed per parse (Lexicon is frozen and slotted, so it
217 cannot carry a cached_property of its own). The frozenset is
218 hashable and a process holds only a handful of distinct
219 vocabularies -- the default one, plus one per constructed pack
220 parser -- so maxsize=16 bounds pathological many-lexicon churn
221 without ever evicting in normal use. Keyed by the frozenset VALUE,
222 not by (lexicon, field): the callers pass surnames,
223 honorific_tails and glued_titles, but every lexicon that leaves KOREAN_SURNAMES
224 alone shares one entry, so the count is distinct SETS rather than
225 lexicons times fields.
226
227 Callers must pass a NON-EMPTY vocabulary: max() of an empty set
228 raises, and every call site sits under a match guard that cannot
229 reach it with one."""
230 return max(map(len, entries))
231
232
233def _is_post_nominal(state: ParseState, i: int) -> bool:
234 """Whether token `i` is post-nominal VOCABULARY. Two of this
235 stage's decisions ask it and neither is about script: an honorific
236 is neither a surname SITE nor the token a glued honorific hangs off
237 (#308).
238
239 It answers a VOCABULARY question, not a positional one, and the two
240 callers do not spend the answer the same way. In TRAILING position
241 vocabulary and position agree, so the peel site steps over a True
242 and goes on scanning. In LEADING position they disagree -- 양 is
243 the family name there, whatever the suffix set says -- so the
244 surname site reads a True as an ANSWER and declines, rather than as
245 a token to step past.
246
247 STRICT, not lenient: the initial veto applies, so "V." is not a
248 post-nominal here though bare "v" is a suffix word. That agrees
249 with what classify does with the same token downstream -- "V." is
250 a middle initial -- and the difference is reachable under the
251 default lexicon: "田中さん V." stops its scan-back at the initial
252 and does not peel, while "田中さん II" steps over II and does. That
253 pair is the case table's ja_honorific_glued_before_an_initial and
254 ja_honorific_glued_before_a_roman_suffix, added because the clause
255 could NAME the discriminating input while swapping in
256 is_suffix_lenient still failed no test -- the shape a "unify the
257 two suffix predicates" refactor would have walked straight past.
258
259 Suffixes only, deliberately. Should a CJK entry ever join titles,
260 the surname site would want it excluded while the peel site must
261 not: a title never trails, so widening the peel's scan-back would
262 move it off the real last name token. Split the predicate then, not
263 before."""
264 # rules/T4, #727: a bare lowercase letter in a name written in one
265 # case is vetoed as its capital is; the case fact is asked only of
266 # such a letter, so a CJK honorific (no case) never asks it
267 text = state.tokens[i].text
268 return is_suffix_strict(text, state.lexicon,
269 len(text) == 1 and text.islower()
270 and _one_case(state))
271
272
273# rules/W2: "A part that is not name text — a post-nominal word
274# standing on its own — is never the name's end: the split-off steps
275# past it to the name word behind, and never dissects it." (history:
276# decisions/W2)
277# The scan-back below is that clause, and it needs no punctuation to
278# fire. '김민준 박사님' steps past 박사님 to 김민준, finds no listed
279# tail there and returns None -- so 박사님 is left whole for suffix
280# classification rather than cut into 박사 + 님, which is what the
281# same input gives when the step is removed. '선생님' is post-nominal
282# entire with no name word behind it, so the scan yields no site at
283# all and the token stays whole. Both are corpus names and
284# rules/W2 example lines; decisions/cjk-comma-demotion
285# carries the forced-predicate measurement behind them.
286def _peel_site(state: ParseState, flat: Sequence[int],
287 tails: frozenset[str]) -> tuple[int, int] | None:
288 """Where a peel would land in the token run `flat`: the index of the
289 token to cut and the OFFSET to cut it at (the listed tail, and any
290 full stops riding behind it, are what comes off the end), or None
291 where that run offers no peel.
292
293 Two callers, one answer, which is the point of naming it. The peel
294 itself asks it once, of the runs it decided to scan. The gate above
295 that decision asks it of segments[0] ALONE, to find out whether
296 declining the second run would cost the only site. Sharing the scan
297 with the peel rather than approximating it there is what makes the
298 gate's answer mean what it says: a gate that merely looked for a
299 token ENDING in a listed tail would count a token that is a tail
300 entire, which the scan-back skips as a site -- "선생님, J.씨" would
301 decline on a site the peel then cannot use, and lose the peel in
302 exactly the way the gate exists to prevent. (Only the lone-token
303 shape of that divergence is reachable from the gate, and the gate's
304 own other conjunct is what makes that so: SUFFIX_COMMA wants BOTH
305 a suffix-shaped second run and more than one word before the
306 comma, and the gate is asked only where the first of those is
307 already true -- so a run this call ever sees under FAMILY_COMMA
308 failed on the second, and segments[0] holds at most one token. The
309 word-count alone would not say that: "Dr 김민준, 지훈" has two
310 words before the comma and is FAMILY_COMMA.)
311
312 Callers must pass a NON-EMPTY `tails` -- _longest_entry's
313 precondition, which the stage's own early return supplies."""
314 i = next((j for j in reversed(flat)
315 if not _is_post_nominal(state, j)), None)
316 if i is None:
317 # nothing but post-nominals, or no tokens at all
318 return None
319 text = state.tokens[i].text
320 # The tail is matched on the token's core (#323): a stop glued after
321 # the honorific ('김민준씨.', '田中さん.') stands between the listed
322 # tail and the token's end and used to defeat the match. What the
323 # text read instead depended on the stop: the ASCII spelling went to
324 # a title downstream (H2's shape is ASCII-period-only), while a
325 # fullwidth or ideographic stop left the whole text a lone name word
326 # ('田中さん。' read given). The cut lands BEFORE the tail, so the
327 # stops ride with the honorific piece and the token text is never
328 # rewritten. TRAILING only: a leading stop is not between the name
329 # and its honorific, and the offset returned below is the core's
330 # length less the tail's, one subtraction.
331 core = text.rstrip(FULL_STOPS)
332 # range/cap construction identical to the surname match below, and
333 # for the same two reasons: longest-first, and a len-1 cap that
334 # makes the offset interior by construction (_split's contract). An
335 # empty or one-character core caps below 1 and the loop is empty.
336 cap = min(_longest_entry(tails), len(core) - 1)
337 for length in range(cap, 0, -1):
338 if core[-length:] in tails:
339 return i, len(core) - length
340 return None
341
342
343# rules/W2: "a listed honorific glued to the end of the name's
344# last name word splits off once and reads as a suffix." (history:
345# decisions/W2)
346# That the peel also reaches ACROSS a family comma is stated at
347# rules/W3 instead, which is a tolerated rule since the
348# 2026-09-01 comma demotion -- the crossing is what the parser does
349# today, not something W2 promises. W3 also carries the reading of a
350# period a listing leaves behind (decisions/cjk-comma-demotion,
351# amended by decisions/cjk-full-stops): a period on a SEPARATE
352# post-nominal word rides into the suffix and moves nothing ('様.'
353# is post-nominal-strict and the scan steps past it as it steps past
354# '様'), and since #323 a period glued to the honorific's OWN token
355# rides with the honorific too -- _peel_site matches the tail through
356# the trailing stop and cuts before it, so '田中さん.' divides where
357# '田中さん' does, and '김민준씨.' where '김민준씨' does (both are
358# case rows now; before 2026-09-10 they read as a title, measured
359# 2026-09-05 and pinned by nothing, and for one commit of the #323
360# branch the surname site read '김민준씨.' as 김 + 민준씨.). Neither
361# reading is a promise; the step past the post-nominal word itself
362# is W2's, above, and is.
363def _one_case(state: ParseState) -> bool:
364 """ParseState.one_case, asked here where no earlier stage did, as
365 classify asks it: segment records the fact only where C2's flag
366 asked for it (#613)."""
367 if state.one_case is not None:
368 return state.one_case
369 return is_one_case(own_words(state.tokens, state.comma_offsets,
370 state.lexicon._sets.maiden_markers)[0])
371
372
373def _postnominal_behind_a_whole_name(state: ParseState) -> bool:
374 """Whether the part after the comma is the postnominal part of a
375 whole name, so the part before it is a name and not a surname --
376 rules/C1's question, which group decides once the words are
377 tagged (#613). This stage runs first, so it asks THAT decision, on
378 the name as written: `_comma.decide` over a classified copy of the
379 state, which is the one implementation of the question. A hand copy
380 asked the vocabulary here until #613's /simplify pass, and was
381 patched four times in review for drifting from decide (the ambiguous
382 class's count, the numeral refusal, a suffix before the comma, the
383 split 'Ph. D.'), each drift dividing a name decide then read as a
384 family comma, or leaving whole one it read as a suffix comma.
385
386 The copy costs a classify pass and a decision, so the callers ask
387 only where the answer can change something: the peel once it has
388 found a site, the division once there is a token it could divide
389 (Latin and accented-Latin comma names never pay it)."""
390 return (_comma.decide(classify(state)).structure
391 is Structure.SUFFIX_COMMA)
392
393
394def _peel_honorific_tail(state: ParseState,
395 postnominal: Callable[[], bool]) -> ParseState:
396 """#308: split a listed honorific off the END of the name's last
397 NON-POST-NOMINAL token -- 田中さん -> 田中 + さん -- and let
398 the existing machinery do the rest. Suffix classification claims
399 the tail downstream (every honorific_tails entry is a suffix word
400 too, enforced by Lexicon), and the segmentation half below then
401 sees the remainder rather than the glued whole, so 김민준씨 splits
402 김 + 민준 and a configured segmenter is handed 山田太郎 rather
403 than 山田太郎様.
404
405 Scanning back over post-nominals rather than taking the last token
406 outright does three things at once. An unrelated trailing suffix
407 cannot hide the peel site, so "김민준씨 Jr." answers as the
408 comma-written "Dr 김민준씨, Jr." does -- one name, two spellings,
409 one parse. A token that IS a tail (씨, さん, and the nested 선생님,
410 which the cap alone would peel to 선생 + 님) is skipped as a site
411 and stays whole: every tail is a suffix word by the Lexicon
412 invariant, which is what makes that guard hold, and the cap below
413 only keeps the offset interior for _split. And the scan answers
414 None rather than indexing anything, which two reachable inputs
415 need: a name that is nothing but post-nominals ("씨"), and one
416 whose name runs are empty (", , 씨" scopes to two empty ones).
417 Nothing here rests on a structural gate landing first, then, which
418 is what let #312 move both of the stage's gates below it.
419
420 WHICH tokens are scanned is a separate decision, and the one a
421 reader is likeliest to undo: the NAME's segment runs, flattened,
422 and never state.tokens or every segment. The alternatives agree
423 except where extract_delimited has already claimed a token or a
424 comma has closed the name, both of which this stage can still see
425 -- so "김민준씨 (Jimmy)" and "Dr 김민준씨, V." are the inputs that
426 tell the three apart. See the note at the scan itself.
427
428 That last token is the last of the NAME, which reaches into a
429 maiden clause: maiden tokens are still main-stream here
430 (extract_delimited has masked only bracketed content), so
431 "김민준 née 박씨" peels 씨 off the MAIDEN name 박씨 and hands it to
432 the person's suffix list -- "née Ms. Park". Intended rather than
433 incidental in that direction: the honorific is the reader's
434 regardless of which of her names it was glued to, and a
435 name-final honorific is exactly what this peels. Since #312 that
436 reach extends to FAMILY_COMMA along with the rest of the crossing
437 -- "김, 민준 née 박씨" now routes 씨 to suffix, where before #312
438 the stage returned at the family-comma gate above the peel and
439 left it in maiden "박씨".
440
441 The other direction is a LIMIT, stated rather than fixed: a maiden
442 clause pushes the site off the person's own name, so "김민준씨 née
443 박" does NOT peel and gives given "민준씨" -- the original bug,
444 intact behind a marker. "김민준씨 née 박씨" shows both at once, two
445 identical honorifics of which only the maiden's is routed. Chasing
446 the marker into the site scan is scope creep for an uncommon input,
447 and it could not be done here anyway: classify has not run, so the
448 marker tokens carry no tag this stage could read.
449
450 Longest-first, and ONE peel: a remainder that itself ends in a
451 listed tail is accepted rather than chased. No SHIPPED input
452 witnesses that any more -- 박사님 was the last one, and adding it
453 is what removed the case: 김민준박사님 now gives up 박사님 entire,
454 since longest-first reaches the whole honorific. The pin needs a
455 tail whose remainder ends in a DIFFERENT tail, the two not
456 themselves a listed entry, and no pair in the shipped vocabulary
457 has that shape; the stage test test_one_peel_never_a_stack carries
458 it on a synthetic lexicon, which is now its only witness. No
459 script precondition on the remainder either, since the tail alone
460 is the license: Andersonさん peels.
461
462 Emits no ambiguity, unlike the surname fork below, though
463 longest-first does CHOOSE here too -- 김선생님 gives 선생님 where
464 님 also matches. The difference is what the runner-up is: a second
465 matching surname is a competing READING of the name, which a
466 caller may prefer, while a shorter tail leaves a remainder that is
467 not a name at all (김선생), so there is nothing to adjudicate."""
468 tails = state.lexicon._sets.honorific_tails
469 if not tails:
470 return state
471 # The NAME's runs: more than segments[0], never every segment. A
472 # FAMILY comma splits the name across two runs and the honorific
473 # glues to either side (#312); every other structure keeps the
474 # name whole in segments[0], a trailing post-nominal under
475 # NO_COMMA included, which the scan-back steps over. Flattening
476 # SEGMENTS rather than state.tokens keeps the site off extracted
477 # nickname and maiden content.
478 #
479 # rules/W3: "A part that is nothing but suffix words is not the
480 # name's end: it is declined as the site, and the split-off falls
481 # back to the part before the comma and takes the honorific there,
482 # provided that part offers a site of its own."
483 # The structure does not say whether segments[1] is name text, so
484 # the run predicate is asked (`is_wholly_suffix`, not the plural of
485 # `_is_post_nominal`, which vetoes an initial-shaped 'V.' and never
486 # sees period_joined_vocab's 'J.씨'), with the case fact and policy
487 # `_comma.decide` reads it with; an empty run is in
488 # scope and adds no site. The second condition is there because
489 # the predicate is circular at this site alone: a glued honorific
490 # is itself suffix evidence. decisions/W2 (#319).
491 site = _peel_site(state, state.segments[0], tails)
492 if state.structure is Structure.FAMILY_COMMA:
493 # Under a family comma both runs may be scanned. The comma's
494 # decision is asked only where it can matter -- where scanning
495 # one run and scanning both find different sites (#613's
496 # /simplify: it is a classify pass and a decision)
497 both = _peel_site(state, [j for seg in state.segments[:2]
498 for j in seg], tails)
499 if both != site and not postnominal():
500 second = [state.tokens[j].text for j in state.segments[1]]
501 # `one_case` is passed for the reason the field exists: the
502 # credential lean is part of what "wholly suffix" MEANS since
503 # #289, and a stage that asks the question without it gets a
504 # different answer from `_comma.decide`, which reads the same
505 # run with the fact in hand at group's head. Left out, 'Kim김민준씨, MA' read
506 # 'MA' as name material, declined nothing, and scanned the
507 # second run -- where the site is 'MA' itself, which carries no
508 # listed tail -- so the person's own 씨 went unpeeled (family
509 # 'Kim김민준씨') while 'Kim김민준씨, PhD' peeled it, one name in
510 # two spellings parsed two ways (review round, #289/#516).
511 # `segment` records the fact only where C2's flag asks for it,
512 # so `_one_case` asks it here for every other name (#613).
513 # the site test first: it is the cheaper half, and false
514 # for every name whose part before the comma holds no glued
515 # honorific, which spares those the case fact
516 # one fact, asked for the lean and for the strict test's
517 # initial veto alike (rules/T4, #727)
518 if not (site is not None
519 and is_wholly_suffix(second, state.lexicon,
520 state.policy,
521 one_case=(case := _one_case(state)),
522 letters_one_case=case)):
523 site = both
524 if site is None:
525 return state
526 i, offset = site
527 # The tail carries a tag because this stage MANUFACTURED it. The
528 # segmenter's neighbour test below needs to tell it from a token
529 # somebody wrote, and no vocabulary question can: the two spellings
530 # put the same word in the same place, and only the provenance
531 # differs.
532 return _split(state, i, (offset,), None, tail_tag=_PEELED_TAG)
533
534
535#: The Thai vowels written after their consonant (U+0E30 to U+0E3A,
536#: U+0E45), which no word opens with: where one follows a title, the
537#: title's last letters belong to the word, so the peel falls back to a
538#: shorter title ('นางสาวิตรี' is นาง + สาวิตรี) or keeps the word whole
539#: ('นางิ', Nagi; 'นางาเซะ', Nagase), as it does behind a combining mark.
540_AFTER_A_CONSONANT = frozenset(map(chr, (*range(0x0E30, 0x0E3B), 0x0E45)))
541
542
543def _head_sites(state: ParseState) -> list[int]:
544 """The tokens a glued title may open: the first word of the name and,
545 after a family comma, the first word of the given part, each past
546 any listed title written apart in front of it, alone or joined at its
547 full stops ('รองศาสตราจารย์ นายแพทย์สมชาย', 'รศ.ดร. นายสมชาย')."""
548 titles = state.lexicon._sets.titles
549 runs = (state.segments[:2] if state.structure is Structure.FAMILY_COMMA
550 else state.segments[:1])
551 sites = []
552 for run in runs:
553 j = next((j for j in run
554 if not _all_titles(state.tokens[j].text, titles)), None)
555 if j is not None:
556 sites.append(j)
557 return sites
558
559
560def _all_titles(text: str, titles: frozenset[str]) -> bool:
561 """Whether `text` is a listed title, whole or chunk by chunk between
562 its full stops ('รองศาสตราจารย์', 'พ.อ.หญิง', 'รศ.ดร.'): a title
563 written apart, which the site walk passes over; a word holding a
564 name ('ดร.สมชาย') is a site, never passed over."""
565 n = _normalize(text)
566 if n in titles:
567 return True
568 chunks = [c for c in n.split(".") if c]
569 return bool(chunks) and all(c in titles for c in chunks)
570
571
572# rules/W6: "a title the vocabulary marks to peel, glued to the start of
573# the name's first word, splits off once and reads as a title" (history:
574# decisions/W6 (#317))
575def _peel_title_head(state: ParseState) -> ParseState:
576 """#317: split a listed title off the START of the name's first word
577 -- นายสมชาย -> นาย + สมชาย -- the mirror of `_peel_honorific_tail`,
578 licensed the same way: only a title written `attached` peels
579 (`Lexicon.glued_titles`), the vocabulary carrying its own license.
580 Longest first, ONE peel, and never off a word the vocabulary lists
581 whole (`นายแพทย์`, which opens with `นาย`), nor where what is left
582 opens with no letter, a Thai vowel written after its consonant
583 (`_AFTER_A_CONSONANT`) taking the next shorter title instead. The head
584 piece needs no tag: classify reads it as the listed title it is.
585
586 T8's division ran on the word whole, before this peel, and found no
587 chunk at its head (`อาจารย์ดร.สมชาย`), so a remainder still glued at
588 a full stop (`ดร.สมชาย`) is divided here, as T8 divides the same
589 word written apart; behind a family comma it stays whole, as T8
590 leaves every word after a comma."""
591 sets = state.lexicon._sets
592 divide = False
593 for i in reversed(_head_sites(state)):
594 text = state.tokens[i].text
595 low = text.lower()
596 if len(low) != len(text):
597 # a letter lowered into two: the offsets of `low` would not
598 # be the text's
599 continue
600 cut, w = _peel_cut(low, state)
601 if not cut:
602 continue
603 divide = divide or bool(state.segments and i in state.segments[0]
604 and GLUED_SHAPE.search(text, cut))
605 state = _split(state, i, (cut,), None)
606 if w in sets.title_modifiers:
607 # a title only in a phrase peeled with its head behind it:
608 # the head peels too, as written apart ('ว่าที่จ่าสิบตรีสมชาย',
609 # 'ใจดี, ว่าที่ร.ท.วินัย')
610 second, _ = _peel_cut(low[cut:], state)
611 if second:
612 state = _split(state, i + 1, (second,), None)
613 return _divide_glued(state) if divide else state
614
615
616def _peel_cut(low: str, state: ParseState) -> tuple[int, str]:
617 """Where rules/W6's peel cuts the lower-cased word `low`, and the
618 title it takes, or (0, '').
619
620 Longest first; a title that would leave a Thai vowel or a mark at
621 the opening falls back to the next shorter one ('นางสาวิตรี' is นาง +
622 สาวิตรี), while one followed by anything else that opens no word peels
623 nothing: a hyphen, a digit, the repetition mark ('นางสาว-สุดา',
624 'นางสาวๆ')."""
625 sets = state.lexicon._sets
626 heads = sets.glued_titles
627 # longest first, capped so a word is never peeled whole, as the
628 # tail peel and the surname match read
629 for end in range(min(_longest_entry(heads), len(low) - 1), 0, -1):
630 w = low[:end]
631 if w not in heads:
632 continue
633 if "." in w:
634 # a title written short ends where T8 reads it end: past its
635 # own stop, or behind a last chunk of two or more letters
636 # (#1319: 'พล.ต.ต.สุรศักดิ์', 'พ.อ.หญิงวาสนา', never 'พ.ต.อ'
637 # in 'พ.ต.อนุชา')
638 e = dotted_title_end(low, 0, (w,))
639 if e is None or e >= len(low):
640 continue
641 end = e
642 elif low[end] == "." and end + 1 < len(low):
643 end += 1
644 if w in sets.title_modifiers and not low.startswith(
645 title_prefixes(sets.titles), end):
646 # a title only in a phrase (rules/H9) peels only with a
647 # listed title behind it ('ว่าที่ร.ท.วินัย', 'ว่าที่ดร.สมชาย')
648 continue
649 nxt = low[end]
650 if nxt in _AFTER_A_CONSONANT or unicodedata.category(nxt) == "Mn":
651 continue
652 return (end, w) if nxt.isalpha() and nxt != "\u0e46" else (0, "")
653 return 0, ""
654
655
656def _split_candidate(state: ParseState) -> int | None:
657 """The token `_split_surname_site` would try to divide, or None:
658 asked on its own so a caller can learn cheaply that there is
659 nothing to divide before asking anything costlier (#613's
660 /simplify)."""
661 scripts = state.policy.segment_scripts
662 # an empty VOCABULARY deliberately does not bail here -- see below
663 if not scripts:
664 return None
665 # segments[0] is the NAME part under both remaining structures
666 # (everything, under NO_COMMA); later segments are suffixes. Its
667 # members are main-stream token indices by construction, so
668 # extracted nickname/maiden content is unreachable from here. For
669 # this site that is merely tidy -- the first script-written token
670 # is the same either way. It is the PEEL above that reads this run
671 # load-bearingly, and in the two structures that reach here it
672 # reads exactly this one, only backwards; the argument lives at
673 # that scan.
674 # a Cyrillic word is no site, CYRILLIC keying a declared order alone
675 # (#1237), so a segmenter is never handed one
676 i = next((i for i in state.segments[0]
677 if (script := effective_script(state.tokens[i].text)) in scripts
678 and script is not Script.CYRILLIC), None)
679 # A post-nominal in the surname's own position is not a site to
680 # skip past but an answer: a surname LEADS, so if the leading
681 # script-written token is an honorific there is no surname here to
682 # find. Scanning ON would reach the given name, which is exactly
683 # what the first-token rule exists to prevent -- 지 is a listed
684 # surname, so "양 지훈" (양 is a surname AND a shipped honorific)
685 # would have its own given name split in half. Declining also
686 # covers the token the peel above manufactures, which is the first
687 # and only script-written one in "Anderson선생님".
688 if i is None or _is_post_nominal(state, i):
689 return None
690 # A token that IS a surname never splits: a bare "남궁" must not
691 # become 남 + 궁 just because the single-syllable surname also
692 # matches -- there is nothing to split off, and a lone token's
693 # role is the order resolution's call, stop or no stop. Asked here,
694 # with the core the split reads (#323), so the comma gate in front
695 # learns it before asking the comma's decision (#613's /simplify)
696 if state.tokens[i].text.rstrip(FULL_STOPS) in state.lexicon._sets.surnames:
697 return None
698 return i
699
700
701def _surname_pair(state: ParseState, i: int, core: str,
702 surnames: frozenset[str]) -> tuple[int, ...] | None:
703 """rules/W5: "whose first two are each a listed single surname" --
704 the offsets at which `_split` divides token `i` into its two
705 surnames and, written undivided, the given name behind them: (1, 2)
706 for four characters, (1,) for two with the given name after the
707 space; or None where it holds no second single surname the family
708 can take, by the length, script and order tests below (#845). Token
709 `i`'s longest listed surname is its first character, so no listed
710 compound opens it.
711
712 Four characters written undivided, or two with a word of two
713 written after the space: a Han given name is nearly always one or
714 two characters, and a three-character name is nearly always a
715 single surname before a two-character given name (李林伟, and
716 `李林 伟` written with a stray space), the reason no married pair is
717 listed as a compound.
718
719 Only where the name will be read family-first, since only there is
720 the first surname the family for the second to join: every word of
721 the name segment but the post-nominals ending it written in the
722 scripts assign's order resolution keys (rules/W4), resolving to an
723 entry, or failing one, to a declared order, that puts the family
724 first -- the resolution assign makes over its name pieces, asked of
725 the words before titles are known. A word in another
726 script, a Latin title included, keeps W1's division, which reads
727 the same under any order, so the stage never cuts a name the order
728 then reads otherwise. History: decisions/W5 (#845)."""
729 # the length tests first: they are C-level, and refuse a
730 # three-character token, the usual single surname and given name,
731 # before the script walk below
732 if core[1] not in surnames or len(core) not in (2, 4):
733 return None
734 run = state.segments[0]
735 at = run.index(i)
736 if len(core) == 2 and (
737 at + 1 == len(run)
738 or len(state.tokens[run[at + 1]].text.rstrip(FULL_STOPS)) != 2):
739 return None
740 # post-nominals ending the name, a peeled honorific among them, are
741 # no name pieces of assign's, so they key no order (王李小明さん,
742 # 王李小明 PhD); anything before them does
743 end = len(run)
744 while (end > at + 1
745 and (_PEELED_TAG in state.tokens[run[end - 1]].tags
746 or _is_post_nominal(state, run[end - 1]))):
747 end -= 1
748 found: set[Script] = set()
749 for j in run[:end]:
750 script = effective_script(state.tokens[j].text)
751 if script is None:
752 return None
753 found.add(script)
754 if resolve_script_set(found) is not Script.HAN:
755 return None
756 order = next((o for s, o in state.policy.script_orders
757 if s is Script.HAN), state.policy.name_order)
758 if order[0] is Role.GIVEN:
759 return None
760 if len(core) == 4:
761 return (1, 2)
762 return None if _is_post_nominal(state, run[at + 1]) else (1,)
763
764
765def _split_surname_pair(state: ParseState, i: int,
766 splits: tuple[int, ...]) -> ParseState:
767 """Token `i` divided at `_surname_pair`'s cuts into its two surnames
768 and, unspaced, the given name behind them, the second surname
769 tagged for post_rules to read as the family's second unit. No
770 report here: whether the pair is read is post_rules' decision,
771 under the order the name is read in, so it reports there
772 (mechanisms.md#AMBIGUITY-AT-THE-DECISION-SITE)."""
773 state = _split(state, i, splits, None)
774 second = state.tokens[i + 1]
775 tokens = list(state.tokens)
776 tokens[i + 1] = copy_with(second, tags=second.tags | {SURNAME_PAIR_TAG})
777 return copy_with(state, tokens=tuple(tokens))
778
779
780def _split_surname_site(state: ParseState) -> ParseState:
781 """The stage's other split: the first activated-script token of the
782 name part is matched longest-first against Lexicon.surnames, and a
783 hit splits it in two; where the vocabulary declines, an optional
784 Parser(segmenter=...) is consulted instead.
785
786 A sibling of _peel_honorific_tail rather than a continuation of it.
787 The two answer different questions -- this one asks where a name
788 divides into surname and given, the peel asks whether a token ends
789 in a word that can never end a name -- which is why they carry
790 different gates: the FAMILY comma and the 间隔号 gate this half
791 alone (#312), and segment_scripts below gates it alone too. That
792 is also why the stage entry below interleaves gates with its two
793 calls rather than running one cascade."""
794 i = _split_candidate(state)
795 if i is None:
796 return state
797 token = state.tokens[i]
798 text = token.text
799 surnames = state.lexicon._sets.surnames
800 # The vocabulary match reads the token's CORE (#323). Without it
801 # the stop WAS the remainder: '김.' matched its own head and became
802 # 김 + '.'; the stop rides with the remainder instead, so '김민준.'
803 # divides as 김 + '민준.'. A leading stop never reaches THIS site --
804 # the classification fold in front rstrips too
805 # (_vocab._normalized_for_script) and hides such a token before it
806 # arrives -- while the peel above has no such gate in front of it
807 # and its own rstrip is what does the work there.
808 core = text.rstrip(FULL_STOPS)
809 # Longest-first (compound-before-single falls out of it), capped
810 # so the remainder is never empty. Direct membership, no
811 # _normalize: the script gate admits only CJK text, and a CJK
812 # entry's stored form is its NFC composition with no case or
813 # edge-stop change (#322) -- so an entry AUTHORED in NFD is
814 # composed on the way in, raw NFD input matches nothing here, and
815 # the name goes unsplit, the no-split NFD degradation that
816 # decisions/W1's 2026-07-29 NFD bullet (ja amendment 1a) accepts. An empty vocabulary skips the match rather
817 # than bailing the stage (_longest_entry's max() has nothing to
818 # take): a surname-less lexicon declines every token, which is
819 # exactly the condition the segmenter is consulted on, so an early
820 # bail would make a configured segmenter silently inert under
821 # Lexicon.empty() -- the JA pack's own shape.
822 matches: list[int] = []
823 if surnames:
824 cap = min(_longest_entry(surnames), len(core) - 1)
825 matches = [length for length in range(cap, 0, -1)
826 if core[:length] in surnames]
827 if matches:
828 take = matches[0]
829 if take == 1:
830 pair = _surname_pair(state, i, core, surnames)
831 if pair is not None:
832 return _split_surname_pair(state, i, pair)
833 detail = None
834 if len(matches) > 1:
835 # more than one vocabulary-supported split: longest-first
836 # DECIDED a fork, and the deciding stage records it. A
837 # single-match split chose nothing, so it stays silent --
838 # a dictionary certainty and the statistical guess below
839 # are different epistemic states, and these two emission
840 # rules say so.
841 chosen = " + ".join(map(repr, _pieces(text, (take,))))
842 other = " + ".join(map(repr, _pieces(text, (matches[1],))))
843 detail = (f"{text!r} splits as {chosen} on the longest "
844 f"surname; {other} also reads")
845 return _split(state, i, (take,), detail)
846 if state.segmenter is None:
847 return state # the first activated-script token decides
848 # rules/W1: "is consulted only for a name whose written form is
849 # wholly undivided, a spaced honorific counting as a written
850 # division" -- the segmenter's precondition: a second token of the
851 # name part written in an East Asian script, activated or not, is a
852 # division its writer drew ('山田太郎 マイケル' under JA declines;
853 # '山田 太郎' must not have its family divided again, and
854 # namedivider scores a two-character answer 1.0, so no confidence
855 # check would catch it). A Latin title or suffix is no such division,
856 # nor a Cyrillic word, whose script keys only a declared order; nor
857 # the honorific this stage peeled, a boundary nobody wrote, told by
858 # provenance (_PEELED_TAG) since the suffix set cannot separate it
859 # from a spaced one (decisions/W3, decisions/W4 (#1237))
860 if any(j != i and effective_script(state.tokens[j].text)
861 in _EAST_ASIAN_SCRIPTS
862 and _PEELED_TAG not in state.tokens[j].tags
863 for j in state.segments[0]):
864 return state
865 # No try/except around the call: rules/A1's Accepted clause
866 # ("a user-supplied segmenter's own error, which propagates"). The
867 # two checks below are that same doctrine, curated, and they are
868 # where the line this module draws is easiest to state:
869 # a PROTOCOL VIOLATION BY THE SEGMENTER AUTHOR RAISES, while an
870 # ADAPTER'S DEFENSE AGAINST ITS LIBRARY DECLINES. Both checks here
871 # are the first kind -- a wrong answer TYPE and an answer indexing
872 # past the token it was handed are stage-detectable bugs in
873 # user-supplied code, inside the declared totality exception, so
874 # they get the same treatment the callable's own exceptions get.
875 # locales/ja.py is the second kind: its repertoire, length,
876 # reconstruction and score guards all return None, because what
877 # they defend against is namedivider answering a question nobody
878 # asked it, which is a fact about the CONTENT, not a broken
879 # protocol. Bounded like every message here: the type's NAME, never
880 # its contents.
881 # The CORE, not the raw token (#323): handed the raw token, a
882 # segmenter answering len-1 would make the stop a piece of its own
883 # ('田中太郎' + '。'), where against the core the trailing stops
884 # ride with the last piece -- '山田太郎.' answered at 2 divides as
885 # 山田 + '太郎.'.
886 answer = state.segmenter(core)
887 if answer is not None and not isinstance(answer, Segmentation):
888 # a duck-typed answer carrying a .splits of its own would
889 # otherwise wander into the split path and surface as a
890 # ValueError naming Token, pointing the reader at nameparser's
891 # insides instead of at their segmenter
892 raise TypeError(
893 f"segmenter must return Segmentation or None, got "
894 f"{type(answer).__name__}")
895 if answer is None or not answer.splits:
896 return state # declined, or confidently one token
897 # splits[-1] is the max -- Segmentation enforced ascending. The
898 # upper bound is the half Segmentation cannot check, since it never
899 # sees the text; an offset at or past the end would make an empty
900 # piece. Declining silently here (as this did before the review)
901 # made an off-by-one segmenter undebuggable: every answer it gave
902 # vanished, and the parse merely looked unsegmented.
903 # The bound is the CORE's length, the string the segmenter was
904 # actually handed: an offset it could not have derived from its own
905 # input is the same author bug whether or not `text` is longer.
906 if answer.splits[-1] >= len(core):
907 raise ValueError(
908 f"segmenter returned splits beyond the token: last offset "
909 f"{answer.splits[-1]}, the segmenter was given "
910 f"{len(core)} characters")
911 conf = answer.confidence
912 detail = None
913 if conf is not None and conf < _SEGMENTER_CONFIDENCE_FLOOR:
914 reading = " + ".join(map(repr, _pieces(text, answer.splits)))
915 detail = (f"{text!r} splits as {reading} on a segmenter answer "
916 f"scoring {conf:.2f}, under the "
917 f"{_SEGMENTER_CONFIDENCE_FLOOR} confidence floor")
918 return _split(state, i, answer.splits, detail)
919
920
921def _drop(state: ParseState, i: int) -> ParseState:
922 """Token `i` removed, a slash T9 reads as a separator: every later
923 index shifts down by one, in the segment runs and the reports
924 alike, as `_split` shifts them up."""
925 tokens = state.tokens[:i] + state.tokens[i + 1:]
926 segments = tuple(tuple(j - 1 if j > i else j for j in run if j != i)
927 for run in state.segments)
928 ambiguities = tuple(
929 copy_with(a, indices=tuple(
930 j - 1 if j > i else j for j in a.indices if j != i))
931 for a in state.ambiguities)
932 return copy_with(state, tokens=tokens, segments=segments,
933 ambiguities=ambiguities)
934
935
936def _slash_title(text: str, lexicon: Lexicon) -> bool:
937 """Whether `text` is a listed title T9 reads before a slash: one no
938 suffix reading claims and no saint particle, since a title/suffix
939 dual joined by a slash is a credential as often (`CPO/L`,
940 `MS/CCRP`)."""
941 word = _normalize(text)
942 sets = lexicon._sets
943 return (word in sets.titles and word not in sets.suffix_acronyms
944 and word not in sets.suffix_words
945 and word not in sets.saint_particles)
946
947
948def _slash_name(text: str, lexicon: Lexicon) -> bool:
949 """Whether `text`, written after a title's slash, is a name word
950 T9 divides at the slash: one name word in T8's shape (no delimiter,
951 digit or slash) once its full stops are set aside, so an initial or
952 a name written short reads as after the title's full stop (`J.`,
953 `Wm.`), which no title, title modifier or suffix reading claims
954 outright (`Dr/Mrs`, `Dr/MD`, `Dr/M.D.` keep their one word). A
955 title or suffix that is also a given name (`Dean`, `Ed`, `Junior`)
956 is read as it is after the title's full stop, and so is a given name
957 written short that is also a credential where it is not written in
958 capitals (`Md.`, rules/H2's yield), `MD` being the credential."""
959 if text.startswith(".") or not is_name_word(text.replace(".", "")):
960 return False
961 word = _normalize(text)
962 sets = lexicon._sets
963 if word in sets.given_name_abbreviations and not text.isupper():
964 return True
965 # the acronyms both as stored and without their stops: a caller's
966 # acronym may be stored with them ('q.z'), the shipped ones never
967 return not (word in sets.titles or word in sets.title_modifiers
968 or (word in sets.suffix_words
969 and word not in sets.suffix_words_ambiguous)
970 or (word in sets.suffix_acronyms
971 and word not in sets.suffix_acronyms_ambiguous)
972 or (word.replace(".", "") in sets.suffix_acronyms
973 and word.replace(".", "")
974 not in sets.suffix_acronyms_ambiguous))
975
976
977# rules/T9: "the slash reads as the title's full stop would, a
978# separator" -- the word opening the name, or the given part after a
979# family comma, and only there (decisions/T9 (#1149))
980def _divide_title_slash(state: ParseState) -> ParseState:
981 """The slash after a listed title opening the name, or the given
982 part after a family comma, cut off and dropped. Group decides the
983 comma later, so a comma is asked its decision here, and only where
984 a head is a site, the decision costing a classify pass: a part
985 after it read as post-nominals leaves the name whole before it,
986 where the head is read, and a family comma leaves the part before
987 it a surname, where a slash joins two (`JURIST/KANJO,
988 DAVID/KATHRYN`), so only the given part after it is read."""
989 plan = _slash_plan(state, 0)
990 if state.structure is Structure.FAMILY_COMMA:
991 given = _slash_plan(state, 1)
992 if plan is None and given is None:
993 return state
994 if not _postnominal_behind_a_whole_name(state):
995 plan = given
996 if plan is None:
997 return state
998 split_at, splits, slash = plan
999 if split_at is not None:
1000 state = _split(state, split_at, splits, None)
1001 return _drop(state, slash)
1002
1003
1004def _slash_plan(state: ParseState, site: int
1005 ) -> tuple[int | None, tuple[int, ...], int] | None:
1006 """T9's cut at the head of segment `site`, in each of the slash's
1007 four writings (`X/`, `X/word`, `X / word` and `X /word`): the token
1008 to split and where (None where the slash stands alone), and the
1009 index the slash's token then holds. None where the head is no
1010 site."""
1011 if len(state.segments) <= site or not state.segments[site]:
1012 return None
1013 run = state.segments[site]
1014 lexicon = state.lexicon
1015 tokens = state.tokens
1016 i = run[0]
1017 text = tokens[i].text
1018 # the last slash, so a title listed with one of its own ('mag/judge')
1019 # is X whole; the name after it holds none
1020 slash = text.rfind("/")
1021 if slash > 0 and _slash_title(text[:slash], lexicon): # glued to X
1022 rest = text[slash + 1:]
1023 name = rest or (tokens[run[1]].text if len(run) > 1 else "")
1024 if name and _slash_name(name, lexicon):
1025 # `X/word` or `X/ word`
1026 return i, ((slash, slash + 1) if rest else (slash,)), i + 1
1027 # a word refused there may be a title listed with its slash
1028 # ('mag/judge'), read as X whole before a spaced slash
1029 if len(run) < 2 or not _slash_title(text, lexicon):
1030 return None
1031 nxt = tokens[run[1]].text # the slash spaced from X
1032 if nxt == "/": # `X / word`
1033 if len(run) < 3 or not _slash_name(tokens[run[2]].text, lexicon):
1034 return None
1035 return None, (), run[1]
1036 if nxt.startswith("/") and _slash_name(nxt[1:], lexicon):
1037 return run[1], (1,), run[1] # `X /word`
1038 return None
1039
1040
1041# rules/T8: "the word reads as it does with a space there" -- the part
1042# before any comma, where the division acts (decisions/T8 (#1230, #1235))
1043def _divide_glued(state: ParseState) -> ParseState:
1044 """Every word of the part before the first comma divided where
1045 `_vocab.glued_cuts` finds a chunk read alone meeting a name, last
1046 word first, so the indices still to visit do not move."""
1047 head = state.segments[0]
1048 lexicon = state.lexicon
1049 # the words as written, before any of them divides: the report reads
1050 # the words after its own, which may have divided already
1051 texts = [state.tokens[j].text for j in head]
1052 for k in range(len(head) - 1, -1, -1):
1053 i = head[k]
1054 text = texts[k]
1055 # a C-level test first, so a word with no stop pays no frame
1056 if GLUED_SHAPE.search(text) is None:
1057 continue
1058 cuts = glued_cuts(text, lexicon)
1059 if not cuts:
1060 # rules/T8: "a saint particle glued to a name is one name
1061 # word" -- save as the last name word of the part behind
1062 # another, where it divides and the particle opens the
1063 # surname as written apart (rules/P10, 'Juan dela Cruz
1064 # Sta.Maria'; decisions/T8 (#1071))
1065 saint = glued_saint_cut(text, lexicon)
1066 if (saint is not None
1067 and _a_name_before(texts[:k], state)
1068 and _only_post_nominals(texts[k + 1:], state)
1069 and _ends_with_the_family(state)):
1070 state = _split(state, i, (saint,), None)
1071 continue
1072 state = _split(state, i, cuts, None)
1073 if _ends_the_name(cuts, texts, k, state):
1074 # initials glued to the word ending the name, behind a word
1075 # to spare: S3 would have read the whole as a credential by
1076 # its shape, and the reading not taken is still that one
1077 # ('John Smith B.Eng', 'Ahmed Ali M.Hassan', 'John Smith
1078 # A.Brown PhD')
1079 state = copy_with(state, ambiguities=(
1080 *state.ambiguities, PendingAmbiguity(
1081 AmbiguityKind.SUFFIX_OR_NAME,
1082 f"{text!r} ending the name may be a credential "
1083 f"written short; read as ",
1084 (i + len(cuts),), field_tail="",
1085 alternative=PendingReading(
1086 ReadingKind.CREDENTIAL, ReadingSource.SHAPE,
1087 Role.SUFFIX))))
1088 return state
1089
1090
1091def _only_post_nominals(texts: Sequence[str], state: ParseState) -> bool:
1092 """Whether every word in `texts` is suffix vocabulary, an acronym
1093 looked up without its stops ('Ph.D.' as 'phd'), up to a maiden
1094 marker, whose clause holds no word of the name ('Juan dela Cruz
1095 Sta.Maria née Jones'): what may follow the last name word of a
1096 part."""
1097 sets = state.lexicon._sets
1098 for j, later in enumerate(texts):
1099 n = _normalize(later)
1100 # a marker of one word or two ('née', 'z domu'), with a word after
1101 # it: a marker ending the text is no clause ('John Smith Sta.Ana
1102 # née' reads 'née' as a name word)
1103 if (n in sets.maiden_markers and j + 1 < len(texts)) or (
1104 j + 2 < len(texts) and f"{n} {_normalize(texts[j + 1])}"
1105 in sets.maiden_markers):
1106 return True
1107 if (n not in sets.suffix_words
1108 and n.replace(".", "") not in sets.suffix_acronyms):
1109 return False
1110 return True
1111
1112
1113def _a_name_before(texts: Sequence[str], state: ParseState) -> bool:
1114 """Whether the word right before a glued saint word is a name, the
1115 surname the particle cannot then be part of a title with: no title
1116 of any kind (listed, gated, a modifier or a style), no connective,
1117 nor titles glued at their stops; and no connective earlier in the
1118 part, which joins a title phrase or names ('Mr and Mrs St.Clair',
1119 'Dean of Students St.Clair', 'Associate Dean St.Clair' keep their
1120 word whole, rules/T8)."""
1121 if not texts:
1122 return False
1123 sets = state.lexicon._sets
1124 for before in texts:
1125 if _normalize(before) in sets.conjunctions:
1126 return False
1127 last = _normalize(texts[-1])
1128 if (last in sets.titles or last in sets.titles_ambiguous
1129 or last in sets.title_modifiers or last in sets.title_styles):
1130 return False
1131 return (period_joined_vocab(texts[-1], state.lexicon) != "title"
1132 or bool(glued_cuts(texts[-1], state.lexicon)))
1133
1134
1135def _ends_with_the_family(state: ParseState) -> bool:
1136 """Whether the part's last name word is the family's: before a
1137 family comma under every order, the comma naming the surname, and
1138 otherwise under an order that ends the name with the family (a
1139 suffix comma reads as no comma, `_postnominal_behind_a_whole_name`
1140 asking the comma as group will decide it)."""
1141 if (state.structure is Structure.FAMILY_COMMA
1142 and not _postnominal_behind_a_whole_name(state)):
1143 return True
1144 return state.policy.name_order[-1] is Role.FAMILY
1145
1146
1147def _a_word_to_spare(texts: Sequence[str], state: ParseState) -> bool:
1148 """Whether a word of `texts` is no unambiguous title, nor titles
1149 glued at their stops with no name after them ('Prof.Dr.'): a word
1150 of the name before the last one, which a title is not ('Mr.
1151 St.Clair', 'Dr. A.Smith')."""
1152 sets = state.lexicon._sets
1153 lexicon = state.lexicon
1154 return any(_normalize(before) not in sets.titles
1155 and (period_joined_vocab(before, lexicon) != "title"
1156 or glued_cuts(before, lexicon))
1157 for before in texts)
1158
1159
1160def _ends_the_name(cuts: tuple[int, ...], texts: Sequence[str],
1161 k: int, state: ParseState) -> bool:
1162 """Whether T8's division of `texts[k]` took the credential S3's
1163 shape read: initials (a letter, a run of them, a digraph) before a
1164 name that is no suffix word or acronym, which reports itself
1165 (rules/S11, 'Pedro M.Filho'); the last name word of the part, only
1166 post-nominals after it; a word before it that is no unambiguous
1167 title; and no family comma's surname, which S3 never read so, the
1168 comma asked here as group will decide it ('John Smith A.Brown,
1169 PhD' is a suffix comma, 'Smith A.Brown, John' a family one)."""
1170 sets = state.lexicon._sets
1171 text = texts[k]
1172 starts = (0, *cuts[:-1])
1173 if not all(is_initial_chunk(text[a:b - 1])
1174 for a, b in zip(starts, cuts)):
1175 return False
1176 name = _normalize(text[cuts[-1]:])
1177 if name in sets.suffix_words or name in sets.suffix_acronyms:
1178 return False
1179 if not _only_post_nominals(texts[k + 1:], state):
1180 return False
1181 # a title, or titles glued at their stops with no name after them, is
1182 # no word to spare ('Prof.Dr. A.Brown' as 'Prof. Dr. A.Brown'); a
1183 # glued word that divides holds a name ('Dr.John J.Smith')
1184 if not _a_word_to_spare(texts[:k], state):
1185 return False
1186 return (state.structure is not Structure.FAMILY_COMMA
1187 or _postnominal_behind_a_whole_name(state))
1188
1189
1190# rules/W1: "an undivided word in the family position of a name
1191# written in an activated script divides after a recognized surname,
1192# the longest recognized surname first; where the vocabulary
1193# recognizes nothing, an optional segmenter may divide instead"
1194# rules/W3: "under a family comma the pre-comma text is the
1195# family by declaration and never divides, and the post-comma side
1196# is given text with no family to find" (history: decisions/W3)
1197def script_segment(state: ParseState) -> ParseState:
1198 # a C-level test first, so a name with no slash pays no frame
1199 if "/" in state.original and state.segments:
1200 state = _divide_title_slash(state)
1201 if state.segments and GLUED_SHAPE.search(state.original):
1202 state = _divide_glued(state)
1203 if state.original.isascii():
1204 # spans index the original exactly (the anti-#100 invariant),
1205 # so an ASCII original has only ASCII tokens: nothing here is
1206 # in any script's ranges. It also short-circuits the PEEL,
1207 # which has no script gate of its own -- so a caller-configured
1208 # ASCII tail never fires, and one non-ASCII character anywhere
1209 # in the name switches it on. Correct for the CJK vocabulary
1210 # that ships, stated because honorific_tails is public: see
1211 # that field's own note. Latin orthography SPACES its
1212 # post-nominals ("John Smith PhD"), so the glued position this
1213 # peel exists for is a CJK one to begin with. What Latin does
1214 # glue is PREnominal and period-joined (Mr.Smith, Lt.Gov.),
1215 # which T8's division above divides where a name follows the
1216 # stop, and _vocab.period_joined_vocab classifies as one token
1217 # where none does -- a different mechanism, and no peel site
1218 # either way. A glued Latin POST-nominal is spelled the
1219 # same way, so it reaches that same mechanism rather than
1220 # nothing: period_joined_vocab reads "Smith.Jr." by its shape,
1221 # 'smith' being no chunk that counts (#1131), and position
1222 # decides whether that reading lands -- "John Anderson
1223 # Smith.Jr." gives suffix "Smith.Jr.", reported, while
1224 # "Smith.Jr. Anderson" gives given "Smith.Jr.", family
1225 # "Anderson" (measured 2026-11-07). Whatever it decides, this
1226 # bail is what settles the question here: it
1227 # returns above all of it, so no ASCII input reaches the peel.
1228 return state
1229 if not state.segments:
1230 return state
1231 # The glued-title peel, the tail peel's mirror, runs in front of it
1232 # and of the gates below for the tail peel's reason, which follows.
1233 heads = state.lexicon._sets.glued_titles
1234 if heads:
1235 # the C-level test first, over the words a site can be, written
1236 # as a loop rather than any() over a generator, whose frames a
1237 # name holding no word that opens with a glued title would pay
1238 # (rules/W6)
1239 prefixes = title_prefixes(heads)
1240 for run in state.segments[:2]:
1241 for j in run:
1242 if state.tokens[j].text.lower().startswith(prefixes):
1243 state = _peel_title_head(state)
1244 break
1245 else:
1246 continue
1247 break
1248 # #312: the peel runs in front of both gates below, because both
1249 # answer where a name divides into surname and given, and the peel
1250 # does not ask that. It asks whether a token ends in a word that
1251 # can never end a name, and a comma or a dot elsewhere in the
1252 # string does not change the answer. Placing it above the block
1253 # also keeps a future segmentation gate from silently capturing
1254 # it: a new gate lands with its siblings, below.
1255 # The comma's decision, asked lazily: the peel asks it only once it
1256 # has a site, the division below only once there is a token to
1257 # divide (#613's /simplify), each on the state it acts on.
1258 state = _peel_honorific_tail(
1259 state, lambda: _postnominal_behind_a_whole_name(state))
1260 if (state.structure is Structure.FAMILY_COMMA
1261 and (_split_candidate(state) is None
1262 or not _postnominal_behind_a_whole_name(state))):
1263 return state # the comma already drew the SURNAME boundary
1264 if state.interpunct_offsets:
1265 # #298: a 间隔号-divided name is a transcription -- its pieces
1266 # are syllable groups, not surname+given, so neither the
1267 # vocabulary nor the segmenter applies (codepoint-scoped: the
1268 # nakaguro records nothing and gates nothing, spec decision 5).
1269 # State-global like the FAMILY_COMMA gate above: a marker
1270 # anywhere in the name reads the WHOLE name as a transcription
1271 # listing, so even an un-dotted hangul token beside a dotted
1272 # one stays whole. Scoped to the surname split since #312: an
1273 # honorific glued to a transcription is still an honorific.
1274 return state
1275 return _split_surname_site(state)