Sub topic 12
Testing invalid transitions with compile_fail doctests
A typestate API makes a promise: invalid call orders do not compile. Nothing checks that promise unless you test it. If someone later adds a stray impl<S> Door<S> block with a close method, Door<Closed> gains a method it should not have, and every ordinary test still passes. This chapter shows how to turn "this must not compile" into a test that runs in CI.
You should already know the typestate pattern from the earlier chapters: Door<Open> and Door<Closed>, transitions that take self, and state-specific impl blocks. You should also know how to run cargo test and read a rustc error code such as E0599.
Why ordinary tests cannot check this
A normal #[test] function must compile before it can run. A test that calls Door::new("front").close() would break the whole test crate, not fail one test. The check has to compile a snippet in isolation and pass only when compilation fails.
Rust gives you two tools for this:
compile_faildoctests, built into rustdoc. They live in documentation comments.- The
trybuildcrate, which compiles whole files and can compare the compiler's message against a saved copy.
Doctests come first because they need no extra dependency and double as documentation of what is forbidden.
The library under test
Doctests compile as if they were external crates. They can only use pub items and must import them by crate name. Put the door in a library crate named doorlib (cargo new doorlib --lib).
use std::marker::PhantomData;
pub struct Open;
pub struct Closed;
pub struct Door<S> {
name: String,
_state: PhantomData<S>,
}
impl<S> Door<S> {
pub fn name(&self) -> &str {
&self.name
}
}
impl Door<Closed> {
pub fn new(name: &str) -> Self {
Door { name: name.to_string(), _state: PhantomData }
}
pub fn open(self) -> Door<Open> {
Door { name: self.name, _state: PhantomData }
}
}
impl Door<Open> {
pub fn close(self) -> Door<Closed> {
Door { name: self.name, _state: PhantomData }
}
}The fields are private. That matters for one of the tests below.
Writing a compile_fail doctest
A doctest is a fenced block inside a /// or //! comment. Rustdoc compiles each block as its own small program, wrapping it in fn main() { ... } when you do not write one. Adding compile_fail after the fence marker inverts the result. The test passes when compilation fails and fails when the code compiles.
Inside a Rust source file, the documentation fence can use tildes (~~~) instead of backticks. Rustdoc accepts both. Here is the same library with the three invalid-use tests written next to the items they protect:
use std::marker::PhantomData;
pub struct Open;
pub struct Closed;
/// A door whose state is part of its type.
///
/// A closed door has no `close` method:
///
/// ~~~compile_fail,E0599
/// use doorlib::Door;
///
/// Door::new("front").close();
/// ~~~
///
/// The fields are private, so a caller cannot pick a state by building
/// the struct directly:
///
/// ~~~compile_fail,E0451
/// use doorlib::{Door, Open};
/// use std::marker::PhantomData;
///
/// let _door = Door::<Open> { name: String::new(), _state: PhantomData };
/// ~~~
pub struct Door<S> {
name: String,
_state: PhantomData<S>,
}
impl<S> Door<S> {
pub fn name(&self) -> &str {
&self.name
}
}
impl Door<Closed> {
/// Creates a closed door.
///
/// ~~~
/// use doorlib::Door;
///
/// let door = Door::new("front");
/// assert_eq!(door.name(), "front");
/// ~~~
pub fn new(name: &str) -> Self {
Door { name: name.to_string(), _state: PhantomData }
}
/// Opens the door. The old binding is moved, so it cannot be reused:
///
/// ~~~compile_fail,E0382
/// use doorlib::Door;
///
/// let closed = Door::new("front");
/// let _open = closed.open();
/// println!("{}", closed.name());
/// ~~~
pub fn open(self) -> Door<Open> {
Door { name: self.name, _state: PhantomData }
}
}
impl Door<Open> {
pub fn close(self) -> Door<Closed> {
Door { name: self.name, _state: PhantomData }
}
}Run the doctests with:
cargo test --docYou should see one line per block, similar to this:
test src/lib.rs - Door (line 5) - compile fail ... ok
test src/lib.rs - Door (line 14) - compile fail ... ok
test src/lib.rs - Door<Closed>::new (line 36) ... ok
test src/lib.rs - Door<Closed>::open (line 50) - compile fail ... okEach failing snippet protects one rule:
| Snippet | Rule it protects | Error it expects |
|---|---|---|
| `Door::new("front").close()` | `close` exists only on `Door<Open>` | `E0599`, no method found |
| `Door::<Open> { ... }` | Callers cannot forge a state | `E0451`, private field |
| use after `closed.open()` | Transitions consume the old value | `E0382`, use of moved value |
The E0451 test is easy to forget. If someone makes the fields pub, every other guarantee is bypassed, because a caller can write Door::<Open> { ... } without ever calling open.
The main pitfall: failing for the wrong reason
compile_fail passes on any compile error. Suppose you write the first snippet and forget the import:
// Inside a compile_fail doctest, this "passes" for the wrong reason:
// Door is not in scope, so compilation fails, but not because
// close() is missing on a closed door.
//
// Door::new("front").close();The test is green, yet it proves nothing about typestate. Two habits prevent this.
- Write the passing version first. Run it as a normal doctest, then change exactly one thing, such as calling
closeon the closed door, and addcompile_fail. - Attach the expected error code, as the examples above do.
The code check has a limit. The rustdoc book describes checking the error code as available on nightly toolchains. Stable accepts the annotation but may not enforce it. Check the rustdoc book for your toolchain version before you rely on it in CI. Writing the code anyway is still worthwhile, because it tells the next reader what the failure should be.
The workflow
Step E also catches regressions. If a refactor makes the invalid snippet compile, cargo test --doc reports that the test should have failed to compile.
Limits of doctests
Doctests have three limits you should know about.
- They only reach public API. A private helper type with typestate cannot be tested this way. Documentation tests also cannot see
pub(crate)items. - One snippet is one test. Each block pays for a separate compilation, so hundreds of them slow
cargo test --docnoticeably. - They do not compare messages. A change in the compiler's wording, or a different error that happens to share a code, goes unnoticed.
For a single-line rule, a doctest is the right tool. For a large API surface, or when the exact diagnostic matters, use trybuild.
Using trybuild for exact diagnostics
trybuild compiles each file in a directory and checks that it fails. It compares the compiler's output to a .stderr file next to it. Add it as a dev-dependency:
[dev-dependencies]
trybuild = "1"Create tests/ui.rs:
#[test]
fn invalid_transitions_do_not_compile() {
let t = trybuild::TestCases::new();
t.compile_fail("tests/ui/*.rs");
}Then create tests/ui/close_closed.rs:
use doorlib::Door;
fn main() {
Door::new("front").close();
}The first run fails because no expected output exists yet. trybuild writes the actual compiler output to a wip/ directory. After you review it, move the file to tests/ui/close_closed.stderr. Later runs compare against that file.
| Feature | compile_fail doctest | trybuild |
|---|---|---|
| Extra dependency | None | `trybuild` |
| Lives next to the API docs | Yes | No, in `tests/ui` |
| Checks the full message | No | Yes, via `.stderr` files |
| Sees private items | No | No, it uses the public crate |
| Sensitive to compiler upgrades | Little | High, messages change between releases |
The last row is the real cost of trybuild. A new compiler version can reword a diagnostic and break your saved .stderr files without any change in behavior. Many projects pin a toolchain for these tests, or run them only on one CI job.
What to cover
A reasonable checklist for a typestate type:
- Each state-specific method is absent from the other states (
E0599). - Each transition consumes the old value (
E0382). - Fields are private, so states cannot be forged (
E0451). - If you use a sealed trait, an outside type cannot implement it (
E0277on use, orE0603if the sealed module itself is private and named). - In a builder,
buildis absent until required fields are set (E0599).
Pair each negative test with a positive one that follows the allowed path. The positive tests prove the API remains usable. Without them, a change that breaks every call would make all the negative tests pass.
Exercise
A teammate adds this test to Door<Open>'s docs and it passes. What is wrong with it, and how would you fix it?
~~~compile_fail
let door = Door::new("front");
door.close();
~~~
Show answer
The snippet never imports Door, so it fails with an unresolved-name error, not the E0599 that shows close is missing on Door<Closed>. The test would pass even if close existed on closed doors. Fix it by adding use doorlib::Door;, first confirming the version with the use of .open().close() compiles, and then writing compile_fail,E0599 on the broken variant.
Exercise
You make the name field of Door pub. Which of the three tests in this chapter fails, and why does that failure matter?
Show answer
The E0451 test fails, because the snippet now compiles. It matters because a public field lets any caller write Door::<Open> { ... } directly, which skips open and breaks the guarantee that a Door<Open> came from a valid transition.