Skip to content
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Fixed

- **`dokimi memory lint` no longer reads a code span before an angle destination as whitespace**, so the link check no longer takes ``[x]( `a` <y `b`>)`` for a link, in `prose_lines` and in the index targets `MemoryStore.index_targets()` returns (#1343). Whether a `[label]` uses a definition is read the same way, and a `](` inside a destination is not a second link.
98 changes: 71 additions & 27 deletions dokimi/dokimi/memory/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

import re
from bisect import bisect_right
from collections.abc import Callable
from collections.abc import Callable, Iterable
from dataclasses import dataclass, field
from functools import cache, partial
from html import unescape
Expand Down Expand Up @@ -44,6 +44,7 @@
_BLOCK_START = re.compile(r" {0,3}(?:#{1,6}(?:[ \t]|$)|>)")
_BACKTICK_RUN = re.compile(r"(?<!`)`+(?!`)")
_BLANKS = re.compile(_WS)
_FILL = "\x00" # a blank of the line a link is read on: no space, bracket, parenthesis, quote, backtick or angle bracket, so a blanked span is text there
_ANGLE_LINK = re.compile(r"\]\(" + _WS + r"<[^<>\n]*>(?:\s+(?:\"[^\"]*\"|'[^']*'|\([^()]*\)))?" + _WS + r"\)") # the title grammar of _MD_LINK
_TITLE_CLOSED = re.compile(r"[ \t]+(?:\"(?:\\.|[^\"\\])*\"|'(?:\\.|[^'\\])*'|\((?:\\.|[^()\\])*\))\s*$")
_TITLE_CLOSER = {'"': '"', "'": "'", "(": ")"}
Expand Down Expand Up @@ -114,22 +115,26 @@
"""
if self.index is None:
return []
lines = prose_lines(self.index.text) # blanked to the same columns, so a label is read from the raw text
source = self.index.text.split("\n")
lines, filled = _blank_blocks(source) # blanked to the same columns, so a label is read from the raw text
defs = _definitions(lines)
used = _used_labels(lines, source, defs)
used = _used_labels(filled, source, defs)
found: list[tuple[int, str, bool]] = []
text = "\n".join(lines)
text = "\n".join(filled) # a blanked span is text to a link, not a space that ends its destination
Comment thread
antonwolfy marked this conversation as resolved.
Resolved
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
matches = list(_MD_LINK.finditer(text))
opened = _closing_openers(text, {m.start() for m in matches})
title_starts, title_ends = _merged(titles)
for m in matches:
i = bisect_right(title_starts, m.start()) - 1
if m.start() in opened and not (i >= 0 and m.start() < title_ends[i]):
found.append((bisect_right(starts, m.start()) + 1, m.group(1), True))

def live(at: int) -> bool:
i = bisect_right(title_starts, at) - 1
return at in opened and not (i >= 0 and at < title_ends[i])

for link in _links(matches, raw, live):
found.append((bisect_right(starts, link.start()) + 1, link.group(1), True))
defined: set[str] = set()
for k, m in sorted(defs.items()): # the first definition of a label is the one Markdown uses
label = _label(source[k][m.start(1):m.end(1)])
Expand All @@ -150,17 +155,20 @@

def prose_lines(text: str) -> list[str]:
"""The lines of ``text`` with fenced blocks, HTML comments and code spans blanked: no link lives there."""
return _blank_blocks(text.split("\n"))
return _blank_blocks(text.split("\n"))[0]


def _blank_blocks(lines: list[str]) -> list[str]:
"""The lines with fenced and indented code, HTML comments and code spans blanked to spaces, so every column keeps its place.
def _blank_blocks(lines: list[str]) -> tuple[list[str], list[str]]:
"""``(blanked, filled)``: the lines with fenced and indented code, HTML comments and code spans blanked to spaces, so every column keeps its place.

``filled`` is the same with each blank inside a line as ``_FILL``: the text a link is matched on, where a blanked span is text.

One scan, so whichever opens first holds the lines after it. A comment that opens a line (up to three
spaces in) runs to its ``-->``, blank lines included, or to the end of the text. One opened mid-line
needs a ``-->`` in its paragraph and ends at a blank line, a fence or the next block start.
"""
out: list[str] = []
filled: list[str] = [] # the same lines with a blanked span as ``_FILL``, the paragraph above that a link is read on
fence = ""
comment = "" # "", or the kind of the comment the scan is inside: "block" or "inline"
span = "" # the backtick run of a code span that runs on over the line break
Expand All @@ -176,6 +184,7 @@
fence = ""
out.append(" " * len(line))
continue
source = line
if comment:
rest, comment, opener = _resume_comment(line, comment, opener)
if rest is None:
Expand All @@ -198,13 +207,38 @@
if hidden and not pos:
out.append(" " * len(line))
continue
above = cache(partial(_paragraph_above, out, start, i)) # joined only when a link check reads it, and once
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, span = _open_span(lines, i, line, run)
out.append(line)
filled.append(_fill_blanks(source, line))
filled.extend(out[len(filled):])
return out, filled


def _links(matches: Iterable[re.Match], raw: str, live: Callable[[int], bool] = lambda _: True) -> list[re.Match]:
"""The links of ``matches`` (read on the filled text) that ``raw`` holds at the same offset, each matched on ``raw``.

A span is text to the filled match, but its backticks are plain characters of a destination. A raw link may
run past its filled match: a later match inside it is part of that destination, not a link.
"""
out: list[re.Match] = []
end = 0

Check warning on line 227 in dokimi/dokimi/memory/store.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: bump-int `0` -> `1`
for m in matches:
if m.start() >= end and live(m.start()) and (link := _MD_LINK.match(raw, m.start())) is not None:
out.append(link)
end = link.end()
return out


def _fill_blanks(source: str, blanked: str) -> str:
"""``blanked`` with each space that replaced a non-space of ``source`` as ``_FILL``."""
Comment thread
antonwolfy marked this conversation as resolved.
Resolved
if blanked == source:
return blanked
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
Expand Down Expand Up @@ -323,13 +357,16 @@
return "\n".join(out[start:i])


def _unpaired_run(line: str, before: str | Callable[[], str] = "") -> re.Match | None:
"""The first backtick run left on ``line`` whose first backtick is not escaped and not in a ``<...>`` destination."""
def _unpaired_run(line: str, before: str | Callable[[], str] = "", 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
text = head + (line if linked is None else linked)
opens = [m.start() for m in re.finditer(r"\]\(", text)]
links = _LinkCache(final=True)

Expand Down Expand Up @@ -445,18 +482,18 @@
self._next += 1 # a ``](`` the blank touches is gone
self.ranges.append((start, end))

def text(self, upto: int | None = None) -> str:
"""The blanked line, or its first ``upto`` characters, joined from the ranges in one pass."""
def text(self, upto: int | None = None, fill: str = " ") -> str:
"""The blanked line, or its first ``upto`` characters, joined from the ranges in one pass; a blank is ``fill`` per column."""
line = self.line if upto is None else self.line[:upto]
chunks, prev = [], 0
for a, b in self.ranges:
chunks += [line[prev:a], " " * (b - a)]
chunks += [line[prev:a], fill * (b - a)]
prev = b
return "".join(chunks) + line[prev:]

def _so_far(self) -> str:
for a, b in self.ranges[self._seen:]: # the ranges blanked since the last call extend the prefix
self._prefix += self.line[self._ends:a] + " " * (b - a)
self._prefix += self.line[self._ends:a] + _FILL * (b - a)
self._ends = b
self._seen = len(self.ranges)
return self._prefix + self.line[self._ends:]
Expand Down Expand Up @@ -491,7 +528,7 @@
start = line.find("<!--", pos) # a start the scan has passed; -1 stays -1, as no later read finds one
if code is None and start < 0:
out = blanked.text()
return out, "", _unpaired_run(out, before)
return out, "", _unpaired_run(out, before, blanked.text(fill=_FILL))
if code is not None and (start < 0 or code.start() < start):
if (link := blanked.angle_link_end(code.start())) is not None: # a backtick in the destination is text
pos = link
Expand All @@ -512,11 +549,14 @@


def _used_labels(lines: list[str], source: list[str], defs: dict[int, re.Match]) -> set[str]:
"""The labels some link uses: ``[label]``, ``[label][]``, ``[text][label]`` (only ``label``). A label is read from ``source``."""
"""The labels some link uses: ``[label]``, ``[label][]``, ``[text][label]`` (only ``label``). A label is read from ``source``.

``lines`` are the filled lines: an inline link is read on them and on ``source``, as ``index_targets`` reads it.
"""
used: set[str] = set() # the label that opens a definition is not a use of itself
for k, line in enumerate(lines):
d = defs.get(k)
span_starts, span_ends = _merged([m.span() for m in _MD_LINK.finditer(line)]) # a label inside a destination or title is no use
span_starts, span_ends = _merged([m.span() for m in _links(_MD_LINK.finditer(line), source[k])]) # a label inside a destination or title is no use
begin = d.end() if d else 0
if d and d.end() > len(line): # the destination is on the next line: the label line holds no use
begin = len(line)
Expand All @@ -528,15 +568,16 @@
inside = at >= 0 and m.start() < span_ends[at]
text_of_explicit = j + 1 < len(labels) and labels[j + 1].start() == m.end() # [text][label]: text is no use
two = line + "\n" + lines[k + 1] if k + 1 < len(lines) else line # a destination may start on the next line
raw = source[k] + "\n" + source[k + 1] if k + 1 < len(lines) else source[k]

Check warning on line 571 in dokimi/dokimi/memory/store.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: swap-addsub `k + 1` -> `k - 1`

Check warning on line 571 in dokimi/dokimi/memory/store.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: take-branch `source[k] + "\n" + source[k + 1] if k + 1 < len(lines) else source[k]` -> `(source[k])`
escaped = _escaped(line, m.start()) # \[label] opens no reference
if not inside and not escaped and not text_of_explicit and not _inline_link_at(two, m.end()): # [t](...) with no valid destination is [t]
if not inside and not escaped and not text_of_explicit and not _inline_link_at(two, raw, m.end()): # [t](...) with no valid destination is [t]

Check warning on line 573 in dokimi/dokimi/memory/store.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: drop-clause `not inside and not escaped and not text_of_explicit and not _inline_link_at(two, raw, m.end())` -> `(not inside and (not text_of_explicit) and (not _inline_link_at(two, raw, m.end())))`

Check warning on line 573 in dokimi/dokimi/memory/store.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: drop-clause `not inside and not escaped and not text_of_explicit and not _inline_link_at(two, raw, m.end())` -> `(not inside and (not escaped) and (not _inline_link_at(two, raw, m.end())))`
used.add(_label(source[k][m.start(1):m.end(1)]))
for k, (a, b) in enumerate(zip(lines, lines[1:], strict=False)): # a label may wrap onto the next line
pair = f"{a}\n{b}"
source_pair = f"{source[k]}\n{source[k + 1]}"
for m in _LABEL_ACROSS_LINES.finditer(pair):
explicit = pair.startswith("[", m.end()) and not pair.startswith("[]", m.end())
if "\n" in m.group(1) and not explicit and not _escaped(pair, m.start()) and not _inline_link_at(pair, m.end()):
if "\n" in m.group(1) and not explicit and not _escaped(pair, m.start()) and not _inline_link_at(pair, source_pair, m.end()):

Check warning on line 580 in dokimi/dokimi/memory/store.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: drop-clause `"\n" in m.group(1) and not explicit and not _escaped(pair, m.start()) and not _inline_link_at(pair, source_pair, m.end())` -> `('\n' in m.group(1) and (not explicit) and (not _inline_link_at(pair, source_pair, m.end())))`

Check warning on line 580 in dokimi/dokimi/memory/store.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: drop-clause `"\n" in m.group(1) and not explicit and not _escaped(pair, m.start()) and not _inline_link_at(pair, source_pair, m.end())` -> `('\n' in m.group(1) and (not explicit) and (not _escaped(pair, m.start())))`

Check warning on line 580 in dokimi/dokimi/memory/store.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: drop-clause `"\n" in m.group(1) and not explicit and not _escaped(pair, m.start()) and not _inline_link_at(pair, source_pair, m.end())` -> `('\n' in m.group(1) and (not _escaped(pair, m.start())) and (not _inline_link_at(pair, source_pair, m.end())))`
used.add(_label(source_pair[m.start(1):m.end(1)]))
return used

Expand Down Expand Up @@ -637,9 +678,12 @@
return re.sub(r"\s+", " ", text).strip().casefold()


def _inline_link_at(line: str, end: int) -> bool:
"""Whether the ``[label]`` ending at ``end`` is followed by a valid inline destination ``(...)``."""
return line.startswith("(", end) and (_MD_LINK.match(line, end - 1) or _EMPTY_LINK.match(line, end - 1)) is not None
def _inline_link_at(line: str, raw: str, end: int) -> bool:
"""Whether the ``[label]`` ending at ``end`` of the filled ``line`` is followed by a valid inline destination ``(...)``."""
if not line.startswith("(", end):
return False

Check warning on line 684 in dokimi/dokimi/memory/store.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: return-none `False` -> `None`
link = _MD_LINK.match(line, end - 1)
return bool(link and _links([link], raw)) or _EMPTY_LINK.match(line, end - 1) is not None

Check warning on line 686 in dokimi/dokimi/memory/store.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: drop-clause `bool(link and _links([link], raw)) or _EMPTY_LINK.match(line, end - 1) is not None` -> `(bool(link and _links([link], raw)))`


def slug(name: str) -> str:
Expand Down
72 changes: 68 additions & 4 deletions dokimi/tests/test_blank_inline.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,28 +15,31 @@

from dokimi.code_spans import LINE_BREAK, CodeSpanScanner
from dokimi.memory import store
from dokimi.memory.store import _angle_link_end, _blank_inline, _code_span, _unpaired_run
from dokimi.memory.store import MemoryEntry, MemoryStore, _angle_link_end, _blank_inline, _code_span, _unpaired_run, prose_lines
from tests.growth_timing import GROWTH_LIMIT, growth


def _rebuilding(line: str, closes_ahead: bool, pos: int = 0, before: str = "") -> tuple[str, str, re.Match | None]:
"""The function as it was: the line is rebuilt, and every later read sees the blanked text."""
scan = CodeSpanScanner(line, pos, stop=LINE_BREAK)
filled = line # the same line with a blank as the filler, which the links are read on
while True:
code = _code_span(line, pos, scan)
start = line.find("<!--", pos)
if code is None and start < 0:
return line, "", _unpaired_run(line, before)
return line, "", _unpaired_run(line, before, filled)
if code is not None and (start < 0 or code.start() < start):
if (link := _angle_link_end(line, code.start(), before)) is not None:
if (link := _angle_link_end(filled, code.start(), before)) is not None:
pos = link
continue
line = line[:code.start()] + " " * (code.end() - code.start()) + line[code.end():]
filled = filled[:code.start()] + store._FILL * (code.end() - code.start()) + filled[code.end():]
pos = code.end()
continue
end = line.find("-->", start + 2)
if end >= 0:
line = line[:start] + " " * (end + 3 - start) + line[end + 3:]
filled = filled[:start] + store._FILL * (end + 3 - start) + filled[end + 3:]
pos = end + 3
continue
block = start <= 3 and not line[:start].strip()
Expand Down Expand Up @@ -192,13 +195,74 @@ def test_a_link_opened_on_the_line_above_holds_the_spans_of_its_destination(befo
_same("<`a`>) `b` `c`", False, 0, before)


@pytest.mark.parametrize("line, out", [("[x](`a`<`a`>)", "[x]( <`a`>)"), ("[x](`a` <`a`>) `b`", "[x]( <`a`>) "),
@pytest.mark.parametrize("line, out", [("[x](`a`<`a`>)", "[x]( < >)"), ("[x](`a` <`a`>) `b`", "[x]( < >) "),
("[x](<`<` `a`>)", "[x](< `a`>)")])
def test_a_link_that_matches_only_once_a_code_span_is_blanked_still_holds_its_spans(line: str, out: str) -> None:
assert _blank_inline(line, False)[0] == out # a ``](`` that does not match yet stays live while a ``<`` may follow it
_same(line, False)


@pytest.mark.parametrize("line, out", [
("[x]( `a` <y `b`>)", "[x]( <y >)"), # `a` is the destination and ``<y`` no title: no link, so ``b`` is a span
("[x]( <y `b`>)", "[x]( <y `b`>)"),
("[x]( `a` <y b>)", "[x]( <y b>)"),
("[x](<a `b`>)", "[x](<a `b`>)"),
("[x](<a `b`> \"t `c`\")", "[x](<a `b`> \"t `c`\")"),
("[`c`](<a `b`>)", "[ ](<a `b`>)"),
])
def test_a_code_span_before_an_angle_destination_is_not_whitespace(line: str, out: str) -> None:
assert _blank_inline(line, False)[0] == out
_same(line, False)


@pytest.mark.parametrize("text, lines", [
("[x]( `a`\n<y `b`>)", ["[x]( ", "<y >)"]), # a span on the line above is not whitespace either
("[x]( `a` <y ` z>)\nfoo` bar", ["[x]( <y ", " bar"]), # no link: the lone backtick opens a span that closes on line 2
("[x](\n<y `b`>)", ["[x](", "<y `b`>)"]),
("[x](<a\n`b`>) `c`", ["[x](<a", " >) "]),
Comment thread
vchamarthi marked this conversation as resolved.
Resolved
("~~~\nx\n~~~\n[x](\n<y `b`>)", [" ", " ", " ", "[x](", "<y `b`>)"]), # a fence above: the paragraph above starts after it
])
def test_a_code_span_on_the_line_above_an_angle_destination_is_not_whitespace(text: str, lines: list[str]) -> None:
assert prose_lines(text) == lines


@pytest.mark.parametrize("text, targets", [
("[x]( `a` <y `b`>)", []), # the first example of #1343: a span is text before ``<y``, so no destination
("[x]( `a`\n<y `b`>)", []),
("[x]( `a` <y b>)", []),
("[x](a`b`c)", [(1, "a`b`c", True)]), # a span inside a bare destination is part of it, read from the raw text
("[x]( <y `b`>)", [(1, "y `b`", True)]),
("[x](<a `b`>) `c`", [(1, "a `b`", True)]),
("[x](foo`(bar`)", []), # the parenthesis of the span is a parenthesis of the destination, which is never closed
("[x](`(`a)", []),
("[x](a`(b`)c)", [(1, "a`(b`)c", True)]), # balanced in the raw text: the destination runs past the span
("~~~\nx\n~~~\n[x](\n<y `b`>)", [(4, "y `b`", True)]), # a link after a block blanked whole is still checked
("<!--\nc\n-->\n[x](\n<y `b`>)", [(4, "y `b`", True)]),
])
def test_index_targets_reject_a_link_whose_destination_follows_a_code_span(text: str, targets: list[tuple[int, str, bool]]) -> None:
index = MemoryEntry("MEMORY.md", text, text, None)
assert MemoryStore(Path("/x"), index, []).index_targets() == targets


@pytest.mark.parametrize("text, targets", [
("[x]( `a` <y b>)\n\n[x]: missing.md", [(3, "missing.md", True)]), # no inline link, so [x] uses the definition
("[x](a`b`c)\n\n[x]: missing.md", [(1, "a`b`c", True), (3, "missing.md", False)]), # an inline link: no use
("[x](foo`(bar`)\n\n[x]: missing.md", [(3, "missing.md", True)]), # never closed in the raw text: a use
("[x](a`(`b)[y](z))", [(1, "a`(`b)[y](z)", True)]), # [y](z) is inside the destination, no link of its own
])
def test_a_label_and_a_link_are_read_as_index_targets_reads_a_destination(text: str, targets: list[tuple[int, str, bool]]) -> None:
index = MemoryEntry("MEMORY.md", text, text, None)
assert MemoryStore(Path("/x"), index, []).index_targets() == targets


def test_the_filled_lines_keep_every_line_of_the_text_and_its_columns() -> None:
lines = ["[x]( `a` <y `b`>)", "```", "code", "```"]
blanked, filled = store._blank_blocks(lines)
assert len(filled) == len(lines)
assert filled == ["[x]( \x00\x00\x00 <y \x00\x00\x00>)", " ", " ", " "]
assert [len(f) for f in filled] == [len(b) for b in blanked]


def test_scanning_past_many_comment_openers_with_no_close_grows_linearly() -> None:
ratio, result = growth(lambda k: partial(_blank_inline, _unclosed(k), False), 2000)
assert ratio < GROWTH_LIMIT
Expand Down
Loading