[project @ 2001-01-19 15:26:37 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                  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 StringBuffer     ( stringToStringBuffer, freeStringBuffer )
19 import Unique           ( Uniquable(..) )
20 import Type             ( Type, splitTyConApp_maybe )
21 import PrelNames        ( ioTyConKey )
22 import ByteCodeGen      ( byteCodeGen )
23 #endif
24
25 import HsSyn
26
27 import StringBuffer     ( hGetStringBuffer )
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        ( knownKeyNames )
35 import MkIface          ( completeIface, mkModDetailsFromIface, mkModDetails,
36                           writeIface, pprIface )
37 import TcModule
38 import InstEnv          ( emptyInstEnv )
39 import Desugar
40 import SimplCore
41 import CoreUtils        ( coreBindsSize )
42 import CoreTidy         ( tidyCorePgm )
43 import CoreSat
44 import CoreToStg        ( coreToStg )
45 import SimplStg         ( stg2stg )
46 import CodeGen          ( codeGen )
47 import CodeOutput       ( codeOutput )
48
49 import Module           ( ModuleName, moduleName, mkHomeModule )
50 import CmdLineOpts
51 import ErrUtils         ( dumpIfSet_dyn, showPass )
52 import Util             ( unJust )
53 import UniqSupply       ( mkSplitUniqSupply )
54
55 import Bag              ( emptyBag )
56 import Outputable
57 import Interpreter
58 import CmStaticInfo     ( GhciMode(..) )
59 import HscStats         ( ppSourceStats )
60 import HscTypes         ( ModDetails, ModIface(..), PersistentCompilerState(..),
61                           PersistentRenamerState(..), ModuleLocation(..),
62                           HomeSymbolTable, 
63                           NameSupply(..), PackageRuleBase, HomeIfaceTable, 
64                           typeEnvClasses, typeEnvTyCons, emptyIfaceTable )
65 import FiniteMap        ( FiniteMap, plusFM, emptyFM, addToFM )
66 import OccName          ( OccName )
67 import Name             ( Name, nameModule, nameOccName, getName  )
68 import Name             ( emptyNameEnv )
69 import Module           ( Module, lookupModuleEnvByName )
70
71 import Monad            ( when )
72 import Maybe            ( isJust )
73 import IO
74 \end{code}
75
76
77 %************************************************************************
78 %*                                                                      *
79 \subsection{The main compiler pipeline}
80 %*                                                                      *
81 %************************************************************************
82
83 \begin{code}
84 data HscResult
85    -- compilation failed
86    = HscFail     PersistentCompilerState -- updated PCS
87    -- concluded that it wasn't necessary
88    | HscNoRecomp PersistentCompilerState -- updated PCS
89                  ModDetails              -- new details (HomeSymbolTable additions)
90                  ModIface                -- new iface (if any compilation was done)
91    -- did recompilation
92    | HscRecomp   PersistentCompilerState -- updated PCS
93                  ModDetails              -- new details (HomeSymbolTable additions)
94                  ModIface                -- new iface (if any compilation was done)
95                  (Maybe String)          -- generated stub_h filename (in /tmp)
96                  (Maybe String)          -- generated stub_c filename (in /tmp)
97                  (Maybe ([UnlinkedBCO],ItblEnv)) -- interpreted code, if any
98              
99
100         -- no errors or warnings; the individual passes
101         -- (parse/rename/typecheck) print messages themselves
102
103 hscMain
104   :: GhciMode
105   -> DynFlags
106   -> Bool                       -- source unchanged?
107   -> ModuleLocation             -- location info
108   -> Maybe ModIface             -- old interface, if available
109   -> HomeSymbolTable            -- for home module ModDetails
110   -> HomeIfaceTable
111   -> PersistentCompilerState    -- IN: persistent compiler state
112   -> IO HscResult
113
114 hscMain ghci_mode dflags source_unchanged location maybe_old_iface hst hit pcs
115  = do {
116       showPass dflags ("Checking old interface for hs = " 
117                         ++ show (ml_hs_file location)
118                         ++ ", hspp = " ++ show (ml_hspp_file location));
119
120       (pcs_ch, errs_found, (recomp_reqd, maybe_checked_iface))
121          <- checkOldIface ghci_mode dflags hit hst pcs 
122                 (unJust "hscMain" (ml_hi_file location))
123                 source_unchanged maybe_old_iface;
124
125       if errs_found then
126          return (HscFail pcs_ch)
127       else do {
128
129       let no_old_iface = not (isJust maybe_checked_iface)
130           what_next | recomp_reqd || no_old_iface = hscRecomp 
131                     | otherwise                   = hscNoRecomp
132       ;
133       what_next ghci_mode dflags location maybe_checked_iface
134                 hst hit pcs_ch
135       }}
136
137
138 -- we definitely expect to have the old interface available
139 hscNoRecomp ghci_mode dflags location (Just old_iface) hst hit pcs_ch
140  | ghci_mode == OneShot
141  = do {
142       hPutStrLn stderr "compilation IS NOT required";
143       let { bomb = panic "hscNoRecomp:OneShot" };
144       return (HscNoRecomp pcs_ch bomb bomb)
145       }
146  | otherwise
147  = do {
148       hPutStr stderr "compilation IS NOT required";
149       when (verbosity dflags /= 1) $ hPutStrLn stderr "";
150
151       -- CLOSURE
152       (pcs_cl, closure_errs, cl_hs_decls) 
153          <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
154       if closure_errs then 
155          return (HscFail pcs_cl) 
156       else do {
157
158       -- TYPECHECK
159       maybe_tc_result <- typecheckModule dflags pcs_cl hst 
160                                          old_iface alwaysQualify cl_hs_decls;
161       case maybe_tc_result of {
162          Nothing -> return (HscFail pcs_cl);
163          Just (pcs_tc, tc_result) -> do {
164
165       let env_tc      = tc_env tc_result
166           local_rules = tc_rules tc_result
167       ;
168       -- create a new details from the closed, typechecked, old iface
169       let new_details = mkModDetailsFromIface env_tc local_rules
170       ;
171       return (HscNoRecomp pcs_tc new_details old_iface)
172       }}}}
173
174
175 hscRecomp ghci_mode dflags location maybe_checked_iface hst hit pcs_ch
176  = do   {
177         ; when (verbosity dflags >= 1) $
178                 hPutStr stderr "compilation IS required";
179           -- mode -v1 tries to keep everything on one line
180           when (verbosity dflags > 1) $
181                 hPutStrLn stderr "";
182
183           -- what target are we shooting for?
184         ; let toInterp = dopt_HscLang dflags == HscInterpreted
185
186             -------------------
187             -- PARSE
188             -------------------
189         ; maybe_parsed <- myParseModule dflags 
190                              (unJust "hscRecomp:hspp" (ml_hspp_file location))
191         ; case maybe_parsed of {
192              Nothing -> return (HscFail pcs_ch);
193              Just rdr_module -> do {
194         ; let this_mod = mkHomeModule (hsModuleName rdr_module)
195     
196             -------------------
197             -- RENAME
198             -------------------
199         ; (pcs_rn, maybe_rn_result) 
200              <- _scc_ "Rename" 
201                  renameModule dflags hit hst pcs_ch this_mod rdr_module
202         ; case maybe_rn_result of {
203              Nothing -> return (HscFail pcs_rn);
204              Just (print_unqualified, (is_exported, new_iface, rn_hs_decls)) -> do {
205     
206             -------------------
207             -- TYPECHECK
208             -------------------
209         ; maybe_tc_result 
210             <- _scc_ "TypeCheck" 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              <- _scc_ "DeSugar" 
223                 deSugar dflags pcs_tc hst this_mod print_unqualified tc_result
224
225             -------------------
226             -- SIMPLIFY, TIDY-CORE
227             -------------------
228           -- We grab the the unfoldings at this point.
229         ; (pcs_simpl, tidy_binds, orphan_rules)
230               <- simplThenTidy dflags pcs_tc hst this_mod is_exported ds_binds ds_rules
231             
232             -------------------
233             -- BUILD THE NEW ModDetails AND ModIface
234             -------------------
235         ; let new_details = mkModDetails env_tc tidy_binds orphan_rules
236         ; final_iface <- _scc_ "MkFinalIface" 
237                           mkFinalIface ghci_mode dflags location 
238                                       maybe_checked_iface new_iface new_details
239
240             -------------------
241             -- CONVERT TO STG and COMPLETE CODE GENERATION
242             -------------------
243         ; (maybe_stub_h_filename, maybe_stub_c_filename, maybe_bcos)
244              <- restOfCodeGeneration dflags toInterp this_mod
245                    (map ideclName (hsModuleImports rdr_module))
246                    foreign_stuff env_tc tidy_binds
247                    hit (pcs_PIT pcs_simpl)       
248
249           -- and the answer is ...
250         ; return (HscRecomp pcs_simpl new_details final_iface
251                             maybe_stub_h_filename maybe_stub_c_filename
252                             maybe_bcos)
253           }}}}}}}
254
255
256
257 mkFinalIface ghci_mode dflags location maybe_old_iface new_iface new_details
258  = case completeIface maybe_old_iface new_iface new_details of
259       (new_iface, Nothing) -- no change in the interfacfe
260          -> do when (dopt Opt_D_dump_hi_diffs dflags)
261                     (printDump (text "INTERFACE UNCHANGED"))
262                dumpIfSet_dyn dflags Opt_D_dump_hi
263                              "UNCHANGED FINAL INTERFACE" (pprIface new_iface)
264                return new_iface
265       (new_iface, Just sdoc_diffs)
266          -> do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "INTERFACE HAS CHANGED" 
267                                     sdoc_diffs
268                dumpIfSet_dyn dflags Opt_D_dump_hi "NEW FINAL INTERFACE" 
269                                     (pprIface new_iface)
270                -- Write the interface file
271                when (ghci_mode /= Interactive) 
272                     (writeIface (unJust "hscRecomp:hi" (ml_hi_file location))
273                                 new_iface)
274                return new_iface
275
276
277 myParseModule dflags src_filename
278  = do --------------------------  Parser  ----------------
279       showPass dflags "Parser"
280       _scc_  "Parser" do
281
282       buf <- hGetStringBuffer True{-expand tabs-} src_filename
283
284       let glaexts | dopt Opt_GlasgowExts dflags = 1#
285                   | otherwise                   = 0#
286
287       case parseModule buf PState{ bol = 0#, atbol = 1#,
288                                    context = [], glasgow_exts = glaexts,
289                                    loc = mkSrcLoc (_PK_ src_filename) 1 } of {
290
291         PFailed err -> do { hPutStrLn stderr (showSDoc err);
292                             return Nothing };
293
294         POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) -> do {
295
296       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
297       
298       dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
299                            (ppSourceStats False rdr_module) ;
300       
301       return (Just rdr_module)
302       }}
303
304
305 simplThenTidy dflags pcs hst this_mod is_exported binds rules
306  = do -- Do main Core-language transformations ---------
307       -- _scc_     "Core2Core"
308       (simplified, orphan_rules) 
309          <- core2core dflags pcs hst is_exported binds rules
310
311       -- Do saturation and convert to A-normal form
312       -- NOTE: subsequent passes may not transform the syntax, only annotate it
313       saturated <- coreSatPgm dflags simplified
314
315       -- Do the final tidy-up
316       (pcs', tidy_binds, tidy_orphan_rules) 
317          <- tidyCorePgm dflags this_mod pcs saturated orphan_rules
318       
319       return (pcs', tidy_binds, tidy_orphan_rules)
320
321
322 restOfCodeGeneration dflags toInterp this_mod imported_module_names
323                      foreign_stuff env_tc tidy_binds
324                      hit pit -- these last two for mapping ModNames to Modules
325  | toInterp
326  = do (bcos,itbl_env) 
327          <- byteCodeGen dflags tidy_binds local_tycons local_classes
328       return (Nothing, Nothing, Just (bcos,itbl_env))
329
330  | otherwise
331  = do
332       --------------------------  Convert to STG -------------------------------
333       (stg_binds, cost_centre_info) 
334                 <- _scc_ "CoreToStg"
335                     myCoreToStg dflags this_mod tidy_binds env_tc
336
337       --------------------------  Code generation ------------------------------
338       abstractC <- _scc_ "CodeGen"
339                     codeGen dflags this_mod imported_modules
340                            cost_centre_info fe_binders
341                            local_tycons stg_binds
342
343       --------------------------  Code output -------------------------------
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 env_tc
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 dflags tidy_binds local_tycons local_classes
376
377       
378       stg_binds <- _scc_ "Core2Stg" coreToStg dflags this_mod tidy_binds
379
380       (stg_binds2, cost_centre_info)
381            <- _scc_ "Core2Stg" stg2stg dflags this_mod stg_binds
382
383       return (stg_binds2, cost_centre_info)
384    where
385       local_tycons  = typeEnvTyCons env_tc
386       local_classes = typeEnvClasses env_tc
387 \end{code}
388
389
390 %************************************************************************
391 %*                                                                      *
392 \subsection{Compiling an expression}
393 %*                                                                      *
394 %************************************************************************
395
396 \begin{code}
397 #ifdef GHCI
398 hscExpr
399   :: DynFlags
400   -> HomeSymbolTable    
401   -> HomeIfaceTable
402   -> PersistentCompilerState    -- IN: persistent compiler state
403   -> Module                     -- Context for compiling
404   -> String                     -- The expression
405   -> Bool                       -- Should we wrap print if not IO-typed?
406   -> IO ( PersistentCompilerState, 
407           Maybe (UnlinkedBCOExpr, PrintUnqualified, Type) )
408
409 hscExpr dflags hst hit pcs0 this_module expr wrap_print
410    = do {
411         maybe_parsed <- hscParseExpr dflags expr;
412         case maybe_parsed of
413              Nothing -> return (pcs0, Nothing)
414              Just parsed_expr -> do {
415
416                 -- Rename it
417         (pcs1, maybe_renamed_expr) <- 
418                 renameExpr dflags hit hst pcs0 this_module parsed_expr;
419         case maybe_renamed_expr of
420                 Nothing -> return ({-WAS:pcs1-} pcs0, Nothing)
421                 Just (print_unqual, rn_expr) -> do {
422
423                 -- Typecheck it
424         maybe_tc_return
425            <- typecheckExpr dflags pcs1 hst print_unqual this_module rn_expr;
426         case maybe_tc_return of {
427                 Nothing -> return ({-WAS:pcs1-} pcs0, Nothing);
428                 Just (pcs2, tc_expr, ty) -> do
429
430         -- if it isn't an IO-typed expression, 
431         -- wrap "print" around it & recompile...
432         let { is_IO_type = case splitTyConApp_maybe ty of {
433                             Just (tycon, _) -> getUnique tycon == ioTyConKey;
434                             Nothing -> False }
435             };
436
437         if (wrap_print && not is_IO_type)
438                 then do (new_pcs, maybe_stuff)
439                           <- hscExpr dflags hst hit pcs2 this_module
440                                 ("PrelIO.print (" ++ expr ++ ")") False
441                         case maybe_stuff of
442                            Nothing -> return (new_pcs, maybe_stuff)
443                            Just (bcos, _, _) ->
444                               return (new_pcs, Just (bcos, print_unqual, ty))
445                 else do
446
447                 -- Desugar it
448         ds_expr <- deSugarExpr dflags pcs2 hst this_module
449                         print_unqual tc_expr;
450         
451                 -- Simplify it
452         simpl_expr <- simplifyExpr dflags pcs2 hst ds_expr;
453
454                 -- Saturate it
455         sat_expr <- coreSatExpr dflags simpl_expr;
456
457                 -- ToDo: need to do SRTs?
458
459                 -- Convert to BCOs
460         bcos <- coreExprToBCOs dflags sat_expr
461
462         return (pcs2, Just (bcos, 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" do
470
471       buf <- stringToStringBuffer str
472
473       let glaexts | dopt Opt_GlasgowExts dflags = 1#
474                   | otherwise             = 0#
475
476       case parseExpr buf PState{ bol = 0#, atbol = 1#,
477                                  context = [], glasgow_exts = glaexts,
478                                  loc = mkSrcLoc SLIT("<no file>") 0 } of {
479
480         PFailed err -> do { hPutStrLn stderr (showSDoc err);
481                             freeStringBuffer buf;
482                             return Nothing };
483
484         POk _ rdr_expr -> do {
485
486       --ToDo: can't free the string buffer until we've finished this
487       -- compilation sweep and all the identifiers have gone away.
488       --freeStringBuffer buf;
489       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_expr);
490       return (Just rdr_expr)
491       }}
492 #endif
493 \end{code}
494
495 %************************************************************************
496 %*                                                                      *
497 \subsection{Initial persistent state}
498 %*                                                                      *
499 %************************************************************************
500
501 \begin{code}
502 initPersistentCompilerState :: IO PersistentCompilerState
503 initPersistentCompilerState 
504   = do prs <- initPersistentRenamerState
505        return (
506         PCS { pcs_PIT   = emptyIfaceTable,
507               pcs_PTE   = wiredInThingEnv,
508               pcs_insts = emptyInstEnv,
509               pcs_rules = emptyRuleBase,
510               pcs_PRS   = prs
511             }
512         )
513
514 initPersistentRenamerState :: IO PersistentRenamerState
515   = do us <- mkSplitUniqSupply 'r'
516        return (
517         PRS { prsOrig  = NameSupply { nsUniqs = us,
518                                       nsNames = initOrigNames,
519                                       nsIPs   = emptyFM },
520               prsDecls   = (emptyNameEnv, 0),
521               prsInsts   = (emptyBag, 0),
522               prsRules   = (emptyBag, 0),
523               prsImpMods = emptyFM
524             }
525         )
526
527 initOrigNames :: FiniteMap (ModuleName,OccName) Name
528 initOrigNames 
529    = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
530      where
531         grab names = foldl add emptyFM names
532         add env name 
533            = addToFM env (moduleName (nameModule name), nameOccName name) name
534
535
536 initRules :: PackageRuleBase
537 initRules = emptyRuleBase
538 {- SHOULD BE (ish)
539             foldl add emptyVarEnv builtinRules
540           where
541             add env (name,rule) 
542               = extendRuleBase env name rule
543 -}
544 \end{code}