diff --git a/dokimi/changelog.d/20261130_100000_memory-paragraph-linear.md b/dokimi/changelog.d/20261130_100000_memory-paragraph-linear.md new file mode 100644 index 000000000..4580a8558 --- /dev/null +++ b/dokimi/changelog.d/20261130_100000_memory-paragraph-linear.md @@ -0,0 +1,8 @@ + + +### Fixed + +- **`dokimi memory` reads a paragraph of many lines in time linear in its lines** — the memory lint joined the blanked paragraph above for every line and scanned it again, so `"word `a` word\n" * 2000` took 0.49 s, 3.7 times what 1000 lines took. It now keeps the start of the paragraph and the offsets it needs as it goes, with the same output. diff --git a/dokimi/dokimi/memory/blocks.py b/dokimi/dokimi/memory/blocks.py new file mode 100644 index 000000000..9c5bab6a1 --- /dev/null +++ b/dokimi/dokimi/memory/blocks.py @@ -0,0 +1,85 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""The block structure of a Markdown line, as ``memory.store`` blanks the code in an index: fences, lists, paragraph breaks.""" + +from __future__ import annotations + +import re + +FENCE = re.compile(r" {0,3}(`{3,}|~{3,})") +_LIST_ITEM = re.compile(r" *(?:[-*+]|\d{1,9}[.)])(?:[ \t]|$)") +_BLOCK_START = re.compile(r" {0,3}(?:#{1,6}(?:[ \t]|$)|>)") + + +def fence_opener(line: str) -> str: + """The fence marker that ``line`` opens, or ``""``: an info string holds no backtick.""" + m = FENCE.match(line) + if m and not (m.group(1)[0] == "`" and "`" in line[m.end():]): + return m.group(1) + return "" + + +def closes_fence(line: str, fence: str) -> bool: + """Whether ``line`` closes the fence ``fence``: the same character, at least as long, nothing after it.""" + m = FENCE.match(line) + return bool(m and m.group(1)[0] == fence[0] and len(m.group(1)) >= len(fence) and not line[m.end():].strip()) + + +def span_end(line: str, span: str) -> int: + """The offset just past the backtick run ``span`` that closes a code span on ``line``, or -1.""" + closer = re.search(r"(? tuple[bool, bool, bool]: + """``(in_list, code, hidden)`` after line ``i``: an indented line outside a list item, after a blank line or code, is code.""" + line = lines[i] + if not line.strip(): + return in_list, code, False + prev_blank = i == 0 or not lines[i - 1].strip() + if _LIST_ITEM.match(line) and (in_list or not line.startswith((" ", "\t")) or not (prev_blank or code)): + in_list = True + elif line[0] not in " \t" and (prev_blank or _BLOCK_START.match(line)): + in_list = False + hidden = not in_list and line.startswith((" ", "\t")) and (prev_blank or code) + return in_list, hidden, hidden + + +def paragraph_break(line: str) -> bool: + """Whether ``line`` ends the paragraph before it: blank, a fence, a list item, a heading or a quote.""" + return not line.strip() or bool(fence_opener(line) or _LIST_ITEM.match(line) or _BLOCK_START.match(line)) + + +def close_ahead(lines: list[str]) -> list[bool]: + """For each line, whether a ``-->`` follows it in the same paragraph.""" + ahead = [False] * len(lines) # mutation-ok[flip-bool]: the loop sets every row + seen = False + for i in range(len(lines) - 1, -1, -1): + ahead[i] = seen + if paragraph_break(lines[i]): + seen = False + elif "-->" in lines[i]: + seen = True + return ahead + + +def span_closes_ahead(lines: list[str], i: int, run: str) -> bool: + """Whether a backtick run of the length of ``run`` closes the code span it opens on line ``i``, within its paragraph.""" + closer = re.compile(r"(? tuple[str | None, str, str]: + """``(line, comment, opener)`` for a line met inside a comment; ``line`` is None while the comment holds all of it.""" + if comment == "inline" and paragraph_break(line): # a blank line, a fence or a block start ends it + return line, "", opener + end = line.find("-->") + if end < 0: + return None, comment, opener + return " " * (end + 3) + line[end + 3:], "", "" # the text after the close is prose, not a fence diff --git a/dokimi/dokimi/memory/store.py b/dokimi/dokimi/memory/store.py index 80096e392..0886471bc 100644 --- a/dokimi/dokimi/memory/store.py +++ b/dokimi/dokimi/memory/store.py @@ -12,17 +12,29 @@ import re from bisect import bisect_right -from collections.abc import Callable, Iterable +from collections.abc import Callable, Iterable, Iterator from dataclasses import dataclass, field -from functools import cache, partial +from functools import cached_property from html import unescape from pathlib import Path +from typing import Protocol from urllib.parse import unquote import yaml from dokimi.code_spans import LINE_BREAK, CodeSpan, CodeSpanScanner from dokimi.digest_entries import listed_entries +from dokimi.memory.blocks import ( + FENCE as _FENCE, + close_ahead, + closes_fence, + fence_opener, + indented_code, + resume_comment, + span_closes_ahead, + span_end, +) +from dokimi.memory.titles import title_spans INDEX_NAME = "MEMORY.md" ARCHIVE_DIR = "archive" @@ -38,21 +50,12 @@ _ENTITY = re.compile(r"&(?:#[0-9]{1,7}|#[xX][0-9a-fA-F]{1,6}|[A-Za-z][A-Za-z0-9]{1,31});") # a reference ends in a semicolon _MD_ESCAPE = re.compile(r"\\([!-/:-@\[-`{-~])") _WIKILINK = re.compile(r"\[\[([^\]\n]+)\]\]") -_FENCE = re.compile(r" {0,3}(`{3,}|~{3,})") _SCHEME = re.compile(r"[A-Za-z][A-Za-z0-9+.-]+:") # two letters or more, so a drive path like C:\\x is not a scheme -_LIST_ITEM = re.compile(r" *(?:[-*+]|\d{1,9}[.)])(?:[ \t]|$)") -_BLOCK_START = re.compile(r" {0,3}(?:#{1,6}(?:[ \t]|$)|>)") _BACKTICK_RUN = re.compile(r"(?\n]*>(?:\s+(?:\"[^\"]*\"|'[^']*'|\([^()]*\)))?" + _WS + r"\)") # the title grammar of _MD_LINK _TITLE_CLOSED = re.compile(r"[ \t]+(?:\"(?:\\.|[^\"\\])*\"|'(?:\\.|[^'\\])*'|\((?:\\.|[^()\\])*\))\s*$") -_TITLE_CLOSER = {'"': '"', "'": "'", "(": ")"} -_TITLE_BODY = { # what _TITLE_CLOSED reads between the opener and the closer, one line at a time - '"': re.compile(r"(?:\\.|[^\"\\])*"), - "'": re.compile(r"(?:\\.|[^'\\])*"), - "(": re.compile(r"(?:\\.|[^()\\])*"), -} class MemoryStoreError(ValueError): @@ -124,7 +127,7 @@ def index_targets(self) -> list[tuple[int, str, bool]]: raw = "\n".join(source) starts = [m.start() for m in re.finditer("\n", text)] # a link may run over a line break: find its line by offset begin = [0, *(s + 1 for s in starts)] - titles = _title_spans(lines, begin, defs) # a closed title holds no link + titles = title_spans(lines, begin, defs) # a closed title holds no link matches = list(_MD_LINK.finditer(text)) opened = _closing_openers(text, {m.start() for m in matches}) title_starts, title_ends = _merged(titles) @@ -174,19 +177,20 @@ def _blank_blocks(lines: list[str]) -> tuple[list[str], list[str]]: span = "" # the backtick run of a code span that runs on over the line break in_list = False code = False # the previous line was an indented code line - close_ahead = _close_ahead(lines) - start = 0 # the line the paragraph of line i begins at + closes = close_ahead(lines) + above = _Above(filled) for i, line in enumerate(lines): - start = _paragraph_start(lines, i, start) - opener = _fence_opener(line) + filled.extend(out[len(filled):]) # a line blanked whole keeps its spaces: it starts a block of its own + above.reach(lines, i) + opener = fence_opener(line) if fence: - if _closes_fence(line, fence): + if closes_fence(line, fence): fence = "" out.append(" " * len(line)) continue source = line if comment: - rest, comment, opener = _resume_comment(line, comment, opener) + rest, comment, opener = resume_comment(line, comment, opener) if rest is None: out.append(" " * len(line)) continue @@ -197,19 +201,17 @@ def _blank_blocks(lines: list[str]) -> tuple[list[str], list[str]]: continue pos = 0 if span: - pos = _span_end(line, span) + pos = span_end(line, span) if pos < 0: out.append(" " * len(line)) continue line = " " * pos + line[pos:] span = "" - in_list, code, hidden = _indented_code(lines, i, in_list, code and not pos) + in_list, code, hidden = indented_code(lines, i, in_list, code and not pos) # mutation-ok[drop-clause]: a span is open only after a prose line, which clears ``code`` if hidden and not pos: out.append(" " * len(line)) continue - filled.extend(out[len(filled):]) # a line blanked whole keeps its spaces: it starts a block of its own - above = cache(partial(_paragraph_above, filled, start, i)) # joined only when a link check reads it, and once - line, comment, run = _blank_inline(line, close_ahead[i], pos, above) + line, comment, run = _blank_inline(line, closes[i], pos, above) line, span = _open_span(lines, i, line, run) out.append(line) filled.append(_fill_blanks(source, line)) @@ -239,16 +241,6 @@ def _fill_blanks(source: str, blanked: str) -> str: return "".join(_FILL if b == " " and not s.isspace() else b for s, b in zip(source, blanked, strict=True)) -def _resume_comment(line: str, comment: str, opener: str) -> tuple[str | None, str, str]: - """``(line, comment, opener)`` for a line met inside a comment; ``line`` is None while the comment holds all of it.""" - if comment == "inline" and _paragraph_break(line): # a blank line, a fence or a block start ends it - return line, "", opener - end = line.find("-->") - if end < 0: - return None, comment, opener - return " " * (end + 3) + line[end + 3:], "", "" # the text after the close is prose, not a fence - - def _code_span(line: str, pos: int, scan: CodeSpanScanner | None = None) -> CodeSpan | None: """The first code span of ``line`` from ``pos`` whose opening backtick is not escaped. @@ -263,50 +255,128 @@ def _code_span(line: str, pos: int, scan: CodeSpanScanner | None = None) -> Code return None -def _title_spans(lines: list[str], begin: list[int], defs: dict[int, re.Match]) -> list[tuple[int, int]]: - """The offsets in the joined text of each definition's title, for a title closed on its line or the next.""" - out = [] - for k, d in defs.items(): - joined = d.end() > len(lines[k]) # the destination, and so the title, is on line k + 1 - col = d.end(2) - (len(lines[k]) + 1 if joined else 0) - if (last := _title_last_line(lines, k + joined, col)) is not None: - out.append((begin[k] + d.end(2), begin[last] + len(lines[last]))) - return out - - -def _title_last_line(lines: list[str], row: int, col: int) -> int | None: - """The line where the title that starts after ``col`` on ``lines[row]`` closes, as ``_TITLE_CLOSED`` reads it. +def _angle_link_end(line: str, pos: int, before: str | _Above = "") -> int | None: + """End, on ``line``, of the ``](<...>)`` link whose destination holds ``pos``: a backtick there is text, and opens no span. - Each line is read once, up to a blank line. The first closer decides: only blanks may follow it on its line. + Its ``]`` must close an opener in the paragraph, which may begin on the lines above (``before``). """ - rest = lines[row][col:] - text = rest.lstrip(" \t") # the destination ends at a blank, so the opener follows one - if text[:1] not in _TITLE_CLOSER: + above = _above(before) + found = line.rfind("](", 0, pos) + at = above.head + found if found >= 0 else above.last_open + if at is None: return None - body, closer = _TITLE_BODY[text[0]], _TITLE_CLOSER[text[0]] - pos = col + len(rest) - len(text) + 1 - while True: - line = lines[row] - stop = body.match(line, pos).end() # type: ignore[union-attr] # the body may be empty: it always matches - if stop < len(line): # a closer, or what no title holds: a `(`, or a backslash that ends the line - return row if line[stop] == closer and not line[stop + 1:].strip() else None - row += 1 - if row == len(lines) or not lines[row].strip(): - return None - pos = 0 + # mutation-ok[flip-bool]: the cache lives for this one call, and ``final`` only marks a ``](`` dead for the next + end = _LinkCache(final=True).end(lambda: _Text(above, line), at, above.head + pos) + return end - above.head if end is not None else None -def _angle_link_end(line: str, pos: int, before: str = "") -> int | None: - """End, on ``line``, of the ``](<...>)`` link whose destination holds ``pos``: a backtick there is text, and opens no span. +class _Above: + """The blanked lines above a line in its paragraph: the shared list ``rows``, which ends there, from ``start``. - Its ``]`` must close an opener in the paragraph, which may begin on the lines above (``before``). + The text a link check reads is ``"\\n".join(rows)``, a newline and the line. This keeps what a check needs of + it as the scan goes (the offset of each row, the last ``](`` whose link the rows have not settled), so the + rows are never joined or scanned per line. """ - head = before + "\n" if before else "" - text = head + line - p = len(head) + pos - i = text.rfind("](", 0, p) - end = _LinkCache(final=True).end(lambda: text, i, p) if i >= 0 else None - return end - len(head) if end is not None else None + + def __init__(self, rows: list[str]) -> None: + self.rows = rows + self.start = 0 + self.begins = [0] # the offset of each row scanned in the text, then of the line after them + self._open: int | None = None # the offset of the last ``](`` in the rows scanned, until a read settles its link + self._open_row = 0 # its row, counted from ``start`` # mutation-ok[bump-int,delete-statement]: read only once _open is set, with the row + + @classmethod + def of(cls, before: str) -> _Above: + # mutation-ok[take-branch]: a leading empty row only moves every offset by one + above = cls(before.split("\n") if before else []) + above.sync() + return above + + @property + def head(self) -> int: + """The offset of the line in the text.""" + return self.begins[-1] + + def reach(self, lines: list[str], i: int) -> None: + """Move to line ``i``: a raw blank line or a fence line above it ends the paragraph; a line blanked to spaces does not.""" + if i and (not lines[i - 1].strip() or _FENCE.match(lines[i - 1])): # mutation-ok[drop-clause]: a reset at line 0 changes nothing + self.start = i + self.begins = [0] + self._open = None + self.sync() + + def sync(self) -> None: + """Scan the rows not scanned yet, once each.""" + for j in range(self.start + len(self.begins) - 1, len(self.rows)): + row = self.rows[j] + if (k := row.rfind("](")) >= 0: + self._open = self.begins[-1] + k + self._open_row = j - self.start + self.begins.append(self.begins[-1] + len(row) + 1) + + @property + def last_open(self) -> int | None: + """The offset of the last ``](`` in the rows whose link they do not settle, or ``None``. + + A line that reads no link (no backtick, no ``](``) never asks, so it never joins the rows. + """ + self._settle() + return self._open + + def _settle(self) -> None: + """Drop the last ``](`` once the rows alone decide its link: it closes in them, or what follows the ``](`` is no ``<``. + + Text added after the rows cannot change either answer, and a link that ends in the rows ends before any line + below them, so no line reads it again. A link still open stays, and is read from its own row on. + """ + if self._open is None: + return + tail = "\n".join(self.rows[self.start + self._open_row:]) + i = self._open - self.begins[self._open_row] + if _ANGLE_LINK.match(tail, i): + self._open = None + elif (j := _BLANKS.match(tail, i + 2).end()) < len(tail) and tail[j] != "<": # type: ignore[union-attr] # _BLANKS matches the empty string + self._open = None + + +def _above(before: str | _Above) -> _Above: + return before if isinstance(before, _Above) else _Above.of(before) + + +class _Text: + """The text of the paragraph above and ``line``, read by offset without joining the rows.""" + + def __init__(self, above: _Above, line: str) -> None: + self.above = above + self.line = line + + def __getitem__(self, i: int) -> str: + above = self.above + if i >= above.head: + return self.line[i - above.head] + t = bisect_right(above.begins, i) - 1 + row = above.rows[above.start + t] + return row[i - above.begins[t]] if i - above.begins[t] < len(row) else "\n" + + def tail(self, i: int) -> tuple[str, int]: + """The text from the row that holds offset ``i`` to the end of the line, and the offset of that row.""" + above = self.above + if i >= above.head: + return self.line, above.head + t = bisect_right(above.begins, i) - 1 + return "\n".join(above.rows[above.start + t:]) + "\n" + self.line, above.begins[t] + + def pieces(self, close: int) -> Iterator[str]: + """The text before offset ``close``, one row at a time, the last first; the row ``close`` is on stops at it.""" + above = self.above + if close >= above.head: + yield self.line[:close - above.head] + t = len(above.begins) - 1 + else: + t = bisect_right(above.begins, close) - 1 + yield above.rows[above.start + t][:close - above.begins[t]] + for j in range(above.start + t - 1, above.start - 1, -1): + yield above.rows[j] class _LinkCache: @@ -324,7 +394,7 @@ def __init__(self, final: bool) -> None: self._opened: set[int] = set() self._ends: dict[int, int] = {} - def end(self, text_of: Callable[[], str], i: int, p: int) -> int | None: + def end(self, text_of: Callable[[], _Text], i: int, p: int) -> int | None: """The end of the link the ``](`` at ``i`` starts when it is past ``p``; ``text_of`` builds the text, only when it is read.""" if i in self._dead: return None @@ -336,42 +406,35 @@ def end(self, text_of: Callable[[], str], i: int, p: int) -> int | None: self._dead.add(i) return None self._opened.add(i) - m = _ANGLE_LINK.match(text, i) + tail, shift = text.tail(i) # the ``](`` and what follows it: the rows above it are not read + m = _ANGLE_LINK.match(tail, i - shift) if m: - self._ends[i] = m.end() - return m.end() if m.end() > p else None - blanks = _BLANKS.match(text, i + 2) - j = blanks.end() if blanks else i + 2 - if self.final or (j < p and not text.startswith("<", j)): + self._ends[i] = m.end() + shift + return self._ends[i] if self._ends[i] > p else None + blanks = _BLANKS.match(tail, i - shift + 2) # mutation-ok[swap-addsub]: a wrong j only marks the ``](`` dead later or never + # mutation-ok[take-branch]: _BLANKS matches the empty string, so there is always a match + j = blanks.end() if blanks else i - shift + 2 + # mutation-ok[drop-clause]: a ``](`` not marked dead is read again, with the same answer + if self.final or (j + shift < p and not tail.startswith("<", j)): self._dead.add(i) return None -def _paragraph_start(lines: list[str], i: int, start: int) -> int: - """The line the paragraph of line ``i`` begins at, given ``start`` for line ``i - 1``: a raw blank line or fence ends one.""" - return i if i and (not lines[i - 1].strip() or _FENCE.match(lines[i - 1])) else start - - -def _paragraph_above(out: list[str], start: int, i: int) -> str: - """The blanked lines of the paragraph that starts at line ``start``, up to line ``i``, joined.""" - return "\n".join(out[start:i]) - - -def _unpaired_run(line: str, before: str | Callable[[], str] = "", linked: str | None = None) -> re.Match | None: +def _unpaired_run(line: str, before: str | _Above = "", linked: str | None = None) -> re.Match | None: """The first backtick run left on ``line`` whose first backtick is not escaped and not in a ``<...>`` destination. The links are read on ``linked``, the line with a blank as ``_FILL``, not as a space (``line`` when None). """ - if not _BACKTICK_RUN.search(line): - return None # the paragraph above is read only for a run - before = before() if callable(before) else before - head = before + "\n" if before else "" - text = head + (line if linked is None else linked) - opens = [m.start() for m in re.finditer(r"\]\(", text)] + if "`" not in line: + return None + above = _above(before) + read = line if linked is None else linked + text = _Text(above, read) + opens = ([] if above.last_open is None else [above.last_open]) + [above.head + m.start() for m in re.finditer(r"\]\(", read)] links = _LinkCache(final=True) def in_link(pos: int) -> bool: - p = len(head) + pos + p = above.head + pos k = bisect_right(opens, p - 2) - 1 return k >= 0 and links.end(lambda: text, opens[k], p) is not None @@ -380,66 +443,11 @@ def in_link(pos: int) -> bool: def _open_span(lines: list[str], i: int, line: str, run: re.Match | None) -> tuple[str, str]: """``(line, span)``: an unpaired backtick run that closes in a later line of its paragraph blanks the rest of ``line``.""" - if run and _span_closes_ahead(lines, i, run.group()): + if run and span_closes_ahead(lines, i, run.group()): return line[:run.start()] + " " * (len(line) - run.start()), run.group() return line, "" -def _span_end(line: str, span: str) -> int: - """The offset just past the backtick run ``span`` that closes a code span on ``line``, or -1.""" - closer = re.search(r"(? tuple[bool, bool, bool]: - """``(in_list, code, hidden)`` after line ``i``: an indented line outside a list item, after a blank line or code, is code.""" - line = lines[i] - if not line.strip(): - return in_list, code, False - prev_blank = i == 0 or not lines[i - 1].strip() - if _LIST_ITEM.match(line) and (in_list or not line.startswith((" ", "\t")) or not (prev_blank or code)): - in_list = True - elif line[0] not in " \t" and (prev_blank or _BLOCK_START.match(line)): - in_list = False - hidden = not in_list and line.startswith((" ", "\t")) and (prev_blank or code) - return in_list, hidden, hidden - - -def _paragraph_break(line: str) -> bool: - """Whether ``line`` ends the paragraph before it: blank, a fence, a list item, a heading or a quote.""" - return not line.strip() or bool(_fence_opener(line) or _LIST_ITEM.match(line) or _BLOCK_START.match(line)) - - -def _close_ahead(lines: list[str]) -> list[bool]: - """For each line, whether a ``-->`` follows it in the same paragraph.""" - ahead = [False] * len(lines) - seen = False - for i in range(len(lines) - 1, -1, -1): - ahead[i] = seen - if _paragraph_break(lines[i]): - seen = False - elif "-->" in lines[i]: - seen = True - return ahead - - -def _span_closes_ahead(lines: list[str], i: int, run: str) -> bool: - """Whether a backtick run of the length of ``run`` closes the code span it opens on line ``i``, within its paragraph.""" - closer = re.compile(r"(? bool: - """Whether ``line`` closes the fence ``fence``: the same character, at least as long, nothing after it.""" - m = _FENCE.match(line) - return bool(m and m.group(1)[0] == fence[0] and len(m.group(1)) >= len(fence) and not line[m.end():].strip()) - - class _BlankedLine: """``line`` with ranges blanked to spaces, collected as the scan goes and joined once. @@ -447,13 +455,11 @@ class _BlankedLine: reads the text before it, and it builds the blanked line when a ``](`` the blanks left may open a link. """ - def __init__(self, line: str, before: str | Callable[[], str]) -> None: + def __init__(self, line: str, above: _Above) -> None: self.line = line - self.before = before + self.above = above self.ranges: list[tuple[int, int]] = [] - self._prefix_text = "" # the paragraph above, newline-terminated, built once, when a blank or a link check first reads it - self._head = 0 - self._found: list[int] | None = None + self._head = above.head self._next = 0 self._last: int | None = None # the last ``](`` before the scan point that no blank touched self._links = _LinkCache(final=False) @@ -461,24 +467,20 @@ def __init__(self, line: str, before: str | Callable[[], str]) -> None: self._ends = 0 self._seen = 0 - def _opens(self) -> list[int]: - if self._found is None: - before = self.before() if callable(self.before) else self.before - self._prefix_text = before + "\n" if before else "" - self._head = len(self._prefix_text) - self._found = [m.start() for m in re.finditer(r"\]\(", self._prefix_text + self.line)] - return self._found + @cached_property + def _found(self) -> list[int]: + """The offsets of the ``](`` the scan may need, read only when a span is found: the open one above, then the line's.""" + above = self.above.last_open + return ([] if above is None else [above]) + [self._head + m.start() for m in re.finditer(r"\]\(", self.line)] def _advance(self, upto: int) -> None: - found = self._opens() - while self._next < len(found) and found[self._next] + 2 <= upto + self._head: - self._last = found[self._next] + while self._next < len(self._found) and self._found[self._next] + 2 <= upto + self._head: + self._last = self._found[self._next] self._next += 1 def blank(self, start: int, end: int) -> None: self._advance(start) - found = self._opens() - while self._next < len(found) and found[self._next] < end + self._head: + while self._next < len(self._found) and self._found[self._next] < end + self._head: self._next += 1 # a ``](`` the blank touches is gone self.ranges.append((start, end)) @@ -503,23 +505,22 @@ def angle_link_end(self, pos: int) -> int | None: self._advance(pos) if self._last is None: return None - end = self._links.end(lambda: self._prefix_text + self._so_far(), self._last, self._head + pos) + end = self._links.end(lambda: _Text(self.above, self._so_far()), self._last, self._head + pos) return end - self._head if end is not None else None -def _blank_inline( - line: str, closes_ahead: bool, pos: int = 0, before: str | Callable[[], str] = "" -) -> tuple[str, str, re.Match | None]: +def _blank_inline(line: str, closes_ahead: bool, pos: int = 0, before: str | _Above = "") -> tuple[str, str, re.Match | None]: """Blank the code spans and the comments of ``line``, left to right: whichever starts first holds the text after it. - ``before`` is the paragraph above, or a call that builds it: it is called only when a link check needs it. + ``before`` is the paragraph above, as a string or an ``_Above``. Returns the line, the kind of a comment it leaves open, and a backtick run left unpaired on the line (its span may close on a later line). A comment opened mid-line with no ``-->`` in its paragraph (``closes_ahead`` False) is plain text, as Markdown reads it, so the scan goes on past it. """ scan = CodeSpanScanner(line, pos, stop=LINE_BREAK) - blanked = _BlankedLine(line, before) + above = _above(before) + blanked = _BlankedLine(line, above) start = line.find("`` is left from a comment start on: none is left from a later one while True: @@ -528,7 +529,7 @@ def _blank_inline( start = line.find(" `a` `b`", + "](<`a`>) `b`", ] @@ -146,23 +148,19 @@ def counting(text: str, close: int) -> bool: assert len(calls) == 2 # once while the spans are blanked, once for the unpaired run left at the end -class _CountingBefore(str): - """A paragraph above that counts how often a newline is appended to it, as a copy of the paragraph.""" +def test_the_paragraph_above_is_not_copied_for_a_link_on_the_line(monkeypatch: pytest.MonkeyPatch) -> None: + read: list[int] = [] + real = store._Text.tail - appended = 0 + def counting(self: store._Text, i: int) -> tuple[str, int]: + text, shift = real(self, i) + read.append(len(text) - len(self.line)) # what the text read holds beyond the line + return text, shift - def __add__(self, other: str) -> str: - if other == "\n": - type(self).appended += 1 - return str.__add__(self, other) - - -def test_the_paragraph_above_is_copied_with_its_newline_once_not_once_per_span() -> None: - _CountingBefore.appended = 0 - before = _CountingBefore("[open " + "x" * 1000) - out, _, _ = _blank_inline("]() " + _ticks(500) + "`b", False, 0, before) + monkeypatch.setattr(store._Text, "tail", counting) + out, _, _ = _blank_inline("]() " + _ticks(500) + "`b", False, 0, "[open " + "x" * 1000) assert out.startswith("]() ") - assert _CountingBefore.appended == 2 # one for the blanked line, one for the unpaired run left at the end + assert read and set(read) == {0} # a link on the line is read from the line: no row above is joined to it def test_the_backtick_runs_of_one_destination_are_checked_against_one_lookup_of_its_opener(monkeypatch: pytest.MonkeyPatch) -> None: @@ -180,6 +178,66 @@ def counting(text: str, close: int) -> bool: assert len(calls) == 1 +def test_the_opener_of_a_link_in_the_rows_above_is_looked_up_without_reading_each_character(monkeypatch: pytest.MonkeyPatch) -> None: + read: list[int] = [] + real = store._Text.__getitem__ + + def counting(self: store._Text, i: int) -> str: + read.append(i) + return real(self, i) + + monkeypatch.setattr(store._Text, "__getitem__", counting) + above = store._Above.of("\n".join("a](b" for _ in range(300))) + assert not store._has_opener(store._Text(above, "x"), 1001) + assert len(read) < 10 # each row is scanned whole: only the characters before the ``]`` itself are read + + +def test_the_opener_of_each_link_of_one_row_is_found_without_reading_the_brackets_before_it() -> None: + def every_link(k: int) -> Callable[[], list[bool]]: + row = "[x](a.md) " * k + text = store._Text(store._Above.of(""), row) + closes = [i for i, c in enumerate(row) if c == "]"] + return lambda: [store._has_opener(text, i) for i in closes] + + ratio, result = growth(every_link, 2000) + assert ratio < GROWTH_LIMIT + assert all(result) + + +@pytest.mark.parametrize("above, line, close, expected", [ + ("[a", "b]", 1, True), + ("[a\nb", "c](x", 1, True), + ("[a\n\nb", "c]", 1, False), + ("[a\n", "b]", 1, False), + ("\\[a", "b]", 1, False), + ("[a]\nb", "c]", 1, False), + ("[[a]\nb", "c]", 1, True), + ("[a\nb\\", "]", 0, True), +]) +def test_a_close_bracket_finds_its_opener_across_the_rows_above(above: str, line: str, close: int, expected: bool) -> None: + text = store._Text(store._Above.of(above), line) + joined = above + "\n" + line + assert store._has_opener(text, len(above) + 1 + close) is expected + assert store._has_opener(joined, len(above) + 1 + close) is expected + + +def test_the_text_of_the_rows_above_and_the_line_reads_as_the_joined_text() -> None: + lines = ["o]ld", "", "a[b", "c]", "d]ef", "gh"] + above = store._Above(lines[:5]) + for i in range(6): + above.reach(lines, i) + assert above.start == 2 # the raw blank line above ends the paragraph + text = store._Text(above, lines[5]) + joined = "\n".join(lines[2:]) + assert [text[i] for i in range(len(joined))] == list(joined) + for i in range(len(joined)): + tail, shift = text.tail(i) + assert shift == joined.rfind("\n", 0, i) + 1 # the offset of the row that holds ``i`` + assert tail == joined[shift:] + assert store._has_opener(text, i) == store._has_opener(joined, i) + assert [i for i in range(len(joined)) if store._has_opener(text, i)] == [2, 3, 4, 5] # ``a[`` opens until the ``]`` after the row break closes it + + def test_an_opener_blanked_inside_a_code_span_no_longer_opens_the_link() -> None: assert _blank_inline("`[`](<`a`>) `b`", False) == (" ](< >) ", "", None) assert _blank_inline("[`[`](<`a`>) `b`", False) == ("[ ](<`a`>) ", "", None) diff --git a/dokimi/tests/test_blank_paragraph.py b/dokimi/tests/test_blank_paragraph.py new file mode 100644 index 000000000..9a28a6e12 --- /dev/null +++ b/dokimi/tests/test_blank_paragraph.py @@ -0,0 +1,190 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""``prose_lines`` blanks a paragraph of many lines in time linear in its lines, with the output the joined paragraph gave (#1261).""" + +from __future__ import annotations + +import random +import re +from functools import partial + +import pytest + +from dokimi.memory import store +from dokimi.memory.store import _blank_blocks, _has_opener, prose_lines +from tests import test_blank_inline +from tests.growth_timing import GROWTH_LIMIT, growth +from tests.work_count import WORK_LIMIT, Tally, count_calls, work_ratio + + +def _old_paragraph_above(lines: list[str], out: list[str], i: int) -> str: + """The paragraph above line ``i`` as it was found and joined for every line.""" + k = i + while k > 0 and lines[k - 1].strip() and not store._FENCE.match(lines[k - 1]): + k -= 1 + return "\n".join(out[k:i]) + + +def _ref_angle_link_end(line: str, pos: int, before: str = "") -> int | None: + head = before + "\n" if before else "" + text = head + line + i = text.rfind("](", 0, len(head) + pos) + if i < 0 or not _has_opener(text, i): + return None + m = store._ANGLE_LINK.match(text, i) + return m.end() - len(head) if m and m.end() > len(head) + pos else None + + +def _ref_unpaired_run(line: str, before: str = "", linked: str | None = None): + read = line if linked is None else linked + for m in store._BACKTICK_RUN.finditer(line): + if not store._escaped(line, m.start()) and _ref_angle_link_end(read, m.start(), before) is None: + return m + return None + + +def _reference(lines: list[str], monkeypatch: pytest.MonkeyPatch) -> tuple[list[str], list[str]]: + """``_blank_blocks`` with the paragraph above joined for every line and scanned as text, with no cache.""" + + def blank_inline(line, closes_ahead, pos, above): + before = above if isinstance(above, str) else _old_paragraph_above(lines, above.rows, len(above.rows)) + return test_blank_inline._rebuilding(line, closes_ahead, pos, before) + + with monkeypatch.context() as mp: + mp.setattr(test_blank_inline, "_angle_link_end", _ref_angle_link_end) + mp.setattr(test_blank_inline, "_unpaired_run", _ref_unpaired_run) + mp.setattr(store, "_blank_inline", blank_inline) + return _blank_blocks(lines) + + +COUNTEREXAMPLES = [ + "[x]() `c`", # a destination that goes on at the next line + "[x]() `c`\n`d` `e`\n[y](<`f`>) `g`", + "[open\n" + "word `a` word\n" * 20 + "x](<`b`>) `c`", # an opener many lines above + "[open\n``` `a`\n](<`b`>) `c`", # a fence ends the paragraph, even one that opens no block + "[open\n```\nx\n```\n](<`b`>) `c`", + "[open\n`x`\n](<`b`>) `c`", # a line blanked to spaces does not end it + "[open\n\n](<`b`>) `c`", + "[open\n\n](<`b`>) `c`", + "".join(f"[x{k}](<`a`>) `b` ](<`c`>)\n" for k in range(12)), # every line holds a ]( + "".join(f"x](<`a{k}`>) `b` [y\n" for k in range(12)), + "[x](\n<`a`>) `b`\n[y](\n<`c`> \"t\n`d`\") `e`", + "`a\nb` [x](<`c`>)\n`d", + "[yyyy](\n\n[x](<`a`>) `b`", # the ]( of the paragraph before is not the one above + "z\n\n[x\ny](\n<`a`>) `b`", # a ]( in the second row of a paragraph that is not the first + "z\n\n[open\n`x`\n](<`b`>) `c`", + "[x]() z\n`a` ](<`b`>) `c`\n`d` `e`", # a link closed on its own row, then another opener + "[x](y) z\n`a` ](<`b`>) `c`", + "[x]( \"\n`a`\nt\") `b`\n`c` `d`", # a title that closes three rows on holds the code span between + "[x](\n\"t\"\n) `a`\n`b`", + "[x](\n<`a`>) `b`\n`c` `d`", # blanks to the end of the rows: the next row may still open the destination + "[x]( \n \n`a` `b`", +] + + +@pytest.mark.parametrize("text", COUNTEREXAMPLES) +def test_a_paragraph_blanks_as_the_joined_paragraph_above_did(text: str, monkeypatch: pytest.MonkeyPatch) -> None: + assert _blank_blocks(text.split("\n")) == _reference(text.split("\n"), monkeypatch) + + +def test_the_paragraph_above_is_the_lines_after_the_last_raw_blank_line_or_fence() -> None: + assert prose_lines("[open\n``` `a`\n](<`b`>) `c`") == ["[open", "``` ", "](< >) "] # no opener: the link is no link + assert prose_lines("[open\n`x`\n](<`b`>) `c`") == ["[open", " ", "](<`b`>) "] # the opener is in the paragraph + + +def test_a_link_destination_goes_on_at_the_next_line_as_it_did() -> None: + assert prose_lines("[x]() `c`") == ["[x]() "] + assert store._blank_inline("`b`>) `c`", False, 0, "[x]() ", "", None) + + +def test_the_blanked_lines_match_on_short_seeded_random_texts(monkeypatch: pytest.MonkeyPatch) -> None: + rng = random.Random(1261) + pieces = ["`", "``", "`a`", "", "[a](<", ">)", "](", "[", "]", " ", "\\", "x", "\n", "\n", "\n\n", "```\n", "~~~\n", " ", "- ", "# "] + for _ in range(2500): + text = "".join(rng.choice(pieces) for _ in range(rng.randrange(1, 24))) + assert _blank_blocks(text.split("\n")) == _reference(text.split("\n"), monkeypatch), text + + +def _ticks(k: int) -> str: + return "word `a` word\n" * k + + +def _links(k: int) -> str: + return "[x]() word `a` word\n" * k + + +def _opener_at_the_top(k: int) -> str: + return "[open\n" + _ticks(k) + + +def _closed_link_at_the_top(k: int) -> str: + return "[x]() z\n" + _ticks(k) + + +def _closed_link_below_the_top(k: int) -> str: + return "intro\nmore\n[x]() z\n" + _ticks(k) + + +def _closed_link_below_the_top_each_row(k: int) -> str: + return "intro\n" + "[x]() z `a`\n" * k + + +def _closed_title_at_the_top(k: int) -> str: + return '[x]( "t\nu") z\n' + _ticks(k) + + +def _plain_destination_at_the_top(k: int) -> str: + return "[x](y) z\n" + _ticks(k) + + +def _closed_link_then_unpaired(k: int) -> str: + return "[x]() z\n" + "word ` word\n" * k + + +@pytest.mark.parametrize( + "shape", [_closed_link_at_the_top, _closed_link_below_the_top, _closed_title_at_the_top, _plain_destination_at_the_top, _closed_link_then_unpaired] +) +def test_a_link_settled_in_the_rows_above_is_not_read_again_for_each_line(monkeypatch: pytest.MonkeyPatch, shape) -> None: + tally = count_calls(monkeypatch, store._Text, "tail", size=lambda self, i: len(self.line)) + prose_lines(shape(50)) + assert tally.calls == 0 # each line below it would join the rows from the link's row on + + +class _WholeText: + """``_ANGLE_LINK`` that adds the whole length of each text it matches on, from its start, not from the match position.""" + + def __init__(self, pattern: re.Pattern[str], tally: Tally) -> None: + self.pattern, self.tally = pattern, tally + + def match(self, text: str, pos: int = 0) -> re.Match[str] | None: + self.tally.size += len(text) + self.tally.calls += 1 + return self.pattern.match(text, pos) + + +def test_a_link_is_settled_from_its_own_row_not_from_the_start_of_the_paragraph(monkeypatch: pytest.MonkeyPatch) -> None: + tally = Tally() + monkeypatch.setattr(store, "_ANGLE_LINK", _WholeText(store._ANGLE_LINK, tally)) + assert work_ratio(tally, lambda n: prose_lines(_closed_link_below_the_top_each_row(n)), 60) < WORK_LIMIT + + +def test_a_line_with_no_backtick_does_not_read_the_link_left_open_above_it(monkeypatch: pytest.MonkeyPatch) -> None: + tally = Tally() + monkeypatch.setattr(store, "_ANGLE_LINK", _WholeText(store._ANGLE_LINK, tally)) + assert prose_lines("[x](\n" + "word word\n" * 50) == ["[x]("] + ["word word"] * 50 + [""] + assert tally.calls == 0 # each plain line would join the rows from the open link on + + +def test_a_link_still_open_in_the_rows_above_is_read_from_its_own_row_on(monkeypatch: pytest.MonkeyPatch) -> None: + tally = count_calls(monkeypatch, store._Text, "tail", size=lambda self, i: len(self.line)) + assert prose_lines('[x]( "\n`a`\nt") `b`\n') == ['[x]( "', " ", 't") ', ""] + assert tally.calls > 0 + + +@pytest.mark.parametrize("shape, first", [(_ticks, "word word"), (_links, "[x]() word word"), (_opener_at_the_top, "[open")]) +def test_a_paragraph_of_many_lines_grows_linearly_in_its_lines(shape, first: str) -> None: + ratio, result = growth(lambda k: partial(prose_lines, shape(k)), 200) + assert ratio < GROWTH_LIMIT + assert result[0] == first + assert len(result) == 16 * 200 + 1 + (shape is _opener_at_the_top) diff --git a/dokimi/tests/test_memory_blocks.py b/dokimi/tests/test_memory_blocks.py new file mode 100644 index 000000000..0e6e04363 --- /dev/null +++ b/dokimi/tests/test_memory_blocks.py @@ -0,0 +1,114 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""The block rules ``memory.store`` blanks an index by: which lines are fences, code, list items, and where a paragraph ends.""" + +from __future__ import annotations + +import pytest + +from dokimi.memory.blocks import ( + close_ahead, + closes_fence, + fence_opener, + indented_code, + paragraph_break, + resume_comment, + span_closes_ahead, + span_end, +) + + +@pytest.mark.parametrize("line, opener", [("```py", "```"), (" ~~~~", "~~~~"), ("``` `a`", ""), ("~~~ `x`", "~~~"), ("text", ""), (" ```", "")]) +def test_a_fence_opens_at_three_marks_up_to_three_spaces_in_and_a_backtick_fence_has_no_backtick_in_its_info(line: str, opener: str) -> None: + assert fence_opener(line) == opener + + +@pytest.mark.parametrize("line, fence, closes", [ + ("```", "```", True), ("````", "```", True), ("``", "```", False), ("~~~", "```", False), ("``` x", "```", False), ("```", "````", False), +]) +def test_a_fence_closes_on_the_same_mark_as_long_with_nothing_after_it(line: str, fence: str, closes: bool) -> None: + assert closes_fence(line, fence) is closes + + +@pytest.mark.parametrize("line, span, end", [("a``b``c", "``", 3), ("a`b", "``", -1), ("x ` y", "`", 3), ("a``b", "`", -1)]) +def test_a_span_ends_after_the_first_run_of_its_own_length(line: str, span: str, end: int) -> None: + assert span_end(line, span) == end + + +def _hidden(lines: list[str]) -> list[bool]: + in_list = code = False + out = [] + for i in range(len(lines)): + in_list, code, hidden = indented_code(lines, i, in_list, code) + out.append(hidden) + return out + + +@pytest.mark.parametrize("lines, hidden", [ + ([" x"], [True]), + ([" c", " d"], [True, True]), + (["a", " b"], [False, False]), + (["a", "", " code"], [False, False, True]), + (["- a", " b"], [False, False]), + (["- a", "", " b"], [False, False, False]), + (["- a", "# h", "", " c"], [False, False, False, True]), + (["- a", "b", "", " c"], [False, False, False, False]), + (["- a", "", "b", "", " c"], [False, False, False, False, True]), + (["", " - a"], [False, True]), + (["x", " - a"], [False, False]), + ([" c", "", " d"], [True, False, True]), +]) +def test_an_indented_line_outside_a_list_item_after_a_blank_line_or_code_is_code(lines: list[str], hidden: list[bool]) -> None: + assert _hidden(lines) == hidden + + +def test_a_blank_line_changes_neither_the_list_nor_the_code_state() -> None: + assert indented_code([""], 0, True, True) == (True, True, False) + assert indented_code([" "], 0, False, False) == (False, False, False) + + +@pytest.mark.parametrize("line, breaks", [ + ("", True), (" ", True), ("```", True), ("- a", True), ("1. a", True), ("# h", True), ("> q", True), + ("text", False), (" # x", False), ("a - b", False), +]) +def test_a_paragraph_ends_at_a_blank_line_a_fence_a_list_item_a_heading_or_a_quote(line: str, breaks: bool) -> None: + assert paragraph_break(line) is breaks + + +@pytest.mark.parametrize("lines, ahead", [ + ([""], [True, False]), + ([""], [False, True, False]), # the blank line itself is followed by a close, the line above it is cut off + (["", "d"], [True, True, False, False]), + (["-->", "- x"], [False, False]), + (["a", "- b -->"], [False, False]), + (["a", "b"], [False, False]), +]) +def test_a_close_ahead_is_a_close_later_in_the_same_paragraph(lines: list[str], ahead: list[bool]) -> None: + assert close_ahead(lines) == ahead + + +@pytest.mark.parametrize("lines, closes", [ + (["`a", "b`"], True), + (["`a", "", "b`"], False), + (["`a", "b``"], False), + (["`a", "- b`"], False), + (["`a", "b"], False), + (["`a"], False), +]) +def test_a_span_closes_ahead_on_a_run_of_its_length_within_its_paragraph(lines: list[str], closes: bool) -> None: + assert span_closes_ahead(lines, 0, "`") is closes + + +@pytest.mark.parametrize("line, comment, opener, expected", [ + ("", "inline", "", ("", "", "")), + ("```", "inline", "```", ("```", "", "```")), + ("", "block", "", (None, "block", "")), + ("text", "inline", "", (None, "inline", "")), + ("a --> b", "inline", "", (" b", "", "")), + ("a --> b", "block", "```", (" b", "", "")), +]) +def test_a_comment_resumes_on_a_line_until_its_close_and_an_inline_one_ends_at_a_paragraph_break( + line: str, comment: str, opener: str, expected: tuple[str | None, str, str] +) -> None: + assert resume_comment(line, comment, opener) == expected diff --git a/dokimi/tests/test_memory_index_definitions_linear.py b/dokimi/tests/test_memory_index_definitions_linear.py index 3e6c2dc4d..ececd1ad3 100644 --- a/dokimi/tests/test_memory_index_definitions_linear.py +++ b/dokimi/tests/test_memory_index_definitions_linear.py @@ -17,7 +17,8 @@ import pytest from dokimi.memory import store -from dokimi.memory.store import MemoryEntry, MemoryStore, _definitions, _title_spans +from dokimi.memory.store import MemoryEntry, MemoryStore, _definitions +from dokimi.memory.titles import title_spans from tests.work_count import WORK_LIMIT, count_calls, count_pattern, work_ratio @@ -67,7 +68,7 @@ def _spans_both(text: str, every: bool = False) -> tuple[list[tuple[int, int]], for line in lines: begin.append(begin[-1] + len(line) + 1) defs = _every_definition(lines) if every else _definitions(lines) - return _title_spans(lines, begin, defs), _old_title_spans(lines, begin, defs) + return title_spans(lines, begin, defs), _old_title_spans(lines, begin, defs) AWKWARD = [ @@ -153,16 +154,18 @@ def test_the_paragraph_start_is_tracked_not_found_by_a_walk_back_per_line(monkey @pytest.mark.parametrize("shape", REPROS) -def test_the_paragraph_above_is_not_joined_for_a_line_with_no_code_span_or_comment(monkeypatch: pytest.MonkeyPatch, shape: Callable[[int], str]) -> None: - tally = count_calls(monkeypatch, store, "_paragraph_above", size=lambda *args, **kwargs: 1) +def test_the_paragraph_above_is_not_read_for_a_line_with_no_code_span_or_comment(monkeypatch: pytest.MonkeyPatch, shape: Callable[[int], str]) -> None: + # Test-narrowed: renamed, not removed: `_paragraph_above` is gone, so it counts the reads of the paragraph above. + tally = count_calls(monkeypatch, store._Text, "tail", size=lambda *args, **kwargs: 1) _targets(shape(200)) assert tally.calls == 0 -def test_the_paragraph_above_is_joined_once_for_a_line_that_reads_it_twice(monkeypatch: pytest.MonkeyPatch) -> None: - tally = count_calls(monkeypatch, store, "_paragraph_above", size=lambda *args, **kwargs: 1) +def test_the_paragraph_above_is_not_read_for_a_backtick_left_over_when_no_link_is_above(monkeypatch: pytest.MonkeyPatch) -> None: + # Test-narrowed: renamed, not removed: the paragraph above is not joined at all now, so no row of it is read. + tally = count_calls(monkeypatch, store._Text, "tail", size=lambda *args, **kwargs: 1) _targets("[x]: a.md\n`a` `\n") # the span is blanked, then the backtick left over is checked against the links above - assert tally.calls == 1 + assert tally.calls == 0 def test_the_index_of_definitions_gives_its_targets() -> None: