IfaceSyn.hs 69.3 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,
13
        IfaceExpr(..), IfaceAlt, IfaceLetBndr(..),
dterei's avatar
dterei committed
14 15 16
        IfaceBinding(..), IfaceConAlt(..),
        IfaceIdInfo(..), IfaceIdDetails(..), IfaceUnfolding(..),
        IfaceInfoItem(..), IfaceRule(..), IfaceAnnotation(..), IfaceAnnTarget,
17
        IfaceClsInst(..), IfaceFamInst(..), IfaceTickish(..),
18 19 20
        IfaceBang(..),
        IfaceSrcBang(..), SrcUnpackedness(..), SrcStrictness(..),
        IfaceAxBranch(..),
21
        IfaceTyConParent(..),
22

dterei's avatar
dterei committed
23
        -- Misc
24
        ifaceDeclImplicitBndrs, visibleIfConDecls,
25
        ifaceDeclFingerprints,
26

27
        -- Free Names
28
        freeNamesIfDecl, freeNamesIfRule, freeNamesIfFamInst,
29

dterei's avatar
dterei committed
30
        -- Pretty printing
31 32 33
        pprIfaceExpr,
        pprIfaceDecl,
        ShowSub(..), ShowHowMuch(..)
34 35 36 37 38
    ) where

#include "HsVersions.h"

import IfaceType
39
import PprCore()            -- Printing DFunArgs
40
import Demand
Simon Marlow's avatar
Simon Marlow committed
41
import Class
dterei's avatar
dterei committed
42
import NameSet
43
import CoAxiom ( BranchIndex, Role )
Simon Marlow's avatar
Simon Marlow committed
44 45 46 47
import Name
import CostCentre
import Literal
import ForeignCall
48
import Annotations( AnnPayload, AnnTarget )
49
import BasicTypes
50 51
import Outputable
import FastString
52
import Module
Peter Wortmann's avatar
Peter Wortmann committed
53
import SrcLoc
54 55
import Fingerprint
import Binary
56
import BooleanFormula ( BooleanFormula )
57
import HsBinds
58 59 60
import TyCon (Role (..))
import StaticFlags (opt_PprStyle_Debug)
import Util( filterOut )
61
import InstEnv
62
import DataCon (SrcStrictness(..), SrcUnpackedness(..))
63

64
import Control.Monad
65
import System.IO.Unsafe
66
import Data.Maybe (isJust)
67

68 69
infixl 3 &&&

Austin Seipp's avatar
Austin Seipp committed
70 71 72
{-
************************************************************************
*                                                                      *
73
                    Declarations
Austin Seipp's avatar
Austin Seipp committed
74 75 76
*                                                                      *
************************************************************************
-}
77

78 79 80 81
type IfaceTopBndr = OccName
  -- It's convenient to have an OccName in the IfaceSyn, altough in each
  -- case the namespace is implied by the context. However, having an
  -- OccNames makes things like ifaceDeclImplicitBndrs and ifaceDeclFingerprints
82 83 84
  -- very convenient.
  --
  -- We don't serialise the namespace onto the disk though; rather we
85 86
  -- drop it when serialising and add it back in when deserialising.

dterei's avatar
dterei committed
87
data IfaceDecl
88
  = IfaceId { ifName      :: IfaceTopBndr,
dterei's avatar
dterei committed
89 90 91 92
              ifType      :: IfaceType,
              ifIdDetails :: IfaceIdDetails,
              ifIdInfo    :: IfaceIdInfo }

93
  | IfaceData { ifName       :: IfaceTopBndr,        -- Type constructor
94
                ifCType      :: Maybe CType,    -- C type for CAPI FFI
dterei's avatar
dterei committed
95
                ifTyVars     :: [IfaceTvBndr],  -- Type variables
96
                ifRoles      :: [Role],         -- Roles
dterei's avatar
dterei committed
97
                ifCtxt       :: IfaceContext,   -- The "stupid theta"
98
                ifCons       :: IfaceConDecls,  -- Includes new/data/data family info
dterei's avatar
dterei committed
99
                ifRec        :: RecFlag,        -- Recursive or not?
100
                ifPromotable :: Bool,           -- Promotable to kind level?
dterei's avatar
dterei committed
101 102
                ifGadtSyntax :: Bool,           -- True <=> declared using
                                                -- GADT syntax
103 104
                ifParent     :: IfaceTyConParent -- The axiom, for a newtype,
                                                 -- or data/newtype family instance
105
    }
106

107 108 109 110 111 112 113 114 115 116 117 118
  | IfaceSynonym { ifName    :: IfaceTopBndr,      -- Type constructor
                   ifTyVars  :: [IfaceTvBndr],     -- Type variables
                   ifRoles   :: [Role],            -- Roles
                   ifSynKind :: IfaceKind,         -- Kind of the *rhs* (not of
                                                   -- the tycon)
                   ifSynRhs  :: IfaceType }

  | IfaceFamily  { ifName    :: IfaceTopBndr,      -- Type constructor
                   ifTyVars  :: [IfaceTvBndr],     -- Type variables
                   ifFamKind :: IfaceKind,         -- Kind of the *rhs* (not of
                                                   -- the tycon)
                   ifFamFlav :: IfaceFamTyConFlav }
