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