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