File: missingdeclarationassistant.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 (403 lines) | stat: -rw-r--r-- 13,037 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
/*
   Copyright 2009 David Nolden <david.nolden.kdevelop@art-master.de>

   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 "missingdeclarationassistant.h"
#include <language/duchain/duchainlock.h>
#include <language/duchain/duchain.h>
#include <klocalizedstring.h>
#include <language/codegen/documentchangeset.h>
#include <language/duchain/types/constantintegraltype.h>
#include "typeutils.h"
#include <interfaces/icore.h>
#include <interfaces/iprojectcontroller.h>
#include "sourcemanipulation.h"
#include <language/duchain/duchainutils.h>
#include <interfaces/idocumentcontroller.h>
#include "cppduchain.h"
#include <interfaces/ilanguagecontroller.h>
#include <language/backgroundparser/backgroundparser.h>
#include <QTextDocument>

using namespace Cpp;
using namespace KDevelop;

class MissingDeclarationAction : public IAssistantAction
{
  Q_OBJECT
public:
  MissingDeclarationAction(const MissingDeclarationProblem::Ptr &problem)
  : m_problem(problem)
  {}
  // returns a full string representing the resulting declaration, without scope or access specifiers.
  virtual QString declarationString() const = 0;

protected:
  /**
   * @return the DUContext in which the declaration will be added.
   *
   * NOTE: The DUChain is locked when this is being called.
   */
  virtual DUContext* targetContext() const = 0;

  QString typeString(const AbstractType::Ptr& type) const
  {
    DUChainReadLocker lock;
    if(!type) {
      return "<no type>";
    } else if(DUContext* container = targetContext()) {
      return shortenedTypeString(type, container, 30);
    } else {
      return QString();
    }
  }

  AbstractType::Ptr type(const AbstractType::Ptr& base) const
  {
    DUChainReadLocker lock;
    AbstractType::Ptr ret = TypeUtils::removeConstants(base, m_problem->topContext());
    if(ret) {
      ret = TypeUtils::realTypeKeepAliases(ret);
      TypeUtils::removeConstModifier(ret);
    }
    return ret;
  }

  AbstractType::Ptr assignedType() const
  {
    return type(m_problem->type->assigned.type.abstractType());
  }

  MissingDeclarationProblem::Ptr m_problem;
};

class CreateLocalDeclarationAction : public MissingDeclarationAction
{
  Q_OBJECT
public:
    CreateLocalDeclarationAction(const MissingDeclarationProblem::Ptr& problem)
    : MissingDeclarationAction(problem)
    {
    }
    virtual void execute()
    {
      DUChainReadLocker lock;
      if(targetContext()) {
        DocumentChangeSet changes;
        SimpleCursor start = m_problem->rangeInCurrentRevision().start;
        changes.addChange(DocumentChange(m_problem->url(), SimpleRange(start, start),
                                         QString(), typeString(assignedType()) + " "));
        lock.unlock();

        changes.setReplacementPolicy(DocumentChangeSet::WarnOnFailedChange);
        changes.applyAllChanges();
        emit executed(this);
      }
    }
    virtual QString description() const
    {
      return i18n("<b>local</b> variable");
    }
    virtual QString toolTip() const
    {
      return i18n("Create local declaration %1", declarationString());
    }
    virtual QString declarationString() const
    {
      return typeString(assignedType()) + " "
              + m_problem->type->identifier().toString();
    }
    virtual DUContext* targetContext() const
    {
      return m_problem->type->searchStartContext.data();
    }
};

