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