Skip to content
Navigation Menu
{{ message }}
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTypes.lean
More file actions
391 lines (352 loc) · 14.8 KB
/
Copy pathTypes.lean
File metadata and controls
391 lines (352 loc) · 14.8 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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
import LeanPython.AST.Types
import Std.Data.HashMap
set_option autoImplicit false
namespace LeanPython.Runtime
open LeanPython.AST (Arguments Stmt Expr)
open LeanPython.Lexer (SourceSpan)
-- ============================================================
-- Heap references
-- ============================================================
/-- Opaque heap reference (index into the interpreter heap). -/
abbrev HeapRef := Nat
-- ============================================================
-- Runtime values
-- ============================================================
/-- A Python runtime value. Mutable containers (list, dict, set) use HeapRef
indirection to model Python's reference semantics. -/
inductive Value where
| none
| bool : Bool → Value
| int : Int → Value
| float : Float → Value
| str : String → Value
| bytes : ByteArray → Value
| list : HeapRef → Value
| tuple : Array Value → Value
| dict : HeapRef → Value
| set : HeapRef → Value
| function : HeapRef → Value
| builtin : String → Value
| ellipsis
| boundMethod : Value → String → Value
| exception : String → String → Value
| generator : HeapRef → Value
| coroutine : Value → Value
| classObj : HeapRef → Value
| instance : HeapRef → Value
| superObj : Value → Value → Value
| staticMethod : Value → Value
| classMethod : Value → Value
| property : Value → Option Value → Option Value → Value
| module : HeapRef → Value
instance : Inhabited Value where
default := .none
-- ============================================================
-- Scope
-- ============================================================
/-- A variable scope mapping names to values. -/
abbrev Scope := Std.HashMap String Value
-- ============================================================
-- Function data (stored on the heap)
-- ============================================================
/-- Captured closure: a snapshot of the scope chain at function definition time. -/
abbrev ClosureEnv := Array Scope
/-- Runtime function data stored on the heap. -/
structure FuncData where
name : String
params : Arguments
body : List Stmt
defaults : Array Value
kwDefaults : Array (Option Value)
closure : ClosureEnv
isGenerator : Bool
definingModule : Option String := none
isAsync : Bool := false
-- ============================================================
-- Class and instance data (stored on the heap)
-- ============================================================
/-- Runtime class data stored on the heap. -/
structure ClassData where
name : String
bases : Array Value
mro : Array Value
ns : Std.HashMap String Value
slots : Option (Array String) := none
/-- Runtime instance data stored on the heap.
`wrappedValue` stores the underlying built-in value for subclasses of int/bytes
(e.g., `class Uint64(int, SSZType)` produces instances with `wrappedValue := some (.int n)`). -/
structure InstanceData where
cls : Value
attrs : Std.HashMap String Value
wrappedValue : Option Value := none
/-- Runtime module data stored on the heap. -/
structure ModuleData where
name : String -- __name__
file : Option String -- __file__
package : Option String -- __package__
ns : Std.HashMap String Value -- module namespace
allNames : Option (Array String) -- __all__ if defined
-- ============================================================
-- Heap objects
-- ============================================================
/-- Objects stored on the interpreter heap. -/
inductive HeapObject where
| listObj : Array Value → HeapObject
| dictObj : Array (Value × Value) → HeapObject
| setObj : Array Value → HeapObject
| funcObj : FuncData → HeapObject
| generatorObj : Array Value → Nat → HeapObject
| classObjData : ClassData → HeapObject
| instanceObjData : InstanceData → HeapObject
| moduleObj : ModuleData → HeapObject
-- ============================================================
-- Runtime errors
-- ============================================================
/-- Python-style runtime errors. -/
inductive RuntimeError where
| nameError : String → RuntimeError
| typeError : String → RuntimeError
| valueError : String → RuntimeError
| indexError : String → RuntimeError
| keyError : String → RuntimeError
| zeroDivision : String → RuntimeError
| assertionError : String → RuntimeError
| attributeError : String → RuntimeError
| overflowError : String → RuntimeError
| stopIteration : RuntimeError
| notImplemented : String → RuntimeError
| runtimeError : String → RuntimeError
| importError : String → RuntimeError
| moduleNotFound : String → RuntimeError
| customError : String → String → List String → RuntimeError -- typeName, message, parentTypeNames
deriving Repr
instance : ToString RuntimeError where
toString
| .nameError s => s!"NameError: {s}"
| .typeError s => s!"TypeError: {s}"
| .valueError s => s!"ValueError: {s}"
| .indexError s => s!"IndexError: {s}"
| .keyError s => s!"KeyError: {s}"
| .zeroDivision s => s!"ZeroDivisionError: {s}"
| .assertionError s => s!"AssertionError: {s}"
| .attributeError s => s!"AttributeError: {s}"
| .overflowError s => s!"OverflowError: {s}"
| .stopIteration => "StopIteration"
| .notImplemented s => s!"NotImplementedError: {s}"
| .runtimeError s => s!"RuntimeError: {s}"
| .importError s => s!"ImportError: {s}"
| .moduleNotFound s => s!"ModuleNotFoundError: No module named '{s}'"
| .customError tn msg _ => if msg.isEmpty then tn else s!"{tn}: {msg}"
-- ============================================================
-- BEq Value (needed for dict lookup, == operator, in operator)
-- ============================================================
/-- Structural equality for values. Mutable containers compare by reference
(heap address), matching Python's default `is` semantics for objects.
For `==` semantics, use `valueEq` in Ops.lean which does deep comparison. -/
partial def Value.beq : Value → Value → Bool
| .none, .none => true
| .bool a, .bool b => a == b
| .int a, .int b => a == b
| .float a, .float b => a == b
| .str a, .str b => a == b
| .bytes a, .bytes b => a == b
| .list a, .list b => a == b
| .tuple a, .tuple b => a.size == b.size && (List.range a.size).all fun i =>
match a[i]?, b[i]? with
| some va, some vb => Value.beq va vb
| _, _ => false
| .dict a, .dict b => a == b
| .set a, .set b => a == b
| .function a, .function b => a == b
| .builtin a, .builtin b => a == b
| .ellipsis, .ellipsis => true
| .boundMethod _ _, _ => false
| _, .boundMethod _ _ => false
| .exception a1 a2, .exception b1 b2 => a1 == b1 && a2 == b2
| .generator a, .generator b => a == b
| .coroutine a, .coroutine b => Value.beq a b
| .classObj a, .classObj b => a == b
| .instance a, .instance b => a == b
| .superObj _ _, _ => false
| _, .superObj _ _ => false
| .staticMethod a, .staticMethod b => Value.beq a b
| .classMethod a, .classMethod b => Value.beq a b
| .property a1 _ _, .property b1 _ _ => Value.beq a1 b1
| .staticMethod _, _ => false
| _, .staticMethod _ => false
| .classMethod _, _ => false
| _, .classMethod _ => false
| .property _ _ _, _ => false
| _, .property _ _ _ => false
| .module a, .module b => a == b
| .module _, _ => false
| _, .module _ => false
-- Cross-type: bool/int interop (Python: True == 1, False == 0)
| .bool a, .int b => (if a then 1 else 0) == b
| .int a, .bool b => a == (if b then 1 else 0)
-- int/float comparison
| .int a, .float b => Float.ofInt a == b
| .float a, .int b => a == Float.ofInt b
| .bool a, .float b => Float.ofInt (if a then 1 else 0) == b
| .float a, .bool b => a == Float.ofInt (if b then 1 else 0)
| _, _ => false
instance : BEq Value where
beq := Value.beq
-- ============================================================
-- Value display
-- ============================================================
/-- Convert a Value to its Python `str()` representation. -/
partial def Value.toStr : Value → String
| .none => "None"
| .bool true => "True"
| .bool false => "False"
| .int n => toString n
| .float f =>
let s := toString f
s
| .str s => s
-- str(exception) returns just the message (not the type name)
| .exception _typeName msg => msg
| .bytes _b => "b'...'"
| .list _ => "[...]"
| .tuple elems =>
if elems.size == 1 then
s!"({Value.toStr elems[0]!},)"
else
"(" ++ ", ".intercalate (elems.toList.map Value.toStr) ++ ")"
| .dict _ => "{...}"
| .set _ => "{...}"
| .function _ => "<function>"
| .builtin name => s!"<built-in function {name}>"
| .ellipsis => "Ellipsis"
| .boundMethod _ method => s!"<bound method {method}>"
| .generator _ => "<generator object>"
| .coroutine _ => "<coroutine object>"
| .classObj _ => "<class>"
| .instance _ => "<instance>"
| .superObj _ _ => "<super>"
| .staticMethod _ => "<staticmethod object>"
| .classMethod _ => "<classmethod object>"
| .property _ _ _ => "<property object>"
| .module _ => "<module>"
/-- Convert a Value to its Python `repr()` representation. -/
partial def Value.toRepr : Value → String
| .none => "None"
| .bool true => "True"
| .bool false => "False"
| .int n => toString n
| .float f => toString f
| .str s => s!"'{s}'"
| .bytes _b => "b'...'"
| .list _ => "[...]"
| .tuple elems =>
if elems.size == 1 then
s!"({Value.toRepr elems[0]!},)"
else
"(" ++ ", ".intercalate (elems.toList.map Value.toRepr) ++ ")"
| .dict _ => "{...}"
| .set _ => "{...}"
| .function _ => "<function>"
| .builtin name => s!"<built-in function {name}>"
| .ellipsis => "Ellipsis"
| .boundMethod _ method => s!"<bound method {method}>"
| .exception typeName msg => if msg.isEmpty then typeName else s!"{typeName}('{msg}')"
| .generator _ => "<generator object>"
| .coroutine _ => "<coroutine object>"
| .classObj _ => "<class>"
| .instance _ => "<instance>"
| .superObj _ _ => "<super>"
| .staticMethod _ => "<staticmethod object>"
| .classMethod _ => "<classmethod object>"
| .property _ _ _ => "<property object>"
| .module _ => "<module>"
instance : ToString Value where
toString := Value.toStr
-- ============================================================
-- Exception type name mapping
-- ============================================================
/-- Get the Python exception class name for a RuntimeError. -/
def runtimeErrorTypeName : RuntimeError → String
| .nameError _ => "NameError"
| .typeError _ => "TypeError"
| .valueError _ => "ValueError"
| .indexError _ => "IndexError"
| .keyError _ => "KeyError"
| .zeroDivision _ => "ZeroDivisionError"
| .assertionError _ => "AssertionError"
| .attributeError _ => "AttributeError"
| .overflowError _ => "OverflowError"
| .stopIteration => "StopIteration"
| .notImplemented _ => "NotImplementedError"
| .runtimeError _ => "RuntimeError"
| .importError _ => "ImportError"
| .moduleNotFound _ => "ModuleNotFoundError"
| .customError tn _ _ => tn
/-- Get the message portion of a RuntimeError. -/
def runtimeErrorMessage : RuntimeError → String
| .nameError s | .typeError s | .valueError s | .indexError s
| .keyError s | .zeroDivision s | .assertionError s
| .attributeError s | .overflowError s | .notImplemented s
| .runtimeError s | .importError s | .moduleNotFound s => s
| .stopIteration => ""
| .customError _ msg _ => msg
/-- Check if an exception type matches a handler type, respecting the hierarchy.
`Exception` catches all standard errors, `BaseException` catches everything. -/
def exceptionMatches (errorTypeName handlerTypeName : String) : Bool :=
if handlerTypeName == "BaseException" then true
else if handlerTypeName == "Exception" then
-- Exception catches everything except BaseException-only subtypes
errorTypeName != "SystemExit" && errorTypeName != "KeyboardInterrupt" &&
errorTypeName != "GeneratorExit"
else
errorTypeName == handlerTypeName
/-- Check if a custom exception matches a handler, considering parent type names. -/
def customExceptionMatches (error : RuntimeError) (handlerTypeName : String) : Bool :=
match error with
| .customError tn _ parents =>
if handlerTypeName == "BaseException" || handlerTypeName == "Exception" then true
else tn == handlerTypeName || parents.any (· == handlerTypeName)
| other => exceptionMatches (runtimeErrorTypeName other) handlerTypeName
-- ============================================================
-- Builtin name table
-- ============================================================
/-- Names of all built-in functions recognized by the interpreter. -/
def builtinNames : List String :=
["print", "len", "range", "type", "int", "str", "bool", "float",
"list", "tuple", "set", "dict", "isinstance", "repr", "abs",
"min", "max", "sorted", "reversed", "enumerate", "zip",
"sum", "any", "all", "hash", "id", "input", "ord", "chr",
"hex", "oct", "bin", "round", "pow", "divmod", "map", "filter",
"iter", "next", "hasattr", "getattr", "setattr", "callable",
"issubclass", "super", "object", "bytes", "bytearray",
"memoryview", "frozenset", "complex", "slice",
"staticmethod", "classmethod", "property",
-- Dataclass
"dataclass",
-- Exception classes
"ValueError", "TypeError", "KeyError", "IndexError",
"RuntimeError", "ZeroDivisionError", "AssertionError",
"AttributeError", "OverflowError", "StopIteration",
"NotImplementedError", "Exception", "BaseException",
"NameError", "OSError", "IOError", "FileNotFoundError",
"ImportError", "ModuleNotFoundError", "SystemExit",
"KeyboardInterrupt", "GeneratorExit",
"CancelledError", "TimeoutError"]
/-- Check if a name is a built-in function. -/
def isBuiltinName (name : String) : Bool :=
builtinNames.contains name
/-- Check if a name is a built-in exception class. -/
def isBuiltinExceptionName (name : String) : Bool :=
name == "Exception" || name == "BaseException" ||
name == "ValueError" || name == "TypeError" ||
name == "KeyError" || name == "IndexError" ||
name == "RuntimeError" || name == "ZeroDivisionError" ||
name == "AssertionError" || name == "AttributeError" ||
name == "OverflowError" || name == "StopIteration" ||
name == "NotImplementedError" || name == "NameError" ||
name == "OSError" || name == "IOError" ||
name == "FileNotFoundError" || name == "ImportError" ||
name == "ModuleNotFoundError" || name == "SystemExit" ||
name == "KeyboardInterrupt" || name == "GeneratorExit" ||
name == "CancelledError" || name == "TimeoutError"
end LeanPython.Runtime
You can’t perform that action at this time.