119

120
  | IfaceClass { ifCtxt    :: IfaceContext,             -- Superclasses
121 122 123 124
                 ifName    :: IfaceTopBndr,             -- Name of the class TyCon
                 ifTyVars  :: [IfaceTvBndr],            -- Type variables
                 ifRoles   :: [Role],                   -- Roles
                 ifFDs     :: [FunDep FastString],      -- Functional dependencies
125 126 127
                 ifATs     :: [IfaceAT],                -- Associated type families
                 ifSigs    :: [IfaceClassOp],           -- Method signatures
                 ifMinDef  :: BooleanFormula IfLclName, -- Minimal complete definition
128 129
                 ifRec     :: RecFlag                   -- Is newtype/datatype associated
                                                        --   with the class recursive?
130 131
    }

132
  | IfaceAxiom { ifName       :: IfaceTopBndr,        -- Axiom name
133
                 ifTyCon      :: IfaceTyCon,     -- LHS TyCon
134
                 ifRole       :: Role,           -- Role of axiom
135 136
                 ifAxBranches :: [IfaceAxBranch] -- Branches
    }
137

138
  | IfacePatSyn { ifName          :: IfaceTopBndr,           -- Name of the pattern synonym
Gergő Érdi's avatar
Gergő Érdi committed
139
                  ifPatIsInfix    :: Bool,
140 141
                  ifPatMatcher    :: (IfExtName, Bool),
                  ifPatBuilder    :: Maybe (IfExtName, Bool),
142 143
                  -- Everything below is redundant,
                  -- but needed to implement pprIfaceDecl
Gergő Érdi's avatar
Gergő Érdi committed
144 145 146 147
                  ifPatUnivTvs    :: [IfaceTvBndr],
                  ifPatExTvs      :: [IfaceTvBndr],
                  ifPatProvCtxt   :: IfaceContext,
                  ifPatReqCtxt    :: IfaceContext,
148
                  ifPatArgs       :: [IfaceType],
Gergő Érdi's avatar
Gergő Érdi committed
149 150 151
                  ifPatTy         :: IfaceType }


152 153 154 155 156
data IfaceTyConParent
  = IfNoParent
  | IfDataInstance IfExtName
                   IfaceTyCon
                   IfaceTcArgs
157

158
data IfaceFamTyConFlav
159
  = IfaceOpenSynFamilyTyCon
160 161 162
  | IfaceClosedSynFamilyTyCon (Maybe (IfExtName, [IfaceAxBranch]))
    -- ^ Name of associated axiom and branches for pretty printing purposes,
    -- or 'Nothing' for an empty closed family without an axiom
163
  | IfaceAbstractClosedSynFamilyTyCon
164
  | IfaceBuiltInSynFamTyCon -- for pretty printing purposes only
165

166
data IfaceClassOp = IfaceClassOp IfaceTopBndr DefMethSpec IfaceType
dterei's avatar
dterei committed
167 168 169
        -- Nothing    => no default method
        -- Just False => ordinary polymorphic default method
        -- Just True  => generic default method
170

171 172 173 174
data IfaceAT = IfaceAT  -- See Class.ClassATItem
                  IfaceDecl          -- The associated type declaration
                  (Maybe IfaceType)  -- Default associated type instance, if any

175

176
-- This is just like CoAxBranch
177
data IfaceAxBranch = IfaceAxBranch { ifaxbTyVars  :: [IfaceTvBndr]
178
                                   , ifaxbLHS     :: IfaceTcArgs
179
                                   , ifaxbRoles   :: [Role]
180 181 182
                                   , ifaxbRHS     :: IfaceType
                                   , ifaxbIncomps :: [BranchIndex] }
                                     -- See Note [Storing compatibility] in CoAxiom
183

184
data IfaceConDecls
185
  = IfAbstractTyCon Bool        -- c.f TyCon.AbstractTyCon
186 187 188
  | IfDataFamTyCon              -- Data family
  | IfDataTyCon [IfaceConDecl]  -- Data type decls
  | IfNewTyCon  IfaceConDecl    -- Newtype decls
189

