Debian Codegraph @

c2hs/c/CTrav.hs

raw symbols SCIP
1 -- C->Haskell Compiler: traversals of C structure tree
2 --
3 -- Author : Manuel M. T. Chakravarty
4 -- Created: 16 October 99
5 --
6 -- Version $Revision: 1.1 $ from $Date: 2004/11/21 21:05:27 $
7 --
8 -- Copyright (c) [1999..2001] 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 provides for traversals of C structure trees. The C
23 -- traversal monad supports traversals that need convenient access to the
24 -- attributes of an attributed C structure tree. The monads state can still
25 -- be extended.
26 --
27 --- DOCU ----------------------------------------------------------------------
28 --
29 -- language: Haskell 98
30 --
31 -- Handling of redefined tag values
32 -- --------------------------------
33 --
34 -- Structures allow both
35 --
36 -- struct s {...} ...;
37 -- struct s ...;
38 --
39 -- and
40 --
41 -- struct s ...; /* this is called a forward reference */
42 -- struct s {...} ...;
43 --
44 -- In contrast enumerations only allow (in ANSI C)
45 --
46 -- enum e {...} ...;
47 -- enum e ...;
48 --
49 -- The function `defTag' handles both types and establishes an object
50 -- association from the tag identifier in the empty declaration (ie, the one
51 -- without `{...}') to the actually definition of the structure of
52 -- enumeration. This implies that when looking for the details of a
53 -- structure or enumeration, possibly a chain of references on tag
54 -- identifiers has to be chased. Note that the object association attribute
55 -- is _not_defined_ when the `{...}' part is present in a declaration.
56 --
57 --- TODO ----------------------------------------------------------------------
58 --
59 -- * `extractStruct' doesn't account for forward declarations that have no
60 -- full declaration yet; if `extractStruct' is called on such a declaration,
61 -- we have a user error, but currently an internal error is raised
62 --
63
64 module CTrav (CT, readCT, transCT, getCHeaderCT, runCT, throwCTExc, ifCTExc,
65 raiseErrorCTExc,
66 enter, enterObjs, leave, leaveObjs, defObj, findObj,
67 findObjShadow, defTag, findTag, findTagShadow,
68 applyPrefixToNameSpaces, getDefOf, refersToDef, refersToNewDef,
69 getDeclOf, findTypeObjMaybe, findTypeObj, findValueObj,
70 findFunObj,
71 --
72 -- C structure tree query functions
73 --
74 isTypedef, simplifyDecl, declrFromDecl, declrNamed,
75 declaredDeclr, declaredName, structMembers, expandDecl,
76 structName, enumName, tagName, isArrDeclr, isPtrDeclr, dropPtrDeclr,
77 isPtrDecl, isFunDeclr, structFromDecl, funResultAndArgs,
78 chaseDecl, findAndChaseDecl, checkForAlias,
79 checkForOneAliasName, lookupEnum, lookupStructUnion,
80 lookupDeclOrTag)
81 where
82
83 import Data.List (find)
84 import Data.Maybe (fromMaybe)
85 import Control.Monad (liftM)
86 import Control.Exception (assert)
87
88 import Position (Position, Pos(..), nopos)
89 import Errors (interr)
90 import Idents (Ident, dumpIdent, identToLexeme)
91 import Attributes (Attr(..), newAttrsOnlyPos)
92
93 import C2HSState (CST, nop, readCST, transCST, runCST, raiseError, catchExc,
94 throwExc, Traces(..), putTraceStr)
95 import CAST
96 import CAttrs (AttrC, getCHeader, enterNewRangeC, enterNewObjRangeC,
97 leaveRangeC, leaveObjRangeC, addDefObjC, lookupDefObjC,
98 lookupDefObjCShadow, addDefTagC, lookupDefTagC,
99 lookupDefTagCShadow, applyPrefix, getDefOfIdentC,
100 setDefOfIdentC, updDefOfIdentC, CObj(..), CTag(..),
101 CDef(..))
102
103
104 -- the C traversal monad
105 -- ---------------------
106
107 -- C traversal monad (EXPORTED ABSTRACTLY)
108 --
109 type CState s = (AttrC, s)
110 type CT s a = CST (CState s) a
111
112 -- read attributed structure tree
113 --
114 readAttrCCT :: (AttrC -> a) -> CT s a
115 readAttrCCT reader = readCST $ \(ac, _) -> reader ac
116
117 -- transform attributed structure tree
118 --
119 transAttrCCT :: (AttrC -> (AttrC, a)) -> CT s a
120 transAttrCCT trans = transCST $ \(ac, s) -> let
121 (ac', r) = trans ac
122 in
123 ((ac', s), r)
124
125 -- access to the user-defined state
126 --
127
128 -- read user-defined state (EXPORTED)
129 --
130 readCT :: (s -> a) -> CT s a
131 readCT reader = readCST $ \(_, s) -> reader s
132
133 -- transform user-defined state (EXPORTED)
134 --
135 transCT :: (s -> (s, a)) -> CT s a
136 transCT trans = transCST $ \(ac, s) -> let
137 (s', r) = trans s
138 in
139 ((ac, s'), r)
140
141 -- usage of a traversal monad
142 --
143
144 -- get the raw C header from the monad (EXPORTED)
145 --
146 getCHeaderCT :: CT s CHeader
147 getCHeaderCT = readAttrCCT getCHeader
148
149 -- execute a traversal monad (EXPORTED)
150 --
151 -- * given a traversal monad, an attribute structure tree, and a user
152 -- state, the transformed structure tree and monads result are returned
153 --
154 runCT :: CT s a -> AttrC -> s -> CST t (AttrC, a)
155 runCT m ac s = runCST m' (ac, s)
156 where
157 m' = do
158 r <- m
159 (ac, _) <- readCST id
160 return (ac, r)
161
162
163 -- exception handling
164 -- ------------------
165
166 -- exception identifier
167 --
168 ctExc :: String
169 ctExc = "ctExc"
170
171 -- throw an exception (EXPORTED)
172 --
173 throwCTExc :: CT s a
174 throwCTExc = throwExc ctExc "Error during traversal of a C structure tree"
175
176 -- catch a `ctExc' (EXPORTED)
177 --
178 ifCTExc :: CT s a -> CT s a -> CT s a
179 ifCTExc m handler = m `catchExc` (ctExc, const handler)
180
181 -- raise an error followed by throwing a CT exception (EXPORTED)
182 --
183 raiseErrorCTExc :: Position -> [String] -> CT s a
184 raiseErrorCTExc pos errs = raiseError pos errs >> throwCTExc
185
186
187 -- attribute manipulation
188 -- ----------------------
189
190 -- name spaces
191 --
192
193 -- enter a new local range (EXPORTED)
194 --
195 enter :: CT s ()
196 enter = transAttrCCT $ \ac -> (enterNewRangeC ac, ())
197
198 -- enter a new local range, only for objects (EXPORTED)
199 --
200 enterObjs :: CT s ()
201 enterObjs = transAttrCCT $ \ac -> (enterNewObjRangeC ac, ())
202
203 -- leave the current local range (EXPORTED)
204 --
205 leave :: CT s ()
206 leave = transAttrCCT $ \ac -> (leaveRangeC ac, ())
207
208 -- leave the current local range, only for objects (EXPORTED)
209 --
210 leaveObjs :: CT s ()
211 leaveObjs = transAttrCCT $ \ac -> (leaveObjRangeC ac, ())
212
213 -- enter an object definition into the object name space (EXPORTED)
214 --
215 -- * if a definition of the same name was already present, it is returned
216 --
217 defObj :: Ident -> CObj -> CT s (Maybe CObj)
218 defObj ide obj = transAttrCCT $ \ac -> addDefObjC ac ide obj
219
220 -- find a definition in the object name space (EXPORTED)
221 --
222 findObj :: Ident -> CT s (Maybe CObj)
223 findObj ide = readAttrCCT $ \ac -> lookupDefObjC ac ide
224
225 -- find a definition in the object name space; if nothing found, try
226 -- whether there is a shadow identifier that matches (EXPORTED)
227 --
228 findObjShadow :: Ident -> CT s (Maybe (CObj, Ident))
229 findObjShadow ide = readAttrCCT $ \ac -> lookupDefObjCShadow ac ide
230
231 -- enter a tag definition into the tag name space (EXPORTED)
232 --
233 -- * empty definitions of structures get overwritten with complete ones and a
234 -- forward reference is added to their tag identifier; furthermore, both
235 -- structures and enums may be referenced using an empty definition when
236 -- there was a full definition earlier and in this case there is also an
237 -- object association added; otherwise, if a definition of the same name was
238 -- already present, it is returned (see DOCU section)
239 --
240 -- * it is checked that the first occurrence of an enumeration tag is
241 -- accompanied by a full definition of the enumeration
242 --
243 defTag :: Ident -> CTag -> CT s (Maybe CTag)
244 defTag ide tag =
245 do
246 otag <- transAttrCCT $ \ac -> addDefTagC ac ide tag
247 case otag of
248 Nothing -> do
249 assertIfEnumThenFull tag
250 return Nothing -- no collision
251 Just prevTag -> case isRefinedOrUse prevTag tag of
252 Nothing -> return otag
253 Just (fullTag, foreIde) -> do
254 transAttrCCT $ \ac -> addDefTagC ac ide fullTag
255 foreIde `refersToDef` TagCD fullTag
256 return Nothing -- transparent for env
257 where
258 -- compute whether we have the case of a non-conflicting redefined tag
259 -- definition, and if so, return the full definition and the forward
260 -- definition's tag identifier
261 --
262 -- * the first argument contains the _previous_ definition
263 --
264 -- * in the case of a structure, a forward definition after a full
265 -- definition is allowed, so we have to handle this case; enumerations
266 -- don't allow forward definitions
267 --
268 -- * there may also be multiple forward definition; if we have two of
269 -- them here, one is arbitrarily selected to take the role of the full
270 -- definition
271 --
272 isRefinedOrUse (StructUnionCT (CStruct _ (Just ide) [] _))
273 tag@(StructUnionCT (CStruct _ (Just _ ) _ _)) =
274 Just (tag, ide)
275 isRefinedOrUse tag@(StructUnionCT (CStruct _ (Just _ ) _ _))
276 (StructUnionCT (CStruct _ (Just ide) [] _)) =
277 Just (tag, ide)
278 isRefinedOrUse tag@(EnumCT (CEnum (Just _ ) _ _))
279 (EnumCT (CEnum (Just ide) [] _)) =
280 Just (tag, ide)
281 isRefinedOrUse _ _ = Nothing
282
283 -- find an definition in the tag name space (EXPORTED)
284 --
285 findTag :: Ident -> CT s (Maybe CTag)
286 findTag ide = readAttrCCT $ \ac -> lookupDefTagC ac ide
287
288 -- find an definition in the tag name space; if nothing found, try
289 -- whether there is a shadow identifier that matches (EXPORTED)
290 --
291 findTagShadow :: Ident -> CT s (Maybe (CTag, Ident))
292 findTagShadow ide = readAttrCCT $ \ac -> lookupDefTagCShadow ac ide
293
294 -- enrich the object and tag name space with identifiers obtained by dropping
295 -- the given prefix from the identifiers already in the name space (EXPORTED)
296 --
297 -- * if a new identifier would collides with an existing one, the new one is
298 -- discarded, ie, all associations that existed before the transformation
299 -- started are still in effect after the transformation
300 --
301 applyPrefixToNameSpaces :: String -> CT s ()
302 applyPrefixToNameSpaces prefix =
303 transAttrCCT $ \ac -> (applyPrefix ac prefix, ())
304
305 -- definition attribute
306 --
307
308 -- get the definition of an identifier (EXPORTED)
309 --
310 -- * the attribute must be defined, ie, a definition must be associated with
311 -- the given identifier
312 --
313 getDefOf :: Ident -> CT s CDef
314 getDefOf ide = do
315 def <- readAttrCCT $ \ac -> getDefOfIdentC ac ide
316 assert (not . isUndef $ def) $
317 return def
318
319 -- set the definition of an identifier (EXPORTED)
320 --
321 refersToDef :: Ident -> CDef -> CT s ()
322 refersToDef ide def = transAttrCCT $ \akl -> (setDefOfIdentC akl ide def, ())
323
324 -- update the definition of an identifier (EXPORTED)
325 --
326 refersToNewDef :: Ident -> CDef -> CT s ()
327 refersToNewDef ide def =
328 transAttrCCT $ \akl -> (updDefOfIdentC akl ide def, ())
329
330 -- get the declarator of an identifier (EXPORTED)
331 --
332 getDeclOf :: Ident -> CT s CDecl
333 getDeclOf ide =
334 do
335 traceEnter
336 def <- getDefOf ide
337 case def of
338 UndefCD -> interr "CTrav.getDeclOf: Undefined!"
339 DontCareCD -> interr "CTrav.getDeclOf: Don't care!"
340 TagCD _ -> interr "CTrav.getDeclOf: Illegal tag!"
341 ObjCD obj -> case obj of
342 TypeCO decl -> traceTypeCO >>
343 return decl
344 ObjCO decl -> traceObjCO >>
345 return decl
346 EnumCO _ _ -> illegalEnum
347 BuiltinCO -> illegalBuiltin
348 where
349 illegalEnum = interr "CTrav.getDeclOf: Illegal enum!"
350 illegalBuiltin = interr "CTrav.getDeclOf: Attempted to get declarator of \
351 \builtin entity!"
352 -- if the latter ever becomes necessary, we have to
353 -- change the representation of builtins and give them
354 -- some dummy declarator
355 traceEnter = traceCTrav $
356 "Entering `getDeclOf' for `" ++ identToLexeme ide
357 ++ "'...\n"
358 traceTypeCO = traceCTrav $
359 "...found a type object.\n"
360 traceObjCO = traceCTrav $
361 "...found a vanilla object.\n"
362
363
364 -- convenience functions
365 --
366
367 -- find a type object in the object name space; returns `nothing' if the
368 -- identifier is not defined (EXPORTED)
369 --
370 -- * if the second argument is `True', use `findObjShadow'
371 --
372 findTypeObjMaybe :: Ident -> Bool -> CT s (Maybe (CObj, Ident))
373 findTypeObjMaybe ide useShadows =
374 do
375 oobj <- if useShadows
376 then findObjShadow ide
377 else liftM (fmap (\obj -> (obj, ide))) $ findObj ide
378 case oobj of
379 Just obj@(TypeCO _ , _) -> return $ Just obj
380 Just obj@(BuiltinCO, _) -> return $ Just obj
381 Just _ -> typedefExpectedErr ide
382 Nothing -> return $ Nothing
383
384 -- find a type object in the object name space; raises an error and exception
385 -- if the identifier is not defined (EXPORTED)
386 --
387 -- * if the second argument is `True', use `findObjShadow'
388 --
389 findTypeObj :: Ident -> Bool -> CT s (CObj, Ident)
390 findTypeObj ide useShadows = do
391 oobj <- findTypeObjMaybe ide useShadows
392 case oobj of
393 Nothing -> unknownObjErr ide
394 Just obj -> return obj
395
396 -- find an object, function, or enumerator in the object name space; raises an
397 -- error and exception if the identifier is not defined (EXPORTED)
398 --
399 -- * if the second argument is `True', use `findObjShadow'
400 --
401 findValueObj :: Ident -> Bool -> CT s (CObj, Ident)
402 findValueObj ide useShadows =
403 do
404 oobj <- if useShadows
405 then findObjShadow ide
406 else liftM (fmap (\obj -> (obj, ide))) $ findObj ide
407 case oobj of
408 Just obj@(ObjCO _ , _) -> return obj
409 Just obj@(EnumCO _ _, _) -> return obj
410 Just _ -> unexpectedTypedefErr (posOf ide)
411 Nothing -> unknownObjErr ide
412
413 -- find a function in the object name space; raises an error and exception if
414 -- the identifier is not defined (EXPORTED)
415 --
416 -- * if the second argument is `True', use `findObjShadow'
417 --
418 findFunObj :: Ident -> Bool -> CT s (CObj, Ident)
419 findFunObj ide useShadows =
420 do
421 (obj, ide') <- findValueObj ide useShadows
422 case obj of
423 EnumCO _ _ -> funExpectedErr (posOf ide)
424 ObjCO decl -> do
425 let declr = ide' `declrFromDecl` decl
426 assertFunDeclr (posOf ide) declr
427 return (obj, ide')
428
429
430 -- C structure tree query routines
431 -- -------------------------------
432
433 -- test if this is a type definition specification (EXPORTED)
434 --
435 isTypedef :: CDecl -> Bool
436 isTypedef (CDecl specs _ _) =
437 not . null $ [() | CStorageSpec (CTypedef _) <- specs]
438
439 -- discard all declarators but the one declaring the given identifier
440 -- (EXPORTED)
441 --
442 -- * the declaration must contain the identifier
443 --
444 simplifyDecl :: Ident -> CDecl -> CDecl
445 ide `simplifyDecl` (CDecl specs declrs at) =
446 case find (`declrPlusNamed` ide) declrs of
447 Nothing -> err
448 Just declr -> CDecl specs [declr] at
449 where
450 (Just declr, _, _) `declrPlusNamed` ide = declr `declrNamed` ide
451 _ `declrPlusNamed` _ = False
452 --
453 err = interr $ "CTrav.simplifyDecl: Wrong C object!\n\
454 \ Looking for `" ++ identToLexeme ide ++ "' in decl \
455 \at " ++ show (posOf at)
456
457 -- extract the declarator that declares the given identifier (EXPORTED)
458 --
459 -- * the declaration must contain the identifier
460 --
461 declrFromDecl :: Ident -> CDecl -> CDeclr
462 ide `declrFromDecl` decl =
463 let CDecl _ [(Just declr, _, _)] _ = ide `simplifyDecl` decl
464 in
465 declr
466
467 -- tests whether the given declarator has the given name (EXPORTED)
468 --
469 declrNamed :: CDeclr -> Ident -> Bool
470 declr `declrNamed` ide = declrName declr == Just ide
471
472 -- get the declarator of a declaration that has at most one declarator
473 -- (EXPORTED)
474 --
475 declaredDeclr :: CDecl -> Maybe CDeclr
476 declaredDeclr (CDecl _ [] _) = Nothing
477 declaredDeclr (CDecl _ [(odeclr, _, _)] _) = odeclr
478 declaredDeclr decl =
479 interr $ "CTrav.declaredDeclr: Too many declarators!\n\
480 \ Declaration at " ++ show (posOf decl)
481
482 -- get the name declared by a declaration that has exactly one declarator
483 -- (EXPORTED)
484 --
485 declaredName :: CDecl -> Maybe Ident
486 declaredName decl = declaredDeclr decl >>= declrName
487
488 -- obtains the member definitions and the tag of a struct (EXPORTED)
489 --
490 -- * member definitions are expanded
491 --
492 structMembers :: CStructUnion -> ([CDecl], CStructTag)
493 structMembers (CStruct tag _ members _) = (concat . map expandDecl $ members,
494 tag)
495
496 -- expand declarators declaring more than one identifier into multiple
497 -- declarators, eg, `int x, y;' becomes `int x; int y;' (EXPORTED)
498 --
499 expandDecl :: CDecl -> [CDecl]
500 expandDecl (CDecl specs decls at) =
501 map (\decl -> CDecl specs [decl] at) decls
502
503 -- get a struct's name (EXPORTED)
504 --
505 structName :: CStructUnion -> Maybe Ident
506 structName (CStruct _ oide _ _) = oide
507
508 -- get an enum's name (EXPORTED)
509 --
510 enumName :: CEnum -> Maybe Ident
511 enumName (CEnum oide _ _) = oide
512
513 -- get a tag's name (EXPORTED)
514 --
515 -- * fail if the tag is anonymous
516 --
517 tagName :: CTag -> Ident
518 tagName tag =
519 case tag of
520 StructUnionCT struct -> maybe err id $ structName struct
521 EnumCT enum -> maybe err id $ enumName enum
522 where
523 err = interr "CTrav.tagName: Anonymous tag definition"
524
525 -- checks whether the given declarator defines an object that is a pointer to
526 -- some other type (EXPORTED)
527 --
528 -- * as far as parameter passing is concerned, arrays are also pointer
529 --
530 isPtrDeclr :: CDeclr -> Bool
531 isPtrDeclr (CPtrDeclr _ (CVarDeclr _ _) _) = True
532 isPtrDeclr (CPtrDeclr _ declr _) = isPtrDeclr declr
533 isPtrDeclr (CArrDeclr (CVarDeclr _ _) _ _ _) = True
534 isPtrDeclr (CArrDeclr declr _ _ _) = isPtrDeclr declr
535 isPtrDeclr (CFunDeclr declr _ _ _) = isPtrDeclr declr
536 isPtrDeclr _ = False
537
538 -- checks whether the given declarator defines an object that is an array of
539 -- some other type (EXPORTED)
540 --
541 -- * difference between arrays and pure pointers is important for size
542 -- calculations
543 --
544 isArrDeclr :: CDeclr -> Bool
545 isArrDeclr (CArrDeclr declr _ _ _) = True
546 isArrDeclr _ = False
547
548 -- drops the first pointer level from the given declarator (EXPORTED)
549 --
550 -- * the declarator must declare a pointer object
551 --
552 -- FIXME: this implementation isn't nice, because we retain the `CVarDeclr'
553 -- unchanged; as the declarator is changed, we should maybe make this
554 -- into an anonymous declarator and also change its attributes
555 --
556 dropPtrDeclr :: CDeclr -> CDeclr
557 dropPtrDeclr (CPtrDeclr qs declr@(CVarDeclr _ _) ats) = declr
558 dropPtrDeclr (CPtrDeclr qs declr ats) =
559 let declr' = dropPtrDeclr declr
560 in
561 CPtrDeclr qs declr' ats
562 dropPtrDeclr (CArrDeclr declr@(CVarDeclr _ _) _ _ _) = declr
563 dropPtrDeclr (CArrDeclr declr tq e ats) =
564 let declr' = dropPtrDeclr declr
565 in
566 CArrDeclr declr' tq e ats
567 dropPtrDeclr (CFunDeclr declr args vari ats) =
568 let declr' = dropPtrDeclr declr
569 in
570 CFunDeclr declr' args vari ats
571 dropPtrDeclr _ =
572 interr "CTrav.dropPtrDeclr: No pointer!"
573
574 -- checks whether the given declaration defines a pointer object (EXPORTED)
575 --
576 -- * there may only be a single declarator in the declaration
577 --
578 isPtrDecl :: CDecl -> Bool
579 isPtrDecl (CDecl _ [] _) = False
580 isPtrDecl (CDecl _ [(Just declr, _, _)] _) = isPtrDeclr declr
581 isPtrDecl _ =
582 interr "CTrav.isPtrDecl: There was more than one declarator!"
583
584 -- checks whether the given declarator defines a function object (EXPORTED)
585 --
586 isFunDeclr :: CDeclr -> Bool
587 isFunDeclr (CPtrDeclr _ declr _) = isFunDeclr declr
588 isFunDeclr (CArrDeclr declr _ _ _) = isFunDeclr declr
589 isFunDeclr (CFunDeclr (CVarDeclr _ _) _ _ _) = True
590 isFunDeclr (CFunDeclr declr _ _ _) = isFunDeclr declr
591 isFunDeclr _ = False
592
593 -- extract the structure from the type specifiers of a declaration (EXPORTED)
594 --
595 structFromDecl :: Position -> CDecl -> CT s CStructUnion
596 structFromDecl pos (CDecl specs _ _) =
597 case head [ts | CTypeSpec ts <- specs] of
598 CSUType su _ -> extractStruct pos (StructUnionCT su)
599 _ -> structExpectedErr pos
600
601 -- extracts the arguments from a function declaration (must be a unique
602 -- declarator) and constructs a declaration for the result of the function
603 -- (EXPORTED)
604 --
605 -- * the boolean result indicates whether the function is variadic
606 --
607 funResultAndArgs :: CDecl -> ([CDecl], CDecl, Bool)
608 funResultAndArgs (CDecl specs [(Just declr, _, _)] _) =
609 let (args, declr', variadic) = funArgs declr
610 result = CDecl specs [(Just declr', Nothing, Nothing)]
611 (newAttrsOnlyPos nopos)
612 in
613 (args, result, variadic)
614 where
615 funArgs (CFunDeclr var@(CVarDeclr _ _) args variadic _) =
616 (args, var, variadic)
617 funArgs (CPtrDeclr qs declr at) =
618 let (args, declr', variadic) = funArgs declr
619 in
620 (args, CPtrDeclr qs declr' at, variadic)
621 funArgs (CArrDeclr declr tqs oe at) =
622 let (args, declr', variadic) = funArgs declr
623 in
624 (args, CArrDeclr declr' tqs oe at, variadic)
625 funArgs (CFunDeclr declr args var at) =
626 let (args, declr', variadic) = funArgs declr
627 in
628 (args, CFunDeclr declr' args var at, variadic)
629 funArgs _ =
630 interr "CTrav.funResultAndArgs: Illegal declarator!"
631
632 -- name chasing
633 --
634
635 -- find the declarator identified by the given identifier; if the declarator
636 -- is itself only a `typedef'ed name, the operation recursively searches for
637 -- the declarator associated with that name (this is called ``typedef
638 -- chasing'') (EXPORTED)
639 --
640 -- * if `ind = True', we have to hop over one indirection
641 --
642 -- * remove all declarators except the one we just looked up
643 --
644 chaseDecl :: Ident -> Bool -> CT s CDecl
645 --
646 -- * cycles are no issue, as they cannot occur in a correct C header (we would
647 -- have spotted the problem during name analysis)
648 --
649 chaseDecl ide ind =
650 do
651 traceEnter
652 cdecl <- getDeclOf ide
653 let sdecl = ide `simplifyDecl` cdecl
654 case extractAlias sdecl ind of
655 Just (ide', ind') -> chaseDecl ide' ind'
656 Nothing -> return sdecl
657 where
658 traceEnter = traceCTrav $
659 "Entering `chaseDecl' for `" ++ identToLexeme ide
660 ++ "' " ++ (if ind then "" else "not ")
661 ++ "following indirections...\n"
662
663 -- find type object in object name space and then chase it (EXPORTED)
664 --
665 -- * see also `chaseDecl'
666 --
667 -- * also create an object association from the given identifier to the object
668 -- that it _directly_ represents
669 --
670 -- * if the third argument is `True', use `findObjShadow'
671 --
672 findAndChaseDecl :: Ident -> Bool -> Bool -> CT s CDecl
673 findAndChaseDecl ide ind useShadows =
674 do
675 (obj, ide') <- findTypeObj ide useShadows -- is there an object def?
676 ide `refersToNewDef` ObjCD obj
677 ide' `refersToNewDef` ObjCD obj -- assoc needed for chasing
678 chaseDecl ide' ind
679
680 -- given a declaration (which must have exactly one declarator), if the
681 -- declarator is an alias, chase it to the actual declaration (EXPORTED)
682 --
683 checkForAlias :: CDecl -> CT s (Maybe CDecl)
684 checkForAlias decl =
685 case extractAlias decl False of
686 Nothing -> return Nothing
687 Just (ide', _) -> liftM Just $ chaseDecl ide' False
688
689 -- given a declaration (which must have exactly one declarator), if the
690 -- declarator is an alias, yield the alias name; *no* chasing (EXPORTED)
691 --
692 checkForOneAliasName :: CDecl -> Maybe Ident
693 checkForOneAliasName decl = fmap fst $ extractAlias decl False
694
695
696 -- smart lookup
697 --
698
699 -- for the given identifier, either find an enumeration in the tag name space
700 -- or a type definition referring to an enumeration in the object name space;
701 -- raises an error and exception if the identifier is not defined (EXPORTED)
702 --
703 -- * if the second argument is `True', use `findTagShadow'
704 --
705 lookupEnum :: Ident -> Bool -> CT s CEnum
706 lookupEnum ide useShadows =
707 do
708 otag <- if useShadows
709 then liftM (fmap fst) $ findTagShadow ide
710 else findTag ide
711 case otag of
712 Just (StructUnionCT _ ) -> enumExpectedErr ide -- wrong tag definition
713 Just (EnumCT enum) -> return enum -- enum tag definition
714 Nothing -> do -- no tag definition
715 (CDecl specs _ _) <- findAndChaseDecl ide False useShadows
716 case head [ts | CTypeSpec ts <- specs] of
717 CEnumType enum _ -> return enum
718 _ -> enumExpectedErr ide
719
720 -- for the given identifier, either find a struct/union in the tag name space
721 -- or a type definition referring to a struct/union in the object name space;
722 -- raises an error and exception if the identifier is not defined (EXPORTED)
723 --
724 -- * if `ind = True', the identifier names a reference type to the searched
725 -- for struct/union
726 --
727 -- * typedef chasing is used only if there is no tag of the same name or an
728 -- indirection (ie, `ind = True') is explicitly required
729 --
730 -- * if the third argument is `True', use `findTagShadow'
731 --
732 -- * when finding a forward definition of a tag, follow it to the real
733 -- definition
734 --
735 lookupStructUnion :: Ident -> Bool -> Bool -> CT s CStructUnion
736 lookupStructUnion ide ind useShadows
737 | ind = chase
738 | otherwise =
739 do
740 otag <- if useShadows
741 then liftM (fmap fst) $ findTagShadow ide
742 else findTag ide
743 maybe chase (extractStruct (posOf ide)) otag -- `chase' if `Nothing'
744 where
745 chase =
746 do
747 decl <- findAndChaseDecl ide ind useShadows
748 structFromDecl (posOf ide) decl
749
750 -- for the given identifier, check for the existence of both a type definition
751 -- or a struct, union, or enum definition (EXPORTED)
752 --
753 -- * if a typedef and a tag exists, the typedef takes precedence
754 --
755 -- * typedefs are chased
756 --
757 -- * if the second argument is `True', look for shadows, too
758 --
759 lookupDeclOrTag :: Ident -> Bool -> CT s (Either CDecl CTag)
760 lookupDeclOrTag ide useShadows = do
761 oobj <- findTypeObjMaybe ide useShadows
762 case oobj of
763 Just (_, ide) -> liftM Left $ findAndChaseDecl ide False False
764 -- already did check shadows
765 Nothing -> do
766 otag <- if useShadows
767 then liftM (fmap fst) $ findTagShadow ide
768 else findTag ide
769 case otag of
770 Nothing -> unknownObjErr ide
771 Just tag -> return $ Right tag
772
773
774 -- auxiliary routines (internal)
775 --
776
777 -- if the given declaration (which may have at most one declarator) is a
778 -- `typedef' alias, yield the referenced name
779 --
780 -- * a `typedef' alias has one of the following forms
781 --
782 -- <specs> at x, ...;
783 -- <specs> at *x, ...;
784 --
785 -- where `at' is the alias type, which has been defined by a `typedef', and
786 -- <specs> are arbitrary specifiers and qualifiers. Note that `x' may be a
787 -- variable, a type name (if `typedef' is in <specs>), or be entirely
788 -- omitted.
789 --
790 -- * if `ind = True', the alias may be via an indirection
791 --
792 -- * if `ind = True' and the alias is _not_ over an indirection, yield `True';
793 -- otherwise `False' (ie, the ability to hop over an indirection is consumed)
794 --
795 -- * this may be an anonymous declaration, ie, the name in `CVarDeclr' may be
796 -- omitted or there may be no declarator at all
797 --
798 extractAlias :: CDecl -> Bool -> Maybe (Ident, Bool)
799 extractAlias decl@(CDecl specs _ _) ind =
800 case [ts | CTypeSpec ts <- specs] of
801 [CTypeDef ide' _] -> -- type spec is aliased ident
802 case declaredDeclr decl of
803 Nothing -> Just (ide', ind)
804 Just (CVarDeclr _ _ ) -> Just (ide', ind)
805 Just (CPtrDeclr [_] (CVarDeclr _ _) _)
806 | ind -> Just (ide', False)
807 | otherwise -> Nothing
808 _ -> Nothing
809 _ -> Nothing
810
811 -- if the given tag is a forward declaration of a structure, follow the
812 -- reference to the full declaration
813 --
814 -- * the recursive call is not dangerous as there can't be any cycles
815 --
816 extractStruct :: Position -> CTag -> CT s CStructUnion
817 extractStruct pos (EnumCT _ ) = structExpectedErr pos
818 extractStruct pos (StructUnionCT su) =
819 case su of
820 CStruct _ (Just ide') [] _ -> do -- found forward definition
821 def <- getDefOf ide'
822 case def of
823 TagCD tag -> extractStruct pos tag
824 _ -> err
825 _ -> return su
826 where
827 err = interr "CTrav.extractStruct: Illegal reference!"
828
829 -- yield the name declared by a declarator if any
830 --
831 declrName :: CDeclr -> Maybe Ident
832 declrName (CVarDeclr oide _) = oide
833 declrName (CPtrDeclr _ declr _) = declrName declr
834 declrName (CArrDeclr declr _ _ _) = declrName declr
835 declrName (CFunDeclr declr _ _ _) = declrName declr
836
837 -- raise an error if the given declarator does not declare a C function or if
838 -- the function is supposed to return an array (the latter is illegal in C)
839 --
840 assertFunDeclr :: Position -> CDeclr -> CT s ()
841 assertFunDeclr pos (CArrDeclr (CFunDeclr (CVarDeclr _ _) _ _ _) _ _ _) =
842 illegalFunResultErr pos
843 assertFunDeclr pos (CFunDeclr (CVarDeclr _ _) _ _ _) =
844 nop -- everything is ok
845 assertFunDeclr pos (CFunDeclr declr _ _ _) =
846 assertFunDeclr pos declr
847 assertFunDeclr pos (CPtrDeclr _ declr _) =
848 assertFunDeclr pos declr
849 assertFunDeclr pos (CArrDeclr declr _ _ _) =
850 assertFunDeclr pos declr
851 assertFunDeclr pos _ =
852 funExpectedErr pos
853
854 -- raise an error if the given tag defines an enumeration, but does not fully
855 -- define it
856 --
857 assertIfEnumThenFull :: CTag -> CT s ()
858 assertIfEnumThenFull (EnumCT (CEnum _ [] at)) = enumForwardErr (posOf at)
859 assertIfEnumThenFull _ = nop
860
861 -- trace for this module
862 --
863 traceCTrav :: String -> CT s ()
864 traceCTrav = putTraceStr traceCTravSW
865
866
867 -- error messages
868 -- --------------
869
870 unknownObjErr :: Ident -> CT s a
871 unknownObjErr ide =
872 raiseErrorCTExc (posOf ide)
873 ["Unknown identifier!",
874 "Cannot find a definition for `" ++ identToLexeme ide ++ "' in the \
875 \header file."]
876
877 typedefExpectedErr :: Ident -> CT s a
878 typedefExpectedErr ide =
879 raiseErrorCTExc (posOf ide)
880 ["Expected type definition!",
881 "The identifier `" ++ identToLexeme ide ++ "' needs to be a C type name."]
882
883 unexpectedTypedefErr :: Position -> CT s a
884 unexpectedTypedefErr pos =
885 raiseErrorCTExc pos
886 ["Unexpected type name!",
887 "An object, function, or enum constant is required here."]
888
889 illegalFunResultErr :: Position -> CT s a
890 illegalFunResultErr pos =
891 raiseErrorCTExc pos ["Function cannot return an array!",
892 "ANSI C does not allow functions to return an array."]
893
894 funExpectedErr :: Position -> CT s a
895 funExpectedErr pos =
896 raiseErrorCTExc pos
897 ["Function expected!",
898 "A function is needed here, but this declarator does not declare",
899 "a function."]
900
901 enumExpectedErr :: Ident -> CT s a
902 enumExpectedErr ide =
903 raiseErrorCTExc (posOf ide)
904 ["Expected enum!",
905 "Expected `" ++ identToLexeme ide ++ "' to denote an enum; instead found",
906 "a struct, union, or object."]
907
908 structExpectedErr :: Position -> CT s a
909 structExpectedErr pos =
910 raiseErrorCTExc pos
911 ["Expected a struct!",
912 "Expected a structure or union; instead found an enum or basic type."]
913
914 enumForwardErr :: Position -> CT s a
915 enumForwardErr pos =
916 raiseErrorCTExc pos
917 ["Forward definition of enumeration!",
918 "ANSI C does not permit forward definitions of enumerations!"]