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