1"""Stage: extract_delimited.
2
3Consumes: ParseState.original.
4Produces: extracted (role + inner span per delimited region), masked
5(full regions incl. delimiter chars, skipped by tokenize),
6UNBALANCED_DELIMITER ambiguities for opens with no close.
7A Role.MAIDEN region is the WHOLE inner span, marker included (all of
8it, a phrase marker being several words) -- nothing here strips one.
9classify tags a marker inside it like any other token, and group drops
10it from a multi-token clause (#329).
11A region reaches that role two ways: the pair that matched sits in
12Policy.maiden_delimiters (M1), or the content itself opens with a
13marker word (M3). The content's marker reassigns the role after the
14match both ways -- a maiden marker to the maiden name (M3), an alias
15marker to the nickname (N4) -- and so is the one thing here that a
16bucket alone does not decide.
17Reads: Policy.nickname_delimiters, Policy.maiden_delimiters,
18Lexicon.maiden_markers, Lexicon.alias_markers (rules/N4),
19Lexicon.particles (an apostrophe opening a
20listed particle, rules/N2), Policy.strip_emoji and Policy.strip_bidi
21(through `_tokenize._ignorable`, where that particle's word ends), and
22through `_vocab.set_apart_kind` and
23`set_apart` (rules/S1) Lexicon.suffix_words / suffix_words_ambiguous /
24suffix_acronyms / suffix_acronyms_ambiguous / titles /
25title_modifiers / title_styles / given_name_titles /
26after_given_titles, honorific_tails (through
27`_vocab.period_joined_credential`) and generation_words and
28honorific_words (through `_vocab.settles_a_member`, the words that
29do NOT settle a member beside them, rules/S1).
30
31Implements rules N1, N2, N4, S1, M1 and M3 of docs/design/rules/ (the #273
32matching mechanism); each is cited at its code below. One scan
33mechanic worth stating up front: matching is one left-to-right pass,
34no nesting, and delimiter characters inside a matched region are
35literal content for every other pair.
36
37Bucket precedence is NOT decided here: Policy canonicalizes overlap
38away before parsing, so the two buckets are always disjoint by the
39time this stage runs. The nickname-before-maiden candidate order
40below is only a same-position tie-break for exotic configs where two
41pairs share an OPEN character.
42"""
43from __future__ import annotations
44
45import bisect
46import functools
47
48from nameparser._lexicon import Lexicon, _normalize
49from nameparser._pipeline._state import (
50 COMMA_CHARS, ParseState, PendingAmbiguity, copy_with,
51)
52from nameparser._pipeline._tokenize import _ignorable
53from nameparser._pipeline._vocab import (
54 comma_follows_marker, maiden_marker_run, set_apart, set_apart_kind,
55)
56from nameparser._types import AmbiguityKind, Role, Span
57
58
59# rules/S1: "loses its brackets and reads exactly as if written bare,
60# the escape v1 made for any period-final content" -- asked only of a
61# clause `_set_apart` declined (decisions/S1, #792)
62def _period_escape(content: str) -> bool:
63 """v1 parse_nicknames' escape (parser.py:1125-1141) for content
64 ending in a period. v1's other two arms, an unambiguous suffix word
65 or acronym standing alone, are `_set_apart`'s since #792, which
66 takes every such clause first."""
67 return content.endswith(".")
68
69
70def _set_apart(text: str, inner: Span,
71 lexicon: Lexicon) -> bool:
72 """Whether a delimited clause is wholly of words the vocabulary
73 reads as no name, by `_vocab.set_apart_kind` and `set_apart`: the
74 unambiguous half of S1's set-apart reading, which needs no role. A
75 member of the ambiguous class settled by its writing (S13) is
76 weighed in post_rules, once it is known where the name ends, and
77 post_rules may still decline a clause this sets apart (titles
78 alone behind a credential, initials before a name word), which then
79 keeps its pair's reading and not the period escape."""
80 words = text[inner.start:inner.end].split()
81 kinds = []
82 for word in words:
83 kind = set_apart_kind(word, lexicon)
84 if kind is None or kind == "member":
85 return False
86 kinds.append(kind)
87 return bool(words) and set_apart(words, kinds, False, lexicon)
88
89
90# rules/M3: "a bracketed clause whose content opens with a
91# recognized marker and carries a word after it reads as the
92# maiden name, whichever bucket the enclosing pair sits in"
93def _maiden_marked(content: str, lexicon: Lexicon) -> bool:
94 """The clause says 'maiden' out loud, so the caller does not have to
95 say it in Policy. Requires a word AFTER the marker: a lone marker in
96 brackets is a word in brackets, and M1 deliberately keeps a one-word
97 clause's word (it may be the surname Nee). A PHRASE marker is one
98 marker, so the word after is the word after the whole run --
99 '(z domu Nowak)' has one, '(z domu)' has none. The word after is
100 not tested for anything, which is
101 rules/M3's Accepted bullet "The word taken after the marker is not tested"
102 (decisions/M3) and the reason a bracketed '(née PhD)' reads maiden
103 'PhD' where the bare 'née PhD' gives M2 a suffix.
104
105 This stage runs before tokenize, so it calls maiden_marker_run
106 itself rather than reading the tags classify will set. The two
107 questions are deliberately not the same one: this splits on
108 WHITESPACE, so a marker the writer glued to punctuation is not one
109 here ('née,') -- nor to classify, since #653 keeps a clause's comma
110 on its word. A nakaguro still divides the two: the tokenizer splits
111 '旧姓・田中' at it (rules/T2) and classify tags '旧姓', which is
112 what keeps _group's Role.MAIDEN filter reachable (cases.py's
113 marker_divided_by_a_nakaguro_keeps_the_clause_a_nickname). Sharing
114 the PREDICATE does not merge the two
115 questions -- each hands it a different sequence of words."""
116 words = content.split()
117 # A one-word clause cannot satisfy the condition whatever the
118 # vocabulary says -- `run > 0 and 1 > run` is unsatisfiable -- so
119 # refuse it before any fold or lookup, as the pre-#434 words[0]
120 # test did for free.
121 if len(words) < 2:
122 return False
123 run = maiden_marker_run(words, lexicon._sets.maiden_markers)
124 return (run > 0 and len(words) > run
125 and not comma_follows_marker(words[run]))
126
127
128# rules/N4: "a bracketed or quoted clause whose content opens with a
129# recognized alias marker and carries a word after it reads as the
130# nickname"
131def _alias_marked(content: str, lexicon: Lexicon) -> bool:
132 """M3's test for an alias marker, which is one word: the marker
133 opens the content, a word follows it, and no comma follows the
134 marker. Split on whitespace as `_maiden_marked` is, for the same
135 reason (this stage runs before tokenize)."""
136 words = content.split(None, 2)
137 return (len(words) > 1
138 and _normalize(words[0]) in lexicon._sets.alias_markers
139 and not comma_follows_marker(words[1]))
140
141
142# rules/N2: "a quote whose open and close are the same character
143# opens only at a word start and closes only at a word end, so an
144# apostrophe inside or at the end of a word is literal"
145def _open_ok(text: str, i: int, state: ParseState) -> bool:
146 return ((i == 0 or text[i - 1].isspace())
147 and not _opens_a_listed_particle(text, i, state))
148
149
150# rules/N2: "An apostrophe opening a word the vocabulary lists as a
151# particle" -- the Except clause: it opens no quote, so Dutch 't
152# reports nothing (decisions/N2, #1241). Asked of any same-character
153# open, the curly ’t being listed too. The word ends at a comma or a
154# character tokenize's _ignorable separates at. A delimited region's
155# edge is not asked, so 'Pieter \'t(Bob) Hart' still reports, a shape
156# no measured name writes; nor is T6's join, no particle holding U+202F.
157def _opens_a_listed_particle(text: str, i: int, state: ParseState) -> bool:
158 # Only where the NEXT same character cannot close the quote, being
159 # absent or after whitespace: 'T Bone' and 'T-Bone Jones' keep their
160 # nicknames though 't is listed (decisions/N2). Asked first, a C
161 # call, so a closed quoted nickname pays neither the word scan nor
162 # a _normalize frame.
163 j = text.find(text[i], i + 1)
164 if j >= 0 and not text[j - 1].isspace():
165 return False
166 k = i + 1
167 while k < len(text):
168 ch = text[k]
169 # the narrower question inline: a letter, or an ASCII character
170 # other than whitespace and the comma, never ends the word (no
171 # letter is _ignorable or a comma), so a quoted nickname pays a
172 # frame only per mark, digit or symbol beyond ASCII
173 if ch.isalpha() or (ch.isascii() and not ch.isspace()
174 and ch != ","):
175 k += 1
176 continue
177 if ch in COMMA_CHARS or _ignorable(ch, state):
178 break
179 k += 1
180 word = text[i:k]
181 particles = state.lexicon._sets.particles
182 if _normalize(word) in particles:
183 return True
184 # a particle hyphened to its surname ('s-Gravesande), its head the
185 # word before the FIRST hyphen; a word without one pays no second
186 # _normalize frame
187 head, hyphen, _ = word.partition("-")
188 return bool(hyphen) and _normalize(head) in particles
189
190
191def _close_ok(text: str, j: int, width: int) -> bool:
192 k = j + width
193 return k >= len(text) or text[k].isspace() or text[k] in COMMA_CHARS
194
195
196# Delimiters that also occur INSIDE and at the end of real name parts,
197# so a dangling one is literal rather than unbalanced. Only the straight
198# apostrophe qualifies: quotes do not appear inside names, so the same
199# position with a quote genuinely is ambiguous. #273 dropped the curly
200# apostrophe from the defaults outright for this reason; the straight
201# one has to stay a delimiter (v1's quoted_word), so it is carved out
202# here instead. Deliberately not widened to a configured delimiter set.
203WORD_INTERNAL_DELIMITERS = frozenset({"'"})
204
205
206def _word_internal(text: str, j: int, close: str) -> bool:
207 """A word-internal delimiter directly after a word character is part
208 of the word, not a dangling close -- "Mari' Aube'", "Ali Baba'"."""
209 return (close in WORD_INTERNAL_DELIMITERS and j > 0
210 and (text[j - 1].isalnum() or text[j - 1] == "."))
211
212
213def _overlaps(span: Span, taken: list[Span], starts: list[int]) -> bool:
214 """`taken` sorted and non-overlapping (both hold by construction),
215 `starts` its start offsets. Bisect rather than scan: the closer
216 sweep tests one span per delimiter character found, so a linear
217 probe is quadratic in the number of matched pairs
218 (decisions/parse-cost, 2026-07-19 4e02fa4e, holds the measurement).
219 Same idiom, and the same reason, as the origin resolution in
220 _tokenize."""
221 i = bisect.bisect_right(starts, span.start) - 1
222 # the only candidates are the last span starting at or before us and
223 # its successor -- anything earlier ends before it, anything later
224 # starts after us
225 for k in (i, i + 1):
226 if 0 <= k < len(taken) and span.start < taken[k].end and (
227 taken[k].start < span.end):
228 return True
229 return False
230
231
232@functools.lru_cache(maxsize=128)
233def _delimiter_chars(
234 nickname_pairs: frozenset[tuple[str, str]],
235 maiden_pairs: frozenset[tuple[str, str]],
236) -> frozenset[str]:
237 """Every character appearing in any configured delimiter, cached on
238 the (hashable) policy frozensets: the common no-delimiter name pays
239 one isdisjoint() instead of a per-pair scan."""
240 return frozenset(
241 ch
242 for pairs in (nickname_pairs, maiden_pairs)
243 for pair in pairs
244 for part in pair
245 for ch in part
246 )
247
248
249def _unmatched(open_: str, offset: int) -> tuple[int, PendingAmbiguity]:
250 return (offset, PendingAmbiguity(
251 AmbiguityKind.UNBALANCED_DELIMITER,
252 f"unmatched {open_!r} at offset {offset}; treated as literal text",
253 origin=offset,
254 ))
255
256
257# rules/N1: "a clause enclosed by a configured nickname delimiter
258# pair reads as the nickname and is lifted out of the name" -- Then,
259# and the empty enclosure it drops; its punctuation is tokenize's half
260# of the rule (decisions/N1)
261# rules/M1: "its enclosed clause reads as the maiden name" -- Then,
262# the pair being one the caller configured for maiden names; the
263# marker drop is group's half (decisions/M1)
264def extract_delimited(state: ParseState) -> ParseState:
265 text = state.original
266 policy = state.policy
267 if _delimiter_chars(policy.nickname_delimiters,
268 policy.maiden_delimiters).isdisjoint(text):
269 return state
270 # Candidate order matters only as a same-position tie-break (see
271 # module docstring); the scan itself is position-driven.
272 order = tuple(
273 (role, open_, close)
274 for role, pairs in ((Role.NICKNAME, policy.nickname_delimiters),
275 (Role.MAIDEN, policy.maiden_delimiters))
276 for open_, close in sorted(pairs)
277 )
278 extracted: list[tuple[Role, Span]] = []
279 masked: list[Span] = []
280 # candidates, not final: each carries the offset of the unmatched
281 # open so ones consumed by a later match can be filtered at the end
282 unbalanced: list[tuple[int, PendingAmbiguity]] = []
283 # per-candidate cursor cache: next boundary-valid open at or after
284 # the position it was computed for. find() calls only ever move
285 # forward, keeping the whole scan linear in len(text) per pair.
286 cursors: dict[tuple[Role, str, str], int] = {}
287 exhausted: set[tuple[Role, str, str]] = set()
288 pos = 0
289 while pos < len(text):
290 best: tuple[int, Role, str, str] | None = None
291 for key in order:
292 if key in exhausted:
293 continue
294 _, open_, close = key
295 i = cursors.get(key, -2)
296 if i != -1 and i < pos:
297 i = text.find(open_, pos)
298 while (i != -1 and open_ == close
299 and not _open_ok(text, i, state)):
300 i = text.find(open_, i + 1)
301 cursors[key] = i
302 if i != -1 and (best is None or i < best[0]):
303 best = (i, *key)
304 if best is None:
305 break
306 i, role, open_, close = best
307 j = text.find(close, i + len(open_))
308 while (open_ == close and j != -1
309 and not _close_ok(text, j, len(close))):
310 j = text.find(close, j + 1)
311 if j == -1:
312 # No (boundary-valid) close exists anywhere to the right --
313 # the walk above ran to end of text -- so every remaining
314 # open of this pair is unmatched too. Record them all in
315 # one forward pass and retire the pair; other pairs keep
316 # scanning from the same position.
317 unbalanced.append(_unmatched(open_, i))
318 scan = i + len(open_)
319 while (k := text.find(open_, scan)) != -1:
320 if open_ != close or _open_ok(text, k, state):
321 unbalanced.append(_unmatched(open_, k))
322 scan = k + 1
323 exhausted.add((role, open_, close))
324 continue
325 inner = Span(i + len(open_), j)
326 if inner.start < inner.end and _set_apart(text, inner, state.lexicon):
327 # rules/S1: "it is no nickname and no maiden name, and the
328 # words around it read as they would beside a nickname"
329 # -- extracted as its pair reads it, post_rules giving its
330 # words their roles once the name's words are placed
331 # (decisions/S1, #792)
332 extracted.append((role, inner))
333 masked.append(Span(i, j + len(close)))
334 elif inner.start < inner.end and _period_escape(
335 text[inner.start:inner.end]):
336 # v1 parse_nicknames: period-final content S1 does not set
337 # apart is left IN PLACE (undelimited) for normal downstream
338 # parsing -- 'John Smith (M.A.)' keeps M.A. a suffix, not a
339 # nickname. Spans index the original (anti-#100), so the v2
340 # spelling masks only the two delimiter spans and lets the
341 # inner content join the main token stream.
342 masked.append(Span(i, i + len(open_)))
343 masked.append(Span(j, j + len(close)))
344 else:
345 if inner.start < inner.end:
346 # M3 upgrades a nickname clause; a configured maiden
347 # pair is M1's and is left alone. The role test is
348 # False whenever a maiden pair matched, but it cannot
349 # change the OUTCOME, and no test can catch its
350 # removal: `order` above holds exactly two roles, so a
351 # role that is not NICKNAME is already MAIDEN and the
352 # assignment would be a no-op either way. It is kept
353 # for the day `order` gains a third bucket, when it
354 # becomes the difference between M3 claiming that
355 # bucket's clauses and leaving them. Measured
356 # 2026-08-26: dropping it leaves the suite and all
357 # three gates green.
358 if (role is Role.NICKNAME and _maiden_marked(
359 text[inner.start:inner.end], state.lexicon)):
360 role = Role.MAIDEN
361 elif (role is Role.MAIDEN and _alias_marked(
362 text[inner.start:inner.end], state.lexicon)):
363 # rules/N4: "whichever bucket the enclosing pair
364 # sits in" -- M3's mirror for a pair configured
365 # maiden
366 role = Role.NICKNAME
367 extracted.append((role, inner))
368 masked.append(Span(i, j + len(close)))
369 # position-driven scanning makes overlapping matches
370 # impossible by construction: every later open is found at or
371 # after this match's end
372 pos = j + len(close)
373 extracted.sort(key=lambda pair: pair[1])
374 masked.sort()
375 # An unmatched-open candidate whose character was consumed by a
376 # later successful match (the bulk pass above runs ahead of the
377 # main scan) is literal content there, not a dangling delimiter.
378 # offsets already claimed as unbalanced, by an open above or by a
379 # close in the sweep below -- either way, do not report one twice
380 reported = {offset for offset, _ in unbalanced}
381 mask_starts = [s.start for s in masked]
382 ambiguities = [
383 a for offset, a in unbalanced
384 if not _overlaps(Span(offset, offset + 1), masked, mask_starts)]
385 # The scan above is opener-driven: it searches for an open and then
386 # looks rightward for its close, so a close with no open to its
387 # LEFT is never in its search space. Sweep for those separately --
388 # they signal the same malformed input, and the kind's contract has
389 # always covered them ("opened without closing, or closed without
390 # opening"). Same boundary test as the matched path, which is what
391 # keeps the apostrophe in "O'connor" out of it.
392 # Distinct closes only: the defaults list '”' twice (from both
393 # ('“','”') and ('”','”')), and a repeat can only rediscover
394 # offsets the first pass already handled.
395 for close in sorted({c for _, _, c in order}):
396 start = 0
397 while (j := text.find(close, start)) != -1:
398 start = j + 1
399 if (j in reported
400 or not _close_ok(text, j, len(close))
401 or _word_internal(text, j, close)
402 or _overlaps(Span(j, j + len(close)), masked,
403 mask_starts)):
404 continue
405 reported.add(j)
406 ambiguities.append(_unmatched(close, j)[1])
407 return copy_with(
408 state, extracted=tuple(extracted), masked=tuple(masked),
409 ambiguities=state.ambiguities + tuple(ambiguities))