2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
5 \section[TcBinds]{TcBinds}
8 module TcBinds ( tcLocalBinds, tcTopBinds,
9 tcHsBootSigs, tcMonoBinds,
10 TcPragFun, tcSpecPrag, tcPrags, mkPragFun,
11 TcSigInfo(..), TcSigFun, mkTcSigFun,
12 badBootDeclErr ) where
14 #include "HsVersions.h"
16 import {-# SOURCE #-} TcMatches ( tcGRHSsPat, tcMatchesFun )
17 import {-# SOURCE #-} TcExpr ( tcMonoExpr )
32 import {- Kind parts of -} Type
54 %************************************************************************
56 \subsection{Type-checking bindings}
58 %************************************************************************
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.
68 @tcBindsAndThen@ also takes a "combiner" which glues together the
69 bindings and the "thing" to make a new "thing".
71 The real work is done by @tcBindWithSigsAndThen@.
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.
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.
82 At the top-level the LIE is sure to contain nothing but constant
83 dictionaries, which we resolve at the module level.
86 tcTopBinds :: HsValBinds Name -> TcM (LHsBinds TcId, TcLclEnv)
87 -- Note: returning the TcLclEnv is more than we really
88 -- want. The bit we care about is the local bindings
89 -- and the free type variables thereof
91 = do { (ValBindsOut prs _, env) <- tcValBinds TopLevel binds getLclEnv
92 ; return (foldr (unionBags . snd) emptyBag prs, env) }
93 -- The top level bindings are flattened into a giant
94 -- implicitly-mutually-recursive LHsBinds
96 tcHsBootSigs :: HsValBinds Name -> TcM [Id]
97 -- A hs-boot file has only one BindGroup, and it only has type
98 -- signatures in it. The renamer checked all this
99 tcHsBootSigs (ValBindsOut binds sigs)
100 = do { checkTc (null binds) badBootDeclErr
101 ; mapM (addLocM tc_boot_sig) (filter isVanillaLSig sigs) }
103 tc_boot_sig (TypeSig (L _ name) ty)
104 = do { sigma_ty <- tcHsSigType (FunSigCtxt name) ty
105 ; return (mkVanillaGlobal name sigma_ty vanillaIdInfo) }
106 -- Notice that we make GlobalIds, not LocalIds
107 tcHsBootSigs groups = pprPanic "tcHsBootSigs" (ppr groups)
109 badBootDeclErr :: Message
110 badBootDeclErr = ptext SLIT("Illegal declarations in an hs-boot file")
112 ------------------------
113 tcLocalBinds :: HsLocalBinds Name -> TcM thing
114 -> TcM (HsLocalBinds TcId, thing)
116 tcLocalBinds EmptyLocalBinds thing_inside
117 = do { thing <- thing_inside
118 ; return (EmptyLocalBinds, thing) }
120 tcLocalBinds (HsValBinds binds) thing_inside
121 = do { (binds', thing) <- tcValBinds NotTopLevel binds thing_inside
122 ; return (HsValBinds binds', thing) }
124 tcLocalBinds (HsIPBinds (IPBinds ip_binds _)) thing_inside
125 = do { (thing, lie) <- getLIE thing_inside
126 ; (avail_ips, ip_binds') <- mapAndUnzipM (wrapLocSndM tc_ip_bind) ip_binds
128 -- If the binding binds ?x = E, we must now
129 -- discharge any ?x constraints in expr_lie
130 ; dict_binds <- tcSimplifyIPs avail_ips lie
131 ; return (HsIPBinds (IPBinds ip_binds' dict_binds), thing) }
133 -- I wonder if we should do these one at at time
136 tc_ip_bind (IPBind ip expr)
137 = newFlexiTyVarTy argTypeKind `thenM` \ ty ->
138 newIPDict (IPBindOrigin ip) ip ty `thenM` \ (ip', ip_inst) ->
139 tcMonoExpr expr ty `thenM` \ expr' ->
140 returnM (ip_inst, (IPBind ip' expr'))
142 ------------------------
143 tcValBinds :: TopLevelFlag
144 -> HsValBinds Name -> TcM thing
145 -> TcM (HsValBinds TcId, thing)
147 tcValBinds top_lvl (ValBindsIn binds sigs) thing_inside
148 = pprPanic "tcValBinds" (ppr binds)
150 tcValBinds top_lvl (ValBindsOut binds sigs) thing_inside
151 = do { -- Typecheck the signature
152 ; let { prag_fn = mkPragFun sigs
153 ; ty_sigs = filter isVanillaLSig sigs
154 ; sig_fn = mkTcSigFun ty_sigs }
156 ; poly_ids <- mapM tcTySig ty_sigs
157 -- No recovery from bad signatures, because the type sigs
158 -- may bind type variables, so proceeding without them
159 -- can lead to a cascade of errors
160 -- ToDo: this means we fall over immediately if any type sig
161 -- is wrong, which is over-conservative, see Trac bug #745
163 -- Extend the envt right away with all
164 -- the Ids declared with type signatures
165 ; gla_exts <- doptM Opt_GlasgowExts
166 ; (binds', thing) <- tcExtendIdEnv poly_ids $
167 tc_val_binds gla_exts top_lvl sig_fn prag_fn
170 ; return (ValBindsOut binds' sigs, thing) }
172 ------------------------
173 tc_val_binds :: Bool -> TopLevelFlag -> TcSigFun -> TcPragFun
174 -> [(RecFlag, LHsBinds Name)] -> TcM thing
175 -> TcM ([(RecFlag, LHsBinds TcId)], thing)
176 -- Typecheck a whole lot of value bindings,
177 -- one strongly-connected component at a time
179 tc_val_binds gla_exts top_lvl sig_fn prag_fn [] thing_inside
180 = do { thing <- thing_inside
181 ; return ([], thing) }
183 tc_val_binds gla_exts top_lvl sig_fn prag_fn (group : groups) thing_inside
184 = do { (group', (groups', thing))
185 <- tc_group gla_exts top_lvl sig_fn prag_fn group $
186 tc_val_binds gla_exts top_lvl sig_fn prag_fn groups thing_inside
187 ; return (group' ++ groups', thing) }
189 ------------------------
190 tc_group :: Bool -> TopLevelFlag -> TcSigFun -> TcPragFun
191 -> (RecFlag, LHsBinds Name) -> TcM thing
192 -> TcM ([(RecFlag, LHsBinds TcId)], thing)
194 -- Typecheck one strongly-connected component of the original program.
195 -- We get a list of groups back, because there may
196 -- be specialisations etc as well
198 tc_group gla_exts top_lvl sig_fn prag_fn (NonRecursive, binds) thing_inside
199 -- A single non-recursive binding
200 -- We want to keep non-recursive things non-recursive
201 -- so that we desugar unlifted bindings correctly
202 = do { (binds, thing) <- tc_haskell98 top_lvl sig_fn prag_fn NonRecursive binds thing_inside
203 ; return ([(NonRecursive, b) | b <- binds], thing) }
205 tc_group gla_exts top_lvl sig_fn prag_fn (Recursive, binds) thing_inside
206 | not gla_exts -- Recursive group, normal Haskell 98 route
207 = do { (binds1, thing) <- tc_haskell98 top_lvl sig_fn prag_fn Recursive binds thing_inside
208 ; return ([(Recursive, unionManyBags binds1)], thing) }
210 | otherwise -- Recursive group, with gla-exts
211 = -- To maximise polymorphism (with -fglasgow-exts), we do a new
212 -- strongly-connected-component analysis, this time omitting
213 -- any references to variables with type signatures.
215 -- Notice that the bindInsts thing covers *all* the bindings in the original
216 -- group at once; an earlier one may use a later one!
217 do { traceTc (text "tc_group rec" <+> pprLHsBinds binds)
218 ; (binds1,thing) <- bindLocalInsts top_lvl $
219 go (stronglyConnComp (mkEdges sig_fn binds))
220 ; return ([(Recursive, unionManyBags binds1)], thing) }
221 -- Rec them all together
223 -- go :: SCC (LHsBind Name) -> TcM ([LHsBind TcId], [TcId], thing)
224 go (scc:sccs) = do { (binds1, ids1) <- tc_scc scc
225 ; (binds2, ids2, thing) <- tcExtendIdEnv ids1 $ go sccs
226 ; return (binds1 ++ binds2, ids1 ++ ids2, thing) }
227 go [] = do { thing <- thing_inside; return ([], [], thing) }
229 tc_scc (AcyclicSCC bind) = tc_sub_group NonRecursive (unitBag bind)
230 tc_scc (CyclicSCC binds) = tc_sub_group Recursive (listToBag binds)
232 tc_sub_group = tcPolyBinds top_lvl sig_fn prag_fn Recursive
234 tc_haskell98 top_lvl sig_fn prag_fn rec_flag binds thing_inside
235 = bindLocalInsts top_lvl $ do
236 { (binds1, ids) <- tcPolyBinds top_lvl sig_fn prag_fn rec_flag rec_flag binds
237 ; thing <- tcExtendIdEnv ids thing_inside
238 ; return (binds1, ids, thing) }
240 ------------------------
241 bindLocalInsts :: TopLevelFlag -> TcM ([LHsBinds TcId], [TcId], a) -> TcM ([LHsBinds TcId], a)
242 bindLocalInsts top_lvl thing_inside
243 | isTopLevel top_lvl = do { (binds, ids, thing) <- thing_inside; return (binds, thing) }
244 -- For the top level don't bother will all this bindInstsOfLocalFuns stuff.
245 -- All the top level things are rec'd together anyway, so it's fine to
246 -- leave them to the tcSimplifyTop, and quite a bit faster too
248 | otherwise -- Nested case
249 = do { ((binds, ids, thing), lie) <- getLIE thing_inside
250 ; lie_binds <- bindInstsOfLocalFuns lie ids
251 ; return (binds ++ [lie_binds], thing) }
253 ------------------------
254 mkEdges :: TcSigFun -> LHsBinds Name
255 -> [(LHsBind Name, BKey, [BKey])]
257 type BKey = Int -- Just number off the bindings
260 = [ (bind, key, [key | n <- nameSetToList (bind_fvs (unLoc bind)),
261 Just key <- [lookupNameEnv key_map n], no_sig n ])
262 | (bind, key) <- keyd_binds
265 no_sig :: Name -> Bool
266 no_sig n = isNothing (sig_fn n)
268 keyd_binds = bagToList binds `zip` [0::BKey ..]
270 key_map :: NameEnv BKey -- Which binding it comes from
271 key_map = mkNameEnv [(bndr, key) | (L _ bind, key) <- keyd_binds
272 , bndr <- bindersOfHsBind bind ]
274 bindersOfHsBind :: HsBind Name -> [Name]
275 bindersOfHsBind (PatBind { pat_lhs = pat }) = collectPatBinders pat
276 bindersOfHsBind (FunBind { fun_id = L _ f }) = [f]
278 ------------------------
279 tcPolyBinds :: TopLevelFlag -> TcSigFun -> TcPragFun
280 -> RecFlag -- Whether the group is really recursive
281 -> RecFlag -- Whether it's recursive after breaking
282 -- dependencies based on type signatures
284 -> TcM ([LHsBinds TcId], [TcId])
286 -- Typechecks a single bunch of bindings all together,
287 -- and generalises them. The bunch may be only part of a recursive
288 -- group, because we use type signatures to maximise polymorphism
290 -- Returns a list because the input may be a single non-recursive binding,
291 -- in which case the dependency order of the resulting bindings is
294 -- Knows nothing about the scope of the bindings
296 tcPolyBinds top_lvl sig_fn prag_fn rec_group rec_tc binds
298 bind_list = bagToList binds
299 binder_names = collectHsBindBinders binds
300 loc = getLoc (head bind_list)
301 -- TODO: location a bit awkward, but the mbinds have been
302 -- dependency analysed and may no longer be adjacent
304 -- SET UP THE MAIN RECOVERY; take advantage of any type sigs
306 recoverM (recoveryCode binder_names sig_fn) $ do
308 { traceTc (ptext SLIT("------------------------------------------------"))
309 ; traceTc (ptext SLIT("Bindings for") <+> ppr binder_names)
311 -- TYPECHECK THE BINDINGS
312 ; ((binds', mono_bind_infos), lie_req)
313 <- getLIE (tcMonoBinds bind_list sig_fn rec_tc)
314 ; traceTc (text "temp" <+> (ppr binds' $$ ppr lie_req))
316 -- CHECK FOR UNLIFTED BINDINGS
317 -- These must be non-recursive etc, and are not generalised
318 -- They desugar to a case expression in the end
319 ; zonked_mono_tys <- zonkTcTypes (map getMonoType mono_bind_infos)
320 ; is_strict <- checkStrictBinds top_lvl rec_group binds'
321 zonked_mono_tys mono_bind_infos
323 do { extendLIEs lie_req
324 ; let exports = zipWith mk_export mono_bind_infos zonked_mono_tys
325 mk_export (name, Nothing, mono_id) mono_ty = ([], mkLocalId name mono_ty, mono_id, [])
326 mk_export (name, Just sig, mono_id) mono_ty = ([], sig_id sig, mono_id, [])
327 -- ToDo: prags for unlifted bindings
329 ; return ( [unitBag $ L loc $ AbsBinds [] [] exports binds'],
330 [poly_id | (_, poly_id, _, _) <- exports]) } -- Guaranteed zonked
332 else do -- The normal lifted case: GENERALISE
334 ; (tyvars_to_gen, dicts, dict_binds)
335 <- addErrCtxt (genCtxt (bndrNames mono_bind_infos)) $
336 generalise dflags top_lvl bind_list sig_fn mono_bind_infos lie_req
338 -- BUILD THE POLYMORPHIC RESULT IDs
339 ; let dict_ids = map instToId dicts
340 ; exports <- mapM (mkExport prag_fn tyvars_to_gen (map idType dict_ids))
343 ; let poly_ids = [poly_id | (_, poly_id, _, _) <- exports]
344 ; traceTc (text "binding:" <+> ppr (poly_ids `zip` map idType poly_ids))
346 ; let abs_bind = L loc $ AbsBinds tyvars_to_gen
348 (dict_binds `unionBags` binds')
350 ; return ([unitBag abs_bind], poly_ids) -- poly_ids are guaranteed zonked by mkExport
355 mkExport :: TcPragFun -> [TyVar] -> [TcType] -> MonoBindInfo
356 -> TcM ([TyVar], Id, Id, [Prag])
357 -- mkExport generates exports with
358 -- zonked type variables,
360 -- The former is just because no further unifications will change
361 -- the quantified type variables, so we can fix their final form
363 -- The latter is needed because the poly_ids are used to extend the
364 -- type environment; see the invariant on TcEnv.tcExtendIdEnv
366 -- Pre-condition: the inferred_tvs are already zonked
368 mkExport prag_fn inferred_tvs dict_tys (poly_name, mb_sig, mono_id)
369 = do { (tvs, poly_id) <- mk_poly_id mb_sig
371 ; poly_id' <- zonkId poly_id
372 ; prags <- tcPrags poly_id' (prag_fn poly_name)
373 -- tcPrags requires a zonked poly_id
375 ; return (tvs, poly_id', mono_id, prags) }
377 poly_ty = mkForAllTys inferred_tvs (mkFunTys dict_tys (idType mono_id))
379 mk_poly_id Nothing = return (inferred_tvs, mkLocalId poly_name poly_ty)
380 mk_poly_id (Just sig) = do { tvs <- mapM zonk_tv (sig_tvs sig)
381 ; return (tvs, sig_id sig) }
383 zonk_tv tv = do { ty <- zonkTcTyVar tv; return (tcGetTyVar "mkExport" ty) }
385 ------------------------
386 type TcPragFun = Name -> [LSig Name]
388 mkPragFun :: [LSig Name] -> TcPragFun
389 mkPragFun sigs = \n -> lookupNameEnv env n `orElse` []
391 prs = [(expectJust "mkPragFun" (sigName sig), sig)
392 | sig <- sigs, isPragLSig sig]
393 env = foldl add emptyNameEnv prs
394 add env (n,p) = extendNameEnv_Acc (:) singleton env n p
396 tcPrags :: Id -> [LSig Name] -> TcM [Prag]
397 tcPrags poly_id prags = mapM tc_prag prags
399 tc_prag (L loc prag) = setSrcSpan loc $
400 addErrCtxt (pragSigCtxt prag) $
403 pragSigCtxt prag = hang (ptext SLIT("In the pragma")) 2 (ppr prag)
405 tcPrag :: TcId -> Sig Name -> TcM Prag
406 -- Pre-condition: the poly_id is zonked
407 -- Reason: required by tcSubExp
408 tcPrag poly_id (SpecSig orig_name hs_ty inl) = tcSpecPrag poly_id hs_ty inl
409 tcPrag poly_id (SpecInstSig hs_ty) = tcSpecPrag poly_id hs_ty defaultInlineSpec
410 tcPrag poly_id (InlineSig v inl) = return (InlinePrag inl)
413 tcSpecPrag :: TcId -> LHsType Name -> InlineSpec -> TcM Prag
414 tcSpecPrag poly_id hs_ty inl
415 = do { spec_ty <- tcHsSigType (FunSigCtxt (idName poly_id)) hs_ty
416 ; (co_fn, lie) <- getLIE (tcSubExp (idType poly_id) spec_ty)
418 ; let const_dicts = map instToId lie
419 ; return (SpecPrag (mkHsWrap co_fn (HsVar poly_id)) spec_ty const_dicts inl) }
420 -- Most of the work of specialisation is done by
421 -- the desugarer, guided by the SpecPrag
424 -- If typechecking the binds fails, then return with each
425 -- signature-less binder given type (forall a.a), to minimise
426 -- subsequent error messages
427 recoveryCode binder_names sig_fn
428 = do { traceTc (text "tcBindsWithSigs: error recovery" <+> ppr binder_names)
429 ; poly_ids <- mapM mk_dummy binder_names
430 ; return ([], poly_ids) }
433 | isJust (sig_fn name) = tcLookupId name -- Had signature; look it up
434 | otherwise = return (mkLocalId name forall_a_a) -- No signature
437 forall_a_a = mkForAllTy alphaTyVar (mkTyVarTy alphaTyVar)
440 -- Check that non-overloaded unlifted bindings are
443 -- c) not a multiple-binding group (more or less implied by (a))
445 checkStrictBinds :: TopLevelFlag -> RecFlag
446 -> LHsBinds TcId -> [TcType] -> [MonoBindInfo]
448 checkStrictBinds top_lvl rec_group mbind mono_tys infos
449 | unlifted || bang_pat
450 = do { checkTc (isNotTopLevel top_lvl)
451 (strictBindErr "Top-level" unlifted mbind)
452 ; checkTc (isNonRec rec_group)
453 (strictBindErr "Recursive" unlifted mbind)
454 ; checkTc (isSingletonBag mbind)
455 (strictBindErr "Multiple" unlifted mbind)
456 ; mapM_ check_sig infos
461 unlifted = any isUnLiftedType mono_tys
462 bang_pat = anyBag (isBangHsBind . unLoc) mbind
463 check_sig (_, Just sig, _) = checkTc (null (sig_tvs sig) && null (sig_theta sig))
464 (badStrictSig unlifted sig)
465 check_sig other = return ()
467 strictBindErr flavour unlifted mbind
468 = hang (text flavour <+> msg <+> ptext SLIT("aren't allowed:"))
469 4 (pprLHsBinds mbind)
471 msg | unlifted = ptext SLIT("bindings for unlifted types")
472 | otherwise = ptext SLIT("bang-pattern bindings")
474 badStrictSig unlifted sig
475 = hang (ptext SLIT("Illegal polymorphic signature in") <+> msg)
478 msg | unlifted = ptext SLIT("an unlifted binding")
479 | otherwise = ptext SLIT("a bang-pattern binding")
483 %************************************************************************
485 \subsection{tcMonoBind}
487 %************************************************************************
489 @tcMonoBinds@ deals with a perhaps-recursive group of HsBinds.
490 The signatures have been dealt with already.
493 tcMonoBinds :: [LHsBind Name]
495 -> RecFlag -- Whether the binding is recursive for typechecking purposes
496 -- i.e. the binders are mentioned in their RHSs, and
497 -- we are not resuced by a type signature
498 -> TcM (LHsBinds TcId, [MonoBindInfo])
500 tcMonoBinds [L b_loc (FunBind { fun_id = L nm_loc name, fun_infix = inf,
501 fun_matches = matches, bind_fvs = fvs })]
502 sig_fn -- Single function binding,
503 NonRecursive -- binder isn't mentioned in RHS,
504 | Nothing <- sig_fn name -- ...with no type signature
505 = -- In this very special case we infer the type of the
506 -- right hand side first (it may have a higher-rank type)
507 -- and *then* make the monomorphic Id for the LHS
508 -- e.g. f = \(x::forall a. a->a) -> <body>
509 -- We want to infer a higher-rank type for f
511 do { ((co_fn, matches'), rhs_ty) <- tcInfer (tcMatchesFun name matches)
513 -- Check for an unboxed tuple type
514 -- f = (# True, False #)
515 -- Zonk first just in case it's hidden inside a meta type variable
516 -- (This shows up as a (more obscure) kind error
517 -- in the 'otherwise' case of tcMonoBinds.)
518 ; zonked_rhs_ty <- zonkTcType rhs_ty
519 ; checkTc (not (isUnboxedTupleType zonked_rhs_ty))
520 (unboxedTupleErr name zonked_rhs_ty)
522 ; mono_name <- newLocalName name
523 ; let mono_id = mkLocalId mono_name zonked_rhs_ty
524 ; return (unitBag (L b_loc (FunBind { fun_id = L nm_loc mono_id, fun_infix = inf,
525 fun_matches = matches', bind_fvs = fvs,
526 fun_co_fn = co_fn, fun_tick = Nothing })),
527 [(name, Nothing, mono_id)]) }
529 tcMonoBinds [L b_loc (FunBind { fun_id = L nm_loc name, fun_infix = inf,
530 fun_matches = matches, bind_fvs = fvs })]
531 sig_fn -- Single function binding
533 | Just scoped_tvs <- sig_fn name -- ...with a type signature
534 = -- When we have a single function binding, with a type signature
535 -- we can (a) use genuine, rigid skolem constants for the type variables
536 -- (b) bring (rigid) scoped type variables into scope
538 do { tc_sig <- tcInstSig True name scoped_tvs
539 ; mono_name <- newLocalName name
540 ; let mono_ty = sig_tau tc_sig
541 mono_id = mkLocalId mono_name mono_ty
542 rhs_tvs = [ (name, mkTyVarTy tv)
543 | (name, tv) <- sig_scoped tc_sig `zip` sig_tvs tc_sig ]
545 ; (co_fn, matches') <- tcExtendTyVarEnv2 rhs_tvs $
546 tcMatchesFun mono_name matches mono_ty
548 ; let fun_bind' = FunBind { fun_id = L nm_loc mono_id,
549 fun_infix = inf, fun_matches = matches',
550 bind_fvs = placeHolderNames, fun_co_fn = co_fn,
552 ; return (unitBag (L b_loc fun_bind'),
553 [(name, Just tc_sig, mono_id)]) }
555 tcMonoBinds binds sig_fn non_rec
556 = do { tc_binds <- mapM (wrapLocM (tcLhs sig_fn)) binds
558 -- Bring the monomorphic Ids, into scope for the RHSs
559 ; let mono_info = getMonoBindInfo tc_binds
560 rhs_id_env = [(name,mono_id) | (name, Nothing, mono_id) <- mono_info]
561 -- A monomorphic binding for each term variable that lacks
562 -- a type sig. (Ones with a sig are already in scope.)
564 ; binds' <- tcExtendIdEnv2 rhs_id_env $
565 traceTc (text "tcMonoBinds" <+> vcat [ ppr n <+> ppr id <+> ppr (idType id)
566 | (n,id) <- rhs_id_env]) `thenM_`
567 mapM (wrapLocM tcRhs) tc_binds
568 ; return (listToBag binds', mono_info) }
570 ------------------------
571 -- tcLhs typechecks the LHS of the bindings, to construct the environment in which
572 -- we typecheck the RHSs. Basically what we are doing is this: for each binder:
573 -- if there's a signature for it, use the instantiated signature type
574 -- otherwise invent a type variable
575 -- You see that quite directly in the FunBind case.
577 -- But there's a complication for pattern bindings:
578 -- data T = MkT (forall a. a->a)
580 -- Here we can guess a type variable for the entire LHS (which will be refined to T)
581 -- but we want to get (f::forall a. a->a) as the RHS environment.
582 -- The simplest way to do this is to typecheck the pattern, and then look up the
583 -- bound mono-ids. Then we want to retain the typechecked pattern to avoid re-doing
584 -- it; hence the TcMonoBind data type in which the LHS is done but the RHS isn't
586 data TcMonoBind -- Half completed; LHS done, RHS not done
587 = TcFunBind MonoBindInfo (Located TcId) Bool (MatchGroup Name)
588 | TcPatBind [MonoBindInfo] (LPat TcId) (GRHSs Name) TcSigmaType
590 type MonoBindInfo = (Name, Maybe TcSigInfo, TcId)
591 -- Type signature (if any), and
592 -- the monomorphic bound things
594 bndrNames :: [MonoBindInfo] -> [Name]
595 bndrNames mbi = [n | (n,_,_) <- mbi]
597 getMonoType :: MonoBindInfo -> TcTauType
598 getMonoType (_,_,mono_id) = idType mono_id
600 tcLhs :: TcSigFun -> HsBind Name -> TcM TcMonoBind
601 tcLhs sig_fn (FunBind { fun_id = L nm_loc name, fun_infix = inf, fun_matches = matches })
602 = do { mb_sig <- tcInstSig_maybe sig_fn name
603 ; mono_name <- newLocalName name
604 ; mono_ty <- mk_mono_ty mb_sig
605 ; let mono_id = mkLocalId mono_name mono_ty
606 ; return (TcFunBind (name, mb_sig, mono_id) (L nm_loc mono_id) inf matches) }
608 mk_mono_ty (Just sig) = return (sig_tau sig)
609 mk_mono_ty Nothing = newFlexiTyVarTy argTypeKind
611 tcLhs sig_fn bind@(PatBind { pat_lhs = pat, pat_rhs = grhss })
612 = do { mb_sigs <- mapM (tcInstSig_maybe sig_fn) names
613 ; mono_pat_binds <- doptM Opt_MonoPatBinds
614 -- With -fmono-pat-binds, we do no generalisation of pattern bindings
615 -- But the signature can still be polymoprhic!
616 -- data T = MkT (forall a. a->a)
617 -- x :: forall a. a->a
619 -- The function get_sig_ty decides whether the pattern-bound variables
620 -- should have exactly the type in the type signature (-fmono-pat-binds),
621 -- or the instantiated version (-fmono-pat-binds)
623 ; let nm_sig_prs = names `zip` mb_sigs
624 get_sig_ty | mono_pat_binds = idType . sig_id
625 | otherwise = sig_tau
626 tau_sig_env = mkNameEnv [ (name, get_sig_ty sig)
627 | (name, Just sig) <- nm_sig_prs]
628 sig_tau_fn = lookupNameEnv tau_sig_env
630 tc_pat exp_ty = tcLetPat sig_tau_fn pat exp_ty $
631 mapM lookup_info nm_sig_prs
633 -- After typechecking the pattern, look up the binder
634 -- names, which the pattern has brought into scope.
635 lookup_info :: (Name, Maybe TcSigInfo) -> TcM MonoBindInfo
636 lookup_info (name, mb_sig) = do { mono_id <- tcLookupId name
637 ; return (name, mb_sig, mono_id) }
639 ; ((pat', infos), pat_ty) <- addErrCtxt (patMonoBindsCtxt pat grhss) $
642 ; return (TcPatBind infos pat' grhss pat_ty) }
644 names = collectPatBinders pat
647 tcLhs sig_fn other_bind = pprPanic "tcLhs" (ppr other_bind)
648 -- AbsBind, VarBind impossible
651 tcRhs :: TcMonoBind -> TcM (HsBind TcId)
652 tcRhs (TcFunBind info fun'@(L _ mono_id) inf matches)
653 = do { (co_fn, matches') <- tcMatchesFun (idName mono_id) matches
655 ; return (FunBind { fun_id = fun', fun_infix = inf, fun_matches = matches',
656 bind_fvs = placeHolderNames, fun_co_fn = co_fn,
657 fun_tick = Nothing }) }
659 tcRhs bind@(TcPatBind _ pat' grhss pat_ty)
660 = do { grhss' <- addErrCtxt (patMonoBindsCtxt pat' grhss) $
661 tcGRHSsPat grhss pat_ty
662 ; return (PatBind { pat_lhs = pat', pat_rhs = grhss', pat_rhs_ty = pat_ty,
663 bind_fvs = placeHolderNames }) }
666 ---------------------
667 getMonoBindInfo :: [Located TcMonoBind] -> [MonoBindInfo]
668 getMonoBindInfo tc_binds
669 = foldr (get_info . unLoc) [] tc_binds
671 get_info (TcFunBind info _ _ _) rest = info : rest
672 get_info (TcPatBind infos _ _ _) rest = infos ++ rest
676 %************************************************************************
680 %************************************************************************
683 generalise :: DynFlags -> TopLevelFlag
684 -> [LHsBind Name] -> TcSigFun
685 -> [MonoBindInfo] -> [Inst]
686 -> TcM ([TyVar], [Inst], TcDictBinds)
687 -- The returned [TyVar] are all ready to quantify
689 generalise dflags top_lvl bind_list sig_fn mono_infos lie_req
690 | isMonoGroup dflags bind_list
691 = do { extendLIEs lie_req
692 ; return ([], [], emptyBag) }
694 | isRestrictedGroup dflags bind_list sig_fn -- RESTRICTED CASE
695 = -- Check signature contexts are empty
696 do { checkTc (all is_mono_sig sigs)
697 (restrictedBindCtxtErr bndrs)
699 -- Now simplify with exactly that set of tyvars
700 -- We have to squash those Methods
701 ; (qtvs, binds) <- tcSimplifyRestricted doc top_lvl bndrs
704 -- Check that signature type variables are OK
705 ; final_qtvs <- checkSigsTyVars qtvs sigs
707 ; return (final_qtvs, [], binds) }
709 | null sigs -- UNRESTRICTED CASE, NO TYPE SIGS
710 = tcSimplifyInfer doc tau_tvs lie_req
712 | otherwise -- UNRESTRICTED CASE, WITH TYPE SIGS
713 = do { sig_lie <- unifyCtxts sigs -- sigs is non-empty; sig_lie is zonked
714 ; let -- The "sig_avails" is the stuff available. We get that from
715 -- the context of the type signature, BUT ALSO the lie_avail
716 -- so that polymorphic recursion works right (see Note [Polymorphic recursion])
717 local_meths = [mkMethInst sig mono_id | (_, Just sig, mono_id) <- mono_infos]
718 sig_avails = sig_lie ++ local_meths
719 loc = sig_loc (head sigs)
721 -- Check that the needed dicts can be
722 -- expressed in terms of the signature ones
723 ; (qtvs, binds) <- tcSimplifyInferCheck loc tau_tvs sig_avails lie_req
725 -- Check that signature type variables are OK
726 ; final_qtvs <- checkSigsTyVars qtvs sigs
728 ; returnM (final_qtvs, sig_lie, binds) }
730 bndrs = bndrNames mono_infos
731 sigs = [sig | (_, Just sig, _) <- mono_infos]
732 tau_tvs = foldr (unionVarSet . exactTyVarsOfType . getMonoType) emptyVarSet mono_infos
733 -- NB: exactTyVarsOfType; see Note [Silly type synonym]
734 -- near defn of TcType.exactTyVarsOfType
735 is_mono_sig sig = null (sig_theta sig)
736 doc = ptext SLIT("type signature(s) for") <+> pprBinders bndrs
738 mkMethInst (TcSigInfo { sig_id = poly_id, sig_tvs = tvs,
739 sig_theta = theta, sig_loc = loc }) mono_id
740 = Method {tci_id = mono_id, tci_oid = poly_id, tci_tys = mkTyVarTys tvs,
741 tci_theta = theta, tci_loc = loc}
744 unifyCtxts checks that all the signature contexts are the same
745 The type signatures on a mutually-recursive group of definitions
746 must all have the same context (or none).
748 The trick here is that all the signatures should have the same
749 context, and we want to share type variables for that context, so that
750 all the right hand sides agree a common vocabulary for their type
753 We unify them because, with polymorphic recursion, their types
754 might not otherwise be related. This is a rather subtle issue.
757 unifyCtxts :: [TcSigInfo] -> TcM [Inst]
758 -- Post-condition: the returned Insts are full zonked
759 unifyCtxts (sig1 : sigs) -- Argument is always non-empty
760 = do { mapM unify_ctxt sigs
761 ; theta <- zonkTcThetaType (sig_theta sig1)
762 ; newDictBndrs (sig_loc sig1) theta }
764 theta1 = sig_theta sig1
765 unify_ctxt :: TcSigInfo -> TcM ()
766 unify_ctxt sig@(TcSigInfo { sig_theta = theta })
767 = setSrcSpan (instLocSpan (sig_loc sig)) $
768 addErrCtxt (sigContextsCtxt sig1 sig) $
769 unifyTheta theta1 theta
771 checkSigsTyVars :: [TcTyVar] -> [TcSigInfo] -> TcM [TcTyVar]
772 checkSigsTyVars qtvs sigs
773 = do { gbl_tvs <- tcGetGlobalTyVars
774 ; sig_tvs_s <- mappM (check_sig gbl_tvs) sigs
776 ; let -- Sigh. Make sure that all the tyvars in the type sigs
777 -- appear in the returned ty var list, which is what we are
778 -- going to generalise over. Reason: we occasionally get
780 -- type T a = () -> ()
783 -- Here, 'a' won't appear in qtvs, so we have to add it
784 sig_tvs = foldl extendVarSetList emptyVarSet sig_tvs_s
785 all_tvs = varSetElems (extendVarSetList sig_tvs qtvs)
788 check_sig gbl_tvs (TcSigInfo {sig_id = id, sig_tvs = tvs,
789 sig_theta = theta, sig_tau = tau})
790 = addErrCtxt (ptext SLIT("In the type signature for") <+> quotes (ppr id)) $
791 addErrCtxtM (sigCtxt id tvs theta tau) $
792 do { tvs' <- checkDistinctTyVars tvs
793 ; ifM (any (`elemVarSet` gbl_tvs) tvs')
794 (bleatEscapedTvs gbl_tvs tvs tvs')
797 checkDistinctTyVars :: [TcTyVar] -> TcM [TcTyVar]
798 -- (checkDistinctTyVars tvs) checks that the tvs from one type signature
799 -- are still all type variables, and all distinct from each other.
800 -- It returns a zonked set of type variables.
801 -- For example, if the type sig is
802 -- f :: forall a b. a -> b -> b
803 -- we want to check that 'a' and 'b' haven't
804 -- (a) been unified with a non-tyvar type
805 -- (b) been unified with each other (all distinct)
807 checkDistinctTyVars sig_tvs
808 = do { zonked_tvs <- mapM zonkSigTyVar sig_tvs
809 ; foldlM check_dup emptyVarEnv (sig_tvs `zip` zonked_tvs)
810 ; return zonked_tvs }
812 check_dup :: TyVarEnv TcTyVar -> (TcTyVar, TcTyVar) -> TcM (TyVarEnv TcTyVar)
813 -- The TyVarEnv maps each zonked type variable back to its
814 -- corresponding user-written signature type variable
815 check_dup acc (sig_tv, zonked_tv)
816 = case lookupVarEnv acc zonked_tv of
817 Just sig_tv' -> bomb_out sig_tv sig_tv'
819 Nothing -> return (extendVarEnv acc zonked_tv sig_tv)
821 bomb_out sig_tv1 sig_tv2
822 = do { env0 <- tcInitTidyEnv
823 ; let (env1, tidy_tv1) = tidyOpenTyVar env0 sig_tv1
824 (env2, tidy_tv2) = tidyOpenTyVar env1 sig_tv2
825 msg = ptext SLIT("Quantified type variable") <+> quotes (ppr tidy_tv1)
826 <+> ptext SLIT("is unified with another quantified type variable")
827 <+> quotes (ppr tidy_tv2)
828 ; failWithTcM (env2, msg) }
833 @getTyVarsToGen@ decides what type variables to generalise over.
835 For a "restricted group" -- see the monomorphism restriction
836 for a definition -- we bind no dictionaries, and
837 remove from tyvars_to_gen any constrained type variables
839 *Don't* simplify dicts at this point, because we aren't going
840 to generalise over these dicts. By the time we do simplify them
841 we may well know more. For example (this actually came up)
843 f x = array ... xs where xs = [1,2,3,4,5]
844 We don't want to generate lots of (fromInt Int 1), (fromInt Int 2)
845 stuff. If we simplify only at the f-binding (not the xs-binding)
846 we'll know that the literals are all Ints, and we can just produce
849 Find all the type variables involved in overloading, the
850 "constrained_tyvars". These are the ones we *aren't* going to
851 generalise. We must be careful about doing this:
853 (a) If we fail to generalise a tyvar which is not actually
854 constrained, then it will never, ever get bound, and lands
855 up printed out in interface files! Notorious example:
856 instance Eq a => Eq (Foo a b) where ..
857 Here, b is not constrained, even though it looks as if it is.
858 Another, more common, example is when there's a Method inst in
859 the LIE, whose type might very well involve non-overloaded
861 [NOTE: Jan 2001: I don't understand the problem here so I'm doing
862 the simple thing instead]
864 (b) On the other hand, we mustn't generalise tyvars which are constrained,
865 because we are going to pass on out the unmodified LIE, with those
866 tyvars in it. They won't be in scope if we've generalised them.
868 So we are careful, and do a complete simplification just to find the
869 constrained tyvars. We don't use any of the results, except to
870 find which tyvars are constrained.
872 Note [Polymorphic recursion]
873 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
874 The game plan for polymorphic recursion in the code above is
876 * Bind any variable for which we have a type signature
877 to an Id with a polymorphic type. Then when type-checking
878 the RHSs we'll make a full polymorphic call.
880 This fine, but if you aren't a bit careful you end up with a horrendous
881 amount of partial application and (worse) a huge space leak. For example:
883 f :: Eq a => [a] -> [a]
886 If we don't take care, after typechecking we get
888 f = /\a -> \d::Eq a -> let f' = f a d
892 Notice the the stupid construction of (f a d), which is of course
893 identical to the function we're executing. In this case, the
894 polymorphic recursion isn't being used (but that's a very common case).
895 This can lead to a massive space leak, from the following top-level defn
901 Now (f dEqInt) evaluates to a lambda that has f' as a free variable; but
902 f' is another thunk which evaluates to the same thing... and you end
903 up with a chain of identical values all hung onto by the CAF ff.
907 = let f' = f Int dEqInt in \ys. ...f'...
909 = let f' = let f' = f Int dEqInt in \ys. ...f'...
914 NOTE: a bit of arity anaysis would push the (f a d) inside the (\ys...),
915 which would make the space leak go away in this case
917 Solution: when typechecking the RHSs we always have in hand the
918 *monomorphic* Ids for each binding. So we just need to make sure that
919 if (Method f a d) shows up in the constraints emerging from (...f...)
920 we just use the monomorphic Id. We achieve this by adding monomorphic Ids
921 to the "givens" when simplifying constraints. That's what the "lies_avail"
926 f = /\a -> \d::Eq a -> letrec
927 fm = \ys:[a] -> ...fm...
933 %************************************************************************
937 %************************************************************************
939 Type signatures are tricky. See Note [Signature skolems] in TcType
941 @tcSigs@ checks the signatures for validity, and returns a list of
942 {\em freshly-instantiated} signatures. That is, the types are already
943 split up, and have fresh type variables installed. All non-type-signature
944 "RenamedSigs" are ignored.
946 The @TcSigInfo@ contains @TcTypes@ because they are unified with
947 the variable's type, and after that checked to see whether they've
951 type TcSigFun = Name -> Maybe [Name] -- Maps a let-binder to the list of
952 -- type variables brought into scope
953 -- by its type signature.
954 -- Nothing => no type signature
956 mkTcSigFun :: [LSig Name] -> TcSigFun
957 -- Search for a particular type signature
958 -- Precondition: the sigs are all type sigs
959 -- Precondition: no duplicates
960 mkTcSigFun sigs = lookupNameEnv env
962 env = mkNameEnv [(name, hsExplicitTvs lhs_ty)
963 | L span (TypeSig (L _ name) lhs_ty) <- sigs]
964 -- The scoped names are the ones explicitly mentioned
965 -- in the HsForAll. (There may be more in sigma_ty, because
966 -- of nested type synonyms. See Note [Scoped] with TcSigInfo.)
967 -- See Note [Only scoped tyvars are in the TyVarEnv]
972 sig_id :: TcId, -- *Polymorphic* binder for this value...
974 sig_scoped :: [Name], -- Names for any scoped type variables
975 -- Invariant: correspond 1-1 with an initial
976 -- segment of sig_tvs (see Note [Scoped])
978 sig_tvs :: [TcTyVar], -- Instantiated type variables
979 -- See Note [Instantiate sig]
981 sig_theta :: TcThetaType, -- Instantiated theta
982 sig_tau :: TcTauType, -- Instantiated tau
983 sig_loc :: InstLoc -- The location of the signature
987 -- Note [Only scoped tyvars are in the TyVarEnv]
988 -- We are careful to keep only the *lexically scoped* type variables in
989 -- the type environment. Why? After all, the renamer has ensured
990 -- that only legal occurrences occur, so we could put all type variables
991 -- into the type env.
993 -- But we want to check that two distinct lexically scoped type variables
994 -- do not map to the same internal type variable. So we need to know which
995 -- the lexically-scoped ones are... and at the moment we do that by putting
996 -- only the lexically scoped ones into the environment.
1000 -- There may be more instantiated type variables than scoped
1001 -- ones. For example:
1002 -- type T a = forall b. b -> (a,b)
1003 -- f :: forall c. T c
1004 -- Here, the signature for f will have one scoped type variable, c,
1005 -- but two instantiated type variables, c' and b'.
1007 -- We assume that the scoped ones are at the *front* of sig_tvs,
1008 -- and remember the names from the original HsForAllTy in sig_scoped
1010 -- Note [Instantiate sig]
1011 -- It's vital to instantiate a type signature with fresh variables.
1013 -- type S = forall a. a->a
1017 -- Here, we must use distinct type variables when checking f,g's right hand sides.
1018 -- (Instantiation is only necessary because of type synonyms. Otherwise,
1019 -- it's all cool; each signature has distinct type variables from the renamer.)
1021 instance Outputable TcSigInfo where
1022 ppr (TcSigInfo { sig_id = id, sig_tvs = tyvars, sig_theta = theta, sig_tau = tau})
1023 = ppr id <+> ptext SLIT("::") <+> ppr tyvars <+> ppr theta <+> ptext SLIT("=>") <+> ppr tau
1027 tcTySig :: LSig Name -> TcM TcId
1028 tcTySig (L span (TypeSig (L _ name) ty))
1030 do { sigma_ty <- tcHsSigType (FunSigCtxt name) ty
1031 ; return (mkLocalId name sigma_ty) }
1034 tcInstSig_maybe :: TcSigFun -> Name -> TcM (Maybe TcSigInfo)
1035 -- Instantiate with *meta* type variables;
1036 -- this signature is part of a multi-signature group
1037 tcInstSig_maybe sig_fn name
1038 = case sig_fn name of
1039 Nothing -> return Nothing
1040 Just tvs -> do { tc_sig <- tcInstSig False name tvs
1041 ; return (Just tc_sig) }
1043 tcInstSig :: Bool -> Name -> [Name] -> TcM TcSigInfo
1044 -- Instantiate the signature, with either skolems or meta-type variables
1045 -- depending on the use_skols boolean. This variable is set True
1046 -- when we are typechecking a single function binding; and False for
1047 -- pattern bindings and a group of several function bindings.
1048 -- Reason: in the latter cases, the "skolems" can be unified together,
1049 -- so they aren't properly rigid in the type-refinement sense.
1050 -- NB: unless we are doing H98, each function with a sig will be done
1051 -- separately, even if it's mutually recursive, so use_skols will be True
1053 -- We always instantiate with fresh uniques,
1054 -- although we keep the same print-name
1056 -- type T = forall a. [a] -> [a]
1058 -- f = g where { g :: T; g = <rhs> }
1060 -- We must not use the same 'a' from the defn of T at both places!!
1062 tcInstSig use_skols name scoped_names
1063 = do { poly_id <- tcLookupId name -- Cannot fail; the poly ids are put into
1064 -- scope when starting the binding group
1065 ; let skol_info = SigSkol (FunSigCtxt name)
1066 inst_tyvars = tcInstSigTyVars use_skols skol_info
1067 ; (tvs, theta, tau) <- tcInstType inst_tyvars (idType poly_id)
1068 ; loc <- getInstLoc (SigOrigin skol_info)
1069 ; return (TcSigInfo { sig_id = poly_id,
1070 sig_tvs = tvs, sig_theta = theta, sig_tau = tau,
1071 sig_scoped = final_scoped_names, sig_loc = loc }) }
1072 -- Note that the scoped_names and the sig_tvs will have
1073 -- different Names. That's quite ok; when we bring the
1074 -- scoped_names into scope, we just bind them to the sig_tvs
1076 -- We also only have scoped type variables when we are instantiating
1077 -- with true skolems
1078 final_scoped_names | use_skols = scoped_names
1082 isMonoGroup :: DynFlags -> [LHsBind Name] -> Bool
1083 -- No generalisation at all
1084 isMonoGroup dflags binds
1085 = dopt Opt_MonoPatBinds dflags && any is_pat_bind binds
1087 is_pat_bind (L _ (PatBind {})) = True
1088 is_pat_bind other = False
1091 isRestrictedGroup :: DynFlags -> [LHsBind Name] -> TcSigFun -> Bool
1092 isRestrictedGroup dflags binds sig_fn
1093 = mono_restriction && not all_unrestricted
1095 mono_restriction = dopt Opt_MonomorphismRestriction dflags
1096 all_unrestricted = all (unrestricted . unLoc) binds
1097 has_sig n = isJust (sig_fn n)
1099 unrestricted (PatBind {}) = False
1100 unrestricted (VarBind { var_id = v }) = has_sig v
1101 unrestricted (FunBind { fun_id = v, fun_matches = matches }) = unrestricted_match matches
1102 || has_sig (unLoc v)
1104 unrestricted_match (MatchGroup (L _ (Match [] _ _) : _) _) = False
1105 -- No args => like a pattern binding
1106 unrestricted_match other = True
1107 -- Some args => a function binding
1111 %************************************************************************
1113 \subsection[TcBinds-errors]{Error contexts and messages}
1115 %************************************************************************
1119 -- This one is called on LHS, when pat and grhss are both Name
1120 -- and on RHS, when pat is TcId and grhss is still Name
1121 patMonoBindsCtxt pat grhss
1122 = hang (ptext SLIT("In a pattern binding:")) 4 (pprPatBind pat grhss)
1124 -----------------------------------------------
1125 sigContextsCtxt sig1 sig2
1126 = vcat [ptext SLIT("When matching the contexts of the signatures for"),
1127 nest 2 (vcat [ppr id1 <+> dcolon <+> ppr (idType id1),
1128 ppr id2 <+> dcolon <+> ppr (idType id2)]),
1129 ptext SLIT("The signature contexts in a mutually recursive group should all be identical")]
1135 -----------------------------------------------
1136 unboxedTupleErr name ty
1137 = hang (ptext SLIT("Illegal binding of unboxed tuple"))
1138 4 (ppr name <+> dcolon <+> ppr ty)
1140 -----------------------------------------------
1141 restrictedBindCtxtErr binder_names
1142 = hang (ptext SLIT("Illegal overloaded type signature(s)"))
1143 4 (vcat [ptext SLIT("in a binding group for") <+> pprBinders binder_names,
1144 ptext SLIT("that falls under the monomorphism restriction")])
1146 genCtxt binder_names
1147 = ptext SLIT("When generalising the type(s) for") <+> pprBinders binder_names