class CreateMemberDeclarationAction : public MissingDeclarationAction
{
  Q_OBJECT
public:
  CreateMemberDeclarationAction(const MissingDeclarationProblem::Ptr& problem,
                                Declaration::AccessPolicy access = Declaration::Public)
  : MissingDeclarationAction(problem)
  , m_access(access)
  {
  }
  virtual void execute()
  {
    DUChainReadLocker lock;
    DUContext* searchFrom = m_problem->type->searchStartContext.data();
    DUContext* container = targetContext();

    if(searchFrom && container) {
      Cpp::SourceCodeInsertion ins(container->topContext());
      ins.setContext(container);
      ins.setAccess(m_access);

      if(m_problem->type->isFunction) {
        QList<Cpp::SourceCodeInsertion::SignatureItem> signature;
        int num = 1;
        QSet<QString> hadNames;
        foreach(const OverloadResolver::Parameter& arg, m_problem->type->arguments) {
          Cpp::SourceCodeInsertion::SignatureItem item;
          item.type = type(arg.type);
          item.name = QString("arg%1").arg(num);
          kDebug() << "have declaration: " << arg.declaration.data();

          if(arg.declaration.data())
          {
            // Find a unique name
            QString baseName = arg.declaration.data()->identifier().identifier().str();
            for(int a = 1; a < 1000; ++a)
            {
              if(!hadNames.contains(baseName))
              {
                item.name = baseName;
                break;
              }
              QString name = QString(baseName + "%1").arg(a);
              if(!hadNames.contains(name))
              {
                item.name = name;
                break;
              }
            }
          }

          signature << item;
          ++num;
        }
        ins.insertFunctionDeclaration(m_problem->type->identifier().identifier().identifier().last(), returnType(), signature);
      } else {
        ins.insertVariableDeclaration(m_problem->type->identifier().identifier().identifier().last(), returnType());
      }
      lock.unlock();

      ins.changes().setReplacementPolicy(DocumentChangeSet::WarnOnFailedChange);
      ins.changes().applyAllChanges();
      const IndexedString localUrl = searchFrom->url();
      const IndexedString changeUrl = container->url();
      if(changeUrl != localUrl) {
        ICore::self()->languageController()->backgroundParser()->addDocument(changeUrl);
        ICore::self()->languageController()->backgroundParser()->addDocument(localUrl);
      }
      emit executed(this);
    }
  }
  virtual QString description() const
  {
    return QString("<b>%1</b>").arg(accessString());
  }

  virtual QString containerString() const
  {
    DUChainReadLocker lock;
    DUContext* container = targetContext();
    if(container)
      return container->scopeIdentifier(false).toString();
    else
      return QString();
  }

  virtual QString declarationString() const
  {
    DUChainReadLocker lock;
    if(targetContext())
      return returnString() + " " + m_problem->type->identifier().toString() + signatureString();
    else
      return QString();
  }

  virtual QString toolTip() const
  {
    return i18nc("%1: access, %2: identifier/signature", "Declare %1 %2",
                  accessString(), declarationString());
  }
private:
  virtual DUContext* targetContext() const
  {
    DUContext* container = m_problem->type->containerContext.data();
    if(!container) {
      Declaration* classDecl = localClassFromCodeContext(m_problem->type->searchStartContext.data());
      if(classDecl)
        container = classDecl->internalContext();
    }
    return container;
  }

  QString accessString() const
  {
    switch(m_access) {
      case Declaration::Protected:
        return "protected";
      case Declaration::Private:
        return "private";
      case Declaration::Public:
        return "public";
      default:
        return QString();
    }
  }

  AbstractType::Ptr returnType() const
  {
    AbstractType::Ptr r = type(m_problem->type->convertedTo.type.abstractType());
    if(r)
      return r;

    r = assignedType();
    if(r) {
      if(m_problem->type->isFunction)
      {
        //A function that something is assigned to must return a reference
        ReferenceType::Ptr ref(new ReferenceType);
        ref->setBaseType(r);
        r = ref.cast<AbstractType>();
      }
      return r;
    }

    IntegralType* i = new IntegralType;
    i->setDataType(IntegralType::TypeVoid);
    return AbstractType::Ptr(i);
  }

  QString returnString() const
  {
    if (AbstractType::Ptr ret = returnType()) {
      return typeString(ret);
    } else {
      return QString();
    }
  }

  QString signatureString() const
  {
    if(!m_problem->type->isFunction) {
      return QString();
    }

    QString ret = "(";
    bool first = true;
    foreach(const OverloadResolver::Parameter& arg, m_problem->type->arguments) {
      if(!first)
        ret += ", ";
      else
        first = false;
      ret += typeString(arg.type);
    }
    ret += ")";
    return ret;
  }

