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