Skip to content

Documents as modules

documents

Documents compiled as modules: the units of the documentation gate.

Every Markdown document of the documentation is checked by compiling the modules it contains, as document_units reads them from its fenced blocks (scan_blocks):

  • the document's cumulative blocks (unmarked ones in a literate .qvr.md module, and those marked cumulative or qiec-cumulative) form one module, its tangle;
  • each block marked standalone or qiec, and each unmarked block of an ordinary document, is a module of its own;
  • a block that includes a corpus file compiles that file, its imports found as that file's own package finds them;
  • the blocks marked file PATH are the files of one package, written to their paths below a fresh root and each checked as a module of that package, the way qvr check checks a file;
  • a block marked refused "TEXT" is a module that must be refused, with a diagnostic whose message contains TEXT;
  • compile: false fragments and example fences are not modules (an example is a test of the document's module, run by qvr test).

A unit's source keeps every block line on its document line and blanks every other line, so a diagnostic names the document's own line. A unit compiles through the module system, with the document's directory as the root its imports are found below; a unit holding a qiec block also has its flat program lowered through the exact QVR to QIEC route.

UnitRoute

UnitRoute = Literal['module', 'qiec', 'package', 'refused']

How a unit is compiled: as a module through the categorical compiler, lowered through the exact QVR to QIEC route, as the files of a package, or as a module the compiler must refuse.

PackageFile didactic-model

PackageFile(*, path: str, source: str)

Bases: Model

One file of a document's package.

PARAMETER DESCRIPTION
path

Its path below the package root, such as worlds/boolean.qvr.

TYPE: str

source

Its source, with its block's lines on their document lines.

TYPE: str

DocumentUnit didactic-model

DocumentUnit(*, document: str, line: int, blocks: tuple[int, ...], routes: tuple[UnitRoute, ...], source: str, include: str = '', files: tuple[PackageFile, ...] = (), refusal: str = '')

Bases: Model

One module a document contains.

PARAMETER DESCRIPTION
document

The document's path.

TYPE: str

line

The fence line of the unit's first block.

TYPE: int

blocks

The fence lines of every block the unit compiles.

TYPE: tuple[int, ...]

routes

How the unit is compiled; each route is checked.

TYPE: tuple[UnitRoute, ...]

source

The unit's QVR source.

TYPE: str

include

The corpus file an include block compiles, or empty.

TYPE: str DEFAULT: ''

files

The files of a package unit, or empty.

TYPE: tuple[PackageFile, ...] DEFAULT: ()

refusal

The text the diagnostic of a refused unit contains, or empty.

TYPE: str DEFAULT: ''

label property

label: str

The unit's name in diagnostics.

RETURNS DESCRIPTION
str

<document>:<line>.

DocumentError

Bases: ValueError

A unit of a document that does not compile, located at its document.

document_units

document_units(path: str | Path, text: str | None = None) -> tuple[DocumentUnit, ...]

The modules a document contains.

PARAMETER DESCRIPTION
path

The document; a name ending in .qvr.md makes it a literate module.

TYPE: str | Path

text

Its text; read from path when None.

TYPE: str | None DEFAULT: None

RETURNS DESCRIPTION
tuple[DocumentUnit, ...]

Its cumulative module first (when it has cumulative blocks), then its package (when it has file blocks), then its other units in document order.

RAISES DESCRIPTION
OSError

If the document or an included file cannot be read.

ValueError

If two file blocks name one path.

Source code in src/quivers/literate/documents.py
def document_units(
    path: str | Path, text: str | None = None
) -> tuple[DocumentUnit, ...]:
    """The modules a document contains.

    Parameters
    ----------
    path : str | Path
        The document; a name ending in ``.qvr.md`` makes it a literate
        module.
    text : str | None
        Its text; read from ``path`` when None.

    Returns
    -------
    tuple[DocumentUnit, ...]
        Its cumulative module first (when it has cumulative blocks), then
        its package (when it has file blocks), then its other units in
        document order.

    Raises
    ------
    OSError
        If the document or an included file cannot be read.
    ValueError
        If two file blocks name one path.
    """
    document = Path(path)
    if text is None:
        text = document.read_text(encoding="utf-8")
    label = str(path)
    blocks = scan_blocks(text, literate=is_literate_path(document))
    chain = tuple(block for block in blocks if block.mode in CUMULATIVE_MODES)
    units: list[DocumentUnit] = []
    if chain:
        sources: list[FencedBlock] = []
        for block in chain:
            sources.append(
                block.with_(body=_included(document, block.include))
                if block.include
                else block
            )
        included = tuple(block for block in sources if block.include)
        if included:
            # An include's file is not on the document's lines; the chain
            # then compiles as the concatenation its blocks spell.
            source = "\n".join(block.body for block in sources)
        else:
            source = _line_preserving(text, tuple(sources))
        units.append(
            DocumentUnit(
                document=label,
                line=chain[0].line,
                blocks=tuple(block.line for block in chain),
                routes=tuple(sorted({_route(block.mode) for block in chain})),
                source=source,
            )
        )
    package = tuple(block for block in blocks if block.mode == "file")
    if package:
        paths = [block.path for block in package]
        repeated = sorted({path for path in paths if paths.count(path) > 1})
        if repeated:
            raise ValueError(
                f"{label}: file blocks name one path twice: {', '.join(repeated)}"
            )
        units.append(
            DocumentUnit(
                document=label,
                line=package[0].line,
                blocks=tuple(block.line for block in package),
                routes=("package",),
                source="",
                files=tuple(
                    PackageFile(
                        path=block.path, source=_line_preserving(text, (block,))
                    )
                    for block in package
                ),
            )
        )
    for block in blocks:
        if block.mode in CUMULATIVE_MODES or block.mode in ("false", "example", "file"):
            continue
        units.append(
            DocumentUnit(
                document=label,
                line=block.line,
                blocks=(block.line,),
                routes=(_route(block.mode),),
                source=_included(document, block.include)
                if block.include
                else _line_preserving(text, (block,)),
                include=block.include,
                refusal=block.refusal,
            )
        )
    return tuple(units)

compile_unit

compile_unit(unit: DocumentUnit) -> None

Compile one unit of a document along each of its routes.

PARAMETER DESCRIPTION
unit

The unit.

TYPE: DocumentUnit

RAISES DESCRIPTION
DocumentError

If the unit does not parse, resolve, or compile on a route; the message names the document and the unit's first block, and the underlying error (which names the document's line) is its cause.

Source code in src/quivers/literate/documents.py
def compile_unit(unit: DocumentUnit) -> None:
    """Compile one unit of a document along each of its routes.

    Parameters
    ----------
    unit : DocumentUnit
        The unit.

    Raises
    ------
    DocumentError
        If the unit does not parse, resolve, or compile on a route; the
        message names the document and the unit's first block, and the
        underlying error (which names the document's line) is its cause.
    """
    root = _import_root(unit)
    for route in unit.routes:
        try:
            if route == "package":
                _check_package(unit)
            elif route == "refused":
                _check_refused(unit, root)
            elif route == "module":
                loads(unit.source, roots=(root,))
            else:
                lower_flat_to_qiec(
                    interpret_source(unit.source, label=unit.document, roots=(root,)),
                    module_name=f"docs.{module_stem(unit.document)}.{unit.line}",
                    file_path=unit.document,
                )
        except Exception as error:  # noqa: BLE001 - every failure is the unit's
            raise DocumentError(
                f"{unit.label} ({route}): {type(error).__name__}: {error}"
            ) from error