[project @ 2000-12-11 16:42:26 by sewardj]
[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                  hscExpr,
10 #endif
11                  initPersistentCompilerState ) where
12
13 #include "HsVersions.h"
14
15 #ifdef GHCI
16 import RdrHsSyn         ( RdrNameHsExpr )
17 import Rename           ( renameExpr )
18 import CoreToStg        ( coreExprToStg )
19 import StringBuffer     ( stringToStringBuffer, freeStringBuffer )
20 import Unique           ( Uniquable(..) )
21 import Type             ( splitTyConApp_maybe )
22 import PrelNames        ( ioTyConKey )
23 import ByteCodeGen      ( byteCodeGen )
24 #endif
25
26 import HsSyn
27
28 import StringBuffer     ( hGetStringBuffer )
29 import Parser
30 import Lex              ( PState(..), ParseResult(..) )
31 import SrcLoc           ( mkSrcLoc )
32 import Rename           ( checkOldIface, renameModule, closeIfaceDecls )
33 import Rules            ( emptyRuleBase )
34 import PrelInfo         ( wiredInThingEnv, wiredInThings )
35 import PrelNames        ( knownKeyNames )
36 import MkIface          ( completeIface, mkModDetailsFromIface, mkModDetails,
37                           writeIface, pprIface )
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 CoreToStg        ( coreToStg )
46 import SimplStg         ( stg2stg )
47 import CodeGen          ( codeGen )
48 import CodeOutput       ( codeOutput )
49
50 import Module           ( ModuleName, moduleName, mkHomeModule )
51 import CmdLineOpts
52 import ErrUtils         ( dumpIfSet_dyn, showPass )
53 import Util             ( unJust )
54 import UniqSupply       ( mkSplitUniqSupply )
55
56 import Bag              ( emptyBag )
57 import Outputable
58 import Interpreter
59 import CmStaticInfo     ( GhciMode(..) )
60 import HscStats         ( ppSourceStats )
61 import HscTypes         ( ModDetails, ModIface(..), PersistentCompilerState(..),
62                           PersistentRenamerState(..), ModuleLocation(..),
63                           HomeSymbolTable, 
64                           NameSupply(..), PackageRuleBase, HomeIfaceTable, 
65                           typeEnvClasses, typeEnvTyCons, emptyIfaceTable )
66 import FiniteMap        ( FiniteMap, plusFM, emptyFM, addToFM )
67 import OccName          ( OccName )
68 import Name             ( Name, nameModule, nameOccName, getName  )
69 import Name             ( emptyNameEnv )
70 import Module           ( Module, lookupModuleEnvByName )
71
72 import Monad            ( when )
73 import Maybe            ( isJust )
74 import IO
75 import List             ( intersperse )
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 ([UnlinkedIBind],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       hPutStr stderr "compilation IS NOT required";
151       when (verbosity dflags /= 1) $ hPutStrLn stderr "";
152
153       -- CLOSURE
154       (pcs_cl, closure_errs, cl_hs_decls) 
155          <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
156       if closure_errs then 
157          return (HscFail pcs_cl) 
158       else do {
159
160       -- TYPECHECK
161       maybe_tc_result <- typecheckModule dflags pcs_cl hst 
162                                          old_iface alwaysQualify cl_hs_decls;
163       case maybe_tc_result of {
164          Nothing -> return (HscFail pcs_cl);
165          Just (pcs_tc, tc_result) -> do {
166
167       let env_tc      = tc_env tc_result
168           local_rules = tc_rules tc_result
169       ;
170       -- create a new details from the closed, typechecked, old iface
171       let new_details = mkModDetailsFromIface env_tc local_rules
172       ;
173       return (HscNoRecomp pcs_tc new_details old_iface)
174       }}}}
175
176
177 hscRecomp ghci_mode dflags location maybe_checked_iface hst hit pcs_ch
178  = do   {
179         ; when (verbosity dflags >= 1) $
180                 hPutStr stderr "compilation IS required";
181           -- mode -v1 tries to keep everything on one line
182           when (verbosity dflags > 1) $
183                 hPutStrLn stderr "";
184
185           -- what target are we shooting for?
186         ; let toInterp = dopt_HscLang dflags == HscInterpreted
187
188             -------------------
189             -- PARSE
190             -------------------
191         ; maybe_parsed <- myParseModule dflags 
192                              (unJust "hscRecomp:hspp" (ml_hspp_file location))
193         ; case maybe_parsed of {
194              Nothing -> return (HscFail pcs_ch);
195              Just rdr_module -> do {
196         ; let this_mod = mkHomeModule (hsModuleName rdr_module)
197     
198             -------------------
199             -- RENAME
200             -------------------
201         ; (pcs_rn, maybe_rn_result) 
202              <- renameModule dflags hit hst pcs_ch this_mod rdr_module
203         ; case maybe_rn_result of {
204              Nothing -> return (HscFail pcs_rn);
205              Just (print_unqualified, (is_exported, new_iface, rn_hs_decls)) -> do {
206     
207             -------------------
208             -- TYPECHECK
209             -------------------
210         ; maybe_tc_result <- typecheckModule dflags pcs_rn hst new_iface 
211                                              print_unqualified rn_hs_decls
212         ; case maybe_tc_result of {
213              Nothing -> return (HscFail pcs_rn);
214              Just (pcs_tc, tc_result) -> do {
215     
216         ; let env_tc = tc_env tc_result
217
218             -------------------
219             -- DESUGAR
220             -------------------
221         ; (ds_binds, ds_rules, foreign_stuff) 
222              <- deSugar dflags pcs_tc hst this_mod print_unqualified tc_result
223
224             -------------------
225             -- SIMPLIFY, TIDY-CORE
226             -------------------
227           -- We grab the the unfoldings at this point.
228         ; (pcs_simpl, tidy_binds, orphan_rules)
229               <- simplThenTidy dflags pcs_tc hst this_mod is_exported ds_binds ds_rules
230             
231             -------------------
232             -- BUILD THE NEW ModDetails AND ModIface
233             -------------------
234         ; let new_details = mkModDetails env_tc tidy_binds orphan_rules
235         ; final_iface <- mkFinalIface ghci_mode dflags location 
236                                       maybe_checked_iface new_iface new_details
237
238             -------------------
239             -- CONVERT TO STG
240             -------------------
241         ; (stg_binds, cost_centre_info) 
242                 <- myCoreToStg dflags this_mod tidy_binds
243
244             -------------------
245             -- COMPLETE CODE GENERATION
246             -------------------
247         ; (maybe_stub_h_filename, maybe_stub_c_filename, maybe_ibinds)
248              <- restOfCodeGeneration dflags toInterp this_mod
249                    (map ideclName (hsModuleImports rdr_module))
250                    cost_centre_info foreign_stuff env_tc stg_binds tidy_binds
251                    hit (pcs_PIT pcs_simpl)       
252
253           -- and the answer is ...
254         ; return (HscRecomp pcs_simpl new_details final_iface
255                             maybe_stub_h_filename maybe_stub_c_filename
256                             maybe_ibinds)
257           }}}}}}}
258
259
260
261 mkFinalIface ghci_mode dflags location maybe_old_iface new_iface new_details
262  = case completeIface maybe_old_iface new_iface new_details of
263       (new_iface, Nothing) -- no change in the interfacfe
264          -> do when (dopt Opt_D_dump_hi_diffs dflags)
265                     (printDump (text "INTERFACE UNCHANGED"))
266                dumpIfSet_dyn dflags Opt_D_dump_hi
267                              "UNCHANGED FINAL INTERFACE" (pprIface new_iface)
268                return new_iface
269       (new_iface, Just sdoc_diffs)
270          -> do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "INTERFACE HAS CHANGED" 
271                                     sdoc_diffs
272                dumpIfSet_dyn dflags Opt_D_dump_hi "NEW FINAL INTERFACE" 
273                                     (pprIface new_iface)
274                -- Write the interface file
275                when (ghci_mode /= Interactive) 
276                     (writeIface (unJust "hscRecomp:hi" (ml_hi_file location))
277                                 new_iface)
278                return new_iface
279
280
281 myParseModule dflags src_filename
282  = do --------------------------  Parser  ----------------
283       showPass dflags "Parser"
284       -- _scc_     "Parser"
285
286       buf <- hGetStringBuffer True{-expand tabs-} src_filename
287
288       let glaexts | dopt Opt_GlasgowExts dflags = 1#
289                   | otherwise                   = 0#
290
291       case parse buf PState{ bol = 0#, atbol = 1#,
292                              context = [], glasgow_exts = glaexts,
293                              loc = mkSrcLoc (_PK_ src_filename) 1 } of {
294
295         PFailed err -> do { hPutStrLn stderr (showSDoc err);
296                             return Nothing };
297
298         POk _ (PModule rdr_module@(HsModule mod_name _ _ _ _ _ _)) -> do {
299
300       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
301       
302       dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
303                            (ppSourceStats False rdr_module) ;
304       
305       return (Just rdr_module)
306       }}
307
308
309 simplThenTidy dflags pcs hst this_mod is_exported binds rules
310  = do -- Do main Core-language transformations ---------
311       -- _scc_     "Core2Core"
312       (simplified, orphan_rules) 
313          <- core2core dflags pcs hst is_exported binds rules
314
315       -- Do saturation and convert to A-normal form
316       --    NOTE: future passes cannot transform the syntax, only annotate it
317       saturated <- coreSatPgm dflags simplified
318
319       -- Do the final tidy-up
320       (pcs', tidy_binds, tidy_orphan_rules) 
321          <- tidyCorePgm dflags this_mod pcs saturated orphan_rules
322       
323       return (pcs', tidy_binds, tidy_orphan_rules)
324
325
326 restOfCodeGeneration dflags toInterp this_mod imported_module_names cost_centre_info 
327                      foreign_stuff env_tc stg_binds tidy_binds
328                      hit pit -- these last two for mapping ModNames to Modules
329  | toInterp
330  = do (ibinds,itbl_env) 
331          <- stgBindsToInterpSyn dflags (map fst stg_binds) 
332                 local_tycons local_classes
333       return (Nothing, Nothing, Just (ibinds,itbl_env))
334
335  | otherwise
336  = do --------------------------  Code generation -------------------------------
337       -- _scc_     "CodeGen"
338       abstractC <- codeGen dflags this_mod imported_modules
339                            cost_centre_info fe_binders
340                            local_tycons stg_binds
341
342       --------------------------  Code output -------------------------------
343       -- _scc_     "CodeOutput"
344       (maybe_stub_h_name, maybe_stub_c_name)
345          <- codeOutput dflags this_mod local_tycons
346                        tidy_binds stg_binds
347                        c_code h_code abstractC
348
349       return (maybe_stub_h_name, maybe_stub_c_name, Nothing)
350  where
351     local_tycons     = typeEnvTyCons env_tc
352     local_classes    = typeEnvClasses env_tc
353     imported_modules = map mod_name_to_Module imported_module_names
354     (h_code,c_code,fe_binders) = foreign_stuff
355
356     mod_name_to_Module :: ModuleName -> Module
357     mod_name_to_Module nm
358        = let str_mi = case lookupModuleEnvByName hit nm of
359                           Just mi -> mi
360                           Nothing -> case lookupModuleEnvByName pit nm of
361                                         Just mi -> mi
362                                         Nothing -> barf nm
363          in  mi_module str_mi
364     barf nm = pprPanic "mod_name_to_Module: no hst or pst mapping for" 
365                        (ppr nm)
366
367
368 myCoreToStg dflags this_mod tidy_binds
369  = do 
370       () <- coreBindsSize tidy_binds `seq` return ()
371       -- TEMP: the above call zaps some space usage allocated by the
372       -- simplifier, which for reasons I don't understand, persists
373       -- thoroughout code generation
374
375       --let bcos = byteCodeGen tidy_binds
376       --putStrLn ("\n\n" ++ showSDocDebug (vcat (intersperse (char ' ') (map ppr bcos))))
377
378       -- _scc_     "Core2Stg"
379       stg_binds <- coreToStg dflags this_mod tidy_binds
380
381       -- _scc_     "Stg2Stg"
382       (stg_binds2, cost_centre_info) <- stg2stg dflags this_mod stg_binds
383
384       return (stg_binds2, cost_centre_info)
385 \end{code}
386
387
388 %************************************************************************
389 %*                                                                      *
390 \subsection{Compiling an expression}
391 %*                                                                      *
392 %************************************************************************
393
394 \begin{code}
395 #ifdef GHCI
396 hscExpr
397   :: DynFlags
398   -> HomeSymbolTable    
399   -> HomeIfaceTable
400   -> PersistentCompilerState    -- IN: persistent compiler state
401   -> Module                     -- Context for compiling
402   -> String                     -- The expression
403   -> IO ( PersistentCompilerState, 
404           Maybe (UnlinkedIExpr, PrintUnqualified, Type) )
405
406 hscExpr dflags hst hit pcs0 this_module expr
407    = do {
408         maybe_parsed <- hscParseExpr dflags expr;
409         case maybe_parsed of
410              Nothing -> return (pcs0, Nothing)
411              Just parsed_expr -> do {
412
413                 -- Rename it
414         (pcs1, maybe_renamed_expr) <- 
415                 renameExpr dflags hit hst pcs0 this_module parsed_expr;
416         case maybe_renamed_expr of
417                 Nothing -> return (pcs1, Nothing)
418                 Just (print_unqual, rn_expr) -> do {
419
420                 -- Typecheck it
421         maybe_tc_return
422            <- typecheckExpr dflags pcs1 hst print_unqual this_module rn_expr;
423         case maybe_tc_return of {
424                 Nothing -> return (pcs1, Nothing);
425                 Just (pcs2, tc_expr, ty) -> do
426
427         -- if it isn't an IO-typed expression, 
428         -- wrap "print" around it & recompile...
429         let { is_IO_type = case splitTyConApp_maybe ty of {
430                             Just (tycon, _) -> getUnique tycon == ioTyConKey;
431                             Nothing -> False }
432             };
433
434         if (not is_IO_type)
435                 then do (new_pcs, maybe_stuff)
436                           <- hscExpr dflags hst hit pcs2 this_module 
437                                 ("print (" ++ expr ++ ")")
438                         case maybe_stuff of
439                            Nothing -> return (new_pcs, maybe_stuff)
440                            Just (expr, _, _) ->
441                               return (new_pcs, Just (expr, print_unqual, ty))
442                 else do
443
444                 -- Desugar it
445         ds_expr <- deSugarExpr dflags pcs2 hst this_module
446                         print_unqual tc_expr;
447         
448                 -- Simplify it
449         simpl_expr <- simplifyExpr dflags pcs2 hst ds_expr;
450
451                 -- Saturate it
452         sat_expr <- coreSatExpr dflags simpl_expr;
453
454                 -- Convert to STG
455         let stg_expr = coreExprToStg sat_expr;
456
457                 -- ToDo: need to do SRTs?
458
459                 -- Convert to InterpSyn
460         unlinked_iexpr <- stgExprToInterpSyn dflags stg_expr;
461
462         return (pcs2, Just (unlinked_iexpr, print_unqual, ty));
463      }}}}
464
465 hscParseExpr :: DynFlags -> String -> IO (Maybe RdrNameHsExpr)
466 hscParseExpr dflags str
467  = do --------------------------  Parser  ----------------
468       showPass dflags "Parser"
469       -- _scc_     "Parser"
470
471       buf <- stringToStringBuffer ("__expr " ++ str)
472
473       -- glaexts is True for now (because of the daft __expr at the front
474       -- of the string...)
475       let glaexts = 1#
476       --let glaexts | dopt Opt_GlasgowExts dflags = 1#
477       --            | otherwise                   = 0#
478
479       case parse buf PState{ bol = 0#, atbol = 1#,
480                              context = [], glasgow_exts = glaexts,
481                              loc = mkSrcLoc SLIT("<no file>") 0 } of {
482
483         PFailed err -> do { freeStringBuffer buf;
484                             hPutStrLn stderr (showSDoc err);
485                             return Nothing };
486
487         POk _ (PExpr rdr_expr) -> do {
488
489       --ToDo: can't free the string buffer until we've finished this
490       -- compilation sweep and all the identifiers have gone away.
491       --freeStringBuffer buf;
492       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_expr);
493       return (Just rdr_expr)
494       }}
495 #endif
496 \end{code}
497
498 %************************************************************************
499 %*                                                                      *
500 \subsection{Initial persistent state}
501 %*                                                                      *
502 %************************************************************************
503
504 \begin{code}
505 initPersistentCompilerState :: IO PersistentCompilerState
506 initPersistentCompilerState 
507   = do prs <- initPersistentRenamerState
508        return (
509         PCS { pcs_PIT   = emptyIfaceTable,
510               pcs_PTE   = wiredInThingEnv,
511               pcs_insts = emptyInstEnv,
512               pcs_rules = emptyRuleBase,
513               pcs_PRS   = prs
514             }
515         )
516
517 initPersistentRenamerState :: IO PersistentRenamerState
518   = do us <- mkSplitUniqSupply 'r'
519        return (
520         PRS { prsOrig  = NameSupply { nsUniqs = us,
521                                       nsNames = initOrigNames,
522                                       nsIPs   = emptyFM },
523               prsDecls = (emptyNameEnv, 0),
524               prsInsts = (emptyBag, 0),
525               prsRules = (emptyBag, 0)
526             }
527         )
528
529 initOrigNames :: FiniteMap (ModuleName,OccName) Name
530 initOrigNames 
531    = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
532      where
533         grab names = foldl add emptyFM names
534         add env name 
535            = addToFM env (moduleName (nameModule name), nameOccName name) name
536
537
538 initRules :: PackageRuleBase
539 initRules = emptyRuleBase
540 {- SHOULD BE (ish)
541             foldl add emptyVarEnv builtinRules
542           where
543             add env (name,rule) 
544               = extendRuleBase env name rule
545 -}
546 \end{code}