Debian Codegraph @

c2hs/gen/GenBind.hs

raw symbols SCIP
1 -- C->Haskell Compiler: binding generator
2 --
3 -- Author : Manuel M T Chakravarty
4 -- Created: 17 August 99
5 --
6 -- Version $Revision: 1.3 $ from $Date: 2005/10/17 20:41:30 $
7 --
8 -- Copyright (c) [1999..2003] Manuel M T Chakravarty
9 --
10 -- This file is free software; you can redistribute it and/or modify
11 -- it under the terms of the GNU General Public License as published by
12 -- the Free Software Foundation; either version 2 of the License, or
13 -- (at your option) any later version.
14 --
15 -- This file is distributed in the hope that it will be useful,
16 -- but WITHOUT ANY WARRANTY; without even the implied warranty of
17 -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 -- GNU General Public License for more details.
19 --
20 --- DESCRIPTION ---------------------------------------------------------------
21 --
22 -- Module implementing the expansion of the binding hooks.
23 --
24 --- DOCU ----------------------------------------------------------------------
25 --
26 -- language: Haskell 98
27 --
28 -- * If there is an error in one binding hook, it is skipped and the next one
29 -- is processed (to collect as many errors as possible). However, if at
30 -- least one error occurred, the expansion of binding hooks ends in a fatal
31 -- exception.
32 --
33 -- * `CST' exceptions are used to back off a binding hook as soon as an error
34 -- is encountered while it is processed.
35 --
36 -- Mapping of C types to Haskell FFI types:
37 -- ----------------------------------------
38 --
39 -- The following defines the mapping for basic types. If the type specifer
40 -- is missing, it is taken to be `int'. In the following, elements enclosed
41 -- in square brackets are optional.
42 --
43 -- void -> ()
44 -- char -> CChar
45 -- unsigned char -> CUChar
46 -- signed char -> CShort
47 -- signed -> CInt
48 -- [signed] int -> CInt
49 -- [signed] short [int] -> CSInt
50 -- [signed] long [int] -> CLong
51 -- [signed] long long [int] -> CLLong
52 -- unsigned [int] -> CUInt
53 -- unsigned short [int] -> CUShort
54 -- unsigned long [int] -> CULong
55 -- unsigned long long [int] -> CULLong
56 -- float -> CFloat
57 -- double -> CDouble
58 -- long double -> CLDouble
59 -- enum ... -> CInt
60 -- struct ... -> ** error **
61 -- union ... -> ** error **
62 --
63 -- Plain structures or unions (ie, if not the base type of a pointer type)
64 -- are not supported at the moment (the underlying FFI does not support them
65 -- directly). Named types (ie, in C type names defined using `typedef') are
66 -- traced back to their original definitions. Pointer types are mapped
67 -- to `Ptr a' or `FunPtr a' depending on whether they point to a functional.
68 -- Values obtained from bit fields are represented by `CInt' or `CUInt'
69 -- depending on whether they are signed.
70 --
71 -- We obtain the size and alignment constraints for all primitive types of C
72 -- from `CInfo', which obtains it from the Haskell 98 FFI. In the alignment
73 -- computations involving bit fields, we assume that the alignment
74 -- constraints for bitfields (wrt to non-bitfield members) is always the same
75 -- as for `int' irrespective of the size of the bitfield. This seems to be
76 -- implicitly guaranteed by K&R A8.3, but it is not entirely clear.
77 --
78 -- Identifier lookup:
79 -- ------------------
80 --
81 -- We allow to identify enumerations and structures by the names of `typedef'
82 -- types aliased to them.
83 --
84 -- * enumerations: It is first checked whether there is a tag with the given
85 -- identifier; if such a tag does not exist, the definition of a typedef
86 -- with the same name is taken if it exists.
87 -- * structs/unions: like enumerations
88 --
89 -- We generally use `shadow' lookups. When an identifier cannot be found,
90 -- we check whether - according to the prefix set by the context hook -
91 -- another identifier casts a shadow that matches. If so, that identifier is
92 -- taken instead of the original one.
93 --
94 --- TODO ----------------------------------------------------------------------
95 --
96 -- * A function prototype that uses a defined type on its left hand side may
97 -- declare a function, while that is not obvious from the declaration
98 -- itself (without also considering the `typedef'). Calls to such
99 -- functions are currently rejected, which is a BUG.
100 --
101 -- * context hook must precede all but the import hooks
102 --
103 -- * The use of `++' in the recursive definition of the routines generating
104 -- `Enum' instances is not particularly efficient.
105 --
106 -- * Some operands are missing in `applyBin' - unfortunately, Haskell does
107 -- not have standard bit operations. Some constructs are also missing
108 -- from `evalConstCExpr'. Haskell 98 FFI standardises `Bits'; use that.
109 --
110
111 module GenBind (expandHooks)
112 where
113
114 -- standard libraries
115 import Data.Char (toUpper, toLower, isSpace)
116 import Data.List (deleteBy, intersperse, isPrefixOf, find, nubBy)
117 import Data.Maybe (isNothing, isJust, fromJust, fromMaybe)
118 import Control.Monad (when, unless, liftM, mapAndUnzipM)
119
120 import Data.Bits ((.&.), (.|.), xor, complement)
121
122 -- Compiler Toolkit
123 import Position (Position, Pos(posOf), nopos, builtinPos)
124 import Errors (interr, todo)
125 import Idents (Ident, identToLexeme, onlyPosIdent)
126 import Attributes (newAttrsOnlyPos)
127
128 -- C->Haskell
129 import C2HSConfig (dlsuffix)
130 import C2HSState (CST, nop, errorsPresent, showErrors, fatal,
131 SwitchBoard(..), Traces(..), putTraceStr, getSwitch,
132 printCIO)
133 import C (AttrC, CObj(..), CTag(..), lookupDefObjC, lookupDefTagC,
134 CHeader(..), CExtDecl, CDecl(..), CDeclSpec(..),
135 CStorageSpec(..), CTypeSpec(..), CTypeQual(..),
136 CStructUnion(..), CStructTag(..), CEnum(..), CDeclr(..),
137 CInit(..), CExpr(..), CAssignOp(..), CBinaryOp(..),
138 CUnaryOp(..), CConst (..),
139 CT, readCT, transCT, getCHeaderCT, runCT, ifCTExc,
140 raiseErrorCTExc, findValueObj, findFunObj, findTag,
141 findTypeObj, applyPrefixToNameSpaces, isTypedef,
142 simplifyDecl, declrFromDecl, declrNamed, structMembers,
143 structName, tagName, declaredName , structFromDecl,
144 funResultAndArgs, chaseDecl, findAndChaseDecl,
145 findObjShadow,
146 checkForAlias, checkForOneAliasName, lookupEnum,
147 lookupStructUnion, lookupDeclOrTag, isPtrDeclr,
148 isArrDeclr, dropPtrDeclr, isPtrDecl, getDeclOf, isFunDeclr,
149 refersToNewDef, CDef(..))
150
151 -- friends
152 import CHS (CHSModule(..), CHSFrag(..), CHSHook(..), CHSTrans(..),
153 CHSParm(..), CHSArg(..), CHSAccess(..), CHSAPath(..),
154 CHSPtrType(..), showCHSParm)
155 import CInfo (CPrimType(..), size, alignment, bitfieldIntSigned,
156 bitfieldAlignment)
157 import GBMonad (TransFun, transTabToTransFun, HsObject(..), GB, HsPtrRep,
158 initialGBState, setContext, getPrefix, getLock,
159 delayCode, getDelayedCode, ptrMapsTo, queryPtr, objIs,
160 queryObj, queryClass, queryPointer, mergeMaps, dumpMaps)
161
162 -- default marshallers
163 -- -------------------
164
165 -- FIXME:
166 -- - we might have a dynamically extended table in the monad if needed (we
167 -- could marshall enums this way and also save the `id' marshallers for
168 -- pointers defined via (newtype) pointer hooks)
169 -- - the checks for the Haskell types are quite kludgy
170
171 -- determine the default "in" marshaller for the given Haskell and C types
172 --
173 lookupDftMarshIn :: String -> [ExtType] -> GB (Maybe (Ident, CHSArg))
174 lookupDftMarshIn "Bool" [PrimET pt] | isIntegralCPrimType pt =
175 return $ Just (cFromBoolIde, CHSValArg)
176 lookupDftMarshIn hsTy [PrimET pt] | isIntegralHsType hsTy
177 &&isIntegralCPrimType pt =
178 return $ Just (cIntConvIde, CHSValArg)
179 lookupDftMarshIn hsTy [PrimET pt] | isFloatHsType hsTy
180 &&isFloatCPrimType pt =
181 return $ Just (cFloatConvIde, CHSValArg)
182 lookupDftMarshIn "String" [PtrET (PrimET CCharPT)] =
183 return $ Just (withCStringIde, CHSIOArg)
184 lookupDftMarshIn "String" [PtrET (PrimET CCharPT), PrimET pt]
185 | isIntegralCPrimType pt =
186 return $ Just (withCStringLenIde, CHSIOArg)
187 lookupDftMarshIn hsTy [PtrET ty] | showExtType ty == hsTy =
188 return $ Just (withIde, CHSIOArg)
189 lookupDftMarshIn hsTy [PtrET (PrimET pt)]
190 | isIntegralHsType hsTy && isIntegralCPrimType pt =
191 return $ Just (withIntConvIde, CHSIOArg)
192 lookupDftMarshIn hsTy [PtrET (PrimET pt)]
193 | isFloatHsType hsTy && isFloatCPrimType pt =
194 return $ Just (withFloatConvIde, CHSIOArg)
195 lookupDftMarshIn "Bool" [PtrET (PrimET pt)]
196 | isIntegralCPrimType pt =
197 return $ Just (withFromBoolIde, CHSIOArg)
198 -- FIXME: handle array-list conversion
199 lookupDftMarshIn _ _ =
200 return Nothing
201
202 -- determine the default "out" marshaller for the given Haskell and C types
203 --
204 lookupDftMarshOut :: String -> [ExtType] -> GB (Maybe (Ident, CHSArg))
205 lookupDftMarshOut "()" _ =
206 return $ Just (voidIde, CHSVoidArg)
207 lookupDftMarshOut "Bool" [PrimET pt] | isIntegralCPrimType pt =
208 return $ Just (cToBoolIde, CHSValArg)
209 lookupDftMarshOut hsTy [PrimET pt] | isIntegralHsType hsTy
210 &&isIntegralCPrimType pt =
211 return $ Just (cIntConvIde, CHSValArg)
212 lookupDftMarshOut hsTy [PrimET pt] | isFloatHsType hsTy
213 &&isFloatCPrimType pt =
214 return $ Just (cFloatConvIde, CHSValArg)
215 lookupDftMarshOut "String" [PtrET (PrimET CCharPT)] =
216 return $ Just (peekCStringIde, CHSIOArg)
217 lookupDftMarshOut "String" [PtrET (PrimET CCharPT), PrimET pt]
218 | isIntegralCPrimType pt =
219 return $ Just (peekCStringLenIde, CHSIOArg)
220 lookupDftMarshOut hsTy [PtrET ty] | showExtType ty == hsTy =
221 return $ Just (peekIde, CHSIOArg)
222 -- FIXME: add combination, such as "peek" plus "cIntConv" etc
223 -- FIXME: handle array-list conversion
224 lookupDftMarshOut _ _ =
225 return Nothing
226
227
228 -- check for integral Haskell types
229 --
230 isIntegralHsType :: String -> Bool
231 isIntegralHsType "Int" = True
232 isIntegralHsType "Int8" = True
233 isIntegralHsType "Int16" = True
234 isIntegralHsType "Int32" = True
235 isIntegralHsType "Int64" = True
236 isIntegralHsType "Word8" = True
237 isIntegralHsType "Word16" = True
238 isIntegralHsType "Word32" = True
239 isIntegralHsType "Word64" = True
240 isIntegralHsType _ = False
241
242 -- check for floating Haskell types
243 --
244 isFloatHsType :: String -> Bool
245 isFloatHsType "Float" = True
246 isFloatHsType "Double" = True
247 isFloatHsType _ = False
248
249 -- check for integral C types
250 --
251 -- * For marshalling purposes C char's are integral types (see also types
252 -- classes for which the FFI guarantees instances for `CChar', `CSChar', and
253 -- `CUChar')
254 --
255 isIntegralCPrimType :: CPrimType -> Bool
256 isIntegralCPrimType = (`elem` [CCharPT, CSCharPT, CIntPT, CShortPT, CLongPT,
257 CLLongPT, CUIntPT, CUCharPT, CUShortPT,
258 CULongPT, CULLongPT])
259
260 -- check for floating C types
261 --
262 isFloatCPrimType :: CPrimType -> Bool
263 isFloatCPrimType = (`elem` [CFloatPT, CDoublePT, CLDoublePT])
264
265 -- standard conversions
266 --
267 voidIde = noPosIdent "void" -- never appears in the output
268 cFromBoolIde = noPosIdent "cFromBool"
269 cToBoolIde = noPosIdent "cToBool"
270 cIntConvIde = noPosIdent "cIntConv"
271 cFloatConvIde = noPosIdent "cFloatConv"
272 withIde = noPosIdent "with"
273 withCStringIde = noPosIdent "withCString"
274 withCStringLenIde = noPosIdent "withCStringLenIntConv"
275 withIntConvIde = noPosIdent "withIntConv"
276 withFloatConvIde = noPosIdent "withFloatConv"
277 withFromBoolIde = noPosIdent "withFromBoolConv"
278 peekIde = noPosIdent "peek"
279 peekCStringIde = noPosIdent "peekCString"
280 peekCStringLenIde = noPosIdent "peekCStringLenIntConv"
281
282
283 -- expansion of binding hooks
284 -- --------------------------
285
286 -- given a C header file and a binding file, expand all hooks in the binding
287 -- file using the C header information (EXPORTED)
288 --
289 -- * together with the module, returns the contents of the .chi file
290 --
291 -- * if any error (not warnings) is encountered, a fatal error is raised.
292 --
293 -- * also returns all warning messages encountered (last component of result)
294 --
295 expandHooks :: AttrC -> CHSModule -> CST s (CHSModule, String, String)
296 expandHooks ac mod = do
297 mLock <- getSwitch lockFunSB
298 (_, res) <- runCT (expandModule mod) ac (initialGBState mLock)
299 return res
300
301 expandModule :: CHSModule -> GB (CHSModule, String, String)
302 expandModule (CHSModule frags) =
303 do
304 -- expand hooks
305 --
306 traceInfoExpand
307 frags' <- expandFrags frags
308 delayedFrags <- getDelayedCode
309
310 -- get .chi dump
311 --
312 chi <- dumpMaps
313
314 -- check for errors and finalise
315 --
316 errs <- errorsPresent
317 if errs
318 then do
319 traceInfoErr
320 errmsgs <- showErrors
321 fatal ("Errors during expansion of binding hooks:\n\n" -- fatal error
322 ++ errmsgs)
323 else do
324 traceInfoOK
325 warnmsgs <- showErrors
326 return (CHSModule (frags' ++ delayedFrags), chi, warnmsgs)
327 where
328 traceInfoExpand = putTraceStr tracePhasesSW
329 ("...expanding binding hooks...\n")
330 traceInfoErr = putTraceStr tracePhasesSW
331 ("...error(s) detected.\n")
332 traceInfoOK = putTraceStr tracePhasesSW
333 ("...successfully completed.\n")
334
335 expandFrags :: [CHSFrag] -> GB [CHSFrag]
336 expandFrags = liftM concat . mapM expandFrag
337
338 expandFrag :: CHSFrag -> GB [CHSFrag]
339 expandFrag verb@(CHSVerb _ _ ) = return [verb]
340 expandFrag line@(CHSLine _ ) = return [line]
341 expandFrag prag@(CHSLang _ _ ) = return [prag]
342 expandFrag (CHSHook h ) =
343 do
344 code <- expandHook h
345 return [CHSVerb code builtinPos]
346 `ifCTExc` return [CHSVerb "** ERROR **" builtinPos]
347 expandFrag (CHSCPP s _ ) =
348 interr $ "GenBind.expandFrag: Left over CHSCPP!\n---\n" ++ s ++ "\n---"
349 expandFrag (CHSC s _ ) =
350 interr $ "GenBind.expandFrag: Left over CHSC!\n---\n" ++ s ++ "\n---"
351 expandFrag (CHSCond alts dft) =
352 do
353 traceInfoCond
354 select alts
355 where
356 select [] = do
357 traceInfoDft dft
358 expandFrags (maybe [] id dft)
359 select ((ide, frags):alts) = do
360 oobj <- findTag ide
361 traceInfoVal ide oobj
362 if isNothing oobj
363 then
364 select alts
365 else -- found right alternative
366 expandFrags frags
367 --
368 traceInfoCond = traceGenBind "** CPP conditional:\n"
369 traceInfoVal ide oobj = traceGenBind $ identToLexeme ide ++ " is " ++
370 (if isNothing oobj then "not " else "") ++
371 "defined.\n"
372 traceInfoDft dft = if isNothing dft
373 then
374 return ()
375 else
376 traceGenBind "Choosing else branch.\n"
377
378 expandHook :: CHSHook -> GB String
379 expandHook (CHSImport qual ide chi _) =
380 do
381 mergeMaps chi
382 return $
383 "import " ++ (if qual then "qualified " else "") ++ identToLexeme ide
384 expandHook (CHSContext olib oprefix olock _) =
385 do
386 setContext olib oprefix olock -- enter context information
387 mapMaybeM_ applyPrefixToNameSpaces oprefix -- use the prefix on name spaces
388 return ""
389 expandHook (CHSType ide pos) =
390 do
391 traceInfoType
392 decl <- findAndChaseDecl ide False True -- no indirection, but shadows
393 ty <- extractSimpleType pos decl
394 traceInfoDump decl ty
395 return $ "(" ++ showExtType ty ++ ")"
396 where
397 traceInfoType = traceGenBind "** Type hook:\n"
398 traceInfoDump decl ty = traceGenBind $
399 "Declaration\n" ++ show decl ++ "\ntranslates to\n"
400 ++ showExtType ty ++ "\n"
401 expandHook (CHSSizeof ide pos) =
402 do
403 traceInfoSizeof
404 decl <- findAndChaseDecl ide False True -- no indirection, but shadows
405 (size, _) <- sizeAlignOf decl
406 traceInfoDump decl size
407 return $ show (fromIntegral . padBits $ size)
408 where
409 traceInfoSizeof = traceGenBind "** Sizeof hook:\n"
410 traceInfoDump decl size = traceGenBind $
411 "Size of declaration\n" ++ show decl ++ "\nis "
412 ++ show (fromIntegral . padBits $ size) ++ "\n"
413 expandHook (CHSEnum cide oalias chsTrans oprefix derive _) =
414 do
415 -- get the corresponding C declaration
416 --
417 enum <- lookupEnum cide True -- smart lookup incl error handling
418 --
419 -- convert the translation table and generate data type definition code
420 --
421 gprefix <- getPrefix
422 let prefix = fromMaybe gprefix oprefix
423 trans = transTabToTransFun prefix chsTrans
424 hide = identToLexeme . fromMaybe cide $ oalias
425 enumDef enum hide trans (map identToLexeme derive)
426 expandHook hook@(CHSCall isPure isUns isNol ide oalias pos) =
427 do
428 traceEnter
429 -- get the corresponding C declaration; raises error if not found or not a
430 -- function; we use shadow identifiers, so the returned identifier is used
431 -- afterwards instead of the original one
432 --
433 (ObjCO cdecl, ide) <- findFunObj ide True
434 mLock <- if isNol then return Nothing else getLock
435 let ideLexeme = identToLexeme ide -- original name might have been a shadow
436 hsLexeme = ideLexeme `maybe` identToLexeme $ oalias
437 cdecl' = ide `simplifyDecl` cdecl
438 callImport hook isPure isUns mLock ideLexeme hsLexeme cdecl' pos
439 where
440 traceEnter = traceGenBind $
441 "** Call hook for `" ++ identToLexeme ide ++ "':\n"
442 expandHook hook@(CHSFun isPure isUns isNol ide oalias ctxt parms parm pos) =
443 do
444 traceEnter
445 -- get the corresponding C declaration; raises error if not found or not a
446 -- function; we use shadow identifiers, so the returned identifier is used
447 -- afterwards instead of the original one
448 --
449 (ObjCO cdecl, cide) <- findFunObj ide True
450 mLock <- if isNol then return Nothing else getLock
451 let ideLexeme = identToLexeme ide -- original name might have been a shadow
452 hsLexeme = ideLexeme `maybe` identToLexeme $ oalias
453 fiLexeme = hsLexeme ++ "'_" -- *Urgh* - probably unique...
454 fiIde = onlyPosIdent nopos fiLexeme
455 cdecl' = cide `simplifyDecl` cdecl
456 callHook = CHSCall isPure isUns isNol cide (Just fiIde) pos
457 callImport callHook isPure isUns mLock (identToLexeme cide) fiLexeme cdecl' pos
458 funDef isPure hsLexeme fiLexeme cdecl' ctxt mLock parms parm pos
459 where
460 traceEnter = traceGenBind $
461 "** Fun hook for `" ++ identToLexeme ide ++ "':\n"
462 expandHook (CHSField access path pos) =
463 do
464 traceInfoField
465 (decl, offsets) <- accessPath path
466 traceDepth offsets
467 ty <- extractSimpleType pos decl
468 traceValueType ty
469 setGet pos access offsets ty
470 where
471 accessString = case access of
472 CHSGet -> "Get"
473 CHSSet -> "Set"
474 traceInfoField = traceGenBind $ "** " ++ accessString ++ " hook:\n"
475 traceDepth offsets = traceGenBind $ "Depth of access path: "
476 ++ show (length offsets) ++ "\n"
477 traceValueType et = traceGenBind $
478 "Type of accessed value: " ++ showExtType et ++ "\n"
479 expandHook (CHSPointer isStar cName oalias ptrKind isNewtype oRefType pos) =
480 do
481 traceInfoPointer
482 let hsIde = fromMaybe cName oalias
483 hsName = identToLexeme hsIde
484 hsIde `objIs` Pointer ptrKind isNewtype -- register Haskell object
485 --
486 -- we check for a typedef declaration or tag (struct, union, or enum)
487 --
488 declOrTag <- lookupDeclOrTag cName True
489 case declOrTag of
490 Left cdecl -> do -- found a typedef declaration
491 cNameFull <- case declaredName cdecl of
492 Just ide -> return ide
493 Nothing -> interr
494 "GenBind.expandHook: Where is the name?"
495 cNameFull `refersToNewDef` ObjCD (TypeCO cdecl)
496 -- assoc needed for chasing
497 traceInfoCName "declaration" cNameFull
498 unless (isStar || isPtrDecl cdecl) $
499 ptrExpectedErr (posOf cName)
500 (hsType, isFun) <-
501 case oRefType of
502 Nothing -> do
503 cDecl <- chaseDecl cNameFull (not isStar)
504 et <- extractPtrType cDecl
505 let et' = adjustPtr isStar et
506 return (showExtType et', isFunExtType et')
507 Just hsType -> return (identToLexeme hsType, False)
508 -- FIXME: it is not possible to determine whether `hsType'
509 -- is a function; we would need to extend the syntax to
510 -- allow `... -> fun HSTYPE' to explicitly mark function
511 -- types if this ever becomes important
512 traceInfoHsType hsName hsType
513 realCName <- liftM (maybe cName snd) $ findObjShadow cName
514 pointerDef isStar realCName hsName ptrKind isNewtype hsType isFun
515 Right tag -> do -- found a tag definition
516 let cNameFull = tagName tag
517 traceInfoCName "tag definition" cNameFull
518 unless isStar $ -- tags need an explicit `*'
519 ptrExpectedErr (posOf cName)
520 let hsType = case oRefType of
521 Nothing -> "()"
522 Just hsType -> identToLexeme hsType
523 traceInfoHsType hsName hsType
524 pointerDef isStar cNameFull hsName ptrKind isNewtype hsType False
525 where
526 -- remove a pointer level if the first argument is `False'
527 --
528 adjustPtr True et = et
529 adjustPtr False (PtrET et) = et
530 adjustPtr _ _ = interr "GenBind.adjustPtr: Where is the Ptr?"
531 --
532 traceInfoPointer = traceGenBind "** Pointer hook:\n"
533 traceInfoCName kind ide = traceGenBind $
534 "found C " ++ kind ++ " for `" ++ identToLexeme ide ++ "'\n"
535 traceInfoHsType name ty = traceGenBind $
536 "associated with Haskell entity `" ++ name ++ "'\nhaving type " ++ ty
537 ++ "\n"
538 expandHook (CHSClass oclassIde classIde typeIde pos) =
539 do
540 traceInfoClass
541 classIde `objIs` Class oclassIde typeIde -- register Haskell object
542 superClasses <- collectClasses oclassIde
543 Pointer ptrType isNewtype <- queryPointer typeIde
544 when (ptrType == CHSStablePtr) $
545 illegalStablePtrErr pos
546 classDef pos (identToLexeme classIde) (identToLexeme typeIde)
547 ptrType isNewtype superClasses
548 where
549 -- compile a list of all super classes (the direct super class first)
550 --
551 collectClasses :: Maybe Ident -> GB [(String, String, HsObject)]
552 collectClasses Nothing = return []
553 collectClasses (Just ide) =
554 do
555 Class oclassIde typeIde <- queryClass ide
556 ptr <- queryPointer typeIde
557 classes <- collectClasses oclassIde
558 return $ (identToLexeme ide, identToLexeme typeIde, ptr) : classes
559 --
560 traceInfoClass = traceGenBind $ "** Class hook:\n"
561
562 -- produce code for an enumeration
563 --
564 -- * an extra instance declaration is required when any of the enumeration
565 -- constants is explicitly assigned a value in its definition
566 --
567 -- * the translation function strips prefixes where possible (different
568 -- enumerators maye have different prefixes)
569 --
570 enumDef :: CEnum -> String -> TransFun -> [String] -> GB String
571 enumDef cenum@(CEnum _ list _) hident trans userDerive =
572 do
573 (list', enumAuto) <- evalTagVals list
574 let enumVals = [(trans ide, cexpr) | (ide, cexpr) <- list'] -- translate
575 defHead = enumHead hident
576 defBody = enumBody (length defHead - 2) enumVals
577 inst = makeDerives
578 (if enumAuto then "Enum" : userDerive else userDerive) ++
579 if enumAuto then "\n" else "\n" ++ enumInst hident enumVals
580 return $ defHead ++ defBody ++ inst
581 where
582 cpos = posOf cenum
583 --
584 evalTagVals [] = return ([], True)
585 evalTagVals ((ide, Nothing ):list) =
586 do
587 (list', derived) <- evalTagVals list
588 return ((ide, Nothing):list', derived)
589 evalTagVals ((ide, Just exp):list) =
590 do
591 (list', derived) <- evalTagVals list
592 val <- evalConstCExpr exp
593 case val of
594 IntResult val' ->
595 return ((ide, Just $ CConst (CIntConst val' at1) at2):list',
596 False)
597 FloatResult _ ->
598 illegalConstExprErr (posOf exp) "a float result"
599 where
600 at1 = newAttrsOnlyPos nopos
601 at2 = newAttrsOnlyPos nopos
602 makeDerives [] = ""
603 makeDerives dList = "deriving (" ++ concat (intersperse "," dList) ++")"
604
605 -- Haskell code for the head of an enumeration definition
606 --
607 enumHead :: String -> String
608 enumHead ident = "data " ++ ident ++ " = "
609
610 -- Haskell code for the body of an enumeration definition
611 --
612 enumBody :: Int -> [(String, Maybe CExpr)] -> String
613 enumBody indent [] = ""
614 enumBody indent ((ide, _):list) =
615 ide ++ "\n" ++ replicate indent ' '
616 ++ (if null list then "" else "| " ++ enumBody indent list)
617
618 -- Haskell code for an instance declaration for `Enum'
619 --
620 -- * the expression of all explicitly specified tag values already have to be
621 -- in normal form, ie, to be an int constant
622 --
623 -- * enumerations start at 0 and whenever an explicit value is specified,
624 -- following tags are assigned values continuing from the explicitly
625 -- specified one
626 --
627 enumInst :: String -> [(String, Maybe CExpr)] -> String
628 enumInst ident list =
629 "instance Enum " ++ ident ++ " where\n"
630 ++ fromDef flatList ++ "\n" ++ toDef flatList ++ "\n"
631 ++ succDef names ++ "\n" ++ predDef names ++ "\n"
632 ++ enumFromToDef names
633 where
634 names = map fst list
635 flatList = flatten list 0
636
637 flatten [] n = []
638 flatten ((ide, exp):list) n = (ide, val) : flatten list (val + 1)
639 where
640 val = case exp of
641 Nothing -> n
642 Just (CConst (CIntConst m _) _) -> m
643 Just _ -> interr "GenBind.enumInst: Integer constant expected!"
644
645 show' x = if x < 0 then "(" ++ show x ++ ")" else show x
646 fromDef list = concat
647 [ " fromEnum " ++ ide ++ " = " ++ show' val ++ "\n"
648 | (ide, val) <- list
649 ]
650 toDef list = concat
651 [ " toEnum " ++ show' val ++ " = " ++ ide ++ "\n"
652 | (ide, val) <- nubBy (\x y -> snd x == snd y) list
653 ]
654 ++ " toEnum unmatched = error (\"" ++ ident
655 ++ ".toEnum: Cannot match \" ++ show unmatched)\n"
656
657 succDef [] = " succ _ = undefined\n"
658 succDef [x] = " succ _ = undefined\n"
659 succDef (x:x':xs) =
660 " succ " ++ x ++ " = " ++ x' ++ "\n"
661 ++ succDef (x':xs)
662 predDef [] = " pred _ = undefined\n"
663 predDef [x] = " pred _ = undefined\n"
664 predDef (x:x':xs) =
665 " pred " ++ x' ++ " = " ++ x ++ "\n"
666 ++ predDef (x':xs)
667 enumFromToDef [] = ""
668 enumFromToDef names =
669 " enumFromTo x y | fromEnum x == fromEnum y = [ y ]\n"
670 ++ " | otherwise = x : enumFromTo (succ x) y\n"
671 ++ " enumFrom x = enumFromTo x " ++ last names ++ "\n"
672 ++ " enumFromThen _ _ = "
673 ++ " error \"Enum "++ident++": enumFromThen not implemented\"\n"
674 ++ " enumFromThenTo _ _ _ = "
675 ++ " error \"Enum "++ident++": enumFromThenTo not implemented\"\n"
676
677
678 -- generate a foreign import declaration that is put into the delayed code
679 --
680 -- * the C declaration is a simplified declaration of the function that we
681 -- want to import into Haskell land
682 --
683 callImport :: CHSHook -> Bool -> Bool -> Maybe String -> String -> String
684 -> CDecl -> Position -> GB String
685 callImport hook isPure isUns mLock ideLexeme hsLexeme cdecl pos =
686 do
687 -- compute the external type from the declaration, and delay the foreign
688 -- export declaration
689 --
690 (mHsPtrRep, extType) <- extractFunType pos cdecl isPure
691 header <- getSwitch headerSB
692 delayCode hook (foreignImport header ideLexeme hsLexeme isUns extType)
693 traceFunType extType
694 -- if the type any special pointer aliases, generate a lambda expression
695 -- which strips off the constructors
696 if any isJust mHsPtrRep
697 then createLambdaExpr mHsPtrRep
698 else return funStr
699 where
700 createLambdaExpr :: [Maybe HsPtrRep] -> GB String
701 createLambdaExpr foreignVec = return $
702 "(\\" ++
703 unwords (zipWith wrPattern foreignVec [1..])++ " -> "++
704 concat (zipWith wrForPtr foreignVec [1..])++funStr++" "++
705 unwords (zipWith wrArg foreignVec [1..])++")"
706 wrPattern (Just (_,_,Just con,_)) n = "("++con++" arg"++show n++")"
707 wrPattern _ n = "arg"++show n
708 wrForPtr (Just (_,CHSForeignPtr,_,_)) n
709 = "withForeignPtr arg"++show n++" $ \\argPtr"++show n++" ->"
710 wrForPtr _ n = ""
711 wrArg (Just (_,CHSForeignPtr,_,_)) n = "argPtr"++show n
712 wrArg (Just (_,CHSStablePtr,_,_)) n =
713 "(castStablePtrToPtr arg"++show n++")"
714 wrArg _ n = "arg"++show n
715
716 funStr = case mLock of Nothing -> hsLexeme
717 Just lockFun -> lockFun ++ " $ " ++ hsLexeme
718 traceFunType et = traceGenBind $
719 "Imported function type: " ++ showExtType et ++ "\n"
720
721 -- Haskell code for the foreign import declaration needed by a call hook
722 --
723 -- On Windows, the paths for headers in "entity" may include backslashes, like
724 -- dist\build\System\Types\GIO.h
725 -- It seems GHC expects these to be escaped. Below, we make an educated guess
726 -- that it in fact expects a Haskell string, and use the "show" function to do
727 -- the escaping of this (and any other cases) for us.
728 foreignImport :: String -> String -> String -> Bool -> ExtType -> String
729 foreignImport header ident hsIdent isUnsafe ty =
730 "foreign import ccall " ++ safety ++ " " ++ show entity ++
731 "\n " ++ hsIdent ++ " :: " ++ showExtType ty ++ "\n"
732 where
733 safety = if isUnsafe then "unsafe" else "safe"
734 entity | null header = ident
735 | otherwise = header ++ " " ++ ident
736
737 -- produce a Haskell function definition for a fun hook
738 --
739 funDef :: Bool -- pure function?
740 -> String -- name of the new Haskell function
741 -> String -- Haskell name of the foreign imported C function
742 -> CDecl -- simplified declaration of the C function
743 -> Maybe String -- type context of the new Haskell function
744 -> Maybe String -- lock function
745 -> [CHSParm] -- parameter marshalling description
746 -> CHSParm -- result marshalling description
747 -> Position -- source location of the hook
748 -> GB String -- Haskell code in text form
749 funDef isPure hsLexeme fiLexeme cdecl octxt mLock parms parm pos =
750 do
751 (parms', parm', isImpure) <- addDftMarshaller pos parms parm cdecl
752 traceMarsh parms' parm' isImpure
753 let
754 sig = hsLexeme ++ " :: " ++ funTy parms' parm' ++ "\n"
755 marshs = [marshArg i parm | (i, parm) <- zip [1..] parms']
756 funArgs = [funArg | (funArg, _, _, _, _) <- marshs, funArg /= ""]
757 marshIns = [marshIn | (_, marshIn, _, _, _) <- marshs]
758 callArgs = [callArg | (_, _, callArg, _, _) <- marshs]
759 marshOuts = [marshOut | (_, _, _, marshOut, _) <- marshs, marshOut /= ""]
760 retArgs = [retArg | (_, _, _, _, retArg) <- marshs, retArg /= ""]
761 funHead = hsLexeme ++ join funArgs ++ " =\n" ++
762 if isPure && isImpure then " unsafePerformIO $\n" else ""
763 lock = case mLock of Nothing -> ""
764 Just lock -> lock ++ " $"
765 call = if isPure
766 then " let {res = " ++ fiLexeme ++ join callArgs ++ "} in\n"
767 else " " ++ lock ++ fiLexeme ++ join callArgs ++ " >>= \\res ->\n"
768 marshRes = case parm' of
769 CHSParm _ _ twoCVal (Just (_ , CHSVoidArg)) _ -> ""
770 CHSParm _ _ twoCVal (Just (omIde, CHSIOArg )) _ ->
771 " " ++ identToLexeme omIde ++ " res >>= \\res' ->\n"
772 CHSParm _ _ twoCVal (Just (omIde, CHSValArg )) _ ->
773 " let {res' = " ++ identToLexeme omIde ++ " res} in\n"
774 CHSParm _ _ _ Nothing _ ->
775 interr "GenBind.funDef: marshRes: no default?"
776 retArgs' = case parm' of
777 CHSParm _ _ _ (Just (_, CHSVoidArg)) _ -> retArgs
778 _ -> "res'":retArgs
779 ret = "(" ++ concat (intersperse ", " retArgs') ++ ")"
780 funBody = joinLines marshIns ++
781 call ++
782 joinLines marshOuts ++
783 marshRes ++
784 " " ++
785 (if isImpure || not isPure then "return " else "") ++ ret
786 return $ sig ++ funHead ++ funBody
787 where
788 join = concatMap (' ':)
789 joinLines = concatMap (\s -> " " ++ s ++ "\n")
790 --
791 -- construct the function type
792 --
793 -- * specified types appear in the argument and result only if their "in"
794 -- and "out" marshaller, respectively, is not the `void' marshaller
795 --
796 funTy parms parm =
797 let
798 ctxt = case octxt of
799 Nothing -> ""
800 Just ctxtStr -> ctxtStr ++ " => "
801 argTys = [ty | CHSParm im ty _ _ _ <- parms , notVoid im]
802 resTys = [ty | CHSParm _ ty _ om _ <- parm:parms, notVoid om]
803 resTup = let
804 (lp, rp) = if isPure && length resTys == 1
805 then ("", "")
806 else ("(", ")")
807 io = if isPure then "" else "IO "
808 in
809 io ++ lp ++ concat (intersperse ", " resTys) ++ rp
810
811 in
812 ctxt ++ concat (intersperse " -> " (argTys ++ [resTup]))
813 where
814 notVoid Nothing = interr "GenBind.funDef: \
815 \No default marshaller?"
816 notVoid (Just (_, kind)) = kind /= CHSVoidArg
817 --
818 -- for an argument marshaller, generate all "in" and "out" marshalling
819 -- code fragments
820 --
821 marshArg i (CHSParm (Just (imIde, imArgKind)) _ twoCVal
822 (Just (omIde, omArgKind)) _ ) =
823 let
824 a = "a" ++ show i
825 imStr = identToLexeme imIde
826 imApp = imStr ++ " " ++ a
827 funArg = if imArgKind == CHSVoidArg then "" else a
828 inBndr = if twoCVal
829 then "(" ++ a ++ "'1, " ++ a ++ "'2)"
830 else a ++ "'"
831 marshIn = case imArgKind of
832 CHSVoidArg -> imStr ++ " $ \\" ++ inBndr ++ " -> "
833 CHSIOArg -> imApp ++ " $ \\" ++ inBndr ++ " -> "
834 CHSValArg -> "let {" ++ inBndr ++ " = " ++
835 imApp ++ "} in "
836 callArg = if twoCVal
837 then "" ++ a ++ "'1 " ++ a ++ "'2"
838 else a ++ "'"
839 omApp = identToLexeme omIde ++ " " ++ callArg
840 outBndr = a ++ "''"
841 marshOut = case omArgKind of
842 CHSVoidArg -> ""
843 CHSIOArg -> omApp ++ ">>= \\" ++ outBndr ++ " -> "
844 CHSValArg -> "let {" ++ outBndr ++ " = " ++
845 omApp ++ "} in "
846 retArg = if omArgKind == CHSVoidArg then "" else outBndr
847 in
848 (funArg, marshIn, callArg, marshOut, retArg)
849 marshArg _ _ = interr "GenBind.funDef: Missing default?"
850 --
851 traceMarsh parms parm isImpure = traceGenBind $
852 "Marshalling specification including defaults: \n" ++
853 showParms (parms ++ [parm]) "" ++
854 " The marshalling is " ++ if isImpure then "impure.\n" else "pure.\n"
855 where
856 showParms [] = id
857 showParms (parm:parms) = showString " "
858 . showCHSParm parm
859 . showChar '\n'
860 . showParms parms
861
862 -- add default marshallers for "in" and "out" marshalling
863 --
864 addDftMarshaller :: Position -> [CHSParm] -> CHSParm -> CDecl
865 -> GB ([CHSParm], CHSParm, Bool)
866 addDftMarshaller pos parms parm cdecl = do
867 (_, fType) <- extractFunType pos cdecl True
868 let (resTy, argTys) = splitFunTy fType
869 (parm' , isImpure1) <- checkResMarsh parm resTy
870 (parms', isImpure2) <- addDft parms argTys
871 return (parms', parm', isImpure1 || isImpure2)
872 where
873 -- the result marshalling may not use an "in" marshaller and can only have
874 -- one C value
875 --
876 -- * a default marshaller maybe used for "out" marshalling
877 --
878 checkResMarsh (CHSParm (Just _) _ _ _ pos) _ =
879 resMarshIllegalInErr pos
880 checkResMarsh (CHSParm _ _ True _ pos) _ =
881 resMarshIllegalTwoCValErr pos
882 checkResMarsh (CHSParm _ ty _ omMarsh pos) cTy = do
883 (imMarsh', _ ) <- addDftVoid Nothing
884 (omMarsh', isImpure) <- addDftOut pos omMarsh ty [cTy]
885 return (CHSParm imMarsh' ty False omMarsh' pos, isImpure)
886 --
887 splitFunTy (FunET UnitET ty ) = splitFunTy ty
888 splitFunTy (FunET ty1 ty2) = let
889 (resTy, argTys) = splitFunTy ty2
890 in
891 (resTy, ty1:argTys)
892 splitFunTy resTy = (resTy, [])
893 --
894 -- match Haskell with C arguments (and results)
895 --
896 addDft ((CHSParm imMarsh hsTy False omMarsh p):parms) (cTy :cTys) = do
897 (imMarsh', isImpureIn ) <- addDftIn p imMarsh hsTy [cTy]
898 (omMarsh', isImpureOut) <- addDftVoid omMarsh
899 (parms' , isImpure ) <- addDft parms cTys
900 return (CHSParm imMarsh' hsTy False omMarsh' p : parms',
901 isImpure || isImpureIn || isImpureOut)
902 addDft ((CHSParm imMarsh hsTy True omMarsh p):parms) (cTy1:cTy2:cTys) = do
903 (imMarsh', isImpureIn ) <- addDftIn p imMarsh hsTy [cTy1, cTy2]
904 (omMarsh', isImpureOut) <- addDftVoid omMarsh
905 (parms' , isImpure ) <- addDft parms cTys
906 return (CHSParm imMarsh' hsTy True omMarsh' p : parms',
907 isImpure || isImpureIn || isImpureOut)
908 addDft [] [] =
909 return ([], False)
910 addDft ((CHSParm _ _ _ _ pos):parms) [] =
911 marshArgMismatchErr pos "This parameter is in excess of the C arguments."
912 addDft [] (_:_) =
913 marshArgMismatchErr pos "Parameter marshallers are missing."
914 --
915 addDftIn _ imMarsh@(Just (_, kind)) _ _ = return (imMarsh,
916 kind == CHSIOArg)
917 addDftIn pos imMarsh@Nothing hsTy cTys = do
918 marsh <- lookupDftMarshIn hsTy cTys
919 when (isNothing marsh) $
920 noDftMarshErr pos "\"in\"" hsTy cTys
921 return (marsh, case marsh of {Just (_, kind) -> kind == CHSIOArg})
922 --
923 addDftOut _ omMarsh@(Just (_, kind)) _ _ = return (omMarsh,
924 kind == CHSIOArg)
925 addDftOut pos omMarsh@Nothing hsTy cTys = do
926 marsh <- lookupDftMarshOut hsTy cTys
927 when (isNothing marsh) $
928 noDftMarshErr pos "\"out\"" hsTy cTys
929 return (marsh, case marsh of {Just (_, kind) -> kind == CHSIOArg})
930 --
931 -- add void marshaller if no explicit one is given
932 --
933 addDftVoid marsh@(Just (_, kind)) = return (marsh, kind == CHSIOArg)
934 addDftVoid Nothing = do
935 return (Just (noPosIdent "void", CHSVoidArg), False)
936
937 -- compute from an access path, the declarator finally accessed and the index
938 -- path required for the access
939 --
940 -- * each element in the index path specifies dereferencing an address and the
941 -- offset to be added to the address before dereferencing
942 --
943 -- * the returned declaration is already normalised (ie, alias have been
944 -- expanded)
945 --
946 -- * it may appear as if `t.m' and `t->m' should have different access paths,
947 -- as the latter specifies one more dereferencing; this is certainly true in
948 -- C, but it doesn't apply here, as `t.m' is merely provided for the
949 -- convenience of the interface writer - it is strictly speaking an
950 -- impossible access paths, as in Haskell we always have a pointer to a
951 -- structure, we can never have the structure as a value itself
952 --
953 accessPath :: CHSAPath -> GB (CDecl, [BitSize])
954 accessPath (CHSRoot ide) = -- t
955 do
956 decl <- findAndChaseDecl ide False True
957 return (ide `simplifyDecl` decl, [BitSize 0 0])
958 accessPath (CHSDeref (CHSRoot ide) _) = -- *t
959 do
960 decl <- findAndChaseDecl ide True True
961 return (ide `simplifyDecl` decl, [BitSize 0 0])
962 accessPath (CHSRef root@(CHSRoot ide1) ide2) = -- t.m
963 do
964 su <- lookupStructUnion ide1 False True
965 (offset, decl') <- refStruct su ide2
966 adecl <- replaceByAlias decl'
967 return (adecl, [offset])
968 accessPath (CHSRef (CHSDeref (CHSRoot ide1) _) ide2) = -- t->m
969 do
970 su <- lookupStructUnion ide1 True True
971 (offset, decl') <- refStruct su ide2
972 adecl <- replaceByAlias decl'
973 return (adecl, [offset])
974 accessPath (CHSRef path ide) = -- a.m
975 do
976 (decl, offset:offsets) <- accessPath path
977 assertPrimDeclr ide decl
978 su <- structFromDecl (posOf ide) decl
979 (addOffset, decl') <- refStruct su ide
980 adecl <- replaceByAlias decl'
981 return (adecl, offset `addBitSize` addOffset : offsets)
982 where
983 assertPrimDeclr ide (CDecl _ [declr] _) =
984 case declr of
985 (Just (CVarDeclr _ _), _, _) -> nop
986 _ -> structExpectedErr ide
987 accessPath (CHSDeref path pos) = -- *a
988 do
989 (decl, offsets) <- accessPath path
990 decl' <- derefOrErr decl
991 adecl <- replaceByAlias decl'
992 return (adecl, BitSize 0 0 : offsets)
993 where
994 derefOrErr (CDecl specs [declr] at) =
995 case declr of
996 (Just (CPtrDeclr [_] declr at), oinit, oexpr) ->
997 return $ CDecl specs [(Just declr, oinit, oexpr)] at
998 (Just (CPtrDeclr (_:quals) declr at), oinit, oexpr) ->
999 return $
1000 CDecl specs [(Just (CPtrDeclr quals declr at), oinit, oexpr)] at
1001 _ ->
1002 ptrExpectedErr pos
1003
1004 -- replaces a declaration by its alias if any
1005 --
1006 -- * the alias inherits any field size specification that the original
1007 -- declaration may have
1008 --
1009 -- * declaration must have exactly one declarator
1010 --
1011 replaceByAlias :: CDecl -> GB CDecl
1012 replaceByAlias cdecl@(CDecl _ [(_, _, size)] at) =
1013 do
1014 ocdecl <- checkForAlias cdecl
1015 case ocdecl of
1016 Nothing -> return cdecl
1017 Just (CDecl specs [(declr, init, _)] at) -> -- form of an alias
1018 return $ CDecl specs [(declr, init, size)] at
1019
1020 -- given a structure declaration and member name, compute the offset of the
1021 -- member in the structure and the declaration of the referenced member
1022 --
1023 refStruct :: CStructUnion -> Ident -> GB (BitSize, CDecl)
1024 refStruct su ide =
1025 do
1026 -- get the list of fields and check for our selector
1027 --
1028 let (fields, tag) = structMembers su
1029 (pre, post) = span (not . flip declNamed ide) fields
1030 when (null post) $
1031 unknownFieldErr (posOf su) ide
1032 --
1033 -- get sizes of preceding fields and the result type (`pre' are all
1034 -- declarators preceding `ide' and the first declarator in `post' defines
1035 -- `ide')
1036 --
1037 let decl = head post
1038 offset <- case tag of
1039 CStructTag -> offsetInStruct pre decl tag
1040 CUnionTag -> return $ BitSize 0 0
1041 return (offset, decl)
1042
1043 -- does the given declarator define the given name?
1044 --
1045 declNamed :: CDecl -> Ident -> Bool
1046 (CDecl _ [(Nothing , _, _)] _) `declNamed` ide = False
1047 (CDecl _ [(Just declr, _, _)] _) `declNamed` ide = declr `declrNamed` ide
1048 (CDecl _ [] _) `declNamed` _ =
1049 interr "GenBind.declNamed: Abstract declarator in structure!"
1050 _ `declNamed` _ =
1051 interr "GenBind.declNamed: More than one declarator!"
1052
1053 -- Haskell code for writing to or reading from a struct
1054 --
1055 setGet :: Position -> CHSAccess -> [BitSize] -> ExtType -> GB String
1056 setGet pos access offsets ty =
1057 do
1058 let pre = case access of
1059 CHSSet -> "(\\ptr val -> do {"
1060 CHSGet -> "(\\ptr -> do {"
1061 body <- setGetBody (reverse offsets)
1062 return $ pre ++ body ++ "})"
1063 where
1064 setGetBody [BitSize offset bitOffset] =
1065 do
1066 let ty' = case ty of
1067 t@(DefinedET _ _) -> PtrET t
1068 t -> t
1069 let tyTag = showExtType ty'
1070 bf <- checkType ty'
1071 case bf of
1072 Nothing -> return $ case access of -- not a bitfield
1073 CHSGet -> peekOp offset tyTag
1074 CHSSet -> pokeOp offset tyTag "val"
1075 --FIXME: must take `bitfieldDirection' into account
1076 Just (_, bs) -> return $ case access of -- a bitfield
1077 CHSGet -> "val <- " ++ peekOp offset tyTag
1078 ++ extractBitfield
1079 CHSSet -> "org <- " ++ peekOp offset tyTag
1080 ++ insertBitfield
1081 ++ pokeOp offset tyTag "val'"
1082 where
1083 -- we have to be careful here to ensure proper sign extension;
1084 -- in particular, shifting right followed by anding a mask is
1085 -- *not* sufficient; instead, we exploit in the following that
1086 -- `shiftR' performs sign extension
1087 --
1088 extractBitfield = "; return $ (val `shiftL` ("
1089 ++ bitsPerField ++ " - "
1090 ++ show (bs + bitOffset) ++ ")) `shiftR` ("
1091 ++ bitsPerField ++ " - " ++ show bs
1092 ++ ")"
1093 bitsPerField = show $ size CIntPT * 8
1094 --
1095 insertBitfield = "; let {val' = (org .&. " ++ middleMask
1096 ++ ") .|. (val `shiftL` "
1097 ++ show bitOffset ++ ")}; "
1098 middleMask = "fromIntegral (((maxBound::CUInt) `shiftL` "
1099 ++ show bs ++ ") `rotateL` "
1100 ++ show bitOffset ++ ")"
1101 setGetBody (BitSize offset 0 : offsets) =
1102 do
1103 code <- setGetBody offsets
1104 return $ "ptr <- peekByteOff ptr " ++ show offset ++ "; " ++ code
1105 setGetBody (BitSize _ _ : _ ) =
1106 derefBitfieldErr pos
1107 --
1108 -- check that the type can be marshalled and compute extra operations for
1109 -- bitfields
1110 --
1111 checkType (IOET _ ) = interr "GenBind.setGet: Illegal \
1112 \type!"
1113 checkType (UnitET ) = voidFieldErr pos
1114 checkType (PrimET (CUFieldPT bs)) = return $ Just (False, bs)
1115 checkType (PrimET (CSFieldPT bs)) = return $ Just (True , bs)
1116 checkType _ = return Nothing
1117 --
1118 peekOp off tyTag = "peekByteOff ptr " ++ show off ++ " ::IO " ++ tyTag
1119 pokeOp off tyTag var = "pokeByteOff ptr " ++ show off ++ " (" ++ var
1120 ++ "::" ++ tyTag ++ ")"
1121
1122 -- generate the type definition for a pointer hook and enter the required type
1123 -- mapping into the `ptrmap'
1124 --
1125 pointerDef :: Bool -- explicit `*' in pointer hook
1126 -> Ident -- full C name
1127 -> String -- Haskell name
1128 -> CHSPtrType -- kind of the pointer
1129 -> Bool -- explicit newtype tag
1130 -> String -- Haskell type expression of pointer argument
1131 -> Bool -- do we have a pointer to a function?
1132 -> GB String
1133 pointerDef isStar cNameFull hsName ptrKind isNewtype hsType isFun =
1134 do
1135 keepOld <- getSwitch oldFFI
1136 let ptrArg = if keepOld
1137 then "()" -- legacy FFI interface
1138 else if isNewtype
1139 then hsName -- abstract type
1140 else hsType -- concrete type
1141 ptrCon = case ptrKind of
1142 CHSPtr | isFun -> "FunPtr"
1143 _ -> show ptrKind
1144 ptrType = ptrCon ++ " (" ++ ptrArg ++ ")"
1145 thePtr = (isStar, cNameFull)
1146
1147 thePtr `ptrMapsTo` (isFun,
1148 ptrKind,
1149 if isNewtype then Just hsName else Nothing,
1150 ptrArg)
1151 return $
1152 if isNewtype
1153 then "newtype " ++ hsName ++ " = " ++ hsName ++ " (" ++ ptrType ++ ")"
1154 else "type " ++ hsName ++ " = " ++ ptrType
1155
1156 -- generate the class and instance definitions for a class hook
1157 --
1158 -- * the pointer type must not be a stable pointer
1159 --
1160 -- * the first super class (if present) must be the direct superclass
1161 --
1162 -- * all Haskell objects in the superclass list must be pointer objects
1163 --
1164 classDef :: Position -- for error messages
1165 -> String -- class name
1166 -> String -- pointer type name
1167 -> CHSPtrType -- type of the pointer
1168 -> Bool -- is a newtype?
1169 -> [(String, String, HsObject)] -- superclasses
1170 -> GB String
1171 classDef pos className typeName ptrType isNewtype superClasses =
1172 do
1173 let
1174 toMethodName = case typeName of
1175 "" -> interr "GenBind.classDef: \
1176 \Illegal identifier!"
1177 c:cs -> toLower c : cs
1178 fromMethodName = "from" ++ typeName
1179 classDefContext = case superClasses of
1180 [] -> ""
1181 (superName, _, _):_ -> superName ++ " p => "
1182 classDef =
1183 "class " ++ classDefContext ++ className ++ " p where\n"
1184 ++ " " ++ toMethodName ++ " :: p -> " ++ typeName ++ "\n"
1185 ++ " " ++ fromMethodName ++ " :: " ++ typeName ++ " -> p\n"
1186 instDef =
1187 "instance " ++ className ++ " " ++ typeName ++ " where\n"
1188 ++ " " ++ toMethodName ++ " = id\n"
1189 ++ " " ++ fromMethodName ++ " = id\n"
1190 instDefs <- castInstDefs superClasses
1191 return $ classDef ++ instDefs ++ instDef
1192 where
1193 castInstDefs [] = return ""
1194 castInstDefs ((superName, ptrName, Pointer ptrType' isNewtype'):classes) =
1195 do
1196 unless (ptrType == ptrType') $
1197 pointerTypeMismatchErr pos className superName
1198 let toMethodName = case ptrName of
1199 "" -> interr "GenBind.classDef: \
1200 \Illegal identifier - 2!"
1201 c:cs -> toLower c : cs
1202 fromMethodName = "from" ++ ptrName
1203 castFun = "cast" ++ show ptrType
1204 typeConstr = if isNewtype then typeName ++ " " else ""
1205 superConstr = if isNewtype' then ptrName ++ " " else ""
1206 instDef =
1207 "instance " ++ superName ++ " " ++ typeName ++ " where\n"
1208 ++ " " ++ toMethodName ++ " (" ++ typeConstr ++ "p) = "
1209 ++ superConstr ++ "(" ++ castFun ++ " p)\n"
1210 ++ " " ++ fromMethodName ++ " (" ++ superConstr ++ "p) = "
1211 ++ typeConstr ++ "(" ++ castFun ++ " p)\n"
1212 instDefs <- castInstDefs classes
1213 return $ instDef ++ instDefs
1214
1215
1216 -- C code computations
1217 -- -------------------
1218
1219 -- the result of a constant expression
1220 --
1221 data ConstResult = IntResult Integer
1222 | FloatResult Float
1223
1224 -- types that may occur in foreign declarations, ie, Haskell land types
1225 --
1226 -- * we represent C functions with no arguments (ie, the ANSI C `void'
1227 -- argument) by `FunET UnitET res' rather than just `res' internally,
1228 -- although the latter representation is finally emitted into the binding
1229 -- file; this is because we need to know which types are functions (in
1230 -- particular, to distinguish between `Ptr a' and `FunPtr a')
1231 --
1232 -- * aliased types (`DefinedET') are represented by a string plus their C
1233 -- declaration; the latter is for functions interpreting the following
1234 -- structure; an aliased type is always a pointer type that is contained in
1235 -- the pointer map (and got there either from a .chi or from a pointer hook
1236 -- in the same module)
1237 --
1238 -- * the representation for pointers does not distinguish between normal,
1239 -- function, foreign, and stable pointers; function pointers are identified
1240 -- by their argument and foreign and stable pointers are only used
1241 -- indirectly, by referring to type names introduced by a `pointer' hook
1242 --
1243 data ExtType = FunET ExtType ExtType -- function
1244 | IOET ExtType -- operation with side effect
1245 | PtrET ExtType -- typed pointer
1246 | DefinedET CDecl HsPtrRep -- aliased type
1247 | PrimET CPrimType -- basic C type
1248 | UnitET -- void
1249
1250 instance Eq ExtType where
1251 (FunET t1 t2 ) == (FunET t1' t2' ) = t1 == t1' && t2 == t2'
1252 (IOET t ) == (IOET t' ) = t == t'
1253 (PtrET t ) == (PtrET t' ) = t == t'
1254 (DefinedET _ rep ) == (DefinedET _ rep' ) = rep == rep'
1255 (PrimET t ) == (PrimET t' ) = t == t'
1256 UnitET == UnitET = True
1257
1258 -- composite C type
1259 --
1260 data CompType = ExtType ExtType -- external type
1261 | SUType CStructUnion -- structure or union
1262
1263 -- check whether an external type denotes a function type
1264 --
1265 isFunExtType :: ExtType -> Bool
1266 isFunExtType (FunET _ _) = True
1267 isFunExtType (IOET _ ) = True
1268 isFunExtType (DefinedET _ (isFun,_,_,_)) = isFun
1269 isFunExtType _ = False
1270
1271 -- pretty print an external type
1272 --
1273 -- * a previous version of this function attempted to not print unnecessary
1274 -- brackets; this however doesn't work consistently due to `DefinedET'; so,
1275 -- we give up on the idea (preferring simplicity)
1276 --
1277 showExtType :: ExtType -> String
1278 showExtType (FunET UnitET res) = showExtType res
1279 showExtType (FunET arg res) = "(" ++ showExtType arg ++ " -> "
1280 ++ showExtType res ++ ")"
1281 showExtType (IOET t) = "(IO " ++ showExtType t ++ ")"
1282 showExtType (PtrET t) = let ptrCon = if isFunExtType t
1283 then "FunPtr" else "Ptr"
1284 in
1285 "(" ++ ptrCon ++ " " ++ showExtType t
1286 ++ ")"
1287 showExtType (DefinedET _ (_,_,_,str)) = str
1288 showExtType (PrimET CPtrPT) = "(Ptr ())"
1289 showExtType (PrimET CFunPtrPT) = "(FunPtr ())"
1290 showExtType (PrimET CCharPT) = "CChar"
1291 showExtType (PrimET CUCharPT) = "CUChar"
1292 showExtType (PrimET CSCharPT) = "CSChar"
1293 showExtType (PrimET CIntPT) = "CInt"
1294 showExtType (PrimET CShortPT) = "CShort"
1295 showExtType (PrimET CLongPT) = "CLong"
1296 showExtType (PrimET CLLongPT) = "CLLong"
1297 showExtType (PrimET CUIntPT) = "CUInt"
1298 showExtType (PrimET CUShortPT) = "CUShort"
1299 showExtType (PrimET CULongPT) = "CULong"
1300 showExtType (PrimET CULLongPT) = "CULLong"
1301 showExtType (PrimET CFloatPT) = "CFloat"
1302 showExtType (PrimET CDoublePT) = "CDouble"
1303 showExtType (PrimET CLDoublePT) = "CLDouble"
1304 showExtType (PrimET (CSFieldPT bs)) = "CInt{-:" ++ show bs ++ "-}"
1305 showExtType (PrimET (CUFieldPT bs)) = "CUInt{-:" ++ show bs ++ "-}"
1306 showExtType UnitET = "()"
1307
1308 -- compute the type of the C function declared by the given C object
1309 --
1310 -- * the identifier specifies in which of the declarators we are interested
1311 --
1312 -- * if the third argument is `True', the function result should not be
1313 -- wrapped into an `IO' type
1314 --
1315 -- * the caller has to guarantee that the object does indeed refer to a
1316 -- function
1317 --
1318 extractFunType :: Position -> CDecl -> Bool ->
1319 GB ([Maybe HsPtrRep], ExtType)
1320 extractFunType pos cdecl isPure =
1321 do
1322 -- remove all declarators except that of the function we are processing;
1323 -- then, extract the functions arguments and result type (also check that
1324 -- the function is not variadic); finally, compute the external type for
1325 -- the result
1326 --
1327 let (args, resultDecl, variadic) = funResultAndArgs cdecl
1328 when variadic $
1329 variadicErr pos cpos
1330 preResultType <- liftM (snd . expandSpecialPtrs) $
1331 extractSimpleType pos resultDecl
1332 --
1333 -- we can now add the `IO' monad if this is no pure function
1334 --
1335 let resultType = if isPure
1336 then preResultType
1337 else IOET preResultType
1338 --
1339 -- compute function arguments and create a function type (a function
1340 -- prototype with `void' as its single argument declares a nullary
1341 -- function)
1342 --
1343 (foreignSyn, argTypes) <- liftM (unzip . map expandSpecialPtrs) $
1344 mapM (extractSimpleType pos) args
1345
1346 return (foreignSyn, foldr FunET resultType argTypes)
1347 where
1348 cpos = posOf cdecl
1349
1350 -- provide info on Haskell wrappers around C pointers
1351 expandSpecialPtrs :: ExtType -> (Maybe HsPtrRep, ExtType)
1352 -- no special treatment for a simple type synonym
1353 expandSpecialPtrs all@(DefinedET cdecl (_, CHSPtr, Nothing, _)) =
1354 (Nothing, PtrET all)
1355 -- all other Haskell pointer wrappings require
1356 -- special calling conventions
1357 expandSpecialPtrs all@(DefinedET cdecl hsPtrRep) =
1358 (Just hsPtrRep, PtrET all)
1359 -- non-pointer arguments are passed normal
1360 expandSpecialPtrs all = (Nothing, all)
1361
1362 -- compute a non-struct/union type from the given declaration
1363 --
1364 -- * the declaration may have at most one declarator
1365 --
1366 -- * C functions are represented as `Ptr (FunEt ...)' or `Addr' if in
1367 -- compatibility mode (ie, `--old-ffi=yes')
1368 --
1369 extractSimpleType :: Position -> CDecl -> GB ExtType
1370 extractSimpleType pos cdecl =
1371 do
1372 traceEnter
1373 ct <- extractCompType cdecl
1374 case ct of
1375 ExtType et -> return et
1376 SUType _ -> illegalStructUnionErr (posOf cdecl) pos
1377 where
1378 traceEnter = traceGenBind $
1379 "Entering `extractSimpleType'...\n"
1380
1381 -- compute a Haskell type for a type referenced in a C pointer type
1382 --
1383 -- * the declaration may have at most one declarator
1384 --
1385 -- * struct/union types are mapped to `()'
1386 --
1387 -- * NB: this is by definition not a result type
1388 --
1389 extractPtrType :: CDecl -> GB ExtType
1390 extractPtrType cdecl = do
1391 ct <- extractCompType cdecl
1392 case ct of
1393 ExtType et -> return et
1394 SUType _ -> return UnitET
1395
1396 -- compute a Haskell type from the given C declaration, where C functions are
1397 -- represented by function pointers
1398 --
1399 -- * the declaration may have at most one declarator
1400 --
1401 -- * all C pointers (including functions) are represented as `Addr' if in
1402 -- compatibility mode (--old-ffi)
1403 --
1404 -- * typedef'ed types are chased
1405 --
1406 -- * takes the pointer map into account
1407 --
1408 -- * IMPORTANT NOTE: `sizeAlignOf' relies on `DefinedET' only being produced
1409 -- for pointer types; if this ever changes, we need to
1410 -- handle `DefinedET's differently. The problem is that
1411 -- entries in the pointer map currently prevent
1412 -- `extractCompType' from looking further "into" the
1413 -- definition of that pointer.
1414 --
1415 extractCompType :: CDecl -> GB CompType
1416 extractCompType cdecl@(CDecl specs declrs ats) =
1417 if length declrs > 1
1418 then interr "GenBind.extractCompType: Too many declarators!"
1419 else case declrs of
1420 [(Just declr, _, size)] | isPtrDeclr declr -> ptrType declr
1421 | isFunDeclr declr -> funType
1422 | otherwise -> aliasOrSpecType size
1423 [] -> aliasOrSpecType Nothing
1424 where
1425 -- handle explicit pointer types
1426 --
1427 ptrType declr = do
1428 tracePtrType
1429 let declrs' = dropPtrDeclr declr -- remove indirection
1430 cdecl' = CDecl specs [(Just declrs', Nothing, Nothing)] ats
1431 oalias = checkForOneAliasName cdecl' -- is only an alias remaining?
1432 oHsRepr <- case oalias of
1433 Nothing -> return $ Nothing
1434 Just ide -> queryPtr (True, ide)
1435 case oHsRepr of
1436 Just repr -> ptrAlias repr -- got an alias
1437 Nothing -> do -- no alias => recurs
1438 ct <- extractCompType cdecl'
1439 returnX $ case ct of
1440 ExtType et -> PtrET et
1441 SUType _ -> PtrET UnitET
1442 --
1443 -- handle explicit function types
1444 --
1445 -- FIXME: we currently regard any functions as being impure (ie, being IO
1446 -- functions); is this ever going to be a problem?
1447 --
1448 funType = do
1449 traceFunType
1450 (_, et) <- extractFunType (posOf cdecl) cdecl False
1451 returnX et
1452 --
1453 -- handle all types, which are not obviously pointers or functions
1454 --
1455 aliasOrSpecType :: Maybe CExpr -> GB CompType
1456 aliasOrSpecType size = do
1457 traceAliasOrSpecType size
1458 case checkForOneAliasName cdecl of
1459 Nothing -> specType (posOf cdecl) specs size
1460 Just ide -> do -- this is a typedef alias
1461 traceAlias ide
1462 oHsRepr <- queryPtr (False, ide) -- check for pointer hook alias
1463 case oHsRepr of
1464 Nothing -> do -- skip current alias (only one)
1465 cdecl' <- getDeclOf ide
1466 let CDecl specs [(declr, init, _)] at =
1467 ide `simplifyDecl` cdecl'
1468 sdecl = CDecl specs [(declr, init, size)] at
1469 -- propagate `size' down (slightly kludgy)
1470 extractCompType sdecl
1471 Just repr -> ptrAlias repr -- found a pointer hook alias
1472 --
1473 -- compute the result for a pointer alias
1474 --
1475 ptrAlias (isFun, ptrTy, wrapped, tyArg) =
1476 returnX $ DefinedET cdecl (isFun, ptrTy, wrapped, tyArg)
1477 --
1478 -- wrap an `ExtType' into a `CompType' and convert parametrised pointers
1479 -- to `Addr' if needed
1480 --
1481 returnX retval@(PtrET et) = do
1482 keepOld <- getSwitch oldFFI
1483 if keepOld
1484 then return $ ExtType (PrimET CPtrPT)
1485 else return $ ExtType retval
1486 returnX retval = return $ ExtType retval
1487 --
1488 tracePtrType = traceGenBind $ "extractCompType: explicit pointer type\n"
1489 traceFunType = traceGenBind $ "extractCompType: explicit function type\n"
1490 traceAliasOrSpecType Nothing = traceGenBind $
1491 "extractCompType: checking for alias\n"
1492 traceAliasOrSpecType (Just _) = traceGenBind $
1493 "extractCompType: checking for alias of bitfield\n"
1494 traceAlias ide = traceGenBind $
1495 "extractCompType: found an alias called `" ++ identToLexeme ide ++ "'\n"
1496
1497 -- C to Haskell type mapping described in the DOCU section
1498 --
1499 typeMap :: [([CTypeSpec], ExtType)]
1500 typeMap = [([void] , UnitET ),
1501 ([char] , PrimET CCharPT ),
1502 ([unsigned, char] , PrimET CUCharPT ),
1503 ([signed, char] , PrimET CSCharPT ),
1504 ([signed] , PrimET CIntPT ),
1505 ([int] , PrimET CIntPT ),
1506 ([signed, int] , PrimET CIntPT ),
1507 ([short] , PrimET CShortPT ),
1508 ([short, int] , PrimET CShortPT ),
1509 ([signed, short] , PrimET CShortPT ),
1510 ([signed, short, int] , PrimET CShortPT ),
1511 ([long] , PrimET CLongPT ),
1512 ([long, int] , PrimET CLongPT ),
1513 ([signed, long] , PrimET CLongPT ),
1514 ([signed, long, int] , PrimET CLongPT ),
1515 ([long, long] , PrimET CLLongPT ),
1516 ([long, long, int] , PrimET CLLongPT ),
1517 ([signed, long, long] , PrimET CLLongPT ),
1518 ([signed, long, long, int] , PrimET CLLongPT ),
1519 ([unsigned] , PrimET CUIntPT ),
1520 ([unsigned, int] , PrimET CUIntPT ),
1521 ([unsigned, short] , PrimET CUShortPT ),
1522 ([unsigned, short, int] , PrimET CUShortPT ),
1523 ([unsigned, long] , PrimET CULongPT ),
1524 ([unsigned, long, int] , PrimET CULongPT ),
1525 ([unsigned, long, long] , PrimET CULLongPT ),
1526 ([unsigned, long, long, int] , PrimET CULLongPT ),
1527 ([float] , PrimET CFloatPT ),
1528 ([double] , PrimET CDoublePT ),
1529 ([long, double] , PrimET CLDoublePT),
1530 ([enum] , PrimET CIntPT )]
1531 where
1532 void = CVoidType undefined
1533 char = CCharType undefined
1534 short = CShortType undefined
1535 int = CIntType undefined
1536 long = CLongType undefined
1537 float = CFloatType undefined
1538 double = CDoubleType undefined
1539 signed = CSignedType undefined
1540 unsigned = CUnsigType undefined
1541 enum = CEnumType undefined undefined
1542
1543 -- compute the complex (external) type determined by a list of type specifiers
1544 --
1545 -- * may not be called for a specifier that defines a typedef alias
1546 --
1547 specType :: Position -> [CDeclSpec] -> Maybe CExpr -> GB CompType
1548 specType cpos specs osize =
1549 let tspecs = [ts | CTypeSpec ts <- specs]
1550 in case lookupTSpec tspecs typeMap of
1551 Just et | isUnsupportedType et -> unsupportedTypeSpecErr cpos
1552 | isNothing osize -> return $ ExtType et -- not a bitfield
1553 | otherwise -> bitfieldSpec tspecs et osize -- bitfield
1554 Nothing ->
1555 case tspecs of
1556 [CSUType cu _] -> return $ SUType cu -- struct or union
1557 [CEnumType _ _] -> return $ ExtType (PrimET CIntPT) -- enum
1558 [CTypeDef _ _] -> interr "GenBind.specType: Illegal typedef alias!"
1559 _ -> illegalTypeSpecErr cpos
1560 where
1561 lookupTSpec = lookupBy matches
1562 --
1563 isUnsupportedType (PrimET et) = size et == 0 -- can't be a bitfield (yet)
1564 isUnsupportedType _ = False
1565 --
1566 -- check whether two type specifier lists denote the same type; handles
1567 -- types like `long long' correctly, as `deleteBy' removes only the first
1568 -- occurrence of the given element
1569 --
1570 matches :: [CTypeSpec] -> [CTypeSpec] -> Bool
1571 [] `matches` [] = True
1572 [] `matches` (_:_) = False
1573 (spec:specs) `matches` specs'
1574 | any (eqSpec spec) specs' = specs `matches` deleteBy eqSpec spec specs'
1575 | otherwise = False
1576 --
1577 eqSpec (CVoidType _) (CVoidType _) = True
1578 eqSpec (CCharType _) (CCharType _) = True
1579 eqSpec (CShortType _) (CShortType _) = True
1580 eqSpec (CIntType _) (CIntType _) = True
1581 eqSpec (CLongType _) (CLongType _) = True
1582 eqSpec (CFloatType _) (CFloatType _) = True
1583 eqSpec (CDoubleType _) (CDoubleType _) = True
1584 eqSpec (CSignedType _) (CSignedType _) = True
1585 eqSpec (CUnsigType _) (CUnsigType _) = True
1586 eqSpec (CSUType _ _) (CSUType _ _) = True
1587 eqSpec (CEnumType _ _) (CEnumType _ _) = True
1588 eqSpec (CTypeDef _ _) (CTypeDef _ _) = True
1589 eqSpec _ _ = False
1590 --
1591 bitfieldSpec :: [CTypeSpec] -> ExtType -> Maybe CExpr -> GB CompType
1592 bitfieldSpec tspecs et (Just sizeExpr) = -- never called with `Nothing'
1593 do
1594 let pos = posOf sizeExpr
1595 sizeResult <- evalConstCExpr sizeExpr
1596 case sizeResult of
1597 FloatResult _ -> illegalConstExprErr pos "a float result"
1598 IntResult size' -> do
1599 let size = fromInteger size'
1600 case et of
1601 PrimET CUIntPT -> returnCT $ CUFieldPT size
1602 PrimET CIntPT
1603 | [signed] `matches` tspecs
1604 || [signed, int] `matches` tspecs -> returnCT $ CSFieldPT size
1605 | [int] `matches` tspecs ->
1606 returnCT $ if bitfieldIntSigned then CSFieldPT size
1607 else CUFieldPT size
1608 _ -> illegalFieldSizeErr pos
1609 where
1610 returnCT = return . ExtType . PrimET
1611 --
1612 int = CIntType undefined
1613 signed = CSignedType undefined
1614
1615
1616 -- offset and size computations
1617 -- ----------------------------
1618
1619 -- precise size representation
1620 --
1621 -- * this is a pair of a number of octets and a number of bits
1622 --
1623 -- * if the number of bits is nonzero, the octet component is aligned by the
1624 -- alignment constraint for `CIntPT' (important for accessing bitfields with
1625 -- more than 8 bits)
1626 --
1627 data BitSize = BitSize Int Int
1628 deriving (Eq, Show)
1629
1630 -- ordering relation compares in terms of required storage units
1631 --
1632 instance Ord BitSize where
1633 bs1@(BitSize o1 b1) < bs2@(BitSize o2 b2) =
1634 padBits bs1 < padBits bs2 || (o1 == o2 && b1 < b2)
1635 bs1 <= bs2 = bs1 < bs2 || bs1 == bs2
1636 -- the <= instance is needed for Ord's compare functions, which is used in
1637 -- the defaults for all other members
1638
1639 -- add two bit size values
1640 --
1641 addBitSize :: BitSize -> BitSize -> BitSize
1642 addBitSize (BitSize o1 b1) (BitSize o2 b2) = BitSize (o1 + o2 + overflow) rest
1643 where
1644 bitsPerBitfield = size CIntPT * 8
1645 (overflow, rest) = (b1 + b2) `divMod` bitsPerBitfield
1646
1647 -- pad any storage unit that is partially used by a bitfield
1648 --
1649 padBits :: BitSize -> Int
1650 padBits (BitSize o 0) = o
1651 padBits (BitSize o _) = o + size CIntPT
1652
1653 -- compute the offset of the declarator in the second argument when it is
1654 -- preceded by the declarators in the first argument
1655 --
1656 offsetInStruct :: [CDecl] -> CDecl -> CStructTag -> GB BitSize
1657 offsetInStruct [] _ _ = return $ BitSize 0 0
1658 offsetInStruct decls decl tag =
1659 do
1660 (offset, _) <- sizeAlignOfStruct decls tag
1661 (_, align) <- sizeAlignOf decl
1662 return $ alignOffset offset align
1663
1664 -- compute the size and alignment (no padding at the end) of a set of
1665 -- declarators from a struct
1666 --
1667 sizeAlignOfStruct :: [CDecl] -> CStructTag -> GB (BitSize, Int)
1668 sizeAlignOfStruct [] _ = return (BitSize 0 0, 1)
1669 sizeAlignOfStruct decls CStructTag =
1670 do
1671 (offset, preAlign) <- sizeAlignOfStruct (init decls) CStructTag
1672 (size, align) <- sizeAlignOf (last decls)
1673 let sizeOfStruct = alignOffset offset align `addBitSize` size
1674 align' = if align > 0 then align else bitfieldAlignment
1675 alignOfStruct = preAlign `max` align'
1676 return (sizeOfStruct, alignOfStruct)
1677 sizeAlignOfStruct decls CUnionTag =
1678 do
1679 (sizes, aligns) <- mapAndUnzipM sizeAlignOf decls
1680 let aligns' = [if align > 0 then align else bitfieldAlignment
1681 | align <- aligns]
1682 return (maximum sizes, maximum aligns')
1683
1684 -- compute the size and alignment of the declarators forming a struct
1685 -- including any end-of-struct padding that is needed to make the struct ``tile
1686 -- in an array'' (K&R A7.4.8)
1687 --
1688 sizeAlignOfStructPad :: [CDecl] -> CStructTag -> GB (BitSize, Int)
1689 sizeAlignOfStructPad decls tag =
1690 do
1691 (size, align) <- sizeAlignOfStruct decls tag
1692 return (alignOffset size align, align)
1693
1694 -- compute the size and alignment constraint of a given C declaration
1695 --
1696 sizeAlignOf :: CDecl -> GB (BitSize, Int)
1697 --
1698 -- * we make use of the assertion that `extractCompType' can only return a
1699 -- `DefinedET' when the declaration is a pointer declaration
1700 --
1701 sizeAlignOf (CDecl specs [(Just declr, _, size)] ats) | isArrDeclr declr =
1702 interr $ "sizeAlignOf: calculating size of constant array not supported."
1703 sizeAlignOf cdecl =
1704 do
1705 ct <- extractCompType cdecl
1706 case ct of
1707 ExtType (FunET _ _ ) -> return (bitSize CFunPtrPT,
1708 alignment CFunPtrPT)
1709 ExtType (IOET _ ) -> interr "GenBind.sizeof: Illegal IO type!"
1710 ExtType (PtrET t )
1711 | isFunExtType t -> return (bitSize CFunPtrPT,
1712 alignment CFunPtrPT)
1713 | otherwise -> return (bitSize CPtrPT, alignment CPtrPT)
1714 ExtType (DefinedET _ _ ) -> return (bitSize CPtrPT, alignment CPtrPT)
1715 -- FIXME: The defined type could be a function pointer!!!
1716 ExtType (PrimET pt ) -> return (bitSize pt, alignment pt)
1717 ExtType UnitET -> voidFieldErr (posOf cdecl)
1718 SUType su ->
1719 do
1720 let (fields, tag) = structMembers su
1721 fields' <- let ide = structName su
1722 in
1723 if (not . null $ fields) || isNothing ide
1724 then return fields
1725 else do -- get the real...
1726 tag <- findTag (fromJust ide) -- ...definition
1727 case tag of
1728 Just (StructUnionCT su) -> return
1729 (fst . structMembers $ su)
1730 _ -> return fields
1731 sizeAlignOfStructPad fields' tag
1732 where
1733 bitSize et | sz < 0 = BitSize 0 (-sz) -- size is in bits
1734 | otherwise = BitSize sz 0
1735 where
1736 sz = size et
1737
1738 -- apply the given alignment constraint at the given offset
1739 --
1740 -- * if the alignment constraint is negative or zero, it is the alignment
1741 -- constraint for a bitfield
1742 --
1743 alignOffset :: BitSize -> Int -> BitSize
1744 alignOffset offset@(BitSize octetOffset bitOffset) align
1745 | align > 0 && bitOffset /= 0 = -- close bitfield first
1746 alignOffset (BitSize (octetOffset + (bitOffset + 7) `div` 8) 0) align
1747 | align > 0 && bitOffset == 0 = -- no bitfields involved
1748 BitSize (((octetOffset - 1) `div` align + 1) * align) 0
1749 | bitOffset == 0 -- start a bitfield
1750 || overflowingBitfield = -- .. or overflowing bitfield
1751 alignOffset offset bitfieldAlignment
1752 | otherwise = -- stays in current bitfield
1753 offset
1754 where
1755 bitsPerBitfield = size CIntPT * 8
1756 overflowingBitfield = bitOffset - align >= bitsPerBitfield
1757 -- note, `align' is negative
1758
1759
1760 -- constant folding
1761 -- ----------------
1762
1763 -- evaluate a constant expression
1764 --
1765 -- FIXME: this is a bit too simplistic, as the range of expression allowed as
1766 -- constant expression varies depending on the context in which the
1767 -- constant expression occurs
1768 --
1769 evalConstCExpr :: CExpr -> GB ConstResult
1770 evalConstCExpr (CComma _ at) =
1771 illegalConstExprErr (posOf at) "a comma expression"
1772 evalConstCExpr (CAssign _ _ _ at) =
1773 illegalConstExprErr (posOf at) "an assignment"
1774 evalConstCExpr (CCond b (Just t) e _) =
1775 do
1776 bv <- evalConstCExpr b
1777 case bv of
1778 IntResult bvi -> if bvi /= 0 then evalConstCExpr t else evalConstCExpr e
1779 FloatResult _ -> illegalConstExprErr (posOf b) "a float result"
1780 evalConstCExpr (CBinary op lhs rhs at) =
1781 do
1782 lhsVal <- evalConstCExpr lhs
1783 rhsVal <- evalConstCExpr rhs
1784 let (lhsVal', rhsVal') = usualArithConv lhsVal rhsVal
1785 applyBin (posOf at) op lhsVal' rhsVal'
1786 evalConstCExpr (CCast _ _ _) =
1787 todo "GenBind.evalConstCExpr: Casts are not implemented yet."
1788 evalConstCExpr (CUnary op arg at) =
1789 do
1790 argVal <- evalConstCExpr arg
1791 applyUnary (posOf at) op argVal
1792 evalConstCExpr (CSizeofExpr _ _) =
1793 todo "GenBind.evalConstCExpr: sizeof not implemented yet."
1794 evalConstCExpr (CSizeofType decl _) =
1795 do
1796 (size, _) <- sizeAlignOf decl
1797 return $ IntResult (fromIntegral . padBits $ size)
1798 evalConstCExpr (CAlignofExpr _ _) =
1799 todo "GenBind.evalConstCExpr: alignof (GNU C extension) not implemented yet."
1800 evalConstCExpr (CAlignofType decl _) =
1801 do
1802 (_, align) <- sizeAlignOf decl
1803 return $ IntResult (fromIntegral align)
1804 evalConstCExpr (CIndex _ _ at) =
1805 illegalConstExprErr (posOf at) "array indexing"
1806 evalConstCExpr (CCall _ _ at) =
1807 illegalConstExprErr (posOf at) "function call"
1808 evalConstCExpr (CMember _ _ _ at) =
1809 illegalConstExprErr (posOf at) "a . or -> operator"
1810 evalConstCExpr (CVar ide at) =
1811 do
1812 (cobj, _) <- findValueObj ide False
1813 case cobj of
1814 EnumCO ide (CEnum _ enumrs _) -> liftM IntResult $
1815 enumTagValue ide enumrs 0
1816 _ ->
1817 todo $ "GenBind.evalConstCExpr: variable names not implemented yet " ++
1818 show (posOf at)
1819 where
1820 -- FIXME: this is not very nice; instead, CTrav should have some support
1821 -- for determining enum tag values (but then, constant folding needs
1822 -- to be moved to CTrav, too)
1823 --
1824 -- Compute the tag value for `ide' defined in the given enumerator list
1825 --
1826 enumTagValue _ [] _ =
1827 interr "GenBind.enumTagValue: enumerator not in declaration"
1828 enumTagValue ide ((ide', oexpr):enumrs) val =
1829 do
1830 val' <- case oexpr of
1831 Nothing -> return val
1832 Just exp ->
1833 do
1834 val' <- evalConstCExpr exp
1835 case val' of
1836 IntResult val' -> return val'
1837 FloatResult _ ->
1838 illegalConstExprErr (posOf exp) "a float result"
1839 if ide == ide'
1840 then -- found the right enumerator
1841 return val'
1842 else -- continue down the enumerator list
1843 enumTagValue ide enumrs (val' + 1)
1844 evalConstCExpr (CConst c _) =
1845 evalCConst c
1846
1847 evalCConst :: CConst -> GB ConstResult
1848 evalCConst (CIntConst i _ ) = return $ IntResult i
1849 evalCConst (CCharConst c _ ) = return $ IntResult (toInteger (fromEnum c))
1850 evalCConst (CFloatConst s _ ) =
1851 todo "GenBind.evalCConst: Float conversion from literal misses."
1852 evalCConst (CStrConst s at) =
1853 illegalConstExprErr (posOf at) "a string constant"
1854
1855 usualArithConv :: ConstResult -> ConstResult -> (ConstResult, ConstResult)
1856 usualArithConv lhs@(FloatResult _) rhs = (lhs, toFloat rhs)
1857 usualArithConv lhs rhs@(FloatResult _) = (toFloat lhs, rhs)
1858 usualArithConv lhs rhs = (lhs, rhs)
1859
1860 toFloat :: ConstResult -> ConstResult
1861 toFloat x@(FloatResult _) = x
1862 toFloat (IntResult i) = FloatResult . fromIntegral $ i
1863
1864 applyBin :: Position
1865 -> CBinaryOp
1866 -> ConstResult
1867 -> ConstResult
1868 -> GB ConstResult
1869 applyBin cpos CMulOp (IntResult x)
1870 (IntResult y) = return $ IntResult (x * y)
1871 applyBin cpos CMulOp (FloatResult x)
1872 (FloatResult y) = return $ FloatResult (x * y)
1873 applyBin cpos CDivOp (IntResult x)
1874 (IntResult y) = return $ IntResult (x `div` y)
1875 applyBin cpos CDivOp (FloatResult x)
1876 (FloatResult y) = return $ FloatResult (x / y)
1877 applyBin cpos CRmdOp (IntResult x)
1878 (IntResult y) = return$ IntResult (x `mod` y)
1879 applyBin cpos CRmdOp (FloatResult x)
1880 (FloatResult y) =
1881 illegalConstExprErr cpos "a % operator applied to a float"
1882 applyBin cpos CAddOp (IntResult x)
1883 (IntResult y) = return $ IntResult (x + y)
1884 applyBin cpos CAddOp (FloatResult x)
1885 (FloatResult y) = return $ FloatResult (x + y)
1886 applyBin cpos CSubOp (IntResult x)
1887 (IntResult y) = return $ IntResult (x - y)
1888 applyBin cpos CSubOp (FloatResult x)
1889 (FloatResult y) = return $ FloatResult (x - y)
1890 applyBin cpos CShlOp (IntResult x)
1891 (IntResult y) = return $ IntResult (x * 2^y)
1892 applyBin cpos CShlOp (FloatResult x)
1893 (FloatResult y) =
1894 illegalConstExprErr cpos "a << operator applied to a float"
1895 applyBin cpos CShrOp (IntResult x)
1896 (IntResult y) = return $ IntResult (x `div` 2^y)
1897 applyBin cpos CShrOp (FloatResult x)
1898 (FloatResult y) =
1899 illegalConstExprErr cpos "a >> operator applied to a float"
1900 applyBin cpos CAndOp (IntResult x)
1901 (IntResult y) = return $ IntResult (x .&. y)
1902 applyBin cpos COrOp (IntResult x)
1903 (IntResult y) = return $ IntResult (x .|. y)
1904 applyBin cpos CXorOp (IntResult x)
1905 (IntResult y) = return $ IntResult (x `xor` y)
1906 applyBin cpos _ (IntResult x)
1907 (IntResult y) =
1908 todo "GenBind.applyBin: Not yet implemented operator in constant expression."
1909 applyBin cpos _ (FloatResult x)
1910 (FloatResult y) =
1911 todo "GenBind.applyBin: Not yet implemented operator in constant expression."
1912 applyBin _ _ _ _ =
1913 interr "GenBind.applyBinOp: Illegal combination!"
1914
1915 applyUnary :: Position -> CUnaryOp -> ConstResult -> GB ConstResult
1916 applyUnary cpos CPreIncOp _ =
1917 illegalConstExprErr cpos "a ++ operator"
1918 applyUnary cpos CPreDecOp _ =
1919 illegalConstExprErr cpos "a -- operator"
1920 applyUnary cpos CPostIncOp _ =
1921 illegalConstExprErr cpos "a ++ operator"
1922 applyUnary cpos CPostDecOp _ =
1923 illegalConstExprErr cpos "a -- operator"
1924 applyUnary cpos CAdrOp _ =
1925 illegalConstExprErr cpos "a & operator"
1926 applyUnary cpos CIndOp _ =
1927 illegalConstExprErr cpos "a * operator"
1928 applyUnary cpos CPlusOp arg = return arg
1929 applyUnary cpos CMinOp (IntResult x) = return (IntResult (-x))
1930 applyUnary cpos CMinOp (FloatResult x) = return (FloatResult (-x))
1931 applyUnary cpos CCompOp (IntResult x) = return (IntResult (complement x))
1932 applyUnary cpos CNegOp (IntResult x) =
1933 let r = toInteger . fromEnum $ (x == 0)
1934 in return (IntResult r)
1935 applyUnary cpos CNegOp (FloatResult _) =
1936 illegalConstExprErr cpos "! applied to a float"
1937
1938
1939 -- auxiliary functions
1940 -- --------------------
1941
1942 -- create an identifier without position information
1943 --
1944 noPosIdent :: String -> Ident
1945 noPosIdent = onlyPosIdent nopos
1946
1947 -- print trace message
1948 --
1949 traceGenBind :: String -> GB ()
1950 traceGenBind = putTraceStr traceGenBindSW
1951
1952 -- generic lookup
1953 --
1954 lookupBy :: (a -> a -> Bool) -> a -> [(a, b)] -> Maybe b
1955 lookupBy eq x = fmap snd . find (eq x . fst)
1956
1957 -- maps some monad operation into a `Maybe', discarding the result
1958 --
1959 mapMaybeM_ :: Monad m => (a -> m b) -> Maybe a -> m ()
1960 mapMaybeM_ m Nothing = return ()
1961 mapMaybeM_ m (Just a) = m a >> return ()
1962
1963
1964 -- error messages
1965 -- --------------
1966
1967 unknownFieldErr :: Position -> Ident -> GB a
1968 unknownFieldErr cpos ide =
1969 raiseErrorCTExc (posOf ide)
1970 ["Unknown member name!",
1971 "The structure has no member called `" ++ identToLexeme ide
1972 ++ "'. The structure is defined at",
1973 show cpos ++ "."]
1974
1975 illegalStructUnionErr :: Position -> Position -> GB a
1976 illegalStructUnionErr cpos pos =
1977 raiseErrorCTExc pos
1978 ["Illegal structure or union type!",
1979 "There is not automatic support for marshaling of structures and",
1980 "unions; the offending type is declared at "
1981 ++ show cpos ++ "."]
1982
1983 illegalTypeSpecErr :: Position -> GB a
1984 illegalTypeSpecErr cpos =
1985 raiseErrorCTExc cpos
1986 ["Illegal type!",
1987 "The type specifiers of this declaration do not form a legal ANSI C(89) \
1988 \type."
1989 ]
1990
1991 unsupportedTypeSpecErr :: Position -> GB a
1992 unsupportedTypeSpecErr cpos =
1993 raiseErrorCTExc cpos
1994 ["Unsupported type!",
1995 "The type specifier of this declaration is not supported by your C \
1996 \compiler."
1997 ]
1998
1999 variadicErr :: Position -> Position -> GB a
2000 variadicErr pos cpos =
2001 raiseErrorCTExc pos
2002 ["Variadic function!",
2003 "Calling variadic functions is not supported by the FFI; the function",
2004 "is defined at " ++ show cpos ++ "."]
2005
2006 illegalConstExprErr :: Position -> String -> GB a
2007 illegalConstExprErr cpos hint =
2008 raiseErrorCTExc cpos ["Illegal constant expression!",
2009 "Encountered " ++ hint ++ " in a constant expression,",
2010 "which ANSI C89 does not permit."]
2011
2012 voidFieldErr :: Position -> GB a
2013 voidFieldErr cpos =
2014 raiseErrorCTExc cpos ["Void field in struct!",
2015 "Attempt to access a structure field of type void."]
2016
2017 structExpectedErr :: Ident -> GB a
2018 structExpectedErr ide =
2019 raiseErrorCTExc (posOf ide)
2020 ["Expected a structure or union!",
2021 "Attempt to access member `" ++ identToLexeme ide ++ "' in something not",
2022 "a structure or union."]
2023
2024 ptrExpectedErr :: Position -> GB a
2025 ptrExpectedErr pos =
2026 raiseErrorCTExc pos
2027 ["Expected a pointer object!",
2028 "Attempt to dereference a non-pointer object or to use it in a `pointer' \
2029 \hook."]
2030
2031 illegalStablePtrErr :: Position -> GB a
2032 illegalStablePtrErr pos =
2033 raiseErrorCTExc pos
2034 ["Illegal use of a stable pointer!",
2035 "Class hooks cannot be used for stable pointers."]
2036
2037 pointerTypeMismatchErr :: Position -> String -> String -> GB a
2038 pointerTypeMismatchErr pos className superName =
2039 raiseErrorCTExc pos
2040 ["Pointer type mismatch!",
2041 "The pointer of the class hook for `" ++ className
2042 ++ "' is of a different kind",
2043 "than that of the class hook for `" ++ superName ++ "'; this is illegal",
2044 "as the latter is defined to be an (indirect) superclass of the former."]
2045
2046 illegalFieldSizeErr :: Position -> GB a
2047 illegalFieldSizeErr cpos =
2048 raiseErrorCTExc cpos
2049 ["Illegal field size!",
2050 "Only signed and unsigned `int' types may have a size annotation."]
2051
2052 derefBitfieldErr :: Position -> GB a
2053 derefBitfieldErr pos =
2054 raiseErrorCTExc pos
2055 ["Illegal dereferencing of a bit field!",
2056 "Bit fields cannot be dereferenced."]
2057
2058 resMarshIllegalInErr :: Position -> GB a
2059 resMarshIllegalInErr pos =
2060 raiseErrorCTExc pos
2061 ["Malformed result marshalling!",
2062 "There may not be an \"in\" marshaller for the result."]
2063
2064 resMarshIllegalTwoCValErr :: Position -> GB a
2065 resMarshIllegalTwoCValErr pos =
2066 raiseErrorCTExc pos
2067 ["Malformed result marshalling!",
2068 "Two C values (i.e., the `&' symbol) are not allowed for the result."]
2069
2070 marshArgMismatchErr :: Position -> String -> GB a
2071 marshArgMismatchErr pos reason =
2072 raiseErrorCTExc pos
2073 ["Function arity mismatch!",
2074 reason]
2075
2076 noDftMarshErr :: Position -> String -> String -> [ExtType] -> GB a
2077 noDftMarshErr pos inOut hsTy cTys =
2078 raiseErrorCTExc pos
2079 ["Missing " ++ inOut ++ " marshaller!",
2080 "There is no default marshaller for this combination of Haskell and \
2081 \C type:",
2082 "Haskell type: " ++ hsTy,
2083 "C type : " ++ concat (intersperse " " (map showExtType cTys))]