-
Notifications
You must be signed in to change notification settings - Fork 0
/
Language.hs
540 lines (417 loc) · 14.9 KB
/
Language.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
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
{-# LANGUAGE InstanceSigs #-}
--{-# LANGUAGE ExistentialQuantification #-}
module Language where
import CoreParser
data Expr a
= A Atom
| EAp (Expr a) (Expr a)
| ELet --let的表达式
IsRec --bool类 (True 表示recursive,目的是区分递归和非递归的)
[(a, Expr a)] --定义
(Expr a) --body of let
| ECase --case 表达式
(Expr a)
[Alter a] --可选项
| ELam [a] (Expr a) --lambda表达式
data Atom
= ENum CN
| EConstr Int Int
| EVar Name
| Prn CoreExpr --包含在括号内的表达式
data CN = I Int | F Double
deriving (Show, Eq)
instance Ord CN where
(>) (I x) (I y) = x > y
(>) (I x) (F y) = fromIntegral x > y
(>) (F x) (F y) = x > y
(>) (F x) (I y) = x > fromIntegral y
(<) = flip (>)
(>=) (I x) (I y) = x >= y
(>=) (I x) (F y) = fromIntegral x >= y
(>=) (F x) (F y) = x >= y
(>=) (F x) (I y) = x >= fromIntegral y
(<=) = flip (>=)
instance Num CN where
(+) (I x) (I y) = I (x + y)
(+) (I x) (F y) = F (fromIntegral x + y)
(+) (F x) (F y) = F (x + y)
(+) (F x) (I y) = F (fromIntegral y + x)
(-) (I x) (I y) = I (x - y)
(-) (I x) (F y) = F (fromIntegral x - y)
(-) (F x) (F y) = F (x - y)
(-) (F x) (I y) = F (x - fromIntegral y)
(*) (I x) (I y) = I (x * y)
(*) (I x) (F y) = F (fromIntegral x * y)
(*) (F x) (F y) = F (x * y)
(*) (F x) (I y) = F (x * fromIntegral y)
abs (I x) = I $ abs x
abs (F x) = F $ abs x
negate (I x) = I $ negate x
negate (F x) = F $ negate x
signum (I x)
| x > 0 = (I 1)
| x < 0 = (I (-1))
| otherwise = (I x)
signum (F x)
| x > 0 = (F 1.0)
| x < 0 = (F (-1.0))
| otherwise = F x
fromInteger n = I (fromIntegral n)
type CoreExpr = Expr Name --一般表达式
type Name = String --变量名
type IsRec = Bool
type Alter a = (Int, [a], Expr a)
type CoreAlt = Alter Name
type Program a = [ScDefn a]
type CoreProgram = Program Name
type ScDefn a = (Name, [a], Expr a) --supercombinator definition
type CoreScDefn = ScDefn Name
type Defn a = (a, Expr a)
type CoreDefn = Defn Name
data PartialExpr = NoOp | Op Name CoreExpr --Op 操作符名称 表达式
instance Functor Expr where
fmap :: (a -> b) -> Expr a -> Expr b
fmap _ (A (EVar ne)) = A (EVar ne)
fmap _ (A (ENum n)) = A (ENum n)
fmap _ (A (EConstr n1 n2)) = A (EConstr n1 n2)
fmap f (EAp e1 e2) = EAp (f <$> e1) (f <$> e2)
fmap f (ELet b defn e) = ELet b defn' (f <$> e)
where
defn' = (\(a, e1) -> (f a, f <$> e1)) <$> defn
fmap f (ECase e atrs) = ECase (f <$> e) atrs'
where
atrs' = (\(n, as, e) -> (n, f <$> as, f <$> e)) <$> atrs
fmap f (ELam as e) = ELam (f <$> as) (f <$> e)
recursive, nonRecursive :: IsRec
recursive = True
nonRecursive = False
data Iseq
= INil
| IStr String
| IAppend Iseq Iseq
| IIndent Iseq
| INewline
deriving Eq
iNil :: Iseq
iNil = INil
iStr :: String -> Iseq
iStr str = IStr str
iAppend :: Iseq -> Iseq -> Iseq
iAppend seq1 INil = seq1
iAppend INil seq2 = seq2
iAppend seq1 seq2 = IAppend seq1 seq2
iIndent seq = IIndent seq
iNewline = INewline
iSpace n = iStr $ rSpaces n
iNum :: CN -> Iseq
iNum (I n) = iStr $ show n
iNum (F n) = iStr $ show n
iFWNum :: Int -> Int -> Iseq
iFWNum n w = iStr $ (rSpaces (w - length digits)) ++ digits
where
digits = show n
iLayn :: [Iseq] -> Iseq --列表每一行以数字开头表示行数
iLayn seqs = foldr makeIt iNil (zip [1..] seqs)
where
makeIt (n,seq) rs
| rs == iNil = iConcat [iFWNum n 4, iStr ") ", iIndent seq, rs]
| otherwise = iConcat [iFWNum n 4, iStr ") ", iIndent seq, iNewline, rs]
--取绑定的名称
bindersOf :: [(a, b)] -> [a]
bindersOf defns = [name | (name, _) <- defns]
--取右值
rhssOf :: [(a,b)] -> [b]
rhssOf defns = [rhs | (_, rhs) <- defns]
--判断基本表达式
isAtomicExpr :: Expr a -> Bool
isAtomicExpr (A _) = True
isAtomicExpr _ = False
preludeDefs :: CoreProgram
preludeDefs = [ ("I", ["x"], A (EVar "x")),
("K", ["x", "y"],A (EVar "x")),
("K1", ["x", "y"], A (EVar "y")),
("S", ["f", "g", "x"], EAp (EAp (A (EVar "f")) (A (EVar "x")))
(EAp (A (EVar "g")) (A (EVar "x")))),
("compose", ["f","g","x"], EAp (A (EVar "f"))
(EAp (A (EVar "g")) (A (EVar "x")))),
("twice", ["f"], EAp (EAp (A (EVar "compose")) (A (EVar "f"))) (A (EVar "f"))),
("length", ["xs"], EAp
(EAp
(EAp (A $ EVar "caseList") (A $ EVar "xs"))
(A $ ENum 0))
(A $ EVar "length'")),
("length'", ["x", "xs"], EAp
(EAp (A $ EVar "+") (A $ ENum 1))
(EAp (A $ EVar "length") (A $ EVar "xs")))]
--打印表达式
pprExpr :: CoreExpr -> Iseq
pprExpr e@(A ae) = pprAExpr e
pprExpr (EAp e1 e2)
| isBinop e1 = iConcat [pprExpr e2, (iStr " "), pprExpr e1]
| otherwise = iConcat [pprExpr e1, (iStr " "), pprExpr e2] --打印类似与+,-,*,/之类的中序运算符
--let或letrec的表达
pprExpr (ELet isrec defns expr)
= iConcat [ iStr keyword, iNewline,
(iSpace 2), iIndent (pprDefns defns), iNewline,
iStr "in ", pprExpr expr]
where
keyword | isrec = "letrec"
| otherwise = "let"
--打印case
pprExpr (ECase expr alters)
= iConcat [iStr "case ", iIndent (pprExpr expr), iStr " of", iNewline, (chng alters)]
where
chng tgs = foldr (\x xs -> iConcat [iIndent (pprAlter x), iNewline, xs]) INil tgs
--lambda表达式
--lambda (x y z..) ...
pprExpr (ELam eles expr)
= iConcat [iStr "lambda ",pprArgs eles, iStr " -> ",pprExpr expr]
--打印函数定义
--type Alter a = (Int, [a], Expr a)
--type CoreAlt = Alter Name
pprAlter :: CoreAlt -> Iseq
pprAlter (i, as, expr) = iConcat [iStr (show "<" ++ show i ++ ">: "), (chng as), iStr " -> ", iIndent(pprExpr expr)]
where
chng tgs = foldr (\x xs -> iConcat [iStr x, iStr " ",xs]) INil tgs
pprDefns :: [(Name, CoreExpr)] -> Iseq
pprDefns defns = foldr makeIt iNil defns
where
makeIt x rs = if rs == iNil
then iConcat [pprDefn x, rs]
else iConcat [pprDefn x, iNewline, rs]
pprDefn :: (Name, CoreExpr) -> Iseq
pprDefn (name, expr)
= iConcat [iIndent (iStr name), iStr " = ", iIndent (pprExpr expr)]
pprAExpr :: CoreExpr -> Iseq
pprAExpr (A (EVar v)) = iStr v
pprAExpr (A (ENum cn)) = pprCN cn
pprAExpr (A (Prn e)) = iConcat [iStr "(", (pprExpr e), iStr ")"]
pprAExpr (A (EConstr t a)) = iConcat [iStr "Pack {", iNum (I t), iStr ",", iNum (I a), iStr "}"]
pprCN :: CN -> Iseq
pprCN (I n) = iStr $ show n
pprCN (F n) = iStr $ show n
pprArgs :: [String] -> Iseq
pprArgs args = foldr (\x rs -> iConcat [iStr x, iSpace 1, rs]) iNil args
{-
pprProgram prog = iInterleave (iAppend (iStr " ;") iNewline) (map pprSc prog)
-}
--type Program a = [ScDefn a]
--type CoreProgram = Program Name
pprProgram :: CoreProgram -> Iseq
pprProgram p = foldr process INil p
where
process x xs = iConcat [pprScDefn x, iStr "; ", iNewline, xs]
{-
type ScDefn a = (Name, [a], Expr a) --supercombinator definition
type CoreScDefn = ScDefn Name
-}
pprScDefn :: CoreScDefn -> Iseq
pprScDefn (name, as, expr) = iConcat [iStr name, iSpace 1 ,pprArgs as, iStr "= ", iIndent (pprExpr expr)]
-- where
-- chng as = foldr (\x xs -> (iStr x) `iAppend` xs) INil as
mkMultiAp :: Int -> CoreExpr -> CoreExpr -> CoreExpr
mkMultiAp n e1 e2 = foldl (EAp) e1 (take n e2s_i)
where
e2s_i = e2 : e2s_i
iConcat :: [Iseq] -> Iseq
iConcat tgs = foldl1 iAppend tgs
iInterleave :: Iseq -> [Iseq] -> Iseq
iInterleave iseq tgs = foldl1 (\x y -> iConcat [x, iseq, y]) tgs
--转换Iseq为String
flatten :: Int -> [(Iseq, Int)] -> String
flatten _ ((INewline, indent):prs)
= '\n' : (rSpaces indent) ++ (flatten indent prs)
flatten col ((IIndent seq, _):prs)
= flatten col ((seq, col):prs)
flatten col ((IStr s, indent):prs)
-- | s == "\n" = flatten col ((INewline, indent):prs)
= s ++ flatten (col + length s) prs
flatten col ((IAppend seq1 seq2, indent):prs)
= flatten col ((seq1,indent):(seq2,indent):prs)
flatten _ _ = []
iDisplay :: Iseq -> String
iDisplay seq = flatten 0 [(seq, 0)]
--解析程序
pProgram :: Parser CoreProgram
pProgram = sepByc1 pSc ';'
pSc :: Parser CoreScDefn
pSc = liftA4 mk_sc oneWord (foldParser oneWord) (tok $ string1 "=") pExpr
where
mk_sc name args _ body = (name,args,body)
pVar :: Parser CoreExpr
pVar = do w <- oneWord
if w `elem` keyWords1
then unexpectedStringParser w
else return $ A (EVar w)
pExpr :: Parser CoreExpr
pExpr = (pLet True) <|> (pLet False) <|> pCase <|> pLam <|> pExpr1
pCase :: Parser CoreExpr
pCase = liftA4 mk_case (tok $ string1 "case") pExpr (stringTok "of\n") pAlters
where
mk_case _ e _ as = ECase e as
pAlters :: Parser [CoreAlt]
pAlters = do as <- sepByc1 pAlter '\n'
return $ zipWith (\(_, vs, e) n -> (n, vs, e)) as [1..]
--默认tag为0,后期再修改
pAlter :: Parser CoreAlt
pAlter = do vars <- list oneWord
string1 "->"
expr <- pExpr
return $ (0, vars, expr)
pLet :: Bool -> Parser CoreExpr
pLet isRec = if not isRec
then liftA4 mk_let (tok $ string1 "let") pEq_Expr (string1 "in") pExpr
else liftA4 mk_letrec (tok $ string1 "letrec") (sepByc1 pEq_Expr '\n') (string1 "in") pExpr
where
mk_let _ eqe _ e = ELet False [eqe] e
mk_letrec _ eqes _ e = ELet True eqes e
pEq_Expr :: Parser CoreDefn
pEq_Expr = do v <- oneWord
tok $ string1 "="
e <- pExpr
return (v, e)
pLam :: Parser CoreExpr
pLam = liftA4 mk_lambda (tok $ string1 "\\") (list oneWord) (string1 "->") pExpr
where
mk_lambda _ es _ e = ELam es e
pCommon :: Parser CoreExpr
pCommon = do v <- oneWord
c <- symbol
makeIt (pure (\e -> EAp (EAp (A (EVar [c])) (A (EVar v))) e))
where
makeIt mrs = do v <- list (letter <|> digit)
c <- symbol
let new_mrs = liftA (makeAp c v)mrs in
makeIt new_mrs
<|> do v <- list (letter <|> digit)
rs <- mrs
return $ rs (A (EVar v))
makeAp c v f = \e' -> EAp (EAp (A (EVar [c])) (f $ (A (EVar v)))) e'
{-expr -> let defns in expr
| letrec dfns in expr
| case expr of alts
| \ var1 ... varn . expr
| expr1
expr1 -> expr2 | expr1
| expr2
expr2 -> expr3 & expr2
| expr3
expr3 -> expr4 relop expr4
| expr4
expr4 -> expr5 + expr4
| expr5 - expr5
| expr5
expr5 -> expr6 * expr5
| expr6 / expr6
| expr6
expr6 -> aexpr1 ... aexprn
-}
pExpr1 :: Parser CoreExpr
pExpr1 = (liftA2 assembleOp pExpr2 pExpr1c) <|> pExpr2
pExpr1c :: Parser PartialExpr
pExpr1c = (liftA2 Op (tok $ string1 "|") pExpr1) <|> (pure NoOp)
pExpr2 :: Parser CoreExpr
pExpr2 = (liftA2 assembleOp pExpr3 pExpr2c) <|> pExpr3
pExpr2c :: Parser PartialExpr
pExpr2c = (liftA2 Op (tok $ string1 "&") pExpr1) <|> (pure NoOp)
pExpr3 :: Parser CoreExpr
pExpr3 = (liftA2 assembleOp pExpr4 pExpr3c) <|> pExpr4
pExpr3c :: Parser PartialExpr
pExpr3c = (liftA2 Op pRelop pExpr4) <|> (pure NoOp)
pRelop :: Parser String
pRelop = foldr (\x xs-> (tok $ string1 x) <|> xs) (string1 ">") ["<=", ">=", "==", "/=", "<"]
pExpr4 :: Parser CoreExpr
pExpr4 = (liftA2 assembleOp pExpr5 pExpr4c) <|> pExpr5
pExpr4c :: Parser PartialExpr
pExpr4c = (liftA2 Op (tok $ string1 "+") pExpr4) <|>
(liftA2 Op (tok $ string1 "-") pExpr5) <|> (pure NoOp)
pExpr5 :: Parser CoreExpr
pExpr5 = (liftA2 assembleOp pExpr6 pExpr5c) <|> pExpr6
pExpr5c :: Parser PartialExpr
pExpr5c = (liftA2 Op (tok $ string1 "*") pExpr5) <|>
(liftA2 Op (tok $ string1 "/") pExpr5) <|>
(liftA2 Op (tok $ string1 "`div`") pExpr5) <|> (pure NoOp)
pExpr6 :: Parser CoreExpr
pExpr6 = do i <- pItem
makeIt $ pure (\x -> EAp i x)
<|> do i <- pItem
return i
where
pItem = pNum1 <|> pVar <|> pPack <|> pPrnedExpr
makeIt mrs = do i <- pItem
let new_mrs = liftA (\f -> (\x -> EAp (f i) x)) mrs in
makeIt new_mrs
<|> do i <- pItem
rs <- mrs
return $ rs i
pPrnedExpr :: Parser CoreExpr
pPrnedExpr = do e <- betweenWithc pExpr '(' ')'
return $ A (Prn e)
assembleOp :: CoreExpr -> PartialExpr -> CoreExpr
assembleOp e1 (Op op e2) = EAp (EAp (A (EVar op)) e1) e2
assembleOp e1 _ = e1
--auxilliary function
binOperators :: [String]
binOperators = ["+","-","*","/","<","<=",">",">=","==","/=","&","|"]
isBinop :: CoreExpr -> Bool
isBinop (A (EVar op)) = op `elem` binOperators
isBinop _ = False
oneWord :: Parser String
oneWord = tok $ list1 (alpha' <|> digit')
rSpaces :: Int -> String
rSpaces n
| n > 0 = replicate n ' '
| otherwise = ""
pExpr2pString :: Parser CoreExpr -> Parser String
pExpr2pString pe = do e <- pe
return $ iDisplay $ pprExpr e
pDefn2pString :: Parser CoreDefn -> Parser String
pDefn2pString pd = pd >>= (return . iDisplay . pprDefn)
pScDefn2pString :: Parser CoreScDefn -> Parser String
pScDefn2pString pscd = pscd >>= (return . iDisplay . pprScDefn)
pProgram2pString :: Parser CoreProgram -> Parser String
pProgram2pString pp = pp >>= (return . iDisplay . pprProgram)
pNum1 :: Parser CoreExpr
pNum1 = do n <- pInt
f <- pDouble
let f' = fromIntegral n + 0.0 in
return $ A (ENum (F (f' + f)))
<|> do n <- pInt
return $ A (ENum (I n))
pInt :: Parser Int
pInt = do d <- tok (list1 digit')
return $ (read d :: Int)
pFloat :: Parser Float
pFloat = do p <- is '.'
ds <- tok (list1 digit')
let f = (read ('0':p:ds) :: Float) in
return f
pDouble :: Parser Double
pDouble = do p <- is '.'
ds <- tok (list1 digit')
let f = (read ('0':p:ds) :: Double) in
return f
pPack :: Parser CoreExpr
pPack = do string1 "Pack"
(tag,arity) <- betweenWithc getIt '{' '}'
if arity == 0
then return $ A $ EConstr tag arity
else do args <- getPackArgs arity
return $ EAp (A $ EConstr tag arity) args
where
getIt = do t <- pInt
charTok ','
a <- pInt
return (t,a)
getPackArgs 1 = pVar
getPackArgs n = do arg <- pVar
reminders <- getPackArgs (n-1)
return $ EAp arg reminders
pUDInfix :: Parser String
pUDInfix = betweenWithc oneWord '`' '`'
keyWords1 :: [String]
keyWords1 = ["case","in","letrec","let","of","Pack"]
countEAp :: (Expr a) -> Int
countEAp (EAp e1 e2)
| isAtomicExpr e1 = 1
| otherwise = 1 + countEAp e1