HsDecls.hs 79 KB
Newer Older
Austin Seipp's avatar
Austin Seipp committed
1 2 3 4
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
-}
5

6 7
{-# LANGUAGE DeriveDataTypeable, DeriveFunctor, DeriveFoldable,
             DeriveTraversable #-}
8 9 10 11 12
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UndecidableInstances #-} -- Note [Pass sensitive types]
                                      -- in module PlaceHolder
{-# LANGUAGE ConstraintKinds #-}
13
{-# LANGUAGE FlexibleInstances #-}
14

15 16
-- | Abstract syntax of global declarations.
--
17
-- Definitions for: @SynDecl@ and @ConDecl@, @ClassDecl@,
18
-- @InstDecl@, @DefaultDecl@ and @ForeignDecl@.
19
module HsDecls (
20
  -- * Toplevel declarations
21
  HsDecl(..), LHsDecl, HsDataDefn(..), HsDeriving,
Ryan Scott's avatar
Ryan Scott committed
22
  HsDerivingClause(..), LHsDerivingClause,
23

24
  -- ** Class or type declarations
25
  TyClDecl(..), LTyClDecl,
26 27
  TyClGroup(..), mkTyClGroup, emptyTyClGroup,
  tyClGroupTyClDecls, tyClGroupInstDecls, tyClGroupRoleDecls,
28 29
  isClassDecl, isDataDecl, isSynDecl, tcdName,
  isFamilyDecl, isTypeFamilyDecl, isDataFamilyDecl,
30
  isOpenTypeFamilyInfo, isClosedTypeFamilyInfo,
31 32 33
  tyFamInstDeclName, tyFamInstDeclLName,
  countTyClDecls, pprTyClDeclFlavour,
  tyClDeclLName, tyClDeclTyVars,
34
  hsDeclHasCusk, famDeclHasCusk,
35
  FamilyDecl(..), LFamilyDecl,
36

37
  -- ** Instance declarations
38
  InstDecl(..), LInstDecl, NewOrData(..), FamilyInfo(..),
39 40
  TyFamInstDecl(..), LTyFamInstDecl, instDeclDataFamInsts,
  DataFamInstDecl(..), LDataFamInstDecl, pprDataFamInstFlavour,
41
  TyFamEqn(..), TyFamInstEqn, LTyFamInstEqn, TyFamDefltEqn, LTyFamDefltEqn,
Alan Zimmerman's avatar
Alan Zimmerman committed
42
  HsTyPats,
43
  LClsInstDecl, ClsInstDecl(..),
44

45 46 47
  -- ** Standalone deriving declarations
  DerivDecl(..), LDerivDecl,
  -- ** @RULE@ declarations
Alan Zimmerman's avatar
Alan Zimmerman committed
48
  LRuleDecls,RuleDecls(..),RuleDecl(..), LRuleDecl, RuleBndr(..),LRuleBndr,
49
  collectRuleBndrSigTys,
50
  flattenRuleDecls, pprFullRuleName,
51 52
  -- ** @VECTORISE@ declarations
  VectDecl(..), LVectDecl,
53
  lvectDeclName, lvectInstDecl,
54 55
  -- ** @default@ declarations
  DefaultDecl(..), LDefaultDecl,
56
  -- ** Template haskell declaration splice
57
  SpliceExplicitFlag(..),
58
  SpliceDecl(..), LSpliceDecl,
59 60
  -- ** Foreign function interface declarations
  ForeignDecl(..), LForeignDecl, ForeignImport(..), ForeignExport(..),
61
  noForeignImportCoercionYet, noForeignExportCoercionYet,
62
  CImportSpec(..),
63
  -- ** Data-constructor declarations
Alan Zimmerman's avatar
Alan Zimmerman committed
64
  ConDecl(..), LConDecl,
65
  HsConDeclDetails, hsConDeclArgTys,
Alan Zimmerman's avatar
Alan Zimmerman committed
66 67 68
  getConNames,
  getConDetails,
  gadtDeclDetails,
69 70 71 72
  -- ** Document comments
  DocDecl(..), LDocDecl, docDeclDoc,
  -- ** Deprecations
  WarnDecl(..),  LWarnDecl,
Alan Zimmerman's avatar
Alan Zimmerman committed
73
  WarnDecls(..), LWarnDecls,
74
  -- ** Annotations
75
  AnnDecl(..), LAnnDecl,
76
  AnnProvenance(..), annProvenanceName_maybe,
77 78
  -- ** Role annotations
  RoleAnnotDecl(..), LRoleAnnotDecl, roleAnnotDeclName,
Jan Stolarek's avatar
Jan Stolarek committed
79 80 81
  -- ** Injective type families
  FamilyResultSig(..), LFamilyResultSig, InjectivityAnn(..), LInjectivityAnn,
  resultVariableName,
82 83

  -- * Grouping
84
  HsGroup(..),  emptyRdrGroup, emptyRnGroup, appendGroups, hsGroupInstDecls
85

86
    ) where
87 88

-- friends:
89
import {-# SOURCE #-}   HsExpr( LHsExpr, HsExpr, HsSplice, pprExpr, pprSplice )
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
90
        -- Because Expr imports Decls via HsBracket
91

92
import HsBinds
93
import HsTypes
94
import HsDoc
95
import TyCon
96
import Name
97
import BasicTypes
98
import Coercion
99
import ForeignCall
100
import PlaceHolder ( PostTc,PostRn,PlaceHolder(..),DataId, OutputableBndrId )
101
import NameSet
102 103

-- others:
104
import InstEnv
105
import Class
106
import Outputable
107 108 109
import Util
import SrcLoc

110
import Bag
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
111
import Maybes
112
import Data.Data        hiding (TyCon,Fixity)
113

Austin Seipp's avatar
Austin Seipp committed
114 115 116
{-
************************************************************************
*                                                                      *
117
\subsection[HsDecl]{Declarations}
Austin Seipp's avatar
Austin Seipp committed
118 119 120
*                                                                      *
************************************************************************
-}
121

122
type LHsDecl id = Located (HsDecl id)
Alan Zimmerman's avatar
Alan Zimmerman committed
123 124 125 126
        -- ^ When in a list this may have
        --
        --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnSemi'
        --
127

128 129
-- For details on above see note [Api annotations] in ApiAnnotation

130
-- | A Haskell Declaration
131
data HsDecl id
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
  = TyClD       (TyClDecl id)      -- ^ Type or Class Declaration
  | InstD       (InstDecl  id)     -- ^ Instance declaration
  | DerivD      (DerivDecl id)     -- ^ Deriving declaration
  | ValD        (HsBind id)        -- ^ Value declaration
  | SigD        (Sig id)           -- ^ Signature declaration
  | DefD        (DefaultDecl id)   -- ^ 'default' declaration
  | ForD        (ForeignDecl id)   -- ^ Foreign declaration
  | WarningD    (WarnDecls id)     -- ^ Warning declaration
  | AnnD        (AnnDecl id)       -- ^ Annotation declaration
  | RuleD       (RuleDecls id)     -- ^ Rule declaration
  | VectD       (VectDecl id)      -- ^ Vectorise declaration
  | SpliceD     (SpliceDecl id)    -- ^ Splice declaration
                                   -- (Includes quasi-quotes)
  | DocD        (DocDecl)          -- ^ Documentation comment declaration
  | RoleAnnotD  (RoleAnnotDecl id) -- ^ Role annotation declaration
147
deriving instance (DataId id) => Data (HsDecl id)
148

149 150

-- NB: all top-level fixity decls are contained EITHER
151
-- EITHER SigDs
152 153 154
-- OR     in the ClassDecls in TyClDs
--
-- The former covers
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
155 156 157 158 159
--      a) data constructors
--      b) class methods (but they can be also done in the
--              signatures of class decls)
--      c) imported functions (that have an IfacSig)
--      d) top level decls
160 161
--
-- The latter is for class methods only
162

