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