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