[project @ 2000-11-09 08:18:11 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                           RecTcEnv, 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, idUnfolding )
45 import Module           ( Module )
46 import Name             ( Name, toRdrName )
47 import Name             ( nameEnvElts, lookupNameEnv )
48 import TyCon            ( tyConGenInfo )
49 import Util
50 import BasicTypes       ( EP(..), Fixity )
51 import Bag              ( isEmptyBag )
52 import Outputable
53 import HscTypes         ( PersistentCompilerState(..), HomeSymbolTable, 
54                           PackageTypeEnv, DFunId, ModIface(..),
55                           TypeEnv, extendTypeEnvList, 
56                           TyThing(..), mkTypeEnv )
57 import List             ( partition )
58 \end{code}
59
60 Outside-world interface:
61 \begin{code}
62
63 -- Convenient type synonyms first:
64 data TcResults
65   = TcResults {
66         tc_pcs     :: PersistentCompilerState,  -- Augmented with imported information,
67                                                 -- (but not stuff from this module)
68
69         -- All these fields have info *just for this module*
70         tc_env     :: TypeEnv,                  -- The top level TypeEnv
71         tc_insts   :: [DFunId],                 -- Instances
72         tc_binds   :: TypecheckedMonoBinds,     -- Bindings
73         tc_fords   :: [TypecheckedForeignDecl], -- Foreign import & exports.
74         tc_rules   :: [TypecheckedRuleDecl]     -- Transformation rules
75     }
76
77 ---------------
78 typecheckModule
79         :: DynFlags
80         -> Module
81         -> PersistentCompilerState
82         -> HomeSymbolTable
83         -> ModIface             -- Iface for this module
84         -> [RenamedHsDecl]
85         -> IO (Maybe TcResults)
86
87 typecheckModule dflags this_mod pcs hst mod_iface decls
88   = do  env <- initTcEnv hst (pcs_PTE pcs)
89
90         (maybe_result, (warns,errs)) <- initTc dflags env tc_module
91
92         let { maybe_tc_result :: Maybe TcResults ;
93               maybe_tc_result = case maybe_result of
94                                   Nothing    -> Nothing
95                                   Just (_,r) -> Just r }
96
97         printErrorsAndWarnings (errs,warns)
98         printTcDump dflags maybe_tc_result
99
100         if isEmptyBag errs then 
101              return maybe_tc_result
102            else 
103              return Nothing 
104   where
105     tc_module :: TcM (RecTcEnv, TcResults)
106     tc_module = fixTc (\ ~(unf_env ,_) -> tcModule pcs hst get_fixity this_mod decls unf_env)
107
108     fixity_env = mi_fixities mod_iface
109
110     get_fixity :: Name -> Maybe Fixity
111     get_fixity nm = lookupNameEnv fixity_env nm
112 \end{code}
113
114 The internal monster:
115 \begin{code}
116 tcModule :: PersistentCompilerState
117          -> HomeSymbolTable
118          -> (Name -> Maybe Fixity)
119          -> Module
120          -> [RenamedHsDecl]
121          -> RecTcEnv            -- The knot-tied environment
122          -> TcM (TcEnv, TcResults)
123
124   -- (unf_env :: RecTcEnv) is used for type-checking interface pragmas
125   -- which is done lazily [ie failure just drops the pragma
126   -- without having any global-failure effect].
127   -- 
128   -- unf_env is also used to get the pragama info
129   -- for imported dfuns and default methods
130
131 tcModule pcs hst get_fixity this_mod decls unf_env
132   =              -- Type-check the type and class decls
133     tcTyAndClassDecls unf_env decls             `thenTc` \ env ->
134     tcSetEnv env                                $
135     let
136         classes = tcEnvClasses env
137         tycons  = tcEnvTyCons env       -- INCLUDES tycons derived from classes
138     in
139     
140         -- Typecheck the instance decls, includes deriving
141     tcInstDecls1 (pcs_insts pcs) (pcs_PRS pcs) 
142                  hst unf_env get_fixity this_mod 
143                  tycons decls           `thenTc` \ (new_pcs_insts, inst_env, local_inst_info, deriv_binds) ->
144     tcSetInstEnv inst_env                       $
145     
146         -- Default declarations
147     tcDefaults decls                            `thenTc` \ defaulting_tys ->
148     tcSetDefaultTys defaulting_tys              $
149     
150     -- Interface type signatures
151     -- We tie a knot so that the Ids read out of interfaces are in scope
152     --   when we read their pragmas.
153     -- What we rely on is that pragmas are typechecked lazily; if
154     --   any type errors are found (ie there's an inconsistency)
155     --   we silently discard the pragma
156     -- We must do this before mkImplicitDataBinds (which comes next), since
157     -- the latter looks up unpackCStringId, for example, which is usually 
158     -- imported
159     tcInterfaceSigs unf_env decls               `thenTc` \ sig_ids ->
160     tcExtendGlobalValEnv sig_ids                $
161     
162     -- Create any necessary record selector Ids and their bindings
163     -- "Necessary" includes data and newtype declarations
164     -- We don't create bindings for dictionary constructors;
165     -- they are always fully applied, and the bindings are just there
166     -- to support partial applications
167     mkImplicitDataBinds  this_mod tycons        `thenTc`    \ (data_ids, imp_data_binds) ->
168     mkImplicitClassBinds this_mod classes       `thenNF_Tc` \ (cls_ids,  imp_cls_binds) ->
169     
170     -- Extend the global value environment with 
171     --  (a) constructors
172     --  (b) record selectors
173     --  (c) class op selectors
174     --  (d) default-method ids... where? I can't see where these are
175     --      put into the envt, and I'm worried that the zonking phase
176     --      will find they aren't there and complain.
177     tcExtendGlobalValEnv data_ids               $
178     tcExtendGlobalValEnv cls_ids                $
179     tcGetEnv                                    `thenTc` \ unf_env ->
180     
181         -- Foreign import declarations next
182     tcForeignImports decls                      `thenTc`    \ (fo_ids, foi_decls) ->
183     tcExtendGlobalValEnv fo_ids                 $
184     
185     -- Value declarations next.
186     -- We also typecheck any extra binds that came out of the "deriving" process
187     tcTopBinds (get_binds decls `ThenBinds` deriv_binds)        `thenTc` \ ((val_binds, env), lie_valdecls) ->
188     tcSetEnv env $
189     
190         -- Foreign export declarations next
191     tcForeignExports decls              `thenTc`    \ (lie_fodecls, foe_binds, foe_decls) ->
192     
193         -- Second pass over class and instance declarations,
194         -- to compile the bindings themselves.
195     tcInstDecls2  local_inst_info               `thenNF_Tc` \ (lie_instdecls, inst_binds) ->
196     tcClassDecls2 this_mod decls                `thenNF_Tc` \ (lie_clasdecls, cls_dm_binds) ->
197     tcRules (pcs_rules pcs) this_mod decls      `thenNF_Tc` \ (new_pcs_rules, lie_rules, local_rules) ->
198     
199          -- Deal with constant or ambiguous InstIds.  How could
200          -- there be ambiguous ones?  They can only arise if a
201          -- top-level decl falls under the monomorphism
202          -- restriction, and no subsequent decl instantiates its
203          -- type.  (Usually, ambiguous type variables are resolved
204          -- during the generalisation step.)
205     let
206         lie_alldecls = lie_valdecls     `plusLIE`
207                    lie_instdecls        `plusLIE`
208                    lie_clasdecls        `plusLIE`
209                    lie_fodecls          `plusLIE`
210                    lie_rules
211     in
212     tcSimplifyTop lie_alldecls                  `thenTc` \ const_inst_binds ->
213     
214         -- Backsubstitution.    This must be done last.
215         -- Even tcSimplifyTop may do some unification.
216     let
217         all_binds = imp_data_binds      `AndMonoBinds` 
218                     imp_cls_binds       `AndMonoBinds` 
219                     val_binds           `AndMonoBinds`
220                     inst_binds          `AndMonoBinds`
221                     cls_dm_binds        `AndMonoBinds`
222                     const_inst_binds    `AndMonoBinds`
223                     foe_binds
224     in
225     zonkTopBinds all_binds              `thenNF_Tc` \ (all_binds', final_env)  ->
226     tcSetEnv final_env                  $
227         -- zonkTopBinds puts all the top-level Ids into the tcGEnv
228     zonkForeignExports foe_decls        `thenNF_Tc` \ foe_decls' ->
229     zonkRules local_rules               `thenNF_Tc` \ local_rules' ->
230     
231     
232     let (local_things, imported_things) = partition (isLocalThing this_mod) 
233                                                     (nameEnvElts (getTcGEnv final_env))
234
235         local_type_env :: TypeEnv
236         local_type_env = mkTypeEnv local_things
237     
238         new_pte :: PackageTypeEnv
239         new_pte = extendTypeEnvList (pcs_PTE pcs) imported_things
240
241         final_pcs :: PersistentCompilerState
242         final_pcs = pcs { pcs_PTE   = new_pte,
243                           pcs_insts = new_pcs_insts,
244                           pcs_rules = new_pcs_rules
245                     }
246     in  
247     returnTc (unf_env,
248               TcResults { tc_pcs     = final_pcs,
249                           tc_env     = local_type_env,
250                           tc_binds   = all_binds', 
251                           tc_insts   = map iDFunId local_inst_info,
252                           tc_fords   = foi_decls ++ foe_decls',
253                           tc_rules   = local_rules'
254                         }
255     )
256
257 get_binds decls = foldr ThenBinds EmptyBinds [binds | ValD binds <- decls]
258 \end{code}
259
260
261
262 %************************************************************************
263 %*                                                                      *
264 \subsection{Dumping output}
265 %*                                                                      *
266 %************************************************************************
267
268 \begin{code}
269 printTcDump dflags Nothing = return ()
270 printTcDump dflags (Just results)
271   = do dumpIfSet_dyn dflags Opt_D_dump_types 
272                      "Type signatures" (dump_sigs results)
273        dumpIfSet_dyn dflags Opt_D_dump_tc    
274                      "Typechecked" (dump_tc results) 
275
276 dump_tc results
277   = vcat [ppr (tc_binds results),
278           pp_rules (tc_rules results),
279           ppr_gen_tycons [tc | ATyCon tc <- nameEnvElts (tc_env results)]
280     ]
281
282 dump_sigs results       -- Print type signatures
283   =     -- Convert to HsType so that we get source-language style printing
284         -- And sort by RdrName
285     vcat $ map ppr_sig $ sortLt lt_sig $
286     [ (toRdrName id, toHsType (idType id))
287     | AnId id <- nameEnvElts (tc_env results),
288       want_sig id
289     ]
290   where
291     lt_sig (n1,_) (n2,_) = n1 < n2
292     ppr_sig (n,t)        = ppr n <+> dcolon <+> ppr t
293
294     want_sig id | opt_PprStyle_Debug = True
295                 | otherwise          = True     -- For now
296
297 ppr_gen_tycons tcs = vcat [ptext SLIT("{-# Generic type constructor details"),
298                            vcat (map ppr_gen_tycon tcs),
299                            ptext SLIT("#-}")
300                      ]
301
302 -- x&y are now Id's, not CoreExpr's 
303 ppr_gen_tycon tycon 
304   | Just ep <- tyConGenInfo tycon
305   = (ppr tycon <> colon) $$ nest 4 (ppr_ep ep)
306
307   | otherwise = ppr tycon <> colon <+> ptext SLIT("Not derivable")
308
309 ppr_ep (EP from to)
310   = vcat [ ptext SLIT("Rep type:") <+> ppr (funResultTy from_tau),
311            ptext SLIT("From:") <+> ppr (unfoldingTemplate (idUnfolding from)),
312            ptext SLIT("To:")   <+> ppr (unfoldingTemplate (idUnfolding to))
313     ]
314   where
315     (_,from_tau) = splitForAllTys (idType from)
316
317 pp_rules [] = empty
318 pp_rules rs = vcat [ptext SLIT("{-# RULES"),
319                     nest 4 (vcat (map ppr rs)),
320                     ptext SLIT("#-}")]
321 \end{code}