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