watchutils.cpp 46.8 KB
Newer Older
1 2 3 4 5 6
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
7
** Contact: Nokia Corporation (qt-info@nokia.com)
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
26
** contact the sales department at http://www.qtsoftware.com/contact.
27 28 29 30
**
**************************************************************************/

#include "watchutils.h"
31 32
#include "watchhandler.h"
#include <utils/qtcassert.h>
33

34 35 36 37 38 39 40 41 42 43 44 45
#include <texteditor/basetexteditor.h>
#include <texteditor/basetextmark.h>
#include <texteditor/itexteditor.h>
#include <texteditor/texteditorconstants.h>

#include <cpptools/cppmodelmanagerinterface.h>
#include <cpptools/cpptoolsconstants.h>

#include <cplusplus/ExpressionUnderCursor.h>

#include <extensionsystem/pluginmanager.h>

46 47 48
#include <QtCore/QDebug>
#include <QtCore/QTime>
#include <QtCore/QStringList>
49 50 51
#include <QtCore/QCoreApplication>
#include <QtCore/QTextStream>

52 53 54
#include <QtGui/QTextCursor>
#include <QtGui/QPlainTextEdit>

55 56 57 58
#include <string.h>
#include <ctype.h>

enum { debug = 0 };
59 60 61 62 63 64

