1{-# LANGUAGE PatternGuards #-}
3module IRTS.CodegenJavaScript (codegenJavaScript, codegenNode, JSTarget(..)) where
5import Idris.AbsSyntax hiding (TypeCase)
9import IRTS.CodegenCommon
15import Control.Applicative ((<$>), (<*>), pure)
22import System.Directory
26idrNamespace = "__IDR__"
27idrRTNamespace = "__IDRRT__"
28idrLTNamespace = "__IDRLT__"
29idrCTRNamespace = "__IDRCTR__"
32data JSTarget = Node | JavaScript deriving Eq
45data JSInteger = JSBigZero
57data JSWord = JSWord8 Word8
64data JSAnnotation = JSConstructor deriving Eq
67instance Show JSAnnotation where
68 show JSConstructor = "constructor"
73 | JSFunction [String] JS
80 | JSBinOp String JS JS
94 | JSAlloc String (Maybe JS)
101 | JSAnnotation JSAnnotation JS
106data FFI = FFICode Char | FFIArg Int | FFIError String
109ffi :: String -> [String] -> String
110ffi code args = let parsed = ffiParse code in
111 case ffiError parsed of
112 Just err -> error err
113 Nothing -> renderFFI parsed args
115 ffiParse :: String -> [FFI]
117 ffiParse ['%'] = [FFIError $ "FFI - Invalid positional argument"]
118 ffiParse ('%':'%':ss) = FFICode '%' : ffiParse ss
121 FFIArg (read $ s : takeWhile isDigit ss) : ffiParse (dropWhile isDigit ss)
123 [FFIError $ "FFI - Invalid positional argument"]
124 ffiParse (s:ss) = FFICode s : ffiParse ss
127 ffiError :: [FFI] -> Maybe String
128 ffiError [] = Nothing
129 ffiError ((FFIError s):xs) = Just s
130 ffiError (x:xs) = ffiError xs
133 renderFFI :: [FFI] -> [String] -> String
135 renderFFI ((FFICode c) : fs) args = c : renderFFI fs args
136 renderFFI ((FFIArg i) : fs) args
137 | i < length args && i >= 0 = args !! i ++ renderFFI fs args
138 | otherwise = error "FFI - Argument index out of bounds"
141compileJS :: JS -> String
144compileJS (JSAnnotation annotation js) =
145 "/** @" ++ show annotation ++ " */\n" ++ compileJS js
147compileJS (JSFFI raw args) =
148 ffi raw (map compileJS args)
150compileJS (JSRaw code) =
153compileJS (JSIdent ident) =
156compileJS (JSFunction args body) =
158 ++ intercalate "," args
164 | JSIntTy <- ty = idrRTNamespace ++ "Int"
165 | JSStringTy <- ty = idrRTNamespace ++ "String"
166 | JSIntegerTy <- ty = idrRTNamespace ++ "Integer"
167 | JSFloatTy <- ty = idrRTNamespace ++ "Float"
168 | JSCharTy <- ty = idrRTNamespace ++ "Char"
169 | JSPtrTy <- ty = idrRTNamespace ++ "Ptr"
170 | JSForgotTy <- ty = idrRTNamespace ++ "Forgot"
172compileJS (JSSeq seq) =
173 intercalate ";\n" (map compileJS seq)
175compileJS (JSReturn val) =
176 "return " ++ compileJS val
178compileJS (JSApp lhs rhs)
179 | JSFunction {} <- lhs =
180 concat ["(", compileJS lhs, ")(", args, ")"]
182 concat [compileJS lhs, "(", args, ")"]
184 args = intercalate "," $ map compileJS rhs
186compileJS (JSNew name args) =
187 "new " ++ name ++ "(" ++ intercalate "," (map compileJS args) ++ ")"
189compileJS (JSError exc) =
190 "throw new Error(\"" ++ exc ++ "\")"
192compileJS (JSBinOp op lhs rhs) =
193 compileJS lhs ++ " " ++ op ++ " " ++ compileJS rhs
195compileJS (JSPreOp op val) =
198compileJS (JSProj obj field)
199 | JSFunction {} <- obj =
200 concat ["(", compileJS obj, ").", field]
201 | JSAssign {} <- obj =
202 concat ["(", compileJS obj, ").", field]
204 compileJS obj ++ '.' : field
206compileJS (JSVar var) =
207 translateVariableName var
221compileJS (JSArray elems) =
222 "[" ++ intercalate "," (map compileJS elems) ++ "]"
224compileJS (JSString str) =
228 | JSInt i <- num = show i
229 | JSFloat f <- num = show f
230 | JSInteger JSBigZero <- num = "__IDRRT__ZERO"
231 | JSInteger JSBigOne <- num = "__IDRRT__ONE"
232 | JSInteger (JSBigInt i) <- num = show i
234compileJS (JSAssign lhs rhs) =
235 compileJS lhs ++ "=" ++ compileJS rhs
237compileJS (JSAlloc name val) =
238 "var " ++ name ++ maybe "" ((" = " ++) . compileJS) val
240compileJS (JSIndex lhs rhs) =
241 compileJS lhs ++ "[" ++ compileJS rhs ++ "]"
243compileJS (JSCond branches) =
244 intercalate " else " $ map createIfBlock branches
246 createIfBlock (JSNoop, e) =
250 createIfBlock (cond, e) =
251 "if (" ++ compileJS cond ++") {\n"
255compileJS (JSTernary cond true false) =
256 let c = compileJS cond
258 f = compileJS false in
259 "(" ++ c ++ ")?(" ++ t ++ "):(" ++ f ++ ")"
261compileJS (JSParens js) =
262 "(" ++ compileJS js ++ ")"
264compileJS (JSWhile cond body) =
265 "while (" ++ compileJS cond ++ ") {\n"
269compileJS (JSWord word)
270 | JSWord8 b <- word = "new Uint8Array([" ++ show b ++ "])"
271 | JSWord16 b <- word = "new Uint16Array([" ++ show b ++ "])"
272 | JSWord32 b <- word = "new Uint32Array([" ++ show b ++ "])"
273 | JSWord64 b <- word = idrRTNamespace ++ "bigInt(\"" ++ show b ++ "\")"
276jsTailcall :: JS -> JS
278 jsCall (idrRTNamespace ++ "tailcall") [
279 JSFunction [] (JSReturn call)
283jsCall :: String -> [JS] -> JS
284jsCall fun = JSApp (JSIdent fun)
287jsMeth :: JS -> String -> [JS] -> JS
289 JSApp (JSProj obj meth)
292jsInstanceOf :: JS -> JS -> JS
293jsInstanceOf = JSBinOp "instanceof"
296jsEq :: JS -> JS -> JS
300jsAnd :: JS -> JS -> JS
304jsOr :: JS -> JS -> JS
309jsType = JSIdent $ idrRTNamespace ++ "Type"
313jsCon = JSIdent $ idrRTNamespace ++ "Con"
317jsTag obj = JSProj obj "tag"
321jsTypeTag obj = JSProj obj "type"
325jsBigInt (JSString "0") = JSNum $ JSInteger JSBigZero
326jsBigInt (JSString "1") = JSNum $ JSInteger JSBigOne
327jsBigInt val = JSApp (JSIdent $ idrRTNamespace ++ "bigInt") [val]
330jsVar :: Int -> String
331jsVar = ("__var_" ++) . show
334jsLet :: String -> JS -> JS -> JS
335jsLet name value body =
343jsError :: String -> JS
344jsError err = JSApp (JSFunction [] (JSError err)) []
346jsUnPackBits :: JS -> JS
347jsUnPackBits js = JSIndex js $ JSNum (JSInt 0)
350jsPackUBits8 :: JS -> JS
351jsPackUBits8 js = JSNew "Uint8Array" [JSArray [js]]
353jsPackUBits16 :: JS -> JS
354jsPackUBits16 js = JSNew "Uint16Array" [JSArray [js]]
356jsPackUBits32 :: JS -> JS
357jsPackUBits32 js = JSNew "Uint32Array" [JSArray [js]]
359jsPackSBits8 :: JS -> JS
360jsPackSBits8 js = JSNew "Int8Array" [JSArray [js]]
362jsPackSBits16 :: JS -> JS
363jsPackSBits16 js = JSNew "Int16Array" [JSArray [js]]
365jsPackSBits32 :: JS -> JS
366jsPackSBits32 js = JSNew "Int32Array" [JSArray [js]]
369foldJS :: (JS -> a) -> (a -> a -> a) -> a -> JS -> a
370foldJS tr add acc js =
374 | JSFunction args body <- js =
375 add (tr js) (fold body)
377 add (tr js) $ foldl' add acc (map fold seq)
378 | JSReturn ret <- js =
379 add (tr js) (fold ret)
380 | JSApp lhs rhs <- js =
381 add (tr js) $ add (fold lhs) (foldl' add acc $ map fold rhs)
382 | JSNew _ args <- js =
383 add (tr js) $ foldl' add acc $ map fold args
384 | JSBinOp _ lhs rhs <- js =
385 add (tr js) $ add (fold lhs) (fold rhs)
386 | JSPreOp _ val <- js =
387 add (tr js) $ fold val
388 | JSPostOp _ val <- js =
389 add (tr js) $ fold val
390 | JSProj obj _ <- js =
391 add (tr js) (fold obj)
392 | JSArray vals <- js =
393 add (tr js) $ foldl' add acc $ map fold vals
394 | JSAssign lhs rhs <- js =
395 add (tr js) $ add (fold lhs) (fold rhs)
396 | JSIndex lhs rhs <- js =
397 add (tr js) $ add (fold lhs) (fold rhs)
398 | JSAlloc _ val <- js =
399 add (tr js) $ fromMaybe acc $ fmap fold val
400 | JSTernary c t f <- js =
401 add (tr js) $ add (fold c) (add (fold t) (fold f))
402 | JSParens val <- js =
403 add (tr js) $ fold val
404 | JSCond conds <- js =
405 add (tr js) $ foldl' add acc $ map (uncurry add . (fold *** fold)) conds
406 | JSWhile cond body <- js =
407 add (tr js) $ add (fold cond) (fold body)
408 | JSFFI raw args <- js =
409 add (tr js) $ foldl' add acc $ map fold args
410 | JSAnnotation a js <- js =
411 add (tr js) $ fold js
416transformJS :: (JS -> JS) -> JS -> JS
420 transformHelper :: JS -> JS
422 | JSFunction args body <- js = JSFunction args $ tr body
423 | JSSeq seq <- js = JSSeq $ map tr seq
424 | JSReturn ret <- js = JSReturn $ tr ret
425 | JSApp lhs rhs <- js = JSApp (tr lhs) $ map tr rhs
426 | JSNew con args <- js = JSNew con $ map tr args
427 | JSBinOp op lhs rhs <- js = JSBinOp op (tr lhs) (tr rhs)
428 | JSPreOp op val <- js = JSPreOp op (tr val)
429 | JSPostOp op val <- js = JSPostOp op (tr val)
430 | JSProj obj field <- js = JSProj (tr obj) field
431 | JSArray vals <- js = JSArray $ map tr vals
432 | JSAssign lhs rhs <- js = JSAssign (tr lhs) (tr rhs)
433 | JSAlloc var val <- js = JSAlloc var $ fmap tr val
434 | JSIndex lhs rhs <- js = JSIndex (tr lhs) (tr rhs)
435 | JSCond conds <- js = JSCond $ map (tr *** tr) conds
436 | JSTernary c t f <- js = JSTernary (tr c) (tr t) (tr f)
437 | JSParens val <- js = JSParens $ tr val
438 | JSWhile cond body <- js = JSWhile (tr cond) (tr body)
439 | JSFFI raw args <- js = JSFFI raw (map tr args)
440 | JSAnnotation a js <- js = JSAnnotation a (tr js)
444moveJSDeclToTop :: String -> [JS] -> [JS]
445moveJSDeclToTop decl js = move ([], js)
447 move :: ([JS], [JS]) -> [JS]
448 move (front, js@(JSAnnotation _ (JSAlloc name _)):back)
449 | name == decl = js : front ++ back
451 move (front, js@(JSAlloc name _):back)
452 | name == decl = js : front ++ back
454 move (front, js:back) =
455 move (front ++ [js], back)
458jsSubst :: JS -> JS -> JS -> JS
462jsSubst (JSIdent var) new (JSVar old)
463 | var == translateVariableName old = new
464 | otherwise = JSVar old
466jsSubst var new old@(JSIdent _)
470jsSubst var new (JSArray fields) =
471 JSArray (map (jsSubst var new) fields)
473jsSubst var new (JSNew con vals) =
474 JSNew con $ map (jsSubst var new) vals
476jsSubst (JSIdent var) new (JSApp (JSProj (JSFunction args body) "apply") vals)
477 | var `notElem` args =
478 JSApp (JSProj (JSFunction args (jsSubst (JSIdent var) new body)) "apply") (
479 map (jsSubst (JSIdent var) new) vals
482 JSApp (JSProj (JSFunction args body) "apply") (
483 map (jsSubst (JSIdent var) new) vals
486jsSubst (JSIdent var) new (JSApp (JSFunction [arg] body) vals)
488 JSApp (JSFunction [arg] (
489 jsSubst (JSIdent var) new body
490 )) $ map (jsSubst (JSIdent var) new) vals
492 JSApp (JSFunction [arg] (
494 )) $ map (jsSubst (JSIdent var) new) vals
496jsSubst var new js = transformJS (jsSubst var new) js
499removeAllocations :: JS -> JS
500removeAllocations (JSSeq body) =
501 let opt = removeHelper (map removeAllocations body) in
506 removeHelper :: [JS] -> [JS]
507 removeHelper [js] = [js]
508 removeHelper ((JSAlloc name (Just val@(JSIdent _))):js) =
509 map (jsSubst (JSIdent name) val) (removeHelper js)
510 removeHelper (j:js) = j : removeHelper js
512removeAllocations js = transformJS removeAllocations js
515isJSConstant :: JS -> Bool
517 | JSString _ <- js = True
518 | JSNum _ <- js = True
519 | JSType _ <- js = True
520 | JSNull <- js = True
521 | JSArray vals <- js = all isJSConstant vals
523 | JSApp (JSIdent "__IDRRT__bigInt") _ <- js = True
527isJSConstantConstructor :: [String] -> JS -> Bool
528isJSConstantConstructor constants js
531 | JSArray vals <- js =
532 all (isJSConstantConstructor constants) vals
533 | JSNew "__IDRRT__Con" args <- js =
534 all (isJSConstantConstructor constants) args
535 | JSIndex (JSProj (JSIdent name) "vars") (JSNum _) <- js
536 , name `elem` constants =
539 , name `elem` constants =
545inlineJS = inlineAssign . inlineError . inlineApply . inlineCaseMatch . inlineJSLet
547 inlineJSLet :: JS -> JS
548 inlineJSLet (JSApp (JSFunction [arg] (JSReturn ret)) [val])
549 | opt <- inlineJSLet val =
550 inlineJS $ jsSubst (JSIdent arg) opt ret
552 inlineJSLet js = transformJS inlineJSLet js
555 inlineCaseMatch (JSReturn (JSApp (JSFunction ["cse"] body) [val]))
556 | opt <- inlineCaseMatch val =
557 inlineCaseMatch $ jsSubst (JSIdent "cse") opt body
559 inlineCaseMatch js = transformJS inlineCaseMatch js
564 JSProj (JSFunction args (JSReturn body)) "apply"
565 ) [JSThis, JSProj var "vars"] <- js =
566 inlineApply $ inlineApply' var args body 0
568 JSProj (JSFunction args body@(JSCond _)) "apply"
569 ) [JSThis, JSProj var "vars"]) <- js =
570 inlineApply $ inlineApply' var args body 0
572 inlineApply' _ [] body _ = body
573 inlineApply' var (a:as) body n =
574 inlineApply' var as (
575 jsSubst (JSIdent a) (
576 JSIndex (JSProj var "vars") (JSNum (JSInt n))
580 inlineApply js = transformJS inlineApply js
583 inlineError (JSReturn (JSApp (JSFunction [] error@(JSError _)) [])) =
586 inlineError js = transformJS inlineError js
589 inlineAssign (JSAssign lhs rhs)
595 inlineAssign (JSAssign lhs rhs)
601 inlineAssign js = transformJS inlineAssign js
604removeEval :: [JS] -> [JS]
606 let (ret, isReduced) = checkEval js in
608 then removeEvalApp ret
611 removeEvalApp js = catMaybes (map removeEvalApp' js)
613 removeEvalApp' :: JS -> Maybe JS
614 removeEvalApp' (JSAlloc "__IDR__mEVAL0" _) = Nothing
615 removeEvalApp' js = Just $ transformJS match js
617 match (JSApp (JSIdent "__IDR__mEVAL0") [val]) = val
618 match js = transformJS match js
620 checkEval :: [JS] -> ([JS], Bool)
621 checkEval js = foldr f ([], False) $ map checkEval' js
623 f :: (Maybe JS, Bool) -> ([JS], Bool) -> ([JS], Bool)
624 f (Just js, isReduced) (ret, b) = (js : ret, isReduced || b)
625 f (Nothing, isReduced) (ret, b) = (ret, isReduced || b)
628 checkEval' :: JS -> (Maybe JS, Bool)
629 checkEval' (JSAlloc "__IDRLT__EVAL" (Just (JSApp (JSFunction [] (
631 , JSReturn (JSIdent "t")
633 )) []))) = (Nothing, True)
635 checkEval' js = (Just js, False)
638reduceJS :: [JS] -> [JS]
639reduceJS js = moveJSDeclToTop "__IDRRT__Con" $ reduceLoop [] ([], js)
642funName :: JS -> String
643funName (JSAlloc fun _) = fun
646elimDeadLoop :: [JS] -> [JS]
648 | ret <- deadEvalApplyCases js
649 , ret /= js = elimDeadLoop ret
653deadEvalApplyCases :: [JS] -> [JS]
654deadEvalApplyCases js =
655 let tags = sort $ nub $ concatMap (getTags) js in
656 map (removeHelper tags) js
658 getTags :: JS -> [Int]
659 getTags = foldJS match (++) []
662 | JSNew "__IDRRT__Con" [JSNum (JSInt tag), _] <- js = [tag]
666 removeHelper :: [Int] -> JS -> JS
667 removeHelper tags (JSAlloc fun (Just (
668 JSApp (JSFunction [] (JSSeq seq)) []))
671 JSApp (JSFunction [] (JSSeq $ remover tags seq)) []))
674 removeHelper _ js = js
677 remover :: [Int] -> [JS] -> [JS]
679 j@(JSAssign ((JSIndex (JSIdent "t") (JSNum (JSInt tag)))) _):js
681 | tag `notElem` tags = remover tags js
683 remover tags (j:js) = j : remover tags js
687initConstructors :: [JS] -> [JS]
689 let tags = nub $ sort $ concat (map getTags js) in
690 rearrangePrelude $ map createConstant tags ++ replaceConstructors tags js
692 rearrangePrelude :: [JS] -> [JS]
693 rearrangePrelude = moveJSDeclToTop $ idrRTNamespace ++ "Con"
696 getTags :: JS -> [Int]
697 getTags = foldJS match (++) []
700 | JSNew "__IDRRT__Con" [JSNum (JSInt tag), JSArray []] <- js = [tag]
704 replaceConstructors :: [Int] -> [JS] -> [JS]
705 replaceConstructors tags js = map (replaceHelper tags) js
707 replaceHelper :: [Int] -> JS -> JS
708 replaceHelper tags (JSNew "__IDRRT__Con" [JSNum (JSInt tag), JSArray []])
709 | tag `elem` tags = JSIdent (idrCTRNamespace ++ show tag)
711 replaceHelper tags js = transformJS (replaceHelper tags) js
714 createConstant :: Int -> JS
716 JSAlloc (idrCTRNamespace ++ show tag) (Just (
717 JSNew (idrRTNamespace ++ "Con") [JSNum (JSInt tag), JSArray []]
721removeIDs :: [JS] -> [JS]
723 case partition isID js of
725 (ids, rest) -> removeIDs $ map (removeIDCall (map idFor ids)) rest
726 where isID :: JS -> Bool
727 isID (JSAlloc _ (Just (JSFunction _ (JSSeq body))))
728 | JSReturn (JSVar _) <- last body = True
733 idFor :: JS -> (String, Int)
734 idFor (JSAlloc fun (Just (JSFunction _ (JSSeq body))))
735 | JSReturn (JSVar (Loc pos)) <- last body = (fun, pos)
738 removeIDCall :: [(String, Int)] -> JS -> JS
739 removeIDCall ids (JSApp (JSIdent "__IDRRT__tailcall") [JSFunction [] (
740 JSReturn (JSApp (JSIdent fun) args)
742 | Just pos <- lookup fun ids
743 , pos < length args = removeIDCall ids (args !! pos)
745 removeIDCall ids (JSNew _ [JSFunction [] (
746 JSReturn (JSApp (JSIdent fun) args)
748 | Just pos <- lookup fun ids
749 , pos < length args = removeIDCall ids (args !! pos)
751 removeIDCall ids js@(JSApp id@(JSIdent fun) args)
752 | Just pos <- lookup fun ids
753 , pos < length args = removeIDCall ids (args !! pos)
755 removeIDCall ids js = transformJS (removeIDCall ids) js
758inlineFunction :: String -> [String] -> JS -> JS -> JS
759inlineFunction fun args body js = inline' js
762 inline' (JSApp (JSIdent name) vals)
764 let (js, phs) = insertPlaceHolders args body in
765 inline' $ foldr (uncurry jsSubst) js (zip phs vals)
767 inline' js = transformJS inline' js
769 insertPlaceHolders :: [String] -> JS -> (JS, [JS])
770 insertPlaceHolders args body = insertPlaceHolders' args body []
772 insertPlaceHolders' :: [String] -> JS -> [JS] -> (JS, [JS])
773 insertPlaceHolders' (a:as) body ph
774 | (body', ph') <- insertPlaceHolders' as body ph =
775 let phvar = JSIdent $ "__PH_" ++ show (length ph') in
776 (jsSubst (JSIdent a) phvar body', phvar : ph')
778 insertPlaceHolders' [] body ph = (body, ph)
781inlineFunctions :: [JS] -> [JS]
783 inlineHelper ([], js)
785 inlineHelper :: ([JS], [JS]) -> [JS]
786 inlineHelper (front , (JSAlloc fun (Just (JSFunction args body))):back)
787 | countAll fun front + countAll fun back == 0 =
788 inlineHelper (front, back)
789 | Just new <- inlineAble (
790 countAll fun front + countAll fun back
792 let f = map (inlineFunction fun args new) in
793 inlineHelper (f front, f back)
795 inlineHelper (front, next:back) = inlineHelper (front ++ [next], back)
796 inlineHelper (front, []) = front
799 inlineAble :: Int -> String -> [String] -> JS -> Maybe JS
800 inlineAble 1 fun args (JSReturn body)
801 | nonRecur fun body =
802 if all (<= 1) (map ($ body) (map countIDOccurences args))
806 inlineAble _ _ _ _ = Nothing
809 nonRecur :: String -> JS -> Bool
810 nonRecur name body = countInvokations name body == 0
813 countAll :: String -> [JS] -> Int
814 countAll name js = sum $ map (countInvokations name) js
817 countIDOccurences :: String -> JS -> Int
818 countIDOccurences name = foldJS match (+) 0
822 | JSIdent ident <- js
827 countInvokations :: String -> JS -> Int
828 countInvokations name = foldJS match (+) 0
832 | JSApp (JSIdent ident) _ <- js
839reduceContinuations :: JS -> JS
840reduceContinuations = inlineTC . reduceJS
843 reduceJS (JSNew "__IDRRT__Cont" [JSFunction [] (
844 JSReturn js@(JSNew "__IDRRT__Cont" [JSFunction [] body])
847 reduceJS js = transformJS reduceJS js
852 | JSApp (JSIdent "__IDRRT__tailcall") [JSFunction [] (
853 JSReturn (JSNew "__IDRRT__Cont" [JSFunction [] (
854 JSReturn ret@(JSApp (JSIdent "__IDRRT__tailcall") [JSFunction [] (
855 JSReturn (JSNew "__IDRRT__Cont" _)
858 )] <- js = inlineTC ret
860 inlineTC js = transformJS inlineTC js
865reduceConstant :: JS -> JS
867 (JSApp (JSIdent "__IDRRT__tailcall") [JSFunction [] (
868 JSReturn (JSApp (JSIdent "__IDR__mEVAL0") [val])
870 | JSNum num <- val = val
871 | JSBinOp op lhs rhs <- val =
872 JSParens $ JSBinOp op (reduceConstant lhs) (reduceConstant rhs)
874 | JSApp (JSProj lhs op) [rhs] <- val
875 , op `elem` [ "subtract"
887reduceConstant (JSApp ident [(JSParens js)]) =
888 JSApp ident [reduceConstant js]
890reduceConstant js = transformJS reduceConstant js
893reduceConstants :: JS -> JS
895 | ret <- reduceConstant js
896 , ret /= js = reduceConstants ret
900elimDuplicateEvals :: JS -> JS
901elimDuplicateEvals (JSAlloc fun (Just (JSFunction args (JSSeq seq)))) =
902 JSAlloc fun $ Just (JSFunction args $ JSSeq (elimHelper seq))
904 elimHelper :: [JS] -> [JS]
905 elimHelper (j@(JSAlloc var (Just val)):js) =
906 j : map (jsSubst val (JSIdent var)) (elimHelper js)
911elimDuplicateEvals js = js
914optimizeRuntimeCalls :: String -> String -> [JS] -> [JS]
915optimizeRuntimeCalls fun tc js =
916 optTC tc : map optHelper js
918 optHelper :: JS -> JS
919 optHelper (JSApp (JSIdent "__IDRRT__tailcall") [
920 JSFunction [] (JSReturn (JSApp (JSIdent n) args))
922 | n == fun = JSApp (JSIdent tc) $ map optHelper args
924 optHelper js = transformJS optHelper js
927 optTC :: String -> JS
928 optTC tc@"__IDRRT__EVALTC" =
929 JSAlloc tc (Just $ JSFunction ["arg0"] (
930 JSSeq [ JSAlloc "ret" $ Just (
932 (JSIdent "arg0" `jsInstanceOf` jsCon) `jsAnd`
933 (hasProp "__IDRLT__EVAL" "arg0")
936 (JSIdent "__IDRLT__EVAL")
937 (JSProj (JSIdent "arg0") "tag")
942 , JSWhile (JSIdent "ret" `jsInstanceOf` (JSIdent "__IDRRT__Cont")) (
943 JSAssign (JSIdent "ret") (
944 JSApp (JSProj (JSIdent "ret") "k") []
947 , JSReturn $ JSIdent "ret"
951 optTC tc@"__IDRRT__APPLYTC" =
952 JSAlloc tc (Just $ JSFunction ["fn0", "arg0"] (
953 JSSeq [ JSAlloc "ret" $ Just (
955 (JSIdent "fn0" `jsInstanceOf` jsCon) `jsAnd`
956 (hasProp "__IDRLT__APPLY" "fn0")
959 (JSIdent "__IDRLT__APPLY")
960 (JSProj (JSIdent "fn0") "tag")
962 [JSIdent "fn0", JSIdent "arg0", JSIdent "fn0"]
965 , JSWhile (JSIdent "ret" `jsInstanceOf` (JSIdent "__IDRRT__Cont")) (
966 JSAssign (JSIdent "ret") (
967 JSApp (JSProj (JSIdent "ret") "k") []
970 , JSReturn $ JSIdent "ret"
975 hasProp :: String -> String -> JS
977 JSIndex (JSIdent table) (JSProj (JSIdent var) "tag")
980unfoldLookupTable :: [JS] -> [JS]
981unfoldLookupTable input =
982 let (evals, evalunfold) = unfoldLT "__IDRLT__EVAL" input
983 (applys, applyunfold) = unfoldLT "__IDRLT__APPLY" evalunfold
985 adaptRuntime $ expandCons evals applys js
987 adaptRuntime :: [JS] -> [JS]
989 adaptEvalTC . adaptApplyTC . adaptEval . adaptApply . adaptCon
992 adaptApply :: [JS] -> [JS]
993 adaptApply js = adaptApply' [] js
995 adaptApply' :: [JS] -> [JS] -> [JS]
996 adaptApply' front ((JSAlloc "__IDR__mAPPLY0" (Just _)):back) =
999 adaptApply' front (next:back) =
1000 adaptApply' (front ++ [next]) back
1002 adaptApply' front [] = front
1005 JSAlloc "__IDR__mAPPLY0" (Just $ JSFunction ["mfn0", "marg0"] (JSReturn $
1007 (JSIdent "mfn0" `jsInstanceOf` jsCon) `jsAnd`
1008 (JSProj (JSIdent "mfn0") "app")
1010 (JSProj (JSIdent "mfn0") "app")
1011 [JSIdent "mfn0", JSIdent "marg0"]
1017 adaptApplyTC :: [JS] -> [JS]
1018 adaptApplyTC js = adaptApplyTC' [] js
1020 adaptApplyTC' :: [JS] -> [JS] -> [JS]
1021 adaptApplyTC' front ((JSAlloc "__IDRRT__APPLYTC" (Just _)):back) =
1024 adaptApplyTC' front (next:back) =
1025 adaptApplyTC' (front ++ [next]) back
1027 adaptApplyTC' front [] = front
1030 JSAlloc "__IDRRT__APPLYTC" (Just $ JSFunction ["mfn0", "marg0"] (
1031 JSSeq [ JSAlloc "ret" $ Just (
1033 (JSIdent "mfn0" `jsInstanceOf` jsCon) `jsAnd`
1034 (JSProj (JSIdent "mfn0") "app")
1036 (JSProj (JSIdent "mfn0") "app")
1037 [JSIdent "mfn0", JSIdent "marg0"]
1040 , JSWhile (JSIdent "ret" `jsInstanceOf` (JSIdent "__IDRRT__Cont")) (
1041 JSAssign (JSIdent "ret") (
1042 JSApp (JSProj (JSIdent "ret") "k") []
1045 , JSReturn $ JSIdent "ret"
1050 adaptEval :: [JS] -> [JS]
1051 adaptEval js = adaptEval' [] js
1053 adaptEval' :: [JS] -> [JS] -> [JS]
1054 adaptEval' front ((JSAlloc "__IDR__mEVAL0" (Just _)):back) =
1057 adaptEval' front (next:back) =
1058 adaptEval' (front ++ [next]) back
1060 adaptEval' front [] = front
1063 JSAlloc "__IDR__mEVAL0" (Just $ JSFunction ["marg0"] (JSReturn $
1065 (JSIdent "marg0" `jsInstanceOf` jsCon) `jsAnd`
1066 (JSProj (JSIdent "marg0") "eval")
1068 (JSProj (JSIdent "marg0") "eval")
1075 adaptEvalTC :: [JS] -> [JS]
1076 adaptEvalTC js = adaptEvalTC' [] js
1078 adaptEvalTC' :: [JS] -> [JS] -> [JS]
1079 adaptEvalTC' front ((JSAlloc "__IDRRT__EVALTC" (Just _)):back) =
1082 adaptEvalTC' front (next:back) =
1083 adaptEvalTC' (front ++ [next]) back
1085 adaptEvalTC' front [] = front
1088 JSAlloc "__IDRRT__EVALTC" (Just $ JSFunction ["marg0"] (
1089 JSSeq [ JSAlloc "ret" $ Just (
1091 (JSIdent "marg0" `jsInstanceOf` jsCon) `jsAnd`
1092 (JSProj (JSIdent "marg0") "eval")
1094 (JSProj (JSIdent "marg0") "eval")
1098 , JSWhile (JSIdent "ret" `jsInstanceOf` (JSIdent "__IDRRT__Cont")) (
1099 JSAssign (JSIdent "ret") (
1100 JSApp (JSProj (JSIdent "ret") "k") []
1103 , JSReturn $ JSIdent "ret"
1111 adaptCon' front ((JSAnnotation _ (JSAlloc "__IDRRT__Con" _)):back) =
1114 adaptCon' front (next:back) =
1115 adaptCon' (front ++ [next]) back
1117 adaptCon' front [] = front
1121 JSAnnotation JSConstructor $
1122 JSAlloc "__IDRRT__Con" (Just $
1123 JSFunction newArgs (
1124 JSSeq (map newVar newArgs)
1128 newVar var = JSAssign (JSProj JSThis var) (JSIdent var)
1129 newArgs = ["tag", "eval", "app", "vars"]
1132 unfoldLT :: String -> [JS] -> ([Int], [JS])
1134 let (table, code) = extractLT lt js
1135 expanded = expandLT lt table in
1136 (map fst expanded, map snd expanded ++ code)
1139 expandCons :: [Int] -> [Int] -> [JS] -> [JS]
1140 expandCons evals applys js =
1143 expandCons' :: JS -> JS
1144 expandCons' (JSNew "__IDRRT__Con" [JSNum (JSInt tag), JSArray args])
1145 | evalid <- getId "__IDRLT__EVAL" tag evals
1146 , applyid <- getId "__IDRLT__APPLY" tag applys =
1147 JSNew "__IDRRT__Con" [ JSNum (JSInt tag)
1148 , maybe JSNull JSIdent evalid
1149 , maybe JSNull JSIdent applyid
1150 , JSArray (map expandCons' args)
1153 expandCons' js = transformJS expandCons' js
1156 getId :: String -> Int -> [Int] -> Maybe String
1157 getId lt tag entries
1158 | tag `elem` entries = Just $ ltIdentifier lt tag
1159 | otherwise = Nothing
1162 ltIdentifier :: String -> Int -> String
1163 ltIdentifier "__IDRLT__EVAL" id = idrLTNamespace ++ "EVAL" ++ show id
1164 ltIdentifier "__IDRLT__APPLY" id = idrLTNamespace ++ "APPLY" ++ show id
1167 extractLT :: String -> [JS] -> (JS, [JS])
1171 extractLT' :: ([JS], [JS]) -> (JS, [JS])
1172 extractLT' (front, js@(JSAlloc fun _):back)
1173 | fun == lt = (js, front ++ back)
1175 extractLT' (front, js:back) = extractLT' (front ++ [js], back)
1176 extractLT' (front, back) = (JSNoop, front ++ back)
1179 expandLT :: String -> JS -> [(Int, JS)]
1181 JSAlloc _ (Just (JSApp (JSFunction [] (JSSeq seq)) []))
1182 ) = catMaybes (map expandEntry seq)
1184 expandEntry :: JS -> Maybe (Int, JS)
1185 expandEntry (JSAssign (JSIndex _ (JSNum (JSInt id))) body) =
1186 Just $ (id, JSAlloc (ltIdentifier lt id) (Just body))
1188 expandEntry js = Nothing
1190 expandLT lt JSNoop = []
1193removeInstanceChecks :: JS -> JS
1194removeInstanceChecks (JSCond conds) =
1195 removeNoopConds $ JSCond $ eliminateDeadBranches $ map (
1196 removeHelper *** removeInstanceChecks
1200 JSBinOp "&&" (JSBinOp "instanceof" _ (JSIdent "__IDRRT__Con")) check
1201 ) = removeHelper check
1202 removeHelper js = js
1205 eliminateDeadBranches ((JSTrue, cond):_) = [(JSNoop, cond)]
1206 eliminateDeadBranches [(_, js)] = [(JSNoop, js)]
1207 eliminateDeadBranches (x:xs) = x : eliminateDeadBranches xs
1208 eliminateDeadBranches [] = []
1211 removeNoopConds :: JS -> JS
1212 removeNoopConds (JSCond [(JSNoop, js)]) = js
1213 removeNoopConds js = js
1215removeInstanceChecks js = transformJS removeInstanceChecks js
1218reduceLoop :: [String] -> ([JS], [JS]) -> [JS]
1219reduceLoop reduced (cons, program) =
1220 case partition findConstructors program of
1221 ([], js) -> cons ++ js
1222 (candidates, rest) ->
1223 let names = reduced ++ map funName candidates in
1225 cons ++ map reduce candidates, map (reduceCall names) rest
1227 where findConstructors :: JS -> Bool
1229 | (JSAlloc fun (Just (JSFunction _ (JSSeq body)))) <- js =
1230 reducable $ last body
1232 where reducable :: JS -> Bool
1234 | JSReturn ret <- js = reducable ret
1235 | JSNew _ args <- js = and $ map reducable args
1236 | JSArray fields <- js = and $ map reducable fields
1237 | JSNum _ <- js = True
1238 | JSNull <- js = True
1239 | JSIdent _ <- js = True
1244 reduce (JSAlloc fun (Just (JSFunction _ (JSSeq body))))
1245 | JSReturn js <- last body = (JSAlloc fun (Just js))
1250 reduceCall :: [String] -> JS -> JS
1251 reduceCall funs (JSApp (JSIdent "__IDRRT__tailcall") [JSFunction [] (
1252 JSReturn (JSApp id@(JSIdent ret) _)
1254 | ret `elem` funs = id
1256 reduceCall funs js@(JSApp id@(JSIdent fun) _)
1257 | fun `elem` funs = id
1259 reduceCall funs js = transformJS (reduceCall funs) js
1262extractLocalConstructors :: [JS] -> [JS]
1263extractLocalConstructors js =
1264 concatMap extractLocalConstructors' js
1266 globalCons :: [String]
1267 globalCons = concatMap (getGlobalCons) js
1270 extractLocalConstructors' :: JS -> [JS]
1271 extractLocalConstructors' js@(JSAlloc fun (Just (JSFunction args body))) =
1272 addCons cons [foldr (uncurry jsSubst) js (reverse cons)]
1275 cons = zipWith genName (foldJS match (++) [] body) [1..]
1277 genName :: JS -> Int -> (JS, JS)
1279 (js, JSIdent $ idrCTRNamespace ++ fun ++ "_" ++ show id)
1283 | JSNew "__IDRRT__Con" args <- js
1284 , all isConstant args = [js]
1288 addCons :: [(JS, JS)] -> [JS] -> [JS]
1290 addCons (con@(_, name):cons) js
1291 | sum (map (countOccur name) js) > 0 =
1292 addCons cons ((allocCon con) : js)
1297 countOccur :: JS -> JS -> Int
1298 countOccur ident js = foldJS match (+) 0 js
1306 allocCon :: (JS, JS) -> JS
1307 allocCon (js, JSIdent name) =
1308 JSAlloc name (Just js)
1311 isConstant :: JS -> Bool
1313 | JSNew "__IDRRT__Con" args <- js
1314 , all isConstant args =
1317 isJSConstantConstructor globalCons js
1319 extractLocalConstructors' js = [js]
1322 getGlobalCons :: JS -> [String]
1323 getGlobalCons js = foldJS match (++) [] js
1325 match :: JS -> [String]
1327 | (JSAlloc name (Just (JSNew "__IDRRT__Con" _))) <- js =
1333evalCons :: [JS] -> [JS]
1335 map (collapseCont . collapseTC . expandProj . evalCons') js
1337 cons :: [(String, JS)]
1338 cons = concatMap getGlobalCons js
1340 evalCons' :: JS -> JS
1341 evalCons' js = transformJS match js
1344 match (JSApp (JSIdent "__IDRRT__EVALTC") [arg])
1345 | JSIdent name <- arg
1346 , Just (JSNew _ [_, JSNull, _, _]) <- lookupConstructor name cons =
1349 match (JSApp (JSIdent "__IDR__mEVAL0") [arg])
1350 | JSIdent name <- arg
1351 , Just (JSNew _ [_, JSNull, _, _]) <- lookupConstructor name cons =
1354 match js = transformJS match js
1357 lookupConstructor :: String -> [(String, JS)] -> Maybe JS
1358 lookupConstructor ctr cons
1359 | Just (JSIdent name) <- lookup ctr cons = lookupConstructor name cons
1360 | Just con@(JSNew _ _) <- lookup ctr cons = Just con
1361 | otherwise = Nothing
1364 expandProj :: JS -> JS
1365 expandProj js = transformJS match js
1370 JSProj (JSIdent name) "vars"
1375 | Just (JSNew _ [_, _, _, JSArray args]) <- lookup name cons =
1378 match js = transformJS match js
1381 collapseTC :: JS -> JS
1382 collapseTC js = transformJS match js
1385 match (JSApp (JSIdent "__IDRRT__tailcall") [JSFunction [] (
1386 JSReturn (JSIdent name)
1388 | Just _ <- lookup name cons = (JSIdent name)
1390 match js = transformJS match js
1393 collapseCont :: JS -> JS
1394 collapseCont js = transformJS match js
1397 match (JSNew "__IDRRT__Cont" [JSFunction [] (
1398 JSReturn ret@(JSNew "__IDRRT__Cont" [JSFunction [] _])
1399 )]) = collapseCont ret
1402 match (JSNew "__IDRRT__Cont" [JSFunction [] (
1403 JSReturn (JSIdent name)
1406 match (JSNew "__IDRRT__Cont" [JSFunction [] (
1407 JSReturn ret@(JSNew "__IDRRT__Con" [_, _, _, JSArray args])
1409 | all collapsable args = ret
1411 collapsable :: JS -> Bool
1412 collapsable (JSIdent _) = True
1413 collapsable js = isJSConstantConstructor (map fst cons) js
1416 match js = transformJS match js
1419elimConds :: [JS] -> [JS]
1421 let (conds, rest) = partition isCond js in
1422 foldl' eraseCond rest conds
1424 isCond :: JS -> Bool
1426 fun (Just (JSFunction args (JSCond
1427 [ (JSBinOp "==" (JSNum (JSInt tag)) _, JSReturn (JSIdent _))
1428 , (JSNoop, JSReturn (JSIdent _))
1433 fun (Just (JSFunction args (JSCond
1434 [ (JSBinOp "==" _ (JSNum (JSInt tag)), JSReturn (JSIdent _))
1435 , (JSNoop, JSReturn (JSIdent _))
1442 eraseCond :: [JS] -> JS -> [JS]
1443 eraseCond js (JSAlloc
1444 fun (Just (JSFunction args (JSCond
1449 )) = map (inlineFunction fun args (JSTernary c t f)) js
1452removeUselessCons :: [JS] -> [JS]
1453removeUselessCons js =
1454 let (cons, rest) = partition isUseless js in
1455 foldl' eraseCon rest cons
1457 isUseless :: JS -> Bool
1458 isUseless (JSAlloc fun (Just JSNull)) = True
1459 isUseless (JSAlloc fun (Just (JSIdent _))) = True
1463 eraseCon :: [JS] -> JS -> [JS]
1464 eraseCon js (JSAlloc fun (Just val)) = map (jsSubst (JSIdent fun) val) js
1467getGlobalCons :: JS -> [(String, JS)]
1468getGlobalCons js = foldJS match (++) [] js
1470 match :: JS -> [(String, JS)]
1472 | (JSAlloc name (Just con@(JSNew "__IDRRT__Con" _))) <- js =
1474 | (JSAlloc name (Just con@(JSIdent _))) <- js =
1480getIncludes :: [FilePath] -> IO [String]
1481getIncludes = mapM readFile
1483codegenJavaScript :: CodeGenerator
1484codegenJavaScript ci = codegenJS_all JavaScript (simpleDecls ci)
1485 (includes ci) (outputFile ci) (outputType ci)
1487codegenNode :: CodeGenerator
1488codegenNode ci = codegenJS_all Node (simpleDecls ci)
1489 (includes ci) (outputFile ci) (outputType ci)
1498codegenJS_all target definitions includes filename outputType = do
1499 let (header, rt) = case target of
1501 ("#!/usr/bin/env node\n", "-node")
1504 included <- getIncludes includes
1505 path <- (++) <$> getDataDir <*> (pure "/jsrts/")
1506 idrRuntime <- readFile $ path ++ "Runtime-common.js"
1507 tgtRuntime <- readFile $ concat [path, "Runtime", rt, ".js"]
1508 jsbn <- readFile $ path ++ "jsbn/jsbn.js"
1509 writeFile filename $ header ++ (
1510 intercalate "\n" $ included ++ runtime jsbn idrRuntime tgtRuntime ++ functions
1513 setPermissions filename (emptyPermissions { readable = True
1514 , executable = target == Node
1518 def :: [(String, SDecl)]
1519 def = map (first translateNamespace) definitions
1522 checkForBigInt :: [JS] -> Bool
1523 checkForBigInt js = occur
1526 occur = or $ map (foldJS match (||) False) js
1529 match (JSIdent "__IDRRT__bigInt") = True
1530 match (JSWord (JSWord64 _)) = True
1531 match (JSNum (JSInteger _)) = True
1535 runtime :: String -> String -> String -> [String]
1536 runtime jsbn idrRuntime tgtRuntime =
1537 if checkForBigInt optimized
1538 then [jsbn, idrRuntime, tgtRuntime]
1539 else [idrRuntime, tgtRuntime]
1543 optimized = translate >>> optimize $ def
1546 prelude ++ concatMap translateDeclaration p ++ [mainLoop, invokeLoop]
1548 foldl' (flip ($)) p opt
1555 , map reduceConstants
1557 , map removeAllocations
1559 , map elimDuplicateEvals
1560 , optimizeRuntimeCalls "__IDR__mEVAL0" "__IDRRT__EVALTC"
1561 , optimizeRuntimeCalls "__IDR__mAPPLY0" "__IDRRT__APPLYTC"
1562 , map removeInstanceChecks
1564 , map reduceContinuations
1565 , extractLocalConstructors
1572 functions :: [String]
1573 functions = map compileJS optimized
1577 [ JSAnnotation JSConstructor $
1578 JSAlloc (idrRTNamespace ++ "Cont") (Just $ JSFunction ["k"] (
1579 JSAssign (JSProj JSThis "k") (JSIdent "k")
1581 , JSAnnotation JSConstructor $
1582 JSAlloc (idrRTNamespace ++ "Con") (Just $ JSFunction ["tag", "vars"] (
1583 JSSeq [ JSAssign (JSProj JSThis "tag") (JSIdent "tag")
1584 , JSAssign (JSProj JSThis "vars") (JSIdent "vars")
1591 JSAlloc "main" $ Just $ JSFunction [] (
1594 JavaScript -> JSCond [(isReady, mainFun), (JSTrue, jsMeth (JSIdent "window") "addEventListener" [
1595 JSString "DOMContentLoaded", JSFunction [] (
1602 mainFun = jsTailcall $ jsCall runMain []
1606 isReady = readyState `jsEq` JSString "complete" `jsOr` readyState `jsEq` JSString "loaded"
1610 readyState = JSProj (JSIdent "document") "readyState"
1614 runMain = idrNamespace ++ translateName (sMN 0 "runMain")
1618 invokeLoop = jsCall "main" []
1621translateIdentifier :: String -> String
1622translateIdentifier =
1623 replaceReserved . concatMap replaceBadChars
1624 where replaceBadChars :: Char -> String
1628 | isDigit c = '_' : show (ord c)
1629 | not (isLetter c && isAscii c) = '_' : show (ord c)
1632 | s `elem` reserved = '_' : s
1636 reserved = [ "break"
1682translateNamespace :: Name -> String
1683translateNamespace (UN _) = idrNamespace
1684translateNamespace (NS _ ns) = idrNamespace ++ concatMap (translateIdentifier . str) ns
1685translateNamespace (MN _ _) = idrNamespace
1686translateNamespace (SN name) = idrNamespace ++ translateSpecialName name
1687translateNamespace NErased = idrNamespace
1690translateName :: Name -> String
1691translateName (UN name) = 'u' : translateIdentifier (str name)
1692translateName (NS name _) = 'n' : translateName name
1693translateName (MN i name) = 'm' : translateIdentifier (str name) ++ show i
1694translateName (SN name) = 's' : translateSpecialName name
1695translateName NErased = "e"
1698translateSpecialName :: SpecialName -> String
1699translateSpecialName name
1700 | WhereN i m n <- name =
1701 'w' : translateName m ++ translateName n ++ show i
1702 | InstanceN n s <- name =
1703 'i' : translateName n ++ concatMap (translateIdentifier . str) s
1704 | ParentN n s <- name =
1705 'p' : translateName n ++ translateIdentifier (str s)
1706 | MethodN n <- name =
1707 'm' : translateName n
1709 'c' : translateName n
1712translateConstant :: Const -> JS
1713translateConstant (I i) = JSNum (JSInt i)
1714translateConstant (Fl f) = JSNum (JSFloat f)
1715translateConstant (Ch c) = JSString $ translateChar c
1716translateConstant (Str s) = JSString $ concatMap translateChar s
1717translateConstant (AType (ATInt ITNative)) = JSType JSIntTy
1718translateConstant StrType = JSType JSStringTy
1719translateConstant (AType (ATInt ITBig)) = JSType JSIntegerTy
1720translateConstant (AType ATFloat) = JSType JSFloatTy
1721translateConstant (AType (ATInt ITChar)) = JSType JSCharTy
1722translateConstant PtrType = JSType JSPtrTy
1723translateConstant Forgot = JSType JSForgotTy
1724translateConstant (BI i) = jsBigInt $ JSString (show i)
1725translateConstant (B8 b) = JSWord (JSWord8 b)
1726translateConstant (B16 b) = JSWord (JSWord16 b)
1727translateConstant (B32 b) = JSWord (JSWord32 b)
1728translateConstant (B64 b) = JSWord (JSWord64 b)
1729translateConstant c =
1730 jsError $ "Unimplemented Constant: " ++ show c
1733translateChar :: Char -> String
1735 | '\a' <- ch = "\\u0007"
1736 | '\b' <- ch = "\\b"
1737 | '\f' <- ch = "\\f"
1738 | '\n' <- ch = "\\n"
1739 | '\r' <- ch = "\\r"
1740 | '\t' <- ch = "\\t"
1741 | '\v' <- ch = "\\v"
1742 | '\SO' <- ch = "\\u000E"
1743 | '\DEL' <- ch = "\\u007F"
1744 | '\\' <- ch = "\\\\"
1745 | '\"' <- ch = "\\\""
1746 | '\'' <- ch = "\\\'"
1747 | ch `elem` asciiTab = "\\u00" ++ fill (showIntAtBase 16 intToDigit (ord ch) "")
1750 fill :: String -> String
1751 fill s = if length s == 1
1756 ['\NUL', '\SOH', '\STX', '\ETX', '\EOT', '\ENQ', '\ACK', '\BEL',
1757 '\BS', '\HT', '\LF', '\VT', '\FF', '\CR', '\SO', '\SI',
1758 '\DLE', '\DC1', '\DC2', '\DC3', '\DC4', '\NAK', '\SYN', '\ETB',
1759 '\CAN', '\EM', '\SUB', '\ESC', '\FS', '\GS', '\RS', '\US']
1762translateDeclaration :: (String, SDecl) -> [JS]
1763translateDeclaration (path, SFun name params stackSize body)
1765 , (SChkCase var cases) <- body
1766 , ap == txt "APPLY" =
1767 [ lookupTable "APPLY" [] var cases
1768 , jsDecl $ JSFunction ["mfn0", "marg0"] (JSReturn $
1770 (JSIdent "mfn0" `jsInstanceOf` jsCon) `jsAnd`
1771 (hasProp (idrLTNamespace ++ "APPLY") "mfn0")
1774 (JSIdent (idrLTNamespace ++ "APPLY"))
1775 (JSProj (JSIdent "mfn0") "tag")
1777 [JSIdent "mfn0", JSIdent "marg0"]
1783 , (SChkCase var cases) <- body
1784 , ev == txt "EVAL" =
1785 [ lookupTable "EVAL" [] var cases
1786 , jsDecl $ JSFunction ["marg0"] (JSReturn $
1788 (JSIdent "marg0" `jsInstanceOf` jsCon) `jsAnd`
1789 (hasProp (idrLTNamespace ++ "EVAL") "marg0")
1792 (JSIdent (idrLTNamespace ++ "EVAL"))
1793 (JSProj (JSIdent "marg0") "tag")
1800 let fun = translateExpression body in
1801 [jsDecl $ jsFun fun]
1804 hasProp :: String -> String -> JS
1806 JSIndex (JSIdent table) (JSProj (JSIdent var) "tag")
1809 caseFun :: [(LVar, String)] -> LVar -> SAlt -> JS
1810 caseFun aux var cse =
1811 let (JSReturn c) = translateCase (Just (translateVariableName var)) cse in
1815 getTag :: SAlt -> Maybe Int
1816 getTag (SConCase _ tag _ _ _) = Just tag
1820 lookupTable :: String -> [(LVar, String)] -> LVar -> [SAlt] -> JS
1821 lookupTable table aux var cases =
1822 JSAlloc (idrLTNamespace ++ table) $ Just (
1823 JSApp (JSFunction [] (
1825 JSAlloc "t" $ Just (JSArray [])
1826 ] ++ assignEntries (catMaybes $ map (lookupEntry aux var) cases) ++ [
1827 JSReturn (JSIdent "t")
1832 assignEntries :: [(Int, JS)] -> [JS]
1833 assignEntries entries =
1835 JSAssign (JSIndex (JSIdent "t") (JSNum $ JSInt tag)) fun
1839 lookupEntry :: [(LVar, String)] -> LVar -> SAlt -> Maybe (Int, JS)
1840 lookupEntry aux var alt = do
1842 return (tag, caseFun aux var alt)
1846 jsDecl = JSAlloc (path ++ translateName name) . Just
1849 jsFun body = jsFunAux [] body
1852 jsFunAux :: [(LVar, String)] -> JS -> JS
1854 JSFunction (p ++ map snd aux) (
1856 zipWith assignVar [0..] p ++
1857 map assignAux aux ++
1861 assignVar :: Int -> String -> JS
1862 assignVar n s = JSAlloc (jsVar n) (Just $ JSIdent s)
1865 assignAux :: (LVar, String) -> JS
1866 assignAux (Loc var, val) =
1867 JSAlloc (jsVar var) (Just $ JSIdent val)
1871 p = map translateName params
1874translateVariableName :: LVar -> String
1875translateVariableName (Loc i) =
1879translateExpression :: SExp -> JS
1880translateExpression (SLet name value body) =
1881 jsLet (translateVariableName name) (
1882 translateExpression value
1883 ) (translateExpression body)
1885translateExpression (SConst cst) =
1886 translateConstant cst
1888translateExpression (SV var) =
1891translateExpression (SApp tc name vars)
1893 jsTailcall $ translateFunctionCall name vars
1895 JSNew (idrRTNamespace ++ "Cont") [JSFunction [] (
1896 JSReturn $ translateFunctionCall name vars
1899 translateFunctionCall name vars =
1900 jsCall (translateNamespace name ++ translateName name) (map JSVar vars)
1902translateExpression (SOp op vars)
1903 | LNoOp <- op = JSVar (last vars)
1905 | (LZExt (ITFixed IT8) ITNative) <- op = jsUnPackBits $ JSVar (last vars)
1906 | (LZExt (ITFixed IT16) ITNative) <- op = jsUnPackBits $ JSVar (last vars)
1907 | (LZExt (ITFixed IT32) ITNative) <- op = jsUnPackBits $ JSVar (last vars)
1909 | (LZExt _ ITBig) <- op = jsBigInt $ jsCall "String" [JSVar (last vars)]
1910 | (LPlus (ATInt ITBig)) <- op
1911 , (lhs:rhs:_) <- vars = invokeMeth lhs "add" [rhs]
1912 | (LMinus (ATInt ITBig)) <- op
1913 , (lhs:rhs:_) <- vars = invokeMeth lhs "subtract" [rhs]
1914 | (LTimes (ATInt ITBig)) <- op
1915 , (lhs:rhs:_) <- vars = invokeMeth lhs "multiply" [rhs]
1916 | (LSDiv (ATInt ITBig)) <- op
1917 , (lhs:rhs:_) <- vars = invokeMeth lhs "divide" [rhs]
1918 | (LSRem (ATInt ITBig)) <- op
1919 , (lhs:rhs:_) <- vars = invokeMeth lhs "mod" [rhs]
1920 | (LEq (ATInt ITBig)) <- op
1921 , (lhs:rhs:_) <- vars = invokeMeth lhs "equals" [rhs]
1922 | (LSLt (ATInt ITBig)) <- op
1923 , (lhs:rhs:_) <- vars = invokeMeth lhs "lesser" [rhs]
1924 | (LSLe (ATInt ITBig)) <- op
1925 , (lhs:rhs:_) <- vars = invokeMeth lhs "lesserOrEquals" [rhs]
1926 | (LSGt (ATInt ITBig)) <- op
1927 , (lhs:rhs:_) <- vars = invokeMeth lhs "greater" [rhs]
1928 | (LSGe (ATInt ITBig)) <- op
1929 , (lhs:rhs:_) <- vars = invokeMeth lhs "greaterOrEquals" [rhs]
1931 | (LPlus ATFloat) <- op
1932 , (lhs:rhs:_) <- vars = translateBinaryOp "+" lhs rhs
1933 | (LMinus ATFloat) <- op
1934 , (lhs:rhs:_) <- vars = translateBinaryOp "-" lhs rhs
1935 | (LTimes ATFloat) <- op
1936 , (lhs:rhs:_) <- vars = translateBinaryOp "*" lhs rhs
1937 | (LSDiv ATFloat) <- op
1938 , (lhs:rhs:_) <- vars = translateBinaryOp "/" lhs rhs
1939 | (LEq ATFloat) <- op
1940 , (lhs:rhs:_) <- vars = translateBinaryOp "==" lhs rhs
1941 | (LSLt ATFloat) <- op
1942 , (lhs:rhs:_) <- vars = translateBinaryOp "<" lhs rhs
1943 | (LSLe ATFloat) <- op
1944 , (lhs:rhs:_) <- vars = translateBinaryOp "<=" lhs rhs
1945 | (LSGt ATFloat) <- op
1946 , (lhs:rhs:_) <- vars = translateBinaryOp ">" lhs rhs
1947 | (LSGe ATFloat) <- op
1948 , (lhs:rhs:_) <- vars = translateBinaryOp ">=" lhs rhs
1950 | (LPlus (ATInt ITChar)) <- op
1951 , (lhs:rhs:_) <- vars =
1952 jsCall "__IDRRT__fromCharCode" [
1954 jsCall "__IDRRT__charCode" [JSVar lhs]
1956 jsCall "__IDRRT__charCode" [JSVar rhs]
1960 | (LTrunc (ITFixed IT16) (ITFixed IT8)) <- op
1963 JSBinOp "&" (jsUnPackBits $ JSVar arg) (JSNum (JSInt 0xFF))
1966 | (LTrunc (ITFixed IT32) (ITFixed IT16)) <- op
1969 JSBinOp "&" (jsUnPackBits $ JSVar arg) (JSNum (JSInt 0xFFFF))
1972 | (LTrunc (ITFixed IT64) (ITFixed IT32)) <- op
1975 jsMeth (jsMeth (JSVar arg) "and" [
1976 jsBigInt (JSString $ show 0xFFFFFFFF)
1980 | (LTrunc ITBig (ITFixed IT64)) <- op
1982 jsMeth (JSVar arg) "and" [
1983 jsBigInt (JSString $ show 0xFFFFFFFFFFFFFFFF)
1986 | (LLSHR (ITFixed IT8)) <- op
1987 , (lhs:rhs:_) <- vars =
1989 JSBinOp ">>" (jsUnPackBits $ JSVar lhs) (jsUnPackBits $ JSVar rhs)
1992 | (LLSHR (ITFixed IT16)) <- op
1993 , (lhs:rhs:_) <- vars =
1995 JSBinOp ">>" (jsUnPackBits $ JSVar lhs) (jsUnPackBits $ JSVar rhs)
1998 | (LLSHR (ITFixed IT32)) <- op
1999 , (lhs:rhs:_) <- vars =
2001 JSBinOp ">>" (jsUnPackBits $ JSVar lhs) (jsUnPackBits $ JSVar rhs)
2004 | (LLSHR (ITFixed IT64)) <- op
2005 , (lhs:rhs:_) <- vars =
2006 jsMeth (JSVar lhs) "shiftRight" [JSVar rhs]
2008 | (LSHL (ITFixed IT8)) <- op
2009 , (lhs:rhs:_) <- vars =
2011 JSBinOp "<<" (jsUnPackBits $ JSVar lhs) (jsUnPackBits $ JSVar rhs)
2014 | (LSHL (ITFixed IT16)) <- op
2015 , (lhs:rhs:_) <- vars =
2017 JSBinOp "<<" (jsUnPackBits $ JSVar lhs) (jsUnPackBits $ JSVar rhs)
2020 | (LSHL (ITFixed IT32)) <- op
2021 , (lhs:rhs:_) <- vars =
2023 JSBinOp "<<" (jsUnPackBits $ JSVar lhs) (jsUnPackBits $ JSVar rhs)
2026 | (LSHL (ITFixed IT64)) <- op
2027 , (lhs:rhs:_) <- vars =
2028 jsMeth (jsMeth (JSVar lhs) "shiftLeft" [JSVar rhs]) "and" [
2029 jsBigInt (JSString $ show 0xFFFFFFFFFFFFFFFF)
2032 | (LAnd (ITFixed IT8)) <- op
2033 , (lhs:rhs:_) <- vars =
2035 JSBinOp "&" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2038 | (LAnd (ITFixed IT16)) <- op
2039 , (lhs:rhs:_) <- vars =
2041 JSBinOp "&" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2044 | (LAnd (ITFixed IT32)) <- op
2045 , (lhs:rhs:_) <- vars =
2047 JSBinOp "&" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2050 | (LAnd (ITFixed IT64)) <- op
2051 , (lhs:rhs:_) <- vars =
2052 jsMeth (JSVar lhs) "and" [JSVar rhs]
2054 | (LOr (ITFixed IT8)) <- op
2055 , (lhs:rhs:_) <- vars =
2057 JSBinOp "|" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2060 | (LOr (ITFixed IT16)) <- op
2061 , (lhs:rhs:_) <- vars =
2063 JSBinOp "|" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2066 | (LOr (ITFixed IT32)) <- op
2067 , (lhs:rhs:_) <- vars =
2069 JSBinOp "|" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2072 | (LOr (ITFixed IT64)) <- op
2073 , (lhs:rhs:_) <- vars =
2074 jsMeth (JSVar lhs) "or" [JSVar rhs]
2076 | (LXOr (ITFixed IT8)) <- op
2077 , (lhs:rhs:_) <- vars =
2079 JSBinOp "^" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2082 | (LXOr (ITFixed IT16)) <- op
2083 , (lhs:rhs:_) <- vars =
2085 JSBinOp "^" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2088 | (LXOr (ITFixed IT32)) <- op
2089 , (lhs:rhs:_) <- vars =
2091 JSBinOp "^" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2094 | (LXOr (ITFixed IT64)) <- op
2095 , (lhs:rhs:_) <- vars =
2096 jsMeth (JSVar lhs) "xor" [JSVar rhs]
2098 | (LPlus (ATInt (ITFixed IT8))) <- op
2099 , (lhs:rhs:_) <- vars =
2101 JSBinOp "+" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2104 | (LPlus (ATInt (ITFixed IT16))) <- op
2105 , (lhs:rhs:_) <- vars =
2107 JSBinOp "+" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2110 | (LPlus (ATInt (ITFixed IT32))) <- op
2111 , (lhs:rhs:_) <- vars =
2113 JSBinOp "+" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2116 | (LPlus (ATInt (ITFixed IT64))) <- op
2117 , (lhs:rhs:_) <- vars =
2118 jsMeth (jsMeth (JSVar lhs) "add" [JSVar rhs]) "and" [
2119 jsBigInt (JSString $ show 0xFFFFFFFFFFFFFFFF)
2122 | (LMinus (ATInt (ITFixed IT8))) <- op
2123 , (lhs:rhs:_) <- vars =
2125 JSBinOp "-" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2128 | (LMinus (ATInt (ITFixed IT16))) <- op
2129 , (lhs:rhs:_) <- vars =
2131 JSBinOp "-" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2134 | (LMinus (ATInt (ITFixed IT32))) <- op
2135 , (lhs:rhs:_) <- vars =
2137 JSBinOp "-" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2140 | (LMinus (ATInt (ITFixed IT64))) <- op
2141 , (lhs:rhs:_) <- vars =
2142 jsMeth (jsMeth (JSVar lhs) "subtract" [JSVar rhs]) "and" [
2143 jsBigInt (JSString $ show 0xFFFFFFFFFFFFFFFF)
2146 | (LTimes (ATInt (ITFixed IT8))) <- op
2147 , (lhs:rhs:_) <- vars =
2149 JSBinOp "*" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2152 | (LTimes (ATInt (ITFixed IT16))) <- op
2153 , (lhs:rhs:_) <- vars =
2155 JSBinOp "*" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2158 | (LTimes (ATInt (ITFixed IT32))) <- op
2159 , (lhs:rhs:_) <- vars =
2161 JSBinOp "*" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2164 | (LTimes (ATInt (ITFixed IT64))) <- op
2165 , (lhs:rhs:_) <- vars =
2166 jsMeth (jsMeth (JSVar lhs) "multiply" [JSVar rhs]) "and" [
2167 jsBigInt (JSString $ show 0xFFFFFFFFFFFFFFFF)
2170 | (LEq (ATInt (ITFixed IT8))) <- op
2171 , (lhs:rhs:_) <- vars =
2173 JSBinOp "==" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2176 | (LEq (ATInt (ITFixed IT16))) <- op
2177 , (lhs:rhs:_) <- vars =
2179 JSBinOp "==" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2182 | (LEq (ATInt (ITFixed IT32))) <- op
2183 , (lhs:rhs:_) <- vars =
2185 JSBinOp "==" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2188 | (LEq (ATInt (ITFixed IT64))) <- op
2189 , (lhs:rhs:_) <- vars =
2190 jsMeth (jsMeth (JSVar lhs) "equals" [JSVar rhs]) "and" [
2191 jsBigInt (JSString $ show 0xFFFFFFFFFFFFFFFF)
2194 | (LLt (ITFixed IT8)) <- op
2195 , (lhs:rhs:_) <- vars =
2197 JSBinOp "<" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2200 | (LLt (ITFixed IT16)) <- op
2201 , (lhs:rhs:_) <- vars =
2203 JSBinOp "<" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2206 | (LLt (ITFixed IT32)) <- op
2207 , (lhs:rhs:_) <- vars =
2209 JSBinOp "<" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2212 | (LLt (ITFixed IT64)) <- op
2213 , (lhs:rhs:_) <- vars = invokeMeth lhs "lesser" [rhs]
2215 | (LLe (ITFixed IT8)) <- op
2216 , (lhs:rhs:_) <- vars =
2218 JSBinOp "<=" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2221 | (LLe (ITFixed IT16)) <- op
2222 , (lhs:rhs:_) <- vars =
2224 JSBinOp "<=" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2227 | (LLe (ITFixed IT32)) <- op
2228 , (lhs:rhs:_) <- vars =
2230 JSBinOp "<=" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2233 | (LLe (ITFixed IT64)) <- op
2234 , (lhs:rhs:_) <- vars = invokeMeth lhs "lesserOrEquals" [rhs]
2236 | (LGt (ITFixed IT8)) <- op
2237 , (lhs:rhs:_) <- vars =
2239 JSBinOp ">" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2242 | (LGt (ITFixed IT16)) <- op
2243 , (lhs:rhs:_) <- vars =
2245 JSBinOp ">" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2247 | (LGt (ITFixed IT32)) <- op
2248 , (lhs:rhs:_) <- vars =
2250 JSBinOp ">" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2253 | (LGt (ITFixed IT64)) <- op
2254 , (lhs:rhs:_) <- vars = invokeMeth lhs "greater" [rhs]
2256 | (LGe (ITFixed IT8)) <- op
2257 , (lhs:rhs:_) <- vars =
2259 JSBinOp ">=" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2262 | (LGe (ITFixed IT16)) <- op
2263 , (lhs:rhs:_) <- vars =
2265 JSBinOp ">=" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2267 | (LGe (ITFixed IT32)) <- op
2268 , (lhs:rhs:_) <- vars =
2270 JSBinOp ">=" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2273 | (LGe (ITFixed IT64)) <- op
2274 , (lhs:rhs:_) <- vars = invokeMeth lhs "greaterOrEquals" [rhs]
2276 | (LUDiv (ITFixed IT8)) <- op
2277 , (lhs:rhs:_) <- vars =
2279 JSBinOp "/" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2282 | (LUDiv (ITFixed IT16)) <- op
2283 , (lhs:rhs:_) <- vars =
2285 JSBinOp "/" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2288 | (LUDiv (ITFixed IT32)) <- op
2289 , (lhs:rhs:_) <- vars =
2291 JSBinOp "/" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2294 | (LUDiv (ITFixed IT64)) <- op
2295 , (lhs:rhs:_) <- vars = invokeMeth lhs "divide" [rhs]
2297 | (LSDiv (ATInt (ITFixed IT8))) <- op
2298 , (lhs:rhs:_) <- vars =
2301 jsUnPackBits $ jsPackSBits8 $ jsUnPackBits (JSVar lhs)
2303 jsUnPackBits $ jsPackSBits8 $ jsUnPackBits (JSVar rhs)
2307 | (LSDiv (ATInt (ITFixed IT16))) <- op
2308 , (lhs:rhs:_) <- vars =
2311 jsUnPackBits $ jsPackSBits16 $ jsUnPackBits (JSVar lhs)
2313 jsUnPackBits $ jsPackSBits16 $ jsUnPackBits (JSVar rhs)
2317 | (LSDiv (ATInt (ITFixed IT32))) <- op
2318 , (lhs:rhs:_) <- vars =
2321 jsUnPackBits $ jsPackSBits32 $ jsUnPackBits (JSVar lhs)
2323 jsUnPackBits $ jsPackSBits32 $ jsUnPackBits (JSVar rhs)
2327 | (LSDiv (ATInt (ITFixed IT64))) <- op
2328 , (lhs:rhs:_) <- vars = invokeMeth lhs "divide" [rhs]
2330 | (LSRem (ATInt (ITFixed IT8))) <- op
2331 , (lhs:rhs:_) <- vars =
2334 jsUnPackBits $ jsPackSBits8 $ jsUnPackBits (JSVar lhs)
2336 jsUnPackBits $ jsPackSBits8 $ jsUnPackBits (JSVar rhs)
2340 | (LSRem (ATInt (ITFixed IT16))) <- op
2341 , (lhs:rhs:_) <- vars =
2344 jsUnPackBits $ jsPackSBits16 $ jsUnPackBits (JSVar lhs)
2346 jsUnPackBits $ jsPackSBits16 $ jsUnPackBits (JSVar rhs)
2350 | (LSRem (ATInt (ITFixed IT32))) <- op
2351 , (lhs:rhs:_) <- vars =
2354 jsUnPackBits $ jsPackSBits32 $ jsUnPackBits (JSVar lhs)
2356 jsUnPackBits $ jsPackSBits32 $ jsUnPackBits (JSVar rhs)
2360 | (LSRem (ATInt (ITFixed IT64))) <- op
2361 , (lhs:rhs:_) <- vars = invokeMeth lhs "mod" [rhs]
2363 | (LCompl (ITFixed IT8)) <- op
2365 jsPackSBits8 $ JSPreOp "~" $ jsUnPackBits (JSVar arg)
2367 | (LCompl (ITFixed IT16)) <- op
2369 jsPackSBits16 $ JSPreOp "~" $ jsUnPackBits (JSVar arg)
2371 | (LCompl (ITFixed IT32)) <- op
2373 jsPackSBits32 $ JSPreOp "~" $ jsUnPackBits (JSVar arg)
2375 | (LCompl (ITFixed IT64)) <- op
2377 invokeMeth arg "not" []
2380 , (lhs:rhs:_) <- vars = translateBinaryOp "+" lhs rhs
2382 , (lhs:rhs:_) <- vars = translateBinaryOp "-" lhs rhs
2384 , (lhs:rhs:_) <- vars = translateBinaryOp "*" lhs rhs
2386 , (lhs:rhs:_) <- vars = translateBinaryOp "/" lhs rhs
2388 , (lhs:rhs:_) <- vars = translateBinaryOp "%" lhs rhs
2390 , (lhs:rhs:_) <- vars = translateBinaryOp "==" lhs rhs
2392 , (lhs:rhs:_) <- vars = translateBinaryOp "<" lhs rhs
2394 , (lhs:rhs:_) <- vars = translateBinaryOp "<=" lhs rhs
2396 , (lhs:rhs:_) <- vars = translateBinaryOp ">" lhs rhs
2398 , (lhs:rhs:_) <- vars = translateBinaryOp ">=" lhs rhs
2400 , (lhs:rhs:_) <- vars = translateBinaryOp "&" lhs rhs
2402 , (lhs:rhs:_) <- vars = translateBinaryOp "|" lhs rhs
2404 , (lhs:rhs:_) <- vars = translateBinaryOp "^" lhs rhs
2406 , (lhs:rhs:_) <- vars = translateBinaryOp "<<" rhs lhs
2408 , (lhs:rhs:_) <- vars = translateBinaryOp ">>" rhs lhs
2410 , (arg:_) <- vars = JSPreOp "~" (JSVar arg)
2413 , (lhs:rhs:_) <- vars = invokeMeth lhs "concat" [rhs]
2415 , (lhs:rhs:_) <- vars = translateBinaryOp "==" lhs rhs
2417 , (lhs:rhs:_) <- vars = translateBinaryOp "<" lhs rhs
2419 , (arg:_) <- vars = JSProj (JSVar arg) "length"
2421 | (LStrInt ITNative) <- op
2422 , (arg:_) <- vars = jsCall "parseInt" [JSVar arg]
2423 | (LIntStr ITNative) <- op
2424 , (arg:_) <- vars = jsCall "String" [JSVar arg]
2425 | (LSExt ITNative ITBig) <- op
2426 , (arg:_) <- vars = jsBigInt $ jsCall "String" [JSVar arg]
2427 | (LTrunc ITBig ITNative) <- op
2428 , (arg:_) <- vars = jsMeth (JSVar arg) "intValue" []
2429 | (LIntStr ITBig) <- op
2430 , (arg:_) <- vars = jsMeth (JSVar arg) "toString" []
2431 | (LStrInt ITBig) <- op
2432 , (arg:_) <- vars = jsBigInt $ JSVar arg
2434 , (arg:_) <- vars = jsCall "String" [JSVar arg]
2436 , (arg:_) <- vars = jsCall "parseFloat" [JSVar arg]
2437 | (LIntFloat ITNative) <- op
2438 , (arg:_) <- vars = JSVar arg
2439 | (LFloatInt ITNative) <- op
2440 , (arg:_) <- vars = JSVar arg
2441 | (LChInt ITNative) <- op
2442 , (arg:_) <- vars = jsCall "__IDRRT__charCode" [JSVar arg]
2443 | (LIntCh ITNative) <- op
2444 , (arg:_) <- vars = jsCall "__IDRRT__fromCharCode" [JSVar arg]
2447 , (arg:_) <- vars = jsCall "Math.exp" [JSVar arg]
2449 , (arg:_) <- vars = jsCall "Math.log" [JSVar arg]
2451 , (arg:_) <- vars = jsCall "Math.sin" [JSVar arg]
2453 , (arg:_) <- vars = jsCall "Math.cos" [JSVar arg]
2455 , (arg:_) <- vars = jsCall "Math.tan" [JSVar arg]
2457 , (arg:_) <- vars = jsCall "Math.asin" [JSVar arg]
2459 , (arg:_) <- vars = jsCall "Math.acos" [JSVar arg]
2461 , (arg:_) <- vars = jsCall "Math.atan" [JSVar arg]
2463 , (arg:_) <- vars = jsCall "Math.sqrt" [JSVar arg]
2465 , (arg:_) <- vars = jsCall "Math.floor" [JSVar arg]
2467 , (arg:_) <- vars = jsCall "Math.ceil" [JSVar arg]
2470 , (lhs:rhs:_) <- vars = invokeMeth lhs "concat" [rhs]
2472 , (arg:_) <- vars = JSIndex (JSVar arg) (JSNum (JSInt 0))
2474 , (arg:_) <- vars = JSProj (JSVar arg) "split('').reverse().join('')"
2476 , (lhs:rhs:_) <- vars = JSIndex (JSVar lhs) (JSVar rhs)
2478 , (arg:_) <- vars = let v = translateVariableName arg in
2479 JSApp (JSProj (JSIdent v) "substr") [
2481 JSBinOp "-" (JSProj (JSIdent v) "length") (JSNum (JSInt 1))
2484 , (_) <- vars = JSNull
2487 translateBinaryOp :: String -> LVar -> LVar -> JS
2488 translateBinaryOp f lhs rhs = JSParens $ JSBinOp f (JSVar lhs) (JSVar rhs)
2491 invokeMeth :: LVar -> String -> [LVar] -> JS
2492 invokeMeth obj meth args = jsMeth (JSVar obj) meth (map JSVar args)
2494translateExpression (SError msg) =
2497translateExpression (SForeign _ _ "putStr" [(FString, var)]) =
2498 jsCall (idrRTNamespace ++ "print") [JSVar var]
2500translateExpression (SForeign _ _ "isNull" [(FPtr, var)]) =
2501 JSBinOp "==" (JSVar var) JSNull
2503translateExpression (SForeign _ _ "idris_eqPtr" [(FPtr, lhs),(FPtr, rhs)]) =
2504 JSBinOp "==" (JSVar lhs) (JSVar rhs)
2506translateExpression (SForeign _ _ "idris_time" []) =
2507 JSRaw "(new Date()).getTime()"
2509translateExpression (SForeign _ _ fun args) =
2510 JSFFI fun (map generateWrapper args)
2512 generateWrapper (ffunc, name)
2513 | FFunction <- ffunc =
2515 JSIdent $ idrRTNamespace ++ "ffiWrap"
2516 ) [JSIdent $ translateVariableName name]
2517 | FFunctionIO <- ffunc =
2519 JSIdent $ idrRTNamespace ++ "ffiWrap"
2520 ) [JSIdent $ translateVariableName name]
2522 generateWrapper (_, name) =
2523 JSIdent $ translateVariableName name
2525translateExpression patterncase
2526 | (SChkCase var cases) <- patterncase = caseHelper var cases "chk"
2527 | (SCase var cases) <- patterncase = caseHelper var cases "cse"
2529 caseHelper var cases param =
2530 JSApp (JSFunction [param] (
2531 JSCond $ map (expandCase param . translateCaseCond param) cases
2535 expandCase :: String -> (Cond, JS) -> (JS, JS)
2536 expandCase _ (RawCond cond, branch) = (cond, branch)
2537 expandCase _ (CaseCond DefaultCase, branch) = (JSTrue , branch)
2538 expandCase var (CaseCond caseTy, branch)
2539 | ConCase tag <- caseTy =
2540 let checkCon = JSIdent var `jsInstanceOf` jsCon
2541 checkTag = (JSNum $ JSInt tag) `jsEq` jsTag (JSIdent var) in
2542 (checkCon `jsAnd` checkTag, branch)
2544 | TypeCase ty <- caseTy =
2545 let checkTy = JSIdent var `jsInstanceOf` jsType
2546 checkTag = jsTypeTag (JSIdent var) `jsEq` JSType ty in
2547 (checkTy `jsAnd` checkTag, branch)
2549translateExpression (SCon i name vars) =
2550 JSNew (idrRTNamespace ++ "Con") [ JSNum $ JSInt i
2551 , JSArray $ map JSVar vars
2554translateExpression (SUpdate var@(Loc i) e) =
2555 JSAssign (JSVar var) (translateExpression e)
2557translateExpression (SProj var i) =
2558 JSIndex (JSProj (JSVar var) "vars") (JSNum $ JSInt i)
2560translateExpression SNothing = JSNull
2562translateExpression e =
2563 jsError $ "Not yet implemented: " ++ filter (/= '\'') (show e)
2566data CaseType = ConCase Int
2572data Cond = CaseCond CaseType
2576translateCaseCond :: String -> SAlt -> (Cond, JS)
2577translateCaseCond _ cse@(SDefaultCase _) =
2578 (CaseCond DefaultCase, translateCase Nothing cse)
2580translateCaseCond var cse@(SConstCase ty _)
2581 | StrType <- ty = matchHelper JSStringTy
2582 | PtrType <- ty = matchHelper JSPtrTy
2583 | Forgot <- ty = matchHelper JSForgotTy
2584 | (AType ATFloat) <- ty = matchHelper JSFloatTy
2585 | (AType (ATInt ITBig)) <- ty = matchHelper JSIntegerTy
2586 | (AType (ATInt ITNative)) <- ty = matchHelper JSIntTy
2587 | (AType (ATInt ITChar)) <- ty = matchHelper JSCharTy
2589 matchHelper :: JSType -> (Cond, JS)
2590 matchHelper ty = (CaseCond $ TypeCase ty, translateCase Nothing cse)
2592translateCaseCond var cse@(SConstCase cst@(BI _) _) =
2593 let cond = jsMeth (JSIdent var) "equals" [translateConstant cst] in
2594 (RawCond cond, translateCase Nothing cse)
2596translateCaseCond var cse@(SConstCase cst _) =
2597 let cond = JSIdent var `jsEq` translateConstant cst in
2598 (RawCond cond, translateCase Nothing cse)
2600translateCaseCond var cse@(SConCase _ tag _ _ _) =
2601 (CaseCond $ ConCase tag, translateCase (Just var) cse)
2604translateCase :: Maybe String -> SAlt -> JS
2605translateCase _ (SDefaultCase e) = JSReturn $ translateExpression e
2606translateCase _ (SConstCase _ e) = JSReturn $ translateExpression e
2607translateCase (Just var) (SConCase a _ _ vars e) =
2608 let params = map jsVar [a .. (a + length vars)] in
2609 JSReturn $ jsMeth (JSFunction params (JSReturn $ translateExpression e)) "apply" [
2610 JSThis, JSProj (JSIdent var) "vars"
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