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