[project @ 2001-03-08 12:07:38 by simonpj]
[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 )
20 import IdInfo           ( GlobalIdDetails(VanillaGlobal) )
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, writeIface, pprIface )
36 import Type             ( Type )
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 import NameEnv          ( emptyNameEnv )
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 TMPDIR)
99                  (Maybe String)          -- generated stub_c filename (in TMPDIR)
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, new_details) ->
169
170       return (HscNoRecomp pcs_tc new_details old_iface)
171       }}}
172
173 compMsg mod location =
174     mod_str ++ take (12 - length mod_str) (repeat ' ')
175     ++ " (" ++ unJust "hscRecomp" (ml_hs_file location) ++ ")"
176  where mod_str = moduleUserString mod
177
178
179 hscRecomp ghci_mode dflags mod location maybe_checked_iface hst hit pcs_ch
180  = do   {
181         ; when (verbosity dflags >= 1) $
182                 hPutStrLn stderr ("Compiling " ++ compMsg mod location);
183
184           -- what target are we shooting for?
185         ; let toInterp = dopt_HscLang dflags == HscInterpreted
186
187             -------------------
188             -- PARSE
189             -------------------
190         ; maybe_parsed <- myParseModule dflags 
191                              (unJust "hscRecomp:hspp" (ml_hspp_file location))
192         ; case maybe_parsed of {
193              Nothing -> return (HscFail pcs_ch);
194              Just rdr_module -> do {
195         ; let this_mod = mkHomeModule (hsModuleName rdr_module)
196     
197             -------------------
198             -- RENAME
199             -------------------
200         ; (pcs_rn, print_unqualified, maybe_rn_result) 
201              <- _scc_ "Rename" 
202                  renameModule dflags hit hst pcs_ch this_mod rdr_module
203         ; case maybe_rn_result of {
204              Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
205              Just (is_exported, new_iface, rn_hs_decls) -> do {
206     
207             -- In interactive mode, we don't want to discard any top-level entities at
208             -- all (eg. do not inline them away during simplification), and retain them
209             -- all in the TypeEnv so they are available from the command line.
210             --
211             -- isGlobalName separates the user-defined top-level names from those
212             -- introduced by the type checker.
213         ; let dont_discard | ghci_mode == Interactive = isGlobalName
214                            | otherwise = is_exported
215
216             -------------------
217             -- TYPECHECK
218             -------------------
219         ; maybe_tc_result 
220             <- _scc_ "TypeCheck" typecheckModule dflags pcs_rn hst new_iface 
221                                              print_unqualified rn_hs_decls 
222         ; case maybe_tc_result of {
223              Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
224              Just (pcs_tc, tc_result) -> do {
225     
226         ; let env_tc   = tc_env tc_result
227               insts_tc = tc_insts tc_result
228
229             -------------------
230             -- DESUGAR
231             -------------------
232         ; (ds_binds, ds_rules, foreign_stuff) 
233              <- _scc_ "DeSugar" 
234                 deSugar dflags pcs_tc hst this_mod print_unqualified tc_result
235
236             -------------------
237             -- SIMPLIFY
238             -------------------
239         ; (simplified, orphan_rules) 
240              <- _scc_     "Core2Core"
241                 core2core dflags pcs_tc hst dont_discard ds_binds ds_rules
242
243             -------------------
244             -- TIDY
245             -------------------
246         ; (pcs_simpl, tidy_binds, new_details) 
247              <- tidyCorePgm dflags this_mod pcs_tc env_tc insts_tc 
248                             simplified orphan_rules
249       
250             -------------------
251             -- BUILD THE NEW ModDetails AND ModIface
252             -------------------
253         ; final_iface <- _scc_ "MkFinalIface" 
254                           mkFinalIface ghci_mode dflags location 
255                                        maybe_checked_iface new_iface new_details
256
257             -------------------
258             -- CONVERT TO STG and COMPLETE CODE GENERATION
259             -------------------
260               -- Do saturation and convert to A-normal form
261         ; saturated <- coreSatPgm dflags tidy_binds
262
263         ; (maybe_stub_h_filename, maybe_stub_c_filename, maybe_bcos)
264              <- restOfCodeGeneration dflags toInterp this_mod
265                    (map ideclName (hsModuleImports rdr_module))
266                    foreign_stuff env_tc saturated
267                    hit (pcs_PIT pcs_simpl)       
268
269           -- and the answer is ...
270         ; return (HscRecomp pcs_simpl new_details final_iface
271                             maybe_stub_h_filename maybe_stub_c_filename
272                             maybe_bcos)
273           }}}}}}}
274
275
276
277 mkFinalIface ghci_mode dflags location maybe_old_iface new_iface new_details
278  = case completeIface maybe_old_iface new_iface new_details of
279       (new_iface, Nothing) -- no change in the interfacfe
280          -> do when (dopt Opt_D_dump_hi_diffs dflags)
281                     (printDump (text "INTERFACE UNCHANGED"))
282                dumpIfSet_dyn dflags Opt_D_dump_hi
283                              "UNCHANGED FINAL INTERFACE" (pprIface new_iface)
284                return new_iface
285       (new_iface, Just sdoc_diffs)
286          -> do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "INTERFACE HAS CHANGED" 
287                                     sdoc_diffs
288                dumpIfSet_dyn dflags Opt_D_dump_hi "NEW FINAL INTERFACE" 
289                                     (pprIface new_iface)
290                -- Write the interface file
291                when (ghci_mode /= Interactive) 
292                     (writeIface (unJust "hscRecomp:hi" (ml_hi_file location))
293                                 new_iface)
294                return new_iface
295
296
297 myParseModule dflags src_filename
298  = do --------------------------  Parser  ----------------
299       showPass dflags "Parser"
300       _scc_  "Parser" do
301
302       buf <- hGetStringBuffer True{-expand tabs-} src_filename
303
304       let glaexts | dopt Opt_GlasgowExts dflags = 1#
305                   | otherwise                   = 0#
306
307       case parseModule buf PState{ bol = 0#, atbol = 1#,
308                                    context = [], glasgow_exts = glaexts,
309                                    loc = mkSrcLoc (_PK_ src_filename) 1 } of {
310
311         PFailed err -> do { hPutStrLn stderr (showSDoc err);
312                             freeStringBuffer buf;
313                             return Nothing };
314
315         POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) -> do {
316
317       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
318       
319       dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
320                            (ppSourceStats False rdr_module) ;
321       
322       return (Just rdr_module)
323         -- ToDo: free the string buffer later.
324       }}
325
326
327 restOfCodeGeneration dflags toInterp this_mod imported_module_names
328                      foreign_stuff env_tc tidy_binds
329                      hit pit -- these last two for mapping ModNames to Modules
330  | toInterp
331  = do (bcos,itbl_env) 
332          <- byteCodeGen dflags tidy_binds local_tycons local_classes
333       return (Nothing, Nothing, Just (bcos,itbl_env))
334
335  | otherwise
336  = do
337       --------------------------  Convert to STG -------------------------------
338       (stg_binds, cost_centre_info) 
339                 <- _scc_ "CoreToStg"
340                     myCoreToStg dflags this_mod tidy_binds env_tc
341
342       --------------------------  Code generation ------------------------------
343       abstractC <- _scc_ "CodeGen"
344                     codeGen dflags this_mod imported_modules
345                            cost_centre_info fe_binders
346                            local_tycons stg_binds
347
348       --------------------------  Code output -------------------------------
349       (maybe_stub_h_name, maybe_stub_c_name)
350          <- codeOutput dflags this_mod local_tycons
351                        tidy_binds stg_binds
352                        c_code h_code abstractC
353
354       return (maybe_stub_h_name, maybe_stub_c_name, Nothing)
355  where
356     local_tycons     = typeEnvTyCons env_tc
357     local_classes    = typeEnvClasses env_tc
358     imported_modules = map mod_name_to_Module imported_module_names
359     (h_code,c_code,fe_binders) = foreign_stuff
360
361     mod_name_to_Module :: ModuleName -> Module
362     mod_name_to_Module nm
363        = let str_mi = case lookupModuleEnvByName hit nm of
364                           Just mi -> mi
365                           Nothing -> case lookupModuleEnvByName pit nm of
366                                         Just mi -> mi
367                                         Nothing -> barf nm
368          in  mi_module str_mi
369     barf nm = pprPanic "mod_name_to_Module: no hst or pst mapping for" 
370                        (ppr nm)
371
372
373 myCoreToStg dflags this_mod tidy_binds env_tc
374  = do 
375       () <- coreBindsSize tidy_binds `seq` return ()
376       -- TEMP: the above call zaps some space usage allocated by the
377       -- simplifier, which for reasons I don't understand, persists
378       -- thoroughout code generation
379
380       --let bcos = byteCodeGen dflags tidy_binds local_tycons local_classes
381
382       
383       stg_binds <- _scc_ "Core2Stg" coreToStg dflags this_mod tidy_binds
384
385       (stg_binds2, cost_centre_info)
386            <- _scc_ "Core2Stg" stg2stg dflags this_mod stg_binds
387
388       return (stg_binds2, cost_centre_info)
389    where
390       local_tycons  = typeEnvTyCons env_tc
391       local_classes = typeEnvClasses env_tc
392 \end{code}
393
394
395 %************************************************************************
396 %*                                                                      *
397 \subsection{Compiling a do-statement}
398 %*                                                                      *
399 %************************************************************************
400
401 \begin{code}
402 #ifdef GHCI
403 hscStmt
404   :: DynFlags
405   -> HomeSymbolTable    
406   -> HomeIfaceTable
407   -> PersistentCompilerState    -- IN: persistent compiler state
408   -> InteractiveContext         -- Context for compiling
409   -> String                     -- The statement
410   -> Bool                       -- just treat it as an expression
411   -> IO ( PersistentCompilerState, 
412           Maybe ( [Id], 
413                   Type, 
414                   UnlinkedBCOExpr) )
415 \end{code}
416
417 When the UnlinkedBCOExpr is linked you get an HValue of type
418         IO [HValue]
419 When you run it you get a list of HValues that should be 
420 the same length as the list of names; add them to the ClosureEnv.
421
422 A naked expression returns a singleton Name [it].
423
424         What you type                   The IO [HValue] that hscStmt returns
425         -------------                   ------------------------------------
426         let pat = expr          ==>     let pat = expr in return [coerce HVal x, coerce HVal y, ...]
427                                         bindings: [x,y,...]
428
429         pat <- expr             ==>     expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
430                                         bindings: [x,y,...]
431
432         expr (of IO type)       ==>     expr >>= \ v -> return [v]
433           [NB: result not printed]      bindings: [it]
434           
435
436         expr (of non-IO type, 
437           result showable)      ==>     let v = expr in print v >> return [v]
438                                         bindings: [it]
439
440         expr (of non-IO type, 
441           result not showable)  ==>     error
442
443 \begin{code}
444 hscStmt dflags hst hit pcs0 icontext stmt just_expr
445    = let 
446         InteractiveContext { 
447              ic_rn_env   = rn_env, 
448              ic_type_env = type_env,
449              ic_module   = scope_mod } = icontext
450      in
451      do { maybe_stmt <- hscParseStmt dflags stmt
452         ; case maybe_stmt of
453              Nothing -> return (pcs0, Nothing)
454              Just parsed_stmt -> do {
455
456            let { notExprStmt (ExprStmt _ _) = False;
457                  notExprStmt _              = True 
458                };
459
460            if (just_expr && notExprStmt parsed_stmt)
461                 then do hPutStrLn stderr ("not an expression: `" ++ stmt ++ "'")
462                         return (pcs0, Nothing)
463                 else do {
464
465                 -- Rename it
466           (pcs1, print_unqual, maybe_renamed_stmt)
467                  <- renameStmt dflags hit hst pcs0 scope_mod 
468                                 iNTERACTIVE rn_env parsed_stmt
469
470         ; case maybe_renamed_stmt of
471                 Nothing -> return (pcs0, Nothing)
472                 Just (bound_names, rn_stmt) -> do {
473
474                 -- Typecheck it
475           maybe_tc_return <- 
476             if just_expr 
477                 then case rn_stmt of { (syn, ExprStmt e _, decls) -> 
478                      typecheckExpr dflags pcs1 hst type_env
479                            print_unqual iNTERACTIVE (syn,e,decls) }
480                 else typecheckStmt dflags pcs1 hst type_env
481                            print_unqual iNTERACTIVE bound_names rn_stmt
482
483         ; case maybe_tc_return of
484                 Nothing -> return (pcs0, Nothing)
485                 Just (pcs2, tc_expr, bound_ids, ty) ->  do {
486
487                 -- Desugar it
488           ds_expr <- deSugarExpr dflags pcs2 hst iNTERACTIVE print_unqual tc_expr
489         
490                 -- Simplify it
491         ; simpl_expr <- simplifyExpr dflags pcs2 hst ds_expr
492
493                 -- Tidy it (temporary, until coreSat does cloning)
494         ; tidy_expr <- tidyCoreExpr simpl_expr
495
496                 -- Saturate it
497         ; sat_expr <- coreSatExpr dflags tidy_expr
498
499                 -- Convert to BCOs
500         ; bcos <- coreExprToBCOs dflags sat_expr
501
502         ; let
503                 -- Make all the bound ids "global" ids, now that
504                 -- they're notionally top-level bindings.  This is
505                 -- important: otherwise when we come to compile an expression
506                 -- using these ids later, the byte code generator will consider
507                 -- the occurrences to be free rather than global.
508              global_bound_ids = map globaliseId bound_ids;
509              globaliseId id   = setIdGlobalDetails id VanillaGlobal
510
511         ; return (pcs2, Just (global_bound_ids, ty, bcos))
512
513      }}}}}
514
515 hscParseStmt :: DynFlags -> String -> IO (Maybe RdrNameStmt)
516 hscParseStmt dflags str
517  = do --------------------------  Parser  ----------------
518       showPass dflags "Parser"
519       _scc_ "Parser" do
520
521       buf <- stringToStringBuffer str
522
523       let glaexts | dopt Opt_GlasgowExts dflags = 1#
524                   | otherwise                   = 0#
525
526       case parseStmt buf PState{ bol = 0#, atbol = 1#,
527                                  context = [], glasgow_exts = glaexts,
528                                  loc = mkSrcLoc SLIT("<no file>") 0 } of {
529
530         PFailed err -> do { hPutStrLn stderr (showSDoc err);
531 --      Not yet implemented in <4.11    freeStringBuffer buf;
532                             return Nothing };
533
534         -- no stmt: the line consisted of just space or comments
535         POk _ Nothing -> return Nothing;
536
537         POk _ (Just rdr_stmt) -> do {
538
539       --ToDo: can't free the string buffer until we've finished this
540       -- compilation sweep and all the identifiers have gone away.
541       --freeStringBuffer buf;
542       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_stmt);
543       return (Just rdr_stmt)
544       }}
545 #endif
546 \end{code}
547
548 %************************************************************************
549 %*                                                                      *
550 \subsection{Initial persistent state}
551 %*                                                                      *
552 %************************************************************************
553
554 \begin{code}
555 initPersistentCompilerState :: IO PersistentCompilerState
556 initPersistentCompilerState 
557   = do prs <- initPersistentRenamerState
558        return (
559         PCS { pcs_PIT   = emptyIfaceTable,
560               pcs_PTE   = wiredInThingEnv,
561               pcs_insts = emptyInstEnv,
562               pcs_rules = emptyRuleBase,
563               pcs_PRS   = prs
564             }
565         )
566
567 initPersistentRenamerState :: IO PersistentRenamerState
568   = do us <- mkSplitUniqSupply 'r'
569        return (
570         PRS { prsOrig  = NameSupply { nsUniqs = us,
571                                       nsNames = initOrigNames,
572                                       nsIPs   = emptyFM },
573               prsDecls   = (emptyNameEnv, 0),
574               prsInsts   = (emptyBag, 0),
575               prsRules   = (emptyBag, 0),
576               prsImpMods = emptyFM
577             }
578         )
579
580 initOrigNames :: FiniteMap (ModuleName,OccName) Name
581 initOrigNames 
582    = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
583      where
584         grab names = foldl add emptyFM names
585         add env name 
586            = addToFM env (moduleName (nameModule name), nameOccName name) name
587
588
589 initRules :: PackageRuleBase
590 initRules = emptyRuleBase
591 {- SHOULD BE (ish)
592             foldl add emptyVarEnv builtinRules
593           where
594             add env (name,rule) 
595               = extendRuleBase env name rule
596 -}
597 \end{code}