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