/
Liscript.hs
297 lines (220 loc) · 10.5 KB
/
Liscript.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
--module Liscript where
import Data.Maybe (fromMaybe)
import Control.Monad
import qualified Data.Map.Strict as Map
import Data.IORef
import System.IO
import Data.Time
import GHC.IO.Encoding --(setLocaleEncoding, utf8)
------------------------ ТИП LispVal И ЕГО ИНСТАНСЫ ---------------------
data LispVal = Atom String
| List [LispVal]
| Func { params :: [String], body :: [LispVal], closure :: Env }
| Macr { params :: [String], body :: [LispVal] }
instance Show LispVal where show = showVal
instance Eq LispVal where (==) = eqVal
showVal :: LispVal -> String
showVal (Atom contents) = contents
showVal (List contents) = "(" ++ unwords (map showVal contents) ++ ")"
showVal (Func {params = args, body = body, closure = _}) = "(LAMBDA "
++ unwords (map show args) ++ " (" ++ unwords (map showVal body) ++ "))"
showVal (Macr {params = args, body = body}) = "(MACRO "
++ unwords (map show args) ++ " (" ++ unwords (map showVal body) ++ "))"
eqVal :: LispVal -> LispVal -> Bool
eqVal (Atom a) (Atom b) = a == b
eqVal (List []) (List []) = True
eqVal (List (a:_)) (List []) = False
eqVal (List []) (List (b:_)) = False
eqVal (List (a:as)) (List (b:bs)) = eqVal a b && eqVal (List as) (List bs)
eqVal (Macr {params = a1, body = b1}) (Macr {params = a2, body = b2}) =
a1 == a2 && eqVal (List b1) (List b2)
eqVal _ _ = False
------------------------------- ОКРУЖЕНИЕ -------------------------------
type Frame = Map.Map String LispVal -- кадр связывания имен ключ-значение
data Env = NullEnv | Voc (IORef Frame, Env) -- дерево кадров текущий-родитель
setVar NullEnv _ value = return ()
setVar (Voc (refframe, parenv)) var value = do
frame <- readIORef refframe
if Map.member var frame then modifyIORef' refframe $ Map.insert var value
else setVar parenv var value
getVar NullEnv var = return $ Atom var
getVar (Voc (refframe, parenv)) var = readIORef refframe >>=
maybe (getVar parenv var) return . Map.lookup var
defVar NullEnv _ value = return ()
defVar (Voc (refframe, parenv)) var value = modifyIORef' refframe $ Map.insert var value
------------------------------- ПАРСЕР -------------------------------
mytokens :: String -> [String]
mytokens = go 0 False "" where
go _ _ t [] = addtoken t []
go l f t (c:cs)
| elem c " \n\t" && l==0 && not f = addtoken t $ go 0 False "" cs
| otherwise = go l' f' (c:t) cs
where
l' | f = l | c=='(' = l+1 | c==')' = l-1 | otherwise = l
f' | c=='"' = not f | otherwise = f
addtoken t r | null t = r | otherwise = reverse t:r
str2LV :: String -> LispVal
str2LV = go . mytokens where
go [t] | fst == '(' && lst == ')' = List . map str2LV . mytokens $ mid
| fst == '"' && lst == '"' = Atom mid
| fst == '\'' = List $ Atom "quote" : [str2LV $ tail t]
| otherwise = Atom t
where fst = head t
lst = last t
mid = tail $ init t
go l = List $ map str2LV l
fromAtom (Atom s) = s
prepare = id -- можно написать замену "(" на " (" и т.п. перед парсингом
------------------------------ МАКРОСЫ -----------------------------
macroexpand :: [(String, LispVal)] -> LispVal -> LispVal
macroexpand kv = go where
go (Atom a) = fromMaybe (Atom a) $ lookup a kv
go (List l) = List $ map go l
go x = x
------------------------------- ЭВАЛ -------------------------------
eval :: Handle -> Env -> LispVal -> IO LispVal
eval hFile env (Atom s) = getVar env s
eval hFile env (List l) = do
let ls = tail l
listOrVal [v] = v
listOrVal l = List l
zipArgsVals [] _ = []
zipArgsVals _ [] = []
zipArgsVals [a] b = [(a, listOrVal b)]
zipArgsVals (a:as) (b:bs) = (a, b) : zipArgsVals as bs
--mapM (eval hFile env) ls = mapM (eval hFile env) ls
str2Int s = read s :: Integer
str2Dou s = read s :: Double
foldStrOp op = mapM (eval hFile env) ls >>= return . Atom . foldl1 op . map fromAtom
foldOp op t = mapM (eval hFile env) ls >>= return . Atom . show . foldl1 op . map (t . fromAtom)
compOp op t = mapM (eval hFile env) ls >>= return . Atom . show . go . map (t . fromAtom) where
go (a:b:xx) = op a b && go (b:xx)
go _ = True
op <- eval hFile env $ head l
case op of
Atom "++" -> foldStrOp (++)
Atom "+" -> foldOp (+) str2Int
Atom "-" -> foldOp (-) str2Int
Atom "*" -> foldOp (*) str2Int
Atom "/" -> foldOp div str2Int
Atom "mod" -> foldOp mod str2Int
Atom "+'" -> foldOp (+) str2Dou
Atom "-'" -> foldOp (-) str2Dou
Atom "*'" -> foldOp (*) str2Dou
Atom "/'" -> foldOp (/) str2Dou
Atom ">" -> compOp (>) str2Int
Atom ">=" -> compOp (>=) str2Int
Atom "<" -> compOp (<) str2Int
Atom "<=" -> compOp (<=) str2Int
Atom "=" -> compOp (==) str2Int
Atom "/=" -> compOp (/=) str2Int
Atom ">'" -> compOp (>) str2Dou
Atom ">='" -> compOp (>=) str2Dou
Atom "<'" -> compOp (<) str2Dou
Atom "<='" -> compOp (<=) str2Dou
Atom "='" -> compOp (==) str2Dou
Atom "/='" -> compOp (/=) str2Dou
Atom "eq?" -> mapM (eval hFile env) ls >>= return . Atom . show . (\l -> all (==head l) l)
Atom "quote" -> return $ listOrVal ls
Atom "eval" -> mapM (eval hFile env) ls >>= mapM (eval hFile env) >>= return . listOrVal
Atom "str" -> mapM (eval hFile env) ls >>= return . List
Atom "strTolist" -> mapM (eval hFile env) ls >>= return . List . map (Atom.(:"")) . concatMap fromAtom
Atom "cond" -> cond ls where
cond (p:e:xx) = eval hFile env p >>=
\p -> if (read $ fromAtom p) then eval hFile env e else cond xx
cond [e] = eval hFile env e
cond [] = return $ Atom ""
Atom "while" -> while ls where
while px@(p:xx) = eval hFile env p >>= \p -> if (read $ fromAtom p)
then eval hFile env (List xx) >> while px else return $ Atom ""
Atom "printLn" -> mapM (eval hFile env) ls >>=
mapM_ ((if printToFile then hPutStrLn hFile else putStrLn) . show) >> return (Atom "")
Atom "print" -> mapM (eval hFile env) ls >>=
mapM_ ((if printToFile then hPutStr hFile else putStr) . show) >> return (Atom "")
Atom "def" -> go ls where
go (n:e:xx) = eval hFile env e >>= defVar env (fromAtom n) >> go xx
go _ = return $ Atom ""
Atom "name-def" -> mapM (eval hFile env) ls >>= go where
go (n:v:xx) = defVar env (fromAtom n) v >> go xx
go _ = return $ Atom ""
Atom "set!" -> go ls where
go (n:e:xx) = eval hFile env e >>= setVar env (fromAtom n) >> go xx
go _ = return $ Atom ""
Atom "name-set!" -> mapM (eval hFile env) ls >>= go where
go (n:v:xx) = setVar env (fromAtom n) v >> go xx
go _ = return $ Atom ""
-- Atom "defn" -> eval hFile env (List $ (Atom "lambda") : tail ls) >>=
-- defVar env (fromAtom . head $ ls) >> return (Atom "")
Atom "cons" -> mapM (eval hFile env) ls >>= return . foldr1 cons where
cons x (List l) = List (x:l)
cons x y = List [x,y]
Atom "car" -> eval hFile env (head ls) >>= return . car where
car (List l) = if null l then List [] else head l
car x = x
Atom "cdr" -> eval hFile env (head ls) >>= return . cdr where
cdr (List l) = if null l then List [] else List (tail l)
cdr _ = List []
Atom x | x == "lambda"-> return Func { params = args, body = foobody, closure = env }
| x == "macro" -> return Macr { params = args, body = foobody }
where args = (\(List l) -> map fromAtom l) $ head ls
getbody [List a] = getbody a
getbody l = l
foobody = getbody $ tail ls
Atom x | x `elem` ["atom?", "list?", "func?", "macr?"] ->
mapM (eval hFile env) ls >>= return . Atom . show . all tst where
tst = (==x) . gettype
gettype (Atom _) = "atom?"
gettype (List _) = "list?"
gettype (Func { params = _, body = _, closure = _ }) = "func?"
gettype (Macr { params = _, body = _ }) = "macr?"
Func {params = args, body = foobody, closure = envfun} -> do
reflocalframe <- mapM (eval hFile env) ls >>= newIORef . Map.fromList . zipArgsVals args
eval hFile (Voc (reflocalframe, envfun)) $ List foobody
Macr {params = args, body = macrobody} -> eval hFile env
. macroexpand (zipArgsVals args ls) $ List macrobody
_ -> go ls where
go [] = return op
go [x] = eval hFile env x
go (x:xs) = eval hFile env x >> go xs
------------------------------- МЭЙН -------------------------------
loadfile hFile env filename = do
handle <- openFile filename ReadMode
hSetEncoding handle utf8
contents <- hGetContents handle
res <- eval hFile env . str2LV . prepare $ contents
print res
hClose handle
return res
printToFile = False --True
main = do
setLocaleEncoding utf8
begT <- getCurrentTime
refglobalframe <- newIORef Map.empty
let globalframe = Voc (refglobalframe, NullEnv)
--hOutFile <- openFile "rezult_Liscript.txt" WriteMode
let hOutFile = undefined
loadfile hOutFile globalframe "lib.txt"
-- loadfile hOutFile globalframe "test.txt"
loadfile hOutFile globalframe "test1.txt"
-- loadfile hOutFile globalframe "test2.txt"
-- loadfile hOutFile globalframe "test3.txt"
--hClose hOutFile
endT <- getCurrentTime
putStrLn $ "Elapced time: " ++ show (diffUTCTime endT begT)
--_ <- getLine
--putStr ""
-- дополнительные необязательные функции
-- если для отладки надо посмотреть содержимое окружения
showEnv NullEnv = putStr "Null"
showEnv (Voc (refframe, parenv)) = do
putStr "("
frame <- readIORef refframe
putStr $ show frame
putStr ","
showEnv parenv
putStr ")"
myprint f@(Func {params = _, body = _, closure = env}) = do
print f
showEnv env
putStrLn ""
myprint x = print x