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

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

157 statements  

1"""Internal pipeline state: WorkToken and ParseState. 

2 

3WorkTokens are pipeline-internal (no validation -- the tokenizer is the 

4only producer) and are addressed BY INDEX in every stage: pieces and 

5segments are runs of token indices, never joined strings, so value-based 

6lookup (v1's #100 family) is structurally impossible. 

7 

8Layering: imports _types, _lexicon, _policy only (enforced by 

9tests/v2/test_layering.py). 

10""" 

11from __future__ import annotations 

12 

13import bisect 

14import dataclasses 

15from collections.abc import Iterable, Mapping, Sequence 

16from dataclasses import dataclass 

17from enum import Enum, auto 

18from types import MappingProxyType 

19from typing import TYPE_CHECKING, TypeVar 

20 

21from nameparser._lexicon import Lexicon 

22from nameparser._policy import Policy 

23from nameparser._types import AmbiguityKind, Segmenter, Span 

24# re-exported for _vocab, which layering keeps off _types 

25from nameparser._types import ReadingKind as ReadingKind 

26from nameparser._types import ReadingSource as ReadingSource 

27from nameparser._types import Role as Role 

28from nameparser._types import SHAPE_ACRONYM_TAG as SHAPE_ACRONYM_TAG 

29from nameparser._types import SPLIT_CREDENTIAL_TAG as SPLIT_CREDENTIAL_TAG 

30from nameparser._types import SPLIT_MEMBER_TAG as SPLIT_MEMBER_TAG 

31 

32if TYPE_CHECKING: 

33 from nameparser._pipeline._pieces import TailRead 

34 

35 

36# The comma characters (ASCII/Arabic/fullwidth, #265; Ethiopic and 

37# Burmese, #1202; N'Ko, Mongolian, Manchu, Lisu, Vai and Bamum, #1202's 

38# follow-up -- not the Armenian U+055D, which is no comma, decisions/C1). 

39# Shared here so tokenize (separators/segmentation), extract 

40# (close-quote boundaries, a listed particle's word end) and _vocab 

41# cannot drift apart. 

42COMMA_CHARS = frozenset({",", "\u060c", "\uff0c", "\u1363", "\u104a", 

43 "\u07f8", "\u1802", "\u1808", "\ua4fe", 

44 "\ua60d", "\ua6f5"}) 

45#: The same characters as one string, for str.strip: a word of a 

46#: set-apart clause keeps the comma written against it (rules/N1), and 

47#: every site reading that word without it strips this, so a clause 

48#: reads alike whichever script's comma divides it (decisions/C1, #1202). 

49COMMA_STRIP = "".join(sorted(COMMA_CHARS)) 

50 

51 

52def comma_bucket(start: int, comma_offsets: Sequence[int]) -> int: 

53 """Which comma-delimited part of the name a token starting at 

54 `start` falls in: the number of commas before it. 

55 

56 Shared here for the reason COMMA_CHARS is, and the sharing is 

57 load-bearing in the same way. segment BUILDS the segments with this 

58 (comma_offsets is sorted and no offset ever equals a token start, 

59 so bisect_left counts the commas before the token); classify asks 

60 it to decide whether two tokens could be in one segment, which is 

61 half of what stops a maiden marker run from spanning a boundary no 

62 segment holds. Two tokens agree here iff segment would put them in 

63 one segment, and that is an identity rather than a resemblance 

64 only while both sides ask this function. 

65 """ 

66 return bisect.bisect_left(comma_offsets, start) 

67 

68@dataclass(frozen=True, slots=True) 

69class WorkToken: 

70 """One tokenized word. role stays None until assign; extracted 

71 nickname/maiden tokens arrive with their role pre-set. text is 

72 always the exact original slice (tokenize is the sole producer; 

73 the anti-#100 invariant depends on it).""" 

74 

75 text: str 

76 span: Span 

77 tags: frozenset[str] = frozenset() 

78 role: Role | None = None 

79 

80 

81#: M4's two carve-outs, as the tags classify recorded them: a bound 

82#: given-name word is vocabulary claiming the word as a given name, 

83#: and `initial` is the initial reading. Neither is a predicate M4 owns. 

84#: Shared here beside WorkToken.tags for the reason COMMA_CHARS is: 

85#: assign's `_WORD_ALREADY_CLAIMED` is built from this pair, and the 

86#: two stages must not drift (post_rules imports _assign, so _assign 

