2016-07-22 31 views
2

我想确定在ASTvisitor中的变量声明是否是数组,如果是数组,我想确定数组的维数。下面你可以找到我的代码。如何检查铛铛ASTvisitor中的变量声明是否为数组

bool VisitVarDecl(VarDecl *var) 
    { 
     if (astContext->getSourceManager().isInMainFile(var->getLocStart())) //checks if the node is in the main = input file. 
     { 
      FullSourceLoc FullLocation = astContext->getFullLoc(var->getLocStart()); 
      if((var->hasLocalStorage() || var->isStaticLocal())) 
      { 
       if (!var->isDefinedOutsideFunctionOrMethod()) 
       { 
        if(avoid == 0) 
        { 
         numVariables++; 
         string varName = var->getQualifiedNameAsString(); 
         string varType = var->getType().getAsString(); 
         const Type *type = var->getType().getTypePtr(); 
         if(type->isConstantArrayType()) 
         { 
          const ArrayType *Array = type->castAsArrayTypeUnsafe(); 
          cout << "Is array of type: " << Array->getElementType().getAsString() << endl; 
         } 
         REPORT << "[" << FullLocation.getSpellingLineNumber() << "," << FullLocation.getSpellingColumnNumber() << "]Variable Declaration: " << varName << " of type " << varType << "\n"; 
         APIs << varType << ";"; 
        } 
        else 
        { 
         avoid--; 
         REPORT << "Avoid is: " << avoid << endl; 
        } 
       } 
      } 
     } 
     return true; 
    } 

我不知道我是否已经正确地将VarDecl“投射”到ArrayType。如果你有一个更好,更安全,更不马虎的方式做到这一点,欢迎任何意见。 此外我现在的主要问题是如何获得数组的维数,甚至是单元格的大小。

谢谢大家。

回答

3

试试这个:

bool VisitVarDecl(VarDecl *D){ 
    if (auto t = dyn_cast_or_null<ConstantArrayType>(D->getType().getTypePtr())) { 
     t->getSize().dump(); // We got the array size as an APInt here 
    } 
    return true; 
} 

末,这里是 “一个更好,更安全和更小马虎的方式”:
the-isa-cast-and-dyn-cast-templates

+0

正如我所看到的getAsConstantArray的工作方式相同。然而,当我尝试与dyn_cast_or_null编译时,我得到的错误: '没有匹配的函数调用'dyn_cast_or_null(铿:: QualType)' –

+0

是的,这是所期望的,因为没有从clang :: QualType派生类型,所以没有匹配您的通话功能。你应该使用clang :: Type对象或指针。 –