163 164 165
-- | Haskell Group
--
-- A 'HsDecl' is categorised into a 'HsGroup' before being
166 167 168
-- fed to the renamer.
data HsGroup id
  = HsGroup {
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
169
        hs_valds  :: HsValBinds id,
170
        hs_splcds :: [LSpliceDecl id],
171

172
        hs_tyclds :: [TyClGroup id],
173 174
                -- A list of mutually-recursive groups;
                -- This includes `InstDecl`s as well;
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
175 176
                -- Parser generates a singleton list;
                -- renamer does dependency analysis
177

178
        hs_derivds :: [LDerivDecl id],
179

chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
180 181 182
        hs_fixds  :: [LFixitySig id],
                -- Snaffled out of both top-level fixity signatures,
                -- and those in class declarations
183

184 185
        hs_defds  :: [LDefaultDecl id],
        hs_fords  :: [LForeignDecl id],
Alan Zimmerman's avatar
Alan Zimmerman committed
186
        hs_warnds :: [LWarnDecls id],
187
        hs_annds  :: [LAnnDecl id],
Alan Zimmerman's avatar
Alan Zimmerman committed
188
        hs_ruleds :: [LRuleDecls id],
189
        hs_vects  :: [LVectDecl id],
190

191
        hs_docs   :: [LDocDecl]
192
  }
193
deriving instance (DataId id) => Data (HsGroup id)
194

195 196 197 198
emptyGroup, emptyRdrGroup, emptyRnGroup :: HsGroup a
emptyRdrGroup = emptyGroup { hs_valds = emptyValBindsIn }
emptyRnGroup  = emptyGroup { hs_valds = emptyValBindsOut }

199 200 201 202
hsGroupInstDecls :: HsGroup id -> [LInstDecl id]
hsGroupInstDecls = (=<<) group_instds . hs_tyclds

emptyGroup = HsGroup { hs_tyclds = [],
203
                       hs_derivds = [],
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
204 205 206
                       hs_fixds = [], hs_defds = [], hs_annds = [],
                       hs_fords = [], hs_warnds = [], hs_ruleds = [], hs_vects = [],
                       hs_valds = error "emptyGroup hs_valds: Can't happen",
207
                       hs_splcds = [],
208
                       hs_docs = [] }
209 210

appendGroups :: HsGroup a -> HsGroup a -> HsGroup a
211 212
appendGroups
    HsGroup {
213
        hs_valds  = val_groups1,
214
        hs_splcds = spliceds1,
215
        hs_tyclds = tyclds1,
216
        hs_derivds = derivds1,
217
        hs_fixds  = fixds1,
218 219
        hs_defds  = defds1,
        hs_annds  = annds1,
220
        hs_fords  = fords1,
221 222 223
        hs_warnds = warnds1,
        hs_ruleds = rulds1,
        hs_vects = vects1,
224
  hs_docs   = docs1 }
