cppelementevaluator.cpp 15.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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
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
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** 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
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "cppelementevaluator.h"

#include <coreplugin/ifile.h>
#include <cpptools/cppmodelmanagerinterface.h>

#include <FullySpecifiedType.h>
#include <Names.h>
#include <CoreTypes.h>
#include <Scope.h>
#include <Symbol.h>
#include <Symbols.h>
#include <cplusplus/ExpressionUnderCursor.h>
#include <cplusplus/Overview.h>
#include <cplusplus/TypeOfExpression.h>
#include <cplusplus/LookupContext.h>
#include <cplusplus/LookupItem.h>
#include <cplusplus/Icons.h>

#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtCore/QSet>
#include <QtCore/QQueue>

using namespace CppEditor;
using namespace Internal;
using namespace CPlusPlus;

namespace {
    void moveCursorToEndOfName(QTextCursor *tc) {
        QTextDocument *doc = tc->document();
        if (!doc)
            return;

        QChar ch = doc->characterAt(tc->position());
        while (ch.isLetterOrNumber() || ch == QLatin1Char('_')) {
            tc->movePosition(QTextCursor::NextCharacter);
            ch = doc->characterAt(tc->position());
        }
    }
}

CppElementEvaluator::CppElementEvaluator(CPPEditor *editor) :
    m_editor(editor),
    m_modelManager(CppTools::CppModelManagerInterface::instance()),
    m_tc(editor->textCursor()),
    m_lookupBaseClasses(false)
{}

void CppElementEvaluator::setTextCursor(const QTextCursor &tc)
{ m_tc = tc; }

void CppElementEvaluator::setLookupBaseClasses(const bool lookup)
{ m_lookupBaseClasses = lookup; }

QSharedPointer<CppElement> CppElementEvaluator::identifyCppElement()
{
    m_element.clear();
    evaluate();
    return m_element;
}

// @todo: Consider refactoring code from CPPEditor::findLinkAt into here.
void CppElementEvaluator::evaluate()
{
    if (!m_modelManager)
        return;

    const Snapshot &snapshot = m_modelManager->snapshot();
    Document::Ptr doc = snapshot.document(m_editor->file()->fileName());
    if (!doc)
        return;

    int line = 0;
    int column = 0;
    const int pos = m_tc.position();
    m_editor->convertPosition(pos, &line, &column);

    if (!matchDiagnosticMessage(doc, line)) {
        if (!matchIncludeFile(doc, line) && !matchMacroInUse(doc, pos)) {
            moveCursorToEndOfName(&m_tc);

            // Fetch the expression's code
            ExpressionUnderCursor expressionUnderCursor;
            const QString &expression = expressionUnderCursor(m_tc);
            Scope *scope = doc->scopeAt(line, column);

            TypeOfExpression typeOfExpression;
            typeOfExpression.init(doc, snapshot);
            const QList<LookupItem> &lookupItems = typeOfExpression(expression, scope);
            if (lookupItems.isEmpty())
                return;

            const LookupItem &lookupItem = lookupItems.first(); // ### TODO: select best candidate.
            handleLookupItemMatch(snapshot, lookupItem, typeOfExpression.context());
        }
    }
}

bool CppElementEvaluator::matchDiagnosticMessage(const CPlusPlus::Document::Ptr &document,
                                                 unsigned line)
{
    foreach (const Document::DiagnosticMessage &m, document->diagnosticMessages()) {
        if (m.line() == line) {
            m_element = QSharedPointer<CppElement>(new CppDiagnosis(m));
            return true;
        }
    }
    return false;
}

bool CppElementEvaluator::matchIncludeFile(const CPlusPlus::Document::Ptr &document, unsigned line)
{
    foreach (const Document::Include &includeFile, document->includes()) {
        if (includeFile.line() == line) {
            m_element = QSharedPointer<CppElement>(new CppInclude(includeFile));
            return true;
        }
    }
    return false;
}

