-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCompiler.hs
More file actions
163 lines (138 loc) · 6.3 KB
/
Compiler.hs
File metadata and controls
163 lines (138 loc) · 6.3 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
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
module CCC.Compiler
( compileNumExpr
) where
import CCC.CatExpr (CatExpr (..))
import CCC.Cat (fanC)
import Parser (Environment, Expr (..))
-- Public API ------------------------------------------------------------------
compileNumExpr :: Environment -> Expr -> CatExpr () Integer
compileNumExpr env expr =
either (\e -> error ("Compilation failed: " ++ e)) id (compile env [] expr >>= expectInt)
-- Core compilation ------------------------------------------------------------
compile :: forall c. Environment -> [(String, RVal c)] -> Expr -> Either String (RVal c)
compile env local = \case
Int i -> Right (RInt (IntConst i))
Var name ->
case lookup name local of
Just v -> Right v
Nothing -> resolveVar name
App f x
| isFixOp env local f -> compileFix env x
Lam p body ->
Right (RFun (\arg -> compile env ((p, arg) : local) body))
App f x -> do
fv <- compile env local f
xv <- compile env local x
apply fv xv
where
resolveVar name =
case lookup name env of
Just expr -> compile env local expr
Nothing -> maybe (Left $ "Unbound variable: " ++ name) Right (lookupBuiltin name)
apply (RFun fn) x = fn x
apply _ _ = Left "Cannot apply non-function value"
-- Fixpoint compilation --------------------------------------------------------
isFixOp :: Environment -> [(String, RVal c)] -> Expr -> Bool
isFixOp env local = go []
where
go _ (Int _) = False
go _ (Lam _ _) = False
go _ (App _ _) = False
go seen (Var name)
| name `elem` map fst local = False
| name == "y" || name == "fix" = True
| name `elem` seen = False
| otherwise = maybe False (go (name : seen)) (lookup name env)
compileFix :: forall c. Environment -> Expr -> Either String (RVal c)
compileFix env = \case
Lam fName body ->
let (params, bodyExpr) = collectLams body
in maybe (Left "fix expects at least one integer argument") Right $
withIntArgs (length params) $ \args ->
curryIntArgs args $ \actualArgs -> do
paramTuple <- tupleFromExprs args actualArgs
let recCall = curryIntArgs args $ \recArgs -> do
t <- tupleFromExprs args recArgs
Right (RInt (Comp Apply (fanC Fst t)))
let fixLocal = (fName, recCall) :
zipWith (\n p -> (n, RInt p)) params (projections args Snd)
stepBody <- compile env fixLocal bodyExpr >>= expectInt
Right (RInt (Comp (Fix stepBody) paramTuple))
_ -> Left "fix expects a lambda step function"
-- | Build a curried RVal that collects n integer arguments, then applies a continuation.
curryIntArgs :: forall c input. IntArgs input -> ([CatExpr c Integer] -> Either String (RVal c)) -> RVal c
curryIntArgs args k = go args []
where
go :: IntArgs r -> [CatExpr c Integer] -> RVal c
go OneArg acc = RFun $ \case
RInt a -> k (reverse (a : acc))
_ -> Left "Expected Integer argument"
go (MoreArgs rest) acc = RFun $ \case
RInt a -> Right (go rest (a : acc))
_ -> Left "Expected Integer argument"
-- IntArgs helpers -------------------------------------------------------------
data IntArgs input where
OneArg :: IntArgs Integer
MoreArgs :: IntArgs rest -> IntArgs (Integer, rest)
withIntArgs :: Int -> (forall input. IntArgs input -> r) -> Maybe r
withIntArgs n _ | n <= 0 = Nothing
withIntArgs 1 k = Just (k OneArg)
withIntArgs n k = withIntArgs (n - 1) (k . MoreArgs)
tupleFromExprs :: IntArgs input -> [CatExpr c Integer] -> Either String (CatExpr c input)
tupleFromExprs OneArg [a] = Right a
tupleFromExprs (MoreArgs rest) (a : as) = fanC a <$> tupleFromExprs rest as
tupleFromExprs _ _ = Left "Incorrect recursive arity"
projections :: IntArgs input -> CatExpr c input -> [CatExpr c Integer]
projections OneArg t = [t]
projections (MoreArgs rest) t = Comp Fst t : projections rest (Comp Snd t)
collectLams :: Expr -> ([String], Expr)
collectLams (Lam p e) = let (ps, b) = collectLams e in (p : ps, b)
collectLams e = ([], e)
-- RVal ------------------------------------------------------------------------
data RVal c
= RInt (CatExpr c Integer)
| RSel (CatExpr c (CatExpr (Integer, Integer) Integer))
| RFun (RVal c -> Either String (RVal c))
expectInt :: RVal c -> Either String (CatExpr c Integer)
expectInt (RInt e) = Right e
expectInt _ = Left "Expected integer expression"
-- Builtins --------------------------------------------------------------------
lookupBuiltin :: String -> Maybe (RVal c)
lookupBuiltin "+" = Just $ rBin RInt Add
lookupBuiltin "-" = Just $ rBin RInt Sub
lookupBuiltin "*" = Just $ rBin RInt Mul
lookupBuiltin "sub" = Just $ rBin RInt Sub
lookupBuiltin "sub1" = Just $ rUnary (\x -> RInt (Comp Sub (fanC x (IntConst 1))))
lookupBuiltin "is0" = Just $ rUnary (\x -> RSel (Comp Eql (fanC x (IntConst 0))))
lookupBuiltin "eql" = Just $ rBin RSel Eql
lookupBuiltin "leq" = Just $ rBin RSel Leq
lookupBuiltin "geq" = Just $ rBin RSel Geq
lookupBuiltin "true" = Just $ RSel (Lift (const Snd))
lookupBuiltin "false" = Just $ RSel (Lift (const Fst))
lookupBuiltin "if" = Just rIfFun
lookupBuiltin _ = Nothing
-- | Unary builtin: extracts one integer, applies f to produce any RVal.
rUnary :: (CatExpr c Integer -> RVal c) -> RVal c
rUnary f = RFun $ \case
RInt x -> Right (f x)
_ -> Left "Expected integer argument"
-- | Binary builtin: extracts two integers, applies op, wraps result.
-- wrap = RInt for arithmetic, RSel for comparisons.
rBin :: (CatExpr c r -> RVal c) -> CatExpr (Integer, Integer) r -> RVal c
rBin wrap op = RFun $ \l -> Right $ RFun $ \r ->
case (l, r) of
(RInt x, RInt y) -> Right (wrap (Comp op (fanC x y)))
_ -> Left "Expected integer arguments"
-- Scott-encoded if: Apply . <selector, <elseVal, thenVal>>
rIfFun :: RVal c
rIfFun = RFun $ \case
RSel sel -> Right $ RFun $ \case
RInt t -> Right $ RFun $ \case
RInt e -> Right (RInt (Comp Apply (fanC sel (fanC e t))))
_ -> Left "if: else branch must be integer"
_ -> Left "if: then branch must be integer"
_ -> Left "if: condition must be a Scott boolean (selector)"