225
    HsGroup {
226
        hs_valds  = val_groups2,
227
        hs_splcds = spliceds2,
228
        hs_tyclds = tyclds2,
229
        hs_derivds = derivds2,
230
        hs_fixds  = fixds2,
231 232
        hs_defds  = defds2,
        hs_annds  = annds2,
233
        hs_fords  = fords2,
234 235 236 237
        hs_warnds = warnds2,
        hs_ruleds = rulds2,
        hs_vects  = vects2,
        hs_docs   = docs2 }
238 239
  =
    HsGroup {
240
        hs_valds  = val_groups1 `plusHsValBinds` val_groups2,
241 242
        hs_splcds = spliceds1 ++ spliceds2,
        hs_tyclds = tyclds1 ++ tyclds2,
243
        hs_derivds = derivds1 ++ derivds2,
244 245 246
        hs_fixds  = fixds1 ++ fixds2,
        hs_annds  = annds1 ++ annds2,
        hs_defds  = defds1 ++ defds2,
247
        hs_fords  = fords1 ++ fords2,
248 249 250 251
        hs_warnds = warnds1 ++ warnds2,
        hs_ruleds = rulds1 ++ rulds2,
        hs_vects  = vects1 ++ vects2,
        hs_docs   = docs1  ++ docs2 }
252

253
instance (OutputableBndrId name) => Outputable (HsDecl name) where
254 255 256 257 258 259 260 261
    ppr (TyClD dcl)             = ppr dcl
    ppr (ValD binds)            = ppr binds
    ppr (DefD def)              = ppr def
    ppr (InstD inst)            = ppr inst
    ppr (DerivD deriv)          = ppr deriv
    ppr (ForD fd)               = ppr fd
    ppr (SigD sd)               = ppr sd
    ppr (RuleD rd)              = ppr rd
262
    ppr (VectD vect)            = ppr vect
Ian Lynagh's avatar
Ian Lynagh committed
263
    ppr (WarningD wd)           = ppr wd
264
    ppr (AnnD ad)               = ppr ad
265 266
    ppr (SpliceD dd)            = ppr dd
    ppr (DocD doc)              = ppr doc
267
    ppr (RoleAnnotD ra)         = ppr ra
268

269
instance (OutputableBndrId name) => Outputable (HsGroup name) where
270
    ppr (HsGroup { hs_valds  = val_decls,
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
271
                   hs_tyclds = tycl_decls,
272
                   hs_derivds = deriv_decls,
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
273 274 275 276 277 278 279
                   hs_fixds  = fix_decls,
                   hs_warnds = deprec_decls,
                   hs_annds  = ann_decls,
                   hs_fords  = foreign_decls,
                   hs_defds  = default_decls,
                   hs_ruleds = rule_decls,
                   hs_vects  = vect_decls })
280 281
        = vcat_mb empty
            [ppr_ds fix_decls, ppr_ds default_decls,
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
282 283 284
             ppr_ds deprec_decls, ppr_ds ann_decls,
             ppr_ds rule_decls,
             ppr_ds vect_decls,
285 286
             if isEmptyValBinds val_decls
                then Nothing
287
                else Just (ppr val_decls),
288 289
             ppr_ds (tyClGroupTyClDecls tycl_decls),
             ppr_ds (tyClGroupInstDecls tycl_decls),
290
             ppr_ds deriv_decls,
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
291 292
             ppr_ds foreign_decls]
        where
293
          ppr_ds :: Outputable a => [a] -> Maybe SDoc
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
294 295
          ppr_ds [] = Nothing
          ppr_ds ds = Just (vcat (map ppr ds))
296 297

          vcat_mb :: SDoc -> [Maybe SDoc] -> SDoc
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
298
          -- Concatenate vertically with white-space between non-blanks
299 300 301
          vcat_mb _    []             = empty
          vcat_mb gap (Nothing : ds) = vcat_mb gap ds
          vcat_mb gap (Just d  : ds) = gap $$ d $$ vcat_mb blankLine ds
302

303 304
data SpliceExplicitFlag = ExplicitSplice | -- <=> $(f x y)
                          ImplicitSplice   -- <=> f x y,  i.e. a naked top level expression
305
    deriving Data
306

307
-- | Located Splice Declaration
308
type LSpliceDecl name = Located (SpliceDecl name)
309 310

-- | Splice Declaration
311
data SpliceDecl id
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
312
  = SpliceDecl                  -- Top level splice
313
        (Located (HsSplice id))
314
        SpliceExplicitFlag
315
deriving instance (DataId id) => Data (SpliceDecl id)
316

317
instance (OutputableBndrId name) => Outputable (SpliceDecl name) where
318
   ppr (SpliceDecl (L _ e) _) = pprSplice e
319

