cppquickfixes.cpp 201 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
2
**
3
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
hjk's avatar
hjk committed
4
** Contact: http://www.qt-project.org/legal
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
7
**
hjk's avatar
hjk committed
8
9
10
11
12
13
14
** 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
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
15
16
**
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17
18
19
20
21
22
23
24
25
** 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.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
con's avatar
con committed
26
27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
29

Nikolai Kosjar's avatar
Nikolai Kosjar committed
30
31
#include "cppquickfixes.h"

32
#include "cppeditor.h"
33
#include "cppfunctiondecldeflink.h"
Leandro Melo's avatar
Leandro Melo committed
34
#include "cppquickfixassistant.h"
35

36
37
#include <coreplugin/icore.h>

38
#include <cpptools/cppclassesfilter.h>
39
#include <cpptools/cppcodestylesettings.h>
40
41
#include <cpptools/cpppointerdeclarationformatter.h>
#include <cpptools/cpptoolsconstants.h>
42
#include <cpptools/cpptoolsreuse.h>
43
#include <cpptools/includeutils.h>
44
#include <cpptools/insertionpointlocator.h>
45
#include <cpptools/symbolfinder.h>
46

47
#include <cplusplus/ASTPath.h>
48
#include <cplusplus/CPlusPlusForwardDeclarations.h>
49
50
51
52
#include <cplusplus/CppRewriter.h>
#include <cplusplus/DependencyTable.h>
#include <cplusplus/TypeOfExpression.h>

53
#include <extensionsystem/pluginmanager.h>
54

55
56
57
#include <texteditor/fontsettings.h>
#include <texteditor/texteditorsettings.h>

58
59
#include <utils/qtcassert.h>

60
#include <QApplication>
61
62
63
#include <QCheckBox>
#include <QComboBox>
#include <QDialogButtonBox>
64
#include <QDir>
65
#include <QFileInfo>
66
67
#include <QGroupBox>
#include <QHBoxLayout>
68
#include <QInputDialog>
69
70
#include <QItemDelegate>
#include <QLabel>
71
#include <QMessageBox>
72
73
74
#include <QPointer>
#include <QPushButton>
#include <QQueue>
Nikolai Kosjar's avatar
Nikolai Kosjar committed
75
#include <QSharedPointer>
76
77
#include <QSortFilterProxyModel>
#include <QStandardItemModel>
78
79
#include <QTextBlock>
#include <QTextCursor>
80
81
#include <QTreeView>
#include <QVBoxLayout>
82

Nikolai Kosjar's avatar
Nikolai Kosjar committed
83
84
#include <cctype>

85
using namespace CPlusPlus;
86
87
using namespace CppEditor;
using namespace CppEditor::Internal;
88
89
90
using namespace CppTools;
using namespace TextEditor;
using namespace Utils;
Nikolai Kosjar's avatar
Nikolai Kosjar committed
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

void CppEditor::Internal::registerQuickFixes(ExtensionSystem::IPlugin *plugIn)
{
    plugIn->addAutoReleasedObject(new AddIncludeForUndefinedIdentifier);
    plugIn->addAutoReleasedObject(new AddIncludeForForwardDeclaration);

    plugIn->addAutoReleasedObject(new FlipLogicalOperands);
    plugIn->addAutoReleasedObject(new InverseLogicalComparison);
    plugIn->addAutoReleasedObject(new RewriteLogicalAnd);

    plugIn->addAutoReleasedObject(new ConvertToCamelCase);

    plugIn->addAutoReleasedObject(new ConvertCStringToNSString);
    plugIn->addAutoReleasedObject(new ConvertNumericLiteral);
    plugIn->addAutoReleasedObject(new TranslateStringLiteral);
    plugIn->addAutoReleasedObject(new WrapStringLiteral);

    plugIn->addAutoReleasedObject(new MoveDeclarationOutOfIf);
    plugIn->addAutoReleasedObject(new MoveDeclarationOutOfWhile);

    plugIn->addAutoReleasedObject(new SplitIfStatement);
    plugIn->addAutoReleasedObject(new SplitSimpleDeclaration);

    plugIn->addAutoReleasedObject(new AddLocalDeclaration);
    plugIn->addAutoReleasedObject(new AddBracesToIf);
    plugIn->addAutoReleasedObject(new RearrangeParamDeclarationList);
    plugIn->addAutoReleasedObject(new ReformatPointerDeclaration);

    plugIn->addAutoReleasedObject(new CompleteSwitchCaseStatement);
    plugIn->addAutoReleasedObject(new InsertQtPropertyMembers);

    plugIn->addAutoReleasedObject(new ApplyDeclDefLinkChanges);
    plugIn->addAutoReleasedObject(new ExtractFunction);
    plugIn->addAutoReleasedObject(new GenerateGetterSetter);
    plugIn->addAutoReleasedObject(new InsertDeclFromDef);
    plugIn->addAutoReleasedObject(new InsertDefFromDecl);
127
128
129

    plugIn->addAutoReleasedObject(new MoveFuncDefOutside);
    plugIn->addAutoReleasedObject(new MoveFuncDefToDecl);
130
131

    plugIn->addAutoReleasedObject(new AssignToLocalVariable);
132
133

    plugIn->addAutoReleasedObject(new InsertVirtualMethods);
134
135

    plugIn->addAutoReleasedObject(new OptimizeForLoop);
Nikolai Kosjar's avatar
Nikolai Kosjar committed
136
}
137

