on 09bbada help sign in
elk/elm/src/Gen/CompileToJS.hs
225 lines 10 kB history raw
2module CompileToJS (showErr, jsModule) where
4import Ast
5import Control.Arrow (first)
6import Control.Monad (liftM,(<=<),join,ap)
7import Data.Char (isAlpha,isDigit)
8import Data.List (intercalate,sortBy,inits,foldl')
9import Data.Map (toList)
10import Data.Maybe (mapMaybe)
11import qualified Text.Pandoc as Pan
13import Initialize
14import Rename (derename)
15import Cases
16import Guid
18showErr :: String -> String
19showErr err = mainEquals $ "text(monospace(" ++ msg ++ "))"
20 where msg = show . concatMap (++"<br>") . lines $ err
22indent = concatMap f
23 where f '\n' = "\n "
24 f c = [c]
26parens s = "(" ++ s ++ ")"
27braces s = "{" ++ s ++ "}"
28jsList ss = "["++ intercalate "," ss ++"]"
29jsFunc args body = "function(" ++ args ++ "){" ++ indent body ++ "}"
30assign x e = "\nvar " ++ x ++ "=" ++ e ++ ";"
31ret e = "\nreturn "++ e ++";"
32iff a b c = a ++ "?" ++ b ++ ":" ++ c
34mainEquals s = globalAssign "Elm.main" (jsFunc "" (ret s))
35globalAssign m s = "\n" ++ m ++ "=" ++ s ++ ";"
37tryBlock escapees names e =
38 concat [ "\ntry{\n" ++ e ++ "\n} catch (e) {"
39 , "Elm.main=function() {"
40 , "var msg = ('<br/><h2>Your browser may not be supported. " ++
41 "Are you using a modern browser?</h2>' +" ++
42 " '<br/><span style=\"color:grey\">Runtime Error in " ++
43 intercalate "." names ++ " module:<br/>' + e + '" ++ msg ++ "</span>');"
44 , "document.body.innerHTML = Text.monospace(msg);"
45 , "throw e;"
46 , "};}"
47 ]
48 where msg | escapees /= [] = concat [ "<br/><br/>The problem may stem from an improper usage of:<br/>"
49 , intercalate ", " $ map (concatMap escape) escapees ]
50 | otherwise = ""
51 escape '\'' = "\\'"
52 escape '"' = "\\\""
53 escape c = [c]
56jsModule (escapees, Module names exports imports stmts) =
57 tryBlock escapees (tail modNames) $ concat
58 [ "\nfor(var i in Elm) { this[i] = Elm[i]; }"
59 , concatMap (\n -> globalAssign n $ n ++ " || {}") .
60 map (intercalate ".") . drop 2 . inits $
61 take (length modNames - 1) modNames
62 , "\nif (" ++ modName ++ ") throw \"Module name collision, '" ++
63 intercalate "." (tail modNames) ++ "' is already defined.\"; "
64 , globalAssign modName $ jsFunc "" (includes ++body++ export) ++ "()"
65 , mainEquals $ modName ++ ".main" ]
66 where modNames = if null names then ["Elm", "Main"]
67 else "Elm" : names
68 modName = intercalate "." modNames
69 includes = concatMap jsImport $ map (first ("Elm."++)) imports
70 body = stmtsToJS stmts
71 export = getExports exports stmts
72 exps = if null exports then ["main"] else exports
74getExports names stmts = ret . braces $ intercalate "," pairs
75 where pairs = mapMaybe pair $ concatMap get stmts
76 pair x = if null names || y `elem` names then
77 Just $ y ++ ":" ++ x else Nothing
78 where y = derename x
79 get s = case s of Def x _ _ -> [x]
80 Datatype _ _ tcs -> map fst tcs
81 ImportEvent _ _ x _ -> [x]
82 ExportEvent _ _ _ -> []
85jsImport (modul, how) =
86 concat [ "\ntry{if (!(" ++ modul ++ " instanceof Object)) throw 'module not found'; } catch(e) {throw \"Module '"
87 , drop 1 (dropWhile (/='.') modul)
88 , "' is missing. Compile with --make flag or load missing "
89 , "module in a separate JavaScript file.\";}" ] ++
90 jsImport' (modul, how)
92jsImport' (modul, As name) = assign name modul
93jsImport' (modul, Importing vs) =
94 concatMap (\v -> assign v $ modul ++ "." ++ v) vs
95jsImport' (modul, Hiding vs) =
96 concat [ assign "hiddenVars" . jsList $ map (\v -> "'" ++ v ++ "'") vs
97 , "\nfor(var i in " ++ modul ++ "){"
98 , indent $ "\nif (hiddenVars.indexOf(i) >= 0) continue;"
99 , indent $ globalAssign "this[i]" $ modul ++ "[i]"
100 , "}" ]
102stmtsToJS :: [Statement] -> String
103stmtsToJS stmts = concatMap stmtToJS (sortBy cmpStmt stmts)
104 where cmpStmt s1 s2 = compare (valueOf s1) (valueOf s2)
105 valueOf s = case s of Datatype _ _ _ -> 1
106 ImportEvent _ _ _ _ -> 3
107 Def _ [] _ -> 3
108 Def _ _ _ -> 4
109 ExportEvent _ _ _ -> 5
111stmtToJS :: Statement -> String
112stmtToJS (Def name [] e) = assign name (toJS e)
113stmtToJS (Def name (a:as) e) = "\nfunction " ++ name ++ parens a ++
114 braces (indent . ret . toJS $ foldr Lambda e as) ++ ";"
115stmtToJS (Datatype _ _ tcs) = concatMap (stmtToJS . toDef) tcs
116 where toDef (name,args) = Def name vars $ Data (derename name) (map Var vars)
117 where vars = map (('a':) . show) [1..length args]
118stmtToJS (ImportEvent js base elm _) =
119 concat [ "\nvar " ++ elm ++ " = Elm.Signal.constant(" ++ toJS base ++ ");"
120 , "\nValue.addListener(document, '" ++ js
121 , "', function(e) { Dispatcher.notify(" ++ elm
122 , ".id, e.value); });" ]
123stmtToJS (ExportEvent js elm _) =
124 concat [ "\nlift(function(v) { var e = document.createEvent('Event');"
125 , "e.initEvent('" ++ js ++ "', true, true);"
126 , "e.value = v;"
127 , "document.dispatchEvent(e); return v; })(" ++ elm ++ ");"
128 ]
131toJS = run . toJS'
133toJS' :: Expr -> GuidCounter String
134toJS' expr =
135 case expr of
136 IntNum n -> return $ show n
137 FloatNum n -> return $ show n
138 Var x -> return $ x
139 Chr c -> return $ show c
140 Str s -> return $ "Value.str" ++ parens (show s)
141 Boolean b -> return $ if b then "true" else "false"
142 Range lo hi -> jsRange `liftM` toJS' lo `ap` toJS' hi
143 Access e lbl -> (\s -> s ++ "." ++ lbl) `liftM` toJS' e
144 Binop op e1 e2 -> binop op `liftM` toJS' e1 `ap` toJS' e2
145 If eb et ef -> parens `liftM` (iff `liftM` toJS' eb `ap` toJS' et `ap` toJS' ef)
146 Lambda v e -> liftM (jsFunc v . ret) (toJS' e)
147 App (Var "toText") (Str s) -> return $ "toText" ++ parens (show s)
148 App (Var "link") (Str s) -> return $ "link(" ++ show s ++ ")"
149 App (Var "plainText") (Str s) -> return $ "plainText(" ++ show s ++ ")"
150 App e1 e2 -> (++) `liftM` (toJS' e1) `ap` (parens `liftM` toJS' e2)
151 Let defs e -> jsLet defs e
152 Case e cases -> caseToJS e cases
153 Data name es -> (\ss -> jsList $ show name : ss) `liftM` mapM toJS' es
154 Markdown doc -> return $ "text('" ++ pad ++ md ++ pad ++ "')"
155 where md = formatMarkdown $ Pan.writeHtmlString Pan.defaultWriterOptions doc
156 pad = "<div style=\"height:0;width:0;\">&nbsp;</div>"
158formatMarkdown = concatMap f
159 where f '\'' = "\\'"
160 f '\n' = "\\n"
161 f '"' = "\""
162 f c = [c]
164jsLet defs e' = do
165 body <- (++) `liftM` jsDefs defs `ap` (ret `liftM` toJS' e')
166 return $ jsFunc "" body ++ "()"
168jsDefs defs = concat `liftM` mapM toDef (sortBy f defs)
169 where f a b = compare (valueOf a) (valueOf b)
170 valueOf (Definition _ args _) = min 1 (length args)
171 toDef (Definition x [] e) = assign x `liftM` toJS' e
172 toDef (Definition f (a:as) e) = do
173 out <- toJS' $ foldr Lambda e as
174 return $ "\nfunction " ++ f ++ parens a ++ braces (indent $ ret out) ++ ";"
176caseToJS e ps = do
177 match <- caseToMatch ps
178 e' <- toJS' e
179 (match',stmt) <- case (match,e) of
180 (Match name _ _, Var x) -> return (matchSubst [(name,x)] match, "")
181 (Match name _ _, _ ) -> return (match, assign name e')
182 _ -> liftM (\n -> (match, e')) guid
183 matches <- matchToJS match'
184 return $ concat [ "function(){", stmt, matches, "}()" ]
186matchToJS (Match name clauses def) = do
187 cases <- concat `liftM` mapM (clauseToJS name) clauses
188 finally <- matchToJS def
189 return $ concat [ "\nswitch(", name, "[0]){", indent cases, "\n}", finally ]
190matchToJS Fail = return "\nthrow \"Non-exhaustive pattern match in case\";"
191matchToJS Break = return "break;"
192matchToJS (Other e) = ret `liftM` toJS' e
193matchToJS (Seq ms) = concat `liftM` mapM matchToJS ms
195clauseToJS var (Clause name vars e) = do
196 let vars' = map (\n -> var ++ "[" ++ show n ++ "]") [ 1 .. length vars ]
197 s <- matchToJS $ matchSubst (zip vars vars') e
198 return $ concat [ "\ncase ", show name, ":", s ]
200jsNil = "[\"Nil\"]"
201jsCons e1 e2 = jsList [ show "Cons", e1, e2 ]
202jsRange e1 e2 = (++"()") . jsFunc "" $
203 assign "lo" e1 ++ assign "hi" e2 ++ assign "lst" jsNil ++
204 "if(lo<=hi){do{" ++ assign "lst" (jsCons "hi" "lst") ++ "}while(hi-->lo)}" ++
205 ret "lst"
207binop (o:p) e1 e2
208 | isAlpha o || '_' == o = (o:p) ++ parens e1 ++ parens e2
209 | otherwise = case o:p of
210 ":" -> jsCons e1 e2
211 "++" -> append e1 e2
212 "$" -> e1 ++ parens e2
213 "." -> jsFunc "x" . ret $ e1 ++ parens (e2 ++ parens "x")
214 "^" -> "Math.pow(" ++ e1 ++ "," ++ e2 ++ ")"
215 "==" -> "eq(" ++ e1 ++ "," ++ e2 ++ ")"
216 "/=" -> "not(eq(" ++ e1 ++ "," ++ e2 ++ "))"
217 "<" -> "(compare(" ++ e1 ++ ")(" ++ e2 ++ ")[0] === 'LT')"
218 ">" -> "(compare(" ++ e1 ++ ")(" ++ e2 ++ ")[0] === 'GT')"
219 "<=" -> "function() { var ord = compare(" ++ e1 ++ ")(" ++ e2 ++ ")[0]; return ord === 'LT' || ord === 'EQ'; }()"
220 ">=" -> "function() { var ord = compare(" ++ e1 ++ ")(" ++ e2 ++ ")[0]; return ord === 'GT' || ord === 'EQ'; }()"
221 ">>>" -> "composeAuto(" ++ e1 ++ ")(" ++ e2 ++ ")"
222 "<<<" -> "composeAuto(" ++ e2 ++ ")(" ++ e1 ++ ")"
223 _ -> parens (e1 ++ (o:p) ++ e2)
225append e1 e2 = "Value.append" ++ parens (e1 ++ "," ++ e2)