Commit b2659950 authored by Erik Verbruggen's avatar Erik Verbruggen

Added the InsertionPointLocator.

For answers to questions about where to insert a snippet/chunk of C++ code. Ok,
currently it will only find the One And Only place to insert method
declarations in classes, and it will need some tuning.
parent 51d6b09e
/**************************************************************************
**
** 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 "InsertionPointLocator.h"
#include <AST.h>
#include <ASTVisitor.h>
#include <TranslationUnit.h>
using namespace CPlusPlus;
namespace {
static QString generate(InsertionPointLocator::AccessSpec xsSpec)
{
switch (xsSpec) {
default:
case InsertionPointLocator::Public:
return QLatin1String("public:\n");
case InsertionPointLocator::Protected:
return QLatin1String("protected:\n");
case InsertionPointLocator::Private:
return QLatin1String("private:\n");
case InsertionPointLocator::PublicSlot:
return QLatin1String("public slots:\n");
case InsertionPointLocator::ProtectedSlot:
return QLatin1String("protected slots:\n");
case InsertionPointLocator::PrivateSlot:
return QLatin1String("private slot:\n");
case InsertionPointLocator::Signals:
return QLatin1String("signals:\n");
}
}
static int distance(InsertionPointLocator::AccessSpec one, InsertionPointLocator::AccessSpec two)
{
static QList<InsertionPointLocator::AccessSpec> distances = QList<InsertionPointLocator::AccessSpec>()
<< InsertionPointLocator::Public
<< InsertionPointLocator::PublicSlot
<< InsertionPointLocator::Signals
<< InsertionPointLocator::Protected
<< InsertionPointLocator::ProtectedSlot
<< InsertionPointLocator::PrivateSlot
<< InsertionPointLocator::Private
;
return distances.indexOf(one) - distances.indexOf(two);
}
struct AccessRange
{
unsigned start;
unsigned end;
InsertionPointLocator::AccessSpec xsSpec;
AccessRange()
: start(0)
, end(0)
, xsSpec(InsertionPointLocator::Invalid)
{}
AccessRange(unsigned start, unsigned end, InsertionPointLocator::AccessSpec xsSpec)
: start(start)
, end(end)
, xsSpec(xsSpec)
{}
};
class FindInClass: public ASTVisitor
{
public:
FindInClass(const Document::Ptr &doc, const Class *clazz, InsertionPointLocator::AccessSpec xsSpec)
: ASTVisitor(doc->translationUnit())
, _doc(doc)
, _clazz(clazz)
, _xsSpec(xsSpec)
{}
InsertionLocation operator()()
{
_result = InsertionLocation();
AST *ast = translationUnit()->ast();
accept(ast);
return _result;
}
protected:
using ASTVisitor::visit;
bool visit(ClassSpecifierAST *ast)
{
if (!ast->lbrace_token || !ast->rbrace_token)
return true;
if (!ast->symbol || !ast->symbol->isEqualTo(_clazz))
return true;
QList<AccessRange> ranges = collectAccessRanges(
ast->member_specifier_list,
tokenKind(ast->classkey_token) == T_CLASS ? InsertionPointLocator::Private : InsertionPointLocator::Public,
ast->lbrace_token,
ast->rbrace_token);
QPair<unsigned, bool> result = findMatch(ranges, _xsSpec);
unsigned line = 0, column = 0;
getTokenStartPosition(result.first, &line, &column);
QString prefix;
if (!result.second)
prefix = generate(_xsSpec);
_result = InsertionLocation(prefix, line, column);
return false;
}
static QPair<unsigned, bool> findMatch(const QList<AccessRange> &ranges,
InsertionPointLocator::AccessSpec xsSpec)
{
// try an exact match, and ignore the first (default) access spec:
for (int i = ranges.size() - 1; i > 0; --i) {
const AccessRange &range = ranges.at(i);
if (range.xsSpec == xsSpec)
return qMakePair(range.end, true);
}
// try to find a fitting access spec to insert in front of:
AccessRange best = ranges.first();
for (int i = ranges.size() - 1; i > 0; --i) {
const AccessRange &range = ranges.at(i);
if (distance(range.xsSpec, xsSpec) < distance(best.xsSpec, xsSpec))
best = range;
}
// otherwise:
return qMakePair(ranges.first().end, false);
}
QList<AccessRange> collectAccessRanges(DeclarationListAST *decls,
InsertionPointLocator::AccessSpec initialXs,
int firstRangeStart,
int lastRangeEnd) const
{
QList<AccessRange> ranges;
ranges.append(AccessRange(firstRangeStart, lastRangeEnd, initialXs));
for (DeclarationListAST *iter = decls; iter; iter = iter->next) {
DeclarationAST *decl = iter->value;
if (AccessDeclarationAST *xsDecl = decl->asAccessDeclaration()) {
const unsigned token = xsDecl->access_specifier_token;
int newXsSpec = initialXs;
bool isSlot = xsDecl->slots_token && tokenKind(xsDecl->slots_token) == T_Q_SLOTS;
switch (tokenKind(token)) {
case T_PUBLIC:
newXsSpec = isSlot ? InsertionPointLocator::PublicSlot : InsertionPointLocator::Public;
break;
case T_PROTECTED:
newXsSpec = isSlot ? InsertionPointLocator::PublicSlot : InsertionPointLocator::Protected;
break;
case T_PRIVATE:
newXsSpec = isSlot ? InsertionPointLocator::PublicSlot : InsertionPointLocator::Private;
break;
case T_Q_SIGNALS:
newXsSpec = InsertionPointLocator::Signals;
break;
case T_Q_SLOTS: {
newXsSpec = ranges.last().xsSpec | InsertionPointLocator::SlotBit;
break;
}
default:
break;
}
if (newXsSpec != ranges.last().xsSpec) {
ranges.last().end = token;
ranges.append(AccessRange(token, lastRangeEnd, (InsertionPointLocator::AccessSpec) newXsSpec));
}
}
}
ranges.last().end = lastRangeEnd;
return ranges;
}
private:
Document::Ptr _doc;
const Class *_clazz;
InsertionPointLocator::AccessSpec _xsSpec;
InsertionLocation _result;
};
} // end of anonymous namespace
InsertionLocation::InsertionLocation()
: m_line(0)
, m_column(0)
{}
InsertionLocation::InsertionLocation(const QString &prefix, unsigned line, unsigned column)
: m_prefix(prefix)
, m_line(line)
, m_column(column)
{}
InsertionPointLocator::InsertionPointLocator(const Document::Ptr &doc)
: m_doc(doc)
{
}
InsertionLocation InsertionPointLocator::methodDeclarationInClass(const Class *clazz, AccessSpec xsSpec) const
{
FindInClass find(m_doc, clazz, xsSpec);
return find();
}
/**************************************************************************
**
** 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.
**
**************************************************************************/
#ifndef INSERTIONPOINTLOCATOR_H
#define INSERTIONPOINTLOCATOR_H
#include <CPlusPlusForwardDeclarations.h>
#include <Symbols.h>
#include <cplusplus/CppDocument.h>
namespace CPlusPlus {
class CPLUSPLUS_EXPORT InsertionLocation
{
public:
InsertionLocation();
InsertionLocation(const QString &prefix, unsigned line, unsigned column);
/// \returns The prefix to insert before any other text.
QString prefix() const
{ return m_prefix; }
/// \returns The line where to insert. The line number is 1-based.
int line() const
{ return m_line; }
/// \returns The column where to insert. The column number is 1-based.
int column() const
{ return m_column; }
bool isValid() const
{ return m_line > 0 && m_column > 0; }
private:
QString m_prefix;
unsigned m_line;
unsigned m_column;
};
class CPLUSPLUS_EXPORT InsertionPointLocator
{
public:
enum AccessSpec {
Invalid = -1,
Signals = 0,
Public = 1,
Protected = 2,
Private = 3,
SlotBit = 1 << 2,
PublicSlot = Public | SlotBit,
ProtectedSlot = Protected | SlotBit,
PrivateSlot = Private | SlotBit,
};
public:
InsertionPointLocator(const Document::Ptr &doc);
InsertionLocation methodDeclarationInClass(const Class *clazz,
AccessSpec xsSpec) const;
private:
Document::Ptr m_doc;
};
} // namespace CPlusPlus
#endif // INSERTIONPOINTLOCATOR_H
......@@ -48,7 +48,8 @@ HEADERS += \
$$PWD/pp-cctype.h \
$$PWD/pp-engine.h \
$$PWD/pp-macro-expander.h \
$$PWD/pp-scanner.h
$$PWD/pp-scanner.h \
$$PWD/InsertionPointLocator.h
SOURCES += \
$$PWD/SimpleLexer.cpp \
......@@ -72,6 +73,7 @@ SOURCES += \
$$PWD/Macro.cpp \
$$PWD/pp-engine.cpp \
$$PWD/pp-macro-expander.cpp \
$$PWD/pp-scanner.cpp
$$PWD/pp-scanner.cpp \
$$PWD/InsertionPointLocator.cpp
RESOURCES += $$PWD/cplusplus.qrc
......@@ -39,6 +39,7 @@
#include <Symbols.h>
#include <TranslationUnit.h>
#include <cplusplus/ASTPath.h>
#include <cplusplus/InsertionPointLocator.h>
#include <cplusplus/LookupContext.h>
#include <cplusplus/Overview.h>
......@@ -53,84 +54,6 @@ using CppEditor::CppRefactoringChanges;
namespace {
class InsertionPointFinder: public ASTVisitor
{
public:
InsertionPointFinder(Document::Ptr doc, const QString &className)
: ASTVisitor(doc->translationUnit())
, _doc(doc)
, _className(className)
{}
void operator()(int *line, int *column)
{
if (!line && !column)
return;
_line = 0;
_column = 0;
AST *ast = translationUnit()->ast();
accept(ast);
if (line)
*line = _line - 1;
if (column)
*column = _column - 1;
}
protected:
using ASTVisitor::visit;
bool visit(ClassSpecifierAST *ast)
{
if (!ast->symbol || _className != QLatin1String(ast->symbol->identifier()->chars()))
return true;
unsigned currentVisibility = (tokenKind(ast->classkey_token) == T_CLASS) ? T_PUBLIC : T_PRIVATE;
unsigned insertBefore = 0;
for (DeclarationListAST *iter = ast->member_specifier_list; iter; iter = iter->next) {
DeclarationAST *decl = iter->value;
if (AccessDeclarationAST *xsDecl = decl->asAccessDeclaration()) {
const unsigned token = xsDecl->access_specifier_token;
const int kind = tokenKind(token);
if (kind == T_PUBLIC) {
currentVisibility = T_PUBLIC;
} else if (kind == T_PROTECTED) {
if (currentVisibility == T_PUBLIC) {
insertBefore = token;
break;
} else {
currentVisibility = T_PROTECTED;
}
} else if (kind == T_PRIVATE) {
if (currentVisibility == T_PUBLIC
|| currentVisibility == T_PROTECTED) {
insertBefore = token;
break;
} else {
currentVisibility = T_PRIVATE;
}
}
}
}
if (!insertBefore)
insertBefore = ast->rbrace_token;
getTokenStartPosition(insertBefore, &_line, &_column);
return false;
}
private:
Document::Ptr _doc;
QString _className;
unsigned _line;
unsigned _column;
};
QString prettyMinimalType(const FullySpecifiedType &ty,
const LookupContext &context,
Scope *source,
......@@ -151,11 +74,11 @@ class Operation: public CppQuickFixOperation
{
public:
Operation(const CppQuickFixState &state, int priority,
const QString &targetFileName, const QString &targetSymbolName,
const QString &targetFileName, const Class *targetSymbol,
const QString &decl)
: CppQuickFixOperation(state, priority)
, m_targetFileName(targetFileName)
, m_targetSymbolName(targetSymbolName)
, m_targetSymbol(targetSymbol)
, m_decl(decl)
{
setDescription(QCoreApplication::tr("Create Declaration from Definition",
......@@ -167,26 +90,25 @@ public:
CppRefactoringChanges *changes = refactoringChanges();
Document::Ptr targetDoc = changes->document(m_targetFileName);
InsertionPointFinder findInsertionPoint(targetDoc, m_targetSymbolName);
int line = 0, column = 0;
findInsertionPoint(&line, &column);
InsertionPointLocator locator(targetDoc);
const InsertionLocation loc = locator.methodDeclarationInClass(m_targetSymbol, InsertionPointLocator::Public);
int targetPosition1 = changes->positionInFile(m_targetFileName, line, column);
int targetPosition2 = changes->positionInFile(m_targetFileName, line + 1, 0) - 1;
int targetPosition1 = changes->positionInFile(m_targetFileName, loc.line() - 1, loc.column() - 1);
int targetPosition2 = changes->positionInFile(m_targetFileName, loc.line(), 0) - 1;
Utils::ChangeSet target;
target.insert(targetPosition1, m_decl);
target.insert(targetPosition1, loc.prefix() + m_decl);
changes->changeFile(m_targetFileName, target);
changes->reindent(m_targetFileName,
Utils::ChangeSet::Range(targetPosition1, targetPosition2));
changes->openEditor(m_targetFileName, line, column);
changes->openEditor(m_targetFileName, loc.line() - 1, loc.column() - 1);
}
private:
QString m_targetFileName;
QString m_targetSymbolName;
const Class *m_targetSymbol;
QString m_decl;
};
......@@ -201,7 +123,7 @@ QList<CppQuickFixOperation::Ptr> DeclFromDef::match(const CppQuickFixState &stat
for (; idx < path.size(); ++idx) {
AST *node = path.at(idx);
if (FunctionDefinitionAST *candidate = node->asFunctionDefinition()) {
if (!funDef)
if (!funDef && state.isCursorOn(candidate) && !state.isCursorOn(candidate->function_body))
funDef = candidate;
} else if (node->asClassSpecifier()) {
return noResult();
......@@ -218,7 +140,7 @@ QList<CppQuickFixOperation::Ptr> DeclFromDef::match(const CppQuickFixState &stat
if (Class *clazz = s->asClass()) {
return singleResult(new Operation(state, idx,
QLatin1String(clazz->fileName()),
QLatin1String(clazz->identifier()->chars()),
clazz,
generateDeclaration(state,
method,
targetBinding)));
......
......@@ -81,7 +81,7 @@ SemanticInfo CppQuickFixState::semanticInfo() const
return _semanticInfo;
}
LookupContext CppQuickFixState::context() const
const LookupContext &CppQuickFixState::context() const
{
return _context;
}
......
......@@ -68,7 +68,7 @@ public:
CPlusPlus::Snapshot snapshot() const;
CPlusPlus::Document::Ptr document() const;
CppEditor::Internal::SemanticInfo semanticInfo() const;
CPlusPlus::LookupContext context() const;
const CPlusPlus::LookupContext &context() const;
using TextEditor::QuickFixState::range;
using TextEditor::QuickFixState::textOf;
......
......@@ -1726,8 +1726,5 @@ void CppQuickFixCollector::registerQuickFixes(ExtensionSystem::IPlugin *plugIn)
plugIn->addAutoReleasedObject(new FixForwardDeclarationOp);
plugIn->addAutoReleasedObject(new AddLocalDeclarationOp);
plugIn->addAutoReleasedObject(new ToCamelCaseConverter);
#if NOT_YET
plugIn->addAutoReleasedObject(new Internal::DeclFromDef);
#endif
}
......@@ -159,7 +159,7 @@ QStringList RefactoringChanges::apply()
BaseTextEditor *editor = editorForFile(m_fileNameToShow);
editorManager->activateEditor(editor->editableInterface());
if (m_lineToShow != -1)
editor->gotoLine(m_lineToShow + 1, m_columnToShow + 1);
editor->gotoLine(m_lineToShow + 1, m_columnToShow);
}
return changed.toList();
......@@ -205,6 +205,11 @@ BaseTextEditor *RefactoringChanges::editorForNewFile(const QString &fileName)
return editorForFile(fileName, true);
}
/**
* \param fileName the file to open
* \param line the line to focus on, 0-based
* \param column the column to focus on, 0-based
*/
void RefactoringChanges::openEditor(const QString &fileName, int line, int column)
{
m_fileNameToShow = fileName;
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment