@@ -322,6 +322,17 @@ transformJS tr js =
322322 | otherwise = js
323323
324324
325+moveJSDeclToTop :: String -> [JS] -> [JS]
326+moveJSDeclToTop decl js = move ([], js)
327+ where
328+ move :: ([JS], [JS]) -> [JS]
329+ move (front, js@(JSAlloc name _):back)
330+ | name == decl = js : front ++ back
331+
332+ move (front, js:back) =
333+ move (front ++ [js], back)
334+
335+
325336jsSubst :: JS -> JS -> JS -> JS
326337jsSubst var new old
327338 | var == old = new
@@ -518,8 +529,12 @@ deadEvalApplyCases js =
518529initConstructors :: [JS] -> [JS]
519530initConstructors js =
520531 let tags = nub $ sort $ concat (map getTags js) in
521− map createConstant tags ++ replaceConstructors tags js
532+ rearrangePrelude $ map createConstant tags ++ replaceConstructors tags js
522533 where
534+ rearrangePrelude :: [JS] -> [JS]
535+ rearrangePrelude = moveJSDeclToTop $ idrRTNamespace ++ "Con"
536+
537+
523538 getTags :: JS -> [Int]
524539 getTags = foldJS match (++) []
525540 where
@@ -670,6 +685,8 @@ inlineFunctions js =
670685 match js
671686 | JSApp (JSIdent ident) _ <- js
672687 , name == ident = 1
688+ | JSNew con _ <- js
689+ , name == con = 1
673690 | otherwise = 0
674691
675692
@@ -854,9 +871,12 @@ codegenJavaScript target definitions filename outputType = do
854871 functions :: [String]
855872 functions = translate >>> optimize >>> compile $ def
856873 where
857− translate p = concatMap translateDeclaration p ++ [mainLoop, invokeLoop]
858− optimize p = foldl' (flip ($)) p opt
859− compile = map compileJS
874+ translate p =
875+ prelude ++ concatMap translateDeclaration p ++ [mainLoop, invokeLoop]
876+ optimize p =
877+ foldl' (flip ($)) p opt
878+ compile =
879+ map compileJS
860880
861881 opt =
862882 [ map optimizeJS
@@ -874,6 +894,17 @@ codegenJavaScript target definitions filename outputType = do
874894 , map reduceContinuations
875895 ]
876896
897+ prelude :: [JS]
898+ prelude =
899+ [ JSAlloc (idrRTNamespace ++ "Cont") (Just $ JSFunction ["k"] (
900+ JSAssign (JSProj JSThis "k") (JSIdent "k")
901+ ))
902+ , JSAlloc (idrRTNamespace ++ "Con") (Just $ JSFunction ["tag", "vars"] (
903+ JSSeq [ JSAssign (JSProj JSThis "tag") (JSIdent "tag")
904+ , JSAssign (JSProj JSThis "vars") (JSIdent "vars")
905+ ]
906+ ))
907+ ]
877908
878909 mainLoop :: JS
879910 mainLoop =