87#: cannot reach the other way). 

88_NEVER_FLIPPED = frozenset({"vocab:bound-given", "initial"}) 

89 

90# SHAPE_ACRONYM_TAG is defined and explained in _types (its #: block 

91# above the constant, not restated here -- defined there so _render 

92# can read it too); re-exported here beside the membership half below 

93# because the stages read both halves from one module. 

94 

95#: The MEMBERSHIP half of the same class: classify's tag for a token 

96#: the ambiguous credential vocabulary claims, by listing 

97#: (`Lexicon.suffix_acronyms_ambiguous`) or -- where a Policy switch 

98#: admits the by-shape half -- beside `SHAPE_ACRONYM_TAG`. Beside that 

99#: constant and for its reason: the string was spelled out at eight 

100#: sites across four modules, each of them a place for a typo to pass 

101#: silently, since a tag that is never written is simply a tag no 

102#: reader ever finds. 

103AMBIGUOUS_ACRONYM_TAG = "vocab:suffix-ambiguous" 

104 

105#: Beside `AMBIGUOUS_ACRONYM_TAG` on a suffix WORD that is also a name 

106#: (`Lexicon.suffix_words_ambiguous`, rules/S11): the class is the 

107#: same, and so is every site that weighs it, but the writing leans the 

108#: other way -- lower case in a mixed-case name is the suffix, where an 

109#: acronym's capitals are (`_vocab.ambiguous_lean`), but only on a 

110#: word written `title_case_is_name` (`fils`, `kc`), which 

111#: `TITLE_CASE_NAME_TAG` marks; any other leans nowhere (#1039). 

112#: `AGNOMEN_TAG` rides beside both on an agnomen, for its reading's kind. 

113AMBIGUOUS_WORD_TAG = "vocab:suffix-word-ambiguous" 

114AGNOMEN_TAG = "vocab:agnomen" 

115TITLE_CASE_NAME_TAG = "vocab:title-case-name" 

116 

117#: Beside "vocab:suffix-word" on a word whose shipped reading index 

118#: kind is a generation (`jr`), a credential written as a word 

119#: (`博士`) or an honorific (`さん`, #326), which the compiled sets do 

120#: not record (rules/R8, 3.0's 4b): 

121#: written by classify from the word as it reads it, a delimiter glued 

122#: on removed (`Jr.;`, rules/C10), and read by `_vocab.suffix_kind`. 

123GENERATION_WORD_TAG = "vocab:generation-word" 

124CREDENTIAL_WORD_TAG = "vocab:credential-word" 

125HONORIFIC_WORD_TAG = "vocab:honorific-word" 

126 

127#: Beside "particle" on a word the shipped reading index holds as a 

128#: patronymic particle (`bin`, `ibn`, `bat`), which the compiled sets 

129#: do not record (rules/R9, 3.0's 4c): written by classify, read by 

130#: assemble for `Token.reading` and by assign for the reading a report 

131#: names, and dropped from the published token like the kind tags above. 

132PATRONYMIC_TAG = "vocab:patronymic" 

133 

134#: On a word the lexicon holds as an alias marker (`@`, `urf`), which 

135#: group reads to take the words after it as the nickname (rules/N4, 

136#: #1164). Kept on the published token, as "vocab:maiden-marker" is: a 

137#: marker the rule takes leaves no token, and one read as a word keeps 

138#: its tag. 

139ALIAS_MARKER_TAG = "vocab:alias-marker" 

140 

141#: On each word of a particle chain opening a family-first name past 

142#: the reach of rules/P1's fold (#828), written by post_rules whether or 

143#: not the fold cuts the chain there, so assemble can tell where a 

144#: report's other reading would land; dropped from the published token 

145#: like the kind tags above. 

146PAST_REACH_TAG = "chain:past-reach" 

147 

148 

149def reported_suffix_fork(ambiguities: Sequence[PendingAmbiguity], 

150 indices: Iterable[int], 

151 skip: PendingAmbiguity | None = None) -> bool: 

152 """rules/P1's question about a chain opening a family-first name 

153 that the fold would cut (#828): whether a suffix-or-name report (the 

154 trailing read's, or group's on a word the chain took) names a word 

155 of `indices`, the words past the fold's reach. Such a word was read 

156 against the whole chain, so the chain stands. Asked by the fold in post_rules and, with `skip` 

157 the report whose other reading it names, by assemble.""" 

158 past = set(indices) 