bool CppElementEvaluator::matchMacroInUse(const CPlusPlus::Document::Ptr &document, unsigned pos)
{
    foreach (const Document::MacroUse &use, document->macroUses()) {
        if (use.contains(pos)) {
            const unsigned begin = use.begin();
            const QString &name = use.macro().name();
            if (pos < begin + name.length()) {
                m_element = QSharedPointer<CppElement>(new CppMacro(use.macro()));
                return true;
            }
        }
    }
    return false;
}

void CppElementEvaluator::handleLookupItemMatch(const Snapshot &snapshot,
                                                const LookupItem &lookupItem,
                                                const LookupContext &context)
{
    Symbol *declaration = lookupItem.declaration();
    if (!declaration) {
        const QString &type = Overview().prettyType(lookupItem.type(), QString());
        m_element = QSharedPointer<CppElement>(new Unknown(type));
    } else {
        const FullySpecifiedType &type = declaration->type();
        if (declaration->isNamespace()) {
            m_element = QSharedPointer<CppElement>(new CppNamespace(declaration));
        } else if (declaration->isClass() || declaration->isForwardClassDeclaration()) {
            if (declaration->isForwardClassDeclaration())
                if (Symbol *classDeclaration = snapshot.findMatchingClassDeclaration(declaration))
                    declaration = classDeclaration;
            CppClass *cppClass = new CppClass(declaration);
            if (m_lookupBaseClasses)
                cppClass->lookupBases(declaration, context);
            m_element = QSharedPointer<CppElement>(cppClass);
186
        } else if (declaration->isEnum() || declaration->enclosingScope()->isEnum()) {
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
            m_element = QSharedPointer<CppElement>(new CppEnum(declaration));
        } else if (declaration->isTypedef()) {
            m_element = QSharedPointer<CppElement>(new CppTypedef(declaration));
        } else if (declaration->isFunction() || (type.isValid() && type->isFunctionType())) {
            m_element = QSharedPointer<CppElement>(new CppFunction(declaration));
        } else if (declaration->isDeclaration() && type.isValid()) {
            m_element = QSharedPointer<CppElement>(
                new CppVariable(declaration, context, lookupItem.scope()));
        } else {
            m_element = QSharedPointer<CppElement>(new CppDeclarableElement(declaration));
        }
    }
}

// CppElement
202
CppElement::CppElement() : m_helpCategory(TextEditor::HelpItem::Unknown)
203
204
205
206
207
{}

CppElement::~CppElement()
{}

208
void CppElement::setHelpCategory(const TextEditor::HelpItem::Category &cat)
209
210
{ m_helpCategory = cat; }

211
const TextEditor::HelpItem::Category &CppElement::helpCategory() const
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
{ return m_helpCategory; }

void CppElement::setHelpIdCandidates(const QStringList &candidates)
{ m_helpIdCandidates = candidates; }

void CppElement::addHelpIdCandidate(const QString &candidate)
{ m_helpIdCandidates.append(candidate); }

const QStringList &CppElement::helpIdCandidates() const
{ return m_helpIdCandidates; }

void CppElement::setHelpMark(const QString &mark)
{ m_helpMark = mark; }

const QString &CppElement::helpMark() const
{ return m_helpMark; }

void CppElement::setLink(const CPPEditor::Link &link)
{ m_link = link; }

const CPPEditor::Link &CppElement::link() const
{ return m_link; }

void CppElement::setTooltip(const QString &tooltip)
{ m_tooltip = tooltip; }

const QString &CppElement::tooltip() const
{ return m_tooltip; }


// Unknown
Unknown::Unknown(const QString &type) : CppElement(), m_type(type)
{
    setTooltip(m_type);
}

Unknown::~Unknown()
{}

const QString &Unknown::type() const
{ return m_type; }

// CppDiagnosis
CppDiagnosis::CppDiagnosis(const Document::DiagnosticMessage &message) :
    CppElement(), m_text(message.text())
{
    setTooltip(m_text);
}

CppDiagnosis::~CppDiagnosis()
{}

