File: implementationhelperitem.cpp

package info (click to toggle)
kdevelop 4%3A4.7.0-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 18,360 kB
  • ctags: 11,484
  • sloc: cpp: 105,371; python: 522; ansic: 488; lex: 422; sh: 139; ruby: 120; makefile: 51; xml: 42; php: 12
file content (472 lines) | stat: -rw-r--r-- 19,528 bytes parent folder | download
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
/*
   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License version 2 as published by the Free Software Foundation.

   This library 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
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/

#include "implementationhelperitem.h"
#include <ktexteditor/document.h>
#include <klocalizedstring.h>
#include <language/duchain/duchainutils.h>
#include "context.h"
#include "helpers.h"
#include <language/duchain/types/functiontype.h>
#include <language/duchain/classfunctiondeclaration.h>
#include <qtfunctiondeclaration.h>
#include <cppduchain.h>
#include <sourcemanipulation.h>
#include <language/codegen/coderepresentation.h>
#include <language/codegen/documentchangeset.h>
#include <language/backgroundparser/backgroundparser.h>
#include <interfaces/icore.h>
#include <interfaces/ilanguagecontroller.h>

namespace Cpp {

ImplementationHelperItem::ImplementationHelperItem(HelperType type, KDevelop::DeclarationPointer decl, KSharedPtr<Cpp::CodeCompletionContext> context, int _inheritanceDepth, int _listOffset) : NormalDeclarationCompletionItem(decl, KSharedPtr<KDevelop::CodeCompletionContext>::staticCast(context), _inheritanceDepth, _listOffset), m_type(type) {
}

#define RETURN_CACHED_ICON(name) {static QIcon icon(KIcon(name).pixmap(QSize(16, 16))); return icon;}

QString ImplementationHelperItem::getOverrideName(const KDevelop::QualifiedIdentifier& forcedParentIdentifier) const {
  QString ret;
  if(m_declaration) {
    ret = m_declaration->identifier().toString();

    KDevelop::ClassFunctionDeclaration* classDecl = dynamic_cast<KDevelop::ClassFunctionDeclaration*>(declaration().data());
    if(classDecl) {
      if(classDecl->isConstructor() || classDecl->isDestructor()) {
        if (forcedParentIdentifier.isEmpty() && completionContext() && completionContext()->duContext()) {
          ret = completionContext()->duContext()->localScopeIdentifier().toString();
        } else {
          ret = forcedParentIdentifier.last().toString();
        }
      }
      if(classDecl->isDestructor())
        ret = "~" + ret;
    }
  }
  return ret;
}

QVariant ImplementationHelperItem::data(const QModelIndex& index, int role, const KDevelop::CodeCompletionModel* model) const {
  QVariant ret = NormalDeclarationCompletionItem::data(index, role, model);
  if(role == Qt::DecorationRole) {
    if(index.column() == KTextEditor::CodeCompletionModel::Icon) {
      switch(m_type) {
        case Override: {
          KDevelop::DUChainReadLocker lock(KDevelop::DUChain::lock());
          KDevelop::ClassFunctionDeclaration* classFunction = dynamic_cast<ClassFunctionDeclaration*>(m_declaration.data());
          if(classFunction && classFunction->isAbstract())
            RETURN_CACHED_ICON("flag-red");

          RETURN_CACHED_ICON("CTparents");
        }
        case CreateDefinition:
          RETURN_CACHED_ICON("CTsuppliers"); ///@todo Better icon?
        case CreateSignalSlot:
          RETURN_CACHED_ICON("dialog-ok-apply"); ///@todo Better icon?
      }
    }
  }
  if(role == Qt::DisplayRole) {
    if(index.column() == KTextEditor::CodeCompletionModel::Prefix) {
      QString prefix;
      if(m_type == Override)
        prefix = i18nc("@action C++ code completion", "Override");
      if(m_type == CreateDefinition)
        prefix = i18nc("@action C++ code completion", "Implement");
      if(m_type == CreateSignalSlot)
        return i18nc("@action C++ code completion", "Create Slot");

      ret = QString(prefix + " " + ret.toString());
    }

    if(index.column() == KTextEditor::CodeCompletionModel::Name) {
      KDevelop::DUChainReadLocker lock(KDevelop::DUChain::lock());
      if(m_type == CreateSignalSlot) {
        ret = completionContext()->followingText();
        Cpp::QtFunctionDeclaration* cDecl = dynamic_cast<Cpp::QtFunctionDeclaration*>(m_declaration.data());

        if(cDecl && ret.toString().isEmpty())
          ret = cDecl->identifier().toString();

        return ret;
      }else if(m_type == Override) {
        ret = getOverrideName();
      }
      if(declaration().data() && m_type != Override) {
        QualifiedIdentifier parentScope = declaration()->context()->scopeIdentifier(true);
        parentScope = Cpp::stripPrefixes(m_completionContext->duContext(), parentScope);
        if(!parentScope.isEmpty())
          ret = QString(parentScope.toString() + "::" + ret.toString());
      }
    }
    if(index.column() == KTextEditor::CodeCompletionModel::Arguments) {
      KDevelop::DUChainReadLocker lock(KDevelop::DUChain::lock());
      KDevelop::ClassFunctionDeclaration* classFunction = dynamic_cast<ClassFunctionDeclaration*>(m_declaration.data());
      if(classFunction && classFunction->isAbstract())
        ret = QString(ret.toString() + " = 0");
    }
  }

  if(role == KTextEditor::CodeCompletionModel::ItemSelected) {
    KDevelop::DUChainReadLocker lock(KDevelop::DUChain::lock());
    if(declaration().data() && m_type == Override) {
      QualifiedIdentifier parentScope = declaration()->context()->scopeIdentifier(true);
      return i18n("From %1", parentScope.toString());
    }
  }

  if(role == KTextEditor::CodeCompletionModel::InheritanceDepth)
    return QVariant(0);
  return ret;
}

QString ImplementationHelperItem::signaturePart(bool includeDefaultParams) {
  KDevelop::DUChainReadLocker lock(KDevelop::DUChain::lock());
  QString ret;
  createArgumentList(*this, ret, 0, includeDefaultParams, true);
  if(m_declaration->abstractType() && m_declaration->abstractType()->modifiers() & AbstractType::ConstModifier)
    ret += " const";
  return ret;
}

QString ImplementationHelperItem::insertionText(KUrl url, KDevelop::SimpleCursor position, QualifiedIdentifier forceParentScope) {
  KDevelop::DUChainReadLocker lock(KDevelop::DUChain::lock());
  QString newText;
  if(!m_declaration)
    return QString();

  DUContext* duContext = 0;
  if(completionContext())
    duContext = completionContext()->duContext(); ///@todo Take the DUContext from somewhere lese

  KDevelop::ClassFunctionDeclaration* classFunction = dynamic_cast<ClassFunctionDeclaration*>(m_declaration.data());

  ///@todo Move these functionalities into sourcemanipulation.cpp
  if(m_type == Override) {
    if(!useAlternativeText) {

      if(!classFunction || !classFunction->isConstructor())
        newText = "virtual ";
      else if(classFunction && classFunction->isConstructor() && classFunction->isExplicit())
        newText = "explicit ";

      if(m_declaration) {
        FunctionType::Ptr asFunction = m_declaration->type<FunctionType>();
        if(asFunction && asFunction->returnType())
            newText += Cpp::simplifiedTypeString(asFunction->returnType(), duContext) + " ";

        newText += getOverrideName(forceParentScope);

        newText += signaturePart(true);
        newText += ";";
      } else {
        kDebug() << "Declaration disappeared";
        return QString();
      }
    }else{
      newText = alternativeText;
    }
  }else if(m_type == CreateDefinition) {
      TopDUContext* topContext = DUChainUtils::standardContextForUrl(url);
      if(topContext) {
        duContext = topContext->findContextAt(topContext->transformToLocalRevision(position));
      }

      QualifiedIdentifier scope = m_declaration->qualifiedIdentifier();

      if(!forceParentScope.isEmpty() && !scope.isEmpty()) {
        if (classFunction && classFunction->isConstructor()) {
          // HACK: for the new class dialog use the parentscope's identifier for the ctor
          //       see also hack further below
          scope = forceParentScope;
          scope.push(forceParentScope.last());
        } else {
          scope = forceParentScope;
          scope.push(m_declaration->identifier());
        }
      }else{
        //Shorten the scope considering the context
        scope = Cpp::stripPrefixes(duContext, scope);
      }

/*      if(scope.count() <= localScope.count() || !scope.toString().startsWith(localScope.toString()))
        return QString();

      scope = scope.mid( localScope.count() );*/

      FunctionType::Ptr asFunction = m_declaration->type<FunctionType>();

      if(asFunction && asFunction->returnType())
          newText += Cpp::simplifiedTypeString(asFunction->returnType(), duContext) + " ";
      newText += scope.toString();
      newText += signaturePart(false);

      if(classFunction && classFunction->isConstructor()) {
        KDevelop::DUContext* funCtx = classFunction->internalFunctionContext();
        if(funCtx) {
          typedef QMultiMap<IndexedType, QString> TypeNamesMap;  // type -> names of arguments with this type
          TypeNamesMap namesForType;
          typedef QMap<QString, IndexedType> NameTypeMap;
          NameTypeMap typeForName;     // argument name -> type
          foreach (const Declaration* arg, funCtx->localDeclarations()) {
            namesForType.insert(arg->indexedType(), arg->identifier().toString());
            typeForName.insert(arg->identifier().toString(), arg->indexedType());
          }
          bool started = false;
          const QVector< KDevelop::DUContext::Import > imports = classFunction->context()->importedParentContexts();
          foreach(const DUContext::Import& import, imports) {
            KDevelop::DUContext* ctx = import.context(topContext);
            if(ctx && ctx->type() == DUContext::Class && ctx->owner()) {
              const int MaxMismatchCount = 20; // hope there won't be more than 20 arguments
              int bestMismatchCount = MaxMismatchCount;
              QString bestBaseCallText;
              bool isBestDefault = false;
              foreach (Declaration* decl, ctx->localDeclarations()) {
                ClassFunctionDeclaration* func = dynamic_cast<ClassFunctionDeclaration*>(decl);
                if (!func || !func->isConstructor()) {
                  continue;
                }
                QString baseCallText;
                int mismatchCount = 0;   // Matched arguments for base constructor
                if(!started)
                  baseCallText += ": ";
                else
                  baseCallText += ", ";
                if (!forceParentScope.isEmpty()) {
                  //HACK: for the new class dialog use the direct declaration's identifier for the ctor call,
                  //      as otherwise we'd try to call a indirect parent's ctor
                  baseCallText += m_declaration->identifier().toString();
                } else {
                  baseCallText += ctx->owner()->identifier().toString();
                }
                baseCallText += '(';
                QVector<Declaration*> parentArgs = func->internalFunctionContext()->localDeclarations();
                for(int a = 0; a < parentArgs.size(); ++a) {
                  if(a)
                    baseCallText += ", ";
                  Declaration* parentArg = parentArgs[a];
                  NameTypeMap::const_iterator byName = typeForName.constFind(parentArg->identifier().toString());
                  if (byName != typeForName.constEnd() && byName.value() == parentArg->indexedType()) {
                    // Both type and name match - good
                    baseCallText += byName.key();
                  } else {
                    TypeNamesMap::const_iterator byType = namesForType.constFind(parentArg->indexedType());
                    if (byType != namesForType.constEnd()) {
                      // Anything with a suitable type will do
                      baseCallText += byType.value();
                    } else {
                      ++mismatchCount;
                    }
                  }
                }
                if (mismatchCount < bestMismatchCount || (mismatchCount == bestMismatchCount && isBestDefault)) {
                  bestMismatchCount = mismatchCount;
                  bestBaseCallText = baseCallText + ')';
                  isBestDefault = (parentArgs.size() == 0);
                  if (mismatchCount == 0 && !isBestDefault) {
                    break;
                  }
                }
              }
              if (bestMismatchCount < MaxMismatchCount && !isBestDefault) {   // There was an actual match
                started = true;
                newText += bestBaseCallText;
              }
            }
          }
        }
      }

      newText += "\n{\n";

      if(asFunction) {

        ClassFunctionDeclaration* overridden = dynamic_cast<ClassFunctionDeclaration*>(DUChainUtils::getOverridden(m_declaration.data()));

        if(!forceParentScope.isEmpty())
          overridden = dynamic_cast<ClassFunctionDeclaration*>(m_declaration.data());

        if(overridden && !overridden->isAbstract() && !overridden->isDestructor() && !overridden->isConstructor()) {
          QualifiedIdentifier baseScope = overridden->qualifiedIdentifier();
          // baseScope == scope is the case for the "default method" implementations in the CreateClass wizard
          const bool callParent = baseScope != scope;
          QString parentCall;
          if (callParent) {
            bool foundShorter = true;
            do {
              foundShorter = false;
              QualifiedIdentifier candidate = baseScope;
              if(candidate.count() > 2) {
                candidate.pop();
                QList<Declaration*> decls = m_declaration->context()->findDeclarations(candidate);
                if(decls.contains(overridden)) {
                  foundShorter = true;
                  baseScope = candidate;
                }
              }
            }while(foundShorter);

            parentCall += baseScope.toString() + '(';
            DUContext* ctx = m_declaration->internalContext();
            if(ctx->type() == DUContext::Function) {
              bool first = true;
              foreach(Declaration* decl, ctx->localDeclarations()) {
                if(!first)
                  parentCall += ", ";
                first = false;
                parentCall += decl->identifier().toString();
              }
            }

            parentCall += ");";
          }

          const bool needsReturn = asFunction->returnType() && asFunction->returnType()->toString() != "void";
          // true when we return something like Foo* and are currently in class Foo
          bool returnThis = false;
          // true when we return something like const Foo& and are currently in class Foo
          bool returnThisDeref = false;
          QualifiedIdentifier parentScope = scope;
          parentScope.pop(); // function identifier
          if (needsReturn) {
            StructureType::Ptr sType;
            bool wasRef = false;
            bool wasPtr = false;
            if (ReferenceType::Ptr refType = asFunction->returnType().cast<ReferenceType>()) {
              wasRef = true;
              sType = refType->baseType().cast<StructureType>();
            } else if (PointerType::Ptr ptrType = asFunction->returnType().cast<PointerType>()) {
              wasPtr = true;
              sType = ptrType->baseType().cast<StructureType>();
            }
            if (sType && sType->qualifiedIdentifier() == parentScope) {
              Q_ASSERT(wasPtr || wasRef);
              if (wasPtr) {
                returnThis = true;
              } else if (wasRef) {
                returnThisDeref = true;
              }
            }
          }

          if (!needsReturn && callParent) {
            newText += parentCall;
          } else if (needsReturn && (returnThisDeref || returnThis)) {
            if (callParent) {
              newText += parentCall;
            }
            newText += "return ";
            if (returnThisDeref) {
              newText += "*this;";
            } else {
              newText += "this;";
            }
          } else if (needsReturn && callParent) {
            newText += "return " + parentCall;
          } else if (needsReturn) {
            newText += "///TODO: return ...;";
          }

        }
      }

      newText += "\n}\n";
  }

  return newText;
}