dterei's avatar
dterei committed
190
data IfaceConDecl
191
  = IfCon {
192
        ifConOcc     :: IfaceTopBndr,                -- Constructor name
dterei's avatar
dterei committed
193 194
        ifConWrapper :: Bool,                   -- True <=> has a wrapper
        ifConInfix   :: Bool,                   -- True <=> declared infix
195 196 197 198 199 200 201

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

202 203 204 205 206 207 208 209 210 211
        ifConExTvs   :: [IfaceTvBndr],      -- Existential tyvars
        ifConEqSpec  :: IfaceEqSpec,        -- Equality constraints
        ifConCtxt    :: IfaceContext,       -- Non-stupid context
        ifConArgTys  :: [IfaceType],        -- Arg types
        ifConFields  :: [IfaceTopBndr],     -- ...ditto... (field labels)
        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
212

213
type IfaceEqSpec = [(IfLclName,IfaceType)]
214

215 216 217
-- | This corresponds to an HsImplBang; that is, the final
-- implementation decision about the data constructor arg
data IfaceBang
218 219
  = IfNoBang | IfStrict | IfUnpack | IfUnpackCo IfaceCoercion

220 221 222 223
-- | This corresponds to HsSrcBang
data IfaceSrcBang
  = IfSrcBang SrcUnpackedness SrcStrictness

224 225 226 227 228
data IfaceClsInst
  = IfaceClsInst { ifInstCls  :: IfExtName,                -- See comments with
                   ifInstTys  :: [Maybe IfaceTyCon],       -- the defn of ClsInst
                   ifDFun     :: IfExtName,                -- The dfun
                   ifOFlag    :: OverlapFlag,              -- Overlap flag
229
                   ifInstOrph :: IsOrphan }                -- See Note [Orphans] in InstEnv
dterei's avatar
dterei committed
230 231 232 233 234 235
        -- 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
236

237
-- The ifFamInstTys field of IfaceFamInst contains a list of the rough
238
-- match types
239
data IfaceFamInst
240
  = IfaceFamInst { ifFamInstFam      :: IfExtName            -- Family name
241
                 , ifFamInstTys      :: [Maybe IfaceTyCon]   -- See above
242
                 , ifFamInstAxiom    :: IfExtName            -- The axiom
243
                 , ifFamInstOrph     :: IsOrphan             -- Just like IfaceClsInst
dterei's avatar
dterei committed
244
                 }
245

246
data IfaceRule
dterei's avatar
dterei committed
247 248 249 250 251 252 253 254
  = 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,
255
        ifRuleOrph   :: IsOrphan   -- Just like IfaceClsInst
256 257
    }

258 259 260
data IfaceAnnotation
  = IfaceAnnotation {
        ifAnnotatedTarget :: IfaceAnnTarget,
261
        ifAnnotatedValue  :: AnnPayload
262 263 264 265
  }

type IfaceAnnTarget = AnnTarget OccName

