summaryrefslogtreecommitdiff
path: root/compiler/GHC/Unit/Module/ModIface.hs
blob: 9a748c9ea0bfe368ada0f9282154b2ac9cb2c65f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
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
489
490
491
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
518
519
520
521
522
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeFamilyDependencies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE NamedFieldPuns #-}

module GHC.Unit.Module.ModIface
   ( ModIface
   , ModIface_ (..)
   , PartialModIface
   , ModIfaceBackend (..)
   , ModIfaceSelfRecompBackend (..)
   , ModIfaceSelfRecomp (..)
   , isSelfRecompilationInterface
   , IfaceDeclExts
   , IfaceBackendExts
   , IfaceExport
   , WhetherHasOrphans
   , WhetherHasFamInst
   , mi_boot
   , mi_fix
   , mi_semantic_module
   , mi_free_holes
   , mi_mnwib
   , mi_flag_hash
   , mi_iface_hash
   , mi_opt_hash
   , mi_hpc_hash
   , mi_plugin_hash
   , mi_usages
   , mi_src_hash
   , renameFreeHoles
   , emptyPartialModIface
   , emptyFullModIface
   , mkIfaceHashCache
   , emptyIfaceHashCache
   , forceModIface
   )
where

import GHC.Prelude

import GHC.Hs

import GHC.Iface.Syntax
import GHC.Iface.Ext.Fields

import GHC.Unit
import GHC.Unit.Module.Deps
import GHC.Unit.Module.Warnings

import GHC.Types.Avail
import GHC.Types.Fixity
import GHC.Types.Fixity.Env
import GHC.Types.HpcInfo
import GHC.Types.Name
import GHC.Types.Name.Reader
import GHC.Types.SafeHaskell
import GHC.Types.SourceFile
import GHC.Types.Unique.DSet
import GHC.Types.Unique.FM

import GHC.Data.Maybe

import GHC.Utils.Fingerprint
import GHC.Utils.Binary

import Control.DeepSeq
import Control.Exception
import GHC.Utils.Panic
import GHC.Utils.Outputable
import GHC.Utils.Misc

{- Note [Interface file stages]
   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Interface files have two possible stages.

* A partial stage built from the result of the core pipeline.
* A fully instantiated form. Which also includes fingerprints and
  potentially information provided by backends.

We can build a full interface file two ways:
* Directly from a partial one:
  Then we omit backend information and mostly compute fingerprints.
* From a partial one + information produced by a backend.
  Then we store the provided information and fingerprint both.
-}

type PartialModIface = ModIface_ 'ModIfaceCore
type ModIface = ModIface_ 'ModIfaceFinal

-- | Extends a PartialModIface with information which is either:
-- * Computed after codegen
-- * Or computed just before writing the iface to disk. (Hashes)
-- In order to fully instantiate it.
data ModIfaceBackend = ModIfaceBackend
  { mi_mod_hash :: !Fingerprint
    -- ^ Hash of the ABI only
  , mi_self_recomp_backend_info :: !ModIfaceSelfRecompBackend
    -- ^ Information needed for checking self-recompilation.
    -- See Note [Self recompilation information in interface files]
  , mi_orphan :: !WhetherHasOrphans
    -- ^ Whether this module has orphans
  , mi_finsts :: !WhetherHasFamInst
    -- ^ Whether this module has family instances. See Note [The type family
    -- instance consistency story].
  , mi_exp_hash :: !Fingerprint
    -- ^ Hash of export list
  , mi_orphan_hash :: !Fingerprint
    -- ^ Hash for orphan rules, class and family instances combined

    -- Cached environments for easy lookup. These are computed (lazily) from
    -- other fields and are not put into the interface file.
    -- Not really produced by the backend but there is no need to create them
    -- any earlier.
  , mi_warn_fn :: !(OccName -> Maybe (WarningTxt GhcRn))
    -- ^ Cached lookup for 'mi_warns'
  , mi_fix_fn :: !(OccName -> Maybe Fixity)
    -- ^ Cached lookup for 'mi_fixities'
  , mi_hash_fn :: !(OccName -> Maybe (OccName, Fingerprint))
    -- ^ Cached lookup for 'mi_decls'. The @Nothing@ in 'mi_hash_fn' means that
    -- the thing isn't in decls. It's useful to know that when seeing if we are
    -- up to date wrt. the old interface. The 'OccName' is the parent of the
    -- name, if it has one.
  }