159 return any(a is not skip and a.kind is AmbiguityKind.SUFFIX_OR_NAME 

160 and not past.isdisjoint(a.indices) for a in ambiguities) 

161 

162 

163#: Beside FOLDED_TAG on the particles rules/P6 attaches to the family 

164#: written before them, at either of its sites, so rules/R9 can tell 

165#: the attachment from O3's middle fold, which writes FOLDED_TAG alone; 

166#: dropped from the published token like the kind tags above. 

167ATTACHED_TAG = "vocab:attached" 

168 

169#: On each word of the second name unit rules/O6 reads a family as, 

170#: written by `_post_rules._divide_family` wherever O6 divides a family 

171#: into two, a word taken or not (and by W5's surname pair), and 

172#: dropped from the published 

173#: token like the kind tags above: `Reading.second_surname` carries it 

174#: out (rules/R10, 3.0's 4d). 

175SECOND_SURNAME_TAG = "vocab:second-surname" 

176 

177#: Its twin on each word of the FIRST name unit: written by 

178#: `_post_rules._divide_family` wherever O6 divides a family into two 

179#: (a particle P6 attached going with it), by W5's surname pair, and 

180#: where O6 marked none, by O3 on the family it folds middles into, 

181#: so a folded middle is in no unit; carried out on 

182#: `Reading.first_surname` (rules/R11, #1022). 

183FIRST_SURNAME_TAG = "vocab:first-surname" 

184 

185#: On the second of two listed single surnames that script_segment 

186#: divides a Han name's family into (rules/W5, #845), so post_rules 

187#: reads it as the family's second unit and marks both units with the 

188#: two tags above; dropped from the published token like them. 

189SURNAME_PAIR_TAG = "vocab:surname-pair" 

190 

191#: On a word of `Lexicon.titles_ambiguous` whichever way classify read 

192#: it (rules/H9): read as a title it carries "vocab:title" too, read 

193#: out of the title it carries this alone, which is how assign finds 

194#: the fork to report where the word opens the name. 

195TITLE_AMBIGUOUS_TAG = "vocab:title-ambiguous" 

196 

197#: Written by classify on every occurrence of a word of 

198#: `Lexicon.titles_ambiguous` whose title reading is written short 

199#: (`Lexicon.title_abbreviations`, `maj`), whichever way the phrase 

200#: test read it; read by classify's CHAIN_TITLE_TAG below, rules/H5's 

201#: trailing chain taking the word where it wears the abbreviation 

202#: shape, and by group's P5 decline. Dropped from the published token like 

203#: the kind tags above; the published token keeps TITLE_AMBIGUOUS_TAG. 

204TRAILING_TITLE_TAG = "vocab:trailing-title" 

205 

206#: Written by classify on a word of `Lexicon.titles` (not 

207#: `titles_ambiguous`), listed whole, whose letters a period joins, a 

208#: hyphen beside it or not (`_vocab._JOINED_WORD`: 'Dott.ssa', 

209#: 'Priv.-Doz'), and on a word with interior periods every chunk of 

210#: which is a title ('Lt.Gov', #1131), never on one read as a title 

211#: through some chunk only ('Dr.PhD', 'St.John') nor on one a hyphen 

212#: alone joins ('Co-Founder'); read by classify's CHAIN_TITLE_TAG 

213#: below, rules/H5's trailing chain taking it without a final period 

214#: (#1104). Dropped from the published token like the kind tags above. 

215JOINED_TITLE_TAG = "vocab:joined-title" 

216 

217#: Written by classify, after rules/H9's phrase test has settled which 

218#: words keep "vocab:title", on every word rules/H5's trailing chain 

219#: takes: a word carrying JOINED_TITLE_TAG, or one wearing the trailing 

220#: abbreviation shape (`_vocab._TRAILING_TITLE_SHAPE`) that carries 

221#: "vocab:title" or TRAILING_TITLE_TAG. The one statement of that test, 

222#: read as a set membership by the chain (`_pieces.trailing_titles`), 

223#: by its one-word form (`_pieces.is_trailing_title_word`, which the 

224#: maiden take and P13's walk back ask) and by `_pieces._weighed` 

225#: (#1171). Whether the word stands where the chain reaches is the 

226#: reader's question. Dropped from the published token like the kind 

227#: tags above. 

228CHAIN_TITLE_TAG = "vocab:chain-title" 

229 

230#: On a run of two or more single letters joined by full stops whose 