const QString &CppDiagnosis::text() const
{ return m_text; }

// CppInclude
CppInclude::~CppInclude()
{}

CppInclude::CppInclude(const Document::Include &includeFile) :
    CppElement(),
    m_path(QDir::toNativeSeparators(includeFile.fileName())),
    m_fileName(QFileInfo(includeFile.fileName()).fileName())
{
276
    setHelpCategory(TextEditor::HelpItem::Brief);
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
    setHelpIdCandidates(QStringList(m_fileName));
    setHelpMark(m_fileName);
    setLink(CPPEditor::Link(m_path));
    setTooltip(m_path);
}

const QString &CppInclude::path() const
{ return m_path; }

const QString &CppInclude::fileName() const
{ return m_fileName; }

// CppMacro
CppMacro::CppMacro(const Macro &macro) : CppElement()
{
292
    setHelpCategory(TextEditor::HelpItem::Macro);
293
294
295
296
297
298
299
300
301
302
303
304
    setHelpIdCandidates(QStringList(macro.name()));
    setHelpMark(macro.name());
    setLink(CPPEditor::Link(macro.fileName(), macro.line()));
    setTooltip(macro.toString());
}

CppMacro::~CppMacro()
{}

// CppDeclarableElement
CppDeclarableElement::CppDeclarableElement(Symbol *declaration) : CppElement()
{
305
    m_icon = Icons().iconForSymbol(declaration);
306
307
308
309
310

    Overview overview;
    overview.setShowArgumentNames(true);
    overview.setShowReturnTypes(true);
    m_name = overview.prettyName(declaration->name());
311
312
313
    if (declaration->enclosingScope()->isClass() ||
        declaration->enclosingScope()->isNamespace() ||
        declaration->enclosingScope()->isEnum()) {
314
315
316
317
318
        m_qualifiedName = overview.prettyName(LookupContext::fullyQualifiedName(declaration));
    } else {
        m_qualifiedName = m_name;
    }

319
    setTooltip(overview.prettyType(declaration->type(), m_qualifiedName));
320
321
322
    setLink(CPPEditor::linkToSymbol(declaration));

    QStringList helpIds;
323
    helpIds << m_qualifiedName << m_name;
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
    setHelpIdCandidates(helpIds);
    setHelpMark(m_name);
}

CppDeclarableElement::~CppDeclarableElement()
{}

void CppDeclarableElement::setName(const QString &name)
{ m_name = name; }

const QString &CppDeclarableElement::name() const
{ return m_name; }

void CppDeclarableElement::setQualifiedName(const QString &name)
{ m_qualifiedName = name; }

const QString &CppDeclarableElement::qualifiedName() const
{ return m_qualifiedName; }

void CppDeclarableElement::setType(const QString &type)
{ m_type = type; }

const QString &CppDeclarableElement::type() const
{ return m_type; }

void CppDeclarableElement::setIcon(const QIcon &icon)
{ m_icon = icon; }

const QIcon &CppDeclarableElement::icon() const
{ return m_icon; }

// CppNamespace
CppNamespace::CppNamespace(Symbol *declaration) : CppDeclarableElement(declaration)
{
358
    setHelpCategory(TextEditor::HelpItem::ClassOrNamespace);
359
    setTooltip(qualifiedName());
360
361
362
363
364
365
366
367
}

CppNamespace::~CppNamespace()
{}

// CppClass
CppClass::CppClass(Symbol *declaration) : CppDeclarableElement(declaration)
{
368
    setHelpCategory(TextEditor::HelpItem::ClassOrNamespace);
369
    setTooltip(qualifiedName());
370
371
372
373
374
375
376
377
378
379
380
381
382
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
408
409
410
411
}

CppClass::~CppClass()
{}

