3bd6902b408dc06f9313bf107ff28282823d819a
[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, typecheckExpr, TcResults(..)
9     ) where
10
11 #include "HsVersions.h"
12
13 import CmdLineOpts      ( DynFlag(..), DynFlags, opt_PprStyle_Debug )
14 import HsSyn            ( HsBinds(..), MonoBinds(..), HsDecl(..), 
15                           isIfaceRuleDecl, nullBinds, andMonoBindList
16                         )
17 import HsTypes          ( toHsType )
18 import RnHsSyn          ( RenamedHsBinds, RenamedHsDecl, RenamedHsExpr )
19 import TcHsSyn          ( TypecheckedMonoBinds, TypecheckedHsExpr,
20                           TypecheckedForeignDecl, TypecheckedRuleDecl,
21                           zonkTopBinds, zonkForeignExports, zonkRules, mkHsLet,
22                           zonkExpr
23                         )
24
25
26 import TcMonad
27 import TcType           ( newTyVarTy, zonkTcType )
28 import Inst             ( plusLIE )
29 import TcBinds          ( tcTopBinds )
30 import TcClassDcl       ( tcClassDecls2 )
31 import TcDefaults       ( tcDefaults, defaultDefaultTys )
32 import TcExpr           ( tcMonoExpr )
33 import TcEnv            ( TcEnv, InstInfo, tcExtendGlobalValEnv, 
34                           isLocalThing, tcSetEnv, tcSetInstEnv, initTcEnv, getTcGEnv
35                         )
36 import TcRules          ( tcIfaceRules, tcSourceRules )
37 import TcForeign        ( tcForeignImports, tcForeignExports )
38 import TcIfaceSig       ( tcInterfaceSigs )
39 import TcInstDcls       ( tcInstDecls1, tcInstDecls2 )
40 import TcSimplify       ( tcSimplifyTop )
41 import TcTyClsDecls     ( tcTyAndClassDecls )
42
43 import CoreUnfold       ( unfoldingTemplate, hasUnfolding )
44 import Type             ( funResultTy, splitForAllTys, openTypeKind )
45 import Bag              ( isEmptyBag )
46 import ErrUtils         ( printErrorsAndWarnings, dumpIfSet_dyn, showPass )
47 import Id               ( idType, idUnfolding )
48 import Module           ( Module )
49 import Name             ( Name, toRdrName )
50 import Name             ( nameEnvElts, lookupNameEnv )
51 import TyCon            ( tyConGenInfo )
52 import Util
53 import BasicTypes       ( EP(..), Fixity )
54 import Bag              ( isEmptyBag )
55 import Outputable
56 import HscTypes         ( PersistentCompilerState(..), HomeSymbolTable, 
57                           PackageTypeEnv, ModIface(..),
58                           TypeEnv, extendTypeEnvList, 
59                           TyThing(..), implicitTyThingIds, 
60                           mkTypeEnv
61                         )
62 \end{code}
63
64 Outside-world interface:
65 \begin{code}
66
67 -- Convenient type synonyms first:
68 data TcResults
69   = TcResults {
70         -- All these fields have info *just for this module*
71         tc_env     :: TypeEnv,                  -- The top level TypeEnv
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         -> PersistentCompilerState
81         -> HomeSymbolTable
82         -> ModIface             -- Iface for this module
83         -> PrintUnqualified     -- For error printing
84         -> [RenamedHsDecl]
85         -> IO (Maybe (PersistentCompilerState, TcResults))
86                         -- The new PCS is Augmented with imported information,
87                                                 -- (but not stuff from this module)
88
89
90 typecheckModule dflags pcs hst mod_iface unqual decls
91   = do  { maybe_tc_result <- typecheck dflags pcs hst unqual $
92                              tcModule pcs hst get_fixity this_mod decls
93         ; printTcDump dflags maybe_tc_result
94         ; return maybe_tc_result }
95   where
96     this_mod   = mi_module   mod_iface
97     fixity_env = mi_fixities mod_iface
98
99     get_fixity :: Name -> Maybe Fixity
100     get_fixity nm = lookupNameEnv fixity_env nm
101
102 ---------------
103 typecheckExpr :: DynFlags
104               -> PersistentCompilerState
105               -> HomeSymbolTable
106               -> PrintUnqualified       -- For error printing
107               -> Module
108               -> (RenamedHsExpr,        -- The expression itself
109                   [RenamedHsDecl])      -- Plus extra decls it sucked in from interface files
110               -> IO (Maybe (PersistentCompilerState, TypecheckedHsExpr, TcType))
111
112 typecheckExpr dflags pcs hst unqual this_mod (expr, decls)
113   = typecheck dflags pcs hst unqual $
114
115          -- use the default default settings, i.e. [Integer, Double]
116     tcSetDefaultTys defaultDefaultTys $
117     tcImports pcs hst get_fixity this_mod decls `thenTc` \ (env, new_pcs, local_inst_info, deriv_binds, local_rules) ->
118     ASSERT( null local_inst_info && nullBinds deriv_binds && null local_rules )
119
120     tcSetEnv env                                $
121     newTyVarTy openTypeKind     `thenTc` \ ty ->
122     tcMonoExpr expr ty          `thenTc` \ (expr', lie) ->
123     tcSimplifyTop lie           `thenTc` \ binds ->
124     let all_expr = mkHsLet binds expr' in
125     zonkExpr all_expr           `thenNF_Tc` \ zonked_expr ->
126     zonkTcType ty               `thenNF_Tc` \ zonked_ty ->
127     returnTc (new_pcs, zonked_expr, zonked_ty) 
128   where
129     get_fixity :: Name -> Maybe Fixity
130     get_fixity n = pprPanic "typecheckExpr" (ppr n)
131
132 ---------------
133 typecheck :: DynFlags
134           -> PersistentCompilerState
135           -> HomeSymbolTable
136           -> PrintUnqualified   -- For error printing
137           -> TcM r
138           -> IO (Maybe r)
139
140 typecheck dflags pcs hst unqual thing_inside 
141  = do   { showPass dflags "Typechecker";
142         ; env <- initTcEnv hst (pcs_PTE pcs)
143
144         ; (maybe_tc_result, (warns,errs)) <- initTc dflags env thing_inside
145
146         ; printErrorsAndWarnings unqual (errs,warns)
147
148         ; if isEmptyBag errs then 
149              return maybe_tc_result
150            else 
151              return Nothing 
152         }
153 \end{code}
154
155 The internal monster:
156 \begin{code}
157 tcModule :: PersistentCompilerState
158          -> HomeSymbolTable
159          -> (Name -> Maybe Fixity)
160          -> Module
161          -> [RenamedHsDecl]
162          -> TcM (PersistentCompilerState, TcResults)
163
164 tcModule pcs hst get_fixity this_mod decls
165   =     -- Type-check the type and class decls, and all imported decls
166     tcImports pcs hst get_fixity this_mod decls `thenTc` \ (env, new_pcs, local_inst_info, deriv_binds, local_rules) ->
167
168     tcSetEnv env                                $
169
170         -- Foreign import declarations next
171 --  traceTc (text "Tc4")                        `thenNF_Tc_`
172     tcForeignImports decls                      `thenTc`    \ (fo_ids, foi_decls) ->
173     tcExtendGlobalValEnv fo_ids                 $
174     
175         -- Default declarations
176     tcDefaults decls                            `thenTc` \ defaulting_tys ->
177     tcSetDefaultTys defaulting_tys              $
178         
179         -- Value declarations next.
180         -- We also typecheck any extra binds that came out of the "deriving" process
181 --  traceTc (text "Tc5")                                `thenNF_Tc_`
182     tcTopBinds (val_binds `ThenBinds` deriv_binds)      `thenTc` \ ((val_binds, env), lie_valdecls) ->
183     tcSetEnv env $
184     
185         -- Foreign export declarations next
186 --  traceTc (text "Tc6")                `thenNF_Tc_`
187     tcForeignExports decls              `thenTc`    \ (lie_fodecls, foe_binds, foe_decls) ->
188     
189         -- Second pass over class and instance declarations,
190         -- to compile the bindings themselves.
191     tcInstDecls2  local_inst_info               `thenNF_Tc` \ (lie_instdecls, inst_binds) ->
192     tcClassDecls2 this_mod tycl_decls           `thenNF_Tc` \ (lie_clasdecls, cls_dm_binds) ->
193     tcSourceRules source_rules                  `thenNF_Tc` \ (lie_rules,     more_local_rules) ->
194     
195          -- Deal with constant or ambiguous InstIds.  How could
196          -- there be ambiguous ones?  They can only arise if a
197          -- top-level decl falls under the monomorphism
198          -- restriction, and no subsequent decl instantiates its
199          -- type.  (Usually, ambiguous type variables are resolved
200          -- during the generalisation step.)
201     let
202         lie_alldecls = lie_valdecls     `plusLIE`
203                        lie_instdecls    `plusLIE`
204                        lie_clasdecls    `plusLIE`
205                        lie_fodecls      `plusLIE`
206                        lie_rules
207     in
208     tcSimplifyTop lie_alldecls                  `thenTc` \ const_inst_binds ->
209     
210         -- Backsubstitution.    This must be done last.
211         -- Even tcSimplifyTop may do some unification.
212     let
213         all_binds = val_binds           `AndMonoBinds`
214                     inst_binds          `AndMonoBinds`
215                     cls_dm_binds        `AndMonoBinds`
216                     const_inst_binds    `AndMonoBinds`
217                     foe_binds
218     in
219 --  traceTc (text "Tc9")                `thenNF_Tc_`
220     zonkTopBinds all_binds              `thenNF_Tc` \ (all_binds', final_env)  ->
221     tcSetEnv final_env                  $
222         -- zonkTopBinds puts all the top-level Ids into the tcGEnv
223     zonkForeignExports foe_decls        `thenNF_Tc` \ foe_decls' ->
224     zonkRules more_local_rules          `thenNF_Tc` \ more_local_rules' ->
225     
226     
227     let local_things = filter (isLocalThing this_mod) (nameEnvElts (getTcGEnv final_env))
228
229         -- Create any necessary "implicit" bindings (data constructors etc)
230         -- Should we create bindings for dictionary constructors?
231         -- They are always fully applied, and the bindings are just there
232         -- to support partial applications. But it's easier to let them through.
233         implicit_binds = andMonoBindList [ CoreMonoBind id (unfoldingTemplate unf)
234                                          | id <- implicitTyThingIds local_things
235                                          , let unf = idUnfolding id
236                                          , hasUnfolding unf
237                                          ]
238
239         local_type_env :: TypeEnv
240         local_type_env = mkTypeEnv local_things
241             
242         all_local_rules = local_rules ++ more_local_rules'
243     in  
244 --  traceTc (text "Tc10")               `thenNF_Tc_`
245     returnTc (new_pcs,
246               TcResults { tc_env     = local_type_env,
247                           tc_binds   = implicit_binds `AndMonoBinds` all_binds', 
248                           tc_fords   = foi_decls ++ foe_decls',
249                           tc_rules   = all_local_rules
250                         }
251     )
252   where
253     tycl_decls   = [d | TyClD d <- decls]
254     val_binds    = foldr ThenBinds EmptyBinds [binds | ValD binds <- decls]
255     source_rules = [d | RuleD d <- decls, not (isIfaceRuleDecl d)]
256 \end{code}
257
258
259 \begin{code}
260 tcImports :: PersistentCompilerState
261           -> HomeSymbolTable
262           -> (Name -> Maybe Fixity)
263           -> Module
264           -> [RenamedHsDecl]
265           -> TcM (TcEnv, PersistentCompilerState, 
266                   [InstInfo], RenamedHsBinds, [TypecheckedRuleDecl])
267
268 -- tcImports is a slight mis-nomer.  
269 -- It deals with everythign that could be an import:
270 --      type and class decls
271 --      interface signatures
272 --      instance decls
273 --      rule decls
274 -- These can occur in source code too, of course
275
276 tcImports pcs hst get_fixity this_mod decls
277   = fixTc (\ ~(unf_env, _, _, _, _) -> 
278           -- (unf_env :: RecTcEnv) is used for type-checking interface pragmas
279           -- which is done lazily [ie failure just drops the pragma
280           -- without having any global-failure effect].
281           -- 
282           -- unf_env is also used to get the pragama info
283           -- for imported dfuns and default methods
284                 
285 --      traceTc (text "Tc1")                    `thenNF_Tc_`
286         tcTyAndClassDecls unf_env tycl_decls    `thenTc` \ env ->
287         tcSetEnv env                            $
288         
289                 -- Typecheck the instance decls, includes deriving
290 --      traceTc (text "Tc2")    `thenNF_Tc_`
291         tcInstDecls1 (pcs_insts pcs) (pcs_PRS pcs) 
292                      hst unf_env get_fixity this_mod 
293                      decls                      `thenTc` \ (new_pcs_insts, inst_env, local_inst_info, deriv_binds) ->
294         tcSetInstEnv inst_env                   $
295         
296         -- Interface type signatures
297         -- We tie a knot so that the Ids read out of interfaces are in scope
298         --   when we read their pragmas.
299         -- What we rely on is that pragmas are typechecked lazily; if
300         --   any type errors are found (ie there's an inconsistency)
301         --   we silently discard the pragma
302 --      traceTc (text "Tc3")                    `thenNF_Tc_`
303         tcInterfaceSigs unf_env tycl_decls      `thenTc` \ sig_ids ->
304         tcExtendGlobalValEnv sig_ids            $
305         
306         
307         tcIfaceRules (pcs_rules pcs) this_mod iface_rules       `thenNF_Tc` \ (new_pcs_rules, local_rules) ->
308
309         tcGetEnv                                                `thenTc` \ unf_env ->
310         let
311             imported_things = filter (not . isLocalThing this_mod) (nameEnvElts (getTcGEnv unf_env))
312
313             new_pte :: PackageTypeEnv
314             new_pte = extendTypeEnvList (pcs_PTE pcs) imported_things
315             
316             new_pcs :: PersistentCompilerState
317             new_pcs = pcs { pcs_PTE   = new_pte,
318                             pcs_insts = new_pcs_insts,
319                             pcs_rules = new_pcs_rules
320                       }
321         in
322         returnTc (unf_env, new_pcs, local_inst_info, deriv_binds, local_rules)
323     )
324   where
325     tycl_decls  = [d | TyClD d <- decls]
326     iface_rules = [d | RuleD d <- decls, isIfaceRuleDecl d]
327 \end{code}    
328
329 %************************************************************************
330 %*                                                                      *
331 \subsection{Dumping output}
332 %*                                                                      *
333 %************************************************************************
334
335 \begin{code}
336 printTcDump dflags Nothing = return ()
337 printTcDump dflags (Just (_, results))
338   = do dumpIfSet_dyn dflags Opt_D_dump_types 
339                      "Type signatures" (dump_sigs results)
340        dumpIfSet_dyn dflags Opt_D_dump_tc    
341                      "Typechecked" (dump_tc results) 
342
343 dump_tc results
344   = vcat [ppr (tc_binds results),
345           pp_rules (tc_rules results),
346           ppr_gen_tycons [tc | ATyCon tc <- nameEnvElts (tc_env results)]
347     ]
348
349 dump_sigs results       -- Print type signatures
350   =     -- Convert to HsType so that we get source-language style printing
351         -- And sort by RdrName
352     vcat $ map ppr_sig $ sortLt lt_sig $
353     [ (toRdrName id, toHsType (idType id))
354     | AnId id <- nameEnvElts (tc_env results),
355       want_sig id
356     ]
357   where
358     lt_sig (n1,_) (n2,_) = n1 < n2
359     ppr_sig (n,t)        = ppr n <+> dcolon <+> ppr t
360
361     want_sig id | opt_PprStyle_Debug = True
362                 | otherwise          = True     -- For now
363
364 ppr_gen_tycons tcs = vcat [ptext SLIT("{-# Generic type constructor details"),
365                            vcat (map ppr_gen_tycon tcs),
366                            ptext SLIT("#-}")
367                      ]
368
369 -- x&y are now Id's, not CoreExpr's 
370 ppr_gen_tycon tycon 
371   | Just ep <- tyConGenInfo tycon
372   = (ppr tycon <> colon) $$ nest 4 (ppr_ep ep)
373
374   | otherwise = ppr tycon <> colon <+> ptext SLIT("Not derivable")
375
376 ppr_ep (EP from to)
377   = vcat [ ptext SLIT("Rep type:") <+> ppr (funResultTy from_tau),
378            ptext SLIT("From:") <+> ppr (unfoldingTemplate (idUnfolding from)),
379            ptext SLIT("To:")   <+> ppr (unfoldingTemplate (idUnfolding to))
380     ]
381   where
382     (_,from_tau) = splitForAllTys (idType from)
383
384 pp_rules [] = empty
385 pp_rules rs = vcat [ptext SLIT("{-# RULES"),
386                     nest 4 (vcat (map ppr rs)),
387                     ptext SLIT("#-}")]
388 \end{code}