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