namespace Debugger {
namespace Internal {

QString dotEscape(QString str)
{
65
    const QChar dot = QLatin1Char('.');
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
    str.replace(QLatin1Char(' '), dot);
    str.replace(QLatin1Char('\\'), dot);
    str.replace(QLatin1Char('/'), dot);
    return str;
}

QString currentTime()
{
    return QTime::currentTime().toString(QLatin1String("hh:mm:ss.zzz"));
}

bool isSkippableFunction(const QString &funcName, const QString &fileName)
{
    if (fileName.endsWith(QLatin1String("kernel/qobject.cpp")))
        return true;
    if (fileName.endsWith(QLatin1String("kernel/moc_qobject.cpp")))
        return true;
    if (fileName.endsWith(QLatin1String("kernel/qmetaobject.cpp")))
        return true;
    if (fileName.endsWith(QLatin1String(".moc")))
        return true;

    if (funcName.endsWith("::qt_metacall"))
        return true;

    return false;
}

bool isLeavableFunction(const QString &funcName, const QString &fileName)
{
    if (funcName.endsWith(QLatin1String("QObjectPrivate::setCurrentSender")))
        return true;
    if (fileName.endsWith(QLatin1String("kernel/qmetaobject.cpp"))
            && funcName.endsWith(QLatin1String("QMetaObject::methodOffset")))
        return true;
    if (fileName.endsWith(QLatin1String("kernel/qobject.h")))
        return true;
    if (fileName.endsWith(QLatin1String("kernel/qobject.cpp"))
            && funcName.endsWith(QLatin1String("QObjectConnectionListVector::at")))
        return true;
    if (fileName.endsWith(QLatin1String("kernel/qobject.cpp"))
            && funcName.endsWith(QLatin1String("~QObject")))
        return true;
    if (fileName.endsWith(QLatin1String("thread/qmutex.cpp")))
        return true;
    if (fileName.endsWith(QLatin1String("thread/qthread.cpp")))
        return true;
    if (fileName.endsWith(QLatin1String("thread/qthread_unix.cpp")))
        return true;
    if (fileName.endsWith(QLatin1String("thread/qmutex.h")))
        return true;
    if (fileName.contains(QLatin1String("thread/qbasicatomic")))
        return true;
    if (fileName.contains(QLatin1String("thread/qorderedmutexlocker_p")))
        return true;
    if (fileName.contains(QLatin1String("arch/qatomic")))
        return true;
    if (fileName.endsWith(QLatin1String("tools/qvector.h")))
        return true;
    if (fileName.endsWith(QLatin1String("tools/qlist.h")))
        return true;
    if (fileName.endsWith(QLatin1String("tools/qhash.h")))
        return true;
    if (fileName.endsWith(QLatin1String("tools/qmap.h")))
        return true;
    if (fileName.endsWith(QLatin1String("tools/qstring.h")))
        return true;
    if (fileName.endsWith(QLatin1String("global/qglobal.h")))
        return true;

    return false;
}

bool hasLetterOrNumber(const QString &exp)
{
    const QChar underscore = QLatin1Char('_');
    for (int i = exp.size(); --i >= 0; )
        if (exp.at(i).isLetterOrNumber() || exp.at(i) == underscore)
            return true;
    return false;
}

bool hasSideEffects(const QString &exp)
{
    // FIXME: complete?
    return exp.contains(QLatin1String("-="))
        || exp.contains(QLatin1String("+="))
        || exp.contains(QLatin1String("/="))
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
154
        || exp.contains(QLatin1String("%="))
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
        || exp.contains(QLatin1String("*="))
        || exp.contains(QLatin1String("&="))
        || exp.contains(QLatin1String("|="))
        || exp.contains(QLatin1String("^="))
        || exp.contains(QLatin1String("--"))
        || exp.contains(QLatin1String("++"));
}

bool isKeyWord(const QString &exp)
{
    // FIXME: incomplete
    return exp == QLatin1String("class")
        || exp == QLatin1String("const")
        || exp == QLatin1String("do")
        || exp == QLatin1String("if")
        || exp == QLatin1String("return")
        || exp == QLatin1String("struct")
        || exp == QLatin1String("template")
        || exp == QLatin1String("void")
        || exp == QLatin1String("volatile")
        || exp == QLatin1String("while");
}

bool isPointerType(const QString &type)
{
    return type.endsWith(QLatin1Char('*')) || type.endsWith(QLatin1String("* const"));
}

bool isAccessSpecifier(const QString &str)
{
hjk's avatar
hjk committed
185 186 187 188
    static const QStringList items = QStringList()
        << QLatin1String("private")
        << QLatin1String("protected")
        << QLatin1String("public");
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
    return items.contains(str);
}

bool startsWithDigit(const QString &str)
{
    return !str.isEmpty() && str.at(0).isDigit();
}

QString stripPointerType(QString type)
{
    if (type.endsWith(QLatin1Char('*')))
        type.chop(1);
    if (type.endsWith(QLatin1String("* const")))
        type.chop(7);
    if (type.endsWith(QLatin1Char(' ')))
        type.chop(1);
    return type;
}

QString gdbQuoteTypes(const QString &type)
{
    // gdb does not understand sizeof(Core::IFile*).
    // "sizeof('Core::IFile*')" is also not acceptable,
    // it needs to be "sizeof('Core::IFile'*)"
    //
    // We never will have a perfect solution here (even if we had a full blown
    // C++ parser as we do not have information on what is a type and what is
    // a variable name. So "a<b>::c" could either be two comparisons of values
    // 'a', 'b' and '::c', or a nested type 'c' in a template 'a<b>'. We
    // assume here it is the latter.
    //return type;

    // (*('myns::QPointer<myns::QObject>*'*)0x684060)" is not acceptable
    // (*('myns::QPointer<myns::QObject>'**)0x684060)" is acceptable
    if (isPointerType(type))
        return gdbQuoteTypes(stripPointerType(type)) + QLatin1Char('*');

    QString accu;
    QString result;
    int templateLevel = 0;

    const QChar colon = QLatin1Char(':');
    const QChar singleQuote = QLatin1Char('\'');
    const QChar lessThan = QLatin1Char('<');
    const QChar greaterThan = QLatin1Char('>');
    for (int i = 0; i != type.size(); ++i) {
        const QChar c = type.at(i);
        if (c.isLetterOrNumber() || c == QLatin1Char('_') || c == colon || c == QLatin1Char(' ')) {
            accu += c;
        } else if (c == lessThan) {
            ++templateLevel;
            accu += c;
        } else if (c == greaterThan) {
            --templateLevel;
            accu += c;
        } else if (templateLevel > 0) {
            accu += c;
        } else {
            if (accu.contains(colon) || accu.contains(lessThan))
                result += singleQuote + accu + singleQuote;
            else
                result += accu;
            accu.clear();
            result += c;
        }
    }
    if (accu.contains(colon) || accu.contains(lessThan))
        result += singleQuote + accu + singleQuote;
    else
        result += accu;
    //qDebug() << "GDB_QUOTING" << type << " TO " << result;

    return result;
}

bool extractTemplate(const QString &type, QString *tmplate, QString *inner)
{
    // Input "Template<Inner1,Inner2,...>::Foo" will return "Template::Foo" in
    // 'tmplate' and "Inner1@Inner2@..." etc in 'inner'. Result indicates
    // whether parsing was successful
    int level = 0;
    bool skipSpace = false;

    for (int i = 0; i != type.size(); ++i) {
        const QChar c = type.at(i);
        if (c == QLatin1Char(' ') && skipSpace) {
            skipSpace = false;
        } else if (c == QLatin1Char('<')) {
            *(level == 0 ? tmplate : inner) += c;
            ++level;
        } else if (c == QLatin1Char('>')) {
            --level;
            *(level == 0 ? tmplate : inner) += c;
        } else if (c == QLatin1Char(',')) {
            *inner += (level == 1) ? QLatin1Char('@') : QLatin1Char(',');
            skipSpace = true;
        } else {
            *(level == 0 ? tmplate : inner) += c;
        }
    }
    *tmplate = tmplate->trimmed();
    *tmplate = tmplate->remove(QLatin1String("<>"));
    *inner = inner->trimmed();
    //qDebug() << "EXTRACT TEMPLATE: " << *tmplate << *inner << " FROM " << type;
    return !inner->isEmpty();
}

QString extractTypeFromPTypeOutput(const QString &str)
{
    int pos0 = str.indexOf(QLatin1Char('='));
    int pos1 = str.indexOf(QLatin1Char('{'));
    int pos2 = str.lastIndexOf(QLatin1Char('}'));
    QString res = str;
    if (pos0 != -1 && pos1 != -1 && pos2 != -1)
        res = str.mid(pos0 + 2, pos1 - 1 - pos0)
            + QLatin1String(" ... ") + str.right(str.size() - pos2);
    return res.simplified();
}

bool isIntOrFloatType(const QString &type)
{
    static const QStringList types = QStringList()
        << QLatin1String("char") << QLatin1String("int") << QLatin1String("short")
        << QLatin1String("float") << QLatin1String("double") << QLatin1String("long")
        << QLatin1String("bool") << QLatin1String("signed char") << QLatin1String("unsigned")
        << QLatin1String("unsigned char")
        << QLatin1String("unsigned int") << QLatin1String("unsigned long")
        << QLatin1String("long long")  << QLatin1String("unsigned long long");
    return types.contains(type);
}

QString sizeofTypeExpression(const QString &type)
{
    if (type.endsWith(QLatin1Char('*')))
        return QLatin1String("sizeof(void*)");
    if (type.endsWith(QLatin1Char('>')))
        return QLatin1String("sizeof(") + type + QLatin1Char(')');
    return QLatin1String("sizeof(") + gdbQuoteTypes(type) + QLatin1Char(')');
}

329 330
// Utilities to decode string data returned by the dumper helpers.

331
QString quoteUnprintableLatin1(const QByteArray &ba)
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
{
    QString res;
    char buf[10];
    for (int i = 0, n = ba.size(); i != n; ++i) {
        const unsigned char c = ba.at(i);
        if (isprint(c)) {
            res += c;
        } else {
            qsnprintf(buf, sizeof(buf) - 1, "\\%x", int(c));
            res += buf;
        }
    }
    return res;
}

hjk's avatar
hjk committed
347
QString decodeData(const QByteArray &ba, int encoding)
348 349 350
{
    switch (encoding) {
        case 0: // unencoded 8 bit data
hjk's avatar
hjk committed
351
            return quoteUnprintableLatin1(ba);
352 353 354
        case 1: { //  base64 encoded 8 bit data, used for QByteArray
            const QChar doubleQuote(QLatin1Char('"'));
            QString rc = doubleQuote;
hjk's avatar
hjk committed
355
            rc += quoteUnprintableLatin1(QByteArray::fromBase64(ba));
356 357 358 359 360
            rc += doubleQuote;
            return rc;
        }
        case 2: { //  base64 encoded 16 bit data, used for QString
            const QChar doubleQuote(QLatin1Char('"'));
361
            const QByteArray decodedBa = QByteArray::fromBase64(ba);
362
            QString rc = doubleQuote;
363
            rc += QString::fromUtf16(reinterpret_cast<const ushort *>(decodedBa.data()), decodedBa.size() / 2);
364 365 366 367
            rc += doubleQuote;
            return rc;
        }
        case 3: { //  base64 encoded 32 bit data
368
            const QByteArray decodedBa = QByteArray::fromBase64(ba);
369 370
            const QChar doubleQuote(QLatin1Char('"'));
            QString rc = doubleQuote;
371
            rc += QString::fromUcs4(reinterpret_cast<const uint *>(decodedBa.data()), decodedBa.size() / 4);
372 373 374 375
            rc += doubleQuote;
            return rc;
        }
        case 4: { //  base64 encoded 16 bit data, without quotes (see 2)
376 377
            const QByteArray decodedBa = QByteArray::fromBase64(ba);
            return QString::fromUtf16(reinterpret_cast<const ushort *>(decodedBa.data()), decodedBa.size() / 2);
378
        }
379 380 381
        case 5: { //  base64 encoded 8 bit data, without quotes (see 1)
            return quoteUnprintableLatin1(QByteArray::fromBase64(ba));
        }
382 383 384 385
    }
    return QCoreApplication::translate("Debugger", "<Encoding error>");
}

386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
// Editor tooltip support
bool isCppEditor(Core::IEditor *editor)
{
    static QStringList cppMimeTypes;
    if (cppMimeTypes.empty()) {
        cppMimeTypes << QLatin1String(CppTools::Constants::C_SOURCE_MIMETYPE)
                << QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE)
                << QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE)
                << QLatin1String(CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE);
    }
    if (const Core::IFile *file = editor->file())
        return cppMimeTypes.contains(file->mimeType());
    return  false;
}

