Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluating constant expressions in clang tools

Tags:

clang

clang++

I'm writing a Clang tool and I'm trying to figure out how to evaluate a string literal given access to the program's AST. Given the following program:

class DHolder { 
public:
  DHolder(std::string s) {}
};

DHolder x("foo");    

I have the following code in the Clang tool:

const CXXConstructExpr *ctor = ... // constructs `x` above
const Expr *expr = ctor->getArg(0); // the "foo" expression
???

How can I get from the Expr representing the "foo" string literal to an actual C++ string in my tool? I've tried to do something like:

// From ExprConstant.cpp
Evaluate(result, info, expr);

but I don't know how to initialize the result and info parameters.

Any clues?

like image 681
JesperE Avatar asked Oct 15 '25 04:10

JesperE


1 Answers

I realize this is an old question, but I ran into this a moment ago when I could not use stringLiteral() to bind to any arguments (the code is not C++11). For example, I have a CXXMMemberCallExpr:

addProperty(object, char*, char*, ...); // has 7 arguments, N=[0,6]

The AST dump shows that ahead of the StringLiteral is a CXXBindTemporaryExpr. So in order for my memberCallExpr query to bind using hasArgument(N,expr()), I wrapped my query with bindTemporaryExpr() (shown here on separate lines for readability):

memberCallExpr(
    hasArgument(6, bindTemporaryExpr( 
        hasDescendant(stringLiteral().bind("argument"))
        )
    )
)
like image 98
Thomas Avatar answered Oct 18 '25 11:10

Thomas