git.iko.soy/rowtype-yoga/purescript-native
on golang help sign in
More optimizations
commitfbbc197c661c87e80bc86d7a81c9c3f764501e4b authorPhil Freeman <paf31@cantab.net> dateFri 1 Nov 2013, 18:34 (13 years ago) parent36bae69
1 file changed+39−2
src/Language/PureScript/Optimize.hs+39−2
src/Language/PureScript/Optimize.hs+39−2
@@ -23,7 +23,7 @@ import Language.PureScript.Names
2323import Language.PureScript.CodeGen.JS.AST
2424
2525optimize :: JS -> JS
26−optimize = etaConvert . inlineVariables
26+optimize = removeUnusedVariables . unThunk . etaConvert . inlineVariables
2727
2828replaceIdent :: (Data d) => Ident -> JS -> d -> d
2929replaceIdent var1 js = everywhere (mkT replace)
@@ -31,9 +31,28 @@ replaceIdent var1 js = everywhere (mkT replace)
3131 replace (JSVar var2) | var1 == var2 = js
3232 replace js = js
3333
34+isReassigned :: (Data d) => Ident -> d -> Bool
35+isReassigned var1 = everything (||) (mkQ False check)
36+ where
37+ check :: JS -> Bool
38+ check (JSAssignment var2 _) | var1 == var2 = True
39+ check _ = False
40+
41+isUsed :: (Data d) => Ident -> d -> Bool
42+isUsed var1 = everything (||) (mkQ False check)
43+ where
44+ check :: JS -> Bool
45+ check (JSVar var2) | var1 == var2 = True
46+ check (JSAssignment var2 _) | var1 == var2 = True
47+ check _ = False
48+
3449shouldInline :: JS -> Bool
3550shouldInline (JSVar _) = True
51+shouldInline (JSNumericLiteral _) = True
52+shouldInline (JSStringLiteral _) = True
53+shouldInline (JSBooleanLiteral _) = True
3654shouldInline (JSAccessor _ val) = shouldInline val
55+shouldInline (JSIndexer index val) = shouldInline index && shouldInline val
3756shouldInline _ = False
3857
3958inlineVariables :: JS -> JS
@@ -44,7 +63,18 @@ inlineVariables = everywhere (mkT removeFromBlock)
4463 removeFromBlock js = js
4564 go :: [JS] -> [JS]
4665 go [] = []
47− go (JSVariableIntroduction var js : sts) | shouldInline js = go (replaceIdent var js sts)
66+ go (JSVariableIntroduction var js : sts) | shouldInline js && not (isReassigned var sts) = go (replaceIdent var js sts)
67+ go (s:sts) = s : go sts
68+
69+removeUnusedVariables :: JS -> JS
70+removeUnusedVariables = everywhere (mkT removeFromBlock)
71+ where
72+ removeFromBlock :: JS -> JS
73+ removeFromBlock (JSBlock sts) = JSBlock (go sts)
74+ removeFromBlock js = js
75+ go :: [JS] -> [JS]
76+ go [] = []
77+ go (JSVariableIntroduction var _ : sts) | not (isUsed var sts) = go sts
4878 go (s:sts) = s : go sts
4979
5080etaConvert :: JS -> JS
@@ -53,3 +83,10 @@ etaConvert = everywhere (mkT convert)
5383 convert :: JS -> JS
5484 convert (JSBlock [JSReturn (JSApp (JSFunction Nothing [ident] (JSBlock body)) [arg])]) | shouldInline arg = JSBlock (replaceIdent ident arg body)
5585 convert js = js
86+
87+unThunk :: JS -> JS
88+unThunk = everywhere (mkT convert)
89+ where
90+ convert :: JS -> JS
91+ convert (JSBlock [JSReturn (JSApp (JSFunction Nothing [] (JSBlock body)) [])]) = JSBlock body
92+ convert js = js