Skip to content
Snippets Groups Projects
ResolveExpression.cpp 22.5 KiB
Newer Older
/**************************************************************************
con's avatar
con committed
**
** This file is part of Qt Creator
**
hjk's avatar
hjk committed
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
con's avatar
con committed
**
** Contact: Nokia Corporation (qt-info@nokia.com)
con's avatar
con committed
**
** 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
hjk's avatar
hjk committed
** contact the sales department at http://qt.nokia.com/contact.
con's avatar
con committed
**
**************************************************************************/
con's avatar
con committed

#include "ResolveExpression.h"
#include "LookupContext.h"
con's avatar
con committed
#include "Overview.h"
#include "DeprecatedGenTemplateInstance.h"
#include "CppRewriter.h"
con's avatar
con committed

#include <Control.h>
#include <AST.h>
#include <Scope.h>
#include <Names.h>
#include <Symbols.h>
#include <Literals.h>
#include <CoreTypes.h>
#include <TypeVisitor.h>
#include <NameVisitor.h>
hjk's avatar
hjk committed

hjk's avatar
hjk committed
#include <QtCore/QList>
#include <QtCore/QtDebug>
con's avatar
con committed

using namespace CPlusPlus;

hjk's avatar
hjk committed
namespace {
con's avatar
con committed

template <typename _Tp>
static QList<_Tp> removeDuplicates(const QList<_Tp> &results)
{
    QList<_Tp> uniqueList;
    QSet<_Tp> processed;
    foreach (const _Tp &r, results) {
        if (processed.contains(r))
            continue;

        processed.insert(r);
        uniqueList.append(r);
    }

    return uniqueList;
}

con's avatar
con committed
} // end of anonymous namespace

/////////////////////////////////////////////////////////////////////
// ResolveExpression
/////////////////////////////////////////////////////////////////////
ResolveExpression::ResolveExpression(const LookupContext &context)
    : ASTVisitor(context.expressionDocument()->translationUnit()),
con's avatar
con committed
      _context(context),
      bind(context.expressionDocument()->translationUnit())
con's avatar
con committed

ResolveExpression::~ResolveExpression()
{ }

QList<LookupItem> ResolveExpression::operator()(ExpressionAST *ast, Scope *scope)
{ return resolve(ast, scope); }

QList<LookupItem> ResolveExpression::resolve(ExpressionAST *ast, Scope *scope)
{
    if (! scope)
        return QList<LookupItem>();

    Scope *previousVisibleSymbol = _scope;
    _scope = scope;
    const QList<LookupItem> result = resolve(ast);
    _scope = previousVisibleSymbol;
    return result;
}

QList<LookupItem> ResolveExpression::resolve(ExpressionAST *ast)
con's avatar
con committed
{
    const QList<LookupItem> previousResults = switchResults(QList<LookupItem>());
con's avatar
con committed
    accept(ast);
    return removeDuplicates(switchResults(previousResults));
con's avatar
con committed
}

QList<LookupItem> ResolveExpression::switchResults(const QList<LookupItem> &results)
con's avatar
con committed
{
    const QList<LookupItem> previousResults = _results;
con's avatar
con committed
    _results = results;
    return previousResults;
}

