[project @ 2000-11-20 11:39:57 by sewardj]
[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 "hscMain" (ml_hi_file location))
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 
176                              (unJust "hscRecomp:hspp" (ml_hspp_file location))
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 ghci_mode dflags location 
227                                       maybe_checked_iface 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 ghci_mode 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" 
256                                     sdoc_diffs
257                dumpIfSet_dyn dflags Opt_D_dump_hi "NEW FINAL INTERFACE" 
258                                     (pprIface new_iface)
259                -- Write the interface file
260                when (ghci_mode /= Interactive) 
261                     (writeIface (unJust "hscRecomp:hi" (ml_hi_file location))
262                                 new_iface)
263                return new_iface
264
265
266 myParseModule dflags src_filename
267  = do --------------------------  Parser  ----------------
268       showPass dflags "Parser"
269       -- _scc_     "Parser"
270
271       buf <- hGetStringBuffer True{-expand tabs-} src_filename
272
273       let glaexts | dopt Opt_GlasgowExts dflags = 1#
274                   | otherwise                 = 0#
275
276       case parse buf PState{ bol = 0#, atbol = 1#,
277                              context = [], glasgow_exts = glaexts,
278                              loc = mkSrcLoc (_PK_ src_filename) 1 } of {
279
280         PFailed err -> do { hPutStrLn stderr (showSDoc err);
281                             return Nothing };
282
283         POk _ (PModule rdr_module@(HsModule mod_name _ _ _ _ _ _)) -> do {
284
285       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
286       
287       dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
288                            (ppSourceStats False rdr_module) ;
289       
290       return (Just rdr_module)
291       }}
292
293
294 restOfCodeGeneration dflags toInterp this_mod imported_module_names cost_centre_info 
295                      foreign_stuff env_tc stg_binds oa_tidy_binds
296                      hit pit -- these last two for mapping ModNames to Modules
297  | toInterp
298  = do (ibinds,itbl_env) 
299          <- stgBindsToInterpSyn dflags (map fst stg_binds) 
300                 local_tycons local_classes
301       return (Nothing, Nothing, Just (ibinds,itbl_env))
302
303  | otherwise
304  = do --------------------------  Code generation -------------------------------
305       -- _scc_     "CodeGen"
306       abstractC <- codeGen dflags this_mod imported_modules
307                            cost_centre_info fe_binders
308                            local_tycons stg_binds
309
310       --------------------------  Code output -------------------------------
311       -- _scc_     "CodeOutput"
312       (maybe_stub_h_name, maybe_stub_c_name)
313          <- codeOutput dflags this_mod local_tycons
314                        oa_tidy_binds stg_binds
315                        c_code h_code abstractC
316
317       return (maybe_stub_h_name, maybe_stub_c_name, Nothing)
318  where
319     local_tycons     = typeEnvTyCons env_tc
320     local_classes    = typeEnvClasses env_tc
321     imported_modules = map mod_name_to_Module imported_module_names
322     (fe_binders,h_code,c_code) = foreign_stuff
323
324     mod_name_to_Module :: ModuleName -> Module
325     mod_name_to_Module nm
326        = let str_mi = case lookupModuleEnvByName hit nm of
327                           Just mi -> mi
328                           Nothing -> case lookupModuleEnvByName pit nm of
329                                         Just mi -> mi
330                                         Nothing -> barf nm
331          in  mi_module str_mi
332     barf nm = pprPanic "mod_name_to_Module: no hst or pst mapping for" 
333                        (ppr nm)
334
335
336 dsThenSimplThenTidy dflags pcs hst this_mod print_unqual is_exported tc_result
337  = do --------------------------  Desugaring ----------------
338       showPass dflags "DeSugar"
339       -- _scc_     "DeSugar"
340       (desugared, rules, h_code, c_code, fe_binders) 
341          <- deSugar dflags pcs hst this_mod print_unqual tc_result
342
343       --------------------------  Main Core-language transformations ----------------
344       -- _scc_     "Core2Core"
345       (simplified, orphan_rules) 
346          <- core2core dflags pcs hst is_exported desugared rules
347
348       -- Do the final tidy-up
349       showPass dflags "TidyCore"
350       (tidy_binds, tidy_orphan_rules) 
351          <- tidyCorePgm dflags this_mod simplified orphan_rules
352       
353       return (tidy_binds, tidy_orphan_rules, (fe_binders,h_code,c_code))
354
355
356 myCoreToStg dflags this_mod tidy_binds
357  = do 
358       st_uniqs  <- mkSplitUniqSupply 'g'
359       let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds
360
361       () <- coreBindsSize occ_anal_tidy_binds `seq` return ()
362       -- TEMP: the above call zaps some space usage allocated by the
363       -- simplifier, which for reasons I don't understand, persists
364       -- thoroughout code generation
365
366       -- _scc_     "Core2Stg"
367       stg_binds <- topCoreBindsToStg dflags occ_anal_tidy_binds
368
369       showPass dflags "Stg2Stg"
370       -- _scc_     "Stg2Stg"
371       (stg_binds2, cost_centre_info) <- stg2stg dflags this_mod st_uniqs stg_binds
372       let final_ids = collectFinalStgBinders (map fst stg_binds2)
373
374       return (stg_binds2, occ_anal_tidy_binds, cost_centre_info, final_ids)
375 \end{code}
376
377
378 %************************************************************************
379 %*                                                                      *
380 \subsection{Compiling an expression}
381 %*                                                                      *
382 %************************************************************************
383
384 \begin{code}
385 hscExpr
386   :: DynFlags
387   -> HomeSymbolTable    
388   -> HomeIfaceTable
389   -> PersistentCompilerState    -- IN: persistent compiler state
390   -> Module                     -- Context for compiling
391   -> String                     -- The expression
392   -> IO ( PersistentCompilerState, Maybe UnlinkedIExpr )
393
394 hscExpr dflags hst hit pcs0 this_module expr
395   = do  {       -- Parse it
396         maybe_parsed <- hscParseExpr dflags expr;
397         case maybe_parsed of
398              Nothing -> return (pcs0, Nothing)
399              Just parsed_expr -> do {
400
401                 -- Rename it
402         (pcs1, maybe_renamed_expr) <- 
403                 renameExpr dflags hit hst pcs0 this_module parsed_expr;
404         case maybe_renamed_expr of
405                 Nothing -> return (pcs1, Nothing)
406                 Just (print_unqual, rn_expr) -> do {
407
408                 -- Typecheck it
409         maybe_tc_expr <- typecheckExpr dflags pcs1 hst print_unqual rn_expr;
410         case maybe_tc_expr of
411                 Nothing -> return (pcs1, Nothing)
412                 Just tc_expr -> do {
413
414                 -- Desugar it
415         ds_expr <- deSugarExpr dflags pcs1 hst this_module 
416                         print_unqual tc_expr;
417         
418                 -- Simplify it
419         simpl_expr <- simplifyExpr dflags pcs1 hst ds_expr;
420
421                 -- Convert to STG
422         stg_expr <- coreToStgExpr dflags simpl_expr;
423
424                 -- ToDo: need to do StgVarInfo?  or SRTs?
425
426                 -- Convert to InterpSyn
427         unlinked_iexpr <- stgExprToInterpSyn dflags stg_expr;
428
429         return (pcs1, Just unlinked_iexpr);
430      }}}}
431
432 hscParseExpr :: DynFlags -> String -> IO (Maybe RdrNameHsExpr)
433 hscParseExpr dflags str
434  = do --------------------------  Parser  ----------------
435       showPass dflags "Parser"
436       -- _scc_     "Parser"
437
438       buf <- stringToStringBuffer ("__expr " ++ str)
439
440       -- glaexts is True for now (because of the daft __expr at the front
441       -- of the string...)
442       let glaexts = 1#
443       --let glaexts | dopt Opt_GlasgowExts dflags = 1#
444       --                  | otherwise                   = 0#
445
446       case parse buf PState{ bol = 0#, atbol = 1#,
447                              context = [], glasgow_exts = glaexts,
448                              loc = mkSrcLoc SLIT("<no file>") 0 } of {
449
450         PFailed err -> do { freeStringBuffer buf
451                           ; hPutStrLn stderr (showSDoc err)
452                           ; return Nothing };
453
454         POk _ (PExpr rdr_expr) -> do {
455
456       -- ToDo:
457       -- freeStringBuffer buf;
458
459       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_expr);
460       
461       return (Just rdr_expr)
462       }}
463 \end{code}
464
465 %************************************************************************
466 %*                                                                      *
467 \subsection{Initial persistent state}
468 %*                                                                      *
469 %************************************************************************
470
471 \begin{code}
472 initPersistentCompilerState :: IO PersistentCompilerState
473 initPersistentCompilerState 
474   = do prs <- initPersistentRenamerState
475        return (
476         PCS { pcs_PIT   = emptyIfaceTable,
477               pcs_PTE   = wiredInThingEnv,
478               pcs_insts = emptyInstEnv,
479               pcs_rules = emptyRuleBase,
480               pcs_PRS   = prs
481             }
482         )
483
484 initPersistentRenamerState :: IO PersistentRenamerState
485   = do ns <- mkSplitUniqSupply 'r'
486        return (
487         PRS { prsOrig  = Orig { origNames  = initOrigNames,
488                                 origIParam = emptyFM },
489               prsDecls = (emptyNameEnv, 0),
490               prsInsts = (emptyBag, 0),
491               prsRules = (emptyBag, 0),
492               prsNS    = ns
493             }
494         )
495
496 initOrigNames :: FiniteMap (ModuleName,OccName) Name
497 initOrigNames 
498    = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
499      where
500         grab names = foldl add emptyFM names
501         add env name 
502            = addToFM env (moduleName (nameModule name), nameOccName name) name
503
504
505 initRules :: PackageRuleBase
506 initRules = emptyRuleBase
507 {- SHOULD BE (ish)
508             foldl add emptyVarEnv builtinRules
509           where
510             add env (name,rule) 
511               = extendRuleBase env name rule
512 -}
513 \end{code}