1module Optimize (optimize) where
3import Control.Applicative
4import Control.Arrow (second)
5import qualified Control.Monad as M
6import qualified Control.Monad.State as State
7import qualified Data.Map as Map
9import qualified Data.Maybe as Maybe
10import qualified Data.Traversable as T
12import qualified AST.Expression.General as Expr
13import qualified AST.Expression.Canonical as Can
14import qualified AST.Expression.Optimized as Opt
15import qualified AST.Module as Module
16import qualified AST.Module.Name as ModuleName
17import qualified AST.Pattern as P
18import qualified AST.Variable as Var
19import Elm.Utils ((|>))
20import qualified Optimize.Cases as Cases
21import qualified Reporting.Annotation as A
22import qualified Reporting.Region as R
25-- OPTIMIZE - turn a canonical module into a list of optimized defs
27optimize :: Module.CanonicalModule -> Module.Optimized
34 flattenLets [] (Module.program (Module.body module_))
37 (concat <$> mapM (optimizeDef (Just home)) defs)
41flattenLets :: [Can.Def] -> Can.Expr -> ([Can.Def], Can.Expr)
42flattenLets defs annExpr@(A.A _ expr) =
45 flattenLets (defs ++ ds) body
51-- TRACKER TO THREAD FINDINGS THROUGH TRAVERSAL
58 { _hasTailCall :: Bool
63setTailCall :: Bool -> Optimizer ()
65 do uid <- State.gets _uid
66 State.put (Env bool uid)
69mapSnd :: M.Functor box => (a -> box b) -> (x, a) -> box (x, b)
76optimizeDef :: Maybe ModuleName.Canonical -> Can.Def -> Optimizer [Opt.Def]
77optimizeDef home (Can.Definition (Can.Facts deps) pattern@(A.A _ ptrn) expression _) =
80 Expr.collectLambdas expression
83 (P.Var name, _ : _) ->
85 do (Env htc uid) <- State.get
86 State.put (Env False uid)
88 (args, body) <- optimizeFunction (Just name) args rawBody
90 (Env isTailCall uid') <- State.get
91 State.put (Env htc uid')
93 let facts = Opt.Facts home deps
98 [ Opt.TailDef facts name args body ]
102 [ Opt.Def facts name (Opt.Function args body) ]
106 do hasTailCall <- State.gets _hasTailCall
107 body <- optimizeExpr Nothing rawBody
108 setTailCall hasTailCall
109 return [ Opt.Def (Opt.Facts home deps) name body ]
114 optBody <- optimizeExpr Nothing rawBody
115 let optDef = Opt.Def (Opt.Facts home deps) name optBody
116 return (optDef : patternToDefs home name pattern)
119 error "there should never be a function where the name is not a P.Var"
126 -> [P.CanonicalPattern]
128 -> Optimizer ([String], Opt.Expr)
129optimizeFunction maybeName patterns givenBody =
130 do (argNames, body) <- M.foldM depatternArgs ([], givenBody) (reverse patterns)
131 optBody <- optimizeExpr (makeContext argNames =<< maybeName) body
132 return (argNames, optBody)
135makeContext :: [String] -> String -> Context
136makeContext argNames name =
137 Just (name, length argNames, argNames)
141 :: ([String], Can.Expr)
142 -> P.CanonicalPattern
143 -> Optimizer ([String], Can.Expr)
144depatternArgs (names, rawExpr) ptrn =
145 do (name, expr) <- depattern ptrn rawExpr
146 return (name : names, expr)
150 :: Maybe ModuleName.Canonical
152 -> P.CanonicalPattern
154patternToDefs home rootName pattern =
160 , Opt.Var (Var.local rootName)
164 ( [ Var.TopLevelVar moduleName rootName ]
165 , Opt.Var (Var.topLevel moduleName rootName)
168 toDef (name, accessExpr) =
169 Opt.Def (Opt.Facts home deps) name accessExpr
171 map toDef (substitutions rootExpr pattern)
174substitutions :: Opt.Expr -> P.CanonicalPattern -> [(String, Opt.Expr)]
175substitutions expr (A.A _ pattern) =
184 map (\name -> (name, Opt.Access expr name)) fields
189 P.Alias alias realPattern ->
190 (alias, expr) : substitutions expr realPattern
193 concat (zipWith (substitutions . Opt.DataAccess expr) [0..] patterns)
196-- OPTIMIZE EXPRESSIONS
198type Context = Maybe (String, Int, [String])
201{-| This optimizer detects tail calls. The `Context` holds a function name,
202function arity, and list of argument names. If a tail call is possible, the
203`Context` will be filled in and we check any function we run into. If we go
204down a route that cannot possibly have tail calls, we remove the context.
206optimizeExpr :: Context -> Can.Expr -> Optimizer Opt.Expr
207optimizeExpr context annExpr@(A.A region expression) =
211 -- this *might* find a tail call, use this when something is a potential
216 -- this will never find tail calls, use this when you are working with
217 -- expressions that cannot be turned into tail calls
221 pure (Opt.Literal lit)
226 Expr.Range lowExpr highExpr ->
228 <$> justConvert lowExpr
229 <*> justConvert highExpr
231 Expr.ExplicitList elements ->
233 <$> T.traverse justConvert elements
235 Expr.Binop op leftExpr rightExpr ->
236 optimizeBinop context region op leftExpr rightExpr
241 Expr.collectLambdas annExpr
243 uncurry Opt.Function <$> optimizeFunction Nothing patterns body
248 Expr.collectApps annExpr
250 case isTailCall context func (length args) of
251 Just (name, argNames) ->
252 do optArgs <- T.traverse justConvert args
254 return (Opt.TailCall name argNames optArgs)
257 do hasTailCall <- State.gets _hasTailCall
258 optFunc <- justConvert func
259 optArgs <- T.traverse justConvert args
260 setTailCall hasTailCall
261 return (Opt.Call optFunc optArgs)
264 Expr.If branches finally ->
266 crawlBranch (cond,branch) =
267 (,) <$> justConvert cond <*> keepLooking branch
270 <$> T.traverse crawlBranch branches
271 <*> keepLooking finally
273 Expr.Let defs body ->
274 do optDefs <- concat <$> T.traverse (optimizeDef Nothing) defs
275 Opt.Let optDefs <$> keepLooking body
277 Expr.Case expr branches ->
278 optimizeCase context region expr branches
280 Expr.Data name exprs ->
281 Opt.Data name <$> T.traverse justConvert exprs
283 Expr.Access record field ->
285 <$> justConvert record
288 Expr.Update record fields ->
290 <$> justConvert record
291 <*> T.traverse (mapSnd justConvert) fields
293 Expr.Record fields ->
295 <$> T.traverse (mapSnd justConvert) fields
297 Expr.GLShader uid src gltipe ->
298 pure (Opt.GLShader uid src gltipe)
304 pure (Expr.In name tipe)
306 Expr.Out name expr tipe ->
307 (\e -> Expr.Out name e tipe) <$> justConvert expr
309 Expr.Task name expr tipe ->
310 (\e -> Expr.Task name e tipe) <$> justConvert expr
315isTailCall :: Context -> Can.Expr -> Int -> Maybe (String, [String])
316isTailCall context (A.A _ function) arity =
317 case (context, function) of
318 ( Just (ctxName, ctxArity, argNames), Expr.Var (Var.Canonical home name) ) ->
320 if name == ctxName && arity == ctxArity && Var.isLocalHome home then
321 Just (name, argNames)
332-- given a pattern and an expression, push the actual pattern matching into the
333-- expression as a case-expression if necessary. The pattern compiler will work
336depattern :: P.CanonicalPattern -> Can.Expr -> Optimizer (String, Can.Expr)
337depattern canPattern@(A.A _ pattern) expr =
340 A.A (error "the annotation added in 'depattern' should not be observed!")
342 caseExpr e branches =
343 ann (Expr.Case e branches)
346 ann (Expr.Var (Var.local name))
352 , caseExpr (var name) [ (canPattern, expr) ]
376freshName :: Optimizer String
378 do (Env htc uid) <- State.get
379 State.put (Env htc (uid + 1))
380 return ("_p" ++ show uid)
389 -> [(P.CanonicalPattern, Can.Expr)]
390 -> Optimizer Opt.Expr
391optimizeCase context region expr rawBranches =
393 indexify index (pattern, branch) =
398 do optBranches <- T.traverse (mapSnd (optimizeExpr context)) rawBranches
400 case last optBranches of
401 (A.A ann P.Anything, Opt.Call (Opt.Crash _ _) [arg]) ->
403 let newPattern = A.A ann (P.Var name)
404 let newCall = Opt.Call (Opt.Crash region (Just name)) [arg]
405 return (init optBranches ++ [(newPattern, newCall)])
410 let (patterns, indexedBranches) =
411 unzip (zipWith indexify [0..] crashBranches)
414 Cases.compile (error "need a VariantDict") patterns
416 optExpr <- optimizeExpr Nothing expr
418 return (inlinedCase optExpr decisionTree indexedBranches)
423 -> Cases.DecisionTree Cases.Jump
426inlinedCase expr decisionTree jumpTargets =
429 gatherSubstitutions decisionTree
431 (jumps, sharedBranches) =
432 unzip (map (toJumps substitutionDict) jumpTargets)
436 (inlineJumps (Map.fromList jumps) decisionTree)
437 (Maybe.catMaybes sharedBranches)
441 :: Cases.DecisionTree Cases.Jump
442 -> Map.Map Int [[(String, Cases.Path)]]
443gatherSubstitutions decisionTree =
445 Cases.Decision _ edges fallback ->
447 |> maybe id (:) fallback
448 |> map gatherSubstitutions
449 |> Map.unionsWith (++)
451 Cases.Match (Cases.Jump target substitutions) ->
452 Map.singleton target [substitutions]
456 :: Map.Map Int [[(String, Cases.Path)]]
458 -> ( (Int, Opt.Jump), Maybe (Int, Opt.Branch) )
459toJumps substitutionDict (target, branch) =
460 case substitutionDict ! target of
462 ( (target, Opt.Inline (Opt.Branch substitutions branch))
467 ( (target, Opt.Jump target)
468 , Just (target, Opt.Branch substitutions branch)
472 error "it is not possible for there to be no substitutions"
476 :: Map.Map Int Opt.Jump
477 -> Cases.DecisionTree Cases.Jump
478 -> Cases.DecisionTree Opt.Jump
479inlineJumps jumpDict decisionTree =
485 Cases.Decision test edges fallback ->
486 Cases.Decision test (map (second go) edges) (fmap go fallback)
488 Cases.Match (Cases.Jump target _) ->
489 Cases.Match (jumpDict ! target)
500 -> Optimizer Opt.Expr
501optimizeBinop context region op leftExpr rightExpr =
504 binop = ann (Expr.Binop op leftExpr rightExpr)
506 if op == forwardApply then
508 optimizeExpr context (collect id left forwardApply binop)
510 else if op == backwardApply then
512 optimizeExpr context (collect id right backwardApply binop)
514 else if op == forwardCompose then
517 let makeRoot func = ann (Expr.App func (ann (Expr.Var (Var.local var))))
518 let body = collect makeRoot left forwardCompose binop
519 optimizeExpr context (ann (Expr.Lambda (ann (P.Var var)) body))
521 else if op == backwardCompose then
524 let makeRoot func = ann (Expr.App func (ann (Expr.Var (Var.local var))))
525 let body = collect makeRoot right backwardCompose binop
526 optimizeExpr context (ann (Expr.Lambda (ann (P.Var var)) body))
528 else if op == Var.Canonical Var.BuiltIn "::" then
530 optimizeExpr context (ann (Expr.Data "::" [ leftExpr, rightExpr ]))
535 <$> optimizeExpr Nothing leftExpr
536 <*> optimizeExpr Nothing rightExpr
539-- left-associative ((x |> f) |> g)
540forwardApply :: Var.Canonical
542 Var.inCore ["Basics"] "|>"
545-- right-associative (g <| (f <| x))
546backwardApply :: Var.Canonical
548 Var.inCore ["Basics"] "<|"
551-- left-associative ((f >> g) >> h)
552forwardCompose :: Var.Canonical
554 Var.inCore ["Basics"] ">>"
557-- right-associative (h << (g << f))
558backwardCompose :: Var.Canonical
560 Var.inCore ["Basics"] "<<"
564 Can.Expr -> Can.Expr -> (Can.Expr, Can.Expr)
577collect :: (Can.Expr -> Can.Expr) -> Assoc -> Var.Canonical -> Can.Expr -> Can.Expr
578collect makeRoot assoc desiredOp annExpr@(A.A ann expr) =
580 Expr.Binop op leftExpr rightExpr | op == desiredOp ->
582 (func, arg) = assoc leftExpr rightExpr
584 A.A ann (Expr.App func (collect makeRoot assoc desiredOp arg))
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list