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