HscTypes.lhs 17.9 KB
Newer Older
1 2 3 4 5 6
%
% (c) The University of Glasgow, 2000
%
\section[HscTypes]{Types for the per-module compiler}

\begin{code}
7
module HscTypes ( 
8 9
	Finder, ModuleLocation(..),

10
	ModDetails(..),	ModIface(..), GlobalSymbolTable, 
11
	HomeSymbolTable, PackageSymbolTable,
12
	HomeIfaceTable, PackageIfaceTable, 
13
	lookupTable, lookupTableByModName,
14

15 16 17
	IfaceDecls(..), 

	VersionInfo(..), initialVersionInfo,
18

19 20 21 22
	TyThing(..), groupTyThings,

	TypeEnv, extendTypeEnv, lookupTypeEnv, 

23
	WhetherHasOrphans, ImportVersion, WhatsImported(..),
24
	PersistentRenamerState(..), IsBootInterface, Avails, DeclsMap,
25
	IfaceInsts, IfaceRules, GatedDecl,
26
	OrigNameEnv(..), OrigNameNameEnv, OrigNameIParamEnv,
27
	AvailEnv, AvailInfo, GenAvailInfo(..),
28
	PersistentCompilerState(..),
29

30 31
	Deprecations(..), lookupDeprec,

32
	InstEnv, ClsInstEnv, DFunId,
33
	PackageInstEnv, PackageRuleBase,
34

35
	GlobalRdrEnv, RdrAvailInfo,
36

37
	-- Provenance
38
	Provenance(..), ImportReason(..), PrintUnqualified,
39
        pprNameProvenance, hasBetterProv
40 41

    ) where
42 43 44

#include "HsVersions.h"

45
import RdrName		( RdrNameEnv, emptyRdrEnv )
46
import Name		( Name, NameEnv, NamedThing,
47
			  emptyNameEnv, unitNameEnv, extendNameEnv, plusNameEnv, 
48 49
			  lookupNameEnv, emptyNameEnv, getName, nameModule,
			  nameSrcLoc )
50
import NameSet		( NameSet )
51
import OccName		( OccName )
52
import Module		( Module, ModuleName, ModuleEnv,
53 54
			  lookupModuleEnv, lookupModuleEnvByName
			)
55
import Rules		( RuleBase )
56
import VarSet		( TyVarSet )
57
import VarEnv		( emptyVarEnv )
58 59
import Id		( Id )
import Class		( Class )
60
import TyCon		( TyCon )
61

62
import BasicTypes	( Version, initialVersion, Fixity )
63 64

import HsSyn		( DeprecTxt )
65 66
import RdrHsSyn		( RdrNameHsDecl, RdrNameTyClDecl )
import RnHsSyn		( RenamedTyClDecl, RenamedRuleDecl, RenamedInstDecl )
67

68
import CoreSyn		( CoreRule )
69
import Type		( Type )
70 71 72

import FiniteMap	( FiniteMap, emptyFM, addToFM, lookupFM, foldFM )
import Bag		( Bag )
73
import Maybes		( seqMaybe )
74
import UniqFM 		( UniqFM )
75 76
import Outputable
import SrcLoc		( SrcLoc, isGoodSrcLoc )
77
import Util		( thenCmp )
78
import UniqSupply	( UniqSupply )
79 80
\end{code}

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
%************************************************************************
%*									*
\subsection{The Finder type}
%*									*
%************************************************************************

\begin{code}
type Finder = ModuleName -> IO (Maybe (Module, ModuleLocation))

data ModuleLocation
   = ModuleLocation {
	hs_file  :: FilePath,
	hi_file  :: FilePath,
	obj_file :: FilePath
      }
\end{code}

For a module in another package, the hs_file and obj_file
components of ModuleLocation are undefined.  

The locations specified by a ModuleLocation may or may not
correspond to actual files yet: for example, even if the object
file doesn't exist, the ModuleLocation still contains the path to
where the object file will reside if/when it is created.


107 108
%************************************************************************
%*									*
109
\subsection{Symbol tables and Module details}
110 111 112
%*									*
%************************************************************************

113 114 115 116
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; it is the "linked" form of the mi_decls field.
117 118