231#: spelling without them is a title written `dotted` 

232#: (`Lexicon.dotted_titles`: 'U.S.', 'P.D.', #490), a word the 

233#: vocabulary does not list as a title as written: rules/H10's two 

234#: title runs at the head of a part, the given part's 

235#: (`_pieces.leading_titles`) and H6's before a family comma (assign), 

236#: take it as a title only where a title the run keeps stands behind it, 

237#: so 'U.S. Grant' stays a name; classify's H9 fold and assemble's 

238#: reading source read it too, and C4's count (`_vocab.name_word_count`) 

239#: asks the same question without it. 

240DOTTED_TITLE_TAG = "vocab:dotted-title" 

241 

242#: On a word of `Lexicon.given_name_abbreviations`, a given name written 

243#: short ('Chas.', 'Ma.'): rules/H2's shape test declines a word 

244#: carrying it, so the given reading outranks the shape-derived title 

245#: (`_pieces.is_leading_title`, `_vocab.is_title_shaped`); rules/C13's 

246#: given-name Except (`_comma._given_name_written_short`) and rules/S8's 

247#: one-case clause (`_pieces.short_given_name_in_one_case`, #1394) read 

248#: it too. 

249GIVEN_ABBREVIATION_TAG = "vocab:given-abbreviation" 

250 

251#: On a word of `Lexicon.shared_names`, a name a community gives every 

252#: member (Sikh 'Kaur', 'Singh'): rules/O6 and O7 decline a join that 

253#: takes or completes one, and P10 completes none 

254#: (`_post_rules._take_second_family_name`, `_take_second_given_name`, 

255#: `_given_phrase_middle`). 

256#: Dropped from the published token like the kind tags above (#704). 

257SHARED_NAME_TAG = "vocab:shared-name" 

258 

259#: On a word of `Lexicon.particle_given_names`, a given name written 

260#: behind a particle as the second of a compound given name ('del 

261#: Carmen'): rules/P10 reads the particle run and the word as a 

262#: middle name behind a one-word given name, and O6 leaves them there. 

263#: Dropped from the published token like the kind tags above (#704). 

264PARTICLE_GIVEN_TAG = "vocab:particle-given" 

265 

266#: On a bound given name whose word and the word after it are a phrase 

267#: of `Lexicon.bound_phrases` ('عبد' before 'الله'), or one of 

268#: `Lexicon.bound_completes_any` before a plain name word (#1464; one 

269#: of `Lexicon.bound_long_names_only` post_rules strips again in a name 

270#: of fewer than four name words), which rules/P12 joins past the first 

271#: name word 

272#: (`_group._join_bound_phrases`), and group leaves it only on a pair 

273#: it joined. Dropped from the published token like the kind tags 

274#: above (#694). 

275BOUND_PHRASE_TAG = "vocab:bound-phrase" 

276#: On the first word of a pair joined backward, from a word of 

277#: `Lexicon.bound_seconds` or a pair of `Lexicon.bound_second_phrases` 

278#: ('عز' before 'الدين'), beside BOUND_PHRASE_TAG: group joins such a 

279#: pair at the first name word too (rules/P12, #1072). Dropped from the 

280#: published token like the kind tags above. 

281BOUND_SECOND_TAG = "vocab:bound-second" 

282#: rules/O9 ("the capitals settle the field"): a word in capitals that 

283#: Policy.capitals_as_family read as the family, written by post_rules, 

284#: so assemble reads its reading as the shape's (a word in capitals) 

285#: rather than its position's. 

286CAPITALS_FAMILY_TAG = "capitals-family" 

287 

288#: EITHER way a token joins the ambiguous credential class -- the 

289#: vocabulary's claim and the writing's. The two emitters that report 

290#: a fork the peel called and declined ask exactly this: `_group`'s 

291#: prefix chain (a listed member the case lean read as a name, 'John 

292#: van der Berg Ma'; a by-shape member the count left standing, 

293#: 'Freiherr von Berg X.Y.I.') and `_assign`'s family-comma slot. One 

294#: constant beside the two above and for their reason -- the pair was 

295#: spelled two ways, a frozenset here and an `or` of two `in` tests 

296#: there -- and a frozenset so each test is one `isdisjoint`, a C call 

297#: with no Python frame, on a branch every chained name reaches. 

298_AMBIGUOUS_CREDENTIAL_TAGS = frozenset( 

299 {AMBIGUOUS_ACRONYM_TAG, SHAPE_ACRONYM_TAG}) 

