living zhang
living zhang

Reputation: 359

how to get the children of OpaqueValueExpr in Clang AST

I have a part of AST as the picture followed. enter image description here

The code of this BinaryOperator is:

self.contentMode = UIViewContentModeScaleAspectFit;

Then I use ASTVisitor to get the information of this line of code.

bool VisitBinaryOperator(BinaryOperator *node) {

    ObjCPropertyRefExpr *lvalue = dyn_cast<ObjCPropertyRefExpr>(node->getLHS());

    if (lvalue && \
        lvalue->isMessagingSetter() && \
        lvalue->getSetterSelector().getAsString() == "setContentMode:")
    {
        OpaqueValueExpr *rvalue = dyn_cast<OpaqueValueExpr>(node->getRHS());

        // I want to get DeclRefExpr of UIViewContentModeScaleAspectFit here.
    }
    return true;
}

I can get the lvalue right, but how can I get the DeclRefExpr at the last line of the AST.

Upvotes: 2

Views: 1176

Answers (1)

AlexDenisov
AlexDenisov

Reputation: 4117

OpaqueValueExpr holds another expression, you can access it using method getSourceExpr().

Within your AST the source expression will be an implicit cast, which is not the goal. For this purpose Clang's Expr class has family of 'ignore' methods such as IgnoreImpCasts or IgnoreParens. These methods used to access underlying expression, like in your case.

For example, if an expression a has type ImplicitCastExpr and it holds some b of type DeclRefExpr, then a->IgnoreImpCasts() will return pointer to b. However, if we call the method on b, then it will return b itself.

Here is code to answer your question:

Expr *SE = rvalue->getSourceExpr()->IgnoreImpCasts();
if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SE)) {
    // do you magic with DeclRefExpr here
}

Upvotes: 3

Related Questions