[Qt-creator] Accessing the AST

Jesper K. Pedersen jesper.pedersen at kdab.com
Mon Apr 22 11:26:59 CEST 2013


Greetings,

I'm working with Nicolas Arnaud-Cormos on developing a scripting interface to Qt Creator[1]. Our hope is to lower the bar for automating tasks.

I'm currently trying to get my hands on the AST for a given file, so I e.g. can tell which method and class I'm in. I have some trouble getting a valid AST, despite hours of browsing the code. 

Here is what I currently have:

I believe that my luck is made, as soon as I can get something valid out of ASTPath::operator(), which returns a list of AST*, so I'm working backwards from that.

    // Fetch information about line, coumn and file name
    Core::IEditor* editor = Core::EditorManager::instance()->currentEditor();
    const int line = editor->currentLine();
    const int column = editor->currentColumn();
    const QString fileName = editor->document()->fileName();

    // Fetch document content
    QFile file(editor->document()->fileName());
    file.open(QFile::ReadOnly);
    const QByteArray content = file.readAll();

    // Get a Document pointer
    CPlusPlus::Snapshot snapshot = CPlusPlus::CppModelManagerInterface::instance()->snapshot();
    CPlusPlus::Document::Ptr document = snapshot.documentFromSource(content, fileName);
    const bool ok = document->parse(CPlusPlus::Document::ParseTranlationUnit);

    // OK, I'm desperate, so lets wait a bit in case something needs to initialize asyncronic
    QTime time;
    time.start();
    while ( time.elapsed() < 2000 )
        qApp->processEvents(QEventLoop::AllEvents, 100);


    // Give me an AST, please
    QList<AST *> path = ASTPath(document)(editor->currentLine(), editor->currentColumn());

    qDebug("Result:\nFileName: %s\nColumn: %d\nLine: %d\nParsed OK: %d\nLength of result from ASTPath: %d", qPrintable(fileName), column, line, ok, path.count());

Now, I try to execute this code on a C++ file loaded from a valid QMake project. The result is:
Result:
FileName: /home/blackie/Klaralv/training-material/addon/dialogs/sol-orderform/orderform.cpp
Column: 25
Line: 28
Parsed OK: 1
Length of result from ASTPath: 0

Everything seems OK, still I don't get any AST's back.

Any hints on what I do wrong, or even better on how to do it right would be greatly appreciated.

Kind Regards
Jesper.

[1] http://qt-project.org/wiki/Scripting
-- 
Jesper K. Pedersen | jesper.pedersen at kdab.com
Training Director and Senior Software Engineer
Klarälvdalens Datakonsult AB, a KDAB Group company
Tel. Direct: +45 5146 8464, Sweden (HQ) +46-563-540090
KDAB - Qt Experts - Platform-independent software solutions



More information about the Qt-creator mailing list