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
|
/*
* KDevelop C++ Language Support
*
* Copyright 2008 Hamish Rodda <rodda@kde.org>
* Copyright 2012 Miha Čančula <miha@noughmad.eu>
* Copyright 2017 Friedrich W. H. Kossebau <kossebau@kde.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* 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, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "clangclasshelper.h"
#include "util/clangdebug.h"
#include "duchain/unknowndeclarationproblem.h"
#include <interfaces/iprojectcontroller.h>
#include <language/duchain/duchain.h>
#include <language/duchain/duchainlock.h>
#include <language/duchain/topducontext.h>
#include <language/duchain/declaration.h>
#include <language/codegen/documentchangeset.h>
#include <language/codegen/codedescription.h>
#include <custom-definesandincludes/idefinesandincludesmanager.h>
#include <project/projectmodel.h>
#include <util/path.h>
#include <QTemporaryFile>
#include <QDir>
using namespace KDevelop;
ClangClassHelper::ClangClassHelper()
{
}
ClangClassHelper::~ClangClassHelper() = default;
TemplateClassGenerator* ClangClassHelper::createGenerator(const QUrl& baseUrl)
{
return new ClangTemplateNewClass(baseUrl);
}
QList<DeclarationPointer> ClangClassHelper::defaultMethods(const QString& name) const
{
// TODO: this is the oldcpp approach, perhaps clang provides this directly?
// TODO: default destructor misses info about virtualness, possible needs ICreateClassHelper change?
QTemporaryFile file(QDir::tempPath() + QLatin1String("/class_") + name + QLatin1String("_XXXXXX.cpp"));
file.open();
QTextStream stream(&file);
stream << "class " << name << " {\n"
<< " public:\n"
// default ctor
<< " " << name << "();\n"
// copy ctor
<< " " << name << "(const " << name << "& other);\n"
// default dtor
<< " ~" << name << "();\n"
// assignment operator
<< " " << name << "& operator=(const " << name << "& other);\n"
// equality operators
<< " bool operator==(const " << name << "& other) const;\n"
<< " bool operator!=(const " << name << "& other) const;\n"
<< "};\n";
file.close();
ReferencedTopDUContext context(DUChain::self()->waitForUpdate(IndexedString(file.fileName()),
TopDUContext::AllDeclarationsAndContexts));
QList<DeclarationPointer> methods;
{
DUChainReadLocker lock;
if (context && context->childContexts().size() == 1) {
const auto localDeclarations = context->childContexts().first()->localDeclarations();
methods.reserve(localDeclarations.size());
for (auto* declaration : localDeclarations) {
methods << DeclarationPointer(declaration);
}
}
}
return methods;
}
ClangTemplateNewClass::ClangTemplateNewClass(const QUrl& url)
: TemplateClassGenerator(url)
{
}
ClangTemplateNewClass::~ClangTemplateNewClass() = default;
namespace {
QString includeArgumentForFile(const QString& includefile, const Path::List& includePaths,
const Path& source)
{
const auto sourceFolder = source.parent();
const Path canonicalFile(QFileInfo(includefile).canonicalFilePath());
QString shortestDirective;
bool isRelative = false;
// we can include the file directly
if (sourceFolder == canonicalFile.parent()) {
shortestDirective = canonicalFile.lastPathSegment();
isRelative = true;
} else {
// find the include directive with the shortest length
for (const auto& includePath : includePaths) {
QString relative = includePath.relativePath(canonicalFile);
if (relative.startsWith(QLatin1String("./"))) {
relative.remove(0, 2);
}
if (shortestDirective.isEmpty() || relative.length() < shortestDirective.length()) {
shortestDirective = relative;
isRelative = (includePath == sourceFolder);
}
}
}
// Item not found in include path?
if (shortestDirective.isEmpty()) {
return {};
}
if (isRelative) {
return QLatin1Char('\"') + shortestDirective + QLatin1Char('\"');
}
return QLatin1Char('<') + shortestDirective + QLatin1Char('>');
}
QString includeDirectiveArgumentFromPath(const Path& file,
const DeclarationPointer& declaration)
{
const auto includeManager = IDefinesAndIncludesManager::manager();
const auto filePath = file.toLocalFile();
const auto projectModel = ICore::self()->projectController()->projectModel();
auto item = projectModel->itemForPath(IndexedString(filePath));
if (!item) {
// try the folder where the file is placed and guess includes from there
// prefer target over file
const auto folderPath = IndexedString(file.parent().toLocalFile());
clangDebug() << "File not known, guessing includes from items in folder:" << folderPath.str();
// default to the folder, if no targets or files
item = projectModel->itemForPath(folderPath);
if (item) {
const auto targetItems = item->targetList();
bool itemChosen = false;
// Prefer items defined inside a target with non-empty includes.
for (const auto& targetItem : targetItems) {
item = targetItem;
if (!includeManager->includes(targetItem, IDefinesAndIncludesManager::ProjectSpecific).isEmpty()) {
clangDebug() << "Guessing includes from target" << targetItem->baseName();
itemChosen = true;
break;
}
}
if (!itemChosen) {
const auto fileItems = item->fileList();
// Prefer items defined inside a target with non-empty includes.
for (const auto& fileItem : fileItems) {
item = fileItem;
if (!includeManager->includes(fileItem, IDefinesAndIncludesManager::ProjectSpecific).isEmpty()) {
clangDebug() << "Guessing includes from file" << fileItem->baseName();
break;
}
}
}
}
}
const auto includePaths = includeManager->includes(item);
if (includePaths.isEmpty()) {
clangDebug() << "Include path is empty";
return {};
}
clangDebug() << "found include paths for" << file << ":" << includePaths;
const auto includeFiles = UnknownDeclarationProblem::findMatchingIncludeFiles(QVector<Declaration*> {declaration.data()});
if (includeFiles.isEmpty()) {
// return early as the computation of the include paths is quite expensive
return {};
}
// create include arguments for all candidates
QStringList includeArguments;
includeArguments.reserve(includeFiles.size());
for (const auto& includeFile : includeFiles) {
const auto includeArgument = includeArgumentForFile(includeFile, includePaths, file);
if (includeArgument.isEmpty()) {
clangDebug() << "unable to create include argument for" << includeFile << "in" << file.toLocalFile();
}
includeArguments << includeArgument;
}
if (includeArguments.isEmpty()) {
return {};
}
std::sort(includeArguments.begin(), includeArguments.end(),
[](const QString& lhs, const QString& rhs) {
return lhs.length() < rhs.length();
});
return includeArguments.at(0);
}
template<typename Map>
void addVariables(QVariantHash* variables, QLatin1String suffix, const Map& map)
{
for (auto it = map.begin(), end = map.end(); it != end; ++it) {
variables->insert(it.key() + suffix, CodeDescription::toVariantList(it.value()));
}
}
}
QVariantHash ClangTemplateNewClass::extraVariables() const
{
QVariantHash variables;
const QString publicAccess = QStringLiteral("public");
QHash<QString, VariableDescriptionList> variableDescriptions;
QHash<QString, FunctionDescriptionList> functionDescriptions;
QHash<QString, FunctionDescriptionList> slotDescriptions;
FunctionDescriptionList signalDescriptions;
const auto desc = description();
for (const auto& function : desc.methods) {
const QString& access = function.access.isEmpty() ? publicAccess : function.access;
if (function.isSignal) {
signalDescriptions << function;
} else if (function.isSlot) {
slotDescriptions[access] << function;
} else {
functionDescriptions[access] << function;
}
}
for (const auto& variable : desc.members) {
const QString& access = variable.access.isEmpty() ? publicAccess : variable.access;
variableDescriptions[access] << variable;
}
::addVariables(&variables, QLatin1String("_members"), variableDescriptions);
::addVariables(&variables, QLatin1String("_functions"), functionDescriptions);
::addVariables(&variables, QLatin1String("_slots"), slotDescriptions);
variables[QStringLiteral("signals")] = CodeDescription::toVariantList(signalDescriptions);
variables[QStringLiteral("needs_qobject_macro")] = !slotDescriptions.isEmpty() || !signalDescriptions.isEmpty();
QStringList includedFiles;
DUChainReadLocker locker(DUChain::lock());
QUrl sourceUrl;
const auto urls = fileUrls();
if (!urls.isEmpty()) {
sourceUrl = urls.constBegin().value();
} else {
// includeDirectiveArgumentFromPath() expects a path to the folder where includes are used from
sourceUrl = baseUrl();
sourceUrl.setPath(sourceUrl.path() + QLatin1String("/.h"));
}
const Path sourcePath(sourceUrl);
const auto& directBaseClasses = this->directBaseClasses();
for (const auto& baseClass : directBaseClasses) {
if (!baseClass) {
continue;
}
clangDebug() << "Looking for includes for class" << baseClass->identifier().toString();
const QString includeDirective = includeDirectiveArgumentFromPath(sourcePath, baseClass);
if (!includeDirective.isEmpty()) {
includedFiles << includeDirective;
}
}
variables[QStringLiteral("included_files")] = includedFiles;
return variables;
}
DocumentChangeSet ClangTemplateNewClass::generate()
{
addVariables(extraVariables());
return TemplateClassGenerator::generate();
}
|