void ImplementationHelperItem::execute(KTextEditor::Document* document, const KTextEditor::Range& word) {

  if(m_type == CreateSignalSlot) {
    //Step 1: Decide where to put the declaration
    KDevelop::DUChainReadLocker lock(KDevelop::DUChain::lock());

    IndexedString doc;
    {
      QSet<DUContext*> containers = completionContext()->memberAccessContainers();

      if(containers.isEmpty())
        return;
      else
        doc = (*containers.begin())->url();
    }

    lock.unlock();
    //Make sure the top-context is up-to-date, waiting for an update if required
    KDevelop::ReferencedTopDUContext updated( DUChain::self()->waitForUpdate(doc, TopDUContext::AllDeclarationsAndContexts) );

    if(!updated) {
      kDebug() << "not creating slot because failed to update" << doc.str();
      return;
    }
    lock.lock();

    QSet<DUContext*> containers = completionContext()->memberAccessContainers();

    if(containers.isEmpty())
      return;

    DUContext* classContext = *containers.begin();

    Cpp::SourceCodeInsertion insertion(updated.data());
    insertion.setContext(classContext);
    insertion.setAccess(Declaration::Private);

    QString slotName = completionContext()->followingText();
    if(slotName.isEmpty())
      slotName = completionContext()->m_connectedSignalIdentifier.toString();

    QString slotSignature = QString::fromUtf8(completionContext()->m_connectedSignalNormalizedSignature);
    insertion.insertSlot(slotName, slotSignature);

    QString name = completionContext()->followingText();
    if(name.isEmpty() && m_declaration)
      name = m_declaration->identifier().toString();

    lock.unlock();

    if(!insertion.changes().applyAllChanges()) {
      kDebug() << "failed";
      return;
    }

    ICore::self()->languageController()->backgroundParser()->addDocument(doc);
    executeSignalSlotCompletionItem( document, word, false, slotName, slotSignature );
  }else{
    //this code assumes (safely for now) that the "word" range is on one line
    KTextEditor::Range rangeToReplace(word.start().line(), 0, word.end().line(), word.end().column());
    QString rangeToReplaceText = document->text(rangeToReplace);
    QString replacementText = insertionText(document->url(), SimpleCursor(rangeToReplace.end()));
    //Don't replace anything before end of comment, open or closing bracket, or semicolon
    QRegExp replaceAfter = QRegExp("inline|[{}/;]");
    int noReplace = replaceAfter.lastIndexIn(rangeToReplaceText) + replaceAfter.matchedLength() - 1;
    if (noReplace >= 0)
    {
      rangeToReplace = KTextEditor::Range(word.start().line(), noReplace + 1, word.end().line(), word.end().column());
      replacementText.prepend(" ");
    }
    DocumentChangeSet changes;
    changes.addChange(DocumentChange(IndexedString(document->url()), rangeToReplace, document->text(rangeToReplace), replacementText));
    changes.applyAllChanges();
   }
}

bool ImplementationHelperItem::dataChangedWithInput() const {
  return m_type == CreateSignalSlot;
}

}