on ef93607 help sign in
Idris-dev/src/Core/Unify.hs
489 lines 21 kB history raw
1{-# LANGUAGE PatternGuards #-}
3module Core.Unify(match_unify, unify, Fails) where
5import Core.TT
6import Core.Evaluate
8import Control.Monad
9import Control.Monad.State
10import Data.List
11import Debug.Trace
13-- Unification is applied inside the theorem prover. We're looking for holes
14-- which can be filled in, by matching one term's normal form against another.
15-- Returns a list of hole names paired with the term which solves them, and
16-- a list of things which need to be injective.
18-- terms which need to be injective, with the things we're trying to unify
19-- at the time
21type Injs = [(TT Name, TT Name, TT Name)]
22type Fails = [(TT Name, TT Name, Env, Err)]
24data UInfo = UI Int Fails
25 deriving Show
27data UResult a = UOK a
28 | UPartOK a
29 | UFail Err
31-- Solve metavariables by matching terms against each other
32-- Not really unification, of course!
34match_unify :: Context -> Env -> TT Name -> TT Name -> [Name] -> [Name] ->
35 TC [(Name, TT Name)]
36match_unify ctxt env topx topy dont holes =
37-- trace ("Matching " ++ show (topx, topy)) $
38 case runStateT (un [] topx topy) (UI 0 []) of
39 OK (v, UI _ []) -> return (filter notTrivial v)
40 res ->
41 let topxn = normalise ctxt env topx
42 topyn = normalise ctxt env topy in
43 case runStateT (un [] topxn topyn)
44 (UI 0 []) of
45 OK (v, UI _ fails) ->
46 return (filter notTrivial v)
47 Error e -> tfail e
48 where
49 un names (P _ x _) tm
50 | holeIn env x || x `elem` holes
51 = do sc 1; checkCycle names (x, tm)
52 un names tm (P _ y _)
53 | holeIn env y || y `elem` holes
54 = do sc 1; checkCycle names (y, tm)
55 un bnames (V i) (P _ x _)
56 | fst (bnames!!i) == x || snd (bnames!!i) == x = do sc 1; return []
57 un bnames (P _ x _) (V i)
58 | fst (bnames!!i) == x || snd (bnames!!i) == x = do sc 1; return []
59 un names (App fx ax) (App fy ay)
60 = do hf <- un names fx fy
61 ha <- un names ax ay
62 combine names hf ha
63 un names x y
64 | OK True <- convEq' ctxt x y = do sc 1; return []
65 | otherwise = do UI s f <- get
66 let r = recoverable x y
67 let err = CantUnify r
68 topx topy (CantUnify r x y (Msg "") [] s) (errEnv env) s
69 if (not r) then lift $ tfail err
70 else do put (UI s ((x, y, env, err) : f))
71 lift $ tfail err
74 -- TODO: there's an annoying amount of repetition between this and the
75 -- main unification function. Consider lifting it out.
77 sc i = do UI s f <- get
78 put (UI (s+i) f)
80 unifyFail x y = do UI s f <- get
81 let r = recoverable x y
82 let err = CantUnify r
83 topx topy (CantUnify r x y (Msg "") [] s) (errEnv env) s
84 put (UI s ((x, y, env, err) : f))
85 lift $ tfail err
86 combine bnames as [] = return as
87 combine bnames as ((n, t) : bs)
88 = case lookup n as of
89 Nothing -> combine bnames (as ++ [(n,t)]) bs
90 Just t' -> do ns <- un bnames t t'
91 -- make sure there's n mapping from n in ns
92 let ns' = filter (\ (x, _) -> x/=n) ns
93 sc 1
94 combine bnames as (ns' ++ bs)
96 checkCycle ns p@(x, P _ _ _) = return [p]
97 checkCycle ns (x, tm)
98 | not (x `elem` freeNames tm) = checkScope ns (x, tm)
99 | otherwise = lift $ tfail (InfiniteUnify x tm (errEnv env))
101 checkScope ns (x, tm) =
102 case boundVs (envPos x 0 env) tm of
103 [] -> return [(x, tm)]
104 (i:_) -> lift $ tfail (UnifyScope x (fst (ns!!i))
105 (inst ns tm) (errEnv env))
106 where inst [] tm = tm
107 inst ((n, _) : ns) tm = inst ns (substV (P Bound n Erased) tm)
109notTrivial (x, P _ x' _) = x /= x'
110notTrivial _ = True
112expandLets env (x, tm) = (x, doSubst (reverse env) tm)
113 where
114 doSubst [] tm = tm
115 doSubst ((n, Let v t) : env) tm
116 = doSubst env (subst n v tm)
117 doSubst (_ : env) tm
118 = doSubst env tm
121unify :: Context -> Env -> TT Name -> TT Name -> [Name] -> [Name] ->
122 TC ([(Name, TT Name)], Fails)
123unify ctxt env topx topy dont holes =
124-- trace ("Unifying " ++ show (topx, topy)) $
125 -- don't bother if topx and topy are different at the head
126 case runStateT (un False [] topx topy) (UI 0 []) of
127 OK (v, UI _ []) -> return (filter notTrivial v,
128 [])
129 res ->
130 let topxn = normalise ctxt env topx
131 topyn = normalise ctxt env topy in
132-- trace ("Unifying " ++ show (topx, topy) ++ "\n\n==>\n" ++ show (topxn, topyn) ++ "\n\n" ++ show res ++ "\n\n") $
133 case runStateT (un False [] topxn topyn)
134 (UI 0 []) of
135 OK (v, UI _ fails) ->
136 return (filter notTrivial v, reverse fails)
137-- Error e@(CantUnify False _ _ _ _ _) -> tfail e
138 Error e -> tfail e
139 where
140 headDiff (P (DCon _ _) x _) (P (DCon _ _) y _) = x /= y
141 headDiff (P (TCon _ _) x _) (P (TCon _ _) y _) = x /= y
142 headDiff _ _ = False
144 injective (P (DCon _ _) _ _) = True
145 injective (P (TCon _ _) _ _) = True
146-- injective (App f (P _ _ _)) = injective f
147-- injective (App f (Constant _)) = injective f
148 injective (App f a) = injective f -- && injective a
149 injective _ = False
151 notP (P _ _ _) = False
152 notP _ = True
154 sc i = do UI s f <- get
155 put (UI (s+i) f)
157 uplus u1 u2 = do UI s f <- get
158 r <- u1
159 UI s f' <- get
160 if (length f == length f')
161 then return r
162 else do put (UI s f); u2
164 un :: Bool -> [(Name, Name)] -> TT Name -> TT Name ->
165 StateT UInfo
166 TC [(Name, TT Name)]
167 un = un'
168-- un fn names x y
169-- = let (xf, _) = unApply x
170-- (yf, _) = unApply y in
171-- if headDiff xf yf then unifyFail x y else
172-- uplus (un' fn names x y)
173-- (un' fn names (hnf ctxt env x) (hnf ctxt env y))
175 un' :: Bool -> [(Name, Name)] -> TT Name -> TT Name ->
176 StateT UInfo
177 TC [(Name, TT Name)]
178 un' fn names x y | x == y = return [] -- shortcut
179 un' fn names topx@(P (DCon _ _) x _) topy@(P (DCon _ _) y _)
180 | x /= y = unifyFail topx topy
181 un' fn names topx@(P (TCon _ _) x _) topy@(P (TCon _ _) y _)
182 | x /= y = unifyFail topx topy
183 un' fn names topx@(P (DCon _ _) x _) topy@(P (TCon _ _) y _)
184 = unifyFail topx topy
185 un' fn names topx@(P (TCon _ _) x _) topy@(P (DCon _ _) y _)
186 = unifyFail topx topy
187 un' fn names topx@(Constant _) topy@(P (TCon _ _) y _)
188 = unifyFail topx topy
189 un' fn names topx@(P (TCon _ _) x _) topy@(Constant _)
190 = unifyFail topx topy
191 un' fn bnames tx@(P _ x _) ty@(P _ y _)
192 | (x,y) `elem` bnames || x == y = do sc 1; return []
193 | injective tx && not (holeIn env y || y `elem` holes)
194 = unifyTmpFail tx ty
195 | injective ty && not (holeIn env x || x `elem` holes)
196 = unifyTmpFail tx ty
197 un' fn bnames xtm@(P _ x _) tm
198 | holeIn env x || x `elem` holes
199 = do UI s f <- get
200 -- injectivity check
201 if (notP tm && fn)
202-- trace (show (x, tm, normalise ctxt env tm)) $
203-- put (UI s ((tm, topx, topy) : i) f)
204 then unifyTmpFail xtm tm
205 else do sc 1
206 checkCycle bnames (x, tm)
207 | not (injective xtm) && injective tm = unifyFail xtm tm
208 un' fn bnames tm ytm@(P _ y _)
209 | holeIn env y || y `elem` holes
210 = do UI s f <- get
211 -- injectivity check
212 if (notP tm && fn)
213-- trace (show (y, tm, normalise ctxt env tm)) $
214-- put (UI s ((tm, topx, topy) : i) f)
215 then unifyTmpFail tm ytm
216 else do sc 1
217 checkCycle bnames (y, tm)
218 | not (injective ytm) && injective tm = unifyFail ytm tm
219 un' fn bnames (V i) (P _ x _)
220 | fst (bnames!!i) == x || snd (bnames!!i) == x = do sc 1; return []
221 un' fn bnames (P _ x _) (V i)
222 | fst (bnames!!i) == x || snd (bnames!!i) == x = do sc 1; return []
224 un' fn bnames appx@(App _ _) appy@(App _ _)
225 = unApp fn bnames appx appy
226-- = uplus (unApp fn bnames appx appy)
227-- (unifyTmpFail appx appy) -- take the whole lot
229 un' fn bnames x (Bind n (Lam t) (App y (P Bound n' _)))
230 | n == n' = un' False bnames x y
231 un' fn bnames (Bind n (Lam t) (App x (P Bound n' _))) y
232 | n == n' = un' False bnames x y
233 un' fn bnames x (Bind n (Lam t) (App y (V 0)))
234 = un' False bnames x y
235 un' fn bnames (Bind n (Lam t) (App x (V 0))) y
236 = un' False bnames x y
237-- un' fn bnames (Bind x (PVar _) sx) (Bind y (PVar _) sy)
238-- = un' False ((x,y):bnames) sx sy
239-- un' fn bnames (Bind x (PVTy _) sx) (Bind y (PVTy _) sy)
240-- = un' False ((x,y):bnames) sx sy
241 un' fn bnames (Bind x bx sx) (Bind y by sy)
242 = do h1 <- uB bnames bx by
243 h2 <- un' False ((x,y):bnames) sx sy
244 combine bnames h1 h2
245 un' fn bnames x y
246 | OK True <- convEq' ctxt x y = do sc 1; return []
247 | otherwise = do UI s f <- get
248 let r = recoverable x y
249 let err = CantUnify r
250 topx topy (CantUnify r x y (Msg "") [] s) (errEnv env) s
251 if (not r) then lift $ tfail err
252 else do put (UI s ((x, y, env, err) : f))
253 return [] -- lift $ tfail err
255 unApp fn bnames appx@(App fx ax) appy@(App fy ay)
256 | (injective fx && injective fy)
257 || (injective fx && rigid appx && metavarApp appy)
258 || (injective fy && rigid appy && metavarApp appx)
259 || (injective fx && metavarApp fy && ax == ay)
260 || (injective fy && metavarApp fx && ax == ay)
261 = do let (headx, _) = unApply fx
262 let (heady, _) = unApply fy
263 -- fail quickly if the heads are disjoint
264 checkHeads headx heady
265-- if True then -- (injective fx || injective fy || fx == fy) then
266-- if (injective fx && metavarApp appy) ||
267-- (injective fy && metavarApp appx) ||
268-- (injective fx && injective fy) || fx == fy
269 uplus
270 (do hf <- un' True bnames fx fy
271 let ax' = hnormalise hf ctxt env (substNames hf ax)
272 let ay' = hnormalise hf ctxt env (substNames hf ay)
273 ha <- un' False bnames ax' ay'
274 sc 1
275 combine bnames hf ha)
276 (do ha <- un' False bnames ax ay
277 let fx' = hnormalise ha ctxt env (substNames ha fx)
278 let fy' = hnormalise ha ctxt env (substNames ha fy)
279 hf <- un' False bnames fx' fy'
280 sc 1
281 combine bnames hf ha)
282 | otherwise = -- trace (show (appx, appy, injective fx, metavarApp appy, sameArgStruct appx appy)) $
283 do let (headx, argsx) = unApply appx
284 let (heady, argsy) = unApply appy
285 -- traceWhen (headx == heady) (show (appx, appy)) $
286 uplus (
287 if (length argsx == length argsy &&
288 ((headx == heady && inenv headx) || (argsx == argsy) ||
289 (and (zipWith sameStruct (headx:argsx) (heady:argsy)))))
290 then
291-- (notFn headx && notFn heady))) then
292 do uf <- un' True bnames headx heady
293 unArgs uf argsx argsy
294 else -- trace ("TMPFAIL " ++ show (appx, appy, injective appx, injective appy)) $
295 unifyTmpFail appx appy)
296 (unifyTmpFail appx appy) -- whole application fails
297 where hnormalise [] _ _ t = t
298 hnormalise ns ctxt env t = normalise ctxt env t
299 checkHeads (P (DCon _ _) x _) (P (DCon _ _) y _)
300 | x /= y = unifyFail appx appy
301 checkHeads (P (TCon _ _) x _) (P (TCon _ _) y _)
302 | x /= y = unifyFail appx appy
303 checkHeads (P (DCon _ _) x _) (P (TCon _ _) y _)
304 = unifyFail appx appy
305 checkHeads (P (TCon _ _) x _) (P (DCon _ _) y _)
306 = unifyFail appx appy
307 checkHeads _ _ = return []
309 unArgs as [] [] = return as
310 unArgs as (x : xs) (y : ys)
311 = do let x' = hnormalise as ctxt env (substNames as x)
312 let y' = hnormalise as ctxt env (substNames as y)
313 as' <- un' False bnames x' y'
314 vs <- combine bnames as as'
315 unArgs vs xs ys
317 metavarApp tm = let (f, args) = unApply tm in
318 all (\x -> metavar x) (f : args)
319 && nub args == args
320 metavarArgs tm = let (f, args) = unApply tm in
321 all (\x -> metavar x || inenv x) args
322 && nub args == args
323 metavarApp' tm = let (f, args) = unApply tm in
324 all (\x -> pat x || metavar x) (f : args)
325 && nub args == args
327 sameArgStruct appx appy
328 = let (_, ax) = unApply appx
329 (_, ay) = unApply appy in
330 length ax == length ay &&
331 and (zipWith sameStruct ax ay)
333 sameStruct fapp@(App f x) gapp@(App g y)
334 = let (f',a') = unApply fapp
335 (g',b') = unApply gapp in
336 (f' == g' && length a' == length b' &&
337 (injective f' || injective g'))
338 || (sameStruct f g && sameStruct x y)
339 sameStruct (P _ x _) (P _ y _) = True
340 sameStruct (V i) (V j) = i == j
341 sameStruct (Constant x) (Constant y) = True
342 sameStruct (P _ _ _) (Constant y) = True
343 sameStruct (Constant x) (P _ _ _) = True
344 sameStruct (Bind n t sc) (P _ _ _) = True
345 sameStruct (P _ _ _) (Bind n t sc) = True
346 sameStruct (Bind n t sc) (Bind n' t' sc') = sameStruct sc sc'
347 sameStruct _ _ = False
349 rigid (P (DCon _ _) _ _) = True
350 rigid (P (TCon _ _) _ _) = True
351 rigid t@(P Ref _ _) = inenv t
352 rigid (Constant _) = True
353 rigid (App f a) = rigid f && rigid a
354 rigid t = not (metavar t)
356 metavar t = case t of
357 P _ x _ -> (x `elem` holes || holeIn env x) &&
358 not (x `elem` dont)
359 _ -> False
360 pat t = case t of
361 P _ x _ -> x `elem` holes || patIn env x
362 _ -> False
363 inenv t = case t of
364 P _ x _ -> x `elem` (map fst env)
365 _ -> False
367 notFn t = injective t || metavar t || inenv t
370 unifyTmpFail x y
371 = do UI s f <- get
372 let r = recoverable x y
373 let err = CantUnify r
374 topx topy (CantUnify r x y (Msg "") [] s) (errEnv env) s
375 put (UI s ((topx, topy, env, err) : f))
376 return []
378 -- shortcut failure, if we *know* nothing can fix it
379 unifyFail x y = do UI s f <- get
380 let r = recoverable x y
381 let err = CantUnify r
382 topx topy (CantUnify r x y (Msg "") [] s) (errEnv env) s
383 put (UI s ((topx, topy, env, err) : f))
384 lift $ tfail err
387 uB bnames (Let tx vx) (Let ty vy)
388 = do h1 <- un' False bnames tx ty
389 h2 <- un' False bnames ty vy
390 sc 1
391 combine bnames h1 h2
392 uB bnames (Guess tx vx) (Guess ty vy)
393 = do h1 <- un' False bnames tx ty
394 h2 <- un' False bnames ty vy
395 sc 1
396 combine bnames h1 h2
397 uB bnames (Lam tx) (Lam ty) = do sc 1; un' False bnames tx ty
398 uB bnames (Pi tx) (Pi ty) = do sc 1; un' False bnames tx ty
399 uB bnames (Hole tx) (Hole ty) = un' False bnames tx ty
400 uB bnames (PVar tx) (PVar ty) = un' False bnames tx ty
401 uB bnames x y = do UI s f <- get
402 let r = recoverable (binderTy x) (binderTy y)
403 let err = CantUnify r topx topy
404 (CantUnify r (binderTy x) (binderTy y) (Msg "") [] s)
405 (errEnv env) s
406 put (UI s ((binderTy x, binderTy y, env, err) : f))
407 return [] -- lift $ tfail err
409 checkCycle ns p@(x, P _ _ _) = return [p]
410 checkCycle ns (x, tm)
411 | not (x `elem` freeNames tm) = checkScope ns (x, tm)
412 | otherwise = lift $ tfail (InfiniteUnify x tm (errEnv env))
414 checkScope ns (x, tm) =
415 case boundVs (envPos x 0 env) tm of
416 [] -> return [(x, tm)]
417 (i:_) -> lift $ tfail (UnifyScope x (fst (ns!!i))
418 (inst ns tm) (errEnv env))
419 where inst [] tm = tm
420 inst ((n, _) : ns) tm = inst ns (substV (P Bound n Erased) tm)
422 combineArgs bnames args = ca [] args where
423 ca acc [] = return acc
424 ca acc (x : xs) = do x' <- combine bnames acc x
425 ca x' xs
427 combine bnames as [] = return as
428 combine bnames as ((n, t) : bs)
429 = case lookup n as of
430 Nothing -> combine bnames (as ++ [(n,t)]) bs
431 Just t' -> do ns <- un' False bnames t t'
432 -- make sure there's n mapping from n in ns
433 let ns' = filter (\ (x, _) -> x/=n) ns
434 sc 1
435 combine bnames as (ns' ++ bs)
437boundVs :: Int -> Term -> [Int]
438boundVs i (V j) | j <= i = []
439 | otherwise = [j]
440boundVs i (Bind n b sc) = boundVs (i + 1) sc
441boundVs i (App f x) = let fs = boundVs i f
442 xs = boundVs i x in
443 nub (fs ++ xs)
444boundVs i _ = []
446envPos x i [] = 0
447envPos x i ((y, _) : ys) | x == y = i
448 | otherwise = envPos x (i + 1) ys
451-- If there are any clashes of constructors, deem it unrecoverable, otherwise some
452-- more work may help.
453-- FIXME: Depending on how overloading gets used, this may cause problems. Better
454-- rethink overloading properly...
456recoverable (P (DCon _ _) x _) (P (DCon _ _) y _)
457 | x == y = True
458 | otherwise = False
459recoverable (P (TCon _ _) x _) (P (TCon _ _) y _)
460 | x == y = True
461 | otherwise = False
462recoverable (Constant _) (P (DCon _ _) y _) = False
463recoverable (P (DCon _ _) x _) (Constant _) = False
464recoverable (Constant _) (P (TCon _ _) y _) = False
465recoverable (P (TCon _ _) x _) (Constant _) = False
466recoverable (P (DCon _ _) x _) (P (TCon _ _) y _) = False
467recoverable (P (TCon _ _) x _) (P (DCon _ _) y _) = False
468recoverable p@(Constant _) (App f a) = recoverable p f
469recoverable (App f a) p@(Constant _) = recoverable f p
470recoverable p@(P _ n _) (App f a) = recoverable p f
471-- recoverable (App f a) p@(P _ _ _) = recoverable f p
472recoverable (App f a) (App f' a')
473 = recoverable f f' -- && recoverable a a'
474recoverable _ _ = True
476errEnv = map (\(x, b) -> (x, binderTy b))
478holeIn :: Env -> Name -> Bool
479holeIn env n = case lookup n env of
480 Just (Hole _) -> True
481 Just (Guess _ _) -> True
482 _ -> False
484patIn :: Env -> Name -> Bool
485patIn env n = case lookup n env of
486 Just (PVar _) -> True
487 Just (PVTy _) -> True
488 _ -> False