2module CompileToJS (showErr, jsModule) where
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
14import Rename (derename)
18showErr :: String -> String
19showErr err = mainEquals $ "text(monospace(" ++ msg ++ "))"
20 where msg = show . concatMap (++"<br>") . lines $ err
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);"
48 where msg | escapees /= [] = concat [ "<br/><br/>The problem may stem from an improper usage of:<br/>"
49 , intercalate ", " $ map (concatMap escape) escapees ]
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"]
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
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 []) = jsImport' (modul, Hiding [])
94jsImport' (modul, Importing vs) =
95 concatMap (\v -> assign v $ modul ++ "." ++ v) vs
96jsImport' (modul, Hiding vs) =
97 concat [ assign "hiddenVars" . jsList $ map (\v -> "'" ++ v ++ "'") vs
98 , "\nfor(var i in " ++ modul ++ "){"
99 , indent $ "\nif (hiddenVars.indexOf(i) >= 0) continue;"
100 , indent $ globalAssign "this[i]" $ modul ++ "[i]"
103stmtsToJS :: [Statement] -> String
104stmtsToJS stmts = concatMap stmtToJS (sortBy cmpStmt stmts)
105 where cmpStmt s1 s2 = compare (valueOf s1) (valueOf s2)
106 valueOf s = case s of Datatype _ _ _ -> 1
107 ImportEvent _ _ _ _ -> 3
110 ExportEvent _ _ _ -> 5
112stmtToJS :: Statement -> String
113stmtToJS (Def name [] e) = assign name (toJS e)
114stmtToJS (Def name (a:as) e) = "\nfunction " ++ name ++ parens a ++
115 braces (indent . ret . toJS $ foldr Lambda e as) ++ ";"
116stmtToJS (Datatype _ _ tcs) = concatMap (stmtToJS . toDef) tcs
117 where toDef (name,args) = Def name vars $ Data (derename name) (map Var vars)
118 where vars = map (('a':) . show) [1..length args]
119stmtToJS (ImportEvent js base elm _) =
120 concat [ "\nvar " ++ elm ++ " = Elm.Input(" ++ toJS base ++ ");"
121 , "\nSignal.addListener(document, '" ++ js
122 , "', function(e) { Dispatcher.notify(" ++ elm
123 , ".id, e.value); });" ]
124stmtToJS (ExportEvent js elm _) =
125 concat [ "\nlift(function(v) { var e = document.createEvent('Event');"
126 , "e.initEvent('" ++ js ++ "', true, true);"
128 , "document.dispatchEvent(e); return v; })(" ++ elm ++ ");"
134toJS' :: Expr -> GuidCounter String
137 IntNum n -> return $ show n
138 FloatNum n -> return $ show n
140 Chr c -> return $ show c
141 Str s -> return $ "Value.str" ++ parens (show s)
142 Boolean b -> return $ if b then "true" else "false"
143 Range lo hi -> jsRange `liftM` toJS' lo `ap` toJS' hi
144 Access e lbl -> (\s -> s ++ "." ++ lbl) `liftM` toJS' e
145 Binop op e1 e2 -> binop op `liftM` toJS' e1 `ap` toJS' e2
146 If eb et ef -> parens `liftM` (iff `liftM` toJS' eb `ap` toJS' et `ap` toJS' ef)
147 Lambda v e -> liftM (jsFunc v . ret) (toJS' e)
148 App (Var "toText") (Str s) -> return $ "toText" ++ parens (show s)
149 App (Var "link") (Str s) -> return $ "link(" ++ show s ++ ")"
150 App (Var "plainText") (Str s) -> return $ "plainText(" ++ show s ++ ")"
151 App e1 e2 -> (++) `liftM` (toJS' e1) `ap` (parens `liftM` toJS' e2)
152 Let defs e -> jsLet defs e
153 Case e cases -> caseToJS e cases
154 Data name es -> (\ss -> jsList $ show name : ss) `liftM` mapM toJS' es
155 Markdown doc -> return $ "text('" ++ pad ++ md ++ pad ++ "')"
156 where md = formatMarkdown $ Pan.writeHtmlString Pan.defaultWriterOptions doc
157 pad = "<div style=\"height:0;width:0;\"> </div>"
159formatMarkdown = concatMap f
166 body <- (++) `liftM` jsDefs defs `ap` (ret `liftM` toJS' e')
167 return $ jsFunc "" body ++ "()"
169jsDefs defs = concat `liftM` mapM toDef (sortBy f defs)
170 where f a b = compare (valueOf a) (valueOf b)
171 valueOf (Definition _ args _) = min 1 (length args)
172 toDef (Definition x [] e) = assign x `liftM` toJS' e
173 toDef (Definition f (a:as) e) = do
174 out <- toJS' $ foldr Lambda e as
175 return $ "\nfunction " ++ f ++ parens a ++ braces (indent $ ret out) ++ ";"
178 match <- caseToMatch ps
180 (match',stmt) <- case (match,e) of
181 (Match name _ _, Var x) -> return (matchSubst [(name,x)] match, "")
182 (Match name _ _, _ ) -> return (match, assign name e')
183 _ -> liftM (\n -> (match, e')) guid
184 matches <- matchToJS match'
185 return $ concat [ "function(){", stmt, matches, "}()" ]
187matchToJS (Match name clauses def) = do
188 cases <- concat `liftM` mapM (clauseToJS name) clauses
189 finally <- matchToJS def
190 return $ concat [ "\nswitch(", name, "[0]){", indent cases, "\n}", finally ]
191matchToJS Fail = return "\nthrow \"Non-exhaustive pattern match in case\";"
192matchToJS Break = return "break;"
193matchToJS (Other e) = ret `liftM` toJS' e
194matchToJS (Seq ms) = concat `liftM` mapM matchToJS ms
196clauseToJS var (Clause name vars e) = do
197 let vars' = map (\n -> var ++ "[" ++ show n ++ "]") [ 1 .. length vars ]
198 s <- matchToJS $ matchSubst (zip vars vars') e
199 return $ concat [ "\ncase ", show name, ":", s ]
202jsCons e1 e2 = jsList [ show "Cons", e1, e2 ]
203jsRange e1 e2 = (++"()") . jsFunc "" $
204 assign "lo" e1 ++ assign "hi" e2 ++ assign "lst" jsNil ++
205 "if(lo<=hi){do{" ++ assign "lst" (jsCons "hi" "lst") ++ "}while(hi-->lo)}" ++
209 | isAlpha o || '_' == o = (o:p) ++ parens e1 ++ parens e2
210 | otherwise = case o:p of
213 "$" -> e1 ++ parens e2
214 "." -> jsFunc "x" . ret $ e1 ++ parens (e2 ++ parens "x")
215 "^" -> "Math.pow(" ++ e1 ++ "," ++ e2 ++ ")"
216 "==" -> "eq(" ++ e1 ++ "," ++ e2 ++ ")"
217 "/=" -> "not(eq(" ++ e1 ++ "," ++ e2 ++ "))"
218 "<" -> "(compare(" ++ e1 ++ ")(" ++ e2 ++ ")[0] === 'LT')"
219 ">" -> "(compare(" ++ e1 ++ ")(" ++ e2 ++ ")[0] === 'GT')"
220 "<=" -> "function() { var ord = compare(" ++ e1 ++ ")(" ++ e2 ++ ")[0]; return ord === 'LT' || ord === 'EQ'; }()"
221 ">=" -> "function() { var ord = compare(" ++ e1 ++ ")(" ++ e2 ++ ")[0]; return ord === 'GT' || ord === 'EQ'; }()"
222 ">>>" -> "composeAuto(" ++ e1 ++ ")(" ++ e2 ++ ")"
223 "<<<" -> "composeAuto(" ++ e2 ++ ")(" ++ e1 ++ ")"
224 _ -> parens (e1 ++ (o:p) ++ e2)
226append e1 e2 = "Value.append" ++ parens (e1 ++ "," ++ e2)
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list