[cfe-dev] RFC: Easier AST Matching by Default

David Rector via cfe-dev cfe-dev at lists.llvm.org
Wed Jun 24 09:05:55 PDT 2020

> Stmt {
>> 	T *getAs() {
> 		if (isa<T>(this))
> 			return cast<T>(this);
> 		if (this->isImplicit() || isa<ParenExpr>(this)) {
> 			assert(children.size() == 1 && "Expected implicit nodes to have exactly one child");
> 			return (*children.begin())->getAs<T>();
> 		}
> 		return nullptr;
> 	}
> Note that the analogy to Type::getAs has already broken down here; getAs always returns a type with the same semantics but a possibly different meaning, whereas this can return an expression with different semantics by skipping implicit nodes.

This, I believe, gets to the heart of the issue Stephen has raised.  In

struct B { B(int); };
B f() { return 42; }

is it ever valid for a user to treat the 42 as an IntegerLiteral, instead of an ExprWCleanups?  

What is interesting about the analogy between the proposed Stmt::getAs<T>() and the existing Type::getAs<T>() is that, considering only their effect on syntax and semantics, they are precisely the opposite (disregarding the extra handling of ParenExpr, which probably should be removed): whereas each desugaring performed in Type::getAs<T> peels back a layer of meaningless syntax to get ever closer to the underlying semantics, Stmt::getAs<T> would peel back layers of invisible semantics to get ever closer to the underlying syntax.

So it might be confusing.

But in another sense, the analogy holds: in both cases, getAs<T> retrieves only the *essential information* about the node: the information without which the semantics could not be reconstructed.  In the case of types, this is the fully de-aliased, de-sugared type.  In the case of Stmts (or really, just Exprs), this is the originally written statement.

So, there are two possible ways the user might interpret a universal getAs, such that it would either confuse them or help them.  I am satisfied the case has been made, will defer to you and others with greater experience and wisdom to reflect on it and decide it.

Thanks for engaging this issue, and Stephen thanks again for raising this important issue,

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20200624/33475e56/attachment-0001.html>

More information about the cfe-dev mailing list