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