138
139
140
141
// In the following anonymous namespace all functions are collected, which could be of interest for
// different quick fixes.
namespace {

142
143
144
145
146
147
enum DefPos {
    DefPosInsideClass,
    DefPosOutsideClass,
    DefPosImplementationFile
};

148
InsertionLocation insertLocationForMethodDefinition(Symbol *symbol, const bool useSymbolFinder,
149
150
151
152
153
154
155
                                                    CppRefactoringChanges& refactoring,
                                                    const QString& fileName)
{
    QTC_ASSERT(symbol, return InsertionLocation());

    // Try to find optimal location
    const InsertionPointLocator locator(refactoring);
156
157
    const QList<InsertionLocation> list
            = locator.methodDefinition(symbol, useSymbolFinder, fileName);
158
159
160
161
162
163
164
165
    for (int i = 0; i < list.count(); ++i) {
        InsertionLocation location = list.at(i);
        if (location.isValid() && location.fileName() == fileName) {
            return location;
            break;
        }
    }

166
167
    // ...failed,
    // if class member try to get position right after class
168
    CppRefactoringFilePtr file = refactoring.file(fileName);
169
170
171
172
173
174
175
176
177
178
179
180
181
    unsigned line = 0, column = 0;
    if (Class *clazz = symbol->enclosingClass()) {
        if (symbol->fileName() == fileName.toUtf8()) {
            file->cppDocument()->translationUnit()->getPosition(clazz->endOffset(), &line, &column);
            if (line != 0) {
                ++column; // Skipping the ";"
                return InsertionLocation(fileName, QLatin1String("\n\n"), QLatin1String(""),
                                         line, column);
            }
        }
    }

    // fall through: position at end of file
182
183
184
185
186
187
188
189
190
191
    const QTextDocument *doc = file->document();
    int pos = qMax(0, doc->characterCount() - 1);

    //TODO watch for matching namespace
    //TODO watch for moc-includes

    file->lineAndColumn(pos, &line, &column);
    return InsertionLocation(fileName, QLatin1String("\n\n"), QLatin1String("\n"), line, column);
}

192
inline bool isQtStringLiteral(const QByteArray &id)
193
194
195
196
{
    return id == "QLatin1String" || id == "QLatin1Literal" || id == "QStringLiteral";
}

197
inline bool isQtStringTranslation(const QByteArray &id)
198
199
200
201
{
    return id == "tr" || id == "trUtf8" || id == "translate" || id == "QT_TRANSLATE_NOOP";
}

202
203
204
205
206
Class *isMemberFunction(const LookupContext &context, Function *function)
{
    QTC_ASSERT(function, return 0);

    Scope *enclosingScope = function->enclosingScope();
207
    while (!(enclosingScope->isNamespace() || enclosingScope->isClass()))
208
209
210
211
        enclosingScope = enclosingScope->enclosingScope();
    QTC_ASSERT(enclosingScope != 0, return 0);

    const Name *functionName = function->name();
212
    if (!functionName)
213
214
        return 0; // anonymous function names are not valid c++

215
    if (!functionName->isQualifiedNameId())
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
        return 0; // trying to add a declaration for a global function

    const QualifiedNameId *q = functionName->asQualifiedNameId();
    if (!q->base())
        return 0;

    if (ClassOrNamespace *binding = context.lookupType(q->base(), enclosingScope)) {
        foreach (Symbol *s, binding->symbols()) {
            if (Class *matchingClass = s->asClass())
                return matchingClass;
        }
    }

    return 0;
}

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
Namespace *isNamespaceFunction(const LookupContext &context, Function *function)
{
    QTC_ASSERT(function, return 0);
    if (isMemberFunction(context, function))
        return 0;

    Scope *enclosingScope = function->enclosingScope();
    while (!(enclosingScope->isNamespace() || enclosingScope->isClass()))
        enclosingScope = enclosingScope->enclosingScope();
    QTC_ASSERT(enclosingScope != 0, return 0);

    const Name *functionName = function->name();
    if (!functionName)
        return 0; // anonymous function names are not valid c++

    // global namespace
    if (!functionName->isQualifiedNameId()) {
        foreach (Symbol *s, context.globalNamespace()->symbols()) {
            if (Namespace *matchingNamespace = s->asNamespace())
                return matchingNamespace;
        }
        return 0;
    }

    const QualifiedNameId *q = functionName->asQualifiedNameId();
    if (!q->base())
        return 0;

    if (ClassOrNamespace *binding = context.lookupType(q->base(), enclosingScope)) {
        foreach (Symbol *s, binding->symbols()) {
            if (Namespace *matchingNamespace = s->asNamespace())
                return matchingNamespace;
        }
    }

    return 0;
}

270
271
272
273
274
// Given include is e.g. "afile.h" or <afile.h> (quotes/angle brackets included!).
void insertNewIncludeDirective(const QString &include, CppRefactoringFilePtr file)
{
    // Find optimal position
    using namespace IncludeUtils;
275
    LineForNewIncludeDirective finder(file->document(), file->cppDocument()->resolvedIncludes(),
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
                                      LineForNewIncludeDirective::IgnoreMocIncludes,
                                      LineForNewIncludeDirective::AutoDetect);
    unsigned newLinesToPrepend = 0;
    unsigned newLinesToAppend = 0;
    const int insertLine = finder(include, &newLinesToPrepend, &newLinesToAppend);
    QTC_ASSERT(insertLine >= 1, return);
    const int insertPosition = file->position(insertLine, 1);
    QTC_ASSERT(insertPosition >= 0, return);

    // Construct text to insert
    const QString includeLine = QLatin1String("#include ") + include + QLatin1Char('\n');
    QString prependedNewLines, appendedNewLines;
    while (newLinesToAppend--)
        appendedNewLines += QLatin1String("\n");
    while (newLinesToPrepend--)
        prependedNewLines += QLatin1String("\n");
    const QString textToInsert = prependedNewLines + includeLine + appendedNewLines;

    // Insert
    ChangeSet changes;
    changes.insert(insertPosition, textToInsert);
    file->setChangeSet(changes);
    file->apply();
}

301
302
303
304
305
306
bool nameIncludesOperatorName(const Name *name)
{
    return name->isOperatorNameId()
        || (name->isQualifiedNameId() && name->asQualifiedNameId()->name()->isOperatorNameId());
}

307
308
309
310
} // anonymous namespace

