[project @ 2000-10-20 15:38:42 by sewardj]
[ghc-hetmet.git] / ghc / compiler / types / FunDeps.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 2000
3 %
4 \section[FunDeps]{FunDeps - functional dependencies}
5
6 It's better to read it as: "if we know these, then we're going to know these"
7
8 \begin{code}
9 module FunDeps (
10         oclose,
11         instantiateFdClassTys,
12         tyVarFunDep,
13         pprFundeps
14     ) where
15
16 #include "HsVersions.h"
17
18 import Var              ( TyVar )
19 import Class            ( Class, FunDep, classTvsFds )
20 import Type             ( Type, tyVarsOfTypes )
21 import Outputable       ( Outputable, SDoc, interppSP, ptext, empty, hsep, punctuate, comma )
22 import UniqSet
23 import VarSet
24 import VarEnv
25 import Unique           ( Uniquable )
26 import List             ( elemIndex )
27 import Util             ( zipEqual )
28 \end{code}
29
30
31 \begin{code}
32 oclose :: Uniquable a => [FunDep a] -> UniqSet a -> UniqSet a
33 -- (oclose fds tvs) closes the set of type variables tvs, 
34 -- wrt the functional dependencies fds.  The result is a superset
35 -- of the argument set.
36 --
37 -- For example,
38 --      oclose [a -> b] {a}     = {a,b}
39 --      oclose [a b -> c] {a}   = {a}
40 --      oclose [a b -> c] {a,b} = {a,b,c}
41 -- If all of the things on the left of an arrow are in the set, add
42 -- the things on the right of that arrow.
43
44 oclose fds vs =
45     case oclose1 fds vs of
46       (vs', False) -> vs'
47       (vs', True)  -> oclose fds vs'
48
49 oclose1 [] vs = (vs, False)
50 oclose1 (fd@(ls, rs):fds) vs =
51     if osubset ls vs then
52         (vs'', b1 || b2)
53     else
54         vs'b1
55     where
56         vs'b1@(vs', b1) = oclose1 fds vs
57         (vs'', b2) = ounion rs vs'
58
59 osubset [] vs = True
60 osubset (u:us) vs = if u `elementOfUniqSet` vs then osubset us vs else False
61
62 ounion [] ys = (ys, False)
63 ounion (x:xs) ys
64     | x `elementOfUniqSet` ys = (ys', b)
65     | otherwise               = (addOneToUniqSet ys' x, True)
66     where
67         (ys', b) = ounion xs ys
68
69 instantiateFdClassTys :: Class -> [Type] -> [FunDep Type]
70 -- Get the FDs of the class, and instantiate them
71 instantiateFdClassTys clas tys
72   = [(map lookup us, map lookup vs) | (us,vs) <- fundeps]
73   where
74     (tyvars, fundeps) = classTvsFds clas
75     env       = mkVarEnv (zipEqual "instantiateFdClassTys" tyvars tys)
76     lookup tv = lookupVarEnv_NF env tv
77
78 tyVarFunDep :: [FunDep Type] -> [FunDep TyVar]
79 tyVarFunDep fdtys 
80   = [(getTyvars xs, getTyvars ys) | (xs, ys) <- fdtys]
81   where 
82     getTyvars = varSetElems . tyVarsOfTypes
83
84 pprFundeps :: Outputable a => [FunDep a] -> SDoc
85 pprFundeps [] = empty
86 pprFundeps fds = hsep (ptext SLIT("|") : punctuate comma (map ppr_fd fds))
87
88 ppr_fd (us, vs) = hsep [interppSP us, ptext SLIT("->"), interppSP vs]
89 \end{code}