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