data ModIfacePhase
  = ModIfaceCore
  -- ^ Partial interface built based on output of core pipeline.
  | ModIfaceFinal

-- | Selects a IfaceDecl representation.
-- For fully instantiated interfaces we also maintain
-- a fingerprint, which is used for recompilation checks.
type family IfaceDeclExts (phase :: ModIfacePhase) = decl | decl -> phase where
  IfaceDeclExts 'ModIfaceCore = IfaceDecl
  IfaceDeclExts 'ModIfaceFinal = (Fingerprint, IfaceDecl)

type family IfaceBackendExts (phase :: ModIfacePhase) = bk | bk -> phase where
  IfaceBackendExts 'ModIfaceCore = ()
  IfaceBackendExts 'ModIfaceFinal = ModIfaceBackend

-- | The information for a module which is only used when deciding whether to recompile
-- itself. In particular the external interface of a module is recorded by the ABI
-- hash
data ModIfaceSelfRecompBackend = NoSelfRecompBackend | ModIfaceSelfRecompBackend {
    mi_sr_flag_hash :: !Fingerprint
    -- ^ Hash of the important flags used when compiling the module, excluding
    -- optimisation flags
  , mi_sr_iface_hash :: !Fingerprint
    -- ^ Hash of the whole interface
  , mi_sr_opt_hash :: !Fingerprint
    -- ^ Hash of optimisation flags
  , mi_sr_hpc_hash :: !Fingerprint
    -- ^ Hash of hpc flags
  , mi_sr_plugin_hash :: !Fingerprint
    -- ^ Hash of plugins
}
withSelfRecompBackend :: HasCallStack => (ModIfaceSelfRecompBackend-> t) -> ModIfaceBackend-> t

withSelfRecompBackend f mi =
  case mi_self_recomp_backend_info mi of
    NoSelfRecompBackend -> panic "Trying to use self-recomp info"
    x -> f x

mi_flag_hash :: HasCallStack => ModIfaceBackend -> Fingerprint
mi_flag_hash = withSelfRecompBackend mi_sr_flag_hash
mi_iface_hash :: HasCallStack => ModIfaceBackend -> Fingerprint
mi_iface_hash = withSelfRecompBackend mi_sr_iface_hash
mi_opt_hash :: HasCallStack => ModIfaceBackend -> Fingerprint
mi_opt_hash   = withSelfRecompBackend mi_sr_opt_hash
mi_hpc_hash :: HasCallStack => ModIfaceBackend -> Fingerprint
mi_hpc_hash   = withSelfRecompBackend mi_sr_hpc_hash
mi_plugin_hash :: HasCallStack => ModIfaceBackend -> Fingerprint
mi_plugin_hash = withSelfRecompBackend mi_sr_plugin_hash

isSelfRecompilationInterface :: ModIface -> Bool
isSelfRecompilationInterface iface =
  case mi_self_recomp_info iface of
    NoSelfRecomp -> False
    ModIfaceSelfRecomp {} -> True

{-
Note [Self recompilation information in interface files]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The flag -fwrite-self-recomp-info controls whether
interface files contain the information necessary to answer the
question:

  Do I need to recompile myself or is this current interface file
  suitable?

Why? Most packages are only built once either by a distribution or cabal
and then placed into an immutable store, after which we will never ask
this question. Therefore we can derive two benefits from omitting this
information.

* Primary motivation: It vastly reduces the surface area for creating
  non-deterministic interface files. See issue #10424 which motivated a
  proper fix to that issue. Distributions have long contained versions
  of GHC which just have broken self-recompilation checking (in order to
  get deterministic interface files).

* Secondary motivation: This reduces the size of interface files
  slightly.. the `mi_usages` field can be quite big but probably this
  isn't such a great benefit.

* Third motivation: Conceptually clarity about which parts of an
  interface file are used in order to **communicate** with subsequent
  packages about the **interface** for a module. And which parts are
  used to self-communicate during recompilation checking.

The main tracking issue is #22188 but fixes issues such as #10424 in a
proper way.

-}


