opensheaf-literate

Tangling: from the documents to the program

The documents of a literate program are its source. The files of the program are tangled out of them: the pieces of code, written in the order in which they are best explained, are put back in the order the compiler or the interpreter wants. This chapter is the tangler, src/literate/tangle.py; like every other file of this package, it is itself tangled out of a document, this one.

The idea, and the syntax, come from Kragen Sitaker's handaxeweb, itself inspired by Phil Bewig's "The Essence of Literate Programming" (1996): the essence of literate programming is rearranging chunks of code, and a few dozen lines suffice for that. The documents are plain Markdown, readable as they stand on GitHub, and woven into a website by the weaver.

The syntax

handaxeweb also has versions of chunks (in NAME v2:), to keep several versions of a program in one document. We leave them out: git keeps our versions.

Here is a complete small example, with the program indented and the reference on a line of its own:

    # in hello.py:
    import sys

    <<say hello>>

Saying hello needs only a print.

    # in say hello:
    print("hello", " ".join(sys.argv[1:]))

The module

The tangler reads the documents, collects the fragments of every chunk, and writes every file chunk, expanding the references. It can also check that the files are up to date, list the chunks, and tell from which line of which document a line of a program comes, which is what one needs when an interpreter reports an error at a line of a tangled file. The command line that does these things is in its own chapter; here are the functions it calls. They need nothing but the standard library.

"""Tangling: the files of a program out of its literate documents."""
import re
import sys
from dataclasses import dataclass
from pathlib import Path

⟨the syntax as patterns⟩

⟨reading the documents⟩

⟨expanding the chunks⟩

⟨the files⟩

A mistake in the documents is reported, wherever possible, as DOCUMENT:LINE: what is wrong, the form editors know how to jump to. The functions raise it as an Error; the command line prints it and stops.

class Error(Exception):
    """A mistake in the documents, or in the use of the tools."""

The syntax as patterns

A header is a line of the form in NAME:, with any punctuation (a comment sign) before it and after the colon; a reference is a whole line <<NAME>>; fences are lines starting, after at most three spaces, with three backquotes or tildes; a file name is a name without spaces, with a slash or a dot.

HEADER = re.compile(r"^[^\w\s]*\s*in (.+?):\s*[^\w\s]*$")
REFERENCE = re.compile(r"^(\s*)<<(.+?)>>\s*$")
FENCE = re.compile(r"^ {0,3}(```|~~~)")
FILE = re.compile(r"^[\w.-]*[/.][\w./-]*$")

Every tangled file in which a comment is possible starts with a notice saying where it comes from, after the #! line if there is one. The notice is written in the comment syntax of the file, chosen by its suffix; a file without a suffix (a script, .gitignore) takes #. Files where a comment would be seen by others (HTML pages and templates, stylesheets served to readers) or is impossible (JSON) get no notice; a project can change the patterns, or add some, in its configuration.

COMMENTS = {".py": "# {}", "": "# {}", ".sh": "# {}", ".toml": "# {}",
            ".yml": "# {}", ".yaml": "# {}",
            ".js": "// {}", ".mjs": "// {}", ".cjs": "// {}"}
NOTICE = "Generated from {doc} by opensheaf-literate: edit the document, not this file."

The notice names the tool but not its version. With the version, every release of the tool would change every tangled file of every project that uses it, and the history of those files would be full of changes that change nothing; what version a project uses is recorded once, where the project pins it.

Reading the documents

A code block, for us as for Markdown, is a run of lines indented by four spaces, after a blank line (or at the start of the document) and outside a fenced block; blank lines inside the run belong to it, blank lines at its end do not. We record for each block the document, the lines it occupies (the weaver replaces them by its rendering), the chunk it belongs to, whether it began with a header, and its lines without the four spaces.

@dataclass
class Block:
    doc: Path        # the document
    start: int       # its first line in the document, counting from 0
    end: int         # the line after its last
    name: str        # the chunk it belongs to
    header: bool     # whether its first line is a header
    lines: list      # its program lines, without the four spaces

    @property
    def first(self):
        """The line of the document, counting from 1, of its first program line."""
        return self.start + 1 + self.header


def is_blank(line):
    return not line.strip()


def is_indented(line):
    return line.startswith("    ")

The blocks of a document are found in one pass. Inside a fence nothing is code; otherwise an indented line after a blank line starts a block, which extends over the indented and blank lines that follow.

def blocks(doc, text=None):
    """The code blocks of a document, in order."""
    if text is None:
        text = doc.read_text(encoding="utf-8")
    lines = text.split("\n")
    found, name, fenced, i = [], None, False, 0
    while i < len(lines):
        line = lines[i]
        if FENCE.match(line):
            fenced = not fenced
        elif (not fenced and is_indented(line) and not is_blank(line)
              and (i == 0 or is_blank(lines[i - 1]))):
            ⟨read the block that starts at line i⟩
            continue
        i += 1
    return found

The block ends before its trailing blank lines. If its first line is a header, it names the chunk; otherwise the block continues the chunk of the block before it, and a document cannot start with such a block.

start = i
while i < len(lines) and (is_indented(lines[i]) or is_blank(lines[i])):
    i += 1