266
-- Here's a tricky case:
267 268
--   * Compile with -O module A, and B which imports A.f
--   * Change function f in A, and recompile without -O
269
--   * When we read in old A.hi we read in its IdInfo (as a thunk)
dterei's avatar
dterei committed
270 271 272
--      (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
273
--   * The version comparison sees that new (=NoInfo) differs from old (=HasInfo *)
dterei's avatar
dterei committed
274
--      and so gives a new version.
275

276 277 278 279
data IfaceIdInfo
  = NoInfo                      -- When writing interface file without -O
  | HasInfo [IfaceInfoItem]     -- Has info, and here it is

280
data IfaceInfoItem
281 282 283 284 285
  = HsArity         Arity
  | HsStrictness    StrictSig
  | HsInline        InlinePragma
  | HsUnfold        Bool             -- True <=> isStrongLoopBreaker is true
                    IfaceUnfolding   -- See Note [Expose recursive functions]
286
  | HsNoCafRefs
287

288 289 290
-- 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
291
data IfaceUnfolding
292
  = IfCoreUnfold Bool IfaceExpr -- True <=> INLINABLE, False <=> regular unfolding
293 294
                                -- Possibly could eliminate the Bool here, the information
                                -- is also in the InlinePragma.
295

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

298
  | IfInlineRule Arity          -- INLINE pragmas
dterei's avatar
dterei committed
299 300 301
                 Bool           -- OK to inline even if *un*-saturated
                 Bool           -- OK to inline even if context is boring
                 IfaceExpr
302

303
  | IfDFunUnfold [IfaceBndr] [IfaceExpr]
304

305

306 307 308 309
-- 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
310

311 312 313
data IfaceIdDetails
  = IfVanillaId
  | IfRecSelId IfaceTyCon Bool
314
  | IfDFunId
315

Austin Seipp's avatar
Austin Seipp committed
316
{-
317 318
Note [Versioning of instances]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
319
See [http://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/RecompilationAvoidance#Instances]
320

321

Austin Seipp's avatar
Austin Seipp committed
322 323
************************************************************************
*                                                                      *
324
                Functions over declarations
Austin Seipp's avatar
Austin Seipp committed
325 326 327
*                                                                      *
************************************************************************
-}
328 329 330 331 332 333

visibleIfConDecls :: IfaceConDecls -> [IfaceConDecl]
visibleIfConDecls (IfAbstractTyCon {}) = []
visibleIfConDecls IfDataFamTyCon       = []
visibleIfConDecls (IfDataTyCon cs)     = cs
visibleIfConDecls (IfNewTyCon c)       = [c]
334

335
ifaceDeclImplicitBndrs :: IfaceDecl -> [OccName]
336 337 338
--  *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
339
-- See Note [Implicit TyThings] in HscTypes
340

341 342 343 344 345
-- 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.
346
ifaceDeclImplicitBndrs IfaceData {ifCons = IfAbstractTyCon {}}  = []
347 348

-- Newtype
349
ifaceDeclImplicitBndrs (IfaceData {ifName = tc_occ,
350
                              ifCons = IfNewTyCon (
351 352 353
                                        IfCon { ifConOcc = con_occ })})
  =   -- implicit newtype coercion
    (mkNewTyCoOcc tc_occ) : -- JPM: newtype coercions shouldn't be implicit
354
      -- data constructor and worker (newtypes don't have a wrapper)
355 356
    [con_occ, mkDataConWorkerOcc con_occ]

357

358 359 360 361 362
ifaceDeclImplicitBndrs (IfaceData {ifName = _tc_occ,
                              ifCons = IfDataTyCon cons })
  = -- for each data constructor in order,
    --    data constructor, worker, and (possibly) wrapper
    concatMap dc_occs cons
363 364
  where
    dc_occs con_decl
dterei's avatar
dterei committed
365 366 367 368 369 370 371 372 373
        | has_wrapper = [con_occ, work_occ, wrap_occ]
        | otherwise   = [con_occ, work_occ]
        where
          con_occ  = ifConOcc con_decl            -- DataCon namespace
          wrap_occ = mkDataConWrapperOcc con_occ  -- Id namespace
          work_occ = mkDataConWorkerOcc con_occ   -- Id namespace
          has_wrapper = ifConWrapper con_decl     -- This is the reason for
                                                  -- having the ifConWrapper field!

374
ifaceDeclImplicitBndrs (IfaceClass {ifCtxt = sc_ctxt, ifName = cls_tc_occ,
dterei's avatar
dterei committed
375
                               ifSigs = sigs, ifATs = ats })
batterseapower's avatar
batterseapower committed
376
  = --   (possibly) newtype coercion
377 378 379 380 381 382
    co_occs ++
    --    data constructor (DataCon namespace)
    --    data worker (Id namespace)
    --    no wrapper (class dictionaries never have a wrapper)
    [dc_occ, dcww_occ] ++
    -- associated types
383
    [ifName at | IfaceAT at _ <- ats ] ++
384
    -- superclass selectors
batterseapower's avatar
batterseapower committed
385
    [mkSuperDictSelOcc n cls_tc_occ | n <- [1..n_ctxt]] ++
386 387 388 389 390
    -- operation selectors
    [op | IfaceClassOp op  _ _ <- sigs]
  where
    n_ctxt = length sc_ctxt
    n_sigs = length sigs
batterseapower's avatar
batterseapower committed
391
    co_occs | is_newtype = [mkNewTyCoOcc cls_tc_occ]
dterei's avatar
dterei committed
392
            | otherwise  = []
393
    dcww_occ = mkDataConWorkerOcc dc_occ
batterseapower's avatar
batterseapower committed
394
    dc_occ = mkClassDataConOcc cls_tc_occ
dterei's avatar
dterei committed
395
    is_newtype = n_sigs + n_ctxt == 1 -- Sigh
396

397
ifaceDeclImplicitBndrs _ = []
398

399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
-- -----------------------------------------------------------------------------
-- 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
  = (ifName decl, hash) :
    [ (occ, computeFingerprint' (hash,occ))
    | occ <- ifaceDeclImplicitBndrs decl ]
  where
     computeFingerprint' =
       unsafeDupablePerformIO
        . computeFingerprint (panic "ifaceDeclFingerprints")
415

Austin Seipp's avatar
Austin Seipp committed
416 417 418
{-
************************************************************************
*                                                                      *
419
                Expressions
Austin Seipp's avatar
Austin Seipp committed
420 421 422
*                                                                      *
************************************************************************
-}
423 424 425 426 427 428

data IfaceExpr
  = IfaceLcl    IfLclName
  | IfaceExt    IfExtName
  | IfaceType   IfaceType
  | IfaceCo     IfaceCoercion
429
  | IfaceTuple  TupleSort [IfaceExpr]   -- Saturated; type arguments omitted
430
  | IfaceLam    IfaceLamBndr IfaceExpr
431 432
  | IfaceApp    IfaceExpr IfaceExpr
  | IfaceCase   IfaceExpr IfLclName [IfaceAlt]
433
  | IfaceECase  IfaceExpr IfaceType     -- See Note [Empty case alternatives]
434
  | IfaceLet    IfaceBinding  IfaceExpr
435 436 437 438 439 440 441 442
  | 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
443
  | IfaceSource  RealSrcSpan String        -- from SourceNote
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
  -- 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]
data IfaceLetBndr = IfLetBndr IfLclName IfaceType IfaceIdInfo

Austin Seipp's avatar
Austin Seipp committed
464
{-
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
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
489 490
************************************************************************
*                                                                      *
491
              Printing IfaceDecl
Austin Seipp's avatar
Austin Seipp committed
492 493 494
*                                                                      *
************************************************************************
-}
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517

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
                                  , ifaxbLHS = pat_tys
                                  , ifaxbRHS = rhs
                                  , ifaxbIncomps = incomps })
  = hang (pprUserIfaceForAll tvs)
       2 (hang pp_lhs 2 (equals <+> ppr rhs))
    $+$
    nest 2 maybe_incomps
  where
    pp_lhs = hang pp_tc 2 (pprParendIfaceTcArgs pat_tys)
    maybe_incomps = ppUnless (null incomps) $ parens $
                    ptext (sLit "incompatible indices:") <+> ppr incomps

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

instance HasOccName IfaceClassOp where
  occName (IfaceClassOp n _ _) = n
518

519 520
instance HasOccName IfaceConDecl where
  occName = ifConOcc
521

522 523 524
instance HasOccName IfaceDecl where
  occName = ifName

525
instance Outputable IfaceDecl where
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
  ppr = pprIfaceDecl showAll

data ShowSub
  = ShowSub
      { ss_ppr_bndr :: OccName -> SDoc  -- Pretty-printer for binders in IfaceDecl
                                        -- See Note [Printing IfaceDecl binders]
      , ss_how_much :: ShowHowMuch }

data ShowHowMuch
  = ShowHeader   -- Header information only, not rhs
  | ShowSome [OccName]    -- []     <=> 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)

