[project @ 2002-03-04 17:01:26 by simonmar]
[ghc-hetmet.git] / ghc / compiler / deSugar / DsForeign.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1998
3 %
4 \section[DsCCall]{Desugaring \tr{foreign} declarations}
5
6 Expanding out @foreign import@ and @foreign export@ declarations.
7
8 \begin{code}
9 module DsForeign ( dsForeigns ) where
10
11 #include "HsVersions.h"
12
13 import CoreSyn
14
15 import DsCCall          ( dsCCall, mkFCall, boxResult, unboxArg, resultWrapper )
16 import DsMonad
17
18 import HsSyn            ( ForeignDecl(..), ForeignExport(..),
19                           ForeignImport(..), CImportSpec(..) )
20 import TcHsSyn          ( TypecheckedForeignDecl )
21 import CoreUtils        ( exprType, mkInlineMe )
22 import Id               ( Id, idType, idName, mkVanillaGlobal, mkSysLocal,
23                           setInlinePragma )
24 import IdInfo           ( vanillaIdInfo )
25 import Literal          ( Literal(..) )
26 import Module           ( Module, moduleUserString )
27 import Name             ( mkGlobalName, nameModule, nameOccName, getOccString, 
28                           mkForeignExportOcc, isLocalName,
29                           NamedThing(..),
30                         )
31 import OccName          ( encodeFS )
32 import Type             ( repType, eqType )
33 import TcType           ( Type, mkFunTys, mkForAllTys, mkTyConApp,
34                           mkFunTy, applyTy, 
35                           tcSplitForAllTys, tcSplitFunTys, tcTyConAppArgs,
36                           tcSplitTyConApp_maybe, tcSplitAppTy,
37                           tcFunResultTy
38                         )
39
40 import ForeignCall      ( ForeignCall(..), CCallSpec(..), 
41                           Safety(..), playSafe,
42                           CExportSpec(..),
43                           CCallConv(..), ccallConvToInt,
44                           ccallConvAttribute
45                         )
46 import CStrings         ( CLabelString )
47 import TysWiredIn       ( addrTy, unitTy, stablePtrTyCon )
48 import TysPrim          ( addrPrimTy )
49 import PrelNames        ( hasKey, ioTyConKey, deRefStablePtrName, newStablePtrName,
50                           bindIOName, returnIOName
51                         )
52 import BasicTypes       ( Activation( NeverActive ) )
53 import ErrUtils         ( addShortWarnLocLine )
54 import Outputable
55 import Maybe            ( fromJust )
56 \end{code}
57
58 Desugaring of @foreign@ declarations is naturally split up into
59 parts, an @import@ and an @export@  part. A @foreign import@ 
60 declaration
61 \begin{verbatim}
62   foreign import cc nm f :: prim_args -> IO prim_res
63 \end{verbatim}
64 is the same as
65 \begin{verbatim}
66   f :: prim_args -> IO prim_res
67   f a1 ... an = _ccall_ nm cc a1 ... an
68 \end{verbatim}
69 so we reuse the desugaring code in @DsCCall@ to deal with these.
70
71 \begin{code}
72 type Binding = (Id, CoreExpr)   -- No rec/nonrec structure;
73                                 -- the occurrence analyser will sort it all out
74
75 dsForeigns :: Module
76            -> [TypecheckedForeignDecl] 
77            -> DsM ( [Id]                -- Foreign-exported binders; 
78                                         -- we have to generate code to register these
79                   , [Binding]
80                   , SDoc              -- Header file prototypes for
81                                       -- "foreign exported" functions.
82                   , SDoc              -- C stubs to use when calling
83                                       -- "foreign exported" functions.
84                   , [FAST_STRING]     -- headers that need to be included
85                                       -- into C code generated for this module
86                   )
87 dsForeigns mod_name fos
88   = foldlDs combine ([], [], empty, empty, []) fos
89  where
90   combine (acc_feb, acc_f, acc_h, acc_c, acc_header) 
91           (ForeignImport id _ spec depr loc)
92     = dsFImport mod_name id spec                   `thenDs` \(bs, h, c, hd) -> 
93       warnDepr depr loc                            `thenDs` \_              ->
94       returnDs (acc_feb, bs ++ acc_f, h $$ acc_h, c $$ acc_c, hd ++ acc_header)
95
96   combine (acc_feb, acc_f, acc_h, acc_c, acc_header) 
97           (ForeignExport id _ (CExport (CExportStatic ext_nm cconv)) depr loc)
98     = dsFExport mod_name id (idType id) 
99                 ext_nm cconv False                 `thenDs` \(h, c) ->
100       warnDepr depr loc                            `thenDs` \_              ->
101       returnDs (acc_feb, acc_f, h $$ acc_h, c $$ acc_c, acc_header)
102
103   warnDepr False _   = returnDs ()
104   warnDepr True  loc = dsWarn (addShortWarnLocLine loc msg)
105    where
106     msg = ptext SLIT("foreign declaration uses deprecated non-standard syntax")
107 \end{code}
108
109
110 %************************************************************************
111 %*                                                                      *
112 \subsection{Foreign import}
113 %*                                                                      *
114 %************************************************************************
115
116 Desugaring foreign imports is just the matter of creating a binding
117 that on its RHS unboxes its arguments, performs the external call
118 (using the @CCallOp@ primop), before boxing the result up and returning it.
119
120 However, we create a worker/wrapper pair, thus:
121
122         foreign import f :: Int -> IO Int
123 ==>
124         f x = IO ( \s -> case x of { I# x# ->
125                          case fw s x# of { (# s1, y# #) ->
126                          (# s1, I# y# #)}})
127
128         fw s x# = ccall f s x#
129
130 The strictness/CPR analyser won't do this automatically because it doesn't look
131 inside returned tuples; but inlining this wrapper is a Really Good Idea 
132 because it exposes the boxing to the call site.
133
134 \begin{code}
135 dsFImport :: Module
136           -> Id
137           -> ForeignImport
138           -> DsM ([Binding], SDoc, SDoc, [FAST_STRING])
139 dsFImport modName id (CImport cconv safety header lib spec)
140   = dsCImport modName id spec cconv safety        `thenDs` \(ids, h, c) ->
141     returnDs (ids, h, c, if _NULL_ header then [] else [header])
142   -- FIXME: the `lib' field is needed for .NET ILX generation when invoking
143   --        routines that are external to the .NET runtime, but GHC doesn't
144   --        support such calls yet; if `_NULL_ lib', the value was not given
145 dsFImport modName id (DNImport spec)
146   = dsFCall modName id (DNCall spec)              `thenDs` \(ids, h, c) ->
147     returnDs (ids, h, c, [])
148
149 dsCImport :: Module
150           -> Id
151           -> CImportSpec
152           -> CCallConv
153           -> Safety
154           -> DsM ([Binding], SDoc, SDoc)
155 dsCImport modName id (CLabel cid)       _     _
156  = ASSERT(fromJust resTy `eqType` addrPrimTy)    -- typechecker ensures this
157    returnDs ([(id, rhs)], empty, empty)
158  where
159    (resTy, foRhs) = resultWrapper (idType id)
160    rhs            = foRhs (mkLit (MachLabel cid))
161 dsCImport modName id (CFunction target) cconv safety
162   = dsFCall modName id (CCall (CCallSpec target cconv safety))
163 dsCImport modName id CWrapper           cconv _
164   = dsFExportDynamic modName id cconv
165 \end{code}
166
167
168 %************************************************************************
169 %*                                                                      *
170 \subsection{Foreign calls}
171 %*                                                                      *
172 %************************************************************************
173
174 \begin{code}
175 dsFCall mod_Name fn_id fcall
176   = let
177         ty                   = idType fn_id
178         (tvs, fun_ty)        = tcSplitForAllTys ty
179         (arg_tys, io_res_ty) = tcSplitFunTys fun_ty
180                 -- Must use tcSplit* functions because we want to 
181                 -- see that (IO t) in the corner
182     in
183     newSysLocalsDs arg_tys                      `thenDs` \ args ->
184     mapAndUnzipDs unboxArg (map Var args)       `thenDs` \ (val_args, arg_wrappers) ->
185
186     let
187         work_arg_ids  = [v | Var v <- val_args] -- All guaranteed to be vars
188
189         -- These are the ids we pass to boxResult, which are used to decide
190         -- whether to touch# an argument after the call (used to keep
191         -- ForeignObj#s live across a 'safe' foreign import).
192         maybe_arg_ids | unsafe_call fcall = work_arg_ids
193                       | otherwise         = []
194     in
195     boxResult maybe_arg_ids io_res_ty           `thenDs` \ (ccall_result_ty, res_wrapper) ->
196
197     getUniqueDs                                 `thenDs` \ ccall_uniq ->
198     getUniqueDs                                 `thenDs` \ work_uniq ->
199     let
200         -- Build the worker
201         worker_ty     = mkForAllTys tvs (mkFunTys (map idType work_arg_ids) ccall_result_ty)
202         the_ccall_app = mkFCall ccall_uniq fcall val_args ccall_result_ty
203         work_rhs      = mkLams tvs (mkLams work_arg_ids the_ccall_app)
204         work_id       = mkSysLocal (encodeFS SLIT("$wccall")) work_uniq worker_ty
205
206         -- Build the wrapper
207         work_app     = mkApps (mkVarApps (Var work_id) tvs) val_args
208         wrapper_body = foldr ($) (res_wrapper work_app) arg_wrappers
209         wrap_rhs     = mkInlineMe (mkLams (tvs ++ args) wrapper_body)
210     in
211     returnDs ([(work_id, work_rhs), (fn_id, wrap_rhs)], empty, empty)
212
213 unsafe_call (CCall (CCallSpec _ _ safety)) = playSafe safety
214 unsafe_call (DNCall _)                     = False
215 \end{code}
216
217
218 %************************************************************************
219 %*                                                                      *
220 \subsection{Foreign export}
221 %*                                                                      *
222 %************************************************************************
223
224 The function that does most of the work for `@foreign export@' declarations.
225 (see below for the boilerplate code a `@foreign export@' declaration expands
226  into.)
227
228 For each `@foreign export foo@' in a module M we generate:
229 \begin{itemize}
230 \item a C function `@foo@', which calls
231 \item a Haskell stub `@M.$ffoo@', which calls
232 \end{itemize}
233 the user-written Haskell function `@M.foo@'.
234
235 \begin{code}
236 dsFExport :: Module
237           -> Id                 -- Either the exported Id, 
238                                 -- or the foreign-export-dynamic constructor
239           -> Type               -- The type of the thing callable from C
240           -> CLabelString       -- The name to export to C land
241           -> CCallConv
242           -> Bool               -- True => foreign export dynamic
243                                 --         so invoke IO action that's hanging off 
244                                 --         the first argument's stable pointer
245           -> DsM ( SDoc         -- contents of Module_stub.h
246                  , SDoc         -- contents of Module_stub.c
247                  )
248
249 dsFExport mod_name fn_id ty ext_name cconv isDyn
250    = 
251      let
252         (tvs,sans_foralls)              = tcSplitForAllTys ty
253         (fe_arg_tys', orig_res_ty)      = tcSplitFunTys sans_foralls
254         -- We must use tcSplits here, because we want to see 
255         -- the (IO t) in the corner of the type!
256         fe_arg_tys | isDyn     = tail fe_arg_tys'
257                    | otherwise = fe_arg_tys'
258      in
259         -- Look at the result type of the exported function, orig_res_ty
260         -- If it's IO t, return         (t, True)
261         -- If it's plain t, return      (t, False)
262      (case tcSplitTyConApp_maybe orig_res_ty of
263         -- We must use tcSplit here so that we see the (IO t) in
264         -- the type.  [IO t is transparent to plain splitTyConApp.]
265
266         Just (ioTyCon, [res_ty])
267               -> ASSERT( ioTyCon `hasKey` ioTyConKey )
268                  -- The function already returns IO t
269                  returnDs (res_ty, True)
270
271         other -> -- The function returns t
272                  returnDs (orig_res_ty, False)
273      )
274                                         `thenDs` \ (res_ty,             -- t
275                                                     is_IO_res_ty) ->    -- Bool
276      getModuleDs
277                                         `thenDs` \ mod -> 
278      let
279         (h_stub, c_stub) 
280            = mkFExportCBits (moduleUserString mod) ext_name 
281                             (if isDyn then Nothing else Just fn_id)
282                             fe_arg_tys res_ty is_IO_res_ty cconv
283      in
284      returnDs (h_stub, c_stub)
285 \end{code}
286
287 @foreign export dynamic@ lets you dress up Haskell IO actions
288 of some fixed type behind an externally callable interface (i.e.,
289 as a C function pointer). Useful for callbacks and stuff.
290
291 \begin{verbatim}
292 foreign export dynamic f :: (Addr -> Int -> IO Int) -> IO Addr
293
294 -- Haskell-visible constructor, which is generated from the above:
295 -- SUP: No check for NULL from createAdjustor anymore???
296
297 f :: (Addr -> Int -> IO Int) -> IO Addr
298 f cback =
299    bindIO (newStablePtr cback)
300           (\StablePtr sp# -> IO (\s1# ->
301               case _ccall_ createAdjustor cconv sp# ``f_helper'' s1# of
302                  (# s2#, a# #) -> (# s2#, A# a# #)))
303
304 foreign export "f_helper" f_helper :: StablePtr (Addr -> Int -> IO Int) -> Addr -> Int -> IO Int
305 -- `special' foreign export that invokes the closure pointed to by the
306 -- first argument.
307 \end{verbatim}
308
309 \begin{code}
310 dsFExportDynamic :: Module
311                  -> Id
312                  -> CCallConv
313                  -> DsM ([Binding], SDoc, SDoc)
314 dsFExportDynamic mod_name id cconv
315   =  newSysLocalDs ty                                    `thenDs` \ fe_id ->
316      let 
317         -- hack: need to get at the name of the C stub we're about to generate.
318        fe_nm       = _PK_ (moduleUserString mod_name ++ "_" ++ toCName fe_id)
319      in
320      dsFExport mod_name id export_ty fe_nm cconv True   `thenDs` \ (h_code, c_code) ->
321      newSysLocalDs arg_ty                               `thenDs` \ cback ->
322      dsLookupGlobalValue newStablePtrName               `thenDs` \ newStablePtrId ->
323      let
324         mk_stbl_ptr_app    = mkApps (Var newStablePtrId) [ Type arg_ty, Var cback ]
325      in
326      dsLookupGlobalValue bindIOName                     `thenDs` \ bindIOId ->
327      newSysLocalDs (mkTyConApp stablePtrTyCon [arg_ty]) `thenDs` \ stbl_value ->
328      let
329       stbl_app cont ret_ty 
330         = mkApps (Var bindIOId)
331                  [ Type (mkTyConApp stablePtrTyCon [arg_ty])
332                  , Type ret_ty
333                  , mk_stbl_ptr_app
334                  , cont
335                  ]
336
337        {-
338         The arguments to the external function which will
339         create a little bit of (template) code on the fly
340         for allowing the (stable pointed) Haskell closure
341         to be entered using an external calling convention
342         (stdcall, ccall).
343        -}
344       adj_args      = [ mkIntLitInt (ccallConvToInt cconv)
345                       , Var stbl_value
346                       , mkLit (MachLabel fe_nm)
347                       ]
348         -- name of external entry point providing these services.
349         -- (probably in the RTS.) 
350       adjustor      = SLIT("createAdjustor")
351      in
352      dsCCall adjustor adj_args PlayRisky False io_res_ty        `thenDs` \ ccall_adj ->
353         -- PlayRisky: the adjustor doesn't allocate in the Haskell heap or do a callback
354      let ccall_adj_ty = exprType ccall_adj
355          ccall_io_adj = mkLams [stbl_value]                  $
356                         Note (Coerce io_res_ty ccall_adj_ty)
357                              ccall_adj
358          io_app = mkLams tvs     $
359                   mkLams [cback] $
360                   stbl_app ccall_io_adj res_ty
361          fed = (id `setInlinePragma` NeverActive, io_app)
362                 -- Never inline the f.e.d. function, because the litlit
363                 -- might not be in scope in other modules.
364      in
365      returnDs ([fed], h_code, c_code)
366
367  where
368   ty                    = idType id
369   (tvs,sans_foralls)    = tcSplitForAllTys ty
370   ([arg_ty], io_res_ty) = tcSplitFunTys sans_foralls
371   [res_ty]              = tcTyConAppArgs io_res_ty
372         -- Must use tcSplit* to see the (IO t), which is a newtype
373   export_ty             = mkFunTy (mkTyConApp stablePtrTyCon [arg_ty]) arg_ty
374
375 toCName :: Id -> String
376 toCName i = showSDoc (pprCode CStyle (ppr (idName i)))
377 \end{code}
378
379 %*
380 %
381 \subsection{Generating @foreign export@ stubs}
382 %
383 %*
384
385 For each @foreign export@ function, a C stub function is generated.
386 The C stub constructs the application of the exported Haskell function 
387 using the hugs/ghc rts invocation API.
388
389 \begin{code}
390 mkFExportCBits :: String
391                -> FAST_STRING
392                -> Maybe Id      -- Just==static, Nothing==dynamic
393                -> [Type] 
394                -> Type 
395                -> Bool          -- True <=> returns an IO type
396                -> CCallConv 
397                -> (SDoc, SDoc)
398 mkFExportCBits mod_nm c_nm maybe_target arg_htys res_hty is_IO_res_ty cc 
399  = (header_bits, c_bits)
400  where
401   -- Create up types and names for the real args
402   arg_cnames, arg_ctys :: [SDoc]
403   arg_cnames = mkCArgNames 1 arg_htys
404   arg_ctys   = map showStgType arg_htys
405
406   -- and also for auxiliary ones; the stable ptr in the dynamic case, and
407   -- a slot for the dummy return address in the dynamic + ccall case
408   extra_cnames_and_ctys
409      = case maybe_target of
410           Nothing -> [(text "the_stableptr", text "StgStablePtr")]
411           other   -> []
412        ++
413        case (maybe_target, cc) of
414           (Nothing, CCallConv) -> [(text "original_return_addr", text "void*")]
415           other                -> []
416
417   all_cnames_and_ctys :: [(SDoc, SDoc)]
418   all_cnames_and_ctys 
419      = extra_cnames_and_ctys ++ zip arg_cnames arg_ctys
420
421   -- stuff to do with the return type of the C function
422   res_hty_is_unit = res_hty `eqType` unitTy     -- Look through any newtypes
423
424   cResType | res_hty_is_unit = text "void"
425            | otherwise       = showStgType res_hty
426
427   -- Now we can cook up the prototype for the exported function.
428   pprCconv = case cc of
429                 CCallConv   -> empty
430                 StdCallConv -> text (ccallConvAttribute cc)
431
432   header_bits = ptext SLIT("extern") <+> fun_proto <> semi
433
434   fun_proto = cResType <+> pprCconv <+> ptext c_nm <>
435               parens (hsep (punctuate comma (map (\(nm,ty) -> ty <+> nm) 
436                                                  all_cnames_and_ctys)))
437
438   -- the target which will form the root of what we ask rts_evalIO to run
439   the_cfun
440      = case maybe_target of
441           Nothing    -> text "(StgClosure*)deRefStablePtr(the_stableptr)"
442           Just hs_fn -> ppr hs_fn <> text "_closure"
443
444   -- the expression we give to rts_evalIO
445   expr_to_run
446      = foldl appArg the_cfun (zip arg_cnames arg_htys)
447        where
448           appArg acc (arg_cname, arg_hty) 
449              = text "rts_apply" 
450                <> parens (acc <> comma <> mkHObj arg_hty <> parens arg_cname)
451
452   -- various other bits for inside the fn
453   declareResult = text "HaskellObj ret;"
454
455   return_what | res_hty_is_unit = empty
456               | otherwise       = parens (unpackHObj res_hty <> parens (text "ret"))
457
458   -- an extern decl for the fn being called
459   extern_decl
460      = case maybe_target of
461           Nothing -> empty
462           Just hs_fn -> text "extern StgClosure* " <> ppr hs_fn <> text "_closure" <> semi
463
464   -- finally, the whole darn thing
465   c_bits =
466     space $$
467     extern_decl $$
468     fun_proto  $$
469     vcat 
470      [ lbrace
471      ,   text "SchedulerStatus rc;"
472      ,   declareResult
473           -- create the application + perform it.
474      ,   text (if is_IO_res_ty then "rc=rts_evalIO" else "rc=rts_eval")
475          <> parens (expr_to_run <+> comma <> text "&ret")
476          <> semi
477      ,   text "rts_checkSchedStatus" <> parens (doubleQuotes (ptext c_nm)
478                                                 <> comma <> text "rc") <> semi
479      ,   text "return" <> return_what <> semi
480      , rbrace
481      ]
482
483
484 mkCArgNames :: Int -> [a] -> [SDoc]
485 mkCArgNames n as = zipWith (\ _ n -> text ('a':show n)) as [n..] 
486
487 mkHObj :: Type -> SDoc
488 mkHObj t = text "rts_mk" <> text (showFFIType t)
489
490 unpackHObj :: Type -> SDoc
491 unpackHObj t = text "rts_get" <> text (showFFIType t)
492
493 showStgType :: Type -> SDoc
494 showStgType t = text "Hs" <> text (showFFIType t)
495
496 showFFIType :: Type -> String
497 showFFIType t = getOccString (getName tc)
498  where
499   tc = case tcSplitTyConApp_maybe (repType t) of
500             Just (tc,_) -> tc
501             Nothing     -> pprPanic "showFFIType" (ppr t)
502 \end{code}