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