How to Verify a Turing Machine with Dafny
Edgar F. A. Lederer
TL;DR
This work demonstrates rigorous, machine-checked verification of two classic Turing machines in Dafny, establishing total correctness for each decider and illustrating the feasibility of formal proofs for teaching-oriented TM models. The author develops detailed invariants and termination metrics, including a left-minus-right invariant and a never-more invariant for the parentheses machine, and a halving/power-of-two invariant for Sipser’s M2, to drive complete partial and total correctness proofs. Beyond the specific machines, the paper showcases a practical methodology for mechanized TM verification, including ghost state, auxiliary lemmas, and structured stepwise proofs that reveal the interplay between tape content, head position, and input word properties. The work argues that mechanized proof not only certifies correctness but deepens understanding, and positions Dafny as a suitable tool for formalizing basic theoretical constructs used in computer science education. The contributions thus bridge pedagogy and formal verification, yielding compact, executable specifications and verifiable proofs that illuminate TM behavior with precise invariants and termination arguments.
Abstract
This paper describes the formal verification of two Turing machines using the program verifier Dafny. Both machines are deciders, so we prove total correctness. They are typical first examples of Turing machines used in any course of Theoretical Computer Science; in fact, the second machine is literally taken from a relevant textbook. Usually, the correctness of such machines is made plausible by some informal explanations of their basic ideas, augmented with a few sample executions, but neither by rigorous mathematical nor mechanized formal proof. No wonder: The invariants (and variants) required for such proofs are big artifacts, peppered with overpowering technical details. Finding and checking these artifacts without mechanical support is practically impossible, and such support is only available since recent times. But nowadays, just because of these technicalities, with such subjects under proof a program verifier can really show off and demonstrate its capabilities.
