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