[project @ 2000-10-12 15:05:59 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, tcLookupGlobal_maybe,
29                           tcEnvTyCons, tcEnvClasses, 
30                           tcSetEnv, tcSetInstEnv, initEnv
31                         )
32 import TcRules          ( tcRules )
33 import TcForeign        ( tcForeignImports, tcForeignExports )
34 import TcIfaceSig       ( tcInterfaceSigs )
35 import TcInstDcls       ( tcInstDecls1, tcInstDecls2 )
36 import TcInstUtil       ( buildInstanceEnv, InstInfo )
37 import TcSimplify       ( tcSimplifyTop )
38 import TcTyClsDecls     ( tcTyAndClassDecls )
39 import TcTyDecls        ( mkImplicitDataBinds )
40
41 import CoreUnfold       ( unfoldingTemplate )
42 import Type             ( funResultTy, splitForAllTys )
43 import RnMonad          ( RnNameSupply, FixityEnv )
44 import Bag              ( isEmptyBag )
45 import ErrUtils         ( printErrorsAndWarnings, dumpIfSet )
46 import Id               ( idType, idName, idUnfolding )
47 import Module           ( pprModuleName, mkThisModule, plusModuleEnv )
48 import Name             ( nameOccName, isLocallyDefined, isGlobalName,
49                           toRdrName, nameEnvElts, 
50                         )
51 import TyCon            ( TyCon, isDataTyCon, tyConName, tyConGenInfo )
52 import OccName          ( isSysOcc )
53 import TyCon            ( TyCon, isClassTyCon )
54 import Class            ( Class )
55 import PrelNames        ( mAIN_Name, mainKey )
56 import UniqSupply       ( UniqSupply )
57 import Maybes           ( maybeToBool )
58 import Util
59 import BasicTypes       ( EP(..) )
60 import Bag              ( Bag, isEmptyBag )
61 import Outputable
62
63 \end{code}
64
65 Outside-world interface:
66 \begin{code}
67
68 -- Convenient type synonyms first:
69 data TcResults
70   = TcResults {
71         tc_prs     :: PersistentCompilerState,  -- Augmented with imported information,
72                                                 -- (but not stuff from this module)
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         :: PersistentCompilerState
85         -> HomeSymbolTable
86         -> RenamedHsModule
87         -> IO (Maybe TcResults)
88
89 typecheckModule pcs hst mod
90   = do { us <- mkSplitUniqSupply 'a' ;
91
92          env <- initTcEnv global_symbol_table global_inst_env ;
93
94          (maybe_result, warns, errs) <- initTc us env (tcModule (pcsPRS pcs) mod)
95                 
96          printErrorsAndWarnings errs warns ;
97         
98          (case maybe_result of
99                 Nothing -> return ()
100                 Just results -> do { dumpIfSet opt_D_dump_types "Type signatures" (dump_sigs results)
101                                      dumpIfSet opt_D_dump_tc    "Typechecked"     (dump_tc   results)
102          }) ;
103                         
104         return (if isEmptyBag errs then 
105                         maybe_result 
106                 else 
107                         Nothing)
108     }
109   where
110     global_symbol_table = pcsPST pcs `plusModuleEnv` hst
111
112     global_inst_env     = foldModuleEnv (plusInstEnv . instEnv) (pcsInsts pcs) gst
113         -- For now, make the total instance envt by simply
114         -- folding together all the instances we can find anywhere
115 \end{code}
116
117 The internal monster:
118 \begin{code}
119 tcModule :: PersistentRenamerState
120          -> RenamedHsModule     -- input
121          -> TcM TcResults       -- output
122
123 tcModule prs (HsModule mod_name _ _ _ decls _ src_loc)
124   = tcAddSrcLoc src_loc $       -- record where we're starting
125
126     fixTc (\ ~(unf_env ,_) ->
127         -- (unf_env :: TcEnv) is used for type-checking interface pragmas
128         -- which is done lazily [ie failure just drops the pragma
129         -- without having any global-failure effect].
130         -- 
131         -- unf_env is also used to get the pragama info
132         -- for imported dfuns and default methods
133
134                  -- Type-check the type and class decls
135         tcTyAndClassDecls unf_env decls         `thenTc` \ env ->
136         tcSetEnv env $
137
138                  -- Typecheck the instance decls, includes deriving
139         tcInstDecls1 prs unf_env decls 
140                      (mkThisModule mod_name)    `thenTc` \ (inst_info, deriv_binds) ->
141     
142         buildInstanceEnv inst_info      `thenNF_Tc` \ inst_env ->
143
144         tcSetInstEnv inst_env $
145         let
146             classes      = tcEnvClasses env
147             tycons       = tcEnvTyCons env      -- INCLUDES tycons derived from classes
148             local_classes = filter isLocallyDefined classes
149             local_tycons  = [ tc | tc <- tycons,
150                                    isLocallyDefined tc,
151                                    not (isClassTyCon tc)
152                             ]
153                                 -- For local_tycons, filter out the ones derived from classes
154                                 -- Otherwise the latter show up in interface files
155         in
156         
157             -- Default declarations
158         tcDefaults decls                `thenTc` \ defaulting_tys ->
159         tcSetDefaultTys defaulting_tys  $
160         
161         -- Interface type signatures
162         -- We tie a knot so that the Ids read out of interfaces are in scope
163         --   when we read their pragmas.
164         -- What we rely on is that pragmas are typechecked lazily; if
165         --   any type errors are found (ie there's an inconsistency)
166         --   we silently discard the pragma
167         -- We must do this before mkImplicitDataBinds (which comes next), since
168         -- the latter looks up unpackCStringId, for example, which is usually 
169         -- imported
170         tcInterfaceSigs unf_env decls           `thenTc` \ sig_ids ->
171         tcExtendGlobalValEnv sig_ids            $
172
173         -- Create any necessary record selector Ids and their bindings
174         -- "Necessary" includes data and newtype declarations
175         -- We don't create bindings for dictionary constructors;
176         -- they are always fully applied, and the bindings are just there
177         -- to support partial applications
178         mkImplicitDataBinds tycons              `thenTc`    \ (data_ids, imp_data_binds) ->
179         mkImplicitClassBinds classes            `thenNF_Tc` \ (cls_ids,  imp_cls_binds) ->
180         
181         -- Extend the global value environment with 
182         --      (a) constructors
183         --      (b) record selectors
184         --      (c) class op selectors
185         --      (d) default-method ids... where? I can't see where these are
186         --          put into the envt, and I'm worried that the zonking phase
187         --          will find they aren't there and complain.
188         tcExtendGlobalValEnv data_ids           $
189         tcExtendGlobalValEnv cls_ids            $
190
191             -- foreign import declarations next.
192         tcForeignImports decls                  `thenTc`    \ (fo_ids, foi_decls) ->
193         tcExtendGlobalValEnv fo_ids             $
194
195         -- Value declarations next.
196         -- We also typecheck any extra binds that came out of the "deriving" process
197         tcTopBindsAndThen
198             (\ is_rec binds1 (binds2, thing) -> (binds1 `AndMonoBinds` binds2, thing))
199             (get_val_decls decls `ThenBinds` deriv_binds)
200             (   tcGetEnv                                `thenNF_Tc` \ env ->
201                 returnTc ((EmptyMonoBinds, env), emptyLIE)
202             )                           `thenTc` \ ((val_binds, final_env), lie_valdecls) ->
203         tcSetEnv final_env $
204
205             -- foreign export declarations next.
206         tcForeignExports decls          `thenTc`    \ (lie_fodecls, foe_binds, foe_decls) ->
207
208                 -- Second pass over class and instance declarations,
209                 -- to compile the bindings themselves.
210         tcInstDecls2  inst_info         `thenNF_Tc` \ (lie_instdecls, inst_binds) ->
211         tcClassDecls2 decls             `thenNF_Tc` \ (lie_clasdecls, cls_dm_binds) ->
212         tcRules decls                   `thenNF_Tc` \ (lie_rules,     rules) ->
213
214
215              -- Deal with constant or ambiguous InstIds.  How could
216              -- there be ambiguous ones?  They can only arise if a
217              -- top-level decl falls under the monomorphism
218              -- restriction, and no subsequent decl instantiates its
219              -- type.  (Usually, ambiguous type variables are resolved
220              -- during the generalisation step.)
221         let
222             lie_alldecls = lie_valdecls  `plusLIE`
223                            lie_instdecls `plusLIE`
224                            lie_clasdecls `plusLIE`
225                            lie_fodecls   `plusLIE`
226                            lie_rules
227         in
228         tcSimplifyTop lie_alldecls                      `thenTc` \ const_inst_binds ->
229
230                 -- Check that Main defines main
231         (if mod_name == mAIN_Name then
232                 tcLookupGlobal_maybe mainName           `thenNF_Tc` \ maybe_main ->
233                 case maybe_main of
234                    Just (AnId _) -> returnTc ()
235                    other         -> addErrTc noMainErr
236          else
237                 returnTc ()
238         )                                       `thenTc_`
239
240             -- Backsubstitution.    This must be done last.
241             -- Even tcSimplifyTop may do some unification.
242         let
243             all_binds = imp_data_binds          `AndMonoBinds` 
244                         imp_cls_binds           `AndMonoBinds` 
245                         val_binds               `AndMonoBinds`
246                         inst_binds              `AndMonoBinds`
247                         cls_dm_binds            `AndMonoBinds`
248                         const_inst_binds        `AndMonoBinds`
249                         foe_binds
250         in
251         zonkTopBinds all_binds          `thenNF_Tc` \ (all_binds', really_final_env)  ->
252         tcSetEnv really_final_env       $
253                 -- zonkTopBinds puts all the top-level Ids into the tcGEnv
254
255         zonkForeignExports foe_decls    `thenNF_Tc` \ foe_decls' ->
256         zonkRules rules                 `thenNF_Tc` \ rules' ->
257
258         returnTc (really_final_env, 
259                   (TcResults {  tc_binds   = all_binds', 
260                                 tc_tycons  = local_tycons,
261                                 tc_classes = local_classes,
262                                 tc_insts   = inst_info,
263                                 tc_fords   = foi_decls ++ foe_decls',
264                                 tc_rules   = rules',
265                                 tc_env     = really_final_env
266                  }))
267
268     -- End of outer fix loop
269     ) `thenTc` \ (final_env, stuff) ->
270     returnTc stuff
271
272 get_val_decls decls = foldr ThenBinds EmptyBinds [binds | ValD binds <- decls]
273 \end{code}
274
275
276 \begin{code}
277 noMainErr
278   = hsep [ptext SLIT("Module"), quotes (pprModuleName mAIN_Name), 
279           ptext SLIT("must include a definition for"), quotes (ptext SLIT("main"))]
280 \end{code}
281
282
283 %************************************************************************
284 %*                                                                      *
285 \subsection{Dumping output}
286 %*                                                                      *
287 %************************************************************************
288
289 \begin{code}
290 dump_tc results
291   = vcat [ppr (tc_binds results),
292           pp_rules (tc_rules results),
293           ppr_gen_tycons (tc_tycons results)
294     ]
295
296 dump_sigs results       -- Print type signatures
297   =     -- Convert to HsType so that we get source-language style printing
298         -- And sort by RdrName
299     vcat $ map ppr_sig $ sortLt lt_sig $
300     [(toRdrName id, toHsType (idType id)) | id <- nameEnvElts (tc_env results), 
301                                             want_sig id
302     ]
303   where
304     lt_sig (n1,_) (n2,_) = n1 < n2
305     ppr_sig (n,t)        = ppr n <+> dcolon <+> ppr t
306
307     want_sig id | opt_PprStyle_Debug = True
308                 | otherwise          = isLocallyDefined n && 
309                                        isGlobalName n && 
310                                        not (isSysOcc (nameOccName n))
311                                      where
312                                        n = idName id
313
314 ppr_gen_tycons tcs = vcat [ptext SLIT("{-# Generic type constructor details"),
315                            vcat (map ppr_gen_tycon (filter isLocallyDefined tcs)),
316                            ptext SLIT("#-}")
317                      ]
318
319 -- x&y are now Id's, not CoreExpr's 
320 ppr_gen_tycon tycon 
321   | Just ep <- tyConGenInfo tycon
322   = (ppr tycon <> colon) $$ nest 4 (ppr_ep ep)
323
324   | otherwise = ppr tycon <> colon <+> ptext SLIT("Not derivable")
325
326 ppr_ep (EP from to)
327   = vcat [ ptext SLIT("Rep type:") <+> ppr (funResultTy from_tau),
328            ptext SLIT("From:") <+> ppr (unfoldingTemplate (idUnfolding from)),
329            ptext SLIT("To:")   <+> ppr (unfoldingTemplate (idUnfolding to))
330     ]
331   where
332     (_,from_tau) = splitForAllTys (idType from)
333
334 pp_rules [] = empty
335 pp_rules rs = vcat [ptext SLIT("{-# RULES"),
336                     nest 4 (vcat (map ppr rs)),
337                     ptext SLIT("#-}")]
338 \end{code}