如何使用 clang 从源代码中解析带前置注释行的 C++ 结构体

注意:相关文章:

在我们之前的文章中(见上文),我们展示了如何使用 Clang C++ 解析器从源代码中提取 C++ 结构体定义。在这篇文章中,我们将扩展该功能以包含前置注释行。

以下修改后的代码片段演示了如何解析 C++ 结构体并提取其字段,包括前置注释行。虽然目前只能解析单行前置注释,但可以扩展以处理多行注释。

示例数据

example_structs.cpp
/* 此结构体定义了我的参数 */
typedef struct {
    double a; /* 那个奇怪的参数 */
    double b; /* 另一个奇怪的参数 */
} myParameters;

typedef struct {
    double x; /* x 坐标 */
    double y; /* y 坐标 */
} myPoint;

// 此结构体用于向函数传递参数
typedef struct {
    myParameters params; /* 函数的参数 */
    myPoint point;       /* 要评估的点 */
} myFunctionInput;
parse_struct_with_comments.cpp
#include <clang-c/Index.h>
#include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <fstream>
#include <rapidjson/document.h>
#include <rapidjson/writer.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/prettywriter.h>

std::string extractInlineComment(CXCursor cursor, const char* sourceCode) {
    if (sourceCode == nullptr) {
        return "";
    }

    CXSourceRange range = clang_getCursorExtent(cursor);
    CXSourceLocation start = clang_getRangeStart(range);
    CXSourceLocation end = clang_getRangeEnd(range);

    CXFile file;
    unsigned startLine, startColumn, startOffset;
    unsigned endLine, endColumn, endOffset;

    clang_getExpansionLocation(start, &file, &startLine, &startColumn, &startOffset);
    clang_getExpansionLocation(end, &file, &endLine, &endColumn, &endOffset);

    // 查找包含此字段声明的行
    const char* lineStart = sourceCode;
    unsigned currentLine = 1;

    // 导航到包含该字段的行
    while (currentLine < startLine && *lineStart) {
        if (*lineStart == '\n') {
            currentLine++;
        }
        lineStart++;
    }

    // 查找行尾
    const char* lineEnd = lineStart;
    while (*lineEnd && *lineEnd != '\n') {
        lineEnd++;
    }

    // 将该行提取为字符串
    std::string line(lineStart, lineEnd - lineStart);

    // 在此行中查找注释
    std::string comment = "";

    // 查找 /* */ 风格的注释
    size_t blockStart = line.find("/*");
    if (blockStart != std::string::npos) {
        size_t blockEnd = line.find("*/", blockStart);
        if (blockEnd != std::string::npos) {
            comment = line.substr(blockStart, blockEnd - blockStart + 2);
        }
    }

    // 如果未找到块注释,则查找 // 风格的注释
    if (comment.empty()) {
        size_t lineCommentStart = line.find("//");
        if (lineCommentStart != std::string::npos) {
            comment = line.substr(lineCommentStart);
        }
    }

    return comment;
}

std::string extractPrecedingComment(CXCursor cursor, const char* sourceCode) {
    if (sourceCode == nullptr) {
        return "";
    }

    CXSourceRange range = clang_getCursorExtent(cursor);
    CXSourceLocation start = clang_getRangeStart(range);

    CXFile file;
    unsigned startLine, startColumn, startOffset;

    clang_getExpansionLocation(start, &file, &startLine, &startColumn, &startOffset);

    // 如果在第一行,则没有前置行
    if (startLine <= 1) {
        return "";
    }

    // 查找结构体定义之前的行
    const char* lineStart = sourceCode;
    unsigned currentLine = 1;

    // 导航到结构体定义之前的行
    while (currentLine < startLine - 1 && *lineStart) {
        if (*lineStart == '\n') {
            currentLine++;
        }
        lineStart++;
    }

    // 查找前一行的结尾
    const char* lineEnd = lineStart;
    while (*lineEnd && *lineEnd != '\n') {
        lineEnd++;
    }

    // 将该行提取为字符串
    std::string line(lineStart, lineEnd - lineStart);

    // 去除行首尾的空白字符
    size_t start_pos = line.find_first_not_of(" \t\r");
    if (start_pos == std::string::npos) {
        return "";
    }

    line = line.substr(start_pos);
    size_t end_pos = line.find_last_not_of(" \t\r");
    if (end_pos != std::string::npos) {
        line = line.substr(0, end_pos + 1);
    }

    // 检查该行是否为注释
    if (line.find("//") == 0 || (line.find("/*") == 0 && line.find("*/") != std::string::npos)) {
        return line;
    }

    return "";
}