\begin{code}
119 120 121 122 123
data ModIface 
   = ModIface {
        mi_module   :: Module,			-- Complete with package info
        mi_version  :: VersionInfo,		-- Module version number
        mi_orphan   :: WhetherHasOrphans,       -- Whether this module has orphans
124

125 126 127 128
        mi_usages   :: [ImportVersion Name],	-- Usages; kept sorted so that it's easy
						-- to decide whether to write a new iface file
						-- (changing usages doesn't affect the version of
						--  this module)
129

130 131
        mi_exports  :: Avails,			-- What it exports
						-- Kept sorted by (mod,occ),
132 133
						-- to make version comparisons easier

134
        mi_globals  :: GlobalRdrEnv,		-- Its top level environment
135

136
        mi_fixities :: NameEnv Fixity,		-- Fixities
137
	mi_deprecs  :: Deprecations,		-- Deprecations
138

139
	mi_decls    :: IfaceDecls		-- The RnDecls form of ModDetails
140
     }
141

142 143 144 145
data IfaceDecls = IfaceDecls { dcl_tycl  :: [RenamedTyClDecl],	-- Sorted
			       dcl_rules :: [RenamedRuleDecl],	-- Sorted
			       dcl_insts :: [RenamedInstDecl] }	-- Unsorted

146 147 148 149
-- typechecker should only look at this, not ModIface
-- Should be able to construct ModDetails from mi_decls in ModIface
data ModDetails
   = ModDetails {
150 151
	-- The next three fields are created by the typechecker
        md_types    :: TypeEnv,
152
        md_insts    :: [DFunId],	-- Dfun-ids for the instances in this module
153
        md_rules    :: [(Id,CoreRule)]	-- Domain may include Ids from other modules
154
     }
155 156 157
\end{code}

\begin{code}
158 159 160 161
emptyModDetails :: ModDetails
emptyModDetails
  = ModDetails { md_types = emptyTypeEnv,
                 md_insts = [],
162
                 md_rules = []
163 164 165 166 167 168 169
    }

emptyModIface :: Module -> ModIface
emptyModIface mod
  = ModIface { mi_module   = mod,
	       mi_exports  = [],
	       mi_globals  = emptyRdrEnv,
170
	       mi_deprecs  = NoDeprecs
171
    }		
172 173
\end{code}

174 175 176
Symbol tables map modules to ModDetails:

\begin{code}
177
type SymbolTable	= ModuleEnv ModDetails
178 179 180 181 182
type IfaceTable		= ModuleEnv ModIface

type HomeIfaceTable     = IfaceTable
type PackageIfaceTable  = IfaceTable

183 184 185
type HomeSymbolTable    = SymbolTable	-- Domain = modules in the home package
type PackageSymbolTable = SymbolTable	-- Domain = modules in the some other package
type GlobalSymbolTable  = SymbolTable	-- Domain = all modules
186 187
\end{code}

188
Simple lookups in the symbol table.
189 190

\begin{code}
191 192 193 194 195 196
lookupTable :: ModuleEnv a -> ModuleEnv a -> Name -> Maybe a
-- We often have two Symbol- or IfaceTables, and want to do a lookup
lookupTable ht pt name
  = lookupModuleEnv ht mod `seqMaybe` lookupModuleEnv pt mod
  where
    mod = nameModule name
197 198 199 200 201

lookupTableByModName :: ModuleEnv a -> ModuleEnv a -> ModuleName -> Maybe a
-- We often have two Symbol- or IfaceTables, and want to do a lookup
lookupTableByModName ht pt mod
  = lookupModuleEnvByName ht mod `seqMaybe` lookupModuleEnvByName pt mod
202 203 204 205 206 207 208 209 210 211 212
\end{code}


%************************************************************************
%*									*
\subsection{Type environment stuff}
%*									*
%************************************************************************

\begin{code}
type TypeEnv = NameEnv TyThing
213
emptyTypeEnv = emptyNameEnv
214 215 216 217

data TyThing = AnId   Id
	     | ATyCon TyCon
	     | AClass Class
218

219 220 221 222 223 224 225 226
instance NamedThing TyThing where
  getName (AnId id)   = getName id
  getName (ATyCon tc) = getName tc
  getName (AClass cl) = getName cl
\end{code}


\begin{code}
227 228 229
lookupTypeEnv :: SymbolTable -> Name -> Maybe TyThing
lookupTypeEnv tbl name
  = case lookupModuleEnv tbl (nameModule name) of
