# Why a program is checked before it runs

An alchemy program is compiled into a plan before it reads a byte, which is what lets dmog report mistakes early and state what a run keeps in memory.

dmog never interprets a program line by line over a document. It compiles the whole program into a plan first, and only then reads the input. `check` and `explain` are that first step on its own.

## Mistakes before the input

A program run over a large document should not fail at the last record because of a misspelt name. Compiling first means every name is resolved and every call is checked against what it is given before any of the document is read. `dmog check` reports such a mistake with its row and column, and exits without reading an input at all.

The checks go further than names. A program's values have types and its streams have protocols: a stream of a document's events is not a stream of table rows. A program that hands one to a function that wants the other fails the check with `protocol_mismatch`, whatever document it would have read.

## A plan that can be read

Because the plan exists before the run, it can be described. `dmog explain` prints what the plan does: how many times it reads the input, which parts of the document it holds and the limit that caps each, and what its memory does not grow with.

That last line is a guarantee, and it is a property of the program, not of a document. A program that selects one record at a time keeps memory flat however many records there are. A program that keeps state from record to record has that state capped by a limit, and its report names the limit. Knowing this before running a program over a document of unknown size is what makes the run safe to start.

## Where the language is defined

The language, its checks, and its plan reports belong to alchemy, which dmog runs. For the forms, the standard library, and every field of a report, see [the alchemy language reference](https://github.com/tabnas/alchemy/blob/main/docs/language.md), on GitHub. For the commands that run these steps, see [Check and format a program](https://dmog.tabnas.dev/how-to/check-and-format.html) and [Find out what a program keeps in memory](https://dmog.tabnas.dev/how-to/explain-a-program.html).
