Skip to content

Prose references

prose

Prose references to declarations in a literate document.

The prose of a literate document names declarations with the role {qvr:ref}`Name`. prose_references finds them outside the document's fenced blocks, with the offsets of each target, so a checker can resolve them in the module's scope (quivers.literate.references) and a migration can rewrite them when a declaration is renamed.

ROLE module-attribute

ROLE = re.compile('\\{qvr:ref\\}`(?P<target>[^`\\n]+)`')

A prose reference: {qvr:ref}`Name`.

ProseReference didactic-model

ProseReference(*, target: str, line: int, column: int, start: int, end: int)

Bases: Model

One prose reference to a declaration.

PARAMETER DESCRIPTION
target

The name referred to, as written.

TYPE: str

line

The 1-based document line of the target.

TYPE: int

column

The 0-based column of the target.

TYPE: int

start

The character offset of the target in the document.

TYPE: int

end

The character offset one past the target.

TYPE: int

prose_references

prose_references(text: str) -> tuple[ProseReference, ...]

The prose references of a document, outside its fenced blocks.

PARAMETER DESCRIPTION
text

The document.

TYPE: str

RETURNS DESCRIPTION
tuple[ProseReference, ...]

Each {qvr:ref}`Name` occurrence, in document order.

Source code in src/quivers/dsl/literate/prose.py
def prose_references(text: str) -> tuple[ProseReference, ...]:
    """The prose references of a document, outside its fenced blocks.

    Parameters
    ----------
    text : str
        The document.

    Returns
    -------
    tuple[ProseReference, ...]
        Each ``{qvr:ref}`Name` `` occurrence, in document order.
    """
    fenced = [(match.start(), match.end()) for match in _ANY_FENCE.finditer(text)]
    found: list[ProseReference] = []
    for match in ROLE.finditer(text):
        if any(start <= match.start() < end for start, end in fenced):
            continue
        start = match.start("target")
        line_start = text.rfind("\n", 0, start) + 1
        found.append(
            ProseReference(
                target=match.group("target"),
                line=text.count("\n", 0, start) + 1,
                column=start - line_start,
                start=start,
                end=match.end("target"),
            )
        )
    return tuple(found)