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