Sub topic 12
Testing invalid transitions with compile_fail doctests
This chapter assumes you can write a typestate Door<State> like the one in the earlier chapters. It also assumes you can run cargo test. The goal is to turn "this call must not compile" into a test that fails if someone weakens your API.
Why test code that must not compile
A typestate API makes a promise: invalid call orders are rejected by the compiler. Ordinary tests can't check that promise, because a test that calls close on a closed door doesn't build. If a refactor adds a close method to Door<Closed>, every existing test still passes and the guarantee is gone.
Rustdoc has a fence attribute for this, compile_fail. A doctest marked with it passes only if compilation fails.
A library crate with doctests
Doctests run only for library crates, and they see only public items. Create a library with cargo new --lib typestate_demo. Doctests import the crate by name, so the examples below use typestate_demo.
Doc comments use tilde fences (~~~) here. Rustdoc accepts them, and they let a code sample contain fenced examples without conflict.
use std::marker::PhantomData;
pub struct Open;
pub struct Closed;
pub struct Door<State> {
_state: PhantomData<State>,
}
impl Door<Closed> {
pub fn new() -> Self {
Door { _state: PhantomData }
}
/// Opens the door.
///
/// Opening and closing in order compiles:
///
/// ~~~
/// use typestate_demo::Door;
/// let door = Door::new().open();
/// let _closed = door.close();
/// ~~~
///
/// An open door has no `open` method:
///
/// ~~~compile_fail,E0599
/// use typestate_demo::Door;
/// let door = Door::new().open();
/// door.open();
/// ~~~
///
/// The old binding is moved by `open`, so it cannot be reused:
///
/// ~~~compile_fail,E0382
/// use typestate_demo::Door;
/// let door = Door::new();
/// let _open = door.open();
/// door.open();
/// ~~~
pub fn open(self) -> Door<Open> {
Door { _state: PhantomData }
}
}
impl Door<Open> {
pub fn close(self) -> Door<Closed> {
Door { _state: PhantomData }
}
}Run the doctests with cargo test --doc. Each fence becomes a separate test, and the compile_fail ones are reported as "compile fail".
What the test actually proves
A compile_fail doctest passes on any compile error. That is its main weakness. If you misspell Door in the import, the test still passes, but it no longer checks your API.
Two habits reduce this risk:
- Put a passing doctest next to each failing one, as above. The passing example proves the imports and the setup are valid. The failing example then differs by one invalid call.
- Add an error code, such as
compile_fail,E0599. Rustdoc checks the code only on the nightly toolchain. On stable it accepts the code and ignores it, so treat it as documentation of intent there.
| Error code | Meaning in typestate code |
|---|---|
| E0599 | The method does not exist in this state |
| E0382 | The value was already moved by a transition |
| E0308 | A function expected a different state type |
When doctests are not enough
Doctests are good for public API guarantees and double as documentation. They have limits:
- They can't test private items, because they compile as an external crate.
- On stable they don't check the error message.
- Each doctest is compiled separately, so a large suite is slow.
For exact error output, the trybuild crate compiles files from a tests/ directory and compares the compiler's message with a saved snapshot. It is a dev-dependency and costs more to maintain. Use doctests for the main guarantees and trybuild only if message stability matters.
Exercise
A compile_fail doctest for Door<Closed>::close passes, yet someone later adds close to Door<Closed>. Why might the test still pass, and how do you guard against it?
Show answer
The test passes on any compile error, so an unrelated error such as a wrong import path or a typo would keep it green. Guard against this by adding a passing doctest with the same setup, so the imports are proven valid. Also add the error code E0599, which stable rustdoc ignores but nightly checks. The failing example should then differ from the passing one only by the invalid call.