symbolfinder.cpp 10.8 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 186 187 188 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 329 330 331 332 333 334 335 336 337 338
#if defined(_MSC_VER)
#pragma warning(disable:4996)
#endif

#include "symbolfinder.h"

#include <Symbols.h>
#include <Names.h>
#include <Literals.h>
#include <SymbolVisitor.h>
#include <Control.h>
#include <LookupContext.h>

#include <QtCore/QDebug>

#include <algorithm>
#include <utility>

using namespace CPlusPlus;
using namespace CppTools;

namespace {

class FindMatchingDefinition: public SymbolVisitor
{
    Symbol *_declaration;
    const OperatorNameId *_oper;
    QList<Function *> _result;

public:
    FindMatchingDefinition(Symbol *declaration)
        : _declaration(declaration)
        , _oper(0)
    {
        if (_declaration->name())
            _oper = _declaration->name()->asOperatorNameId();
    }

    QList<Function *> result() const { return _result; }

    using SymbolVisitor::visit;

    virtual bool visit(Function *fun)
    {
        if (_oper) {
            if (const Name *name = fun->unqualifiedName()) {
                    if (_oper->isEqualTo(name))
                        _result.append(fun);
            }
        } else if (const Identifier *id = _declaration->identifier()) {
            if (id->isEqualTo(fun->identifier()))
                _result.append(fun);
        }

        return false;
    }

    virtual bool visit(Block *)
    {
        return false;
    }
};

} // end of anonymous namespace


SymbolFinder::SymbolFinder(const QString &referenceFileName)
    : m_referenceFile(referenceFileName)
{}

SymbolFinder::SymbolFinder(const char *referenceFileName, unsigned referenceFileLength)
    : m_referenceFile(QString::fromUtf8(referenceFileName, referenceFileLength))
{}

// strict means the returned symbol has to match exactly,
// including argument count and argument types
Symbol *SymbolFinder::findMatchingDefinition(Symbol *declaration,
                                             const Snapshot &snapshot,
                                             bool strict)
{
    if (!declaration)
        return 0;

    QString declFile = QString::fromUtf8(declaration->fileName(), declaration->fileNameLength());
    Q_ASSERT(declFile == m_referenceFile);

    Document::Ptr thisDocument = snapshot.document(declFile);
    if (! thisDocument) {
        qWarning() << "undefined document:" << declaration->fileName();
        return 0;
    }

    Function *declarationTy = declaration->type()->asFunctionType();
    if (! declarationTy) {
        qWarning() << "not a function:" << declaration->fileName()
                   << declaration->line() << declaration->column();
        return 0;
    }

    foreach (const QString &fileName, fileIterationOrder(snapshot)) {
        Document::Ptr doc = snapshot.document(fileName);
        if (!doc) {
            clear(fileName);
            continue;
        }

        const Identifier *id = declaration->identifier();
        if (id && ! doc->control()->findIdentifier(id->chars(), id->size()))
            continue;

        if (!id) {
            if (!declaration->name())
                continue;
            const OperatorNameId *oper = declaration->name()->asOperatorNameId();
            if (!oper)
                continue;
            if (!doc->control()->findOperatorNameId(oper->kind()))
                continue;
        }

        FindMatchingDefinition candidates(declaration);
        candidates.accept(doc->globalNamespace());

        const QList<Function *> result = candidates.result();
        if (! result.isEmpty()) {
            LookupContext context(doc, snapshot);

            QList<Function *> viableFunctions;

            ClassOrNamespace *enclosingType = context.lookupType(declaration);
            if (! enclosingType)
                continue; // nothing to do

            foreach (Function *fun, result) {
                const QList<LookupItem> declarations = context.lookup(fun->name(), fun->enclosingScope());
                if (declarations.isEmpty())
                    continue;

                const LookupItem best = declarations.first();
                if (enclosingType == context.lookupType(best.declaration()))
                    viableFunctions.append(fun);
            }

            if (viableFunctions.isEmpty())
                continue;

            else if (! strict && viableFunctions.length() == 1)
                return viableFunctions.first();

            Function *best = 0;

            foreach (Function *fun, viableFunctions) {
                if (! (fun->unqualifiedName() && fun->unqualifiedName()->isEqualTo(declaration->unqualifiedName())))
                    continue;
                else if (fun->argumentCount() == declarationTy->argumentCount()) {
                    if (! strict && ! best)
                        best = fun;

                    unsigned argc = 0;
                    for (; argc < declarationTy->argumentCount(); ++argc) {
                        Symbol *arg = fun->argumentAt(argc);
                        Symbol *otherArg = declarationTy->argumentAt(argc);
                        if (! arg->type().isEqualTo(otherArg->type()))
                            break;
                    }

                    if (argc == declarationTy->argumentCount())
                        best = fun;
                }
            }

            if (strict && ! best)
                continue;

            if (! best)
                best = viableFunctions.first();
            return best;
        }
    }

    return 0;
}

