Print which warning-flag controls an emitted warning
[ghc.git] / compiler / typecheck / TcBinds.hs
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
8 {-# LANGUAGE CPP, RankNTypes, ScopedTypeVariables #-}
9
10 module TcBinds ( tcLocalBinds, tcTopBinds, tcRecSelBinds,
11 tcValBinds, tcHsBootSigs, tcPolyCheck,
12 tcSpecPrags, tcSpecWrapper,
13 tcVectDecls, addTypecheckedBinds,
14 TcSigInfo(..), TcSigFun,
15 TcPragEnv, mkPragEnv,
16 tcUserTypeSig, instTcTySig, chooseInferredQuantifiers,
17 instTcTySigFromId, tcExtendTyVarEnvFromSig,
18 badBootDeclErr ) where
19
20 import {-# SOURCE #-} TcMatches ( tcGRHSsPat, tcMatchesFun )
21 import {-# SOURCE #-} TcExpr ( tcMonoExpr )
22 import {-# SOURCE #-} TcPatSyn ( tcInferPatSynDecl, tcCheckPatSynDecl
23 , tcPatSynBuilderBind, tcPatSynSig )
24 import DynFlags
25 import HsSyn
26 import HscTypes( isHsBootOrSig )
27 import TcRnMonad
28 import TcEnv
29 import TcUnify
30 import TcSimplify
31 import TcEvidence
32 import TcHsType
33 import TcPat
34 import TcMType
35 import Inst( topInstantiate, deeplyInstantiate )
36 import FamInstEnv( normaliseType )
37 import FamInst( tcGetFamInstEnvs )
38 import TyCon
39 import TcType
40 import TysPrim
41 import Id
42 import Var
43 import VarSet
44 import VarEnv( TidyEnv )
45 import Module
46 import Name
47 import NameSet
48 import NameEnv
49 import SrcLoc
50 import Bag
51 import ListSetOps
52 import ErrUtils
53 import Digraph
54 import Maybes
55 import Util
56 import BasicTypes
57 import Outputable
58 import Type(mkStrLitTy, tidyOpenType)
59 import PrelNames( mkUnboundName, gHC_PRIM, ipClassName )
60 import TcValidity (checkValidType)
61 import qualified GHC.LanguageExtensions as LangExt
62
63 import Control.Monad
64
65 #include "HsVersions.h"
66
67 {- *********************************************************************
68 * *
69 A useful helper function
70 * *
71 ********************************************************************* -}
72
73 addTypecheckedBinds :: TcGblEnv -> [LHsBinds Id] -> TcGblEnv
74 addTypecheckedBinds tcg_env binds
75 | isHsBootOrSig (tcg_src tcg_env) = tcg_env
76 -- Do not add the code for record-selector bindings
77 -- when compiling hs-boot files
78 | otherwise = tcg_env { tcg_binds = foldr unionBags
79 (tcg_binds tcg_env)
80 binds }
81
82 {-
83 ************************************************************************
84 * *
85 \subsection{Type-checking bindings}
86 * *
87 ************************************************************************
88
89 @tcBindsAndThen@ typechecks a @HsBinds@. The "and then" part is because
90 it needs to know something about the {\em usage} of the things bound,
91 so that it can create specialisations of them. So @tcBindsAndThen@
92 takes a function which, given an extended environment, E, typechecks
93 the scope of the bindings returning a typechecked thing and (most
94 important) an LIE. It is this LIE which is then used as the basis for
95 specialising the things bound.
96
97 @tcBindsAndThen@ also takes a "combiner" which glues together the
98 bindings and the "thing" to make a new "thing".
99
100 The real work is done by @tcBindWithSigsAndThen@.
101
102 Recursive and non-recursive binds are handled in essentially the same
103 way: because of uniques there are no scoping issues left. The only
104 difference is that non-recursive bindings can bind primitive values.
105
106 Even for non-recursive binding groups we add typings for each binder
107 to the LVE for the following reason. When each individual binding is
108 checked the type of its LHS is unified with that of its RHS; and
109 type-checking the LHS of course requires that the binder is in scope.
110
111 At the top-level the LIE is sure to contain nothing but constant
112 dictionaries, which we resolve at the module level.
113
114 Note [Polymorphic recursion]
115 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
116 The game plan for polymorphic recursion in the code above is
117
118 * Bind any variable for which we have a type signature
119 to an Id with a polymorphic type. Then when type-checking
120 the RHSs we'll make a full polymorphic call.
121
122 This fine, but if you aren't a bit careful you end up with a horrendous
123 amount of partial application and (worse) a huge space leak. For example:
124
125 f :: Eq a => [a] -> [a]
126 f xs = ...f...
127
128 If we don't take care, after typechecking we get
129
130 f = /\a -> \d::Eq a -> let f' = f a d
131 in
132 \ys:[a] -> ...f'...
133
134 Notice the the stupid construction of (f a d), which is of course
135 identical to the function we're executing. In this case, the
136 polymorphic recursion isn't being used (but that's a very common case).
137 This can lead to a massive space leak, from the following top-level defn
138 (post-typechecking)
139
140 ff :: [Int] -> [Int]
141 ff = f Int dEqInt
142
143 Now (f dEqInt) evaluates to a lambda that has f' as a free variable; but
144 f' is another thunk which evaluates to the same thing... and you end
145 up with a chain of identical values all hung onto by the CAF ff.
146
147 ff = f Int dEqInt
148
149 = let f' = f Int dEqInt in \ys. ...f'...
150
151 = let f' = let f' = f Int dEqInt in \ys. ...f'...
152 in \ys. ...f'...
153
154 Etc.
155
156 NOTE: a bit of arity anaysis would push the (f a d) inside the (\ys...),
157 which would make the space leak go away in this case
158
159 Solution: when typechecking the RHSs we always have in hand the
160 *monomorphic* Ids for each binding. So we just need to make sure that
161 if (Method f a d) shows up in the constraints emerging from (...f...)
162 we just use the monomorphic Id. We achieve this by adding monomorphic Ids
163 to the "givens" when simplifying constraints. That's what the "lies_avail"
164 is doing.
165
166 Then we get
167
168 f = /\a -> \d::Eq a -> letrec
169 fm = \ys:[a] -> ...fm...
170 in
171 fm
172 -}
173
174 tcTopBinds :: [(RecFlag, LHsBinds Name)] -> [LSig Name] -> TcM (TcGblEnv, TcLclEnv)
175 -- The TcGblEnv contains the new tcg_binds and tcg_spects
176 -- The TcLclEnv has an extended type envt for the new bindings
177 tcTopBinds binds sigs
178 = do { -- Pattern synonym bindings populate the global environment
179 (binds', (tcg_env, tcl_env)) <- tcValBinds TopLevel binds sigs $
180 do { gbl <- getGblEnv
181 ; lcl <- getLclEnv
182 ; return (gbl, lcl) }
183 ; specs <- tcImpPrags sigs -- SPECIALISE prags for imported Ids
184
185 ; let { tcg_env' = tcg_env { tcg_imp_specs = specs ++ tcg_imp_specs tcg_env }
186 `addTypecheckedBinds` map snd binds' }
187
188 ; return (tcg_env', tcl_env) }
189 -- The top level bindings are flattened into a giant
190 -- implicitly-mutually-recursive LHsBinds
191
192 tcRecSelBinds :: HsValBinds Name -> TcM TcGblEnv
193 tcRecSelBinds (ValBindsOut binds sigs)
194 = tcExtendGlobalValEnv [sel_id | L _ (IdSig sel_id) <- sigs] $
195 do { (rec_sel_binds, tcg_env) <- discardWarnings $
196 tcValBinds TopLevel binds sigs getGblEnv
197 ; let tcg_env' = tcg_env `addTypecheckedBinds` map snd rec_sel_binds
198 ; return tcg_env' }
199 tcRecSelBinds (ValBindsIn {}) = panic "tcRecSelBinds"
200
201 tcHsBootSigs :: [(RecFlag, LHsBinds Name)] -> [LSig Name] -> TcM [Id]
202 -- A hs-boot file has only one BindGroup, and it only has type
203 -- signatures in it. The renamer checked all this
204 tcHsBootSigs binds sigs
205 = do { checkTc (null binds) badBootDeclErr
206 ; concat <$> mapM (addLocM tc_boot_sig) (filter isTypeLSig sigs) }
207 where
208 tc_boot_sig (TypeSig lnames hs_ty) = mapM f lnames
209 where
210 f (L _ name)
211 = do { sigma_ty <- solveEqualities $
212 tcHsSigWcType (FunSigCtxt name False) hs_ty
213 ; return (mkVanillaGlobal name sigma_ty) }
214 -- Notice that we make GlobalIds, not LocalIds
215 tc_boot_sig s = pprPanic "tcHsBootSigs/tc_boot_sig" (ppr s)
216
217 badBootDeclErr :: MsgDoc
218 badBootDeclErr = text "Illegal declarations in an hs-boot file"
219
220 ------------------------
221 tcLocalBinds :: HsLocalBinds Name -> TcM thing
222 -> TcM (HsLocalBinds TcId, thing)
223
224 tcLocalBinds EmptyLocalBinds thing_inside
225 = do { thing <- thing_inside
226 ; return (EmptyLocalBinds, thing) }
227
228 tcLocalBinds (HsValBinds (ValBindsOut binds sigs)) thing_inside
229 = do { (binds', thing) <- tcValBinds NotTopLevel binds sigs thing_inside
230 ; return (HsValBinds (ValBindsOut binds' sigs), thing) }
231 tcLocalBinds (HsValBinds (ValBindsIn {})) _ = panic "tcLocalBinds"
232
233 tcLocalBinds (HsIPBinds (IPBinds ip_binds _)) thing_inside
234 = do { ipClass <- tcLookupClass ipClassName
235 ; (given_ips, ip_binds') <-
236 mapAndUnzipM (wrapLocSndM (tc_ip_bind ipClass)) ip_binds
237
238 -- If the binding binds ?x = E, we must now
239 -- discharge any ?x constraints in expr_lie
240 -- See Note [Implicit parameter untouchables]
241 ; (ev_binds, result) <- checkConstraints (IPSkol ips)
242 [] given_ips thing_inside
243
244 ; return (HsIPBinds (IPBinds ip_binds' ev_binds), result) }
245 where
246 ips = [ip | L _ (IPBind (Left (L _ ip)) _) <- ip_binds]
247
248 -- I wonder if we should do these one at at time
249 -- Consider ?x = 4
250 -- ?y = ?x + 1
251 tc_ip_bind ipClass (IPBind (Left (L _ ip)) expr)
252 = do { ty <- newOpenFlexiTyVarTy
253 ; let p = mkStrLitTy $ hsIPNameFS ip
254 ; ip_id <- newDict ipClass [ p, ty ]
255 ; expr' <- tcMonoExpr expr (mkCheckExpType ty)
256 ; let d = toDict ipClass p ty `fmap` expr'
257 ; return (ip_id, (IPBind (Right ip_id) d)) }
258 tc_ip_bind _ (IPBind (Right {}) _) = panic "tc_ip_bind"
259
260 -- Coerces a `t` into a dictionry for `IP "x" t`.
261 -- co : t -> IP "x" t
262 toDict ipClass x ty = HsWrap $ mkWpCastR $
263 wrapIP $ mkClassPred ipClass [x,ty]
264
265 {- Note [Implicit parameter untouchables]
266 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
267 We add the type variables in the types of the implicit parameters
268 as untouchables, not so much because we really must not unify them,
269 but rather because we otherwise end up with constraints like this
270 Num alpha, Implic { wanted = alpha ~ Int }
271 The constraint solver solves alpha~Int by unification, but then
272 doesn't float that solved constraint out (it's not an unsolved
273 wanted). Result disaster: the (Num alpha) is again solved, this
274 time by defaulting. No no no.
275
276 However [Oct 10] this is all handled automatically by the
277 untouchable-range idea.
278
279 Note [Inlining and hs-boot files]
280 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
281 Consider this example (Trac #10083):
282
283 ---------- RSR.hs-boot ------------
284 module RSR where
285 data RSR
286 eqRSR :: RSR -> RSR -> Bool
287
288 ---------- SR.hs ------------
289 module SR where
290 import {-# SOURCE #-} RSR
291 data SR = MkSR RSR
292 eqSR (MkSR r1) (MkSR r2) = eqRSR r1 r2
293
294 ---------- RSR.hs ------------
295 module RSR where
296 import SR
297 data RSR = MkRSR SR -- deriving( Eq )
298 eqRSR (MkRSR s1) (MkRSR s2) = (eqSR s1 s2)
299 foo x y = not (eqRSR x y)
300
301 When compiling RSR we get this code
302
303 RSR.eqRSR :: RSR -> RSR -> Bool
304 RSR.eqRSR = \ (ds1 :: RSR.RSR) (ds2 :: RSR.RSR) ->
305 case ds1 of _ { RSR.MkRSR s1 ->
306 case ds2 of _ { RSR.MkRSR s2 ->
307 SR.eqSR s1 s2 }}
308
309 RSR.foo :: RSR -> RSR -> Bool
310 RSR.foo = \ (x :: RSR) (y :: RSR) -> not (RSR.eqRSR x y)
311
312 Now, when optimising foo:
313 Inline eqRSR (small, non-rec)
314 Inline eqSR (small, non-rec)
315 but the result of inlining eqSR from SR is another call to eqRSR, so
316 everything repeats. Neither eqSR nor eqRSR are (apparently) loop
317 breakers.
318
319 Solution: when compiling RSR, add a NOINLINE pragma to every function
320 exported by the boot-file for RSR (if it exists).
321
322 ALAS: doing so makes the boostrappted GHC itself slower by 8% overall
323 (on Trac #9872a-d, and T1969. So I un-did this change, and
324 parked it for now. Sigh.
325 -}
326
327 tcValBinds :: TopLevelFlag
328 -> [(RecFlag, LHsBinds Name)] -> [LSig Name]
329 -> TcM thing
330 -> TcM ([(RecFlag, LHsBinds TcId)], thing)
331
332 tcValBinds top_lvl binds sigs thing_inside
333 = do { let patsyns = getPatSynBinds binds
334
335 -- Typecheck the signature
336 ; (poly_ids, sig_fn) <- tcAddPatSynPlaceholders patsyns $
337 tcTySigs sigs
338
339 ; _self_boot <- tcSelfBootInfo
340 ; let prag_fn = mkPragEnv sigs (foldr (unionBags . snd) emptyBag binds)
341
342 -- ------- See Note [Inlining and hs-boot files] (change parked) --------
343 -- prag_fn | isTopLevel top_lvl -- See Note [Inlining and hs-boot files]
344 -- , SelfBoot { sb_ids = boot_id_names } <- self_boot
345 -- = foldNameSet add_no_inl prag_fn1 boot_id_names
346 -- | otherwise
347 -- = prag_fn1
348 -- add_no_inl boot_id_name prag_fn
349 -- = extendPragEnv prag_fn (boot_id_name, no_inl_sig boot_id_name)
350 -- no_inl_sig name = L boot_loc (InlineSig (L boot_loc name) neverInlinePragma)
351 -- boot_loc = mkGeneralSrcSpan (fsLit "The hs-boot file for this module")
352
353 -- Extend the envt right away with all the Ids
354 -- declared with complete type signatures
355 -- Do not extend the TcIdBinderStack; instead
356 -- we extend it on a per-rhs basis in tcExtendForRhs
357 ; tcExtendLetEnvIds top_lvl [(idName id, id) | id <- poly_ids] $ do
358 { (binds', (extra_binds', thing)) <- tcBindGroups top_lvl sig_fn prag_fn binds $ do
359 { thing <- thing_inside
360 -- See Note [Pattern synonym builders don't yield dependencies]
361 ; patsyn_builders <- mapM (tcPatSynBuilderBind sig_fn) patsyns
362 ; let extra_binds = [ (NonRecursive, builder) | builder <- patsyn_builders ]
363 ; return (extra_binds, thing) }
364 ; return (binds' ++ extra_binds', thing) }}
365
366 ------------------------
367 tcBindGroups :: TopLevelFlag -> TcSigFun -> TcPragEnv
368 -> [(RecFlag, LHsBinds Name)] -> TcM thing
369 -> TcM ([(RecFlag, LHsBinds TcId)], thing)
370 -- Typecheck a whole lot of value bindings,
371 -- one strongly-connected component at a time
372 -- Here a "strongly connected component" has the strightforward
373 -- meaning of a group of bindings that mention each other,
374 -- ignoring type signatures (that part comes later)
375
376 tcBindGroups _ _ _ [] thing_inside
377 = do { thing <- thing_inside
378 ; return ([], thing) }
379
380 tcBindGroups top_lvl sig_fn prag_fn (group : groups) thing_inside
381 = do { (group', (groups', thing))
382 <- tc_group top_lvl sig_fn prag_fn group $
383 tcBindGroups top_lvl sig_fn prag_fn groups thing_inside
384 ; return (group' ++ groups', thing) }
385
386 ------------------------
387 tc_group :: forall thing.
388 TopLevelFlag -> TcSigFun -> TcPragEnv
389 -> (RecFlag, LHsBinds Name) -> TcM thing
390 -> TcM ([(RecFlag, LHsBinds TcId)], thing)
391
392 -- Typecheck one strongly-connected component of the original program.
393 -- We get a list of groups back, because there may
394 -- be specialisations etc as well
395
396 tc_group top_lvl sig_fn prag_fn (NonRecursive, binds) thing_inside
397 -- A single non-recursive binding
398 -- We want to keep non-recursive things non-recursive
399 -- so that we desugar unlifted bindings correctly
400 = do { let bind = case bagToList binds of
401 [bind] -> bind
402 [] -> panic "tc_group: empty list of binds"
403 _ -> panic "tc_group: NonRecursive binds is not a singleton bag"
404 ; (bind', thing) <- tc_single top_lvl sig_fn prag_fn bind thing_inside
405 ; return ( [(NonRecursive, bind')], thing) }
406
407 tc_group top_lvl sig_fn prag_fn (Recursive, binds) thing_inside
408 = -- To maximise polymorphism, we do a new
409 -- strongly-connected-component analysis, this time omitting
410 -- any references to variables with type signatures.
411 -- (This used to be optional, but isn't now.)
412 -- See Note [Polymorphic recursion] in HsBinds.
413 do { traceTc "tc_group rec" (pprLHsBinds binds)
414 ; when hasPatSyn $ recursivePatSynErr binds
415 ; (binds1, thing) <- go sccs
416 ; return ([(Recursive, binds1)], thing) }
417 -- Rec them all together
418 where
419 hasPatSyn = anyBag (isPatSyn . unLoc) binds
420 isPatSyn PatSynBind{} = True
421 isPatSyn _ = False
422
423 sccs :: [SCC (LHsBind Name)]
424 sccs = stronglyConnCompFromEdgedVertices (mkEdges sig_fn binds)
425
426 go :: [SCC (LHsBind Name)] -> TcM (LHsBinds TcId, thing)
427 go (scc:sccs) = do { (binds1, ids1) <- tc_scc scc
428 ; (binds2, thing) <- tcExtendLetEnv top_lvl ids1 $
429 go sccs
430 ; return (binds1 `unionBags` binds2, thing) }
431 go [] = do { thing <- thing_inside; return (emptyBag, thing) }
432
433 tc_scc (AcyclicSCC bind) = tc_sub_group NonRecursive [bind]
434 tc_scc (CyclicSCC binds) = tc_sub_group Recursive binds
435
436 tc_sub_group = tcPolyBinds top_lvl sig_fn prag_fn Recursive
437
438 recursivePatSynErr :: OutputableBndr name => LHsBinds name -> TcM a
439 recursivePatSynErr binds
440 = failWithTc $
441 hang (text "Recursive pattern synonym definition with following bindings:")
442 2 (vcat $ map pprLBind . bagToList $ binds)
443 where
444 pprLoc loc = parens (text "defined at" <+> ppr loc)
445 pprLBind (L loc bind) = pprWithCommas ppr (collectHsBindBinders bind) <+>
446 pprLoc loc
447
448 tc_single :: forall thing.
449 TopLevelFlag -> TcSigFun -> TcPragEnv
450 -> LHsBind Name -> TcM thing
451 -> TcM (LHsBinds TcId, thing)
452 tc_single _top_lvl sig_fn _prag_fn (L _ (PatSynBind psb@PSB{ psb_id = L _ name })) thing_inside
453 = do { (aux_binds, tcg_env) <- tc_pat_syn_decl
454 ; thing <- setGblEnv tcg_env thing_inside
455 ; return (aux_binds, thing)
456 }
457 where
458 tc_pat_syn_decl :: TcM (LHsBinds TcId, TcGblEnv)
459 tc_pat_syn_decl = case sig_fn name of
460 Nothing -> tcInferPatSynDecl psb
461 Just (TcPatSynSig tpsi) -> tcCheckPatSynDecl psb tpsi
462 Just _ -> panic "tc_single"
463
464 tc_single top_lvl sig_fn prag_fn lbind thing_inside
465 = do { (binds1, ids) <- tcPolyBinds top_lvl sig_fn prag_fn
466 NonRecursive NonRecursive
467 [lbind]
468 ; thing <- tcExtendLetEnv top_lvl ids thing_inside
469 ; return (binds1, thing) }
470
471 ------------------------
472 type BKey = Int -- Just number off the bindings
473
474 mkEdges :: TcSigFun -> LHsBinds Name -> [Node BKey (LHsBind Name)]
475 -- See Note [Polymorphic recursion] in HsBinds.
476 mkEdges sig_fn binds
477 = [ (bind, key, [key | n <- nameSetElems (bind_fvs (unLoc bind)),
478 Just key <- [lookupNameEnv key_map n], no_sig n ])
479 | (bind, key) <- keyd_binds
480 ]
481 where
482 no_sig :: Name -> Bool
483 no_sig n = noCompleteSig (sig_fn n)
484
485 keyd_binds = bagToList binds `zip` [0::BKey ..]
486
487 key_map :: NameEnv BKey -- Which binding it comes from
488 key_map = mkNameEnv [(bndr, key) | (L _ bind, key) <- keyd_binds
489 , bndr <- collectHsBindBinders bind ]
490
491 ------------------------
492 tcPolyBinds :: TopLevelFlag -> TcSigFun -> TcPragEnv
493 -> RecFlag -- Whether the group is really recursive
494 -> RecFlag -- Whether it's recursive after breaking
495 -- dependencies based on type signatures
496 -> [LHsBind Name] -- None are PatSynBind
497 -> TcM (LHsBinds TcId, [TcId])
498
499 -- Typechecks a single bunch of values bindings all together,
500 -- and generalises them. The bunch may be only part of a recursive
501 -- group, because we use type signatures to maximise polymorphism
502 --
503 -- Returns a list because the input may be a single non-recursive binding,
504 -- in which case the dependency order of the resulting bindings is
505 -- important.
506 --
507 -- Knows nothing about the scope of the bindings
508 -- None of the bindings are pattern synonyms
509
510 tcPolyBinds top_lvl sig_fn prag_fn rec_group rec_tc bind_list
511 = setSrcSpan loc $
512 recoverM (recoveryCode binder_names sig_fn) $ do
513 -- Set up main recover; take advantage of any type sigs
514
515 { traceTc "------------------------------------------------" Outputable.empty
516 ; traceTc "Bindings for {" (ppr binder_names)
517 ; dflags <- getDynFlags
518 ; type_env <- getLclTypeEnv
519 ; let plan = decideGeneralisationPlan dflags type_env
520 binder_names bind_list sig_fn
521 ; traceTc "Generalisation plan" (ppr plan)
522 ; result@(tc_binds, poly_ids) <- case plan of
523 NoGen -> tcPolyNoGen rec_tc prag_fn sig_fn bind_list
524 InferGen mn -> tcPolyInfer rec_tc prag_fn sig_fn mn bind_list
525 CheckGen lbind sig -> tcPolyCheck rec_tc prag_fn sig lbind
526
527 -- Check whether strict bindings are ok
528 -- These must be non-recursive etc, and are not generalised
529 -- They desugar to a case expression in the end
530 ; checkStrictBinds top_lvl rec_group bind_list tc_binds poly_ids
531 ; traceTc "} End of bindings for" (vcat [ ppr binder_names, ppr rec_group
532 , vcat [ppr id <+> ppr (idType id) | id <- poly_ids]
533 ])
534
535 ; return result }
536 where
537 binder_names = collectHsBindListBinders bind_list
538 loc = foldr1 combineSrcSpans (map getLoc bind_list)
539 -- The mbinds have been dependency analysed and
540 -- may no longer be adjacent; so find the narrowest
541 -- span that includes them all
542
543 ------------------
544 tcPolyNoGen -- No generalisation whatsoever
545 :: RecFlag -- Whether it's recursive after breaking
546 -- dependencies based on type signatures
547 -> TcPragEnv -> TcSigFun
548 -> [LHsBind Name]
549 -> TcM (LHsBinds TcId, [TcId])
550
551 tcPolyNoGen rec_tc prag_fn tc_sig_fn bind_list
552 = do { (binds', mono_infos) <- tcMonoBinds rec_tc tc_sig_fn
553 (LetGblBndr prag_fn)
554 bind_list
555 ; mono_ids' <- mapM tc_mono_info mono_infos
556 ; return (binds', mono_ids') }
557 where
558 tc_mono_info (MBI { mbi_poly_name = name, mbi_mono_id = mono_id })
559 = do { mono_ty' <- zonkTcType (idType mono_id)
560 -- Zonk, mainly to expose unboxed types to checkStrictBinds
561 ; let mono_id' = setIdType mono_id mono_ty'
562 ; _specs <- tcSpecPrags mono_id' (lookupPragEnv prag_fn name)
563 ; return mono_id' }
564 -- NB: tcPrags generates error messages for
565 -- specialisation pragmas for non-overloaded sigs
566 -- Indeed that is why we call it here!
567 -- So we can safely ignore _specs
568
569 ------------------
570 tcPolyCheck :: RecFlag -- Whether it's recursive after breaking
571 -- dependencies based on type signatures
572 -> TcPragEnv
573 -> TcIdSigInfo
574 -> LHsBind Name
575 -> TcM (LHsBinds TcId, [TcId])
576 -- There is just one binding,
577 -- it binds a single variable,
578 -- it has a complete type signature,
579 tcPolyCheck rec_tc prag_fn
580 sig@(TISI { sig_bndr = CompleteSig poly_id
581 , sig_skols = skol_prs
582 , sig_theta = theta
583 , sig_tau = tau
584 , sig_ctxt = ctxt
585 , sig_loc = loc })
586 bind
587 = do { ev_vars <- newEvVars theta
588 ; let skol_info = SigSkol ctxt (mkCheckExpType $ mkPhiTy theta tau)
589 prag_sigs = lookupPragEnv prag_fn name
590 skol_tvs = map snd skol_prs
591 -- Find the location of the original source type sig, if
592 -- there is was one. This will appear in messages like
593 -- "type variable x is bound by .. at <loc>"
594 name = idName poly_id
595 ; (ev_binds, (binds', _))
596 <- setSrcSpan loc $
597 checkConstraints skol_info skol_tvs ev_vars $
598 tcMonoBinds rec_tc (\_ -> Just (TcIdSig sig)) LetLclBndr [bind]
599
600 ; spec_prags <- tcSpecPrags poly_id prag_sigs
601 ; poly_id <- addInlinePrags poly_id prag_sigs
602
603 ; let bind' = case bagToList binds' of
604 [b] -> b
605 _ -> pprPanic "tcPolyCheck" (ppr binds')
606 abs_bind = L loc $ AbsBindsSig
607 { abs_tvs = skol_tvs
608 , abs_ev_vars = ev_vars
609 , abs_sig_export = poly_id
610 , abs_sig_prags = SpecPrags spec_prags
611 , abs_sig_ev_bind = ev_binds
612 , abs_sig_bind = bind' }
613
614 ; return (unitBag abs_bind, [poly_id]) }
615
616 tcPolyCheck _rec_tc _prag_fn sig _bind
617 = pprPanic "tcPolyCheck" (ppr sig)
618
619 ------------------
620 tcPolyInfer
621 :: RecFlag -- Whether it's recursive after breaking
622 -- dependencies based on type signatures
623 -> TcPragEnv -> TcSigFun
624 -> Bool -- True <=> apply the monomorphism restriction
625 -> [LHsBind Name]
626 -> TcM (LHsBinds TcId, [TcId])
627 tcPolyInfer rec_tc prag_fn tc_sig_fn mono bind_list
628 = do { (tclvl, wanted, (binds', mono_infos))
629 <- pushLevelAndCaptureConstraints $
630 tcMonoBinds rec_tc tc_sig_fn LetLclBndr bind_list
631
632 ; let name_taus = [ (mbi_poly_name info, idType (mbi_mono_id info))
633 | info <- mono_infos ]
634 sigs = [ sig | MBI { mbi_sig = Just sig } <- mono_infos ]
635
636 ; traceTc "simplifyInfer call" (ppr tclvl $$ ppr name_taus $$ ppr wanted)
637 ; (qtvs, givens, ev_binds)
638 <- simplifyInfer tclvl mono sigs name_taus wanted
639
640 ; let inferred_theta = map evVarPred givens
641 ; exports <- checkNoErrs $
642 mapM (mkExport prag_fn qtvs inferred_theta) mono_infos
643
644 ; loc <- getSrcSpanM
645 ; let poly_ids = map abe_poly exports
646 abs_bind = L loc $
647 AbsBinds { abs_tvs = qtvs
648 , abs_ev_vars = givens, abs_ev_binds = [ev_binds]
649 , abs_exports = exports, abs_binds = binds' }
650
651 ; traceTc "Binding:" (ppr (poly_ids `zip` map idType poly_ids))
652 ; return (unitBag abs_bind, poly_ids) }
653 -- poly_ids are guaranteed zonked by mkExport
654
655 --------------
656 mkExport :: TcPragEnv
657 -> [TyVar] -> TcThetaType -- Both already zonked
658 -> MonoBindInfo
659 -> TcM (ABExport Id)
660 -- Only called for generalisation plan InferGen, not by CheckGen or NoGen
661 --
662 -- mkExport generates exports with
663 -- zonked type variables,
664 -- zonked poly_ids
665 -- The former is just because no further unifications will change
666 -- the quantified type variables, so we can fix their final form
667 -- right now.
668 -- The latter is needed because the poly_ids are used to extend the
669 -- type environment; see the invariant on TcEnv.tcExtendIdEnv
670
671 -- Pre-condition: the qtvs and theta are already zonked
672
673 mkExport prag_fn qtvs theta
674 mono_info@(MBI { mbi_poly_name = poly_name
675 , mbi_sig = mb_sig
676 , mbi_mono_id = mono_id })
677 = do { mono_ty <- zonkTcType (idType mono_id)
678 ; poly_id <- case mb_sig of
679 Just sig | Just poly_id <- completeIdSigPolyId_maybe sig
680 -> return poly_id
681 _other -> checkNoErrs $
682 mkInferredPolyId qtvs theta
683 poly_name mb_sig mono_ty
684 -- The checkNoErrs ensures that if the type is ambiguous
685 -- we don't carry on to the impedence matching, and generate
686 -- a duplicate ambiguity error. There is a similar
687 -- checkNoErrs for complete type signatures too.
688
689 -- NB: poly_id has a zonked type
690 ; poly_id <- addInlinePrags poly_id prag_sigs
691 ; spec_prags <- tcSpecPrags poly_id prag_sigs
692 -- tcPrags requires a zonked poly_id
693
694 -- See Note [Impedence matching]
695 -- NB: we have already done checkValidType, including an ambiguity check,
696 -- on the type; either when we checked the sig or in mkInferredPolyId
697 ; let sel_poly_ty = mkInvSigmaTy qtvs theta mono_ty
698 -- this type is just going into tcSubType, so Inv vs. Spec doesn't
699 -- matter
700
701 poly_ty = idType poly_id
702 ; wrap <- if sel_poly_ty `eqType` poly_ty -- NB: eqType ignores visibility
703 then return idHsWrapper -- Fast path; also avoids complaint when we infer
704 -- an ambiguouse type and have AllowAmbiguousType
705 -- e..g infer x :: forall a. F a -> Int
706 else addErrCtxtM (mk_impedence_match_msg mono_info sel_poly_ty poly_ty) $
707 tcSubType_NC sig_ctxt sel_poly_ty (mkCheckExpType poly_ty)
708
709 ; warn_missing_sigs <- woptM Opt_WarnMissingLocalSignatures
710 ; when warn_missing_sigs $
711 localSigWarn Opt_WarnMissingLocalSignatures poly_id mb_sig
712
713 ; return (ABE { abe_wrap = wrap
714 -- abe_wrap :: idType poly_id ~ (forall qtvs. theta => mono_ty)
715 , abe_poly = poly_id
716 , abe_mono = mono_id
717 , abe_prags = SpecPrags spec_prags}) }
718 where
719 prag_sigs = lookupPragEnv prag_fn poly_name
720 sig_ctxt = InfSigCtxt poly_name
721
722 mkInferredPolyId :: [TyVar] -> TcThetaType
723 -> Name -> Maybe TcIdSigInfo -> TcType
724 -> TcM TcId
725 mkInferredPolyId qtvs inferred_theta poly_name mb_sig mono_ty
726 = do { fam_envs <- tcGetFamInstEnvs
727 ; let (_co, mono_ty') = normaliseType fam_envs Nominal mono_ty
728 -- Unification may not have normalised the type,
729 -- (see Note [Lazy flattening] in TcFlatten) so do it
730 -- here to make it as uncomplicated as possible.
731 -- Example: f :: [F Int] -> Bool
732 -- should be rewritten to f :: [Char] -> Bool, if possible
733 --
734 -- We can discard the coercion _co, because we'll reconstruct
735 -- it in the call to tcSubType below
736
737 ; (binders, theta') <- chooseInferredQuantifiers inferred_theta
738 (tyCoVarsOfType mono_ty') qtvs mb_sig
739
740 ; let inferred_poly_ty = mkForAllTys binders (mkPhiTy theta' mono_ty')
741
742 ; traceTc "mkInferredPolyId" (vcat [ppr poly_name, ppr qtvs, ppr theta'
743 , ppr inferred_poly_ty])
744 ; addErrCtxtM (mk_inf_msg poly_name inferred_poly_ty) $
745 checkValidType (InfSigCtxt poly_name) inferred_poly_ty
746 -- See Note [Validity of inferred types]
747
748 ; return (mkLocalIdOrCoVar poly_name inferred_poly_ty) }
749
750
751 chooseInferredQuantifiers :: TcThetaType -- inferred
752 -> TcTyVarSet -- tvs free in tau type
753 -> [TcTyVar] -- inferred quantified tvs
754 -> Maybe TcIdSigInfo
755 -> TcM ([TcTyBinder], TcThetaType)
756 chooseInferredQuantifiers inferred_theta tau_tvs qtvs Nothing
757 = do { let free_tvs = closeOverKinds (growThetaTyVars inferred_theta tau_tvs)
758 -- Include kind variables! Trac #7916
759 my_theta = pickQuantifiablePreds free_tvs inferred_theta
760 binders = [ mkNamedBinder Invisible tv
761 | tv <- qtvs
762 , tv `elemVarSet` free_tvs ]
763 ; return (binders, my_theta) }
764
765 chooseInferredQuantifiers inferred_theta tau_tvs qtvs
766 (Just (TISI { sig_bndr = bndr_info
767 , sig_ctxt = ctxt
768 , sig_theta = annotated_theta
769 , sig_skols = annotated_tvs }))
770 | PartialSig { sig_cts = extra } <- bndr_info
771 , Nothing <- extra
772 = do { annotated_theta <- zonkTcTypes annotated_theta
773 ; let free_tvs = closeOverKinds (tyCoVarsOfTypes annotated_theta
774 `unionVarSet` tau_tvs)
775 ; traceTc "ciq" (vcat [ ppr bndr_info, ppr annotated_theta, ppr free_tvs])
776 ; return (mk_binders free_tvs, annotated_theta) }
777
778 | PartialSig { sig_cts = extra } <- bndr_info
779 , Just loc <- extra
780 = do { annotated_theta <- zonkTcTypes annotated_theta
781 ; let free_tvs = closeOverKinds (tyCoVarsOfTypes annotated_theta
782 `unionVarSet` tau_tvs)
783 my_theta = pickQuantifiablePreds free_tvs inferred_theta
784
785 -- Report the inferred constraints for an extra-constraints wildcard/hole as
786 -- an error message, unless the PartialTypeSignatures flag is enabled. In this
787 -- case, the extra inferred constraints are accepted without complaining.
788 -- Returns the annotated constraints combined with the inferred constraints.
789 inferred_diff = [ pred
790 | pred <- my_theta
791 , all (not . (`eqType` pred)) annotated_theta ]
792 final_theta = annotated_theta ++ inferred_diff
793 ; partial_sigs <- xoptM LangExt.PartialTypeSignatures
794 ; warn_partial_sigs <- woptM Opt_WarnPartialTypeSignatures
795 ; msg <- mkLongErrAt loc (mk_msg inferred_diff partial_sigs) empty
796 ; traceTc "completeTheta" $
797 vcat [ ppr bndr_info
798 , ppr annotated_theta, ppr inferred_theta
799 , ppr inferred_diff ]
800 ; case partial_sigs of
801 True | warn_partial_sigs ->
802 reportWarning (Reason Opt_WarnPartialTypeSignatures) msg
803 | otherwise -> return ()
804 False -> reportError msg
805
806 ; return (mk_binders free_tvs, final_theta) }
807
808 | otherwise = pprPanic "chooseInferredQuantifiers" (ppr bndr_info)
809
810 where
811 pts_hint = text "To use the inferred type, enable PartialTypeSignatures"
812 mk_msg inferred_diff suppress_hint
813 = vcat [ hang ((text "Found constraint wildcard") <+> quotes (char '_'))
814 2 (text "standing for") <+> quotes (pprTheta inferred_diff)
815 , if suppress_hint then empty else pts_hint
816 , typeSigCtxt ctxt bndr_info ]
817
818 spec_tv_set = mkVarSet $ map snd annotated_tvs
819 mk_binders free_tvs
820 = [ mkNamedBinder vis tv
821 | tv <- qtvs
822 , tv `elemVarSet` free_tvs
823 , let vis | tv `elemVarSet` spec_tv_set = Specified
824 | otherwise = Invisible ]
825 -- Pulling from qtvs maintains original order
826
827 mk_impedence_match_msg :: MonoBindInfo
828 -> TcType -> TcType
829 -> TidyEnv -> TcM (TidyEnv, SDoc)
830 -- This is a rare but rather awkward error messages
831 mk_impedence_match_msg (MBI { mbi_poly_name = name, mbi_sig = mb_sig })
832 inf_ty sig_ty tidy_env
833 = do { (tidy_env1, inf_ty) <- zonkTidyTcType tidy_env inf_ty
834 ; (tidy_env2, sig_ty) <- zonkTidyTcType tidy_env1 sig_ty
835 ; let msg = vcat [ text "When checking that the inferred type"
836 , nest 2 $ ppr name <+> dcolon <+> ppr inf_ty
837 , text "is as general as its" <+> what <+> text "signature"
838 , nest 2 $ ppr name <+> dcolon <+> ppr sig_ty ]
839 ; return (tidy_env2, msg) }
840 where
841 what = case mb_sig of
842 Nothing -> text "inferred"
843 Just sig | isPartialSig sig -> text "(partial)"
844 | otherwise -> empty
845
846
847 mk_inf_msg :: Name -> TcType -> TidyEnv -> TcM (TidyEnv, SDoc)
848 mk_inf_msg poly_name poly_ty tidy_env
849 = do { (tidy_env1, poly_ty) <- zonkTidyTcType tidy_env poly_ty
850 ; let msg = vcat [ text "When checking the inferred type"
851 , nest 2 $ ppr poly_name <+> dcolon <+> ppr poly_ty ]
852 ; return (tidy_env1, msg) }
853
854
855 -- | Warn the user about polymorphic local binders that lack type signatures.
856 localSigWarn :: WarningFlag -> Id -> Maybe TcIdSigInfo -> TcM ()
857 localSigWarn flag id mb_sig
858 | Just _ <- mb_sig = return ()
859 | not (isSigmaTy (idType id)) = return ()
860 | otherwise = warnMissingSignatures flag msg id
861 where
862 msg = text "Polymorphic local binding with no type signature:"
863
864 warnMissingSignatures :: WarningFlag -> SDoc -> Id -> TcM ()
865 warnMissingSignatures flag msg id
866 = do { env0 <- tcInitTidyEnv
867 ; let (env1, tidy_ty) = tidyOpenType env0 (idType id)
868 ; addWarnTcM (Reason flag) (env1, mk_msg tidy_ty) }
869 where
870 mk_msg ty = sep [ msg, nest 2 $ pprPrefixName (idName id) <+> dcolon <+> ppr ty ]
871
872 {-
873 Note [Partial type signatures and generalisation]
874 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
875 When we have a partial type signature, like
876 f :: _ -> Int
877 then we *always* use the InferGen plan, and hence tcPolyInfer.
878 We do this even for a local binding with -XMonoLocalBinds.
879 Reasons:
880 * The TcSigInfo for 'f' has a unification variable for the '_',
881 whose TcLevel is one level deeper than the current level.
882 (See pushTcLevelM in tcTySig.) But NoGen doesn't increase
883 the TcLevel like InferGen, so we lose the level invariant.
884
885 * The signature might be f :: forall a. _ -> a
886 so it really is polymorphic. It's not clear what it would
887 mean to use NoGen on this, and indeed the ASSERT in tcLhs,
888 in the (Just sig) case, checks that if there is a signature
889 then we are using LetLclBndr, and hence a nested AbsBinds with
890 increased TcLevel
891
892 It might be possible to fix these difficulties somehow, but there
893 doesn't seem much point. Indeed, adding a partial type signature is a
894 way to get per-binding inferred generalisation.
895
896 Note [Validity of inferred types]
897 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
898 We need to check inferred type for validity, in case it uses language
899 extensions that are not turned on. The principle is that if the user
900 simply adds the inferred type to the program source, it'll compile fine.
901 See #8883.
902
903 Examples that might fail:
904 - the type might be ambiguous
905
906 - an inferred theta that requires type equalities e.g. (F a ~ G b)
907 or multi-parameter type classes
908 - an inferred type that includes unboxed tuples
909
910
911 Note [Impedence matching]
912 ~~~~~~~~~~~~~~~~~~~~~~~~~
913 Consider
914 f 0 x = x
915 f n x = g [] (not x)
916
917 g [] y = f 10 y
918 g _ y = f 9 y
919
920 After typechecking we'll get
921 f_mono_ty :: a -> Bool -> Bool
922 g_mono_ty :: [b] -> Bool -> Bool
923 with constraints
924 (Eq a, Num a)
925
926 Note that f is polymorphic in 'a' and g in 'b'; and these are not linked.
927 The types we really want for f and g are
928 f :: forall a. (Eq a, Num a) => a -> Bool -> Bool
929 g :: forall b. [b] -> Bool -> Bool
930
931 We can get these by "impedance matching":
932 tuple :: forall a b. (Eq a, Num a) => (a -> Bool -> Bool, [b] -> Bool -> Bool)
933 tuple a b d1 d1 = let ...bind f_mono, g_mono in (f_mono, g_mono)
934
935 f a d1 d2 = case tuple a Any d1 d2 of (f, g) -> f
936 g b = case tuple Integer b dEqInteger dNumInteger of (f,g) -> g
937
938 Suppose the shared quantified tyvars are qtvs and constraints theta.
939 Then we want to check that
940 forall qtvs. theta => f_mono_ty is more polymorphic than f's polytype
941 and the proof is the impedance matcher.
942
943 Notice that the impedance matcher may do defaulting. See Trac #7173.
944
945 It also cleverly does an ambiguity check; for example, rejecting
946 f :: F a -> F a
947 where F is a non-injective type function.
948 -}
949
950 --------------
951 -- If typechecking the binds fails, then return with each
952 -- signature-less binder given type (forall a.a), to minimise
953 -- subsequent error messages
954 recoveryCode :: [Name] -> TcSigFun -> TcM (LHsBinds TcId, [Id])
955 recoveryCode binder_names sig_fn
956 = do { traceTc "tcBindsWithSigs: error recovery" (ppr binder_names)
957 ; let poly_ids = map mk_dummy binder_names
958 ; return (emptyBag, poly_ids) }
959 where
960 mk_dummy name
961 | Just sig <- sig_fn name
962 , Just poly_id <- completeSigPolyId_maybe sig
963 = poly_id
964 | otherwise
965 = mkLocalId name forall_a_a
966
967 forall_a_a :: TcType
968 forall_a_a = mkSpecForAllTys [runtimeRep1TyVar, openAlphaTyVar] openAlphaTy
969
970 {- *********************************************************************
971 * *
972 Pragmas, including SPECIALISE
973 * *
974 ************************************************************************
975
976 Note [Handling SPECIALISE pragmas]
977 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
978 The basic idea is this:
979
980 foo :: Num a => a -> b -> a
981 {-# SPECIALISE foo :: Int -> b -> Int #-}
982
983 We check that
984 (forall a b. Num a => a -> b -> a)
985 is more polymorphic than
986 forall b. Int -> b -> Int
987 (for which we could use tcSubType, but see below), generating a HsWrapper
988 to connect the two, something like
989 wrap = /\b. <hole> Int b dNumInt
990 This wrapper is put in the TcSpecPrag, in the ABExport record of
991 the AbsBinds.
992
993
994 f :: (Eq a, Ix b) => a -> b -> Bool
995 {-# SPECIALISE f :: (Ix p, Ix q) => Int -> (p,q) -> Bool #-}
996 f = <poly_rhs>
997
998 From this the typechecker generates
999
1000 AbsBinds [ab] [d1,d2] [([ab], f, f_mono, prags)] binds
1001
1002 SpecPrag (wrap_fn :: forall a b. (Eq a, Ix b) => XXX
1003 -> forall p q. (Ix p, Ix q) => XXX[ Int/a, (p,q)/b ])
1004
1005 From these we generate:
1006
1007 Rule: forall p, q, (dp:Ix p), (dq:Ix q).
1008 f Int (p,q) dInt ($dfInPair dp dq) = f_spec p q dp dq
1009
1010 Spec bind: f_spec = wrap_fn <poly_rhs>
1011
1012 Note that
1013
1014 * The LHS of the rule may mention dictionary *expressions* (eg
1015 $dfIxPair dp dq), and that is essential because the dp, dq are
1016 needed on the RHS.
1017
1018 * The RHS of f_spec, <poly_rhs> has a *copy* of 'binds', so that it
1019 can fully specialise it.
1020
1021
1022
1023 From the TcSpecPrag, in DsBinds we generate a binding for f_spec and a RULE:
1024
1025 f_spec :: Int -> b -> Int
1026 f_spec = wrap<f rhs>
1027
1028 RULE: forall b (d:Num b). f b d = f_spec b
1029
1030 The RULE is generated by taking apart the HsWrapper, which is a little
1031 delicate, but works.
1032
1033 Some wrinkles
1034
1035 1. We don't use full-on tcSubType, because that does co and contra
1036 variance and that in turn will generate too complex a LHS for the
1037 RULE. So we use a single invocation of skolemise /
1038 topInstantiate in tcSpecWrapper. (Actually I think that even
1039 the "deeply" stuff may be too much, because it introduces lambdas,
1040 though I think it can be made to work without too much trouble.)
1041
1042 2. We need to take care with type families (Trac #5821). Consider
1043 type instance F Int = Bool
1044 f :: Num a => a -> F a
1045 {-# SPECIALISE foo :: Int -> Bool #-}
1046
1047 We *could* try to generate an f_spec with precisely the declared type:
1048 f_spec :: Int -> Bool
1049 f_spec = <f rhs> Int dNumInt |> co
1050
1051 RULE: forall d. f Int d = f_spec |> sym co
1052
1053 but the 'co' and 'sym co' are (a) playing no useful role, and (b) are
1054 hard to generate. At all costs we must avoid this:
1055 RULE: forall d. f Int d |> co = f_spec
1056 because the LHS will never match (indeed it's rejected in
1057 decomposeRuleLhs).
1058
1059 So we simply do this:
1060 - Generate a constraint to check that the specialised type (after
1061 skolemiseation) is equal to the instantiated function type.
1062 - But *discard* the evidence (coercion) for that constraint,
1063 so that we ultimately generate the simpler code
1064 f_spec :: Int -> F Int
1065 f_spec = <f rhs> Int dNumInt
1066
1067 RULE: forall d. f Int d = f_spec
1068 You can see this discarding happening in
1069
1070 3. Note that the HsWrapper can transform *any* function with the right
1071 type prefix
1072 forall ab. (Eq a, Ix b) => XXX
1073 regardless of XXX. It's sort of polymorphic in XXX. This is
1074 useful: we use the same wrapper to transform each of the class ops, as
1075 well as the dict. That's what goes on in TcInstDcls.mk_meth_spec_prags
1076 -}
1077
1078 mkPragEnv :: [LSig Name] -> LHsBinds Name -> TcPragEnv
1079 mkPragEnv sigs binds
1080 = foldl extendPragEnv emptyNameEnv prs
1081 where
1082 prs = mapMaybe get_sig sigs
1083
1084 get_sig :: LSig Name -> Maybe (Name, LSig Name)
1085 get_sig (L l (SpecSig lnm@(L _ nm) ty inl)) = Just (nm, L l $ SpecSig lnm ty (add_arity nm inl))
1086 get_sig (L l (InlineSig lnm@(L _ nm) inl)) = Just (nm, L l $ InlineSig lnm (add_arity nm inl))
1087 get_sig _ = Nothing
1088
1089 add_arity n inl_prag -- Adjust inl_sat field to match visible arity of function
1090 | Inline <- inl_inline inl_prag
1091 -- add arity only for real INLINE pragmas, not INLINABLE
1092 = case lookupNameEnv ar_env n of
1093 Just ar -> inl_prag { inl_sat = Just ar }
1094 Nothing -> WARN( True, text "mkPragEnv no arity" <+> ppr n )
1095 -- There really should be a binding for every INLINE pragma
1096 inl_prag
1097 | otherwise
1098 = inl_prag
1099
1100 -- ar_env maps a local to the arity of its definition
1101 ar_env :: NameEnv Arity
1102 ar_env = foldrBag lhsBindArity emptyNameEnv binds
1103
1104 extendPragEnv :: TcPragEnv -> (Name, LSig Name) -> TcPragEnv
1105 extendPragEnv prag_fn (n, sig) = extendNameEnv_Acc (:) singleton prag_fn n sig
1106
1107 lhsBindArity :: LHsBind Name -> NameEnv Arity -> NameEnv Arity
1108 lhsBindArity (L _ (FunBind { fun_id = id, fun_matches = ms })) env
1109 = extendNameEnv env (unLoc id) (matchGroupArity ms)
1110 lhsBindArity _ env = env -- PatBind/VarBind
1111
1112 ------------------
1113 tcSpecPrags :: Id -> [LSig Name]
1114 -> TcM [LTcSpecPrag]
1115 -- Add INLINE and SPECIALSE pragmas
1116 -- INLINE prags are added to the (polymorphic) Id directly
1117 -- SPECIALISE prags are passed to the desugarer via TcSpecPrags
1118 -- Pre-condition: the poly_id is zonked
1119 -- Reason: required by tcSubExp
1120 tcSpecPrags poly_id prag_sigs
1121 = do { traceTc "tcSpecPrags" (ppr poly_id <+> ppr spec_sigs)
1122 ; unless (null bad_sigs) warn_discarded_sigs
1123 ; pss <- mapAndRecoverM (wrapLocM (tcSpecPrag poly_id)) spec_sigs
1124 ; return $ concatMap (\(L l ps) -> map (L l) ps) pss }
1125 where
1126 spec_sigs = filter isSpecLSig prag_sigs
1127 bad_sigs = filter is_bad_sig prag_sigs
1128 is_bad_sig s = not (isSpecLSig s || isInlineLSig s)
1129
1130 warn_discarded_sigs
1131 = addWarnTc NoReason
1132 (hang (text "Discarding unexpected pragmas for" <+> ppr poly_id)
1133 2 (vcat (map (ppr . getLoc) bad_sigs)))
1134
1135 --------------
1136 tcSpecPrag :: TcId -> Sig Name -> TcM [TcSpecPrag]
1137 tcSpecPrag poly_id prag@(SpecSig fun_name hs_tys inl)
1138 -- See Note [Handling SPECIALISE pragmas]
1139 --
1140 -- The Name fun_name in the SpecSig may not be the same as that of the poly_id
1141 -- Example: SPECIALISE for a class method: the Name in the SpecSig is
1142 -- for the selector Id, but the poly_id is something like $cop
1143 -- However we want to use fun_name in the error message, since that is
1144 -- what the user wrote (Trac #8537)
1145 = addErrCtxt (spec_ctxt prag) $
1146 do { warnIf NoReason (not (isOverloadedTy poly_ty || isInlinePragma inl))
1147 (text "SPECIALISE pragma for non-overloaded function"
1148 <+> quotes (ppr fun_name))
1149 -- Note [SPECIALISE pragmas]
1150 ; spec_prags <- mapM tc_one hs_tys
1151 ; traceTc "tcSpecPrag" (ppr poly_id $$ nest 2 (vcat (map ppr spec_prags)))
1152 ; return spec_prags }
1153 where
1154 name = idName poly_id
1155 poly_ty = idType poly_id
1156 spec_ctxt prag = hang (text "In the SPECIALISE pragma") 2 (ppr prag)
1157
1158 tc_one hs_ty
1159 = do { spec_ty <- tcHsSigType (FunSigCtxt name False) hs_ty
1160 ; wrap <- tcSpecWrapper (FunSigCtxt name True) poly_ty spec_ty
1161 ; return (SpecPrag poly_id wrap inl) }
1162
1163 tcSpecPrag _ prag = pprPanic "tcSpecPrag" (ppr prag)
1164
1165 --------------
1166 tcSpecWrapper :: UserTypeCtxt -> TcType -> TcType -> TcM HsWrapper
1167 -- A simpler variant of tcSubType, used for SPECIALISE pragmas
1168 -- See Note [Handling SPECIALISE pragmas], wrinkle 1
1169 tcSpecWrapper ctxt poly_ty spec_ty
1170 = do { (sk_wrap, inst_wrap)
1171 <- tcSkolemise ctxt spec_ty $ \ _ spec_tau ->
1172 do { (inst_wrap, tau) <- topInstantiate orig poly_ty
1173 ; _ <- unifyType noThing spec_tau tau
1174 -- Deliberately ignore the evidence
1175 -- See Note [Handling SPECIALISE pragmas],
1176 -- wrinkle (2)
1177 ; return inst_wrap }
1178 ; return (sk_wrap <.> inst_wrap) }
1179 where
1180 orig = SpecPragOrigin ctxt
1181
1182 --------------
1183 tcImpPrags :: [LSig Name] -> TcM [LTcSpecPrag]
1184 -- SPECIALISE pragmas for imported things
1185 tcImpPrags prags
1186 = do { this_mod <- getModule
1187 ; dflags <- getDynFlags
1188 ; if (not_specialising dflags) then
1189 return []
1190 else do
1191 { pss <- mapAndRecoverM (wrapLocM tcImpSpec)
1192 [L loc (name,prag)
1193 | (L loc prag@(SpecSig (L _ name) _ _)) <- prags
1194 , not (nameIsLocalOrFrom this_mod name) ]
1195 ; return $ concatMap (\(L l ps) -> map (L l) ps) pss } }
1196 where
1197 -- Ignore SPECIALISE pragmas for imported things
1198 -- when we aren't specialising, or when we aren't generating
1199 -- code. The latter happens when Haddocking the base library;
1200 -- we don't wnat complaints about lack of INLINABLE pragmas
1201 not_specialising dflags
1202 | not (gopt Opt_Specialise dflags) = True
1203 | otherwise = case hscTarget dflags of
1204 HscNothing -> True
1205 HscInterpreted -> True
1206 _other -> False
1207
1208 tcImpSpec :: (Name, Sig Name) -> TcM [TcSpecPrag]
1209 tcImpSpec (name, prag)
1210 = do { id <- tcLookupId name
1211 ; unless (isAnyInlinePragma (idInlinePragma id))
1212 (addWarnTc NoReason (impSpecErr name))
1213 ; tcSpecPrag id prag }
1214
1215 impSpecErr :: Name -> SDoc
1216 impSpecErr name
1217 = hang (text "You cannot SPECIALISE" <+> quotes (ppr name))
1218 2 (vcat [ text "because its definition has no INLINE/INLINABLE pragma"
1219 , parens $ sep
1220 [ text "or its defining module" <+> quotes (ppr mod)
1221 , text "was compiled without -O"]])
1222 where
1223 mod = nameModule name
1224
1225
1226 {- *********************************************************************
1227 * *
1228 Vectorisation
1229 * *
1230 ********************************************************************* -}
1231
1232 tcVectDecls :: [LVectDecl Name] -> TcM ([LVectDecl TcId])
1233 tcVectDecls decls
1234 = do { decls' <- mapM (wrapLocM tcVect) decls
1235 ; let ids = [lvectDeclName decl | decl <- decls', not $ lvectInstDecl decl]
1236 dups = findDupsEq (==) ids
1237 ; mapM_ reportVectDups dups
1238 ; traceTcConstraints "End of tcVectDecls"
1239 ; return decls'
1240 }
1241 where
1242 reportVectDups (first:_second:_more)
1243 = addErrAt (getSrcSpan first) $
1244 text "Duplicate vectorisation declarations for" <+> ppr first
1245 reportVectDups _ = return ()
1246
1247 --------------
1248 tcVect :: VectDecl Name -> TcM (VectDecl TcId)
1249 -- FIXME: We can't typecheck the expression of a vectorisation declaration against the vectorised
1250 -- type of the original definition as this requires internals of the vectoriser not available
1251 -- during type checking. Instead, constrain the rhs of a vectorisation declaration to be a single
1252 -- identifier (this is checked in 'rnHsVectDecl'). Fix this by enabling the use of 'vectType'
1253 -- from the vectoriser here.
1254 tcVect (HsVect s name rhs)
1255 = addErrCtxt (vectCtxt name) $
1256 do { var <- wrapLocM tcLookupId name
1257 ; let L rhs_loc (HsVar (L lv rhs_var_name)) = rhs
1258 ; rhs_id <- tcLookupId rhs_var_name
1259 ; return $ HsVect s var (L rhs_loc (HsVar (L lv rhs_id)))
1260 }
1261
1262 {- OLD CODE:
1263 -- turn the vectorisation declaration into a single non-recursive binding
1264 ; let bind = L loc $ mkTopFunBind name [mkSimpleMatch [] rhs]
1265 sigFun = const Nothing
1266 pragFun = emptyPragEnv
1267
1268 -- perform type inference (including generalisation)
1269 ; (binds, [id'], _) <- tcPolyInfer False True sigFun pragFun NonRecursive [bind]
1270
1271 ; traceTc "tcVect inferred type" $ ppr (varType id')
1272 ; traceTc "tcVect bindings" $ ppr binds
1273
1274 -- add all bindings, including the type variable and dictionary bindings produced by type
1275 -- generalisation to the right-hand side of the vectorisation declaration
1276 ; let [AbsBinds tvs evs _ evBinds actualBinds] = (map unLoc . bagToList) binds
1277 ; let [bind'] = bagToList actualBinds
1278 MatchGroup
1279 [L _ (Match _ _ (GRHSs [L _ (GRHS _ rhs')] _))]
1280 _ = (fun_matches . unLoc) bind'
1281 rhsWrapped = mkHsLams tvs evs (mkHsDictLet evBinds rhs')
1282
1283 -- We return the type-checked 'Id', to propagate the inferred signature
1284 -- to the vectoriser - see "Note [Typechecked vectorisation pragmas]" in HsDecls
1285 ; return $ HsVect (L loc id') (Just rhsWrapped)
1286 }
1287 -}
1288 tcVect (HsNoVect s name)
1289 = addErrCtxt (vectCtxt name) $
1290 do { var <- wrapLocM tcLookupId name
1291 ; return $ HsNoVect s var
1292 }
1293 tcVect (HsVectTypeIn _ isScalar lname rhs_name)
1294 = addErrCtxt (vectCtxt lname) $
1295 do { tycon <- tcLookupLocatedTyCon lname
1296 ; checkTc ( not isScalar -- either we have a non-SCALAR declaration
1297 || isJust rhs_name -- or we explicitly provide a vectorised type
1298 || tyConArity tycon == 0 -- otherwise the type constructor must be nullary
1299 )
1300 scalarTyConMustBeNullary
1301
1302 ; rhs_tycon <- fmapMaybeM (tcLookupTyCon . unLoc) rhs_name
1303 ; return $ HsVectTypeOut isScalar tycon rhs_tycon
1304 }
1305 tcVect (HsVectTypeOut _ _ _)
1306 = panic "TcBinds.tcVect: Unexpected 'HsVectTypeOut'"
1307 tcVect (HsVectClassIn _ lname)
1308 = addErrCtxt (vectCtxt lname) $
1309 do { cls <- tcLookupLocatedClass lname
1310 ; return $ HsVectClassOut cls
1311 }
1312 tcVect (HsVectClassOut _)
1313 = panic "TcBinds.tcVect: Unexpected 'HsVectClassOut'"
1314 tcVect (HsVectInstIn linstTy)
1315 = addErrCtxt (vectCtxt linstTy) $
1316 do { (cls, tys) <- tcHsVectInst linstTy
1317 ; inst <- tcLookupInstance cls tys
1318 ; return $ HsVectInstOut inst
1319 }
1320 tcVect (HsVectInstOut _)
1321 = panic "TcBinds.tcVect: Unexpected 'HsVectInstOut'"
1322
1323 vectCtxt :: Outputable thing => thing -> SDoc
1324 vectCtxt thing = text "When checking the vectorisation declaration for" <+> ppr thing
1325
1326 scalarTyConMustBeNullary :: MsgDoc
1327 scalarTyConMustBeNullary = text "VECTORISE SCALAR type constructor must be nullary"
1328
1329 {-
1330 Note [SPECIALISE pragmas]
1331 ~~~~~~~~~~~~~~~~~~~~~~~~~
1332 There is no point in a SPECIALISE pragma for a non-overloaded function:
1333 reverse :: [a] -> [a]
1334 {-# SPECIALISE reverse :: [Int] -> [Int] #-}
1335
1336 But SPECIALISE INLINE *can* make sense for GADTS:
1337 data Arr e where
1338 ArrInt :: !Int -> ByteArray# -> Arr Int
1339 ArrPair :: !Int -> Arr e1 -> Arr e2 -> Arr (e1, e2)
1340
1341 (!:) :: Arr e -> Int -> e
1342 {-# SPECIALISE INLINE (!:) :: Arr Int -> Int -> Int #-}
1343 {-# SPECIALISE INLINE (!:) :: Arr (a, b) -> Int -> (a, b) #-}
1344 (ArrInt _ ba) !: (I# i) = I# (indexIntArray# ba i)
1345 (ArrPair _ a1 a2) !: i = (a1 !: i, a2 !: i)
1346
1347 When (!:) is specialised it becomes non-recursive, and can usefully
1348 be inlined. Scary! So we only warn for SPECIALISE *without* INLINE
1349 for a non-overloaded function.
1350
1351 ************************************************************************
1352 * *
1353 tcMonoBinds
1354 * *
1355 ************************************************************************
1356
1357 @tcMonoBinds@ deals with a perhaps-recursive group of HsBinds.
1358 The signatures have been dealt with already.
1359
1360 Note [Pattern bindings]
1361 ~~~~~~~~~~~~~~~~~~~~~~~
1362 The rule for typing pattern bindings is this:
1363
1364 ..sigs..
1365 p = e
1366
1367 where 'p' binds v1..vn, and 'e' may mention v1..vn,
1368 typechecks exactly like
1369
1370 ..sigs..
1371 x = e -- Inferred type
1372 v1 = case x of p -> v1
1373 ..
1374 vn = case x of p -> vn
1375
1376 Note that
1377 (f :: forall a. a -> a) = id
1378 should not typecheck because
1379 case id of { (f :: forall a. a->a) -> f }
1380 will not typecheck.
1381
1382 Note [Instantiate when inferring a type]
1383 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1384 Consider
1385 f = (*)
1386 As there is no incentive to instantiate the RHS, tcMonoBinds will
1387 produce a type of forall a. Num a => a -> a -> a for `f`. This will then go
1388 through simplifyInfer and such, remaining unchanged.
1389
1390 There are two problems with this:
1391 1) If the definition were `g _ = (*)`, we get a very unusual type of
1392 `forall {a}. a -> forall b. Num b => b -> b -> b` for `g`. This is
1393 surely confusing for users.
1394
1395 2) The monomorphism restriction can't work. The MR is dealt with in
1396 simplifyInfer, and simplifyInfer has no way of instantiating. This
1397 could perhaps be worked around, but it may be hard to know even
1398 when instantiation should happen.
1399
1400 There is an easy solution to both problems: instantiate (deeply) when
1401 inferring a type. So that's what we do. Note that this decision is
1402 user-facing.
1403
1404 We do this deep instantiation in tcMonoBinds, in the FunBind case
1405 only, and only when we do not have a type signature. Conveniently,
1406 the fun_co_fn field of FunBind gives a place to record the coercion.
1407
1408 We do not need to do this
1409 * for PatBinds, because we don't have a function type
1410 * for FunBinds where we have a signature, bucause we aren't doing inference
1411 -}
1412
1413 tcMonoBinds :: RecFlag -- Whether the binding is recursive for typechecking purposes
1414 -- i.e. the binders are mentioned in their RHSs, and
1415 -- we are not rescued by a type signature
1416 -> TcSigFun -> LetBndrSpec
1417 -> [LHsBind Name]
1418 -> TcM (LHsBinds TcId, [MonoBindInfo])
1419 tcMonoBinds is_rec sig_fn no_gen
1420 [ L b_loc (FunBind { fun_id = L nm_loc name,
1421 fun_matches = matches, bind_fvs = fvs })]
1422 -- Single function binding,
1423 | NonRecursive <- is_rec -- ...binder isn't mentioned in RHS
1424 , Nothing <- sig_fn name -- ...with no type signature
1425 = -- In this very special case we infer the type of the
1426 -- right hand side first (it may have a higher-rank type)
1427 -- and *then* make the monomorphic Id for the LHS
1428 -- e.g. f = \(x::forall a. a->a) -> <body>
1429 -- We want to infer a higher-rank type for f
1430 setSrcSpan b_loc $
1431 do { rhs_ty <- newOpenInferExpType
1432 ; (co_fn, matches')
1433 <- tcExtendIdBndrs [TcIdBndr_ExpType name rhs_ty NotTopLevel] $
1434 -- We extend the error context even for a non-recursive
1435 -- function so that in type error messages we show the
1436 -- type of the thing whose rhs we are type checking
1437 tcMatchesFun name matches rhs_ty
1438 ; rhs_ty <- readExpType rhs_ty
1439
1440 -- Deeply instantiate the inferred type
1441 -- See Note [Instantiate when inferring a type]
1442 ; let orig = matchesCtOrigin matches
1443 ; rhs_ty <- zonkTcType rhs_ty -- NB: zonk to uncover any foralls
1444 ; (inst_wrap, rhs_ty) <- addErrCtxtM (instErrCtxt name rhs_ty) $
1445 deeplyInstantiate orig rhs_ty
1446
1447 ; mono_id <- newNoSigLetBndr no_gen name rhs_ty
1448 ; return (unitBag $ L b_loc $
1449 FunBind { fun_id = L nm_loc mono_id,
1450 fun_matches = matches', bind_fvs = fvs,
1451 fun_co_fn = inst_wrap <.> co_fn, fun_tick = [] },
1452 [MBI { mbi_poly_name = name
1453 , mbi_sig = Nothing
1454 , mbi_mono_id = mono_id }]) }
1455
1456 tcMonoBinds _ sig_fn no_gen binds
1457 = do { tc_binds <- mapM (wrapLocM (tcLhs sig_fn no_gen)) binds
1458
1459 -- Bring the monomorphic Ids, into scope for the RHSs
1460 ; let mono_infos = getMonoBindInfo tc_binds
1461 rhs_id_env = [(name, mono_id) | MBI { mbi_poly_name = name
1462 , mbi_sig = mb_sig
1463 , mbi_mono_id = mono_id }
1464 <- mono_infos
1465 , case mb_sig of
1466 Just sig -> isPartialSig sig
1467 Nothing -> True ]
1468 -- A monomorphic binding for each term variable that lacks
1469 -- a type sig. (Ones with a sig are already in scope.)
1470
1471 ; traceTc "tcMonoBinds" $ vcat [ ppr n <+> ppr id <+> ppr (idType id)
1472 | (n,id) <- rhs_id_env]
1473 ; binds' <- tcExtendLetEnvIds NotTopLevel rhs_id_env $
1474 mapM (wrapLocM tcRhs) tc_binds
1475 ; return (listToBag binds', mono_infos) }
1476
1477 ------------------------
1478 -- tcLhs typechecks the LHS of the bindings, to construct the environment in which
1479 -- we typecheck the RHSs. Basically what we are doing is this: for each binder:
1480 -- if there's a signature for it, use the instantiated signature type
1481 -- otherwise invent a type variable
1482 -- You see that quite directly in the FunBind case.
1483 --
1484 -- But there's a complication for pattern bindings:
1485 -- data T = MkT (forall a. a->a)
1486 -- MkT f = e
1487 -- Here we can guess a type variable for the entire LHS (which will be refined to T)
1488 -- but we want to get (f::forall a. a->a) as the RHS environment.
1489 -- The simplest way to do this is to typecheck the pattern, and then look up the
1490 -- bound mono-ids. Then we want to retain the typechecked pattern to avoid re-doing
1491 -- it; hence the TcMonoBind data type in which the LHS is done but the RHS isn't
1492
1493 data TcMonoBind -- Half completed; LHS done, RHS not done
1494 = TcFunBind MonoBindInfo SrcSpan (MatchGroup Name (LHsExpr Name))
1495 | TcPatBind [MonoBindInfo] (LPat TcId) (GRHSs Name (LHsExpr Name)) TcSigmaType
1496
1497 data MonoBindInfo = MBI { mbi_poly_name :: Name
1498 , mbi_sig :: Maybe TcIdSigInfo
1499 , mbi_mono_id :: TcId }
1500
1501 tcLhs :: TcSigFun -> LetBndrSpec -> HsBind Name -> TcM TcMonoBind
1502 tcLhs sig_fn no_gen (FunBind { fun_id = L nm_loc name, fun_matches = matches })
1503 | Just (TcIdSig sig) <- sig_fn name
1504 , TISI { sig_tau = tau } <- sig
1505 = ASSERT2( case no_gen of { LetLclBndr -> True; LetGblBndr {} -> False }
1506 , ppr name )
1507 -- { f :: ty; f x = e } is always done via CheckGen (full signature)
1508 -- or InferGen (partial signature)
1509 -- see Note [Partial type signatures and generalisation]
1510 -- Both InferGen and CheckGen gives rise to LetLclBndr
1511 do { mono_name <- newLocalName name
1512 ; let mono_id = mkLocalIdOrCoVar mono_name tau
1513 ; return (TcFunBind (MBI { mbi_poly_name = name
1514 , mbi_sig = Just sig
1515 , mbi_mono_id = mono_id })
1516 nm_loc matches) }
1517
1518 | otherwise
1519 = do { mono_ty <- newOpenFlexiTyVarTy
1520 ; mono_id <- newNoSigLetBndr no_gen name mono_ty
1521 ; return (TcFunBind (MBI { mbi_poly_name = name
1522 , mbi_sig = Nothing
1523 , mbi_mono_id = mono_id })
1524 nm_loc matches) }
1525
1526 tcLhs sig_fn no_gen (PatBind { pat_lhs = pat, pat_rhs = grhss })
1527 = do { let tc_pat exp_ty = tcLetPat sig_fn no_gen pat exp_ty $
1528 mapM lookup_info (collectPatBinders pat)
1529
1530 -- After typechecking the pattern, look up the binder
1531 -- names, which the pattern has brought into scope.
1532 lookup_info :: Name -> TcM MonoBindInfo
1533 lookup_info name
1534 = do { mono_id <- tcLookupId name
1535 ; let mb_sig = case sig_fn name of
1536 Just (TcIdSig sig) -> Just sig
1537 _ -> Nothing
1538 ; return (MBI { mbi_poly_name = name
1539 , mbi_sig = mb_sig
1540 , mbi_mono_id = mono_id }) }
1541
1542 ; ((pat', infos), pat_ty) <- addErrCtxt (patMonoBindsCtxt pat grhss) $
1543 tcInfer tc_pat
1544
1545 ; return (TcPatBind infos pat' grhss pat_ty) }
1546
1547 tcLhs _ _ other_bind = pprPanic "tcLhs" (ppr other_bind)
1548 -- AbsBind, VarBind impossible
1549
1550 -------------------
1551 tcRhs :: TcMonoBind -> TcM (HsBind TcId)
1552 tcRhs (TcFunBind info@(MBI { mbi_sig = mb_sig, mbi_mono_id = mono_id })
1553 loc matches)
1554 = tcExtendIdBinderStackForRhs [info] $
1555 tcExtendTyVarEnvForRhs mb_sig $
1556 do { traceTc "tcRhs: fun bind" (ppr mono_id $$ ppr (idType mono_id))
1557 ; (co_fn, matches') <- tcMatchesFun (idName mono_id)
1558 matches (mkCheckExpType $ idType mono_id)
1559 ; return ( FunBind { fun_id = L loc mono_id
1560 , fun_matches = matches'
1561 , fun_co_fn = co_fn
1562 , bind_fvs = placeHolderNamesTc
1563 , fun_tick = [] } ) }
1564
1565 -- TODO: emit Hole Constraints for wildcards
1566 tcRhs (TcPatBind infos pat' grhss pat_ty)
1567 = -- When we are doing pattern bindings we *don't* bring any scoped
1568 -- type variables into scope unlike function bindings
1569 -- Wny not? They are not completely rigid.
1570 -- That's why we have the special case for a single FunBind in tcMonoBinds
1571 tcExtendIdBinderStackForRhs infos $
1572 do { traceTc "tcRhs: pat bind" (ppr pat' $$ ppr pat_ty)
1573 ; grhss' <- addErrCtxt (patMonoBindsCtxt pat' grhss) $
1574 tcGRHSsPat grhss pat_ty
1575 ; return ( PatBind { pat_lhs = pat', pat_rhs = grhss'
1576 , pat_rhs_ty = pat_ty
1577 , bind_fvs = placeHolderNamesTc
1578 , pat_ticks = ([],[]) } )}
1579
1580 tcExtendTyVarEnvForRhs :: Maybe TcIdSigInfo -> TcM a -> TcM a
1581 tcExtendTyVarEnvForRhs Nothing thing_inside
1582 = thing_inside
1583 tcExtendTyVarEnvForRhs (Just sig) thing_inside
1584 = tcExtendTyVarEnvFromSig sig thing_inside
1585
1586 tcExtendTyVarEnvFromSig :: TcIdSigInfo -> TcM a -> TcM a
1587 tcExtendTyVarEnvFromSig sig thing_inside
1588 | TISI { sig_bndr = s_bndr, sig_skols = skol_prs, sig_ctxt = ctxt } <- sig
1589 = tcExtendTyVarEnv2 skol_prs $
1590 case s_bndr of
1591 CompleteSig {} -> thing_inside
1592 PartialSig { sig_wcs = wc_prs } -- Extend the env ad emit the holes
1593 -> tcExtendTyVarEnv2 wc_prs $
1594 do { addErrCtxt (typeSigCtxt ctxt s_bndr) $
1595 emitWildCardHoleConstraints wc_prs
1596 ; thing_inside }
1597
1598 tcExtendIdBinderStackForRhs :: [MonoBindInfo] -> TcM a -> TcM a
1599 -- Extend the TcIdBinderStack for the RHS of the binding, with
1600 -- the monomorphic Id. That way, if we have, say
1601 -- f = \x -> blah
1602 -- and something goes wrong in 'blah', we get a "relevant binding"
1603 -- looking like f :: alpha -> beta
1604 -- This applies if 'f' has a type signature too:
1605 -- f :: forall a. [a] -> [a]
1606 -- f x = True
1607 -- We can't unify True with [a], and a relevant binding is f :: [a] -> [a]
1608 -- If we had the *polymorphic* version of f in the TcIdBinderStack, it
1609 -- would not be reported as relevant, because its type is closed
1610 tcExtendIdBinderStackForRhs infos thing_inside
1611 = tcExtendIdBndrs [ TcIdBndr mono_id NotTopLevel
1612 | MBI { mbi_mono_id = mono_id } <- infos ]
1613 thing_inside
1614 -- NotTopLevel: it's a monomorphic binding
1615
1616 ---------------------
1617 getMonoBindInfo :: [Located TcMonoBind] -> [MonoBindInfo]
1618 getMonoBindInfo tc_binds
1619 = foldr (get_info . unLoc) [] tc_binds
1620 where
1621 get_info (TcFunBind info _ _) rest = info : rest
1622 get_info (TcPatBind infos _ _ _) rest = infos ++ rest
1623
1624 {-
1625 ************************************************************************
1626 * *
1627 Signatures
1628 * *
1629 ************************************************************************
1630
1631 Type signatures are tricky. See Note [Signature skolems] in TcType
1632
1633 @tcSigs@ checks the signatures for validity, and returns a list of
1634 {\em freshly-instantiated} signatures. That is, the types are already
1635 split up, and have fresh type variables installed. All non-type-signature
1636 "RenamedSigs" are ignored.
1637
1638 The @TcSigInfo@ contains @TcTypes@ because they are unified with
1639 the variable's type, and after that checked to see whether they've
1640 been instantiated.
1641
1642 Note [Scoped tyvars]
1643 ~~~~~~~~~~~~~~~~~~~~
1644 The -XScopedTypeVariables flag brings lexically-scoped type variables
1645 into scope for any explicitly forall-quantified type variables:
1646 f :: forall a. a -> a
1647 f x = e
1648 Then 'a' is in scope inside 'e'.
1649
1650 However, we do *not* support this
1651 - For pattern bindings e.g
1652 f :: forall a. a->a
1653 (f,g) = e
1654
1655 Note [Signature skolems]
1656 ~~~~~~~~~~~~~~~~~~~~~~~~
1657 When instantiating a type signature, we do so with either skolems or
1658 SigTv meta-type variables depending on the use_skols boolean. This
1659 variable is set True when we are typechecking a single function
1660 binding; and False for pattern bindings and a group of several
1661 function bindings.
1662
1663 Reason: in the latter cases, the "skolems" can be unified together,
1664 so they aren't properly rigid in the type-refinement sense.
1665 NB: unless we are doing H98, each function with a sig will be done
1666 separately, even if it's mutually recursive, so use_skols will be True
1667
1668
1669 Note [Only scoped tyvars are in the TyVarEnv]
1670 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1671 We are careful to keep only the *lexically scoped* type variables in
1672 the type environment. Why? After all, the renamer has ensured
1673 that only legal occurrences occur, so we could put all type variables
1674 into the type env.
1675
1676 But we want to check that two distinct lexically scoped type variables
1677 do not map to the same internal type variable. So we need to know which
1678 the lexically-scoped ones are... and at the moment we do that by putting
1679 only the lexically scoped ones into the environment.
1680
1681 Note [Instantiate sig with fresh variables]
1682 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1683 It's vital to instantiate a type signature with fresh variables.
1684 For example:
1685 type T = forall a. [a] -> [a]
1686 f :: T;
1687 f = g where { g :: T; g = <rhs> }
1688
1689 We must not use the same 'a' from the defn of T at both places!!
1690 (Instantiation is only necessary because of type synonyms. Otherwise,
1691 it's all cool; each signature has distinct type variables from the renamer.)
1692
1693 Note [Fail eagerly on bad signatures]
1694 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1695 If a type signaure is wrong, fail immediately:
1696
1697 * the type sigs may bind type variables, so proceeding without them
1698 can lead to a cascade of errors
1699
1700 * the type signature might be ambiguous, in which case checking
1701 the code against the signature will give a very similar error
1702 to the ambiguity error.
1703
1704 ToDo: this means we fall over if any type sig
1705 is wrong (eg at the top level of the module),
1706 which is over-conservative
1707 -}
1708
1709 tcTySigs :: [LSig Name] -> TcM ([TcId], TcSigFun)
1710 tcTySigs hs_sigs
1711 = checkNoErrs $ -- See Note [Fail eagerly on bad signatures]
1712 do { ty_sigs_s <- mapAndRecoverM tcTySig hs_sigs
1713 ; let ty_sigs = concat ty_sigs_s
1714 poly_ids = mapMaybe completeSigPolyId_maybe ty_sigs
1715 -- The returned [TcId] are the ones for which we have
1716 -- a complete type signature.
1717 -- See Note [Complete and partial type signatures]
1718 env = mkNameEnv [(tcSigInfoName sig, sig) | sig <- ty_sigs]
1719 ; return (poly_ids, lookupNameEnv env) }
1720
1721 tcTySig :: LSig Name -> TcM [TcSigInfo]
1722 tcTySig (L _ (IdSig id))
1723 = do { sig <- instTcTySigFromId id
1724 ; return [TcIdSig sig] }
1725
1726 tcTySig (L loc (TypeSig names sig_ty))
1727 = setSrcSpan loc $
1728 do { sigs <- sequence [ tcUserTypeSig sig_ty (Just name)
1729 | L _ name <- names ]
1730 ; return (map TcIdSig sigs) }
1731
1732 tcTySig (L loc (PatSynSig (L _ name) sig_ty))
1733 = setSrcSpan loc $
1734 do { tpsi <- tcPatSynSig name sig_ty
1735 ; return [TcPatSynSig tpsi] }
1736
1737 tcTySig _ = return []
1738
1739 isCompleteHsSig :: LHsSigWcType Name -> Bool
1740 -- ^ If there are no wildcards, return a LHsSigType
1741 isCompleteHsSig sig_ty
1742 | HsWC { hswc_wcs = wcs, hswc_ctx = extra } <- hsib_body sig_ty
1743 , null wcs
1744 , Nothing <- extra
1745 = True
1746 | otherwise
1747 = False
1748
1749 tcUserTypeSig :: LHsSigWcType Name -> Maybe Name -> TcM TcIdSigInfo
1750 -- Just n => Function type signatre name :: type
1751 -- Nothing => Expression type signature <expr> :: type
1752 tcUserTypeSig hs_sig_ty mb_name
1753 | isCompleteHsSig hs_sig_ty
1754 = pushTcLevelM_ $ -- When instantiating the signature, do so "one level in"
1755 -- so that they can be unified under the forall
1756 do { sigma_ty <- tcHsSigWcType ctxt_F hs_sig_ty
1757 ; (inst_tvs, theta, tau) <- tcInstType tcInstSigTyVars sigma_ty
1758 ; loc <- getSrcSpanM
1759 ; return $
1760 TISI { sig_bndr = CompleteSig (mkLocalId name sigma_ty)
1761 , sig_skols = findScopedTyVars sigma_ty inst_tvs
1762 , sig_theta = theta
1763 , sig_tau = tau
1764 , sig_ctxt = ctxt_T
1765 , sig_loc = loc } }
1766
1767 -- Partial sig with wildcards
1768 | HsIB { hsib_vars = vars, hsib_body = wc_ty } <- hs_sig_ty
1769 , HsWC { hswc_wcs = wcs, hswc_ctx = extra, hswc_body = hs_ty } <- wc_ty
1770 , (hs_tvs, L _ hs_ctxt, hs_tau) <- splitLHsSigmaTy hs_ty
1771 = do { (vars1, (wcs, tvs2, theta, tau))
1772 <- pushTcLevelM_ $
1773 -- When instantiating the signature, do so "one level in"
1774 -- so that they can be unified under the forall
1775 tcImplicitTKBndrs vars $
1776 tcWildCardBinders wcs $ \ wcs ->
1777 tcExplicitTKBndrs hs_tvs $ \ tvs2 ->
1778 do { -- Instantiate the type-class context; but if there
1779 -- is an extra-constraints wildcard, just discard it here
1780 traceTc "tcPartial" (ppr name $$ ppr vars $$ ppr wcs)
1781 ; theta <- mapM tcLHsPredType $
1782 case extra of
1783 Nothing -> hs_ctxt
1784 Just _ -> dropTail 1 hs_ctxt
1785
1786 ; tau <- tcHsOpenType hs_tau
1787
1788 -- zonking is necessary to establish type representation
1789 -- invariants
1790 ; theta <- zonkTcTypes theta
1791 ; tau <- zonkTcType tau
1792
1793 -- Check for validity (eg rankN etc)
1794 -- The ambiguity check will happen (from checkValidType),
1795 -- but unnecessarily; it will always succeed because there
1796 -- is no quantification
1797 ; checkValidType ctxt_F (mkPhiTy theta tau)
1798 -- NB: Do this in the context of the pushTcLevel so that
1799 -- the TcLevel invariant is respected
1800
1801 ; let bound_tvs
1802 = unionVarSets [ allBoundVariabless theta
1803 , allBoundVariables tau
1804 , mkVarSet (map snd wcs) ]
1805 ; return ((wcs, tvs2, theta, tau), bound_tvs) }
1806
1807 ; loc <- getSrcSpanM
1808 ; return $
1809 TISI { sig_bndr = PartialSig { sig_name = name, sig_hs_ty = hs_ty
1810 , sig_cts = extra, sig_wcs = wcs }
1811 , sig_skols = [ (tyVarName tv, tv) | tv <- vars1 ++ tvs2 ]
1812 , sig_theta = theta
1813 , sig_tau = tau
1814 , sig_ctxt = ctxt_F
1815 , sig_loc = loc } }
1816 where
1817 name = case mb_name of
1818 Just n -> n
1819 Nothing -> mkUnboundName (mkVarOcc "<expression>")
1820 ctxt_F = case mb_name of
1821 Just n -> FunSigCtxt n False
1822 Nothing -> ExprSigCtxt
1823 ctxt_T = case mb_name of
1824 Just n -> FunSigCtxt n True
1825 Nothing -> ExprSigCtxt
1826
1827 instTcTySigFromId :: Id -> TcM TcIdSigInfo
1828 -- Used for instance methods and record selectors
1829 instTcTySigFromId id
1830 = do { let name = idName id
1831 loc = getSrcSpan name
1832 ; (tvs, theta, tau) <- tcInstType (tcInstSigTyVarsLoc loc)
1833 (idType id)
1834 ; return $ TISI { sig_bndr = CompleteSig id
1835 , sig_skols = [(tyVarName tv, tv) | tv <- tvs]
1836 -- These are freshly instantiated, so although
1837 -- we put them in the type envt, doing so has
1838 -- no effect
1839 , sig_theta = theta
1840 , sig_tau = tau
1841 , sig_ctxt = FunSigCtxt name False
1842 -- False: do not report redundant constraints
1843 -- The user has no control over the signature!
1844 , sig_loc = loc } }
1845
1846 instTcTySig :: UserTypeCtxt
1847 -> LHsSigType Name -- Used to get the scoped type variables
1848 -> TcType
1849 -> Name -- Name of the function
1850 -> TcM TcIdSigInfo
1851 instTcTySig ctxt hs_ty sigma_ty name
1852 = do { (inst_tvs, theta, tau) <- tcInstType tcInstSigTyVars sigma_ty
1853 ; return (TISI { sig_bndr = CompleteSig (mkLocalIdOrCoVar name sigma_ty)
1854 , sig_skols = findScopedTyVars sigma_ty inst_tvs
1855 , sig_theta = theta
1856 , sig_tau = tau
1857 , sig_ctxt = ctxt
1858 , sig_loc = getLoc (hsSigType hs_ty)
1859 -- SrcSpan from the signature
1860 }) }
1861
1862 -------------------------------
1863 data GeneralisationPlan
1864 = NoGen -- No generalisation, no AbsBinds
1865
1866 | InferGen -- Implicit generalisation; there is an AbsBinds
1867 Bool -- True <=> apply the MR; generalise only unconstrained type vars
1868
1869 | CheckGen (LHsBind Name) TcIdSigInfo
1870 -- One FunBind with a signature
1871 -- Explicit generalisation; there is an AbsBindsSig
1872
1873 -- A consequence of the no-AbsBinds choice (NoGen) is that there is
1874 -- no "polymorphic Id" and "monmomorphic Id"; there is just the one
1875
1876 instance Outputable GeneralisationPlan where
1877 ppr NoGen = text "NoGen"
1878 ppr (InferGen b) = text "InferGen" <+> ppr b
1879 ppr (CheckGen _ s) = text "CheckGen" <+> ppr s
1880
1881 decideGeneralisationPlan
1882 :: DynFlags -> TcTypeEnv -> [Name]
1883 -> [LHsBind Name] -> TcSigFun -> GeneralisationPlan
1884 decideGeneralisationPlan dflags type_env bndr_names lbinds sig_fn
1885 | unlifted_pat_binds = NoGen
1886 | Just bind_sig <- one_funbind_with_sig = sig_plan bind_sig
1887 | mono_local_binds = NoGen
1888 | otherwise = InferGen mono_restriction
1889 where
1890 bndr_set = mkNameSet bndr_names
1891 binds = map unLoc lbinds
1892
1893 sig_plan :: (LHsBind Name, TcIdSigInfo) -> GeneralisationPlan
1894 -- See Note [Partial type signatures and generalisation]
1895 -- We use InferGen False to say "do inference, but do not apply
1896 -- the MR". It's stupid to apply the MR when we are given a
1897 -- signature! C.f Trac #11016, function f2
1898 sig_plan (lbind, sig@(TISI { sig_bndr = s_bndr, sig_theta = theta }))
1899 = case s_bndr of
1900 CompleteSig {} -> CheckGen lbind sig
1901 PartialSig { sig_cts = extra_constraints }
1902 | Nothing <- extra_constraints
1903 , [] <- theta
1904 -> InferGen True -- No signature constraints: apply the MR
1905 | otherwise
1906 -> InferGen False -- Don't apply the MR
1907
1908 unlifted_pat_binds = any isUnliftedHsBind binds
1909 -- Unlifted patterns (unboxed tuple) must not
1910 -- be polymorphic, because we are going to force them
1911 -- See Trac #4498, #8762
1912
1913 mono_restriction = xopt LangExt.MonomorphismRestriction dflags
1914 && any restricted binds
1915
1916 is_closed_ns :: NameSet -> Bool -> Bool
1917 is_closed_ns ns b = foldNameSet ((&&) . is_closed_id) b ns
1918 -- ns are the Names referred to from the RHS of this bind
1919
1920 is_closed_id :: Name -> Bool
1921 -- See Note [Bindings with closed types] in TcRnTypes
1922 is_closed_id name
1923 | name `elemNameSet` bndr_set
1924 = True -- Ignore binders in this groups, of course
1925 | Just thing <- lookupNameEnv type_env name
1926 = case thing of
1927 ATcId { tct_closed = cl } -> isTopLevel cl -- This is the key line
1928 ATyVar {} -> False -- In-scope type variables
1929 AGlobal {} -> True -- are not closed!
1930 _ -> pprPanic "is_closed_id" (ppr name)
1931 | otherwise
1932 = WARN( isInternalName name, ppr name ) True
1933 -- The free-var set for a top level binding mentions
1934 -- imported things too, so that we can report unused imports
1935 -- These won't be in the local type env.
1936 -- Ditto class method etc from the current module
1937
1938 mono_local_binds = xopt LangExt.MonoLocalBinds dflags
1939 && not closed_flag
1940
1941 closed_flag = foldr (is_closed_ns . bind_fvs) True binds
1942
1943 no_sig n = noCompleteSig (sig_fn n)
1944
1945 -- With OutsideIn, all nested bindings are monomorphic
1946 -- except a single function binding with a signature
1947 one_funbind_with_sig
1948 | [lbind@(L _ (FunBind { fun_id = v }))] <- lbinds
1949 , Just (TcIdSig sig) <- sig_fn (unLoc v)
1950 = Just (lbind, sig)
1951 | otherwise
1952 = Nothing
1953
1954 -- The Haskell 98 monomorphism restriction
1955 restricted (PatBind {}) = True
1956 restricted (VarBind { var_id = v }) = no_sig v
1957 restricted (FunBind { fun_id = v, fun_matches = m }) = restricted_match m
1958 && no_sig (unLoc v)
1959 restricted (PatSynBind {}) = panic "isRestrictedGroup/unrestricted PatSynBind"
1960 restricted (AbsBinds {}) = panic "isRestrictedGroup/unrestricted AbsBinds"
1961 restricted (AbsBindsSig {}) = panic "isRestrictedGroup/unrestricted AbsBindsSig"
1962
1963 restricted_match (MG { mg_alts = L _ (L _ (Match _ [] _ _) : _ )}) = True
1964 restricted_match _ = False
1965 -- No args => like a pattern binding
1966 -- Some args => a function binding
1967
1968 -------------------
1969 checkStrictBinds :: TopLevelFlag -> RecFlag
1970 -> [LHsBind Name]
1971 -> LHsBinds TcId -> [Id]
1972 -> TcM ()
1973 -- Check that non-overloaded unlifted bindings are
1974 -- a) non-recursive,
1975 -- b) not top level,
1976 -- c) not a multiple-binding group (more or less implied by (a))
1977
1978 checkStrictBinds top_lvl rec_group orig_binds tc_binds poly_ids
1979 | any_unlifted_bndr || any_strict_pat -- This binding group must be matched strictly
1980 = do { check (isNotTopLevel top_lvl)
1981 (strictBindErr "Top-level" any_unlifted_bndr orig_binds)
1982 ; check (isNonRec rec_group)
1983 (strictBindErr "Recursive" any_unlifted_bndr orig_binds)
1984
1985 ; check (all is_monomorphic (bagToList tc_binds))
1986 (polyBindErr orig_binds)
1987 -- data Ptr a = Ptr Addr#
1988 -- f x = let p@(Ptr y) = ... in ...
1989 -- Here the binding for 'p' is polymorphic, but does
1990 -- not mix with an unlifted binding for 'y'. You should
1991 -- use a bang pattern. Trac #6078.
1992
1993 ; check (isSingleton orig_binds)
1994 (strictBindErr "Multiple" any_unlifted_bndr orig_binds)
1995
1996 -- Complain about a binding that looks lazy
1997 -- e.g. let I# y = x in ...
1998 -- Remember, in checkStrictBinds we are going to do strict
1999 -- matching, so (for software engineering reasons) we insist
2000 -- that the strictness is manifest on each binding
2001 -- However, lone (unboxed) variables are ok
2002 ; check (not any_pat_looks_lazy)
2003 (unliftedMustBeBang orig_binds) }
2004 | otherwise
2005 = traceTc "csb2" (ppr [(id, idType id) | id <- poly_ids]) >>
2006 return ()
2007 where
2008 any_unlifted_bndr = any is_unlifted poly_ids
2009 any_strict_pat = any (isUnliftedHsBind . unLoc) orig_binds
2010 any_pat_looks_lazy = any (looksLazyPatBind . unLoc) orig_binds
2011
2012 is_unlifted id = case tcSplitSigmaTy (idType id) of
2013 (_, _, rho) -> isUnliftedType rho
2014 -- For the is_unlifted check, we need to look inside polymorphism
2015 -- and overloading. E.g. x = (# 1, True #)
2016 -- would get type forall a. Num a => (# a, Bool #)
2017 -- and we want to reject that. See Trac #9140
2018
2019 is_monomorphic (L _ (AbsBinds { abs_tvs = tvs, abs_ev_vars = evs }))
2020 = null tvs && null evs
2021 is_monomorphic (L _ (AbsBindsSig { abs_tvs = tvs, abs_ev_vars = evs }))
2022 = null tvs && null evs
2023 is_monomorphic _ = True
2024
2025 check :: Bool -> MsgDoc -> TcM ()
2026 -- Just like checkTc, but with a special case for module GHC.Prim:
2027 -- see Note [Compiling GHC.Prim]
2028 check True _ = return ()
2029 check False err = do { mod <- getModule
2030 ; checkTc (mod == gHC_PRIM) err }
2031
2032 unliftedMustBeBang :: [LHsBind Name] -> SDoc
2033 unliftedMustBeBang binds
2034 = hang (text "Pattern bindings containing unlifted types should use an outermost bang pattern:")
2035 2 (vcat (map ppr binds))
2036
2037 polyBindErr :: [LHsBind Name] -> SDoc
2038 polyBindErr binds
2039 = hang (text "You can't mix polymorphic and unlifted bindings")
2040 2 (vcat [vcat (map ppr binds),
2041 text "Probable fix: add a type signature"])
2042
2043 strictBindErr :: String -> Bool -> [LHsBind Name] -> SDoc
2044 strictBindErr flavour any_unlifted_bndr binds
2045 = hang (text flavour <+> msg <+> text "aren't allowed:")
2046 2 (vcat (map ppr binds))
2047 where
2048 msg | any_unlifted_bndr = text "bindings for unlifted types"
2049 | otherwise = text "bang-pattern or unboxed-tuple bindings"
2050
2051
2052 {- Note [Compiling GHC.Prim]
2053 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2054 Module GHC.Prim has no source code: it is the host module for
2055 primitive, built-in functions and types. However, for Haddock-ing
2056 purposes we generate (via utils/genprimopcode) a fake source file
2057 GHC/Prim.hs, and give it to Haddock, so that it can generate
2058 documentation. It contains definitions like
2059 nullAddr# :: NullAddr#
2060 which would normally be rejected as a top-level unlifted binding. But
2061 we don't want to complain, because we are only "compiling" this fake
2062 mdule for documentation purposes. Hence this hacky test for gHC_PRIM
2063 in checkStrictBinds.
2064
2065 (We only make the test if things look wrong, so there is no cost in
2066 the common case.) -}
2067
2068
2069 {- *********************************************************************
2070 * *
2071 Error contexts and messages
2072 * *
2073 ********************************************************************* -}
2074
2075 -- This one is called on LHS, when pat and grhss are both Name
2076 -- and on RHS, when pat is TcId and grhss is still Name
2077 patMonoBindsCtxt :: (OutputableBndr id, Outputable body) => LPat id -> GRHSs Name body -> SDoc
2078 patMonoBindsCtxt pat grhss
2079 = hang (text "In a pattern binding:") 2 (pprPatBind pat grhss)
2080
2081 typeSigCtxt :: UserTypeCtxt -> TcIdSigBndr -> SDoc
2082 typeSigCtxt ctxt (PartialSig { sig_hs_ty = hs_ty })
2083 = pprSigCtxt ctxt empty (ppr hs_ty)
2084 typeSigCtxt ctxt (CompleteSig id)
2085 = pprSigCtxt ctxt empty (ppr (idType id))
2086
2087 instErrCtxt :: Name -> TcType -> TidyEnv -> TcM (TidyEnv, SDoc)
2088 instErrCtxt name ty env
2089 = do { let (env', ty') = tidyOpenType env ty
2090 ; return (env', hang (text "When instantiating" <+> quotes (ppr name) <>
2091 text ", initially inferred to have" $$
2092 text "this overly-general type:")
2093 2 (ppr ty') $$
2094 extra) }
2095 where
2096 extra = sdocWithDynFlags $ \dflags ->
2097 ppWhen (xopt LangExt.MonomorphismRestriction dflags) $
2098 text "NB: This instantiation can be caused by the" <+>
2099 text "monomorphism restriction."