// Find the function the cursor is in to use a scope.


    


// Return the Cpp expression, and, if desired, the function
QString cppExpressionAt(TextEditor::ITextEditor *editor, int pos,
                        int *line, int *column, QString *function /* = 0 */)
{

    *line = *column = 0;
    if (function)
        function->clear();

    const QPlainTextEdit *plaintext = qobject_cast<QPlainTextEdit*>(editor->widget());
    if (!plaintext)
        return QString();

    QString expr = plaintext->textCursor().selectedText();
    if (expr.isEmpty()) {
        QTextCursor tc(plaintext->document());
        tc.setPosition(pos);

        const QChar ch = editor->characterAt(pos);
        if (ch.isLetterOrNumber() || ch == QLatin1Char('_'))
            tc.movePosition(QTextCursor::EndOfWord);

        // Fetch the expression's code.
        CPlusPlus::ExpressionUnderCursor expressionUnderCursor;
        expr = expressionUnderCursor(tc);
        *column = tc.columnNumber();
        *line = tc.blockNumber();
    } else {
        const QTextCursor tc = plaintext->textCursor();
        *column = tc.columnNumber();
        *line = tc.blockNumber();
    }    

    if (function && !expr.isEmpty())
        if (const Core::IFile *file = editor->file())
            if (CppTools::CppModelManagerInterface *modelManager = ExtensionSystem::PluginManager::instance()->getObject<CppTools::CppModelManagerInterface>())
                *function = CppTools::AbstractEditorSupport::functionAt(modelManager, file->fileName(), *line, *column);

    return expr;
}

448 449 450
// --------------- QtDumperResult

QtDumperResult::Child::Child() :
451 452 453
   valueEncoded(0),
   childCount(0),
   valuedisabled(false)
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
{
}

QtDumperResult::QtDumperResult() :
    valueEncoded(0),
    valuedisabled(false),
    childCount(0),
    internal(false)
{
}

void QtDumperResult::clear()
{
    iname.clear();
    value.clear();
    address.clear();
    type.clear();
471
    displayedType.clear();
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
    valueEncoded = 0;
    valuedisabled = false;
    childCount = 0;
    internal = false;
    childType.clear();
    children.clear();
}

QList<WatchData> QtDumperResult::toWatchData(int source) const
{
    QList<WatchData> rc;
    rc.push_back(WatchData());
    WatchData &root = rc.front();
    root.iname = iname;
    const QChar dot = QLatin1Char('.');
    const int lastDotIndex = root.iname.lastIndexOf(dot);
    root.exp = root.name = lastDotIndex == -1 ? iname : iname.mid(lastDotIndex + 1);
    root.setValue(decodeData(value, valueEncoded));
490
    root.setType(displayedType.isEmpty() ? type : displayedType);
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
    root.valuedisabled = valuedisabled;
    root.setAddress(address);
    root.source = source;
    root.setChildCount(childCount);
    // Children
    if (childCount > 0) {
        if (children.size() == childCount) {
            for (int c = 0; c < childCount; c++) {
                const Child &dchild = children.at(c);
                rc.push_back(WatchData());
                WatchData &wchild = rc.back();
                wchild.source = source;
                wchild.iname = iname;
                wchild.iname += dot;
                wchild.iname += dchild.name;                
506 507 508 509
                wchild.name = dchild.name;
                wchild.exp = dchild.exp;
                wchild.valuedisabled = dchild.valuedisabled;
                wchild.setType(dchild.type.isEmpty() ? childType : dchild.type);
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
                wchild.setAddress(dchild.address);
                wchild.setValue(decodeData(dchild.value, dchild.valueEncoded));
                wchild.setChildCount(0);
            }
            root.setChildrenUnneeded();
        } else {
            root.setChildrenNeeded();
        }
    }
    return rc;
}

QDebug operator<<(QDebug in, const QtDumperResult &d)
{
    QDebug nospace = in.nospace();
525 526
    nospace << " iname=" << d.iname << " type=" << d.type << " displayed=" << d.displayedType
            << " address=" << d.address
527 528 529
            << " value="  << d.value
            << " disabled=" << d.valuedisabled
            << " encoded=" << d.valueEncoded << " internal=" << d.internal;
530 531 532
    const int realChildCount = d.children.size();
    if (d.childCount || realChildCount) {
        nospace << " childCount=" << d.childCount << '/' << realChildCount
533
                << " childType=" << d.childType << '\n';
534
        for (int i = 0; i < realChildCount; i++) {
535 536
            const QtDumperResult::Child &c = d.children.at(i);
            nospace << "   #" << i << " addr=" << c.address
537
                    << " disabled=" << c.valuedisabled
538
                    << " type=" << c.type << " exp=" << c.exp
539
                    << " name=" << c.name << " encoded=" << c.valueEncoded
540 541
                    << " value=" << c.value
                    << "childcount=" << c.childCount << '\n';
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
        }
    }
    return in;
}

// ----------------- QtDumperHelper::TypeData
QtDumperHelper::TypeData::TypeData() :
    type(UnknownType),
    isTemplate(false)
{
}

void QtDumperHelper::TypeData::clear()
{
    isTemplate = false;
    type = UnknownType;
    tmplate.clear();
    inner.clear();
}

// ----------------- QtDumperHelper
563 564
const QString stdAllocatorPrefix = QLatin1String("std::allocator");

