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