@@ -6,6 +6,7 @@ import Idris.AbsSyntax
66import Idris.Core.CaseTree
77import Idris.Core.TT
88
9+import Debug.Trace
910
1011transformPats :: IState -> [Either Term (Term, Term)] ->
1112 [Either Term (Term, Term)]
@@ -19,4 +20,52 @@ applyTransRules :: IState -> Term -> Term
1920applyTransRules ist tm = applyAll (idris_transforms ist) tm
2021
2122applyAll :: Ctxt [(Term, Term)] -> Term -> Term
22−applyAll ts t = t
23+applyAll ts ap@(App f a)
24+ | (P _ fn ty, args) <- unApply ap
25+ = case lookupCtxtExact fn ts of
26+ Just rules -> case applyFnRules rules ap of
27+ Just tm' -> tm'
28+ _ -> App (applyAll ts f) (applyAll ts a)
29+ Nothing -> App (applyAll ts f) (applyAll ts a)
30+applyAll ts (Bind n b sc) = Bind n (fmap (applyAll ts) b) (applyAll ts sc)
31+applyAll ts t = t
32+
33+applyFnRules :: [(Term, Term)] -> Term -> Maybe Term
34+applyFnRules [] tm = Nothing
35+applyFnRules (r : rs) tm | Just tm' <- applyRule r tm = Just tm'
36+ | otherwise = applyFnRules rs tm
37+
38+applyRule :: (Term, Term) -> Term -> Maybe Term
39+applyRule (lhs, rhs) tm
40+ | Just ms <- matchTerm lhs tm
41+-- = trace ("SUCCESS " ++ show ms ++ "\n FROM\n" ++ show lhs ++
42+-- "\n" ++ show rhs
43+-- ++ "\n" ++ show tm) $
44+ = Just $ depat ms rhs
45+ | otherwise = Nothing
46+ where depat ms (Bind n (PVar t) sc)
47+ = case lookup n ms of
48+ Just tm -> depat ms (instantiate tm sc)
49+ _ -> depat ms sc -- no occurrence? Shouldn't happen
50+ depat ms tm = tm
51+
52+matchTerm :: Term -> Term -> Maybe [(Name, Term)]
53+matchTerm lhs tm = matchVars [] lhs tm
54+ where
55+ matchVars acc (Bind n (PVar t) sc) tm
56+ = matchVars (n : acc) (instantiate (P Bound n t) sc) tm
57+ matchVars acc sc tm
58+ = -- trace (show acc ++ ": " ++ show (sc, tm)) $
59+ doMatch acc sc tm
60+
61+ doMatch :: [Name] -> Term -> Term -> Maybe [(Name, Term)]
62+ doMatch ns (P _ n _) tm
63+ | n `elem` ns = return [(n, tm)]
64+ doMatch ns (App f a) (App f' a')
65+ = do fm <- doMatch ns f f'
66+ am <- doMatch ns a a'
67+ return (fm ++ am)
68+ doMatch ns x y | x == y = return []
69+ | otherwise = Nothing
70+
71+