void CppClass::lookupBases(Symbol *declaration, const CPlusPlus::LookupContext &context)
{
    typedef QPair<ClassOrNamespace *, CppClass *> Data;

    if (ClassOrNamespace *clazz = context.lookupType(declaration)) {
        QSet<ClassOrNamespace *> visited;

        QQueue<Data> q;
        q.enqueue(qMakePair(clazz, this));
        while (!q.isEmpty()) {
            Data current = q.dequeue();
            clazz = current.first;
            visited.insert(clazz);
            const QList<ClassOrNamespace *> &bases = clazz->usings();
            foreach (ClassOrNamespace *baseClass, bases) {
                const QList<Symbol *> &symbols = baseClass->symbols();
                foreach (Symbol *symbol, symbols) {
                    if (symbol->isClass() && (
                        clazz = context.lookupType(symbol)) &&
                        !visited.contains(clazz)) {
                        CppClass baseCppClass(symbol);
                        CppClass *cppClass = current.second;
                        cppClass->m_bases.append(baseCppClass);
                        q.enqueue(qMakePair(clazz, &cppClass->m_bases.last()));
                    }
                }
            }
        }
    }
}

const QList<CppClass> &CppClass::bases() const
{ return m_bases; }

// CppFunction
CppFunction::CppFunction(Symbol *declaration) : CppDeclarableElement(declaration)
{
412
    setHelpCategory(TextEditor::HelpItem::Function);
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431

    const FullySpecifiedType &type = declaration->type();

    // Functions marks can be found either by the main overload or signature based
    // (with no argument names and no return). Help ids have no signature at all.
    Overview overview;
    overview.setShowDefaultArguments(false);
    setHelpMark(overview.prettyType(type, name()));

    overview.setShowFunctionSignatures(false);
    addHelpIdCandidate(overview.prettyName(declaration->name()));
}

CppFunction::~CppFunction()
{}

// CppEnum
CppEnum::CppEnum(Symbol *declaration) : CppDeclarableElement(declaration)
{
432
    setHelpCategory(TextEditor::HelpItem::Enum);
433

434
435
    if (declaration->enclosingScope()->isEnum()) {
        Symbol *enumSymbol = declaration->enclosingScope()->asEnum();
436
437
438
        Overview overview;
        setHelpMark(overview.prettyName(enumSymbol->name()));
        setTooltip(overview.prettyName(LookupContext::fullyQualifiedName(enumSymbol)));
439
440
    } else {
        setTooltip(qualifiedName());
441
442
443
444
445
446
447
    }
}

CppEnum::~CppEnum()
{}

// CppTypedef
448
CppTypedef::CppTypedef(Symbol *declaration) : CppDeclarableElement(declaration)
449
{
450
    setHelpCategory(TextEditor::HelpItem::Typedef);
451
    setTooltip(Overview().prettyType(declaration->type(), qualifiedName()));
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
}

CppTypedef::~CppTypedef()
{}

// CppVariable
CppVariable::CppVariable(Symbol *declaration, const LookupContext &context, Scope *scope) :
    CppDeclarableElement(declaration)
{
    const FullySpecifiedType &type = declaration->type();

    const Name *typeName = 0;
    if (type->isNamedType()) {
        typeName = type->asNamedType()->name();
    } else if (type->isPointerType() || type->isReferenceType()) {
        FullySpecifiedType associatedType;
        if (type->isPointerType())
            associatedType = type->asPointerType()->elementType();
        else
            associatedType = type->asReferenceType()->elementType();
        if (associatedType->isNamedType())
            typeName = associatedType->asNamedType()->name();
    }

    if (typeName) {
        if (ClassOrNamespace *clazz = context.lookupType(typeName, scope)) {
            if (!clazz->symbols().isEmpty()) {
                Overview overview;
                Symbol *symbol = clazz->symbols().at(0);
                const QString &name =
                    overview.prettyName(LookupContext::fullyQualifiedName(symbol));
                setTooltip(name);
484
                setHelpCategory(TextEditor::HelpItem::ClassOrNamespace);
485
486
487
488
489
490
491
492
493
                setHelpMark(name);
                setHelpIdCandidates(QStringList(name));
            }
        }
    }
}

CppVariable::~CppVariable()
{}