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