void ResolveExpression::addResults(const QList<Symbol *> &symbols)
con's avatar
con committed
{
    foreach (Symbol *symbol, symbols) {
        LookupItem item;
        item.setType(symbol->type());
        item.setScope(symbol->scope());
        item.setDeclaration(symbol);
con's avatar
con committed
}

void ResolveExpression::addResults(const QList<LookupItem> &items)
{
    _results += items;
}

void ResolveExpression::addResult(const FullySpecifiedType &ty, Scope *scope)
con's avatar
con committed
{
    LookupItem item;
    item.setType(ty);
    item.setScope(scope);
con's avatar
con committed

con's avatar
con committed

bool ResolveExpression::visit(IdExpressionAST *ast)
{
    accept(ast->name);
    return false;
}

bool ResolveExpression::visit(BinaryExpressionAST *ast)
con's avatar
con committed
{
    if (tokenKind(ast->binary_op_token) == T_COMMA && ast->right_expression && ast->right_expression->asQtMethod() != 0) {

        if (ast->left_expression && ast->left_expression->asQtMethod() != 0)
            thisObject();
        else
            accept(ast->left_expression);

        QtMethodAST *qtMethod = ast->right_expression->asQtMethod();
        if (DeclaratorAST *d = qtMethod->declarator) {
            if (d->core_declarator) {
                if (DeclaratorIdAST *declaratorId = d->core_declarator->asDeclaratorId()) {
                    if (NameAST *nameAST = declaratorId->name) {
                        if (ClassOrNamespace *binding = baseExpression(_results, T_ARROW)) {
                            _results.clear();
                            addResults(binding->lookup(nameAST->name));
                        }
                    }
                }
    accept(ast->left_expression);
con's avatar
con committed
    return false;
}

bool ResolveExpression::visit(CastExpressionAST *ast)
{
    Scope *dummyScope = _context.expressionDocument()->globalNamespace();
    FullySpecifiedType ty = bind(ast->type_id, dummyScope);
con's avatar
con committed
    return false;
}

bool ResolveExpression::visit(ConditionAST *)
{
    // nothing to do.
    return false;
}

bool ResolveExpression::visit(ConditionalExpressionAST *ast)
con's avatar
con committed
{
    if (ast->left_expression)
        accept(ast->left_expression);

    else if (ast->right_expression)
        accept(ast->right_expression);

con's avatar
con committed
    return false;
}

bool ResolveExpression::visit(CppCastExpressionAST *ast)
{
    Scope *dummyScope = _context.expressionDocument()->globalNamespace();
    FullySpecifiedType ty = bind(ast->type_id, dummyScope);
con's avatar
con committed
    return false;
}

bool ResolveExpression::visit(DeleteExpressionAST *)
{
    FullySpecifiedType ty(control()->voidType());
con's avatar
con committed
    return false;
}

bool ResolveExpression::visit(ArrayInitializerAST *)
{
    // nothing to do.
    return false;
}

bool ResolveExpression::visit(NewExpressionAST *ast)
con's avatar
con committed
{
    if (ast->new_type_id) {
        Scope *dummyScope = _context.expressionDocument()->globalNamespace();
        FullySpecifiedType ty = bind(ast->new_type_id, dummyScope);
        FullySpecifiedType ptrTy(control()->pointerType(ty));
        addResult(ptrTy, _scope);
con's avatar
con committed
    // nothing to do.
    return false;
}

bool ResolveExpression::visit(TypeidExpressionAST *)
{
    const Name *stdName = control()->nameId(control()->identifier("std"));
    const Name *tiName = control()->nameId(control()->identifier("type_info"));
    const Name *q = control()->qualifiedNameId(control()->qualifiedNameId(/* :: */ 0, stdName), tiName);
con's avatar
con committed

    FullySpecifiedType ty(control()->namedType(q));
con's avatar
con committed

    return false;
}

bool ResolveExpression::visit(TypenameCallExpressionAST *)
{
    // nothing to do
    return false;
}

bool ResolveExpression::visit(TypeConstructorCallAST *)
{
    // nothing to do.
    return false;
}

bool ResolveExpression::visit(SizeofExpressionAST *)
{
    FullySpecifiedType ty(control()->integerType(IntegerType::Int));
    ty.setUnsigned(true);
con's avatar
con committed
    return false;
}

bool ResolveExpression::visit(NumericLiteralAST *ast)
con's avatar
con committed
{
    const Token &tk = tokenAt(ast->literal_token);

    Type *type = 0;
    bool isUnsigned = false;
    if (tk.is(T_CHAR_LITERAL))
        type = control()->integerType(IntegerType::Char);
    else if (tk.is(T_WIDE_CHAR_LITERAL))
        type = control()->integerType(IntegerType::WideChar);
    else if (const NumericLiteral *literal = numericLiteral(ast->literal_token)) {
        isUnsigned = literal->isUnsigned();

        if (literal->isInt())
            type = control()->integerType(IntegerType::Int);
        else if (literal->isLong())
            type = control()->integerType(IntegerType::Long);
        else if (literal->isLongLong())
            type = control()->integerType(IntegerType::LongLong);
        else if (literal->isFloat())
            type = control()->floatType(FloatType::Float);
        else if (literal->isDouble())
            type = control()->floatType(FloatType::Double);
        else if (literal->isLongDouble())
            type = control()->floatType(FloatType::LongDouble);
        else
            type = control()->integerType(IntegerType::Int);
    }

    FullySpecifiedType ty(type);
    ty.setUnsigned(isUnsigned);
con's avatar
con committed
    return false;
}

bool ResolveExpression::visit(BoolLiteralAST *)
{
    FullySpecifiedType ty(control()->integerType(IntegerType::Bool));
con's avatar
con committed
    return false;
}

bool ResolveExpression::visit(ThisExpressionAST *)
{
    thisObject();
    return false;
}

void ResolveExpression::thisObject()
con's avatar
con committed
{
    Scope *scope = _scope;
    for (; scope; scope = scope->scope()) {
        if (Function *fun = scope->asFunction()) {
            if (Class *klass = scope->enclosingClass()) {
con's avatar
con committed
                FullySpecifiedType classTy(control()->namedType(klass->name()));
                FullySpecifiedType ptrTy(control()->pointerType(classTy));
                addResult(ptrTy, fun->scope());
con's avatar
con committed
                break;
Roberto Raggi's avatar
Roberto Raggi committed
            } else if (const QualifiedNameId *q = fun->name()->asQualifiedNameId()) {
                if (q->base()) {
                    FullySpecifiedType classTy(control()->namedType(q->base()));
                    FullySpecifiedType ptrTy(control()->pointerType(classTy));
                    addResult(ptrTy, fun->scope());
                }
con's avatar
con committed
                break;
            }
        }
    }
}

bool ResolveExpression::visit(CompoundExpressionAST *ast)
{
    CompoundStatementAST *cStmt = ast->statement;
    if (cStmt && cStmt->statement_list) {
        accept(cStmt->statement_list->lastValue());
    }
    return false;
con's avatar
con committed
bool ResolveExpression::visit(NestedExpressionAST *ast)
{
    accept(ast->expression);
    return false;
}

bool ResolveExpression::visit(StringLiteralAST *)
{
    FullySpecifiedType charTy = control()->integerType(IntegerType::Char);
    charTy.setConst(true);
    FullySpecifiedType ty(control()->pointerType(charTy));
con's avatar
con committed
    return false;
}

bool ResolveExpression::visit(ThrowExpressionAST *)
{
    return false;
}

bool ResolveExpression::visit(TypeIdAST *)
{
    return false;
}

bool ResolveExpression::visit(UnaryExpressionAST *ast)
{
    accept(ast->expression);
    unsigned unaryOp = tokenKind(ast->unary_op_token);
    if (unaryOp == T_AMPER) {
        QMutableListIterator<LookupItem > it(_results);
con's avatar
con committed
        while (it.hasNext()) {
            LookupItem p = it.next();
            FullySpecifiedType ty = p.type();
            ty.setType(control()->pointerType(ty));
            p.setType(ty);
con's avatar
con committed
            it.setValue(p);
        }
    } else if (unaryOp == T_STAR) {
        QMutableListIterator<LookupItem > it(_results);
con's avatar
con committed
        while (it.hasNext()) {
            LookupItem p = it.next();
            if (PointerType *ptrTy = p.type()->asPointerType()) {
                p.setType(ptrTy->elementType());
con's avatar
con committed
                it.setValue(p);
            } else {
                it.remove();
            }
        }
    }
    return false;
}

bool ResolveExpression::visit(CompoundLiteralAST *ast)
{
    accept(ast->type_id);
    return false;
}

con's avatar
con committed
bool ResolveExpression::visit(QualifiedNameAST *ast)
{
    if (const Name *name = ast->name) {
        const QList<LookupItem> candidates = _context.lookup(name, _scope);
con's avatar
con committed
    }

    return false;
}

bool ResolveExpression::visit(SimpleNameAST *ast)
con's avatar
con committed
{
    const QList<LookupItem> candidates = _context.lookup(ast->name, _scope);
con's avatar
con committed
    return false;
}

bool ResolveExpression::visit(TemplateIdAST *ast)
con's avatar
con committed
{
    const QList<LookupItem> candidates = _context.lookup(ast->name, _scope);
con's avatar
con committed
    return false;
}

bool ResolveExpression::visit(DestructorNameAST *)
{
    FullySpecifiedType ty(control()->voidType());
con's avatar
con committed
    return false;
}

bool ResolveExpression::visit(OperatorFunctionIdAST *)
con's avatar
con committed
{
    return false;
}
con's avatar
con committed

bool ResolveExpression::visit(ConversionFunctionIdAST *)
{
con's avatar
con committed
    return false;
}

bool ResolveExpression::maybeValidPrototype(Function *funTy, unsigned actualArgumentCount) const
{
    unsigned minNumberArguments = 0;

    for (; minNumberArguments < funTy->argumentCount(); ++minNumberArguments) {
        Argument *arg = funTy->argumentAt(minNumberArguments)->asArgument();

        if (arg->hasInitializer())
            break;
    }

    if (actualArgumentCount < minNumberArguments) {
        // not enough arguments.
        return false;

    } else if (! funTy->isVariadic() && actualArgumentCount > funTy->argumentCount()) {
        // too many arguments.
        return false;
    }

    return true;
}

con's avatar
con committed
bool ResolveExpression::visit(CallAST *ast)
{
    const QList<LookupItem> baseResults = resolve(ast->base_expression, _scope);
con's avatar
con committed
    // Compute the types of the actual arguments.
    int actualArgumentCount = 0;
con's avatar
con committed

    //QList< QList<Result> > arguments;
    for (ExpressionListAST *exprIt = ast->expression_list; exprIt; exprIt = exprIt->next) {
        //arguments.append(resolve(exprIt->expression));
        ++actualArgumentCount;
    }
con's avatar
con committed

Roberto Raggi's avatar
Roberto Raggi committed
    const Name *functionCallOp = control()->operatorNameId(OperatorNameId::FunctionCallOp);
    foreach (const LookupItem &result, baseResults) {
        FullySpecifiedType ty = result.type().simplified();
        Scope *scope = result.scope();

        if (NamedType *namedTy = ty->asNamedType()) {
            if (ClassOrNamespace *b = _context.lookupType(namedTy->name(), scope)) {
                foreach (const LookupItem &r, b->find(functionCallOp)) {
                    Symbol *overload = r.declaration();
                    if (Function *funTy = overload->type()->asFunctionType()) {
                        if (maybeValidPrototype(funTy, actualArgumentCount)) {
                            if (Function *proto = instantiate(namedTy->name(), funTy)->asFunctionType())
                                addResult(proto->returnType().simplified(), scope);
con's avatar
con committed
            }
        } else if (Function *funTy = ty->asFunctionType()) {
            if (maybeValidPrototype(funTy, actualArgumentCount))
                addResult(funTy->returnType().simplified(), scope);

        } else if (Class *classTy = ty->asClassType()) {
con's avatar
con committed
            // Constructor call
            FullySpecifiedType ctorTy = control()->namedType(classTy->name());
            addResult(ctorTy, scope);
con's avatar
con committed
        }
    }

    return false;
}

bool ResolveExpression::visit(ArrayAccessAST *ast)
{
    const QList<LookupItem> baseResults = resolve(ast->base_expression, _scope);
    const QList<LookupItem> indexResults = resolve(ast->expression);
con's avatar
con committed

Roberto Raggi's avatar
Roberto Raggi committed
    const Name *arrayAccessOp = control()->operatorNameId(OperatorNameId::ArrayAccessOp);
con's avatar
con committed

    foreach (const LookupItem &result, baseResults) {
        FullySpecifiedType ty = result.type().simplified();
        Scope *scope = result.scope();
con's avatar
con committed

        if (PointerType *ptrTy = ty->asPointerType()) {
            addResult(ptrTy->elementType().simplified(), scope);
con's avatar
con committed
        } else if (ArrayType *arrTy = ty->asArrayType()) {
            addResult(arrTy->elementType().simplified(), scope);
con's avatar
con committed
        } else if (NamedType *namedTy = ty->asNamedType()) {
            if (ClassOrNamespace *b = _context.lookupType(namedTy->name(), scope)) {
                foreach (const LookupItem &r, b->find(arrayAccessOp)) {
                    Symbol *overload = r.declaration();
                    if (Function *funTy = overload->type()->asFunctionType()) {
                        if (Function *proto = instantiate(namedTy->name(), funTy)->asFunctionType())
                            // ### TODO: check the actual arguments
                            addResult(proto->returnType().simplified(), scope);
con's avatar
con committed
                }
con's avatar
con committed
            }
        }
    }
    return false;
}

QList<LookupItem> ResolveExpression::getMembers(ClassOrNamespace *binding, const Name *memberName) const
{
    Q_UNUSED(binding);
    Q_UNUSED(memberName);

    // ### port me
    QList<LookupItem> members;
#if 0
    const QList<LookupItem> originalMembers = binding->find(memberName);

    foreach (const LookupItem &m, originalMembers) {
        if (! m.binding() || ! m.binding()->templateId()) {
            members.append(m);
            continue;
        }

        Symbol *decl = m.declaration();

        if (Class *klass = decl->scope()->asClass()) {
            if (klass->templateParameters() != 0) {
                SubstitutionMap map;

                const TemplateNameId *templateId = m.binding()->templateId();
                unsigned count = qMin(klass->templateParameterCount(), templateId->templateArgumentCount());

                for (unsigned i = 0; i < count; ++i) {
                    map.bind(klass->templateParameterAt(i)->name(), templateId->templateArgumentAt(i));
                }

                SubstitutionEnvironment env;
                if (m.scope())
                    env.switchScope(m.scope());
                env.setContext(_context);
                FullySpecifiedType instantiatedTy = rewriteType(decl->type(), &env, _context.control().data());

                Overview oo;
                oo.setShowReturnTypes(true);
                oo.setShowFunctionSignatures(true);

                qDebug() << "original:" << oo(decl->type(), decl->name()) << "inst:" << oo(instantiatedTy, decl->name());

                LookupItem newItem;
                newItem = m;
                newItem.setType(instantiatedTy);
                members.append(newItem);
            }
        }
    }
#endif
con's avatar
con committed
bool ResolveExpression::visit(MemberAccessAST *ast)
{
    // The candidate types for the base expression are stored in
    // _results.
    const QList<LookupItem> baseResults = resolve(ast->base_expression, _scope);
con's avatar
con committed

    // Evaluate the expression-id that follows the access operator.
Roberto Raggi's avatar
Roberto Raggi committed
    const Name *memberName = 0;
    if (ast->member_name)
        memberName = ast->member_name->name;
con's avatar
con committed

    // Remember the access operator.
    const int accessOp = tokenKind(ast->access_token);
con's avatar
con committed

    if (ClassOrNamespace *binding = baseExpression(baseResults, accessOp))
        addResults(binding->lookup(memberName));
con's avatar
con committed

    return false;
}

ClassOrNamespace *ResolveExpression::findClass(const FullySpecifiedType &originalTy, Scope *scope) const
{
    FullySpecifiedType ty = originalTy.simplified();
    ClassOrNamespace *binding = 0;

    if (Class *klass = ty->asClassType())
        binding = _context.lookupType(klass);

    else if (NamedType *namedTy = ty->asNamedType())
        binding = _context.lookupType(namedTy->name(), scope);
    else if (Function *funTy = ty->asFunctionType())
        return findClass(funTy->returnType(), scope);

ClassOrNamespace *ResolveExpression::baseExpression(const QList<LookupItem> &baseResults,
                                                    int accessOp,
                                                    bool *replacedDotOperator) const
{
    foreach (const LookupItem &r, baseResults) {
        FullySpecifiedType ty = r.type().simplified();
        Scope *scope = r.scope();
        if (accessOp == T_ARROW) {
            if (PointerType *ptrTy = ty->asPointerType()) {
                if (ClassOrNamespace *binding = findClass(ptrTy->elementType(), scope))
                    return binding;

            } else if (ClassOrNamespace *binding = findClass(ty, scope)) {
                // lookup for overloads of operator->
                const OperatorNameId *arrowOp = control()->operatorNameId(OperatorNameId::ArrowOp);
                foreach (const LookupItem &r, binding->find(arrowOp)) {
                    Symbol *overload = r.declaration();
                    if (! overload)
                        continue;
Roberto Raggi's avatar
Roberto Raggi committed
                    if (overload->type()->isFunctionType()) {
                        FullySpecifiedType overloadTy = instantiate(binding->templateId(), overload);
                        Function *instantiatedFunction = overloadTy->asFunctionType();
                        Q_ASSERT(instantiatedFunction != 0);

                        FullySpecifiedType retTy = instantiatedFunction->returnType().simplified();

                        if (PointerType *ptrTy = retTy->asPointerType()) {
                            if (ClassOrNamespace *retBinding = findClass(ptrTy->elementType(), overload->scope()))
                                return retBinding;
                            else if (scope != overload->scope()) {
                                if (ClassOrNamespace *retBinding = findClass(ptrTy->elementType(), scope))
                                    return retBinding;
                            }
        } else if (accessOp == T_DOT) {
            if (replacedDotOperator) {
                if (PointerType *ptrTy = ty->asPointerType()) {
                    // replace . with ->
                    ty = ptrTy->elementType();
                    *replacedDotOperator = true;
                }
            if (ClassOrNamespace *binding = findClass(ty, scope))
                return binding;
        }
FullySpecifiedType ResolveExpression::instantiate(const Name *className, Symbol *candidate) const
{
    return DeprecatedGenTemplateInstance::instantiate(className, candidate, _context.control());
bool ResolveExpression::visit(PostIncrDecrAST *ast)
con's avatar
con committed
{
    const QList<LookupItem> baseResults = resolve(ast->base_expression, _scope);
    _results = baseResults;
con's avatar
con committed
    return false;
}
bool ResolveExpression::visit(ObjCMessageExpressionAST *ast)
    const QList<LookupItem> receiverResults = resolve(ast->receiver_expression);
    foreach (const LookupItem &result, receiverResults) {
        FullySpecifiedType ty = result.type().simplified();
        ClassOrNamespace *binding = 0;
        if (ObjCClass *clazz = ty->asObjCClassType()) {
            // static access, e.g.:
            //   [NSObject description];
            binding = _context.lookupType(clazz);
        } else if (PointerType *ptrTy = ty->asPointerType()) {
            if (NamedType *namedTy = ptrTy->elementType()->asNamedType()) {
                // dynamic access, e.g.:
                //   NSObject *obj = ...; [obj release];
                binding = _context.lookupType(namedTy->name(), result.scope());
            foreach (const LookupItem &r, binding->lookup(ast->selector->name)) {
                Symbol *s = r.declaration();
                if (ObjCMethod *m = s->asObjCMethod())
                    addResult(m->returnType(), result.scope());