0

I have a header file for which I want to generate an AST and save it to a file. I run clang-cl on Visual Studio command line like this:

clang-cl <header-path> -Xclang -ast-dump -fsyntax-only -fno-color-diagnostics -w

I then take the output of this command and save it to a file called f.ast. I now want to read the AST from that file with the clang Python bindings. I created the following script:

from clang.cindex import Config, Index
import clang.cindex
import os
import logging

def read_ast(libclang_path, ast_file):
    assert os.path.exists(libclang_path)
    assert os.path.exists(ast_file)
    Config.set_library_file(libclang_path)
    logging.debug("Creating index...")
    index = Index(clang.cindex.conf.lib.clang_createIndex(False, True))
    logging.debug("Reading ast file '{}'...".format(
        ast_file
    ))
    tu = index.read(ast_file)
    assert tu is not None

And called it with appropriate args. After printing "Reading ast file 'f.ast'..." to the terminal, I got the following popup error with title "Microsoft Visual C++ Runtime Library":

Assertion failed!

Program: C:\Program Files (x86)\LLVM\bin\libclang.dll File D:\src\llvm_release_build_3.7.0\llvm.../Bitstre...eader.h Line: 78

Expression: ((End-Start) & 3) == 0 && "Bitcode stream not a multiple of 4 bytes"

Do you know what the problem might be and how to fix it?

Daniel Kats
  • 5,141
  • 15
  • 65
  • 102

1 Answers1

1

The AST dump is a debugging tool. It’s not the same thing as the serialized representation of a translation unit. Use libclang to parse and serialize your header instead of doing it from the command line with clang-cl.

Jason Haslam
  • 2,617
  • 13
  • 19
  • What does the function `read` do in the Python bindings for clang: https://github.com/llvm-mirror/clang/blob/master/bindings/python/clang/cindex.py#L2220)? Is it not meant to read AST generated by -emit-ast or -ast-dump from clang command line? – Daniel Kats Dec 10 '15 at 18:45
  • 2
    `read` takes an AST file that was written with `TranslationUnit.save`. -ast-dump doesn't write an AST file. It prints out the AST in a human readable format. – Jason Haslam Dec 11 '15 at 04:13