Debian Codegraph @

c2hs/gen/GBMonad.hs

raw symbols SCIP
1 -- C->Haskell Compiler: monad for the binding generator
2 --
3 -- Author : Manuel M T Chakravarty
4 -- Derived: 18 February 2 (extracted from GenBind.hs)
5 --
6 -- Version $Revision: 1.1 $ from $Date: 2004/11/21 21:05:41 $
7 --
8 -- Copyright (c) [2002..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 -- This modules defines the monad and related utility routines for the code
23 -- that implements the expansion of the binding hooks.
24 --
25 --- DOCU ----------------------------------------------------------------------
26 --
27 -- language: Haskell 98
28 --
29 -- Translation table handling for enumerators:
30 -- -------------------------------------------
31 --
32 -- First a translation table lookup on the original identifier of the
33 -- enumerator is done. If that doesn't match and the prefix can be removed
34 -- from the identifier, a second lookup on the identifier without the prefix
35 -- is performed. If this also doesn't match, the identifier without prefix
36 -- (possible after underscoreToCase translation is returned). If there is a
37 -- match, the translation (without any further stripping of prefix) is
38 -- returned.
39 --
40 -- Pointer map
41 -- -----------
42 --
43 -- Pointer hooks allow the use to customise the Haskell types to which C
44 -- pointer types are mapped. The globally maintained map essentially maps C
45 -- pointer types to Haskell pointer types. The representation of the Haskell
46 -- types is defined by the `type' or `newtype' declaration emitted by the
47 -- corresponding pointer hook. However, the map stores a flag that tells
48 -- whether the C type is itself the pointer type in question or whether it is
49 -- pointers to this C type that should be mapped as specified. The pointer
50 -- map is dumped into and read from `.chi' files.
51 --
52 -- Haskell object map
53 -- ------------------
54 --
55 -- Some features require information about Haskell objects defined by c2hs.
56 -- Therefore, the Haskell object map maintains the necessary information
57 -- about these Haskell objects. The Haskell object map is dumped into and
58 -- read from `.chi' files.
59 --
60 --- TODO ----------------------------------------------------------------------
61 --
62 -- * Look up in translation tables is naive - this probably doesn't affect
63 -- costs much, but at some point a little profiling might be beneficial.
64 --
65
66 module GBMonad (
67 TransFun, transTabToTransFun,
68
69 HsObject(..), GB, HsPtrRep, initialGBState, setContext, getLibrary,
70 getPrefix, getLock, delayCode, getDelayedCode, ptrMapsTo, queryPtr, objIs,
71 queryObj, queryClass, queryPointer, mergeMaps, dumpMaps
72 ) where
73
74 -- standard libraries
75 import Data.Char (toUpper, toLower, isSpace)
76 import Data.List (find)
77 import Data.Maybe (fromMaybe)
78
79 -- Compiler Toolkit
80 import Position (Position, Pos(posOf), nopos, builtinPos)
81 import Errors (interr)
82 import Idents (Ident, identToLexeme, onlyPosIdent)
83 import Map (Map)
84 import qualified Map as Map (empty, insert, lookup, fromList, toList, union)
85
86 -- C -> Haskell
87 import C (CT, readCT, transCT, raiseErrorCTExc)
88
89 -- friends
90 import CHS (CHSModule(..), CHSFrag(..), CHSHook(..), CHSTrans(..),
91 CHSAccess(..), CHSAPath(..), CHSPtrType(..))
92
93
94 -- translation tables
95 -- ------------------
96
97 -- takes an identifier to a lexeme including a potential mapping by a
98 -- translation table
99 --
100 type TransFun = Ident -> String
101
102 -- translation function for the `underscoreToCase' flag
103 --
104 underscoreToCase :: TransFun
105 underscoreToCase ide = let lexeme = identToLexeme ide
106 ps = filter (not . null) . parts $ lexeme
107 in
108 concat . map adjustCase $ ps
109 where
110 parts s = let (l, s') = break (== '_') s
111 in
112 l : case s' of
113 [] -> []
114 (_:s'') -> parts s''
115
116 adjustCase (c:cs) = toUpper c : map toLower cs
117
118 -- takes an identifier association table to a translation function
119 --
120 -- * if first argument is `True', identifiers that are not found in the
121 -- translation table are subjected to `underscoreToCase'
122 --
123 -- * the details of handling the prefix are given in the DOCU section at the
124 -- beginning of this file
125 --
126 transTabToTransFun :: String -> CHSTrans -> TransFun
127 transTabToTransFun prefix (CHSTrans _2Case table) =
128 \ide -> let
129 lexeme = identToLexeme ide
130 dft = if _2Case -- default uses maybe the...
131 then underscoreToCase ide -- ..._2case transformed...
132 else lexeme -- ...lexeme
133 in
134 case lookup ide table of -- lookup original ident
135 Just ide' -> identToLexeme ide' -- original ident matches
136 Nothing ->
137 case eat prefix lexeme of
138 Nothing -> dft -- no match & no prefix
139 Just eatenLexeme ->
140 let
141 eatenIde = onlyPosIdent (posOf ide) eatenLexeme
142 eatenDft = if _2Case
143 then underscoreToCase eatenIde
144 else eatenLexeme
145 in
146 case lookup eatenIde table of -- lookup without prefix
147 Nothing -> eatenDft -- orig ide without prefix
148 Just ide' -> identToLexeme ide' -- without prefix matched
149 where
150 -- try to eat prefix and return `Just partialLexeme' if successful
151 --
152 eat [] ('_':cs) = eat [] cs
153 eat [] cs = Just cs
154 eat (p:prefix) (c:cs) | toUpper p == toUpper c = eat prefix cs
155 | otherwise = Nothing
156 eat _ _ = Nothing
157
158
159 -- the local monad
160 -- ---------------
161
162 -- map that for maps C pointer types to Haskell types for pointer that have
163 -- been registered using a pointer hook
164 --
165 -- * the `Bool' indicates whether for a C type "ctype", we map "ctype" itself
166 -- or "*ctype"
167 --
168 -- * the co-domain details how this pointer is represented in Haskell.
169 -- See HsPtrRep.
170 --
171 type PointerMap = Map (Bool, Ident) HsPtrRep
172
173
174 -- Define how pointers are represented in Haskell.
175 --
176 -- * The first element is true if the pointer points to a function.
177 -- The second is the Haskell pointer type (plain
178 -- Ptr, ForeignPtr or StablePtr). The third field is (Just wrap) if the
179 -- pointer is wrapped in a newtype. Where "wrap"
180 -- contains the name of the Haskell data type that was defined for this
181 -- pointer. The forth element contains the type argument of the
182 -- Ptr, ForeignPtr or StablePtr and is the same as "wrap"
183 -- unless the user overrode it with the -> notation.
184 type HsPtrRep = (Bool, CHSPtrType, Maybe String, String)
185
186
187 -- map that maintains key information about some of the Haskell objects
188 -- generated by c2hs
189 --
190 -- NB: using records here avoids to run into a bug with deriving `Read' in GHC
191 -- 5.04.1
192 --
193 data HsObject = Pointer {
194 ptrTypeHO :: CHSPtrType, -- kind of pointer
195 isNewtypeHO :: Bool -- newtype?
196 }
197 | Class {
198 superclassHO :: (Maybe Ident),-- superclass
199 ptrHO :: Ident -- pointer
200 }
201 deriving (Show, Read)
202 type HsObjectMap = Map Ident HsObject
203
204 {- FIXME: What a mess...
205 instance Show HsObject where
206 show (Pointer ptrType isNewtype) =
207 "Pointer " ++ show ptrType ++ show isNewtype
208 show (Class osuper pointer ) =
209 "Class " ++ show ptrType ++ show isNewtype
210 -}
211 -- super kludgy (depends on Show instance of Ident)
212 instance Read Ident where
213 readsPrec _ ('`':lexeme) = let (ideChars, rest) = span (/= '\'') lexeme
214 in
215 if null ideChars
216 then []
217 else [(onlyPosIdent nopos ideChars, tail rest)]
218 readsPrec p (c:cs)
219 | isSpace c = readsPrec p cs
220 readsPrec _ _ = []
221
222 -- the local state consists of
223 --
224 -- (1) the dynamic library specified by the context hook,
225 -- (2) the prefix specified by the context hook,
226 -- (3) an optional wrapper function that acquires a lock, this may also
227 -- be specified on the command line
228 -- (3) the set of delayed code fragaments, ie, pieces of Haskell code that,
229 -- finally, have to be appended at the CHS module together with the hook
230 -- that created them (the latter allows avoid duplication of foreign
231 -- export declarations), and
232 -- (4) a map associating C pointer types with their Haskell representation
233 --
234 -- access to the attributes of the C structure tree is via the `CT' monad of
235 -- which we use an instance here
236 --
237 data GBState = GBState {
238 lib :: String, -- dynamic library
239 prefix :: String, -- prefix
240 mLock :: Maybe String, -- a lock function
241 frags :: [(CHSHook, CHSFrag)], -- delayed code (with hooks)
242 ptrmap :: PointerMap, -- pointer representation
243 objmap :: HsObjectMap -- generated Haskell objects
244 }
245
246 type GB a = CT GBState a
247
248 initialGBState :: Maybe String -> GBState
249 initialGBState mLock = GBState {
250 lib = "",
251 prefix = "",
252 mLock = mLock,
253 frags = [],
254 ptrmap = Map.empty,
255 objmap = Map.empty
256 }
257
258 -- set the dynamic library and library prefix
259 --
260 setContext :: (Maybe String) -> (Maybe String) -> (Maybe String) ->
261 GB ()
262 setContext lib prefix newMLock =
263 transCT $ \state -> (state {lib = fromMaybe "" lib,
264 prefix = fromMaybe "" prefix,
265 mLock = case newMLock of
266 Nothing -> mLock state
267 Just _ -> newMLock },
268 ())
269
270 -- get the dynamic library
271 --
272 getLibrary :: GB String
273 getLibrary = readCT lib
274
275 -- get the prefix string
276 --
277 getPrefix :: GB String
278 getPrefix = readCT prefix
279
280 -- get the lock function
281 getLock :: GB (Maybe String)
282 getLock = readCT mLock
283
284 -- add code to the delayed fragments (the code is made to start at a new line)
285 --
286 -- * currently only code belonging to call hooks can be delayed
287 --
288 -- * if code for the same call hook (ie, same C function) is delayed
289 -- repeatedly only the first entry is stored; it is checked that the hooks
290 -- specify the same flags (ie, produce the same delayed code)
291 --
292 delayCode :: CHSHook -> String -> GB ()
293 delayCode hook str =
294 do
295 frags <- readCT frags
296 frags' <- delay hook frags
297 transCT (\state -> (state {frags = frags'}, ()))
298 where
299 newEntry = (hook, (CHSVerb ("\n" ++ str) (posOf hook)))
300 --
301 delay hook@(CHSCall isFun isUns _ ide oalias _) frags =
302 case find (\(hook', _) -> hook' == hook) frags of
303 Just (CHSCall isFun' isUns' _ ide' _ _, _)
304 | isFun == isFun'
305 && isUns == isUns'
306 && ide == ide' -> return frags
307 | otherwise -> err (posOf ide) (posOf ide')
308 Nothing -> return $ frags ++ [newEntry]
309 delay _ _ =
310 interr "GBMonad.delayCode: Illegal delay!"
311 --
312 err = incompatibleCallHooksErr
313
314 -- get the complete list of delayed fragments
315 --
316 getDelayedCode :: GB [CHSFrag]
317 getDelayedCode = readCT (map snd . frags)
318
319 -- add an entry to the pointer map
320 --
321 ptrMapsTo :: (Bool, Ident) -> HsPtrRep -> GB ()
322 (isStar, cName) `ptrMapsTo` hsRepr =
323 transCT (\state -> (state {
324 ptrmap = Map.insert (isStar, cName) hsRepr (ptrmap state)
325 }, ()))
326
327 -- query the pointer map
328 --
329 queryPtr :: (Bool, Ident) -> GB (Maybe HsPtrRep)
330 queryPtr pcName = do
331 fm <- readCT ptrmap
332 return $ Map.lookup pcName fm
333
334 -- add an entry to the Haskell object map
335 --
336 objIs :: Ident -> HsObject -> GB ()
337 hsName `objIs` obj =
338 transCT (\state -> (state {
339 objmap = Map.insert hsName obj (objmap state)
340 }, ()))
341
342 -- query the Haskell object map
343 --
344 queryObj :: Ident -> GB (Maybe HsObject)
345 queryObj hsName = do
346 fm <- readCT objmap
347 return $ Map.lookup hsName fm
348
349 -- query the Haskell object map for a class
350 --
351 -- * raise an error if the class cannot be found
352 --
353 queryClass :: Ident -> GB HsObject
354 queryClass hsName = do
355 let pos = posOf hsName
356 oobj <- queryObj hsName
357 case oobj of
358 Just obj@(Class _ _) -> return obj
359 Just _ -> classExpectedErr hsName
360 Nothing -> hsObjExpectedErr hsName
361
362 -- query the Haskell object map for a pointer
363 --
364 -- * raise an error if the pointer cannot be found
365 --
366 queryPointer :: Ident -> GB HsObject
367 queryPointer hsName = do
368 let pos = posOf hsName
369 oobj <- queryObj hsName
370 case oobj of
371 Just obj@(Pointer _ _) -> return obj
372 Just _ -> pointerExpectedErr hsName
373 Nothing -> hsObjExpectedErr hsName
374
375 -- merge the pointer and Haskell object maps
376 --
377 -- * currently, the read map overrides any entries for shared keys in the map
378 -- that is already in the monad; this is so that, if multiple import hooks
379 -- add entries for shared keys, the textually latest prevails; any local
380 -- entries are entered after all import hooks anyway
381 --
382 -- FIXME: This currently has several shortcomings:
383 -- * It just dies in case of a corrupted .chi file
384 -- * We should at least have the option to raise a warning if two
385 -- entries collide in the `objmap'. But it would be better to
386 -- implement qualified names.
387 -- * Do we want position information associated with the read idents?
388 --
389 mergeMaps :: String -> GB ()
390 mergeMaps str =
391 transCT (\state -> (state {
392 ptrmap = Map.union (ptrmap state) readPtrMap,
393 objmap = Map.union (objmap state) readObjMap
394 }, ()))
395 where
396 (ptrAssoc, objAssoc) = read str
397 readPtrMap = Map.fromList [((isStar, onlyPosIdent nopos ide), repr)
398 | ((isStar, ide), repr) <- ptrAssoc]
399 readObjMap = Map.fromList [(onlyPosIdent nopos ide, obj)
400 | (ide, obj) <- objAssoc]
401
402 -- convert the whole pointer and Haskell object maps into printable form
403 --
404 dumpMaps :: GB String
405 dumpMaps = do
406 ptrFM <- readCT ptrmap
407 objFM <- readCT objmap
408 let dumpable = ([((isStar, identToLexeme ide), repr)
409 | ((isStar, ide), repr) <- Map.toList ptrFM],
410 [(identToLexeme ide, obj)
411 | (ide, obj) <- Map.toList objFM])
412 return $ show dumpable
413
414
415 -- error messages
416 -- --------------
417
418 incompatibleCallHooksErr :: Position -> Position -> GB a
419 incompatibleCallHooksErr here there =
420 raiseErrorCTExc here
421 ["Incompatible call hooks!",
422 "There is a another call hook for the same C function at " ++ show there,
423 "The flags and C function name of the two hooks should be identical,",
424 "but they are not."]
425
426 classExpectedErr :: Ident -> GB a
427 classExpectedErr ide =
428 raiseErrorCTExc (posOf ide)
429 ["Expected a class name!",
430 "Expected `" ++ identToLexeme ide ++ "' to refer to a class introduced",
431 "by a class hook."]
432
433 pointerExpectedErr :: Ident -> GB a
434 pointerExpectedErr ide =
435 raiseErrorCTExc (posOf ide)
436 ["Expected a pointer name!",
437 "Expected `" ++ identToLexeme ide ++ "' to be a type name introduced by",
438 "a pointer hook."]
439
440 hsObjExpectedErr :: Ident -> GB a
441 hsObjExpectedErr ide =
442 raiseErrorCTExc (posOf ide)
443 ["Unknown name!",
444 "`" ++ identToLexeme ide ++ "' is unknown; it has *not* been defined by",
445 "a previous hook."]
446