HsDecls.hs 86.7 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 TypeFamilies #-}
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,
22
  HsDerivingClause(..), LHsDerivingClause, NewOrData(..), newOrDataToFlavour,
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, FamilyInfo(..),
39
  TyFamInstDecl(..), LTyFamInstDecl, instDeclDataFamInsts,
40
  DataFamInstDecl(..), LDataFamInstDecl, pprDataFamInstFlavour, pprFamInstLHS,
41 42
  FamInstEqn, LFamInstEqn, FamEqn(..),
  TyFamInstEqn, LTyFamInstEqn, TyFamDefltEqn, LTyFamDefltEqn,
Alan Zimmerman's avatar
Alan Zimmerman committed
43
  HsTyPats,
44
  LClsInstDecl, ClsInstDecl(..),
45

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

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

85
    ) where
86 87

-- friends:
88 89
import GhcPrelude

Alan Zimmerman's avatar
Alan Zimmerman committed
90 91
import {-# SOURCE #-}   HsExpr( LHsExpr, HsExpr, HsSplice, pprExpr,
                                pprSpliceDecl )
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
92
        -- Because Expr imports Decls via HsBracket
93

94
import HsBinds
95
import HsTypes
96
import HsDoc
97
import TyCon
98
import Name
99
import BasicTypes
100
import Coercion
101
import ForeignCall
102
import PlaceHolder ( PlaceHolder, placeHolder )
103
import HsExtension
104
import NameSet
105 106

-- others:
107
import InstEnv
108
import Class
109
import Outputable
110 111 112
import Util
import SrcLoc

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

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

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

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

133
-- | A Haskell Declaration
134
data HsDecl id
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
  = 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
150
deriving instance (DataIdLR id id) => Data (HsDecl id)
151

152 153

-- NB: all top-level fixity decls are contained EITHER
154
-- EITHER SigDs
155 156 157
-- OR     in the ClassDecls in TyClDs
--
-- The former covers
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
158 159 160 161 162
--      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
163 164
--
-- The latter is for class methods only
165

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

175
        hs_tyclds :: [TyClGroup id],
176 177
                -- 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
178 179
                -- Parser generates a singleton list;
                -- renamer does dependency analysis
180

181
        hs_derivds :: [LDerivDecl id],
182

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

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

194
        hs_docs   :: [LDocDecl]
195
  }
196
deriving instance (DataIdLR id id) => Data (HsGroup id)
197

198
emptyGroup, emptyRdrGroup, emptyRnGroup :: HsGroup (GhcPass a)
199 200 201
emptyRdrGroup = emptyGroup { hs_valds = emptyValBindsIn }
emptyRnGroup  = emptyGroup { hs_valds = emptyValBindsOut }

202 203 204 205
hsGroupInstDecls :: HsGroup id -> [LInstDecl id]
hsGroupInstDecls = (=<<) group_instds . hs_tyclds

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

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

257
instance (p ~ GhcPass pass, OutputableBndrId p) => Outputable (HsDecl p) where
258 259 260 261 262 263 264 265
    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
266
    ppr (VectD vect)            = ppr vect
Ian Lynagh's avatar
Ian Lynagh committed
267
    ppr (WarningD wd)           = ppr wd
268
    ppr (AnnD ad)               = ppr ad
269 270
    ppr (SpliceD dd)            = ppr dd
    ppr (DocD doc)              = ppr doc
271
    ppr (RoleAnnotD ra)         = ppr ra
272

273
instance (p ~ GhcPass pass, OutputableBndrId p) => Outputable (HsGroup p) where
274
    ppr (HsGroup { hs_valds  = val_decls,
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
275
                   hs_tyclds = tycl_decls,
276
                   hs_derivds = deriv_decls,
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
277 278 279 280 281 282 283
                   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 })
