如何做一个干净的前端

How to make a clean clang front-end?

本文关键字:前端 何做一      更新时间:2023-10-16

我正在做一个c++源代码分析器项目,看起来clang是一个不错的候选解析工作。问题是clang严重依赖基础设施"llvm"项目,我如何配置它,以获得一个干净的前端没有任何具体的面向机器的后端?就像LCC一样,它们为专注于解析器部分的人提供了一个"空"后端。

我最近在Windows上这样做了。

从这里下载clang和llvm源代码。

安装cmake和Python(与文档相反,你确实需要Python来构建clang;至少,如果找不到Python运行时,cmake会放弃)。

还需要VS2008或VS2010。

有一件事不是很明显,那就是所需的目录结构:
projectRoot
    build  <- intermediate build files and DLLs, etc. will go here
    llvm  <- contents of llvm-3.0.src from llvm-3.0.tar go here
        tools
            clang  <- contents of clang-3.0.src from clang-3.0.tar go here

并从步骤4开始遵循windows构建说明。不要尝试使用cmake GUI,它太可怕了;使用构建指令中给出的命令即可。

一旦构建完成(这需要一些时间),您将有:

projectRoot
    build
        bin
            Release  <- libclang.dll will be here
        lib
            Release  <- libclang.lib will be here
    llvm
        tools
            clang
                include
                    clang-c  <- Index.h is here

Index.h定义了访问源代码信息的API;它包含了相当多关于api的文档。

要开始使用clang,你需要这样做:

CXIndex index = clang_createIndex(1, 1);
// Support Microsoft extensions
char *args[] = {"-fms-extensions"};
CXTranslationUnit tu = clang_parseTranslationUnit(index, "mySource.c", args, ARRAY_SIZE(args), 0, 0, 0);
if (tu)
{
    CXCursor cursor = clang_getTranslationUnitCursor(tu);
    // Use the cursor functions to navigate through the AST
}

不幸的是,如果没有特定于机器的细节,就无法获得"纯"前端。C/c++本质上是机器绑定的语言。想想预处理器和内置定义,内置类型的大小,等等。其中一些可以抽象出来,但不能,例如preprocessor.