[project @ 2003-01-25 15:54:48 by wolfgang]
[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 fos
70   = foldlDs combine (ForeignStubs empty empty [] [], []) fos
71  where
72   combine (ForeignStubs acc_h acc_c acc_hdrs acc_feb, acc_f) 
73           (ForeignImport id _ spec depr loc)
74     = dsFImport id spec            `thenDs` \(bs, h, c, hd) -> 
75       warnDepr depr loc                            `thenDs` \_              ->
76       returnDs (ForeignStubs (h $$ acc_h) (c $$ acc_c) (hd ++ acc_hdrs) acc_feb, 
77                 bs ++ acc_f)
78
79   combine (ForeignStubs acc_h acc_c acc_hdrs acc_feb, acc_f) 
80           (ForeignExport id _ (CExport (CExportStatic ext_nm cconv)) depr loc)
81     = dsFExport id (idType id) 
82                 ext_nm cconv False                 `thenDs` \(h, c) ->
83       warnDepr depr loc                            `thenDs` \_              ->
84       returnDs (ForeignStubs (h $$ acc_h) (c $$ acc_c) acc_hdrs (id:acc_feb), 
85                 acc_f)
86
87   warnDepr False _   = returnDs ()
88   warnDepr True  loc = dsWarn (loc, msg)
89    where
90     msg = ptext SLIT("foreign declaration uses deprecated non-standard syntax")
91 \end{code}
92
93
94 %************************************************************************
95 %*                                                                      *
96 \subsection{Foreign import}
97 %*                                                                      *
98 %************************************************************************
99
100 Desugaring foreign imports is just the matter of creating a binding
101 that on its RHS unboxes its arguments, performs the external call
102 (using the @CCallOp@ primop), before boxing the result up and returning it.
103
104 However, we create a worker/wrapper pair, thus:
105
106         foreign import f :: Int -> IO Int
107 ==>
108         f x = IO ( \s -> case x of { I# x# ->
109                          case fw s x# of { (# s1, y# #) ->
110                          (# s1, I# y# #)}})
111
112         fw s x# = ccall f s x#
113
114 The strictness/CPR analyser won't do this automatically because it doesn't look
115 inside returned tuples; but inlining this wrapper is a Really Good Idea 
116 because it exposes the boxing to the call site.
117
118 \begin{code}
119 dsFImport :: Id
120           -> ForeignImport
121           -> DsM ([Binding], SDoc, SDoc, [FastString])
122 dsFImport id (CImport cconv safety header lib spec)
123   = dsCImport id spec cconv safety no_hdrs        `thenDs` \(ids, h, c) ->
124     returnDs (ids, h, c, if no_hdrs then [] else [header])
125   where
126     no_hdrs = nullFastString header
127
128   -- FIXME: the `lib' field is needed for .NET ILX generation when invoking
129   --        routines that are external to the .NET runtime, but GHC doesn't
130   --        support such calls yet; if `nullFastString lib', the value was not given
131 dsFImport id (DNImport spec)
132   = dsFCall id (DNCall spec) True {- No headers -} `thenDs` \(ids, h, c) ->
133     returnDs (ids, h, c, [])
134
135 dsCImport :: Id
136           -> CImportSpec
137           -> CCallConv
138           -> Safety
139           -> Bool       -- True <=> no headers in the f.i decl
140           -> DsM ([Binding], SDoc, SDoc)
141 dsCImport id (CLabel cid) _ _ no_hdrs
142  = ASSERT(fromJust resTy `eqType` addrPrimTy)    -- typechecker ensures this
143    returnDs ([(setImpInline no_hdrs id, rhs)], empty, empty)
144  where
145    (resTy, foRhs) = resultWrapper (idType id)
146    rhs            = foRhs (mkLit (MachLabel cid))
147 dsCImport id (CFunction target) cconv safety no_hdrs
148   = dsFCall id (CCall (CCallSpec target cconv safety)) no_hdrs
149 dsCImport id CWrapper cconv _ _
150   = dsFExportDynamic id cconv
151
152 setImpInline :: Bool    -- True <=> No #include headers 
153                         -- in the foreign import declaration
154              -> Id -> Id
155 -- If there is a #include header in the foreign import
156 -- we make the worker non-inlinable, because we currently
157 -- don't keep the #include stuff in the CCallId, and hence
158 -- it won't be visible in the importing module, which can be
159 -- fatal. 
160 -- (The #include stuff is just collected from the foreign import
161 --  decls in a module.)
162 -- If you want to do cross-module inlining of the c-calls themselves,
163 -- put the #include stuff in the package spec, not the foreign 
164 -- import decl.
165 setImpInline True  id = id
166 setImpInline False id = id `setInlinePragma` NeverActive
167 \end{code}
168
169
170 %************************************************************************
171 %*                                                                      *
172 \subsection{Foreign calls}
173 %*                                                                      *
174 %************************************************************************
175
176 \begin{code}
177 dsFCall fn_id fcall no_hdrs
178   = let
179         ty                   = idType fn_id
180         (tvs, fun_ty)        = tcSplitForAllTys ty
181         (arg_tys, io_res_ty) = tcSplitFunTys fun_ty
182                 -- Must use tcSplit* functions because we want to 
183                 -- see that (IO t) in the corner
184     in
185     newSysLocalsDs arg_tys                      `thenDs` \ args ->
186     mapAndUnzipDs unboxArg (map Var args)       `thenDs` \ (val_args, arg_wrappers) ->
187
188     let
189         work_arg_ids  = [v | Var v <- val_args] -- All guaranteed to be vars
190
191         -- These are the ids we pass to boxResult, which are used to decide
192         -- whether to touch# an argument after the call (used to keep
193         -- ForeignObj#s live across a 'safe' foreign import).
194         maybe_arg_ids | unsafe_call fcall = work_arg_ids
195                       | otherwise         = []
196     in
197     boxResult maybe_arg_ids io_res_ty           `thenDs` \ (ccall_result_ty, res_wrapper) ->
198
199     getUniqueDs                                 `thenDs` \ ccall_uniq ->
200     getUniqueDs                                 `thenDs` \ work_uniq ->
201     let
202         -- Build the worker
203         worker_ty     = mkForAllTys tvs (mkFunTys (map idType work_arg_ids) ccall_result_ty)
204         the_ccall_app = mkFCall ccall_uniq fcall val_args ccall_result_ty
205         work_rhs      = mkLams tvs (mkLams work_arg_ids the_ccall_app)
206         work_id       = setImpInline no_hdrs $  -- See comments with setImpInline
207                         mkSysLocal (encodeFS FSLIT("$wccall")) work_uniq worker_ty
208
209         -- Build the wrapper
210         work_app     = mkApps (mkVarApps (Var work_id) tvs) val_args
211         wrapper_body = foldr ($) (res_wrapper work_app) arg_wrappers
212         wrap_rhs     = mkInlineMe (mkLams (tvs ++ args) wrapper_body)
213     in
214     returnDs ([(work_id, work_rhs), (fn_id, wrap_rhs)], empty, empty)
215
216 unsafe_call (CCall (CCallSpec _ _ safety)) = playSafe safety
217 unsafe_call (DNCall _)                     = False
218 \end{code}
219
220
221 %************************************************************************
222 %*                                                                      *
223 \subsection{Foreign export}
224 %*                                                                      *
225 %************************************************************************
226
227 The function that does most of the work for `@foreign export@' declarations.
228 (see below for the boilerplate code a `@foreign export@' declaration expands
229  into.)
230
231 For each `@foreign export foo@' in a module M we generate:
232 \begin{itemize}
233 \item a C function `@foo@', which calls
234 \item a Haskell stub `@M.$ffoo@', which calls
235 \end{itemize}
236 the user-written Haskell function `@M.foo@'.
237
238 \begin{code}
239 dsFExport :: Id                 -- Either the exported Id, 
240                                 -- or the foreign-export-dynamic constructor
241           -> Type               -- The type of the thing callable from C
242           -> CLabelString       -- The name to export to C land
243           -> CCallConv
244           -> Bool               -- True => foreign export dynamic
245                                 --         so invoke IO action that's hanging off 
246                                 --         the first argument's stable pointer
247           -> DsM ( SDoc         -- contents of Module_stub.h
248                  , SDoc         -- contents of Module_stub.c
249                  )
250
251 dsFExport fn_id ty ext_name cconv isDyn
252    = 
253      let
254         (tvs,sans_foralls)              = tcSplitForAllTys ty
255         (fe_arg_tys', orig_res_ty)      = tcSplitFunTys sans_foralls
256         -- We must use tcSplits here, because we want to see 
257         -- the (IO t) in the corner of the type!
258         fe_arg_tys | isDyn     = tail fe_arg_tys'
259                    | otherwise = fe_arg_tys'
260      in
261         -- Look at the result type of the exported function, orig_res_ty
262         -- If it's IO t, return         (t, True)
263         -- If it's plain t, return      (t, False)
264      (case tcSplitTyConApp_maybe orig_res_ty of
265         -- We must use tcSplit here so that we see the (IO t) in
266         -- the type.  [IO t is transparent to plain splitTyConApp.]
267
268         Just (ioTyCon, [res_ty])
269               -> ASSERT( ioTyCon `hasKey` ioTyConKey )
270                  -- The function already returns IO t
271                  returnDs (res_ty, True)
272
273         other -> -- The function returns t
274                  returnDs (orig_res_ty, False)
275      )
276                                         `thenDs` \ (res_ty,             -- t
277                                                     is_IO_res_ty) ->    -- Bool
278      let
279         (h_stub, c_stub) 
280            = mkFExportCBits 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 :: Id
311                  -> CCallConv
312                  -> DsM ([Binding], SDoc, SDoc)
313 dsFExportDynamic id cconv
314   =  newSysLocalDs ty                            `thenDs` \ fe_id ->
315      getModuleDs                                `thenDs` \ mod_name -> 
316      let 
317         -- hack: need to get at the name of the C stub we're about to generate.
318        fe_nm       = mkFastString (moduleString mod_name ++ "_" ++ toCName fe_id)
319      in
320      dsFExport id export_ty fe_nm cconv True    `thenDs` \ (h_code, c_code) ->
321      newSysLocalDs arg_ty                       `thenDs` \ cback ->
322      dsLookupGlobalId newStablePtrName  `thenDs` \ newStablePtrId ->
323      let
324         mk_stbl_ptr_app    = mkApps (Var newStablePtrId) [ Type arg_ty, Var cback ]
325      in
326      dsLookupGlobalId 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      = FSLIT("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 :: FastString
391                -> Maybe Id      -- Just==static, Nothing==dynamic
392                -> [Type] 
393                -> Type 
394                -> Bool          -- True <=> returns an IO type
395                -> CCallConv 
396                -> (SDoc, SDoc)
397 mkFExportCBits c_nm maybe_target arg_htys res_hty is_IO_res_ty cc 
398  = (header_bits, c_bits)
399  where
400   -- Create up types and names for the real args
401   arg_cnames, arg_ctys :: [SDoc]
402   arg_cnames = mkCArgNames 1 arg_htys
403   arg_ctys   = map showStgType arg_htys
404
405   -- and also for auxiliary ones; the stable ptr in the dynamic case, and
406   -- a slot for the dummy return address in the dynamic + ccall case
407   extra_cnames_and_ctys
408      = case maybe_target of
409           Nothing -> [(text "the_stableptr", text "StgStablePtr")]
410           other   -> []
411        ++
412        case (maybe_target, cc) of
413           (Nothing, CCallConv) -> [(text "original_return_addr", text "void*")]
414           other                -> []
415
416   all_cnames_and_ctys :: [(SDoc, SDoc)]
417   all_cnames_and_ctys 
418      = extra_cnames_and_ctys ++ zip arg_cnames arg_ctys
419
420   -- stuff to do with the return type of the C function
421   res_hty_is_unit = res_hty `eqType` unitTy     -- Look through any newtypes
422
423   cResType | res_hty_is_unit = text "void"
424            | otherwise       = showStgType res_hty
425
426   -- Now we can cook up the prototype for the exported function.
427   pprCconv = case cc of
428                 CCallConv   -> empty
429                 StdCallConv -> text (ccallConvAttribute cc)
430
431   header_bits = ptext SLIT("extern") <+> fun_proto <> semi
432
433   fun_proto = cResType <+> pprCconv <+> ftext c_nm <>
434               parens (hsep (punctuate comma (map (\(nm,ty) -> ty <+> nm) 
435                                                  all_cnames_and_ctys)))
436
437   -- the target which will form the root of what we ask rts_evalIO to run
438   the_cfun
439      = case maybe_target of
440           Nothing    -> text "(StgClosure*)deRefStablePtr(the_stableptr)"
441           Just hs_fn -> char '&' <> ppr hs_fn <> text "_closure"
442
443   -- the expression we give to rts_evalIO
444   expr_to_run
445      = foldl appArg the_cfun (zip arg_cnames arg_htys)
446        where
447           appArg acc (arg_cname, arg_hty) 
448              = text "rts_apply" 
449                <> parens (acc <> comma <> mkHObj arg_hty <> parens arg_cname)
450
451   -- various other bits for inside the fn
452   declareResult = text "HaskellObj ret;"
453   declareCResult | res_hty_is_unit = empty
454                  | otherwise       = cResType <+> text "cret;"
455
456   assignCResult | res_hty_is_unit = empty
457                 | otherwise       =
458                         text "cret=" <> unpackHObj res_hty <> parens (text "ret") <> semi
459
460   -- an extern decl for the fn being called
461   extern_decl
462      = case maybe_target of
463           Nothing -> empty
464           Just hs_fn -> text "extern StgClosure " <> ppr hs_fn <> text "_closure" <> semi
465
466   -- finally, the whole darn thing
467   c_bits =
468     space $$
469     extern_decl $$
470     fun_proto  $$
471     vcat 
472      [ lbrace
473      ,   text "SchedulerStatus rc;"
474      ,   declareResult
475      ,   declareCResult
476      ,   text "rts_lock();"
477           -- create the application + perform it.
478      ,   text "rc=rts_evalIO" <> parens (
479                 text "rts_apply" <> parens (
480                     text "(HaskellObj)"
481                  <> text (if is_IO_res_ty 
482                                 then "runIO_closure" 
483                                 else "runNonIO_closure")
484                  <> comma
485                  <> expr_to_run
486                 ) <+> comma
487                <> text "&ret"
488              ) <> semi
489      ,   text "rts_checkSchedStatus" <> parens (doubleQuotes (ftext c_nm)
490                                                 <> comma <> text "rc") <> semi
491      ,   assignCResult
492      ,   text "rts_unlock();"
493      ,   if res_hty_is_unit then empty
494             else text "return cret;"
495      , rbrace
496      ]
497
498
499 mkCArgNames :: Int -> [a] -> [SDoc]
500 mkCArgNames n as = zipWith (\ _ n -> text ('a':show n)) as [n..] 
501
502 mkHObj :: Type -> SDoc
503 mkHObj t = text "rts_mk" <> text (showFFIType t)
504
505 unpackHObj :: Type -> SDoc
506 unpackHObj t = text "rts_get" <> text (showFFIType t)
507
508 showStgType :: Type -> SDoc
509 showStgType t = text "Hs" <> text (showFFIType t)
510
511 showFFIType :: Type -> String
512 showFFIType t = getOccString (getName tc)
513  where
514   tc = case tcSplitTyConApp_maybe (repType t) of
515             Just (tc,_) -> tc
516             Nothing     -> pprPanic "showFFIType" (ppr t)
517 \end{code}