namespace {

Nikolai Kosjar's avatar
Nikolai Kosjar committed
311
class InverseLogicalComparisonOp: public CppQuickFixOperation
312
313
{
public:
Nikolai Kosjar's avatar
Nikolai Kosjar committed
314
315
316
317
    InverseLogicalComparisonOp(const CppQuickFixInterface &interface, int priority,
                               BinaryExpressionAST *binary, Kind invertToken)
        : CppQuickFixOperation(interface, priority)
        , binary(binary), nested(0), negation(0)
318
    {
Nikolai Kosjar's avatar
Nikolai Kosjar committed
319
320
321
        Token tok;
        tok.f.kind = invertToken;
        replacement = QLatin1String(tok.spell());
322

Nikolai Kosjar's avatar
Nikolai Kosjar committed
323
324
325
        // check for enclosing nested expression
        if (priority - 1 >= 0)
            nested = interface->path()[priority - 1]->asNestedExpression();
326

Nikolai Kosjar's avatar
Nikolai Kosjar committed
327
328
329
        // check for ! before parentheses
        if (nested && priority - 2 >= 0) {
            negation = interface->path()[priority - 2]->asUnaryExpression();
330
331
            if (negation
                    && !interface->currentFile()->tokenAt(negation->unary_op_token).is(T_EXCLAIM)) {
Nikolai Kosjar's avatar
Nikolai Kosjar committed
332
                negation = 0;
333
            }
334
335
336
        }
    }

Nikolai Kosjar's avatar
Nikolai Kosjar committed
337
    QString description() const
338
    {
Nikolai Kosjar's avatar
Nikolai Kosjar committed
339
340
        return QApplication::translate("CppTools::QuickFix", "Rewrite Using %1").arg(replacement);
    }
341

Nikolai Kosjar's avatar
Nikolai Kosjar committed
342
343
344
345
346
347
348
349
350
351
352
353
354
355
    void perform()
    {
        CppRefactoringChanges refactoring(snapshot());
        CppRefactoringFilePtr currentFile = refactoring.file(fileName());

        ChangeSet changes;
        if (negation) {
            // can't remove parentheses since that might break precedence
            changes.remove(currentFile->range(negation->unary_op_token));
        } else if (nested) {
            changes.insert(currentFile->startOf(nested), QLatin1String("!"));
        } else {
            changes.insert(currentFile->startOf(binary), QLatin1String("!("));
            changes.insert(currentFile->endOf(binary), QLatin1String(")"));
356
        }
Nikolai Kosjar's avatar
Nikolai Kosjar committed
357
358
359
360
        changes.replace(currentFile->range(binary->binary_op_token), replacement);
        currentFile->setChangeSet(changes);
        currentFile->apply();
    }
361

Nikolai Kosjar's avatar
Nikolai Kosjar committed
362
363
364
365
private:
    BinaryExpressionAST *binary;
    NestedExpressionAST *nested;
    UnaryExpressionAST *negation;
366

Nikolai Kosjar's avatar
Nikolai Kosjar committed
367
    QString replacement;
368
369
};

370
371
} // anonymous namespace

Nikolai Kosjar's avatar
Nikolai Kosjar committed
372
373
374
375
376
377
378
379
void InverseLogicalComparison::match(const CppQuickFixInterface &interface,
                                     QuickFixOperations &result)
{
    CppRefactoringFilePtr file = interface->currentFile();

    const QList<AST *> &path = interface->path();
    int index = path.size() - 1;
    BinaryExpressionAST *binary = path.at(index)->asBinaryExpression();
380
    if (!binary)
Nikolai Kosjar's avatar
Nikolai Kosjar committed
381
        return;
382
    if (!interface->isCursorOn(binary->binary_op_token))
Nikolai Kosjar's avatar
Nikolai Kosjar committed
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
        return;

    Kind invertToken;
    switch (file->tokenAt(binary->binary_op_token).kind()) {
    case T_LESS_EQUAL:
        invertToken = T_GREATER;
        break;
    case T_LESS:
        invertToken = T_GREATER_EQUAL;
        break;
    case T_GREATER:
        invertToken = T_LESS_EQUAL;
        break;
    case T_GREATER_EQUAL:
        invertToken = T_LESS;
        break;
    case T_EQUAL_EQUAL:
        invertToken = T_EXCLAIM_EQUAL;
        break;
    case T_EXCLAIM_EQUAL:
        invertToken = T_EQUAL_EQUAL;
        break;
    default:
        return;
    }
408

Nikolai Kosjar's avatar
Nikolai Kosjar committed
409
410
411
    result.append(CppQuickFixOperation::Ptr(
        new InverseLogicalComparisonOp(interface, index, binary, invertToken)));
}
412

413
414
namespace {

Nikolai Kosjar's avatar
Nikolai Kosjar committed
415
class FlipLogicalOperandsOp: public CppQuickFixOperation
416
417
{
public:
Nikolai Kosjar's avatar
Nikolai Kosjar committed
418
419
420
421
422
    FlipLogicalOperandsOp(const CppQuickFixInterface &interface, int priority,
                          BinaryExpressionAST *binary, QString replacement)
        : CppQuickFixOperation(interface)
        , binary(binary)
        , replacement(replacement)
423
    {
Nikolai Kosjar's avatar
Nikolai Kosjar committed
424
425
        setPriority(priority);
    }
426

Nikolai Kosjar's avatar
Nikolai Kosjar committed
427
428
429
430
431
432
433
    QString description() const
    {
        if (replacement.isEmpty())
            return QApplication::translate("CppTools::QuickFix", "Swap Operands");
        else
            return QApplication::translate("CppTools::QuickFix", "Rewrite Using %1").arg(replacement);
    }
434

Nikolai Kosjar's avatar
Nikolai Kosjar committed
435
436
437
438
    void perform()
    {
        CppRefactoringChanges refactoring(snapshot());
        CppRefactoringFilePtr currentFile = refactoring.file(fileName());
439

Nikolai Kosjar's avatar
Nikolai Kosjar committed
440
        ChangeSet changes;
441
442
        changes.flip(currentFile->range(binary->left_expression),
                     currentFile->range(binary->right_expression));
443
        if (!replacement.isEmpty())
Nikolai Kosjar's avatar
Nikolai Kosjar committed
444
            changes.replace(currentFile->range(binary->binary_op_token), replacement);
445

Nikolai Kosjar's avatar
Nikolai Kosjar committed
446
447
        currentFile->setChangeSet(changes);
        currentFile->apply();
448
449
450
    }

private:
Nikolai Kosjar's avatar
Nikolai Kosjar committed
451
452
453
    BinaryExpressionAST *binary;
    QString replacement;
};
454

455
456
} // anonymous namespace

