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