[Qt-creator] Accessing the AST

Nikolai Kosjar nikolai.kosjar at digia.com
Mon Apr 22 12:45:46 CEST 2013


On 04/22/2013 11:26 AM, Jesper K. Pedersen wrote:
> 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.

You might be interested in
  * Document::lastVisibleSymbolAt(line, column)
  * QString AbstractEditorSupport::functionAt(const 
CppModelManagerInterface *modelManager, QString &fileName, int line, int 

> 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);

Did you try Document::Ptr document(const QString &fileName)? There is 
also Document::utf8Source(), so you don't need to reread the file and 
create a document.

>      // 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);

I'm not sure in which context you run this, but in general this 
shouldn't be needed after calling document->parse().

>      // 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());

Where is your cursor positioned? Note that if the cursor is on the very 
first or last character of the document (or some whitespace characters 
in front/after), ASTPath will return an empty list since the cursor is 
not considered to be on any AST in these cases.


More information about the Qt-creator mailing list