Nikolai Kosjar's avatar
Nikolai Kosjar committed
457
458
459
460
void FlipLogicalOperands::match(const CppQuickFixInterface &interface, QuickFixOperations &result)
{
    const QList<AST *> &path = interface->path();
    CppRefactoringFilePtr file = interface->currentFile();
461

Nikolai Kosjar's avatar
Nikolai Kosjar committed
462
463
    int index = path.size() - 1;
    BinaryExpressionAST *binary = path.at(index)->asBinaryExpression();
464
    if (!binary)
Nikolai Kosjar's avatar
Nikolai Kosjar committed
465
        return;
466
    if (!interface->isCursorOn(binary->binary_op_token))
Nikolai Kosjar's avatar
Nikolai Kosjar committed
467
        return;
468

Nikolai Kosjar's avatar
Nikolai Kosjar committed
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
    Kind flipToken;
    switch (file->tokenAt(binary->binary_op_token).kind()) {
    case T_LESS_EQUAL:
        flipToken = T_GREATER_EQUAL;
        break;
    case T_LESS:
        flipToken = T_GREATER;
        break;
    case T_GREATER:
        flipToken = T_LESS;
        break;
    case T_GREATER_EQUAL:
        flipToken = T_LESS_EQUAL;
        break;
    case T_EQUAL_EQUAL:
    case T_EXCLAIM_EQUAL:
    case T_AMPER_AMPER:
    case T_PIPE_PIPE:
        flipToken = T_EOF_SYMBOL;
        break;
    default:
        return;
    }
492

Nikolai Kosjar's avatar
Nikolai Kosjar committed
493
494
495
496
497
498
    QString replacement;
    if (flipToken != T_EOF_SYMBOL) {
        Token tok;
        tok.f.kind = flipToken;
        replacement = QLatin1String(tok.spell());
    }
499

Nikolai Kosjar's avatar
Nikolai Kosjar committed
500
501
502
    result.append(QuickFixOperation::Ptr(
        new FlipLogicalOperandsOp(interface, index, binary, replacement)));
}
503

504
505
namespace {

Nikolai Kosjar's avatar
Nikolai Kosjar committed
506
class RewriteLogicalAndOp: public CppQuickFixOperation
507
508
{
public:
Nikolai Kosjar's avatar
Nikolai Kosjar committed
509
510
511
512
513
514
515
516
    QSharedPointer<ASTPatternBuilder> mk;
    UnaryExpressionAST *left;
    UnaryExpressionAST *right;
    BinaryExpressionAST *pattern;

    RewriteLogicalAndOp(const CppQuickFixInterface &interface)
        : CppQuickFixOperation(interface)
        , mk(new ASTPatternBuilder)
517
    {
Nikolai Kosjar's avatar
Nikolai Kosjar committed
518
519
520
521
        left = mk->UnaryExpression();
        right = mk->UnaryExpression();
        pattern = mk->BinaryExpression(left, right);
    }
522

Nikolai Kosjar's avatar
Nikolai Kosjar committed
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
    void perform()
    {
        CppRefactoringChanges refactoring(snapshot());
        CppRefactoringFilePtr currentFile = refactoring.file(fileName());

        ChangeSet changes;
        changes.replace(currentFile->range(pattern->binary_op_token), QLatin1String("||"));
        changes.remove(currentFile->range(left->unary_op_token));
        changes.remove(currentFile->range(right->unary_op_token));
        const int start = currentFile->startOf(pattern);
        const int end = currentFile->endOf(pattern);
        changes.insert(start, QLatin1String("!("));
        changes.insert(end, QLatin1String(")"));

        currentFile->setChangeSet(changes);
        currentFile->appendIndentRange(currentFile->range(pattern));
        currentFile->apply();
    }
};
542

543
544
} // anonymous namespace

Nikolai Kosjar's avatar
Nikolai Kosjar committed
545
546
547
548
549
void RewriteLogicalAnd::match(const CppQuickFixInterface &interface, QuickFixOperations &result)
{
    BinaryExpressionAST *expression = 0;
    const QList<AST *> &path = interface->path();
    CppRefactoringFilePtr file = interface->currentFile();
550

Nikolai Kosjar's avatar
Nikolai Kosjar committed
551
552
553
554
555
    int index = path.size() - 1;
    for (; index != -1; --index) {
        expression = path.at(index)->asBinaryExpression();
        if (expression)
            break;
556
557
    }

558
    if (!expression)
Nikolai Kosjar's avatar
Nikolai Kosjar committed
559
        return;
560

561
    if (!interface->isCursorOn(expression->binary_op_token))
Nikolai Kosjar's avatar
Nikolai Kosjar committed
562
        return;
563

Nikolai Kosjar's avatar
Nikolai Kosjar committed
564
    QSharedPointer<RewriteLogicalAndOp> op(new RewriteLogicalAndOp(interface));
565

Nikolai Kosjar's avatar
Nikolai Kosjar committed
566
567
568
569
    if (expression->match(op->pattern, &matcher) &&
            file->tokenAt(op->pattern->binary_op_token).is(T_AMPER_AMPER) &&
            file->tokenAt(op->left->unary_op_token).is(T_EXCLAIM) &&
            file->tokenAt(op->right->unary_op_token).is(T_EXCLAIM)) {
570
571
        op->setDescription(QApplication::translate("CppTools::QuickFix",
                                                   "Rewrite Condition Using ||"));
Nikolai Kosjar's avatar
Nikolai Kosjar committed
572
573
574
575
        op->setPriority(index);
        result.append(op);
    }
}
576

Nikolai Kosjar's avatar
Nikolai Kosjar committed
577
578
bool SplitSimpleDeclaration::checkDeclaration(SimpleDeclarationAST *declaration)
{
579
    if (!declaration->semicolon_token)
Nikolai Kosjar's avatar
Nikolai Kosjar committed
580
        return false;
581

582
    if (!declaration->decl_specifier_list)
Nikolai Kosjar's avatar
Nikolai Kosjar committed
583
        return false;
584

Nikolai Kosjar's avatar
Nikolai Kosjar committed
585
586
    for (SpecifierListAST *it = declaration->decl_specifier_list; it; it = it->next) {
        SpecifierAST *specifier = it->value;
587

Nikolai Kosjar's avatar
Nikolai Kosjar committed
588
        if (specifier->asEnumSpecifier() != 0)
589
590
            return false;

Nikolai Kosjar's avatar
Nikolai Kosjar committed
591
        else if (specifier->asClassSpecifier() != 0)
592
            return false;
Nikolai Kosjar's avatar
Nikolai Kosjar committed
593
    }
594

595
    if (!declaration->declarator_list)
Nikolai Kosjar's avatar
Nikolai Kosjar committed
596
        return false;
597

598
    else if (!declaration->declarator_list->next)
Nikolai Kosjar's avatar
Nikolai Kosjar committed
599
        return false;
600

Nikolai Kosjar's avatar
Nikolai Kosjar committed
601
602
    return true;
}
603

