@@ -21,7 +21,7 @@ module Language.PureScript.CodeGen.Cpp.Optimizer.Blocks
23import Prelude.Compat
23import Prelude.Compat
24−import Control.Monad (foldM)
24+import Data.Either
26import Language.PureScript.CodeGen.Cpp.AST
26import Language.PureScript.CodeGen.Cpp.AST
27import Language.PureScript.CodeGen.Cpp.Types
27import Language.PureScript.CodeGen.Cpp.Types
@@ -91,26 +91,19 @@ collapseCtorChecksToSwitch :: Cpp -> Cpp
91collapseCtorChecksToSwitch = everywhereOnCpp collapse
91collapseCtorChecksToSwitch = everywhereOnCpp collapse
93 collapse :: Cpp -> Cpp
93 collapse :: Cpp -> Cpp
94− collapse (CppBlock cpps) = CppBlock (go cpps)
94+ collapse (CppBlock cpps@(_:_:_)) = CppBlock (go cpps)
96− go cpps'
96+ go cpps'@(cpp:_)
97− | length cpps' > 2
97+ | Right (lhs, _, _) <- fromif Nothing cpp
98− , ifs <- init cpps'
98+ , (otherCpps, ifs@(_:_:_)) <- partitionEithers $ fromif (Just lhs) <$> cpps'
99− , def@(CppThrow _) <- last cpps'
99+ = CppSwitch lhs ((\(_,b,c) -> (b,c)) <$> ifs) Nothing : otherCpps
100− , Just (cond, _, _) <- fromif $ head ifs
101− , Just (cond', cases) <- foldM builder (cond, []) ifs
102− = [CppSwitch cond' cases (Just def)]
103− go (cpp' : cpps') = cpp' : go cpps'
100+ go (cpp':cpps') = cpp' : go cpps'
104 go cpp' = cpp'
101 go cpp' = cpp'
105− fromif :: Cpp -> Maybe (Cpp, Cpp, Cpp)
102+ fromif :: Maybe Cpp -> Cpp -> Either Cpp (Cpp, Cpp, Cpp)
106− fromif (CppIfElse (CppBinary EqualTo lhs rhs) stmt Nothing)
103+ fromif cond (CppIfElse (CppBinary EqualTo lhs rhs) stmt Nothing)
107 | CppApp (CppVar f) _ <- lhs
104 | CppApp (CppVar f) _ <- lhs
108− , f == getCtor = Just (lhs, rhs, stmt)
105+ , f == getCtor
109− fromif _ = Nothing
106+ , maybe True (lhs==) cond
110− builder :: (Cpp, [(Cpp, Cpp)]) -> Cpp -> Maybe (Cpp, [(Cpp, Cpp)])
111− builder (cond, cases) cpp
112− | Just (lhs, rhs, stmt) <- fromif cpp
114− = Just (cond, cases ++ [(rhs, stmt)])
107+ = Right (lhs, rhs, stmt)
115− builder _ _ = Nothing
108+ fromif _ cpp = Left cpp
116 collapse cpp = cpp
109 collapse cpp = cpp