Skip to content

Commit 3db3057

Browse files
committed
Merge remote-tracking branch 'origin/claude/own-types-documentation-1x4iut' into claude/pr-docs-review-validation-1wat02
2 parents ac909ee + 64f4e67 commit 3db3057

1 file changed

Lines changed: 231 additions & 25 deletions

File tree

‎docs/proposals/P-010-type-disciplines.md‎

Lines changed: 231 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,18 @@
22

33
- **Status:** draft (horizon)
44
- **Depends on:** `spec/OwnCore.md` (the ownership/affine core and its fact
5-
vocabulary), `spec/Lifetimes.md`; relates to P-006 (capability/lifetime — where
6-
branded `resource`/capability types are held), P-008 (effects — the `use !Db`
7-
half of a signature), and P-005 (IDisposable typestate — the first concrete
8-
protocol). See `docs/ROADMAP.md` for where this sits in the strategy.
5+
vocabulary), `spec/Lifetimes.md`; relates to P-005 (`IDisposable` typestate —
6+
the first concrete protocol), P-006 (DI lifetimes — a region contract, not a
7+
protocol), P-007 (ArrayPool/Span borrow-view — the pooled-buffer instance),
8+
P-008 (effects — the `use !Db` half of a signature), and P-017 (multi-stack
9+
frontends — where `Own.Types` facts travel beyond C#). See `docs/ROADMAP.md`
10+
for where this sits in the strategy.
911

1012
## Motivation
1113

14+
> **Own.Types is not trying to make C# pretty. Own.Types makes domain lies
15+
> mechanically harder to write.**
16+
1217
The guiding heuristic: types aren't only about the *shape* of data
1318
(`string`/`int`/`User`). They can encode validity, access rights, state,
1419
dimension, order of operations, effects, protocol, ownership, even proofs. If a
@@ -24,25 +29,66 @@ not `DeclarationId`, even though both are `string`) and **what STATE it is in**
2429
make everything `string` / `int` / `Guid` / `Dictionary<string, object>` — is not
2530
flexibility. It is homeless JSON pretending to be architecture.
2631

27-
`Own.Types` adds those two dimensions as an **external static-contract layer**
28-
over existing C#: an analyzer / source generator / `.own` spec that checks the
32+
`Own.Types` adds those dimensions as an **external static-contract layer** over
33+
existing C#: an analyzer / source generator / `.own` spec that checks the
2934
discipline, without rewriting the code into a new language. This is the move that
3035
turns Own.NET from "a borrow checker for C#" into "an external static contract
3136
layer for C#/.NET that adds ownership, typestate, effects, capabilities, and
3237
domain types" — while the DSL stays a spec/model/contract language and pointedly
3338
refuses to become a second C# people write business logic in.
3439

