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
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);"
44 where msg | escapees /= [] = concat [ "<br/><br/>The problem may stem from an improper usage of:<br/>"
45 , intercalate ", " $ map (concatMap escape) escapees ]
52jsModule (escapees, Module names exports imports stmts) =
53 tryBlock escapees (tail modNames) $ concat
54 [ concatMap (\n -> globalAssign n $ n ++ " || {}") .
55 map (intercalate ".") . drop 2 . inits $
56 take (length modNames - 1) modNames
57 , "\nif (" ++ modName ++ ") throw \"Module name collision, '" ++
58 intercalate "." (tail modNames) ++ "' is already defined.\"; "
59 , globalAssign modName $ jsFunc "" (includes ++body++ export) ++ "()"
60 , mainEquals $ modName ++ ".main" ]
61 where modNames = if null names then ["ElmCode", "Main"]
62 else "ElmCode" : names
63 modName = intercalate "." modNames
64 includes = concatMap jsImport $ map (first ("ElmCode."++)) imports
65 body = stmtsToJS stmts
66 export = getExports exports stmts
67 exps = if null exports then ["main"] else exports
69getExports names stmts = ret . braces $ intercalate "," pairs
70 where pairs = mapMaybe pair $ concatMap get stmts
71 pair x = if null names || y `elem` names then
72 Just $ y ++ ":" ++ x else Nothing
74 get s = case s of Def x _ _ -> [x]
75 Datatype _ _ tcs -> map fst tcs
76 ImportEvent _ _ x _ -> [x]
77 ExportEvent _ _ _ -> []
80jsImport (modul, how) =
81 concat [ "\ntry{if (!(" ++ modul ++ " instanceof Object)) throw 'module not found'; } catch(e) {throw \"Module '"
82 , drop 1 (dropWhile (/='.') modul)
83 , "' is missing. Compile with --make flag or load missing "
84 , "module in a separate JavaScript file.\";}" ] ++
85 jsImport' (modul, how)
87jsImport' (modul, As name) = assign name modul
88jsImport' (modul, Importing []) = jsImport' (modul, Hiding [])
89jsImport' (modul, Importing vs) =
90 concatMap (\v -> assign v $ modul ++ "." ++ v) vs
91jsImport' (modul, Hiding vs) =
92 concat [ assign "hiddenVars" . jsList $ map (\v -> "'" ++ v ++ "'") vs
93 , "\nfor(var i in " ++ modul ++ "){"
94 , "\nif (hiddenVars.indexOf(i) >= 0) continue;"
95 , globalAssign "this[i]" $ modul ++ "[i]"
98stmtsToJS :: [Statement] -> String
99stmtsToJS stmts = concatMap stmtToJS (sortBy cmpStmt stmts)
100 where cmpStmt s1 s2 = compare (valueOf s1) (valueOf s2)
101 valueOf s = case s of Datatype _ _ _ -> 1
102 ImportEvent _ _ _ _ -> 3
105 ExportEvent _ _ _ -> 5
107stmtToJS :: Statement -> String
108stmtToJS (Def name [] e) = assign name (toJS e)
109stmtToJS (Def name (a:as) e) = "\nfunction " ++ name ++ parens a ++
110 braces (ret . toJS $ foldr Lambda e as) ++ ";"
111stmtToJS (Datatype _ _ tcs) = concatMap (stmtToJS . toDef) tcs
112 where toDef (name,args) = Def name vars $ Data (derename name) (map Var vars)
113 where vars = map (('a':) . show) [1..length args]
114stmtToJS (ImportEvent js base elm _) =
115 concat [ "\nvar " ++ elm ++ " = Elm.Input(" ++ toJS base ++ ");"
116 , "\nSignal.addListener(document, '" ++ js
117 , "', function(e) { Dispatcher.notify(" ++ elm
118 , ".id, e.value); });" ]
119stmtToJS (ExportEvent js elm _) =
120 concat [ "\nlift(function(v) { var e = document.createEvent('Event');"
121 , "e.initEvent('" ++ js ++ "', true, true);"
123 , "document.dispatchEvent(e); return v; })(" ++ elm ++ ");"
129toJS' :: Expr -> GuidCounter String
132 IntNum n -> return $ show n
133 FloatNum n -> return $ show n
135 Chr c -> return $ show c
136 Str s -> return $ "Value.str" ++ parens (show s)
137 Boolean b -> return $ if b then "true" else "false"
138 Range lo hi -> jsRange `liftM` toJS' lo `ap` toJS' hi
139 Access e lbl -> (\s -> s ++ "." ++ lbl) `liftM` toJS' e
140 Binop op e1 e2 -> binop op `liftM` toJS' e1 `ap` toJS' e2
141 If eb et ef -> parens `liftM` (iff `liftM` toJS' eb `ap` toJS' et `ap` toJS' ef)
142 Lambda v e -> liftM (jsFunc v . ret) (toJS' e)
143 App (Var "toText") (Str s) -> return $ "toText" ++ parens (show s)
144 App (Var "link") (Str s) -> return $ "link(" ++ show s ++ ")"
145 App (Var "plainText") (Str s) -> return $ "plainText(" ++ show s ++ ")"
146 App e1 e2 -> (++) `liftM` (toJS' e1) `ap` (parens `liftM` toJS' e2)
147 Let defs e -> jsLet defs e
148 Case e cases -> caseToJS e cases
149 Data name es -> (\ss -> jsList $ show name : ss) `liftM` mapM toJS' es
150 Markdown doc -> return $ "text('" ++ pad ++ md ++ pad ++ "')"
151 where md = formatMarkdown $ Pan.writeHtmlString Pan.defaultWriterOptions doc
152 pad = "<div style=\"height:0;width:0;\"> </div>"
154formatMarkdown = concatMap f
161 body <- (++) `liftM` jsDefs defs `ap` (ret `liftM` toJS' e')
162 return $ jsFunc "" body ++ "()"
164jsDefs defs = concat `liftM` mapM toDef (sortBy f defs)
165 where f a b = compare (valueOf a) (valueOf b)
166 valueOf (Definition _ args _) = min 1 (length args)
167 toDef (Definition x [] e) = assign x `liftM` toJS' e
168 toDef (Definition f (a:as) e) = do
169 out <- toJS' $ foldr Lambda e as
170 return $ "\nfunction " ++ f ++ parens a ++ braces (ret out) ++ ";"
173 match <- caseToMatch ps
174 var <- liftM (\n -> "case" ++ show n) guid
175 matches <- matchToJS var match
177 return $ concat [ "function(", var, "){"
178 , case match of { Match name _ _ -> assign name var ; _ -> "" }
182matchToJS v (Match name clauses def) = do
183 cases <- concat `liftM` mapM (clauseToJS name) clauses
184 finally <- matchToJS v def
185 return $ concat [ "\nswitch(", name, "[0]){", cases, "\n}", finally ]
186matchToJS _ Fail = return "\nthrow \"Non-exhaustive pattern match in case\";"
187matchToJS _ Break = return "break;"
188matchToJS _ (Other e) = ret `liftM` toJS' e
189matchToJS v (Seq ms) = concat `liftM` mapM (matchToJS v) ms
191clauseToJS var (Clause name vars e) = do
193 return $ concat [ "\ncase ", show name, ":"
196 where toDef v n = v ++ "=" ++ var ++ "[" ++ show n ++ "]"
197 defs = case vars of [] -> ""
198 _ -> ("\nvar "++) . (++";") . intercalate "," $
199 zipWith toDef vars [ 1 .. length vars ]
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