[project @ 1997-07-05 02:43:52 by sof]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcBinds.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
3 %
4 \section[TcBinds]{TcBinds}
5
6 \begin{code}
7 #include "HsVersions.h"
8
9 module TcBinds ( tcBindsAndThen, tcPragmaSigs, checkSigTyVars, tcBindWithSigs, TcSigInfo(..) ) where
10
11 IMP_Ubiq()
12 #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ <= 201
13 IMPORT_DELOOPER(TcLoop)         ( tcGRHSsAndBinds )
14 #else
15 import {-# SOURCE #-} TcGRHSs ( tcGRHSsAndBinds )
16 #endif
17
18 import HsSyn            ( HsBinds(..), Sig(..), MonoBinds(..), 
19                           Match, HsType, InPat(..), OutPat(..), HsExpr(..),
20                           SYN_IE(RecFlag), nonRecursive,
21                           GRHSsAndBinds, ArithSeqInfo, HsLit, Fake, Stmt, DoOrListComp, Fixity, 
22                           collectMonoBinders )
23 import RnHsSyn          ( SYN_IE(RenamedHsBinds), RenamedSig(..), 
24                           SYN_IE(RenamedMonoBinds)
25                         )
26 import TcHsSyn          ( SYN_IE(TcHsBinds), SYN_IE(TcMonoBinds),
27                           TcIdOcc(..), SYN_IE(TcIdBndr), SYN_IE(TcExpr), 
28                           tcIdType
29                         )
30
31 import TcMonad
32 import Inst             ( Inst, SYN_IE(LIE), emptyLIE, plusLIE, InstOrigin(..),
33                           newDicts, tyVarsOfInst, instToId
34                         )
35 import TcEnv            ( tcExtendLocalValEnv, tcLookupLocalValueOK, newMonoIds,
36                           tcGetGlobalTyVars, tcExtendGlobalTyVars
37                         )
38 import SpecEnv          ( SpecEnv )
39 import TcMatches        ( tcMatchesFun )
40 import TcSimplify       ( tcSimplify, tcSimplifyAndCheck )
41 import TcMonoType       ( tcHsType )
42 import TcPat            ( tcPat )
43 import TcSimplify       ( bindInstsOfLocalFuns )
44 import TcType           ( SYN_IE(TcType), SYN_IE(TcThetaType), SYN_IE(TcTauType), 
45                           SYN_IE(TcTyVarSet), SYN_IE(TcTyVar),
46                           newTyVarTy, zonkTcType, zonkTcTyVar, zonkTcTyVars,
47                           newTcTyVar, tcInstSigType, newTyVarTys
48                         )
49 import Unify            ( unifyTauTy, unifyTauTyLists )
50
51 import Kind             ( isUnboxedTypeKind, mkTypeKind, isTypeKind, mkBoxedTypeKind )
52 import Id               ( GenId, idType, mkUserLocal, mkUserId )
53 import IdInfo           ( noIdInfo )
54 import Maybes           ( maybeToBool, assocMaybe, catMaybes )
55 import Name             ( getOccName, getSrcLoc, Name )
56 import PragmaInfo       ( PragmaInfo(..) )
57 import Pretty
58 import Type             ( mkTyVarTy, mkTyVarTys, isTyVarTy, tyVarsOfTypes, eqSimpleTheta, 
59                           mkSigmaTy, splitSigmaTy, mkForAllTys, mkFunTys, getTyVar, mkDictTy,
60                           splitRhoTy, mkForAllTy, splitForAllTy )
61 import TyVar            ( GenTyVar, SYN_IE(TyVar), tyVarKind, minusTyVarSet, emptyTyVarSet,
62                           elementOfTyVarSet, unionTyVarSets, tyVarSetToList )
63 import Bag              ( bagToList, foldrBag, isEmptyBag )
64 import Util             ( isIn, zipEqual, zipWithEqual, zipWith3Equal, hasNoDups, assoc,
65                           assertPanic, panic, pprTrace )
66 import PprType          ( GenClass, GenType, GenTyVar )
67 import Unique           ( Unique )
68 import SrcLoc           ( SrcLoc )
69
70 import Outputable       --( interppSP, interpp'SP )
71
72
73 \end{code}
74
75
76 %************************************************************************
77 %*                                                                      *
78 \subsection{Type-checking bindings}
79 %*                                                                      *
80 %************************************************************************
81
82 @tcBindsAndThen@ typechecks a @HsBinds@.  The "and then" part is because
83 it needs to know something about the {\em usage} of the things bound,
84 so that it can create specialisations of them.  So @tcBindsAndThen@
85 takes a function which, given an extended environment, E, typechecks
86 the scope of the bindings returning a typechecked thing and (most
87 important) an LIE.  It is this LIE which is then used as the basis for
88 specialising the things bound.
89
90 @tcBindsAndThen@ also takes a "combiner" which glues together the
91 bindings and the "thing" to make a new "thing".
92
93 The real work is done by @tcBindWithSigsAndThen@.
94
95 Recursive and non-recursive binds are handled in essentially the same
96 way: because of uniques there are no scoping issues left.  The only
97 difference is that non-recursive bindings can bind primitive values.
98
99 Even for non-recursive binding groups we add typings for each binder
100 to the LVE for the following reason.  When each individual binding is
101 checked the type of its LHS is unified with that of its RHS; and
102 type-checking the LHS of course requires that the binder is in scope.
103
104 At the top-level the LIE is sure to contain nothing but constant
105 dictionaries, which we resolve at the module level.
106
107 \begin{code}
108 tcBindsAndThen
109         :: (RecFlag -> TcMonoBinds s -> thing -> thing)         -- Combinator
110         -> RenamedHsBinds
111         -> TcM s (thing, LIE s)
112         -> TcM s (thing, LIE s)
113
114 tcBindsAndThen combiner EmptyBinds do_next
115   = do_next     `thenTc` \ (thing, lie) ->
116     returnTc (combiner nonRecursive EmptyMonoBinds thing, lie)
117
118 tcBindsAndThen combiner (ThenBinds binds1 binds2) do_next
119   = tcBindsAndThen combiner binds1 (tcBindsAndThen combiner binds2 do_next)
120
121 tcBindsAndThen combiner (MonoBind bind sigs is_rec) do_next
122   = fixTc (\ ~(prag_info_fn, _) ->
123         -- This is the usual prag_info fix; the PragmaInfo field of an Id
124         -- is not inspected till ages later in the compiler, so there
125         -- should be no black-hole problems here.
126
127         -- TYPECHECK THE SIGNATURES
128     mapTc (tcTySig prag_info_fn) ty_sigs                `thenTc` \ tc_ty_sigs ->
129
130     tcBindWithSigs binder_names bind 
131                    tc_ty_sigs is_rec prag_info_fn       `thenTc` \ (poly_binds, poly_lie, poly_ids) ->
132
133         -- Extend the environment to bind the new polymorphic Ids
134     tcExtendLocalValEnv binder_names poly_ids $
135
136         -- Build bindings and IdInfos corresponding to user pragmas
137     tcPragmaSigs sigs                   `thenTc` \ (prag_info_fn, prag_binds, prag_lie) ->
138
139         -- Now do whatever happens next, in the augmented envt
140     do_next                             `thenTc` \ (thing, thing_lie) ->
141
142         -- Create specialisations of functions bound here
143     bindInstsOfLocalFuns (prag_lie `plusLIE` thing_lie)
144                           poly_ids      `thenTc` \ (lie2, inst_mbinds) ->
145
146         -- All done
147     let
148         final_lie   = lie2 `plusLIE` poly_lie
149         final_thing = combiner is_rec poly_binds $
150                       combiner nonRecursive inst_mbinds $
151                       combiner nonRecursive prag_binds 
152                       thing
153     in
154     returnTc (prag_info_fn, (final_thing, final_lie))
155     )                                   `thenTc` \ (_, result) ->
156     returnTc result
157   where
158     binder_names = map fst (bagToList (collectMonoBinders bind))
159     ty_sigs      = [sig  | sig@(Sig name _ _) <- sigs]
160 \end{code}
161
162 An aside.  The original version of @tcBindsAndThen@ which lacks a
163 combiner function, appears below.  Though it is perfectly well
164 behaved, it cannot be typed by Haskell, because the recursive call is
165 at a different type to the definition itself.  There aren't too many
166 examples of this, which is why I thought it worth preserving! [SLPJ]
167
168 \begin{pseudocode}
169 tcBindsAndThen
170         :: RenamedHsBinds
171         -> TcM s (thing, LIE s, thing_ty))
172         -> TcM s ((TcHsBinds s, thing), LIE s, thing_ty)
173
174 tcBindsAndThen EmptyBinds do_next
175   = do_next             `thenTc` \ (thing, lie, thing_ty) ->
176     returnTc ((EmptyBinds, thing), lie, thing_ty)
177
178 tcBindsAndThen (ThenBinds binds1 binds2) do_next
179   = tcBindsAndThen binds1 (tcBindsAndThen binds2 do_next)
180         `thenTc` \ ((binds1', (binds2', thing')), lie1, thing_ty) ->
181
182     returnTc ((binds1' `ThenBinds` binds2', thing'), lie1, thing_ty)
183
184 tcBindsAndThen (MonoBind bind sigs is_rec) do_next
185   = tcBindAndThen bind sigs do_next
186 \end{pseudocode}
187
188
189 %************************************************************************
190 %*                                                                      *
191 \subsection{tcBindWithSigs}
192 %*                                                                      *
193 %************************************************************************
194
195 @tcBindWithSigs@ deals with a single binding group.  It does generalisation,
196 so all the clever stuff is in here.
197
198 * binder_names and mbind must define the same set of Names
199
200 * The Names in tc_ty_sigs must be a subset of binder_names
201
202 * The Ids in tc_ty_sigs don't necessarily have to have the same name
203   as the Name in the tc_ty_sig
204
205 \begin{code}
206 tcBindWithSigs  
207         :: [Name]
208         -> RenamedMonoBinds
209         -> [TcSigInfo s]
210         -> RecFlag
211         -> (Name -> PragmaInfo)
212         -> TcM s (TcMonoBinds s, LIE s, [TcIdBndr s])
213
214 tcBindWithSigs binder_names mbind tc_ty_sigs is_rec prag_info_fn
215   = recoverTc (
216         -- If typechecking the binds fails, then return with each
217         -- signature-less binder given type (forall a.a), to minimise subsequent
218         -- error messages
219         newTcTyVar mkBoxedTypeKind              `thenNF_Tc` \ alpha_tv ->
220         let
221           forall_a_a = mkForAllTy alpha_tv (mkTyVarTy alpha_tv)
222           poly_ids   = map mk_dummy binder_names
223           mk_dummy name = case maybeSig tc_ty_sigs name of
224                             Just (TySigInfo _ poly_id _ _ _ _) -> poly_id       -- Signature
225                             Nothing -> mkUserId name forall_a_a NoPragmaInfo    -- No signature
226         in
227         returnTc (EmptyMonoBinds, emptyLIE, poly_ids)
228     ) $
229
230         -- Create a new identifier for each binder, with each being given
231         -- a fresh unique, and a type-variable type.
232     tcGetUniques no_of_binders                  `thenNF_Tc` \ uniqs ->
233     mapNF_Tc mk_mono_id_ty binder_names         `thenNF_Tc` \ mono_id_tys ->
234     let
235         mono_id_tyvars     = tyVarsOfTypes mono_id_tys
236         mono_ids           = zipWith3Equal "tcBindAndSigs" mk_id binder_names uniqs mono_id_tys
237         mk_id name uniq ty = mkUserLocal (getOccName name) uniq ty (getSrcLoc name)
238     in
239
240         -- TYPECHECK THE BINDINGS
241     tcMonoBinds mbind binder_names mono_ids tc_ty_sigs  `thenTc` \ (mbind', lie) ->
242
243         -- CHECK THAT THE SIGNATURES MATCH
244         -- (must do this before getTyVarsToGen)
245     checkSigMatch tc_ty_sigs                            `thenTc` \ sig_theta ->
246         
247         -- COMPUTE VARIABLES OVER WHICH TO QUANTIFY, namely tyvars_to_gen
248         -- The tyvars_not_to_gen are free in the environment, and hence
249         -- candidates for generalisation, but sometimes the monomorphism
250         -- restriction means we can't generalise them nevertheless
251     getTyVarsToGen is_unrestricted mono_id_tyvars lie   `thenTc` \ (tyvars_not_to_gen, tyvars_to_gen) ->
252
253         -- DEAL WITH TYPE VARIABLE KINDS
254     mapTc defaultUncommittedTyVar (tyVarSetToList tyvars_to_gen)        `thenTc` \ tyvars_to_gen_list ->
255                 -- It's important that the final list (tyvars_to_gen_list) is fully
256                 -- zonked, *including boxity*, because they'll be included in the forall types of
257                 -- the polymorphic Ids, and instances of these Ids will be generated from them.
258                 --
259                 -- This step can do unification => keep other zonking after this
260
261         -- SIMPLIFY THE LIE
262     tcExtendGlobalTyVars tyvars_not_to_gen (
263         if null tc_ty_sigs then
264                 -- No signatures, so just simplify the lie
265             tcSimplify tyvars_to_gen lie                `thenTc` \ (lie_free, dict_binds, lie_bound) ->
266             returnTc (lie_free, dict_binds, map instToId (bagToList lie_bound))
267
268         else
269             zonk_theta sig_theta                        `thenNF_Tc` \ sig_theta' ->
270             newDicts SignatureOrigin sig_theta'         `thenNF_Tc` \ (dicts_sig, dict_ids) ->
271                 -- It's important that sig_theta is zonked, because
272                 -- dict_id is later used to form the type of the polymorphic thing,
273                 -- and forall-types must be zonked so far as their bound variables
274                 -- are concerned
275
276                 -- Check that the needed dicts can be expressed in
277                 -- terms of the signature ones
278             tcAddErrCtxt (sigsCtxt tysig_names) $
279             tcSimplifyAndCheck tyvars_to_gen dicts_sig lie      `thenTc` \ (lie_free, dict_binds) ->
280             returnTc (lie_free, dict_binds, dict_ids)
281
282     )                                           `thenTc` \ (lie_free, dict_binds, dicts_bound) ->
283
284     ASSERT( not (any (isUnboxedTypeKind . tyVarKind) tyvars_to_gen_list) )
285                 -- The instCantBeGeneralised stuff in tcSimplify should have
286                 -- already raised an error if we're trying to generalise an unboxed tyvar
287                 -- (NB: unboxed tyvars are always introduced along with a class constraint)
288                 -- and it's better done there because we have more precise origin information.
289                 -- That's why we just use an ASSERT here.
290
291          -- BUILD THE POLYMORPHIC RESULT IDs
292     mapNF_Tc zonkTcType mono_id_tys                     `thenNF_Tc` \ zonked_mono_id_types ->
293     let
294         exports  = zipWith3 mk_export binder_names mono_ids zonked_mono_id_types
295         dict_tys = map tcIdType dicts_bound
296
297         mk_export binder_name mono_id zonked_mono_id_ty
298           | maybeToBool maybe_sig = (sig_tyvars,         TcId sig_poly_id, TcId mono_id)
299           | otherwise             = (tyvars_to_gen_list, TcId poly_id,     TcId mono_id)
300           where
301             maybe_sig = maybeSig tc_ty_sigs binder_name
302             Just (TySigInfo _ sig_poly_id sig_tyvars _ _ _) = maybe_sig
303             poly_id = mkUserId binder_name poly_ty (prag_info_fn binder_name)
304             poly_ty = mkForAllTys tyvars_to_gen_list $ mkFunTys dict_tys $ zonked_mono_id_ty
305                                 -- It's important to build a fully-zonked poly_ty, because
306                                 -- we'll slurp out its free type variables when extending the
307                                 -- local environment (tcExtendLocalValEnv); if it's not zonked
308                                 -- it appears to have free tyvars that aren't actually free at all.
309     in
310
311          -- BUILD RESULTS
312     returnTc (
313          AbsBinds tyvars_to_gen_list
314                   dicts_bound
315                   exports
316                   (dict_binds `AndMonoBinds` mbind'),
317          lie_free,
318          [poly_id | (_, TcId poly_id, _) <- exports]
319     )
320   where
321     no_of_binders = length binder_names
322
323     mk_mono_id_ty binder_name = case maybeSig tc_ty_sigs binder_name of
324                                   Just (TySigInfo name _ _ _ tau_ty _) -> returnNF_Tc tau_ty -- There's a signature
325                                   otherwise                            -> newTyVarTy kind    -- No signature
326
327     tysig_names     = [name | (TySigInfo name _ _ _ _ _) <- tc_ty_sigs]
328     is_unrestricted = isUnRestrictedGroup tysig_names mbind
329
330     kind | is_rec    = mkBoxedTypeKind  -- Recursive, so no unboxed types
331          | otherwise = mkTypeKind               -- Non-recursive, so we permit unboxed types
332
333 zonk_theta theta = mapNF_Tc zonk theta
334         where
335           zonk (c,t) = zonkTcType t     `thenNF_Tc` \ t' ->
336                        returnNF_Tc (c,t')
337 \end{code}
338
339 @getImplicitStuffToGen@ decides what type variables generalise over.
340
341 For a "restricted group" -- see the monomorphism restriction
342 for a definition -- we bind no dictionaries, and
343 remove from tyvars_to_gen any constrained type variables
344
345 *Don't* simplify dicts at this point, because we aren't going
346 to generalise over these dicts.  By the time we do simplify them
347 we may well know more.  For example (this actually came up)
348         f :: Array Int Int
349         f x = array ... xs where xs = [1,2,3,4,5]
350 We don't want to generate lots of (fromInt Int 1), (fromInt Int 2)
351 stuff.  If we simplify only at the f-binding (not the xs-binding)
352 we'll know that the literals are all Ints, and we can just produce
353 Int literals!
354
355 Find all the type variables involved in overloading, the
356 "constrained_tyvars".  These are the ones we *aren't* going to
357 generalise.  We must be careful about doing this:
358
359  (a) If we fail to generalise a tyvar which is not actually
360         constrained, then it will never, ever get bound, and lands
361         up printed out in interface files!  Notorious example:
362                 instance Eq a => Eq (Foo a b) where ..
363         Here, b is not constrained, even though it looks as if it is.
364         Another, more common, example is when there's a Method inst in
365         the LIE, whose type might very well involve non-overloaded
366         type variables.
367
368  (b) On the other hand, we mustn't generalise tyvars which are constrained,
369         because we are going to pass on out the unmodified LIE, with those
370         tyvars in it.  They won't be in scope if we've generalised them.
371
372 So we are careful, and do a complete simplification just to find the
373 constrained tyvars. We don't use any of the results, except to
374 find which tyvars are constrained.
375
376 \begin{code}
377 getTyVarsToGen is_unrestricted mono_tyvars lie
378   = tcGetGlobalTyVars                           `thenNF_Tc` \ free_tyvars ->
379     zonkTcTyVars mono_tyvars                    `thenNF_Tc` \ mentioned_tyvars ->
380     let
381         tyvars_to_gen    = mentioned_tyvars `minusTyVarSet` free_tyvars
382     in
383     if is_unrestricted
384     then
385         returnTc (emptyTyVarSet, tyvars_to_gen)
386     else
387         tcSimplify tyvars_to_gen lie        `thenTc` \ (_, _, constrained_dicts) ->
388         let
389           -- ASSERT: dicts_sig is already zonked!
390             constrained_tyvars    = foldrBag (unionTyVarSets . tyVarsOfInst) emptyTyVarSet constrained_dicts
391             reduced_tyvars_to_gen = tyvars_to_gen `minusTyVarSet` constrained_tyvars
392         in
393         returnTc (constrained_tyvars, reduced_tyvars_to_gen)
394 \end{code}
395
396
397 \begin{code}
398 isUnRestrictedGroup :: [Name]           -- Signatures given for these
399                     -> RenamedMonoBinds
400                     -> Bool
401
402 is_elem v vs = isIn "isUnResMono" v vs
403
404 isUnRestrictedGroup sigs (PatMonoBind (VarPatIn v) _ _) = v `is_elem` sigs
405 isUnRestrictedGroup sigs (PatMonoBind other      _ _)   = False
406 isUnRestrictedGroup sigs (VarMonoBind v _)              = v `is_elem` sigs
407 isUnRestrictedGroup sigs (FunMonoBind _ _ _ _)          = True
408 isUnRestrictedGroup sigs (AndMonoBinds mb1 mb2)         = isUnRestrictedGroup sigs mb1 &&
409                                                           isUnRestrictedGroup sigs mb2
410 isUnRestrictedGroup sigs EmptyMonoBinds                 = True
411 \end{code}
412
413 @defaultUncommittedTyVar@ checks for generalisation over unboxed
414 types, and defaults any TypeKind TyVars to BoxedTypeKind.
415
416 \begin{code}
417 defaultUncommittedTyVar tyvar
418   | isTypeKind (tyVarKind tyvar)
419   = newTcTyVar mkBoxedTypeKind                                  `thenNF_Tc` \ boxed_tyvar ->
420     unifyTauTy (mkTyVarTy boxed_tyvar) (mkTyVarTy tyvar)        `thenTc_`
421     returnTc boxed_tyvar
422
423   | otherwise
424   = returnTc tyvar
425 \end{code}
426
427
428 %************************************************************************
429 %*                                                                      *
430 \subsection{tcMonoBind}
431 %*                                                                      *
432 %************************************************************************
433
434 @tcMonoBinds@ deals with a single @MonoBind@.  
435 The signatures have been dealt with already.
436
437 \begin{code}
438 tcMonoBinds :: RenamedMonoBinds 
439             -> [Name] -> [TcIdBndr s]
440             -> [TcSigInfo s]
441             -> TcM s (TcMonoBinds s, LIE s)
442
443 tcMonoBinds mbind binder_names mono_ids tc_ty_sigs
444   = tcExtendLocalValEnv binder_names mono_ids (
445         tc_mono_binds mbind
446     )
447   where
448     sig_names = [name | (TySigInfo name _ _ _ _ _) <- tc_ty_sigs]
449     sig_ids   = [id   | (TySigInfo _   id _ _ _ _) <- tc_ty_sigs]
450
451     tc_mono_binds EmptyMonoBinds = returnTc (EmptyMonoBinds, emptyLIE)
452
453     tc_mono_binds (AndMonoBinds mb1 mb2)
454       = tc_mono_binds mb1               `thenTc` \ (mb1a, lie1) ->
455         tc_mono_binds mb2               `thenTc` \ (mb2a, lie2) ->
456         returnTc (AndMonoBinds mb1a mb2a, lie1 `plusLIE` lie2)
457
458     tc_mono_binds (FunMonoBind name inf matches locn)
459       = tcAddSrcLoc locn                                $
460         tcLookupLocalValueOK "tc_mono_binds" name       `thenNF_Tc` \ id ->
461
462                 -- Before checking the RHS, extend the envt with
463                 -- bindings for the *polymorphic* Ids from any type signatures
464         tcExtendLocalValEnv sig_names sig_ids           $
465         tcMatchesFun name (idType id) matches           `thenTc` \ (matches', lie) ->
466
467         returnTc (FunMonoBind (TcId id) inf matches' locn, lie)
468
469     tc_mono_binds bind@(PatMonoBind pat grhss_and_binds locn)
470       = tcAddSrcLoc locn                        $
471         tcPat pat                               `thenTc` \ (pat2, lie_pat, pat_ty) ->
472         tcExtendLocalValEnv sig_names sig_ids   $
473         tcGRHSsAndBinds grhss_and_binds         `thenTc` \ (grhss_and_binds2, lie, grhss_ty) ->
474         tcAddErrCtxt (patMonoBindsCtxt bind)    $
475         unifyTauTy pat_ty grhss_ty              `thenTc_`
476         returnTc (PatMonoBind pat2 grhss_and_binds2 locn,
477                   plusLIE lie_pat lie)
478 \end{code}
479
480 %************************************************************************
481 %*                                                                      *
482 \subsection{Signatures}
483 %*                                                                      *
484 %************************************************************************
485
486 @tcSigs@ checks the signatures for validity, and returns a list of
487 {\em freshly-instantiated} signatures.  That is, the types are already
488 split up, and have fresh type variables installed.  All non-type-signature
489 "RenamedSigs" are ignored.
490
491 The @TcSigInfo@ contains @TcTypes@ because they are unified with
492 the variable's type, and after that checked to see whether they've
493 been instantiated.
494
495 \begin{code}
496 data TcSigInfo s
497   = TySigInfo       
498         Name                    -- N, the Name in corresponding binding
499         (TcIdBndr s)            -- *Polymorphic* binder for this value...
500                                 -- Usually has name = N, but doesn't have to.
501         [TcTyVar s]
502         (TcThetaType s)
503         (TcTauType s)
504         SrcLoc
505
506
507 maybeSig :: [TcSigInfo s] -> Name -> Maybe (TcSigInfo s)
508         -- Search for a particular signature
509 maybeSig [] name = Nothing
510 maybeSig (sig@(TySigInfo sig_name _ _ _ _ _) : sigs) name
511   | name == sig_name = Just sig
512   | otherwise        = maybeSig sigs name
513 \end{code}
514
515
516 \begin{code}
517 tcTySig :: (Name -> PragmaInfo)
518         -> RenamedSig
519         -> TcM s (TcSigInfo s)
520
521 tcTySig prag_info_fn (Sig v ty src_loc)
522  = tcAddSrcLoc src_loc $
523    tcHsType ty                  `thenTc` \ sigma_ty ->
524    tcInstSigType sigma_ty       `thenNF_Tc` \ sigma_ty' ->
525    let
526      poly_id = mkUserId v sigma_ty' (prag_info_fn v)
527      (tyvars', theta', tau') = splitSigmaTy sigma_ty'
528         -- This splitSigmaTy tries hard to make sure that tau' is a type synonym
529         -- wherever possible, which can improve interface files.
530    in
531    returnTc (TySigInfo v poly_id tyvars' theta' tau' src_loc)
532 \end{code}
533
534 @checkSigMatch@ does the next step in checking signature matching.
535 The tau-type part has already been unified.  What we do here is to
536 check that this unification has not over-constrained the (polymorphic)
537 type variables of the original signature type.
538
539 The error message here is somewhat unsatisfactory, but it'll do for
540 now (ToDo).
541
542 \begin{code}
543 checkSigMatch []
544   = returnTc (error "checkSigMatch")
545
546 checkSigMatch tc_ty_sigs@( sig1@(TySigInfo _ id1 _ theta1 _ _) : all_sigs_but_first )
547   =     -- CHECK THAT THE SIGNATURE TYVARS AND TAU_TYPES ARE OK
548         -- Doesn't affect substitution
549     mapTc check_one_sig tc_ty_sigs      `thenTc_`
550
551         -- CHECK THAT ALL THE SIGNATURE CONTEXTS ARE UNIFIABLE
552         -- The type signatures on a mutually-recursive group of definitions
553         -- must all have the same context (or none).
554         --
555         -- We unify them because, with polymorphic recursion, their types
556         -- might not otherwise be related.  This is a rather subtle issue.
557         -- ToDo: amplify
558     mapTc check_one_cxt all_sigs_but_first              `thenTc_`
559
560     returnTc theta1
561   where
562     sig1_dict_tys       = mk_dict_tys theta1
563     n_sig1_dict_tys     = length sig1_dict_tys
564
565     check_one_cxt sig@(TySigInfo _ id _  theta _ src_loc)
566        = tcAddSrcLoc src_loc    $
567          tcAddErrCtxt (sigContextsCtxt id1 id) $
568          checkTc (length this_sig_dict_tys == n_sig1_dict_tys)
569                                 sigContextsErr          `thenTc_`
570          unifyTauTyLists sig1_dict_tys this_sig_dict_tys
571       where
572          this_sig_dict_tys = mk_dict_tys theta
573
574     check_one_sig (TySigInfo name id sig_tyvars _ sig_tau src_loc)
575       = tcAddSrcLoc src_loc     $
576         tcAddErrCtxt (sigCtxt id) $
577         checkSigTyVars sig_tyvars sig_tau
578
579     mk_dict_tys theta = [mkDictTy c t | (c,t) <- theta]
580 \end{code}
581
582
583 @checkSigTyVars@ is used after the type in a type signature has been unified with
584 the actual type found.  It then checks that the type variables of the type signature
585 are
586         (a) still all type variables
587                 eg matching signature [a] against inferred type [(p,q)]
588                 [then a will be unified to a non-type variable]
589
590         (b) still all distinct
591                 eg matching signature [(a,b)] against inferred type [(p,p)]
592                 [then a and b will be unified together]
593
594 BUT ACTUALLY THESE FIRST TWO ARE FORCED BY USING DontBind TYVARS
595
596         (c) not mentioned in the environment
597                 eg the signature for f in this:
598
599                         g x = ... where
600                                         f :: a->[a]
601                                         f y = [x,y]
602
603                 Here, f is forced to be monorphic by the free occurence of x.
604
605 Before doing this, the substitution is applied to the signature type variable.
606
607 \begin{code}
608 checkSigTyVars :: [TcTyVar s]           -- The original signature type variables
609                -> TcType s              -- signature type (for err msg)
610                -> TcM s ()
611
612 checkSigTyVars sig_tyvars sig_tau
613   = tcGetGlobalTyVars                   `thenNF_Tc` \ globals ->
614     let
615         mono_tyvars = filter (`elementOfTyVarSet` globals) sig_tyvars
616     in
617         -- TEMPORARY FIX
618         -- Until the final Bind-handling stuff is in, several type signatures in the same
619         -- bindings group can cause the signature type variable from the different
620         -- signatures to be unified.  So we still need to zonk and check point (b).
621         -- Remove when activating the new binding code
622     mapNF_Tc zonkTcTyVar sig_tyvars     `thenNF_Tc` \ sig_tys ->
623     checkTcM (hasNoDups (map (getTyVar "checkSigTyVars") sig_tys))
624              (zonkTcType sig_tau        `thenNF_Tc` \ sig_tau' ->
625               failTc (badMatchErr sig_tau sig_tau')
626              )                          `thenTc_`
627
628
629         -- Check point (c)
630         -- We want to report errors in terms of the original signature tyvars,
631         -- ie sig_tyvars, NOT sig_tyvars'.  sig_tys and sig_tyvars' correspond
632         -- 1-1 with sig_tyvars, so we can just map back.
633     checkTc (null mono_tyvars)
634             (notAsPolyAsSigErr sig_tau mono_tyvars)
635 \end{code}
636
637
638 %************************************************************************
639 %*                                                                      *
640 \subsection{SPECIALIZE pragmas}
641 %*                                                                      *
642 %************************************************************************
643
644
645 @tcPragmaSigs@ munches up the "signatures" that arise through *user*
646 pragmas.  It is convenient for them to appear in the @[RenamedSig]@
647 part of a binding because then the same machinery can be used for
648 moving them into place as is done for type signatures.
649
650 \begin{code}
651 tcPragmaSigs :: [RenamedSig]                    -- The pragma signatures
652              -> TcM s (Name -> PragmaInfo,      -- Maps name to the appropriate PragmaInfo
653                        TcMonoBinds s,
654                        LIE s)
655
656 -- For now we just deal with INLINE pragmas
657 tcPragmaSigs sigs = returnTc (prag_fn, EmptyMonoBinds, emptyLIE )
658   where
659     prag_fn name | any has_inline sigs = IWantToBeINLINEd
660                  | otherwise           = NoPragmaInfo
661                  where
662                     has_inline (InlineSig n _) = (n == name)
663                     has_inline other           = False
664                 
665
666 {- 
667 tcPragmaSigs sigs
668   = mapAndUnzip3Tc tcPragmaSig sigs     `thenTc` \ (names_w_id_infos, binds, lies) ->
669     let
670         name_to_info name = foldr ($) noIdInfo
671                                   [info_fn | (n,info_fn) <- names_w_id_infos, n==name]
672     in
673     returnTc (name_to_info,
674               foldr ThenBinds EmptyBinds binds,
675               foldr plusLIE emptyLIE lies)
676 \end{code}
677
678 Here are the easy cases for tcPragmaSigs
679
680 \begin{code}
681 tcPragmaSig (DeforestSig name loc)
682   = returnTc ((name, addDeforestInfo DoDeforest),EmptyBinds,emptyLIE)
683 tcPragmaSig (InlineSig name loc)
684   = returnTc ((name, addUnfoldInfo (iWantToBeINLINEd UnfoldAlways)), EmptyBinds, emptyLIE)
685 tcPragmaSig (MagicUnfoldingSig name string loc)
686   = returnTc ((name, addUnfoldInfo (mkMagicUnfolding string)), EmptyBinds, emptyLIE)
687 \end{code}
688
689 The interesting case is for SPECIALISE pragmas.  There are two forms.
690 Here's the first form:
691 \begin{verbatim}
692         f :: Ord a => [a] -> b -> b
693         {-# SPECIALIZE f :: [Int] -> b -> b #-}
694 \end{verbatim}
695
696 For this we generate:
697 \begin{verbatim}
698         f* = /\ b -> let d1 = ...
699                      in f Int b d1
700 \end{verbatim}
701
702 where f* is a SpecPragmaId.  The **sole** purpose of SpecPragmaIds is to
703 retain a right-hand-side that the simplifier will otherwise discard as
704 dead code... the simplifier has a flag that tells it not to discard
705 SpecPragmaId bindings.
706
707 In this case the f* retains a call-instance of the overloaded
708 function, f, (including appropriate dictionaries) so that the
709 specialiser will subsequently discover that there's a call of @f@ at
710 Int, and will create a specialisation for @f@.  After that, the
711 binding for @f*@ can be discarded.
712
713 The second form is this:
714 \begin{verbatim}
715         f :: Ord a => [a] -> b -> b
716         {-# SPECIALIZE f :: [Int] -> b -> b = g #-}
717 \end{verbatim}
718
719 Here @g@ is specified as a function that implements the specialised
720 version of @f@.  Suppose that g has type (a->b->b); that is, g's type
721 is more general than that required.  For this we generate
722 \begin{verbatim}
723         f@Int = /\b -> g Int b
724         f* = f@Int
725 \end{verbatim}
726
727 Here @f@@Int@ is a SpecId, the specialised version of @f@.  It inherits
728 f's export status etc.  @f*@ is a SpecPragmaId, as before, which just serves
729 to prevent @f@@Int@ from being discarded prematurely.  After specialisation,
730 if @f@@Int@ is going to be used at all it will be used explicitly, so the simplifier can
731 discard the f* binding.
732
733 Actually, there is really only point in giving a SPECIALISE pragma on exported things,
734 and the simplifer won't discard SpecIds for exporte things anyway, so maybe this is
735 a bit of overkill.
736
737 \begin{code}
738 tcPragmaSig (SpecSig name poly_ty maybe_spec_name src_loc)
739   = tcAddSrcLoc src_loc                         $
740     tcAddErrCtxt (valSpecSigCtxt name spec_ty)  $
741
742         -- Get and instantiate its alleged specialised type
743     tcHsType poly_ty                            `thenTc` \ sig_sigma ->
744     tcInstSigType  sig_sigma                    `thenNF_Tc` \ sig_ty ->
745     let
746         (sig_tyvars, sig_theta, sig_tau) = splitSigmaTy sig_ty
747         origin = ValSpecOrigin name
748     in
749
750         -- Check that the SPECIALIZE pragma had an empty context
751     checkTc (null sig_theta)
752             (panic "SPECIALIZE non-empty context (ToDo: msg)") `thenTc_`
753
754         -- Get and instantiate the type of the id mentioned
755     tcLookupLocalValueOK "tcPragmaSig" name     `thenNF_Tc` \ main_id ->
756     tcInstSigType [] (idType main_id)           `thenNF_Tc` \ main_ty ->
757     let
758         (main_tyvars, main_rho) = splitForAllTy main_ty
759         (main_theta,main_tau)   = splitRhoTy main_rho
760         main_arg_tys            = mkTyVarTys main_tyvars
761     in
762
763         -- Check that the specialised type is indeed an instance of
764         -- the type of the main function.
765     unifyTauTy sig_tau main_tau         `thenTc_`
766     checkSigTyVars sig_tyvars sig_tau   `thenTc_`
767
768         -- Check that the type variables of the polymorphic function are
769         -- either left polymorphic, or instantiate to ground type.
770         -- Also check that the overloaded type variables are instantiated to
771         -- ground type; or equivalently that all dictionaries have ground type
772     mapTc zonkTcType main_arg_tys       `thenNF_Tc` \ main_arg_tys' ->
773     zonkTcThetaType main_theta          `thenNF_Tc` \ main_theta' ->
774     tcAddErrCtxt (specGroundnessCtxt main_arg_tys')
775               (checkTc (all isGroundOrTyVarTy main_arg_tys'))           `thenTc_`
776     tcAddErrCtxt (specContextGroundnessCtxt main_theta')
777               (checkTc (and [isGroundTy ty | (_,ty) <- theta']))        `thenTc_`
778
779         -- Build the SpecPragmaId; it is the thing that makes sure we
780         -- don't prematurely dead-code-eliminate the binding we are really interested in.
781     newSpecPragmaId name sig_ty         `thenNF_Tc` \ spec_pragma_id ->
782
783         -- Build a suitable binding; depending on whether we were given
784         -- a value (Maybe Name) to be used as the specialisation.
785     case using of
786       Nothing ->                -- No implementation function specified
787
788                 -- Make a Method inst for the occurrence of the overloaded function
789         newMethodWithGivenTy (OccurrenceOf name)
790                   (TcId main_id) main_arg_tys main_rho  `thenNF_Tc` \ (lie, meth_id) ->
791
792         let
793             pseudo_bind = VarMonoBind spec_pragma_id pseudo_rhs
794             pseudo_rhs  = mkHsTyLam sig_tyvars (HsVar (TcId meth_id))
795         in
796         returnTc (pseudo_bind, lie, \ info -> info)
797
798       Just spec_name ->         -- Use spec_name as the specialisation value ...
799
800                 -- Type check a simple occurrence of the specialised Id
801         tcId spec_name          `thenTc` \ (spec_body, spec_lie, spec_tau) ->
802
803                 -- Check that it has the correct type, and doesn't constrain the
804                 -- signature variables at all
805         unifyTauTy sig_tau spec_tau             `thenTc_`
806         checkSigTyVars sig_tyvars sig_tau       `thenTc_`
807
808             -- Make a local SpecId to bind to applied spec_id
809         newSpecId main_id main_arg_tys sig_ty   `thenNF_Tc` \ local_spec_id ->
810
811         let
812             spec_rhs   = mkHsTyLam sig_tyvars spec_body
813             spec_binds = VarMonoBind local_spec_id spec_rhs
814                            `AndMonoBinds`
815                          VarMonoBind spec_pragma_id (HsVar (TcId local_spec_id))
816             spec_info  = SpecInfo spec_tys (length main_theta) local_spec_id
817         in
818         returnTc ((name, addSpecInfo spec_info), spec_binds, spec_lie)
819 -}
820 \end{code}
821
822
823 %************************************************************************
824 %*                                                                      *
825 \subsection[TcBinds-errors]{Error contexts and messages}
826 %*                                                                      *
827 %************************************************************************
828
829
830 \begin{code}
831 patMonoBindsCtxt bind sty
832   = hang (ptext SLIT("In a pattern binding:")) 4 (ppr sty bind)
833
834 -----------------------------------------------
835 valSpecSigCtxt v ty sty
836   = hang (ptext SLIT("In a SPECIALIZE pragma for a value:"))
837          4 (sep [(<>) (ppr sty v) (ptext SLIT(" ::")),
838                   ppr sty ty])
839
840
841
842 -----------------------------------------------
843 notAsPolyAsSigErr sig_tau mono_tyvars sty
844   = hang (ptext SLIT("A type signature is more polymorphic than the inferred type"))
845         4  (vcat [text "Some type variables in the inferred type can't be forall'd, namely:",
846                       interpp'SP sty mono_tyvars,
847                       ptext SLIT("Possible cause: the RHS mentions something subject to the monomorphism restriction")
848                      ])
849
850 -----------------------------------------------
851 badMatchErr sig_ty inferred_ty sty
852   = hang (ptext SLIT("Type signature doesn't match inferred type"))
853          4 (vcat [hang (ptext SLIT("Signature:")) 4 (ppr sty sig_ty),
854                       hang (ptext SLIT("Inferred :")) 4 (ppr sty inferred_ty)
855            ])
856
857 -----------------------------------------------
858 sigCtxt id sty 
859   = sep [ptext SLIT("When checking signature for"), ppr sty id]
860 sigsCtxt ids sty 
861   = sep [ptext SLIT("When checking signature(s) for:"), interpp'SP sty ids]
862
863 -----------------------------------------------
864 sigContextsErr sty
865   = ptext SLIT("Mismatched contexts")
866 sigContextsCtxt s1 s2 sty
867   = hang (hsep [ptext SLIT("When matching the contexts of the signatures for"), 
868                 ppr sty s1, ptext SLIT("and"), ppr sty s2])
869          4 (ptext SLIT("(the signature contexts in a mutually recursive group should all be identical)"))
870
871 -----------------------------------------------
872 specGroundnessCtxt
873   = panic "specGroundnessCtxt"
874
875 --------------------------------------------
876 specContextGroundnessCtxt -- err_ctxt dicts sty
877   = panic "specContextGroundnessCtxt"
878 {-
879   = hang (
880         sep [hsep [ptext SLIT("In the SPECIALIZE pragma for"), ppr sty name],
881              hcat [ptext SLIT(" specialised to the type"), ppr sty spec_ty],
882              pp_spec_id sty,
883              ptext SLIT("... not all overloaded type variables were instantiated"),
884              ptext SLIT("to ground types:")])
885       4 (vcat [hsep [ppr sty c, ppr sty t]
886                   | (c,t) <- map getDictClassAndType dicts])
887   where
888     (name, spec_ty, locn, pp_spec_id)
889       = case err_ctxt of
890           ValSpecSigCtxt    n ty loc      -> (n, ty, loc, \ x -> empty)
891           ValSpecSpecIdCtxt n ty spec loc ->
892             (n, ty, loc,
893              \ sty -> hsep [ptext SLIT("... type of explicit id"), ppr sty spec])
894 -}
895 \end{code}
896
897
898
899