showAll :: ShowSub
showAll = ShowSub { ss_how_much = ShowIface, ss_ppr_bndr = ppr }

ppShowIface :: ShowSub -> SDoc -> SDoc
ppShowIface (ShowSub { ss_how_much = ShowIface }) doc = doc
547
ppShowIface _                                     _   = Outputable.empty
548 549

ppShowRhs :: ShowSub -> SDoc -> SDoc
550
ppShowRhs (ShowSub { ss_how_much = ShowHeader }) _   = Outputable.empty
551 552 553 554 555 556
ppShowRhs _                                      doc = doc

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

Austin Seipp's avatar
Austin Seipp committed
558
{-
559 560 561 562 563 564 565
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.
566

567 568
When printing an interface file (--show-iface), we want to print
everything unqualified, so we can just print the OccName directly.
Austin Seipp's avatar
Austin Seipp committed
569
-}
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584

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)
    go Nothing    (False, so_far) = (True, ptext (sLit "...") : so_far)

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

pprIfaceDecl :: ShowSub -> IfaceDecl -> SDoc
585 586
-- NB: pprIfaceDecl is also used for pretty-printing TyThings in GHCi
--     See Note [Pretty-printing TyThings] in PprTyThing
587
pprIfaceDecl ss (IfaceData { ifName = tycon, ifCType = ctype,
588
                             ifCtxt = context, ifTyVars = tc_tyvars,
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
                             ifRoles = roles, ifCons = condecls,
                             ifParent = parent, ifRec = isrec,
                             ifGadtSyntax = gadt,
                             ifPromotable = is_prom })

  | gadt_style = vcat [ pp_roles
                      , pp_nd <+> pp_lhs <+> pp_where
                      , nest 2 (vcat pp_cons)
                      , nest 2 $ ppShowIface ss pp_extra ]
  | otherwise  = vcat [ pp_roles
                      , hang (pp_nd <+> pp_lhs) 2 (add_bars pp_cons)
                      , nest 2 $ ppShowIface ss pp_extra ]
  where
    is_data_instance = isIfaceDataInstance parent

    gadt_style = gadt || any (not . isVanillaIfaceConDecl) cons
    cons       = visibleIfConDecls condecls
    pp_where   = ppWhen (gadt_style && not (null cons)) $ ptext (sLit "where")
    pp_cons    = ppr_trim (map show_con cons) :: [SDoc]

    pp_lhs = case parent of
610
               IfNoParent -> pprIfaceDeclHead context ss tycon tc_tyvars
611 612 613
               _          -> ptext (sLit "instance") <+> pprIfaceTyConParent parent

    pp_roles
614
      | is_data_instance = Outputable.empty
615
      | otherwise        = pprRoles (== Representational) (pprPrefixIfDeclBndr ss tycon)
616
                                    tc_tyvars roles
617 618 619
            -- Don't display roles for data family instances (yet)
            -- See discussion on Trac #8672.

620
    add_bars []     = Outputable.empty
621 622 623 624 625 626 627
    add_bars (c:cs) = sep ((equals <+> c) : map (char '|' <+>) cs)

    ok_con dc = showSub ss dc || any (showSub ss) (ifConFields dc)

    show_con dc
      | ok_con dc = Just $ pprIfaceConDecl ss gadt_style mk_user_con_res_ty dc
      | otherwise = Nothing
