1"""Not a stage: rules/C1's decision, made by group at its head.
2
3The comma's structure is decided ONCE, after classify has tagged every
4word and before group joins any of them (#613): the part after the
5first comma is read by `_pieces.segment_suffix_reading`, the one
6reading a part that holds no name word gets, with the words C4's count
7licenses as credentials behind a whole name. Where it reads as the
8postnominal part its roles are set here, so no join in group and no
9walk in assign can reach them, and the comma is a suffix comma when
10the part before it is a whole name; otherwise the family comma
11`segment` handed over stands, and assign reads the listing form.
12
13Deciding in `segment`, before the tags existed, meant predicting what
14later stages would do -- group's particle chain (#562's pair), assign's
15reading of a run the capitals settle -- and assign re-deciding #296's
16positional read with a second count; reading once and binding is
17mechanisms.md#READ-WITHOUT-THEN-BIND.
18
19Reads: Lexicon suffix, title, particle and ambiguous-class vocabulary
20through the tags classify wrote and through _vocab.name_word_count and
21_vocab.is_wholly_suffix; every Lexicon wordlist through
22_vocab.caps_shape_candidate (to know an all-caps word is unlisted) and
23_vocab.claimed_as_non_name (the name's contrast); Lexicon
24.maiden_markers through _pieces.own_words, for the name's contrast;
25Lexicon.generation_words, Lexicon.suffix_words_ambiguous and
26Lexicon.suffix_acronyms_ambiguous, for a chunk of a joined word beside
27a pair of capitals (rules/C5);
28Lexicon.capitalization_exceptions, a credential's case mask, for rules/C13's
29given-name Except; Policy.lenient_comma_suffixes, Policy.extra_suffix_delimiters,
30Policy.unlisted_caps_suffixes and Policy.unlisted_dotted_suffixes.
31"""
32from __future__ import annotations
33
34import unicodedata
35from collections.abc import Sequence, Set
36
37from nameparser._lexicon import Lexicon, _normalize
38from nameparser._pipeline._pieces import (
39 split_credential_report,
40 has_name_content, is_suffix_piece, is_title_piece, join_connectives,
41 listed_lean, own_words, segment_suffix_reading, settled_by_case,
42)
43from nameparser._pipeline._state import (
44 AMBIGUOUS_ACRONYM_TAG, AMBIGUOUS_WORD_TAG, GENERATION_WORD_TAG,
45 GIVEN_ABBREVIATION_TAG, SHAPE_ACRONYM_TAG,
46 SPLIT_CREDENTIAL_TAG, SPLIT_MEMBER_TAG, ParseState, PendingAmbiguity,
47 PendingReading, Structure, WorkToken, copy_with,
48)
49from nameparser._pipeline._vocab import (
50 ROMAN, caps_shape_candidate, claimed_as_non_name,
51 composed_len, delimiter_cores, ends_in_a_generation, glued_cores,
52 glued_stem, glues, is_caps_word, is_mixed_caps_word,
53 is_letter_run, is_paired_initials, is_single_letter_numeral,
54 is_wholly_suffix, _joined_chunks, _listed_whole,
55 name_reading, name_word_count, reads_as_generation, suffix_reading,
56 surname_unit_facts, unit_ends, written_as_a_name,
57)
58from nameparser._policy import CapsSuffixes
59from nameparser._types import AmbiguityKind, Role
60
61
62def _pieces(seg: Sequence[int], tokens: Sequence[WorkToken],
63 splits: bool = True,
64 ) -> tuple[list[list[int]], list[set[str]]]:
65 """One piece per token but a split credential (`split_pair`, read
66 off the tag classify wrote on its first word), which group's first
67 merge builds (group alone declines a pair at the head of the
68 string, rules/S2) -- the part as it stands before any join: the
69 Ph./D. pair tagged "suffix" where the lexicon lists `phd` as
70 unambiguous suffix vocabulary, any other "split", a member of the
71 ambiguous class for rules/C4's count, unless `splits` is False.
72 Every piece a fresh list, as `join_connectives` requires: it
73 extends a joined piece's first list in place."""
74 pieces: list[list[int]] = []
75 ptags: list[set[str]] = []
76 k = 0
77 while k < len(seg):
78 a = seg[k]
79 tags = tokens[a].tags
80 if k + 1 < len(seg) and (SPLIT_CREDENTIAL_TAG in tags
81 or splits and SPLIT_MEMBER_TAG in tags):
82 pieces.append([a, seg[k + 1]])
83 ptags.append({"suffix" if SPLIT_CREDENTIAL_TAG in tags
84 else "split"})
85 k += 2
86 else:
87 pieces.append([a])
88 ptags.append(set())
89 k += 1
90 return pieces, ptags
91
92
93def _reading_pieces(part: Sequence[int], tokens: Sequence[WorkToken],
94 splits: bool = True,
95 ) -> tuple[list[list[int]], list[set[str]]]:
96 """The part as the reading takes it: `_pieces`, then the one join it
97 can hold."""
98 pieces, ptags = _pieces(part, tokens, splits)
99 # The one join a postnominal part can hold, made here so the reading
100 # sees it: rules/P3's connective joining its neighbours where the
101 # neighbour it takes its kind from is a title, which makes the
102 # joined part a title ('Mr. and Mrs.', 'Secretary of State', 'Dr.
103 # and'), a run of connectives merging first as it does in the name
104 # ('Minister of the Interior'). A LONE single-letter connective is
105 # left as it stands, P3 or P8 reading it as a name word or an initial in
106 # short names; one beside another connective is a member of their
107 # run and joins with it ('Mr. y and Mrs.'). Any other join is not
108 # made here: where no credential opens the part, a name word in it
109 # makes it the given part; where one does, the run #603 opens takes
110 # the connective as a word and reports it ('John Smith, PhD and
111 # Dr.'). Group's own joins, the one loop since #617: its copy here
112 # merged no run and joined 'Minister of the' alone.
113 #
114 # rules/P3: "A connective that is also generational vocabulary
115 # joins only where a name word stands on each side of it" -- and in
116 # a part read for credentials none does, so every such connective
117 # is frozen here, where group freezes only the ones it finds without
118 # a name word beside them ('Rovira, Dr. i i' keeps suffix 'i i'
119 # rather than run-merging the pair into the title, #617); a
120 # neighbour's join may still take one in ('Smith, Dr. and i' reads
121 # title 'Dr. and i'), as `join_connectives` says.
122 #
123 # The same walk says whether there is anything to join, and a part
124 # with no connective left free -- nearly every part -- skips the
125 # shared loop, whose predicate calls cost two frames per word
126 # ('Smith, John' paid two; #617's review).
127 frozen: set[int] = set()
128 free = False
129 for i in part:
130 tags = tokens[i].tags
131 if "conjunction" in tags:
132 if "vocab:suffix" in tags:
133 frozen.add(i)
134 else:
135 free = True
136 if free:
137 join_connectives(pieces, ptags, tokens, letter_stays=True,
138 titles_only=True, frozen=frozen)
139 return pieces, ptags
140
141
142def _unclaimed_name_word(text: str, lexicon: Lexicon) -> bool:
143 """A word written as a name and claimed by no wordlist as anything
144 else -- #564's contrast word and rules/C12's veto, one question.
145 The caller tests for a period first, in C: a word with one is an
146 abbreviation or an initial, not a name word."""
147 return (written_as_a_name(text)
148 and not claimed_as_non_name(_normalize(text), lexicon))
149
150
151def _name_contrast(state: ParseState, seg0: Sequence[int],
152 clause_at: int | None = None) -> bool:
153 """#564 (Derek): the contrast the caps shape needs is the NAME's,
154 and the name carries it only if one of its own words before the
155 comma (no maiden clause, no delimited content, as `own_words`
156 defines them) is written the way a name is written in mixed case
157 -- a capital in it and its last letter lowercase
158 (`written_as_a_name`) -- and is not claimed as a title, particle,
159 connective, credential or generation (`claimed_as_non_name`); a
160 word with a period is an abbreviation or an initial, not one. A
161 lone capital ('de GAULLE C'), a lowercase-only word and a surname
162 written in capitals with anything glued in front ("d'ESTAING",
163 'FitzGERALD', 'McDONALD') all fail it, so such a record keeps its
164 given name beside its lowercase particles, clauses and titles and
165 beside a mixed-case credential ('LLOYD WEBBER, ANDREW PhD'). A part
166 with no lowercase at all is settled in one C-level comparison.
167 `clause_at` is `own_words`' clause index where the caller already
168 holds it."""
169 before = "".join([state.tokens[i].text for i in seg0])
170 if before == before.upper():
171 return False
172 if clause_at is None:
173 _, clause_at = own_words(state.tokens, state.comma_offsets,
174 state.lexicon._sets.maiden_markers)
175 lex = state.lexicon
176 return any(
177 i < clause_at and (tok := state.tokens[i]).role is None
178 and "." not in tok.text and _unclaimed_name_word(tok.text, lex)
179 for i in seg0)
180
181
182def _whole_name(seg0: Sequence[int], tokens: Sequence[WorkToken],
183 one_case: bool | None) -> bool:
184 """rules/C3's count before the comma for an unambiguous
185 credential, read off classify's tags (the ambiguous class's count
186 of NAME words, which leaves titles out, is
187 `_vocab.name_word_count`'s, asked in `decide`): two or more units (a particle run and
188 the name word it attaches to one unit, a connective join not, #575)
189 holding a word that is not a suffix word -- a title counts, being a
190 word to the count an unambiguous credential takes, and so does a
191 suffix word opening the part with a name word behind it. A numeral
192 ending the part, or standing before the suffix words that end it,
193 that the trailing fork reads as the generation is no name word, as
194 a listed one is not (`one_case` is
195 ParseState.one_case, for that fork)."""
196 # rules/C3: "a particle run and the one name word it attaches to are
197 # one word"
198 # the part before a family comma merges no member pair (rules/S12)
199 pieces, ptags = _pieces(seg0, tokens, False)
200 named: set[int] = set()
201 opener: list[int] = []
202 name_behind = False
203 for k, (piece, tags) in enumerate(zip(pieces, ptags)):
204 if not is_suffix_piece(piece, tags, tokens):
205 named.update(piece)
206 # a title behind it is a word to this count but no name
207 # word, asked only once a suffix word has opened the part
208 if opener and not is_title_piece(piece, tags, tokens):
209 name_behind = True
210 elif k == 0 and SPLIT_MEMBER_TAG not in tokens[piece[0]].tags:
211 opener = piece
212 # rules/C3: "A suffix word opening the part is a name word to the
213 # count where a name word follows it" -- a split credential's
214 # member is half a credential, not a name (rules/S12)
215 if name_behind:
216 named.update(opener)
217 # rules/C3: "a numeral ending the part, or standing before the
218 # listed suffix words it ends with, that the trailing fork reads as the
219 # generation is no name word" ('Dumas VI, Jr.' and 'Dumas VI MD,
220 # Ed' as their 'III' twins); decisions/C3 (#893). The suffix
221 # words are the pieces the loop above left out of `named`. The
222 # `ROMAN` match is a test the predicate makes itself
223 # (`reads_as_generation`'s first), asked here at C level so a part
224 # ending in no numeral pays no frame for it, as group's count does
225 e = len(seg0) - 1
226 while e > 0 and seg0[e] not in named:
227 e -= 1
228 if (e > 0 and ROMAN.match(tokens[seg0[e]].text.rstrip(".")) is not None
229 and ends_in_a_generation(
230 [tokens[seg0[e - 1]].text, tokens[seg0[e]].text], one_case)):
231 named.discard(seg0[e])
232 if len(named) < 2:
233 return False
234 idx = list(seg0)
235 names = 0
236 start = 0
237 for end in unit_ends([surname_unit_facts(tokens[i].tags, k == 0)
238 for k, i in enumerate(idx)], chain=False):
239 if not named.isdisjoint(idx[start:end]):
240 names += 1
241 if names > 1:
242 return True
243 start = end
244 return False
245
246
247def _members(seg: Sequence[int], tokens: Sequence[WorkToken]) -> set[int]:
248 """The positions in `seg` of split credentials' members, for
249 `name_word_count`'s opening word (rules/S12), on the one-letter
250 numeral's rare path; `decide` scans for them inline."""
251 members: set[int] = set()
252 for k, i in enumerate(seg):
253 if SPLIT_MEMBER_TAG in tokens[i].tags:
254 members.add(k)
255 return members
256
257
258def _behind_a_generation(state: ParseState, seg0: Sequence[int],
259 p1: Sequence[list[int]], pt1: Sequence[set[str]],
260 tokens: Sequence[WorkToken], contrast: bool | None,
261 ) -> tuple[bool, ...] | None:
262 """rules/C12's reading of the part after the comma, or None where
263 the listing form stands: behind a whole name ending in a suffix
264 word, or in a numeral the trailing fork reads as the generation,
265 the part is the credential run, its titles (a word or a run a
266 connective joins) reading as titles, unless a word of it is
267 written as a name. The caller has tested the tag, or the numeral
268 shape with `ROMAN`, as a cheap filter. The part's veto is asked
269 first, being the cheap question and the one a listing with a given
270 name answers ('Garcia Lopez Jr., Juan'). `contrast` is C6's answer
271 where `decide` has already asked it, else None."""
272 # two name words and the generation at least: exact, since
273 # `_whole_name` needs two units in front ('Smith VI, AD')
274 if len(seg0) < 3:
275 return None
276 lex = state.lexicon
277 reading: list[bool] = []
278 for p, pt in zip(p1, pt1):
279 # a title reads as a title, a word or a run a connective joins
280 # ('Mr. and Mrs.', a dual inside it included); a lone dual of
281 # the title and the suffix vocabulary is the suffix here, the
282 # slot being postnominal ('John Smith Jr., AD VC'): C13's two
283 # predicates, asked in C13's order
284 title = (not is_suffix_piece(p, pt, tokens)
285 and is_title_piece(p, pt, tokens))
286 for i in p:
287 tok = tokens[i]
288 # rules/C12: "a word of it written as a name, or an
289 # initial, keeps the listing form" -- unlisted, and a word
290 # with a period is an abbreviation, as for the contrast;
291 # paired initials are initials, as C5 keeps them ('J.A.')
292 if "initial" in tok.tags or (
293 is_paired_initials(tok.text) if "." in tok.text
294 else _unclaimed_name_word(tok.text, lex)):
295 return None
296 reading.append(not title)
297 last = tokens[seg0[-1]].text
298 # a numeral by shape alone (VI to X) is the generation the trailing
299 # fork reads, as the listed ones are (#610's class: 'VI' beside 'V'
300 # and 'III'), and not one it reads as an initial's neighbour
301 # ('John J VI, AD'). C12's evidence is broader than a generation:
302 # any suffix word ('Jr.', 'Esq.') counts, by its tag
303 if ("vocab:suffix-word" not in tokens[seg0[-1]].tags
304 and not reads_as_generation(
305 last, tokens[seg0[-1]].tags, tokens[seg0[-2]].text,
306 state.one_case)):
307 return None
308 # the generation set aside, the name's own words in front of it are
309 # a whole name: 'Smith VI' is one word and a numeral, as 'Smith III'
310 # is, and a maiden clause is no word of the name ('Jane nee Smith
311 # Jr., AD' reads as 'Jane Jr., AD'; own_words, as for the contrast)
312 _, clause_at = own_words(state.tokens, state.comma_offsets,
313 lex._sets.maiden_markers)
314 front = [i for i in seg0[:-1]
315 if i < clause_at and tokens[i].role is None]
316 if not _whole_name(front, tokens, state.one_case):
317 return None
318 # a one-letter numeral is the generation only where the name has a
319 # word to spare for it, a title being none (rules/S10), and is no
320 # evidence where the name reads it as a name word ('Dr. Smith V,
321 # AD', whose title is a word to the count above but none here)
322 if (len(last.rstrip(".")) == 1 and is_single_letter_numeral(last)
323 and name_word_count([tokens[i].text for i in front], lex,
324 state.policy,
325 letters_one_case=state.one_case,
326 members=_members(front, tokens)) < 2):
327 return None
328 if contrast is None:
329 contrast = _name_contrast(state, seg0, clause_at)
330 if not contrast:
331 return None
332 return tuple(reading)
333
334
335def _given_part(token: WorkToken) -> PendingReading:
336 """The name reading of a word this decision bound as a credential:
337 the comma's other branch makes the part the given part, and with
338 every other word of it read as the decision read it, the word is
339 its given name (rules/C1's listing form)."""
340 return name_reading(token, Role.GIVEN)
341
342
343def _lone_word(state: ParseState, seg0: Sequence[int]) -> bool:
344 """Whether the head before the comma is one word as written, for
345 rules/C16's run of initials (#1238), where C4's count reads one name
346 word: a word the count leaves out as a title is a word here
347 ('Ashley Knight, M.S. BME'), and so is a particle unless written in
348 lower case in a head that holds a capital, in a name of mixed case
349 ('de Waart, J.P.', but 'Bin Zhang, M.D.', whose 'Bin' is as likely
350 the given name, and 'du juan, M.D.', written all in lower case). A
351 suffix word, or a numeral in capitals, of two or more letters ending
352 the head behind a word is none ('Jansen Jr., J.P.', 'Jansen VI,
353 J.P.', but 'Le Vi, M.D.' and 'Smith V, M.D.' are two words), and a
354 title left alone is no surname ('Dr. VI, M.D.')."""
355 tokens = state.tokens
356 # as C3 counts it: one in front of a word is a word ('Dr.B. Akila.,
357 # M.D'), a single letter ends a whole name (C1)
358 end = len(seg0)
359 while end > 1:
360 token = tokens[seg0[end - 1]]
361 stem = token.text.rstrip(".")
362 if len(stem) < 2 or not ("vocab:suffix" in token.tags
363 or stem.isupper()
364 and ROMAN.match(stem) is not None):
365 break
366 end -= 1
367 word: WorkToken | None = None
368 particle = False
369 for i in seg0[:end]:
370 token = tokens[i]
371 if "particle" in token.tags and token.text.islower():
372 particle = True
373 elif word is not None:
374 return False
375 else:
376 # a capitalized particle is a word ('Le, J.P.' one, 'Bin
377 # Zhang, M.D.' two), and so is a title word
378 word = token
379 if word is None:
380 # an empty head reads as C15 has it, as 'Smith, X' less the
381 # surname
382 return not particle
383 # a title left alone by the walk is no surname ('Dr. VI, M.D.'), a
384 # title word standing alone is one ('Knight, J.P.'); a lower-case
385 # word behind lower-case particles is a name all in lower case
386 return ((end == len(seg0) or "vocab:title" not in word.tags)
387 and not (particle and word.text.islower()))
388
389
390def _company(state: ParseState, seg0: Sequence[int], p: Sequence[int],
391 pt: Set[str], texts: dict[int, str],
392 contrast: list[bool]) -> bool:
393 """Whether one piece beside rules/C16's run is a credential that
394 makes the part the credential run (#1238): a suffix word that is
395 no generation and, if it is title vocabulary too, written in
396 capitals; a word of the ambiguous class; or an unlisted capitals
397 word C6 admits where the name carries its contrast (`contrast`
398 holds that answer once asked). A split credential, or a piece of
399 several words that is a suffix piece ('Ph. D.'), always is; a
400 numeral by shape, like a listed generation, never is."""
401 tokens = state.tokens
402 if "split" in pt:
403 return True
404 if len(p) != 1:
405 return is_suffix_piece(p, pt, tokens)
406 token = tokens[p[0]]
407 text = texts[p[0]]
408 if (GENERATION_WORD_TAG in token.tags
409 or ROMAN.match(text.rstrip(".")) is not None):
410 return False
411 if is_suffix_piece(p, pt, tokens):
412 return ("vocab:title" not in token.tags or text.isupper()
413 or bool(state.one_case))
414 if AMBIGUOUS_ACRONYM_TAG in token.tags:
415 return True
416 if (state.one_case
417 or not caps_shape_candidate(text, state.lexicon, state.policy,
418 one_case=False, mixed_case=True)):
419 return False
420 if not contrast:
421 contrast.append(_name_contrast(state, seg0))
422 return contrast[0]
423
424
425def _a_names_word(state: ParseState, token: WorkToken, text: str) -> bool:
426 """Whether one word beside a pair of capitals is a word a name
427 holds, so that it speaks for no credential (rules/C5, #1323): a
428 particle ('Mc'), a member of the ambiguous class its capitals do
429 not settle ('Ed', and a word the count gates, S11: 'Junior',
430 'Filho', 'KC', which classify tags a member and `settled_by_case`
431 never settles), or a word S3 joins with a slash or a hyphen holding
432 a generation, a gated word or an unsettled member among its chunks
433 ('MD/Jr.', 'Ma/PhD'), a word the vocabulary lists whole being one
434 word. `text` is the word less a glued delimiter."""
435 if "particle" in token.tags:
436 return True
437 if (AMBIGUOUS_ACRONYM_TAG in token.tags
438 and not settled_by_case(token, state.one_case)):
439 return True
440 lexicon = state.lexicon
441 if ("/" in text or "-" in text) and not _listed_whole(text, lexicon):
442 for chunk in _joined_chunks(text, lexicon) or ():
443 folded = _normalize(chunk)
444 if (folded in lexicon._sets.generation_words
445 or folded in lexicon._sets.suffix_words_ambiguous
446 or ROMAN.match(chunk.rstrip(".")) is not None
447 or folded.replace(".", "")
448 in lexicon._sets.suffix_acronyms_ambiguous
449 and (state.one_case or not chunk.isupper())):
450 return True
451 return False
452
453
454def _credentials_beside(state: ParseState, seg0: Sequence[int],
455 p1: Sequence[Sequence[int]],
456 pt1: Sequence[Set[str]], k: int,
457 texts: dict[int, str],
458 contrast: list[bool]) -> bool:
459 """Whether every piece of the part but the undotted pair at `k` is
460 a credential the pair's own writing would not doubt (rules/C5,
461 #1323), at least one of them behind it: a word of C16's company
462 that is no title in front of the pair, no word gated by the count
463 (S11: 'Junior', 'Filho', 'KC') and, where it is a member of the
464 ambiguous class, one its capitals settle ('MA', not 'Ed'); and the
465 name carries C6's contrast, asked here too, so a record in capitals
466 stays the listing form under every caps setting. A particle is no
467 credential ('Mc'), and a word S3 joins with a slash or a hyphen is
468 asked chunk by chunk, as its words written apart would be ('MD/Jr.',
469 'Ma/PhD'), a word the vocabulary lists whole being one word."""
470 tokens = state.tokens
471 for j, (q, qt) in enumerate(zip(p1, pt1)):
472 if j == k:
473 continue
474 if j < k and is_title_piece(q, qt, tokens):
475 return False
476 if (len(q) == 1 and "split" not in qt
477 and _a_names_word(state, tokens[q[0]], texts[q[0]])):
478 return False
479 if not _company(state, seg0, q, qt, texts, contrast):
480 return False
481 if not contrast:
482 contrast.append(_name_contrast(state, seg0))
483 return contrast[0]
484
485
486def _capitals_in_contrast(state: ParseState, seg0: Sequence[int],
487 text: str, contrast: bool | None) -> bool:
488 """Whether a pair, dotted or not, is two capitals in a name that
489 carries rules/C6's contrast, which a later part's credential needs
490 before it speaks for the pair (rules/C5, #1392): 'M.H.' behind
491 'Jane Doe', not 'm.h.' nor a pair behind a record in capitals. The
492 undotted pair is admitted by that contrast by default, and asked
493 here because `CapsSuffixes.EVERYWHERE` tags it without one.
494 `contrast` is C6's answer where the decision has already asked it.
495 The letters are composed first, a combining mark being no
496 capital."""
497 if not all(map(str.isupper, unicodedata.normalize(
498 "NFC", text.replace(".", "")))):
499 return False
500 return _name_contrast(state, seg0) if contrast is None else contrast
501
502
503def _listed_credentials_behind(state: ParseState, seg0: Sequence[int],
504 cores: Set[str], inner: frozenset[str],
505 contrast: list[bool]) -> bool:
506 """Whether a part past the second comma is nothing but listed
507 credentials (rules/C5, #1392), read word by word as the company of
508 a pair in its own part is (`_a_names_word`, then `_company`): a
509 suffix word that is no generation, a title/suffix dual only in
510 capitals, a listed member of the ambiguous class its capitals
511 settle ('MA', not 'Ma'), a credential split across a space
512 ('Ph. D.'); never a word classify tagged a particle (one with a
513 delimiter glued to it carries no such tag and passes, 'Mc;', as in
514 the pair's own part), a word the count gates, a joined word holding
515 a generation or a gated or unsettled chunk ('MD/Jr.'), nor a word
516 read by its shape alone ('XYZ',
517 'X.Y.Z.': untagged, or tagged a member no capitals settle). A
518 delimiter core standing alone is no word of the part ('MD - PhD',
519 rules/C10), and a word with one glued is read without it, as the
520 decision reads the pair's own part ('MD/Jr.;'). Any later part
521 answers, one with no word in it being none."""
522 tokens = state.tokens
523 for seg in state.segments[2:]:
524 texts: dict[int, str] = {}
525 for i in seg:
526 text = tokens[i].text
527 # the stem asked for only where a core is glued, a C-level
528 # test, so a plain word pays no frame for it
529 for core in inner:
530 if core in text and glues(core):
531 text = glued_stem(text, inner) or text
532 break
533 texts[i] = text
534 pieces, ptags = _reading_pieces(seg, tokens)
535 found = False
536 for p, pt in zip(pieces, ptags):
537 if len(p) == 1:
538 token = tokens[p[0]]
539 if token.text in cores:
540 continue
541 if (_a_names_word(state, token, texts[p[0]])
542 or not ("vocab:suffix" in token.tags
543 or AMBIGUOUS_ACRONYM_TAG in token.tags)):
544 break
545 if not _company(state, seg0, p, pt, texts, contrast):
546 break
547 found = True
548 else:
549 if found:
550 return True
551 return False
552
553
554def _run_read_as_initials(state: ParseState, i: int) -> ParseState:
555 """The listing form, with the run of initials at `i` that made the
556 part the given part (rules/C16, #1238) tagged an initial, as a run
557 written apart is, so the given part's walk keeps it a name behind a
558 title ('Jansen, Ir. J.P.'), and the decision reported here where it
559 was taken: the other branch is the credential its letters spell."""
560 tokens = list(state.tokens)
561 token = tokens[i]
562 tokens[i] = copy_with(token, tags=token.tags | {"initial"})
563 return copy_with(state, tokens=tuple(tokens), ambiguities=(
564 *state.ambiguities, _credential_fork(token, i)))
565
566
567def _credential_fork(token: WorkToken, i: int) -> PendingAmbiguity:
568 """The report of the word at `i` after the comma read as a name
569 where the other branch is the credential it spells (rules/C13,
570 rules/C16)."""
571 return PendingAmbiguity(
572 AmbiguityKind.SUFFIX_OR_NAME,
573 f"{token.text!r} after the comma also spells a credential; "
574 f"read as ", (i,), field_tail="",
575 alternative=suffix_reading(token))
576
577
578def _given_name_written_short(part: Sequence[int],
579 tokens: Sequence[WorkToken],
580 one_case: bool | None,
581 lexicon: Lexicon) -> int | None:
582 """The word opening the part after a family comma, behind any titles,
583 that is an unambiguous credential and a given name written short
584 ('Md'), where it is written as the given name: alone in the part with
585 no title in front, in a name of mixed case, with a lower-case letter
586 its credential's own case mask does not write ('Md', not 'PhD'); or
587 with a name word behind it. Its index, else None (`one_case` is
588 ParseState.one_case, None read as mixed case)."""
589 k = 0
590 while k < len(part) and "vocab:title" in tokens[part[k]].tags:
591 k += 1
592 if k == len(part):
593 return None
594 token = tokens[part[k]]
595 if GIVEN_ABBREVIATION_TAG not in token.tags or "vocab:suffix" not in token.tags:
596 return None
597 if k + 1 == len(part):
598 # alone: a title in front leaves the given part's walk nothing
599 # but the title to read as the name, so the part stays the
600 # postnominal one there (decisions/C13 (#1395))
601 if k or one_case or not any(map(str.islower, token.text)):
602 return None
603 bare = token.text.replace(".", "")
604 cased = lexicon._cap_map.get(_normalize(bare), bare.upper())
605 return None if bare == cased else part[k]
606 after = tokens[part[k + 1]]
607 text = after.text.rstrip(".")
608 # a name word: no conjunction, no suffix or title reading, ambiguous
609 # or not, no half of a split credential, a letter, and in a name of
610 # mixed case no word in capitals but an initial, counted in letters
611 # (`composed_len`) so a letter written decomposed is one letter
612 if "conjunction" in after.tags or any(
613 t.startswith(("vocab:suffix", "vocab:title", "split:"))
614 for t in after.tags):
615 return None
616 if not any(map(str.isalpha, text)):
617 return None
618 return (part[k] if one_case or composed_len(text) == 1
619 or not text.isupper() else None)
620
621
622def decide(state: ParseState, splits: bool | None = True) -> ParseState:
623 """The structure of a comma form, and the postnominal part bound.
624 Returns `state` unchanged where the listing form stands.
625
626 `splits` is for the retry below alone: None reads the part with each
627 split credential merged and asks nothing further, False with none
628 merged."""
629 if (state.structure is not Structure.FAMILY_COMMA
630 or len(state.segments) < 2):
631 return state
632 # rules/S12: "where the count declines it, the pair is the two words
633 # it is written as" -- the part read with each split credential
634 # merged, and read again as written where the reading did not take
635 # one as a credential, so a declined pair reads as it reads unmerged
636 # (an 'MB' it hid opens the part again, rules/C13). A loop, and the
637 # retry a call of this function only where a pair stands, so a part
638 # holding none pays no frame for it.
639 if splits:
640 heads: list[int] = []
641 for i in state.segments[1]:
642 if SPLIT_MEMBER_TAG in state.tokens[i].tags:
643 heads.append(i)
644 if heads:
645 out = decide(state, None)
646 if all(out.tokens[i].role is Role.SUFFIX for i in heads):
647 return out
648 return decide(state, False)
649 seg0, seg1 = state.segments[0], state.segments[1]
650 # Nothing after the comma: nothing to read. An EMPTY part BEFORE it
651 # is read on, being no whole name (`_whole_name` answers no):
652 # rules/C15: "the part after it reads as the given part after a
653 # family comma reads" -- so ', PhD' binds its credential as
654 # 'Smith, PhD' does; decisions/C15 (#892), decisions/C1 (#613)
655 if not seg1:
656 return state
657 tokens = list(state.tokens)
658 lex, pol = state.lexicon, state.policy
659 # rules/C10: "a suffix delimiter parts the suffix words on each side
660 # of it as a comma would" -- behind a whole name its cores are
661 # no word of the reading, and leave as group drops them in a tail;
662 # behind one name word the core is a word, v1 having applied the
663 # delimiter to the suffix-comma form alone (C10's core-is-a-word
664 # Accepted entry)
665 cores = delimiter_cores(pol.extra_suffix_delimiters)
666 inner = glued_cores(pol.extra_suffix_delimiters)
667 whole: bool | None = None
668 core_idx: list[int] = []
669 # a loop, and the head counted only where a core stands alone: the
670 # built-in ';', '-' and '/' leave `cores` non-empty for every
671 # policy (D15, #889)
672 if len(seg1) > 1:
673 for i in seg1:
674 if tokens[i].text in cores:
675 core_idx.append(i)
676 if core_idx:
677 whole = _whole_name(seg0, tokens, state.one_case)
678 if not whole:
679 core_idx = []
680 # a set for the membership test: a list scanned per token was
681 # quadratic in the part (#613's PR review, 'MD / '*k under '/')
682 core_set = frozenset(core_idx)
683 part = [i for i in seg1 if i not in core_set] if core_idx else list(seg1)
684 if not part:
685 return state
686 # rules/C13: "A credential that is also a given name written short
687 # opens the given part" -- the tag tested inline, so a part holding
688 # no such word pays no frame for it; the fork reported here, where
689 # it is taken, as a word of the ambiguous class reports it (C4)
690 for i in part:
691 if GIVEN_ABBREVIATION_TAG in tokens[i].tags:
692 short = _given_name_written_short(part, tokens, state.one_case,
693 lex)
694 if short is not None:
695 if whole is None:
696 whole = _whole_name(seg0, tokens, state.one_case)
697 if not whole:
698 return copy_with(state, ambiguities=(
699 *state.ambiguities,
700 _credential_fork(tokens[short], short)))
701 break
702 if pol.unlisted_dotted_suffixes:
703 # rules/S3: "Paired initials are the exception [...] where S4
704 # would count words to spare for them they are the name word
705 # they are written as" -- classify holds the class tag back from
706 # them, and at this comma C5 reads them instead (S3's Precedence
707 # bullet), so they rejoin the class for C5's count. Shape-tagged
708 # and untagged with the switch on is exactly that word
709 # (classify's dotted branch), asked of the tags in C
710 # (decisions/S3 (#864)).
711 for i in part:
712 tags = tokens[i].tags
713 if (SHAPE_ACRONYM_TAG in tags
714 and AMBIGUOUS_ACRONYM_TAG not in tags):
715 tokens[i] = copy_with(
716 tokens[i], tags=tags | {AMBIGUOUS_ACRONYM_TAG})
717 p1, pt1 = _reading_pieces(part, tokens, splits is not False)
718 anchored: list[int] = []
719 absorbed: list[int] = []
720 # A core in the part, standing alone or glued to a word or inside
721 # one: either keeps the part from the listing form's early return,
722 # and only a glued one reads behind any head, a core standing alone
723 # being a word behind one name word (C10's Accepted bullet). The
724 # shape tests below read a word with one glued at an end as the word
725 # without it, as classify tags it ('MBBS;' as 'MBBS'). A loop, so
726 # the listing form pays no frame for it.
727 cored = glued = False
728 texts: dict[int, str] = {}
729 for i in part:
730 text = texts[i] = tokens[i].text
731 here = False
732 if text in cores:
733 cored = True
734 else:
735 for core in inner:
736 if core in text:
737 cored = True
738 if glues(core):
739 here = glued = True
740 if here:
741 stem = glued_stem(text, inner)
742 if stem is not None:
743 texts[i] = stem
744 # The words of the class in the part, and the unlisted all-caps
745 # words the caps shape could admit: only a part holding one asks
746 # the count, so 'Smith, John' and 'John Smith, PhD' never build it.
747 # A split credential is a word of the class too (rules/S3), its
748 # piece tag the test.
749 maybe = [p[0] for p, pt in zip(p1, pt1) if "split" in pt
750 or len(p) == 1
751 and (AMBIGUOUS_ACRONYM_TAG in (tags := tokens[p[0]].tags)
752 or ("vocab:suffix" not in tags
753 # capitals, or the mixed case `_mixed_capitals`
754 # reads, asked here in C by its two ends ('MRes',
755 # 'AuD'; not 'McDonald', which pays no count);
756 # `caps_shape_candidate` decides
757 and ((texts[p[0]].isupper()
758 or texts[p[0]][:2].isupper()
759 or texts[p[0]][-1:].isupper())
760 and (texts[p[0]].isalpha()
761 # the joined spelling ('PU-PH'), the
762 # predicate's other half (rules/S9)
763 or "-" in texts[p[0]]
764 or "/" in texts[p[0]])
765 or not unicodedata.is_normalized(
766 "NFC", texts[p[0]])
767 and (is_caps_word(texts[p[0]])
768 or is_mixed_caps_word(texts[p[0]])))))]
769 # rules/C16: "behind one word, initials run together are the given
770 # name whatever they spell" -- the runs that spell a listed
771 # credential ('J.P.', 'M.A.'), joined to the class so C4's count is
772 # taken where the head may be one word (decisions/C16 (#1238),
773 # #1435). Gathered only
774 # where the part holds a full stop, so 'Smith, John' pays no frame;
775 # a part whose other words are all credentials is C8's run
776 # ('Smith, M.D. Ph.D.').
777 initials_at: int | None = None
778 # whether the run is the part's only entry in `maybe` (no word of
779 # the class and no caps-shape candidate beside it), and, asked only
780 # then, whether the head is one word as C16 reads it (`_lone_word`;
781 # None where not asked, the reading's own test asking it instead)
782 run_alone = False
783 lone_head: bool | None = None
784 for at, p in enumerate(p1):
785 if len(p) == 1 and "." in (text := texts[p[0]]):
786 tags = tokens[p[0]].tags
787 if ("vocab:suffix" in tags
788 and SHAPE_ACRONYM_TAG not in tags
789 and is_letter_run(text)
790 # every letter a capital ('J.씨' is a glued
791 # honorific; NFC first, a combining mark being no
792 # capital), or one case through the whole name; map
793 # over a builtin, so no frame per letter
794 and (all(map(str.isupper, letters := unicodedata.normalize(
795 "NFC", text.replace(".", ""))))
796 or state.one_case
797 and all(map(str.islower, letters)))):
798 # the first run is the one asked about; another run
799 # beside it is company like any credential ('Anderson,
800 # M.T. B.A.')
801 initials_at = p[0]
802 break
803 contrast_box: list[bool] = []
804 # the unlisted capitals words the run's company admitted, marked as
805 # caps-shape credentials below as the count's own are, so case
806 # repair keeps them ('Smith, M.B. ChB' keeps 'ChB' forced, rules/R4)
807 company_caps: list[int] = []
808 if initials_at is not None:
809 # titles in front of the run are the given part's (C16);
810 # behind it a credential is company: a title/suffix dual only in
811 # capitals ('Smith, M.D. MS', but 'Smith, J.P. Ms.'), never a
812 # generation ('Rinehart, J.D. Jr.'), a spaced delimiter none
813 # ('Smith, M.D. / PhD'), and an unlisted capitals word where C6
814 # finds the name's contrast ('Smith, M.D. FRCS')
815 rest = [(p, pt) for k, (p, pt) in enumerate(zip(p1, pt1))
816 if (k > at or k < at and not is_title_piece(p, pt, tokens))
817 and not (len(p) == 1 and texts[p[0]] in cores)]
818 if rest and all(_company(state, seg0, p, pt, texts, contrast_box)
819 for p, pt in rest):
820 initials_at = None
821 # `_company` admits a single unlisted word by the caps shape
822 # alone (its last test)
823 company_caps = [
824 p[0] for p, pt in rest
825 if len(p) == 1 and "split" not in pt
826 and "vocab:suffix" not in tokens[p[0]].tags
827 and AMBIGUOUS_ACRONYM_TAG not in tokens[p[0]].tags]
828 elif initials_at not in maybe:
829 run_alone = not maybe
830 maybe.append(initials_at)
831 # rules/C8: "a part that is nothing but suffix words is the
832 # credential run and reads as suffixes, whole" -- the reading below.
833 # The part is read ONCE: here where it holds no word of the class,
834 # after the count below where it does, with the words the count
835 # licensed (a read here and a second after licensing threw the first
836 # away, #613's /simplify). A part holding a word no vocabulary
837 # claims as a suffix, and none of the class, is the given part: the
838 # listing form stands. (a declared delimiter's core may sit inside a
839 # word, 'RN/CRNA', which only the lenient fallback below reads)
840 reading: tuple[bool, ...] | None = None
841 # rules/C12's evidence, filtered by the tag and a C-level match so
842 # the listing form pays no frame for it ('Smith, John' never calls
843 # the helper)
844 generation = bool(seg0) and (
845 "vocab:suffix-word" in tokens[seg0[-1]].tags
846 or ROMAN.match(tokens[seg0[-1]].text.rstrip(".")) is not None)
847 behind_generation = listing = False
848 # C6's contrast, where the run's company has already asked it
849 contrast: bool | None = contrast_box[0] if contrast_box else None
850 if not maybe:
851 reading = segment_suffix_reading(
852 p1, pt1, tokens, pol.lenient_comma_suffixes, state.one_case,
853 anchored, absorbed)
854 # a word no vocabulary claims as a suffix: the listing form,
855 # unless C12 reads it below, which skips C1's fallback for it
856 listing = reading is None and not all(
857 "suffix" in t or "vocab:suffix" in tokens[p[0]].tags
858 for p, t in zip(p1, pt1))
859 # a part holding a delimiter core ('MD;', 'MD ; PhD') is left
860 # to C1's run test below, which reads a core alone as no word
861 # and a word with one glued as the word without it (rules/C10)
862 if cored:
863 listing = False
864 if listing and not generation:
865 return state
866 names = 0
867 caps: set[int] = set(company_caps)
868 licensed: set[int] = set()
869 run = False
870 # a pair a later comma part's credential spoke for (rules/C5), whose
871 # flip is reported as the count's, dotted or not
872 later = False
873 # C16's run alone in `maybe`, behind a head that is not one word,
874 # asks no count and keeps no books (#1435): the run reads as
875 # initials only behind one word, and with nothing else in `maybe`
876 # the count licenses nothing, `head_named` meets no member and the books find
877 # none, so the reading is the one the count would give ('John
878 # Smith, M.D.'). The run stays in `maybe`, so the part is still read
879 # below as the count's part, never the listing form's
880 if run_alone:
881 lone_head = _lone_word(state, seg0)
882 counted = bool(maybe) and lone_head is not False
883 if counted:
884 # `_members` inline: a frame here is paid by every name with the
885 # ambiguous class after its comma ('John Smith, MA')
886 split_at: set[int] = set()
887 for k, i in enumerate(seg0):
888 if SPLIT_MEMBER_TAG in tokens[i].tags:
889 split_at.add(k)
890 names = name_word_count([tokens[i].text for i in seg0], lex, pol,
891 letters_one_case=state.one_case,
892 members=split_at)
893 if names >= 2:
894 # rules/C6: "an unlisted word in the caps shape (S9), written in
895 # capitals or in a credential's mixed case, joins the ambiguous
896 # credential class (C4, S9) in the part after the comma only where
897 # the name carries the contrast" -- the part after the comma's
898 # half, read once two name words stand before it (decisions/C6
899 # (#564, #1517))
900 for i in maybe:
901 text = texts[i]
902 if SHAPE_ACRONYM_TAG in tokens[i].tags:
903 # tagged by classify (EVERYWHERE); the dotted shape has
904 # a period
905 if "." not in text:
906 caps.add(i)
907 continue
908 if (AMBIGUOUS_ACRONYM_TAG not in tokens[i].tags
909 and pol.unlisted_caps_suffixes is not CapsSuffixes.OFF
910 and caps_shape_candidate(text, lex, pol, one_case=False,
911 mixed_case=True)):
912 if contrast is None:
913 contrast = _name_contrast(state, seg0)
914 # the box the helpers below read, empty until now
915 contrast_box.append(contrast)
916 # a two-capital word is how initials are written: the
917 # paired-initials rule below discards one nothing speaks
918 # for, a lone one included ('John Smith, XY')
919 if contrast:
920 caps.add(i)
921 # rules/C4: "The same count reads a part of two or more words
922 # as the credential run when every word of it is a suffix word
923 # or a word of this class", none of them a single-letter numeral.
924 # the words not of the class are asked as C1's suffix test asks
925 # them, the lenient word test by default ('Ma B.')
926 others: list[str] = []
927 for p, pt in zip(p1, pt1):
928 if ("split" in pt
929 or len(p) == 1
930 and (AMBIGUOUS_ACRONYM_TAG in tokens[p[0]].tags
931 or p[0] in caps)):
932 licensed.add(p[0])
933 else:
934 # a loop, not a comprehension: a listcomp is a frame
935 # per piece on 3.11
936 for i in p:
937 others.append(tokens[i].text)
938 run = (bool(licensed)
939 and (not others or is_wholly_suffix(
940 others, lex, pol, letters_one_case=state.one_case))
941 and not any(len(p) == 1
942 and is_single_letter_numeral(texts[p[0]])
943 for p in p1))
944 if not run:
945 licensed.clear()
946 else:
947 # rules/C5: "Paired initials are the exception to the [...]
948 # count" -- "Only an unambiguous suffix word in front of
949 # them that is not also title vocabulary, or another word
950 # the class admits by its dotted shape standing in the same
951 # part, makes them the credential run"
952 shape = {i for i in licensed
953 if i in caps or SHAPE_ACRONYM_TAG in tokens[i].tags}
954 # Where the first such suffix word stands, found once and
955 # only when a pair asks: a pair is spoken for exactly when
956 # it stands behind that word, so one scan answers every
957 # pair. Asked per pair, the scan re-walked every word in
958 # front of each one, quadratic in the part ('John Smith, ' +
959 # 'VC '*k + 'G.J. '*k, the duals never ending it; #563's
960 # shape, back in #613 and caught in review)
961 speaker = -1
962 for k, p in enumerate(p1):
963 i = p[0]
964 if len(p) != 1 or i not in licensed:
965 continue
966 text = texts[i]
967 if not (is_paired_initials(text)
968 or (i in caps and composed_len(text) == 2)):
969 continue
970 if speaker < 0:
971 speaker = next(
972 (j for j in range(len(p1))
973 if is_suffix_piece(p1[j], pt1[j], tokens)
974 and not is_title_piece(p1[j], pt1[j], tokens)),
975 len(p1))
976 # another shape word than this one: no set built per
977 # pair (a copy of `shape` each time was quadratic in C)
978 if not (speaker < k or len(shape) > 1
979 or (shape and i not in shape)
980 # rules/C5: "undotted, two capitals followed by
981 # credentials and standing beside nothing else
982 # are the credential run" ('Jane Doe, BM PhD');
983 # asked of the one shape word alone, so once
984 # per part (decisions/C5 (#1323))
985 or "." not in text and k + 1 < len(p1)
986 and _credentials_beside(state, seg0, p1, pt1, k,
987 texts, contrast_box)
988 # rules/C5: "alone in its part, two capitals
989 # with a listed credential in a later comma
990 # part are the credential run, dotted or not"
991 # -- asked only where the pair is the whole
992 # part and a later part stands, so no other
993 # name pays a frame for it; C6's contrast is
994 # asked last, of the dotted pair and of an
995 # undotted one EVERYWHERE tagged without it,
996 # so a pair no later part speaks for does not
997 # pay for it (decisions/C5 (#1392))
998 or (later := len(p1) == 1
999 and len(state.segments) > 2
1000 and _listed_credentials_behind(
1001 state, seg0, cores, inner, contrast_box)
1002 and _capitals_in_contrast(
1003 state, seg0, text,
1004 contrast_box[0] if contrast_box
1005 else contrast))):
1006 licensed.discard(i)
1007 caps.discard(i)
1008 if maybe:
1009 lone = (initials_at is not None and names < 2
1010 and (lone_head if lone_head is not None
1011 else _lone_word(state, seg0)))
1012 reading = segment_suffix_reading(
1013 p1, pt1, tokens, pol.lenient_comma_suffixes, state.one_case,
1014 anchored, absorbed, licensed, head_named=names >= 2,
1015 runs=(initials_at,) if lone and initials_at is not None
1016 else ())
1017 if reading is None and lone:
1018 # rules/C16: "behind one word, initials run together are the
1019 # given name whatever they spell" -- the run the reading
1020 # stopped at, the part's first piece that is no title (a
1021 # name word in front of the run made the part the given part
1022 # itself, and the run is that part's to read). Asked before
1023 # C10's glued reading, so 'Smith, J.P.;' is the given name as
1024 # its unlisted twin 'Smith, X.Q.;' is
1025 k = next((j for j, p in enumerate(p1)
1026 if not is_title_piece(p, pt1[j], tokens)), -1)
1027 if k >= 0 and p1[k][0] == initials_at:
1028 return _run_read_as_initials(state, p1[k][0])
1029 if not listing:
1030 if whole is None:
1031 whole = _whole_name(seg0, tokens, state.one_case)
1032 # rules/C1: "By default a recognized suffix word counts even
1033 # written like an initial" -- behind a whole name ('John Smith, V.')
1034 # rules/C10: "A delimiter glued to a suffix word parts it from
1035 # the next as a comma glued there would" -- the part "reads as
1036 # it does with a space in the delimiter's place", behind any
1037 # head, so 'Smith, MD; PhD' reads as 'Smith, MD PhD' does; behind
1038 # one that is not a whole name by the strict test, where "A
1039 # glued word written like an initial is the given name"
1040 # (decisions/C10, D15)
1041 if reading is None and (whole or glued) and is_wholly_suffix(
1042 [tokens[i].text for i in part], lex, pol, one_case=None,
1043 letters_one_case=state.one_case, strict=not whole):
1044 reading = (True,) * len(p1)
1045 # the words of the part C12 reads as suffixes, which its report
1046 # names: a title in the part, a word or a joined run, is no
1047 # credential it took
1048 taken: list[int] = []
1049 if reading is None and generation:
1050 reading = _behind_a_generation(state, seg0, p1, pt1, tokens,
1051 contrast)
1052 if reading is not None:
1053 behind_generation = True
1054 for p, suffix in zip(p1, reading):
1055 if not suffix:
1056 continue
1057 for i in p:
1058 taken.append(i)
1059 text = texts[i]
1060 # #564's marks on an unlisted all-caps word, as the
1061 # caps shape writes them, so case repair keeps 'AD'
1062 # (rules/R4); the C-level filter `maybe` uses first
1063 if ("vocab:suffix" not in tokens[i].tags
1064 and (text.isupper()
1065 and (text.isalpha() or "-" in text
1066 or "/" in text)
1067 # the mixed case C12 reads where the
1068 # count marked nothing ('Dr. Smith
1069 # Jr., AuD', #1517)
1070 or not text.islower()
1071 and not text.istitle()
1072 and is_mixed_caps_word(text)
1073 or not unicodedata.is_normalized(
1074 "NFC", text) and is_caps_word(text))):
1075 caps.add(i)
1076 if reading is None:
1077 return state
1078 # rules/C7: "that reading is final" -- the part is the postnominal
1079 # part, bound here whatever stands before the comma. The comma is a
1080 # suffix comma behind a whole name; behind one name word it stays
1081 # the family comma naming the family.
1082 ambiguities = list(state.ambiguities)
1083 for k, piece in enumerate(p1):
1084 role = Role.SUFFIX if reading[k] else Role.TITLE
1085 for i in piece:
1086 tags = tokens[i].tags
1087 if i in caps:
1088 # #564: the caps shape's marks, as classify writes them
1089 # EVERYWHERE, so case repair keeps 'XYZ' (rules/R4)
1090 tags = tags | {SHAPE_ACRONYM_TAG, AMBIGUOUS_ACRONYM_TAG}
1091 tokens[i] = copy_with(tokens[i], role=role, tags=tags)
1092 # rules/C11: "A decision either way at the comma C1 reads is reported;
1093 # for a run of words the decision is the flip to the credential
1094 # run, reported once over the whole part" -- its Then, which this
1095 # implements, with rules/C11's Then bullet "A run the count leaves
1096 # in the listing form reports as S7 reads the words in it" and
1097 # rules/C11's Except bullet "A flip in which no listed word of the
1098 # ambiguous credential class (C4) takes part is the exception and
1099 # is made in silence" -- "unless what said so is nothing but other
1100 # paired initials, or a listed credential in a later comma part",
1101 # the clause that bullet ends on (decisions/C11 (#544),
1102 # decisions/C5 (#1392)). A run whose every class word is listed and settled by
1103 # its capitals is read on that evidence, not flipped by the count.
1104 # A caps word bound above carries the class tags now, so membership
1105 # is the tag alone; a part with no word of the class has none, and
1106 # skips the bookkeeping (three list comprehensions, a frame each on
1107 # 3.11, on every bound part)
1108 members: list[int] = []
1109 listed: list[int] = []
1110 settled = pair_only = False
1111 if counted:
1112 members = [p[0] for p in p1 if len(p) == 1
1113 and AMBIGUOUS_ACRONYM_TAG in tokens[p[0]].tags]
1114 listed = [i for i in members
1115 if SHAPE_ACRONYM_TAG not in tokens[i].tags]
1116 settled = (bool(members)
1117 and len(listed) == len(members)
1118 and all(listed_lean(tokens[i], state.one_case)
1119 == "credential"
1120 and (names >= 2
1121 or AMBIGUOUS_WORD_TAG not in tokens[i].tags)
1122 for i in listed)
1123 # rules/S6: "a clash settled by the writing is not
1124 # reported" -- a lone word only where it is an
1125 # acronym its capitals settle
1126 and (len(p1) > 1
1127 or settled_by_case(tokens[listed[0]],
1128 state.one_case)))
1129 member_set = frozenset(members)
1130 pairs = [k for k, p in enumerate(p1) if p[0] in member_set
1131 and (is_paired_initials(texts[p[0]])
1132 or (p[0] in caps
1133 and composed_len(texts[p[0]]) == 2))]
1134 # spoken for by each other only: every class word a pair, and
1135 # only titles among the other words in front of the first
1136 pair_only = (len(pairs) >= 2 and len(pairs) == len(members)
1137 and all(p[0] in member_set
1138 or is_title_piece(p, pt, tokens)
1139 for p, pt in zip(p1[:pairs[0]], pt1)))
1140 part_reported = behind_generation
1141 if behind_generation:
1142 # rules/C11: "A decision either way at the comma C1 reads is
1143 # reported" -- here the suffix word before the comma decided it,
1144 # not C4's count, which C12 does not consult
1145 ambiguities.append(PendingAmbiguity(
1146 AmbiguityKind.SUFFIX_OR_NAME,
1147 f"{' '.join(tokens[i].text for i in taken)!r} after the comma "
1148 f"follows {tokens[seg0[-1]].text!r}, so it is read as a "
1149 f"credential run; it may be a name", tuple(taken),
1150 alternative=_given_part(tokens[taken[0]])))
1151 elif whole and run and ((listed and not settled) or caps or pair_only
1152 or later):
1153 part_reported = True
1154 if len(part) == 1:
1155 what = (f"{tokens[part[0]].text!r} after the comma is also an "
1156 f"ordinary name word")
1157 else:
1158 what = (f"{' '.join(tokens[i].text for i in part)!r} after the "
1159 f"comma holds a word that is also an ordinary name word")
1160 ambiguities.append(PendingAmbiguity(
1161 AmbiguityKind.SUFFIX_OR_NAME,
1162 f"{what}; the part before the comma holds {names} name words, "
1163 f"so it is read as a credential run", tuple(part),
1164 alternative=_given_part(tokens[part[0]])))
1165 elif (len(p1[0]) == 1 and p1[0][0] in listed
1166 and not (reading[0]
1167 and settled_by_case(tokens[p1[0][0]], state.one_case))):
1168 # the first word after the comma reports as it always does,
1169 # naming the role bound above: the listing form binds a word
1170 # the reading declines as a title ('John, Si.', #793), and no
1171 # later rule moves a word of the emptied part; one its capitals
1172 # settled as the credential does not
1173 i = p1[0][0]
1174 field = "a credential" if reading[0] else "a title"
1175 ambiguities.append(PendingAmbiguity(
1176 AmbiguityKind.SUFFIX_OR_NAME,
1177 f"{tokens[i].text!r} after the comma is also an ordinary name "
1178 f"word; read as {field}", (i,),
1179 # the fork is credential or name: a word the reading
1180 # declined is bound as a title, and its other branch is the
1181 # credential
1182 alternative=(_given_part(tokens[i]) if reading[0]
1183 else suffix_reading(tokens[i]))))
1184 # rules/S7: "A member the company decides reports the fork as a
1185 # counted pick does" -- reported where it decided: a member the
1186 # anchor read as a credential after its own writing declined (#544)
1187 for k in anchored:
1188 i = p1[k][0]
1189 ambiguities.append(PendingAmbiguity(
1190 AmbiguityKind.SUFFIX_OR_NAME,
1191 f"{tokens[i].text!r} behind a credential after the comma is "
1192 f"also an ordinary name word; read as a credential", (i,),
1193 alternative=_given_part(tokens[i])))
1194 # rules/C13: "A credential opening the part after a family comma
1195 # makes it the postnominal part however it goes on" -- each word it takes that
1196 # would have made it the given part, as #602's run reports them
1197 for k in absorbed:
1198 # a split credential the run takes reports itself, below
1199 if has_name_content(p1[k], tokens) and "split" not in pt1[k]:
1200 text = " ".join(tokens[i].text for i in p1[k])
1201 ambiguities.append(PendingAmbiguity(
1202 AmbiguityKind.SUFFIX_OR_NAME,
1203 f"{text!r} follows a credential, so it reads as part of the "
1204 f"suffix run; it may be a name word", tuple(p1[k]),
1205 alternative=_given_part(tokens[p1[k][0]])))
1206 # rules/S12: "where the count takes the pair, the reading is reported"
1207 # -- C4's count took it, unless the flip it took part in reported
1208 # the part
1209 if not part_reported:
1210 for k, piece in enumerate(p1):
1211 if "split" in pt1[k] and reading[k]:
1212 ambiguities.append(
1213 split_credential_report(piece, tokens,
1214 _given_part(tokens[piece[0]])))
1215 # Every word of the part is bound above or dropped as a core, so the
1216 # segment hands group nothing to join -- emptied here, where the
1217 # binding is, as #601's take removes what it binds, rather than
1218 # filtered out again in group (#613's /simplify)
1219 return copy_with(state, tokens=tuple(tokens),
1220 segments=state.segments[:1] + ((),)
1221 + state.segments[2:],
1222 structure=(Structure.SUFFIX_COMMA
1223 if whole or behind_generation
1224 else Structure.FAMILY_COMMA),
1225 ambiguities=tuple(ambiguities),
1226 dropped=tuple(state.dropped) + tuple(core_idx))