Austin Seipp's avatar
Austin Seipp committed
320 321 322
{-
************************************************************************
*                                                                      *
323
            Type and class declarations
Austin Seipp's avatar
Austin Seipp committed
324 325
*                                                                      *
************************************************************************
326

327 328
Note [The Naming story]
~~~~~~~~~~~~~~~~~~~~~~~
329 330
Here is the story about the implicit names that go with type, class,
and instance decls.  It's a bit tricky, so pay attention!
331 332 333

"Implicit" (or "system") binders
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
334
  Each data type decl defines
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
335 336
        a worker name for each constructor
        to-T and from-T convertors
337
  Each class decl defines
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
338 339 340 341
        a tycon for the class
        a data constructor for that tycon
        the worker for that constructor
        a selector for each superclass
342

343 344
All have occurrence names that are derived uniquely from their parent
declaration.
345 346 347 348 349 350 351

None of these get separate definitions in an interface file; they are
fully defined by the data or class decl.  But they may *occur* in
interface files, of course.  Any such occurrence must haul in the
relevant type or class decl.

Plan of attack:
352
 - Ensure they "point to" the parent data/class decl
353
   when loading that decl from an interface file
354 355 356 357 358
   (See RnHiFiles.getSysBinders)

 - When typechecking the decl, we build the implicit TyCons and Ids.
   When doing so we look them up in the name cache (RnEnv.lookupSysName),
   to ensure correct module and provenance is set
359

360 361
These are the two places that we have to conjure up the magic derived
names.  (The actual magic is in OccName.mkWorkerOcc, etc.)
362

363 364 365 366 367 368
Default methods
~~~~~~~~~~~~~~~
 - Occurrence name is derived uniquely from the method name
   E.g. $dmmax

 - If there is a default method name at all, it's recorded in
369 370
   the ClassOpSig (in HsBinds), in the DefMethInfo field.
   (DefMethInfo is defined in Class.hs)
371 372 373 374 375 376 377

Source-code class decls and interface-code class decls are treated subtly
differently, which has given me a great deal of confusion over the years.
Here's the deal.  (We distinguish the two cases because source-code decls
have (Just binds) in the tcdMeths field, whereas interface decls have Nothing.

In *source-code* class declarations:
378

379 380 381 382 383
 - When parsing, every ClassOpSig gets a DefMeth with a suitable RdrName
   This is done by RdrHsSyn.mkClassOpSigDM

 - The renamer renames it to a Name

384
 - During typechecking, we generate a binding for each $dm for
385
   which there's a programmer-supplied default method:
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
386 387 388 389
        class Foo a where
          op1 :: <type>
          op2 :: <type>
          op1 = ...
390
   We generate a binding for $dmop1 but not for $dmop2.
391 392
   The Class for Foo has a Nothing for op2 and
                         a Just ($dm_op1, VanillaDM) for op1.
393 394 395 396 397
   The Name for $dmop2 is simply discarded.

In *interface-file* class declarations:
  - When parsing, we see if there's an explicit programmer-supplied default method
    because there's an '=' sign to indicate it:
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
398 399 400
        class Foo a where
          op1 = :: <type>       -- NB the '='
          op2   :: <type>
401 402 403 404 405
    We use this info to generate a DefMeth with a suitable RdrName for op1,
    and a NoDefMeth for op2
  - The interface file has a separate definition for $dmop1, with unfolding etc.
  - The renamer renames it to a Name.
  - The renamer treats $dmop1 as a free variable of the declaration, so that
406
    the binding for $dmop1 will be sucked in.  (See RnHsSyn.tyClDeclFVs)
407 408 409 410 411 412 413 414 415 416 417 418 419 420
    This doesn't happen for source code class decls, because they *bind* the default method.

Dictionary functions
~~~~~~~~~~~~~~~~~~~~
Each instance declaration gives rise to one dictionary function binding.

The type checker makes up new source-code instance declarations
(e.g. from 'deriving' or generic default methods --- see
TcInstDcls.tcInstDecls1).  So we can't generate the names for
dictionary functions in advance (we don't know how many we need).

On the other hand for interface-file instance declarations, the decl
specifies the name of the dictionary function, and it has a binding elsewhere
in the interface file:
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
421 422
        instance {Eq Int} = dEqInt
        dEqInt :: {Eq Int} <pragma info>
423 424 425 426 427 428 429 430 431 432 433

So again we treat source code and interface file code slightly differently.

Source code:
  - Source code instance decls have a Nothing in the (Maybe name) field
    (see data InstDecl below)

  - The typechecker makes up a Local name for the dict fun for any source-code
    instance decl, whether it comes from a source-code instance decl, or whether
    the instance decl is derived from some other construct (e.g. 'deriving').

434
  - The occurrence name it chooses is derived from the instance decl (just for
435 436
    documentation really) --- e.g. dNumInt.  Two dict funs may share a common
    occurrence name, but will have different uniques.  E.g.
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
437 438
        instance Foo [Int]  where ...
        instance Foo [Bool] where ...
439 440
    These might both be dFooList

441
  - The CoreTidy phase externalises the name, and ensures the occurrence name is
442 443
    unique (this isn't special to dict funs).  So we'd get dFooList and dFooList1.

444
  - We can take this relaxed approach (changing the occurrence name later)
445 446 447 448 449 450 451 452 453
    because dict fun Ids are not captured in a TyCon or Class (unlike default
    methods, say).  Instead, they are kept separately in the InstEnv.  This
    makes it easy to adjust them after compiling a module.  (Once we've finished
    compiling that module, they don't change any more.)


Interface file code:
  - The instance decl gives the dict fun name, so the InstDecl has a (Just name)
    in the (Maybe name) field.
454

455 456
  - RnHsSyn.instDeclFVs treats the dict fun name as free in the decl, so that we
    suck in the dfun binding
Austin Seipp's avatar
Austin Seipp committed
457
-}
458

459
-- | Located Declaration of a Type or Class
460 461
type LTyClDecl name = Located (TyClDecl name)

462
-- | A type or class declaration.
463
data TyClDecl name
Yuras's avatar
Yuras committed
464
  = -- | @type/data family T :: *->*@
Alan Zimmerman's avatar
Alan Zimmerman committed
465 466 467
    --
    --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnType',
    --             'ApiAnnotation.AnnData',
468
    --             'ApiAnnotation.AnnFamily','ApiAnnotation.AnnDcolon',
Jan Stolarek's avatar
Jan Stolarek committed
469 470 471 472
    --             'ApiAnnotation.AnnWhere','ApiAnnotation.AnnOpenP',
    --             'ApiAnnotation.AnnDcolon','ApiAnnotation.AnnCloseP',
    --             'ApiAnnotation.AnnEqual','ApiAnnotation.AnnRarrow',
    --             'ApiAnnotation.AnnVbar'
Alan Zimmerman's avatar
Alan Zimmerman committed
473

474
    -- For details on above see note [Api annotations] in ApiAnnotation
475
    FamDecl { tcdFam :: FamilyDecl name }
476

477
  | -- | @type@ declaration
Alan Zimmerman's avatar
Alan Zimmerman committed
478 479 480
    --
    --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnType',
    --             'ApiAnnotation.AnnEqual',
481 482

    -- For details on above see note [Api annotations] in ApiAnnotation
483 484
    SynDecl { tcdLName  :: Located name           -- ^ Type constructor
            , tcdTyVars :: LHsQTyVars name        -- ^ Type variables; for an associated type
485
                                                  --   these include outer binders
486
            , tcdRhs    :: LHsType name           -- ^ RHS of type declaration
487
            , tcdFVs    :: PostRn name NameSet }
488 489

  | -- | @data@ declaration
Alan Zimmerman's avatar
Alan Zimmerman committed
490 491 492 493
    --
    --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnData',
    --              'ApiAnnotation.AnnFamily',
    --              'ApiAnnotation.AnnNewType',
494 495
    --              'ApiAnnotation.AnnNewType','ApiAnnotation.AnnDcolon'
    --              'ApiAnnotation.AnnWhere',
496 497

    -- For details on above see note [Api annotations] in ApiAnnotation
498
    DataDecl { tcdLName    :: Located name        -- ^ Type constructor
499
             , tcdTyVars   :: LHsQTyVars name  -- ^ Type variables; for an associated type
500
                                                  --   these include outer binders
501 502 503
                                                  -- Eg  class T a where
                                                  --       type F a :: *
                                                  --       type F a = a -> a
504
                                                  -- Here the type decl for 'f' includes 'a'
505
                                                  -- in its tcdTyVars
506
             , tcdDataDefn :: HsDataDefn name
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
507
             , tcdDataCusk :: PostRn name Bool    -- ^ does this have a CUSK?
508
             , tcdFVs      :: PostRn name NameSet }
509

chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
510 511
  | ClassDecl { tcdCtxt    :: LHsContext name,          -- ^ Context...
                tcdLName   :: Located name,             -- ^ Name of the class
512
                tcdTyVars  :: LHsQTyVars name,          -- ^ Class type variables
Alan Zimmerman's avatar
Alan Zimmerman committed
513 514
                tcdFDs     :: [Located (FunDep (Located name))],
                                                        -- ^ Functional deps
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
515 516
                tcdSigs    :: [LSig name],              -- ^ Methods' signatures
                tcdMeths   :: LHsBinds name,            -- ^ Default methods
Alan Zimmerman's avatar
Alan Zimmerman committed
517
                tcdATs     :: [LFamilyDecl name],       -- ^ Associated types;
518
                tcdATDefs  :: [LTyFamDefltEqn name],    -- ^ Associated type defaults
519
                tcdDocs    :: [LDocDecl],               -- ^ Haddock docs
520
                tcdFVs     :: PostRn name NameSet
521
    }
Alan Zimmerman's avatar
Alan Zimmerman committed
522 523 524 525 526 527
        -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnClass',
        --           'ApiAnnotation.AnnWhere','ApiAnnotation.AnnOpen',
        --           'ApiAnnotation.AnnClose'
        --   - The tcdFDs will have 'ApiAnnotation.AnnVbar',
        --                          'ApiAnnotation.AnnComma'
        --                          'ApiAnnotation.AnnRarrow'
528

529 530
        -- For details on above see note [Api annotations] in ApiAnnotation

531
deriving instance (DataId id) => Data (TyClDecl id)
532

533

Jan Stolarek's avatar
Jan Stolarek committed
534 535
-- Simple classifiers for TyClDecl
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
536

537
-- | @True@ <=> argument is a @data@\/@newtype@
538 539
-- declaration.
isDataDecl :: TyClDecl name -> Bool
540 541
isDataDecl (DataDecl {}) = True
isDataDecl _other        = False
542

543 544
-- | type or type instance declaration
isSynDecl :: TyClDecl name -> Bool
545 546
isSynDecl (SynDecl {})   = True
isSynDecl _other        = False
547

548 549
-- | type class
isClassDecl :: TyClDecl name -> Bool
550
isClassDecl (ClassDecl {}) = True
551
isClassDecl _              = False
552

553
-- | type/data family declaration
554
isFamilyDecl :: TyClDecl name -> Bool
555
isFamilyDecl (FamDecl {})  = True
556
isFamilyDecl _other        = False
557 558 559

-- | type family declaration
isTypeFamilyDecl :: TyClDecl name -> Bool
560 561 562 563 564
isTypeFamilyDecl (FamDecl (FamilyDecl { fdInfo = info })) = case info of
  OpenTypeFamily      -> True
  ClosedTypeFamily {} -> True
  _                   -> False
isTypeFamilyDecl _ = False
565

566 567 568 569 570 571 572 573 574 575
-- | open type family info
isOpenTypeFamilyInfo :: FamilyInfo name -> Bool
isOpenTypeFamilyInfo OpenTypeFamily = True
isOpenTypeFamilyInfo _              = False

-- | closed type family info
isClosedTypeFamilyInfo :: FamilyInfo name -> Bool
isClosedTypeFamilyInfo (ClosedTypeFamily {}) = True
isClosedTypeFamilyInfo _                     = False

576 577
-- | data family declaration
isDataFamilyDecl :: TyClDecl name -> Bool
578
isDataFamilyDecl (FamDecl (FamilyDecl { fdInfo = DataFamily })) = True
579
isDataFamilyDecl _other      = False
580

Austin Seipp's avatar
Austin Seipp committed
581
-- Dealing with names
582

583
tyFamInstDeclName :: TyFamInstDecl name -> name
584 585
tyFamInstDeclName = unLoc . tyFamInstDeclLName

586
tyFamInstDeclLName :: TyFamInstDecl name -> Located name
587
tyFamInstDeclLName (TyFamInstDecl { tfid_eqn =
588
                     (L _ (TyFamEqn { tfe_tycon = ln })) })
589 590 591 592 593
  = ln

tyClDeclLName :: TyClDecl name -> Located name
tyClDeclLName (FamDecl { tcdFam = FamilyDecl { fdLName = ln } }) = ln
tyClDeclLName decl = tcdLName decl
594

595
tcdName :: TyClDecl name -> name
596 597
tcdName = unLoc . tyClDeclLName

598
tyClDeclTyVars :: TyClDecl name -> LHsQTyVars name
599 600
tyClDeclTyVars (FamDecl { tcdFam = FamilyDecl { fdTyVars = tvs } }) = tvs
tyClDeclTyVars d = tcdTyVars d
601

602 603
countTyClDecls :: [TyClDecl name] -> (Int, Int, Int, Int, Int)
        -- class, synonym decls, data, newtype, family decls
604
countTyClDecls decls
605 606 607 608
 = (count isClassDecl    decls,
    count isSynDecl      decls,  -- excluding...
    count isDataTy       decls,  -- ...family...
    count isNewTy        decls,  -- ...instances
609
    count isFamilyDecl   decls)
sof's avatar
sof committed
610
 where
611 612
   isDataTy DataDecl{ tcdDataDefn = HsDataDefn { dd_ND = DataType } } = True
   isDataTy _                                                       = False
613

614 615
   isNewTy DataDecl{ tcdDataDefn = HsDataDefn { dd_ND = NewType } } = True
   isNewTy _                                                      = False
616 617 618

-- | Does this declaration have a complete, user-supplied kind signature?
-- See Note [Complete user-supplied kind signatures]
619
hsDeclHasCusk :: TyClDecl Name -> Bool
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
620
hsDeclHasCusk (FamDecl { tcdFam = fam_decl }) = famDeclHasCusk Nothing fam_decl
621
hsDeclHasCusk (SynDecl { tcdTyVars = tyvars, tcdRhs = rhs })
622
  -- NB: Keep this synchronized with 'getInitialKind'
623 624 625 626 627 628
  = hsTvbAllKinded tyvars && rhs_annotated rhs
  where
    rhs_annotated (L _ ty) = case ty of
      HsParTy lty  -> rhs_annotated lty
      HsKindSig {} -> True
      _            -> False
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
629
hsDeclHasCusk (DataDecl { tcdDataCusk = cusk }) = cusk
630 631
hsDeclHasCusk (ClassDecl { tcdTyVars = tyvars }) = hsTvbAllKinded tyvars

Jan Stolarek's avatar
Jan Stolarek committed
632 633
-- Pretty-printing TyClDecl
-- ~~~~~~~~~~~~~~~~~~~~~~~~
634

635
instance (OutputableBndrId name) => Outputable (TyClDecl name) where
636

637 638
    ppr (FamDecl { tcdFam = decl }) = ppr decl
    ppr (SynDecl { tcdLName = ltycon, tcdTyVars = tyvars, tcdRhs = rhs })
639
      = hang (text "type" <+>
640
              pp_vanilla_decl_head ltycon tyvars [] <+> equals)
641
          4 (ppr rhs)
642

643 644
    ppr (DataDecl { tcdLName = ltycon, tcdTyVars = tyvars, tcdDataDefn = defn })
      = pp_data_defn (pp_vanilla_decl_head ltycon tyvars) defn
645

646
    ppr (ClassDecl {tcdCtxt = context, tcdLName = lclas, tcdTyVars = tyvars,
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
647
                    tcdFDs  = fds,
648 649 650
                    tcdSigs = sigs, tcdMeths = methods,
                    tcdATs = ats, tcdATDefs = at_defs})
      | null sigs && isEmptyBag methods && null ats && null at_defs -- No "where" part
651 652
      = top_matter

chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
653
      | otherwise       -- Laid out
654
      = vcat [ top_matter <+> text "where"
655
             , nest 2 $ pprDeclList (map (pprFamilyDecl NotTopLevel . unLoc) ats ++
656
                                     map ppr_fam_deflt_eqn at_defs ++
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
657
                                     pprLHsBindsForUser methods sigs) ]
658
      where
659
        top_matter = text "class"
660
                     <+> pp_vanilla_decl_head lclas tyvars (unLoc context)
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
661
                     <+> pprFundeps (map unLoc fds)
662

663
instance (OutputableBndrId name) => Outputable (TyClGroup name) where
664 665 666 667 668
  ppr (TyClGroup { group_tyclds = tyclds
                 , group_roles = roles
                 , group_instds = instds
                 }
      )
669
    = ppr tyclds $$
670 671
      ppr roles $$
      ppr instds
672

673
pp_vanilla_decl_head :: (OutputableBndrId name)
Jan Stolarek's avatar
Jan Stolarek committed
674
   => Located name
675
   -> LHsQTyVars name
Jan Stolarek's avatar
Jan Stolarek committed
676 677 678 679 680 681
   -> HsContext name
   -> SDoc
pp_vanilla_decl_head thing tyvars context
 = hsep [pprHsContext context, pprPrefixOcc (unLoc thing), ppr tyvars]

pprTyClDeclFlavour :: TyClDecl a -> SDoc
682 683
pprTyClDeclFlavour (ClassDecl {})   = text "class"
pprTyClDeclFlavour (SynDecl {})     = text "type"
Jan Stolarek's avatar
Jan Stolarek committed
684
pprTyClDeclFlavour (FamDecl { tcdFam = FamilyDecl { fdInfo = info }})
685
  = pprFlavour info <+> text "family"
Jan Stolarek's avatar
Jan Stolarek committed
686 687 688 689
pprTyClDeclFlavour (DataDecl { tcdDataDefn = HsDataDefn { dd_ND = nd } })
  = ppr nd


690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
{- Note [Complete user-supplied kind signatures]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We kind-check declarations differently if they have a complete, user-supplied
kind signature (CUSK). This is because we can safely generalise a CUSKed
declaration before checking all of the others, supporting polymorphic recursion.
See ghc.haskell.org/trac/ghc/wiki/GhcKinds/KindInference#Proposednewstrategy
and #9200 for lots of discussion of how we got here.

A declaration has a CUSK if we can know its complete kind without doing any
inference, at all. Here are the rules:

 - A class or datatype is said to have a CUSK if and only if all of its type
variables are annotated. Its result kind is, by construction, Constraint or *
respectively.

 - A type synonym has a CUSK if and only if all of its type variables and its
RHS are annotated with kinds.

 - A closed type family is said to have a CUSK if and only if all of its type
variables and its return type are annotated.

 - An open type family always has a CUSK -- unannotated type variables (and
return type) default to *.

 - Additionally, if -XTypeInType is on, then a data definition with a top-level
   :: must explicitly bind all kind variables to the right of the ::.
   See test dependent/should_compile/KindLevels, which requires this case.
   (Naturally, any kind variable mentioned before the :: should not be bound
   after it.)
-}


{- *********************************************************************
*                                                                      *
                         TyClGroup
        Strongly connected components of
      type, class, instance, and role declarations
*                                                                      *
********************************************************************* -}

{- Note [TyClGroups and dependency analysis]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A TyClGroup represents a strongly connected components of type/class/instance
decls, together with the role annotations for the type/class declarations.

The hs_tyclds :: [TyClGroup] field of a HsGroup is a dependency-order
sequence of strongly-connected components.

Invariants
 * The type and class declarations, group_tyclds, may depend on each
   other, or earlier TyClGroups, but not on later ones

 * The role annotations, group_roles, are role-annotations for some or
   all of the types and classes in group_tyclds (only).

 * The instance declarations, group_instds, may (and usually will)
   depend on group_tyclds, or on earlier TyClGroups, but not on later
   ones.

See Note [Dependency analsis of type, class, and instance decls]
in RnSource for more info.
-}

753
-- | Type or Class Group
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
data TyClGroup name  -- See Note [TyClGroups and dependency analysis]
  = TyClGroup { group_tyclds :: [LTyClDecl name]
              , group_roles  :: [LRoleAnnotDecl name]
              , group_instds :: [LInstDecl name] }
deriving instance (DataId id) => Data (TyClGroup id)

emptyTyClGroup :: TyClGroup name
emptyTyClGroup = TyClGroup [] [] []

tyClGroupTyClDecls :: [TyClGroup name] -> [LTyClDecl name]
tyClGroupTyClDecls = concatMap group_tyclds

tyClGroupInstDecls :: [TyClGroup name] -> [LInstDecl name]
tyClGroupInstDecls = concatMap group_instds

tyClGroupRoleDecls :: [TyClGroup name] -> [LRoleAnnotDecl name]
tyClGroupRoleDecls = concatMap group_roles

mkTyClGroup :: [LTyClDecl name] -> [LInstDecl name] -> TyClGroup name
mkTyClGroup decls instds = TyClGroup
  { group_tyclds = decls
  , group_roles = []
  , group_instds = instds
  }



Jan Stolarek's avatar
Jan Stolarek committed
781 782 783 784 785 786
{- *********************************************************************
*                                                                      *
               Data and type family declarations
*                                                                      *
********************************************************************* -}

787 788
{- Note [FamilyResultSig]
~~~~~~~~~~~~~~~~~~~~~~~~~
Jan Stolarek's avatar
Jan Stolarek committed
789

790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848
This data type represents the return signature of a type family.  Possible
values are:

 * NoSig - the user supplied no return signature:
      type family Id a where ...

 * KindSig - the user supplied the return kind:
      type family Id a :: * where ...

 * TyVarSig - user named the result with a type variable and possibly
   provided a kind signature for that variable:
      type family Id a = r where ...
      type family Id a = (r :: *) where ...

   Naming result of a type family is required if we want to provide
   injectivity annotation for a type family:
      type family Id a = r | r -> a where ...

See also: Note [Injectivity annotation]

Note [Injectivity annotation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

A user can declare a type family to be injective:

   type family Id a = r | r -> a where ...

 * The part after the "|" is called "injectivity annotation".
 * "r -> a" part is called "injectivity condition"; at the moment terms
   "injectivity annotation" and "injectivity condition" are synonymous
   because we only allow a single injectivity condition.
 * "r" is the "LHS of injectivity condition". LHS can only contain the
   variable naming the result of a type family.

 * "a" is the "RHS of injectivity condition". RHS contains space-separated
   type and kind variables representing the arguments of a type
   family. Variables can be omitted if a type family is not injective in
   these arguments. Example:
         type family Foo a b c = d | d -> a c where ...

Note that:
 (a) naming of type family result is required to provide injectivity
     annotation
 (b) for associated types if the result was named then injectivity annotation
     is mandatory. Otherwise result type variable is indistinguishable from
     associated type default.

It is possible that in the future this syntax will be extended to support
more complicated injectivity annotations. For example we could declare that
if we know the result of Plus and one of its arguments we can determine the
other argument:

   type family Plus a b = (r :: Nat) | r a -> b, r b -> a where ...

Here injectivity annotation would consist of two comma-separated injectivity
conditions.

See also Note [Injective type families] in TyCon
-}
Jan Stolarek's avatar
Jan Stolarek committed
849

850
-- | Located type Family Result Signature
Jan Stolarek's avatar
Jan Stolarek committed
851
type LFamilyResultSig name = Located (FamilyResultSig name)
852 853

-- | type Family Result Signature
Jan Stolarek's avatar
Jan Stolarek committed
854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
data FamilyResultSig name = -- see Note [FamilyResultSig]
    NoSig
  -- ^ - 'ApiAnnotation.AnnKeywordId' :

  -- For details on above see note [Api annotations] in ApiAnnotation

  | KindSig  (LHsKind name)
  -- ^ - 'ApiAnnotation.AnnKeywordId' :
  --             'ApiAnnotation.AnnOpenP','ApiAnnotation.AnnDcolon',
  --             'ApiAnnotation.AnnCloseP'

  -- For details on above see note [Api annotations] in ApiAnnotation

  | TyVarSig (LHsTyVarBndr name)
  -- ^ - 'ApiAnnotation.AnnKeywordId' :
  --             'ApiAnnotation.AnnOpenP','ApiAnnotation.AnnDcolon',
  --             'ApiAnnotation.AnnCloseP', 'ApiAnnotation.AnnEqual'

  -- For details on above see note [Api annotations] in ApiAnnotation

deriving instance (DataId name) => Data (FamilyResultSig name)

876
-- | Located type Family Declaration
Jan Stolarek's avatar
Jan Stolarek committed
877
type LFamilyDecl name = Located (FamilyDecl name)
878 879

-- | type Family Declaration
Jan Stolarek's avatar
Jan Stolarek committed
880 881 882
data FamilyDecl name = FamilyDecl
  { fdInfo           :: FamilyInfo name              -- type/data, closed/open
  , fdLName          :: Located name                 -- type constructor
883
  , fdTyVars         :: LHsQTyVars name              -- type variables
Jan Stolarek's avatar
Jan Stolarek committed
884 885 886 887 888 889 890 891 892 893 894 895 896 897
  , fdResultSig      :: LFamilyResultSig name        -- result signature
  , fdInjectivityAnn :: Maybe (LInjectivityAnn name) -- optional injectivity ann
  }
  -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnType',
  --             'ApiAnnotation.AnnData', 'ApiAnnotation.AnnFamily',
  --             'ApiAnnotation.AnnWhere', 'ApiAnnotation.AnnOpenP',
  --             'ApiAnnotation.AnnDcolon', 'ApiAnnotation.AnnCloseP',
  --             'ApiAnnotation.AnnEqual', 'ApiAnnotation.AnnRarrow',
  --             'ApiAnnotation.AnnVbar'

  -- For details on above see note [Api annotations] in ApiAnnotation

deriving instance (DataId id) => Data (FamilyDecl id)

898
-- | Located Injectivity Annotation
Jan Stolarek's avatar
Jan Stolarek committed
899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
type LInjectivityAnn name = Located (InjectivityAnn name)

-- | If the user supplied an injectivity annotation it is represented using
-- InjectivityAnn. At the moment this is a single injectivity condition - see
-- Note [Injectivity annotation]. `Located name` stores the LHS of injectivity
-- condition. `[Located name]` stores the RHS of injectivity condition. Example:
--
--   type family Foo a b c = r | r -> a c where ...
--
-- This will be represented as "InjectivityAnn `r` [`a`, `c`]"
data InjectivityAnn name
  = InjectivityAnn (Located name) [Located name]
  -- ^ - 'ApiAnnotation.AnnKeywordId' :
  --             'ApiAnnotation.AnnRarrow', 'ApiAnnotation.AnnVbar'

  -- For details on above see note [Api annotations] in ApiAnnotation
915
  deriving Data
Jan Stolarek's avatar
Jan Stolarek committed
916 917 918 919 920 921 922 923 924 925

data FamilyInfo name
  = DataFamily
  | OpenTypeFamily
     -- | 'Nothing' if we're in an hs-boot file and the user
     -- said "type family Foo x where .."
  | ClosedTypeFamily (Maybe [LTyFamInstEqn name])
deriving instance (DataId name) => Data (FamilyInfo name)

-- | Does this family declaration have a complete, user-supplied kind signature?
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
926 927 928 929 930