IfaceSyn.hs 84.6 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, 1993-1998
-}
5

6
{-# LANGUAGE CPP #-}
Ian Lynagh's avatar
Ian Lynagh committed
7

8
module IfaceSyn (
dterei's avatar
dterei committed
9
        module IfaceType,
10

11
        IfaceDecl(..), IfaceFamTyConFlav(..), IfaceClassOp(..), IfaceAT(..),
12
        IfaceConDecl(..), IfaceConDecls(..), IfaceEqSpec,
lukemaurer's avatar
lukemaurer committed
13
        IfaceExpr(..), IfaceAlt, IfaceLetBndr(..), IfaceJoinInfo(..),
dterei's avatar
dterei committed
14 15 16
        IfaceBinding(..), IfaceConAlt(..),
        IfaceIdInfo(..), IfaceIdDetails(..), IfaceUnfolding(..),
        IfaceInfoItem(..), IfaceRule(..), IfaceAnnotation(..), IfaceAnnTarget,
17
        IfaceClsInst(..), IfaceFamInst(..), IfaceTickish(..),
18
        IfaceClassBody(..),
19 20 21
        IfaceBang(..),
        IfaceSrcBang(..), SrcUnpackedness(..), SrcStrictness(..),
        IfaceAxBranch(..),
22
        IfaceTyConParent(..),
23
        IfaceCompleteMatch(..),
24

25 26 27 28
        -- * Binding names
        IfaceTopBndr,
        putIfaceTopBndr, getIfaceTopBndr,

dterei's avatar
dterei committed
29
        -- Misc
30
        ifaceDeclImplicitBndrs, visibleIfConDecls,
31
        ifaceDeclFingerprints,
32

33
        -- Free Names
34
        freeNamesIfDecl, freeNamesIfRule, freeNamesIfFamInst,
35

dterei's avatar
dterei committed
36
        -- Pretty printing
37 38
        pprIfaceExpr,
        pprIfaceDecl,
39
        AltPpr(..), ShowSub(..), ShowHowMuch(..), showToIface, showToHeader
40 41 42 43
    ) where

#include "HsVersions.h"

44 45
import GhcPrelude

46
import IfaceType
47
import BinFingerprint
48
import CoreSyn( IsOrphan, isOrphan )
49
import PprCore()            -- Printing DFunArgs
50
import Demand
Simon Marlow's avatar
Simon Marlow committed
51
import Class
Adam Gundry's avatar
Adam Gundry committed
52
import FieldLabel
dterei's avatar
dterei committed
53
import NameSet
Adam Gundry's avatar
Adam Gundry committed
54
import CoAxiom ( BranchIndex )
Simon Marlow's avatar
Simon Marlow committed
55 56 57 58
import Name
import CostCentre
import Literal
import ForeignCall
59
import Annotations( AnnPayload, AnnTarget )
60
import BasicTypes
61
import Outputable
62
import Module
Peter Wortmann's avatar
Peter Wortmann committed
63
import SrcLoc
64 65
import Fingerprint
import Binary
66
import BooleanFormula ( BooleanFormula, pprBooleanFormula, isTrue )
67
import Var( VarBndr(..), binderVar )
68
import TyCon ( Role (..), Injectivity(..) )
69
import Util( dropList, filterByList )
70
import DataCon (SrcStrictness(..), SrcUnpackedness(..))
71
import Lexeme (isLexSym)
72

73
import Control.Monad
74
import System.IO.Unsafe
75

76 77
infixl 3 &&&

Austin Seipp's avatar
Austin Seipp committed
78 79 80
{-
************************************************************************
*                                                                      *
81
                    Declarations
Austin Seipp's avatar
Austin Seipp committed
82 83 84
*                                                                      *
************************************************************************
-}
85

86 87 88
-- | A binding top-level 'Name' in an interface file (e.g. the name of an
-- 'IfaceDecl').
type IfaceTopBndr = Name
Gabor Greif's avatar
Gabor Greif committed
89
  -- It's convenient to have a Name in the IfaceSyn, although in each
90
  -- case the namespace is implied by the context. However, having an
91 92 93 94
  -- Name makes things like ifaceDeclImplicitBndrs and ifaceDeclFingerprints
  -- very convenient. Moreover, having the key of the binder means that
  -- we can encode known-key things cleverly in the symbol table. See Note
  -- [Symbol table representation of Names]
95 96
  --
  -- We don't serialise the namespace onto the disk though; rather we
97 98
  -- drop it when serialising and add it back in when deserialising.

99 100 101 102 103 104 105 106 107 108
getIfaceTopBndr :: BinHandle -> IO IfaceTopBndr
getIfaceTopBndr bh = get bh

putIfaceTopBndr :: BinHandle -> IfaceTopBndr -> IO ()
putIfaceTopBndr bh name =
    case getUserData bh of
      UserData{ ud_put_binding_name = put_binding_name } ->
          --pprTrace "putIfaceTopBndr" (ppr name) $
          put_binding_name bh name

dterei's avatar
dterei committed
109
data IfaceDecl
110
  = IfaceId { ifName      :: IfaceTopBndr,
dterei's avatar
dterei committed
111 112 113 114
              ifType      :: IfaceType,
              ifIdDetails :: IfaceIdDetails,
              ifIdInfo    :: IfaceIdInfo }

115
  | IfaceData { ifName       :: IfaceTopBndr,   -- Type constructor
116 117
                ifBinders    :: [IfaceTyConBinder],
                ifResKind    :: IfaceType,      -- Result kind of type constructor
118
                ifCType      :: Maybe CType,    -- C type for CAPI FFI
119
                ifRoles      :: [Role],         -- Roles
dterei's avatar
dterei committed
120
                ifCtxt       :: IfaceContext,   -- The "stupid theta"
121
                ifCons       :: IfaceConDecls,  -- Includes new/data/data family info
dterei's avatar
dterei committed
122 123
                ifGadtSyntax :: Bool,           -- True <=> declared using
                                                -- GADT syntax
124 125
                ifParent     :: IfaceTyConParent -- The axiom, for a newtype,
                                                 -- or data/newtype family instance
126
    }
127

128 129
  | IfaceSynonym { ifName    :: IfaceTopBndr,      -- Type constructor
                   ifRoles   :: [Role],            -- Roles
130 131
                   ifBinders :: [IfaceTyConBinder],
                   ifResKind :: IfaceKind,         -- Kind of the *result*
132 133 134
                   ifSynRhs  :: IfaceType }

  | IfaceFamily  { ifName    :: IfaceTopBndr,      -- Type constructor
Jan Stolarek's avatar
Jan Stolarek committed
135 136 137
                   ifResVar  :: Maybe IfLclName,   -- Result variable name, used
                                                   -- only for pretty-printing
                                                   -- with --show-iface
138 139
                   ifBinders :: [IfaceTyConBinder],
                   ifResKind :: IfaceKind,         -- Kind of the *tycon*
Jan Stolarek's avatar
Jan Stolarek committed
140 141
                   ifFamFlav :: IfaceFamTyConFlav,
                   ifFamInj  :: Injectivity }      -- injectivity information
142

143
  | IfaceClass { ifName    :: IfaceTopBndr,             -- Name of the class TyCon
144
                 ifRoles   :: [Role],                   -- Roles
145
                 ifBinders :: [IfaceTyConBinder],
146 147
                 ifFDs     :: [FunDep IfLclName],       -- Functional dependencies
                 ifBody    :: IfaceClassBody            -- Methods, superclasses, ATs
148 149
    }

150
  | IfaceAxiom { ifName       :: IfaceTopBndr,        -- Axiom name
151
                 ifTyCon      :: IfaceTyCon,     -- LHS TyCon
152
                 ifRole       :: Role,           -- Role of axiom
153 154
                 ifAxBranches :: [IfaceAxBranch] -- Branches
    }
155

156
  | IfacePatSyn { ifName          :: IfaceTopBndr,           -- Name of the pattern synonym
cactus's avatar
cactus committed
157
                  ifPatIsInfix    :: Bool,
158 159
                  ifPatMatcher    :: (IfExtName, Bool),
                  ifPatBuilder    :: Maybe (IfExtName, Bool),
160 161
                  -- Everything below is redundant,
                  -- but needed to implement pprIfaceDecl
162 163
                  ifPatUnivBndrs  :: [IfaceForAllBndr],
                  ifPatExBndrs    :: [IfaceForAllBndr],
cactus's avatar
cactus committed
164 165
                  ifPatProvCtxt   :: IfaceContext,
                  ifPatReqCtxt    :: IfaceContext,
166
                  ifPatArgs       :: [IfaceType],
Matthew Pickering's avatar
Matthew Pickering committed
167 168
                  ifPatTy         :: IfaceType,
                  ifFieldLabels   :: [FieldLabel] }
cactus's avatar
cactus committed
169

170 171 172 173 174 175 176 177 178 179 180
-- See also 'ClassBody'
data IfaceClassBody
  -- Abstract classes don't specify their body; they only occur in @hs-boot@ and
  -- @hsig@ files.
  = IfAbstractClass
  | IfConcreteClass {
     ifClassCtxt :: IfaceContext,             -- Super classes
     ifATs       :: [IfaceAT],                -- Associated type families
     ifSigs      :: [IfaceClassOp],           -- Method signatures
     ifMinDef    :: BooleanFormula IfLclName  -- Minimal complete definition
    }
cactus's avatar
cactus committed
181

182 183
data IfaceTyConParent
  = IfNoParent
184 185 186 187 188
  | IfDataInstance
       IfExtName     -- Axiom name
       IfaceTyCon    -- Family TyCon (pretty-printing only, not used in TcIface)
                     -- see Note [Pretty printing via IfaceSyn] in PprTyThing
       IfaceAppArgs  -- Arguments of the family TyCon
189

190
data IfaceFamTyConFlav
191 192
  = IfaceDataFamilyTyCon                      -- Data family
  | IfaceOpenSynFamilyTyCon
193 194 195
  | IfaceClosedSynFamilyTyCon (Maybe (IfExtName, [IfaceAxBranch]))
    -- ^ Name of associated axiom and branches for pretty printing purposes,
    -- or 'Nothing' for an empty closed family without an axiom
196
    -- See Note [Pretty printing via IfaceSyn] in PprTyThing
197
  | IfaceAbstractClosedSynFamilyTyCon
198
  | IfaceBuiltInSynFamTyCon -- for pretty printing purposes only
199

200 201 202 203 204
data IfaceClassOp
  = IfaceClassOp IfaceTopBndr
                 IfaceType                         -- Class op type
                 (Maybe (DefMethSpec IfaceType))   -- Default method
                 -- The types of both the class op itself,
Gabor Greif's avatar
Gabor Greif committed
205
                 -- and the default method, are *not* quantified
206
                 -- over the class variables
207

208 209 210 211
data IfaceAT = IfaceAT  -- See Class.ClassATItem
                  IfaceDecl          -- The associated type declaration
                  (Maybe IfaceType)  -- Default associated type instance, if any

212

213
-- This is just like CoAxBranch
214 215
data IfaceAxBranch = IfaceAxBranch { ifaxbTyVars   :: [IfaceTvBndr]
                                   , ifaxbCoVars   :: [IfaceIdBndr]
216
                                   , ifaxbLHS      :: IfaceAppArgs
217 218 219
                                   , ifaxbRoles    :: [Role]
                                   , ifaxbRHS      :: IfaceType
                                   , ifaxbIncomps  :: [BranchIndex] }
220
                                     -- See Note [Storing compatibility] in CoAxiom
221

222
data IfaceConDecls
223
  = IfAbstractTyCon     -- c.f TyCon.AbstractTyCon
224 225
  | IfDataTyCon [IfaceConDecl] -- Data type decls
  | IfNewTyCon  IfaceConDecl   -- Newtype decls
Adam Gundry's avatar
Adam Gundry committed
226 227 228

-- For IfDataTyCon and IfNewTyCon we store:
--  * the data constructor(s);
229 230 231
-- The field labels are stored individually in the IfaceConDecl
-- (there is some redundancy here, because a field label may occur
-- in multiple IfaceConDecls and represent the same field label)
232

dterei's avatar
dterei committed
233
data IfaceConDecl
234
  = IfCon {
235
        ifConName    :: IfaceTopBndr,                -- Constructor name
dterei's avatar
dterei committed
236 237
        ifConWrapper :: Bool,                   -- True <=> has a wrapper
        ifConInfix   :: Bool,                   -- True <=> declared infix
238 239 240 241 242 243 244

        -- The universal type variables are precisely those
        -- of the type constructor of this data constructor
        -- This is *easy* to guarantee when creating the IfCon
        -- but it's not so easy for the original TyCon/DataCon
        -- So this guarantee holds for IfaceConDecl, but *not* for DataCon

Ningning Xie's avatar
Ningning Xie committed
245
        ifConExTCvs   :: [IfaceBndr],  -- Existential ty/covars
246 247 248
        ifConUserTvBinders :: [IfaceForAllBndr],
          -- The tyvars, in the order the user wrote them
          -- INVARIANT: the set of tyvars in ifConUserTvBinders is exactly the
Ningning Xie's avatar
Ningning Xie committed
249 250 251
          --            set of tyvars (*not* covars) of ifConExTCvs, unioned
          --            with the set of ifBinders (from the parent IfaceDecl)
          --            whose tyvars do not appear in ifConEqSpec
252
          -- See Note [DataCon user type variable binders] in DataCon
253 254 255
        ifConEqSpec  :: IfaceEqSpec,        -- Equality constraints
        ifConCtxt    :: IfaceContext,       -- Non-stupid context
        ifConArgTys  :: [IfaceType],        -- Arg types
256
        ifConFields  :: [FieldLabel],  -- ...ditto... (field labels)
257 258 259 260 261
        ifConStricts :: [IfaceBang],
          -- Empty (meaning all lazy),
          -- or 1-1 corresp with arg tys
          -- See Note [Bangs on imported data constructors] in MkId
        ifConSrcStricts :: [IfaceSrcBang] } -- empty meaning no src stricts
dterei's avatar
dterei committed
262

263
type IfaceEqSpec = [(IfLclName,IfaceType)]
264

265 266 267
-- | This corresponds to an HsImplBang; that is, the final
-- implementation decision about the data constructor arg
data IfaceBang
268 269
  = IfNoBang | IfStrict | IfUnpack | IfUnpackCo IfaceCoercion

270 271 272 273
-- | This corresponds to HsSrcBang
data IfaceSrcBang
  = IfSrcBang SrcUnpackedness SrcStrictness

274 275 276 277 278
data IfaceClsInst
  = IfaceClsInst { ifInstCls  :: IfExtName,                -- See comments with
                   ifInstTys  :: [Maybe IfaceTyCon],       -- the defn of ClsInst
                   ifDFun     :: IfExtName,                -- The dfun
                   ifOFlag    :: OverlapFlag,              -- Overlap flag
279
                   ifInstOrph :: IsOrphan }                -- See Note [Orphans] in InstEnv
dterei's avatar
dterei committed
280 281 282 283 284 285
        -- There's always a separate IfaceDecl for the DFun, which gives
        -- its IdInfo with its full type and version number.
        -- The instance declarations taken together have a version number,
        -- and we don't want that to wobble gratuitously
        -- If this instance decl is *used*, we'll record a usage on the dfun;
        -- and if the head does not change it won't be used if it wasn't before
286

287
-- The ifFamInstTys field of IfaceFamInst contains a list of the rough
288
-- match types
289
data IfaceFamInst
290
  = IfaceFamInst { ifFamInstFam      :: IfExtName            -- Family name
291
                 , ifFamInstTys      :: [Maybe IfaceTyCon]   -- See above
292
                 , ifFamInstAxiom    :: IfExtName            -- The axiom
293
                 , ifFamInstOrph     :: IsOrphan             -- Just like IfaceClsInst
dterei's avatar
dterei committed
294
                 }
295

296
data IfaceRule
dterei's avatar
dterei committed
297 298 299 300 301 302 303 304
  = IfaceRule {
        ifRuleName   :: RuleName,
        ifActivation :: Activation,
        ifRuleBndrs  :: [IfaceBndr],    -- Tyvars and term vars
        ifRuleHead   :: IfExtName,      -- Head of lhs
        ifRuleArgs   :: [IfaceExpr],    -- Args of LHS
        ifRuleRhs    :: IfaceExpr,
        ifRuleAuto   :: Bool,
305
        ifRuleOrph   :: IsOrphan   -- Just like IfaceClsInst
306 307
    }

308 309 310
data IfaceAnnotation
  = IfaceAnnotation {
        ifAnnotatedTarget :: IfaceAnnTarget,
311
        ifAnnotatedValue  :: AnnPayload
312 313 314 315
  }

type IfaceAnnTarget = AnnTarget OccName

316 317
data IfaceCompleteMatch = IfaceCompleteMatch [IfExtName] IfExtName

318 319 320 321
instance Outputable IfaceCompleteMatch where
  ppr (IfaceCompleteMatch cls ty) = text "COMPLETE" <> colon <+> ppr cls
                                                    <+> dcolon <+> ppr ty

322 323 324



325
-- Here's a tricky case:
326 327
--   * Compile with -O module A, and B which imports A.f
--   * Change function f in A, and recompile without -O
328
--   * When we read in old A.hi we read in its IdInfo (as a thunk)
dterei's avatar
dterei committed
329 330 331
--      (In earlier GHCs we used to drop IdInfo immediately on reading,
--       but we do not do that now.  Instead it's discarded when the
--       ModIface is read into the various decl pools.)
Gabor Greif's avatar
typo  
Gabor Greif committed
332
--   * The version comparison sees that new (=NoInfo) differs from old (=HasInfo *)
dterei's avatar
dterei committed
333
--      and so gives a new version.
334

335 336 337 338
data IfaceIdInfo
  = NoInfo                      -- When writing interface file without -O
  | HasInfo [IfaceInfoItem]     -- Has info, and here it is

339
data IfaceInfoItem
340 341 342 343 344
  = HsArity         Arity
  | HsStrictness    StrictSig
  | HsInline        InlinePragma
  | HsUnfold        Bool             -- True <=> isStrongLoopBreaker is true
                    IfaceUnfolding   -- See Note [Expose recursive functions]
345
  | HsNoCafRefs
Richard Eisenberg's avatar
Richard Eisenberg committed
346
  | HsLevity                         -- Present <=> never levity polymorphic
347

348 349 350
-- NB: Specialisations and rules come in separately and are
-- only later attached to the Id.  Partial reason: some are orphans.

dterei's avatar
dterei committed
351
data IfaceUnfolding
352
  = IfCoreUnfold Bool IfaceExpr -- True <=> INLINABLE, False <=> regular unfolding
353 354
                                -- Possibly could eliminate the Bool here, the information
                                -- is also in the InlinePragma.
355

dterei's avatar
dterei committed
356
  | IfCompulsory IfaceExpr      -- Only used for default methods, in fact
357

358
  | IfInlineRule Arity          -- INLINE pragmas
dterei's avatar
dterei committed
359 360 361
                 Bool           -- OK to inline even if *un*-saturated
                 Bool           -- OK to inline even if context is boring
                 IfaceExpr
362

363
  | IfDFunUnfold [IfaceBndr] [IfaceExpr]
364

365

366 367 368 369
-- We only serialise the IdDetails of top-level Ids, and even then
-- we only need a very limited selection.  Notably, none of the
-- implicit ones are needed here, because they are not put it
-- interface files
370

371 372
data IfaceIdDetails
  = IfVanillaId
Matthew Pickering's avatar
Matthew Pickering committed
373
  | IfRecSelId (Either IfaceTyCon IfaceDecl) Bool
374
  | IfDFunId
375

Austin Seipp's avatar
Austin Seipp committed
376
{-
377 378
Note [Versioning of instances]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
379
See [http://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/RecompilationAvoidance#Instances]
380

381

Austin Seipp's avatar
Austin Seipp committed
382 383
************************************************************************
*                                                                      *
384
                Functions over declarations
Austin Seipp's avatar
Austin Seipp committed
385 386 387
*                                                                      *
************************************************************************
-}
388 389

visibleIfConDecls :: IfaceConDecls -> [IfaceConDecl]
390
visibleIfConDecls IfAbstractTyCon  = []
391
visibleIfConDecls (IfDataTyCon cs) = cs
392
visibleIfConDecls (IfNewTyCon c)   = [c]
393

394
ifaceDeclImplicitBndrs :: IfaceDecl -> [OccName]
395 396 397
--  *Excludes* the 'main' name, but *includes* the implicitly-bound names
-- Deeply revolting, because it has to predict what gets bound,
-- especially the question of whether there's a wrapper for a datacon
398
-- See Note [Implicit TyThings] in HscTypes
399

400 401 402 403 404
-- N.B. the set of names returned here *must* match the set of
-- TyThings returned by HscTypes.implicitTyThings, in the sense that
-- TyThing.getOccName should define a bijection between the two lists.
-- This invariant is used in LoadIface.loadDecl (see note [Tricky iface loop])
-- The order of the list does not matter.
405

406
ifaceDeclImplicitBndrs (IfaceData {ifName = tc_name, ifCons = cons })
407
  = case cons of
408
      IfAbstractTyCon -> []
409 410
      IfNewTyCon  cd  -> mkNewTyCoOcc (occName tc_name) : ifaceConDeclImplicitBndrs cd
      IfDataTyCon cds -> concatMap ifaceConDeclImplicitBndrs cds
411

412 413 414 415 416 417 418 419 420
ifaceDeclImplicitBndrs (IfaceClass { ifBody = IfAbstractClass })
  = []

ifaceDeclImplicitBndrs (IfaceClass { ifName = cls_tc_name
                                   , ifBody = IfConcreteClass {
                                        ifClassCtxt = sc_ctxt,
                                        ifSigs      = sigs,
                                        ifATs       = ats
                                     }})
batterseapower's avatar
batterseapower committed
421
  = --   (possibly) newtype coercion
422 423 424 425 426 427
    co_occs ++
    --    data constructor (DataCon namespace)
    --    data worker (Id namespace)
    --    no wrapper (class dictionaries never have a wrapper)
    [dc_occ, dcww_occ] ++
    -- associated types
428
    [occName (ifName at) | IfaceAT at _ <- ats ] ++
429
    -- superclass selectors
batterseapower's avatar
batterseapower committed
430
    [mkSuperDictSelOcc n cls_tc_occ | n <- [1..n_ctxt]] ++
431
    -- operation selectors
432
    [occName op | IfaceClassOp op  _ _ <- sigs]
433
  where
434
    cls_tc_occ = occName cls_tc_name
435 436
    n_ctxt = length sc_ctxt
    n_sigs = length sigs
batterseapower's avatar
batterseapower committed
437
    co_occs | is_newtype = [mkNewTyCoOcc cls_tc_occ]
dterei's avatar
dterei committed
438
            | otherwise  = []
439
    dcww_occ = mkDataConWorkerOcc dc_occ
batterseapower's avatar
batterseapower committed
440
    dc_occ = mkClassDataConOcc cls_tc_occ
441
    is_newtype = n_sigs + n_ctxt == 1 -- Sigh (keep this synced with buildClass)
442

443
ifaceDeclImplicitBndrs _ = []
444

445
ifaceConDeclImplicitBndrs :: IfaceConDecl -> [OccName]
446 447
ifaceConDeclImplicitBndrs (IfCon {
        ifConWrapper = has_wrapper, ifConName = con_name })
448
  = [occName con_name, work_occ] ++ wrap_occs
449
  where
450
    con_occ = occName con_name
451 452 453 454
    work_occ  = mkDataConWorkerOcc con_occ                   -- Id namespace
    wrap_occs | has_wrapper = [mkDataConWrapperOcc con_occ]  -- Id namespace
              | otherwise   = []

455 456 457 458 459 460 461 462 463
-- -----------------------------------------------------------------------------
-- The fingerprints of an IfaceDecl

       -- We better give each name bound by the declaration a
       -- different fingerprint!  So we calculate the fingerprint of
       -- each binder by combining the fingerprint of the whole
       -- declaration with the name of the binder. (#5614, #7215)
ifaceDeclFingerprints :: Fingerprint -> IfaceDecl -> [(OccName,Fingerprint)]
ifaceDeclFingerprints hash decl
464
  = (getOccName decl, hash) :
465 466 467 468 469 470
    [ (occ, computeFingerprint' (hash,occ))
    | occ <- ifaceDeclImplicitBndrs decl ]
  where
     computeFingerprint' =
       unsafeDupablePerformIO
        . computeFingerprint (panic "ifaceDeclFingerprints")
471

Austin Seipp's avatar
Austin Seipp committed
472 473 474
{-
************************************************************************
*                                                                      *
475
                Expressions
Austin Seipp's avatar
Austin Seipp committed
476 477 478
*                                                                      *
************************************************************************
-}
479 480 481 482 483 484

data IfaceExpr
  = IfaceLcl    IfLclName
  | IfaceExt    IfExtName
  | IfaceType   IfaceType
  | IfaceCo     IfaceCoercion
485
  | IfaceTuple  TupleSort [IfaceExpr]   -- Saturated; type arguments omitted
486
  | IfaceLam    IfaceLamBndr IfaceExpr
487 488
  | IfaceApp    IfaceExpr IfaceExpr
  | IfaceCase   IfaceExpr IfLclName [IfaceAlt]
489
  | IfaceECase  IfaceExpr IfaceType     -- See Note [Empty case alternatives]
490
  | IfaceLet    IfaceBinding  IfaceExpr
491 492 493 494 495 496 497 498
  | IfaceCast   IfaceExpr IfaceCoercion
  | IfaceLit    Literal
  | IfaceFCall  ForeignCall IfaceType
  | IfaceTick   IfaceTickish IfaceExpr    -- from Tick tickish E

data IfaceTickish
  = IfaceHpcTick Module Int                -- from HpcTick x
  | IfaceSCC     CostCentre Bool Bool      -- from ProfNote
Peter Wortmann's avatar
Peter Wortmann committed
499
  | IfaceSource  RealSrcSpan String        -- from SourceNote
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
  -- no breakpoints: we never export these into interface files

type IfaceAlt = (IfaceConAlt, [IfLclName], IfaceExpr)
        -- Note: IfLclName, not IfaceBndr (and same with the case binder)
        -- We reconstruct the kind/type of the thing from the context
        -- thus saving bulk in interface files

data IfaceConAlt = IfaceDefault
                 | IfaceDataAlt IfExtName
                 | IfaceLitAlt Literal

data IfaceBinding
  = IfaceNonRec IfaceLetBndr IfaceExpr
  | IfaceRec    [(IfaceLetBndr, IfaceExpr)]

-- IfaceLetBndr is like IfaceIdBndr, but has IdInfo too
-- It's used for *non-top-level* let/rec binders
-- See Note [IdInfo on nested let-bindings]
lukemaurer's avatar
lukemaurer committed
518 519 520 521
data IfaceLetBndr = IfLetBndr IfLclName IfaceType IfaceIdInfo IfaceJoinInfo

data IfaceJoinInfo = IfaceNotJoinPoint
                   | IfaceJoinPoint JoinArity
522

Austin Seipp's avatar
Austin Seipp committed
523
{-
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
Note [Empty case alternatives]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In IfaceSyn an IfaceCase does not record the types of the alternatives,
unlike CorSyn Case.  But we need this type if the alternatives are empty.
Hence IfaceECase.  See Note [Empty case alternatives] in CoreSyn.

Note [Expose recursive functions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For supercompilation we want to put *all* unfoldings in the interface
file, even for functions that are recursive (or big).  So we need to
know when an unfolding belongs to a loop-breaker so that we can refrain
from inlining it (except during supercompilation).

Note [IdInfo on nested let-bindings]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Occasionally we want to preserve IdInfo on nested let bindings. The one
that came up was a NOINLINE pragma on a let-binding inside an INLINE
function.  The user (Duncan Coutts) really wanted the NOINLINE control
to cross the separate compilation boundary.

In general we retain all info that is left by CoreTidy.tidyLetBndr, since
that is what is seen by importing module with --make


Austin Seipp's avatar
Austin Seipp committed
548 549
************************************************************************
*                                                                      *
550
              Printing IfaceDecl
Austin Seipp's avatar
Austin Seipp committed
551 552 553
*                                                                      *
************************************************************************
-}
554 555 556 557 558 559

pprAxBranch :: SDoc -> IfaceAxBranch -> SDoc
-- The TyCon might be local (just an OccName), or this might
-- be a branch for an imported TyCon, so it would be an ExtName
-- So it's easier to take an SDoc here
pprAxBranch pp_tc (IfaceAxBranch { ifaxbTyVars = tvs
560 561 562 563
                                 , ifaxbLHS = pat_tys
                                 , ifaxbRHS = rhs
                                 , ifaxbIncomps = incomps })
  = hang ppr_binders 2 (hang pp_lhs 2 (equals <+> ppr rhs))
564 565 566
    $+$
    nest 2 maybe_incomps
  where
567 568
    -- See Note [Printing foralls in type family instances] in IfaceType
    ppr_binders = pprUserIfaceForAll $ map (mkIfaceForAllTvBndr Specified) tvs
569
    pp_lhs = hang pp_tc 2 (pprParendIfaceAppArgs pat_tys)
570
    maybe_incomps = ppUnless (null incomps) $ parens $
571
                    text "incompatible indices:" <+> ppr incomps
572 573 574 575

instance Outputable IfaceAnnotation where
  ppr (IfaceAnnotation target value) = ppr target <+> colon <+> ppr value

576 577 578
instance NamedThing IfaceClassOp where
  getName (IfaceClassOp n _ _) = n

579
instance HasOccName IfaceClassOp where
580 581 582 583
  occName = getOccName

instance NamedThing IfaceConDecl where
  getName = ifConName
584

585
instance HasOccName IfaceConDecl where
586 587 588 589
  occName = getOccName

instance NamedThing IfaceDecl where
  getName = ifName
590

591
instance HasOccName IfaceDecl where
592
  occName = getOccName
593

594
instance Outputable IfaceDecl where
595
  ppr = pprIfaceDecl showToIface
596

597 598 599 600 601 602 603 604 605
{-
Note [Minimal complete definition] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The minimal complete definition should only be included if a complete
class definition is shown. Since the minimal complete definition is
anonymous we can't reuse the same mechanism that is used for the
filtering of method signatures. Instead we just check if anything at all is
filtered and hide it in that case.
-}

606 607
data ShowSub
  = ShowSub
608 609 610 611 612 613
      { ss_how_much :: ShowHowMuch
      , ss_forall :: ShowForAllFlag }

-- See Note [Printing IfaceDecl binders]
-- The alternative pretty printer referred to in the note.
newtype AltPpr = AltPpr (Maybe (OccName -> SDoc))
614 615

data ShowHowMuch
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
  = ShowHeader AltPpr -- ^Header information only, not rhs
  | ShowSome [OccName] AltPpr
  -- ^ Show only some sub-components. Specifically,
  --
  -- [@[]@] Print all sub-components.
  -- [@(n:ns)@] Print sub-component @n@ with @ShowSub = ns@;
  -- elide other sub-components to @...@
  -- May 14: the list is max 1 element long at the moment
  | ShowIface
  -- ^Everything including GHC-internal information (used in --show-iface)

{-
Note [Printing IfaceDecl binders]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The binders in an IfaceDecl are just OccNames, so we don't know what module they
come from.  But when we pretty-print a TyThing by converting to an IfaceDecl
(see PprTyThing), the TyThing may come from some other module so we really need
the module qualifier.  We solve this by passing in a pretty-printer for the
binders.

When printing an interface file (--show-iface), we want to print
everything unqualified, so we can just print the OccName directly.
-}
639

640
instance Outputable ShowHowMuch where
641 642 643 644 645 646 647
  ppr (ShowHeader _)    = text "ShowHeader"
  ppr ShowIface         = text "ShowIface"
  ppr (ShowSome occs _) = text "ShowSome" <+> ppr occs

showToHeader :: ShowSub
showToHeader = ShowSub { ss_how_much = ShowHeader $ AltPpr Nothing
                       , ss_forall = ShowForAllWhen }
648

649 650 651
showToIface :: ShowSub
showToIface = ShowSub { ss_how_much = ShowIface
                      , ss_forall = ShowForAllWhen }
652 653 654

ppShowIface :: ShowSub -> SDoc -> SDoc
ppShowIface (ShowSub { ss_how_much = ShowIface }) doc = doc
655
ppShowIface _                                     _   = Outputable.empty
656

657 658
-- show if all sub-components or the complete interface is shown
ppShowAllSubs :: ShowSub -> SDoc -> SDoc -- Note [Minimal complete definition]
659 660 661
ppShowAllSubs (ShowSub { ss_how_much = ShowSome [] _ }) doc = doc
ppShowAllSubs (ShowSub { ss_how_much = ShowIface })     doc = doc
ppShowAllSubs _                                         _   = Outputable.empty
662

663
ppShowRhs :: ShowSub -> SDoc -> SDoc
664 665
ppShowRhs (ShowSub { ss_how_much = ShowHeader _ }) _   = Outputable.empty
ppShowRhs _                                        doc = doc
666 667

showSub :: HasOccName n => ShowSub -> n -> Bool
668 669
showSub (ShowSub { ss_how_much = ShowHeader _ })     _     = False
showSub (ShowSub { ss_how_much = ShowSome (n:_) _ }) thing = n == occName thing
670
showSub (ShowSub { ss_how_much = _ })              _     = True
671

672 673 674 675 676 677 678
ppr_trim :: [Maybe SDoc] -> [SDoc]
-- Collapse a group of Nothings to a single "..."
ppr_trim xs
  = snd (foldr go (False, []) xs)
  where
    go (Just doc) (_,     so_far) = (False, doc : so_far)
    go Nothing    (True,  so_far) = (True, so_far)
679
    go Nothing    (False, so_far) = (True, text "..." : so_far)
680 681 682 683 684

isIfaceDataInstance :: IfaceTyConParent -> Bool
isIfaceDataInstance IfNoParent = False
isIfaceDataInstance _          = True

685 686 687 688 689 690 691
pprClassRoles :: ShowSub -> IfaceTopBndr -> [IfaceTyConBinder] -> [Role] -> SDoc
pprClassRoles ss clas binders roles =
    pprRoles (== Nominal)
             (pprPrefixIfDeclBndr (ss_how_much ss) (occName clas))
             binders
             roles

692
pprIfaceDecl :: ShowSub -> IfaceDecl -> SDoc
693 694
-- NB: pprIfaceDecl is also used for pretty-printing TyThings in GHCi
--     See Note [Pretty-printing TyThings] in PprTyThing
695
pprIfaceDecl ss (IfaceData { ifName = tycon, ifCType = ctype,
Edward Z. Yang's avatar
Edward Z. Yang committed
696
                             ifCtxt = context, ifResKind = kind,
697
                             ifRoles = roles, ifCons = condecls,
Edward Z. Yang's avatar
Edward Z. Yang committed
698
                             ifParent = parent,
699
                             ifGadtSyntax = gadt,
700
                             ifBinders = binders })
701

702
  | gadt      = vcat [ pp_roles
Edward Z. Yang's avatar
Edward Z. Yang committed
703
                     , pp_nd <+> pp_lhs <+> pp_kind <+> pp_where
704 705 706
                     , nest 2 (vcat pp_cons)
                     , nest 2 $ ppShowIface ss pp_extra ]
  | otherwise = vcat [ pp_roles
Edward Z. Yang's avatar
Edward Z. Yang committed
707
                     , hang (pp_nd <+> pp_lhs <+> pp_kind) 2 (add_bars pp_cons)
708
                     , nest 2 $ ppShowIface ss pp_extra ]
709 710
  where
    is_data_instance = isIfaceDataInstance parent
711 712 713 714 715 716
    -- See Note [Printing foralls in type family instances] in IfaceType
    pp_data_inst_forall :: SDoc
    pp_data_inst_forall = pprUserIfaceForAll forall_bndrs

    forall_bndrs :: [IfaceForAllBndr]
    forall_bndrs = [Bndr (binderVar tc_bndr) Specified | tc_bndr <- binders]
717 718

    cons       = visibleIfConDecls condecls
719
    pp_where   = ppWhen (gadt && not (null cons)) $ text "where"
720
    pp_cons    = ppr_trim (map show_con cons) :: [SDoc]
Edward Z. Yang's avatar
Edward Z. Yang committed
721 722 723
    pp_kind
      | isIfaceLiftedTypeKind kind = empty
      | otherwise = dcolon <+> ppr kind
724 725

    pp_lhs = case parent of
726
               IfNoParent -> pprIfaceDeclHead context ss tycon binders Nothing
727 728 729
               IfDataInstance{}
                          -> text "instance" <+> pp_data_inst_forall
                                             <+> pprIfaceTyConParent parent
730 731

    pp_roles
732 733
      | is_data_instance = empty
      | otherwise        = pprRoles (== Representational)
734 735 736
                                    (pprPrefixIfDeclBndr
                                        (ss_how_much ss)
                                        (occName tycon))
737
                                    binders roles
738 739 740
            -- Don't display roles for data family instances (yet)
            -- See discussion on Trac #8672.

741
    add_bars []     = Outputable.empty
742
    add_bars (c:cs) = sep ((equals <+> c) : map (vbar <+>) cs)
743

744
    ok_con dc = showSub ss dc || any (showSub ss . flSelector) (ifConFields dc)
745 746

    show_con dc
747
      | ok_con dc = Just $ pprIfaceConDecl ss gadt tycon binders parent dc
748
      | otherwise = Nothing
749

750
    pp_nd = case condecls of
751
              IfAbstractTyCon{} -> text "data"
752 753
              IfDataTyCon{}     -> text "data"
              IfNewTyCon{}      -> text "newtype"
754

Edward Z. Yang's avatar
Edward Z. Yang committed
755
    pp_extra = vcat [pprCType ctype]
756

757
pprIfaceDecl ss (IfaceClass { ifName  = clas
758
                            , ifRoles = roles
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
                            , ifFDs    = fds
                            , ifBinders = binders
                            , ifBody = IfAbstractClass })
  = vcat [ pprClassRoles ss clas binders roles
         , text "class" <+> pprIfaceDeclHead [] ss clas binders Nothing
                                <+> pprFundeps fds ]

pprIfaceDecl ss (IfaceClass { ifName  = clas
                            , ifRoles = roles
                            , ifFDs    = fds
                            , ifBinders = binders
                            , ifBody = IfConcreteClass {
                                ifATs = ats,
                                ifSigs = sigs,
                                ifClassCtxt = context,
                                ifMinDef = minDef
                              }})
  = vcat [ pprClassRoles ss clas binders roles
777
         , text "class" <+> pprIfaceDeclHead context ss clas binders Nothing
778
                                <+> pprFundeps fds <+> pp_where
Edward Z. Yang's avatar
Edward Z. Yang committed
779
         , nest 2 (vcat [ vcat asocs, vcat dsigs
780
                        , ppShowAllSubs ss (pprMinDef minDef)])]
781
    where
782
      pp_where = ppShowRhs ss $ ppUnless (null sigs && null ats) (text "where")
783 784 785 786 787 788 789 790 791 792 793 794 795 796

      asocs = ppr_trim $ map maybeShowAssoc ats
      dsigs = ppr_trim $ map maybeShowSig sigs

      maybeShowAssoc :: IfaceAT -> Maybe SDoc
      maybeShowAssoc asc@(IfaceAT d _)
        | showSub ss d = Just $ pprIfaceAT ss asc
        | otherwise    = Nothing

      maybeShowSig :: IfaceClassOp -> Maybe SDoc
      maybeShowSig sg
        | showSub ss sg = Just $  pprIfaceClassOp ss sg
        | otherwise     = Nothing

797 798
      pprMinDef :: BooleanFormula IfLclName -> SDoc
      pprMinDef minDef = ppUnless (isTrue minDef) $ -- hide empty definitions
799
        text "{-# MINIMAL" <+>
800 801
        pprBooleanFormula
          (\_ def -> cparen (isLexSym def) (ppr def)) 0 minDef <+>
802
        text "#-}"
803

804
pprIfaceDecl ss (IfaceSynonym { ifName    = tc
805
                              , ifBinders = binders
806
                              , ifSynRhs  = mono_ty
807 808 809 810
                              , ifResKind = res_kind})
  = hang (text "type" <+> pprIfaceDeclHead [] ss tc binders Nothing <+> equals)
       2 (sep [ pprIfaceForAll tvs, pprIfaceContextArr theta, ppr tau
              , ppUnless (isIfaceLiftedTypeKind res_kind) (dcolon <+> ppr res_kind) ])
811
  where
812
    (tvs, theta, tau) = splitIfaceSigmaTy mono_ty
813

814 815 816
pprIfaceDecl ss (IfaceFamily { ifName = tycon
                             , ifFamFlav = rhs, ifBinders = binders
                             , ifResKind = res_kind
Jan Stolarek's avatar
Jan Stolarek committed
817
                             , ifResVar = res_var, ifFamInj = inj })
818
  | IfaceDataFamilyTyCon <- rhs
819
  = text "data family" <+> pprIfaceDeclHead [] ss tycon binders Nothing
820 821

  | otherwise
822 823 824
  = hang (text "type family"
            <+> pprIfaceDeclHead [] ss tycon binders (Just res_kind)
            <+> ppShowRhs ss (pp_where rhs))