Expose enabled language extensions to TH
[ghc.git] / compiler / typecheck / TcInstDcls.hs
1 {-
2 (c) The University of Glasgow 2006
3 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4
5
6 TcInstDecls: Typechecking instance declarations
7 -}
8
9 {-# LANGUAGE CPP #-}
10
11 module TcInstDcls ( tcInstDecls1, tcInstDecls2 ) where
12
13 #include "HsVersions.h"
14
15 import HsSyn
16 import TcBinds
17 import TcTyClsDecls
18 import TcClassDcl( tcClassDecl2, tcATDefault,
19 HsSigFun, lookupHsSig, mkHsSigFun,
20 findMethodBind, instantiateMethod )
21 import TcPat ( addInlinePrags, lookupPragEnv, emptyPragEnv )
22 import TcRnMonad
23 import TcValidity
24 import TcHsSyn ( zonkTcTypeToTypes, emptyZonkEnv )
25 import TcMType
26 import TcType
27 import BuildTyCl
28 import Inst
29 import InstEnv
30 import FamInst
31 import FamInstEnv
32 import TcDeriv
33 import TcEnv
34 import TcHsType
35 import TcUnify
36 import MkCore ( nO_METHOD_BINDING_ERROR_ID )
37 import Type
38 import TcEvidence
39 import TyCon
40 import Coercion ( emptyCvSubstEnv )
41 import CoAxiom
42 import DataCon
43 import Class
44 import Var
45 import VarEnv
46 import VarSet
47 import PrelNames ( typeableClassName, genericClassNames )
48 import Bag
49 import BasicTypes
50 import DynFlags
51 import ErrUtils
52 import FastString
53 import HscTypes ( isHsBootOrSig )
54 import Id
55 import MkId
56 import Name
57 import NameSet
58 import Outputable
59 import SrcLoc
60 import Util
61 import BooleanFormula ( isUnsatisfied, pprBooleanFormulaNice )
62 import qualified GHC.LanguageExtensions as LangExt
63
64 import Control.Monad
65 import Maybes
66 import Data.List ( partition )
67
68
69
70 {-
71 Typechecking instance declarations is done in two passes. The first
72 pass, made by @tcInstDecls1@, collects information to be used in the
73 second pass.
74
75 This pre-processed info includes the as-yet-unprocessed bindings
76 inside the instance declaration. These are type-checked in the second
77 pass, when the class-instance envs and GVE contain all the info from
78 all the instance and value decls. Indeed that's the reason we need
79 two passes over the instance decls.
80
81
82 Note [How instance declarations are translated]
83 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
84 Here is how we translate instance declarations into Core
85
86 Running example:
87 class C a where
88 op1, op2 :: Ix b => a -> b -> b
89 op2 = <dm-rhs>
90
91 instance C a => C [a]
92 {-# INLINE [2] op1 #-}
93 op1 = <rhs>
94 ===>
95 -- Method selectors
96 op1,op2 :: forall a. C a => forall b. Ix b => a -> b -> b
97 op1 = ...
98 op2 = ...
99
100 -- Default methods get the 'self' dictionary as argument
101 -- so they can call other methods at the same type
102 -- Default methods get the same type as their method selector
103 $dmop2 :: forall a. C a => forall b. Ix b => a -> b -> b
104 $dmop2 = /\a. \(d:C a). /\b. \(d2: Ix b). <dm-rhs>
105 -- NB: type variables 'a' and 'b' are *both* in scope in <dm-rhs>
106 -- Note [Tricky type variable scoping]
107
108 -- A top-level definition for each instance method
109 -- Here op1_i, op2_i are the "instance method Ids"
110 -- The INLINE pragma comes from the user pragma
111 {-# INLINE [2] op1_i #-} -- From the instance decl bindings
112 op1_i, op2_i :: forall a. C a => forall b. Ix b => [a] -> b -> b
113 op1_i = /\a. \(d:C a).
114 let this :: C [a]
115 this = df_i a d
116 -- Note [Subtle interaction of recursion and overlap]
117
118 local_op1 :: forall b. Ix b => [a] -> b -> b
119 local_op1 = <rhs>
120 -- Source code; run the type checker on this
121 -- NB: Type variable 'a' (but not 'b') is in scope in <rhs>
122 -- Note [Tricky type variable scoping]
123
124 in local_op1 a d
125
126 op2_i = /\a \d:C a. $dmop2 [a] (df_i a d)
127
128 -- The dictionary function itself
129 {-# NOINLINE CONLIKE df_i #-} -- Never inline dictionary functions
130 df_i :: forall a. C a -> C [a]
131 df_i = /\a. \d:C a. MkC (op1_i a d) (op2_i a d)
132 -- But see Note [Default methods in instances]
133 -- We can't apply the type checker to the default-method call
134
135 -- Use a RULE to short-circuit applications of the class ops
136 {-# RULE "op1@C[a]" forall a, d:C a.
137 op1 [a] (df_i d) = op1_i a d #-}
138
139 Note [Instances and loop breakers]
140 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
141 * Note that df_i may be mutually recursive with both op1_i and op2_i.
142 It's crucial that df_i is not chosen as the loop breaker, even
143 though op1_i has a (user-specified) INLINE pragma.
144
145 * Instead the idea is to inline df_i into op1_i, which may then select
146 methods from the MkC record, and thereby break the recursion with
147 df_i, leaving a *self*-recurisve op1_i. (If op1_i doesn't call op at
148 the same type, it won't mention df_i, so there won't be recursion in
149 the first place.)
150
151 * If op1_i is marked INLINE by the user there's a danger that we won't
152 inline df_i in it, and that in turn means that (since it'll be a
153 loop-breaker because df_i isn't), op1_i will ironically never be
154 inlined. But this is OK: the recursion breaking happens by way of
155 a RULE (the magic ClassOp rule above), and RULES work inside InlineRule
156 unfoldings. See Note [RULEs enabled in SimplGently] in SimplUtils
157
158 Note [ClassOp/DFun selection]
159 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
160 One thing we see a lot is stuff like
161 op2 (df d1 d2)
162 where 'op2' is a ClassOp and 'df' is DFun. Now, we could inline *both*
163 'op2' and 'df' to get
164 case (MkD ($cop1 d1 d2) ($cop2 d1 d2) ... of
165 MkD _ op2 _ _ _ -> op2
166 And that will reduce to ($cop2 d1 d2) which is what we wanted.
167
168 But it's tricky to make this work in practice, because it requires us to
169 inline both 'op2' and 'df'. But neither is keen to inline without having
170 seen the other's result; and it's very easy to get code bloat (from the
171 big intermediate) if you inline a bit too much.
172
173 Instead we use a cunning trick.
174 * We arrange that 'df' and 'op2' NEVER inline.
175
176 * We arrange that 'df' is ALWAYS defined in the sylised form
177 df d1 d2 = MkD ($cop1 d1 d2) ($cop2 d1 d2) ...
178
179 * We give 'df' a magical unfolding (DFunUnfolding [$cop1, $cop2, ..])
180 that lists its methods.
181
182 * We make CoreUnfold.exprIsConApp_maybe spot a DFunUnfolding and return
183 a suitable constructor application -- inlining df "on the fly" as it
184 were.
185
186 * ClassOp rules: We give the ClassOp 'op2' a BuiltinRule that
187 extracts the right piece iff its argument satisfies
188 exprIsConApp_maybe. This is done in MkId mkDictSelId
189
190 * We make 'df' CONLIKE, so that shared uses still match; eg
191 let d = df d1 d2
192 in ...(op2 d)...(op1 d)...
193
194 Note [Single-method classes]
195 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
196 If the class has just one method (or, more accurately, just one element
197 of {superclasses + methods}), then we use a different strategy.
198
199 class C a where op :: a -> a
200 instance C a => C [a] where op = <blah>
201
202 We translate the class decl into a newtype, which just gives a
203 top-level axiom. The "constructor" MkC expands to a cast, as does the
204 class-op selector.
205
206 axiom Co:C a :: C a ~ (a->a)
207
208 op :: forall a. C a -> (a -> a)
209 op a d = d |> (Co:C a)
210
211 MkC :: forall a. (a->a) -> C a
212 MkC = /\a.\op. op |> (sym Co:C a)
213
214 The clever RULE stuff doesn't work now, because ($df a d) isn't
215 a constructor application, so exprIsConApp_maybe won't return
216 Just <blah>.
217
218 Instead, we simply rely on the fact that casts are cheap:
219
220 $df :: forall a. C a => C [a]
221 {-# INLINE df #-} -- NB: INLINE this
222 $df = /\a. \d. MkC [a] ($cop_list a d)
223 = $cop_list |> forall a. C a -> (sym (Co:C [a]))
224
225 $cop_list :: forall a. C a => [a] -> [a]
226 $cop_list = <blah>
227
228 So if we see
229 (op ($df a d))
230 we'll inline 'op' and '$df', since both are simply casts, and
231 good things happen.
232
233 Why do we use this different strategy? Because otherwise we
234 end up with non-inlined dictionaries that look like
235 $df = $cop |> blah
236 which adds an extra indirection to every use, which seems stupid. See
237 Trac #4138 for an example (although the regression reported there
238 wasn't due to the indirection).
239
240 There is an awkward wrinkle though: we want to be very
241 careful when we have
242 instance C a => C [a] where
243 {-# INLINE op #-}
244 op = ...
245 then we'll get an INLINE pragma on $cop_list but it's important that
246 $cop_list only inlines when it's applied to *two* arguments (the
247 dictionary and the list argument). So we must not eta-expand $df
248 above. We ensure that this doesn't happen by putting an INLINE
249 pragma on the dfun itself; after all, it ends up being just a cast.
250
251 There is one more dark corner to the INLINE story, even more deeply
252 buried. Consider this (Trac #3772):
253
254 class DeepSeq a => C a where
255 gen :: Int -> a
256
257 instance C a => C [a] where
258 gen n = ...
259
260 class DeepSeq a where
261 deepSeq :: a -> b -> b
262
263 instance DeepSeq a => DeepSeq [a] where
264 {-# INLINE deepSeq #-}
265 deepSeq xs b = foldr deepSeq b xs
266
267 That gives rise to these defns:
268
269 $cdeepSeq :: DeepSeq a -> [a] -> b -> b
270 -- User INLINE( 3 args )!
271 $cdeepSeq a (d:DS a) b (x:[a]) (y:b) = ...
272
273 $fDeepSeq[] :: DeepSeq a -> DeepSeq [a]
274 -- DFun (with auto INLINE pragma)
275 $fDeepSeq[] a d = $cdeepSeq a d |> blah
276
277 $cp1 a d :: C a => DeepSep [a]
278 -- We don't want to eta-expand this, lest
279 -- $cdeepSeq gets inlined in it!
280 $cp1 a d = $fDeepSep[] a (scsel a d)
281
282 $fC[] :: C a => C [a]
283 -- Ordinary DFun
284 $fC[] a d = MkC ($cp1 a d) ($cgen a d)
285
286 Here $cp1 is the code that generates the superclass for C [a]. The
287 issue is this: we must not eta-expand $cp1 either, or else $fDeepSeq[]
288 and then $cdeepSeq will inline there, which is definitely wrong. Like
289 on the dfun, we solve this by adding an INLINE pragma to $cp1.
290
291 Note [Subtle interaction of recursion and overlap]
292 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
293 Consider this
294 class C a where { op1,op2 :: a -> a }
295 instance C a => C [a] where
296 op1 x = op2 x ++ op2 x
297 op2 x = ...
298 instance C [Int] where
299 ...
300
301 When type-checking the C [a] instance, we need a C [a] dictionary (for
302 the call of op2). If we look up in the instance environment, we find
303 an overlap. And in *general* the right thing is to complain (see Note
304 [Overlapping instances] in InstEnv). But in *this* case it's wrong to
305 complain, because we just want to delegate to the op2 of this same
306 instance.
307
308 Why is this justified? Because we generate a (C [a]) constraint in
309 a context in which 'a' cannot be instantiated to anything that matches
310 other overlapping instances, or else we would not be executing this
311 version of op1 in the first place.
312
313 It might even be a bit disguised:
314
315 nullFail :: C [a] => [a] -> [a]
316 nullFail x = op2 x ++ op2 x
317
318 instance C a => C [a] where
319 op1 x = nullFail x
320
321 Precisely this is used in package 'regex-base', module Context.hs.
322 See the overlapping instances for RegexContext, and the fact that they
323 call 'nullFail' just like the example above. The DoCon package also
324 does the same thing; it shows up in module Fraction.hs.
325
326 Conclusion: when typechecking the methods in a C [a] instance, we want to
327 treat the 'a' as an *existential* type variable, in the sense described
328 by Note [Binding when looking up instances]. That is why isOverlappableTyVar
329 responds True to an InstSkol, which is the kind of skolem we use in
330 tcInstDecl2.
331
332
333 Note [Tricky type variable scoping]
334 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
335 In our example
336 class C a where
337 op1, op2 :: Ix b => a -> b -> b
338 op2 = <dm-rhs>
339
340 instance C a => C [a]
341 {-# INLINE [2] op1 #-}
342 op1 = <rhs>
343
344 note that 'a' and 'b' are *both* in scope in <dm-rhs>, but only 'a' is
345 in scope in <rhs>. In particular, we must make sure that 'b' is in
346 scope when typechecking <dm-rhs>. This is achieved by subFunTys,
347 which brings appropriate tyvars into scope. This happens for both
348 <dm-rhs> and for <rhs>, but that doesn't matter: the *renamer* will have
349 complained if 'b' is mentioned in <rhs>.
350
351
352
353 ************************************************************************
354 * *
355 \subsection{Extracting instance decls}
356 * *
357 ************************************************************************
358
359 Gather up the instance declarations from their various sources
360 -}
361
362 tcInstDecls1 -- Deal with both source-code and imported instance decls
363 :: [TyClGroup Name] -- For deriving stuff
364 -> [LInstDecl Name] -- Source code instance decls
365 -> [LDerivDecl Name] -- Source code stand-alone deriving decls
366 -> TcM (TcGblEnv, -- The full inst env
367 [InstInfo Name], -- Source-code instance decls to process;
368 -- contains all dfuns for this module
369 HsValBinds Name) -- Supporting bindings for derived instances
370
371 tcInstDecls1 tycl_decls inst_decls deriv_decls
372 = checkNoErrs $
373 do { -- Stop if addInstInfos etc discovers any errors
374 -- (they recover, so that we get more than one error each
375 -- round)
376
377 -- Do class and family instance declarations
378 ; stuff <- mapAndRecoverM tcLocalInstDecl inst_decls
379 ; let (local_infos_s, fam_insts_s, datafam_deriv_infos) = unzip3 stuff
380 fam_insts = concat fam_insts_s
381 local_infos' = concat local_infos_s
382 -- Handwritten instances of the poly-kinded Typeable class are
383 -- forbidden, so we handle those separately
384 (typeable_instances, local_infos)
385 = partition bad_typeable_instance local_infos'
386
387 ; addClsInsts local_infos $
388 addFamInsts fam_insts $
389 do { -- Compute instances from "deriving" clauses;
390 -- This stuff computes a context for the derived instance
391 -- decl, so it needs to know about all the instances possible
392 -- NB: class instance declarations can contain derivings as
393 -- part of associated data type declarations
394 failIfErrsM -- If the addInsts stuff gave any errors, don't
395 -- try the deriving stuff, because that may give
396 -- more errors still
397
398 ; traceTc "tcDeriving" Outputable.empty
399 ; th_stage <- getStage -- See Note [Deriving inside TH brackets ]
400 ; (gbl_env, deriv_inst_info, deriv_binds)
401 <- if isBrackStage th_stage
402 then do { gbl_env <- getGblEnv
403 ; return (gbl_env, emptyBag, emptyValBindsOut) }
404 else do { data_deriv_infos <- mkDerivInfos tycl_decls
405 ; let deriv_infos = concat datafam_deriv_infos ++
406 data_deriv_infos
407 ; tcDeriving deriv_infos deriv_decls }
408
409 -- Fail if there are any handwritten instance of poly-kinded Typeable
410 ; mapM_ typeable_err typeable_instances
411
412 -- Check that if the module is compiled with -XSafe, there are no
413 -- hand written instances of old Typeable as then unsafe casts could be
414 -- performed. Derived instances are OK.
415 ; dflags <- getDynFlags
416 ; when (safeLanguageOn dflags) $ forM_ local_infos $ \x -> case x of
417 _ | genInstCheck x -> addErrAt (getSrcSpan $ iSpec x) (genInstErr x)
418 _ -> return ()
419
420 -- As above but for Safe Inference mode.
421 ; when (safeInferOn dflags) $ forM_ local_infos $ \x -> case x of
422 _ | genInstCheck x -> recordUnsafeInfer emptyBag
423 _ -> return ()
424
425 ; return ( gbl_env
426 , bagToList deriv_inst_info ++ local_infos
427 , deriv_binds )
428 }}
429 where
430 -- Separate the Typeable instances from the rest
431 bad_typeable_instance i
432 = typeableClassName == is_cls_nm (iSpec i)
433
434 -- Check for hand-written Generic instances (disallowed in Safe Haskell)
435 genInstCheck ty = is_cls_nm (iSpec ty) `elem` genericClassNames
436 genInstErr i = hang (ptext (sLit $ "Generic instances can only be "
437 ++ "derived in Safe Haskell.") $+$
438 ptext (sLit "Replace the following instance:"))
439 2 (pprInstanceHdr (iSpec i))
440
441 -- Report an error or a warning for a Typeable instances.
442 -- If we are working on an .hs-boot file, we just report a warning,
443 -- and ignore the instance. We do this, to give users a chance to fix
444 -- their code.
445 typeable_err i =
446 setSrcSpan (getSrcSpan (iSpec i)) $
447 do env <- getGblEnv
448 if isHsBootOrSig (tcg_src env)
449 then
450 do warn <- woptM Opt_WarnDerivingTypeable
451 when warn $ addWarnTc $ vcat
452 [ ppTypeable <+> ptext (sLit "instances in .hs-boot files are ignored")
453 , ptext (sLit "This warning will become an error in future versions of the compiler")
454 ]
455 else addErrTc $ ptext (sLit "Class") <+> ppTypeable
456 <+> ptext (sLit "does not support user-specified instances")
457 ppTypeable :: SDoc
458 ppTypeable = quotes (ppr typeableClassName)
459
460 addClsInsts :: [InstInfo Name] -> TcM a -> TcM a
461 addClsInsts infos thing_inside
462 = tcExtendLocalInstEnv (map iSpec infos) thing_inside
463
464 addFamInsts :: [FamInst] -> TcM a -> TcM a
465 -- Extend (a) the family instance envt
466 -- (b) the type envt with stuff from data type decls
467 addFamInsts fam_insts thing_inside
468 = tcExtendLocalFamInstEnv fam_insts $
469 tcExtendGlobalEnv axioms $
470 tcExtendTyConEnv data_rep_tycons $
471 do { traceTc "addFamInsts" (pprFamInsts fam_insts)
472 ; tcg_env <- tcAddImplicits data_rep_tycons
473 -- Does not add its axiom; that comes from
474 -- adding the 'axioms' above
475 ; setGblEnv tcg_env thing_inside }
476 where
477 axioms = map (ACoAxiom . toBranchedAxiom . famInstAxiom) fam_insts
478 data_rep_tycons = famInstsRepTyCons fam_insts
479 -- The representation tycons for 'data instances' declarations
480
481 {-
482 Note [Deriving inside TH brackets]
483 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
484 Given a declaration bracket
485 [d| data T = A | B deriving( Show ) |]
486
487 there is really no point in generating the derived code for deriving(
488 Show) and then type-checking it. This will happen at the call site
489 anyway, and the type check should never fail! Moreover (Trac #6005)
490 the scoping of the generated code inside the bracket does not seem to
491 work out.
492
493 The easy solution is simply not to generate the derived instances at
494 all. (A less brutal solution would be to generate them with no
495 bindings.) This will become moot when we shift to the new TH plan, so
496 the brutal solution will do.
497 -}
498
499 tcLocalInstDecl :: LInstDecl Name
500 -> TcM ([InstInfo Name], [FamInst], [DerivInfo])
501 -- A source-file instance declaration
502 -- Type-check all the stuff before the "where"
503 --
504 -- We check for respectable instance type, and context
505 tcLocalInstDecl (L loc (TyFamInstD { tfid_inst = decl }))
506 = do { fam_inst <- tcTyFamInstDecl Nothing (L loc decl)
507 ; return ([], [fam_inst], []) }
508
509 tcLocalInstDecl (L loc (DataFamInstD { dfid_inst = decl }))
510 = do { (fam_inst, m_deriv_info) <- tcDataFamInstDecl Nothing (L loc decl)
511 ; return ([], [fam_inst], maybeToList m_deriv_info) }
512
513 tcLocalInstDecl (L loc (ClsInstD { cid_inst = decl }))
514 = do { (insts, fam_insts, deriv_infos) <- tcClsInstDecl (L loc decl)
515 ; return (insts, fam_insts, deriv_infos) }
516
517 tcClsInstDecl :: LClsInstDecl Name
518 -> TcM ([InstInfo Name], [FamInst], [DerivInfo])
519 -- the returned DerivInfos are for any associated data families
520 tcClsInstDecl (L loc (ClsInstDecl { cid_poly_ty = poly_ty, cid_binds = binds
521 , cid_sigs = uprags, cid_tyfam_insts = ats
522 , cid_overlap_mode = overlap_mode
523 , cid_datafam_insts = adts }))
524 = setSrcSpan loc $
525 addErrCtxt (instDeclCtxt1 poly_ty) $
526 do { is_boot <- tcIsHsBootOrSig
527 ; checkTc (not is_boot || (isEmptyLHsBinds binds && null uprags))
528 badBootDeclErr
529
530 ; (tyvars, theta, clas, inst_tys) <- tcHsClsInstType InstDeclCtxt poly_ty
531 ; let mini_env = mkVarEnv (classTyVars clas `zip` inst_tys)
532 mini_subst = mkTCvSubst (mkInScopeSet (mkVarSet tyvars))
533 (mini_env, emptyCvSubstEnv)
534 mb_info = Just (clas, mini_env)
535
536 -- Next, process any associated types.
537 ; traceTc "tcLocalInstDecl" (ppr poly_ty)
538 ; tyfam_insts0 <- tcExtendTyVarEnv tyvars $
539 mapAndRecoverM (tcTyFamInstDecl mb_info) ats
540 ; datafam_stuff <- tcExtendTyVarEnv tyvars $
541 mapAndRecoverM (tcDataFamInstDecl mb_info) adts
542 ; let (datafam_insts, m_deriv_infos) = unzip datafam_stuff
543 deriv_infos = catMaybes m_deriv_infos
544
545 -- Check for missing associated types and build them
546 -- from their defaults (if available)
547 ; let defined_ats = mkNameSet (map (tyFamInstDeclName . unLoc) ats)
548 `unionNameSet`
549 mkNameSet (map (unLoc . dfid_tycon . unLoc) adts)
550 ; tyfam_insts1 <- mapM (tcATDefault True loc mini_subst defined_ats)
551 (classATItems clas)
552
553 -- Finally, construct the Core representation of the instance.
554 -- (This no longer includes the associated types.)
555 ; dfun_name <- newDFunName clas inst_tys (getLoc (hsSigType poly_ty))
556 -- Dfun location is that of instance *header*
557
558 ; ispec <- newClsInst (fmap unLoc overlap_mode) dfun_name tyvars theta
559 clas inst_tys
560 ; let inst_info = InstInfo { iSpec = ispec
561 , iBinds = InstBindings
562 { ib_binds = binds
563 , ib_tyvars = map Var.varName tyvars -- Scope over bindings
564 , ib_pragmas = uprags
565 , ib_extensions = []
566 , ib_derived = False } }
567
568 ; return ( [inst_info], tyfam_insts0 ++ concat tyfam_insts1 ++ datafam_insts
569 , deriv_infos ) }
570
571
572 {-
573 ************************************************************************
574 * *
575 Type checking family instances
576 * *
577 ************************************************************************
578
579 Family instances are somewhat of a hybrid. They are processed together with
580 class instance heads, but can contain data constructors and hence they share a
581 lot of kinding and type checking code with ordinary algebraic data types (and
582 GADTs).
583 -}
584
585 tcFamInstDeclCombined :: Maybe ClsInfo
586 -> Located Name -> TcM TyCon
587 tcFamInstDeclCombined mb_clsinfo fam_tc_lname
588 = do { -- Type family instances require -XTypeFamilies
589 -- and can't (currently) be in an hs-boot file
590 ; traceTc "tcFamInstDecl" (ppr fam_tc_lname)
591 ; type_families <- xoptM LangExt.TypeFamilies
592 ; is_boot <- tcIsHsBootOrSig -- Are we compiling an hs-boot file?
593 ; checkTc type_families $ badFamInstDecl fam_tc_lname
594 ; checkTc (not is_boot) $ badBootFamInstDeclErr
595
596 -- Look up the family TyCon and check for validity including
597 -- check that toplevel type instances are not for associated types.
598 ; fam_tc <- tcLookupLocatedTyCon fam_tc_lname
599 ; when (isNothing mb_clsinfo && -- Not in a class decl
600 isTyConAssoc fam_tc) -- but an associated type
601 (addErr $ assocInClassErr fam_tc_lname)
602
603 ; return fam_tc }
604
605 tcTyFamInstDecl :: Maybe ClsInfo
606 -> LTyFamInstDecl Name -> TcM FamInst
607 -- "type instance"
608 tcTyFamInstDecl mb_clsinfo (L loc decl@(TyFamInstDecl { tfid_eqn = eqn }))
609 = setSrcSpan loc $
610 tcAddTyFamInstCtxt decl $
611 do { let fam_lname = tfe_tycon (unLoc eqn)
612 ; fam_tc <- tcFamInstDeclCombined mb_clsinfo fam_lname
613
614 -- (0) Check it's an open type family
615 ; checkTc (isFamilyTyCon fam_tc) (notFamily fam_tc)
616 ; checkTc (isTypeFamilyTyCon fam_tc) (wrongKindOfFamily fam_tc)
617 ; checkTc (isOpenTypeFamilyTyCon fam_tc) (notOpenFamily fam_tc)
618
619 -- (1) do the work of verifying the synonym group
620 ; co_ax_branch <- tcTyFamInstEqn (famTyConShape fam_tc) mb_clsinfo eqn
621
622 -- (2) check for validity
623 ; checkValidCoAxBranch mb_clsinfo fam_tc co_ax_branch
624
625 -- (3) construct coercion axiom
626 ; rep_tc_name <- newFamInstAxiomName loc (unLoc fam_lname)
627 [co_ax_branch]
628 ; let axiom = mkUnbranchedCoAxiom rep_tc_name fam_tc co_ax_branch
629 ; newFamInst SynFamilyInst axiom }
630
631 tcDataFamInstDecl :: Maybe ClsInfo
632 -> LDataFamInstDecl Name -> TcM (FamInst, Maybe DerivInfo)
633 -- "newtype instance" and "data instance"
634 tcDataFamInstDecl mb_clsinfo
635 (L loc decl@(DataFamInstDecl
636 { dfid_pats = pats
637 , dfid_tycon = fam_tc_name
638 , dfid_defn = defn@HsDataDefn { dd_ND = new_or_data, dd_cType = cType
639 , dd_ctxt = ctxt, dd_cons = cons
640 , dd_derivs = derivs } }))
641 = setSrcSpan loc $
642 tcAddDataFamInstCtxt decl $
643 do { fam_tc <- tcFamInstDeclCombined mb_clsinfo fam_tc_name
644
645 -- Check that the family declaration is for the right kind
646 ; checkTc (isFamilyTyCon fam_tc) (notFamily fam_tc)
647 ; checkTc (isDataFamilyTyCon fam_tc) (wrongKindOfFamily fam_tc)
648
649 -- Kind check type patterns
650 ; tcFamTyPats (famTyConShape fam_tc) mb_clsinfo pats
651 (kcDataDefn (unLoc fam_tc_name) pats defn) $
652 \tvs' pats' res_kind -> do
653 {
654 -- Check that left-hand side contains no type family applications
655 -- (vanilla synonyms are fine, though, and we checked for
656 -- foralls earlier)
657 ; checkValidFamPats fam_tc tvs' [] pats'
658 -- Check that type patterns match class instance head, if any
659 ; checkConsistentFamInst mb_clsinfo fam_tc tvs' pats'
660
661 -- Result kind must be '*' (otherwise, we have too few patterns)
662 ; checkTc (isLiftedTypeKind res_kind) $ tooFewParmsErr (tyConArity fam_tc)
663
664 ; stupid_theta <- solveEqualities $ tcHsContext ctxt
665 ; stupid_theta <- zonkTcTypeToTypes emptyZonkEnv stupid_theta
666 ; gadt_syntax <- dataDeclChecks (tyConName fam_tc) new_or_data stupid_theta cons
667
668 -- Construct representation tycon
669 ; rep_tc_name <- newFamInstTyConName fam_tc_name pats'
670 ; axiom_name <- newImplicitBinder rep_tc_name mkInstTyCoOcc
671 ; let (eta_pats, etad_tvs) = eta_reduce pats'
672 eta_tvs = filterOut (`elem` etad_tvs) tvs'
673 full_tvs = eta_tvs ++ etad_tvs
674 -- Put the eta-removed tyvars at the end
675 -- Remember, tvs' is in arbitrary order (except kind vars are
676 -- first, so there is no reason to suppose that the etad_tvs
677 -- (obtained from the pats) are at the end (Trac #11148)
678 orig_res_ty = mkTyConApp fam_tc pats'
679
680 ; (rep_tc, fam_inst) <- fixM $ \ ~(rec_rep_tc, _) ->
681 do { data_cons <- tcConDecls new_or_data
682 rec_rep_tc
683 (full_tvs, orig_res_ty) cons
684 ; tc_rhs <- case new_or_data of
685 DataType -> return (mkDataTyConRhs data_cons)
686 NewType -> ASSERT( not (null data_cons) )
687 mkNewTyConRhs rep_tc_name rec_rep_tc (head data_cons)
688 -- freshen tyvars
689 ; let axiom = mkSingleCoAxiom Representational
690 axiom_name eta_tvs [] fam_tc eta_pats
691 (mkTyConApp rep_tc (mkTyVarTys eta_tvs))
692 parent = DataFamInstTyCon axiom fam_tc pats'
693 kind = mkPiTypesPreferFunTy tvs' liftedTypeKind
694
695
696 -- NB: Use the full_tvs from the pats. See bullet toward
697 -- the end of Note [Data type families] in TyCon
698 rep_tc = mkAlgTyCon rep_tc_name kind full_tvs
699 (map (const Nominal) full_tvs)
700 (fmap unLoc cType) stupid_theta
701 tc_rhs parent
702 Recursive gadt_syntax
703 -- We always assume that indexed types are recursive. Why?
704 -- (1) Due to their open nature, we can never be sure that a
705 -- further instance might not introduce a new recursive
706 -- dependency. (2) They are always valid loop breakers as
707 -- they involve a coercion.
708 ; fam_inst <- newFamInst (DataFamilyInst rep_tc) axiom
709 ; return (rep_tc, fam_inst) }
710
711 -- Remember to check validity; no recursion to worry about here
712 ; checkValidTyCon rep_tc
713
714 ; let m_deriv_info = case derivs of
715 Nothing -> Nothing
716 Just (L _ preds) ->
717 Just $ DerivInfo { di_rep_tc = rep_tc
718 , di_preds = preds
719 , di_ctxt = tcMkDataFamInstCtxt decl }
720
721 ; return (fam_inst, m_deriv_info) } }
722 where
723 eta_reduce :: [Type] -> ([Type], [TyVar])
724 -- See Note [Eta reduction for data families] in FamInstEnv
725 -- Splits the incoming patterns into two: the [TyVar]
726 -- are the patterns that can be eta-reduced away.
727 -- e.g. T [a] Int a d c ==> (T [a] Int a, [d,c])
728 --
729 -- NB: quadratic algorithm, but types are small here
730 eta_reduce pats
731 = go (reverse pats) []
732 go (pat:pats) etad_tvs
733 | Just tv <- getTyVar_maybe pat
734 , not (tv `elemVarSet` tyCoVarsOfTypes pats)
735 = go pats (tv : etad_tvs)
736 go pats etad_tvs = (reverse pats, etad_tvs)
737
738
739 {- *********************************************************************
740 * *
741 Type-checking instance declarations, pass 2
742 * *
743 ********************************************************************* -}
744
745 tcInstDecls2 :: [LTyClDecl Name] -> [InstInfo Name]
746 -> TcM (LHsBinds Id)
747 -- (a) From each class declaration,
748 -- generate any default-method bindings
749 -- (b) From each instance decl
750 -- generate the dfun binding
751
752 tcInstDecls2 tycl_decls inst_decls
753 = do { -- (a) Default methods from class decls
754 let class_decls = filter (isClassDecl . unLoc) tycl_decls
755 ; dm_binds_s <- mapM tcClassDecl2 class_decls
756 ; let dm_binds = unionManyBags dm_binds_s
757
758 -- (b) instance declarations
759 ; let dm_ids = collectHsBindsBinders dm_binds
760 -- Add the default method Ids (again)
761 -- See Note [Default methods and instances]
762 ; inst_binds_s <- tcExtendLetEnv TopLevel dm_ids $
763 mapM tcInstDecl2 inst_decls
764
765 -- Done
766 ; return (dm_binds `unionBags` unionManyBags inst_binds_s) }
767
768 {-
769 See Note [Default methods and instances]
770 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
771 The default method Ids are already in the type environment (see Note
772 [Default method Ids and Template Haskell] in TcTyClsDcls), BUT they
773 don't have their InlinePragmas yet. Usually that would not matter,
774 because the simplifier propagates information from binding site to
775 use. But, unusually, when compiling instance decls we *copy* the
776 INLINE pragma from the default method to the method for that
777 particular operation (see Note [INLINE and default methods] below).
778
779 So right here in tcInstDecls2 we must re-extend the type envt with
780 the default method Ids replete with their INLINE pragmas. Urk.
781 -}
782
783 tcInstDecl2 :: InstInfo Name -> TcM (LHsBinds Id)
784 -- Returns a binding for the dfun
785 tcInstDecl2 (InstInfo { iSpec = ispec, iBinds = ibinds })
786 = recoverM (return emptyLHsBinds) $
787 setSrcSpan loc $
788 addErrCtxt (instDeclCtxt2 (idType dfun_id)) $
789 do { -- Instantiate the instance decl with skolem constants
790 ; (inst_tyvars, dfun_theta, inst_head) <- tcSkolDFunType (idType dfun_id)
791 ; dfun_ev_vars <- newEvVars dfun_theta
792 -- We instantiate the dfun_id with superSkolems.
793 -- See Note [Subtle interaction of recursion and overlap]
794 -- and Note [Binding when looking up instances]
795
796 ; let (clas, inst_tys) = tcSplitDFunHead inst_head
797 (class_tyvars, sc_theta, _, op_items) = classBigSig clas
798 sc_theta' = substTheta (zipOpenTCvSubst class_tyvars inst_tys) sc_theta
799
800 ; traceTc "tcInstDecl2" (vcat [ppr inst_tyvars, ppr inst_tys, ppr dfun_theta, ppr sc_theta'])
801
802 -- Deal with 'SPECIALISE instance' pragmas
803 -- See Note [SPECIALISE instance pragmas]
804 ; spec_inst_info@(spec_inst_prags,_) <- tcSpecInstPrags dfun_id ibinds
805
806 -- Typecheck superclasses and methods
807 -- See Note [Typechecking plan for instance declarations]
808 ; dfun_ev_binds_var <- newTcEvBinds
809 ; let dfun_ev_binds = TcEvBinds dfun_ev_binds_var
810 ; ((sc_meth_ids, sc_meth_binds, sc_meth_implics), tclvl)
811 <- pushTcLevelM $
812 do { fam_envs <- tcGetFamInstEnvs
813 ; (sc_ids, sc_binds, sc_implics)
814 <- tcSuperClasses dfun_id clas inst_tyvars dfun_ev_vars
815 inst_tys dfun_ev_binds fam_envs
816 sc_theta'
817
818 -- Typecheck the methods
819 ; (meth_ids, meth_binds, meth_implics)
820 <- tcMethods dfun_id clas inst_tyvars dfun_ev_vars
821 inst_tys dfun_ev_binds spec_inst_info
822 op_items ibinds
823
824 ; return ( sc_ids ++ meth_ids
825 , sc_binds `unionBags` meth_binds
826 , sc_implics `unionBags` meth_implics ) }
827
828 ; env <- getLclEnv
829 ; emitImplication $ Implic { ic_tclvl = tclvl
830 , ic_skols = inst_tyvars
831 , ic_no_eqs = False
832 , ic_given = dfun_ev_vars
833 , ic_wanted = addImplics emptyWC sc_meth_implics
834 , ic_status = IC_Unsolved
835 , ic_binds = Just dfun_ev_binds_var
836 , ic_env = env
837 , ic_info = InstSkol }
838
839 -- Create the result bindings
840 ; self_dict <- newDict clas inst_tys
841 ; let class_tc = classTyCon clas
842 [dict_constr] = tyConDataCons class_tc
843 dict_bind = mkVarBind self_dict (L loc con_app_args)
844
845 -- We don't produce a binding for the dict_constr; instead we
846 -- rely on the simplifier to unfold this saturated application
847 -- We do this rather than generate an HsCon directly, because
848 -- it means that the special cases (e.g. dictionary with only one
849 -- member) are dealt with by the common MkId.mkDataConWrapId
850 -- code rather than needing to be repeated here.
851 -- con_app_tys = MkD ty1 ty2
852 -- con_app_scs = MkD ty1 ty2 sc1 sc2
853 -- con_app_args = MkD ty1 ty2 sc1 sc2 op1 op2
854 con_app_tys = wrapId (mkWpTyApps inst_tys)
855 (dataConWrapId dict_constr)
856 -- NB: We *can* have covars in inst_tys, in the case of
857 -- promoted GADT constructors.
858
859 con_app_args = foldl app_to_meth con_app_tys sc_meth_ids
860
861 app_to_meth :: HsExpr Id -> Id -> HsExpr Id
862 app_to_meth fun meth_id = L loc fun `HsApp` L loc (wrapId arg_wrapper meth_id)
863
864 inst_tv_tys = mkTyVarTys inst_tyvars
865 arg_wrapper = mkWpEvVarApps dfun_ev_vars <.> mkWpTyApps inst_tv_tys
866
867 -- Do not inline the dfun; instead give it a magic DFunFunfolding
868 dfun_spec_prags
869 | isNewTyCon class_tc = SpecPrags []
870 -- Newtype dfuns just inline unconditionally,
871 -- so don't attempt to specialise them
872 | otherwise
873 = SpecPrags spec_inst_prags
874
875 export = ABE { abe_wrap = idHsWrapper, abe_poly = dfun_id
876 , abe_mono = self_dict, abe_prags = dfun_spec_prags }
877 -- NB: see Note [SPECIALISE instance pragmas]
878 main_bind = AbsBinds { abs_tvs = inst_tyvars
879 , abs_ev_vars = dfun_ev_vars
880 , abs_exports = [export]
881 , abs_ev_binds = []
882 , abs_binds = unitBag dict_bind }
883
884 ; return (unitBag (L loc main_bind) `unionBags` sc_meth_binds)
885 }
886 where
887 dfun_id = instanceDFunId ispec
888 loc = getSrcSpan dfun_id
889
890 wrapId :: HsWrapper -> id -> HsExpr id
891 wrapId wrapper id = mkHsWrap wrapper (HsVar (noLoc id))
892
893 {- Note [Typechecking plan for instance declarations]
894 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
895 For intance declarations we generate the following bindings and implication
896 constraints. Example:
897
898 instance Ord a => Ord [a] where compare = <compare-rhs>
899
900 generates this:
901
902 Bindings:
903 -- Method bindings
904 $ccompare :: forall a. Ord a => a -> a -> Ordering
905 $ccompare = /\a \(d:Ord a). let <meth-ev-binds> in ...
906
907 -- Superclass bindings
908 $cp1Ord :: forall a. Ord a => Eq [a]
909 $cp1Ord = /\a \(d:Ord a). let <sc-ev-binds>
910 in dfEqList (dw :: Eq a)
911
912 Constraints:
913 forall a. Ord a =>
914 -- Method constraint
915 (forall. (empty) => <constraints from compare-rhs>)
916 -- Superclass constraint
917 /\ (forall. (empty) => dw :: Eq a)
918
919 Notice that
920
921 * Per-meth/sc implication. There is one inner implication per
922 superclass or method, with no skolem variables or givens. The only
923 reason for this one is to gather the evidence bindings privately
924 for this superclass or method. This implication is generated
925 by checkInstConstraints.
926
927 * Overall instance implication. There is an overall enclosing
928 implication for the whole instance declaratation, with the expected
929 skolems and givens. We need this to get the correct "redundant
930 constraint" warnings, gathering all the uses from all the methods
931 and superclasses. See TcSimplify Note [Tracking redundant
932 constraints]
933
934 * The given constraints in the outer implication may generate
935 evidence, notably by superclass selection. Since the method and
936 superclass bindings are top-level, we want that evidence copied
937 into *every* method or superclass definition. (Some of it will
938 be usused in some, but dead-code elimination will drop it.)
939
940 We achieve this by putting the the evidence variable for the overall
941 instance implicaiton into the AbsBinds for each method/superclass.
942 Hence the 'dfun_ev_binds' passed into tcMethods and tcSuperClasses.
943 (And that in turn is why the abs_ev_binds field of AbBinds is a
944 [TcEvBinds] rather than simply TcEvBinds.
945
946 This is a bit of a hack, but works very nicely in practice.
947
948 * Note that if a method has a locally-polymorphic binding, there will
949 be yet another implication for that, generated by tcPolyCheck
950 in tcMethodBody. E.g.
951 class C a where
952 foo :: forall b. Ord b => blah
953
954
955 ************************************************************************
956 * *
957 Type-checking superclases
958 * *
959 ************************************************************************
960 -}
961
962 tcSuperClasses :: DFunId -> Class -> [TcTyVar] -> [EvVar] -> [TcType]
963 -> TcEvBinds -> FamInstEnvs
964 -> TcThetaType
965 -> TcM ([EvVar], LHsBinds Id, Bag Implication)
966 -- Make a new top-level function binding for each superclass,
967 -- something like
968 -- $Ordp1 :: forall a. Ord a => Eq [a]
969 -- $Ordp1 = /\a \(d:Ord a). dfunEqList a (sc_sel d)
970 --
971 -- See Note [Recursive superclasses] for why this is so hard!
972 -- In effect, be build a special-purpose solver for the first step
973 -- of solving each superclass constraint
974 tcSuperClasses dfun_id cls tyvars dfun_evs inst_tys dfun_ev_binds _fam_envs sc_theta
975 = do { (ids, binds, implics) <- mapAndUnzip3M tc_super (zip sc_theta [fIRST_TAG..])
976 ; return (ids, listToBag binds, listToBag implics) }
977 where
978 loc = getSrcSpan dfun_id
979 size = sizeTypes inst_tys
980 tc_super (sc_pred, n)
981 = do { (sc_implic, ev_binds_var, sc_ev_tm)
982 <- checkInstConstraints $ emitWanted (ScOrigin size) sc_pred
983
984 ; sc_top_name <- newName (mkSuperDictAuxOcc n (getOccName cls))
985 ; sc_ev_id <- newEvVar sc_pred
986 ; addTcEvBind ev_binds_var $ mkWantedEvBind sc_ev_id sc_ev_tm
987 ; let sc_top_ty = mkInvForAllTys tyvars (mkPiTypes dfun_evs sc_pred)
988 sc_top_id = mkLocalId sc_top_name sc_top_ty
989 export = ABE { abe_wrap = idHsWrapper, abe_poly = sc_top_id
990 , abe_mono = sc_ev_id
991 , abe_prags = SpecPrags [] }
992 local_ev_binds = TcEvBinds ev_binds_var
993 bind = AbsBinds { abs_tvs = tyvars
994 , abs_ev_vars = dfun_evs
995 , abs_exports = [export]
996 , abs_ev_binds = [dfun_ev_binds, local_ev_binds]
997 , abs_binds = emptyBag }
998 ; return (sc_top_id, L loc bind, sc_implic) }
999
1000 -------------------
1001 checkInstConstraints :: TcM result
1002 -> TcM (Implication, EvBindsVar, result)
1003 -- See Note [Typechecking plan for instance declarations]
1004 checkInstConstraints thing_inside
1005 = do { (tclvl, wanted, result) <- pushLevelAndCaptureConstraints $
1006 thing_inside
1007
1008 ; ev_binds_var <- newTcEvBinds
1009 ; env <- getLclEnv
1010 ; let implic = Implic { ic_tclvl = tclvl
1011 , ic_skols = []
1012 , ic_no_eqs = False
1013 , ic_given = []
1014 , ic_wanted = wanted
1015 , ic_status = IC_Unsolved
1016 , ic_binds = Just ev_binds_var
1017 , ic_env = env
1018 , ic_info = InstSkol }
1019
1020 ; return (implic, ev_binds_var, result) }
1021
1022 {-
1023 Note [Recursive superclasses]
1024 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1025 See Trac #3731, #4809, #5751, #5913, #6117, #6161, which all
1026 describe somewhat more complicated situations, but ones
1027 encountered in practice.
1028
1029 See also tests tcrun020, tcrun021, tcrun033
1030
1031 ----- THE PROBLEM --------
1032 The problem is that it is all too easy to create a class whose
1033 superclass is bottom when it should not be.
1034
1035 Consider the following (extreme) situation:
1036 class C a => D a where ...
1037 instance D [a] => D [a] where ... (dfunD)
1038 instance C [a] => C [a] where ... (dfunC)
1039 Although this looks wrong (assume D [a] to prove D [a]), it is only a
1040 more extreme case of what happens with recursive dictionaries, and it
1041 can, just about, make sense because the methods do some work before
1042 recursing.
1043
1044 To implement the dfunD we must generate code for the superclass C [a],
1045 which we had better not get by superclass selection from the supplied
1046 argument:
1047 dfunD :: forall a. D [a] -> D [a]
1048 dfunD = \d::D [a] -> MkD (scsel d) ..
1049
1050 Otherwise if we later encounter a situation where
1051 we have a [Wanted] dw::D [a] we might solve it thus:
1052 dw := dfunD dw
1053 Which is all fine except that now ** the superclass C is bottom **!
1054
1055 The instance we want is:
1056 dfunD :: forall a. D [a] -> D [a]
1057 dfunD = \d::D [a] -> MkD (dfunC (scsel d)) ...
1058
1059 ----- THE SOLUTION --------
1060 The basic solution is simple: be very careful about using superclass
1061 selection to generate a superclass witness in a dictionary function
1062 definition. More precisely:
1063
1064 Superclass Invariant: in every class dictionary,
1065 every superclass dictionary field
1066 is non-bottom
1067
1068 To achieve the Superclass Invariant, in a dfun definition we can
1069 generate a guaranteed-non-bottom superclass witness from:
1070 (sc1) one of the dictionary arguments itself (all non-bottom)
1071 (sc2) an immediate superclass of a smaller dictionary
1072 (sc3) a call of a dfun (always returns a dictionary constructor)
1073
1074 The tricky case is (sc2). We proceed by induction on the size of
1075 the (type of) the dictionary, defined by TcValidity.sizeTypes.
1076 Let's suppose we are building a dictionary of size 3, and
1077 suppose the Superclass Invariant holds of smaller dictionaries.
1078 Then if we have a smaller dictionary, its immediate superclasses
1079 will be non-bottom by induction.
1080
1081 What does "we have a smaller dictionary" mean? It might be
1082 one of the arguments of the instance, or one of its superclasses.
1083 Here is an example, taken from CmmExpr:
1084 class Ord r => UserOfRegs r a where ...
1085 (i1) instance UserOfRegs r a => UserOfRegs r (Maybe a) where
1086 (i2) instance (Ord r, UserOfRegs r CmmReg) => UserOfRegs r CmmExpr where
1087
1088 For (i1) we can get the (Ord r) superclass by selection from (UserOfRegs r a),
1089 since it is smaller than the thing we are building (UserOfRegs r (Maybe a).
1090
1091 But for (i2) that isn't the case, so we must add an explicit, and
1092 perhaps surprising, (Ord r) argument to the instance declaration.
1093
1094 Here's another example from Trac #6161:
1095
1096 class Super a => Duper a where ...
1097 class Duper (Fam a) => Foo a where ...
1098 (i3) instance Foo a => Duper (Fam a) where ...
1099 (i4) instance Foo Float where ...
1100
1101 It would be horribly wrong to define
1102 dfDuperFam :: Foo a -> Duper (Fam a) -- from (i3)
1103 dfDuperFam d = MkDuper (sc_sel1 (sc_sel2 d)) ...
1104
1105 dfFooFloat :: Foo Float -- from (i4)
1106 dfFooFloat = MkFoo (dfDuperFam dfFooFloat) ...
1107
1108 Now the Super superclass of Duper is definitely bottom!
1109
1110 This won't happen because when processing (i3) we can use the
1111 superclasses of (Foo a), which is smaller, namely Duper (Fam a). But
1112 that is *not* smaller than the target so we can't take *its*
1113 superclasses. As a result the program is rightly rejected, unless you
1114 add (Super (Fam a)) to the context of (i3).
1115
1116 Note [Solving superclass constraints]
1117 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1118 How do we ensure that every superclass witness is generated by
1119 one of (sc1) (sc2) or (sc3) in Note [Recursive superclases].
1120 Answer:
1121
1122 * Superclass "wanted" constraints have CtOrigin of (ScOrigin size)
1123 where 'size' is the size of the instance declaration. e.g.
1124 class C a => D a where...
1125 instance blah => D [a] where ...
1126 The wanted superclass constraint for C [a] has origin
1127 ScOrigin size, where size = size( D [a] ).
1128
1129 * (sc1) When we rewrite such a wanted constraint, it retains its
1130 origin. But if we apply an instance declaration, we can set the
1131 origin to (ScOrigin infinity), thus lifting any restrictions by
1132 making prohibitedSuperClassSolve return False.
1133
1134 * (sc2) ScOrigin wanted constraints can't be solved from a
1135 superclass selection, except at a smaller type. This test is
1136 implemented by TcInteract.prohibitedSuperClassSolve
1137
1138 * The "given" constraints of an instance decl have CtOrigin
1139 GivenOrigin InstSkol.
1140
1141 * When we make a superclass selection from InstSkol we use
1142 a SkolemInfo of (InstSC size), where 'size' is the size of
1143 the constraint whose superclass we are taking. An similarly
1144 when taking the superclass of an InstSC. This is implemented
1145 in TcCanonical.newSCWorkFromFlavored
1146
1147 Note [Silent superclass arguments] (historical interest only)
1148 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1149 NB1: this note describes our *old* solution to the
1150 recursive-superclass problem. I'm keeping the Note
1151 for now, just as institutional memory.
1152 However, the code for silent superclass arguments
1153 was removed in late Dec 2014
1154
1155 NB2: the silent-superclass solution introduced new problems
1156 of its own, in the form of instance overlap. Tests
1157 SilentParametersOverlapping, T5051, and T7862 are examples
1158
1159 NB3: the silent-superclass solution also generated tons of
1160 extra dictionaries. For example, in monad-transformer
1161 code, when constructing a Monad dictionary you had to pass
1162 an Applicative dictionary; and to construct that you neede
1163 a Functor dictionary. Yet these extra dictionaries were
1164 often never used. Test T3064 compiled *far* faster after
1165 silent superclasses were eliminated.
1166
1167 Our solution to this problem "silent superclass arguments". We pass
1168 to each dfun some ``silent superclass arguments’’, which are the
1169 immediate superclasses of the dictionary we are trying to
1170 construct. In our example:
1171 dfun :: forall a. C [a] -> D [a] -> D [a]
1172 dfun = \(dc::C [a]) (dd::D [a]) -> DOrd dc ...
1173 Notice the extra (dc :: C [a]) argument compared to the previous version.
1174
1175 This gives us:
1176
1177 -----------------------------------------------------------
1178 DFun Superclass Invariant
1179 ~~~~~~~~~~~~~~~~~~~~~~~~
1180 In the body of a DFun, every superclass argument to the
1181 returned dictionary is
1182 either * one of the arguments of the DFun,
1183 or * constant, bound at top level
1184 -----------------------------------------------------------
1185
1186 This net effect is that it is safe to treat a dfun application as
1187 wrapping a dictionary constructor around its arguments (in particular,
1188 a dfun never picks superclasses from the arguments under the
1189 dictionary constructor). No superclass is hidden inside a dfun
1190 application.
1191
1192 The extra arguments required to satisfy the DFun Superclass Invariant
1193 always come first, and are called the "silent" arguments. You can
1194 find out how many silent arguments there are using Id.dfunNSilent;
1195 and then you can just drop that number of arguments to see the ones
1196 that were in the original instance declaration.
1197
1198 DFun types are built (only) by MkId.mkDictFunId, so that is where we
1199 decide what silent arguments are to be added.
1200 -}
1201
1202 {-
1203 ************************************************************************
1204 * *
1205 Type-checking an instance method
1206 * *
1207 ************************************************************************
1208
1209 tcMethod
1210 - Make the method bindings, as a [(NonRec, HsBinds)], one per method
1211 - Remembering to use fresh Name (the instance method Name) as the binder
1212 - Bring the instance method Ids into scope, for the benefit of tcInstSig
1213 - Use sig_fn mapping instance method Name -> instance tyvars
1214 - Ditto prag_fn
1215 - Use tcValBinds to do the checking
1216 -}
1217
1218 tcMethods :: DFunId -> Class
1219 -> [TcTyVar] -> [EvVar]
1220 -> [TcType]
1221 -> TcEvBinds
1222 -> ([Located TcSpecPrag], TcPragEnv)
1223 -> [ClassOpItem]
1224 -> InstBindings Name
1225 -> TcM ([Id], LHsBinds Id, Bag Implication)
1226 -- The returned inst_meth_ids all have types starting
1227 -- forall tvs. theta => ...
1228 tcMethods dfun_id clas tyvars dfun_ev_vars inst_tys
1229 dfun_ev_binds prags@(spec_inst_prags,_) op_items
1230 (InstBindings { ib_binds = binds
1231 , ib_tyvars = lexical_tvs
1232 , ib_pragmas = sigs
1233 , ib_extensions = exts
1234 , ib_derived = is_derived })
1235 = tcExtendTyVarEnv2 (lexical_tvs `zip` tyvars) $
1236 -- The lexical_tvs scope over the 'where' part
1237 do { traceTc "tcInstMeth" (ppr sigs $$ ppr binds)
1238 ; checkMinimalDefinition
1239 ; (ids, binds, mb_implics) <- set_exts exts $
1240 mapAndUnzip3M tc_item op_items
1241 ; return (ids, listToBag binds, listToBag (catMaybes mb_implics)) }
1242 where
1243 set_exts :: [LangExt.Extension] -> TcM a -> TcM a
1244 set_exts es thing = foldr setXOptM thing es
1245
1246 hs_sig_fn = mkHsSigFun sigs
1247 inst_loc = getSrcSpan dfun_id
1248
1249 ----------------------
1250 tc_item :: ClassOpItem -> TcM (Id, LHsBind Id, Maybe Implication)
1251 tc_item (sel_id, dm_info)
1252 | Just (user_bind, bndr_loc) <- findMethodBind (idName sel_id) binds
1253 = tcMethodBody clas tyvars dfun_ev_vars inst_tys
1254 dfun_ev_binds is_derived hs_sig_fn prags
1255 sel_id user_bind bndr_loc
1256 | otherwise
1257 = do { traceTc "tc_def" (ppr sel_id)
1258 ; tc_default sel_id dm_info }
1259
1260 ----------------------
1261 tc_default :: Id -> DefMethInfo -> TcM (TcId, LHsBind Id, Maybe Implication)
1262
1263 tc_default sel_id (Just (dm_name, GenericDM {}))
1264 = do { meth_bind <- mkGenericDefMethBind clas inst_tys sel_id dm_name
1265 ; tcMethodBody clas tyvars dfun_ev_vars inst_tys
1266 dfun_ev_binds is_derived hs_sig_fn prags
1267 sel_id meth_bind inst_loc }
1268
1269 tc_default sel_id Nothing -- No default method at all
1270 = do { traceTc "tc_def: warn" (ppr sel_id)
1271 ; (meth_id, _, _) <- mkMethIds hs_sig_fn clas tyvars dfun_ev_vars
1272 inst_tys sel_id
1273 ; dflags <- getDynFlags
1274 ; let meth_bind = mkVarBind meth_id $
1275 mkLHsWrap lam_wrapper (error_rhs dflags)
1276 ; return (meth_id, meth_bind, Nothing) }
1277 where
1278 error_rhs dflags = L inst_loc $ HsApp error_fun (error_msg dflags)
1279 error_fun = L inst_loc $
1280 wrapId (mkWpTyApps
1281 [ getLevity "tcInstanceMethods.tc_default" meth_tau
1282 , meth_tau])
1283 nO_METHOD_BINDING_ERROR_ID
1284 error_msg dflags = L inst_loc (HsLit (HsStringPrim ""
1285 (unsafeMkByteString (error_string dflags))))
1286 meth_tau = funResultTy (applyTys (idType sel_id) inst_tys)
1287 error_string dflags = showSDoc dflags
1288 (hcat [ppr inst_loc, vbar, ppr sel_id ])
1289 lam_wrapper = mkWpTyLams tyvars <.> mkWpLams dfun_ev_vars
1290
1291 tc_default sel_id (Just (dm_name, VanillaDM)) -- A polymorphic default method
1292 = do { -- Build the typechecked version directly,
1293 -- without calling typecheck_method;
1294 -- see Note [Default methods in instances]
1295 -- Generate /\as.\ds. let self = df as ds
1296 -- in $dm inst_tys self
1297 -- The 'let' is necessary only because HsSyn doesn't allow
1298 -- you to apply a function to a dictionary *expression*.
1299
1300 ; self_dict <- newDict clas inst_tys
1301 ; let ev_term = EvDFunApp dfun_id (mkTyVarTys tyvars)
1302 (map EvId dfun_ev_vars)
1303 self_ev_bind = mkWantedEvBind self_dict ev_term
1304
1305 ; (meth_id, local_meth_sig, hs_wrap)
1306 <- mkMethIds hs_sig_fn clas tyvars dfun_ev_vars inst_tys sel_id
1307 ; dm_id <- tcLookupId dm_name
1308 ; let dm_inline_prag = idInlinePragma dm_id
1309 rhs = HsWrap (mkWpEvVarApps [self_dict] <.> mkWpTyApps inst_tys) $
1310 HsVar (noLoc dm_id)
1311
1312 -- A method always has a complete type signature,
1313 -- hence it is safe to call completeIdSigPolyId
1314 local_meth_id = completeIdSigPolyId local_meth_sig
1315 meth_bind = mkVarBind local_meth_id (L inst_loc rhs)
1316 meth_id1 = meth_id `setInlinePragma` dm_inline_prag
1317 -- Copy the inline pragma (if any) from the default
1318 -- method to this version. Note [INLINE and default methods]
1319
1320
1321 export = ABE { abe_wrap = hs_wrap, abe_poly = meth_id1
1322 , abe_mono = local_meth_id
1323 , abe_prags = mk_meth_spec_prags meth_id1 spec_inst_prags [] }
1324 bind = AbsBinds { abs_tvs = tyvars, abs_ev_vars = dfun_ev_vars
1325 , abs_exports = [export]
1326 , abs_ev_binds = [EvBinds (unitBag self_ev_bind)]
1327 , abs_binds = unitBag meth_bind }
1328 -- Default methods in an instance declaration can't have their own
1329 -- INLINE or SPECIALISE pragmas. It'd be possible to allow them, but
1330 -- currently they are rejected with
1331 -- "INLINE pragma lacks an accompanying binding"
1332
1333 ; return (meth_id1, L inst_loc bind, Nothing) }
1334
1335 ----------------------
1336 -- Check if one of the minimal complete definitions is satisfied
1337 checkMinimalDefinition
1338 = whenIsJust (isUnsatisfied methodExists (classMinimalDef clas)) $
1339 warnUnsatisfiedMinimalDefinition
1340 where
1341 methodExists meth = isJust (findMethodBind meth binds)
1342
1343 ------------------------
1344 tcMethodBody :: Class -> [TcTyVar] -> [EvVar] -> [TcType]
1345 -> TcEvBinds -> Bool
1346 -> HsSigFun
1347 -> ([LTcSpecPrag], TcPragEnv)
1348 -> Id -> LHsBind Name -> SrcSpan
1349 -> TcM (TcId, LHsBind Id, Maybe Implication)
1350 tcMethodBody clas tyvars dfun_ev_vars inst_tys
1351 dfun_ev_binds is_derived
1352 sig_fn (spec_inst_prags, prag_fn)
1353 sel_id (L bind_loc meth_bind) bndr_loc
1354 = add_meth_ctxt $
1355 do { traceTc "tcMethodBody" (ppr sel_id <+> ppr (idType sel_id))
1356 ; (global_meth_id, local_meth_sig, hs_wrap)
1357 <- setSrcSpan bndr_loc $
1358 mkMethIds sig_fn clas tyvars dfun_ev_vars
1359 inst_tys sel_id
1360
1361 ; let prags = lookupPragEnv prag_fn (idName sel_id)
1362 -- A method always has a complete type signature,
1363 -- so it is safe to call cmpleteIdSigPolyId
1364 local_meth_id = completeIdSigPolyId local_meth_sig
1365 lm_bind = meth_bind { fun_id = L bndr_loc (idName local_meth_id) }
1366 -- Substitute the local_meth_name for the binder
1367 -- NB: the binding is always a FunBind
1368
1369 ; global_meth_id <- addInlinePrags global_meth_id prags
1370 ; spec_prags <- tcSpecPrags global_meth_id prags
1371 ; (meth_implic, ev_binds_var, (tc_bind, _))
1372 <- checkInstConstraints $
1373 tcPolyCheck NonRecursive no_prag_fn local_meth_sig
1374 (L bind_loc lm_bind)
1375
1376 ; let specs = mk_meth_spec_prags global_meth_id spec_inst_prags spec_prags
1377 export = ABE { abe_poly = global_meth_id
1378 , abe_mono = local_meth_id
1379 , abe_wrap = hs_wrap
1380 , abe_prags = specs }
1381
1382 local_ev_binds = TcEvBinds ev_binds_var
1383 full_bind = AbsBinds { abs_tvs = tyvars
1384 , abs_ev_vars = dfun_ev_vars
1385 , abs_exports = [export]
1386 , abs_ev_binds = [dfun_ev_binds, local_ev_binds]
1387 , abs_binds = tc_bind }
1388
1389 ; return (global_meth_id, L bind_loc full_bind, Just meth_implic) }
1390 where
1391 -- For instance decls that come from deriving clauses
1392 -- we want to print out the full source code if there's an error
1393 -- because otherwise the user won't see the code at all
1394 add_meth_ctxt thing
1395 | is_derived = addLandmarkErrCtxt (derivBindCtxt sel_id clas inst_tys) thing
1396 | otherwise = thing
1397
1398 no_prag_fn = emptyPragEnv -- No pragmas for local_meth_id;
1399 -- they are all for meth_id
1400
1401
1402 ------------------------
1403 mkMethIds :: HsSigFun -> Class -> [TcTyVar] -> [EvVar]
1404 -> [TcType] -> Id -> TcM (TcId, TcIdSigInfo, HsWrapper)
1405 mkMethIds sig_fn clas tyvars dfun_ev_vars inst_tys sel_id
1406 = do { poly_meth_name <- newName (mkClassOpAuxOcc sel_occ)
1407 ; local_meth_name <- newName sel_occ
1408 -- Base the local_meth_name on the selector name, because
1409 -- type errors from tcMethodBody come from here
1410 ; let poly_meth_id = mkLocalId poly_meth_name poly_meth_ty
1411 local_meth_id = mkLocalId local_meth_name local_meth_ty
1412
1413 ; case lookupHsSig sig_fn sel_name of
1414 Just lhs_ty -- There is a signature in the instance declaration
1415 -- See Note [Instance method signatures]
1416 -> setSrcSpan (getLoc (hsSigType lhs_ty)) $
1417 do { inst_sigs <- xoptM LangExt.InstanceSigs
1418 ; checkTc inst_sigs (misplacedInstSig sel_name lhs_ty)
1419 ; sig_ty <- tcHsSigType (FunSigCtxt sel_name False) lhs_ty
1420 ; let poly_sig_ty = mkInvSigmaTy tyvars theta sig_ty
1421 ctxt = FunSigCtxt sel_name True
1422 ; tc_sig <- instTcTySig ctxt lhs_ty sig_ty local_meth_name
1423 ; hs_wrap <- addErrCtxtM (methSigCtxt sel_name poly_sig_ty poly_meth_ty) $
1424 tcSubType ctxt (Just poly_meth_id)
1425 poly_sig_ty poly_meth_ty
1426 ; return (poly_meth_id, tc_sig, hs_wrap) }
1427
1428 Nothing -- No type signature
1429 -> do { tc_sig <- instTcTySigFromId local_meth_id
1430 ; return (poly_meth_id, tc_sig, idHsWrapper) } }
1431 -- Absent a type sig, there are no new scoped type variables here
1432 -- Only the ones from the instance decl itself, which are already
1433 -- in scope. Example:
1434 -- class C a where { op :: forall b. Eq b => ... }
1435 -- instance C [c] where { op = <rhs> }
1436 -- In <rhs>, 'c' is scope but 'b' is not!
1437 where
1438 sel_name = idName sel_id
1439 sel_occ = nameOccName sel_name
1440 local_meth_ty = instantiateMethod clas sel_id inst_tys
1441 poly_meth_ty = mkInvSigmaTy tyvars theta local_meth_ty
1442 theta = map idType dfun_ev_vars
1443
1444 methSigCtxt :: Name -> TcType -> TcType -> TidyEnv -> TcM (TidyEnv, MsgDoc)
1445 methSigCtxt sel_name sig_ty meth_ty env0
1446 = do { (env1, sig_ty) <- zonkTidyTcType env0 sig_ty
1447 ; (env2, meth_ty) <- zonkTidyTcType env1 meth_ty
1448 ; let msg = hang (ptext (sLit "When checking that instance signature for") <+> quotes (ppr sel_name))
1449 2 (vcat [ ptext (sLit "is more general than its signature in the class")
1450 , ptext (sLit "Instance sig:") <+> ppr sig_ty
1451 , ptext (sLit " Class sig:") <+> ppr meth_ty ])
1452 ; return (env2, msg) }
1453
1454 misplacedInstSig :: Name -> LHsSigType Name -> SDoc
1455 misplacedInstSig name hs_ty
1456 = vcat [ hang (ptext (sLit "Illegal type signature in instance declaration:"))
1457 2 (hang (pprPrefixName name)
1458 2 (dcolon <+> ppr hs_ty))
1459 , ptext (sLit "(Use InstanceSigs to allow this)") ]
1460
1461 {-
1462 Note [Instance method signatures]
1463 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1464 With -XInstanceSigs we allow the user to supply a signature for the
1465 method in an instance declaration. Here is an artificial example:
1466
1467 data Age = MkAge Int
1468 instance Ord Age where
1469 compare :: a -> a -> Bool
1470 compare = error "You can't compare Ages"
1471
1472 The instance signature can be *more* polymorphic than the instantiated
1473 class method (in this case: Age -> Age -> Bool), but it cannot be less
1474 polymorphic. Moreover, if a signature is given, the implementation
1475 code should match the signature, and type variables bound in the
1476 singature should scope over the method body.
1477
1478 We achieve this by building a TcSigInfo for the method, whether or not
1479 there is an instance method signature, and using that to typecheck
1480 the declaration (in tcMethodBody). That means, conveniently,
1481 that the type variables bound in the signature will scope over the body.
1482
1483 What about the check that the instance method signature is more
1484 polymorphic than the instantiated class method type? We just do a
1485 tcSubType call in mkMethIds, and use the HsWrapper thus generated in
1486 the method AbsBind. It's very like the tcSubType impedance-matching
1487 call in mkExport. We have to pass the HsWrapper into
1488 tcMethodBody.
1489 -}
1490
1491 ----------------------
1492 mk_meth_spec_prags :: Id -> [LTcSpecPrag] -> [LTcSpecPrag] -> TcSpecPrags
1493 -- Adapt the 'SPECIALISE instance' pragmas to work for this method Id
1494 -- There are two sources:
1495 -- * spec_prags_for_me: {-# SPECIALISE op :: <blah> #-}
1496 -- * spec_prags_from_inst: derived from {-# SPECIALISE instance :: <blah> #-}
1497 -- These ones have the dfun inside, but [perhaps surprisingly]
1498 -- the correct wrapper.
1499 -- See Note [Handling SPECIALISE pragmas] in TcBinds
1500 mk_meth_spec_prags meth_id spec_inst_prags spec_prags_for_me
1501 = SpecPrags (spec_prags_for_me ++ spec_prags_from_inst)
1502 where
1503 spec_prags_from_inst
1504 | isInlinePragma (idInlinePragma meth_id)
1505 = [] -- Do not inherit SPECIALISE from the instance if the
1506 -- method is marked INLINE, because then it'll be inlined
1507 -- and the specialisation would do nothing. (Indeed it'll provoke
1508 -- a warning from the desugarer
1509 | otherwise
1510 = [ L inst_loc (SpecPrag meth_id wrap inl)
1511 | L inst_loc (SpecPrag _ wrap inl) <- spec_inst_prags]
1512
1513
1514 mkGenericDefMethBind :: Class -> [Type] -> Id -> Name -> TcM (LHsBind Name)
1515 mkGenericDefMethBind clas inst_tys sel_id dm_name
1516 = -- A generic default method
1517 -- If the method is defined generically, we only have to call the
1518 -- dm_name.
1519 do { dflags <- getDynFlags
1520 ; liftIO (dumpIfSet_dyn dflags Opt_D_dump_deriv "Filling in method body"
1521 (vcat [ppr clas <+> ppr inst_tys,
1522 nest 2 (ppr sel_id <+> equals <+> ppr rhs)]))
1523
1524 ; return (noLoc $ mkTopFunBind Generated (noLoc (idName sel_id))
1525 [mkSimpleMatch [] rhs]) }
1526 where
1527 rhs = nlHsVar dm_name
1528
1529 ----------------------
1530 derivBindCtxt :: Id -> Class -> [Type ] -> SDoc
1531 derivBindCtxt sel_id clas tys
1532 = vcat [ ptext (sLit "When typechecking the code for") <+> quotes (ppr sel_id)
1533 , nest 2 (ptext (sLit "in a derived instance for")
1534 <+> quotes (pprClassPred clas tys) <> colon)
1535 , nest 2 $ ptext (sLit "To see the code I am typechecking, use -ddump-deriv") ]
1536
1537 warnUnsatisfiedMinimalDefinition :: ClassMinimalDef -> TcM ()
1538 warnUnsatisfiedMinimalDefinition mindef
1539 = do { warn <- woptM Opt_WarnMissingMethods
1540 ; warnTc warn message
1541 }
1542 where
1543 message = vcat [ptext (sLit "No explicit implementation for")
1544 ,nest 2 $ pprBooleanFormulaNice mindef
1545 ]
1546
1547 {-
1548 Note [Export helper functions]
1549 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1550 We arrange to export the "helper functions" of an instance declaration,
1551 so that they are not subject to preInlineUnconditionally, even if their
1552 RHS is trivial. Reason: they are mentioned in the DFunUnfolding of
1553 the dict fun as Ids, not as CoreExprs, so we can't substitute a
1554 non-variable for them.
1555
1556 We could change this by making DFunUnfoldings have CoreExprs, but it
1557 seems a bit simpler this way.
1558
1559 Note [Default methods in instances]
1560 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1561 Consider this
1562
1563 class Baz v x where
1564 foo :: x -> x
1565 foo y = <blah>
1566
1567 instance Baz Int Int
1568
1569 From the class decl we get
1570
1571 $dmfoo :: forall v x. Baz v x => x -> x
1572 $dmfoo y = <blah>
1573
1574 Notice that the type is ambiguous. That's fine, though. The instance
1575 decl generates
1576
1577 $dBazIntInt = MkBaz fooIntInt
1578 fooIntInt = $dmfoo Int Int $dBazIntInt
1579
1580 BUT this does mean we must generate the dictionary translation of
1581 fooIntInt directly, rather than generating source-code and
1582 type-checking it. That was the bug in Trac #1061. In any case it's
1583 less work to generate the translated version!
1584
1585 Note [INLINE and default methods]
1586 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1587 Default methods need special case. They are supposed to behave rather like
1588 macros. For exmample
1589
1590 class Foo a where
1591 op1, op2 :: Bool -> a -> a
1592
1593 {-# INLINE op1 #-}
1594 op1 b x = op2 (not b) x
1595
1596 instance Foo Int where
1597 -- op1 via default method
1598 op2 b x = <blah>
1599
1600 The instance declaration should behave
1601
1602 just as if 'op1' had been defined with the
1603 code, and INLINE pragma, from its original
1604 definition.
1605
1606 That is, just as if you'd written
1607
1608 instance Foo Int where
1609 op2 b x = <blah>
1610
1611 {-# INLINE op1 #-}
1612 op1 b x = op2 (not b) x
1613
1614 So for the above example we generate:
1615
1616 {-# INLINE $dmop1 #-}
1617 -- $dmop1 has an InlineCompulsory unfolding
1618 $dmop1 d b x = op2 d (not b) x
1619
1620 $fFooInt = MkD $cop1 $cop2
1621
1622 {-# INLINE $cop1 #-}
1623 $cop1 = $dmop1 $fFooInt
1624
1625 $cop2 = <blah>
1626
1627 Note carefully:
1628
1629 * We *copy* any INLINE pragma from the default method $dmop1 to the
1630 instance $cop1. Otherwise we'll just inline the former in the
1631 latter and stop, which isn't what the user expected
1632
1633 * Regardless of its pragma, we give the default method an
1634 unfolding with an InlineCompulsory source. That means
1635 that it'll be inlined at every use site, notably in
1636 each instance declaration, such as $cop1. This inlining
1637 must happen even though
1638 a) $dmop1 is not saturated in $cop1
1639 b) $cop1 itself has an INLINE pragma
1640
1641 It's vital that $dmop1 *is* inlined in this way, to allow the mutual
1642 recursion between $fooInt and $cop1 to be broken
1643
1644 * To communicate the need for an InlineCompulsory to the desugarer
1645 (which makes the Unfoldings), we use the IsDefaultMethod constructor
1646 in TcSpecPrags.
1647
1648
1649 ************************************************************************
1650 * *
1651 Specialise instance pragmas
1652 * *
1653 ************************************************************************
1654
1655 Note [SPECIALISE instance pragmas]
1656 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1657 Consider
1658
1659 instance (Ix a, Ix b) => Ix (a,b) where
1660 {-# SPECIALISE instance Ix (Int,Int) #-}
1661 range (x,y) = ...
1662
1663 We make a specialised version of the dictionary function, AND
1664 specialised versions of each *method*. Thus we should generate
1665 something like this:
1666
1667 $dfIxPair :: (Ix a, Ix b) => Ix (a,b)
1668 {-# DFUN [$crangePair, ...] #-}
1669 {-# SPECIALISE $dfIxPair :: Ix (Int,Int) #-}
1670 $dfIxPair da db = Ix ($crangePair da db) (...other methods...)
1671
1672 $crange :: (Ix a, Ix b) -> ((a,b),(a,b)) -> [(a,b)]
1673 {-# SPECIALISE $crange :: ((Int,Int),(Int,Int)) -> [(Int,Int)] #-}
1674 $crange da db = <blah>
1675
1676 The SPECIALISE pragmas are acted upon by the desugarer, which generate
1677
1678 dii :: Ix Int
1679 dii = ...
1680
1681 $s$dfIxPair :: Ix ((Int,Int),(Int,Int))
1682 {-# DFUN [$crangePair di di, ...] #-}
1683 $s$dfIxPair = Ix ($crangePair di di) (...)
1684
1685 {-# RULE forall (d1,d2:Ix Int). $dfIxPair Int Int d1 d2 = $s$dfIxPair #-}
1686
1687 $s$crangePair :: ((Int,Int),(Int,Int)) -> [(Int,Int)]
1688 $c$crangePair = ...specialised RHS of $crangePair...
1689
1690 {-# RULE forall (d1,d2:Ix Int). $crangePair Int Int d1 d2 = $s$crangePair #-}
1691
1692 Note that
1693
1694 * The specialised dictionary $s$dfIxPair is very much needed, in case we
1695 call a function that takes a dictionary, but in a context where the
1696 specialised dictionary can be used. See Trac #7797.
1697
1698 * The ClassOp rule for 'range' works equally well on $s$dfIxPair, because
1699 it still has a DFunUnfolding. See Note [ClassOp/DFun selection]
1700
1701 * A call (range ($dfIxPair Int Int d1 d2)) might simplify two ways:
1702 --> {ClassOp rule for range} $crangePair Int Int d1 d2
1703 --> {SPEC rule for $crangePair} $s$crangePair
1704 or thus:
1705 --> {SPEC rule for $dfIxPair} range $s$dfIxPair
1706 --> {ClassOpRule for range} $s$crangePair
1707 It doesn't matter which way.
1708
1709 * We want to specialise the RHS of both $dfIxPair and $crangePair,
1710 but the SAME HsWrapper will do for both! We can call tcSpecPrag
1711 just once, and pass the result (in spec_inst_info) to tcMethods.
1712 -}
1713
1714 tcSpecInstPrags :: DFunId -> InstBindings Name
1715 -> TcM ([Located TcSpecPrag], TcPragEnv)
1716 tcSpecInstPrags dfun_id (InstBindings { ib_binds = binds, ib_pragmas = uprags })
1717 = do { spec_inst_prags <- mapM (wrapLocM (tcSpecInst dfun_id)) $
1718 filter isSpecInstLSig uprags
1719 -- The filter removes the pragmas for methods
1720 ; return (spec_inst_prags, mkPragEnv uprags binds) }
1721
1722 ------------------------------
1723 tcSpecInst :: Id -> Sig Name -> TcM TcSpecPrag
1724 tcSpecInst dfun_id prag@(SpecInstSig _ hs_ty)
1725 = addErrCtxt (spec_ctxt prag) $
1726 do { (tyvars, theta, clas, tys) <- tcHsClsInstType SpecInstCtxt hs_ty
1727 ; let spec_dfun_ty = mkDictFunTy tyvars theta clas tys
1728 ; co_fn <- tcSpecWrapper SpecInstCtxt (idType dfun_id) spec_dfun_ty
1729 ; return (SpecPrag dfun_id co_fn defaultInlinePragma) }
1730 where
1731 spec_ctxt prag = hang (ptext (sLit "In the SPECIALISE pragma")) 2 (ppr prag)
1732
1733 tcSpecInst _ _ = panic "tcSpecInst"
1734
1735 {-
1736 ************************************************************************
1737 * *
1738 \subsection{Error messages}
1739 * *
1740 ************************************************************************
1741 -}
1742
1743 instDeclCtxt1 :: LHsSigType Name -> SDoc
1744 instDeclCtxt1 hs_inst_ty
1745 | (_, _, head_ty) <- splitLHsInstDeclTy hs_inst_ty
1746 = inst_decl_ctxt (ppr head_ty)
1747
1748 instDeclCtxt2 :: Type -> SDoc
1749 instDeclCtxt2 dfun_ty
1750 = inst_decl_ctxt (ppr (mkClassPred cls tys))
1751 where
1752 (_,_,cls,tys) = tcSplitDFunTy dfun_ty
1753
1754 inst_decl_ctxt :: SDoc -> SDoc
1755 inst_decl_ctxt doc = hang (ptext (sLit "In the instance declaration for"))
1756 2 (quotes doc)
1757
1758 badBootFamInstDeclErr :: SDoc
1759 badBootFamInstDeclErr
1760 = ptext (sLit "Illegal family instance in hs-boot file")
1761
1762 notFamily :: TyCon -> SDoc
1763 notFamily tycon
1764 = vcat [ ptext (sLit "Illegal family instance for") <+> quotes (ppr tycon)
1765 , nest 2 $ parens (ppr tycon <+> ptext (sLit "is not an indexed type family"))]
1766
1767 tooFewParmsErr :: Arity -> SDoc
1768 tooFewParmsErr arity
1769 = ptext (sLit "Family instance has too few parameters; expected") <+>
1770 ppr arity
1771
1772 assocInClassErr :: Located Name -> SDoc
1773 assocInClassErr name
1774 = ptext (sLit "Associated type") <+> quotes (ppr name) <+>
1775 ptext (sLit "must be inside a class instance")
1776
1777 badFamInstDecl :: Located Name -> SDoc
1778 badFamInstDecl tc_name
1779 = vcat [ ptext (sLit "Illegal family instance for") <+>
1780 quotes (ppr tc_name)
1781 , nest 2 (parens $ ptext (sLit "Use TypeFamilies to allow indexed type families")) ]
1782
1783 notOpenFamily :: TyCon -> SDoc
1784 notOpenFamily tc
1785 = ptext (sLit "Illegal instance for closed family") <+> quotes (ppr tc)