struct VisitorData {
    const char* sourceCode;
    rapidjson::Value* fieldsArray;
    rapidjson::Document::AllocatorType* allocator;
};

void extractStructFields(CXCursor cursor, const char* sourceCode, rapidjson::Document& doc) {
    CXCursorKind kind = clang_getCursorKind(cursor);
    if (kind == CXCursor_StructDecl) {
        CXString structName = clang_getCursorDisplayName(cursor);
        std::string structNameStr = clang_getCString(structName);

        // 提取前置注释
        std::string precedingComment = extractPrecedingComment(cursor, sourceCode);

        // 在 JSON 中创建结构体对象
        rapidjson::Value structObj(rapidjson::kObjectType);
        rapidjson::Value fieldsArray(rapidjson::kArrayType);

        clang_disposeString(structName);

        VisitorData data = {sourceCode, &fieldsArray, &doc.GetAllocator()};

        clang_visitChildren(cursor, [](CXCursor c, CXCursor parent, CXClientData client_data) {
            VisitorData* data = static_cast<VisitorData*>(client_data);
            const char* sourceCode = data->sourceCode;
            rapidjson::Value* fieldsArray = data->fieldsArray;
            rapidjson::Document::AllocatorType* allocator = data->allocator;

            CXCursorKind kind = clang_getCursorKind(c);
            if (kind == CXCursor_FieldDecl) {
                CXString fieldName = clang_getCursorDisplayName(c);
                CXType fieldType = clang_getCursorType(c);
                CXString typeName = clang_getTypeSpelling(fieldType);

                std::string comment = extractInlineComment(c, sourceCode);
                std::string fieldNameStr = clang_getCString(fieldName);
                std::string typeNameStr = clang_getCString(typeName);

                // 创建字段对象
                rapidjson::Value fieldObj(rapidjson::kObjectType);
                rapidjson::Value nameVal(fieldNameStr.c_str(), *allocator);
                rapidjson::Value typeVal(typeNameStr.c_str(), *allocator);
                rapidjson::Value commentVal(comment.c_str(), *allocator);

                fieldObj.AddMember("name", nameVal, *allocator);
                fieldObj.AddMember("type", typeVal, *allocator);
                fieldObj.AddMember("comment", commentVal, *allocator);

                fieldsArray->PushBack(fieldObj, *allocator);

                clang_disposeString(fieldName);
                clang_disposeString(typeName);
            }
            return CXChildVisit_Continue;
        }, &data);

        // 将结构体添加到文档中
        structObj.AddMember("fields", fieldsArray, doc.GetAllocator());
        if (!precedingComment.empty()) {
            rapidjson::Value precedingCommentVal(precedingComment.c_str(), doc.GetAllocator());
            structObj.AddMember("precedingComment", precedingCommentVal, doc.GetAllocator());
        }
        rapidjson::Value structNameVal(structNameStr.c_str(), doc.GetAllocator());
        doc.AddMember(structNameVal, structObj, doc.GetAllocator());
    }
}

