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