Skip to content

Go ​

Tolean translates Go code that has effects. A function that calls methods on an interface, such as a database store, becomes a function in a state monad, so a proof can plug in a model of what the interface does. The README describes the parts that all languages share.

This graph shows the verification chain for Go. It marks which links are proved, tested against a reference, or trusted.

The translator ​

Parsing ​

tolean/Go/Syntax/ puts on every node the span that go/ast gives it, and it inserts semicolons at line breaks as the Go specification requires. It reads:

  • Declarations: package, imports, const, var and type (including aliases), each alone or grouped; functions and methods.
  • Types: names and qualified names, pointers, arrays, slices, maps, structs (with embedded fields and tags), interfaces (with embedded interfaces), function types and ... parameters.
  • Statements: blocks, :=, = and the compound assignments, ++ and --, declarations, return, break and continue, if with an init statement and else, the three forms of for, range with :=, = or no variables, switch with an init statement and a tag, type switches and defer.
  • Expressions: names; integer (decimal, hex, octal, binary, with separators), floating-point, rune, string and raw string literals; composite literals, including those whose element type is left out; selectors, indexing, two-index slicing, calls with ..., unary and binary operators, type assertions and function literals. Like go/parser, it does not read T{ as a composite literal in the header of if, for or switch when T is a plain type name, unless the literal is in parentheses.

The parser refuses generics, channels, go, goto, select, labels, fallthrough, three-index slices, [...]T arrays, imaginary literals and non-ASCII names. It reads type switches, type assertions, function literals and defer even though the translator refuses them, so that a file can be read when the translator needs only some of its declarations.

tests/go/check checks the parser against go/parser. tests/go/goast prints the tree from go/parser in the same S-expression form, with columns counted in code points, and it refuses the node kinds that the Lean parser does not read:

  • For corpus/parse/accept/*.go, both parsers must accept the file, and the two trees must be equal, spans included.
  • For corpus/parse/reject/*.go, the Lean parser must refuse the file. The first line gives the line, the column and part of the message to expect.
  • Any Go file named on the command line is checked like an accepted file.

Translation ​

tolean/Go/Translate.lean translates one Go package at a time. It starts from the functions named with --root and keeps only the declarations they reach, so a file can hold code that Tolean does not support:

sh
tolean translate-go --root Post --erase-type Log --erase-package time \
  Ledger.lean Ledger ledger.go

The generated code imports tolean/Go/Spec/Basic.lean, the trusted model of Go values. Review it with care.

  • A function that calls a method on an interface parameter, such as a store, becomes a function in StateM State. The interface becomes a structure that holds the methods the code calls, so a proof can plug in a model of the store.
  • A range loop over a slice becomes its own recursive function. continue is the recursive call, break returns the locals that the loop changes, and return leaves the function with its result.
  • int and int64 arithmetic wraps as Go's does, through Go.wrap64. A proof shows that the values stay in range and then reasons over Int.
  • An error is Option GoError. Tolean models how an error was made (errors.New, or fmt.Errorf with a leading %w) and drops the rest of the message.
  • Code that only feeds observability is erased. A statement is erased when it reads a value of a type named by --erase-type or calls a package named by --erase-package. Tolean refuses to erase a statement unless it only assigns through the erased value, so that erasing it cannot change any other value.

tests/go/check also translates each package in corpus/translate/*/ with the options in its args file. The result must equal the committed .lean file in the same directory, and Lean must compile it. The corpus package ledger posts a double-entry journal entry, and fees computes the fee on a transfer with pure functions.

What is proved ​

A pure function takes and returns int, int64, bool, string and error values, one or several, and calls only other pure functions. Its body may declare locals with := or var, assign them with =, +=, -=, *=, /=, %=, ++ and --, test with if, else and switch, and return. The translator writes each pure function through tolean/Go/Translate/Pure.lean, which proves that translation, and it writes everything else as before.

A parameter without a name, as in func Ignore(int) int, still takes an argument. The output names it _, as the interpreter binds it. A function, parameter or local whose name Lean reads as a keyword, such as partial, is written quoted, as «partial». A field with such a name keeps the function on the string translation. The corpus package fallback shows both.

A pure function may read a constant that the package declares at the top level, such as const Limit = 100 or const Fee int64 = 3, alone or in a group. The constant's value must be an integer or string literal, an integer literal after -, true or false, and a typed constant must have one of the four types above. The output writes the value where the function reads the name. A constant may also use iota, constants declared before it and the operators -, !, +, -, *, /, %, <<, >>, comparisons, && and ||, and a spec without values repeats the one before it, as in const ( Low Level = iota; Mid; High ). The value is exact, as Go computes constants, and the output writes it. An unexported var may start at such a constant expression when it has a type or is not an integer. A constant from a later one, a float or rune, other operators and calls keep the function on the string translation. The decision record gives the reasons, and the corpus package consts shows the output.

A pure function may also use a type that the package declares over int, int64, bool or string, such as type Celsius int or the alias type Count = int64, for its parameters, results, locals and constants. It may convert a value to such a type, as in Celsius(x) or Name(s), and back with int(c) or int64(c). A type may also be declared over another such type of the package, as in type Reading Celsius, in any order. A conversion keeps the value, so the output uses the underlying type, Int or Bool, and writes the operand alone. Go's type checker keeps Celsius apart from int, so the translator reads only programs that go build accepts. A conversion to a type over string is proved only for an operand of type string; an integer operand keeps the function on the string translation, because Go turns it into a code point. A type over a composite type, or a cycle of types, does too. The decision record and its follow-up give the reasons, and the corpus package named shows the output.

A pure function may also read a package-level variable that nothing in the package changes, such as var fallback string or var limit = 10. The variable must be unexported, because another package can assign an exported one. Its initial value must be a literal of the kind a constant may have, or it must have a type and no value, and then it starts at the zero value. No function, method, init function or function literal of the package may assign it, increment it, assign it in a range clause, or take its address. The check is syntactic, so a local of the same name that is assigned counts too. Such a variable keeps its initial value, so the output writes that value as it does for a constant. A variable that some code changes stays on the string translation, as the decision record explains.

A pure function may also read or assign an unexported package-level variable that the package changes. Such a function takes every variable of the package's state as its first parameters, and a function that assigns one also returns them after its own results. For example, func Bump(d int) int that assigns count becomes def Bump (count : Int) (d : Int) : (Int × Int). A call of a function that assigns a variable may stand alone: as a statement f(…), after = or :=, or after return. The caller then assigns the variables too, and takes the new values from the call's tuple, as in let (a, n'11_2) := (G n x) then let n := n'11_2. Such a call cannot stand inside an expression, in its arguments, after var or in the head of an if, for or switch, because Go leaves open whether x in x + f() is read before or after the call. The translator refuses a function with such a call with a message. When a reached function uses a variable that changes, every function that assigns one must be on the proved path: a root, or reached from one, and accepted. Otherwise the translator refuses the package with a message that names the function and the reason, such as "add --root G" for one the roots do not reach, since the output would read the variable as its initial value. A function may not declare a name of a variable it uses. The decision record gives the reasons.

A pure function may also use a struct type of the package whose fields have those four types, such as type Point struct { X int; Y int }. It may build one with Point{}, Point{x, y} or Point{X: x, Y: y}, which names every field once in order, Point{X: x}, which names some fields in order and gives the others their zero values, or declare one with var p Point, which holds the zero value of each field, read a field with p.X, and set a field of a local with p.X = e, and compare two with == or !=, which compares every field. The output declares a structure, which derives DecidableEq when every field has one of the four types, writes { p with X := e } for the assignment and decide (p = q) for p == q. Embedded fields, a field of another type, and a keyed literal that changes the order of the fields keep the function on the string translation. The decision record gives the reasons, and the corpus package structs shows the output.

A pure function may also take, return and build slices of those four types, such as []int. It may build one with []int{a, b} or var xs []int, read len(xs), and read xs[i], which panics as Go does when i is out of range. The output writes List Int, Go.sliceLen xs and Go.sliceAt xs i 0 after a test of the index. A local made by a literal, var xs []int, make([]int, 0) or make([]int, 0, 8) can grow with xs = append(xs, a, b), written xs ++ [a, b], when the function owns it: no other slice, parameter or call ever reads it, and it leaves only by return xs. The append decision record gives the check. Such a local can also change an element with xs[i] = e, written Go.sliceSet xs i e after a test of the index, which Go makes after it evaluates i and e; the index assignment decision record gives the rules. Any other append or xs[i] = e, make with a length or a computed capacity, slice expressions with a high bound such as xs[a:b], xs == nil, xss[i][j] = e, keyed elements whose keys are not growing literals, and range over a slice keep the function on the string translation. Slices of structs, such as []P{P{1, "a"}}, slices of slices such as [][]int{[]int{1}} (decision), and keyed elements such as []int{2: x, 5: y}, whose gaps the output fills with zeros, are on the proved path, and so are xs[a:] and xs[:], written Go.sliceFrom xs a after a test of the bound (decision); the decision record explains why xs == nil waits for a slice model that records nil. Only the statements of an owned local change a slice, and no other slice shares its array, so a list is exact even when two other slices share one; the decision record gives the reasons, and the corpus package slices shows the output.

An if may have an init statement, as in if d := x - y; d > 0 { … }. A switch may have a tag or none, an init statement, several values in one case, and a default clause anywhere in its body. The translator writes a switch as the chain of if statements that Go's rules give it: the first case value that equals the tag picks its clause, and default runs when none does. A plain block { … } is accepted too. Proof/Switch.lean proves that the interpreter gives each of these statements the meaning of the statements that the translator writes for it.

An if or a switch with an init statement v := e that returns on some path may be followed by more code, as in if v := f(); v > 0 { return v }; return 0, when that code does not use the name v and v is not a package variable. The output keeps v bound in the code after the statement, where it goes unused; Proof/Unused.lean proves that such a binding changes nothing.

Some forms of these statements stay on the string translation. Otherwise, an if with an init statement, a switch or a block that returns on some path must be the last statement of its list. So must one whose later code reads an outer local with the init statement's name. A switch with a tag needs at least one case value, because only a case test evaluates the tag. A case with several values becomes a || of tests, so a value after the first may not divide or index a string, and neither may the tag of such a switch. A break inside a switch leaves the switch. A switch whose clauses break must change a local, and it must not also hold a continue of an enclosing loop. The decision record gives the reasons.

Integer / and % become Int.tdiv and Int.tmod, which round toward zero as Go does. / wraps through Go.wrap64, so MinInt64 / -1 is MinInt64, as in Go. Go panics when the divisor is zero, and Lean's division gives zero instead, so a statement that divides first tests each divisor that is not a nonzero literal. When one of them is zero, the function throws Go's message, runtime error: integer divide by zero. A function that can panic returns Except String T and pure of its value; a function whose divisors are all nonzero literals still returns T:

lean
def Quo (a : Int) (b : Int) : (Except String Int) :=
  if b = (0 : Int) then
    let _ := (Go.wrap64 (Int.tdiv a b))
    throw ("runtime error: integer divide by zero")
  else
    (pure (Go.wrap64 (Int.tdiv a b)))

A string is a sequence of bytes, as in Go. len(s) gives the number of its bytes, and s[i] gives the byte at index i, which the subset converts with int(s[i]) or int64(s[i]). The orders <, <=, > and >= compare the bytes of two strings. The output writes Go.byteLen, Go.byteAt and Go.strLt and its siblings. An index out of range panics with Go's message, such as runtime error: index out of range [5] with length 3, so a statement that indexes a string first tests each index, in Go's order of evaluation:

lean
def First (s : String) : (Except String Int) :=
  if (Go.indexFault s (0 : Int)) ≠ "" then
    throw (Go.after (Go.byteAt s (0 : Int)) (Go.indexFault s (0 : Int)))
  else
    (pure (Go.byteAt s (0 : Int)))

The translator refuses a slice of a string, range over a string, runes, and arithmetic on a byte. A slice can cut a character of UTF-8 in two, and the interpreter keeps a string as a Lean String, which holds only valid UTF-8. The decision record gives the reasons. The corpus package strbytes shows the output.

The translator refuses a division by the constant zero, which Go refuses too, and a division or an index in the right operand of && or ||, which Go might not evaluate. It also refuses a statement that mixes an index inside the argument of a call or len with a division or an index outside one, such as s[1][len(s[3])]: gc tests the check in the argument first, which the specification allows (decision). gc also tests the bound of each xs[a:] before the other checks, so a statement is refused unless its slices, with the checks of their bases and bounds, come first, such as s[3] + t[2:][0] (decision). The same rule applies inside the base and the bound of each slice, so len(xs[1/x + xs[2:][0]:]) is refused, and across all the values of return a, b and a, b := …. A slice whose base and bound both have checks, such as ss[:][3][1/x:], is refused too, because gc may test the bound first. The corpus package divide shows the output.

A pure function may call a function that can panic, when the call stands alone after :=, =, var x T = or return. Its arguments may divide, but they may not call another such function. The output binds the call with >>=, so the callee's panic ends the caller, and the caller can panic too:

lean
def Scaled (a : Int) (b : Int) : (Except String Int) :=
  (Quo a ((2 : Int))) >>= fun half =>
  (Quo half ((Go.wrap64 (Int.tdiv b ((2 : Int)))))) >>= fun result =>
  (pure result)

The proved path refuses such a call inside a larger expression, and in x += f(…) and the other compound assignments. The string translation accepts it inside an expression: a function there that calls a function that can panic runs in Except String, or in ExceptT String (StateM σ) when it has effects, and binds each such call with ←. It refuses one in the right operand of && or ||, because ← would run it even when Go does not. The corpus package panics shows both.

A pure function may have several results, such as func DivMod(a int, b int) (int, int) or (q, r int). A named result is a local that starts at its type's zero value. Its output returns a Lean tuple, (Int × Int). return a, b evaluates its values from left to right, and return f(…) returns the results of a call with the same results. The statements a, b := … and a, b = … take their values from one call of a function with as many results, or from as many expressions, and any name may be the blank identifier _. Every value is evaluated before any local changes, so a, b = b, a swaps. The output takes the tuple apart with let:

lean
def Rotate (a : Int) (b : Int) (c : Int) : Int :=
  let (a, b, c) := (b, c, a)
  (Go.wrap64 ((Go.wrap64 ((Go.wrap64 (a * (100 : Int))) + (Go.wrap64 (b * (10 : Int))))) + c))

A call with several results of a function that can panic may be the right side of a, b := … or a, b = …, or the value of return. The output binds the tuple with >>= and then takes it apart, so the callee's panic ends the caller.

The proved path refuses a bare return with named results, _, _ = f() when f can panic, a := that would redeclare a local in scope, two values of one statement that may each divide or index a string, and an assignment of several values in the body of a counted loop. The decision record gives the reasons, and the corpus package multi shows the output.

The proved path accepts for _, x := range s over a local slice s, with break and continue, when the body changes neither x nor s and holds no other loop. It folds over s with List.foldl or forIn. It also accepts for i := range s under the same rules for i, and folds over Go.upTo 0 (Go.sliceLen s). It accepts for i, x := range s as that index loop whose body starts with x := s[i], when i, x and s are three names, neither is _, and the body is not empty. The element may change in the body. The output reads Go.sliceAt s i after a bounds test, so the function returns Except. The decision record gives the details, and the corpus package ranges shows the output.

It also accepts for _, x := range e over any pure expression e of a slice type, such as a literal, s[a:], s[:] or a call. The output computes e once, before the loop. When e can panic, as on the bound of s[a:], the panic comes before the loop, as in Go. The body may not change x or any local that e reads. range append(…) and the index forms over anything but a local slice are refused. A certificate covers a range over a literal list, but not over a sliced expression such as s[a:] or s[:] or over a call. The decision record gives the details, and the corpus package rangeexprs shows the output.

The proved path accepts values of type error: nil, errors.New(s), and fmt.Errorf with a literal format that starts with %w and has no other verb, when the file imports the package by its exact standard library path, "errors" or "fmt". A package of another path whose name is errors or fmt, such as example.com/errors, may define New otherwise, so its calls stay refused, and so do these calls in every file of the package when any file binds the name errors or fmt to another path, since the declarations of a package do not record their file. An import without an alias binds the name in the imported package clause, which can be errors or fmt for any path, so an import without an alias of a path outside a short list of standard library paths refuses these calls too. The arguments of errors.New and fmt.Errorf count as call arguments for the order of checks: Go evaluates them first, so an expression that mixes a check inside them with one outside is refused, as for other calls. An error compares only with nil, as Go.isNil e. Comparing two errors that are not nil, package-level sentinel errors, errors.Is, .Error(), other uses of fmt and errors in struct fields or slices stay refused, because Go compares errors by identity, which the model leaves out. The decision record gives the details, and the corpus package errs shows the output.

The proved path accepts a method with a value receiver on a struct type, func (p T) M(…) R, as the function T.M that takes p first, and a call x.M(…) as T.M x …. Pointer receivers, methods on other types, a method name that several types declare and calls of methods that can panic stay refused. The decision record gives the reasons, and the corpus package methods shows the output. A certificate covers methods as it covers functions: the theorem for T.M runs the interpreter on the method with the receiver as the first argument.

The proved path also accepts a counted loop at any position in a body: for i := a; i < b; i++ { body }. A bound may be an integer literal, a local, len of a local, or a sum, difference or product of those. Each bound must have type int, must not read the counter, and must contain no division, so it cannot panic. The body must not change what the bounds read. It may set an element of a slice whose length alone the bound reads, as for i := 0; i < len(xs); i++ { xs[i] = 2 * xs[i] }, because that keeps the length (Proof.Bound.counted_bound_fixed); the package must not declare its own len. The counter must have a fresh, unreserved name. The body may update locals, declare iteration-local variables, and use the existing non-returning if forms. For example, func Bytes(s string) int may sum int(s[i]) with for i := 0; i < len(s); i++. Arithmetic in the body still wraps.

The interpreter evaluates both bounds once, before the first iteration, and runs the body over the finite list Go.upTo a b. The translation emits the same list. When both bounds are literals and the loop takes at most 256 iterations, it prints the list element by element, as before; otherwise it prints (Go.upTo a b). The shared IR.Body.fold threads the changed locals, and LoopFrame.loop_law uses Core.Loop.execLoop_refines to connect the source loop with that fold wherever the loop stands. A panic in the body ends the loop, as a return does. The record on counted-loop termination explains why the loop needs no fuel.

The body may hold break and continue, and so may an if, a block or a switch inside it. The interpreter and the IR both have a break and a continue outcome, and the shared loop core stops on a break. The output runs such a body with forIn, where each run of the body gives a ForInStep: continue and the end of the body give yield, and break gives done. A block that breaks or continues must end its list of statements. A labeled break or continue stays refused.

This proved form refuses early return, nested loops, other comparison or update operators, counter mutation, bounds of another integer type, and bounds that could panic.

A condition-only loop for i < b { …; i++ } is accepted when the body ends with i++, writes i nowhere else, holds no continue, and b does not read i. It is proved as the counted loop for i' := i; i' < b; i'++ { i = i'; …; i++ }, so i keeps its last value after the loop. Other condition loops stay refused, because the proved path has no termination measure for them. The decision record gives the details, and the corpus package while shows the output. The other restrictions keep the loop within the existing state-only body translation and the leading-loop proof. Ranges over slices use the same loop core; see below. The older string translator's range support is unchanged and is not covered by this theorem.

Pure.lean is a total function, so Lean can reason about it. It does not write text. It builds the Tolean IR, the Lean code it writes as Lean data. tolean/Go/IR.lean adds what only Go needs to the shared IR: Go.wrap64, ++ on strings, pure for the value of a function that can panic, and the byte operations on strings. The shared IR gives Int.tdiv, Int.tmod, throw, and the tuples of several results. tolean/Go/IR/Eval.lean gives the IR a meaning.

tolean/Go/Spec/Eval.lean is an interpreter for the pure subset. It runs the syntax tree that the parser returns and follows the Go specification. The interpreter has an outcome for a panic next to the one for a return. The theorem translate_sound in tolean/Go/Proof/Package.lean states that when a function of the IR returns a value for a call, or throws, the interpreter returns the same value for the same call of the source's function, or panics with the same message. It holds for every package, every input and every amount of fuel. The proof follows the one for TypeScript, in three files: Proof/Expr.lean for expressions, Proof/Stmt.lean for statements and Proof/Package.lean for calls.

The translator types each expression as Go does. An integer literal is an untyped constant that takes the type of the other operand. The translator refuses an operator on two constants, because Go computes such an operator exactly at compile time. In Go, 9223372036854775807 + 1 > 0 is true, but the wrapping arithmetic of the output would make it false.

Three links of the chain are still trusted for a pure function. The parser is tested against go/parser. The printer writes the IR as Lean text, and the corpus tests it. The interpreter states what Go means, and a test compares it with the Go runtime on random programs. A certificate proves the printer link for one package, as the next section describes.

Certificates ​

A certificate is a Lean file with two theorems for each function that it covers. tolean translate writes one next to the translation of a Go package whose settings in tolean.json have "certify": true, as it does for a TypeScript file. The output Sums.lean with the namespace Sums gets SumsCert.lean with the namespace SumsCert:

json
{
  "go": {
    "sources": ["src/*.go"],
    "moduleRoot": "src",
    "overrides": [{ "sources": ["src/*.go"], "output": "src/Sums.lean", "certify": true }]
  }
}

Without a project file, translate-go --certify does the same:

sh
tolean translate-go --certify --root Add Sums.lean Sums sums.go

The translator picks the functions. Each function that qualifies gets theorems, and the certificate lists every other function of the proved path with the reason. It refuses the package only when no function qualifies. The certificate is recorded in the translation's .chain.json.

The certificate holds the declarations that the parser read and the IR that Pure.lean gives for them. The kernel runs Pure.translateFuncs on the declarations and checks that it gives that IR. Then Add_link states that the printed Sums.Add computes what the evaluator of the IR gives, for every input, and Add_cert follows from translate_sound:

lean
theorem Add_cert (x0 : Int) (x1 : Int) :
    tolean.Go.Eval.runIn (tolean.Go.Eval.program decls) "Add" [.int x0, .int x1] =
      some (.ok (.int (_root_.Sums.Add x0 x1)))

So when Lean accepts the certificate, the printed function returns what the interpreter returns for the same call, or panics with the same message. The parser stays trusted. It is a partial def, so the kernel cannot run it, and the certificate cannot check that decls is what the source says.

A theorem covers a function whose parameters and result are int, int64, bool, string, a struct of the package, or a slice of one of these or of a slice of one, also when it can panic, and a function with several such results. The certificate defines an encoder for each struct, such as enc.Point, which gives the interpreter's value of a printed Point. A slice is encoded element by element, and several results are Val.pair of the first and the rest, as the interpreter returns them. The reasons for the other functions are a loop that the certificate cannot prove yet. A function that uses package-level variables takes them as parameters and returns their new values after its results, in the interpreter and in the printed Lean, so its theorem has the form of any other. The manifest marks the theorems as proved, and the translator as proved only when every function of the output has one. It keeps the parser tested, because the certificate does not check the parse.

A loop gets a lemma before the theorem of its function. The lemma states that the evaluator runs the loop as the printed List.foldl. It holds in every environment where the locals that the loop reads have values of their types, and it reads them back with decoders such as decInt. Each lemma follows from exec_fold in Certify/Loop.lean, and the link theorem rewrites the loop with it. A loop that a break can end is printed with forIn, and its lemma states that instead. A loop whose body can panic, for example on an index or a division, runs in Except String, and its lemma states that a panic in the body is the panic of the loop. The certificate covers a counted loop and a range over a slice when the body holds no other loop, and calls only functions that have a theorem. The locals and the elements must be int, bool, string, structs, or slices of these.

go run ./check translates every package of tests/go/corpus/translate with --certify, and Lean must accept each certificate. A package with a file named certified must have a theorem for every function of the proved path. Each project in tests/go/corpus/projects sets "certify": true, and its committed certificate and manifest must be current.

That test is tests/go/differential. It writes random functions of the proved subset, calls each one with random arguments, and requires four results to agree: the value that go run prints, or the message of its panic, the interpreter's value, the value of the IR that Pure.lean builds, and the value of the Lean code that tolean translate-go prints. It also requires that Pure.lean accepts every generated function, so a generator that leaves the subset fails loudly instead of testing less. The test checks a sample, so it is evidence for the interpreter and the printer, not a proof. It assumes that int is 64 bits wide, as the interpreter does, so it runs on a 64-bit platform. When the subset grows, the generator should grow with it. Run it from tests/go after lake build:

sh
go run ./differential

A failing seed is a bug in the generator, the translator or the printer; this record shows one of each. Rebuild tolean before a run, because a stale binary gives false failures.

TOLEAN_SEED repeats a run, TOLEAN_PROGRAMS sets the number of random programs, and TOLEAN_KEEP=1 keeps the generated files.

This page is docs/go/README.md at commit 5f1d031.