[project @ 1997-03-14 07:52:06 by simonpj]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcInstUtil.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
3 %
4 \section[TcInstUtil]{Utilities for typechecking instance declarations}
5
6 The bits common to TcInstDcls and TcDeriv.
7
8 \begin{code}
9 #include "HsVersions.h"
10
11 module TcInstUtil (
12         InstInfo(..),
13         mkInstanceRelatedIds,
14         buildInstanceEnvs
15     ) where
16
17 IMP_Ubiq()
18
19 import HsSyn            ( MonoBinds, Fake, InPat, Sig )
20 import RnHsSyn          ( SYN_IE(RenamedMonoBinds), RenamedSig(..), 
21                           RenamedInstancePragmas(..) )
22
23 import TcEnv            ( tcAddImportedIdInfo )
24 import TcMonad
25 import Inst             ( SYN_IE(InstanceMapper) )
26
27 import Bag              ( bagToList )
28 import Class            ( GenClass, GenClassOp, SYN_IE(ClassInstEnv),
29                           classBigSig, classOps, classOpLocalType,
30                           SYN_IE(ClassOp)
31                         )
32 import CoreSyn          ( GenCoreExpr(..), mkValLam, mkTyApp )
33 import Id               ( GenId, mkDictFunId, mkConstMethodId, mkSysLocal )
34 import MatchEnv         ( nullMEnv, insertMEnv )
35 import Maybes           ( MaybeErr(..), mkLookupFunDef )
36 import Name             ( getSrcLoc, Name{--O only-} )
37 import PprType          ( GenClass, GenType, GenTyVar )
38 import Pretty
39 import SpecEnv          ( SpecEnv, nullSpecEnv, addOneToSpecEnv )
40 import SrcLoc           ( SrcLoc )
41 import Type             ( mkSigmaTy, mkForAllTys, mkDictTy, mkTyVarTys,
42                           splitForAllTy, instantiateTy, matchTy, SYN_IE(ThetaType) )
43 import TyVar            ( GenTyVar )
44 import Unique           ( Unique )
45 import Util             ( equivClasses, zipWithEqual, panic{-, pprTrace-} )
46 --import PprStyle
47
48 --import TcPragmas      ( tcDictFunPragmas, tcGenPragmas )
49 \end{code}
50
51     instance c => k (t tvs) where b
52
53 \begin{code}
54 data InstInfo
55   = InstInfo
56       Class             -- Class, k
57       [TyVar]           -- Type variables, tvs
58       Type              -- The type at which the class is being instantiated
59       ThetaType         -- inst_decl_theta: the original context, c, from the
60                         --   instance declaration.  It constrains (some of)
61                         --   the TyVars above
62       ThetaType         -- dfun_theta: the inst_decl_theta, plus one
63                         --   element for each superclass; the "Mark
64                         --   Jones optimisation"
65       Id                -- The dfun id
66       RenamedMonoBinds  -- Bindings, b
67       SrcLoc            -- Source location assoc'd with this instance's defn
68       [RenamedSig]      -- User pragmas recorded for generating specialised instances
69 \end{code}
70
71 %************************************************************************
72 %*                                                                      *
73 \subsection{Creating instance related Ids}
74 %*                                                                      *
75 %************************************************************************
76
77 \begin{code}
78 mkInstanceRelatedIds :: Name            -- Name to use for the dict fun;
79                      -> Class 
80                      -> [TyVar]
81                      -> Type
82                      -> ThetaType
83                      -> NF_TcM s (Id, ThetaType)
84
85 mkInstanceRelatedIds dfun_name clas inst_tyvars inst_ty inst_decl_theta
86   = tcAddImportedIdInfo dfun_id                 `thenNF_Tc` \ new_dfun_id ->
87     returnNF_Tc (new_dfun_id, dfun_theta)
88   where
89     (_, super_classes, _, _, _, _) = classBigSig clas
90     super_class_theta = super_classes `zip` repeat inst_ty
91
92     dfun_theta = case inst_decl_theta of
93                         []    -> []     -- If inst_decl_theta is empty, then we don't
94                                         -- want to have any dict arguments, so that we can
95                                         -- expose the constant methods.
96
97                         other -> inst_decl_theta ++ super_class_theta
98                                         -- Otherwise we pass the superclass dictionaries to
99                                         -- the dictionary function; the Mark Jones optimisation.
100
101     dfun_ty = mkSigmaTy inst_tyvars dfun_theta (mkDictTy clas inst_ty)
102
103     dfun_id = mkDictFunId dfun_name dfun_ty clas inst_ty
104 \end{code}
105
106
107 %************************************************************************
108 %*                                                                      *
109 \subsection{Converting instance info into suitable InstEnvs}
110 %*                                                                      *
111 %************************************************************************
112
113 \begin{code}
114 buildInstanceEnvs :: Bag InstInfo
115                   -> TcM s InstanceMapper
116
117 buildInstanceEnvs info
118   = let
119         icmp :: InstInfo -> InstInfo -> TAG_
120         (InstInfo c1 _ _ _ _ _ _ _ _) `icmp` (InstInfo c2 _ _ _ _ _ _ _ _)
121           = c1 `cmp` c2
122
123         info_by_class = equivClasses icmp (bagToList info)
124     in
125     mapTc buildInstanceEnv info_by_class    `thenTc` \ inst_env_entries ->
126     let
127         class_lookup_fn = mkLookupFunDef (==) inst_env_entries 
128                                          (nullMEnv, \ o -> nullSpecEnv)
129     in
130     returnTc class_lookup_fn
131 \end{code}
132
133 \begin{code}
134 buildInstanceEnv :: [InstInfo]          -- Non-empty, and all for same class
135                  -> TcM s (Class, (ClassInstEnv, (ClassOp -> SpecEnv)))
136
137 buildInstanceEnv inst_infos@((InstInfo clas _ _ _ _ _ _ _ _) : _)
138   = foldlTc addClassInstance
139             (nullMEnv, [(op, nullSpecEnv) | op <- classOps clas])
140             inst_infos
141                                         `thenTc` \ (class_inst_env, op_inst_envs) ->
142     returnTc (clas, (class_inst_env,
143                      mkLookupFunDef (==) op_inst_envs
144                                     (panic "buildInstanceEnv")))
145 \end{code}
146
147 @addClassInstance@ adds the appropriate stuff to the @ClassInstEnv@
148 based on information from a single instance declaration.  It complains
149 about any overlap with an existing instance.
150
151 \begin{code}
152 addClassInstance
153     :: (ClassInstEnv, [(ClassOp,SpecEnv)])
154     -> InstInfo
155     -> TcM s (ClassInstEnv, [(ClassOp,SpecEnv)])
156
157 addClassInstance
158     input_stuff@(class_inst_env, op_spec_envs)
159     (InstInfo clas inst_tyvars inst_ty _ _ 
160               dfun_id _ src_loc _)
161   = 
162
163 -- We only add specialised/overlapped instances
164 -- if we are specialising the overloading
165 -- ToDo ... This causes getConstMethodId errors!
166 --
167 --    if not (is_plain_instance inst_ty) && not opt_SpecialiseOverloaded
168 --    then
169 --      -- Drop this specialised/overlapped instance
170 --      returnTc (class_inst_env, op_spec_envs)
171 --    else      
172
173         -- Add the instance to the class's instance environment
174     case insertMEnv matchTy class_inst_env inst_ty dfun_id of {
175         Failed (ty', dfun_id')    -> recoverTc (returnTc input_stuff) $
176                                      dupInstFailure clas (inst_ty, src_loc) 
177                                                          (ty', getSrcLoc dfun_id');
178         Succeeded class_inst_env' -> 
179
180             returnTc (class_inst_env', op_spec_envs)
181
182 {-              OLD STUFF FOR CONSTANT METHODS 
183
184         -- If there are any constant methods, then add them to 
185         -- the SpecEnv of each class op (ie selector)
186         --
187         -- Example.  class    Foo a     where { op :: Baz b => a -> b; ... }
188         --           instance Foo (p,q) where { op (x,y) = ...       ; ... }
189         --
190         -- The class decl means that 
191         --      op :: forall a. Foo a => forall b. Baz b => a -> b
192         --
193         -- The constant method from the instance decl will be:
194         --      op_Pair :: forall p q b. Baz b => (p,q) -> b
195         --
196         -- What we put in op's SpecEnv is
197         --      (p,q) |-->  (\d::Foo (p,q) -> op_Pair p q)
198         --
199         -- Here, [p,q] are the inst_tyvars, and d is a dict whose only
200         -- purpose is to cancel with the dict to which op is applied.
201         -- 
202         -- NOTE THAT this correctly deals with the case where there are
203         -- constant methods even though there are type variables in the
204         -- instance declaration.
205
206     tcGetUnique                         `thenNF_Tc` \ uniq ->
207     let 
208       dict = mkSysLocal SLIT("dict_tpl") uniq (mkDictTy clas inst_ty) src_loc
209                 -- Slightly disgusting, but it's only a placeholder for
210                 -- a dictionary to be chucked away.
211
212       op_spec_envs' | null const_meth_ids = op_spec_envs
213                     | otherwise           = zipWithEqual "add_const_meth" add_const_meth op_spec_envs const_meth_ids
214
215       add_const_meth (op,spec_env) meth_id
216         = (op, case addOneToSpecEnv spec_env [inst_ty] rhs of
217                  Failed (tys', rhs') -> panic "TcInstDecls:add_const_meth"
218                  Succeeded spec_env' -> spec_env' )
219         where
220           rhs = mkValLam [dict] (mkTyApp (Var meth_id) (mkTyVarTys inst_tyvars))
221     in
222     returnTc (class_inst_env', op_spec_envs')
223                 END OF OLD STUFF -}
224
225     }
226 \end{code}
227
228 \begin{code}
229 dupInstFailure clas info1@(ty1, locn1) info2@(ty2, locn2)
230         -- Overlapping/duplicate instances for given class; msg could be more glamourous
231   = tcAddErrCtxt ctxt $
232     failTc (\sty -> ppPStr SLIT("Duplicate or overlapping instance declarations"))
233   where
234     ctxt sty = ppHang (ppSep [ppBesides[ppPStr SLIT("Class `"), ppr sty clas, ppChar '\''],
235                               ppBesides[ppPStr SLIT("type `"), ppr sty ty1, ppChar '\'']])
236                     4 (ppSep [ppBesides [ppPStr SLIT("at "), ppr sty locn1],
237                               ppBesides [ppPStr SLIT("and "), ppr sty locn2]])
238 \end{code}