on 028d2ec help sign in
elk/elm/src/Gen/CompileToJS.hs
193 lines 8.3 kB history raw
2module CompileToJS (showErr, jsModule) where
4import Ast
5import Control.Arrow (first)
6import Control.Monad (liftM,(<=<),join)
7import Data.Char (isAlpha,isDigit)
8import Data.List (intercalate,sortBy,inits)
9import Data.Map (toList)
10import Data.Maybe (mapMaybe)
12import Initialize
13import Rename (derename)
15showErr :: String -> String
16showErr err = mainEquals $ "text(monospace(" ++ msg ++ "))"
17 where msg = show . concatMap (++"<br>") . lines $ err
19parens s = "(" ++ s ++ ")"
20braces s = "{" ++ s ++ "}"
21jsList ss = "["++ intercalate "," ss ++"]"
22jsFunc args body = "function(" ++ args ++ "){" ++ body ++ "}"
23assign x e = "\nvar " ++ x ++ "=" ++ e ++ ";"
24ret e = "\nreturn "++ e ++";"
25iff a b c = a ++ "?" ++ b ++ ":" ++ c
27mainEquals s = globalAssign "ElmCode.main" (jsFunc "" (ret s))
28globalAssign m s = "\n" ++ m ++ "=" ++ s ++ ";"
30tryBlock names e =
31 concat [ "\ntry{\n" ++ e ++ "\n\n} catch (e) {"
32 , "ElmCode.main=function() {"
33 , "var msg = ('<br><h2>Your browser may not be supported. " ++
34 "Are you using a modern browser?</h2>' +" ++
35 " '<br><span style=\"color:grey\">Runtime Error in " ++
36 intercalate "." names ++ " module:<br>' + e + '</span>');"
37 , "document.body.innerHTML = Text.monospace(msg);"
38 , "throw e;"
39 , "};}"
40 ]
43jsModule (Module names exports imports stmts) =
44 tryBlock (tail modNames) $ concat
45 [ concatMap (\n -> globalAssign n $ n ++ " || {}") .
46 map (intercalate ".") . drop 2 . inits $
47 take (length modNames - 1) modNames
48 , "\nif (" ++ modName ++ ") throw \"Module name collision, '" ++
49 intercalate "." (tail modNames) ++ "' is already defined.\"; "
50 , globalAssign modName $ jsFunc "" (includes ++body++ export) ++ "()"
51 , mainEquals $ modName ++ ".main" ]
52 where modNames = if null names then ["ElmCode", "Main"]
53 else "ElmCode" : names
54 modName = intercalate "." modNames
55 includes = concatMap jsImport $ map (first ("ElmCode."++)) imports
56 body = stmtsToJS stmts
57 export = getExports exps stmts
58 exps = if null exports then ["main"] else exports
60getExports names stmts = ret . braces $ intercalate "," pairs
61 where pairs = mapMaybe pair $ concatMap get stmts
62 pair x = if y `elem` names then Just $ y ++ ":" ++ x else Nothing
63 where y = derename x
64 get s = case s of Def x _ _ -> [x]
65 Datatype _ _ tcs -> map fst tcs
66 ImportEvent _ _ x _ -> [x]
67 ExportEvent _ _ _ -> []
70jsImport (modul, how) =
71 concat [ "\ntry{" ++ modul ++ " instanceof Object} catch(e) {throw \"Module '"
72 , drop 1 (dropWhile (/='.') modul)
73 , "' is missing. Compile with --make flag or load missing "
74 , "module in a separate JavaScript file.\";}" ] ++
75 jsImport' (modul, how)
77jsImport' (modul, As name) = assign name modul
78jsImport' (modul, Importing []) = jsImport' (modul, Hiding [])
79jsImport' (modul, Importing vs) =
80 concatMap (\v -> assign v $ modul ++ "." ++ v) vs
81jsImport' (modul, Hiding vs) =
82 concat [ "\nfor(var i in " ++ modul ++ "){"
83 , assign "hiddenVars" . jsList $ map (\v -> "'" ++ v ++ "'") vs
84 , "\nif (hiddenVars.indexOf(i) >= 0) continue;"
85 , globalAssign "this[i]" $ modul ++ "[i]"
86 , "}" ]
88stmtsToJS :: [Statement] -> String
89stmtsToJS stmts = concatMap stmtToJS (sortBy cmpStmt stmts)
90 where cmpStmt s1 s2 = compare (valueOf s1) (valueOf s2)
91 valueOf s = case s of Datatype _ _ _ -> 1
92 ImportEvent _ _ _ _ -> 3
93 Def _ [] _ -> 3
94 Def _ _ _ -> 4
95 ExportEvent _ _ _ -> 5
97stmtToJS :: Statement -> String
98stmtToJS (Def name [] e) = assign name (toJS e)
99stmtToJS (Def name (a:as) e) = "\nfunction " ++ name ++ parens a ++
100 braces (ret . toJS $ foldr Lambda e as) ++ ";"
101stmtToJS (Datatype _ _ tcs) = concatMap (stmtToJS . toDef) tcs
102 where toDef (name,args) = Def name vars $ Data (derename name) (map Var vars)
103 where vars = map (('a':) . show) [1..length args]
104stmtToJS (ImportEvent js base elm _) =
105 concat [ "\nvar " ++ elm ++ " = Elm.Input(" ++ toJS base ++ ");"
106 , "\nSignal.addListener(document, '" ++ js
107 , "', function(e) { Dispatcher.notify(" ++ elm
108 , ".id, e.value); });" ]
109stmtToJS (ExportEvent js elm _) =
110 concat [ "\nlift(function(v) { var e = document.createEvent('Event');"
111 , "e.initEvent('" ++ js ++ "', true, true);"
112 , "e.value = v;"
113 , "document.dispatchEvent(e); return v; })(" ++ elm ++ ");"
114 ]
118toJS :: Expr -> String
119toJS expr =
120 case expr of
121 IntNum n -> show n
122 FloatNum n -> show n
123 Var x -> x
124 Chr c -> show c
125 Str s -> "Value.str" ++ parens (show s)
126 Boolean b -> if b then "true" else "false"
127 Range lo hi -> jsRange (toJS lo) (toJS hi)
128 Access e lbl -> toJS e ++ "." ++ lbl
129 Binop op e1 e2 -> binop op (toJS e1) (toJS e2)
130 If eb et ef -> parens $ iff (toJS eb) (toJS et) (toJS ef)
131 Lambda v e -> jsFunc v $ ret (toJS e)
132 App (Var "toText") (Str s) -> show s
133 App (Var "link") (Str s) -> "link(" ++ show s ++ ")"
134 App (Var "plainText") (Str s) -> "plainText(" ++ show s ++ ")"
135 App e1 e2 -> toJS e1 ++ parens (toJS e2)
136 Let defs e -> jsLet defs e
137 Case e cases -> jsCase e cases
138 Data name es -> jsList $ show name : map toJS es
140jsLet defs e' = jsFunc "" (jsDefs defs ++ ret (toJS e')) ++ "()"
142jsDefs defs = concatMap toDef $ sortBy f defs
143 where f a b = compare (valueOf a) (valueOf b)
144 valueOf (Definition _ args _) = min 1 (length args)
145 toDef (Definition x [] e) = assign x (toJS e)
146 toDef (Definition f (a:as) e) =
147 "\nfunction " ++ f ++ parens a ++ braces (ret . toJS $ foldr Lambda e as) ++ ";"
149jsCase e [c] = jsMatch c ++ parens (toJS e)
150jsCase e cases = "(function(){" ++
151 assign "v" (toJS e) ++
152 assign "c" jsCases ++
153 "for(var i=c.length;i--;){" ++
154 assign "r" "c[i](v)" ++
155 "if(r!==undefined){return r;}}}())"
156 where jsCases = jsList $ map jsMatch (reverse cases)
158jsMatch (p,e) = jsFunc "v" . match p "v" . ret $ toJS e
159match p v hole =
160 case p of
161 PAnything -> hole
162 PVar x -> assign x v ++ hole
163 PData name ps ->
164 "if(" ++ show name ++ "!==" ++ v ++
165 "[0]){return undefined;}else{"++body++"}"
166 where matches = zipWith match ps vs
167 vs = map (\i -> v++"["++show (i+1)++"]") [0..length ps-1]
168 body = foldr ($) hole matches
170jsNil = "[\"Nil\"]"
171jsCons e1 e2 = jsList [ show "Cons", e1, e2 ]
172jsRange e1 e2 = (++"()") . jsFunc "" $
173 assign "lo" e1 ++ assign "hi" e2 ++ assign "lst" jsNil ++
174 "if(lo<=hi){do{" ++ assign "lst" (jsCons "hi" "lst") ++ "}while(hi-->lo)}" ++
175 ret "lst"
177binop (o:p) e1 e2
178 | isAlpha o || '_' == o = (o:p) ++ parens e1 ++ parens e2
179 | otherwise = case o:p of
180 ":" -> jsCons e1 e2
181 "++" -> append e1 e2
182 "$" -> e1 ++ parens e2
183 "." -> jsFunc "x" . ret $ e1 ++ parens (e2 ++ parens "x")
184 "^" -> "Math.pow(" ++ e1 ++ "," ++ e2 ++ ")"
185 "==" -> "eq(" ++ e1 ++ "," ++ e2 ++ ")"
186 "/=" -> "not(eq(" ++ e1 ++ "," ++ e2 ++ "))"
187 "<" -> "(compare(" ++ e1 ++ ")(" ++ e2 ++ ")[0] === 'LT')"
188 ">" -> "(compare(" ++ e1 ++ ")(" ++ e2 ++ ")[0] === 'GT')"
189 "<=" -> "function() { var ord = compare(" ++ e1 ++ ")(" ++ e2 ++ ")[0]; return ord === 'LT' || ord === 'EQ'; }()"
190 ">=" -> "function() { var ord = compare(" ++ e1 ++ ")(" ++ e2 ++ ")[0]; return ord === 'GT' || ord === 'EQ'; }()"
191 _ -> parens (e1 ++ (o:p) ++ e2)
193append e1 e2 = "Value.append" ++ parens (e1 ++ "," ++ e2)