565
QtDumperHelper::QtDumperHelper() :
566 567 568
    m_intSize(0),
    m_pointerSize(0),
    m_stdAllocatorSize(0),
569 570 571 572 573 574 575 576 577
    m_qtVersion(0)
{
}

void QtDumperHelper::clear()
{
    m_nameTypeMap.clear();
    m_qtVersion = 0;
    m_qtNamespace.clear();
578 579 580 581
    m_sizeCache.clear();
    m_intSize = 0;
    m_pointerSize = 0;
    m_stdAllocatorSize = 0;
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
}

static inline void formatQtVersion(int v, QTextStream &str)
{
    str  << ((v >> 16) & 0xFF) << '.' << ((v >> 8) & 0xFF) << '.' << (v & 0xFF);
}

QString QtDumperHelper::toString(bool debug) const
{
    if (debug)  {
        QString rc;
        QTextStream str(&rc);
        str << "version=";
        formatQtVersion(m_qtVersion, str);
        str << " namespace='" << m_qtNamespace << "'," << m_nameTypeMap.size() << " known types: ";
        const NameTypeMap::const_iterator cend = m_nameTypeMap.constEnd();
        for (NameTypeMap::const_iterator it = m_nameTypeMap.constBegin(); it != cend; ++it) {
            str <<",[" << it.key() << ',' << it.value() << ']';
        }
601 602 603 604 605 606
        str << "Sizes: intsize=" << m_intSize << " pointer size=" << m_pointerSize
                << " allocatorsize=" << m_stdAllocatorSize;
        const SizeCache::const_iterator scend = m_sizeCache.constEnd();
        for (SizeCache::const_iterator it = m_sizeCache.constBegin(); it != scend; ++it) {
            str << ' ' << it.key() << '=' << it.value();
        }
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
        return rc;
    }
    const QString nameSpace = m_qtNamespace.isEmpty() ? QCoreApplication::translate("QtDumperHelper", "<none>") : m_qtNamespace;
    return QCoreApplication::translate("QtDumperHelper",
                                       "%n known types, Qt version: %1, Qt namespace: %2",
                                       0, QCoreApplication::CodecForTr,
                                       m_nameTypeMap.size()).arg(qtVersionString(), nameSpace);
}

QtDumperHelper::Type QtDumperHelper::simpleType(const QString &simpleType) const
{
    return m_nameTypeMap.value(simpleType, UnknownType);
}

int QtDumperHelper::qtVersion() const
{
    return m_qtVersion;
}

QString QtDumperHelper::qtNamespace() const
{
    return m_qtNamespace;
}

void QtDumperHelper::setQtNamespace(const QString &qtNamespace)
{
    m_qtNamespace = qtNamespace;
}

int QtDumperHelper::typeCount() const
{
    return m_nameTypeMap.size();
}

// Look up unnamespaced 'std' types.
static inline QtDumperHelper::Type stdType(const QString &s)
{
    if (s == QLatin1String("vector"))
        return QtDumperHelper::StdVectorType;
    if (s == QLatin1String("deque"))
        return QtDumperHelper::StdDequeType;
    if (s == QLatin1String("set"))
        return QtDumperHelper::StdSetType;
    if (s == QLatin1String("stack"))
        return QtDumperHelper::StdStackType;
    if (s == QLatin1String("map"))
        return QtDumperHelper::StdMapType;
    if (s == QLatin1String("basic_string"))
        return QtDumperHelper::StdStringType;
    return QtDumperHelper::UnknownType;
}

QtDumperHelper::Type QtDumperHelper::specialType(QString s)
{
    // Std classes.
    if (s.startsWith(QLatin1String("std::")))
        return stdType(s.mid(5));
    // Strip namespace
665
    // FIXME: that's not a good idea as it makes all namespaces equal.
666 667 668 669 670 671 672
    const int namespaceIndex = s.lastIndexOf(QLatin1String("::"));
    if (namespaceIndex == -1) {
        // None ... check for std..
        const Type sType = stdType(s);
        if (sType != UnknownType)
            return sType;
    } else {
673
        s = s.mid(namespaceIndex + 2);
674 675 676 677 678 679 680 681 682 683 684
    }
    if (s == QLatin1String("QObject"))
        return QObjectType;
    if (s == QLatin1String("QWidget"))
        return QWidgetType;
    if (s == QLatin1String("QObjectSlot"))
        return QObjectSlotType;
    if (s == QLatin1String("QObjectSignal"))
        return QObjectSignalType;
    if (s == QLatin1String("QVector"))
        return QVectorType;
685 686
    if (s == QLatin1String("QAbstractItem"))
        return QAbstractItemType;
687 688 689 690 691 692 693 694 695 696 697 698
    if (s == QLatin1String("QMap"))
        return QMapType;
    if (s == QLatin1String("QMultiMap"))
        return QMultiMapType;
    if (s == QLatin1String("QMapNode"))
        return QMapNodeType;
    return UnknownType;
}

bool QtDumperHelper::needsExpressionSyntax(Type t)
{
    switch (t) {
699
        case QAbstractItemType:
700 701 702 703 704 705 706 707 708 709
        case QObjectSlotType:
        case QObjectSignalType:
        case QMapType:
        case QVectorType:
        case QMultiMapType:
        case QMapNodeType:
        case StdMapType:
            return true;
        default:
            break;
hjk's avatar
hjk committed
710
    }
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
    return false;
}

QString QtDumperHelper::qtVersionString() const
{
    QString rc;
    QTextStream str(&rc);
    formatQtVersion(m_qtVersion, str);
    return rc;
}

void QtDumperHelper::setQtVersion(int v)
{
    m_qtVersion = v;
}

void QtDumperHelper::setQtVersion(const QString &v)
{
    m_qtVersion = 0;
    const QStringList vl = v.split(QLatin1Char('.'));
    if (vl.size() == 3) {
        const int major = vl.at(0).toInt();
        const int minor = vl.at(1).toInt();
        const int patch = vl.at(2).toInt();
        m_qtVersion = (major << 16) | (minor << 8) | patch;
    }
}

// Parse a list of types.
void QtDumperHelper::parseQueryTypes(const QStringList &l, Debugger debugger)
{
    m_nameTypeMap.clear();
    const int count = l.count();
    for (int i = 0; i < count; i++) {
        const Type t = specialType(l.at(i));
        if (t != UnknownType) {
            // Exclude types that require expression syntax for CDB
hjk's avatar
hjk committed
748
            if (debugger == GdbDebugger || !needsExpressionSyntax(t))
749 750 751 752 753 754 755 756 757 758 759 760 761 762
                m_nameTypeMap.insert(l.at(i), t);
        } else {
            m_nameTypeMap.insert(l.at(i), SupportedType);
        }
    }
}

