[project @ 1998-01-08 18:03:08 by simonm]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcModule.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
3 %
4 \section[TcModule]{Typechecking a whole module}
5
6 \begin{code}
7 module TcModule (
8         typecheckModule,
9         TcResults,
10         TcDDumpDeriv
11     ) where
12
13 #include "HsVersions.h"
14
15 import CmdLineOpts      ( opt_D_dump_tc, opt_D_dump_deriv )
16 import HsSyn            ( HsModule(..), HsBinds(..), MonoBinds(..), HsDecl(..) )
17 import RnHsSyn          ( RenamedHsModule, RenamedFixityDecl(..) )
18 import TcHsSyn          ( TypecheckedHsBinds, TypecheckedHsExpr,
19                           TypecheckedDictBinds, TcMonoBinds,
20                           TypecheckedMonoBinds,
21                           zonkTopBinds )
22
23 import TcMonad
24 import Inst             ( Inst, emptyLIE, plusLIE )
25 import TcBinds          ( tcTopBindsAndThen )
26 import TcClassDcl       ( tcClassDecls2 )
27 import TcDefaults       ( tcDefaults )
28 import TcEnv            ( TcIdOcc(..), tcExtendGlobalValEnv, tcExtendTyConEnv, getEnv_LocalIds,
29                           getEnv_TyCons, getEnv_Classes, tcLookupLocalValue,
30                           tcLookupLocalValueByKey, tcLookupTyCon,
31                           tcLookupGlobalValueByKeyMaybe )
32 import TcExpr           ( tcId )
33 import TcIfaceSig       ( tcInterfaceSigs )
34 import TcInstDcls       ( tcInstDecls1, tcInstDecls2 )
35 import TcInstUtil       ( buildInstanceEnvs, classDataCon, InstInfo )
36 import TcSimplify       ( tcSimplifyTop )
37 import TcTyClsDecls     ( tcTyAndClassDecls1 )
38 import TcTyDecls        ( mkDataBinds )
39 import TcType           ( TcType, tcInstType )
40 import TcKind           ( TcKind, kindToTcKind )
41
42 import RnMonad          ( RnNameSupply(..) )
43 import Bag              ( isEmptyBag )
44 import ErrUtils         ( WarnMsg, ErrMsg, 
45                           pprBagOfErrors, dumpIfSet, ghcExit
46                         )
47 import Id               ( idType, GenId, IdEnv, nullIdEnv )
48 import Maybes           ( catMaybes, MaybeErr(..) )
49 import Name             ( Name, isLocallyDefined, pprModule, NamedThing(..) )
50 import TyCon            ( TyCon, isSynTyCon, tyConKind )
51 import Class            ( Class, classSelIds, classTyCon )
52 import Type             ( mkTyConApp, mkSynTy, Type )
53 import TyVar            ( emptyTyVarEnv )
54 import TysWiredIn       ( unitTy )
55 import PrelMods         ( gHC_MAIN, mAIN )
56 import PrelInfo         ( main_NAME, ioTyCon_NAME )
57 import Unify            ( unifyTauTy )
58 import UniqFM           ( lookupUFM_Directly, lookupWithDefaultUFM_Directly,
59                           filterUFM, eltsUFM )
60 import Unique           ( Unique  )
61 import UniqSupply       ( UniqSupply )
62 import Util
63 import Bag              ( Bag, isEmptyBag )
64 import FiniteMap        ( emptyFM, FiniteMap )
65 import Outputable
66 \end{code}
67
68 Outside-world interface:
69 \begin{code}
70
71 -- Convenient type synonyms first:
72 type TcResults
73   = (TypecheckedMonoBinds,
74      [TyCon], [Class],
75      Bag InstInfo,              -- Instance declaration information
76      TcDDumpDeriv)
77
78 type TcDDumpDeriv = SDoc
79
80 ---------------
81 typecheckModule
82         :: UniqSupply
83         -> RnNameSupply
84         -> RenamedHsModule
85         -> IO (Maybe TcResults)
86
87 typecheckModule us rn_name_supply mod
88   = let
89       (maybe_result, warns, errs) = initTc us (tcModule rn_name_supply mod)
90     in
91     print_errs warns    >>
92     print_errs errs     >>
93
94     dumpIfSet opt_D_dump_tc "Typechecked"
95         (case maybe_result of
96             Just (binds, _, _, _, _) -> ppr binds
97             Nothing                  -> text "Typecheck failed")        >>
98
99     dumpIfSet opt_D_dump_deriv "Derived instances"
100         (case maybe_result of
101             Just (_, _, _, _, dump_deriv) -> dump_deriv
102             Nothing                       -> empty)     >>
103
104     return (if isEmptyBag errs then 
105                 maybe_result 
106             else 
107                 Nothing)
108
109 print_errs errs
110   | isEmptyBag errs = return ()
111   | otherwise       = printErrs (pprBagOfErrors errs)
112 \end{code}
113
114 The internal monster:
115 \begin{code}
116 tcModule :: RnNameSupply        -- for renaming derivings
117          -> RenamedHsModule     -- input
118          -> TcM s TcResults     -- output
119
120 tcModule rn_name_supply
121         (HsModule mod_name verion exports imports fixities decls src_loc)
122   = tcAddSrcLoc src_loc $       -- record where we're starting
123
124     fixTc (\ ~(unf_env ,_) ->
125         -- unf_env is used for type-checking interface pragmas
126         -- which is done lazily [ie failure just drops the pragma
127         -- without having any global-failure effect].
128         -- 
129         -- unf_env is also used to get the pragam info for dfuns.
130
131             -- The knot for instance information.  This isn't used at all
132             -- till we type-check value declarations
133         fixTc ( \ ~(rec_inst_mapper, _, _, _, _) ->
134     
135                  -- Type-check the type and class decls
136                 -- trace "tcTyAndClassDecls:"   $
137                 tcTyAndClassDecls1 unf_env rec_inst_mapper decls        `thenTc` \ env ->
138     
139                 -- trace "tc3" $
140                     -- Typecheck the instance decls, includes deriving
141                 tcSetEnv env (
142                 -- trace "tcInstDecls:" $
143                 tcInstDecls1 unf_env decls mod_name rn_name_supply
144                 )                               `thenTc` \ (inst_info, deriv_binds, ddump_deriv) ->
145     
146                 -- trace "tc4" $
147                 buildInstanceEnvs inst_info     `thenNF_Tc` \ inst_mapper ->
148     
149                 returnTc (inst_mapper, env, inst_info, deriv_binds, ddump_deriv)
150     
151         -- End of inner fix loop
152         ) `thenTc` \ (_, env, inst_info, deriv_binds, ddump_deriv) ->
153     
154         -- trace "tc5" $
155         tcSetEnv env $
156         
157             -- Default declarations
158         tcDefaults decls                `thenTc` \ defaulting_tys ->
159         tcSetDefaultTys defaulting_tys  $
160         
161         -- Create any necessary record selector Ids and their bindings
162         -- "Necessary" includes data and newtype declarations
163         let
164             tycons       = getEnv_TyCons env
165             classes      = getEnv_Classes env
166             local_tycons  = filter isLocallyDefined tycons
167             local_classes = filter isLocallyDefined classes
168         in
169         mkDataBinds tycons              `thenTc` \ (data_ids, data_binds) ->
170         
171         -- Extend the global value environment with 
172         --      (a) constructors
173         --      (b) record selectors
174         --      (c) class op selectors
175         --      (d) default-method ids
176         tcExtendGlobalValEnv data_ids                           $
177         tcExtendGlobalValEnv (concat (map classSelIds classes)) $
178
179         -- Extend the TyCon envt with the tycons corresponding to
180         -- the classes, and the global value environment with the
181         -- corresponding data cons.
182         --  They are mentioned in types in interface files.
183         tcExtendGlobalValEnv (map classDataCon classes)         $
184         tcExtendTyConEnv [ (getName tycon, (kindToTcKind (tyConKind tycon), Nothing, tycon))
185                          | clas <- classes,
186                            let tycon = classTyCon clas
187                          ]                              $
188
189             -- Interface type signatures
190             -- We tie a knot so that the Ids read out of interfaces are in scope
191             --   when we read their pragmas.
192             -- What we rely on is that pragmas are typechecked lazily; if
193             --   any type errors are found (ie there's an inconsistency)
194             --   we silently discard the pragma
195         tcInterfaceSigs unf_env decls           `thenTc` \ sig_ids ->
196         tcExtendGlobalValEnv sig_ids            $
197
198
199         -- Value declarations next.
200         -- We also typecheck any extra binds that came out of the "deriving" process
201         -- trace "tcBinds:"                     $
202         tcTopBindsAndThen
203             (\ is_rec binds1 (binds2, thing) -> (binds1 `AndMonoBinds` binds2, thing))
204             (get_val_decls decls `ThenBinds` deriv_binds)
205             (   tcGetEnv                `thenNF_Tc` \ env ->
206                 returnTc ((EmptyMonoBinds, env), emptyLIE)
207             )                           `thenTc` \ ((val_binds, final_env), lie_valdecls) ->
208         tcSetEnv final_env $
209
210
211                 -- Second pass over class and instance declarations,
212                 -- to compile the bindings themselves.
213         -- trace "tc8" $
214         tcInstDecls2  inst_info         `thenNF_Tc` \ (lie_instdecls, inst_binds) ->
215         tcClassDecls2 decls             `thenNF_Tc` \ (lie_clasdecls, cls_binds) ->
216
217
218
219         -- Check that "main" has the right signature
220         tcCheckMainSig mod_name         `thenTc_` 
221
222              -- Deal with constant or ambiguous InstIds.  How could
223              -- there be ambiguous ones?  They can only arise if a
224              -- top-level decl falls under the monomorphism
225              -- restriction, and no subsequent decl instantiates its
226              -- type.  (Usually, ambiguous type variables are resolved
227              -- during the generalisation step.)
228         -- trace "tc9" $
229         let
230             lie_alldecls = lie_valdecls `plusLIE` lie_instdecls `plusLIE` lie_clasdecls
231         in
232         tcSimplifyTop lie_alldecls                      `thenTc` \ const_inst_binds ->
233
234
235             -- Backsubstitution.    This must be done last.
236             -- Even tcCheckMainSig and tcSimplifyTop may do some unification.
237         let
238             all_binds = data_binds              `AndMonoBinds` 
239                         val_binds               `AndMonoBinds`
240                         inst_binds              `AndMonoBinds`
241                         cls_binds               `AndMonoBinds`
242                         const_inst_binds
243         in
244         zonkTopBinds all_binds  `thenNF_Tc` \ (all_binds', really_final_env)  ->
245
246         returnTc (really_final_env, 
247                   (all_binds', local_tycons, local_classes, inst_info, ddump_deriv))
248
249     -- End of outer fix loop
250     ) `thenTc` \ (final_env, stuff) ->
251     returnTc stuff
252
253 get_val_decls decls = foldr ThenBinds EmptyBinds [binds | ValD binds <- decls]
254 \end{code}
255
256
257 \begin{code}
258 tcCheckMainSig mod_name
259   | mod_name /= mAIN
260   = returnTc ()         -- A non-main module
261
262   | otherwise
263   =     -- Check that main is defined
264     tcLookupTyCon ioTyCon_NAME          `thenTc`    \ (_,_,ioTyCon) ->
265     tcLookupLocalValue main_NAME        `thenNF_Tc` \ maybe_main_id ->
266     case maybe_main_id of {
267         Nothing  -> failWithTc noMainErr ;
268         Just main_id   ->
269
270         -- Check that it has the right type (or a more general one)
271     let 
272         expected_ty = mkTyConApp ioTyCon [unitTy]
273     in
274     tcInstType emptyTyVarEnv expected_ty        `thenNF_Tc` \ expected_tau ->
275     tcId main_NAME                              `thenNF_Tc` \ (_, lie, main_tau) ->
276     tcSetErrCtxt mainTyCheckCtxt $
277     unifyTauTy expected_tau
278                main_tau                 `thenTc_`
279     checkTc (isEmptyBag lie) (mainTyMisMatch expected_ty (idType main_id))
280     }
281
282
283 mainTyCheckCtxt
284   = hsep [ptext SLIT("When checking that"), ppr main_NAME, ptext SLIT("has the required type")]
285
286 noMainErr
287   = hsep [ptext SLIT("Module"), quotes (pprModule mAIN), 
288           ptext SLIT("must include a definition for"), quotes (ppr main_NAME)]
289
290 mainTyMisMatch :: Type -> TcType s -> ErrMsg
291 mainTyMisMatch expected actual
292   = hang (hsep [ppr main_NAME, ptext SLIT("has the wrong type")])
293          4 (vcat [
294                         hsep [ptext SLIT("Expected:"), ppr expected],
295                         hsep [ptext SLIT("Inferred:"), ppr actual]
296                      ])
297 \end{code}