int main(int argc, char* argv[]) {
    if (argc != 2) {
        std::cerr << "用法:" << argv[0] << " <filename>" << std::endl;
        return 1;
    }

    const char* filename = argv[1];
    CXIndex index = clang_createIndex(0, 0);

    CXTranslationUnit unit = clang_parseTranslationUnit(index, filename, nullptr, 0, nullptr, 0,
                                                    CXTranslationUnit_DetailedPreprocessingRecord |
                                                    CXTranslationUnit_SkipFunctionBodies);
    if (unit == nullptr) {
        std::cerr << "解析翻译单元失败。" << std::endl;
        return 1;
    }

    // 创建 JSON 文档
    rapidjson::Document doc;
    doc.SetObject();

    // 读取源文件内容
    std::ifstream file(filename, std::ios::binary);
    if (!file) {
        std::cerr << "打开文件失败:" << filename << std::endl;
        return 1;
    }

    file.seekg(0, std::ios::end);
    size_t fileSize = file.tellg();
    file.seekg(0, std::ios::beg);

    std::string sourceCode(fileSize, '\0');
    file.read(&sourceCode[0], fileSize);
    file.close();

    struct CallbackData {
        rapidjson::Document* doc;
        const char* sourceCode;
    };

    CallbackData callbackData = {&doc, sourceCode.c_str()};

    CXCursor cursor = clang_getTranslationUnitCursor(unit);
    clang_visitChildren(cursor, [](CXCursor c, CXCursor parent, CXClientData client_data) {
        CallbackData* data = static_cast<CallbackData*>(client_data);
        extractStructFields(c, data->sourceCode, *(data->doc));
        return CXChildVisit_Continue;
    }, &callbackData);

    // 将 JSON 转换为字符串并输出
    rapidjson::StringBuffer buffer;
    rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
    doc.Accept(writer);

    std::cout << buffer.GetString() << std::endl;

    clang_disposeTranslationUnit(unit);
    clang_disposeIndex(index);
    return 0;
}

如何编译

在 Ubuntu 上,使用以下命令安装所需的库:

install_libclang19.sh
sudo apt -y install libclang-19-dev

并使用以下命令编译代码:

build_parse_struct.sh
g++ parse_struct_with_comments.cpp -o parse_struct_with_comments -std=c++17 -I/usr/lib/llvm-19/include -L/usr/lib/llvm-19/lib -lclang

测试运行

将此下载为 test_struct.h:

test_struct.h
/* 此结构体定义了我的参数 */
typedef struct {
    double a; /* 那个奇怪的参数 */
    double b; /* 另一个奇怪的参数 */
} myParameters;

typedef struct {
    double x; /* x 坐标 */
    double y; /* y 坐标 */
} myPoint;

// 此结构体用于向函数传递参数
typedef struct {
    myParameters params; /* 函数的参数 */
    myPoint point;       /* 要评估的点 */
} myFunctionInput;

然后运行程序:

run_parse_struct_test.sh
./parse_struct test_struct.h  | jq

示例输出

parse_struct_output.json
{
    "myParameters": {
        "fields": [
            {
                "name": "a",
                "type": "double",
                "comment": "/* 那个奇怪的参数 */"
            },
            {
                "name": "b",
                "type": "double",
                "comment": "/* 另一个奇怪的参数 */"
            }
        ],
        "precedingComment": "/* 此结构体定义了我的参数 */"
    },
    "myPoint": {
        "fields": [
            {
                "name": "x",
                "type": "double",
                "comment": "/* x 坐标 */"
            },
            {
                "name": "y",
                "type": "double",
                "comment": "/* y 坐标 */"
            }
        ]
    },
    "myFunctionInput": {
        "fields": [
            {
                "name": "params",
                "type": "myParameters",
                "comment": "/* 函数的参数 */"
            },
            {
                "name": "point",
                "type": "myPoint",
                "comment": "/* 要评估的点 */"
            }
        ],
        "precedingComment": "// 此结构体用于向函数传递参数"
    }
}

按类别查看类似文章: C/C++ Clang 源码内省