604
605
namespace {

Nikolai Kosjar's avatar
Nikolai Kosjar committed
606
607
608
609
610
611
612
613
614
615
class SplitSimpleDeclarationOp: public CppQuickFixOperation
{
public:
    SplitSimpleDeclarationOp(const CppQuickFixInterface &interface, int priority,
                             SimpleDeclarationAST *decl)
        : CppQuickFixOperation(interface, priority)
        , declaration(decl)
    {
        setDescription(QApplication::translate("CppTools::QuickFix",
                                               "Split Declaration"));
616
617
    }

Nikolai Kosjar's avatar
Nikolai Kosjar committed
618
    void perform()
619
    {
Nikolai Kosjar's avatar
Nikolai Kosjar committed
620
621
        CppRefactoringChanges refactoring(snapshot());
        CppRefactoringFilePtr currentFile = refactoring.file(fileName());
622

Nikolai Kosjar's avatar
Nikolai Kosjar committed
623
        ChangeSet changes;
624

Nikolai Kosjar's avatar
Nikolai Kosjar committed
625
626
627
628
        SpecifierListAST *specifiers = declaration->decl_specifier_list;
        int declSpecifiersStart = currentFile->startOf(specifiers->firstToken());
        int declSpecifiersEnd = currentFile->endOf(specifiers->lastToken() - 1);
        int insertPos = currentFile->endOf(declaration->semicolon_token);
629

Nikolai Kosjar's avatar
Nikolai Kosjar committed
630
        DeclaratorAST *prevDeclarator = declaration->declarator_list->value;
631

Nikolai Kosjar's avatar
Nikolai Kosjar committed
632
633
        for (DeclaratorListAST *it = declaration->declarator_list->next; it; it = it->next) {
            DeclaratorAST *declarator = it->value;
634

Nikolai Kosjar's avatar
Nikolai Kosjar committed
635
636
637
638
639
            changes.insert(insertPos, QLatin1String("\n"));
            changes.copy(declSpecifiersStart, declSpecifiersEnd, insertPos);
            changes.insert(insertPos, QLatin1String(" "));
            changes.move(currentFile->range(declarator), insertPos);
            changes.insert(insertPos, QLatin1String(";"));
640

Nikolai Kosjar's avatar
Nikolai Kosjar committed
641
642
            const int prevDeclEnd = currentFile->endOf(prevDeclarator);
            changes.remove(prevDeclEnd, currentFile->startOf(declarator));
643

Nikolai Kosjar's avatar
Nikolai Kosjar committed
644
            prevDeclarator = declarator;
645
        }
Nikolai Kosjar's avatar
Nikolai Kosjar committed
646
647
648
649

        currentFile->setChangeSet(changes);
        currentFile->appendIndentRange(currentFile->range(declaration));
        currentFile->apply();
650
651
652
    }

private:
Nikolai Kosjar's avatar
Nikolai Kosjar committed
653
654
    SimpleDeclarationAST *declaration;
};
655

656
657
} // anonymous namespace

Nikolai Kosjar's avatar
Nikolai Kosjar committed
658
659
660
661
662
663
664
void SplitSimpleDeclaration::match(const CppQuickFixInterface &interface,
                                   QuickFixOperations &result)
{
    CoreDeclaratorAST *core_declarator = 0;
    const QList<AST *> &path = interface->path();
    CppRefactoringFilePtr file = interface->currentFile();
    const int cursorPosition = file->cursor().selectionStart();
665

Nikolai Kosjar's avatar
Nikolai Kosjar committed
666
667
    for (int index = path.size() - 1; index != -1; --index) {
        AST *node = path.at(index);
668

669
        if (CoreDeclaratorAST *coreDecl = node->asCoreDeclarator()) {
Nikolai Kosjar's avatar
Nikolai Kosjar committed
670
            core_declarator = coreDecl;
671
        } else if (SimpleDeclarationAST *simpleDecl = node->asSimpleDeclaration()) {
Nikolai Kosjar's avatar
Nikolai Kosjar committed
672
673
            if (checkDeclaration(simpleDecl)) {
                SimpleDeclarationAST *declaration = simpleDecl;
674

Nikolai Kosjar's avatar
Nikolai Kosjar committed
675
676
                const int startOfDeclSpecifier = file->startOf(declaration->decl_specifier_list->firstToken());
                const int endOfDeclSpecifier = file->endOf(declaration->decl_specifier_list->lastToken() - 1);
677

Nikolai Kosjar's avatar
Nikolai Kosjar committed
678
679
680
681
682
683
                if (cursorPosition >= startOfDeclSpecifier && cursorPosition <= endOfDeclSpecifier) {
                    // the AST node under cursor is a specifier.
                    result.append(QuickFixOperation::Ptr(
                        new SplitSimpleDeclarationOp(interface, index, declaration)));
                    return;
                }
684

Nikolai Kosjar's avatar
Nikolai Kosjar committed
685
686
687
688
689
690
                if (core_declarator && interface->isCursorOn(core_declarator)) {
                    // got a core-declarator under the text cursor.
                    result.append(QuickFixOperation::Ptr(
                        new SplitSimpleDeclarationOp(interface, index, declaration)));
                    return;
                }
691
692
            }

Nikolai Kosjar's avatar
Nikolai Kosjar committed
693
            return;
694
        }
Nikolai Kosjar's avatar
Nikolai Kosjar committed
695
696
    }
}
697

698
699
namespace {

Nikolai Kosjar's avatar
Nikolai Kosjar committed
700
701
702
703
704
705
706
class AddBracesToIfOp: public CppQuickFixOperation
{
public:
    AddBracesToIfOp(const CppQuickFixInterface &interface, int priority, StatementAST *statement)
        : CppQuickFixOperation(interface, priority)
        , _statement(statement)
    {
707
        setDescription(QApplication::translate("CppTools::QuickFix", "Add Curly Braces"));
Nikolai Kosjar's avatar
Nikolai Kosjar committed
708
709
710
711
712
713
714
715
    }