300 

301# SPLIT_CREDENTIAL_TAG and SPLIT_MEMBER_TAG are defined and explained in 

302# _types beside SHAPE_ACRONYM_TAG, case repair reading them too. 

303 

304#: The roles that make a piece a name word (rules/P6's walk), and 

305#: the roles of a word not yet read as one: a suffix, or nothing yet 

306#: -- what `_pieces.particle_tail` reads, asked by assign's given-part 

307#: walk when it reaches the credential run, whose words are unread. 

308NAME_ROLES = (Role.GIVEN, Role.MIDDLE, Role.FAMILY) 

309SUFFIX_OR_UNREAD = (Role.SUFFIX, None) 

310 

311 

312class Structure(Enum): 

313 """The comma structure: segment writes NO_COMMA or FAMILY_COMMA, 

314 and group's head decides a comma form once classify has tagged the 

315 words, which may make it SUFFIX_COMMA (#613, `_comma.decide`).""" 

316 

317 NO_COMMA = auto() 

318 FAMILY_COMMA = auto() # "Family, Given ..." (v1 lastname-comma) 

319 SUFFIX_COMMA = auto() # "Given Family, Suffix ..." 

320 

321 

322@dataclass(frozen=True, slots=True) 

323# rules/A1: "the parse completes on the best reading and carries an 

324# ambiguity report naming the doubt, as parsing never fails on any 

325# input" -- its Then clause: this is the report's mid-pipeline record, 

326# by token index (decisions/A1) 

327class PendingAmbiguity: 

328 """An ambiguity recorded mid-pipeline by token INDEX; assemble 

329 materializes real Ambiguity objects over the final tokens. 

330 

331 ``origin`` is for the one stage that runs BEFORE tokens exist: 

332 extract_delimited knows only a character offset, so it records that 

333 and tokenize resolves it to the containing token's index. Stages 

334 after tokenize set ``indices`` directly and leave ``origin`` None. 

335 

336 ``field_tail`` is for a report that names the field its word was 

337 read into. post_rules may still move the word (H1's move behind a 

338 title, P1's family-first fold, P6's attachment, and under opt-in 

339 policies the patronymic rotations, O6's two family names and 

340 `middle_as_family`'s fold), 

341 so the emitter 

342 writes ``detail`` up to the field and the rest of its sentence 

343 here -- ``""`` where the field ends the sentence, which is why 

344 assemble tests ``is not None`` -- and assemble joins them around 

345 the FIELD_READING of the first referent's final role, the one 

346 place that knows it (#626). Until then ``detail`` is a fragment. 

347 """ 

348 

349 kind: AmbiguityKind 

350 detail: str 

351 indices: tuple[int, ...] = () 

352 origin: int | None = None 

353 field_tail: str | None = None 

354 alternative: PendingReading | None = None 

355 

356 

357class Deferred(Enum): 

358 """A PendingReading field its emitter cannot name yet.""" 

359 

360 #: O5's: a lone name word read as one of the two primary fields 

361 #: would be read as the other, named from its FINAL role by 

362 #: assemble, since H1 or a rotation may still move it after the 

363 #: emitter (#626's reason for ``field_tail``). 

364 OTHER_PRIMARY = auto() 

365 #: classify's connective: the letter read as a connective would 

366 #: join the name words on either side into one, whose field assign 

367 #: names once it has positions -- the positional read's, where the 

368 #: join would merge two pieces, and the letter's own piece's 

369 #: (`Beside`), where both words are already in it. 

370 JOINED = auto() 

371 #: group's particle chain: the particle it chained would stand as a 

372 #: name word of its own in front of the piece, named by assign. 

373 UNCHAINED = auto() 

374 

375 

376@dataclass(frozen=True, slots=True) 

377class Beside: 

378 """A PendingReading field named from another token's: the reading 

379 lands where the token at `index` lands, named by assemble from that 

380 token's final role -- a word the name piece in front would take in 

381 (a particle chain, which runs to the end of the name words, or a 

382 bound given name), or a connective whose join stays inside its own 

383 piece. Where P6 then attached that token to the family 

384 (`FOLDED_TAG`), which it would not have done with a word behind 

385 it, `unfolded`, the field the word held when the report was made, 

386 stands instead. Where the piece in front is a chain, `last` is its 

387 last word: rules/P10 reads a chain's opening phrase as a middle name 

388 and leaves its last word the family, where the word would join, so 

389 a `last` still in the family names the field (#704).""" 

