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