[project @ 2000-07-11 16:24:57 by simonmar]
[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, opt_D_dump_types, opt_PprStyle_Debug )
15 import HsSyn            ( HsModule(..), HsBinds(..), MonoBinds(..), HsDecl(..) )
16 import HsTypes          ( toHsType )
17 import RnHsSyn          ( RenamedHsModule )
18 import TcHsSyn          ( TcMonoBinds, TypecheckedMonoBinds, 
19                           TypecheckedForeignDecl, TypecheckedRuleDecl,
20                           zonkTopBinds, zonkForeignExports, zonkRules
21                         )
22
23 import TcMonad
24 import Inst             ( Inst, emptyLIE, plusLIE )
25 import TcBinds          ( tcTopBindsAndThen )
26 import TcClassDcl       ( tcClassDecls2, mkImplicitClassBinds )
27 import TcDefaults       ( tcDefaults )
28 import TcEnv            ( tcExtendGlobalValEnv, tcExtendTypeEnv,
29                           getEnvTyCons, getEnvClasses, tcLookupValueByKeyMaybe,
30                           explicitLookupValueByKey, tcSetValueEnv, tcSetInstEnv,
31                           initEnv, 
32                           ValueEnv, TcTyThing(..)
33                         )
34 import TcRules          ( tcRules )
35 import TcForeign        ( tcForeignImports, tcForeignExports )
36 import TcIfaceSig       ( tcInterfaceSigs )
37 import TcInstDcls       ( tcInstDecls1, tcInstDecls2 )
38 import TcInstUtil       ( buildInstanceEnv, InstInfo )
39 import TcSimplify       ( tcSimplifyTop )
40 import TcTyClsDecls     ( tcTyAndClassDecls )
41 import TcTyDecls        ( mkImplicitDataBinds )
42 import TcType           ( TcType, typeToTcType,
43                           TcKind, kindToTcKind,
44                           newTyVarTy
45                         )
46
47 import RnMonad          ( RnNameSupply, FixityEnv )
48 import Bag              ( isEmptyBag )
49 import ErrUtils         ( Message, printErrorsAndWarnings, dumpIfSet )
50 import Id               ( Id, idType, idName )
51 import Module           ( pprModuleName )
52 import OccName          ( isSysOcc )
53 import Name             ( Name, nameUnique, nameOccName, isLocallyDefined, 
54                           toRdrName, nameEnvElts, NamedThing(..)
55                         )
56 import TyCon            ( TyCon, tyConKind )
57 import Class            ( Class, classSelIds, classTyCon )
58 import PrelInfo         ( mAIN_Name )
59 import Unique           ( Unique, mainKey )
60 import UniqSupply       ( UniqSupply )
61 import Maybes           ( maybeToBool )
62 import Util
63 import Bag              ( Bag, isEmptyBag )
64 import Outputable
65 \end{code}
66
67 Outside-world interface:
68 \begin{code}
69
70 -- Convenient type synonyms first:
71 data TcResults
72   = TcResults {
73         tc_binds   :: TypecheckedMonoBinds,
74         tc_tycons  :: [TyCon],
75         tc_classes :: [Class],
76         tc_insts   :: Bag InstInfo,             -- Instance declaration information
77         tc_fords   :: [TypecheckedForeignDecl], -- Foreign import & exports.
78         tc_rules   :: [TypecheckedRuleDecl],    -- Transformation rules
79         tc_env     :: ValueEnv
80     }
81
82 ---------------
83 typecheckModule
84         :: UniqSupply
85         -> RnNameSupply
86         -> FixityEnv
87         -> RenamedHsModule
88         -> IO (Maybe TcResults)
89
90 typecheckModule us rn_name_supply fixity_env mod
91   = initTc us initEnv (tcModule rn_name_supply fixity_env mod)  >>= \ (maybe_result, warns, errs) ->
92                 
93     printErrorsAndWarnings errs warns           >>
94         
95     (case maybe_result of
96         Nothing -> return ()
97         Just results -> dumpIfSet opt_D_dump_types "Type signatures" (dump_sigs results) >>
98                         dumpIfSet opt_D_dump_tc    "Typechecked"     (dump_tc   results)
99     )                                           >>
100                         
101     return (if isEmptyBag errs then 
102                 maybe_result 
103             else 
104                 Nothing)
105
106 dump_tc results
107   = ppr (tc_binds results) $$ pp_rules (tc_rules results) 
108
109 dump_sigs results       -- Print type signatures
110   =     -- Convert to HsType so that we get source-language style printing
111         -- And sort by RdrName
112     vcat $ map ppr_sig $ sortLt lt_sig $
113     [(toRdrName id, toHsType (idType id)) | id <- nameEnvElts (tc_env results), 
114                                             want_sig id
115     ]
116   where
117     lt_sig (n1,_) (n2,_) = n1 < n2
118     ppr_sig (n,t)        = ppr n <+> dcolon <+> ppr t
119
120     want_sig id | opt_PprStyle_Debug = True
121                 | otherwise          = isLocallyDefined n && not (isSysOcc (nameOccName n))
122                                      where
123                                        n = idName id
124
125 pp_rules [] = empty
126 pp_rules rs = vcat [ptext SLIT("{-# RULES"),
127                     nest 4 (vcat (map ppr rs)),
128                     ptext SLIT("#-}")]
129 \end{code}
130
131 The internal monster:
132 \begin{code}
133 tcModule :: RnNameSupply        -- for renaming derivings
134          -> FixityEnv           -- needed for Show/Read derivings.
135          -> RenamedHsModule     -- input
136          -> TcM s TcResults     -- output
137
138 tcModule rn_name_supply fixities
139         (HsModule mod_name _ _ _ decls _ src_loc)
140   = tcAddSrcLoc src_loc $       -- record where we're starting
141
142     fixTc (\ ~(unf_env ,_) ->
143         -- unf_env is used for type-checking interface pragmas
144         -- which is done lazily [ie failure just drops the pragma
145         -- without having any global-failure effect].
146         -- 
147         -- unf_env is also used to get the pragam info
148         -- for imported dfuns and default methods
149
150                  -- Type-check the type and class decls
151         tcTyAndClassDecls unf_env decls `thenTc` \ env ->
152     
153                     -- Typecheck the instance decls, includes deriving
154         tcSetEnv env $
155
156         tcInstDecls1 unf_env decls 
157                      mod_name fixities 
158                      rn_name_supply     `thenTc` \ (inst_info, deriv_binds) ->
159     
160         buildInstanceEnv inst_info      `thenNF_Tc` \ inst_env ->
161
162         tcSetInstEnv inst_env $
163         let
164             tycons       = getEnvTyCons env
165             classes      = getEnvClasses env
166             local_tycons  = filter isLocallyDefined tycons
167             local_classes = filter isLocallyDefined classes
168         in
169         
170             -- Default declarations
171         tcDefaults decls                `thenTc` \ defaulting_tys ->
172         tcSetDefaultTys defaulting_tys  $
173         
174         -- Extend the TyCon envt with the tycons corresponding to
175         -- the classes.
176         --  They are mentioned in types in interface files.
177         tcExtendTypeEnv [ (getName tycon, (kindToTcKind (tyConKind tycon), ADataTyCon tycon))
178                         | clas <- classes,
179                           let tycon = classTyCon clas
180                         ]                               $
181
182         -- Interface type signatures
183         -- We tie a knot so that the Ids read out of interfaces are in scope
184         --   when we read their pragmas.
185         -- What we rely on is that pragmas are typechecked lazily; if
186         --   any type errors are found (ie there's an inconsistency)
187         --   we silently discard the pragma
188         -- We must do this before mkImplicitDataBinds (which comes next), since
189         -- the latter looks up unpackCStringId, for example, which is usually 
190         -- imported
191         tcInterfaceSigs unf_env decls           `thenTc` \ sig_ids ->
192         tcExtendGlobalValEnv sig_ids            $
193
194         -- Create any necessary record selector Ids and their bindings
195         -- "Necessary" includes data and newtype declarations
196         -- We don't create bindings for dictionary constructors;
197         -- they are always fully applied, and the bindings are just there
198         -- to support partial applications
199         mkImplicitDataBinds tycons              `thenTc`    \ (data_ids, imp_data_binds) ->
200         mkImplicitClassBinds classes            `thenNF_Tc` \ (cls_ids,  imp_cls_binds) ->
201         
202         -- Extend the global value environment with 
203         --      (a) constructors
204         --      (b) record selectors
205         --      (c) class op selectors
206         --      (d) default-method ids... where? I can't see where these are
207         --          put into the envt, and I'm worried that the zonking phase
208         --          will find they aren't there and complain.
209         tcExtendGlobalValEnv data_ids           $
210         tcExtendGlobalValEnv cls_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_dm_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                 tcLookupValueByKeyMaybe mainKey         `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 = imp_data_binds          `AndMonoBinds` 
264                         imp_cls_binds           `AndMonoBinds` 
265                         val_binds               `AndMonoBinds`
266                         inst_binds              `AndMonoBinds`
267                         cls_dm_binds            `AndMonoBinds`
268                         const_inst_binds        `AndMonoBinds`
269                         foe_binds
270         in
271         zonkTopBinds all_binds          `thenNF_Tc` \ (all_binds', really_final_env)  ->
272         tcSetValueEnv really_final_env  $
273         zonkForeignExports foe_decls    `thenNF_Tc` \ foe_decls' ->
274         zonkRules rules                 `thenNF_Tc` \ rules' ->
275
276         returnTc (really_final_env, 
277                   (TcResults {  tc_binds   = all_binds', 
278                                 tc_tycons  = local_tycons,
279                                 tc_classes = local_classes,
280                                 tc_insts   = inst_info,
281                                 tc_fords   = foi_decls ++ foe_decls',
282                                 tc_rules   = rules',
283                                 tc_env     = really_final_env
284                  }))
285
286     -- End of outer fix loop
287     ) `thenTc` \ (final_env, stuff) ->
288     returnTc stuff
289
290 get_val_decls decls = foldr ThenBinds EmptyBinds [binds | ValD binds <- decls]
291 \end{code}
292
293
294 \begin{code}
295 noMainErr
296   = hsep [ptext SLIT("Module"), quotes (pprModuleName mAIN_Name), 
297           ptext SLIT("must include a definition for"), quotes (ptext SLIT("main"))]
298 \end{code}
299