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