230
	Just details -> lookupNameEnv (md_types details) name
231
	Nothing	     -> Nothing
232 233


234 235
groupTyThings :: [TyThing] -> FiniteMap Module TypeEnv
  -- Finite map because we want the range too
236
groupTyThings things
237
  = foldl add emptyFM things
238 239 240 241 242 243 244 245 246 247
  where
    add :: FiniteMap Module TypeEnv -> TyThing -> FiniteMap Module TypeEnv
    add tbl thing = addToFM tbl mod new_env
		  where
		    name    = getName thing
		    mod     = nameModule name
		    new_env = case lookupFM tbl mod of
				Nothing  -> unitNameEnv name thing
				Just env -> extendNameEnv env name thing
		
248
extendTypeEnv :: SymbolTable -> FiniteMap Module TypeEnv -> SymbolTable
249
extendTypeEnv tbl things
250
  = foldFM add tbl things
251
  where
252
    add mod type_env tbl
253
	= panic "extendTypeEnv" --extendModuleEnv mod new_details
254
	where
255 256
	  new_details 
             = case lookupModuleEnv tbl mod of
257
                  Nothing      -> emptyModDetails {md_types = type_env}
258
                  Just details -> details {md_types = md_types details 
259
                                                     `plusNameEnv` type_env}
260 261 262 263 264 265 266 267 268 269 270
\end{code}


%************************************************************************
%*									*
\subsection{Auxiliary types}
%*									*
%************************************************************************

These types are defined here because they are mentioned in ModDetails,
but they are mostly elaborated elsewhere
271 272

\begin{code}
273 274
data VersionInfo 
  = VersionInfo {
275 276 277 278 279 280 281 282
	vers_module  :: Version,	-- Changes when anything changes
	vers_exports :: Version,	-- Changes when export list changes
	vers_rules   :: Version,	-- Changes when any rule changes
	vers_decls   :: NameEnv Version
		-- Versions for "big" names only (not data constructors, class ops)
		-- The version of an Id changes if its fixity changes
		-- Ditto data constructors, class operations, except that the version of
		-- the parent class/tycon changes
283
    }
284

285 286 287 288 289 290
initialVersionInfo :: VersionInfo
initialVersionInfo = VersionInfo { vers_module  = initialVersion,
				   vers_exports = initialVersion,
				   vers_rules   = initialVersion,
				   vers_decls   = emptyNameEnv }

291 292 293 294
data Deprecations = NoDeprecs
	 	  | DeprecAll DeprecTxt			-- Whole module deprecated
		  | DeprecSome (NameEnv DeprecTxt)	-- Some things deprecated
							-- Just "big" names
295

296 297 298 299 300 301 302
lookupDeprec :: ModIface -> Name -> Maybe DeprecTxt
lookupDeprec iface name
  = case mi_deprecs iface of
	NoDeprecs      -> Nothing
	DeprecAll txt  -> Just txt
	DeprecSome env -> lookupNameEnv env name

303
type InstEnv    = UniqFM ClsInstEnv		-- Maps Class to instances for that class
304

305 306
type ClsInstEnv = [(TyVarSet, [Type], DFunId)]	-- The instances for a particular class
type DFunId	= Id
307 308 309 310 311 312 313 314
\end{code}


\begin{code}
type Avails	  = [AvailInfo]
type AvailInfo    = GenAvailInfo Name
type RdrAvailInfo = GenAvailInfo OccName

315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
data GenAvailInfo name	= Avail name	 -- An ordinary identifier
			| AvailTC name 	 -- The name of the type or class
				  [name] -- The available pieces of type/class.
					 -- NB: If the type or class is itself
					 -- to be in scope, it must be in this list.
					 -- Thus, typically: AvailTC Eq [Eq, ==, /=]
			deriving( Eq )
			-- Equality used when deciding if the interface has changed

type AvailEnv	  = NameEnv AvailInfo	-- Maps a Name to the AvailInfo that contains it
\end{code}


%************************************************************************
%*									*
\subsection{ModIface}
%*									*
%************************************************************************

\begin{code}
335 336 337 338 339 340 341 342 343
type WhetherHasOrphans   = Bool
	-- An "orphan" is 
	-- 	* an instance decl in a module other than the defn module for 
	--		one of the tycons or classes in the instance head
	--	* a transformation rule in a module other than the one defining
	--		the function in the head of the rule.

