[cfe-dev] Evaluating bitfield width with libclang

Jacob Carlborg doob at me.com
Thu Sep 6 01:03:09 PDT 2012


On 2012-09-06 01:08, Sergiy Migdalskiy wrote:
> Hello,
> I just implemented my first function in libclang – it gets a field
> cursor and returns the bitfield width, if that’s a bitfield. Otherwise
> it returns a negative value.

This is just what I need.

> I’d like to submit it as a patch (never did that before, I’ll read up on
> how to do that later), but first can someone review this routine? It
> seems to work, but having never written anything inside clang (and
> having played with clang for only a couple of weeks now), I suspect
> there may just be half a dozen bugs there. In any case, I hope it’ll be
> helpful at least for some people reading this list.
> And by the way, kudos to all Clang developers for the high quality
> product. The code (at least the bits I looked at when implementing this)
> is a delight to read.
> // -1 : cursor is not a field declaration
> // -2 : cursor is not a bitfield declaration
> // -3 : could not evaluate the bitfield width
> int clang_Cursor_getBitfieldWidth(CXCursor C) {
>    if (clang_isDeclaration(C.kind)) {
>      Decl *D = cxcursor::getCursorDecl(C);
>      if( const FieldDecl *FD = dyn_cast_or_null< FieldDecl >(D) ){
>        Expr *pBitWidth = FD->getBitWidth();
>        if( pBitWidth ){
>          llvm::APSInt width;
>          if( pBitWidth->EvaluateAsInt(width,
> getCursorASTUnit(C)->getASTContext() ) ){
>            return *width.getRawData();
>          }
>          return -3;
>        }
>        return -2;
>      }
>    }
>    return -1;
> }
> Sincerely,
> Sergiy Migdalskiy

Do we really need three different values to indicate a failure? Either 
you can get the width of the bitfield or you can't.

-- 
/Jacob Carlborg




More information about the cfe-dev mailing list