diff --git a/docs/AGENTS.md b/docs/AGENTS.md index 485064dd0..48c95c570 100644 --- a/docs/AGENTS.md +++ b/docs/AGENTS.md @@ -22,7 +22,7 @@ The rules below were distilled from PR #588, which restructured `customize.rst` **A recipe is a doctest; an edge case is a unit test.** A *recipe* — how to do the thing the reader came to do — belongs in the docs as a `.. doctest::` block, which teaches and is CI-checked at once. The line between the two is whether the prose states the behavior: a claim the section makes to the reader (`edd` repairs to `EDD`, not a mask) earns a doctest beside it, which is what keeps the claim true; an edge case the prose has no reason to mention earns one sentence at most and a unit test, never a doctest (PR #216). An example sitting as prose inside a table cell is the worst of both: it teaches from the wrong place and nothing checks it. -**An example must be non-vacuous.** Show the baseline before the customization, and check that they differ: an `add(titles={"chancellor"})` example (2.x's spelling) once shipped (fixed in 0ab19fdb) where `chancellor` was already a default title, so the add was a no-op and the doctest passed demonstrating nothing. Prefer a word absent from the defaults for a teachable reason (`dean`, which is also a given name). +**An example must be non-vacuous.** Show the baseline before the customization, and check that they differ: an `add(titles={"chancellor"})` example (2.x's spelling) once shipped (fixed in 0ab19fdb) where `chancellor` was already a default title, so the add was a no-op and the doctest passed demonstrating nothing. Prefer a word absent from the defaults for a teachable reason (`dean`, which is also a given name). Run each recipe's example without its edit too and check that the output moves: #1534's review found docs/migrate.rst removing `alhaj` as a religious title (it is a style), the doctest green throughout because the output shown held with or without the call. `Lexicon.remove` warns where no file and no earlier add holds the reading named (#1535), which catches that shape, but not an edit that takes a reading the example never reaches. **An example must run warning-free.** Readers paste examples, so a warning the doctest build prints is one every reader gets. Fix the example, not the build: a `Lexicon.empty()` used only to drop titles also dropped the Korean surnames and drew the segmenterless warning, and the fix was an example that empties only the field it is about. Run the doctest build under Verifying below and expect no output at all. diff --git a/docs/customize.rst b/docs/customize.rst index 69fedea97..7e8063917 100644 --- a/docs/customize.rst +++ b/docs/customize.rst @@ -169,6 +169,41 @@ its category: >>> Parser(lexicon=lean).parse("Professor Robert Johns").title '' +A remove that can take nothing warns. One naming a kind the word does +not hold lists the kinds it does, one naming a word no vocabulary file +and no earlier ``add`` lists asks you to check its spelling, and each +opens with the call and "changes nothing". ``alhaj`` is a style, not a +religious title: + +.. doctest:: + + >>> import warnings + >>> with warnings.catch_warnings(record=True) as caught: + ... warnings.simplefilter("always") + ... inert = Lexicon.default().remove("alhaj", kind="religious") + >>> print(caught[0].message) + remove('alhaj', kind='religious') changes nothing: 'alhaj' has no 'religious' reading in any vocabulary file or earlier add(); it holds: style. Did you mean remove('alhaj', kind='style')? + >>> Parser(lexicon=inert).parse("Alhaj Ahmed Khan").title + 'Alhaj' + +A reading some file holds counts even where it is off by default, since +a choice of languages may turn it on, and so does one the same lexicon +added earlier. A fragment meant to remove a word another lexicon adds +warns, since ``remove`` cannot see the lexicon it will be joined with. +Do the remove on the joined lexicon, or filter that one warning by its +message, never by its category, which would hide every other warning: + +.. doctest:: + + >>> with warnings.catch_warnings(): + ... warnings.filterwarnings("ignore", message=r"remove\('zzq'") + ... fragment = Lexicon.empty().remove("zzq", kind="title") + >>> with_zzq = Lexicon.default().add("zzq", kind="title") + >>> Parser(lexicon=with_zzq).parse("Zzq Ana Smith").title + 'Zzq' + >>> Parser(lexicon=with_zzq | fragment).parse("Zzq Ana Smith").title + '' + Seeing what the vocabulary says about a word ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/docs/design/decisions/vocabulary-model.md b/docs/design/decisions/vocabulary-model.md index 43a64bd6f..fdbfa70ca 100644 --- a/docs/design/decisions/vocabulary-model.md +++ b/docs/design/decisions/vocabulary-model.md @@ -25,6 +25,7 @@ The vocabulary was a set of base sets plus marker subsets (`particles` and `part - The configure-by-reading API: `add(*words, kind, **properties)` and `remove(*words, kind=None)` (a `familiar` or `spelling` remove also taking the pairs to drop, `short_for=[...]` or `spelling_of=[...]`, 2026-11-15 #1404), the views reading a word's kind from the lexicon, `readings_of` returning a public `LexiconReading` and a repr counting readings by kind, a five-part state (base, ordered edit log, choice, lists, masks) compared structurally, a clash a later choice exposes raised at `parser_for` naming the choice, the choice recorded on the `Lexicon` with chained choices unioning, the default's base lazy, built in 4i-a to 4i-d with no default parse moving; since 3.1 a 2.x pickle is refused, naming the re-pickle under 3.0, and an old spelling refused naming docs/migrate.rst's table of kinds — 2026-11-02 #754, the `Lexicon` surface (Derek); 2026-11-02 #754, sub-phase 4i-a; 2026-11-02 #754, sub-phase 4i-b; 2026-11-02 #754, sub-phase 4i-c; 2026-11-02 #754, sub-phase 4i-d; 2026-11-08 #1003. - A whole kind is taken out with `remove(kind=..., every=True)`, every word's readings of it going, those a later choice turns on included, and `words(kind=..., **properties)` lists the words holding a reading of a kind or category — 2026-11-02 #1007, a kind as a whole (Derek). - Configured by reading, an `add` of a title reading that a `given` reading keeps a title only inside a phrase warns, naming `remove(w, kind="given")`, save one that only updates a held title reading's properties — 2026-11-01 #754, the title warning (Derek). +- A `remove` of a reading no vocabulary file holds, on by default or not, and no earlier `add` of the lexicon gave, warns, its message naming which of five cases it is; a remove of every word's readings and a `familiar` or `spelling` remove are not judged, a fragment removing a word another lexicon adds warns too, and an `add` repeating a held reading does not — 2026-11-22 #1535. - A `Locale` may carry CLDR-shaped render patterns, display and sorting, a later addition whose shape is agreed; how a call reaches one is open — 2026-10-28 #754, render patterns. - 3.0's output model keeps the seven roles and adds every new field as a view, read from `Token.reading`, the reading each token took, or for `surname2` from rules/O6's tag: `generation`, `credentials` and, since 2026-11-03, `honorifics` partitioning `suffix` (decisions/R8), `patronymic`, and `surname2` where rules/O6 read two family names; `middle` and `surnames` keep their meaning, a compound given name being a rule a caller or pack turns on; the default `str()` renders a name in the order it was read in with its written separators in a normalized form, through `render(spec: str | None = None)`, `None` being that default; a language file's `[rules]` compile into its `Locale`'s policy patch — 2026-10-28 #754 (Derek). - `surname2` is read from O6's mark as `Token.reading` publishes it, `Reading.second_surname`, a field not compared, and not from a published tag, which would make an O6 parse unequal to its 2.x pickle (decisions/R10) — 2026-10-29 #754, sub-phase 4d. @@ -653,3 +654,5 @@ Open: [#1145](https://github.com/derek73/python-nameparser/issues/1145), the dis - **Accepted:** under strict `ms`, a ruler's style opening a name reads the given name, as it does by default and under `locales.MS` (`Sultan Rahmat ibni Sultan Kamil` → given 'Sultan'); behind a style it stays the title where the style is read (`His Majesty Sultan Rahmat` under strict `ms` + `en`; strict `ms` alone drops en.toml's `his` and `majesty`, before this change and after). - **The pairs re-taken here stay ungated, as wanted:** under a strict choice the word is the particle that language writes. Re-taken 2026-11-21 on `81a24221` by the same score with each tag's ungated words given back their `given` reading: `ben` under strict `ar` fixes 62 records (Tunisia 45, Algeria 9, Morocco 8), `bin` under strict `ms` 6 (ORCID 2, PatentsView 4), `del`, `la`, `san` and `santa` under strict `it` 7, `del`, `la` and `san` under strict `fil` 2, `da`, `do` and `santa` under strict `pt-BR` 1, each breaking none. Read record by record, nearly all are a family name written first with the boxes filed that way round (`Ben Amri Salma`, given box `Ben Amri`): strict reads the whole name as the family (rules/P1's fold, `Ben Amri Salma` → family 'Ben Amri Salma'), wrong too, and the gate agrees with the boxes only because it reads the first word as a given name, so neither reading is the name and the gate's is no better. The rest are a given name the particle is spelled like: of another origin (`Bin Qiaoyu`, the Chinese given name, in Malaysia; `La Thuy`), a cost accepted under strict's premise that its data is of one origin (docs/locales.rst, "Reading one language only": strict is "for data you know to be of one origin"), which answers the issue's second question for `Bin`; and one of the language's own (`La Reina Dimaculangan`, a Philippine given name), a cost of reading `la` as the particle that the premise does not answer, left with the pair. - **Not weighed here:** the rest of `STRICT_UNGATED`, which stays as it was: `gd`, `hr`, `sk`, `sl` and `hi`, and `marquis`, `marquise`, `tho`, `st` and `sushri`, which the issue's samples held too rarely to say anything (its first open question); the pairs of `nl`, `fr`, `ca` and `ga`, which moved none of the 822 records the issue's table read for them, so no reading of a record weighs them; `pt` and `pt-PT` (the issue's table read `pt` with `pt-BR` and holds no `pt-PT`; only `pt-BR` is re-taken here); and `my`'s ranks, which joined after the issue (#1483) and are titles, not particles, their given names written only in en.toml. None is decided as wanted by this entry (#1463). + +- 2026-11-22 #1535 — `Lexicon.remove` WARNS WHERE NO VOCABULARY FILE HOLDS THE READING IT NAMES, AND NO EARLIER `add` OF THE LEXICON GAVE IT. Decided 2026-11-22. A remove of a kind the word does not hold, or of a word in no file, took nothing and said nothing, so it could not be told from a working one: docs/migrate.rst's recipe removed `alhaj` as `kind="religious"`, a style, and its doctest passed because the assertion shown held with or without the call (found by #1534's review). THE RULE: for each word of `remove(*words, kind=...)`, the kinds held are every kind the reading index gives the word (`_reading_index.readings_of`, every file's rows whether on by default or not, the word looked up as `remove` stores it) and every kind an `add` earlier in the lexicon's log gave it, a joined lexicon's included; the call warns where no held kind is the one asked or, for a category, of it, and with no kind where the word holds none. A word named twice in one call warns once. THE MESSAGE opens with the call and "changes nothing", so a caller filters one by it, and names its case: (i) the word holds other kinds, listed, with `remove(word, kind=K)` offered only where one kind is plainly meant (the single held kind of the asked kind's category, else the single held kind of all) and never a `familiar` or `spelling` kind, whose remove reaches name matching's pairs; (ii) the word holds no reading but stands in the `surnames` or `given_names` list, which `remove` does not edit, and the kind asked is the list's (none, `family` or `name` for the surnames, none, `given` or `name` for the given names), with the `dataclasses.replace` that drops it offered; (iii) it holds no reading of its own but is the other name of other words' `familiar` or `spelling` pairs, found in the reading index as well as the lexicon's compiled pairs, with the pair remove offered; (iv) it is a suffix acronym or a dotted title written with its full stops, the spellings the parse reads as the bare word (`remove("Ph.D.", kind="credential")`, stored `ph.d`, the vocabulary's `phd`), and the message names the bare word; it offers the call on the bare word where the reading the dotted spelling is read by (the bare word's suffix reading if it is a suffix acronym, else its title reading, in the files or an earlier add) is of the kind asked, or, with no kind asked, is of exactly one kind, which the call names (`remove("M.D.")` offers `remove("md", kind="credential")`, leaving `md`'s given reading, Muhammad written short), and otherwise lists the kinds the dotted spelling is read by and offers nothing; a suffix word written with stops is no such spelling (`J.R.` is not read as `jr`). Accepted: the offered call takes the vocabulary's reading, while rules/S3's dotted shape (`Policy.unlisted_dotted_suffixes`) still reads `Ph.D.` or `D.D.S.` as a suffix by its shape; (v) it is in no file and no earlier add, and the message says to check its spelling or, where a lexicon this one is joined with adds it, to remove it from the joined lexicon. Each offered call is run by a test and checked to take what the inert one missed. Not judged: a remove with no words (`every=True`), and the `familiar` and `spelling` pair removes, which match by folded forms through name matching's index. WHERE: in `Lexicon.remove` alone, through `_warn_at_caller`, so it names the caller's own line through a chained call and inside `Parser(lexicon=...)`; never where a constructor replays the log or a pickle loads. WHY A WARNING: the edit misparses nothing, so a raise is wrong by the invariants rule (AGENTS.md: invariants guard harm, not no-ops), and it is statically decidable and indistinguishable from a working edit, the construction-time warning's case. ACCEPTED, decided 2026-11-22 over staying silent on a fragment built on `Lexicon.empty()`, which would have cost every hand-built fragment its typo check, packs included: a fragment meant to remove a word another lexicon adds warns, since `remove` cannot see the lexicon it will be joined with (tests/v2/test_parser.py's pack-fragment join asserts it); its caller filters that warning by its message, never by category, or does the remove on the joined lexicon, as case (v)'s message and docs/customize.rst say. A fragment removing a file's reading, which is how a pack is written, stays silent. A word spelled in a way the fold does not reach warns as unknown, the intended signal. DECLINED: the same warning on an `add` of a reading the word already holds with the same properties, the issue's open point. An inert remove leaves a reading the caller wanted gone, so the parse is not what they asked for; a redundant add leaves the reading the caller wanted present, so the parse is what they asked for, and its usual cause is a recipe a later release made unnecessary, so the warning would fire on working code after an upgrade each time a release ships a word a caller had added, teaching callers to ignore it. MEASURED on `ffc5d23c` with this change: no parse moves (`tools/differential/snapshot.jsonl` byte-identical), and the reference parse's frames do not move (`tools/perf/call_count.py --against origin/master`: 195.72 on py3.11 both sides), `remove` not being on the parse path; no shipped pack, plain or strict, warns; outside this change's own tests, three removes in the tests named readings nothing held (tests/v2/test_lexicon.py's remove-before-add, test_match.py's `zzrobert`, test_parser.py's pack fragment), each exercising an inert remove on purpose; in docs/, README.rst and tools/, none besides the two examples docs/customize.rst adds to show the warning. diff --git a/docs/release_log.rst b/docs/release_log.rst index dc7c9f74d..44cbc49eb 100644 --- a/docs/release_log.rst +++ b/docs/release_log.rst @@ -46,6 +46,7 @@ Release Log - **Change locales.HR and locales.SL to read two family names, as locales.CS and locales.SK do.** ``parser_for(locales.HR).parse("Ana Puž Kukuljan")`` gives family ``Puž Kukuljan``, where 3.0.0 through 3.1.0 gave middle ``Puž``, family ``Kukuljan``; with no given-name list, a second given name is read as a family name too (``Janez Jože Novak`` gives family ``Jože Novak`` under ``locales.SL``), and a family comma keeps both as before. :issue:`1190` - **Change locales.PT_BR to read two family names, and add locales.PT_PT, which reads names from Portugal the same way.** ``parser_for(locales.PT_BR).parse("Ana Souza Lima")`` gives family ``Souza Lima``, where 3.0.0 through 3.1.0 gave middle ``Souza``, family ``Lima``; a second given name on the packs' Portuguese given-name list stays where it stands (``Ana Beatriz Costa`` keeps family ``Costa``), and ``locales.PT``, chosen for Portuguese names from any country, is unchanged. ``locales.PT_PT`` also reads four given names Portugal writes behind a particle and Brazil does not (``Maria do Rosário Pinto`` gives middle ``do Rosário``, as ``do Carmo``, ``da Conceição`` and ``da Luz`` do). :issue:`1453`, :issue:`1189` - **Change the Spanish given-name lists, rewritten from their tool.** ``parser_for(locales.ES_AR).parse("Juan Gerhard Lopez")`` gives family ``Gerhard Lopez``, where 3.0.0 through 3.1.0 gave middle ``Gerhard``; nine words leave locales.ES_AR's list (``Gerhard``, ``Zuleyma`` among them) and nine join it (``Azhar``, ``Houari``, ``Grace``), each joining reading as a middle name where it read as the first family name, and locales.ES's gains ``Lahcen`` and drops ``Rim``. :issue:`1471`, :issue:`1476` + - **Add a warning when Lexicon.remove names a reading no vocabulary file holds, which took nothing and said nothing.** ``Lexicon.default().remove("alhaj", kind="religious")`` now warns ``remove('alhaj', kind='religious') changes nothing: 'alhaj' has no 'religious' reading in any vocabulary file or earlier add(); it holds: style. Did you mean remove('alhaj', kind='style')?``, where 3.0.0 through 3.1.0 returned the lexicon unchanged in silence. A fragment that removes a word another lexicon adds, when the two are joined, warns too, since the call cannot see that lexicon. :issue:`1535` * 3.1.0 - November 16, 2026 diff --git a/nameparser/_lexicon.py b/nameparser/_lexicon.py index 9c880ef92..15d492172 100644 --- a/nameparser/_lexicon.py +++ b/nameparser/_lexicon.py @@ -286,6 +286,19 @@ def _reject_buffer(value: object, label: str, plural: str) -> None: ) +@functools.cache +def _pair_names(category: str) -> frozenset[str]: + """Every name a shipped `category` reading (familiar or spelling) + lists as its pair's other name, `short_for` or `spelling_of`, read + from the reading index once: the names #1535's warning tells apart + from a word in no file, whatever pairs a lexicon has compiled.""" + ri = _index_module() + prop = ri.MATCHING_LISTS[category] + return frozenset( + _normalize(name) for r in ri.index() if r.kind == category + for name in r.props.get(prop) or ()) + + def _warn_at_caller(message: str) -> None: # A fixed stacklevel always lands on library internals: the call # depth differs per entry point (Lexicon(), add(), unpickle, @@ -2588,7 +2601,23 @@ def remove(self, *words: str, kind: str | None = None, empty ``remove(*words, kind=...)`` never takes out a whole kind. Removing a reading the word does not hold changes nothing now, and is kept: a later choice of languages may turn that reading - on. + on. Where no vocabulary file holds the reading, on by default or + not, and no :meth:`add` earlier in this lexicon's log (a joined + lexicon's included) gave it, the edit can never take effect, and + the call warns with a ``UserWarning`` (#1535); a remove of every + word's readings and a ``familiar`` or ``spelling`` pair remove + are not judged. The message opens with the call and "changes + nothing", and says which case it is: a word holding other kinds + (they are listed, and the call to paste offered where one is + plainly meant, never a pair kind); a word held only in the + ``surnames`` or ``given_names`` list, which ``remove`` does not + edit (the ``dataclasses.replace`` that drops it); a word held + only as the other name of other words' ``familiar`` or + ``spelling`` pairs (the pair remove that reaches them); or a + word in no file and no earlier add. A fragment meant to remove a word + another lexicon adds warns, since ``remove`` cannot see the + lexicon it will be joined with: filter that warning by its + message, or do the remove on the joined lexicon. A ``familiar`` or ``spelling`` reading is a pair of given names, stored on one of the two and read by name matching both ways, so @@ -2637,10 +2666,132 @@ def remove(self, *words: str, kind: str | None = None, "word's readings of it, e.g. remove(kind='title', " "every=True)") edit = _make_edit("remove", words, kind, pairs) + for message in self._inert_removes(edit): + _warn_at_caller(message) return dataclasses.replace(self, _edits=self._edits + (edit,)) # -- private helpers -------------------------------------------------- + def _inert_removes(self, edit: _Edit) -> list[str]: + """A warning for each word of a `remove` that no vocabulary file + and no `add` earlier in this lexicon's log (a joined lexicon's + included) gives a reading of the kind asked (any reading, with + no kind), so that the edit can take effect under no choice of + languages (#1535). A file's reading counts whether it is on by + default or not, since a choice may turn it on. Read at `remove` + alone, never when a constructor replays the log or a pickle + loads. A remove of every word's readings (no words) and the + familiar and spelling pair removes, which match names by their + folded forms, are not judged. Each message opens with the call + and "changes nothing", so a caller filters one by it.""" + ri = _index_module() + kind = edit.kind + if not edit.words or (kind is not None and ri.CATEGORY.get( + kind, kind) in ri.MATCHING_ONLY): + return [] + added: dict[str, set[str]] = {} + for earlier in self._edits: + if earlier.op == "add" and earlier.kind is not None: + for w in earlier.words: + added.setdefault(w, set()).add(earlier.kind) + messages = [] + for w in dict.fromkeys(edit.words): + held = {r.kind for r in ri.readings_of(w)} | added.get(w, set()) + if kind is None and held: + continue + if kind is not None and any( + k == kind or ri.CATEGORY[k] == kind for k in held): + continue + call = (f"remove({w!r})" if kind is None + else f"remove({w!r}, kind={kind!r})") + head = f"{call} changes nothing: " + if held: + messages.append(head + self._other_kinds(w, kind, held)) + else: + messages.append(head + self._no_reading(w, kind, added)) + return messages + + def _other_kinds(self, w: str, kind: str | None, + held: set[str]) -> str: + """Case (i) of #1535: the word holds readings, none of `kind`. + The call to paste is offered only where one kind is plainly the + one meant: the single held kind of the asked kind's category, + else the single held kind of all; a familiar or spelling kind is + never offered, its remove reaching name matching's pairs.""" + ri = _index_module() + kinds = sorted(held) + candidates = [k for k in kinds if ri.CATEGORY[k] not in + ri.MATCHING_ONLY] + same = [k for k in candidates + if ri.CATEGORY[k] == ri.CATEGORY.get(kind or "", kind)] + offer = (same[0] if len(same) == 1 else + candidates[0] if not same and len(candidates) == 1 else None) + text = (f"{w!r} has no {kind!r} reading in any vocabulary file or " + f"earlier add(); it holds: {', '.join(kinds)}") + if offer is not None: + text += f". Did you mean remove({w!r}, kind={offer!r})?" + return text + + def _no_reading(self, w: str, kind: str | None, + added: dict[str, set[str]]) -> str: + """Cases (ii) and (iii) of #1535: the word holds no reading. It + may stand in the two lists, which remove() does not edit, be + only the other name of other words' familiar or spelling pairs, + which a remove of the pair kind takes, or be a suffix acronym or + a dotted title written with its full stops (``ph.d``, held as + ``phd``), where the bare word holds the kind asked; else it is + in no file.""" + ri = _index_module() + lists = {"surnames": ("family", "name"), "given_names": ("given", "name")} + for list_field, kinds in lists.items(): + if w in getattr(self, list_field) and ( + kind is None or kind in kinds): + return (f"{w!r} holds no reading, only an entry in this " + f"lexicon's {list_field} list, which remove() does " + f"not edit; drop it with dataclasses.replace(" + f"lexicon, {list_field}=lexicon.{list_field} - " + f"{{{w!r}}})") + pair_kind = ("familiar" if self._familiar_forms(w) + or w in _pair_names("familiar") else + "spelling" if self._alternate_spellings(w) + or w in _pair_names("spelling") else None) + if pair_kind is not None: + return (f"{w!r} holds no reading of its own, only the other " + f"name of {pair_kind} pairs other words hold; " + f"remove({w!r}, kind={pair_kind!r}) takes those pairs") + # only where the parse reads the dotted spelling as the bare word: + # a suffix acronym (M.D. as md) or a dotted title (U.S. as us), + # and the bare word holds the kind asked + bare = w.replace(".", "") + bare_kinds = ({r.kind for r in ri.readings_of(bare)} + | added.get(bare, set())) + # the kind the dotted spelling is read by: a suffix acronym's + # suffix reading, a dotted title's title one (M.D. is md's + # credential, not its given reading, Muhammad written short) + read_as = {k for k in bare_kinds if ri.CATEGORY[k] == ( + "suffix" if bare in self._sets.suffix_acronyms else "title")} + if bare != w and bare in (self._sets.suffix_acronyms + | self._sets.dotted_titles): + text = (f"the vocabulary writes {w!r} without its full stops, " + f"as {bare!r}") + asked = [k for k in read_as if kind is not None + and (k == kind or ri.CATEGORY[k] == kind)] + if kind is None and len(read_as) == 1: + offer: str | None = next(iter(read_as)) + elif len(asked) == 1: + offer = kind + else: + offer = None + if offer is not None: + return text + (f": did you mean remove({bare!r}, " + f"kind={offer!r})?") + return text + (", read with its full stops as " + + ", ".join(sorted(read_as))) + return (f"{w!r} is in no vocabulary file and no earlier add() of " + f"this lexicon; check its spelling, or, where a lexicon " + f"this one is joined with adds it, remove it from the " + f"joined lexicon") + def _pool(self) -> Pool: return self._files.pool() diff --git a/tests/v2/test_lexicon.py b/tests/v2/test_lexicon.py index 45dcb2b70..11025bff8 100644 --- a/tests/v2/test_lexicon.py +++ b/tests/v2/test_lexicon.py @@ -1407,7 +1407,10 @@ def test_two_lexicons_are_equal_when_their_logs_are_as_written() -> None: def test_a_later_edit_reads_after_an_earlier_one() -> None: lex = Lexicon.empty() assert lex.add("x", kind="title").remove("x")._sets.titles == frozenset() - assert lex.remove("x").add("x", kind="title")._sets.titles == {"x"} + # a remove before the add it would undo takes nothing, and warns (#1535) + with pytest.warns(UserWarning, match="'x' is in no vocabulary file"): + removed_first = lex.remove("x") + assert removed_first.add("x", kind="title")._sets.titles == {"x"} def test_replace_carries_the_base_and_the_log() -> None: @@ -2219,6 +2222,277 @@ def test_words_finds_a_spelling_of_several_by_any_word_it_names() -> None: assert lexicon.words(kind="given", same_as="charles") == ("chas",) +# -- a remove that takes nothing (#1535) ------------------------------------ +# +# remove() warns where no vocabulary file and no earlier add() of the +# lexicon gives the word a reading of the kind asked, since such an edit +# takes effect under no choice of languages. + +_INERT_REMOVES = [ + # a kind the word does not hold: the warning names the kinds it does + pytest.param(lambda L: L.remove("alhaj", kind="religious"), + ["'alhaj' has no 'religious' reading", "style", + "remove('alhaj', kind='style')"], id="wrong-kind"), + # a word in no file, with a kind and without one + pytest.param(lambda L: L.remove("zzyzx", kind="title"), + ["remove('zzyzx', kind='title') changes nothing", + "in no vocabulary file"], id="unknown-word"), + pytest.param(lambda L: L.remove("zzyzx"), + ["remove('zzyzx') changes nothing", + "in no vocabulary file"], id="unknown-word-no-kind"), + # a category none of whose kinds the word holds + pytest.param(lambda L: L.remove("alhaj", kind="name"), + ["'alhaj' has no 'name' reading", + "remove('alhaj', kind='style')"], id="category-none-held"), +] + + +@pytest.mark.parametrize("call, expected", _INERT_REMOVES) +def test_a_remove_that_takes_nothing_warns( + call: Callable[[Lexicon], Lexicon], expected: list[str]) -> None: + with pytest.warns(UserWarning) as record: + removed = call(Lexicon.default()) + assert len(record) == 1 + message = str(record[0].message) + for part in expected: + assert part in message, message + # the edit is still logged, as before + assert len(removed._edits) == 1 + + +_MESSAGE_CASES = [ + # several kinds held, none in the asked category: no call offered + pytest.param(lambda L: L.remove("dean", kind="particle"), + "it holds: family, given, office", None, id="several-kinds"), + # the asked category's one held kind is offered + pytest.param(lambda L: L.remove("dean", kind="religious"), + "it holds: family, given, office", "remove('dean', kind='office')", + id="same-category"), + # a pair kind is never offered: its remove reaches name matching + pytest.param(lambda L: L.remove("don", kind="title"), + "it holds: familiar", None, id="pair-kind-only"), + pytest.param(lambda L: L.remove("olha", kind="given"), + "it holds: spelling", None, id="spelling-only"), + # a kind held through the lexicon's own earlier add + pytest.param(lambda L: L.add("zzq", kind="office").remove("zzq", kind="family"), + "in any vocabulary file or earlier add(); it holds: office", + "remove('zzq', kind='office')", id="own-add-other-kind"), + # a name held only as other words' pairs, with a kind and on an empty + # lexicon, which has compiled no pairs + pytest.param(lambda L: L.remove("robert", kind="given"), + "'robert' holds no reading of its own", + "remove('robert', kind='familiar')", id="pair-name-kind"), + pytest.param(lambda L: Lexicon.empty().remove("abigail"), + "'abigail' holds no reading of its own", + "remove('abigail', kind='familiar')", id="pair-name-empty"), + # full stops inside a word the vocabulary writes without them + pytest.param(lambda L: L.remove("Ph.D.", kind="credential"), + "the vocabulary writes 'ph.d' without its full stops", + "remove('phd', kind='credential')", id="interior-stops"), + # with no kind, the kind the dotted spelling is read by: md's + # credential, not its given reading (Muhammad written short) + pytest.param(lambda L: L.remove("M.D."), + "the vocabulary writes 'm.d' without its full stops", + "remove('md', kind='credential')", id="stops-no-kind"), + # an acronym the lexicon's own earlier add gave + pytest.param(lambda L: L.add("xq", kind="credential", acronym=True) + .remove("x.q.", kind="credential"), + "the vocabulary writes 'x.q' without its full stops", + "remove('xq', kind='credential')", id="stops-own-add"), + # a suffix word with stops is no acronym (J.R. is not read as jr), and + # a kind the dotted spelling is not read by names the one it is + pytest.param(lambda L: L.remove("j.r."), "'j.r' is in no vocabulary file", + None, id="stops-not-an-acronym"), + pytest.param(lambda L: L.remove("m.d.", kind="title"), + "as 'md', read with its full stops as credential", None, + id="stops-other-kind"), + # a word in no file: the join remedy named beside the spelling one + pytest.param(lambda L: L.remove("zzyzx", kind="title"), + "remove it from the joined lexicon", None, id="no-file"), +] + + +@pytest.mark.parametrize("call, part, offered", _MESSAGE_CASES) +def test_a_remove_warning_names_its_case( + call: Callable[[Lexicon], Lexicon], part: str, + offered: str | None) -> None: + with pytest.warns(UserWarning) as record: + call(Lexicon.default()) + message = str(record[0].message) + # every case opens with the call and "changes nothing", the text a + # caller filters one by + assert re.match(r"remove\('[^']+'(, kind='[a-z_]+')?\) changes nothing: ", + message), message + assert part in message, message + found = re.findall(r"remove\('[^']+', kind='[a-z_]+'\)", message.split( + "changes nothing: ", 1)[1]) + assert found == ([offered] if offered else []), message + + +def test_a_dotted_spellings_offer_takes_only_the_reading_it_is_read_by() -> None: + # M.D. is md's credential, and md is also Muhammad written short: the + # offered call takes the credential and leaves the given name (#1535) + with pytest.warns(UserWarning) as record: + Lexicon.default().remove("M.D.") + offered = re.search(r"did you mean (remove\([^)]*\))", + str(record[0].message)) + assert offered is not None + taken = Parser(lexicon=eval("Lexicon.default()." + offered.group(1))) # noqa: S307 + assert Parser().parse("John Smith M.D.").suffix == "M.D." + assert taken.parse("John Smith M.D.").suffix == "" + assert taken.parse("Md. Ali Khan").given == "Md." + # an acronym the lexicon added itself, offered and taken the same way + added = Lexicon.default().add("xq", kind="credential", acronym=True) + with pytest.warns(UserWarning) as own: + added.remove("x.q.") + offered = re.search(r"did you mean (remove\([^)]*\))", str(own[0].message)) + assert offered is not None + assert Parser(lexicon=added).parse("Jane Doe XQ").suffix == "XQ" + assert Parser(lexicon=eval("added." + offered.group(1))).parse( # noqa: S307 + "Jane Doe XQ").suffix == "" + + +def test_a_dotted_spelling_read_by_two_kinds_lists_them() -> None: + # us is a dotted title read by two title kinds once a caller adds one, + # so no call is plainly meant: the kinds are listed, none offered + lexicon = Lexicon.default().add("us", kind="academic") + with pytest.warns(UserWarning) as record: + lexicon.remove("u.s.") + message = str(record[0].message) + assert "the vocabulary writes 'u.s' without its full stops" in message + assert "read with its full stops as academic, modifier" in message + assert "did you mean" not in message + + +@pytest.mark.parametrize("field", ["surnames", "given_names"]) +def test_a_word_held_only_in_a_list_is_told_how_to_drop_it(field: str) -> None: + listed = frozenset({"zzluis"}) + lexicon = (dataclasses.replace(Lexicon.default(), surnames=listed) + if field == "surnames" else + dataclasses.replace(Lexicon.default(), given_names=listed)) + with pytest.warns(UserWarning) as record: + lexicon.remove("zzluis") + message = str(record[0].message) + assert f"this lexicon's {field} list" in message + offered = re.search(r"dataclasses\.replace\(.*\}\)", message) + assert offered is not None + dropped = eval(offered.group(0)) # noqa: S307 + assert "zzluis" in getattr(lexicon, field) + assert "zzluis" not in getattr(dropped, field) + + +def test_a_remove_of_several_words_names_only_those_it_takes_nothing_from() -> None: + with pytest.warns(UserWarning) as record: + Lexicon.default().remove("alhaj", "qari", "zzyzx", kind="religious") + messages = [str(w.message) for w in record] + assert len(messages) == 2 + assert any("'alhaj'" in m for m in messages) + # a word named twice in one call warns once + with pytest.warns(UserWarning) as twice: + Lexicon.default().remove("alhaj", "alhaj", kind="religious") + assert len(twice) == 1 + assert any("'zzyzx'" in m for m in messages) + assert not any("'qari'" in m for m in messages) + + +def test_the_remove_a_warning_offers_takes_the_reading() -> None: + # the offered call is code to paste: run it, on the default, and + # check that it takes the reading the inert one missed + with pytest.warns(UserWarning) as record: + Lexicon.default().remove("alhaj", kind="religious") + offered = re.search(r"Did you mean (remove\([^)]*\))", + str(record[0].message)) + assert offered is not None + fixed = eval("Lexicon.default()." + offered.group(1)) # noqa: S307 + assert "style" in {r.kind for r in Lexicon.default().readings_of("alhaj")} + assert "style" not in {r.kind for r in fixed.readings_of("alhaj")} + assert Parser(lexicon=fixed).parse("Alhaj Ahmed Khan").title == "" + + +@pytest.mark.parametrize("call", [ + # a reading a file holds off by default, which a choice turns on + pytest.param(lambda L: L.remove("piedade", kind="given"), + id="default-false"), + # a category one of whose kinds the word holds + pytest.param(lambda L: L.remove("dean", kind="title"), id="category"), + # the lexicon's own earlier add, and a second remove of a reading + pytest.param(lambda L: L.add("zzorvan", kind="family") + .remove("zzorvan", kind="family"), id="own-add"), + pytest.param(lambda L: L.add("zzorvan", kind="family") + .remove("zzorvan", kind="family") + .remove("zzorvan", kind="family"), id="own-add-twice"), + pytest.param(lambda L: L.remove("phd", kind="credential") + .remove("phd", kind="credential"), id="file-twice"), + # the word as the lexicon stores it: case and full stops folded, as + # for an earlier add of the caller's own + pytest.param(lambda L: L.remove("Dean", kind="title"), id="cased"), + pytest.param(lambda L: L.remove("Dean.", kind="title"), id="dotted"), + pytest.param(lambda L: L.add("zzk", kind="family") + .remove("ZZK", kind="family"), id="own-add-cased"), + # a remove of every word's readings of a kind names no word + pytest.param(lambda L: L.remove(kind="title", every=True), id="every"), + # the pair removes are not judged: they match by name matching's + # folded forms, which this check does not read + pytest.param(lambda L: L.remove("zzbob", kind="familiar"), + id="familiar"), + pytest.param(lambda L: L.remove("zzsara", kind="spelling", + spelling_of=["zzsarah"]), + id="spelling"), +]) +def test_a_remove_that_can_take_effect_is_silent( + call: Callable[[Lexicon], Lexicon]) -> None: + with warnings.catch_warnings(): + warnings.simplefilter("error") + call(Lexicon.default()) + + +def test_a_remove_warning_points_at_the_callers_line() -> None: + def line_of(make: Callable[[], object]) -> tuple[str, int]: + with pytest.warns(UserWarning) as record: + make() + return record[0].filename, record[0].lineno + + def plain() -> object: + return Lexicon.default().remove("zzyzx") + + def chained() -> object: + return Lexicon.default().remove("dean", kind="title").remove("zzyzx") + + def in_a_parser() -> object: + return Parser(lexicon=Lexicon.default().remove("zzyzx")) + + for make in (plain, chained, in_a_parser): + filename, lineno = line_of(make) + # the warning names this file and the remove's own line, the + # function's body, not a line inside the library + assert filename == __file__ + assert lineno == make.__code__.co_firstlineno + 1, make.__name__ + + +def test_a_logged_remove_does_not_warn_again() -> None: + with pytest.warns(UserWarning): + inert = Lexicon.default().remove("zzyzx", kind="title") + with warnings.catch_warnings(): + warnings.simplefilter("error") + # replaying the log, by a copy and by a pickle, warns nothing + dataclasses.replace(inert, given_names=frozenset({"luis"})) + loaded = pickle.loads(pickle.dumps(inert)) + assert loaded == inert + Parser(lexicon=inert).parse("Zzyzx Smith") + + +def test_every_pack_builds_with_no_remove_warning() -> None: + with warnings.catch_warnings(): + warnings.simplefilter("error") + warnings.filterwarnings( + "ignore", message="Policy.segment_scripts activates") + for code in locales.available(): + pack = locales.get(code) + parser_for(pack) + if pack.languages: + parser_for(pack, strict=True) + + @pytest.mark.parametrize("prop, kind, word", [ ("completes", "bound_second", "ذو"), ("completed_by", "bound_given", "الله"), diff --git a/tests/v2/test_match.py b/tests/v2/test_match.py index d9487f5dd..7503f9b3b 100644 --- a/tests/v2/test_match.py +++ b/tests/v2/test_match.py @@ -2803,11 +2803,34 @@ def test_a_remove_of_every_reading_of_a_word_keeps_the_pairs_other_words_hold() # spelling ones among them; a pair another word holds with it is # that word's reading, and takes a remove of the kind (#1404) lexicon = _pairs("familiar", "short_for").add("zzbo", kind="title") - after = lexicon.remove("zzbo").remove("zzrobert") + # zzrobert holds no reading of its own, so the remove takes nothing + # and warns (#1535) + with pytest.warns(UserWarning, + match="'zzrobert' holds no reading of its own"): + after = lexicon.remove("zzbo").remove("zzrobert") assert after.readings_of("zzbo") == () assert after._familiar_forms("zzrobert") == {"zzrob"} +@_pair_kinds +def test_a_no_kind_remove_of_a_name_held_only_in_pairs_offers_the_pair_remove( + kind: str, prop: str, outcome: Outcome, + paired: Callable[..., frozenset[str]]) -> None: + # zzsho is the other name of a pair zzlong holds: a remove with no + # kind takes nothing, and the warning offers the remove that takes + # the pair, which this runs (#1535) + lexicon = _pairs(kind, prop) + with pytest.warns(UserWarning) as record: + lexicon.remove("zzsho") + message = str(record[0].message) + assert "'zzsho' holds no reading of its own" in message + offered = re.search(r"remove\('zzsho', kind='[a-z]+'\)", message) + assert offered is not None + taken = eval("lexicon." + offered.group(0)) # noqa: S307 + assert paired(lexicon, "zzsho") == {"zzlong"} + assert paired(taken, "zzsho") == frozenset() + + @_pair_kinds @pytest.mark.parametrize("call, error, match", [ # a bare string is not a list of names, as on add diff --git a/tests/v2/test_parser.py b/tests/v2/test_parser.py index d56620a34..38039119e 100644 --- a/tests/v2/test_parser.py +++ b/tests/v2/test_parser.py @@ -3263,8 +3263,12 @@ def test_a_packs_fragment_joins_under_the_callers_lexicon() -> None: # and a later pack's fragment after an earlier one's first = _choosing("en", code="aa", lexicon=Lexicon.empty().add("zzq", kind="title")) - second = _choosing("en", code="bb", - lexicon=Lexicon.empty().remove("zzq", kind="title")) + # the fragment's remove takes out a reading another lexicon adds, which + # remove() cannot see, so it warns that no file and no earlier add + # of its own lexicon holds it (#1535) + with pytest.warns(UserWarning, match="'zzq' is in no vocabulary file"): + second = _choosing("en", code="bb", + lexicon=Lexicon.empty().remove("zzq", kind="title")) assert parser_for(first, second).parse("Zzq Smith").title == "" assert parser_for(second, first).parse("Zzq Smith").title == "Zzq"