[cfe-users] Get AST of uncomplete C++ code

Richard Smith via cfe-users cfe-users at lists.llvm.org
Fri Apr 24 14:44:06 PDT 2020


On Tue, 21 Apr 2020 at 05:41, Dr S3curity via cfe-users <
cfe-users at lists.llvm.org> wrote:

> Hi,
>
> Imagine the very basic code below, it has some missing elements, we dont
> have the foo() function and MyClass class,
>
> ```test.cpp
> int main(int argc, char *argv[])
> {
>     MyClass* mc = new MyClass();
>     mc.get_count();
>     foo(1, 2, 3);
>     std::cout << "this is a test" << endl;
> }
> ```
>
> How can I get AST for that code?
> I tried `clang -Xclang -ast-dump -fsyntax-only test.cpp`, I can get the
> AST tree but without MyClass and foo() function, it doesn't even say foo is
> a function with 3 integer parameters.
>
> This can be problematic for different cases for example IDE's where you
> dont have all the project dependencies but yet you need to know what are
> the elements in your code.
>
> Is that possible to do with libclang? Any other suggestions are welcome.
>

You can request that more invalid portions of the AST are retained by using
`-Xclang -frecovery-ast`. In this case, that will preserve the function
call expression as a RecoveryExpr. For now at least, we don't have the
ability to preserve AST information for the invalid "new MyClass" nor the
expression using of undeclared "std::cout" and "endl", but
-frecovery-ast is expected to improve over time to retain more such AST
nodes. (And perhaps eventually it will be enabled by default, at which
point the flag for it might disappear. We don't guarantee any forward
compatibility with -Xclang flags.)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-users/attachments/20200424/22afb43d/attachment.html>


More information about the cfe-users mailing list