end = i
while is_blank(lines[end - 1]):
    end -= 1
code = ["" if is_blank(line) else line[4:] for line in lines[start:end]]
header = HEADER.match(code[0])
if header:
    name, code = header.group(1), code[1:]
elif name is None:
    raise Error(f"{doc}:{start + 1}: a code block before the first chunk name")
found.append(Block(doc, start, end, name, bool(header), code))
⟨warn about a header inside the block⟩
i = end

Two code blocks separated only by a blank line are, for Markdown, one block; a header in the second is then program text. That is almost always a mistake: a sentence of prose between the blocks separates them. We warn, without stopping, since the program may mean it.

for n in range(1, len(code)):
    if not code[n - 1] and HEADER.match(code[n]) and not code[n].startswith("#!"):
        print(f"{doc}:{start + n + 1 + bool(header)}: a header inside a code block "
              "(put some prose before it)", file=sys.stderr)

The chunks are the fragments of all documents, grouped by name, in the order of the documents: index.md first, then the others in the order of their names (which, by convention, start with numbers).

def documents(folder="literate"):
    """The literate documents of a folder, in reading order."""
    return sorted(Path(folder).glob("*.md"), key=lambda d: (d.name != "index.md", d.name))


def read_chunks(docs):
    """The fragments of every chunk, by name."""
    chunks = {}
    for doc in docs:
        for block in blocks(doc):
            chunks.setdefault(block.name, []).append(block)
    return chunks

Expanding the chunks

Expanding a chunk appends its lines to a list, each with the document and line it comes from (blank lines between fragments come from nowhere). A reference is expanded in place, with the indentation of the reference added to every line. A reference to a chunk that is not defined is an error, and so is a chunk that includes itself, directly or not; both are reported at the line of the reference, with, for a cycle, the chain of chunks that closes it.

def expand(chunks, name, indent, out, python, stack=()):
    """Append the lines of chunk `name` to `out` as (text, document, line)."""
    gap = 2 if python and indent == "" else 1
    for k, block in enumerate(chunks[name]):
        if k:
            out.extend([("", None, None)] * gap)
        for n, line in enumerate(block.lines):
            ref = REFERENCE.match(line)
            if not ref:
                out.append((indent + line if line else "", block.doc, block.first + n))
                continue
            target, here = ref.group(2), f"{block.doc}:{block.first + n}"
            if target not in chunks:
                raise Error(f"{here}: <<{target}>> is never defined")
            if target in stack + (name,):
                raise Error(f"{here}: <<{target}>> includes itself: "
                            + " > ".join(stack + (name, target)))
            expand(chunks, target, indent + ref.group(1), out, python, stack + (name,))

The files

A file is the expansion of its chunk, with the notice, ending with a newline. With the text we return the origin of every line, which is what --where looks up. The comment patterns are those above unless the project's configuration gives others.

def file_names(chunks):
    return [name for name in chunks if FILE.match(name)]


def tangle(chunks, name, comments=None):
    """The text of file `name`, and where each of its lines comes from."""
    out = []
    expand(chunks, name, "", out, name.endswith(".py"))
    comment = (COMMENTS if comments is None else comments).get(Path(name).suffix)
    if comment:
        notice = comment.format(NOTICE.format(doc=chunks[name][0].doc.as_posix()))
        at = 1 if out and out[0][0].startswith("#!") else 0
        out.insert(at, (notice, None, None))
    return "\n".join(text for text, _, _ in out) + "\n", out

The line of a document a line of a file comes from is then a lookup; the notice, and the blank lines between fragments, come from no document.

def where(chunks, name, line, comments=None):
    """The place `DOCUMENT:LINE` line `line` of file `name` comes from, or None."""
    if name not in chunks or not FILE.match(name):
        raise Error(f"{name} is not made by the documents")
    _, lines = tangle(chunks, name, comments)
    if not 1 <= line <= len(lines):
        raise Error(f"{name} has {len(lines)} lines")
    _, doc, n = lines[line - 1]
    return f"{doc.as_posix()}:{n}" if doc else None

A file is written only when its text changes, so that the dates of the others stay, and with Unix line ends whatever the system. A file that starts with #! is a script and is made executable.

def write(path, text):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_bytes(text.encode("utf-8"))
    if text.startswith("#!"):
        path.chmod(path.stat().st_mode | 0o111)

Tangling the whole program is then: every file is tangled and compared with what is on disk, under the folder out; the files that differ are written, or, when we only check, just named.

def update(chunks, out=Path("."), comments=None, check=False):
    """Write the files that differ from their documents; return their names."""
    stale = []
    for name in file_names(chunks):
        text, _ = tangle(chunks, name, comments)
        path = Path(out) / name
        if path.exists() and path.read_bytes() == text.encode("utf-8"):
            continue
        stale.append(name)
        if not check:
            write(path, text)
    return stale

A chunk that is neither a file nor used anywhere is probably a mistake (a misspelt name); the command line says so, without stopping.

def unused(chunks):
    used = {ref.group(2) for fragments in chunks.values() for block in fragments
            for line in block.lines for ref in [REFERENCE.match(line)] if ref}
    return [name for name in chunks if name not in used and not FILE.match(name)]