390 

391 index: int 

392 unfolded: Role | None = None 

393 last: int | None = None 

394 

395 

396@dataclass(frozen=True, slots=True) 

397class PendingReading: 

398 """The reading a report's decision did not take, as its emitter 

399 knows it; assemble turns it into the public Reading. 

400 

401 ``role`` is the field the first referent would hold under that 

402 reading, with every other word of the name read as the parse read 

403 it, a `Deferred` form for a stage that runs before the field is 

404 known, or `Beside` for a field another token's final role names. 

405 A JOINED or UNCHAINED form assign leaves unresolved -- a referent 

406 that ends outside every name position -- surfaces as no 

407 alternative rather than a guess. Assemble also folds a MIDDLE into 

408 the family under ``middle_as_family``, the one later rule that 

409 moves a field whatever word stands in it.""" 

410 

411 kind: ReadingKind 

412 source: ReadingSource 

413 role: Role | Deferred | Beside 

414 

415 

416#: How a report names the field a word was read into, by final role. 

417FIELD_READING: Mapping[Role, str] = MappingProxyType({ 

418 Role.TITLE: "a title", Role.GIVEN: "a given name", 

419 Role.MIDDLE: "a middle name", Role.FAMILY: "a family name", 

420 Role.SUFFIX: "a suffix", Role.NICKNAME: "a nickname", 

421 Role.MAIDEN: "a maiden name"}) 

422# every role a referent can hold, or a new one is a KeyError at the 

423# first parse whose report lands in it 

424assert FIELD_READING.keys() == set(Role) 

425 

426 

427@dataclass(frozen=True, slots=True) 

428class ParseState: 

429 """Carried through the stage fold. Frozen; stages return copies via 

430 copy_with. Fields are filled progressively: 

431 extract_delimited -> extracted/masked; tokenize -> tokens (span- 

432 sorted)/comma_offsets/interpunct_offsets (the 间隔号 and fullwidth-stop offsets the 

433 order and segmentation decisions consult, #298; the nakaguro 

434 separators record NOTHING); segment -> segments/structure/one_case 

435 (lazily, only where C2's flag asks for it -- #289/#516, #613); 

436 script_segment -> tokens and segments again (the one stage that 

437 changes the token COUNT: an unspaced CJK token, or a word glued at 

438 its full stop before any comma (rules/T8), splits into n+1 pieces, 

439 still as sub-slices of the original, and every later index in the 

440 segment runs shifts by n; the slash after a title opening the name 

441 or the given part after a family comma is cut off its word where 

442 glued and its token dropped, rules/T9, every later index remapped 

443 by the net count); classify -> token tags AND 

444 one_case; group -> structure (its head decides a comma form, #613) 

445 AND the SUFFIX/TITLE roles of a postnominal part after the comma, 

446 whose segment it empties so no join reaches it, 

447 then pieces/piece_tags/dropped AND maiden token roles, plus the 

448 SUFFIX/TITLE roles of the run a maiden take gives up (#601), AND 

449 tail_reads, S2's trailing run read once before its joins (#614); 

450 assign -> the remaining token roles AND `order`, the effective 

451 order it read them under, AND the folded-middle and attached tags 

452 on the particles P6's attachment joins after a family comma (#613); 

453 post_rules -> roles again (the TITLE and SUFFIX roles of a clause 

454 S1 sets apart, each word's comma trimmed off its text and span, 

455 #792; a delimited member S13 settles becomes the suffix, #810), 

456 the folded-middle tag on what O3 folds and the 

457 no-comma attachment joins, with the attached tag on the latter, 

458 the second-surname tag on the words of the family's second unit 

459 where O6 reads two or W5 reads a Han surname pair (rules/R10), the 

460 first-surname tag on the words of its first unit (rules/R11), and the ambiguity P6's no-comma 

461 attachment 

462 reports (#467) and SUFFIX_OR_NICKNAME on a member it leaves a 

463 nickname. 

464 Ambiguities are recorded by every stage that DECIDES one -- 

465 extract (resolved to a token index by tokenize), segment, 

466 script_segment, classify, group, assign, and post_rules -- since a 

467 fork whose branches are taken in different stages needs an emitter 

468 in each. Post-group, segments may retain indices of dropped tokens 

469 -- assign iterates pieces, never segments. This ownership map is 

470 pinned by tests/v2/pipeline/test_state.py. 

471 

472 segmenter belongs to no stage: like original/lexicon/policy it is 

473 passed in at construction by Parser.parse and only ever READ (by 

474 script_segment, for a token the vocabulary declined).""" 

