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