2module CompileToJS (showErr, jsModule) where
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)
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 escapees 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 + '" ++ msg ++ "</span>');"
37 , "document.body.innerHTML = Text.monospace(msg);"
41 where msg | escapees /= [] = concat [ "<br/><br/>The problem may stem from an improper usage of:<br/>"
42 , intercalate ", " escapees ]
45jsModule (escapees, Module names exports imports stmts) =
46 tryBlock escapees (tail modNames) $ concat
47 [ concatMap (\n -> globalAssign n $ n ++ " || {}") .
48 map (intercalate ".") . drop 2 . inits $
49 take (length modNames - 1) modNames
50 , "\nif (" ++ modName ++ ") throw \"Module name collision, '" ++
51 intercalate "." (tail modNames) ++ "' is already defined.\"; "
52 , globalAssign modName $ jsFunc "" (includes ++body++ export) ++ "()"
53 , mainEquals $ modName ++ ".main" ]
54 where modNames = if null names then ["ElmCode", "Main"]
55 else "ElmCode" : names
56 modName = intercalate "." modNames
57 includes = concatMap jsImport $ map (first ("ElmCode."++)) imports
58 body = stmtsToJS stmts
59 export = getExports exps stmts
60 exps = if null exports then ["main"] else exports
62getExports names stmts = ret . braces $ intercalate "," pairs
63 where pairs = mapMaybe pair $ concatMap get stmts
64 pair x = if y `elem` names then Just $ y ++ ":" ++ x else Nothing
66 get s = case s of Def x _ _ -> [x]
67 Datatype _ _ tcs -> map fst tcs
68 ImportEvent _ _ x _ -> [x]
69 ExportEvent _ _ _ -> []
72jsImport (modul, how) =
73 concat [ "\ntry{" ++ modul ++ " instanceof Object} catch(e) {throw \"Module '"
74 , drop 1 (dropWhile (/='.') modul)
75 , "' is missing. Compile with --make flag or load missing "
76 , "module in a separate JavaScript file.\";}" ] ++
77 jsImport' (modul, how)
79jsImport' (modul, As name) = assign name modul
80jsImport' (modul, Importing []) = jsImport' (modul, Hiding [])
81jsImport' (modul, Importing vs) =
82 concatMap (\v -> assign v $ modul ++ "." ++ v) vs
83jsImport' (modul, Hiding vs) =
84 concat [ "\nfor(var i in " ++ modul ++ "){"
85 , assign "hiddenVars" . jsList $ map (\v -> "'" ++ v ++ "'") vs
86 , "\nif (hiddenVars.indexOf(i) >= 0) continue;"
87 , globalAssign "this[i]" $ modul ++ "[i]"
90stmtsToJS :: [Statement] -> String
91stmtsToJS stmts = concatMap stmtToJS (sortBy cmpStmt stmts)
92 where cmpStmt s1 s2 = compare (valueOf s1) (valueOf s2)
93 valueOf s = case s of Datatype _ _ _ -> 1
94 ImportEvent _ _ _ _ -> 3
97 ExportEvent _ _ _ -> 5
99stmtToJS :: Statement -> String
100stmtToJS (Def name [] e) = assign name (toJS e)
101stmtToJS (Def name (a:as) e) = "\nfunction " ++ name ++ parens a ++
102 braces (ret . toJS $ foldr Lambda e as) ++ ";"
103stmtToJS (Datatype _ _ tcs) = concatMap (stmtToJS . toDef) tcs
104 where toDef (name,args) = Def name vars $ Data (derename name) (map Var vars)
105 where vars = map (('a':) . show) [1..length args]
106stmtToJS (ImportEvent js base elm _) =
107 concat [ "\nvar " ++ elm ++ " = Elm.Input(" ++ toJS base ++ ");"
108 , "\nSignal.addListener(document, '" ++ js
109 , "', function(e) { Dispatcher.notify(" ++ elm
110 , ".id, e.value); });" ]
111stmtToJS (ExportEvent js elm _) =
112 concat [ "\nlift(function(v) { var e = document.createEvent('Event');"
113 , "e.initEvent('" ++ js ++ "', true, true);"
115 , "document.dispatchEvent(e); return v; })(" ++ elm ++ ");"
120toJS :: Expr -> String
127 Str s -> "Value.str" ++ parens (show s)
128 Boolean b -> if b then "true" else "false"
129 Range lo hi -> jsRange (toJS lo) (toJS hi)
130 Access e lbl -> toJS e ++ "." ++ lbl
131 Binop op e1 e2 -> binop op (toJS e1) (toJS e2)
132 If eb et ef -> parens $ iff (toJS eb) (toJS et) (toJS ef)
133 Lambda v e -> jsFunc v $ ret (toJS e)
134 App (Var "toText") (Str s) -> "toText" ++ parens (show s)
135 App (Var "link") (Str s) -> "link(" ++ show s ++ ")"
136 App (Var "plainText") (Str s) -> "plainText(" ++ show s ++ ")"
137 App e1 e2 -> toJS e1 ++ parens (toJS e2)
138 Let defs e -> jsLet defs e
139 Case e cases -> jsCase e cases
140 Data name es -> jsList $ show name : map toJS es
142jsLet defs e' = jsFunc "" (jsDefs defs ++ ret (toJS e')) ++ "()"
144jsDefs defs = concatMap toDef $ sortBy f defs
145 where f a b = compare (valueOf a) (valueOf b)
146 valueOf (Definition _ args _) = min 1 (length args)
147 toDef (Definition x [] e) = assign x (toJS e)
148 toDef (Definition f (a:as) e) =
149 "\nfunction " ++ f ++ parens a ++ braces (ret . toJS $ foldr Lambda e as) ++ ";"
151jsCase e [c] = jsMatch c ++ parens (toJS e)
152jsCase e cases = "(function(){" ++
153 assign "v" (toJS e) ++
154 assign "c" jsCases ++
155 "for(var i=c.length;i--;){" ++
156 assign "r" "c[i](v)" ++
157 "if(r!==undefined){return r;}}}())"
158 where jsCases = jsList $ map jsMatch (reverse cases)
160jsMatch (p,e) = jsFunc "v" . match p "v" . ret $ toJS e
164 PVar x -> assign x v ++ hole
166 "if(" ++ show name ++ "!==" ++ v ++
167 "[0]){return undefined;}else{"++body++"}"
168 where matches = zipWith match ps vs
169 vs = map (\i -> v++"["++show (i+1)++"]") [0..length ps-1]
170 body = foldr ($) hole matches
173jsCons e1 e2 = jsList [ show "Cons", e1, e2 ]
174jsRange e1 e2 = (++"()") . jsFunc "" $
175 assign "lo" e1 ++ assign "hi" e2 ++ assign "lst" jsNil ++
176 "if(lo<=hi){do{" ++ assign "lst" (jsCons "hi" "lst") ++ "}while(hi-->lo)}" ++
180 | isAlpha o || '_' == o = (o:p) ++ parens e1 ++ parens e2
181 | otherwise = case o:p of
184 "$" -> e1 ++ parens e2
185 "." -> jsFunc "x" . ret $ e1 ++ parens (e2 ++ parens "x")
186 "^" -> "Math.pow(" ++ e1 ++ "," ++ e2 ++ ")"
187 "==" -> "eq(" ++ e1 ++ "," ++ e2 ++ ")"
188 "/=" -> "not(eq(" ++ e1 ++ "," ++ e2 ++ "))"
189 "<" -> "(compare(" ++ e1 ++ ")(" ++ e2 ++ ")[0] === 'LT')"
190 ">" -> "(compare(" ++ e1 ++ ")(" ++ e2 ++ ")[0] === 'GT')"
191 "<=" -> "function() { var ord = compare(" ++ e1 ++ ")(" ++ e2 ++ ")[0]; return ord === 'LT' || ord === 'EQ'; }()"
192 ">=" -> "function() { var ord = compare(" ++ e1 ++ ")(" ++ e2 ++ ")[0]; return ord === 'GT' || ord === 'EQ'; }()"
193 _ -> parens (e1 ++ (o:p) ++ e2)
195append 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