std:EVM/State/Layout/Derive
lib/EVM/State/Layout/Derive.omg
lib/EVM/State/Layout/Derive.omg443 lines
1let Structure = std:Reflection/Structure
2{- Automatic placement: one policy that produces ordinary candidate data.
3 It does not define validity; explicit placements may use other graphs.
4 A union takes tags 0 to n - 1 in the order of its reflected cases. A
5 record places its unaligned fields next fit in reflected order, then its
6 aligned fields on slot boundaries, then the fields that hold a direct
7 mapping, each at a multiple of its extent rounded up to a power of two.
8 A list packs elements of at most 256 bits. Hashed objects live in the
9 top block of the reservation.
10
11 A mapping in the root object's records whose key has a fixed width of
12 at most `directLimit` bits is direct: an array of whole-slot entries
13 indexed by the key, with no hash. Every other mapping is hashed: one in
14 a list element, a mapping value or a union payload, whose array would
15 multiply the extent of a hashed object or of an overlay that no path
16 reaches (a path selects no union alternative).
17-}
18let Address = std:EVM/State/Layout/Address
19let D = std:EVM/State/Layout/Description
20let L = std:List
21let N = std:Natural
22let O = std:Optional
23let R = std:Region
24let Form = D.Form
25-- A subtree that starts at bit `r` modulo 256 of a slot has the inline
26-- extent `bits r` and the nodes `build r id` from identifier `id`.
27-- `aligned`: it holds an anchored node (a list, blob or mapping) inline.
28-- `lead`: for a union with aligned alternatives, the tag bits before its
29-- payload, which starts at the next slot boundary, so that the union may
30-- start anywhere; every other aligned subtree starts on a slot boundary.
31-- `objects`: the slots of its largest hashed object (keys excluded: they
32-- store nothing). `count`: its number of nodes. `direct`: it is a direct
33-- mapping or a record that holds one.
34let Tree
35 : Type
36 = { bits : Natural -> Natural
37 , aligned : Bool
38 , lead : Optional Natural
39 , objects : Natural
40 , count : Natural
41 , direct : Bool
42 , build : Natural -> Natural -> List D.Node
43 }
44-- A type's subtree in the root object's records (`static`) and anywhere
45-- else (`nested`); they differ only where a mapping can be direct.
46let Trees : Type = { static : Tree, nested : Tree }
47let same : Tree -> Trees = \tree -> { static = tree, nested = tree }
48-- The widest key of a direct mapping: an address.
49let directLimit : Natural = 160
50let Field : Type = { name : Text, tree : Tree }
51let Named : Type = { name : Text, trees : Trees }
52let leaf
53 : Natural -> Bool -> Natural -> D.Form -> Tree
54 = \bits aligned objects form ->
55 { bits = \(_ : Natural) -> bits
56 , aligned
57 , lead = None Natural
58 , objects
59 , count = 1
60 , direct = False
61 , build = \(_ : Natural) (id : Natural) -> [ { id, bits, form } ]
62 }
63let scalar
64 : D.Scalar -> Natural -> Trees
65 = \kind bits -> same (leaf bits False 0 (Form.Primitive kind))
66let blob : D.Scalar -> Trees = \kind -> same (leaf 256 True Address.blobSlots (Form.Blob kind))
67let anyAligned : List Field -> Bool = L.any (\(field : Field) -> field.tree.aligned)
68let largest
69 : List Field -> Natural
70 = L.fold (\(field : Field) (n : Natural) -> N.max field.tree.objects n) 0
71let nodeCount
72 : List Field -> Natural
73 = L.fold (\(field : Field) (n : Natural) -> field.tree.count + n) 1
74-- The start of a field of `bits` bits at bit `offset`: there if it fits in
75-- the rest of the slot, else at the next slot boundary. A field wider than
76-- a slot therefore starts on a boundary.
77let nextFit
78 : Natural -> Natural -> Natural
79 = \offset bits ->
80 let r = Natural/mod offset 256
81 in offset + (if N.lessThanEqual (r + N.min bits 256) 256 then 0 else N.minus 256 r)
82{- A record places its fields in four passes, each in reflected order:
83 (0) unaligned fields next fit; (1) unions with a lead, whose tag goes next
84 fit; (2) the other aligned fields on slot boundaries, but (3) those that
85 hold a direct mapping, each at a multiple of its extent rounded up to a
86 power of two, whose literal is short. Each pass records a start for
87 every field and moves its cursor only for its own fields.
88
89 The passes are written so that each step reads the cursor a bounded
90 number of times and never in both branches of a condition on a field.
91 Generic library code compares derivations of unknown types; conversion
92 expands the shared cursor once per read, so a step that read it in both
93 branches would make that comparison exponential in the number of fields
94 of a pair or an optional.
95-}
96let Pass : Type = { end : Natural, starts : List Natural }
97let loosePass
98 : List Field -> Pass
99 = L.foldLeft
100 (\(acc : Pass) (field : Field) ->
101 let bits = if field.tree.aligned then 0 else field.tree.bits 0
102 let at = nextFit acc.end bits
103 in { end = at + bits, starts = acc.starts # [ at ] })
104 { end = 0, starts = ([] : List Natural) }
105let leadPass
106 : Natural -> List Field -> Pass
107 = \offset ->
108 L.foldLeft
109 (\(acc : Pass) (field : Field) ->
110 let at = nextFit acc.end (O.default 0 field.tree.lead)
111 in { end =
112 if field.tree.aligned && O.isSome field.tree.lead
113 then at + field.tree.bits (Natural/mod at 256)
114 else acc.end
115 , starts = acc.starts # [ at ]
116 })
117 { end = offset, starts = ([] : List Natural) }
118let slotPass
119 : Natural -> List Field -> Pass
120 = \offset ->
121 L.foldLeft
122 (\(acc : Pass) (field : Field) ->
123 let at = Address.alignUp acc.end
124 in { end =
125 at
126 + (if field.tree.aligned
127 && O.isNone field.tree.lead
128 && (if field.tree.direct then False else True)
129 then field.tree.bits 0
130 else 0)
131 , starts = acc.starts # [ at ]
132 })
133 { end = offset, starts = ([] : List Natural) }
134let directPass
135 : Natural -> List Field -> Pass
136 = \offset ->
137 L.foldLeft
138 (\(acc : Pass) (field : Field) ->
139 let bits = if field.tree.direct then field.tree.bits 0 else 0
140 let step = N.pow2 (Address.extentBits (Address.slotsOf bits))
141 let at = 256 * (step * Natural/div (Address.slotsOf acc.end + N.minus step 1) step)
142 in { end = at + bits, starts = acc.starts # [ at ] })
143 { end = offset, starts = ([] : List Natural) }
144let Placed : Type = { name : Text, tree : Tree, offset : Natural }
145let Starts : Type = { loose : Natural, led : Natural, slotted : Natural, directed : Natural }
146let record
147 : List Field -> Tree
148 = \fields ->
149 let loose = loosePass fields
150 let led = leadPass loose.end fields
151 let slotted = slotPass led.end fields
152 let directed = directPass slotted.end fields
153 let direct = L.any (\(field : Field) -> field.tree.direct) fields
154 let bits =
155 if direct
156 then directed.end
157 else if L.any
158 (\(field : Field) -> field.tree.aligned && O.isNone field.tree.lead)
159 fields
160 then slotted.end
161 else led.end
162 let placed =
163 L.zipWith
164 (\(field : Field) (starts : Starts) ->
165 { name = field.name
166 , tree = field.tree
167 , offset =
168 if field.tree.direct
169 then starts.directed
170 else if field.tree.aligned
171 then O.fold (\(_ : Natural) -> starts.led) starts.slotted field.tree.lead
172 else starts.loose
173 })
174 fields
175 (L.zipWith
176 (\(first : { loose : Natural, led : Natural, slotted : Natural })
177 (directed : Natural) ->
178 { loose = first.loose, led = first.led, slotted = first.slotted, directed })
179 (L.zipWith
180 (\(first : { loose : Natural, led : Natural }) (slotted : Natural) ->
181 { loose = first.loose, led = first.led, slotted })
182 (L.zipWith (\(loose led : Natural) -> { loose, led }) loose.starts led.starts)
183 slotted.starts)
184 directed.starts)
185 in { bits = \(_ : Natural) -> bits
186 , aligned = anyAligned fields
187 , lead = None Natural
188 , objects = largest fields
189 , count = nodeCount fields
190 , direct
191 , build =
192 \(_ : Natural) (id : Natural) ->
193 let members =
194 L.foldLeft
195 (\(acc : { next : Natural, members : List D.Member, nodes : List D.Node })
196 (field : Placed) ->
197 { next = acc.next + field.tree.count
198 , members =
199 acc.members
200 # [ { name = field.name, offset = field.offset, child = acc.next }
201 ]
202 , nodes =
203 acc.nodes
204 # field.tree.build (Natural/mod field.offset 256) acc.next
205 })
206 { next = id + 1
207 , members = ([] : List D.Member)
208 , nodes = ([] : List D.Node)
209 }
210 placed
211 in [ { id, bits, form = Form.Fields members.members } ] # members.nodes
212 }
213-- A union whose alternatives are aligned starts its payload at the next
214-- slot boundary after its tag; the others follow the tag directly.
215let union
216 : List Field -> Tree
217 = \fields ->
218 let width = N.bitLength (N.minus (L.length fields) 1)
219 let aligned = anyAligned fields
220 let widest = L.fold (\(field : Field) (n : Natural) -> N.max (field.tree.bits 0) n) 0 fields
221 let payload =
222 \(r : Natural) -> if aligned then N.minus (Address.alignUp (r + width)) r else width
223 in { bits = \(r : Natural) -> payload r + widest
224 , aligned
225 , lead = if aligned then Some width else None Natural
226 , objects = largest fields
227 , count = nodeCount fields
228 , direct = False
229 , build =
230 \(r : Natural) (id : Natural) ->
231 let alternatives =
232 L.foldLeft
233 (\(acc :
234 { next : Natural
235 , tag : Natural
236 , alternatives : List D.Alternative
237 , nodes : List D.Node
238 })
239 (field : Field) ->
240 { next = acc.next + field.tree.count
241 , tag = acc.tag + 1
242 , alternatives =
243 acc.alternatives
244 # [ { name = field.name, tag = acc.tag, child = acc.next } ]
245 , nodes = acc.nodes # field.tree.build 0 acc.next
246 })
247 { next = id + 1
248 , tag = 0
249 , alternatives = ([] : List D.Alternative)
250 , nodes = ([] : List D.Node)
251 }
252 fields
253 in [ { id
254 , bits = payload r + widest
255 , form =
256 Form.Choice
257 { width
258 , payload = payload r
259 , alternatives = alternatives.alternatives
260 }
261 }
262 ]
263 # alternatives.nodes
264 }
265-- A list element of at most 256 bits packs; a wider or aligned one takes
266-- whole slots.
267let stride
268 : Tree -> Natural
269 = \element ->
270 let bits = element.bits 0
271 in if element.aligned || N.lessThan 256 bits then Address.alignUp bits else bits
272let list
273 : Tree -> Tree
274 = \element ->
275 let step = stride element
276 in { bits = \(_ : Natural) -> 256
277 , aligned = True
278 , lead = None Natural
279 , objects = N.max element.objects (Address.listSlots step)
280 , count = 1 + element.count
281 , direct = False
282 , build =
283 \(_ : Natural) (id : Natural) ->
284 [ { id, bits = 256, form = Form.List { element = id + 1, stride = step } } ]
285 # element.build 0 (id + 1)
286 }
287-- The nodes of a mapping of `bits` bits, its key's and its value's.
288let mapping
289 : Natural -> D.Addressing -> Tree -> Tree -> Natural -> Natural -> List D.Node
290 = \bits addressing key value _ id ->
291 [ { id
292 , bits
293 , form = Form.Dictionary { key = id + 1, value = id + 1 + key.count, addressing }
294 }
295 ]
296 # key.build 0 (id + 1)
297 # value.build 0 (id + 1 + key.count)
298-- A mapping whose entries are objects at hashes of their keys.
299let hashed
300 : Tree -> Tree -> Tree
301 = \key value ->
302 { bits = \(_ : Natural) -> 256
303 , aligned = True
304 , lead = None Natural
305 , objects = N.max value.objects (Address.slotsOf (value.bits 0))
306 , count = 1 + key.count + value.count
307 , direct = False
308 , build = mapping 256 D.Addressing.Hashed key value
309 }
310-- A mapping laid out as an array of whole-slot entries, one for every
311-- encoding of its key, so that a write of a value of at most a slot
312-- stores without a load.
313let array
314 : Tree -> Tree -> Tree
315 = \key value ->
316 let step = Address.alignUp (value.bits 0)
317 let bits = Address.directBits (key.bits 0) step
318 in { bits = \(_ : Natural) -> bits
319 , aligned = True
320 , lead = None Natural
321 , objects = value.objects
322 , count = 1 + key.count + value.count
323 , direct = True
324 , build = mapping bits (D.Addressing.Direct step) key value
325 }
326let statics
327 : List Named -> List Field
328 = L.map (\(named : Named) -> { name = named.name, tree = named.trees.static })
329let nesteds
330 : List Named -> List Field
331 = L.map (\(named : Named) -> { name = named.name, tree = named.trees.nested })
332let records
333 : List Named -> Trees
334 = \named -> { static = record (statics named), nested = record (nesteds named) }
335let unions : List Named -> Trees = \named -> same (union (nesteds named))
336-- The algebra is one top-level value: two derivations of the same unknown
337-- type then pass the same algebra to the reflected fold, which conversion
338-- accepts by sharing instead of comparing every case.
339let algebra
340 : Structure.FamilyAlgebra {} (\(_ : {} -> Type) -> Trees) {}
341 = Structure.algebra
342 {=}
343 (\(_ : Type) -> Trees)
344 { leaf = {=}
345 , bool = scalar D.Scalar.Boolean 1
346 , word = \bits -> scalar (D.Scalar.Unsigned bits) bits
347 , text = blob D.Scalar.String
348 , natural = blob D.Scalar.NaturalNumber
349 , integer = blob D.Scalar.IntegerNumber
350 , double = same (leaf 0 False 0 (Form.Unsupported "Double has no storage representation"))
351 , function =
352 \A B argument result ->
353 let key = argument.nested
354 let entries = hashed key result.nested
355 in { static =
356 if key.aligned || N.lessThan directLimit (key.bits 0)
357 then entries
358 else array key result.nested
359 , nested = entries
360 }
361 , list = \A child -> same (list child.nested)
362 , optional =
363 \A child ->
364 unions
365 [ { name = "None", trees = same (record []) }, { name = "Some", trees = child } ]
366 , pair =
367 \A B first second ->
368 records [ { name = "1", trees = first }, { name = "2", trees = second } ]
369 , record =
370 \A build fields ->
371 records
372 (fields
373 (List Named)
374 (\B name position child project rest -> rest # [ { name, trees = child } ])
375 [])
376 , union =
377 \A cases fold ->
378 unions
379 (cases
380 (List Named)
381 (\B name position child inject rest -> rest # [ { name, trees = child } ])
382 [])
383 }
384let tree
385 : forall {A : Type} -> D.Of A -> Tree
386 = \{A} source -> (source.fold (\(_ : {} -> Type) -> Trees) algebra).static
387-- The top block of a reservation of `size` slots whose root object takes
388-- `rootSlots`: the largest power of two that fits above the root. When
389-- nothing fits, or the block is too small for the layout's objects, the
390-- result is invalid and validity says so.
391let confine
392 : Natural -> Natural -> D.Hashing
393 = \size rootSlots ->
394 let bits = N.log2Floor (N.minus size rootSlots)
395 in D.Hashing.Confined { start = N.minus size (N.pow2 bits), bits }
396let automatic
397 : forall {A : Type} -> D.Of A -> D.Description
398 = \{A} source ->
399 let layout = tree source
400 let size = N.pow2 256
401 in { version = D.version
402 , root = 0
403 , nodes = layout.build 0 0
404 , space = { start = 0, size }
405 , hashing =
406 if N.isZero layout.objects
407 then D.Hashing.Absent
408 else confine size (Address.slotsOf (layout.bits 0))
409 }
410-- The description in another reservation. Blocks are relative to the
411-- reservation's start, so only its size matters: the hashing policy stays
412-- if it still holds there, and is otherwise the top block.
413let relocate
414 : R.Region -> D.Description -> D.Description
415 = \space description ->
416 let rootSlots = Address.rootSlots description
417 let kept =
418 L.null
419 (Address.hashingProblems
420 space
421 rootSlots
422 (Address.objectSlots description.nodes)
423 description.hashing)
424 let moved = if kept then description.hashing else confine space.size rootSlots
425 in description
426 // { space
427 , hashing =
428 merge
429 { Absent = D.Hashing.Absent
430 , Confined = \(_ : { start : Natural, bits : Natural }) -> moved
431 , Solidity = moved
432 }
433 description.hashing
434 }
435-- The least reservation that holds the root object and a block of the
436-- required bits; `relocate` places the block right after the root.
437let reservationSize
438 : D.Description -> Natural
439 = \description ->
440 let objects = Address.objectSlots description.nodes
441 in Address.rootSlots description
442 + (if N.isZero objects then 0 else N.pow2 (Address.extentBits objects + D.margin))
443in { automatic, confine, relocate, reservationSize }