type IsBootInterface     = Bool

344 345
type ImportVersion name  = (ModuleName, WhetherHasOrphans, IsBootInterface, WhatsImported name)

346 347 348
data WhatsImported name  = NothingAtAll				-- The module is below us in the
								-- hierarchy, but we import nothing

349 350 351 352 353 354 355 356
			 | Everything Version		-- Used for modules from other packages;
							-- we record only the module's version number

			 | Specifically 
				Version			-- Module version
				(Maybe Version)		-- Export-list version, if we depend on it
				[(name,Version)]	-- List guaranteed non-empty
				Version			-- Rules version
357 358

			 deriving( Eq )
359 360 361
	-- 'Specifically' doesn't let you say "I imported f but none of the rules in
	-- the module". If you use anything in the module you get its rule version
	-- So if the rules change, you'll recompile, even if you don't use them.
362 363 364
	-- This is easy to implement, and it's safer: you might not have used the rules last
	-- time round, but if someone has added a new rule you might need it this time

365 366 367 368
	-- The export list field is (Just v) if we depend on the export list:
	--	we imported the module without saying exactly what we imported
	-- We need to recompile if the module exports changes, because we might
	-- now have a name clash in the importing module.
369 370
\end{code}

371

372 373 374 375 376 377 378 379 380
%************************************************************************
%*									*
\subsection{The persistent compiler state}
%*									*
%************************************************************************

\begin{code}
data PersistentCompilerState 
   = PCS {
381 382
        pcs_PIT :: PackageIfaceTable,	-- Domain = non-home-package modules
					--   the mi_decls component is empty
383

384 385
        pcs_PST :: PackageSymbolTable,	-- Domain = non-home-package modules
					--   except that the InstEnv components is empty
386 387

	pcs_insts :: PackageInstEnv,	-- The total InstEnv accumulated from all
388
					--   the non-home-package modules
389

390
	pcs_rules :: PackageRuleBase,	-- Ditto RuleEnv
391

392
        pcs_PRS :: PersistentRenamerState
393
     }
394

395 396 397 398
\end{code}

The @PersistentRenamerState@ persists across successive calls to the
compiler.
399

400
It contains:
401
  * A name supply, which deals with allocating unique names to
402 403
    (Module,OccName) original names, 
 
404
  * An accumulated InstEnv from all the modules in pcs_PST
405 406 407 408 409 410 411 412 413
    The point is that we don't want to keep recreating it whenever
    we compile a new module.  The InstEnv component of pcPST is empty.
    (This means we might "see" instances that we shouldn't "really" see;
    but the Haskell Report is vague on what is meant to be visible, 
    so we just take the easy road here.)

  * Ditto for rules

  * A "holding pen" for declarations that have been read out of
414 415 416
    interface files but not yet sucked in, renamed, and typechecked

\begin{code}
417 418 419
type PackageRuleBase = RuleBase
type PackageInstEnv  = InstEnv

420
data PersistentRenamerState
421
  = PRS { prsOrig  :: OrigNameEnv,
422 423
	  prsDecls :: DeclsMap,
	  prsInsts :: IfaceInsts,
424 425
	  prsRules :: IfaceRules,
	  prsNS    :: UniqSupply
426
    }
427 428 429 430 431 432 433 434 435 436 437 438 439
\end{code}

The OrigNameEnv makes sure that there is just one Unique assigned for
each original name; i.e. (module-name, occ-name) pair.  The Name is
always stored as a Global, and has the SrcLoc of its binding location.
Actually that's not quite right.  When we first encounter the original
name, we might not be at its binding site (e.g. we are reading an
interface file); so we give it 'noSrcLoc' then.  Later, when we find
its binding site, we fix it up.

Exactly the same is true of the Module stored in the Name.  When we first
encounter the occurrence, we may not know the details of the module, so
we just store junk.  Then when we find the binding site, we fix it up.
440

441
\begin{code}
442
data OrigNameEnv
443 444 445 446
 = Orig { origNames  :: OrigNameNameEnv,
		-- Ensures that one original name gets one unique
	  origIParam :: OrigNameIParamEnv
		-- Ensures that one implicit parameter name gets one unique
447
   }
