a16cddcc0caf56c150181e25e5971110ff4e196e
[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, tcTopBinds, tcHsBootSigs, tcMonoBinds, tcSpecSigs ) where
8
9 #include "HsVersions.h"
10
11 import {-# SOURCE #-} TcMatches ( tcGRHSsPat, tcMatchesFun )
12 import {-# SOURCE #-} TcExpr  ( tcCheckSigma, tcCheckRho )
13
14 import CmdLineOpts      ( DynFlag(Opt_MonomorphismRestriction) )
15 import HsSyn            ( HsExpr(..), HsBind(..), LHsBinds, Sig(..),
16                           LSig, Match(..), HsBindGroup(..), IPBind(..), 
17                           HsType(..), hsLTyVarNames, isVanillaLSig,
18                           LPat, GRHSs, MatchGroup(..), emptyLHsBinds, isEmptyLHsBinds,
19                           collectHsBindBinders, collectPatBinders, pprPatBind
20                         )
21 import TcHsSyn          ( TcId, TcDictBinds, zonkId, mkHsLet )
22
23 import TcRnMonad
24 import Inst             ( InstOrigin(..), newDictsAtLoc, newIPDict, instToId )
25 import TcEnv            ( tcExtendIdEnv, tcExtendIdEnv2, tcExtendTyVarEnv2, 
26                           newLocalName, tcLookupLocalIds, pprBinders,
27                           tcGetGlobalTyVars )
28 import TcUnify          ( Expected(..), tcInfer, unifyTheta, 
29                           bleatEscapedTvs, sigCtxt )
30 import TcSimplify       ( tcSimplifyInfer, tcSimplifyInferCheck, tcSimplifyRestricted, 
31                           tcSimplifyToDicts, tcSimplifyIPs )
32 import TcHsType         ( tcHsSigType, UserTypeCtxt(..), tcAddLetBoundTyVars,
33                           TcSigInfo(..), TcSigFun, lookupSig
34                         )
35 import TcPat            ( tcPat, PatCtxt(..) )
36 import TcSimplify       ( bindInstsOfLocalFuns )
37 import TcMType          ( newTyFlexiVarTy, zonkQuantifiedTyVar, 
38                           tcInstSigType, zonkTcTypes, zonkTcTyVar )
39 import TcType           ( TcTyVar, SkolemInfo(SigSkol), 
40                           TcTauType, TcSigmaType, 
41                           mkTyVarTy, mkForAllTys, mkFunTys, tyVarsOfType, 
42                           mkForAllTy, isUnLiftedType, tcGetTyVar_maybe, 
43                           mkTyVarTys, tidyOpenTyVar, tidyOpenType )
44 import Kind             ( argTypeKind )
45 import VarEnv           ( TyVarEnv, emptyVarEnv, lookupVarEnv, extendVarEnv, emptyTidyEnv ) 
46 import TysPrim          ( alphaTyVar )
47 import Id               ( mkLocalId, mkSpecPragmaId, setInlinePragma )
48 import Var              ( idType, idName )
49 import Name             ( Name )
50 import NameSet
51 import VarSet
52 import SrcLoc           ( Located(..), unLoc, noLoc, getLoc )
53 import Bag
54 import Util             ( isIn )
55 import BasicTypes       ( TopLevelFlag(..), RecFlag(..), isNonRec, isRec, 
56                           isNotTopLevel, isAlwaysActive )
57 import FiniteMap        ( listToFM, lookupFM )
58 import Outputable
59 \end{code}
60
61
62 %************************************************************************
63 %*                                                                      *
64 \subsection{Type-checking bindings}
65 %*                                                                      *
66 %************************************************************************
67
68 @tcBindsAndThen@ typechecks a @HsBinds@.  The "and then" part is because
69 it needs to know something about the {\em usage} of the things bound,
70 so that it can create specialisations of them.  So @tcBindsAndThen@
71 takes a function which, given an extended environment, E, typechecks
72 the scope of the bindings returning a typechecked thing and (most
73 important) an LIE.  It is this LIE which is then used as the basis for
74 specialising the things bound.
75
76 @tcBindsAndThen@ also takes a "combiner" which glues together the
77 bindings and the "thing" to make a new "thing".
78
79 The real work is done by @tcBindWithSigsAndThen@.
80
81 Recursive and non-recursive binds are handled in essentially the same
82 way: because of uniques there are no scoping issues left.  The only
83 difference is that non-recursive bindings can bind primitive values.
84
85 Even for non-recursive binding groups we add typings for each binder
86 to the LVE for the following reason.  When each individual binding is
87 checked the type of its LHS is unified with that of its RHS; and
88 type-checking the LHS of course requires that the binder is in scope.
89
90 At the top-level the LIE is sure to contain nothing but constant
91 dictionaries, which we resolve at the module level.
92
93 \begin{code}
94 tcTopBinds :: [HsBindGroup Name] -> TcM (LHsBinds TcId, TcLclEnv)
95         -- Note: returning the TcLclEnv is more than we really
96         --       want.  The bit we care about is the local bindings
97         --       and the free type variables thereof
98 tcTopBinds binds
99   = tc_binds_and_then TopLevel glue binds $
100             do  { env <- getLclEnv
101                 ; return (emptyLHsBinds, env) }
102   where
103         -- The top level bindings are flattened into a giant 
104         -- implicitly-mutually-recursive MonoBinds
105     glue (HsBindGroup binds1 _ _) (binds2, env) = (binds1 `unionBags` binds2, env)
106     glue (HsIPBinds _)            _             = panic "Top-level HsIpBinds"
107         -- Can't have a HsIPBinds at top level
108
109 tcHsBootSigs :: [HsBindGroup Name] -> TcM (LHsBinds TcId, TcLclEnv)
110 -- A hs-boot file has only one BindGroup, and it only has type
111 -- signatures in it.  The renamer checked all this
112 tcHsBootSigs [HsBindGroup _ sigs _]
113   = do  { ids <- mapM (addLocM tc_sig) (filter isVanillaLSig sigs)
114         ; tcExtendIdEnv ids $ do 
115         { env <- getLclEnv
116         ; return (emptyLHsBinds, env) }}
117   where
118     tc_sig (Sig (L _ name) ty)
119       = do { sigma_ty <- tcHsSigType (FunSigCtxt name) ty
120            ; return (mkLocalId name sigma_ty) }
121
122 tcBindsAndThen
123         :: (HsBindGroup TcId -> thing -> thing)         -- Combinator
124         -> [HsBindGroup Name]
125         -> TcM thing
126         -> TcM thing
127
128 tcBindsAndThen = tc_binds_and_then NotTopLevel
129
130 tc_binds_and_then top_lvl combiner [] do_next
131   = do_next
132 tc_binds_and_then top_lvl combiner (group : groups) do_next
133   = tc_bind_and_then top_lvl combiner group $ 
134     tc_binds_and_then top_lvl combiner groups do_next
135
136 tc_bind_and_then top_lvl combiner (HsIPBinds binds) do_next
137   = getLIE do_next                              `thenM` \ (result, expr_lie) ->
138     mapAndUnzipM (wrapLocSndM tc_ip_bind) binds `thenM` \ (avail_ips, binds') ->
139
140         -- If the binding binds ?x = E, we  must now 
141         -- discharge any ?x constraints in expr_lie
142     tcSimplifyIPs avail_ips expr_lie    `thenM` \ dict_binds ->
143
144     returnM (combiner (HsIPBinds binds') $
145              combiner (HsBindGroup dict_binds [] Recursive) result)
146   where
147         -- I wonder if we should do these one at at time
148         -- Consider     ?x = 4
149         --              ?y = ?x + 1
150     tc_ip_bind (IPBind ip expr)
151       = newTyFlexiVarTy argTypeKind             `thenM` \ ty ->
152         newIPDict (IPBindOrigin ip) ip ty       `thenM` \ (ip', ip_inst) ->
153         tcCheckRho expr ty                      `thenM` \ expr' ->
154         returnM (ip_inst, (IPBind ip' expr'))
155
156 tc_bind_and_then top_lvl combiner (HsBindGroup binds sigs is_rec) do_next
157   | isEmptyLHsBinds binds 
158   = do_next
159   | otherwise
160  =      -- BRING ANY SCOPED TYPE VARIABLES INTO SCOPE
161           -- Notice that they scope over 
162           --       a) the type signatures in the binding group
163           --       b) the bindings in the group
164           --       c) the scope of the binding group (the "in" part)
165       tcAddLetBoundTyVars binds  $
166  
167       case top_lvl of
168           TopLevel       -- For the top level don't bother will all this
169                          --  bindInstsOfLocalFuns stuff. All the top level 
170                          -- things are rec'd together anyway, so it's fine to
171                          -- leave them to the tcSimplifyTop, and quite a bit faster too
172                 -> tcBindWithSigs top_lvl binds sigs is_rec     `thenM` \ (poly_binds, poly_ids) ->
173                    tc_body poly_ids                             `thenM` \ (prag_binds, thing) ->
174                    returnM (combiner (HsBindGroup
175                                         (poly_binds `unionBags` prag_binds)
176                                         [] -- no sigs
177                                         Recursive)
178                                      thing)
179  
180           NotTopLevel   -- For nested bindings we must do the bindInstsOfLocalFuns thing.
181                 | not (isRec is_rec)            -- Non-recursive group
182                 ->      -- We want to keep non-recursive things non-recursive
183                         -- so that we desugar unlifted bindings correctly
184                     tcBindWithSigs top_lvl binds sigs is_rec    `thenM` \ (poly_binds, poly_ids) ->
185                     getLIE (tc_body poly_ids)                   `thenM` \ ((prag_binds, thing), lie) ->
186  
187                              -- Create specialisations of functions bound here
188                     bindInstsOfLocalFuns lie poly_ids `thenM` \ lie_binds ->
189  
190                     returnM (
191                         combiner (HsBindGroup poly_binds [] NonRecursive) $
192                         combiner (HsBindGroup prag_binds [] NonRecursive) $
193                         combiner (HsBindGroup lie_binds  [] Recursive)    $
194                          -- NB: the binds returned by tcSimplify and
195                          -- bindInstsOfLocalFuns aren't guaranteed in
196                          -- dependency order (though we could change that);
197                          -- hence the Recursive marker.
198                         thing)
199
200                 | otherwise
201                 ->      -- NB: polymorphic recursion means that a function
202                         -- may use an instance of itself, we must look at the LIE arising
203                         -- from the function's own right hand side.  Hence the getLIE
204                         -- encloses the tcBindWithSigs.
205
206                    getLIE (
207                       tcBindWithSigs top_lvl binds sigs is_rec  `thenM` \ (poly_binds, poly_ids) ->
208                       tc_body poly_ids                          `thenM` \ (prag_binds, thing) ->
209                       returnM (poly_ids, poly_binds `unionBags` prag_binds, thing)
210                    )   `thenM` \ ((poly_ids, extra_binds, thing), lie) ->
211  
212                    bindInstsOfLocalFuns lie poly_ids    `thenM` \ lie_binds ->
213
214                    returnM (combiner (HsBindGroup
215                                         (extra_binds `unionBags` lie_binds)
216                                         [] Recursive) thing
217                    )
218   where
219     tc_body poly_ids    -- Type check the pragmas and "thing inside"
220       =   -- Extend the environment to bind the new polymorphic Ids
221           tcExtendIdEnv poly_ids        $
222   
223           -- Build bindings and IdInfos corresponding to user pragmas
224           tcSpecSigs sigs               `thenM` \ prag_binds ->
225
226           -- Now do whatever happens next, in the augmented envt
227           do_next                       `thenM` \ thing ->
228
229           returnM (prag_binds, thing)
230 \end{code}
231
232
233 %************************************************************************
234 %*                                                                      *
235 \subsection{tcBindWithSigs}
236 %*                                                                      *
237 %************************************************************************
238
239 @tcBindWithSigs@ deals with a single binding group.  It does generalisation,
240 so all the clever stuff is in here.
241
242 * binder_names and mbind must define the same set of Names
243
244 * The Names in tc_ty_sigs must be a subset of binder_names
245
246 * The Ids in tc_ty_sigs don't necessarily have to have the same name
247   as the Name in the tc_ty_sig
248
249 \begin{code}
250 tcBindWithSigs  :: TopLevelFlag
251                 -> LHsBinds Name
252                 -> [LSig Name]
253                 -> RecFlag
254                 -> TcM (LHsBinds TcId, [TcId])
255         -- The returned TcIds are guaranteed zonked
256
257 tcBindWithSigs top_lvl mbind sigs is_rec = do   
258   {     -- TYPECHECK THE SIGNATURES
259     tc_ty_sigs <- recoverM (returnM []) $
260                   tcTySigs (filter isVanillaLSig sigs)
261   ; let lookup_sig = lookupSig tc_ty_sigs
262
263         -- SET UP THE MAIN RECOVERY; take advantage of any type sigs
264   ; recoverM (recoveryCode mbind lookup_sig) $ do
265
266   { traceTc (ptext SLIT("--------------------------------------------------------"))
267   ; traceTc (ptext SLIT("Bindings for") <+> ppr (collectHsBindBinders mbind))
268
269         -- TYPECHECK THE BINDINGS
270   ; ((mbind', mono_bind_infos), lie_req) 
271         <- getLIE (tcMonoBinds mbind lookup_sig is_rec)
272
273         -- CHECK FOR UNLIFTED BINDINGS
274         -- These must be non-recursive etc, and are not generalised
275         -- They desugar to a case expression in the end
276   ; zonked_mono_tys <- zonkTcTypes (map getMonoType mono_bind_infos)
277   ; if any isUnLiftedType zonked_mono_tys then
278     do  {       -- Unlifted bindings
279           checkUnliftedBinds top_lvl is_rec mbind
280         ; extendLIEs lie_req
281         ; let exports  = zipWith mk_export mono_bind_infos zonked_mono_tys
282               mk_export (name, Nothing,  mono_id) mono_ty = ([], mkLocalId name mono_ty, mono_id)
283               mk_export (name, Just sig, mono_id) mono_ty = ([], sig_id sig,             mono_id)
284
285         ; return ( unitBag $ noLoc $ AbsBinds [] [] exports emptyNameSet mbind',
286                    [poly_id | (_, poly_id, _) <- exports]) }    -- Guaranteed zonked
287
288     else do     -- The normal lifted case: GENERALISE
289   { is_unres <- isUnRestrictedGroup mbind tc_ty_sigs
290   ; (tyvars_to_gen, dict_binds, dict_ids)
291         <- setSrcSpan (getLoc (head (bagToList mbind)))     $
292                 -- TODO: location a bit awkward, but the mbinds have been
293                 --       dependency analysed and may no longer be adjacent
294            addErrCtxt (genCtxt (bndrNames mono_bind_infos)) $
295            generalise top_lvl is_unres mono_bind_infos tc_ty_sigs lie_req
296
297         -- FINALISE THE QUANTIFIED TYPE VARIABLES
298         -- The quantified type variables often include meta type variables
299         -- we want to freeze them into ordinary type variables, and
300         -- default their kind (e.g. from OpenTypeKind to TypeKind)
301   ; tyvars_to_gen' <- mappM zonkQuantifiedTyVar tyvars_to_gen
302
303         -- BUILD THE POLYMORPHIC RESULT IDs
304   ; let
305         exports  = map mk_export mono_bind_infos
306         poly_ids = [poly_id | (_, poly_id, _) <- exports]
307         dict_tys = map idType dict_ids
308
309         inlines = mkNameSet [ name
310                             | L _ (InlineSig True (L _ name) _) <- sigs]
311                         -- Any INLINE sig (regardless of phase control) 
312                         -- makes the RHS look small
313         inline_phases = listToFM [ (name, phase)
314                                  | L _ (InlineSig _ (L _ name) phase) <- sigs, 
315                                    not (isAlwaysActive phase)]
316                         -- Set the IdInfo field to control the inline phase
317                         -- AlwaysActive is the default, so don't bother with them
318         add_inlines id = attachInlinePhase inline_phases id
319
320         mk_export (binder_name, mb_sig, mono_id)
321           = case mb_sig of
322               Just sig -> (sig_tvs sig, add_inlines (sig_id sig),  mono_id)
323               Nothing  -> (tyvars_to_gen', add_inlines new_poly_id, mono_id)
324           where
325             new_poly_id = mkLocalId binder_name poly_ty
326             poly_ty = mkForAllTys tyvars_to_gen'
327                     $ mkFunTys dict_tys 
328                     $ idType mono_id
329
330         -- ZONK THE poly_ids, because they are used to extend the type 
331         -- environment; see the invariant on TcEnv.tcExtendIdEnv 
332   ; zonked_poly_ids <- mappM zonkId poly_ids
333
334   ; traceTc (text "binding:" <+> ppr ((dict_ids, dict_binds),
335                                       exports, map idType zonked_poly_ids))
336
337   ; return (
338             unitBag $ noLoc $
339             AbsBinds tyvars_to_gen'
340                      dict_ids
341                      exports
342                      inlines
343                      (dict_binds `unionBags` mbind'),
344             zonked_poly_ids
345         )
346   } } }
347
348 -- If typechecking the binds fails, then return with each
349 -- signature-less binder given type (forall a.a), to minimise 
350 -- subsequent error messages
351 recoveryCode mbind lookup_sig
352   = do  { traceTc (text "tcBindsWithSigs: error recovery" <+> ppr binder_names)
353         ; return (emptyLHsBinds, poly_ids) }
354   where
355     forall_a_a    = mkForAllTy alphaTyVar (mkTyVarTy alphaTyVar)
356     binder_names  = collectHsBindBinders mbind
357     poly_ids      = map mk_dummy binder_names
358     mk_dummy name = case lookup_sig name of
359                       Just sig -> sig_id sig                    -- Signature
360                       Nothing  -> mkLocalId name forall_a_a     -- No signature
361
362 attachInlinePhase inline_phases bndr
363   = case lookupFM inline_phases (idName bndr) of
364         Just prag -> bndr `setInlinePragma` prag
365         Nothing   -> bndr
366
367 -- Check that non-overloaded unlifted bindings are
368 --      a) non-recursive,
369 --      b) not top level, 
370 --      c) not a multiple-binding group (more or less implied by (a))
371
372 checkUnliftedBinds top_lvl is_rec mbind
373   = checkTc (isNotTopLevel top_lvl)
374             (unliftedBindErr "Top-level" mbind)         `thenM_`
375     checkTc (isNonRec is_rec)
376             (unliftedBindErr "Recursive" mbind)         `thenM_`
377     checkTc (isSingletonBag mbind)
378             (unliftedBindErr "Multiple" mbind)
379 \end{code}
380
381
382 Polymorphic recursion
383 ~~~~~~~~~~~~~~~~~~~~~
384 The game plan for polymorphic recursion in the code above is 
385
386         * Bind any variable for which we have a type signature
387           to an Id with a polymorphic type.  Then when type-checking 
388           the RHSs we'll make a full polymorphic call.
389
390 This fine, but if you aren't a bit careful you end up with a horrendous
391 amount of partial application and (worse) a huge space leak. For example:
392
393         f :: Eq a => [a] -> [a]
394         f xs = ...f...
395
396 If we don't take care, after typechecking we get
397
398         f = /\a -> \d::Eq a -> let f' = f a d
399                                in
400                                \ys:[a] -> ...f'...
401
402 Notice the the stupid construction of (f a d), which is of course
403 identical to the function we're executing.  In this case, the
404 polymorphic recursion isn't being used (but that's a very common case).
405 We'd prefer
406
407         f = /\a -> \d::Eq a -> letrec
408                                  fm = \ys:[a] -> ...fm...
409                                in
410                                fm
411
412 This can lead to a massive space leak, from the following top-level defn
413 (post-typechecking)
414
415         ff :: [Int] -> [Int]
416         ff = f Int dEqInt
417
418 Now (f dEqInt) evaluates to a lambda that has f' as a free variable; but
419 f' is another thunk which evaluates to the same thing... and you end
420 up with a chain of identical values all hung onto by the CAF ff.
421
422         ff = f Int dEqInt
423
424            = let f' = f Int dEqInt in \ys. ...f'...
425
426            = let f' = let f' = f Int dEqInt in \ys. ...f'...
427                       in \ys. ...f'...
428
429 Etc.
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.  That's what the "lies_avail"
435 is doing.
436
437
438 %************************************************************************
439 %*                                                                      *
440 \subsection{tcMonoBind}
441 %*                                                                      *
442 %************************************************************************
443
444 @tcMonoBinds@ deals with a single @MonoBind@.  
445 The signatures have been dealt with already.
446
447 \begin{code}
448 tcMonoBinds :: LHsBinds Name
449             -> TcSigFun -> RecFlag
450             -> TcM (LHsBinds TcId, [MonoBindInfo])
451
452 tcMonoBinds binds lookup_sig is_rec
453   = do  { tc_binds <- mapBagM (wrapLocM (tcLhs lookup_sig)) binds
454
455         -- Bring (a) the scoped type variables, and (b) the Ids, into scope for the RHSs
456         -- For (a) it's ok to bring them all into scope at once, even
457         -- though each type sig should scope only over its own RHS,
458         -- because the renamer has sorted all that out.
459         ; let mono_info  = getMonoBindInfo tc_binds
460               rhs_tvs    = [ (name, mkTyVarTy tv)
461                            | (_, Just sig, _) <- mono_info, 
462                              (name, tv) <- sig_scoped sig `zip` sig_tvs sig ]
463               rhs_id_env = map mk mono_info     -- A binding for each term variable
464
465         ; binds' <- tcExtendTyVarEnv2 rhs_tvs   $
466                     tcExtendIdEnv2   rhs_id_env $
467                     traceTc (text "tcMonoBinds" <+> vcat [ppr n <+> ppr id <+> ppr (idType id) | (n,id) <- rhs_id_env]) `thenM_`
468                     mapBagM (wrapLocM tcRhs) tc_binds
469         ; return (binds', mono_info) }
470    where
471     mk (name, Just sig, _)       = (name, sig_id sig)   -- Use the type sig if there is one
472     mk (name, Nothing,  mono_id) = (name, mono_id)      -- otherwise use a monomorphic version
473
474 ------------------------
475 -- tcLhs typechecks the LHS of the bindings, to construct the environment in which
476 -- we typecheck the RHSs.  Basically what we are doing is this: for each binder:
477 --      if there's a signature for it, use the instantiated signature type
478 --      otherwise invent a type variable
479 -- You see that quite directly in the FunBind case.
480 -- 
481 -- But there's a complication for pattern bindings:
482 --      data T = MkT (forall a. a->a)
483 --      MkT f = e
484 -- Here we can guess a type variable for the entire LHS (which will be refined to T)
485 -- but we want to get (f::forall a. a->a) as the RHS environment.
486 -- The simplest way to do this is to typecheck the pattern, and then look up the
487 -- bound mono-ids.  Then we want to retain the typechecked pattern to avoid re-doing
488 -- it; hence the TcMonoBind data type in which the LHS is done but the RHS isn't
489
490 data TcMonoBind         -- Half completed; LHS done, RHS not done
491   = TcFunBind  MonoBindInfo  (Located TcId) Bool (MatchGroup Name) 
492   | TcPatBind [MonoBindInfo] (LPat TcId) (GRHSs Name) TcSigmaType
493
494 type MonoBindInfo = (Name, Maybe TcSigInfo, TcId)
495         -- Type signature (if any), and
496         -- the monomorphic bound things
497
498 bndrNames :: [MonoBindInfo] -> [Name]
499 bndrNames mbi = [n | (n,_,_) <- mbi]
500
501 getMonoType :: MonoBindInfo -> TcTauType
502 getMonoType (_,_,mono_id) = idType mono_id
503
504 tcLhs :: TcSigFun -> HsBind Name -> TcM TcMonoBind
505 tcLhs lookup_sig (FunBind (L nm_loc name) inf matches)
506   = do  { let mb_sig = lookup_sig name
507         ; mono_name <- newLocalName name
508         ; mono_ty   <- mk_mono_ty mb_sig
509         ; let mono_id = mkLocalId mono_name mono_ty
510         ; return (TcFunBind (name, mb_sig, mono_id) (L nm_loc mono_id) inf matches) }
511   where
512     mk_mono_ty (Just sig) = return (sig_tau sig)
513     mk_mono_ty Nothing    = newTyFlexiVarTy argTypeKind
514
515 tcLhs lookup_sig bind@(PatBind pat grhss _)
516   = do  { let tc_pat exp_ty = tcPat (LetPat lookup_sig) pat exp_ty lookup_infos
517         ; ((pat', ex_tvs, infos), pat_ty) 
518                 <- addErrCtxt (patMonoBindsCtxt pat grhss)
519                               (tcInfer tc_pat)
520
521         -- Don't know how to deal with pattern-bound existentials yet
522         ; checkTc (null ex_tvs) (existentialExplode bind)
523
524         ; return (TcPatBind infos pat' grhss pat_ty) }
525   where
526     names = collectPatBinders pat
527
528         -- After typechecking the pattern, look up the binder
529         -- names, which the pattern has brought into scope.
530     lookup_infos :: TcM [MonoBindInfo]
531     lookup_infos = do { mono_ids <- tcLookupLocalIds names
532                       ; return [ (name, lookup_sig name, mono_id)
533                                | (name, mono_id) <- names `zip` mono_ids] }
534
535 -------------------
536 tcRhs :: TcMonoBind -> TcM (HsBind TcId)
537 tcRhs (TcFunBind info fun'@(L _ mono_id) inf matches)
538   = do  { matches' <- tcMatchesFun (idName mono_id) matches 
539                                    (Check (idType mono_id))
540         ; return (FunBind fun' inf matches') }
541
542 tcRhs bind@(TcPatBind _ pat' grhss pat_ty)
543   = do  { grhss' <- addErrCtxt (patMonoBindsCtxt pat' grhss) $
544                     tcGRHSsPat grhss (Check pat_ty)
545         ; return (PatBind pat' grhss' pat_ty) }
546
547
548 ---------------------
549 getMonoBindInfo :: Bag (Located TcMonoBind) -> [MonoBindInfo]
550 getMonoBindInfo tc_binds
551   = foldrBag (get_info . unLoc) [] tc_binds
552   where
553     get_info (TcFunBind info _ _ _)  rest = info : rest
554     get_info (TcPatBind infos _ _ _) rest = infos ++ rest
555 \end{code}
556
557
558 %************************************************************************
559 %*                                                                      *
560 \subsection{getTyVarsToGen}
561 %*                                                                      *
562 %************************************************************************
563
564 Type signatures are tricky.  Consider
565
566   x :: [a]
567   y :: b
568   (x,y,z) = ([y,z], z, head x)
569
570 Here, x and y have type sigs, which go into the environment.  We used to
571 instantiate their types with skolem constants, and push those types into
572 the RHS, so we'd typecheck the RHS with type
573         ( [a*], b*, c )
574 where a*, b* are skolem constants, and c is an ordinary meta type varible.
575
576 The trouble is that the occurrences of z in the RHS force a* and b* to 
577 be the *same*, so we can't make them into skolem constants that don't unify
578 with each other.  Alas.
579
580 Current solution: don't use skolems at all.  Instead, instantiate the type
581 signatures with ordinary meta type variables, and check at the end that
582 each group has remained distinct.
583
584
585 \begin{code}
586 tcTySigs :: [LSig Name] -> TcM [TcSigInfo]
587 -- The trick here is that all the signatures should have the same
588 -- context, and we want to share type variables for that context, so that
589 -- all the right hand sides agree a common vocabulary for their type
590 -- constraints
591 tcTySigs [] = return []
592
593 tcTySigs sigs
594   = do  { (tc_sig1 : tc_sigs) <- mappM tcTySig sigs
595         ; mapM (check_ctxt tc_sig1) tc_sigs
596         ; return (tc_sig1 : tc_sigs) }
597   where
598         -- Check tha all the signature contexts are the same
599         -- The type signatures on a mutually-recursive group of definitions
600         -- must all have the same context (or none).
601         --
602         -- We unify them because, with polymorphic recursion, their types
603         -- might not otherwise be related.  This is a rather subtle issue.
604     check_ctxt :: TcSigInfo -> TcSigInfo -> TcM ()
605     check_ctxt sig1@(TcSigInfo { sig_theta = theta1 }) sig@(TcSigInfo { sig_theta = theta })
606         = setSrcSpan (instLocSrcSpan (sig_loc sig))     $
607           addErrCtxt (sigContextsCtxt sig1 sig)         $
608           unifyTheta theta1 theta
609
610
611 tcTySig :: LSig Name -> TcM TcSigInfo
612 tcTySig (L span (Sig (L _ name) ty))
613   = setSrcSpan span             $
614     do  { sigma_ty <- tcHsSigType (FunSigCtxt name) ty
615         ; let rigid_info = SigSkol name
616               poly_id    = mkLocalId name sigma_ty
617
618                 -- The scoped names are the ones explicitly mentioned
619                 -- in the HsForAll.  (There may be more in sigma_ty, because
620                 -- of nested type synonyms.  See Note [Scoped] with TcSigInfo.)
621               scoped_names = case ty of
622                                 L _ (HsForAllTy _ tvs _ _) -> hsLTyVarNames tvs
623                                 other                      -> []
624
625         ; (tvs, theta, tau) <- tcInstSigType sigma_ty
626         ; loc <- getInstLoc (SigOrigin rigid_info)
627         ; return (TcSigInfo { sig_id = poly_id, sig_scoped = scoped_names,
628                               sig_tvs = tvs, sig_theta = theta, sig_tau = tau, 
629                               sig_loc = loc }) }
630 \end{code}
631
632 \begin{code}
633 generalise :: TopLevelFlag -> Bool -> [MonoBindInfo] -> [TcSigInfo] -> [Inst]
634            -> TcM ([TcTyVar], TcDictBinds, [TcId])
635 generalise top_lvl is_unrestricted mono_infos sigs lie_req
636   | not is_unrestricted -- RESTRICTED CASE
637   =     -- Check signature contexts are empty 
638     do  { checkTc (all is_mono_sig sigs)
639                   (restrictedBindCtxtErr bndr_names)
640
641         -- Now simplify with exactly that set of tyvars
642         -- We have to squash those Methods
643         ; (qtvs, binds) <- tcSimplifyRestricted doc top_lvl bndr_names 
644                                                 tau_tvs lie_req
645
646         -- Check that signature type variables are OK
647         ; final_qtvs <- checkSigsTyVars qtvs sigs
648
649         ; return (final_qtvs, binds, []) }
650
651   | null sigs   -- UNRESTRICTED CASE, NO TYPE SIGS
652   = tcSimplifyInfer doc tau_tvs lie_req
653
654   | otherwise   -- UNRESTRICTED CASE, WITH TYPE SIGS
655   = do  { let sig1 = head sigs
656         ; sig_lie <- newDictsAtLoc (sig_loc sig1) (sig_theta sig1)
657         ; let   -- The "sig_avails" is the stuff available.  We get that from
658                 -- the context of the type signature, BUT ALSO the lie_avail
659                 -- so that polymorphic recursion works right (see comments at end of fn)
660                 local_meths = [mkMethInst sig mono_id | (_, Just sig, mono_id) <- mono_infos]
661                 sig_avails = sig_lie ++ local_meths
662
663         -- Check that the needed dicts can be
664         -- expressed in terms of the signature ones
665         ; (forall_tvs, dict_binds) <- tcSimplifyInferCheck doc tau_tvs sig_avails lie_req
666         
667         -- Check that signature type variables are OK
668         ; final_qtvs <- checkSigsTyVars forall_tvs sigs
669
670         ; returnM (final_qtvs, dict_binds, map instToId sig_lie) }
671
672   where
673     bndr_names = bndrNames mono_infos
674     tau_tvs = foldr (unionVarSet . tyVarsOfType . getMonoType) emptyVarSet mono_infos
675     is_mono_sig sig = null (sig_theta sig)
676     doc = ptext SLIT("type signature(s) for") <+> pprBinders bndr_names
677
678     mkMethInst (TcSigInfo { sig_id = poly_id, sig_tvs = tvs, 
679                             sig_theta = theta, sig_tau = tau, sig_loc = loc }) mono_id
680       = Method mono_id poly_id (mkTyVarTys tvs) theta tau loc
681
682 checkSigsTyVars :: [TcTyVar] -> [TcSigInfo] -> TcM [TcTyVar]
683 checkSigsTyVars qtvs sigs 
684   = do  { gbl_tvs <- tcGetGlobalTyVars
685         ; sig_tvs_s <- mappM (check_sig gbl_tvs) sigs
686
687         ; let   -- Sigh.  Make sure that all the tyvars in the type sigs
688                 -- appear in the returned ty var list, which is what we are
689                 -- going to generalise over.  Reason: we occasionally get
690                 -- silly types like
691                 --      type T a = () -> ()
692                 --      f :: T a
693                 --      f () = ()
694                 -- Here, 'a' won't appear in qtvs, so we have to add it
695                 sig_tvs = foldl extendVarSetList emptyVarSet sig_tvs_s
696                 all_tvs = varSetElems (extendVarSetList sig_tvs qtvs)
697         ; returnM all_tvs }
698   where
699     check_sig gbl_tvs (TcSigInfo {sig_id = id, sig_tvs = tvs, 
700                                   sig_theta = theta, sig_tau = tau})
701       = addErrCtxt (ptext SLIT("In the type signature for") <+> quotes (ppr id))        $
702         addErrCtxtM (sigCtxt id tvs theta tau)                                          $
703         do { tvs' <- checkDistinctTyVars tvs
704            ; ifM (any (`elemVarSet` gbl_tvs) tvs')
705                  (bleatEscapedTvs gbl_tvs tvs tvs') 
706            ; return tvs' }
707
708 checkDistinctTyVars :: [TcTyVar] -> TcM [TcTyVar]
709 -- (checkDistinctTyVars tvs) checks that the tvs from one type signature
710 -- are still all type variables, and all distinct from each other.  
711 -- It returns a zonked set of type variables.
712 -- For example, if the type sig is
713 --      f :: forall a b. a -> b -> b
714 -- we want to check that 'a' and 'b' haven't 
715 --      (a) been unified with a non-tyvar type
716 --      (b) been unified with each other (all distinct)
717
718 checkDistinctTyVars sig_tvs
719   = do  { zonked_tvs <- mapM zonk_one sig_tvs
720         ; foldlM check_dup emptyVarEnv (sig_tvs `zip` zonked_tvs)
721         ; return zonked_tvs }
722   where
723     zonk_one sig_tv = do { ty <- zonkTcTyVar sig_tv
724                          ; case tcGetTyVar_maybe ty of
725                              Just tv' -> return tv'
726                              Nothing  -> bomb_out sig_tv "a type" ty }
727
728     check_dup :: TyVarEnv TcTyVar -> (TcTyVar, TcTyVar) -> TcM (TyVarEnv TcTyVar)
729         -- The TyVarEnv maps each zonked type variable back to its
730         -- corresponding user-written signature type variable
731     check_dup acc (sig_tv, zonked_tv)
732         = case lookupVarEnv acc zonked_tv of
733                 Just sig_tv' -> bomb_out sig_tv "another quantified type variable" 
734                                                 (mkTyVarTy sig_tv')
735
736                 Nothing -> return (extendVarEnv acc zonked_tv sig_tv)
737
738     bomb_out sig_tv doc ty 
739        = failWithTc (ptext SLIT("Quantified type variable") <+> quotes (ppr tidy_tv) 
740                      <+> ptext SLIT("is unified with") <+> text doc <+> ppr tidy_ty)
741        where
742          (env1,  tidy_tv) = tidyOpenTyVar emptyTidyEnv sig_tv
743          (_env2, tidy_ty) = tidyOpenType  env1         ty
744 \end{code}    
745
746
747 @getTyVarsToGen@ decides what type variables to generalise over.
748
749 For a "restricted group" -- see the monomorphism restriction
750 for a definition -- we bind no dictionaries, and
751 remove from tyvars_to_gen any constrained type variables
752
753 *Don't* simplify dicts at this point, because we aren't going
754 to generalise over these dicts.  By the time we do simplify them
755 we may well know more.  For example (this actually came up)
756         f :: Array Int Int
757         f x = array ... xs where xs = [1,2,3,4,5]
758 We don't want to generate lots of (fromInt Int 1), (fromInt Int 2)
759 stuff.  If we simplify only at the f-binding (not the xs-binding)
760 we'll know that the literals are all Ints, and we can just produce
761 Int literals!
762
763 Find all the type variables involved in overloading, the
764 "constrained_tyvars".  These are the ones we *aren't* going to
765 generalise.  We must be careful about doing this:
766
767  (a) If we fail to generalise a tyvar which is not actually
768         constrained, then it will never, ever get bound, and lands
769         up printed out in interface files!  Notorious example:
770                 instance Eq a => Eq (Foo a b) where ..
771         Here, b is not constrained, even though it looks as if it is.
772         Another, more common, example is when there's a Method inst in
773         the LIE, whose type might very well involve non-overloaded
774         type variables.
775   [NOTE: Jan 2001: I don't understand the problem here so I'm doing 
776         the simple thing instead]
777
778  (b) On the other hand, we mustn't generalise tyvars which are constrained,
779         because we are going to pass on out the unmodified LIE, with those
780         tyvars in it.  They won't be in scope if we've generalised them.
781
782 So we are careful, and do a complete simplification just to find the
783 constrained tyvars. We don't use any of the results, except to
784 find which tyvars are constrained.
785
786 \begin{code}
787 isUnRestrictedGroup :: LHsBinds Name -> [TcSigInfo] -> TcM Bool
788 isUnRestrictedGroup binds sigs
789   = do  { mono_restriction <- doptM Opt_MonomorphismRestriction
790         ; return (not mono_restriction || all_unrestricted) }
791   where 
792     all_unrestricted = all (unrestricted . unLoc) (bagToList binds)
793     tysig_names      = map (idName . sig_id) sigs
794
795     unrestricted (PatBind other _ _)   = False
796     unrestricted (VarBind v _)         = v `is_elem` tysig_names
797     unrestricted (FunBind v _ matches) = unrestricted_match matches 
798                                          || unLoc v `is_elem` tysig_names
799
800     unrestricted_match (MatchGroup (L _ (Match [] _ _) : _) _) = False
801         -- No args => like a pattern binding
802     unrestricted_match other              = True
803         -- Some args => a function binding
804
805 is_elem v vs = isIn "isUnResMono" v vs
806 \end{code}
807
808
809 %************************************************************************
810 %*                                                                      *
811 \subsection{SPECIALIZE pragmas}
812 %*                                                                      *
813 %************************************************************************
814
815 @tcSpecSigs@ munches up the specialisation "signatures" that arise through *user*
816 pragmas.  It is convenient for them to appear in the @[RenamedSig]@
817 part of a binding because then the same machinery can be used for
818 moving them into place as is done for type signatures.
819
820 They look like this:
821
822 \begin{verbatim}
823         f :: Ord a => [a] -> b -> b
824         {-# SPECIALIZE f :: [Int] -> b -> b #-}
825 \end{verbatim}
826
827 For this we generate:
828 \begin{verbatim}
829         f* = /\ b -> let d1 = ...
830                      in f Int b d1
831 \end{verbatim}
832
833 where f* is a SpecPragmaId.  The **sole** purpose of SpecPragmaIds is to
834 retain a right-hand-side that the simplifier will otherwise discard as
835 dead code... the simplifier has a flag that tells it not to discard
836 SpecPragmaId bindings.
837
838 In this case the f* retains a call-instance of the overloaded
839 function, f, (including appropriate dictionaries) so that the
840 specialiser will subsequently discover that there's a call of @f@ at
841 Int, and will create a specialisation for @f@.  After that, the
842 binding for @f*@ can be discarded.
843
844 We used to have a form
845         {-# SPECIALISE f :: <type> = g #-}
846 which promised that g implemented f at <type>, but we do that with 
847 a RULE now:
848         {-# RULES (f::<type>) = g #-}
849
850 \begin{code}
851 tcSpecSigs :: [LSig Name] -> TcM (LHsBinds TcId)
852 tcSpecSigs (L loc (SpecSig (L nm_loc name) poly_ty) : sigs)
853   =     -- SPECIALISE f :: forall b. theta => tau  =  g
854     setSrcSpan loc                              $
855     addErrCtxt (valSpecSigCtxt name poly_ty)    $
856
857         -- Get and instantiate its alleged specialised type
858     tcHsSigType (FunSigCtxt name) poly_ty       `thenM` \ sig_ty ->
859
860         -- Check that f has a more general type, and build a RHS for
861         -- the spec-pragma-id at the same time
862     getLIE (tcCheckSigma (L nm_loc (HsVar name)) sig_ty)        `thenM` \ (spec_expr, spec_lie) ->
863
864         -- Squeeze out any Methods (see comments with tcSimplifyToDicts)
865     tcSimplifyToDicts spec_lie                  `thenM` \ spec_binds ->
866
867         -- Just specialise "f" by building a SpecPragmaId binding
868         -- It is the thing that makes sure we don't prematurely 
869         -- dead-code-eliminate the binding we are really interested in.
870     newLocalName name                   `thenM` \ spec_name ->
871     let
872         spec_bind = VarBind (mkSpecPragmaId spec_name sig_ty)
873                                 (mkHsLet spec_binds spec_expr)
874     in
875
876         -- Do the rest and combine
877     tcSpecSigs sigs                     `thenM` \ binds_rest ->
878     returnM (binds_rest `snocBag` L loc spec_bind)
879
880 tcSpecSigs (other_sig : sigs) = tcSpecSigs sigs
881 tcSpecSigs []                 = returnM emptyLHsBinds
882 \end{code}
883
884 %************************************************************************
885 %*                                                                      *
886 \subsection[TcBinds-errors]{Error contexts and messages}
887 %*                                                                      *
888 %************************************************************************
889
890
891 \begin{code}
892 -- This one is called on LHS, when pat and grhss are both Name 
893 -- and on RHS, when pat is TcId and grhss is still Name
894 patMonoBindsCtxt pat grhss
895   = hang (ptext SLIT("In a pattern binding:")) 4 (pprPatBind pat grhss)
896
897 -----------------------------------------------
898 valSpecSigCtxt v ty
899   = sep [ptext SLIT("In a SPECIALIZE pragma for a value:"),
900          nest 4 (ppr v <+> dcolon <+> ppr ty)]
901
902 -----------------------------------------------
903 sigContextsCtxt sig1 sig2
904   = vcat [ptext SLIT("When matching the contexts of the signatures for"), 
905           nest 2 (vcat [ppr id1 <+> dcolon <+> ppr (idType id1),
906                         ppr id2 <+> dcolon <+> ppr (idType id2)]),
907           ptext SLIT("The signature contexts in a mutually recursive group should all be identical")]
908   where
909     id1 = sig_id sig1
910     id2 = sig_id sig2
911
912
913 -----------------------------------------------
914 unliftedBindErr flavour mbind
915   = hang (text flavour <+> ptext SLIT("bindings for unlifted types aren't allowed:"))
916          4 (ppr mbind)
917
918 -----------------------------------------------
919 existentialExplode mbinds
920   = hang (vcat [text "My brain just exploded.",
921                 text "I can't handle pattern bindings for existentially-quantified constructors.",
922                 text "In the binding group"])
923         4 (ppr mbinds)
924
925 -----------------------------------------------
926 restrictedBindCtxtErr binder_names
927   = hang (ptext SLIT("Illegal overloaded type signature(s)"))
928        4 (vcat [ptext SLIT("in a binding group for") <+> pprBinders binder_names,
929                 ptext SLIT("that falls under the monomorphism restriction")])
930
931 genCtxt binder_names
932   = ptext SLIT("When generalising the type(s) for") <+> pprBinders binder_names
933 \end{code}