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 ", " escapees ]
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 exps 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 y `elem` names then Just $ y ++ ":" ++ x else Nothing
69 get s = case s of Def x _ _ -> [x]
70 Datatype _ _ tcs -> map fst tcs
71 ImportEvent _ _ x _ -> [x]
72 ExportEvent _ _ _ -> []
75jsImport (modul, how) =
76 concat [ "\ntry{" ++ modul ++ " instanceof Object} catch(e) {throw \"Module '"
77 , drop 1 (dropWhile (/='.') modul)
78 , "' is missing. Compile with --make flag or load missing "
79 , "module in a separate JavaScript file.\";}" ] ++
80 jsImport' (modul, how)
82jsImport' (modul, As name) = assign name modul
83jsImport' (modul, Importing []) = jsImport' (modul, Hiding [])
84jsImport' (modul, Importing vs) =
85 concatMap (\v -> assign v $ modul ++ "." ++ v) vs
86jsImport' (modul, Hiding vs) =
87 concat [ assign "hiddenVars" . jsList $ map (\v -> "'" ++ v ++ "'") vs
88 , "\nfor(var i in " ++ modul ++ "){"
89 , "\nif (hiddenVars.indexOf(i) >= 0) continue;"
90 , globalAssign "this[i]" $ modul ++ "[i]"
93stmtsToJS :: [Statement] -> String
94stmtsToJS stmts = concatMap stmtToJS (sortBy cmpStmt stmts)
95 where cmpStmt s1 s2 = compare (valueOf s1) (valueOf s2)
96 valueOf s = case s of Datatype _ _ _ -> 1
97 ImportEvent _ _ _ _ -> 3
100 ExportEvent _ _ _ -> 5
102stmtToJS :: Statement -> String
103stmtToJS (Def name [] e) = assign name (toJS e)
104stmtToJS (Def name (a:as) e) = "\nfunction " ++ name ++ parens a ++
105 braces (ret . toJS $ foldr Lambda e as) ++ ";"
106stmtToJS (Datatype _ _ tcs) = concatMap (stmtToJS . toDef) tcs
107 where toDef (name,args) = Def name vars $ Data (derename name) (map Var vars)
108 where vars = map (('a':) . show) [1..length args]
109stmtToJS (ImportEvent js base elm _) =
110 concat [ "\nvar " ++ elm ++ " = Elm.Input(" ++ toJS base ++ ");"
111 , "\nSignal.addListener(document, '" ++ js
112 , "', function(e) { Dispatcher.notify(" ++ elm
113 , ".id, e.value); });" ]
114stmtToJS (ExportEvent js elm _) =
115 concat [ "\nlift(function(v) { var e = document.createEvent('Event');"
116 , "e.initEvent('" ++ js ++ "', true, true);"
118 , "document.dispatchEvent(e); return v; })(" ++ elm ++ ");"
124toJS' :: Expr -> GuidCounter String
127 IntNum n -> return $ show n
128 FloatNum n -> return $ show n
130 Chr c -> return $ show c
131 Str s -> return $ "Value.str" ++ parens (show s)
132 Boolean b -> return $ if b then "true" else "false"
133 Range lo hi -> jsRange `liftM` toJS' lo `ap` toJS' hi
134 Access e lbl -> (\s -> s ++ "." ++ lbl) `liftM` toJS' e
135 Binop op e1 e2 -> binop op `liftM` toJS' e1 `ap` toJS' e2
136 If eb et ef -> parens `liftM` (iff `liftM` toJS' eb `ap` toJS' et `ap` toJS' ef)
137 Lambda v e -> liftM (jsFunc v . ret) (toJS' e)
138 App (Var "toText") (Str s) -> return $ "toText" ++ parens (show s)
139 App (Var "link") (Str s) -> return $ "link(" ++ show s ++ ")"
140 App (Var "plainText") (Str s) -> return $ "plainText(" ++ show s ++ ")"
141 App e1 e2 -> (++) `liftM` (toJS' e1) `ap` (parens `liftM` toJS' e2)
142 Let defs e -> jsLet defs e
143 Case e cases -> caseToJS e cases
144 Data name es -> (\ss -> jsList $ show name : ss) `liftM` mapM toJS' es
145 Markdown doc -> return $ "text('" ++ pad ++ md ++ pad ++ "')"
146 where md = formatMarkdown $ Pan.writeHtmlString Pan.defaultWriterOptions doc
147 pad = "<div style=\"height:0;width:0;\"> </div>"
149formatMarkdown = concatMap f
156 body <- (++) `liftM` jsDefs defs `ap` (ret `liftM` toJS' e')
157 return $ jsFunc "" body ++ "()"
159jsDefs defs = concat `liftM` mapM toDef (sortBy f defs)
160 where f a b = compare (valueOf a) (valueOf b)
161 valueOf (Definition _ args _) = min 1 (length args)
162 toDef (Definition x [] e) = assign x `liftM` toJS' e
163 toDef (Definition f (a:as) e) = do
164 out <- toJS' $ foldr Lambda e as
165 return $ "\nfunction " ++ f ++ parens a ++ braces (ret out) ++ ";"
168 match <- caseToMatch ps
169 var <- liftM (\n -> "case" ++ show n) guid
170 matches <- matchToJS var match
172 return $ concat [ "function(", var, "){"
173 , case match of { Match name _ _ -> assign name var ; _ -> "" }
177matchToJS v (Match name clauses def) = do
178 cases <- concat `liftM` mapM (clauseToJS name) clauses
179 finally <- matchToJS v def
180 return $ concat [ "\nswitch(", name, "[0]){", cases, "\n}", finally ]
181matchToJS _ Fail = return "\nthrow \"Non-exhaustive pattern match in case\";"
182matchToJS _ Break = return "break;"
183matchToJS _ (Other e) = ret `liftM` toJS' e
184matchToJS v (Seq ms) = concat `liftM` mapM (matchToJS v) ms
186clauseToJS var (Clause name vars e) = do
188 return $ concat [ "\ncase ", show name, ":"
191 where toDef v n = v ++ "=" ++ var ++ "[" ++ show n ++ "]"
192 defs = case vars of [] -> ""
193 _ -> ("\nvar "++) . (++";") . intercalate "," $
194 zipWith toDef vars [ 1 .. length vars ]
197jsCons e1 e2 = jsList [ show "Cons", e1, e2 ]
198jsRange e1 e2 = (++"()") . jsFunc "" $
199 assign "lo" e1 ++ assign "hi" e2 ++ assign "lst" jsNil ++
200 "if(lo<=hi){do{" ++ assign "lst" (jsCons "hi" "lst") ++ "}while(hi-->lo)}" ++
204 | isAlpha o || '_' == o = (o:p) ++ parens e1 ++ parens e2
205 | otherwise = case o:p of
208 "$" -> e1 ++ parens e2
209 "." -> jsFunc "x" . ret $ e1 ++ parens (e2 ++ parens "x")
210 "^" -> "Math.pow(" ++ e1 ++ "," ++ e2 ++ ")"
211 "==" -> "eq(" ++ e1 ++ "," ++ e2 ++ ")"
212 "/=" -> "not(eq(" ++ e1 ++ "," ++ e2 ++ "))"
213 "<" -> "(compare(" ++ e1 ++ ")(" ++ e2 ++ ")[0] === 'LT')"
214 ">" -> "(compare(" ++ e1 ++ ")(" ++ e2 ++ ")[0] === 'GT')"
215 "<=" -> "function() { var ord = compare(" ++ e1 ++ ")(" ++ e2 ++ ")[0]; return ord === 'LT' || ord === 'EQ'; }()"
216 ">=" -> "function() { var ord = compare(" ++ e1 ++ ")(" ++ e2 ++ ")[0]; return ord === 'GT' || ord === 'EQ'; }()"
217 _ -> parens (e1 ++ (o:p) ++ e2)
219append 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