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