Add nakedSubstTy and use it in TcHsType.tcInferApps
[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 = HsIBRn { hsib_vars = 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 solveEqualities
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 ; ungen_patsyn_ty <- zonkPromoteType $
323 build_patsyn_type [] implicit_tvs univ_tvs req
324 ex_tvs prov body_ty
325
326 -- Kind generalisation
327 ; kvs <- kindGeneralize ungen_patsyn_ty
328
329 -- These are /signatures/ so we zonk to squeeze out any kind
330 -- unification variables. Do this after kindGeneralize which may
331 -- default kind variables to *.
332 ; implicit_tvs <- mapM zonkTcTyCoVarBndr implicit_tvs
333 ; univ_tvs <- mapM zonkTcTyCoVarBndr univ_tvs
334 ; ex_tvs <- mapM zonkTcTyCoVarBndr ex_tvs
335 ; req <- zonkTcTypes req
336 ; prov <- zonkTcTypes prov
337 ; body_ty <- zonkTcType body_ty
338
339 -- Skolems have TcLevels too, though they're used only for debugging.
340 -- If you don't do this, the debugging checks fail in TcPatSyn.
341 -- Test case: patsyn/should_compile/T13441
342 ; tclvl <- getTcLevel
343 ; let env0 = mkEmptyTCvSubst $ mkInScopeSet $ mkVarSet kvs
344 (env1, implicit_tvs') = promoteSkolemsX tclvl env0 implicit_tvs
345 (env2, univ_tvs') = promoteSkolemsX tclvl env1 univ_tvs
346 (env3, ex_tvs') = promoteSkolemsX tclvl env2 ex_tvs
347 req' = substTys env3 req
348 prov' = substTys env3 prov
349 body_ty' = substTy env3 body_ty
350
351 -- Now do validity checking
352 ; checkValidType ctxt $
353 build_patsyn_type kvs implicit_tvs' univ_tvs' req' ex_tvs' prov' body_ty'
354
355 -- arguments become the types of binders. We thus cannot allow
356 -- levity polymorphism here
357 ; let (arg_tys, _) = tcSplitFunTys body_ty'
358 ; mapM_ (checkForLevPoly empty) arg_tys
359
360 ; traceTc "tcTySig }" $
361 vcat [ text "implicit_tvs" <+> ppr_tvs implicit_tvs'
362 , text "kvs" <+> ppr_tvs kvs
363 , text "univ_tvs" <+> ppr_tvs univ_tvs'
364 , text "req" <+> ppr req'
365 , text "ex_tvs" <+> ppr_tvs ex_tvs'
366 , text "prov" <+> ppr prov'
367 , text "body_ty" <+> ppr body_ty' ]
368 ; return (TPSI { patsig_name = name
369 , patsig_implicit_bndrs = mkTyVarBinders Inferred kvs ++
370 mkTyVarBinders Specified implicit_tvs'
371 , patsig_univ_bndrs = univ_tvs'
372 , patsig_req = req'
373 , patsig_ex_bndrs = ex_tvs'
374 , patsig_prov = prov'
375 , patsig_body_ty = body_ty' }) }
376 where
377 ctxt = PatSynCtxt name
378 skol_info = SigTypeSkol ctxt
379
380 build_patsyn_type kvs imp univ req ex prov body
381 = mkInvForAllTys kvs $
382 mkSpecForAllTys (imp ++ univ) $
383 mkFunTys req $
384 mkSpecForAllTys ex $
385 mkFunTys prov $
386 body
387 tcPatSynSig _ (XHsImplicitBndrs _) = panic "tcPatSynSig"
388
389 ppr_tvs :: [TyVar] -> SDoc
390 ppr_tvs tvs = braces (vcat [ ppr tv <+> dcolon <+> ppr (tyVarKind tv)
391 | tv <- tvs])
392
393
394 {- *********************************************************************
395 * *
396 Instantiating user signatures
397 * *
398 ********************************************************************* -}
399
400
401 tcInstSig :: TcIdSigInfo -> TcM TcIdSigInst
402 -- Instantiate a type signature; only used with plan InferGen
403 tcInstSig sig@(CompleteSig { sig_bndr = poly_id, sig_loc = loc })
404 = setSrcSpan loc $ -- Set the binding site of the tyvars
405 do { (tv_prs, theta, tau) <- tcInstType newMetaSigTyVars poly_id
406 -- See Note [Pattern bindings and complete signatures]
407
408 ; return (TISI { sig_inst_sig = sig
409 , sig_inst_skols = tv_prs
410 , sig_inst_wcs = []
411 , sig_inst_wcx = Nothing
412 , sig_inst_theta = theta
413 , sig_inst_tau = tau }) }
414
415 tcInstSig sig@(PartialSig { psig_hs_ty = hs_ty
416 , sig_ctxt = ctxt
417 , sig_loc = loc })
418 = setSrcSpan loc $ -- Set the binding site of the tyvars
419 do { (wcs, wcx, tv_names, tvs, theta, tau) <- tcHsPartialSigType ctxt hs_ty
420
421 -- Clone the quantified tyvars
422 -- Reason: we might have f, g :: forall a. a -> _ -> a
423 -- and we want it to behave exactly as if there were
424 -- two separate signatures. Cloning here seems like
425 -- the easiest way to do so, and is very similar to
426 -- the tcInstType in the CompleteSig case
427 -- See Trac #14643
428 ; let in_scope = mkInScopeSet $ closeOverKinds $ unionVarSets
429 [ mkVarSet (map snd wcs)
430 , maybe emptyVarSet tyCoVarsOfType wcx
431 , mkVarSet tvs
432 , tyCoVarsOfTypes theta
433 , tyCoVarsOfType tau ]
434 -- the in_scope is a bit bigger than nec'y, but too big is always
435 -- safe
436 empty_subst = mkEmptyTCvSubst in_scope
437 ; (subst, tvs') <- instSkolTyCoVarsX mk_sig_tv empty_subst tvs
438 ; let tv_prs = tv_names `zip` tvs'
439
440 ; return (TISI { sig_inst_sig = sig
441 , sig_inst_skols = tv_prs
442 , sig_inst_wcs = wcs
443 , sig_inst_wcx = wcx
444 , sig_inst_theta = substTys subst theta
445 , sig_inst_tau = substTy subst tau
446 }) }
447 where
448 mk_sig_tv old_name kind
449 = do { uniq <- newUnique
450 ; newSigTyVar (setNameUnique old_name uniq) kind }
451 -- Why newSigTyVar? See TcBinds
452 -- Note [Quantified variables in partial type signatures]
453
454
455 {- Note [Pattern bindings and complete signatures]
456 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
457 Consider
458 data T a = MkT a a
459 f :: forall a. a->a
460 g :: forall b. b->b
461 MkT f g = MkT (\x->x) (\y->y)
462 Here we'll infer a type from the pattern of 'T a', but if we feed in
463 the signature types for f and g, we'll end up unifying 'a' and 'b'
464
465 So we instantiate f and g's signature with SigTv skolems
466 (newMetaSigTyVars) that can unify with each other. If too much
467 unification takes place, we'll find out when we do the final
468 impedance-matching check in TcBinds.mkExport
469
470 See Note [Signature skolems] in TcType
471
472 None of this applies to a function binding with a complete
473 signature, which doesn't use tcInstSig. See TcBinds.tcPolyCheck.
474 -}
475
476 {- *********************************************************************
477 * *
478 Pragmas and PragEnv
479 * *
480 ********************************************************************* -}
481
482 type TcPragEnv = NameEnv [LSig GhcRn]
483
484 emptyPragEnv :: TcPragEnv
485 emptyPragEnv = emptyNameEnv
486
487 lookupPragEnv :: TcPragEnv -> Name -> [LSig GhcRn]
488 lookupPragEnv prag_fn n = lookupNameEnv prag_fn n `orElse` []
489
490 extendPragEnv :: TcPragEnv -> (Name, LSig GhcRn) -> TcPragEnv
491 extendPragEnv prag_fn (n, sig) = extendNameEnv_Acc (:) singleton prag_fn n sig
492
493 ---------------
494 mkPragEnv :: [LSig GhcRn] -> LHsBinds GhcRn -> TcPragEnv
495 mkPragEnv sigs binds
496 = foldl extendPragEnv emptyNameEnv prs
497 where
498 prs = mapMaybe get_sig sigs
499
500 get_sig :: LSig GhcRn -> Maybe (Name, LSig GhcRn)
501 get_sig (L l (SpecSig x lnm@(L _ nm) ty inl))
502 = Just (nm, L l $ SpecSig x lnm ty (add_arity nm inl))
503 get_sig (L l (InlineSig x lnm@(L _ nm) inl))
504 = Just (nm, L l $ InlineSig x lnm (add_arity nm inl))
505 get_sig (L l (SCCFunSig x st lnm@(L _ nm) str))
506 = Just (nm, L l $ SCCFunSig x st lnm str)
507 get_sig _ = Nothing
508
509 add_arity n inl_prag -- Adjust inl_sat field to match visible arity of function
510 | Inline <- inl_inline inl_prag
511 -- add arity only for real INLINE pragmas, not INLINABLE
512 = case lookupNameEnv ar_env n of
513 Just ar -> inl_prag { inl_sat = Just ar }
514 Nothing -> WARN( True, text "mkPragEnv no arity" <+> ppr n )
515 -- There really should be a binding for every INLINE pragma
516 inl_prag
517 | otherwise
518 = inl_prag
519
520 -- ar_env maps a local to the arity of its definition
521 ar_env :: NameEnv Arity
522 ar_env = foldrBag lhsBindArity emptyNameEnv binds
523
524 lhsBindArity :: LHsBind GhcRn -> NameEnv Arity -> NameEnv Arity
525 lhsBindArity (L _ (FunBind { fun_id = id, fun_matches = ms })) env
526 = extendNameEnv env (unLoc id) (matchGroupArity ms)
527 lhsBindArity _ env = env -- PatBind/VarBind
528
529
530 -----------------
531 addInlinePrags :: TcId -> [LSig GhcRn] -> TcM TcId
532 addInlinePrags poly_id prags_for_me
533 | inl@(L _ prag) : inls <- inl_prags
534 = do { traceTc "addInlinePrag" (ppr poly_id $$ ppr prag)
535 ; unless (null inls) (warn_multiple_inlines inl inls)
536 ; return (poly_id `setInlinePragma` prag) }
537 | otherwise
538 = return poly_id
539 where
540 inl_prags = [L loc prag | L loc (InlineSig _ _ prag) <- prags_for_me]
541
542 warn_multiple_inlines _ [] = return ()
543
544 warn_multiple_inlines inl1@(L loc prag1) (inl2@(L _ prag2) : inls)
545 | inlinePragmaActivation prag1 == inlinePragmaActivation prag2
546 , noUserInlineSpec (inlinePragmaSpec prag1)
547 = -- Tiresome: inl1 is put there by virtue of being in a hs-boot loop
548 -- and inl2 is a user NOINLINE pragma; we don't want to complain
549 warn_multiple_inlines inl2 inls
550 | otherwise
551 = setSrcSpan loc $
552 addWarnTc NoReason
553 (hang (text "Multiple INLINE pragmas for" <+> ppr poly_id)
554 2 (vcat (text "Ignoring all but the first"
555 : map pp_inl (inl1:inl2:inls))))
556
557 pp_inl (L loc prag) = ppr prag <+> parens (ppr loc)
558
559
560 {- *********************************************************************
561 * *
562 SPECIALISE pragmas
563 * *
564 ************************************************************************
565
566 Note [Handling SPECIALISE pragmas]
567 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
568 The basic idea is this:
569
570 foo :: Num a => a -> b -> a
571 {-# SPECIALISE foo :: Int -> b -> Int #-}
572
573 We check that
574 (forall a b. Num a => a -> b -> a)
575 is more polymorphic than
576 forall b. Int -> b -> Int
577 (for which we could use tcSubType, but see below), generating a HsWrapper
578 to connect the two, something like
579 wrap = /\b. <hole> Int b dNumInt
580 This wrapper is put in the TcSpecPrag, in the ABExport record of
581 the AbsBinds.
582
583
584 f :: (Eq a, Ix b) => a -> b -> Bool
585 {-# SPECIALISE f :: (Ix p, Ix q) => Int -> (p,q) -> Bool #-}
586 f = <poly_rhs>
587
588 From this the typechecker generates
589
590 AbsBinds [ab] [d1,d2] [([ab], f, f_mono, prags)] binds
591
592 SpecPrag (wrap_fn :: forall a b. (Eq a, Ix b) => XXX
593 -> forall p q. (Ix p, Ix q) => XXX[ Int/a, (p,q)/b ])
594
595 From these we generate:
596
597 Rule: forall p, q, (dp:Ix p), (dq:Ix q).
598 f Int (p,q) dInt ($dfInPair dp dq) = f_spec p q dp dq
599
600 Spec bind: f_spec = wrap_fn <poly_rhs>
601
602 Note that
603
604 * The LHS of the rule may mention dictionary *expressions* (eg
605 $dfIxPair dp dq), and that is essential because the dp, dq are
606 needed on the RHS.
607
608 * The RHS of f_spec, <poly_rhs> has a *copy* of 'binds', so that it
609 can fully specialise it.
610
611
612
613 From the TcSpecPrag, in DsBinds we generate a binding for f_spec and a RULE:
614
615 f_spec :: Int -> b -> Int
616 f_spec = wrap<f rhs>
617
618 RULE: forall b (d:Num b). f b d = f_spec b
619
620 The RULE is generated by taking apart the HsWrapper, which is a little
621 delicate, but works.
622
623 Some wrinkles
624
625 1. We don't use full-on tcSubType, because that does co and contra
626 variance and that in turn will generate too complex a LHS for the
627 RULE. So we use a single invocation of skolemise /
628 topInstantiate in tcSpecWrapper. (Actually I think that even
629 the "deeply" stuff may be too much, because it introduces lambdas,
630 though I think it can be made to work without too much trouble.)
631
632 2. We need to take care with type families (Trac #5821). Consider
633 type instance F Int = Bool
634 f :: Num a => a -> F a
635 {-# SPECIALISE foo :: Int -> Bool #-}
636
637 We *could* try to generate an f_spec with precisely the declared type:
638 f_spec :: Int -> Bool
639 f_spec = <f rhs> Int dNumInt |> co
640
641 RULE: forall d. f Int d = f_spec |> sym co
642
643 but the 'co' and 'sym co' are (a) playing no useful role, and (b) are
644 hard to generate. At all costs we must avoid this:
645 RULE: forall d. f Int d |> co = f_spec
646 because the LHS will never match (indeed it's rejected in
647 decomposeRuleLhs).
648
649 So we simply do this:
650 - Generate a constraint to check that the specialised type (after
651 skolemiseation) is equal to the instantiated function type.
652 - But *discard* the evidence (coercion) for that constraint,
653 so that we ultimately generate the simpler code
654 f_spec :: Int -> F Int
655 f_spec = <f rhs> Int dNumInt
656
657 RULE: forall d. f Int d = f_spec
658 You can see this discarding happening in
659
660 3. Note that the HsWrapper can transform *any* function with the right
661 type prefix
662 forall ab. (Eq a, Ix b) => XXX
663 regardless of XXX. It's sort of polymorphic in XXX. This is
664 useful: we use the same wrapper to transform each of the class ops, as
665 well as the dict. That's what goes on in TcInstDcls.mk_meth_spec_prags
666 -}
667
668 tcSpecPrags :: Id -> [LSig GhcRn]
669 -> TcM [LTcSpecPrag]
670 -- Add INLINE and SPECIALSE pragmas
671 -- INLINE prags are added to the (polymorphic) Id directly
672 -- SPECIALISE prags are passed to the desugarer via TcSpecPrags
673 -- Pre-condition: the poly_id is zonked
674 -- Reason: required by tcSubExp
675 tcSpecPrags poly_id prag_sigs
676 = do { traceTc "tcSpecPrags" (ppr poly_id <+> ppr spec_sigs)
677 ; unless (null bad_sigs) warn_discarded_sigs
678 ; pss <- mapAndRecoverM (wrapLocM (tcSpecPrag poly_id)) spec_sigs
679 ; return $ concatMap (\(L l ps) -> map (L l) ps) pss }
680 where
681 spec_sigs = filter isSpecLSig prag_sigs
682 bad_sigs = filter is_bad_sig prag_sigs
683 is_bad_sig s = not (isSpecLSig s || isInlineLSig s || isSCCFunSig s)
684
685 warn_discarded_sigs
686 = addWarnTc NoReason
687 (hang (text "Discarding unexpected pragmas for" <+> ppr poly_id)
688 2 (vcat (map (ppr . getLoc) bad_sigs)))
689
690 --------------
691 tcSpecPrag :: TcId -> Sig GhcRn -> TcM [TcSpecPrag]
692 tcSpecPrag poly_id prag@(SpecSig _ fun_name hs_tys inl)
693 -- See Note [Handling SPECIALISE pragmas]
694 --
695 -- The Name fun_name in the SpecSig may not be the same as that of the poly_id
696 -- Example: SPECIALISE for a class method: the Name in the SpecSig is
697 -- for the selector Id, but the poly_id is something like $cop
698 -- However we want to use fun_name in the error message, since that is
699 -- what the user wrote (Trac #8537)
700 = addErrCtxt (spec_ctxt prag) $
701 do { warnIf (not (isOverloadedTy poly_ty || isInlinePragma inl))
702 (text "SPECIALISE pragma for non-overloaded function"
703 <+> quotes (ppr fun_name))
704 -- Note [SPECIALISE pragmas]
705 ; spec_prags <- mapM tc_one hs_tys
706 ; traceTc "tcSpecPrag" (ppr poly_id $$ nest 2 (vcat (map ppr spec_prags)))
707 ; return spec_prags }
708 where
709 name = idName poly_id
710 poly_ty = idType poly_id
711 spec_ctxt prag = hang (text "In the SPECIALISE pragma") 2 (ppr prag)
712
713 tc_one hs_ty
714 = do { spec_ty <- tcHsSigType (FunSigCtxt name False) hs_ty
715 ; wrap <- tcSpecWrapper (FunSigCtxt name True) poly_ty spec_ty
716 ; return (SpecPrag poly_id wrap inl) }
717
718 tcSpecPrag _ prag = pprPanic "tcSpecPrag" (ppr prag)
719
720 --------------
721 tcSpecWrapper :: UserTypeCtxt -> TcType -> TcType -> TcM HsWrapper
722 -- A simpler variant of tcSubType, used for SPECIALISE pragmas
723 -- See Note [Handling SPECIALISE pragmas], wrinkle 1
724 tcSpecWrapper ctxt poly_ty spec_ty
725 = do { (sk_wrap, inst_wrap)
726 <- tcSkolemise ctxt spec_ty $ \ _ spec_tau ->
727 do { (inst_wrap, tau) <- topInstantiate orig poly_ty
728 ; _ <- unifyType Nothing spec_tau tau
729 -- Deliberately ignore the evidence
730 -- See Note [Handling SPECIALISE pragmas],
731 -- wrinkle (2)
732 ; return inst_wrap }
733 ; return (sk_wrap <.> inst_wrap) }
734 where
735 orig = SpecPragOrigin ctxt
736
737 --------------
738 tcImpPrags :: [LSig GhcRn] -> TcM [LTcSpecPrag]
739 -- SPECIALISE pragmas for imported things
740 tcImpPrags prags
741 = do { this_mod <- getModule
742 ; dflags <- getDynFlags
743 ; if (not_specialising dflags) then
744 return []
745 else do
746 { pss <- mapAndRecoverM (wrapLocM tcImpSpec)
747 [L loc (name,prag)
748 | (L loc prag@(SpecSig _ (L _ name) _ _)) <- prags
749 , not (nameIsLocalOrFrom this_mod name) ]
750 ; return $ concatMap (\(L l ps) -> map (L l) ps) pss } }
751 where
752 -- Ignore SPECIALISE pragmas for imported things
753 -- when we aren't specialising, or when we aren't generating
754 -- code. The latter happens when Haddocking the base library;
755 -- we don't want complaints about lack of INLINABLE pragmas
756 not_specialising dflags
757 | not (gopt Opt_Specialise dflags) = True
758 | otherwise = case hscTarget dflags of
759 HscNothing -> True
760 HscInterpreted -> True
761 _other -> False
762
763 tcImpSpec :: (Name, Sig GhcRn) -> TcM [TcSpecPrag]
764 tcImpSpec (name, prag)
765 = do { id <- tcLookupId name
766 ; unless (isAnyInlinePragma (idInlinePragma id))
767 (addWarnTc NoReason (impSpecErr name))
768 ; tcSpecPrag id prag }
769
770 impSpecErr :: Name -> SDoc
771 impSpecErr name
772 = hang (text "You cannot SPECIALISE" <+> quotes (ppr name))
773 2 (vcat [ text "because its definition has no INLINE/INLINABLE pragma"
774 , parens $ sep
775 [ text "or its defining module" <+> quotes (ppr mod)
776 , text "was compiled without -O"]])
777 where
778 mod = nameModule name