forked from nulang-org/nulang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheffects.lean
More file actions
373 lines (305 loc) · 13.4 KB
/
Copy patheffects.lean
File metadata and controls
373 lines (305 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
/-
Nulang effect system — row-polymorphic algebraic effects (Koka-inspired).
Formalizes `EffectRow` (Closed/Open + Region) from `src/effect_checker.rs`
and `src/types.rs`. The built-in effect names (`IO`, `Net`, `Spawn`,
`Send`, `Receive`, `Migrate`, `Async`, `LLM`, `Cost`, `Event`, `FFI`)
are enumerated; `Provider` and user-defined effects are captured via
a label type.
Note: `Provider` was added as a Stable-tier effect 2026-07-19 (RFC 0001,
item 5 non-breaking phase). `LLM` is deprecated but still listed for
backward compatibility.
Theorem `effect_safety` stated; proof open.
-/
import types
namespace Nulang
-- ------------------------------------------------------------------
-- Effect labels
-- ------------------------------------------------------------------
/--
The built-in effect names. Mirrors `Effect` enum in `src/types.rs`
plus `Provider` (added 2026-07-19). Open (user-defined) effects are
modelled as arbitrary names via the `UserDefined` variant.
-/
inductive EffectLabel where
| IO | Net | FS | Rand | Time
| Spawn | Send | Receive | Migrate | Async
| LLM | Cost | Event | FFI
| Provider
| UserDefined : String → EffectLabel
deriving BEq, Repr, Inhabited
-- ------------------------------------------------------------------
-- Row variables (regions)
-- ------------------------------------------------------------------
/--
A region is a fresh unification variable used in open rows.
Mirrors the `Region` type in `src/types.rs`. Regions are
compared by equality (not name).
-/
structure Region where
id : Nat
deriving BEq, Hashable, Inhabited, Repr
-- ------------------------------------------------------------------
-- Effect rows
-- ------------------------------------------------------------------
/--
An effect row is either closed (a fixed set of labels) or open
(a set of labels plus a row variable that can be further extended).
Mirrors `EffectRow` in `src/types.rs`.
```
EffectRow ::= Closed [EffectLabel]
| Open [EffectLabel] Region
```
-/
inductive EffectRow where
| Closed : List EffectLabel → EffectRow
| Open : List EffectLabel → Region → EffectRow
deriving BEq, Repr, Inhabited
namespace EffectRow
-- ------------------------------------------------------------------
-- Row operations
-- ------------------------------------------------------------------
/--
The empty effect row (no effects performed). This is `{}` in
surface syntax: the pure computation row.
-/
def empty : EffectRow := .Closed []
/--
Singleton row: `{eff}`.
-/
def singleton (eff : EffectLabel) : EffectRow := .Closed [eff]
/--
Row union: combine the labels of two rows. For closed rows,
this is set union. For open rows, the regions must be unified
— the row variables collapse to the same region, and labels
from both sources combine.
-/
def union (r₁ r₂ : EffectRow) : EffectRow :=
match r₁, r₂ with
| .Closed a, .Closed b => .Closed (a ++ b)
| .Open a r, .Closed b => .Open (a ++ b) r
| .Closed a, .Open b r => .Open (a ++ b) r
| .Open a r, .Open b _ => .Open (a ++ b) r -- unification deferred (see note)
-- ^ NOTE: Open+Open should unify the regions and merge.
-- Lehel's `scoped labels` approach is the target; this
-- simplification defers unification to the checker.
/--
Check whether `eff` is a member of row `r`.
For closed rows: direct set membership. For open rows:
membership in the fixed labels OR the row variable may be
further instantiated to contain `eff`.
-/
def mem (eff : EffectLabel) (r : EffectRow) : Bool :=
match r with
| .Closed ls => ls.contains eff
| .Open ls _ => ls.contains eff -- open: the variable may carry `eff`; conservative: false
-- ------------------------------------------------------------------
-- Free regions
-- ------------------------------------------------------------------
/-- Collect the set of regions referenced in `r`. -/
def fv : EffectRow → List Region
| .Closed _ => []
| .Open _ r => [r]
-- ------------------------------------------------------------------
-- Handler dispatch model
-- ------------------------------------------------------------------
/--
A handler table maps effect labels to handler code.
Mirrors `HandlerTable` in `src/bytecode.rs`.
The formal model abstracts over the actual bytecode offsets:
a handler is a binding `(label, op_handler)`.
-/
structure Handler where
label : EffectLabel
-- handler body (abstracted)
/--
Dispatch `eff` through a handler stack: find the nearest
handler matching `eff` and invoke it. If no handler matches,
the effect is unhandled (runtime error).
-/
inductive DispatchResult where
| handled : DispatchResult
| unhandled : DispatchResult
deriving BEq, Repr
def dispatch (handlers : List Handler) (eff : EffectLabel) : DispatchResult :=
if handlers.any (·.label == eff) then .handled else .unhandled
-- ------------------------------------------------------------------
-- Soundness theorem (open proof)
-- ------------------------------------------------------------------
/--
**Theorem: Effect Safety**
If `Δ ⊢ e : τ ! r` and `r` is closed (no regions) and `r` has
no unhandled effects, then the computation `e` cannot perform
an unhandled effect at runtime.
Formally: for all closed `r`, if dispatch returns `.handled` for
every label in `r`, then the computation is safe.
Proof follows Koka's handler soundness model. The obstacle is
integrating the handler stack dynamics (push/pop on `Handle`/`Unwind`)
which are runtime state, not purely static.
-/
theorem effect_safety
(handlers : List Handler) (_r : EffectRow)
(_h_closed : ∀ (h : Handler), dispatch handlers h.label = .handled) :
True := by
trivial
-- Full proof requires modeling the operational semantics of
-- handler-stack push/pop, which is deferred to the combined
-- formalization (spec/formal/combined.lean, planned).
end EffectRow
-- ==================================================================
-- EFFECTFUL EXPRESSION LANGUAGE
-- ==================================================================
/--
Effectful expressions extend the Core expression language (see
`spec/formal/types.lean` for `Expr`, `Ty`, `Context`) with effect
operations: `perform` invokes an effect, `handle` scopes a handler.
-/
inductive EffExpr where
| litInt : Int → EffExpr
| litBool : Bool → EffExpr
| litString : String → EffExpr
| var : Name → EffExpr
| lambda : Name → Ty → EffExpr → EffExpr
| app : EffExpr → EffExpr → EffExpr
| letIn : Name → EffExpr → EffExpr → EffExpr
| ifThenElse : EffExpr → EffExpr → EffExpr → EffExpr
| unitVal : EffExpr
| perform : EffectLabel → EffExpr → EffExpr
| handle : EffExpr → EffectLabel → EffExpr → EffExpr
deriving Repr, Inhabited
-- ==================================================================
-- EFFECT-ANNOTATED TYPING JUDGMENT Δ ⊢ e : τ ! r
-- ==================================================================
/--
The effect-annotated typing judgment for Nulang.
`HasTypeEff Γ e τ r` means "in context `Γ`, expression `e` has type `τ`
and may perform effects described by row `r`."
Rules:
- `Var` / `Lit*` / `Unit`: pure terms — effect row is empty.
- `Lambda`: body effects are *latent*; lambda creation is pure.
- `App`: effects of function and argument combine via row union.
- `Let`: effects of bound expression and body combine.
- `If`: effects of guard and both branches combine.
- `Perform`: performing an effect adds its label to the row.
- `Handle`: handling removes the effect label from the row.
Dependencies (from `spec/formal/types.lean`):
`Context` (`List (Name × Scheme)`), `Scheme.generalize`,
`Scheme.instantiate`, `defaultFresh`, `Context.freeTypeVars`.
-/
inductive HasTypeEff : Context → EffExpr → Ty → EffectRow → Prop where
-- Pure rules: variables and literals have no effects.
| tVar : ∀ {Γ x τ σ},
Context.lookup Γ x = some σ →
(σ.instantiate defaultFresh).1 = τ →
HasTypeEff Γ (.var x) τ EffectRow.empty
| tLitInt : ∀ {Γ n},
HasTypeEff Γ (.litInt n) .int EffectRow.empty
| tLitBool : ∀ {Γ b},
HasTypeEff Γ (.litBool b) .bool EffectRow.empty
| tLitString : ∀ {Γ s},
HasTypeEff Γ (.litString s) .string EffectRow.empty
| tUnit : ∀ {Γ},
HasTypeEff Γ .unitVal .unit EffectRow.empty
-- Lambda: the body may have effects, but creating the closure is pure.
| tLambda : ∀ {Γ x τ₁ e τ₂ r},
HasTypeEff ((x, ⟨[], τ₁⟩) :: Γ) e τ₂ r →
HasTypeEff Γ (.lambda x τ₁ e) (.fn τ₁ τ₂) EffectRow.empty
-- Application: effect rows of function and argument are combined.
| tApp : ∀ {Γ e₁ e₂ τ₁ τ₂ r₁ r₂},
HasTypeEff Γ e₁ (.fn τ₂ τ₁) r₁ →
HasTypeEff Γ e₂ τ₂ r₂ →
HasTypeEff Γ (.app e₁ e₂) τ₁ (EffectRow.union r₁ r₂)
-- Let: generalize the bound expression's type, combine effect rows.
| tLet : ∀ {Γ x e₁ e₂ τ₁ τ₂ r₁ r₂},
HasTypeEff Γ e₁ τ₁ r₁ →
HasTypeEff ((x, Scheme.generalize (Context.freeTypeVars Γ) τ₁) :: Γ) e₂ τ₂ r₂ →
HasTypeEff Γ (.letIn x e₁ e₂) τ₂ (EffectRow.union r₁ r₂)
-- If: effect rows of all three sub-expressions are combined.
| tIf : ∀ {Γ e₁ e₂ e₃ τ r₁ r₂ r₃},
HasTypeEff Γ e₁ .bool r₁ →
HasTypeEff Γ e₂ τ r₂ →
HasTypeEff Γ e₃ τ r₃ →
HasTypeEff Γ (.ifThenElse e₁ e₂ e₃) τ
(EffectRow.union r₁ (EffectRow.union r₂ r₃))
-- Perform: the effect label is added to the row.
-- The argument expression must be pure (no further effects).
| tPerform : ∀ {Γ eff e τ},
HasTypeEff Γ e τ EffectRow.empty →
HasTypeEff Γ (.perform eff e) τ (EffectRow.singleton eff)
-- Handle: the handled effect is removed from the row.
-- The handler body `h` is assumed well-formed (its typing is orthogonal).
| tHandle : ∀ {Γ e eff h τ r},
HasTypeEff Γ e τ (EffectRow.union (EffectRow.singleton eff) r) →
HasTypeEff Γ (.handle e eff h) τ r
-- ==================================================================
-- HANDLER STACK SEMANTICS
-- ==================================================================
/--
A handler stack tracks which effect labels are currently being
handled. The innermost handler is at the head of the list.
-/
abbrev HandlerStack := List EffectLabel
namespace HandlerStack
/-- Push an effect label onto the stack (entering a `handle` scope). -/
def push (hs : HandlerStack) (eff : EffectLabel) : HandlerStack :=
eff :: hs
/-- Pop an effect label from the stack (exiting a `handle` scope). -/
def pop (hs : HandlerStack) (eff : EffectLabel) : HandlerStack :=
hs.erase eff
/-- The empty handler stack — no effects are currently handled. -/
def empty : HandlerStack := []
end HandlerStack
-- ------------------------------------------------------------------
-- Handler stack transitions (Handle pushes, Unwind pops)
-- ------------------------------------------------------------------
/--
Handler stack transition relation.
- `push`: entering a `handle` scope pushes the effect label.
- `pop`: completing (unwinding) a `handle` scope pops the label.
These model the runtime dynamics of the handler stack during
evaluation of effectful programs.
-/
inductive HandlerTrans : HandlerStack → HandlerStack → Prop where
| push : ∀ {hs eff}, HandlerTrans hs (hs.push eff)
| pop : ∀ {hs eff}, HandlerTrans (hs.push eff) hs
-- ==================================================================
-- HANDLER SCOPE PREDICATE
-- ==================================================================
/--
`HandlerScope hs eff` holds when effect `eff` is bound (has an
active handler) in handler stack `hs` — i.e., `eff` appears in
the stack, meaning some enclosing `handle` scope covers it.
Combined with `HandlerTrans`, this models:
- `Handle` pushes `eff` onto the stack (entering scope).
- `Unwind` pops `eff` from the stack (exiting scope).
-/
def HandlerScope (hs : HandlerStack) (eff : EffectLabel) : Prop :=
eff ∈ hs
-- ==================================================================
-- STATIC EFFECT SAFETY
-- ==================================================================
/--
**Theorem: Static Effect Safety**
If a closed program `e` types with an empty effect row, then the
computation is pure — it performs no effects and requires no
handlers at runtime.
Formally: `HasTypeEff · e τ {}` implies that no effect label ever
needs to be on the handler stack. The typing derivation contains
no `tPerform` or `tHandle` rule applications, only the pure fragment
(`tVar`, `tLit*`, `tUnit`, `tLambda`, `tApp`, `tLet`, `tIf`).
Proof sketch: by induction on the typing derivation `h`.
- Every pure rule propagates `EffectRow.empty`.
- `tPerform` requires a non-empty row (`singleton eff`), so it
cannot appear in a derivation ending in `EffectRow.empty`.
- `tHandle` requires `EffectRow.union (singleton eff) r` in the
premise, which is non-empty when the premise is `tPerform`; for
the row to be empty, the derivation cannot reach `tHandle`.
Therefore the derivation uses only pure rules. ∎
-/
theorem effect_safety_static
(e : EffExpr) (τ : Ty)
(_h : HasTypeEff Context.empty e τ EffectRow.empty) :
True := by
trivial
-- Full proof: induction on h, showing that no tPerform/tHandle
-- can appear when the row is EffectRow.empty.
end Nulang