[project @ 2000-11-21 14:31:58 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, hscExpr,
8                  initPersistentCompilerState ) where
9
10 #include "HsVersions.h"
11
12 #ifdef GHCI
13 import RdrHsSyn         ( RdrNameHsExpr )
14 import CoreToStg        ( coreToStgExpr )
15 import StringBuffer     ( stringToStringBuffer, freeStringBuffer )
16 #endif
17
18 import HsSyn
19
20 import StringBuffer     ( hGetStringBuffer )
21 import Parser
22 import Lex              ( PState(..), ParseResult(..) )
23 import SrcLoc           ( mkSrcLoc )
24 import Rename
25 import Rules            ( emptyRuleBase )
26 import PrelInfo         ( wiredInThingEnv, wiredInThings )
27 import PrelNames        ( knownKeyNames )
28 import MkIface          ( completeIface, mkModDetailsFromIface, mkModDetails,
29                           writeIface, pprIface )
30 import TcModule
31 import InstEnv          ( emptyInstEnv )
32 import Desugar
33 import SimplCore
34 import OccurAnal        ( occurAnalyseBinds )
35 import CoreUtils        ( coreBindsSize )
36 import CoreTidy         ( tidyCorePgm )
37 import CoreToStg        ( topCoreBindsToStg )
38 import StgSyn           ( collectFinalStgBinders )
39 import SimplStg         ( stg2stg )
40 import CodeGen          ( codeGen )
41 import CodeOutput       ( codeOutput )
42
43 import Module           ( ModuleName, moduleName, mkHomeModule )
44 import CmdLineOpts
45 import ErrUtils         ( dumpIfSet_dyn, showPass )
46 import Util             ( unJust )
47 import Unique           ( Uniquable(..) )
48 import PrelNames        ( ioTyConKey )
49 import UniqSupply       ( mkSplitUniqSupply )
50
51 import Bag              ( emptyBag )
52 import Outputable
53 import Interpreter
54 import CmStaticInfo     ( GhciMode(..) )
55 import HscStats         ( ppSourceStats )
56 import HscTypes         ( ModDetails, ModIface(..), PersistentCompilerState(..),
57                           PersistentRenamerState(..), ModuleLocation(..),
58                           HomeSymbolTable, 
59                           OrigNameEnv(..), PackageRuleBase, HomeIfaceTable, 
60                           typeEnvClasses, typeEnvTyCons, emptyIfaceTable )
61 import Type             ( splitTyConApp_maybe )
62 import FiniteMap        ( FiniteMap, plusFM, emptyFM, addToFM )
63 import OccName          ( OccName )
64 import Name             ( Name, nameModule, nameOccName, getName  )
65 import Name             ( emptyNameEnv )
66 import Module           ( Module, lookupModuleEnvByName )
67
68 import Monad            ( when )
69 import Maybe            ( isJust )
70 import IO               ( hPutStrLn, stderr )
71 \end{code}
72
73
74 %************************************************************************
75 %*                                                                      *
76 \subsection{The main compiler pipeline}
77 %*                                                                      *
78 %************************************************************************
79
80 \begin{code}
81 data HscResult
82    -- compilation failed
83    = HscFail     PersistentCompilerState -- updated PCS
84    -- concluded that it wasn't necessary
85    | HscNoRecomp PersistentCompilerState -- updated PCS
86                  ModDetails              -- new details (HomeSymbolTable additions)
87                  ModIface                -- new iface (if any compilation was done)
88    -- did recompilation
89    | HscRecomp   PersistentCompilerState -- updated PCS
90                  ModDetails              -- new details (HomeSymbolTable additions)
91                  ModIface                -- new iface (if any compilation was done)
92                  (Maybe String)          -- generated stub_h filename (in /tmp)
93                  (Maybe String)          -- generated stub_c filename (in /tmp)
94                  (Maybe ([UnlinkedIBind],ItblEnv)) -- interpreted code, if any
95              
96
97         -- no errors or warnings; the individual passes
98         -- (parse/rename/typecheck) print messages themselves
99
100 hscMain
101   :: GhciMode
102   -> DynFlags
103   -> Bool                       -- source unchanged?
104   -> ModuleLocation             -- location info
105   -> Maybe ModIface             -- old interface, if available
106   -> HomeSymbolTable            -- for home module ModDetails
107   -> HomeIfaceTable
108   -> PersistentCompilerState    -- IN: persistent compiler state
109   -> IO HscResult
110
111 hscMain ghci_mode dflags source_unchanged location maybe_old_iface hst hit pcs
112  = do {
113       showPass dflags ("Checking old interface for hs = " 
114                         ++ show (ml_hs_file location)
115                         ++ ", hspp = " ++ show (ml_hspp_file location));
116
117       (pcs_ch, errs_found, (recomp_reqd, maybe_checked_iface))
118          <- checkOldIface dflags hit hst pcs 
119                 (unJust "hscMain" (ml_hi_file location))
120                 source_unchanged maybe_old_iface;
121
122       if errs_found then
123          return (HscFail pcs_ch)
124       else do {
125
126       let no_old_iface = not (isJust maybe_checked_iface)
127           what_next | recomp_reqd || no_old_iface = hscRecomp 
128                     | otherwise                   = hscNoRecomp
129       ;
130       what_next ghci_mode dflags location maybe_checked_iface
131                 hst hit pcs_ch
132       }}
133
134
135 -- we definitely expect to have the old interface available
136 hscNoRecomp ghci_mode dflags location (Just old_iface) hst hit pcs_ch
137  | ghci_mode == OneShot
138  = let bomb = panic "hscNoRecomp:OneShot"
139    in  return (HscNoRecomp pcs_ch bomb bomb)
140  | otherwise
141  = do {
142       hPutStrLn stderr "compilation not required";
143       ;
144       -- CLOSURE
145       (pcs_cl, closure_errs, cl_hs_decls) 
146          <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
147       if closure_errs then 
148          return (HscFail pcs_cl) 
149       else do {
150
151       -- TYPECHECK
152       maybe_tc_result <- typecheckModule dflags pcs_cl hst 
153                                          old_iface alwaysQualify cl_hs_decls;
154       case maybe_tc_result of {
155          Nothing -> return (HscFail pcs_cl);
156          Just (pcs_tc, tc_result) -> do {
157
158       let env_tc      = tc_env tc_result
159           local_insts = tc_insts tc_result
160           local_rules = tc_rules tc_result
161       ;
162       -- create a new details from the closed, typechecked, old iface
163       let new_details = mkModDetailsFromIface env_tc local_insts local_rules
164       ;
165       return (HscNoRecomp pcs_tc new_details old_iface)
166       }}}}
167
168
169 hscRecomp ghci_mode dflags location maybe_checked_iface hst hit pcs_ch
170  = do   {
171         ; hPutStrLn stderr "compilation IS required";
172
173           -- what target are we shooting for?
174         ; let toInterp = dopt_HscLang dflags == HscInterpreted
175
176             -------------------
177             -- PARSE
178             -------------------
179         ; maybe_parsed <- myParseModule dflags 
180                              (unJust "hscRecomp:hspp" (ml_hspp_file location))
181         ; case maybe_parsed of {
182              Nothing -> return (HscFail pcs_ch);
183              Just rdr_module -> do {
184         ; let this_mod = mkHomeModule (hsModuleName rdr_module)
185     
186             -------------------
187             -- RENAME
188             -------------------
189         ; showPass dflags "Rename"
190         ; (pcs_rn, maybe_rn_result) 
191              <- renameModule dflags hit hst pcs_ch this_mod rdr_module
192         ; case maybe_rn_result of {
193              Nothing -> return (HscFail pcs_rn);
194              Just (print_unqualified, (is_exported, new_iface, rn_hs_decls)) -> do {
195     
196             -------------------
197             -- TYPECHECK
198             -------------------
199         ; showPass dflags "Typecheck"
200         ; maybe_tc_result <- typecheckModule dflags pcs_rn hst new_iface 
201                                              print_unqualified rn_hs_decls
202         ; case maybe_tc_result of {
203              Nothing -> do { hPutStrLn stderr "Typecheck failed" 
204                            ; return (HscFail pcs_rn) } ;
205              Just (pcs_tc, tc_result) -> do {
206     
207         ; let env_tc        = tc_env tc_result
208               local_insts   = tc_insts tc_result
209
210             -------------------
211             -- DESUGAR, SIMPLIFY, TIDY-CORE
212             -------------------
213           -- We grab the the unfoldings at this point.
214         ; simpl_result <- dsThenSimplThenTidy dflags pcs_tc hst this_mod 
215                                               print_unqualified is_exported tc_result
216         ; let (tidy_binds, orphan_rules, foreign_stuff) = simpl_result
217             
218             -------------------
219             -- CONVERT TO STG
220             -------------------
221         ; (stg_binds, oa_tidy_binds, cost_centre_info, top_level_ids) 
222              <- myCoreToStg dflags this_mod tidy_binds
223
224
225             -------------------
226             -- BUILD THE NEW ModDetails AND ModIface
227             -------------------
228         ; let new_details = mkModDetails env_tc local_insts tidy_binds 
229                                          top_level_ids orphan_rules
230         ; final_iface <- mkFinalIface ghci_mode dflags location 
231                                       maybe_checked_iface new_iface new_details
232
233             -------------------
234             -- COMPLETE CODE GENERATION
235             -------------------
236         ; (maybe_stub_h_filename, maybe_stub_c_filename, maybe_ibinds)
237              <- restOfCodeGeneration dflags toInterp this_mod
238                    (map ideclName (hsModuleImports rdr_module))
239                    cost_centre_info foreign_stuff env_tc stg_binds oa_tidy_binds
240                    hit (pcs_PIT pcs_tc)       
241
242           -- and the answer is ...
243         ; return (HscRecomp pcs_tc new_details final_iface
244                             maybe_stub_h_filename maybe_stub_c_filename
245                             maybe_ibinds)
246           }}}}}}}
247
248
249
250 mkFinalIface ghci_mode dflags location maybe_old_iface new_iface new_details
251  = case completeIface maybe_old_iface new_iface new_details of
252       (new_iface, Nothing) -- no change in the interfacfe
253          -> do when (dopt Opt_D_dump_hi_diffs dflags)
254                     (printDump (text "INTERFACE UNCHANGED"))
255                dumpIfSet_dyn dflags Opt_D_dump_hi
256                              "UNCHANGED FINAL INTERFACE" (pprIface new_iface)
257                return new_iface
258       (new_iface, Just sdoc_diffs)
259          -> do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "INTERFACE HAS CHANGED" 
260                                     sdoc_diffs
261                dumpIfSet_dyn dflags Opt_D_dump_hi "NEW FINAL INTERFACE" 
262                                     (pprIface new_iface)
263                -- Write the interface file
264                when (ghci_mode /= Interactive) 
265                     (writeIface (unJust "hscRecomp:hi" (ml_hi_file location))
266                                 new_iface)
267                return new_iface
268
269
270 myParseModule dflags src_filename
271  = do --------------------------  Parser  ----------------
272       showPass dflags "Parser"
273       -- _scc_     "Parser"
274
275       buf <- hGetStringBuffer True{-expand tabs-} src_filename
276
277       let glaexts | dopt Opt_GlasgowExts dflags = 1#
278                   | otherwise                 = 0#
279
280       case parse buf PState{ bol = 0#, atbol = 1#,
281                              context = [], glasgow_exts = glaexts,
282                              loc = mkSrcLoc (_PK_ src_filename) 1 } of {
283
284         PFailed err -> do { hPutStrLn stderr (showSDoc err);
285                             return Nothing };
286
287         POk _ (PModule rdr_module@(HsModule mod_name _ _ _ _ _ _)) -> do {
288
289       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
290       
291       dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
292                            (ppSourceStats False rdr_module) ;
293       
294       return (Just rdr_module)
295       }}
296
297
298 restOfCodeGeneration dflags toInterp this_mod imported_module_names cost_centre_info 
299                      foreign_stuff env_tc stg_binds oa_tidy_binds
300                      hit pit -- these last two for mapping ModNames to Modules
301  | toInterp
302  = do (ibinds,itbl_env) 
303          <- stgBindsToInterpSyn dflags (map fst stg_binds) 
304                 local_tycons local_classes
305       return (Nothing, Nothing, Just (ibinds,itbl_env))
306
307  | otherwise
308  = do --------------------------  Code generation -------------------------------
309       -- _scc_     "CodeGen"
310       abstractC <- codeGen dflags this_mod imported_modules
311                            cost_centre_info fe_binders
312                            local_tycons stg_binds
313
314       --------------------------  Code output -------------------------------
315       -- _scc_     "CodeOutput"
316       (maybe_stub_h_name, maybe_stub_c_name)
317          <- codeOutput dflags this_mod local_tycons
318                        oa_tidy_binds stg_binds
319                        c_code h_code abstractC
320
321       return (maybe_stub_h_name, maybe_stub_c_name, Nothing)
322  where
323     local_tycons     = typeEnvTyCons env_tc
324     local_classes    = typeEnvClasses env_tc
325     imported_modules = map mod_name_to_Module imported_module_names
326     (fe_binders,h_code,c_code) = foreign_stuff
327
328     mod_name_to_Module :: ModuleName -> Module
329     mod_name_to_Module nm
330        = let str_mi = case lookupModuleEnvByName hit nm of
331                           Just mi -> mi
332                           Nothing -> case lookupModuleEnvByName pit nm of
333                                         Just mi -> mi
334                                         Nothing -> barf nm
335          in  mi_module str_mi
336     barf nm = pprPanic "mod_name_to_Module: no hst or pst mapping for" 
337                        (ppr nm)
338
339
340 dsThenSimplThenTidy dflags pcs hst this_mod print_unqual is_exported tc_result
341  = do --------------------------  Desugaring ----------------
342       showPass dflags "DeSugar"
343       -- _scc_     "DeSugar"
344       (desugared, rules, h_code, c_code, fe_binders) 
345          <- deSugar dflags pcs hst this_mod print_unqual tc_result
346
347       --------------------------  Main Core-language transformations ----------------
348       -- _scc_     "Core2Core"
349       (simplified, orphan_rules) 
350          <- core2core dflags pcs hst is_exported desugared rules
351
352       -- Do the final tidy-up
353       showPass dflags "TidyCore"
354       (tidy_binds, tidy_orphan_rules) 
355          <- tidyCorePgm dflags this_mod simplified orphan_rules
356       
357       return (tidy_binds, tidy_orphan_rules, (fe_binders,h_code,c_code))
358
359
360 myCoreToStg dflags this_mod tidy_binds
361  = do 
362       st_uniqs  <- mkSplitUniqSupply 'g'
363       let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds
364
365       () <- coreBindsSize occ_anal_tidy_binds `seq` return ()
366       -- TEMP: the above call zaps some space usage allocated by the
367       -- simplifier, which for reasons I don't understand, persists
368       -- thoroughout code generation
369
370       -- _scc_     "Core2Stg"
371       stg_binds <- topCoreBindsToStg dflags occ_anal_tidy_binds
372
373       showPass dflags "Stg2Stg"
374       -- _scc_     "Stg2Stg"
375       (stg_binds2, cost_centre_info) <- stg2stg dflags this_mod st_uniqs stg_binds
376       let final_ids = collectFinalStgBinders (map fst stg_binds2)
377
378       return (stg_binds2, occ_anal_tidy_binds, cost_centre_info, final_ids)
379 \end{code}
380
381
382 %************************************************************************
383 %*                                                                      *
384 \subsection{Compiling an expression}
385 %*                                                                      *
386 %************************************************************************
387
388 \begin{code}
389 hscExpr
390   :: DynFlags
391   -> HomeSymbolTable    
392   -> HomeIfaceTable
393   -> PersistentCompilerState    -- IN: persistent compiler state
394   -> Module                     -- Context for compiling
395   -> String                     -- The expression
396   -> IO ( PersistentCompilerState, Maybe UnlinkedIExpr )
397
398 #ifndef GHCI
399 hscExpr dflags hst hit pcs this_module expr
400   = panic "hscExpr: non-interactive build"
401 #else 
402
403 hscExpr dflags hst hit pcs0 this_module expr
404   = do  {       -- Parse it
405         maybe_parsed <- hscParseExpr dflags expr;
406         case maybe_parsed of
407              Nothing -> return (pcs0, Nothing)
408              Just parsed_expr -> do {
409
410                 -- Rename it
411         (pcs1, maybe_renamed_expr) <- 
412                 renameExpr dflags hit hst pcs0 this_module parsed_expr;
413         case maybe_renamed_expr of
414                 Nothing -> return (pcs1, Nothing)
415                 Just (print_unqual, rn_expr) -> do {
416
417                 -- Typecheck it
418         maybe_tc_return
419            <- typecheckExpr dflags pcs1 hst print_unqual this_module rn_expr;
420         case maybe_tc_return of
421                 Nothing -> return (pcs1, Nothing)
422                 Just (pcs2, tc_expr, ty) -> do {
423
424         let { is_IO_type = case splitTyConApp_maybe ty of {
425                             Just (tycon, _) -> getUnique tycon == ioTyConKey;
426                             Nothing -> False }
427             };
428
429         if (not is_IO_type)
430                 then hscExpr dflags hst hit pcs2 this_module 
431                         ("print (" ++ expr ++ ")")
432                 else do
433
434                 -- Desugar it
435         ds_expr <- deSugarExpr dflags pcs2 hst this_module
436                         print_unqual tc_expr;
437         
438                 -- Simplify it
439         simpl_expr <- simplifyExpr dflags pcs2 hst ds_expr;
440
441                 -- Convert to STG
442         stg_expr <- coreToStgExpr dflags simpl_expr;
443
444                 -- ToDo: need to do StgVarInfo?  or SRTs?
445
446                 -- Convert to InterpSyn
447         unlinked_iexpr <- stgExprToInterpSyn dflags stg_expr;
448
449         return (pcs2, Just unlinked_iexpr);
450      }}}}
451
452 hscParseExpr :: DynFlags -> String -> IO (Maybe RdrNameHsExpr)
453 hscParseExpr dflags str
454  = do --------------------------  Parser  ----------------
455       showPass dflags "Parser"
456       -- _scc_     "Parser"
457
458       buf <- stringToStringBuffer ("__expr " ++ str)
459
460       -- glaexts is True for now (because of the daft __expr at the front
461       -- of the string...)
462       let glaexts = 1#
463       --let glaexts | dopt Opt_GlasgowExts dflags = 1#
464       --            | otherwise                   = 0#
465
466       case parse buf PState{ bol = 0#, atbol = 1#,
467                              context = [], glasgow_exts = glaexts,
468                              loc = mkSrcLoc SLIT("<no file>") 0 } of {
469
470         PFailed err -> do { freeStringBuffer buf;
471                             hPutStrLn stderr (showSDoc err);
472                             return Nothing };
473
474         POk _ (PExpr rdr_expr) -> do {
475
476       --ToDo: can't free the string buffer until we've finished this
477       -- compilation sweep and all the identifiers have gone away.
478       --freeStringBuffer buf;
479       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_expr);
480       return (Just rdr_expr)
481       }}
482 #endif
483 \end{code}
484
485 %************************************************************************
486 %*                                                                      *
487 \subsection{Initial persistent state}
488 %*                                                                      *
489 %************************************************************************
490
491 \begin{code}
492 initPersistentCompilerState :: IO PersistentCompilerState
493 initPersistentCompilerState 
494   = do prs <- initPersistentRenamerState
495        return (
496         PCS { pcs_PIT   = emptyIfaceTable,
497               pcs_PTE   = wiredInThingEnv,
498               pcs_insts = emptyInstEnv,
499               pcs_rules = emptyRuleBase,
500               pcs_PRS   = prs
501             }
502         )
503
504 initPersistentRenamerState :: IO PersistentRenamerState
505   = do ns <- mkSplitUniqSupply 'r'
506        return (
507         PRS { prsOrig  = Orig { origNames  = initOrigNames,
508                                 origIParam = emptyFM },
509               prsDecls = (emptyNameEnv, 0),
510               prsInsts = (emptyBag, 0),
511               prsRules = (emptyBag, 0),
512               prsNS    = ns
513             }
514         )
515
516 initOrigNames :: FiniteMap (ModuleName,OccName) Name
517 initOrigNames 
518    = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
519      where
520         grab names = foldl add emptyFM names
521         add env name 
522            = addToFM env (moduleName (nameModule name), nameOccName name) name
523
524
525 initRules :: PackageRuleBase
526 initRules = emptyRuleBase
527 {- SHOULD BE (ish)
528             foldl add emptyVarEnv builtinRules
529           where
530             add env (name,rule) 
531               = extendRuleBase env name rule
532 -}
533 \end{code}