[project @ 2000-10-30 09:52:14 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      ( DynFlag(..), DynFlags, opt_PprStyle_Debug )
15 import HsSyn            ( HsBinds(..), MonoBinds(..), HsDecl(..) )
16 import HsTypes          ( toHsType )
17 import RnHsSyn          ( RenamedHsDecl )
18 import TcHsSyn          ( TypecheckedMonoBinds, 
19                           TypecheckedForeignDecl, TypecheckedRuleDecl,
20                           zonkTopBinds, zonkForeignExports, zonkRules
21                         )
22
23 import TcMonad
24 import Inst             ( plusLIE )
25 import TcBinds          ( tcTopBinds )
26 import TcClassDcl       ( tcClassDecls2, mkImplicitClassBinds )
27 import TcDefaults       ( tcDefaults )
28 import TcEnv            ( TcEnv, InstInfo(iDFunId), tcExtendGlobalValEnv, 
29                           tcEnvTyCons, tcEnvClasses,  isLocalThing,
30                           tcSetEnv, tcSetInstEnv, initTcEnv, getTcGEnv
31                         )
32 import TcRules          ( tcRules )
33 import TcForeign        ( tcForeignImports, tcForeignExports )
34 import TcIfaceSig       ( tcInterfaceSigs )
35 import TcInstDcls       ( tcInstDecls1, tcInstDecls2 )
36 import TcSimplify       ( tcSimplifyTop )
37 import TcTyClsDecls     ( tcTyAndClassDecls )
38 import TcTyDecls        ( mkImplicitDataBinds )
39
40 import CoreUnfold       ( unfoldingTemplate )
41 import Type             ( funResultTy, splitForAllTys )
42 import Bag              ( isEmptyBag )
43 import ErrUtils         ( printErrorsAndWarnings, dumpIfSet_dyn )
44 import Id               ( idType, idName, idUnfolding )
45 import Module           ( Module, plusModuleEnv )
46 import Name             ( Name, nameOccName, isLocallyDefined, isGlobalName, getName,
47                           toRdrName, nameEnvElts, lookupNameEnv, mkNameEnv
48                         )
49 import TyCon            ( tyConGenInfo, isClassTyCon )
50 import OccName          ( isSysOcc )
51 import Maybes           ( thenMaybe )
52 import Util
53 import BasicTypes       ( EP(..), Fixity )
54 import Bag              ( isEmptyBag )
55 import Outputable
56 import HscTypes         ( PersistentCompilerState(..), HomeSymbolTable, HomeIfaceTable,
57                           PackageSymbolTable, DFunId, ModIface(..),
58                           TypeEnv, extendTypeEnv, lookupTable,
59                           TyThing(..), groupTyThings )
60 import List             ( partition )
61 \end{code}
62
63 Outside-world interface:
64 \begin{code}
65
66 -- Convenient type synonyms first:
67 data TcResults
68   = TcResults {
69         tc_pcs     :: PersistentCompilerState,  -- Augmented with imported information,
70                                                 -- (but not stuff from this module)
71
72         -- All these fields have info *just for this module*
73         tc_env     :: TypeEnv,                  -- The top level TypeEnv
74         tc_insts   :: [DFunId],                 -- Instances
75         tc_binds   :: TypecheckedMonoBinds,     -- Bindings
76         tc_fords   :: [TypecheckedForeignDecl], -- Foreign import & exports.
77         tc_rules   :: [TypecheckedRuleDecl]     -- Transformation rules
78     }
79
80 ---------------
81 typecheckModule
82         :: DynFlags
83         -> Module
84         -> PersistentCompilerState
85         -> HomeSymbolTable -> HomeIfaceTable
86         -> [RenamedHsDecl]
87         -> IO (Maybe TcResults)
88
89 typecheckModule dflags this_mod pcs hst hit decls
90   = do  env <- initTcEnv global_symbol_table
91
92         (maybe_result, (warns,errs)) <- initTc dflags env tc_module
93
94         let { maybe_tc_result :: Maybe TcResults ;
95               maybe_tc_result = case maybe_result of
96                                   Nothing    -> Nothing
97                                   Just (_,r) -> Just r }
98
99         printErrorsAndWarnings (errs,warns)
100         printTcDump dflags maybe_tc_result
101
102         if isEmptyBag errs then 
103              return maybe_tc_result
104            else 
105              return Nothing 
106   where
107     global_symbol_table = pcs_PST pcs `plusModuleEnv` hst
108
109     tc_module :: TcM (TcEnv, TcResults)
110     tc_module = fixTc (\ ~(unf_env ,_) -> tcModule pcs hst get_fixity this_mod decls unf_env)
111
112     pit = pcs_PIT pcs
113
114     get_fixity :: Name -> Maybe Fixity
115     get_fixity nm = lookupTable hit pit nm      `thenMaybe` \ iface ->
116                     lookupNameEnv (mi_fixities iface) nm
117 \end{code}
118
119 The internal monster:
120 \begin{code}
121 tcModule :: PersistentCompilerState
122          -> HomeSymbolTable
123          -> (Name -> Maybe Fixity)
124          -> Module
125          -> [RenamedHsDecl]
126          -> TcEnv               -- The knot-tied environment
127          -> TcM (TcEnv, TcResults)
128
129   -- (unf_env :: TcEnv) 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 pragama info
134   -- for imported dfuns and default methods
135
136 tcModule pcs hst get_fixity this_mod decls unf_env
137   =              -- Type-check the type and class decls
138     tcTyAndClassDecls unf_env decls             `thenTc` \ env ->
139     tcSetEnv env                                $
140     let
141         classes       = tcEnvClasses env
142         tycons        = tcEnvTyCons env -- INCLUDES tycons derived from classes
143         local_tycons  = [ tc | tc <- tycons,
144                                isLocallyDefined tc,
145                                not (isClassTyCon tc)
146                         ]
147                         -- For local_tycons, filter out the ones derived from classes
148                         -- Otherwise the latter show up in interface files
149     in
150     
151         -- Typecheck the instance decls, includes deriving
152     tcInstDecls1 (pcs_insts pcs) (pcs_PRS pcs) 
153                  hst unf_env get_fixity this_mod 
154                  local_tycons decls             `thenTc` \ (new_pcs_insts, inst_env, local_inst_info, deriv_binds) ->
155     tcSetInstEnv inst_env                       $
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     tcTopBinds (get_binds decls `ThenBinds` deriv_binds)        `thenTc` \ ((val_binds, env), lie_valdecls) ->
198     tcSetEnv env $
199     
200         -- Foreign export declarations next
201     tcForeignExports decls              `thenTc`    \ (lie_fodecls, foe_binds, foe_decls) ->
202     
203         -- Second pass over class and instance declarations,
204         -- to compile the bindings themselves.
205     tcInstDecls2  local_inst_info               `thenNF_Tc` \ (lie_instdecls, inst_binds) ->
206     tcClassDecls2 decls                         `thenNF_Tc` \ (lie_clasdecls, cls_dm_binds) ->
207     tcRules (pcs_rules pcs) this_mod decls      `thenNF_Tc` \ (new_pcs_rules, lie_rules, local_rules) ->
208     
209          -- Deal with constant or ambiguous InstIds.  How could
210          -- there be ambiguous ones?  They can only arise if a
211          -- top-level decl falls under the monomorphism
212          -- restriction, and no subsequent decl instantiates its
213          -- type.  (Usually, ambiguous type variables are resolved
214          -- during the generalisation step.)
215     let
216         lie_alldecls = lie_valdecls     `plusLIE`
217                    lie_instdecls        `plusLIE`
218                    lie_clasdecls        `plusLIE`
219                    lie_fodecls          `plusLIE`
220                    lie_rules
221     in
222     tcSimplifyTop lie_alldecls                  `thenTc` \ const_inst_binds ->
223     
224         -- Backsubstitution.    This must be done last.
225         -- Even tcSimplifyTop may do some unification.
226     let
227         all_binds = imp_data_binds      `AndMonoBinds` 
228                     imp_cls_binds       `AndMonoBinds` 
229                     val_binds           `AndMonoBinds`
230                     inst_binds          `AndMonoBinds`
231                     cls_dm_binds        `AndMonoBinds`
232                     const_inst_binds    `AndMonoBinds`
233                     foe_binds
234     in
235     zonkTopBinds all_binds              `thenNF_Tc` \ (all_binds', final_env)  ->
236     tcSetEnv final_env                  $
237         -- zonkTopBinds puts all the top-level Ids into the tcGEnv
238     zonkForeignExports foe_decls        `thenNF_Tc` \ foe_decls' ->
239     zonkRules local_rules               `thenNF_Tc` \ local_rules' ->
240     
241     
242     let (local_things, imported_things) = partition (isLocalThing this_mod) 
243                                                     (nameEnvElts (getTcGEnv final_env))
244
245         local_type_env :: TypeEnv
246         local_type_env = mkNameEnv [(getName thing, thing) | thing <- local_things]
247     
248         new_pst :: PackageSymbolTable
249         new_pst = extendTypeEnv (pcs_PST pcs) (groupTyThings imported_things)
250
251         final_pcs :: PersistentCompilerState
252         final_pcs = pcs { pcs_PST   = new_pst,
253                           pcs_insts = new_pcs_insts,
254                           pcs_rules = new_pcs_rules
255                     }
256     in  
257     returnTc (final_env,
258               TcResults { tc_pcs     = final_pcs,
259                           tc_env     = local_type_env,
260                           tc_binds   = all_binds', 
261                           tc_insts   = map iDFunId local_inst_info,
262                           tc_fords   = foi_decls ++ foe_decls',
263                           tc_rules   = local_rules'
264                         })
265
266 get_binds decls = foldr ThenBinds EmptyBinds [binds | ValD binds <- decls]
267 \end{code}
268
269
270
271 %************************************************************************
272 %*                                                                      *
273 \subsection{Dumping output}
274 %*                                                                      *
275 %************************************************************************
276
277 \begin{code}
278 printTcDump dflags Nothing = return ()
279 printTcDump dflags (Just results)
280   = do dumpIfSet_dyn dflags Opt_D_dump_types 
281                      "Type signatures" (dump_sigs results)
282        dumpIfSet_dyn dflags Opt_D_dump_tc    
283                      "Typechecked" (dump_tc results) 
284
285 dump_tc results
286   = vcat [ppr (tc_binds results),
287           pp_rules (tc_rules results),
288           ppr_gen_tycons [tc | ATyCon tc <- nameEnvElts (tc_env results)]
289     ]
290
291 dump_sigs results       -- Print type signatures
292   =     -- Convert to HsType so that we get source-language style printing
293         -- And sort by RdrName
294     vcat $ map ppr_sig $ sortLt lt_sig $
295     [(toRdrName id, toHsType (idType id))
296         | AnId id <- nameEnvElts (tc_env results), 
297           want_sig id
298     ]
299   where
300     lt_sig (n1,_) (n2,_) = n1 < n2
301     ppr_sig (n,t)        = ppr n <+> dcolon <+> ppr t
302
303     want_sig id | opt_PprStyle_Debug = True
304                 | otherwise          = isLocallyDefined n && 
305                                        isGlobalName n && 
306                                        not (isSysOcc (nameOccName n))
307                                      where
308                                        n = idName id
309
310 ppr_gen_tycons tcs = vcat [ptext SLIT("{-# Generic type constructor details"),
311                            vcat (map ppr_gen_tycon (filter isLocallyDefined tcs)),
312                            ptext SLIT("#-}")
313                      ]
314
315 -- x&y are now Id's, not CoreExpr's 
316 ppr_gen_tycon tycon 
317   | Just ep <- tyConGenInfo tycon
318   = (ppr tycon <> colon) $$ nest 4 (ppr_ep ep)
319
320   | otherwise = ppr tycon <> colon <+> ptext SLIT("Not derivable")
321
322 ppr_ep (EP from to)
323   = vcat [ ptext SLIT("Rep type:") <+> ppr (funResultTy from_tau),
324            ptext SLIT("From:") <+> ppr (unfoldingTemplate (idUnfolding from)),
325            ptext SLIT("To:")   <+> ppr (unfoldingTemplate (idUnfolding to))
326     ]
327   where
328     (_,from_tau) = splitForAllTys (idType from)
329
330 pp_rules [] = empty
331 pp_rules rs = vcat [ptext SLIT("{-# RULES"),
332                     nest 4 (vcat (map ppr rs)),
333                     ptext SLIT("#-}")]
334 \end{code}