1{-
2(c) The University of Glasgow 2006
3(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4
5
6Loading interface files
7-}
8
9{-# LANGUAGE CPP, BangPatterns, RecordWildCards, NondecreasingIndentation #-}
10{-# LANGUAGE TypeFamilies #-}
11{-# OPTIONS_GHC -fno-warn-orphans #-}
12module LoadIface (
13        -- Importing one thing
14        tcLookupImported_maybe, importDecl,
15        checkWiredInTyCon, ifCheckWiredInThing,
16
17        -- RnM/TcM functions
18        loadModuleInterface, loadModuleInterfaces,
19        loadSrcInterface, loadSrcInterface_maybe,
20        loadInterfaceForName, loadInterfaceForNameMaybe, loadInterfaceForModule,
21
22        -- IfM functions
23        loadInterface,
24        loadSysInterface, loadUserInterface, loadPluginInterface,
25        findAndReadIface, readIface,    -- Used when reading the module's old interface
26        loadDecls,      -- Should move to TcIface and be renamed
27        initExternalPackageState,
28        moduleFreeHolesPrecise,
29        needWiredInHomeIface, loadWiredInHomeIface,
30
31        pprModIfaceSimple,
32        ifaceStats, pprModIface, showIface
33   ) where
34
35#include "HsVersions.h"
36
37import GhcPrelude
38
39import {-# SOURCE #-}   TcIface( tcIfaceDecl, tcIfaceRules, tcIfaceInst,
40                                 tcIfaceFamInst,
41                                 tcIfaceAnnotations, tcIfaceCompleteSigs )
42
43import DynFlags
44import IfaceSyn
45import IfaceEnv
46import HscTypes
47
48import BasicTypes hiding (SuccessFlag(..))
49import TcRnMonad
50
51import Constants
52import PrelNames
53import PrelInfo
54import PrimOp   ( allThePrimOps, primOpFixity, primOpOcc )
55import MkId     ( seqId )
56import TysPrim  ( funTyConName )
57import Rules
58import TyCon
59import Annotations
60import InstEnv
61import FamInstEnv
62import Name
63import NameEnv
64import Avail
65import Module
66import Maybes
67import ErrUtils
68import Finder
69import UniqFM
70import SrcLoc
71import Outputable
72import BinIface
73import Panic
74import Util
75import FastString
76import Fingerprint
77import Hooks
78import FieldLabel
79import RnModIface
80import UniqDSet
81import Plugins
82
83import Control.Monad
84import Control.Exception
85import Data.IORef
86import System.FilePath
87
88{-
89************************************************************************
90*                                                                      *
91*      tcImportDecl is the key function for "faulting in"              *
92*      imported things
93*                                                                      *
94************************************************************************
95
96The main idea is this.  We are chugging along type-checking source code, and
97find a reference to GHC.Base.map.  We call tcLookupGlobal, which doesn't find
98it in the EPS type envt.  So it
99        1 loads GHC.Base.hi
100        2 gets the decl for GHC.Base.map
101        3 typechecks it via tcIfaceDecl
102        4 and adds it to the type env in the EPS
103
104Note that DURING STEP 4, we may find that map's type mentions a type
105constructor that also
106
107Notice that for imported things we read the current version from the EPS
108mutable variable.  This is important in situations like
109        ...$(e1)...$(e2)...
110where the code that e1 expands to might import some defns that
111also turn out to be needed by the code that e2 expands to.
112-}
113
114tcLookupImported_maybe :: Name -> TcM (MaybeErr MsgDoc TyThing)
115-- Returns (Failed err) if we can't find the interface file for the thing
116tcLookupImported_maybe name
117  = do  { hsc_env <- getTopEnv
118        ; mb_thing <- liftIO (lookupTypeHscEnv hsc_env name)
119        ; case mb_thing of
120            Just thing -> return (Succeeded thing)
121            Nothing    -> tcImportDecl_maybe name }
122
123tcImportDecl_maybe :: Name -> TcM (MaybeErr MsgDoc TyThing)
124-- Entry point for *source-code* uses of importDecl
125tcImportDecl_maybe name
126  | Just thing <- wiredInNameTyThing_maybe name
127  = do  { when (needWiredInHomeIface thing)
128               (initIfaceTcRn (loadWiredInHomeIface name))
129                -- See Note [Loading instances for wired-in things]
130        ; return (Succeeded thing) }
131  | otherwise
132  = initIfaceTcRn (importDecl name)
133
134importDecl :: Name -> IfM lcl (MaybeErr MsgDoc TyThing)
135-- Get the TyThing for this Name from an interface file
136-- It's not a wired-in thing -- the caller caught that
137importDecl name
138  = ASSERT( not (isWiredInName name) )
139    do  { traceIf nd_doc
140
141        -- Load the interface, which should populate the PTE
142        ; mb_iface <- ASSERT2( isExternalName name, ppr name )
143                      loadInterface nd_doc (nameModule name) ImportBySystem
144        ; case mb_iface of {
145                Failed err_msg  -> return (Failed err_msg) ;
146                Succeeded _ -> do
147
148        -- Now look it up again; this time we should find it
149        { eps <- getEps
150        ; case lookupTypeEnv (eps_PTE eps) name of
151            Just thing -> return $ Succeeded thing
152            Nothing    -> let doc = whenPprDebug (found_things_msg eps $$ empty)
153                                    $$ not_found_msg
154                          in return $ Failed doc
155    }}}
156  where
157    nd_doc = text "Need decl for" <+> ppr name
158    not_found_msg = hang (text "Can't find interface-file declaration for" <+>
159                                pprNameSpace (nameNameSpace name) <+> ppr name)
160                       2 (vcat [text "Probable cause: bug in .hi-boot file, or inconsistent .hi file",
161                                text "Use -ddump-if-trace to get an idea of which file caused the error"])
162    found_things_msg eps =
163        hang (text "Found the following declarations in" <+> ppr (nameModule name) <> colon)
164           2 (vcat (map ppr $ filter is_interesting $ nameEnvElts $ eps_PTE eps))
165      where
166        is_interesting thing = nameModule name == nameModule (getName thing)
167
168
169{-
170************************************************************************
171*                                                                      *
172           Checks for wired-in things
173*                                                                      *
174************************************************************************
175
176Note [Loading instances for wired-in things]
177~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
178We need to make sure that we have at least *read* the interface files
179for any module with an instance decl or RULE that we might want.
180
181* If the instance decl is an orphan, we have a whole separate mechanism
182  (loadOrphanModules)
183
184* If the instance decl is not an orphan, then the act of looking at the
185  TyCon or Class will force in the defining module for the
186  TyCon/Class, and hence the instance decl
187
188* BUT, if the TyCon is a wired-in TyCon, we don't really need its interface;
189  but we must make sure we read its interface in case it has instances or
190  rules.  That is what LoadIface.loadWiredInHomeIface does.  It's called
191  from TcIface.{tcImportDecl, checkWiredInTyCon, ifCheckWiredInThing}
192
193* HOWEVER, only do this for TyCons.  There are no wired-in Classes.  There
194  are some wired-in Ids, but we don't want to load their interfaces. For
195  example, Control.Exception.Base.recSelError is wired in, but that module
196  is compiled late in the base library, and we don't want to force it to
197  load before it's been compiled!
198
199All of this is done by the type checker. The renamer plays no role.
200(It used to, but no longer.)
201-}
202
203checkWiredInTyCon :: TyCon -> TcM ()
204-- Ensure that the home module of the TyCon (and hence its instances)
205-- are loaded. See Note [Loading instances for wired-in things]
206-- It might not be a wired-in tycon (see the calls in TcUnify),
207-- in which case this is a no-op.
208checkWiredInTyCon tc
209  | not (isWiredInName tc_name)
210  = return ()
211  | otherwise
212  = do  { mod <- getModule
213        ; traceIf (text "checkWiredInTyCon" <+> ppr tc_name $$ ppr mod)
214        ; ASSERT( isExternalName tc_name )
215          when (mod /= nameModule tc_name)
216               (initIfaceTcRn (loadWiredInHomeIface tc_name))
217                -- Don't look for (non-existent) Float.hi when
218                -- compiling Float.hs, which mentions Float of course
219                -- A bit yukky to call initIfaceTcRn here
220        }
221  where
222    tc_name = tyConName tc
223
224ifCheckWiredInThing :: TyThing -> IfL ()
225-- Even though we are in an interface file, we want to make
226-- sure the instances of a wired-in thing are loaded (imagine f :: Double -> Double)
227-- Ditto want to ensure that RULES are loaded too
228-- See Note [Loading instances for wired-in things]
229ifCheckWiredInThing thing
230  = do  { mod <- getIfModule
231                -- Check whether we are typechecking the interface for this
232                -- very module.  E.g when compiling the base library in --make mode
233                -- we may typecheck GHC.Base.hi. At that point, GHC.Base is not in
234                -- the HPT, so without the test we'll demand-load it into the PIT!
235                -- C.f. the same test in checkWiredInTyCon above
236        ; let name = getName thing
237        ; ASSERT2( isExternalName name, ppr name )
238          when (needWiredInHomeIface thing && mod /= nameModule name)
239               (loadWiredInHomeIface name) }
240
241needWiredInHomeIface :: TyThing -> Bool
242-- Only for TyCons; see Note [Loading instances for wired-in things]
243needWiredInHomeIface (ATyCon {}) = True
244needWiredInHomeIface _           = False
245
246
247{-
248************************************************************************
249*                                                                      *
250        loadSrcInterface, loadOrphanModules, loadInterfaceForName
251
252                These three are called from TcM-land
253*                                                                      *
254************************************************************************
255-}
256
257-- | Load the interface corresponding to an @import@ directive in
258-- source code.  On a failure, fail in the monad with an error message.
259loadSrcInterface :: SDoc
260                 -> ModuleName
261                 -> IsBootInterface     -- {-# SOURCE #-} ?
262                 -> Maybe FastString    -- "package", if any
263                 -> RnM ModIface
264
265loadSrcInterface doc mod want_boot maybe_pkg
266  = do { res <- loadSrcInterface_maybe doc mod want_boot maybe_pkg
267       ; case res of
268           Failed err      -> failWithTc err
269           Succeeded iface -> return iface }
270
271-- | Like 'loadSrcInterface', but returns a 'MaybeErr'.
272loadSrcInterface_maybe :: SDoc
273                       -> ModuleName
274                       -> IsBootInterface     -- {-# SOURCE #-} ?
275                       -> Maybe FastString    -- "package", if any
276                       -> RnM (MaybeErr MsgDoc ModIface)
277
278loadSrcInterface_maybe doc mod want_boot maybe_pkg
279  -- We must first find which Module this import refers to.  This involves
280  -- calling the Finder, which as a side effect will search the filesystem
281  -- and create a ModLocation.  If successful, loadIface will read the
282  -- interface; it will call the Finder again, but the ModLocation will be
283  -- cached from the first search.
284  = do { hsc_env <- getTopEnv
285       ; res <- liftIO $ findImportedModule hsc_env mod maybe_pkg
286       ; case res of
287           Found _ mod -> initIfaceTcRn $ loadInterface doc mod (ImportByUser want_boot)
288           -- TODO: Make sure this error message is good
289           err         -> return (Failed (cannotFindModule (hsc_dflags hsc_env) mod err)) }
290
291-- | Load interface directly for a fully qualified 'Module'.  (This is a fairly
292-- rare operation, but in particular it is used to load orphan modules
293-- in order to pull their instances into the global package table and to
294-- handle some operations in GHCi).
295loadModuleInterface :: SDoc -> Module -> TcM ModIface
296loadModuleInterface doc mod = initIfaceTcRn (loadSysInterface doc mod)
297
298-- | Load interfaces for a collection of modules.
299loadModuleInterfaces :: SDoc -> [Module] -> TcM ()
300loadModuleInterfaces doc mods
301  | null mods = return ()
302  | otherwise = initIfaceTcRn (mapM_ load mods)
303  where
304    load mod = loadSysInterface (doc <+> parens (ppr mod)) mod
305
306-- | Loads the interface for a given Name.
307-- Should only be called for an imported name;
308-- otherwise loadSysInterface may not find the interface
309loadInterfaceForName :: SDoc -> Name -> TcRn ModIface
310loadInterfaceForName doc name
311  = do { when debugIsOn $  -- Check pre-condition
312         do { this_mod <- getModule
313            ; MASSERT2( not (nameIsLocalOrFrom this_mod name), ppr name <+> parens doc ) }
314      ; ASSERT2( isExternalName name, ppr name )
315        initIfaceTcRn $ loadSysInterface doc (nameModule name) }
316
317-- | Only loads the interface for external non-local names.
318loadInterfaceForNameMaybe :: SDoc -> Name -> TcRn (Maybe ModIface)
319loadInterfaceForNameMaybe doc name
320  = do { this_mod <- getModule
321       ; if nameIsLocalOrFrom this_mod name || not (isExternalName name)
322         then return Nothing
323         else Just <$> (initIfaceTcRn $ loadSysInterface doc (nameModule name))
324       }
325
326-- | Loads the interface for a given Module.
327loadInterfaceForModule :: SDoc -> Module -> TcRn ModIface
328loadInterfaceForModule doc m
329  = do
330    -- Should not be called with this module
331    when debugIsOn $ do
332      this_mod <- getModule
333      MASSERT2( this_mod /= m, ppr m <+> parens doc )
334    initIfaceTcRn $ loadSysInterface doc m
335
336{-
337*********************************************************
338*                                                      *
339                loadInterface
340
341        The main function to load an interface
342        for an imported module, and put it in
343        the External Package State
344*                                                      *
345*********************************************************
346-}
347
348-- | An 'IfM' function to load the home interface for a wired-in thing,
349-- so that we're sure that we see its instance declarations and rules
350-- See Note [Loading instances for wired-in things]
351loadWiredInHomeIface :: Name -> IfM lcl ()
352loadWiredInHomeIface name
353  = ASSERT( isWiredInName name )
354    do _ <- loadSysInterface doc (nameModule name); return ()
355  where
356    doc = text "Need home interface for wired-in thing" <+> ppr name
357
358------------------
359-- | Loads a system interface and throws an exception if it fails
360loadSysInterface :: SDoc -> Module -> IfM lcl ModIface
361loadSysInterface doc mod_name = loadInterfaceWithException doc mod_name ImportBySystem
362
363------------------
364-- | Loads a user interface and throws an exception if it fails. The first parameter indicates
365-- whether we should import the boot variant of the module
366loadUserInterface :: Bool -> SDoc -> Module -> IfM lcl ModIface
367loadUserInterface is_boot doc mod_name
368  = loadInterfaceWithException doc mod_name (ImportByUser is_boot)
369
370loadPluginInterface :: SDoc -> Module -> IfM lcl ModIface
371loadPluginInterface doc mod_name
372  = loadInterfaceWithException doc mod_name ImportByPlugin
373
374------------------
375-- | A wrapper for 'loadInterface' that throws an exception if it fails
376loadInterfaceWithException :: SDoc -> Module -> WhereFrom -> IfM lcl ModIface
377loadInterfaceWithException doc mod_name where_from
378  = withException (loadInterface doc mod_name where_from)
379
380------------------
381loadInterface :: SDoc -> Module -> WhereFrom
382              -> IfM lcl (MaybeErr MsgDoc ModIface)
383
384-- loadInterface looks in both the HPT and PIT for the required interface
385-- If not found, it loads it, and puts it in the PIT (always).
386
387-- If it can't find a suitable interface file, we
388--      a) modify the PackageIfaceTable to have an empty entry
389--              (to avoid repeated complaints)
390--      b) return (Left message)
391--
392-- It's not necessarily an error for there not to be an interface
393-- file -- perhaps the module has changed, and that interface
394-- is no longer used
395
396loadInterface doc_str mod from
397  | isHoleModule mod
398  -- Hole modules get special treatment
399  = do dflags <- getDynFlags
400       -- Redo search for our local hole module
401       loadInterface doc_str (mkModule (thisPackage dflags) (moduleName mod)) from
402  | otherwise
403  = withTimingSilentD (text "loading interface") (pure ()) $
404    do  {       -- Read the state
405          (eps,hpt) <- getEpsAndHpt
406        ; gbl_env <- getGblEnv
407
408        ; traceIf (text "Considering whether to load" <+> ppr mod <+> ppr from)
409
410                -- Check whether we have the interface already
411        ; dflags <- getDynFlags
412        ; case lookupIfaceByModule hpt (eps_PIT eps) mod of {
413            Just iface
414                -> return (Succeeded iface) ;   -- Already loaded
415                        -- The (src_imp == mi_boot iface) test checks that the already-loaded
416                        -- interface isn't a boot iface.  This can conceivably happen,
417                        -- if an earlier import had a before we got to real imports.   I think.
418            _ -> do {
419
420        -- READ THE MODULE IN
421        ; read_result <- case (wantHiBootFile dflags eps mod from) of
422                           Failed err             -> return (Failed err)
423                           Succeeded hi_boot_file -> computeInterface doc_str hi_boot_file mod
424        ; case read_result of {
425            Failed err -> do
426                { let fake_iface = emptyFullModIface mod
427
428                ; updateEps_ $ \eps ->
429                        eps { eps_PIT = extendModuleEnv (eps_PIT eps) (mi_module fake_iface) fake_iface }
430                        -- Not found, so add an empty iface to
431                        -- the EPS map so that we don't look again
432
433                ; return (Failed err) } ;
434
435        -- Found and parsed!
436        -- We used to have a sanity check here that looked for:
437        --  * System importing ..
438        --  * a home package module ..
439        --  * that we know nothing about (mb_dep == Nothing)!
440        --
441        -- But this is no longer valid because thNameToGhcName allows users to
442        -- cause the system to load arbitrary interfaces (by supplying an appropriate
443        -- Template Haskell original-name).
444            Succeeded (iface, loc) ->
445        let
446            loc_doc = text loc
447        in
448        initIfaceLcl (mi_semantic_module iface) loc_doc (mi_boot iface) $ do
449
450        dontLeakTheHPT $ do
451
452        --      Load the new ModIface into the External Package State
453        -- Even home-package interfaces loaded by loadInterface
454        --      (which only happens in OneShot mode; in Batch/Interactive
455        --      mode, home-package modules are loaded one by one into the HPT)
456        -- are put in the EPS.
457        --
458        -- The main thing is to add the ModIface to the PIT, but
459        -- we also take the
460        --      IfaceDecls, IfaceClsInst, IfaceFamInst, IfaceRules,
461        -- out of the ModIface and put them into the big EPS pools
462
463        -- NB: *first* we do loadDecl, so that the provenance of all the locally-defined
464        ---    names is done correctly (notably, whether this is an .hi file or .hi-boot file).
465        --     If we do loadExport first the wrong info gets into the cache (unless we
466        --      explicitly tag each export which seems a bit of a bore)
467
468        ; ignore_prags      <- goptM Opt_IgnoreInterfacePragmas
469        ; new_eps_decls     <- loadDecls ignore_prags (mi_decls iface)
470        ; new_eps_insts     <- mapM tcIfaceInst (mi_insts iface)
471        ; new_eps_fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
472        ; new_eps_rules     <- tcIfaceRules ignore_prags (mi_rules iface)
473        ; new_eps_anns      <- tcIfaceAnnotations (mi_anns iface)
474        ; new_eps_complete_sigs <- tcIfaceCompleteSigs (mi_complete_sigs iface)
475
476        ; let { final_iface = iface {
477                                mi_decls     = panic "No mi_decls in PIT",
478                                mi_insts     = panic "No mi_insts in PIT",
479                                mi_fam_insts = panic "No mi_fam_insts in PIT",
480                                mi_rules     = panic "No mi_rules in PIT",
481                                mi_anns      = panic "No mi_anns in PIT"
482                              }
483               }
484
485        ; let bad_boot = mi_boot iface && fmap fst (if_rec_types gbl_env) == Just mod
486                            -- Warn warn against an EPS-updating import
487                            -- of one's own boot file! (one-shot only)
488                            -- See Note [Loading your own hi-boot file]
489                            -- in MkIface.
490
491        ; WARN( bad_boot, ppr mod )
492          updateEps_  $ \ eps ->
493           if elemModuleEnv mod (eps_PIT eps) || is_external_sig dflags iface
494                then eps
495           else if bad_boot
496                -- See Note [Loading your own hi-boot file]
497                then eps { eps_PTE = addDeclsToPTE (eps_PTE eps) new_eps_decls }
498           else
499                eps {
500                  eps_PIT          = extendModuleEnv (eps_PIT eps) mod final_iface,
501                  eps_PTE          = addDeclsToPTE   (eps_PTE eps) new_eps_decls,
502                  eps_rule_base    = extendRuleBaseList (eps_rule_base eps)
503                                                        new_eps_rules,
504                  eps_complete_matches
505                                   = extendCompleteMatchMap
506                                         (eps_complete_matches eps)
507                                         new_eps_complete_sigs,
508                  eps_inst_env     = extendInstEnvList (eps_inst_env eps)
509                                                       new_eps_insts,
510                  eps_fam_inst_env = extendFamInstEnvList (eps_fam_inst_env eps)
511                                                          new_eps_fam_insts,
512                  eps_ann_env      = extendAnnEnvList (eps_ann_env eps)
513                                                      new_eps_anns,
514                  eps_mod_fam_inst_env
515                                   = let
516                                       fam_inst_env =
517                                         extendFamInstEnvList emptyFamInstEnv
518                                                              new_eps_fam_insts
519                                     in
520                                     extendModuleEnv (eps_mod_fam_inst_env eps)
521                                                     mod
522                                                     fam_inst_env,
523                  eps_stats        = addEpsInStats (eps_stats eps)
524                                                   (length new_eps_decls)
525                                                   (length new_eps_insts)
526                                                   (length new_eps_rules) }
527
528        ; -- invoke plugins
529          res <- withPlugins dflags interfaceLoadAction final_iface
530        ; return (Succeeded res)
531    }}}}
532
533{- Note [Loading your own hi-boot file]
534~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
535Generally speaking, when compiling module M, we should not
536load M.hi boot into the EPS.  After all, we are very shortly
537going to have full information about M.  Moreover, see
538Note [Do not update EPS with your own hi-boot] in MkIface.
539
540But there is a HORRIBLE HACK here.
541
542* At the end of tcRnImports, we call checkFamInstConsistency to
543  check consistency of imported type-family instances
544  See Note [The type family instance consistency story] in FamInst
545
546* Alas, those instances may refer to data types defined in M,
547  if there is a M.hs-boot.
548
549* And that means we end up loading M.hi-boot, because those
550  data types are not yet in the type environment.
551
552But in this wierd case, /all/ we need is the types. We don't need
553instances, rules etc.  And if we put the instances in the EPS
554we get "duplicate instance" warnings when we compile the "real"
555instance in M itself.  Hence the strange business of just updateing
556the eps_PTE.
557
558This really happens in practice.  The module HsExpr.hs gets
559"duplicate instance" errors if this hack is not present.
560
561This is a mess.
562
563
564Note [HPT space leak] (#15111)
565~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
566In IfL, we defer some work until it is demanded using forkM, such
567as building TyThings from IfaceDecls. These thunks are stored in
568the ExternalPackageState, and they might never be poked.  If we're
569not careful, these thunks will capture the state of the loaded
570program when we read an interface file, and retain all that data
571for ever.
572
573Therefore, when loading a package interface file , we use a "clean"
574version of the HscEnv with all the data about the currently loaded
575program stripped out. Most of the fields can be panics because
576we'll never read them, but hsc_HPT needs to be empty because this
577interface will cause other interfaces to be loaded recursively, and
578when looking up those interfaces we use the HPT in loadInterface.
579We know that none of the interfaces below here can refer to
580home-package modules however, so it's safe for the HPT to be empty.
581-}
582
583dontLeakTheHPT :: IfL a -> IfL a
584dontLeakTheHPT thing_inside = do
585  let
586    cleanTopEnv HscEnv{..} =
587       let
588         -- wrinkle: when we're typechecking in --backpack mode, the
589         -- instantiation of a signature might reside in the HPT, so
590         -- this case breaks the assumption that EPS interfaces only
591         -- refer to other EPS interfaces. We can detect when we're in
592         -- typechecking-only mode by using hscTarget==HscNothing, and
593         -- in that case we don't empty the HPT.  (admittedly this is
594         -- a bit of a hack, better suggestions welcome). A number of
595         -- tests in testsuite/tests/backpack break without this
596         -- tweak.
597         !hpt | hscTarget hsc_dflags == HscNothing = hsc_HPT
598              | otherwise = emptyHomePackageTable
599       in
600       HscEnv {  hsc_targets      = panic "cleanTopEnv: hsc_targets"
601              ,  hsc_mod_graph    = panic "cleanTopEnv: hsc_mod_graph"
602              ,  hsc_IC           = panic "cleanTopEnv: hsc_IC"
603              ,  hsc_HPT          = hpt
604              , .. }
605
606  updTopEnv cleanTopEnv $ do
607  !_ <- getTopEnv        -- force the updTopEnv
608  thing_inside
609
610
611-- | Returns @True@ if a 'ModIface' comes from an external package.
612-- In this case, we should NOT load it into the EPS; the entities
613-- should instead come from the local merged signature interface.
614is_external_sig :: DynFlags -> ModIface -> Bool
615is_external_sig dflags iface =
616    -- It's a signature iface...
617    mi_semantic_module iface /= mi_module iface &&
618    -- and it's not from the local package
619    moduleUnitId (mi_module iface) /= thisPackage dflags
620
621-- | This is an improved version of 'findAndReadIface' which can also
622-- handle the case when a user requests @p[A=<B>]:M@ but we only
623-- have an interface for @p[A=<A>]:M@ (the indefinite interface.
624-- If we are not trying to build code, we load the interface we have,
625-- *instantiating it* according to how the holes are specified.
626-- (Of course, if we're actually building code, this is a hard error.)
627--
628-- In the presence of holes, 'computeInterface' has an important invariant:
629-- to load module M, its set of transitively reachable requirements must
630-- have an up-to-date local hi file for that requirement.  Note that if
631-- we are loading the interface of a requirement, this does not
632-- apply to the requirement itself; e.g., @p[A=<A>]:A@ does not require
633-- A.hi to be up-to-date (and indeed, we MUST NOT attempt to read A.hi, unless
634-- we are actually typechecking p.)
635computeInterface ::
636       SDoc -> IsBootInterface -> Module
637    -> TcRnIf gbl lcl (MaybeErr MsgDoc (ModIface, FilePath))
638computeInterface doc_str hi_boot_file mod0 = do
639    MASSERT( not (isHoleModule mod0) )
640    dflags <- getDynFlags
641    case splitModuleInsts mod0 of
642        (imod, Just indef) | not (unitIdIsDefinite (thisPackage dflags)) -> do
643            r <- findAndReadIface doc_str imod mod0 hi_boot_file
644            case r of
645                Succeeded (iface0, path) -> do
646                    hsc_env <- getTopEnv
647                    r <- liftIO $
648                        rnModIface hsc_env (indefUnitIdInsts (indefModuleUnitId indef))
649                                   Nothing iface0
650                    case r of
651                        Right x -> return (Succeeded (x, path))
652                        Left errs -> liftIO . throwIO . mkSrcErr $ errs
653                Failed err -> return (Failed err)
654        (mod, _) ->
655            findAndReadIface doc_str mod mod0 hi_boot_file
656
657-- | Compute the signatures which must be compiled in order to
658-- load the interface for a 'Module'.  The output of this function
659-- is always a subset of 'moduleFreeHoles'; it is more precise
660-- because in signature @p[A=<A>,B=<B>]:B@, although the free holes
661-- are A and B, B might not depend on A at all!
662--
663-- If this is invoked on a signature, this does NOT include the
664-- signature itself; e.g. precise free module holes of
665-- @p[A=<A>,B=<B>]:B@ never includes B.
666moduleFreeHolesPrecise
667    :: SDoc -> Module
668    -> TcRnIf gbl lcl (MaybeErr MsgDoc (UniqDSet ModuleName))
669moduleFreeHolesPrecise doc_str mod
670 | moduleIsDefinite mod = return (Succeeded emptyUniqDSet)
671 | otherwise =
672   case splitModuleInsts mod of
673    (imod, Just indef) -> do
674        let insts = indefUnitIdInsts (indefModuleUnitId indef)
675        traceIf (text "Considering whether to load" <+> ppr mod <+>
676                 text "to compute precise free module holes")
677        (eps, hpt) <- getEpsAndHpt
678        case tryEpsAndHpt eps hpt `firstJust` tryDepsCache eps imod insts of
679            Just r -> return (Succeeded r)
680            Nothing -> readAndCache imod insts
681    (_, Nothing) -> return (Succeeded emptyUniqDSet)
682  where
683    tryEpsAndHpt eps hpt =
684        fmap mi_free_holes (lookupIfaceByModule hpt (eps_PIT eps) mod)
685    tryDepsCache eps imod insts =
686        case lookupInstalledModuleEnv (eps_free_holes eps) imod of
687            Just ifhs  -> Just (renameFreeHoles ifhs insts)
688            _otherwise -> Nothing
689    readAndCache imod insts = do
690        mb_iface <- findAndReadIface (text "moduleFreeHolesPrecise" <+> doc_str) imod mod False
691        case mb_iface of
692            Succeeded (iface, _) -> do
693                let ifhs = mi_free_holes iface
694                -- Cache it
695                updateEps_ (\eps ->
696                    eps { eps_free_holes = extendInstalledModuleEnv (eps_free_holes eps) imod ifhs })
697                return (Succeeded (renameFreeHoles ifhs insts))
698            Failed err -> return (Failed err)
699
700wantHiBootFile :: DynFlags -> ExternalPackageState -> Module -> WhereFrom
701               -> MaybeErr MsgDoc IsBootInterface
702-- Figure out whether we want Foo.hi or Foo.hi-boot
703wantHiBootFile dflags eps mod from
704  = case from of
705       ImportByUser usr_boot
706          | usr_boot && not this_package
707          -> Failed (badSourceImport mod)
708          | otherwise -> Succeeded usr_boot
709
710       ImportByPlugin
711          -> Succeeded False
712
713       ImportBySystem
714          | not this_package   -- If the module to be imported is not from this package
715          -> Succeeded False   -- don't look it up in eps_is_boot, because that is keyed
716                               -- on the ModuleName of *home-package* modules only.
717                               -- We never import boot modules from other packages!
718
719          | otherwise
720          -> case lookupUFM (eps_is_boot eps) (moduleName mod) of
721                Just (_, is_boot) -> Succeeded is_boot
722                Nothing           -> Succeeded False
723                     -- The boot-ness of the requested interface,
724                     -- based on the dependencies in directly-imported modules
725  where
726    this_package = thisPackage dflags == moduleUnitId mod
727
728badSourceImport :: Module -> SDoc
729badSourceImport mod
730  = hang (text "You cannot {-# SOURCE #-} import a module from another package")
731       2 (text "but" <+> quotes (ppr mod) <+> ptext (sLit "is from package")
732          <+> quotes (ppr (moduleUnitId mod)))
733
734-----------------------------------------------------
735--      Loading type/class/value decls
736-- We pass the full Module name here, replete with
737-- its package info, so that we can build a Name for
738-- each binder with the right package info in it
739-- All subsequent lookups, including crucially lookups during typechecking
740-- the declaration itself, will find the fully-glorious Name
741--
742-- We handle ATs specially.  They are not main declarations, but also not
743-- implicit things (in particular, adding them to `implicitTyThings' would mess
744-- things up in the renaming/type checking of source programs).
745-----------------------------------------------------
746
747addDeclsToPTE :: PackageTypeEnv -> [(Name,TyThing)] -> PackageTypeEnv
748addDeclsToPTE pte things = extendNameEnvList pte things
749
750loadDecls :: Bool
751          -> [(Fingerprint, IfaceDecl)]
752          -> IfL [(Name,TyThing)]
753loadDecls ignore_prags ver_decls
754   = do { thingss <- mapM (loadDecl ignore_prags) ver_decls
755        ; return (concat thingss)
756        }
757
758loadDecl :: Bool                    -- Don't load pragmas into the decl pool
759          -> (Fingerprint, IfaceDecl)
760          -> IfL [(Name,TyThing)]   -- The list can be poked eagerly, but the
761                                    -- TyThings are forkM'd thunks
762loadDecl ignore_prags (_version, decl)
763  = do  {       -- Populate the name cache with final versions of all
764                -- the names associated with the decl
765          let main_name = ifName decl
766
767        -- Typecheck the thing, lazily
768        -- NB. Firstly, the laziness is there in case we never need the
769        -- declaration (in one-shot mode), and secondly it is there so that
770        -- we don't look up the occurrence of a name before calling mk_new_bndr
771        -- on the binder.  This is important because we must get the right name
772        -- which includes its nameParent.
773
774        ; thing <- forkM doc $ do { bumpDeclStats main_name
775                                  ; tcIfaceDecl ignore_prags decl }
776
777        -- Populate the type environment with the implicitTyThings too.
778        --
779        -- Note [Tricky iface loop]
780        -- ~~~~~~~~~~~~~~~~~~~~~~~~
781        -- Summary: The delicate point here is that 'mini-env' must be
782        -- buildable from 'thing' without demanding any of the things
783        -- 'forkM'd by tcIfaceDecl.
784        --
785        -- In more detail: Consider the example
786        --      data T a = MkT { x :: T a }
787        -- The implicitTyThings of T are:  [ <datacon MkT>, <selector x>]
788        -- (plus their workers, wrappers, coercions etc etc)
789        --
790        -- We want to return an environment
791        --      [ "MkT" -> <datacon MkT>, "x" -> <selector x>, ... ]
792        -- (where the "MkT" is the *Name* associated with MkT, etc.)
793        --
794        -- We do this by mapping the implicit_names to the associated
795        -- TyThings.  By the invariant on ifaceDeclImplicitBndrs and
796        -- implicitTyThings, we can use getOccName on the implicit
797        -- TyThings to make this association: each Name's OccName should
798        -- be the OccName of exactly one implicitTyThing.  So the key is
799        -- to define a "mini-env"
800        --
801        -- [ 'MkT' -> <datacon MkT>, 'x' -> <selector x>, ... ]
802        -- where the 'MkT' here is the *OccName* associated with MkT.
803        --
804        -- However, there is a subtlety: due to how type checking needs
805        -- to be staged, we can't poke on the forkM'd thunks inside the
806        -- implicitTyThings while building this mini-env.
807        -- If we poke these thunks too early, two problems could happen:
808        --    (1) When processing mutually recursive modules across
809        --        hs-boot boundaries, poking too early will do the
810        --        type-checking before the recursive knot has been tied,
811        --        so things will be type-checked in the wrong
812        --        environment, and necessary variables won't be in
813        --        scope.
814        --
815        --    (2) Looking up one OccName in the mini_env will cause
816        --        others to be looked up, which might cause that
817        --        original one to be looked up again, and hence loop.
818        --
819        -- The code below works because of the following invariant:
820        -- getOccName on a TyThing does not force the suspended type
821        -- checks in order to extract the name. For example, we don't
822        -- poke on the "T a" type of <selector x> on the way to
823        -- extracting <selector x>'s OccName. Of course, there is no
824        -- reason in principle why getting the OccName should force the
825        -- thunks, but this means we need to be careful in
826        -- implicitTyThings and its helper functions.
827        --
828        -- All a bit too finely-balanced for my liking.
829
830        -- This mini-env and lookup function mediates between the
831        --'Name's n and the map from 'OccName's to the implicit TyThings
832        ; let mini_env = mkOccEnv [(getOccName t, t) | t <- implicitTyThings thing]
833              lookup n = case lookupOccEnv mini_env (getOccName n) of
834                           Just thing -> thing
835                           Nothing    ->
836                             pprPanic "loadDecl" (ppr main_name <+> ppr n $$ ppr (decl))
837
838        ; implicit_names <- mapM lookupIfaceTop (ifaceDeclImplicitBndrs decl)
839
840--         ; traceIf (text "Loading decl for " <> ppr main_name $$ ppr implicit_names)
841        ; return $ (main_name, thing) :
842                      -- uses the invariant that implicit_names and
843                      -- implicitTyThings are bijective
844                      [(n, lookup n) | n <- implicit_names]
845        }
846  where
847    doc = text "Declaration for" <+> ppr (ifName decl)
848
849bumpDeclStats :: Name -> IfL ()         -- Record that one more declaration has actually been used
850bumpDeclStats name
851  = do  { traceIf (text "Loading decl for" <+> ppr name)
852        ; updateEps_ (\eps -> let stats = eps_stats eps
853                              in eps { eps_stats = stats { n_decls_out = n_decls_out stats + 1 } })
854        }
855
856{-
857*********************************************************
858*                                                      *
859\subsection{Reading an interface file}
860*                                                      *
861*********************************************************
862
863Note [Home module load error]
864~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
865If the sought-for interface is in the current package (as determined
866by -package-name flag) then it jolly well should already be in the HPT
867because we process home-package modules in dependency order.  (Except
868in one-shot mode; see notes with hsc_HPT decl in HscTypes).
869
870It is possible (though hard) to get this error through user behaviour.
871  * Suppose package P (modules P1, P2) depends on package Q (modules Q1,
872    Q2, with Q2 importing Q1)
873  * We compile both packages.
874  * Now we edit package Q so that it somehow depends on P
875  * Now recompile Q with --make (without recompiling P).
876  * Then Q1 imports, say, P1, which in turn depends on Q2. So Q2
877    is a home-package module which is not yet in the HPT!  Disaster.
878
879This actually happened with P=base, Q=ghc-prim, via the AMP warnings.
880See #8320.
881-}
882
883findAndReadIface :: SDoc
884                 -- The unique identifier of the on-disk module we're
885                 -- looking for
886                 -> InstalledModule
887                 -- The *actual* module we're looking for.  We use
888                 -- this to check the consistency of the requirements
889                 -- of the module we read out.
890                 -> Module
891                 -> IsBootInterface     -- True  <=> Look for a .hi-boot file
892                                        -- False <=> Look for .hi file
893                 -> TcRnIf gbl lcl (MaybeErr MsgDoc (ModIface, FilePath))
894        -- Nothing <=> file not found, or unreadable, or illegible
895        -- Just x  <=> successfully found and parsed
896
897        -- It *doesn't* add an error to the monad, because
898        -- sometimes it's ok to fail... see notes with loadInterface
899findAndReadIface doc_str mod wanted_mod_with_insts hi_boot_file
900  = do traceIf (sep [hsep [text "Reading",
901                           if hi_boot_file
902                             then text "[boot]"
903                             else Outputable.empty,
904                           text "interface for",
905                           ppr mod <> semi],
906                     nest 4 (text "reason:" <+> doc_str)])
907
908       -- Check for GHC.Prim, and return its static interface
909       -- TODO: make this check a function
910       if mod `installedModuleEq` gHC_PRIM
911           then do
912               iface <- getHooked ghcPrimIfaceHook ghcPrimIface
913               return (Succeeded (iface,
914                                   "<built in interface for GHC.Prim>"))
915           else do
916               dflags <- getDynFlags
917               -- Look for the file
918               hsc_env <- getTopEnv
919               mb_found <- liftIO (findExactModule hsc_env mod)
920               case mb_found of
921                   InstalledFound loc mod -> do
922                       -- Found file, so read it
923                       let file_path = addBootSuffix_maybe hi_boot_file
924                                                           (ml_hi_file loc)
925
926                       -- See Note [Home module load error]
927                       if installedModuleUnitId mod `installedUnitIdEq` thisPackage dflags &&
928                          not (isOneShot (ghcMode dflags))
929                           then return (Failed (homeModError mod loc))
930                           else do r <- read_file file_path
931                                   checkBuildDynamicToo r
932                                   return r
933                   err -> do
934                       traceIf (text "...not found")
935                       dflags <- getDynFlags
936                       return (Failed (cannotFindInterface dflags
937                                           (installedModuleName mod) err))
938    where read_file file_path = do
939              traceIf (text "readIFace" <+> text file_path)
940              -- Figure out what is recorded in mi_module.  If this is
941              -- a fully definite interface, it'll match exactly, but
942              -- if it's indefinite, the inside will be uninstantiated!
943              dflags <- getDynFlags
944              let wanted_mod =
945                    case splitModuleInsts wanted_mod_with_insts of
946                        (_, Nothing) -> wanted_mod_with_insts
947                        (_, Just indef_mod) ->
948                          indefModuleToModule dflags
949                            (generalizeIndefModule indef_mod)
950              read_result <- readIface wanted_mod file_path
951              case read_result of
952                Failed err -> return (Failed (badIfaceFile file_path err))
953                Succeeded iface -> return (Succeeded (iface, file_path))
954                            -- Don't forget to fill in the package name...
955          checkBuildDynamicToo (Succeeded (iface, filePath)) = do
956              dflags <- getDynFlags
957              -- Indefinite interfaces are ALWAYS non-dynamic, and
958              -- that's OK.
959              let is_definite_iface = moduleIsDefinite (mi_module iface)
960              when is_definite_iface $
961                whenGeneratingDynamicToo dflags $ withDoDynamicToo $ do
962                  let ref = canGenerateDynamicToo dflags
963                      dynFilePath = addBootSuffix_maybe hi_boot_file
964                                  $ replaceExtension filePath (dynHiSuf dflags)
965                  r <- read_file dynFilePath
966                  case r of
967                      Succeeded (dynIface, _)
968                       | mi_mod_hash (mi_final_exts iface) == mi_mod_hash (mi_final_exts dynIface) ->
969                          return ()
970                       | otherwise ->
971                          do traceIf (text "Dynamic hash doesn't match")
972                             liftIO $ writeIORef ref False
973                      Failed err ->
974                          do traceIf (text "Failed to load dynamic interface file:" $$ err)
975                             liftIO $ writeIORef ref False
976          checkBuildDynamicToo _ = return ()
977
978-- @readIface@ tries just the one file.
979
980readIface :: Module -> FilePath
981          -> TcRnIf gbl lcl (MaybeErr MsgDoc ModIface)
982        -- Failed err    <=> file not found, or unreadable, or illegible
983        -- Succeeded iface <=> successfully found and parsed
984
985readIface wanted_mod file_path
986  = do  { res <- tryMostM $
987                 readBinIface CheckHiWay QuietBinIFaceReading file_path
988        ; dflags <- getDynFlags
989        ; case res of
990            Right iface
991                -- NB: This check is NOT just a sanity check, it is
992                -- critical for correctness of recompilation checking
993                -- (it lets us tell when -this-unit-id has changed.)
994                | wanted_mod == actual_mod
995                                -> return (Succeeded iface)
996                | otherwise     -> return (Failed err)
997                where
998                  actual_mod = mi_module iface
999                  err = hiModuleNameMismatchWarn dflags wanted_mod actual_mod
1000
1001            Left exn    -> return (Failed (text (showException exn)))
1002    }
1003
1004{-
1005*********************************************************
1006*                                                       *
1007        Wired-in interface for GHC.Prim
1008*                                                       *
1009*********************************************************
1010-}
1011
1012initExternalPackageState :: ExternalPackageState
1013initExternalPackageState
1014  = EPS {
1015      eps_is_boot          = emptyUFM,
1016      eps_PIT              = emptyPackageIfaceTable,
1017      eps_free_holes       = emptyInstalledModuleEnv,
1018      eps_PTE              = emptyTypeEnv,
1019      eps_inst_env         = emptyInstEnv,
1020      eps_fam_inst_env     = emptyFamInstEnv,
1021      eps_rule_base        = mkRuleBase builtinRules,
1022        -- Initialise the EPS rule pool with the built-in rules
1023      eps_mod_fam_inst_env
1024                           = emptyModuleEnv,
1025      eps_complete_matches = emptyUFM,
1026      eps_ann_env          = emptyAnnEnv,
1027      eps_stats = EpsStats { n_ifaces_in = 0, n_decls_in = 0, n_decls_out = 0
1028                           , n_insts_in = 0, n_insts_out = 0
1029                           , n_rules_in = length builtinRules, n_rules_out = 0 }
1030    }
1031
1032{-
1033*********************************************************
1034*                                                       *
1035        Wired-in interface for GHC.Prim
1036*                                                       *
1037*********************************************************
1038-}
1039
1040ghcPrimIface :: ModIface
1041ghcPrimIface
1042  = empty_iface {
1043        mi_exports  = ghcPrimExports,
1044        mi_decls    = [],
1045        mi_fixities = fixities,
1046        mi_final_exts = (mi_final_exts empty_iface){ mi_fix_fn = mkIfaceFixCache fixities }
1047        }
1048  where
1049    empty_iface = emptyFullModIface gHC_PRIM
1050
1051    -- The fixities listed here for @`seq`@ or @->@ should match
1052    -- those in primops.txt.pp (from which Haddock docs are generated).
1053    fixities = (getOccName seqId, Fixity NoSourceText 0 InfixR)
1054             : (occName funTyConName, funTyFixity)  -- trac #10145
1055             : mapMaybe mkFixity allThePrimOps
1056    mkFixity op = (,) (primOpOcc op) <$> primOpFixity op
1057
1058{-
1059*********************************************************
1060*                                                      *
1061\subsection{Statistics}
1062*                                                      *
1063*********************************************************
1064-}
1065
1066ifaceStats :: ExternalPackageState -> SDoc
1067ifaceStats eps
1068  = hcat [text "Renamer stats: ", msg]
1069  where
1070    stats = eps_stats eps
1071    msg = vcat
1072        [int (n_ifaces_in stats) <+> text "interfaces read",
1073         hsep [ int (n_decls_out stats), text "type/class/variable imported, out of",
1074                int (n_decls_in stats), text "read"],
1075         hsep [ int (n_insts_out stats), text "instance decls imported, out of",
1076                int (n_insts_in stats), text "read"],
1077         hsep [ int (n_rules_out stats), text "rule decls imported, out of",
1078                int (n_rules_in stats), text "read"]
1079        ]
1080
1081{-
1082************************************************************************
1083*                                                                      *
1084                Printing interfaces
1085*                                                                      *
1086************************************************************************
1087
1088Note [Name qualification with --show-iface]
1089~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1090
1091In order to disambiguate between identifiers from different modules, we qualify
1092all names that don't originate in the current module. In order to keep visual
1093noise as low as possible, we keep local names unqualified.
1094
1095For some background on this choice see trac #15269.
1096-}
1097
1098-- | Read binary interface, and print it out
1099showIface :: HscEnv -> FilePath -> IO ()
1100showIface hsc_env filename = do
1101   -- skip the hi way check; we don't want to worry about profiled vs.
1102   -- non-profiled interfaces, for example.
1103   iface <- initTcRnIf 's' hsc_env () () $
1104       readBinIface IgnoreHiWay TraceBinIFaceReading filename
1105   let dflags = hsc_dflags hsc_env
1106       -- See Note [Name qualification with --show-iface]
1107       qualifyImportedNames mod _
1108           | mod == mi_module iface = NameUnqual
1109           | otherwise              = NameNotInScope1
1110       print_unqual = QueryQualify qualifyImportedNames
1111                                   neverQualifyModules
1112                                   neverQualifyPackages
1113   putLogMsg dflags NoReason SevDump noSrcSpan
1114      (mkDumpStyle dflags print_unqual) (pprModIface iface)
1115
1116-- Show a ModIface but don't display details; suitable for ModIfaces stored in
1117-- the EPT.
1118pprModIfaceSimple :: ModIface -> SDoc
1119pprModIfaceSimple iface = ppr (mi_module iface) $$ pprDeps (mi_deps iface) $$ nest 2 (vcat (map pprExport (mi_exports iface)))
1120
1121pprModIface :: ModIface -> SDoc
1122-- Show a ModIface
1123pprModIface iface@ModIface{ mi_final_exts = exts }
1124 = vcat [ text "interface"
1125                <+> ppr (mi_module iface) <+> pp_hsc_src (mi_hsc_src iface)
1126                <+> (if mi_orphan exts then text "[orphan module]" else Outputable.empty)
1127                <+> (if mi_finsts exts then text "[family instance module]" else Outputable.empty)
1128                <+> (if mi_hpc iface then text "[hpc]" else Outputable.empty)
1129                <+> integer hiVersion
1130        , nest 2 (text "interface hash:" <+> ppr (mi_iface_hash exts))
1131        , nest 2 (text "ABI hash:" <+> ppr (mi_mod_hash exts))
1132        , nest 2 (text "export-list hash:" <+> ppr (mi_exp_hash exts))
1133        , nest 2 (text "orphan hash:" <+> ppr (mi_orphan_hash exts))
1134        , nest 2 (text "flag hash:" <+> ppr (mi_flag_hash exts))
1135        , nest 2 (text "opt_hash:" <+> ppr (mi_opt_hash exts))
1136        , nest 2 (text "hpc_hash:" <+> ppr (mi_hpc_hash exts))
1137        , nest 2 (text "plugin_hash:" <+> ppr (mi_plugin_hash exts))
1138        , nest 2 (text "sig of:" <+> ppr (mi_sig_of iface))
1139        , nest 2 (text "used TH splices:" <+> ppr (mi_used_th iface))
1140        , nest 2 (text "where")
1141        , text "exports:"
1142        , nest 2 (vcat (map pprExport (mi_exports iface)))
1143        , pprDeps (mi_deps iface)
1144        , vcat (map pprUsage (mi_usages iface))
1145        , vcat (map pprIfaceAnnotation (mi_anns iface))
1146        , pprFixities (mi_fixities iface)
1147        , vcat [ppr ver $$ nest 2 (ppr decl) | (ver,decl) <- mi_decls iface]
1148        , vcat (map ppr (mi_insts iface))
1149        , vcat (map ppr (mi_fam_insts iface))
1150        , vcat (map ppr (mi_rules iface))
1151        , ppr (mi_warns iface)
1152        , pprTrustInfo (mi_trust iface)
1153        , pprTrustPkg (mi_trust_pkg iface)
1154        , vcat (map ppr (mi_complete_sigs iface))
1155        , text "module header:" $$ nest 2 (ppr (mi_doc_hdr iface))
1156        , text "declaration docs:" $$ nest 2 (ppr (mi_decl_docs iface))
1157        , text "arg docs:" $$ nest 2 (ppr (mi_arg_docs iface))
1158        ]
1159  where
1160    pp_hsc_src HsBootFile = text "[boot]"
1161    pp_hsc_src HsigFile = text "[hsig]"
1162    pp_hsc_src HsSrcFile = Outputable.empty
1163
1164{-
1165When printing export lists, we print like this:
1166        Avail   f               f
1167        AvailTC C [C, x, y]     C(x,y)
1168        AvailTC C [x, y]        C!(x,y)         -- Exporting x, y but not C
1169-}
1170
1171pprExport :: IfaceExport -> SDoc
1172pprExport (Avail n)         = ppr n
1173pprExport (AvailTC _ [] []) = Outputable.empty
1174pprExport (AvailTC n ns0 fs)
1175  = case ns0 of
1176      (n':ns) | n==n' -> ppr n <> pp_export ns fs
1177      _               -> ppr n <> vbar <> pp_export ns0 fs
1178  where
1179    pp_export []    [] = Outputable.empty
1180    pp_export names fs = braces (hsep (map ppr names ++ map (ppr . flLabel) fs))
1181
1182pprUsage :: Usage -> SDoc
1183pprUsage usage@UsagePackageModule{}
1184  = pprUsageImport usage usg_mod
1185pprUsage usage@UsageHomeModule{}
1186  = pprUsageImport usage usg_mod_name $$
1187    nest 2 (
1188        maybe Outputable.empty (\v -> text "exports: " <> ppr v) (usg_exports usage) $$
1189        vcat [ ppr n <+> ppr v | (n,v) <- usg_entities usage ]
1190        )
1191pprUsage usage@UsageFile{}
1192  = hsep [text "addDependentFile",
1193          doubleQuotes (text (usg_file_path usage)),
1194          ppr (usg_file_hash usage)]
1195pprUsage usage@UsageMergedRequirement{}
1196  = hsep [text "merged", ppr (usg_mod usage), ppr (usg_mod_hash usage)]
1197
1198pprUsageImport :: Outputable a => Usage -> (Usage -> a) -> SDoc
1199pprUsageImport usage usg_mod'
1200  = hsep [text "import", safe, ppr (usg_mod' usage),
1201                       ppr (usg_mod_hash usage)]
1202    where
1203        safe | usg_safe usage = text "safe"
1204             | otherwise      = text " -/ "
1205
1206pprDeps :: Dependencies -> SDoc
1207pprDeps (Deps { dep_mods = mods, dep_pkgs = pkgs, dep_orphs = orphs,
1208                dep_finsts = finsts })
1209  = vcat [text "module dependencies:" <+> fsep (map ppr_mod mods),
1210          text "package dependencies:" <+> fsep (map ppr_pkg pkgs),
1211          text "orphans:" <+> fsep (map ppr orphs),
1212          text "family instance modules:" <+> fsep (map ppr finsts)
1213        ]
1214  where
1215    ppr_mod (mod_name, boot) = ppr mod_name <+> ppr_boot boot
1216    ppr_pkg (pkg,trust_req)  = ppr pkg <>
1217                               (if trust_req then text "*" else Outputable.empty)
1218    ppr_boot True  = text "[boot]"
1219    ppr_boot False = Outputable.empty
1220
1221pprFixities :: [(OccName, Fixity)] -> SDoc
1222pprFixities []    = Outputable.empty
1223pprFixities fixes = text "fixities" <+> pprWithCommas pprFix fixes
1224                  where
1225                    pprFix (occ,fix) = ppr fix <+> ppr occ
1226
1227pprTrustInfo :: IfaceTrustInfo -> SDoc
1228pprTrustInfo trust = text "trusted:" <+> ppr trust
1229
1230pprTrustPkg :: Bool -> SDoc
1231pprTrustPkg tpkg = text "require own pkg trusted:" <+> ppr tpkg
1232
1233instance Outputable Warnings where
1234    ppr = pprWarns
1235
1236pprWarns :: Warnings -> SDoc
1237pprWarns NoWarnings         = Outputable.empty
1238pprWarns (WarnAll txt)  = text "Warn all" <+> ppr txt
1239pprWarns (WarnSome prs) = text "Warnings"
1240                        <+> vcat (map pprWarning prs)
1241    where pprWarning (name, txt) = ppr name <+> ppr txt
1242
1243pprIfaceAnnotation :: IfaceAnnotation -> SDoc
1244pprIfaceAnnotation (IfaceAnnotation { ifAnnotatedTarget = target, ifAnnotatedValue = serialized })
1245  = ppr target <+> text "annotated by" <+> ppr serialized
1246
1247{-
1248*********************************************************
1249*                                                       *
1250\subsection{Errors}
1251*                                                       *
1252*********************************************************
1253-}
1254
1255badIfaceFile :: String -> SDoc -> SDoc
1256badIfaceFile file err
1257  = vcat [text "Bad interface file:" <+> text file,
1258          nest 4 err]
1259
1260hiModuleNameMismatchWarn :: DynFlags -> Module -> Module -> MsgDoc
1261hiModuleNameMismatchWarn dflags requested_mod read_mod
1262 | moduleUnitId requested_mod == moduleUnitId read_mod =
1263    sep [text "Interface file contains module" <+> quotes (ppr read_mod) <> comma,
1264         text "but we were expecting module" <+> quotes (ppr requested_mod),
1265         sep [text "Probable cause: the source code which generated interface file",
1266             text "has an incompatible module name"
1267            ]
1268        ]
1269 | otherwise =
1270  -- ToDo: This will fail to have enough qualification when the package IDs
1271  -- are the same
1272  withPprStyle (mkUserStyle dflags alwaysQualify AllTheWay) $
1273    -- we want the Modules below to be qualified with package names,
1274    -- so reset the PrintUnqualified setting.
1275    hsep [ text "Something is amiss; requested module "
1276         , ppr requested_mod
1277         , text "differs from name found in the interface file"
1278         , ppr read_mod
1279         , parens (text "if these names look the same, try again with -dppr-debug")
1280         ]
1281
1282homeModError :: InstalledModule -> ModLocation -> SDoc
1283-- See Note [Home module load error]
1284homeModError mod location
1285  = text "attempting to use module " <> quotes (ppr mod)
1286    <> (case ml_hs_file location of
1287           Just file -> space <> parens (text file)
1288           Nothing   -> Outputable.empty)
1289    <+> text "which is not loaded"
1290