1"""Stage: tokenize.
2
3Consumes: original, masked (regions to skip), extracted (regions that
4tokenize with a pre-set role), and ambiguities (extract's
5UNBALANCED_DELIMITER reports, which carry a character offset).
6Produces: tokens (span-sorted WorkTokens; text always == original
7slice), comma_offsets (segmentation points of the main stream; a comma
8there is never a token, one inside an extracted region is word text),
9interpunct_offsets (间隔号 and fullwidth-stop transcription markers, #298,
10#1312; never tokens), and ambiguities, each report extract left
11carrying a character offset rewritten to the index of the token
12holding that character (no index where the offset is masked).
13Reads: Policy.strip_emoji, Policy.strip_bidi.
14
15Implements rules T1, T2, T3 and T6 of docs/design/rules/, and N1's
16comma kept inside a clause, cited at their code below. There is NO
17text-rewriting normalize stage: the four T rules are
18character-classification rules, so spans always index the
19original exactly as given (v1 contrast: decisions/T1).
20
21Beside the stage function, `_ignorable` is shared: extract asks it
22where a listed particle's word ends (rules/N2, #1241). It matches the
23ignorable class tokenize's own scan is built from, so the two stages
24agree on every character that separates in every context; the ones
25context decides (a transcription dot between classified characters,
26U+202F between Mongolian letters) are tokenize's alone.
27"""
28from __future__ import annotations
29
30import bisect
31import operator
32import re
33
34from nameparser._pipeline._state import (
35 COMMA_CHARS, ParseState, WorkToken, copy_with,
36)
37from nameparser._policy import Policy, _classified_char
38from nameparser._types import Role, Span
39
40# Ported from v1's "emoji" and "bidi" patterns (the 1.x and 2.x
41# nameparser.config.regexes, removed in 3.0, #1008); this is now the
42# only copy. The emoji ranges are written as integers, never as a
43# literal regex class: CodeQL's py/overly-large-range false-positives on
44# literal astral ranges (surrogate decomposition), so their class,
45# _EMOJI_CHARS, is built from the integers. The bidi marks are all in
46# the BMP and stay a literal class body.
47_EMOJI_RANGES = ((0x1F300, 0x1F64F), (0x1F680, 0x1F6FF),
48 (0x2600, 0x26FF), (0x2700, 0x27BF))
49_BIDI_CHARS = '\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069'
50_EMOJI_CHARS = ''.join(f'{chr(lo)}-{chr(hi)}' for lo, hi in _EMOJI_RANGES)
51
52# rules/T2: "the katakana middle dot, its halfwidth twin and the
53# Ethiopic wordspace divide a name like whitespace, always." -- the
54# Then, for these three characters, in every context. They record no
55# offset: the nakaguro also divides kanji roster pairs
56# (高橋・一郎, read family-first by the script license, #272), so it is
57# not a transcription marker; _TRANSCRIPTION_DOTS below are
58# (decisions/T2 and T3, #298, #1202, #1312).
59_NAME_DOT_SEPARATORS = frozenset({"\u30FB", "\uFF65", "\u1361"})
60
61# rules/T6: "a narrow no-break space between two Mongolian letters
62# joins them into one word" -- the whole rule, T1's Except: anywhere
63# else U+202F is whitespace and divides (decisions/T6, #1236).
64_NARROW_NBSP = "\u202F"
65_MONGOLIAN_BLOCK = (0x1800, 0x18AF)
66
67# rules/T1: "a zero-width space, an invisible separator and a
68# byte-order mark have no such opt-out" -- the Except clause: they
69# separate under every policy, carrying nothing a caller would keep.
70# Not here: U+200C and U+200D, which decide how the letters around
71# them join, the word joiner U+2060, which means no break, the soft
72# hyphen U+00AD, which marks a break inside one word, the invisible
73# math operators U+2061, U+2062 and U+2064, and the Mongolian vowel
74# separator U+180E, which shapes the letters beside it
75# (decisions/T1, #851).
76_INVISIBLE_SEPARATORS = frozenset({"\u200B", "\u2063", "\uFEFF"})
77
78_INTERPUNCT = "\u00B7"
79# The fullwidth full stop is the same transcription dot where Taiwan's
80# writers type it between two Han names (`台邦.撒沙勒`, #1312), and the
81# same plain full stop everywhere else, so it takes the interpunct's
82# flank guard whole: it divides, and records, only between two characters
83# of a classified script. The ideographic full stop U+3002 is not one:
84# it is the sentence stop (decisions/T3, #1312).
85_TRANSCRIPTION_DOTS = frozenset({_INTERPUNCT, "\uFF0E"})
86# rules/T3: "the interpunct divides a name only between two
87# characters of a classified East Asian script; anywhere else it is
88# part of the word" -- the Then, for both _TRANSCRIPTION_DOTS, whose
89# flank guard _tokenize_region applies (decisions/T3, #298, #1312). The
90# guard asks _policy._classified_char per CHAR: a one-char string is
91# wholly-classified iff the character is. Context-sensitivity is why the
92# guard lives in _tokenize_region (where the index exists) and not in
93# _ignorable.
94
95
96def _chars(chars: frozenset[str]) -> str:
97 """A set of single characters as the body of a regex class."""
98 return ''.join(re.escape(ch) for ch in sorted(chars))
99
100
101# rules/T1: "an ignorable character separates its neighbors and
102# never joins them" (v1 contrast: decisions/T1). The ignorable set as
103# regex classes, one per setting of the two strip switches, so a region
104# is scanned for its separators in C rather than asked character by
105# character. These classes ARE the definition: _ignorable and _stripped
106# match against them, and the boundary pattern _tokenize_region scans
107# with is the ignorable class plus the characters that separate only by
108# context (the commas, which record an offset, and the transcription
109# dots, whose flanks decide); U+202F is whitespace, ignorable, save
110# where rules/T6 has it join two Mongolian letters. `\s` matches
111# exactly what str.isspace() accepts, which
112# test_the_separator_classes_hold_their_parts_over_every_code_point
113# holds over every code point.
114_ALWAYS = r'\s' + _chars(_NAME_DOT_SEPARATORS | _INVISIBLE_SEPARATORS)
115_SWITCHES = ((False, False), (False, True), (True, False), (True, True))
116
117
118def _strip_class(strip_bidi: bool, strip_emoji: bool) -> str:
119 return ((_BIDI_CHARS if strip_bidi else '')
120 + (_EMOJI_CHARS if strip_emoji else ''))
121
122
123_STRIPPED = {key: re.compile(f'[{_strip_class(*key)}]') if any(key) else None
124 for key in _SWITCHES}
125_IGNORABLE = {key: re.compile(f'[{_ALWAYS}{_strip_class(*key)}]')
126 for key in _SWITCHES}
127_BOUNDARY = {key: re.compile(
128 f'[{_ALWAYS}{_strip_class(*key)}'
129 f'{_chars(COMMA_CHARS | _TRANSCRIPTION_DOTS)}]') for key in _SWITCHES}
130
131
132def _mongolian_letter(ch: str) -> bool:
133 """A character of the Mongolian block that is not its punctuation
134 (U+1800-U+180A) or a digit (U+1810-U+1819): its letters, free
135 variation selectors and vowel separator, each of which stands
136 inside a written word, and the block's unassigned codepoints."""
137 cp = ord(ch)
138 return (_MONGOLIAN_BLOCK[0] <= cp <= _MONGOLIAN_BLOCK[1]
139 and not 0x1800 <= cp <= 0x180A and not 0x1810 <= cp <= 0x1819)
140
141
142def _stripped(ch: str, policy: Policy) -> bool:
143 """True when the strip policy removes `ch` from the token stream.
144 It matches the class _strip_class builds, which _IGNORABLE and
145 _BOUNDARY are built from too. _flank skips what it matches, so a
146 stripped character never occupies a flank, and a strip class added
147 to _strip_class is transparent to the transcription-dot guard by
148 construction. The separators (whitespace, the name dots and
149 _INVISIBLE_SEPARATORS) are not stripped and do occupy one."""
150 pattern = _STRIPPED[policy.strip_bidi, policy.strip_emoji]
151 return pattern is not None and pattern.match(ch) is not None
152
153
154def _flank(text: str, indices: range, policy: Policy) -> str | None:
155 """The nearest flank character the strip policy would keep, or
156 None if the range exhausts. What the strip policy removes (the
157 bidi marks and the emoji, each under its switch) is TRANSPARENT
158 here: an RTL document quoting a transcription puts U+200F beside
159 the dot in visually identical text. Whitespace, the name dots and
160 _INVISIBLE_SEPARATORS stay guard-defeating: a dot beside a space is
161 not between characters."""
162 for i in indices:
163 ch = text[i]
164 if not _stripped(ch, policy):
165 return ch
166 return None
167
168
169def _ignorable(ch: str, state: ParseState) -> bool:
170 """True when `ch` separates the words beside it: whitespace, the
171 name dots, _INVISIBLE_SEPARATORS (all unconditional, not
172 policy-gated, and recording no offset, which the commas and the
173 transcription dots do), and what the strip policy removes. The
174 one exception is decided in _tokenize_region, by context: U+202F
175 between two Mongolian letters joins them (rules/T6)."""
176 policy = state.policy
177 return _IGNORABLE[policy.strip_bidi, policy.strip_emoji].match(
178 ch) is not None
179
180
181def _tokenize_region(state: ParseState, start: int, end: int,
182 role: Role | None, record_offsets: bool,
183 tokens: list[WorkToken], commas: list[int],
184 interpuncts: list[int]) -> None:
185 text = state.original
186 policy = state.policy
187 tok_start = start
188 # Only the characters that may separate are visited; a word's
189 # letters are passed over in C
190 for m in _BOUNDARY[policy.strip_bidi, policy.strip_emoji].finditer(
191 text, start, end):
192 i = m.start()
193 ch = text[i]
194 if ch in COMMA_CHARS:
195 # rules/N1: "a comma inside the clause is kept as written:
196 # the comma divides nothing there" -- the Then bullet on a
197 # comma: a comma separates only where it records a
198 # segmentation offset, the main stream; inside an extracted
199 # region it is the clause's text, like ';' (decisions/N1,
200 # #653)
201 if not record_offsets:
202 continue
203 commas.append(i)
204 elif ch == _NARROW_NBSP:
205 if (start < i < end - 1 and _mongolian_letter(text[i - 1])
206 and _mongolian_letter(text[i + 1])):
207 continue
208 elif ch in _TRANSCRIPTION_DOTS:
209 # Region-local flanks: a dot at a region edge stays token
210 # text, and the bound also stops a custom delimiter's
211 # classified edge character from acting as a flank across
212 # a mask seam. The scan reads raw characters, not the NFC
213 # copy classification reads; the script table holds the
214 # conjoining jamo a decomposed syllable is written in, so
215 # decomposed hangul flanks as composed hangul does
216 # (decisions/nfd-shapes, #1087).
217 left = _flank(text, range(i - 1, start - 1, -1), policy)
218 if left is None or not _classified_char(left):
219 continue
220 right = _flank(text, range(i + 1, end), policy)
221 if right is None or not _classified_char(right):
222 continue
223 if record_offsets:
224 interpuncts.append(i)
225 if tok_start < i:
226 tokens.append(WorkToken(text[tok_start:i],
227 Span(tok_start, i), role=role))
228 tok_start = i + 1
229 if tok_start < end:
230 tokens.append(WorkToken(text[tok_start:end],
231 Span(tok_start, end), role=role))
232
233
234def tokenize(state: ParseState) -> ParseState:
235 tokens: list[WorkToken] = []
236 commas: list[int] = []
237 interpuncts: list[int] = []
238 # main stream: everything outside masked regions
239 boundaries = [0]
240 for m in state.masked:
241 boundaries.extend((m.start, m.end))
242 boundaries.append(len(state.original))
243 for start, end in zip(boundaries[::2], boundaries[1::2]):
244 _tokenize_region(state, start, end, None, True, tokens, commas,
245 interpuncts)
246 # extracted regions: pre-set role; a comma is word text there, and a
247 # transcription dot divides where its flanks allow but records no
248 # offset
249 for role, inner in state.extracted:
250 _tokenize_region(state, inner.start, inner.end, role, False,
251 tokens, commas, interpuncts)
252 # attrgetter, not a lambda: the key is read in C, with no frame
253 # per token
254 tokens.sort(key=operator.attrgetter("span"))
255 # extract_delimited runs before tokens exist, so its ambiguities
256 # carry a character offset instead of an index. Resolve them now
257 # that the stray character has landed in a token ('"Nick', 'Smith)')
258 # -- without this the ambiguity is locatable only by parsing the
259 # offset back out of its detail string. An offset inside a masked
260 # region belongs to no token; those keep an empty tuple, which the
261 # kind's contract already allows.
262 # Bisect rather than rescan: the closer sweep reports one ambiguity
263 # per stray closing delimiter, so a linear scan per ambiguity is
264 # quadratic in them (test_benchmark.py's `unmatched_closes` row;
265 # decisions/parse-cost, 2026-11-22 #1527). Spans are non-overlapping and
266 # sorted just above, so the candidate is the last token whose start
267 # is <= the offset.
268 # Nothing to resolve on the common parse with no ambiguity, which
269 # the empty-tuple test passes without the generator's frame.
270 ambiguities = state.ambiguities
271 if ambiguities and any(a.origin is not None for a in ambiguities):
272 starts = [t.span.start for t in tokens]
273
274 def _containing(offset: int) -> tuple[int, ...]:
275 i = bisect.bisect_right(starts, offset) - 1
276 if i >= 0 and offset < tokens[i].span.end:
277 return (i,)
278 return ()
279
280 ambiguities = tuple(
281 a if a.origin is None
282 else copy_with(a, indices=_containing(a.origin))
283 for a in ambiguities)
284 return copy_with(state, tokens=tuple(tokens),
285 comma_offsets=tuple(sorted(commas)),
286 interpunct_offsets=tuple(sorted(interpuncts)),
287 ambiguities=ambiguities)