std:EVM/Native/Codec

lib/EVM/Native/Codec.omg

lib/EVM/Native/Codec.omg357 lines
1-- Native structural boundary codecs. Fixed bits are packed MSB first,
2-- fields/alternatives use canonical label order, and final padding is zero.
3-- The compiler rejects descriptions listed in `problems` before lowering.
4let N = std:Natural
5let L = std:List
6let S = std:EVM/Signature
7let Runtime = std:EVM/Runtime
8let Solidity = std:EVM/Solidity
9let Word256 = Word 256
10let lit = Word/fromNatural 256
11let Of = \(A : Type) -> Reflect {=} (\(_ : {}) -> A)
12let Writer = { chunks : List Runtime.Piece, word : Word256, used : Natural }
13let empty : Writer = { chunks = [], word = lit 0, used = 0 }
14
15let finish =
16      \(s : Writer) ->
17        s.chunks
18        # (if Natural/isZero s.used
19           then []
20           else [ Runtime.Piece.Raw { size = N.div (s.used + 7) 8, word = s.word } ])
21
22-- A bit position in the input: a byte offset, a run-time value after a
23-- Text, and the bits after it, which staging always knows since every
24-- variable-width part ends on a byte.
25let Cursor = { byte : Natural, bit : Natural }
26
27let advance
28    : Cursor -> Natural -> Cursor
29    = \(at : Cursor) (bits : Natural) ->
30        { byte = at.byte + N.div (at.bit + bits) 8, bit = N.mod (at.bit + bits) 8 }
31
32let bitOffset : Cursor -> Natural = \(at : Cursor) -> at.byte * 8 + at.bit
33
34-- Each step loads the word at the byte of the cursor and takes as many bits
35-- as it holds after the cursor: a field of at most 256 bits that fits in
36-- that word is one load and one shift, and a mask when it starts inside a
37-- byte. The bits in the byte are static, so the steps are too.
38let readBits
39    : forall (Code : Type)
40      -> S.Ops Word256 Bool Code
41      -> forall (bits : Natural)
42      -> Cursor
43      -> Word bits
44    = \(Code : Type) (o : S.Ops Word256 Bool Code) (bits : Natural) (start : Cursor) ->
45        let Acc = { value : Word bits, at : Natural, left : Natural }
46        let step =
47              \(s : Acc) ->
48                let used = N.mod s.at 8
49                let count = N.min (N.minus 256 used) s.left
50                let address = lit (start.byte + N.div s.at 8)
51                let loaded = Word/shr (N.minus 256 (used + count)) (o.cdload address)
52                let word =
53                      if Natural/isZero used
54                      then loaded
55                      else Word/and loaded (lit (N.minus (N.pow2 count) 1))
56                in  { value =
57                        Word/or
58                          (Word/shl count s.value)
59                          (Word/fromNatural bits (Word/toNatural word))
60                    , at = s.at + count
61                    , left = N.minus s.left count
62                    }
63        let steps =
64              if Natural/isZero bits
65              then 0
66              else N.div (start.bit + bits + 255) 256
67        in  (N.fold
68               steps
69               step
70               { value = Word/fromNatural bits 0, at = start.bit, left = bits }).value
71
72let writeSmall =
73      \(count : Natural) (value : Word256) (s : Writer) ->
74        let room = N.minus 256 s.used
75        let first = N.min room count
76        let rest = N.minus count first
77        let word = Word/or s.word (Word/shl (N.minus room first) (Word/shr rest value))
78        in  if N.equal (s.used + first) 256
79            then { chunks = s.chunks # [ Runtime.Piece.Raw { size = 32, word } ]
80                 , word = Word/shl (N.minus 256 rest) value
81                 , used = rest
82                 }
83            else { chunks = s.chunks, word, used = s.used + first }
84
85-- A word of at most 256 bits is one step; a wider one is split into words.
86let writeBits =
87      \(bits : Natural) (value : Word bits) (writer : Writer) ->
88        let Acc = { writer : Writer, left : Natural }
89        let step =
90              \(s : Acc) ->
91                let count = N.min 256 s.left
92                let rest = N.minus s.left count
93                let part =
94                      Word/and
95                        (lit (Word/toNatural (Word/shr rest value)))
96                        (lit (N.minus (N.pow2 count) 1))
97                in  { writer = writeSmall count part s.writer, left = rest }
98        in  (N.fold (N.div (bits + 255) 256) step { writer, left = bits }).writer
99
100let Codec =
101      \(Code A : Type) ->
102        { read : Cursor -> (A -> Cursor -> Code) -> Code
103        , write : A -> Writer -> (Writer -> Code) -> Code
104        }
105
106let codec
107    : forall {A : Solidity.Families -> Type}
108             (d : Reflect Solidity.types A)
109             (Code : Type)
110             (runtime : Runtime.Ops Code)
111      -> Codec Code (A Solidity.values)
112    = \{A} d Code runtime ->
113        let o = runtime.evm
114        let fail = o.revert ([] : List (S.Chunk Word256))
115        let unsupported =
116              \(T : Type) -> ({ read = \_ _ -> fail, write = \_ _ _ -> fail } : Codec Code T)
117        let wordCodec
118            : forall (bits : Natural) -> Codec Code (Word bits)
119            = \bits ->
120                { read = \at next -> next (readBits Code o bits at) (advance at bits)
121                , write = \value writer next -> next (writeBits bits value writer)
122                }
123        let Reader = \(T : Type) -> Cursor -> (T -> Cursor -> Code) -> Code
124        let readerMonad
125            : std:Monad.Monad Reader
126            = { pure = \{T} value offset next -> next value offset
127              , bind =
128                  \{T} {U} action after offset next ->
129                    action offset (\value at -> after value at next)
130              }
131        in  Solidity.interpret
132              d
133              Solidity.values
134              (Codec Code)
135              { leaf =
136                  { word = \kind -> wordCodec (Solidity.wordBits kind)
137                  , bytes = \_ -> unsupported (List (Word 8))
138                  , indexed = \key -> unsupported key.1
139                  , anonymous = \key -> unsupported key.1
140                  }
141              , function = \A B argument result -> unsupported (A -> B)
142              , bool =
143                  { read =
144                      \at next ->
145                        next
146                          (Word/equal (readBits Code o 1 at) (Word/fromNatural 1 1))
147                          (advance at 1)
148                  , write =
149                      \value writer next ->
150                        next (writeSmall 1 (if value then lit 1 else lit 0) writer)
151                  }
152              , word = wordCodec
153              , natural = unsupported Natural
154              , integer = unsupported Integer
155              , double = unsupported Double
156              , text =
157                  { read =
158                      \at next ->
159                        o.branch
160                          (N.lessThan (bitOffset at) (N.pow2 256))
161                          (runtime.readText
162                             (lit (bitOffset at))
163                             (\text end ->
164                                next text { byte = N.div (Word/toNatural end) 8, bit = 0 }))
165                          fail
166                  , write =
167                      \value writer next ->
168                        next
169                          { chunks = finish writer # [ Runtime.Piece.Text value ]
170                          , word = lit 0
171                          , used = 0
172                          }
173                  }
174              , list = \T child -> unsupported (List T)
175              , optional =
176                  \T child ->
177                    { read =
178                        \offset next ->
179                          o.branch
180                            (Word/isZero (readBits Code o 1 offset))
181                            (next (None T) (advance offset 1))
182                            (child.read (advance offset 1) (\value at -> next (Some value) at))
183                    , write =
184                        \value writer next ->
185                          std:Optional.fold
186                            (\x -> child.write x (writeSmall 1 (lit 1) writer) next)
187                            (next (writeSmall 1 (lit 0) writer))
188                            value
189                    }
190              , pair =
191                  \T U first second ->
192                    { read =
193                        \offset next ->
194                          first.read offset (\a at -> second.read at (\b end -> next (a, b) end))
195                    , write =
196                        \value writer next ->
197                          first.write value.1 writer (\at -> second.write value.2 at next)
198                    }
199              , record =
200                  \R build fields ->
201                    { read = build Reader readerMonad (\T name pos child -> child.read)
202                    , write =
203                        \value ->
204                          fields
205                            (Writer -> (Writer -> Code) -> Code)
206                            (\T name pos child project before writer next ->
207                               before writer (\at -> child.write (project value) at next))
208                            (\writer next -> next writer)
209                    }
210              , union =
211                  \U cases fold ->
212                    let labels =
213                          cases (List Text) (\T name pos child inject rest -> rest # [ name ]) []
214                    let count = L.length labels
215                    let tagBits =
216                          N.fold
217                            count
218                            (\bits -> if N.lessThan (N.pow2 bits) count then bits + 1 else bits)
219                            0
220                    let index =
221                          \name ->
222                            L.length (L.takeWhile (\other -> Text/equal name other == False) labels)
223                    in  { read =
224                            \offset next ->
225                              let tag = readBits Code o tagBits offset
226                              in  cases
227                                    Code
228                                    (\T name pos child inject rest ->
229                                       o.branch
230                                         (Word/equal tag (Word/fromNatural tagBits (index name)))
231                                         (child.read
232                                            (advance offset tagBits)
233                                            (\value at -> next (inject value) at))
234                                         rest)
235                                    fail
236                        , write =
237                            fold
238                              (Writer -> (Writer -> Code) -> Code)
239                              (\T name pos child value writer next ->
240                                 child.write
241                                   value
242                                   (writeBits
243                                      tagBits
244                                      (Word/fromNatural tagBits (index name))
245                                      writer)
246                                   next)
247                        }
248              }
249
250-- A separate static interpretation checks every alternative, including ones
251-- a particular handler never returns. There is no silent fallback encoding.
252let problems =
253      \{A : Solidity.Families -> Type} (d : Reflect Solidity.types A) ->
254        Solidity.interpret
255          d
256          Solidity.values
257          (\(_ : Type) -> List Text)
258          { leaf = { word = \_ -> [], bytes = \_ -> [], indexed = \_ -> [], anonymous = \_ -> [] }
259          , bool = []
260          , word = \_ -> []
261          , natural = []
262          , integer = []
263          , double = [ "Double has no native contract codec" ]
264          , function = \A B argument result -> [ "functions have no native contract codec" ]
265          , text = []
266          , list = \T child -> child
267          , optional = \T child -> child
268          , pair = \T U first second -> first # second
269          , record =
270              \R build fields ->
271                fields
272                  (List Text)
273                  (\T name pos child project rest ->
274                     rest # L.map (\why -> name ++ ": " ++ why) child)
275                  []
276          , union =
277              \U cases fold ->
278                cases
279                  (List Text)
280                  (\T name pos child inject rest ->
281                     rest # L.map (\why -> name ++ ": " ++ why) child)
282                  []
283          }
284
285-- The bits in the last byte are static, so a byte-aligned end checks no
286-- padding.
287let complete
288    : forall (Code : Type) -> S.Ops Word256 Bool Code -> Cursor -> Code -> Code
289    = \(Code : Type) (o : S.Ops Word256 Bool Code) (end : Cursor) (next : Code) ->
290        let bytes = end.byte + N.div (end.bit + 7) 8
291        let padding =
292              if Natural/isZero end.bit
293              then True
294              else Word/isZero
295                     (Word/and
296                        (Word/shr 248 (o.cdload (lit end.byte)))
297                        (Word/sub (Word/shl (N.minus 8 end.bit) (lit 1)) (lit 1)))
298        in  o.branch (Word/equal o.cdsize (lit bytes) && padding) next (o.revert [])
299
300-- Fixed fragment plans keep their specialized code. Dynamic numbers and
301-- collections use the typed buffer codec with a shared bit cursor.
302let buffered =
303      \{A : Solidity.Families -> Type} (d : Reflect Solidity.types A) ->
304        Solidity.interpret
305          d
306          Solidity.values
307          (\(_ : Type) -> Bool)
308          { leaf =
309              { word = \_ -> False
310              , bytes = \_ -> True
311              , indexed = \_ -> True
312              , anonymous = \_ -> True
313              }
314          , bool = False
315          , word = \_ -> False
316          , natural = True
317          , integer = True
318          , double = False
319          , function = \A B argument result -> False
320          , text = False
321          , list = \T child -> True
322          , optional = \T child -> child
323          , pair = \T U first second -> first || second
324          , record =
325              \R build fields -> fields Bool (\T name pos child project rest -> child || rest) False
326          , union =
327              \U cases fold -> cases Bool (\T name pos child inject rest -> child || rest) False
328          }
329
330let decode
331    : forall {A : Solidity.Families -> Type}
332             (d : Reflect Solidity.types A)
333             (Code : Type)
334             (raw : Runtime.Ops Code)
335             (offset : Natural)
336             (next : A Solidity.values -> Code)
337      -> Code
338    = \{A} d Code raw offset next ->
339        if buffered d
340        then raw.readValue (A Solidity.values) (lit offset) next
341        else (codec d Code raw).read
342               { byte = N.div offset 8, bit = N.mod offset 8 }
343               (\value end -> complete Code raw.evm end (next value))
344
345let encode
346    : forall {A : Solidity.Families -> Type}
347             (d : Reflect Solidity.types A)
348             (Code : Type)
349             (raw : Runtime.Ops Code)
350             (value : A Solidity.values)
351      -> Code
352    = \{A} d Code raw value ->
353        if buffered d
354        then raw.outputValue (A Solidity.values) value
355        else (codec d Code raw).write value empty (\writer -> raw.outputNative (finish writer))
356
357in  { Of, problems, decode, encode }
Your result
Complete file: lib/EVM/Native/Codec.omg · with imports