Decls.hs 95.2 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
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE FlexibleContexts #-}
10
{-# LANGUAGE FlexibleInstances #-}
11
{-# LANGUAGE UndecidableInstances #-} -- Note [Pass sensitive types]
12
                                      -- in module GHC.Hs.PlaceHolder
13
{-# LANGUAGE ConstraintKinds #-}
14
{-# LANGUAGE TypeFamilies #-}
15

16 17
-- | Abstract syntax of global declarations.
--
18
-- Definitions for: @SynDecl@ and @ConDecl@, @ClassDecl@,
19
-- @InstDecl@, @DefaultDecl@ and @ForeignDecl@.
20
module GHC.Hs.Decls (
21
  -- * Toplevel declarations
22
  HsDecl(..), LHsDecl, HsDataDefn(..), HsDeriving, LHsFunDep,
23
  HsDerivingClause(..), LHsDerivingClause, NewOrData(..), newOrDataToFlavour,
24
  StandaloneKindSig(..), LStandaloneKindSig, standaloneKindSigName,
25

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

40
  -- ** Instance declarations
41
  InstDecl(..), LInstDecl, FamilyInfo(..),
42
  TyFamInstDecl(..), LTyFamInstDecl, instDeclDataFamInsts,
43
  TyFamDefltDecl, LTyFamDefltDecl,
44
  DataFamInstDecl(..), LDataFamInstDecl,
45
  pprDataFamInstFlavour, pprTyFamInstDecl, pprHsFamInstLHS,
46
  FamInstEqn, LFamInstEqn, FamEqn(..),
47
  TyFamInstEqn, LTyFamInstEqn, HsTyPats,
48
  LClsInstDecl, ClsInstDecl(..),
49

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

  -- * Grouping
87
  HsGroup(..),  emptyRdrGroup, emptyRnGroup, appendGroups, hsGroupInstDecls
88

89
    ) where
90 91

-- friends:
92 93
import GhcPrelude

94 95
import {-# SOURCE #-} GHC.Hs.Expr( HsExpr, HsSplice, pprExpr,
                                   pprSpliceDecl )
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
96
        -- Because Expr imports Decls via HsBracket
97

98 99 100
import GHC.Hs.Binds
import GHC.Hs.Types
import GHC.Hs.Doc
101
import TyCon
102
import BasicTypes
103
import Coercion
104
import ForeignCall
105
import GHC.Hs.Extension
106
import NameSet
107 108

-- others:
109
import Class
110
import Outputable
111 112
import Util
import SrcLoc
Ryan Scott's avatar
Ryan Scott committed
113
import Type
114

115
import Bag
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
116
import Maybes
117
import Data.Data        hiding (TyCon,Fixity, Infix)
118

Austin Seipp's avatar
Austin Seipp committed
119 120 121
{-
************************************************************************
*                                                                      *
122
\subsection[HsDecl]{Declarations}
Austin Seipp's avatar
Austin Seipp committed
123 124 125
*                                                                      *
************************************************************************
-}
126

127
type LHsDecl p = Located (HsDecl p)
Alan Zimmerman's avatar
Alan Zimmerman committed
128 129 130 131
        -- ^ When in a list this may have
        --
        --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnSemi'
        --
132

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

135
-- | A Haskell Declaration
136 137 138 139 140 141
data HsDecl p
  = TyClD      (XTyClD p)      (TyClDecl p)      -- ^ Type or Class Declaration
  | InstD      (XInstD p)      (InstDecl  p)     -- ^ Instance declaration
  | DerivD     (XDerivD p)     (DerivDecl p)     -- ^ Deriving declaration
  | ValD       (XValD p)       (HsBind p)        -- ^ Value declaration
  | SigD       (XSigD p)       (Sig p)           -- ^ Signature declaration
142
  | KindSigD   (XKindSigD p)   (StandaloneKindSig p) -- ^ Standalone kind signature
143 144 145 146 147 148 149 150 151 152 153
  | DefD       (XDefD p)       (DefaultDecl p)   -- ^ 'default' declaration
  | ForD       (XForD p)       (ForeignDecl p)   -- ^ Foreign declaration
  | WarningD   (XWarningD p)   (WarnDecls p)     -- ^ Warning declaration
  | AnnD       (XAnnD p)       (AnnDecl p)       -- ^ Annotation declaration
  | RuleD      (XRuleD p)      (RuleDecls p)     -- ^ Rule declaration
  | SpliceD    (XSpliceD p)    (SpliceDecl p)    -- ^ Splice declaration
                                                 -- (Includes quasi-quotes)
  | DocD       (XDocD p)       (DocDecl)  -- ^ Documentation comment declaration
  | RoleAnnotD (XRoleAnnotD p) (RoleAnnotDecl p) -- ^Role annotation declaration
  | XHsDecl    (XXHsDecl p)

154 155 156 157 158
type instance XTyClD      (GhcPass _) = NoExtField
type instance XInstD      (GhcPass _) = NoExtField
type instance XDerivD     (GhcPass _) = NoExtField
type instance XValD       (GhcPass _) = NoExtField
type instance XSigD       (GhcPass _) = NoExtField
159
type instance XKindSigD   (GhcPass _) = NoExtField
160 161 162 163 164 165 166 167 168
type instance XDefD       (GhcPass _) = NoExtField
type instance XForD       (GhcPass _) = NoExtField
type instance XWarningD   (GhcPass _) = NoExtField
type instance XAnnD       (GhcPass _) = NoExtField
type instance XRuleD      (GhcPass _) = NoExtField
type instance XSpliceD    (GhcPass _) = NoExtField
type instance XDocD       (GhcPass _) = NoExtField
type instance XRoleAnnotD (GhcPass _) = NoExtField
type instance XXHsDecl    (GhcPass _) = NoExtCon
169 170

-- NB: all top-level fixity decls are contained EITHER
171
-- EITHER SigDs
172 173 174
-- OR     in the ClassDecls in TyClDs
--
-- The former covers
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
175 176 177 178 179
--      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
180 181
--
-- The latter is for class methods only
182

183 184 185
-- | Haskell Group
--
-- A 'HsDecl' is categorised into a 'HsGroup' before being
186
-- fed to the renamer.
187
data HsGroup p
188
  = HsGroup {
189 190 191
        hs_ext    :: XCHsGroup p,
        hs_valds  :: HsValBinds p,
        hs_splcds :: [LSpliceDecl p],
192

193
        hs_tyclds :: [TyClGroup p],
194 195
                -- 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
196 197
                -- Parser generates a singleton list;
                -- renamer does dependency analysis
198

199
        hs_derivds :: [LDerivDecl p],
200

201
        hs_fixds  :: [LFixitySig p],
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
202 203
                -- Snaffled out of both top-level fixity signatures,
                -- and those in class declarations
204

205 206 207 208 209
        hs_defds  :: [LDefaultDecl p],
        hs_fords  :: [LForeignDecl p],
        hs_warnds :: [LWarnDecls p],
        hs_annds  :: [LAnnDecl p],
        hs_ruleds :: [LRuleDecls p],
210

211
        hs_docs   :: [LDocDecl]
212 213 214
    }
  | XHsGroup (XXHsGroup p)

215 216
type instance XCHsGroup (GhcPass _) = NoExtField
type instance XXHsGroup (GhcPass _) = NoExtCon
217

218 219

emptyGroup, emptyRdrGroup, emptyRnGroup :: HsGroup (GhcPass p)
220 221 222
emptyRdrGroup = emptyGroup { hs_valds = emptyValBindsIn }
emptyRnGroup  = emptyGroup { hs_valds = emptyValBindsOut }

223 224 225
hsGroupInstDecls :: HsGroup id -> [LInstDecl id]
hsGroupInstDecls = (=<<) group_instds . hs_tyclds

226
emptyGroup = HsGroup { hs_ext = noExtField,
227
                       hs_tyclds = [],
228
                       hs_derivds = [],
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
229
                       hs_fixds = [], hs_defds = [], hs_annds = [],
230
                       hs_fords = [], hs_warnds = [], hs_ruleds = [],
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
231
                       hs_valds = error "emptyGroup hs_valds: Can't happen",
232
                       hs_splcds = [],
233
                       hs_docs = [] }
234

235 236
appendGroups :: HsGroup (GhcPass p) -> HsGroup (GhcPass p)
             -> HsGroup (GhcPass p)
237 238
appendGroups
    HsGroup {
239
        hs_valds  = val_groups1,
240
        hs_splcds = spliceds1,
241
        hs_tyclds = tyclds1,
242
        hs_derivds = derivds1,
243
        hs_fixds  = fixds1,
244 245
        hs_defds  = defds1,
        hs_annds  = annds1,
246
        hs_fords  = fords1,
247 248
        hs_warnds = warnds1,
        hs_ruleds = rulds1,
249
        hs_docs   = docs1 }
250
    HsGroup {
251
        hs_valds  = val_groups2,
252
        hs_splcds = spliceds2,
253
        hs_tyclds = tyclds2,
254
        hs_derivds = derivds2,
255
        hs_fixds  = fixds2,
256 257
        hs_defds  = defds2,
        hs_annds  = annds2,
258
        hs_fords  = fords2,
259 260 261
        hs_warnds = warnds2,
        hs_ruleds = rulds2,
        hs_docs   = docs2 }
262 263
  =
    HsGroup {
264
        hs_ext    = noExtField,
265
        hs_valds  = val_groups1 `plusHsValBinds` val_groups2,
266 267
        hs_splcds = spliceds1 ++ spliceds2,
        hs_tyclds = tyclds1 ++ tyclds2,
268
        hs_derivds = derivds1 ++ derivds2,
269 270 271
        hs_fixds  = fixds1 ++ fixds2,
        hs_annds  = annds1 ++ annds2,
        hs_defds  = defds1 ++ defds2,
272
        hs_fords  = fords1 ++ fords2,
273 274 275
        hs_warnds = warnds1 ++ warnds2,
        hs_ruleds = rulds1 ++ rulds2,
        hs_docs   = docs1  ++ docs2 }
276
appendGroups _ _ = panic "appendGroups"
277

278
instance (OutputableBndrId p) => Outputable (HsDecl (GhcPass p)) where
279 280 281 282 283 284 285
    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
286
    ppr (KindSigD _ ksd)          = ppr ksd
287 288 289 290 291 292 293
    ppr (RuleD _ rd)              = ppr rd
    ppr (WarningD _ wd)           = ppr wd
    ppr (AnnD _ ad)               = ppr ad
    ppr (SpliceD _ dd)            = ppr dd
    ppr (DocD _ doc)              = ppr doc
    ppr (RoleAnnotD _ ra)         = ppr ra
    ppr (XHsDecl x)               = ppr x
294

295
instance (OutputableBndrId p) => Outputable (HsGroup (GhcPass p)) where
296
    ppr (HsGroup { hs_valds  = val_decls,
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
297
                   hs_tyclds = tycl_decls,
298
                   hs_derivds = deriv_decls,
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
299 300 301 302 303
                   hs_fixds  = fix_decls,
                   hs_warnds = deprec_decls,
                   hs_annds  = ann_decls,
                   hs_fords  = foreign_decls,
                   hs_defds  = default_decls,
304
                   hs_ruleds = rule_decls })
305 306
        = vcat_mb empty
            [ppr_ds fix_decls, ppr_ds default_decls,
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
307 308
             ppr_ds deprec_decls, ppr_ds ann_decls,
             ppr_ds rule_decls,
309 310
             if isEmptyValBinds val_decls
                then Nothing
311
                else Just (ppr val_decls),
312
             ppr_ds (tyClGroupRoleDecls tycl_decls),
313
             ppr_ds (tyClGroupKindSigs  tycl_decls),
314 315
             ppr_ds (tyClGroupTyClDecls tycl_decls),
             ppr_ds (tyClGroupInstDecls tycl_decls),
316
             ppr_ds deriv_decls,
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
317 318
             ppr_ds foreign_decls]
        where
319
          ppr_ds :: Outputable a => [a] -> Maybe SDoc
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
320 321
          ppr_ds [] = Nothing
          ppr_ds ds = Just (vcat (map ppr ds))
322 323

          vcat_mb :: SDoc -> [Maybe SDoc] -> SDoc
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
324
          -- Concatenate vertically with white-space between non-blanks
325 326 327
          vcat_mb _    []             = empty
          vcat_mb gap (Nothing : ds) = vcat_mb gap ds
          vcat_mb gap (Just d  : ds) = gap $$ d $$ vcat_mb blankLine ds
328
    ppr (XHsGroup x) = ppr x
329

330
-- | Located Splice Declaration
331
type LSpliceDecl pass = Located (SpliceDecl pass)
332 333

-- | Splice Declaration
334
data SpliceDecl p
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
335
  = SpliceDecl                  -- Top level splice
336 337
        (XSpliceDecl p)
        (Located (HsSplice p))
338
        SpliceExplicitFlag
339 340
  | XSpliceDecl (XXSpliceDecl p)

341 342
type instance XSpliceDecl      (GhcPass _) = NoExtField
type instance XXSpliceDecl     (GhcPass _) = NoExtCon
343

344 345
instance OutputableBndrId p
       => Outputable (SpliceDecl (GhcPass p)) where
346 347
   ppr (SpliceDecl _ (L _ e) f) = pprSpliceDecl e f
   ppr (XSpliceDecl x) = ppr x
348

Austin Seipp's avatar
Austin Seipp committed
349 350 351
{-
************************************************************************
*                                                                      *
352
            Type and class declarations
Austin Seipp's avatar
Austin Seipp committed
353 354
*                                                                      *
************************************************************************
355

356 357
Note [The Naming story]
~~~~~~~~~~~~~~~~~~~~~~~
358 359
Here is the story about the implicit names that go with type, class,
and instance decls.  It's a bit tricky, so pay attention!
360 361 362

"Implicit" (or "system") binders
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
363
  Each data type decl defines
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
364 365
        a worker name for each constructor
        to-T and from-T convertors
366
  Each class decl defines
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
367 368 369 370
        a tycon for the class
        a data constructor for that tycon
        the worker for that constructor
        a selector for each superclass
371

372 373
All have occurrence names that are derived uniquely from their parent
declaration.
374 375 376 377 378 379 380

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:
381
 - Ensure they "point to" the parent data/class decl
382
   when loading that decl from an interface file
383 384 385
   (See RnHiFiles.getSysBinders)

 - When typechecking the decl, we build the implicit TyCons and Ids.
386
   When doing so we look them up in the name cache (GHC.Rename.Env.lookupSysName),
387
   to ensure correct module and provenance is set
388

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

392 393 394 395 396 397
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
398
   the ClassOpSig (in GHC.Hs.Binds), in the DefMethInfo field.
399
   (DefMethInfo is defined in Class.hs)
400 401 402 403 404 405 406

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:
407

408 409 410 411 412
 - When parsing, every ClassOpSig gets a DefMeth with a suitable RdrName
   This is done by RdrHsSyn.mkClassOpSigDM

 - The renamer renames it to a Name

413
 - During typechecking, we generate a binding for each $dm for
414
   which there's a programmer-supplied default method:
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
415 416 417 418
        class Foo a where
          op1 :: <type>
          op2 :: <type>
          op1 = ...
419
   We generate a binding for $dmop1 but not for $dmop2.
420 421
   The Class for Foo has a Nothing for op2 and
                         a Just ($dm_op1, VanillaDM) for op1.
422 423 424 425 426
   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
427 428 429
        class Foo a where
          op1 = :: <type>       -- NB the '='
          op2   :: <type>
430 431 432 433 434
    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
435
    the binding for $dmop1 will be sucked in.  (See RnHsSyn.tyClDeclFVs)
436 437 438 439 440 441 442 443 444 445 446 447 448 449
    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
450 451
        instance {Eq Int} = dEqInt
        dEqInt :: {Eq Int} <pragma info>
452 453 454 455 456 457 458 459 460 461 462

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').

463
  - The occurrence name it chooses is derived from the instance decl (just for
464 465
    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
466 467
        instance Foo [Int]  where ...
        instance Foo [Bool] where ...
468 469
    These might both be dFooList

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

473
  - We can take this relaxed approach (changing the occurrence name later)
474 475 476 477 478 479 480 481 482
    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.
483

484 485
  - 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
486
-}
487

488
-- | Located Declaration of a Type or Class
489
type LTyClDecl pass = Located (TyClDecl pass)
490

491
-- | A type or class declaration.
492
data TyClDecl pass
Yuras's avatar
Yuras committed
493
  = -- | @type/data family T :: *->*@
Alan Zimmerman's avatar
Alan Zimmerman committed
494 495 496
    --
    --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnType',
    --             'ApiAnnotation.AnnData',
497
    --             'ApiAnnotation.AnnFamily','ApiAnnotation.AnnDcolon',
Jan Stolarek's avatar
Jan Stolarek committed
498 499 500 501
    --             'ApiAnnotation.AnnWhere','ApiAnnotation.AnnOpenP',
    --             'ApiAnnotation.AnnDcolon','ApiAnnotation.AnnCloseP',
    --             'ApiAnnotation.AnnEqual','ApiAnnotation.AnnRarrow',
    --             'ApiAnnotation.AnnVbar'
Alan Zimmerman's avatar
Alan Zimmerman committed
502

503
    -- For details on above see note [Api annotations] in ApiAnnotation
504
    FamDecl { tcdFExt :: XFamDecl pass, tcdFam :: FamilyDecl pass }
505

506
  | -- | @type@ declaration
Alan Zimmerman's avatar
Alan Zimmerman committed
507 508 509
    --
    --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnType',
    --             'ApiAnnotation.AnnEqual',
510 511

    -- For details on above see note [Api annotations] in ApiAnnotation
512 513
    SynDecl { tcdSExt   :: XSynDecl pass          -- ^ Post renameer, FVs
            , tcdLName  :: Located (IdP pass)     -- ^ Type constructor
514 515 516
            , tcdTyVars :: LHsQTyVars pass        -- ^ Type variables; for an
                                                  -- associated type these
                                                  -- include outer binders
517
            , tcdFixity :: LexicalFixity    -- ^ Fixity used in the declaration
518
            , tcdRhs    :: LHsType pass }         -- ^ RHS of type declaration
519 520

  | -- | @data@ declaration
Alan Zimmerman's avatar
Alan Zimmerman committed
521 522 523 524
    --
    --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnData',
    --              'ApiAnnotation.AnnFamily',
    --              'ApiAnnotation.AnnNewType',
525 526
    --              'ApiAnnotation.AnnNewType','ApiAnnotation.AnnDcolon'
    --              'ApiAnnotation.AnnWhere',
527 528

    -- For details on above see note [Api annotations] in ApiAnnotation
529 530 531 532 533
    DataDecl { tcdDExt     :: XDataDecl pass       -- ^ Post renamer, CUSK flag, FVs
             , tcdLName    :: Located (IdP pass)   -- ^ Type constructor
             , tcdTyVars   :: LHsQTyVars pass      -- ^ Type variables
                              -- See Note [TyVar binders for associated declarations]
             , tcdFixity   :: LexicalFixity        -- ^ Fixity used in the declaration
534
             , tcdDataDefn :: HsDataDefn pass }
535

536 537
  | ClassDecl { tcdCExt    :: XClassDecl pass,         -- ^ Post renamer, FVs
                tcdCtxt    :: LHsContext pass,         -- ^ Context...
538 539
                tcdLName   :: Located (IdP pass),      -- ^ Name of the class
                tcdTyVars  :: LHsQTyVars pass,         -- ^ Class type variables
540
                tcdFixity  :: LexicalFixity, -- ^ Fixity used in the declaration
541
                tcdFDs     :: [LHsFunDep pass],         -- ^ Functional deps
542 543 544
                tcdSigs    :: [LSig pass],              -- ^ Methods' signatures
                tcdMeths   :: LHsBinds pass,            -- ^ Default methods
                tcdATs     :: [LFamilyDecl pass],       -- ^ Associated types;
545
                tcdATDefs  :: [LTyFamDefltDecl pass],   -- ^ Associated type defaults
546
                tcdDocs    :: [LDocDecl]                -- ^ Haddock docs
547
    }
Alan Zimmerman's avatar
Alan Zimmerman committed
548 549 550 551 552 553
        -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnClass',
        --           'ApiAnnotation.AnnWhere','ApiAnnotation.AnnOpen',
        --           'ApiAnnotation.AnnClose'
        --   - The tcdFDs will have 'ApiAnnotation.AnnVbar',
        --                          'ApiAnnotation.AnnComma'
        --                          'ApiAnnotation.AnnRarrow'
554

555
        -- For details on above see note [Api annotations] in ApiAnnotation
556 557
  | XTyClDecl (XXTyClDecl pass)

558 559
type LHsFunDep pass = Located (FunDep (Located (IdP pass)))

560 561
data DataDeclRn = DataDeclRn
             { tcdDataCusk :: Bool    -- ^ does this have a CUSK?
562
                 -- See Note [CUSKs: complete user-supplied kind signatures]
563 564
             , tcdFVs      :: NameSet }
  deriving Data
565

566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
{- Note [TyVar binders for associated decls]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For an /associated/ data, newtype, or type-family decl, the LHsQTyVars
/includes/ outer binders.  For example
    class T a where
       data D a c
       type F a b :: *
       type F a b = a -> a
Here the data decl for 'D', and type-family decl for 'F', both include 'a'
in their LHsQTyVars (tcdTyVars and fdTyVars resp).

Ditto any implicit binders in the hsq_implicit field of the LHSQTyVars.

The idea is that the associated type is really a top-level decl in its
own right.  However we are careful to use the same name 'a', so that
we can match things up.

c.f. Note [Associated type tyvar names] in Class.hs
     Note [Family instance declaration binders]
-}

587
type instance XFamDecl      (GhcPass _) = NoExtField
588

589
type instance XSynDecl      GhcPs = NoExtField
590 591 592
type instance XSynDecl      GhcRn = NameSet -- FVs
type instance XSynDecl      GhcTc = NameSet -- FVs

593
type instance XDataDecl     GhcPs = NoExtField
594 595 596
type instance XDataDecl     GhcRn = DataDeclRn
type instance XDataDecl     GhcTc = DataDeclRn

597
type instance XClassDecl    GhcPs = NoExtField
598 599 600
type instance XClassDecl    GhcRn = NameSet -- FVs
type instance XClassDecl    GhcTc = NameSet -- FVs

601
type instance XXTyClDecl    (GhcPass _) = NoExtCon
602

Jan Stolarek's avatar
Jan Stolarek committed
603 604
-- Simple classifiers for TyClDecl
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
605

606
-- | @True@ <=> argument is a @data@\/@newtype@
607
-- declaration.
608
isDataDecl :: TyClDecl pass -> Bool
609 610
isDataDecl (DataDecl {}) = True
isDataDecl _other        = False
611

612
-- | type or type instance declaration
613
isSynDecl :: TyClDecl pass -> Bool
614 615
isSynDecl (SynDecl {})   = True
isSynDecl _other        = False
616

617
-- | type class
618
isClassDecl :: TyClDecl pass -> Bool
619
isClassDecl (ClassDecl {}) = True
620
isClassDecl _              = False
621

622
-- | type/data family declaration
623
isFamilyDecl :: TyClDecl pass -> Bool
624
isFamilyDecl (FamDecl {})  = True
625
isFamilyDecl _other        = False
626 627

-- | type family declaration
628
isTypeFamilyDecl :: TyClDecl pass -> Bool
629
isTypeFamilyDecl (FamDecl _ (FamilyDecl { fdInfo = info })) = case info of
630 631 632 633
  OpenTypeFamily      -> True
  ClosedTypeFamily {} -> True
  _                   -> False
isTypeFamilyDecl _ = False
634

635
-- | open type family info
636
isOpenTypeFamilyInfo :: FamilyInfo pass -> Bool
637 638 639 640
isOpenTypeFamilyInfo OpenTypeFamily = True
isOpenTypeFamilyInfo _              = False

-- | closed type family info
641
isClosedTypeFamilyInfo :: FamilyInfo pass -> Bool
642 643 644
isClosedTypeFamilyInfo (ClosedTypeFamily {}) = True
isClosedTypeFamilyInfo _                     = False

645
-- | data family declaration
646
isDataFamilyDecl :: TyClDecl pass -> Bool
647
isDataFamilyDecl (FamDecl _ (FamilyDecl { fdInfo = DataFamily })) = True
648
isDataFamilyDecl _other      = False
649

Austin Seipp's avatar
Austin Seipp committed
650
-- Dealing with names
651

652
tyFamInstDeclName :: TyFamInstDecl (GhcPass p) -> IdP (GhcPass p)
653 654
tyFamInstDeclName = unLoc . tyFamInstDeclLName

655
tyFamInstDeclLName :: TyFamInstDecl (GhcPass p) -> Located (IdP (GhcPass p))
656
tyFamInstDeclLName (TyFamInstDecl { tfid_eqn =
657
                     (HsIB { hsib_body = FamEqn { feqn_tycon = ln }}) })
658
  = ln
659 660 661 662
tyFamInstDeclLName (TyFamInstDecl (HsIB _ (XFamEqn nec)))
  = noExtCon nec
tyFamInstDeclLName (TyFamInstDecl (XHsImplicitBndrs nec))
  = noExtCon nec
663

664
tyClDeclLName :: TyClDecl pass -> Located (IdP pass)
665 666
tyClDeclLName (FamDecl { tcdFam = FamilyDecl { fdLName = ln } }) = ln
tyClDeclLName decl = tcdLName decl
667

668
tcdName :: TyClDecl pass -> IdP pass
669 670
tcdName = unLoc . tyClDeclLName

671
tyClDeclTyVars :: TyClDecl pass -> LHsQTyVars pass
672 673
tyClDeclTyVars (FamDecl { tcdFam = FamilyDecl { fdTyVars = tvs } }) = tvs
tyClDeclTyVars d = tcdTyVars d
674

675
countTyClDecls :: [TyClDecl pass] -> (Int, Int, Int, Int, Int)
676
        -- class, synonym decls, data, newtype, family decls
677
countTyClDecls decls
678 679 680 681
 = (count isClassDecl    decls,
    count isSynDecl      decls,  -- excluding...
    count isDataTy       decls,  -- ...family...
    count isNewTy        decls,  -- ...instances
682
    count isFamilyDecl   decls)
sof's avatar
sof committed
683
 where
684 685
   isDataTy DataDecl{ tcdDataDefn = HsDataDefn { dd_ND = DataType } } = True
   isDataTy _                                                       = False
686

687 688
   isNewTy DataDecl{ tcdDataDefn = HsDataDefn { dd_ND = NewType } } = True
   isNewTy _                                                      = False
689 690

-- | Does this declaration have a complete, user-supplied kind signature?
691
-- See Note [CUSKs: complete user-supplied kind signatures]
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
hsDeclHasCusk :: TyClDecl GhcRn -> Bool
hsDeclHasCusk (FamDecl { tcdFam =
    FamilyDecl { fdInfo      = fam_info
               , fdTyVars    = tyvars
               , fdResultSig = L _ resultSig } }) =
    case fam_info of
      ClosedTypeFamily {} -> hsTvbAllKinded tyvars
                          && isJust (famResultKindSignature resultSig)
      _ -> True -- Un-associated open type/data families have CUSKs
hsDeclHasCusk (SynDecl { tcdTyVars = tyvars, tcdRhs = rhs })
  = hsTvbAllKinded tyvars && isJust (hsTyKindSig rhs)
hsDeclHasCusk (DataDecl { tcdDExt = DataDeclRn { tcdDataCusk = cusk }}) = cusk
hsDeclHasCusk (ClassDecl { tcdTyVars = tyvars }) = hsTvbAllKinded tyvars
hsDeclHasCusk (FamDecl { tcdFam = XFamilyDecl nec }) = noExtCon nec
hsDeclHasCusk (XTyClDecl nec) = noExtCon nec
707

Jan Stolarek's avatar
Jan Stolarek committed
708 709
-- Pretty-printing TyClDecl
-- ~~~~~~~~~~~~~~~~~~~~~~~~
710

711
instance (OutputableBndrId p) => Outputable (TyClDecl (GhcPass p)) where
712

713
    ppr (FamDecl { tcdFam = decl }) = ppr decl
714 715
    ppr (SynDecl { tcdLName = ltycon, tcdTyVars = tyvars, tcdFixity = fixity
                 , tcdRhs = rhs })
716
      = hang (text "type" <+>
717
              pp_vanilla_decl_head ltycon tyvars fixity noLHsContext <+> equals)
718
          4 (ppr rhs)
719

720 721 722
    ppr (DataDecl { tcdLName = ltycon, tcdTyVars = tyvars, tcdFixity = fixity
                  , tcdDataDefn = defn })
      = pp_data_defn (pp_vanilla_decl_head ltycon tyvars fixity) defn
723

724
    ppr (ClassDecl {tcdCtxt = context, tcdLName = lclas, tcdTyVars = tyvars,
725
                    tcdFixity = fixity,
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
726
                    tcdFDs  = fds,
727 728 729
                    tcdSigs = sigs, tcdMeths = methods,
                    tcdATs = ats, tcdATDefs = at_defs})
      | null sigs && isEmptyBag methods && null ats && null at_defs -- No "where" part
730 731
      = top_matter

chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
732
      | otherwise       -- Laid out
733
      = vcat [ top_matter <+> text "where"
734
             , nest 2 $ pprDeclList (map (pprFamilyDecl NotTopLevel . unLoc) ats ++
735
                                     map (pprTyFamDefltDecl . unLoc) at_defs ++
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
736
                                     pprLHsBindsForUser methods sigs) ]
737
      where
738
        top_matter = text "class"
739
                    <+> pp_vanilla_decl_head lclas tyvars fixity context
740
                    <+> pprFundeps (map unLoc fds)
741

742
    ppr (XTyClDecl x) = ppr x
743

744 745
instance OutputableBndrId p
       => Outputable (TyClGroup (GhcPass p)) where
746 747
  ppr (TyClGroup { group_tyclds = tyclds
                 , group_roles = roles
748
                 , group_kisigs = kisigs
749 750 751
                 , group_instds = instds
                 }
      )
752 753 754
    = hang (text "TyClGroup") 2 $
      ppr kisigs $$
      ppr tyclds $$
755 756
      ppr roles $$
      ppr instds
757
  ppr (XTyClGroup x) = ppr x
758

759
pp_vanilla_decl_head :: (OutputableBndrId p)
760 761
   => Located (IdP (GhcPass p))
   -> LHsQTyVars (GhcPass p)
762
   -> LexicalFixity
763
   -> LHsContext (GhcPass p)
Jan Stolarek's avatar
Jan Stolarek committed
764
   -> SDoc
765
pp_vanilla_decl_head thing (HsQTvs { hsq_explicit = tyvars }) fixity context
766
 = hsep [pprLHsContext context, pp_tyvars tyvars]
767 768
  where
    pp_tyvars (varl:varsr)
769 770 771 772
      | fixity == Infix && length varsr > 1
         = hsep [char '(',ppr (unLoc varl), pprInfixOcc (unLoc thing)
                , (ppr.unLoc) (head varsr), char ')'
                , hsep (map (ppr.unLoc) (tail varsr))]
773
      | fixity == Infix
774 775 776 777
         = hsep [ppr (unLoc varl), pprInfixOcc (unLoc thing)
         , hsep (map (ppr.unLoc) varsr)]
      | otherwise = hsep [ pprPrefixOcc (unLoc thing)
                  , hsep (map (ppr.unLoc) (varl:varsr))]
778
    pp_tyvars [] = pprPrefixOcc (unLoc thing)
779
pp_vanilla_decl_head _ (XLHsQTyVars x) _ _ = ppr x
Jan Stolarek's avatar
Jan Stolarek committed
780

781
pprTyClDeclFlavour :: TyClDecl (GhcPass p) -> SDoc
782 783
pprTyClDeclFlavour (ClassDecl {})   = text "class"
pprTyClDeclFlavour (SynDecl {})     = text "type"
Jan Stolarek's avatar
Jan Stolarek committed
784
pprTyClDeclFlavour (FamDecl { tcdFam = FamilyDecl { fdInfo = info }})
785
  = pprFlavour info <+> text "family"
786 787
pprTyClDeclFlavour (FamDecl { tcdFam = XFamilyDecl nec })
  = noExtCon nec
Jan Stolarek's avatar
Jan Stolarek committed
788 789
pprTyClDeclFlavour (DataDecl { tcdDataDefn = HsDataDefn { dd_ND = nd } })
  = ppr nd
790 791 792
pprTyClDeclFlavour (DataDecl { tcdDataDefn = XHsDataDefn x })
  = ppr x
pprTyClDeclFlavour (XTyClDecl x) = ppr x
Jan Stolarek's avatar
Jan Stolarek committed
793 794


795 796
{- Note [CUSKs: complete user-supplied kind signatures]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
797 798 799
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.
800
See https://gitlab.haskell.org/ghc/ghc/wikis/ghc-kinds/kind-inference#proposed-new-strategy
801 802
and #9200 for lots of discussion of how we got here.

803 804 805 806
The detection of CUSKs is enabled by the -XCUSKs extension, switched on by default.
Under -XNoCUSKs, all declarations are treated as if they have no CUSK.
See https://github.com/ghc-proposals/ghc-proposals/blob/master/proposals/0036-kind-signatures.rst

807 808 809 810 811 812 813 814 815 816 817
PRINCIPLE:
  a type declaration has a CUSK iff we could produce a separate kind signature
  for it, just like a type signature for a function,
  looking only at the header of the declaration.

Examples:
  * data T1 (a :: *->*) (b :: *) = ....
    -- Has CUSK; equivalant to   T1 :: (*->*) -> * -> *

 * data T2 a b = ...
   -- No CUSK; we do not want to guess T2 :: * -> * -> *
Gabor Greif's avatar
Gabor Greif committed
818
   -- because the full decl might be   data T a b = MkT (a b)
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 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872

  * data T3 (a :: k -> *) (b :: *) = ...
    -- CUSK; equivalent to   T3 :: (k -> *) -> * -> *
    -- We lexically generalise over k to get
    --    T3 :: forall k. (k -> *) -> * -> *
    -- The generalisation is here is purely lexical, just like
    --    f3 :: a -> a
    -- means
    --    f3 :: forall a. a -> a

  * data T4 (a :: j k) = ...
     -- CUSK; equivalent to   T4 :: j k -> *
     -- which we lexically generalise to  T4 :: forall j k. j k -> *
     -- and then, if PolyKinds is on, we further generalise to
     --   T4 :: forall kk (j :: kk -> *) (k :: kk). j k -> *
     -- Again this is exactly like what happens as the term level
     -- when you write
     --    f4 :: forall a b. a b -> Int

NOTE THAT
  * A CUSK does /not/ mean that everything about the kind signature is
    fully specified by the user.  Look at T4 and f4: we had do do kind
    inference to figure out the kind-quantification.  But in both cases
    (T4 and f4) that inference is done looking /only/ at the header of T4
    (or signature for f4), not at the definition thereof.

  * The CUSK completely fixes the kind of the type constructor, forever.

  * The precise rules, for each declaration form, for whethher a declaration
    has a CUSK are given in the user manual section "Complete user-supplied
    kind signatures and polymorphic recursion".  BUt they simply implement
    PRINCIPLE above.

  * Open type families are interesting:
      type family T5 a b :: *
    There simply /is/ no accompanying declaration, so that info is all
    we'll ever get.  So we it has a CUSK by definition, and we default
    any un-fixed kind variables to *.

  * Associated types are a bit tricker:
      class C6 a where
         type family T6 a b :: *
         op :: a Int -> Int
    Here C6 does not have a CUSK (in fact we ultimately discover that
    a :: * -> *).  And hence neither does T6, the associated family,
    because we can't fix its kind until we have settled C6.  Another
    way to say it: unlike a top-level, we /may/ discover more about
    a's kind from C6's definition.

  * 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.)
Simon Peyton Jones's avatar
Simon Peyton Jones committed
873 874

    This last point is much more debatable than the others; see
875
    #15142 comment:22
876 877 878 879

    Because this is fiddly to check, there is a field in the DataDeclRn
    structure (included in a DataDecl after the renamer) that stores whether
    or not the declaration has a CUSK.
880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
-}


{- *********************************************************************
*                                                                      *
                         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.

910
See Note [Dependency analysis of type, class, and instance decls]
911
in GHC.Rename.Source for more info.
912 913
-}

914
-- | Type or Class Group
915
data TyClGroup pass  -- See Note [TyClGroups and dependency analysis]
916 917
  = TyClGroup { group_ext    :: XCTyClGroup pass
              , group_tyclds :: [LTyClDecl pass]
918
              , group_roles  :: [LRoleAnnotDecl pass]
919
              , group_kisigs :: [LStandaloneKindSig pass]
920
              , group_instds :: [LInstDecl pass] }
921
  | XTyClGroup (XXTyClGroup pass)
922

923 924
type instance XCTyClGroup (GhcPass _) = NoExtField
type instance XXTyClGroup (GhcPass _) = NoExtCon
925 926


927
tyClGroupTyClDecls :: [TyClGroup pass] -> [LTyClDecl pass]
928 929
tyClGroupTyClDecls = concatMap group_tyclds

930
tyClGroupInstDecls :: [TyClGroup pass] -> [LInstDecl pass]
931 932
tyClGroupInstDecls = concatMap group_instds

933
tyClGroupRoleDecls :: [TyClGroup pass] -> [LRoleAnnotDecl pass]
934 935
tyClGroupRoleDecls = concatMap group_roles

936 937
tyClGroupKindSigs :: [TyClGroup pass] -> [LStandaloneKindSig pass]
tyClGroupKindSigs = concatMap group_kisigs
938 939


Jan Stolarek's avatar
Jan Stolarek committed
940 941 942 943 944 945
{- *********************************************************************
*                                                                      *
               Data and type family declarations
*                                                                      *
********************************************************************* -}

946 947
{- Note [FamilyResultSig]
~~~~~~~~~~~~~~~~~~~~~~~~~
Jan Stolarek's avatar
Jan Stolarek committed
948

949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
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
1008

1009
-- | Located type Family Result Signature