/*  A parse for dumper output:
 * "iname="local.sl",addr="0x0012BA84",value="<3 items>",valuedisabled="true",
 * numchild="3",childtype="QString",childnumchild="0",children=[{name="0",value="<binhex>",
 * valueencoded="2"},{name="1",value="dAB3AG8A",valueencoded="2"},{name="2",
 * value="dABoAHIAZQBlAA==",valueencoded="2"}]"
 * Default implementation can be used for debugging purposes. */

hjk's avatar
hjk committed
763 764
class DumperParser
{
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
public:
    explicit DumperParser(const char *s) : m_s(s) {}
    bool run();

protected:
    // handle 'key="value"'
    virtual bool handleKeyword(const char *k, int size);
    virtual bool handleListStart();
    virtual bool handleListEnd();
    virtual bool handleHashStart();
    virtual bool handleHashEnd();
    virtual bool handleValue(const char *k, int size);

private:
    bool parseHash(int level, const char *&pos);
    bool parseValue(int level, const char *&pos);
    bool parseStringValue(const char *&ptr, int &size, const char *&pos) const;

    const char *m_s;
};

// get a string value with pos at the opening double quote
bool DumperParser::parseStringValue(const char *&ptr, int &size, const char *&pos) const
{
    pos++;
    const char *endValuePtr = strchr(pos, '"');
    if (!endValuePtr)
        return false;
    size = endValuePtr - pos;
    ptr = pos;
    pos = endValuePtr + 1;
    return true;
}

bool DumperParser::run()
{
    const char *ptr = m_s;
    const bool rc = parseHash(0, ptr);
    if (debug)
        qDebug() << Q_FUNC_INFO << '\n' << m_s << rc;
    return rc;
}

// Parse a non-empty hash with pos at the first keyword.
// Curly braces are present at level 0 only.
// '{a="X", b="X"}'
bool DumperParser::parseHash(int level, const char *&pos)
{
    while (true) {
        switch (*pos) {
        case '\0': // EOS is acceptable at level 0 only
            return level == 0;
        case '}':
            pos++;
            return true;
        default:
            break;
        }
        const char *equalsPtr = strchr(pos, '=');
        if (!equalsPtr)
            return false;
        const int keywordLen = equalsPtr - pos;
        if (!handleKeyword(pos, keywordLen))
            return false;
        pos = equalsPtr + 1;
        if (!*pos)
            return false;        
        if (!parseValue(level + 1, pos))
            return false;    
        if (*pos == ',')
            pos++;
    }
    return false;
}

bool DumperParser::parseValue(int level, const char *&pos)
{
    // Simple string literal
    switch (*pos) {
    case '"': {
            const char *valuePtr;
            int valueSize;
            return parseStringValue(valuePtr, valueSize, pos) && handleValue(valuePtr, valueSize);
        }
        // A List. Note that it has a trailing comma '["a",]'
    case '[': {
            if (!handleListStart())
                return false;
            pos++;
            while (true) {
                switch (*pos) {
                case ']':
                    pos++;
                    return handleListEnd();
                case '\0':
                    return false;
                default:
                    break;
                }
                if (!parseValue(level + 1, pos))
                    return false;
                if (*pos == ',')
                    pos++;
            }
        }        
        return false;
        // A hash '{a="b",b="c"}'
    case '{': {
            if (!handleHashStart())
                return false;
            pos++;
            if (!parseHash(level + 1, pos))
                return false;            
            return handleHashEnd();
        }
        return false;
    }
    return false;
}

bool DumperParser::handleKeyword(const char *k, int size)
{
    if (debug)
        qDebug() << Q_FUNC_INFO << '\n' << QByteArray(k, size);
    return true;
}

bool DumperParser::handleListStart()
{
    if (debug)
        qDebug() << Q_FUNC_INFO;
    return true;
}

bool DumperParser::handleListEnd()
{
    if (debug)
        qDebug() << Q_FUNC_INFO;
    return true;
}

bool DumperParser::handleHashStart()
{
    if (debug)
        qDebug() << Q_FUNC_INFO;
    return true;
}

bool DumperParser::handleHashEnd()
{
    if (debug)
        qDebug() << Q_FUNC_INFO;

    return true;
}

bool DumperParser::handleValue(const char *k, int size)
{
    if (debug)
        qDebug() << Q_FUNC_INFO << '\n' << QByteArray(k, size);
    return true;
}

928 929 930 931
/* Parse 'query' (1) protocol response of the custom dumpers:
 * "'dumpers=["QByteArray","QDateTime",..."std::basic_string",],
 * qtversion=["4","5","1"],namespace="""' */

932 933
class QueryDumperParser : public DumperParser {
public:
934
    typedef QPair<QString, int> SizeEntry;
935 936 937 938 939 940 941
    explicit QueryDumperParser(const char *s);

    struct Data {
        Data() : qtVersion(0) {}
        QString qtNameSpace;
        QString qtVersion;
        QStringList types;
942
        QList<SizeEntry> sizes;
943 944 945 946 947 948
    };

    inline Data data() const { return m_data; }

protected:
    virtual bool handleKeyword(const char *k, int size);
949
    virtual bool handleListStart();    
950
    virtual bool handleListEnd();
951
    virtual bool handleHashEnd();
952 953 954
    virtual bool handleValue(const char *k, int size);

private:
955
    enum Mode { None, ExpectingDumpers, ExpectingVersion, ExpectingNameSpace, ExpectingSizes };
956 957
    Mode m_mode;
    Data m_data;
958
    QString m_lastSizeType;
959 960 961 962 963 964 965 966 967
};

QueryDumperParser::QueryDumperParser(const char *s) :
    DumperParser(s),
    m_mode(None)
{
}

bool QueryDumperParser::handleKeyword(const char *k, int size)        
968 969 970 971 972
{    
    if (m_mode == ExpectingSizes) {
        m_lastSizeType = QString::fromLatin1(k, size);
        return true;
    }
973 974 975 976 977 978 979 980 981 982 983 984
    if (!qstrncmp(k, "dumpers", size)) {
        m_mode = ExpectingDumpers;
        return true;
    }
    if (!qstrncmp(k, "qtversion", size)) {
        m_mode = ExpectingVersion;
        return true;
    }
    if (!qstrncmp(k, "namespace", size)) {
        m_mode = ExpectingNameSpace;
        return true;
    }
985 986 987 988
    if (!qstrncmp(k, "sizes", size)) {
        m_mode = ExpectingSizes;
        return true;
    }
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
    qWarning("%s Unexpected keyword %s.\n", Q_FUNC_INFO, QByteArray(k, size).constData());
    return false;
}

