on e28fbb1 help sign in
Idris-dev/src/IRTS/CodegenJavaScript.hs
2561 lines 79 kB history raw
1{-# LANGUAGE PatternGuards #-}
3module IRTS.CodegenJavaScript (codegenJavaScript, codegenNode, JSTarget(..)) where
5import Idris.AbsSyntax hiding (TypeCase)
6import IRTS.Bytecode
7import IRTS.Lang
8import IRTS.Simplified
9import IRTS.CodegenCommon
10import Idris.Core.TT
11import Paths_idris
12import Util.System
14import Control.Arrow
15import Control.Applicative ((<$>), (<*>), pure)
16import Data.Char
17import Numeric
18import Data.List
19import Data.Maybe
20import Data.Word
21import System.IO
22import System.Directory
25idrNamespace :: String
26idrNamespace = "__IDR__"
27idrRTNamespace = "__IDRRT__"
28idrLTNamespace = "__IDRLT__"
29idrCTRNamespace = "__IDRCTR__"
32data JSTarget = Node | JavaScript deriving Eq
35data JSType = JSIntTy
36 | JSStringTy
37 | JSIntegerTy
38 | JSFloatTy
39 | JSCharTy
40 | JSPtrTy
41 | JSForgotTy
42 deriving Eq
45data JSInteger = JSBigZero
46 | JSBigOne
47 | JSBigInt Integer
48 deriving Eq
51data JSNum = JSInt Int
52 | JSFloat Double
53 | JSInteger JSInteger
54 deriving Eq
57data JSWord = JSWord8 Word8
58 | JSWord16 Word16
59 | JSWord32 Word32
60 | JSWord64 Word64
61 deriving Eq
64data JSAnnotation = JSConstructor deriving Eq
67instance Show JSAnnotation where
68 show JSConstructor = "constructor"
71data JS = JSRaw String
72 | JSIdent String
73 | JSFunction [String] JS
74 | JSType JSType
75 | JSSeq [JS]
76 | JSReturn JS
77 | JSApp JS [JS]
78 | JSNew String [JS]
79 | JSError String
80 | JSBinOp String JS JS
81 | JSPreOp String JS
82 | JSPostOp String JS
83 | JSProj JS String
84 | JSVar LVar
85 | JSNull
86 | JSThis
87 | JSTrue
88 | JSFalse
89 | JSArray [JS]
90 | JSString String
91 | JSNum JSNum
92 | JSWord JSWord
93 | JSAssign JS JS
94 | JSAlloc String (Maybe JS)
95 | JSIndex JS JS
96 | JSCond [(JS, JS)]
97 | JSTernary JS JS JS
98 | JSParens JS
99 | JSWhile JS JS
100 | JSFFI String [JS]
101 | JSAnnotation JSAnnotation JS
102 | JSNoop
103 deriving Eq
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
114 where
115 ffiParse :: String -> [FFI]
116 ffiParse "" = []
117 ffiParse ['%'] = [FFIError $ "FFI - Invalid positional argument"]
118 ffiParse ('%':'%':ss) = FFICode '%' : ffiParse ss
119 ffiParse ('%':s:ss)
120 | isDigit s =
121 FFIArg (read $ s : takeWhile isDigit ss) : ffiParse (dropWhile isDigit ss)
122 | otherwise =
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
134 renderFFI [] _ = ""
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
142compileJS JSNoop = ""
144compileJS (JSAnnotation annotation js) =
145 "/** @" ++ show annotation ++ " */\n" ++ compileJS js
147compileJS (JSFFI raw args) =
148 ffi raw (map compileJS args)
150compileJS (JSRaw code) =
151 code
153compileJS (JSIdent ident) =
154 ident
156compileJS (JSFunction args body) =
157 "function("
158 ++ intercalate "," args
159 ++ "){\n"
160 ++ compileJS body
161 ++ "\n}"
163compileJS (JSType ty)
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, ")"]
181 | otherwise =
182 concat [compileJS lhs, "(", args, ")"]
183 where args :: String
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) =
196 op ++ compileJS val
198compileJS (JSProj obj field)
199 | JSFunction {} <- obj =
200 concat ["(", compileJS obj, ").", field]
201 | JSAssign {} <- obj =
202 concat ["(", compileJS obj, ").", field]
203 | otherwise =
204 compileJS obj ++ '.' : field
206compileJS (JSVar var) =
207 translateVariableName var
209compileJS JSNull =
210 "null"
212compileJS JSThis =
213 "this"
215compileJS JSTrue =
216 "true"
218compileJS JSFalse =
219 "false"
221compileJS (JSArray elems) =
222 "[" ++ intercalate "," (map compileJS elems) ++ "]"
224compileJS (JSString str) =
225 "\"" ++ str ++ "\""
227compileJS (JSNum num)
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
245 where
246 createIfBlock (JSNoop, e) =
247 "{\n"
248 ++ compileJS e
249 ++ ";\n}"
250 createIfBlock (cond, e) =
251 "if (" ++ compileJS cond ++") {\n"
252 ++ compileJS e
253 ++ ";\n}"
255compileJS (JSTernary cond true false) =
256 let c = compileJS cond
257 t = compileJS true
258 f = compileJS false in
259 "(" ++ c ++ ")?(" ++ t ++ "):(" ++ f ++ ")"
261compileJS (JSParens js) =
262 "(" ++ compileJS js ++ ")"
264compileJS (JSWhile cond body) =
265 "while (" ++ compileJS cond ++ ") {\n"
266 ++ compileJS body
267 ++ "\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
277jsTailcall call =
278 jsCall (idrRTNamespace ++ "tailcall") [
279 JSFunction [] (JSReturn call)
280 ]
283jsCall :: String -> [JS] -> JS
284jsCall fun = JSApp (JSIdent fun)
287jsMeth :: JS -> String -> [JS] -> JS
288jsMeth obj meth =
289 JSApp (JSProj obj meth)
292jsInstanceOf :: JS -> JS -> JS
293jsInstanceOf = JSBinOp "instanceof"
296jsEq :: JS -> JS -> JS
297jsEq = JSBinOp "=="
300jsAnd :: JS -> JS -> JS
301jsAnd = JSBinOp "&&"
304jsOr :: JS -> JS -> JS
305jsOr = JSBinOp "||"
308jsType :: JS
309jsType = JSIdent $ idrRTNamespace ++ "Type"
312jsCon :: JS
313jsCon = JSIdent $ idrRTNamespace ++ "Con"
316jsTag :: JS -> JS
317jsTag obj = JSProj obj "tag"
320jsTypeTag :: JS -> JS
321jsTypeTag obj = JSProj obj "type"
324jsBigInt :: JS -> JS
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 =
336 JSApp (
337 JSFunction [name] (
338 JSReturn body
339 )
340 ) [value]
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 =
371 fold js
372 where
373 fold js
374 | JSFunction args body <- js =
375 add (tr js) (fold body)
376 | JSSeq seq <- js =
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
412 | otherwise =
413 tr js
416transformJS :: (JS -> JS) -> JS -> JS
417transformJS tr js =
418 transformHelper js
419 where
420 transformHelper :: JS -> JS
421 transformHelper 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)
441 | otherwise = js
444moveJSDeclToTop :: String -> [JS] -> [JS]
445moveJSDeclToTop decl js = move ([], js)
446 where
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
459jsSubst var new old
460 | var == old = new
462jsSubst (JSIdent var) new (JSVar old)
463 | var == translateVariableName old = new
464 | otherwise = JSVar old
466jsSubst var new old@(JSIdent _)
467 | var == old = new
468 | otherwise = old
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
480 )
481 | otherwise =
482 JSApp (JSProj (JSFunction args body) "apply") (
483 map (jsSubst (JSIdent var) new) vals
484 )
486jsSubst (JSIdent var) new (JSApp (JSFunction [arg] body) vals)
487 | var /= arg =
488 JSApp (JSFunction [arg] (
489 jsSubst (JSIdent var) new body
490 )) $ map (jsSubst (JSIdent var) new) vals
491 | otherwise =
492 JSApp (JSFunction [arg] (
493 body
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
502 case opt of
503 [ret] -> ret
504 _ -> JSSeq opt
505 where
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
516isJSConstant js
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
525 | otherwise = False
527isJSConstantConstructor :: [String] -> JS -> Bool
528isJSConstantConstructor constants js
529 | isJSConstant js =
530 True
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 =
537 True
538 | JSIdent name <- js
539 , name `elem` constants =
540 True
541 | otherwise = False
544inlineJS :: JS -> JS
545inlineJS = inlineAssign . inlineError . inlineApply . inlineCaseMatch . inlineJSLet
546 where
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
562 inlineApply js
563 | JSApp (
564 JSProj (JSFunction args (JSReturn body)) "apply"
565 ) [JSThis, JSProj var "vars"] <- js =
566 inlineApply $ inlineApply' var args body 0
567 | JSReturn (JSApp (
568 JSProj (JSFunction args body@(JSCond _)) "apply"
569 ) [JSThis, JSProj var "vars"]) <- js =
570 inlineApply $ inlineApply' var args body 0
571 where
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))
577 ) body
578 ) (n + 1)
580 inlineApply js = transformJS inlineApply js
583 inlineError (JSReturn (JSApp (JSFunction [] error@(JSError _)) [])) =
584 inlineError error
586 inlineError js = transformJS inlineError js
589 inlineAssign (JSAssign lhs rhs)
590 | JSVar _ <- lhs
591 , JSVar _ <- rhs
592 , lhs == rhs =
593 lhs
595 inlineAssign (JSAssign lhs rhs)
596 | JSIdent _ <- lhs
597 , JSIdent _ <- rhs
598 , lhs == rhs =
599 lhs
601 inlineAssign js = transformJS inlineAssign js
604removeEval :: [JS] -> [JS]
605removeEval js =
606 let (ret, isReduced) = checkEval js in
607 if isReduced
608 then removeEvalApp ret
609 else ret
610 where
611 removeEvalApp js = catMaybes (map removeEvalApp' js)
612 where
613 removeEvalApp' :: JS -> Maybe JS
614 removeEvalApp' (JSAlloc "__IDR__mEVAL0" _) = Nothing
615 removeEvalApp' js = Just $ transformJS match js
616 where
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
622 where
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 [] (
630 JSSeq [ _
631 , JSReturn (JSIdent "t")
632 ]
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]
647elimDeadLoop js
648 | ret <- deadEvalApplyCases js
649 , ret /= js = elimDeadLoop ret
650 | otherwise = js
653deadEvalApplyCases :: [JS] -> [JS]
654deadEvalApplyCases js =
655 let tags = sort $ nub $ concatMap (getTags) js in
656 map (removeHelper tags) js
657 where
658 getTags :: JS -> [Int]
659 getTags = foldJS match (++) []
660 where
661 match js
662 | JSNew "__IDRRT__Con" [JSNum (JSInt tag), _] <- js = [tag]
663 | otherwise = []
666 removeHelper :: [Int] -> JS -> JS
667 removeHelper tags (JSAlloc fun (Just (
668 JSApp (JSFunction [] (JSSeq seq)) []))
669 ) =
670 (JSAlloc fun (Just (
671 JSApp (JSFunction [] (JSSeq $ remover tags seq)) []))
672 )
674 removeHelper _ js = js
677 remover :: [Int] -> [JS] -> [JS]
678 remover tags (
679 j@(JSAssign ((JSIndex (JSIdent "t") (JSNum (JSInt tag)))) _):js
680 )
681 | tag `notElem` tags = remover tags js
683 remover tags (j:js) = j : remover tags js
684 remover _ [] = []
687initConstructors :: [JS] -> [JS]
688initConstructors js =
689 let tags = nub $ sort $ concat (map getTags js) in
690 rearrangePrelude $ map createConstant tags ++ replaceConstructors tags js
691 where
692 rearrangePrelude :: [JS] -> [JS]
693 rearrangePrelude = moveJSDeclToTop $ idrRTNamespace ++ "Con"
696 getTags :: JS -> [Int]
697 getTags = foldJS match (++) []
698 where
699 match js
700 | JSNew "__IDRRT__Con" [JSNum (JSInt tag), JSArray []] <- js = [tag]
701 | otherwise = []
704 replaceConstructors :: [Int] -> [JS] -> [JS]
705 replaceConstructors tags js = map (replaceHelper tags) js
706 where
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
715 createConstant tag =
716 JSAlloc (idrCTRNamespace ++ show tag) (Just (
717 JSNew (idrRTNamespace ++ "Con") [JSNum (JSInt tag), JSArray []]
718 ))
721removeIDs :: [JS] -> [JS]
722removeIDs js =
723 case partition isID js of
724 ([], rest) -> rest
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
730 isID _ = False
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)
741 )])
742 | Just pos <- lookup fun ids
743 , pos < length args = args !! pos
745 removeIDCall ids (JSNew _ [JSFunction [] (
746 JSReturn (JSApp (JSIdent fun) args)
747 )])
748 | Just pos <- lookup fun ids
749 , pos < length args = args !! pos
751 removeIDCall ids js@(JSApp id@(JSIdent fun) args)
752 | Just pos <- lookup fun ids
753 , pos < length args = args !! pos
755 removeIDCall ids js = transformJS (removeIDCall ids) js
758inlineFunctions :: [JS] -> [JS]
759inlineFunctions js =
760 inlineHelper ([], js)
761 where
762 inlineHelper :: ([JS], [JS]) -> [JS]
763 inlineHelper (front , (JSAlloc fun (Just (JSFunction args body))):back)
764 | countAll fun front + countAll fun back == 0 =
765 inlineHelper (front, back)
766 | Just new <- inlineAble (
767 countAll fun front + countAll fun back
768 ) fun args body =
769 let f = map (inline fun args new) in
770 inlineHelper (f front, f back)
772 inlineHelper (front, next:back) = inlineHelper (front ++ [next], back)
773 inlineHelper (front, []) = front
776 inlineAble :: Int -> String -> [String] -> JS -> Maybe JS
777 inlineAble 1 fun args (JSReturn body)
778 | nonRecur fun body =
779 if all (<= 1) (map ($ body) (map countIDOccurences args))
780 then Just body
781 else Nothing
783 inlineAble _ _ _ _ = Nothing
786 inline :: String -> [String] -> JS -> JS -> JS
787 inline fun args body js = inline' js
788 where
789 inline' :: JS -> JS
790 inline' (JSApp (JSIdent name) vals)
791 | name == fun =
792 let (js, phs) = insertPlaceHolders args body in
793 inline' $ foldr (uncurry jsSubst) js (zip phs vals)
795 inline' js = transformJS inline' js
797 insertPlaceHolders :: [String] -> JS -> (JS, [JS])
798 insertPlaceHolders args body = insertPlaceHolders' args body []
799 where
800 insertPlaceHolders' :: [String] -> JS -> [JS] -> (JS, [JS])
801 insertPlaceHolders' (a:as) body ph
802 | (body', ph') <- insertPlaceHolders' as body ph =
803 let phvar = JSIdent $ "__PH_" ++ show (length ph') in
804 (jsSubst (JSIdent a) phvar body', phvar : ph')
806 insertPlaceHolders' [] body ph = (body, ph)
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
819 where
820 match :: JS -> Int
821 match js
822 | JSIdent ident <- js
823 , name == ident = 1
824 | otherwise = 0
827 countInvokations :: String -> JS -> Int
828 countInvokations name = foldJS match (+) 0
829 where
830 match :: JS -> Int
831 match js
832 | JSApp (JSIdent ident) _ <- js
833 , name == ident = 1
834 | JSNew con _ <- js
835 , name == con = 1
836 | otherwise = 0
839reduceContinuations :: JS -> JS
840reduceContinuations = inlineTC . reduceJS
841 where
842 reduceJS :: JS -> JS
843 reduceJS (JSNew "__IDRRT__Cont" [JSFunction [] (
844 JSReturn js@(JSNew "__IDRRT__Cont" [JSFunction [] body])
845 )]) = reduceJS js
847 reduceJS js = transformJS reduceJS js
850 inlineTC :: JS -> JS
851 inlineTC 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" _)
856 )])
857 )])
858 )] <- js = inlineTC ret
860 inlineTC js = transformJS inlineTC js
865reduceConstant :: JS -> JS
866reduceConstant
867 (JSApp (JSIdent "__IDRRT__tailcall") [JSFunction [] (
868 JSReturn (JSApp (JSIdent "__IDR__mEVAL0") [val])
869 )])
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"
876 , "add"
877 , "multiply"
878 , "divide"
879 , "mod"
880 , "equals"
881 , "lesser"
882 , "lesserOrEquals"
883 , "greater"
884 , "greaterOrEquals"
885 ] = val
887reduceConstant (JSApp ident [(JSParens js)]) =
888 JSApp ident [reduceConstant js]
890reduceConstant js = transformJS reduceConstant js
893reduceConstants :: JS -> JS
894reduceConstants js
895 | ret <- reduceConstant js
896 , ret /= js = reduceConstants ret
897 | otherwise = js
900elimDuplicateEvals :: JS -> JS
901elimDuplicateEvals (JSAlloc fun (Just (JSFunction args (JSSeq seq)))) =
902 JSAlloc fun $ Just (JSFunction args $ JSSeq (elimHelper seq))
903 where
904 elimHelper :: [JS] -> [JS]
905 elimHelper (j@(JSAlloc var (Just val)):js) =
906 j : map (jsSubst val (JSIdent var)) (elimHelper js)
907 elimHelper (j:js) =
908 j : elimHelper js
909 elimHelper [] = []
911elimDuplicateEvals js = js
914optimizeRuntimeCalls :: String -> String -> [JS] -> [JS]
915optimizeRuntimeCalls fun tc js =
916 optTC tc : map optHelper js
917 where
918 optHelper :: JS -> JS
919 optHelper (JSApp (JSIdent "__IDRRT__tailcall") [
920 JSFunction [] (JSReturn (JSApp (JSIdent n) args))
921 ])
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 (
931 JSTernary (
932 (JSIdent "arg0" `jsInstanceOf` jsCon) `jsAnd`
933 (hasProp "__IDRLT__EVAL" "arg0")
934 ) (JSApp
935 (JSIndex
936 (JSIdent "__IDRLT__EVAL")
937 (JSProj (JSIdent "arg0") "tag")
938 )
939 [JSIdent "arg0"]
940 ) (JSIdent "arg0")
941 )
942 , JSWhile (JSIdent "ret" `jsInstanceOf` (JSIdent "__IDRRT__Cont")) (
943 JSAssign (JSIdent "ret") (
944 JSApp (JSProj (JSIdent "ret") "k") []
945 )
946 )
947 , JSReturn $ JSIdent "ret"
948 ]
949 ))
951 optTC tc@"__IDRRT__APPLYTC" =
952 JSAlloc tc (Just $ JSFunction ["fn0", "arg0"] (
953 JSSeq [ JSAlloc "ret" $ Just (
954 JSTernary (
955 (JSIdent "fn0" `jsInstanceOf` jsCon) `jsAnd`
956 (hasProp "__IDRLT__APPLY" "fn0")
957 ) (JSApp
958 (JSIndex
959 (JSIdent "__IDRLT__APPLY")
960 (JSProj (JSIdent "fn0") "tag")
961 )
962 [JSIdent "fn0", JSIdent "arg0", JSIdent "fn0"]
963 ) JSNull
964 )
965 , JSWhile (JSIdent "ret" `jsInstanceOf` (JSIdent "__IDRRT__Cont")) (
966 JSAssign (JSIdent "ret") (
967 JSApp (JSProj (JSIdent "ret") "k") []
968 )
969 )
970 , JSReturn $ JSIdent "ret"
971 ]
972 ))
975 hasProp :: String -> String -> JS
976 hasProp table var =
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
984 js = applyunfold in
985 adaptRuntime $ expandCons evals applys js
986 where
987 adaptRuntime :: [JS] -> [JS]
988 adaptRuntime =
989 adaptEvalTC . adaptApplyTC . adaptEval . adaptApply . adaptCon
992 adaptApply :: [JS] -> [JS]
993 adaptApply js = adaptApply' [] js
994 where
995 adaptApply' :: [JS] -> [JS] -> [JS]
996 adaptApply' front ((JSAlloc "__IDR__mAPPLY0" (Just _)):back) =
997 front ++ (new:back)
999 adaptApply' front (next:back) =
1000 adaptApply' (front ++ [next]) back
1002 adaptApply' front [] = front
1004 new =
1005 JSAlloc "__IDR__mAPPLY0" (Just $ JSFunction ["mfn0", "marg0"] (JSReturn $
1006 JSTernary (
1007 (JSIdent "mfn0" `jsInstanceOf` jsCon) `jsAnd`
1008 (JSProj (JSIdent "mfn0") "app")
1009 ) (JSApp
1010 (JSProj (JSIdent "mfn0") "app")
1011 [JSIdent "mfn0", JSIdent "marg0"]
1012 ) JSNull
1017 adaptApplyTC :: [JS] -> [JS]
1018 adaptApplyTC js = adaptApplyTC' [] js
1019 where
1020 adaptApplyTC' :: [JS] -> [JS] -> [JS]
1021 adaptApplyTC' front ((JSAlloc "__IDRRT__APPLYTC" (Just _)):back) =
1022 front ++ (new:back)
1024 adaptApplyTC' front (next:back) =
1025 adaptApplyTC' (front ++ [next]) back
1027 adaptApplyTC' front [] = front
1029 new =
1030 JSAlloc "__IDRRT__APPLYTC" (Just $ JSFunction ["mfn0", "marg0"] (
1031 JSSeq [ JSAlloc "ret" $ Just (
1032 JSTernary (
1033 (JSIdent "mfn0" `jsInstanceOf` jsCon) `jsAnd`
1034 (JSProj (JSIdent "mfn0") "app")
1035 ) (JSApp
1036 (JSProj (JSIdent "mfn0") "app")
1037 [JSIdent "mfn0", JSIdent "marg0"]
1038 ) JSNull
1040 , JSWhile (JSIdent "ret" `jsInstanceOf` (JSIdent "__IDRRT__Cont")) (
1041 JSAssign (JSIdent "ret") (
1042 JSApp (JSProj (JSIdent "ret") "k") []
1045 , JSReturn $ JSIdent "ret"
1047 ))
1050 adaptEval :: [JS] -> [JS]
1051 adaptEval js = adaptEval' [] js
1052 where
1053 adaptEval' :: [JS] -> [JS] -> [JS]
1054 adaptEval' front ((JSAlloc "__IDR__mEVAL0" (Just _)):back) =
1055 front ++ (new:back)
1057 adaptEval' front (next:back) =
1058 adaptEval' (front ++ [next]) back
1060 adaptEval' front [] = front
1062 new =
1063 JSAlloc "__IDR__mEVAL0" (Just $ JSFunction ["marg0"] (JSReturn $
1064 JSTernary (
1065 (JSIdent "marg0" `jsInstanceOf` jsCon) `jsAnd`
1066 (JSProj (JSIdent "marg0") "eval")
1067 ) (JSApp
1068 (JSProj (JSIdent "marg0") "eval")
1069 [JSIdent "marg0"]
1070 ) (JSIdent "marg0")
1075 adaptEvalTC :: [JS] -> [JS]
1076 adaptEvalTC js = adaptEvalTC' [] js
1077 where
1078 adaptEvalTC' :: [JS] -> [JS] -> [JS]
1079 adaptEvalTC' front ((JSAlloc "__IDRRT__EVALTC" (Just _)):back) =
1080 front ++ (new:back)
1082 adaptEvalTC' front (next:back) =
1083 adaptEvalTC' (front ++ [next]) back
1085 adaptEvalTC' front [] = front
1087 new =
1088 JSAlloc "__IDRRT__EVALTC" (Just $ JSFunction ["marg0"] (
1089 JSSeq [ JSAlloc "ret" $ Just (
1090 JSTernary (
1091 (JSIdent "marg0" `jsInstanceOf` jsCon) `jsAnd`
1092 (JSProj (JSIdent "marg0") "eval")
1093 ) (JSApp
1094 (JSProj (JSIdent "marg0") "eval")
1095 [JSIdent "marg0"]
1096 ) (JSIdent "marg0")
1098 , JSWhile (JSIdent "ret" `jsInstanceOf` (JSIdent "__IDRRT__Cont")) (
1099 JSAssign (JSIdent "ret") (
1100 JSApp (JSProj (JSIdent "ret") "k") []
1103 , JSReturn $ JSIdent "ret"
1105 ))
1108 adaptCon js =
1109 adaptCon' [] js
1110 where
1111 adaptCon' front ((JSAnnotation _ (JSAlloc "__IDRRT__Con" _)):back) =
1112 front ++ (new:back)
1114 adaptCon' front (next:back) =
1115 adaptCon' (front ++ [next]) back
1117 adaptCon' front [] = front
1120 new =
1121 JSAnnotation JSConstructor $
1122 JSAlloc "__IDRRT__Con" (Just $
1123 JSFunction newArgs (
1124 JSSeq (map newVar newArgs)
1127 where
1128 newVar var = JSAssign (JSProj JSThis var) (JSIdent var)
1129 newArgs = ["tag", "eval", "app", "vars"]
1132 unfoldLT :: String -> [JS] -> ([Int], [JS])
1133 unfoldLT lt 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 =
1141 map expandCons' js
1142 where
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])
1168 extractLT lt js =
1169 extractLT' ([], js)
1170 where
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)]
1180 expandLT lt (
1181 JSAlloc _ (Just (JSApp (JSFunction [] (JSSeq seq)) []))
1182 ) = catMaybes (map expandEntry seq)
1183 where
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
1197 ) conds
1198 where
1199 removeHelper (
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
1224 reduceLoop names (
1225 cons ++ map reduce candidates, map (reduceCall names) rest
1227 where findConstructors :: JS -> Bool
1228 findConstructors js
1229 | (JSAlloc fun (Just (JSFunction _ (JSSeq body)))) <- js =
1230 reducable $ last body
1231 | otherwise = False
1232 where reducable :: JS -> Bool
1233 reducable js
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
1240 | otherwise = False
1243 reduce :: JS -> JS
1244 reduce (JSAlloc fun (Just (JSFunction _ (JSSeq body))))
1245 | JSReturn js <- last body = (JSAlloc fun (Just js))
1247 reduce js = js
1250 reduceCall :: [String] -> JS -> JS
1251 reduceCall funs (JSApp (JSIdent "__IDRRT__tailcall") [JSFunction [] (
1252 JSReturn (JSApp id@(JSIdent ret) _)
1253 )])
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
1265 where
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)]
1273 where
1274 cons :: [(JS, JS)]
1275 cons = zipWith genName (foldJS match (++) [] body) [1..]
1276 where
1277 genName :: JS -> Int -> (JS, JS)
1278 genName js id =
1279 (js, JSIdent $ idrCTRNamespace ++ fun ++ "_" ++ show id)
1281 match :: JS -> [JS]
1282 match js
1283 | JSNew "__IDRRT__Con" args <- js
1284 , all isConstant args = [js]
1285 | otherwise = []
1288 addCons :: [(JS, JS)] -> [JS] -> [JS]
1289 addCons [] js = js
1290 addCons (con@(_, name):cons) js
1291 | sum (map (countOccur name) js) > 0 =
1292 addCons cons ((allocCon con) : js)
1293 | otherwise =
1294 addCons cons js
1297 countOccur :: JS -> JS -> Int
1298 countOccur ident js = foldJS match (+) 0 js
1299 where
1300 match :: JS -> Int
1301 match js
1302 | js == ident = 1
1303 | otherwise = 0
1306 allocCon :: (JS, JS) -> JS
1307 allocCon (js, JSIdent name) =
1308 JSAlloc name (Just js)
1311 isConstant :: JS -> Bool
1312 isConstant js
1313 | JSNew "__IDRRT__Con" args <- js
1314 , all isConstant args =
1315 True
1316 | otherwise =
1317 isJSConstantConstructor globalCons js
1319 extractLocalConstructors' js = [js]
1322 getGlobalCons :: JS -> [String]
1323 getGlobalCons js = foldJS match (++) [] js
1324 where
1325 match :: JS -> [String]
1326 match js
1327 | (JSAlloc name (Just (JSNew "__IDRRT__Con" _))) <- js =
1328 [name]
1329 | otherwise =
1330 []
1333evalCons :: [JS] -> [JS]
1334evalCons js =
1335 map (collapseCont . collapseTC . expandProj . evalCons') js
1336 where
1337 cons :: [(String, JS)]
1338 cons = concatMap getGlobalCons js
1340 evalCons' :: JS -> JS
1341 evalCons' js = transformJS match js
1342 where
1343 match :: JS -> JS
1344 match (JSApp (JSIdent "__IDRRT__EVALTC") [arg])
1345 | JSIdent name <- arg
1346 , Just (JSNew _ [_, JSNull, _, _]) <- lookupConstructor name cons =
1347 arg
1349 match (JSApp (JSIdent "__IDR__mEVAL0") [arg])
1350 | JSIdent name <- arg
1351 , Just (JSNew _ [_, JSNull, _, _]) <- lookupConstructor name cons =
1352 arg
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
1366 where
1367 match :: JS -> JS
1368 match (
1369 JSIndex (
1370 JSProj (JSIdent name) "vars"
1371 ) (
1372 JSNum (JSInt idx)
1375 | Just (JSNew _ [_, _, _, JSArray args]) <- lookup name cons =
1376 args !! idx
1378 match js = transformJS match js
1381 collapseTC :: JS -> JS
1382 collapseTC js = transformJS match js
1383 where
1384 match :: JS -> JS
1385 match (JSApp (JSIdent "__IDRRT__tailcall") [JSFunction [] (
1386 JSReturn (JSIdent name)
1387 )])
1388 | Just _ <- lookup name cons = (JSIdent name)
1390 match js = transformJS match js
1393 collapseCont :: JS -> JS
1394 collapseCont js = transformJS match js
1395 where
1396 match :: JS -> 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)
1404 )]) = JSIdent name
1406 match (JSNew "__IDRRT__Cont" [JSFunction [] (
1407 JSReturn ret@(JSNew "__IDRRT__Con" [_, _, _, JSArray args])
1408 )])
1409 | all collapsable args = ret
1410 where
1411 collapsable :: JS -> Bool
1412 collapsable (JSIdent _) = True
1413 collapsable js = isJSConstantConstructor (map fst cons) js
1416 match js = transformJS match js
1419getGlobalCons :: JS -> [(String, JS)]
1420getGlobalCons js = foldJS match (++) [] js
1421 where
1422 match :: JS -> [(String, JS)]
1423 match js
1424 | (JSAlloc name (Just con@(JSNew "__IDRRT__Con" _))) <- js =
1425 [(name, con)]
1426 | (JSAlloc name (Just con@(JSIdent _))) <- js =
1427 [(name, con)]
1428 | otherwise =
1429 []
1432getIncludes :: [FilePath] -> IO [String]
1433getIncludes = mapM readFile
1435codegenJavaScript :: CodeGenerator
1436codegenJavaScript ci = codegenJS_all JavaScript (simpleDecls ci)
1437 (includes ci) (outputFile ci) (outputType ci)
1439codegenNode :: CodeGenerator
1440codegenNode ci = codegenJS_all Node (simpleDecls ci)
1441 (includes ci) (outputFile ci) (outputType ci)
1443codegenJS_all
1444 :: JSTarget
1445 -> [(Name, SDecl)]
1446 -> [FilePath]
1447 -> FilePath
1448 -> OutputType
1449 -> IO ()
1450codegenJS_all target definitions includes filename outputType = do
1451 let (header, rt) = case target of
1452 Node ->
1453 ("#!/usr/bin/env node\n", "-node")
1454 JavaScript ->
1455 ("", "-browser")
1456 included <- getIncludes includes
1457 path <- (++) <$> getDataDir <*> (pure "/jsrts/")
1458 idrRuntime <- readFile $ path ++ "Runtime-common.js"
1459 tgtRuntime <- readFile $ concat [path, "Runtime", rt, ".js"]
1460 jsbn <- readFile $ path ++ "jsbn/jsbn.js"
1461 writeFile filename $ header ++ (
1462 intercalate "\n" $ included ++ runtime jsbn idrRuntime tgtRuntime ++ functions
1465 setPermissions filename (emptyPermissions { readable = True
1466 , executable = target == Node
1467 , writable = True
1468 })
1469 where
1470 def :: [(String, SDecl)]
1471 def = map (first translateNamespace) definitions
1474 checkForBigInt :: [JS] -> Bool
1475 checkForBigInt js = occur
1476 where
1477 occur :: Bool
1478 occur = or $ map (foldJS match (||) False) js
1480 match :: JS -> Bool
1481 match (JSIdent "__IDRRT__bigInt") = True
1482 match (JSWord (JSWord64 _)) = True
1483 match (JSNum (JSInteger _)) = True
1484 match js = False
1487 runtime :: String -> String -> String -> [String]
1488 runtime jsbn idrRuntime tgtRuntime =
1489 if checkForBigInt optimized
1490 then [jsbn, idrRuntime, tgtRuntime]
1491 else [idrRuntime, tgtRuntime]
1494 optimized :: [JS]
1495 optimized = translate >>> optimize $ def
1496 where
1497 translate p =
1498 prelude ++ concatMap translateDeclaration p ++ [mainLoop, invokeLoop]
1499 optimize p =
1500 foldl' (flip ($)) p opt
1502 opt =
1503 [ removeEval
1504 , map inlineJS
1505 , removeIDs
1506 , reduceJS
1507 , map reduceConstants
1508 , initConstructors
1509 , map removeAllocations
1510 , elimDeadLoop
1511 , map elimDuplicateEvals
1512 , optimizeRuntimeCalls "__IDR__mEVAL0" "__IDRRT__EVALTC"
1513 , optimizeRuntimeCalls "__IDR__mAPPLY0" "__IDRRT__APPLYTC"
1514 , map removeInstanceChecks
1515 , inlineFunctions
1516 , map reduceContinuations
1517 , extractLocalConstructors
1518 , unfoldLookupTable
1519 , evalCons
1522 functions :: [String]
1523 functions = map compileJS optimized
1525 prelude :: [JS]
1526 prelude =
1527 [ JSAnnotation JSConstructor $
1528 JSAlloc (idrRTNamespace ++ "Cont") (Just $ JSFunction ["k"] (
1529 JSAssign (JSProj JSThis "k") (JSIdent "k")
1530 ))
1531 , JSAnnotation JSConstructor $
1532 JSAlloc (idrRTNamespace ++ "Con") (Just $ JSFunction ["tag", "vars"] (
1533 JSSeq [ JSAssign (JSProj JSThis "tag") (JSIdent "tag")
1534 , JSAssign (JSProj JSThis "vars") (JSIdent "vars")
1536 ))
1539 mainLoop :: JS
1540 mainLoop =
1541 JSAlloc "main" $ Just $ JSFunction [] (
1542 case target of
1543 Node -> mainFun
1544 JavaScript -> JSCond [(isReady, mainFun), (JSTrue, jsMeth (JSIdent "window") "addEventListener" [
1545 JSString "DOMContentLoaded", JSFunction [] (
1546 mainFun
1547 ), JSFalse
1548 ])]
1550 where
1551 mainFun :: JS
1552 mainFun = jsTailcall $ jsCall runMain []
1555 isReady :: JS
1556 isReady = readyState `jsEq` JSString "complete" `jsOr` readyState `jsEq` JSString "loaded"
1559 readyState :: JS
1560 readyState = JSProj (JSIdent "document") "readyState"
1563 runMain :: String
1564 runMain = idrNamespace ++ translateName (sMN 0 "runMain")
1567 invokeLoop :: JS
1568 invokeLoop = jsCall "main" []
1571translateIdentifier :: String -> String
1572translateIdentifier =
1573 replaceReserved . concatMap replaceBadChars
1574 where replaceBadChars :: Char -> String
1575 replaceBadChars c
1576 | ' ' <- c = "_"
1577 | '_' <- c = "__"
1578 | isDigit c = '_' : show (ord c)
1579 | not (isLetter c && isAscii c) = '_' : show (ord c)
1580 | otherwise = [c]
1581 replaceReserved s
1582 | s `elem` reserved = '_' : s
1583 | otherwise = s
1586 reserved = [ "break"
1587 , "case"
1588 , "catch"
1589 , "continue"
1590 , "debugger"
1591 , "default"
1592 , "delete"
1593 , "do"
1594 , "else"
1595 , "finally"
1596 , "for"
1597 , "function"
1598 , "if"
1599 , "in"
1600 , "instanceof"
1601 , "new"
1602 , "return"
1603 , "switch"
1604 , "this"
1605 , "throw"
1606 , "try"
1607 , "typeof"
1608 , "var"
1609 , "void"
1610 , "while"
1611 , "with"
1613 , "class"
1614 , "enum"
1615 , "export"
1616 , "extends"
1617 , "import"
1618 , "super"
1620 , "implements"
1621 , "interface"
1622 , "let"
1623 , "package"
1624 , "private"
1625 , "protected"
1626 , "public"
1627 , "static"
1628 , "yield"
1632translateNamespace :: Name -> String
1633translateNamespace (UN _) = idrNamespace
1634translateNamespace (NS _ ns) = idrNamespace ++ concatMap (translateIdentifier . str) ns
1635translateNamespace (MN _ _) = idrNamespace
1636translateNamespace (SN name) = idrNamespace ++ translateSpecialName name
1637translateNamespace NErased = idrNamespace
1640translateName :: Name -> String
1641translateName (UN name) = 'u' : translateIdentifier (str name)
1642translateName (NS name _) = 'n' : translateName name
1643translateName (MN i name) = 'm' : translateIdentifier (str name) ++ show i
1644translateName (SN name) = 's' : translateSpecialName name
1645translateName NErased = "e"
1648translateSpecialName :: SpecialName -> String
1649translateSpecialName name
1650 | WhereN i m n <- name =
1651 'w' : translateName m ++ translateName n ++ show i
1652 | InstanceN n s <- name =
1653 'i' : translateName n ++ concatMap (translateIdentifier . str) s
1654 | ParentN n s <- name =
1655 'p' : translateName n ++ translateIdentifier (str s)
1656 | MethodN n <- name =
1657 'm' : translateName n
1658 | CaseN n <- name =
1659 'c' : translateName n
1662translateConstant :: Const -> JS
1663translateConstant (I i) = JSNum (JSInt i)
1664translateConstant (Fl f) = JSNum (JSFloat f)
1665translateConstant (Ch c) = JSString $ translateChar c
1666translateConstant (Str s) = JSString $ concatMap translateChar s
1667translateConstant (AType (ATInt ITNative)) = JSType JSIntTy
1668translateConstant StrType = JSType JSStringTy
1669translateConstant (AType (ATInt ITBig)) = JSType JSIntegerTy
1670translateConstant (AType ATFloat) = JSType JSFloatTy
1671translateConstant (AType (ATInt ITChar)) = JSType JSCharTy
1672translateConstant PtrType = JSType JSPtrTy
1673translateConstant Forgot = JSType JSForgotTy
1674translateConstant (BI i) = jsBigInt $ JSString (show i)
1675translateConstant (B8 b) = JSWord (JSWord8 b)
1676translateConstant (B16 b) = JSWord (JSWord16 b)
1677translateConstant (B32 b) = JSWord (JSWord32 b)
1678translateConstant (B64 b) = JSWord (JSWord64 b)
1679translateConstant c =
1680 jsError $ "Unimplemented Constant: " ++ show c
1683translateChar :: Char -> String
1684translateChar ch
1685 | '\a' <- ch = "\\u0007"
1686 | '\b' <- ch = "\\b"
1687 | '\f' <- ch = "\\f"
1688 | '\n' <- ch = "\\n"
1689 | '\r' <- ch = "\\r"
1690 | '\t' <- ch = "\\t"
1691 | '\v' <- ch = "\\v"
1692 | '\SO' <- ch = "\\u000E"
1693 | '\DEL' <- ch = "\\u007F"
1694 | '\\' <- ch = "\\\\"
1695 | '\"' <- ch = "\\\""
1696 | '\'' <- ch = "\\\'"
1697 | ch `elem` asciiTab = "\\u00" ++ fill (showIntAtBase 16 intToDigit (ord ch) "")
1698 | otherwise = [ch]
1699 where
1700 fill :: String -> String
1701 fill s = if length s == 1
1702 then '0' : s
1703 else s
1705 asciiTab =
1706 ['\NUL', '\SOH', '\STX', '\ETX', '\EOT', '\ENQ', '\ACK', '\BEL',
1707 '\BS', '\HT', '\LF', '\VT', '\FF', '\CR', '\SO', '\SI',
1708 '\DLE', '\DC1', '\DC2', '\DC3', '\DC4', '\NAK', '\SYN', '\ETB',
1709 '\CAN', '\EM', '\SUB', '\ESC', '\FS', '\GS', '\RS', '\US']
1712translateDeclaration :: (String, SDecl) -> [JS]
1713translateDeclaration (path, SFun name params stackSize body)
1714 | (MN _ ap) <- name
1715 , (SChkCase var cases) <- body
1716 , ap == txt "APPLY" =
1717 [ lookupTable "APPLY" [] var cases
1718 , jsDecl $ JSFunction ["mfn0", "marg0"] (JSReturn $
1719 JSTernary (
1720 (JSIdent "mfn0" `jsInstanceOf` jsCon) `jsAnd`
1721 (hasProp (idrLTNamespace ++ "APPLY") "mfn0")
1722 ) (JSApp
1723 (JSIndex
1724 (JSIdent (idrLTNamespace ++ "APPLY"))
1725 (JSProj (JSIdent "mfn0") "tag")
1727 [JSIdent "mfn0", JSIdent "marg0"]
1728 ) JSNull
1732 | (MN _ ev) <- name
1733 , (SChkCase var cases) <- body
1734 , ev == txt "EVAL" =
1735 [ lookupTable "EVAL" [] var cases
1736 , jsDecl $ JSFunction ["marg0"] (JSReturn $
1737 JSTernary (
1738 (JSIdent "marg0" `jsInstanceOf` jsCon) `jsAnd`
1739 (hasProp (idrLTNamespace ++ "EVAL") "marg0")
1740 ) (JSApp
1741 (JSIndex
1742 (JSIdent (idrLTNamespace ++ "EVAL"))
1743 (JSProj (JSIdent "marg0") "tag")
1745 [JSIdent "marg0"]
1746 ) (JSIdent "marg0")
1749 | otherwise =
1750 let fun = translateExpression body in
1751 [jsDecl $ jsFun fun]
1753 where
1754 hasProp :: String -> String -> JS
1755 hasProp table var =
1756 JSIndex (JSIdent table) (JSProj (JSIdent var) "tag")
1759 caseFun :: [(LVar, String)] -> LVar -> SAlt -> JS
1760 caseFun aux var cse =
1761 let (JSReturn c) = translateCase (Just (translateVariableName var)) cse in
1762 jsFunAux aux c
1765 getTag :: SAlt -> Maybe Int
1766 getTag (SConCase _ tag _ _ _) = Just tag
1767 getTag _ = Nothing
1770 lookupTable :: String -> [(LVar, String)] -> LVar -> [SAlt] -> JS
1771 lookupTable table aux var cases =
1772 JSAlloc (idrLTNamespace ++ table) $ Just (
1773 JSApp (JSFunction [] (
1774 JSSeq $ [
1775 JSAlloc "t" $ Just (JSArray [])
1776 ] ++ assignEntries (catMaybes $ map (lookupEntry aux var) cases) ++ [
1777 JSReturn (JSIdent "t")
1779 )) []
1781 where
1782 assignEntries :: [(Int, JS)] -> [JS]
1783 assignEntries entries =
1784 map (\(tag, fun) ->
1785 JSAssign (JSIndex (JSIdent "t") (JSNum $ JSInt tag)) fun
1786 ) entries
1789 lookupEntry :: [(LVar, String)] -> LVar -> SAlt -> Maybe (Int, JS)
1790 lookupEntry aux var alt = do
1791 tag <- getTag alt
1792 return (tag, caseFun aux var alt)
1795 jsDecl :: JS -> JS
1796 jsDecl = JSAlloc (path ++ translateName name) . Just
1799 jsFun body = jsFunAux [] body
1802 jsFunAux :: [(LVar, String)] -> JS -> JS
1803 jsFunAux aux body =
1804 JSFunction (p ++ map snd aux) (
1805 JSSeq $
1806 zipWith assignVar [0..] p ++
1807 map assignAux aux ++
1808 [JSReturn body]
1810 where
1811 assignVar :: Int -> String -> JS
1812 assignVar n s = JSAlloc (jsVar n) (Just $ JSIdent s)
1815 assignAux :: (LVar, String) -> JS
1816 assignAux (Loc var, val) =
1817 JSAlloc (jsVar var) (Just $ JSIdent val)
1820 p :: [String]
1821 p = map translateName params
1824translateVariableName :: LVar -> String
1825translateVariableName (Loc i) =
1826 jsVar i
1829translateExpression :: SExp -> JS
1830translateExpression (SLet name value body) =
1831 jsLet (translateVariableName name) (
1832 translateExpression value
1833 ) (translateExpression body)
1835translateExpression (SConst cst) =
1836 translateConstant cst
1838translateExpression (SV var) =
1839 JSVar var
1841translateExpression (SApp tc name vars)
1842 | False <- tc =
1843 jsTailcall $ translateFunctionCall name vars
1844 | True <- tc =
1845 JSNew (idrRTNamespace ++ "Cont") [JSFunction [] (
1846 JSReturn $ translateFunctionCall name vars
1847 )]
1848 where
1849 translateFunctionCall name vars =
1850 jsCall (translateNamespace name ++ translateName name) (map JSVar vars)
1852translateExpression (SOp op vars)
1853 | LNoOp <- op = JSVar (last vars)
1855 | (LZExt (ITFixed IT8) ITNative) <- op = jsUnPackBits $ JSVar (last vars)
1856 | (LZExt (ITFixed IT16) ITNative) <- op = jsUnPackBits $ JSVar (last vars)
1857 | (LZExt (ITFixed IT32) ITNative) <- op = jsUnPackBits $ JSVar (last vars)
1859 | (LZExt _ ITBig) <- op = jsBigInt $ jsCall "String" [JSVar (last vars)]
1860 | (LPlus (ATInt ITBig)) <- op
1861 , (lhs:rhs:_) <- vars = invokeMeth lhs "add" [rhs]
1862 | (LMinus (ATInt ITBig)) <- op
1863 , (lhs:rhs:_) <- vars = invokeMeth lhs "subtract" [rhs]
1864 | (LTimes (ATInt ITBig)) <- op
1865 , (lhs:rhs:_) <- vars = invokeMeth lhs "multiply" [rhs]
1866 | (LSDiv (ATInt ITBig)) <- op
1867 , (lhs:rhs:_) <- vars = invokeMeth lhs "divide" [rhs]
1868 | (LSRem (ATInt ITBig)) <- op
1869 , (lhs:rhs:_) <- vars = invokeMeth lhs "mod" [rhs]
1870 | (LEq (ATInt ITBig)) <- op
1871 , (lhs:rhs:_) <- vars = invokeMeth lhs "equals" [rhs]
1872 | (LSLt (ATInt ITBig)) <- op
1873 , (lhs:rhs:_) <- vars = invokeMeth lhs "lesser" [rhs]
1874 | (LSLe (ATInt ITBig)) <- op
1875 , (lhs:rhs:_) <- vars = invokeMeth lhs "lesserOrEquals" [rhs]
1876 | (LSGt (ATInt ITBig)) <- op
1877 , (lhs:rhs:_) <- vars = invokeMeth lhs "greater" [rhs]
1878 | (LSGe (ATInt ITBig)) <- op
1879 , (lhs:rhs:_) <- vars = invokeMeth lhs "greaterOrEquals" [rhs]
1881 | (LPlus ATFloat) <- op
1882 , (lhs:rhs:_) <- vars = translateBinaryOp "+" lhs rhs
1883 | (LMinus ATFloat) <- op
1884 , (lhs:rhs:_) <- vars = translateBinaryOp "-" lhs rhs
1885 | (LTimes ATFloat) <- op
1886 , (lhs:rhs:_) <- vars = translateBinaryOp "*" lhs rhs
1887 | (LSDiv ATFloat) <- op
1888 , (lhs:rhs:_) <- vars = translateBinaryOp "/" lhs rhs
1889 | (LEq ATFloat) <- op
1890 , (lhs:rhs:_) <- vars = translateBinaryOp "==" lhs rhs
1891 | (LSLt ATFloat) <- op
1892 , (lhs:rhs:_) <- vars = translateBinaryOp "<" lhs rhs
1893 | (LSLe ATFloat) <- op
1894 , (lhs:rhs:_) <- vars = translateBinaryOp "<=" lhs rhs
1895 | (LSGt ATFloat) <- op
1896 , (lhs:rhs:_) <- vars = translateBinaryOp ">" lhs rhs
1897 | (LSGe ATFloat) <- op
1898 , (lhs:rhs:_) <- vars = translateBinaryOp ">=" lhs rhs
1900 | (LPlus (ATInt ITChar)) <- op
1901 , (lhs:rhs:_) <- vars =
1902 jsCall "__IDRRT__fromCharCode" [
1903 JSBinOp "+" (
1904 jsCall "__IDRRT__charCode" [JSVar lhs]
1905 ) (
1906 jsCall "__IDRRT__charCode" [JSVar rhs]
1910 | (LTrunc (ITFixed IT16) (ITFixed IT8)) <- op
1911 , (arg:_) <- vars =
1912 jsPackUBits8 (
1913 JSBinOp "&" (jsUnPackBits $ JSVar arg) (JSNum (JSInt 0xFF))
1916 | (LTrunc (ITFixed IT32) (ITFixed IT16)) <- op
1917 , (arg:_) <- vars =
1918 jsPackUBits16 (
1919 JSBinOp "&" (jsUnPackBits $ JSVar arg) (JSNum (JSInt 0xFFFF))
1922 | (LTrunc (ITFixed IT64) (ITFixed IT32)) <- op
1923 , (arg:_) <- vars =
1924 jsPackUBits32 (
1925 jsMeth (jsMeth (JSVar arg) "and" [
1926 jsBigInt (JSString $ show 0xFFFFFFFF)
1927 ]) "intValue" []
1930 | (LTrunc ITBig (ITFixed IT64)) <- op
1931 , (arg:_) <- vars =
1932 jsMeth (JSVar arg) "and" [
1933 jsBigInt (JSString $ show 0xFFFFFFFFFFFFFFFF)
1936 | (LLSHR (ITFixed IT8)) <- op
1937 , (lhs:rhs:_) <- vars =
1938 jsPackUBits8 (
1939 JSBinOp ">>" (jsUnPackBits $ JSVar lhs) (jsUnPackBits $ JSVar rhs)
1942 | (LLSHR (ITFixed IT16)) <- op
1943 , (lhs:rhs:_) <- vars =
1944 jsPackUBits16 (
1945 JSBinOp ">>" (jsUnPackBits $ JSVar lhs) (jsUnPackBits $ JSVar rhs)
1948 | (LLSHR (ITFixed IT32)) <- op
1949 , (lhs:rhs:_) <- vars =
1950 jsPackUBits32 (
1951 JSBinOp ">>" (jsUnPackBits $ JSVar lhs) (jsUnPackBits $ JSVar rhs)
1954 | (LLSHR (ITFixed IT64)) <- op
1955 , (lhs:rhs:_) <- vars =
1956 jsMeth (JSVar lhs) "shiftRight" [JSVar rhs]
1958 | (LSHL (ITFixed IT8)) <- op
1959 , (lhs:rhs:_) <- vars =
1960 jsPackUBits8 (
1961 JSBinOp "<<" (jsUnPackBits $ JSVar lhs) (jsUnPackBits $ JSVar rhs)
1964 | (LSHL (ITFixed IT16)) <- op
1965 , (lhs:rhs:_) <- vars =
1966 jsPackUBits16 (
1967 JSBinOp "<<" (jsUnPackBits $ JSVar lhs) (jsUnPackBits $ JSVar rhs)
1970 | (LSHL (ITFixed IT32)) <- op
1971 , (lhs:rhs:_) <- vars =
1972 jsPackUBits32 (
1973 JSBinOp "<<" (jsUnPackBits $ JSVar lhs) (jsUnPackBits $ JSVar rhs)
1976 | (LSHL (ITFixed IT64)) <- op
1977 , (lhs:rhs:_) <- vars =
1978 jsMeth (jsMeth (JSVar lhs) "shiftLeft" [JSVar rhs]) "and" [
1979 jsBigInt (JSString $ show 0xFFFFFFFFFFFFFFFF)
1982 | (LAnd (ITFixed IT8)) <- op
1983 , (lhs:rhs:_) <- vars =
1984 jsPackUBits8 (
1985 JSBinOp "&" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
1988 | (LAnd (ITFixed IT16)) <- op
1989 , (lhs:rhs:_) <- vars =
1990 jsPackUBits16 (
1991 JSBinOp "&" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
1994 | (LAnd (ITFixed IT32)) <- op
1995 , (lhs:rhs:_) <- vars =
1996 jsPackUBits32 (
1997 JSBinOp "&" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2000 | (LAnd (ITFixed IT64)) <- op
2001 , (lhs:rhs:_) <- vars =
2002 jsMeth (JSVar lhs) "and" [JSVar rhs]
2004 | (LOr (ITFixed IT8)) <- op
2005 , (lhs:rhs:_) <- vars =
2006 jsPackUBits8 (
2007 JSBinOp "|" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2010 | (LOr (ITFixed IT16)) <- op
2011 , (lhs:rhs:_) <- vars =
2012 jsPackUBits16 (
2013 JSBinOp "|" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2016 | (LOr (ITFixed IT32)) <- op
2017 , (lhs:rhs:_) <- vars =
2018 jsPackUBits32 (
2019 JSBinOp "|" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2022 | (LOr (ITFixed IT64)) <- op
2023 , (lhs:rhs:_) <- vars =
2024 jsMeth (JSVar lhs) "or" [JSVar rhs]
2026 | (LXOr (ITFixed IT8)) <- op
2027 , (lhs:rhs:_) <- vars =
2028 jsPackUBits8 (
2029 JSBinOp "^" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2032 | (LXOr (ITFixed IT16)) <- op
2033 , (lhs:rhs:_) <- vars =
2034 jsPackUBits16 (
2035 JSBinOp "^" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2038 | (LXOr (ITFixed IT32)) <- op
2039 , (lhs:rhs:_) <- vars =
2040 jsPackUBits32 (
2041 JSBinOp "^" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2044 | (LXOr (ITFixed IT64)) <- op
2045 , (lhs:rhs:_) <- vars =
2046 jsMeth (JSVar lhs) "xor" [JSVar rhs]
2048 | (LPlus (ATInt (ITFixed IT8))) <- op
2049 , (lhs:rhs:_) <- vars =
2050 jsPackUBits8 (
2051 JSBinOp "+" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2054 | (LPlus (ATInt (ITFixed IT16))) <- op
2055 , (lhs:rhs:_) <- vars =
2056 jsPackUBits16 (
2057 JSBinOp "+" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2060 | (LPlus (ATInt (ITFixed IT32))) <- op
2061 , (lhs:rhs:_) <- vars =
2062 jsPackUBits32 (
2063 JSBinOp "+" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2066 | (LPlus (ATInt (ITFixed IT64))) <- op
2067 , (lhs:rhs:_) <- vars =
2068 jsMeth (jsMeth (JSVar lhs) "add" [JSVar rhs]) "and" [
2069 jsBigInt (JSString $ show 0xFFFFFFFFFFFFFFFF)
2072 | (LMinus (ATInt (ITFixed IT8))) <- op
2073 , (lhs:rhs:_) <- vars =
2074 jsPackUBits8 (
2075 JSBinOp "-" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2078 | (LMinus (ATInt (ITFixed IT16))) <- op
2079 , (lhs:rhs:_) <- vars =
2080 jsPackUBits16 (
2081 JSBinOp "-" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2084 | (LMinus (ATInt (ITFixed IT32))) <- op
2085 , (lhs:rhs:_) <- vars =
2086 jsPackUBits32 (
2087 JSBinOp "-" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2090 | (LMinus (ATInt (ITFixed IT64))) <- op
2091 , (lhs:rhs:_) <- vars =
2092 jsMeth (jsMeth (JSVar lhs) "subtract" [JSVar rhs]) "and" [
2093 jsBigInt (JSString $ show 0xFFFFFFFFFFFFFFFF)
2096 | (LTimes (ATInt (ITFixed IT8))) <- op
2097 , (lhs:rhs:_) <- vars =
2098 jsPackUBits8 (
2099 JSBinOp "*" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2102 | (LTimes (ATInt (ITFixed IT16))) <- op
2103 , (lhs:rhs:_) <- vars =
2104 jsPackUBits16 (
2105 JSBinOp "*" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2108 | (LTimes (ATInt (ITFixed IT32))) <- op
2109 , (lhs:rhs:_) <- vars =
2110 jsPackUBits32 (
2111 JSBinOp "*" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2114 | (LTimes (ATInt (ITFixed IT64))) <- op
2115 , (lhs:rhs:_) <- vars =
2116 jsMeth (jsMeth (JSVar lhs) "multiply" [JSVar rhs]) "and" [
2117 jsBigInt (JSString $ show 0xFFFFFFFFFFFFFFFF)
2120 | (LEq (ATInt (ITFixed IT8))) <- op
2121 , (lhs:rhs:_) <- vars =
2122 jsPackUBits8 (
2123 JSBinOp "==" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2126 | (LEq (ATInt (ITFixed IT16))) <- op
2127 , (lhs:rhs:_) <- vars =
2128 jsPackUBits16 (
2129 JSBinOp "==" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2132 | (LEq (ATInt (ITFixed IT32))) <- op
2133 , (lhs:rhs:_) <- vars =
2134 jsPackUBits32 (
2135 JSBinOp "==" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2138 | (LEq (ATInt (ITFixed IT64))) <- op
2139 , (lhs:rhs:_) <- vars =
2140 jsMeth (jsMeth (JSVar lhs) "equals" [JSVar rhs]) "and" [
2141 jsBigInt (JSString $ show 0xFFFFFFFFFFFFFFFF)
2144 | (LLt (ITFixed IT8)) <- op
2145 , (lhs:rhs:_) <- vars =
2146 jsPackUBits8 (
2147 JSBinOp "<" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2150 | (LLt (ITFixed IT16)) <- op
2151 , (lhs:rhs:_) <- vars =
2152 jsPackUBits16 (
2153 JSBinOp "<" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2156 | (LLt (ITFixed IT32)) <- op
2157 , (lhs:rhs:_) <- vars =
2158 jsPackUBits32 (
2159 JSBinOp "<" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2162 | (LLt (ITFixed IT64)) <- op
2163 , (lhs:rhs:_) <- vars = invokeMeth lhs "lesser" [rhs]
2165 | (LLe (ITFixed IT8)) <- op
2166 , (lhs:rhs:_) <- vars =
2167 jsPackUBits8 (
2168 JSBinOp "<=" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2171 | (LLe (ITFixed IT16)) <- op
2172 , (lhs:rhs:_) <- vars =
2173 jsPackUBits16 (
2174 JSBinOp "<=" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2177 | (LLe (ITFixed IT32)) <- op
2178 , (lhs:rhs:_) <- vars =
2179 jsPackUBits32 (
2180 JSBinOp "<=" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2183 | (LLe (ITFixed IT64)) <- op
2184 , (lhs:rhs:_) <- vars = invokeMeth lhs "lesserOrEquals" [rhs]
2186 | (LGt (ITFixed IT8)) <- op
2187 , (lhs:rhs:_) <- vars =
2188 jsPackUBits8 (
2189 JSBinOp ">" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2192 | (LGt (ITFixed IT16)) <- op
2193 , (lhs:rhs:_) <- vars =
2194 jsPackUBits16 (
2195 JSBinOp ">" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2197 | (LGt (ITFixed IT32)) <- op
2198 , (lhs:rhs:_) <- vars =
2199 jsPackUBits32 (
2200 JSBinOp ">" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2203 | (LGt (ITFixed IT64)) <- op
2204 , (lhs:rhs:_) <- vars = invokeMeth lhs "greater" [rhs]
2206 | (LGe (ITFixed IT8)) <- op
2207 , (lhs:rhs:_) <- vars =
2208 jsPackUBits8 (
2209 JSBinOp ">=" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2212 | (LGe (ITFixed IT16)) <- op
2213 , (lhs:rhs:_) <- vars =
2214 jsPackUBits16 (
2215 JSBinOp ">=" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2217 | (LGe (ITFixed IT32)) <- op
2218 , (lhs:rhs:_) <- vars =
2219 jsPackUBits32 (
2220 JSBinOp ">=" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2223 | (LGe (ITFixed IT64)) <- op
2224 , (lhs:rhs:_) <- vars = invokeMeth lhs "greaterOrEquals" [rhs]
2226 | (LUDiv (ITFixed IT8)) <- op
2227 , (lhs:rhs:_) <- vars =
2228 jsPackUBits8 (
2229 JSBinOp "/" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2232 | (LUDiv (ITFixed IT16)) <- op
2233 , (lhs:rhs:_) <- vars =
2234 jsPackUBits16 (
2235 JSBinOp "/" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2238 | (LUDiv (ITFixed IT32)) <- op
2239 , (lhs:rhs:_) <- vars =
2240 jsPackUBits32 (
2241 JSBinOp "/" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
2244 | (LUDiv (ITFixed IT64)) <- op
2245 , (lhs:rhs:_) <- vars = invokeMeth lhs "divide" [rhs]
2247 | (LSDiv (ATInt (ITFixed IT8))) <- op
2248 , (lhs:rhs:_) <- vars =
2249 jsPackSBits8 (
2250 JSBinOp "/" (
2251 jsUnPackBits $ jsPackSBits8 $ jsUnPackBits (JSVar lhs)
2252 ) (
2253 jsUnPackBits $ jsPackSBits8 $ jsUnPackBits (JSVar rhs)
2257 | (LSDiv (ATInt (ITFixed IT16))) <- op
2258 , (lhs:rhs:_) <- vars =
2259 jsPackSBits16 (
2260 JSBinOp "/" (
2261 jsUnPackBits $ jsPackSBits16 $ jsUnPackBits (JSVar lhs)
2262 ) (
2263 jsUnPackBits $ jsPackSBits16 $ jsUnPackBits (JSVar rhs)
2267 | (LSDiv (ATInt (ITFixed IT32))) <- op
2268 , (lhs:rhs:_) <- vars =
2269 jsPackSBits32 (
2270 JSBinOp "/" (
2271 jsUnPackBits $ jsPackSBits32 $ jsUnPackBits (JSVar lhs)
2272 ) (
2273 jsUnPackBits $ jsPackSBits32 $ jsUnPackBits (JSVar rhs)
2277 | (LSDiv (ATInt (ITFixed IT64))) <- op
2278 , (lhs:rhs:_) <- vars = invokeMeth lhs "divide" [rhs]
2280 | (LSRem (ATInt (ITFixed IT8))) <- op
2281 , (lhs:rhs:_) <- vars =
2282 jsPackSBits8 (
2283 JSBinOp "%" (
2284 jsUnPackBits $ jsPackSBits8 $ jsUnPackBits (JSVar lhs)
2285 ) (
2286 jsUnPackBits $ jsPackSBits8 $ jsUnPackBits (JSVar rhs)
2290 | (LSRem (ATInt (ITFixed IT16))) <- op
2291 , (lhs:rhs:_) <- vars =
2292 jsPackSBits16 (
2293 JSBinOp "%" (
2294 jsUnPackBits $ jsPackSBits16 $ jsUnPackBits (JSVar lhs)
2295 ) (
2296 jsUnPackBits $ jsPackSBits16 $ jsUnPackBits (JSVar rhs)
2300 | (LSRem (ATInt (ITFixed IT32))) <- op
2301 , (lhs:rhs:_) <- vars =
2302 jsPackSBits32 (
2303 JSBinOp "%" (
2304 jsUnPackBits $ jsPackSBits32 $ jsUnPackBits (JSVar lhs)
2305 ) (
2306 jsUnPackBits $ jsPackSBits32 $ jsUnPackBits (JSVar rhs)
2310 | (LSRem (ATInt (ITFixed IT64))) <- op
2311 , (lhs:rhs:_) <- vars = invokeMeth lhs "mod" [rhs]
2313 | (LCompl (ITFixed IT8)) <- op
2314 , (arg:_) <- vars =
2315 jsPackSBits8 $ JSPreOp "~" $ jsUnPackBits (JSVar arg)
2317 | (LCompl (ITFixed IT16)) <- op
2318 , (arg:_) <- vars =
2319 jsPackSBits16 $ JSPreOp "~" $ jsUnPackBits (JSVar arg)
2321 | (LCompl (ITFixed IT32)) <- op
2322 , (arg:_) <- vars =
2323 jsPackSBits32 $ JSPreOp "~" $ jsUnPackBits (JSVar arg)
2325 | (LCompl (ITFixed IT64)) <- op
2326 , (arg:_) <- vars =
2327 invokeMeth arg "not" []
2329 | (LPlus _) <- op
2330 , (lhs:rhs:_) <- vars = translateBinaryOp "+" lhs rhs
2331 | (LMinus _) <- op
2332 , (lhs:rhs:_) <- vars = translateBinaryOp "-" lhs rhs
2333 | (LTimes _) <- op
2334 , (lhs:rhs:_) <- vars = translateBinaryOp "*" lhs rhs
2335 | (LSDiv _) <- op
2336 , (lhs:rhs:_) <- vars = translateBinaryOp "/" lhs rhs
2337 | (LSRem _) <- op
2338 , (lhs:rhs:_) <- vars = translateBinaryOp "%" lhs rhs
2339 | (LEq _) <- op
2340 , (lhs:rhs:_) <- vars = translateBinaryOp "==" lhs rhs
2341 | (LSLt _) <- op
2342 , (lhs:rhs:_) <- vars = translateBinaryOp "<" lhs rhs
2343 | (LSLe _) <- op
2344 , (lhs:rhs:_) <- vars = translateBinaryOp "<=" lhs rhs
2345 | (LSGt _) <- op
2346 , (lhs:rhs:_) <- vars = translateBinaryOp ">" lhs rhs
2347 | (LSGe _) <- op
2348 , (lhs:rhs:_) <- vars = translateBinaryOp ">=" lhs rhs
2349 | (LAnd _) <- op
2350 , (lhs:rhs:_) <- vars = translateBinaryOp "&" lhs rhs
2351 | (LOr _) <- op
2352 , (lhs:rhs:_) <- vars = translateBinaryOp "|" lhs rhs
2353 | (LXOr _) <- op
2354 , (lhs:rhs:_) <- vars = translateBinaryOp "^" lhs rhs
2355 | (LSHL _) <- op
2356 , (lhs:rhs:_) <- vars = translateBinaryOp "<<" rhs lhs
2357 | (LASHR _) <- op
2358 , (lhs:rhs:_) <- vars = translateBinaryOp ">>" rhs lhs
2359 | (LCompl _) <- op
2360 , (arg:_) <- vars = JSPreOp "~" (JSVar arg)
2362 | LStrConcat <- op
2363 , (lhs:rhs:_) <- vars = invokeMeth lhs "concat" [rhs]
2364 | LStrEq <- op
2365 , (lhs:rhs:_) <- vars = translateBinaryOp "==" lhs rhs
2366 | LStrLt <- op
2367 , (lhs:rhs:_) <- vars = translateBinaryOp "<" lhs rhs
2368 | LStrLen <- op
2369 , (arg:_) <- vars = JSProj (JSVar arg) "length"
2371 | (LStrInt ITNative) <- op
2372 , (arg:_) <- vars = jsCall "parseInt" [JSVar arg]
2373 | (LIntStr ITNative) <- op
2374 , (arg:_) <- vars = jsCall "String" [JSVar arg]
2375 | (LSExt ITNative ITBig) <- op
2376 , (arg:_) <- vars = jsBigInt $ jsCall "String" [JSVar arg]
2377 | (LTrunc ITBig ITNative) <- op
2378 , (arg:_) <- vars = jsMeth (JSVar arg) "intValue" []
2379 | (LIntStr ITBig) <- op
2380 , (arg:_) <- vars = jsMeth (JSVar arg) "toString" []
2381 | (LStrInt ITBig) <- op
2382 , (arg:_) <- vars = jsBigInt $ JSVar arg
2383 | LFloatStr <- op
2384 , (arg:_) <- vars = jsCall "String" [JSVar arg]
2385 | LStrFloat <- op
2386 , (arg:_) <- vars = jsCall "parseFloat" [JSVar arg]
2387 | (LIntFloat ITNative) <- op
2388 , (arg:_) <- vars = JSVar arg
2389 | (LFloatInt ITNative) <- op
2390 , (arg:_) <- vars = JSVar arg
2391 | (LChInt ITNative) <- op
2392 , (arg:_) <- vars = jsCall "__IDRRT__charCode" [JSVar arg]
2393 | (LIntCh ITNative) <- op
2394 , (arg:_) <- vars = jsCall "__IDRRT__fromCharCode" [JSVar arg]
2396 | LFExp <- op
2397 , (arg:_) <- vars = jsCall "Math.exp" [JSVar arg]
2398 | LFLog <- op
2399 , (arg:_) <- vars = jsCall "Math.log" [JSVar arg]
2400 | LFSin <- op
2401 , (arg:_) <- vars = jsCall "Math.sin" [JSVar arg]
2402 | LFCos <- op
2403 , (arg:_) <- vars = jsCall "Math.cos" [JSVar arg]
2404 | LFTan <- op
2405 , (arg:_) <- vars = jsCall "Math.tan" [JSVar arg]
2406 | LFASin <- op
2407 , (arg:_) <- vars = jsCall "Math.asin" [JSVar arg]
2408 | LFACos <- op
2409 , (arg:_) <- vars = jsCall "Math.acos" [JSVar arg]
2410 | LFATan <- op
2411 , (arg:_) <- vars = jsCall "Math.atan" [JSVar arg]
2412 | LFSqrt <- op
2413 , (arg:_) <- vars = jsCall "Math.sqrt" [JSVar arg]
2414 | LFFloor <- op
2415 , (arg:_) <- vars = jsCall "Math.floor" [JSVar arg]
2416 | LFCeil <- op
2417 , (arg:_) <- vars = jsCall "Math.ceil" [JSVar arg]
2419 | LStrCons <- op
2420 , (lhs:rhs:_) <- vars = invokeMeth lhs "concat" [rhs]
2421 | LStrHead <- op
2422 , (arg:_) <- vars = JSIndex (JSVar arg) (JSNum (JSInt 0))
2423 | LStrRev <- op
2424 , (arg:_) <- vars = JSProj (JSVar arg) "split('').reverse().join('')"
2425 | LStrIndex <- op
2426 , (lhs:rhs:_) <- vars = JSIndex (JSVar lhs) (JSVar rhs)
2427 | LStrTail <- op
2428 , (arg:_) <- vars = let v = translateVariableName arg in
2429 JSApp (JSProj (JSIdent v) "substr") [
2430 JSNum (JSInt 1),
2431 JSBinOp "-" (JSProj (JSIdent v) "length") (JSNum (JSInt 1))
2433 | LNullPtr <- op
2434 , (_) <- vars = JSNull
2436 where
2437 translateBinaryOp :: String -> LVar -> LVar -> JS
2438 translateBinaryOp f lhs rhs = JSParens $ JSBinOp f (JSVar lhs) (JSVar rhs)
2441 invokeMeth :: LVar -> String -> [LVar] -> JS
2442 invokeMeth obj meth args = jsMeth (JSVar obj) meth (map JSVar args)
2444translateExpression (SError msg) =
2445 jsError msg
2447translateExpression (SForeign _ _ "putStr" [(FString, var)]) =
2448 jsCall (idrRTNamespace ++ "print") [JSVar var]
2450translateExpression (SForeign _ _ "isNull" [(FPtr, var)]) =
2451 JSBinOp "==" (JSVar var) JSNull
2453translateExpression (SForeign _ _ "idris_eqPtr" [(FPtr, lhs),(FPtr, rhs)]) =
2454 JSBinOp "==" (JSVar lhs) (JSVar rhs)
2456translateExpression (SForeign _ _ "idris_time" []) =
2457 JSRaw "(new Date()).getTime()"
2459translateExpression (SForeign _ _ fun args) =
2460 JSFFI fun (map generateWrapper args)
2461 where
2462 generateWrapper (ffunc, name)
2463 | FFunction <- ffunc =
2464 JSApp (
2465 JSIdent $ idrRTNamespace ++ "ffiWrap"
2466 ) [JSIdent $ translateVariableName name]
2467 | FFunctionIO <- ffunc =
2468 JSApp (
2469 JSIdent $ idrRTNamespace ++ "ffiWrap"
2470 ) [JSIdent $ translateVariableName name]
2472 generateWrapper (_, name) =
2473 JSIdent $ translateVariableName name
2475translateExpression patterncase
2476 | (SChkCase var cases) <- patterncase = caseHelper var cases "chk"
2477 | (SCase var cases) <- patterncase = caseHelper var cases "cse"
2478 where
2479 caseHelper var cases param =
2480 JSApp (JSFunction [param] (
2481 JSCond $ map (expandCase param . translateCaseCond param) cases
2482 )) [JSVar var]
2485 expandCase :: String -> (Cond, JS) -> (JS, JS)
2486 expandCase _ (RawCond cond, branch) = (cond, branch)
2487 expandCase _ (CaseCond DefaultCase, branch) = (JSTrue , branch)
2488 expandCase var (CaseCond caseTy, branch)
2489 | ConCase tag <- caseTy =
2490 let checkCon = JSIdent var `jsInstanceOf` jsCon
2491 checkTag = (JSNum $ JSInt tag) `jsEq` jsTag (JSIdent var) in
2492 (checkCon `jsAnd` checkTag, branch)
2494 | TypeCase ty <- caseTy =
2495 let checkTy = JSIdent var `jsInstanceOf` jsType
2496 checkTag = jsTypeTag (JSIdent var) `jsEq` JSType ty in
2497 (checkTy `jsAnd` checkTag, branch)
2499translateExpression (SCon i name vars) =
2500 JSNew (idrRTNamespace ++ "Con") [ JSNum $ JSInt i
2501 , JSArray $ map JSVar vars
2504translateExpression (SUpdate var@(Loc i) e) =
2505 JSAssign (JSVar var) (translateExpression e)
2507translateExpression (SProj var i) =
2508 JSIndex (JSProj (JSVar var) "vars") (JSNum $ JSInt i)
2510translateExpression SNothing = JSNull
2512translateExpression e =
2513 jsError $ "Not yet implemented: " ++ filter (/= '\'') (show e)
2516data CaseType = ConCase Int
2517 | TypeCase JSType
2518 | DefaultCase
2519 deriving Eq
2522data Cond = CaseCond CaseType
2523 | RawCond JS
2526translateCaseCond :: String -> SAlt -> (Cond, JS)
2527translateCaseCond _ cse@(SDefaultCase _) =
2528 (CaseCond DefaultCase, translateCase Nothing cse)
2530translateCaseCond var cse@(SConstCase ty _)
2531 | StrType <- ty = matchHelper JSStringTy
2532 | PtrType <- ty = matchHelper JSPtrTy
2533 | Forgot <- ty = matchHelper JSForgotTy
2534 | (AType ATFloat) <- ty = matchHelper JSFloatTy
2535 | (AType (ATInt ITBig)) <- ty = matchHelper JSIntegerTy
2536 | (AType (ATInt ITNative)) <- ty = matchHelper JSIntTy
2537 | (AType (ATInt ITChar)) <- ty = matchHelper JSCharTy
2538 where
2539 matchHelper :: JSType -> (Cond, JS)
2540 matchHelper ty = (CaseCond $ TypeCase ty, translateCase Nothing cse)
2542translateCaseCond var cse@(SConstCase cst@(BI _) _) =
2543 let cond = jsMeth (JSIdent var) "equals" [translateConstant cst] in
2544 (RawCond cond, translateCase Nothing cse)
2546translateCaseCond var cse@(SConstCase cst _) =
2547 let cond = JSIdent var `jsEq` translateConstant cst in
2548 (RawCond cond, translateCase Nothing cse)
2550translateCaseCond var cse@(SConCase _ tag _ _ _) =
2551 (CaseCond $ ConCase tag, translateCase (Just var) cse)
2554translateCase :: Maybe String -> SAlt -> JS
2555translateCase _ (SDefaultCase e) = JSReturn $ translateExpression e
2556translateCase _ (SConstCase _ e) = JSReturn $ translateExpression e
2557translateCase (Just var) (SConCase a _ _ vars e) =
2558 let params = map jsVar [a .. (a + length vars)] in
2559 JSReturn $ jsMeth (JSFunction params (JSReturn $ translateExpression e)) "apply" [
2560 JSThis, JSProj (JSIdent var) "vars"