  Declaration::AccessPolicy m_access;
};

MissingDeclarationAssistant::MissingDeclarationAssistant(const MissingDeclarationProblem::Ptr& p)
: problem(p)
, type(p->type)
{
  bool actionAdded = false;
  DUChainReadLocker lock;
  if(p->type->identifier().identifier().identifier().isEmpty())
    return;
  kDebug() << "creating assistant for" << type->toString() << "assigned:" << type->assigned.toString();

  DUContext* searchFrom = type->searchStartContext.data();
  if (!searchFrom) {
    return;
  }

  if(canCreateLocal(searchFrom)) {
    //Action to just copy in the type, i.e. create local declaration
    addAction(IAssistantAction::Ptr(new CreateLocalDeclarationAction(problem)));
  }

  Declaration* localClass = localClassFromCodeContext(searchFrom);
  Declaration* targetClass = 0;
  if (problem->type->containerContext.isValid()) {
    targetClass = localClassFromCodeContext(problem->type->containerContext.data());
  } else {
    targetClass = localClass;
  }

  if (canAddTo(targetClass, localClass)
      && (type->convertedTo.isValid() || type->assigned.isValid() || type->isFunction))
  {
    // public is always possible
    CreateMemberDeclarationAction* publicAction = new CreateMemberDeclarationAction(problem, Declaration::Public);

    if (actionAdded) {
      // place label between first action and the following actions
      const QString label = i18nc("assistant, declare member in class identified by %1",
                                  "member of <code>%1</code>:",
                                  Qt::escape(publicAction->containerString()));
      addAction(IAssistantAction::Ptr(new AssistantLabelAction(label)));
    } else {
      // set the title manually
      m_title = i18nc("assistant, declare %1 as member of class identified by %2",
                      "Declare <code>'%1'</code> as member of <code>%2</code>",
                      publicAction->declarationString(),
                      Qt::escape(publicAction->containerString()));
    }

    if(localClass == targetClass) {
      //Actions to create a declaration within the local class
      addAction(IAssistantAction::Ptr(new CreateMemberDeclarationAction(problem, Declaration::Private)));
      addAction(IAssistantAction::Ptr(new CreateMemberDeclarationAction(problem, Declaration::Protected)));
    } else if (localClass && targetClass
               && TypeUtils::isPublicBaseClass(localClass->type<CppClassType>(),
                                               targetClass->type<CppClassType>(),
                                               problem->topContext()))
    {
      //if we are in a subclass, we can provide the protected option
        addAction(IAssistantAction::Ptr(new CreateMemberDeclarationAction(problem, Declaration::Protected)));
    }
    // public is always possible
    addAction(IAssistantAction::Ptr(publicAction));
  }

  if(!actions().isEmpty() && m_title.isEmpty()) {
    MissingDeclarationAction* action = dynamic_cast<MissingDeclarationAction*>(actions().last().data());
    Q_ASSERT(action);
    m_title = i18n("Declare <code>'%1'</code> as", action->declarationString());
  }
}

bool MissingDeclarationAssistant::canCreateLocal(DUContext* searchFrom) const
{
  return !type->containerContext.data() && searchFrom->type() == DUContext::Other
    && type->assigned.type.isValid() && !type->assigned.type.type<DelayedType>()
    && !type->convertedTo.isValid();
}

bool MissingDeclarationAssistant::canAddTo(Declaration* toClass, Declaration* fromClass) const
{
  if (!toClass) {
    return false;
  }
  // same file, should be possible
  if (fromClass && fromClass->url() == toClass->url()) {
    return true;
  }
  // otherwise only if we currently edit the file, or if it's in an opened project
  const KUrl url = toClass->url().toUrl();
  return ICore::self()->projectController()->findProjectForUrl(url)
        || ICore::self()->documentController()->documentForUrl(url);
}

#include "missingdeclarationassistant.moc"