448 449 450

type OrigNameNameEnv   = FiniteMap (ModuleName,OccName) Name
type OrigNameIParamEnv = FiniteMap OccName Name
451
\end{code}
452

453 454 455 456 457 458

A DeclsMap contains a binding for each Name in the declaration
including the constructors of a type decl etc.  The Bool is True just
for the 'main' Name.

\begin{code}
459
type DeclsMap = NameEnv (AvailInfo, Bool, (Module, RdrNameTyClDecl))
460 461 462 463 464

type IfaceInsts = Bag GatedDecl
type IfaceRules = Bag GatedDecl

type GatedDecl = (NameSet, (Module, RdrNameHsDecl))
465 466
\end{code}

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
%************************************************************************
%*									*
\subsection{Provenance and export info}
%*									*
%************************************************************************

The GlobalRdrEnv gives maps RdrNames to Names.  There is a separate
one for each module, corresponding to that module's top-level scope.

\begin{code}
type GlobalRdrEnv = RdrNameEnv [(Name,Provenance)]	-- The list is because there may be name clashes
							-- These only get reported on lookup,
							-- not on construction
\end{code}

The "provenance" of something says how it came to be in scope.

\begin{code}
data Provenance
  = LocalDef			-- Defined locally

  | NonLocalDef  		-- Defined non-locally
	ImportReason
	PrintUnqualified

493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
-- Just used for grouping error messages (in RnEnv.warnUnusedBinds)
instance Eq Provenance where
  p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False

instance Eq ImportReason where
  p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False

instance Ord Provenance where
   compare LocalDef LocalDef = EQ
   compare LocalDef (NonLocalDef _ _) = LT
   compare (NonLocalDef _ _) LocalDef = GT

   compare (NonLocalDef reason1 _) (NonLocalDef reason2 _) 
      = compare reason1 reason2

instance Ord ImportReason where
   compare ImplicitImport ImplicitImport = EQ
   compare ImplicitImport (UserImport _ _ _) = LT
   compare (UserImport _ _ _) ImplicitImport = GT
   compare (UserImport m1 loc1 _) (UserImport m2 loc2 _) 
      = (m1 `compare` m2) `thenCmp` (loc1 `compare` loc2)


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
data ImportReason
  = UserImport Module SrcLoc Bool	-- Imported from module M on line L
					-- Note the M may well not be the defining module
					-- for this thing!
	-- The Bool is true iff the thing was named *explicitly* in the import spec,
	-- rather than being imported as part of a group; e.g.
	--	import B
	--	import C( T(..) )
	-- Here, everything imported by B, and the constructors of T
	-- are not named explicitly; only T is named explicitly.
	-- This info is used when warning of unused names.

  | ImplicitImport			-- Imported implicitly for some other reason
			

type PrintUnqualified = Bool	-- True <=> the unqualified name of this thing is
				-- in scope in this module, so print it 
				-- unqualified in error messages
\end{code}

\begin{code}
hasBetterProv :: Provenance -> Provenance -> Bool
-- Choose 
--	a local thing		      over an	imported thing
--	a user-imported thing	      over a	non-user-imported thing
-- 	an explicitly-imported thing  over an	implicitly imported thing
hasBetterProv LocalDef 				    _				   = True
hasBetterProv (NonLocalDef (UserImport _ _ True) _) _				   = True
hasBetterProv (NonLocalDef (UserImport _ _ _   ) _) (NonLocalDef ImplicitImport _) = True
hasBetterProv _					    _				   = False

547
pprNameProvenance :: Name -> Provenance -> SDoc
548
pprNameProvenance name LocalDef   	   = ptext SLIT("defined at") <+> ppr (nameSrcLoc name)
549
pprNameProvenance name (NonLocalDef why _) = sep [ppr_reason why, 
550 551 552 553 554 555 556 557
					      nest 2 (parens (ppr_defn (nameSrcLoc name)))]

ppr_reason ImplicitImport	  = ptext SLIT("implicitly imported")
ppr_reason (UserImport mod loc _) = ptext SLIT("imported from") <+> ppr mod <+> ptext SLIT("at") <+> ppr loc

ppr_defn loc | isGoodSrcLoc loc = ptext SLIT("at") <+> ppr loc
	     | otherwise	= empty
\end{code}