[project @ 2000-10-23 09:03:26 by simonpj]
[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 Util             ( zipEqual )
27 \end{code}
28
29
30 \begin{code}
31 oclose :: Uniquable a => [FunDep a] -> UniqSet a -> UniqSet a
32 -- (oclose fds tvs) closes the set of type variables tvs, 
33 -- wrt the functional dependencies fds.  The result is a superset
34 -- of the argument set.
35 --
36 -- For example,
37 --      oclose [a -> b] {a}     = {a,b}
38 --      oclose [a b -> c] {a}   = {a}
39 --      oclose [a b -> c] {a,b} = {a,b,c}
40 -- If all of the things on the left of an arrow are in the set, add
41 -- the things on the right of that arrow.
42
43 oclose fds vs =
44     case oclose1 fds vs of
45       (vs', False) -> vs'
46       (vs', True)  -> oclose fds vs'
47
48 oclose1 [] vs = (vs, False)
49 oclose1 (fd@(ls, rs):fds) vs =
50     if osubset ls vs then
51         (vs'', b1 || b2)
52     else
53         vs'b1
54     where
55         vs'b1@(vs', b1) = oclose1 fds vs
56         (vs'', b2) = ounion rs vs'
57
58 osubset [] vs = True
59 osubset (u:us) vs = if u `elementOfUniqSet` vs then osubset us vs else False
60
61 ounion [] ys = (ys, False)
62 ounion (x:xs) ys
63     | x `elementOfUniqSet` ys = (ys', b)
64     | otherwise               = (addOneToUniqSet ys' x, True)
65     where
66         (ys', b) = ounion xs ys
67
68 instantiateFdClassTys :: Class -> [Type] -> [FunDep Type]
69 -- Get the FDs of the class, and instantiate them
70 instantiateFdClassTys clas tys
71   = [(map lookup us, map lookup vs) | (us,vs) <- fundeps]
72   where
73     (tyvars, fundeps) = classTvsFds clas
74     env       = mkVarEnv (zipEqual "instantiateFdClassTys" tyvars tys)
75     lookup tv = lookupVarEnv_NF env tv
76
77 tyVarFunDep :: [FunDep Type] -> [FunDep TyVar]
78 tyVarFunDep fdtys 
79   = [(getTyvars xs, getTyvars ys) | (xs, ys) <- fdtys]
80   where 
81     getTyvars = varSetElems . tyVarsOfTypes
82
83 pprFundeps :: Outputable a => [FunDep a] -> SDoc
84 pprFundeps [] = empty
85 pprFundeps fds = hsep (ptext SLIT("|") : punctuate comma (map ppr_fd fds))
86
87 ppr_fd (us, vs) = hsep [interppSP us, ptext SLIT("->"), interppSP vs]
88 \end{code}