diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d4b6a9..234723a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,11 @@ The package version runs on its own semver; the schema it is generated from is ` ## Unreleased +## 0.147.0 (2026-11-24) + +- **Added: `find.shared` on `name_finder`'s answer**: every name two or more elements hold, each a `NameShared` (`name`, `elements`), in the order each name was first met. `name` is the name as it is compared (trimmed, and folded when `case` is `"folded"`); `elements` is a tuple of the objects that were passed in, in the order given. `find` never answers such a name, and until now nothing said it was there: a tool reads the list to tell a writer why a name stays plain, or to test that no two elements of a world share one. A name too short to be looked for is not on it. `shared` is a read-only tuple, read once when the finder is made. New public names: `NameFinder` (what `name_finder` answers, called on a text as before) and `NameShared`. +- **Changed: `name_finder` reads a text once, whatever the names.** The work for one text was at most its length times the longest name's length, and a long name whose opening words the text repeats reached that: one 5,000-character name against 400,000 characters of its first word ran for more than a minute. The names are now held as one matcher with failure links and the text is read once from its end to its start, so the work grows with the text's length alone: that case takes about a twentieth of a second. No answer moves: the 47 cases of 0.141.0 stand, with 15 more (names that end other names, names of marks alone, names nested in one another, overlaps, a name that ends in a mark against an address, and what `find.shared` lists). Finding names in ordinary prose costs about what it did (12 ms where it was 14, for 15,000 names over 100 KB of prose), and reading the names about 1.7 times as long. + ## 0.146.0 (2026-11-23) - **`read_folder` takes a declared type only when it is one of the 22 slugs as written.** The folder format says a declared type is a string exactly equal to one of the 22 type slugs, and that anything else in `type` declares nothing, so the directory fills it. The reader took any non-empty string, in lower case: `"type": "Location"` in `elements/character/` was served as a location, and `"type": "widget"` as an element of type `widget`. Each is now a character, flagged `type_inferred`, its body left as the file wrote it. A slug as written still beats the directory: `"type": "location"` in `elements/character/` is a location. What follows for callers: `push` sends such an element to its directory's route, and a file whose `type` was an unknown word, which `pack` left out and the OKF export skipped, is now read as an element of its directory's type. The npm SDK's folder source already read it this way; both packages hold the same 21 cases (`tests/fixtures/declared-type.cases.json`). diff --git a/README.md b/README.md index 03e4dda..51c4565 100644 --- a/README.md +++ b/README.md @@ -386,11 +386,11 @@ found = find("Kira's watch ends at the Iron Gate.") - A whole name only: the character on each side is not a letter, a combining mark, a decimal digit or an underscore, in any script. `Kira's` and `Kira-led` hold the name; `Kiran` does not. - A name is trimmed and is three characters at least. Where several names start at one place, the longest whole one is taken. -- A name two elements share is never answered, and nothing inside it is: the text stays plain there. +- A name two elements share is never answered, and nothing inside it is: the text stays plain there. `find.shared` lists those names, each a `NameShared` (`name`, `elements`), so a tool can say why a name never links. - Nothing is read inside an address or a Markdown link `[label](target)`. - Every mention is answered, in order. `element` is the object you passed in; `start` and `end` count code points (the npm SDK counts UTF-16 units). -`names` gives the names an element is found by, such as a tool's own aliases: `name_finder(elements, case="folded", names=lambda el: [el["name"], *el.get("aliases", [])])`. Which elements go in is yours to choose. Three limits: text is compared as written, with no Unicode normalisation; a space in a name matches that one space; and in a script written without spaces between words (Chinese, Japanese, Thai) a name is whole only between punctuation or spaces. The work for one text is at most its length times the longest name's length, whatever the number of names. +`names` gives the names an element is found by, such as a tool's own aliases: `name_finder(elements, case="folded", names=lambda el: [el["name"], *el.get("aliases", [])])`. Which elements go in is yours to choose. Three limits: text is compared as written, with no Unicode normalisation; a space in a name matches that one space; and in a script written without spaces between words (Chinese, Japanese, Thai) a name is whole only between punctuation or spaces. The work for one text grows with its length alone, whatever the names and however many. ### Open with diff --git a/src/onlyworlds/__init__.py b/src/onlyworlds/__init__.py index 27308a7..e1aea41 100644 --- a/src/onlyworlds/__init__.py +++ b/src/onlyworlds/__init__.py @@ -134,7 +134,7 @@ thread_of, unread_for, ) -from .name_finder import NameFound, name_finder +from .name_finder import NameFinder, NameFound, NameShared, name_finder from .names import type_word from .openers import Opener, Tool, ToolOpen, openers_for from .push import Patch, PushPlan, PushResult, plan_push, push, verify_level @@ -237,7 +237,9 @@ "MapSpaceMap", "MapSpaceOutline", "MapSpacePin", + "NameFinder", "NameFound", + "NameShared", "Opener", "Patch", "PreconditionFailed", diff --git a/src/onlyworlds/_version.py b/src/onlyworlds/_version.py index 31a9856..013e5b9 100644 --- a/src/onlyworlds/_version.py +++ b/src/onlyworlds/_version.py @@ -1 +1 @@ -__version__ = "0.146.0" +__version__ = "0.147.0" diff --git a/src/onlyworlds/name_finder.py b/src/onlyworlds/name_finder.py index d611eca..9e94d6f 100644 --- a/src/onlyworlds/name_finder.py +++ b/src/onlyworlds/name_finder.py @@ -16,13 +16,17 @@ from .room import _WHITE_SPACE from .worldfile import simple_case_fold -__all__ = ["NameFound", "name_finder"] +__all__ = ["NameFinder", "NameFound", "NameShared", "name_finder"] _NAME_MIN = 3 """A name shorter than this many characters (code points, after its white space is trimmed) is never looked for.""" _ASCII_WORD = frozenset("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_") +_END = "" +"""The mark the matcher reads between two characters wherever a name may end: before a character that is not a +word character, and at the end of the text. No character is the empty string.""" + @dataclass(frozen=True) class NameFound[T]: @@ -34,21 +38,46 @@ class NameFound[T]: element: T +@dataclass(frozen=True) +class NameShared[T]: + """A name two or more elements hold: the finder answers nothing for it, and this says that it is there. + ``name`` is the name as the finder compares it (trimmed of white space, and folded when ``case`` is + ``"folded"``); ``elements`` are the elements that hold it, two at least, in the order they were given: the same + objects ``name_finder`` was given.""" + + name: str + elements: tuple[T, ...] + + class _Hit[T]: - __slots__ = ("element", "id", "shared") + """One name, as compared, and every element that holds it.""" - def __init__(self, id: str, element: T) -> None: - self.id = id - self.element = element - self.shared = False + __slots__ = ("elements", "ids", "length", "name") + def __init__(self, name: str, element: T) -> None: + self.name = name + self.length = len(name) + self.elements: list[T] = [element] + self.ids: set[str] | None = None + """The ids of ``elements``, kept once a second element holds the name.""" -class _Node[T]: - __slots__ = ("hit", "next") + +class _State[T]: + """A state of the matcher. The names are held backwards, each from its last character to its first, with + ``_END`` before every character that is not a word character and once at the name's end: so a text read from + its end towards its start, with the same mark laid wherever a name may end, passes each character once (Aho + and Corasick's failure links), and the state after a character says which whole names start there. + + ``hit`` is the name that is this state, read backwards; ``longest`` the longest name that ends, read backwards, + at this state: ``hit``, or the failure state's.""" + + __slots__ = ("fail", "hit", "longest", "next") def __init__(self) -> None: - self.next: dict[str, _Node[T]] = {} + self.next: dict[str, _State[T]] = {} + self.fail: _State[T] | None = None self.hit: _Hit[T] | None = None + self.longest: _Hit[T] | None = None def _in_a_word(ch: str) -> bool: @@ -98,12 +127,112 @@ def _passed_over(text: str) -> list[tuple[int, int]]: return out +class NameFinder[T]: + """What ``name_finder`` answers: call it on a text for the names found there; ``shared`` lists the names two or + more elements hold. Made by ``name_finder``, not by hand.""" + + __slots__ = ("_folded", "_root", "_shared") + + def __init__(self, root: _State[T], hits: list[_Hit[T]], folded: bool) -> None: + self._root = root + self._folded = folded + self._shared: tuple[NameShared[T], ...] = tuple( + NameShared(hit.name, tuple(hit.elements)) for hit in hits if len(hit.elements) > 1 + ) + + @property + def shared(self) -> tuple[NameShared[T], ...]: + """Every name two or more elements hold, in the order each name was first met. The finder never answers + one of these, so a tool reads this to say why a name stays plain.""" + return self._shared + + def __call__(self, text: str) -> list[NameFound[T]]: + if not isinstance(text, str): + raise TypeError("name_finder: text must be a string") + found: list[NameFound[T]] = [] + root = self._root + if not root.next: + return found + spans = _passed_over(text) + hay = simple_case_fold(text) if self._folded else text + length = len(text) + ascii_word = _ASCII_WORD + end_mark = _END + # Where a whole name starts and the longest one that does, as the backward pass meets them: last place first. + starts: list[int] = [] + longest: list[_Hit[T]] = [] + frm = 0 + for span in range(len(spans) + 1): + to = spans[span][0] if span < len(spans) else length + if to > frm: + starts.clear() + longest.clear() + state = root + k = to + # Whether a name may end at k: the text ends there, or the character at k is not a word character. + if k >= length: + may_end = True + else: + ch = text[k] + may_end = ch not in ascii_word if ch < "\x80" else not _in_a_word(ch) + while k > frm: + if may_end: + to_state = state.next.get(end_mark) + while to_state is None: + back = state.fail + if back is None: + to_state = root + break + state = back + to_state = state.next.get(end_mark) + state = to_state + k -= 1 + ch = text[k] + may_end = ch not in ascii_word if ch < "\x80" else not _in_a_word(ch) + if state is not root: + token = hay[k] + to_state = state.next.get(token) + while to_state is None: + back = state.fail + if back is None: + to_state = root + break + state = back + to_state = state.next.get(token) + state = to_state + hit = state.longest + if hit is not None: + if k == 0: + word_before = False + else: + before = text[k - 1] + word_before = before in ascii_word if before < "\x80" else _in_a_word(before) + if not word_before: + starts.append(k) + longest.append(hit) + # Forwards over what was met: the first place a name starts takes its longest name, and the next + # name starts at or after that one's end. + free = frm + for r in range(len(starts) - 1, -1, -1): + start = starts[r] + if start < free: + continue + hit = longest[r] + end = start + hit.length + if len(hit.elements) == 1: + found.append(NameFound(start, end, hit.elements[0])) + free = end + if span < len(spans): + frm = spans[span][1] + return found + + def name_finder[T: Mapping[str, Any]]( elements: Iterable[T], *, case: Literal["exact", "folded"], names: Callable[[T], Iterable[object]] | None = None, -) -> Callable[[str], list[NameFound[T]]]: +) -> NameFinder[T]: """A finder of a world's element names in prose: read the names once, then call the answer on each text. ``elements`` is any iterable of mappings with a string ``id`` and a ``name``. ``case`` must be given: ``"exact"`` @@ -124,11 +253,16 @@ def name_finder[T: Mapping[str, Any]]( no name is read across the edge of one. - Text is compared as written: no Unicode normalisation, and a space in a name matches that one space. - ``element`` in an answer is the object that was passed in. Nothing given is changed. The work for one text is - at most its length times the longest name's length, whatever the number of names, with no pattern that - backtracks. ``start`` and ``end`` count code points (the npm SDK's ``nameFinder`` counts UTF-16 units). A - ``case`` that is neither word, a ``names`` that cannot be called, an element without a string ``id``, or a - ``text`` that is not a string is a ``TypeError``.""" + ``find.shared`` lists every name two or more elements hold, each a ``NameShared`` (``name``, ``elements``): the + name as it is compared (trimmed, and folded when ``case`` is ``"folded"``) and the elements that hold it, in the + order given. A name too short to be looked for is not on it. + + ``element`` in an answer is the object that was passed in. Nothing given is changed. The work for one text + grows with its length alone, whatever the names and however many: the text is read once, from its end to its + start, and no character is read again for another name. Reading the names grows with their total length. + ``start`` and ``end`` count code points (the npm SDK's ``nameFinder`` counts UTF-16 units). A ``case`` that is + neither word, a ``names`` that cannot be called, an element without a string ``id``, or a ``text`` that is not + a string is a ``TypeError``.""" if case not in ("exact", "folded"): raise TypeError(f"name_finder: case is 'exact' or 'folded'; got {case!r}.") if names is not None and not callable(names): @@ -136,65 +270,67 @@ def name_finder[T: Mapping[str, Any]]( if isinstance(elements, (str, bytes, Mapping)) or not isinstance(elements, Iterable): raise TypeError("name_finder: elements is an iterable of mappings with an id and a name.") folded = case == "folded" - root: _Node[T] = _Node() + root: _State[T] = _State() + hits: list[_Hit[T]] = [] for element in elements: if not isinstance(element, Mapping) or not isinstance(element.get("id"), str) or element["id"] == "": raise TypeError("name_finder: every element is a mapping with a string id.") + element_id: str = element["id"] for raw in names(element) if names is not None else (element.get("name"),): if not isinstance(raw, str): continue name = raw.strip(_WHITE_SPACE) if len(name) < _NAME_MIN: continue - node = root - for ch in simple_case_fold(name) if folded else name: - child = node.next.get(ch) - if child is None: - child = node.next[ch] = _Node() - node = child - if node.hit is None: - node.hit = _Hit(element["id"], element) - elif node.hit.id != element["id"]: - node.hit.shared = True - - def find(text: str) -> list[NameFound[T]]: - if not isinstance(text, str): - raise TypeError("name_finder: text must be a string") - found: list[NameFound[T]] = [] - firsts = root.next - if not firsts: - return found - spans = _passed_over(text) - hay = simple_case_fold(text) if folded else text - length = len(text) - span = 0 - i = 0 - while i < length: - if span < len(spans) and i >= spans[span][0]: - i = spans[span][1] - span += 1 - continue - if hay[i] in firsts and (i == 0 or not _in_a_word(text[i - 1])): - limit = spans[span][0] if span < len(spans) else length - node = root - j = i - best: _Hit[T] | None = None - best_end = -1 - while j < limit: - child = node.next.get(hay[j]) - if child is None: - break - node = child - j += 1 - if node.hit is not None and (j >= length or not _in_a_word(text[j])): - best = node.hit - best_end = j - if best is not None: - if not best.shared: - found.append(NameFound(i, best_end, best.element)) - i = best_end - continue - i += 1 - return found + if folded: + name = simple_case_fold(name) + # The name backwards: the end mark, then each character from the last to the first, and the mark again + # after (so, in the text, before) every character but the first that is not a word character. + state = root + for k in range(len(name) - 1, -1, -1): + if k == len(name) - 1: + state = _child(state, _END) + ch = name[k] + state = _child(state, ch) + if k > 0 and not _in_a_word(ch): + state = _child(state, _END) + hit = state.hit + if hit is None: + state.hit = _Hit(name, element) + hits.append(state.hit) + elif hit.ids is None: + first_id: str = hit.elements[0]["id"] + if first_id != element_id: + hit.ids = {first_id, element_id} + hit.elements.append(element) + elif element_id not in hit.ids: + hit.ids.add(element_id) + hit.elements.append(element) + + # The failure links, level by level: where the matcher goes on when the text leaves the name it was reading. + level: list[_State[T]] = [] + for child in root.next.values(): + child.fail = root + child.longest = child.hit + level.append(child) + while level: + deeper: list[_State[T]] = [] + for state in level: + for token, child in state.next.items(): + back = state.fail + while back is not None and token not in back.next: + back = back.fail + fail = root if back is None else back.next[token] + child.fail = fail + child.longest = child.hit if child.hit is not None else fail.longest + deeper.append(child) + level = deeper + + return NameFinder(root, hits, folded) + - return find +def _child[T](state: _State[T], token: str) -> _State[T]: + child = state.next.get(token) + if child is None: + child = state.next[token] = _State() + return child diff --git a/tests/fixtures/name-finder.cases.json b/tests/fixtures/name-finder.cases.json index 56b4ead..f4ec62f 100644 --- a/tests/fixtures/name-finder.cases.json +++ b/tests/fixtures/name-finder.cases.json @@ -1,6 +1,6 @@ { - "about": "Cases for nameFinder (@onlyworlds/sdk) and name_finder (the onlyworlds Python package): the same bytes in both repositories. In a case, an element with a names list is found by those names (the names option), one without by its name; want lists what find(text) answers, in order, each the place of its first character and its length, both in code points, and the id of its element. A timed case is built from its recipe ({i} is the count from 0) and must answer count names in under underMs milliseconds. Made by test/fixtures/generate-name-finder-cases.mjs in the SDK repository; every want is written by hand there.", - "version": 1, + "about": "Cases for nameFinder (@onlyworlds/sdk) and name_finder (the onlyworlds Python package): the same bytes in both repositories. In a case, an element with a names list is found by those names (the names option), one without by its name; want lists what find(text) answers, in order, each the place of its first character and its length, both in code points, and the id of its element; shared lists what find.shared holds, in order, each a name as it is compared and the ids of the elements that hold it. A timed case is built from its recipe ({i} is the count from 0; a long name is its repeat, times over, and then its then) and must answer count names in under underMs milliseconds. Made by test/fixtures/generate-name-finder-cases.mjs in the SDK repository; every want is written by hand there.", + "version": 2, "underMs": 2000, "cases": [ { @@ -28,7 +28,8 @@ "length": 9, "id": "a" } - ] + ], + "shared": [] }, { "name": "a possessive and a hyphen leave the name whole", @@ -55,7 +56,8 @@ "length": 6, "id": "j" } - ] + ], + "shared": [] }, { "name": "a name inside a longer word is not found, at either end", @@ -67,7 +69,8 @@ } ], "text": "Kiran and McKira and McKiran.", - "want": [] + "want": [], + "shared": [] }, { "name": "a digit on either side is inside a word", @@ -89,7 +92,8 @@ "length": 6, "id": "u" } - ] + ], + "shared": [] }, { "name": "an underscore on either side is inside a word", @@ -107,7 +111,8 @@ "length": 4, "id": "k" } - ] + ], + "shared": [] }, { "name": "a name that starts or ends with a letter outside ASCII is found whole", @@ -134,7 +139,8 @@ "length": 3, "id": "z" } - ] + ], + "shared": [] }, { "name": "a letter outside ASCII after or before a name is inside a word", @@ -154,7 +160,8 @@ } ], "text": "Ana\u00efs and Zo\u00ebx and \u00c9lodie.", - "want": [] + "want": [], + "shared": [] }, { "name": "a combining mark after a name is inside a word", @@ -172,7 +179,8 @@ "length": 3, "id": "a" } - ] + ], + "shared": [] }, { "name": "a decimal digit of another script is inside a word; a superscript is not", @@ -190,7 +198,8 @@ "length": 4, "id": "k" } - ] + ], + "shared": [] }, { "name": "places count code points: a character above the BMP before a name", @@ -213,7 +222,8 @@ "length": 4, "id": "k" } - ] + ], + "shared": [] }, { "name": "a name of letters above the BMP; two of them are too short", @@ -235,7 +245,8 @@ "length": 3, "id": "d" } - ] + ], + "shared": [] }, { "name": "the longest whole name wins", @@ -267,7 +278,8 @@ "length": 4, "id": "i" } - ] + ], + "shared": [] }, { "name": "the leftmost name is taken, and the search goes on after it", @@ -294,7 +306,8 @@ "length": 11, "id": "k" } - ] + ], + "shared": [] }, { "name": "every mention is answered", @@ -331,7 +344,8 @@ "length": 4, "id": "k" } - ] + ], + "shared": [] }, { "name": "a name two elements share stays plain", @@ -357,6 +371,15 @@ "length": 4, "id": "k" } + ], + "shared": [ + { + "name": "Ember", + "ids": [ + "a", + "b" + ] + } ] }, { @@ -383,6 +406,15 @@ "length": 5, "id": "e" } + ], + "shared": [ + { + "name": "Old Ember", + "ids": [ + "a", + "b" + ] + } ] }, { @@ -409,6 +441,15 @@ "length": 10, "id": "l" } + ], + "shared": [ + { + "name": "Ember", + "ids": [ + "a", + "b" + ] + } ] }, { @@ -443,7 +484,8 @@ "length": 4, "id": "m" } - ] + ], + "shared": [] }, { "name": "an element is found by each of its names", @@ -475,7 +517,8 @@ "length": 10, "id": "v" } - ] + ], + "shared": [] }, { "name": "two elements that share one of several names: that name is plain, the others are found", @@ -508,6 +551,15 @@ "length": 4, "id": "w" } + ], + "shared": [ + { + "name": "the Consul", + "ids": [ + "v", + "w" + ] + } ] }, { @@ -534,7 +586,8 @@ "length": 3, "id": "c" } - ] + ], + "shared": [] }, { "name": "a name is trimmed of white space, every kind of it", @@ -561,7 +614,8 @@ "length": 4, "id": "m" } - ] + ], + "shared": [] }, { "name": "a byte order mark and a file separator are not white space: the name keeps them", @@ -577,7 +631,8 @@ } ], "text": "Kira and Mira.", - "want": [] + "want": [], + "shared": [] }, { "name": "exact: another case is another word", @@ -595,7 +650,8 @@ "length": 6, "id": "c" } - ] + ], + "shared": [] }, { "name": "folded: case is ignored, and the answer is the text as written", @@ -623,7 +679,8 @@ "length": 6, "id": "c" } - ] + ], + "shared": [] }, { "name": "folded: two names that differ only by case are shared", @@ -649,6 +706,15 @@ "length": 4, "id": "k" } + ], + "shared": [ + { + "name": "ember", + "ids": [ + "a", + "b" + ] + } ] }, { @@ -676,7 +742,8 @@ "length": 5, "id": "b" } - ] + ], + "shared": [] }, { "name": "folded: letters outside ASCII fold too, and above the BMP", @@ -703,7 +770,8 @@ "length": 3, "id": "d" } - ] + ], + "shared": [] }, { "name": "folded: the long s and the Kelvin sign fold to s and k", @@ -730,7 +798,8 @@ "length": 4, "id": "k" } - ] + ], + "shared": [] }, { "name": "folded: simple folding only: a dotted capital I stays itself, and a sharp s is never two letters", @@ -757,7 +826,8 @@ "length": 6, "id": "s" } - ] + ], + "shared": [] }, { "name": "text is compared as written: a letter with a combining mark is not its one-character form", @@ -769,7 +839,8 @@ } ], "text": "E\u0301lodie rode.", - "want": [] + "want": [], + "shared": [] }, { "name": "a space in a name is that one space", @@ -787,7 +858,8 @@ "length": 9, "id": "g" } - ] + ], + "shared": [] }, { "name": "a name may hold punctuation, and may start or end with it", @@ -823,7 +895,8 @@ "length": 4, "id": "w" } - ] + ], + "shared": [] }, { "name": "nothing is read inside an address, in either form", @@ -849,7 +922,8 @@ "length": 4, "id": "k" } - ] + ], + "shared": [] }, { "name": "an address that is not one is prose", @@ -872,7 +946,8 @@ "length": 9, "id": "c" } - ] + ], + "shared": [] }, { "name": "nothing is read inside a Markdown link, label or target", @@ -894,7 +969,8 @@ "length": 4, "id": "k" } - ] + ], + "shared": [] }, { "name": "an address inside a link's target does not end the link", @@ -916,7 +992,8 @@ "length": 4, "id": "m" } - ] + ], + "shared": [] }, { "name": "brackets that are not a link are prose", @@ -944,7 +1021,8 @@ "length": 4, "id": "k" } - ] + ], + "shared": [] }, { "name": "a bracket that is not a link does not hide a later link", @@ -962,7 +1040,8 @@ "length": 4, "id": "k" } - ] + ], + "shared": [] }, { "name": "a link takes its label from the first bracket and its target to the first parenthesis", @@ -994,7 +1073,8 @@ "length": 4, "id": "m" } - ] + ], + "shared": [] }, { "name": "no name is read across the edge of a link; a shorter whole one before it is", @@ -1021,7 +1101,8 @@ "length": 7, "id": "n" } - ] + ], + "shared": [] }, { "name": "a name is found right beside a link", @@ -1044,7 +1125,8 @@ "length": 4, "id": "k" } - ] + ], + "shared": [] }, { "name": "a script written without spaces: a name is whole only between punctuation or spaces", @@ -1062,7 +1144,8 @@ "length": 3, "id": "t" } - ] + ], + "shared": [] }, { "name": "a name that is not a string is passed over", @@ -1095,7 +1178,8 @@ "length": 4, "id": "l" } - ] + ], + "shared": [] }, { "name": "a name alone is the whole text", @@ -1113,14 +1197,16 @@ "length": 4, "id": "k" } - ] + ], + "shared": [] }, { "name": "no elements, and no text", "case": "exact", "elements": [], "text": "Kira.", - "want": [] + "want": [], + "shared": [] }, { "name": "an empty text", @@ -1132,7 +1218,486 @@ } ], "text": "", - "want": [] + "want": [], + "shared": [] + }, + { + "name": "shared: three elements hold one name, and the list keeps the order the names were first met", + "case": "exact", + "elements": [ + { + "id": "k", + "name": "Kira" + }, + { + "id": "a", + "name": "Ember" + }, + { + "id": "z", + "name": "Old Gate" + }, + { + "id": "b", + "name": "Ember" + }, + { + "id": "y", + "name": "Old Gate" + }, + { + "id": "c", + "name": "Ember" + } + ], + "text": "Kira saw Ember at the Old Gate.", + "want": [ + { + "at": 0, + "length": 4, + "id": "k" + } + ], + "shared": [ + { + "name": "Ember", + "ids": [ + "a", + "b", + "c" + ] + }, + { + "name": "Old Gate", + "ids": [ + "z", + "y" + ] + } + ] + }, + { + "name": "shared: the name is listed as it is compared, trimmed and folded", + "case": "folded", + "elements": [ + { + "id": "a", + "name": " Iron GATE " + }, + { + "id": "b", + "name": "iron gate" + } + ], + "text": "The Iron Gate.", + "want": [], + "shared": [ + { + "name": "iron gate", + "ids": [ + "a", + "b" + ] + } + ] + }, + { + "name": "shared: a name too short to be looked for is not listed", + "case": "exact", + "elements": [ + { + "id": "a", + "name": "Al" + }, + { + "id": "b", + "name": "Al" + }, + { + "id": "c", + "name": "Ada" + }, + { + "id": "d", + "name": "Ada" + } + ], + "text": "Al and Ada.", + "want": [], + "shared": [ + { + "name": "Ada", + "ids": [ + "c", + "d" + ] + } + ] + }, + { + "name": "shared: one element twice is not two, by listing or by two of its own names", + "case": "exact", + "elements": [ + { + "id": "k", + "name": "Kira" + }, + { + "id": "k", + "name": "Kira" + }, + { + "id": "m", + "names": [ + "Mira", + "Mira" + ] + }, + { + "id": "n", + "name": "Mira" + } + ], + "text": "Kira and Mira.", + "want": [ + { + "at": 0, + "length": 4, + "id": "k" + } + ], + "shared": [ + { + "name": "Mira", + "ids": [ + "m", + "n" + ] + } + ] + }, + { + "name": "shared: an element that holds a shared name more than once is listed once", + "case": "exact", + "elements": [ + { + "id": "a", + "names": [ + "Ember", + "Ember" + ] + }, + { + "id": "b", + "name": "Ember" + }, + { + "id": "a", + "name": "Ember" + } + ], + "text": "Ember.", + "want": [], + "shared": [ + { + "name": "Ember", + "ids": [ + "a", + "b" + ] + } + ] + }, + { + "name": "a name that ends another name is found where the longer one is not", + "case": "exact", + "elements": [ + { + "id": "o", + "name": "Old Iron Gate" + }, + { + "id": "g", + "name": "Gate" + }, + { + "id": "i", + "name": "Iron Gate" + } + ], + "text": "The Old Iron Gate, a New Iron Gate, the Cold Gate.", + "want": [ + { + "at": 4, + "length": 13, + "id": "o" + }, + { + "at": 25, + "length": 9, + "id": "i" + }, + { + "at": 45, + "length": 4, + "id": "g" + } + ], + "shared": [] + }, + { + "name": "folded: a name that ends another name is found in its own case", + "case": "folded", + "elements": [ + { + "id": "o", + "name": "OLD iron gate" + }, + { + "id": "g", + "name": "GATE" + } + ], + "text": "The Old Iron Gate and the cold gate.", + "want": [ + { + "at": 4, + "length": 13, + "id": "o" + }, + { + "at": 31, + "length": 4, + "id": "g" + } + ], + "shared": [] + }, + { + "name": "a name of words that repeat is found where the text stops repeating", + "case": "exact", + "elements": [ + { + "id": "t", + "name": "the the end" + } + ], + "text": "the the the the the end.", + "want": [ + { + "at": 12, + "length": 11, + "id": "t" + } + ], + "shared": [] + }, + { + "name": "a name of marks alone: every place is a start, and the next name starts after the last", + "case": "exact", + "elements": [ + { + "id": "d", + "name": "---" + } + ], + "text": "-----, -------.", + "want": [ + { + "at": 0, + "length": 3, + "id": "d" + }, + { + "at": 7, + "length": 3, + "id": "d" + }, + { + "at": 10, + "length": 3, + "id": "d" + } + ], + "shared": [] + }, + { + "name": "a name that ends in a mark is whole only where no word character follows", + "case": "exact", + "elements": [ + { + "id": "w", + "name": "Who?" + }, + { + "id": "h", + "name": "Who" + } + ], + "text": "Who? Who?s Who.", + "want": [ + { + "at": 0, + "length": 4, + "id": "w" + }, + { + "at": 5, + "length": 3, + "id": "h" + }, + { + "at": 11, + "length": 3, + "id": "h" + } + ], + "shared": [] + }, + { + "name": "a name that ends in a mark is not whole against the first letter of an address", + "case": "exact", + "elements": [ + { + "id": "w", + "name": "Who?" + } + ], + "text": "Who?ow://character/01a1d4ef-0000-7000-8000-000000000084 and Who? ow://character/01a1d4ef-0000-7000-8000-000000000084", + "want": [ + { + "at": 60, + "length": 4, + "id": "w" + } + ], + "shared": [] + }, + { + "name": "a name that starts with a mark starts only where no word character stands before it", + "case": "exact", + "elements": [ + { + "id": "h", + "name": "'t Hooft" + } + ], + "text": "x't Hooft and 't Hooft.", + "want": [ + { + "at": 14, + "length": 8, + "id": "h" + } + ], + "shared": [] + }, + { + "name": "names nested in one another: the longest that is whole is taken", + "case": "exact", + "elements": [ + { + "id": "a", + "name": "a-b" + }, + { + "id": "b", + "name": "a-b-c" + }, + { + "id": "c", + "name": "a-b-c-d" + } + ], + "text": "a-b-c-d a-b-c-dx a-bx a-b-cx", + "want": [ + { + "at": 0, + "length": 7, + "id": "c" + }, + { + "at": 8, + "length": 5, + "id": "b" + }, + { + "at": 22, + "length": 3, + "id": "a" + } + ], + "shared": [] + }, + { + "name": "names that overlap: the leftmost is taken, and the next starts after it", + "case": "exact", + "elements": [ + { + "id": "x", + "name": "aaa bbb" + }, + { + "id": "y", + "name": "bbb ccc" + }, + { + "id": "z", + "name": "ccc ddd" + } + ], + "text": "aaa bbb ccc ddd and bbb ccc ddd", + "want": [ + { + "at": 0, + "length": 7, + "id": "x" + }, + { + "at": 8, + "length": 7, + "id": "z" + }, + { + "at": 20, + "length": 7, + "id": "y" + } + ], + "shared": [] + }, + { + "name": "a name beside a character above the BMP, at both ends of a text", + "case": "exact", + "elements": [ + { + "id": "k", + "name": "Kira" + }, + { + "id": "d", + "name": "\ud83d\udc09 den" + } + ], + "text": "Kira\ud83d\udc09 \ud83d\udc09 den \ud83d\udc09Kira", + "want": [ + { + "at": 0, + "length": 4, + "id": "k" + }, + { + "at": 6, + "length": 5, + "id": "d" + }, + { + "at": 13, + "length": 4, + "id": "k" + } + ], + "shared": [] } ], "timed": [ @@ -1220,6 +1785,54 @@ "times": 60000 }, "count": 0 + }, + { + "name": "a name of five thousand characters that almost matches at every word", + "elements": { + "count": 1, + "long": { + "repeat": "a ", + "times": 2500, + "then": "b" + } + }, + "text": { + "repeat": "a ", + "times": 200000 + }, + "count": 0 + }, + { + "name": "a name of five thousand marks and a letter, in a text of marks", + "elements": { + "count": 1, + "long": { + "repeat": "-", + "times": 5000, + "then": "x" + } + }, + "text": { + "repeat": "-", + "times": 400000 + }, + "count": 0 + }, + { + "name": "a name of five thousand marks, found eighty times", + "elements": { + "count": 1, + "long": { + "repeat": "-", + "times": 5000, + "then": "" + } + }, + "text": { + "repeat": "-", + "times": 400000 + }, + "count": 80 } ] } diff --git a/tests/test_name_finder.py b/tests/test_name_finder.py index feee2ce..7997321 100644 --- a/tests/test_name_finder.py +++ b/tests/test_name_finder.py @@ -1,7 +1,8 @@ """``name_finder``: a world's element names found in prose. The shared cases (``tests/fixtures/name-finder.cases.json``, the same bytes as the npm SDK's ``test/fixtures/name-finder.cases.json``; both suites hold its sha256, every want -written by hand in the SDK's generator), their timed recipes, then what the cases cannot hold: the object answered, -purity and the refusals.""" +written by hand in the SDK's generator): what ``find(text)`` answers and what ``find.shared`` lists, then their +timed recipes, then what the cases cannot hold: the objects answered, purity, the refusals and the one fact about +folding the matcher stands on.""" from __future__ import annotations @@ -13,15 +14,18 @@ import pytest -from onlyworlds import NameFound, name_finder +from onlyworlds import NameFinder, NameFound, NameShared, name_finder +from onlyworlds.name_finder import _in_a_word +from onlyworlds.worldfile import simple_case_fold FIXTURE = Path(__file__).resolve().parent / "fixtures" / "name-finder.cases.json" -FIXTURE_SHA256 = "4c4d7d3b4480e4c20bab799972faf90c542b5b570c1b43f7882291444c31007a" +FIXTURE_SHA256 = "8e91e79981830511055976011f9fc6d4f4b62fb0183c29bad61c2d05fd4b13e4" DATA: dict[str, Any] = json.loads(FIXTURE.read_bytes()) PYTHON_FACTOR = 5 """The cases' ``underMs`` is the npm SDK's line, where the slowest recipe takes about a tenth of a second. Here the -slowest recipe's whole test took 0.76 s when this was written, so the line is five times ``underMs``: far above a -slow machine's run, and far below a search that is not linear, which takes minutes on these texts.""" +slowest recipe's whole test took 0.76 s when this was first written (0.62 s once the text was read once, from its +end), so the line is five times ``underMs``: far above a slow machine's run, and far below a search that is not +linear, which takes minutes on these texts.""" def _names_of(element: dict[str, Any]) -> list[Any]: @@ -36,8 +40,8 @@ def _answer(case: dict[str, Any]) -> list[dict[str, Any]]: def test_the_cases_file_is_the_pinned_bytes_the_ones_the_npm_sdk_runs() -> None: assert hashlib.sha256(FIXTURE.read_bytes()).hexdigest() == FIXTURE_SHA256 - assert DATA["version"] == 1 - assert len(DATA["cases"]) >= 47 + assert DATA["version"] == 2 + assert len(DATA["cases"]) >= 62 def test_every_shared_case() -> None: @@ -49,6 +53,24 @@ def test_every_shared_case() -> None: assert not wrong, f"{len(wrong)} case(s) disagree:\n " + "\n ".join(wrong) +def _shared(case: dict[str, Any]) -> list[dict[str, Any]]: + find = name_finder(case["elements"], case=case["case"], names=_names_of) + return [{"name": s.name, "ids": [e["id"] for e in s.elements]} for s in find.shared] + + +def test_every_shared_case_what_find_shared_lists() -> None: + wrong = [ + f"{case['name']}\n want {case['shared']}\n got {got}" + for case in DATA["cases"] + if (got := _shared(case)) != case["shared"] + ] + assert not wrong, f"{len(wrong)} case(s) disagree:\n " + "\n ".join(wrong) + assert sum(1 for case in DATA["cases"] if case["shared"]) >= 10 + assert any(len(case["shared"]) > 1 for case in DATA["cases"]) + for fold in ("exact", "folded"): + assert any(case["case"] == fold and case["shared"] for case in DATA["cases"]), fold + + def test_the_shared_cases_hold_answers_of_both_kinds() -> None: assert any(case["want"] for case in DATA["cases"]) assert any(not case["want"] for case in DATA["cases"]) @@ -58,7 +80,16 @@ def test_the_shared_cases_hold_answers_of_both_kinds() -> None: def _build(recipe: dict[str, Any]) -> tuple[list[dict[str, str]], str]: made = recipe["elements"] - elements = [{"id": f"e{i}", "name": made["pattern"].replace("{i}", str(i))} for i in range(made["count"])] + long = made.get("long") + elements = [ + { + "id": f"e{i}", + "name": made["pattern"].replace("{i}", str(i)) + if long is None + else long["repeat"] * long["times"] + long["then"], + } + for i in range(made["count"]) + ] text = recipe["text"] if "repeat" in text: return elements, text["repeat"] * text["times"] @@ -76,8 +107,10 @@ def test_linear_in_the_text_on_the_timed_recipes(recipe: dict[str, Any]) -> None assert ms < DATA["underMs"] * PYTHON_FACTOR, f"{round(ms)} ms" -def test_the_timed_recipes_are_the_seven() -> None: - assert len(DATA["timed"]) >= 7 +def test_the_timed_recipes_are_the_ten_three_with_a_name_of_thousands_of_characters() -> None: + assert len(DATA["timed"]) >= 10 + long = [r for r in DATA["timed"] if "long" in r["elements"] and r["elements"]["long"]["times"] >= 2500] + assert len(long) >= 3 def test_start_and_end_count_code_points_and_the_slice_is_the_name_as_written() -> None: @@ -95,6 +128,53 @@ def test_element_is_the_object_passed_in_and_the_default_name_is_its_name() -> N assert name_finder(iter([kira]), case="exact")("Kira.")[0].element is kira +def test_find_shared_the_objects_passed_in_in_the_order_given_a_tuple_read_only_and_read_once() -> None: + a = {"id": "a", "name": "Ember"} + b = {"id": "b", "name": "EMBER "} + k = {"id": "k", "name": "Kira"} + elements = [k, b, a, b] + find = name_finder(elements, case="folded", names=lambda e: [e["name"], e["name"]]) + assert isinstance(find, NameFinder) + assert isinstance(find.shared, tuple) + (listed,) = find.shared + assert isinstance(listed, NameShared) + assert listed.name == "ember" + assert isinstance(listed.elements, tuple) + assert len(listed.elements) == 2 + assert listed.elements[0] is b + assert listed.elements[1] is a + with pytest.raises(AttributeError): + find.shared = () # type: ignore[misc] + with pytest.raises(AttributeError): + listed.name = "x" # type: ignore[misc] + elements.append({"id": "x", "name": "Kira"}) + assert len(find.shared) == 1, "the names were read once, when the finder was made" + assert [s.name for s in name_finder(elements, case="exact").shared] == ["Kira"] + assert name_finder([], case="exact").shared == () + assert name_finder([{"id": "a", "name": "Al"}, {"id": "b", "name": "Al"}], case="exact").shared == () + assert [f.element["id"] for f in find("Ember, ember, Kira")] == ["k"], "a listed name is never answered" + + +def test_folding_never_moves_a_character_into_or_out_of_a_word() -> None: + # The matcher lays a mark before every character of a name that is not a word character, read from the name + # as folded, and before every such character of the text, read as written. The two agree only while no + # character changes kind when it is folded: held here on every code point. + folds = 0 + moved: list[str] = [] + for cp in range(0x110000): + if 0xD800 <= cp <= 0xDFFF: + continue + ch = chr(cp) + folded = simple_case_fold(ch) + if folded == ch: + continue + folds += 1 + if _in_a_word(ch) != _in_a_word(folded): + moved.append(f"U+{cp:04X}") + assert folds > 1400, f"{folds} code points fold" + assert moved == [] + + def test_nothing_given_is_changed_and_the_names_are_read_once() -> None: elements: list[dict[str, Any]] = [ {"id": "k", "name": " Kira ", "aliases": ["The Watch"]},