[project @ 2000-11-22 10:56:53 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, hscTypeExpr,
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 Type
32 import TcHsSyn
33 import InstEnv          ( emptyInstEnv )
34 import Desugar
35 import SimplCore
36 import OccurAnal        ( occurAnalyseBinds )
37 import CoreUtils        ( coreBindsSize )
38 import CoreTidy         ( tidyCorePgm )
39 import CoreToStg        ( topCoreBindsToStg )
40 import StgSyn           ( collectFinalStgBinders )
41 import SimplStg         ( stg2stg )
42 import CodeGen          ( codeGen )
43 import CodeOutput       ( codeOutput )
44
45 import Module           ( ModuleName, moduleName, mkHomeModule )
46 import CmdLineOpts
47 import ErrUtils         ( dumpIfSet_dyn, showPass )
48 import Util             ( unJust )
49 import Unique           ( Uniquable(..) )
50 import PrelNames        ( ioTyConKey )
51 import UniqSupply       ( mkSplitUniqSupply )
52
53 import Bag              ( emptyBag )
54 import Outputable
55 import Interpreter
56 import CmStaticInfo     ( GhciMode(..) )
57 import HscStats         ( ppSourceStats )
58 import HscTypes         ( ModDetails, ModIface(..), PersistentCompilerState(..),
59                           PersistentRenamerState(..), ModuleLocation(..),
60                           HomeSymbolTable, 
61                           OrigNameEnv(..), PackageRuleBase, HomeIfaceTable, 
62                           typeEnvClasses, typeEnvTyCons, emptyIfaceTable )
63 import Type             ( splitTyConApp_maybe )
64 import FiniteMap        ( FiniteMap, plusFM, emptyFM, addToFM )
65 import OccName          ( OccName )
66 import Name             ( Name, nameModule, nameOccName, getName  )
67 import Name             ( emptyNameEnv )
68 import Module           ( Module, lookupModuleEnvByName )
69
70 import Monad            ( when )
71 import Maybe            ( isJust )
72 import IO               ( hPutStrLn, stderr )
73 \end{code}
74
75
76 %************************************************************************
77 %*                                                                      *
78 \subsection{The main compiler pipeline}
79 %*                                                                      *
80 %************************************************************************
81
82 \begin{code}
83 data HscResult
84    -- compilation failed
85    = HscFail     PersistentCompilerState -- updated PCS
86    -- concluded that it wasn't necessary
87    | HscNoRecomp PersistentCompilerState -- updated PCS
88                  ModDetails              -- new details (HomeSymbolTable additions)
89                  ModIface                -- new iface (if any compilation was done)
90    -- did recompilation
91    | HscRecomp   PersistentCompilerState -- updated PCS
92                  ModDetails              -- new details (HomeSymbolTable additions)
93                  ModIface                -- new iface (if any compilation was done)
94                  (Maybe String)          -- generated stub_h filename (in /tmp)
95                  (Maybe String)          -- generated stub_c filename (in /tmp)
96                  (Maybe ([UnlinkedIBind],ItblEnv)) -- interpreted code, if any
97              
98
99         -- no errors or warnings; the individual passes
100         -- (parse/rename/typecheck) print messages themselves
101
102 hscMain
103   :: GhciMode
104   -> DynFlags
105   -> Bool                       -- source unchanged?
106   -> ModuleLocation             -- location info
107   -> Maybe ModIface             -- old interface, if available
108   -> HomeSymbolTable            -- for home module ModDetails
109   -> HomeIfaceTable
110   -> PersistentCompilerState    -- IN: persistent compiler state
111   -> IO HscResult
112
113 hscMain ghci_mode dflags source_unchanged location maybe_old_iface hst hit pcs
114  = do {
115       showPass dflags ("Checking old interface for hs = " 
116                         ++ show (ml_hs_file location)
117                         ++ ", hspp = " ++ show (ml_hspp_file location));
118
119       (pcs_ch, errs_found, (recomp_reqd, maybe_checked_iface))
120          <- checkOldIface dflags hit hst pcs 
121                 (unJust "hscMain" (ml_hi_file location))
122                 source_unchanged maybe_old_iface;
123
124       if errs_found then
125          return (HscFail pcs_ch)
126       else do {
127
128       let no_old_iface = not (isJust maybe_checked_iface)
129           what_next | recomp_reqd || no_old_iface = hscRecomp 
130                     | otherwise                   = hscNoRecomp
131       ;
132       what_next ghci_mode dflags location maybe_checked_iface
133                 hst hit pcs_ch
134       }}
135
136
137 -- we definitely expect to have the old interface available
138 hscNoRecomp ghci_mode dflags location (Just old_iface) hst hit pcs_ch
139  | ghci_mode == OneShot
140  = let bomb = panic "hscNoRecomp:OneShot"
141    in  return (HscNoRecomp pcs_ch bomb bomb)
142  | otherwise
143  = do {
144       hPutStrLn stderr "compilation IS NOT required";
145
146       -- CLOSURE
147       (pcs_cl, closure_errs, cl_hs_decls) 
148          <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
149       if closure_errs then 
150          return (HscFail pcs_cl) 
151       else do {
152
153       -- TYPECHECK
154       maybe_tc_result <- typecheckModule dflags pcs_cl hst 
155                                          old_iface alwaysQualify cl_hs_decls;
156       case maybe_tc_result of {
157          Nothing -> return (HscFail pcs_cl);
158          Just (pcs_tc, tc_result) -> do {
159
160       let env_tc      = tc_env tc_result
161           local_insts = tc_insts tc_result
162           local_rules = tc_rules tc_result
163       ;
164       -- create a new details from the closed, typechecked, old iface
165       let new_details = mkModDetailsFromIface env_tc local_insts local_rules
166       ;
167       return (HscNoRecomp pcs_tc new_details old_iface)
168       }}}}
169
170
171 hscRecomp ghci_mode dflags location maybe_checked_iface hst hit pcs_ch
172  = do   {
173         ; when (verbosity dflags >= 1) $
174                 hPutStrLn stderr "compilation IS required";
175
176           -- what target are we shooting for?
177         ; let toInterp = dopt_HscLang dflags == HscInterpreted
178
179             -------------------
180             -- PARSE
181             -------------------
182         ; maybe_parsed <- myParseModule dflags 
183                              (unJust "hscRecomp:hspp" (ml_hspp_file location))
184         ; case maybe_parsed of {
185              Nothing -> return (HscFail pcs_ch);
186              Just rdr_module -> do {
187         ; let this_mod = mkHomeModule (hsModuleName rdr_module)
188     
189             -------------------
190             -- RENAME
191             -------------------
192         ; showPass dflags "Rename"
193         ; (pcs_rn, maybe_rn_result) 
194              <- renameModule dflags hit hst pcs_ch this_mod rdr_module
195         ; case maybe_rn_result of {
196              Nothing -> return (HscFail pcs_rn);
197              Just (print_unqualified, (is_exported, new_iface, rn_hs_decls)) -> do {
198     
199             -------------------
200             -- TYPECHECK
201             -------------------
202         ; showPass dflags "Typecheck"
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 (tidy_binds, orphan_rules, foreign_stuff) = simpl_result
219             
220             -------------------
221             -- CONVERT TO STG
222             -------------------
223         ; (stg_binds, oa_tidy_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 oa_tidy_binds
242                    hit (pcs_PIT pcs_tc)       
243
244           -- and the answer is ...
245         ; return (HscRecomp pcs_tc 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 oa_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                        oa_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       showPass dflags "DeSugar"
345       -- _scc_     "DeSugar"
346       (desugared, rules, h_code, c_code, fe_binders) 
347          <- deSugar dflags pcs hst this_mod print_unqual tc_result
348
349       --------------------------  Main Core-language transformations ----------------
350       -- _scc_     "Core2Core"
351       (simplified, orphan_rules) 
352          <- core2core dflags pcs hst is_exported desugared rules
353
354       -- Do the final tidy-up
355       showPass dflags "TidyCore"
356       (tidy_binds, tidy_orphan_rules) 
357          <- tidyCorePgm dflags this_mod simplified orphan_rules
358       
359       return (tidy_binds, tidy_orphan_rules, (fe_binders,h_code,c_code))
360
361
362 myCoreToStg dflags this_mod tidy_binds
363  = do 
364       st_uniqs  <- mkSplitUniqSupply 'g'
365       let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds
366
367       () <- coreBindsSize occ_anal_tidy_binds `seq` return ()
368       -- TEMP: the above call zaps some space usage allocated by the
369       -- simplifier, which for reasons I don't understand, persists
370       -- thoroughout code generation
371
372       -- _scc_     "Core2Stg"
373       stg_binds <- topCoreBindsToStg dflags occ_anal_tidy_binds
374
375       showPass dflags "Stg2Stg"
376       -- _scc_     "Stg2Stg"
377       (stg_binds2, cost_centre_info) <- stg2stg dflags this_mod st_uniqs stg_binds
378       let final_ids = collectFinalStgBinders (map fst stg_binds2)
379
380       return (stg_binds2, occ_anal_tidy_binds, cost_centre_info, final_ids)
381 \end{code}
382
383
384 %************************************************************************
385 %*                                                                      *
386 \subsection{Compiling an expression}
387 %*                                                                      *
388 %************************************************************************
389
390 \begin{code}
391 #ifndef GHCI
392 hscExpr dflags hst hit pcs this_module expr
393   = panic "hscExpr: non-interactive build"
394 hscTypeExpr dflags hst hit pcs0 this_module expr
395   = panic "hscTypeExpr: non-interactive build"
396 #else 
397
398 hscExpr
399   :: DynFlags
400   -> HomeSymbolTable    
401   -> HomeIfaceTable
402   -> PersistentCompilerState    -- IN: persistent compiler state
403   -> Module                     -- Context for compiling
404   -> String                     -- The expression
405   -> IO ( PersistentCompilerState, Maybe UnlinkedIExpr )
406
407 hscExpr dflags hst hit pcs0 this_module expr
408    = do {
409         -- parse, rename & typecheck the expression
410         (pcs1, maybe_tc_result)
411            <- hscExprFrontEnd dflags hst hit pcs0 this_module expr;
412
413         case maybe_tc_result of {
414            Nothing -> return (pcs1, Nothing);
415            Just (print_unqual, tc_expr, ty) -> do {
416
417         -- if it isn't an IO-typed expression, 
418         -- wrap "print" around it & recompile...
419         let { is_IO_type = case splitTyConApp_maybe ty of {
420                             Just (tycon, _) -> getUnique tycon == ioTyConKey;
421                             Nothing -> False }
422             };
423
424         if (not is_IO_type)
425                 then hscExpr dflags hst hit pcs1 this_module 
426                         ("print (" ++ expr ++ ")")
427                 else do
428
429                 -- Desugar it
430         ds_expr <- deSugarExpr dflags pcs1 hst this_module
431                         print_unqual tc_expr;
432         
433                 -- Simplify it
434         simpl_expr <- simplifyExpr dflags pcs1 hst ds_expr;
435
436                 -- Convert to STG
437         stg_expr <- coreToStgExpr dflags simpl_expr;
438
439                 -- ToDo: need to do StgVarInfo?  or SRTs?
440
441                 -- Convert to InterpSyn
442         unlinked_iexpr <- stgExprToInterpSyn dflags stg_expr;
443
444         return (pcs1, Just unlinked_iexpr);
445      }}}
446
447 hscExprFrontEnd
448   :: DynFlags
449   -> HomeSymbolTable    
450   -> HomeIfaceTable
451   -> PersistentCompilerState    -- IN: persistent compiler state
452   -> Module                     -- Context for compiling
453   -> String                     -- The expression
454   -> IO ( PersistentCompilerState, 
455           Maybe (PrintUnqualified,TypecheckedHsExpr,Type) 
456         )
457 hscExprFrontEnd dflags hst hit pcs0 this_module expr
458   = do  {       -- Parse it
459         maybe_parsed <- hscParseExpr dflags expr;
460         case maybe_parsed of
461              Nothing -> return (pcs0, Nothing)
462              Just parsed_expr -> do {
463
464                 -- Rename it
465         (pcs1, maybe_renamed_expr) <- 
466                 renameExpr dflags hit hst pcs0 this_module parsed_expr;
467         case maybe_renamed_expr of
468                 Nothing -> return (pcs1, Nothing)
469                 Just (print_unqual, rn_expr) -> do {
470
471                 -- Typecheck it
472         maybe_tc_return
473            <- typecheckExpr dflags pcs1 hst print_unqual this_module rn_expr;
474         case maybe_tc_return of
475                 Nothing -> return (pcs1, Nothing)
476                 Just (pcs2, tc_expr, ty) -> 
477                    return (pcs2, Just (print_unqual, tc_expr, ty))
478     }}}
479
480 hscTypeExpr
481   :: DynFlags
482   -> HomeSymbolTable    
483   -> HomeIfaceTable
484   -> PersistentCompilerState    -- IN: persistent compiler state
485   -> Module                     -- Context for compiling
486   -> String                     -- The expression
487   -> IO (PersistentCompilerState, Maybe (PrintUnqualified, Type))
488 hscTypeExpr dflags hst hit pcs0 this_module expr
489   = do (pcs1, maybe_tc_result)
490           <- hscExprFrontEnd dflags hst hit pcs0 this_module expr
491        case maybe_tc_result of
492           Nothing -> return (pcs1, Nothing)
493           Just (print_unqual,_,ty) -> return (pcs1, Just (print_unqual,ty))
494
495 hscParseExpr :: DynFlags -> String -> IO (Maybe RdrNameHsExpr)
496 hscParseExpr dflags str
497  = do --------------------------  Parser  ----------------
498       showPass dflags "Parser"
499       -- _scc_     "Parser"
500
501       buf <- stringToStringBuffer ("__expr " ++ str)
502
503       -- glaexts is True for now (because of the daft __expr at the front
504       -- of the string...)
505       let glaexts = 1#
506       --let glaexts | dopt Opt_GlasgowExts dflags = 1#
507       --            | otherwise                   = 0#
508
509       case parse buf PState{ bol = 0#, atbol = 1#,
510                              context = [], glasgow_exts = glaexts,
511                              loc = mkSrcLoc SLIT("<no file>") 0 } of {
512
513         PFailed err -> do { freeStringBuffer buf;
514                             hPutStrLn stderr (showSDoc err);
515                             return Nothing };
516
517         POk _ (PExpr rdr_expr) -> do {
518
519       --ToDo: can't free the string buffer until we've finished this
520       -- compilation sweep and all the identifiers have gone away.
521       --freeStringBuffer buf;
522       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_expr);
523       return (Just rdr_expr)
524       }}
525 #endif
526 \end{code}
527
528 %************************************************************************
529 %*                                                                      *
530 \subsection{Initial persistent state}
531 %*                                                                      *
532 %************************************************************************
533
534 \begin{code}
535 initPersistentCompilerState :: IO PersistentCompilerState
536 initPersistentCompilerState 
537   = do prs <- initPersistentRenamerState
538        return (
539         PCS { pcs_PIT   = emptyIfaceTable,
540               pcs_PTE   = wiredInThingEnv,
541               pcs_insts = emptyInstEnv,
542               pcs_rules = emptyRuleBase,
543               pcs_PRS   = prs
544             }
545         )
546
547 initPersistentRenamerState :: IO PersistentRenamerState
548   = do ns <- mkSplitUniqSupply 'r'
549        return (
550         PRS { prsOrig  = Orig { origNames  = initOrigNames,
551                                 origIParam = emptyFM },
552               prsDecls = (emptyNameEnv, 0),
553               prsInsts = (emptyBag, 0),
554               prsRules = (emptyBag, 0),
555               prsNS    = ns
556             }
557         )
558
559 initOrigNames :: FiniteMap (ModuleName,OccName) Name
560 initOrigNames 
561    = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
562      where
563         grab names = foldl add emptyFM names
564         add env name 
565            = addToFM env (moduleName (nameModule name), nameOccName name) name
566
567
568 initRules :: PackageRuleBase
569 initRules = emptyRuleBase
570 {- SHOULD BE (ish)
571             foldl add emptyVarEnv builtinRules
572           where
573             add env (name,rule) 
574               = extendRuleBase env name rule
575 -}
576 \end{code}