[project @ 2000-09-28 15:15:48 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, 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          ( TypecheckedMonoBinds, 
19                           TypecheckedForeignDecl, TypecheckedRuleDecl,
20                           zonkTopBinds, zonkForeignExports, zonkRules
21                         )
22
23 import TcMonad
24 import Inst             ( emptyLIE, plusLIE )
25 import TcBinds          ( tcTopBindsAndThen )
26 import TcClassDcl       ( tcClassDecls2, mkImplicitClassBinds )
27 import TcDefaults       ( tcDefaults )
28 import TcEnv            ( tcExtendGlobalValEnv, 
29                           getEnvTyCons, getEnvClasses, tcLookupValueByKeyMaybe,
30                           tcSetValueEnv, tcSetInstEnv, initEnv, 
31                           ValueEnv, 
32                         )
33 import TcRules          ( tcRules )
34 import TcForeign        ( tcForeignImports, tcForeignExports )
35 import TcIfaceSig       ( tcInterfaceSigs )
36 import TcInstDcls       ( tcInstDecls1, tcInstDecls2 )
37 import TcInstUtil       ( buildInstanceEnv, InstInfo )
38 import TcSimplify       ( tcSimplifyTop )
39 import TcTyClsDecls     ( tcTyAndClassDecls )
40 import TcTyDecls        ( mkImplicitDataBinds )
41
42 import RnMonad          ( RnNameSupply, FixityEnv )
43 import Bag              ( isEmptyBag )
44 import ErrUtils         ( printErrorsAndWarnings, dumpIfSet )
45 import Id               ( idType, idName )
46 import Module           ( pprModuleName, mkThisModule )
47 import Name             ( nameOccName, isLocallyDefined, isGlobalName,
48                           toRdrName, nameEnvElts, 
49                         )
50 import OccName          ( isSysOcc )
51 import TyCon            ( TyCon, isClassTyCon )
52 import Class            ( Class )
53 import PrelNames        ( mAIN_Name, mainKey )
54 import UniqSupply       ( UniqSupply )
55 import Maybes           ( maybeToBool )
56 import Util
57 import Bag              ( Bag, isEmptyBag )
58 import Outputable
59 \end{code}
60
61 Outside-world interface:
62 \begin{code}
63
64 -- Convenient type synonyms first:
65 data TcResults
66   = TcResults {
67         tc_binds   :: TypecheckedMonoBinds,
68         tc_tycons  :: [TyCon],
69         tc_classes :: [Class],
70         tc_insts   :: Bag InstInfo,             -- Instance declaration information
71         tc_fords   :: [TypecheckedForeignDecl], -- Foreign import & exports.
72         tc_rules   :: [TypecheckedRuleDecl],    -- Transformation rules
73         tc_env     :: ValueEnv
74     }
75
76 ---------------
77 typecheckModule
78         :: UniqSupply
79         -> RnNameSupply
80         -> FixityEnv
81         -> RenamedHsModule
82         -> IO (Maybe TcResults)
83
84 typecheckModule us rn_name_supply fixity_env mod
85   = initTc us initEnv (tcModule rn_name_supply fixity_env mod)  >>= \ (maybe_result, warns, errs) ->
86                 
87     printErrorsAndWarnings errs warns           >>
88         
89     (case maybe_result of
90         Nothing -> return ()
91         Just results -> dumpIfSet opt_D_dump_types "Type signatures" (dump_sigs results) >>
92                         dumpIfSet opt_D_dump_tc    "Typechecked"     (dump_tc   results)
93     )                                           >>
94                         
95     return (if isEmptyBag errs then 
96                 maybe_result 
97             else 
98                 Nothing)
99
100 dump_tc results
101   = ppr (tc_binds results) $$ pp_rules (tc_rules results) 
102
103 dump_sigs results       -- Print type signatures
104   =     -- Convert to HsType so that we get source-language style printing
105         -- And sort by RdrName
106     vcat $ map ppr_sig $ sortLt lt_sig $
107     [(toRdrName id, toHsType (idType id)) | id <- nameEnvElts (tc_env results), 
108                                             want_sig id
109     ]
110   where
111     lt_sig (n1,_) (n2,_) = n1 < n2
112     ppr_sig (n,t)        = ppr n <+> dcolon <+> ppr t
113
114     want_sig id | opt_PprStyle_Debug = True
115                 | otherwise          = isLocallyDefined n && 
116                                        isGlobalName n && 
117                                        not (isSysOcc (nameOccName n))
118                                      where
119                                        n = idName id
120
121 pp_rules [] = empty
122 pp_rules rs = vcat [ptext SLIT("{-# RULES"),
123                     nest 4 (vcat (map ppr rs)),
124                     ptext SLIT("#-}")]
125 \end{code}
126
127 The internal monster:
128 \begin{code}
129 tcModule :: RnNameSupply        -- for renaming derivings
130          -> FixityEnv           -- needed for Show/Read derivings.
131          -> RenamedHsModule     -- input
132          -> TcM s TcResults     -- output
133
134 tcModule rn_name_supply fixities
135         (HsModule mod_name _ _ _ decls _ src_loc)
136   = tcAddSrcLoc src_loc $       -- record where we're starting
137
138     fixTc (\ ~(unf_env ,_) ->
139         -- unf_env is used for type-checking interface pragmas
140         -- which is done lazily [ie failure just drops the pragma
141         -- without having any global-failure effect].
142         -- 
143         -- unf_env is also used to get the pragam info
144         -- for imported dfuns and default methods
145
146                  -- Type-check the type and class decls
147         tcTyAndClassDecls unf_env decls `thenTc` \ env ->
148     
149                  -- Typecheck the instance decls, includes deriving
150         tcSetEnv env $
151
152         tcInstDecls1 unf_env decls 
153                      (mkThisModule mod_name)
154                      fixities rn_name_supply    `thenTc` \ (inst_info, deriv_binds) ->
155     
156         buildInstanceEnv inst_info      `thenNF_Tc` \ inst_env ->
157
158         tcSetInstEnv inst_env $
159         let
160             classes      = getEnvClasses env
161             tycons       = getEnvTyCons env     -- INCLUDES tycons derived from classes
162             local_classes = filter isLocallyDefined classes
163             local_tycons  = [ tc | tc <- tycons,
164                                    isLocallyDefined tc,
165                                    not (isClassTyCon tc)
166                             ]
167                                 -- For local_tycons, filter out the ones derived from classes
168                                 -- Otherwise the latter show up in interface files
169         in
170         
171             -- Default declarations
172         tcDefaults decls                `thenTc` \ defaulting_tys ->
173         tcSetDefaultTys defaulting_tys  $
174         
175         -- Interface type signatures
176         -- We tie a knot so that the Ids read out of interfaces are in scope
177         --   when we read their pragmas.
178         -- What we rely on is that pragmas are typechecked lazily; if
179         --   any type errors are found (ie there's an inconsistency)
180         --   we silently discard the pragma
181         -- We must do this before mkImplicitDataBinds (which comes next), since
182         -- the latter looks up unpackCStringId, for example, which is usually 
183         -- imported
184         tcInterfaceSigs unf_env decls           `thenTc` \ sig_ids ->
185         tcExtendGlobalValEnv sig_ids            $
186
187         -- Create any necessary record selector Ids and their bindings
188         -- "Necessary" includes data and newtype declarations
189         -- We don't create bindings for dictionary constructors;
190         -- they are always fully applied, and the bindings are just there
191         -- to support partial applications
192         mkImplicitDataBinds tycons              `thenTc`    \ (data_ids, imp_data_binds) ->
193         mkImplicitClassBinds classes            `thenNF_Tc` \ (cls_ids,  imp_cls_binds) ->
194         
195         -- Extend the global value environment with 
196         --      (a) constructors
197         --      (b) record selectors
198         --      (c) class op selectors
199         --      (d) default-method ids... where? I can't see where these are
200         --          put into the envt, and I'm worried that the zonking phase
201         --          will find they aren't there and complain.
202         tcExtendGlobalValEnv data_ids           $
203         tcExtendGlobalValEnv cls_ids            $
204
205             -- foreign import declarations next.
206         tcForeignImports decls          `thenTc`    \ (fo_ids, foi_decls) ->
207         tcExtendGlobalValEnv fo_ids             $
208
209         -- Value declarations next.
210         -- We also typecheck any extra binds that came out of the "deriving" process
211         tcTopBindsAndThen
212             (\ is_rec binds1 (binds2, thing) -> (binds1 `AndMonoBinds` binds2, thing))
213             (get_val_decls decls `ThenBinds` deriv_binds)
214             (   tcGetEnv                                `thenNF_Tc` \ env ->
215                 tcGetUnique                             `thenNF_Tc` \ uniq ->
216                 returnTc ((EmptyMonoBinds, env), emptyLIE)
217             )                           `thenTc` \ ((val_binds, final_env), lie_valdecls) ->
218         tcSetEnv final_env $
219
220             -- foreign export declarations next.
221         tcForeignExports decls          `thenTc`    \ (lie_fodecls, foe_binds, foe_decls) ->
222
223                 -- Second pass over class and instance declarations,
224                 -- to compile the bindings themselves.
225         tcInstDecls2  inst_info         `thenNF_Tc` \ (lie_instdecls, inst_binds) ->
226         tcClassDecls2 decls             `thenNF_Tc` \ (lie_clasdecls, cls_dm_binds) ->
227         tcRules decls                   `thenNF_Tc` \ (lie_rules,     rules) ->
228
229
230              -- Deal with constant or ambiguous InstIds.  How could
231              -- there be ambiguous ones?  They can only arise if a
232              -- top-level decl falls under the monomorphism
233              -- restriction, and no subsequent decl instantiates its
234              -- type.  (Usually, ambiguous type variables are resolved
235              -- during the generalisation step.)
236         let
237             lie_alldecls = lie_valdecls  `plusLIE`
238                            lie_instdecls `plusLIE`
239                            lie_clasdecls `plusLIE`
240                            lie_fodecls   `plusLIE`
241                            lie_rules
242         in
243         tcSimplifyTop lie_alldecls                      `thenTc` \ const_inst_binds ->
244
245                 -- Check that Main defines main
246         (if mod_name == mAIN_Name then
247                 tcLookupValueByKeyMaybe mainKey         `thenNF_Tc` \ maybe_main ->
248                 checkTc (maybeToBool maybe_main) noMainErr
249          else
250                 returnTc ()
251         )                                       `thenTc_`
252
253             -- Backsubstitution.    This must be done last.
254             -- Even tcSimplifyTop may do some unification.
255         let
256             all_binds = imp_data_binds          `AndMonoBinds` 
257                         imp_cls_binds           `AndMonoBinds` 
258                         val_binds               `AndMonoBinds`
259                         inst_binds              `AndMonoBinds`
260                         cls_dm_binds            `AndMonoBinds`
261                         const_inst_binds        `AndMonoBinds`
262                         foe_binds
263         in
264         zonkTopBinds all_binds          `thenNF_Tc` \ (all_binds', really_final_env)  ->
265         tcSetValueEnv really_final_env  $
266         zonkForeignExports foe_decls    `thenNF_Tc` \ foe_decls' ->
267         zonkRules rules                 `thenNF_Tc` \ rules' ->
268
269         returnTc (really_final_env, 
270                   (TcResults {  tc_binds   = all_binds', 
271                                 tc_tycons  = local_tycons,
272                                 tc_classes = local_classes,
273                                 tc_insts   = inst_info,
274                                 tc_fords   = foi_decls ++ foe_decls',
275                                 tc_rules   = rules',
276                                 tc_env     = really_final_env
277                  }))
278
279     -- End of outer fix loop
280     ) `thenTc` \ (final_env, stuff) ->
281     returnTc stuff
282
283 get_val_decls decls = foldr ThenBinds EmptyBinds [binds | ValD binds <- decls]
284 \end{code}
285
286
287 \begin{code}
288 noMainErr
289   = hsep [ptext SLIT("Module"), quotes (pprModuleName mAIN_Name), 
290           ptext SLIT("must include a definition for"), quotes (ptext SLIT("main"))]
291 \end{code}
292