[project @ 2000-12-06 17:27:17 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 StringBuffer     ( stringToStringBuffer, freeStringBuffer )
18 import Unique           ( Uniquable(..) )
19 import Type             ( splitTyConApp_maybe )
20 import PrelNames        ( ioTyConKey )
21 import ByteCodeGen      ( byteCodeGen )
22 #endif
23
24 import HsSyn
25
26 import StringBuffer     ( hGetStringBuffer )
27 import Parser
28 import Lex              ( PState(..), ParseResult(..) )
29 import SrcLoc           ( mkSrcLoc )
30 import Rename
31 import Rules            ( emptyRuleBase )
32 import PrelInfo         ( wiredInThingEnv, wiredInThings )
33 import PrelNames        ( knownKeyNames )
34 import MkIface          ( completeIface, mkModDetailsFromIface, mkModDetails,
35                           writeIface, pprIface )
36 import TcModule
37 import Type
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, coreExprToStg )
45 import StgSyn           ( collectFinalStgBinders )
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                           OrigNameEnv(..), 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 \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 ([UnlinkedIBind],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       hPutStr stderr "compilation IS NOT required";
150       when (verbosity dflags /= 1) $ hPutStrLn stderr "";
151
152       -- CLOSURE
153       (pcs_cl, closure_errs, cl_hs_decls) 
154          <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
155       if closure_errs then 
156          return (HscFail pcs_cl) 
157       else do {
158
159       -- TYPECHECK
160       maybe_tc_result <- typecheckModule dflags pcs_cl hst 
161                                          old_iface alwaysQualify cl_hs_decls;
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                 hPutStr stderr "compilation IS required";
180           -- mode -v1 tries to keep everything on one line
181           when (verbosity dflags > 1) $
182                 hPutStrLn stderr "";
183
184           -- what target are we shooting for?
185         ; let toInterp = dopt_HscLang dflags == HscInterpreted
186
187             -------------------
188             -- PARSE
189             -------------------
190         ; maybe_parsed <- myParseModule dflags 
191                              (unJust "hscRecomp:hspp" (ml_hspp_file location))
192         ; case maybe_parsed of {
193              Nothing -> return (HscFail pcs_ch);
194              Just rdr_module -> do {
195         ; let this_mod = mkHomeModule (hsModuleName rdr_module)
196     
197             -------------------
198             -- RENAME
199             -------------------
200         ; (pcs_rn, maybe_rn_result) 
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 <- typecheckModule dflags pcs_rn hst new_iface 
210                                              print_unqualified rn_hs_decls
211         ; case maybe_tc_result of {
212              Nothing -> return (HscFail pcs_rn);
213              Just (pcs_tc, tc_result) -> do {
214     
215         ; let env_tc = tc_env tc_result
216
217             -------------------
218             -- DESUGAR, SIMPLIFY, TIDY-CORE
219             -------------------
220           -- We grab the the unfoldings at this point.
221         ; simpl_result <- dsThenSimplThenTidy dflags pcs_tc hst this_mod 
222                                               print_unqualified is_exported tc_result
223         ; let (pcs_simpl, tidy_binds, orphan_rules, foreign_stuff) = simpl_result
224             
225             -------------------
226             -- CONVERT TO STG
227             -------------------
228         ; (stg_binds, cost_centre_info, top_level_ids) 
229              <- myCoreToStg dflags this_mod tidy_binds
230
231
232             -------------------
233             -- BUILD THE NEW ModDetails AND ModIface
234             -------------------
235         ; let new_details = mkModDetails env_tc tidy_binds 
236                                          top_level_ids orphan_rules
237         ; final_iface <- mkFinalIface ghci_mode dflags location 
238                                       maybe_checked_iface new_iface new_details
239
240             -------------------
241             -- COMPLETE CODE GENERATION
242             -------------------
243         ; (maybe_stub_h_filename, maybe_stub_c_filename, maybe_ibinds)
244              <- restOfCodeGeneration dflags toInterp this_mod
245                    (map ideclName (hsModuleImports rdr_module))
246                    cost_centre_info foreign_stuff env_tc stg_binds 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_ibinds)
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"
281
282       buf <- hGetStringBuffer True{-expand tabs-} src_filename
283
284       let glaexts | dopt Opt_GlasgowExts dflags = 1#
285                   | otherwise                   = 0#
286
287       case parse 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 _ (PModule 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 restOfCodeGeneration dflags toInterp this_mod imported_module_names cost_centre_info 
306                      foreign_stuff env_tc stg_binds tidy_binds
307                      hit pit -- these last two for mapping ModNames to Modules
308  | toInterp
309  = do (ibinds,itbl_env) 
310          <- stgBindsToInterpSyn dflags (map fst stg_binds) 
311                 local_tycons local_classes
312       return (Nothing, Nothing, Just (ibinds,itbl_env))
313
314  | otherwise
315  = do --------------------------  Code generation -------------------------------
316       -- _scc_     "CodeGen"
317       abstractC <- codeGen dflags this_mod imported_modules
318                            cost_centre_info fe_binders
319                            local_tycons stg_binds
320
321       --------------------------  Code output -------------------------------
322       -- _scc_     "CodeOutput"
323       (maybe_stub_h_name, maybe_stub_c_name)
324          <- codeOutput dflags this_mod local_tycons
325                        tidy_binds stg_binds
326                        c_code h_code abstractC
327
328       return (maybe_stub_h_name, maybe_stub_c_name, Nothing)
329  where
330     local_tycons     = typeEnvTyCons env_tc
331     local_classes    = typeEnvClasses env_tc
332     imported_modules = map mod_name_to_Module imported_module_names
333     (fe_binders,h_code,c_code) = foreign_stuff
334
335     mod_name_to_Module :: ModuleName -> Module
336     mod_name_to_Module nm
337        = let str_mi = case lookupModuleEnvByName hit nm of
338                           Just mi -> mi
339                           Nothing -> case lookupModuleEnvByName pit nm of
340                                         Just mi -> mi
341                                         Nothing -> barf nm
342          in  mi_module str_mi
343     barf nm = pprPanic "mod_name_to_Module: no hst or pst mapping for" 
344                        (ppr nm)
345
346
347 dsThenSimplThenTidy dflags pcs hst this_mod print_unqual is_exported tc_result
348  = do ------------------  Desugaring ---------------------------------
349       -- _scc_     "DeSugar"
350       (desugared, rules, h_code, c_code, fe_binders) 
351          <- deSugar dflags pcs hst this_mod print_unqual tc_result
352
353       ------------------  Main Core-language transformations ---------
354       -- _scc_     "Core2Core"
355       (simplified, orphan_rules) 
356          <- core2core dflags pcs hst is_exported desugared rules
357
358       -- Do saturation and convert to A-normal form
359       --    NOTE: future passes cannot transform the syntax, only annotate it
360       saturated <- coreSatPgm dflags simplified
361
362       -- Do the final tidy-up
363       (pcs', tidy_binds, tidy_orphan_rules) 
364          <- tidyCorePgm dflags this_mod pcs saturated orphan_rules
365       
366       return (pcs', tidy_binds, tidy_orphan_rules, (fe_binders,h_code,c_code))
367
368
369 myCoreToStg dflags this_mod tidy_binds
370  = do 
371       () <- coreBindsSize tidy_binds `seq` return ()
372       -- TEMP: the above call zaps some space usage allocated by the
373       -- simplifier, which for reasons I don't understand, persists
374       -- thoroughout code generation
375
376       --let bcos = byteCodeGen tidy_binds
377       --putStrLn (showSDoc (vcat (map ppr bcos)))
378
379       -- _scc_     "Core2Stg"
380       stg_binds <- coreToStg dflags this_mod tidy_binds
381
382       -- _scc_     "Stg2Stg"
383       (stg_binds2, cost_centre_info) <- stg2stg dflags this_mod stg_binds
384       let final_ids = collectFinalStgBinders (map fst stg_binds2)
385
386       return (stg_binds2, cost_centre_info, final_ids)
387 \end{code}
388
389
390 %************************************************************************
391 %*                                                                      *
392 \subsection{Compiling an expression}
393 %*                                                                      *
394 %************************************************************************
395
396 \begin{code}
397 #ifndef GHCI
398 hscExpr dflags hst hit pcs this_module expr
399   = panic "hscExpr: non-interactive build"
400 hscTypeExpr dflags hst hit pcs0 this_module expr
401   = panic "hscTypeExpr: non-interactive build"
402 #else 
403
404 hscExpr
405   :: DynFlags
406   -> HomeSymbolTable    
407   -> HomeIfaceTable
408   -> PersistentCompilerState    -- IN: persistent compiler state
409   -> Module                     -- Context for compiling
410   -> String                     -- The expression
411   -> IO ( PersistentCompilerState, 
412           Maybe (UnlinkedIExpr, PrintUnqualified, Type) )
413
414 hscExpr dflags hst hit pcs0 this_module expr
415    = do {
416         maybe_parsed <- hscParseExpr dflags expr;
417         case maybe_parsed of
418              Nothing -> return (pcs0, Nothing)
419              Just parsed_expr -> do {
420
421                 -- Rename it
422         (pcs1, maybe_renamed_expr) <- 
423                 renameExpr dflags hit hst pcs0 this_module parsed_expr;
424         case maybe_renamed_expr of
425                 Nothing -> return (pcs1, Nothing)
426                 Just (print_unqual, rn_expr) -> do {
427
428                 -- Typecheck it
429         maybe_tc_return
430            <- typecheckExpr dflags pcs1 hst print_unqual this_module rn_expr;
431         case maybe_tc_return of {
432                 Nothing -> return (pcs1, Nothing);
433                 Just (pcs2, tc_expr, ty) -> do
434
435         -- if it isn't an IO-typed expression, 
436         -- wrap "print" around it & recompile...
437         let { is_IO_type = case splitTyConApp_maybe ty of {
438                             Just (tycon, _) -> getUnique tycon == ioTyConKey;
439                             Nothing -> False }
440             };
441
442         if (not is_IO_type)
443                 then do (new_pcs, maybe_stuff)
444                           <- hscExpr dflags hst hit pcs2 this_module 
445                                 ("print (" ++ expr ++ ")")
446                         case maybe_stuff of
447                            Nothing -> return (new_pcs, maybe_stuff)
448                            Just (expr, _, _) ->
449                               return (new_pcs, Just (expr, print_unqual, ty))
450                 else do
451
452                 -- Desugar it
453         ds_expr <- deSugarExpr dflags pcs2 hst this_module
454                         print_unqual tc_expr;
455         
456                 -- Simplify it
457         simpl_expr <- simplifyExpr dflags pcs2 hst ds_expr;
458
459                 -- Saturate it
460         sat_expr <- coreSatExpr dflags simpl_expr;
461
462                 -- Convert to STG
463         let stg_expr = coreExprToStg sat_expr;
464
465                 -- ToDo: need to do SRTs?
466
467                 -- Convert to InterpSyn
468         unlinked_iexpr <- stgExprToInterpSyn dflags stg_expr;
469
470         return (pcs2, Just (unlinked_iexpr, print_unqual, ty));
471      }}}}
472
473 hscParseExpr :: DynFlags -> String -> IO (Maybe RdrNameHsExpr)
474 hscParseExpr dflags str
475  = do --------------------------  Parser  ----------------
476       showPass dflags "Parser"
477       -- _scc_     "Parser"
478
479       buf <- stringToStringBuffer ("__expr " ++ str)
480
481       -- glaexts is True for now (because of the daft __expr at the front
482       -- of the string...)
483       let glaexts = 1#
484       --let glaexts | dopt Opt_GlasgowExts dflags = 1#
485       --            | otherwise                   = 0#
486
487       case parse buf PState{ bol = 0#, atbol = 1#,
488                              context = [], glasgow_exts = glaexts,
489                              loc = mkSrcLoc SLIT("<no file>") 0 } of {
490
491         PFailed err -> do { freeStringBuffer buf;
492                             hPutStrLn stderr (showSDoc err);
493                             return Nothing };
494
495         POk _ (PExpr rdr_expr) -> do {
496
497       --ToDo: can't free the string buffer until we've finished this
498       -- compilation sweep and all the identifiers have gone away.
499       --freeStringBuffer buf;
500       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_expr);
501       return (Just rdr_expr)
502       }}
503 #endif
504 \end{code}
505
506 %************************************************************************
507 %*                                                                      *
508 \subsection{Initial persistent state}
509 %*                                                                      *
510 %************************************************************************
511
512 \begin{code}
513 initPersistentCompilerState :: IO PersistentCompilerState
514 initPersistentCompilerState 
515   = do prs <- initPersistentRenamerState
516        return (
517         PCS { pcs_PIT   = emptyIfaceTable,
518               pcs_PTE   = wiredInThingEnv,
519               pcs_insts = emptyInstEnv,
520               pcs_rules = emptyRuleBase,
521               pcs_PRS   = prs
522             }
523         )
524
525 initPersistentRenamerState :: IO PersistentRenamerState
526   = do ns <- mkSplitUniqSupply 'r'
527        return (
528         PRS { prsOrig  = Orig { origNames  = initOrigNames,
529                                 origIParam = emptyFM },
530               prsDecls = (emptyNameEnv, 0),
531               prsInsts = (emptyBag, 0),
532               prsRules = (emptyBag, 0),
533               prsNS    = ns
534             }
535         )
536
537 initOrigNames :: FiniteMap (ModuleName,OccName) Name
538 initOrigNames 
539    = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
540      where
541         grab names = foldl add emptyFM names
542         add env name 
543            = addToFM env (moduleName (nameModule name), nameOccName name) name
544
545
546 initRules :: PackageRuleBase
547 initRules = emptyRuleBase
548 {- SHOULD BE (ish)
549             foldl add emptyVarEnv builtinRules
550           where
551             add env (name,rule) 
552               = extendRuleBase env name rule
553 -}
554 \end{code}