[project @ 1998-03-19 17:44:26 by simonpj]
[ghc-hetmet.git] / ghc / compiler / main / MkIface.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1996
3 %
4 \section[MkIface]{Print an interface for a module}
5
6 \begin{code}
7 module MkIface (
8         startIface, endIface,
9         ifaceMain,
10         ifaceDecls
11     ) where
12
13 #include "HsVersions.h"
14
15 import IO               ( Handle, hPutStr, openFile, 
16                           hClose, hPutStrLn, IOMode(..) )
17
18 import HsSyn
19 import RdrHsSyn         ( RdrName(..) )
20 import RnHsSyn          ( RenamedHsModule )
21 import BasicTypes       ( Fixity(..), FixityDirection(..), NewOrData(..), IfaceFlavour(..),
22                           pprModule
23                         )
24 import RnMonad
25 import RnEnv            ( availName, ifaceFlavour )
26
27 import TcInstUtil       ( InstInfo(..) )
28 import WorkWrap         ( getWorkerIdAndCons )
29
30 import CmdLineOpts
31 import Id               ( idType, dataConRawArgTys, dataConFieldLabels, 
32                           getIdInfo, getInlinePragma, omitIfaceSigForId,
33                           dataConStrictMarks, StrictnessMark(..), 
34                           IdSet, idSetToList, unionIdSets, unitIdSet, minusIdSet, 
35                           isEmptyIdSet, elementOfIdSet, emptyIdSet, mkIdSet,
36                           pprId,
37                           Id
38
39                         )
40 import IdInfo           ( IdInfo, StrictnessInfo, ArityInfo, 
41                           arityInfo, ppArityInfo, strictnessInfo, ppStrictnessInfo, 
42                           bottomIsGuaranteed, workerExists, 
43                         )
44 import PragmaInfo       ( PragmaInfo(..) )
45 import CoreSyn          ( CoreExpr, CoreBinding, GenCoreExpr, GenCoreBinding(..) )
46 import CoreUnfold       ( calcUnfoldingGuidance, UnfoldingGuidance(..), Unfolding )
47 import FreeVars         ( addExprFVs )
48 import Name             ( isLocallyDefined, isWiredInName, modAndOcc, nameModule, pprOccName,
49                           OccName, occNameString, nameOccName, nameString, isExported,
50                           Name {-instance NamedThing-}, Provenance, NamedThing(..)
51                         )
52 import TyCon            ( TyCon, getSynTyConDefn, isSynTyCon, isNewTyCon, isAlgTyCon,
53                           tyConTheta, tyConTyVars, tyConDataCons
54                         )
55 import Class            ( Class, classBigSig )
56 import FieldLabel       ( fieldLabelName, fieldLabelType )
57 import Type             ( mkSigmaTy, splitSigmaTy, mkDictTy,
58                           mkTyVarTys, Type, ThetaType
59                         )
60
61 import PprEnv           -- not sure how much...
62 import PprType
63 import PprCore          ( pprIfaceUnfolding )
64
65 import Bag              ( bagToList, isEmptyBag )
66 import Maybes           ( catMaybes, maybeToBool )
67 import FiniteMap        ( emptyFM, addToFM, addToFM_C, lookupFM, fmToList, eltsFM, FiniteMap )
68 import UniqFM           ( UniqFM, lookupUFM, listToUFM )
69 import Util             ( sortLt, zipWithEqual, zipWith3Equal, mapAccumL )
70 import Outputable
71 \end{code}
72
73 We have a function @startIface@ to open the output file and put
74 (something like) ``interface Foo'' in it.  It gives back a handle
75 for subsequent additions to the interface file.
76
77 We then have one-function-per-block-of-interface-stuff, e.g.,
78 @ifaceExportList@ produces the @__exports__@ section; it appends
79 to the handle provided by @startIface@.
80
81 \begin{code}
82 startIface  :: Module
83             -> IO (Maybe Handle) -- Nothing <=> don't do an interface
84
85 ifaceMain   :: Maybe Handle
86             -> InterfaceDetails
87             -> IO ()
88
89
90 ifaceDecls :: Maybe Handle
91            -> [TyCon] -> [Class]
92            -> Bag InstInfo 
93            -> [Id]              -- Ids used at code-gen time; they have better pragma info!
94            -> [CoreBinding]     -- In dependency order, later depend on earlier
95            -> IO ()
96
97 endIface    :: Maybe Handle -> IO ()
98 \end{code}
99
100 \begin{code}
101 startIface mod
102   = case opt_ProduceHi of
103       Nothing -> return Nothing -- not producing any .hi file
104       Just fn -> do
105         if_hdl <- openFile fn WriteMode
106         hPutStrLn if_hdl ("_interface_ "++ _UNPK_ mod ++ ' ':show (PROJECTVERSION :: Int))
107         return (Just if_hdl)
108
109 endIface Nothing        = return ()
110 endIface (Just if_hdl)  = hPutStr if_hdl "\n" >> hClose if_hdl
111 \end{code}
112
113
114 \begin{code}
115 ifaceMain Nothing iface_stuff = return ()
116 ifaceMain (Just if_hdl)
117           (import_usages, ExportEnv avails fixities, instance_modules)
118   =
119     ifaceInstanceModules        if_hdl instance_modules         >>
120     ifaceUsages                 if_hdl import_usages            >>
121     ifaceExports                if_hdl avails                   >>
122     ifaceFixities               if_hdl fixities                 >>
123     return ()
124
125 ifaceDecls Nothing tycons classes inst_info final_ids simplified = return ()
126 ifaceDecls (Just hdl)
127            tycons classes
128            inst_infos
129            final_ids binds
130   | null_decls = return ()               
131         --  You could have a module with just (re-)exports/instances in it
132   | otherwise
133   = ifaceInstances hdl inst_infos               >>= \ needed_ids ->
134     hPutStr hdl "_declarations_\n"              >>
135     ifaceClasses hdl classes                    >>
136     ifaceTyCons hdl tycons                      >>
137     ifaceBinds hdl needed_ids final_ids binds   >>
138     return ()
139   where
140      null_decls = null binds      && 
141                   null tycons     &&
142                   null classes    && 
143                   isEmptyBag inst_infos
144 \end{code}
145
146 \begin{code}
147 ifaceUsages if_hdl import_usages
148   = hPutStr if_hdl "_usages_\n"   >>
149     hPutCol if_hdl upp_uses (sortLt lt_imp_vers import_usages)
150   where
151     upp_uses (m, hif, mv, whats_imported)
152       = hsep [pprModule m, pp_hif hif, int mv, ptext SLIT("::"),
153               upp_import_versions whats_imported
154         ] <> semi
155
156         -- Importing the whole module is indicated by an empty list
157     upp_import_versions Everything = empty
158
159         -- For imported versions we do print the version number
160     upp_import_versions (Specifically nvs)
161       = hsep [ hsep [ppr_unqual_name n, int v] | (n,v) <- sort_versions nvs ]
162
163 ifaceInstanceModules if_hdl [] = return ()
164 ifaceInstanceModules if_hdl imods
165   = hPutStr if_hdl "_instance_modules_\n" >>
166     printForIface if_hdl (hsep (map ptext (sortLt (<) imods))) >>
167     hPutStr if_hdl "\n"
168
169 ifaceExports if_hdl [] = return ()
170 ifaceExports if_hdl avails
171   = hPutStr if_hdl "_exports_\n"                        >>
172     hPutCol if_hdl do_one_module (fmToList export_fm)
173   where
174         -- Sort them into groups by module
175     export_fm :: FiniteMap Module [AvailInfo]
176     export_fm = foldr insert emptyFM avails
177
178     insert NotAvailable efm = efm
179     insert avail efm = addToFM_C (++) efm mod [avail] 
180                      where
181                        mod = nameModule (availName avail)
182
183         -- Print one module's worth of stuff
184     do_one_module (mod_name, avails@(avail1:_))
185         = hsep [pp_hif (ifaceFlavour (availName avail1)), 
186                 pprModule mod_name,
187                 hsep (map upp_avail (sortLt lt_avail avails))
188           ] <> semi
189
190 -- The "!" indicates that the exported things came from a hi-boot interface 
191 pp_hif HiFile     = empty
192 pp_hif HiBootFile = char '!'
193
194 ifaceFixities if_hdl [] = return ()
195 ifaceFixities if_hdl fixities 
196   = hPutStr if_hdl "_fixities_\n"               >>
197     hPutCol if_hdl upp_fixity fixities
198 \end{code}                       
199
200 %************************************************************************
201 %*                                                                      *
202 \subsection{Instance declarations}
203 %*                                                                      *
204 %************************************************************************
205
206
207 \begin{code}                     
208 ifaceInstances :: Handle -> Bag InstInfo -> IO IdSet            -- The IdSet is the needed dfuns
209 ifaceInstances if_hdl inst_infos
210   | null togo_insts = return emptyIdSet          
211   | otherwise       = hPutStr if_hdl "_instances_\n" >>
212                       hPutCol if_hdl pp_inst (sortLt lt_inst togo_insts) >>
213                       return needed_ids
214   where                          
215     togo_insts  = filter is_togo_inst (bagToList inst_infos)
216     needed_ids  = mkIdSet [dfun_id | InstInfo _ _ _ _ _ dfun_id _ _ _ <- togo_insts]
217     is_togo_inst (InstInfo _ _ _ _ _ dfun_id _ _ _) = isLocallyDefined dfun_id
218                                  
219     -------                      
220     lt_inst (InstInfo _ _ _ _ _ dfun_id1 _ _ _)
221             (InstInfo _ _ _ _ _ dfun_id2 _ _ _)
222       = getOccName dfun_id1 < getOccName dfun_id2
223         -- The dfuns are assigned names df1, df2, etc, in order of original textual
224         -- occurrence, and this makes as good a sort order as any
225
226     -------                      
227     pp_inst (InstInfo clas tvs tys theta _ dfun_id _ _ _)
228       = let                      
229             forall_ty     = mkSigmaTy tvs theta (mkDictTy clas tys)
230             renumbered_ty = nmbrGlobalType forall_ty
231         in                       
232         hcat [ptext SLIT("instance "), pprType renumbered_ty, 
233                     ptext SLIT(" = "), ppr_unqual_name dfun_id, semi]
234 \end{code}
235
236
237 %************************************************************************
238 %*                                                                      *
239 \subsection{Printing values}
240 %*                                                                      *
241 %************************************************************************
242
243 \begin{code}
244 ifaceId :: (Id -> IdInfo)               -- This function "knows" the extra info added
245                                         -- by the STG passes.  Sigh
246
247             -> IdSet                    -- Set of Ids that are needed by earlier interface
248                                         -- file emissions.  If the Id isn't in this set, and isn't
249                                         -- exported, there's no need to emit anything
250             -> Bool                     -- True <=> recursive, so don't print unfolding
251             -> Id
252             -> CoreExpr                 -- The Id's right hand side
253             -> Maybe (SDoc, IdSet)      -- The emitted stuff, plus a possibly-augmented set of needed Ids
254
255 ifaceId get_idinfo needed_ids is_rec id rhs
256   | not (id `elementOfIdSet` needed_ids ||              -- Needed [no id in needed_ids has omitIfaceSigForId]
257          (isExported id && not (omitIfaceSigForId id))) -- or exported and not to be omitted
258   = Nothing             -- Well, that was easy!
259
260 ifaceId get_idinfo needed_ids is_rec id rhs
261   = Just (hsep [sig_pretty, pp_double_semi, prag_pretty], new_needed_ids)
262   where
263     pp_double_semi = ptext SLIT(";;")
264     idinfo         = get_idinfo id
265     inline_pragma  = getInlinePragma id 
266
267     ty_pretty  = pprType (nmbrGlobalType (idType id))
268     sig_pretty = hcat [ppr (getOccName id), ptext SLIT(" _:_ "), ty_pretty]
269
270     prag_pretty 
271      | opt_OmitInterfacePragmas = empty
272      | otherwise                = hsep [arity_pretty, strict_pretty, unfold_pretty, pp_double_semi]
273
274     ------------  Arity  --------------
275     arity_pretty  = ppArityInfo (arityInfo idinfo)
276
277     ------------  Strictness  --------------
278     strict_info   = strictnessInfo idinfo
279     has_worker    = workerExists strict_info
280     strict_pretty = ppStrictnessInfo strict_info <+> wrkr_pretty
281
282     wrkr_pretty | not has_worker = empty
283                 | null con_list  = pprId work_id
284                 | otherwise      = pprId work_id <+> 
285                                    braces (hsep (map (pprId) con_list))
286
287     (work_id, wrapper_cons) = getWorkerIdAndCons id rhs
288     con_list               = idSetToList wrapper_cons
289
290     ------------  Unfolding  --------------
291     unfold_pretty | show_unfold = hsep [ptext unfold_herald, pprIfaceUnfolding rhs]
292                   | otherwise   = empty
293
294     unfold_herald = case inline_pragma of
295                         IMustBeINLINEd   -> SLIT("_U_")
296                         IWantToBeINLINEd -> SLIT("_U_")
297                         other            -> SLIT("_u_")
298
299     show_unfold = not implicit_unfolding &&             -- Not unnecessary
300                   not dodgy_unfolding                   -- Not dangerous
301
302     implicit_unfolding = has_worker ||
303                          bottomIsGuaranteed strict_info
304
305     dodgy_unfolding = case guidance of                  -- True <=> too big to show, or the Inline pragma
306                         UnfoldNever -> True             -- says it shouldn't be inlined
307                         other       -> False
308
309     guidance    = calcUnfoldingGuidance inline_pragma
310                                         opt_InterfaceUnfoldThreshold
311                                         rhs
312
313     
314     ------------  Extra free Ids  --------------
315     new_needed_ids = (needed_ids `minusIdSet` unitIdSet id)     `unionIdSets` 
316                      extra_ids
317
318     extra_ids | opt_OmitInterfacePragmas = emptyIdSet
319               | otherwise                = worker_ids   `unionIdSets`
320                                            unfold_ids
321
322     worker_ids | has_worker = unitIdSet work_id
323                | otherwise  = emptyIdSet
324
325     unfold_ids | show_unfold = free_vars
326                | otherwise   = emptyIdSet
327                              where
328                                (_,free_vars) = addExprFVs interesting emptyIdSet rhs
329                                interesting bound id = isLocallyDefined id &&
330                                                       not (id `elementOfIdSet` bound) &&
331                                                       not (omitIfaceSigForId id)
332 \end{code}
333
334 \begin{code}
335 ifaceBinds :: Handle
336            -> IdSet             -- These Ids are needed already
337            -> [Id]              -- Ids used at code-gen time; they have better pragma info!
338            -> [CoreBinding]     -- In dependency order, later depend on earlier
339            -> IO ()
340
341 ifaceBinds hdl needed_ids final_ids binds
342   = mapIO (printForIface hdl) pretties >>
343     hPutStr hdl "\n"
344   where
345     final_id_map  = listToUFM [(id,id) | id <- final_ids]
346     get_idinfo id = case lookupUFM final_id_map id of
347                         Just id' -> getIdInfo id'
348                         Nothing  -> pprTrace "ifaceBinds not found:" (ppr id) $
349                                     getIdInfo id
350
351     pretties = go needed_ids (reverse binds)    -- Reverse so that later things will 
352                                                 -- provoke earlier ones to be emitted
353     go needed [] = if not (isEmptyIdSet needed) then
354                         pprTrace "ifaceBinds: free vars:" 
355                                   (sep (map ppr (idSetToList needed))) $
356                         []
357                    else
358                         []
359
360     go needed (NonRec id rhs : binds)
361         = case ifaceId get_idinfo needed False id rhs of
362                 Nothing                -> go needed binds
363                 Just (pretty, needed') -> pretty : go needed' binds
364
365         -- Recursive groups are a bit more of a pain.  We may only need one to
366         -- start with, but it may call out the next one, and so on.  So we
367         -- have to look for a fixed point.
368     go needed (Rec pairs : binds)
369         = pretties ++ go needed'' binds
370         where
371           (needed', pretties) = go_rec needed pairs
372           needed'' = needed' `minusIdSet` mkIdSet (map fst pairs)
373                 -- Later ones may spuriously cause earlier ones to be "needed" again
374
375     go_rec :: IdSet -> [(Id,CoreExpr)] -> (IdSet, [SDoc])
376     go_rec needed pairs
377         | null pretties = (needed, [])
378         | otherwise     = (final_needed, more_pretties ++ pretties)
379         where
380           reduced_pairs                 = [pair | (pair,Nothing) <- pairs `zip` maybes]
381           pretties                      = catMaybes maybes
382           (needed', maybes)             = mapAccumL do_one needed pairs
383           (final_needed, more_pretties) = go_rec needed' reduced_pairs
384
385           do_one needed (id,rhs) = case ifaceId get_idinfo needed True id rhs of
386                                         Nothing                -> (needed,  Nothing)
387                                         Just (pretty, needed') -> (needed', Just pretty)
388 \end{code}
389
390
391 %************************************************************************
392 %*                                                                      *
393 \subsection{Random small things}
394 %*                                                                      *
395 %************************************************************************
396
397 \begin{code}
398 ifaceTyCons hdl tycons   = hPutCol hdl upp_tycon (sortLt (<) (filter (for_iface_name . getName) tycons ))
399 ifaceClasses hdl classes = hPutCol hdl upp_class (sortLt (<) (filter (for_iface_name . getName) classes))
400
401 for_iface_name name = isLocallyDefined name && 
402                       not (isWiredInName name)
403
404 upp_tycon tycon = ifaceTyCon tycon
405 upp_class clas  = ifaceClass clas
406 \end{code}
407
408
409 \begin{code}
410 ifaceTyCon :: TyCon -> SDoc
411 ifaceTyCon tycon
412   | isSynTyCon tycon
413   = hsep [ ptext SLIT("type"),
414            ppr (getName tycon),
415            pprTyVarBndrs tyvars,
416            ptext SLIT("="),
417            ppr ty,
418            semi
419     ]
420   where
421     (tyvars, ty) = getSynTyConDefn tycon
422
423 ifaceTyCon tycon
424   | isAlgTyCon tycon
425   = hsep [ ptext keyword,
426            ppr_decl_context (tyConTheta tycon),
427            ppr (getName tycon),
428            pprTyVarBndrs (tyConTyVars tycon),
429            ptext SLIT("="),
430            hsep (punctuate (ptext SLIT(" | ")) (map ppr_con (tyConDataCons tycon))),
431            semi
432     ]
433   where
434     keyword | isNewTyCon tycon = SLIT("newtype")
435             | otherwise        = SLIT("data")
436
437     ppr_con data_con 
438         | null field_labels
439         = hsep [ ppr name,
440                   hsep (map ppr_arg_ty (strict_marks `zip` arg_tys))
441                 ]
442
443         | otherwise
444         = hsep [ ppr name,
445                   braces $ hsep $ punctuate comma (map ppr_field (strict_marks `zip` field_labels))
446                 ]
447           where
448            field_labels   = dataConFieldLabels data_con
449            arg_tys        = dataConRawArgTys   data_con
450            strict_marks   = dataConStrictMarks data_con
451            name           = getName            data_con
452
453     ppr_arg_ty (strict_mark, ty) = ppr_strict_mark strict_mark <> pprParendType ty
454
455     ppr_strict_mark NotMarkedStrict = empty
456     ppr_strict_mark MarkedStrict    = ptext SLIT("! ")
457                                 -- The extra space helps the lexical analyser that lexes
458                                 -- interface files; it doesn't make the rigid operator/identifier
459                                 -- distinction, so "!a" is a valid identifier so far as it is concerned
460
461     ppr_field (strict_mark, field_label)
462         = hsep [ ppr (fieldLabelName field_label),
463                   ptext SLIT("::"),
464                   ppr_strict_mark strict_mark <> pprParendType (fieldLabelType field_label)
465                 ]
466
467 ifaceTyCon tycon
468   = pprPanic "pprIfaceTyDecl" (ppr tycon)
469
470 ifaceClass clas
471   = hsep [ptext SLIT("class"),
472            ppr_decl_context sc_theta,
473            ppr clas,                    -- Print the name
474            pprTyVarBndrs clas_tyvars,
475            pp_ops,
476            semi
477           ]
478    where
479      (clas_tyvars, sc_theta, _, sel_ids, defms) = classBigSig clas
480
481      pp_ops | null sel_ids  = empty
482             | otherwise = hsep [ptext SLIT("where"),
483                                  braces (hsep (punctuate semi (zipWith ppr_classop sel_ids defms)))
484                           ]
485
486      ppr_classop sel_id maybe_defm
487         = ASSERT( sel_tyvars == clas_tyvars)
488           hsep [ppr (getOccName sel_id),
489                 if maybeToBool maybe_defm then equals else empty,
490                 ptext SLIT("::"),
491                 ppr op_ty
492           ]
493         where
494           (sel_tyvars, _, op_ty) = splitSigmaTy (idType sel_id)
495
496 ppr_decl_context :: ThetaType -> SDoc
497 ppr_decl_context [] = empty
498 ppr_decl_context theta
499   = braces (hsep (punctuate comma (map (ppr_dict) theta)))
500     <> 
501     ptext SLIT(" =>")
502   where
503     ppr_dict (clas,tys) = ppr clas <+> hsep (map pprParendType tys)
504 \end{code}
505
506 %************************************************************************
507 %*                                                                      *
508 \subsection{Random small things}
509 %*                                                                      *
510 %************************************************************************
511
512 When printing export lists, we print like this:
513         Avail   f               f
514         AvailTC C [C, x, y]     C(x,y)
515         AvailTC C [x, y]        C!(x,y)         -- Exporting x, y but not C
516
517 \begin{code}
518 upp_avail NotAvailable      = empty
519 upp_avail (Avail name)      = upp_occname (getOccName name)
520 upp_avail (AvailTC name []) = empty
521 upp_avail (AvailTC name ns) = hcat [upp_occname (getOccName name), bang, upp_export ns']
522                             where
523                               bang | name `elem` ns = empty
524                                    | otherwise      = char '|'
525                               ns' = filter (/= name) ns
526
527 upp_export []    = empty
528 upp_export names = parens (hsep (map (upp_occname . getOccName) names)) 
529
530 upp_fixity (occ, fixity) = hcat [ppr fixity, space, upp_occname occ, semi]
531
532 ppr_unqual_name :: NamedThing a => a -> SDoc            -- Just its occurrence name
533 ppr_unqual_name name = upp_occname (getOccName name)
534
535 upp_occname :: OccName -> SDoc
536 upp_occname occ = ptext (occNameString occ)
537 \end{code}
538
539
540 %************************************************************************
541 %*                                                                      *
542 \subsection{Comparisons
543 %*                                                                      *
544 %************************************************************************
545                                  
546
547 The various sorts above simply prevent unnecessary "wobbling" when
548 things change that don't have to.  We therefore compare lexically, not
549 by unique
550
551 \begin{code}
552 lt_avail :: AvailInfo -> AvailInfo -> Bool
553
554 a1 `lt_avail` a2 = availName a1 `lt_name` availName a2
555
556 lt_name :: Name -> Name -> Bool
557 n1 `lt_name` n2 = modAndOcc n1 < modAndOcc n2
558
559 lt_lexical :: NamedThing a => a -> a -> Bool
560 lt_lexical a1 a2 = getName a1 `lt_name` getName a2
561
562 lt_imp_vers :: ImportVersion a -> ImportVersion a -> Bool
563 lt_imp_vers (m1,_,_,_) (m2,_,_,_) = m1 < m2
564
565 sort_versions vs = sortLt lt_vers vs
566
567 lt_vers :: LocalVersion Name -> LocalVersion Name -> Bool
568 lt_vers (n1,v1) (n2,v2) = n1 `lt_name` n2
569 \end{code}
570
571
572 \begin{code}
573 hPutCol :: Handle 
574         -> (a -> SDoc)
575         -> [a]
576         -> IO ()
577 hPutCol hdl fmt xs = mapIO (printForIface hdl . fmt) xs
578
579 mapIO :: (a -> IO b) -> [a] -> IO ()
580 mapIO f []     = return ()
581 mapIO f (x:xs) = f x >> mapIO f xs
582 \end{code}