    void perform()
    {
        CppRefactoringChanges refactoring(snapshot());
        CppRefactoringFilePtr currentFile = refactoring.file(fileName());

        ChangeSet changes;
716

Nikolai Kosjar's avatar
Nikolai Kosjar committed
717
718
        const int start = currentFile->endOf(_statement->firstToken() - 1);
        changes.insert(start, QLatin1String(" {"));
719

Nikolai Kosjar's avatar
Nikolai Kosjar committed
720
721
        const int end = currentFile->endOf(_statement->lastToken() - 1);
        changes.insert(end, QLatin1String("\n}"));
722

Nikolai Kosjar's avatar
Nikolai Kosjar committed
723
        currentFile->setChangeSet(changes);
724
        currentFile->appendIndentRange(ChangeSet::Range(start, end));
Nikolai Kosjar's avatar
Nikolai Kosjar committed
725
726
727
728
729
730
731
        currentFile->apply();
    }

private:
    StatementAST *_statement;
};

732
733
} // anonymous namespace

Nikolai Kosjar's avatar
Nikolai Kosjar committed
734
void AddBracesToIf::match(const CppQuickFixInterface &interface, QuickFixOperations &result)
735
{
Nikolai Kosjar's avatar
Nikolai Kosjar committed
736
    const QList<AST *> &path = interface->path();
737

Nikolai Kosjar's avatar
Nikolai Kosjar committed
738
739
740
741
    // show when we're on the 'if' of an if statement
    int index = path.size() - 1;
    IfStatementAST *ifStatement = path.at(index)->asIfStatement();
    if (ifStatement && interface->isCursorOn(ifStatement->if_token) && ifStatement->statement
742
        && !ifStatement->statement->asCompoundStatement()) {
Nikolai Kosjar's avatar
Nikolai Kosjar committed
743
744
745
746
747
748
749
750
        result.append(QuickFixOperation::Ptr(
            new AddBracesToIfOp(interface, index, ifStatement->statement)));
        return;
    }

    // or if we're on the statement contained in the if
    // ### This may not be such a good idea, consider nested ifs...
    for (; index != -1; --index) {
751
        IfStatementAST *ifStatement = path.at(index)->asIfStatement();
Nikolai Kosjar's avatar
Nikolai Kosjar committed
752
753
        if (ifStatement && ifStatement->statement
            && interface->isCursorOn(ifStatement->statement)
754
            && !ifStatement->statement->asCompoundStatement()) {
Nikolai Kosjar's avatar
Nikolai Kosjar committed
755
756
            result.append(QuickFixOperation::Ptr(
                new AddBracesToIfOp(interface, index, ifStatement->statement)));
757
            return;
758
        }
Nikolai Kosjar's avatar
Nikolai Kosjar committed
759
    }
760

Nikolai Kosjar's avatar
Nikolai Kosjar committed
761
762
763
    // ### This could very well be extended to the else branch
    // and other nodes entirely.
}
764

765
766
namespace {

Nikolai Kosjar's avatar
Nikolai Kosjar committed
767
768
769
770
771
772
773
774
775
776
777
class MoveDeclarationOutOfIfOp: public CppQuickFixOperation
{
public:
    MoveDeclarationOutOfIfOp(const CppQuickFixInterface &interface)
        : CppQuickFixOperation(interface)
    {
        setDescription(QApplication::translate("CppTools::QuickFix",
                                               "Move Declaration out of Condition"));

        condition = mk.Condition();
        pattern = mk.IfStatement(condition);
778
779
    }

Nikolai Kosjar's avatar
Nikolai Kosjar committed
780
    void perform()
781
    {
Nikolai Kosjar's avatar
Nikolai Kosjar committed
782
783
        CppRefactoringChanges refactoring(snapshot());
        CppRefactoringFilePtr currentFile = refactoring.file(fileName());
784

Nikolai Kosjar's avatar
Nikolai Kosjar committed
785
        ChangeSet changes;
786

Nikolai Kosjar's avatar
Nikolai Kosjar committed
787
        changes.copy(currentFile->range(core), currentFile->startOf(condition));
788

Nikolai Kosjar's avatar
Nikolai Kosjar committed
789
790
791
        int insertPos = currentFile->startOf(pattern);
        changes.move(currentFile->range(condition), insertPos);
        changes.insert(insertPos, QLatin1String(";\n"));
792

Nikolai Kosjar's avatar
Nikolai Kosjar committed
793
794
795
796
        currentFile->setChangeSet(changes);
        currentFile->appendIndentRange(currentFile->range(pattern));
        currentFile->apply();
    }
797

Nikolai Kosjar's avatar
Nikolai Kosjar committed
798
799
800
801
802
    ASTMatcher matcher;
    ASTPatternBuilder mk;
    ConditionAST *condition;
    IfStatementAST *pattern;
    CoreDeclaratorAST *core;
803
804
};

805
806
} // anonymous namespace

Nikolai Kosjar's avatar
Nikolai Kosjar committed
807
808
void MoveDeclarationOutOfIf::match(const CppQuickFixInterface &interface,
                                   QuickFixOperations &result)
809
{
Nikolai Kosjar's avatar
Nikolai Kosjar committed
810
811
812
813
814
815
816
817
818
819
    const QList<AST *> &path = interface->path();
    typedef QSharedPointer<MoveDeclarationOutOfIfOp> Ptr;
    Ptr op(new MoveDeclarationOutOfIfOp(interface));

    int index = path.size() - 1;
    for (; index != -1; --index) {
        if (IfStatementAST *statement = path.at(index)->asIfStatement()) {
            if (statement->match(op->pattern, &op->matcher) && op->condition->declarator) {
                DeclaratorAST *declarator = op->condition->declarator;
                op->core = declarator->core_declarator;
820
                if (!op->core)
Nikolai Kosjar's avatar
Nikolai Kosjar committed
821
                    return;
822

Nikolai Kosjar's avatar
Nikolai Kosjar committed
823
824
825
826
                if (interface->isCursorOn(op->core)) {
                    op->setPriority(index);
                    result.append(op);
                    return;
827
828
829
830
                }
            }
        }
    }
Nikolai Kosjar's avatar
Nikolai Kosjar committed
831
}
832

