cpptoolsreuse.cpp 8.36 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
2
**
3 4
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
7
**
hjk's avatar
hjk committed
8 9 10 11
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
12 13 14
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
15
**
16 17 18 19 20 21 22
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
23
**
hjk's avatar
hjk committed
24
****************************************************************************/
25 26 27

#include "cpptoolsreuse.h"

28 29
#include "cpptoolsplugin.h"

30
#include <coreplugin/documentmanager.h>
31
#include <coreplugin/editormanager/editormanager.h>
32
#include <coreplugin/idocument.h>
33
#include <texteditor/convenience.h>
34

35 36
#include <cplusplus/Overview.h>
#include <cplusplus/LookupContext.h>
37
#include <utils/algorithm.h>
38
#include <utils/qtcassert.h>
39

40
#include <QDebug>
41
#include <QSet>
42
#include <QStringRef>
43 44
#include <QTextCursor>
#include <QTextDocument>
45

46 47
using namespace CPlusPlus;

48 49
namespace CppTools {

50 51 52 53
static void moveCursorToStartOrEndOfIdentifier(QTextCursor *tc,
                                               QTextCursor::MoveOperation op,
                                               int posDiff = 0)
{
54 55 56 57
    QTextDocument *doc = tc->document();
    if (!doc)
        return;

58
    QChar ch = doc->characterAt(tc->position() - posDiff);
59
    while (isValidIdentifierChar(ch)) {
60 61
        tc->movePosition(op);
        ch = doc->characterAt(tc->position() - posDiff);
62 63 64
    }
}

65 66 67 68 69 70 71 72 73 74
void moveCursorToEndOfIdentifier(QTextCursor *tc)
{
    moveCursorToStartOrEndOfIdentifier(tc, QTextCursor::NextCharacter);
}

void moveCursorToStartOfIdentifier(QTextCursor *tc)
{
    moveCursorToStartOrEndOfIdentifier(tc, QTextCursor::PreviousCharacter, 1);
}

75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
static bool isOwnershipRAIIName(const QString &name)
{
    static QSet<QString> knownNames;
    if (knownNames.isEmpty()) {
        // Qt
        knownNames.insert(QLatin1String("QScopedPointer"));
        knownNames.insert(QLatin1String("QScopedArrayPointer"));
        knownNames.insert(QLatin1String("QMutexLocker"));
        knownNames.insert(QLatin1String("QReadLocker"));
        knownNames.insert(QLatin1String("QWriteLocker"));
        // Standard C++
        knownNames.insert(QLatin1String("auto_ptr"));
        knownNames.insert(QLatin1String("unique_ptr"));
        // Boost
        knownNames.insert(QLatin1String("scoped_ptr"));
        knownNames.insert(QLatin1String("scoped_array"));
    }

    return knownNames.contains(name);
}

96
bool isOwnershipRAIIType(Symbol *symbol, const LookupContext &context)
97 98 99 100 101 102 103 104 105 106
{
    if (!symbol)
        return false;

    // This is not a "real" comparison of types. What we do is to resolve the symbol
    // in question and then try to match its name with already known ones.
    if (symbol->isDeclaration()) {
        Declaration *declaration = symbol->asDeclaration();
        const NamedType *namedType = declaration->type()->asNamedType();
        if (namedType) {
107
            ClassOrNamespace *clazz = context.lookupType(namedType->name(),
108 109 110 111 112 113 114 115 116 117 118 119
                                                         declaration->enclosingScope());
            if (clazz && !clazz->symbols().isEmpty()) {
                Overview overview;
                Symbol *symbol = clazz->symbols().at(0);
                return isOwnershipRAIIName(overview.prettyName(symbol->name()));
            }
        }
    }

    return false;
}

120 121
bool isValidAsciiIdentifierChar(const QChar &ch)
{
122
    return ch.isLetterOrNumber() || ch == QLatin1Char('_');
123 124 125 126 127 128 129 130 131 132 133 134
}

bool isValidFirstIdentifierChar(const QChar &ch)
{
    return ch.isLetter() || ch == QLatin1Char('_') || ch.isHighSurrogate() || ch.isLowSurrogate();
}

bool isValidIdentifierChar(const QChar &ch)
{
    return isValidFirstIdentifierChar(ch) || ch.isNumber();
}

135 136 137 138 139 140
bool isValidIdentifier(const QString &s)
{
    const int length = s.length();
    for (int i = 0; i < length; ++i) {
        const QChar &c = s.at(i);
        if (i == 0) {
141
            if (!isValidFirstIdentifierChar(c))
142 143
                return false;
        } else {
144
            if (!isValidIdentifierChar(c))
145 146 147 148 149 150
                return false;
        }
    }
    return true;
}

151 152 153 154 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 185 186 187 188 189 190 191 192 193 194
bool isQtKeyword(const QStringRef &text)
{
    switch (text.length()) {
    case 4:
        switch (text.at(0).toLatin1()) {
        case 'e':
            if (text == QLatin1String("emit"))
                return true;
            break;
        case 'S':
            if (text == QLatin1String("SLOT"))
                return true;
            break;
        }
        break;

    case 5:
        if (text.at(0) == QLatin1Char('s') && text == QLatin1String("slots"))
            return true;
        break;

    case 6:
        if (text.at(0) == QLatin1Char('S') && text == QLatin1String("SIGNAL"))
            return true;
        break;

    case 7:
        switch (text.at(0).toLatin1()) {
        case 's':
            if (text == QLatin1String("signals"))
                return true;
            break;
        case 'f':
            if (text == QLatin1String("foreach") || text ==  QLatin1String("forever"))
                return true;
            break;
        }
        break;

    default:
        break;
    }
    return false;
}
195

196 197 198 199
void switchHeaderSource()
{
    const Core::IDocument *currentDocument = Core::EditorManager::currentDocument();
    QTC_ASSERT(currentDocument, return);
200
    const QString otherFile = correspondingHeaderOrSource(currentDocument->filePath().toString());
201 202 203 204
    if (!otherFile.isEmpty())
        Core::EditorManager::openEditor(otherFile);
}

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
QString identifierUnderCursor(QTextCursor *cursor)
{
    cursor->movePosition(QTextCursor::StartOfWord);
    cursor->movePosition(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
    return cursor->selectedText();
}

const Macro *findCanonicalMacro(const QTextCursor &cursor, Document::Ptr document)
{
    QTC_ASSERT(document, return 0);

    int line, column;
    TextEditor::Convenience::convertPosition(cursor.document(), cursor.position(), &line, &column);

    if (const Macro *macro = document->findMacroDefinitionAt(line)) {
        QTextCursor macroCursor = cursor;
        const QByteArray name = CppTools::identifierUnderCursor(&macroCursor).toUtf8();
        if (macro->name() == name)
            return macro;
    } else if (const Document::MacroUse *use = document->findMacroUseAt(cursor.position())) {
        return &use->macro();
    }

    return 0;
}

231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
TextEditor::TextEditorWidget::Link linkToSymbol(Symbol *symbol)
{
    typedef TextEditor::TextEditorWidget::Link Link;

    if (!symbol)
        return Link();

    const QString filename = QString::fromUtf8(symbol->fileName(),
                                               symbol->fileNameLength());

    unsigned line = symbol->line();
    unsigned column = symbol->column();

    if (column)
        --column;

    if (symbol->isGenerated())
        column = 0;

    return Link(filename, line, column);
}

253 254 255 256 257
QSharedPointer<CppCodeModelSettings> codeModelSettings()
{
    return CppTools::Internal::CppToolsPlugin::instance()->codeModelSettings();
}

258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
int fileSizeLimit()
{
    static const QByteArray fileSizeLimitAsByteArray = qgetenv("QTC_CPP_FILE_SIZE_LIMIT_MB");
    static int fileSizeLimitAsInt = -1;

    if (fileSizeLimitAsInt == -1) {
        bool ok;
        const int limit = fileSizeLimitAsByteArray.toInt(&ok);
        fileSizeLimitAsInt = ok && limit >= 0 ? limit : 0;
    }

    return fileSizeLimitAsInt;
}

bool skipFileDueToSizeLimit(const QFileInfo &fileInfo, int limitInMB)
{
    if (limitInMB == 0) // unlimited
        return false;

277
    const int fileSizeInMB = fileInfo.size() / (1000 * 1000);
278 279 280 281 282 283 284 285 286
    if (fileSizeInMB > limitInMB) {
        qWarning() << "Files to process limited by QTC_CPP_FILE_SIZE_LIMIT_MB, skipping"
                   << fileInfo.absoluteFilePath();
        return true;
    }

    return false;
}

287
} // CppTools