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