1"""Stage: segment.
2
3Consumes: tokens (role-None main stream), comma_offsets, one_case
4(where an earlier stage recorded it).
5Produces: segments (runs of main-token indices; interior segments may
6be EMPTY -- doubled commas keep their structural position), structure
7-- NO_COMMA, or FAMILY_COMMA for every comma form: whether the part
8after the first comma is the postnominal part is decided at the head
9of group once classify has tagged the words (#613, `_comma.decide`),
10which may set SUFFIX_COMMA -- one_case where C2's flag asked for it,
11and COMMA_STRUCTURE ambiguities for unrecognized extra segments (a
12part of title and suffix words is recognized, #603).
13Reads: for C2's flag on a part past the second comma only: Lexicon
14suffix vocabulary (the four suffix sets; generation_words and
15honorific_words, the suffix words that do not settle a joined member;
16title_case_name_words,
17whose Title case leans to the name; and honorific_tails, through
18_vocab.period_joined_credential) and Policy through _vocab.is_wholly_suffix
19(Policy.lenient_comma_suffixes picks the lenient or strict token test;
20Policy.extra_suffix_delimiters makes a delimiter-core token
21transparent, as the built-in cores are), with the credential lean the lazy case gate supplies
22(Lexicon.maiden_markers DIRECTLY, for the own-words span
23_pieces.own_words takes); Policy.unlisted_dotted_suffixes through
24_vocab.ambiguous_class_candidate and _vocab.ambiguous_class_member,
25for a part of by-shape credentials; and Lexicon.titles DIRECTLY, with
26_vocab.period_joined_vocab for a period-joined title, and
27Policy.extra_suffix_delimiters through _vocab.glued_cores for a
28title with a delimiter glued to it (rules/C10), for a part of titles
29and suffixes (#603).
30
31Implements rules C2 and C10 (a title with a delimiter glued to it) of
32docs/design/rules/, and C1's segmentation;
33C1's decision is `_comma.decide`'s. History in decisions/C1.
34"""
35from __future__ import annotations
36
37from nameparser._lexicon import _normalize
38from nameparser._pipeline._pieces import own_words
39from nameparser._pipeline._state import (
40 ParseState, PendingAmbiguity, Structure, comma_bucket, copy_with,
41)
42from nameparser._pipeline._vocab import (
43 ambiguous_class_candidate, ambiguous_class_member, glued_cores,
44 glued_stem, period_joined_vocab, is_one_case, is_wholly_suffix,
45)
46from nameparser._types import AmbiguityKind
47
48
49
50
51
52def segment(state: ParseState) -> ParseState:
53 main = [i for i, t in enumerate(state.tokens) if t.role is None]
54 if not main:
55 return copy_with(state, segments=(),
56 structure=Structure.NO_COMMA)
57 if not state.comma_offsets:
58 return copy_with(state, segments=(tuple(main),),
59 structure=Structure.NO_COMMA)
60 buckets: list[list[int]] = [[] for _ in range(len(state.comma_offsets) + 1)]
61 for i in main:
62 # _state.comma_bucket, not a local bisect: classify asks the
63 # same question of the same offsets to keep a marker run inside
64 # one segment, and the two must be one expression rather than
65 # two that agree
66 buckets[comma_bucket(state.tokens[i].span.start,
67 state.comma_offsets)].append(i)
68 groups = [tuple(b) for b in buckets]
69 # v1 strips exactly ONE trailing comma as cosmetic (parser.py's
70 # collapse_whitespace); every other empty bucket is STRUCTURAL and
71 # keeps its position -- in 'Doe,, Jr.' the given segment is empty,
72 # so 'Jr.' stays a tail suffix instead of masquerading as a lone
73 # post-comma title (v1 parity, pinned live 2026-07-16)
74 if len(groups) > 1 and not groups[-1]:
75 groups.pop()
76 if len(groups) <= 1:
77 segs = tuple(groups) if groups and groups[0] else (tuple(main),)
78 return copy_with(state, segments=segs,
79 structure=Structure.NO_COMMA)
80
81 # The case fact, asked LAZILY: here only C2's flag on a part past
82 # the second comma turns on it. A name that never asks pays nothing;
83 # classify asks for itself later where this did not
84 # (decisions/S6, and #429's precedent for paying a predicate
85 # twice rather than plumbing a field two sites would not otherwise
86 # share).
87 one_case = state.one_case
88
89 def case_class() -> bool:
90 nonlocal one_case
91 if one_case is None:
92 one_case = is_one_case(own_words(
93 state.tokens, state.comma_offsets,
94 state.lexicon._sets.maiden_markers)[0])
95 return one_case
96
97 # The texts are built inline rather than through a helper
98 # (measured, #289/#516's eager-gate fix round): on 3.11 a list
99 # comprehension IS a frame
100 # (PEP 709 inlines it only from 3.12 on; see
101 # tools/perf/call_count.py's docstring), so wrapping it in another
102 # call doubles the cost of every tail segment asked.
103 #
104 # `case` is ParseState.one_case: None is the case-FREE reading,
105 # which is what every caller on this path wants, and the tail
106 # walk below passes `case_class()` for the leaning one. One
107 # closure with a default rather than two whose bodies differ only
108 # in that argument.
109 # The strict test also reads the case fact, for its initial veto
110 # (rules/T4, #727): asked only under that opt-in policy, so the
111 # default pays nothing for it.
112 def suffixy(seg: tuple[int, ...], case: bool | None = None) -> bool:
113 return is_wholly_suffix(
114 [state.tokens[i].text for i in seg], state.lexicon,
115 state.policy, one_case=case,
116 letters_one_case=(None if state.policy.lenient_comma_suffixes
117 else case_class()))
118
119 def class_run(seg: tuple[int, ...]) -> bool:
120 # Every token of the run joins the ambiguous credential class
121 # BY SHAPE -- a candidate that is not a LISTED member, which is
122 # the one half `is_wholly_suffix` cannot see (its own docstring
123 # says so, and the blindness is what keeps a by-shape token out
124 # of C1's whole-name suffix fallback in `_comma.decide`). A tail
125 # segment is consumed as suffix either way, so what this decides is only
126 # whether the parse says it did not RECOGNIZE the segment -- and
127 # a run the parse itself reads as a credential run by shape is
128 # recognized. Without it, the narrow roman retirement
129 # (rules/S3) moved 'R.A.I.', 'X.Y.I.' and 'J.u.n.i.o.r.' out
130 # of the vocabulary verdict and into the shape class, and every
131 # one of them gained a COMMA_STRUCTURE flag in a third segment
132 # that 2.3 did not raise -- a report about the parser's own new
133 # reading rather than about the name (review round, #289/#516).
134 #
135 # The LISTED half is excluded rather than folded in: a listed
136 # member reaches this reading through the LEAN (the leaning
137 # `suffixy` call below), and that is the whole of what quiets
138 # it -- 'STEVEN HARDMAN, MD, DO, DDS' is written in one case,
139 # leans nothing, and keeps its flag, the recorded negative
140 # control for the lean's own effect here. Admitting membership
141 # alone would silence it and leave the control measuring
142 # nothing.
143 #
144 # Policy-sensitive by construction: with
145 # `unlisted_dotted_suffixes` off the token is name material, is
146 # no candidate, and the flag stands.
147 return all(ambiguous_class_candidate(state.tokens[i].text,
148 state.lexicon, state.policy)
149 and not ambiguous_class_member(state.tokens[i].text,
150 state.lexicon)
151 for i in seg)
152
153 def titles_and_suffixes(seg: tuple[int, ...]) -> bool:
154 # rules/C2: "a word of the title vocabulary there that is not
155 # also suffix vocabulary is a title" -- at least one title
156 # word, and every other word a suffix word
157 # period_joined_vocab for 'Lt.Gov.', one token that classify
158 # (not yet run) tags a title by this same call, and that assign
159 # then reads as one; a word without a period cannot be one
160 # rules/C10: "the word keeps the delimiter in its text and reads
161 # as it would without it" -- a title with one glued ('Dr;')
162 # reads as the title, as classify tags it (decisions/C10)
163 titles = state.lexicon._sets.titles
164 cores = glued_cores(state.policy.extra_suffix_delimiters)
165 rest = tuple([i for i in seg
166 if _normalize(t := state.tokens[i].text) not in titles
167 and ("." not in t
168 or period_joined_vocab(t, state.lexicon)
169 != "title")
170 # the pre-check keeps glued_stem's frame off a
171 # word that holds no core (its docstring's terms)
172 and not ((";" in t or len(cores) > 1)
173 and (g := glued_stem(t, cores))
174 and _normalize(g) in titles)])
175 return len(rest) < len(seg) and (not rest or suffixy(rest))
176
177 # rules/C1's decision is not this stage's since #613: every comma
178 # form leaves here as the FAMILY comma -- the listing form, what a
179 # comma means until the part after it has been read -- and group
180 # decides at its head, once classify has tagged every word, whether
181 # that part is the postnominal part (`_comma.decide`). Deciding here
182 # meant predicting the later stages: group's particle chain (#562's
183 # pair) and assign's reading of a run the capitals settle, with a
184 # second count in assign besides. What stays here is the
185 # segmentation and C2's flag on a part past the second comma.
186 ambiguities = list(state.ambiguities)
187 # rules/C2: "a non-empty extra part that is not entirely suffix
188 # words is flagged as a structural ambiguity rather than rejected"
189 # -- parts[2:] are consumed as suffixes either way, their title
190 # words as titles (#603), so a tail segment that is neither all
191 # suffix words nor title words beside suffix words gets the
192 # COMMA_STRUCTURE flag, not a structure veto. The lean reaches this reading too:
193 # a tail of leaning credentials is a credential run, which is the
194 # one place this design quiets a report rather than adding one.
195 for seg in groups[2:]:
196 # empty segments are consumed silently (v1 skips them without
197 # comment); only non-empty non-suffix tails get flagged.
198 # The case-FREE `suffixy(seg)` first: by construction the
199 # leaning call can only ADD a disjunct to it
200 # (`is_wholly_suffix`'s credential-lean branch), never remove
201 # one -- so a seg that already reads wholly suffix case-free
202 # reads so case-aware too, and the case fact is worth forcing
203 # only when the case-free answer was False (measured
204 # regression: the leaning call forced the fact for every tail
205 # segment, suffix or not).
206 # `class_run` last, for the same lazy reason and one step
207 # further out: it is the only one of the three that walks the
208 # by-shape class, and it is asked only of a run BOTH suffix
209 # readings have already declined.
210 # #603: a part assign reads as titles and suffixes is
211 # recognized too -- word by word, off the title vocabulary
212 # (classify has not run yet), so a part holding a connective ('Secretary of State') keeps the
213 # flag: knowing that group's title chain takes it would be a
214 # model of group, the shape mechanisms.md's
215 # READ-WITHOUT-THEN-BIND exists to remove. Last, as the
216 # rarest reading.
217 if (seg and not suffixy(seg) and not suffixy(seg, case_class())
218 and not class_run(seg) and not titles_and_suffixes(seg)):
219 texts_joined = " ".join([state.tokens[i].text for i in seg])
220 # Names no field: since #603 a title word in the part reads
221 # as a title, so 'consumed as suffix' had told
222 # 'John Smith, Jr., Dr. Bart' its 'Dr.' was a suffix, and
223 # the fields themselves say where each word went (#629).
224 ambiguities.append(PendingAmbiguity(
225 AmbiguityKind.COMMA_STRUCTURE,
226 f"segment {texts_joined!r} beyond the recognized comma "
227 f"structures; read best-effort",
228 tuple(seg)))
229 return copy_with(state, segments=tuple(groups),
230 structure=Structure.FAMILY_COMMA,
231 ambiguities=tuple(ambiguities),
232 one_case=one_case)