[project @ 2000-11-16 11:39:36 by simonmar]
[ghc-hetmet.git] / ghc / compiler / main / HscMain.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
3 %
4 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
5
6 \begin{code}
7 module HscMain ( HscResult(..), hscMain, 
8                  initPersistentCompilerState ) where
9
10 #include "HsVersions.h"
11
12 import Maybe            ( isJust )
13 import IO               ( hPutStrLn, stderr )
14 import HsSyn
15
16 import StringBuffer     ( hGetStringBuffer )
17 import Parser
18 import Lex              ( PState(..), ParseResult(..) )
19 import SrcLoc           ( mkSrcLoc )
20
21 import Rename           ( renameModule, checkOldIface, closeIfaceDecls )
22 import Rules            ( emptyRuleBase )
23 import PrelInfo         ( wiredInThingEnv, wiredInThings )
24 import PrelNames        ( knownKeyNames )
25 import MkIface          ( completeIface, mkModDetailsFromIface, mkModDetails,
26                           writeIface, pprIface )
27 import TcModule         ( TcResults(..), typecheckModule )
28 import InstEnv          ( emptyInstEnv )
29 import Desugar          ( deSugar )
30 import SimplCore        ( core2core )
31 import OccurAnal        ( occurAnalyseBinds )
32 import CoreUtils        ( coreBindsSize )
33 import CoreTidy         ( tidyCorePgm )
34 import CoreToStg        ( topCoreBindsToStg )
35 import StgSyn           ( collectFinalStgBinders )
36 import SimplStg         ( stg2stg )
37 import CodeGen          ( codeGen )
38 import CodeOutput       ( codeOutput )
39
40 import Module           ( ModuleName, moduleName, mkModuleInThisPackage )
41 import CmdLineOpts
42 import ErrUtils         ( dumpIfSet_dyn, showPass )
43 import Util             ( unJust )
44 import UniqSupply       ( mkSplitUniqSupply )
45
46 import Bag              ( emptyBag )
47 import Outputable
48 import Interpreter      ( UnlinkedIBind, ItblEnv, stgToInterpSyn )
49 import HscStats         ( ppSourceStats )
50 import HscTypes         ( ModDetails, ModIface(..), PersistentCompilerState(..),
51                           PersistentRenamerState(..), ModuleLocation(..),
52                           HomeSymbolTable, 
53                           OrigNameEnv(..), PackageRuleBase, HomeIfaceTable, 
54                           typeEnvClasses, typeEnvTyCons, emptyIfaceTable )
55 import FiniteMap        ( FiniteMap, plusFM, emptyFM, addToFM )
56 import OccName          ( OccName )
57 import Name             ( Name, nameModule, nameOccName, getName  )
58 import Name             ( emptyNameEnv )
59 import Module           ( Module, lookupModuleEnvByName )
60
61 import Monad            ( when )
62 \end{code}
63
64
65 %************************************************************************
66 %*                                                                      *
67 \subsection{The main compiler pipeline}
68 %*                                                                      *
69 %************************************************************************
70
71 \begin{code}
72 data HscResult
73    = HscOK   ModDetails              -- new details (HomeSymbolTable additions)
74              (Maybe ModIface)        -- new iface (if any compilation was done)
75              (Maybe String)          -- generated stub_h filename (in /tmp)
76              (Maybe String)          -- generated stub_c filename (in /tmp)
77              (Maybe ([UnlinkedIBind],ItblEnv)) -- interpreted code, if any
78              PersistentCompilerState -- updated PCS
79
80    | HscFail PersistentCompilerState -- updated PCS
81         -- no errors or warnings; the individual passes
82         -- (parse/rename/typecheck) print messages themselves
83
84 hscMain
85   :: DynFlags
86   -> Bool                       -- source unchanged?
87   -> ModuleLocation             -- location info
88   -> Maybe ModIface             -- old interface, if available
89   -> HomeSymbolTable            -- for home module ModDetails
90   -> HomeIfaceTable
91   -> PersistentCompilerState    -- IN: persistent compiler state
92   -> IO HscResult
93
94 hscMain dflags source_unchanged location maybe_old_iface hst hit pcs
95  = do {
96       putStrLn ("CHECKING OLD IFACE for hs = " ++ show (ml_hs_file location)
97                 ++ ", hspp = " ++ show (ml_hspp_file location));
98
99       (pcs_ch, errs_found, (recomp_reqd, maybe_checked_iface))
100          <- checkOldIface dflags hit hst pcs (unJust (ml_hi_file location) "hscMain")
101                           source_unchanged maybe_old_iface;
102
103       if errs_found then
104          return (HscFail pcs_ch)
105       else do {
106
107       let no_old_iface = not (isJust maybe_checked_iface)
108           what_next | recomp_reqd || no_old_iface = hscRecomp 
109                     | otherwise                   = hscNoRecomp
110       ;
111       what_next dflags location maybe_checked_iface
112                 hst hit pcs_ch
113       }}
114
115
116 hscNoRecomp dflags location maybe_checked_iface hst hit pcs_ch
117  = do {
118       hPutStrLn stderr "COMPILATION NOT REQUIRED";
119       -- we definitely expect to have the old interface available
120       let old_iface = case maybe_checked_iface of 
121                          Just old_if -> old_if
122                          Nothing -> panic "hscNoRecomp:old_iface"
123           this_mod = mi_module old_iface
124       ;
125       -- CLOSURE
126       (pcs_cl, closure_errs, cl_hs_decls) 
127          <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
128       if closure_errs then 
129          return (HscFail pcs_cl) 
130       else do {
131
132       -- TYPECHECK
133       maybe_tc_result <- typecheckModule dflags this_mod pcs_cl hst 
134                                          old_iface alwaysQualify cl_hs_decls;
135       case maybe_tc_result of {
136          Nothing -> return (HscFail pcs_cl);
137          Just tc_result -> do {
138
139       let pcs_tc      = tc_pcs tc_result
140           env_tc      = tc_env tc_result
141           local_insts = tc_insts tc_result
142           local_rules = tc_rules tc_result
143       ;
144       -- create a new details from the closed, typechecked, old iface
145       let new_details = mkModDetailsFromIface env_tc local_insts local_rules
146       ;
147       return (HscOK new_details
148                     Nothing -- tells CM to use old iface and linkables
149                     Nothing Nothing -- foreign export stuff
150                     Nothing -- ibinds
151                     pcs_tc)
152       }}}}
153
154
155 hscRecomp dflags location maybe_checked_iface hst hit pcs_ch
156  = do   {
157         ; hPutStrLn stderr "COMPILATION IS REQUIRED";
158
159           -- what target are we shooting for?
160         ; let toInterp = dopt_HscLang dflags == HscInterpreted
161
162             -------------------
163             -- PARSE
164             -------------------
165         ; maybe_parsed <- myParseModule dflags (unJust (ml_hspp_file location) "hscRecomp:hspp")
166         ; case maybe_parsed of {
167              Nothing -> return (HscFail pcs_ch);
168              Just rdr_module -> do {
169         ; let this_mod = mkModuleInThisPackage (hsModuleName rdr_module)
170     
171             -------------------
172             -- RENAME
173             -------------------
174         ; (pcs_rn, maybe_rn_result) 
175              <- renameModule dflags hit hst pcs_ch this_mod rdr_module
176         ; case maybe_rn_result of {
177              Nothing -> return (HscFail pcs_rn);
178              Just (print_unqualified, is_exported, new_iface, rn_hs_decls) -> do {
179     
180             -------------------
181             -- TYPECHECK
182             -------------------
183         ; maybe_tc_result <- typecheckModule dflags this_mod pcs_rn hst new_iface 
184                                              print_unqualified rn_hs_decls
185         ; case maybe_tc_result of {
186              Nothing -> do { hPutStrLn stderr "Typecheck failed" 
187                            ; return (HscFail pcs_rn) } ;
188              Just tc_result -> do {
189     
190         ; let pcs_tc        = tc_pcs tc_result
191               env_tc        = tc_env tc_result
192               local_insts   = tc_insts tc_result
193
194             -------------------
195             -- DESUGAR, SIMPLIFY, TIDY-CORE
196             -------------------
197           -- We grab the the unfoldings at this point.
198         ; simpl_result <- dsThenSimplThenTidy dflags (pcs_rules pcs_tc) this_mod 
199                                               print_unqualified is_exported tc_result hst
200         ; let (tidy_binds, orphan_rules, foreign_stuff) = simpl_result
201             
202             -------------------
203             -- CONVERT TO STG
204             -------------------
205         ; (stg_binds, oa_tidy_binds, cost_centre_info, top_level_ids) 
206              <- myCoreToStg dflags this_mod tidy_binds
207
208
209             -------------------
210             -- BUILD THE NEW ModDetails AND ModIface
211             -------------------
212         ; let new_details = mkModDetails env_tc local_insts tidy_binds 
213                                          top_level_ids orphan_rules
214         ; final_iface <- mkFinalIface dflags location maybe_checked_iface 
215                                       new_iface new_details
216
217             -------------------
218             -- COMPLETE CODE GENERATION
219             -------------------
220         ; (maybe_stub_h_filename, maybe_stub_c_filename, maybe_ibinds)
221              <- restOfCodeGeneration dflags toInterp this_mod
222                    (map ideclName (hsModuleImports rdr_module))
223                    cost_centre_info foreign_stuff env_tc stg_binds oa_tidy_binds
224                    hit (pcs_PIT pcs_tc)       
225
226           -- and the answer is ...
227         ; return (HscOK new_details (Just final_iface)
228                         maybe_stub_h_filename maybe_stub_c_filename
229                         maybe_ibinds pcs_tc)
230           }}}}}}}
231
232
233
234 mkFinalIface dflags location maybe_old_iface new_iface new_details
235  = case completeIface maybe_old_iface new_iface new_details of
236       (new_iface, Nothing) -- no change in the interfacfe
237          -> do when (dopt Opt_D_dump_hi_diffs dflags)
238                     (printDump (text "INTERFACE UNCHANGED"))
239                dumpIfSet_dyn dflags Opt_D_dump_hi
240                              "UNCHANGED FINAL INTERFACE" (pprIface new_iface)
241                return new_iface
242       (new_iface, Just sdoc_diffs)
243          -> do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "INTERFACE HAS CHANGED" sdoc_diffs
244                dumpIfSet_dyn dflags Opt_D_dump_hi "NEW FINAL INTERFACE" (pprIface new_iface)
245                -- Write the interface file
246                writeIface (unJust (ml_hi_file location) "hscRecomp:hi") new_iface
247                return new_iface
248
249
250 myParseModule dflags src_filename
251  = do --------------------------  Parser  ----------------
252       showPass dflags "Parser"
253       -- _scc_     "Parser"
254
255       buf <- hGetStringBuffer True{-expand tabs-} src_filename
256
257       let glaexts | dopt Opt_GlasgowExts dflags = 1#
258                   | otherwise                 = 0#
259
260       case parse buf PState{ bol = 0#, atbol = 1#,
261                              context = [], glasgow_exts = glaexts,
262                              loc = mkSrcLoc (_PK_ src_filename) 1 } of {
263
264         PFailed err -> do { hPutStrLn stderr (showSDoc err);
265                             return Nothing };
266
267         POk _ (PModule rdr_module@(HsModule mod_name _ _ _ _ _ _)) -> do {
268
269       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
270       
271       dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
272                            (ppSourceStats False rdr_module) ;
273       
274       return (Just rdr_module)
275       }}
276
277
278 restOfCodeGeneration dflags toInterp this_mod imported_module_names cost_centre_info 
279                      foreign_stuff env_tc stg_binds oa_tidy_binds
280                      hit pit -- these last two for mapping ModNames to Modules
281  | toInterp
282  = do (ibinds,itbl_env) 
283          <- stgToInterpSyn (map fst stg_binds) local_tycons local_classes
284       return (Nothing, Nothing, Just (ibinds,itbl_env))
285
286  | otherwise
287  = do --------------------------  Code generation -------------------------------
288       -- _scc_     "CodeGen"
289       abstractC <- codeGen dflags this_mod imported_modules
290                            cost_centre_info fe_binders
291                            local_tycons stg_binds
292
293       --------------------------  Code output -------------------------------
294       -- _scc_     "CodeOutput"
295       (maybe_stub_h_name, maybe_stub_c_name)
296          <- codeOutput dflags this_mod local_tycons
297                        oa_tidy_binds stg_binds
298                        c_code h_code abstractC
299
300       return (maybe_stub_h_name, maybe_stub_c_name, Nothing)
301  where
302     local_tycons     = typeEnvTyCons env_tc
303     local_classes    = typeEnvClasses env_tc
304     imported_modules = map mod_name_to_Module imported_module_names
305     (fe_binders,h_code,c_code) = foreign_stuff
306
307     mod_name_to_Module :: ModuleName -> Module
308     mod_name_to_Module nm
309        = let str_mi = case lookupModuleEnvByName hit nm of
310                           Just mi -> mi
311                           Nothing -> case lookupModuleEnvByName pit nm of
312                                         Just mi -> mi
313                                         Nothing -> barf nm
314          in  mi_module str_mi
315     barf nm = pprPanic "mod_name_to_Module: no hst or pst mapping for" 
316                        (ppr nm)
317
318
319 dsThenSimplThenTidy dflags rule_base this_mod print_unqual is_exported tc_result hst
320  = do --------------------------  Desugaring ----------------
321       -- _scc_     "DeSugar"
322       (desugared, rules, h_code, c_code, fe_binders) 
323          <- deSugar dflags this_mod print_unqual hst tc_result
324
325       --------------------------  Main Core-language transformations ----------------
326       -- _scc_     "Core2Core"
327       (simplified, orphan_rules) 
328          <- core2core dflags rule_base hst is_exported desugared rules
329
330       -- Do the final tidy-up
331       (tidy_binds, tidy_orphan_rules) 
332          <- tidyCorePgm dflags this_mod simplified orphan_rules
333       
334       return (tidy_binds, tidy_orphan_rules, (fe_binders,h_code,c_code))
335
336
337 myCoreToStg dflags this_mod tidy_binds
338  = do 
339       c2s_uniqs <- mkSplitUniqSupply 'c'
340       st_uniqs  <- mkSplitUniqSupply 'g'
341       let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds
342
343       () <- coreBindsSize occ_anal_tidy_binds `seq` return ()
344       -- TEMP: the above call zaps some space usage allocated by the
345       -- simplifier, which for reasons I don't understand, persists
346       -- thoroughout code generation
347
348       showPass dflags "Core2Stg"
349       -- _scc_     "Core2Stg"
350       let stg_binds   = topCoreBindsToStg c2s_uniqs occ_anal_tidy_binds
351
352       showPass dflags "Stg2Stg"
353       -- _scc_     "Stg2Stg"
354       (stg_binds2, cost_centre_info) <- stg2stg dflags this_mod st_uniqs stg_binds
355       let final_ids = collectFinalStgBinders (map fst stg_binds2)
356
357       return (stg_binds2, occ_anal_tidy_binds, cost_centre_info, final_ids)
358 \end{code}
359
360
361 %************************************************************************
362 %*                                                                      *
363 \subsection{Compiling an expression}
364 %*                                                                      *
365 %************************************************************************
366
367 hscExpr
368   :: DynFlags
369   -> HomeSymbolTable    
370   -> HomeIfaceTable
371   -> PersistentCompilerState    -- IN: persistent compiler state
372   -> Module                     -- Context for compiling
373   -> String                     -- The expression
374   -> IO HscResult
375
376 hscExpr dflags hst hit pcs this_module expr
377   = do  {       -- Parse it
378         ; maybe_parsed <- myParseExpr dflags expr
379         ; case maybe_parsed of {
380              Nothing -> return (HscFail pcs_ch);
381              Just parsed_expr -> do {
382
383                 -- Rename it
384           (new_pcs, maybe_renamed_expr) <- renameExpr dflags hit hst pcs this_module parsed_expr ;
385         ; case maybe_renamed_expr of {
386                 Nothing -> FAIL
387                 Just renamed_expr -> 
388
389                 -- Typecheck it
390           maybe_tc_expr <- typecheckExpr dflags pcs hst unqual renamed_expr 
391         ; case maybe_tc_expr of
392                 Nothing -> FAIL
393                 Just typechecked_expr ->
394
395         
396
397
398 %************************************************************************
399 %*                                                                      *
400 \subsection{Initial persistent state}
401 %*                                                                      *
402 %************************************************************************
403
404 \begin{code}
405 initPersistentCompilerState :: IO PersistentCompilerState
406 initPersistentCompilerState 
407   = do prs <- initPersistentRenamerState
408        return (
409         PCS { pcs_PIT   = emptyIfaceTable,
410               pcs_PTE   = wiredInThingEnv,
411               pcs_insts = emptyInstEnv,
412               pcs_rules = emptyRuleBase,
413               pcs_PRS   = prs
414             }
415         )
416
417 initPersistentRenamerState :: IO PersistentRenamerState
418   = do ns <- mkSplitUniqSupply 'r'
419        return (
420         PRS { prsOrig  = Orig { origNames  = initOrigNames,
421                                 origIParam = emptyFM },
422               prsDecls = (emptyNameEnv, 0),
423               prsInsts = (emptyBag, 0),
424               prsRules = (emptyBag, 0),
425               prsNS    = ns
426             }
427         )
428
429 initOrigNames :: FiniteMap (ModuleName,OccName) Name
430 initOrigNames 
431    = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
432      where
433         grab names = foldl add emptyFM names
434         add env name 
435            = addToFM env (moduleName (nameModule name), nameOccName name) name
436
437
438 initRules :: PackageRuleBase
439 initRules = emptyRuleBase
440 {- SHOULD BE (ish)
441             foldl add emptyVarEnv builtinRules
442           where
443             add env (name,rule) 
444               = extendRuleBase env name rule
445 -}
446 \end{code}