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