38b8f2fb41034190e33bac527b54999a06f127a0
[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 TcMonad          hiding ( rnMtoTcM )
24 import Inst             ( SYN_IE(InstanceMapper) )
25
26 import Bag              ( bagToList )
27 import Class            ( GenClass, GenClassOp, SYN_IE(ClassInstEnv),
28                           classBigSig, classOps, classOpLocalType,
29                           SYN_IE(ClassOp)
30                         )
31 import CoreSyn          ( GenCoreExpr(..), mkValLam, mkTyApp )
32 import Id               ( GenId, mkDictFunId, mkConstMethodId, mkSysLocal )
33 import MatchEnv         ( nullMEnv, insertMEnv )
34 import Maybes           ( MaybeErr(..), mkLookupFunDef )
35 import Name             ( getSrcLoc, Name{--O only-} )
36 import PprType          ( GenClass, GenType, GenTyVar )
37 import Pretty
38 import SpecEnv          ( SpecEnv, nullSpecEnv, addOneToSpecEnv )
39 import SrcLoc           ( SrcLoc )
40 import Type             ( mkSigmaTy, mkForAllTys, mkDictTy, mkTyVarTys,
41                           splitForAllTy, instantiateTy, matchTy, SYN_IE(ThetaType) )
42 import TyVar            ( GenTyVar )
43 import Unique           ( Unique )
44 import Util             ( equivClasses, zipWithEqual, panic )
45
46 import IdInfo           ( noIdInfo )
47 --import TcPragmas      ( tcDictFunPragmas, tcGenPragmas )
48 \end{code}
49
50     instance c => k (t tvs) where b
51
52 \begin{code}
53 data InstInfo
54   = InstInfo
55       Class             -- Class, k
56       [TyVar]           -- Type variables, tvs
57       Type              -- The type at which the class is being instantiated
58       ThetaType         -- inst_decl_theta: the original context, c, from the
59                         --   instance declaration.  It constrains (some of)
60                         --   the TyVars above
61       ThetaType         -- dfun_theta: the inst_decl_theta, plus one
62                         --   element for each superclass; the "Mark
63                         --   Jones optimisation"
64       Id                -- The dfun id
65       [Id]              -- Constant methods (either all or none)
66       RenamedMonoBinds  -- Bindings, b
67       Bool              -- True <=> local instance decl
68       Module            -- Name of module where this instance defined
69       SrcLoc            -- Source location assoc'd with this instance's defn
70       [RenamedSig]      -- User pragmas recorded for generating specialised instances
71 \end{code}
72
73 %************************************************************************
74 %*                                                                      *
75 \subsection{Creating instance related Ids}
76 %*                                                                      *
77 %************************************************************************
78
79 \begin{code}
80 mkInstanceRelatedIds :: Bool
81                      -> SrcLoc
82                      -> Module
83                      -> RenamedInstancePragmas
84                      -> Class 
85                      -> [TyVar]
86                      -> Type
87                      -> ThetaType
88                      -> [RenamedSig]
89                      -> TcM s (Id, ThetaType, [Id])
90
91 mkInstanceRelatedIds from_here src_loc inst_mod inst_pragmas
92                      clas inst_tyvars inst_ty inst_decl_theta uprags
93   =     -- MAKE THE DFUN ID
94     let
95         dfun_theta = case inst_decl_theta of
96                         []    -> []     -- If inst_decl_theta is empty, then we don't
97                                         -- want to have any dict arguments, so that we can
98                                         -- expose the constant methods.
99
100                         other -> inst_decl_theta ++ super_class_theta
101                                         -- Otherwise we pass the superclass dictionaries to
102                                         -- the dictionary function; the Mark Jones optimisation.
103
104         dfun_ty = mkSigmaTy inst_tyvars dfun_theta (mkDictTy clas inst_ty)
105     in
106     tcGetUnique                         `thenNF_Tc` \ dfun_uniq ->
107     fixTc ( \ rec_dfun_id ->
108
109 {- LATER
110         tcDictFunPragmas dfun_ty rec_dfun_id inst_pragmas
111                                         `thenNF_Tc` \ dfun_pragma_info ->
112         let
113             dfun_specenv = mkInstSpecEnv clas inst_ty inst_tyvars dfun_theta
114             dfun_id_info = dfun_pragma_info `addInfo` dfun_specenv
115         in
116 -}
117         let dfun_id_info = noIdInfo in  -- For now
118
119         returnTc (mkDictFunId dfun_uniq clas inst_ty dfun_ty from_here src_loc inst_mod dfun_id_info)
120     ) `thenTc` \ dfun_id ->
121
122         -- MAKE THE CONSTANT-METHOD IDS
123         -- if there are no type variables involved
124     (if (null inst_decl_theta)
125      then
126         mapTc mk_const_meth_id class_ops
127      else
128         returnTc []
129     )                                   `thenTc` \ const_meth_ids ->
130
131     returnTc (dfun_id, dfun_theta, const_meth_ids)
132   where
133     (class_tyvar, super_classes, _, class_ops, _, _) = classBigSig clas
134     tenv = [(class_tyvar, inst_ty)]
135   
136     super_class_theta = super_classes `zip` repeat inst_ty
137
138     mk_const_meth_id op
139         = tcGetUnique           `thenNF_Tc` \ uniq ->
140           fixTc (\ rec_const_meth_id ->
141
142 {- LATER
143                 -- Figure out the IdInfo from the pragmas
144              (case assocMaybe opname_prag_pairs (getName op) of
145                 Nothing   -> returnTc inline_info
146                 Just prag -> tcGenPragmas (Just meth_ty) rec_const_meth_id prag
147              )                  `thenNF_Tc` \ id_info ->
148 -}
149              let id_info = noIdInfo     -- For now
150              in
151              returnTc (mkConstMethodId uniq clas op inst_ty meth_ty
152                                        from_here src_loc inst_mod id_info)
153           )
154         where
155           op_ty       = classOpLocalType op
156           meth_ty     = mkForAllTys inst_tyvars (instantiateTy tenv op_ty)
157 {- LATER
158           inline_me   = isIn "mkInstanceRelatedIds" op ops_to_inline
159           inline_info = if inline_me
160                         then noIdInfo `addInfo_UF` (iWantToBeINLINEd UnfoldAlways)
161                         else noIdInfo
162
163     opname_prag_pairs = case inst_pragmas of
164                            ConstantInstancePragma _ name_prag_pairs -> name_prag_pairs
165                            other_inst_pragmas                       -> []
166
167     ops_to_inline = [op | (InlineSig op _) <- uprags]
168 -}
169 \end{code}
170
171
172 %************************************************************************
173 %*                                                                      *
174 \subsection{Converting instance info into suitable InstEnvs}
175 %*                                                                      *
176 %************************************************************************
177
178 \begin{code}
179 buildInstanceEnvs :: Bag InstInfo
180                   -> TcM s InstanceMapper
181
182 buildInstanceEnvs info
183   = let
184         icmp :: InstInfo -> InstInfo -> TAG_
185         (InstInfo c1 _ _ _ _ _ _ _ _ _ _ _) `icmp` (InstInfo c2 _ _ _ _ _ _ _ _ _ _ _)
186           = c1 `cmp` c2
187
188         info_by_class = equivClasses icmp (bagToList info)
189     in
190     mapTc buildInstanceEnv info_by_class    `thenTc` \ inst_env_entries ->
191     let
192         class_lookup_fn = mkLookupFunDef (==) inst_env_entries 
193                                          (nullMEnv, \ o -> nullSpecEnv)
194     in
195     returnTc class_lookup_fn
196 \end{code}
197
198 \begin{code}
199 buildInstanceEnv :: [InstInfo]          -- Non-empty, and all for same class
200                  -> TcM s (Class, (ClassInstEnv, (ClassOp -> SpecEnv)))
201
202 buildInstanceEnv inst_infos@((InstInfo clas _ _ _ _ _ _ _ _ _ _ _) : _)
203   = foldlTc addClassInstance
204             (nullMEnv, [(op, nullSpecEnv) | op <- classOps clas])
205             inst_infos
206                                         `thenTc` \ (class_inst_env, op_inst_envs) ->
207     returnTc (clas, (class_inst_env,
208                      mkLookupFunDef (==) op_inst_envs
209                                     (panic "buildInstanceEnv")))
210 \end{code}
211
212 @addClassInstance@ adds the appropriate stuff to the @ClassInstEnv@
213 based on information from a single instance declaration.  It complains
214 about any overlap with an existing instance.
215
216 \begin{code}
217 addClassInstance
218     :: (ClassInstEnv, [(ClassOp,SpecEnv)])
219     -> InstInfo
220     -> TcM s (ClassInstEnv, [(ClassOp,SpecEnv)])
221
222 addClassInstance
223     (class_inst_env, op_spec_envs)
224     (InstInfo clas inst_tyvars inst_ty _ _ 
225               dfun_id const_meth_ids _ _ _ src_loc _)
226   = 
227
228 -- We only add specialised/overlapped instances
229 -- if we are specialising the overloading
230 -- ToDo ... This causes getConstMethodId errors!
231 --
232 --    if not (is_plain_instance inst_ty) && not opt_SpecialiseOverloaded
233 --    then
234 --      -- Drop this specialised/overlapped instance
235 --      returnTc (class_inst_env, op_spec_envs)
236 --    else      
237
238         -- Add the instance to the class's instance environment
239     case insertMEnv matchTy class_inst_env inst_ty dfun_id of {
240         Failed (ty', dfun_id')    -> dupInstFailure clas (inst_ty, src_loc) 
241                                                          (ty', getSrcLoc dfun_id');
242         Succeeded class_inst_env' -> 
243
244         -- If there are any constant methods, then add them to 
245         -- the SpecEnv of each class op (ie selector)
246         --
247         -- Example.  class    Foo a     where { op :: Baz b => a -> b; ... }
248         --           instance Foo (p,q) where { op (x,y) = ...       ; ... }
249         --
250         -- The class decl means that 
251         --      op :: forall a. Foo a => forall b. Baz b => a -> b
252         --
253         -- The constant method from the instance decl will be:
254         --      op_Pair :: forall p q b. Baz b => (p,q) -> b
255         --
256         -- What we put in op's SpecEnv is
257         --      (p,q) |-->  (\d::Foo (p,q) -> op_Pair p q)
258         --
259         -- Here, [p,q] are the inst_tyvars, and d is a dict whose only
260         -- purpose is to cancel with the dict to which op is applied.
261         -- 
262         -- NOTE THAT this correctly deals with the case where there are
263         -- constant methods even though there are type variables in the
264         -- instance declaration.
265
266     tcGetUnique                         `thenNF_Tc` \ uniq ->
267     let 
268       dict = mkSysLocal SLIT("dict_tpl") uniq (mkDictTy clas inst_ty) src_loc
269                 -- Slightly disgusting, but it's only a placeholder for
270                 -- a dictionary to be chucked away.
271
272       op_spec_envs' | null const_meth_ids = op_spec_envs
273                     | otherwise           = zipWithEqual "add_const_meth" add_const_meth op_spec_envs const_meth_ids
274
275       add_const_meth (op,spec_env) meth_id
276         = (op, case addOneToSpecEnv spec_env [inst_ty] rhs of
277                  Failed (tys', rhs') -> panic "TcInstDecls:add_const_meth"
278                  Succeeded spec_env' -> spec_env' )
279         where
280           rhs = mkValLam [dict] (mkTyApp (Var meth_id) (mkTyVarTys inst_tyvars))
281     in
282     returnTc (class_inst_env', op_spec_envs')
283     }
284 \end{code}
285
286 \begin{code}
287 dupInstFailure clas info1@(ty1, locn1) info2@(ty2, locn2)
288         -- Overlapping/duplicate instances for given class; msg could be more glamourous
289   = tcAddErrCtxt ctxt $
290     failTc (\sty -> ppStr "Duplicate or overlapping instance declarations")
291   where
292     ctxt sty = ppHang (ppSep [ppBesides[ppStr "Class `", ppr sty clas, ppStr "'"],
293                               ppBesides[ppStr "type `", ppr sty ty1, ppStr "'"]])
294                     4 (ppSep [ppBesides [ppStr "at ", ppr sty locn1],
295                               ppBesides [ppStr "and ", ppr sty locn2]])
296 \end{code}