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