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