#play-TBD. No [pending] items, and no numbers on this page.
In a large program I cannot hold all of it in my head. I change one function, and something three modules away quietly depends on what I changed. A check that is always on tells me, seconds after the edit, which other part I just broke. That is why I count safety as part of agility: it lets me change code without being afraid of it.
This page says what Cone checks. It starts with a picture of where the compiler's reach ends, then lists every check, then shows a few at work with the compiler's own words.
The picture: what the compiler can prove
Take every program that is truly safe: no memory freed and then used, no two threads changing one value, no reading past the end of an array. Draw a box around all of them. Now ask which of those programs a compiler can prove are safe. It can prove some of them, and not others. Draw a horizontal line across the box. Above the line are the programs the compiler proves safe. Below the line are programs that really are safe, but whose safety the compiler cannot work out for itself.
Two things to see about the part below the line. The programs there are not unsafe. They are safe programs that rest on something other than the compiler: the author's reasoning, tests and review. I call that trusted. And moving the line down is the whole game. Every idiom the compiler learns to prove moves a piece of code from "trusted" to "proven".
Here are two boxes of the same size. Each stands for the same thing: every program that is truly safe.
Rust raised the bar, and showed that proof of this kind need not cost performance. The left box is that bar. Cone's aim is the right box: the same safety, with the line lower. Giving up nothing above the line is the point. Where Cone moves it lower is mostly in memory: a borrowed reference works the same on a local value, a single owner, a counted owner, an arena or a pool slot, and the compiler checks that the reference cannot outlive any of them. The memory page shows that.
What lives below the line in Cone is what you would expect: raw pointers, calls into C, and the few data structures with several owners that are better built from raw pointers behind a small, safe interface. A trust block will mark those places, so the code the compiler cannot check is easy to find and review. It is coming; it is not built, so today that code compiles unmarked.
The checklist
These are all the kinds of mistake Cone's compiler checks for before you run, or stops you at the moment one happens. Each row has a tick, the mistake, when it is caught (compile: before the program runs; run: the program stops at that line with a message; by design: the language makes the mistake impossible to write), and what it saves you when you change the code later. Almost all of it is checked while compiling, and costs nothing when the program runs. The bounds check on an index is the exception.
Memory
| Mistake caught | When | What it saves you later | |
|---|---|---|---|
| ✓ | Using a value after it was moved or given away | compile | Handing a value to a new owner can never leave a stale copy behind that a later edit uses by accident. |
| ✓ | A reference that outlives the value it points to (returning a borrow of a local, or storing one where it would outlast its source) | compile | Reorganizing which function owns what cannot create a dangling reference. |
| ✓ | Changing or moving a value while a borrow of it is still to be used | compile | A new line placed between "take a reference" and "use it" is refused instead of corrupting data. |
| ✓ | Changing the shape of a collection, or the variant of an enum, while a reference into it is alive (a push while holding a reference to an element) | compile | Adding a push inside a loop cannot invalidate the loop's references. |
| ✓ | Reading a variable, field or element that has no value yet, on any path through the code | compile | Adding a branch cannot leave a variable unset on the new path. |
| ✓ | Taking a value out of something that does not own it (a field out of a struct, an element out of an array, through a borrow) | compile | Refactoring cannot leave a struct or array with a hole in it. |
| ✓ | Freeing a value twice, or leaving a reference to a freed value | compile | Switching how a value is owned (single owner, counted, arena) cannot produce a double free. |
| ✓ | Letting a value outlive the arena it was allocated in | compile | Moving data into an arena cannot let it escape the arena's lifetime. |
| ✓ | Mixing up keys from different dynamic arenas | compile | Two arenas in one program cannot have their keys swapped. |
| ✓ | An index or range outside an array, list or slice | run | An off-by-one introduced by an edit stops at the line, with the index and the length. |
| ✓ | Running out of memory on an allocation | run | A failed allocation is reported where it happened, not later as garbage. |
| ✓ | A handle to something removed (a pool reference, a weak reference) | run | A stale handle answers "nothing there" as an Option. It never reads reused memory. |
Concurrency
| Mistake caught | When | What it saves you later | |
|---|---|---|---|
| ✓ | Two threads able to change the same value (a data race) | compile | Sharing a structure with a new thread is refused until it is safe, however far from the edit the other thread is. |
| ✓ | A borrowed reference crossing to another thread, in a message or a thread start | compile | Passing one more argument to an actor cannot smuggle in a reference tied to the sender's stack. |
| ✓ | A counted owner whose count is not thread-safe crossing threads | compile | Turning a helper into a parallel one cannot silently share a non-atomic count. |
| ✓ | A parallel each body writing to a variable outside the loop, or calling a function that writes a global | compile | Changing a loop to run on all cores is refused if the body is not independent. The message names the variable. |
| ✓ | break inside a parallel each, or using a traced Gc reference inside one | compile | The results of a parallel loop cannot depend on timing. |
| ✓ | Reaching locked data without taking the lock | compile | Adding a read of a locked value cannot skip the lock. |
| ✓ | Holding a borrow or a lock across an await | compile | Adding an await to a behavior cannot keep a lock held while it waits. |
| ✓ | Reaching an actor's private state from outside | compile | Only the actor's own behaviors touch its state, one message at a time, so its internals can change without hunting for outside users. |
| ✓ | await outside a behavior, or awaiting a behavior that returns nothing | compile | Reply shapes are visible in the declaration and enforced at every call. |
| ✓ | A conflicting borrow on a single-thread read/write cell | run | The program stops at the second borrow, naming the conflict. |
Today the compiler does not stop a plain var global from being reached by several threads. That row is not on the list because it is not built yet.
Types and values
| Mistake caught | When | What it saves you later | |
|---|---|---|---|
| ✓ | A value of one type used where another is expected, including silent narrowing between number types | compile | Changing a field's type shows every place that depended on the old one. |
| ✓ | A bool or char used as a number (or the reverse) | compile | You ask for the conversion by name, so it is visible when you read the code later. |
| ✓ | A value that might be absent used as if present: references are never null, and a maybe-missing value is an Option that must be tested | compile | Making a result optional lists every caller that has to cope. |
| ✓ | A match that misses a case of an enum | compile | Adding a variant lists every match that must learn it. |
| ✓ | A match using a function as a pattern with no else | compile | The compiler cannot know what a function covers, so it requires the fallback. |
| ✓ | An error value (Result) thrown away unread | compile (warning) | Making a function fallible flags every caller that ignores the failure. _ = says it was on purpose. |
| ✓ | Writing through a read-only reference, a let variable, or an Immutable type | compile | A promise of "this does not change" holds after the next edit. |
| ✓ | Reaching a private field or method from another module, or giving it a value in a construction | compile | Private means free to change. |
| ✓ | A name that does not exist; a folded or imported name that collides with another | compile | A library upgrade that adds a clashing name is refused where the fold is written, not at a mysterious call. |
| ✓ | A generic called with a type that lacks what the constraint asks; a method used on an instance where it does not exist | compile | The error names the constraint at the call, not deep inside the template. |
| ✓ | A type that claims to meet a trait (is) but lacks a method; a module that claims a module trait but lacks a function or global | compile | Changing a trait shows every type or module that must follow. |
| ✓ | An integer literal too big for its type; a constant divided by zero; a constant shift out of range | compile | Constants are checked as written. |
| ✓ | A tuple index past the end, or a field that does not exist; a call that could mean two overloads | compile | Reshaping a tuple or adding an overload lists what it affects. |
| ✓ | A failed assert, unreachable() or todo() | run | A stated assumption that stops holding is reported at the line, with your message. |
| ✓ | assertDebug: expensive checks kept out of the finished build | run (debug builds only) | You can leave slow invariants in the code permanently. |
Coming, beside the checks it would add to: a pure function promises it reads only its arguments, and the compiler will refuse a call to anything impure inside it. pure is not accepted yet. Conditions on entry and exit (requires and ensures) are designed and not built.
Resources and lifecycle
| Mistake caught | When | What it saves you later | |
|---|---|---|---|
| ✓ | Forgetting to release a file, socket or lock | by design | A value's final runs exactly once, when its last owner goes, in a fixed order (newest first; value, then fields). Nothing to remember when code moves. |
| ✓ | A type marked Copy that has a finalizer | compile | A value that must be closed cannot be copied into two owners. |
| ✓ | Modules that depend on each other in a loop; a module importing its parent | compile | Dependencies run one way, so a module can be moved or replaced without surprises. |
| ✓ | Setup and teardown of module globals in the wrong order | by design | Initializers run dependencies-first and finalizers in reverse, every time. |
| ✓ | A closure that holds a borrow being stored or sent | compile | The error names the variable and says to list it as a copied capture. |
| ✓ | A temporary dying while a borrow of it lives on | compile | Chaining calls differently cannot leave a borrow of a dead temporary. |
Coming: recover blocks will build a shared structure and take it out as a uniquely owned or immutable one, so it can move across threads without a lock.
Six checks at work
A list of ticks is easy to nod at. Here are six of them, each a mistake I could make in a few seconds, and what the compiler says. These are the compiler's real words, not my paraphrase.
A value that has moved
An Order owns its customer's name, so handing it to bake gives it away. A second call has nothing left to hand over.
mod baker;
import stdio use *;
struct Order { pub customer: Uni[str]; pub loaves: i32; }
fn bake(o: Order) {
print <- "baking ", o.loaves, " for ", o.customer, "\n";
}
fn main() {
let o = Order("Ana", 3);
bake(o);
bake(o);
}
Error 1048: This variable's value has been moved out. It is no longer there to use.
--> bake(o);
^--- safety_moved_refused.cone:14:8
Try it: using a value after it moved
The rule: one owner at a time. Later, when I change who owns what, this is the check that stops me leaving a stale copy behind.
A reference and a push
I take a reference to the first score, then push a third. The push may move the list's storage, and my reference would point at nothing.
mod scores;
import stdio use *;
import collections use *;
fn main() {
var scores = List[i32]() <- 10, 20;
let best = &mut scores[0usize];
scores.push(30);
*best = 7;
print <- scores[0usize], "\n";
}
Error 1339: This call could change the shape of a 'List' while 'best' still holds a borrow into it (made by '&[]' at 8:14, through a path other references share), used again at 10:4: 'push' reshapes the 'List' it is called on: it writes a field of it, runs a finalizer of an element, or moves an element out. A 'List' that changes shape may move or free what it lent. Reach it through an 'imm' or 'uni' reference, or copy what is needed out before this call.
--> scores.push(30);
^--- safety_shape_refused.cone:9:9
Try it: a push while a reference is held
The message also says how to fix it: reach the list through a reference that cannot reshape it, or copy out what you need first.
A value that might not be there
References are never null. When a value may be missing, its type says so: Option. To use it, I have to find out whether something is in it.
mod lookup;
import stdio use *;
fn half(n: i32) Option[i32] {
if n % 2 == 0 { Some(n / 2) } else { None }
}
fn main() {
let h: i32 = half(7);
print <- h, "\n";
}
Error 1013: Initialization value's type does not match variable's declared type
--> let h: i32 = half(7);
^--- safety_option_refused.cone:10:20
Try it: an Option used as if it were there
This is the null dereference, stopped before it can happen. Making a result optional later will do the same to every caller that forgot.
An enum with a new variant
Suppose the cafe adds hot chocolate to the menu. Every match over drinks has to learn about it, and the compiler lists the ones that do not.
mod cafe;
import stdio use *;
enum Drink { Espresso; Tea; HotChocolate; }
fn show(d: Drink) {
match d {
case Espresso { print <- "espresso: 250\n"; }
case Tea { print <- "tea: 200\n"; }
}
}
fn main() {
show(Drink.Tea);
}
Error 1417: This match does not cover HotChocolate: add a case for each, or end the match with 'else {}'.
--> match d {
^--- safety_match_refused.cone:8:3
Try it: a match that misses a case
Two cores, one variable
Putting parallel before each runs the passes at the same time. Adding up into a variable outside the loop would be a data race.
mod tally;
import stdio use *;
import collections use *;
import actors;
fn main() {
let orders = List[i32]() <- 40, 60, 90;
var total = 0;
parallel each o in orders {
total = total + *o;
}
print <- "total: ", total, "\n";
}
Error 1382: A 'parallel each' body may not write total, which is declared outside the loop: the passes run at the same time. Outside variables are read-only for the loop. Hand results back with the parallel builder, or 'mutItems()' on the items, or count with an Atomic.
--> total = total + *o;
^--- safety_par_refused.cone:11:23
Try it: a parallel loop that writes a shared total
It names the variable and offers three ways to get the answer out safely. The concurrency page shows them.
A count that is not thread-safe
An Rc keeps its count with one thread in mind. Sending one to an actor in a message would let two threads change the count at once.
mod till;
import stdio use *;
import actors;
struct Prices {
pub loaf: i32;
}
actor Till {
pub async fn sell(self, prices: Rc[imm, Prices], loaves: i32) i32 {
loaves * prices.loaf
}
}
fn main() {
let prices = Rc[imm, Prices](loaf: 3);
Till().sell(prices, 2);
}
Error 1194: Actor Till's behaviour sell takes prices, a Rc[imm, Prices], which is not Sendable: it is an owner that may be copied, and Rc does not declare ThreadSafe: its copies could not be made and dropped on several threads at once. It may cross as a uni owner, which moves it, or as an owner of a region declaring ThreadSafe, such as Arc. A message carries its arguments to the thread the actor runs on, so each must be Sendable.
--> pub async fn sell(self, prices: Rc[imm, Prices], loaves: i32) i32 {
^--- safety_send_refused.cone:11:27
Try it: sending an Rc to an actor
It tells you what may cross instead: a single owner that moves, or an Arc.
The few checks that happen as the program runs
A bounds check cannot be done at compile time when the index is only known as the program runs. So the program stops where the mistake happens, rather than adding up whatever lies past the end of the array. Here the loop makes one pass too many.
mod guard;
import stdio use *;
fn main() {
let shelves = [12, 0, 7];
var total = 0;
var n = 0usize;
while n <= 3usize {
total += shelves[n];
n += 1usize;
}
print <- "loaves: ", total, "\n";
}
panic at safety_index_panic.cone:10: index 3 is out of bounds for a count of 3
The message gives the line, the index and the length. It is one of the checks marked "run" in the lists above.
What stays your job
Cone is a teammate, not a guard. The compiler cannot know what a program is for, so these are still yours:
- deadlocks, and race conditions other than data races;
- loops that never end, and logic that is simply wrong;
- memory waste, and running out of stack or memory;
- integer overflow, which wraps silently;
- division by zero at run time, which is not checked yet (a panic for it is decided and coming);
- raw pointers and calls into C, which are not guarded (the trust block that marks them is coming).
The checks above do not make a program right. They make it quick to find out when an edit has broken something. That is the part of safety I want for agility. Next: how memory is managed, which is where most of the line's move downward happens; or back to why I built Cone.