bool QueryDumperParser::handleListStart()
{
    return m_mode == ExpectingDumpers || m_mode == ExpectingVersion;
}

bool QueryDumperParser::handleListEnd()
{
    m_mode = None;
    return true;
}

1004 1005 1006 1007 1008 1009
bool QueryDumperParser::handleHashEnd()
{
    m_mode = None; // Size hash
    return true;
}

1010 1011 1012
bool QueryDumperParser::handleValue(const char *k, int size)
{
    switch (m_mode) {
1013
    case None:
1014
        return false;
1015
    case ExpectingDumpers:
1016 1017
        m_data.types.push_back(QString::fromLatin1(k, size));
        break;
1018
    case ExpectingNameSpace:
1019 1020 1021 1022 1023 1024 1025
        m_data.qtNameSpace = QString::fromLatin1(k, size);
        break;
    case ExpectingVersion: // ["4","1","5"]
        if (!m_data.qtVersion.isEmpty())
            m_data.qtVersion += QLatin1Char('.');
        m_data.qtVersion += QString::fromLatin1(k, size);
        break;
1026 1027 1028
    case ExpectingSizes:
        m_data.sizes.push_back(SizeEntry(m_lastSizeType, QString::fromLatin1(k, size).toInt()));
        break;
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
    }
    return true;
}

// parse a query
bool QtDumperHelper::parseQuery(const char *data, Debugger debugger)
{
    QueryDumperParser parser(data);
    if (!parser.run())
        return false;
    clear();
    m_qtNamespace = parser.data().qtNameSpace;
    setQtVersion(parser.data().qtVersion);
    parseQueryTypes(parser.data().types, debugger);
1043 1044
    foreach (const QueryDumperParser::SizeEntry &se, parser.data().sizes)
        addSize(se.first, se.second);
1045 1046 1047
    return true;
}

1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
void QtDumperHelper::addSize(const QString &name, int size)
{
    // Special interest cases
    do {
        if (name == QLatin1String("char*")) {
            m_pointerSize = size;
            break;
        }
        if (name == QLatin1String("int")) {
            m_intSize = size;
            break;
        }
1060
        if (name.startsWith(stdAllocatorPrefix)) {
1061 1062 1063 1064 1065 1066 1067 1068
            m_stdAllocatorSize = size;
            break;
        }
        if (name == QLatin1String("std::string")) {
            m_sizeCache.insert(QLatin1String("std::basic_string<char,std::char_traits<char>,std::allocator<char>>"), size);
            break;
        }
        if (name == QLatin1String("std::wstring")) {
1069
            // FIXME: check space between > > below?
1070 1071 1072 1073 1074 1075 1076
            m_sizeCache.insert(QLatin1String("std::basic_string<unsigned short,std::char_traits<unsignedshort>,std::allocator<unsignedshort> >"), size);
            break;
        }
    } while (false);
    m_sizeCache.insert(name, size);
}

1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
QtDumperHelper::Type QtDumperHelper::type(const QString &typeName) const
{
    const QtDumperHelper::TypeData td = typeData(typeName);
    return td.type;
}

QtDumperHelper::TypeData QtDumperHelper::typeData(const QString &typeName) const
{
    TypeData td;
    td.type = UnknownType;
    const Type st = simpleType(typeName);
    if (st != UnknownType) {
        td.isTemplate = false;
1090
        td.type = st;
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
        return td;
    }
    // Try template
    td.isTemplate = extractTemplate(typeName, &td.tmplate, &td.inner);
    if (!td.isTemplate)
        return td;
    // Check the template type QMap<X,Y> -> 'QMap'
    td.type = simpleType(td.tmplate);
    return td;
}

1102 1103 1104 1105 1106 1107 1108 1109
// Format an expression to have the debugger query the
// size. Use size cache if possible
QString QtDumperHelper::evaluationSizeofTypeExpression(const QString &typeName,
                                                       Debugger /* debugger */) const
{
    // Look up fixed types
    if (m_pointerSize && isPointerType(typeName))
        return QString::number(m_pointerSize);
1110
    if (m_stdAllocatorSize && typeName.startsWith(stdAllocatorPrefix))
1111 1112 1113 1114 1115 1116 1117 1118
        return QString::number(m_stdAllocatorSize);
    const SizeCache::const_iterator sit = m_sizeCache.constFind(typeName);
    if (sit != m_sizeCache.constEnd())
        return QString::number(sit.value());
    // Finally have the debugger evaluate
    return sizeofTypeExpression(typeName);
}

