b5bbeb1940e47b9cb989922a9c0c96f622df59ad
[ghc-hetmet.git] / compiler / typecheck / TcBinds.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5 \section[TcBinds]{TcBinds}
6
7 \begin{code}
8 module TcBinds ( tcLocalBinds, tcTopBinds, 
9                  tcHsBootSigs, tcPolyBinds,
10                  PragFun, tcSpecPrags, tcVectDecls, mkPragFun, 
11                  TcSigInfo(..), SigFun, mkSigFun,
12                  badBootDeclErr ) where
13
14 import {-# SOURCE #-} TcMatches ( tcGRHSsPat, tcMatchesFun )
15 import {-# SOURCE #-} TcExpr  ( tcMonoExpr )
16
17 import DynFlags
18 import HsSyn
19
20 import TcRnMonad
21 import TcEnv
22 import TcUnify
23 import TcSimplify
24 import TcHsType
25 import TcPat
26 import TcMType
27 import TcType
28 import Coercion
29 import TysPrim
30 import Id
31 import Var
32 import Name
33 import NameSet
34 import NameEnv
35 import SrcLoc
36 import Bag
37 import ListSetOps
38 import ErrUtils
39 import Digraph
40 import Maybes
41 import Util
42 import BasicTypes
43 import Outputable
44 import FastString
45
46 import Control.Monad
47
48 #include "HsVersions.h"
49 \end{code}
50
51
52 %************************************************************************
53 %*                                                                      *
54 \subsection{Type-checking bindings}
55 %*                                                                      *
56 %************************************************************************
57
58 @tcBindsAndThen@ typechecks a @HsBinds@.  The "and then" part is because
59 it needs to know something about the {\em usage} of the things bound,
60 so that it can create specialisations of them.  So @tcBindsAndThen@
61 takes a function which, given an extended environment, E, typechecks
62 the scope of the bindings returning a typechecked thing and (most
63 important) an LIE.  It is this LIE which is then used as the basis for
64 specialising the things bound.
65
66 @tcBindsAndThen@ also takes a "combiner" which glues together the
67 bindings and the "thing" to make a new "thing".
68
69 The real work is done by @tcBindWithSigsAndThen@.
70
71 Recursive and non-recursive binds are handled in essentially the same
72 way: because of uniques there are no scoping issues left.  The only
73 difference is that non-recursive bindings can bind primitive values.
74
75 Even for non-recursive binding groups we add typings for each binder
76 to the LVE for the following reason.  When each individual binding is
77 checked the type of its LHS is unified with that of its RHS; and
78 type-checking the LHS of course requires that the binder is in scope.
79
80 At the top-level the LIE is sure to contain nothing but constant
81 dictionaries, which we resolve at the module level.
82
83 \begin{code}
84 tcTopBinds :: HsValBinds Name 
85            -> TcM ( LHsBinds TcId       -- Typechecked bindings
86                   , [LTcSpecPrag]       -- SPECIALISE prags for imported Ids
87                   , TcLclEnv)           -- Augmented environment
88
89         -- Note: returning the TcLclEnv is more than we really
90         --       want.  The bit we care about is the local bindings
91         --       and the free type variables thereof
92 tcTopBinds binds
93   = do  { (ValBindsOut prs sigs, env) <- tcValBinds TopLevel binds getLclEnv
94         ; let binds = foldr (unionBags . snd) emptyBag prs
95         ; specs <- tcImpPrags sigs
96         ; return (binds, specs, env) }
97         -- The top level bindings are flattened into a giant 
98         -- implicitly-mutually-recursive LHsBinds
99
100 tcHsBootSigs :: HsValBinds Name -> TcM [Id]
101 -- A hs-boot file has only one BindGroup, and it only has type
102 -- signatures in it.  The renamer checked all this
103 tcHsBootSigs (ValBindsOut binds sigs)
104   = do  { checkTc (null binds) badBootDeclErr
105         ; mapM (addLocM tc_boot_sig) (filter isTypeLSig sigs) }
106   where
107     tc_boot_sig (TypeSig (L _ name) ty)
108       = do { sigma_ty <- tcHsSigType (FunSigCtxt name) ty
109            ; return (mkVanillaGlobal name sigma_ty) }
110         -- Notice that we make GlobalIds, not LocalIds
111     tc_boot_sig s = pprPanic "tcHsBootSigs/tc_boot_sig" (ppr s)
112 tcHsBootSigs groups = pprPanic "tcHsBootSigs" (ppr groups)
113
114 badBootDeclErr :: Message
115 badBootDeclErr = ptext (sLit "Illegal declarations in an hs-boot file")
116
117 ------------------------
118 tcLocalBinds :: HsLocalBinds Name -> TcM thing
119              -> TcM (HsLocalBinds TcId, thing)
120
121 tcLocalBinds EmptyLocalBinds thing_inside 
122   = do  { thing <- thing_inside
123         ; return (EmptyLocalBinds, thing) }
124
125 tcLocalBinds (HsValBinds binds) thing_inside
126   = do  { (binds', thing) <- tcValBinds NotTopLevel binds thing_inside
127         ; return (HsValBinds binds', thing) }
128
129 tcLocalBinds (HsIPBinds (IPBinds ip_binds _)) thing_inside
130   = do  { (given_ips, ip_binds') <- mapAndUnzipM (wrapLocSndM tc_ip_bind) ip_binds
131
132         -- If the binding binds ?x = E, we  must now 
133         -- discharge any ?x constraints in expr_lie
134         -- See Note [Implicit parameter untouchables]
135         ; (ev_binds, result) <- checkConstraints (IPSkol ips) 
136                                   [] given_ips thing_inside
137
138         ; return (HsIPBinds (IPBinds ip_binds' ev_binds), result) }
139   where
140     ips = [ip | L _ (IPBind ip _) <- ip_binds]
141
142         -- I wonder if we should do these one at at time
143         -- Consider     ?x = 4
144         --              ?y = ?x + 1
145     tc_ip_bind (IPBind ip expr) 
146        = do { ty <- newFlexiTyVarTy argTypeKind
147             ; ip_id <- newIP ip ty
148             ; expr' <- tcMonoExpr expr ty
149             ; return (ip_id, (IPBind (IPName ip_id) expr')) }
150 \end{code}
151
152 Note [Implicit parameter untouchables]
153 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
154 We add the type variables in the types of the implicit parameters
155 as untouchables, not so much because we really must not unify them,
156 but rather because we otherwise end up with constraints like this
157     Num alpha, Implic { wanted = alpha ~ Int }
158 The constraint solver solves alpha~Int by unification, but then
159 doesn't float that solved constraint out (it's not an unsolved 
160 wanted.  Result disaster: the (Num alpha) is again solved, this
161 time by defaulting.  No no no.
162
163 However [Oct 10] this is all handled automatically by the 
164 untouchable-range idea.
165
166 \begin{code}
167 tcValBinds :: TopLevelFlag 
168            -> HsValBinds Name -> TcM thing
169            -> TcM (HsValBinds TcId, thing) 
170
171 tcValBinds _ (ValBindsIn binds _) _
172   = pprPanic "tcValBinds" (ppr binds)
173
174 tcValBinds top_lvl (ValBindsOut binds sigs) thing_inside
175   = do  {       -- Typecheck the signature
176         ; let { prag_fn = mkPragFun sigs (foldr (unionBags . snd) emptyBag binds)
177               ; ty_sigs = filter isTypeLSig sigs
178               ; sig_fn  = mkSigFun ty_sigs }
179
180         ; poly_ids <- checkNoErrs (mapAndRecoverM tcTySig ty_sigs)
181                 -- No recovery from bad signatures, because the type sigs
182                 -- may bind type variables, so proceeding without them
183                 -- can lead to a cascade of errors
184                 -- ToDo: this means we fall over immediately if any type sig
185                 -- is wrong, which is over-conservative, see Trac bug #745
186
187                 -- Extend the envt right away with all 
188                 -- the Ids declared with type signatures
189         ; (binds', thing) <- tcExtendIdEnv poly_ids $
190                              tcBindGroups top_lvl sig_fn prag_fn 
191                                           binds thing_inside
192
193         ; return (ValBindsOut binds' sigs, thing) }
194
195 ------------------------
196 tcBindGroups :: TopLevelFlag -> SigFun -> PragFun
197              -> [(RecFlag, LHsBinds Name)] -> TcM thing
198              -> TcM ([(RecFlag, LHsBinds TcId)], thing)
199 -- Typecheck a whole lot of value bindings,
200 -- one strongly-connected component at a time
201 -- Here a "strongly connected component" has the strightforward
202 -- meaning of a group of bindings that mention each other, 
203 -- ignoring type signatures (that part comes later)
204
205 tcBindGroups _ _ _ [] thing_inside
206   = do  { thing <- thing_inside
207         ; return ([], thing) }
208
209 tcBindGroups top_lvl sig_fn prag_fn (group : groups) thing_inside
210   = do  { (group', (groups', thing))
211                 <- tc_group top_lvl sig_fn prag_fn group $ 
212                    tcBindGroups top_lvl sig_fn prag_fn groups thing_inside
213         ; return (group' ++ groups', thing) }
214
215 ------------------------
216 tc_group :: forall thing. 
217             TopLevelFlag -> SigFun -> PragFun
218          -> (RecFlag, LHsBinds Name) -> TcM thing
219          -> TcM ([(RecFlag, LHsBinds TcId)], thing)
220
221 -- Typecheck one strongly-connected component of the original program.
222 -- We get a list of groups back, because there may 
223 -- be specialisations etc as well
224
225 tc_group top_lvl sig_fn prag_fn (NonRecursive, binds) thing_inside
226         -- A single non-recursive binding
227         -- We want to keep non-recursive things non-recursive
228         -- so that we desugar unlifted bindings correctly
229  =  do { (binds1, ids) <- tcPolyBinds top_lvl sig_fn prag_fn NonRecursive NonRecursive
230                                       (bagToList binds)
231        ; thing <- tcExtendIdEnv ids thing_inside
232        ; return ( [(NonRecursive, binds1)], thing) }
233
234 tc_group top_lvl sig_fn prag_fn (Recursive, binds) thing_inside
235   =     -- To maximise polymorphism (assumes -XRelaxedPolyRec), we do a new 
236         -- strongly-connected-component analysis, this time omitting 
237         -- any references to variables with type signatures.
238     do  { traceTc "tc_group rec" (pprLHsBinds binds)
239         ; (binds1, _ids, thing) <- go sccs
240              -- Here is where we should do bindInstsOfLocalFuns
241              -- if we start having Methods again
242         ; return ([(Recursive, binds1)], thing) }
243                 -- Rec them all together
244   where
245     sccs :: [SCC (LHsBind Name)]
246     sccs = stronglyConnCompFromEdgedVertices (mkEdges sig_fn binds)
247
248     go :: [SCC (LHsBind Name)] -> TcM (LHsBinds TcId, [TcId], thing)
249     go (scc:sccs) = do  { (binds1, ids1)        <- tc_scc scc
250                         ; (binds2, ids2, thing) <- tcExtendIdEnv ids1 $ go sccs
251                         ; return (binds1 `unionBags` binds2, ids1 ++ ids2, thing) }
252     go []         = do  { thing <- thing_inside; return (emptyBag, [], thing) }
253
254     tc_scc (AcyclicSCC bind) = tc_sub_group NonRecursive [bind]
255     tc_scc (CyclicSCC binds) = tc_sub_group Recursive    binds
256
257     tc_sub_group = tcPolyBinds top_lvl sig_fn prag_fn Recursive
258
259
260 ------------------------
261 {-
262 bindLocalInsts :: TopLevelFlag
263                -> TcM (LHsBinds TcId, [TcId],    a)
264                -> TcM (LHsBinds TcId, TcEvBinds, a)
265 bindLocalInsts top_lvl thing_inside
266   | isTopLevel top_lvl
267   = do { (binds, _, thing) <- thing_inside; return (binds, emptyBag, thing) }
268         -- For the top level don't bother with all this bindInstsOfLocalFuns stuff. 
269         -- All the top level things are rec'd together anyway, so it's fine to
270         -- leave them to the tcSimplifyTop, and quite a bit faster too
271
272   | otherwise   -- Nested case
273   = do  { ((binds, ids, thing), lie) <- captureConstraints thing_inside
274         ; lie_binds <- bindLocalMethods lie ids
275         ; return (binds, lie_binds, thing) }
276 -}
277
278 ------------------------
279 mkEdges :: SigFun -> LHsBinds Name
280         -> [(LHsBind Name, BKey, [BKey])]
281
282 type BKey  = Int -- Just number off the bindings
283
284 mkEdges sig_fn binds
285   = [ (bind, key, [key | n <- nameSetToList (bind_fvs (unLoc bind)),
286                          Just key <- [lookupNameEnv key_map n], no_sig n ])
287     | (bind, key) <- keyd_binds
288     ]
289   where
290     no_sig :: Name -> Bool
291     no_sig n = isNothing (sig_fn n)
292
293     keyd_binds = bagToList binds `zip` [0::BKey ..]
294
295     key_map :: NameEnv BKey     -- Which binding it comes from
296     key_map = mkNameEnv [(bndr, key) | (L _ bind, key) <- keyd_binds
297                                      , bndr <- bindersOfHsBind bind ]
298
299 bindersOfHsBind :: HsBind Name -> [Name]
300 bindersOfHsBind (PatBind { pat_lhs = pat })  = collectPatBinders pat
301 bindersOfHsBind (FunBind { fun_id = L _ f }) = [f]
302 bindersOfHsBind (AbsBinds {})                = panic "bindersOfHsBind AbsBinds"
303 bindersOfHsBind (VarBind {})                 = panic "bindersOfHsBind VarBind"
304
305 ------------------------
306 tcPolyBinds :: TopLevelFlag -> SigFun -> PragFun
307             -> RecFlag       -- Whether the group is really recursive
308             -> RecFlag       -- Whether it's recursive after breaking
309                              -- dependencies based on type signatures
310             -> [LHsBind Name]
311             -> TcM (LHsBinds TcId, [TcId])
312
313 -- Typechecks a single bunch of bindings all together, 
314 -- and generalises them.  The bunch may be only part of a recursive
315 -- group, because we use type signatures to maximise polymorphism
316 --
317 -- Returns a list because the input may be a single non-recursive binding,
318 -- in which case the dependency order of the resulting bindings is
319 -- important.  
320 -- 
321 -- Knows nothing about the scope of the bindings
322
323 tcPolyBinds top_lvl sig_fn prag_fn rec_group rec_tc bind_list
324   = setSrcSpan loc                              $
325     recoverM (recoveryCode binder_names sig_fn) $ do 
326         -- Set up main recover; take advantage of any type sigs
327
328     { traceTc "------------------------------------------------" empty
329     ; traceTc "Bindings for" (ppr binder_names)
330
331     -- Instantiate the polytypes of any binders that have signatures
332     -- (as determined by sig_fn), returning a TcSigInfo for each
333     ; tc_sig_fn <- tcInstSigs sig_fn binder_names
334
335     ; dflags <- getDOpts
336     ; let plan = decideGeneralisationPlan dflags top_lvl binder_names bind_list tc_sig_fn
337     ; traceTc "Generalisation plan" (ppr plan)
338     ; (binds, poly_ids) <- case plan of
339          NoGen         -> tcPolyNoGen tc_sig_fn prag_fn rec_tc bind_list
340          InferGen mono -> tcPolyInfer top_lvl mono tc_sig_fn prag_fn rec_tc bind_list
341          CheckGen sig  -> tcPolyCheck sig prag_fn rec_tc bind_list
342
343         -- Check whether strict bindings are ok
344         -- These must be non-recursive etc, and are not generalised
345         -- They desugar to a case expression in the end
346     ; checkStrictBinds top_lvl rec_group bind_list poly_ids
347
348     ; return (binds, poly_ids) }
349   where
350     binder_names = collectHsBindListBinders bind_list
351     loc = foldr1 combineSrcSpans (map getLoc bind_list)
352          -- The mbinds have been dependency analysed and 
353          -- may no longer be adjacent; so find the narrowest
354          -- span that includes them all
355
356 ------------------
357 tcPolyNoGen 
358   :: TcSigFun -> PragFun
359   -> RecFlag       -- Whether it's recursive after breaking
360                    -- dependencies based on type signatures
361   -> [LHsBind Name]
362   -> TcM (LHsBinds TcId, [TcId])
363 -- No generalisation whatsoever
364
365 tcPolyNoGen tc_sig_fn prag_fn rec_tc bind_list
366   = do { (binds', mono_infos) <- tcMonoBinds tc_sig_fn (LetGblBndr prag_fn) 
367                                              rec_tc bind_list
368        ; mono_ids' <- mapM tc_mono_info mono_infos
369        ; return (binds', mono_ids') }
370   where
371     tc_mono_info (name, _, mono_id)
372       = do { mono_ty' <- zonkTcTypeCarefully (idType mono_id)
373              -- Zonk, mainly to expose unboxed types to checkStrictBinds
374            ; let mono_id' = setIdType mono_id mono_ty'
375            ; _specs <- tcSpecPrags mono_id' (prag_fn name)
376            ; return mono_id' }
377            -- NB: tcPrags generates error messages for
378            --     specialisation pragmas for non-overloaded sigs
379            -- Indeed that is why we call it here!
380            -- So we can safely ignore _specs
381
382 ------------------
383 tcPolyCheck :: TcSigInfo -> PragFun
384             -> RecFlag       -- Whether it's recursive after breaking
385                              -- dependencies based on type signatures
386             -> [LHsBind Name]
387             -> TcM (LHsBinds TcId, [TcId])
388 -- There is just one binding, 
389 --   it binds a single variable,
390 --   it has a signature,
391 tcPolyCheck sig@(TcSigInfo { sig_id = id, sig_tvs = tvs, sig_scoped = scoped
392                            , sig_theta = theta, sig_tau = tau })
393     prag_fn rec_tc bind_list
394   = do { ev_vars <- newEvVars theta
395        ; let skol_info = SigSkol (FunSigCtxt (idName id)) (mkPhiTy theta tau)
396        ; (ev_binds, (binds', [mono_info])) 
397             <- checkConstraints skol_info tvs ev_vars $
398                tcExtendTyVarEnv2 (scoped `zip` mkTyVarTys tvs)    $
399                tcMonoBinds (\_ -> Just sig) LetLclBndr rec_tc bind_list
400
401        ; export <- mkExport prag_fn tvs theta mono_info
402
403        ; loc <- getSrcSpanM
404        ; let (_, poly_id, _, _) = export
405              abs_bind = L loc $ AbsBinds 
406                         { abs_tvs = tvs
407                         , abs_ev_vars = ev_vars, abs_ev_binds = ev_binds
408                         , abs_exports = [export], abs_binds = binds' }
409        ; return (unitBag abs_bind, [poly_id]) }
410
411 ------------------
412 tcPolyInfer 
413   :: TopLevelFlag 
414   -> Bool         -- True <=> apply the monomorphism restriction
415   -> TcSigFun -> PragFun
416   -> RecFlag       -- Whether it's recursive after breaking
417                    -- dependencies based on type signatures
418   -> [LHsBind Name]
419   -> TcM (LHsBinds TcId, [TcId])
420 tcPolyInfer top_lvl mono tc_sig_fn prag_fn rec_tc bind_list
421   = do { ((binds', mono_infos), wanted) 
422              <- captureConstraints $
423                 tcMonoBinds tc_sig_fn LetLclBndr rec_tc bind_list
424
425        ; unifyCtxts [sig | (_, Just sig, _) <- mono_infos] 
426
427        ; let name_taus = [(name, idType mono_id) | (name, _, mono_id) <- mono_infos]
428        ; (qtvs, givens, ev_binds) <- simplifyInfer top_lvl mono name_taus wanted
429
430        ; exports <- mapM (mkExport prag_fn qtvs (map evVarPred givens))
431                     mono_infos
432
433        ; let poly_ids = [poly_id | (_, poly_id, _, _) <- exports]
434        ; traceTc "Binding:" (ppr (poly_ids `zip` map idType poly_ids))
435
436        ; loc <- getSrcSpanM
437        ; let abs_bind = L loc $ AbsBinds { abs_tvs = qtvs
438                                          , abs_ev_vars = givens, abs_ev_binds = ev_binds
439                                          , abs_exports = exports, abs_binds = binds' }
440
441        ; return (unitBag abs_bind, poly_ids)   -- poly_ids are guaranteed zonked by mkExport
442   }
443
444
445 --------------
446 mkExport :: PragFun -> [TyVar] -> TcThetaType
447          -> MonoBindInfo
448          -> TcM ([TyVar], Id, Id, TcSpecPrags)
449 -- mkExport generates exports with 
450 --      zonked type variables, 
451 --      zonked poly_ids
452 -- The former is just because no further unifications will change
453 -- the quantified type variables, so we can fix their final form
454 -- right now.
455 -- The latter is needed because the poly_ids are used to extend the
456 -- type environment; see the invariant on TcEnv.tcExtendIdEnv 
457
458 -- Pre-condition: the inferred_tvs are already zonked
459
460 mkExport prag_fn inferred_tvs theta
461          (poly_name, mb_sig, mono_id)
462   = do  { (tvs, poly_id) <- mk_poly_id mb_sig
463                 -- poly_id has a zonked type
464
465         ; poly_id' <- addInlinePrags poly_id prag_sigs
466
467         ; spec_prags <- tcSpecPrags poly_id prag_sigs
468                 -- tcPrags requires a zonked poly_id
469
470         ; return (tvs, poly_id', mono_id, SpecPrags spec_prags) }
471   where
472     prag_sigs = prag_fn poly_name
473     poly_ty = mkSigmaTy inferred_tvs theta (idType mono_id)
474
475     mk_poly_id Nothing    = do { poly_ty' <- zonkTcTypeCarefully poly_ty
476                                ; return (inferred_tvs, mkLocalId poly_name poly_ty') }
477     mk_poly_id (Just sig) = do { tvs <- mapM zonk_tv (sig_tvs sig)
478                                ; return (tvs,  sig_id sig) }
479
480     zonk_tv tv = do { ty <- zonkTcTyVar tv; return (tcGetTyVar "mkExport" ty) }
481
482 ------------------------
483 type PragFun = Name -> [LSig Name]
484
485 mkPragFun :: [LSig Name] -> LHsBinds Name -> PragFun
486 mkPragFun sigs binds = \n -> lookupNameEnv prag_env n `orElse` []
487   where
488     prs = mapCatMaybes get_sig sigs
489
490     get_sig :: LSig Name -> Maybe (Located Name, LSig Name)
491     get_sig (L l (SpecSig nm ty inl)) = Just (nm, L l $ SpecSig  nm ty (add_arity nm inl))
492     get_sig (L l (InlineSig nm inl))  = Just (nm, L l $ InlineSig nm   (add_arity nm inl))
493     get_sig _                         = Nothing
494
495     add_arity (L _ n) inl_prag   -- Adjust inl_sat field to match visible arity of function
496       | Just ar <- lookupNameEnv ar_env n,
497         Inline <- inl_inline inl_prag     = inl_prag { inl_sat = Just ar }
498         -- add arity only for real INLINE pragmas, not INLINABLE
499       | otherwise                         = inl_prag
500
501     prag_env :: NameEnv [LSig Name]
502     prag_env = foldl add emptyNameEnv prs
503     add env (L _ n,p) = extendNameEnv_Acc (:) singleton env n p
504
505     -- ar_env maps a local to the arity of its definition
506     ar_env :: NameEnv Arity
507     ar_env = foldrBag lhsBindArity emptyNameEnv binds
508
509 lhsBindArity :: LHsBind Name -> NameEnv Arity -> NameEnv Arity
510 lhsBindArity (L _ (FunBind { fun_id = id, fun_matches = ms })) env
511   = extendNameEnv env (unLoc id) (matchGroupArity ms)
512 lhsBindArity _ env = env        -- PatBind/VarBind
513
514 ------------------
515 tcSpecPrags :: Id -> [LSig Name]
516             -> TcM [LTcSpecPrag]
517 -- Add INLINE and SPECIALSE pragmas
518 --    INLINE prags are added to the (polymorphic) Id directly
519 --    SPECIALISE prags are passed to the desugarer via TcSpecPrags
520 -- Pre-condition: the poly_id is zonked
521 -- Reason: required by tcSubExp
522 tcSpecPrags poly_id prag_sigs
523   = do { unless (null bad_sigs) warn_discarded_sigs
524        ; mapAndRecoverM (wrapLocM (tcSpec poly_id)) spec_sigs }
525   where
526     spec_sigs = filter isSpecLSig prag_sigs
527     bad_sigs  = filter is_bad_sig prag_sigs
528     is_bad_sig s = not (isSpecLSig s || isInlineLSig s)
529
530     warn_discarded_sigs = warnPrags poly_id bad_sigs $
531                           ptext (sLit "Discarding unexpected pragmas for")
532
533
534 --------------
535 tcSpec :: TcId -> Sig Name -> TcM TcSpecPrag
536 tcSpec poly_id prag@(SpecSig _ hs_ty inl) 
537   -- The Name in the SpecSig may not be the same as that of the poly_id
538   -- Example: SPECIALISE for a class method: the Name in the SpecSig is
539   --          for the selector Id, but the poly_id is something like $cop
540   = addErrCtxt (spec_ctxt prag) $
541     do  { spec_ty <- tcHsSigType sig_ctxt hs_ty
542         ; warnIf (not (isOverloadedTy poly_ty || isInlinePragma inl))
543                  (ptext (sLit "SPECIALISE pragma for non-overloaded function") <+> quotes (ppr poly_id))
544                   -- Note [SPECIALISE pragmas]
545         ; wrap <- tcSubType origin sig_ctxt (idType poly_id) spec_ty
546         ; return (SpecPrag poly_id wrap inl) }
547   where
548     name      = idName poly_id
549     poly_ty   = idType poly_id
550     origin    = SpecPragOrigin name
551     sig_ctxt  = FunSigCtxt name
552     spec_ctxt prag = hang (ptext (sLit "In the SPECIALISE pragma")) 2 (ppr prag)
553
554 tcSpec _ prag = pprPanic "tcSpec" (ppr prag)
555
556 --------------
557 tcImpPrags :: [LSig Name] -> TcM [LTcSpecPrag]
558 -- SPECIALISE pragamas for imported things
559 tcImpPrags prags
560   = do { this_mod <- getModule
561        ; dflags <- getDOpts
562        ; if (not_specialising dflags) then
563             return []
564          else
565             mapAndRecoverM (wrapLocM tcImpSpec) 
566             [L loc (name,prag) | (L loc prag@(SpecSig (L _ name) _ _)) <- prags
567                                , not (nameIsLocalOrFrom this_mod name) ] }
568   where
569     -- Ignore SPECIALISE pragmas for imported things
570     -- when we aren't specialising, or when we aren't generating
571     -- code.  The latter happens when Haddocking the base library;
572     -- we don't wnat complaints about lack of INLINABLE pragmas 
573     not_specialising dflags
574       | not (dopt Opt_Specialise dflags) = True
575       | otherwise = case hscTarget dflags of
576                       HscNothing -> True
577                       HscInterpreted -> True
578                       _other         -> False
579
580 tcImpSpec :: (Name, Sig Name) -> TcM TcSpecPrag
581 tcImpSpec (name, prag)
582  = do { id <- tcLookupId name
583       ; unless (isAnyInlinePragma (idInlinePragma id))
584                (addWarnTc (impSpecErr name))
585       ; tcSpec id prag }
586
587 impSpecErr :: Name -> SDoc
588 impSpecErr name
589   = hang (ptext (sLit "You cannot SPECIALISE") <+> quotes (ppr name))
590        2 (vcat [ ptext (sLit "because its definition has no INLINE/INLINABLE pragma")
591                , parens $ sep 
592                    [ ptext (sLit "or its defining module") <+> quotes (ppr mod)
593                    , ptext (sLit "was compiled without -O")]])
594   where
595     mod = nameModule name
596
597 --------------
598 tcVectDecls :: [LVectDecl Name] -> TcM ([LVectDecl TcId])
599 tcVectDecls decls 
600   = do { decls' <- mapM (wrapLocM tcVect) decls
601        ; let ids  = map lvectDeclName decls'
602              dups = findDupsEq (==) ids
603        ; mapM_ reportVectDups dups
604        ; traceTcConstraints "End of tcVectDecls"
605        ; return decls'
606        }
607   where
608     reportVectDups (first:_second:_more) 
609       = addErrAt (getSrcSpan first) $
610           ptext (sLit "Duplicate vectorisation declarations for") <+> ppr first
611     reportVectDups _ = return ()
612
613 --------------
614 tcVect :: VectDecl Name -> TcM (VectDecl TcId)
615 -- We can't typecheck the expression of a vectorisation declaration against the vectorised type
616 -- of the original definition as this requires internals of the vectoriser not available during
617 -- type checking.  Instead, we infer the type of the expression and leave it to the vectoriser
618 -- to check the compatibility of the Core types.
619 tcVect (HsVect name Nothing)
620   = addErrCtxt (vectCtxt name) $
621     do { id <- wrapLocM tcLookupId name
622        ; return $ HsVect id Nothing
623        }
624 tcVect (HsVect name@(L loc _) (Just rhs))
625   = addErrCtxt (vectCtxt name) $
626     do { _id <- wrapLocM tcLookupId name     -- need to ensure that the name is already defined
627
628          -- turn the vectorisation declaration into a single non-recursive binding
629        ; let bind    = L loc $ mkFunBind name [mkSimpleMatch [] rhs] 
630              sigFun  = const Nothing
631              pragFun = mkPragFun [] (unitBag bind)
632
633          -- perform type inference (including generalisation)
634        ; (binds, [id']) <- tcPolyInfer TopLevel False sigFun pragFun NonRecursive [bind]
635
636        ; traceTc "tcVect inferred type" $ ppr (varType id')
637        ; traceTc "tcVect bindings"      $ ppr binds
638        
639          -- add all bindings, including the type variable and dictionary bindings produced by type
640          -- generalisation to the right-hand side of the vectorisation declaration
641        ; let [AbsBinds tvs evs _ evBinds actualBinds] = (map unLoc . bagToList) binds
642        ; let [bind']                                  = bagToList actualBinds
643              MatchGroup 
644                [L _ (Match _ _ (GRHSs [L _ (GRHS _ rhs')] _))]
645                _                                      = (fun_matches . unLoc) bind'
646              rhsWrapped                               = mkHsLams tvs evs (mkHsDictLet evBinds rhs')
647         
648         -- We return the type-checked 'Id', to propagate the inferred signature
649         -- to the vectoriser - see "Note [Typechecked vectorisation pragmas]" in HsDecls
650        ; return $ HsVect (L loc id') (Just rhsWrapped)
651        }
652 tcVect (HsNoVect name)
653   = addErrCtxt (vectCtxt name) $
654     do { id <- wrapLocM tcLookupId name
655        ; return $ HsNoVect id
656        }
657
658 vectCtxt :: Located Name -> SDoc
659 vectCtxt name = ptext (sLit "When checking the vectorisation declaration for") <+> ppr name
660
661 --------------
662 -- If typechecking the binds fails, then return with each
663 -- signature-less binder given type (forall a.a), to minimise 
664 -- subsequent error messages
665 recoveryCode :: [Name] -> SigFun -> TcM (LHsBinds TcId, [Id])
666 recoveryCode binder_names sig_fn
667   = do  { traceTc "tcBindsWithSigs: error recovery" (ppr binder_names)
668         ; poly_ids <- mapM mk_dummy binder_names
669         ; return (emptyBag, poly_ids) }
670   where
671     mk_dummy name 
672         | isJust (sig_fn name) = tcLookupId name        -- Had signature; look it up
673         | otherwise            = return (mkLocalId name forall_a_a)    -- No signature
674
675 forall_a_a :: TcType
676 forall_a_a = mkForAllTy openAlphaTyVar (mkTyVarTy openAlphaTyVar)
677 \end{code}
678
679 Note [SPECIALISE pragmas]
680 ~~~~~~~~~~~~~~~~~~~~~~~~~
681 There is no point in a SPECIALISE pragma for a non-overloaded function:
682    reverse :: [a] -> [a]
683    {-# SPECIALISE reverse :: [Int] -> [Int] #-}
684
685 But SPECIALISE INLINE *can* make sense for GADTS:
686    data Arr e where
687      ArrInt :: !Int -> ByteArray# -> Arr Int
688      ArrPair :: !Int -> Arr e1 -> Arr e2 -> Arr (e1, e2)
689
690    (!:) :: Arr e -> Int -> e
691    {-# SPECIALISE INLINE (!:) :: Arr Int -> Int -> Int #-}  
692    {-# SPECIALISE INLINE (!:) :: Arr (a, b) -> Int -> (a, b) #-}
693    (ArrInt _ ba)     !: (I# i) = I# (indexIntArray# ba i)
694    (ArrPair _ a1 a2) !: i      = (a1 !: i, a2 !: i)
695
696 When (!:) is specialised it becomes non-recursive, and can usefully
697 be inlined.  Scary!  So we only warn for SPECIALISE *without* INLINE
698 for a non-overloaded function.
699
700 %************************************************************************
701 %*                                                                      *
702 \subsection{tcMonoBind}
703 %*                                                                      *
704 %************************************************************************
705
706 @tcMonoBinds@ deals with a perhaps-recursive group of HsBinds.
707 The signatures have been dealt with already.
708
709 \begin{code}
710 tcMonoBinds :: TcSigFun -> LetBndrSpec 
711             -> RecFlag  -- Whether the binding is recursive for typechecking purposes
712                         -- i.e. the binders are mentioned in their RHSs, and
713                         --      we are not resuced by a type signature
714             -> [LHsBind Name]
715             -> TcM (LHsBinds TcId, [MonoBindInfo])
716
717 tcMonoBinds sig_fn no_gen is_rec
718            [ L b_loc (FunBind { fun_id = L nm_loc name, fun_infix = inf, 
719                                 fun_matches = matches, bind_fvs = fvs })]
720                              -- Single function binding, 
721   | NonRecursive <- is_rec   -- ...binder isn't mentioned in RHS
722   , Nothing <- sig_fn name   -- ...with no type signature
723   =     -- In this very special case we infer the type of the
724         -- right hand side first (it may have a higher-rank type)
725         -- and *then* make the monomorphic Id for the LHS
726         -- e.g.         f = \(x::forall a. a->a) -> <body>
727         --      We want to infer a higher-rank type for f
728     setSrcSpan b_loc    $
729     do  { ((co_fn, matches'), rhs_ty) <- tcInfer (tcMatchesFun name inf matches)
730
731         ; mono_id <- newNoSigLetBndr no_gen name rhs_ty
732         ; return (unitBag (L b_loc (FunBind { fun_id = L nm_loc mono_id, fun_infix = inf,
733                                               fun_matches = matches', bind_fvs = fvs,
734                                               fun_co_fn = co_fn, fun_tick = Nothing })),
735                   [(name, Nothing, mono_id)]) }
736
737 tcMonoBinds sig_fn no_gen _ binds
738   = do  { tc_binds <- mapM (wrapLocM (tcLhs sig_fn no_gen)) binds
739
740         -- Bring the monomorphic Ids, into scope for the RHSs
741         ; let mono_info  = getMonoBindInfo tc_binds
742               rhs_id_env = [(name,mono_id) | (name, Nothing, mono_id) <- mono_info]
743                     -- A monomorphic binding for each term variable that lacks 
744                     -- a type sig.  (Ones with a sig are already in scope.)
745
746         ; binds' <- tcExtendIdEnv2 rhs_id_env $ do
747                     traceTc "tcMonoBinds" $  vcat [ ppr n <+> ppr id <+> ppr (idType id) 
748                                                   | (n,id) <- rhs_id_env]
749                     mapM (wrapLocM tcRhs) tc_binds
750         ; return (listToBag binds', mono_info) }
751
752 ------------------------
753 -- tcLhs typechecks the LHS of the bindings, to construct the environment in which
754 -- we typecheck the RHSs.  Basically what we are doing is this: for each binder:
755 --      if there's a signature for it, use the instantiated signature type
756 --      otherwise invent a type variable
757 -- You see that quite directly in the FunBind case.
758 -- 
759 -- But there's a complication for pattern bindings:
760 --      data T = MkT (forall a. a->a)
761 --      MkT f = e
762 -- Here we can guess a type variable for the entire LHS (which will be refined to T)
763 -- but we want to get (f::forall a. a->a) as the RHS environment.
764 -- The simplest way to do this is to typecheck the pattern, and then look up the
765 -- bound mono-ids.  Then we want to retain the typechecked pattern to avoid re-doing
766 -- it; hence the TcMonoBind data type in which the LHS is done but the RHS isn't
767
768 data TcMonoBind         -- Half completed; LHS done, RHS not done
769   = TcFunBind  MonoBindInfo  SrcSpan Bool (MatchGroup Name) 
770   | TcPatBind [MonoBindInfo] (LPat TcId) (GRHSs Name) TcSigmaType
771
772 type MonoBindInfo = (Name, Maybe TcSigInfo, TcId)
773         -- Type signature (if any), and
774         -- the monomorphic bound things
775
776 tcLhs :: TcSigFun -> LetBndrSpec -> HsBind Name -> TcM TcMonoBind
777 tcLhs sig_fn no_gen (FunBind { fun_id = L nm_loc name, fun_infix = inf, fun_matches = matches })
778   | Just sig <- sig_fn name
779   = do  { mono_id <- newSigLetBndr no_gen name sig
780         ; return (TcFunBind (name, Just sig, mono_id) nm_loc inf matches) }
781   | otherwise
782   = do  { mono_ty <- newFlexiTyVarTy argTypeKind
783         ; mono_id <- newNoSigLetBndr no_gen name mono_ty
784         ; return (TcFunBind (name, Nothing, mono_id) nm_loc inf matches) }
785
786 tcLhs sig_fn no_gen (PatBind { pat_lhs = pat, pat_rhs = grhss })
787   = do  { let tc_pat exp_ty = tcLetPat sig_fn no_gen pat exp_ty $
788                               mapM lookup_info (collectPatBinders pat)
789
790                 -- After typechecking the pattern, look up the binder
791                 -- names, which the pattern has brought into scope.
792               lookup_info :: Name -> TcM MonoBindInfo
793               lookup_info name = do { mono_id <- tcLookupId name
794                                     ; return (name, sig_fn name, mono_id) }
795
796         ; ((pat', infos), pat_ty) <- addErrCtxt (patMonoBindsCtxt pat grhss) $
797                                      tcInfer tc_pat
798
799         ; return (TcPatBind infos pat' grhss pat_ty) }
800
801 tcLhs _ _ other_bind = pprPanic "tcLhs" (ppr other_bind)
802         -- AbsBind, VarBind impossible
803
804 -------------------
805 tcRhs :: TcMonoBind -> TcM (HsBind TcId)
806 -- When we are doing pattern bindings, or multiple function bindings at a time
807 -- we *don't* bring any scoped type variables into scope
808 -- Wny not?  They are not completely rigid.
809 -- That's why we have the special case for a single FunBind in tcMonoBinds
810 tcRhs (TcFunBind (_,_,mono_id) loc inf matches)
811   = do  { (co_fn, matches') <- tcMatchesFun (idName mono_id) inf 
812                                             matches (idType mono_id)
813         ; return (FunBind { fun_id = L loc mono_id, fun_infix = inf
814                           , fun_matches = matches'
815                           , fun_co_fn = co_fn 
816                           , bind_fvs = placeHolderNames, fun_tick = Nothing }) }
817
818 tcRhs (TcPatBind _ pat' grhss pat_ty)
819   = do  { grhss' <- addErrCtxt (patMonoBindsCtxt pat' grhss) $
820                     tcGRHSsPat grhss pat_ty
821         ; return (PatBind { pat_lhs = pat', pat_rhs = grhss', pat_rhs_ty = pat_ty 
822                           , bind_fvs = placeHolderNames }) }
823
824
825 ---------------------
826 getMonoBindInfo :: [Located TcMonoBind] -> [MonoBindInfo]
827 getMonoBindInfo tc_binds
828   = foldr (get_info . unLoc) [] tc_binds
829   where
830     get_info (TcFunBind info _ _ _)  rest = info : rest
831     get_info (TcPatBind infos _ _ _) rest = infos ++ rest
832 \end{code}
833
834
835 %************************************************************************
836 %*                                                                      *
837                 Generalisation
838 %*                                                                      *
839 %************************************************************************
840
841 unifyCtxts checks that all the signature contexts are the same
842 The type signatures on a mutually-recursive group of definitions
843 must all have the same context (or none).
844
845 The trick here is that all the signatures should have the same
846 context, and we want to share type variables for that context, so that
847 all the right hand sides agree a common vocabulary for their type
848 constraints
849
850 We unify them because, with polymorphic recursion, their types
851 might not otherwise be related.  This is a rather subtle issue.
852
853 \begin{code}
854 unifyCtxts :: [TcSigInfo] -> TcM ()
855 -- Post-condition: the returned Insts are full zonked
856 unifyCtxts [] = return ()
857 unifyCtxts (sig1 : sigs)
858   = do  { traceTc "unifyCtxts" (ppr (sig1 : sigs))
859         ; mapM_ unify_ctxt sigs }
860   where
861     theta1 = sig_theta sig1
862     unify_ctxt :: TcSigInfo -> TcM ()
863     unify_ctxt sig@(TcSigInfo { sig_theta = theta })
864         = setSrcSpan (sig_loc sig)                      $
865           addErrCtxt (sigContextsCtxt sig1 sig)         $
866           do { cois <- unifyTheta theta1 theta
867              ; -- Check whether all coercions are identity coercions
868                -- That can happen if we have, say
869                --         f :: C [a]   => ...
870                --         g :: C (F a) => ...
871                -- where F is a type function and (F a ~ [a])
872                -- Then unification might succeed with a coercion.  But it's much
873                -- much simpler to require that such signatures have identical contexts
874                checkTc (all isReflCo cois)
875                        (ptext (sLit "Mutually dependent functions have syntactically distinct contexts"))
876              }
877 \end{code}
878
879
880 @getTyVarsToGen@ decides what type variables to generalise over.
881
882 For a "restricted group" -- see the monomorphism restriction
883 for a definition -- we bind no dictionaries, and
884 remove from tyvars_to_gen any constrained type variables
885
886 *Don't* simplify dicts at this point, because we aren't going
887 to generalise over these dicts.  By the time we do simplify them
888 we may well know more.  For example (this actually came up)
889         f :: Array Int Int
890         f x = array ... xs where xs = [1,2,3,4,5]
891 We don't want to generate lots of (fromInt Int 1), (fromInt Int 2)
892 stuff.  If we simplify only at the f-binding (not the xs-binding)
893 we'll know that the literals are all Ints, and we can just produce
894 Int literals!
895
896 Find all the type variables involved in overloading, the
897 "constrained_tyvars".  These are the ones we *aren't* going to
898 generalise.  We must be careful about doing this:
899
900  (a) If we fail to generalise a tyvar which is not actually
901         constrained, then it will never, ever get bound, and lands
902         up printed out in interface files!  Notorious example:
903                 instance Eq a => Eq (Foo a b) where ..
904         Here, b is not constrained, even though it looks as if it is.
905         Another, more common, example is when there's a Method inst in
906         the LIE, whose type might very well involve non-overloaded
907         type variables.
908   [NOTE: Jan 2001: I don't understand the problem here so I'm doing 
909         the simple thing instead]
910
911  (b) On the other hand, we mustn't generalise tyvars which are constrained,
912         because we are going to pass on out the unmodified LIE, with those
913         tyvars in it.  They won't be in scope if we've generalised them.
914
915 So we are careful, and do a complete simplification just to find the
916 constrained tyvars. We don't use any of the results, except to
917 find which tyvars are constrained.
918
919 Note [Polymorphic recursion]
920 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
921 The game plan for polymorphic recursion in the code above is 
922
923         * Bind any variable for which we have a type signature
924           to an Id with a polymorphic type.  Then when type-checking 
925           the RHSs we'll make a full polymorphic call.
926
927 This fine, but if you aren't a bit careful you end up with a horrendous
928 amount of partial application and (worse) a huge space leak. For example:
929
930         f :: Eq a => [a] -> [a]
931         f xs = ...f...
932
933 If we don't take care, after typechecking we get
934
935         f = /\a -> \d::Eq a -> let f' = f a d
936                                in
937                                \ys:[a] -> ...f'...
938
939 Notice the the stupid construction of (f a d), which is of course
940 identical to the function we're executing.  In this case, the
941 polymorphic recursion isn't being used (but that's a very common case).
942 This can lead to a massive space leak, from the following top-level defn
943 (post-typechecking)
944
945         ff :: [Int] -> [Int]
946         ff = f Int dEqInt
947
948 Now (f dEqInt) evaluates to a lambda that has f' as a free variable; but
949 f' is another thunk which evaluates to the same thing... and you end
950 up with a chain of identical values all hung onto by the CAF ff.
951
952         ff = f Int dEqInt
953
954            = let f' = f Int dEqInt in \ys. ...f'...
955
956            = let f' = let f' = f Int dEqInt in \ys. ...f'...
957                       in \ys. ...f'...
958
959 Etc.
960
961 NOTE: a bit of arity anaysis would push the (f a d) inside the (\ys...),
962 which would make the space leak go away in this case
963
964 Solution: when typechecking the RHSs we always have in hand the
965 *monomorphic* Ids for each binding.  So we just need to make sure that
966 if (Method f a d) shows up in the constraints emerging from (...f...)
967 we just use the monomorphic Id.  We achieve this by adding monomorphic Ids
968 to the "givens" when simplifying constraints.  That's what the "lies_avail"
969 is doing.
970
971 Then we get
972
973         f = /\a -> \d::Eq a -> letrec
974                                  fm = \ys:[a] -> ...fm...
975                                in
976                                fm
977
978 %************************************************************************
979 %*                                                                      *
980                 Signatures
981 %*                                                                      *
982 %************************************************************************
983
984 Type signatures are tricky.  See Note [Signature skolems] in TcType
985
986 @tcSigs@ checks the signatures for validity, and returns a list of
987 {\em freshly-instantiated} signatures.  That is, the types are already
988 split up, and have fresh type variables installed.  All non-type-signature
989 "RenamedSigs" are ignored.
990
991 The @TcSigInfo@ contains @TcTypes@ because they are unified with
992 the variable's type, and after that checked to see whether they've
993 been instantiated.
994
995 Note [Scoped tyvars]
996 ~~~~~~~~~~~~~~~~~~~~
997 The -XScopedTypeVariables flag brings lexically-scoped type variables
998 into scope for any explicitly forall-quantified type variables:
999         f :: forall a. a -> a
1000         f x = e
1001 Then 'a' is in scope inside 'e'.
1002
1003 However, we do *not* support this 
1004   - For pattern bindings e.g
1005         f :: forall a. a->a
1006         (f,g) = e
1007
1008   - For multiple function bindings, unless Opt_RelaxedPolyRec is on
1009         f :: forall a. a -> a
1010         f = g
1011         g :: forall b. b -> b
1012         g = ...f...
1013     Reason: we use mutable variables for 'a' and 'b', since they may
1014     unify to each other, and that means the scoped type variable would
1015     not stand for a completely rigid variable.
1016
1017     Currently, we simply make Opt_ScopedTypeVariables imply Opt_RelaxedPolyRec
1018
1019
1020 Note [More instantiated than scoped]
1021 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1022 There may be more instantiated type variables than lexically-scoped 
1023 ones.  For example:
1024         type T a = forall b. b -> (a,b)
1025         f :: forall c. T c
1026 Here, the signature for f will have one scoped type variable, c,
1027 but two instantiated type variables, c' and b'.  
1028
1029 We assume that the scoped ones are at the *front* of sig_tvs,
1030 and remember the names from the original HsForAllTy in the TcSigFun.
1031
1032 Note [Signature skolems]
1033 ~~~~~~~~~~~~~~~~~~~~~~~~
1034 When instantiating a type signature, we do so with either skolems or
1035 SigTv meta-type variables depending on the use_skols boolean.  This
1036 variable is set True when we are typechecking a single function
1037 binding; and False for pattern bindings and a group of several
1038 function bindings.
1039
1040 Reason: in the latter cases, the "skolems" can be unified together, 
1041         so they aren't properly rigid in the type-refinement sense.
1042 NB: unless we are doing H98, each function with a sig will be done
1043     separately, even if it's mutually recursive, so use_skols will be True
1044
1045
1046 Note [Only scoped tyvars are in the TyVarEnv]
1047 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1048 We are careful to keep only the *lexically scoped* type variables in
1049 the type environment.  Why?  After all, the renamer has ensured
1050 that only legal occurrences occur, so we could put all type variables
1051 into the type env.
1052
1053 But we want to check that two distinct lexically scoped type variables
1054 do not map to the same internal type variable.  So we need to know which
1055 the lexically-scoped ones are... and at the moment we do that by putting
1056 only the lexically scoped ones into the environment.
1057
1058 Note [Instantiate sig with fresh variables]
1059 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1060 It's vital to instantiate a type signature with fresh variables.
1061 For example:
1062       type T = forall a. [a] -> [a]
1063       f :: T; 
1064       f = g where { g :: T; g = <rhs> }
1065
1066  We must not use the same 'a' from the defn of T at both places!!
1067 (Instantiation is only necessary because of type synonyms.  Otherwise,
1068 it's all cool; each signature has distinct type variables from the renamer.)
1069
1070 \begin{code}
1071 type SigFun = Name -> Maybe ([Name], SrcSpan)
1072          -- Maps a let-binder to the list of
1073          -- type variables brought into scope
1074          -- by its type signature, plus location
1075          -- Nothing => no type signature
1076
1077 mkSigFun :: [LSig Name] -> SigFun
1078 -- Search for a particular type signature
1079 -- Precondition: the sigs are all type sigs
1080 -- Precondition: no duplicates
1081 mkSigFun sigs = lookupNameEnv env
1082   where
1083     env = mkNameEnv (mapCatMaybes mk_pair sigs)
1084     mk_pair (L loc (TypeSig (L _ name) lhs_ty)) = Just (name, (hsExplicitTvs lhs_ty, loc))
1085     mk_pair (L loc (IdSig id))                  = Just (idName id, ([], loc))
1086     mk_pair _                                   = Nothing    
1087         -- The scoped names are the ones explicitly mentioned
1088         -- in the HsForAll.  (There may be more in sigma_ty, because
1089         -- of nested type synonyms.  See Note [More instantiated than scoped].)
1090         -- See Note [Only scoped tyvars are in the TyVarEnv]
1091 \end{code}
1092
1093 \begin{code}
1094 tcTySig :: LSig Name -> TcM TcId
1095 tcTySig (L span (TypeSig (L _ name) ty))
1096   = setSrcSpan span             $
1097     do  { sigma_ty <- tcHsSigType (FunSigCtxt name) ty
1098         ; return (mkLocalId name sigma_ty) }
1099 tcTySig (L _ (IdSig id))
1100   = return id
1101 tcTySig s = pprPanic "tcTySig" (ppr s)
1102
1103 -------------------
1104 tcInstSigs :: SigFun -> [Name] -> TcM TcSigFun
1105 tcInstSigs sig_fn bndrs
1106   = do { prs <- mapMaybeM (tcInstSig sig_fn use_skols) bndrs
1107        ; return (lookupNameEnv (mkNameEnv prs)) }
1108   where
1109     use_skols = isSingleton bndrs       -- See Note [Signature skolems]
1110
1111 tcInstSig :: SigFun -> Bool -> Name -> TcM (Maybe (Name, TcSigInfo))
1112 -- For use_skols :: Bool see Note [Signature skolems]
1113 --
1114 -- We must instantiate with fresh uniques, 
1115 -- (see Note [Instantiate sig with fresh variables])
1116 -- although we keep the same print-name.
1117
1118 tcInstSig sig_fn use_skols name
1119   | Just (scoped_tvs, loc) <- sig_fn name
1120   = do  { poly_id <- tcLookupId name    -- Cannot fail; the poly ids are put into 
1121                                         -- scope when starting the binding group
1122         ; let poly_ty = idType poly_id
1123         ; (tvs, theta, tau) <- if use_skols
1124                                then tcInstType tcInstSkolTyVars poly_ty
1125                                else tcInstType tcInstSigTyVars  poly_ty
1126         ; let sig = TcSigInfo { sig_id = poly_id
1127                               , sig_scoped = scoped_tvs
1128                               , sig_tvs = tvs, sig_theta = theta, sig_tau = tau
1129                               , sig_loc = loc }
1130         ; return (Just (name, sig)) } 
1131   | otherwise
1132   = return Nothing
1133
1134 -------------------------------
1135 data GeneralisationPlan 
1136   = NoGen               -- No generalisation, no AbsBinds
1137   | InferGen Bool       -- Implicit generalisation; there is an AbsBinds
1138                         --   True <=> apply the MR; generalise only unconstrained type vars
1139   | CheckGen TcSigInfo  -- Explicit generalisation; there is an AbsBinds
1140
1141 -- A consequence of the no-AbsBinds choice (NoGen) is that there is
1142 -- no "polymorphic Id" and "monmomorphic Id"; there is just the one
1143
1144 instance Outputable GeneralisationPlan where
1145   ppr NoGen        = ptext (sLit "NoGen")
1146   ppr (InferGen b) = ptext (sLit "InferGen") <+> ppr b
1147   ppr (CheckGen s) = ptext (sLit "CheckGen") <+> ppr s
1148
1149 decideGeneralisationPlan 
1150    :: DynFlags -> TopLevelFlag -> [Name] -> [LHsBind Name] -> TcSigFun -> GeneralisationPlan
1151 decideGeneralisationPlan dflags top_lvl _bndrs binds sig_fn
1152   | bang_pat_binds                         = NoGen
1153   | mono_pat_binds                         = NoGen
1154   | Just sig <- one_funbind_with_sig binds = if null (sig_tvs sig) && null (sig_theta sig)
1155                                              then NoGen       -- Optimise common case
1156                                              else CheckGen sig
1157   | (xopt Opt_MonoLocalBinds dflags 
1158       && isNotTopLevel top_lvl)            = NoGen
1159   | otherwise                              = InferGen mono_restriction
1160
1161   where
1162     bang_pat_binds = any (isBangHsBind . unLoc) binds
1163        -- Bang patterns must not be polymorphic,
1164        -- because we are going to force them
1165        -- See Trac #4498
1166
1167     mono_pat_binds = xopt Opt_MonoPatBinds dflags
1168                   && any (is_pat_bind . unLoc) binds
1169
1170     mono_restriction = xopt Opt_MonomorphismRestriction dflags 
1171                     && any (restricted . unLoc) binds
1172
1173     no_sig n = isNothing (sig_fn n)
1174
1175     -- With OutsideIn, all nested bindings are monomorphic
1176     -- except a single function binding with a signature
1177     one_funbind_with_sig [L _ FunBind { fun_id = v }] = sig_fn (unLoc v)
1178     one_funbind_with_sig _                            = Nothing
1179
1180     -- The Haskell 98 monomorphism resetriction
1181     restricted (PatBind {})                              = True
1182     restricted (VarBind { var_id = v })                  = no_sig v
1183     restricted (FunBind { fun_id = v, fun_matches = m }) = restricted_match m
1184                                                            && no_sig (unLoc v)
1185     restricted (AbsBinds {}) = panic "isRestrictedGroup/unrestricted AbsBinds"
1186
1187     restricted_match (MatchGroup (L _ (Match [] _ _) : _) _) = True
1188     restricted_match _                                       = False
1189         -- No args => like a pattern binding
1190         -- Some args => a function binding
1191
1192     is_pat_bind (PatBind {}) = True
1193     is_pat_bind _            = False
1194
1195 -------------------
1196 checkStrictBinds :: TopLevelFlag -> RecFlag
1197                  -> [LHsBind Name] -> [Id]
1198                  -> TcM ()
1199 -- Check that non-overloaded unlifted bindings are
1200 --      a) non-recursive,
1201 --      b) not top level, 
1202 --      c) not a multiple-binding group (more or less implied by (a))
1203
1204 checkStrictBinds top_lvl rec_group binds poly_ids
1205   | unlifted || bang_pat
1206   = do  { checkTc (isNotTopLevel top_lvl)
1207                   (strictBindErr "Top-level" unlifted binds)
1208         ; checkTc (isNonRec rec_group)
1209                   (strictBindErr "Recursive" unlifted binds)
1210         ; checkTc (isSingleton binds)
1211                   (strictBindErr "Multiple" unlifted binds)
1212         -- This should be a checkTc, not a warnTc, but as of GHC 6.11
1213         -- the versions of alex and happy available have non-conforming
1214         -- templates, so the GHC build fails if it's an error:
1215         ; warnUnlifted <- doptM Opt_WarnLazyUnliftedBindings
1216         ; warnTc (warnUnlifted && not bang_pat && lifted_pat)
1217                  -- No outer bang, but it's a compound pattern
1218                  -- E.g   (I# x#) = blah
1219                  -- Warn about this, but not about
1220                  --      x# = 4# +# 1#
1221                  --      (# a, b #) = ...
1222                  (unliftedMustBeBang binds) }
1223   | otherwise
1224   = return ()
1225   where
1226     unlifted    = any is_unlifted poly_ids
1227     bang_pat    = any (isBangHsBind . unLoc) binds
1228     lifted_pat  = any (isLiftedPatBind . unLoc) binds
1229     is_unlifted id = case tcSplitForAllTys (idType id) of
1230                        (_, rho) -> isUnLiftedType rho
1231
1232 unliftedMustBeBang :: [LHsBind Name] -> SDoc
1233 unliftedMustBeBang binds
1234   = hang (text "Pattern bindings containing unlifted types should use an outermost bang pattern:")
1235        2 (pprBindList binds)
1236
1237 strictBindErr :: String -> Bool -> [LHsBind Name] -> SDoc
1238 strictBindErr flavour unlifted binds
1239   = hang (text flavour <+> msg <+> ptext (sLit "aren't allowed:")) 
1240        2 (pprBindList binds)
1241   where
1242     msg | unlifted  = ptext (sLit "bindings for unlifted types")
1243         | otherwise = ptext (sLit "bang-pattern bindings")
1244
1245 pprBindList :: [LHsBind Name] -> SDoc
1246 pprBindList binds = vcat (map ppr binds)
1247 \end{code}
1248
1249
1250 %************************************************************************
1251 %*                                                                      *
1252 \subsection[TcBinds-errors]{Error contexts and messages}
1253 %*                                                                      *
1254 %************************************************************************
1255
1256
1257 \begin{code}
1258 -- This one is called on LHS, when pat and grhss are both Name 
1259 -- and on RHS, when pat is TcId and grhss is still Name
1260 patMonoBindsCtxt :: OutputableBndr id => LPat id -> GRHSs Name -> SDoc
1261 patMonoBindsCtxt pat grhss
1262   = hang (ptext (sLit "In a pattern binding:")) 2 (pprPatBind pat grhss)
1263
1264 -----------------------------------------------
1265 sigContextsCtxt :: TcSigInfo -> TcSigInfo -> SDoc
1266 sigContextsCtxt sig1 sig2
1267   = vcat [ptext (sLit "When matching the contexts of the signatures for"), 
1268           nest 2 (vcat [ppr id1 <+> dcolon <+> ppr (idType id1),
1269                         ppr id2 <+> dcolon <+> ppr (idType id2)]),
1270           ptext (sLit "The signature contexts in a mutually recursive group should all be identical")]
1271   where
1272     id1 = sig_id sig1
1273     id2 = sig_id sig2
1274 \end{code}