Re: using clang for C++ parsing and source-to-source translation
> I am interested in using clang libraries for parsing a subset
> of C++ and then doing source-to-source translation.
> Is there an example of how this can be achieved with clang libraries?
> (parsing C++, constructing AST, resolving names, etc. and then walking AST tree and writing it out in, say, C)
Clang and LLVM can already turn C++ into C:
clang -emit-llvm source.cpp -o - | llc -march=c
If you really want to roll your own, though, here are some tips:
- Use the Frontend library to set up your environment. In particular,
take a look at the CompilerInstance/CompilerInvocation classes.
- You want to derive a class from ASTConsumer (from the AST library).
This interface accepts a fully parsed and (possibly) annotated AST as input.
- The Rewriter library does what you want. It allows you to rewrite
source code on the fly. Take a look at lib/Frontend/RewriteObjC.cpp as
an example (for ObjC->C++).
> Basically what I was thinking about was using clang libraries
> to add some rudimentary C++ support (namespaces, basic templates,
> operator overload, functors, etc.)
> to OpenCL to make it more CUDA-like. So, I just want to instantiate appropriate templates and perform correct namespace lookup while leaving everything else much intact. What would be your recommendation?
The Sema library supports namespace lookup and template instantiation.
The LookupQualifiedName() method of the Sema class lets you perform
qualified lookup (which is what you want). Of course, I'm not sure you'd
want to do this, because all uses of decls inside namespaces should
already have been resolved; all you should have to do is rewrite the
namespaces away, then rewrite the decls inside to have mangled names. Right?
The Sema machinery for template instantiation, however, is a bit
complicated. You'll have to ask Doug Gregor (he wrote most of it) or
possibly John McCall about it, because to be honest I don't really
understand it that well :). If you're curious, the files
lib/Sema/SemaTemplateInstantiateDecl.cpp contain this support.
If you want this kind of support, though, you'll have to make your
ASTConsumer into a SemaConsumer (which isn't hard, because SemaConsumer
is derived from ASTConsumer).
> At first glance, it seems that name mangling is a bit of a problem.
The CodeGen library has a name mangler built into it. You may be able to
use it. Take a look at lib/CodeGen/Mangle.cpp.