Class *SymbolFinder::findMatchingClassDeclaration(Symbol *declaration, const Snapshot &snapshot)
{
    if (! declaration->identifier())
        return 0;

    QString declFile = QString::fromUtf8(declaration->fileName(), declaration->fileNameLength());
    Q_ASSERT(declFile == m_referenceFile);

    foreach (const QString &file, fileIterationOrder(snapshot)) {
        Document::Ptr doc = snapshot.document(file);
        if (!doc) {
            clear(file);
            continue;
        }

        if (! doc->control()->findIdentifier(declaration->identifier()->chars(),
                                             declaration->identifier()->size()))
            continue;

        LookupContext context(doc, snapshot);

        ClassOrNamespace *type = context.lookupType(declaration);
        if (!type)
            continue;

        foreach (Symbol *s, type->symbols()) {
            if (Class *c = s->asClass())
                return c;
        }
    }

    return 0;
}

void SymbolFinder::findMatchingDeclaration(const LookupContext &context,
                                           Function *functionType,
                                           QList<Declaration *> *typeMatch,
                                           QList<Declaration *> *argumentCountMatch,
                                           QList<Declaration *> *nameMatch)
{
    Scope *enclosingScope = functionType->enclosingScope();
    while (! (enclosingScope->isNamespace() || enclosingScope->isClass()))
        enclosingScope = enclosingScope->enclosingScope();
    Q_ASSERT(enclosingScope != 0);

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

    ClassOrNamespace *binding = 0;
    const QualifiedNameId *qName = functionName->asQualifiedNameId();
    if (qName) {
        if (qName->base())
            binding = context.lookupType(qName->base(), enclosingScope);
        else
            binding = context.globalNamespace();
        functionName = qName->name();
    }

    if (!binding) { // declaration for a global function
        binding = context.lookupType(enclosingScope);

        if (!binding)
            return;
    }

    const Identifier *funcId = functionName->identifier();
    if (!funcId) // E.g. operator, which we might be able to handle in the future...
        return;

    foreach (Symbol *s, binding->symbols()) {
        Scope *scope = s->asScope();
        if (!scope)
            continue;

        for (Symbol *s = scope->find(funcId); s; s = s->next()) {
            if (! s->name())
                continue;
            else if (! funcId->isEqualTo(s->identifier()))
                continue;
            else if (! s->type()->isFunctionType())
                continue;
            else if (Declaration *decl = s->asDeclaration()) {
                if (Function *declFunTy = decl->type()->asFunctionType()) {
                    if (functionType->isEqualTo(declFunTy))
                        typeMatch->prepend(decl);
                    else if (functionType->argumentCount() == declFunTy->argumentCount())
                        argumentCountMatch->prepend(decl);
                    else
                        nameMatch->append(decl);
                }
            }
        }
    }
}

QList<Declaration *> SymbolFinder::findMatchingDeclaration(const LookupContext &context,
                                                           Function *functionType)
{
    QList<Declaration *> result;
    QList<Declaration *> nameMatch, argumentCountMatch, typeMatch;
    findMatchingDeclaration(context, functionType, &typeMatch, &argumentCountMatch, &nameMatch);
    result.append(typeMatch);
    result.append(argumentCountMatch);
    result.append(nameMatch);
    return result;
}

#include <QtCore/QThread>
QStringList SymbolFinder::fileIterationOrder(const Snapshot &snapshot)
{
    if (m_filePriorityCache.isEmpty()) {
        foreach (const Document::Ptr &doc, snapshot)
            insert(doc->fileName());
    } else {
        checkCacheConsistency(snapshot);
    }

    return m_filePriorityCache.values();
}

void SymbolFinder::checkCacheConsistency(const Snapshot &snapshot)
{
    // We only check for "new" files, which which are in the snapshot but not in the cache.
    // The counterpart validation for "old" files is done when one tries to access the
    // corresponding document and notices it's now null.
    foreach (const Document::Ptr &doc, snapshot) {
        if (!m_fileMetaCache.contains(doc->fileName()))
            insert(doc->fileName());
    }
}

void SymbolFinder::clear(const QString &comparingFile)
{
    m_filePriorityCache.remove(computeKey(m_referenceFile, comparingFile), comparingFile);
    m_fileMetaCache.remove(comparingFile);
}

void SymbolFinder::insert(const QString &comparingFile)
{
    // We want an ordering such that the documents with the most common path appear first.
    m_filePriorityCache.insert(computeKey(m_referenceFile, comparingFile), comparingFile);
    m_fileMetaCache.insert(comparingFile);
}

int SymbolFinder::computeKey(const QString &referenceFile, const QString &comparingFile)
{
    // As similar the path from the comparing file is to the path from the reference file,
    // the smaller the key is, which is then used for sorting the map.
    std::pair<QString::const_iterator,
              QString::const_iterator> r = std::mismatch(referenceFile.begin(),
                                                         referenceFile.end(),
                                                         comparingFile.begin());
    return referenceFile.length() - (r.first - referenceFile.begin());
}