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