1119 1120
void QtDumperHelper::evaluationParameters(const WatchData &data,
                                          const TypeData &td,
1121
                                          Debugger debugger,
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
                                          QByteArray *inBuffer,
                                          QStringList *extraArgsIn) const
{
    enum { maxExtraArgCount = 4 };

    QStringList &extraArgs = *extraArgsIn;

    // See extractTemplate for parameters
    QStringList inners = td.inner.split(QLatin1Char('@'));
    if (inners.at(0).isEmpty())
        inners.clear();
    for (int i = 0; i != inners.size(); ++i)
        inners[i] = inners[i].simplified();

    QString outertype = td.isTemplate ? td.tmplate : data.type;
    // adjust the data extract
    if (outertype == m_qtNamespace + QLatin1String("QWidget"))
        outertype = m_qtNamespace + QLatin1String("QObject");

1141 1142
    QString inner = td.inner;

1143 1144 1145 1146 1147 1148 1149
    extraArgs.clear();

    if (!inners.empty()) {
        // "generic" template dumpers: passing sizeof(argument)
        // gives already most information the dumpers need
        const int count = qMin(int(maxExtraArgCount), inners.size());
        for (int i = 0; i < count; i++)
1150
            extraArgs.push_back(evaluationSizeofTypeExpression(inners.at(i), debugger));
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
    }
    int extraArgCount = extraArgs.size();
    // Pad with zeros
    const QString zero = QString(QLatin1Char('0'));
    const int extraPad = maxExtraArgCount - extraArgCount;
    for (int i = 0; i < extraPad; i++)
        extraArgs.push_back(zero);

    // in rare cases we need more or less:
    switch (td.type) {
1161 1162 1163
    case QAbstractItemType:
        inner = data.addr.mid(1);
        break;
1164 1165
    case QObjectType:
    case QWidgetType:
1166 1167 1168 1169 1170 1171 1172 1173
        if (debugger == GdbDebugger) {
            extraArgs[0] = QLatin1String("(char*)&((('");
            extraArgs[0] += m_qtNamespace;
            extraArgs[0] += QLatin1String("QObjectPrivate'*)&");
            extraArgs[0] += data.exp;
            extraArgs[0] += QLatin1String(")->children)-(char*)&");
            extraArgs[0] += data.exp;
        }
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
        break;
    case QVectorType:
        extraArgs[1] = QLatin1String("(char*)&((");
        extraArgs[1] += data.exp;
        extraArgs[1] += QLatin1String(").d->array)-(char*)");
        extraArgs[1] += data.exp;
        extraArgs[1] +=  QLatin1String(".d");
        break;
    case QObjectSlotType:
    case QObjectSignalType: {
            // we need the number out of something like
            // iname="local.ob.slots.2" // ".deleteLater()"?
            const int pos = data.iname.lastIndexOf('.');
            const QString slotNumber = data.iname.mid(pos + 1);
            QTC_ASSERT(slotNumber.toInt() != -1, /**/);
            extraArgs[0] = slotNumber;
        }
        break;
    case QMapType:
    case QMultiMapType: {
            QString nodetype;
            if (m_qtVersion >= (4 << 16) + (5 << 8) + 0) {
                nodetype = m_qtNamespace + QLatin1String("QMapNode");
                nodetype += data.type.mid(outertype.size());
1198
            } else {
1199 1200
                // FIXME: doesn't work for QMultiMap
                nodetype  = data.type + QLatin1String("::Node");
1201
            }
1202 1203
            //qDebug() << "OUTERTYPE: " << outertype << " NODETYPE: " << nodetype
            //    << "QT VERSION" << m_qtVersion << ((4 << 16) + (5 << 8) + 0);
1204
            extraArgs[2] = evaluationSizeofTypeExpression(nodetype, debugger);
1205 1206 1207
            extraArgs[3] = QLatin1String("(size_t)&(('");
            extraArgs[3] += nodetype;
            extraArgs[3] += QLatin1String("'*)0)->value");
1208
        }
1209 1210
        break;
            case QMapNodeType:
1211
        extraArgs[2] = evaluationSizeofTypeExpression(data.type, debugger);
1212 1213 1214 1215 1216 1217 1218 1219 1220
        extraArgs[3] = QLatin1String("(size_t)&(('");
        extraArgs[3] += data.type;
        extraArgs[3] += QLatin1String("'*)0)->value");
        break;
    case StdVectorType:
        //qDebug() << "EXTRACT TEMPLATE: " << outertype << inners;
        if (inners.at(0) == QLatin1String("bool")) {
            outertype = QLatin1String("std::vector::bool");
        } else {
1221
            //extraArgs[extraArgCount++] = evaluationSizeofTypeExpression(data.type, debugger);
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
            //extraArgs[extraArgCount++] = "(size_t)&(('" + data.type + "'*)0)->value";
        }
        break;
    case StdDequeType:
        extraArgs[1] = zero;
    case StdStackType:
        // remove 'std::allocator<...>':
        extraArgs[1] = zero;
        break;
    case StdSetType:
        // remove 'std::less<...>':
        extraArgs[1] = zero;
        // remove 'std::allocator<...>':
        extraArgs[2] = zero;
        break;
    case StdMapType: {
            // We don't want the comparator and the allocator confuse gdb.
            // But we need the offset of the second item in the value pair.
            // We read the type of the pair from the allocator argument because
            // that gets the constness "right" (in the sense that gdb can
            // read it back;
            QString pairType = inners.at(3);
            // remove 'std::allocator<...>':
            pairType = pairType.mid(15, pairType.size() - 15 - 2);
            extraArgs[2] = QLatin1String("(size_t)&(('");
            extraArgs[2] += pairType;
            extraArgs[2] += QLatin1String("'*)0)->second");
            extraArgs[3] = zero;
        }
        break;
    case StdStringType:
        //qDebug() << "EXTRACT TEMPLATE: " << outertype << inners;
        if (inners.at(0) == QLatin1String("char")) {
            outertype = QLatin1String("std::string");
        } else if (inners.at(0) == QLatin1String("wchar_t")) {
            outertype = QLatin1String("std::wstring");
        }
        qFill(extraArgs, zero);
        break;
    case UnknownType:
        qWarning("Unknown type encountered in %s.\n", Q_FUNC_INFO);
        break;
    case SupportedType:
        break;
    }

    inBuffer->clear();
    inBuffer->append(outertype.toUtf8());
    inBuffer->append('\0');
    inBuffer->append(data.iname.toUtf8());
    inBuffer->append('\0');
    inBuffer->append(data.exp.toUtf8());
    inBuffer->append('\0');
1275
    inBuffer->append(inner.toUtf8());
1276
    inBuffer->append('\0');
1277 1278
    inBuffer->append(data.iname.toUtf8());
    inBuffer->append('\0');
1279 1280 1281 1282 1283 1284 1285

    if (debug)
        qDebug() << '\n' << Q_FUNC_INFO << '\n' << data.toString() << "\n-->" << outertype << td.type << extraArgs;
}

/* Parse value:
 * "iname="local.sl",addr="0x0012BA84",value="<3 items>",valuedisabled="true",
hjk's avatar
hjk committed
1286 1287 1288 1289
 * numchild="3",childtype="QString",childnumchild="0",
 * children=[{name="0",value="<binhex>",valueencoded="2"},
 * {name="1",value="dAB3AG8A",valueencoded="2"},
 * {name="2",value="dABoAHIAZQBlAA==",valueencoded="2"}]" */
1290

hjk's avatar
hjk committed
1291 1292
class ValueDumperParser : public DumperParser
{
1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
public:
    explicit ValueDumperParser(const char *s);

    inline QtDumperResult result() const { return m_result; }

protected:
    virtual bool handleKeyword(const char *k, int size);
    virtual bool handleHashStart();
    virtual bool handleValue(const char *k, int size);

private:
    enum Mode { None, ExpectingIName, ExpectingAddress, ExpectingValue,
1305
                ExpectingType, ExpectingDisplayedType, ExpectingInternal,
1306
                ExpectingValueDisabled,  ExpectingValueEncoded,
1307
                ExpectingCommonChildType, ExpectingChildCount,
1308 1309 1310
                IgnoreNext,
                ChildModeStart,
                ExpectingChildren,ExpectingChildName, ExpectingChildAddress,
1311 1312 1313 1314
                ExpectingChildExpression, ExpectingChildType,
                ExpectingChildValue, ExpectingChildValueEncoded,
                ExpectingChildValueDisabled, ExpectingChildChildCount
              };
1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332