833
834
namespace {

Nikolai Kosjar's avatar
Nikolai Kosjar committed
835
836
837
838
839
class MoveDeclarationOutOfWhileOp: public CppQuickFixOperation
{
public:
    MoveDeclarationOutOfWhileOp(const CppQuickFixInterface &interface)
        : CppQuickFixOperation(interface)
840
    {
Nikolai Kosjar's avatar
Nikolai Kosjar committed
841
842
        setDescription(QApplication::translate("CppTools::QuickFix",
                                               "Move Declaration out of Condition"));
843

Nikolai Kosjar's avatar
Nikolai Kosjar committed
844
845
846
        condition = mk.Condition();
        pattern = mk.WhileStatement(condition);
    }
847

Nikolai Kosjar's avatar
Nikolai Kosjar committed
848
849
850
851
    void perform()
    {
        CppRefactoringChanges refactoring(snapshot());
        CppRefactoringFilePtr currentFile = refactoring.file(fileName());
852

Nikolai Kosjar's avatar
Nikolai Kosjar committed
853
        ChangeSet changes;
854

Nikolai Kosjar's avatar
Nikolai Kosjar committed
855
856
        changes.insert(currentFile->startOf(condition), QLatin1String("("));
        changes.insert(currentFile->endOf(condition), QLatin1String(") != 0"));
857

Nikolai Kosjar's avatar
Nikolai Kosjar committed
858
859
860
861
862
        int insertPos = currentFile->startOf(pattern);
        const int conditionStart = currentFile->startOf(condition);
        changes.move(conditionStart, currentFile->startOf(core), insertPos);
        changes.copy(currentFile->range(core), insertPos);
        changes.insert(insertPos, QLatin1String(";\n"));
863

Nikolai Kosjar's avatar
Nikolai Kosjar committed
864
865
866
867
        currentFile->setChangeSet(changes);
        currentFile->appendIndentRange(currentFile->range(pattern));
        currentFile->apply();
    }
868

Nikolai Kosjar's avatar
Nikolai Kosjar committed
869
870
871
872
873
874
    ASTMatcher matcher;
    ASTPatternBuilder mk;
    ConditionAST *condition;
    WhileStatementAST *pattern;
    CoreDeclaratorAST *core;
};
875

876
877
} // anonymous namespace

Nikolai Kosjar's avatar
Nikolai Kosjar committed
878
879
void MoveDeclarationOutOfWhile::match(const CppQuickFixInterface &interface,
                                      QuickFixOperations &result)
880
{
Nikolai Kosjar's avatar
Nikolai Kosjar committed
881
882
    const QList<AST *> &path = interface->path();
    QSharedPointer<MoveDeclarationOutOfWhileOp> op(new MoveDeclarationOutOfWhileOp(interface));
883

Nikolai Kosjar's avatar
Nikolai Kosjar committed
884
885
886
887
888
889
    int index = path.size() - 1;
    for (; index != -1; --index) {
        if (WhileStatementAST *statement = path.at(index)->asWhileStatement()) {
            if (statement->match(op->pattern, &op->matcher) && op->condition->declarator) {
                DeclaratorAST *declarator = op->condition->declarator;
                op->core = declarator->core_declarator;
890

891
                if (!op->core)
Nikolai Kosjar's avatar
Nikolai Kosjar committed
892
                    return;
893

894
                if (!declarator->equal_token)
Nikolai Kosjar's avatar
Nikolai Kosjar committed
895
                    return;
896

897
                if (!declarator->initializer)
Nikolai Kosjar's avatar
Nikolai Kosjar committed
898
                    return;
899

Nikolai Kosjar's avatar
Nikolai Kosjar committed
900
901
902
903
                if (interface->isCursorOn(op->core)) {
                    op->setPriority(index);
                    result.append(op);
                    return;
904
905
906
907
                }
            }
        }
    }
Nikolai Kosjar's avatar
Nikolai Kosjar committed
908
}
909

910
911
namespace {

Nikolai Kosjar's avatar
Nikolai Kosjar committed
912
913
914
915
916
917
918
919
class SplitIfStatementOp: public CppQuickFixOperation
{
public:
    SplitIfStatementOp(const CppQuickFixInterface &interface, int priority,
                       IfStatementAST *pattern, BinaryExpressionAST *condition)
        : CppQuickFixOperation(interface, priority)
        , pattern(pattern)
        , condition(condition)
920
    {
Nikolai Kosjar's avatar
Nikolai Kosjar committed
921
922
923
924
925
926
927
928
        setDescription(QApplication::translate("CppTools::QuickFix",
                                               "Split if Statement"));
    }

    void perform()
    {
        CppRefactoringChanges refactoring(snapshot());
        CppRefactoringFilePtr currentFile = refactoring.file(fileName());
929

Nikolai Kosjar's avatar
Nikolai Kosjar committed
930
        const Token binaryToken = currentFile->tokenAt(condition->binary_op_token);
931

Nikolai Kosjar's avatar
Nikolai Kosjar committed
932
933
934
935
936
        if (binaryToken.is(T_AMPER_AMPER))
            splitAndCondition(currentFile);
        else
            splitOrCondition(currentFile);
    }
937

Nikolai Kosjar's avatar
Nikolai Kosjar committed
938
939
940
    void splitAndCondition(CppRefactoringFilePtr currentFile) const
    {
        ChangeSet changes;
941

Nikolai Kosjar's avatar
Nikolai Kosjar committed
942
943
944
945
        int startPos = currentFile->startOf(pattern);
        changes.insert(startPos, QLatin1String("if ("));
        changes.move(currentFile->range(condition->left_expression), startPos);
        changes.insert(startPos, QLatin1String(") {\n"));
946

Nikolai Kosjar's avatar
Nikolai Kosjar committed
947
948
949
        const int lExprEnd = currentFile->endOf(condition->left_expression);
        changes.remove(lExprEnd, currentFile->startOf(condition->right_expression));
        changes.insert(currentFile->endOf(pattern), QLatin1String("\n}"));
950

Nikolai Kosjar's avatar
Nikolai Kosjar committed
951
952
953
954
        currentFile->setChangeSet(changes);
        currentFile->appendIndentRange(currentFile->range(pattern));
        currentFile->apply();
    }
955

Nikolai Kosjar's avatar
Nikolai Kosjar committed
956
    void splitOrCondition(CppRefactoringFilePtr currentFile) const
957
    {
Nikolai Kosjar's avatar
Nikolai Kosjar committed
958
        ChangeSet changes;
959

Nikolai Kosjar's avatar
Nikolai Kosjar committed
960
961
        StatementAST *ifTrueStatement = pattern->statement;
        CompoundStatementAST *compoundStatement = ifTrueStatement->asCompoundStatement();
962

Nikolai Kosjar's avatar
Nikolai Kosjar committed
963
964
965
966
967
968
        int insertPos = currentFile->endOf(ifTrueStatement);
        if (compoundStatement)
            changes.insert(insertPos, QLatin1String(" "));
        else
            changes.insert(insertPos, QLatin1String("\n"));
        changes.insert(insertPos, QLatin1String("else if ("));
969

Nikolai Kosjar's avatar
Nikolai Kosjar committed
970
971
972
        const int rExprStart = currentFile->startOf(condition->right_expression);
        changes.move(rExprStart, currentFile->startOf(pattern->rparen_token), insertPos);
        changes.insert(insertPos, QLatin1String(")"));
973

Nikolai Kosjar's avatar
Nikolai Kosjar committed
974
975
        const int rParenEnd = currentFile->endOf(pattern->rparen_token);
        changes.copy(rParenEnd, currentFile->endOf(pattern->statement), insertPos);
976

Nikolai Kosjar's avatar
Nikolai Kosjar committed
977
978
979
980
981
982
        const int lExprEnd = currentFile->endOf(condition->left_expression);
        changes.remove(lExprEnd, currentFile->startOf(condition->right_expression));

        currentFile->setChangeSet(changes);
        currentFile->appendIndentRange(currentFile->range(pattern));
        currentFile->apply();
983
984
985
    }

private:
Nikolai Kosjar's avatar
Nikolai Kosjar committed
986
987
988
    IfStatementAST *pattern;
    BinaryExpressionAST *condition;
};
989

990
991
} // anonymous namespace

