c7149211530904d24a0e947996c49030493dfdf3
[ghc-hetmet.git] / compiler / hsSyn / HsDecls.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5
6
7
8 \begin{code}
9 {-# OPTIONS -fno-warn-incomplete-patterns #-}
10 -- The above warning supression flag is a temporary kludge.
11 -- While working on this module you are encouraged to remove it and fix
12 -- any warnings in the module. See
13 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
14 -- for details
15
16 -- | Abstract syntax of global declarations.
17 --
18 -- Definitions for: @TyDecl@ and @ConDecl@, @ClassDecl@,
19 -- @InstDecl@, @DefaultDecl@ and @ForeignDecl@.
20 module HsDecls (
21   -- * Toplevel declarations
22   HsDecl(..), LHsDecl,
23   -- ** Class or type declarations
24   TyClDecl(..), LTyClDecl,
25   isClassDecl, isSynDecl, isDataDecl, isTypeDecl, isFamilyDecl,
26   isFamInstDecl, tcdName, tyClDeclNames, tyClDeclTyVars,
27   countTyClDecls,
28   -- ** Instance declarations
29   InstDecl(..), LInstDecl, NewOrData(..), FamilyFlavour(..),
30   instDeclATs,
31   -- ** Standalone deriving declarations
32   DerivDecl(..), LDerivDecl,
33   -- ** @RULE@ declarations
34   RuleDecl(..), LRuleDecl, RuleBndr(..),
35   collectRuleBndrSigTys,
36   -- ** @default@ declarations
37   DefaultDecl(..), LDefaultDecl,
38   -- ** Top-level template haskell splice
39   SpliceDecl(..),
40   -- ** Foreign function interface declarations
41   ForeignDecl(..), LForeignDecl, ForeignImport(..), ForeignExport(..),
42   CImportSpec(..),
43   -- ** Data-constructor declarations
44   ConDecl(..), LConDecl, ResType(..), 
45   HsConDeclDetails, hsConDeclArgTys, hsConDeclsNames,
46   -- ** Document comments
47   DocDecl(..), LDocDecl, docDeclDoc,
48   -- ** Deprecations
49   WarnDecl(..),  LWarnDecl,
50   -- ** Annotations
51   AnnDecl(..), LAnnDecl, 
52   AnnProvenance(..), annProvenanceName_maybe, modifyAnnProvenanceNameM,
53
54   -- * Grouping
55   HsGroup(..),  emptyRdrGroup, emptyRnGroup, appendGroups
56     ) where
57
58 -- friends:
59 import {-# SOURCE #-}   HsExpr( HsExpr, pprExpr )
60         -- Because Expr imports Decls via HsBracket
61
62 import HsBinds
63 import HsPat
64 import HsTypes
65 import HsDoc
66 import NameSet
67 import {- Kind parts of -} Type
68 import BasicTypes
69 import ForeignCall
70
71 -- others:
72 import Class
73 import Outputable       
74 import Util
75 import SrcLoc
76 import FastString
77
78 import Control.Monad    ( liftM )
79 import Data.Maybe       ( isJust )
80 \end{code}
81
82 %************************************************************************
83 %*                                                                      *
84 \subsection[HsDecl]{Declarations}
85 %*                                                                      *
86 %************************************************************************
87
88 \begin{code}
89 type LHsDecl id = Located (HsDecl id)
90
91 -- | A Haskell Declaration
92 data HsDecl id
93   = TyClD       (TyClDecl id)     -- ^ A type or class declaration.
94   | InstD       (InstDecl  id)    -- ^ An instance declaration.
95   | DerivD      (DerivDecl id)
96   | ValD        (HsBind id)
97   | SigD        (Sig id)
98   | DefD        (DefaultDecl id)
99   | ForD        (ForeignDecl id)
100   | WarningD    (WarnDecl id)
101   | AnnD        (AnnDecl id)
102   | RuleD       (RuleDecl id)
103   | SpliceD     (SpliceDecl id)
104   | DocD        (DocDecl id)
105
106
107 -- NB: all top-level fixity decls are contained EITHER
108 -- EITHER SigDs
109 -- OR     in the ClassDecls in TyClDs
110 --
111 -- The former covers
112 --      a) data constructors
113 --      b) class methods (but they can be also done in the
114 --              signatures of class decls)
115 --      c) imported functions (that have an IfacSig)
116 --      d) top level decls
117 --
118 -- The latter is for class methods only
119
120 -- | A 'HsDecl' is categorised into a 'HsGroup' before being
121 -- fed to the renamer.
122 data HsGroup id
123   = HsGroup {
124         hs_valds  :: HsValBinds id,
125         hs_tyclds :: [LTyClDecl id],
126         hs_instds :: [LInstDecl id],
127         hs_derivds :: [LDerivDecl id],
128
129         hs_fixds  :: [LFixitySig id],
130                 -- Snaffled out of both top-level fixity signatures,
131                 -- and those in class declarations
132
133         hs_defds  :: [LDefaultDecl id],
134         hs_fords  :: [LForeignDecl id],
135         hs_warnds :: [LWarnDecl id],
136         hs_annds   :: [LAnnDecl id],
137         hs_ruleds :: [LRuleDecl id],
138
139         hs_docs   :: [LDocDecl id]
140   }
141
142 emptyGroup, emptyRdrGroup, emptyRnGroup :: HsGroup a
143 emptyRdrGroup = emptyGroup { hs_valds = emptyValBindsIn }
144 emptyRnGroup  = emptyGroup { hs_valds = emptyValBindsOut }
145
146 emptyGroup = HsGroup { hs_tyclds = [], hs_instds = [], hs_derivds = [],
147                        hs_fixds = [], hs_defds = [], hs_annds = [],
148                        hs_fords = [], hs_warnds = [], hs_ruleds = [],
149                        hs_valds = error "emptyGroup hs_valds: Can't happen",
150                        hs_docs = [] }
151
152 appendGroups :: HsGroup a -> HsGroup a -> HsGroup a
153 appendGroups 
154     HsGroup { 
155         hs_valds  = val_groups1,
156         hs_tyclds = tyclds1, 
157         hs_instds = instds1,
158         hs_derivds = derivds1,
159         hs_fixds  = fixds1, 
160         hs_defds  = defds1,
161         hs_annds  = annds1,
162         hs_fords  = fords1, 
163         hs_warnds = warnds1,
164         hs_ruleds = rulds1,
165   hs_docs   = docs1 }
166     HsGroup { 
167         hs_valds  = val_groups2,
168         hs_tyclds = tyclds2, 
169         hs_instds = instds2,
170         hs_derivds = derivds2,
171         hs_fixds  = fixds2, 
172         hs_defds  = defds2,
173         hs_annds  = annds2,
174         hs_fords  = fords2, 
175         hs_warnds = warnds2,
176         hs_ruleds = rulds2,
177   hs_docs   = docs2 }
178   = 
179     HsGroup { 
180         hs_valds  = val_groups1 `plusHsValBinds` val_groups2,
181         hs_tyclds = tyclds1 ++ tyclds2, 
182         hs_instds = instds1 ++ instds2,
183         hs_derivds = derivds1 ++ derivds2,
184         hs_fixds  = fixds1 ++ fixds2,
185         hs_annds  = annds1 ++ annds2,
186         hs_defds  = defds1 ++ defds2,
187         hs_fords  = fords1 ++ fords2, 
188         hs_warnds = warnds1 ++ warnds2,
189         hs_ruleds = rulds1 ++ rulds2,
190   hs_docs   = docs1  ++ docs2 }
191 \end{code}
192
193 \begin{code}
194 instance OutputableBndr name => Outputable (HsDecl name) where
195     ppr (TyClD dcl)             = ppr dcl
196     ppr (ValD binds)            = ppr binds
197     ppr (DefD def)              = ppr def
198     ppr (InstD inst)            = ppr inst
199     ppr (DerivD deriv)          = ppr deriv
200     ppr (ForD fd)               = ppr fd
201     ppr (SigD sd)               = ppr sd
202     ppr (RuleD rd)              = ppr rd
203     ppr (WarningD wd)           = ppr wd
204     ppr (AnnD ad)               = ppr ad
205     ppr (SpliceD dd)            = ppr dd
206     ppr (DocD doc)              = ppr doc
207
208 instance OutputableBndr name => Outputable (HsGroup name) where
209     ppr (HsGroup { hs_valds  = val_decls,
210                    hs_tyclds = tycl_decls,
211                    hs_instds = inst_decls,
212                    hs_derivds = deriv_decls,
213                    hs_fixds  = fix_decls,
214                    hs_warnds = deprec_decls,
215                    hs_annds  = ann_decls,
216                    hs_fords  = foreign_decls,
217                    hs_defds  = default_decls,
218                    hs_ruleds = rule_decls })
219         = vcat [ppr_ds fix_decls, ppr_ds default_decls, 
220                 ppr_ds deprec_decls, ppr_ds ann_decls,
221                 ppr_ds rule_decls,
222                 ppr val_decls,
223                 ppr_ds tycl_decls, ppr_ds inst_decls,
224                 ppr_ds deriv_decls,
225                 ppr_ds foreign_decls]
226         where
227           ppr_ds [] = empty
228           ppr_ds ds = text "" $$ vcat (map ppr ds)
229
230 data SpliceDecl id = SpliceDecl (Located (HsExpr id))   -- Top level splice
231
232 instance OutputableBndr name => Outputable (SpliceDecl name) where
233    ppr (SpliceDecl e) = ptext (sLit "$") <> parens (pprExpr (unLoc e))
234 \end{code}
235
236
237 %************************************************************************
238 %*                                                                      *
239 \subsection[TyDecl]{@data@, @newtype@ or @type@ (synonym) type declaration}
240 %*                                                                      *
241 %************************************************************************
242
243                 --------------------------------
244                         THE NAMING STORY
245                 --------------------------------
246
247 Here is the story about the implicit names that go with type, class,
248 and instance decls.  It's a bit tricky, so pay attention!
249
250 "Implicit" (or "system") binders
251 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
252   Each data type decl defines 
253         a worker name for each constructor
254         to-T and from-T convertors
255   Each class decl defines
256         a tycon for the class
257         a data constructor for that tycon
258         the worker for that constructor
259         a selector for each superclass
260
261 All have occurrence names that are derived uniquely from their parent
262 declaration.
263
264 None of these get separate definitions in an interface file; they are
265 fully defined by the data or class decl.  But they may *occur* in
266 interface files, of course.  Any such occurrence must haul in the
267 relevant type or class decl.
268
269 Plan of attack:
270  - Ensure they "point to" the parent data/class decl 
271    when loading that decl from an interface file
272    (See RnHiFiles.getSysBinders)
273
274  - When typechecking the decl, we build the implicit TyCons and Ids.
275    When doing so we look them up in the name cache (RnEnv.lookupSysName),
276    to ensure correct module and provenance is set
277
278 These are the two places that we have to conjure up the magic derived
279 names.  (The actual magic is in OccName.mkWorkerOcc, etc.)
280
281 Default methods
282 ~~~~~~~~~~~~~~~
283  - Occurrence name is derived uniquely from the method name
284    E.g. $dmmax
285
286  - If there is a default method name at all, it's recorded in
287    the ClassOpSig (in HsBinds), in the DefMeth field.
288    (DefMeth is defined in Class.lhs)
289
290 Source-code class decls and interface-code class decls are treated subtly
291 differently, which has given me a great deal of confusion over the years.
292 Here's the deal.  (We distinguish the two cases because source-code decls
293 have (Just binds) in the tcdMeths field, whereas interface decls have Nothing.
294
295 In *source-code* class declarations:
296
297  - When parsing, every ClassOpSig gets a DefMeth with a suitable RdrName
298    This is done by RdrHsSyn.mkClassOpSigDM
299
300  - The renamer renames it to a Name
301
302  - During typechecking, we generate a binding for each $dm for 
303    which there's a programmer-supplied default method:
304         class Foo a where
305           op1 :: <type>
306           op2 :: <type>
307           op1 = ...
308    We generate a binding for $dmop1 but not for $dmop2.
309    The Class for Foo has a NoDefMeth for op2 and a DefMeth for op1.
310    The Name for $dmop2 is simply discarded.
311
312 In *interface-file* class declarations:
313   - When parsing, we see if there's an explicit programmer-supplied default method
314     because there's an '=' sign to indicate it:
315         class Foo a where
316           op1 = :: <type>       -- NB the '='
317           op2   :: <type>
318     We use this info to generate a DefMeth with a suitable RdrName for op1,
319     and a NoDefMeth for op2
320   - The interface file has a separate definition for $dmop1, with unfolding etc.
321   - The renamer renames it to a Name.
322   - The renamer treats $dmop1 as a free variable of the declaration, so that
323     the binding for $dmop1 will be sucked in.  (See RnHsSyn.tyClDeclFVs)  
324     This doesn't happen for source code class decls, because they *bind* the default method.
325
326 Dictionary functions
327 ~~~~~~~~~~~~~~~~~~~~
328 Each instance declaration gives rise to one dictionary function binding.
329
330 The type checker makes up new source-code instance declarations
331 (e.g. from 'deriving' or generic default methods --- see
332 TcInstDcls.tcInstDecls1).  So we can't generate the names for
333 dictionary functions in advance (we don't know how many we need).
334
335 On the other hand for interface-file instance declarations, the decl
336 specifies the name of the dictionary function, and it has a binding elsewhere
337 in the interface file:
338         instance {Eq Int} = dEqInt
339         dEqInt :: {Eq Int} <pragma info>
340
341 So again we treat source code and interface file code slightly differently.
342
343 Source code:
344   - Source code instance decls have a Nothing in the (Maybe name) field
345     (see data InstDecl below)
346
347   - The typechecker makes up a Local name for the dict fun for any source-code
348     instance decl, whether it comes from a source-code instance decl, or whether
349     the instance decl is derived from some other construct (e.g. 'deriving').
350
351   - The occurrence name it chooses is derived from the instance decl (just for 
352     documentation really) --- e.g. dNumInt.  Two dict funs may share a common
353     occurrence name, but will have different uniques.  E.g.
354         instance Foo [Int]  where ...
355         instance Foo [Bool] where ...
356     These might both be dFooList
357
358   - The CoreTidy phase externalises the name, and ensures the occurrence name is
359     unique (this isn't special to dict funs).  So we'd get dFooList and dFooList1.
360
361   - We can take this relaxed approach (changing the occurrence name later) 
362     because dict fun Ids are not captured in a TyCon or Class (unlike default
363     methods, say).  Instead, they are kept separately in the InstEnv.  This
364     makes it easy to adjust them after compiling a module.  (Once we've finished
365     compiling that module, they don't change any more.)
366
367
368 Interface file code:
369   - The instance decl gives the dict fun name, so the InstDecl has a (Just name)
370     in the (Maybe name) field.
371
372   - RnHsSyn.instDeclFVs treats the dict fun name as free in the decl, so that we
373     suck in the dfun binding
374
375
376 \begin{code}
377 -- Representation of indexed types
378 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
379 -- Family kind signatures are represented by the variant `TyFamily'.  It
380 -- covers "type family", "newtype family", and "data family" declarations,
381 -- distinguished by the value of the field `tcdFlavour'.
382 --
383 -- Indexed types are represented by 'TyData' and 'TySynonym' using the field
384 -- 'tcdTyPats::Maybe [LHsType name]', with the following meaning:
385 --
386 --   * If it is 'Nothing', we have a *vanilla* data type declaration or type
387 --     synonym declaration and 'tcdVars' contains the type parameters of the
388 --     type constructor.
389 --
390 --   * If it is 'Just pats', we have the definition of an indexed type.  Then,
391 --     'pats' are type patterns for the type-indexes of the type constructor
392 --     and 'tcdTyVars' are the variables in those patterns.  Hence, the arity of
393 --     the indexed type (ie, the number of indexes) is 'length tcdTyPats' and
394 --     *not* 'length tcdVars'.
395 --
396 -- In both cases, 'tcdVars' collects all variables we need to quantify over.
397
398 type LTyClDecl name = Located (TyClDecl name)
399
400 -- | A type or class declaration.
401 data TyClDecl name
402   = ForeignType { 
403                 tcdLName    :: Located name,
404                 tcdExtName  :: Maybe FastString
405     }
406
407
408   | -- | @type/data family T :: *->*@
409     TyFamily {  tcdFlavour:: FamilyFlavour,             -- type or data
410                 tcdLName  :: Located name,              -- type constructor
411                 tcdTyVars :: [LHsTyVarBndr name],       -- type variables
412                 tcdKind   :: Maybe Kind                 -- result kind
413     }
414
415
416   | -- | Declares a data type or newtype, giving its construcors
417     -- @
418     --  data/newtype T a = <constrs>
419     --  data/newtype instance T [a] = <constrs>
420     -- @
421     TyData {    tcdND     :: NewOrData,
422                 tcdCtxt   :: LHsContext name,           -- ^ Context
423                 tcdLName  :: Located name,              -- ^ Type constructor
424
425                 tcdTyVars :: [LHsTyVarBndr name],       -- ^ Type variables
426                         
427                 tcdTyPats :: Maybe [LHsType name],
428                         -- ^ Type patterns.
429                         --
430                         -- @Just [t1..tn]@ for @data instance T t1..tn = ...@
431                         --      in this case @tcdTyVars = fv( tcdTyPats )@.
432                         -- @Nothing@ for everything else.
433
434                 tcdKindSig:: Maybe Kind,
435                         -- ^ Optional kind signature.
436                         --
437                         -- @(Just k)@ for a GADT-style @data@, or @data
438                         -- instance@ decl with explicit kind sig
439
440                 tcdCons   :: [LConDecl name],
441                         -- ^ Data constructors
442                         --
443                         -- For @data T a = T1 | T2 a@
444                         --   the 'LConDecl's all have 'ResTyH98'.
445                         -- For @data T a where { T1 :: T a }@
446                         --   the 'LConDecls' all have 'ResTyGADT'.
447
448                 tcdDerivs :: Maybe [LHsType name]
449                         -- ^ Derivings; @Nothing@ => not specified,
450                         --              @Just []@ => derive exactly what is asked
451                         --
452                         -- These "types" must be of form
453                         -- @
454                         --      forall ab. C ty1 ty2
455                         -- @
456                         -- Typically the foralls and ty args are empty, but they
457                         -- are non-empty for the newtype-deriving case
458     }
459
460   | TySynonym { tcdLName  :: Located name,              -- ^ type constructor
461                 tcdTyVars :: [LHsTyVarBndr name],       -- ^ type variables
462                 tcdTyPats :: Maybe [LHsType name],      -- ^ Type patterns
463                         -- See comments for tcdTyPats in TyData
464                         -- 'Nothing' => vanilla type synonym
465
466                 tcdSynRhs :: LHsType name               -- ^ synonym expansion
467     }
468
469   | ClassDecl { tcdCtxt    :: LHsContext name,          -- ^ Context...
470                 tcdLName   :: Located name,             -- ^ Name of the class
471                 tcdTyVars  :: [LHsTyVarBndr name],      -- ^ Class type variables
472                 tcdFDs     :: [Located (FunDep name)],  -- ^ Functional deps
473                 tcdSigs    :: [LSig name],              -- ^ Methods' signatures
474                 tcdMeths   :: LHsBinds name,            -- ^ Default methods
475                 tcdATs     :: [LTyClDecl name],         -- ^ Associated types; ie
476                                                         --   only 'TyFamily' and
477                                                         --   'TySynonym'; the
478                                                         --   latter for defaults
479                 tcdDocs    :: [LDocDecl name]           -- ^ Haddock docs
480     }
481
482 data NewOrData
483   = NewType                     -- ^ @newtype Blah ...@
484   | DataType                    -- ^ @data Blah ...@
485   deriving( Eq )                -- Needed because Demand derives Eq
486
487 data FamilyFlavour
488   = TypeFamily                  -- ^ @type family ...@
489   | DataFamily                  -- ^ @data family ...@
490 \end{code}
491
492 Simple classifiers
493
494 \begin{code}
495 -- | @True@ <=> argument is a @data@\/@newtype@ or @data@\/@newtype instance@
496 -- declaration.
497 isDataDecl :: TyClDecl name -> Bool
498 isDataDecl (TyData {}) = True
499 isDataDecl _other      = False
500
501 -- | type or type instance declaration
502 isTypeDecl :: TyClDecl name -> Bool
503 isTypeDecl (TySynonym {}) = True
504 isTypeDecl _other         = False
505
506 -- | vanilla Haskell type synonym (ie, not a type instance)
507 isSynDecl :: TyClDecl name -> Bool
508 isSynDecl (TySynonym {tcdTyPats = Nothing}) = True
509 isSynDecl _other                            = False
510
511 -- | type class
512 isClassDecl :: TyClDecl name -> Bool
513 isClassDecl (ClassDecl {}) = True
514 isClassDecl _              = False
515
516 -- | type family declaration
517 isFamilyDecl :: TyClDecl name -> Bool
518 isFamilyDecl (TyFamily {}) = True
519 isFamilyDecl _other        = False
520
521 -- | family instance (types, newtypes, and data types)
522 isFamInstDecl :: TyClDecl name -> Bool
523 isFamInstDecl tydecl
524    | isTypeDecl tydecl
525      || isDataDecl tydecl = isJust (tcdTyPats tydecl)
526    | otherwise            = False
527 \end{code}
528
529 Dealing with names
530
531 \begin{code}
532 tcdName :: TyClDecl name -> name
533 tcdName decl = unLoc (tcdLName decl)
534
535 tyClDeclNames :: Eq name => TyClDecl name -> [Located name]
536 -- ^ Returns all the /binding/ names of the decl, along with their SrcLocs.
537 -- The first one is guaranteed to be the name of the decl. For record fields
538 -- mentioned in multiple constructors, the SrcLoc will be from the first
539 -- occurence.  We use the equality to filter out duplicate field names
540
541 tyClDeclNames (TyFamily    {tcdLName = name})    = [name]
542 tyClDeclNames (TySynonym   {tcdLName = name})    = [name]
543 tyClDeclNames (ForeignType {tcdLName = name})    = [name]
544
545 tyClDeclNames (ClassDecl {tcdLName = cls_name, tcdSigs = sigs, tcdATs = ats})
546   = cls_name : 
547     concatMap (tyClDeclNames . unLoc) ats ++ [n | L _ (TypeSig n _) <- sigs]
548
549 tyClDeclNames (TyData {tcdLName = tc_name, tcdCons = cons})
550   = tc_name : hsConDeclsNames cons
551
552 tyClDeclTyVars :: TyClDecl name -> [LHsTyVarBndr name]
553 tyClDeclTyVars (TyFamily    {tcdTyVars = tvs}) = tvs
554 tyClDeclTyVars (TySynonym   {tcdTyVars = tvs}) = tvs
555 tyClDeclTyVars (TyData      {tcdTyVars = tvs}) = tvs
556 tyClDeclTyVars (ClassDecl   {tcdTyVars = tvs}) = tvs
557 tyClDeclTyVars (ForeignType {})                = []
558 \end{code}
559
560 \begin{code}
561 countTyClDecls :: [TyClDecl name] -> (Int, Int, Int, Int, Int, Int)
562         -- class, synonym decls, data, newtype, family decls, family instances
563 countTyClDecls decls 
564  = (count isClassDecl    decls,
565     count isSynDecl      decls,  -- excluding...
566     count isDataTy       decls,  -- ...family...
567     count isNewTy        decls,  -- ...instances
568     count isFamilyDecl   decls,
569     count isFamInstDecl  decls)
570  where
571    isDataTy TyData{tcdND = DataType, tcdTyPats = Nothing} = True
572    isDataTy _                                             = False
573    
574    isNewTy TyData{tcdND = NewType, tcdTyPats = Nothing} = True
575    isNewTy _                                            = False
576 \end{code}
577
578 \begin{code}
579 instance OutputableBndr name
580               => Outputable (TyClDecl name) where
581
582     ppr (ForeignType {tcdLName = ltycon})
583         = hsep [ptext (sLit "foreign import type dotnet"), ppr ltycon]
584
585     ppr (TyFamily {tcdFlavour = flavour, tcdLName = ltycon, 
586                    tcdTyVars = tyvars, tcdKind = mb_kind})
587       = pp_flavour <+> pp_decl_head [] ltycon tyvars Nothing <+> pp_kind
588         where
589           pp_flavour = case flavour of
590                          TypeFamily -> ptext (sLit "type family")
591                          DataFamily -> ptext (sLit "data family")
592
593           pp_kind = case mb_kind of
594                       Nothing   -> empty
595                       Just kind -> dcolon <+> pprKind kind
596
597     ppr (TySynonym {tcdLName = ltycon, tcdTyVars = tyvars, tcdTyPats = typats,
598                     tcdSynRhs = mono_ty})
599       = hang (ptext (sLit "type") <+> 
600               (if isJust typats then ptext (sLit "instance") else empty) <+>
601               pp_decl_head [] ltycon tyvars typats <+> 
602               equals)
603              4 (ppr mono_ty)
604
605     ppr (TyData {tcdND = new_or_data, tcdCtxt = context, tcdLName = ltycon,
606                  tcdTyVars = tyvars, tcdTyPats = typats, tcdKindSig = mb_sig, 
607                  tcdCons = condecls, tcdDerivs = derivings})
608       = pp_tydecl (null condecls && isJust mb_sig) 
609                   (ppr new_or_data <+> 
610                    (if isJust typats then ptext (sLit "instance") else empty) <+>
611                    pp_decl_head (unLoc context) ltycon tyvars typats <+> 
612                    ppr_sig mb_sig)
613                   (pp_condecls condecls)
614                   derivings
615       where
616         ppr_sig Nothing = empty
617         ppr_sig (Just kind) = dcolon <+> pprKind kind
618
619     ppr (ClassDecl {tcdCtxt = context, tcdLName = lclas, tcdTyVars = tyvars, 
620                     tcdFDs = fds, 
621                     tcdSigs = sigs, tcdMeths = methods, tcdATs = ats})
622       | null sigs && null ats  -- No "where" part
623       = top_matter
624
625       | otherwise       -- Laid out
626       = sep [hsep [top_matter, ptext (sLit "where {")],
627              nest 4 (sep [ sep (map ppr_semi ats)
628                          , sep (map ppr_semi sigs)
629                          , pprLHsBinds methods
630                          , char '}'])]
631       where
632         top_matter    =     ptext (sLit "class") 
633                         <+> pp_decl_head (unLoc context) lclas tyvars Nothing
634                         <+> pprFundeps (map unLoc fds)
635         ppr_semi decl = ppr decl <> semi
636
637 pp_decl_head :: OutputableBndr name
638    => HsContext name
639    -> Located name
640    -> [LHsTyVarBndr name]
641    -> Maybe [LHsType name]
642    -> SDoc
643 pp_decl_head context thing tyvars Nothing       -- no explicit type patterns
644   = hsep [pprHsContext context, ppr thing, interppSP tyvars]
645 pp_decl_head context thing _      (Just typats) -- explicit type patterns
646   = hsep [ pprHsContext context, ppr thing
647          , hsep (map (pprParendHsType.unLoc) typats)]
648
649 pp_condecls :: OutputableBndr name => [LConDecl name] -> SDoc
650 pp_condecls cs@(L _ ConDecl{ con_res = ResTyGADT _ } : _) -- In GADT syntax
651   = hang (ptext (sLit "where")) 2 (vcat (map ppr cs))
652 pp_condecls cs                    -- In H98 syntax
653   = equals <+> sep (punctuate (ptext (sLit " |")) (map ppr cs))
654
655 pp_tydecl :: OutputableBndr name => Bool -> SDoc -> SDoc -> Maybe [LHsType name] -> SDoc
656 pp_tydecl True  pp_head _ _
657   = pp_head
658 pp_tydecl False pp_head pp_decl_rhs derivings
659   = hang pp_head 4 (sep [
660       pp_decl_rhs,
661       case derivings of
662         Nothing -> empty
663         Just ds -> hsep [ptext (sLit "deriving"), parens (interpp'SP ds)]
664     ])
665
666 instance Outputable NewOrData where
667   ppr NewType  = ptext (sLit "newtype")
668   ppr DataType = ptext (sLit "data")
669 \end{code}
670
671
672 %************************************************************************
673 %*                                                                      *
674 \subsection[ConDecl]{A data-constructor declaration}
675 %*                                                                      *
676 %************************************************************************
677
678 \begin{code}
679 type LConDecl name = Located (ConDecl name)
680
681 -- data T b = forall a. Eq a => MkT a b
682 --   MkT :: forall b a. Eq a => MkT a b
683
684 -- data T b where
685 --      MkT1 :: Int -> T Int
686
687 -- data T = Int `MkT` Int
688 --        | MkT2
689
690 -- data T a where
691 --      Int `MkT` Int :: T Int
692
693 data ConDecl name
694   = ConDecl
695     { con_name      :: Located name
696         -- ^ Constructor name.  This is used for the DataCon itself, and for
697         -- the user-callable wrapper Id.
698
699     , con_explicit  :: HsExplicitForAll
700         -- ^ Is there an user-written forall? (cf. 'HsTypes.HsForAllTy')
701
702     , con_qvars     :: [LHsTyVarBndr name]
703         -- ^ Type variables.  Depending on 'con_res' this describes the
704         -- follewing entities
705         --
706         --  - ResTyH98:  the constructor's *existential* type variables
707         --  - ResTyGADT: *all* the constructor's quantified type variables
708
709     , con_cxt       :: LHsContext name
710         -- ^ The context.  This /does not/ include the \"stupid theta\" which
711         -- lives only in the 'TyData' decl.
712
713     , con_details   :: HsConDeclDetails name
714         -- ^ The main payload
715
716     , con_res       :: ResType name
717         -- ^ Result type of the constructor
718
719     , con_doc       :: Maybe (LHsDoc name)
720         -- ^ A possible Haddock comment.
721
722     , con_old_rec :: Bool   
723         -- ^ TEMPORARY field; True <=> user has employed now-deprecated syntax for
724         --                             GADT-style record decl   C { blah } :: T a b
725         -- Remove this when we no longer parse this stuff, and hence do not
726         -- need to report decprecated use
727     }
728
729 type HsConDeclDetails name = HsConDetails (LBangType name) [ConDeclField name]
730
731 hsConDeclArgTys :: HsConDeclDetails name -> [LBangType name]
732 hsConDeclArgTys (PrefixCon tys)    = tys
733 hsConDeclArgTys (InfixCon ty1 ty2) = [ty1,ty2]
734 hsConDeclArgTys (RecCon flds)      = map cd_fld_type flds
735
736 data ResType name
737    = ResTyH98           -- Constructor was declared using Haskell 98 syntax
738    | ResTyGADT (LHsType name)   -- Constructor was declared using GADT-style syntax,
739                                 --      and here is its result type
740
741 instance OutputableBndr name => Outputable (ResType name) where
742          -- Debugging only
743    ppr ResTyH98 = ptext (sLit "ResTyH98")
744    ppr (ResTyGADT ty) = ptext (sLit "ResTyGADT") <+> pprParendHsType (unLoc ty)
745 \end{code}
746
747 \begin{code}
748 hsConDeclsNames :: (Eq name) => [LConDecl name] -> [Located name]
749   -- See tyClDeclNames for what this does
750   -- The function is boringly complicated because of the records
751   -- And since we only have equality, we have to be a little careful
752 hsConDeclsNames cons
753   = snd (foldl do_one ([], []) cons)
754   where
755     do_one (flds_seen, acc) (L _ (ConDecl { con_name = lname, con_details = RecCon flds }))
756         = (map unLoc new_flds ++ flds_seen, lname : new_flds ++ acc)
757         where
758           new_flds = filterOut (\f -> unLoc f `elem` flds_seen) 
759                                (map cd_fld_name flds)
760
761     do_one (flds_seen, acc) (L _ (ConDecl { con_name = lname }))
762         = (flds_seen, lname:acc)
763 \end{code}
764   
765
766 \begin{code}
767 instance (OutputableBndr name) => Outputable (ConDecl name) where
768     ppr = pprConDecl
769
770 pprConDecl :: OutputableBndr name => ConDecl name -> SDoc
771 pprConDecl (ConDecl { con_name =con, con_explicit = expl, con_qvars = tvs
772                     , con_cxt = cxt, con_details = details
773                     , con_res = ResTyH98, con_doc = doc })
774   = sep [ppr_mbDoc doc, pprHsForAll expl tvs cxt, ppr_details con details]
775   where
776     ppr_details con (InfixCon t1 t2) = hsep [ppr t1, pprHsInfix con, ppr t2]
777     ppr_details con (PrefixCon tys)  = hsep (pprHsVar con : map ppr tys)
778     ppr_details con (RecCon fields)  = ppr con <+> pprConDeclFields fields
779
780 pprConDecl (ConDecl { con_name = con, con_explicit = expl, con_qvars = tvs
781                     , con_cxt = cxt, con_details = PrefixCon arg_tys
782                     , con_res = ResTyGADT res_ty })
783   = ppr con <+> dcolon <+> 
784     sep [pprHsForAll expl tvs cxt, ppr (foldr mk_fun_ty res_ty arg_tys)]
785   where
786     mk_fun_ty a b = noLoc (HsFunTy a b)
787
788 pprConDecl (ConDecl { con_name = con, con_explicit = expl, con_qvars = tvs
789                     , con_cxt = cxt, con_details = RecCon fields, con_res = ResTyGADT res_ty })
790   = sep [ppr con <+> dcolon <+> pprHsForAll expl tvs cxt, 
791          pprConDeclFields fields <+> arrow <+> ppr res_ty]
792
793 pprConDecl (ConDecl {con_name = con, con_details = InfixCon {}, con_res = ResTyGADT {} })
794   = pprPanic "pprConDecl" (ppr con)
795         -- In GADT syntax we don't allow infix constructors
796 \end{code}
797
798 %************************************************************************
799 %*                                                                      *
800 \subsection[InstDecl]{An instance declaration
801 %*                                                                      *
802 %************************************************************************
803
804 \begin{code}
805 type LInstDecl name = Located (InstDecl name)
806
807 data InstDecl name
808   = InstDecl    (LHsType name)  -- Context => Class Instance-type
809                                 -- Using a polytype means that the renamer conveniently
810                                 -- figures out the quantified type variables for us.
811                 (LHsBinds name)
812                 [LSig name]     -- User-supplied pragmatic info
813                 [LTyClDecl name]-- Associated types (ie, 'TyData' and
814                                 -- 'TySynonym' only)
815
816 instance (OutputableBndr name) => Outputable (InstDecl name) where
817
818     ppr (InstDecl inst_ty binds uprags ats)
819       = vcat [hsep [ptext (sLit "instance"), ppr inst_ty, ptext (sLit "where")]
820              , nest 4 $ vcat (map ppr ats)
821              , nest 4 $ vcat (map ppr uprags)
822              , nest 4 $ pprLHsBinds binds ]
823
824 -- Extract the declarations of associated types from an instance
825 --
826 instDeclATs :: InstDecl name -> [LTyClDecl name]
827 instDeclATs (InstDecl _ _ _ ats) = ats
828 \end{code}
829
830 %************************************************************************
831 %*                                                                      *
832 \subsection[DerivDecl]{A stand-alone instance deriving declaration
833 %*                                                                      *
834 %************************************************************************
835
836 \begin{code}
837 type LDerivDecl name = Located (DerivDecl name)
838
839 data DerivDecl name = DerivDecl (LHsType name)
840
841 instance (OutputableBndr name) => Outputable (DerivDecl name) where
842     ppr (DerivDecl ty) 
843         = hsep [ptext (sLit "deriving instance"), ppr ty]
844 \end{code}
845
846 %************************************************************************
847 %*                                                                      *
848 \subsection[DefaultDecl]{A @default@ declaration}
849 %*                                                                      *
850 %************************************************************************
851
852 There can only be one default declaration per module, but it is hard
853 for the parser to check that; we pass them all through in the abstract
854 syntax, and that restriction must be checked in the front end.
855
856 \begin{code}
857 type LDefaultDecl name = Located (DefaultDecl name)
858
859 data DefaultDecl name
860   = DefaultDecl [LHsType name]
861
862 instance (OutputableBndr name)
863               => Outputable (DefaultDecl name) where
864
865     ppr (DefaultDecl tys)
866       = ptext (sLit "default") <+> parens (interpp'SP tys)
867 \end{code}
868
869 %************************************************************************
870 %*                                                                      *
871 \subsection{Foreign function interface declaration}
872 %*                                                                      *
873 %************************************************************************
874
875 \begin{code}
876
877 -- foreign declarations are distinguished as to whether they define or use a
878 -- Haskell name
879 --
880 --  * the Boolean value indicates whether the pre-standard deprecated syntax
881 --   has been used
882 --
883 type LForeignDecl name = Located (ForeignDecl name)
884
885 data ForeignDecl name
886   = ForeignImport (Located name) (LHsType name) ForeignImport  -- defines name
887   | ForeignExport (Located name) (LHsType name) ForeignExport  -- uses name
888
889 -- Specification Of an imported external entity in dependence on the calling
890 -- convention 
891 --
892 data ForeignImport = -- import of a C entity
893                      --
894                      --  * the two strings specifying a header file or library
895                      --   may be empty, which indicates the absence of a
896                      --   header or object specification (both are not used
897                      --   in the case of `CWrapper' and when `CFunction'
898                      --   has a dynamic target)
899                      --
900                      --  * the calling convention is irrelevant for code
901                      --   generation in the case of `CLabel', but is needed
902                      --   for pretty printing 
903                      --
904                      --  * `Safety' is irrelevant for `CLabel' and `CWrapper'
905                      --
906                      CImport  CCallConv       -- ccall or stdcall
907                               Safety          -- safe or unsafe
908                               FastString      -- name of C header
909                               CImportSpec     -- details of the C entity
910
911 -- details of an external C entity
912 --
913 data CImportSpec = CLabel    CLabelString     -- import address of a C label
914                  | CFunction CCallTarget      -- static or dynamic function
915                  | CWrapper                   -- wrapper to expose closures
916                                               -- (former f.e.d.)
917
918 -- specification of an externally exported entity in dependence on the calling
919 -- convention
920 --
921 data ForeignExport = CExport  CExportSpec    -- contains the calling convention
922
923 -- pretty printing of foreign declarations
924 --
925
926 instance OutputableBndr name => Outputable (ForeignDecl name) where
927   ppr (ForeignImport n ty fimport) =
928     hang (ptext (sLit "foreign import") <+> ppr fimport <+> ppr n)
929        2 (dcolon <+> ppr ty)
930   ppr (ForeignExport n ty fexport) =
931     hang (ptext (sLit "foreign export") <+> ppr fexport <+> ppr n)
932        2 (dcolon <+> ppr ty)
933
934 instance Outputable ForeignImport where
935   ppr (CImport  cconv safety header spec) =
936     ppr cconv <+> ppr safety <+> 
937     char '"' <> pprCEntity spec <> char '"'
938     where
939       pp_hdr = if nullFS header then empty else ftext header
940
941       pprCEntity (CLabel lbl) = 
942         ptext (sLit "static") <+> pp_hdr <+> char '&' <> ppr lbl
943       pprCEntity (CFunction (StaticTarget lbl)) = 
944         ptext (sLit "static") <+> pp_hdr <+> ppr lbl
945       pprCEntity (CFunction (DynamicTarget)) =
946         ptext (sLit "dynamic")
947       pprCEntity (CWrapper) = ptext (sLit "wrapper")
948
949 instance Outputable ForeignExport where
950   ppr (CExport  (CExportStatic lbl cconv)) = 
951     ppr cconv <+> char '"' <> ppr lbl <> char '"'
952 \end{code}
953
954
955 %************************************************************************
956 %*                                                                      *
957 \subsection{Transformation rules}
958 %*                                                                      *
959 %************************************************************************
960
961 \begin{code}
962 type LRuleDecl name = Located (RuleDecl name)
963
964 data RuleDecl name
965   = HsRule                      -- Source rule
966         RuleName                -- Rule name
967         Activation
968         [RuleBndr name]         -- Forall'd vars; after typechecking this includes tyvars
969         (Located (HsExpr name)) -- LHS
970         NameSet                 -- Free-vars from the LHS
971         (Located (HsExpr name)) -- RHS
972         NameSet                 -- Free-vars from the RHS
973
974 data RuleBndr name
975   = RuleBndr (Located name)
976   | RuleBndrSig (Located name) (LHsType name)
977
978 collectRuleBndrSigTys :: [RuleBndr name] -> [LHsType name]
979 collectRuleBndrSigTys bndrs = [ty | RuleBndrSig _ ty <- bndrs]
980
981 instance OutputableBndr name => Outputable (RuleDecl name) where
982   ppr (HsRule name act ns lhs _fv_lhs rhs _fv_rhs)
983         = sep [text "{-# RULES" <+> doubleQuotes (ftext name) <+> ppr act,
984                nest 4 (pp_forall <+> pprExpr (unLoc lhs)), 
985                nest 4 (equals <+> pprExpr (unLoc rhs) <+> text "#-}") ]
986         where
987           pp_forall | null ns   = empty
988                     | otherwise = text "forall" <+> fsep (map ppr ns) <> dot
989
990 instance OutputableBndr name => Outputable (RuleBndr name) where
991    ppr (RuleBndr name) = ppr name
992    ppr (RuleBndrSig name ty) = ppr name <> dcolon <> ppr ty
993 \end{code}
994
995 %************************************************************************
996 %*                                                                      *
997 \subsection[DocDecl]{Document comments}
998 %*                                                                      *
999 %************************************************************************
1000
1001 \begin{code}
1002
1003 type LDocDecl name = Located (DocDecl name)
1004
1005 data DocDecl name
1006   = DocCommentNext (HsDoc name)
1007   | DocCommentPrev (HsDoc name)
1008   | DocCommentNamed String (HsDoc name)
1009   | DocGroup Int (HsDoc name)
1010  
1011 -- Okay, I need to reconstruct the document comments, but for now:
1012 instance Outputable (DocDecl name) where
1013   ppr _ = text "<document comment>"
1014
1015 docDeclDoc :: DocDecl name -> HsDoc name
1016 docDeclDoc (DocCommentNext d) = d
1017 docDeclDoc (DocCommentPrev d) = d
1018 docDeclDoc (DocCommentNamed _ d) = d
1019 docDeclDoc (DocGroup _ d) = d
1020
1021 \end{code}
1022
1023 %************************************************************************
1024 %*                                                                      *
1025 \subsection[DeprecDecl]{Deprecations}
1026 %*                                                                      *
1027 %************************************************************************
1028
1029 We use exported entities for things to deprecate.
1030
1031 \begin{code}
1032 type LWarnDecl name = Located (WarnDecl name)
1033
1034 data WarnDecl name = Warning name WarningTxt
1035
1036 instance OutputableBndr name => Outputable (WarnDecl name) where
1037     ppr (Warning thing txt)
1038       = hsep [text "{-# DEPRECATED", ppr thing, doubleQuotes (ppr txt), text "#-}"]
1039 \end{code}
1040
1041 %************************************************************************
1042 %*                                                                      *
1043 \subsection[AnnDecl]{Annotations}
1044 %*                                                                      *
1045 %************************************************************************
1046
1047 \begin{code}
1048 type LAnnDecl name = Located (AnnDecl name)
1049
1050 data AnnDecl name = HsAnnotation (AnnProvenance name) (Located (HsExpr name))
1051
1052 instance (OutputableBndr name) => Outputable (AnnDecl name) where
1053     ppr (HsAnnotation provenance expr) 
1054       = hsep [text "{-#", pprAnnProvenance provenance, pprExpr (unLoc expr), text "#-}"]
1055
1056
1057 data AnnProvenance name = ValueAnnProvenance name
1058                         | TypeAnnProvenance name
1059                         | ModuleAnnProvenance
1060
1061 annProvenanceName_maybe :: AnnProvenance name -> Maybe name
1062 annProvenanceName_maybe (ValueAnnProvenance name) = Just name
1063 annProvenanceName_maybe (TypeAnnProvenance name)  = Just name
1064 annProvenanceName_maybe ModuleAnnProvenance       = Nothing
1065
1066 -- TODO: Replace with Traversable instance when GHC bootstrap version rises high enough
1067 modifyAnnProvenanceNameM :: Monad m => (before -> m after) -> AnnProvenance before -> m (AnnProvenance after)
1068 modifyAnnProvenanceNameM fm prov =
1069     case prov of
1070             ValueAnnProvenance name -> liftM ValueAnnProvenance (fm name)
1071             TypeAnnProvenance name -> liftM TypeAnnProvenance (fm name)
1072             ModuleAnnProvenance -> return ModuleAnnProvenance
1073
1074 pprAnnProvenance :: OutputableBndr name => AnnProvenance name -> SDoc
1075 pprAnnProvenance ModuleAnnProvenance       = ptext (sLit "ANN module")
1076 pprAnnProvenance (ValueAnnProvenance name) = ptext (sLit "ANN") <+> ppr name
1077 pprAnnProvenance (TypeAnnProvenance name)  = ptext (sLit "ANN type") <+> ppr name
1078 \end{code}