628

629 630 631 632 633 634 635
    mk_user_con_res_ty :: IfaceEqSpec -> ([IfaceTvBndr], SDoc)
    -- See Note [Result type of a data family GADT]
    mk_user_con_res_ty eq_spec
      | IfDataInstance _ tc tys <- parent
      = (con_univ_tvs, pprIfaceType (IfaceTyConApp tc (substIfaceTcArgs gadt_subst tys)))
      | otherwise
      = (con_univ_tvs, sdocWithDynFlags (ppr_tc_app gadt_subst))
636
      where
637 638 639
        gadt_subst = mkFsEnv eq_spec
        done_univ_tv (tv,_) = isJust (lookupFsEnv gadt_subst tv)
        con_univ_tvs = filterOut done_univ_tv tc_tyvars
640

641 642 643 644
    ppr_tc_app gadt_subst dflags
       = pprPrefixIfDeclBndr ss tycon
         <+> sep [ pprParendIfaceType (substIfaceTyVar gadt_subst tv)
                 | (tv,_kind) <- stripIfaceKindVars dflags tc_tyvars ]
645 646 647 648 649 650

    pp_nd = case condecls of
              IfAbstractTyCon d -> ptext (sLit "abstract") <> ppShowIface ss (parens (ppr d))
              IfDataFamTyCon    -> ptext (sLit "data family")
              IfDataTyCon _     -> ptext (sLit "data")
              IfNewTyCon _      -> ptext (sLit "newtype")
651

652 653 654
    pp_extra = vcat [pprCType ctype, pprRec isrec, pp_prom]

    pp_prom | is_prom   = ptext (sLit "Promotable")
655
            | otherwise = Outputable.empty
656 657 658 659 660 661


pprIfaceDecl ss (IfaceClass { ifATs = ats, ifSigs = sigs, ifRec = isrec
                            , ifCtxt   = context, ifName  = clas
                            , ifTyVars = tyvars,  ifRoles = roles
                            , ifFDs    = fds })
662
  = vcat [ pprRoles (== Nominal) (pprPrefixIfDeclBndr ss clas) tyvars roles
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
         , ptext (sLit "class") <+> pprIfaceDeclHead context ss clas tyvars
                                <+> pprFundeps fds <+> pp_where
         , nest 2 (vcat [vcat asocs, vcat dsigs, pprec])]
    where
      pp_where = ppShowRhs ss $ ppUnless (null sigs && null ats) (ptext (sLit "where"))

      asocs = ppr_trim $ map maybeShowAssoc ats
      dsigs = ppr_trim $ map maybeShowSig sigs
      pprec = ppShowIface ss (pprRec isrec)

      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

683 684 685
pprIfaceDecl ss (IfaceSynonym { ifName   = tc
                              , ifTyVars = tv
                              , ifSynRhs = mono_ty })
686 687
  = hang (ptext (sLit "type") <+> pprIfaceDeclHead [] ss tc tv <+> equals)
       2 (sep [pprIfaceForAll tvs, pprIfaceContextArr theta, ppr tau])
688
  where
689
    (tvs, theta, tau) = splitIfaceSigmaTy mono_ty
690

691 692
pprIfaceDecl ss (IfaceFamily { ifName = tycon, ifTyVars = tyvars
                             , ifFamFlav = rhs, ifFamKind = kind })
693 694 695
  = vcat [ hang (text "type family" <+> pprIfaceDeclHead [] ss tycon tyvars <+> dcolon)
              2 (ppr kind <+> ppShowRhs ss (pp_rhs rhs))
         , ppShowRhs ss (nest 2 (pp_branches rhs)) ]
696
  where
697 698 699 700 701 702 703 704 705 706
    pp_rhs IfaceOpenSynFamilyTyCon
      = ppShowIface ss (ptext (sLit "open"))
    pp_rhs IfaceAbstractClosedSynFamilyTyCon
      = ppShowIface ss (ptext (sLit "closed, abstract"))
    pp_rhs (IfaceClosedSynFamilyTyCon _)
      = ptext (sLit "where")
    pp_rhs IfaceBuiltInSynFamTyCon
      = ppShowIface ss (ptext (sLit "built-in"))

    pp_branches (IfaceClosedSynFamilyTyCon (Just (ax, brs)))
707
      = vcat (map (pprAxBranch (pprPrefixIfDeclBndr ss tycon)) brs)
708
        $$ ppShowIface ss (ptext (sLit "axiom") <+> ppr ax)
709
    pp_branches _ = Outputable.empty
710

