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