[project @ 2000-11-16 15:57:05 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       ;
124       -- CLOSURE
125       (pcs_cl, closure_errs, cl_hs_decls) 
126          <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
127       if closure_errs then 
128          return (HscFail pcs_cl) 
129       else do {
130
131       -- TYPECHECK
132       maybe_tc_result <- typecheckModule dflags pcs_cl hst 
133                                          old_iface alwaysQualify cl_hs_decls;
134       case maybe_tc_result of {
135          Nothing -> return (HscFail pcs_cl);
136          Just (pcs_tc, tc_result) -> do {
137
138       let env_tc      = tc_env tc_result
139           local_insts = tc_insts tc_result
140           local_rules = tc_rules tc_result
141       ;
142       -- create a new details from the closed, typechecked, old iface
143       let new_details = mkModDetailsFromIface env_tc local_insts local_rules
144       ;
145       return (HscOK new_details
146                     Nothing -- tells CM to use old iface and linkables
147                     Nothing Nothing -- foreign export stuff
148                     Nothing -- ibinds
149                     pcs_tc)
150       }}}}
151
152
153 hscRecomp dflags location maybe_checked_iface hst hit pcs_ch
154  = do   {
155         ; hPutStrLn stderr "COMPILATION IS REQUIRED";
156
157           -- what target are we shooting for?
158         ; let toInterp = dopt_HscLang dflags == HscInterpreted
159
160             -------------------
161             -- PARSE
162             -------------------
163         ; maybe_parsed <- myParseModule dflags (unJust (ml_hspp_file location) "hscRecomp:hspp")
164         ; case maybe_parsed of {
165              Nothing -> return (HscFail pcs_ch);
166              Just rdr_module -> do {
167         ; let this_mod = mkModuleInThisPackage (hsModuleName rdr_module)
168     
169             -------------------
170             -- RENAME
171             -------------------
172         ; (pcs_rn, maybe_rn_result) 
173              <- renameModule dflags hit hst pcs_ch this_mod rdr_module
174         ; case maybe_rn_result of {
175              Nothing -> return (HscFail pcs_rn);
176              Just (print_unqualified, is_exported, new_iface, rn_hs_decls) -> do {
177     
178             -------------------
179             -- TYPECHECK
180             -------------------
181         ; maybe_tc_result <- typecheckModule dflags pcs_rn hst new_iface 
182                                              print_unqualified rn_hs_decls
183         ; case maybe_tc_result of {
184              Nothing -> do { hPutStrLn stderr "Typecheck failed" 
185                            ; return (HscFail pcs_rn) } ;
186              Just (pcs_tc, tc_result) -> do {
187     
188         ; let env_tc        = tc_env tc_result
189               local_insts   = tc_insts tc_result
190
191             -------------------
192             -- DESUGAR, SIMPLIFY, TIDY-CORE
193             -------------------
194           -- We grab the the unfoldings at this point.
195         ; simpl_result <- dsThenSimplThenTidy dflags pcs_tc hst this_mod 
196                                               print_unqualified is_exported tc_result
197         ; let (tidy_binds, orphan_rules, foreign_stuff) = simpl_result
198             
199             -------------------
200             -- CONVERT TO STG
201             -------------------
202         ; (stg_binds, oa_tidy_binds, cost_centre_info, top_level_ids) 
203              <- myCoreToStg dflags this_mod tidy_binds
204
205
206             -------------------
207             -- BUILD THE NEW ModDetails AND ModIface
208             -------------------
209         ; let new_details = mkModDetails env_tc local_insts tidy_binds 
210                                          top_level_ids orphan_rules
211         ; final_iface <- mkFinalIface dflags location maybe_checked_iface 
212                                       new_iface new_details
213
214             -------------------
215             -- COMPLETE CODE GENERATION
216             -------------------
217         ; (maybe_stub_h_filename, maybe_stub_c_filename, maybe_ibinds)
218              <- restOfCodeGeneration dflags toInterp this_mod
219                    (map ideclName (hsModuleImports rdr_module))
220                    cost_centre_info foreign_stuff env_tc stg_binds oa_tidy_binds
221                    hit (pcs_PIT pcs_tc)       
222
223           -- and the answer is ...
224         ; return (HscOK new_details (Just final_iface)
225                         maybe_stub_h_filename maybe_stub_c_filename
226                         maybe_ibinds pcs_tc)
227           }}}}}}}
228
229
230
231 mkFinalIface dflags location maybe_old_iface new_iface new_details
232  = case completeIface maybe_old_iface new_iface new_details of
233       (new_iface, Nothing) -- no change in the interfacfe
234          -> do when (dopt Opt_D_dump_hi_diffs dflags)
235                     (printDump (text "INTERFACE UNCHANGED"))
236                dumpIfSet_dyn dflags Opt_D_dump_hi
237                              "UNCHANGED FINAL INTERFACE" (pprIface new_iface)
238                return new_iface
239       (new_iface, Just sdoc_diffs)
240          -> do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "INTERFACE HAS CHANGED" sdoc_diffs
241                dumpIfSet_dyn dflags Opt_D_dump_hi "NEW FINAL INTERFACE" (pprIface new_iface)
242                -- Write the interface file
243                writeIface (unJust (ml_hi_file location) "hscRecomp:hi") new_iface
244                return new_iface
245
246
247 myParseModule dflags src_filename
248  = do --------------------------  Parser  ----------------
249       showPass dflags "Parser"
250       -- _scc_     "Parser"
251
252       buf <- hGetStringBuffer True{-expand tabs-} src_filename
253
254       let glaexts | dopt Opt_GlasgowExts dflags = 1#
255                   | otherwise                 = 0#
256
257       case parse buf PState{ bol = 0#, atbol = 1#,
258                              context = [], glasgow_exts = glaexts,
259                              loc = mkSrcLoc (_PK_ src_filename) 1 } of {
260
261         PFailed err -> do { hPutStrLn stderr (showSDoc err);
262                             return Nothing };
263
264         POk _ (PModule rdr_module@(HsModule mod_name _ _ _ _ _ _)) -> do {
265
266       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
267       
268       dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
269                            (ppSourceStats False rdr_module) ;
270       
271       return (Just rdr_module)
272       }}
273
274
275 restOfCodeGeneration dflags toInterp this_mod imported_module_names cost_centre_info 
276                      foreign_stuff env_tc stg_binds oa_tidy_binds
277                      hit pit -- these last two for mapping ModNames to Modules
278  | toInterp
279  = do (ibinds,itbl_env) 
280          <- stgToInterpSyn (map fst stg_binds) local_tycons local_classes
281       return (Nothing, Nothing, Just (ibinds,itbl_env))
282
283  | otherwise
284  = do --------------------------  Code generation -------------------------------
285       -- _scc_     "CodeGen"
286       abstractC <- codeGen dflags this_mod imported_modules
287                            cost_centre_info fe_binders
288                            local_tycons stg_binds
289
290       --------------------------  Code output -------------------------------
291       -- _scc_     "CodeOutput"
292       (maybe_stub_h_name, maybe_stub_c_name)
293          <- codeOutput dflags this_mod local_tycons
294                        oa_tidy_binds stg_binds
295                        c_code h_code abstractC
296
297       return (maybe_stub_h_name, maybe_stub_c_name, Nothing)
298  where
299     local_tycons     = typeEnvTyCons env_tc
300     local_classes    = typeEnvClasses env_tc
301     imported_modules = map mod_name_to_Module imported_module_names
302     (fe_binders,h_code,c_code) = foreign_stuff
303
304     mod_name_to_Module :: ModuleName -> Module
305     mod_name_to_Module nm
306        = let str_mi = case lookupModuleEnvByName hit nm of
307                           Just mi -> mi
308                           Nothing -> case lookupModuleEnvByName pit nm of
309                                         Just mi -> mi
310                                         Nothing -> barf nm
311          in  mi_module str_mi
312     barf nm = pprPanic "mod_name_to_Module: no hst or pst mapping for" 
313                        (ppr nm)
314
315
316 dsThenSimplThenTidy dflags pcs hst this_mod print_unqual is_exported tc_result
317  = do --------------------------  Desugaring ----------------
318       -- _scc_     "DeSugar"
319       (desugared, rules, h_code, c_code, fe_binders) 
320          <- deSugar dflags pcs hst this_mod print_unqual tc_result
321
322       --------------------------  Main Core-language transformations ----------------
323       -- _scc_     "Core2Core"
324       (simplified, orphan_rules) 
325          <- core2core dflags pcs hst is_exported desugared rules
326
327       -- Do the final tidy-up
328       (tidy_binds, tidy_orphan_rules) 
329          <- tidyCorePgm dflags this_mod simplified orphan_rules
330       
331       return (tidy_binds, tidy_orphan_rules, (fe_binders,h_code,c_code))
332
333
334 myCoreToStg dflags this_mod tidy_binds
335  = do 
336       c2s_uniqs <- mkSplitUniqSupply 'c'
337       st_uniqs  <- mkSplitUniqSupply 'g'
338       let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds
339
340       () <- coreBindsSize occ_anal_tidy_binds `seq` return ()
341       -- TEMP: the above call zaps some space usage allocated by the
342       -- simplifier, which for reasons I don't understand, persists
343       -- thoroughout code generation
344
345       showPass dflags "Core2Stg"
346       -- _scc_     "Core2Stg"
347       let stg_binds   = topCoreBindsToStg c2s_uniqs occ_anal_tidy_binds
348
349       showPass dflags "Stg2Stg"
350       -- _scc_     "Stg2Stg"
351       (stg_binds2, cost_centre_info) <- stg2stg dflags this_mod st_uniqs stg_binds
352       let final_ids = collectFinalStgBinders (map fst stg_binds2)
353
354       return (stg_binds2, occ_anal_tidy_binds, cost_centre_info, final_ids)
355 \end{code}
356
357
358 %************************************************************************
359 %*                                                                      *
360 \subsection{Compiling an expression}
361 %*                                                                      *
362 %************************************************************************
363
364 hscExpr
365   :: DynFlags
366   -> HomeSymbolTable    
367   -> HomeIfaceTable
368   -> PersistentCompilerState    -- IN: persistent compiler state
369   -> Module                     -- Context for compiling
370   -> String                     -- The expression
371   -> IO HscResult
372
373 hscExpr dflags hst hit pcs this_module expr
374   = do  {       -- Parse it
375           maybe_parsed <- myParseExpr dflags expr
376         ; case maybe_parsed of {
377              Nothing -> return (HscFail pcs_ch);
378              Just parsed_expr -> do {
379
380                 -- Rename it
381           (new_pcs, maybe_renamed_expr) <- renameExpr dflags hit hst pcs this_module parsed_expr ;
382         ; case maybe_renamed_expr of {
383                 Nothing -> FAIL
384                 Just (print_unqual, rn_expr) -> 
385
386                 -- Typecheck it
387           maybe_tc_expr <- typecheckExpr dflags pcs hst print_unqual rn_expr 
388         ; case maybe_tc_expr of
389                 Nothing -> FAIL
390                 Just tc_expr ->
391
392                 -- Desugar it
393         ; ds_expr <- deSugarExpr dflags pcs hst this_module print_unqual tc_expr
394         
395                 -- Simplify it
396         ; simpl_expr <- simplifyExpr dflags pcs hst ds_expr
397
398         ; return I'M NOT SURE
399         }
400
401         
402
403
404 %************************************************************************
405 %*                                                                      *
406 \subsection{Initial persistent state}
407 %*                                                                      *
408 %************************************************************************
409
410 \begin{code}
411 initPersistentCompilerState :: IO PersistentCompilerState
412 initPersistentCompilerState 
413   = do prs <- initPersistentRenamerState
414        return (
415         PCS { pcs_PIT   = emptyIfaceTable,
416               pcs_PTE   = wiredInThingEnv,
417               pcs_insts = emptyInstEnv,
418               pcs_rules = emptyRuleBase,
419               pcs_PRS   = prs
420             }
421         )
422
423 initPersistentRenamerState :: IO PersistentRenamerState
424   = do ns <- mkSplitUniqSupply 'r'
425        return (
426         PRS { prsOrig  = Orig { origNames  = initOrigNames,
427                                 origIParam = emptyFM },
428               prsDecls = (emptyNameEnv, 0),
429               prsInsts = (emptyBag, 0),
430               prsRules = (emptyBag, 0),
431               prsNS    = ns
432             }
433         )
434
435 initOrigNames :: FiniteMap (ModuleName,OccName) Name
436 initOrigNames 
437    = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
438      where
439         grab names = foldl add emptyFM names
440         add env name 
441            = addToFM env (moduleName (nameModule name), nameOccName name) name
442
443
444 initRules :: PackageRuleBase
445 initRules = emptyRuleBase
446 {- SHOULD BE (ish)
447             foldl add emptyVarEnv builtinRules
448           where
449             add env (name,rule) 
450               = extendRuleBase env name rule
451 -}
452 \end{code}