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