-- | A 'ModIface' plus a 'ModDetails' summarises everything we know
-- about a compiled module.  The 'ModIface' is the stuff *before* linking,
-- and can be written out to an interface file. The 'ModDetails is after
-- linking and can be completely recovered from just the 'ModIface'.
--
-- When we read an interface file, we also construct a 'ModIface' from it,
-- except that we explicitly make the 'mi_decls' and a few other fields empty;
-- as when reading we consolidate the declarations etc. into a number of indexed
-- maps and environments in the 'ExternalPackageState'.
--
-- See Note [Strictness in ModIface] to learn about why some fields are
-- strict and others are not.
data ModIface_ (phase :: ModIfacePhase)
  = ModIface {
        mi_module     :: !Module,             -- ^ Name of the module we are for
        mi_sig_of     :: !(Maybe Module),     -- ^ Are we a sig of another mod?

        mi_hsc_src    :: !HscSource,          -- ^ Boot? Signature?

        mi_deps     :: Dependencies,
                -- ^ The dependencies of the module.  This is
                -- consulted for directly-imported modules, but not
                -- for anything else (hence lazy)


        mi_exports  :: ![IfaceExport],
                -- ^ Exports
                -- Kept sorted by (mod,occ), to make version comparisons easier
                -- Records the modules that are the declaration points for things
                -- exported by this module, and the 'OccName's of those things


        mi_used_th  :: !Bool,
                -- ^ Module required TH splices when it was compiled.
                -- This disables recompilation avoidance (see #481).

        mi_fixities :: [(OccName,Fixity)],
                -- ^ Fixities
                -- NOT STRICT!  we read this field lazily from the interface file

        mi_warns    :: (Warnings GhcRn),
                -- ^ Warnings
                -- NOT STRICT!  we read this field lazily from the interface file

        mi_anns     :: [IfaceAnnotation],
                -- ^ Annotations
                -- NOT STRICT!  we read this field lazily from the interface file


        mi_decls    :: [IfaceDeclExts phase],
                -- ^ Type, class and variable declarations
                -- The hash of an Id changes if its fixity or deprecations change
                --      (as well as its type of course)
                -- Ditto data constructors, class operations, except that
                -- the hash of the parent class/tycon changes

        mi_extra_decls :: Maybe [IfaceBindingX IfaceMaybeRhs IfaceTopBndrInfo],
                -- ^ Extra variable definitions which are **NOT** exposed but when
                -- combined with mi_decls allows us to restart code generation.
                -- See Note [Interface Files with Core Definitions] and Note [Interface File with Core: Sharing RHSs]

        mi_globals  :: !(Maybe GlobalRdrEnv),
                -- ^ Binds all the things defined at the top level in
                -- the /original source/ code for this module. which
                -- is NOT the same as mi_exports, nor mi_decls (which
                -- may contains declarations for things not actually
                -- defined by the user).  Used for GHCi and for inspecting
                -- the contents of modules via the GHC API only.
                --
                -- (We need the source file to figure out the
                -- top-level environment, if we didn't compile this module
                -- from source then this field contains @Nothing@).
                --
                -- Strictly speaking this field should live in the
                -- 'HomeModInfo', but that leads to more plumbing.

                -- Instance declarations and rules
        mi_insts       :: [IfaceClsInst],     -- ^ Sorted class instance
        mi_fam_insts   :: [IfaceFamInst],  -- ^ Sorted family instances
        mi_rules       :: [IfaceRule],     -- ^ Sorted rules

        mi_hpc       :: !AnyHpcUsage,
                -- ^ True if this program uses Hpc at any point in the program.

        mi_trust     :: !IfaceTrustInfo,
                -- ^ Safe Haskell Trust information for this module.

        mi_trust_pkg :: !Bool,
                -- ^ Do we require the package this module resides in be trusted
                -- to trust this module? This is used for the situation where a
                -- module is Safe (so doesn't require the package be trusted
                -- itself) but imports some trustworthy modules from its own
                -- package (which does require its own package be trusted).
                -- See Note [Trust Own Package] in GHC.Rename.Names
        mi_complete_matches :: ![IfaceCompleteMatch],

        mi_docs :: Maybe Docs,
                -- ^ Docstrings and related data for use by haddock, the ghci
                -- @:doc@ command, and other tools.
                --
                -- @Just _@ @<=>@ the module was built with @-haddock@.

        mi_final_exts :: !(IfaceBackendExts phase),
                -- ^ Either `()` or `ModIfaceBackend` for
                -- a fully instantiated interface.

        mi_ext_fields :: !ExtensibleFields,
                -- ^ Additional optional fields, where the Map key represents
                -- the field name, resulting in a (size, serialized data) pair.
                -- Because the data is intended to be serialized through the
                -- internal `Binary` class (increasing compatibility with types
                -- using `Name` and `FastString`, such as HIE), this format is
                -- chosen over `ByteString`s.
                --

        mi_self_recomp_info :: !ModIfaceSelfRecomp
                -- ^ Information needed for checking self-recompilation.
                -- See Note [Self recompilation information in interface files]
     }

data ModIfaceSelfRecomp = NoSelfRecomp
  | ModIfaceSelfRecomp { mi_sr_src_hash :: !Fingerprint
                       -- ^ Hash of the .hs source, used for recompilation checking.
                       , mi_sr_usages   :: [Usage]
                       -- ^ Usages; kept sorted so that it's easy to decide
                       -- whether to write a new iface file (changing usages
                       -- doesn't affect the hash of this module)
                       -- NOT STRICT!  we read this field lazily from the interface file
                       -- It is *only* consulted by the recompilation checker
                       }

instance Outputable ModIfaceSelfRecomp where
  ppr NoSelfRecomp = text "NoSelfRecomp"
  ppr (ModIfaceSelfRecomp{mi_sr_src_hash, mi_sr_usages}) = vcat [text "Self-Recomp"
                                                                , nest 2 (vcat [text "src hash:" <+> ppr mi_sr_src_hash
                                                                , text "usages:" <+> ppr (length mi_sr_usages)])]

withSelfRecomp :: HasCallStack => (ModIfaceSelfRecomp-> t) -> ModIface_ phase -> t
withSelfRecomp f mi =
  case mi_self_recomp_info mi of
    NoSelfRecomp -> panic "Trying to use self-recomp info"
    x -> f x

mi_usages :: HasCallStack => ModIface_ phase -> [Usage]
mi_usages = withSelfRecomp mi_sr_usages
mi_src_hash :: HasCallStack => ModIface_ phase -> Fingerprint
mi_src_hash = withSelfRecomp mi_sr_src_hash


{-
Note [Strictness in ModIface]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The ModIface is the Haskell representation of an interface (.hi) file.

* During compilation we write out ModIface values to disk for files
  that we have just compiled
* For packages that we depend on we load the ModIface from disk.

Some fields in the ModIface are deliberately lazy because when we read
an interface file we don't always need all the parts. For example, an
interface file contains information about documentation which is often
not needed during compilation. This is achieved using the lazyPut/lazyGet pair.
If the field was strict then we would pointlessly load this information into memory.

On the other hand, if we create a ModIface but **don't** write it to
disk then to avoid space leaks we need to make sure to deepseq all these lazy fields
because the ModIface might live for a long time (for instance in a GHCi session).
That's why in GHC.Driver.Main.hscMaybeWriteIface there is the call to
forceModIface.
-}

-- | Old-style accessor for whether or not the ModIface came from an hs-boot
-- file.
mi_boot :: ModIface -> IsBootInterface
mi_boot iface = if mi_hsc_src iface == HsBootFile
    then IsBoot
    else NotBoot

mi_mnwib :: ModIface -> ModuleNameWithIsBoot
mi_mnwib iface = GWIB (moduleName $ mi_module iface) (mi_boot iface)

-- | Lookups up a (possibly cached) fixity from a 'ModIface'. If one cannot be
-- found, 'defaultFixity' is returned instead.
mi_fix :: ModIface -> OccName -> Fixity
mi_fix iface name = mi_fix_fn (mi_final_exts iface) name `orElse` defaultFixity

-- | The semantic module for this interface; e.g., if it's a interface
-- for a signature, if 'mi_module' is @p[A=<A>]:A@, 'mi_semantic_module'
-- will be @<A>@.
mi_semantic_module :: ModIface_ a -> Module
mi_semantic_module iface = case mi_sig_of iface of
                            Nothing -> mi_module iface
                            Just mod -> mod

-- | The "precise" free holes, e.g., the signatures that this
-- 'ModIface' depends on.
mi_free_holes :: ModIface -> UniqDSet ModuleName
mi_free_holes iface =
  case getModuleInstantiation (mi_module iface) of
    (_, Just indef)
        -- A mini-hack: we rely on the fact that 'renameFreeHoles'
        -- drops things that aren't holes.
        -> renameFreeHoles (mkUniqDSet cands) (instUnitInsts (moduleUnit indef))
    _   -> emptyUniqDSet
  where
    cands = dep_sig_mods $ mi_deps iface

-- | Given a set of free holes, and a unit identifier, rename
-- the free holes according to the instantiation of the unit
-- identifier.  For example, if we have A and B free, and
-- our unit identity is @p[A=<C>,B=impl:B]@, the renamed free
-- holes are just C.
renameFreeHoles :: UniqDSet ModuleName -> [(ModuleName, Module)] -> UniqDSet ModuleName
renameFreeHoles fhs insts =
    unionManyUniqDSets (map lookup_impl (uniqDSetToList fhs))
  where
    hmap = listToUFM insts
    lookup_impl mod_name
        | Just mod <- lookupUFM hmap mod_name = moduleFreeHoles mod
        -- It wasn't actually a hole
        | otherwise                           = emptyUniqDSet

instance Binary ModIfaceSelfRecompBackend where
  put_ bh NoSelfRecompBackend = put_ bh (0 :: Int)
  put_ bh (ModIfaceSelfRecompBackend {mi_sr_flag_hash, mi_sr_iface_hash, mi_sr_plugin_hash, mi_sr_opt_hash, mi_sr_hpc_hash}) = do
    put_ bh (1 :: Int)
    put_ bh mi_sr_flag_hash
    put_ bh mi_sr_iface_hash
    put_ bh mi_sr_plugin_hash
    put_ bh mi_sr_opt_hash
    put_ bh mi_sr_hpc_hash

  get bh = do
    (tag :: Int) <- get bh
    case tag of
      0 -> return NoSelfRecompBackend
      1 -> do
        mi_sr_flag_hash <- get bh
        mi_sr_iface_hash <- get bh
        mi_sr_plugin_hash <- get bh
        mi_sr_opt_hash <- get bh
        mi_sr_hpc_hash <- get bh
        return (ModIfaceSelfRecompBackend {mi_sr_flag_hash, mi_sr_iface_hash, mi_sr_plugin_hash, mi_sr_opt_hash, mi_sr_hpc_hash})
      x -> pprPanic "get_ModIfaceSelfRecomp" (ppr x)

instance Binary ModIfaceSelfRecomp where
  put_ bh NoSelfRecomp = put_ bh (0 :: Int)
  put_ bh (ModIfaceSelfRecomp{mi_sr_src_hash, mi_sr_usages}) = do
    put_ bh (1 :: Int)
    put_ bh mi_sr_src_hash
    lazyPut bh mi_sr_usages

  get bh = do
    (tag :: Int) <- get bh
    case tag of
      0 -> return NoSelfRecomp
      1 -> do
        src_hash    <- get bh
        usages      <- {-# SCC "bin_usages" #-} lazyGet bh
        return $ ModIfaceSelfRecomp { mi_sr_src_hash = src_hash, mi_sr_usages = usages }
      x -> pprPanic "get_ModIfaceSelfRecomp" (ppr x)

-- See Note [Strictness in ModIface] about where we use lazyPut vs put
instance Binary ModIface where
   put_ bh (ModIface {
                 mi_module    = mod,
                 mi_sig_of    = sig_of,
                 mi_hsc_src   = hsc_src,
                 mi_deps      = deps,
                 mi_exports   = exports,
                 mi_used_th   = used_th,
                 mi_fixities  = fixities,
                 mi_warns     = warns,
                 mi_anns      = anns,
                 mi_decls     = decls,
                 mi_extra_decls = extra_decls,
                 mi_insts     = insts,
                 mi_fam_insts = fam_insts,
                 mi_rules     = rules,
                 mi_hpc       = hpc_info,
                 mi_trust     = trust,
                 mi_trust_pkg = trust_pkg,
                 mi_complete_matches = complete_matches,
                 mi_docs      = docs,
                 mi_ext_fields = _ext_fields, -- Don't `put_` this in the instance so we
                                              -- can deal with it's pointer in the header
                                              -- when we write the actual file
                 mi_self_recomp_info = self_recomp,
                 mi_final_exts = ModIfaceBackend {
                   mi_self_recomp_backend_info = self_recomp_backend,
                   mi_mod_hash = mod_hash,
                   mi_orphan = orphan,
                   mi_finsts = hasFamInsts,
                   mi_exp_hash = exp_hash,
                   mi_orphan_hash = orphan_hash
                 }}) = do
        put_ bh mod
        put_ bh sig_of
        put_ bh hsc_src
        put_ bh self_recomp
        put_ bh self_recomp_backend
        put_ bh mod_hash
        put_ bh orphan
        put_ bh hasFamInsts
        lazyPut bh deps
        put_ bh exports
        put_ bh exp_hash
        put_ bh used_th
        put_ bh fixities
        lazyPut bh warns
        lazyPut bh anns
        put_ bh decls
        put_ bh extra_decls
        put_ bh insts
        put_ bh fam_insts
        lazyPut bh rules
        put_ bh orphan_hash
        put_ bh hpc_info
        put_ bh trust
        put_ bh trust_pkg
        put_ bh complete_matches
        lazyPutMaybe bh docs

   get bh = do
        mod         <- get bh
        sig_of      <- get bh
        hsc_src     <- get bh
        self_recomp_info <- get bh
        self_recomp_backend_info <- get bh
        mod_hash    <- get bh
        orphan      <- get bh
        hasFamInsts <- get bh
        deps        <- lazyGet bh
        exports     <- {-# SCC "bin_exports" #-} get bh
        exp_hash    <- get bh
        used_th     <- get bh
        fixities    <- {-# SCC "bin_fixities" #-} get bh
        warns       <- {-# SCC "bin_warns" #-} lazyGet bh
        anns        <- {-# SCC "bin_anns" #-} lazyGet bh
        decls       <- {-# SCC "bin_tycldecls" #-} get bh
        extra_decls <- get bh
        insts       <- {-# SCC "bin_insts" #-} get bh
        fam_insts   <- {-# SCC "bin_fam_insts" #-} get bh
        rules       <- {-# SCC "bin_rules" #-} lazyGet bh
        orphan_hash <- get bh
        hpc_info    <- get bh
        trust       <- get bh
        trust_pkg   <- get bh
        complete_matches <- get bh
        docs        <- lazyGetMaybe bh
        return (ModIface {
                 mi_module      = mod,
                 mi_sig_of      = sig_of,
                 mi_hsc_src     = hsc_src,
                 mi_deps        = deps,
                 mi_exports     = exports,
                 mi_used_th     = used_th,
                 mi_anns        = anns,
                 mi_fixities    = fixities,
                 mi_warns       = warns,
                 mi_decls       = decls,
                 mi_extra_decls = extra_decls,
                 mi_globals     = Nothing,
                 mi_insts       = insts,
                 mi_fam_insts   = fam_insts,
                 mi_rules       = rules,
                 mi_hpc         = hpc_info,
                 mi_trust       = trust,
                 mi_trust_pkg   = trust_pkg,
                        -- And build the cached values
                 mi_complete_matches = complete_matches,
                 mi_docs        = docs,
                 mi_ext_fields  = emptyExtensibleFields, -- placeholder because this is dealt
                                                         -- with specially when the file is read
                 mi_self_recomp_info = self_recomp_info,
                 mi_final_exts = ModIfaceBackend {
                   mi_self_recomp_backend_info = self_recomp_backend_info,
                   mi_mod_hash = mod_hash,
                   mi_orphan = orphan,
                   mi_finsts = hasFamInsts,
                   mi_exp_hash = exp_hash,
                   mi_orphan_hash = orphan_hash,
                   mi_warn_fn = mkIfaceWarnCache warns,
                   mi_fix_fn = mkIfaceFixCache fixities,
                   mi_hash_fn = mkIfaceHashCache decls
                 }})

-- | The original names declared of a certain module that are exported
type IfaceExport = AvailInfo

emptyPartialModIface :: Module -> PartialModIface
emptyPartialModIface mod
  = ModIface { mi_module      = mod,
               mi_sig_of      = Nothing,
               mi_hsc_src     = HsSrcFile,
               mi_deps        = noDependencies,
               mi_exports     = [],
               mi_used_th     = False,
               mi_fixities    = [],
               mi_warns       = NoWarnings,
               mi_anns        = [],
               mi_insts       = [],
               mi_fam_insts   = [],
               mi_rules       = [],
               mi_decls       = [],
               mi_extra_decls = Nothing,
               mi_globals     = Nothing,
               mi_hpc         = False,
               mi_trust       = noIfaceTrustInfo,
               mi_trust_pkg   = False,
               mi_complete_matches = [],
               mi_docs        = Nothing,
               mi_final_exts  = (),
               mi_self_recomp_info = NoSelfRecomp,
               mi_ext_fields  = emptyExtensibleFields
             }

emptyFullModIface :: Module -> ModIface
emptyFullModIface mod =
    (emptyPartialModIface mod)
      { mi_decls = []
      , mi_final_exts = ModIfaceBackend {
          mi_mod_hash = fingerprint0,
          mi_self_recomp_backend_info = NoSelfRecompBackend, -- TODO
          mi_orphan = False,
          mi_finsts = False,
          mi_exp_hash = fingerprint0,
          mi_orphan_hash = fingerprint0,
          mi_warn_fn = emptyIfaceWarnCache,
          mi_fix_fn = emptyIfaceFixCache,
          mi_hash_fn = emptyIfaceHashCache } }

-- | Constructs cache for the 'mi_hash_fn' field of a 'ModIface'
mkIfaceHashCache :: [(Fingerprint,IfaceDecl)]
                 -> (OccName -> Maybe (OccName, Fingerprint))
mkIfaceHashCache pairs
  = \occ -> lookupOccEnv env occ
  where
    env = foldl' add_decl emptyOccEnv pairs
    add_decl env0 (v,d) = foldl' add env0 (ifaceDeclFingerprints v d)
      where
        add env0 (occ,hash) = extendOccEnv env0 occ (occ,hash)

emptyIfaceHashCache :: OccName -> Maybe (OccName, Fingerprint)
emptyIfaceHashCache _occ = Nothing

-- Take care, this instance only forces to the degree necessary to
-- avoid major space leaks.
instance (NFData (IfaceBackendExts (phase :: ModIfacePhase)), NFData (IfaceDeclExts (phase :: ModIfacePhase))) => NFData (ModIface_ phase) where
  rnf (ModIface f1 f2 f3 f4 f6 f7 f8 f9 f10 f11 f12
                f13 f14 f15 f16 f17 f18 f19 f20 f21 f22 f23 f24) =
    rnf f1 `seq` rnf f2 `seq` f3 `seq` f4 `seq` f6 `seq` rnf f7 `seq` f8 `seq`
    f9 `seq` rnf f10 `seq` rnf f11 `seq` rnf f12 `seq` f13 `seq` rnf f14 `seq` rnf f15 `seq` rnf f16 `seq`
    rnf f17 `seq` f18 `seq` rnf f19 `seq` rnf f20 `seq` f21 `seq` f22 `seq` f23 `seq` rnf f24
    `seq` ()


instance NFData (ModIfaceBackend) where
  rnf (ModIfaceBackend f1 f2 f3 f4 f5 f6 f7 f8 f9)
    = rnf f1 `seq` rnf f2 `seq` rnf f3 `seq` rnf f4 `seq`
      rnf f5 `seq` rnf f6 `seq` rnf f7 `seq` rnf f8 `seq`
      rnf f9

instance NFData ModIfaceSelfRecompBackend where
  -- Sufficient as all fields are strict (and simple)
  rnf NoSelfRecompBackend = ()
  -- Written like this so if you add another field you have to think about it
  rnf !(ModIfaceSelfRecompBackend _ _ _ _ _) = ()
instance NFData ModIfaceSelfRecomp where
  -- Sufficient as all fields are strict (and simple)
  rnf NoSelfRecomp = ()
  -- MP: Note does not deeply force Usages but the old ModIface logic didn't either, so
  -- I left it as a shallow force.
  rnf (ModIfaceSelfRecomp src_hash usages) = src_hash `seq` usages `seq` ()


forceModIface :: ModIface -> IO ()
forceModIface iface = () <$ (evaluate $ force iface)

-- | Records whether a module has orphans. An \"orphan\" is one of:
--
-- * An instance declaration in a module other than the definition
--   module for one of the type constructors or classes in the instance head
--
-- * A rewrite rule in a module other than the one defining
--   the function in the head of the rule
--
type WhetherHasOrphans   = Bool

-- | Does this module define family instances?
type WhetherHasFamInst = Bool