[project @ 1998-12-18 17:40:31 by simonpj]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcBinds.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[TcBinds]{TcBinds}
5
6 \begin{code}
7 module TcBinds ( tcBindsAndThen, tcTopBindsAndThen,
8                  tcPragmaSigs, tcBindWithSigs ) where
9
10 #include "HsVersions.h"
11
12 import {-# SOURCE #-} TcMatches ( tcGRHSs, tcMatchesFun )
13 import {-# SOURCE #-} TcExpr  ( tcExpr )
14
15 import HsSyn            ( HsExpr(..), HsBinds(..), MonoBinds(..), Sig(..), InPat(..), StmtCtxt(..),
16                           collectMonoBinders, andMonoBindList, andMonoBinds
17                         )
18 import RnHsSyn          ( RenamedHsBinds, RenamedSig, RenamedMonoBinds )
19 import TcHsSyn          ( TcHsBinds, TcMonoBinds, TcId, zonkId )
20
21 import TcMonad
22 import Inst             ( Inst, LIE, emptyLIE, mkLIE, plusLIE, plusLIEs, InstOrigin(..),
23                           newDicts, tyVarsOfInst, instToId,
24                         )
25 import TcEnv            ( tcExtendLocalValEnv,
26                           newSpecPragmaId,
27                           tcGetGlobalTyVars, tcExtendGlobalTyVars
28                         )
29 import TcSimplify       ( tcSimplify, tcSimplifyAndCheck )
30 import TcMonoType       ( tcHsType, checkSigTyVars,
31                           TcSigInfo(..), tcTySig, maybeSig, sigCtxt
32                         )
33 import TcPat            ( tcVarPat, tcPat )
34 import TcSimplify       ( bindInstsOfLocalFuns )
35 import TcType           ( TcType, TcThetaType,
36                           TcTyVar,
37                           newTyVarTy, newTyVar, newTyVarTy_OpenKind, tcInstTcType,
38                           zonkTcType, zonkTcTypes, zonkTcThetaType, zonkTcTyVarToTyVar
39                         )
40 import TcUnify          ( unifyTauTy, unifyTauTyLists )
41
42 import Id               ( mkUserId )
43 import Var              ( idType, idName, setIdInfo )
44 import IdInfo           ( IdInfo, noIdInfo, setInlinePragInfo, InlinePragInfo(..) )
45 import Name             ( Name )
46 import Type             ( mkTyVarTy, tyVarsOfTypes,
47                           splitSigmaTy, mkForAllTys, mkFunTys, getTyVar, 
48                           mkDictTy, splitRhoTy, mkForAllTy, isUnLiftedType, 
49                           isUnboxedType, unboxedTypeKind, boxedTypeKind
50                         )
51 import Var              ( TyVar, tyVarKind )
52 import VarSet
53 import Bag
54 import Util             ( isIn )
55 import BasicTypes       ( TopLevelFlag(..), RecFlag(..) )
56 import SrcLoc           ( SrcLoc )
57 import Outputable
58 \end{code}
59
60
61 %************************************************************************
62 %*                                                                      *
63 \subsection{Type-checking bindings}
64 %*                                                                      *
65 %************************************************************************
66
67 @tcBindsAndThen@ typechecks a @HsBinds@.  The "and then" part is because
68 it needs to know something about the {\em usage} of the things bound,
69 so that it can create specialisations of them.  So @tcBindsAndThen@
70 takes a function which, given an extended environment, E, typechecks
71 the scope of the bindings returning a typechecked thing and (most
72 important) an LIE.  It is this LIE which is then used as the basis for
73 specialising the things bound.
74
75 @tcBindsAndThen@ also takes a "combiner" which glues together the
76 bindings and the "thing" to make a new "thing".
77
78 The real work is done by @tcBindWithSigsAndThen@.
79
80 Recursive and non-recursive binds are handled in essentially the same
81 way: because of uniques there are no scoping issues left.  The only
82 difference is that non-recursive bindings can bind primitive values.
83
84 Even for non-recursive binding groups we add typings for each binder
85 to the LVE for the following reason.  When each individual binding is
86 checked the type of its LHS is unified with that of its RHS; and
87 type-checking the LHS of course requires that the binder is in scope.
88
89 At the top-level the LIE is sure to contain nothing but constant
90 dictionaries, which we resolve at the module level.
91
92 \begin{code}
93 tcTopBindsAndThen, tcBindsAndThen
94         :: (RecFlag -> TcMonoBinds -> thing -> thing)           -- Combinator
95         -> RenamedHsBinds
96         -> TcM s (thing, LIE)
97         -> TcM s (thing, LIE)
98
99 tcTopBindsAndThen = tc_binds_and_then TopLevel
100 tcBindsAndThen    = tc_binds_and_then NotTopLevel
101
102 tc_binds_and_then top_lvl combiner EmptyBinds do_next
103   = do_next
104 tc_binds_and_then top_lvl combiner (MonoBind EmptyMonoBinds sigs is_rec) do_next
105   = do_next
106
107 tc_binds_and_then top_lvl combiner (ThenBinds b1 b2) do_next
108   = tc_binds_and_then top_lvl combiner b1       $
109     tc_binds_and_then top_lvl combiner b2       $
110     do_next
111
112 tc_binds_and_then top_lvl combiner (MonoBind bind sigs is_rec) do_next
113   = fixTc (\ ~(prag_info_fn, _, _) ->
114         -- This is the usual prag_info fix; the PragmaInfo field of an Id
115         -- is not inspected till ages later in the compiler, so there
116         -- should be no black-hole problems here.
117
118         -- TYPECHECK THE SIGNATURES
119       mapTc tcTySig [sig | sig@(Sig name _ _) <- sigs]  `thenTc` \ tc_ty_sigs ->
120   
121       tcBindWithSigs top_lvl bind 
122                      tc_ty_sigs is_rec prag_info_fn     `thenTc` \ (poly_binds, poly_lie, poly_ids) ->
123   
124           -- Extend the environment to bind the new polymorphic Ids
125       tcExtendLocalValEnv [(idName poly_id, poly_id) | poly_id <- poly_ids] $
126   
127           -- Build bindings and IdInfos corresponding to user pragmas
128       tcPragmaSigs sigs         `thenTc` \ (prag_info_fn, prag_binds, prag_lie) ->
129
130         -- Now do whatever happens next, in the augmented envt
131       do_next                   `thenTc` \ (thing, thing_lie) ->
132
133         -- Create specialisations of functions bound here
134         -- We want to keep non-recursive things non-recursive
135         -- so that we desugar unboxed bindings correctly
136       case (top_lvl, is_rec) of
137
138                 -- For the top level don't bother will all this bindInstsOfLocalFuns stuff
139                 -- All the top level things are rec'd together anyway, so it's fine to
140                 -- leave them to the tcSimplifyTop, and quite a bit faster too
141         (TopLevel, _)
142                 -> returnTc (prag_info_fn, 
143                              combiner Recursive (poly_binds `andMonoBinds` prag_binds) thing,
144                              thing_lie `plusLIE` prag_lie `plusLIE` poly_lie)
145
146         (NotTopLevel, NonRecursive) 
147                 -> bindInstsOfLocalFuns 
148                                 (thing_lie `plusLIE` prag_lie)
149                                 poly_ids                        `thenTc` \ (thing_lie', lie_binds) ->
150
151                    returnTc (
152                         prag_info_fn,
153                         combiner NonRecursive poly_binds $
154                         combiner NonRecursive prag_binds $
155                         combiner Recursive lie_binds  $
156                                 -- NB: the binds returned by tcSimplify and bindInstsOfLocalFuns
157                                 -- aren't guaranteed in dependency order (though we could change
158                                 -- that); hence the Recursive marker.
159                         thing,
160
161                         thing_lie' `plusLIE` poly_lie
162                    )
163
164         (NotTopLevel, Recursive)
165                 -> bindInstsOfLocalFuns 
166                                 (thing_lie `plusLIE` poly_lie `plusLIE` prag_lie) 
167                                 poly_ids                        `thenTc` \ (final_lie, lie_binds) ->
168
169                    returnTc (
170                         prag_info_fn,
171                         combiner Recursive (
172                                 poly_binds `andMonoBinds`
173                                 lie_binds  `andMonoBinds`
174                                 prag_binds) thing,
175                         final_lie
176                   )
177     )                                           `thenTc` \ (_, thing, lie) ->
178     returnTc (thing, lie)
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, thing_ty))
191 %       -> TcM s ((TcHsBinds, thing), LIE, 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         -> RenamedMonoBinds
228         -> [TcSigInfo]
229         -> RecFlag
230         -> (Name -> IdInfo)
231         -> TcM s (TcMonoBinds, LIE, [TcId])
232
233 tcBindWithSigs top_lvl mbind tc_ty_sigs is_rec prag_info_fn
234   = recoverTc (
235         -- If typechecking the binds fails, then return with each
236         -- signature-less binder given type (forall a.a), to minimise subsequent
237         -- error messages
238         newTyVar boxedTypeKind          `thenNF_Tc` \ alpha_tv ->
239         let
240           forall_a_a    = mkForAllTy alpha_tv (mkTyVarTy alpha_tv)
241           binder_names  = map fst (bagToList (collectMonoBinders mbind))
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         -- TYPECHECK THE BINDINGS
251     tcMonoBinds mbind tc_ty_sigs is_rec `thenTc` \ (mbind', lie_req, binder_names, mono_ids) ->
252
253     let
254         mono_id_tys = map idType mono_ids
255     in
256
257         -- CHECK THAT THE SIGNATURES MATCH
258         -- (must do this before getTyVarsToGen)
259     checkSigMatch tc_ty_sigs                            `thenTc` \ (sig_theta, lie_avail) ->    
260
261         -- COMPUTE VARIABLES OVER WHICH TO QUANTIFY, namely tyvars_to_gen
262         -- The tyvars_not_to_gen are free in the environment, and hence
263         -- candidates for generalisation, but sometimes the monomorphism
264         -- restriction means we can't generalise them nevertheless
265     getTyVarsToGen is_unrestricted mono_id_tys lie_req  `thenNF_Tc` \ (tyvars_not_to_gen, tyvars_to_gen) ->
266
267         -- Finally, zonk the generalised type variables to real TyVars
268         -- This commits any unbound kind variables to boxed kind
269         -- I'm a little worried that such a kind variable might be
270         -- free in the environment, but I don't think it's possible for
271         -- this to happen when the type variable is not free in the envt
272         -- (which it isn't).            SLPJ Nov 98
273     mapTc zonkTcTyVarToTyVar (varSetElems tyvars_to_gen)        `thenTc` \ real_tyvars_to_gen_list ->
274     let
275         real_tyvars_to_gen = mkVarSet real_tyvars_to_gen_list
276                 -- It's important that the final list 
277                 -- (real_tyvars_to_gen and real_tyvars_to_gen_list) is fully
278                 -- zonked, *including boxity*, because they'll be included in the forall types of
279                 -- the polymorphic Ids, and instances of these Ids will be generated from them.
280                 -- 
281                 -- Also NB that tcSimplify takes zonked tyvars as its arg, hence we pass
282                 -- real_tyvars_to_gen
283     in
284
285         -- SIMPLIFY THE LIE
286     tcExtendGlobalTyVars tyvars_not_to_gen (
287         if null real_tyvars_to_gen_list then
288                 -- No polymorphism, so no need to simplify context
289             returnTc (lie_req, EmptyMonoBinds, [])
290         else
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 lie_avail (which will be empty anyway)
295             tcSimplify (text "tcBinds1" <+> ppr binder_names)
296                        top_lvl real_tyvars_to_gen lie_req       `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 lie_avail
310                 -- so that polymorphic recursion works right (see comments at end of fn)
311                 givens = dicts_sig `plusLIE` lie_avail
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") <+> pprQuotedList binder_names)
319                 real_tyvars_to_gen givens lie_req       `thenTc` \ (lie_free, dict_binds) ->
320
321             returnTc (lie_free, dict_binds, dict_ids)
322
323     )                                           `thenTc` \ (lie_free, dict_binds, dicts_bound) ->
324
325         -- GET THE FINAL MONO_ID_TYS
326     zonkTcTypes mono_id_tys                     `thenNF_Tc` \ zonked_mono_id_types ->
327
328
329         -- CHECK FOR BOGUS UNPOINTED BINDINGS
330     (if any isUnLiftedType zonked_mono_id_types then
331                 -- Unlifted bindings must be non-recursive,
332                 -- not top level, and non-polymorphic
333         checkTc (case top_lvl of {TopLevel -> False; NotTopLevel -> True})
334                 (unliftedBindErr "Top-level" mbind)             `thenTc_`
335         checkTc (case is_rec of {Recursive -> False; NonRecursive -> True})
336                 (unliftedBindErr "Recursive" mbind)             `thenTc_`
337         checkTc (null real_tyvars_to_gen_list)
338                 (unliftedBindErr "Polymorphic" mbind)
339      else
340         returnTc ()
341     )                                                   `thenTc_`
342
343     ASSERT( not (any ((== unboxedTypeKind) . tyVarKind) real_tyvars_to_gen_list) )
344                 -- The instCantBeGeneralised stuff in tcSimplify should have
345                 -- already raised an error if we're trying to generalise an 
346                 -- unboxed tyvar (NB: unboxed tyvars are always introduced 
347                 -- along with a class constraint) and it's better done there 
348                 -- because we have more precise origin information.
349                 -- That's why we just use an ASSERT here.
350
351
352          -- BUILD THE POLYMORPHIC RESULT IDs
353     mapNF_Tc zonkId mono_ids            `thenNF_Tc` \ zonked_mono_ids ->
354     let
355         exports  = zipWith mk_export binder_names zonked_mono_ids
356         dict_tys = map idType dicts_bound
357
358         mk_export binder_name zonked_mono_id
359           = (tyvars, 
360              setIdInfo poly_id (prag_info_fn binder_name),
361              zonked_mono_id)
362           where
363             (tyvars, poly_id) = 
364                 case maybeSig tc_ty_sigs binder_name of
365                   Just (TySigInfo _ sig_poly_id sig_tyvars _ _ _ _ _) -> 
366                         (sig_tyvars, sig_poly_id)
367                   Nothing -> (real_tyvars_to_gen_list, new_poly_id)
368
369             new_poly_id = mkUserId binder_name poly_ty
370             poly_ty = mkForAllTys real_tyvars_to_gen_list 
371                         $ mkFunTys dict_tys 
372                         $ idType (zonked_mono_id)
373                 -- It's important to build a fully-zonked poly_ty, because
374                 -- we'll slurp out its free type variables when extending the
375                 -- local environment (tcExtendLocalValEnv); if it's not zonked
376                 -- it appears to have free tyvars that aren't actually free 
377                 -- at all.
378         
379         pat_binders :: [Name]
380         pat_binders = map fst $ bagToList $ collectMonoBinders $ 
381                       (justPatBindings mbind EmptyMonoBinds)
382     in
383         -- CHECK FOR UNBOXED BINDERS IN PATTERN BINDINGS
384     mapTc (\id -> checkTc (not (idName id `elem` pat_binders
385                                 && isUnboxedType (idType id)))
386                           (unboxedPatBindErr id)) zonked_mono_ids
387                                 `thenTc_`
388
389          -- BUILD RESULTS
390     returnTc (
391          AbsBinds real_tyvars_to_gen_list
392                   dicts_bound
393                   exports
394                   (dict_binds `andMonoBinds` mbind'),
395          lie_free,
396          [poly_id | (_, poly_id, _) <- exports]
397     )
398   where
399     tysig_names     = [name | (TySigInfo name _ _ _ _ _ _ _) <- tc_ty_sigs]
400     is_unrestricted = isUnRestrictedGroup tysig_names mbind
401
402 justPatBindings bind@(PatMonoBind _ _ _) binds = bind `andMonoBinds` binds
403 justPatBindings (AndMonoBinds b1 b2) binds = 
404         justPatBindings b1 (justPatBindings b2 binds) 
405 justPatBindings other_bind binds = binds
406 \end{code}
407
408 Polymorphic recursion
409 ~~~~~~~~~~~~~~~~~~~~~
410 The game plan for polymorphic recursion in the code above is 
411
412         * Bind any variable for which we have a type signature
413           to an Id with a polymorphic type.  Then when type-checking 
414           the RHSs we'll make a full polymorphic call.
415
416 This fine, but if you aren't a bit careful you end up with a horrendous
417 amount of partial application and (worse) a huge space leak. For example:
418
419         f :: Eq a => [a] -> [a]
420         f xs = ...f...
421
422 If we don't take care, after typechecking we get
423
424         f = /\a -> \d::Eq a -> let f' = f a d
425                                in
426                                \ys:[a] -> ...f'...
427
428 Notice the the stupid construction of (f a d), which is of course
429 identical to the function we're executing.  In this case, the
430 polymorphic recursion isn't being used (but that's a very common case).
431 We'd prefer
432
433         f = /\a -> \d::Eq a -> letrec
434                                  fm = \ys:[a] -> ...fm...
435                                in
436                                fm
437
438 This can lead to a massive space leak, from the following top-level defn
439 (post-typechecking)
440
441         ff :: [Int] -> [Int]
442         ff = f Int dEqInt
443
444 Now (f dEqInt) evaluates to a lambda that has f' as a free variable; but
445 f' is another thunk which evaluates to the same thing... and you end
446 up with a chain of identical values all hung onto by the CAF ff.
447
448         ff = f Int dEqInt
449
450            = let f' = f Int dEqInt in \ys. ...f'...
451
452            = let f' = let f' = f Int dEqInt in \ys. ...f'...
453                       in \ys. ...f'...
454
455 Etc.
456 Solution: when typechecking the RHSs we always have in hand the
457 *monomorphic* Ids for each binding.  So we just need to make sure that
458 if (Method f a d) shows up in the constraints emerging from (...f...)
459 we just use the monomorphic Id.  We achieve this by adding monomorphic Ids
460 to the "givens" when simplifying constraints.  That's what the "lies_avail"
461 is doing.
462
463
464 %************************************************************************
465 %*                                                                      *
466 \subsection{getTyVarsToGen}
467 %*                                                                      *
468 %************************************************************************
469
470 @getTyVarsToGen@ decides what type variables generalise over.
471
472 For a "restricted group" -- see the monomorphism restriction
473 for a definition -- we bind no dictionaries, and
474 remove from tyvars_to_gen any constrained type variables
475
476 *Don't* simplify dicts at this point, because we aren't going
477 to generalise over these dicts.  By the time we do simplify them
478 we may well know more.  For example (this actually came up)
479         f :: Array Int Int
480         f x = array ... xs where xs = [1,2,3,4,5]
481 We don't want to generate lots of (fromInt Int 1), (fromInt Int 2)
482 stuff.  If we simplify only at the f-binding (not the xs-binding)
483 we'll know that the literals are all Ints, and we can just produce
484 Int literals!
485
486 Find all the type variables involved in overloading, the
487 "constrained_tyvars".  These are the ones we *aren't* going to
488 generalise.  We must be careful about doing this:
489
490  (a) If we fail to generalise a tyvar which is not actually
491         constrained, then it will never, ever get bound, and lands
492         up printed out in interface files!  Notorious example:
493                 instance Eq a => Eq (Foo a b) where ..
494         Here, b is not constrained, even though it looks as if it is.
495         Another, more common, example is when there's a Method inst in
496         the LIE, whose type might very well involve non-overloaded
497         type variables.
498
499  (b) On the other hand, we mustn't generalise tyvars which are constrained,
500         because we are going to pass on out the unmodified LIE, with those
501         tyvars in it.  They won't be in scope if we've generalised them.
502
503 So we are careful, and do a complete simplification just to find the
504 constrained tyvars. We don't use any of the results, except to
505 find which tyvars are constrained.
506
507 \begin{code}
508 getTyVarsToGen is_unrestricted mono_id_tys lie
509   = tcGetGlobalTyVars                   `thenNF_Tc` \ free_tyvars ->
510     zonkTcTypes mono_id_tys             `thenNF_Tc` \ zonked_mono_id_tys ->
511     let
512         tyvars_to_gen = tyVarsOfTypes zonked_mono_id_tys `minusVarSet` free_tyvars
513     in
514     if is_unrestricted
515     then
516         returnNF_Tc (emptyVarSet, tyvars_to_gen)
517     else
518         -- This recover and discard-errs is to avoid duplicate error
519         -- messages; this, after all, is an "extra" call to tcSimplify
520         recoverNF_Tc (returnNF_Tc (emptyVarSet, tyvars_to_gen))         $
521         discardErrsTc                                                   $
522
523         tcSimplify (text "getTVG") NotTopLevel tyvars_to_gen lie    `thenTc` \ (_, _, constrained_dicts) ->
524         let
525           -- ASSERT: dicts_sig is already zonked!
526             constrained_tyvars    = foldrBag (unionVarSet . tyVarsOfInst) emptyVarSet constrained_dicts
527             reduced_tyvars_to_gen = tyvars_to_gen `minusVarSet` constrained_tyvars
528         in
529         returnTc (constrained_tyvars, reduced_tyvars_to_gen)
530 \end{code}
531
532
533 \begin{code}
534 isUnRestrictedGroup :: [Name]           -- Signatures given for these
535                     -> RenamedMonoBinds
536                     -> Bool
537
538 is_elem v vs = isIn "isUnResMono" v vs
539
540 isUnRestrictedGroup sigs (PatMonoBind (VarPatIn v) _ _) = v `is_elem` sigs
541 isUnRestrictedGroup sigs (PatMonoBind other        _ _) = False
542 isUnRestrictedGroup sigs (VarMonoBind v _)              = v `is_elem` sigs
543 isUnRestrictedGroup sigs (FunMonoBind _ _ _ _)          = True
544 isUnRestrictedGroup sigs (AndMonoBinds mb1 mb2)         = isUnRestrictedGroup sigs mb1 &&
545                                                           isUnRestrictedGroup sigs mb2
546 isUnRestrictedGroup sigs EmptyMonoBinds                 = True
547 \end{code}
548
549
550 %************************************************************************
551 %*                                                                      *
552 \subsection{tcMonoBind}
553 %*                                                                      *
554 %************************************************************************
555
556 @tcMonoBinds@ deals with a single @MonoBind@.  
557 The signatures have been dealt with already.
558
559 \begin{code}
560 tcMonoBinds :: RenamedMonoBinds 
561             -> [TcSigInfo]
562             -> RecFlag
563             -> TcM s (TcMonoBinds, 
564                       LIE,              -- LIE required
565                       [Name],           -- Bound names
566                       [TcId])   -- Corresponding monomorphic bound things
567
568 tcMonoBinds mbinds tc_ty_sigs is_rec
569   = tc_mb_pats mbinds           `thenTc` \ (complete_it, lie_req_pat, tvs, ids, lie_avail) ->
570     let
571         tv_list           = bagToList tvs
572         id_list           = bagToList ids
573         (names, mono_ids) = unzip id_list
574
575                 -- This last defn is the key one:
576                 -- extend the val envt with bindings for the 
577                 -- things bound in this group, overriding the monomorphic
578                 -- ids with the polymorphic ones from the pattern
579         extra_val_env = case is_rec of
580                           Recursive    -> map mk_bind id_list
581                           NonRecursive -> []
582     in
583         -- Don't know how to deal with pattern-bound existentials yet
584     checkTc (isEmptyBag tvs && isEmptyBag lie_avail) 
585             (existentialExplode mbinds)                 `thenTc_` 
586
587         -- *Before* checking the RHSs, but *after* checking *all* the patterns,
588         -- extend the envt with bindings for all the bound ids;
589         --   and *then* override with the polymorphic Ids from the signatures
590         -- That is the whole point of the "complete_it" stuff.
591         --
592         -- There's a further wrinkle: we have to delay extending the environment
593         -- until after we've dealt with any pattern-bound signature type variables
594         -- Consider  f (x::a) = ...f...
595         -- We're going to check that a isn't unified with anything in the envt, 
596         -- so f itself had better not be!  So we pass the envt binding f into
597         -- complete_it, which extends the actual envt in TcMatches.tcMatch, after
598         -- dealing with the signature tyvars
599
600     complete_it extra_val_env                           `thenTc` \ (mbinds', lie_req_rhss) ->
601
602     returnTc (mbinds', lie_req_pat `plusLIE` lie_req_rhss, names, mono_ids)
603   where
604     sig_fn name = case maybeSig tc_ty_sigs name of
605                         Nothing                                -> Nothing
606                         Just (TySigInfo _ _ _ _ _ mono_id _ _) -> Just mono_id
607
608     mk_bind (name, mono_id) = case maybeSig tc_ty_sigs name of
609                                 Nothing                                   -> (name, mono_id)
610                                 Just (TySigInfo name poly_id _ _ _ _ _ _) -> (name, poly_id)
611
612     tc_mb_pats EmptyMonoBinds
613       = returnTc (\ xve -> returnTc (EmptyMonoBinds, emptyLIE), emptyLIE, emptyBag, emptyBag, emptyLIE)
614
615     tc_mb_pats (AndMonoBinds mb1 mb2)
616       = tc_mb_pats mb1          `thenTc` \ (complete_it1, lie_req1, tvs1, ids1, lie_avail1) ->
617         tc_mb_pats mb2          `thenTc` \ (complete_it2, lie_req2, tvs2, ids2, lie_avail2) ->
618         let
619            complete_it xve = complete_it1 xve   `thenTc` \ (mb1', lie1) ->
620                              complete_it2 xve   `thenTc` \ (mb2', lie2) ->
621                              returnTc (AndMonoBinds mb1' mb2', lie1 `plusLIE` lie2)
622         in
623         returnTc (complete_it,
624                   lie_req1 `plusLIE` lie_req2,
625                   tvs1 `unionBags` tvs2,
626                   ids1 `unionBags` ids2,
627                   lie_avail1 `plusLIE` lie_avail2)
628
629     tc_mb_pats (FunMonoBind name inf matches locn)
630       = newTyVarTy boxedTypeKind        `thenNF_Tc` \ bndr_ty ->
631         tcVarPat sig_fn name bndr_ty    `thenTc` \ bndr_id ->
632         let
633            complete_it xve = tcAddSrcLoc locn                           $
634                              tcMatchesFun xve name bndr_ty  matches     `thenTc` \ (matches', lie) ->
635                              returnTc (FunMonoBind bndr_id inf matches' locn, lie)
636         in
637         returnTc (complete_it, emptyLIE, emptyBag, unitBag (name, bndr_id), emptyLIE)
638
639     tc_mb_pats bind@(PatMonoBind pat grhss locn)
640       = tcAddSrcLoc locn                $
641
642                 -- Figure out the appropriate kind for the pattern,
643                 -- and generate a suitable type variable 
644         (case is_rec of
645              Recursive    -> newTyVarTy boxedTypeKind   -- Recursive, so no unboxed types
646              NonRecursive -> newTyVarTy_OpenKind        -- Non-recursive, so we permit unboxed types
647         )                                       `thenNF_Tc` \ pat_ty ->
648
649                 --      Now typecheck the pattern
650                 -- We don't support binding fresh type variables in the
651                 -- pattern of a pattern binding.  For example, this is illegal:
652                 --      (x::a, y::b) = e
653                 -- whereas this is ok
654                 --      (x::Int, y::Bool) = e
655                 --
656                 -- We don't check explicitly for this problem.  Instead, we simply
657                 -- type check the pattern with tcPat.  If the pattern mentions any
658                 -- fresh tyvars we simply get an out-of-scope type variable error
659         tcPat sig_fn pat pat_ty         `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
660         let
661            complete_it xve = tcAddSrcLoc locn                           $
662                              tcAddErrCtxt (patMonoBindsCtxt bind)       $
663                              tcExtendLocalValEnv xve                    $
664                              tcGRHSs grhss pat_ty PatBindRhs            `thenTc` \ (grhss', lie) ->
665                              returnTc (PatMonoBind pat' grhss' locn, lie)
666         in
667         returnTc (complete_it, lie_req, tvs, ids, lie_avail)
668 \end{code}
669
670 %************************************************************************
671 %*                                                                      *
672 \subsection{Signatures}
673 %*                                                                      *
674 %************************************************************************
675
676 @checkSigMatch@ does the next step in checking signature matching.
677 The tau-type part has already been unified.  What we do here is to
678 check that this unification has not over-constrained the (polymorphic)
679 type variables of the original signature type.
680
681 The error message here is somewhat unsatisfactory, but it'll do for
682 now (ToDo).
683
684 \begin{code}
685 checkSigMatch []
686   = returnTc (error "checkSigMatch", emptyLIE)
687
688 checkSigMatch tc_ty_sigs@( sig1@(TySigInfo _ id1 _ theta1 _ _ _ _) : all_sigs_but_first )
689   =     -- CHECK THAT THE SIGNATURE TYVARS AND TAU_TYPES ARE OK
690         -- Doesn't affect substitution
691     mapTc check_one_sig tc_ty_sigs      `thenTc_`
692
693         -- CHECK THAT ALL THE SIGNATURE CONTEXTS ARE UNIFIABLE
694         -- The type signatures on a mutually-recursive group of definitions
695         -- must all have the same context (or none).
696         --
697         -- We unify them because, with polymorphic recursion, their types
698         -- might not otherwise be related.  This is a rather subtle issue.
699         -- ToDo: amplify
700     mapTc check_one_cxt all_sigs_but_first              `thenTc_`
701
702     returnTc (theta1, sig_lie)
703   where
704     sig1_dict_tys       = mk_dict_tys theta1
705     n_sig1_dict_tys     = length sig1_dict_tys
706     sig_lie             = mkLIE [inst | TySigInfo _ _ _ _ _ _ inst _ <- tc_ty_sigs]
707
708     check_one_cxt sig@(TySigInfo _ id _ theta _ _ _ src_loc)
709        = tcAddSrcLoc src_loc    $
710          tcAddErrCtxt (sigContextsCtxt id1 id) $
711          checkTc (length this_sig_dict_tys == n_sig1_dict_tys)
712                                 sigContextsErr          `thenTc_`
713          unifyTauTyLists sig1_dict_tys this_sig_dict_tys
714       where
715          this_sig_dict_tys = mk_dict_tys theta
716
717     check_one_sig (TySigInfo _ id sig_tyvars _ sig_tau _ _ src_loc)
718       = tcAddSrcLoc src_loc                                     $
719         tcAddErrCtxtM (sigCtxt (sig_msg id) (idType id))        $
720         checkSigTyVars sig_tyvars
721
722     mk_dict_tys theta = [mkDictTy c ts | (c,ts) <- theta]
723
724     sig_msg id tidy_ty = sep [ptext SLIT("When checking the type signature"),
725                               nest 4 (ppr id <+> dcolon <+> ppr tidy_ty)]
726 \end{code}
727
728
729 %************************************************************************
730 %*                                                                      *
731 \subsection{SPECIALIZE pragmas}
732 %*                                                                      *
733 %************************************************************************
734
735
736 @tcPragmaSigs@ munches up the "signatures" that arise through *user*
737 pragmas.  It is convenient for them to appear in the @[RenamedSig]@
738 part of a binding because then the same machinery can be used for
739 moving them into place as is done for type signatures.
740
741 \begin{code}
742 tcPragmaSigs :: [RenamedSig]            -- The pragma signatures
743              -> TcM s (Name -> IdInfo,  -- Maps name to the appropriate IdInfo
744                        TcMonoBinds,
745                        LIE)
746
747 tcPragmaSigs sigs
748   = mapAndUnzip3Tc tcPragmaSig sigs     `thenTc` \ (maybe_info_modifiers, binds, lies) ->
749     let
750         prag_fn name = foldr ($) noIdInfo [f | Just (n,f) <- maybe_info_modifiers, n==name]
751     in
752     returnTc (prag_fn, andMonoBindList binds, plusLIEs lies)
753 \end{code}
754
755 The interesting case is for SPECIALISE pragmas.  There are two forms.
756 Here's the first form:
757 \begin{verbatim}
758         f :: Ord a => [a] -> b -> b
759         {-# SPECIALIZE f :: [Int] -> b -> b #-}
760 \end{verbatim}
761
762 For this we generate:
763 \begin{verbatim}
764         f* = /\ b -> let d1 = ...
765                      in f Int b d1
766 \end{verbatim}
767
768 where f* is a SpecPragmaId.  The **sole** purpose of SpecPragmaIds is to
769 retain a right-hand-side that the simplifier will otherwise discard as
770 dead code... the simplifier has a flag that tells it not to discard
771 SpecPragmaId bindings.
772
773 In this case the f* retains a call-instance of the overloaded
774 function, f, (including appropriate dictionaries) so that the
775 specialiser will subsequently discover that there's a call of @f@ at
776 Int, and will create a specialisation for @f@.  After that, the
777 binding for @f*@ can be discarded.
778
779 The second form is this:
780 \begin{verbatim}
781         f :: Ord a => [a] -> b -> b
782         {-# SPECIALIZE f :: [Int] -> b -> b = g #-}
783 \end{verbatim}
784
785 Here @g@ is specified as a function that implements the specialised
786 version of @f@.  Suppose that g has type (a->b->b); that is, g's type
787 is more general than that required.  For this we generate
788 \begin{verbatim}
789         f@Int = /\b -> g Int b
790         f* = f@Int
791 \end{verbatim}
792
793 Here @f@@Int@ is a SpecId, the specialised version of @f@.  It inherits
794 f's export status etc.  @f*@ is a SpecPragmaId, as before, which just serves
795 to prevent @f@@Int@ from being discarded prematurely.  After specialisation,
796 if @f@@Int@ is going to be used at all it will be used explicitly, so the simplifier can
797 discard the f* binding.
798
799 Actually, there is really only point in giving a SPECIALISE pragma on exported things,
800 and the simplifer won't discard SpecIds for exporte things anyway, so maybe this is
801 a bit of overkill.
802
803 \begin{code}
804 tcPragmaSig :: RenamedSig -> TcM s (Maybe (Name, IdInfo -> IdInfo), TcMonoBinds, LIE)
805 tcPragmaSig (Sig _ _ _)       = returnTc (Nothing, EmptyMonoBinds, emptyLIE)
806 tcPragmaSig (SpecInstSig _ _) = returnTc (Nothing, EmptyMonoBinds, emptyLIE)
807
808 tcPragmaSig (InlineSig name loc)
809   = returnTc (Just (name, setInlinePragInfo IWantToBeINLINEd), EmptyMonoBinds, emptyLIE)
810
811 tcPragmaSig (NoInlineSig name loc)
812   = returnTc (Just (name, setInlinePragInfo IMustNotBeINLINEd), EmptyMonoBinds, emptyLIE)
813
814 tcPragmaSig (SpecSig name poly_ty maybe_spec_name src_loc)
815   =     -- SPECIALISE f :: forall b. theta => tau  =  g
816     tcAddSrcLoc src_loc                         $
817     tcAddErrCtxt (valSpecSigCtxt name poly_ty)  $
818
819         -- Get and instantiate its alleged specialised type
820     tcHsType poly_ty                            `thenTc` \ sig_ty ->
821
822         -- Check that f has a more general type, and build a RHS for
823         -- the spec-pragma-id at the same time
824     tcExpr (HsVar name) sig_ty                  `thenTc` \ (spec_expr, spec_lie) ->
825
826     case maybe_spec_name of
827         Nothing ->      -- Just specialise "f" by building a SpecPragmaId binding
828                         -- It is the thing that makes sure we don't prematurely 
829                         -- dead-code-eliminate the binding we are really interested in.
830                    newSpecPragmaId name sig_ty          `thenNF_Tc` \ spec_id ->
831                    returnTc (Nothing, VarMonoBind spec_id spec_expr, spec_lie)
832
833         Just g_name ->  -- Don't create a SpecPragmaId.  Instead add some suitable IdIfo
834                 
835                 panic "Can't handle SPECIALISE with a '= g' part"
836
837         {-  Not yet.  Because we're still in the TcType world we
838             can't really add to the SpecEnv of the Id.  Instead we have to
839             record the information in a different sort of Sig, and add it to
840             the IdInfo after zonking.
841
842             For now we just leave out this case
843
844                         -- Get the type of f, and find out what types
845                         --  f has to be instantiated at to give the signature type
846                     tcLookupValue name                  `thenNF_Tc` \ f_id ->
847                     tcInstTcType (idType f_id)          `thenNF_Tc` \ (f_tyvars, f_rho) ->
848
849                     let
850                         (sig_tyvars, sig_theta, sig_tau) = splitSigmaTy sig_ty
851                         (f_theta, f_tau)                 = splitRhoTy f_rho
852                         sig_tyvar_set                    = mkVarSet sig_tyvars
853                     in
854                     unifyTauTy sig_tau f_tau            `thenTc_`
855
856                     tcPolyExpr str (HsVar g_name) (mkSigmaTy sig_tyvars f_theta sig_tau)        `thenTc` \ (_, _, 
857         -}
858
859 tcPragmaSig other = pprTrace "tcPragmaSig: ignoring" (ppr other) $
860                     returnTc (Nothing, EmptyMonoBinds, emptyLIE)
861 \end{code}
862
863
864 %************************************************************************
865 %*                                                                      *
866 \subsection[TcBinds-errors]{Error contexts and messages}
867 %*                                                                      *
868 %************************************************************************
869
870
871 \begin{code}
872 patMonoBindsCtxt bind
873   = hang (ptext SLIT("In a pattern binding:")) 4 (ppr bind)
874
875 -----------------------------------------------
876 valSpecSigCtxt v ty
877   = sep [ptext SLIT("In a SPECIALIZE pragma for a value:"),
878          nest 4 (ppr v <+> dcolon <+> ppr ty)]
879
880 -----------------------------------------------
881 notAsPolyAsSigErr sig_tau mono_tyvars
882   = hang (ptext SLIT("A type signature is more polymorphic than the inferred type"))
883         4  (vcat [text "Can't for-all the type variable(s)" <+> 
884                   pprQuotedList mono_tyvars,
885                   text "in the type" <+> quotes (ppr sig_tau)
886            ])
887
888 -----------------------------------------------
889 badMatchErr sig_ty inferred_ty
890   = hang (ptext SLIT("Type signature doesn't match inferred type"))
891          4 (vcat [hang (ptext SLIT("Signature:")) 4 (ppr sig_ty),
892                       hang (ptext SLIT("Inferred :")) 4 (ppr inferred_ty)
893            ])
894
895 -----------------------------------------------
896 unboxedPatBindErr id
897   = ptext SLIT("variable in a lazy pattern binding has unboxed type: ")
898          <+> quotes (ppr id)
899
900 -----------------------------------------------
901 bindSigsCtxt ids
902   = ptext SLIT("When checking the type signature(s) for") <+> pprQuotedList ids
903
904 -----------------------------------------------
905 sigContextsErr
906   = ptext SLIT("Mismatched contexts")
907 sigContextsCtxt s1 s2
908   = hang (hsep [ptext SLIT("When matching the contexts of the signatures for"), 
909                 quotes (ppr s1), ptext SLIT("and"), quotes (ppr s2)])
910          4 (ptext SLIT("(the signature contexts in a mutually recursive group should all be identical)"))
911
912 -----------------------------------------------
913 unliftedBindErr flavour mbind
914   = hang (text flavour <+> ptext SLIT("bindings for unlifted types aren't allowed"))
915          4 (ppr mbind)
916
917 existentialExplode mbinds
918   = hang (vcat [text "My brain just exploded.",
919                 text "I can't handle pattern bindings for existentially-quantified constructors.",
920                 text "In the binding group"])
921         4 (ppr mbinds)
922 \end{code}