0

I already wrote a little code that determines whether a structure is a Bit Field declaration or not, but it really seems incomplete as I probably didn't think of all the possibilities :

class SCLE_MISRA_C_6_4Rule : public AbstractASTVisitorRule<SCLE_MISRA_C_6_4Rule>
{
public:

    /* class ExploreStruct provides 2 methods : isBitFieldDecl returns true if given struct decl only has 1 type for all fields. isShortType returns true if a given bit field has as bitfield type of "short" and not int as it should */
    class ExploreStruct : public RecursiveASTVisitor<ExploreStruct>
    {
    private : 
        // Count of fields
        int _nb_field;
        // Type of last field visited 
        QualType _last_type;
        // True if current type of field and last type of field are the same
        bool _same_type;
    public : 
        // True if current struct decl is a bit field 
        bool isBitFieldDecl(CXXRecordDecl *structDecl){
            _nb_field = 0;
            _same_type = false;
            (void) TraverseDecl(structDecl);
            return _same_type;
        }


// For all field decl in struct 
        bool VisitFieldDecl(FieldDecl * fieldDecl){
            _nb_field++;
            // If we are in the 2nd field or more 
            if(_nb_field > 1){
                // Is it a bit field ?
                if(fieldDecl->getType() == _last_type){
                    _same_type = true;
                }
                else{
                    _same_type = false; 
                    return false;
                }
            }
            // update type
            _last_type = fieldDecl->getType();
            return true;
        }
    };
    // For all CXXRecordDecl
    bool VisitCXXRecordDecl(CXXRecordDecl *structDecl){
        // Is it a struct decl ? 
        bool isStruct = structDecl->getTypeForDecl()->isStructureType();
        //If it is a structure 
        if(isStruct){
            ExploreStruct exploreStruct;
            // If this struct is a bit field 
            if(exploreStruct.isBitFieldDecl(structDecl)){

            }
        }
        return true;
    }
};

But I really feel that this code is quite unsafe and could give either false negatives or false positives. As I only discovered today what a bit field is, I don't have so many examples in my mind. Is there a better way to spot Bit Fields ?

Marc-O
  • 701
  • 1
  • 5
  • 22

1 Answers1

1

I did find an answer to my own question through the FieldDecl description in Clang library

Now, I just have to verify that every FieldDecl of a structure returns true for the method isBitField() to conclude that this CXXRecordDecl is a bit field declaration.

Marc-O
  • 701
  • 1
  • 5
  • 22