Stroustrup objects to adding Contracts to C++

Richard (Rikki) Andrew Cattermole richard at cattermole.co.nz
Thu Nov 12 02:17:07 UTC 2026


On 12/11/2026 2:57 PM, Walter Bright wrote:
> Keep in mind that Rust compiles a couple orders of magnitude slower than 
> dmd.

A good chunk of that is LLVM, but yes.

> Also, if attribute inference is made optional (for speedy compilations), 
> there's a risk of different semantics result from debug vs inference 
> builds. Template instantiations, for example, are sensitive to attributes.

Yes that is why its important to take them out of the type system, that 
way codegen doesn't change.

> D's DFA analysis uses the most efficient algorithm known at the time. I 
> spent many, many hours profiling and optimizing it. But still, the 
> compute time goes up exponentially with the cyclomatic complexity of it. 
> Extending it to the whole program would make dmd a slug.
> 
> Faster computers hasn't helped, because the complexity of code has risen 
> to match it.

There were others.

I do think with the right motivation, and knowledge of future 
requirements that you would have solved it better than you had.
But that might just be me thinking highly of you ;)

For reference here is what DeepSeek has to say about my compiler's 
architecture for this. I do want to note that it is faster than the 
backend, and together its faster than clang compiling the code 
transcompiled to c++. Also note that it isn't so far away from dmd, that 
I do believe that you could have come up with some of it.

-----------------------------------------------------------------------------

## Short answer

`cailc` treats an effect as a **summary attached to the declaration**, 
not as a path-sensitive proof to be re-derived. The analysis is a 
**single memoized DFS over the call graph**:

- effects live in a tiny join-semilattice (`impure`, `noreturn`, `unsafe`);
- each declaration is analyzed once and its normalized signature is 
cached on the `FuncDecl`;
- a re-entered declaration is a back edge and contributes the identity `∅`;
- a cycle root later **patches its whole cycle to its final signature**, 
so cycles are solved in one write instead of a fixed-point loop;
- symbolic effect expressions are kept in a canonical normal form, so 
repeated joins/substitutions do not grow an expression tree.

That is what keeps the pass linear-ish instead of exponential.

---

## 1. The effect domain is deliberately small

`source/cail/core/effect.d:13-17`:

```d
enum Capability : ubyte {
     impure   = 1 << 0,
     noreturn = 1 << 1,
     unsafe   = 1 << 2,
}
```

`EffectSet` is just a `ubyte` mask; `join` is bitwise OR:

```d
EffectSet join(EffectSet o) { return EffectSet(bits | o.bits); }
```

So the concrete lattice has height at most 3. Even if iteration were 
used, it would terminate. The implementation does not iterate anyway.

Symbolic effects add free variables (`EffVar`) for effect-polymorphic 
signatures, but those are normalized separately, discussed below.

---

## 2. The “archive”: one summary per declaration

The memoization state is on the declaration (`source/cail/ast/decl.d:94` 
and `source/cail/sema/effects.d:155-163`):

```d
private void settleEffect(FuncDecl f, EffectExpr sig) {
     f.effectSig = sig;
     f.effects = effConcretize(sig, EffectSet.top);
     ...
     f.effectState = EvalState.resolved;
}
```

`computeFuncEffect` (`source/cail/sema/effects.d:166-229`) does:

```d
if (f.effectState == EvalState.resolved) return f.effectSig;
```

So once a function has been visited, every later call site reads the 
cached summary in `O(1)` instead of re-walking the body.

Why this matters for exponential blow-up:

- Without summaries, a call graph shaped like a diamond (`a → b,c`; `b,c 
→ d`; ...) re-analyzes shared callees once per path. The number of paths 
is exponential in depth.
- With summaries, each function body is scanned once, and each call edge 
performs a join of already-computed summaries. The call-graph cost is 
`O(|V| + |E|)` plus the AST scan cost.

The stored summary is a normalized effect expression, not the 
derivation/proof tree that produced it. That is the key space-saving choice.

---

## 3. Cycle handling: tri-state DFS plus cycle identity

`EvalState` is the standard three-state mark 
(`source/cail/core/effect.d:62-66`):

```d
enum EvalState : ubyte {
     unvisited,
     inFlight,
     resolved,
}
```

`computeFuncEffect` marks a function `inFlight`, pushes it on 
`effectDfsStack`, scans its body, then pops and marks it `resolved`.

When a call re-enters an `inFlight` function, that is a back edge. 
Instead of recursing, it returns the identity:

```d
if (f.effectState == EvalState.inFlight) {
     ...record cycle members...
     return effPure();   // cycle identity
}
```

The comment at `source/cail/sema/effects.d:16-29` states the invariant:

 > Effects are a join-semilattice of capabilities; a declaration's 
signature is a monotone map over its callable parameters' latent 
effects. Inference is a depth-first walk over the call graph with cycle 
interception: re-entering an in-flight declaration contributes the 
identity `∅`, and the capabilities observed on the recursive path are 
recovered as the stack unwinds (`F_parent = F_local ⊔ F_child`). No 
fixed point iteration, no worklist.

