9

clang-check -ast-dump -ast-dump-filter=<function_name> main.c gives a AST (only a function declaration) of the particular code.

How can we represent generated AST in JSON format?

PS: I Want AST for function declaration only.

achala
  • 197
  • 1
  • 11

1 Answers1

9

Call clang with the -ast-dump=json argument.

This was implemented only recently (May 2019) so you need an up-to-date version of Clang.

See https://reviews.llvm.org/D60910 for details.

There's also a library to export more lower-level information available via libTooling at https://github.com/facebook/facebook-clang-plugins

Update in 2022: The full command line is now clang -Xclang -ast-dump=json -fsyntax-only <file> since the clang command is now a compilation driver, not just the compiler itself.

Jaen
  • 390
  • 3
  • 6
  • this `-ast-dump=json` is supported with `clang` but not with `clang-check` And this is working fine for C program not C++ – achala Dec 20 '19 at 07:33
  • Using clang from 2021 and it doesn't work for me: `clang.exe: warning: argument unused during compilation: '-ast-dump=json' [-Wunused-command-line-argument]` – kungfooman Jul 05 '22 at 11:21
  • @kungfooman Answer updated for the latest version of clang. – Jaen Jul 06 '22 at 12:10
  • @Jaen The updated answer works perfectly, thank you! Its funny that it generates ~400 lines from a 3 line function. – kungfooman Jul 08 '22 at 13:02
  • 1
    with filter: `clang -fsyntax-only -Xclang -ast-dump=json -Xclang -ast-dump-filter=some_function some_source.cc` – milahu Mar 06 '23 at 16:50