Improve error reports for kind checking (Trac #2994)
[ghc-hetmet.git] / compiler / typecheck / TcTyClsDecls.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The AQUA Project, Glasgow University, 1996-1998
4 %
5
6 TcTyClsDecls: Typecheck type and class declarations
7
8 \begin{code}
9 module TcTyClsDecls (
10         tcTyAndClassDecls, tcFamInstDecl, mkAuxBinds
11     ) where
12
13 #include "HsVersions.h"
14
15 import HsSyn
16 import HsTypes
17 import HscTypes
18 import BuildTyCl
19 import TcUnify
20 import TcRnMonad
21 import TcEnv
22 import TcTyDecls
23 import TcClassDcl
24 import TcHsType
25 import TcMType
26 import TcType
27 import TysWiredIn       ( unitTy )
28 import FunDeps
29 import Type
30 import Generics
31 import Class
32 import TyCon
33 import DataCon
34 import Id
35 import MkId             ( rEC_SEL_ERROR_ID )
36 import IdInfo
37 import Var
38 import VarSet
39 import Name
40 import OccName
41 import Outputable
42 import Maybes
43 import Monad
44 import Unify
45 import Util
46 import SrcLoc
47 import ListSetOps
48 import Digraph
49 import DynFlags
50 import FastString
51 import Unique           ( mkBuiltinUnique )
52 import BasicTypes
53
54 import Bag
55 import Data.List
56 import Control.Monad    ( mplus )
57 \end{code}
58
59
60 %************************************************************************
61 %*                                                                      *
62 \subsection{Type checking for type and class declarations}
63 %*                                                                      *
64 %************************************************************************
65
66 Dealing with a group
67 ~~~~~~~~~~~~~~~~~~~~
68 Consider a mutually-recursive group, binding 
69 a type constructor T and a class C.
70
71 Step 1:         getInitialKind
72         Construct a KindEnv by binding T and C to a kind variable 
73
74 Step 2:         kcTyClDecl
75         In that environment, do a kind check
76
77 Step 3: Zonk the kinds
78
79 Step 4:         buildTyConOrClass
80         Construct an environment binding T to a TyCon and C to a Class.
81         a) Their kinds comes from zonking the relevant kind variable
82         b) Their arity (for synonyms) comes direct from the decl
83         c) The funcional dependencies come from the decl
84         d) The rest comes a knot-tied binding of T and C, returned from Step 4
85         e) The variances of the tycons in the group is calculated from 
86                 the knot-tied stuff
87
88 Step 5:         tcTyClDecl1
89         In this environment, walk over the decls, constructing the TyCons and Classes.
90         This uses in a strict way items (a)-(c) above, which is why they must
91         be constructed in Step 4. Feed the results back to Step 4.
92         For this step, pass the is-recursive flag as the wimp-out flag
93         to tcTyClDecl1.
94         
95
96 Step 6:         Extend environment
97         We extend the type environment with bindings not only for the TyCons and Classes,
98         but also for their "implicit Ids" like data constructors and class selectors
99
100 Step 7:         checkValidTyCl
101         For a recursive group only, check all the decls again, just
102         to check all the side conditions on validity.  We could not
103         do this before because we were in a mutually recursive knot.
104
105 Identification of recursive TyCons
106 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
107 The knot-tying parameters: @rec_details_list@ is an alist mapping @Name@s to
108 @TyThing@s.
109
110 Identifying a TyCon as recursive serves two purposes
111
112 1.  Avoid infinite types.  Non-recursive newtypes are treated as
113 "transparent", like type synonyms, after the type checker.  If we did
114 this for all newtypes, we'd get infinite types.  So we figure out for
115 each newtype whether it is "recursive", and add a coercion if so.  In
116 effect, we are trying to "cut the loops" by identifying a loop-breaker.
117
118 2.  Avoid infinite unboxing.  This is nothing to do with newtypes.
119 Suppose we have
120         data T = MkT Int T
121         f (MkT x t) = f t
122 Well, this function diverges, but we don't want the strictness analyser
123 to diverge.  But the strictness analyser will diverge because it looks
124 deeper and deeper into the structure of T.   (I believe there are
125 examples where the function does something sane, and the strictness
126 analyser still diverges, but I can't see one now.)
127
128 Now, concerning (1), the FC2 branch currently adds a coercion for ALL
129 newtypes.  I did this as an experiment, to try to expose cases in which
130 the coercions got in the way of optimisations.  If it turns out that we
131 can indeed always use a coercion, then we don't risk recursive types,
132 and don't need to figure out what the loop breakers are.
133
134 For newtype *families* though, we will always have a coercion, so they
135 are always loop breakers!  So you can easily adjust the current
136 algorithm by simply treating all newtype families as loop breakers (and
137 indeed type families).  I think.
138
139 \begin{code}
140 tcTyAndClassDecls :: ModDetails -> [LTyClDecl Name]
141                    -> TcM (TcGblEnv,         -- Input env extended by types and classes 
142                                              -- and their implicit Ids,DataCons
143                            HsValBinds Name)  -- Renamed bindings for record selectors
144 -- Fails if there are any errors
145
146 tcTyAndClassDecls boot_details allDecls
147   = checkNoErrs $       -- The code recovers internally, but if anything gave rise to
148                         -- an error we'd better stop now, to avoid a cascade
149     do  {       -- Omit instances of type families; they are handled together
150                 -- with the *heads* of class instances
151         ; let decls = filter (not . isFamInstDecl . unLoc) allDecls
152
153                 -- First check for cyclic type synonysm or classes
154                 -- See notes with checkCycleErrs
155         ; checkCycleErrs decls
156         ; mod <- getModule
157         ; traceTc (text "tcTyAndCl" <+> ppr mod)
158         ; (syn_tycons, alg_tyclss) <- fixM (\ ~(_rec_syn_tycons, rec_alg_tyclss) ->
159           do    { let { -- Seperate ordinary synonyms from all other type and
160                         -- class declarations and add all associated type
161                         -- declarations from type classes.  The latter is
162                         -- required so that the temporary environment for the
163                         -- knot includes all associated family declarations.
164                       ; (syn_decls, alg_decls) = partition (isSynDecl . unLoc)
165                                                    decls
166                       ; alg_at_decls           = concatMap addATs alg_decls
167                       }
168                         -- Extend the global env with the knot-tied results
169                         -- for data types and classes
170                         -- 
171                         -- We must populate the environment with the loop-tied
172                         -- T's right away, because the kind checker may "fault
173                         -- in" some type  constructors that recursively
174                         -- mention T
175                 ; let gbl_things = mkGlobalThings alg_at_decls rec_alg_tyclss
176                 ; tcExtendRecEnv gbl_things $ do
177
178                         -- Kind-check the declarations
179                 { (kc_syn_decls, kc_alg_decls) <- kcTyClDecls syn_decls alg_decls
180
181                 ; let { -- Calculate rec-flag
182                       ; calc_rec  = calcRecFlags boot_details rec_alg_tyclss
183                       ; tc_decl   = addLocM (tcTyClDecl calc_rec) }
184
185                         -- Type-check the type synonyms, and extend the envt
186                 ; syn_tycons <- tcSynDecls kc_syn_decls
187                 ; tcExtendGlobalEnv syn_tycons $ do
188
189                         -- Type-check the data types and classes
190                 { alg_tyclss <- mapM tc_decl kc_alg_decls
191                 ; return (syn_tycons, concat alg_tyclss)
192             }}})
193         -- Finished with knot-tying now
194         -- Extend the environment with the finished things
195         ; tcExtendGlobalEnv (syn_tycons ++ alg_tyclss) $ do
196
197         -- Perform the validity check
198         { traceTc (text "ready for validity check")
199         ; mapM_ (addLocM checkValidTyCl) decls
200         ; traceTc (text "done")
201    
202         -- Add the implicit things;
203         -- we want them in the environment because 
204         -- they may be mentioned in interface files
205         -- NB: All associated types and their implicit things will be added a
206         --     second time here.  This doesn't matter as the definitions are
207         --     the same.
208         ; let { implicit_things = concatMap implicitTyThings alg_tyclss
209               ; aux_binds       = mkAuxBinds alg_tyclss }
210         ; traceTc ((text "Adding" <+> ppr alg_tyclss) 
211                    $$ (text "and" <+> ppr implicit_things))
212         ; env <- tcExtendGlobalEnv implicit_things getGblEnv
213         ; return (env, aux_binds) }
214     }
215   where
216     -- Pull associated types out of class declarations, to tie them into the
217     -- knot above.  
218     -- NB: We put them in the same place in the list as `tcTyClDecl' will
219     --     eventually put the matching `TyThing's.  That's crucial; otherwise,
220     --     the two argument lists of `mkGlobalThings' don't match up.
221     addATs decl@(L _ (ClassDecl {tcdATs = ats})) = decl : ats
222     addATs decl                                  = [decl]
223
224 mkGlobalThings :: [LTyClDecl Name]      -- The decls
225                -> [TyThing]             -- Knot-tied, in 1-1 correspondence with the decls
226                -> [(Name,TyThing)]
227 -- Driven by the Decls, and treating the TyThings lazily
228 -- make a TypeEnv for the new things
229 mkGlobalThings decls things
230   = map mk_thing (decls `zipLazy` things)
231   where
232     mk_thing (L _ (ClassDecl {tcdLName = L _ name}), ~(AClass cl))
233          = (name, AClass cl)
234     mk_thing (L _ decl, ~(ATyCon tc))
235          = (tcdName decl, ATyCon tc)
236 \end{code}
237
238
239 %************************************************************************
240 %*                                                                      *
241                Type checking family instances
242 %*                                                                      *
243 %************************************************************************
244
245 Family instances are somewhat of a hybrid.  They are processed together with
246 class instance heads, but can contain data constructors and hence they share a
247 lot of kinding and type checking code with ordinary algebraic data types (and
248 GADTs).
249
250 \begin{code}
251 tcFamInstDecl :: LTyClDecl Name -> TcM TyThing
252 tcFamInstDecl (L loc decl)
253   =     -- Prime error recovery, set source location
254     setSrcSpan loc                              $
255     tcAddDeclCtxt decl                          $
256     do { -- type families require -XTypeFamilies and can't be in an
257          -- hs-boot file
258        ; type_families <- doptM Opt_TypeFamilies
259        ; is_boot  <- tcIsHsBoot   -- Are we compiling an hs-boot file?
260        ; checkTc type_families $ badFamInstDecl (tcdLName decl)
261        ; checkTc (not is_boot) $ badBootFamInstDeclErr
262
263          -- Perform kind and type checking
264        ; tc <- tcFamInstDecl1 decl
265        ; checkValidTyCon tc     -- Remember to check validity;
266                                 -- no recursion to worry about here
267        ; return (ATyCon tc) }
268
269 tcFamInstDecl1 :: TyClDecl Name -> TcM TyCon
270
271   -- "type instance"
272 tcFamInstDecl1 (decl@TySynonym {tcdLName = L loc tc_name})
273   = kcIdxTyPats decl $ \k_tvs k_typats resKind family ->
274     do { -- check that the family declaration is for a synonym
275          unless (isSynTyCon family) $
276            addErr (wrongKindOfFamily family)
277
278        ; -- (1) kind check the right-hand side of the type equation
279        ; k_rhs <- kcCheckLHsType (tcdSynRhs decl) resKind
280
281          -- we need the exact same number of type parameters as the family
282          -- declaration 
283        ; let famArity = tyConArity family
284        ; checkTc (length k_typats == famArity) $ 
285            wrongNumberOfParmsErr famArity
286
287          -- (2) type check type equation
288        ; tcTyVarBndrs k_tvs $ \t_tvs -> do {  -- turn kinded into proper tyvars
289        ; t_typats <- mapM tcHsKindedType k_typats
290        ; t_rhs    <- tcHsKindedType k_rhs
291
292          -- (3) check the well-formedness of the instance
293        ; checkValidTypeInst t_typats t_rhs
294
295          -- (4) construct representation tycon
296        ; rep_tc_name <- newFamInstTyConName tc_name loc
297        ; buildSynTyCon rep_tc_name t_tvs (SynonymTyCon t_rhs) 
298                        (typeKind t_rhs) (Just (family, t_typats))
299        }}
300
301   -- "newtype instance" and "data instance"
302 tcFamInstDecl1 (decl@TyData {tcdND = new_or_data, tcdLName = L loc tc_name,
303                              tcdCons = cons})
304   = kcIdxTyPats decl $ \k_tvs k_typats resKind fam_tycon ->
305     do { -- check that the family declaration is for the right kind
306          unless (isAlgTyCon fam_tycon) $
307            addErr (wrongKindOfFamily fam_tycon)
308
309        ; -- (1) kind check the data declaration as usual
310        ; k_decl <- kcDataDecl decl k_tvs
311        ; let k_ctxt = tcdCtxt k_decl
312              k_cons = tcdCons k_decl
313
314          -- result kind must be '*' (otherwise, we have too few patterns)
315        ; checkTc (isLiftedTypeKind resKind) $ tooFewParmsErr (tyConArity fam_tycon)
316
317          -- (2) type check indexed data type declaration
318        ; tcTyVarBndrs k_tvs $ \t_tvs -> do {  -- turn kinded into proper tyvars
319        ; unbox_strict <- doptM Opt_UnboxStrictFields
320
321          -- kind check the type indexes and the context
322        ; t_typats     <- mapM tcHsKindedType k_typats
323        ; stupid_theta <- tcHsKindedContext k_ctxt
324
325          -- (3) Check that
326          --     (a) left-hand side contains no type family applications
327          --         (vanilla synonyms are fine, though, and we checked for
328          --         foralls earlier)
329        ; mapM_ checkTyFamFreeness t_typats
330
331          --     (b) a newtype has exactly one constructor
332        ; checkTc (new_or_data == DataType || isSingleton k_cons) $
333                  newtypeConError tc_name (length k_cons)
334
335          -- (4) construct representation tycon
336        ; rep_tc_name <- newFamInstTyConName tc_name loc
337        ; let ex_ok = True       -- Existentials ok for type families!
338        ; fixM (\ rep_tycon -> do 
339              { let orig_res_ty = mkTyConApp fam_tycon t_typats
340              ; data_cons <- tcConDecls unbox_strict ex_ok rep_tycon
341                                        (t_tvs, orig_res_ty) k_cons
342              ; tc_rhs <-
343                  case new_or_data of
344                    DataType -> return (mkDataTyConRhs data_cons)
345                    NewType  -> ASSERT( not (null data_cons) )
346                                mkNewTyConRhs rep_tc_name rep_tycon (head data_cons)
347              ; buildAlgTyCon rep_tc_name t_tvs stupid_theta tc_rhs Recursive
348                              False h98_syntax (Just (fam_tycon, t_typats))
349                  -- We always assume that indexed types are recursive.  Why?
350                  -- (1) Due to their open nature, we can never be sure that a
351                  -- further instance might not introduce a new recursive
352                  -- dependency.  (2) They are always valid loop breakers as
353                  -- they involve a coercion.
354              })
355        }}
356        where
357          h98_syntax = case cons of      -- All constructors have same shape
358                         L _ (ConDecl { con_res = ResTyGADT _ }) : _ -> False
359                         _ -> True
360
361 tcFamInstDecl1 d = pprPanic "tcFamInstDecl1" (ppr d)
362
363 -- Kind checking of indexed types
364 -- -
365
366 -- Kind check type patterns and kind annotate the embedded type variables.
367 --
368 -- * Here we check that a type instance matches its kind signature, but we do
369 --   not check whether there is a pattern for each type index; the latter
370 --   check is only required for type synonym instances.
371
372 kcIdxTyPats :: TyClDecl Name
373             -> ([LHsTyVarBndr Name] -> [LHsType Name] -> Kind -> TyCon -> TcM a)
374                -- ^^kinded tvs         ^^kinded ty pats  ^^res kind
375             -> TcM a
376 kcIdxTyPats decl thing_inside
377   = kcHsTyVars (tcdTyVars decl) $ \tvs -> 
378     do { fam_tycon <- tcLookupLocatedTyCon (tcdLName decl)
379        ; let { (kinds, resKind) = splitKindFunTys (tyConKind fam_tycon)
380              ; hs_typats        = fromJust $ tcdTyPats decl }
381
382          -- we may not have more parameters than the kind indicates
383        ; checkTc (length kinds >= length hs_typats) $
384            tooManyParmsErr (tcdLName decl)
385
386          -- type functions can have a higher-kinded result
387        ; let resultKind = mkArrowKinds (drop (length hs_typats) kinds) resKind
388        ; typats <- zipWithM kcCheckLHsType hs_typats kinds
389        ; thing_inside tvs typats resultKind fam_tycon
390        }
391   where
392 \end{code}
393
394
395 %************************************************************************
396 %*                                                                      *
397                 Kind checking
398 %*                                                                      *
399 %************************************************************************
400
401 We need to kind check all types in the mutually recursive group
402 before we know the kind of the type variables.  For example:
403
404 class C a where
405    op :: D b => a -> b -> b
406
407 class D c where
408    bop :: (Monad c) => ...
409
410 Here, the kind of the locally-polymorphic type variable "b"
411 depends on *all the uses of class D*.  For example, the use of
412 Monad c in bop's type signature means that D must have kind Type->Type.
413
414 However type synonyms work differently.  They can have kinds which don't
415 just involve (->) and *:
416         type R = Int#           -- Kind #
417         type S a = Array# a     -- Kind * -> #
418         type T a b = (# a,b #)  -- Kind * -> * -> (# a,b #)
419 So we must infer their kinds from their right-hand sides *first* and then
420 use them, whereas for the mutually recursive data types D we bring into
421 scope kind bindings D -> k, where k is a kind variable, and do inference.
422
423 Type families
424 ~~~~~~~~~~~~~
425 This treatment of type synonyms only applies to Haskell 98-style synonyms.
426 General type functions can be recursive, and hence, appear in `alg_decls'.
427
428 The kind of a type family is solely determinded by its kind signature;
429 hence, only kind signatures participate in the construction of the initial
430 kind environment (as constructed by `getInitialKind').  In fact, we ignore
431 instances of families altogether in the following.  However, we need to
432 include the kinds of associated families into the construction of the
433 initial kind environment.  (This is handled by `allDecls').
434
435 \begin{code}
436 kcTyClDecls :: [LTyClDecl Name] -> [Located (TyClDecl Name)]
437             -> TcM ([LTyClDecl Name], [Located (TyClDecl Name)])
438 kcTyClDecls syn_decls alg_decls
439   = do  {       -- First extend the kind env with each data type, class, and
440                 -- indexed type, mapping them to a type variable
441           let initialKindDecls = concat [allDecls decl | L _ decl <- alg_decls]
442         ; alg_kinds <- mapM getInitialKind initialKindDecls
443         ; tcExtendKindEnv alg_kinds $ do
444
445                 -- Now kind-check the type synonyms, in dependency order
446                 -- We do these differently to data type and classes,
447                 -- because a type synonym can be an unboxed type
448                 --      type Foo = Int#
449                 -- and a kind variable can't unify with UnboxedTypeKind
450                 -- So we infer their kinds in dependency order
451         { (kc_syn_decls, syn_kinds) <- kcSynDecls (calcSynCycles syn_decls)
452         ; tcExtendKindEnv syn_kinds $  do
453
454                 -- Now kind-check the data type, class, and kind signatures,
455                 -- returning kind-annotated decls; we don't kind-check
456                 -- instances of indexed types yet, but leave this to
457                 -- `tcInstDecls1'
458         { kc_alg_decls <- mapM (wrapLocM kcTyClDecl)
459                             (filter (not . isFamInstDecl . unLoc) alg_decls)
460
461         ; return (kc_syn_decls, kc_alg_decls) }}}
462   where
463     -- get all declarations relevant for determining the initial kind
464     -- environment
465     allDecls (decl@ClassDecl {tcdATs = ats}) = decl : [ at 
466                                                       | L _ at <- ats
467                                                       , isFamilyDecl at]
468     allDecls decl | isFamInstDecl decl = []
469                   | otherwise          = [decl]
470
471 ------------------------------------------------------------------------
472 getInitialKind :: TyClDecl Name -> TcM (Name, TcKind)
473 -- Only for data type, class, and indexed type declarations
474 -- Get as much info as possible from the data, class, or indexed type decl,
475 -- so as to maximise usefulness of error messages
476 getInitialKind decl
477   = do  { arg_kinds <- mapM (mk_arg_kind . unLoc) (tyClDeclTyVars decl)
478         ; res_kind  <- mk_res_kind decl
479         ; return (tcdName decl, mkArrowKinds arg_kinds res_kind) }
480   where
481     mk_arg_kind (UserTyVar _)        = newKindVar
482     mk_arg_kind (KindedTyVar _ kind) = return kind
483
484     mk_res_kind (TyFamily { tcdKind    = Just kind }) = return kind
485     mk_res_kind (TyData   { tcdKindSig = Just kind }) = return kind
486         -- On GADT-style declarations we allow a kind signature
487         --      data T :: *->* where { ... }
488     mk_res_kind _ = return liftedTypeKind
489
490
491 ----------------
492 kcSynDecls :: [SCC (LTyClDecl Name)] 
493            -> TcM ([LTyClDecl Name],    -- Kind-annotated decls
494                    [(Name,TcKind)])     -- Kind bindings
495 kcSynDecls []
496   = return ([], [])
497 kcSynDecls (group : groups)
498   = do  { (decl,  nk)  <- kcSynDecl group
499         ; (decls, nks) <- tcExtendKindEnv [nk] (kcSynDecls groups)
500         ; return (decl:decls, nk:nks) }
501                         
502 ----------------
503 kcSynDecl :: SCC (LTyClDecl Name) 
504            -> TcM (LTyClDecl Name,      -- Kind-annotated decls
505                    (Name,TcKind))       -- Kind bindings
506 kcSynDecl (AcyclicSCC (L loc decl))
507   = tcAddDeclCtxt decl  $
508     kcHsTyVars (tcdTyVars decl) (\ k_tvs ->
509     do { traceTc (text "kcd1" <+> ppr (unLoc (tcdLName decl)) <+> brackets (ppr (tcdTyVars decl)) 
510                         <+> brackets (ppr k_tvs))
511        ; (k_rhs, rhs_kind) <- kcLHsType (tcdSynRhs decl)
512        ; traceTc (text "kcd2" <+> ppr (unLoc (tcdLName decl)))
513        ; let tc_kind = foldr (mkArrowKind . kindedTyVarKind) rhs_kind k_tvs
514        ; return (L loc (decl { tcdTyVars = k_tvs, tcdSynRhs = k_rhs }),
515                  (unLoc (tcdLName decl), tc_kind)) })
516
517 kcSynDecl (CyclicSCC decls)
518   = do { recSynErr decls; failM }       -- Fail here to avoid error cascade
519                                         -- of out-of-scope tycons
520
521 kindedTyVarKind :: LHsTyVarBndr Name -> Kind
522 kindedTyVarKind (L _ (KindedTyVar _ k)) = k
523 kindedTyVarKind x = pprPanic "kindedTyVarKind" (ppr x)
524
525 ------------------------------------------------------------------------
526 kcTyClDecl :: TyClDecl Name -> TcM (TyClDecl Name)
527         -- Not used for type synonyms (see kcSynDecl)
528
529 kcTyClDecl decl@(TyData {})
530   = ASSERT( not . isFamInstDecl $ decl )   -- must not be a family instance
531     kcTyClDeclBody decl $
532       kcDataDecl decl
533
534 kcTyClDecl decl@(TyFamily {})
535   = kcFamilyDecl [] decl      -- the empty list signals a toplevel decl      
536
537 kcTyClDecl decl@(ClassDecl {tcdCtxt = ctxt, tcdSigs = sigs, tcdATs = ats})
538   = kcTyClDeclBody decl $ \ tvs' ->
539     do  { ctxt' <- kcHsContext ctxt     
540         ; ats'  <- mapM (wrapLocM (kcFamilyDecl tvs')) ats
541         ; sigs' <- mapM (wrapLocM kc_sig) sigs
542         ; return (decl {tcdTyVars = tvs', tcdCtxt = ctxt', tcdSigs = sigs',
543                         tcdATs = ats'}) }
544   where
545     kc_sig (TypeSig nm op_ty) = do { op_ty' <- kcHsLiftedSigType op_ty
546                                    ; return (TypeSig nm op_ty') }
547     kc_sig other_sig          = return other_sig
548
549 kcTyClDecl decl@(ForeignType {})
550   = return decl
551
552 kcTyClDecl (TySynonym {}) = panic "kcTyClDecl TySynonym"
553
554 kcTyClDeclBody :: TyClDecl Name
555                -> ([LHsTyVarBndr Name] -> TcM a)
556                -> TcM a
557 -- getInitialKind has made a suitably-shaped kind for the type or class
558 -- Unpack it, and attribute those kinds to the type variables
559 -- Extend the env with bindings for the tyvars, taken from
560 -- the kind of the tycon/class.  Give it to the thing inside, and 
561 -- check the result kind matches
562 kcTyClDeclBody decl thing_inside
563   = tcAddDeclCtxt decl          $
564     do  { tc_ty_thing <- tcLookupLocated (tcdLName decl)
565         ; let tc_kind    = case tc_ty_thing of
566                            AThing k -> k
567                            _ -> pprPanic "kcTyClDeclBody" (ppr tc_ty_thing)
568               (kinds, _) = splitKindFunTys tc_kind
569               hs_tvs     = tcdTyVars decl
570               kinded_tvs = ASSERT( length kinds >= length hs_tvs )
571                            [ L loc (KindedTyVar (hsTyVarName tv) k)
572                            | (L loc tv, k) <- zip hs_tvs kinds]
573         ; tcExtendKindEnvTvs kinded_tvs (thing_inside kinded_tvs) }
574
575 -- Kind check a data declaration, assuming that we already extended the
576 -- kind environment with the type variables of the left-hand side (these
577 -- kinded type variables are also passed as the second parameter).
578 --
579 kcDataDecl :: TyClDecl Name -> [LHsTyVarBndr Name] -> TcM (TyClDecl Name)
580 kcDataDecl decl@(TyData {tcdND = new_or_data, tcdCtxt = ctxt, tcdCons = cons})
581            tvs
582   = do  { ctxt' <- kcHsContext ctxt     
583         ; cons' <- mapM (wrapLocM kc_con_decl) cons
584         ; return (decl {tcdTyVars = tvs, tcdCtxt = ctxt', tcdCons = cons'}) }
585   where
586     -- doc comments are typechecked to Nothing here
587     kc_con_decl (ConDecl name expl ex_tvs ex_ctxt details res _) 
588       = addErrCtxt (dataConCtxt name)   $ 
589         kcHsTyVars ex_tvs $ \ex_tvs' -> do
590         do { ex_ctxt' <- kcHsContext ex_ctxt
591            ; details' <- kc_con_details details 
592            ; res'     <- case res of
593                 ResTyH98 -> return ResTyH98
594                 ResTyGADT ty -> do { ty' <- kcHsSigType ty; return (ResTyGADT ty') }
595            ; return (ConDecl name expl ex_tvs' ex_ctxt' details' res' Nothing) }
596
597     kc_con_details (PrefixCon btys) 
598         = do { btys' <- mapM kc_larg_ty btys 
599              ; return (PrefixCon btys') }
600     kc_con_details (InfixCon bty1 bty2) 
601         = do { bty1' <- kc_larg_ty bty1
602              ; bty2' <- kc_larg_ty bty2
603              ; return (InfixCon bty1' bty2') }
604     kc_con_details (RecCon fields) 
605         = do { fields' <- mapM kc_field fields
606              ; return (RecCon fields') }
607
608     kc_field (ConDeclField fld bty d) = do { bty' <- kc_larg_ty bty
609                                            ; return (ConDeclField fld bty' d) }
610
611     kc_larg_ty bty = case new_or_data of
612                         DataType -> kcHsSigType bty
613                         NewType  -> kcHsLiftedSigType bty
614         -- Can't allow an unlifted type for newtypes, because we're effectively
615         -- going to remove the constructor while coercing it to a lifted type.
616         -- And newtypes can't be bang'd
617 kcDataDecl d _ = pprPanic "kcDataDecl" (ppr d)
618
619 -- Kind check a family declaration or type family default declaration.
620 --
621 kcFamilyDecl :: [LHsTyVarBndr Name]  -- tyvars of enclosing class decl if any
622              -> TyClDecl Name -> TcM (TyClDecl Name)
623 kcFamilyDecl classTvs decl@(TyFamily {tcdKind = kind})
624   = kcTyClDeclBody decl $ \tvs' ->
625     do { mapM_ unifyClassParmKinds tvs'
626        ; return (decl {tcdTyVars = tvs', 
627                        tcdKind = kind `mplus` Just liftedTypeKind})
628                        -- default result kind is '*'
629        }
630   where
631     unifyClassParmKinds (L _ (KindedTyVar n k))
632       | Just classParmKind <- lookup n classTyKinds = unifyKind k classParmKind
633       | otherwise                                   = return ()
634     unifyClassParmKinds x = pprPanic "kcFamilyDecl/unifyClassParmKinds" (ppr x)
635     classTyKinds = [(n, k) | L _ (KindedTyVar n k) <- classTvs]
636 kcFamilyDecl _ (TySynonym {})              -- type family defaults
637   = panic "TcTyClsDecls.kcFamilyDecl: not implemented yet"
638 kcFamilyDecl _ d = pprPanic "kcFamilyDecl" (ppr d)
639 \end{code}
640
641
642 %************************************************************************
643 %*                                                                      *
644 \subsection{Type checking}
645 %*                                                                      *
646 %************************************************************************
647
648 \begin{code}
649 tcSynDecls :: [LTyClDecl Name] -> TcM [TyThing]
650 tcSynDecls [] = return []
651 tcSynDecls (decl : decls) 
652   = do { syn_tc <- addLocM tcSynDecl decl
653        ; syn_tcs <- tcExtendGlobalEnv [syn_tc] (tcSynDecls decls)
654        ; return (syn_tc : syn_tcs) }
655
656   -- "type"
657 tcSynDecl :: TyClDecl Name -> TcM TyThing
658 tcSynDecl
659   (TySynonym {tcdLName = L _ tc_name, tcdTyVars = tvs, tcdSynRhs = rhs_ty})
660   = tcTyVarBndrs tvs            $ \ tvs' -> do 
661     { traceTc (text "tcd1" <+> ppr tc_name) 
662     ; rhs_ty' <- tcHsKindedType rhs_ty
663     ; tycon <- buildSynTyCon tc_name tvs' (SynonymTyCon rhs_ty') 
664                              (typeKind rhs_ty') Nothing
665     ; return (ATyCon tycon) 
666     }
667 tcSynDecl d = pprPanic "tcSynDecl" (ppr d)
668
669 --------------------
670 tcTyClDecl :: (Name -> RecFlag) -> TyClDecl Name -> TcM [TyThing]
671
672 tcTyClDecl calc_isrec decl
673   = tcAddDeclCtxt decl (tcTyClDecl1 calc_isrec decl)
674
675   -- "type family" declarations
676 tcTyClDecl1 :: (Name -> RecFlag) -> TyClDecl Name -> TcM [TyThing]
677 tcTyClDecl1 _calc_isrec 
678   (TyFamily {tcdFlavour = TypeFamily, 
679              tcdLName = L _ tc_name, tcdTyVars = tvs,
680              tcdKind = Just kind}) -- NB: kind at latest added during kind checking
681   = tcTyVarBndrs tvs  $ \ tvs' -> do 
682   { traceTc (text "type family: " <+> ppr tc_name) 
683
684         -- Check that we don't use families without -XTypeFamilies
685   ; idx_tys <- doptM Opt_TypeFamilies
686   ; checkTc idx_tys $ badFamInstDecl tc_name
687
688         -- Check for no type indices
689   ; checkTc (not (null tvs)) (noIndexTypes tc_name)
690
691   ; tycon <- buildSynTyCon tc_name tvs' (OpenSynTyCon kind Nothing) kind Nothing
692   ; return [ATyCon tycon]
693   }
694
695   -- "data family" declaration
696 tcTyClDecl1 _calc_isrec 
697   (TyFamily {tcdFlavour = DataFamily, 
698              tcdLName = L _ tc_name, tcdTyVars = tvs, tcdKind = mb_kind})
699   = tcTyVarBndrs tvs  $ \ tvs' -> do 
700   { traceTc (text "data family: " <+> ppr tc_name) 
701   ; extra_tvs <- tcDataKindSig mb_kind
702   ; let final_tvs = tvs' ++ extra_tvs    -- we may not need these
703
704
705         -- Check that we don't use families without -XTypeFamilies
706   ; idx_tys <- doptM Opt_TypeFamilies
707   ; checkTc idx_tys $ badFamInstDecl tc_name
708
709         -- Check for no type indices
710   ; checkTc (not (null tvs)) (noIndexTypes tc_name)
711
712   ; tycon <- buildAlgTyCon tc_name final_tvs [] 
713                mkOpenDataTyConRhs Recursive False True Nothing
714   ; return [ATyCon tycon]
715   }
716
717   -- "newtype" and "data"
718   -- NB: not used for newtype/data instances (whether associated or not)
719 tcTyClDecl1 calc_isrec
720   (TyData {tcdND = new_or_data, tcdCtxt = ctxt, tcdTyVars = tvs,
721            tcdLName = L _ tc_name, tcdKindSig = mb_ksig, tcdCons = cons})
722   = tcTyVarBndrs tvs    $ \ tvs' -> do 
723   { extra_tvs <- tcDataKindSig mb_ksig
724   ; let final_tvs = tvs' ++ extra_tvs
725   ; stupid_theta <- tcHsKindedContext ctxt
726   ; want_generic <- doptM Opt_Generics
727   ; unbox_strict <- doptM Opt_UnboxStrictFields
728   ; empty_data_decls <- doptM Opt_EmptyDataDecls
729   ; kind_signatures <- doptM Opt_KindSignatures
730   ; existential_ok <- doptM Opt_ExistentialQuantification
731   ; gadt_ok      <- doptM Opt_GADTs
732   ; is_boot      <- tcIsHsBoot  -- Are we compiling an hs-boot file?
733   ; let ex_ok = existential_ok || gadt_ok       -- Data cons can have existential context
734
735         -- Check that we don't use GADT syntax in H98 world
736   ; checkTc (gadt_ok || h98_syntax) (badGadtDecl tc_name)
737
738         -- Check that we don't use kind signatures without Glasgow extensions
739   ; checkTc (kind_signatures || isNothing mb_ksig) (badSigTyDecl tc_name)
740
741         -- Check that the stupid theta is empty for a GADT-style declaration
742   ; checkTc (null stupid_theta || h98_syntax) (badStupidTheta tc_name)
743
744         -- Check that a newtype has exactly one constructor
745         -- Do this before checking for empty data decls, so that
746         -- we don't suggest -XEmptyDataDecls for newtypes
747   ; checkTc (new_or_data == DataType || isSingleton cons) 
748             (newtypeConError tc_name (length cons))
749
750         -- Check that there's at least one condecl,
751         -- or else we're reading an hs-boot file, or -XEmptyDataDecls
752   ; checkTc (not (null cons) || empty_data_decls || is_boot)
753             (emptyConDeclsErr tc_name)
754     
755   ; tycon <- fixM (\ tycon -> do 
756         { let res_ty = mkTyConApp tycon (mkTyVarTys final_tvs)
757         ; data_cons <- tcConDecls unbox_strict ex_ok 
758                                   tycon (final_tvs, res_ty) cons
759         ; tc_rhs <-
760             if null cons && is_boot     -- In a hs-boot file, empty cons means
761             then return AbstractTyCon   -- "don't know"; hence Abstract
762             else case new_or_data of
763                    DataType -> return (mkDataTyConRhs data_cons)
764                    NewType  -> ASSERT( not (null data_cons) )
765                                mkNewTyConRhs tc_name tycon (head data_cons)
766         ; buildAlgTyCon tc_name final_tvs stupid_theta tc_rhs is_rec
767             (want_generic && canDoGenerics data_cons) h98_syntax Nothing
768         })
769   ; return [ATyCon tycon]
770   }
771   where
772     is_rec   = calc_isrec tc_name
773     h98_syntax = case cons of   -- All constructors have same shape
774                         L _ (ConDecl { con_res = ResTyGADT _ }) : _ -> False
775                         _ -> True
776
777 tcTyClDecl1 calc_isrec 
778   (ClassDecl {tcdLName = L _ class_name, tcdTyVars = tvs, 
779               tcdCtxt = ctxt, tcdMeths = meths,
780               tcdFDs = fundeps, tcdSigs = sigs, tcdATs = ats} )
781   = tcTyVarBndrs tvs            $ \ tvs' -> do 
782   { ctxt' <- tcHsKindedContext ctxt
783   ; fds' <- mapM (addLocM tc_fundep) fundeps
784   ; atss <- mapM (addLocM (tcTyClDecl1 (const Recursive))) ats
785             -- NB: 'ats' only contains "type family" and "data family"
786             --     declarations as well as type family defaults
787   ; let ats' = map (setAssocFamilyPermutation tvs') (concat atss)
788   ; sig_stuff <- tcClassSigs class_name sigs meths
789   ; clas <- fixM (\ clas ->
790                 let     -- This little knot is just so we can get
791                         -- hold of the name of the class TyCon, which we
792                         -- need to look up its recursiveness
793                     tycon_name = tyConName (classTyCon clas)
794                     tc_isrec = calc_isrec tycon_name
795                 in
796                 buildClass False {- Must include unfoldings for selectors -}
797                            class_name tvs' ctxt' fds' ats'
798                            sig_stuff tc_isrec)
799   ; return (AClass clas : ats')
800       -- NB: Order is important due to the call to `mkGlobalThings' when
801       --     tying the the type and class declaration type checking knot.
802   }
803   where
804     tc_fundep (tvs1, tvs2) = do { tvs1' <- mapM tcLookupTyVar tvs1 ;
805                                 ; tvs2' <- mapM tcLookupTyVar tvs2 ;
806                                 ; return (tvs1', tvs2') }
807
808 tcTyClDecl1 _
809   (ForeignType {tcdLName = L _ tc_name, tcdExtName = tc_ext_name})
810   = return [ATyCon (mkForeignTyCon tc_name tc_ext_name liftedTypeKind 0)]
811
812 tcTyClDecl1 _ d = pprPanic "tcTyClDecl1" (ppr d)
813
814 -----------------------------------
815 tcConDecls :: Bool -> Bool -> TyCon -> ([TyVar], Type)
816            -> [LConDecl Name] -> TcM [DataCon]
817 tcConDecls unbox ex_ok rep_tycon res_tmpl cons
818   = mapM (addLocM (tcConDecl unbox ex_ok rep_tycon res_tmpl)) cons
819
820 tcConDecl :: Bool               -- True <=> -funbox-strict_fields
821           -> Bool               -- True <=> -XExistentialQuantificaton or -XGADTs
822           -> TyCon              -- Representation tycon
823           -> ([TyVar], Type)    -- Return type template (with its template tyvars)
824           -> ConDecl Name 
825           -> TcM DataCon
826
827 tcConDecl unbox_strict existential_ok rep_tycon res_tmpl        -- Data types
828           (ConDecl name _ tvs ctxt details res_ty _)
829   = addErrCtxt (dataConCtxt name)       $ 
830     tcTyVarBndrs tvs                    $ \ tvs' -> do 
831     { ctxt' <- tcHsKindedContext ctxt
832     ; checkTc (existential_ok || (null tvs && null (unLoc ctxt)))
833               (badExistential name)
834     ; (univ_tvs, ex_tvs, eq_preds, res_ty') <- tcResultType res_tmpl tvs' res_ty
835     ; let 
836         tc_datacon is_infix field_lbls btys
837           = do { (arg_tys, stricts) <- mapAndUnzipM (tcConArg unbox_strict) btys
838                ; buildDataCon (unLoc name) is_infix
839                     stricts field_lbls
840                     univ_tvs ex_tvs eq_preds ctxt' arg_tys
841                     res_ty' rep_tycon }
842                 -- NB:  we put data_tc, the type constructor gotten from the
843                 --      constructor type signature into the data constructor;
844                 --      that way checkValidDataCon can complain if it's wrong.
845
846     ; case details of
847         PrefixCon btys     -> tc_datacon False [] btys
848         InfixCon bty1 bty2 -> tc_datacon True  [] [bty1,bty2]
849         RecCon fields      -> tc_datacon False field_names btys
850                            where
851                               field_names = map (unLoc . cd_fld_name) fields
852                               btys        = map cd_fld_type fields
853     }
854
855 -- Example
856 --   data instance T (b,c) where 
857 --      TI :: forall e. e -> T (e,e)
858 --
859 -- The representation tycon looks like this:
860 --   data :R7T b c where 
861 --      TI :: forall b1 c1. (b1 ~ c1) => b1 -> :R7T b1 c1
862 -- In this case orig_res_ty = T (e,e)
863
864 tcResultType :: ([TyVar], Type) -- Template for result type; e.g.
865                                 -- data instance T [a] b c = ...  
866                                 --      gives template ([a,b,c], T [a] b c)
867              -> [TyVar]         -- where MkT :: forall x y z. ...
868              -> ResType Name
869              -> TcM ([TyVar],           -- Universal
870                      [TyVar],           -- Existential (distinct OccNames from univs)
871                      [(TyVar,Type)],    -- Equality predicates
872                      Type)              -- Typechecked return type
873         -- We don't check that the TyCon given in the ResTy is
874         -- the same as the parent tycon, becuase we are in the middle
875         -- of a recursive knot; so it's postponed until checkValidDataCon
876
877 tcResultType (tmpl_tvs, res_ty) dc_tvs ResTyH98
878   = return (tmpl_tvs, dc_tvs, [], res_ty)
879         -- In H98 syntax the dc_tvs are the existential ones
880         --      data T a b c = forall d e. MkT ...
881         -- The {a,b,c} are tc_tvs, and {d,e} are dc_tvs
882
883 tcResultType (tmpl_tvs, res_tmpl) dc_tvs (ResTyGADT res_ty)
884         -- E.g.  data T [a] b c where
885         --         MkT :: forall x y z. T [(x,y)] z z
886         -- Then we generate
887         --      Univ tyvars     Eq-spec
888         --          a              a~(x,y)
889         --          b              b~z
890         --          z              
891         -- Existentials are the leftover type vars: [x,y]
892         -- So we return ([a,b,z], [x,y], [a~(x,y),b~z], T [(x,y)] z z)
893   = do  { res_ty' <- tcHsKindedType res_ty
894         ; let Just subst = tcMatchTy (mkVarSet tmpl_tvs) res_tmpl res_ty'
895
896                 -- /Lazily/ figure out the univ_tvs etc
897                 -- Each univ_tv is either a dc_tv or a tmpl_tv
898               (univ_tvs, eq_spec) = foldr choose ([], []) tidy_tmpl_tvs
899               choose tmpl (univs, eqs)
900                 | Just ty <- lookupTyVar subst tmpl 
901                 = case tcGetTyVar_maybe ty of
902                     Just tv | not (tv `elem` univs)
903                             -> (tv:univs,   eqs)
904                     _other  -> (tmpl:univs, (tmpl,ty):eqs)
905                 | otherwise = pprPanic "tcResultType" (ppr res_ty)
906               ex_tvs = dc_tvs `minusList` univ_tvs
907
908         ; return (univ_tvs, ex_tvs, eq_spec, res_ty') }
909   where
910         -- NB: tmpl_tvs and dc_tvs are distinct, but
911         -- we want them to be *visibly* distinct, both for
912         -- interface files and general confusion.  So rename
913         -- the tc_tvs, since they are not used yet (no 
914         -- consequential renaming needed)
915     (_, tidy_tmpl_tvs) = mapAccumL tidy_one init_occ_env tmpl_tvs
916     init_occ_env       = initTidyOccEnv (map getOccName dc_tvs)
917     tidy_one env tv    = (env', setTyVarName tv (tidyNameOcc name occ'))
918               where
919                  name = tyVarName tv
920                  (env', occ') = tidyOccName env (getOccName name) 
921
922 -------------------
923 tcConArg :: Bool                -- True <=> -funbox-strict_fields
924            -> LHsType Name
925            -> TcM (TcType, StrictnessMark)
926 tcConArg unbox_strict bty
927   = do  { arg_ty <- tcHsBangType bty
928         ; let bang = getBangStrictness bty
929         ; return (arg_ty, chooseBoxingStrategy unbox_strict arg_ty bang) }
930
931 -- We attempt to unbox/unpack a strict field when either:
932 --   (i)  The field is marked '!!', or
933 --   (ii) The field is marked '!', and the -funbox-strict-fields flag is on.
934 --
935 -- We have turned off unboxing of newtypes because coercions make unboxing 
936 -- and reboxing more complicated
937 chooseBoxingStrategy :: Bool -> TcType -> HsBang -> StrictnessMark
938 chooseBoxingStrategy unbox_strict_fields arg_ty bang
939   = case bang of
940         HsNoBang                                    -> NotMarkedStrict
941         HsStrict | unbox_strict_fields 
942                    && can_unbox arg_ty              -> MarkedUnboxed
943         HsUnbox  | can_unbox arg_ty                 -> MarkedUnboxed
944         _                                           -> MarkedStrict
945   where
946     -- we can unbox if the type is a chain of newtypes with a product tycon
947     -- at the end
948     can_unbox arg_ty = case splitTyConApp_maybe arg_ty of
949                    Nothing                      -> False
950                    Just (arg_tycon, tycon_args) -> 
951                        not (isRecursiveTyCon arg_tycon) &&      -- Note [Recusive unboxing]
952                        isProductTyCon arg_tycon &&
953                        (if isNewTyCon arg_tycon then 
954                             can_unbox (newTyConInstRhs arg_tycon tycon_args)
955                         else True)
956 \end{code}
957
958 Note [Recursive unboxing]
959 ~~~~~~~~~~~~~~~~~~~~~~~~~
960 Be careful not to try to unbox this!
961         data T = MkT !T Int
962 But it's the *argument* type that matters. This is fine:
963         data S = MkS S !Int
964 because Int is non-recursive.
965
966
967 %************************************************************************
968 %*                                                                      *
969                 Validity checking
970 %*                                                                      *
971 %************************************************************************
972
973 Validity checking is done once the mutually-recursive knot has been
974 tied, so we can look at things freely.
975
976 \begin{code}
977 checkCycleErrs :: [LTyClDecl Name] -> TcM ()
978 checkCycleErrs tyclss
979   | null cls_cycles
980   = return ()
981   | otherwise
982   = do  { mapM_ recClsErr cls_cycles
983         ; failM }       -- Give up now, because later checkValidTyCl
984                         -- will loop if the synonym is recursive
985   where
986     cls_cycles = calcClassCycles tyclss
987
988 checkValidTyCl :: TyClDecl Name -> TcM ()
989 -- We do the validity check over declarations, rather than TyThings
990 -- only so that we can add a nice context with tcAddDeclCtxt
991 checkValidTyCl decl
992   = tcAddDeclCtxt decl $
993     do  { thing <- tcLookupLocatedGlobal (tcdLName decl)
994         ; traceTc (text "Validity of" <+> ppr thing)    
995         ; case thing of
996             ATyCon tc -> checkValidTyCon tc
997             AClass cl -> checkValidClass cl 
998             _ -> panic "checkValidTyCl"
999         ; traceTc (text "Done validity of" <+> ppr thing)       
1000         }
1001
1002 -------------------------
1003 -- For data types declared with record syntax, we require
1004 -- that each constructor that has a field 'f' 
1005 --      (a) has the same result type
1006 --      (b) has the same type for 'f'
1007 -- module alpha conversion of the quantified type variables
1008 -- of the constructor.
1009 --
1010 -- Note that we allow existentials to match becuase the
1011 -- fields can never meet. E.g
1012 --      data T where
1013 --        T1 { f1 :: b, f2 :: a, f3 ::Int } :: T
1014 --        T2 { f1 :: c, f2 :: c, f3 ::Int } :: T  
1015 -- Here we do not complain about f1,f2 because they are existential
1016
1017 checkValidTyCon :: TyCon -> TcM ()
1018 checkValidTyCon tc 
1019   | isSynTyCon tc 
1020   = case synTyConRhs tc of
1021       OpenSynTyCon _ _ -> return ()
1022       SynonymTyCon ty  -> checkValidType syn_ctxt ty
1023   | otherwise
1024   = do  -- Check the context on the data decl
1025     checkValidTheta (DataTyCtxt name) (tyConStupidTheta tc)
1026         
1027         -- Check arg types of data constructors
1028     mapM_ (checkValidDataCon tc) data_cons
1029
1030         -- Check that fields with the same name share a type
1031     mapM_ check_fields groups
1032
1033   where
1034     syn_ctxt  = TySynCtxt name
1035     name      = tyConName tc
1036     data_cons = tyConDataCons tc
1037
1038     groups = equivClasses cmp_fld (concatMap get_fields data_cons)
1039     cmp_fld (f1,_) (f2,_) = f1 `compare` f2
1040     get_fields con = dataConFieldLabels con `zip` repeat con
1041         -- dataConFieldLabels may return the empty list, which is fine
1042
1043     -- See Note [GADT record selectors] in MkId.lhs
1044     -- We must check (a) that the named field has the same 
1045     --                   type in each constructor
1046     --               (b) that those constructors have the same result type
1047     --
1048     -- However, the constructors may have differently named type variable
1049     -- and (worse) we don't know how the correspond to each other.  E.g.
1050     --     C1 :: forall a b. { f :: a, g :: b } -> T a b
1051     --     C2 :: forall d c. { f :: c, g :: c } -> T c d
1052     -- 
1053     -- So what we do is to ust Unify.tcMatchTys to compare the first candidate's
1054     -- result type against other candidates' types BOTH WAYS ROUND.
1055     -- If they magically agrees, take the substitution and
1056     -- apply them to the latter ones, and see if they match perfectly.
1057     check_fields ((label, con1) : other_fields)
1058         -- These fields all have the same name, but are from
1059         -- different constructors in the data type
1060         = recoverM (return ()) $ mapM_ checkOne other_fields
1061                 -- Check that all the fields in the group have the same type
1062                 -- NB: this check assumes that all the constructors of a given
1063                 -- data type use the same type variables
1064         where
1065         (tvs1, _, _, res1) = dataConSig con1
1066         ts1 = mkVarSet tvs1
1067         fty1 = dataConFieldType con1 label
1068
1069         checkOne (_, con2)    -- Do it bothways to ensure they are structurally identical
1070             = do { checkFieldCompat label con1 con2 ts1 res1 res2 fty1 fty2
1071                  ; checkFieldCompat label con2 con1 ts2 res2 res1 fty2 fty1 }
1072             where        
1073                 (tvs2, _, _, res2) = dataConSig con2
1074                 ts2 = mkVarSet tvs2
1075                 fty2 = dataConFieldType con2 label
1076     check_fields [] = panic "checkValidTyCon/check_fields []"
1077
1078 checkFieldCompat :: Name -> DataCon -> DataCon -> TyVarSet
1079                  -> Type -> Type -> Type -> Type -> TcM ()
1080 checkFieldCompat fld con1 con2 tvs1 res1 res2 fty1 fty2
1081   = do  { checkTc (isJust mb_subst1) (resultTypeMisMatch fld con1 con2)
1082         ; checkTc (isJust mb_subst2) (fieldTypeMisMatch fld con1 con2) }
1083   where
1084     mb_subst1 = tcMatchTy tvs1 res1 res2
1085     mb_subst2 = tcMatchTyX tvs1 (expectJust "checkFieldCompat" mb_subst1) fty1 fty2
1086
1087 -------------------------------
1088 checkValidDataCon :: TyCon -> DataCon -> TcM ()
1089 checkValidDataCon tc con
1090   = setSrcSpan (srcLocSpan (getSrcLoc con))     $
1091     addErrCtxt (dataConCtxt con)                $ 
1092     do  { let tc_tvs = tyConTyVars tc
1093               res_ty_tmpl = mkFamilyTyConApp tc (mkTyVarTys tc_tvs)
1094               actual_res_ty = dataConOrigResTy con
1095         ; checkTc (isJust (tcMatchTy (mkVarSet tc_tvs)
1096                                 res_ty_tmpl
1097                                 actual_res_ty))
1098                   (badDataConTyCon con res_ty_tmpl actual_res_ty)
1099         ; checkValidMonoType (dataConOrigResTy con)
1100                 -- Disallow MkT :: T (forall a. a->a)
1101                 -- Reason: it's really the argument of an equality constraint
1102         ; checkValidType ctxt (dataConUserType con)
1103         ; when (isNewTyCon tc) (checkNewDataCon con)
1104     }
1105   where
1106     ctxt = ConArgCtxt (dataConName con) 
1107
1108 -------------------------------
1109 checkNewDataCon :: DataCon -> TcM ()
1110 -- Checks for the data constructor of a newtype
1111 checkNewDataCon con
1112   = do  { checkTc (isSingleton arg_tys) (newtypeFieldErr con (length arg_tys))
1113                 -- One argument
1114         ; checkTc (null eq_spec) (newtypePredError con)
1115                 -- Return type is (T a b c)
1116         ; checkTc (null ex_tvs && null eq_theta && null dict_theta) (newtypeExError con)
1117                 -- No existentials
1118         ; checkTc (not (any isMarkedStrict (dataConStrictMarks con))) 
1119                   (newtypeStrictError con)
1120                 -- No strictness
1121     }
1122   where
1123     (_univ_tvs, ex_tvs, eq_spec, eq_theta, dict_theta, arg_tys, _res_ty) = dataConFullSig con
1124
1125 -------------------------------
1126 checkValidClass :: Class -> TcM ()
1127 checkValidClass cls
1128   = do  { constrained_class_methods <- doptM Opt_ConstrainedClassMethods
1129         ; multi_param_type_classes <- doptM Opt_MultiParamTypeClasses
1130         ; fundep_classes <- doptM Opt_FunctionalDependencies
1131
1132         -- Check that the class is unary, unless GlaExs
1133         ; checkTc (notNull tyvars) (nullaryClassErr cls)
1134         ; checkTc (multi_param_type_classes || unary) (classArityErr cls)
1135         ; checkTc (fundep_classes || null fundeps) (classFunDepsErr cls)
1136
1137         -- Check the super-classes
1138         ; checkValidTheta (ClassSCCtxt (className cls)) theta
1139
1140         -- Check the class operations
1141         ; mapM_ (check_op constrained_class_methods) op_stuff
1142
1143         -- Check that if the class has generic methods, then the
1144         -- class has only one parameter.  We can't do generic
1145         -- multi-parameter type classes!
1146         ; checkTc (unary || no_generics) (genericMultiParamErr cls)
1147         }
1148   where
1149     (tyvars, fundeps, theta, _, _, op_stuff) = classExtraBigSig cls
1150     unary       = isSingleton tyvars
1151     no_generics = null [() | (_, GenDefMeth) <- op_stuff]
1152
1153     check_op constrained_class_methods (sel_id, dm) 
1154       = addErrCtxt (classOpCtxt sel_id tau) $ do
1155         { checkValidTheta SigmaCtxt (tail theta)
1156                 -- The 'tail' removes the initial (C a) from the
1157                 -- class itself, leaving just the method type
1158
1159         ; traceTc (text "class op type" <+> ppr op_ty <+> ppr tau)
1160         ; checkValidType (FunSigCtxt op_name) tau
1161
1162                 -- Check that the type mentions at least one of
1163                 -- the class type variables...or at least one reachable
1164                 -- from one of the class variables.  Example: tc223
1165                 --   class Error e => Game b mv e | b -> mv e where
1166                 --      newBoard :: MonadState b m => m ()
1167                 -- Here, MonadState has a fundep m->b, so newBoard is fine
1168         ; let grown_tyvars = grow theta (mkVarSet tyvars)
1169         ; checkTc (tyVarsOfType tau `intersectsVarSet` grown_tyvars)
1170                   (noClassTyVarErr cls sel_id)
1171
1172                 -- Check that for a generic method, the type of 
1173                 -- the method is sufficiently simple
1174         ; checkTc (dm /= GenDefMeth || validGenericMethodType tau)
1175                   (badGenericMethodType op_name op_ty)
1176         }
1177         where
1178           op_name = idName sel_id
1179           op_ty   = idType sel_id
1180           (_,theta1,tau1) = tcSplitSigmaTy op_ty
1181           (_,theta2,tau2)  = tcSplitSigmaTy tau1
1182           (theta,tau) | constrained_class_methods = (theta1 ++ theta2, tau2)
1183                       | otherwise = (theta1, mkPhiTy (tail theta1) tau1)
1184                 -- Ugh!  The function might have a type like
1185                 --      op :: forall a. C a => forall b. (Eq b, Eq a) => tau2
1186                 -- With -XConstrainedClassMethods, we want to allow this, even though the inner 
1187                 -- forall has an (Eq a) constraint.  Whereas in general, each constraint 
1188                 -- in the context of a for-all must mention at least one quantified
1189                 -- type variable.  What a mess!
1190 \end{code}
1191
1192
1193 %************************************************************************
1194 %*                                                                      *
1195                 Building record selectors
1196 %*                                                                      *
1197 %************************************************************************
1198
1199 \begin{code}
1200 mkAuxBinds :: [TyThing] -> HsValBinds Name
1201 mkAuxBinds ty_things
1202   = ValBindsOut [(NonRecursive, b) | b <- binds] sigs
1203   where
1204     (sigs, binds) = unzip rec_sels
1205     rec_sels = map mkRecSelBind [ (tc,fld) 
1206                                 | ATyCon tc <- ty_things 
1207                                 , fld <- tyConFields tc ]
1208
1209
1210 mkRecSelBind :: (TyCon, FieldLabel) -> (LSig Name, LHsBinds Name)
1211 mkRecSelBind (tycon, sel_name)
1212   = (L loc (IdSig sel_id), unitBag (L loc sel_bind))
1213   where
1214     loc = getSrcSpan tycon    
1215     sel_id = Var.mkLocalVar rec_details sel_name sel_ty vanillaIdInfo
1216     rec_details = RecSelId { sel_tycon = tycon, sel_naughty = is_naughty }
1217
1218     -- Find a representative constructor, con1
1219     all_cons = tyConDataCons tycon 
1220     cons_w_field = [ con | con <- all_cons
1221                    , sel_name `elem` dataConFieldLabels con ] 
1222     con1 = ASSERT( not (null cons_w_field) ) head cons_w_field
1223
1224     -- Selector type; Note [Polymorphic selectors]
1225     field_ty = dataConFieldType con1 sel_name
1226     (field_tvs, field_theta, field_tau) 
1227        | is_naughty = ([], [], unitTy)
1228        | otherwise  = tcSplitSigmaTy field_ty
1229     data_ty    = dataConOrigResTy con1
1230     data_tvs   = tyVarsOfType data_ty
1231     is_naughty = not (tyVarsOfType field_ty `subVarSet` data_tvs)  
1232     sel_ty = mkForAllTys (varSetElems data_tvs ++ field_tvs) $ 
1233              mkPhiTy (dataConStupidTheta con1)  $       -- Urgh!
1234              mkPhiTy field_theta                $       -- Urgh!
1235              mkFunTy data_ty field_tau
1236
1237     -- Make the binding: sel (C2 { fld = x }) = x
1238     --                   sel (C7 { fld = x }) = x
1239     --    where cons_w_field = [C2,C7]
1240     sel_bind     = mkFunBind sel_lname (map mk_match cons_w_field ++ deflt)
1241     mk_match con = mkSimpleMatch [L loc (mk_sel_pat con)] 
1242                                  (L loc match_body)
1243     mk_sel_pat con = ConPatIn (L loc (getName con)) (RecCon rec_fields)
1244     rec_fields = HsRecFields { rec_flds = [rec_field], rec_dotdot = Nothing }
1245     rec_field  = HsRecField { hsRecFieldId = sel_lname
1246                             , hsRecFieldArg = nlVarPat field_var
1247                             , hsRecPun = False }
1248     match_body | is_naughty = ExplicitTuple [] Boxed
1249                | otherwise  = HsVar field_var
1250     sel_lname = L loc sel_name
1251     field_var = mkInternalName (mkBuiltinUnique 1) (getOccName sel_name) loc
1252
1253     -- Add catch-all default case unless the case is exhaustive
1254     -- We do this explicitly so that we get a nice error message that
1255     -- mentions this particular record selector
1256     deflt | length cons_w_field == length all_cons = []
1257           | otherwise = [mkSimpleMatch [nlWildPat] 
1258                             (nlHsApp (nlHsVar (getName rEC_SEL_ERROR_ID))
1259                                      (nlHsLit msg_lit))]
1260     msg_lit = HsStringPrim $ mkFastString $ 
1261               occNameString (getOccName sel_name)
1262
1263 ---------------
1264 tyConFields :: TyCon -> [FieldLabel]
1265 tyConFields tc 
1266   | isAlgTyCon tc = nub (concatMap dataConFieldLabels (tyConDataCons tc))
1267   | otherwise     = []
1268 \end{code}
1269
1270 Note [Polymorphic selectors]
1271 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1272 When a record has a polymorphic field, we pull the foralls out to the front.
1273    data T = MkT { f :: forall a. [a] -> a }
1274 Then f :: forall a. T -> [a] -> a
1275 NOT  f :: T -> forall a. [a] -> a
1276
1277 This is horrid.  It's only needed in deeply obscure cases, which I hate.
1278 The only case I know is test tc163, which is worth looking at.  It's far
1279 from clear that this test should succeed at all!
1280
1281 Note [Naughty record selectors]
1282 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1283 A "naughty" field is one for which we can't define a record 
1284 selector, because an existential type variable would escape.  For example:
1285         data T = forall a. MkT { x,y::a }
1286 We obviously can't define       
1287         x (MkT v _) = v
1288 Nevertheless we *do* put a RecSelId into the type environment
1289 so that if the user tries to use 'x' as a selector we can bleat
1290 helpfully, rather than saying unhelpfully that 'x' is not in scope.
1291 Hence the sel_naughty flag, to identify record selectors that don't really exist.
1292
1293 In general, a field is naughty if its type mentions a type variable that
1294 isn't in the result type of the constructor.
1295
1296 We make a dummy binding for naughty selectors, so that they can be treated
1297 uniformly, apart from their sel_naughty field.  The function is never called.
1298
1299 Note [GADT record selectors]
1300 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1301 For GADTs, we require that all constructors with a common field 'f' have the same
1302 result type (modulo alpha conversion).  [Checked in TcTyClsDecls.checkValidTyCon]
1303 E.g. 
1304         data T where
1305           T1 { f :: Maybe a } :: T [a]
1306           T2 { f :: Maybe a, y :: b  } :: T [a]
1307
1308 and now the selector takes that result type as its argument:
1309    f :: forall a. T [a] -> Maybe a
1310
1311 Details: the "real" types of T1,T2 are:
1312    T1 :: forall r a.   (r~[a]) => a -> T r
1313    T2 :: forall r a b. (r~[a]) => a -> b -> T r
1314
1315 So the selector loooks like this:
1316    f :: forall a. T [a] -> Maybe a
1317    f (a:*) (t:T [a])
1318      = case t of
1319          T1 c   (g:[a]~[c]) (v:Maybe c)       -> v `cast` Maybe (right (sym g))
1320          T2 c d (g:[a]~[c]) (v:Maybe c) (w:d) -> v `cast` Maybe (right (sym g))
1321
1322 Note the forall'd tyvars of the selector are just the free tyvars
1323 of the result type; there may be other tyvars in the constructor's
1324 type (e.g. 'b' in T2).
1325
1326 Note the need for casts in the result!
1327
1328 Note [Selector running example]
1329 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1330 It's OK to combine GADTs and type families.  Here's a running example:
1331
1332         data instance T [a] where 
1333           T1 { fld :: b } :: T [Maybe b]
1334
1335 The representation type looks like this
1336         data :R7T a where
1337           T1 { fld :: b } :: :R7T (Maybe b)
1338
1339 and there's coercion from the family type to the representation type
1340         :CoR7T a :: T [a] ~ :R7T a
1341
1342 The selector we want for fld looks like this:
1343
1344         fld :: forall b. T [Maybe b] -> b
1345         fld = /\b. \(d::T [Maybe b]).
1346               case d `cast` :CoR7T (Maybe b) of 
1347                 T1 (x::b) -> x
1348
1349 The scrutinee of the case has type :R7T (Maybe b), which can be
1350 gotten by appying the eq_spec to the univ_tvs of the data con.
1351
1352 %************************************************************************
1353 %*                                                                      *
1354                 Error messages
1355 %*                                                                      *
1356 %************************************************************************
1357
1358 \begin{code}
1359 resultTypeMisMatch :: Name -> DataCon -> DataCon -> SDoc
1360 resultTypeMisMatch field_name con1 con2
1361   = vcat [sep [ptext (sLit "Constructors") <+> ppr con1 <+> ptext (sLit "and") <+> ppr con2, 
1362                 ptext (sLit "have a common field") <+> quotes (ppr field_name) <> comma],
1363           nest 2 $ ptext (sLit "but have different result types")]
1364
1365 fieldTypeMisMatch :: Name -> DataCon -> DataCon -> SDoc
1366 fieldTypeMisMatch field_name con1 con2
1367   = sep [ptext (sLit "Constructors") <+> ppr con1 <+> ptext (sLit "and") <+> ppr con2, 
1368          ptext (sLit "give different types for field"), quotes (ppr field_name)]
1369
1370 dataConCtxt :: Outputable a => a -> SDoc
1371 dataConCtxt con = ptext (sLit "In the definition of data constructor") <+> quotes (ppr con)
1372
1373 classOpCtxt :: Var -> Type -> SDoc
1374 classOpCtxt sel_id tau = sep [ptext (sLit "When checking the class method:"),
1375                               nest 2 (ppr sel_id <+> dcolon <+> ppr tau)]
1376
1377 nullaryClassErr :: Class -> SDoc
1378 nullaryClassErr cls
1379   = ptext (sLit "No parameters for class")  <+> quotes (ppr cls)
1380
1381 classArityErr :: Class -> SDoc
1382 classArityErr cls
1383   = vcat [ptext (sLit "Too many parameters for class") <+> quotes (ppr cls),
1384           parens (ptext (sLit "Use -XMultiParamTypeClasses to allow multi-parameter classes"))]
1385
1386 classFunDepsErr :: Class -> SDoc
1387 classFunDepsErr cls
1388   = vcat [ptext (sLit "Fundeps in class") <+> quotes (ppr cls),
1389           parens (ptext (sLit "Use -XFunctionalDependencies to allow fundeps"))]
1390
1391 noClassTyVarErr :: Class -> Var -> SDoc
1392 noClassTyVarErr clas op
1393   = sep [ptext (sLit "The class method") <+> quotes (ppr op),
1394          ptext (sLit "mentions none of the type variables of the class") <+> 
1395                 ppr clas <+> hsep (map ppr (classTyVars clas))]
1396
1397 genericMultiParamErr :: Class -> SDoc
1398 genericMultiParamErr clas
1399   = ptext (sLit "The multi-parameter class") <+> quotes (ppr clas) <+> 
1400     ptext (sLit "cannot have generic methods")
1401
1402 badGenericMethodType :: Name -> Kind -> SDoc
1403 badGenericMethodType op op_ty
1404   = hang (ptext (sLit "Generic method type is too complex"))
1405        4 (vcat [ppr op <+> dcolon <+> ppr op_ty,
1406                 ptext (sLit "You can only use type variables, arrows, lists, and tuples")])
1407
1408 recSynErr :: [LTyClDecl Name] -> TcRn ()
1409 recSynErr syn_decls
1410   = setSrcSpan (getLoc (head sorted_decls)) $
1411     addErr (sep [ptext (sLit "Cycle in type synonym declarations:"),
1412                  nest 2 (vcat (map ppr_decl sorted_decls))])
1413   where
1414     sorted_decls = sortLocated syn_decls
1415     ppr_decl (L loc decl) = ppr loc <> colon <+> ppr decl
1416
1417 recClsErr :: [Located (TyClDecl Name)] -> TcRn ()
1418 recClsErr cls_decls
1419   = setSrcSpan (getLoc (head sorted_decls)) $
1420     addErr (sep [ptext (sLit "Cycle in class declarations (via superclasses):"),
1421                  nest 2 (vcat (map ppr_decl sorted_decls))])
1422   where
1423     sorted_decls = sortLocated cls_decls
1424     ppr_decl (L loc decl) = ppr loc <> colon <+> ppr (decl { tcdSigs = [] })
1425
1426 sortLocated :: [Located a] -> [Located a]
1427 sortLocated things = sortLe le things
1428   where
1429     le (L l1 _) (L l2 _) = l1 <= l2
1430
1431 badDataConTyCon :: DataCon -> Type -> Type -> SDoc
1432 badDataConTyCon data_con res_ty_tmpl actual_res_ty
1433   = hang (ptext (sLit "Data constructor") <+> quotes (ppr data_con) <+>
1434                 ptext (sLit "returns type") <+> quotes (ppr actual_res_ty))
1435        2 (ptext (sLit "instead of an instance of its parent type") <+> quotes (ppr res_ty_tmpl))
1436
1437 badGadtDecl :: Name -> SDoc
1438 badGadtDecl tc_name
1439   = vcat [ ptext (sLit "Illegal generalised algebraic data declaration for") <+> quotes (ppr tc_name)
1440          , nest 2 (parens $ ptext (sLit "Use -XGADTs to allow GADTs")) ]
1441
1442 badExistential :: Located Name -> SDoc
1443 badExistential con_name
1444   = hang (ptext (sLit "Data constructor") <+> quotes (ppr con_name) <+>
1445                 ptext (sLit "has existential type variables, or a context"))
1446        2 (parens $ ptext (sLit "Use -XExistentialQuantification or -XGADTs to allow this"))
1447
1448 badStupidTheta :: Name -> SDoc
1449 badStupidTheta tc_name
1450   = ptext (sLit "A data type declared in GADT style cannot have a context:") <+> quotes (ppr tc_name)
1451
1452 newtypeConError :: Name -> Int -> SDoc
1453 newtypeConError tycon n
1454   = sep [ptext (sLit "A newtype must have exactly one constructor,"),
1455          nest 2 $ ptext (sLit "but") <+> quotes (ppr tycon) <+> ptext (sLit "has") <+> speakN n ]
1456
1457 newtypeExError :: DataCon -> SDoc
1458 newtypeExError con
1459   = sep [ptext (sLit "A newtype constructor cannot have an existential context,"),
1460          nest 2 $ ptext (sLit "but") <+> quotes (ppr con) <+> ptext (sLit "does")]
1461
1462 newtypeStrictError :: DataCon -> SDoc
1463 newtypeStrictError con
1464   = sep [ptext (sLit "A newtype constructor cannot have a strictness annotation,"),
1465          nest 2 $ ptext (sLit "but") <+> quotes (ppr con) <+> ptext (sLit "does")]
1466
1467 newtypePredError :: DataCon -> SDoc
1468 newtypePredError con
1469   = sep [ptext (sLit "A newtype constructor must have a return type of form T a1 ... an"),
1470          nest 2 $ ptext (sLit "but") <+> quotes (ppr con) <+> ptext (sLit "does not")]
1471
1472 newtypeFieldErr :: DataCon -> Int -> SDoc
1473 newtypeFieldErr con_name n_flds
1474   = sep [ptext (sLit "The constructor of a newtype must have exactly one field"), 
1475          nest 2 $ ptext (sLit "but") <+> quotes (ppr con_name) <+> ptext (sLit "has") <+> speakN n_flds]
1476
1477 badSigTyDecl :: Name -> SDoc
1478 badSigTyDecl tc_name
1479   = vcat [ ptext (sLit "Illegal kind signature") <+>
1480            quotes (ppr tc_name)
1481          , nest 2 (parens $ ptext (sLit "Use -XKindSignatures to allow kind signatures")) ]
1482
1483 noIndexTypes :: Name -> SDoc
1484 noIndexTypes tc_name
1485   = ptext (sLit "Type family constructor") <+> quotes (ppr tc_name)
1486     <+> ptext (sLit "must have at least one type index parameter")
1487
1488 badFamInstDecl :: Outputable a => a -> SDoc
1489 badFamInstDecl tc_name
1490   = vcat [ ptext (sLit "Illegal family instance for") <+>
1491            quotes (ppr tc_name)
1492          , nest 2 (parens $ ptext (sLit "Use -XTypeFamilies to allow indexed type families")) ]
1493
1494 tooManyParmsErr :: Located Name -> SDoc
1495 tooManyParmsErr tc_name
1496   = ptext (sLit "Family instance has too many parameters:") <+> 
1497     quotes (ppr tc_name)
1498
1499 tooFewParmsErr :: Arity -> SDoc
1500 tooFewParmsErr arity
1501   = ptext (sLit "Family instance has too few parameters; expected") <+> 
1502     ppr arity
1503
1504 wrongNumberOfParmsErr :: Arity -> SDoc
1505 wrongNumberOfParmsErr exp_arity
1506   = ptext (sLit "Number of parameters must match family declaration; expected")
1507     <+> ppr exp_arity
1508
1509 badBootFamInstDeclErr :: SDoc
1510 badBootFamInstDeclErr = 
1511   ptext (sLit "Illegal family instance in hs-boot file")
1512
1513 wrongKindOfFamily :: TyCon -> SDoc
1514 wrongKindOfFamily family =
1515   ptext (sLit "Wrong category of family instance; declaration was for a") <+>
1516   kindOfFamily
1517   where
1518     kindOfFamily | isSynTyCon family = ptext (sLit "type synonym")
1519                  | isAlgTyCon family = ptext (sLit "data type")
1520                  | otherwise = pprPanic "wrongKindOfFamily" (ppr family)
1521
1522 emptyConDeclsErr :: Name -> SDoc
1523 emptyConDeclsErr tycon
1524   = sep [quotes (ppr tycon) <+> ptext (sLit "has no constructors"),
1525          nest 2 $ ptext (sLit "(-XEmptyDataDecls permits this)")]
1526 \end{code}