Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`).
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
4 changes: 3 additions & 1 deletion src/onlyworlds/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -237,7 +237,9 @@
"MapSpaceMap",
"MapSpaceOutline",
"MapSpacePin",
"NameFinder",
"NameFound",
"NameShared",
"Opener",
"Patch",
"PreconditionFailed",
Expand Down
2 changes: 1 addition & 1 deletion src/onlyworlds/_version.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "0.146.0"
__version__ = "0.147.0"
270 changes: 203 additions & 67 deletions src/onlyworlds/name_finder.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]:
Expand All @@ -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:
Expand Down Expand Up @@ -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"``
Expand All @@ -124,77 +253,84 @@ 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):
raise TypeError("name_finder: names is a function from an element to its names.")
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
Loading
Loading