[project @ 2000-11-22 12:22:15 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         ; (pcs_rn, maybe_rn_result) 
193              <- renameModule dflags hit hst pcs_ch this_mod rdr_module
194         ; case maybe_rn_result of {
195              Nothing -> return (HscFail pcs_rn);
196              Just (print_unqualified, (is_exported, new_iface, rn_hs_decls)) -> do {
197     
198             -------------------
199             -- TYPECHECK
200             -------------------
201         ; maybe_tc_result <- typecheckModule dflags pcs_rn hst new_iface 
202                                              print_unqualified rn_hs_decls
203         ; case maybe_tc_result of {
204              Nothing -> 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       -- _scc_     "DeSugar"
343       (desugared, rules, h_code, c_code, fe_binders) 
344          <- deSugar dflags pcs hst this_mod print_unqual tc_result
345
346       --------------------------  Main Core-language transformations ----------------
347       -- _scc_     "Core2Core"
348       (simplified, orphan_rules) 
349          <- core2core dflags pcs hst is_exported desugared rules
350
351       -- Do the final tidy-up
352       (tidy_binds, tidy_orphan_rules) 
353          <- tidyCorePgm dflags this_mod simplified orphan_rules
354       
355       return (tidy_binds, tidy_orphan_rules, (fe_binders,h_code,c_code))
356
357
358 myCoreToStg dflags this_mod tidy_binds
359  = do 
360       st_uniqs  <- mkSplitUniqSupply 'g'
361       let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds
362
363       () <- coreBindsSize occ_anal_tidy_binds `seq` return ()
364       -- TEMP: the above call zaps some space usage allocated by the
365       -- simplifier, which for reasons I don't understand, persists
366       -- thoroughout code generation
367
368       -- _scc_     "Core2Stg"
369       stg_binds <- topCoreBindsToStg dflags occ_anal_tidy_binds
370
371       showPass dflags "Stg2Stg"
372       -- _scc_     "Stg2Stg"
373       (stg_binds2, cost_centre_info) <- stg2stg dflags this_mod st_uniqs stg_binds
374       let final_ids = collectFinalStgBinders (map fst stg_binds2)
375
376       return (stg_binds2, occ_anal_tidy_binds, cost_centre_info, final_ids)
377 \end{code}
378
379
380 %************************************************************************
381 %*                                                                      *
382 \subsection{Compiling an expression}
383 %*                                                                      *
384 %************************************************************************
385
386 \begin{code}
387 #ifndef GHCI
388 hscExpr dflags hst hit pcs this_module expr
389   = panic "hscExpr: non-interactive build"
390 hscTypeExpr dflags hst hit pcs0 this_module expr
391   = panic "hscTypeExpr: non-interactive build"
392 #else 
393
394 hscExpr
395   :: DynFlags
396   -> HomeSymbolTable    
397   -> HomeIfaceTable
398   -> PersistentCompilerState    -- IN: persistent compiler state
399   -> Module                     -- Context for compiling
400   -> String                     -- The expression
401   -> IO ( PersistentCompilerState, Maybe UnlinkedIExpr )
402
403 hscExpr dflags hst hit pcs0 this_module expr
404    = do {
405         -- parse, rename & typecheck the expression
406         (pcs1, maybe_tc_result)
407            <- hscExprFrontEnd dflags hst hit pcs0 this_module expr;
408
409         case maybe_tc_result of {
410            Nothing -> return (pcs1, Nothing);
411            Just (print_unqual, tc_expr, ty) -> do {
412
413         -- if it isn't an IO-typed expression, 
414         -- wrap "print" around it & recompile...
415         let { is_IO_type = case splitTyConApp_maybe ty of {
416                             Just (tycon, _) -> getUnique tycon == ioTyConKey;
417                             Nothing -> False }
418             };
419
420         if (not is_IO_type)
421                 then hscExpr dflags hst hit pcs1 this_module 
422                         ("print (" ++ expr ++ ")")
423                 else do
424
425                 -- Desugar it
426         ds_expr <- deSugarExpr dflags pcs1 hst this_module
427                         print_unqual tc_expr;
428         
429                 -- Simplify it
430         simpl_expr <- simplifyExpr dflags pcs1 hst ds_expr;
431
432                 -- Convert to STG
433         stg_expr <- coreToStgExpr dflags simpl_expr;
434
435                 -- ToDo: need to do StgVarInfo?  or SRTs?
436
437                 -- Convert to InterpSyn
438         unlinked_iexpr <- stgExprToInterpSyn dflags stg_expr;
439
440         return (pcs1, Just unlinked_iexpr);
441      }}}
442
443 hscExprFrontEnd
444   :: DynFlags
445   -> HomeSymbolTable    
446   -> HomeIfaceTable
447   -> PersistentCompilerState    -- IN: persistent compiler state
448   -> Module                     -- Context for compiling
449   -> String                     -- The expression
450   -> IO ( PersistentCompilerState, 
451           Maybe (PrintUnqualified,TypecheckedHsExpr,Type) 
452         )
453 hscExprFrontEnd dflags hst hit pcs0 this_module expr
454   = do  {       -- Parse it
455         maybe_parsed <- hscParseExpr dflags expr;
456         case maybe_parsed of
457              Nothing -> return (pcs0, Nothing)
458              Just parsed_expr -> do {
459
460                 -- Rename it
461         (pcs1, maybe_renamed_expr) <- 
462                 renameExpr dflags hit hst pcs0 this_module parsed_expr;
463         case maybe_renamed_expr of
464                 Nothing -> return (pcs1, Nothing)
465                 Just (print_unqual, rn_expr) -> do {
466
467                 -- Typecheck it
468         maybe_tc_return
469            <- typecheckExpr dflags pcs1 hst print_unqual this_module rn_expr;
470         case maybe_tc_return of
471                 Nothing -> return (pcs1, Nothing)
472                 Just (pcs2, tc_expr, ty) -> 
473                    return (pcs2, Just (print_unqual, tc_expr, ty))
474     }}}
475
476 hscTypeExpr
477   :: DynFlags
478   -> HomeSymbolTable    
479   -> HomeIfaceTable
480   -> PersistentCompilerState    -- IN: persistent compiler state
481   -> Module                     -- Context for compiling
482   -> String                     -- The expression
483   -> IO (PersistentCompilerState, Maybe (PrintUnqualified, Type))
484 hscTypeExpr dflags hst hit pcs0 this_module expr
485   = do (pcs1, maybe_tc_result)
486           <- hscExprFrontEnd dflags hst hit pcs0 this_module expr
487        case maybe_tc_result of
488           Nothing -> return (pcs1, Nothing)
489           Just (print_unqual,_,ty) -> return (pcs1, Just (print_unqual,ty))
490
491 hscParseExpr :: DynFlags -> String -> IO (Maybe RdrNameHsExpr)
492 hscParseExpr dflags str
493  = do --------------------------  Parser  ----------------
494       showPass dflags "Parser"
495       -- _scc_     "Parser"
496
497       buf <- stringToStringBuffer ("__expr " ++ str)
498
499       -- glaexts is True for now (because of the daft __expr at the front
500       -- of the string...)
501       let glaexts = 1#
502       --let glaexts | dopt Opt_GlasgowExts dflags = 1#
503       --            | otherwise                   = 0#
504
505       case parse buf PState{ bol = 0#, atbol = 1#,
506                              context = [], glasgow_exts = glaexts,
507                              loc = mkSrcLoc SLIT("<no file>") 0 } of {
508
509         PFailed err -> do { freeStringBuffer buf;
510                             hPutStrLn stderr (showSDoc err);
511                             return Nothing };
512
513         POk _ (PExpr rdr_expr) -> do {
514
515       --ToDo: can't free the string buffer until we've finished this
516       -- compilation sweep and all the identifiers have gone away.
517       --freeStringBuffer buf;
518       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_expr);
519       return (Just rdr_expr)
520       }}
521 #endif
522 \end{code}
523
524 %************************************************************************
525 %*                                                                      *
526 \subsection{Initial persistent state}
527 %*                                                                      *
528 %************************************************************************
529
530 \begin{code}
531 initPersistentCompilerState :: IO PersistentCompilerState
532 initPersistentCompilerState 
533   = do prs <- initPersistentRenamerState
534        return (
535         PCS { pcs_PIT   = emptyIfaceTable,
536               pcs_PTE   = wiredInThingEnv,
537               pcs_insts = emptyInstEnv,
538               pcs_rules = emptyRuleBase,
539               pcs_PRS   = prs
540             }
541         )
542
543 initPersistentRenamerState :: IO PersistentRenamerState
544   = do ns <- mkSplitUniqSupply 'r'
545        return (
546         PRS { prsOrig  = Orig { origNames  = initOrigNames,
547                                 origIParam = emptyFM },
548               prsDecls = (emptyNameEnv, 0),
549               prsInsts = (emptyBag, 0),
550               prsRules = (emptyBag, 0),
551               prsNS    = ns
552             }
553         )
554
555 initOrigNames :: FiniteMap (ModuleName,OccName) Name
556 initOrigNames 
557    = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
558      where
559         grab names = foldl add emptyFM names
560         add env name 
561            = addToFM env (moduleName (nameModule name), nameOccName name) name
562
563
564 initRules :: PackageRuleBase
565 initRules = emptyRuleBase
566 {- SHOULD BE (ish)
567             foldl add emptyVarEnv builtinRules
568           where
569             add env (name,rule) 
570               = extendRuleBase env name rule
571 -}
572 \end{code}