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