Store a SrcSpan instead of a SrcLoc inside a Name
[ghc-hetmet.git] / compiler / typecheck / TcDeriv.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5
6 Handles @deriving@ clauses on @data@ declarations.
7
8 \begin{code}
9 module TcDeriv ( tcDeriving ) where
10
11 #include "HsVersions.h"
12
13 import HsSyn
14 import DynFlags
15
16 import Generics
17 import TcRnMonad
18 import TcEnv
19 import TcClassDcl( tcAddDeclCtxt )      -- Small helper
20 import TcGenDeriv                       -- Deriv stuff
21 import InstEnv
22 import Inst
23 import TcHsType
24 import TcMType
25 import TcSimplify
26
27 import RnBinds
28 import RnEnv
29 import HscTypes
30
31 import Class
32 import Type
33 import ErrUtils
34 import MkId
35 import DataCon
36 import Maybes
37 import RdrName
38 import Name
39 import NameSet
40 import TyCon
41 import TcType
42 import Var
43 import VarSet
44 import PrelNames
45 import SrcLoc
46 import Util
47 import ListSetOps
48 import Outputable
49 import Bag
50 \end{code}
51
52 %************************************************************************
53 %*                                                                      *
54 \subsection[TcDeriv-intro]{Introduction to how we do deriving}
55 %*                                                                      *
56 %************************************************************************
57
58 Consider
59
60         data T a b = C1 (Foo a) (Bar b)
61                    | C2 Int (T b a)
62                    | C3 (T a a)
63                    deriving (Eq)
64
65 [NOTE: See end of these comments for what to do with 
66         data (C a, D b) => T a b = ...
67 ]
68
69 We want to come up with an instance declaration of the form
70
71         instance (Ping a, Pong b, ...) => Eq (T a b) where
72                 x == y = ...
73
74 It is pretty easy, albeit tedious, to fill in the code "...".  The
75 trick is to figure out what the context for the instance decl is,
76 namely @Ping@, @Pong@ and friends.
77
78 Let's call the context reqd for the T instance of class C at types
79 (a,b, ...)  C (T a b).  Thus:
80
81         Eq (T a b) = (Ping a, Pong b, ...)
82
83 Now we can get a (recursive) equation from the @data@ decl:
84
85         Eq (T a b) = Eq (Foo a) u Eq (Bar b)    -- From C1
86                    u Eq (T b a) u Eq Int        -- From C2
87                    u Eq (T a a)                 -- From C3
88
89 Foo and Bar may have explicit instances for @Eq@, in which case we can
90 just substitute for them.  Alternatively, either or both may have
91 their @Eq@ instances given by @deriving@ clauses, in which case they
92 form part of the system of equations.
93
94 Now all we need do is simplify and solve the equations, iterating to
95 find the least fixpoint.  Notice that the order of the arguments can
96 switch around, as here in the recursive calls to T.
97
98 Let's suppose Eq (Foo a) = Eq a, and Eq (Bar b) = Ping b.
99
100 We start with:
101
102         Eq (T a b) = {}         -- The empty set
103
104 Next iteration:
105         Eq (T a b) = Eq (Foo a) u Eq (Bar b)    -- From C1
106                    u Eq (T b a) u Eq Int        -- From C2
107                    u Eq (T a a)                 -- From C3
108
109         After simplification:
110                    = Eq a u Ping b u {} u {} u {}
111                    = Eq a u Ping b
112
113 Next iteration:
114
115         Eq (T a b) = Eq (Foo a) u Eq (Bar b)    -- From C1
116                    u Eq (T b a) u Eq Int        -- From C2
117                    u Eq (T a a)                 -- From C3
118
119         After simplification:
120                    = Eq a u Ping b
121                    u (Eq b u Ping a)
122                    u (Eq a u Ping a)
123
124                    = Eq a u Ping b u Eq b u Ping a
125
126 The next iteration gives the same result, so this is the fixpoint.  We
127 need to make a canonical form of the RHS to ensure convergence.  We do
128 this by simplifying the RHS to a form in which
129
130         - the classes constrain only tyvars
131         - the list is sorted by tyvar (major key) and then class (minor key)
132         - no duplicates, of course
133
134 So, here are the synonyms for the ``equation'' structures:
135
136 \begin{code}
137 type DerivRhs  = ThetaType
138 type DerivSoln = DerivRhs
139 type DerivEqn  = (SrcSpan, InstOrigin, Name, [TyVar], Class, Type, DerivRhs)
140         -- (span, orig, df, tvs, C, ty, rhs)
141         --    implies a dfun declaration of the form
142         --       df :: forall tvs. rhs => C ty
143         -- The Name is the name for the DFun we'll build
144         -- The tyvars bind all the variables in the RHS
145         -- For family indexes, the tycon is the *family* tycon
146         --              (not the representation tycon)
147
148 pprDerivEqn :: DerivEqn -> SDoc
149 pprDerivEqn (l, _, n, tvs, c, ty, rhs)
150   = parens (hsep [ppr l, ppr n, ppr tvs, ppr c, ppr ty]
151             <+> equals <+> ppr rhs)
152 \end{code}
153
154
155 [Data decl contexts] A note about contexts on data decls
156 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
157 Consider
158
159         data (RealFloat a) => Complex a = !a :+ !a deriving( Read )
160
161 We will need an instance decl like:
162
163         instance (Read a, RealFloat a) => Read (Complex a) where
164           ...
165
166 The RealFloat in the context is because the read method for Complex is bound
167 to construct a Complex, and doing that requires that the argument type is
168 in RealFloat. 
169
170 But this ain't true for Show, Eq, Ord, etc, since they don't construct
171 a Complex; they only take them apart.
172
173 Our approach: identify the offending classes, and add the data type
174 context to the instance decl.  The "offending classes" are
175
176         Read, Enum?
177
178 FURTHER NOTE ADDED March 2002.  In fact, Haskell98 now requires that
179 pattern matching against a constructor from a data type with a context
180 gives rise to the constraints for that context -- or at least the thinned
181 version.  So now all classes are "offending".
182
183 [Newtype deriving]
184 ~~~~~~~~~~~~~~~~~~
185 Consider this:
186     class C a b
187     instance C [a] Char
188     newtype T = T Char deriving( C [a] )
189
190 Notice the free 'a' in the deriving.  We have to fill this out to 
191     newtype T = T Char deriving( forall a. C [a] )
192
193 And then translate it to:
194     instance C [a] Char => C [a] T where ...
195     
196         
197
198
199 %************************************************************************
200 %*                                                                      *
201 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
202 %*                                                                      *
203 %************************************************************************
204
205 \begin{code}
206 tcDeriving  :: [LTyClDecl Name] -- All type constructors
207             -> [LDerivDecl Name] -- All stand-alone deriving declarations
208             -> TcM ([InstInfo],         -- The generated "instance decls"
209                     HsValBinds Name)    -- Extra generated top-level bindings
210
211 tcDeriving tycl_decls deriv_decls
212   = recoverM (returnM ([], emptyValBindsOut)) $
213     do  {       -- Fish the "deriving"-related information out of the TcEnv
214                 -- and make the necessary "equations".
215         ; (ordinary_eqns, newtype_inst_info) <- makeDerivEqns tycl_decls deriv_decls
216
217         ; (ordinary_inst_info, deriv_binds) 
218                 <- extendLocalInstEnv (map iSpec newtype_inst_info)  $
219                    deriveOrdinaryStuff ordinary_eqns
220                 -- Add the newtype-derived instances to the inst env
221                 -- before tacking the "ordinary" ones
222
223         ; let inst_info = newtype_inst_info ++ ordinary_inst_info
224
225         -- If we are compiling a hs-boot file, 
226         -- don't generate any derived bindings
227         ; is_boot <- tcIsHsBoot
228         ; if is_boot then
229                 return (inst_info, emptyValBindsOut)
230           else do
231         {
232
233         -- Generate the generic to/from functions from each type declaration
234         ; gen_binds <- mkGenericBinds tycl_decls
235
236         -- Rename these extra bindings, discarding warnings about unused bindings etc
237         -- Set -fglasgow exts so that we can have type signatures in patterns,
238         -- which is used in the generic binds
239         ; rn_binds
240                 <- discardWarnings $ setOptM Opt_GlasgowExts $ do
241                         { (rn_deriv, _dus1) <- rnTopBinds (ValBindsIn deriv_binds [])
242                         ; (rn_gen, dus_gen) <- rnTopBinds (ValBindsIn gen_binds   [])
243                         ; keepAliveSetTc (duDefs dus_gen)       -- Mark these guys to
244                                                                 -- be kept alive
245                         ; return (rn_deriv `plusHsValBinds` rn_gen) }
246
247
248         ; dflags <- getDOpts
249         ; ioToTcRn (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances" 
250                    (ddump_deriving inst_info rn_binds))
251
252         ; returnM (inst_info, rn_binds)
253         }}
254   where
255     ddump_deriving :: [InstInfo] -> HsValBinds Name -> SDoc
256     ddump_deriving inst_infos extra_binds
257       = vcat (map pprInstInfoDetails inst_infos) $$ ppr extra_binds
258
259 -----------------------------------------
260 deriveOrdinaryStuff []  -- Short cut
261   = returnM ([], emptyLHsBinds)
262
263 deriveOrdinaryStuff eqns
264   = do  {       -- Take the equation list and solve it, to deliver a list of
265                 -- solutions, a.k.a. the contexts for the instance decls
266                 -- required for the corresponding equations.
267           overlap_flag <- getOverlapFlag
268         ; inst_specs <- solveDerivEqns overlap_flag eqns
269
270         -- Generate the InstInfo for each dfun, 
271         -- plus any auxiliary bindings it needs
272         ; (inst_infos, aux_binds_s) <- mapAndUnzipM genInst inst_specs
273
274         -- Generate any extra not-one-inst-decl-specific binds, 
275         -- notably "con2tag" and/or "tag2con" functions.  
276         ; extra_binds <- genTaggeryBinds inst_infos
277
278         -- Done
279         ; returnM (map fst inst_infos, 
280                    unionManyBags (extra_binds : aux_binds_s))
281    }
282
283 -----------------------------------------
284 mkGenericBinds tycl_decls
285   = do  { tcs <- mapM tcLookupTyCon 
286                         [ tc_name | 
287                           L _ (TyData { tcdLName = L _ tc_name }) <- tycl_decls]
288                 -- We are only interested in the data type declarations
289         ; return (unionManyBags [ mkTyConGenericBinds tc | 
290                                   tc <- tcs, tyConHasGenerics tc ]) }
291                 -- And then only in the ones whose 'has-generics' flag is on
292 \end{code}
293
294
295 %************************************************************************
296 %*                                                                      *
297 \subsection[TcDeriv-eqns]{Forming the equations}
298 %*                                                                      *
299 %************************************************************************
300
301 @makeDerivEqns@ fishes around to find the info about needed derived
302 instances.  Complicating factors:
303 \begin{itemize}
304 \item
305 We can only derive @Enum@ if the data type is an enumeration
306 type (all nullary data constructors).
307
308 \item
309 We can only derive @Ix@ if the data type is an enumeration {\em
310 or} has just one data constructor (e.g., tuples).
311 \end{itemize}
312
313 [See Appendix~E in the Haskell~1.2 report.] This code here deals w/
314 all those.
315
316 Note [Newtype deriving superclasses]
317 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
318 The 'tys' here come from the partial application in the deriving
319 clause. The last arg is the new instance type.
320
321 We must pass the superclasses; the newtype might be an instance
322 of them in a different way than the representation type
323 E.g.            newtype Foo a = Foo a deriving( Show, Num, Eq )
324 Then the Show instance is not done via isomorphism; it shows
325         Foo 3 as "Foo 3"
326 The Num instance is derived via isomorphism, but the Show superclass
327 dictionary must the Show instance for Foo, *not* the Show dictionary
328 gotten from the Num dictionary. So we must build a whole new dictionary
329 not just use the Num one.  The instance we want is something like:
330      instance (Num a, Show (Foo a), Eq (Foo a)) => Num (Foo a) where
331         (+) = ((+)@a)
332         ...etc...
333 There may be a coercion needed which we get from the tycon for the newtype
334 when the dict is constructed in TcInstDcls.tcInstDecl2
335
336
337 \begin{code}
338 makeDerivEqns :: [LTyClDecl Name] 
339               -> [LDerivDecl Name] 
340               -> TcM ([DerivEqn],       -- Ordinary derivings
341                       [InstInfo])       -- Special newtype derivings
342
343 makeDerivEqns tycl_decls deriv_decls
344   = do  { eqns1 <- mapM deriveTyData $
345                    [ (p,d) | d@(L _ (TyData {tcdDerivs = Just preds})) <- tycl_decls
346                            , p <- preds ]
347         ; eqns2 <- mapM deriveStandalone deriv_decls
348         ; return ([eqn  | (Just eqn, _)  <- eqns1 ++ eqns2],
349                   [inst | (_, Just inst) <- eqns1 ++ eqns2]) }
350
351 ------------------------------------------------------------------
352 deriveStandalone :: LDerivDecl Name -> TcM (Maybe DerivEqn, Maybe InstInfo)
353 -- Standalone deriving declarations
354 --      e.g.   derive instance Show T
355 -- Rather like tcLocalInstDecl
356 deriveStandalone (L loc (DerivDecl deriv_ty))
357   = setSrcSpan loc                   $
358     addErrCtxt (standaloneCtxt deriv_ty)  $
359     do  { (tvs, theta, tau) <- tcHsInstHead deriv_ty
360         ; (cls, inst_tys) <- checkValidInstHead tau
361         ; let cls_tys = take (length inst_tys - 1) inst_tys
362               inst_ty = last inst_tys
363
364         ; mkEqnHelp StandAloneDerivOrigin tvs cls cls_tys inst_ty }
365
366 ------------------------------------------------------------------
367 deriveTyData :: (LHsType Name, LTyClDecl Name) -> TcM (Maybe DerivEqn, Maybe InstInfo)
368 deriveTyData (deriv_pred, L loc decl@(TyData { tcdLName = L _ tycon_name, 
369                                                tcdTyVars = tv_names, 
370                                                tcdTyPats = ty_pats }))
371   = setSrcSpan loc                   $
372     tcAddDeclCtxt decl               $
373     do  { let hs_ty_args = ty_pats `orElse` map (nlHsTyVar . hsLTyVarName) tv_names
374               hs_app     = nlHsTyConApp tycon_name hs_ty_args
375                 -- We get kinding info for the tyvars by typechecking (T a b)
376                 -- Hence forming a tycon application and then dis-assembling it
377         ; (tvs, tc_app) <- tcHsQuantifiedType tv_names hs_app
378         ; tcExtendTyVarEnv tvs $        -- Deriving preds may (now) mention
379                                         -- the type variables for the type constructor
380     do  { (deriv_tvs, cls, cls_tys) <- tcHsDeriv deriv_pred
381                 -- The "deriv_pred" is a LHsType to take account of the fact that for
382                 -- newtype deriving we allow deriving (forall a. C [a]).
383         ; mkEqnHelp DerivOrigin (tvs++deriv_tvs) cls cls_tys tc_app } }
384 deriveTyData (deriv_pred, other_decl)
385   = panic "derivTyData" -- Caller ensures that only TyData can happen
386
387 ------------------------------------------------------------------
388 mkEqnHelp orig tvs cls cls_tys tc_app
389   | Just (tycon, tc_args) <- tcSplitTyConApp_maybe tc_app
390   = do  {       -- Make tc_app saturated, because that's what the
391                 -- mkDataTypeEqn things expect
392                 -- It might not be saturated in the standalone deriving case
393                 --      derive instance Monad (T a)
394           let extra_tvs = dropList tc_args (tyConTyVars tycon)
395               full_tc_args = tc_args ++ mkTyVarTys extra_tvs
396               full_tvs = tvs ++ extra_tvs
397                 
398         ; (rep_tc, rep_tc_args) <- tcLookupFamInst tycon full_tc_args
399
400         ; gla_exts <- doptM Opt_GlasgowExts
401         ; overlap_flag <- getOverlapFlag
402         ; if isDataTyCon tycon then
403                 mkDataTypeEqn orig gla_exts full_tvs cls cls_tys 
404                               tycon full_tc_args rep_tc rep_tc_args
405           else
406                 mkNewTypeEqn  orig gla_exts overlap_flag full_tvs cls cls_tys 
407                               tycon full_tc_args rep_tc rep_tc_args }
408   | otherwise
409   = baleOut (derivingThingErr cls cls_tys tc_app
410                 (ptext SLIT("Last argument of the instance must be a type application")))
411
412 baleOut err = addErrTc err >> returnM (Nothing, Nothing) 
413 \end{code}
414
415
416 %************************************************************************
417 %*                                                                      *
418                 Deriving data types
419 %*                                                                      *
420 %************************************************************************
421
422 \begin{code}
423 mkDataTypeEqn orig gla_exts tvs cls cls_tys tycon tc_args rep_tc rep_tc_args
424   | Just err <- checkSideConditions gla_exts cls cls_tys rep_tc
425         -- NB: pass the *representation* tycon to checkSideConditions
426   = baleOut (derivingThingErr cls cls_tys (mkTyConApp tycon tc_args) err)
427
428   | otherwise 
429   = ASSERT( null cls_tys )
430     do  { loc <- getSrcSpanM
431         ; eqn <- mk_data_eqn loc orig tvs cls tycon tc_args rep_tc rep_tc_args
432         ; return (Just eqn, Nothing) }
433
434 mk_data_eqn :: SrcSpan -> InstOrigin -> [TyVar] -> Class 
435             -> TyCon -> [TcType] -> TyCon -> [TcType] -> TcM DerivEqn
436 mk_data_eqn loc orig tvs cls tycon tc_args rep_tc rep_tc_args
437   | cls `hasKey` typeableClassKey
438   =     -- The Typeable class is special in several ways
439         --        data T a b = ... deriving( Typeable )
440         -- gives
441         --        instance Typeable2 T where ...
442         -- Notice that:
443         -- 1. There are no constraints in the instance
444         -- 2. There are no type variables either
445         -- 3. The actual class we want to generate isn't necessarily
446         --      Typeable; it depends on the arity of the type
447     do  { real_clas <- tcLookupClass (typeableClassNames !! tyConArity tycon)
448         ; dfun_name <- new_dfun_name real_clas tycon
449         ; return (loc, orig, dfun_name, [], real_clas, mkTyConApp tycon [], []) }
450
451   | otherwise
452   = do  { dfun_name <- new_dfun_name cls tycon
453         ; let ordinary_constraints
454                 = [ mkClassPred cls [arg_ty] 
455                   | data_con <- tyConDataCons rep_tc,
456                     arg_ty   <- dataConInstOrigArgTys data_con rep_tc_args,
457                     not (isUnLiftedType arg_ty) ] -- No constraints for unlifted types?
458
459               tiresome_subst = zipTopTvSubst (tyConTyVars rep_tc) rep_tc_args
460               stupid_constraints = substTheta tiresome_subst (tyConStupidTheta rep_tc)
461                  -- see note [Data decl contexts] above
462
463         ; return (loc, orig, dfun_name, tvs, cls, mkTyConApp tycon tc_args, 
464                   stupid_constraints ++ ordinary_constraints)
465         }
466
467 ------------------------------------------------------------------
468 -- Check side conditions that dis-allow derivability for particular classes
469 -- This is *apart* from the newtype-deriving mechanism
470 --
471 -- Here we get the representation tycon in case of family instances as it has
472 -- the data constructors - but we need to be careful to fall back to the
473 -- family tycon (with indexes) in error messages.
474
475 checkSideConditions :: Bool -> Class -> [TcType] -> TyCon -> Maybe SDoc
476 checkSideConditions gla_exts cls cls_tys rep_tc
477   | notNull cls_tys     
478   = Just ty_args_why    -- e.g. deriving( Foo s )
479   | otherwise
480   = case [cond | (key,cond) <- sideConditions, key == getUnique cls] of
481         []     -> Just (non_std_why cls)
482         [cond] -> cond (gla_exts, rep_tc)
483         other  -> pprPanic "checkSideConditions" (ppr cls)
484   where
485     ty_args_why = quotes (ppr (mkClassPred cls cls_tys)) <+> ptext SLIT("is not a class")
486
487 non_std_why cls = quotes (ppr cls) <+> ptext SLIT("is not a derivable class")
488
489 sideConditions :: [(Unique, Condition)]
490 sideConditions
491   = [   (eqClassKey,       cond_std),
492         (ordClassKey,      cond_std),
493         (readClassKey,     cond_std),
494         (showClassKey,     cond_std),
495         (enumClassKey,     cond_std `andCond` cond_isEnumeration),
496         (ixClassKey,       cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
497         (boundedClassKey,  cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
498         (typeableClassKey, cond_glaExts `andCond` cond_typeableOK),
499         (dataClassKey,     cond_glaExts `andCond` cond_std)
500     ]
501
502 type Condition = (Bool, TyCon) -> Maybe SDoc
503         -- Bool is gla-exts flag
504         -- TyCon is the *representation* tycon if the 
505         --      data type is an indexed one
506         -- Nothing => OK
507
508 orCond :: Condition -> Condition -> Condition
509 orCond c1 c2 tc 
510   = case c1 tc of
511         Nothing -> Nothing              -- c1 succeeds
512         Just x  -> case c2 tc of        -- c1 fails
513                      Nothing -> Nothing
514                      Just y  -> Just (x $$ ptext SLIT("  and") $$ y)
515                                         -- Both fail
516
517 andCond c1 c2 tc = case c1 tc of
518                      Nothing -> c2 tc   -- c1 succeeds
519                      Just x  -> Just x  -- c1 fails
520
521 cond_std :: Condition
522 cond_std (gla_exts, rep_tc)
523   | any (not . isVanillaDataCon) data_cons = Just existential_why     
524   | null data_cons                         = Just no_cons_why
525   | otherwise                              = Nothing
526   where
527     data_cons       = tyConDataCons rep_tc
528     no_cons_why     = quotes (pprSourceTyCon rep_tc) <+> 
529                       ptext SLIT("has no data constructors")
530     existential_why = quotes (pprSourceTyCon rep_tc) <+> 
531                       ptext SLIT("has non-Haskell-98 constructor(s)")
532   
533 cond_isEnumeration :: Condition
534 cond_isEnumeration (gla_exts, rep_tc)
535   | isEnumerationTyCon rep_tc = Nothing
536   | otherwise                 = Just why
537   where
538     why = quotes (pprSourceTyCon rep_tc) <+> 
539           ptext SLIT("has non-nullary constructors")
540
541 cond_isProduct :: Condition
542 cond_isProduct (gla_exts, rep_tc)
543   | isProductTyCon rep_tc = Nothing
544   | otherwise             = Just why
545   where
546     why = quotes (pprSourceTyCon rep_tc) <+> 
547           ptext SLIT("has more than one constructor")
548
549 cond_typeableOK :: Condition
550 -- OK for Typeable class
551 -- Currently: (a) args all of kind *
552 --            (b) 7 or fewer args
553 cond_typeableOK (gla_exts, rep_tc)
554   | tyConArity rep_tc > 7       = Just too_many
555   | not (all (isSubArgTypeKind . tyVarKind) (tyConTyVars rep_tc)) 
556                                 = Just bad_kind
557   | isFamInstTyCon rep_tc       = Just fam_inst  -- no Typable for family insts
558   | otherwise                   = Nothing
559   where
560     too_many = quotes (pprSourceTyCon rep_tc) <+> 
561                ptext SLIT("has too many arguments")
562     bad_kind = quotes (pprSourceTyCon rep_tc) <+> 
563                ptext SLIT("has arguments of kind other than `*'")
564     fam_inst = quotes (pprSourceTyCon rep_tc) <+> 
565                ptext SLIT("is a type family")
566
567 cond_glaExts :: Condition
568 cond_glaExts (gla_exts, _rep_tc) | gla_exts  = Nothing
569                                  | otherwise = Just why
570   where
571     why  = ptext SLIT("You need -fglasgow-exts to derive an instance for this class")
572
573 std_class_via_iso clas  -- These standard classes can be derived for a newtype
574                         -- using the isomorphism trick *even if no -fglasgow-exts*
575   = classKey clas `elem`  [eqClassKey, ordClassKey, ixClassKey, boundedClassKey]
576         -- Not Read/Show because they respect the type
577         -- Not Enum, because newtypes are never in Enum
578
579
580 new_dfun_name clas tycon        -- Just a simple wrapper
581   = newDFunName clas [mkTyConApp tycon []] (getSrcSpan tycon)
582         -- The type passed to newDFunName is only used to generate
583         -- a suitable string; hence the empty type arg list
584 \end{code}
585
586
587 %************************************************************************
588 %*                                                                      *
589                 Deriving newtypes
590 %*                                                                      *
591 %************************************************************************
592
593 \begin{code}
594 mkNewTypeEqn orig gla_exts overlap_flag tvs cls cls_tys
595              tycon tc_args 
596              rep_tycon rep_tc_args
597   | can_derive_via_isomorphism && (gla_exts || std_class_via_iso cls)
598   = do  { traceTc (text "newtype deriving:" <+> ppr tycon <+> ppr rep_tys)
599         ;       -- Go ahead and use the isomorphism
600            dfun_name <- new_dfun_name cls tycon
601         ; return (Nothing, Just (InstInfo { iSpec  = mk_inst_spec dfun_name,
602                                             iBinds = NewTypeDerived ntd_info })) }
603
604   | isNothing mb_std_err        -- Use the standard H98 method
605   = do  { loc <- getSrcSpanM
606         ; eqn <- mk_data_eqn loc orig tvs cls tycon tc_args rep_tycon rep_tc_args
607         ; return (Just eqn, Nothing) }
608
609         -- Otherwise we can't derive
610   | gla_exts  = baleOut cant_derive_err -- Too hard
611   | otherwise = baleOut std_err         -- Just complain about being a non-std instance
612   where
613         mb_std_err = checkSideConditions gla_exts cls cls_tys rep_tycon
614         std_err = derivingThingErr cls cls_tys tc_app $
615                   vcat [fromJust mb_std_err,
616                         ptext SLIT("Try -fglasgow-exts for GHC's newtype-deriving extension")]
617
618         -- Here is the plan for newtype derivings.  We see
619         --        newtype T a1...an = MkT (t ak+1...an) deriving (.., C s1 .. sm, ...)
620         -- where t is a type,
621         --       ak+1...an is a suffix of a1..an, and are all tyars
622         --       ak+1...an do not occur free in t, nor in the s1..sm
623         --       (C s1 ... sm) is a  *partial applications* of class C 
624         --                      with the last parameter missing
625         --       (T a1 .. ak) matches the kind of C's last argument
626         --              (and hence so does t)
627         --
628         -- We generate the instance
629         --       instance forall ({a1..ak} u fvs(s1..sm)).
630         --                C s1 .. sm t => C s1 .. sm (T a1...ak)
631         -- where T a1...ap is the partial application of 
632         --       the LHS of the correct kind and p >= k
633         --
634         --      NB: the variables below are:
635         --              tc_tvs = [a1, ..., an]
636         --              tyvars_to_keep = [a1, ..., ak]
637         --              rep_ty = t ak .. an
638         --              deriv_tvs = fvs(s1..sm) \ tc_tvs
639         --              tys = [s1, ..., sm]
640         --              rep_fn' = t
641         --
642         -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
643         -- We generate the instance
644         --      instance Monad (ST s) => Monad (T s) where 
645
646         cls_tyvars = classTyVars cls
647         kind = tyVarKind (last cls_tyvars)
648                 -- Kind of the thing we want to instance
649                 --   e.g. argument kind of Monad, *->*
650
651         (arg_kinds, _) = splitKindFunTys kind
652         n_args_to_drop = length arg_kinds       
653                 -- Want to drop 1 arg from (T s a) and (ST s a)
654                 -- to get       instance Monad (ST s) => Monad (T s)
655
656         -- Note [newtype representation]
657         -- Need newTyConRhs *not* newTyConRep to get the representation 
658         -- type, because the latter looks through all intermediate newtypes
659         -- For example
660         --      newtype B = MkB Int
661         --      newtype A = MkA B deriving( Num )
662         -- We want the Num instance of B, *not* the Num instance of Int,
663         -- when making the Num instance of A!
664         rep_ty                = newTyConInstRhs rep_tycon rep_tc_args
665         (rep_fn, rep_ty_args) = tcSplitAppTys rep_ty
666
667         n_tyargs_to_keep = tyConArity tycon - n_args_to_drop
668         dropped_tc_args = drop n_tyargs_to_keep tc_args
669         dropped_tvs     = tyVarsOfTypes dropped_tc_args
670
671         n_args_to_keep = length rep_ty_args - n_args_to_drop
672         args_to_drop   = drop n_args_to_keep rep_ty_args
673         args_to_keep   = take n_args_to_keep rep_ty_args
674
675         rep_fn'  = mkAppTys rep_fn args_to_keep
676         rep_tys  = cls_tys ++ [rep_fn']
677         rep_pred = mkClassPred cls rep_tys
678                 -- rep_pred is the representation dictionary, from where
679                 -- we are gong to get all the methods for the newtype
680                 -- dictionary 
681
682         tc_app = mkTyConApp tycon (take n_tyargs_to_keep tc_args)
683
684     -- Next we figure out what superclass dictionaries to use
685     -- See Note [Newtype deriving superclasses] above
686
687         inst_tys = cls_tys ++ [tc_app]
688         sc_theta = substTheta (zipOpenTvSubst cls_tyvars inst_tys)
689                               (classSCTheta cls)
690
691                 -- If there are no tyvars, there's no need
692                 -- to abstract over the dictionaries we need
693                 -- Example:     newtype T = MkT Int deriving( C )
694                 -- We get the derived instance
695                 --              instance C T
696                 -- rather than
697                 --              instance C Int => C T
698         dict_tvs = filterOut (`elemVarSet` dropped_tvs) tvs
699         all_preds = rep_pred : sc_theta         -- NB: rep_pred comes first
700         (dict_args, ntd_info) | null dict_tvs = ([], Just all_preds)
701                               | otherwise     = (all_preds, Nothing)
702
703                 -- Finally! Here's where we build the dictionary Id
704         mk_inst_spec dfun_name = mkLocalInstance dfun overlap_flag
705           where
706             dfun = mkDictFunId dfun_name dict_tvs dict_args cls inst_tys
707
708         -------------------------------------------------------------------
709         --  Figuring out whether we can only do this newtype-deriving thing
710
711         right_arity = length cls_tys + 1 == classArity cls
712
713                 -- Never derive Read,Show,Typeable,Data this way 
714         non_iso_classes = [readClassKey, showClassKey, typeableClassKey, dataClassKey]
715         can_derive_via_isomorphism
716            =  not (getUnique cls `elem` non_iso_classes)
717            && right_arity                       -- Well kinded;
718                                                 -- eg not: newtype T ... deriving( ST )
719                                                 --      because ST needs *2* type params
720            && n_tyargs_to_keep >= 0             -- Type constructor has right kind:
721                                                 -- eg not: newtype T = T Int deriving( Monad )
722            && n_args_to_keep   >= 0             -- Rep type has right kind: 
723                                                 -- eg not: newtype T a = T Int deriving( Monad )
724            && eta_ok                            -- Eta reduction works
725            && not (isRecursiveTyCon tycon)      -- Does not work for recursive tycons:
726                                                 --      newtype A = MkA [A]
727                                                 -- Don't want
728                                                 --      instance Eq [A] => Eq A !!
729                         -- Here's a recursive newtype that's actually OK
730                         --      newtype S1 = S1 [T1 ()]
731                         --      newtype T1 a = T1 (StateT S1 IO a ) deriving( Monad )
732                         -- It's currently rejected.  Oh well.
733                         -- In fact we generate an instance decl that has method of form
734                         --      meth @ instTy = meth @ repTy
735                         -- (no coerce's).  We'd need a coerce if we wanted to handle
736                         -- recursive newtypes too
737
738         -- Check that eta reduction is OK
739         eta_ok = (args_to_drop `tcEqTypes` dropped_tc_args)
740                 -- (a) the dropped-off args are identical in the source and rep type
741                 --        newtype T a b = MkT (S [a] b) deriving( Monad )
742                 --     Here the 'b' must be the same in the rep type (S [a] b)
743
744               && (tyVarsOfType rep_fn' `disjointVarSet` dropped_tvs)
745                 -- (b) the remaining type args do not mention any of the dropped
746                 --     type variables 
747
748               && (tyVarsOfTypes cls_tys `disjointVarSet` dropped_tvs)
749                 -- (c) the type class args do not mention any of the dropped type
750                 --     variables 
751
752               && all isTyVarTy dropped_tc_args
753                 -- (d) in case of newtype family instances, the eta-dropped
754                 --      arguments must be type variables (not more complex indexes)
755
756         cant_derive_err = derivingThingErr cls cls_tys tc_app
757                                 (vcat [ptext SLIT("even with cunning newtype deriving:"),
758                                         if isRecursiveTyCon tycon then
759                                           ptext SLIT("the newtype may be recursive")
760                                         else empty,
761                                         if not right_arity then 
762                                           quotes (ppr (mkClassPred cls cls_tys)) <+> ptext SLIT("does not have arity 1")
763                                         else empty,
764                                         if not (n_tyargs_to_keep >= 0) then 
765                                           ptext SLIT("the type constructor has wrong kind")
766                                         else if not (n_args_to_keep >= 0) then
767                                           ptext SLIT("the representation type has wrong kind")
768                                         else if not eta_ok then 
769                                           ptext SLIT("the eta-reduction property does not hold")
770                                         else empty
771                                       ])
772 \end{code}
773
774
775 %************************************************************************
776 %*                                                                      *
777 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
778 %*                                                                      *
779 %************************************************************************
780
781 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
782 terms, which is the final correct RHS for the corresponding original
783 equation.
784 \begin{itemize}
785 \item
786 Each (k,TyVarTy tv) in a solution constrains only a type
787 variable, tv.
788
789 \item
790 The (k,TyVarTy tv) pairs in a solution are canonically
791 ordered by sorting on type varible, tv, (major key) and then class, k,
792 (minor key)
793 \end{itemize}
794
795 \begin{code}
796 solveDerivEqns :: OverlapFlag
797                -> [DerivEqn]
798                -> TcM [Instance]-- Solns in same order as eqns.
799                                 -- This bunch is Absolutely minimal...
800
801 solveDerivEqns overlap_flag orig_eqns
802   = do  { traceTc (text "solveDerivEqns" <+> vcat (map pprDerivEqn orig_eqns))
803         ; iterateDeriv 1 initial_solutions }
804   where
805         -- The initial solutions for the equations claim that each
806         -- instance has an empty context; this solution is certainly
807         -- in canonical form.
808     initial_solutions :: [DerivSoln]
809     initial_solutions = [ [] | _ <- orig_eqns ]
810
811     ------------------------------------------------------------------
812         -- iterateDeriv calculates the next batch of solutions,
813         -- compares it with the current one; finishes if they are the
814         -- same, otherwise recurses with the new solutions.
815         -- It fails if any iteration fails
816     iterateDeriv :: Int -> [DerivSoln] -> TcM [Instance]
817     iterateDeriv n current_solns
818       | n > 20  -- Looks as if we are in an infinite loop
819                 -- This can happen if we have -fallow-undecidable-instances
820                 -- (See TcSimplify.tcSimplifyDeriv.)
821       = pprPanic "solveDerivEqns: probable loop" 
822                  (vcat (map pprDerivEqn orig_eqns) $$ ppr current_solns)
823       | otherwise
824       = let 
825             inst_specs = zipWithEqual "add_solns" mk_inst_spec 
826                                       orig_eqns current_solns
827         in
828         checkNoErrs (
829                   -- Extend the inst info from the explicit instance decls
830                   -- with the current set of solutions, and simplify each RHS
831             extendLocalInstEnv inst_specs $
832             mappM gen_soln orig_eqns
833         )                               `thenM` \ new_solns ->
834         if (current_solns == new_solns) then
835             returnM inst_specs
836         else
837             iterateDeriv (n+1) new_solns
838
839     ------------------------------------------------------------------
840     gen_soln :: DerivEqn -> TcM [PredType]
841     gen_soln (loc, orig, _, tyvars, clas, inst_ty, deriv_rhs)
842       = setSrcSpan loc  $
843         do { theta <- tcSimplifyDeriv orig tyvars deriv_rhs
844            ; addErrCtxt (derivInstCtxt theta clas [inst_ty]) $ 
845         do { checkNoErrs (checkValidInstance tyvars theta clas [inst_ty])
846                 -- See Note [Deriving context]
847                 -- If this fails, don't continue
848
849                   -- Check for a bizarre corner case, when the derived instance decl should
850                   -- have form  instance C a b => D (T a) where ...
851                   -- Note that 'b' isn't a parameter of T.  This gives rise to all sorts
852                   -- of problems; in particular, it's hard to compare solutions for
853                   -- equality when finding the fixpoint.  So I just rule it out for now.
854            ; let tv_set = mkVarSet tyvars
855                  weird_preds = [pred | pred <- theta, not (tyVarsOfPred pred `subVarSet` tv_set)]  
856            ; mapM_ (addErrTc . badDerivedPred) weird_preds      
857
858                 -- Claim: the result instance declaration is guaranteed valid
859                 -- Hence no need to call:
860                 --   checkValidInstance tyvars theta clas inst_tys
861            ; return (sortLe (<=) theta) } }     -- Canonicalise before returning the solution
862
863     ------------------------------------------------------------------
864     mk_inst_spec :: DerivEqn -> DerivSoln -> Instance
865     mk_inst_spec (loc, orig, dfun_name, tyvars, clas, inst_ty, _) theta
866         = mkLocalInstance dfun overlap_flag
867         where
868           dfun = mkDictFunId dfun_name tyvars theta clas [inst_ty]
869
870 extendLocalInstEnv :: [Instance] -> TcM a -> TcM a
871 -- Add new locally-defined instances; don't bother to check
872 -- for functional dependency errors -- that'll happen in TcInstDcls
873 extendLocalInstEnv dfuns thing_inside
874  = do { env <- getGblEnv
875       ; let  inst_env' = extendInstEnvList (tcg_inst_env env) dfuns 
876              env'      = env { tcg_inst_env = inst_env' }
877       ; setGblEnv env' thing_inside }
878 \end{code}
879
880 Note [Deriving context]
881 ~~~~~~~~~~~~~~~~~~~~~~~
882 With -fglasgow-exts, we allow things like (C Int a) in the simplified
883 context for a derived instance declaration, because at a use of this
884 instance, we might know that a=Bool, and have an instance for (C Int
885 Bool)
886
887 We nevertheless insist that each predicate meets the termination
888 conditions. If not, the deriving mechanism generates larger and larger
889 constraints.  Example:
890   data Succ a = S a
891   data Seq a = Cons a (Seq (Succ a)) | Nil deriving Show
892
893 Note the lack of a Show instance for Succ.  First we'll generate
894   instance (Show (Succ a), Show a) => Show (Seq a)
895 and then
896   instance (Show (Succ (Succ a)), Show (Succ a), Show a) => Show (Seq a)
897 and so on.  Instead we want to complain of no instance for (Show (Succ a)).
898   
899
900 %************************************************************************
901 %*                                                                      *
902 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
903 %*                                                                      *
904 %************************************************************************
905
906 After all the trouble to figure out the required context for the
907 derived instance declarations, all that's left is to chug along to
908 produce them.  They will then be shoved into @tcInstDecls2@, which
909 will do all its usual business.
910
911 There are lots of possibilities for code to generate.  Here are
912 various general remarks.
913
914 PRINCIPLES:
915 \begin{itemize}
916 \item
917 We want derived instances of @Eq@ and @Ord@ (both v common) to be
918 ``you-couldn't-do-better-by-hand'' efficient.
919
920 \item
921 Deriving @Show@---also pretty common--- should also be reasonable good code.
922
923 \item
924 Deriving for the other classes isn't that common or that big a deal.
925 \end{itemize}
926
927 PRAGMATICS:
928
929 \begin{itemize}
930 \item
931 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
932
933 \item
934 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
935
936 \item
937 We {\em normally} generate code only for the non-defaulted methods;
938 there are some exceptions for @Eq@ and (especially) @Ord@...
939
940 \item
941 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
942 constructor's numeric (@Int#@) tag.  These are generated by
943 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
944 these is around is given by @hasCon2TagFun@.
945
946 The examples under the different sections below will make this
947 clearer.
948
949 \item
950 Much less often (really just for deriving @Ix@), we use a
951 @_tag2con_<tycon>@ function.  See the examples.
952
953 \item
954 We use the renamer!!!  Reason: we're supposed to be
955 producing @LHsBinds Name@ for the methods, but that means
956 producing correctly-uniquified code on the fly.  This is entirely
957 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
958 So, instead, we produce @MonoBinds RdrName@ then heave 'em through
959 the renamer.  What a great hack!
960 \end{itemize}
961
962 \begin{code}
963 -- Generate the InstInfo for the required instance paired with the
964 --   *representation* tycon for that instance,
965 -- plus any auxiliary bindings required
966 --
967 -- Representation tycons differ from the tycon in the instance signature in
968 -- case of instances for indexed families.
969 --
970 genInst :: Instance -> TcM ((InstInfo, TyCon), LHsBinds RdrName)
971 genInst spec
972   = do  { fix_env <- getFixityEnv
973         ; let
974             (tyvars,_,clas,[ty])    = instanceHead spec
975             clas_nm                 = className clas
976             (visible_tycon, tyArgs) = tcSplitTyConApp ty 
977
978           -- In case of a family instance, we need to use the representation
979           -- tycon (after all, it has the data constructors)
980         ; (tycon, _) <- tcLookupFamInst visible_tycon tyArgs
981         ; let (meth_binds, aux_binds) = genDerivBinds clas fix_env tycon
982
983         -- Bring the right type variables into 
984         -- scope, and rename the method binds
985         -- It's a bit yukky that we return *renamed* InstInfo, but
986         -- *non-renamed* auxiliary bindings
987         ; (rn_meth_binds, _fvs) <- discardWarnings $ 
988                                    bindLocalNames (map Var.varName tyvars) $
989                                    rnMethodBinds clas_nm (\n -> []) [] meth_binds
990
991         -- Build the InstInfo
992         ; return ((InstInfo { iSpec = spec, 
993                               iBinds = VanillaInst rn_meth_binds [] }, tycon),
994                   aux_binds)
995         }
996
997 genDerivBinds clas fix_env tycon
998   | className clas `elem` typeableClassNames
999   = (gen_Typeable_binds tycon, emptyLHsBinds)
1000
1001   | otherwise
1002   = case assocMaybe gen_list (getUnique clas) of
1003         Just gen_fn -> gen_fn fix_env tycon
1004         Nothing     -> pprPanic "genDerivBinds: bad derived class" (ppr clas)
1005   where
1006     gen_list :: [(Unique, FixityEnv -> TyCon -> (LHsBinds RdrName, LHsBinds RdrName))]
1007     gen_list = [(eqClassKey,      no_aux_binds (ignore_fix_env gen_Eq_binds))
1008                ,(ordClassKey,     no_aux_binds (ignore_fix_env gen_Ord_binds))
1009                ,(enumClassKey,    no_aux_binds (ignore_fix_env gen_Enum_binds))
1010                ,(boundedClassKey, no_aux_binds (ignore_fix_env gen_Bounded_binds))
1011                ,(ixClassKey,      no_aux_binds (ignore_fix_env gen_Ix_binds))
1012                ,(typeableClassKey,no_aux_binds (ignore_fix_env gen_Typeable_binds))
1013                ,(showClassKey,    no_aux_binds gen_Show_binds)
1014                ,(readClassKey,    no_aux_binds gen_Read_binds)
1015                ,(dataClassKey,    gen_Data_binds)
1016                ]
1017
1018       -- no_aux_binds is used for generators that don't 
1019       -- need to produce any auxiliary bindings
1020     no_aux_binds f fix_env tc = (f fix_env tc, emptyLHsBinds)
1021     ignore_fix_env f fix_env tc = f tc
1022 \end{code}
1023
1024
1025 %************************************************************************
1026 %*                                                                      *
1027 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
1028 %*                                                                      *
1029 %************************************************************************
1030
1031
1032 data Foo ... = ...
1033
1034 con2tag_Foo :: Foo ... -> Int#
1035 tag2con_Foo :: Int -> Foo ...   -- easier if Int, not Int#
1036 maxtag_Foo  :: Int              -- ditto (NB: not unlifted)
1037
1038
1039 We have a @con2tag@ function for a tycon if:
1040 \begin{itemize}
1041 \item
1042 We're deriving @Eq@ and the tycon has nullary data constructors.
1043
1044 \item
1045 Or: we're deriving @Ord@ (unless single-constructor), @Enum@, @Ix@
1046 (enum type only????)
1047 \end{itemize}
1048
1049 We have a @tag2con@ function for a tycon if:
1050 \begin{itemize}
1051 \item
1052 We're deriving @Enum@, or @Ix@ (enum type only???)
1053 \end{itemize}
1054
1055 If we have a @tag2con@ function, we also generate a @maxtag@ constant.
1056
1057 \begin{code}
1058 genTaggeryBinds :: [(InstInfo, TyCon)] -> TcM (LHsBinds RdrName)
1059 genTaggeryBinds infos
1060   = do  { names_so_far <- foldlM do_con2tag []           tycons_of_interest
1061         ; nm_alist_etc <- foldlM do_tag2con names_so_far tycons_of_interest
1062         ; return (listToBag (map gen_tag_n_con_monobind nm_alist_etc)) }
1063   where
1064     all_CTs                 = [ (fst (simpleInstInfoClsTy info), tc) 
1065                               | (info, tc) <- infos]
1066     all_tycons              = map snd all_CTs
1067     (tycons_of_interest, _) = removeDups compare all_tycons
1068     
1069     do_con2tag acc_Names tycon
1070       | isDataTyCon tycon &&
1071         ((we_are_deriving eqClassKey tycon
1072             && any isNullarySrcDataCon (tyConDataCons tycon))
1073          || (we_are_deriving ordClassKey  tycon
1074             && not (isProductTyCon tycon))
1075          || (we_are_deriving enumClassKey tycon)
1076          || (we_are_deriving ixClassKey   tycon))
1077         
1078       = returnM ((con2tag_RDR tycon, tycon, GenCon2Tag)
1079                    : acc_Names)
1080       | otherwise
1081       = returnM acc_Names
1082
1083     do_tag2con acc_Names tycon
1084       | isDataTyCon tycon &&
1085          (we_are_deriving enumClassKey tycon ||
1086           we_are_deriving ixClassKey   tycon
1087           && isEnumerationTyCon tycon)
1088       = returnM ( (tag2con_RDR tycon, tycon, GenTag2Con)
1089                  : (maxtag_RDR  tycon, tycon, GenMaxTag)
1090                  : acc_Names)
1091       | otherwise
1092       = returnM acc_Names
1093
1094     we_are_deriving clas_key tycon
1095       = is_in_eqns clas_key tycon all_CTs
1096       where
1097         is_in_eqns clas_key tycon [] = False
1098         is_in_eqns clas_key tycon ((c,t):cts)
1099           =  (clas_key == classKey c && tycon == t)
1100           || is_in_eqns clas_key tycon cts
1101 \end{code}
1102
1103 \begin{code}
1104 derivingThingErr clas tys ty why
1105   = sep [hsep [ptext SLIT("Can't make a derived instance of"), 
1106                quotes (ppr pred)],
1107          nest 2 (parens why)]
1108   where
1109     pred = mkClassPred clas (tys ++ [ty])
1110
1111 standaloneCtxt :: LHsType Name -> SDoc
1112 standaloneCtxt ty = ptext SLIT("In the stand-alone deriving instance for") <+> quotes (ppr ty)
1113
1114 derivInstCtxt theta clas inst_tys
1115   = hang (ptext SLIT("In the derived instance:"))
1116          2 (pprThetaArrow theta <+> pprClassPred clas inst_tys)
1117 -- Used for the ...Thetas variants; all top level
1118
1119 badDerivedPred pred
1120   = vcat [ptext SLIT("Can't derive instances where the instance context mentions"),
1121           ptext SLIT("type variables that are not data type parameters"),
1122           nest 2 (ptext SLIT("Offending constraint:") <+> ppr pred)]
1123 \end{code}
1124
1125