    static inline Mode nextMode(Mode in, const char *keyword, int size);

    Mode m_mode;
    QtDumperResult m_result;
};

ValueDumperParser::ValueDumperParser(const char *s) :
   DumperParser(s),
   m_mode(None)
{
}

// Check key words
ValueDumperParser::Mode ValueDumperParser::nextMode(Mode in, const char *keyword, int size)
{
    // Careful with same prefix
    switch (size) {
1333 1334 1335 1336
    case 3:
        if (!qstrncmp(keyword, "exp", size))
            return ExpectingChildExpression;
        break;
1337 1338 1339 1340
    case 4:
        if (!qstrncmp(keyword, "addr", size))
            return in > ChildModeStart ? ExpectingChildAddress : ExpectingAddress;
        if (!qstrncmp(keyword, "type", size))
1341
            return in > ChildModeStart ? ExpectingChildType : ExpectingType;
1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354
        if (!qstrncmp(keyword, "name", size))
            return ExpectingChildName;
        break;
    case 5:
        if (!qstrncmp(keyword, "iname", size))
            return ExpectingIName;
        if (!qstrncmp(keyword, "value", size))
            return in > ChildModeStart ? ExpectingChildValue : ExpectingValue;
        break;
    case 8:
        if (!qstrncmp(keyword, "children", size))
            return ExpectingChildren;
        if (!qstrncmp(keyword, "numchild", size))
1355
            return in > ChildModeStart ?  ExpectingChildChildCount : ExpectingChildCount;
1356 1357 1358 1359 1360
        if (!qstrncmp(keyword, "internal", size))
            return ExpectingInternal;
        break;
    case 9:
        if (!qstrncmp(keyword, "childtype", size))
1361
            return ExpectingCommonChildType;
1362 1363 1364 1365 1366 1367 1368
        break;    
    case 12:
        if (!qstrncmp(keyword, "valueencoded", size))
            return in > ChildModeStart ? ExpectingChildValueEncoded : ExpectingValueEncoded;
        break;
    case 13:
        if (!qstrncmp(keyword, "valuedisabled", size))
1369 1370 1371
            return in > ChildModeStart ? ExpectingChildValueDisabled : ExpectingValueDisabled;
        if (!qstrncmp(keyword, "displayedtype", size))
            return ExpectingDisplayedType;
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418
        if (!qstrncmp(keyword, "childnumchild", size))
            return IgnoreNext;
        break;
    }
    return IgnoreNext;
}

bool ValueDumperParser::handleKeyword(const char *k, int size)
{
    const Mode newMode = nextMode(m_mode, k, size);
    if (debug && newMode == IgnoreNext)
        qWarning("%s Unexpected keyword %s.\n", Q_FUNC_INFO, QByteArray(k, size).constData());
    m_mode = newMode;
    return true;
}

bool ValueDumperParser::handleHashStart()
{
    m_result.children.push_back(QtDumperResult::Child());
    return true;
}

bool ValueDumperParser::handleValue(const char *k, int size)
{
    const QByteArray valueBA(k, size);
    switch (m_mode) {
    case None:
    case ChildModeStart:
        return false;
    case ExpectingIName:
        m_result.iname = QString::fromLatin1(valueBA);
        break;
    case ExpectingAddress:
        m_result.address = QString::fromLatin1(valueBA);
        break;
    case ExpectingValue:
        m_result.value = valueBA;
        break;
    case ExpectingValueDisabled:
        m_result.valuedisabled = valueBA == "true";
        break;
    case ExpectingValueEncoded:
        m_result.valueEncoded = QString::fromLatin1(valueBA).toInt();
        break;
    case ExpectingType:
        m_result.type = QString::fromLatin1(valueBA);
        break;
1419 1420 1421
    case ExpectingDisplayedType:
        m_result.displayedType = QString::fromLatin1(valueBA);
        break;
1422 1423 1424
    case ExpectingInternal:
        m_result.internal = valueBA == "true";
        break;
1425
    case ExpectingCommonChildType:
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442
        m_result.childType = QString::fromLatin1(valueBA);
        break;
    case ExpectingChildCount:
        m_result.childCount = QString::fromLatin1(valueBA).toInt();
        break;
    case ExpectingChildren:
    case IgnoreNext:
        break;
    case ExpectingChildName:
        m_result.children.back().name = QString::fromLatin1(valueBA);
        break;
    case ExpectingChildAddress:
        m_result.children.back().address = QString::fromLatin1(valueBA);
        break;
    case ExpectingChildValue:
        m_result.children.back().value = valueBA;
        break;
1443 1444 1445
    case ExpectingChildExpression:
        m_result.children.back().exp = QString::fromLatin1(valueBA);
        break;
1446 1447 1448
    case ExpectingChildValueEncoded:
        m_result.children.back().valueEncoded = QString::fromLatin1(valueBA).toInt();
        break;
1449 1450 1451 1452 1453 1454 1455 1456 1457
    case ExpectingChildValueDisabled:
        m_result.children.back().valuedisabled = valueBA == "true";
        break;
    case ExpectingChildType:
        m_result.children.back().type = QString::fromLatin1(valueBA);
        break;
    case ExpectingChildChildCount:
        m_result.children.back().childCount = QString::fromLatin1(valueBA).toInt();
        break;
1458 1459 1460 1461
    }
    return true;
}

1462 1463 1464 1465 1466 1467
bool QtDumperHelper::parseValue(const char *data, QtDumperResult *r)
{    
    ValueDumperParser parser(data);
    if (!parser.run())
        return false;
    *r = parser.result();
1468 1469 1470
    // Sanity
    if (r->childCount < r->children.size())
        r->childCount  = r->children.size();
1471 1472
    if (debug)
        qDebug() << '\n' << data << *r;
1473 1474 1475
    return true;
}

1476 1477 1478 1479 1480 1481 1482 1483 1484
QDebug operator<<(QDebug in, const QtDumperHelper::TypeData &d)
{
    QDebug nsp = in.nospace();
    nsp << " type=" << d.type << " tpl=" << d.isTemplate;
    if (d.isTemplate)
        nsp << d.tmplate << '<' << d.inner << '>';
    return in;
}

hjk's avatar
hjk committed
1485 1486
} // namespace Internal
} // namespace Debugger