475 

476 original: str 

477 lexicon: Lexicon 

478 policy: Policy 

479 #: The optional Parser(segmenter=...) hook; None = not configured. 

480 segmenter: Segmenter | None = None 

481 extracted: tuple[tuple[Role, Span], ...] = () 

482 masked: tuple[Span, ...] = () 

483 tokens: tuple[WorkToken, ...] = () 

484 comma_offsets: tuple[int, ...] = () 

485 interpunct_offsets: tuple[int, ...] = () 

486 segments: tuple[tuple[int, ...], ...] = () 

487 structure: Structure = Structure.NO_COMMA 

488 # pieces[s][p] = run of token indices: piece p of segment s. 

489 # piece_tags[s][p] = derived flags for that piece ("title", "prefix", 

490 # "suffix", "conjunction") set by group's joins. 

491 pieces: tuple[tuple[tuple[int, ...], ...], ...] = () 

492 piece_tags: tuple[tuple[frozenset[str], ...], ...] = () 

493 dropped: tuple[int, ...] = () # structural tokens (maiden markers) 

494 #: rules/S2's trailing run per segment, as group read it ONCE 

495 #: after P3's joins and before the particle chain (#614), for 

496 #: assign to place and report 

497 #: rather than peel again; None where group read none -- a family 

498 #: comma's parts, a part past a comma, a segment of fewer than 

499 #: three pieces, a run with a name piece inside it -- and assign 

500 #: reads those for itself, as it does a name group's joins left 

501 #: without a name word. Aligned with `pieces`. 

502 tail_reads: tuple[TailRead | None, ...] = () 

503 #: The order `assign` actually READ the name under -- name_order, 

504 #: or the script_orders entry that overrode it. None wherever no 

505 #: positional read happened: after a family comma (which fixes the 

506 #: family, so assign consults no order at all), and on every early 

507 #: return in `_assign_main`, where a segment holds no name piece 

508 #: to position. Recorded rather than recomputed downstream, 

509 #: because the two can differ and a post_rules rule keyed on 

510 #: `policy.name_order` would then disagree with the roles assign 

511 #: already wrote (#395). Reaching that divergence needs a custom 

512 #: lexicon -- every shipped particle is Latin, and Latin has no 

513 #: script_orders entry -- which is why the test for it builds its 

514 #: own (test_post_rules.py). 

515 order: tuple[Role, Role, Role] | None = None 

516 #: Whether the name's OWN words are written wholly in one case -- 

517 #: all upper or all lower alike -- and so carry no case EVIDENCE 

518 #: about any word in them (rules/P3's own-words span, 

519 #: _pieces.own_words). None means NOT ASKED YET: the fact is 

520 #: computed by whichever of segment and classify needs it first, 

521 #: segment only when C2's flag on a part past the second comma asks 

522 #: for it, so a reader between the two stages sees None and must 

523 #: not guess -- script_segment asks for itself there (#613). 

524 #: Recorded rather than recomputed, the way `order` above is: the 

525 #: trailing suffix slot, the post-comma slot, the tail-segment 

526 #: reading, the prefix chain's own tail measure (_group) and the 

527 #: glued-honorific peel's decline of a post-comma run 

528 #: (_script_segment) all consult it and must not disagree 

529 #: (#289/#516, decisions/S6). Five stages read it in all -- 

530 #: segment, script_segment, classify, group and assign -- plus the 

531 #: two predicate layers they read it through (_pieces, _vocab). 

532 #: A fact segment records SURVIVES script_segment, the one stage 

533 #: that changes the token count, and survives it unrecomputed 

534 #: because splitting a token cannot change the answer: the verdict 

535 #: is `is_one_case` over the name's own words JOINED, and a split 

536 #: only moves a space into a string whose upper/lower comparison 

537 #: ignores spaces entirely -- '김민준씨' and '김민준 씨' fold alike. 

538 #: So the field is carried through rather than invalidated, and 

539 #: script_segment reads it where segment recorded it (its suffix-run 

540 #: predicate takes the lean), asking for itself only where segment 

541 #: did not, without recording the answer (`_one_case`). 

542 one_case: bool | None = None 

543 ambiguities: tuple[PendingAmbiguity, ...] = () 

