on de2011f help sign in
Idris-dev/src/Idris/TypeSearch.hs
527 lines 22 kB history raw
1{-# LANGUAGE ScopedTypeVariables #-}
3module Idris.TypeSearch (
4 searchByType, searchPred, defaultScoreFunction
5) where
7import Control.Applicative (Applicative (..), (<$>), (<*>), (<|>))
8import Control.Arrow (first, second, (&&&), (***))
9import Control.Monad (when, guard)
11import Data.List (find, partition, (\\))
12import Data.Map (Map)
13import qualified Data.Map as M
14import Data.Maybe (catMaybes, fromMaybe, isJust, maybeToList, mapMaybe)
15import Data.Monoid (Monoid (mempty, mappend))
16import Data.Ord (comparing)
17import qualified Data.PriorityQueue.FingerTree as Q
18import Data.Set (Set)
19import qualified Data.Set as S
20import qualified Data.Text as T (pack, isPrefixOf)
21import Data.Traversable (traverse)
23import Idris.AbsSyntax (addUsingConstraints, addImpl, getIState, putIState, implicit, logLvl)
24import Idris.AbsSyntaxTree (class_instances, ClassInfo, defaultSyntax, eqTy, Idris,
25 IState (idris_classes, idris_docstrings, tt_ctxt, idris_outputmode),
26 implicitAllowed, OutputMode(..), PTerm, toplevel)
27import Idris.Core.Evaluate (Context (definitions), Def (Function, TyDecl, CaseOp), normaliseC)
28import Idris.Core.TT hiding (score)
29import Idris.Core.Unify (match_unify)
30import Idris.Delaborate (delabTy)
31import Idris.Docstrings (noDocs, overview)
32import Idris.Elab.Type (elabType)
33import Idris.Output (iputStrLn, iRenderOutput, iPrintResult, iRenderResult, prettyDocumentedIst)
34import Idris.IBC
36import Prelude hiding (pred)
38import Util.Pretty (text, char, vsep, (<>), Doc, annotate)
40searchByType :: [String] -> PTerm -> Idris ()
41searchByType pkgs pterm = do
42 i <- getIState -- save original
43 when (not (null pkgs)) $
44 iputStrLn $ "Searching packages: " ++ showSep ", " pkgs
46 mapM_ loadPkgIndex pkgs
47 pterm' <- addUsingConstraints syn emptyFC pterm
48 pterm'' <- implicit toplevel syn name pterm'
49 let pterm''' = addImpl i pterm''
50 ty <- elabType toplevel syn (fst noDocs) (snd noDocs) emptyFC [] name pterm'
51 let names = searchUsing searchPred i ty
52 let names' = take numLimit names
53 let docs =
54 [ let docInfo = (n, delabTy i n, fmap (overview . fst) (lookupCtxtExact n (idris_docstrings i))) in
55 displayScore theScore <> char ' ' <> prettyDocumentedIst i docInfo
56 | (n, theScore) <- names']
57 case idris_outputmode i of
58 RawOutput _ -> do mapM_ iRenderOutput docs
59 iPrintResult ""
60 IdeSlave _ _ -> iRenderResult (vsep docs)
61 putIState i -- don't actually make any changes
62 where
63 numLimit = 50
64 syn = defaultSyntax { implicitAllowed = True } -- syntax
65 name = sMN 0 "searchType" -- name
67-- | Conduct a type-directed search using a given match predicate
68searchUsing :: (IState -> Type -> [(Name, Type)] -> [(Name, a)])
69 -> IState -> Type -> [(Name, a)]
70searchUsing pred istate ty = pred istate nty . concat . M.elems $
71 M.mapWithKey (\key -> M.toAscList . M.mapMaybe (f key)) (definitions ctxt)
72 where
73 nty = normaliseC ctxt [] ty
74 ctxt = tt_ctxt istate
75 f k x = do
76 guard $ not (special k)
77 type2 <- typeFromDef x
78 return $ normaliseC ctxt [] type2
79 special :: Name -> Bool
80 special (NS n _) = special n
81 special (SN _) = True
82 special (UN n) = T.pack "default#" `T.isPrefixOf` n
83 || n `elem` map T.pack ["believe_me", "really_believe_me"]
84 special _ = False
86-- | Our default search predicate.
87searchPred :: IState -> Type -> [(Name, Type)] -> [(Name, Score)]
88searchPred istate ty1 = matcher where
89 maxScore = 100
90 matcher = matchTypesBulk istate maxScore ty1
93typeFromDef :: (Def, b, c, d) -> Maybe Type
94typeFromDef (def, _, _, _) = get def where
95 get :: Def -> Maybe Type
96 get (Function ty _) = Just ty
97 get (TyDecl _ ty) = Just ty
98 -- get (Operator ty _ _) = Just ty
99 get (CaseOp _ ty _ _ _ _) = Just ty
100 get _ = Nothing
103-- | reverse the edges for a directed acyclic graph
104reverseDag :: Ord k => [((k, a), Set k)] -> [((k, a), Set k)]
105reverseDag xs = map f xs where
106 f ((k, v), _) = ((k, v), S.fromList . map (fst . fst) $ filter (S.member k . snd) xs)
108-- run vToP first!
109-- | Compute a directed acyclic graph corresponding to the
110-- arguments of a function.
111-- returns [(the name and type of the bound variable
112-- the names in the type of the bound variable)]
113computeDagP :: Ord n
114 => (TT n -> Bool) -- ^ filter to remove some arguments
115 -> TT n
116 -> ([((n, TT n), Set n)], [(n, TT n)], TT n)
117computeDagP removePred t = (reverse (map f arguments), reverse theRemovedArgs , retTy) where
118 f (n, ty) = ((n, ty), M.keysSet (usedVars ty))
120 (arguments, theRemovedArgs, retTy) = go [] [] t
122 -- NOTE : args are in reverse order
123 go args removedArgs (Bind n (Pi _ ty _) sc) = let arg = (n, ty) in
124 if removePred ty
125 then go args (arg : removedArgs) sc
126 else go (arg : args) removedArgs sc
127 go args removedArgs sc = (args, removedArgs, sc)
129-- | Collect the names and types of all the free variables
130-- The Boolean indicates those variables which are determined due to injectivity
131-- I have not given nearly enough thought to know whether this is correct
132usedVars :: Ord n => TT n -> Map n (TT n, Bool)
133usedVars = f True where
134 f b (P Bound n t) = M.singleton n (t, b) `M.union` f b t
135 f b (Bind n binder t2) = (M.delete n (f b t2) `M.union`) $ case binder of
136 Let t v -> f b t `M.union` f b v
137 Guess t v -> f b t `M.union` f b v
138 bind -> f b (binderTy bind)
139 f b (App t1 t2) = f b t1 `M.union` f (b && isInjective t1) t2
140 f b (Proj t _) = f b t
141 f _ (V _) = error "unexpected! run vToP first"
142 f _ _ = M.empty
144-- | Remove a node from a directed acyclic graph
145deleteFromDag :: Ord n => n -> [((n, TT n), (a, Set n))] -> [((n, TT n), (a, Set n))]
146deleteFromDag name [] = []
147deleteFromDag name (((name2, ty), (ix, set)) : xs) = (if name == name2
148 then id
149 else (((name2, ty) , (ix, S.delete name set)) :) ) (deleteFromDag name xs)
151deleteFromArgList :: Ord n => n -> [(n, TT n)] -> [(n, TT n)]
152deleteFromArgList n = filter ((/= n) . fst)
154-- | Asymmetric modifications to keep track of
155data AsymMods = Mods
156 { argApp :: !Int
157 , typeClassApp :: !Int
158 , typeClassIntro :: !Int
159 } deriving (Eq, Show)
162-- | Homogenous tuples
163data Sided a = Sided
164 { left :: !a
165 , right :: !a
166 } deriving (Eq, Show)
168sided :: (a -> a -> b) -> Sided a -> b
169sided f (Sided l r) = f l r
171-- | Could be a functor instance, but let's avoid name overloading
172both :: (a -> b) -> Sided a -> Sided b
173both f (Sided l r) = Sided (f l) (f r)
175-- | Keeps a record of the modifications made to match one type
176-- signature with another
177data Score = Score
178 { transposition :: !Int -- ^ transposition of arguments
179 , equalityFlips :: !Int -- ^ application of symmetry of equality
180 , asymMods :: !(Sided AsymMods) -- ^ "directional" modifications
181 } deriving (Eq, Show)
183displayScore :: Score -> Doc OutputAnnotation
184displayScore score = case both noMods (asymMods score) of
185 Sided True True -> annotated EQ "=" -- types are isomorphic
186 Sided True False -> annotated LT "<" -- found type is more general than searched type
187 Sided False True -> annotated GT ">" -- searched type is more general than found type
188 Sided False False -> text "_"
189 where
190 annotated ordr = annotate (AnnSearchResult ordr) . text
191 noMods (Mods app tcApp tcIntro) = app + tcApp + tcIntro == 0
193-- | This allows the search to stop expanding on a certain state if its
194-- score is already too high. Returns 'True' if the algorithm should keep
195-- exploring from this state, and 'False' otherwise.
196scoreCriterion :: Score -> Bool
197scoreCriterion (Score _ _ amods) = not
198 ( sided (&&) (both ((> 0) . argApp) amods)
199 || sided (+) (both argApp amods) > 4
200 || sided (||) (both (\(Mods _ tcApp tcIntro) -> tcApp > 3 || tcIntro > 3) amods)
201 )
203-- | Convert a 'Score' to an 'Int' to provide an order for search results.
204-- Lower scores are better.
205defaultScoreFunction :: Score -> Int
206defaultScoreFunction (Score trans eqFlip amods) =
207 trans + eqFlip + linearPenalty + upAndDowncastPenalty
208 where
209 -- prefer finding a more general type to a less general type
210 linearPenalty = (\(Sided l r) -> 3 * l + r)
211 (both (\(Mods app tcApp tcIntro) -> 3 * app + 4 * tcApp + 2 * tcIntro) amods)
212 -- it's very bad to have *both* upcasting and downcasting
213 upAndDowncastPenalty = 100 *
214 sided (*) (both (\(Mods app tcApp tcIntro) -> 2 * app + tcApp + tcIntro) amods)
216instance Ord Score where
217 compare = comparing defaultScoreFunction
220instance Monoid a => Monoid (Sided a) where
221 mempty = Sided mempty mempty
222 (Sided l1 r1) `mappend` (Sided l2 r2) = Sided (l1 `mappend` l2) (r1 `mappend` r2)
224instance Monoid AsymMods where
225 mempty = Mods 0 0 0
226 (Mods a b c) `mappend` (Mods a' b' c') = Mods (a + a') (b + b') (c + c')
228instance Monoid Score where
229 mempty = Score 0 0 mempty
230 (Score t e mods) `mappend` (Score t' e' mods') = Score (t + t') (e + e') (mods `mappend` mods')
232-- | A directed acyclic graph representing the arguments to a function
233-- The 'Int' represents the position of the argument (1st argument, 2nd, etc.)
234type ArgsDAG = [((Name, Type), (Int, Set Name))]
236-- | A list of typeclass constraints
237type Classes = [(Name, Type)]
239-- | The state corresponding to an attempted match of two types.
240data State = State
241 { holes :: ![(Name, Type)] -- ^ names which have yet to be resolved
242 , argsAndClasses :: !(Sided (ArgsDAG, Classes))
243 -- ^ arguments and typeclass constraints for each type which have yet to be resolved
244 , score :: !Score -- ^ the score so far
245 , usedNames :: ![Name] -- ^ all names that have been used
246 } deriving Show
248modifyTypes :: (Type -> Type) -> (ArgsDAG, Classes) -> (ArgsDAG, Classes)
249modifyTypes f = modifyDag *** modifyList
250 where
251 modifyDag = map (first (second f))
252 modifyList = map (second f)
254findNameInArgsDAG :: Name -> ArgsDAG -> Maybe (Type, Maybe Int)
255findNameInArgsDAG name = fmap ((snd . fst) &&& (Just . fst . snd)) . find ((name ==) . fst . fst)
257findName :: Name -> (ArgsDAG, Classes) -> Maybe (Type, Maybe Int)
258findName n (args, classes) = findNameInArgsDAG n args <|> ((,) <$> lookup n classes <*> Nothing)
260deleteName :: Name -> (ArgsDAG, Classes) -> (ArgsDAG, Classes)
261deleteName n (args, classes) = (deleteFromDag n args, filter ((/= n) . fst) classes)
263tcToMaybe :: TC a -> Maybe a
264tcToMaybe (OK x) = Just x
265tcToMaybe (Error _) = Nothing
267inArgTys :: (Type -> Type) -> ArgsDAG -> ArgsDAG
268inArgTys = map . first . second
271typeclassUnify :: Ctxt ClassInfo -> Context -> Type -> Type -> Maybe [(Name, Type)]
272typeclassUnify classInfo ctxt ty tyTry = do
273 res <- tcToMaybe $ match_unify ctxt [] ty retTy [] theHoles []
274 guard $ null (theHoles \\ map fst res)
275 let argTys' = map (second $ foldr (.) id [ subst n t | (n, t) <- res ]) tcArgs
276 return argTys'
277 where
278 tyTry' = vToP tyTry
279 theHoles = map fst nonTcArgs
280 retTy = getRetTy tyTry'
281 (tcArgs, nonTcArgs) = partition (isTypeClassArg classInfo . snd) $ getArgTys tyTry'
283isTypeClassArg :: Ctxt ClassInfo -> Type -> Bool
284isTypeClassArg classInfo ty = not (null (getClassName clss >>= flip lookupCtxt classInfo)) where
285 (clss, args) = unApply ty
286 getClassName (P (TCon _ _) className _) = [className]
287 getClassName _ = []
290-- | Compute the power set
291subsets :: [a] -> [[a]]
292subsets [] = [[]]
293subsets (x : xs) = let ss = subsets xs in map (x :) ss ++ ss
296-- not recursive (i.e., doesn't flip iterated identities) at the moment
297-- recalls the number of flips that have been made
298flipEqualities :: Type -> [(Int, Type)]
299flipEqualities t = case t of
300 eq1@(App (App (App (App eq@(P _ eqty _) tyL) tyR) valL) valR) | eqty == eqTy ->
301 [(0, eq1), (1, App (App (App (App eq tyR) tyL) valR) valL)]
302 Bind n binder sc -> (\bind' (j, sc') -> (fst (binderTy bind') + j, Bind n (fmap snd bind') sc'))
303 <$> traverse flipEqualities binder <*> flipEqualities sc
304 App f x -> (\(i, f') (j, x') -> (i + j, App f' x'))
305 <$> flipEqualities f <*> flipEqualities x
306 t' -> [(0, t')]
308--DONT run vToP first!
309-- | Try to match two types together in a unification-like procedure.
310-- Returns a list of types and their minimum scores, sorted in order
311-- of increasing score.
312matchTypesBulk :: forall info. IState -> Int -> Type -> [(info, Type)] -> [(info, Score)]
313matchTypesBulk istate maxScore type1 types = getAllResults startQueueOfQueues where
314 getStartQueues :: (info, Type) -> Maybe (Score, (info, Q.PQueue Score State))
315 getStartQueues nty@(info, type2) = case mapMaybe startStates ty2s of
316 [] -> Nothing
317 xs -> Just (minimum (map fst xs), (info, Q.fromList xs))
318 where
319 ty2s = (\(i, dag) (j, retTy) -> (i + j, dag, retTy))
320 <$> flipEqualitiesDag dag2 <*> flipEqualities retTy2
321 flipEqualitiesDag dag = case dag of
322 [] -> [(0, [])]
323 ((n, ty), (pos, deps)) : xs ->
324 (\(i, ty') (j, xs') -> (i + j , ((n, ty'), (pos, deps)) : xs'))
325 <$> flipEqualities ty <*> flipEqualitiesDag xs
326 startStates (numEqFlips, sndDag, sndRetTy) = do
327 state <- unifyQueue (State startingHoles
328 (Sided (dag1, typeClassArgs1) (sndDag, typeClassArgs2))
329 (mempty { equalityFlips = numEqFlips }) usedns) [(retTy1, sndRetTy)]
330 return (score state, state)
333 (dag2, typeClassArgs2, retTy2) = makeDag (uniqueBinders (map fst argNames1) type2)
334 argNames2 = map fst dag2
335 usedns = map fst startingHoles
336 startingHoles = argNames1 ++ argNames2
338 startingTypes = [(retTy1, retTy2)]
341 startQueueOfQueues :: Q.PQueue Score (info, Q.PQueue Score State)
342 startQueueOfQueues = Q.fromList $ mapMaybe getStartQueues types
344 getAllResults :: Q.PQueue Score (info, Q.PQueue Score State) -> [(info, Score)]
345 getAllResults q = case Q.minViewWithKey q of
346 Nothing -> []
347 Just ((nextScore, (info, stateQ)), q') ->
348 if defaultScoreFunction nextScore <= maxScore
349 then case nextStepsQueue stateQ of
350 Nothing -> getAllResults q'
351 Just (Left stateQ') -> case Q.minViewWithKey stateQ' of
352 Nothing -> getAllResults q'
353 Just ((newQscore,_), _) -> getAllResults (Q.add newQscore (info, stateQ') q')
354 Just (Right theScore) -> (info, theScore) : getAllResults q'
355 else []
358 ctxt = tt_ctxt istate
359 classInfo = idris_classes istate
361 (dag1, typeClassArgs1, retTy1) = makeDag type1
362 argNames1 = map fst dag1
363 makeDag :: Type -> (ArgsDAG, Classes, Type)
364 makeDag = first3 (zipWith (\i (ty, deps) -> (ty, (i, deps))) [0..] . reverseDag) .
365 computeDagP (isTypeClassArg classInfo) . vToP
366 first3 f (a,b,c) = (f a, b, c)
368 -- update our state with the unification resolutions
369 resolveUnis :: [(Name, Type)] -> State -> Maybe (State, [(Type, Type)])
370 resolveUnis [] state = Just (state, [])
371 resolveUnis ((name, term@(P Bound name2 _)) : xs)
372 state | isJust findArgs = do
373 ((ty1, ix1), (ty2, ix2)) <- findArgs
375 (state'', queue) <- resolveUnis xs state'
376 let transScore = fromMaybe 0 (abs <$> ((-) <$> ix1 <*> ix2))
377 return (inScore (\s -> s { transposition = transposition s + transScore }) state'', (ty1, ty2) : queue)
378 where
379 unresolved = argsAndClasses state
380 inScore f stat = stat { score = f (score stat) }
381 findArgs = ((,) <$> findName name (left unresolved) <*> findName name2 (right unresolved)) <|>
382 ((,) <$> findName name2 (left unresolved) <*> findName name (right unresolved))
383 matchnames = [name, name2]
384 deleteArgs = deleteName name . deleteName name2
385 state' = state { holes = filter (not . (`elem` matchnames) . fst) (holes state)
386 , argsAndClasses = both (modifyTypes (subst name term) . deleteArgs) unresolved}
388 resolveUnis ((name, term) : xs)
389 state@(State hs unresolved _ _) = case both (findName name) unresolved of
390 Sided Nothing Nothing -> Nothing
391 Sided (Just _) (Just _) -> error "Idris internal error: TypeSearch.resolveUnis"
392 oneOfEach -> first (addScore (both scoreFor oneOfEach)) <$> nextStep
393 where
394 scoreFor (Just _) = mempty { argApp = 1 }
395 scoreFor Nothing = mempty { argApp = otherApplied }
396 -- find variables which are determined uniquely by the type
397 -- due to injectivity
398 matchedVarMap = usedVars term
399 bothT f (x, y) = (f x, f y)
400 (injUsedVars, notInjUsedVars) = bothT M.keys . M.partition id . M.filterWithKey (\k _-> k `elem` map fst hs) $ M.map snd matchedVarMap
401 varsInTy = injUsedVars ++ notInjUsedVars
402 toDelete = name : varsInTy
403 deleteMany = foldr (.) id (map deleteName toDelete)
405 otherApplied = length notInjUsedVars
407 addScore additions theState = theState { score = let s = score theState in
408 s { asymMods = asymMods s `mappend` additions } }
409 state' = state { holes = filter (not . (`elem` toDelete) . fst) hs
410 , argsAndClasses = both (modifyTypes (subst name term) . deleteMany) (argsAndClasses state) }
411 nextStep = resolveUnis xs state'
414 -- | resolve a queue of unification constraints
415 unifyQueue :: State -> [(Type, Type)] -> Maybe State
416 unifyQueue state [] = return state
417 unifyQueue state ((ty1, ty2) : queue) = do
418 --trace ("go: \n" ++ show state) True `seq` return ()
419 res <- tcToMaybe $ match_unify ctxt [ (n, Pi Nothing ty (TType (UVar 0))) | (n, ty) <- holes state] ty1 ty2 [] (map fst $ holes state) []
420 (state', queueAdditions) <- resolveUnis res state
421 guard $ scoreCriterion (score state')
422 unifyQueue state' (queue ++ queueAdditions)
424 possClassInstances :: [Name] -> Type -> [Type]
425 possClassInstances usedns ty = do
426 className <- getClassName clss
427 classDef <- lookupCtxt className classInfo
428 n <- class_instances classDef
429 def <- lookupCtxt n (definitions ctxt)
430 nty <- normaliseC ctxt [] <$> (case typeFromDef def of Just x -> [x]; Nothing -> [])
431 let ty' = vToP (uniqueBinders usedns nty)
432 return ty'
433 where
434 (clss, _) = unApply ty
435 getClassName (P (TCon _ _) className _) = [className]
436 getClassName _ = []
438 -- 'Just' if the computation hasn't totally failed yet, 'Nothing' if it has
439 -- 'Left' if we haven't found a terminal state, 'Right' if we have
440 nextStepsQueue :: Q.PQueue Score State -> Maybe (Either (Q.PQueue Score State) Score)
441 nextStepsQueue queue = do
442 ((nextScore, next), rest) <- Q.minViewWithKey queue
443 Just $ if isFinal next
444 then Right nextScore
445 else let additions = if scoreCriterion nextScore
446 then Q.fromList [ (score state, state) | state <- nextSteps next ]
447 else Q.empty in
448 Left (Q.union rest additions)
449 where
450 isFinal (State [] (Sided ([], []) ([], [])) _ _) = True
451 isFinal _ = False
453 -- | Find all possible matches starting from a given state.
454 -- We go in stages rather than concatenating all three results in hopes of narrowing
455 -- the search tree. Once we advance in a phase, there should be no going back.
456 nextSteps :: State -> [State]
458 -- Stage 3 - match typeclasses
459 nextSteps (State [] unresolved@(Sided ([], c1) ([], c2)) scoreAcc usedns) =
460 if null results3 then results4 else results3
461 where
462 -- try to match a typeclass argument from the left with a typeclass argument from the right
463 results3 =
464 catMaybes [ unifyQueue (State []
465 (Sided ([], deleteFromArgList n1 c1)
466 ([], map (second subst2for1) (deleteFromArgList n2 c2)))
467 scoreAcc usedns) [(ty1, ty2)]
468 | (n1, ty1) <- c1, (n2, ty2) <- c2, let subst2for1 = psubst n2 (P Bound n1 ty1)]
470 -- try to hunt match a typeclass constraint by replacing it with an instance
471 results4 = [ State [] (both (\(cs, _, _) -> ([], cs)) sds)
472 (scoreAcc `mappend` Score 0 0 (both (\(_, amods, _) -> amods) sds))
473 (usedns ++ sided (++) (both (\(_, _, hs) -> hs) sds))
474 | sds <- allMods ]
475 where
476 allMods = parallel defMod mods
477 mods :: Sided [( Classes, AsymMods, [Name] )]
478 mods = both (instanceMods . snd) unresolved
479 defMod :: Sided (Classes, AsymMods, [Name])
480 defMod = both (\(_, cs) -> (cs, mempty , [])) unresolved
481 parallel :: Sided a -> Sided [a] -> [Sided a]
482 parallel (Sided l r) (Sided ls rs) = map (flip Sided r) ls ++ map (Sided l) rs
483 instanceMods :: Classes -> [( Classes , AsymMods, [Name] )]
484 instanceMods classes = [ ( newClassArgs, mempty { typeClassApp = 1 }, newHoles )
485 | (_, ty) <- classes
486 , inst <- possClassInstances usedns ty
487 , newClassArgs <- maybeToList $ typeclassUnify classInfo ctxt ty inst
488 , let newHoles = map fst newClassArgs ]
491 -- Stage 1 - match arguments
492 nextSteps (State hs (Sided (dagL, c1) (dagR, c2)) scoreAcc usedns) = results where
494 results = concatMap takeSomeClasses results1
496 -- we only try to match arguments whose names don't appear in the types
497 -- of any other arguments
498 canBeFirst :: ArgsDAG -> [(Name, Type)]
499 canBeFirst = map fst . filter (S.null . snd . snd)
501 -- try to match an argument from the left with an argument from the right
502 results1 = catMaybes [ unifyQueue (State (filter (not . (`elem` [n1,n2]) . fst) hs)
503 (Sided (deleteFromDag n1 dagL, c1)
504 (inArgTys subst2for1 $ deleteFromDag n2 dagR, map (second subst2for1) c2))
505 scoreAcc usedns) [(ty1, ty2)]
506 | (n1, ty1) <- canBeFirst dagL, (n2, ty2) <- canBeFirst dagR
507 , let subst2for1 = psubst n2 (P Bound n1 ty1)]
511 -- Stage 2 - simply introduce a subset of the typeclasses
512 -- we've finished, so take some classes
513 takeSomeClasses (State [] unresolved@(Sided ([], _) ([], _)) scoreAcc usedns) =
514 map statesFromMods . prod $ both (classMods . snd) unresolved
515 where
516 swap (Sided l r) = Sided r l
517 statesFromMods :: Sided (Classes, AsymMods) -> State
518 statesFromMods sides = let classes = both (\(c, _) -> ([], c)) sides
519 mods = swap (both snd sides) in
520 State [] classes (scoreAcc `mappend` (mempty { asymMods = mods })) usedns
521 classMods :: Classes -> [(Classes, AsymMods)]
522 classMods cs = let lcs = length cs in
523 [ (cs', mempty { typeClassIntro = lcs - length cs' }) | cs' <- subsets cs ]
524 prod :: Sided [a] -> [Sided a]
525 prod (Sided ls rs) = [Sided l r | l <- ls, r <- rs]
526 -- still have arguments to match, so just be the identity
527 takeSomeClasses s = [s]