a5c3197f5ac008def5ef860d5c9f126fa775dd76
[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 #include "HsVersions.h"
8
9 module TcModule (
10         typecheckModule,
11         SYN_IE(TcResults),
12         SYN_IE(TcResultBinds),
13         SYN_IE(TcSpecialiseRequests),
14         SYN_IE(TcDDumpDeriv)
15     ) where
16
17 IMP_Ubiq(){-uitous-}
18
19 import HsSyn            ( HsDecl(..), HsModule(..), HsBinds(..), Bind, HsExpr,
20                           TyDecl, SpecDataSig, ClassDecl, InstDecl, IfaceSig,
21                           SpecInstSig, DefaultDecl, Sig, Fake, InPat,
22                           FixityDecl, IE, ImportDecl
23                         )
24 import RnHsSyn          ( SYN_IE(RenamedHsModule), RenamedFixityDecl(..) )
25 import TcHsSyn          ( SYN_IE(TypecheckedHsBinds), SYN_IE(TypecheckedHsExpr),
26                           TcIdOcc(..), zonkBinds, zonkDictBinds )
27
28 import TcMonad
29 import Inst             ( Inst, plusLIE )
30 import TcBinds          ( tcBindsAndThen )
31 import TcClassDcl       ( tcClassDecls2 )
32 import TcDefaults       ( tcDefaults )
33 import TcEnv            ( tcExtendGlobalValEnv, getEnv_LocalIds,
34                           getEnv_TyCons, getEnv_Classes, tcLookupLocalValue,
35                           tcLookupLocalValueByKey, tcLookupTyCon,
36                           tcLookupGlobalValueByKeyMaybe )
37 import SpecEnv          ( SpecEnv )
38 import TcExpr           ( tcId )
39 import TcIfaceSig       ( tcInterfaceSigs )
40 import TcInstDcls       ( tcInstDecls1, tcInstDecls2 )
41 import TcInstUtil       ( buildInstanceEnvs, InstInfo )
42 import TcSimplify       ( tcSimplifyTop )
43 import TcTyClsDecls     ( tcTyAndClassDecls1 )
44 import TcTyDecls        ( mkDataBinds )
45 import TcType           ( SYN_IE(TcType), tcInstType )
46 import TcKind           ( TcKind )
47
48 import RnMonad          ( RnNameSupply(..) )
49 import Bag              ( listToBag )
50 import Class            ( GenClass, classSelIds )
51 import ErrUtils         ( SYN_IE(Warning), SYN_IE(Error) )
52 import Id               ( idType, GenId, SYN_IE(IdEnv), nullIdEnv )
53 import Maybes           ( catMaybes )
54 import Name             ( Name, isLocallyDefined, pprModule )
55 import Pretty
56 import TyCon            ( TyCon, isSynTyCon )
57 import Type             ( applyTyCon, mkSynTy )
58 import PprType          ( GenType, GenTyVar )
59 import TysWiredIn       ( unitTy )
60 import PrelMods         ( gHC_MAIN, mAIN )
61 import PrelInfo         ( main_NAME, mainPrimIO_NAME, ioTyCon_NAME, primIoTyCon_NAME )
62 import TyVar            ( GenTyVar, SYN_IE(TyVarEnv), nullTyVarEnv )
63 import Unify            ( unifyTauTy )
64 import UniqFM           ( lookupUFM_Directly, lookupWithDefaultUFM_Directly,
65                           filterUFM, eltsUFM )
66 import Unique           ( Unique  )
67 import Util
68 import Bag              ( Bag, isEmptyBag )
69
70 import FiniteMap        ( emptyFM, FiniteMap )
71 tycon_specs = emptyFM
72 \end{code}
73
74 Outside-world interface:
75 \begin{code}
76 -- Convenient type synonyms first:
77 type TcResults
78   = (TcResultBinds,
79      [TyCon], 
80      Bag InstInfo,              -- Instance declaration information
81      TcSpecialiseRequests,
82      TcDDumpDeriv)
83
84 type TcResultBinds
85   = (TypecheckedHsBinds,        -- record selector binds
86      TypecheckedHsBinds,        -- binds from class decls; does NOT
87                                 -- include default-methods bindings
88      TypecheckedHsBinds,        -- binds from instance decls; INCLUDES
89                                 -- class default-methods binds
90      TypecheckedHsBinds,        -- binds from value decls
91
92      [(Id, TypecheckedHsExpr)]) -- constant instance binds
93
94 type TcSpecialiseRequests
95   = FiniteMap TyCon [(Bool, [Maybe Type])]
96     -- source tycon specialisation requests
97
98 type TcDDumpDeriv
99   = PprStyle -> Pretty
100
101 ---------------
102 typecheckModule
103         :: UniqSupply
104         -> RnNameSupply
105         -> RenamedHsModule
106         -> MaybeErr
107             (TcResults,         -- if all goes well...
108              Bag Warning)       -- (we can still get warnings)
109             (Bag Error,         -- if we had errors...
110              Bag Warning)
111
112 typecheckModule us rn_name_supply mod
113   = initTc us (tcModule rn_name_supply mod)
114 \end{code}
115
116 The internal monster:
117 \begin{code}
118 tcModule :: RnNameSupply        -- for renaming derivings
119          -> RenamedHsModule     -- input
120          -> TcM s TcResults     -- output
121
122 tcModule rn_name_supply
123         (HsModule mod_name verion exports imports fixities decls src_loc)
124   = tcAddSrcLoc src_loc $       -- record where we're starting
125
126         -- Tie the knot for inteface-file value declaration signatures
127         -- This info is only used inside the knot for type-checking the
128         -- pragmas, which is done lazily [ie failure just drops the pragma
129         -- without having any global-failure effect].
130
131     -- trace "tc1" $
132
133     fixTc (\ ~(_, _, _, _, _, _, sig_ids) ->
134
135         -- trace "tc2" $
136         tcExtendGlobalValEnv sig_ids (
137
138         -- The knot for instance information.  This isn't used at all
139         -- till we type-check value declarations
140         fixTc ( \ ~(rec_inst_mapper, _, _, _, _) ->
141
142              -- Type-check the type and class decls
143             -- trace "tcTyAndClassDecls:"       $
144             tcTyAndClassDecls1 rec_inst_mapper decls    `thenTc` \ env ->
145
146             -- trace "tc3" $
147                 -- Typecheck the instance decls, includes deriving
148             tcSetEnv env (
149             -- trace "tcInstDecls:"     $
150             tcInstDecls1 decls mod_name rn_name_supply
151             )                                   `thenTc` \ (inst_info, deriv_binds, ddump_deriv) ->
152
153             -- trace "tc4" $
154             buildInstanceEnvs inst_info `thenTc` \ inst_mapper ->
155
156             returnTc (inst_mapper, env, inst_info, deriv_binds, ddump_deriv)
157
158         ) `thenTc` \ (_, env, inst_info, deriv_binds, ddump_deriv) ->
159
160         -- trace "tc5" $
161         tcSetEnv env (
162
163             -- Default declarations
164         tcDefaults decls                `thenTc` \ defaulting_tys ->
165         tcSetDefaultTys defaulting_tys  ( -- for the iface sigs...
166
167         -- Create any necessary record selector Ids and their bindings
168         -- "Necessary" includes data and newtype declarations
169         let
170                 tycons   = getEnv_TyCons env
171                 classes  = getEnv_Classes env
172         in
173         mkDataBinds tycons              `thenTc` \ (data_ids, data_binds) ->
174
175         -- Extend the global value environment with 
176         --      a) constructors
177         --      b) record selectors
178         --      c) class op selectors
179         tcExtendGlobalValEnv data_ids                           $
180         tcExtendGlobalValEnv (concat (map classSelIds classes)) $
181
182             -- Interface type signatures
183             -- We tie a knot so that the Ids read out of interfaces are in scope
184             --   when we read their pragmas.
185             -- What we rely on is that pragmas are typechecked lazily; if
186             --   any type errors are found (ie there's an inconsistency)
187             --   we silently discard the pragma
188         tcInterfaceSigs decls           `thenTc` \ sig_ids ->
189         tcGetEnv                        `thenNF_Tc` \ env ->
190         -- trace "tc6" $
191
192         returnTc (env, inst_info, data_binds, deriv_binds, ddump_deriv, defaulting_tys, sig_ids)
193
194     )))) `thenTc` \ (env, inst_info, data_binds, deriv_binds, ddump_deriv, defaulting_tys, _) ->
195
196     -- trace "tc7" $
197     tcSetEnv env (                              -- to the end...
198     tcSetDefaultTys defaulting_tys (            -- ditto
199
200         -- Value declarations next.
201         -- We also typecheck any extra binds that came out of the "deriving" process
202     -- trace "tcBinds:"                 $
203     tcBindsAndThen
204         (\ binds1 (binds2, thing) -> (binds1 `ThenBinds` binds2, thing))
205         (get_val_decls decls `ThenBinds` deriv_binds)
206         (       -- Second pass over instance declarations,
207                 -- to compile the bindings themselves.
208             -- trace "tc8" $
209             tcInstDecls2  inst_info     `thenNF_Tc` \ (lie_instdecls, inst_binds) ->
210             tcClassDecls2 decls         `thenNF_Tc` \ (lie_clasdecls, cls_binds) ->
211             tcCheckMainSig mod_name     `thenTc_` 
212             tcGetEnv                    `thenNF_Tc` \ env ->
213             returnTc ( (EmptyBinds, (inst_binds, cls_binds, env)),
214                        lie_instdecls `plusLIE` lie_clasdecls,
215                        () ))
216
217         `thenTc` \ ((val_binds, (inst_binds, cls_binds, final_env)), lie_alldecls, _) ->
218
219         -- Deal with constant or ambiguous InstIds.  How could
220         -- there be ambiguous ones?  They can only arise if a
221         -- top-level decl falls under the monomorphism
222         -- restriction, and no subsequent decl instantiates its
223         -- type.  (Usually, ambiguous type variables are resolved
224         -- during the generalisation step.)
225     -- trace "tc9" $
226     tcSimplifyTop lie_alldecls                  `thenTc` \ const_insts ->
227
228
229         -- Backsubstitution.  Monomorphic top-level decls may have
230         -- been instantiated by subsequent decls, and the final
231         -- simplification step may have instantiated some
232         -- ambiguous types.  So, sadly, we need to back-substitute
233         -- over the whole bunch of bindings.
234         -- 
235         -- More horrible still, we have to do it in a careful order, so that
236         -- all the TcIds are in scope when we come across them.
237         -- 
238         -- These bindings ought really to be bundled together in a huge
239         -- recursive group, but HsSyn doesn't have recursion among Binds, only
240         -- among MonoBinds.  Sigh again.
241     zonkDictBinds nullTyVarEnv nullIdEnv const_insts    `thenNF_Tc` \ (const_insts', ve1) ->
242     zonkBinds nullTyVarEnv ve1 val_binds                `thenNF_Tc` \ (val_binds', ve2) ->
243
244     zonkBinds nullTyVarEnv ve2 data_binds       `thenNF_Tc` \ (data_binds', _) ->
245     zonkBinds nullTyVarEnv ve2 inst_binds       `thenNF_Tc` \ (inst_binds', _) ->
246     zonkBinds nullTyVarEnv ve2 cls_binds        `thenNF_Tc` \ (cls_binds', _) ->
247
248     let
249         localids = getEnv_LocalIds final_env
250         tycons   = getEnv_TyCons   final_env
251         classes  = getEnv_Classes  final_env
252
253         local_tycons  = filter isLocallyDefined tycons
254         local_classes = filter isLocallyDefined classes
255     in
256         -- FINISHED AT LAST
257     returnTc (
258         (data_binds', cls_binds', inst_binds', val_binds', const_insts'),
259
260         local_tycons, inst_info, tycon_specs,
261
262         ddump_deriv
263     )))
264
265 get_val_decls decls = foldr ThenBinds EmptyBinds [binds | ValD binds <- decls]
266 \end{code}
267
268
269 \begin{code}
270 tcCheckMainSig mod_name
271   | not is_main && not is_ghc_main
272   = returnTc ()         -- A non-main module
273
274   | otherwise
275   =     -- Check that main is defined
276     tcLookupTyCon tycon_name                    `thenTc` \ (_,_,tycon) ->
277     tcLookupLocalValue main_name                `thenNF_Tc` \ maybe_main_id ->
278     case maybe_main_id of {
279         Nothing  -> failTc (noMainErr mod_name main_name);
280         Just main_id   ->
281
282         -- Check that it has the right type (or a more general one)
283     let
284         expected_ty | isSynTyCon tycon = mkSynTy tycon [unitTy]
285                     | otherwise        = applyTyCon tycon [unitTy]
286                 -- This is bizarre.  There ought to be a suitable function in Type.lhs!
287     in
288     tcInstType [] expected_ty                   `thenNF_Tc` \ expected_tau ->
289     tcId main_name                              `thenNF_Tc` \ (_, lie, main_tau) ->
290     tcSetErrCtxt (mainTyCheckCtxt main_name) $
291     unifyTauTy expected_tau
292                main_tau                         `thenTc_`
293     checkTc (isEmptyBag lie) (mainTyMisMatch main_name expected_ty (idType main_id))
294     }
295   where
296     is_main     = mod_name == mAIN
297     is_ghc_main = mod_name == gHC_MAIN
298
299     main_name | is_main   = main_NAME
300               | otherwise = mainPrimIO_NAME
301
302     tycon_name | is_main   = ioTyCon_NAME
303                | otherwise = primIoTyCon_NAME
304
305 mainTyCheckCtxt main_name sty
306   = ppCat [ppStr "When checking that", ppr sty main_name, ppStr "has the required type"]
307
308 noMainErr mod_name main_name sty
309   = ppCat [ppStr "Module", pprModule sty mod_name, 
310            ppStr "must include a definition for", ppr sty main_name]
311
312 mainTyMisMatch :: Name -> Type -> TcType s -> Error
313 mainTyMisMatch main_name expected actual sty
314   = ppHang (ppCat [ppr sty main_name, ppStr "has the wrong type"])
315          4 (ppAboves [
316                         ppCat [ppStr "Expected:", ppr sty expected],
317                         ppCat [ppStr "Inferred:", ppr sty actual]
318                      ])
319 \end{code}