711
pprIfaceDecl _ (IfacePatSyn { ifName = name, ifPatBuilder = builder,
712
                              ifPatUnivTvs = univ_tvs, ifPatExTvs = ex_tvs,
713
                              ifPatProvCtxt = prov_ctxt, ifPatReqCtxt = req_ctxt,
714 715 716 717 718 719 720
                              ifPatArgs = arg_tys,
                              ifPatTy = pat_ty} )
  = pprPatSynSig name is_bidirectional
                 (pprUserIfaceForAll tvs)
                 (pprIfaceContextMaybe prov_ctxt)
                 (pprIfaceContextMaybe req_ctxt)
                 (pprIfaceType ty)
Gergő Érdi's avatar
Gergő Érdi committed
721
  where
722
    is_bidirectional = isJust builder
723 724
    tvs = univ_tvs ++ ex_tvs
    ty = foldr IfaceFunTy pat_ty arg_tys
Gergő Érdi's avatar
Gergő Érdi committed
725

726 727
pprIfaceDecl ss (IfaceId { ifName = var, ifType = ty,
                              ifIdDetails = details, ifIdInfo = info })
728
  = vcat [ hang (pprPrefixIfDeclBndr ss var <+> dcolon)
729 730
              2 (pprIfaceSigmaType ty)
         , ppShowIface ss (ppr details)
731
         , ppShowIface ss (ppr info) ]
732 733 734 735 736 737 738

pprIfaceDecl _ (IfaceAxiom { ifName = name, ifTyCon = tycon
                           , ifAxBranches = branches })
  = hang (ptext (sLit "axiom") <+> ppr name <> dcolon)
       2 (vcat $ map (pprAxBranch (ppr tycon)) branches)


739
pprCType :: Maybe CType -> SDoc
740
pprCType Nothing      = Outputable.empty
741 742
pprCType (Just cType) = ptext (sLit "C type:") <+> ppr cType

743 744 745 746 747 748 749 750
-- if, for each role, suppress_if role is True, then suppress the role
-- output
pprRoles :: (Role -> Bool) -> SDoc -> [IfaceTvBndr] -> [Role] -> SDoc
pprRoles suppress_if tyCon tyvars roles
  = sdocWithDynFlags $ \dflags ->
      let froles = suppressIfaceKinds dflags tyvars roles
      in ppUnless (all suppress_if roles || null froles) $
         ptext (sLit "type role") <+> tyCon <+> hsep (map ppr froles)
751

Ian Lynagh's avatar
Ian Lynagh committed
752
pprRec :: RecFlag -> SDoc
753
pprRec NonRecursive = Outputable.empty
754
pprRec Recursive    = ptext (sLit "RecFlag: Recursive")
Ian Lynagh's avatar
Ian Lynagh committed
755

756
pprInfixIfDeclBndr, pprPrefixIfDeclBndr :: ShowSub -> OccName -> SDoc
757
pprInfixIfDeclBndr (ShowSub { ss_ppr_bndr = ppr_bndr }) occ
758 759 760
  = pprInfixVar (isSymOcc occ) (ppr_bndr occ)
pprPrefixIfDeclBndr (ShowSub { ss_ppr_bndr = ppr_bndr }) occ
  = parenSymOcc occ (ppr_bndr occ)
761

762
instance Outputable IfaceClassOp where
763 764 765 766
   ppr = pprIfaceClassOp showAll

pprIfaceClassOp :: ShowSub -> IfaceClassOp -> SDoc
pprIfaceClassOp ss (IfaceClassOp n dm ty) = hang opHdr 2 (pprIfaceSigmaType ty)
767 768
  where opHdr = pprPrefixIfDeclBndr ss n
                <+> ppShowIface ss (ppr dm) <+> dcolon
769

770
instance Outputable IfaceAT where
771 772 773
   ppr = pprIfaceAT showAll

pprIfaceAT :: ShowSub -> IfaceAT -> SDoc
774
pprIfaceAT ss (IfaceAT d mb_def)
775
  = vcat [ pprIfaceDecl ss d
776
         , case mb_def of
777
              Nothing  -> Outputable.empty
778 779
              Just rhs -> nest 2 $
                          ptext (sLit "Default:") <+> ppr rhs ]
780 781 782 783 784 785

instance Outputable IfaceTyConParent where
  ppr p = pprIfaceTyConParent p

pprIfaceTyConParent :: IfaceTyConParent -> SDoc
pprIfaceTyConParent IfNoParent
786
  = Outputable.empty
787 788 789 790 791 792
pprIfaceTyConParent (IfDataInstance _ tc tys)
  = sdocWithDynFlags $ \dflags ->
    let ftys = stripKindArgs dflags tys
    in pprIfaceTypeApp tc ftys

pprIfaceDeclHead :: IfaceContext -> ShowSub -> OccName -> [IfaceTvBndr] -> SDoc
793
pprIfaceDeclHead context ss tc_occ tv_bndrs
794
  = sdocWithDynFlags $ \ dflags ->
795 796 797
    sep [ pprIfaceContextArr context
        , pprPrefixIfDeclBndr ss tc_occ
          <+> pprIfaceTvBndrs (stripIfaceKindVars dflags tv_bndrs) ]
798 799 800 801 802 803 804 805