284 285
        = vcat_mb empty
            [ppr_ds fix_decls, ppr_ds default_decls,
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
286 287 288
             ppr_ds deprec_decls, ppr_ds ann_decls,
             ppr_ds rule_decls,
             ppr_ds vect_decls,
289 290
             if isEmptyValBinds val_decls
                then Nothing
291
                else Just (ppr val_decls),
292 293
             ppr_ds (tyClGroupTyClDecls tycl_decls),
             ppr_ds (tyClGroupInstDecls tycl_decls),
294
             ppr_ds deriv_decls,
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
295 296
             ppr_ds foreign_decls]
        where
297
          ppr_ds :: Outputable a => [a] -> Maybe SDoc
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
298 299
          ppr_ds [] = Nothing
          ppr_ds ds = Just (vcat (map ppr ds))
300 301

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

307
-- | Located Splice Declaration
308
type LSpliceDecl pass = Located (SpliceDecl pass)
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 (DataIdLR id id) => Data (SpliceDecl id)
316

317 318
instance (p ~ GhcPass pass, OutputableBndrId p)
       => Outputable (SpliceDecl p) where
Alan Zimmerman's avatar
Alan Zimmerman committed
319
   ppr (SpliceDecl (L _ e) f) = pprSpliceDecl e f
320

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

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

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

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

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:
353
 - Ensure they "point to" the parent data/class decl
354
   when loading that decl from an interface file
