如何在Clang AST中判断Objective-C消息的接收者是否为自身?
Great question! Since you already have the getInstanceReceiver() method to fetch the receiver expression, let's walk through how to use it to determine if the message is sent to self or another object. Here's a step-by-step breakdown:
1. Start with the receiver expression
First, call getInstanceReceiver() to get the Expr* receiver for your method call. If it returns null, you’re dealing with a non-instance message (like a class method), so you can skip this check.
2. Analyze the receiver’s expression type
The key is to inspect what kind of expression the receiver is, since different types tell you different things about who the message is being sent to:
Direct
selfreference:
If the receiver is an identifier expression (e.g.,IdentifierExprin many AST implementations) and its name exactly matches"self", then the message is directly sent to the current instance (self). For example,[self doSomething]falls into this case.selfproperty/chain access:
If the receiver is a property access expression (e.g.,PropertyAccessExprorObjCPropertyRefExprfor Objective-C) likeself.view, the message is sent to the object referenced by that property—notselfitself. Even though the chain starts withself, the actual receiver is the property’s value, so this counts as "another object". Your example[self.view backgroundColor]is exactly this scenario.superreference:
If the receiver is aSuperExpr(representingsuper), the message is sent to the parent class’s instance of the current object. This is also considered "another object" relative to the currentself.Other identifiers or expressions:
If the receiver is any other identifier (likemyObject) or a more complex expression (e.g.,[[self fetchHelper] performTask]), the message is sent to a different object. For complex nested calls, static analysis might require tracking return types to confirm if it resolves back toself, but that’s a more advanced scenario.
3. Edge cases to consider
- Be mindful of AST implementation differences: Different compiler frontends (like Clang for Objective-C) might use slightly different node names (e.g.,
ObjCIvarRefExprfor instance variable access), but the core logic holds—trace the expression back to see if it’s exactlyselfor a derivative object. - For assignments like your example, note that
[self.view backgroundColor] = ...is technically a setter message (setBackgroundColor:) sent toself.view, so the receiver is stillself.view, notself.
内容的提问来源于stack exchange,提问作者Jevgenij Anciferov