For a simple recursive or mutually recursive cycle, this already gives 
the least fixed point:

- pure recursion: every path contributes `∅`, so the result stays `∅`;
- recursion with an effect on the path: the impure local effect is 
joined as the stack unwinds, so the root becomes `impure`.

The test at `testsuite/pos_run/control_typestate_misc.cail:402-408` 
explicitly checks that mutually recursive `@pure` functions stay pure.

---

## 4. The cycle-root patch: making the answer order-independent

The `∅` back-edge identity alone has a declaration-order weakness: 
effects discovered at the root *after* the recursive call are not 
visible to a callee that was memoized before that discovery.

The implementation fixes that with `effectCycleMembers` 
(`source/cail/sema/effects.d:149-153`):

```d
/// Cycle members recorded for a root that is still in flight. When the root
/// finishes, every member is patched to the root's final signature: the 
root
/// has by then joined every member's local effects and external 
callees, so the
/// result is the SCC's total and does not depend on declaration order.
private FuncDecl[][FuncDecl] effectCycleMembers;
```

On re-entry, it finds the root’s position in `effectDfsStack` and 
records every frame from that root to the top as a cycle member:

```d
int ri = -1;
foreach (i, g; effectDfsStack) if (g is f) { ri = cast(int)i; break; }
if (ri >= 0) {
     auto list = f in effectCycleMembers;
     foreach (i; ri .. cast(int)effectDfsStack.length) { ... }
}
return effPure();
```

When the root finishes, it has joined:

- every member’s local effects observed while unwinding, and
- every external callee summary.

So its signature is the SCC’s total. The patch is one write per member:

```d
if (auto list = f in effectCycleMembers) {
     foreach (m; *list) if (m !is f) settleEffect(m, sig);
     effectCycleMembers.remove(f);
}
```

This is why the analysis can claim “no worklist, no Kleene iteration”: 
the one-shot patch replaces iteration. The reproducer for the original 
order-dependence bug is `testsuite/neg/neg_effects_inference.cail:3-23`, 
with both declaration orders expected to reject `@pure` misuse.

```mermaid
flowchart TD
     A[computeFuncEffect f] --> B{state?}
     B -->|resolved| C[return f.effectSig]
     B -->|inFlight| D[return ∅, record cycle members]
     B -->|unvisited| E[mark inFlight, push f]
     E --> F[scan body]
     F --> G[join callee summaries]
     G --> H[pop, settleEffect f]
     H --> I{cycle root?}
     I -->|yes| J[patch every member to f's signature]
     I -->|no| K[return signature]
     J --> K
```

---

## 5. Symbolic effects do not grow into a tree

Function signatures can mention free effect variables (`@pure(isPure)`) 
and unions. If joins and substitutions built a new tree each time, the 
representation could grow exponentially even with call-graph memoization.

`source/cail/ast/effect.d` prevents that with a canonical normal form:

```d
struct EffectNorm {
     EffectSet concrete;       // bitset
     uint[] vars;              // sorted, deduplicated
     EffectSet[uint] domains;  // per-variable capability domain
}
```

`effectNormalize` flattens `EffUnion` nodes, unions the concrete bits, 
collects variables, then sorts and deduplicates them 
(`source/cail/ast/effect.d:74-103`). `effJoin` normalizes both operands 
and rebuilds one canonical expression (`:153-167`). `effSubst` 
substitutes a variable and renormalizes (`:170-183`).

So the size of a summary is bounded by:

- 3 concrete bits, plus
- the number of distinct free effect variables in that signature.

It is not bounded by the number of call paths or by the depth of nested 
joins.

At a higher-order call, the scanner also groups substitutions by variable:

```d
EffectExpr[uint] bindings;
...
foreach (v; vars) {
     auto cur = v in bindings;
     bindings[v] = cur is null ? argLat : effJoin(*cur, argLat);
}
foreach (v, bound; bindings) callEff = effSubst(callEff, v, bound);
```

That is `source/cail/sema/effects.d:904-910`: one join per variable, 
then one substitution per variable, rather than expanding each argument 
latent at every occurrence.

When inference finishes, `settleEffect` concretizes the summary:

```d
f.effects = effConcretize(sig, EffectSet.top);
```

Unbound variables widen to their declared domains. Later passes 
therefore read a plain `EffectSet` from `f.effects`, while enforcement 
uses the symbolic `f.effectSig`.

---

## 6. Enforcement reads the archive

After all summaries are computed, `inferEffects` runs two enforcement 
passes:

```d
foreach (f; fns) computeFuncEffect(f, state);
foreach (f; fns) enforceDeclaredEffect(state, f);
foreach (f; fns) enforceSafety(state, f);
```

- `enforceDeclaredEffect` checks `effectLeq(effStripUnsafe(f.effectSig), 
declared)` — the body is a theorem against the declared axiom.
- `enforceSafety` reads the normalized `f.effectSig` and checks for 
`unsafe`, including safety variables.

Neither pass re-walks bodies or re-analyzes callees. They are linear in 
the number of declarations.



More information about the Digitalmars-d mailing list