@@ -385,7 +385,8 @@ codegenJS_all target definitions includes libs filename outputType = do
385385 let bytecode = map toBC definitions
386386 let info = initCompileInfo bytecode
387387 let js = concatMap (translateDecl info) bytecode
388− let code = concatMap processFunction js
388+ let full = concatMap processFunction js
389+ let code = deadCodeElim full
389390 let (cons, opt) = optimizeConstructors code
390391 let (header, rt) = case target of
391392 Node -> ("#!/usr/bin/env node\n", "-node")
@@ -416,11 +417,59 @@ codegenJS_all target definitions includes libs filename outputType = do
416417 , writable = True
417418 })
418419 where
420+ deadCodeElim :: [JS] -> [JS]
421+ deadCodeElim js = concatMap collectFunctions js
422+ where
423+ collectFunctions :: JS -> [JS]
424+ collectFunctions fun@(JSAlloc name _)
425+ | name == translateName (sMN 0 "runMain") = [fun]
426+
427+ collectFunctions fun@(JSAlloc name (Just (JSFunction _ body))) =
428+ let invokations = sum $ map (
429+ \x -> execState (countInvokations name x) 0
430+ ) js
431+ in if invokations == 0
432+ then []
433+ else [fun]
434+
435+ countInvokations :: String -> JS -> State Int ()
436+ countInvokations name (JSAlloc _ (Just (JSFunction _ body))) =
437+ countInvokations name body
438+
439+ countInvokations name (JSSeq seq) =
440+ void $ traverse (countInvokations name) seq
441+
442+ countInvokations name (JSAssign _ rhs) =
443+ countInvokations name rhs
444+
445+ countInvokations name (JSCond conds) =
446+ void $ traverse (
447+ runKleisli $ arr id *** Kleisli (countInvokations name)
448+ ) conds
449+
450+ countInvokations name (JSSwitch _ conds def) =
451+ void $ traverse (
452+ runKleisli $ arr id *** Kleisli (countInvokations name)
453+ ) conds >> traverse (countInvokations name) def
454+
455+ countInvokations name (JSApp lhs rhs) =
456+ void $ countInvokations name lhs >> traverse (countInvokations name) rhs
457+
458+ countInvokations name (JSNew _ args) =
459+ void $ traverse (countInvokations name) args
460+
461+ countInvokations name (JSArray args) =
462+ void $ traverse (countInvokations name) args
463+
464+ countInvokations name (JSIdent name')
465+ | name == name' = get >>= put . (+1)
466+ | otherwise = return ()
467+
468+ countInvokations _ _ = return ()
469+
419470 processFunction :: JS -> [JS]
420− processFunction js =
421− (
422− collectSplitFunctions . (\x -> evalRWS (splitFunction x) () 0)
423− ) js
471+ processFunction =
472+ collectSplitFunctions . (\x -> evalRWS (splitFunction x) () 0)
424473
425474 includeLibs :: [String] -> String
426475 includeLibs =