我已经写了一些代码来确定结构是否为位域声明,但是由于我可能没有想到所有可能性,所以它似乎并不完整:

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;
    }
};


但是我真的觉得这段代码是非常不安全的,可能会给出假阴性或假阳性。就像今天才发现什么是位字段一样,我脑海中没有那么多例子。有没有更好的方法来识别位字段?

最佳答案

我确实通过FieldDecl description in Clang library找到了自己的问题的答案

现在,我只需要验证结构的每个FieldDecl为方法true返回isBitField()即可得出结论,该CXXRecordDecl是位字段声明。

关于c++ - 如何用Clang发现位字段?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25058213/

10-11 22:47