[project @ 2001-03-19 16:17:27 by simonpj]
[ghc-hetmet.git] / ghc / compiler / main / HscMain.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
3 %
4
5 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
6
7 \begin{code}
8 module HscMain ( HscResult(..), hscMain, 
9 #ifdef GHCI
10                  hscStmt,
11 #endif
12                  initPersistentCompilerState ) where
13
14 #include "HsVersions.h"
15
16 #ifdef GHCI
17 import ByteCodeGen      ( byteCodeGen )
18 import CoreTidy         ( tidyCoreExpr )
19 import CorePrep         ( corePrepExpr )
20 import Rename           ( renameStmt )
21 import RdrHsSyn         ( RdrNameStmt )
22 import Type             ( Type )
23 import Id               ( Id, idName, setGlobalIdDetails )
24 import IdInfo           ( GlobalIdDetails(VanillaGlobal) )
25 import HscTypes         ( InteractiveContext(..), TyThing(..) )
26 import PrelNames        ( iNTERACTIVE )
27 import StringBuffer     ( stringToStringBuffer )
28 #endif
29
30 import HsSyn
31
32 import Id               ( idName )
33 import IdInfo           ( CafInfo(..), CgInfoEnv, CgInfo(..) )
34 import StringBuffer     ( hGetStringBuffer, freeStringBuffer )
35 import Parser
36 import Lex              ( PState(..), ParseResult(..) )
37 import SrcLoc           ( mkSrcLoc )
38 import Rename           ( checkOldIface, renameModule, closeIfaceDecls )
39 import Rules            ( emptyRuleBase )
40 import PrelInfo         ( wiredInThingEnv, wiredInThings )
41 import PrelNames        ( vanillaSyntaxMap, knownKeyNames )
42 import MkIface          ( mkFinalIface )
43 import TcModule
44 import InstEnv          ( emptyInstEnv )
45 import Desugar
46 import SimplCore
47 import CoreUtils        ( coreBindsSize )
48 import CoreTidy         ( tidyCorePgm )
49 import CorePrep         ( corePrepPgm )
50 import StgSyn
51 import CoreToStg        ( coreToStg )
52 import SimplStg         ( stg2stg )
53 import CodeGen          ( codeGen )
54 import CodeOutput       ( codeOutput )
55
56 import Module           ( ModuleName, moduleName, mkHomeModule, 
57                           moduleUserString )
58 import CmdLineOpts
59 import ErrUtils         ( dumpIfSet_dyn, showPass, printError )
60 import Util             ( unJust )
61 import UniqSupply       ( mkSplitUniqSupply )
62
63 import Bag              ( emptyBag )
64 import Outputable
65 import Interpreter
66 import CmStaticInfo     ( GhciMode(..) )
67 import HscStats         ( ppSourceStats )
68 import HscTypes
69 import FiniteMap        ( FiniteMap, plusFM, emptyFM, addToFM )
70 import OccName          ( OccName )
71 import Name             ( Name, nameModule, nameOccName, getName, isGlobalName )
72 import NameEnv          ( emptyNameEnv, mkNameEnv )
73 import Module           ( Module, lookupModuleEnvByName )
74 import Maybes           ( orElse )
75
76 import IOExts           ( newIORef, readIORef, writeIORef, unsafePerformIO )
77
78 import Monad            ( when )
79 import Maybe            ( isJust )
80 import IO
81 \end{code}
82
83
84 %************************************************************************
85 %*                                                                      *
86 \subsection{The main compiler pipeline}
87 %*                                                                      *
88 %************************************************************************
89
90 \begin{code}
91 data HscResult
92    -- compilation failed
93    = HscFail     PersistentCompilerState -- updated PCS
94    -- concluded that it wasn't necessary
95    | HscNoRecomp PersistentCompilerState -- updated PCS
96                  ModDetails              -- new details (HomeSymbolTable additions)
97                  ModIface                -- new iface (if any compilation was done)
98    -- did recompilation
99    | HscRecomp   PersistentCompilerState -- updated PCS
100                  ModDetails              -- new details (HomeSymbolTable additions)
101                  ModIface                -- new iface (if any compilation was done)
102                  (Maybe String)          -- generated stub_h filename (in TMPDIR)
103                  (Maybe String)          -- generated stub_c filename (in TMPDIR)
104                  (Maybe ([UnlinkedBCO],ItblEnv)) -- interpreted code, if any
105              
106
107         -- no errors or warnings; the individual passes
108         -- (parse/rename/typecheck) print messages themselves
109
110 hscMain
111   :: GhciMode
112   -> DynFlags
113   -> Module
114   -> ModuleLocation             -- location info
115   -> Bool                       -- True <=> source unchanged
116   -> Bool                       -- True <=> have an object file (for msgs only)
117   -> Maybe ModIface             -- old interface, if available
118   -> HomeSymbolTable            -- for home module ModDetails
119   -> HomeIfaceTable
120   -> PersistentCompilerState    -- IN: persistent compiler state
121   -> IO HscResult
122
123 hscMain ghci_mode dflags mod location source_unchanged have_object 
124         maybe_old_iface hst hit pcs
125  = do {
126       showPass dflags ("Checking old interface for hs = " 
127                         ++ show (ml_hs_file location)
128                         ++ ", hspp = " ++ show (ml_hspp_file location));
129
130       (pcs_ch, errs_found, (recomp_reqd, maybe_checked_iface))
131          <- checkOldIface ghci_mode dflags hit hst pcs 
132                 (unJust "hscMain" (ml_hi_file location))
133                 source_unchanged maybe_old_iface;
134
135       if errs_found then
136          return (HscFail pcs_ch)
137       else do {
138
139       let no_old_iface = not (isJust maybe_checked_iface)
140           what_next | recomp_reqd || no_old_iface = hscRecomp 
141                     | otherwise                   = hscNoRecomp
142       ;
143       what_next ghci_mode dflags have_object mod location 
144                 maybe_checked_iface hst hit pcs_ch
145       }}
146
147
148 -- we definitely expect to have the old interface available
149 hscNoRecomp ghci_mode dflags have_object 
150             mod location (Just old_iface) hst hit pcs_ch
151  | ghci_mode == OneShot
152  = do {
153       hPutStrLn stderr "compilation IS NOT required";
154       let { bomb = panic "hscNoRecomp:OneShot" };
155       return (HscNoRecomp pcs_ch bomb bomb)
156       }
157  | otherwise
158  = do {
159       when (verbosity dflags >= 1) $
160                 hPutStrLn stderr ("Skipping  " ++ 
161                         compMsg have_object mod location);
162
163       -- CLOSURE
164       (pcs_cl, closure_errs, cl_hs_decls) 
165          <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
166       if closure_errs then 
167          return (HscFail pcs_cl) 
168       else do {
169
170       -- TYPECHECK
171       maybe_tc_result 
172         <- typecheckIface dflags pcs_cl hst old_iface (vanillaSyntaxMap, cl_hs_decls);
173
174       case maybe_tc_result of {
175          Nothing -> return (HscFail pcs_cl);
176          Just (pcs_tc, new_details) ->
177
178       return (HscNoRecomp pcs_tc new_details old_iface)
179       }}}
180
181 compMsg use_object mod location =
182     mod_str ++ take (max 0 (16 - length mod_str)) (repeat ' ')
183     ++" ( " ++ unJust "hscRecomp" (ml_hs_file location) ++ ", "
184     ++ (if use_object
185           then unJust "hscRecomp" (ml_obj_file location)
186           else "interpreted")
187     ++ " )"
188  where mod_str = moduleUserString mod
189
190
191 hscRecomp ghci_mode dflags have_object 
192           mod location maybe_checked_iface hst hit pcs_ch
193  = do   {
194           -- what target are we shooting for?
195         ; let toInterp = dopt_HscLang dflags == HscInterpreted
196
197         ; when (verbosity dflags >= 1) $
198                 hPutStrLn stderr ("Compiling " ++ 
199                         compMsg (not toInterp) mod location);
200
201             -------------------
202             -- PARSE
203             -------------------
204         ; maybe_parsed <- myParseModule dflags 
205                              (unJust "hscRecomp:hspp" (ml_hspp_file location))
206         ; case maybe_parsed of {
207              Nothing -> return (HscFail pcs_ch);
208              Just rdr_module -> do {
209         ; let this_mod = mkHomeModule (hsModuleName rdr_module)
210     
211             -------------------
212             -- RENAME
213             -------------------
214         ; (pcs_rn, print_unqualified, maybe_rn_result) 
215              <- _scc_ "Rename" 
216                  renameModule dflags hit hst pcs_ch this_mod rdr_module
217         ; case maybe_rn_result of {
218              Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
219              Just (is_exported, new_iface, rn_hs_decls) -> do {
220     
221             -- In interactive mode, we don't want to discard any top-level entities at
222             -- all (eg. do not inline them away during simplification), and retain them
223             -- all in the TypeEnv so they are available from the command line.
224             --
225             -- isGlobalName separates the user-defined top-level names from those
226             -- introduced by the type checker.
227         ; let dont_discard | ghci_mode == Interactive = isGlobalName
228                            | otherwise = is_exported
229
230             -------------------
231             -- TYPECHECK
232             -------------------
233         ; maybe_tc_result 
234             <- _scc_ "TypeCheck" typecheckModule dflags pcs_rn hst new_iface 
235                                              print_unqualified rn_hs_decls 
236         ; case maybe_tc_result of {
237              Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
238              Just (pcs_tc, tc_result) -> do {
239     
240             -------------------
241             -- DESUGAR
242             -------------------
243         ; (ds_details, foreign_stuff) 
244              <- _scc_ "DeSugar" 
245                 deSugar dflags pcs_tc hst this_mod print_unqualified tc_result
246
247             -------------------
248             -- SIMPLIFY
249             -------------------
250         ; simpl_details
251              <- _scc_     "Core2Core"
252                 core2core dflags pcs_tc hst dont_discard ds_details
253
254             -------------------
255             -- TIDY
256             -------------------
257         ; cg_info_ref <- newIORef Nothing ;
258         ; let cg_info :: CgInfoEnv
259               cg_info = unsafePerformIO $ do {
260                            maybe_cg_env <- readIORef cg_info_ref ;
261                            case maybe_cg_env of
262                              Just env -> return env
263                              Nothing  -> do { printError "Urk! Looked at CgInfo too early!";
264                                               return emptyNameEnv } }
265                 -- cg_info_ref will be filled in just after restOfCodeGeneration
266                 -- Meanwhile, tidyCorePgm is careful not to look at cg_info!
267
268         ; (pcs_simpl, tidy_details) 
269              <- tidyCorePgm dflags this_mod pcs_tc cg_info simpl_details
270       
271             -------------------
272             -- PREPARE FOR CODE GENERATION
273             -------------------
274               -- Do saturation and convert to A-normal form
275         ; prepd_details <- corePrepPgm dflags tidy_details
276
277             -------------------
278             -- CONVERT TO STG and COMPLETE CODE GENERATION
279             -------------------
280         ; let
281             ModDetails{md_binds=binds, md_types=env_tc} = prepd_details
282
283             local_tycons     = typeEnvTyCons  env_tc
284             local_classes    = typeEnvClasses env_tc
285
286             imported_module_names = map ideclName (hsModuleImports rdr_module)
287             imported_modules = map mod_name_to_Module imported_module_names
288
289             (h_code,c_code,fe_binders) = foreign_stuff
290         
291             pit = pcs_PIT pcs_simpl
292
293             mod_name_to_Module :: ModuleName -> Module
294             mod_name_to_Module nm
295                = let str_mi = lookupModuleEnvByName hit nm `orElse`
296                               lookupModuleEnvByName pit nm `orElse`
297                               pprPanic "mod_name_to_Module: no hst or pst mapping for" 
298                                 (ppr nm)
299                  in  mi_module str_mi
300
301         ; (maybe_stub_h_filename, maybe_stub_c_filename,
302            maybe_bcos, final_iface )
303            <- if toInterp
304                 then do 
305                     -----------------  Generate byte code ------------------
306                     (bcos,itbl_env) <- byteCodeGen dflags binds 
307                                         local_tycons local_classes
308
309                     -- Fill in the code-gen info
310                     writeIORef cg_info_ref (Just emptyNameEnv)
311
312                     ------------------ BUILD THE NEW ModIface ------------
313                     final_iface <- _scc_ "MkFinalIface" 
314                           mkFinalIface ghci_mode dflags location 
315                                    maybe_checked_iface new_iface tidy_details
316
317                     return ( Nothing, Nothing, 
318                              Just (bcos,itbl_env), final_iface )
319
320                 else do
321                     -----------------  Convert to STG ------------------
322                     (stg_binds, cost_centre_info, stg_back_end_info) 
323                               <- _scc_ "CoreToStg"
324                                   myCoreToStg dflags this_mod binds
325                     
326                     -- Fill in the code-gen info for the earlier tidyCorePgm
327                     writeIORef cg_info_ref (Just stg_back_end_info)
328
329                     ------------------ BUILD THE NEW ModIface ------------
330                     final_iface <- _scc_ "MkFinalIface" 
331                           mkFinalIface ghci_mode dflags location 
332                                    maybe_checked_iface new_iface tidy_details
333
334                     ------------------  Code generation ------------------
335                     abstractC <- _scc_ "CodeGen"
336                                   codeGen dflags this_mod imported_modules
337                                          cost_centre_info fe_binders
338                                          local_tycons stg_binds
339                     
340                     ------------------  Code output -----------------------
341                     (maybe_stub_h_name, maybe_stub_c_name)
342                        <- codeOutput dflags this_mod local_tycons
343                              binds stg_binds
344                              c_code h_code abstractC
345                         
346                     return ( maybe_stub_h_name, maybe_stub_c_name, 
347                              Nothing, final_iface )
348
349         ; let final_details = tidy_details {md_binds = []} 
350
351
352           -- and the answer is ...
353         ; return (HscRecomp pcs_simpl
354                             final_details
355                             final_iface
356                             maybe_stub_h_filename maybe_stub_c_filename
357                             maybe_bcos)
358           }}}}}}}
359
360 myParseModule dflags src_filename
361  = do --------------------------  Parser  ----------------
362       showPass dflags "Parser"
363       _scc_  "Parser" do
364
365       buf <- hGetStringBuffer True{-expand tabs-} src_filename
366
367       let glaexts | dopt Opt_GlasgowExts dflags = 1#
368                   | otherwise                   = 0#
369
370       case parseModule buf PState{ bol = 0#, atbol = 1#,
371                                    context = [], glasgow_exts = glaexts,
372                                    loc = mkSrcLoc (_PK_ src_filename) 1 } of {
373
374         PFailed err -> do { hPutStrLn stderr (showSDoc err);
375                             freeStringBuffer buf;
376                             return Nothing };
377
378         POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) -> do {
379
380       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
381       
382       dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
383                            (ppSourceStats False rdr_module) ;
384       
385       return (Just rdr_module)
386         -- ToDo: free the string buffer later.
387       }}
388
389
390 myCoreToStg dflags this_mod tidy_binds
391  = do 
392       () <- coreBindsSize tidy_binds `seq` return ()
393       -- TEMP: the above call zaps some space usage allocated by the
394       -- simplifier, which for reasons I don't understand, persists
395       -- thoroughout code generation
396
397       stg_binds <- _scc_ "Core2Stg" coreToStg dflags tidy_binds
398
399       (stg_binds2, cost_centre_info)
400            <- _scc_ "Core2Stg" stg2stg dflags this_mod stg_binds
401
402       let env_rhs :: CgInfoEnv
403           env_rhs = mkNameEnv [ (idName bndr, CgInfo (stgRhsArity rhs) caf_info)
404                               | (bind,_) <- stg_binds2, 
405                                 let caf_info 
406                                      | stgBindHasCafRefs bind = MayHaveCafRefs
407                                      | otherwise = NoCafRefs,
408                                 (bndr,rhs) <- stgBindPairs bind ]
409
410       return (stg_binds2, cost_centre_info, env_rhs)
411    where
412       stgBindPairs (StgNonRec _ b r) = [(b,r)]
413       stgBindPairs (StgRec    _ prs) = prs
414 \end{code}
415
416
417 %************************************************************************
418 %*                                                                      *
419 \subsection{Compiling a do-statement}
420 %*                                                                      *
421 %************************************************************************
422
423 \begin{code}
424 #ifdef GHCI
425 hscStmt
426   :: DynFlags
427   -> HomeSymbolTable    
428   -> HomeIfaceTable
429   -> PersistentCompilerState    -- IN: persistent compiler state
430   -> InteractiveContext         -- Context for compiling
431   -> String                     -- The statement
432   -> Bool                       -- just treat it as an expression
433   -> IO ( PersistentCompilerState, 
434           Maybe ( [Id], 
435                   Type, 
436                   UnlinkedBCOExpr) )
437 \end{code}
438
439 When the UnlinkedBCOExpr is linked you get an HValue of type
440         IO [HValue]
441 When you run it you get a list of HValues that should be 
442 the same length as the list of names; add them to the ClosureEnv.
443
444 A naked expression returns a singleton Name [it].
445
446         What you type                   The IO [HValue] that hscStmt returns
447         -------------                   ------------------------------------
448         let pat = expr          ==>     let pat = expr in return [coerce HVal x, coerce HVal y, ...]
449                                         bindings: [x,y,...]
450
451         pat <- expr             ==>     expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
452                                         bindings: [x,y,...]
453
454         expr (of IO type)       ==>     expr >>= \ v -> return [v]
455           [NB: result not printed]      bindings: [it]
456           
457
458         expr (of non-IO type, 
459           result showable)      ==>     let v = expr in print v >> return [v]
460                                         bindings: [it]
461
462         expr (of non-IO type, 
463           result not showable)  ==>     error
464
465 \begin{code}
466 hscStmt dflags hst hit pcs0 icontext stmt just_expr
467    = let 
468         InteractiveContext { 
469              ic_rn_env   = rn_env, 
470              ic_type_env = type_env,
471              ic_module   = scope_mod } = icontext
472      in
473      do { maybe_stmt <- hscParseStmt dflags stmt
474         ; case maybe_stmt of
475              Nothing -> return (pcs0, Nothing)
476              Just parsed_stmt -> do {
477
478            let { notExprStmt (ExprStmt _ _) = False;
479                  notExprStmt _              = True 
480                };
481
482            if (just_expr && notExprStmt parsed_stmt)
483                 then do hPutStrLn stderr ("not an expression: `" ++ stmt ++ "'")
484                         return (pcs0, Nothing)
485                 else do {
486
487                 -- Rename it
488           (pcs1, print_unqual, maybe_renamed_stmt)
489                  <- renameStmt dflags hit hst pcs0 scope_mod 
490                                 iNTERACTIVE rn_env parsed_stmt
491
492         ; case maybe_renamed_stmt of
493                 Nothing -> return (pcs0, Nothing)
494                 Just (bound_names, rn_stmt) -> do {
495
496                 -- Typecheck it
497           maybe_tc_return <- 
498             if just_expr 
499                 then case rn_stmt of { (syn, ExprStmt e _, decls) -> 
500                      typecheckExpr dflags pcs1 hst type_env
501                            print_unqual iNTERACTIVE (syn,e,decls) }
502                 else typecheckStmt dflags pcs1 hst type_env
503                            print_unqual iNTERACTIVE bound_names rn_stmt
504
505         ; case maybe_tc_return of
506                 Nothing -> return (pcs0, Nothing)
507                 Just (pcs2, tc_expr, bound_ids, ty) ->  do {
508
509                 -- Desugar it
510           ds_expr <- deSugarExpr dflags pcs2 hst iNTERACTIVE print_unqual tc_expr
511         
512                 -- Simplify it
513         ; simpl_expr <- simplifyExpr dflags pcs2 hst ds_expr
514
515                 -- Tidy it (temporary, until coreSat does cloning)
516         ; tidy_expr <- tidyCoreExpr simpl_expr
517
518                 -- Prepare for codegen
519         ; prepd_expr <- corePrepExpr dflags tidy_expr
520
521                 -- Convert to BCOs
522         ; bcos <- coreExprToBCOs dflags prepd_expr
523
524         ; let
525                 -- Make all the bound ids "global" ids, now that
526                 -- they're notionally top-level bindings.  This is
527                 -- important: otherwise when we come to compile an expression
528                 -- using these ids later, the byte code generator will consider
529                 -- the occurrences to be free rather than global.
530              global_bound_ids = map globaliseId bound_ids;
531              globaliseId id   = setGlobalIdDetails id VanillaGlobal
532
533         ; return (pcs2, Just (global_bound_ids, ty, bcos))
534
535      }}}}}
536
537 hscParseStmt :: DynFlags -> String -> IO (Maybe RdrNameStmt)
538 hscParseStmt dflags str
539  = do --------------------------  Parser  ----------------
540       showPass dflags "Parser"
541       _scc_ "Parser" do
542
543       buf <- stringToStringBuffer str
544
545       let glaexts | dopt Opt_GlasgowExts dflags = 1#
546                   | otherwise                   = 0#
547
548       case parseStmt buf PState{ bol = 0#, atbol = 1#,
549                                  context = [], glasgow_exts = glaexts,
550                                  loc = mkSrcLoc SLIT("<no file>") 0 } of {
551
552         PFailed err -> do { hPutStrLn stderr (showSDoc err);
553 --      Not yet implemented in <4.11    freeStringBuffer buf;
554                             return Nothing };
555
556         -- no stmt: the line consisted of just space or comments
557         POk _ Nothing -> return Nothing;
558
559         POk _ (Just rdr_stmt) -> do {
560
561       --ToDo: can't free the string buffer until we've finished this
562       -- compilation sweep and all the identifiers have gone away.
563       --freeStringBuffer buf;
564       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_stmt);
565       return (Just rdr_stmt)
566       }}
567 #endif
568 \end{code}
569
570 %************************************************************************
571 %*                                                                      *
572 \subsection{Initial persistent state}
573 %*                                                                      *
574 %************************************************************************
575
576 \begin{code}
577 initPersistentCompilerState :: IO PersistentCompilerState
578 initPersistentCompilerState 
579   = do prs <- initPersistentRenamerState
580        return (
581         PCS { pcs_PIT   = emptyIfaceTable,
582               pcs_PTE   = wiredInThingEnv,
583               pcs_insts = emptyInstEnv,
584               pcs_rules = emptyRuleBase,
585               pcs_PRS   = prs
586             }
587         )
588
589 initPersistentRenamerState :: IO PersistentRenamerState
590   = do us <- mkSplitUniqSupply 'r'
591        return (
592         PRS { prsOrig  = NameSupply { nsUniqs = us,
593                                       nsNames = initOrigNames,
594                                       nsIPs   = emptyFM },
595               prsDecls   = (emptyNameEnv, 0),
596               prsInsts   = (emptyBag, 0),
597               prsRules   = (emptyBag, 0),
598               prsImpMods = emptyFM
599             }
600         )
601
602 initOrigNames :: FiniteMap (ModuleName,OccName) Name
603 initOrigNames 
604    = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
605      where
606         grab names = foldl add emptyFM names
607         add env name 
608            = addToFM env (moduleName (nameModule name), nameOccName name) name
609
610
611 initRules :: PackageRuleBase
612 initRules = emptyRuleBase
613 {- SHOULD BE (ish)
614             foldl add emptyVarEnv builtinRules
615           where
616             add env (name,rule) 
617               = extendRuleBase env name rule
618 -}
619 \end{code}