-
Notifications
You must be signed in to change notification settings - Fork 62
/
Rec.hs
191 lines (170 loc) · 8.32 KB
/
Rec.hs
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
{-# LANGUAGE DefaultSignatures #-}
module Plutarch.Rec (
DataReader (DataReader, readData),
PRecord (PRecord, getRecord),
ScottEncoded,
ScottEncoding,
RecordFromData (fieldFoci, fieldListFoci),
field,
fieldFromData,
letrec,
pletrec,
recordFromFieldReaders,
) where
import Control.Monad.Trans.State.Lazy (State, evalState, get, put)
import Data.Functor.Compose (Compose (Compose, getCompose))
import Data.Kind (Type)
import Data.Monoid (Dual (Dual, getDual), Endo (Endo, appEndo), Sum (Sum, getSum))
import Numeric.Natural (Natural)
import Plutarch (PlutusType (PInner, pcon', pmatch'), pcon, phoistAcyclic, plam, plet, punsafeCoerce, (#), (:-->))
import Plutarch.Bool (pif, (#==))
import Plutarch.Builtin (PAsData, PBuiltinList, PData, pasConstr, pforgetData, pfstBuiltin, psndBuiltin)
import Plutarch.Internal (
PType,
RawTerm (RApply, RLamAbs, RVar),
Term (Term, asRawTerm),
TermResult (TermResult, getDeps, getTerm),
mapTerm,
)
import Plutarch.List (phead, ptail)
import Plutarch.Trace (ptraceError)
import qualified Rank2
newtype PRecord r s = PRecord {getRecord :: r (Term s)}
type family ScottEncoded (r :: ((PType) -> Type) -> Type) (a :: PType) :: PType
newtype ScottArgument r s t = ScottArgument {getScott :: Term s (ScottEncoded r t)}
type ScottEncoding r t = ScottEncoded r t :--> t
instance (Rank2.Distributive r, Rank2.Traversable r) => PlutusType (PRecord r) where
type PInner (PRecord r) t = ScottEncoding r t
pcon' :: forall s. PRecord r s -> forall t. Term s (ScottEncoding r t)
pcon' (PRecord r) = rcon r
pmatch' :: forall s t. (forall t. Term s (ScottEncoding r t)) -> (PRecord r s -> Term s t) -> Term s t
pmatch' p f = p # arg
where
arg :: Term s (ScottEncoded r t)
arg = Term (\i -> TermResult (RLamAbs (fieldCount (initial @r) - 1) $ rawArg i) [])
rawArg :: Natural -> RawTerm
rawArg depth = getTerm $ asRawTerm (f $ PRecord variables) $ depth + fieldCount (initial @r)
rcon :: forall r s t. Rank2.Foldable r => r (Term s) -> Term s (ScottEncoding r t)
rcon r = plam (\f -> punsafeCoerce $ appEndo (getDual $ Rank2.foldMap (Dual . Endo . applyField) r) f)
where
applyField x f = punsafeCoerce f # x
-- | Wrapped recursive let construct, tying into knot the recursive equations specified in the record fields.
pletrec :: forall r s. (Rank2.Distributive r, Rank2.Traversable r) => (r (Term s) -> r (Term s)) -> Term s (PRecord r)
pletrec = punsafeCoerce . letrec
-- | Recursive let construct, tying into knot the recursive equations specified in the record fields.
letrec :: forall r s t. (Rank2.Distributive r, Rank2.Traversable r) => (r (Term s) -> r (Term s)) -> Term s (ScottEncoding r t)
letrec r = Term term
where
term n = TermResult {getTerm = RApply rfix [RLamAbs 1 $ RApply (RVar 0) $ rawTerms], getDeps = deps}
where
(Dual rawTerms, deps) = Rank2.foldMap (rawResult . ($ n) . asRawTerm) (r selfReferring)
rawResult TermResult {getTerm, getDeps} = (Dual [getTerm], getDeps)
selfReferring = Rank2.fmap fromRecord accessors
fromRecord :: ScottArgument r s a -> Term s a
fromRecord (ScottArgument (Term access)) =
Term $ \depth -> mapTerm (\field -> RApply (RVar $ fieldCount (initial @r) + depth - 1) [field]) (access 0)
-- | Converts a Haskell field function to a Scott-encoded record field accessor.
field ::
forall r s t.
(Rank2.Distributive r, Rank2.Traversable r) =>
(r (ScottArgument r s) -> ScottArgument r s t) ->
Term s (ScottEncoded r t)
field f = getScott (f accessors)
-- | Provides a record of function terms that access each field out of a Scott-encoded record.
accessors :: forall r s. (Rank2.Distributive r, Rank2.Traversable r) => r (ScottArgument r s)
accessors = abstract Rank2.<$> variables
where
abstract :: Term s a -> ScottArgument r s a
abstract (Term t) = ScottArgument (phoistAcyclic $ Term $ mapTerm (RLamAbs $ fieldCount (initial @r) - 1) . t)
{- | A record of terms that each accesses a different variable in scope,
outside in following the field order.
-}
variables :: forall r s. (Rank2.Distributive r, Rank2.Traversable r) => r (Term s)
variables = Rank2.cotraverse var id
where
var :: (r (Term s) -> Term s a) -> Term s a
var ref = ref ordered
ordered :: r (Term s)
ordered = evalState (Rank2.traverse next $ initial @r) (fieldCount $ initial @r)
next :: f a -> State Natural (Term s a)
next _ = do
i <- get
let i' = pred i
seq i' (put i')
return $
Term $
const $
TermResult
{ getTerm = RVar i'
, getDeps = []
}
newtype DataReader s a = DataReader {readData :: Term s (PAsData a) -> Term s a}
newtype FocusFromData s a b = FocusFromData {getFocus :: Term s (PAsData a :--> PAsData b)}
newtype FocusFromDataList s a = FocusFromDataList {getItem :: Term s (PBuiltinList PData) -> Term s (PAsData a)}
{- | Converts a record of field DataReaders to a DataReader of the whole
record. If you only need a single field or two, use `fieldFromData`
instead.
-}
recordFromFieldReaders ::
forall r s.
(Rank2.Apply r, RecordFromData r) =>
r (DataReader s) ->
DataReader s (PRecord r)
recordFromFieldReaders reader = DataReader $ verifySoleConstructor readRecord
where
readRecord :: Term s (PBuiltinList PData) -> Term s (PRecord r)
readRecord dat = pcon $ PRecord $ Rank2.liftA2 (flip readData . getCompose) (fields dat) reader
fields :: Term s (PBuiltinList PData) -> r (Compose (Term s) PAsData)
fields bis = (\f -> Compose $ getItem f bis) Rank2.<$> fieldListFoci
{- | Converts a Haskell field function to a function term that extracts the 'Data' encoding of the field from the
encoding of the whole record.
-}
fieldFromData ::
RecordFromData r =>
(r (FocusFromData s (PRecord r)) -> FocusFromData s (PRecord r) t) ->
Term s (PAsData (PRecord r) :--> PAsData t)
fieldFromData f = getFocus (f fieldFoci)
{- | Instances of this class must know how to focus on individual fields of
the data-encoded record. If the declared order of the record fields doesn't
match the encoding order, you must override the method defaults.
-}
class (Rank2.Distributive r, Rank2.Traversable r) => RecordFromData r where
-- | Given the encoding of the whole record, every field focuses on its own encoding.
fieldFoci :: r (FocusFromData s (PRecord r))
-- | Given the encoding of the list of all fields, every field focuses on its own encoding.
fieldListFoci :: r (FocusFromDataList s)
fieldFoci = Rank2.cotraverse focus id
where
focus :: (r (FocusFromData s (PRecord r)) -> FocusFromData s (PRecord r) a) -> FocusFromData s (PRecord r) a
focus ref = ref foci
foci :: r (FocusFromData s (PRecord r))
foci = fieldsFromRecord Rank2.<$> fieldListFoci
fieldsFromRecord :: FocusFromDataList s a -> FocusFromData s (PRecord r) a
fieldsFromRecord (FocusFromDataList f) = FocusFromData $ plam $ verifySoleConstructor f
fieldListFoci = Rank2.cotraverse focus id
where
focus :: (r (FocusFromDataList s) -> FocusFromDataList s a) -> FocusFromDataList s a
focus ref = ref foci
foci :: r (FocusFromDataList s)
foci = evalState (Rank2.traverse next $ initial @r) id
next :: f a -> State (Term s (PBuiltinList PData) -> Term s (PBuiltinList PData)) (FocusFromDataList s a)
next _ = do
rest <- get
put ((ptail #) . rest)
return $ FocusFromDataList (punsafeCoerce . (phead #) . rest)
verifySoleConstructor :: (Term s (PBuiltinList PData) -> Term s a) -> (Term s (PAsData (PRecord r)) -> Term s a)
verifySoleConstructor f d =
plet (pasConstr # pforgetData d) $ \constr ->
pif
(pfstBuiltin # constr #== 0)
(f $ psndBuiltin # constr)
(ptraceError "verifySoleConstructor failed")
initial :: Rank2.Distributive r => r (Compose Maybe (Term s))
initial = Rank2.distribute Nothing
fieldCount :: Rank2.Foldable r => r f -> Natural
fieldCount = getSum . Rank2.foldMap (const $ Sum 1)
-- | The raw Y-combinator term
rfix :: RawTerm
-- The simplest variant of the Y combinator hangs the interpreter, so we use an eta-expanded version instead.
-- rfix = RLamAbs 0 $ RApply (RLamAbs 0 $ RApply (RVar 1) [RApply (RVar 0) [RVar 0]]) [RLamAbs 0 $ RApply (RVar 1) [RApply (RVar 0) [RVar 0]]]
rfix = RLamAbs 0 $ RApply (RLamAbs 0 $ RApply (RVar 1) [RLamAbs 0 $ RApply (RVar 1) [RVar 0, RVar 1]]) [RLamAbs 0 $ RApply (RVar 1) [RLamAbs 0 $ RApply (RVar 1) [RVar 0, RVar 1]]]