40+
## Map of the five pillars
41+
42+
```text
43+
Own.Types
44+
├─ Semantic primitives — what a value MEANS
45+
│ ├─ newtype / branded types
46+
│ ├─ constrained (refinement) types
47+
│ ├─ units / quantities
48+
│ └─ strongly typed IDs
49+
│
50+
├─ Algebraic domain modeling — what a value CAN BE
51+
│ ├─ discriminated unions
52+
│ ├─ exhaustive matching
53+
│ ├─ Option
54+
│ └─ Result / error unions
55+
│
56+
├─ State/lifetime discipline — what STATE a value is in
57+
│ ├─ typestate
58+
│ ├─ owned/borrowed/must-dispose
59+
│ ├─ event subscription lifetime
60+
│ ├─ pooled buffer lifecycle
61+
│ └─ ValueTask/single-use constraints
62+
│
63+
├─ Tooling — how the discipline is enforced
64+
│ ├─ source generators
65+
│ ├─ Roslyn analyzers
66+
│ ├─ code fixes
67+
│ ├─ generated docs
68+
│ └─ OwnIR facts
69+
│
70+
└─ Future — horizon, not committed
71+
├─ .own DSL
72+
├─ F# generator/backend
73+
├─ interop analyzers
74+
└─ multi-language frontends
75+
```
76+
77+
The first four pillars share one restraint: brands, refinements, units, unions,
78+
and protocols all lower to plain structs/records plus smart constructors — the
79+
*discipline* is enforced by analyzer, not by a second type checker that could
80+
drift from the affine core (the project's standing meta-irony).
81+
3582
## Scope
3683

37-
The four most-applied disciplines, in priority order. Each has a `.own`
38-
declaration and a checked C# imitation; none requires a runtime.
84+
### 1. Semantic primitives — what a value means
3985

4086
1. **Branded / opaque types.** Distinguish `ProductId`, `DeclarationId`, `Email`
4187
though all are `string` underneath, so `GetProduct(declarationId)` is a
4288
diagnostic, not a 2 a.m. incident. DSL: `brand ProductId : string;`. C#:
4389
`[OwnBrand("ProductId")]` on a `readonly record struct` plus a smart
4490
constructor; the analyzer enforces that the wrapped value only enters through
45-
it. (Mechanically these are phantom types — see the catalog.)
91+
it. (Mechanically these are phantom types — see the deferred catalog.)
4692

4793
2. **Refinement types** — "int, but valid":
4894
`refinement Port : int where value >= 1 && value <= 65535;`,
@@ -58,8 +104,55 @@ declaration and a checked C# imitation; none requires a runtime.
58104
tax rates, and physical quantities — the domains where a silent unit mix-up
59105
is a financial bug, not a rounding one.
60106

61-
4. **Typestate / protocols.** Encode object state in the type so methods can only
62-
be called in a valid order:
107+
4. **Strongly typed IDs.** Not a new mechanism — the single most-applied
108+
*instance* of branded types, called out because it is the pattern developers
109+
reach for first: `brand OrderId : Guid; brand CustomerId : Guid;` so
110+
`GetOrder(customerId)` is caught even though both brands share the same
111+
underlying `Guid`. The analyzer's job here is narrower than general branding:
112+
catch **argument-order transposition** at call sites where two branded IDs of
113+
the same underlying type are adjacent parameters — the concrete bug this
114+
pillar exists to kill.
115+
116+
### 2. Algebraic domain modeling — what a value can be
117+
118+
5. **Discriminated unions.** A closed set of shapes a value can take:
119+
`union Shape { Circle(radius: float); Rect(w: float, h: float); }`. Lowers to
120+
a sealed hierarchy (or a source-generated closed struct union) that cannot be
121+
extended from outside the declaration — the analyzer, not `sealed` alone,
122+
enforces closedness across partial classes and other-assembly subclassing
123+
attempts.
124+
125+
6. **Exhaustive matching.** C#'s `switch` over a non-`enum` type has no
126+
exhaustiveness check at all, and even enum switches only get an ignorable
127+
`CS8509` warning. Own.Types promotes this to a hard diagnostic tied to the
128+
`union` declaration: every `switch`/pattern match over a branded union must
129+
cover every case or an explicit `default`/discard, and a new case added to
130+
the union must break every non-exhaustive match site at compile time, not at
131+
3 a.m. in production.
132+
133+
7. **`Option`.** Replaces the gap nullable reference types leave open (nothing
134+
stops a `string?` from silently meaning "not yet loaded" *and* "deliberately
135+
absent" *and* "error", all at once). `Option<T>` is a two-state union
136+
(`Some`/`None`); the analyzer flags unmatched `.Value` access the same way it
137+
flags a non-exhaustive union match — this pillar is a specialization of #6,
138+
not a separate mechanism.
139+
140+
8. **`Result` / error unions.** `Result<T, E>` as the alternative to
141+
exceptions-as-control-flow for expected failure. Two enforcement angles: (a)
142+
the exhaustiveness rule from #6 — a `Result` must be matched on both `Ok` and
143+
`Error`, not just unwrapped; (b) an "unobserved result" diagnostic, structurally
144+
the same shape as an unawaited `Task` — a `Result` that is constructed and
145+
never matched or propagated is silently swallowed failure.
146+
147+
Pillar 2's four items are one mechanism wearing three hats: a closed-shape
148+
declaration plus an exhaustiveness check. `Option` and `Result` are simply the
149+
one- and two-error-case unions developers reach for constantly enough to name
150+
directly, rather than making every call site spell out a bespoke `union`.
151+
152+
### 3. State/lifetime discipline — what state a value is in
153+
154+
9. **Typestate / protocols.** Encode object state in the type so methods can
155+
only be called in a valid order:
63156

64157
```text
65158
protocol Report {
@@ -78,12 +171,83 @@ declaration and a checked C# imitation; none requires a runtime.
78171
Typestate is also the generalization that subsumes **session types** (typed
79172
message-ordering protocols) as the special case where the object is a channel.
80173

81-
The combined picture — domain types, refinements, resources, protocol state, and
82-
effects in one signature set:
174+
10. **Owned / borrowed / must-dispose.** Already built as a standalone
175+
diagnostic in [P-005](P-005-idisposable-ownership.md) — Own.NET already
176+
treats `IDisposable` as typestate C# lacks. This pillar's job is *not* to
177+
duplicate P-005's checker; it is to surface the same ownership verdict as a
178+
**type-level marker** in the signature a developer reads (`Owned<T>`,
179+
`Borrowed<T>`, `[OwnMustDispose]`) so the discipline is visible at the call
180+
site, not only in an analyzer squiggle.
181+
182+
11. **Event subscription lifetime.** Already covered as a resource-lifetime
183+
profile in P-004 (WPF) and P-006 (DI lifetime, where a subscription is one
184+
captive-dependency shape). Own.Types' angle: a typed subscription handle
185+
that is itself a two-state protocol (`Active -> Disposed`, unsubscribe
186+
consumes self), so double-unsubscribe and use-after-unsubscribe fall out of
187+
the same typestate mechanism as #9, instead of a bespoke `SUB0xx` rule.
188+
189+
12. **Pooled buffer lifecycle.** Already covered in
190+
[P-007](P-007-arraypool-span.md) (ArrayPool/Span borrow-view). Own.Types'
191+
angle: model a rented buffer as `Buffer<Rented|Returned>` — a two-state
192+
protocol exactly like #9 — so "view survives `Return`" is reported through
193+
the general typestate/use-after-move path rather than a parallel
194+
pool-specific engine.
195+
196+
13. **`ValueTask`/single-use constraints.** A well-known .NET footgun:
197+
`ValueTask` must be awaited (or converted) exactly once, and never both
198+
stored and awaited. Structurally this is a **single-transition protocol**
199+
(`Pending -> Awaited`; awaiting twice, or awaiting after `.AsTask()`, is
200+
use-after-move) — the same affine "consume once" mechanism as #9, applied to
201+
a BCL type Own.NET does not own and cannot annotate at the source, so the
202+
marker has to live at the call site (`[OwnSingleUse]` on the
203+
producing member, or an analyzer-only rule with no DSL declaration).
204+
205+
Pillars 10–13 are **not** new checkers to build — they are existing or
206+
near-existing lifetime facts (P-004/005/006/007) reframed as instances of the
207+
two general Own.Types mechanisms (ownership marker, typestate protocol). The
208+
payoff of doing this pillar at all is *unification*: one mental model
209+
(protocol state, consume-on-transition) instead of four bespoke rule families.
210+
211+
### 4. Tooling — how the discipline is enforced
212+
213+
14. **Source generators.** Emit the boilerplate a brand/refinement/union
214+
declaration implies — smart constructors, equality, `ToString`, exhaustive
215+
`Match`/`Switch` helper methods — so the discipline costs one declaration,
216+
not hand-written ceremony per type.
217+
218+
15. **Roslyn analyzers.** The enforcement side for every pillar above: brand-
219+
boundary violations (#1), predicate bypass (#2), unit mismatch (#3),
220+
non-exhaustive match (#6), unobserved `Result` (#8), invalid protocol
221+
transition / use-after-transition (#9, #11–#13).
222+
223+
16. **Code fixes.** A matching quick-fix per analyzer: insert the missing
224+
`switch` arm stub for a non-exhaustive match, wrap a raw literal in its
225+
brand's smart constructor, insert the missing `Dispose`/transition call.
226+
Diagnostics without a code fix push the discipline back onto the developer
227+
manually re-deriving the fix; that is the gap this item exists to close.
228+
229+
17. **Generated docs.** Render the `.own` declarations (brand / refinement /
230+
union / protocol) into human-readable reference pages, the same way
231+
`spec/Diagnostics.md` is the single source of truth for `OWN` codes today —
232+
one declaration, read by the compiler *and* the wiki, so the contract and
233+
its documentation cannot drift apart.
234+
235+
18. **OwnIR facts.** The seam every pillar above lowers through: new OwnIR fact
236+
kinds (`brand`, `refinement`, `union`, `protocol-state`) alongside the
237+
existing resource/ownership facts in `spec/OwnIR.md`, so any frontend —
238+
today's Roslyn C# extractor, tomorrow's OwnTS/OwnJava/OwnKotlin (P-017) —
239+
emits and consumes the same domain-type vocabulary without re-deriving it
240+
per language.
241+
242+
The combined picture — domain types, refinements, unions, resources, protocol
243+
state, and effects in one signature set:
83244

84245
```text
85246
brand ProductId : string;
247+
brand OrderId : Guid; brand CustomerId : Guid;
86248
refinement NonEmptyString : string where !String.IsNullOrWhiteSpace(value);
249+
unit usd;
250+
union PaymentResult { Approved(txId: string); Declined(reason: string); }
87251
resource Db; resource ArrayPool<T>;
88252
89253
protocol Report {
@@ -95,19 +259,46 @@ protocol Report {
95259
96260
fn CalculateTotal(order: Order) -> Money pure;
97261
fn LoadOrder(id: ProductId) -> Order use Db;
262+
fn Charge(customer: CustomerId, amount: usd) -> PaymentResult use Db;
98263
fn RenderReport(report: Report<Validated>) -> File use !ArrayPool<byte>, !Log;
99264
```
100265

266+
## Future (horizon, not committed)
267+
268+
Distinct from the deferred catalog below: these are things Own.Types plausibly
269+
grows *into*, not type-theory tempo it is refusing.
270+
271+
- **`.own` DSL.** Today's brand/refinement/union/protocol snippets are sketch
272+
syntax inside this proposal, not a ratified grammar. Graduating this pillar
273+
means these constructs get a real entry in `spec/Grammar.md`, with the same
274+
test-pinned discipline as every other DSL construct.
275+
- **F# generator/backend.** F#'s discriminated unions, units of measure, and
276+
records are a structural match for pillars 1–2 — a codegen backend that lowers
277+
`.own` declarations to *idiomatic F#* (real DUs, real `[<Measure>]`) instead of
278+
a C# analyzer shim, for teams that can host an F# core project inside a C#
279+
solution and want the compiler itself enforcing the discipline.
280+
- **Interop analyzers.** Once an F# backend exists, the boundary itself needs
281+
checking: a value crossing from a real F# DU into the C#-side shim
282+
representation must stay branded and exhaustive across the language edge, not
283+
just within one language.
284+
- **Multi-language frontends.** Ties directly to
285+
[P-017](P-017-multi-stack-frontends.md) — Own.Types facts (#1–#13) become one
286+
more fact family the OwnTS/OwnJVM frontends emit over the same OwnIR seam
287+
(#18) the ownership facts already use.
288+
101289
## Non-goals
102290

103291
Refuse the boil-the-ocean version. The first move is explicitly **not** dependent
104292
types, GADTs, or higher-kinded types — that way lies a tower of type-level
105293
arithmetic (башня type-level арифметики) where you wanted to write a function and
106294
end up proving 2 + 2 = 4. The DSL must not become a new general-purpose language;
107295
it stays a spec/model/contract layer. No new runtime, no rewriting the codebase —
108-
brands and refinements lower to plain structs and smart constructors, and the
109-
discipline is enforced by analyzer, not by a parallel type checker that drifts
110-
from the core (the project's standing meta-irony). `[OwnIgnore("reason")]` remains
296+
brands, refinements, and unions lower to plain structs/records and smart
297+
constructors, and the discipline is enforced by analyzer, not by a parallel type
298+
checker that drifts from the core (the project's standing meta-irony).
299+
Algebraic domain modeling (pillar 2) gets the same restraint: exhaustive matching
300+
is enforcement of *existing* C# `switch`/pattern-match syntax, not a new
301+
pattern-matching language grafted on top of it. `[OwnIgnore("reason")]` remains
111302
the escape hatch.
112303

113304
## Deferred catalog
@@ -122,36 +313,51 @@ Surveyed and explicitly **not** first — recorded so the ideas aren't lost:
122313
`Add: Expr<Int> -> Expr<Int> -> Expr<Int>`). Only if a typed AST / DSL /
123314
query-builder need appears — relevant to the Snipper / Reactor / AST-transform
124315
ideas, not before.
125-
- **Phantom types** — already in scope, as the underlying mechanism behind brands.
316+
- **Phantom types** — already in scope, as the underlying mechanism behind
317+
brands (pillar 1, including strongly typed IDs).
126318
- **Higher-kinded types** (abstract over `F<_>`: Functor / Monad). Do not touch:
127319
assembling a spaceship out of `IEnumerable`, `Task`, and pain.
128320
- **Row types** ("an object with at least these fields"), **existential types**
129321
("there is some hidden `T`" — plugin/handler systems, heterogeneous
130-
collections), **intersection `A & B`** / **union `A | B`** types, and
131-
**gradual typing** (strict + dynamic mixed; the risk is `any` spreading until
132-
the type system is a decorative quality sticker).
322+
collections), **intersection `A & B`** / **union `A | B`** types (the
323+
type-theory *union*, distinct from pillar 2's closed-shape `union`
324+
declaration), and **gradual typing** (strict + dynamic mixed; the risk is
325+
`any` spreading until the type system is a decorative quality sticker).
133326
- **Modal types** (`Html<Trusted|Untrusted>`, `Sql<Untrusted|Parameterized>`,
134327
`sanitize: Html<Untrusted> -> Html<Trusted>`) and **indexed types**
135328
(`Buffer<Initialized|Uninitialized>`, `Password<PlainText|Hash>`, pipeline
136329
stages) — both for trust zones, escaping, and lifecycle. These overlap heavily
137330
with branded + typestate, so they may fall out for free once those two land.
138331

139332
Priority, most-applied → academic tail: **branded/opaque · units of measure ·
140-
typestate · refinement · effect types (P-008) · session types · phantom**, then
141-
**dependent / GADT / HKT** as the cognitively expensive end.
333+
typestate · refinement · discriminated unions/exhaustive matching · effect types
334+
(P-008) · session types · phantom**, then **dependent / GADT / HKT** as the
335+
cognitively expensive end.
142336

143337
## Open questions
144338

145339
1. **Surface:** analyzer-only (annotate C# in place) vs `.own` spec + source
146-
generator vs both. Brands and refinements want a generator (smart
147-
constructors); typestate wants the analyzer + the affine core.
340+
generator vs both. Brands, refinements, and unions want a generator (smart
341+
constructors, exhaustive-match helpers); typestate wants the analyzer + the
342+
affine core.
148343
2. **Where do brands live** relative to P-006 capabilities — is a capability just
149344
a branded, non-`Copy` resource token, or its own kind?
150345
3. **Refinement strength:** syntactic predicate enforced at the constructor
151346
boundary (cheap, sound-by-construction) vs flow-checked refinement (needs the
152347
verification backend, P-002). v0 should be the former.
153348
4. **Typestate ↔ ownership seam:** confirm transitions express consume-self
154349
through the *existing* affine facts, so `commit` then `rollback` is reported as
155-
use-after-move by the one core — no second mechanism.
350+
use-after-move by the one core — no second mechanism. Pillar 3's items 10–13
351+
are the concrete test of this seam: each must reduce to it, not spawn a
352+
parallel one.
156353
5. Do **modal/indexed** types ever need their own surface, or are they always
157354
reducible to brand + typestate in practice?
355+
6. **Diagnostic prefix.** `DI`, `EFF`, and `OBL` are established per-pillar
356+
families (see `ownlang/diagnostics.py`). Does Own.Types reserve `TYP0xx` the
357+
same way, or fold into core `OWN` codes with a `[type: …]` kind tag mirroring
358+
the existing `[resource: …]` tag? Reserving `TYP` now avoids repeating the
359+
`WPFxxx`-catalog-vs-emitted-code confusion recorded in
360+
`docs/notes/consolidation-and-positioning.md`.
361+
7. Do discriminated-union exhaustiveness (#6) and `Option`/`Result` unwrap-safety
362+
(#7, #8) stay one analyzer rule family or split into separate rules sharing
363+
only the source-generator scaffolding?

0 commit comments

Comments
 (0)