Comment analyser les structs C++ avec lignes de commentaire précédentes du code source en utilisant clang

Note : Posts associés :

Dans nos posts précédents (voir ci-dessus), nous avons montré comment extraire les définitions de structs C++ du code source en utilisant l’analyseur C++ Clang. Dans ce post, nous allons étendre cette fonctionnalité pour inclure également les lignes de commentaire précédentes.

L’extrait de code modifié suivant montre comment analyser les structs C++ et extraire leurs champs, y compris la ligne de commentaire précédente. Bien qu’actuellement capable d’analyser uniquement les commentaires précédents sur une seule ligne, il peut être étendu pour gérer les commentaires multi-lignes également.

Données d’exemple

example_structs.cpp
/* This struct defines my parameters */
typedef struct {
    double a; /* That weird parameter */
    double b; /* Another weird parameter */
} myParameters;

typedef struct {
    double x; /* The x coordinate */
    double y; /* The y coordinate */
} myPoint;

// This struct is used to pass parameters to a function
typedef struct {
    myParameters params; /* Parameters for the function */
    myPoint point;       /* Point to evaluate */
} 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);

    // Trouver la ligne contenant cette déclaration de champ
    const char* lineStart = sourceCode;
    unsigned currentLine = 1;

    // Naviguer jusqu'à la ligne contenant le champ
    while (currentLine < startLine && *lineStart) {
        if (*lineStart == '\n') {
            currentLine++;
        }
        lineStart++;
    }

    // Trouver la fin de la ligne
    const char* lineEnd = lineStart;
    while (*lineEnd && *lineEnd != '\n') {
        lineEnd++;
    }

    // Extraire la ligne comme une chaîne
    std::string line(lineStart, lineEnd - lineStart);

    // Rechercher des commentaires dans cette ligne
    std::string comment = "";

    // Rechercher les commentaires de style /* */
    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);
        }
    }

    // Rechercher les commentaires de style // si aucun commentaire de bloc trouvé
    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);

    // Si nous sommes sur la première ligne, il n'y a pas de ligne précédente
    if (startLine <= 1) {
        return "";
    }

    // Trouver la ligne avant la définition du struct
    const char* lineStart = sourceCode;
    unsigned currentLine = 1;

    // Naviguer jusqu'à la ligne avant la définition du struct
    while (currentLine < startLine - 1 && *lineStart) {
        if (*lineStart == '\n') {
            currentLine++;
        }
        lineStart++;
    }

    // Trouver la fin de la ligne précédente
    const char* lineEnd = lineStart;
    while (*lineEnd && *lineEnd != '\n') {
        lineEnd++;
    }

    // Extraire la ligne comme une chaîne
    std::string line(lineStart, lineEnd - lineStart);

    // Supprimer les espaces de la ligne
    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);
    }

    // Vérifier si la ligne est un commentaire
    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);

        // Extraire le commentaire précédent
        std::string precedingComment = extractPrecedingComment(cursor, sourceCode);

        // Créer l'objet struct en 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);

                // Créer l'objet champ
                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);

        // Ajouter le struct au document
        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 << "Usage: " << 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 << "Failed to parse translation unit." << std::endl;
        return 1;
    }

    // Créer le document JSON
    rapidjson::Document doc;
    doc.SetObject();

    // Lire le contenu du fichier source
    std::ifstream file(filename, std::ios::binary);
    if (!file) {
        std::cerr << "Failed to open file: " << 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);

    // Convertir le JSON en chaîne et afficher
    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;
}

Comment compiler

Sur Ubuntu, installez les bibliothèques requises avec

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

et compilez le code avec

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 d’exécution

Téléchargez ceci comme test_struct.h :

test_struct.h
/* This struct defines my parameters */
typedef struct {
    double a; /* That weird parameter */
    double b; /* Another weird parameter */
} myParameters;

typedef struct {
    double x; /* The x coordinate */
    double y; /* The y coordinate */
} myPoint;

// This struct is used to pass parameters to a function
typedef struct {
    myParameters params; /* Parameters for the function */
    myPoint point;       /* Point to evaluate */
} myFunctionInput;

Ensuite exécutez le programme :

run_parse_struct_test.sh
./parse_struct test_struct.h  | jq

Exemple de sortie

parse_struct_output.json
{
    "myParameters": {
        "fields": [
            {
                "name": "a",
                "type": "double",
                "comment": "/* That weird parameter */"
            },
            {
                "name": "b",
                "type": "double",
                "comment": "/* Another weird parameter */"
            }
        ],
        "precedingComment": "/* This struct defines my parameters */"
    },
    "myPoint": {
        "fields": [
            {
                "name": "x",
                "type": "double",
                "comment": "/* The x coordinate */"
            },
            {
                "name": "y",
                "type": "double",
                "comment": "/* The y coordinate */"
            }
        ]
    },
    "myFunctionInput": {
        "fields": [
            {
                "name": "params",
                "type": "myParameters",
                "comment": "/* Parameters for the function */"
            },
            {
                "name": "point",
                "type": "myPoint",
                "comment": "/* Point to evaluate */"
            }
        ],
        "precedingComment": "// This struct is used to pass parameters to a function"
    }
}

Check out similar posts by category: C/C++, Clang, Source Introspection