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 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 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 412 413 414 415 416 417 418 419 420 421
|
/*
* This file is part of KDevelop
* Copyright 2014 David Stevens <dgedstevens@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License or (at your option) version 3 or any later version
* accepted by the membership of KDE e.V. (or its successor approved
* by the membership of KDE e.V.), which shall act as a proxy
* defined in Section 14 of version 3 of the license.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "completionhelper.h"
#include "../duchain/cursorkindtraits.h"
#include "../duchain/parsesession.h"
#include "../duchain/documentfinderhelpers.h"
#include "../duchain/clanghelpers.h"
#include "../util/clangdebug.h"
#include "../util/clangtypes.h"
#include "../util/clangutils.h"
#include <language/duchain/stringhelpers.h>
#include <clang-c/Index.h>
#include <algorithm>
using namespace KDevelop;
namespace {
struct OverrideInfo
{
FunctionOverrideList* functions;
QStringList templateTypes;
QMap<QString, QString> templateTypeMap;
};
struct ImplementsInfo
{
CXCursor origin;
CXCursor top;
FunctionImplementsList* prototypes;
QVector<CXCursor> originScope;
QVector<CXFile> fileFilter;
int depth;
QString templatePrefix;
};
QStringList templateParams(CXCursor cursor);
CXChildVisitResult templateParamsHelper(CXCursor cursor, CXCursor /*parent*/, CXClientData data)
{
CXCursorKind kind = clang_getCursorKind(cursor);
auto& params = *static_cast<QStringList*>(data);
if (kind == CXCursor_TemplateTypeParameter) {
auto paramName = ClangString(clang_getCursorSpelling(cursor)).toString();
auto param = QStringLiteral("typename");
if (!paramName.isEmpty()) {
param += QLatin1Char(' ') + paramName;
}
params.append(param);
} else if (kind == CXCursor_NonTypeTemplateParameter) {
auto param = ClangString(clang_getTypeSpelling(clang_getCursorType(cursor))).toString();
auto paramName = ClangString(clang_getCursorSpelling(cursor)).toString();
if (!paramName.isEmpty()) {
param += QLatin1Char(' ') + paramName;
}
params.append(param);
} else if (kind == CXCursor_TemplateTemplateParameter) {
auto paramName = ClangString(clang_getCursorSpelling(cursor)).toString();
auto templateTypes = templateParams(cursor);
QString param = QLatin1String("template<") + templateTypes.join(QLatin1String(", ")) + QLatin1String("> class ") + paramName ;
params.append(param);
}
return CXChildVisit_Continue;
}
QStringList templateParams(CXCursor cursor)
{
QStringList types;
clang_visitChildren(cursor, templateParamsHelper, &types);
return types;
}
FuncOverrideInfo processCXXMethod(CXCursor cursor, OverrideInfo* info)
{
FuncParameterList params;
int numArgs = clang_Cursor_getNumArguments(cursor);
params.reserve(numArgs);
for (int i = 0; i < numArgs; i++) {
CXCursor arg = clang_Cursor_getArgument(cursor, i);
QString id = ClangString(clang_getCursorDisplayName(arg)).toString();
QString type = ClangString(clang_getTypeSpelling(clang_getCursorType(arg))).toString();
const auto templateTypeIt = info->templateTypeMap.constFind(type);
if (templateTypeIt != info->templateTypeMap.constEnd()) {
type = *templateTypeIt;
}
FuncParameterInfo param;
param.type = type;
param.id = id;
params << param;
}
FuncOverrideInfo fp;
QString retType = ClangString(clang_getTypeSpelling(clang_getCursorResultType(cursor))).toString();
const auto templateTypeIt = info->templateTypeMap.constFind(retType);
if (templateTypeIt != info->templateTypeMap.constEnd()) {
retType = *templateTypeIt;
}
fp.returnType = retType;
fp.name = ClangString(clang_getCursorSpelling(cursor)).toString();
fp.params = params;
fp.isPureVirtual = clang_CXXMethod_isPureVirtual(cursor);
fp.isConst = clang_CXXMethod_isConst(cursor);
return fp;
}
CXChildVisitResult baseClassVisitor(CXCursor cursor, CXCursor /*parent*/, CXClientData data);
void processBaseClass(CXCursor cursor, CXCursor parent, FunctionOverrideList* functionList)
{
QStringList concrete;
CXCursor ref = clang_getCursorReferenced(cursor);
if (clang_equalCursors(ref, parent)) {
return;
}
CXCursor isTemplate = clang_getSpecializedCursorTemplate(ref);
if (!clang_Cursor_isNull(isTemplate)) {
concrete = ClangUtils::templateArgumentTypes(ref);
ref = isTemplate;
}
OverrideInfo info{functionList, concrete, {}};
clang_visitChildren(ref, baseClassVisitor, &info);
}
CXChildVisitResult baseClassVisitor(CXCursor cursor, CXCursor parent, CXClientData data)
{
QString templateParam;
auto* info = static_cast<OverrideInfo*>(data);
switch(clang_getCursorKind(cursor)) {
case CXCursor_TemplateTypeParameter:
templateParam = ClangString(clang_getCursorSpelling(cursor)).toString();
// TODO: this is probably just a hotfix, find a proper solution to
// https://bugs.kde.org/show_bug.cgi?id=355163
if (info->templateTypes.size() > info->templateTypeMap.size()) {
info->templateTypeMap.insert(templateParam, info->templateTypes.at(info->templateTypeMap.size()));
}
return CXChildVisit_Continue;
case CXCursor_CXXBaseSpecifier:
processBaseClass(cursor, parent, info->functions);
return CXChildVisit_Continue;
case CXCursor_CXXMethod:
if (clang_CXXMethod_isVirtual(cursor)) {
auto methodInfo = processCXXMethod(cursor, info);
const int methodIndex = info->functions->indexOf(methodInfo);
if (methodIndex == -1) {
info->functions->append(methodInfo);
} else {
// update to subclass override
auto& listedMethodInfo = (*info->functions)[methodIndex];
listedMethodInfo.isPureVirtual = methodInfo.isPureVirtual;
}
}
return CXChildVisit_Continue;
default:
return CXChildVisit_Continue;
}
}
CXChildVisitResult findBaseVisitor(CXCursor cursor, CXCursor parent, CXClientData data)
{
auto cursorKind = clang_getCursorKind(cursor);
if (cursorKind == CXCursor_CXXBaseSpecifier) {
processBaseClass(cursor, parent, static_cast<FunctionOverrideList*>(data));
} else if (cursorKind == CXCursor_CXXMethod) {
if (!clang_CXXMethod_isVirtual(cursor)) {
return CXChildVisit_Continue;
}
auto info = static_cast<FunctionOverrideList*>(data);
OverrideInfo overrideInfo {info, {}, {}};
auto methodInfo = processCXXMethod(cursor, &overrideInfo);
// If this method is already implemented, remove it from the list of methods that can be overridden.
// If not implemented, this is a noop
info->removeOne(methodInfo);
}
return CXChildVisit_Continue;
}
// TODO: make sure we only skip this in classes that actually inherit QObject
bool isQtMocFunction(CXCursor cursor)
{
static const QByteArray mocFunctions[] = {
QByteArrayLiteral("metaObject"),
QByteArrayLiteral("qt_metacast"),
QByteArrayLiteral("qt_metacall"),
QByteArrayLiteral("qt_static_metacall"),
QByteArrayLiteral("qt_check_for_QGADGET_macro")
};
const ClangString function(clang_getCursorSpelling(cursor));
auto it = std::find(std::begin(mocFunctions), std::end(mocFunctions), function.toByteArray());
if (it != std::end(mocFunctions)) {
auto range = ClangRange(clang_getCursorExtent(cursor)).toRange();
// tokenizing the above range fails for some reason, but
// if the function comes from a range that happens to be just as wide
// as the expected Q_OBJECT macro, then we assume this is a moc function
// and skip it.
return range.onSingleLine() && range.columnWidth() == strlen("Q_OBJECT");
}
return false;
}
CXChildVisitResult declVisitor(CXCursor cursor, CXCursor parent, CXClientData d)
{
CXCursorKind kind = clang_getCursorKind(cursor);
auto* data = static_cast<struct ImplementsInfo*>(d);
auto location = clang_getCursorLocation(cursor);
if (clang_Location_isInSystemHeader(location)) {
// never offer implementation items for system headers
// TODO: also filter out non-system files unrelated to the current file
// e.g. based on the path or similar
return CXChildVisit_Continue;
}
CXFile file = nullptr;
clang_getFileLocation(location, &file, nullptr, nullptr, nullptr);
if (!data->fileFilter.contains(file)) {
return CXChildVisit_Continue;
}
//Recurse into cursors which could contain a function declaration
if (ClangUtils::isScopeKind(kind)) {
//Don't enter a scope that branches from the origin's scope
if (data->depth < data->originScope.count() &&
!clang_equalCursors(cursor, data->originScope.at(data->depth))) {
return CXChildVisit_Continue;
}
// we must not declare a function outside of its anonymous namespace, so
// don't recurse into anonymous namespaces if we are not in one already
if (kind == CXCursor_Namespace && !clang_equalCursors(data->origin, cursor) && ClangString(clang_getCursorDisplayName(cursor)).isEmpty()) {
return CXChildVisit_Continue;
}
QString templatePrefix;
if (data->depth >= data->originScope.count()) {
if (kind == CXCursor_ClassTemplate || kind == CXCursor_ClassTemplatePartialSpecialization) {
//If we're at a template, we need to construct the template<typename T1, typename T2>
//which goes at the front of the prototype
const QStringList templateTypes = templateParams(kind == CXCursor_ClassTemplate ? cursor : clang_getSpecializedCursorTemplate(cursor));
templatePrefix = QLatin1String("template<") + templateTypes.join(QLatin1String(", ")) + QLatin1String("> ");
}
}
ImplementsInfo info{data->origin, data->top, data->prototypes, data->originScope,
data->fileFilter,
data->depth + 1,
data->templatePrefix + templatePrefix};
clang_visitChildren(cursor, declVisitor, &info);
return CXChildVisit_Continue;
}
if (data->depth < data->originScope.count()) {
return CXChildVisit_Continue;
}
//If the current cursor is not a function or if it is already defined, there's nothing to do here
if (!CursorKindTraits::isFunction(clang_getCursorKind(cursor)) ||
!clang_equalCursors(clang_getNullCursor(), clang_getCursorDefinition(cursor)))
{
return CXChildVisit_Continue;
}
// don't try to implement pure virtual functions
if (clang_CXXMethod_isPureVirtual(cursor)) {
return CXChildVisit_Continue;
}
CXCursor origin = data->origin;
//Don't try to redefine class/structure/union members
if (clang_equalCursors(origin, parent) && (clang_getCursorKind(origin) != CXCursor_Namespace
&& !clang_equalCursors(origin, data->top))) {
return CXChildVisit_Continue;
}
// skip explicitly defaulted/deleted functions as they don't need a definition
if (ClangUtils::isExplicitlyDefaultedOrDeleted(cursor)) {
return CXChildVisit_Continue;
}
if (isQtMocFunction(cursor) || ClangUtils::specialAttributes(cursor) & FunctionSignalFlag) {
return CXChildVisit_Continue;
}
QString templatePrefix;
if (kind == CXCursor_FunctionTemplate) {
const QStringList templateTypes = templateParams(cursor);
templatePrefix = QLatin1String("template<") + templateTypes.join(QLatin1String(", ")) + QLatin1String("> ");
}
const auto scope = ClangUtils::getScope(cursor, data->origin);
QString signature = ClangUtils::getCursorSignature(cursor, scope);
QString returnType, rest;
if (kind != CXCursor_Constructor && kind != CXCursor_Destructor) {
int spaceIndex = signature.indexOf(QLatin1Char(' '));
returnType = signature.left(spaceIndex);
rest = signature.mid(spaceIndex + 1);
} else {
rest = signature;
}
//TODO Add support for pure virtual functions
ReferencedTopDUContext top;
{
DUChainReadLocker lock;
top = DUChain::self()->chainForDocument(ClangString(clang_getFileName(file)).toIndexed());
}
DeclarationPointer declaration = ClangHelpers::findDeclaration(clang_getCursorLocation(cursor), QualifiedIdentifier(), top);
data->prototypes->append(FuncImplementInfo{kind == CXCursor_Constructor, kind == CXCursor_Destructor,
data->templatePrefix + templatePrefix, returnType, rest, declaration});
return CXChildVisit_Continue;
}
}
bool FuncOverrideInfo::operator==(const FuncOverrideInfo& rhs) const
{
return std::make_tuple(returnType, name, params, isConst)
== std::make_tuple(rhs.returnType, rhs.name, rhs.params, rhs.isConst);
}
CompletionHelper::CompletionHelper()
{
}
void CompletionHelper::computeCompletions(const ParseSession& session, CXFile file, const KTextEditor::Cursor& position)
{
const auto unit = session.unit();
CXSourceLocation location = clang_getLocation(unit, file, position.line() + 1, position.column() + 1);
if (clang_equalLocations(clang_getNullLocation(), location)) {
clangDebug() << "Completion helper given invalid position " << position
<< " in file " << clang_getFileName(file);
return;
}
CXCursor topCursor = clang_getTranslationUnitCursor(unit);
CXCursor currentCursor = clang_getCursor(unit, location);
if (clang_getCursorKind(currentCursor) == CXCursor_NoDeclFound) {
currentCursor = topCursor;
} else if (KTextEditor::Cursor(ClangLocation(clang_getCursorLocation(currentCursor))) >= ClangLocation(location)) {
currentCursor = clang_getCursorLexicalParent(currentCursor);
}
clang_visitChildren(currentCursor, findBaseVisitor, &m_overrides);
if (clang_getCursorKind(currentCursor) == CXCursor_Namespace ||
clang_equalCursors(topCursor, currentCursor)) {
QVector<CXCursor> scopes;
if (!clang_equalCursors(topCursor, currentCursor)) {
CXCursor search = currentCursor;
while (!clang_equalCursors(search, topCursor)) {
scopes.append(clang_getCanonicalCursor(search));
search = clang_getCursorSemanticParent(search);
}
std::reverse(scopes.begin(), scopes.end());
}
QVector<CXFile> fileFilter;
fileFilter << file;
const auto url = QUrl::fromLocalFile(ClangString(clang_getFileName(file)).toString()).adjusted(QUrl::NormalizePathSegments);
const auto& buddies = DocumentFinderHelpers::potentialBuddies(url);
for (const auto& buddy : buddies) {
auto buddyFile = clang_getFile(unit, qPrintable(buddy.toLocalFile()));
if (buddyFile) {
fileFilter << buddyFile;
}
}
ImplementsInfo info{currentCursor, topCursor, &m_implements, scopes, fileFilter, 0, QString()};
clang_visitChildren(topCursor, declVisitor, &info);
}
}
FunctionOverrideList CompletionHelper::overrides() const
{
return m_overrides;
}
FunctionImplementsList CompletionHelper::implements() const
{
return m_implements;
}
|