isVanillaIfaceConDecl :: IfaceConDecl -> Bool
isVanillaIfaceConDecl (IfCon { ifConExTvs  = ex_tvs
                             , ifConEqSpec = eq_spec
                             , ifConCtxt   = ctxt })
  = (null ex_tvs) && (null eq_spec) && (null ctxt)

pprIfaceConDecl :: ShowSub -> Bool
806
                -> (IfaceEqSpec -> ([IfaceTvBndr], SDoc))
807 808 809
                -> IfaceConDecl -> SDoc
pprIfaceConDecl ss gadt_style mk_user_con_res_ty
        (IfCon { ifConOcc = name, ifConInfix = is_infix,
810
                 ifConExTvs = ex_tvs,
dterei's avatar
dterei committed
811
                 ifConEqSpec = eq_spec, ifConCtxt = ctxt, ifConArgTys = arg_tys,
812
                 ifConStricts = stricts, ifConFields = labels })
813
  | gadt_style = pp_prefix_con <+> dcolon <+> ppr_ty
814
  | otherwise  = ppr_fields tys_w_strs
815
  where
816 817
    tys_w_strs :: [(IfaceBang, IfaceType)]
    tys_w_strs = zip stricts arg_tys
818
    pp_prefix_con = pprPrefixIfDeclBndr ss name
819

820 821
    (univ_tvs, pp_res_ty) = mk_user_con_res_ty eq_spec
    ppr_ty = pprIfaceForAllPart (univ_tvs ++ ex_tvs) ctxt pp_tau
dterei's avatar
dterei committed
822 823 824

        -- A bit gruesome this, but we can't form the full con_tau, and ppr it,
        -- because we don't have a Name for the tycon, only an OccName
825
    pp_tau = case map pprParendIfaceType arg_tys ++ [pp_res_ty] of
dterei's avatar
dterei committed
826 827
                (t:ts) -> fsep (t : map (arrow <+>) ts)
                []     -> panic "pp_con_taus"
828

829 830 831 832 833 834 835 836 837 838
    ppr_bang IfNoBang = ppWhen opt_PprStyle_Debug $ char '_'
    ppr_bang IfStrict = char '!'
    ppr_bang IfUnpack = ptext (sLit "{-# UNPACK #-}")
    ppr_bang (IfUnpackCo co) = ptext (sLit "! {-# UNPACK #-}") <>
                               pprParendIfaceCoercion co

    pprParendBangTy (bang, ty) = ppr_bang bang <> pprParendIfaceType ty
    pprBangTy       (bang, ty) = ppr_bang bang <> ppr ty

    maybe_show_label (lbl,bty)
839
      | showSub ss lbl = Just (pprPrefixIfDeclBndr ss lbl <+> dcolon <+> pprBangTy bty)
840 841 842 843
      | otherwise      = Nothing

    ppr_fields [ty1, ty2]
      | is_infix && null labels
844
      = sep [pprParendBangTy ty1, pprInfixIfDeclBndr ss name, pprParendBangTy ty2]
845
    ppr_fields fields
846 847
      | null labels = pp_prefix_con <+> sep (map pprParendBangTy fields)
      | otherwise   = pp_prefix_con <+> (braces $ sep $ punctuate comma $ ppr_trim $
848
                                    map maybe_show_label (zip labels fields))
849

850
instance Outputable IfaceRule where
851
  ppr (IfaceRule { ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
dterei's avatar
dterei committed
852
                   ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs })
853
    = sep [hsep [pprRuleName name, ppr act,
dterei's avatar
dterei committed
854 855 856
                 ptext (sLit "forall") <+> pprIfaceBndrs bndrs],
           nest 2 (sep [ppr fn <+> sep (map pprParendIfaceExpr args),
                        ptext (sLit "=") <+> ppr rhs])
857 858
      ]

859
instance Outputable IfaceClsInst where
860 861
  ppr (IfaceClsInst { ifDFun = dfun_id, ifOFlag = flag
                    , ifInstCls = cls, ifInstTys = mb_tcs})
dterei's avatar
dterei committed
862 863
    = hang (ptext (sLit "instance") <+> ppr flag
                <+> ppr cls <+> brackets (pprWithCommas ppr_rough mb_tcs))
864
         2 (equals <+> ppr dfun_id)
865 866

instance Outputable IfaceFamInst where
867 868
  ppr (IfaceFamInst { ifFamInstFam = fam, ifFamInstTys = mb_tcs
                    , ifFamInstAxiom = tycon_ax})
dterei's avatar
dterei committed
869
    = hang (ptext (sLit "family instance") <+>
870
            ppr fam <+> pprWithCommas (brackets . ppr_rough) mb_tcs)
871
         2 (equals <+> ppr tycon_ax)
872 873 874 875

ppr_rough :: Maybe IfaceTyCon -> SDoc
ppr_rough Nothing   = dot
ppr_rough (Just tc) = ppr tc