ArticleslgStudy

computer science

Dafny

Dafny is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Dafny rather than just read about it. In short: Dafny is an imperative and functional compiled language that compiles to other programming languages, such as C#, Java, JavaScript, Go, and Python. It supports formal specification through preconditions, postconditions, loop invariants, loop variants, termination specifications and read/write framing specifications.

Dafny — main illustration
Dafny — illustration

Key takeaways

  • Dafny belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Dafny to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Dafny from memory before moving on to harder problems.

Reference excerpt

Dafny is an imperative and functional compiled language that compiles to other programming languages, such as C#, Java, JavaScript, Go, and Python. It supports formal specification through preconditions, postconditions, loop invariants, loop variants, termination specifications and read/write framing specifications. The language combines ideas from the functional programming and imperative programming paradigms; it includes support for object-oriented programming. Features include generic classes, dynamic allocation, inductive datatypes and a variation of separation logic known as implicit dynamic frames for reasoning about side effects. Dafny was created by Rustan Leino at Microsoft Research after his prior work on developing ESC/Modula-3, ESC/Java, and Spec#. Dafny is regularly featured in software verification competitions (e.g. VSTTE'08, VSCOMP'10, COST'11, and VerifyThis'12). Dafny was designed as a verification-aware programming language, requiring verification along with code development. It thus fits the Correct by Construction software development paradigm. Verification proofs are supported by a mathematical toolbox that includes mathematical integers and reals, bit-vectors, sequences, sets, multisets, infinite sequences and sets, induction, co-induction, and calculational proofs. Verification obligations are discharged automatically, given sufficient specification. Dafny uses some program analysis to infer many specification assertions, reducing the burden on the user of writing specifications. The general proof framework is that of Hoare logic. Dafny builds on the Boogie intermediate language which uses the Z3 automated theorem prover for discharging proof obligations.

Data types

Dafny provides methods for implementation which may have side-effects and functions for use in specification which are pure. Methods consist of sequences of statements following a familiar imperative style whilst, in contrast, the body of a function is simply an expression. Any side-effecting statements in a method (e.g. assigning an element of an array parameter) must be accounted for by noting which parameters can be mutated, using the modifies clause. Dafny also provides a range of immutable collection types including: sequences (e.g. seq<int>), sets (e.g. set<int>), maps (map<int,int>), tuples, inductive datatypes and mutable arrays (e.g. array<int>).

Imperative features

The following illustrates many of the features in Dafny, including the use of preconditions, postconditions, loop invariants and loop variants.

This example computes the maximum element of an array. The method's precondition and postcondition are given with the requires and ensures clauses (respectively). Likewise, the loop invariant and loop variant are given through the invariant and decreases clauses (respectively).

Loop invariants The treatment of loop invariants in Dafny differs from traditional Hoare logic. Variables mutated in a loop are treated such that (most) information known about them before the loop is discarded. Information required to prove properties of such variables must be expressed explicitly in the loop invariant. In contrast, variables not mutated in the loop retain all information known about them beforehand. The following example illustrates using loops:

This fails verification because Dafny cannot establish that (sum + arr[i]) >= 0 holds at the assignment. From the precondition, intuitively, forall i :: 0 <= i < arr.Length ==> arr[i] >= 0 holds in the loop since arr[i] := arr[i]; is a NOP. However, this assignment causes Dafny to treat arr as a mutable variable and drop information known about it from before the loop. To verify this program in Dafny we can either (a) remove the redundant assignment arr[i] := arr[i];; or (b) add the loop invariant invariant forall i :: 0 <= i < arr.Length ==> arr[i] >= 0 Dafny also employs limited static program analysis to infer simple loop invariants where possible. In the example above, it would seem that the loop invariant invariant i >= 0 is also required as variable i is mutated within the loop. Whilst the underlying logic requires such an invariant, Dafny infers this automatically, and hence, it can be omitted at the source level.

Proof features Dafny includes features which further support its use as a proof assistant. Although proofs of simple properties within a function or method (as shown above) are not unusual for tools of this nature, Dafny also allows the proof of properties between one function and another. As is common for a proof assistant, such proofs are often inductive in nature. Dafny may be unusual in employing method invocation as a mechanism for applying the inductive hypothesis. The following illustrates:

Here, NatSumLemma proves a useful property between sum() and isNatList() (i.e. that isNatList(l) ==> (sum(l) >= 0)). The use of a ghost method for encoding lemmas and theorems is standard in Dafny with recursion employed for induction (typically, structural induction). Case analysis is performed using match statements and non-inductive cases are often discharged automatically. The verifier must also have complete access to the contents of a function or predicate to unroll them as necessary. This has implications when used in conjunction with access modifiers. Specifically, hiding the contents of a function using the protected modifier can limit what properties can be established about it.

See also Design by contract

References

Further reading Meyer, Bertrand; Nordio, Martin, eds. (2012). Tools for Practical Software Verification: International Summer School, LASER 2011, Elba Island, Italy, Revised Tutorial Lectures. Springer. ISBN 978-3642357459. Sitnikovski, Boro (2022). Introducing Software Verification with Dafny Language: Proving Program Correctness. Apress. ISBN 978-1484279779.

External links Dafny: A Language and Program Verifier for Functional Correctness - Microsoft Research Dafny on GitHub, verification-aware programming language

Illustrations

Dafny illustration

Worked examples

Example 1 — a first encounter with Dafny

Start with the simplest possible case. Write down what Dafny claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Dafny before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Dafny ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Dafny

In research
Dafny appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Dafny in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Dafny is common in secondary-school and first-year university syllabi. It links to neighbouring topics Academic programming languages, Experimental programming languages, Microsoft Research, so understanding it makes those chapters shorter.
In everyday life
Look for Dafny outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Dafny” →

How to study Dafny in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Dafny means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Dafny out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Dafny in simple terms?

Dafny is an imperative and functional compiled language that compiles to other programming languages, such as C#, Java, JavaScript, Go, and Python. It supports formal specification through preconditions, postconditions, loop invariants, loop variants, termination specifications and read/write frami…

Why does Dafny matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Dafny?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Dafny.

Tags

  • Academic programming languages
  • Experimental programming languages
  • Microsoft Research
  • Microsoft free software
  • Microsoft programming languages
  • Programming languages created in 2009
  • Proof assistants
  • Software using the MIT license
  • Statically typed programming languages

Keep exploring