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