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