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