Nikolai Kosjar's avatar
Nikolai Kosjar committed
992
993
994
995
void SplitIfStatement::match(const CppQuickFixInterface &interface, QuickFixOperations &result)
{
    IfStatementAST *pattern = 0;
    const QList<AST *> &path = interface->path();
996

Nikolai Kosjar's avatar
Nikolai Kosjar committed
997
998
999
1000
1001
1002
    int index = path.size() - 1;
    for (; index != -1; --index) {
        AST *node = path.at(index);
        if (IfStatementAST *stmt = node->asIfStatement()) {
            pattern = stmt;
            break;
1003
        }
Nikolai Kosjar's avatar
Nikolai Kosjar committed
1004
    }
1005

1006
    if (!pattern || !pattern->statement)
Nikolai Kosjar's avatar
Nikolai Kosjar committed
1007
        return;
1008

Nikolai Kosjar's avatar
Nikolai Kosjar committed
1009
1010
1011
1012
    unsigned splitKind = 0;
    for (++index; index < path.size(); ++index) {
        AST *node = path.at(index);
        BinaryExpressionAST *condition = node->asBinaryExpression();
1013
        if (!condition)
Nikolai Kosjar's avatar
Nikolai Kosjar committed
1014
            return;
1015

Nikolai Kosjar's avatar
Nikolai Kosjar committed
1016
        Token binaryToken = interface->currentFile()->tokenAt(condition->binary_op_token);
1017

Nikolai Kosjar's avatar
Nikolai Kosjar committed
1018
        // only accept a chain of ||s or &&s - no mixing
1019
        if (!splitKind) {
Nikolai Kosjar's avatar
Nikolai Kosjar committed
1020
1021
1022
1023
1024
1025
1026
1027
            splitKind = binaryToken.kind();
            if (splitKind != T_AMPER_AMPER && splitKind != T_PIPE_PIPE)
                return;
            // we can't reliably split &&s in ifs with an else branch
            if (splitKind == T_AMPER_AMPER && pattern->else_statement)
                return;
        } else if (splitKind != binaryToken.kind()) {
            return;
1028
1029
        }

Nikolai Kosjar's avatar
Nikolai Kosjar committed
1030
1031
1032
1033
        if (interface->isCursorOn(condition->binary_op_token)) {
            result.append(QuickFixOperation::Ptr(
                new SplitIfStatementOp(interface, index, pattern, condition)));
            return;
1034
        }
Nikolai Kosjar's avatar
Nikolai Kosjar committed
1035
1036
    }
}
1037

1038
1039
1040
1041
/* Analze a string/character literal like "x", QLatin1String("x") and return the literal
 * (StringLiteral or NumericLiteral for characters) and its type
 * and the enclosing function (QLatin1String, tr...) */
ExpressionAST *WrapStringLiteral::analyze(const QList<AST *> &path,
1042
                                          const CppRefactoringFilePtr &file, Type *type,
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
                                          QByteArray *enclosingFunction /* = 0 */,
                                          CallAST **enclosingFunctionCall /* = 0 */)
{
    *type = TypeNone;
    if (enclosingFunction)
        enclosingFunction->clear();
    if (enclosingFunctionCall)
        *enclosingFunctionCall = 0;

    if (path.isEmpty())
        return 0;

    ExpressionAST *literal = path.last()->asExpression();
    if (literal) {
        if (literal->asStringLiteral()) {
            // Check for Objective C string (@"bla")
            const QChar firstChar = file->charAt(file->startOf(literal));
            *type = firstChar == QLatin1Char('@') ? TypeObjCString : TypeString;
        } else if (NumericLiteralAST *numericLiteral = literal->asNumericLiteral()) {
            // character ('c') constants are numeric.
            if (file->tokenAt(numericLiteral->literal_token).is(T_CHAR_LITERAL))
                *type = TypeChar;
1065
        }
1066
    }
1067

1068
1069
1070
1071
1072
1073
1074
1075
    if (*type != TypeNone && enclosingFunction && path.size() > 1) {
        if (CallAST *call = path.at(path.size() - 2)->asCall()) {
            if (call->base_expression) {
                if (IdExpressionAST *idExpr = call->base_expression->asIdExpression()) {
                    if (SimpleNameAST *functionName = idExpr->name->asSimpleName()) {
                        *enclosingFunction = file->tokenAt(functionName->identifier_token).identifier->chars();
                        if (enclosingFunctionCall)
                            *enclosingFunctionCall = call;
1076
1077
1078
1079
                    }
                }
            }
        }