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