[project @ 2000-10-23 12:55:31 by sewardj]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcModule.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[TcModule]{Typechecking a whole module}
5
6 \begin{code}
7 module TcModule (
8         typecheckModule,
9         TcResults(..)
10     ) where
11
12 #include "HsVersions.h"
13
14 import CmdLineOpts      ( DynFlag(..), DynFlags, opt_PprStyle_Debug )
15 import HsSyn            ( HsModule(..), HsBinds(..), MonoBinds(..), HsDecl(..) )
16 import HsTypes          ( toHsType )
17 import RnHsSyn          ( RenamedHsModule, RenamedHsDecl )
18 import TcHsSyn          ( TypecheckedMonoBinds, 
19                           TypecheckedForeignDecl, TypecheckedRuleDecl,
20                           zonkTopBinds, zonkForeignExports, zonkRules
21                         )
22
23 import TcMonad
24 import Inst             ( emptyLIE, plusLIE )
25 import TcBinds          ( tcTopBinds )
26 import TcClassDcl       ( tcClassDecls2, mkImplicitClassBinds )
27 import TcDefaults       ( tcDefaults )
28 import TcEnv            ( TcEnv, tcExtendGlobalValEnv, tcLookupGlobal_maybe,
29                           tcEnvTyCons, tcEnvClasses, 
30                           tcSetEnv, tcSetInstEnv, initTcEnv, getTcGEnv
31                         )
32 import TcRules          ( tcRules )
33 import TcForeign        ( tcForeignImports, tcForeignExports )
34 import TcIfaceSig       ( tcInterfaceSigs )
35 import TcInstDcls       ( tcInstDecls1, tcInstDecls2 )
36 import InstEnv          ( InstInfo(..) )
37 import TcSimplify       ( tcSimplifyTop )
38 import TcTyClsDecls     ( tcTyAndClassDecls )
39 import TcTyDecls        ( mkImplicitDataBinds )
40
41 import CoreUnfold       ( unfoldingTemplate )
42 import Type             ( funResultTy, splitForAllTys )
43 import Bag              ( isEmptyBag )
44 import ErrUtils         ( printErrorsAndWarnings, dumpIfSet_dyn )
45 import Id               ( idType, idName, idUnfolding )
46 import Module           ( Module, moduleName, plusModuleEnv )
47 import Name             ( nameOccName, isLocallyDefined, isGlobalName,
48                           toRdrName, nameEnvElts, emptyNameEnv
49                         )
50 import TyCon            ( TyCon, isDataTyCon, tyConName, tyConGenInfo )
51 import OccName          ( isSysOcc )
52 import TyCon            ( TyCon, isClassTyCon )
53 import Class            ( Class )
54 import PrelNames        ( mAIN_Name, mainName )
55 import UniqSupply       ( UniqSupply )
56 import Maybes           ( maybeToBool )
57 import Util
58 import BasicTypes       ( EP(..) )
59 import Bag              ( Bag, isEmptyBag )
60 import Outputable
61 import HscTypes         ( PersistentCompilerState(..), HomeSymbolTable, 
62                           PackageSymbolTable, DFunId, 
63                           TypeEnv, extendTypeEnv,
64                           TyThing(..), groupTyThings )
65 import FiniteMap        ( FiniteMap, delFromFM, lookupWithDefaultFM )
66 \end{code}
67
68 Outside-world interface:
69 \begin{code}
70
71 -- Convenient type synonyms first:
72 data TcResults
73   = TcResults {
74         tc_pcs     :: PersistentCompilerState,  -- Augmented with imported information,
75                                                 -- (but not stuff from this module)
76         tc_env     :: TypeEnv,                  -- The TypeEnv just for the stuff from this module
77         tc_insts   :: [DFunId],                 -- Instances, just for this module
78         tc_binds   :: TypecheckedMonoBinds,
79         tc_fords   :: [TypecheckedForeignDecl], -- Foreign import & exports.
80         tc_rules   :: [TypecheckedRuleDecl]     -- Transformation rules
81     }
82
83 ---------------
84 typecheckModule
85         :: DynFlags
86         -> Module
87         -> PersistentCompilerState
88         -> HomeSymbolTable
89         -> HomeIfaceTable
90         -> PackageIfaceTable
91         -> RenamedHsModule
92         -> IO (Maybe (TcEnv, TcResults))
93
94 typecheckModule dflags this_mod pcs hst hit pit (HsModule mod_name _ _ _ decls _ src_loc)
95   = do env <- initTcEnv global_symbol_table
96        (maybe_result, (errs,warns)) <- initTc dflags env src_loc tc_module
97        printErrorsAndWarnings (errs,warns)
98        printTcDump dflags maybe_result
99        if isEmptyBag errs then 
100           return Nothing 
101          else 
102           return maybe_result
103   where
104     global_symbol_table = pcs_PST pcs `plusModuleEnv` hst
105
106     tc_module = fixTc (\ ~(unf_env ,_) 
107                          -> tcModule pcs hst get_fixity this_mod decls unf_env)
108
109     get_fixity :: Name -> Maybe Fixity
110     get_fixity nm
111        = case lookupFixityEnv hit nm of
112             Just f  -> Just f
113             Nothing -> lookupFixityEnv pit nm
114 \end{code}
115
116 The internal monster:
117 \begin{code}
118 tcModule :: PersistentCompilerState
119          -> HomeSymbolTable
120          -> (Name -> Maybe Fixity)
121          -> Module
122          -> [RenamedHsDecl]
123          -> TcEnv               -- The knot-tied environment
124          -> TcM (TcEnv, TcResults)
125
126   -- (unf_env :: TcEnv) is used for type-checking interface pragmas
127   -- which is done lazily [ie failure just drops the pragma
128   -- without having any global-failure effect].
129   -- 
130   -- unf_env is also used to get the pragama info
131   -- for imported dfuns and default methods
132
133 tcModule pcs hst get_fixity this_mod decls unf_env
134   =              -- Type-check the type and class decls
135     tcTyAndClassDecls unf_env decls             `thenTc` \ env ->
136     tcSetEnv env                                $
137     let
138         classes       = tcEnvClasses env
139         tycons        = tcEnvTyCons env -- INCLUDES tycons derived from classes
140         local_classes = filter isLocallyDefined classes
141         local_tycons  = [ tc | tc <- tycons,
142                                isLocallyDefined tc,
143                                not (isClassTyCon tc)
144                         ]
145                         -- For local_tycons, filter out the ones derived from classes
146                         -- Otherwise the latter show up in interface files
147     in
148     
149         -- Typecheck the instance decls, includes deriving
150     tcInstDecls1 pcs hst unf_env get_fixity this_mod 
151                  local_tycons decls             `thenTc` \ (pcs_with_insts, inst_env, inst_info, deriv_binds) ->
152     tcSetInstEnv inst_env                       $
153     
154         -- Default declarations
155     tcDefaults decls                    `thenTc` \ defaulting_tys ->
156     tcSetDefaultTys defaulting_tys      $
157     
158     -- Interface type signatures
159     -- We tie a knot so that the Ids read out of interfaces are in scope
160     --   when we read their pragmas.
161     -- What we rely on is that pragmas are typechecked lazily; if
162     --   any type errors are found (ie there's an inconsistency)
163     --   we silently discard the pragma
164     -- We must do this before mkImplicitDataBinds (which comes next), since
165     -- the latter looks up unpackCStringId, for example, which is usually 
166     -- imported
167     tcInterfaceSigs unf_env decls               `thenTc` \ sig_ids ->
168     tcExtendGlobalValEnv sig_ids                $
169     
170     -- Create any necessary record selector Ids and their bindings
171     -- "Necessary" includes data and newtype declarations
172     -- We don't create bindings for dictionary constructors;
173     -- they are always fully applied, and the bindings are just there
174     -- to support partial applications
175     mkImplicitDataBinds tycons                  `thenTc`    \ (data_ids, imp_data_binds) ->
176     mkImplicitClassBinds classes                `thenNF_Tc` \ (cls_ids,  imp_cls_binds) ->
177     
178     -- Extend the global value environment with 
179     --  (a) constructors
180     --  (b) record selectors
181     --  (c) class op selectors
182     --  (d) default-method ids... where? I can't see where these are
183     --      put into the envt, and I'm worried that the zonking phase
184     --      will find they aren't there and complain.
185     tcExtendGlobalValEnv data_ids               $
186     tcExtendGlobalValEnv cls_ids                $
187     
188         -- Foreign import declarations next
189     tcForeignImports decls                      `thenTc`    \ (fo_ids, foi_decls) ->
190     tcExtendGlobalValEnv fo_ids                 $
191     
192     -- Value declarations next.
193     -- We also typecheck any extra binds that came out of the "deriving" process
194     tcTopBinds (get_binds decls `ThenBinds` deriv_binds)        `thenTc` \ ((val_binds, env), lie_valdecls) ->
195     tcSetEnv env $
196     
197         -- Foreign export declarations next
198     tcForeignExports decls              `thenTc`    \ (lie_fodecls, foe_binds, foe_decls) ->
199     
200         -- Second pass over class and instance declarations,
201         -- to compile the bindings themselves.
202     tcInstDecls2  inst_info             `thenNF_Tc` \ (lie_instdecls, inst_binds) ->
203     tcClassDecls2 decls                 `thenNF_Tc` \ (lie_clasdecls, cls_dm_binds) ->
204     tcRules decls                       `thenNF_Tc` \ (lie_rules,     rules) ->
205     
206          -- Deal with constant or ambiguous InstIds.  How could
207          -- there be ambiguous ones?  They can only arise if a
208          -- top-level decl falls under the monomorphism
209          -- restriction, and no subsequent decl instantiates its
210          -- type.  (Usually, ambiguous type variables are resolved
211          -- during the generalisation step.)
212     let
213         lie_alldecls = lie_valdecls     `plusLIE`
214                    lie_instdecls        `plusLIE`
215                    lie_clasdecls        `plusLIE`
216                    lie_fodecls          `plusLIE`
217                    lie_rules
218     in
219     tcSimplifyTop lie_alldecls                  `thenTc` \ const_inst_binds ->
220     
221         -- Check that Main defines main
222     checkMain this_mod                          `thenTc_`
223     
224         -- Backsubstitution.    This must be done last.
225         -- Even tcSimplifyTop may do some unification.
226     let
227         all_binds = imp_data_binds      `AndMonoBinds` 
228                     imp_cls_binds       `AndMonoBinds` 
229                     val_binds           `AndMonoBinds`
230                     inst_binds          `AndMonoBinds`
231                     cls_dm_binds        `AndMonoBinds`
232                     const_inst_binds    `AndMonoBinds`
233                     foe_binds
234     in
235     zonkTopBinds all_binds              `thenNF_Tc` \ (all_binds', final_env)  ->
236     tcSetEnv final_env                  $
237         -- zonkTopBinds puts all the top-level Ids into the tcGEnv
238     zonkForeignExports foe_decls        `thenNF_Tc` \ foe_decls' ->
239     zonkRules rules                     `thenNF_Tc` \ rules' ->
240     
241     
242     let groups :: FiniteMap Module TypeEnv
243         groups = groupTyThings (nameEnvElts (getTcGEnv final_env))
244     
245         local_type_env :: TypeEnv
246         local_type_env = lookupWithDefaultFM groups emptyNameEnv this_mod 
247     
248         new_pst :: PackageSymbolTable
249         new_pst = extendTypeEnv (pcs_PST pcs) (delFromFM groups this_mod)
250
251         final_pcs :: PersistentCompilerState
252         final_pcs = pcs_with_insts {pcs_PST = new_pst}
253     in  
254     returnTc (final_env, -- WAS: really_final_env, 
255               TcResults { tc_pcs     = final_pcs,
256                           tc_env     = local_type_env,
257                           tc_binds   = all_binds', 
258                           tc_insts   = map iDFunId inst_info,
259                           tc_fords   = foi_decls ++ foe_decls',
260                           tc_rules   = rules'
261                         })
262
263 get_binds decls = foldr ThenBinds EmptyBinds [binds | ValD binds <- decls]
264 \end{code}
265
266
267 \begin{code}
268 checkMain :: Module -> TcM ()
269 checkMain this_mod 
270   | moduleName this_mod == mAIN_Name 
271   = tcLookupGlobal_maybe mainName               `thenNF_Tc` \ maybe_main ->
272     case maybe_main of
273         Just (AnId _) -> returnTc ()
274         other         -> addErrTc noMainErr
275
276   | otherwise = returnTc ()
277
278 noMainErr
279   = hsep [ptext SLIT("Module"), quotes (ppr mAIN_Name), 
280           ptext SLIT("must include a definition for"), quotes (ptext SLIT("main"))]
281 \end{code}
282
283
284 %************************************************************************
285 %*                                                                      *
286 \subsection{Dumping output}
287 %*                                                                      *
288 %************************************************************************
289
290 \begin{code}
291 printTcDump dflags Nothing = return ()
292 printTcDump dflags (Just (_,results))
293   = do dumpIfSet_dyn dflags Opt_D_dump_types 
294                      "Type signatures" (dump_sigs results)
295        dumpIfSet_dyn dflags Opt_D_dump_tc    
296                      "Typechecked" (dump_tc results) 
297
298 dump_tc results
299   = vcat [ppr (tc_binds results),
300           pp_rules (tc_rules results) --,
301 --        ppr_gen_tycons (tc_tycons results)
302     ]
303
304 dump_sigs results       -- Print type signatures
305   =     -- Convert to HsType so that we get source-language style printing
306         -- And sort by RdrName
307     vcat $ map ppr_sig $ sortLt lt_sig $
308     [(toRdrName id, toHsType (idType id))
309         | AnId id <- nameEnvElts (tc_env results), 
310           want_sig id
311     ]
312   where
313     lt_sig (n1,_) (n2,_) = n1 < n2
314     ppr_sig (n,t)        = ppr n <+> dcolon <+> ppr t
315
316     want_sig id | opt_PprStyle_Debug = True
317                 | otherwise          = isLocallyDefined n && 
318                                        isGlobalName n && 
319                                        not (isSysOcc (nameOccName n))
320                                      where
321                                        n = idName id
322
323 ppr_gen_tycons tcs = vcat [ptext SLIT("{-# Generic type constructor details"),
324                            vcat (map ppr_gen_tycon (filter isLocallyDefined tcs)),
325                            ptext SLIT("#-}")
326                      ]
327
328 -- x&y are now Id's, not CoreExpr's 
329 ppr_gen_tycon tycon 
330   | Just ep <- tyConGenInfo tycon
331   = (ppr tycon <> colon) $$ nest 4 (ppr_ep ep)
332
333   | otherwise = ppr tycon <> colon <+> ptext SLIT("Not derivable")
334
335 ppr_ep (EP from to)
336   = vcat [ ptext SLIT("Rep type:") <+> ppr (funResultTy from_tau),
337            ptext SLIT("From:") <+> ppr (unfoldingTemplate (idUnfolding from)),
338            ptext SLIT("To:")   <+> ppr (unfoldingTemplate (idUnfolding to))
339     ]
340   where
341     (_,from_tau) = splitForAllTys (idType from)
342
343 pp_rules [] = empty
344 pp_rules rs = vcat [ptext SLIT("{-# RULES"),
345                     nest 4 (vcat (map ppr rs)),
346                     ptext SLIT("#-}")]
347 \end{code}