4f4d9b0f82974d9b83c11c414c55a8b8d18d3eea
[ghc.git] / compiler / typecheck / TcSigs.hs
1 {-
2 (c) The University of Glasgow 2006-2012
3 (c) The GRASP Project, Glasgow University, 1992-2002
4
5 -}
6
7 {-# LANGUAGE CPP #-}
8 {-# LANGUAGE TypeFamilies #-}
9
10 module TcSigs(
11 TcSigInfo(..),
12 TcIdSigInfo(..), TcIdSigInst,
13 TcPatSynInfo(..),
14 TcSigFun,
15
16 isPartialSig, hasCompleteSig, tcIdSigName, tcSigInfoName,
17 completeSigPolyId_maybe,
18
19 tcTySigs, tcUserTypeSig, completeSigFromId,
20 tcInstSig,
21
22 TcPragEnv, emptyPragEnv, lookupPragEnv, extendPragEnv,
23 mkPragEnv, tcSpecPrags, tcSpecWrapper, tcImpPrags, addInlinePrags
24 ) where
25
26 #include "HsVersions.h"
27
28 import GhcPrelude
29
30 import HsSyn
31 import TcHsType
32 import TcRnTypes
33 import TcRnMonad
34 import TcType
35 import TcMType
36 import TcValidity ( checkValidType )
37 import TcUnify( tcSkolemise, unifyType )
38 import Inst( topInstantiate )
39 import TcEnv( tcLookupId )
40 import TcEvidence( HsWrapper, (<.>) )
41 import Type( mkTyVarBinders )
42
43 import DynFlags
44 import Var ( TyVar, tyVarKind )
45 import VarSet
46 import VarEnv ( mkInScopeSet )
47 import Id ( Id, idName, idType, idInlinePragma, setInlinePragma, mkLocalId )
48 import PrelNames( mkUnboundName )
49 import BasicTypes
50 import Bag( foldrBag )
51 import Module( getModule )
52 import Name
53 import NameEnv
54 import Outputable
55 import SrcLoc
56 import Util( singleton )
57 import Maybes( orElse )
58 import Data.Maybe( mapMaybe )
59 import Control.Monad( unless )
60
61
62 {- -------------------------------------------------------------
63 Note [Overview of type signatures]
64 ----------------------------------------------------------------
65 Type signatures, including partial signatures, are jolly tricky,
66 especially on value bindings. Here's an overview.
67
68 f :: forall a. [a] -> [a]
69 g :: forall b. _ -> b
70
71 f = ...g...
72 g = ...f...
73
74 * HsSyn: a signature in a binding starts off as a TypeSig, in
75 type HsBinds.Sig
76
77 * When starting a mutually recursive group, like f/g above, we
78 call tcTySig on each signature in the group.
79
80 * tcTySig: Sig -> TcIdSigInfo
81 - For a /complete/ signature, like 'f' above, tcTySig kind-checks
82 the HsType, producing a Type, and wraps it in a CompleteSig, and
83 extend the type environment with this polymorphic 'f'.
84
85 - For a /partial/signature, like 'g' above, tcTySig does nothing
86 Instead it just wraps the pieces in a PartialSig, to be handled
87 later.
88
89 * tcInstSig: TcIdSigInfo -> TcIdSigInst
90 In tcMonoBinds, when looking at an individual binding, we use
91 tcInstSig to instantiate the signature forall's in the signature,
92 and attribute that instantiated (monomorphic) type to the
93 binder. You can see this in TcBinds.tcLhsId.
94
95 The instantiation does the obvious thing for complete signatures,
96 but for /partial/ signatures it starts from the HsSyn, so it
97 has to kind-check it etc: tcHsPartialSigType. It's convenient
98 to do this at the same time as instantiation, because we can
99 make the wildcards into unification variables right away, raather
100 than somehow quantifying over them. And the "TcLevel" of those
101 unification variables is correct because we are in tcMonoBinds.
102
103
104 Note [Scoped tyvars]
105 ~~~~~~~~~~~~~~~~~~~~
106 The -XScopedTypeVariables flag brings lexically-scoped type variables
107 into scope for any explicitly forall-quantified type variables:
108 f :: forall a. a -> a
109 f x = e
110 Then 'a' is in scope inside 'e'.
111
112 However, we do *not* support this
113 - For pattern bindings e.g
114 f :: forall a. a->a
115 (f,g) = e
116
117 Note [Binding scoped type variables]
118 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
119 The type variables *brought into lexical scope* by a type signature
120 may be a subset of the *quantified type variables* of the signatures,
121 for two reasons:
122
123 * With kind polymorphism a signature like
124 f :: forall f a. f a -> f a
125 may actually give rise to
126 f :: forall k. forall (f::k -> *) (a:k). f a -> f a
127 So the sig_tvs will be [k,f,a], but only f,a are scoped.
128 NB: the scoped ones are not necessarily the *inital* ones!
129
130 * Even aside from kind polymorphism, there may be more instantiated
131 type variables than lexically-scoped ones. For example:
132 type T a = forall b. b -> (a,b)
133 f :: forall c. T c
134 Here, the signature for f will have one scoped type variable, c,
135 but two instantiated type variables, c' and b'.
136
137 However, all of this only applies to the renamer. The typechecker
138 just puts all of them into the type environment; any lexical-scope
139 errors were dealt with by the renamer.
140
141 -}
142
143
144 {- *********************************************************************
145 * *
146 Utility functions for TcSigInfo
147 * *
148 ********************************************************************* -}
149
150 tcIdSigName :: TcIdSigInfo -> Name
151 tcIdSigName (CompleteSig { sig_bndr = id }) = idName id
152 tcIdSigName (PartialSig { psig_name = n }) = n
153
154 tcSigInfoName :: TcSigInfo -> Name
155 tcSigInfoName (TcIdSig idsi) = tcIdSigName idsi
156 tcSigInfoName (TcPatSynSig tpsi) = patsig_name tpsi
157
158 completeSigPolyId_maybe :: TcSigInfo -> Maybe TcId
159 completeSigPolyId_maybe sig
160 | TcIdSig sig_info <- sig
161 , CompleteSig { sig_bndr = id } <- sig_info = Just id
162 | otherwise = Nothing
163
164
165 {- *********************************************************************
166 * *
167 Typechecking user signatures
168 * *
169 ********************************************************************* -}
170
171 tcTySigs :: [LSig GhcRn] -> TcM ([TcId], TcSigFun)
172 tcTySigs hs_sigs
173 = checkNoErrs $ -- See Note [Fail eagerly on bad signatures]
174 do { ty_sigs_s <- mapAndRecoverM tcTySig hs_sigs
175 ; let ty_sigs = concat ty_sigs_s
176 poly_ids = mapMaybe completeSigPolyId_maybe ty_sigs
177 -- The returned [TcId] are the ones for which we have
178 -- a complete type signature.
179 -- See Note [Complete and partial type signatures]
180 env = mkNameEnv [(tcSigInfoName sig, sig) | sig <- ty_sigs]
181 ; return (poly_ids, lookupNameEnv env) }
182
183 tcTySig :: LSig GhcRn -> TcM [TcSigInfo]
184 tcTySig (L _ (IdSig _ id))
185 = do { let ctxt = FunSigCtxt (idName id) False
186 -- False: do not report redundant constraints
187 -- The user has no control over the signature!
188 sig = completeSigFromId ctxt id
189 ; return [TcIdSig sig] }
190
191 tcTySig (L loc (TypeSig _ names sig_ty))
192 = setSrcSpan loc $
193 do { sigs <- sequence [ tcUserTypeSig loc sig_ty (Just name)
194 | L _ name <- names ]
195 ; return (map TcIdSig sigs) }
196
197 tcTySig (L loc (PatSynSig _ names sig_ty))
198 = setSrcSpan loc $
199 do { tpsigs <- sequence [ tcPatSynSig name sig_ty
200 | L _ name <- names ]
201 ; return (map TcPatSynSig tpsigs) }
202
203 tcTySig _ = return []
204
205
206 tcUserTypeSig :: SrcSpan -> LHsSigWcType GhcRn -> Maybe Name
207 -> TcM TcIdSigInfo
208 -- A function or expression type signature
209 -- Returns a fully quantified type signature; even the wildcards
210 -- are quantified with ordinary skolems that should be instantiated
211 --
212 -- The SrcSpan is what to declare as the binding site of the
213 -- any skolems in the signature. For function signatures we
214 -- use the whole `f :: ty' signature; for expression signatures
215 -- just the type part.
216 --
217 -- Just n => Function type signature name :: type
218 -- Nothing => Expression type signature <expr> :: type
219 tcUserTypeSig loc hs_sig_ty mb_name
220 | isCompleteHsSig hs_sig_ty
221 = do { sigma_ty <- tcHsSigWcType ctxt_F hs_sig_ty
222 ; return $
223 CompleteSig { sig_bndr = mkLocalId name sigma_ty
224 , sig_ctxt = ctxt_T
225 , sig_loc = loc } }
226 -- Location of the <type> in f :: <type>
227
228 -- Partial sig with wildcards
229 | otherwise
230 = return (PartialSig { psig_name = name, psig_hs_ty = hs_sig_ty
231 , sig_ctxt = ctxt_F, sig_loc = loc })
232 where
233 name = case mb_name of
234 Just n -> n
235 Nothing -> mkUnboundName (mkVarOcc "<expression>")
236 ctxt_F = case mb_name of
237 Just n -> FunSigCtxt n False
238 Nothing -> ExprSigCtxt
239 ctxt_T = case mb_name of
240 Just n -> FunSigCtxt n True
241 Nothing -> ExprSigCtxt
242
243
244
245 completeSigFromId :: UserTypeCtxt -> Id -> TcIdSigInfo
246 -- Used for instance methods and record selectors
247 completeSigFromId ctxt id
248 = CompleteSig { sig_bndr = id
249 , sig_ctxt = ctxt
250 , sig_loc = getSrcSpan id }
251
252 isCompleteHsSig :: LHsSigWcType GhcRn -> Bool
253 -- ^ If there are no wildcards, return a LHsSigType
254 isCompleteHsSig (HsWC { hswc_ext = wcs }) = null wcs
255 isCompleteHsSig (XHsWildCardBndrs _) = panic "isCompleteHsSig"
256
257 {- Note [Fail eagerly on bad signatures]
258 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
259 If a type signature is wrong, fail immediately:
260
261 * the type sigs may bind type variables, so proceeding without them
262 can lead to a cascade of errors
263
264 * the type signature might be ambiguous, in which case checking
265 the code against the signature will give a very similar error
266 to the ambiguity error.
267
268 ToDo: this means we fall over if any type sig
269 is wrong (eg at the top level of the module),
270 which is over-conservative
271 -}
272
273 {- *********************************************************************
274 * *
275 Type checking a pattern synonym signature
276 * *
277 ************************************************************************
278
279 Note [Pattern synonym signatures]
280 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
281 Pattern synonym signatures are surprisingly tricky (see Trac #11224 for example).
282 In general they look like this:
283
284 pattern P :: forall univ_tvs. req_theta
285 => forall ex_tvs. prov_theta
286 => arg1 -> .. -> argn -> res_ty
287
288 For parsing and renaming we treat the signature as an ordinary LHsSigType.
289
290 Once we get to type checking, we decompose it into its parts, in tcPatSynSig.
291
292 * Note that 'forall univ_tvs' and 'req_theta =>'
293 and 'forall ex_tvs' and 'prov_theta =>'
294 are all optional. We gather the pieces at the top of tcPatSynSig
295
296 * Initially the implicitly-bound tyvars (added by the renamer) include both
297 universal and existential vars.
298
299 * After we kind-check the pieces and convert to Types, we do kind generalisation.
300 -}
301
302 tcPatSynSig :: Name -> LHsSigType GhcRn -> TcM TcPatSynInfo
303 -- See Note [Pattern synonym signatures]
304 -- See Note [Recipe for checking a signature] in TcHsType
305 tcPatSynSig name sig_ty
306 | HsIB { hsib_ext = implicit_hs_tvs
307 , hsib_body = hs_ty } <- sig_ty
308 , (univ_hs_tvs, hs_req, hs_ty1) <- splitLHsSigmaTy hs_ty
309 , (ex_hs_tvs, hs_prov, hs_body_ty) <- splitLHsSigmaTy hs_ty1
310 = do { (implicit_tvs, (univ_tvs, (ex_tvs, (req, prov, body_ty))))
311 <- -- NB: tcImplicitTKBndrs calls solveLocalEqualities
312 tcImplicitTKBndrs skol_info implicit_hs_tvs $
313 tcExplicitTKBndrs skol_info univ_hs_tvs $
314 tcExplicitTKBndrs skol_info ex_hs_tvs $
315 do { req <- tcHsContext hs_req
316 ; prov <- tcHsContext hs_prov
317 ; body_ty <- tcHsOpenType hs_body_ty
318 -- A (literal) pattern can be unlifted;
319 -- e.g. pattern Zero <- 0# (Trac #12094)
320 ; return (req, prov, body_ty) }
321
322 ; let ungen_patsyn_ty = build_patsyn_type [] implicit_tvs univ_tvs req
323 ex_tvs prov body_ty
324
325 -- Kind generalisation
326 ; kvs <- kindGeneralize ungen_patsyn_ty
327
328 -- These are /signatures/ so we zonk to squeeze out any kind
329 -- unification variables. Do this after kindGeneralize which may
330 -- default kind variables to *.
331 ; implicit_tvs <- mapM zonkTcTyCoVarBndr implicit_tvs
332 ; univ_tvs <- mapM zonkTcTyCoVarBndr univ_tvs
333 ; ex_tvs <- mapM zonkTcTyCoVarBndr ex_tvs
334 ; req <- zonkTcTypes req
335 ; prov <- zonkTcTypes prov
336 ; body_ty <- zonkTcType body_ty
337
338 -- Skolems have TcLevels too, though they're used only for debugging.
339 -- If you don't do this, the debugging checks fail in TcPatSyn.
340 -- Test case: patsyn/should_compile/T13441
341 ; tclvl <- getTcLevel
342 ; let env0 = mkEmptyTCvSubst $ mkInScopeSet $ mkVarSet kvs
343 (env1, implicit_tvs') = promoteSkolemsX tclvl env0 implicit_tvs
344 (env2, univ_tvs') = promoteSkolemsX tclvl env1 univ_tvs
345 (env3, ex_tvs') = promoteSkolemsX tclvl env2 ex_tvs
346 req' = substTys env3 req
347 prov' = substTys env3 prov
348 body_ty' = substTy env3 body_ty
349
350 -- Now do validity checking
351 ; checkValidType ctxt $
352 build_patsyn_type kvs implicit_tvs' univ_tvs' req' ex_tvs' prov' body_ty'
353
354 -- arguments become the types of binders. We thus cannot allow
355 -- levity polymorphism here
356 ; let (arg_tys, _) = tcSplitFunTys body_ty'
357 ; mapM_ (checkForLevPoly empty) arg_tys
358
359 ; traceTc "tcTySig }" $
360 vcat [ text "implicit_tvs" <+> ppr_tvs implicit_tvs'
361 , text "kvs" <+> ppr_tvs kvs
362 , text "univ_tvs" <+> ppr_tvs univ_tvs'
363 , text "req" <+> ppr req'
364 , text "ex_tvs" <+> ppr_tvs ex_tvs'
365 , text "prov" <+> ppr prov'
366 , text "body_ty" <+> ppr body_ty' ]
367 ; return (TPSI { patsig_name = name
368 , patsig_implicit_bndrs = mkTyVarBinders Inferred kvs ++
369 mkTyVarBinders Specified implicit_tvs'
370 , patsig_univ_bndrs = univ_tvs'
371 , patsig_req = req'
372 , patsig_ex_bndrs = ex_tvs'
373 , patsig_prov = prov'
374 , patsig_body_ty = body_ty' }) }
375 where
376 ctxt = PatSynCtxt name
377 skol_info = SigTypeSkol ctxt
378
379 build_patsyn_type kvs imp univ req ex prov body
380 = mkInvForAllTys kvs $
381 mkSpecForAllTys (imp ++ univ) $
382 mkFunTys req $
383 mkSpecForAllTys ex $
384 mkFunTys prov $
385 body
386 tcPatSynSig _ (XHsImplicitBndrs _) = panic "tcPatSynSig"
387
388 ppr_tvs :: [TyVar] -> SDoc
389 ppr_tvs tvs = braces (vcat [ ppr tv <+> dcolon <+> ppr (tyVarKind tv)
390 | tv <- tvs])
391
392
393 {- *********************************************************************
394 * *
395 Instantiating user signatures
396 * *
397 ********************************************************************* -}
398
399
400 tcInstSig :: TcIdSigInfo -> TcM TcIdSigInst
401 -- Instantiate a type signature; only used with plan InferGen
402 tcInstSig sig@(CompleteSig { sig_bndr = poly_id, sig_loc = loc })
403 = setSrcSpan loc $ -- Set the binding site of the tyvars
404 do { (tv_prs, theta, tau) <- tcInstType newMetaSigTyVars poly_id
405 -- See Note [Pattern bindings and complete signatures]
406
407 ; return (TISI { sig_inst_sig = sig
408 , sig_inst_skols = tv_prs
409 , sig_inst_wcs = []
410 , sig_inst_wcx = Nothing
411 , sig_inst_theta = theta
412 , sig_inst_tau = tau }) }
413
414 tcInstSig sig@(PartialSig { psig_hs_ty = hs_ty
415 , sig_ctxt = ctxt
416 , sig_loc = loc })
417 = setSrcSpan loc $ -- Set the binding site of the tyvars
418 do { (wcs, wcx, tv_names, tvs, theta, tau) <- tcHsPartialSigType ctxt hs_ty
419
420 -- Clone the quantified tyvars
421 -- Reason: we might have f, g :: forall a. a -> _ -> a
422 -- and we want it to behave exactly as if there were
423 -- two separate signatures. Cloning here seems like
424 -- the easiest way to do so, and is very similar to
425 -- the tcInstType in the CompleteSig case
426 -- See Trac #14643
427 ; let in_scope = mkInScopeSet $ closeOverKinds $ unionVarSets
428 [ mkVarSet (map snd wcs)
429 , maybe emptyVarSet tyCoVarsOfType wcx
430 , mkVarSet tvs
431 , tyCoVarsOfTypes theta
432 , tyCoVarsOfType tau ]
433 -- the in_scope is a bit bigger than nec'y, but too big is always
434 -- safe
435 empty_subst = mkEmptyTCvSubst in_scope
436 ; (subst, tvs') <- instSkolTyCoVarsX mk_sig_tv empty_subst tvs
437 ; let tv_prs = tv_names `zip` tvs'
438
439 ; return (TISI { sig_inst_sig = sig
440 , sig_inst_skols = tv_prs
441 , sig_inst_wcs = wcs
442 , sig_inst_wcx = wcx
443 , sig_inst_theta = substTys subst theta
444 , sig_inst_tau = substTy subst tau
445 }) }
446 where
447 mk_sig_tv old_name kind
448 = do { uniq <- newUnique
449 ; newSigTyVar (setNameUnique old_name uniq) kind }
450 -- Why newSigTyVar? See TcBinds
451 -- Note [Quantified variables in partial type signatures]
452
453
454 {- Note [Pattern bindings and complete signatures]
455 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
456 Consider
457 data T a = MkT a a
458 f :: forall a. a->a
459 g :: forall b. b->b
460 MkT f g = MkT (\x->x) (\y->y)
461 Here we'll infer a type from the pattern of 'T a', but if we feed in
462 the signature types for f and g, we'll end up unifying 'a' and 'b'
463
464 So we instantiate f and g's signature with SigTv skolems
465 (newMetaSigTyVars) that can unify with each other. If too much
466 unification takes place, we'll find out when we do the final
467 impedance-matching check in TcBinds.mkExport
468
469 See Note [Signature skolems] in TcType
470
471 None of this applies to a function binding with a complete
472 signature, which doesn't use tcInstSig. See TcBinds.tcPolyCheck.
473 -}
474
475 {- *********************************************************************
476 * *
477 Pragmas and PragEnv
478 * *
479 ********************************************************************* -}
480
481 type TcPragEnv = NameEnv [LSig GhcRn]
482
483 emptyPragEnv :: TcPragEnv
484 emptyPragEnv = emptyNameEnv
485
486 lookupPragEnv :: TcPragEnv -> Name -> [LSig GhcRn]
487 lookupPragEnv prag_fn n = lookupNameEnv prag_fn n `orElse` []
488
489 extendPragEnv :: TcPragEnv -> (Name, LSig GhcRn) -> TcPragEnv
490 extendPragEnv prag_fn (n, sig) = extendNameEnv_Acc (:) singleton prag_fn n sig
491
492 ---------------
493 mkPragEnv :: [LSig GhcRn] -> LHsBinds GhcRn -> TcPragEnv
494 mkPragEnv sigs binds
495 = foldl extendPragEnv emptyNameEnv prs
496 where
497 prs = mapMaybe get_sig sigs
498
499 get_sig :: LSig GhcRn -> Maybe (Name, LSig GhcRn)
500 get_sig (L l (SpecSig x lnm@(L _ nm) ty inl))
501 = Just (nm, L l $ SpecSig x lnm ty (add_arity nm inl))
502 get_sig (L l (InlineSig x lnm@(L _ nm) inl))
503 = Just (nm, L l $ InlineSig x lnm (add_arity nm inl))
504 get_sig (L l (SCCFunSig x st lnm@(L _ nm) str))
505 = Just (nm, L l $ SCCFunSig x st lnm str)
506 get_sig _ = Nothing
507
508 add_arity n inl_prag -- Adjust inl_sat field to match visible arity of function
509 | Inline <- inl_inline inl_prag
510 -- add arity only for real INLINE pragmas, not INLINABLE
511 = case lookupNameEnv ar_env n of
512 Just ar -> inl_prag { inl_sat = Just ar }
513 Nothing -> WARN( True, text "mkPragEnv no arity" <+> ppr n )
514 -- There really should be a binding for every INLINE pragma
515 inl_prag
516 | otherwise
517 = inl_prag
518
519 -- ar_env maps a local to the arity of its definition
520 ar_env :: NameEnv Arity
521 ar_env = foldrBag lhsBindArity emptyNameEnv binds
522
523 lhsBindArity :: LHsBind GhcRn -> NameEnv Arity -> NameEnv Arity
524 lhsBindArity (L _ (FunBind { fun_id = id, fun_matches = ms })) env
525 = extendNameEnv env (unLoc id) (matchGroupArity ms)
526 lhsBindArity _ env = env -- PatBind/VarBind
527
528
529 -----------------
530 addInlinePrags :: TcId -> [LSig GhcRn] -> TcM TcId
531 addInlinePrags poly_id prags_for_me
532 | inl@(L _ prag) : inls <- inl_prags
533 = do { traceTc "addInlinePrag" (ppr poly_id $$ ppr prag)
534 ; unless (null inls) (warn_multiple_inlines inl inls)
535 ; return (poly_id `setInlinePragma` prag) }
536 | otherwise
537 = return poly_id
538 where
539 inl_prags = [L loc prag | L loc (InlineSig _ _ prag) <- prags_for_me]
540
541 warn_multiple_inlines _ [] = return ()
542
543 warn_multiple_inlines inl1@(L loc prag1) (inl2@(L _ prag2) : inls)
544 | inlinePragmaActivation prag1 == inlinePragmaActivation prag2
545 , noUserInlineSpec (inlinePragmaSpec prag1)
546 = -- Tiresome: inl1 is put there by virtue of being in a hs-boot loop
547 -- and inl2 is a user NOINLINE pragma; we don't want to complain
548 warn_multiple_inlines inl2 inls
549 | otherwise
550 = setSrcSpan loc $
551 addWarnTc NoReason
552 (hang (text "Multiple INLINE pragmas for" <+> ppr poly_id)
553 2 (vcat (text "Ignoring all but the first"
554 : map pp_inl (inl1:inl2:inls))))
555
556 pp_inl (L loc prag) = ppr prag <+> parens (ppr loc)
557
558
559 {- *********************************************************************
560 * *
561 SPECIALISE pragmas
562 * *
563 ************************************************************************
564
565 Note [Handling SPECIALISE pragmas]
566 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
567 The basic idea is this:
568
569 foo :: Num a => a -> b -> a
570 {-# SPECIALISE foo :: Int -> b -> Int #-}
571
572 We check that
573 (forall a b. Num a => a -> b -> a)
574 is more polymorphic than
575 forall b. Int -> b -> Int
576 (for which we could use tcSubType, but see below), generating a HsWrapper
577 to connect the two, something like
578 wrap = /\b. <hole> Int b dNumInt
579 This wrapper is put in the TcSpecPrag, in the ABExport record of
580 the AbsBinds.
581
582
583 f :: (Eq a, Ix b) => a -> b -> Bool
584 {-# SPECIALISE f :: (Ix p, Ix q) => Int -> (p,q) -> Bool #-}
585 f = <poly_rhs>
586
587 From this the typechecker generates
588
589 AbsBinds [ab] [d1,d2] [([ab], f, f_mono, prags)] binds
590
591 SpecPrag (wrap_fn :: forall a b. (Eq a, Ix b) => XXX
592 -> forall p q. (Ix p, Ix q) => XXX[ Int/a, (p,q)/b ])
593
594 From these we generate:
595
596 Rule: forall p, q, (dp:Ix p), (dq:Ix q).
597 f Int (p,q) dInt ($dfInPair dp dq) = f_spec p q dp dq
598
599 Spec bind: f_spec = wrap_fn <poly_rhs>
600
601 Note that
602
603 * The LHS of the rule may mention dictionary *expressions* (eg
604 $dfIxPair dp dq), and that is essential because the dp, dq are
605 needed on the RHS.
606
607 * The RHS of f_spec, <poly_rhs> has a *copy* of 'binds', so that it
608 can fully specialise it.
609
610
611
612 From the TcSpecPrag, in DsBinds we generate a binding for f_spec and a RULE:
613
614 f_spec :: Int -> b -> Int
615 f_spec = wrap<f rhs>
616
617 RULE: forall b (d:Num b). f b d = f_spec b
618
619 The RULE is generated by taking apart the HsWrapper, which is a little
620 delicate, but works.
621
622 Some wrinkles
623
624 1. We don't use full-on tcSubType, because that does co and contra
625 variance and that in turn will generate too complex a LHS for the
626 RULE. So we use a single invocation of skolemise /
627 topInstantiate in tcSpecWrapper. (Actually I think that even
628 the "deeply" stuff may be too much, because it introduces lambdas,
629 though I think it can be made to work without too much trouble.)
630
631 2. We need to take care with type families (Trac #5821). Consider
632 type instance F Int = Bool
633 f :: Num a => a -> F a
634 {-# SPECIALISE foo :: Int -> Bool #-}
635
636 We *could* try to generate an f_spec with precisely the declared type:
637 f_spec :: Int -> Bool
638 f_spec = <f rhs> Int dNumInt |> co
639
640 RULE: forall d. f Int d = f_spec |> sym co
641
642 but the 'co' and 'sym co' are (a) playing no useful role, and (b) are
643 hard to generate. At all costs we must avoid this:
644 RULE: forall d. f Int d |> co = f_spec
645 because the LHS will never match (indeed it's rejected in
646 decomposeRuleLhs).
647
648 So we simply do this:
649 - Generate a constraint to check that the specialised type (after
650 skolemiseation) is equal to the instantiated function type.
651 - But *discard* the evidence (coercion) for that constraint,
652 so that we ultimately generate the simpler code
653 f_spec :: Int -> F Int
654 f_spec = <f rhs> Int dNumInt
655
656 RULE: forall d. f Int d = f_spec
657 You can see this discarding happening in
658
659 3. Note that the HsWrapper can transform *any* function with the right
660 type prefix
661 forall ab. (Eq a, Ix b) => XXX
662 regardless of XXX. It's sort of polymorphic in XXX. This is
663 useful: we use the same wrapper to transform each of the class ops, as
664 well as the dict. That's what goes on in TcInstDcls.mk_meth_spec_prags
665 -}
666
667 tcSpecPrags :: Id -> [LSig GhcRn]
668 -> TcM [LTcSpecPrag]
669 -- Add INLINE and SPECIALSE pragmas
670 -- INLINE prags are added to the (polymorphic) Id directly
671 -- SPECIALISE prags are passed to the desugarer via TcSpecPrags
672 -- Pre-condition: the poly_id is zonked
673 -- Reason: required by tcSubExp
674 tcSpecPrags poly_id prag_sigs
675 = do { traceTc "tcSpecPrags" (ppr poly_id <+> ppr spec_sigs)
676 ; unless (null bad_sigs) warn_discarded_sigs
677 ; pss <- mapAndRecoverM (wrapLocM (tcSpecPrag poly_id)) spec_sigs
678 ; return $ concatMap (\(L l ps) -> map (L l) ps) pss }
679 where
680 spec_sigs = filter isSpecLSig prag_sigs
681 bad_sigs = filter is_bad_sig prag_sigs
682 is_bad_sig s = not (isSpecLSig s || isInlineLSig s || isSCCFunSig s)
683
684 warn_discarded_sigs
685 = addWarnTc NoReason
686 (hang (text "Discarding unexpected pragmas for" <+> ppr poly_id)
687 2 (vcat (map (ppr . getLoc) bad_sigs)))
688
689 --------------
690 tcSpecPrag :: TcId -> Sig GhcRn -> TcM [TcSpecPrag]
691 tcSpecPrag poly_id prag@(SpecSig _ fun_name hs_tys inl)
692 -- See Note [Handling SPECIALISE pragmas]
693 --
694 -- The Name fun_name in the SpecSig may not be the same as that of the poly_id
695 -- Example: SPECIALISE for a class method: the Name in the SpecSig is
696 -- for the selector Id, but the poly_id is something like $cop
697 -- However we want to use fun_name in the error message, since that is
698 -- what the user wrote (Trac #8537)
699 = addErrCtxt (spec_ctxt prag) $
700 do { warnIf (not (isOverloadedTy poly_ty || isInlinePragma inl))
701 (text "SPECIALISE pragma for non-overloaded function"
702 <+> quotes (ppr fun_name))
703 -- Note [SPECIALISE pragmas]
704 ; spec_prags <- mapM tc_one hs_tys
705 ; traceTc "tcSpecPrag" (ppr poly_id $$ nest 2 (vcat (map ppr spec_prags)))
706 ; return spec_prags }
707 where
708 name = idName poly_id
709 poly_ty = idType poly_id
710 spec_ctxt prag = hang (text "In the SPECIALISE pragma") 2 (ppr prag)
711
712 tc_one hs_ty
713 = do { spec_ty <- tcHsSigType (FunSigCtxt name False) hs_ty
714 ; wrap <- tcSpecWrapper (FunSigCtxt name True) poly_ty spec_ty
715 ; return (SpecPrag poly_id wrap inl) }
716
717 tcSpecPrag _ prag = pprPanic "tcSpecPrag" (ppr prag)
718
719 --------------
720 tcSpecWrapper :: UserTypeCtxt -> TcType -> TcType -> TcM HsWrapper
721 -- A simpler variant of tcSubType, used for SPECIALISE pragmas
722 -- See Note [Handling SPECIALISE pragmas], wrinkle 1
723 tcSpecWrapper ctxt poly_ty spec_ty
724 = do { (sk_wrap, inst_wrap)
725 <- tcSkolemise ctxt spec_ty $ \ _ spec_tau ->
726 do { (inst_wrap, tau) <- topInstantiate orig poly_ty
727 ; _ <- unifyType Nothing spec_tau tau
728 -- Deliberately ignore the evidence
729 -- See Note [Handling SPECIALISE pragmas],
730 -- wrinkle (2)
731 ; return inst_wrap }
732 ; return (sk_wrap <.> inst_wrap) }
733 where
734 orig = SpecPragOrigin ctxt
735
736 --------------
737 tcImpPrags :: [LSig GhcRn] -> TcM [LTcSpecPrag]
738 -- SPECIALISE pragmas for imported things
739 tcImpPrags prags
740 = do { this_mod <- getModule
741 ; dflags <- getDynFlags
742 ; if (not_specialising dflags) then
743 return []
744 else do
745 { pss <- mapAndRecoverM (wrapLocM tcImpSpec)
746 [L loc (name,prag)
747 | (L loc prag@(SpecSig _ (L _ name) _ _)) <- prags
748 , not (nameIsLocalOrFrom this_mod name) ]
749 ; return $ concatMap (\(L l ps) -> map (L l) ps) pss } }
750 where
751 -- Ignore SPECIALISE pragmas for imported things
752 -- when we aren't specialising, or when we aren't generating
753 -- code. The latter happens when Haddocking the base library;
754 -- we don't want complaints about lack of INLINABLE pragmas
755 not_specialising dflags
756 | not (gopt Opt_Specialise dflags) = True
757 | otherwise = case hscTarget dflags of
758 HscNothing -> True
759 HscInterpreted -> True
760 _other -> False
761
762 tcImpSpec :: (Name, Sig GhcRn) -> TcM [TcSpecPrag]
763 tcImpSpec (name, prag)
764 = do { id <- tcLookupId name
765 ; unless (isAnyInlinePragma (idInlinePragma id))
766 (addWarnTc NoReason (impSpecErr name))
767 ; tcSpecPrag id prag }
768
769 impSpecErr :: Name -> SDoc
770 impSpecErr name
771 = hang (text "You cannot SPECIALISE" <+> quotes (ppr name))
772 2 (vcat [ text "because its definition has no INLINE/INLINABLE pragma"
773 , parens $ sep
774 [ text "or its defining module" <+> quotes (ppr mod)
775 , text "was compiled without -O"]])
776 where
777 mod = nameModule name