544 

545 

546def _copy_refusals(cls: type) -> list[str]: 

547 """Why a field copy of `cls` might not build what 

548 `dataclasses.replace` builds, one reason per unmet condition. 

549 

550 `replace` calls `obj.__class__(...)`, and every hook that call can 

551 run -- a metaclass `__call__`, a `__new__`, the `__init__` and any 

552 `__setattr__` it goes through, a `__post_init__`, an `InitVar` it 

553 demands for want of a default -- is one a field copy skips. These conditions are a 

554 TRIPWIRE for a realistic edit to the pipeline's three classes, not 

555 a proof against any class at all: a forged `__qualname__` on a 

556 borrowed `__init__` combined with its own decoration, or a 

557 `__class__` property, is out of scope, and `copy_with` copies 

558 nothing but those three anyway.""" 

559 reasons = [] 

560 params = cls.__dict__.get("__dataclass_params__") 

561 if params is None: 

562 reasons.append("not decorated as a dataclass itself") 

563 elif not params.frozen: 

564 reasons.append("not frozen") 

565 init = cls.__dict__.get("__init__") 

566 # dataclasses compiles the __init__ it generates from a string and 

567 # names it after the class; one written in a class body carries its 

568 # source file, and one borrowed from another class keeps that 

569 # class's name. 

570 if (init is None or init.__code__.co_filename != "<string>" 

571 or init.__qualname__ != f"{cls.__qualname__}.__init__"): 

572 reasons.append("__init__ not generated for it") 

573 init = None 

574 fields = dataclasses.fields(cls) 

575 if init is not None: 

576 # an InitVar is an __init__ parameter that is not a field 

577 code = init.__code__ 

578 taken = code.co_argcount + code.co_kwonlyargcount - 1 

579 if taken != sum(f.init for f in fields): 

580 reasons.append("__init__ does not take exactly its init fields") 

581 if type(cls) is not type: 

582 reasons.append("built by a metaclass") 

583 if any("__new__" in vars(k) for k in cls.__mro__[:-1]): 

584 reasons.append("defines __new__") 

585 if hasattr(cls, "__post_init__"): 

586 reasons.append("defines __post_init__") 

587 if not all(f.init for f in fields): 

588 reasons.append("has an init=False field") 

589 return reasons 

590 

591 

592def _copyable_fields(cls: type) -> tuple[str, ...]: 

593 """The fields `copy_with` carries for `cls`, or TypeError naming 

594 every condition of `_copy_refusals` it fails.""" 

595 reasons = _copy_refusals(cls) 

596 if reasons: 

597 raise TypeError( 

598 f"copy_with cannot copy {cls.__name__}: it needs a frozen " 

599 "dataclass whose generated __init__ only assigns its fields " 

600 f"({'; '.join(reasons)})") 

601 return tuple(f.name for f in dataclasses.fields(cls)) 

602 

603 

604#: Built once, at import: a pipeline class that stops qualifying fails 

605#: here rather than in a parse, and `copy_with` copies nothing else. 

606_COPY_FIELDS: Mapping[type, tuple[str, ...]] = MappingProxyType({ 

607 cls: _copyable_fields(cls) 

608 for cls in (WorkToken, PendingAmbiguity, PendingReading, ParseState)}) 

609 

610_T = TypeVar("_T") 

611 

612if TYPE_CHECKING: 

613 # mypy's dataclass plugin checks replace's keywords against the 

614 # class, which a `**changes: object` signature would not. 

615 from dataclasses import replace as copy_with 

616else: 

617 def copy_with(obj: _T, /, **changes: object) -> _T: 

618 """`dataclasses.replace` for the pipeline's own dataclasses, 

619 without its per-call cost: a direct field copy, which for the 

620 classes in `_COPY_FIELDS` builds the same object 

621 (decisions/parse-cost has the measurement).""" 

622 cls = type(obj) 

623 names = _COPY_FIELDS.get(cls) 

624 if names is None: 

625 raise TypeError( 

626 f"copy_with copies only the pipeline's own dataclasses, " 

627 f"not {cls.__name__}") 

628 new = object.__new__(cls) 

629 for name in names: 

630 value = changes.pop(name) if name in changes else getattr(obj, name) 

631 object.__setattr__(new, name, value) 

632 if changes: 

633 raise TypeError(f"{cls.__name__} has no field named " 

634 f"{', '.join(sorted(changes))}") 

635 return new