355 356 357 358 359
   (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
360

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

364 365 366 367 368 369
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
370 371
   the ClassOpSig (in HsBinds), in the DefMethInfo field.
   (DefMethInfo is defined in Class.hs)
372 373 374 375 376 377 378

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

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

 - The renamer renames it to a Name

385
 - During typechecking, we generate a binding for each $dm for
386
   which there's a programmer-supplied default method:
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
387 388 389 390
        class Foo a where
          op1 :: <type>
          op2 :: <type>
          op1 = ...
391
   We generate a binding for $dmop1 but not for $dmop2.
392 393
   The Class for Foo has a Nothing for op2 and
                         a Just ($dm_op1, VanillaDM) for op1.
394 395 396 397 398
   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
399 400 401
        class Foo a where
          op1 = :: <type>       -- NB the '='
          op2   :: <type>
402 403 404 405 406
    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
407
    the binding for $dmop1 will be sucked in.  (See RnHsSyn.tyClDeclFVs)
408 409 410 411 412 413 414 415 416 417 418 419 420 421
    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
422 423
        instance {Eq Int} = dEqInt
        dEqInt :: {Eq Int} <pragma info>
424 425 426 427 428 429 430 431 432 433 434

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

435
  - The occurrence name it chooses is derived from the instance decl (just for
436 437
    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
438 439
        instance Foo [Int]  where ...
        instance Foo [Bool] where ...
440 441
    These might both be dFooList

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

445
  - We can take this relaxed approach (changing the occurrence name later)
446 447 448 449 450 451 452 453 454
    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.
455

456 457
  - 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
458
-}
459

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

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

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

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

    -- For details on above see note [Api annotations] in ApiAnnotation
484 485 486 487
    SynDecl { tcdLName  :: Located (IdP pass)     -- ^ Type constructor
            , tcdTyVars :: LHsQTyVars pass        -- ^ Type variables; for an
                                                  -- associated type these
                                                  -- include outer binders
488
            , tcdFixity :: LexicalFixity    -- ^ Fixity used in the declaration
489 490
            , tcdRhs    :: LHsType pass           -- ^ RHS of type declaration
            , tcdFVs    :: PostRn pass NameSet }
491 492

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

    -- For details on above see note [Api annotations] in ApiAnnotation
501 502 503 504 505 506 507 508 509
    DataDecl { tcdLName    :: Located (IdP pass) -- ^ Type constructor
             , tcdTyVars   :: LHsQTyVars pass  -- ^ Type variables; for an
                                               -- associated type
                                               --   these include outer binders
                                               -- Eg  class T a where
                                               --       type F a :: *
                                               --       type F a = a -> a
                                               -- Here the type decl for 'f'
                                               -- includes 'a' in its tcdTyVars
510
             , tcdFixity  :: LexicalFixity -- ^ Fixity used in the declaration
511 512 513
             , tcdDataDefn :: HsDataDefn pass
             , tcdDataCusk :: PostRn pass Bool    -- ^ does this have a CUSK?
             , tcdFVs      :: PostRn pass NameSet }
514

515 516 517
  | ClassDecl { tcdCtxt    :: LHsContext pass,         -- ^ Context...
                tcdLName   :: Located (IdP pass),      -- ^ Name of the class
                tcdTyVars  :: LHsQTyVars pass,         -- ^ Class type variables
518
                tcdFixity  :: LexicalFixity, -- ^ Fixity used in the declaration
519
                tcdFDs     :: [Located (FunDep (Located (IdP pass)))],
Alan Zimmerman's avatar
Alan Zimmerman committed
520
                                                        -- ^ Functional deps
521 522 523 524 525
                tcdSigs    :: [LSig pass],              -- ^ Methods' signatures
                tcdMeths   :: LHsBinds pass,            -- ^ Default methods
                tcdATs     :: [LFamilyDecl pass],       -- ^ Associated types;
                tcdATDefs  :: [LTyFamDefltEqn pass],
                                                   -- ^ Associated type defaults
526
                tcdDocs    :: [LDocDecl],               -- ^ Haddock docs
527
                tcdFVs     :: PostRn pass NameSet
528
    }
Alan Zimmerman's avatar
Alan Zimmerman committed
529 530 531 532 533 534
        -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnClass',
        --           'ApiAnnotation.AnnWhere','ApiAnnotation.AnnOpen',
        --           'ApiAnnotation.AnnClose'
        --   - The tcdFDs will have 'ApiAnnotation.AnnVbar',
        --                          'ApiAnnotation.AnnComma'
        --                          'ApiAnnotation.AnnRarrow'
535

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

538
deriving instance (DataIdLR id id) => Data (TyClDecl id)
539

540

Jan Stolarek's avatar
Jan Stolarek committed
541 542
-- Simple classifiers for TyClDecl
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
543

544
-- | @True@ <=> argument is a @data@\/@newtype@
545
-- declaration.
546
isDataDecl :: TyClDecl pass -> Bool
547 548
isDataDecl (DataDecl {}) = True
isDataDecl _other        = False
549

550
-- | type or type instance declaration
551
isSynDecl :: TyClDecl pass -> Bool
552 553
isSynDecl (SynDecl {})   = True
isSynDecl _other        = False
554

555
-- | type class
556
isClassDecl :: TyClDecl pass -> Bool
557
isClassDecl (ClassDecl {}) = True
558
isClassDecl _              = False
559

560
-- | type/data family declaration
561
isFamilyDecl :: TyClDecl pass -> Bool
562
isFamilyDecl (FamDecl {})  = True
563
isFamilyDecl _other        = False
564 565

-- | type family declaration
566
isTypeFamilyDecl :: TyClDecl pass -> Bool
567 568 569 570 571
isTypeFamilyDecl (FamDecl (FamilyDecl { fdInfo = info })) = case info of
  OpenTypeFamily      -> True
  ClosedTypeFamily {} -> True
  _                   -> False
isTypeFamilyDecl _ = False
572

573
-- | open type family info
574
isOpenTypeFamilyInfo :: FamilyInfo pass -> Bool
575 576 577 578
isOpenTypeFamilyInfo OpenTypeFamily = True
isOpenTypeFamilyInfo _              = False

-- | closed type family info
579
isClosedTypeFamilyInfo :: FamilyInfo pass -> Bool
580 581 582
isClosedTypeFamilyInfo (ClosedTypeFamily {}) = True
isClosedTypeFamilyInfo _                     = False

583
-- | data family declaration
584
isDataFamilyDecl :: TyClDecl pass -> Bool
585
isDataFamilyDecl (FamDecl (FamilyDecl { fdInfo = DataFamily })) = True
586
isDataFamilyDecl _other      = False
587

Austin Seipp's avatar
Austin Seipp committed
588
-- Dealing with names
589

590
tyFamInstDeclName :: TyFamInstDecl pass -> (IdP pass)
591 592
tyFamInstDeclName = unLoc . tyFamInstDeclLName

593
tyFamInstDeclLName :: TyFamInstDecl pass -> Located (IdP pass)
594
tyFamInstDeclLName (TyFamInstDecl { tfid_eqn =
595
                     (HsIB { hsib_body = FamEqn { feqn_tycon = ln }}) })
596 597
  = ln

598
tyClDeclLName :: TyClDecl pass -> Located (IdP pass)
599 600
tyClDeclLName (FamDecl { tcdFam = FamilyDecl { fdLName = ln } }) = ln
tyClDeclLName decl = tcdLName decl
601

602
tcdName :: TyClDecl pass -> (IdP pass)
603 604
tcdName = unLoc . tyClDeclLName

605
tyClDeclTyVars :: TyClDecl pass -> LHsQTyVars pass
606 607
tyClDeclTyVars (FamDecl { tcdFam = FamilyDecl { fdTyVars = tvs } }) = tvs
tyClDeclTyVars d = tcdTyVars d
608

609
countTyClDecls :: [TyClDecl pass] -> (Int, Int, Int, Int, Int)
610
        -- class, synonym decls, data, newtype, family decls
611
countTyClDecls decls
612 613 614 615
 = (count isClassDecl    decls,
    count isSynDecl      decls,  -- excluding...
    count isDataTy       decls,  -- ...family...
    count isNewTy        decls,  -- ...instances
616
    count isFamilyDecl   decls)
sof's avatar
sof committed
617
 where
618 619
   isDataTy DataDecl{ tcdDataDefn = HsDataDefn { dd_ND = DataType } } = True
   isDataTy _                                                       = False
620

621 622
   isNewTy DataDecl{ tcdDataDefn = HsDataDefn { dd_ND = NewType } } = True
   isNewTy _                                                      = False
623 624 625

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

Jan Stolarek's avatar
Jan Stolarek committed
639 640
-- Pretty-printing TyClDecl
-- ~~~~~~~~~~~~~~~~~~~~~~~~
641

642
instance (p ~ GhcPass pass, OutputableBndrId p) => Outputable (TyClDecl p) where
643

644
    ppr (FamDecl { tcdFam = decl }) = ppr decl
645 646
    ppr (SynDecl { tcdLName = ltycon, tcdTyVars = tyvars, tcdFixity = fixity
                 , tcdRhs = rhs })
647
      = hang (text "type" <+>
648
              pp_vanilla_decl_head ltycon tyvars fixity [] <+> equals)
649
          4 (ppr rhs)
650

651 652 653
    ppr (DataDecl { tcdLName = ltycon, tcdTyVars = tyvars, tcdFixity = fixity
                  , tcdDataDefn = defn })
      = pp_data_defn (pp_vanilla_decl_head ltycon tyvars fixity) defn
654

655
    ppr (ClassDecl {tcdCtxt = context, tcdLName = lclas, tcdTyVars = tyvars,
656
                    tcdFixity = fixity,
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
657
                    tcdFDs  = fds,
658 659 660
                    tcdSigs = sigs, tcdMeths = methods,
                    tcdATs = ats, tcdATDefs = at_defs})
      | null sigs && isEmptyBag methods && null ats && null at_defs -- No "where" part
661 662
      = top_matter

chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
663
      | otherwise       -- Laid out
664
      = vcat [ top_matter <+> text "where"
665
             , nest 2 $ pprDeclList (map (pprFamilyDecl NotTopLevel . unLoc) ats ++
666
                                     map ppr_fam_deflt_eqn at_defs ++
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
667
                                     pprLHsBindsForUser methods sigs) ]
668
      where
669
        top_matter = text "class"
670 671
                    <+> pp_vanilla_decl_head lclas tyvars fixity (unLoc context)
                    <+> pprFundeps (map unLoc fds)
672

673 674
instance (p ~ GhcPass pass, OutputableBndrId p)
       => Outputable (TyClGroup p) where
675 676 677 678 679
  ppr (TyClGroup { group_tyclds = tyclds
                 , group_roles = roles
                 , group_instds = instds
                 }
      )
680
    = ppr tyclds $$
681 682
      ppr roles $$
      ppr instds
683

684 685 686
pp_vanilla_decl_head :: (OutputableBndrId (GhcPass p))
   => Located (IdP (GhcPass p))
   -> LHsQTyVars (GhcPass p)
687
   -> LexicalFixity
688
   -> HsContext (GhcPass p)
Jan Stolarek's avatar
Jan Stolarek committed
689
   -> SDoc
690
pp_vanilla_decl_head thing (HsQTvs { hsq_explicit = tyvars }) fixity context
Alan Zimmerman's avatar
Alan Zimmerman committed
691 692 693
 = hsep [pprHsContext context, pp_tyvars tyvars]
  where
    pp_tyvars (varl:varsr)
694 695 696 697
      | fixity == Infix && length varsr > 1
         = hsep [char '(',ppr (unLoc varl), pprInfixOcc (unLoc thing)
                , (ppr.unLoc) (head varsr), char ')'
                , hsep (map (ppr.unLoc) (tail varsr))]
698
      | fixity == Infix
Alan Zimmerman's avatar
Alan Zimmerman committed
699 700 701 702 703
         = hsep [ppr (unLoc varl), pprInfixOcc (unLoc thing)
         , hsep (map (ppr.unLoc) varsr)]
      | otherwise = hsep [ pprPrefixOcc (unLoc thing)
                  , hsep (map (ppr.unLoc) (varl:varsr))]
    pp_tyvars [] = ppr thing
Jan Stolarek's avatar
Jan Stolarek committed
704 705

pprTyClDeclFlavour :: TyClDecl a -> SDoc
706 707
pprTyClDeclFlavour (ClassDecl {})   = text "class"
pprTyClDeclFlavour (SynDecl {})     = text "type"
Jan Stolarek's avatar
Jan Stolarek committed
708
pprTyClDeclFlavour (FamDecl { tcdFam = FamilyDecl { fdInfo = info }})
709
  = pprFlavour info <+> text "family"
Jan Stolarek's avatar
Jan Stolarek committed
710 711 712 713
pprTyClDeclFlavour (DataDecl { tcdDataDefn = HsDataDefn { dd_ND = nd } })
  = ppr nd


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 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
{- 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.
-}

777
-- | Type or Class Group
778 779 780 781
data TyClGroup pass  -- See Note [TyClGroups and dependency analysis]
  = TyClGroup { group_tyclds :: [LTyClDecl pass]
              , group_roles  :: [LRoleAnnotDecl pass]
              , group_instds :: [LInstDecl pass] }
782
deriving instance (DataIdLR id id) => Data (TyClGroup id)
783

784
emptyTyClGroup :: TyClGroup pass
785 786
emptyTyClGroup = TyClGroup [] [] []

787
tyClGroupTyClDecls :: [TyClGroup pass] -> [LTyClDecl pass]
788 789
tyClGroupTyClDecls = concatMap group_tyclds

790
tyClGroupInstDecls :: [TyClGroup pass] -> [LInstDecl pass]
791 792
tyClGroupInstDecls = concatMap group_instds

793
tyClGroupRoleDecls :: [TyClGroup pass] -> [LRoleAnnotDecl pass]
794 795
tyClGroupRoleDecls = concatMap group_roles

796
mkTyClGroup :: [LTyClDecl pass] -> [LInstDecl pass] -> TyClGroup pass
797 798 799 800 801 802 803 804
mkTyClGroup decls instds = TyClGroup
  { group_tyclds = decls
  , group_roles = []
  , group_instds = instds
  }



Jan Stolarek's avatar
Jan Stolarek committed
805 806 807 808 809 810
{- *********************************************************************
*                                                                      *
               Data and type family declarations
*                                                                      *
********************************************************************* -}

811 812
{- Note [FamilyResultSig]
~~~~~~~~~~~~~~~~~~~~~~~~~
Jan Stolarek's avatar
Jan Stolarek committed
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 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872
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
873