1{-# LANGUAGE CPP                 #-}
2{-# LANGUAGE ConstraintKinds     #-}
3{-# LANGUAGE DeriveDataTypeable  #-}
4{-# LANGUAGE DeriveTraversable   #-}
5{-# LANGUAGE FlexibleContexts    #-}
6{-# LANGUAGE FlexibleInstances   #-}
7{-# LANGUAGE ScopedTypeVariables #-}
8{-# LANGUAGE StandaloneDeriving  #-}
9{-# LANGUAGE TypeApplications    #-}
10{-# LANGUAGE TypeFamilies        #-}
11{-# LANGUAGE UndecidableInstances #-} -- Wrinkle in Note [Trees That Grow]
12                                      -- in module Language.Haskell.Syntax.Extension
13{-# LANGUAGE ViewPatterns #-}
14
15{-
16(c) The University of Glasgow 2006
17(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
18-}
19
20
21{-# OPTIONS_GHC -Wno-incomplete-record-updates #-}
22
23-- See Note [Language.Haskell.Syntax.* Hierarchy] for why not GHC.Hs.*
24
25-- | Abstract syntax of global declarations.
26--
27-- Definitions for: @SynDecl@ and @ConDecl@, @ClassDecl@,
28-- @InstDecl@, @DefaultDecl@ and @ForeignDecl@.
29module Language.Haskell.Syntax.Decls (
30  -- * Toplevel declarations
31  HsDecl(..), LHsDecl, HsDataDefn(..), HsDeriving, LHsFunDep, FunDep(..),
32  HsDerivingClause(..), LHsDerivingClause, DerivClauseTys(..), LDerivClauseTys,
33  NewOrData(..), newOrDataToFlavour,
34  StandaloneKindSig(..), LStandaloneKindSig,
35
36  -- ** Class or type declarations
37  TyClDecl(..), LTyClDecl, DataDeclRn(..),
38  TyClGroup(..),
39  tyClGroupTyClDecls, tyClGroupInstDecls, tyClGroupRoleDecls,
40  tyClGroupKindSigs,
41  isClassDecl, isDataDecl, isSynDecl,
42  isFamilyDecl, isTypeFamilyDecl, isDataFamilyDecl,
43  isOpenTypeFamilyInfo, isClosedTypeFamilyInfo,
44  countTyClDecls,
45  tyClDeclTyVars,
46  FamilyDecl(..), LFamilyDecl,
47
48  -- ** Instance declarations
49  InstDecl(..), LInstDecl, FamilyInfo(..), pprFlavour,
50  TyFamInstDecl(..), LTyFamInstDecl,
51  TyFamDefltDecl, LTyFamDefltDecl,
52  DataFamInstDecl(..), LDataFamInstDecl,
53  FamEqn(..), TyFamInstEqn, LTyFamInstEqn, HsTyPats,
54  LClsInstDecl, ClsInstDecl(..),
55
56  -- ** Standalone deriving declarations
57  DerivDecl(..), LDerivDecl,
58  -- ** Deriving strategies
59  DerivStrategy(..), LDerivStrategy,
60  derivStrategyName,
61  -- ** @RULE@ declarations
62  LRuleDecls,RuleDecls(..),RuleDecl(..),LRuleDecl,HsRuleRn(..),
63  RuleBndr(..),LRuleBndr,
64  collectRuleBndrSigTys,
65  pprFullRuleName,
66  -- ** @default@ declarations
67  DefaultDecl(..), LDefaultDecl,
68  -- ** Template haskell declaration splice
69  SpliceExplicitFlag(..),
70  SpliceDecl(..), LSpliceDecl,
71  -- ** Foreign function interface declarations
72  ForeignDecl(..), LForeignDecl, ForeignImport(..), ForeignExport(..),
73  CImportSpec(..),
74  -- ** Data-constructor declarations
75  ConDecl(..), LConDecl,
76  HsConDeclH98Details, HsConDeclGADTDetails(..),
77  -- ** Document comments
78  DocDecl(..), LDocDecl, docDeclDoc,
79  -- ** Deprecations
80  WarnDecl(..),  LWarnDecl,
81  WarnDecls(..), LWarnDecls,
82  -- ** Annotations
83  AnnDecl(..), LAnnDecl,
84  AnnProvenance(..), annProvenanceName_maybe,
85  -- ** Role annotations
86  RoleAnnotDecl(..), LRoleAnnotDecl,
87  -- ** Injective type families
88  FamilyResultSig(..), LFamilyResultSig, InjectivityAnn(..), LInjectivityAnn,
89
90  -- * Grouping
91  HsGroup(..), hsGroupInstDecls,
92    ) where
93
94-- friends:
95import GHC.Prelude
96
97import {-# SOURCE #-} Language.Haskell.Syntax.Expr
98  ( HsExpr, HsSplice )
99        -- Because Expr imports Decls via HsBracket
100
101import Language.Haskell.Syntax.Binds
102import Language.Haskell.Syntax.Type
103import GHC.Hs.Doc
104import GHC.Core.TyCon
105import GHC.Types.Basic
106import GHC.Types.ForeignCall
107import Language.Haskell.Syntax.Extension
108import GHC.Types.Name.Set
109import GHC.Types.Fixity
110
111-- others:
112import GHC.Utils.Outputable
113import GHC.Utils.Misc
114import GHC.Types.SrcLoc
115import GHC.Types.SourceText
116import GHC.Core.Type
117import GHC.Unit.Module.Warnings
118
119import GHC.Data.Maybe
120import Data.Data        hiding (TyCon,Fixity, Infix)
121import Data.Void
122
123{-
124************************************************************************
125*                                                                      *
126\subsection[HsDecl]{Declarations}
127*                                                                      *
128************************************************************************
129-}
130
131type LHsDecl p = XRec p (HsDecl p)
132        -- ^ When in a list this may have
133        --
134        --  - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnSemi'
135        --
136
137-- For details on above see note [exact print annotations] in GHC.Parser.Annotation
138
139-- | A Haskell Declaration
140data HsDecl p
141  = TyClD      (XTyClD p)      (TyClDecl p)      -- ^ Type or Class Declaration
142  | InstD      (XInstD p)      (InstDecl  p)     -- ^ Instance declaration
143  | DerivD     (XDerivD p)     (DerivDecl p)     -- ^ Deriving declaration
144  | ValD       (XValD p)       (HsBind p)        -- ^ Value declaration
145  | SigD       (XSigD p)       (Sig p)           -- ^ Signature declaration
146  | KindSigD   (XKindSigD p)   (StandaloneKindSig p) -- ^ Standalone kind signature
147  | DefD       (XDefD p)       (DefaultDecl p)   -- ^ 'default' declaration
148  | ForD       (XForD p)       (ForeignDecl p)   -- ^ Foreign declaration
149  | WarningD   (XWarningD p)   (WarnDecls p)     -- ^ Warning declaration
150  | AnnD       (XAnnD p)       (AnnDecl p)       -- ^ Annotation declaration
151  | RuleD      (XRuleD p)      (RuleDecls p)     -- ^ Rule declaration
152  | SpliceD    (XSpliceD p)    (SpliceDecl p)    -- ^ Splice declaration
153                                                 -- (Includes quasi-quotes)
154  | DocD       (XDocD p)       (DocDecl)  -- ^ Documentation comment declaration
155  | RoleAnnotD (XRoleAnnotD p) (RoleAnnotDecl p) -- ^Role annotation declaration
156  | XHsDecl    !(XXHsDecl p)
157
158{-
159Note [Top-level fixity signatures in an HsGroup]
160~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
161An `HsGroup p` stores every top-level fixity declarations in one of two places:
162
1631. hs_fixds :: [LFixitySig p]
164
165   This stores fixity signatures for top-level declarations (e.g., functions,
166   data constructors, classes, type families, etc.) as well as fixity
167   signatures for class methods written outside of the class, as in this
168   example:
169
170     infixl 4 `m1`
171     class C1 a where
172       m1 :: a -> a -> a
173
1742. hs_tyclds :: [TyClGroup p]
175
176   Each type class can be found in a TyClDecl inside a TyClGroup, and that
177   TyClDecl stores the fixity signatures for its methods written inside of the
178   class, as in this example:
179
180     class C2 a where
181       infixl 4 `m2`
182       m2 :: a -> a -> a
183
184The story for fixity signatures for class methods is made slightly complicated
185by the fact that they can appear both inside and outside of the class itself,
186and both forms of fixity signatures are considered top-level. This matters
187in `GHC.Rename.Module.rnSrcDecls`, which must create a fixity environment out
188of all top-level fixity signatures before doing anything else. Therefore,
189`rnSrcDecls` must be aware of both (1) and (2) above. The
190`hsGroupTopLevelFixitySigs` function is responsible for collecting this
191information from an `HsGroup`.
192
193One might wonder why we even bother separating top-level fixity signatures
194into two places at all. That is, why not just take the fixity signatures
195from `hs_tyclds` and put them into `hs_fixds` so that they are all in one
196location? This ends up causing problems for `GHC.HsToCore.Quote.repTopDs`,
197which translates each fixity signature in `hs_fixds` and `hs_tyclds` into a
198Template Haskell `Dec`. If there are any duplicate signatures between the two
199fields, this will result in an error (#17608).
200-}
201
202-- | Haskell Group
203--
204-- A 'HsDecl' is categorised into a 'HsGroup' before being
205-- fed to the renamer.
206data HsGroup p
207  = HsGroup {
208        hs_ext    :: XCHsGroup p,
209        hs_valds  :: HsValBinds p,
210        hs_splcds :: [LSpliceDecl p],
211
212        hs_tyclds :: [TyClGroup p],
213                -- A list of mutually-recursive groups;
214                -- This includes `InstDecl`s as well;
215                -- Parser generates a singleton list;
216                -- renamer does dependency analysis
217
218        hs_derivds :: [LDerivDecl p],
219
220        hs_fixds  :: [LFixitySig p],
221                -- A list of fixity signatures defined for top-level
222                -- declarations and class methods (defined outside of the class
223                -- itself).
224                -- See Note [Top-level fixity signatures in an HsGroup]
225
226        hs_defds  :: [LDefaultDecl p],
227        hs_fords  :: [LForeignDecl p],
228        hs_warnds :: [LWarnDecls p],
229        hs_annds  :: [LAnnDecl p],
230        hs_ruleds :: [LRuleDecls p],
231
232        hs_docs   :: [LDocDecl p]
233    }
234  | XHsGroup !(XXHsGroup p)
235
236
237hsGroupInstDecls :: HsGroup id -> [LInstDecl id]
238hsGroupInstDecls = (=<<) group_instds . hs_tyclds
239
240-- | Located Splice Declaration
241type LSpliceDecl pass = XRec pass (SpliceDecl pass)
242
243-- | Splice Declaration
244data SpliceDecl p
245  = SpliceDecl                  -- Top level splice
246        (XSpliceDecl p)
247        (XRec p (HsSplice p))
248        SpliceExplicitFlag
249  | XSpliceDecl !(XXSpliceDecl p)
250
251{-
252************************************************************************
253*                                                                      *
254            Type and class declarations
255*                                                                      *
256************************************************************************
257
258Note [The Naming story]
259~~~~~~~~~~~~~~~~~~~~~~~
260Here is the story about the implicit names that go with type, class,
261and instance decls.  It's a bit tricky, so pay attention!
262
263"Implicit" (or "system") binders
264~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
265  Each data type decl defines
266        a worker name for each constructor
267        to-T and from-T convertors
268  Each class decl defines
269        a tycon for the class
270        a data constructor for that tycon
271        the worker for that constructor
272        a selector for each superclass
273
274All have occurrence names that are derived uniquely from their parent
275declaration.
276
277None of these get separate definitions in an interface file; they are
278fully defined by the data or class decl.  But they may *occur* in
279interface files, of course.  Any such occurrence must haul in the
280relevant type or class decl.
281
282Plan of attack:
283 - Ensure they "point to" the parent data/class decl
284   when loading that decl from an interface file
285   (See RnHiFiles.getSysBinders)
286
287 - When typechecking the decl, we build the implicit TyCons and Ids.
288   When doing so we look them up in the name cache (GHC.Rename.Env.lookupSysName),
289   to ensure correct module and provenance is set
290
291These are the two places that we have to conjure up the magic derived
292names.  (The actual magic is in GHC.Types.Name.Occurrence.mkWorkerOcc, etc.)
293
294Default methods
295~~~~~~~~~~~~~~~
296 - Occurrence name is derived uniquely from the method name
297   E.g. $dmmax
298
299 - If there is a default method name at all, it's recorded in
300   the ClassOpSig (in GHC.Hs.Binds), in the DefMethInfo field.
301   (DefMethInfo is defined in GHC.Core.Class)
302
303Source-code class decls and interface-code class decls are treated subtly
304differently, which has given me a great deal of confusion over the years.
305Here's the deal.  (We distinguish the two cases because source-code decls
306have (Just binds) in the tcdMeths field, whereas interface decls have Nothing.
307
308In *source-code* class declarations:
309
310 - When parsing, every ClassOpSig gets a DefMeth with a suitable RdrName
311   This is done by GHC.Parser.PostProcess.mkClassOpSigDM
312
313 - The renamer renames it to a Name
314
315 - During typechecking, we generate a binding for each $dm for
316   which there's a programmer-supplied default method:
317        class Foo a where
318          op1 :: <type>
319          op2 :: <type>
320          op1 = ...
321   We generate a binding for $dmop1 but not for $dmop2.
322   The Class for Foo has a Nothing for op2 and
323                         a Just ($dm_op1, VanillaDM) for op1.
324   The Name for $dmop2 is simply discarded.
325
326In *interface-file* class declarations:
327  - When parsing, we see if there's an explicit programmer-supplied default method
328    because there's an '=' sign to indicate it:
329        class Foo a where
330          op1 = :: <type>       -- NB the '='
331          op2   :: <type>
332    We use this info to generate a DefMeth with a suitable RdrName for op1,
333    and a NoDefMeth for op2
334  - The interface file has a separate definition for $dmop1, with unfolding etc.
335  - The renamer renames it to a Name.
336  - The renamer treats $dmop1 as a free variable of the declaration, so that
337    the binding for $dmop1 will be sucked in.  (See RnHsSyn.tyClDeclFVs)
338    This doesn't happen for source code class decls, because they *bind* the default method.
339
340Dictionary functions
341~~~~~~~~~~~~~~~~~~~~
342Each instance declaration gives rise to one dictionary function binding.
343
344The type checker makes up new source-code instance declarations
345(e.g. from 'deriving' or generic default methods --- see
346GHC.Tc.TyCl.Instance.tcInstDecls1).  So we can't generate the names for
347dictionary functions in advance (we don't know how many we need).
348
349On the other hand for interface-file instance declarations, the decl
350specifies the name of the dictionary function, and it has a binding elsewhere
351in the interface file:
352        instance {Eq Int} = dEqInt
353        dEqInt :: {Eq Int} <pragma info>
354
355So again we treat source code and interface file code slightly differently.
356
357Source code:
358  - Source code instance decls have a Nothing in the (Maybe name) field
359    (see data InstDecl below)
360
361  - The typechecker makes up a Local name for the dict fun for any source-code
362    instance decl, whether it comes from a source-code instance decl, or whether
363    the instance decl is derived from some other construct (e.g. 'deriving').
364
365  - The occurrence name it chooses is derived from the instance decl (just for
366    documentation really) --- e.g. dNumInt.  Two dict funs may share a common
367    occurrence name, but will have different uniques.  E.g.
368        instance Foo [Int]  where ...
369        instance Foo [Bool] where ...
370    These might both be dFooList
371
372  - The CoreTidy phase externalises the name, and ensures the occurrence name is
373    unique (this isn't special to dict funs).  So we'd get dFooList and dFooList1.
374
375  - We can take this relaxed approach (changing the occurrence name later)
376    because dict fun Ids are not captured in a TyCon or Class (unlike default
377    methods, say).  Instead, they are kept separately in the InstEnv.  This
378    makes it easy to adjust them after compiling a module.  (Once we've finished
379    compiling that module, they don't change any more.)
380
381
382Interface file code:
383  - The instance decl gives the dict fun name, so the InstDecl has a (Just name)
384    in the (Maybe name) field.
385
386  - RnHsSyn.instDeclFVs treats the dict fun name as free in the decl, so that we
387    suck in the dfun binding
388-}
389
390-- | Located Declaration of a Type or Class
391type LTyClDecl pass = XRec pass (TyClDecl pass)
392
393-- | A type or class declaration.
394data TyClDecl pass
395  = -- | @type/data family T :: *->*@
396    --
397    --  - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnType',
398    --             'GHC.Parser.Annotation.AnnData',
399    --             'GHC.Parser.Annotation.AnnFamily','GHC.Parser.Annotation.AnnDcolon',
400    --             'GHC.Parser.Annotation.AnnWhere','GHC.Parser.Annotation.AnnOpenP',
401    --             'GHC.Parser.Annotation.AnnDcolon','GHC.Parser.Annotation.AnnCloseP',
402    --             'GHC.Parser.Annotation.AnnEqual','GHC.Parser.Annotation.AnnRarrow',
403    --             'GHC.Parser.Annotation.AnnVbar'
404
405    -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
406    FamDecl { tcdFExt :: XFamDecl pass, tcdFam :: FamilyDecl pass }
407
408  | -- | @type@ declaration
409    --
410    --  - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnType',
411    --             'GHC.Parser.Annotation.AnnEqual',
412
413    -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
414    SynDecl { tcdSExt   :: XSynDecl pass          -- ^ Post renameer, FVs
415            , tcdLName  :: LIdP pass              -- ^ Type constructor
416            , tcdTyVars :: LHsQTyVars pass        -- ^ Type variables; for an
417                                                  -- associated type these
418                                                  -- include outer binders
419            , tcdFixity :: LexicalFixity          -- ^ Fixity used in the declaration
420            , tcdRhs    :: LHsType pass }         -- ^ RHS of type declaration
421
422  | -- | @data@ declaration
423    --
424    --  - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnData',
425    --              'GHC.Parser.Annotation.AnnFamily',
426    --              'GHC.Parser.Annotation.AnnNewType',
427    --              'GHC.Parser.Annotation.AnnNewType','GHC.Parser.Annotation.AnnDcolon'
428    --              'GHC.Parser.Annotation.AnnWhere',
429
430    -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
431    DataDecl { tcdDExt     :: XDataDecl pass       -- ^ Post renamer, CUSK flag, FVs
432             , tcdLName    :: LIdP pass             -- ^ Type constructor
433             , tcdTyVars   :: LHsQTyVars pass      -- ^ Type variables
434                              -- See Note [TyVar binders for associated declarations]
435             , tcdFixity   :: LexicalFixity        -- ^ Fixity used in the declaration
436             , tcdDataDefn :: HsDataDefn pass }
437
438  | ClassDecl { tcdCExt    :: XClassDecl pass,         -- ^ Post renamer, FVs
439                tcdCtxt    :: Maybe (LHsContext pass), -- ^ Context...
440                tcdLName   :: LIdP pass,               -- ^ Name of the class
441                tcdTyVars  :: LHsQTyVars pass,         -- ^ Class type variables
442                tcdFixity  :: LexicalFixity, -- ^ Fixity used in the declaration
443                tcdFDs     :: [LHsFunDep pass],         -- ^ Functional deps
444                tcdSigs    :: [LSig pass],              -- ^ Methods' signatures
445                tcdMeths   :: LHsBinds pass,            -- ^ Default methods
446                tcdATs     :: [LFamilyDecl pass],       -- ^ Associated types;
447                tcdATDefs  :: [LTyFamDefltDecl pass],   -- ^ Associated type defaults
448                tcdDocs    :: [LDocDecl pass]           -- ^ Haddock docs
449    }
450        -- ^ - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnClass',
451        --           'GHC.Parser.Annotation.AnnWhere','GHC.Parser.Annotation.AnnOpen',
452        --           'GHC.Parser.Annotation.AnnClose'
453        --   - The tcdFDs will have 'GHC.Parser.Annotation.AnnVbar',
454        --                          'GHC.Parser.Annotation.AnnComma'
455        --                          'GHC.Parser.Annotation.AnnRarrow'
456
457        -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
458  | XTyClDecl !(XXTyClDecl pass)
459
460data FunDep pass
461  = FunDep (XCFunDep pass)
462           [LIdP pass]
463           [LIdP pass]
464  | XFunDep !(XXFunDep pass)
465
466type LHsFunDep pass = XRec pass (FunDep pass)
467
468data DataDeclRn = DataDeclRn
469             { tcdDataCusk :: Bool    -- ^ does this have a CUSK?
470                 -- See Note [CUSKs: complete user-supplied kind signatures]
471             , tcdFVs      :: NameSet }
472  deriving Data
473
474{- Note [TyVar binders for associated decls]
475~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
476For an /associated/ data, newtype, or type-family decl, the LHsQTyVars
477/includes/ outer binders.  For example
478    class T a where
479       data D a c
480       type F a b :: *
481       type F a b = a -> a
482Here the data decl for 'D', and type-family decl for 'F', both include 'a'
483in their LHsQTyVars (tcdTyVars and fdTyVars resp).
484
485Ditto any implicit binders in the hsq_implicit field of the LHSQTyVars.
486
487The idea is that the associated type is really a top-level decl in its
488own right.  However we are careful to use the same name 'a', so that
489we can match things up.
490
491c.f. Note [Associated type tyvar names] in GHC.Core.Class
492     Note [Family instance declaration binders]
493-}
494
495{- Note [Class LayoutInfo]
496~~~~~~~~~~~~~~~~~~~~~~~~~~
497The LayoutInfo is used to associate Haddock comments with parts of the declaration.
498Compare the following examples:
499
500    class C a where
501      f :: a -> Int
502      -- ^ comment on f
503
504    class C a where
505      f :: a -> Int
506    -- ^ comment on C
507
508Notice how "comment on f" and "comment on C" differ only by indentation level.
509Thus we have to record the indentation level of the class declarations.
510
511See also Note [Adding Haddock comments to the syntax tree] in GHC.Parser.PostProcess.Haddock
512-}
513
514-- Simple classifiers for TyClDecl
515-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
516
517-- | @True@ <=> argument is a @data@\/@newtype@
518-- declaration.
519isDataDecl :: TyClDecl pass -> Bool
520isDataDecl (DataDecl {}) = True
521isDataDecl _other        = False
522
523-- | type or type instance declaration
524isSynDecl :: TyClDecl pass -> Bool
525isSynDecl (SynDecl {})   = True
526isSynDecl _other        = False
527
528-- | type class
529isClassDecl :: TyClDecl pass -> Bool
530isClassDecl (ClassDecl {}) = True
531isClassDecl _              = False
532
533-- | type/data family declaration
534isFamilyDecl :: TyClDecl pass -> Bool
535isFamilyDecl (FamDecl {})  = True
536isFamilyDecl _other        = False
537
538-- | type family declaration
539isTypeFamilyDecl :: TyClDecl pass -> Bool
540isTypeFamilyDecl (FamDecl _ (FamilyDecl { fdInfo = info })) = case info of
541  OpenTypeFamily      -> True
542  ClosedTypeFamily {} -> True
543  _                   -> False
544isTypeFamilyDecl _ = False
545
546-- | open type family info
547isOpenTypeFamilyInfo :: FamilyInfo pass -> Bool
548isOpenTypeFamilyInfo OpenTypeFamily = True
549isOpenTypeFamilyInfo _              = False
550
551-- | closed type family info
552isClosedTypeFamilyInfo :: FamilyInfo pass -> Bool
553isClosedTypeFamilyInfo (ClosedTypeFamily {}) = True
554isClosedTypeFamilyInfo _                     = False
555
556-- | data family declaration
557isDataFamilyDecl :: TyClDecl pass -> Bool
558isDataFamilyDecl (FamDecl _ (FamilyDecl { fdInfo = DataFamily })) = True
559isDataFamilyDecl _other      = False
560
561-- Dealing with names
562
563tyClDeclTyVars :: TyClDecl pass -> LHsQTyVars pass
564tyClDeclTyVars (FamDecl { tcdFam = FamilyDecl { fdTyVars = tvs } }) = tvs
565tyClDeclTyVars d = tcdTyVars d
566
567countTyClDecls :: [TyClDecl pass] -> (Int, Int, Int, Int, Int)
568        -- class, synonym decls, data, newtype, family decls
569countTyClDecls decls
570 = (count isClassDecl    decls,
571    count isSynDecl      decls,  -- excluding...
572    count isDataTy       decls,  -- ...family...
573    count isNewTy        decls,  -- ...instances
574    count isFamilyDecl   decls)
575 where
576   isDataTy DataDecl{ tcdDataDefn = HsDataDefn { dd_ND = DataType } } = True
577   isDataTy _                                                       = False
578
579   isNewTy DataDecl{ tcdDataDefn = HsDataDefn { dd_ND = NewType } } = True
580   isNewTy _                                                      = False
581
582
583{- Note [CUSKs: complete user-supplied kind signatures]
584~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
585We kind-check declarations differently if they have a complete, user-supplied
586kind signature (CUSK). This is because we can safely generalise a CUSKed
587declaration before checking all of the others, supporting polymorphic recursion.
588See https://gitlab.haskell.org/ghc/ghc/wikis/ghc-kinds/kind-inference#proposed-new-strategy
589and #9200 for lots of discussion of how we got here.
590
591The detection of CUSKs is enabled by the -XCUSKs extension, switched on by default.
592Under -XNoCUSKs, all declarations are treated as if they have no CUSK.
593See https://github.com/ghc-proposals/ghc-proposals/blob/master/proposals/0036-kind-signatures.rst
594
595PRINCIPLE:
596  a type declaration has a CUSK iff we could produce a separate kind signature
597  for it, just like a type signature for a function,
598  looking only at the header of the declaration.
599
600Examples:
601  * data T1 (a :: *->*) (b :: *) = ....
602    -- Has CUSK; equivalant to   T1 :: (*->*) -> * -> *
603
604 * data T2 a b = ...
605   -- No CUSK; we do not want to guess T2 :: * -> * -> *
606   -- because the full decl might be   data T a b = MkT (a b)
607
608  * data T3 (a :: k -> *) (b :: *) = ...
609    -- CUSK; equivalent to   T3 :: (k -> *) -> * -> *
610    -- We lexically generalise over k to get
611    --    T3 :: forall k. (k -> *) -> * -> *
612    -- The generalisation is here is purely lexical, just like
613    --    f3 :: a -> a
614    -- means
615    --    f3 :: forall a. a -> a
616
617  * data T4 (a :: j k) = ...
618     -- CUSK; equivalent to   T4 :: j k -> *
619     -- which we lexically generalise to  T4 :: forall j k. j k -> *
620     -- and then, if PolyKinds is on, we further generalise to
621     --   T4 :: forall kk (j :: kk -> *) (k :: kk). j k -> *
622     -- Again this is exactly like what happens as the term level
623     -- when you write
624     --    f4 :: forall a b. a b -> Int
625
626NOTE THAT
627  * A CUSK does /not/ mean that everything about the kind signature is
628    fully specified by the user.  Look at T4 and f4: we had to do kind
629    inference to figure out the kind-quantification.  But in both cases
630    (T4 and f4) that inference is done looking /only/ at the header of T4
631    (or signature for f4), not at the definition thereof.
632
633  * The CUSK completely fixes the kind of the type constructor, forever.
634
635  * The precise rules, for each declaration form, for whether a declaration
636    has a CUSK are given in the user manual section "Complete user-supplied
637    kind signatures and polymorphic recursion".  But they simply implement
638    PRINCIPLE above.
639
640  * Open type families are interesting:
641      type family T5 a b :: *
642    There simply /is/ no accompanying declaration, so that info is all
643    we'll ever get.  So we it has a CUSK by definition, and we default
644    any un-fixed kind variables to *.
645
646  * Associated types are a bit tricker:
647      class C6 a where
648         type family T6 a b :: *
649         op :: a Int -> Int
650    Here C6 does not have a CUSK (in fact we ultimately discover that
651    a :: * -> *).  And hence neither does T6, the associated family,
652    because we can't fix its kind until we have settled C6.  Another
653    way to say it: unlike a top-level, we /may/ discover more about
654    a's kind from C6's definition.
655
656  * A data definition with a top-level :: must explicitly bind all
657    kind variables to the right of the ::. See test
658    dependent/should_compile/KindLevels, which requires this
659    case. (Naturally, any kind variable mentioned before the :: should
660    not be bound after it.)
661
662    This last point is much more debatable than the others; see
663    #15142 comment:22
664
665    Because this is fiddly to check, there is a field in the DataDeclRn
666    structure (included in a DataDecl after the renamer) that stores whether
667    or not the declaration has a CUSK.
668-}
669
670
671{- *********************************************************************
672*                                                                      *
673                         TyClGroup
674        Strongly connected components of
675      type, class, instance, and role declarations
676*                                                                      *
677********************************************************************* -}
678
679{- Note [TyClGroups and dependency analysis]
680~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
681A TyClGroup represents a strongly connected components of type/class/instance
682decls, together with the role annotations for the type/class declarations.
683
684The hs_tyclds :: [TyClGroup] field of a HsGroup is a dependency-order
685sequence of strongly-connected components.
686
687Invariants
688 * The type and class declarations, group_tyclds, may depend on each
689   other, or earlier TyClGroups, but not on later ones
690
691 * The role annotations, group_roles, are role-annotations for some or
692   all of the types and classes in group_tyclds (only).
693
694 * The instance declarations, group_instds, may (and usually will)
695   depend on group_tyclds, or on earlier TyClGroups, but not on later
696   ones.
697
698See Note [Dependency analysis of type, class, and instance decls]
699in GHC.Rename.Module for more info.
700-}
701
702-- | Type or Class Group
703data TyClGroup pass  -- See Note [TyClGroups and dependency analysis]
704  = TyClGroup { group_ext    :: XCTyClGroup pass
705              , group_tyclds :: [LTyClDecl pass]
706              , group_roles  :: [LRoleAnnotDecl pass]
707              , group_kisigs :: [LStandaloneKindSig pass]
708              , group_instds :: [LInstDecl pass] }
709  | XTyClGroup !(XXTyClGroup pass)
710
711
712tyClGroupTyClDecls :: [TyClGroup pass] -> [LTyClDecl pass]
713tyClGroupTyClDecls = concatMap group_tyclds
714
715tyClGroupInstDecls :: [TyClGroup pass] -> [LInstDecl pass]
716tyClGroupInstDecls = concatMap group_instds
717
718tyClGroupRoleDecls :: [TyClGroup pass] -> [LRoleAnnotDecl pass]
719tyClGroupRoleDecls = concatMap group_roles
720
721tyClGroupKindSigs :: [TyClGroup pass] -> [LStandaloneKindSig pass]
722tyClGroupKindSigs = concatMap group_kisigs
723
724
725{- *********************************************************************
726*                                                                      *
727               Data and type family declarations
728*                                                                      *
729********************************************************************* -}
730
731{- Note [FamilyResultSig]
732~~~~~~~~~~~~~~~~~~~~~~~~~
733
734This data type represents the return signature of a type family.  Possible
735values are:
736
737 * NoSig - the user supplied no return signature:
738      type family Id a where ...
739
740 * KindSig - the user supplied the return kind:
741      type family Id a :: * where ...
742
743 * TyVarSig - user named the result with a type variable and possibly
744   provided a kind signature for that variable:
745      type family Id a = r where ...
746      type family Id a = (r :: *) where ...
747
748   Naming result of a type family is required if we want to provide
749   injectivity annotation for a type family:
750      type family Id a = r | r -> a where ...
751
752See also: Note [Injectivity annotation]
753
754Note [Injectivity annotation]
755~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
756
757A user can declare a type family to be injective:
758
759   type family Id a = r | r -> a where ...
760
761 * The part after the "|" is called "injectivity annotation".
762 * "r -> a" part is called "injectivity condition"; at the moment terms
763   "injectivity annotation" and "injectivity condition" are synonymous
764   because we only allow a single injectivity condition.
765 * "r" is the "LHS of injectivity condition". LHS can only contain the
766   variable naming the result of a type family.
767
768 * "a" is the "RHS of injectivity condition". RHS contains space-separated
769   type and kind variables representing the arguments of a type
770   family. Variables can be omitted if a type family is not injective in
771   these arguments. Example:
772         type family Foo a b c = d | d -> a c where ...
773
774Note that:
775 (a) naming of type family result is required to provide injectivity
776     annotation
777 (b) for associated types if the result was named then injectivity annotation
778     is mandatory. Otherwise result type variable is indistinguishable from
779     associated type default.
780
781It is possible that in the future this syntax will be extended to support
782more complicated injectivity annotations. For example we could declare that
783if we know the result of Plus and one of its arguments we can determine the
784other argument:
785
786   type family Plus a b = (r :: Nat) | r a -> b, r b -> a where ...
787
788Here injectivity annotation would consist of two comma-separated injectivity
789conditions.
790
791See also Note [Injective type families] in GHC.Core.TyCon
792-}
793
794-- | Located type Family Result Signature
795type LFamilyResultSig pass = XRec pass (FamilyResultSig pass)
796
797-- | type Family Result Signature
798data FamilyResultSig pass = -- see Note [FamilyResultSig]
799    NoSig (XNoSig pass)
800  -- ^ - 'GHC.Parser.Annotation.AnnKeywordId' :
801
802  -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
803
804  | KindSig  (XCKindSig pass) (LHsKind pass)
805  -- ^ - 'GHC.Parser.Annotation.AnnKeywordId' :
806  --             'GHC.Parser.Annotation.AnnOpenP','GHC.Parser.Annotation.AnnDcolon',
807  --             'GHC.Parser.Annotation.AnnCloseP'
808
809  -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
810
811  | TyVarSig (XTyVarSig pass) (LHsTyVarBndr () pass)
812  -- ^ - 'GHC.Parser.Annotation.AnnKeywordId' :
813  --             'GHC.Parser.Annotation.AnnOpenP','GHC.Parser.Annotation.AnnDcolon',
814  --             'GHC.Parser.Annotation.AnnCloseP', 'GHC.Parser.Annotation.AnnEqual'
815  | XFamilyResultSig !(XXFamilyResultSig pass)
816
817  -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
818
819
820-- | Located type Family Declaration
821type LFamilyDecl pass = XRec pass (FamilyDecl pass)
822
823-- | type Family Declaration
824data FamilyDecl pass = FamilyDecl
825  { fdExt            :: XCFamilyDecl pass
826  , fdInfo           :: FamilyInfo pass              -- type/data, closed/open
827  , fdTopLevel       :: TopLevelFlag                 -- used for printing only
828  , fdLName          :: LIdP pass                    -- type constructor
829  , fdTyVars         :: LHsQTyVars pass              -- type variables
830                       -- See Note [TyVar binders for associated declarations]
831  , fdFixity         :: LexicalFixity                -- Fixity used in the declaration
832  , fdResultSig      :: LFamilyResultSig pass        -- result signature
833  , fdInjectivityAnn :: Maybe (LInjectivityAnn pass) -- optional injectivity ann
834  }
835  | XFamilyDecl !(XXFamilyDecl pass)
836  -- ^ - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnType',
837  --             'GHC.Parser.Annotation.AnnData', 'GHC.Parser.Annotation.AnnFamily',
838  --             'GHC.Parser.Annotation.AnnWhere', 'GHC.Parser.Annotation.AnnOpenP',
839  --             'GHC.Parser.Annotation.AnnDcolon', 'GHC.Parser.Annotation.AnnCloseP',
840  --             'GHC.Parser.Annotation.AnnEqual', 'GHC.Parser.Annotation.AnnRarrow',
841  --             'GHC.Parser.Annotation.AnnVbar'
842
843  -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
844
845
846-- | Located Injectivity Annotation
847type LInjectivityAnn pass = XRec pass (InjectivityAnn pass)
848
849-- | If the user supplied an injectivity annotation it is represented using
850-- InjectivityAnn. At the moment this is a single injectivity condition - see
851-- Note [Injectivity annotation]. `Located name` stores the LHS of injectivity
852-- condition. `[Located name]` stores the RHS of injectivity condition. Example:
853--
854--   type family Foo a b c = r | r -> a c where ...
855--
856-- This will be represented as "InjectivityAnn `r` [`a`, `c`]"
857data InjectivityAnn pass
858  = InjectivityAnn (XCInjectivityAnn pass)
859                   (LIdP pass) [LIdP pass]
860  -- ^ - 'GHC.Parser.Annotation.AnnKeywordId' :
861  --             'GHC.Parser.Annotation.AnnRarrow', 'GHC.Parser.Annotation.AnnVbar'
862
863  -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
864  | XInjectivityAnn !(XXInjectivityAnn pass)
865
866data FamilyInfo pass
867  = DataFamily
868  | OpenTypeFamily
869     -- | 'Nothing' if we're in an hs-boot file and the user
870     -- said "type family Foo x where .."
871  | ClosedTypeFamily (Maybe [LTyFamInstEqn pass])
872
873
874------------- Pretty printing FamilyDecls -----------
875
876pprFlavour :: FamilyInfo pass -> SDoc
877pprFlavour DataFamily            = text "data"
878pprFlavour OpenTypeFamily        = text "type"
879pprFlavour (ClosedTypeFamily {}) = text "type"
880
881instance Outputable (FamilyInfo pass) where
882  ppr info = pprFlavour info <+> text "family"
883
884
885
886{- *********************************************************************
887*                                                                      *
888               Data types and data constructors
889*                                                                      *
890********************************************************************* -}
891
892-- | Haskell Data type Definition
893data HsDataDefn pass   -- The payload of a data type defn
894                       -- Used *both* for vanilla data declarations,
895                       --       *and* for data family instances
896  = -- | Declares a data type or newtype, giving its constructors
897    -- @
898    --  data/newtype T a = <constrs>
899    --  data/newtype instance T [a] = <constrs>
900    -- @
901    HsDataDefn { dd_ext    :: XCHsDataDefn pass,
902                 dd_ND     :: NewOrData,
903                 dd_ctxt   :: Maybe (LHsContext pass), -- ^ Context
904                 dd_cType  :: Maybe (XRec pass CType),
905                 dd_kindSig:: Maybe (LHsKind pass),
906                     -- ^ Optional kind signature.
907                     --
908                     -- @(Just k)@ for a GADT-style @data@,
909                     -- or @data instance@ decl, with explicit kind sig
910                     --
911                     -- Always @Nothing@ for H98-syntax decls
912
913                 dd_cons   :: [LConDecl pass],
914                     -- ^ Data constructors
915                     --
916                     -- For @data T a = T1 | T2 a@
917                     --   the 'LConDecl's all have 'ConDeclH98'.
918                     -- For @data T a where { T1 :: T a }@
919                     --   the 'LConDecls' all have 'ConDeclGADT'.
920
921                 dd_derivs :: HsDeriving pass  -- ^ Optional 'deriving' clause
922
923             -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
924   }
925  | XHsDataDefn !(XXHsDataDefn pass)
926
927-- | Haskell Deriving clause
928type HsDeriving pass = [LHsDerivingClause pass]
929  -- ^ The optional @deriving@ clauses of a data declaration. "Clauses" is
930  -- plural because one can specify multiple deriving clauses using the
931  -- @-XDerivingStrategies@ language extension.
932  --
933  -- The list of 'LHsDerivingClause's corresponds to exactly what the user
934  -- requested to derive, in order. If no deriving clauses were specified,
935  -- the list is empty.
936
937type LHsDerivingClause pass = XRec pass (HsDerivingClause pass)
938
939-- | A single @deriving@ clause of a data declaration.
940--
941--  - 'GHC.Parser.Annotation.AnnKeywordId' :
942--       'GHC.Parser.Annotation.AnnDeriving', 'GHC.Parser.Annotation.AnnStock',
943--       'GHC.Parser.Annotation.AnnAnyClass', 'GHC.Parser.Annotation.AnnNewtype',
944--       'GHC.Parser.Annotation.AnnOpen','GHC.Parser.Annotation.AnnClose'
945data HsDerivingClause pass
946  -- See Note [Deriving strategies] in GHC.Tc.Deriv
947  = HsDerivingClause
948    { deriv_clause_ext :: XCHsDerivingClause pass
949    , deriv_clause_strategy :: Maybe (LDerivStrategy pass)
950      -- ^ The user-specified strategy (if any) to use when deriving
951      -- 'deriv_clause_tys'.
952    , deriv_clause_tys :: LDerivClauseTys pass
953      -- ^ The types to derive.
954    }
955  | XHsDerivingClause !(XXHsDerivingClause pass)
956
957type LDerivClauseTys pass = XRec pass (DerivClauseTys pass)
958
959-- | The types mentioned in a single @deriving@ clause. This can come in two
960-- forms, 'DctSingle' or 'DctMulti', depending on whether the types are
961-- surrounded by enclosing parentheses or not. These parentheses are
962-- semantically different than 'HsParTy'. For example, @deriving ()@ means
963-- \"derive zero classes\" rather than \"derive an instance of the 0-tuple\".
964--
965-- 'DerivClauseTys' use 'LHsSigType' because @deriving@ clauses can mention
966-- type variables that aren't bound by the datatype, e.g.
967--
968-- > data T b = ... deriving (C [a])
969--
970-- should produce a derived instance for @C [a] (T b)@.
971data DerivClauseTys pass
972  = -- | A @deriving@ clause with a single type. Moreover, that type can only
973    -- be a type constructor without any arguments.
974    --
975    -- Example: @deriving Eq@
976    DctSingle (XDctSingle pass) (LHsSigType pass)
977
978    -- | A @deriving@ clause with a comma-separated list of types, surrounded
979    -- by enclosing parentheses.
980    --
981    -- Example: @deriving (Eq, C a)@
982  | DctMulti (XDctMulti pass) [LHsSigType pass]
983
984  | XDerivClauseTys !(XXDerivClauseTys pass)
985
986-- | Located Standalone Kind Signature
987type LStandaloneKindSig pass = XRec pass (StandaloneKindSig pass)
988
989data StandaloneKindSig pass
990  = StandaloneKindSig (XStandaloneKindSig pass)
991      (LIdP pass)           -- Why a single binder? See #16754
992      (LHsSigType pass)     -- Why not LHsSigWcType? See Note [Wildcards in standalone kind signatures]
993  | XStandaloneKindSig !(XXStandaloneKindSig pass)
994
995{- Note [Wildcards in standalone kind signatures]
996~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
997Standalone kind signatures enable polymorphic recursion, and it is unclear how
998to reconcile this with partial type signatures, so we disallow wildcards in
999them.
1000
1001We reject wildcards in 'rnStandaloneKindSignature' by returning False for
1002'StandaloneKindSigCtx' in 'wildCardsAllowed'.
1003
1004The alternative design is to have special treatment for partial standalone kind
1005signatures, much like we have special treatment for partial type signatures in
1006terms. However, partial standalone kind signatures are not a proper replacement
1007for CUSKs, so this would be a separate feature.
1008-}
1009
1010data NewOrData
1011  = NewType                     -- ^ @newtype Blah ...@
1012  | DataType                    -- ^ @data Blah ...@
1013  deriving( Eq, Data )                -- Needed because Demand derives Eq
1014
1015-- | Convert a 'NewOrData' to a 'TyConFlavour'
1016newOrDataToFlavour :: NewOrData -> TyConFlavour
1017newOrDataToFlavour NewType  = NewtypeFlavour
1018newOrDataToFlavour DataType = DataTypeFlavour
1019
1020
1021-- | Located data Constructor Declaration
1022type LConDecl pass = XRec pass (ConDecl pass)
1023      -- ^ May have 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnSemi' when
1024      --   in a GADT constructor list
1025
1026  -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
1027
1028-- |
1029--
1030-- @
1031-- data T b = forall a. Eq a => MkT a b
1032--   MkT :: forall b a. Eq a => MkT a b
1033--
1034-- data T b where
1035--      MkT1 :: Int -> T Int
1036--
1037-- data T = Int `MkT` Int
1038--        | MkT2
1039--
1040-- data T a where
1041--      Int `MkT` Int :: T Int
1042-- @
1043--
1044-- - 'GHC.Parser.Annotation.AnnKeywordId's : 'GHC.Parser.Annotation.AnnOpen',
1045--            'GHC.Parser.Annotation.AnnDotdot','GHC.Parser.Annotation.AnnCLose',
1046--            'GHC.Parser.Annotation.AnnEqual','GHC.Parser.Annotation.AnnVbar',
1047--            'GHC.Parser.Annotation.AnnDarrow','GHC.Parser.Annotation.AnnDarrow',
1048--            'GHC.Parser.Annotation.AnnForall','GHC.Parser.Annotation.AnnDot'
1049
1050-- For details on above see note [exact print annotations] in GHC.Parser.Annotation
1051
1052-- | data Constructor Declaration
1053data ConDecl pass
1054  = ConDeclGADT
1055      { con_g_ext   :: XConDeclGADT pass
1056      , con_names   :: [LIdP pass]
1057
1058      -- The following fields describe the type after the '::'
1059      -- See Note [GADT abstract syntax]
1060      , con_bndrs   :: XRec pass (HsOuterSigTyVarBndrs pass)
1061        -- ^ The outermost type variable binders, be they explicit or
1062        --   implicit.  The 'XRec' is used to anchor exact print
1063        --   annotations, AnnForall and AnnDot.
1064      , con_mb_cxt  :: Maybe (LHsContext pass)   -- ^ User-written context (if any)
1065      , con_g_args  :: HsConDeclGADTDetails pass -- ^ Arguments; never infix
1066      , con_res_ty  :: LHsType pass              -- ^ Result type
1067
1068      , con_doc     :: Maybe LHsDocString
1069          -- ^ A possible Haddock comment.
1070      }
1071
1072  | ConDeclH98
1073      { con_ext     :: XConDeclH98 pass
1074      , con_name    :: LIdP pass
1075
1076      , con_forall  :: Bool
1077                              -- ^ True <=> explicit user-written forall
1078                              --     e.g. data T a = forall b. MkT b (b->a)
1079                              --     con_ex_tvs = {b}
1080                              -- False => con_ex_tvs is empty
1081      , con_ex_tvs :: [LHsTyVarBndr Specificity pass] -- ^ Existentials only
1082      , con_mb_cxt :: Maybe (LHsContext pass)         -- ^ User-written context (if any)
1083      , con_args   :: HsConDeclH98Details pass        -- ^ Arguments; can be infix
1084
1085      , con_doc       :: Maybe LHsDocString
1086          -- ^ A possible Haddock comment.
1087      }
1088  | XConDecl !(XXConDecl pass)
1089
1090{- Note [GADT abstract syntax]
1091~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1092The types of both forms of GADT constructors are very structured, as they
1093must consist of the quantified type variables (if provided), followed by the
1094context (if provided), followed by the argument types (if provided), followed
1095by the result type. (See "Wrinkle: No nested foralls or contexts" below for
1096more discussion on the restrictions imposed here.) As a result, instead of
1097storing the type of a GADT constructor as a single LHsType, we split it up
1098into its constituent components for easier access.
1099
1100There are two broad ways to classify GADT constructors:
1101
1102* Record-syntax constructors. For example:
1103
1104    data T a where
1105      K :: forall a. Ord a => { x :: [a], ... } -> T a
1106
1107* Prefix constructors, which do not use record syntax. For example:
1108
1109    data T a where
1110      K :: forall a. Ord a => [a] -> ... -> T a
1111
1112This distinction is recorded in the `con_args :: HsConDetails pass`, which
1113tracks if we're dealing with a RecCon or PrefixCon. It is easy to distinguish
1114the two in the AST since record GADT constructors use HsRecTy. This distinction
1115is made in GHC.Parser.PostProcess.mkGadtDecl.
1116
1117It is worth elaborating a bit more on the process of splitting the argument
1118types of a GADT constructor, since there are some non-obvious details involved.
1119While splitting the argument types of a record GADT constructor is easy (they
1120are stored in an HsRecTy), splitting the arguments of a prefix GADT constructor
1121is trickier. The basic idea is that we must split along the outermost function
1122arrows ((->) and (%1 ->)) in the type, which GHC.Hs.Type.splitHsFunType
1123accomplishes. But what about type operators? Consider:
1124
1125  C :: a :*: b -> a :*: b -> a :+: b
1126
1127This could parse in many different ways depending on the precedences of each
1128type operator. In particular, if (:*:) were to have lower precedence than (->),
1129then it could very well parse like this:
1130
1131  a :*: ((b -> a) :*: ((b -> a) :+: b)))
1132
1133This would give the false impression that the whole type is part of one large
1134return type, with no arguments. Note that we do not fully resolve the exact
1135precedences of each user-defined type operator until the renamer, so this a
1136more difficult task for the parser.
1137
1138Fortunately, there is no risk of the above happening. GHC's parser gives
1139special treatment to function arrows, and as a result, they are always parsed
1140with a lower precedence than any other type operator. As a result, the type
1141above is actually parsed like this:
1142
1143  (a :*: b) -> ((a :*: b) -> (a :+: b))
1144
1145While we won't know the exact precedences of (:*:) and (:+:) until the renamer,
1146all we are concerned about in the parser is identifying the overall shape of
1147the argument and result types, which we can accomplish by piggybacking on the
1148special treatment given to function arrows. In a future where function arrows
1149aren't given special status in the parser, we will likely have to modify
1150GHC.Parser.PostProcess.mkHsOpTyPV to preserve this trick.
1151
1152-----
1153-- Wrinkle: No nested foralls or contexts
1154-----
1155
1156GADT constructors provide some freedom to change the order of foralls in their
1157types (see Note [DataCon user type variable binders] in GHC.Core.DataCon), but
1158this freedom is still limited. GADTs still require that all quantification
1159occurs "prenex". That is, any explicitly quantified type variables must occur
1160at the front of the GADT type, followed by any contexts, followed by the body of
1161the GADT type, in precisely that order. For instance:
1162
1163  data T where
1164    MkT1 :: forall a b. (Eq a, Eq b) => a -> b -> T
1165      -- OK
1166    MkT2 :: forall a. Eq a => forall b. a -> b -> T
1167      -- Rejected, `forall b` is nested
1168    MkT3 :: forall a b. Eq a => Eq b => a -> b -> T
1169      -- Rejected, `Eq b` is nested
1170    MkT4 :: Int -> forall a. a -> T
1171      -- Rejected, `forall a` is nested
1172    MkT5 :: forall a. Int -> Eq a => a -> T
1173      -- Rejected, `Eq a` is nested
1174    MkT6 :: (forall a. a -> T)
1175      -- Rejected, `forall a` is nested due to the surrounding parentheses
1176    MkT7 :: (Eq a => a -> t)
1177      -- Rejected, `Eq a` is nested due to the surrounding parentheses
1178
1179For the full details, see the "Formal syntax for GADTs" section of the GHC
1180User's Guide. GHC enforces that GADT constructors do not have nested `forall`s
1181or contexts in two parts:
1182
11831. GHC, in the process of splitting apart a GADT's type,
1184   extracts out the leading `forall` and context (if they are provided). To
1185   accomplish this splitting, the renamer uses the
1186   GHC.Hs.Type.splitLHsGADTPrefixTy function, which is careful not to remove
1187   parentheses surrounding the leading `forall` or context (as these
1188   parentheses can be syntactically significant). If the third result returned
1189   by splitLHsGADTPrefixTy contains any `forall`s or contexts, then they must
1190   be nested, so they will be rejected.
1191
1192   Note that this step applies to both prefix and record GADTs alike, as they
1193   both have syntax which permits `forall`s and contexts. The difference is
1194   where this step happens:
1195
1196   * For prefix GADTs, this happens in the renamer (in rnConDecl), as we cannot
1197     split until after the type operator fixities have been resolved.
1198   * For record GADTs, this happens in the parser (in mkGadtDecl).
11992. If the GADT type is prefix, the renamer (in the ConDeclGADTPrefixPs case of
1200   rnConDecl) will then check for nested `forall`s/contexts in the body of a
1201   prefix GADT type, after it has determined what all of the argument types are.
1202   This step is necessary to catch examples like MkT4 above, where the nested
1203   quantification occurs after a visible argument type.
1204-}
1205
1206-- | The arguments in a Haskell98-style data constructor.
1207type HsConDeclH98Details pass
1208   = HsConDetails Void (HsScaled pass (LBangType pass)) (XRec pass [LConDeclField pass])
1209-- The Void argument to HsConDetails here is a reflection of the fact that
1210-- type applications are not allowed in data constructor declarations.
1211
1212-- | The arguments in a GADT constructor. Unlike Haskell98-style constructors,
1213-- GADT constructors cannot be declared with infix syntax. As a result, we do
1214-- not use 'HsConDetails' here, as 'InfixCon' would be an unrepresentable
1215-- state. (There is a notion of infix GADT constructors for the purposes of
1216-- derived Show instances—see Note [Infix GADT constructors] in
1217-- GHC.Tc.TyCl—but that is an orthogonal concern.)
1218data HsConDeclGADTDetails pass
1219   = PrefixConGADT [HsScaled pass (LBangType pass)]
1220   | RecConGADT (XRec pass [LConDeclField pass])
1221
1222instance Outputable NewOrData where
1223  ppr NewType  = text "newtype"
1224  ppr DataType = text "data"
1225
1226{-
1227************************************************************************
1228*                                                                      *
1229                Instance declarations
1230*                                                                      *
1231************************************************************************
1232
1233Note [Type family instance declarations in HsSyn]
1234~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1235The data type FamEqn represents one equation of a type family instance.
1236Aside from the pass, it is also parameterised over another field, feqn_rhs.
1237feqn_rhs is either an HsDataDefn (for data family instances) or an LHsType
1238(for type family instances).
1239
1240Type family instances also include associated type family default equations.
1241That is because a default for a type family looks like this:
1242
1243  class C a where
1244    type family F a b :: Type
1245    type F c d = (c,d)   -- Default instance
1246
1247The default declaration is really just a `type instance` declaration, but one
1248with particularly simple patterns: they must all be distinct type variables.
1249That's because we will instantiate it (in an instance declaration for `C`) if
1250we don't give an explicit instance for `F`. Note that the names of the
1251variables don't need to match those of the class: it really is like a
1252free-standing `type instance` declaration.
1253-}
1254
1255----------------- Type synonym family instances -------------
1256
1257-- | Located Type Family Instance Equation
1258type LTyFamInstEqn pass = XRec pass (TyFamInstEqn pass)
1259  -- ^ May have 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnSemi'
1260  --   when in a list
1261
1262-- For details on above see note [exact print annotations] in GHC.Parser.Annotation
1263
1264-- | Haskell Type Patterns
1265type HsTyPats pass = [LHsTypeArg pass]
1266
1267{- Note [Family instance declaration binders]
1268~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1269The feqn_pats field of FamEqn (family instance equation) stores the LHS type
1270(and kind) patterns. Any type (and kind) variables contained
1271in these type patterns are bound in the feqn_bndrs field.
1272Note that in particular:
1273
1274* The feqn_bndrs *include* any anonymous wildcards.  For example
1275     type instance F a _ = a
1276  The feqn_bndrs will be HsOuterImplicit {a, _}.  Remember that each separate
1277  wildcard '_' gets its own unique.  In this context wildcards behave just like
1278  an ordinary type variable, only anonymous.
1279
1280* The feqn_bndrs *include* type variables that are already in scope
1281
1282   Eg   class C s t where
1283          type F t p :: *
1284        instance C w (a,b) where
1285          type F (a,b) x = x->a
1286   The feqn_bndrs of the F decl is HsOuterImplicit {a,b,x}, even though the
1287   F decl is nested inside the 'instance' decl.
1288
1289   However after the renamer, the uniques will match up:
1290        instance C w7 (a8,b9) where
1291          type F (a8,b9) x10 = x10->a8
1292   so that we can compare the type pattern in the 'instance' decl and
1293   in the associated 'type' decl
1294
1295c.f. Note [TyVar binders for associated decls]
1296-}
1297
1298-- | Type Family Instance Equation
1299type TyFamInstEqn pass = FamEqn pass (LHsType pass)
1300            -- Here, the @pats@ are type patterns (with kind and type bndrs).
1301            -- See Note [Family instance declaration binders]
1302
1303-- | Type family default declarations.
1304-- A convenient synonym for 'TyFamInstDecl'.
1305-- See @Note [Type family instance declarations in HsSyn]@.
1306type TyFamDefltDecl = TyFamInstDecl
1307
1308-- | Located type family default declarations.
1309type LTyFamDefltDecl pass = XRec pass (TyFamDefltDecl pass)
1310
1311-- | Located Type Family Instance Declaration
1312type LTyFamInstDecl pass = XRec pass (TyFamInstDecl pass)
1313
1314-- | Type Family Instance Declaration
1315data TyFamInstDecl pass
1316  = TyFamInstDecl { tfid_xtn :: XCTyFamInstDecl pass
1317                  , tfid_eqn :: TyFamInstEqn pass }
1318    -- ^
1319    --  - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnType',
1320    --           'GHC.Parser.Annotation.AnnInstance',
1321
1322    -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
1323  | XTyFamInstDecl !(XXTyFamInstDecl pass)
1324
1325----------------- Data family instances -------------
1326
1327-- | Located Data Family Instance Declaration
1328type LDataFamInstDecl pass = XRec pass (DataFamInstDecl pass)
1329
1330-- | Data Family Instance Declaration
1331newtype DataFamInstDecl pass
1332  = DataFamInstDecl { dfid_eqn :: FamEqn pass (HsDataDefn pass) }
1333    -- ^
1334    --  - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnData',
1335    --           'GHC.Parser.Annotation.AnnNewType','GHC.Parser.Annotation.AnnInstance',
1336    --           'GHC.Parser.Annotation.AnnDcolon'
1337    --           'GHC.Parser.Annotation.AnnWhere','GHC.Parser.Annotation.AnnOpen',
1338    --           'GHC.Parser.Annotation.AnnClose'
1339
1340    -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
1341
1342----------------- Family instances (common types) -------------
1343
1344-- | Family Equation
1345--
1346-- One equation in a type family instance declaration, data family instance
1347-- declaration, or type family default.
1348-- See Note [Type family instance declarations in HsSyn]
1349-- See Note [Family instance declaration binders]
1350data FamEqn pass rhs
1351  = FamEqn
1352       { feqn_ext    :: XCFamEqn pass rhs
1353       , feqn_tycon  :: LIdP pass
1354       , feqn_bndrs  :: HsOuterFamEqnTyVarBndrs pass -- ^ Optional quantified type vars
1355       , feqn_pats   :: HsTyPats pass
1356       , feqn_fixity :: LexicalFixity -- ^ Fixity used in the declaration
1357       , feqn_rhs    :: rhs
1358       }
1359    -- ^
1360    --  - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnEqual'
1361  | XFamEqn !(XXFamEqn pass rhs)
1362
1363    -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
1364
1365----------------- Class instances -------------
1366
1367-- | Located Class Instance Declaration
1368type LClsInstDecl pass = XRec pass (ClsInstDecl pass)
1369
1370-- | Class Instance Declaration
1371data ClsInstDecl pass
1372  = ClsInstDecl
1373      { cid_ext     :: XCClsInstDecl pass
1374      , cid_poly_ty :: LHsSigType pass    -- Context => Class Instance-type
1375                                          -- Using a polytype means that the renamer conveniently
1376                                          -- figures out the quantified type variables for us.
1377      , cid_binds         :: LHsBinds pass       -- Class methods
1378      , cid_sigs          :: [LSig pass]         -- User-supplied pragmatic info
1379      , cid_tyfam_insts   :: [LTyFamInstDecl pass]   -- Type family instances
1380      , cid_datafam_insts :: [LDataFamInstDecl pass] -- Data family instances
1381      , cid_overlap_mode  :: Maybe (XRec pass OverlapMode)
1382         -- ^ - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnOpen',
1383         --                                    'GHC.Parser.Annotation.AnnClose',
1384
1385        -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
1386      }
1387    -- ^
1388    --  - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnInstance',
1389    --           'GHC.Parser.Annotation.AnnWhere',
1390    --           'GHC.Parser.Annotation.AnnOpen','GHC.Parser.Annotation.AnnClose',
1391
1392    -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
1393  | XClsInstDecl !(XXClsInstDecl pass)
1394
1395----------------- Instances of all kinds -------------
1396
1397-- | Located Instance Declaration
1398type LInstDecl pass = XRec pass (InstDecl pass)
1399
1400-- | Instance Declaration
1401data InstDecl pass  -- Both class and family instances
1402  = ClsInstD
1403      { cid_d_ext :: XClsInstD pass
1404      , cid_inst  :: ClsInstDecl pass }
1405  | DataFamInstD              -- data family instance
1406      { dfid_ext  :: XDataFamInstD pass
1407      , dfid_inst :: DataFamInstDecl pass }
1408  | TyFamInstD              -- type family instance
1409      { tfid_ext  :: XTyFamInstD pass
1410      , tfid_inst :: TyFamInstDecl pass }
1411  | XInstDecl !(XXInstDecl pass)
1412
1413{-
1414************************************************************************
1415*                                                                      *
1416\subsection[DerivDecl]{A stand-alone instance deriving declaration}
1417*                                                                      *
1418************************************************************************
1419-}
1420
1421-- | Located stand-alone 'deriving instance' declaration
1422type LDerivDecl pass = XRec pass (DerivDecl pass)
1423
1424-- | Stand-alone 'deriving instance' declaration
1425data DerivDecl pass = DerivDecl
1426        { deriv_ext          :: XCDerivDecl pass
1427        , deriv_type         :: LHsSigWcType pass
1428          -- ^ The instance type to derive.
1429          --
1430          -- It uses an 'LHsSigWcType' because the context is allowed to be a
1431          -- single wildcard:
1432          --
1433          -- > deriving instance _ => Eq (Foo a)
1434          --
1435          -- Which signifies that the context should be inferred.
1436
1437          -- See Note [Inferring the instance context] in GHC.Tc.Deriv.Infer.
1438
1439        , deriv_strategy     :: Maybe (LDerivStrategy pass)
1440        , deriv_overlap_mode :: Maybe (XRec pass OverlapMode)
1441         -- ^ - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnDeriving',
1442         --        'GHC.Parser.Annotation.AnnInstance', 'GHC.Parser.Annotation.AnnStock',
1443         --        'GHC.Parser.Annotation.AnnAnyClass', 'GHC.Parser.Annotation.AnnNewtype',
1444         --        'GHC.Parser.Annotation.AnnOpen','GHC.Parser.Annotation.AnnClose'
1445
1446  -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
1447        }
1448  | XDerivDecl !(XXDerivDecl pass)
1449
1450{-
1451************************************************************************
1452*                                                                      *
1453                Deriving strategies
1454*                                                                      *
1455************************************************************************
1456-}
1457
1458-- | A 'Located' 'DerivStrategy'.
1459type LDerivStrategy pass = XRec pass (DerivStrategy pass)
1460
1461-- | Which technique the user explicitly requested when deriving an instance.
1462data DerivStrategy pass
1463  -- See Note [Deriving strategies] in GHC.Tc.Deriv
1464  = StockStrategy (XStockStrategy pass)
1465                     -- ^ GHC's \"standard\" strategy, which is to implement a
1466                     --   custom instance for the data type. This only works
1467                     --   for certain types that GHC knows about (e.g., 'Eq',
1468                     --   'Show', 'Functor' when @-XDeriveFunctor@ is enabled,
1469                     --   etc.)
1470  | AnyclassStrategy (XAnyClassStrategy pass) -- ^ @-XDeriveAnyClass@
1471  | NewtypeStrategy  (XNewtypeStrategy pass)  -- ^ @-XGeneralizedNewtypeDeriving@
1472  | ViaStrategy (XViaStrategy pass)
1473                     -- ^ @-XDerivingVia@
1474
1475-- | A short description of a @DerivStrategy'@.
1476derivStrategyName :: DerivStrategy a -> SDoc
1477derivStrategyName = text . go
1478  where
1479    go StockStrategy    {} = "stock"
1480    go AnyclassStrategy {} = "anyclass"
1481    go NewtypeStrategy  {} = "newtype"
1482    go ViaStrategy      {} = "via"
1483
1484{-
1485************************************************************************
1486*                                                                      *
1487\subsection[DefaultDecl]{A @default@ declaration}
1488*                                                                      *
1489************************************************************************
1490
1491There can only be one default declaration per module, but it is hard
1492for the parser to check that; we pass them all through in the abstract
1493syntax, and that restriction must be checked in the front end.
1494-}
1495
1496-- | Located Default Declaration
1497type LDefaultDecl pass = XRec pass (DefaultDecl pass)
1498
1499-- | Default Declaration
1500data DefaultDecl pass
1501  = DefaultDecl (XCDefaultDecl pass) [LHsType pass]
1502        -- ^ - 'GHC.Parser.Annotation.AnnKeywordId's : 'GHC.Parser.Annotation.AnnDefault',
1503        --          'GHC.Parser.Annotation.AnnOpen','GHC.Parser.Annotation.AnnClose'
1504
1505        -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
1506  | XDefaultDecl !(XXDefaultDecl pass)
1507
1508{-
1509************************************************************************
1510*                                                                      *
1511\subsection{Foreign function interface declaration}
1512*                                                                      *
1513************************************************************************
1514-}
1515
1516-- foreign declarations are distinguished as to whether they define or use a
1517-- Haskell name
1518--
1519--  * the Boolean value indicates whether the pre-standard deprecated syntax
1520--   has been used
1521
1522-- | Located Foreign Declaration
1523type LForeignDecl pass = XRec pass (ForeignDecl pass)
1524
1525-- | Foreign Declaration
1526data ForeignDecl pass
1527  = ForeignImport
1528      { fd_i_ext  :: XForeignImport pass   -- Post typechecker, rep_ty ~ sig_ty
1529      , fd_name   :: LIdP pass             -- defines this name
1530      , fd_sig_ty :: LHsSigType pass       -- sig_ty
1531      , fd_fi     :: ForeignImport }
1532
1533  | ForeignExport
1534      { fd_e_ext  :: XForeignExport pass   -- Post typechecker, rep_ty ~ sig_ty
1535      , fd_name   :: LIdP pass             -- uses this name
1536      , fd_sig_ty :: LHsSigType pass       -- sig_ty
1537      , fd_fe     :: ForeignExport }
1538        -- ^
1539        --  - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnForeign',
1540        --           'GHC.Parser.Annotation.AnnImport','GHC.Parser.Annotation.AnnExport',
1541        --           'GHC.Parser.Annotation.AnnDcolon'
1542
1543        -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
1544  | XForeignDecl !(XXForeignDecl pass)
1545
1546{-
1547    In both ForeignImport and ForeignExport:
1548        sig_ty is the type given in the Haskell code
1549        rep_ty is the representation for this type, i.e. with newtypes
1550               coerced away and type functions evaluated.
1551    Thus if the declaration is valid, then rep_ty will only use types
1552    such as Int and IO that we know how to make foreign calls with.
1553-}
1554
1555-- Specification Of an imported external entity in dependence on the calling
1556-- convention
1557--
1558data ForeignImport = -- import of a C entity
1559                     --
1560                     --  * the two strings specifying a header file or library
1561                     --   may be empty, which indicates the absence of a
1562                     --   header or object specification (both are not used
1563                     --   in the case of `CWrapper' and when `CFunction'
1564                     --   has a dynamic target)
1565                     --
1566                     --  * the calling convention is irrelevant for code
1567                     --   generation in the case of `CLabel', but is needed
1568                     --   for pretty printing
1569                     --
1570                     --  * `Safety' is irrelevant for `CLabel' and `CWrapper'
1571                     --
1572                     CImport  (Located CCallConv) -- ccall or stdcall
1573                              (Located Safety)  -- interruptible, safe or unsafe
1574                              (Maybe Header)       -- name of C header
1575                              CImportSpec          -- details of the C entity
1576                              (Located SourceText) -- original source text for
1577                                                   -- the C entity
1578  deriving Data
1579
1580-- details of an external C entity
1581--
1582data CImportSpec = CLabel    CLabelString     -- import address of a C label
1583                 | CFunction CCallTarget      -- static or dynamic function
1584                 | CWrapper                   -- wrapper to expose closures
1585                                              -- (former f.e.d.)
1586  deriving Data
1587
1588-- specification of an externally exported entity in dependence on the calling
1589-- convention
1590--
1591data ForeignExport = CExport  (Located CExportSpec) -- contains the calling
1592                                                    -- convention
1593                              (Located SourceText)  -- original source text for
1594                                                    -- the C entity
1595  deriving Data
1596
1597-- pretty printing of foreign declarations
1598--
1599
1600instance Outputable ForeignImport where
1601  ppr (CImport  cconv safety mHeader spec (L _ srcText)) =
1602    ppr cconv <+> ppr safety
1603      <+> pprWithSourceText srcText (pprCEntity spec "")
1604    where
1605      pp_hdr = case mHeader of
1606               Nothing -> empty
1607               Just (Header _ header) -> ftext header
1608
1609      pprCEntity (CLabel lbl) _ =
1610        doubleQuotes $ text "static" <+> pp_hdr <+> char '&' <> ppr lbl
1611      pprCEntity (CFunction (StaticTarget st _lbl _ isFun)) src =
1612        if dqNeeded then doubleQuotes ce else empty
1613          where
1614            dqNeeded = (take 6 src == "static")
1615                    || isJust mHeader
1616                    || not isFun
1617                    || st /= NoSourceText
1618            ce =
1619                  -- We may need to drop leading spaces first
1620                  (if take 6 src == "static" then text "static" else empty)
1621              <+> pp_hdr
1622              <+> (if isFun then empty else text "value")
1623              <+> (pprWithSourceText st empty)
1624      pprCEntity (CFunction DynamicTarget) _ =
1625        doubleQuotes $ text "dynamic"
1626      pprCEntity CWrapper _ = doubleQuotes $ text "wrapper"
1627
1628instance Outputable ForeignExport where
1629  ppr (CExport  (L _ (CExportStatic _ lbl cconv)) _) =
1630    ppr cconv <+> char '"' <> ppr lbl <> char '"'
1631
1632{-
1633************************************************************************
1634*                                                                      *
1635\subsection{Rewrite rules}
1636*                                                                      *
1637************************************************************************
1638-}
1639
1640-- | Located Rule Declarations
1641type LRuleDecls pass = XRec pass (RuleDecls pass)
1642
1643  -- Note [Pragma source text] in GHC.Types.SourceText
1644-- | Rule Declarations
1645data RuleDecls pass = HsRules { rds_ext   :: XCRuleDecls pass
1646                              , rds_src   :: SourceText
1647                              , rds_rules :: [LRuleDecl pass] }
1648  | XRuleDecls !(XXRuleDecls pass)
1649
1650-- | Located Rule Declaration
1651type LRuleDecl pass = XRec pass (RuleDecl pass)
1652
1653-- | Rule Declaration
1654data RuleDecl pass
1655  = HsRule -- Source rule
1656       { rd_ext  :: XHsRule pass
1657           -- ^ After renamer, free-vars from the LHS and RHS
1658       , rd_name :: XRec pass (SourceText,RuleName)
1659           -- ^ Note [Pragma source text] in "GHC.Types.Basic"
1660       , rd_act  :: Activation
1661       , rd_tyvs :: Maybe [LHsTyVarBndr () (NoGhcTc pass)]
1662           -- ^ Forall'd type vars
1663       , rd_tmvs :: [LRuleBndr pass]
1664           -- ^ Forall'd term vars, before typechecking; after typechecking
1665           --    this includes all forall'd vars
1666       , rd_lhs  :: XRec pass (HsExpr pass)
1667       , rd_rhs  :: XRec pass (HsExpr pass)
1668       }
1669    -- ^
1670    --  - 'GHC.Parser.Annotation.AnnKeywordId' :
1671    --           'GHC.Parser.Annotation.AnnOpen','GHC.Parser.Annotation.AnnTilde',
1672    --           'GHC.Parser.Annotation.AnnVal',
1673    --           'GHC.Parser.Annotation.AnnClose',
1674    --           'GHC.Parser.Annotation.AnnForall','GHC.Parser.Annotation.AnnDot',
1675    --           'GHC.Parser.Annotation.AnnEqual',
1676  | XRuleDecl !(XXRuleDecl pass)
1677
1678data HsRuleRn = HsRuleRn NameSet NameSet -- Free-vars from the LHS and RHS
1679  deriving Data
1680
1681-- | Located Rule Binder
1682type LRuleBndr pass = XRec pass (RuleBndr pass)
1683
1684-- | Rule Binder
1685data RuleBndr pass
1686  = RuleBndr (XCRuleBndr pass)  (LIdP pass)
1687  | RuleBndrSig (XRuleBndrSig pass) (LIdP pass) (HsPatSigType pass)
1688  | XRuleBndr !(XXRuleBndr pass)
1689        -- ^
1690        --  - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnOpen',
1691        --     'GHC.Parser.Annotation.AnnDcolon','GHC.Parser.Annotation.AnnClose'
1692
1693        -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
1694
1695collectRuleBndrSigTys :: [RuleBndr pass] -> [HsPatSigType pass]
1696collectRuleBndrSigTys bndrs = [ty | RuleBndrSig _ _ ty <- bndrs]
1697
1698pprFullRuleName :: Located (SourceText, RuleName) -> SDoc
1699pprFullRuleName (L _ (st, n)) = pprWithSourceText st (doubleQuotes $ ftext n)
1700
1701{-
1702************************************************************************
1703*                                                                      *
1704\subsection[DocDecl]{Document comments}
1705*                                                                      *
1706************************************************************************
1707-}
1708
1709-- | Located Documentation comment Declaration
1710type LDocDecl pass = XRec pass (DocDecl)
1711
1712-- | Documentation comment Declaration
1713data DocDecl
1714  = DocCommentNext HsDocString
1715  | DocCommentPrev HsDocString
1716  | DocCommentNamed String HsDocString
1717  | DocGroup Int HsDocString
1718  deriving Data
1719
1720-- Okay, I need to reconstruct the document comments, but for now:
1721instance Outputable DocDecl where
1722  ppr _ = text "<document comment>"
1723
1724docDeclDoc :: DocDecl -> HsDocString
1725docDeclDoc (DocCommentNext d) = d
1726docDeclDoc (DocCommentPrev d) = d
1727docDeclDoc (DocCommentNamed _ d) = d
1728docDeclDoc (DocGroup _ d) = d
1729
1730{-
1731************************************************************************
1732*                                                                      *
1733\subsection[DeprecDecl]{Deprecations}
1734*                                                                      *
1735************************************************************************
1736
1737We use exported entities for things to deprecate.
1738-}
1739
1740-- | Located Warning Declarations
1741type LWarnDecls pass = XRec pass (WarnDecls pass)
1742
1743 -- Note [Pragma source text] in GHC.Types.SourceText
1744-- | Warning pragma Declarations
1745data WarnDecls pass = Warnings { wd_ext      :: XWarnings pass
1746                               , wd_src      :: SourceText
1747                               , wd_warnings :: [LWarnDecl pass]
1748                               }
1749  | XWarnDecls !(XXWarnDecls pass)
1750
1751-- | Located Warning pragma Declaration
1752type LWarnDecl pass = XRec pass (WarnDecl pass)
1753
1754-- | Warning pragma Declaration
1755data WarnDecl pass = Warning (XWarning pass) [LIdP pass] WarningTxt
1756                   | XWarnDecl !(XXWarnDecl pass)
1757
1758{-
1759************************************************************************
1760*                                                                      *
1761\subsection[AnnDecl]{Annotations}
1762*                                                                      *
1763************************************************************************
1764-}
1765
1766-- | Located Annotation Declaration
1767type LAnnDecl pass = XRec pass (AnnDecl pass)
1768
1769-- | Annotation Declaration
1770data AnnDecl pass = HsAnnotation
1771                      (XHsAnnotation pass)
1772                      SourceText -- Note [Pragma source text] in GHC.Types.SourceText
1773                      (AnnProvenance pass) (XRec pass (HsExpr pass))
1774      -- ^ - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnOpen',
1775      --           'GHC.Parser.Annotation.AnnType'
1776      --           'GHC.Parser.Annotation.AnnModule'
1777      --           'GHC.Parser.Annotation.AnnClose'
1778
1779      -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
1780  | XAnnDecl !(XXAnnDecl pass)
1781
1782-- | Annotation Provenance
1783data AnnProvenance pass = ValueAnnProvenance (LIdP pass)
1784                        | TypeAnnProvenance (LIdP pass)
1785                        | ModuleAnnProvenance
1786-- deriving instance Functor     AnnProvenance
1787-- deriving instance Foldable    AnnProvenance
1788-- deriving instance Traversable AnnProvenance
1789-- deriving instance (Data pass) => Data (AnnProvenance pass)
1790
1791annProvenanceName_maybe :: forall p. UnXRec p => AnnProvenance p -> Maybe (IdP p)
1792annProvenanceName_maybe (ValueAnnProvenance (unXRec @p -> name)) = Just name
1793annProvenanceName_maybe (TypeAnnProvenance (unXRec @p -> name))  = Just name
1794annProvenanceName_maybe ModuleAnnProvenance                      = Nothing
1795
1796{-
1797************************************************************************
1798*                                                                      *
1799\subsection[RoleAnnot]{Role annotations}
1800*                                                                      *
1801************************************************************************
1802-}
1803
1804-- | Located Role Annotation Declaration
1805type LRoleAnnotDecl pass = XRec pass (RoleAnnotDecl pass)
1806
1807-- See #8185 for more info about why role annotations are
1808-- top-level declarations
1809-- | Role Annotation Declaration
1810data RoleAnnotDecl pass
1811  = RoleAnnotDecl (XCRoleAnnotDecl pass)
1812                  (LIdP pass)              -- type constructor
1813                  [XRec pass (Maybe Role)] -- optional annotations
1814      -- ^ - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnType',
1815      --           'GHC.Parser.Annotation.AnnRole'
1816
1817      -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
1818  | XRoleAnnotDecl !(XXRoleAnnotDecl pass)
1819