1{-# OPTIONS_GHC -Wall #-}
2module Optimize.DecisionTree where
3{- To learn more about how this works, definitely read through:
5 "When Do Match-Compilation Heuristics Matter?"
7by Kevin Scott and Norman Ramsey. The rough idea is that we start with a simple
8list of patterns and expressions, and then turn that into a "decision tree"
9that requires as few tests as possible to make it to a leaf. Read the paper, it
10explains this extraordinarily well! We are currently using the same heuristics
11as SML/NJ to get nice trees.
14import Control.Arrow (second)
15import qualified Data.List as List
16import qualified Data.Map as Map
17import qualified Data.Set as Set
18import qualified Data.Maybe as Maybe
19import qualified Data.Text as Text
20import Data.Text (Text)
22import qualified AST.Helpers as Help
23import qualified AST.Literal as L
24import qualified AST.Pattern as P
25import qualified AST.Variable as Var
26import qualified Reporting.Annotation as A
29type CPattern = P.Canonical
34{-| Users of this module will mainly interact with this function. It takes
35some normal branches and gives out a decision tree that has "labels" at all
36the leafs and a dictionary that maps these "labels" to the code that should
39If 2 or more leaves point to the same label, we need to do some tricks in JS to
40make that work nicely. When is JS getting goto?! ;) That is outside the scope
43compile :: VariantDict -> [(CPattern, Int)] -> DecisionTree
44compile variantDict rawBranches =
46 format (pattern, index) =
47 Branch index [(Empty, pattern)]
49 toDecisionTree variantDict (map format rawBranches)
52{-| When a certain union type is defined, you specify a certain number of tags.
53This helps us do a few optimizations:
55 * If there is only one possible tag, we can always skip checking what it is.
56 Tuples are a common example of this.
57 * If we use all possible tags, we can skip doing the last test. If we have
58 checked N-1 of N tags, there is no need to test the Nth, we know its the
61So this dictionary maps tags to the number of variants that exist, so it'll
62contain things like [ ("Just", 2), ("Nothing", 2), ("_Tuple2", 1), ... ] which
63we can use for these optimizations.
66 Map.Map Var.Home (Map.Map Text Int)
75 , _edges :: [(Test, DecisionTree)]
76 , _default :: Maybe DecisionTree
82 = Constructor Var.Canonical
97add :: Path -> Path -> Path
104 error "nothing should be added to an alias path"
106 Position index subpath ->
107 Position index (add subpath finalLink)
109 Field name subpath ->
110 Field name (add subpath finalLink)
113subPositions :: Path -> [CPattern] -> [(Path, CPattern)]
114subPositions path patterns =
116 (\index pattern -> (add path (Position index Empty), pattern))
121-- ACTUALLY BUILD DECISION TREES
126 , _patterns :: [(Path, CPattern)]
130toDecisionTree :: VariantDict -> [Branch] -> DecisionTree
131toDecisionTree variantDict rawBranches =
134 map (flattenPatterns variantDict) rawBranches
136 case checkForMatch branches of
143 pickPath variantDict branches
146 gatherEdges variantDict branches path
149 map (second (toDecisionTree variantDict)) edges
151 case (decisionEdges, fallback) of
152 ([(_tag, decisionTree)], []) ->
156 Decision path decisionEdges Nothing
159 toDecisionTree variantDict fallback
162 Decision path decisionEdges (Just (toDecisionTree variantDict fallback))
165isComplete :: VariantDict -> [Test] -> Bool
166isComplete variantDict tests =
169 getArity variantDict var == length tests
171 Literal (L.Boolean _) ->
178getArity :: VariantDict -> Var.Canonical -> Int
179getArity variantDict (Var.Canonical home name) =
180 case Map.lookup name =<< Map.lookup home variantDict of
185 if Help.isTuple name then
186 read (drop 6 (Text.unpack name))
190 "Since the Optimize phase happens after canonicalization and type \
191 \inference, it is impossible that a pattern cannot be found."
196{-| Flatten type aliases and use the VariantDict to figure out when a tag is
197the only variant so we can skip doing any tests on it.
199flattenPatterns :: VariantDict -> Branch -> Branch
200flattenPatterns variantDict (Branch goal pathPatterns) =
201 Branch goal (concatMap (flatten variantDict) pathPatterns)
204flatten :: VariantDict -> (Path, CPattern) -> [(Path, CPattern)]
205flatten variantDict pathPattern@(path, A.A ann pattern) =
213 P.Alias alias realPattern ->
214 (add path Alias, A.A ann (P.Var alias))
216 flatten variantDict (path, realPattern)
221 P.Ctor tag patterns ->
222 if getArity variantDict tag == 1 then
223 concatMap (flatten variantDict) (subPositions path patterns)
234{-| If the first branch has no more "decision points" we can finally take that
235path. If that is the case we give the resulting label and a mapping from free
236variables to "how to get their value". So a pattern like (Just (x,_)) will give
237us something like ("x" => value.0.0)
239checkForMatch :: [Branch] -> Maybe Int
240checkForMatch branches =
242 Branch goal patterns : _ | all (not . needsTests . snd) patterns ->
249-- GATHER OUTGOING EDGES
251gatherEdges :: VariantDict -> [Branch] -> Path -> ([(Test, [Branch])], [Branch])
252gatherEdges variantDict branches path =
255 testsAtPath path branches
258 map (edgesFor path branches) relevantTests
261 if isComplete variantDict relevantTests then
264 filter (isIrrelevantTo path) branches
266 ( allEdges, fallbacks )
269-- FIND RELEVANT TESTS
271testsAtPath :: Path -> [Branch] -> [Test]
272testsAtPath selectedPath branches =
275 Maybe.mapMaybe (testAtPath selectedPath) branches
277 skipVisited test curr@(uniqueTests, visitedTests) =
278 if Set.member test visitedTests then
282 , Set.insert test visitedTests
285 fst (foldr skipVisited ([], Set.empty) allTests)
288testAtPath :: Path -> Branch -> Maybe Test
289testAtPath selectedPath (Branch _ pathPatterns) =
290 case List.lookup selectedPath pathPatterns of
294 Just (A.A _ pattern) ->
297 Just (Constructor name)
306 error "aliases should never reach 'testAtPath' function"
317edgesFor :: Path -> [Branch] -> Test -> (Test, [Branch])
318edgesFor path branches test =
320 , Maybe.mapMaybe (toRelevantBranch test path) branches
324toRelevantBranch :: Test -> Path -> Branch -> Maybe Branch
325toRelevantBranch test path branch@(Branch goal pathPatterns) =
326 case extract path pathPatterns of
327 Just (start, A.A _ pattern, end) ->
329 P.Ctor name patterns ->
330 if test == Constructor name then
331 Just (Branch goal (start ++ subPositions path patterns ++ end))
337 if test == Literal lit then
338 Just (Branch goal (start ++ end))
352 -> [(Path, CPattern)]
353 -> Maybe ([(Path, CPattern)], CPattern, [(Path, CPattern)])
354extract selectedPath pathPatterns =
359 first@(path, pattern) : rest ->
360 if path == selectedPath then
361 Just ([], pattern, rest)
364 case extract selectedPath rest of
368 Just (start, foundPattern, end) ->
369 Just (first : start, foundPattern, end)
372-- FIND IRRELEVANT BRANCHES
374isIrrelevantTo :: Path -> Branch -> Bool
375isIrrelevantTo selectedPath (Branch _ pathPatterns) =
376 case List.lookup selectedPath pathPatterns of
381 not (needsTests pattern)
384needsTests :: CPattern -> Bool
385needsTests (A.A _ pattern) =
394 error "aliases should never reach 'isIrrelevantTo' function"
408pickPath :: VariantDict -> [Branch] -> Path
409pickPath variantDict branches =
412 Maybe.mapMaybe isChoicePath (concatMap _patterns branches)
414 case bests (addWeights (smallDefaults branches) allPaths) of
419 head (bests (addWeights (smallBranchingFactor variantDict branches) tiedPaths))
422isChoicePath :: (Path, CPattern) -> Maybe Path
423isChoicePath (path, pattern) =
424 if needsTests pattern then
430addWeights :: (Path -> Int) -> [Path] -> [(Path, Int)]
431addWeights toWeight paths =
432 map (\path -> (path, toWeight path)) paths
435bests :: [(Path, Int)] -> [Path]
439 error "Cannot choose the best of zero paths. This should never happen."
441 (headPath, headWeight) : weightedPaths ->
443 gatherMinimum acc@(minWeight, paths) (path, weight) =
444 if weight == minWeight then
445 (minWeight, path : paths)
447 else if weight < minWeight then
453 snd (List.foldl' gatherMinimum (headWeight, [headPath]) weightedPaths)
456-- PATH PICKING HEURISTICS
458smallDefaults :: [Branch] -> Path -> Int
459smallDefaults branches path =
460 length (filter (isIrrelevantTo path) branches)
463smallBranchingFactor :: VariantDict -> [Branch] -> Path -> Int
464smallBranchingFactor variantDict branches path =
467 gatherEdges variantDict branches path
469 length edges + (if null fallback then 0 else 1)
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