[project @ 1999-01-18 19:04:55 by sof]
[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 )
15 import HsSyn            ( HsModule(..), HsBinds(..), MonoBinds(..), HsDecl(..) )
16 import RnHsSyn          ( RenamedHsModule )
17 import TcHsSyn          ( TcMonoBinds, TypecheckedMonoBinds, zonkTopBinds,
18                           TypecheckedForeignDecl, zonkForeignExports
19                         )
20
21 import TcMonad
22 import Inst             ( Inst, emptyLIE, plusLIE )
23 import TcBinds          ( tcTopBindsAndThen )
24 import TcClassDcl       ( tcClassDecls2 )
25 import TcDefaults       ( tcDefaults )
26 import TcEnv            ( tcExtendGlobalValEnv, tcExtendTypeEnv,
27                           getEnvTyCons, getEnvClasses, tcLookupValueMaybe,
28                           explicitLookupValueByKey, tcSetValueEnv,
29                           tcLookupTyCon, initEnv, 
30                           ValueEnv, TcTyThing(..)
31                         )
32 import TcExpr           ( tcId )
33 import TcForeign        ( tcForeignImports, tcForeignExports )
34 import TcIfaceSig       ( tcInterfaceSigs )
35 import TcInstDcls       ( tcInstDecls1, tcInstDecls2 )
36 import TcInstUtil       ( buildInstanceEnvs, classDataCon, InstInfo )
37 import TcSimplify       ( tcSimplifyTop )
38 import TcTyClsDecls     ( tcTyAndClassDecls )
39 import TcTyDecls        ( mkDataBinds )
40 import TcType           ( TcType, typeToTcType,
41                           TcKind, kindToTcKind,
42                           newTyVarTy
43                         )
44
45 import RnMonad          ( RnNameSupply )
46 import Bag              ( isEmptyBag )
47 import ErrUtils         ( Message,
48                           pprBagOfErrors, dumpIfSet
49                         )
50 import Id               ( Id, idType )
51 import Name             ( Name, nameUnique, isLocallyDefined, pprModule, NamedThing(..) )
52 import TyCon            ( TyCon, tyConKind )
53 import DataCon          ( dataConId )
54 import Class            ( Class, classSelIds, classTyCon )
55 import Type             ( mkTyConApp, mkForAllTy, mkTyVarTy, 
56                           boxedTypeKind, getTyVar, Type )
57 import TysWiredIn       ( unitTy )
58 import PrelMods         ( mAIN )
59 import PrelInfo         ( main_NAME, ioTyCon_NAME,
60                           thinAirIdNames, setThinAirIds
61                         )
62 import TcUnify          ( unifyTauTy )
63 import Unique           ( Unique  )
64 import UniqSupply       ( UniqSupply )
65 import Util
66 import Bag              ( Bag, isEmptyBag )
67 import Outputable
68
69 import IOExts
70 \end{code}
71
72 Outside-world interface:
73 \begin{code}
74
75 -- Convenient type synonyms first:
76 type TcResults
77   = (TypecheckedMonoBinds,
78      [TyCon], [Class],
79      Bag InstInfo,              -- Instance declaration information
80      [TypecheckedForeignDecl], -- foreign import & exports.
81      ValueEnv,
82      [Id]                       -- The thin-air Ids
83      )
84
85 ---------------
86 typecheckModule
87         :: UniqSupply
88         -> RnNameSupply
89         -> RenamedHsModule
90         -> IO (Maybe TcResults)
91
92 typecheckModule us rn_name_supply mod
93   = initTc us initEnv (tcModule rn_name_supply mod)     >>= \ (maybe_result, warns, errs) ->
94                 
95     print_errs warns    >>
96     print_errs errs     >>
97
98     -- write the thin-air Id map
99     (case maybe_result of
100         Just (_, _, _, _, _, _, thin_air_ids) -> setThinAirIds thin_air_ids
101         Nothing                               -> return ()
102     )                                                                   >>
103
104     dumpIfSet opt_D_dump_tc "Typechecked"
105         (case maybe_result of
106             Just (binds, _, _, _, _, _, _) -> ppr binds
107             Nothing                       -> text "Typecheck failed")   >>
108
109     return (if isEmptyBag errs then 
110                 maybe_result 
111             else 
112                 Nothing)
113
114 print_errs errs
115   | isEmptyBag errs = return ()
116   | otherwise       = printErrs (pprBagOfErrors errs)
117 \end{code}
118
119 The internal monster:
120 \begin{code}
121 tcModule :: RnNameSupply        -- for renaming derivings
122          -> RenamedHsModule     -- input
123          -> TcM s TcResults     -- output
124
125 tcModule rn_name_supply
126         (HsModule mod_name verion exports imports decls src_loc)
127   = tcAddSrcLoc src_loc $       -- record where we're starting
128
129     fixTc (\ ~(unf_env ,_) ->
130         -- unf_env is used for type-checking interface pragmas
131         -- which is done lazily [ie failure just drops the pragma
132         -- without having any global-failure effect].
133         -- 
134         -- unf_env is also used to get the pragam info
135         -- for imported dfuns and default methods
136
137             -- The knot for instance information.  This isn't used at all
138             -- till we type-check value declarations
139         fixTc ( \ ~(rec_inst_mapper, _, _, _) ->
140     
141                  -- Type-check the type and class decls
142                 tcTyAndClassDecls unf_env rec_inst_mapper decls `thenTc` \ env ->
143     
144                     -- Typecheck the instance decls, includes deriving
145                 tcSetEnv env (
146                 tcInstDecls1 unf_env decls mod_name rn_name_supply
147                 )                               `thenTc` \ (inst_info, deriv_binds) ->
148     
149                 buildInstanceEnvs inst_info     `thenNF_Tc` \ inst_mapper ->
150     
151                 returnTc (inst_mapper, env, inst_info, deriv_binds)
152     
153         -- End of inner fix loop
154         ) `thenTc` \ (_, env, inst_info, deriv_binds) ->
155     
156         tcSetEnv env            (
157         
158             -- Default declarations
159         tcDefaults decls                `thenTc` \ defaulting_tys ->
160         tcSetDefaultTys defaulting_tys  $
161         
162         -- Create any necessary record selector Ids and their bindings
163         -- "Necessary" includes data and newtype declarations
164         -- We don't create bindings for dictionary constructors;
165         -- they are always fully applied, and the bindings are just there
166         -- to support partial applications
167         let
168             tycons       = getEnvTyCons env
169             classes      = getEnvClasses env
170             local_tycons  = filter isLocallyDefined tycons
171             local_classes = filter isLocallyDefined classes
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         --      (d) default-method ids... where? I can't see where these are
180         --          put into the envt, and I'm worried that the zonking phase
181         --          will find they aren't there and complain.
182         tcExtendGlobalValEnv data_ids                           $
183         tcExtendGlobalValEnv (concat (map classSelIds classes)) $
184
185         -- Extend the TyCon envt with the tycons corresponding to
186         -- the classes, and the global value environment with the
187         -- corresponding data cons.
188         --  They are mentioned in types in interface files.
189         tcExtendGlobalValEnv (map (dataConId . classDataCon) classes)           $
190         tcExtendTypeEnv [ (getName tycon, (kindToTcKind (tyConKind tycon), Nothing, ATyCon tycon))
191                         | clas <- classes,
192                           let tycon = classTyCon clas
193                         ]                               $
194
195             -- Interface type signatures
196             -- We tie a knot so that the Ids read out of interfaces are in scope
197             --   when we read their pragmas.
198             -- What we rely on is that pragmas are typechecked lazily; if
199             --   any type errors are found (ie there's an inconsistency)
200             --   we silently discard the pragma
201         tcInterfaceSigs unf_env decls           `thenTc` \ sig_ids ->
202         tcExtendGlobalValEnv sig_ids            $
203
204             -- foreign import declarations next.
205         tcForeignImports decls          `thenTc`    \ (fo_ids, foi_decls) ->
206         tcExtendGlobalValEnv fo_ids             $
207
208         -- Value declarations next.
209         -- We also typecheck any extra binds that came out of the "deriving" process
210         tcTopBindsAndThen
211             (\ is_rec binds1 (binds2, thing) -> (binds1 `AndMonoBinds` binds2, thing))
212             (get_val_decls decls `ThenBinds` deriv_binds)
213             (   tcGetEnv                                `thenNF_Tc` \ env ->
214                 tcGetUnique                             `thenNF_Tc` \ uniq ->
215                 returnTc ((EmptyMonoBinds, env), emptyLIE)
216             )                           `thenTc` \ ((val_binds, final_env), lie_valdecls) ->
217         tcSetEnv final_env $
218
219             -- foreign export declarations next.
220         tcForeignExports decls          `thenTc`    \ (lie_fodecls, foe_binds, foe_decls) ->
221
222                 -- Second pass over class and instance declarations,
223                 -- to compile the bindings themselves.
224         tcInstDecls2  inst_info         `thenNF_Tc` \ (lie_instdecls, inst_binds) ->
225         tcClassDecls2 decls             `thenNF_Tc` \ (lie_clasdecls, cls_binds) ->
226
227         -- Check that "main" has the right signature
228         tcCheckMainSig mod_name         `thenTc_` 
229
230              -- Deal with constant or ambiguous InstIds.  How could
231              -- there be ambiguous ones?  They can only arise if a
232              -- top-level decl falls under the monomorphism
233              -- restriction, and no subsequent decl instantiates its
234              -- type.  (Usually, ambiguous type variables are resolved
235              -- during the generalisation step.)
236         let
237             lie_alldecls = lie_valdecls  `plusLIE`
238                            lie_instdecls `plusLIE`
239                            lie_clasdecls `plusLIE`
240                            lie_fodecls
241         in
242         tcSimplifyTop lie_alldecls                      `thenTc` \ const_inst_binds ->
243
244
245             -- Backsubstitution.    This must be done last.
246             -- Even tcCheckMainSig and tcSimplifyTop may do some unification.
247         let
248             all_binds = data_binds              `AndMonoBinds` 
249                         val_binds               `AndMonoBinds`
250                         inst_binds              `AndMonoBinds`
251                         cls_binds               `AndMonoBinds`
252                         const_inst_binds        `AndMonoBinds`
253                         foe_binds
254         in
255         zonkTopBinds all_binds          `thenNF_Tc` \ (all_binds', really_final_env)  ->
256         tcSetValueEnv really_final_env  $
257         zonkForeignExports foe_decls    `thenNF_Tc` \ foe_decls' ->
258
259         let
260            thin_air_ids = map (explicitLookupValueByKey really_final_env . nameUnique) thinAirIdNames
261                 -- When looking up the thin-air names we must use
262                 -- a global env that includes the zonked locally-defined Ids too
263                 -- Hence using really_final_env
264         in
265         returnTc (really_final_env, 
266                   (all_binds', local_tycons, local_classes, inst_info,
267                    foi_decls ++ foe_decls',
268                    really_final_env,
269                    thin_air_ids))
270         )
271
272     -- End of outer fix loop
273     ) `thenTc` \ (final_env, stuff) ->
274     returnTc stuff
275
276 get_val_decls decls = foldr ThenBinds EmptyBinds [binds | ValD binds <- decls]
277 \end{code}
278
279
280 \begin{code}
281 tcCheckMainSig mod_name
282   | mod_name /= mAIN
283   = returnTc ()         -- A non-main module
284
285   | otherwise
286   =     -- Check that main is defined
287     tcLookupTyCon ioTyCon_NAME          `thenTc`    \ ioTyCon ->
288     tcLookupValueMaybe main_NAME        `thenNF_Tc` \ maybe_main_id ->
289     case maybe_main_id of {
290         Nothing        -> failWithTc noMainErr ;
291         Just main_id   ->
292
293         -- Check that it has the right type (or a more general one)
294         -- As of Haskell 98, anything that unifies with (IO a) is OK.
295     newTyVarTy boxedTypeKind            `thenNF_Tc` \ t_tv ->
296     let 
297         tv           = getTyVar "tcCheckMainSig" t_tv
298         expected_tau = typeToTcType ((mkTyConApp ioTyCon [t_tv]))
299     in
300     tcId main_NAME                              `thenNF_Tc` \ (_, lie, main_tau) ->
301     tcSetErrCtxt mainTyCheckCtxt $
302     unifyTauTy expected_tau
303                main_tau                 `thenTc_`
304     checkTc (isEmptyBag lie) (mainTyMisMatch expected_tau (idType main_id))
305     }
306
307
308 mainTyCheckCtxt
309   = hsep [ptext SLIT("When checking that"), ppr main_NAME, ptext SLIT("has the required type")]
310
311 noMainErr
312   = hsep [ptext SLIT("Module"), quotes (pprModule mAIN), 
313           ptext SLIT("must include a definition for"), quotes (ppr main_NAME)]
314
315 mainTyMisMatch :: TcType -> TcType -> Message
316 mainTyMisMatch expected actual
317   = hang (hsep [ppr main_NAME, ptext SLIT("has the wrong type")])
318          4 (vcat [
319                         hsep [ptext SLIT("Expected:"), ppr expected],
320                         hsep [ptext SLIT("Inferred:"), ppr actual]
321                      ])
322 \end{code}