[project @ 2001-02-23 12:24:10 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 Rename           ( renameExpr )
18 import Unique           ( Uniquable(..) )
19 import Type             ( Type, splitTyConApp_maybe, tidyType )
20 import PrelNames        ( ioTyConKey )
21 import ByteCodeGen      ( byteCodeGen )
22 #endif
23
24 import HsSyn
25
26 import StringBuffer     ( hGetStringBuffer, 
27                           stringToStringBuffer, freeStringBuffer )
28 import Parser
29 import Lex              ( PState(..), ParseResult(..) )
30 import SrcLoc           ( mkSrcLoc )
31 import Rename           ( checkOldIface, renameModule, closeIfaceDecls )
32 import Rules            ( emptyRuleBase )
33 import PrelInfo         ( wiredInThingEnv, wiredInThings )
34 import PrelNames        ( vanillaSyntaxMap, knownKeyNames )
35 import MkIface          ( completeIface, mkModDetailsFromIface, mkModDetails,
36                           writeIface, pprIface )
37 import TcModule
38 import InstEnv          ( emptyInstEnv )
39 import Desugar
40 import SimplCore
41 import CoreUtils        ( coreBindsSize )
42 import CoreTidy         ( tidyCorePgm )
43 import CoreSat
44 import CoreToStg        ( coreToStg )
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                           NameSupply(..), PackageRuleBase, HomeIfaceTable, 
64                           typeEnvClasses, typeEnvTyCons, emptyIfaceTable )
65 import FiniteMap        ( FiniteMap, plusFM, emptyFM, addToFM )
66 import OccName          ( OccName )
67 import VarEnv           ( emptyTidyEnv )
68 import Name             ( Name, nameModule, nameOccName, getName, isGlobalName,
69                           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 ([UnlinkedBCO],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       hPutStrLn stderr "compilation IS NOT required";
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 
160         <- typecheckIface dflags pcs_cl hst old_iface (vanillaSyntaxMap, cl_hs_decls);
161
162       case maybe_tc_result of {
163          Nothing -> return (HscFail pcs_cl);
164          Just (pcs_tc, env_tc, local_rules) -> do {
165
166       -- create a new details from the closed, typechecked, old iface
167       let new_details = mkModDetailsFromIface env_tc local_rules
168       ;
169       return (HscNoRecomp pcs_tc new_details old_iface)
170       }}}}
171
172
173 hscRecomp ghci_mode dflags location maybe_checked_iface hst hit pcs_ch
174  = do   {
175         ; when (verbosity dflags >= 1) $
176                 hPutStrLn stderr "compilation IS required";
177
178           -- what target are we shooting for?
179         ; let toInterp = dopt_HscLang dflags == HscInterpreted
180
181             -------------------
182             -- PARSE
183             -------------------
184         ; maybe_parsed <- myParseModule dflags 
185                              (unJust "hscRecomp:hspp" (ml_hspp_file location))
186         ; case maybe_parsed of {
187              Nothing -> return (HscFail pcs_ch);
188              Just rdr_module -> do {
189         ; let this_mod = mkHomeModule (hsModuleName rdr_module)
190     
191             -------------------
192             -- RENAME
193             -------------------
194         ; (pcs_rn, maybe_rn_result) 
195              <- _scc_ "Rename" 
196                  renameModule dflags hit hst pcs_ch this_mod rdr_module
197         ; case maybe_rn_result of {
198              Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
199              Just (print_unqualified, (is_exported, new_iface, rn_hs_decls)) -> do {
200     
201             -- In interactive mode, we don't want to discard any top-level entities at
202             -- all (eg. do not inline them away during simplification), and retain them
203             -- all in the TypeEnv so they are available from the command line.
204             --
205             -- isGlobalName separates the user-defined top-level names from those
206             -- introduced by the type checker.
207         ; let dont_discard | ghci_mode == Interactive = isGlobalName
208                            | otherwise = is_exported
209
210             -------------------
211             -- TYPECHECK
212             -------------------
213         ; maybe_tc_result 
214             <- _scc_ "TypeCheck" typecheckModule dflags pcs_rn hst new_iface 
215                                              print_unqualified rn_hs_decls 
216         ; case maybe_tc_result of {
217              Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
218              Just (pcs_tc, tc_result) -> do {
219     
220         ; let env_tc = tc_env tc_result
221
222             -------------------
223             -- DESUGAR
224             -------------------
225         ; (ds_binds, ds_rules, foreign_stuff) 
226              <- _scc_ "DeSugar" 
227                 deSugar dflags pcs_tc hst this_mod print_unqualified tc_result
228
229             -------------------
230             -- SIMPLIFY, TIDY-CORE
231             -------------------
232           -- We grab the the unfoldings at this point.
233         ; (pcs_simpl, tidy_binds, orphan_rules)
234               <- simplThenTidy dflags pcs_tc hst this_mod dont_discard ds_binds ds_rules
235             
236             -------------------
237             -- BUILD THE NEW ModDetails AND ModIface
238             -------------------
239         ; let new_details = mkModDetails env_tc tidy_binds orphan_rules
240         ; final_iface <- _scc_ "MkFinalIface" 
241                           mkFinalIface ghci_mode dflags location 
242                                       maybe_checked_iface new_iface new_details
243
244             -------------------
245             -- CONVERT TO STG and COMPLETE CODE GENERATION
246             -------------------
247               -- Do saturation and convert to A-normal form
248         ; saturated <- coreSatPgm dflags tidy_binds
249
250         ; (maybe_stub_h_filename, maybe_stub_c_filename, maybe_bcos)
251              <- restOfCodeGeneration dflags toInterp this_mod
252                    (map ideclName (hsModuleImports rdr_module))
253                    foreign_stuff env_tc saturated
254                    hit (pcs_PIT pcs_simpl)       
255
256           -- and the answer is ...
257         ; return (HscRecomp pcs_simpl new_details final_iface
258                             maybe_stub_h_filename maybe_stub_c_filename
259                             maybe_bcos)
260           }}}}}}}
261
262
263
264 mkFinalIface ghci_mode dflags location maybe_old_iface new_iface new_details
265  = case completeIface maybe_old_iface new_iface new_details of
266       (new_iface, Nothing) -- no change in the interfacfe
267          -> do when (dopt Opt_D_dump_hi_diffs dflags)
268                     (printDump (text "INTERFACE UNCHANGED"))
269                dumpIfSet_dyn dflags Opt_D_dump_hi
270                              "UNCHANGED FINAL INTERFACE" (pprIface new_iface)
271                return new_iface
272       (new_iface, Just sdoc_diffs)
273          -> do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "INTERFACE HAS CHANGED" 
274                                     sdoc_diffs
275                dumpIfSet_dyn dflags Opt_D_dump_hi "NEW FINAL INTERFACE" 
276                                     (pprIface new_iface)
277                -- Write the interface file
278                when (ghci_mode /= Interactive) 
279                     (writeIface (unJust "hscRecomp:hi" (ml_hi_file location))
280                                 new_iface)
281                return new_iface
282
283
284 myParseModule dflags src_filename
285  = do --------------------------  Parser  ----------------
286       showPass dflags "Parser"
287       _scc_  "Parser" do
288
289       buf <- hGetStringBuffer True{-expand tabs-} src_filename
290
291       let glaexts | dopt Opt_GlasgowExts dflags = 1#
292                   | otherwise                   = 0#
293
294       case parseModule buf PState{ bol = 0#, atbol = 1#,
295                                    context = [], glasgow_exts = glaexts,
296                                    loc = mkSrcLoc (_PK_ src_filename) 1 } of {
297
298         PFailed err -> do { hPutStrLn stderr (showSDoc err);
299                             freeStringBuffer buf;
300                             return Nothing };
301
302         POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) -> do {
303
304       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
305       
306       dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
307                            (ppSourceStats False rdr_module) ;
308       
309       return (Just rdr_module)
310         -- ToDo: free the string buffer later.
311       }}
312
313
314 simplThenTidy dflags pcs hst this_mod dont_discard binds rules
315  = do -- Do main Core-language transformations ---------
316       -- _scc_     "Core2Core"
317       (simplified, orphan_rules) 
318          <- core2core dflags pcs hst dont_discard binds rules
319
320       -- Do the final tidy-up
321       (pcs', tidy_binds, tidy_orphan_rules) 
322          <- tidyCorePgm dflags this_mod pcs simplified orphan_rules
323       
324       return (pcs', tidy_binds, tidy_orphan_rules)
325
326
327 restOfCodeGeneration dflags toInterp this_mod imported_module_names
328                      foreign_stuff env_tc tidy_binds
329                      hit pit -- these last two for mapping ModNames to Modules
330  | toInterp
331  = do (bcos,itbl_env) 
332          <- byteCodeGen dflags tidy_binds local_tycons local_classes
333       return (Nothing, Nothing, Just (bcos,itbl_env))
334
335  | otherwise
336  = do
337       --------------------------  Convert to STG -------------------------------
338       (stg_binds, cost_centre_info) 
339                 <- _scc_ "CoreToStg"
340                     myCoreToStg dflags this_mod tidy_binds env_tc
341
342       --------------------------  Code generation ------------------------------
343       abstractC <- _scc_ "CodeGen"
344                     codeGen dflags this_mod imported_modules
345                            cost_centre_info fe_binders
346                            local_tycons stg_binds
347
348       --------------------------  Code output -------------------------------
349       (maybe_stub_h_name, maybe_stub_c_name)
350          <- codeOutput dflags this_mod local_tycons
351                        tidy_binds stg_binds
352                        c_code h_code abstractC
353
354       return (maybe_stub_h_name, maybe_stub_c_name, Nothing)
355  where
356     local_tycons     = typeEnvTyCons env_tc
357     local_classes    = typeEnvClasses env_tc
358     imported_modules = map mod_name_to_Module imported_module_names
359     (h_code,c_code,fe_binders) = foreign_stuff
360
361     mod_name_to_Module :: ModuleName -> Module
362     mod_name_to_Module nm
363        = let str_mi = case lookupModuleEnvByName hit nm of
364                           Just mi -> mi
365                           Nothing -> case lookupModuleEnvByName pit nm of
366                                         Just mi -> mi
367                                         Nothing -> barf nm
368          in  mi_module str_mi
369     barf nm = pprPanic "mod_name_to_Module: no hst or pst mapping for" 
370                        (ppr nm)
371
372
373 myCoreToStg dflags this_mod tidy_binds env_tc
374  = do 
375       () <- coreBindsSize tidy_binds `seq` return ()
376       -- TEMP: the above call zaps some space usage allocated by the
377       -- simplifier, which for reasons I don't understand, persists
378       -- thoroughout code generation
379
380       --let bcos = byteCodeGen dflags tidy_binds local_tycons local_classes
381
382       
383       stg_binds <- _scc_ "Core2Stg" coreToStg dflags this_mod tidy_binds
384
385       (stg_binds2, cost_centre_info)
386            <- _scc_ "Core2Stg" stg2stg dflags this_mod stg_binds
387
388       return (stg_binds2, cost_centre_info)
389    where
390       local_tycons  = typeEnvTyCons env_tc
391       local_classes = typeEnvClasses env_tc
392 \end{code}
393
394
395 %************************************************************************
396 %*                                                                      *
397 \subsection{Compiling an expression}
398 %*                                                                      *
399 %************************************************************************
400
401 \begin{code}
402 #ifdef GHCI
403 hscExpr
404   :: DynFlags
405   -> Bool                       -- True <=> wrap in 'print' to get a result of IO type
406   -> HomeSymbolTable    
407   -> HomeIfaceTable
408   -> PersistentCompilerState    -- IN: persistent compiler state
409   -> Module                     -- Context for compiling
410   -> String                     -- The expression
411   -> IO ( PersistentCompilerState, 
412           Maybe (UnlinkedBCOExpr, PrintUnqualified, Type) )
413
414 hscExpr dflags wrap_io hst hit pcs0 this_module expr
415    = do {
416         maybe_parsed <- hscParseExpr dflags expr;
417         case maybe_parsed of
418              Nothing -> return (pcs0, Nothing)
419              Just parsed_expr -> do {
420
421                 -- Rename it
422         (pcs1, maybe_renamed_expr) <- 
423                 renameExpr dflags hit hst pcs0 this_module parsed_expr;
424         case maybe_renamed_expr of
425                 Nothing -> return ({-WAS:pcs1-} pcs0, Nothing)
426                 Just (print_unqual, rn_expr) -> do {
427
428                 -- Typecheck it
429         maybe_tc_return
430            <- typecheckExpr dflags wrap_io pcs1 hst print_unqual this_module rn_expr;
431         case maybe_tc_return of {
432                 Nothing -> return ({-WAS:pcs1-} pcs0, Nothing);
433                 Just (pcs2, tc_expr, ty) -> do
434
435         let tidy_ty = tidyType emptyTidyEnv ty;
436
437                 -- Desugar it
438         ds_expr <- deSugarExpr dflags pcs2 hst this_module
439                         print_unqual tc_expr;
440         
441                 -- Simplify it
442         simpl_expr <- simplifyExpr dflags pcs2 hst ds_expr;
443
444                 -- Saturate it
445         sat_expr <- coreSatExpr dflags simpl_expr;
446
447                 -- ToDo: need to do SRTs?
448
449                 -- Convert to BCOs
450         bcos <- coreExprToBCOs dflags sat_expr
451
452         return (pcs2, Just (bcos, print_unqual, tidy_ty));
453      }}}}
454
455 hscParseExpr :: DynFlags -> String -> IO (Maybe RdrNameHsExpr)
456 hscParseExpr dflags str
457  = do --------------------------  Parser  ----------------
458       showPass dflags "Parser"
459       _scc_ "Parser" do
460
461       buf <- stringToStringBuffer str
462
463       let glaexts | dopt Opt_GlasgowExts dflags = 1#
464                   | otherwise             = 0#
465
466       case parseExpr buf PState{ bol = 0#, atbol = 1#,
467                                  context = [], glasgow_exts = glaexts,
468                                  loc = mkSrcLoc SLIT("<no file>") 0 } of {
469
470         PFailed err -> do { hPutStrLn stderr (showSDoc err);
471 --      Not yet implemented in <4.11                freeStringBuffer buf;
472                             return Nothing };
473
474         POk _ rdr_expr -> do {
475
476       --ToDo: can't free the string buffer until we've finished this
477       -- compilation sweep and all the identifiers have gone away.
478       --freeStringBuffer buf;
479       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_expr);
480       return (Just rdr_expr)
481       }}
482 #endif
483 \end{code}
484
485 %************************************************************************
486 %*                                                                      *
487 \subsection{Initial persistent state}
488 %*                                                                      *
489 %************************************************************************
490
491 \begin{code}
492 initPersistentCompilerState :: IO PersistentCompilerState
493 initPersistentCompilerState 
494   = do prs <- initPersistentRenamerState
495        return (
496         PCS { pcs_PIT   = emptyIfaceTable,
497               pcs_PTE   = wiredInThingEnv,
498               pcs_insts = emptyInstEnv,
499               pcs_rules = emptyRuleBase,
500               pcs_PRS   = prs
501             }
502         )
503
504 initPersistentRenamerState :: IO PersistentRenamerState
505   = do us <- mkSplitUniqSupply 'r'
506        return (
507         PRS { prsOrig  = NameSupply { nsUniqs = us,
508                                       nsNames = initOrigNames,
509                                       nsIPs   = emptyFM },
510               prsDecls   = (emptyNameEnv, 0),
511               prsInsts   = (emptyBag, 0),
512               prsRules   = (emptyBag, 0),
513               prsImpMods = emptyFM
514             }
515         )
516
517 initOrigNames :: FiniteMap (ModuleName,OccName) Name
518 initOrigNames 
519    = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
520      where
521         grab names = foldl add emptyFM names
522         add env name 
523            = addToFM env (moduleName (nameModule name), nameOccName name) name
524
525
526 initRules :: PackageRuleBase
527 initRules = emptyRuleBase
528 {- SHOULD BE (ish)
529             foldl add emptyVarEnv builtinRules
530           where
531             add env (name,rule) 
532               = extendRuleBase env name rule
533 -}
534 \end{code}