Last active
February 7, 2024 21:17
-
-
Save gilzoide/0c8153a8d164f97a1b61a45682bc8862 to your computer and use it in GitHub Desktop.
Snippet for creating a clang TranslationUnit in python by calling clang as a subprocess instead of parsing with Index.parse
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import subprocess | |
import tempfile | |
import clang.cindex as clang | |
def create_translation_unit_with_ast(source_file_path, clang_args=[], clang_exe='clang'): | |
""" | |
Create a `clang.TranslationUnit` for a source file by compiling it with clang as a | |
subprocess instead of using `clang.Index.parse`. | |
By doing this, clang will dump its errors directly to stderr, which is very nice for | |
oneshot scripts. Also, standard includes like `stddef.h` and `stdbool.h` are handled | |
correctly and we don't have to pass them like `-I/path/to/clang/includes` manually | |
or after parsing the output from `clang -v -E -` or the like. | |
Parameters | |
---------- | |
source_file_path: | |
Path to the input source file. If you want to parse more files, create a new one | |
and `#include<>` all of them. | |
clang_args: | |
Iterable with additional arguments to clang, e.g.: `-I...` or `-D...` | |
clang_exe: | |
Path for the clang executable, defaults to "clang". | |
""" | |
index = clang.Index.create() | |
clang_cmd = [clang_exe, source_file_path, '-emit-ast', '-o', '-'] | |
clang_cmd.extend(clang_args) | |
clang_cmd_result = subprocess.run(clang_cmd, stdout=subprocess.PIPE) | |
# In case of errors, raise `CalledProcessError`. Notice that since we didn't | |
# redirect clang's stderr, the error was already printed to stderr. | |
clang_cmd_result.check_returncode() | |
with tempfile.NamedTemporaryFile() as ast_file: | |
# Since `clang.Index.read` expects a file path, write generated AST to a | |
# temporary named file. This file will be automatically deleted when closed. | |
ast_file.write(clang_cmd_result.stdout) | |
return index.read(ast_file.name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment